{"function": "public boolean replaceStorageContainer(long groupId, StorageContainerInfo groupInfo) {\n synchronized (storageContainers) {\n StorageContainerInfo oldGroupInfo = storageContainers.get(groupId);\n if (null == oldGroupInfo || oldGroupInfo.getRevision() < groupInfo.getRevision()) {\n log.info(\"Updated the storage container info for group {} : {}\", groupId, groupInfo);\n storageContainers.put(groupId, groupInfo);\n return true;\n }\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setProperties(TwitterConfiguration properties) {\n this.properties = properties;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean exists() {\n return delegate.exists();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ManagedAttribute\npublic void setNumberOfPages(Integer numberOfPages) {\n getProperties().setNumberOfPages(numberOfPages);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testIdempotent() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedMessageCount(1);\n String messageId = UUID.randomUUID().toString();\n for (int i = 0; i < 5; i++) {\n template.sendBodyAndHeader(\"direct:start\", UUID.randomUUID().toString(), \"MessageId\", messageId);\n }\n mock.assertIsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected ShortArrayAssert invoke_api_method() {\n return assertions.containsSequence((short) 6, (short) 8);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Integer getValue(Exchange exchange) {\n String s = exchange.getIn().getBody(String.class);\n return Integer.valueOf(s);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testReadme() {\n final String sql = \"SELECT d.name, COUNT(*) cnt\" + \" FROM emps AS e\" + \" JOIN depts AS d ON e.deptno = d.deptno\" + \" GROUP BY d.name\";\n sql(\"smart\", sql).returns(\"NAME=Sales; CNT=1\", \"NAME=Marketing; CNT=2\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void scheduleRefresh() {\n refreshWanted.set(true);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid withDelimiter() {\n val delimiter = TextUtils.delimiter(\".\");\n assertEquals(\"\", delimiter.withDelimiter(\"/\").asDelimitedString());\n assertEquals(\"a/b\", delimiter.parse(\"a.b\").withDelimiter(\"/\").asDelimitedString());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void verifyAssertionInvocation(Date date) {\n verify(dates).assertIsEqualWithPrecision(getInfo(assertions), getActual(assertions), date, TimeUnit.MINUTES);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected MessageListenerContainer createListenerContainer() throws Exception {\n TemporaryQueueMessageListenerContainer answer = new TemporaryQueueMessageListenerContainer(endpoint);\n answer.setMessageListener(this);\n String clientId = endpoint.getClientId();\n if (clientId != null) {\n clientId += \".CamelReplyManager\";\n answer.setClientId(clientId);\n }\n answer.setConcurrentConsumers(endpoint.getReplyToConcurrentConsumers());\n answer.setExceptionListener(new TemporaryReplyQueueExceptionListener(destResolver));\n answer.setDestinationCreationStrategy(destResolver);\n answer.setDestinationName(\"temporary\");\n return answer;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldAllowUnicodeOwners() {\n OwnerDTO createdOwner = owners.createOwner(Owners.random().key(StringUtil.random(\"\u0391\u03ba\u03bc\u03ae \u043a\u043e\u0440\u043f\u043e\u0440\u0430\u0446\u0438\u044f\")));\n assertThat(createdOwner).isNotNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "static NamedQuery named(@NonNull final Class resultType, @NonNull final String queryName) {\n return new _NamedQueryDefault<>(resultType, queryName, QueryRange.unconstrained(), null);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * If the complete() method was called or not.\n *\n * @return true means the complete() method was called, false otherwise.\n */\nboolean isCompleted();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Class getOptionType(String name, boolean ignoreCase) {\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"backofferrorthreshold\":\n case \"backoffErrorThreshold\":\n return int.class;\n case \"backoffidlethreshold\":\n case \"backoffIdleThreshold\":\n return int.class;\n case \"backoffmultiplier\":\n case \"backoffMultiplier\":\n return int.class;\n case \"bridgeerrorhandler\":\n case \"bridgeErrorHandler\":\n return boolean.class;\n case \"delay\":\n return long.class;\n case \"exceptionhandler\":\n case \"exceptionHandler\":\n return org.apache.camel.spi.ExceptionHandler.class;\n case \"exchangepattern\":\n case \"exchangePattern\":\n return org.apache.camel.ExchangePattern.class;\n case \"greedy\":\n return boolean.class;\n case \"inbody\":\n case \"inBody\":\n return java.lang.String.class;\n case \"initialdelay\":\n case \"initialDelay\":\n return long.class;\n case \"lazystartproducer\":\n case \"lazyStartProducer\":\n return boolean.class;\n case \"oauthtoken\":\n case \"oauthToken\":\n return java.lang.String.class;\n case \"password\":\n return java.lang.String.class;\n case \"pollstrategy\":\n case \"pollStrategy\":\n return org.apache.camel.spi.PollingConsumerPollStrategy.class;\n case \"repeatcount\":\n case \"repeatCount\":\n return long.class;\n case \"runlogginglevel\":\n case \"runLoggingLevel\":\n return org.apache.camel.LoggingLevel.class;\n case \"scheduledexecutorservice\":\n case \"scheduledExecutorService\":\n return java.util.concurrent.ScheduledExecutorService.class;\n case \"scheduler\":\n return java.lang.Object.class;\n case \"schedulerproperties\":\n case \"schedulerProperties\":\n return java.util.Map.class;\n case \"sendemptymessagewhenidle\":\n case \"sendEmptyMessageWhenIdle\":\n return boolean.class;\n case \"serverurl\":\n case \"serverUrl\":\n return java.lang.String.class;\n case \"startscheduler\":\n case \"startScheduler\":\n return boolean.class;\n case \"timeunit\":\n case \"timeUnit\":\n return java.util.concurrent.TimeUnit.class;\n case \"token\":\n return java.lang.String.class;\n case \"usefixeddelay\":\n case \"useFixedDelay\":\n return boolean.class;\n case \"username\":\n return java.lang.String.class;\n default:\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@Pointcut\npublic void scope() {\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * add one or multiple key-value pairs to the message.\n *\n * @param keyValuePairs key-value pairs like 'a=1&b=2&...'\n */\nvoid addData(String keyValuePairs);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getStringAttribute() {\n return stringAttribute;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Index where the parsing error occurred\n *\n * @return index of the parsing error in the input\n */\npublic int getIndex() {\n return index;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected LogRecord waitForNextRecord(LogReader reader) throws Exception {\n LogRecord record = reader.readNext(false);\n while (null == record) {\n record = reader.readNext(false);\n }\n return record;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns a model with start index into the set table and maximal number of items to return.\n */\nQueryRange getRange();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getPathSid() {\n return pathSid;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid catchIndexOutOfBoundsException_should_succeed_and_return_actual_instance_with_correct_class() {\n // GIVEN\n final IndexOutOfBoundsException expected = new IndexOutOfBoundsException(\"boom!!\");\n // WHEN\n IndexOutOfBoundsException actual = catchIndexOutOfBoundsException(codeThrowing(expected));\n // THEN\n then(actual).isSameAs(expected);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.StepFailed;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testAggregateProcessorTimeoutRestart() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedBodiesReceived(\"A+B\");\n mock.expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, \"timeout\");\n AsyncProcessor done = new SendProcessor(context.getEndpoint(\"mock:result\"));\n Expression corr = header(\"id\");\n AggregationStrategy as = new BodyInAggregatingStrategy();\n AggregateProcessor ap = new AggregateProcessor(context, done, corr, as, executorService, true);\n // start with a high timeout so no completes before we stop\n ap.setCompletionTimeout(250);\n ap.setCompletionTimeoutCheckerInterval(10);\n ap.start();\n Exchange e1 = new DefaultExchange(context);\n e1.getIn().setBody(\"A\");\n e1.getIn().setHeader(\"id\", 123);\n Exchange e2 = new DefaultExchange(context);\n e2.getIn().setBody(\"B\");\n e2.getIn().setHeader(\"id\", 123);\n ap.process(e1);\n ap.process(e2);\n // shutdown before the 1/4 sec timeout occurs\n // however we use stop instead of shutdown as shutdown will clear the in\n // memory aggregation repository,\n ap.stop();\n // should be no completed\n assertEquals(0, mock.getReceivedCounter());\n // start aggregator again\n ap.start();\n // the aggregator should restore the timeout condition and trigger\n // timeout\n assertMockEndpointsSatisfied();\n assertEquals(1, mock.getReceivedCounter());\n ap.shutdown();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n // required for the sql component\n getContext().getComponent(\"sql-stored\", SqlStoredComponent.class).setDataSource(db);\n from(\"direct:query\").to(\"sql-stored:SUBNUMBERS_FUNCTION(OUT INTEGER resultofsub, INTEGER ${header.num1},INTEGER ${header.num2})?function=true\").to(\"mock:query\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static TaskExecutionFailedEventAck success(int taskInstanceId) {\n return new TaskExecutionFailedEventAck(taskInstanceId, true);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic int orderOfAppearanceInUiDropdown() {\n return 1700;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public WeatherConfiguration getConfiguration() {\n return configuration;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1673]\n * Query with ORDER BY or GROUP BY on TIMESTAMP column throws\n * CompileException.\n */\n@Test\nvoid testTimestampGroupBy() throws SQLException {\n Properties info = new Properties();\n info.put(\"model\", FileAdapterTests.jsonPath(\"bug\"));\n // Use LIMIT to ensure that results are deterministic without ORDER BY\n final String sql = \"select \\\"EMPNO\\\", \\\"JOINTIMES\\\"\\n\" + \"from (select * from \\\"DATE\\\" limit 1)\\n\" + \"group by \\\"EMPNO\\\",\\\"JOINTIMES\\\"\";\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", info);\n Statement statement = connection.createStatement();\n ResultSet resultSet = statement.executeQuery(sql)) {\n assertThat(resultSet.next(), is(true));\n final Timestamp timestamp = resultSet.getTimestamp(2);\n assertThat(timestamp, isA(Timestamp.class));\n // Note: This logic is time zone specific, but the same time zone is\n // used in the CSV adapter and this test, so they should cancel out.\n assertThat(timestamp, is(Timestamp.valueOf(\"1996-08-03 00:01:02.0\")));\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Whether the route template has a parameter with the given name\n *\n * @param name the parameter name\n * @return true if exists\n */\nboolean hasParameter(String name);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nvoid initiate() {\n this.requestTimeNanos = MathUtils.nowInNano();\n List ensemble = getLedgerMetadata().getEnsembleAt(startEntryId);\n request = new SequenceReadRequest(ensemble, lh.ledgerId, startEntryId, maxCount, maxSize);\n request.read();\n if (clientCtx.getConf().readSpeculativeRequestPolicy.isPresent()) {\n speculativeTask = clientCtx.getConf().readSpeculativeRequestPolicy.get().initiateSpeculativeRequest(clientCtx.getScheduler(), request);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return An immutable {@link JsonMarshallerContext} object.\n */\npublic JsonMarshallerContext build() {\n return new JsonMarshallerContext(this);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get the storage container id.\n *\n * @return the storage container id.\n */\nlong getId();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic LedgerManager newLedgerManager() {\n return new LongHierarchicalLedgerManager(conf, zk);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * add one key-value pair to the message.\n *\n * @param key\n * @param value\n */\nvoid addData(String key, Object value);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SchedulerEndpoint getEndpoint() {\n return (SchedulerEndpoint) super.getEndpoint();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nvoid read() {\n sendNextRead();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getFirstName() {\n return firstName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean isBulkV2Operation(OperationName operationName) {\n switch(operationName) {\n case BULK2_CREATE_JOB:\n case BULK2_CREATE_BATCH:\n case BULK2_CLOSE_JOB:\n case BULK2_GET_JOB:\n case BULK2_ABORT_JOB:\n case BULK2_DELETE_JOB:\n case BULK2_GET_SUCCESSFUL_RESULTS:\n case BULK2_GET_FAILED_RESULTS:\n case BULK2_GET_UNPROCESSED_RECORDS:\n case BULK2_GET_ALL_JOBS:\n case BULK2_CREATE_QUERY_JOB:\n case BULK2_GET_QUERY_JOB:\n case BULK2_GET_QUERY_JOB_RESULTS:\n case BULK2_ABORT_QUERY_JOB:\n case BULK2_DELETE_QUERY_JOB:\n case BULK2_GET_ALL_QUERY_JOBS:\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid getChildNodeValue_should_read_primitive_fields() {\n // GIVEN\n Fields node = new Fields();\n // WHEN / THEN\n then(COMPARING_FIELDS.getChildNodeValue(\"privateBoolean\", node)).isEqualTo(true);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateByte\", node)).isEqualTo((byte) 1);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateShort\", node)).isEqualTo((short) 2);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateInt\", node)).isEqualTo(3);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateLong\", node)).isEqualTo((long) 4);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateFloat\", node)).isEqualTo(1.1f);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateDouble\", node)).isEqualTo(2.2);\n then(COMPARING_FIELDS.getChildNodeValue(\"privateChar\", node)).isEqualTo('x');\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates a S3EventNotificationReader\n * @return\n */\nstatic S3EventNotificationReader create() {\n return new DefaultS3EventNotificationReader();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n routeTemplate(\"myTemplate\").templateParameter(\"myCount\").templateParameter(\"myFac\").from(\"direct:start\").onException(Exception.class).maximumRedeliveryDelay(1).maximumRedeliveries(\"{{myCount}}\").collisionAvoidanceFactor(\"{{myFac}}\").onRedelivery(e -> {\n e.getMessage().setBody(e.getMessage().getHeader(Exchange.REDELIVERY_COUNTER));\n }).handled(true).end().throwException(new IllegalArgumentException(\"Forced\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic int hashCode() {\n return new HashCodeBuilder(449, 3).append(productId).append(productName).toHashCode();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onException(JMSException exception) {\n // capture exceptions, and schedule a refresh of the ReplyTo destination\n log.warn(\"Exception inside the DMLC for Temporary ReplyTo Queue for destination {}, refreshing ReplyTo destination\", endpoint.getDestinationName(), exception);\n destResolver.scheduleRefresh();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Boolean isEmailHidden() {\n // pour cacher ou non l'email pour les lecteurs\n return \"yes\".equalsIgnoreCase(getComponentParameterValue(\"isEmailHidden\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic ConsumerDTO translate(Consumer source) {\n return this.translate(null, source);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void run(StorageAdminClient admin, BKFlags globalFlags, Flags cmdFlags) throws Exception {\n checkArgument(!cmdFlags.arguments.isEmpty(), \"Namespace name is not provided\");\n String namespaceName = cmdFlags.arguments.get(0);\n try {\n NamespaceProperties ns = result(admin.getNamespace(namespaceName));\n spec.console().println(\"Namespace '\" + namespaceName + \"' :\");\n spec.console().println(ns);\n } catch (NamespaceNotFoundException nfe) {\n spec.console().println(\"Namespace '\" + namespaceName + \"' does not exist\");\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The folder contains both JSON files and CSV files joins.\n */\n@Test\nvoid testJsonWithCsvJoin() {\n final String sql = \"select emps.empno,\\n\" + \" NAME,\\n\" + \" \\\"DATE\\\".JOINEDAT\\n\" + \" from \\\"DATE\\\"\\n\" + \"join emps on emps.empno = \\\"DATE\\\".EMPNO\\n\" + \"order by empno, name, joinedat limit 3\";\n final String[] lines = { \"EMPNO=100; NAME=Fred; JOINEDAT=1996-08-03\", \"EMPNO=110; NAME=Eric; JOINEDAT=2001-01-01\", \"EMPNO=110; NAME=Eric; JOINEDAT=2002-05-03\" };\n sql(\"sales-json\", sql).returns(lines).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void mdnMessageTest() throws Exception {\n AS2ClientManager clientManager = createDefaultClientManager();\n HttpCoreContext httpContext = clientManager.send(EDI_MESSAGE, REQUEST_URI, SUBJECT, FROM, AS2_NAME, AS2_NAME, AS2MessageStructure.PLAIN, ContentType.create(AS2MediaType.APPLICATION_EDIFACT, StandardCharsets.US_ASCII), null, null, null, null, null, DISPOSITION_NOTIFICATION_TO, SIGNED_RECEIPT_MIC_ALGORITHMS, null, null, \"file.txt\", null);\n HttpResponse response = httpContext.getResponse();\n assertEquals(HttpVersion.HTTP_1_1, response.getVersion(), \"Unexpected method value\");\n assertEquals(HttpStatus.SC_OK, response.getCode(), \"Unexpected method value\");\n assertEquals(EnglishReasonPhraseCatalog.INSTANCE.getReason(200, null), response.getReasonPhrase(), \"Unexpected method value\");\n assertTrue(response instanceof ClassicHttpResponse);\n HttpEntity responseEntity = ((ClassicHttpResponse) response).getEntity();\n assertNotNull(responseEntity, \"Response entity\");\n assertTrue(responseEntity instanceof MultipartSignedEntity, \"Unexpected response entity type\");\n MultipartSignedEntity responseSignedEntity = (MultipartSignedEntity) responseEntity;\n MimeEntity responseSignedDataEntity = responseSignedEntity.getSignedDataEntity();\n assertTrue(responseSignedDataEntity instanceof DispositionNotificationMultipartReportEntity, \"Signed entity wrong type\");\n DispositionNotificationMultipartReportEntity reportEntity = (DispositionNotificationMultipartReportEntity) responseSignedDataEntity;\n assertEquals(2, reportEntity.getPartCount(), \"Unexpected number of body parts in report\");\n MimeEntity firstPart = reportEntity.getPart(0);\n assertEquals(ContentType.create(AS2MimeType.TEXT_PLAIN, StandardCharsets.US_ASCII).toString(), firstPart.getContentType(), \"Unexpected content type in first body part of report\");\n MimeEntity secondPart = reportEntity.getPart(1);\n assertEquals(ContentType.create(AS2MimeType.MESSAGE_DISPOSITION_NOTIFICATION).toString(), secondPart.getContentType(), \"Unexpected content type in second body part of report\");\n ApplicationPkcs7SignatureEntity signatureEntity = responseSignedEntity.getSignatureEntity();\n assertNotNull(signatureEntity, \"Signature Entity\");\n // Validate Signature\n assertTrue(SigningUtils.isValid(responseSignedEntity, new Certificate[] { signingCert }), \"Signature is invalid\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Object getSource() {\n return getService();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isRemote() {\n return false;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "// -- WITHERS\nQuery withRange(@NonNull QueryRange range);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void plainEDIMessageRequestTest() throws Exception {\n AS2ClientManager clientManager = createDefaultClientManager();\n HttpCoreContext httpContext = clientManager.send(EDI_MESSAGE, REQUEST_URI, SUBJECT, FROM, AS2_NAME, AS2_NAME, AS2MessageStructure.PLAIN, ContentType.create(AS2MediaType.APPLICATION_EDIFACT, StandardCharsets.US_ASCII), null, null, null, null, null, DISPOSITION_NOTIFICATION_TO, SIGNED_RECEIPT_MIC_ALGORITHMS, null, null, \"file.txt\", null);\n HttpRequest request = httpContext.getRequest();\n assertEquals(METHOD, request.getMethod(), \"Unexpected method value\");\n assertEquals(REQUEST_URI, request.getUri().getPath(), \"Unexpected request URI value\");\n assertEquals(HttpVersion.HTTP_1_1, request.getVersion(), \"Unexpected HTTP version value\");\n assertEquals(SUBJECT, request.getFirstHeader(AS2Header.SUBJECT).getValue(), \"Unexpected subject value\");\n assertEquals(FROM, request.getFirstHeader(AS2Header.FROM).getValue(), \"Unexpected from value\");\n assertEquals(AS2_VERSION, request.getFirstHeader(AS2Header.AS2_VERSION).getValue(), \"Unexpected AS2 version value\");\n assertEquals(AS2_NAME, request.getFirstHeader(AS2Header.AS2_FROM).getValue(), \"Unexpected AS2 from value\");\n assertEquals(AS2_NAME, request.getFirstHeader(AS2Header.AS2_TO).getValue(), \"Unexpected AS2 to value\");\n assertTrue(request.getFirstHeader(AS2Header.MESSAGE_ID).getValue().endsWith(CLIENT_FQDN + \">\"), \"Unexpected message id value\");\n assertEquals(TARGET_HOST + \":\" + TARGET_PORT, request.getFirstHeader(AS2Header.TARGET_HOST).getValue(), \"Unexpected target host value\");\n assertEquals(USER_AGENT, request.getFirstHeader(AS2Header.USER_AGENT).getValue(), \"Unexpected user agent value\");\n assertNotNull(request.getFirstHeader(AS2Header.DATE), \"Date value missing\");\n assertNotNull(request.getFirstHeader(AS2Header.CONTENT_LENGTH), \"Content length value missing\");\n assertTrue(request.getFirstHeader(AS2Header.CONTENT_TYPE).getValue().startsWith(AS2MediaType.APPLICATION_EDIFACT), \"Unexpected content type for message\");\n assertTrue(request instanceof ClassicHttpRequest, \"Request does not contain entity\");\n HttpEntity entity = ((ClassicHttpRequest) request).getEntity();\n assertNotNull(entity, \"Request does not contain entity\");\n assertTrue(entity instanceof ApplicationEDIFACTEntity, \"Unexpected request entity type\");\n ApplicationEDIFACTEntity ediEntity = (ApplicationEDIFACTEntity) entity;\n assertTrue(ediEntity.getContentType().startsWith(AS2MediaType.APPLICATION_EDIFACT), \"Unexpected content type for entity\");\n assertTrue(ediEntity.isMainBody(), \"Entity not set as main body of request\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextSuspended;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void unparseCube(SqlWriter writer, SqlCall call) {\n writer.keyword(call.getOperator().getName());\n final SqlWriter.Frame frame = writer.startList(SqlWriter.FrameTypeEnum.FUN_CALL, \"(\", \")\");\n for (SqlNode operand : call.getOperandList()) {\n writer.sep(\",\");\n if (operand.getKind() == SqlKind.ROW) {\n final SqlWriter.Frame frame2 = writer.startList(SqlWriter.FrameTypeEnum.SIMPLE, \"(\", \")\");\n for (SqlNode operand2 : ((SqlCall) operand).getOperandList()) {\n writer.sep(\",\");\n operand2.unparse(writer, 0, 0);\n }\n writer.endList(frame2);\n } else if (operand instanceof SqlNodeList && ((SqlNodeList) operand).size() == 0) {\n writer.keyword(\"()\");\n } else {\n operand.unparse(writer, 0, 0);\n }\n }\n writer.endList(frame);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ManagedAttribute\npublic Integer getCount() {\n return getProperties().getCount();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected WorkflowResult doCreate(final GroupCR groupCR, final String creator, final String context) {\n Group group = entityFactory.newEntity(Group.class);\n dataBinder.create(group, groupCR);\n metadata(group, creator, context);\n group = groupDAO.saveAndRefreshDynMemberships(group);\n publisher.publishEvent(new AnyLifecycleEvent<>(this, SyncDeltaType.CREATE, group, AuthContextUtils.getDomain()));\n PropagationByResource propByRes = new PropagationByResource<>();\n propByRes.set(ResourceOperation.CREATE, groupDAO.findAllResourceKeys(group.getKey()));\n return new WorkflowResult<>(group.getKey(), propByRes, \"create\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setStatus(final String status) {\n this.status = status;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextSuspending;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Producer createProducer() throws Exception {\n return new WeatherProducer(this, getWeatherQuery().getQuery());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void endLog(Transaction transaction, Object retVal, Object... params) {\n Header addr = ((HttpResponse) retVal).getFirstHeader(getServerAddrDataKey());\n Header domain = ((HttpResponse) retVal).getFirstHeader(getServerDomainDataKey());\n if (isNotNull(addr)) {\n logServerAddr(addr.getValue());\n }\n if (isNotNull(domain)) {\n logServerDomain(domain.getValue());\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Set propertyNames() {\n return PROPERTY_NAMES;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void filter(ContainerRequestContext requestContext) {\n Map> queryParams = requestContext.getUriInfo().getQueryParameters();\n boolean containsExcludes = queryParams.containsKey(\"exclude\");\n boolean containsIncludes = queryParams.containsKey(\"include\");\n DynamicFilterData filterData = new DynamicFilterData();\n if (queryParams.containsKey(\"filtermode\")) {\n List values = queryParams.get(\"filtermode\");\n filterData.setAllowlistMode(\"whitelist\".equalsIgnoreCase(values.get(0)) || \"allowlist\".equalsIgnoreCase(values.get(0)));\n } else {\n // We want the list to be a blocklist by default when neither include nor exclude is\n // provided, so we don't accidentally filter anything\n filterData.setAllowlistMode(containsIncludes && !containsExcludes);\n }\n if (containsIncludes) {\n for (String path : queryParams.get(\"include\")) {\n filterData.includeAttribute(path);\n }\n }\n if (containsExcludes) {\n for (String path : queryParams.get(\"exclude\")) {\n filterData.excludeAttribute(path);\n }\n }\n if (containsIncludes || containsExcludes) {\n ResteasyContext.pushContext(DynamicFilterData.class, filterData);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getDate() {\n return date;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void bodyWithGSM8bitDataCodingNotModified() throws Exception {\n final int dataCoding = 0xF7;\n /* GSM 8-bit class 3 */\n byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };\n Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);\n exchange.getIn().setHeader(SmppConstants.COMMAND, \"ReplaceSm\");\n exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding);\n exchange.getIn().setBody(body);\n command.execute(exchange);\n verify(session).replaceShortMessage((String) isNull(), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq(\"1616\"), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq((byte) 0), eq(body));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Class getOptionType(String name, boolean ignoreCase) {\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"action\":\n return java.lang.String.class;\n case \"decrement\":\n return java.lang.String.class;\n case \"increment\":\n return java.lang.String.class;\n case \"lazystartproducer\":\n case \"lazyStartProducer\":\n return boolean.class;\n case \"metricsdescription\":\n case \"metricsDescription\":\n return java.lang.String.class;\n case \"value\":\n return java.lang.String.class;\n default:\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_delegate_to_Arrays2D() {\n // WHEN\n short2DArrays.assertHasDimensions(info, actual, 2, 3);\n // THEN\n verify(arrays2d).assertHasDimensions(info, failures, actual, 2, 3);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextReloadFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldCreateScaOwner() {\n OwnerDTO ownerDTO = Owners.randomSca();\n OwnerDTO status = owners.createOwner(ownerDTO);\n assertThat(status.getId()).isNotNull();\n assertThat(status.getCreated()).isNotNull();\n assertThat(status.getUpdated()).isNotNull();\n assertThat(status.getContentAccessMode()).isEqualTo(ownerDTO.getContentAccessMode());\n assertThat(status.getContentAccessModeList()).isEqualTo(ownerDTO.getContentAccessModeList());\n assertThat(status.getKey()).isEqualTo(ownerDTO.getKey());\n assertThat(status.getDisplayName()).isEqualTo(ownerDTO.getDisplayName());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ParameterizedTest\n@MethodSource(\"explainFormats\")\nvoid testPushDownProjectAggregate(String format) {\n String expected = null;\n String extra = null;\n switch(format) {\n case \"dot\":\n expected = \"PLAN=digraph {\\n\" + \"\\\"CsvTableScan\\\\ntable = [SALES, EMPS\\\\n]\\\\nfields = [3]\\\\n\\\" -> \" + \"\\\"EnumerableAggregate\\\\ngroup = {0}\\\\nEXPR$1 = COUNT()\\\\n\\\" [label=\\\"0\\\"]\\n\" + \"}\\n\";\n extra = \" as dot \";\n break;\n case \"text\":\n expected = \"PLAN=\" + \"EnumerableAggregate(group=[{0}], EXPR$1=[COUNT()])\\n\" + \" CsvTableScan(table=[[SALES, EMPS]], fields=[[3]])\\n\";\n extra = \"\";\n break;\n }\n final String sql = \"explain plan \" + extra + \" for\\n\" + \"select gender, count(*) from EMPS group by gender\";\n sql(\"smart\", sql).returns(expected).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@BeforeAll\npublic static void setUpOnce() throws Exception {\n setupKeysAndCertificates();\n testServer = new AS2ServerConnection(AS2_VERSION, \"MyServer-HTTP/1.1\", SERVER_FQDN, TARGET_PORT, AS2SignatureAlgorithm.SHA256WITHRSA, certList.toArray(new Certificate[0]), signingKP.getPrivate(), null, MDN_MESSAGE_TEMPLATE, null, null);\n testServer.listen(\"*\", new HttpRequestHandler() {\n\n @Override\n public void handle(ClassicHttpRequest request, ClassicHttpResponse response, HttpContext context) throws HttpException, IOException {\n try {\n org.apache.camel.component.as2.api.entity.EntityParser.parseAS2MessageEntity(request);\n context.setAttribute(AS2ServerManager.SUBJECT, SUBJECT);\n context.setAttribute(AS2ServerManager.FROM, AS2_NAME);\n ediEntity = HttpMessageUtils.extractEdiPayload(request, new HttpMessageUtils.DecrpytingAndSigningInfo(testServer.getValidateSigningCertificateChain(), testServer.getDecryptingPrivateKey()));\n } catch (Exception e) {\n throw new HttpException(\"Failed to parse AS2 Message Entity\", e);\n }\n }\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected CamelContext createCamelContext() throws Exception {\n return createSpringCamelContext(this, \"org/apache/camel/component/properties/SpringPropertiesComponentEIPConvertBodyToTest.xml\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_use_unambiguousToStringOf_whe_toStringOf_are_equal() {\n // GIVEN\n Object actual = new Object();\n Object expected = new Object();\n given(representation.toStringOf(actual)).willReturn(\"representation\");\n given(representation.toStringOf(expected)).willReturn(\"representation\");\n given(representation.unambiguousToStringOf(actual)).willReturn(\"actual\");\n given(representation.unambiguousToStringOf(expected)).willReturn(\"expected\");\n // WHEN\n UnambiguousRepresentation actualRepresentation = new UnambiguousRepresentation(representation, actual, expected);\n // THEN\n then(actualRepresentation.getActual()).isEqualTo(\"actual\");\n then(actualRepresentation.getExpected()).isEqualTo(\"expected\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void doStart() throws Exception {\n super.doStart();\n // create the client\n processorClient = EventHubsClientFactory.createEventProcessorClient(getConfiguration(), this::onEventListener, this::onErrorListener);\n // start the client but we will rely on the Azure Client Scheduler for thread management\n processorClient.start();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:listClusters\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=listClusters\").to(\"mock:result\");\n from(\"direct:listClustersPojo\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=listClusters&pojoRequest=true\").to(\"mock:result\");\n from(\"direct:createCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=createCluster\").to(\"mock:result\");\n from(\"direct:deleteCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=deleteCluster\").to(\"mock:result\");\n from(\"direct:describeCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=describeCluster\").to(\"mock:result\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public UnmarshallingTestContext withOperationName(String operationName) {\n this.operationName = operationName;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid shouldAdviceTheRoute() throws Exception {\n // Advice the route by replace the from endpoint\n AdviceWith.adviceWith(context, \"foo\", ad -> ad.replaceFromWith(\"direct:foo\"));\n // must start Camel after we are done using advice-with\n context.start();\n MockEndpoint mock = context.getEndpoint(\"mock:out\", MockEndpoint.class);\n mock.expectedBodiesReceived(\"Hello Will!\");\n String result = template.requestBody(\"direct:foo\", null, String.class);\n mock.assertIsSatisfied();\n assertEquals(\"Hello Will!\", result);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List makeBlobs(int samples, int centers, double clusterStd, double min, double max, boolean shuffle, UniformRandomProvider rng) {\n ContinuousDistribution.Sampler uniform = new UniformContinuousDistribution(min, max).createSampler(rng);\n ContinuousDistribution.Sampler gauss = new NormalDistribution(0.0, clusterStd).createSampler(rng);\n Vector2D[] centerPoints = new Vector2D[centers];\n for (int i = 0; i < centers; i++) {\n centerPoints[i] = Vector2D.of(uniform.sample(), uniform.sample());\n }\n int[] nSamplesPerCenter = new int[centers];\n int count = samples / centers;\n Arrays.fill(nSamplesPerCenter, count);\n for (int i = 0; i < samples % centers; i++) {\n nSamplesPerCenter[i]++;\n }\n List points = new ArrayList<>();\n for (int i = 0; i < centers; i++) {\n for (int j = 0; j < nSamplesPerCenter[i]; j++) {\n points.add(centerPoints[i].add(generateNoiseVector(gauss)));\n }\n }\n if (shuffle) {\n ListSampler.shuffle(rng, points);\n }\n return points;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static T getOrCreateBean(final ConfigurableApplicationContext ctx, final String actualClazz, final Class type) throws ClassNotFoundException {\n T bean;\n if (ctx.getBeanFactory().containsSingleton(actualClazz)) {\n bean = type.cast(ctx.getBeanFactory().getSingleton(actualClazz));\n } else {\n if (ApplicationListener.class.isAssignableFrom(type)) {\n RootBeanDefinition bd = new RootBeanDefinition(Class.forName(actualClazz), AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);\n bd.setScope(BeanDefinition.SCOPE_SINGLETON);\n ((BeanDefinitionRegistry) ctx.getBeanFactory()).registerBeanDefinition(actualClazz, bd);\n bean = ctx.getBean(type);\n } else {\n bean = type.cast(ctx.getBeanFactory().createBean(Class.forName(actualClazz), AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false));\n ctx.getBeanFactory().registerSingleton(actualClazz, bean);\n }\n }\n return bean;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isUseAdviceWith() {\n return true;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture deregister() {\n return delegate.deregister();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void destroy() throws Exception {\n ServiceHelper.stopService(template);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@BeforeEach\npublic void setUp() {\n condition = new TestCondition<>(\"JediPower\");\n doesNotHave = doesNotHave(condition);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:start\").aggregate(header(\"id\"), new MyAggregationStrategy()).completionOnNewCorrelationGroup().completionSize(3).to(\"log:aggregated\", \"mock:aggregated\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns the algorithm name corresponding to this variant.\n *\n * @return this variant's algorithm name\n */\npublic String algorithm() {\n return algorithm;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testStreamCacheIsDefault() throws Exception {\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:a\").to(\"mock:a\");\n }\n });\n context.start();\n a.expectedMessageCount(1);\n InputStream message = new ByteArrayInputStream(MESSAGE.getBytes());\n template.sendBody(\"direct:a\", message);\n assertMockEndpointsSatisfied();\n boolean a1 = a.assertExchangeReceived(0).getIn().getBody() instanceof StreamCache;\n assertTrue(a1);\n assertEquals(MESSAGE, a.assertExchangeReceived(0).getIn().getBody(String.class));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected CamelContext createCamelContext() throws Exception {\n return createSpringCamelContext(this, \"org/apache/camel/spring/processor/idempotent/fileConsumerIdempotentTest.xml\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ExchangeFailureHandled;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextStopped;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setLastName(String lastName) {\n this.lastName = lastName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void doSomething(RequestB request) {\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testDecimalType() {\n sql(\"sales-csv\", \"select BUDGET from sales.\\\"DECIMAL\\\"\").checking(resultSet -> {\n try {\n ResultSetMetaData metaData = resultSet.getMetaData();\n assertEquals(\"DECIMAL\", metaData.getColumnTypeName(1));\n assertEquals(18, metaData.getPrecision(1));\n assertEquals(2, metaData.getScale(1));\n } catch (SQLException e) {\n throw TestUtil.rethrow(e);\n }\n }).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void destinationReady() throws InterruptedException {\n if (refreshWanted.get()) {\n synchronized (refreshWanted) {\n //check if requestWanted is still true\n if (refreshWanted.get()) {\n log.debug(\"Waiting for new Temporary ReplyTo queue to be assigned before we can continue\");\n refreshWanted.wait();\n }\n }\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testSplitStopOnExceptionStop2() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:split\");\n // we do stop so we stop splitting when the exception occurs and thus we\n // only receive 1 message\n mock.expectedBodiesReceived(\"Hello World\");\n getMockEndpoint(\"mock:handled\").expectedMessageCount(1);\n String out = template.requestBody(\"direct:start\", \"Hello World,Kaboom,Bye World\", String.class);\n assertEquals(\"Damn Forced\", out);\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected InputValidator create() throws IOException {\n InputValidator result = new GeojsonExporterInputValidator();\n return result;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testReplyTo() {\n String replyTo = \"reply.to.queue\";\n Endpoint endpoint = context.getEndpoint(\"sjms:queue:test.SjmsEndpointTest?replyTo=\" + replyTo);\n assertNotNull(endpoint);\n assertTrue(endpoint instanceof SjmsEndpoint);\n SjmsEndpoint qe = (SjmsEndpoint) endpoint;\n assertEquals(qe.getReplyTo(), replyTo);\n assertEquals(ExchangePattern.InOut, qe.createExchange().getPattern());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic UserNotification createUserNotification(final NotificationContext context) {\n final FormDetail form = context.getObject(FORM_KEY);\n context.put(NotificationContext.PUBLICATION_ID, form.getId());\n return new FormsOnlineUserAlertNotification(form, context.getSender()).build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void readEntriesComplete(int rc, long ledgerId, long startEntryId, ByteBufList bufList, Object ctx) {\n final ReadContext rctx = (ReadContext) ctx;\n final BatchedLedgerEntryRequest entry = (BatchedLedgerEntryRequest) rctx.entry;\n if (rc != BKException.Code.OK) {\n entry.logErrorAndReattemptRead(rctx.bookieIndex, rctx.to, \"Error: \" + BKException.getMessage(rc), rc);\n return;\n }\n heardFromHosts.add(rctx.to);\n heardFromHostsBitSet.set(rctx.bookieIndex, true);\n bufList.retain();\n // if entry has completed don't handle twice\n if (entry.complete(rctx.bookieIndex, rctx.to, bufList)) {\n if (!isRecoveryRead) {\n // do not advance LastAddConfirmed for recovery reads\n lh.updateLastConfirmed(rctx.getLastAddConfirmed(), 0L);\n }\n submitCallback(BKException.Code.OK);\n } else {\n bufList.release();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean equals(Object anObject) {\n if (this == anObject) {\n return true;\n }\n if (!(anObject instanceof ProvidedProduct)) {\n return false;\n }\n ProvidedProduct another = (ProvidedProduct) anObject;\n return productId.equals(another.getProductId()) && productName.equals(another.getProductName());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testThreadProcessor() throws Exception {\n CamelContext context = new DefaultCamelContext();\n final CountDownLatch latch = new CountDownLatch(ITERS);\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:a\").threads(4).to(\"mock:input\").process(new Processor() {\n\n public void process(Exchange ex) {\n latch.countDown();\n }\n });\n }\n });\n MockEndpoint mock = context.getEndpoint(\"mock:input\", MockEndpoint.class);\n mock.expectedMessageCount(ITERS);\n final ProducerTemplate template = context.createProducerTemplate();\n final Endpoint e = context.getEndpoint(\"direct:a\");\n context.start();\n for (int i = 0; i < ITERS; i++) {\n template.send(e, new SendingProcessor(i));\n }\n MockEndpoint.assertIsSatisfied(30, TimeUnit.SECONDS);\n latch.await(30, TimeUnit.SECONDS);\n for (int i = 0; i < ITERS; i++) {\n Integer number = mock.getReceivedExchanges().get(i).getProperty(\"iterationNumber\", Integer.class);\n assertNotNull(number);\n assertEquals(i, number.intValue());\n }\n context.stop();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Retrieve the {@link AwsV4HttpSigner} associated with this authentication scheme.\n */\n@Override\nAwsV4HttpSigner signer();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void verify_internal_effects() {\n verify(objects).assertIsNotInstanceOfAny(getInfo(assertions), getActual(assertions), types);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean checkParameters(String abstractParameterString, String validationParametersString) {\n try {\n GeojsonExportParameters parameters = JSONUtil.fromJSON(abstractParameterString, GeojsonExportParameters.class);\n ValidationParameters validationParameters = JSONUtil.fromJSON(validationParametersString, ValidationParameters.class);\n return checkParameters(parameters, validationParameters);\n } catch (Exception ex) {\n log.error(ex.getMessage());\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected Endpoint createEndpoint(String uri, String remaining, Map parameters) {\n return new ProxyEndpoint(this, uri, remaining);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testAsyncProducer() {\n Endpoint endpoint = context.getEndpoint(\"sjms:queue:test.SjmsEndpointTest?synchronous=true\");\n assertNotNull(endpoint);\n assertTrue(endpoint instanceof SjmsEndpoint);\n SjmsEndpoint qe = (SjmsEndpoint) endpoint;\n assertTrue(qe.isSynchronous());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ManagedAttribute\npublic void setSinceId(long sinceId) {\n getProperties().setSinceId(sinceId);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return Builder instance to construct a {@link JsonMarshallerContext}.\n */\npublic static Builder builder() {\n return new Builder();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String getServiceUrl() {\n return \"http://api.openweathermap.org/data/2.5\";\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\ndefault String toString(@Nullable final T dto) {\n if (dto == null)\n return null;\n val stringHolder = new ArrayList(1);\n write(dto, DataSink.ofStringUtf8Consumer(stringHolder::add));\n return stringHolder.get(0);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setFriendlyName(String friendlyName) {\n this.friendlyName = friendlyName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected boolean useJmx() {\n return true;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void bodyWithLatin1DataCodingNarrowedToCharset() throws Exception {\n final int dataCoding = 0x03;\n /* ISO-8859-1 (Latin1) */\n byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };\n byte[] bodyNarrowed = { '?', 'A', 'B', '\\0', '?', (byte) 0x7F, 'C', '?' };\n Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);\n exchange.getIn().setHeader(SmppConstants.COMMAND, \"ReplaceSm\");\n exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding);\n exchange.getIn().setBody(body);\n command.execute(exchange);\n verify(session).replaceShortMessage((String) isNull(), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq(\"1616\"), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq((byte) 0), eq(bodyNarrowed));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldUpdateAutoBindDisabled() {\n OwnerDTO owner = owners.createOwner(Owners.random());\n assertThat(owner.getAutobindDisabled()).isFalse();\n owner.autobindDisabled(true);\n owners.updateOwner(owner.getKey(), owner);\n OwnerDTO updatedOwner = owners.getOwner(owner.getKey());\n assertThat(updatedOwner.getAutobindDisabled()).isTrue();\n owner.autobindDisabled(false);\n owners.updateOwner(owner.getKey(), owner);\n OwnerDTO updatedOwner2 = owners.getOwner(owner.getKey());\n assertThat(updatedOwner2.getAutobindDisabled()).isFalse();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)\npublic boolean execute(Context context) throws Exception {\n boolean result = ERROR;\n Monitor monitor = MonitorFactory.start(COMMAND);\n try {\n Long id = (Long) context.get(LINE_ID);\n Line line = lineDAO.find(id);\n InitialContext initialContext = (InitialContext) context.get(INITIAL_CONTEXT);\n Command export = CommandFactory.create(initialContext, GeojsonLineExporterCommand.class.getName());\n context.put(LINE, line);\n result = export.execute(context);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n } finally {\n log.info(Color.MAGENTA + monitor.stop() + Color.NORMAL);\n }\n return result;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CamelContext createCamelContext(int bindPort, SessionConfigCustomizer customizer) throws Exception {\n VertxPlatformHttpServerConfiguration conf = new VertxPlatformHttpServerConfiguration();\n conf.setBindPort(bindPort);\n VertxPlatformHttpServerConfiguration.SessionConfig sessionConfig = new VertxPlatformHttpServerConfiguration.SessionConfig();\n customizer.customize(sessionConfig);\n conf.setSessionConfig(sessionConfig);\n CamelContext camelContext = new DefaultCamelContext();\n camelContext.addService(new VertxPlatformHttpServer(conf));\n return camelContext;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic TwitterConfiguration getProperties() {\n return properties;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void largeFilePutGet() throws IOException {\n // 4 MB\n long length = 4 * 1024 * 1024;\n BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(length);\n CompletableFuture response = s3Async.putObject(r -> r.bucket(BUCKET).key(\"foo\"), body);\n try (OutputStream os = body.outputStream()) {\n for (int i = 0; i < length; i++) {\n os.write(i % 255);\n }\n }\n response.join();\n try (ResponseInputStream is = s3Async.getObject(r -> r.bucket(BUCKET).key(\"foo\"), AsyncResponseTransformer.toBlockingInputStream()).join()) {\n assertThat(is.response().contentLength()).isEqualTo(length);\n for (int i = 0; i < length; i++) {\n assertThat(is.read()).isEqualTo(i % 255);\n }\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic List getResourceFilesList() {\n return new ArrayList<>();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "void send(SMSMessage smsMessage);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Appel UserPannel pour r\u00e9cup du user s\u00e9lectionn\u00e9 : UserDetail[]\n * UserPanel.getUserDetailSelected()\n */\npublic UserDetail getUserDetailSelected() {\n UserDetail user = null;\n String selUser = getSelection().getFirstSelectedElement();\n if (StringUtil.isDefined(selUser)) {\n user = getOrganisationController().getUserDetail(selUser);\n }\n return user;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getVpcId() {\n List vpcs = ec2Client.describeVpcs(DescribeVpcsRequest.builder().build()).vpcs();\n if (vpcs.isEmpty()) {\n Assert.fail(\"No VPC found in this account.\");\n }\n return vpcs.get(0).vpcId();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testCookeForDefaultSessionConfig() throws Exception {\n CamelContext context = createCamelContext(sessionConfig -> {\n sessionConfig.setEnabled(true);\n });\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"platform-http:/session\").setBody().constant(\"session\");\n }\n });\n try {\n context.start();\n String sessionCookieValue = given().when().get(\"/session\").then().statusCode(200).cookie(\"vertx-web.session\", detailedCookie().path(\"/\").value(notNullValue()).httpOnly(false).secured(false).sameSite(\"Strict\")).header(\"cookie\", nullValue()).body(equalTo(\"session\")).extract().cookie(\"vertx-web.session\");\n assertTrue(sessionCookieValue.length() >= SessionHandler.DEFAULT_SESSIONID_MIN_LENGTH);\n } finally {\n context.stop();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testFunctionGetOrElse() throws Exception {\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:start\").to(\"mock:foo\").transform().constant(\"{{service.host:BAR:myotherserver}}:{{service.port:BAR:8888}}\").to(\"mock:bar\");\n }\n });\n context.start();\n getMockEndpoint(\"mock:foo\").expectedBodiesReceived(\"Hello World\");\n getMockEndpoint(\"mock:bar\").expectedBodiesReceived(\"myotherserver:8888\");\n template.sendBody(\"direct:start\", \"Hello World\");\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture close(ChannelPromise promise) {\n return delegate.close(promise);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns whether a failed request should be retried.\n *\n * @param retriesAttempted\n * The number of times the current request has been\n * attempted.\n *\n * @return True if the failed request should be retried.\n */\nboolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture write(Object msg, ChannelPromise promise) {\n return delegate.write(msg, promise);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture disconnect() {\n return delegate.disconnect();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setRole(String role) {\n this.role = role;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Indique si un utilisateur poss\u00e8de d\u00e9j\u00e0 une fiche dans l'annuaire courant\n *\n * @param userId l'identifiant d'un utilisateur\n */\npublic boolean existCard(String userId) throws WhitePagesException {\n return getCardManager().existCard(userId, getComponentId());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Sets a custom configurer which allows to do configuration while the route template is being used to create a\n * route. This gives control over the creating process, such as binding local beans and doing other kind of\n * customization.\n *\n * @param configurer the configurer with callback to invoke with the given route template context\n */\nvoid setConfigurer(Consumer configurer);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic URL getURL() throws MalformedURLException {\n return delegate.getURL();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Map getAllOptions(Object target) {\n return ALL_OPTIONS;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void sendInOnly() {\n Exchange exchange = template.send(\"direct:start\", ExchangePattern.InOnly, new Processor() {\n\n public void process(Exchange exchange) {\n exchange.getIn().setHeader(Sns2Constants.SUBJECT, \"This is my subject text.\");\n exchange.getIn().setBody(\"This is my message text.\");\n }\n });\n assertEquals(\"dcc8ce7a-7f18-4385-bedd-b97984b4363c\", exchange.getIn().getHeader(Sns2Constants.MESSAGE_ID));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Consumer createConsumer(Processor processor) throws Exception {\n WeatherConsumer answer = new WeatherConsumer(this, processor);\n // ScheduledPollConsumer default delay is 500 millis and that is too often for polling a feed, so we override\n // with a new default value. End user can override this value by providing a consumer.delay parameter\n answer.setDelay(WeatherConsumer.DEFAULT_CONSUMER_DELAY);\n configureConsumer(answer);\n return answer;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return key value pairs data\n */\nObject getData();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert an {@link AwsCredentialsIdentity} to the CRT equivalent of credentials ({@link Credentials}).\n */\npublic static Credentials toCredentials(AwsCredentialsIdentity credentialsIdentity) {\n byte[] sessionToken = null;\n if (credentialsIdentity == null || credentialsIdentity.accessKeyId() == null || credentialsIdentity.secretAccessKey() == null) {\n return null;\n }\n if (credentialsIdentity instanceof AwsSessionCredentialsIdentity) {\n sessionToken = ((AwsSessionCredentialsIdentity) credentialsIdentity).sessionToken().getBytes(StandardCharsets.UTF_8);\n }\n return new Credentials(credentialsIdentity.accessKeyId().getBytes(StandardCharsets.UTF_8), credentialsIdentity.secretAccessKey().getBytes(StandardCharsets.UTF_8), sessionToken);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public BigDecimal getAmount() {\n return amount;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void configure() {\n errorHandler(noErrorHandler());\n Processor serviceProc = exchange -> {\n // get the request URL and copy it to the request body\n String uri = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);\n exchange.getMessage().setBody(uri);\n };\n from(\"netty-http:http://localhost:\" + port2 + \"/test/hello\").to(\"http://localhost:\" + port1 + \"?throwExceptionOnFailure=false&bridgeEndpoint=true\");\n from(\"netty-http:http://localhost:\" + port1 + \"?matchOnUriPrefix=true\").process(serviceProc);\n // check the from request\n from(\"netty-http:http://localhost:\" + port2 + \"/form?bridgeEndpoint=true\").process(exchange -> {\n // just take out the message body and send it back\n Message in = exchange.getIn();\n String request = in.getBody(String.class);\n exchange.getMessage().setBody(request);\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "default T clone(@Nullable final T dto) {\n if (dto == null)\n return dto;\n val bytesHolder = new ArrayList(1);\n write(dto, DataSink.ofByteArrayConsumer(bytesHolder::add));\n return read(DataSource.ofBytes(bytesHolder.get(0)));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@Around(POINTCUT_NAME)\npublic Object doAround(ProceedingJoinPoint pjp) throws Throwable {\n Object obj = null;\n boolean result = true;\n try {\n result = Entered.get().compareAndSet(false, true);\n } catch (Throwable t) {\n }\n if (result) {\n obj = super.doAround(pjp);\n try {\n Entered.get().set(false);\n } catch (Throwable tt) {\n }\n } else {\n obj = pjp.proceed();\n }\n return obj;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Filter that can be partly handled by CsvFilterableTable.\n */\n@Test\nvoid testFilterableWhere2() {\n final String sql = \"select empno, gender, name from EMPS\\n\" + \" where gender = 'F' and empno > 125\";\n sql(\"filterable-model\", sql).returns(\"EMPNO=130; GENDER=F; NAME=Alice\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Retourne le userTemplate d'un annuaire :\n * PublicationTemplateManager#getPublicationTemplate(instanceId, getParam(\"userTemplate\",\n * instanceId))\n */\nprivate UserTemplate getUserTemplate(String instanceId) {\n SettingBundle templateSettings = ResourceLocator.getSettingBundle(\"org.silverpeas.whitePages.settings.template\");\n String templateDir = templateSettings.getString(\"templateDir\");\n return new UserTemplate(templateDir.replace('\\\\', '/') + \"/\" + getParam(\"userTemplate\", instanceId).replace('\\\\', '/'), getLanguage());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String name() {\n return delegate.name();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Sanitize an {@link SdkHttpRequest}, in order to prepare it for converting to a CRT request destined to be signed.\n *

\n * Sanitizing includes checking the path is not empty, filtering headers and query parameters that are forbidden in CRT, and\n * adding the host header (overriding if already presesnt).\n */\npublic static SdkHttpRequest sanitizeRequest(SdkHttpRequest request) {\n SdkHttpRequest.Builder builder = request.toBuilder();\n // Ensure path is non-empty\n String path = builder.encodedPath();\n if (path == null || path.isEmpty()) {\n builder.encodedPath(\"/\");\n }\n builder.clearHeaders();\n // Filter headers that will cause signing to fail\n request.forEachHeader((name, value) -> {\n if (!FORBIDDEN_HEADERS.contains(name)) {\n builder.putHeader(name, value);\n }\n });\n // Add host, which must be signed. We ignore any pre-existing Host header to match the behavior of the SigV4 signer.\n String hostHeader = SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port()) ? request.host() : request.host() + \":\" + request.port();\n builder.putHeader(HOST, hostHeader);\n builder.clearQueryParameters();\n // Filter query parameters that will cause signing to fail\n request.forEachRawQueryParameter((key, value) -> {\n if (!FORBIDDEN_PARAMS.contains(key)) {\n builder.putRawQueryParameter(key, value);\n }\n });\n return builder.build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Tests the deletion of the search fields belonging to an application instance.\n */\n@Test\npublic void testDeleteSearchFieldsFor() throws Exception {\n Transaction.performInOne(() -> {\n searchFieldDao.deleteSearchFieldsFor(\"whitePages1\");\n return null;\n });\n SearchField actual = entityManager.find(SearchField.class, \"0\");\n assertThat(actual, nullValue());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setInstrumentCode(String instrumentCode) {\n this.instrumentCode = instrumentCode;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@BeforeEach\nvoid beforeOnce() {\n predicate = o -> o != null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic AbstractParameter toActionParameter(String abstractParameter) {\n try {\n return JSONUtil.fromJSON(abstractParameter, GeojsonExportParameters.class);\n } catch (Exception e) {\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Filter that can be slightly handled by CsvFilterableTable.\n */\n@Test\nvoid testFilterableWhere3() {\n final String sql = \"select empno, gender, name from EMPS\\n\" + \" where gender <> 'M' and empno > 125\";\n sql(\"filterable-model\", sql).returns(\"EMPNO=130; GENDER=F; NAME=Alice\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testSelectSingleProjectGz() {\n sql(\"smart\", \"select name from EMPS\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n Properties props = new Properties();\n props.put(\"result\", \"mock:result\");\n context.getPropertiesComponent().setOverrideProperties(props);\n Endpoint bar = context.getEndpoint(\"mock:bar\");\n bindToRegistry(\"bar\", bar);\n from(\"direct:start\").routeId(\"myRoute\").log(\"Got ${body}\").to(\"{{result}}\");\n from(\"seda:bar?size=1234&multipleConsumers=true\").routeId(\"myOtherRoute\").filter().header(\"bar\").to(\"ref:bar\").end();\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RouteStopped;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setUsername(String username) {\n this.username = username;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDebug() throws Exception {\n // we only want to single step the beer route\n context.getDebugger().addSingleStepBreakpoint(breakpoint, beerCondition);\n getMockEndpoint(\"mock:result\").expectedBodiesReceived(\"Hello World\", \"Carlsberg\");\n template.sendBody(\"direct:start\", \"Hello World\");\n template.sendBody(\"direct:beer\", \"Carlsberg\");\n assertMockEndpointsSatisfied();\n assertEquals(2, logs.size());\n assertEquals(\"Single stepping at log:beer with body: Carlsberg\", logs.get(0));\n assertEquals(\"Single stepping at mock:result with body: Carlsberg\", logs.get(1));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String resolveParameterValue(Object obj) {\n String value = null;\n if (obj instanceof String) {\n value = \"'\" + obj.toString() + \"'\";\n } else if (obj instanceof Date) {\n DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);\n value = \"'\" + formatter.format((Date) obj) + \"'\";\n } else {\n if (obj != null) {\n value = obj.toString();\n } else {\n value = \"\";\n }\n }\n return value;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void eightBitDataCodingOverridesDefaultAlphabet() throws Exception {\n final int binDataCoding = 0xF7;\n /* GSM 8-bit class 3 */\n byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };\n Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);\n exchange.getIn().setHeader(SmppConstants.COMMAND, \"ReplaceSm\");\n exchange.getIn().setHeader(SmppConstants.ALPHABET, Alphabet.ALPHA_DEFAULT.value());\n exchange.getIn().setHeader(SmppConstants.DATA_CODING, binDataCoding);\n exchange.getIn().setBody(body);\n command.execute(exchange);\n verify(session).replaceShortMessage((String) isNull(), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq(\"1616\"), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq((byte) 0), eq(body));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ServiceStopFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isBetweenInclusive(Duration start, Duration x, Duration end) {\n return start.compareTo(x) <= 0 && x.compareTo(end) <= 0;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void fifoTesting() throws Exception {\n final int bodyCount = 5;\n List bodies = new ArrayList<>();\n for (int i = 0; i < bodyCount; i++) {\n bodies.add(\"test\" + i);\n }\n mock.expectedBodiesReceived(bodies);\n mock.expectedMessageCount(bodyCount);\n for (int i = 0; i < bodyCount; i++) {\n template.sendBody(\"hazelcast-seda:foo\", \"test\" + i);\n }\n MockEndpoint.assertIsSatisfied(context);\n mock.reset();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Message name.\n *\n * @return message name\n */\nString getName();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:start\").routeId(\"start\").to(\"activemq:queue:JmsRequestReplyExclusiveReplyToRemoveAddRouteTest?replyTo=JmsRequestReplyExclusiveReplyToRemoveAddRouteTest.reply&replyToType=Exclusive\").to(\"log:start\");\n from(\"activemq:queue:JmsRequestReplyExclusiveReplyToRemoveAddRouteTest\").routeId(\"foo\").transform(body().prepend(\"Hello \"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getEmail() {\n return email;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void handle(RoutingContext routingContext) {\n Session session = routingContext.session();\n Integer cnt = session.get(\"hitcount\");\n cnt = (cnt == null ? 0 : cnt) + 1;\n session.put(\"hitcount\", cnt);\n routingContext.response().putHeader(\"hitcount\", Integer.toString(cnt));\n routingContext.next();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic OwnerDTO translate(Owner source) {\n return this.translate(null, source);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isCompositeOperation(OperationName operationName) {\n switch(operationName) {\n case COMPOSITE:\n case COMPOSITE_BATCH:\n case COMPOSITE_TREE:\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "int resume(int current, byte[] buffer, int offset, int len);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldAllowOwnerWithParent() {\n OwnerDTO parentOwner = owners.createOwner(Owners.random());\n OwnerDTO ownerWithParent = Owners.random().parentOwner(Owners.toNested(parentOwner));\n OwnerDTO createdOwner = owners.createOwner(ownerWithParent);\n assertThat(createdOwner).isNotNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {\n MicrometerEndpoint target = (MicrometerEndpoint) obj;\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"action\":\n target.setAction(property(camelContext, java.lang.String.class, value));\n return true;\n case \"decrement\":\n target.setDecrement(property(camelContext, java.lang.String.class, value));\n return true;\n case \"increment\":\n target.setIncrement(property(camelContext, java.lang.String.class, value));\n return true;\n case \"lazystartproducer\":\n case \"lazyStartProducer\":\n target.setLazyStartProducer(property(camelContext, boolean.class, value));\n return true;\n case \"metricsdescription\":\n case \"metricsDescription\":\n target.setMetricsDescription(property(camelContext, java.lang.String.class, value));\n return true;\n case \"value\":\n target.setValue(property(camelContext, java.lang.String.class, value));\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Retourne le cardTemplate d'un annuaire :\n * PublicationTemplateManager#getPublicationTemplate(instanceId, getParam(\"cardTemplate\",\n * instanceId))\n */\nprivate PublicationTemplate getTemplate(String instanceId) throws WhitePagesException {\n try {\n return PublicationTemplateManager.getInstance().getPublicationTemplate(instanceId, getParam(\"cardTemplate\", instanceId));\n } catch (PublicationTemplateException e) {\n throw new WhitePagesException(e);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelHandlerContext fireChannelUnregistered() {\n return delegate.fireChannelUnregistered();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SortedSet getSearchFields() {\n SortedSet fields = WhitePageServiceProvider.getWhitePagesService().getSearchFields(getComponentId());\n if (fields.isEmpty()) {\n return fields;\n }\n try {\n PublicationTemplate template = null;\n Map domainProperties = null;\n RecordTemplate recordTemplate = null;\n for (SearchField field : fields) {\n if (field.getFieldId().startsWith(SearchFieldsType.XML.getLabelType())) {\n if (template == null) {\n template = getTemplate(getComponentId());\n recordTemplate = template.getRecordTemplate();\n }\n field.setLabel(recordTemplate.getFieldTemplate(field.getFieldName()).getLabel(getLanguage()));\n } else if (field.getFieldId().startsWith(SearchFieldsType.LDAP.getLabelType())) {\n if (domainProperties == null) {\n domainProperties = getDomainProperties();\n }\n field.setLabel(domainProperties.get(field.getFieldName()));\n } else if (field.getFieldId().startsWith(SearchFieldsType.USER.getLabelType())) {\n setLabel(field);\n }\n }\n } catch (Exception e) {\n SilverLogger.getLogger(this).error(e);\n }\n return fields;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testInOutExchangePattern() {\n try {\n Endpoint sjms = context.getEndpoint(\"sjms:queue:test.SjmsEndpointTest?exchangePattern=\" + ExchangePattern.InOut);\n assertNotNull(sjms);\n assertEquals(ExchangePattern.InOut, sjms.createExchange().getPattern());\n } catch (Exception e) {\n fail(\"Exception thrown: \" + e.getLocalizedMessage());\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setFirstName(String firstName) {\n this.firstName = firstName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n // required for the sql component\n getContext().getComponent(\"sql-stored\", SqlStoredComponent.class).setDataSource(db);\n from(\"direct:query\").to(\"sql-stored:SUBNUMBERS_FUNCTION(OUT INTEGER resultofsub, INTEGER ${header.num1},INTEGER ${header.num2})?function=true\").to(\"mock:query\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testUseOriginalBody() throws Exception {\n MockEndpoint dead = getMockEndpoint(\"mock:a\");\n dead.expectedBodiesReceived(\"Hello\");\n template.sendBody(\"direct:a\", \"Hello\");\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic StorageServerChannel removeChannel(Endpoint endpoint, StorageServerChannel channel) {\n lock.readLock().lock();\n try {\n if (closed) {\n log.warn(\"Skip removing channel {} of range server {} since the channel manager is already closed\", channel, endpoint);\n return null;\n }\n StorageServerChannel channelRemoved;\n if (null == channel) {\n channelRemoved = channels.remove(endpoint);\n } else {\n if (channels.remove(endpoint, channel)) {\n channelRemoved = channel;\n } else {\n channelRemoved = null;\n }\n }\n if (null == channelRemoved) {\n if (log.isDebugEnabled()) {\n log.debug(\"No channel associated with endpoint {} to be removed.\", endpoint);\n }\n } else {\n log.info(\"Removed channel {} for range server {} successfully\", channelRemoved, endpoint);\n }\n if (null != channelRemoved) {\n channelRemoved.close();\n }\n return channelRemoved;\n } finally {\n lock.readLock().unlock();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"platform-http:/session\").setBody().simple(\"Received cookie from platform-http:/session endpoint: ${header.cookie}\");\n from(\"direct:session\").toF(\"http://localhost:%d/session?cookieHandler=#instanceCookieHander\", port);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Integer getGsiSort() {\n return gsiSort;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextInitialized;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void doPreSetup() throws Exception {\n db = new EmbeddedDatabaseBuilder().setName(getClass().getSimpleName()).setType(EmbeddedDatabaseType.DERBY).addScript(\"sql/storedProcedureTest.sql\").build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static void setupCluster(int nBookies) throws Exception {\n File zkTmpDir = IOUtils.createTempDir(\"zookeeper\", \"distrlog\");\n TMP_DIRS.add(zkTmpDir);\n Pair serverAndPort = LocalDLMEmulator.runZookeeperOnAnyPort(zkTmpDir);\n zks = serverAndPort.getLeft();\n zkPort = serverAndPort.getRight();\n bkutil = LocalDLMEmulator.newBuilder().numBookies(nBookies).zkHost(\"127.0.0.1\").zkPort(zkPort).serverConf(DLMTestUtil.loadTestBkConf()).shouldStartZK(false).build();\n bkutil.start();\n zkServers = \"127.0.0.1:\" + zkPort;\n Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n\n @Override\n public void uncaughtException(Thread t, Throwable e) {\n LOG.warn(\"Uncaught exception at Thread {} : \", t.getName(), e);\n }\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testFilterableSelect() {\n sql(\"filterable-model\", \"select name from EMPS\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * As {@link #testTimestampGroupBy()} but with ORDER BY as well as GROUP\n * BY.\n */\n@Test\nvoid testTimestampGroupByAndOrderBy() throws SQLException {\n Properties info = new Properties();\n info.put(\"model\", FileAdapterTests.jsonPath(\"bug\"));\n final String sql = \"select \\\"EMPNO\\\", \\\"JOINTIMES\\\" from \\\"DATE\\\"\\n\" + \"group by \\\"EMPNO\\\",\\\"JOINTIMES\\\" order by \\\"JOINTIMES\\\"\";\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", info);\n Statement statement = connection.createStatement();\n ResultSet resultSet = statement.executeQuery(sql)) {\n assertThat(resultSet.next(), is(true));\n final Timestamp timestamp = resultSet.getTimestamp(2);\n assertThat(timestamp, is(Timestamp.valueOf(\"1996-08-03 00:01:02\")));\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected int sendTimerExchange() {\n final Exchange exchange = createExchange(false);\n if (getEndpoint().isIncludeMetadata()) {\n exchange.setProperty(Exchange.TIMER_NAME, getEndpoint().getName());\n Date now = new Date();\n exchange.setProperty(Exchange.TIMER_FIRED_TIME, now);\n exchange.getIn().setHeader(SchedulerConstants.MESSAGE_TIMESTAMP, now.getTime());\n }\n if (LOG.isTraceEnabled()) {\n LOG.trace(\"Timer {} is firing\", getEndpoint().getName());\n }\n if (!getEndpoint().isSynchronous()) {\n final AtomicBoolean polled = new AtomicBoolean(true);\n boolean doneSync = getAsyncProcessor().process(exchange, cbDoneSync -> {\n // handle any thrown exception\n if (exchange.getException() != null) {\n getExceptionHandler().handleException(\"Error processing exchange\", exchange, exchange.getException());\n }\n boolean wasPolled = exchange.getProperty(Exchange.SCHEDULER_POLLED_MESSAGES, true, boolean.class);\n if (!wasPolled) {\n polled.set(false);\n }\n // sync wil release outside this callback\n if (!cbDoneSync) {\n releaseExchange(exchange, false);\n }\n });\n if (!doneSync) {\n return polled.get() ? 1 : 0;\n }\n } else {\n try {\n getProcessor().process(exchange);\n } catch (Exception e) {\n exchange.setException(e);\n }\n // handle any thrown exception\n if (exchange.getException() != null) {\n getExceptionHandler().handleException(\"Error processing exchange\", exchange, exchange.getException());\n }\n }\n // a property can be used to control if the scheduler polled a message or not\n // for example to overrule and indicate no message was polled, which can affect the scheduler\n // to leverage backoff on idle etc.\n boolean polled = exchange.getProperty(Exchange.SCHEDULER_POLLED_MESSAGES, true, boolean.class);\n releaseExchange(exchange, false);\n return polled ? 1 : 0;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Consumer createConsumer(Processor processor) throws Exception {\n return target.createConsumer(processor);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public IntermediateModel getModel() {\n return model;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ScanResponse scan(ScanRequest scanRequest) {\n bh.consume(scanRequest);\n return this.scanResponse;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setOrderNr(int orderNr) {\n this.orderNr = orderNr;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Vector2D generateNoiseVector(ContinuousDistribution.Sampler distribution) {\n return Vector2D.of(distribution.sample(), distribution.sample());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n context.addComponent(\"async\", new MyAsyncComponent());\n from(\"direct:start\").to(\"mock:before\").to(\"log:before\").process(new Processor() {\n\n public void process(Exchange exchange) {\n beforeThreadName = Thread.currentThread().getName();\n }\n }).recipientList(constant(\"async:hi:camel,direct:foo\"));\n from(\"direct:foo\").process(new Processor() {\n\n public void process(Exchange exchange) {\n afterThreadName = Thread.currentThread().getName();\n exchange.getMessage().setBody(\"Bye Camel\");\n }\n }).to(\"log:after\").to(\"mock:after\").to(\"mock:result\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_ignore_test_when_assumption_using_path_binaryContent_fails() {\n // WHEN\n ThrowingCallable assumptionCode = () -> assumeThat(PATH).binaryContent().contains(\"foo\".getBytes(UTF_8));\n // THEN\n expectAssumptionNotMetException(assumptionCode);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process(Exchange exchange) {\n beforeThreadName = Thread.currentThread().getName();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doCreateOrUpdate(Exchange exchange, String namespaceName, Function, GenericKubernetesResource> operation) {\n String customResourceInstance = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE, String.class);\n GenericKubernetesResource customResource = new GenericKubernetesResource();\n try {\n customResource = operation.apply(getEndpoint().getKubernetesClient().genericKubernetesResources(getCRDContext(exchange.getIn())).inNamespace(namespaceName).resource(Serialization.unmarshal(customResourceInstance, GenericKubernetesResource.class)));\n } catch (KubernetesClientException e) {\n if (e.getCode() == 409) {\n LOG.info(\"Custom resource instance already exists\", e);\n } else {\n throw e;\n }\n }\n prepareOutboundMessage(exchange, customResource);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getText() {\n return text;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public URI createDLMURI(String path) throws Exception {\n return DLMTestUtil.createDLMURI(zkPort, path);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public UnmarshallingTestContext withModel(IntermediateModel model) {\n this.model = model;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public EventHubsConfiguration getConfiguration() {\n return getEndpoint().getConfiguration();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_have_reflexive_equals() {\n assertEqualsIsReflexive(delta);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void process(Exchange exchange) {\n String body = exchange.getIn().getBody(String.class);\n if (\"Kaboom\".equals(body)) {\n throw new IllegalArgumentException(\"Forced\");\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "Processor getFailureHandler();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getPathAccountSid() {\n return pathAccountSid;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@BeforeEach\npublic void setUp() throws Exception {\n matchingBody = \"\";\n super.setUp();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testJoinOnString() {\n final String sql = \"select * from emps\\n\" + \"join depts on emps.name = depts.name\";\n sql(\"smart\", sql).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Card getCurrentCard() {\n return currentCard;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ByteBufAllocator alloc() {\n return delegate.alloc();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic RangeOptionBuilder newRangeOption() {\n return RangeOptionBuilderImpl.create(rangeOptionBuilderRecycler);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "CompletableFuture put(K key, V value);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setClientNr(String clientNr) {\n this.clientNr = clientNr;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testNoStreamCache() throws Exception {\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:a\").noStreamCaching().to(\"mock:a\");\n }\n });\n context.start();\n a.expectedMessageCount(1);\n InputStream message = new ByteArrayInputStream(MESSAGE.getBytes());\n template.sendBody(\"direct:a\", message);\n assertMockEndpointsSatisfied();\n boolean b1 = a.assertExchangeReceived(0).getIn().getBody() instanceof ByteArrayInputStream;\n assertTrue(b1);\n assertEquals(MESSAGE, a.assertExchangeReceived(0).getIn().getBody(String.class));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testUnionGroupByWithoutGroupKey() {\n final String sql = \"select count(*) as c1 from EMPS group by NAME\\n\" + \"union\\n\" + \"select count(*) as c1 from EMPS group by NAME\";\n sql(\"model\", sql).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testCookieForModifiedSessionConfig() throws Exception {\n CamelContext context = createCamelContext(sessionConfig -> {\n sessionConfig.setSessionCookieName(\"vertx-session\");\n sessionConfig.setEnabled(true);\n sessionConfig.setSessionCookiePath(\"/session\");\n sessionConfig.setCookieSecure(true);\n sessionConfig.setCookieHttpOnly(true);\n sessionConfig.setCookieSameSite(CookieSameSite.LAX);\n sessionConfig.setSessionIdMinLength(64);\n });\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"platform-http:/session\").setBody().constant(\"session\");\n }\n });\n try {\n context.start();\n String sessionCookieValue = given().when().get(\"/session\").then().statusCode(200).cookie(\"vertx-session\", detailedCookie().path(\"/session\").value(notNullValue()).httpOnly(true).secured(true).sameSite(\"Lax\")).header(\"cookie\", nullValue()).body(equalTo(\"session\")).extract().cookie(\"vertx-session\");\n assertTrue(sessionCookieValue.length() >= 64);\n } finally {\n context.stop();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getVariableType() {\n return variableType;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void confirmFieldsChoice(String[] fields) {\n WhitePageServiceProvider.getWhitePagesService().createSearchFields(fields, getComponentId());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture newSucceededFuture() {\n return delegate.newSucceededFuture();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected CamelContext createCamelContext() throws Exception {\n CamelContext context = super.createCamelContext();\n context.getPropertiesComponent().setLocation(\"classpath:org/apache/camel/component/properties/myproperties.properties\");\n return context;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:start\").split(body(), new MyListOfNumbersStrategy()).to(\"mock:line\").end().to(\"mock:result\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void test002_ListStreams() throws Exception {\n String bookie = BookKeeperClusterUtils.getAnyBookie();\n String output = DockerUtils.runCommand(docker, bookie, dlogCLI, \"tool\", \"list\", \"--uri\", dlogUri, \"-f\");\n String[] lines = output.split(\"\\\\r?\\\\n\");\n Set streams = new HashSet<>();\n for (String string : lines) {\n if (string.startsWith(DLOG_STREAM_PREFIX)) {\n streams.add(string);\n }\n }\n assertEquals(100, streams.size());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void verify_internal_effects() {\n verify(iterables).assertHasSize(getInfo(assertions), getActual(assertions), 6);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid loginTest() {\n SelenideAppium.openIOSDeepLink(\"mydemoapprn://login\");\n LoginPage page = new LoginPage();\n page.setLoginName(\"bob@example.com\").setPassword(\"hackerpassword\").pressLogin().verifyWrongCredentials();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "default Query withStart(long start) {\n return withRange(start);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testStopRouteForceCompletionTrue() throws Exception {\n MyCompletionProcessor myCompletionProcessor = context.getRegistry().lookupByNameAndType(\"myCompletionProcessor\", MyCompletionProcessor.class);\n myCompletionProcessor.reset();\n context.getShutdownStrategy().setShutdownNowOnTimeout(true);\n context.getShutdownStrategy().setTimeout(5);\n template.sendBodyAndHeader(\"direct:forceCompletionTrue\", \"test1\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionTrue\", \"test2\", \"id\", \"2\");\n template.sendBodyAndHeader(\"direct:forceCompletionTrue\", \"test3\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionTrue\", \"test4\", \"id\", \"2\");\n assertEquals(0, myCompletionProcessor.getAggregationCount(), \"aggregation should not have completed yet\");\n // stopping a route should also force the completion\n context.getRouteController().stopRoute(\"foo\");\n assertEquals(2, myCompletionProcessor.getAggregationCount(), \"aggregation should have completed\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void fromGeneratedTypeMethodsCreateCorrectType() {\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().nul(true).build())).isEqualTo(EnhancedAttributeValue.nullValue());\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().s(\"foo\").build())).isEqualTo(EnhancedAttributeValue.fromString(\"foo\"));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().n(\"1\").build())).isEqualTo(EnhancedAttributeValue.fromNumber(\"1\"));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().bool(true).build())).isEqualTo(EnhancedAttributeValue.fromBoolean(true));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().b(SdkBytes.fromUtf8String(\"foo\")).build())).isEqualTo(EnhancedAttributeValue.fromBytes(SdkBytes.fromUtf8String(\"foo\")));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().ss(Arrays.asList(\"foo\", \"bar\")).build())).isEqualTo(EnhancedAttributeValue.fromSetOfStrings(Arrays.asList(\"foo\", \"bar\")));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().ns(Arrays.asList(\"1\", \"2\")).build())).isEqualTo(EnhancedAttributeValue.fromSetOfNumbers(Arrays.asList(\"1\", \"2\")));\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().bs(Arrays.asList(SdkBytes.fromUtf8String(\"foo\"), SdkBytes.fromUtf8String(\"foo2\"))).build())).isEqualTo(EnhancedAttributeValue.fromSetOfBytes(Arrays.asList(SdkBytes.fromUtf8String(\"foo\"), SdkBytes.fromUtf8String(\"foo2\"))));\n List list = Arrays.asList(AttributeValue.builder().s(\"foo\").build(), AttributeValue.builder().n(\"1\").build());\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().l(list).build())).isEqualTo(EnhancedAttributeValue.fromListOfAttributeValues(list));\n Map map = new LinkedHashMap<>();\n map.put(\"foo\", AttributeValue.builder().s(\"foo\").build());\n map.put(\"bar\", AttributeValue.builder().n(\"1\").build());\n assertThat(EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().m(map).build())).isEqualTo(EnhancedAttributeValue.fromMap(map));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected DateAssert assertionInvocationWithInstantArg(Instant instant) {\n return assertions.isEqualToIgnoringMinutes(instant);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic AnyTypeClassTO read(final String key) {\n return logic.read(key);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected String getTransactionType() {\n return CatPluginConstants.TYPE_HTTP_CLIENT;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testCreateRouteFromRouteTemplate() throws Exception {\n assertEquals(1, context.getRouteTemplateDefinitions().size());\n Map parameters = new HashMap<>();\n parameters.put(\"myCount\", \"3\");\n parameters.put(\"myFac\", \"1\");\n context.addRouteFromTemplate(\"first\", \"myTemplate\", parameters);\n String out = template.requestBody(\"direct:start\", \"Hello World\", String.class);\n assertEquals(\"3\", out);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setPassword(String password) {\n this.password = password;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean matchProcess(Exchange exchange, Processor processor, NamedNode definition, boolean before) {\n return \"beer\".equals(exchange.getFromRouteId());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads from a local file - finds larger table even without <TH>\n * elements.\n */\n@Test\nvoid testFindBiggerNoTh() {\n final String sql = \"select \\\"col4\\\" from TABLEX2 where \\\"col0\\\" like 'R1%'\";\n sql(\"testModel\", sql).returns(\"col4=R1C4\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getCurrentCardContentId() {\n String contentId = null;\n if (currentCard != null) {\n try {\n ContentManagementEngine contentMgtEngine = ContentManagementEngineProvider.getContentManagementEngine();\n contentId = String.valueOf(contentMgtEngine.getSilverContentId(currentCard.getPK().getId(), currentCard.getInstanceId()));\n } catch (ContentManagerException e) {\n SilverLogger.getLogger(this).error(e);\n }\n }\n return contentId;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the property with the given name\n *\n * @param name name of property\n * @return the property value or null if no property exists\n */\nObject getProperty(String name);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ExchangeCompleted;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RangeOptionBuilderImpl newObject(Handle> handle) {\n return new RangeOptionBuilderImpl<>(handle, rangeOptionRecycler);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return StructuredJsonGenerator used to produce the JSON document for a request.\n */\npublic StructuredJsonGenerator jsonGenerator() {\n return jsonGenerator;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ExchangeFailed;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid catchIndexOutOfBoundsException_should_succeed_and_return_null_if_no_exception_thrown() {\n // WHEN\n IndexOutOfBoundsException actual = catchIndexOutOfBoundsException(() -> {\n });\n // THEN\n then(actual).isNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testGetOne() throws Exception {\n CoapClient client = createClient(\"/users/1\");\n CoapResponse response = client.get();\n assertEquals(\"{ \\\"id\\\":\\\"1\\\", \\\"name\\\":\\\"Scott\\\" }\", response.getResponseText());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isAnalyticsOperation(OperationName operationName) {\n switch(operationName) {\n case GET_RECENT_REPORTS:\n case GET_REPORT_DESCRIPTION:\n case EXECUTE_SYNCREPORT:\n case EXECUTE_ASYNCREPORT:\n case GET_REPORT_INSTANCES:\n case GET_REPORT_RESULTS:\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Set the message timestamp\n *\n * @param timestamp\n */\nvoid setTimestamp(long timestamp);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected AtomicBoolean initialValue() {\n return new AtomicBoolean(false);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic int compareTo(final SimpleObject other) {\n return comparator.compare(this, other);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates all the test resources for the tests.\n */\n@BeforeClass\npublic static void createResources() {\n createBucket(BUCKET);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void sendInOut() {\n Exchange exchange = template.send(\"direct:start\", ExchangePattern.InOut, new Processor() {\n\n public void process(Exchange exchange) {\n exchange.getIn().setHeader(Sns2Constants.SUBJECT, \"This is my subject text.\");\n exchange.getIn().setBody(\"This is my message text.\");\n }\n });\n assertEquals(\"dcc8ce7a-7f18-4385-bedd-b97984b4363c\", exchange.getMessage().getHeader(Sns2Constants.MESSAGE_ID));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:start\").to(\"mock:start\").throwException(BadException.class, \"Forced\").to(\"mock:result\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void validate(DeleteResourceDto deleteResourceDto) {\n String resourceAbsolutePath = deleteResourceDto.getResourceAbsolutePath();\n User loginUser = deleteResourceDto.getLoginUser();\n exceptionResourceAbsolutePathInvalidated(resourceAbsolutePath);\n exceptionResourceNotExists(resourceAbsolutePath);\n exceptionUserNoResourcePermission(loginUser, resourceAbsolutePath);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextStopping;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return String.format(\"L%d-E%d~%d s-%d\", lh.getId(), eId, eId + maxCount, maxSize);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the route id.\n */\nString getRouteId();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@AfterClass\npublic static void teardownCluster() throws Exception {\n bkutil.teardown();\n zks.stop();\n for (File dir : TMP_DIRS) {\n FileUtils.forceDeleteOnExit(dir);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SneakyThrows\npublic HttpResponse post(String url, Map headers, Map params) {\n if (headers == null) {\n headers = new HashMap<>();\n }\n String requestUrl = String.format(\"%s%s\", Constants.DOLPHINSCHEDULER_API_URL, url);\n headers.put(\"Content-Type\", Constants.REQUEST_CONTENT_TYPE);\n Headers headersBuilder = Headers.of(headers);\n RequestBody requestBody = FormBody.create(getParams(params), MediaType.parse(Constants.REQUEST_CONTENT_TYPE));\n log.info(\"POST request to {}, Headers: {}, Params: {}\", requestUrl, headersBuilder, params);\n Request request = new Request.Builder().headers(headersBuilder).url(requestUrl).post(requestBody).build();\n Response response = this.httpClient.newCall(request).execute();\n int responseCode = response.code();\n HttpResponseBody responseData = null;\n if (response.body() != null) {\n responseData = JSONUtils.parseObject(response.body().string(), HttpResponseBody.class);\n }\n response.close();\n HttpResponse httpResponse = new HttpResponse(responseCode, responseData);\n log.info(\"POST response: {}\", httpResponse);\n return httpResponse;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextStopFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean useChunkEncoding(boolean payloadSigningEnabled, boolean chunkEncodingEnabled, boolean isTrailingOrFlexible) {\n return (payloadSigningEnabled && chunkEncodingEnabled) || (chunkEncodingEnabled && isTrailingOrFlexible);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean isSplit() {\n return split;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@DisplayName(\"Tests that trying to upsert without passing the action name triggers a failure\")\n@Test\npublic void upsertWithoutRequiredParameters() {\n Exchange result = fluentTemplate.to(\"qdrant:upsert\").withBody(Points.PointStruct.newBuilder().setId(id(8)).setVectors(VectorsFactory.vectors(List.of(3.5f, 4.5f))).putAllPayload(Map.of(\"foo\", value(\"hello\"), \"bar\", value(1)))).request(Exchange.class);\n assertThat(result).isNotNull();\n assertThat(result.getException()).isInstanceOf(NoSuchHeaderException.class);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Object getCollectionValueType(Object target, String name, boolean ignoreCase) {\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"schedulerproperties\":\n case \"schedulerProperties\":\n return java.lang.Object.class;\n default:\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "Object getSource();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Collection getUserInstanceIds() {\n if (userInstanceIds == null) {\n userInstanceIds = new ArrayList<>();\n CompoSpace[] instances = getOrganisationController().getCompoForUser(getUserId(), \"whitePages\");\n for (CompoSpace instance : instances) {\n userInstanceIds.add(instance.getComponentId());\n }\n }\n return userInstanceIds;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setNestedRecord(NestedRecordWithUpdateBehavior nestedRecord) {\n this.nestedRecord = nestedRecord;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldNotUpdateOwnerKey() {\n OwnerDTO owner = owners.createOwner(Owners.random());\n String originalKey = owner.getKey();\n String newKey = StringUtil.random(\"owner\");\n owner.setKey(newKey);\n owners.updateOwner(originalKey, owner);\n assertNotFound(() -> owners.getOwner(newKey));\n OwnerDTO originalOwner = owners.getOwner(originalKey);\n assertThat(originalOwner).isNotNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic OwnerDTO translate(ModelTranslator translator, Owner source) {\n return source != null ? this.populate(translator, source, new OwnerDTO()) : null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic PutOptionBuilder newPutOption() {\n return PutOptionBuilderImpl.create(putOptionBuilderRecycler);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void verify_internal_effects() {\n verify(arrays).assertContainsSequence(getInfo(assertions), getActual(assertions), arrayOf(6, 8));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Strategy to commit the offset after message being processed successfully.\n *\n * @param exchange the exchange\n */\nprivate void processCommit(final Exchange exchange, final EventContext eventContext) {\n if (lastTask == null || System.currentTimeMillis() > lastTask.scheduledExecutionTime()) {\n lastTask = new EventHubsCheckpointUpdaterTimerTask(eventContext, processedEvents);\n // delegate the checkpoint update to a dedicated Thread\n timer.schedule(lastTask, getConfiguration().getCheckpointBatchTimeout());\n } else {\n // updates the eventContext to use for the offset to be the most accurate\n lastTask.setEventContext(eventContext);\n }\n try {\n var completionCondition = processCheckpoint(exchange);\n if (completionCondition.equals(COMPLETED_BY_SIZE)) {\n eventContext.updateCheckpointAsync().subscribe(unused -> LOG.debug(\"Processed one event...\"), error -> LOG.debug(\"Error when updating Checkpoint: {}\", error.getMessage()), () -> {\n processedEvents.set(0);\n LOG.debug(\"Checkpoint updated.\");\n });\n } else if (!completionCondition.equals(COMPLETED_BY_TIMEOUT)) {\n processedEvents.incrementAndGet();\n }\n // we assume that the timer task has done the update by its side\n } catch (Exception ex) {\n getExceptionHandler().handleException(\"Error occurred during updating the checkpoint. This exception is ignored.\", exchange, ex);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {\n org.apache.camel.main.RouteControllerConfigurationProperties target = (org.apache.camel.main.RouteControllerConfigurationProperties) obj;\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"backoffdelay\":\n case \"backOffDelay\":\n target.setBackOffDelay(property(camelContext, long.class, value));\n return true;\n case \"backoffmaxattempts\":\n case \"backOffMaxAttempts\":\n target.setBackOffMaxAttempts(property(camelContext, long.class, value));\n return true;\n case \"backoffmaxdelay\":\n case \"backOffMaxDelay\":\n target.setBackOffMaxDelay(property(camelContext, long.class, value));\n return true;\n case \"backoffmaxelapsedtime\":\n case \"backOffMaxElapsedTime\":\n target.setBackOffMaxElapsedTime(property(camelContext, long.class, value));\n return true;\n case \"backoffmultiplier\":\n case \"backOffMultiplier\":\n target.setBackOffMultiplier(property(camelContext, double.class, value));\n return true;\n case \"enabled\":\n target.setEnabled(property(camelContext, boolean.class, value));\n return true;\n case \"excluderoutes\":\n case \"excludeRoutes\":\n target.setExcludeRoutes(property(camelContext, java.lang.String.class, value));\n return true;\n case \"includeroutes\":\n case \"includeRoutes\":\n target.setIncludeRoutes(property(camelContext, java.lang.String.class, value));\n return true;\n case \"initialdelay\":\n case \"initialDelay\":\n target.setInitialDelay(property(camelContext, long.class, value));\n return true;\n case \"threadpoolsize\":\n case \"threadPoolSize\":\n target.setThreadPoolSize(property(camelContext, int.class, value));\n return true;\n case \"unhealthyonexhausted\":\n case \"unhealthyOnExhausted\":\n target.setUnhealthyOnExhausted(property(camelContext, boolean.class, value));\n return true;\n case \"unhealthyonrestarting\":\n case \"unhealthyOnRestarting\":\n target.setUnhealthyOnRestarting(property(camelContext, boolean.class, value));\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic LocalDateTime deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {\n final ZonedDateTime zonedDateTime = ctxt.readValue(p, ZonedDateTime.class);\n return zonedDateTime.toLocalDateTime();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getId() {\n return id;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelHandlerContext fireChannelRead(Object msg) {\n return delegate.fireChannelRead(msg);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void process(Exchange exchange) {\n exchange.getIn().setHeader(ECS2Constants.OPERATION, ECS2Operations.describeCluster);\n exchange.getIn().setHeader(ECS2Constants.CLUSTER_NAME, \"Test\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {\n ZendeskEndpoint target = (ZendeskEndpoint) obj;\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"backofferrorthreshold\":\n case \"backoffErrorThreshold\":\n target.setBackoffErrorThreshold(property(camelContext, int.class, value));\n return true;\n case \"backoffidlethreshold\":\n case \"backoffIdleThreshold\":\n target.setBackoffIdleThreshold(property(camelContext, int.class, value));\n return true;\n case \"backoffmultiplier\":\n case \"backoffMultiplier\":\n target.setBackoffMultiplier(property(camelContext, int.class, value));\n return true;\n case \"bridgeerrorhandler\":\n case \"bridgeErrorHandler\":\n target.setBridgeErrorHandler(property(camelContext, boolean.class, value));\n return true;\n case \"delay\":\n target.setDelay(property(camelContext, long.class, value));\n return true;\n case \"exceptionhandler\":\n case \"exceptionHandler\":\n target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value));\n return true;\n case \"exchangepattern\":\n case \"exchangePattern\":\n target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value));\n return true;\n case \"greedy\":\n target.setGreedy(property(camelContext, boolean.class, value));\n return true;\n case \"inbody\":\n case \"inBody\":\n target.setInBody(property(camelContext, java.lang.String.class, value));\n return true;\n case \"initialdelay\":\n case \"initialDelay\":\n target.setInitialDelay(property(camelContext, long.class, value));\n return true;\n case \"lazystartproducer\":\n case \"lazyStartProducer\":\n target.setLazyStartProducer(property(camelContext, boolean.class, value));\n return true;\n case \"oauthtoken\":\n case \"oauthToken\":\n target.getConfiguration().setOauthToken(property(camelContext, java.lang.String.class, value));\n return true;\n case \"password\":\n target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value));\n return true;\n case \"pollstrategy\":\n case \"pollStrategy\":\n target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value));\n return true;\n case \"repeatcount\":\n case \"repeatCount\":\n target.setRepeatCount(property(camelContext, long.class, value));\n return true;\n case \"runlogginglevel\":\n case \"runLoggingLevel\":\n target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value));\n return true;\n case \"scheduledexecutorservice\":\n case \"scheduledExecutorService\":\n target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value));\n return true;\n case \"scheduler\":\n target.setScheduler(property(camelContext, java.lang.Object.class, value));\n return true;\n case \"schedulerproperties\":\n case \"schedulerProperties\":\n target.setSchedulerProperties(property(camelContext, java.util.Map.class, value));\n return true;\n case \"sendemptymessagewhenidle\":\n case \"sendEmptyMessageWhenIdle\":\n target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value));\n return true;\n case \"serverurl\":\n case \"serverUrl\":\n target.getConfiguration().setServerUrl(property(camelContext, java.lang.String.class, value));\n return true;\n case \"startscheduler\":\n case \"startScheduler\":\n target.setStartScheduler(property(camelContext, boolean.class, value));\n return true;\n case \"timeunit\":\n case \"timeUnit\":\n target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value));\n return true;\n case \"token\":\n target.getConfiguration().setToken(property(camelContext, java.lang.String.class, value));\n return true;\n case \"usefixeddelay\":\n case \"useFixedDelay\":\n target.setUseFixedDelay(property(camelContext, boolean.class, value));\n return true;\n case \"username\":\n target.getConfiguration().setUsername(property(camelContext, java.lang.String.class, value));\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDoneFromCurrentRoute() {\n // notify when exchange is done\n NotifyBuilder builder = new NotifyBuilder(context).fromCurrentRoute(\"bar\").whenDone(1);\n builder.create();\n template.sendBody(\"seda:foo\", \"Hello world!\");\n assertTrue(builder.matchesWaitTime());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldRetrieveConsumersServiceLevels() {\n OwnerDTO owner = owners.createOwner(Owners.random());\n UserDTO user = UserUtil.createUser(admin, owner);\n ApiClient userClient = ApiClients.basic(user.getUsername(), user.getPassword());\n ConsumerDTO consumer = userClient.consumers().createConsumer(Consumers.random(owner));\n ApiClient consumerClient = ApiClients.ssl(consumer);\n ProductDTO product = createProduct(owner, ProductAttributes.SupportLevel.withValue(\"VIP\"));\n owners.createPool(owner.getKey(), Pools.random(product));\n List serviceLevels = consumerClient.owners().ownerServiceLevels(owner.getKey(), \"\");\n assertThat(serviceLevels).hasSize(1).contains(\"VIP\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n // turn on debugging\n context.setDebugging(true);\n context.setDebugger(new DefaultDebugger());\n from(\"direct:start\").routeId(\"foo\").to(\"log:foo\").to(\"log:bar\").to(\"mock:result\");\n from(\"direct:beer\").routeId(\"beer\").to(\"log:beer\").to(\"mock:result\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldAllowUserWithOwnerPoolsPermissionCanSeeSystemPurposeOfTheOwnerProducts() throws ApiException {\n OwnerDTO owner = owners.createOwner(Owners.random());\n UserDTO user = UserUtil.createWith(admin, Permissions.OWNER_POOLS.all(owner));\n ApiClient userClient = ApiClients.basic(user.getUsername(), user.getPassword());\n // Make sure we see the role\n List roles = userClient.users().getUserRoles(user.getUsername());\n assertEquals(1, roles.size());\n // The user should have access to the owner's system purpose attributes (expecting this will not\n // return an error)\n SystemPurposeAttributesDTO attributes = userClient.owners().getSyspurpose(owner.getKey());\n assertEquals(owner.getKey(), attributes.getOwner().getKey());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic List getTestList() {\n List emptyList = new ArrayList();\n return emptyList;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Message type.\n *\n *

\n * Typical message types are:\n *

    \n *
  • URL: maps to one method of an action
  • \n *
  • Service: maps to one method of service call
  • \n *
  • Search: maps to one method of search call
  • \n *
  • SQL: maps to one SQL statement
  • \n *
  • Cache: maps to one cache access
  • \n *
  • Error: maps to java.lang.Throwable (java.lang.Exception and java.lang.Error)
  • \n *
\n *

\n *\n * @return message type\n */\nString getType();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List normalize(final List input, double minX, double maxX, double minY, double maxY) {\n double rangeX = maxX - minX;\n double rangeY = maxY - minY;\n List points = new ArrayList<>();\n for (Vector2D p : input) {\n double[] arr = p.toArray();\n arr[0] = (arr[0] - minX) / rangeX * 2 - 1;\n arr[1] = (arr[1] - minY) / rangeY * 2 - 1;\n points.add(new DoublePoint(arr));\n }\n return points;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getTargetValidatorIds() {\n return targetValidatorIds;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1072]\n * CSV adapter incorrectly parses TIMESTAMP values after noon.\n */\n@Test\nvoid testDateType2() throws SQLException {\n Properties info = new Properties();\n info.put(\"model\", FileAdapterTests.jsonPath(\"bug\"));\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", info)) {\n Statement statement = connection.createStatement();\n final String sql = \"select * from \\\"DATE\\\"\\n\" + \"where EMPNO >= 140 and EMPNO < 200\";\n ResultSet resultSet = statement.executeQuery(sql);\n int n = 0;\n while (resultSet.next()) {\n ++n;\n final int empId = resultSet.getInt(1);\n final String date = resultSet.getString(2);\n final String time = resultSet.getString(3);\n final String timestamp = resultSet.getString(4);\n assertThat(date, is(\"2015-12-31\"));\n switch(empId) {\n case 140:\n assertThat(time, is(\"07:15:56\"));\n assertThat(timestamp, is(\"2015-12-31 07:15:56\"));\n break;\n case 150:\n assertThat(time, is(\"13:31:21\"));\n assertThat(timestamp, is(\"2015-12-31 13:31:21\"));\n break;\n default:\n throw new AssertionError();\n }\n }\n assertThat(n, is(2));\n resultSet.close();\n statement.close();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return \"Model : \" + Order.class.getName() + \" : \" + this.orderNr + \", \" + this.orderType + \", \" + String.valueOf(this.amount) + \", \" + this.instrumentCode + \", \" + this.instrumentNumber + \", \" + this.instrumentType + \", \" + this.currency + \", \" + this.clientNr + \", \" + this.firstName + \", \" + this.lastName + \", \" + String.valueOf(this.orderDate);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void createEndpointWithAutowire() throws Exception {\n AmazonECSClientMock clientMock = new AmazonECSClientMock();\n context.getRegistry().bind(\"amazonEcsClient\", clientMock);\n ECS2Component component = context.getComponent(\"aws2-ecs\", ECS2Component.class);\n ECS2Endpoint endpoint = (ECS2Endpoint) component.createEndpoint(\"aws2-ecs://TestDomain?accessKey=xxx&secretKey=yyy\");\n assertSame(clientMock, endpoint.getConfiguration().getEcsClient());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getUserId() {\n return userId;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Filter that can be fully handled by CsvFilterableTable.\n */\n@Test\nvoid testFilterableWhere() {\n final String sql = \"select empno, gender, name from EMPS where name = 'John'\";\n sql(\"filterable-model\", sql).returns(\"EMPNO=110; GENDER=M; NAME=John\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Integer getSort() {\n return sort;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isRawOperation(OperationName operationName) {\n return operationName == OperationName.RAW;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The split delimiter to use when split is enabled. By default the delimiter is new line based. The delimiter can\n * be a regular expression.\n */\npublic void setDelimiter(String delimiter) {\n this.delimiter = delimiter;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testCollectionUpsertInsert() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedMinimumMessageCount(2);\n template.sendBody(String.format(\"nitrite://%s?collection=collection\", tempDb()), Document.createDocument(\"key1\", \"value1\"));\n template.sendBody(String.format(\"nitrite://%s?collection=collection\", tempDb()), Document.createDocument(\"key2\", \"value2\"));\n mock.assertIsSatisfied();\n List sorted = sortByChangeTimestamp(mock.getExchanges());\n Exchange change1 = sorted.get(0);\n Exchange change2 = sorted.get(1);\n assertEquals(ChangeType.INSERT, change1.getMessage().getHeader(NitriteConstants.CHANGE_TYPE));\n assertEquals(ChangeType.INSERT, change2.getMessage().getHeader(NitriteConstants.CHANGE_TYPE));\n assertNotNull(change1.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP));\n assertNotNull(change2.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP));\n assertNotNull(change1.getMessage().getBody(Map.class).get(\"key1\"));\n assertEquals(\"value1\", change1.getMessage().getBody(Map.class).get(\"key1\"));\n assertNotNull(change2.getMessage().getBody(Map.class).get(\"key2\"));\n assertEquals(\"value2\", change2.getMessage().getBody(Map.class).get(\"key2\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Integer getValue() {\n return value;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onHeaders(SdkHttpResponse response) {\n Validate.isTrue(headersFuture != null, \"onHeaders() invoked without prepare().\");\n headersFuture.complete(response);\n logRequestId(response);\n if (response.isSuccessful()) {\n successResponseHandler.onHeaders(response);\n } else {\n errorResponseHandler.onHeaders(response);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextInitializing;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Registers an optional destroy method to invoke on the bean when stopping Camel.\n *\n * @param id the id of the bean\n * @param method the destroy method name\n */\nvoid registerDestroyMethod(String id, String method);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configureConsumer(Consumer consumer) throws Exception {\n super.configureConsumer(consumer);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected ClassPathXmlApplicationContext createApplicationContext() {\n return new ClassPathXmlApplicationContext(\"org/apache/camel/component/aws2/sns/SnsComponentSpringTest-context.xml\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_have_transitive_equals() {\n assertEqualsIsTransitive(delta, new ChangeDelta<>(chunk, chunk), new ChangeDelta<>(chunk, chunk));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testUnsupportedMessageExchangePattern() {\n assertThrows(ResolveEndpointFailedException.class, () -> context.getEndpoint(\"sjms:queue:test2.SjmsEndpointTest?messageExchangePattern=OutOnly\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testToString() {\n assertThat(new SizeLessThanOrEqual(10)).hasToString(\"size <= 10\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isUseRouteBuilder() {\n return false;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SqlOperator getOperator() {\n return OPERATOR;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return the productId\n */\npublic String getProductId() {\n return productId;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void simpleFromMethodsCreateCorrectTypes() {\n assertThat(EnhancedAttributeValue.nullValue()).satisfies(v -> {\n assertThat(v.isNull()).isTrue();\n assertThat(v.type()).isEqualTo(AttributeValueType.NULL);\n });\n assertThat(EnhancedAttributeValue.fromString(\"foo\")).satisfies(v -> {\n assertThat(v.isString()).isTrue();\n assertThat(v.asString()).isEqualTo(\"foo\");\n assertThat(v.type()).isEqualTo(AttributeValueType.S);\n });\n assertThat(EnhancedAttributeValue.fromNumber(\"1\")).satisfies(v -> {\n assertThat(v.isNumber()).isTrue();\n assertThat(v.asNumber()).isEqualTo(\"1\");\n assertThat(v.type()).isEqualTo(AttributeValueType.N);\n });\n assertThat(EnhancedAttributeValue.fromBoolean(true)).satisfies(v -> {\n assertThat(v.isBoolean()).isTrue();\n assertThat(v.asBoolean()).isEqualTo(true);\n assertThat(v.type()).isEqualTo(AttributeValueType.BOOL);\n });\n assertThat(EnhancedAttributeValue.fromBytes(SdkBytes.fromUtf8String(\"foo\"))).satisfies(v -> {\n assertThat(v.isBytes()).isTrue();\n assertThat(v.asBytes().asUtf8String()).isEqualTo(\"foo\");\n assertThat(v.type()).isEqualTo(AttributeValueType.B);\n });\n assertThat(EnhancedAttributeValue.fromSetOfStrings(Arrays.asList(\"a\", \"b\"))).satisfies(v -> {\n assertThat(v.isSetOfStrings()).isTrue();\n assertThat(v.asSetOfStrings()).containsExactly(\"a\", \"b\");\n assertThat(v.type()).isEqualTo(AttributeValueType.SS);\n });\n assertThat(EnhancedAttributeValue.fromSetOfStrings((Collection) Arrays.asList(\"a\", \"b\"))).satisfies(v -> {\n assertThat(v.isSetOfStrings()).isTrue();\n assertThat(v.asSetOfStrings()).containsExactly(\"a\", \"b\");\n assertThat(v.type()).isEqualTo(AttributeValueType.SS);\n });\n assertThat(EnhancedAttributeValue.fromSetOfNumbers(Arrays.asList(\"1\", \"2\"))).satisfies(v -> {\n assertThat(v.isSetOfNumbers()).isTrue();\n assertThat(v.asSetOfNumbers()).containsExactly(\"1\", \"2\");\n assertThat(v.type()).isEqualTo(AttributeValueType.NS);\n });\n assertThat(EnhancedAttributeValue.fromSetOfNumbers((Collection) Arrays.asList(\"1\", \"2\"))).satisfies(v -> {\n assertThat(v.isSetOfNumbers()).isTrue();\n assertThat(v.asSetOfNumbers()).containsExactly(\"1\", \"2\");\n assertThat(v.type()).isEqualTo(AttributeValueType.NS);\n });\n assertThat(EnhancedAttributeValue.fromSetOfBytes(Arrays.asList(SdkBytes.fromUtf8String(\"foo\"), SdkBytes.fromUtf8String(\"foo2\")))).satisfies(v -> {\n assertThat(v.isSetOfBytes()).isTrue();\n assertThat(v.asSetOfBytes().get(0).asUtf8String()).isEqualTo(\"foo\");\n assertThat(v.asSetOfBytes().get(1).asUtf8String()).isEqualTo(\"foo2\");\n assertThat(v.type()).isEqualTo(AttributeValueType.BS);\n });\n assertThat(EnhancedAttributeValue.fromSetOfBytes((Collection) Arrays.asList(SdkBytes.fromUtf8String(\"foo\"), SdkBytes.fromUtf8String(\"foo2\")))).satisfies(v -> {\n assertThat(v.isSetOfBytes()).isTrue();\n assertThat(v.asSetOfBytes().get(0).asUtf8String()).isEqualTo(\"foo\");\n assertThat(v.asSetOfBytes().get(1).asUtf8String()).isEqualTo(\"foo2\");\n assertThat(v.type()).isEqualTo(AttributeValueType.BS);\n });\n assertThat(EnhancedAttributeValue.fromListOfAttributeValues(Arrays.asList(AttributeValue.builder().s(\"foo\").build(), AttributeValue.builder().bool(true).build()))).satisfies(v -> {\n assertThat(v.isListOfAttributeValues()).isTrue();\n assertThat(v.asListOfAttributeValues().get(0).s()).isEqualTo(\"foo\");\n assertThat(v.asListOfAttributeValues().get(1).bool()).isEqualTo(true);\n assertThat(v.type()).isEqualTo(AttributeValueType.L);\n });\n Map map = new LinkedHashMap<>();\n map.put(\"a\", AttributeValue.builder().s(\"foo\").build());\n map.put(\"b\", AttributeValue.builder().bool(true).build());\n assertThat(EnhancedAttributeValue.fromMap(map)).satisfies(v -> {\n assertThat(v.isMap()).isTrue();\n assertThat(v.asMap().get(\"a\").s()).isEqualTo(\"foo\");\n assertThat(v.asMap().get(\"b\").bool()).isEqualTo(true);\n assertThat(v.type()).isEqualTo(AttributeValueType.M);\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic List list() {\n return logic.list();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected DateAssert assertionInvocationWithStringArg(String date) {\n return assertions.isEqualToIgnoringMinutes(date);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CodeBlock resolveMethodJavadoc() {\n CodeBlock.Builder b = CodeBlock.builder();\n b.add(\"Compute the endpoint based on the given set of parameters.\");\n return b.build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean readsOutstanding() {\n return (sentReplicas.cardinality() - erroredReplicas.cardinality()) > 0;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testStopRouteForceCompletionFalse() throws Exception {\n MyCompletionProcessor myCompletionProcessor = context.getRegistry().lookupByNameAndType(\"myCompletionProcessor\", MyCompletionProcessor.class);\n myCompletionProcessor.reset();\n context.getShutdownStrategy().setShutdownNowOnTimeout(true);\n context.getShutdownStrategy().setTimeout(5);\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test1\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test2\", \"id\", \"2\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test3\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test4\", \"id\", \"2\");\n assertEquals(0, myCompletionProcessor.getAggregationCount(), \"aggregation should not have completed yet\");\n context.getRouteController().stopRoute(\"bar\");\n assertEquals(0, myCompletionProcessor.getAggregationCount(), \"aggregation should not have completed yet\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Charge la liste des fiches inter-instance portant sur le user (et non masqu\u00e9es sauf instance\n * courante)et la met en session si le user est diff\u00e9rent du user courant\n * (currentCard.getUserId()) Sinon retourne currentUserCards (Collection de WhitePagesCard)\n *\n * @param userId id d'un user\n */\nprivate void getHomeWhitePagesCards(String userId) throws WhitePagesException {\n if (currentCard == null || !currentCard.getUserId().equals(userId) || getCurrentUserCards().isEmpty()) {\n List cards = getCardManager().getHomeUserCards(userId, getUserInstanceIds(), getComponentId());\n Collections.sort(cards);\n setCurrentUserCards(cards);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ManagedAttribute\npublic void setLocations(String locations) {\n getProperties().setLocations(locations);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public NodePK getFromPK() {\n return fromPK;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convenience method to marshall a nested object (may be simple or structured) at the given location.\n *\n * @param marshallLocation Current {@link MarshallLocation}\n * @param val Value to marshall.\n */\npublic void marshall(MarshallLocation marshallLocation, Object val) {\n marshallerRegistry().getMarshaller(marshallLocation, val).marshall(val, this, null, null);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic EndpointType getEndpointType() {\n return getProperties().getType();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldRetrieveOnlyOwnersConsumers() {\n OwnerDTO testOwner = owners.createOwner(Owners.random());\n UserDTO user = UserUtil.createUser(admin, testOwner);\n ApiClient userClient = ApiClients.basic(user.getUsername(), user.getPassword());\n userClient.consumers().createConsumer(Consumers.random(testOwner));\n List consumers = userClient.owners().listOwnerConsumers(testOwner.getKey());\n assertThat(consumers).hasSize(1);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List makeMoons(int samples, boolean shuffle, double noise, UniformRandomProvider rng) {\n ContinuousDistribution.Sampler dist = new NormalDistribution(0.0, noise).createSampler(rng);\n int nSamplesOut = samples / 2;\n int nSamplesIn = samples - nSamplesOut;\n List points = new ArrayList<>();\n double range = FastMath.PI;\n double step = range / (nSamplesOut / 2.0);\n for (double angle = 0; angle < range; angle += step) {\n Vector2D outerCircle = Vector2D.of(FastMath.cos(angle), FastMath.sin(angle));\n points.add(outerCircle.add(generateNoiseVector(dist)));\n }\n step = range / (nSamplesIn / 2.0);\n for (double angle = 0; angle < range; angle += step) {\n Vector2D innerCircle = Vector2D.of(1 - FastMath.cos(angle), 1 - FastMath.sin(angle) - 0.5);\n points.add(innerCircle.add(generateNoiseVector(dist)));\n }\n if (shuffle) {\n ListSampler.shuffle(rng, points);\n }\n return points;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * retourne la valeur d'un param\u00e8tre affect\u00e9 lors de l'instanciation pour un annuaire donn\u00e9\n */\nprivate String getParam(String paramName, String instanceId) {\n return AdministrationServiceProvider.getAdminService().getComponentParameterValue(instanceId, paramName);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1118]\n * NullPointerException in EXTRACT with WHERE ... IN clause if field has null\n * value.\n */\n@Test\nvoid testFilterOnNullableTimestamp2() throws Exception {\n Properties info = new Properties();\n info.put(\"model\", FileAdapterTests.jsonPath(\"bug\"));\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", info)) {\n final Statement statement = connection.createStatement();\n final String sql1 = \"select extract(year from JOINTIMES)\\n\" + \"from \\\"DATE\\\"\\n\" + \"where extract(year from JOINTIMES) in (2006, 2007)\";\n final ResultSet joinTimes = statement.executeQuery(sql1);\n assertThat(joinTimes.next(), is(true));\n assertThat(joinTimes.getInt(1), is(2007));\n final String sql2 = \"select extract(year from JOINTIMES),\\n\" + \" count(0) from \\\"DATE\\\"\\n\" + \"where extract(year from JOINTIMES) between 2007 and 2016\\n\" + \"group by extract(year from JOINTIMES)\";\n final ResultSet joinTimes2 = statement.executeQuery(sql2);\n assertThat(joinTimes2.next(), is(true));\n assertThat(joinTimes2.getInt(1), is(2007));\n assertThat(joinTimes2.getLong(2), is(1L));\n assertThat(joinTimes2.next(), is(true));\n assertThat(joinTimes2.getInt(1), is(2015));\n assertThat(joinTimes2.getLong(2), is(2L));\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testBoolean() {\n sql(\"smart\", \"select empno, slacker from emps where slacker\").returns(\"EMPNO=100; SLACKER=true\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "Route getRoute();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the local bean repository for the route template when creating the new route\n */\nBeanRepository getLocalBeanRepository();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@BeforeEach\npublic void setUp() {\n this.owner = this.createOwner(\"test-owner\", \"Test Owner\");\n this.ct = new ConsumerType(ConsumerType.ConsumerTypeEnum.SYSTEM);\n this.ct = this.consumerTypeCurator.create(ct);\n this.consumer1 = createConsumer(VALID, VALID);\n this.consumer2 = createConsumer(EXPIRED, VALID);\n this.consumer3 = createConsumer(VALID, EXPIRED);\n this.consumer4 = createConsumer(EXPIRED, EXPIRED);\n job = injector.getInstance(CertificateCleanupJob.class);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onStream(Publisher publisher) {\n Validate.isTrue(headersFuture != null, \"onStream() invoked without prepare().\");\n Validate.isTrue(headersFuture.isDone(), \"headersFuture is still not completed when onStream() is \" + \"invoked.\");\n if (headersFuture.isCompletedExceptionally()) {\n return;\n }\n SdkHttpResponse sdkHttpResponse = headersFuture.join();\n if (sdkHttpResponse.isSuccessful()) {\n successResponseHandler.onStream(publisher);\n } else {\n errorResponseHandler.onStream(publisher);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testBridge() {\n String response = template.requestBodyAndHeader(\"http://localhost:\" + port2 + \"/test/hello\", new ByteArrayInputStream(\"This is a test\".getBytes()), \"Content-Type\", \"application/xml\", String.class);\n assertEquals(\"/\", response, \"Get a wrong response\");\n response = template.requestBody(\"http://localhost:\" + port1 + \"/hello/world\", \"hello\", String.class);\n assertEquals(\"/hello/world\", response, \"Get a wrong response\");\n assertThrows(RuntimeCamelException.class, () -> template.requestBody(\"http://localhost:\" + port2 + \"/hello/world\", \"hello\", String.class));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setTime(String time) {\n this.time = time;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The parameters to use for the route template when creating the new route\n */\nMap getParameters();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "K key();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_maintain_equals_and_hashCode_contract() {\n assertMaintainsEqualsAndHashCodeContract(delta, new ChangeDelta<>(chunk, chunk));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SneakyThrows\npublic HttpResponse put(String url, Map headers, Map params) {\n if (headers == null) {\n headers = new HashMap<>();\n }\n String requestUrl = String.format(\"%s%s\", Constants.DOLPHINSCHEDULER_API_URL, url);\n headers.put(\"Content-Type\", Constants.REQUEST_CONTENT_TYPE);\n Headers headersBuilder = Headers.of(headers);\n RequestBody requestBody = FormBody.create(getParams(params), MediaType.parse(Constants.REQUEST_CONTENT_TYPE));\n log.info(\"PUT request to {}, Headers: {}, Params: {}\", requestUrl, headersBuilder, params);\n Request request = new Request.Builder().headers(headersBuilder).url(requestUrl).put(requestBody).build();\n Response response = this.httpClient.newCall(request).execute();\n int responseCode = response.code();\n HttpResponseBody responseData = null;\n if (response.body() != null) {\n responseData = JSONUtils.parseObject(response.body().string(), HttpResponseBody.class);\n }\n response.close();\n HttpResponse httpResponse = new HttpResponse(responseCode, responseData);\n log.info(\"PUT response: {}\", httpResponse);\n return httpResponse;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)\n */\nprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String single = request.getParameter(\"single\");\n request.setAttribute(\"single\", single);\n RequestDispatcher rd = request.getRequestDispatcher(\"Single.jsp\");\n rd.forward(request, response);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Class getOptionType(String name, boolean ignoreCase) {\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"backoffdelay\":\n case \"backOffDelay\":\n return long.class;\n case \"backoffmaxattempts\":\n case \"backOffMaxAttempts\":\n return long.class;\n case \"backoffmaxdelay\":\n case \"backOffMaxDelay\":\n return long.class;\n case \"backoffmaxelapsedtime\":\n case \"backOffMaxElapsedTime\":\n return long.class;\n case \"backoffmultiplier\":\n case \"backOffMultiplier\":\n return double.class;\n case \"enabled\":\n return boolean.class;\n case \"excluderoutes\":\n case \"excludeRoutes\":\n return java.lang.String.class;\n case \"includeroutes\":\n case \"includeRoutes\":\n return java.lang.String.class;\n case \"initialdelay\":\n case \"initialDelay\":\n return long.class;\n case \"threadpoolsize\":\n case \"threadPoolSize\":\n return int.class;\n case \"unhealthyonexhausted\":\n case \"unhealthyOnExhausted\":\n return boolean.class;\n case \"unhealthyonrestarting\":\n case \"unhealthyOnRestarting\":\n return boolean.class;\n default:\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the {@link ExpressionFactory}.\n */\nExpressionFactory getExpressionFactory();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Set the message status.\n *\n * @param status message status. \"0\" means success, otherwise error code.\n */\nvoid setStatus(String status);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static DisableMultiRegionProviderChain create(ProfileFile profileFile, String profileName) {\n return new DisableMultiRegionProviderChain(Arrays.asList(SystemsSettingsDisableMultiRegionProvider.create(), ProfileDisableMultiRegionProvider.create(profileFile, profileName)));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private MethodSpec resolveEndpointMethod() {\n MethodSpec.Builder b = MethodSpec.methodBuilder(\"resolveEndpoint\");\n b.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);\n b.addParameter(endpointRulesSpecUtils.parametersClassName(), \"endpointParams\");\n b.returns(endpointRulesSpecUtils.resolverReturnType());\n b.addJavadoc(resolveMethodJavadoc());\n return b.build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void postprocess(IntermediateModel intermediateModel) {\n if (shapeModifiers == null) {\n return;\n }\n for (Entry entry : shapeModifiers.entrySet()) {\n String key = entry.getKey();\n ShapeModifier modifier = entry.getValue();\n if (ALL.equals(key)) {\n continue;\n }\n List shapeModels = Utils.findShapesByC2jName(intermediateModel, key);\n if (shapeModels.isEmpty()) {\n throw new IllegalStateException(String.format(\"Cannot find c2j shape [%s] in the intermediate model when processing \" + \"customization config shapeModifiers.%s\", key, key));\n }\n shapeModels.forEach(shapeModel -> {\n if (modifier.getStaxTargetDepthOffset() != null) {\n shapeModel.getCustomization().setStaxTargetDepthOffset(modifier.getStaxTargetDepthOffset());\n }\n if (modifier.isExcludeShape()) {\n shapeModel.getCustomization().setSkipGeneratingModelClass(true);\n shapeModel.getCustomization().setSkipGeneratingMarshaller(true);\n shapeModel.getCustomization().setSkipGeneratingUnmarshaller(true);\n } else if (modifier.getModify() != null) {\n // Modifies properties of a member in shape or shape enum.\n // This customization currently support modifying enum name\n // and marshall/unmarshall location of a member in the Shape.\n modifier.getModify().stream().flatMap(m -> m.entrySet().stream()).forEach(memberEntry -> postprocessModifyMemberProperty(shapeModel, memberEntry.getKey(), memberEntry.getValue()));\n }\n });\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Object doMarshal(Exchange exchange, Object inputObject, OutputStream stream, String soapAction) throws IOException {\n Body body = objectFactory.createBody();\n Header header = objectFactory.createHeader();\n Throwable exception = exchange.getProperty(ExchangePropertyKey.EXCEPTION_CAUGHT, Throwable.class);\n if (exception == null) {\n exception = exchange.getIn().getHeader(Exchange.EXCEPTION_CAUGHT, Throwable.class);\n }\n final List bodyContent;\n List headerContent = new ArrayList<>();\n if (exception != null) {\n bodyContent = new ArrayList<>();\n bodyContent.add(createFaultFromException(exception));\n } else {\n if (!dataFormat.isIgnoreUnmarshalledHeaders()) {\n List inboundSoapHeaders = (List) exchange.getIn().getHeader(SoapDataFormat.SOAP_UNMARSHALLED_HEADER_LIST);\n if (null != inboundSoapHeaders) {\n headerContent.addAll(inboundSoapHeaders);\n }\n }\n bodyContent = getDataFormat().createContentFromObject(inputObject, soapAction);\n }\n for (Object elem : bodyContent) {\n body.getAny().add(elem);\n }\n for (Object elem : headerContent) {\n header.getAny().add(elem);\n }\n Envelope envelope = new Envelope();\n if (!headerContent.isEmpty()) {\n envelope.setHeader(header);\n }\n envelope.setBody(body);\n return objectFactory.createEnvelope(envelope);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Checks either the batch size or the batch timeout is reached\n *\n * @param exchange the exchange\n * @return the completion condition (batch size or batch timeout) if one of them is reached, else the\n * 'uncompleted' state adds a header {@value EventHubsConstants#CHECKPOINT_UPDATED_BY} with the\n * completion condition (\n */\nprivate String processCheckpoint(Exchange exchange) {\n // Check if the batch size is reached\n if (processedEvents.get() % getConfiguration().getCheckpointBatchSize() == 0) {\n exchange.getIn().setHeader(EventHubsConstants.CHECKPOINT_UPDATED_BY, COMPLETED_BY_SIZE);\n LOG.debug(\"eventhub consumer batch size of reached\");\n // no need to run task if the batch size already did the checkpointing\n if (lastTask != null) {\n lastTask.cancel();\n }\n return COMPLETED_BY_SIZE;\n } else {\n LOG.debug(\"eventhub consumer batch size of {}/{} not reached yet\", processedEvents.get(), getConfiguration().getCheckpointBatchSize());\n }\n // Check if the batch timeout is reached\n if (System.currentTimeMillis() >= lastTask.scheduledExecutionTime()) {\n exchange.getIn().setHeader(EventHubsConstants.CHECKPOINT_UPDATED_BY, COMPLETED_BY_TIMEOUT);\n LOG.debug(\"eventhub consumer batch timeout reached\");\n return COMPLETED_BY_TIMEOUT;\n }\n return UNCOMPLETED;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ProductDTO createProduct(OwnerDTO owner, AttributeDTO... attributes) throws ApiException {\n return ownerProducts.createProductByOwner(owner.getKey(), Products.withAttributes(attributes));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testWackyColumns() {\n final String sql = \"select * from wacky_column_names where false\";\n sql(\"bug\", sql).returns().ok();\n final String sql2 = \"select \\\"joined at\\\", \\\"naME\\\"\\n\" + \"from wacky_column_names\\n\" + \"where \\\"2gender\\\" = 'F'\";\n sql(\"bug\", sql2).returns(\"joined at=2005-09-07; naME=Wilma\", \"joined at=2007-01-01; naME=Alice\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Pair, Set> normalize(final Collection realms) {\n Set normalized = new HashSet<>();\n Set groupOwnership = new HashSet<>();\n if (realms != null) {\n realms.forEach(realm -> {\n if (realm.indexOf('@') == -1) {\n normalizingAddTo(normalized, realm);\n } else {\n groupOwnership.add(realm);\n }\n });\n }\n return Pair.of(normalized, groupOwnership);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Record setStringAttribute(String stringAttribute) {\n this.stringAttribute = stringAttribute;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldSetOrgDebug() {\n OwnerDTO owner = owners.createOwner(Owners.random());\n owners.setLogLevel(owner.getKey(), null);\n OwnerDTO updatedOwner = owners.getOwner(owner.getKey());\n assertThat(updatedOwner.getLogLevel()).isEqualTo(\"DEBUG\");\n owners.deleteLogLevel(owner.getKey());\n OwnerDTO updatedOwner2 = owners.getOwner(owner.getKey());\n assertThat(updatedOwner2.getLogLevel()).isNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void sendNotification(String bodyMessage) throws NotificationException {\n String url = URLUtil.getURL(null, getComponentId()) + \"consultIdentity?userCardId=\" + notifiedUserCard.getPK().getId();\n LocalizationBundle message = ResourceLocator.getLocalizationBundle(L10N_BUNDLE, DisplayI18NHelper.getDefaultLanguage());\n String subject = message.getString(\"whitePages.notificationTitle\");\n NotificationMetaData notifMetaData = new NotificationMetaData(NotificationParameters.PRIORITY_NORMAL, subject, bodyMessage);\n for (String language : DisplayI18NHelper.getLanguages()) {\n message = ResourceLocator.getLocalizationBundle(L10N_BUNDLE, language);\n subject = message.getString(\"whitePages.notificationTitle\");\n notifMetaData.addLanguage(language, subject, bodyMessage);\n Link link = new Link(url, message.getString(\"whitePages.notifLinkLabel\"));\n notifMetaData.setLink(link, language);\n }\n notifMetaData.addUserRecipient(new UserRecipient(notifiedUserCard.getUserId()));\n notifMetaData.setAnswerAllowed(false);\n notifMetaData.setComponentId(getComponentId());\n notifMetaData.setDate(new Date());\n notifMetaData.setSender(getSettings().getString(\"whitePages.genericUserId\"));\n NotificationSender sender = new NotificationSender(getComponentId());\n sender.notifyUser(notifMetaData);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private UserTemplate getUserTemplate() {\n if (userTemplate == null) {\n SettingBundle templateSettings = ResourceLocator.getSettingBundle(\"org.silverpeas.whitePages.settings.template\");\n String templateDir = templateSettings.getString(\"templateDir\");\n this.userTemplate = new UserTemplate(templateDir.replace('\\\\', '/') + \"/\" + getParam(\"userTemplate\").replace('\\\\', '/'), getLanguage());\n }\n return this.userTemplate;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Destination createDestination(Session session, String name, boolean topic) throws JMSException {\n return null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean await() {\n return true;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isEnabled(String scheme) {\n return \"hazelcast-multimap\".equals(scheme);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n Record record = (Record) o;\n return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(stringAttribute, record.stringAttribute) && Objects.equals(gsiSort, record.gsiSort);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getFriendlyName() {\n return friendlyName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean checkFilename(String fileName) {\n if (fileName != null) {\n log.error(\"input data not expected\");\n return false;\n }\n return true;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder request(SdkHttpFullRequest.Builder request) {\n this.request = request;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the routes\n */\nRoutesDefinition getRoutes();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testReplyToAndMEPMatch() {\n String replyTo = \"reply.to.queue\";\n Endpoint endpoint = context.getEndpoint(\"sjms:queue:test.SjmsEndpointTest?replyTo=\" + replyTo + \"&exchangePattern=\" + ExchangePattern.InOut);\n assertNotNull(endpoint);\n assertTrue(endpoint instanceof SjmsEndpoint);\n SjmsEndpoint qe = (SjmsEndpoint) endpoint;\n assertEquals(qe.getReplyTo(), replyTo);\n assertEquals(ExchangePattern.InOut, qe.createExchange().getPattern());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Tests that an exception with a member in it is serialized properly. See TT0064111680\n */\n@Test\npublic void describeDirectories_InvalidNextToken_ThrowsExceptionWithRequestIdPresent() {\n try {\n dsClient.describeDirectories(DescribeDirectoriesRequest.builder().nextToken(\"invalid\").build());\n } catch (InvalidNextTokenException e) {\n assertNotNull(e.requestId());\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic EntitlementDTO populate(Entitlement source, EntitlementDTO destination) {\n return this.populate(null, source, destination);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Object getSource() {\n return getExchange();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void test000_Setup() throws Exception {\n // First test to run, formats metadata and bookies, then create a dlog namespace\n if (BookKeeperClusterUtils.metadataFormatIfNeeded(docker, currentVersion)) {\n BookKeeperClusterUtils.formatAllBookies(docker, currentVersion);\n }\n BookKeeperClusterUtils.createDlogNamespaceIfNeeded(docker, currentVersion, \"/distributedlog\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The exec protection level\n *

\n * PROT command. C - Clear S - Safe(SSL protocol only) E - Confidential(SSL protocol only) P - Private\n *\n * @param execProt either C, S, E or P\n */\npublic void setExecProt(String execProt) {\n this.execProt = execProt;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getDestination() {\n return destination;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test the search fields getting by instance id.\n */\n@Test\npublic void testGetSearchFields() {\n String instanceId = \"whitePages1\";\n Set actualSearchFields = searchFieldDao.getSearchFields(instanceId);\n assertThat(actualSearchFields.size(), is(1));\n SearchField actualSearchField = actualSearchFields.iterator().next();\n assertThat(actualSearchField.getFieldId(), is(\"field1\"));\n assertThat(actualSearchField.getInstanceId(), is(\"whitePages1\"));\n assertThat(actualSearchField.getId(), is(\"0\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testForceCompletionFalse() {\n MyCompletionProcessor myCompletionProcessor = context.getRegistry().lookupByNameAndType(\"myCompletionProcessor\", MyCompletionProcessor.class);\n myCompletionProcessor.reset();\n context.getShutdownStrategy().setShutdownNowOnTimeout(true);\n context.getShutdownStrategy().setTimeout(5);\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test1\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test2\", \"id\", \"2\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test3\", \"id\", \"1\");\n template.sendBodyAndHeader(\"direct:forceCompletionFalse\", \"test4\", \"id\", \"2\");\n assertEquals(0, myCompletionProcessor.getAggregationCount(), \"aggregation should not have completed yet\");\n context.stop();\n assertEquals(0, myCompletionProcessor.getAggregationCount(), \"aggregation should not have completed yet\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads the EMPS table from the JSON schema.\n */\n@Test\nvoid testJsonSalesEmps() {\n final String sql = \"select * from sales.emps\";\n final String[] lines = { \"EMPNO=100; NAME=Fred; DEPTNO=10; GENDER=; CITY=; EMPID=30; AGE=25; SLACKER=true; MANAGER=false; JOINEDAT=1996-08-03\", \"EMPNO=110; NAME=Eric; DEPTNO=20; GENDER=M; CITY=San Francisco; EMPID=3; AGE=80; SLACKER=null; MANAGER=false; JOINEDAT=2001-01-01\", \"EMPNO=110; NAME=John; DEPTNO=40; GENDER=M; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2002-05-03\", \"EMPNO=120; NAME=Wilma; DEPTNO=20; GENDER=F; CITY=; EMPID=1; AGE=5; SLACKER=null; MANAGER=true; JOINEDAT=2005-09-07\", \"EMPNO=130; NAME=Alice; DEPTNO=40; GENDER=F; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2007-01-01\" };\n sql(\"sales-json\", sql).returns(lines).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void preprocess(ServiceModel serviceModel) {\n if (shapeModifiers == null) {\n return;\n }\n for (Entry entry : shapeModifiers.entrySet()) {\n String key = entry.getKey();\n ShapeModifier modifier = entry.getValue();\n if (ALL.equals(key)) {\n for (Shape shape : serviceModel.getShapes().values()) {\n preprocessModifyShapeMembers(serviceModel, shape, modifier);\n }\n } else {\n Shape shape = serviceModel.getShapes().get(key);\n if (shape == null) {\n throw new IllegalStateException(\"ShapeModifier customization found for \" + key + \", but this shape doesn't exist in the model!\");\n }\n preprocessModifyShapeMembers(serviceModel, shape, modifier);\n }\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Override name of the enums, marshall/unmarshall location of the\n * members in the given shape model.\n */\nprivate void postprocessModifyMemberProperty(ShapeModel shapeModel, String memberName, ModifyModelShapeModifier modifyModel) {\n if (modifyModel.getEmitEnumName() != null) {\n EnumModel enumModel = shapeModel.findEnumModelByValue(memberName);\n if (enumModel == null) {\n throw new IllegalStateException(String.format(\"Cannot find enum [%s] in the intermediate model when processing \" + \"customization config shapeModifiers.%s\", memberName, memberName));\n }\n enumModel.setName(modifyModel.getEmitEnumName());\n }\n if (modifyModel.getEmitEnumValue() != null) {\n EnumModel enumModel = shapeModel.findEnumModelByValue(memberName);\n if (enumModel == null) {\n throw new IllegalStateException(String.format(\"Cannot find enum [%s] in the intermediate model when processing \" + \"customization config shapeModifiers.%s\", memberName, memberName));\n }\n enumModel.setValue(modifyModel.getEmitEnumValue());\n }\n if (modifyModel.getMarshallLocationName() != null) {\n MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName);\n memberModel.getHttp().setMarshallLocationName(modifyModel.getMarshallLocationName());\n }\n if (modifyModel.getUnmarshallLocationName() != null) {\n MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName);\n memberModel.getHttp().setUnmarshallLocationName(modifyModel.getUnmarshallLocationName());\n }\n if (modifyModel.isIgnoreDataTypeConversionFailures()) {\n MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName);\n memberModel.ignoreDataTypeConversionFailures(true);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets the node prefix id.\n */\nString getNodePrefixId();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDefaultExchangePattern() {\n try {\n SjmsEndpoint sjms = (SjmsEndpoint) context.getEndpoint(\"sjms:queue:test.SjmsEndpointTest\");\n assertNotNull(sjms);\n assertEquals(ExchangePattern.InOnly, sjms.getExchangePattern());\n // assertTrue(sjms.createExchange().getPattern().equals(ExchangePattern.InOnly));\n } catch (Exception e) {\n fail(\"Exception thrown: \" + e.getLocalizedMessage());\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testAnyOrder() throws Exception {\n template.sendBody(\"seda:testme\", \"Bye World\");\n template.sendBody(\"seda:testme\", \"Hello World\");\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:start\").to(\"dataset-test:seda:testme?anyOrder=true&timeout=0\");\n }\n });\n template.sendBody(\"direct:start\", \"Hello World\");\n template.sendBody(\"direct:start\", \"Bye World\");\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testFunction() throws Exception {\n context.addRoutes(new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:start\").to(\"mock:foo\").transform().constant(\"{{service.host:FOO}}:{{service.port:FOO}}\").to(\"mock:bar\");\n }\n });\n context.start();\n String body = System.getenv(\"FOO_SERVICE_HOST\") + \":\" + System.getenv(\"FOO_SERVICE_PORT\");\n getMockEndpoint(\"mock:foo\").expectedBodiesReceived(\"Hello World\");\n getMockEndpoint(\"mock:bar\").expectedBodiesReceived(body);\n template.sendBody(\"direct:start\", \"Hello World\");\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads from a local file and checks the result.\n */\n@Test\nvoid testFileSelect() {\n final String sql = \"select H1 from T1 where H0 = 'R1C0'\";\n sql(\"testModel\", sql).returns(\"H1=R1C1\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "List get();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RouteStarting;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "int resume(int current, ByteBuf buffer);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getSubnetIdInVpc(String vpcId, String az) {\n List subnets = ec2Client.describeSubnets(DescribeSubnetsRequest.builder().filters(Filter.builder().name(\"vpc-id\").values(vpcId).build(), Filter.builder().name(\"availabilityZone\").values(az).build()).build()).subnets();\n if (subnets.isEmpty()) {\n Assert.fail(\"No Subnet found in VPC \" + vpcId + \" AvailabilityZone: \" + az);\n }\n return subnets.get(0).subnetId();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Strategy when processing the exchange failed.\n *\n * @param exchange the exchange\n */\nprivate void processRollback(Exchange exchange) {\n final Exception cause = exchange.getException();\n if (cause != null) {\n getExceptionHandler().handleException(\"Error during processing exchange.\", exchange, cause);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Sets a custom maximum cache size to use in the backing cache pools.\n *\n * @param maximumCacheSize the custom maximum cache size\n */\npublic void setMaximumCacheSize(Integer maximumCacheSize) {\n this.maximumCacheSize = maximumCacheSize;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void close() {\n lock.writeLock().lock();\n try {\n if (closed) {\n return;\n }\n closed = true;\n } finally {\n lock.writeLock().unlock();\n }\n // close the channels\n channels.values().forEach(StorageServerChannel::close);\n channels.clear();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n // shutdown this test faster\n context.getShutdownStrategy().setTimeout(3);\n from(\"seda:start\").routeId(\"start\").delay(100).to(\"mock:result\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getExecProt() {\n return execProt;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected String getEmailAttrName() {\n return \"mailNickname\";\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "OIDCC4UIProvider update(OIDCC4UIProvider op, OIDCC4UIProviderTO opTO);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Appel UserPannel pour set des users selectionnable (4 [] vides) :\n */\npublic String initUserPanel() {\n String mContext = ResourceLocator.getGeneralSettingBundle().getString(\"ApplicationURL\");\n String hostSpaceName = getSpaceLabel();\n Pair hostComponentName = new Pair<>(getComponentLabel(), mContext + RWHITE_PAGES + getComponentId() + \"/Main\");\n //noinspection unchecked\n Pair[] hostPath = new Pair[1];\n hostPath[0] = new Pair<>(getString(\"whitePages.usersList\"), RWHITE_PAGES + getComponentId() + \"/Main\");\n String hostUrl = mContext + RWHITE_PAGES + getComponentId() + \"/createIdentity\";\n Selection sel = getSelection();\n sel.resetAll();\n sel.setHostSpaceName(hostSpaceName);\n sel.setHostComponentName(hostComponentName);\n sel.setHostPath(hostPath);\n sel.setGoBackURL(hostUrl);\n sel.setCancelURL(hostUrl);\n // Contraintes\n sel.setMultiSelect(false);\n sel.setPopupMode(false);\n sel.setSetSelectable(false);\n return Selection.getSelectionURL();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic LinkRepresentation getUp() {\n return getLinkWithRel(Rel.UP);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Constructs a {@link Condition} using the matcher given as a parameter.\n *

\n * Example:\n *

 import static org.assertj.core.api.Assertions.assertThat;\n * import static org.assertj.core.api.HamcrestCondition.matching;\n * import static org.hamcrest.core.StringContains.containsString;\n *\n * assertThat("abc").is(matching(containsString("a")));
\n *\n * @param the type the condition is about\n * @param matcher the Hamcrest matcher to use as a condition\n * @return the built {@link HamcrestCondition}\n */\npublic static HamcrestCondition matching(Matcher matcher) {\n return new HamcrestCondition<>(matcher);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1754]\n * In Csv adapter, convert DATE and TIME values to int, and TIMESTAMP values\n * to long.\n */\n@Test\nvoid testGroupByTimestampAdd() {\n final String sql = \"select count(*) as c,\\n\" + \" {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT) } as t\\n\" + \"from EMPS group by {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT ) } \";\n sql(\"model\", sql).returnsUnordered(\"C=1; T=1996-08-04\", \"C=1; T=2002-05-04\", \"C=1; T=2005-09-08\", \"C=1; T=2007-01-02\", \"C=1; T=2001-01-02\").ok();\n final String sql2 = \"select count(*) as c,\\n\" + \" {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT) } as t\\n\" + \"from EMPS group by {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT ) } \";\n sql(\"model\", sql2).returnsUnordered(\"C=1; T=2002-06-03\", \"C=1; T=2005-10-07\", \"C=1; T=2007-02-01\", \"C=1; T=2001-02-01\", \"C=1; T=1996-09-03\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RouteRemoved;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Card getCurrentCreateCard() {\n return currentCreateCard;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return \"[\" + row + \" \" + col + \"]\";\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void delete(final String key) {\n logic.delete(key);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setId(int id) {\n this.id = id;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List makeRandom(int samples) {\n SobolSequenceGenerator generator = new SobolSequenceGenerator(2);\n generator.skipTo(999999);\n List points = new ArrayList<>();\n for (double i = 0; i < samples; i++) {\n double[] vector = generator.nextVector();\n vector[0] = vector[0] * 2 - 1;\n vector[1] = vector[1] * 2 - 1;\n Vector2D point = Vector2D.of(vector);\n points.add(point);\n }\n return points;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "CompletableFuture delete(K key);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setAmount(BigDecimal amount) {\n this.amount = amount;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelPromise voidPromise() {\n return delegate.voidPromise();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Consumer findConsumer(Consumer consumer) {\n return this.consumerCurator.getConsumer(consumer.getUuid());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void onEventListener(final EventContext eventContext) {\n final Exchange exchange = createAzureEventHubExchange(eventContext);\n // add exchange callback\n exchange.getExchangeExtension().addOnCompletion(new Synchronization() {\n\n @Override\n public void onComplete(Exchange exchange) {\n // we update the consumer offsets\n processCommit(exchange, eventContext);\n }\n\n @Override\n public void onFailure(Exchange exchange) {\n // we do nothing here\n processRollback(exchange);\n }\n });\n // use default consumer callback\n AsyncCallback cb = defaultConsumerCallback(exchange, true);\n getAsyncProcessor().process(exchange, cb);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List getEnumeratedValues(final PlainSchemaTO schemaTO) {\n final List res = new ArrayList<>();\n final String[] values = StringUtils.isBlank(schemaTO.getEnumerationValues()) ? new String[0] : schemaTO.getEnumerationValues().split(SyncopeConstants.ENUM_VALUES_SEPARATOR);\n for (String value : values) {\n res.add(value.trim());\n }\n return res;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testFindFile() throws Exception {\n assertNotNull(manifestFileRecordCurator.findFile(record.getId()));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getSql(Invocation invocation, MappedStatement mappedStatement) {\n Object parameter = null;\n if (invocation.getArgs().length > 1) {\n parameter = invocation.getArgs()[1];\n }\n BoundSql boundSql = mappedStatement.getBoundSql(parameter);\n Configuration configuration = mappedStatement.getConfiguration();\n String sql = sqlResolve(configuration, boundSql);\n return sql;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setCamelException(boolean camelException) {\n this.camelException = camelException;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Set getEffective(final Set allowedRealms, final String requestedRealm) {\n Pair, Set> normalized = normalize(allowedRealms);\n Set requested = Set.of(requestedRealm);\n StartsWithPredicate normalizedFilter = new StartsWithPredicate(normalized.getLeft());\n StartsWithPredicate requestedFilter = new StartsWithPredicate(requested);\n Set effective = new HashSet<>();\n effective.addAll(requested.stream().filter(normalizedFilter).collect(Collectors.toSet()));\n effective.addAll(normalized.getLeft().stream().filter(requestedFilter).collect(Collectors.toSet()));\n // includes group ownership\n effective.addAll(normalized.getRight());\n // includes dynamic realms\n if (allowedRealms != null) {\n effective.addAll(allowedRealms.stream().filter(DYN_REALMS_PREDICATE).collect(Collectors.toSet()));\n }\n return effective;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setConfirmationToken(String confirmationToken) {\n this.confirmationToken = confirmationToken;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isCompositeSObjectCollectionsOperation(OperationName operationName) {\n switch(operationName) {\n case COMPOSITE_CREATE_SOBJECT_COLLECTIONS:\n case COMPOSITE_UPDATE_SOBJECT_COLLECTIONS:\n case COMPOSITE_UPSERT_SOBJECT_COLLECTIONS:\n case COMPOSITE_RETRIEVE_SOBJECT_COLLECTIONS:\n case COMPOSITE_DELETE_SOBJECT_COLLECTIONS:\n return true;\n default:\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isPayloadSigning(BaseSignRequest request) {\n boolean isAnonymous = CredentialUtils.isAnonymous(request.identity());\n boolean isPayloadSigningEnabled = request.requireProperty(PAYLOAD_SIGNING_ENABLED, true);\n boolean isEncrypted = \"https\".equals(request.request().protocol());\n if (isAnonymous) {\n return false;\n }\n // presigning requests should always have a null payload, and should always be unsigned-payload\n if (!isEncrypted && request.payload().isPresent()) {\n if (!isPayloadSigningEnabled) {\n LOG.debug(() -> \"Payload signing was disabled for an HTTP request with a payload. \" + \"Signing will be enabled. Use HTTPS for unsigned payloads.\");\n }\n return true;\n }\n return isPayloadSigningEnabled;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getLastName() {\n return lastName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "void sendReadTo(int bookieIndex, BookieId to, BatchedLedgerEntryRequest entry) throws InterruptedException {\n if (lh.throttler != null) {\n lh.throttler.acquire();\n }\n if (isRecoveryRead) {\n int flags = BookieProtocol.FLAG_HIGH_PRIORITY | BookieProtocol.FLAG_DO_FENCING;\n clientCtx.getBookieClient().batchReadEntries(to, lh.ledgerId, entry.eId, maxCount, maxSize, this, new ReadContext(bookieIndex, to, entry), flags, lh.ledgerKey);\n } else {\n clientCtx.getBookieClient().batchReadEntries(to, lh.ledgerId, entry.eId, maxCount, maxSize, this, new ReadContext(bookieIndex, to, entry), BookieProtocol.FLAG_NONE);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private IdentityCertificate saveCert(IdentityCertificate cert) {\n cert.setId(null);\n certSerialCurator.create(cert.getSerial());\n return identityCertificateCurator.create(cert);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testDelete() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:delete\");\n mock.expectedHeaderReceived(\"id\", \"1\");\n CoapClient client = createClient(\"/users/1\");\n client.delete();\n MockEndpoint.assertIsSatisfied(context);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void ecsListClustersPojoTest() throws Exception {\n mock.expectedMessageCount(1);\n Exchange exchange = template.request(\"direct:listClustersPojo\", new Processor() {\n\n @Override\n public void process(Exchange exchange) {\n exchange.getIn().setHeader(ECS2Constants.OPERATION, ECS2Operations.listClusters);\n exchange.getIn().setBody(ListClustersRequest.builder().maxResults(10).build());\n }\n });\n MockEndpoint.assertIsSatisfied(context);\n ListClustersResponse resultGet = (ListClustersResponse) exchange.getIn().getBody();\n assertEquals(1, resultGet.clusterArns().size());\n assertEquals(\"Test\", resultGet.clusterArns().get(0));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic DeleteOptionBuilder newDeleteOption() {\n return DeleteOptionBuilderImpl.create(deleteOptionBuilderRecycler);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ParameterizedTest\n@CsvSource({ \"false,false\", \"false,true\" })\nvoid unencryptedCompressionSignatureOrderTest(boolean encrypt, boolean compressBeforeSign) {\n compressionSignatureOrderTest(encrypt, compressBeforeSign);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Dimension getPreferredSize() {\n return new Dimension(150, 150);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void configure() throws Exception {\n // ignore failure if its something with Donkey\n onException(IllegalArgumentException.class).onWhen(exceptionMessage().contains(\"Donkey\")).handled(true);\n from(\"direct:okay\").// mark this route as transacted\n transacted().setBody(constant(\"Tiger in Action\")).bean(\"bookService\").setBody(constant(\"Elephant in Action\")).bean(\"bookService\").setBody(constant(\"Donkey in Action\")).bean(\"bookService\");\n from(\"direct:fail\").// and this route is not transacted\n setBody(constant(\"Tiger in Action\")).bean(\"bookService\").setBody(constant(\"Donkey in Action\")).bean(\"bookService\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getRole() {\n return role;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testSplitStopOnExceptionOk() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:split\");\n mock.expectedBodiesReceived(\"Hello World\", \"Bye World\");\n getMockEndpoint(\"mock:handled\").expectedMessageCount(0);\n template.sendBody(\"direct:start\", \"Hello World,Bye World\");\n assertMockEndpointsSatisfied();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean checkParameters(AbstractParameter abstractParameter, ValidationParameters validationParameters) {\n if (!(abstractParameter instanceof GeojsonExportParameters)) {\n log.error(\"invalid parameters for GeoJson export \" + abstractParameter.getClass().getName());\n return false;\n }\n GeojsonExportParameters parameters = (GeojsonExportParameters) abstractParameter;\n if (parameters.getStartDate() != null && parameters.getEndDate() != null) {\n if (parameters.getStartDate().after(parameters.getEndDate())) {\n log.error(\"end date before start date \");\n return false;\n }\n }\n String type = parameters.getReferencesType();\n if (type != null && !type.isEmpty()) {\n if (!Arrays.asList(allowedTypes).contains(type.toLowerCase())) {\n log.error(\"invalid type \" + type);\n return false;\n }\n }\n return true;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "int getAttempt();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RoutesStopped;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getHeader(String header, Exchange exchange) {\n return (String) exchange.getMessage().getHeader(header);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setEmail(String email) {\n this.email = email;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Record setGsiSort(Integer gsiSort) {\n this.gsiSort = gsiSort;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected void verify_internal_effects() {\n verify(iterables).assertAllMatch(getInfo(assertions), getActual(assertions), predicate, PredicateDescription.GIVEN);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n *

\n * Important: Implementations must block the calling thread until all\n * pending metrics are published and any resources acquired have been freed.\n */\n@Override\nvoid close();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return \"User [id=\" + id + \", email=\" + email + \", password=\" + password + \", firstName=\" + firstName + \", lastName=\" + lastName + \", enabled=\" + enabled + \", confirmationToken=\" + confirmationToken + \", gender=\" + gender + \", role=\" + role + \", lastseen=\" + lastseen + \"]\";\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void start() {\n nettyRemotingServer.start();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void uncaughtException(Thread t, Throwable e) {\n LOG.warn(\"Uncaught exception at Thread {} : \", t.getName(), e);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDirectories() {\n String vpcId = getVpcId();\n // Creating a directory requires at least two subnets located in\n // different availability zones\n String subnetId_0 = getSubnetIdInVpc(vpcId, US_EAST_1A);\n String subnetId_1 = getSubnetIdInVpc(vpcId, US_EAST_1B);\n String dsId = dsClient.createDirectory(CreateDirectoryRequest.builder().description(\"This is my directory!\").name(\"AWS.Java.SDK.Directory\").shortName(\"md\").password(\"My.Awesome.Password.2015\").size(DirectorySize.SMALL).vpcSettings(DirectoryVpcSettings.builder().vpcId(vpcId).subnetIds(subnetId_0, subnetId_1).build()).build()).directoryId();\n dsClient.deleteDirectory(DeleteDirectoryRequest.builder().directoryId(dsId).build());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:start\").to(\"mock:foo\").transform().constant(\"{{service.host:FOO}}:{{service.port:FOO}}\").to(\"mock:bar\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Assign next available IP in prefix and store it in the SDNC database, table IPAM_IP_ASSIGNEMENT.\n *\n * @param parameters HashMap of parameters passed by the DG to this function\n * \n * \n * \n * \n * \n * \n * \n *
parameterMandatory/Optionaldescription
service_instance_idMandatoryThe service instance ID uniquely identifying the service.
vf_module_idMandatoryThe VF module ID uniquely identifying the VF.
prefix_idMandatoryThe prefix from which to get next available IP.
\n */\nQueryStatus assignIpAddress(Map parameters, SvcLogicContext ctx);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process(Exchange exchange) throws Exception {\n // if file based we need to load the file into memory as the file may be deleted/moved afterwards\n Object body = getInBody(exchange);\n if (body instanceof WrappedFile) {\n body = exchange.getIn().getBody(String.class);\n }\n if (split) {\n // use new lines in both styles\n Iterator it = ObjectHelper.createIterator(body, delimiter, false, true);\n while (it.hasNext()) {\n Object line = it.next();\n LOG.trace(\"Received message body {}\", line);\n expectedBodies.add(line);\n }\n } else {\n expectedBodies.add(body);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setUserId(final String userId) {\n this.userId = userId;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get the next available entry log ID.\n */\nint nextId() throws IOException;", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return \"Initializing CamelContext: \" + getContext().getName();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Action(semantics = NON_IDEMPOTENT_ARE_YOU_SURE)\n@ActionLayout(position = ActionLayout.Position.PANEL, describedAs = \"Deletes this object from the persistent datastore\")\npublic void delete() {\n final String title = titleService.titleOf(this);\n messageService.informUser(String.format(\"'%s' deleted\", title));\n repositoryService.removeAndFlush(this);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected MapAssert invoke_api_method() {\n return assertions.hasEntrySatisfying(keyCondition, valueCondition);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n // TODO Auto-generated method stub\n String ev = request.getParameter(\"ev\");\n try {\n Class.forName(\"com.mysql.jdbc.Driver\");\n ServletContext ct = getServletContext();\n Connection con = (Connection) DriverManager.getConnection(ct.getInitParameter(\"path\"), ct.getInitParameter(\"user\"), ct.getInitParameter(\"pass\"));\n PreparedStatement st;\n st = con.prepareStatement(\"delete from job where id=?\");\n st.setString(1, ev);\n int i = 0;\n i = st.executeUpdate();\n response.sendRedirect(\"adminjobs.jsp\");\n } catch (SQLException | ClassNotFoundException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "T get(RouteTemplateContext rtc);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object doFinish(Invocation invocation, Transaction t) throws InvocationTargetException, IllegalAccessException {\n Object returnObj = null;\n try {\n returnObj = invocation.proceed();\n t.setStatus(Transaction.SUCCESS);\n } catch (Exception e) {\n Cat.logError(e);\n throw e;\n } finally {\n t.complete();\n }\n return returnObj;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String getSoapPackageName() {\n return SOAP_PACKAGE_NAME;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nAPlainAttrUniqueValue getUniqueValue();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CloseableHttpResponse postWithFile(String url, Map headers, Map params, File file) {\n try {\n Headers headersBuilder = Headers.of(headers);\n MultipartEntityBuilder builder = MultipartEntityBuilder.create();\n builder.addTextBody(\"json\", getParams(params), ContentType.MULTIPART_FORM_DATA);\n builder.addBinaryBody(\"file\", Files.newInputStream(file.toPath()), ContentType.APPLICATION_OCTET_STREAM, file.getName());\n HttpEntity multipart = builder.build();\n String requestUrl = String.format(\"%s%s\", Constants.DOLPHINSCHEDULER_API_URL, url);\n log.info(\"POST request to {}, Headers: {}, Params: {}\", requestUrl, headersBuilder, params);\n HttpPost httpPost = new HttpPost(requestUrl);\n for (Map.Entry header : headers.entrySet()) {\n httpPost.setHeader(new BasicHeader(header.getKey(), header.getValue()));\n }\n httpPost.setEntity(multipart);\n CloseableHttpClient client = HttpClients.createDefault();\n return client.execute(httpPost);\n } catch (Exception e) {\n log.error(\"error\", e);\n }\n return null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public VariableModel withDocumentation(String documentation) {\n setDocumentation(documentation);\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDumpAsYamlUriAsParameters() throws Exception {\n MBeanServer mbeanServer = getMBeanServer();\n ObjectName on = getContextObjectName();\n String yaml = (String) mbeanServer.invoke(on, \"dumpRoutesAsYaml\", new Object[] { true, true }, new String[] { \"boolean\", \"boolean\" });\n assertNotNull(yaml);\n log.info(yaml);\n assertTrue(yaml.contains(\"route\"));\n assertTrue(yaml.contains(\"myRoute\"));\n assertTrue(yaml.contains(\"myOtherRoute\"));\n assertTrue(yaml.contains(\"direct\"));\n assertTrue(yaml.contains(\"name: start\"));\n assertTrue(yaml.contains(\"mock\"));\n assertTrue(yaml.contains(\"name: result\"));\n assertTrue(yaml.contains(\"ref\"));\n assertTrue(yaml.contains(\"name: bar\"));\n assertTrue(yaml.contains(\"seda\"));\n assertTrue(yaml.contains(\"name: bar\"));\n assertTrue(yaml.contains(\"parameters:\"));\n assertTrue(yaml.contains(\"size: 1234\"));\n assertTrue(yaml.contains(\"multipleConsumers: true\"));\n assertTrue(yaml.contains(\"expression: bar\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_not_be_equal_to_null() {\n assertThat(delta.equals(null)).isFalse();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static V4PayloadSigner v4PayloadSigner(SignRequest request, V4Properties properties) {\n boolean isPayloadSigning = isPayloadSigning(request);\n boolean isEventStreaming = isEventStreaming(request.request());\n boolean isChunkEncoding = request.requireProperty(CHUNK_ENCODING_ENABLED, false);\n boolean isTrailing = request.request().firstMatchingHeader(X_AMZ_TRAILER).isPresent();\n boolean isFlexible = request.hasProperty(CHECKSUM_ALGORITHM) && !hasChecksumHeader(request);\n if (isEventStreaming) {\n if (isPayloadSigning) {\n return getEventStreamV4PayloadSigner(properties.getCredentials(), properties.getCredentialScope(), properties.getSigningClock());\n }\n throw new UnsupportedOperationException(\"Unsigned payload is not supported with event-streaming.\");\n }\n if (useChunkEncoding(isPayloadSigning, isChunkEncoding, isTrailing || isFlexible)) {\n return AwsChunkedV4PayloadSigner.builder().credentialScope(properties.getCredentialScope()).chunkSize(DEFAULT_CHUNK_SIZE_IN_BYTES).checksumAlgorithm(request.property(CHECKSUM_ALGORITHM)).build();\n }\n return V4PayloadSigner.create();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Set getSearchFieldIds() {\n Set ids = new HashSet<>();\n SortedSet searchFields = getSearchFields();\n if (searchFields != null && !searchFields.isEmpty()) {\n for (SearchField field : searchFields) {\n ids.add(field.getFieldId());\n }\n }\n return ids;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns the underlying security protocol.\n */\npublic String getSecurityProtocol() {\n return securityProtocol;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doDelete(Exchange exchange, String namespaceName) {\n String customResourceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE_NAME, String.class);\n if (ObjectHelper.isEmpty(customResourceName)) {\n LOG.error(\"Deleting a specific deployment require specify a deployment name\");\n throw new IllegalArgumentException(\"Deleting a specific deployment require specify a deployment name\");\n }\n try {\n List statusDetails = getEndpoint().getKubernetesClient().genericKubernetesResources(getCRDContext(exchange.getIn())).inNamespace(namespaceName).withName(customResourceName).delete();\n boolean deleted = ObjectHelper.isNotEmpty(statusDetails);\n exchange.getMessage().setHeader(KubernetesConstants.KUBERNETES_DELETE_RESULT, deleted);\n } catch (KubernetesClientException e) {\n if (e.getCode() == 404) {\n LOG.info(\"Custom resource instance not found\", e);\n } else {\n throw e;\n }\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String buildUri(String scheme, Map properties, boolean encode) throws URISyntaxException {\n String syntax = scheme + BASE;\n String uri = syntax;\n Map copy = new HashMap<>(properties);\n uri = buildPathParameter(syntax, uri, \"index\", null, true, copy);\n uri = buildQueryParameters(uri, copy, encode);\n return uri;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get a default implementation of a {@link AwsV4AuthScheme}\n */\nstatic AwsV4AuthScheme create() {\n return DefaultAwsV4AuthScheme.create();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Whether this class supports being singleton or not.\n *\n * @return true to be a singleton shared instance, false to create new instances.\n */\nboolean isSingleton();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelHandlerContext fireChannelRegistered() {\n return delegate.fireChannelRegistered();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDuplicate() {\n LedgerEntryImpl duplicatedEntry = LedgerEntryImpl.duplicate(entryImpl);\n // the underneath buffer should have 2 entries referencing it\n assertEquals(2, dataBuf.refCnt());\n assertEquals(ledgerId, duplicatedEntry.getLedgerId());\n assertEquals(entryId, duplicatedEntry.getEntryId());\n assertEquals(length, duplicatedEntry.getLength());\n assertArrayEquals(dataBytes, duplicatedEntry.getEntryBytes());\n duplicatedEntry.close();\n assertEquals(1, dataBuf.refCnt());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "boolean complete(int bookieIndex, BookieId host, final ByteBufList bufList) {\n if (isComplete()) {\n return false;\n }\n if (!complete.getAndSet(true)) {\n for (int i = 0; i < bufList.size(); i++) {\n ByteBuf buffer = bufList.getBuffer(i);\n ByteBuf content;\n try {\n content = lh.macManager.verifyDigestAndReturnData(eId + i, buffer);\n } catch (BKException.BKDigestMatchException e) {\n clientCtx.getClientStats().getReadOpDmCounter().inc();\n logErrorAndReattemptRead(bookieIndex, host, \"Mac mismatch\", BKException.Code.DigestMatchException);\n return false;\n }\n rc = BKException.Code.OK;\n /*\n * The length is a long and it is the last field of the metadata of an entry.\n * Consequently, we have to subtract 8 from METADATA_LENGTH to get the length.\n */\n LedgerEntryImpl entryImpl = LedgerEntryImpl.create(lh.ledgerId, startEntryId + i);\n entryImpl.setLength(buffer.getLong(DigestManager.METADATA_LENGTH - 8));\n entryImpl.setEntryBuf(content);\n entries.add(entryImpl);\n }\n writeSet.recycle();\n return true;\n } else {\n writeSet.recycle();\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected DateAssert assertionInvocationWithInstantArg() {\n return assertions.isEqualToIgnoringMinutes(otherDate.toInstant());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getOrderType() {\n return orderType;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1051]\n * Underflow exception due to scaling IN clause literals.\n */\n@Test\nvoid testInToSemiJoinWithoutCast() {\n final String sql = \"SELECT e.name\\n\" + \"FROM emps AS e\\n\" + \"WHERE e.empno in \" + range(130, SqlToRelConverter.DEFAULT_IN_SUB_QUERY_THRESHOLD);\n sql(\"smart\", sql).returns(\"NAME=Alice\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ResourceParametersHelper getResources() {\n ResourceParametersHelper resources = super.getResources();\n if (customConfig == Flag.YES.ordinal()) {\n return resources;\n }\n resources.put(ResourceType.DATASOURCE, dataSource);\n resources.put(ResourceType.DATASOURCE, dataTarget);\n return resources;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Object getSource() {\n return getContext();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected DateAssert assertionInvocationWithDateArg() {\n return assertions.isEqualToIgnoringMinutes(otherDate);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CustomResourceDefinitionContext getCRDContext(Message message) {\n String name;\n String group;\n String scope;\n String version;\n String plural;\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdName())) {\n name = message.getHeader(KubernetesConstants.KUBERNETES_CRD_NAME, String.class);\n } else {\n name = getEndpoint().getKubernetesConfiguration().getCrdName();\n }\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdGroup())) {\n group = message.getHeader(KubernetesConstants.KUBERNETES_CRD_GROUP, String.class);\n } else {\n group = getEndpoint().getKubernetesConfiguration().getCrdGroup();\n }\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdScope())) {\n scope = message.getHeader(KubernetesConstants.KUBERNETES_CRD_SCOPE, String.class);\n } else {\n scope = getEndpoint().getKubernetesConfiguration().getCrdScope();\n }\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdVersion())) {\n version = message.getHeader(KubernetesConstants.KUBERNETES_CRD_VERSION, String.class);\n } else {\n version = getEndpoint().getKubernetesConfiguration().getCrdVersion();\n }\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdPlural())) {\n plural = message.getHeader(KubernetesConstants.KUBERNETES_CRD_PLURAL, String.class);\n } else {\n plural = getEndpoint().getKubernetesConfiguration().getCrdPlural();\n }\n if (ObjectHelper.isEmpty(name) || ObjectHelper.isEmpty(group) || ObjectHelper.isEmpty(scope) || ObjectHelper.isEmpty(version) || ObjectHelper.isEmpty(plural)) {\n LOG.error(\"one of more of the custom resource definition argument(s) are missing.\");\n throw new IllegalArgumentException(\"one of more of the custom resource definition argument(s) are missing.\");\n }\n return new CustomResourceDefinitionContext.Builder().withName(// example: \"githubsources.sources.knative.dev\"\n message.getHeader(KubernetesConstants.KUBERNETES_CRD_NAME, String.class)).withGroup(// example: \"sources.knative.dev\"\n message.getHeader(KubernetesConstants.KUBERNETES_CRD_GROUP, String.class)).withScope(// example: \"Namespaced\"\n message.getHeader(KubernetesConstants.KUBERNETES_CRD_SCOPE, String.class)).withVersion(// example: \"v1alpha1\"\n message.getHeader(KubernetesConstants.KUBERNETES_CRD_VERSION, String.class)).withPlural(// example: \"githubsources\"\n message.getHeader(KubernetesConstants.KUBERNETES_CRD_PLURAL, String.class)).build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void removeStorageContainer(long groupId) {\n synchronized (storageContainers) {\n storageContainers.remove(groupId);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void test005_CheckStreamDeleted() throws Exception {\n String bookie = BookKeeperClusterUtils.getAnyBookie();\n String output = DockerUtils.runCommand(docker, bookie, true, dlogCLI, \"tool\", \"show\", \"--uri\", dlogUri, \"--stream\", \"stream-99\", \"-f\");\n assertTrue(output.contains(\"Log stream-99 does not exist or has been deleted\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void checkEmpty(ResultSet resultSet) {\n try {\n final ResultSetMetaData metaData = resultSet.getMetaData();\n assertThat(metaData.getColumnCount(), is(1));\n assertThat(metaData.getColumnName(1), is(\"EmptyFileHasNoColumns\"));\n assertThat(metaData.getColumnType(1), is(Types.BOOLEAN));\n String actual = FileAdapterTests.toString(resultSet);\n assertThat(actual, is(\"\"));\n } catch (SQLException e) {\n throw TestUtil.rethrow(e);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid joining() {\n val delimiter = TextUtils.delimiter(\".\");\n assertThatDelimiterEquals(delimiter.parse(null).join(null), new String[0]);\n assertThatDelimiterEquals(delimiter.parse(\"a.b\").join(null), \"a\", \"b\");\n assertThatDelimiterEquals(delimiter.parse(null).join(delimiter.parse(\"a.b\")), \"a\", \"b\");\n assertThatDelimiterEquals(delimiter.join(delimiter.parse(\"a.b\")), \"a\", \"b\");\n assertThatDelimiterEquals(delimiter.parse(\"a.b\").join(delimiter.parse(\"c.d\")), \"a\", \"b\", \"c\", \"d\");\n assertThatDelimiterEquals(delimiter.parse(\"a.b\").join(delimiter.parse(\"c\")).join(delimiter.parse(\"d\")), \"a\", \"b\", \"c\", \"d\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RoutesStopping;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldCreateClaimedOwner() {\n OwnerDTO expectedOwner = Owners.random();\n expectedOwner.claimed(true);\n expectedOwner = owners.createOwner(expectedOwner);\n OwnerDTO actual = owners.getOwner(expectedOwner.getKey());\n assertThat(actual).returns(expectedOwner.getClaimed(), OwnerDTO::getClaimed);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ContentAccessCertificate createContentAccessCert(Date expiration) {\n ContentAccessCertificate certificate = new ContentAccessCertificate();\n certificate.setKey(\"crt_key\");\n certificate.setSerial(new CertificateSerial(expiration));\n certificate.setCert(\"cert_1\");\n certificate.setContent(\"content_1\");\n return saveCert(certificate);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Producer createProducer() throws Exception {\n return target.createProducer();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@BeforeEach\npublic void setUp() throws Exception {\n super.setUp();\n executorService = Executors.newSingleThreadExecutor();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List getAnonymousCertsFromDB() {\n String query = \"select c from AnonymousContentAccessCertificate c\";\n return getEntityManager().createQuery(query, AnonymousContentAccessCertificate.class).getResultList();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public int getId() {\n return id;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ServiceStartupFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void setOrderType(String orderType) {\n this.orderType = orderType;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testDoneFromRoute() {\n // notify when exchange is done\n NotifyBuilder builder = new NotifyBuilder(context).fromRoute(\"foo\").whenDone(1);\n builder.create();\n template.sendBody(\"seda:foo\", \"Hello world!\");\n assertTrue(builder.matchesWaitTime());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doList(Exchange exchange, String namespaceName) {\n CustomResourceDefinitionContext context = getCRDContext(exchange.getIn());\n GenericKubernetesResourceList list = getEndpoint().getKubernetesClient().genericKubernetesResources(context).inNamespace(namespaceName).list();\n if (LOG.isDebugEnabled()) {\n LOG.debug(Serialization.asJson(list));\n }\n JsonArray customResourcesListItems;\n if (list.getItems() != null) {\n customResourcesListItems = new JsonArray(list.getItems());\n } else {\n customResourcesListItems = new JsonArray();\n }\n prepareOutboundMessage(exchange, customResourcesListItems);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void eksDescribeClusterTest() throws Exception {\n mock.expectedMessageCount(1);\n Exchange exchange = template.request(\"direct:describeCluster\", new Processor() {\n\n @Override\n public void process(Exchange exchange) {\n exchange.getIn().setHeader(ECS2Constants.OPERATION, ECS2Operations.describeCluster);\n exchange.getIn().setHeader(ECS2Constants.CLUSTER_NAME, \"Test\");\n }\n });\n MockEndpoint.assertIsSatisfied(context);\n DescribeClustersResponse resultGet = exchange.getIn().getBody(DescribeClustersResponse.class);\n assertEquals(\"Test\", resultGet.clusters().get(0).clusterName());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "Object getService();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Binds the bean to the repository (if possible).\n *

\n * Binding by id and type allows to bind multiple entries with the same id but with different type.\n *\n * If the bean is {@link CamelContextAware} then the registry will automatically inject the context if possible.\n *\n * @param id the id of the bean\n * @param type the type of the bean to associate the binding\n * @param bean the bean\n */\nvoid bind(String id, Class type, Object bean);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Binds the bean (via a supplier) to the repository (if possible).\n *

\n * Camel will cache the result from the supplier from first lookup (singleton scope). If you do not need cached then\n * use {@link #bindAsPrototype(String, Class, Supplier)} instead.\n *

\n * Binding by id and type allows to bind multiple entries with the same id but with different type.\n *\n * If the bean is {@link CamelContextAware} then the registry will automatically inject the context if possible.\n *\n * @param id the id of the bean\n * @param type the type of the bean to associate the binding\n * @param bean a supplier for the bean\n */\nvoid bind(String id, Class type, Supplier bean);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void propagateHeaders(KafkaConfiguration configuration, ConsumerRecord consumerRecord, Exchange exchange) {\n HeaderFilterStrategy headerFilterStrategy = configuration.getHeaderFilterStrategy();\n KafkaHeaderDeserializer headerDeserializer = configuration.getHeaderDeserializer();\n StreamSupport.stream(consumerRecord.headers().spliterator(), false).filter(header -> shouldBeFiltered(header, exchange, headerFilterStrategy)).forEach(header -> exchange.getIn().setHeader(header.key(), headerDeserializer.deserialize(header.key(), header.value())));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The {@link Class} of the objects returned by this query.\n */\nClass getResultType();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Set the security mode (Implicit/Explicit). true - Implicit Mode / False - Explicit Mode\n */\npublic void setImplicit(boolean implicit) {\n this.implicit = implicit;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onFailure(Exchange exchange) {\n // we do nothing here\n processRollback(exchange);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ParameterizedTest(name = \"{0}: {1} {2} \")\n@MethodSource(\"argumentsStreamProvider\")\nvoid should_return_group_description_from_class(Object obj, String groupTypeName, String elementTypeName) {\n // WHEN\n GroupTypeDescription description = getGroupTypeDescription(obj.getClass());\n // THEN\n then(description.getGroupTypeName()).isEqualTo(groupTypeName);\n then(description.getElementTypeName()).isEqualTo(elementTypeName);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testLoadProperties() {\n context.start();\n org.apache.camel.spi.PropertiesComponent pc = context.getPropertiesComponent();\n Properties prop = pc.loadProperties();\n assertNotNull(prop);\n assertEquals(21, prop.size());\n assertEquals(\"{{cool.b}}\", prop.getProperty(\"cool.a\"));\n assertEquals(\"10\", prop.getProperty(\"myQueueSize\"));\n assertEquals(\"true\", prop.getProperty(\"integration.ftpEnabled\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates a new {@link ShouldBeRecord}.\n *\n * @param actual the actual value in the failed assertion.\n * @return the created {@code ErrorMessageFactory}.\n */\npublic static ErrorMessageFactory shouldNotBeRecord(Class actual) {\n return new ShouldBeRecord(actual, false);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private MethodSpec defaultProviderMethod() {\n return MethodSpec.methodBuilder(\"defaultProvider\").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(className()).addStatement(\"return new $T()\", endpointRulesSpecUtils.providerDefaultImplName()).build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BitSet getSentToBitSet() {\n BitSet b = new BitSet(ensemble.size());\n for (int i = 0; i < sentReplicas.length(); i++) {\n if (sentReplicas.get(i)) {\n b.set(writeSet.get(i));\n }\n }\n return b;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads from a URL and checks the result.\n */\n@Disabled(\"[CALCITE-1789] Wikipedia format change breaks file adapter test\")\n@Test\n@RequiresNetwork\nvoid testUrlSelect() {\n final String sql = \"select \\\"State\\\", \\\"Statehood\\\" from \\\"States_as_of\\\"\\n\" + \"where \\\"State\\\" = 'California'\";\n sql(\"wiki\", sql).returns(\"State=California; Statehood=1850-09-09\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ExchangeAsyncProcessingStarted;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RouteAdded;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:listClusters\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=listClusters\").to(\"mock:result\");\n from(\"direct:listClustersPojo\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=listClusters&pojoRequest=true\").to(\"mock:result\");\n from(\"direct:createCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=createCluster\").to(\"mock:result\");\n from(\"direct:deleteCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=deleteCluster\").to(\"mock:result\");\n from(\"direct:describeCluster\").to(\"aws2-ecs://test?ecsClient=#amazonEcsClient&operation=describeCluster\").to(\"mock:result\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1054]\n * NPE caused by wrong code generation for Timestamp fields.\n */\n@Test\nvoid testFilterOnNullableTimestamp() throws Exception {\n Properties info = new Properties();\n info.put(\"model\", FileAdapterTests.jsonPath(\"bug\"));\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", info)) {\n final Statement statement = connection.createStatement();\n // date\n final String sql1 = \"select JOINEDAT from \\\"DATE\\\"\\n\" + \"where JOINEDAT < {d '2000-01-01'}\\n\" + \"or JOINEDAT >= {d '2017-01-01'}\";\n final ResultSet joinedAt = statement.executeQuery(sql1);\n assertThat(joinedAt.next(), is(true));\n assertThat(joinedAt.getDate(1), is(Date.valueOf(\"1996-08-03\")));\n // time\n final String sql2 = \"select JOINTIME from \\\"DATE\\\"\\n\" + \"where JOINTIME >= {t '07:00:00'}\\n\" + \"and JOINTIME < {t '08:00:00'}\";\n final ResultSet joinTime = statement.executeQuery(sql2);\n assertThat(joinTime.next(), is(true));\n assertThat(joinTime.getTime(1), is(Time.valueOf(\"07:15:56\")));\n // timestamp\n final String sql3 = \"select JOINTIMES,\\n\" + \" {fn timestampadd(SQL_TSI_DAY, 1, JOINTIMES)}\\n\" + \"from \\\"DATE\\\"\\n\" + \"where (JOINTIMES >= {ts '2003-01-01 00:00:00'}\\n\" + \"and JOINTIMES < {ts '2006-01-01 00:00:00'})\\n\" + \"or (JOINTIMES >= {ts '2003-01-01 00:00:00'}\\n\" + \"and JOINTIMES < {ts '2007-01-01 00:00:00'})\";\n final ResultSet joinTimes = statement.executeQuery(sql3);\n assertThat(joinTimes.next(), is(true));\n assertThat(joinTimes.getTimestamp(1), is(Timestamp.valueOf(\"2005-09-07 00:00:00\")));\n assertThat(joinTimes.getTimestamp(2), is(Timestamp.valueOf(\"2005-09-08 00:00:00\")));\n final String sql4 = \"select JOINTIMES, extract(year from JOINTIMES)\\n\" + \"from \\\"DATE\\\"\";\n final ResultSet joinTimes2 = statement.executeQuery(sql4);\n assertThat(joinTimes2.next(), is(true));\n assertThat(joinTimes2.getTimestamp(1), is(Timestamp.valueOf(\"1996-08-03 00:01:02\")));\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Read a json formatted Amazon S3 Event Notification from a UTF-8 string.\n * Will ignores all additional fields and missing fields will be set to null.\n *\n * @param event UTF-8 json of the notification.\n * @return S3EventNotification\n * @throws JsonParseException if json if malformed\n */\nS3EventNotification read(String event);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {\n return delegate.connect(remoteAddress, localAddress, promise);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void updateCorrelationId(String correlationId, String newCorrelationId, long requestTimeout) {\n log.trace(\"Updated provisional correlationId [{}] to expected correlationId [{}]\", correlationId, newCorrelationId);\n ReplyHandler handler = correlation.remove(correlationId);\n if (handler != null) {\n correlation.put(newCorrelationId, handler, requestTimeout);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Before\npublic void generalSetup() {\n searchFieldDao = ServiceProvider.getService(SearchFieldDao.class);\n assertThat(searchFieldDao, notNullValue());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "static Stream explainFormats() {\n return Stream.of(\"text\", \"dot\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected ConcreteIterableAssert invoke_api_method() {\n return assertions.hasSize(6);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void process(Exchange exchange) throws Exception {\n String operation = KubernetesHelper.extractOperation(getEndpoint(), exchange);\n String namespace;\n if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getNamespace())) {\n namespace = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);\n } else {\n namespace = getEndpoint().getKubernetesConfiguration().getNamespace();\n }\n if (ObjectHelper.isEmpty(namespace)) {\n throw new IllegalArgumentException(\"Custom Resource producer requires a namespace argument\");\n }\n switch(operation) {\n case KubernetesOperations.LIST_CUSTOMRESOURCES:\n doList(exchange, namespace);\n break;\n case KubernetesOperations.LIST_CUSTOMRESOURCES_BY_LABELS_OPERATION:\n doListByLabels(exchange, namespace);\n break;\n case KubernetesOperations.GET_CUSTOMRESOURCE:\n doGet(exchange, namespace);\n break;\n case KubernetesOperations.DELETE_CUSTOMRESOURCE:\n doDelete(exchange, namespace);\n break;\n case KubernetesOperations.CREATE_CUSTOMRESOURCE:\n doCreate(exchange, namespace);\n break;\n case KubernetesOperations.UPDATE_CUSTOMRESOURCE:\n doUpdate(exchange, namespace);\n break;\n default:\n throw new IllegalArgumentException(\"Unsupported operation \" + operation);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n from(\"direct:putObject\").marshal().gzipDeflater().to(\"aws2-s3://\" + name.get() + \"?autoCreateBucket=true\");\n from(\"direct:getObject\").to(\"aws2-s3://\" + name.get() + \"?autoCreateBucket=true&deleteAfterRead=false&includeBody=true\").unmarshal().gzipDeflater();\n from(\"aws2-s3://\" + name.get() + \"?autoCreateBucket=true&deleteAfterRead=false&includeBody=true&prefix=hello.txt.gz\").unmarshal().gzipDeflater().to(\"mock:poll\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "long getTimeTaken();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "int resume(int current, ByteBuf buffer, int offset, int len);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static CompletableFuture doSign(AsyncSignRequest request, Checksummer checksummer, V4RequestSigner requestSigner, V4PayloadSigner payloadSigner) {\n SdkHttpRequest.Builder requestBuilder = request.request().toBuilder();\n return checksummer.checksum(request.payload().orElse(null), requestBuilder).thenApply(payload -> {\n V4RequestSigningResult requestSigningResultFuture = requestSigner.sign(requestBuilder);\n return AsyncSignedRequest.builder().request(requestSigningResultFuture.getSignedRequest().build()).payload(payloadSigner.signAsync(payload, requestSigningResultFuture)).build();\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void compressedMessageRequestTest() throws Exception {\n AS2ClientManager clientManager = createDefaultClientManager();\n HttpCoreContext httpContext = clientManager.send(EDI_MESSAGE, REQUEST_URI, SUBJECT, FROM, AS2_NAME, AS2_NAME, AS2MessageStructure.PLAIN_COMPRESSED, ContentType.create(AS2MediaType.APPLICATION_EDIFACT, StandardCharsets.US_ASCII), null, null, null, null, AS2CompressionAlgorithm.ZLIB, DISPOSITION_NOTIFICATION_TO, SIGNED_RECEIPT_MIC_ALGORITHMS, null, null, \"file.txt\", null);\n HttpRequest request = httpContext.getRequest();\n assertEquals(METHOD, request.getMethod(), \"Unexpected method value\");\n assertEquals(REQUEST_URI, request.getUri().getPath(), \"Unexpected request URI value\");\n assertEquals(HttpVersion.HTTP_1_1, request.getVersion(), \"Unexpected HTTP version value\");\n assertEquals(SUBJECT, request.getFirstHeader(AS2Header.SUBJECT).getValue(), \"Unexpected subject value\");\n assertEquals(FROM, request.getFirstHeader(AS2Header.FROM).getValue(), \"Unexpected from value\");\n assertEquals(AS2_VERSION, request.getFirstHeader(AS2Header.AS2_VERSION).getValue(), \"Unexpected AS2 version value\");\n assertEquals(AS2_NAME, request.getFirstHeader(AS2Header.AS2_FROM).getValue(), \"Unexpected AS2 from value\");\n assertEquals(AS2_NAME, request.getFirstHeader(AS2Header.AS2_TO).getValue(), \"Unexpected AS2 to value\");\n assertTrue(request.getFirstHeader(AS2Header.MESSAGE_ID).getValue().endsWith(CLIENT_FQDN + \">\"), \"Unexpected message id value\");\n assertEquals(TARGET_HOST + \":\" + TARGET_PORT, request.getFirstHeader(AS2Header.TARGET_HOST).getValue(), \"Unexpected target host value\");\n assertEquals(USER_AGENT, request.getFirstHeader(AS2Header.USER_AGENT).getValue(), \"Unexpected user agent value\");\n assertNotNull(request.getFirstHeader(AS2Header.DATE), \"Date value missing\");\n assertNotNull(request.getFirstHeader(AS2Header.CONTENT_LENGTH), \"Content length value missing\");\n assertTrue(request.getFirstHeader(AS2Header.CONTENT_TYPE).getValue().startsWith(AS2MimeType.APPLICATION_PKCS7_MIME), \"Unexpected content type for message\");\n assertTrue(request instanceof ClassicHttpRequest, \"Request does not contain entity\");\n HttpEntity entity = ((ClassicHttpRequest) request).getEntity();\n assertNotNull(entity, \"Request does not contain entity\");\n assertTrue(entity instanceof ApplicationPkcs7MimeCompressedDataEntity, \"Unexpected request entity type\");\n ApplicationPkcs7MimeCompressedDataEntity compressedDataEntity = (ApplicationPkcs7MimeCompressedDataEntity) entity;\n assertTrue(compressedDataEntity.isMainBody(), \"Entity not set as main body of request\");\n // Validated compessed part.\n MimeEntity compressedEntity = compressedDataEntity.getCompressedEntity(new ZlibExpanderProvider());\n assertTrue(compressedEntity instanceof ApplicationEDIFACTEntity, \"Enveloped mime part incorrect type \");\n ApplicationEDIFACTEntity ediEntity = (ApplicationEDIFACTEntity) compressedEntity;\n assertTrue(ediEntity.getContentType().startsWith(AS2MediaType.APPLICATION_EDIFACT), \"Unexpected content type for compressed entity\");\n assertFalse(ediEntity.isMainBody(), \"Compressed entity set as main body of request\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Notify the publisher of new metric data. After this call returns, the\n * caller can safely discard the given {@code metricCollection} instance if it\n * no longer needs it. Implementations are strongly encouraged to complete\n * any further aggregation and publishing of metrics in an asynchronous manner to\n * avoid blocking the calling thread.\n *

\n * With the exception of a {@code null} {@code metricCollection}, all\n * invocations of this method must return normally. This\n * is to ensure that callers of the publisher can safely assume that even\n * in situations where an error happens during publishing that it will not\n * interrupt the calling thread.\n *\n * @param metricCollection The collection of metrics.\n * @throws IllegalArgumentException If {@code metricCollection} is {@code null}.\n */\nvoid publish(MetricCollection metricCollection);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads the DEPTS table from the CSV schema.\n */\n@Test\nvoid testCsvSalesDepts() {\n final String sql = \"select * from sales.depts\";\n sql(\"sales-csv\", sql).returns(\"DEPTNO=10; NAME=Sales\", \"DEPTNO=20; NAME=Marketing\", \"DEPTNO=30; NAME=Accounts\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private PublicationTemplate getCardTemplate() throws WhitePagesException {\n try {\n if (cardTemplate == null) {\n cardTemplate = PublicationTemplateManager.getInstance().getPublicationTemplate(getComponentId(), getParam(\"cardTemplate\"));\n }\n return cardTemplate;\n } catch (PublicationTemplateException e) {\n throw new WhitePagesException(e);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void main(String[] args) {\n ExampleUtils.showExampleFrame(new Display());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void setupExchangeMessage(Message message, ConsumerRecord consumerRecord) {\n message.setHeader(KafkaConstants.PARTITION, consumerRecord.partition());\n message.setHeader(KafkaConstants.TOPIC, consumerRecord.topic());\n message.setHeader(KafkaConstants.OFFSET, consumerRecord.offset());\n message.setHeader(KafkaConstants.HEADERS, consumerRecord.headers());\n message.setHeader(KafkaConstants.TIMESTAMP, consumerRecord.timestamp());\n message.setHeader(Exchange.MESSAGE_TIMESTAMP, consumerRecord.timestamp());\n if (consumerRecord.key() != null) {\n message.setHeader(KafkaConstants.KEY, consumerRecord.key());\n }\n LOG.debug(\"Setting up the exchange for message from partition {} and offset {}\", consumerRecord.partition(), consumerRecord.offset());\n message.setBody(consumerRecord.value());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected DeleteOptionImpl newObject(Handle> handle) {\n return new DeleteOptionImpl<>(handle);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Fetches this certificate's key as PEM-encoded string. If the key has not been set, this\n * method returns null.\n *\n * @return\n * the key for this certificate, or null if the key has not been set\n */\nString getKey();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected boolean check(final NotificationContext context) {\n final String formId = context.getContributionId();\n final String instanceId = context.getComponentId();\n try {\n final FormDetail form = FormsOnlineService.get().loadForm(new FormPK(formId, instanceId));\n context.put(FORM_KEY, form);\n return form.isPublished();\n } catch (FormsOnlineException e) {\n return false;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getStreamedResponse() {\n return streamedResponse;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() throws Exception {\n return new RouteBuilder() {\n\n @Override\n public void configure() throws Exception {\n from(\"hazelcast-seda:foo\").to(\"mock:result\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String validate0UpdateName(final String newName) {\n for (char prohibitedCharacter : \"&%$!\".toCharArray()) {\n if (newName.contains(\"\" + prohibitedCharacter)) {\n return \"Character '\" + prohibitedCharacter + \"' is not allowed.\";\n }\n }\n return null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "synchronized BookieId sendNextRead() {\n if (nextReplicaIndexToReadFrom >= getLedgerMetadata().getWriteQuorumSize()) {\n // we are done, the read has failed from all replicas, just fail the\n // read\n fail(firstError);\n return null;\n }\n // ToDo: pick replica with writable PCBC. ISSUE #1239\n // https://github.com/apache/bookkeeper/issues/1239\n int replica = nextReplicaIndexToReadFrom;\n int bookieIndex = writeSet.get(nextReplicaIndexToReadFrom);\n nextReplicaIndexToReadFrom++;\n try {\n BookieId to = ensemble.get(bookieIndex);\n sendReadTo(bookieIndex, to, this);\n sentToHosts.add(to);\n sentReplicas.set(replica);\n return to;\n } catch (InterruptedException ie) {\n LOG.error(\"Interrupted reading entry \" + this, ie);\n Thread.currentThread().interrupt();\n fail(BKException.Code.InterruptedException);\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@VisibleForTesting\nboolean contains(Endpoint endpoint) {\n lock.readLock().lock();\n try {\n return channels.containsKey(endpoint);\n } finally {\n lock.readLock().unlock();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:a\").threads(4).to(\"mock:input\").process(new Processor() {\n\n public void process(Exchange ex) {\n latch.countDown();\n }\n });\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Reads the DEPTS table from the JSON schema.\n */\n@Test\nvoid testJsonSalesDepts() {\n final String sql = \"select * from sales.depts\";\n sql(\"sales-json\", sql).returns(\"DEPTNO=10; NAME=Sales\", \"DEPTNO=20; NAME=Marketing\", \"DEPTNO=30; NAME=Accounts\").ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\n@Override\n@BeforeEach\npublic void setUp() throws Exception {\n super.setUp();\n repo = context.getRegistry().lookupByNameAndType(\"fileStore\", IdempotentRepository.class);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void process(Exchange exchange) {\n exchange.getIn().setHeader(ECS2Constants.OPERATION, ECS2Operations.listClusters);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic CompletableFuture asyncClose() {\n LOG.info(\"Shutting down the scheduler\");\n SchedulerUtils.shutdownScheduler(scheduler, 1, TimeUnit.SECONDS);\n LOG.info(\"Shut down the scheduler\");\n LOG.info(\"Closing the namespace\");\n namespace.close();\n LOG.info(\"Closed the namespace\");\n return FutureUtils.Void();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int[] getFieldLengths() {\n if (definition.getHeaders() != null) {\n int i = 0;\n int[] arr = new int[definition.getHeaders().size()];\n for (UniVocityHeader header : definition.getHeaders()) {\n String len = header.getLength();\n int num = Integer.parseInt(len);\n arr[i++] = num;\n }\n return arr;\n } else {\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isEnabled(String scheme) {\n return \"google-mail-stream\".equals(scheme);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_not_be_equal_to_Object_of_different_type() {\n assertThat(delta.equals(\"8\")).isFalse();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextResumeFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Prepares the model definitions of this builder.\n */\nvoid prepareModel(CamelContext context) throws Exception;", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "V value();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextStartupFailure;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Liste les fiches de l'annuaire\n *\n * @return la liste de toutes les fiches de l'annuaire (Collection de Card)\n */\npublic Collection getCards() throws WhitePagesException {\n return setUserRecords(getCardManager().getCards(getComponentId()));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder jsonGenerator(StructuredJsonGenerator jsonGenerator) {\n this.jsonGenerator = jsonGenerator;\n return this;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void process(Exchange exchange) {\n exchange.getIn().setHeader(ECS2Constants.OPERATION, ECS2Operations.createCluster);\n exchange.getIn().setHeader(ECS2Constants.CLUSTER_NAME, \"Test\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n context.addComponent(\"async\", new MyAsyncComponent());\n from(\"direct:start\").to(\"mock:before\").to(\"log:before\").process(new Processor() {\n\n public void process(Exchange exchange) {\n beforeThreadName = Thread.currentThread().getName();\n }\n }).recipientList(constant(\"async:hi:camel,direct:foo\"));\n from(\"direct:foo\").process(new Processor() {\n\n public void process(Exchange exchange) {\n afterThreadName = Thread.currentThread().getName();\n exchange.getMessage().setBody(\"Bye Camel\");\n }\n }).to(\"log:after\").to(\"mock:after\").to(\"mock:result\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String value() {\n return value;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testIdempotent() throws Exception {\n // send a file\n template.sendBodyAndHeader(fileUri(), \"Hello World\", Exchange.FILE_NAME, \"report.txt\");\n // consume the file the first time\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedMessageCount(1);\n assertMockEndpointsSatisfied();\n // reset mock and set new expectations\n mock.reset();\n mock.expectedMessageCount(0);\n // sleep to let the consumer try to poll the file\n mock.setResultMinimumWaitTime(50);\n // move file back\n File file = testFile(\"done/report.txt\").toFile();\n File renamed = testFile(\"report.txt\").toFile();\n file.renameTo(renamed);\n // should NOT consume the file again, let 2 secs pass to let the consumer try to consume it but it should not\n assertMockEndpointsSatisfied();\n String name = FileUtil.normalizePath(testFile(\"report.txt\").toAbsolutePath().toString());\n await().untilAsserted(() -> assertTrue(repo.contains(name), \"Should contain file: \" + name));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-898]\n * Type inference multiplying Java long by SQL INTEGER.\n */\n@Test\nvoid testSelectLongMultiplyInteger() {\n final String sql = \"select empno * 3 as e3\\n\" + \"from long_emps where empno = 100\";\n sql(\"bug\", sql).checking(resultSet -> {\n try {\n assertThat(resultSet.next(), is(true));\n Long o = (Long) resultSet.getObject(1);\n assertThat(o, is(300L));\n assertThat(resultSet.next(), is(false));\n } catch (SQLException e) {\n throw TestUtil.rethrow(e);\n }\n }).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * The route index in this batch (starts from 1)\n */\nint getIndex();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RouteStarted;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic EntitlementDTO translate(ModelTranslator translator, Entitlement source) {\n return source != null ? this.populate(translator, source, new EntitlementDTO()) : null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n // shutdown this test faster\n context.getShutdownStrategy().setTimeout(3);\n from(\"seda:start\").routeId(\"start\").delay(100).to(\"mock:result\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_create_Assert() {\n AbstractIntArrayAssert assertions = Assertions.assertThat(emptyArray());\n assertThat(assertions).isNotNull();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Destination createTemporaryDestination(Session session, boolean topic) throws JMSException {\n synchronized (refreshWanted) {\n if (queue == null || refreshWanted.get()) {\n refreshWanted.set(false);\n queue = session.createTemporaryQueue();\n setReplyTo(queue);\n if (log.isDebugEnabled()) {\n log.debug(\"Refreshed Temporary ReplyTo Queue. New queue: {}\", queue.getQueueName());\n }\n refreshWanted.notifyAll();\n }\n }\n return queue;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "static BeanAttributeGetter create(Class beanClass, Method getter) {\n Validate.isTrue(getter.getParameterCount() == 0, \"%s.%s has parameters, despite being named like a getter.\", beanClass, getter.getName());\n return LambdaToMethodBridgeBuilder.create(BeanAttributeGetter.class).lambdaMethodName(\"apply\").runtimeLambdaSignature(Object.class, Object.class).compileTimeLambdaSignature(getter.getReturnType(), beanClass).targetMethod(getter).build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {\n return delegate.writeAndFlush(msg, promise);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Use this option to disable default options when using secure data channel.\n *

\n * This allows you to be in full control what the execPbsz and execProt setting should be used.\n *

\n * Default is false\n *\n * @see #setExecPbsz(Long)\n * @see #setExecProt(String)\n */\npublic void setDisableSecureDataChannelDefaults(boolean disableSecureDataChannelDefaults) {\n this.disableSecureDataChannelDefaults = disableSecureDataChannelDefaults;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Converts an expression.\n *\n * @param rexBuilder Rex builder\n * @param groupCall Call to the group function, e.g. \"TUMBLE($2, 36000)\"\n * @param e Expression holding result of the group function, e.g. \"$0\"\n *\n * @return Expression for auxiliary function, e.g. \"$0 + 36000\" converts\n * the result of TUMBLE to the result of TUMBLE_END\n */\nRexNode convert(RexBuilder rexBuilder, RexNode groupCall, RexNode e);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {\n return delegate.connect(remoteAddress, promise);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testTwo() throws Exception {\n // set mock expectations\n getMockEndpoint(\"mock:a\").expectedMessageCount(2);\n getMockEndpoint(\"mock:b\").expectedMessageCount(2);\n // send a message\n template.sendBody(\"direct:start\", \"World\");\n template.sendBody(\"direct:start\", \"Camel\");\n // assert mocks\n MockEndpoint.assertIsSatisfied(context);\n Assertions.assertTrue(testDebugBreakpoint.isDebugAfterCalled());\n Assertions.assertTrue(testDebugBreakpoint.isDebugBeforeCalled());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic ChannelPipeline pipeline() {\n return delegate.pipeline();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() throws Exception {\n return new SpringRouteBuilder() {\n\n public void configure() throws Exception {\n // ignore failure if its something with Donkey\n onException(IllegalArgumentException.class).onWhen(exceptionMessage().contains(\"Donkey\")).handled(true);\n from(\"direct:okay\").// mark this route as transacted\n transacted().setBody(constant(\"Tiger in Action\")).bean(\"bookService\").setBody(constant(\"Elephant in Action\")).bean(\"bookService\").setBody(constant(\"Donkey in Action\")).bean(\"bookService\");\n from(\"direct:fail\").// and this route is not transacted\n setBody(constant(\"Tiger in Action\")).bean(\"bookService\").setBody(constant(\"Donkey in Action\")).bean(\"bookService\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testCollectionRemove() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedMinimumMessageCount(2);\n template.sendBodyAndHeader(String.format(\"nitrite://%s?collection=collection\", tempDb()), Document.createDocument(\"key1\", \"value1\"), NitriteConstants.OPERATION, new InsertOperation());\n template.sendBodyAndHeader(String.format(\"nitrite://%s?collection=collection\", tempDb()), null, NitriteConstants.OPERATION, new RemoveCollectionOperation(Filters.eq(\"key1\", \"value1\")));\n assertEquals(0, template.requestBody(\"direct:listAll\", null, List.class).size());\n mock.assertIsSatisfied();\n List sorted = sortByChangeTimestamp(mock.getExchanges());\n Exchange insert = sorted.get(0);\n Exchange remove = sorted.get(1);\n assertEquals(ChangeType.INSERT, insert.getMessage().getHeader(NitriteConstants.CHANGE_TYPE));\n assertEquals(ChangeType.REMOVE, remove.getMessage().getHeader(NitriteConstants.CHANGE_TYPE));\n assertNotNull(insert.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP));\n assertNotNull(remove.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Test case for\n * [CALCITE-1031]\n * In prepared statement, CsvScannableTable.scan is called twice. To see\n * the bug, place a breakpoint in CsvScannableTable.scan, and note that it is\n * called twice. It should only be called once.\n */\n@Test\nvoid testPrepared() throws SQLException {\n final Properties properties = new Properties();\n properties.setProperty(\"caseSensitive\", \"true\");\n try (Connection connection = DriverManager.getConnection(\"jdbc:calcite:\", properties)) {\n final CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);\n final Schema schema = FileSchemaFactory.INSTANCE.create(calciteConnection.getRootSchema(), null, ImmutableMap.of(\"directory\", FileAdapterTests.resourcePath(\"sales-csv\"), \"flavor\", \"scannable\"));\n calciteConnection.getRootSchema().add(\"TEST\", schema);\n final String sql = \"select * from \\\"TEST\\\".\\\"DEPTS\\\" where \\\"NAME\\\" = ?\";\n final PreparedStatement statement2 = calciteConnection.prepareStatement(sql);\n statement2.setString(1, \"Sales\");\n final ResultSet resultSet1 = statement2.executeQuery();\n Consumer expect = FileAdapterTests.expect(\"DEPTNO=10; NAME=Sales\");\n expect.accept(resultSet1);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldIgnoreAutoBindDisabled() {\n OwnerDTO owner = owners.createOwner(Owners.random());\n assertThat(owner.getAutobindDisabled()).isFalse();\n owner.autobindDisabled(null);\n owners.updateOwner(owner.getKey(), owner);\n OwnerDTO updatedOwner2 = owners.getOwner(owner.getKey());\n assertThat(updatedOwner2.getAutobindDisabled()).isFalse();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception {\n CMEndpoint endpoint = new CMEndpoint(uri, this);\n endpoint.setHost(remaining);\n setProperties(endpoint, parameters);\n // Validate configuration\n final Set> constraintViolations = getValidator().validate(endpoint.getConfiguration());\n if (!constraintViolations.isEmpty()) {\n final StringBuilder msg = new StringBuilder();\n for (final ConstraintViolation cv : constraintViolations) {\n msg.append(String.format(\"- Invalid value for %s: %s\", cv.getPropertyPath().toString(), cv.getMessage()));\n }\n throw new ResolveEndpointFailedException(uri, msg.toString());\n }\n return endpoint;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isEventStreaming(SdkHttpRequest request) {\n return \"application/vnd.amazon.eventstream\".equals(request.firstMatchingHeader(Header.CONTENT_TYPE).orElse(\"\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private IdentityCertificate createIdCert(Date expiration) {\n IdentityCertificate idCert = TestUtil.createIdCert(expiration);\n return saveCert(idCert);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void registerServerMethodInvokerProvider(Object serverMethodInvokerProviderBean) {\n for (Class anInterface : serverMethodInvokerProviderBean.getClass().getInterfaces()) {\n if (anInterface.getAnnotation(RpcService.class) == null) {\n continue;\n }\n for (Method method : anInterface.getDeclaredMethods()) {\n RpcMethod rpcMethod = method.getAnnotation(RpcMethod.class);\n if (rpcMethod == null) {\n continue;\n }\n ServerMethodInvoker serverMethodInvoker = new ServerMethodInvokerImpl(serverMethodInvokerProviderBean, method);\n nettyRemotingServer.registerMethodInvoker(serverMethodInvoker);\n log.debug(\"Register ServerMethodInvoker: {} to bean: {}\", serverMethodInvoker.getMethodIdentify(), serverMethodInvoker.getMethodProviderIdentify());\n }\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void test003_ShowStream() throws Exception {\n String bookie = BookKeeperClusterUtils.getAnyBookie();\n String output = DockerUtils.runCommand(docker, bookie, true, dlogCLI, \"tool\", \"show\", \"--uri\", dlogUri, \"--stream\", \"stream-99\", \"-f\");\n assertTrue(output.contains(\"Log stream-99: has no records\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid logicalTypeNameAnnotationPickedUpOnClass() {\n @Named(\"CUS\")\n @DomainObject\n class Customer {\n }\n assertThat(LogicalType.infer(Customer.class).getLogicalTypeName(), is(\"CUS\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void testAggregateProcessorTwoTimeoutExpressionRestart() throws Exception {\n MockEndpoint mock = getMockEndpoint(\"mock:result\");\n mock.expectedBodiesReceived(\"C+D\", \"A+B\");\n mock.expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, \"timeout\");\n AsyncProcessor done = new SendProcessor(context.getEndpoint(\"mock:result\"));\n Expression corr = header(\"id\");\n AggregationStrategy as = new BodyInAggregatingStrategy();\n AggregateProcessor ap = new AggregateProcessor(context, done, corr, as, executorService, true);\n // start with a high timeout so no completes before we stop\n ap.setCompletionTimeoutExpression(header(\"myTimeout\"));\n ap.setCompletionTimeoutCheckerInterval(10);\n ap.start();\n Exchange e1 = new DefaultExchange(context);\n e1.getIn().setBody(\"A\");\n e1.getIn().setHeader(\"id\", 123);\n e1.getIn().setHeader(\"myTimeout\", 300);\n Exchange e2 = new DefaultExchange(context);\n e2.getIn().setBody(\"B\");\n e2.getIn().setHeader(\"id\", 123);\n e2.getIn().setHeader(\"myTimeout\", 300);\n Exchange e3 = new DefaultExchange(context);\n e3.getIn().setBody(\"C\");\n e3.getIn().setHeader(\"id\", 456);\n e3.getIn().setHeader(\"myTimeout\", 250);\n Exchange e4 = new DefaultExchange(context);\n e4.getIn().setBody(\"D\");\n e4.getIn().setHeader(\"id\", 456);\n e4.getIn().setHeader(\"myTimeout\", 250);\n ap.process(e1);\n ap.process(e2);\n ap.process(e3);\n ap.process(e4);\n // shutdown before the 1/4 sec timeout occurs\n // however we use stop instead of shutdown as shutdown will clear the in\n // memory aggregation repository,\n ap.stop();\n // should be no completed\n assertEquals(0, mock.getReceivedCounter());\n // start aggregator again\n ap.start();\n // the aggregator should restore the timeout condition and trigger\n // timeout\n assertMockEndpointsSatisfied();\n assertEquals(2, mock.getReceivedCounter());\n ap.shutdown();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SignedRequest sign(SignRequest request) {\n Checksummer checksummer = checksummer(request, null);\n V4Properties v4Properties = v4Properties(request);\n V4RequestSigner v4RequestSigner = v4RequestSigner(request, v4Properties);\n V4PayloadSigner payloadSigner = v4PayloadSigner(request, v4Properties);\n return doSign(request, checksummer, v4RequestSigner, payloadSigner);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.CamelContextStarting;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic ConsumerDTO translate(ModelTranslator translator, Consumer source) {\n return source != null ? this.populate(translator, source, new ConsumerDTO()) : null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Class getOptionType(String name, boolean ignoreCase) {\n switch(ignoreCase ? name.toLowerCase() : name) {\n case \"apiname\":\n case \"apiName\":\n return org.apache.camel.component.twilio.internal.TwilioApiName.class;\n case \"methodname\":\n case \"methodName\":\n return java.lang.String.class;\n case \"pathaccountsid\":\n case \"pathAccountSid\":\n return java.lang.String.class;\n default:\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "// START SNIPPET: e2\n@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n @Override\n public void configure() {\n // this is the route we want to debug\n from(\"direct:start\").to(\"mock:a\").transform(body().prepend(\"Hello \")).to(\"mock:b\");\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void stop() {\n applicationContext.stop();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void configure() {\n from(\"direct:forceCompletionTrue\").routeId(\"foo\").aggregate(header(\"id\"), new BodyInAggregatingStrategy()).forceCompletionOnStop().completionSize(10).delay(100).process(\"myCompletionProcessor\");\n from(\"direct:forceCompletionFalse\").routeId(\"bar\").aggregate(header(\"id\"), new BodyInAggregatingStrategy()).completionSize(10).delay(100).process(\"myCompletionProcessor\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Component createComponent(final String id, final ScalarModel scalarModel) {\n return new BooleanPanel(id, scalarModel);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid testPushDownProject() {\n final String sql = \"explain plan for select * from EMPS\";\n final String expected = \"PLAN=CsvTableScan(table=[[SALES, EMPS]], \" + \"fields=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])\\n\";\n sql(\"smart\", sql).returns(expected).ok();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return ToString.builder(\"IamAction\").add(\"value\", value).build();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Close a storage container.\n */\n@Override\nvoid close();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.ExchangeCreated;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected RouteBuilder createRouteBuilder() {\n return new RouteBuilder() {\n\n public void configure() {\n errorHandler(noErrorHandler());\n Processor serviceProc = exchange -> {\n // get the request URL and copy it to the request body\n String uri = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);\n exchange.getMessage().setBody(uri);\n };\n from(\"netty-http:http://localhost:\" + port2 + \"/test/hello\").to(\"http://localhost:\" + port1 + \"?throwExceptionOnFailure=false&bridgeEndpoint=true\");\n from(\"netty-http:http://localhost:\" + port1 + \"?matchOnUriPrefix=true\").process(serviceProc);\n // check the from request\n from(\"netty-http:http://localhost:\" + port2 + \"/form?bridgeEndpoint=true\").process(exchange -> {\n // just take out the message body and send it back\n Message in = exchange.getIn();\n String request = in.getBody(String.class);\n exchange.getMessage().setBody(request);\n });\n }\n };\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SneakyThrows\npublic HttpResponse get(String url, Map headers, Map params) {\n String requestUrl = String.format(\"%s%s%s\", Constants.DOLPHINSCHEDULER_API_URL, url, getParams(params));\n Headers headersBuilder = new Headers.Builder().build();\n if (headers != null) {\n headersBuilder = Headers.of(headers);\n }\n log.info(\"GET request to {}, Headers: {}\", requestUrl, headersBuilder);\n Request request = new Request.Builder().url(requestUrl).headers(headersBuilder).get().build();\n Response response = this.httpClient.newCall(request).execute();\n HttpResponseBody responseData = null;\n int responseCode = response.code();\n if (response.body() != null) {\n responseData = JSONUtils.parseObject(response.body().string(), HttpResponseBody.class);\n }\n response.close();\n HttpResponse httpResponse = new HttpResponse(responseCode, responseData);\n log.info(\"GET response: {}\", httpResponse);\n return httpResponse;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doGet(Exchange exchange, String namespaceName) {\n String customResourceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE_NAME, String.class);\n if (ObjectHelper.isEmpty(customResourceName)) {\n throw new IllegalArgumentException(\"Get a specific Deployment require specify a Deployment name\");\n }\n JsonObject customResourceJSON = new JsonObject();\n try {\n customResourceJSON = new JsonObject(getEndpoint().getKubernetesClient().genericKubernetesResources(getCRDContext(exchange.getIn())).inNamespace(namespaceName).withName(customResourceName).require().get());\n } catch (KubernetesClientException e) {\n if (e.getCode() == 404) {\n LOG.info(\"Custom resource instance not found\", e);\n } else {\n throw e;\n }\n }\n prepareOutboundMessage(exchange, customResourceJSON);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected AbstractApplicationContext createApplicationContext() {\n return new ClassPathXmlApplicationContext(\"org/apache/camel/component/ehcache/EhcacheSpringConfigurationTest.xml\");\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Object getSource() {\n return getRoute();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected DeleteOptionBuilderImpl newObject(Handle> handle) {\n return new DeleteOptionBuilderImpl<>(handle, deleteOptionRecycler);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic EventExecutor executor() {\n return delegate.executor();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void shouldExecuteStoredProcedure() throws InterruptedException {\n MockEndpoint mock = getMockEndpoint(\"mock:query\");\n mock.expectedMessageCount(1);\n Map headers = new HashMap<>();\n headers.put(\"num1\", 1);\n headers.put(\"num2\", 2);\n template.requestBodyAndHeaders(\"direct:query\", null, headers);\n MockEndpoint.assertIsSatisfied(context);\n Exchange exchange = mock.getExchanges().get(0);\n assertEquals(Integer.valueOf(-1), exchange.getIn().getBody(Map.class).get(\"resultofsub\"));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean addStorageServer(Endpoint endpoint, StorageServerChannel channel) {\n lock.readLock().lock();\n try {\n if (closed) {\n log.warn(\"Skip adding channel {} of range server {} since the channel manager is already closed\", channel, endpoint);\n channel.close();\n return false;\n }\n StorageServerChannel oldChannel = channels.putIfAbsent(endpoint, channel);\n if (null != oldChannel) {\n if (log.isDebugEnabled()) {\n log.debug(\"KeyRange server ({}) already existed in the channel manager.\", endpoint);\n }\n channel.close();\n return false;\n } else {\n log.info(\"Added range server ({}) into the channel manager.\", endpoint);\n return true;\n }\n } finally {\n lock.readLock().unlock();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean isAdmin() {\n return \"admin\".equals(getHighestSilverpeasUserRole().getName());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void ensureURICreated(URI uri) throws Exception {\n ensureURICreated(zkc, uri);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "// -- HELPER\nprivate static void assertThatDelimiterEquals(final TextUtils.StringDelimiter delimiter, final String... parts) {\n assertEquals(Can.ofArray(parts), delimiter.stream().collect(Can.toCan()));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.StepCompleted;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nsynchronized BookieId maybeSendSpeculativeRead(BitSet heardFrom) {\n if (nextReplicaIndexToReadFrom >= getLedgerMetadata().getWriteQuorumSize()) {\n return null;\n }\n BitSet sentTo = getSentToBitSet();\n sentTo.and(heardFrom);\n // only send another read if we have had no successful response at all\n // (even for other entries) from any of the other bookies we have sent the\n // request to\n if (sentTo.cardinality() == 0) {\n clientCtx.getClientStats().getSpeculativeReadCounter().inc();\n return sendNextRead();\n } else {\n return null;\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toString() {\n return variableName;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\npublic void emptyAttributeValuesCannotBeConverted() {\n assertThatThrownBy(() -> EnhancedAttributeValue.fromAttributeValue(AttributeValue.builder().build())).isInstanceOf(IllegalStateException.class);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\ndefault Type getType() {\n return Type.RoutesStarted;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@AfterAll\npublic static void tearDownAfterClass() {\n if (defaultTimeZone != null) {\n TimeZone.setDefault(defaultTimeZone);\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected ConcreteIterableAssert invoke_api_method() {\n return assertions.doesNotHaveDuplicates();\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return\n */\nboolean isSuccess();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nsynchronized void logErrorAndReattemptRead(int bookieIndex, BookieId host, String errMsg, int rc) {\n super.logErrorAndReattemptRead(bookieIndex, host, errMsg, rc);\n int replica = writeSet.indexOf(bookieIndex);\n if (replica == NOT_FOUND) {\n LOG.error(\"Received error from a host which is not in the ensemble {} {}.\", host, ensemble);\n return;\n }\n erroredReplicas.set(replica);\n if (isRecoveryRead && (numBookiesMissingEntry >= requiredBookiesMissingEntryForRecovery)) {\n /* For recovery, report NoSuchEntry as soon as wQ-aQ+1 bookies report that they do not\n * have the entry */\n fail(BKException.Code.NoSuchEntryException);\n return;\n }\n if (!readsOutstanding()) {\n sendNextRead();\n }\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\nvoid should_fail_if_actual_is_not_in_given_hour() {\n // GIVEN\n LocalDateTime actual = LocalDateTime.of(2021, 12, 31, 23, 59, 59);\n int expectedHour = 22;\n // WHEN\n AssertionError assertionError = expectAssertionError(() -> assertThat(actual).hasHour(expectedHour));\n // THEN\n then(assertionError).hasMessage(shouldHaveDateField(actual, \"hour\", expectedHour).create());\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "CompletableFuture putIfAbsent(K key, V value);", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public short getCol() {\n return col;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "static ThrowingCallable raisingException(final String reason) {\n return codeThrowing(new Exception(reason));\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Consumer createConsumer(Date idExpiration, Date caExpiration) {\n Consumer consumer = new Consumer().setName(\"c1\").setUsername(\"u1\").setOwner(owner).setType(ct).setIdCert(createIdCert(idExpiration)).setContentAccessCert(createContentAccessCert(caExpiration));\n return consumerCurator.create(consumer);\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * A human-readable representation of this query and its values.\n */\nString getDescription();", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Map> getPdcPositions(int cardId) throws PdcException {\n Map> result = new HashMap<>();\n List listOfPositions = getPdcManager().getPositions(cardId, getComponentId());\n if (listOfPositions != null && !listOfPositions.isEmpty()) {\n for (ClassifyPosition position : listOfPositions) {\n for (ClassifyValue value : position.getValues()) {\n List path = value.getFullPath();\n setPdcPosition(value, path, result);\n }\n }\n }\n return result;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "@GET\npublic Response listVipCustomers() {\n return null;\n}", "smellKey": "0", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Serializes row to output for vectorized path.\n * @param byteStream Output to reuse. Can be null, in that case a new one would be created.\n */\npublic static Output serializeVector(Output byteStream, VectorHashKeyWrapperBase kw, VectorExpressionWriter[] keyOutputWriters, VectorHashKeyWrapperBatch keyWrapperBatch, boolean[] nulls, boolean[] sortableSortOrders, byte[] nullMarkers, byte[] notNullMarkers) throws HiveException, SerDeException {\n Object[] fieldData = new Object[keyOutputWriters.length];\n List fieldOis = new ArrayList();\n for (int i = 0; i < keyOutputWriters.length; ++i) {\n VectorExpressionWriter writer = keyOutputWriters[i];\n fieldOis.add(writer.getObjectInspector());\n // This is rather convoluted... to simplify for perf, we could call getRawKeyValue\n // instead of writable, and serialize based on Java type as opposed to OI.\n fieldData[i] = keyWrapperBatch.getWritableKeyValue(kw, i, writer);\n if (nulls != null) {\n nulls[i] = (fieldData[i] == null);\n }\n }\n return serializeRow(byteStream, fieldData, fieldOis, sortableSortOrders, nullMarkers, notNullMarkers);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * \tGet Tax ID - converts parameters to call Get Tax.\n *
{@code\n *       M_Product_ID/C_Charge_ID    ->\tC_TaxCategory_ID\n *       billDate, shipDate          ->\tbillDate, shipDate\n *       AD_Org_ID                   ->\tbillFromC_Location_ID\n *       M_Warehouse_ID              ->\tshipFromC_Location_ID\n *       billC_BPartner_Location_ID  ->\tbillToC_Location_ID\n *       shipC_BPartner_Location_ID  ->\tshipToC_Location_ID\n *\n *   if IsSOTrx is false, bill and ship are reversed\n *   }
\n * \t@param ctx\tcontext\n * \t@param M_Product_ID product\n * \t@param C_Charge_ID product\n * \t@param billDate invoice date\n * \t@param shipDate ship date (ignored)\n * \t@param AD_Org_ID org\n * \t@param M_Warehouse_ID warehouse (ignored)\n * \t@param billC_BPartner_Location_ID invoice location\n * \t@param shipC_BPartner_Location_ID ship location (ignored)\n * \t@param IsSOTrx is a sales trx\n * @param deliveryViaRule if Delivery Via Rule is PickUp, use Warehouse Location instead of Billing Location as Tax Location to\n * @param trxName\n * \t@return C_Tax_ID\n * @throws TaxCriteriaNotFoundException if a criteria was not found\n */\npublic static int get(Properties ctx, int M_Product_ID, int C_Charge_ID, Timestamp billDate, Timestamp shipDate, int AD_Org_ID, int M_Warehouse_ID, int billC_BPartner_Location_ID, int shipC_BPartner_Location_ID, boolean IsSOTrx, String deliveryViaRule, String trxName) {\n return get(ctx, M_Product_ID, C_Charge_ID, billDate, shipDate, AD_Org_ID, M_Warehouse_ID, billC_BPartner_Location_ID, shipC_BPartner_Location_ID, -1, IsSOTrx, deliveryViaRule, trxName);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public EnqueueBean run(String user, Map userArgs, String execute, String srcFile, List defines, List hiveArgs, String otherFiles, String statusdir, String callback, String completedUrl, boolean enablelog, Boolean enableJobReconnect) throws NotAuthorizedException, BadParam, BusyException, QueueException, ExecuteException, IOException, InterruptedException, TooManyRequestsException {\n runAs = user;\n List args = makeArgs(user, execute, srcFile, defines, hiveArgs, otherFiles, statusdir, completedUrl, enablelog, enableJobReconnect);\n return enqueueController(user, userArgs, callback, args);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static MockTable create(MockCatalogReader catalogReader, MockSchema schema, String name, boolean stream, double rowCount, ColumnResolver resolver, InitializerExpressionFactory initializerExpressionFactory, boolean temporal, Double maxRowCount){\r\n MockTable table = new MockTable(catalogReader, schema.getCatalogName(), schema.name, name, stream, temporal, rowCount, resolver, initializerExpressionFactory, maxRowCount);\r\n schema.addTable(name);\r\n return table;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void displayPublications(List allPubs, boolean sortAllowed, boolean linksAllowed, boolean seeAlso, boolean toSearch, KmeliaSessionController kmeliaScc, String profile, GraphicElementFactory gef, MultiSilverpeasBundle resources, List selectedIds, String pubIdToHighlight, Writer out, boolean linkAttachment) throws IOException{\r\n String publicationSrc = resources.getIcon(\"kmelia.publication\");\r\n SettingBundle publicationSettings = ResourceLocator.getSettingBundle(\"org.silverpeas.publication.publicationSettings\");\r\n boolean showNoPublisMessage = resources.getSetting(\"showNoPublisMessage\", true);\r\n boolean targetValidationEnabled = kmeliaScc.isTargetValidationEnable() || kmeliaScc.isTargetMultiValidationEnable();\r\n String language = kmeliaScc.getCurrentLanguage();\r\n String currentUserId = kmeliaScc.getUserDetail().getId();\r\n String currentTopicId = kmeliaScc.getCurrentFolderId();\r\n boolean specificTemplateUsed = kmeliaScc.isCustomPublicationTemplateUsed();\r\n PublicationFragmentSettings fragmentSettings = new PublicationFragmentSettings();\r\n fragmentSettings.displayLinks = URLUtil.displayUniversalLinks();\r\n fragmentSettings.showImportance = kmeliaScc.isFieldImportanceVisible();\r\n fragmentSettings.fileStorageShowExtraInfoPub = resources.getSetting(\"fileStorageShowExtraInfoPub\", false);\r\n fragmentSettings.showTopicPathNameinSearchResult = resources.getSetting(\"showTopicPathNameinSearchResult\", true);\r\n fragmentSettings.toSearch = toSearch;\r\n fragmentSettings.rateable = kmeliaScc.isPublicationRatingAllowed();\r\n int nbPubsPerPage = kmeliaScc.getNbPublicationsPerPage();\r\n int firstDisplayedItemIndex = kmeliaScc.getIndexOfFirstPubToDisplay();\r\n int nbPubs = allPubs.size();\r\n Board board = gef.getBoard();\r\n Pagination pagination = gef.getPagination(nbPubs, nbPubsPerPage, firstDisplayedItemIndex);\r\n List pubs = allPubs.subList(pagination.getFirstItemIndex(), pagination.getLastItemIndex());\r\n out.write(\"
\");\r\n if (!pubs.isEmpty()) {\r\n out.write(board.printBefore());\r\n displayPublicationsListHeader(allPubs, sortAllowed, pagination, resources, kmeliaScc, out);\r\n out.write(\"
    \");\r\n for (KmeliaPublication aPub : pubs) {\r\n PublicationDetail pub = aPub.getDetail();\r\n User currentUser = aPub.getCreator();\r\n String pubColor = \"\";\r\n String pubState = null;\r\n String highlightClass = \"\";\r\n if (StringUtil.isDefined(pubIdToHighlight) && pubIdToHighlight.equals(pub.getPK().getId())) {\r\n highlightClass = \"highlight\";\r\n }\r\n if (pub.getStatus() != null && pub.isValid()) {\r\n if (pub.haveGotClone() && CLONE_STATUS.equals(pub.getCloneStatus()) && !USER.isInRole(profile)) {\r\n pubColor = \"blue\";\r\n pubState = resources.getString(\"kmelia.UpdateInProgress\");\r\n } else if (DRAFT_STATUS.equals(pub.getCloneStatus())) {\r\n if (currentUserId.equals(currentUser.getId())) {\r\n pubColor = \"gray\";\r\n pubState = resources.getString(\"PubStateDraft\");\r\n }\r\n } else if (TO_VALIDATE_STATUS.equals(pub.getCloneStatus())) {\r\n if (ADMIN.isInRole(profile) || PUBLISHER.isInRole(profile) || currentUserId.equals(currentUser.getId())) {\r\n pubColor = \"red\";\r\n pubState = resources.getString(\"kmelia.PubStateToValidate\");\r\n if (targetValidationEnabled) {\r\n ValidatorsList validatorsList = aPub.getValidators();\r\n pubState = getTargetedValidationInfo(validatorsList, resources);\r\n }\r\n }\r\n } else {\r\n if (pub.isNotYetVisible()) {\r\n pubState = resources.getString(\"kmelia.VisibleFrom\") + \" \" + resources.getOutputDateAndHour(pub.getBeginDateAndHour());\r\n } else if (pub.isNoMoreVisible()) {\r\n pubState = resources.getString(\"kmelia.VisibleTo\") + \" \" + resources.getOutputDateAndHour(pub.getEndDateAndHour());\r\n }\r\n if (!pub.isVisible()) {\r\n pubColor = \"gray\";\r\n }\r\n }\r\n } else {\r\n boolean hasModificationAccess = ADMIN.isInRole(profile) || PUBLISHER.isInRole(profile) || pub.isPublicationEditor(currentUserId) || (!USER.isInRole(profile) && kmeliaScc.isCoWritingEnable());\r\n if (pub.getStatus() != null && pub.isDraft()) {\r\n if (pub.isPublicationEditor(currentUserId) || ((kmeliaScc.isCoWritingEnable() && kmeliaScc.isDraftVisibleWithCoWriting()) && !USER.isInRole(profile))) {\r\n pubColor = \"gray\";\r\n pubState = resources.getString(\"PubStateDraft\");\r\n }\r\n } else if (pub.getStatus() != null && pub.isRefused()) {\r\n if (ADMIN.isInRole(profile) || PUBLISHER.isInRole(profile) || (WRITER.isInRole(profile) && (pub.isPublicationEditor(currentUserId) || kmeliaScc.isCoWritingEnable()))) {\r\n pubColor = \"red\";\r\n pubState = resources.getString(\"PublicationRefused\");\r\n }\r\n } else if (hasModificationAccess) {\r\n pubColor = \"red\";\r\n if (pub.isRefused()) {\r\n pubState = resources.getString(\"kmelia.PubStateUnvalidate\");\r\n } else {\r\n pubState = resources.getString(\"kmelia.PubStateToValidate\");\r\n if (targetValidationEnabled) {\r\n ValidatorsList validatorsList = aPub.getValidators();\r\n pubState = getTargetedValidationInfo(validatorsList, resources);\r\n }\r\n }\r\n }\r\n }\r\n if (pub.isAlias()) {\r\n pubState = resources.getString(\"kmelia.Shortcut\");\r\n }\r\n String cssClasses = \"important\" + pub.getImportance();\r\n if (pub.isNew()) {\r\n cssClasses += \" new-contribution\";\r\n }\r\n if (toSearch) {\r\n if (aPub.isRead()) {\r\n cssClasses += \" read\";\r\n } else {\r\n cssClasses += \" unread\";\r\n }\r\n }\r\n out.write(\"
  • \");\r\n out.write(\"
    \");\r\n if (!kmeliaScc.getUserDetail().isAnonymous() && !kmeliaScc.isKmaxMode()) {\r\n String checked = \"\";\r\n if (selectedIds != null && selectedIds.contains(pub.getPK())) {\r\n checked = \"checked=\\\"checked\\\"\";\r\n }\r\n out.write(\"\");\r\n out.write(\"\");\r\n out.write(END_SPAN);\r\n }\r\n if (!seeAlso) {\r\n Thumbnail thumbnail = pub.getThumbnail();\r\n if (thumbnail != null && Boolean.valueOf(resources.getSetting(\"isVignetteVisible\"))) {\r\n out.write(\"\");\r\n displayThumbnail(pub, kmeliaScc, publicationSettings, out);\r\n out.write(END_SPAN);\r\n }\r\n }\r\n out.write(END_DIV);\r\n fragmentSettings.pubColor = pubColor;\r\n fragmentSettings.highlightClass = highlightClass;\r\n fragmentSettings.pubState = pubState;\r\n fragmentSettings.linksAllowed = linksAllowed;\r\n fragmentSettings.seeAlso = seeAlso;\r\n fragmentSettings.linkAttachment = linkAttachment;\r\n out.write(\"
    \");\r\n displayFragmentOfPublication(specificTemplateUsed, aPub, fragmentSettings, language, currentUserId, currentTopicId, kmeliaScc, resources, out);\r\n out.write(END_DIV);\r\n out.write(getPutIntoBasketSelectionHtmlSnippet(String.format(\"putPublicationInBasket('%s')\", pub.getIdentifier().asString()), language));\r\n out.write(\"
  • \");\r\n }\r\n out.write(\"
\");\r\n out.write(\"
\");\r\n out.write(pagination.printIndex(\"doPagination\", true));\r\n out.write(END_DIV);\r\n displayFilePreviewJavascript(language, out);\r\n displayFileViewJavascript(language, out);\r\n out.write(board.printAfter());\r\n } else if (showNoPublisMessage) {\r\n String noPublications = kmeliaScc.getString(\"PubAucune\");\r\n if (toSearch) {\r\n noPublications = kmeliaScc.getString(\"NoPubFound\");\r\n }\r\n out.write(\"
\");\r\n out.write(\"
\");\r\n out.write(\"\" + resources.getString(\"GML.publications\") + \"
\");\r\n out.write(\"

\" + noPublications + \"

\");\r\n out.write(END_DIV);\r\n }\r\n out.write(\"\");\r\n out.write(scriptContent(\"sp.selection.newCheckboxMonitor('form[name=publicationsForm] input[name=C1]')\" + \".addEventListener('change', function(){\" + \"if(typeof showPublicationCheckedBoxes === 'function') {showPublicationCheckedBoxes();}\" + \"}, 'displayPublication');\").toString());\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query9Def query(String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name, Class type6, String arg6name, Class type7, String arg7name, Class type8, String arg8name, Class type9, String arg9name){\r\n return new Query9DefImpl<>(VIEW_BUILDER, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name, type6, arg6name, type7, arg7name, type8, arg8name, type9, arg9name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "VpcOffering createVpcOffering(String name, String displayText, List supportedServices, Map> serviceProviders, Map serviceCapabilitystList, NetUtils.InternetProtocol internetProtocol, Long serviceOfferingId, Boolean forNsx, NetworkOffering.NetworkMode networkMode, List domainIds, List zoneIds, VpcOffering.State state, NetworkOffering.RoutingMode routingMode, boolean specifyAsNumber);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer, boolean inline) {\n if (create) {\n return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId);\n } else {\n return updateStatsEntry(accountId, zoneId, networkId, publicIp, hostId, answer, inline);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Start rolling maintenance for a single host\n * @return tuple: (FAIL, SKIP, DETAILS), where:\n * - FAIL: True if rolling maintenance must fail\n * - SKIP: True if host must be skipped\n * - DETAILS: Information retrieved by the host\n */\nprivate Ternary startRollingMaintenanceHostInCluster(Cluster cluster, Host host, int timeout, String payload, Boolean forced, Map hostsToAvoidMaintenance, List hostsUpdated, List hostsSkipped) throws InterruptedException, AgentUnavailableException {\n Ternary result;\n if (!isMaintenanceScriptDefinedOnHost(host, hostsSkipped)) {\n String msg = \"There is no maintenance script on the host\";\n hostsSkipped.add(new HostSkipped(host, msg));\n return new Ternary<>(false, true, msg);\n }\n result = performPreMaintenanceStageOnHost(host, timeout, payload, forced, hostsToAvoidMaintenance, hostsSkipped);\n if (result.first() || result.second()) {\n return result;\n }\n if (isMaintenanceStageAvoided(host, hostsToAvoidMaintenance, hostsSkipped)) {\n return new Ternary<>(false, true, \"Maintenance stage must be avoided\");\n }\n logger.debug(\"Updating capacity before re-checking capacity\");\n alertManager.recalculateCapacity();\n result = reCheckCapacityBeforeMaintenanceOnHost(cluster, host, forced, hostsSkipped);\n if (result.first() || result.second()) {\n return result;\n }\n Date startTime = new Date();\n putHostIntoMaintenance(host);\n result = performMaintenanceStageOnHost(host, timeout, payload, forced, hostsToAvoidMaintenance, hostsSkipped);\n if (result.first() || result.second()) {\n cancelHostMaintenance(host);\n return result;\n }\n cancelHostMaintenance(host);\n Date endTime = new Date();\n HostUpdated hostUpdated = new HostUpdated(host, startTime, endTime, result.third());\n hostsUpdated.add(hostUpdated);\n result = performPostMaintenanceStageOnHost(host, timeout, payload, forced, hostsToAvoidMaintenance, hostsSkipped);\n if (result.first() || result.second()) {\n return result;\n }\n return new Ternary<>(false, false, \"Completed rolling maintenance on host \" + host.getUuid());\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "DiskProfile allocateRawVolume(Type type, String name, DiskOffering offering, Long size, Long minIops, Long maxIops, VirtualMachine vm, VirtualMachineTemplate template, Account owner, Long deviceId);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static ClientData instance(final String accountNo, final EnumOptionData status, final CodeValueData subStatus, final Long officeId, final String officeName, final Long transferToOfficeId, final String transferToOfficeName, final Long id, final String firstname, final String middlename, final String lastname, final String fullname, final String displayName, final ExternalId externalId, final String mobileNo, final String emailAddress, final LocalDate dateOfBirth, final CodeValueData gender, final LocalDate activationDate, final Long imageId, final Long staffId, final String staffName, final ClientTimelineData timeline, final Long savingsProductId, final String savingsProductName, final Long savingsAccountId, final CodeValueData clientType, final CodeValueData clientClassification, final EnumOptionData legalForm, final ClientNonPersonData clientNonPerson, final Boolean isStaff) {\n final Collection allowedOffices = null;\n final Collection groups = null;\n final Collection staffOptions = null;\n final Collection closureReasons = null;\n final Collection genderOptions = null;\n final Collection savingProductOptions = null;\n final Collection clientTypeOptions = null;\n final Collection clientClassificationOptions = null;\n final Collection clientNonPersonConstitutionOptions = null;\n final Collection clientNonPersonMainBusinessLineOptions = null;\n final List clientLegalFormOptions = null;\n final ClientFamilyMembersData familyMemberOptions = null;\n return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, activationDate, imageId, staffId, staffName, allowedOffices, groups, staffOptions, closureReasons, genderOptions, timeline, savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, null, clientType, clientClassification, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, clientNonPerson, clientLegalFormOptions, familyMemberOptions, legalForm, null, null, null, isStaff, null);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private Operator constructAlignedSeriesAggregationScanOperator(PlanNodeId planNodeId, AlignedPath alignedPath, List aggregationDescriptorList, Expression pushDownPredicate, Ordering scanOrder, GroupByTimeParameter groupByTimeParameter, boolean outputEndTime, LocalExecutionPlanContext context) {\n AlignedFullPath seriesPath = (AlignedFullPath) IFullPath.convertToIFullPath(alignedPath);\n boolean ascending = scanOrder == ASC;\n List aggregators = new ArrayList<>();\n boolean canUseStatistics = true;\n for (AggregationDescriptor descriptor : aggregationDescriptorList) {\n checkArgument(descriptor.getInputExpressions().size() == 1, \"descriptor's input expression size is not 1\");\n Expression expression = descriptor.getInputExpressions().get(0);\n if (expression instanceof TimeSeriesOperand) {\n String inputSeries = ((TimeSeriesOperand) (descriptor.getInputExpressions().get(0))).getPath().getMeasurement();\n int seriesIndex = alignedPath.getMeasurementList().indexOf(inputSeries);\n TSDataType seriesDataType = alignedPath.getSchemaList().get(seriesIndex).getType();\n if (!judgeCanUseStatistics(descriptor.getAggregationType(), seriesDataType)) {\n canUseStatistics = false;\n }\n aggregators.add(new TreeAggregator(AccumulatorFactory.createAccumulator(descriptor.getAggregationFuncName(), descriptor.getAggregationType(), Collections.singletonList(seriesDataType), descriptor.getInputExpressions(), descriptor.getInputAttributes(), ascending, descriptor.getStep().isInputRaw()), descriptor.getStep(), Collections.singletonList(new InputLocation[] { new InputLocation(0, seriesIndex) })));\n } else if (expression instanceof TimestampOperand) {\n aggregators.add(new TreeAggregator(AccumulatorFactory.createAccumulator(descriptor.getAggregationFuncName(), descriptor.getAggregationType(), Collections.singletonList(TSDataType.INT64), descriptor.getInputExpressions(), descriptor.getInputAttributes(), ascending, descriptor.getStep().isInputRaw()), descriptor.getStep(), Collections.singletonList(new InputLocation[] { new InputLocation(0, -1) })));\n } else {\n throw new IllegalArgumentException(\"descriptor's input expression must be TimeSeriesOperand/TimestampOperand, current is \" + expression);\n }\n }\n ITimeRangeIterator timeRangeIterator = initTimeRangeIterator(groupByTimeParameter, ascending, true);\n long maxReturnSize = AggregationUtil.calculateMaxAggregationResultSize(aggregationDescriptorList, timeRangeIterator, context.getTypeProvider());\n SeriesScanOptions.Builder scanOptionsBuilder = getSeriesScanOptionsBuilder(context);\n scanOptionsBuilder.withAllSensors(new HashSet<>(alignedPath.getMeasurementList()));\n if (pushDownPredicate != null) {\n checkArgument(PredicateUtils.predicateCanPushIntoScan(pushDownPredicate));\n scanOptionsBuilder.withPushDownFilter(convertPredicateToFilter(pushDownPredicate, alignedPath.getMeasurementList(), context.getTypeProvider().getTemplatedInfo() != null, context.getTypeProvider(), context.getZoneId()));\n }\n OperatorContext operatorContext = context.getDriverContext().addOperatorContext(context.getNextOperatorId(), planNodeId, AlignedSeriesAggregationScanOperator.class.getSimpleName());\n AlignedSeriesAggregationScanOperator seriesAggregationScanOperator = new AlignedSeriesAggregationScanOperator(planNodeId, seriesPath, scanOrder, outputEndTime, scanOptionsBuilder.build(), operatorContext, aggregators, timeRangeIterator, groupByTimeParameter, maxReturnSize, canUseStatistics);\n ((DataDriverContext) context.getDriverContext()).addSourceOperator(seriesAggregationScanOperator);\n ((DataDriverContext) context.getDriverContext()).addPath(seriesPath);\n context.getDriverContext().setInputDriver(true);\n return seriesAggregationScanOperator;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public static ICreateAlignedTimeSeriesPlan getCreateAlignedTimeSeriesPlan(PartialPath prefixPath, List measurements, List dataTypes, List encodings, List compressors, List aliasList, List> tagsList, List> attributesList){\r\n return new CreateAlignedTimeSeriesPlanImpl(prefixPath, measurements, dataTypes, encodings, compressors, aliasList, tagsList, attributesList);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Fast decimal scale down by factor of 10 with rounding ROUND_HALF_UP.\n *\n * When the fraction being scaled away is >= 0.5, the add 1.\n *\n * @param fastSignum the sign (-1, 0, or +1)\n * @param fast0 word 0 of the internal representation\n * @param fast1 word 1\n * @param fast2 word 2\n * @param fastIntegerDigitCount the number of integer digits\n * @param fastScale the scale of the number\n * @param roundPower the power to round to\n * @param fastResult an object to reuse\n * @return was the operation successful?\n */\npublic static boolean fastRoundIntegerHalfUp(int fastSignum, long fast0, long fast1, long fast2, int fastIntegerDigitCount, int fastScale, int roundPower, FastHiveDecimal fastResult) {\n /*\n * Basic algorithm:\n *\n * 1. Determine if rounding digit is >= 5 for rounding.\n * 2. Scale away fractional digits if present.\n * 3. If rounding, clear integer rounding portion and add 1.\n *\n */\n if (roundPower >= 0) {\n throw new IllegalArgumentException(\"Expecting roundPower < 0 (roundPower \" + roundPower + \")\");\n }\n final int absRoundPower = -roundPower;\n if (fastIntegerDigitCount < absRoundPower) {\n // Zero result.\n fastResult.fastReset();\n return true;\n }\n final int roundingPoint = absRoundPower + fastScale;\n if (roundingPoint > HiveDecimal.MAX_PRECISION) {\n // Value becomes zero for rounding beyond.\n fastResult.fastReset();\n return true;\n }\n // First, determine whether rounding is necessary based on rounding point, which is inside\n // integer part. And, get rid of any fractional digits. The result scale will be 0.\n //\n boolean isRoundPortionHalfUp = isRoundPortionHalfUp(fast0, fast1, fast2, roundingPoint);\n // If necessary, divide and multiply to get rid of fractional digits.\n if (fastScale == 0) {\n fastResult.fast0 = fast0;\n fastResult.fast1 = fast1;\n fastResult.fast2 = fast2;\n } else {\n doFastScaleDown(fast0, fast1, fast2, /* scaleDown */\n fastScale, fastResult);\n }\n // The fractional digits are gone; when rounding, clear remaining round digits and add 1.\n if (isRoundPortionHalfUp) {\n doClearRoundIntegerPortionAndAddOne(fastResult.fast0, fastResult.fast1, fastResult.fast2, absRoundPower, fastResult);\n } else {\n doClearRoundIntegerPortion(fastResult.fast0, fastResult.fast1, fastResult.fast2, absRoundPower, fastResult);\n }\n if (fastResult.fast0 == 0 && fastResult.fast1 == 0 && fastResult.fast2 == 0) {\n fastResult.fastSignum = 0;\n fastResult.fastIntegerDigitCount = 0;\n fastResult.fastScale = 0;\n } else {\n fastResult.fastSignum = fastSignum;\n fastResult.fastIntegerDigitCount = fastRawPrecision(fastResult);\n fastResult.fastScale = 0;\n }\n return true;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected Map> migrateAway(DataObject chosenFileForMigration, Map> storageCapacities, Map, Long>> snapshotChains, Map, Long>> templateChains, DataStore srcDatastore, Long destDatastoreId, ThreadPoolExecutor executor, List>> futures) {\n Long fileSize = migrationHelper.getFileSize(chosenFileForMigration, snapshotChains, templateChains);\n storageCapacities = assumeMigrate(storageCapacities, srcDatastore.getId(), destDatastoreId, fileSize);\n long activeSsvms = migrationHelper.activeSSVMCount(srcDatastore);\n long totalJobs = activeSsvms * numConcurrentCopyTasksPerSSVM;\n // Increase thread pool size with increase in number of SSVMs\n if (totalJobs > executor.getCorePoolSize()) {\n executor.setMaximumPoolSize((int) (totalJobs));\n executor.setCorePoolSize((int) (totalJobs));\n }\n MigrateDataTask task = new MigrateDataTask(chosenFileForMigration, srcDatastore, dataStoreManager.getDataStore(destDatastoreId, DataStoreRole.Image));\n if (chosenFileForMigration instanceof SnapshotInfo) {\n task.setSnapshotChains(snapshotChains);\n }\n if (chosenFileForMigration instanceof TemplateInfo) {\n task.setTemplateChain(templateChains);\n }\n futures.add((executor.submit(task)));\n logger.debug(String.format(\"Migration of {}: {} is initiated.\", chosenFileForMigration.getType().name(), chosenFileForMigration.getUuid()));\n return storageCapacities;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public NodeSet search(final int contextId, final DocumentSet docs, final List qnames, final String query, final String ngram, final XQueryContext context, final NodeSet contextSet, final int axis) throws XPathException {\n final List searchQnames;\n if (qnames == null || qnames.isEmpty()) {\n searchQnames = getDefinedIndexes(context.getBroker(), docs);\n } else {\n searchQnames = qnames;\n }\n final NodeSet result = new ExtArrayNodeSet(docs.getDocumentCount(), 250);\n for (final Iterator iter = docs.getCollectionIterator(); iter.hasNext(); ) {\n final int collectionId = iter.next().getId();\n for (final QName qname : searchQnames) {\n final NGramQNameKey key = new NGramQNameKey(collectionId, qname, index.getBrokerPool().getSymbols(), query);\n try (final ManagedLock dbLock = lockManager.acquireBtreeReadLock(index.db.getLockName())) {\n final SearchCallback cb = new SearchCallback(contextId, query, ngram, docs, contextSet, context, result, axis == NodeSet.ANCESTOR);\n final int op = query.codePointCount(0, query.length()) < getN() ? IndexQuery.TRUNC_RIGHT : IndexQuery.EQ;\n index.db.query(new IndexQuery(op, key), cb);\n } catch (final LockException e) {\n LOG.warn(\"Failed to acquire lock for '{}'\", FileUtils.fileName(index.db.getFile()), e);\n } catch (final IOException | BTreeException e) {\n LOG.error(\"{} in '{}'\", e.getMessage(), FileUtils.fileName(index.db.getFile()), e);\n }\n }\n }\n // ensure result is ready to use\n result.iterate();\n return result;\n}", "smellKey": "S107", "smellId": null, "repo": "eXist-db_exist", "language": "java"} {"function": "public static PushMessage constructPushMessage(long fromUid, long[] toUids, String[] receivers, String fromName, short toAppId, long cts, String extension, XBody body){\r\n PushMessage message = new PushMessage();\r\n message.setFromUid(fromUid);\r\n message.setToUids(toUids);\r\n message.setReceivers(receivers);\r\n message.setFromName(fromName);\r\n message.setMessageType(body.messageType());\r\n message.setToAppId(toAppId);\r\n message.setBody(body);\r\n message.setCts(cts);\r\n if (extension != null) {\r\n message.setExtension(extension);\r\n }\r\n return message;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void addAnnotation(final int context, final String desc, final boolean visible, final List nameRU, final List tags, final List values, final List caseArrayN, final List nestTypeRS, final List nestNameRU, final List nestPairN){\r\n switch(context) {\r\n case MetadataBandGroup.CONTEXT_CLASS:\r\n if (visible) {\r\n class_RVA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n if ((class_flags[index] & (1 << 21)) != 0) {\r\n class_RVA_bands.incrementAnnoN();\r\n } else {\r\n class_RVA_bands.newEntryInAnnoN();\r\n class_flags[index] = class_flags[index] | (1 << 21);\r\n }\r\n } else {\r\n class_RIA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n if ((class_flags[index] & (1 << 22)) != 0) {\r\n class_RIA_bands.incrementAnnoN();\r\n } else {\r\n class_RIA_bands.newEntryInAnnoN();\r\n class_flags[index] = class_flags[index] | (1 << 22);\r\n }\r\n }\r\n break;\r\n case MetadataBandGroup.CONTEXT_FIELD:\r\n if (visible) {\r\n field_RVA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n final Long flag = tempFieldFlags.remove(tempFieldFlags.size() - 1);\r\n if ((flag.intValue() & (1 << 21)) != 0) {\r\n field_RVA_bands.incrementAnnoN();\r\n } else {\r\n field_RVA_bands.newEntryInAnnoN();\r\n }\r\n tempFieldFlags.add(Long.valueOf(flag.intValue() | (1 << 21)));\r\n } else {\r\n field_RIA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n final Long flag = tempFieldFlags.remove(tempFieldFlags.size() - 1);\r\n if ((flag.intValue() & (1 << 22)) != 0) {\r\n field_RIA_bands.incrementAnnoN();\r\n } else {\r\n field_RIA_bands.newEntryInAnnoN();\r\n }\r\n tempFieldFlags.add(Long.valueOf(flag.intValue() | (1 << 22)));\r\n }\r\n break;\r\n case MetadataBandGroup.CONTEXT_METHOD:\r\n if (visible) {\r\n method_RVA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n final Long flag = tempMethodFlags.remove(tempMethodFlags.size() - 1);\r\n if ((flag.intValue() & (1 << 21)) != 0) {\r\n method_RVA_bands.incrementAnnoN();\r\n } else {\r\n method_RVA_bands.newEntryInAnnoN();\r\n }\r\n tempMethodFlags.add(Long.valueOf(flag.intValue() | (1 << 21)));\r\n } else {\r\n method_RIA_bands.addAnnotation(desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n final Long flag = tempMethodFlags.remove(tempMethodFlags.size() - 1);\r\n if ((flag.intValue() & (1 << 22)) != 0) {\r\n method_RIA_bands.incrementAnnoN();\r\n } else {\r\n method_RIA_bands.newEntryInAnnoN();\r\n }\r\n tempMethodFlags.add(Long.valueOf(flag.intValue() | (1 << 22)));\r\n }\r\n break;\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * A helper api for creating an audit log for a failure event.\n */\nstatic String createFailureLog(String user, String operation, String perm, String target, String description, ApplicationId appId, ApplicationAttemptId attemptId, ContainerId containerId, Resource resource) {\n return createFailureLog(user, operation, perm, target, description, appId, attemptId, containerId, resource, null, null, null);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private String createOvfTemplateOfSourceVmwareUnmanagedInstance(String vcenter, String datacenterName, String username, String password, String clusterName, String sourceHostName, String sourceVMwareInstanceName, DataStoreTO convertLocation, int threadsCountToExportOvf) {\n HypervisorGuru vmwareGuru = hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.VMware);\n Map params = createParamsForTemplateFromVmwareVmMigration(vcenter, datacenterName, username, password, clusterName, sourceHostName, sourceVMwareInstanceName);\n return vmwareGuru.createVMTemplateOutOfBand(sourceHostName, sourceVMwareInstanceName, params, convertLocation, threadsCountToExportOvf);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private CnmTAllegato salvaAllegatoVerbaleSoggetto(CnmRVerbaleSoggetto cnmRVerbaleSoggetto, byte[] file, CnmTUser cnmTUser, String nomeFile, TipoAllegato tipoAllegato, boolean protocolla, boolean isProtocollazioneInUscita, boolean isMaster, List cnmTSoggettoList){\r\n if (cnmRVerbaleSoggetto == null)\r\n throw new IllegalArgumentException(\"cnmRVerbaleSoggetto ==null\");\r\n if (nomeFile == null)\r\n throw new IllegalArgumentException(\"nomeFile ==null\");\r\n if (cnmTUser == null)\r\n throw new IllegalArgumentException(\"cnmTUser ==null\");\r\n if (tipoAllegato == null)\r\n throw new IllegalArgumentException(\"tipoAllegato ==null\");\r\n String folder = null;\r\n String idEntitaFruitore = null;\r\n TipoProtocolloAllegato tipoProtocolloAllegato = TipoProtocolloAllegato.NON_PROTOCOLLARE;\r\n String soggettoActa = null;\r\n String rootActa = null;\r\n if (protocolla) {\r\n folder = utilsDoqui.createOrGetfolder(cnmRVerbaleSoggetto);\r\n idEntitaFruitore = utilsDoqui.createIdEntitaFruitore(cnmRVerbaleSoggetto, cnmDTipoAllegatoRepository.findOne(tipoAllegato.getId()));\r\n soggettoActa = utilsDoqui.getSoggettoActa(cnmRVerbaleSoggetto);\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.PROTOCOLLARE;\r\n rootActa = utilsDoqui.getRootActa(cnmRVerbaleSoggetto);\r\n }\r\n CnmTAllegato cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), null, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_USCITA_SENZA_ALLEGATI_GENERERATI, cnmTSoggettoList);\r\n CnmRAllegatoVerbSogPK cnmRAllegatoVerbSogPK = new CnmRAllegatoVerbSogPK();\r\n cnmRAllegatoVerbSogPK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoVerbSogPK.setIdVerbaleSoggetto(cnmRVerbaleSoggetto.getIdVerbaleSoggetto());\r\n CnmRAllegatoVerbSog cnmRAllegatoVerbSog = new CnmRAllegatoVerbSog();\r\n cnmRAllegatoVerbSog.setId(cnmRAllegatoVerbSogPK);\r\n cnmRAllegatoVerbSog.setCnmTAllegato(cnmTAllegato);\r\n cnmRAllegatoVerbSog.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoVerbSog.setCnmTUser(cnmTUser);\r\n cnmRAllegatoVerbSogRepository.save(cnmRAllegatoVerbSog);\r\n return cnmTAllegato;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Flush previously uploaded data to a file.\n * @param path on which data has to be flushed.\n * @param position to which data has to be flushed.\n * @param retainUncommittedData whether to retain uncommitted data after flush.\n * @param isClose specify if this is the last flush to the file.\n * @param cachedSasToken to be used for the authenticating operation.\n * @param leaseId if there is an active lease on the path.\n * @param contextEncryptionAdapter to provide encryption context.\n * @param tracingContext for tracing the server calls.\n * @return executed rest operation containing response from server.\n * @throws AzureBlobFileSystemException if rest operation fails.\n */\npublic abstract AbfsRestOperation flush(String path, long position, boolean retainUncommittedData, boolean isClose, String cachedSasToken, String leaseId, ContextEncryptionAdapter contextEncryptionAdapter, TracingContext tracingContext) throws AzureBlobFileSystemException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Creates an AggregateCall.\n */\npublic static AggregateCall create(SqlAggFunction aggFunction, boolean distinct, boolean approximate, boolean ignoreNulls, List rexList, List argList, int filterArg, @Nullable ImmutableBitSet distinctKeys, RelCollation collation, RelDataType type, @Nullable String name) {\n return create(SqlParserPos.ZERO, aggFunction, distinct, approximate, ignoreNulls, rexList, argList, filterArg, distinctKeys, collation, type, name);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) {\n JOptionPane pane = new SuiOptionPane(message, messageType, optionType, icon, options, initialValue);\n pane.setInitialValue(initialValue);\n JDialog dialog = pane.createDialog(parentComponent, title);\n pane.selectInitialValue();\n dialog.show();\n Object selectedValue = pane.getValue();\n if (selectedValue == null)\n return CLOSED_OPTION;\n if (options == null) {\n if (selectedValue instanceof Integer)\n return ((Integer) selectedValue).intValue();\n return CLOSED_OPTION;\n }\n for (int counter = 0, maxCounter = options.length; counter < maxCounter; counter++) {\n if (options[counter].equals(selectedValue))\n return counter;\n }\n return CLOSED_OPTION;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "/**\n * @param cacheCtx Cache context.\n * @param op Write operation.\n * @param key Key to add to write set.\n * @param val Value.\n * @param entryProcessors Entry processors.\n * @param ttl TTL.\n * @param skipStore Skip store flag.\n */\npublic void addWrite(GridCacheContext cacheCtx, GridCacheOperation op, IgniteTxKey key, @Nullable CacheObject val, @Nullable Collection, Object[]>> entryProcessors, long ttl, boolean skipStore, boolean keepBinary) {\n checkInternal(key);\n if (isSystemInvalidate())\n return;\n GridDhtCacheEntry cached = cacheCtx.dht().entryExx(key.key(), topologyVersion());\n IgniteTxEntry txEntry = new IgniteTxEntry(cacheCtx, this, op, val, ttl, -1L, cached, null, skipStore, keepBinary);\n txEntry.entryProcessors(entryProcessors);\n txState.addWriteEntry(key, txEntry);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public static Query5Def query(String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name){\r\n return new Query5DefImpl<>(VIEW_BUILDER, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Updates a metadata record. Deletes validation report currently in session (if any). If user asks for validation the validation report\n * will be (re-)created then.\n *\n * @return metadata if the that was updated\n */\nAbstractMetadata updateMetadata(ServiceContext context, String metadataId, Element md, boolean validate, boolean ufo, String lang, String changeDate, boolean updateDateStamp, IndexingMode indexingMode) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public IBaseResource resourceById(Class resource, String stringId, String version, String ifVersionMatches, Boolean returnNull, IBaseResource returnResource, Boolean throwError, Map extraParameters){\r\n IReadTyped readTyped = client.read().resource(resource);\r\n IReadExecutable readExecutable = readWithOptionalVersion(stringId, readTyped, version);\r\n ExtraParameters.process(extraParameters, readExecutable);\r\n return processOptionalParams(ifVersionMatches, returnNull, returnResource, throwError, readExecutable);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "//Create the actual blob of new keys to be written to the token\n// Suports prot1 and prot3\nprivate byte[] createKeySetDataWithSymKeys(byte newKeyVersion, byte[] old_kek_key_array, SymmetricKey old_kek_sym_key, SymmetricKey encKey, SymmetricKey macKey, SymmetricKey kekKey, byte protocol, String tokenName) throws EBaseException {\n SymmetricKey wrappingKey = null;\n String method = \"SecureChannelProtocol.createKeySetDataWithSymKeys:\";\n byte alg = (byte) 0x81;\n byte[] output = null;\n if (encKey == null || macKey == null || kekKey == null || tokenName == null) {\n throw new EBaseException(method + \" Invalid input data!\");\n }\n CryptoManager cm = null;\n CryptoToken token = null;\n try {\n cm = CryptoManager.getInstance();\n token = returnTokenByName(tokenName, cm);\n } catch (NotInitializedException e) {\n logger.error(method + \" \" + e.getMessage(), e);\n throw new EBaseException(e);\n } catch (NoSuchTokenException e) {\n logger.error(method + \" \" + e.getMessage(), e);\n throw new EBaseException(e);\n }\n SymmetricKey encKey16 = null;\n SymmetricKey macKey16 = null;\n SymmetricKey kekKey16 = null;\n byte[] encrypted_enc_key = null;\n byte[] encrypted_mac_key = null;\n byte[] encrypted_kek_key = null;\n byte[] keycheck_enc_key = null;\n byte[] keycheck_mac_key = null;\n byte[] keycheck_kek_key = null;\n if (protocol == PROTOCOL_ONE) {\n if (old_kek_sym_key == null) {\n logger.debug(method + \" Using old kek key array.\");\n wrappingKey = unwrapSymKeyOnToken(token, old_kek_key_array, false);\n } else {\n logger.debug(method + \" Using input old key key sym key.\");\n wrappingKey = old_kek_sym_key;\n }\n logger.debug(method + \"Wrapping key: length: \" + wrappingKey.getLength());\n alg = (byte) 0x81;\n encKey16 = extractDes2FromDes3(encKey, tokenName);\n macKey16 = extractDes2FromDes3(macKey, tokenName);\n kekKey16 = extractDes2FromDes3(kekKey, tokenName);\n encrypted_enc_key = this.wrapSessionKey(tokenName, encKey16, wrappingKey);\n encrypted_mac_key = this.wrapSessionKey(tokenName, macKey16, wrappingKey);\n encrypted_kek_key = this.wrapSessionKey(tokenName, kekKey16, wrappingKey);\n keycheck_enc_key = this.computeKeyCheck(encKey, tokenName);\n keycheck_mac_key = this.computeKeyCheck(macKey, tokenName);\n keycheck_kek_key = this.computeKeyCheck(kekKey, tokenName);\n } else if (protocol == PROTOCOL_TWO) {\n throw new EBaseException(method + \" SCP 02 not yet implemented!\");\n } else if (protocol == PROTOCOL_THREE) {\n logger.debug(method + \" Attempting SCP03\");\n if (old_kek_sym_key == null) {\n logger.debug(method + \" SCP03: Using old kek key array.\");\n wrappingKey = unwrapAESSymKeyOnToken(token, old_kek_key_array, false);\n } else {\n logger.debug(method + \"SCP03: Using input old key key sym key.\");\n wrappingKey = old_kek_sym_key;\n }\n alg = (byte) 0x88;\n encrypted_enc_key = this.wrapSessionKey(tokenName, encKey, wrappingKey);\n encrypted_mac_key = this.wrapSessionKey(tokenName, macKey, wrappingKey);\n encrypted_kek_key = this.wrapSessionKey(tokenName, kekKey, wrappingKey);\n try {\n keycheck_enc_key = this.computeKeyCheck_SCP03(encKey, encKey.getOwningToken().getName());\n keycheck_mac_key = this.computeKeyCheck_SCP03(macKey, macKey.getOwningToken().getName());\n keycheck_kek_key = this.computeKeyCheck_SCP03(kekKey, kekKey.getOwningToken().getName());\n } catch (TokenException e) {\n throw new EBaseException(method + e);\n }\n } else {\n throw new EBaseException(method + \" Invalid SCP version requested!\");\n }\n // Compose the final key set data byte array\n byte[] b1 = null;\n byte[] b2 = null;\n if (protocol == PROTOCOL_THREE) {\n //Will be different if the key is bigger than AES 128\n // Support 128 for now\n b1 = new byte[] { alg, 0x11, (byte) encrypted_enc_key.length };\n } else {\n b1 = new byte[] { alg, 0x10 };\n }\n b2 = new byte[] { 0x3 };\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try {\n outputStream.write(newKeyVersion);\n outputStream.write(b1);\n outputStream.write(encrypted_enc_key);\n outputStream.write(b2);\n outputStream.write(keycheck_enc_key);\n outputStream.write(b1);\n outputStream.write(encrypted_mac_key);\n outputStream.write(b2);\n outputStream.write(keycheck_mac_key);\n outputStream.write(b1);\n outputStream.write(encrypted_kek_key);\n outputStream.write(b2);\n outputStream.write(keycheck_kek_key);\n output = outputStream.toByteArray();\n } catch (IOException e) {\n throw new EBaseException(method + \" Can't compose final output byte array!\");\n }\n //SecureChannelProtocol.debugByteArray(output, \" Final output to createKeySetData: \");\n logger.debug(method + \" returning output\");\n return output;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "/**\n * Try to retrieve from system properties the variable with name\n * .key. If not set, create the resource folder using\n * /folder and set the system property value. Create the\n * folder if does not exist.\n *\n * @param jeevesServlet\n * @param webappName\n * @param handlerConfig\n * @param key\n * @param handlerKey @return\n * @param firstPathSeg\n */\nprivate Path setDir(JeevesServlet jeevesServlet, String webappName, ServiceConfig handlerConfig, Path dir, String key, String handlerKey, String firstPathSeg, String... otherSegments) {\n String envKey = webappName + key;\n if (dir != null) {\n if (Log.isDebugEnabled(Geonet.DATA_DIRECTORY)) {\n Log.debug(Geonet.DATA_DIRECTORY, \"path for \" + envKey + \" set to \" + dir.toString() + \" via bean properties, not looking up\");\n }\n } else {\n dir = lookupProperty(jeevesServlet, handlerConfig, envKey);\n }\n if (dir == null) {\n envKey = Geonet.GEONETWORK + key;\n dir = lookupProperty(jeevesServlet, handlerConfig, envKey);\n }\n if (dir == null) {\n dir = this.systemDataDir.resolve(firstPathSeg);\n for (String otherSegment : otherSegments) {\n dir = dir.resolve(otherSegment);\n }\n } else {\n if (!dir.isAbsolute()) {\n Log.info(Geonet.DATA_DIRECTORY, \" - \" + envKey + \" for directory \" + dir + \" is relative path. Use absolute path instead.\");\n }\n }\n if (handlerKey != null) {\n handlerConfig.setValue(handlerKey, dir.toString());\n }\n // Create directory if it does not exist\n try {\n Files.createDirectories(dir);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n Log.info(Geonet.DATA_DIRECTORY, \" - \" + envKey + \" is \" + dir);\n return dir;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "/**\n *

Reference Page

\n *

\n * Respecifies only a cubic subregion of an existing 3D texel array, with incoming data stored in a specific compressed image format.\n *\n * @param target the target texture.\n * @param level the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image.\n * @param xoffset a texel offset in the x direction within the texture array.\n * @param yoffset a texel offset in the y direction within the texture array.\n * @param zoffset a texel offset in the z direction within the texture array.\n * @param width the width of the texture subimage.\n * @param height the height of the texture subimage.\n * @param depth the depth of the texture subimage.\n * @param format the format of the compressed image data stored at address {@code data}.\n * @param data a pointer to the compressed image data.\n */\npublic void glCompressedTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "private String bindOOPathChunk(String originalBind, DrlxParseSuccess patternParseResult, int pos, boolean isLast, OOPathChunk chunk, String fieldName, Class fieldType, Expression accessorLambda, MethodCallExpr reactiveFrom){\r\n String previousBind;\r\n final String bindingId;\r\n if (isLast && patternParseResult.getExprBinding() != null) {\r\n bindingId = patternParseResult.getExprBinding();\r\n context.removeDeclarationById(bindingId);\r\n } else {\r\n bindingId = context.getOOPathId(fieldType, originalBind + fieldName + pos);\r\n }\r\n DeclarationSpec newDeclaration = context.addDeclaration(bindingId, fieldType, reactiveFrom);\r\n context.addOOPathDeclaration(newDeclaration);\r\n final List conditions = chunk.getConditions();\r\n if (conditions.isEmpty()) {\r\n toPatternExpr(bindingId, Collections.emptyList(), patternParseResult, fieldType);\r\n } else if (conditions.size() == 1 && conditions.get(0).getExpr().isIntegerLiteralExpr()) {\r\n reactiveFrom.setArgument(1, new MethodCallExpr(accessorLambda, \"get\", new NodeList<>(conditions.get(0).getExpr())));\r\n toPatternExpr(bindingId, Collections.emptyList(), patternParseResult, fieldType);\r\n } else {\r\n Class finalFieldType = fieldType;\r\n final List conditionParseResult = conditions.stream().map((DrlxExpression c) -> ConstraintParser.defaultConstraintParser(context, packageModel).drlxParse(finalFieldType, bindingId, PrintUtil.printNode(c))).collect(Collectors.toList());\r\n toPatternExpr(bindingId, conditionParseResult, patternParseResult, fieldType);\r\n }\r\n previousBind = bindingId;\r\n return previousBind;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Response uploadBlockBlob(final InputStream data, final long length, final BlobHttpHeaders headers, final Map metadata, AccessTier tier, final byte[] contentMd5, final BlobRequestConditions requestConditions, final Duration timeout) {\n Flux dataBuffer = Utility.convertStreamToByteBuffer(data, length, 4194304, data.markSupported());\n BlockBlobSimpleUploadOptions uploadOptions = new BlockBlobSimpleUploadOptions(dataBuffer, length).setHeaders(headers).setMetadata(metadata).setTier(tier).setContentMd5(contentMd5).setRequestConditions(requestConditions);\n return getBlockBlobClient().uploadWithResponse(uploadOptions, timeout, Context.NONE);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, String secStorageUrl, String volumePath, String workerVmName, String nfsVersion) throws Exception {\n String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl, nfsVersion);\n String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId);\n String installFullPath = secondaryMountPoint + \"/\" + installPath;\n synchronized (installPath.intern()) {\n Script command = new Script(false, \"mkdir\", _timeout, logger);\n command.add(\"-p\");\n command.add(installFullPath);\n String result = command.execute();\n if (result != null) {\n String msg = \"unable to prepare template directory: \" + installPath + \", storage: \" + secStorageUrl + \", error msg: \" + result;\n logger.error(msg);\n throw new Exception(msg);\n }\n }\n VirtualMachineMO clonedVm = null;\n try {\n Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath);\n if (volumeDeviceInfo == null) {\n String msg = \"Unable to find related disk device for volume. volume path: \" + volumePath;\n logger.error(msg);\n throw new Exception(msg);\n }\n if (!vmMo.createSnapshot(templateUniqueName, \"Temporary snapshot for template creation\", false, false)) {\n String msg = \"Unable to take snapshot for creating template from volume. volume path: \" + volumePath;\n logger.error(msg);\n throw new Exception(msg);\n }\n // 4 MB is the minimum requirement for VM memory in VMware\n String vmxFormattedVirtualHardwareVersion = VirtualMachineMO.getVmxFormattedVirtualHardwareVersion(vmMo.getVirtualHardwareVersion());\n vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()), vmxFormattedVirtualHardwareVersion);\n clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);\n if (clonedVm == null) {\n String msg = \"Unable to create dummy VM to export volume. volume path: \" + volumePath;\n logger.error(msg);\n throw new Exception(msg);\n }\n clonedVm.exportVm(secondaryMountPoint + \"/\" + installPath, templateUniqueName, true, false);\n long physicalSize = new File(installFullPath + \"/\" + templateUniqueName + \".ova\").length();\n OVAProcessor processor = new OVAProcessor();\n Map params = new HashMap();\n params.put(StorageLayer.InstanceConfigKey, _storage);\n processor.configure(\"OVA Processor\", params);\n long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName);\n postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);\n return new Ternary(installPath + \"/\" + templateUniqueName + \".ova\", physicalSize, virtualSize);\n } finally {\n if (clonedVm != null) {\n clonedVm.detachAllDisksAndDestroy();\n }\n vmMo.removeSnapshot(templateUniqueName, false);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Create info panel or info window\n * @param WindowNo\n * @param tableName\n * @param keyColumn\n * @param value\n * @param multiSelection\n * @param whereClause\n * @param AD_InfoWindow_ID\n * @param lookup\n * @return {@link InfoPanel}\n */\npublic InfoPanel create(int WindowNo, String tableName, String keyColumn, String value, boolean multiSelection, String whereClause, int AD_InfoWindow_ID, boolean lookup);", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private String createVMAndFolderWithVMName(VmwareContext context, VmwareHypervisorHost hyperHost, TemplateObjectTO template, VirtualMachineMO vmTemplate, VolumeObjectTO volume, DatacenterMO dcMo, DatastoreMO dsMo, String searchExcludedFolders) throws Exception {\n String vmdkName = volume.getName();\n try {\n ManagedObjectReference morDatastore = dsMo.getMor();\n ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool();\n ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();\n if (template.getSize() != null) {\n _fullCloneFlag = volume.getSize() > template.getSize() ? true : _fullCloneFlag;\n }\n if (!_fullCloneFlag) {\n if (_diskProvisioningStrictness && volume.getProvisioningType() != ProvisioningType.THIN) {\n throw new CloudRuntimeException(\"Unable to create linked clones with strict disk provisioning enabled\");\n }\n createVMLinkedClone(vmTemplate, dcMo, vmdkName, morDatastore, morPool);\n } else {\n createVMFullClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool, volume.getProvisioningType());\n }\n VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName);\n assert (vmMo != null);\n String vmdkFileBaseName = vmMo.getVmdkFileBaseNames().get(0);\n logger.info(\"Move volume out of volume-wrapper VM \" + vmdkFileBaseName);\n String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.VMWARE, !_fullCloneFlag);\n String[] legacyCloudStackLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, !_fullCloneFlag);\n for (int i = 0; i < vmwareLayoutFilePair.length; i++) {\n dsMo.moveDatastoreFile(vmwareLayoutFilePair[i], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[i], dcMo.getMor(), true);\n }\n logger.info(\"detach disks from volume-wrapper VM and destroy {}\", vmdkName);\n vmMo.detachAllDisksAndDestroy();\n String srcFile = dsMo.getDatastorePath(vmdkName, true);\n dsMo.deleteFile(srcFile, dcMo.getMor(), true, searchExcludedFolders);\n if (dsMo.folderExists(String.format(\"[%s]\", dsMo.getName()), vmdkName)) {\n dsMo.deleteFolder(srcFile, dcMo.getMor());\n }\n // restoreVM - move the new ROOT disk into corresponding VM folder\n VirtualMachineMO restoreVmMo = dcMo.findVm(volume.getVmName());\n if (restoreVmMo != null) {\n // VM folder name in datastore will be VM's name in vCenter.\n String vmNameInVcenter = restoreVmMo.getName();\n if (dsMo.folderExists(String.format(\"[%s]\", dsMo.getName()), vmNameInVcenter)) {\n VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmNameInVcenter, dsMo, vmdkFileBaseName, searchExcludedFolders);\n }\n }\n return vmdkFileBaseName;\n } finally {\n // check if volume wrapper VM is cleaned, if not cleanup\n VirtualMachineMO vmdknamedVM = dcMo.findVm(vmdkName);\n if (vmdknamedVM != null) {\n vmdknamedVM.destroy();\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private List executeGroupByQueryInternal(SessionInfo sessionInfo, String device, String measurement, TSDataType dataType, boolean isAligned, long startTime, long endTme, long interval, TAggregationType aggregationType, List dataRegionList) throws IllegalPathException{\r\n int dataRegionSize = dataRegionList.size();\r\n if (dataRegionSize != 1) {\r\n throw new IllegalArgumentException(\"dataRegionList.size() should only be 1 now, current size is \" + dataRegionSize);\r\n }\r\n Filter timeFilter = new TimeFilter.TimeGtEqAndLt(startTime, endTme);\r\n QueryId queryId = new QueryId(\"stub_query\");\r\n FragmentInstanceId instanceId = new FragmentInstanceId(new PlanFragmentId(queryId, 0), \"stub-instance\");\r\n FragmentInstanceStateMachine stateMachine = new FragmentInstanceStateMachine(instanceId, FragmentInstanceManager.getInstance().instanceNotificationExecutor);\r\n FragmentInstanceContext fragmentInstanceContext = createFragmentInstanceContext(instanceId, stateMachine, sessionInfo, dataRegionList.get(0), timeFilter);\r\n DriverContext driverContext = new DriverContext(fragmentInstanceContext, 0);\r\n PlanNodeId planNodeId = new PlanNodeId(\"1\");\r\n driverContext.addOperatorContext(1, planNodeId, SeriesScanOperator.class.getSimpleName());\r\n driverContext.getOperatorContexts().forEach(operatorContext -> operatorContext.setMaxRunTime(DEFAULT_TIME_SLICE));\r\n SeriesScanOptions.Builder scanOptionsBuilder = new SeriesScanOptions.Builder();\r\n scanOptionsBuilder.withAllSensors(Collections.singleton(measurement));\r\n scanOptionsBuilder.withGlobalTimeFilter(timeFilter);\r\n Aggregator aggregator = new Aggregator(AccumulatorFactory.createAccumulator(aggregationType, dataType, null, null, true), AggregationStep.SINGLE, Collections.singletonList(new InputLocation[] { new InputLocation(0, 0) }));\r\n GroupByTimeParameter groupByTimeParameter = new GroupByTimeParameter(startTime, endTme, interval, interval, true);\r\n IMeasurementSchema measurementSchema = new MeasurementSchema(measurement, dataType);\r\n AbstractSeriesAggregationScanOperator operator;\r\n PartialPath path;\r\n if (isAligned) {\r\n path = new AlignedPath(device, Collections.singletonList(measurement), Collections.singletonList(measurementSchema));\r\n operator = new AlignedSeriesAggregationScanOperator(planNodeId, (AlignedPath) path, Ordering.ASC, scanOptionsBuilder.build(), driverContext.getOperatorContexts().get(0), Collections.singletonList(aggregator), initTimeRangeIterator(groupByTimeParameter, true, true), groupByTimeParameter, DEFAULT_MAX_TSBLOCK_SIZE_IN_BYTES);\r\n } else {\r\n path = new MeasurementPath(device, measurement, measurementSchema);\r\n operator = new SeriesAggregationScanOperator(planNodeId, path, Ordering.ASC, scanOptionsBuilder.build(), driverContext.getOperatorContexts().get(0), Collections.singletonList(aggregator), initTimeRangeIterator(groupByTimeParameter, true, true), groupByTimeParameter, DEFAULT_MAX_TSBLOCK_SIZE_IN_BYTES);\r\n }\r\n try {\r\n List result = new ArrayList<>();\r\n fragmentInstanceContext.setSourcePaths(Collections.singletonList(path));\r\n operator.initQueryDataSource(fragmentInstanceContext.getSharedQueryDataSource());\r\n while (operator.hasNext()) {\r\n result.add(operator.next());\r\n }\r\n return result;\r\n } catch (Exception e) {\r\n throw new RuntimeException(e);\r\n } finally {\r\n fragmentInstanceContext.releaseResource();\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void checkFieldCount(SqlNode node, SqlValidatorTable table, List strategies, RelDataType targetRowTypeToValidate, RelDataType realTargetRowType, SqlNode source, RelDataType logicalSourceRowType, RelDataType logicalTargetRowType){\r\n final int sourceFieldCount = logicalSourceRowType.getFieldCount();\r\n final int targetFieldCount = logicalTargetRowType.getFieldCount();\r\n final int targetRealFieldCount = realTargetRowType.getFieldCount();\r\n if (sourceFieldCount != targetFieldCount && sourceFieldCount != targetRealFieldCount) {\r\n throw newValidationError(node, RESOURCE.unmatchInsertColumn(targetFieldCount, sourceFieldCount));\r\n }\r\n for (final RelDataTypeField field : table.getRowType().getFieldList()) {\r\n final RelDataTypeField targetField = targetRowTypeToValidate.getField(field.getName(), true, false);\r\n switch(strategies.get(field.getIndex())) {\r\n case NOT_NULLABLE:\r\n assert !field.getType().isNullable();\r\n if (targetField == null) {\r\n throw newValidationError(node, RESOURCE.columnNotNullable(field.getName()));\r\n }\r\n break;\r\n case NULLABLE:\r\n assert field.getType().isNullable();\r\n break;\r\n case VIRTUAL:\r\n case STORED:\r\n if (targetField != null && !isValuesWithDefault(source, targetField.getIndex())) {\r\n throw newValidationError(node, RESOURCE.insertIntoAlwaysGenerated(field.getName()));\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ConsequenceBuilder._23 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18, Variable arg19, Variable arg20, Variable arg21, Variable arg22, Variable arg23){\r\n return new ConsequenceBuilder._23(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Expression translateTableFunction(JavaTypeFactory typeFactory, SqlConformance conformance, BlockBuilder list, Expression root, RexCall rexCall, Expression inputEnumerable, PhysType inputPhysType, PhysType outputPhysType){\r\n final RexToLixTranslator translator = new RexToLixTranslator(null, typeFactory, root, null, list, null, new RexBuilder(typeFactory), conformance, null);\r\n return translator.translateTableFunction(rexCall, inputEnumerable, inputPhysType, outputPhysType);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static TollfreeVerificationCreator creator(final String businessName, final String businessWebsite, final String notificationEmail, final List useCaseCategories, final String useCaseSummary, final String productionMessageSample, final List optInImageUrls, final TollfreeVerification.OptInType optInType, final String messageVolume, final String tollfreePhoneNumberSid) {\n return new TollfreeVerificationCreator(businessName, businessWebsite, notificationEmail, useCaseCategories, useCaseSummary, productionMessageSample, optInImageUrls, optInType, messageVolume, tollfreePhoneNumberSid);\n}", "smellKey": "S107", "smellId": null, "repo": "twilio_twilio-java", "language": "java"} {"function": "PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags, String name);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": " static ChannelReadyForAddEntryCallback create(BookieClientImpl bookieClient, ByteBufList toSend, long ledgerId, long entryId, BookieId addr, Object ctx, WriteCallback cb, int options, byte[] masterKey, boolean allowFastFail, EnumSet writeFlags){\r\n ChannelReadyForAddEntryCallback callback = RECYCLER.get();\r\n callback.bookieClient = bookieClient;\r\n callback.toSend = toSend;\r\n callback.ledgerId = ledgerId;\r\n callback.entryId = entryId;\r\n callback.addr = addr;\r\n callback.ctx = ctx;\r\n callback.cb = cb;\r\n callback.options = options;\r\n callback.masterKey = masterKey;\r\n callback.allowFastFail = allowFastFail;\r\n callback.writeFlags = writeFlags;\r\n return callback;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convenience method that creates a pair of related Debits and Credits for Accrual Based accounting.\n *\n * The target accounts for debits and credits are switched in case of a reversal\n *\n * @param office\n * office\n * @param currencyCode\n * currencyCode\n * @param accountTypeToBeDebited\n * Enum of the placeholder GLAccount to be debited\n * @param accountTypeToBeCredited\n * Enum of the placeholder of the GLAccount to be credited\n * @param loanProductId\n * loanProductId\n * @param loanId\n * loanId\n * @param transactionId\n * transactionId\n * @param transactionDate\n * transactionDate\n * @param totalAmount\n * totalAmount\n * @param isReversal\n * isReversal\n * @param chargePaymentDTOs\n * chargePaymentDTOs\n */\npublic void createJournalEntriesAndReversalsForLoanCharges(final Office office, final String currencyCode, final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited, final Long loanProductId, final Long loanId, final String transactionId, final LocalDate transactionDate, final BigDecimal totalAmount, final Boolean isReversal, final List chargePaymentDTOs) {\n GLAccount receivableAccount = getLinkedGLAccountForLoanCharges(loanProductId, accountTypeToBeDebited, null);\n final Map creditDetailsMap = new LinkedHashMap<>();\n for (final ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) {\n final Long chargeId = chargePaymentDTO.getChargeId();\n final GLAccount chargeSpecificAccount = getLinkedGLAccountForLoanCharges(loanProductId, accountTypeToBeCredited, chargeId);\n BigDecimal chargeSpecificAmount = chargePaymentDTO.getAmount();\n // adjust net credit amount if the account is already present in the\n // map\n if (creditDetailsMap.containsKey(chargeSpecificAccount)) {\n final BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount);\n chargeSpecificAmount = chargeSpecificAmount.add(existingAmount);\n }\n creditDetailsMap.put(chargeSpecificAccount, chargeSpecificAmount);\n }\n BigDecimal totalCreditedAmount = BigDecimal.ZERO;\n for (final Map.Entry entry : creditDetailsMap.entrySet()) {\n final GLAccount account = entry.getKey();\n final BigDecimal amount = entry.getValue();\n totalCreditedAmount = totalCreditedAmount.add(amount);\n if (isReversal) {\n createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n createCreditJournalEntryForLoan(office, currencyCode, receivableAccount, loanId, transactionId, transactionDate, amount);\n } else {\n createDebitJournalEntryForLoan(office, currencyCode, receivableAccount, loanId, transactionId, transactionDate, amount);\n createCreditJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n }\n }\n if (totalAmount.compareTo(totalCreditedAmount) != 0) {\n throw new PlatformDataIntegrityException(\"Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction\", \"Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction\", totalCreditedAmount, totalAmount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Adds a record to verify migration\n * @param tableId\n * @param columnId\n * @param recordId\n * @param changeLogId\n * @param msg\n * @param currentValue\n * @param expectedValue\n * @param priorityRule\n */\nprivate void addVerifyMigration(int tableId, int columnId, int recordId, int changeLogId, String msg, Object currentValue, String expectedValue, String priorityRule) {\n m_SeqNo += 10;\n MVerifyMigration vm = new MVerifyMigration(getCtx(), getAD_PInstance_ID(), tableId, columnId, recordId, changeLogId, msg, m_SeqNo, currentValue, expectedValue, priorityRule, get_TrxName());\n vm.saveEx();\n m_cnt++;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private static long processBetaNode(BetaNode betaNode, SegmentPrototype smem, List memories, List nodes, long nodePosMask, long allLinkedTestMask, boolean updateNodeBit, TerminalNode removingTn, InternalRuleBase rbase){\r\n RightInputAdapterNode riaNode = null;\r\n if (betaNode.isRightInputIsRiaNode()) {\r\n riaNode = (RightInputAdapterNode) betaNode.getRightInput();\r\n SegmentPrototype[] smems = createLeftTupleNodeProtoMemories(riaNode, removingTn, rbase);\r\n setSegments(riaNode, smems);\r\n if (updateNodeBit && canBeDisabled(betaNode) && riaNode.getPathMemSpec().allLinkedTestMask() > 0) {\r\n allLinkedTestMask = allLinkedTestMask | nodePosMask;\r\n }\r\n } else if (updateNodeBit && canBeDisabled(betaNode)) {\r\n allLinkedTestMask = allLinkedTestMask | nodePosMask;\r\n }\r\n if (NodeTypeEnums.NotNode == betaNode.getType()) {\r\n smem.linkNode(nodePosMask);\r\n }\r\n BetaMemoryPrototype bm = new BetaMemoryPrototype(nodePosMask, riaNode);\r\n if (NodeTypeEnums.AccumulateNode == betaNode.getType()) {\r\n AccumulateMemoryPrototype am = new AccumulateMemoryPrototype(bm);\r\n memories.add(am);\r\n } else {\r\n memories.add(bm);\r\n }\r\n nodes.add(betaNode);\r\n return allLinkedTestMask;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Generates method body for encoding map value. The logic is like this:\n *\n *

\n * {@code\n *\n * encoder.writeInt(map.size();\n *\n * for (Map.Entry entry : map.entrySet()) {\n *   encodeKey(entry.getKey(), encoder, keySchema, seenRefs);\n *   encodeValue(entry.getValue(), encoder, valueSchema, seenRefs);\n * }\n *\n * if (map.size() > 0) {\n *   encoder.writeInt(0);\n * }\n * }\n * 
\n */\nprivate void encodeMap(GeneratorAdapter mg, TypeToken keyType, TypeToken valueType, Schema keySchema, Schema valueSchema, int value, int encoder, int schemaLocal, int seenRefs) {\n // Encode and store the map length locally\n mg.loadArg(value);\n mg.invokeInterface(Type.getType(Map.class), getMethod(int.class, \"size\"));\n int length = mg.newLocal(Type.INT_TYPE);\n mg.storeLocal(length);\n mg.loadArg(encoder);\n mg.loadLocal(length);\n mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, \"writeInt\", int.class));\n mg.pop();\n // Stores the key and value schema\n mg.loadArg(schemaLocal);\n mg.invokeVirtual(Type.getType(Schema.class), getMethod(Map.Entry.class, \"getMapSchema\"));\n mg.dup();\n int keySchemaLocal = mg.newLocal(Type.getType(Schema.class));\n mg.invokeInterface(Type.getType(Map.Entry.class), getMethod(Object.class, \"getKey\"));\n mg.checkCast(Type.getType(Schema.class));\n mg.storeLocal(keySchemaLocal);\n int valueSchemaLocal = mg.newLocal(Type.getType(Schema.class));\n mg.invokeInterface(Type.getType(Map.Entry.class), getMethod(Object.class, \"getValue\"));\n mg.checkCast(Type.getType(Schema.class));\n mg.storeLocal(valueSchemaLocal);\n // Store the entry set iterator\n int iterator = mg.newLocal(Type.getType(Iterator.class));\n mg.loadArg(value);\n mg.invokeInterface(Type.getType(Map.class), getMethod(Set.class, \"entrySet\"));\n mg.invokeInterface(Type.getType(Set.class), getMethod(Iterator.class, \"iterator\"));\n mg.storeLocal(iterator);\n // For loop the entry set iterator, encode each key-value pairs\n Label beginFor = mg.mark();\n Label endFor = mg.newLabel();\n mg.loadLocal(iterator);\n mg.invokeInterface(Type.getType(Iterator.class), getMethod(boolean.class, \"hasNext\"));\n mg.ifZCmp(GeneratorAdapter.EQ, endFor);\n int entry = mg.newLocal(Type.getType(Map.Entry.class));\n mg.loadLocal(iterator);\n mg.invokeInterface(Type.getType(Iterator.class), getMethod(Object.class, \"next\"));\n mg.checkCast(Type.getType(Map.Entry.class));\n mg.storeLocal(entry);\n // encode key\n mg.loadThis();\n mg.loadLocal(entry);\n mg.invokeInterface(Type.getType(Map.Entry.class), getMethod(Object.class, \"getKey\"));\n doCast(mg, keyType, keySchema);\n mg.loadArg(encoder);\n mg.loadLocal(keySchemaLocal);\n mg.loadArg(seenRefs);\n mg.invokeVirtual(classType, getEncodeMethod(keyType, keySchema));\n // encode value\n mg.loadThis();\n mg.loadLocal(entry);\n mg.invokeInterface(Type.getType(Map.Entry.class), getMethod(Object.class, \"getValue\"));\n doCast(mg, valueType, valueSchema);\n mg.loadArg(encoder);\n mg.loadLocal(valueSchemaLocal);\n mg.loadArg(seenRefs);\n mg.invokeVirtual(classType, getEncodeMethod(valueType, valueSchema));\n mg.goTo(beginFor);\n mg.mark(endFor);\n // if length > 0, write out 0 at the end of map\n Label zeroLength = mg.newLabel();\n mg.loadLocal(length);\n mg.ifZCmp(GeneratorAdapter.LE, zeroLength);\n encodeInt(mg, 0, encoder);\n mg.mark(zeroLength);\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "public static RexProgramBuilder create(RexBuilder rexBuilder, final RelDataType inputRowType, final List exprList, final List projectList, @Nullable final RexNode condition, final RelDataType outputRowType, boolean normalize, @Nullable RexSimplify simplify){\r\n return new RexProgramBuilder(rexBuilder, inputRowType, exprList, projectList, condition, outputRowType, normalize, simplify);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static LogicalJoin create(RelNode left, RelNode right, List hints, RexNode condition, Set variablesSet, JoinRelType joinType, boolean semiJoinDone, ImmutableList systemFieldList){\r\n final RelOptCluster cluster = left.getCluster();\r\n final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE);\r\n return new LogicalJoin(cluster, traitSet, hints, left, right, condition, variablesSet, joinType, semiJoinDone, systemFieldList);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CnmTAllegato salvaAllegatoSollecito(CnmTSollecito cnmTSollecito, byte[] file, CnmTUser cnmTUser, String nomeFile, TipoAllegato tipoAllegato, boolean protocolla, boolean isProtocollazioneInUscita, boolean isMaster){\r\n if (cnmTSollecito == null)\r\n throw new IllegalArgumentException(\"id ==null\");\r\n if (nomeFile == null)\r\n throw new IllegalArgumentException(\"nomeFile ==null\");\r\n if (cnmTUser == null)\r\n throw new IllegalArgumentException(\"cnmTUser ==null\");\r\n if (tipoAllegato == null)\r\n throw new IllegalArgumentException(\"tipoAllegato ==null\");\r\n String tipoActa = null;\r\n if (tipoAllegato.getId() == TipoAllegato.LETTERA_SOLLECITO.getId() || tipoAllegato.getId() == TipoAllegato.LETTERA_SOLLECITO_RATE.getId()) {\r\n tipoActa = StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_USCITA_SENZA_ALLEGATI_GENERERATI;\r\n }\r\n String folder = null;\r\n String idEntitaFruitore = null;\r\n TipoProtocolloAllegato tipoProtocolloAllegato = TipoProtocolloAllegato.NON_PROTOCOLLARE;\r\n String soggettoActa = null;\r\n String rootActa = null;\r\n List cnmTSoggettoList = null;\r\n if (protocolla) {\r\n folder = utilsDoqui.createOrGetfolder(cnmTSollecito);\r\n idEntitaFruitore = utilsDoqui.createIdEntitaFruitore(cnmTSollecito, cnmDTipoAllegatoRepository.findOne(tipoAllegato.getId()));\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.PROTOCOLLARE;\r\n soggettoActa = utilsDoqui.getSoggettoActa(cnmTSollecito);\r\n rootActa = utilsDoqui.getRootActa(cnmTSollecito);\r\n List cnmTSollecitoList = new ArrayList();\r\n cnmTSollecitoList.add(cnmTSollecito);\r\n List cnmROrdinanzaVerbSogList = cnmROrdinanzaVerbSogRepository.findByCnmTSollecitosIn(cnmTSollecitoList);\r\n List cnmRVerbaleSoggettoList = cnmRVerbaleSoggettoRepository.findByCnmROrdinanzaVerbSogsIn(cnmROrdinanzaVerbSogList);\r\n cnmTSoggettoList = cnmTSoggettoRepository.findByCnmRVerbaleSoggettosIn(cnmRVerbaleSoggettoList);\r\n }\r\n CnmTAllegato cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), null, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, tipoActa, cnmTSoggettoList);\r\n CnmRAllegatoSollecitoPK cnmRAllegatoSollecitoPK = new CnmRAllegatoSollecitoPK();\r\n cnmRAllegatoSollecitoPK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoSollecitoPK.setIdSollecito(cnmTSollecito.getIdSollecito());\r\n CnmRAllegatoSollecito cnmRAllegatoSollecito = new CnmRAllegatoSollecito();\r\n cnmRAllegatoSollecito.setId(cnmRAllegatoSollecitoPK);\r\n cnmRAllegatoSollecito.setCnmTAllegato(cnmTAllegato);\r\n cnmRAllegatoSollecito.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoSollecito.setCnmTUser(cnmTUser);\r\n cnmRAllegatoSollecitoRepository.save(cnmRAllegatoSollecito);\r\n if (tipoAllegato.getId() == TipoAllegato.LETTERA_SOLLECITO_RATE.getId()) {\r\n List cnmRSollecitoSoggRataList = cnmRSollecitoSoggRataRepository.findByCnmTSollecito(cnmTSollecito);\r\n if (cnmRSollecitoSoggRataList == null || cnmRSollecitoSoggRataList.isEmpty())\r\n throw new SecurityException(\"cnmRSollecitoSoggRataList is null\");\r\n CnmRAllegatoPianoRatePK cnmRAllegatoPianoRatePK = new CnmRAllegatoPianoRatePK();\r\n cnmRAllegatoPianoRatePK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoPianoRatePK.setIdPianoRate(cnmRSollecitoSoggRataList.get(0).getCnmTRata().getCnmTPianoRate().getIdPianoRate());\r\n CnmRAllegatoPianoRate cnmRAllegatoPianoRate = new CnmRAllegatoPianoRate();\r\n cnmRAllegatoPianoRate.setId(cnmRAllegatoPianoRatePK);\r\n cnmRAllegatoPianoRate.setCnmTAllegato(cnmTAllegato);\r\n cnmRAllegatoPianoRate.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoPianoRate.setCnmTUser(cnmTUser);\r\n cnmRAllegatoPianoRateRepository.save(cnmRAllegatoPianoRate);\r\n }\r\n return cnmTAllegato;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Operator genReduceSinkPlan(Operator input, List partitionCols, List sortCols, String sortOrder, String nullOrder, int numReducers, AcidUtils.Operation acidOp, boolean isCompaction) throws SemanticException {\n return genReduceSinkPlan(input, partitionCols, sortCols, sortOrder, nullOrder, numReducers, acidOp, false, isCompaction);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Same as {@link #create(String, FsPermission, EnumSet, boolean, short, long,\n * Progressable, int, ChecksumOpt, InetSocketAddress[])} with the addition of\n * ecPolicyName that is used to specify a specific erasure coding policy\n * instead of inheriting any policy from this new file's parent directory.\n * This policy will be persisted in HDFS. A value of null means inheriting\n * parent groups' whatever policy.\n */\npublic DFSOutputStream create(String src, FsPermission permission, EnumSet flag, boolean createParent, short replication, long blockSize, Progressable progress, int buffersize, ChecksumOpt checksumOpt, InetSocketAddress[] favoredNodes, String ecPolicyName) throws IOException {\n return create(src, permission, flag, createParent, replication, blockSize, progress, buffersize, checksumOpt, favoredNodes, ecPolicyName, null);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": " static ServerSocketChannel createServerSocketChannel(ILogger logger, @Nonnull EndpointConfig endpointConfig, InetAddress bindAddress, int port, int portCount, boolean isPortAutoIncrement, boolean isReuseAddress, boolean bindAny){\r\n logger.finest(\"inet reuseAddress:\" + isReuseAddress);\r\n if (port == 0) {\r\n logger.info(\"No explicit port is given, system will pick up an ephemeral port.\");\r\n }\r\n int portTrialCount = port > 0 && isPortAutoIncrement ? portCount : 1;\r\n try {\r\n return tryOpenServerSocketChannel(endpointConfig, bindAddress, port, isReuseAddress, portTrialCount, bindAny, logger);\r\n } catch (IOException e) {\r\n String message = \"Cannot bind to a given address: \" + bindAddress + \". Hazelcast cannot start. \";\r\n if (isPortAutoIncrement) {\r\n message += \"Config-port: \" + port + \", latest-port: \" + (port + portTrialCount - 1);\r\n } else {\r\n message += \"Port [\" + port + \"] is already in use and auto-increment is disabled.\";\r\n }\r\n throw new HazelcastException(message, e);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static RecurringDepositAccountData importInstance(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, EnumOptionData interestCompoundingPeriodTypeEnum, EnumOptionData interestPostingPeriodTypeEnum, EnumOptionData interestCalculationTypeEnum, EnumOptionData interestCalculationDaysInYearTypeEnum, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyTypeEnum, BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, LocalDate expectedFirstDepositOnDate, Integer recurringFrequency, EnumOptionData recurringFrequencyTypeEnum, boolean isCalendarInherited, boolean isMandatoryDeposit, boolean allowWithdrawal, boolean adjustAdvanceTowardsFuturePayments, String externalId, Collection charges, Integer rowIndex, String locale, String dateFormat) {\n return new RecurringDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, depositPeriodFrequencyId, expectedFirstDepositOnDate, recurringFrequency, recurringFrequencyTypeEnum, isCalendarInherited, isMandatoryDeposit, allowWithdrawal, adjustAdvanceTowardsFuturePayments, externalId, charges, rowIndex, locale, dateFormat);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static InterestRateChartData withTemplate(InterestRateChartData interestRateChartData, Collection periodTypes, final Collection entityTypeOptions, final Collection attributeNameOptions, final Collection conditionTypeOptions, final Collection incentiveTypeOptions, final Collection genderOptions, final Collection clientTypeOptions, final Collection clientClassificationOptions) {\n return new InterestRateChartData(interestRateChartData.id, interestRateChartData.name, interestRateChartData.description, interestRateChartData.fromDate, interestRateChartData.endDate, interestRateChartData.isPrimaryGroupingByAmount, interestRateChartData.productId, interestRateChartData.productName, interestRateChartData.chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public AMNodeInfo registerTask(boolean externalClientRequest, String amLocation, int port, String umbilicalUser, Token jobToken, QueryIdentifier queryIdentifier, TezTaskAttemptID attemptId, boolean isGuaranteed){\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Registering for heartbeat: {}, queryIdentifier={}, attemptId={}\", (amLocation + \":\" + port), queryIdentifier, attemptId);\r\n }\r\n synchronized (knownAppMasters) {\r\n LlapNodeId amNodeId = LlapNodeId.getInstance(amLocation, port);\r\n Map amNodeInfoPerQuery = knownAppMasters.get(queryIdentifier);\r\n if (amNodeInfoPerQuery == null) {\r\n amNodeInfoPerQuery = new HashMap<>();\r\n knownAppMasters.put(queryIdentifier, amNodeInfoPerQuery);\r\n }\r\n AMNodeInfo amNodeInfo = amNodeInfoPerQuery.get(amNodeId);\r\n if (amNodeInfo == null) {\r\n amNodeInfo = new AMNodeInfo(amNodeId, umbilicalUser, jobToken, queryIdentifier, retryPolicy, retryTimeout, socketFactory, conf);\r\n amNodeInfo.setIsExternalClientRequest(externalClientRequest);\r\n amNodeInfoPerQuery.put(amNodeId, amNodeInfo);\r\n amNodeInfo.setNextHeartbeatTime(System.currentTimeMillis() + heartbeatInterval);\r\n pendingHeartbeatQueeu.add(amNodeInfo);\r\n }\r\n amNodeInfo.addTaskAttempt(attemptId, isGuaranteed);\r\n return amNodeInfo;\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ConsequenceBuilder._24 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18, Variable arg19, Variable arg20, Variable arg21, Variable arg22, Variable arg23, Variable arg24){\r\n return new ConsequenceBuilder._24(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22, arg23, arg24);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void exportVolumeToSecondaryStorage(VirtualMachineMO vmMo, String volumePath, String secStorageUrl, String secStorageDir, String exportName, String workerVmName, String nfsVersion, boolean clonedWorkerVMNeeded) throws Exception {\n String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl, nfsVersion);\n String exportPath = secondaryMountPoint + \"/\" + secStorageDir + \"/\" + exportName;\n synchronized (exportPath.intern()) {\n if (!new File(exportPath).exists()) {\n Script command = new Script(false, \"mkdir\", _timeout, logger);\n command.add(\"-p\");\n command.add(exportPath);\n String result = command.execute();\n if (result != null) {\n String errorMessage = String.format(\"Unable to prepare snapshot backup directory: [%s] due to [%s].\", exportPath, result);\n logger.error(errorMessage);\n throw new Exception(errorMessage);\n }\n }\n }\n VirtualMachineMO clonedVm = null;\n try {\n Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath);\n if (volumeDeviceInfo == null) {\n String msg = \"Unable to find related disk device for volume. volume path: \" + volumePath;\n logger.error(msg);\n throw new Exception(msg);\n }\n if (clonedWorkerVMNeeded) {\n // 4 MB is the minimum requirement for VM memory in VMware\n String vmxFormattedVirtualHardwareVersion = VirtualMachineMO.getVmxFormattedVirtualHardwareVersion(vmMo.getVirtualHardwareVersion());\n vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()), vmxFormattedVirtualHardwareVersion);\n clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);\n if (clonedVm == null) {\n String msg = String.format(\"Unable to create dummy VM to export volume. volume path: [%s].\", volumePath);\n logger.error(msg);\n throw new Exception(msg);\n }\n //Note: volss: not to create ova.\n clonedVm.exportVm(exportPath, exportName, false, false);\n } else {\n vmMo.exportVm(exportPath, exportName, false, false);\n }\n } finally {\n if (clonedVm != null) {\n clonedVm.detachAllDisksAndDestroy();\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static SelfServiceRegistrationData getData(final Long id, final Client client, final String firstName, final String lastName, final String mobileNumber, final String email, final String authenticationToken, final String username, final String password, final LocalDate createdDate) {\n return new SelfServiceRegistrationData(id, client, firstName, lastName, mobileNumber, email, authenticationToken, username, password, createdDate);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static void log(String user, String operation, String znode, String acl, String createMode, String session, String ip, Result result) {\n auditLogger.logAuditEvent(createLogEvent(user, operation, znode, acl, createMode, session, ip, result));\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_zookeeper", "language": "java"} {"function": " Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, RestConfiguration configuration, Map parameters, boolean api) throws Exception{\r\n String path = basePath;\r\n if (uriTemplate != null) {\r\n if (uriTemplate.startsWith(\"/\")) {\r\n path = path + uriTemplate;\r\n } else {\r\n path = path + \"/\" + uriTemplate;\r\n }\r\n }\r\n path = FileUtil.stripLeadingSeparator(path);\r\n String scheme = \"http\";\r\n String host = \"\";\r\n int port = 0;\r\n RestConfiguration config = configuration;\r\n if (config == null) {\r\n config = CamelContextHelper.getRestConfiguration(getCamelContext(), \"jetty\");\r\n }\r\n if (config.getScheme() != null) {\r\n scheme = config.getScheme();\r\n }\r\n if (config.getHost() != null) {\r\n host = config.getHost();\r\n }\r\n int num = config.getPort();\r\n if (num > 0) {\r\n port = num;\r\n }\r\n String contextPath = config.getContextPath();\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n contextPath = FileUtil.stripTrailingSeparator(contextPath);\r\n contextPath = FileUtil.stripLeadingSeparator(contextPath);\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n path = contextPath + \"/\" + path;\r\n }\r\n }\r\n if (ObjectHelper.isEmpty(host)) {\r\n host = RestComponentHelper.resolveRestHostName(host, config);\r\n }\r\n Map map = RestComponentHelper.initRestEndpointProperties(\"jetty\", config);\r\n boolean cors = config.isEnableCORS();\r\n if (cors) {\r\n map.put(\"optionsEnabled\", \"true\");\r\n }\r\n if (api) {\r\n map.put(\"matchOnUriPrefix\", \"true\");\r\n }\r\n RestComponentHelper.addHttpRestrictParam(map, verb, cors);\r\n String url = RestComponentHelper.createRestConsumerUrl(\"jetty\", scheme, host, port, path, map);\r\n JettyHttpEndpoint endpoint = (JettyHttpEndpoint) camelContext.getEndpoint(url, parameters);\r\n if (!map.containsKey(\"httpBindingRef\")) {\r\n endpoint.setHttpBinding(new JettyRestHttpBinding(endpoint));\r\n endpoint.setEnableMultipartFilter(false);\r\n }\r\n Consumer consumer = endpoint.createConsumer(processor);\r\n if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {\r\n setProperties(camelContext, consumer, config.getConsumerProperties());\r\n }\r\n ServiceHelper.startService(endpoint);\r\n return consumer;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void appendPosixDaylightTransition(TimeZone tz, StringBuilder buf, int mode, int day, int month, int dayOfWeek, int time, int timeMode, boolean verbose, boolean isEnd){\r\n buf.append(',');\r\n int week = day;\r\n switch(mode) {\r\n case 1:\r\n throw Util.needToImplement(0);\r\n case 3:\r\n switch(day) {\r\n case 1:\r\n week = 1;\r\n break;\r\n case 8:\r\n week = 2;\r\n break;\r\n case 15:\r\n week = 3;\r\n break;\r\n case 22:\r\n week = 4;\r\n break;\r\n default:\r\n throw new AssertionError(\"POSIX timezone format cannot represent \" + tz);\r\n }\r\n case 2:\r\n buf.append('M');\r\n buf.append(month + 1);\r\n buf.append('.');\r\n if (week == -1) {\r\n week = 5;\r\n }\r\n buf.append(week);\r\n buf.append('.');\r\n buf.append(dayOfWeek - 1);\r\n break;\r\n case 4:\r\n throw Util.needToImplement(0);\r\n default:\r\n throw new AssertionError(\"unexpected value: \" + mode);\r\n }\r\n switch(timeMode) {\r\n case 0:\r\n break;\r\n case 1:\r\n if (isEnd) {\r\n time += tz.getDSTSavings();\r\n }\r\n break;\r\n case 2:\r\n time += tz.getRawOffset();\r\n if (isEnd) {\r\n time += tz.getDSTSavings();\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n if (verbose || (time != 7200000)) {\r\n buf.append('/');\r\n appendPosixTime(buf, time);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean checkOperandTypesWithPrecedence(HazelcastCallBinding callBinding, boolean throwOnFailure, HazelcastSqlValidator validator, SqlNode high, RelDataType highType, SqlNode low, RelDataType lowType, int lowIndex){\r\n QueryDataType highHZType = HazelcastTypeUtils.toHazelcastType(highType);\r\n QueryDataType lowHZType = HazelcastTypeUtils.toHazelcastType(lowType);\r\n if (highHZType.getTypeFamily().isNumeric()) {\r\n setNumericParameterConverter(validator, high, highHZType);\r\n setNumericParameterConverter(validator, low, highHZType);\r\n }\r\n boolean valid = validator.getTypeCoercion().rowTypeElementCoercion(callBinding.getScope(), low, highType, lowOperandNode -> callBinding.getCall().setOperand(lowIndex, lowOperandNode));\r\n if (valid && highHZType.getTypeFamily() == OBJECT && lowHZType.getTypeFamily() != OBJECT) {\r\n valid = false;\r\n }\r\n if (highHZType.isCustomType() && lowHZType.isCustomType()) {\r\n if (!highHZType.getObjectTypeName().equals(lowHZType.getObjectTypeName())) {\r\n valid = false;\r\n }\r\n assert highHZType.getObjectTypeKind().equals(lowHZType.getObjectTypeKind());\r\n }\r\n if (!valid && throwOnFailure) {\r\n throw callBinding.newValidationSignatureError();\r\n }\r\n return valid;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * \tWrite results to log and records in history table\n *\n * \t\t@param ctx\n * @param success\n * @param detail\n * @param objectName\n * @param objectID\n * @param objectUU\n * @param action\n * @param execCode\n * @param result\n * \t\t@throws SAXException\n */\npublic void logImportDetail(PIPOContext ctx, X_AD_Package_Imp_Detail detail, int success, String objectName, int objectID, String objectUU, String action, String execCode, String result) throws SAXException {\n String msgSuccess = success == 1 ? \"Success\" : \"Failure\";\n // try to figure out the UUID when empty\n if (Util.isEmpty(objectUU) && objectID > 0 && detail.getAD_Table_ID() > 0) {\n MTable table = MTable.get(ctx.ctx, detail.getAD_Table_ID(), getTrxName(ctx));\n PO po = table.getPO(objectID, getTrxName(ctx));\n if (po != null)\n objectUU = po.get_UUID();\n }\n detail.setName(objectName);\n detail.setAction(action);\n detail.setSuccess(msgSuccess);\n if (execCode != null)\n detail.setExecCode(execCode);\n if (result != null)\n detail.setResult(result);\n if (objectID >= 0)\n detail.setRecord_ID(objectID);\n if (!Util.isEmpty(objectUU))\n detail.setRecord_UU(objectUU);\n ctx.packIn.addImportDetail(detail);\n StringBuilder msg = new StringBuilder(action).append(\" \");\n if (detail.getTableName() != null)\n msg.append(detail.getTableName());\n msg.append(\"=\").append(objectName).append(\"[\").append(objectID).append(\"]\");\n if (success == 1)\n ctx.packIn.getNotifier().addSuccessLine(msg.toString());\n else\n ctx.packIn.getNotifier().addFailureLine(msg.toString());\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public static SmsData instance(final Long id, final Long groupId, final Long clientId, final Long staffId, final EnumOptionData status, final String mobileNo, final String message, final Long providerId, final String camapignName) {\n return new SmsData().setId(id).setGroupId(groupId).setClientId(clientId).setStaffId(staffId).setStatus(status).setMobileNo(mobileNo).setMessage(message).setProviderId(providerId).setCampaignName(camapignName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * update tour map and compare result view\n *\n * @param startIndex\n * @param endIndex\n * @param speed\n * @param isDataSaved\n */\nprivate void fireChangeEvent(final int startIndex, final int endIndex, final float avgAltimeter, final float avgPulse, final float maxPulse, final float speed, final float pace, final int tourDeviceTime_Elapsed, final boolean isDataSaved) {\n final TourPropertyCompareTourChanged customData = new TourPropertyCompareTourChanged(_comparedTour_ComparedItemId, _comparedTour_TourId, _comparedTour_RefId, startIndex, endIndex, isDataSaved, _comparedTourItem);\n customData.avgAltimeter = avgAltimeter;\n customData.avgPulse = avgPulse;\n customData.maxPulse = maxPulse;\n customData.tourDeviceTime_Elapsed = tourDeviceTime_Elapsed;\n customData.speed = speed;\n customData.pace = pace;\n TourManager.fireEventWithCustomData(TourEventId.COMPARE_TOUR_CHANGED, customData, this);\n}", "smellKey": "S107", "smellId": null, "repo": "wolfgang-ch_mytourbook", "language": "java"} {"function": " QueryCallViewItem call(Argument var1, Argument var2, Argument var3, Argument var4, Argument var5, Argument var6, Argument var7, Argument var8, Argument var9, Argument var10){\r\n return call(true, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns a {@link RecurringDepositProductData} that contains and exist {@link RecurringDepositProductData} data\n * with further template data for dropdowns.\n *\n * @param taxGroupOptions\n * TODO\n */\npublic static RecurringDepositProductData withTemplate(final RecurringDepositProductData existingProduct, final Collection currencyOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, final Map> accountingMappingOptions, final Collection chargeOptions, final Collection penaltyOptions, final InterestRateChartData chartTemplate, final Collection preClosurePenalInterestOnTypeOptions, final Collection periodFrequencyTypeOptions, final Collection taxGroupOptions) {\n return new RecurringDepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.minBalanceForInterestCalculation, existingProduct.accountingRule, existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, existingProduct.feeToIncomeAccountMappings, existingProduct.penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, chartTemplate, existingProduct.preClosurePenalApplicable, existingProduct.preClosurePenalInterest, existingProduct.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, existingProduct.minDepositTerm, existingProduct.maxDepositTerm, existingProduct.minDepositTermType, existingProduct.maxDepositTermType, existingProduct.inMultiplesOfDepositTerm, existingProduct.inMultiplesOfDepositTermType, existingProduct.isMandatoryDeposit, existingProduct.allowWithdrawal, existingProduct.adjustAdvanceTowardsFuturePayments, periodFrequencyTypeOptions, existingProduct.minDepositAmount, existingProduct.depositAmount, existingProduct.maxDepositAmount, existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "protected String buildFilename(final IVariables variables, final String realFileName, final String realExtension, final String transformnr, final String partnr, final String splitnr, final boolean beamContext, final String transformId, final int bundleNr, final Date date, final boolean ziparchive, final boolean showSamples, final BaseFileOutputMeta meta) {\n SimpleDateFormat daf = new SimpleDateFormat();\n // Replace possible environment variables...\n String retval = realFileName;\n if (meta.isFileAsCommand()) {\n return retval;\n }\n Date now = date == null ? new Date() : date;\n if (meta.isSpecifyingFormat() && !Utils.isEmpty(meta.getDateTimeFormat())) {\n daf.applyPattern(meta.getDateTimeFormat());\n String dt = daf.format(now);\n retval += dt;\n } else {\n if (meta.isDateInFilename()) {\n if (showSamples) {\n daf.applyPattern(\"yyyMMdd\");\n String d = daf.format(now);\n retval += \"_\" + d;\n } else {\n retval += \"_\";\n }\n }\n if (meta.isTimeInFilename()) {\n if (showSamples) {\n daf.applyPattern(\"HHmmss\");\n String t = daf.format(now);\n retval += \"_\" + t;\n } else {\n retval += \"_\";\n }\n }\n }\n if (meta.isTransformNrInFilename()) {\n retval += \"_\" + transformnr;\n }\n if (meta.isPartNrInFilename()) {\n retval += \"_\" + partnr;\n }\n if (meta.getSplitEvery(variables) > 0) {\n retval += \"_\" + splitnr;\n }\n if (beamContext) {\n retval += \"_\" + transformId + \"_\" + bundleNr;\n }\n if (\"Zip\".equals(meta.getFileCompression())) {\n if (ziparchive) {\n retval += \".zip\";\n } else {\n if (realExtension != null && realExtension.length() != 0) {\n retval += \".\" + realExtension;\n }\n }\n } else {\n if (realExtension != null && realExtension.length() != 0) {\n retval += \".\" + realExtension;\n }\n if (\"GZip\".equals(meta.getFileCompression())) {\n retval += \".gz\";\n }\n }\n return retval;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private static void asyncReadRecordFromLogSegment(final String streamName, final LogSegmentRandomAccessEntryReader reader, final LogSegmentMetadata metadata, final ExecutorService executorService, final int scanStartBatchSize, final int scanMaxBatchSize, final boolean includeControl, final boolean includeEndOfStream, final CompletableFuture promise, final AtomicInteger numRecordsScanned, final LogRecordSelector selector, final boolean backward, final long startEntryId){\r\n final long lastAddConfirmed = reader.getLastAddConfirmed();\r\n if (lastAddConfirmed < 0) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Log segment {} is empty for {}.\", new Object[] { metadata, streamName });\r\n }\r\n promise.complete(null);\r\n return;\r\n }\r\n final ScanContext context = new ScanContext(startEntryId, lastAddConfirmed, scanStartBatchSize, scanMaxBatchSize, includeControl, includeEndOfStream, backward, numRecordsScanned);\r\n asyncReadRecordFromEntries(streamName, reader, metadata, executorService, promise, context, selector);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "//\tcreateShipment\n/**\n * \tCreate New Cost Detail record for Physical Inventory.\n * \tCalled from Doc_Inventory.\n * \t@param as accounting schema\n * \t@param AD_Org_ID org\n * \t@param M_Product_ID product\n * \t@param M_AttributeSetInstance_ID asi\n * \t@param M_InventoryLine_ID order\n * \t@param M_CostElement_ID optional cost element\n * \t@param Amt amt total amount\n * \t@param Qty qty\n * \t@param Description optional description\n * \t@param trxName transaction\n * \t@return true if no error\n */\npublic static boolean createInventory(MAcctSchema as, int AD_Org_ID, int M_Product_ID, int M_AttributeSetInstance_ID, int M_InventoryLine_ID, int M_CostElement_ID, BigDecimal Amt, BigDecimal Qty, String Description, String trxName) {\n MCostDetail cd = get(as.getCtx(), \"M_InventoryLine_ID=? AND Coalesce(M_CostElement_ID,0)=\" + M_CostElement_ID, M_InventoryLine_ID, M_AttributeSetInstance_ID, as.getC_AcctSchema_ID(), trxName);\n //\n if (//\tcreateNew\n cd == null) {\n cd = new MCostDetail(as, AD_Org_ID, M_Product_ID, M_AttributeSetInstance_ID, M_CostElement_ID, Amt, Qty, Description, trxName);\n cd.setM_InventoryLine_ID(M_InventoryLine_ID);\n } else {\n if (cd.isProcessed()) {\n // set deltaAmt=Amt, deltaQty=qty, and set Cost Detail for Amt and Qty\n cd.setDeltaAmt(Amt.subtract(cd.getAmt()));\n cd.setDeltaQty(Qty.subtract(cd.getQty()));\n } else {\n cd.setDeltaAmt(BigDecimal.ZERO);\n cd.setDeltaQty(BigDecimal.ZERO);\n cd.setAmt(Amt);\n cd.setQty(Qty);\n }\n if (cd.isDelta()) {\n cd.setProcessed(false);\n cd.setAmt(Amt);\n cd.setQty(Qty);\n } else if (cd.isProcessed())\n //\tnothing to do\n return true;\n }\n boolean ok = cd.save();\n if (ok && !cd.isProcessed()) {\n ok = cd.process();\n }\n if (s_log.isLoggable(Level.CONFIG))\n s_log.config(\"(\" + ok + \") \" + cd);\n return ok;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public static Last[][] setScoreVector(int x, int gop, int gep, int[] subs, boolean storing, int[][][] scores, int[] xyMax, int score){\r\n return setScoreVector(x, 0, 0, scores[0].length - 1, gop, gep, subs, storing, scores, xyMax, score);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BasicHttpServiceContextFactory createContextFactory(Program program, ProgramOptions programOptions, int instanceId, final AtomicInteger instanceCount, MetricsCollectionService metricsCollectionService, DatasetFramework datasetFramework, DiscoveryServiceClient discoveryServiceClient, TransactionSystemClient txClient, @Nullable PluginInstantiator pluginInstantiator, SecureStore secureStore, SecureStoreManager secureStoreManager, MessagingService messagingService, ArtifactManager artifactManager, MetadataReader metadataReader, MetadataPublisher metadataPublisher, PluginFinder pluginFinder, FieldLineageWriter fieldLineageWriter, TransactionRunner transactionRunner, PreferencesFetcher preferencesFetcher, RemoteClientFactory remoteClientFactory, ContextAccessEnforcer contextAccessEnforcer, AppStateStoreProvider appStateStoreProvider) {\n return (spec, handlerClass) -> {\n if (handlerClass != null && AbstractSystemHttpServiceHandler.class.isAssignableFrom(handlerClass)) {\n return new BasicSystemHttpServiceContext(program, programOptions, cConf, spec, instanceId, instanceCount, metricsCollectionService, datasetFramework, discoveryServiceClient, txClient, pluginInstantiator, secureStore, secureStoreManager, messagingService, artifactManager, metadataReader, metadataPublisher, namespaceQueryAdmin, pluginFinder, fieldLineageWriter, transactionRunner, preferencesFetcher, remoteClientFactory, contextAccessEnforcer, appStateStoreProvider);\n }\n return new BasicHttpServiceContext(program, programOptions, cConf, spec, instanceId, instanceCount, metricsCollectionService, datasetFramework, discoveryServiceClient, txClient, pluginInstantiator, secureStore, secureStoreManager, messagingService, artifactManager, metadataReader, metadataPublisher, namespaceQueryAdmin, pluginFinder, fieldLineageWriter, remoteClientFactory, appStateStoreProvider);\n };\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "private void check4Generic1MinSize(Context context, T object, String testName, String column, FieldParameters colParam, Object objVal, String value, PATTERN_OPTION pattern_opt, Logger log){\r\n int minSize = Integer.parseInt(colParam.getMinSize());\r\n if (minSize > 0 && value.isEmpty()) {\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n DataLocation location = buildLocation(context, object);\r\n reporter.addCheckPointReportError(context, testName, MIN_SIZE, location, value, column);\r\n return;\r\n }\r\n if (objVal instanceof Number || objVal instanceof LocalTime || pattern_opt == PATTERN_OPTION.num) {\r\n long val = Long.parseLong(value);\r\n if (val < minSize) {\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n DataLocation location = buildLocation(context, object);\r\n reporter.addCheckPointReportError(context, testName, MIN_SIZE, location, value, column);\r\n }\r\n } else {\r\n if (value.length() < minSize) {\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n DataLocation location = buildLocation(context, object);\r\n reporter.addCheckPointReportError(context, testName, MIN_SIZE, location, value, column);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void alterPartitionForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, Partition partition, String validWriteIds, long writeId) throws Exception {\n EnvironmentContext environmentContext = new EnvironmentContext();\n updateStatsForTruncate(partition.getParameters(), environmentContext);\n if (!transactionalListeners.isEmpty()) {\n MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_PARTITION, new AlterPartitionEvent(partition, partition, table, true, true, writeId, this));\n }\n if (!listeners.isEmpty()) {\n MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_PARTITION, new AlterPartitionEvent(partition, partition, table, true, true, writeId, this));\n }\n if (writeId > 0) {\n partition.setWriteId(writeId);\n }\n alterHandler.alterPartition(ms, wh, catName, dbName, tableName, null, partition, environmentContext, this, validWriteIds);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected static String buildConnectionUri(String loadBalanceStrategy, String driver, boolean useSSL, String host, String replicas, int port, String dbName, boolean autoReconnect, String urlParams, String dbHaParams) {\n StringBuilder connectionUri = new StringBuilder();\n connectionUri.append(driver);\n connectionUri.append(\"://\");\n connectionUri.append(host);\n if (s_dbHAEnabled) {\n connectionUri.append(\",\");\n connectionUri.append(replicas);\n }\n connectionUri.append(\":\");\n connectionUri.append(port);\n connectionUri.append(\"/\");\n connectionUri.append(dbName);\n connectionUri.append(\"?autoReconnect=\");\n connectionUri.append(autoReconnect);\n if (urlParams != null) {\n connectionUri.append(\"&\");\n connectionUri.append(urlParams);\n }\n if (useSSL) {\n connectionUri.append(\"&useSSL=true\");\n }\n if (s_dbHAEnabled) {\n connectionUri.append(\"&\");\n connectionUri.append(dbHaParams);\n connectionUri.append(\"&loadBalanceStrategy=\");\n connectionUri.append(loadBalanceStrategy);\n }\n connectionUri.append(\"&\");\n connectionUri.append(CONNECTION_PARAMS);\n return connectionUri.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, final Host host, final Host lastHost, final VirtualMachineTemplate template, final String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final String userData, Long userDataId, String userDataDetails, final Boolean isDisplayVm, final String keyboard, final long accountId, final long userId, final ServiceOffering offering, final boolean isIso, final String sshPublicKeys, final LinkedHashMap> networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, final Map customParameters, final Map> extraDhcpOptionMap, final Map dataDiskTemplateToDiskOfferingMap, final Map userVmOVFPropertiesMap, final VirtualMachine.PowerState powerState, final boolean dynamicScalingEnabled, String vmType, final Long rootDiskOfferingId, String sshkeypairs) throws InsufficientCapacityException {\n UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.isOfferHA(), offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), userId, offering.getId(), userData, userDataId, userDataDetails, hostName);\n vm.setUuid(uuidName);\n vm.setDynamicallyScalable(dynamicScalingEnabled);\n Map details = template.getDetails();\n if (details != null && !details.isEmpty()) {\n vm.details.putAll(details);\n }\n if (StringUtils.isNotBlank(sshPublicKeys)) {\n vm.setDetail(VmDetailConstants.SSH_PUBLIC_KEY, sshPublicKeys);\n }\n if (StringUtils.isNotBlank(sshkeypairs)) {\n vm.setDetail(VmDetailConstants.SSH_KEY_PAIR_NAMES, sshkeypairs);\n }\n if (keyboard != null && !keyboard.isEmpty()) {\n vm.setDetail(VmDetailConstants.KEYBOARD, keyboard);\n }\n if (!isImport && isIso) {\n vm.setIsoId(template.getId());\n }\n long guestOSId = template.getGuestOSId();\n GuestOSVO guestOS = _guestOSDao.findById(guestOSId);\n long guestOSCategoryId = guestOS.getCategoryId();\n GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);\n if (hypervisorType.equals(HypervisorType.VMware)) {\n updateVMDiskController(vm, customParameters, guestOS);\n }\n Long rootDiskSize = null;\n // custom root disk size, resizes base template to larger size\n if (customParameters.containsKey(VmDetailConstants.ROOT_DISK_SIZE)) {\n // already verified for positive number\n rootDiskSize = Long.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE));\n VMTemplateVO templateVO = _templateDao.findById(template.getId());\n if (templateVO == null) {\n InvalidParameterValueException ipve = new InvalidParameterValueException(\"Unable to look up template by id \" + template.getId());\n ipve.add(VirtualMachine.class, vm.getUuid());\n throw ipve;\n }\n validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);\n }\n if (isDisplayVm != null) {\n vm.setDisplayVm(isDisplayVm);\n } else {\n vm.setDisplayVm(true);\n }\n setVmRequiredFieldsForImport(isImport, vm, zone, hypervisorType, host, lastHost, powerState);\n setVncPasswordForKvmIfAvailable(customParameters, vm);\n vm.setUserVmType(vmType);\n _vmDao.persist(vm);\n for (String key : customParameters.keySet()) {\n // BIOS was explicitly passed as the boot type, so honour it\n if (key.equalsIgnoreCase(ApiConstants.BootType.BIOS.toString())) {\n vm.details.remove(ApiConstants.BootType.UEFI.toString());\n continue;\n }\n // Deploy as is, Don't care about the boot type or template settings\n if (key.equalsIgnoreCase(ApiConstants.BootType.UEFI.toString()) && template.isDeployAsIs()) {\n vm.details.remove(ApiConstants.BootType.UEFI.toString());\n continue;\n }\n if (!hypervisorType.equals(HypervisorType.KVM)) {\n if (key.equalsIgnoreCase(VmDetailConstants.IOTHREADS)) {\n vm.details.remove(VmDetailConstants.IOTHREADS);\n continue;\n }\n if (key.equalsIgnoreCase(VmDetailConstants.IO_POLICY)) {\n vm.details.remove(VmDetailConstants.IO_POLICY);\n continue;\n }\n }\n if (key.equalsIgnoreCase(VmDetailConstants.CPU_NUMBER) || key.equalsIgnoreCase(VmDetailConstants.CPU_SPEED) || key.equalsIgnoreCase(VmDetailConstants.MEMORY)) {\n // handle double byte strings.\n vm.setDetail(key, Integer.toString(Integer.parseInt(customParameters.get(key))));\n } else {\n vm.setDetail(key, customParameters.get(key));\n }\n }\n vm.setDetail(VmDetailConstants.DEPLOY_VM, \"true\");\n persistVMDeployAsIsProperties(vm, userVmOVFPropertiesMap);\n List hiddenDetails = new ArrayList<>();\n if (customParameters.containsKey(VmDetailConstants.NAME_ON_HYPERVISOR)) {\n hiddenDetails.add(VmDetailConstants.NAME_ON_HYPERVISOR);\n }\n _vmDao.saveDetails(vm, hiddenDetails);\n if (!isImport) {\n logger.debug(\"Allocating in the DB for vm\");\n DataCenterDeployment plan = new DataCenterDeployment(zone.getId());\n List computeTags = new ArrayList();\n computeTags.add(offering.getHostTag());\n List rootDiskTags = new ArrayList();\n DiskOfferingVO rootDiskOfferingVO = _diskOfferingDao.findById(rootDiskOfferingId);\n rootDiskTags.add(rootDiskOfferingVO.getTags());\n orchestrateVirtualMachineCreate(vm, guestOSCategory, computeTags, rootDiskTags, plan, rootDiskSize, template, hostName, displayName, owner, diskOfferingId, diskSize, offering, isIso, networkNicMap, hypervisorType, extraDhcpOptionMap, dataDiskTemplateToDiskOfferingMap, rootDiskOfferingId);\n }\n CallContext.current().setEventDetails(\"Vm Id: \" + vm.getUuid());\n if (!isImport) {\n if (!offering.isDynamic()) {\n UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());\n } else {\n UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters, vm.isDisplayVm());\n }\n try {\n //Update Resource Count for the given account\n resourceCountIncrement(accountId, isDisplayVm, offering, template);\n } catch (CloudRuntimeException cre) {\n ArrayList epoList = cre.getIdProxyList();\n if (epoList == null || !epoList.stream().anyMatch(e -> e.getUuid().equals(vm.getUuid()))) {\n cre.addProxyObject(vm.getUuid(), ApiConstants.VIRTUAL_MACHINE_ID);\n }\n throw cre;\n }\n }\n return vm;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata){\r\n if (writeQuorumSize < ackQuorumSize) {\r\n throw new IllegalArgumentException(\"Write quorum must be larger than ack quorum\");\r\n }\r\n closeLock.readLock().lock();\r\n try {\r\n if (closed) {\r\n cb.createComplete(BKException.Code.ClientClosedException, null, ctx);\r\n return;\r\n }\r\n new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats).initiateAdv(-1L);\r\n } finally {\r\n closeLock.readLock().unlock();\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, List hostIds, List poolIds, Long limit);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * @param BPartner\n * @param DocumentNo\n * @param DateFrom\n * @param DateTo\n * @param AmtFrom\n * @param AmtTo\n * @param DocType\n * @param TenderType\n * @param AuthCode\n * @return where clause\n */\npublic String getSQLWhere(Integer BPartner, String DocumentNo, Timestamp DateFrom, Timestamp DateTo, BigDecimal AmtFrom, BigDecimal AmtTo, Integer DocType, String TenderType, String AuthCode) {\n StringBuilder sql = new StringBuilder();\n sql.append(\"WHERE p.Processed='Y' AND p.IsReconciled='N'\");\n sql.append(\" AND p.DocStatus IN ('CO','CL','RE','VO') AND p.PayAmt<>0\");\n sql.append(\" AND p.C_BankAccount_ID = ?\");\n sql.append(\" AND NOT EXISTS (SELECT * FROM C_BankStatementLine l WHERE p.C_Payment_ID=l.C_Payment_ID AND l.StmtAmt <> 0)\");\n if (DocType != null)\n sql.append(\" AND p.C_DocType_ID=?\");\n if (TenderType != null && TenderType.toString().length() > 0)\n sql.append(\" AND p.TenderType=?\");\n if (BPartner != null)\n sql.append(\" AND p.C_BPartner_ID=?\");\n if (DocumentNo.length() > 0)\n sql.append(\" AND UPPER(p.DocumentNo) LIKE ?\");\n if (AuthCode.length() > 0)\n sql.append(\" AND p.R_AuthCode LIKE ?\");\n if (AmtFrom != null || AmtTo != null) {\n if (AmtFrom == null && AmtTo != null)\n sql.append(\" AND p.PayAmt <= ?\");\n else if (AmtFrom != null && AmtTo == null)\n sql.append(\" AND p.PayAmt >= ?\");\n else if (AmtFrom != null && AmtTo != null)\n sql.append(\" AND p.PayAmt BETWEEN ? AND ?\");\n }\n if (DateFrom != null || DateTo != null) {\n if (DateFrom == null && DateTo != null)\n sql.append(\" AND TRUNC(p.DateTrx) <= ?\");\n else if (DateFrom != null && DateTo == null)\n sql.append(\" AND TRUNC(p.DateTrx) >= ?\");\n else if (DateFrom != null && DateTo != null)\n sql.append(\" AND TRUNC(p.DateTrx) BETWEEN ? AND ?\");\n }\n if (log.isLoggable(Level.FINE))\n log.fine(sql.toString());\n return sql.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private VolumeVO resizeVolumeInternal(VolumeVO volume, DiskOfferingVO newDiskOffering, Long currentSize, Long newSize, Long newMinIops, Long newMaxIops, Integer newHypervisorSnapshotReserve, boolean shrinkOk) throws ResourceAllocationException {\n UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());\n HypervisorType hypervisorType = _volsDao.getHypervisorType(volume.getId());\n if (userVm != null) {\n if (volume.getVolumeType().equals(Volume.Type.ROOT) && userVm.getPowerState() != VirtualMachine.PowerState.PowerOff && hypervisorType == HypervisorType.VMware) {\n logger.error(\" For ROOT volume resize VM should be in Power Off state.\");\n throw new InvalidParameterValueException(\"VM current state is : \" + userVm.getPowerState() + \". But VM should be in \" + VirtualMachine.PowerState.PowerOff + \" state.\");\n }\n // serialize VM operation\n AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();\n if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {\n // avoid re-entrance\n VmWorkJobVO placeHolder = null;\n placeHolder = createPlaceHolderWork(userVm.getId());\n try {\n return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newHypervisorSnapshotReserve, newDiskOffering != null ? newDiskOffering.getId() : null, shrinkOk);\n } finally {\n _workJobDao.expunge(placeHolder.getId());\n }\n } else {\n Outcome outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newHypervisorSnapshotReserve, newDiskOffering != null ? newDiskOffering.getId() : null, shrinkOk);\n try {\n outcome.get();\n } catch (InterruptedException e) {\n throw new RuntimeException(\"Operation was interrupted\", e);\n } catch (ExecutionException e) {\n throw new RuntimeException(\"Execution exception\", e);\n }\n Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());\n if (jobResult != null) {\n if (jobResult instanceof ConcurrentOperationException) {\n throw (ConcurrentOperationException) jobResult;\n } else if (jobResult instanceof ResourceAllocationException) {\n throw (ResourceAllocationException) jobResult;\n } else if (jobResult instanceof RuntimeException) {\n throw (RuntimeException) jobResult;\n } else if (jobResult instanceof Throwable) {\n throw new RuntimeException(\"Unexpected exception\", (Throwable) jobResult);\n } else if (jobResult instanceof Long) {\n return _volsDao.findById((Long) jobResult);\n }\n }\n return volume;\n }\n }\n return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newHypervisorSnapshotReserve, newDiskOffering != null ? newDiskOffering.getId() : null, shrinkOk);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n *

Reference Page

\n *

\n * Respecifies a rectangular subregion of an existing texel array. No change is made to the internalformat, width, height, depth, or border parameters of\n * the specified texel array, nor is any change made to texel values outside the specified subregion.\n *\n * @param target the texture target.\n * @param level the level-of-detail-number\n * @param xoffset the left coordinate of the texel subregion\n * @param yoffset the bottom coordinate of the texel subregion\n * @param width the subregion width\n * @param height the subregion height\n * @param format the pixel data format.\n * @param type the pixel data type.\n * @param data the pixel data.\n */\npublic void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "public ApiObjectBase createTungstenLoadbalancerHealthMonitor(String projectUuid, String name, String monitorType, int maxRetries, int delay, int timeout, String httpMethod, String urlPath, String expectedCode) {\n try {\n Project project = (Project) getTungstenObject(Project.class, projectUuid);\n LoadbalancerHealthmonitorType loadbalancerHealthmonitorType = new LoadbalancerHealthmonitorType();\n loadbalancerHealthmonitorType.setMonitorType(monitorType);\n loadbalancerHealthmonitorType.setMaxRetries(maxRetries);\n loadbalancerHealthmonitorType.setDelay(delay);\n loadbalancerHealthmonitorType.setAdminState(true);\n loadbalancerHealthmonitorType.setTimeout(timeout);\n if (monitorType.equals(\"HTTP\")) {\n loadbalancerHealthmonitorType.setHttpMethod(httpMethod);\n loadbalancerHealthmonitorType.setUrlPath(urlPath);\n loadbalancerHealthmonitorType.setExpectedCodes(expectedCode);\n }\n LoadbalancerHealthmonitor loadbalancerHealthmonitor = new LoadbalancerHealthmonitor();\n loadbalancerHealthmonitor.setName(name);\n loadbalancerHealthmonitor.setParent(project);\n loadbalancerHealthmonitor.setProperties(loadbalancerHealthmonitorType);\n Status status = apiConnector.create(loadbalancerHealthmonitor);\n status.ifFailure(errorHandler);\n if (status.isSuccess()) {\n return apiConnector.findById(LoadbalancerHealthmonitor.class, loadbalancerHealthmonitor.getUuid());\n } else {\n return null;\n }\n } catch (IOException e) {\n return null;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "/**\n * This method retrieves a list of entity information, {@link TimelineEntity},\n * sorted by the starting timestamp for the entity, descending. The starting\n * timestamp of an entity is a timestamp specified by the client. If it is not\n * explicitly specified, it will be chosen by the store to be the earliest\n * timestamp of the events received in the first put for the entity.\n *\n * @param entityType\n * The type of entities to return (required).\n * @param limit\n * A limit on the number of entities to return. If null, defaults to\n * {@link #DEFAULT_LIMIT}.\n * @param windowStart\n * The earliest start timestamp to retrieve (exclusive). If null,\n * defaults to retrieving all entities until the limit is reached.\n * @param windowEnd\n * The latest start timestamp to retrieve (inclusive). If null,\n * defaults to {@link Long#MAX_VALUE}\n * @param fromId\n * If fromId is not null, retrieve entities earlier than and\n * including the specified ID. If no start time is found for the\n * specified ID, an empty list of entities will be returned. The\n * windowEnd parameter will take precedence if the start time of this\n * entity falls later than windowEnd.\n * @param fromTs\n * If fromTs is not null, ignore entities that were inserted into the\n * store after the given timestamp. The entity's insert timestamp\n * used for this comparison is the store's system time when the first\n * put for the entity was received (not the entity's start time).\n * @param primaryFilter\n * Retrieves only entities that have the specified primary filter. If\n * null, retrieves all entities. This is an indexed retrieval, and no\n * entities that do not match the filter are scanned.\n * @param secondaryFilters\n * Retrieves only entities that have exact matches for all the\n * specified filters in their primary filters or other info. This is\n * not an indexed retrieval, so all entities are scanned but only\n * those matching the filters are returned.\n * @param fieldsToRetrieve\n * Specifies which fields of the entity object to retrieve (see\n * {@link Field}). If the set of fields contains\n * {@link Field#LAST_EVENT_ONLY} and not {@link Field#EVENTS}, the\n * most recent event for each entity is retrieved. If null, retrieves\n * all fields.\n * @return An {@link TimelineEntities} object.\n * @throws IOException\n */\nTimelineEntities getEntities(String entityType, Long limit, Long windowStart, Long windowEnd, String fromId, Long fromTs, NameValuePair primaryFilter, Collection secondaryFilters, EnumSet fieldsToRetrieve, CheckAcl checkAcl) throws IOException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Produces uniformed output of string with context properties\n *\n * @param str Output prefix or {@code null} if empty.\n * @param name0 Property name.\n * @param val0 Property value.\n * @param sens0 Property sensitive flag.\n * @param name1 Property name.\n * @param val1 Property value.\n * @param sens1 Property sensitive flag.\n * @param name2 Property name.\n * @param val2 Property value.\n * @param sens2 Property sensitive flag.\n * @param name3 Property name.\n * @param val3 Property value.\n * @param sens3 Property sensitive flag.\n * @param name4 Property name.\n * @param val4 Property value.\n * @param sens4 Property sensitive flag.\n * @param name5 Property name.\n * @param val5 Property value.\n * @param sens5 Property sensitive flag.\n * @param name6 Property name.\n * @param val6 Property value.\n * @param sens6 Property sensitive flag.\n * @return String presentation.\n */\npublic static String toString(String str, String name0, @Nullable Object val0, boolean sens0, String name1, @Nullable Object val1, boolean sens1, String name2, @Nullable Object val2, boolean sens2, String name3, @Nullable Object val3, boolean sens3, String name4, @Nullable Object val4, boolean sens4, String name5, @Nullable Object val5, boolean sens5, String name6, @Nullable Object val6, boolean sens6) {\n assert name0 != null;\n assert name1 != null;\n assert name2 != null;\n assert name3 != null;\n assert name4 != null;\n assert name5 != null;\n assert name6 != null;\n Object[] propNames = new Object[7];\n Object[] propVals = new Object[7];\n boolean[] propSens = new boolean[7];\n propNames[0] = name0;\n propVals[0] = val0;\n propSens[0] = sens0;\n propNames[1] = name1;\n propVals[1] = val1;\n propSens[1] = sens1;\n propNames[2] = name2;\n propVals[2] = val2;\n propSens[2] = sens2;\n propNames[3] = name3;\n propVals[3] = val3;\n propSens[3] = sens3;\n propNames[4] = name4;\n propVals[4] = val4;\n propSens[4] = sens4;\n propNames[5] = name5;\n propVals[5] = val5;\n propSens[5] = sens5;\n propNames[6] = name6;\n propVals[6] = val6;\n propSens[6] = sens6;\n SBLimitedLength sb = threadLocSB.get();\n boolean newStr = sb.length() == 0;\n try {\n return toStringImpl(str, sb, propNames, propVals, propSens, 7);\n } finally {\n if (newStr)\n sb.reset();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * Sets up the labeler by providing the point-features to label and\n * the area bounds, the labels are to be placed in. Labels are given in\n * a single vector. Labeling is done in order of entrys within this vector.\n * The minimum and maximum label dimensions are given and are not computed within initialization.\n *\n * @param pointfeatures\n * the point-features to be labeled. If pointfeatures is\n * null, no labeling happens at all.\n * @param labelAreaL\n * the left boundary of the labeling area\n * @param labelAreaR\n * the right boundary of the labeling area\n * @param labelAreaT\n * the top boundary of the labeling area\n * @param labelAreaB\n * the bottom boundary of the labeling area\n * @param minLabelWidth\n * the global minimum label width\n * @param minLabelHeight\n * the global minimum label height\n * @param maxLabelWidth\n * the global maximum label width\n * @param maxLabelHeight\n * the global maximum label height\n *\n * @see #loadDataPriority(java.util.Vector, int, int, int, int)\n * @see #loadDataPriority(java.util.Vector, int, int, int, int, float, float, float, float)\n * @see #loadDataStandard(java.util.Vector, int, int, int, int)\n */\npublic void loadDataStandard(final List pointfeatures, final int labelAreaL, final int labelAreaR, final int labelAreaT, final int labelAreaB, final float minLabelWidth, final float minLabelHeight, final float maxLabelWidth, final float maxLabelHeight) {\n if (pointfeatures != null) {\n final List> nLabels = new ArrayList<>();\n nLabels.add(pointfeatures);\n loadDataPriority(nLabels, labelAreaL, labelAreaR, labelAreaT, labelAreaB, minLabelWidth, minLabelHeight, maxLabelWidth, maxLabelHeight);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "wolfgang-ch_mytourbook", "language": "java"} {"function": "public static ObligeeData instance(final String firstName, final String lastName, final String displayName, final String accountNumber, final BigDecimal loanAmount, final BigDecimal guaranteeAmount, final BigDecimal amountReleased, final BigDecimal amountTransferred) {\n return new ObligeeData(firstName, lastName, displayName, accountNumber, loanAmount, guaranteeAmount, amountReleased, amountTransferred);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static ConsequenceBuilder._14 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14){\r\n return new ConsequenceBuilder._14(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ExprViewItem expr(String exprId, Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Variable var11, Predicate11 predicate){\r\n return new Expr11ViewItemImpl<>(exprId, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, new Predicate11.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": " static ChannelReadyForAddEntryCallback create(BookieClientImpl bookieClient, ReferenceCounted toSend, long ledgerId, long entryId, BookieId addr, Object ctx, WriteCallback cb, int options, byte[] masterKey, boolean allowFastFail, EnumSet writeFlags){\r\n ChannelReadyForAddEntryCallback callback = RECYCLER.get();\r\n callback.bookieClient = bookieClient;\r\n callback.toSend = toSend;\r\n callback.ledgerId = ledgerId;\r\n callback.entryId = entryId;\r\n callback.addr = addr;\r\n callback.ctx = ctx;\r\n callback.cb = cb;\r\n callback.options = options;\r\n callback.masterKey = masterKey;\r\n callback.allowFastFail = allowFastFail;\r\n callback.writeFlags = writeFlags;\r\n return callback;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * deploys a new VM from a ovf spec. It ignores network, defaults locale to 'US'\n * @throws Exception should be a VmwareResourceException\n */\npublic static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost, String configurationId) throws CloudRuntimeException, IOException {\n assert (morRp != null);\n OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();\n importSpecParams.setHostSystem(morHost);\n importSpecParams.setLocale(\"US\");\n importSpecParams.setEntityName(vmName);\n String deploymentOption = StringUtils.isNotBlank(configurationId) ? configurationId : \"\";\n importSpecParams.setDeploymentOption(deploymentOption);\n // diskOption: thin, thick, etc\n importSpecParams.setDiskProvisioning(diskOption);\n String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));\n VmwareContext context = host.getContext();\n OvfCreateImportSpecResult ovfImportResult = null;\n try {\n ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);\n } catch (ConcurrentAccessFaultMsg | FileFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidStateFaultMsg | RuntimeFaultFaultMsg | TaskInProgressFaultMsg | VmConfigFaultFaultMsg error) {\n throw new CloudRuntimeException(\"ImportSpec creation failed\", error);\n }\n if (ovfImportResult == null) {\n String msg = \"createImportSpec() failed. ovfFilePath: \" + ovfFilePath + \", vmName: \" + vmName + \", diskOption: \" + diskOption;\n LOGGER.error(msg);\n throw new CloudRuntimeException(msg);\n }\n if (!ovfImportResult.getError().isEmpty()) {\n for (LocalizedMethodFault fault : ovfImportResult.getError()) {\n LOGGER.error(\"createImportSpec error: \" + fault.getLocalizedMessage());\n }\n throw new CloudRuntimeException(\"Failed to create an import spec from \" + ovfFilePath + \". Check log for details.\");\n }\n if (!ovfImportResult.getWarning().isEmpty()) {\n for (LocalizedMethodFault fault : ovfImportResult.getError()) {\n LOGGER.warn(\"createImportSpec warning: \" + fault.getLocalizedMessage());\n }\n }\n DatacenterMO dcMo = null;\n try {\n dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());\n } catch (Exception e) {\n throw new CloudRuntimeException(String.format(\"no datacenter for host '%s' available in context\", context.getServerAddress()), e);\n }\n ManagedObjectReference folderMO = null;\n try {\n folderMO = dcMo.getVmFolder();\n } catch (Exception e) {\n throw new CloudRuntimeException(\"no management handle for VmFolder\", e);\n }\n ManagedObjectReference morLease = null;\n try {\n morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), folderMO, morHost);\n } catch (DuplicateNameFaultMsg | FileFaultFaultMsg | InsufficientResourcesFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidNameFaultMsg | OutOfBoundsFaultMsg | RuntimeFaultFaultMsg | VmConfigFaultFaultMsg fault) {\n throw new CloudRuntimeException(\"import vApp failed\", fault);\n }\n if (morLease == null) {\n String msg = \"importVApp() failed. ovfFilePath: \" + ovfFilePath + \", vmName: \" + vmName + \", diskOption: \" + diskOption;\n LOGGER.error(msg);\n throw new CloudRuntimeException(msg);\n }\n boolean importSuccess = true;\n final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);\n HttpNfcLeaseState state = null;\n try {\n state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });\n } catch (Exception e) {\n throw new CloudRuntimeException(\"exception while waiting for leaseMO\", e);\n }\n try {\n if (state == HttpNfcLeaseState.READY) {\n final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);\n File ovfFile = new File(ovfFilePath);\n HttpNfcLeaseInfo httpNfcLeaseInfo = null;\n try {\n httpNfcLeaseInfo = leaseMo.getLeaseInfo();\n } catch (Exception e) {\n throw new CloudRuntimeException(\"error waiting for lease info\", e);\n }\n List deviceUrls = httpNfcLeaseInfo.getDeviceUrl();\n long bytesAlreadyWritten = 0;\n final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();\n try {\n for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {\n String deviceKey = deviceUrl.getImportKey();\n for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {\n if (deviceKey.equals(ovfFileItem.getDeviceId())) {\n String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();\n LOGGER.info(\"Uploading file: \" + absoluteFile);\n File f = new File(absoluteFile);\n if (f.exists()) {\n String urlToPost = deviceUrl.getUrl();\n urlToPost = resolveHostNameInUrl(dcMo, urlToPost);\n context.uploadVmdkFile(ovfFileItem.isCreate() ? \"PUT\" : \"POST\", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate() {\n\n @Override\n public void action(Long param) {\n progressReporter.reportProgress((int) (param * 100 / totalBytes));\n }\n });\n bytesAlreadyWritten += ovfFileItem.getSize();\n }\n }\n }\n }\n } catch (Exception e) {\n String erroMsg = \"File upload task failed to complete due to: \" + e.getMessage();\n LOGGER.error(erroMsg);\n // Set flag to cleanup the stale template left due to failed import operation, if any\n importSuccess = false;\n throw new CloudRuntimeException(erroMsg, e);\n } catch (Throwable th) {\n String errorMsg = \"throwable caught during file upload task: \" + th.getMessage();\n LOGGER.error(errorMsg);\n // Set flag to cleanup the stale template left due to failed import operation, if any\n importSuccess = false;\n throw new CloudRuntimeException(errorMsg, th);\n } finally {\n progressReporter.close();\n }\n if (bytesAlreadyWritten == totalBytes) {\n try {\n leaseMo.updateLeaseProgress(100);\n } catch (Exception e) {\n throw new CloudRuntimeException(\"error while waiting for lease update\", e);\n }\n }\n } else if (state == HttpNfcLeaseState.ERROR) {\n LocalizedMethodFault error = null;\n try {\n error = leaseMo.getLeaseError();\n } catch (Exception e) {\n throw new CloudRuntimeException(\"error getting lease error\", e);\n }\n MethodFault fault = error.getFault();\n String erroMsg = \"Object creation on vCenter failed due to: Exception: \" + fault.getClass().getName() + \", message: \" + error.getLocalizedMessage();\n LOGGER.error(erroMsg);\n throw new CloudRuntimeException(erroMsg);\n }\n } finally {\n try {\n if (!importSuccess) {\n LOGGER.error(\"Aborting the lease on \" + vmName + \" after import operation failed.\");\n leaseMo.abortLease();\n } else {\n leaseMo.completeLease();\n }\n } catch (Exception e) {\n throw new CloudRuntimeException(\"error completing lease\", e);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan, String hypervLabel, String ovm3label);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public HiveSession createSession(SessionHandle sessionHandle, TProtocolVersion protocol, String username, String password, String ipAddress, Map sessionConf, boolean withImpersonation, String delegationToken) throws HiveSQLException {\n // Check the flag opportunistically.\n synchronized (sessionAddLock) {\n if (!allowSessions) {\n throw new HiveSQLException(INACTIVE_ERROR_MESSAGE);\n }\n }\n // Do the expensive operations outside of any locks; we'll recheck the flag again at the end.\n // if client proxies connection, use forwarded ip-addresses instead of just the gateway\n final List forwardedAddresses = getForwardedAddresses();\n incrementConnections(username, ipAddress, forwardedAddresses);\n HiveSession session;\n // If doAs is set to true for HiveServer2, we will create a proxy object for the session impl.\n // Within the proxy object, we wrap the method call in a UserGroupInformation#doAs\n if (withImpersonation) {\n HiveSessionImplwithUGI hiveSessionUgi;\n if (sessionImplWithUGIclassName == null) {\n hiveSessionUgi = new HiveSessionImplwithUGI(sessionHandle, protocol, username, password, hiveConf, ipAddress, delegationToken, forwardedAddresses);\n } else {\n try {\n Class clazz = Class.forName(sessionImplWithUGIclassName);\n Constructor constructor = clazz.getConstructor(SessionHandle.class, TProtocolVersion.class, String.class, String.class, HiveConf.class, String.class, String.class, List.class);\n hiveSessionUgi = (HiveSessionImplwithUGI) constructor.newInstance(sessionHandle, protocol, username, password, hiveConf, ipAddress, delegationToken, forwardedAddresses);\n } catch (Exception e) {\n throw new HiveSQLException(\"Cannot initialize session class:\" + sessionImplWithUGIclassName);\n }\n }\n session = HiveSessionProxy.getProxy(hiveSessionUgi, hiveSessionUgi.getSessionUgi());\n hiveSessionUgi.setProxySession(session);\n } else {\n if (sessionImplclassName == null) {\n session = new HiveSessionImpl(sessionHandle, protocol, username, password, hiveConf, ipAddress, forwardedAddresses);\n } else {\n try {\n Class clazz = Class.forName(sessionImplclassName);\n Constructor constructor = clazz.getConstructor(SessionHandle.class, TProtocolVersion.class, String.class, String.class, HiveConf.class, String.class, List.class);\n session = (HiveSession) constructor.newInstance(sessionHandle, protocol, username, password, hiveConf, ipAddress, forwardedAddresses);\n } catch (Exception e) {\n throw new HiveSQLException(\"Cannot initialize session class:\" + sessionImplclassName, e);\n }\n }\n }\n session.setSessionManager(this);\n session.setOperationManager(operationManager);\n try {\n session.open(sessionConf);\n } catch (Exception e) {\n LOG.warn(\"Failed to open session\", e);\n try {\n session.close();\n } catch (Throwable t) {\n LOG.warn(\"Error closing session\", t);\n }\n session = null;\n throw new HiveSQLException(\"Failed to open new session: \" + e.getMessage(), e);\n }\n if (isOperationLogEnabled) {\n session.setOperationLogSessionDir(operationLogRootDir);\n }\n try {\n executeSessionHooks(session);\n } catch (Exception e) {\n LOG.warn(\"Failed to execute session hooks\", e);\n try {\n session.close();\n } catch (Throwable t) {\n LOG.warn(\"Error closing session\", t);\n }\n session = null;\n throw new HiveSQLException(\"Failed to execute session hooks: \" + e.getMessage(), e);\n }\n boolean isAdded = false;\n synchronized (sessionAddLock) {\n if (allowSessions) {\n handleToSession.put(session.getSessionHandle(), session);\n isAdded = true;\n }\n }\n if (!isAdded) {\n try {\n closeSessionInternal(session);\n } catch (Exception e) {\n LOG.warn(\"Failed to close the session opened during an HA state change; ignoring\", e);\n }\n throw new HiveSQLException(FAIL_CLOSE_ERROR_MESSAGE);\n }\n LOG.info(\"Session opened, \" + session.getSessionHandle() + \", current sessions:\" + getOpenSessionCount());\n return session;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void addParameterAnnotation(final int parameter, final String desc, final boolean visible, final List nameRU, final List tags, final List values, final List caseArrayN, final List nestTypeRS, final List nestNameRU, final List nestPairN){\r\n if (visible) {\r\n if (tempMethodRVPA == null) {\r\n tempMethodRVPA = new TempParamAnnotation(numMethodArgs);\r\n tempMethodRVPA.addParameterAnnotation(parameter, desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n }\r\n final Long flag = tempMethodFlags.remove(tempMethodFlags.size() - 1);\r\n tempMethodFlags.add(Long.valueOf(flag.longValue() | (1 << 23)));\r\n } else {\r\n if (tempMethodRIPA == null) {\r\n tempMethodRIPA = new TempParamAnnotation(numMethodArgs);\r\n tempMethodRIPA.addParameterAnnotation(parameter, desc, nameRU, tags, values, caseArrayN, nestTypeRS, nestNameRU, nestPairN);\r\n }\r\n final Long flag = tempMethodFlags.remove(tempMethodFlags.size() - 1);\r\n tempMethodFlags.add(Long.valueOf(flag.longValue() | (1 << 24)));\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * \tRetrieve/Calculate Current Cost Price\n * \t@param product product\n * \t@param M_AttributeSetInstance_ID asi for batchlot costing level\n * \t@param as accounting schema\n * \t@param AD_Org_ID org for organization costing level\n * \t@param costingMethod AcctSchema.COSTINGMETHOD_*\n * \t@param qty qty\n * \t@param C_OrderLine_ID optional order line\n * \t@param zeroCostsOK zero/no costs are OK\n * \t@param trxName trx\n * \t@return current cost price or null\n */\npublic static BigDecimal getCurrentCost(MProduct product, int M_AttributeSetInstance_ID, MAcctSchema as, int AD_Org_ID, String costingMethod, BigDecimal qty, int C_OrderLine_ID, boolean zeroCostsOK, String trxName) {\n String CostingLevel = product.getCostingLevel(as);\n if (MAcctSchema.COSTINGLEVEL_Client.equals(CostingLevel)) {\n AD_Org_ID = 0;\n M_AttributeSetInstance_ID = 0;\n } else if (MAcctSchema.COSTINGLEVEL_Organization.equals(CostingLevel))\n M_AttributeSetInstance_ID = 0;\n else if (MAcctSchema.COSTINGLEVEL_BatchLot.equals(CostingLevel))\n AD_Org_ID = 0;\n //\tCosting Method\n if (costingMethod == null) {\n costingMethod = product.getCostingMethod(as);\n if (costingMethod == null) {\n throw new IllegalArgumentException(\"No Costing Method\");\n }\n }\n //\tCreate/Update Costs\n MCostDetail.processProduct(product, trxName);\n return getCurrentCost(product, M_AttributeSetInstance_ID, as, AD_Org_ID, as.getM_CostType_ID(), costingMethod, qty, C_OrderLine_ID, zeroCostsOK, trxName);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private UserVm importKvmVirtualMachineFromDisk(final ImportSource importSource, final String instanceName, final DataCenter zone, final VirtualMachineTemplate template, final String displayName, final String hostName, final Account caller, final Account owner, final Long userId, final ServiceOfferingVO serviceOffering, final Map dataDiskOfferingMap, final Long networkId, final Long hostId, final Long poolId, final String diskPath, final Map details) throws InsufficientCapacityException, ResourceAllocationException {\n UserVm userVm = null;\n Map allDetails = new HashMap<>(details);\n VirtualMachine.PowerState powerState = VirtualMachine.PowerState.PowerOff;\n NetworkVO network = networkDao.findById(networkId);\n if (network == null) {\n throw new InvalidParameterValueException(\"Unable to find network by id \" + networkId);\n }\n networkModel.checkNetworkPermissions(owner, network);\n // don't allow to use system networks\n NetworkOffering networkOffering = entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());\n if (networkOffering.isSystemOnly()) {\n throw new InvalidParameterValueException(\"Network id=\" + networkId + \" is system only and can't be used for vm deployment\");\n }\n LinkedHashMap> networkNicMap = new LinkedHashMap<>();\n if ((network.getDataCenterId() != zone.getId())) {\n if (!network.isStrechedL2Network()) {\n throw new InvalidParameterValueException(\"Network id=\" + network.getId() + \" doesn't belong to zone \" + zone.getId());\n }\n }\n String macAddress = networkModel.getNextAvailableMacAddressInNetwork(networkId);\n String ipAddress = null;\n if (network.getGuestType() != Network.GuestType.L2) {\n ipAddress = ipAddressManager.acquireGuestIpAddress(network, null);\n }\n Network.IpAddresses requestedIpPair = new Network.IpAddresses(ipAddress, null, macAddress);\n NicProfile nicProfile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());\n nicProfile.setOrderIndex(0);\n boolean securityGroupEnabled = false;\n if (networkModel.isSecurityGroupSupportedInNetwork(network)) {\n securityGroupEnabled = true;\n }\n List profiles = networkNicMap.get(network.getUuid());\n if (CollectionUtils.isEmpty(profiles)) {\n profiles = new ArrayList<>();\n }\n profiles.add(nicProfile);\n networkNicMap.put(network.getUuid(), profiles);\n String internalName = getInternalName(owner.getAccountId());\n try {\n userVm = userVmManager.importVM(zone, null, template, internalName, displayName, owner, null, caller, true, null, owner.getAccountId(), userId, serviceOffering, null, hostName, Hypervisor.HypervisorType.KVM, allDetails, powerState, networkNicMap);\n } catch (InsufficientCapacityException ice) {\n logger.error(String.format(\"Failed to import vm name: %s\", instanceName), ice);\n throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ice.getMessage());\n }\n if (userVm == null) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Failed to import vm name: %s\", instanceName));\n }\n DiskOfferingVO diskOffering = diskOfferingDao.findById(serviceOffering.getDiskOfferingId());\n String rootVolumeName = String.format(\"ROOT-%s\", userVm.getId());\n DiskProfile diskProfile = volumeManager.allocateRawVolume(Volume.Type.ROOT, rootVolumeName, diskOffering, null, null, null, userVm, template, owner, null);\n final VirtualMachineProfile profile = new VirtualMachineProfileImpl(userVm, template, serviceOffering, owner, null);\n ServiceOfferingVO dummyOffering = serviceOfferingDao.findById(userVm.getId(), serviceOffering.getId());\n profile.setServiceOffering(dummyOffering);\n DeploymentPlanner.ExcludeList excludeList = new DeploymentPlanner.ExcludeList();\n final DataCenterDeployment plan = new DataCenterDeployment(zone.getId(), null, null, hostId, poolId, null);\n DeployDestination dest = null;\n try {\n dest = deploymentPlanningManager.planDeployment(profile, plan, excludeList, null);\n } catch (Exception e) {\n logger.warn(String.format(\"Import failed for Vm: %s while finding deployment destination\", userVm.getInstanceName()), e);\n cleanupFailedImportVM(userVm);\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Import failed for Vm: %s while finding deployment destination\", userVm.getInstanceName()));\n }\n if (dest == null) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Import failed for Vm: %s. Suitable deployment destination not found\", userVm.getInstanceName()));\n }\n Map storage = dest.getStorageForDisks();\n Volume volume = volumeDao.findById(diskProfile.getVolumeId());\n StoragePool storagePool = storage.get(volume);\n CheckVolumeCommand checkVolumeCommand = new CheckVolumeCommand();\n checkVolumeCommand.setSrcFile(diskPath);\n StorageFilerTO storageTO = new StorageFilerTO(storagePool);\n checkVolumeCommand.setStorageFilerTO(storageTO);\n Answer answer = agentManager.easySend(dest.getHost().getId(), checkVolumeCommand);\n if (!(answer instanceof CheckVolumeAnswer)) {\n cleanupFailedImportVM(userVm);\n throw new CloudRuntimeException(\"Disk not found or is invalid\");\n }\n CheckVolumeAnswer checkVolumeAnswer = (CheckVolumeAnswer) answer;\n if (!checkVolumeAnswer.getResult()) {\n cleanupFailedImportVM(userVm);\n throw new CloudRuntimeException(\"Disk not found or is invalid\");\n }\n diskProfile.setSize(checkVolumeAnswer.getSize());\n List> diskProfileStoragePoolList = new ArrayList<>();\n try {\n long deviceId = 1L;\n if (ImportSource.SHARED == importSource) {\n diskProfileStoragePoolList.add(importKVMSharedDisk(userVm, diskOffering, Volume.Type.ROOT, template, deviceId, poolId, diskPath, diskProfile));\n } else if (ImportSource.LOCAL == importSource) {\n diskProfileStoragePoolList.add(importKVMLocalDisk(userVm, diskOffering, Volume.Type.ROOT, template, deviceId, hostId, diskPath, diskProfile));\n }\n } catch (Exception e) {\n logger.error(String.format(\"Failed to import volumes while importing vm: %s\", instanceName), e);\n cleanupFailedImportVM(userVm);\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Failed to import volumes while importing vm: %s. %s\", instanceName, StringUtils.defaultString(e.getMessage())));\n }\n networkOrchestrationService.importNic(macAddress, 0, network, true, userVm, requestedIpPair, zone, true);\n publishVMUsageUpdateResourceCount(userVm, dummyOffering, template);\n return userVm;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static CacheEventContext createCacheUpdatedEvent(Data dataKey, Data dataValue, Data dataOldValue, long creationTime, long expirationTime, long lastAccessTime, long accessHit, Data expiryPolicy){\r\n return createCacheUpdatedEvent(dataKey, dataValue, dataOldValue, creationTime, expirationTime, lastAccessTime, accessHit, null, MutableOperation.IGNORE_COMPLETION, expiryPolicy);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String doRequest(URI baseURI, String verb, String set, String from, String until, String metadataPrefix, String token, String identifier) throws IOException, URISyntaxException {\n try (CloseableHttpClient httpclient = getCloseableHttpClient()) {\n URIBuilder builder = new URIBuilder();\n builder.setScheme(baseURI.getScheme()).setHost(baseURI.getHost()).setPort(baseURI.getPort()).setPath(baseURI.getPath()).addParameter(\"verb\", verb).addParameters(URLEncodedUtils.parse(baseURI, Charset.defaultCharset()));\n if (identifier != null) {\n builder.addParameter(\"identifier\", identifier);\n }\n if (token != null) {\n builder.addParameter(\"resumptionToken\", token);\n } else {\n if (metadataPrefix != null) {\n builder.addParameter(\"metadataPrefix\", metadataPrefix);\n }\n if (set != null) {\n builder.addParameter(\"set\", set);\n }\n if (from != null) {\n builder.addParameter(\"from\", from);\n }\n if (until != null) {\n builder.addParameter(\"until\", until);\n }\n }\n HttpGet httpget = new HttpGet(builder.build());\n LOG.info(\"Executing request: {} \", httpget);\n // Create a custom response handler\n HttpClientResponseHandler responseHandler = new HttpClientResponseHandler() {\n\n @Override\n public String handleResponse(final ClassicHttpResponse response) throws HttpException, IOException {\n int status = response.getCode();\n if (status >= 200 && status < 300) {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n throw new IOException(\"No response received\");\n }\n return EntityUtils.toString(entity, StandardCharsets.UTF_8);\n } else {\n throw new ClientProtocolException(\"Unexpected response status: \" + status);\n }\n }\n };\n String responseBody = httpclient.execute(httpget, responseHandler);\n LOG.debug(\"Response received: {}\", responseBody);\n return responseBody;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public void generateClientAndService(String definitionPath, String serviceName, String outPath, Filter filter, boolean nullable, boolean isResource, boolean generateServiceType, boolean generateWithoutDataBinding) throws IOException, FormatterException, io.ballerina.openapi.core.exception.BallerinaOpenApiException{\r\n Path srcPath = Paths.get(outPath);\r\n Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath);\r\n List sourceFiles = new ArrayList<>();\r\n Path openAPIPath = Path.of(definitionPath);\r\n OpenAPI openAPIDef = GeneratorUtils.normalizeOpenAPI(openAPIPath, !isResource);\r\n String concatTitle = serviceName.toLowerCase(Locale.ENGLISH);\r\n String srcFile = concatTitle + \"_service.bal\";\r\n OASServiceMetadata oasServiceMetadata = new OASServiceMetadata.Builder().withOpenAPI(openAPIDef).withFilters(filter).withNullable(nullable).withGenerateServiceType(generateServiceType).withGenerateWithoutDataBinding(generateWithoutDataBinding).build();\r\n BallerinaServiceGenerator serviceGenerator = new BallerinaServiceGenerator(oasServiceMetadata);\r\n String serviceContent = Formatter.format(serviceGenerator.generateSyntaxTree()).toSourceCode();\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, srcFile, (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + serviceContent));\r\n if (generateServiceType) {\r\n BallerinaServiceObjectGenerator ballerinaServiceObjectGenerator = new BallerinaServiceObjectGenerator(serviceGenerator.getFunctionList());\r\n String serviceType = Formatter.format(ballerinaServiceObjectGenerator.generateSyntaxTree()).toSourceCode();\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, \"service_type.bal\", (licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : licenseHeader) + serviceType));\r\n }\r\n OASClientConfig.Builder clientMetaDataBuilder = new OASClientConfig.Builder();\r\n OASClientConfig oasClientConfig = clientMetaDataBuilder.withFilters(filter).withNullable(nullable).withPlugin(false).withOpenAPI(openAPIDef).withResourceMode(isResource).build();\r\n BallerinaClientGenerator clientGenerator = new BallerinaClientGenerator(oasClientConfig);\r\n String clientContent = Formatter.format(clientGenerator.generateSyntaxTree()).toSourceCode();\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CLIENT_FILE_NAME, (licenseHeader.isBlank() ? DO_NOT_MODIFY_FILE_HEADER : licenseHeader) + clientContent));\r\n String utilContent = Formatter.format(clientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree()).toString();\r\n if (!utilContent.isBlank()) {\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.UTIL_SRC, srcPackage, UTIL_FILE_NAME, (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + utilContent));\r\n }\r\n List preGeneratedTypeDefNodes = new ArrayList<>(clientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes());\r\n List typeInclusionRecords = serviceGenerator.getTypeInclusionRecords();\r\n List typeDefinitionNodeList = clientGenerator.getTypeDefinitionNodeList();\r\n preGeneratedTypeDefNodes.addAll(typeInclusionRecords);\r\n preGeneratedTypeDefNodes.addAll(typeDefinitionNodeList);\r\n BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(openAPIDef, nullable, preGeneratedTypeDefNodes);\r\n SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree();\r\n String schemaContent = Formatter.format(schemaSyntaxTree).toSourceCode();\r\n if (filter.getTags().size() > 0) {\r\n schemaContent = GeneratorUtils.removeUnusedEntities(schemaSyntaxTree, clientContent, schemaContent, serviceContent);\r\n }\r\n if (!schemaContent.isBlank()) {\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, srcPackage, TYPE_FILE_NAME, (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + schemaContent));\r\n }\r\n if (this.includeTestFiles) {\r\n BallerinaTestGenerator ballerinaTestGenerator = new BallerinaTestGenerator(clientGenerator);\r\n String testContent = Formatter.format(ballerinaTestGenerator.generateSyntaxTree()).toSourceCode();\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, TEST_FILE_NAME, (licenseHeader.isBlank() ? DEFAULT_FILE_HEADER : licenseHeader) + testContent));\r\n String configContent = ballerinaTestGenerator.getConfigTomlFile();\r\n if (!configContent.isBlank()) {\r\n sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, srcPackage, CONFIG_FILE_NAME, configContent));\r\n }\r\n }\r\n List newGenFiles = sourceFiles.stream().filter(distinctByKey(GenSrcFile::getFileName)).collect(Collectors.toList());\r\n writeGeneratedSources(newGenFiles, srcPath, implPath, GEN_BOTH);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create a table metadata and the directory for the table data\n * @param tableName table name\n * @param columns list of fields of the table\n * @param partCols partition keys of the table\n * @param fileInputFormat Class of the input format of the table data file\n * @param fileOutputFormat Class of the output format of the table data file\n * @param bucketCount number of buckets that each partition (or the table itself) should be\n * divided into\n * @param bucketCols Bucket columns\n * @param parameters Parameters for the table\n * @throws HiveException\n */\npublic void createTable(String tableName, List columns, List partCols, Class fileInputFormat, Class fileOutputFormat, int bucketCount, List bucketCols, Map parameters) throws HiveException {\n if (columns == null) {\n throw new HiveException(\"columns not specified for table \" + tableName);\n }\n Table tbl = newTable(tableName);\n tbl.setInputFormatClass(fileInputFormat.getName());\n tbl.setOutputFormatClass(fileOutputFormat.getName());\n for (String col : columns) {\n FieldSchema field = new FieldSchema(col, STRING_TYPE_NAME, \"default\");\n tbl.getCols().add(field);\n }\n if (partCols != null) {\n for (String partCol : partCols) {\n FieldSchema part = new FieldSchema();\n part.setName(partCol);\n // default partition key\n part.setType(STRING_TYPE_NAME);\n tbl.getPartCols().add(part);\n }\n }\n tbl.setSerializationLib(LazySimpleSerDe.class.getName());\n tbl.setNumBuckets(bucketCount);\n tbl.setBucketCols(bucketCols);\n if (parameters != null) {\n tbl.setParameters(parameters);\n }\n createTable(tbl);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected DirectTemplateDownloader createDownloaderForMetalinks(String url, Long templateId, String destPoolPath, String checksum, Map headers, Integer connectTimeout, Integer soTimeout, Integer connectionRequestTimeout, String temporaryDownloadPath) {\n if (url.toLowerCase().startsWith(\"https:\")) {\n return new HttpsDirectTemplateDownloader(url, templateId, destPoolPath, checksum, headers, connectTimeout, soTimeout, connectionRequestTimeout, temporaryDownloadPath, this.isFollowRedirects());\n } else if (url.toLowerCase().startsWith(\"http:\")) {\n return new HttpDirectTemplateDownloader(url, templateId, destPoolPath, checksum, headers, connectTimeout, soTimeout, temporaryDownloadPath, this.isFollowRedirects());\n } else if (url.toLowerCase().startsWith(\"nfs:\")) {\n return new NfsDirectTemplateDownloader(url);\n } else {\n logger.error(String.format(\"Cannot find a suitable downloader to handle the metalink URL %s\", url));\n return null;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static MutableTableModify of(RelDataType rowType, MutableRel input, RelOptTable table, Prepare.CatalogReader catalogReader, Operation operation, @Nullable List updateColumnList, @Nullable List sourceExpressionList, boolean flattened){\r\n return new MutableTableModify(rowType, input, table, catalogReader, operation, updateColumnList, sourceExpressionList, flattened);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static LoanTransaction accrueTransaction(final Loan loan, final Office office, final LocalDate dateOf, final BigDecimal amount, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, final BigDecimal penaltyChargesPortion, final ExternalId externalId) {\n BigDecimal principalPortion = null;\n BigDecimal overPaymentPortion = null;\n boolean reversed = false;\n PaymentDetail paymentDetail = null;\n return new LoanTransaction(loan, office, LoanTransactionType.ACCRUAL.getValue(), dateOf, amount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overPaymentPortion, reversed, paymentDetail, externalId);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "// /**\n// * Revokes a firewall rule\n// *\n// * @param ruleId\n// * the id of the rule to revoke.\n// * @param caller\n// * TODO\n// * @param userId\n// * TODO\n// * @return\n// */\n// boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId);\n// FirewallRule createFirewallRule(Long ipAddrId, Account caller, String xId, Integer portStart, Integer portEnd, String protocol, List sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId,\n// FirewallRule.FirewallRuleType type, Long networkId, FirewallRule.TrafficType traffictype)\n// throws NetworkRuleConflictException;\nFirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId, long networkId) throws NetworkRuleConflictException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static boolean fastRemainder(int leftSignum, long leftFast0, long leftFast1, long leftFast2, int leftIntegerDigitCount, int leftScale, int rightSignum, long rightFast0, long rightFast1, long rightFast2, int rightIntegerDigitCount, int rightScale, FastHiveDecimal fastResult) {\n // Arithmetic operations reset the results.\n fastResult.fastReset();\n if (rightSignum == 0) {\n // Division by 0.\n return false;\n }\n if (leftSignum == 0) {\n // Zero result.\n return true;\n }\n BigDecimal denominator = fastBigDecimalValue(leftSignum, leftFast0, leftFast1, leftFast2, leftIntegerDigitCount, leftScale);\n BigDecimal divisor = fastBigDecimalValue(rightSignum, rightFast0, rightFast1, rightFast2, rightIntegerDigitCount, rightScale);\n BigDecimal remainder = denominator.remainder(divisor);\n fastResult.fastReset();\n if (!fastSetFromBigDecimal(remainder, true, fastResult)) {\n return false;\n }\n return true;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * @param message\n * @param lookup\n * @param editorType\n * @param callback\n * @param desktop\n * @param windowNo\n * @param title\n * @param defaultValue\n */\npublic static void askForInput(final String message, MLookup lookup, int editorType, final Callback callback, Desktop desktop, int windowNo, String title, Object defaultValue) {\n final WEditor weditor = getEditor(lookup, editorType);\n if (weditor != null && defaultValue != null)\n weditor.setValue(defaultValue);\n Executions.schedule(desktop, new EventListener() {\n\n @Override\n public void onEvent(Event event) throws Exception {\n Dialog.askForInput(windowNo, weditor, message, title, callback);\n }\n }, new Event(\"onAskForInput\"));\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public ExecutionOutboxEntry upsert(final UUID interactionId, final int sequence, final ExecutionOutboxEntryType executionType, final Timestamp startedAt, final String username, final Bookmark target, final String logicalMemberIdentifier, final String xml){\r\n return upsert(interactionId, sequence, executionType, startedAt, username, target, logicalMemberIdentifier, InteractionDtoUtils.dtoMapper().read(xml));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Builds consent string according to consent API. This string can be used as the body of add receipt API\n *\n * @param username Username of the user.\n * @param consent Consent String which contains services.\n * @param jurisdiction Jurisdiction.\n * @param collectionMethod Collection Method.\n * @param language Language.\n * @param policyURL Policy URL.\n * @param consentType Consent Type.\n * @param isPrimaryPurpose Whether this this receipt is for primary purpose.\n * @param isThirdPartyDisclosure Whether this receipt can be disclosed to thrid parties.\n * @param termination Termination date.\n * @return Consent string which contains above facts.\n */\npublic static String buildConsentForResidentIDP(String username, String consent, String jurisdiction, String collectionMethod, String language, String policyURL, String consentType, boolean isPrimaryPurpose, boolean isThirdPartyDisclosure, String termination) {\n if (StringUtils.isEmpty(consent)) {\n if (log.isDebugEnabled()) {\n log.debug(\"Empty consent string. Hence returning without building consent from endpoint\");\n }\n return consent;\n }\n String piiPrincipalId = getPiiPrincipalID(username);\n JSONObject receipt = new JSONObject(consent);\n receipt.put(IdentityManagementEndpointConstants.Consent.JURISDICTION_KEY, jurisdiction);\n receipt.put(IdentityManagementEndpointConstants.Consent.COLLECTION_METHOD_KEY, collectionMethod);\n receipt.put(IdentityManagementEndpointConstants.Consent.LANGUAGE_KEY, language);\n receipt.put(IdentityManagementEndpointConstants.Consent.PII_PRINCIPAL_ID_KEY, piiPrincipalId);\n receipt.put(IdentityManagementEndpointConstants.Consent.POLICY_URL_KEY, policyURL);\n buildServices(receipt, consentType, isPrimaryPurpose, isThirdPartyDisclosure, termination);\n if (log.isDebugEnabled()) {\n log.debug(\"Built consent from endpoint util : \" + consent);\n }\n return receipt.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private void newMember(final ApplicationFeatureId typeFeatureId, final String memberId, @NonNull final ApplicationMemberSort memberSort, @Nullable final Class returnType, final Boolean derived, @Nullable final Integer maxLength, @Nullable final Integer typicalLength, @Nullable final SemanticsOf actionSemantics){\r\n final ApplicationFeatureId featureId = ApplicationFeatureId.newMember(typeFeatureId.getFullyQualifiedName(), memberId);\r\n final ApplicationFeatureDefault memberFeature = (ApplicationFeatureDefault) newApplicationFeature(featureId);\r\n memberFeature.setMemberSort(Optional.of(memberSort));\r\n memberFeature.setActionReturnType(Optional.ofNullable(returnType));\r\n memberFeature.setActionSemantics(Optional.ofNullable(actionSemantics));\r\n memberFeature.setPropertyOrCollectionDerived(Boolean.TRUE.equals(derived));\r\n memberFeature.setPropertyMaxLength(maxLength != null ? OptionalInt.of(maxLength) : OptionalInt.empty());\r\n memberFeature.setPropertyTypicalLength(typicalLength != null ? OptionalInt.of(typicalLength) : OptionalInt.empty());\r\n memberFeatures.put(featureId, memberFeature);\r\n featuresMapFor(memberSort).put(featureId, memberFeature);\r\n final ApplicationFeatureDefault typeFeature = (ApplicationFeatureDefault) findLogicalType(typeFeatureId);\r\n typeFeature.addToMembers(featureId, memberSort);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param io Data page IO.\n * @param pageAddr Data page address.\n * @param itemId Row item Id.\n * @param grp Cache group.\n * @param sharedCtx Cache shared context.\n * @param pageMem Page memory.\n * @param rowData Required row data.\n * @param skipVer Whether version read should be skipped.\n * @throws IgniteCheckedException If failed.\n */\npublic final void initFromDataPage(DataPageIO io, long pageAddr, int itemId, @Nullable CacheGroupContext grp, GridCacheSharedContext sharedCtx, PageMemory pageMem, RowData rowData, boolean skipVer) throws IgniteCheckedException {\n // Group is null if try evict page, with persistence evictions should be disabled.\n assert grp != null || pageMem instanceof PageMemoryNoStoreImpl;\n CacheObjectContext coctx = grp != null ? grp.cacheObjectContext() : null;\n boolean readCacheId = grp == null || grp.storeCacheIdInDataPage();\n int grpId = grp != null ? grp.groupId() : 0;\n IoStatisticsHolder statHolder = grp != null ? grp.statisticsHolderData() : IoStatisticsHolderNoOp.INSTANCE;\n IncompleteObject incomplete = readIncomplete(null, sharedCtx, coctx, pageMem.pageSize(), pageMem.realPageSize(grpId), pageAddr, itemId, io, rowData, readCacheId, skipVer);\n if (incomplete != null) {\n // Initialize the remaining part of the large row from other pages.\n long nextLink = incomplete.getNextLink();\n if (nextLink != 0L) {\n doInitFromLink(nextLink, sharedCtx, coctx, pageMem, grpId, statHolder, readCacheId, rowData, incomplete, skipVer);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * Persists VPC record in the database\n *\n * @param zoneId\n * @param vpcOffId\n * @param vpcOwnerId\n * @param vpcName\n * @param displayText\n * @param cidr\n * @param networkDomain TODO\n * @param ip4Dns1\n * @param ip4Dns2\n * @param displayVpc TODO\n * @return\n * @throws ResourceAllocationException TODO\n */\nVpc createVpc(long zoneId, long vpcOffId, long vpcOwnerId, String vpcName, String displayText, String cidr, String networkDomain, String ip4Dns1, String ip4Dns2, String ip6Dns1, String ip6Dns2, Boolean displayVpc, Integer publicMtu, Integer cidrSize, Long asNumber, List bgpPeerIds) throws ResourceAllocationException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static AccountTransferData instance(final Long id, final Boolean reversed, final LocalDate transferDate, final CurrencyData currency, final BigDecimal transferAmount, final String transferDescription, final OfficeData fromOffice, final OfficeData toOffice, final ClientData fromClient, final ClientData toClient, final EnumOptionData fromAccountType, final PortfolioAccountData fromAccount, final EnumOptionData toAccountType, final PortfolioAccountData toAccount) {\n return new AccountTransferData(id, reversed, fromOffice, fromClient, fromAccountType, fromAccount, currency, transferAmount, transferDate, transferDescription, toOffice, toClient, toAccountType, toAccount, null, null, null, null, null, null, null, null);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Create a readable and parseable audit log string for a successful event.\n *\n * @param user User who made the service request to the ResourceManager\n * @param operation Operation requested by the user.\n * @param target The target on which the operation is being performed.\n * @param appId Application Id in which operation was performed.\n * @param containerId Container Id in which operation was performed.\n * @param resource Resource associated with container.\n * @param queueName Name of queue.\n * @param partition Name of labeled partition.\n *\n *

\n * Note that the {@link RMAuditLogger} uses tabs ('\\t') as a key-val delimiter\n * and hence the value fields should not contains tabs ('\\t').\n */\npublic static void logSuccess(String user, String operation, String target, ApplicationId appId, ContainerId containerId, Resource resource, String queueName, String partition) {\n if (LOG.isInfoEnabled()) {\n LOG.info(createSuccessLog(user, operation, target, appId, null, containerId, resource, null, Server.getRemoteIp(), queueName, partition));\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//\tcreatePayment\n/**\n * \tCreate actual Payment\n * \t@param C_Invoice_ID invoice\n * \t@param C_BPartner_ID partner ignored when invoice exists\n * \t@param C_Currency_ID currency\n * \t@param StmtAmt statement amount\n * \t@param TrxAmt transaction amt\n * \t@param C_BankAccount_ID bank account\n * \t@param DateTrx transaction date\n * \t@param DateAcct\taccounting date\n * \t@param Description description\n * \t@param AD_Org_ID org\n * \t@return payment\n */\nprivate MPayment createPayment(int C_Invoice_ID, int C_BPartner_ID, int C_Currency_ID, BigDecimal StmtAmt, BigDecimal TrxAmt, int C_BankAccount_ID, Timestamp DateTrx, Timestamp DateAcct, String Description, int AD_Org_ID) {\n //\tTrx Amount = Payment overwrites Statement Amount if defined\n BigDecimal PayAmt = TrxAmt;\n if (PayAmt == null || Env.ZERO.compareTo(PayAmt) == 0)\n PayAmt = StmtAmt;\n if (C_Invoice_ID == 0 && (PayAmt == null || Env.ZERO.compareTo(PayAmt) == 0))\n throw new IllegalStateException(\"@PayAmt@ = 0\");\n if (PayAmt == null)\n PayAmt = Env.ZERO;\n //\n MPayment payment = new MPayment(getCtx(), 0, get_TrxName());\n payment.setAD_Org_ID(AD_Org_ID);\n payment.setC_BankAccount_ID(C_BankAccount_ID);\n payment.setTenderType(MPayment.TENDERTYPE_Check);\n if (DateTrx != null)\n payment.setDateTrx(DateTrx);\n else if (DateAcct != null)\n payment.setDateTrx(DateAcct);\n if (DateAcct != null)\n payment.setDateAcct(DateAcct);\n else\n payment.setDateAcct(payment.getDateTrx());\n payment.setDescription(Description);\n //\n if (C_Invoice_ID != 0) {\n MInvoice invoice = new MInvoice(getCtx(), C_Invoice_ID, null);\n //\tReceipt\n payment.setC_DocType_ID(invoice.isSOTrx());\n payment.setC_Invoice_ID(invoice.getC_Invoice_ID());\n payment.setC_BPartner_ID(invoice.getC_BPartner_ID());\n if (//\texplicit Amount\n PayAmt.signum() != 0) {\n payment.setC_Currency_ID(C_Currency_ID);\n if (invoice.isSOTrx())\n payment.setPayAmt(PayAmt);\n else\n //\tpayment is likely to be negative\n payment.setPayAmt(PayAmt.negate());\n BigDecimal discountAmt = invoice.getDiscountAmt(payment.getDateTrx());\n payment.setDiscountAmt(discountAmt);\n BigDecimal overUnderAmt = invoice.getOpenAmt().subtract(payment.getPayAmt()).subtract(discountAmt);\n payment.setOverUnderAmt(overUnderAmt);\n } else // set Pay Amout from Invoice\n {\n payment.setC_Currency_ID(invoice.getC_Currency_ID());\n payment.setPayAmt(invoice.getOpenAmt());\n }\n } else if (C_BPartner_ID != 0) {\n payment.setC_BPartner_ID(C_BPartner_ID);\n payment.setC_Currency_ID(C_Currency_ID);\n if (//\tPayment\n PayAmt.signum() < 0) {\n payment.setPayAmt(PayAmt.abs());\n payment.setC_DocType_ID(false);\n } else //\tReceipt\n {\n payment.setPayAmt(PayAmt);\n payment.setC_DocType_ID(true);\n }\n } else\n return null;\n payment.saveEx();\n //\n if (!payment.processIt(MPayment.DOCACTION_Complete)) {\n log.warning(\"Payment Process Failed: \" + payment.getDocumentNo() + \" \" + payment.getProcessMsg());\n throw new IllegalStateException(\"Payment Process Failed: \" + payment.getDocumentNo() + \" \" + payment.getProcessMsg());\n }\n payment.saveEx();\n return payment;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private void doCompleteAndCloseLogSegmentAfterLogSegmentListFetched(final String inprogressZnodeName, long logSegmentSeqNo, long logSegmentId, long firstTxId, long lastTxId, int recordCount, long lastEntryId, long lastSlotId, final CompletableFuture promise){\r\n try {\r\n lock.checkOwnershipAndReacquire();\r\n } catch (IOException ioe) {\r\n FutureUtils.completeExceptionally(promise, ioe);\r\n return;\r\n }\r\n LOG.debug(\"Completing and Closing Log Segment {} {}\", firstTxId, lastTxId);\r\n LogSegmentMetadata inprogressLogSegment = readLogSegmentFromCache(inprogressZnodeName);\r\n if (inprogressLogSegment.getLogSegmentId() != logSegmentId) {\r\n FutureUtils.completeExceptionally(promise, new IOException(\"Active ledger has different ID to inprogress. \" + inprogressLogSegment.getLogSegmentId() + \" found, \" + logSegmentId + \" expected\"));\r\n return;\r\n }\r\n if (inprogressLogSegment.getFirstTxId() != firstTxId) {\r\n FutureUtils.completeExceptionally(promise, new IOException(\"Transaction id not as expected, \" + inprogressLogSegment.getFirstTxId() + \" found, \" + firstTxId + \" expected\"));\r\n return;\r\n }\r\n if (validateLogSegmentSequenceNumber) {\r\n synchronized (inprogressLSSNs) {\r\n if (inprogressLSSNs.isEmpty()) {\r\n FutureUtils.completeExceptionally(promise, new UnexpectedException(\"Didn't find matched inprogress log segments when completing inprogress \" + inprogressLogSegment));\r\n return;\r\n }\r\n long leastInprogressLSSN = inprogressLSSNs.getFirst();\r\n if ((inprogressLogSegment.getLogSegmentSequenceNumber() != logSegmentSeqNo) || (leastInprogressLSSN != logSegmentSeqNo)) {\r\n FutureUtils.completeExceptionally(promise, new UnexpectedException(\"Didn't find matched inprogress log segments when completing inprogress \" + inprogressLogSegment));\r\n return;\r\n }\r\n }\r\n }\r\n long maxSeqNo = Math.max(logSegmentSeqNo, maxLogSegmentSequenceNo.getSequenceNumber());\r\n if (maxLogSegmentSequenceNo.getSequenceNumber() == logSegmentSeqNo || (maxLogSegmentSequenceNo.getSequenceNumber() == logSegmentSeqNo + 1)) {\r\n LOG.info(\"Try storing max sequence number {} in completing {}.\", new Object[] { logSegmentSeqNo, inprogressLogSegment.getZkPath() });\r\n } else {\r\n LOG.warn(\"Unexpected max ledger sequence number {} found while completing log segment {} for {}\", maxLogSegmentSequenceNo.getSequenceNumber(), logSegmentSeqNo, getFullyQualifiedName());\r\n if (validateLogSegmentSequenceNumber) {\r\n FutureUtils.completeExceptionally(promise, new DLIllegalStateException(\"Unexpected max log segment sequence number \" + maxLogSegmentSequenceNo.getSequenceNumber() + \" for \" + getFullyQualifiedName() + \", expected \" + (logSegmentSeqNo - 1)));\r\n return;\r\n }\r\n }\r\n final String pathForCompletedLedger = completedLedgerZNode(firstTxId, lastTxId, logSegmentSeqNo);\r\n long startSequenceId;\r\n try {\r\n startSequenceId = computeStartSequenceId(inprogressLogSegment);\r\n } catch (IOException ioe) {\r\n FutureUtils.completeExceptionally(promise, ioe);\r\n return;\r\n }\r\n final LogSegmentMetadata completedLogSegment = inprogressLogSegment.completeLogSegment(pathForCompletedLedger, lastTxId, recordCount, lastEntryId, lastSlotId, startSequenceId);\r\n setLastLedgerRollingTimeMillis(completedLogSegment.getCompletionTime());\r\n Transaction txn = streamMetadataStore.newTransaction();\r\n writeLogSegment(txn, completedLogSegment);\r\n deleteLogSegment(txn, inprogressLogSegment);\r\n storeMaxSequenceNumber(txn, maxLogSegmentSequenceNo, maxSeqNo, false);\r\n LOG.debug(\"Trying storing LastTxId in Finalize Path {} LastTxId {}\", pathForCompletedLedger, lastTxId);\r\n storeMaxTxId(txn, maxTxId, lastTxId);\r\n txn.execute().whenCompleteAsync(new FutureEventListener() {\r\n\r\n @Override\r\n public void onSuccess(Void value) {\r\n LOG.info(\"Completed {} to {} for {} : {}\", inprogressZnodeName, completedLogSegment.getSegmentName(), getFullyQualifiedName(), completedLogSegment);\r\n FutureUtils.complete(promise, completedLogSegment);\r\n }\r\n\r\n @Override\r\n public void onFailure(Throwable cause) {\r\n FutureUtils.completeExceptionally(promise, cause);\r\n }\r\n }, scheduler);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public EnqueueBean run(String user, Map userArgs, String jar, String mainClass, String libjars, String files, List jarArgs, List defines, String statusdir, String callback, boolean usesHcatalog, String completedUrl, boolean enablelog, Boolean enableJobReconnect, JobType jobType) throws NotAuthorizedException, BadParam, BusyException, QueueException, ExecuteException, IOException, InterruptedException, TooManyRequestsException{\r\n runAs = user;\r\n List args = makeArgs(jar, mainClass, libjars, files, jarArgs, defines, statusdir, usesHcatalog, completedUrl, enablelog, enableJobReconnect, jobType);\r\n return enqueueController(user, userArgs, callback, args);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create set/get methods for column\n *\n * @param mandatory init call for mandatory columns\n * @param columnName column name\n * @param isUpdateable updateable\n * @param isMandatory mandatory\n * @param displayType display type\n * @param AD_Reference_ID validation reference\n * @param fieldLength int\n * @param defaultValue default value\n * @param ValueMin String\n * @param ValueMax String\n * @param VFormat String\n * @param Callout String\n * @param Name String\n * @param Description String\n * @param virtualColumn virtual column\n * @param IsEncrypted stored encrypted\n * @return set/get method\n */\nprivate String createColumnMethods(StringBuilder mandatory, String columnName, boolean isUpdateable, boolean isMandatory, int displayType, int AD_Reference_ID, int fieldLength, String defaultValue, String ValueMin, String ValueMax, String VFormat, String Callout, String Name, String Description, boolean virtualColumn, boolean IsEncrypted, boolean IsKey, int AD_Table_ID) {\n Class clazz = getClass(columnName, displayType, AD_Reference_ID);\n String dataType = getDataTypeName(clazz, displayType);\n if (defaultValue == null)\n defaultValue = \"\";\n StringBuilder sb = new StringBuilder();\n if (isGenerateSetter(columnName)) {\n // Create Java Comment\n generateJavaComment(\"Set\", Name, Description, sb);\n // public void setColumn (xxx variable)\n sb.append(\"\\tpublic void set\").append(columnName).append(\" (\").append(dataType).append(\" \").append(columnName).append(\");\");\n }\n // ****** Get Comment ******\n generateJavaComment(\"Get\", Name, Description, sb);\n sb.append(\"\\tpublic \").append(dataType);\n if (clazz.equals(Boolean.class)) {\n sb.append(\" is\");\n if (columnName.toLowerCase().startsWith(\"is\"))\n sb.append(columnName.substring(2));\n else\n sb.append(columnName);\n } else\n sb.append(\" get\").append(columnName);\n sb.append(\"();\");\n //\n if (isGenerateModelGetter(columnName) && DisplayType.isID(displayType) && !IsKey) {\n String fieldName = getFieldName(columnName);\n String referenceClassName = getReferenceClassName(AD_Table_ID, columnName, displayType, AD_Reference_ID);\n //\n if (fieldName != null && referenceClassName != null) {\n sb.append(\"\\n\").append(\"\\tpublic \" + referenceClassName + \" get\").append(fieldName).append(\"() throws RuntimeException;\");\n }\n }\n addImportClass(clazz);\n return sb.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private static void generateGet(EnumerableRelImplementor implementor, PhysType physType, BlockBuilder builder, ParameterExpression resultSet_, int i, Expression target, @Nullable Expression calendar_, SqlDialect.CalendarPolicy calendarPolicy){\r\n final Primitive primitive = Primitive.ofBoxOr(physType.fieldClass(i));\r\n final RelDataType fieldType = physType.getRowType().getFieldList().get(i).getType();\r\n final List dateTimeArgs = new ArrayList<>();\r\n dateTimeArgs.add(Expressions.constant(i + 1));\r\n SqlTypeName sqlTypeName = fieldType.getSqlTypeName();\r\n boolean offset = false;\r\n switch(calendarPolicy) {\r\n case LOCAL:\r\n assert calendar_ != null : \"calendar must not be null\";\r\n dateTimeArgs.add(calendar_);\r\n break;\r\n case NULL:\r\n break;\r\n case DIRECT:\r\n sqlTypeName = SqlTypeName.ANY;\r\n break;\r\n case SHIFT:\r\n switch(sqlTypeName) {\r\n case TIMESTAMP:\r\n case DATE:\r\n offset = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n final Expression source;\r\n switch(sqlTypeName) {\r\n case DATE:\r\n case TIME:\r\n case TIMESTAMP:\r\n source = Expressions.call(getMethod(sqlTypeName, fieldType.isNullable(), offset), Expressions.list().append(Expressions.call(resultSet_, getMethod2(sqlTypeName), dateTimeArgs)).appendIf(offset, getTimeZoneExpression(implementor)));\r\n break;\r\n case ARRAY:\r\n final Expression x = Expressions.convert_(Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1)), java.sql.Array.class);\r\n source = Expressions.call(BuiltInMethod.JDBC_ARRAY_TO_LIST.method, x);\r\n break;\r\n case NULL:\r\n source = RexImpTable.NULL_EXPR;\r\n break;\r\n default:\r\n source = Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1));\r\n }\r\n builder.add(Expressions.statement(Expressions.assign(target, source)));\r\n if (primitive != null) {\r\n builder.add(Expressions.ifThen(Expressions.call(resultSet_, \"wasNull\"), Expressions.statement(Expressions.assign(target, Expressions.constant(null)))));\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void createUsageRecord(int type, long runningTime, Date startDate, Date endDate, AccountVO account, long volId, long zoneId, Long doId, Long vmId, long size, Long vmSnapshotId) {\n // Our smallest increment is hourly for now\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Total running time \" + runningTime + \"ms\");\n }\n float usage = runningTime / 1000f / 60f / 60f;\n DecimalFormat dFormat = new DecimalFormat(\"#.######\");\n String usageDisplay = dFormat.format(usage);\n LOGGER.debug(\"Creating usage record for VMSnapshot with id [{}], vol [{}], usage [{}], startDate [{}], and endDate [{}], for account [{}].\", vmSnapshotId, volId, usageDisplay, DateUtil.displayDateInTimezone(UsageManagerImpl.getUsageAggregationTimeZone(), startDate), DateUtil.displayDateInTimezone(UsageManagerImpl.getUsageAggregationTimeZone(), endDate), account.getId());\n // Create the usage record\n String usageDesc = \"VMSnapshot Id: \" + vmSnapshotId + \" Usage: \" + \"VM Id: \" + vmId + \" Volume Id: \" + volId + \" \";\n if (doId != null) {\n usageDesc += \" DiskOffering: \" + doId;\n }\n usageDesc += \" Size: \" + toHumanReadableSize(size);\n UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + \" Hrs\", type, new Double(usage), vmId, null, doId, null, vmSnapshotId, size, startDate, endDate);\n s_usageDao.persist(usageRecord);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "void validateSharedNetworkRouterIPs(String gateway, String startIP, String endIP, String netmask, String routerIPv4, String routerIPv6, String startIPv6, String endIPv6, String ip6Cidr, NetworkOffering ntwkOff) {\n if (ntwkOff.getGuestType() == GuestType.Shared) {\n validateSharedNetworkRouterIPv4(routerIPv4, startIP, endIP, gateway, netmask);\n validateSharedNetworkRouterIPv6(routerIPv6, startIPv6, endIPv6, ip6Cidr);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "//Note: due to bug CLOUDSTACK-4459, createStoragepool can be called in parallel, so need to be synced.\nprivate synchronized KVMStoragePool createStoragePool(String name, String host, int port, String path, String userInfo, StoragePoolType type, Map details, boolean primaryStorage) {\n StorageAdaptor adaptor = getStorageAdaptor(type);\n KVMStoragePool pool = adaptor.createStoragePool(name, host, port, path, userInfo, type, details);\n // LibvirtStorageAdaptor-specific statement\n if (pool.isPoolSupportHA() && primaryStorage) {\n KVMHABase.HAStoragePool storagePool = new KVMHABase.HAStoragePool(pool, host, path, PoolType.PrimaryStorage);\n _haMonitor.addStoragePool(storagePool);\n }\n StoragePoolInformation info = new StoragePoolInformation(name, host, port, path, userInfo, type, details, primaryStorage);\n addStoragePool(pool.getUuid(), info);\n return pool;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private static void createPortGroup(String physicalNetwork, String networkName, String vlanRange, Integer vid, Integer spvlanid, DatacenterMO dataCenterMo, DVSTrafficShapingPolicy shapingPolicy, DVSSecurityPolicy secPolicy, DVSMacManagementPolicy macManagementPolicy, VMwareDVSPortgroupPolicy portGroupPolicy, DistributedVirtualSwitchMO dvSwitchMo, int numPorts, boolean autoExpandSupported, boolean dvSwitchSupportNewPolicies) throws Exception {\n VmwareDistributedVirtualSwitchVlanSpec vlanSpec = null;\n VmwareDistributedVirtualSwitchPvlanSpec pvlanSpec = null;\n VMwareDVSPortSetting dvsPortSetting = null;\n DVPortgroupConfigSpec newDvPortGroupSpec;\n // Next, create the port group. For this, we need to create a VLAN spec.\n // NOTE - VmwareDistributedVirtualSwitchPvlanSpec extends VmwareDistributedVirtualSwitchVlanSpec.\n if (vid == null || spvlanid == null) {\n vlanSpec = createDVPortVlanSpec(vid, vlanRange);\n dvsPortSetting = createVmwareDVPortSettingSpec(shapingPolicy, secPolicy, macManagementPolicy, vlanSpec, dvSwitchSupportNewPolicies);\n } else if (spvlanid != null) {\n // Create a pvlan spec. The pvlan spec is different from the pvlan config spec\n // that we created earlier. The pvlan config spec is used to configure the switch\n // with a tuple. The pvlan spec is used\n // to configure a port group (i.e., a network) with a secondary vlan id. We don't\n // need to mention more than the secondary vlan id because one secondary vlan id\n // can be associated with only one primary vlan id. Give vCenter the secondary vlan id,\n // and it will find out the associated primary vlan id and do the rest of the\n // port group configuration.\n pvlanSpec = createDVPortPvlanIdSpec(spvlanid);\n dvsPortSetting = createVmwareDVPortSettingSpec(shapingPolicy, secPolicy, macManagementPolicy, pvlanSpec, dvSwitchSupportNewPolicies);\n }\n newDvPortGroupSpec = createDvPortGroupSpec(networkName, dvsPortSetting, autoExpandSupported);\n if (portGroupPolicy != null) {\n newDvPortGroupSpec.setPolicy(portGroupPolicy);\n }\n if (!dataCenterMo.hasDvPortGroup(networkName)) {\n LOGGER.info(\"Distributed Virtual Port group \" + networkName + \" not found.\");\n // TODO(sateesh): Handle Exceptions\n try {\n newDvPortGroupSpec.setNumPorts(numPorts);\n dvSwitchMo.createDVPortGroup(newDvPortGroupSpec);\n } catch (Exception e) {\n String msg = \"Failed to create distributed virtual port group \" + networkName + \" on dvSwitch \" + physicalNetwork;\n msg += \". \" + VmwareHelper.getExceptionMessage(e);\n throw new Exception(msg);\n }\n } else {\n LOGGER.info(\"Found Distributed Virtual Port group \" + networkName);\n DVPortgroupConfigInfo currentDvPortgroupInfo = dataCenterMo.getDvPortGroupSpec(networkName);\n if (!isSpecMatch(currentDvPortgroupInfo, newDvPortGroupSpec, dvSwitchSupportNewPolicies)) {\n LOGGER.info(\"Updating Distributed Virtual Port group \" + networkName);\n newDvPortGroupSpec.setDefaultPortConfig(dvsPortSetting);\n newDvPortGroupSpec.setConfigVersion(currentDvPortgroupInfo.getConfigVersion());\n ManagedObjectReference morDvPortGroup = dataCenterMo.getDvPortGroupMor(networkName);\n try {\n dvSwitchMo.updateDvPortGroup(morDvPortGroup, newDvPortGroupSpec);\n } catch (Exception e) {\n String msg = \"Failed to update distributed virtual port group \" + networkName + \" on dvSwitch \" + physicalNetwork;\n msg += \". \" + VmwareHelper.getExceptionMessage(e);\n throw new Exception(msg);\n }\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private static void informListenerForNewTransactions(Block block, AbstractBlockChain.NewBlockType newBlockType, @Nullable List filteredTxHashList, @Nullable Map filteredTxn, StoredBlock_legacy newStoredBlock, boolean first, TransactionReceivedInBlockListener listener, Set falsePositives) throws VerificationException{\r\n if (block.getParsedTransactions() != null) {\r\n sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getParsedTransactions(), !first, falsePositives);\r\n } else if (filteredTxHashList != null) {\r\n checkNotNull(filteredTxn);\r\n int relativityOffset = 0;\r\n for (Sha256Hash hash : filteredTxHashList) {\r\n Transaction tx = filteredTxn.get(hash);\r\n if (tx != null) {\r\n sendTransactionsToListener(newStoredBlock, newBlockType, listener, relativityOffset, Collections.singletonList(tx), !first, falsePositives);\r\n } else {\r\n if (listener.notifyTransactionIsInBlock(hash, newStoredBlock, newBlockType, relativityOffset)) {\r\n falsePositives.remove(hash);\r\n }\r\n }\r\n relativityOffset++;\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private UserVm importExternalKvmVirtualMachine(final UnmanagedInstanceTO unmanagedInstance, final String instanceName, final DataCenter zone, final VirtualMachineTemplate template, final String displayName, final String hostName, final Account caller, final Account owner, final Long userId, final ServiceOfferingVO serviceOffering, final Map dataDiskOfferingMap, final Map nicNetworkMap, final Map callerNicIpAddressMap, final String remoteUrl, String username, String password, String tmpPath, final Map details) {\n UserVm userVm = null;\n Map allDetails = new HashMap<>(details);\n // Check disks and supplied disk offerings\n List unmanagedInstanceDisks = unmanagedInstance.getDisks();\n if (CollectionUtils.isEmpty(unmanagedInstanceDisks)) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"No attached disks found for the unmanaged VM: %s\", instanceName));\n }\n Pair> rootAndDataDisksPair = getRootAndDataDisks(unmanagedInstanceDisks, dataDiskOfferingMap);\n final UnmanagedInstanceTO.Disk rootDisk = rootAndDataDisksPair.first();\n final List dataDisks = rootAndDataDisksPair.second();\n if (rootDisk == null || StringUtils.isEmpty(rootDisk.getController())) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"VM import failed. Unable to retrieve root disk details for VM: %s \", instanceName));\n }\n allDetails.put(VmDetailConstants.ROOT_DISK_CONTROLLER, rootDisk.getController());\n // Check NICs and supplied networks\n Map nicIpAddressMap = getNicIpAddresses(unmanagedInstance.getNics(), callerNicIpAddressMap);\n Map allNicNetworkMap = getUnmanagedNicNetworkMap(unmanagedInstance.getName(), unmanagedInstance.getNics(), nicNetworkMap, nicIpAddressMap, zone, hostName, owner, Hypervisor.HypervisorType.KVM);\n if (!CollectionUtils.isEmpty(unmanagedInstance.getNics())) {\n allDetails.put(VmDetailConstants.NIC_ADAPTER, unmanagedInstance.getNics().get(0).getAdapterType());\n }\n VirtualMachine.PowerState powerState = VirtualMachine.PowerState.PowerOff;\n String internalName = getInternalName(owner.getAccountId());\n try {\n userVm = userVmManager.importVM(zone, null, template, internalName, displayName, owner, null, caller, true, null, owner.getAccountId(), userId, serviceOffering, null, hostName, Hypervisor.HypervisorType.KVM, allDetails, powerState, null);\n } catch (InsufficientCapacityException ice) {\n logger.error(String.format(\"Failed to import vm name: %s\", instanceName), ice);\n throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ice.getMessage());\n }\n if (userVm == null) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Failed to import vm name: %s\", instanceName));\n }\n DiskOfferingVO diskOffering = diskOfferingDao.findById(serviceOffering.getDiskOfferingId());\n String rootVolumeName = String.format(\"ROOT-%s\", userVm.getId());\n DiskProfile diskProfile = volumeManager.allocateRawVolume(Volume.Type.ROOT, rootVolumeName, diskOffering, null, null, null, userVm, template, owner, null);\n DiskProfile[] dataDiskProfiles = new DiskProfile[dataDisks.size()];\n int diskSeq = 0;\n for (UnmanagedInstanceTO.Disk disk : dataDisks) {\n if (disk.getCapacity() == null || disk.getCapacity() == 0) {\n throw new InvalidParameterValueException(String.format(\"Disk ID: %s size is invalid\", disk.getDiskId()));\n }\n DiskOffering offering = diskOfferingDao.findById(dataDiskOfferingMap.get(disk.getDiskId()));\n DiskProfile dataDiskProfile = volumeManager.allocateRawVolume(Volume.Type.DATADISK, String.format(\"DATA-%d-%s\", userVm.getId(), disk.getDiskId()), offering, null, null, null, userVm, template, owner, null);\n dataDiskProfiles[diskSeq++] = dataDiskProfile;\n }\n final VirtualMachineProfile profile = new VirtualMachineProfileImpl(userVm, template, serviceOffering, owner, null);\n ServiceOfferingVO dummyOffering = serviceOfferingDao.findById(userVm.getId(), serviceOffering.getId());\n profile.setServiceOffering(dummyOffering);\n DeploymentPlanner.ExcludeList excludeList = new DeploymentPlanner.ExcludeList();\n final DataCenterDeployment plan = new DataCenterDeployment(zone.getId(), null, null, null, null, null);\n DeployDestination dest = null;\n try {\n dest = deploymentPlanningManager.planDeployment(profile, plan, excludeList, null);\n } catch (Exception e) {\n logger.warn(String.format(\"Import failed for Vm: %s while finding deployment destination\", userVm.getInstanceName()), e);\n cleanupFailedImportVM(userVm);\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Import failed for Vm: %s while finding deployment destination\", userVm.getInstanceName()));\n }\n if (dest == null) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Import failed for Vm: %s. Suitable deployment destination not found\", userVm.getInstanceName()));\n }\n List> diskProfileStoragePoolList = new ArrayList<>();\n try {\n if (rootDisk.getCapacity() == null || rootDisk.getCapacity() == 0) {\n throw new InvalidParameterValueException(String.format(\"Root disk ID: %s size is invalid\", rootDisk.getDiskId()));\n }\n diskProfileStoragePoolList.add(importExternalDisk(rootDisk, userVm, dest, diskOffering, Volume.Type.ROOT, template, null, remoteUrl, username, password, tmpPath, diskProfile));\n long deviceId = 1L;\n diskSeq = 0;\n for (UnmanagedInstanceTO.Disk disk : dataDisks) {\n DiskProfile dataDiskProfile = dataDiskProfiles[diskSeq++];\n DiskOffering offering = diskOfferingDao.findById(dataDiskOfferingMap.get(disk.getDiskId()));\n diskProfileStoragePoolList.add(importExternalDisk(disk, userVm, dest, offering, Volume.Type.DATADISK, template, deviceId, remoteUrl, username, password, tmpPath, dataDiskProfile));\n deviceId++;\n }\n } catch (Exception e) {\n logger.error(String.format(\"Failed to import volumes while importing vm: %s\", instanceName), e);\n cleanupFailedImportVM(userVm);\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Failed to import volumes while importing vm: %s. %s\", instanceName, StringUtils.defaultString(e.getMessage())));\n }\n try {\n int nicIndex = 0;\n for (UnmanagedInstanceTO.Nic nic : unmanagedInstance.getNics()) {\n Network network = networkDao.findById(allNicNetworkMap.get(nic.getNicId()));\n Network.IpAddresses ipAddresses = nicIpAddressMap.get(nic.getNicId());\n importNic(nic, userVm, network, ipAddresses, nicIndex, nicIndex == 0, true);\n nicIndex++;\n }\n } catch (Exception e) {\n logger.error(String.format(\"Failed to import NICs while importing vm: %s\", instanceName), e);\n cleanupFailedImportVM(userVm);\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Failed to import NICs while importing vm: %s. %s\", instanceName, StringUtils.defaultString(e.getMessage())));\n }\n publishVMUsageUpdateResourceCount(userVm, dummyOffering, template);\n return userVm;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Get template ID for VM being imported. If it is not found, it is created\n */\nprivate Long getImportingVMTemplate(List virtualDisks, long zoneId, DatacenterMO dcMo, String vmInternalName, Long guestOsId, long accountId, Map disksMapping, Backup backup) throws Exception {\n for (VirtualDisk disk : virtualDisks) {\n if (isRootDisk(disk, disksMapping, backup)) {\n VolumeVO volumeVO = disksMapping.get(disk);\n if (volumeVO == null) {\n String templatePath = getRootDiskTemplatePath(disk);\n VirtualMachineMO template = getTemplate(dcMo, templatePath);\n Long poolId = getTemplatePoolId(zoneId, template);\n Long templateSize = getTemplateSize(template, vmInternalName, disksMapping, backup);\n long templateId = getTemplateId(templatePath, vmInternalName, guestOsId, accountId);\n updateTemplateRef(templateId, poolId, templatePath, templateSize);\n return templateId;\n } else {\n return volumeVO.getTemplateId();\n }\n }\n }\n throw new CloudRuntimeException(\"Could not find ROOT disk for VM \" + vmInternalName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private void processMailbox(MailboxSetup ms, ArchiveFileServiceLocal caseSvc, AddressServiceLocal adrSvc, SystemManagementLocal sysSvc, FormsServiceLocal formsSvc, ArrayList allFileNumbers, List tags, List blacklistedFileTypes, String exclusionList, boolean ignoreInline, int minAttachmentSize, List allPartyTypes, DocumentNameTemplate defaultNameTemplate) {\n log.info(\"Processing mailbox \" + ms.getEmailAddress());\n String server = null;\n try {\n String emailInPwd = CryptoProvider.newCrypto().decrypt(ms.getEmailInPwd());\n //Properties props = System.getProperties();\n Properties props = new Properties();\n props.setProperty(\"mail.imap.partialfetch\", \"false\");\n props.setProperty(\"mail.imaps.partialfetch\", \"false\");\n props.setProperty(\"mail.store.protocol\", ms.getEmailInType());\n if (ms.isEmailInSsl()) {\n props.setProperty(\"mail.\" + ms.getEmailInType() + \".ssl.enable\", \"true\");\n }\n Session session = null;\n Store store = null;\n server = ms.getEmailInServer();\n if (ms.isMsExchange()) {\n String authToken = MsExchangeUtils.getAuthToken(ms.getTenantId(), ms.getClientId(), ms.getClientSecret(), ms.getEmailInUser(), emailInPwd);\n props.put(\"mail.imaps.sasl.enable\", \"true\");\n props.put(\"mail.imaps.port\", \"993\");\n props.put(\"mail.imaps.auth.mechanisms\", \"XOAUTH2\");\n props.put(\"mail.imaps.sasl.mechanisms\", \"XOAUTH2\");\n props.put(\"mail.imaps.auth.login.disable\", \"true\");\n props.put(\"mail.imaps.auth.plain.disable\", \"true\");\n props.setProperty(\"mail.imaps.socketFactory.class\", SSL_FACTORY);\n props.setProperty(\"mail.imaps.socketFactory.fallback\", \"false\");\n props.setProperty(\"mail.imaps.socketFactory.port\", \"993\");\n props.setProperty(\"mail.imaps.starttls.enable\", \"true\");\n session = Session.getInstance(props);\n // should be imaps for Office 365\n store = session.getStore(\"imaps\");\n // server should be outlook.office365.com\n store.connect(server, ms.getEmailInUser(), authToken);\n } else {\n props.setProperty(\"mail.imaps.host\", server);\n props.setProperty(\"mail.imap.host\", server);\n if (ms.isEmailInSsl()) {\n props.setProperty(\"mail.store.protocol\", \"imaps\");\n }\n InitialContext ic = new InitialContext();\n ServerSettingsBeanFacadeLocal settings = (ServerSettingsBeanFacadeLocal) ic.lookup(\"java:global/j-lawyer-server/j-lawyer-server-ejb/ServerSettingsBeanFacade!com.jdimension.jlawyer.persistence.ServerSettingsBeanFacadeLocal\");\n ServerSettingsBean trustedServers = settings.find(\"mail.imaps.ssl.trust\");\n if (trustedServers != null) {\n props.put(\"mail.imaps.ssl.trust\", trustedServers.getSettingValue());\n }\n session = Session.getInstance(props, new Authenticator() {\n\n @Override\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(ms.getEmailInUser(), emailInPwd);\n }\n });\n store = session.getStore();\n store.connect();\n }\n Folder[] accountFolders = null;\n try {\n accountFolders = store.getDefaultFolder().list();\n } catch (Throwable t) {\n log.warn(\"Unable to get email accounts folder list - falling back to inbox listing...\", t);\n accountFolders = new Folder[1];\n accountFolders[0] = (Folder) store.getFolder(INBOX);\n }\n Folder inboxFolder = CommonMailUtils.getInboxFolder(accountFolders);\n if (!inboxFolder.isOpen()) {\n inboxFolder.open(Folder.READ_WRITE);\n }\n // create \"imported\" folder\n boolean importFolderExists = false;\n Folder importFolder = null;\n try {\n if (!inboxFolder.isOpen()) {\n inboxFolder.open(Folder.READ_WRITE);\n }\n importFolder = inboxFolder.getFolder(\"in Akte importiert\");\n boolean created = false;\n if (!importFolder.exists()) {\n created = importFolder.create(Folder.HOLDS_MESSAGES);\n importFolder = inboxFolder.getFolder(\"in Akte importiert\");\n } else {\n importFolderExists = true;\n }\n if (created) {\n importFolderExists = true;\n }\n if (!importFolderExists) {\n log.error(\"Folder for imported mails does not exist and creation failed!\");\n }\n } catch (Exception ex) {\n log.error(\"Folder for imported mails could not be checked / created!\", ex);\n }\n Message[] allMessages = inboxFolder.getMessages();\n ArrayList deleteMessages = new ArrayList<>();\n long currentTimeStamp = System.currentTimeMillis();\n for (Message msg : allMessages) {\n if (msg.getReceivedDate() != null) {\n if (msg.getReceivedDate().getTime() < (currentTimeStamp - (1000l * 60l * 60l * 24l * 31l * 2l))) {\n log.info(\"Message '\" + msg.getSubject() + \"' is older than two months and will not be processed\");\n continue;\n }\n }\n String from = null;\n Address[] froms = msg.getFrom();\n if (froms != null) {\n if (froms.length > 0 && (froms[0] instanceof javax.mail.internet.InternetAddress)) {\n from = ((javax.mail.internet.InternetAddress) froms[0]).getAddress();\n from = from.toLowerCase();\n }\n }\n if (from != null && exclusionList.toLowerCase().contains(from)) {\n log.info(\"FROM address is excluded from mailscanner processing: \" + from);\n continue;\n }\n boolean excludedTo = false;\n Address[] toAdrs = msg.getRecipients(Message.RecipientType.TO);\n if (toAdrs != null) {\n for (Address to : toAdrs) {\n String toString = null;\n if ((to instanceof javax.mail.internet.InternetAddress)) {\n toString = ((javax.mail.internet.InternetAddress) to).getAddress();\n toString = toString.toLowerCase();\n if (exclusionList.toLowerCase().contains(toString)) {\n log.info(\"TO address is excluded from mailscanner processing: \" + from);\n excludedTo = true;\n break;\n }\n }\n }\n }\n if (excludedTo) {\n continue;\n }\n // FIRST - A: try to find matching case by file number in the subject line\n // find any potential cases by looking for file numbers in subject\n // this should force the message to be fully loaded\n // try two times, i've seen sporadic FolderClosedException\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n try {\n msg.writeTo(bos);\n } catch (FolderClosedException fce) {\n msg.getFolder().open(Folder.READ_WRITE);\n msg.writeTo(bos);\n }\n bos.close();\n SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());\n Message copiedMsg = new MimeMessage(session, bis);\n bis.close();\n if (copiedMsg.getSubject() != null) {\n log.info(\"processing message with subject: \" + copiedMsg.getSubject());\n }\n String subject = \"\";\n if (copiedMsg.getSubject() != null) {\n subject = copiedMsg.getSubject();\n }\n boolean foundInSubject = false;\n for (String fn : allFileNumbers) {\n if (subject.contains(fn.toLowerCase())) {\n ArchiveFileBean toCase = caseSvc.getArchiveFileByFileNumberUnrestricted(fn);\n if (toCase.isArchived()) {\n // need to avoid saving to an archived case - the tag would never be displayed on the desktop\n log.warn(\"message from \" + msg.getFrom().toString() + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by a file number in its subject, but the case is already archived - skipping!\");\n } else {\n log.info(\"message from \" + msg.getFrom().toString() + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by a file number in its subject\");\n boolean saved = this.saveToCase(copiedMsg, msg.getReceivedDate(), toCase, caseSvc, sysSvc, formsSvc, tags, blacklistedFileTypes, ignoreInline, minAttachmentSize, defaultNameTemplate, allPartyTypes);\n if (saved) {\n deleteMessages.add(msg);\n }\n foundInSubject = true;\n }\n break;\n }\n }\n if (foundInSubject) {\n continue;\n }\n // FIRST - B: try to find matching case by file number in the body\n String body = null;\n try {\n if (copiedMsg.isMimeType(\"multipart/*\")) {\n ArrayList partsFound = new ArrayList<>();\n CommonMailUtils.recursiveFindPart(copiedMsg.getContent(), ContentTypes.TEXT_HTML, partsFound);\n if (!partsFound.isEmpty()) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"\");\n for (String p : partsFound) {\n String pNew = p.trim();\n if (pNew.startsWith(\"\")) {\n pNew = pNew.substring(6);\n }\n if (pNew.endsWith(\"\")) {\n pNew = pNew.substring(0, pNew.length() - 7);\n }\n sb.append(pNew);\n }\n sb.append(\"\");\n String html = sb.toString();\n body = CommonMailUtils.html2Text(html);\n } else {\n CommonMailUtils.recursiveFindPart(copiedMsg.getContent(), ContentTypes.TEXT_PLAIN, partsFound);\n if (!partsFound.isEmpty()) {\n String text = partsFound.get(0);\n body = text;\n } else {\n log.warn(\"email with unkown content type\");\n body = \"\";\n }\n }\n } else {\n if (copiedMsg.isMimeType(ContentTypes.TEXT_PLAIN)) {\n body = copiedMsg.getContent().toString();\n } else if (copiedMsg.isMimeType(ContentTypes.TEXT_HTML)) {\n body = copiedMsg.getContent().toString();\n if (copiedMsg.getContent() instanceof InputStream) {\n log.warn(\"content of mail is of type inputstream!\");\n BufferedInputStream contentBis = new BufferedInputStream((InputStream) copiedMsg.getContent());\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int bytesRead = -1;\n while ((bytesRead = contentBis.read(buffer)) > -1) {\n bout.write(buffer, 0, bytesRead);\n }\n bout.close();\n try {\n body = new String(bout.toByteArray());\n } catch (Throwable t) {\n log.error(\"mail content byte array cannot be converted to string\", t);\n }\n log.warn(\"bytes represent the following string:\");\n log.warn(body);\n body = CommonMailUtils.html2Text(body);\n }\n } else {\n log.debug(\"unkown content\");\n }\n }\n } catch (Throwable t) {\n log.error(\"unable to check body for context information\", t);\n }\n if (body == null) {\n body = \"\";\n }\n body = body.toLowerCase();\n if (body.length() > 0) {\n boolean foundInBody = false;\n for (String fn : allFileNumbers) {\n if (body.contains(fn.toLowerCase())) {\n ArchiveFileBean toCase = caseSvc.getArchiveFileByFileNumberUnrestricted(fn);\n if (toCase.isArchived()) {\n // need to avoid saving to an archived case - the tag would never be displayed on the desktop\n log.warn(\"message from \" + msg.getFrom().toString() + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by a file number in its body, but the case is already archived - skipping!\");\n } else {\n log.info(\"message from \" + msg.getFrom().toString() + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by a file number in its body\");\n boolean saved = this.saveToCase(copiedMsg, msg.getReceivedDate(), toCase, caseSvc, sysSvc, formsSvc, tags, blacklistedFileTypes, ignoreInline, minAttachmentSize, defaultNameTemplate, allPartyTypes);\n if (saved) {\n deleteMessages.add(msg);\n }\n foundInBody = true;\n }\n break;\n }\n }\n if (foundInBody) {\n continue;\n }\n }\n // SECOND: try to find matching sender FROM that only has ONE case\n AddressBean[] fromAddresses = adrSvc.searchSimpleUnrestricted(from);\n if (fromAddresses.length > 1) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be uniquely associated by its FROM because there was more than one match for \" + from);\n } else if (fromAddresses.length == 0) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be associated by its FROM because there was no match for \" + from);\n } else {\n Collection parties = caseSvc.getArchiveFileAddressesForAddressUnrestricted(fromAddresses[0].getId());\n ArchiveFileAddressesBean uniqueCase = getUniqueCase(parties);\n if (uniqueCase != null) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by its FROM because there was exactly one match for \" + from);\n boolean saved = this.saveToCase(copiedMsg, msg.getReceivedDate(), uniqueCase.getArchiveFileKey(), caseSvc, sysSvc, formsSvc, tags, blacklistedFileTypes, ignoreInline, minAttachmentSize, defaultNameTemplate, allPartyTypes);\n if (saved) {\n deleteMessages.add(msg);\n }\n continue;\n }\n }\n // THIRD: try to find matching sender CC that only has ONE case\n Address[] ccAdrs = msg.getRecipients(Message.RecipientType.CC);\n boolean foundInCC = false;\n if (ccAdrs != null) {\n for (Address cc : ccAdrs) {\n String ccString = null;\n if ((cc instanceof javax.mail.internet.InternetAddress)) {\n ccString = ((javax.mail.internet.InternetAddress) cc).getAddress();\n ccString = ccString.toLowerCase();\n }\n AddressBean[] ccAddresses = adrSvc.searchSimpleUnrestricted(ccString);\n if (ccAddresses.length > 1) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be uniquely associated by its CC because there was more than one match for \" + ccString);\n } else if (ccAddresses.length == 0) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be associated by its CC because there was no match for \" + ccString);\n } else {\n Collection parties = caseSvc.getArchiveFileAddressesForAddressUnrestricted(ccAddresses[0].getId());\n ArchiveFileAddressesBean uniqueCase = getUniqueCase(parties);\n if (uniqueCase != null) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by its CC because there was exactly one match for \" + ccString);\n boolean saved = this.saveToCase(copiedMsg, msg.getReceivedDate(), uniqueCase.getArchiveFileKey(), caseSvc, sysSvc, formsSvc, tags, blacklistedFileTypes, ignoreInline, minAttachmentSize, defaultNameTemplate, allPartyTypes);\n if (saved) {\n deleteMessages.add(msg);\n }\n foundInCC = true;\n break;\n }\n }\n }\n }\n if (foundInCC) {\n continue;\n }\n // FOURTH: try to find matching sender TO that only has ONE case\n boolean foundInTo = false;\n if (toAdrs != null) {\n for (Address to : toAdrs) {\n String toString = null;\n if ((to instanceof javax.mail.internet.InternetAddress)) {\n toString = ((javax.mail.internet.InternetAddress) to).getAddress();\n toString = toString.toLowerCase();\n }\n AddressBean[] toAddresses = adrSvc.searchSimpleUnrestricted(toString);\n if (toAddresses.length > 1) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be uniquely associated by its TO because there was more than one match for \" + toString);\n } else if (toAddresses.length == 0) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can not be associated by its TO because there was no match for \" + toString);\n } else {\n Collection parties = caseSvc.getArchiveFileAddressesForAddressUnrestricted(toAddresses[0].getId());\n ArchiveFileAddressesBean uniqueCase = getUniqueCase(parties);\n if (uniqueCase != null) {\n log.info(\"message from \" + from + \" with subject '\" + copiedMsg.getSubject() + \"' can be uniquely associated by its TO because there was exactly one match for \" + toString);\n boolean saved = this.saveToCase(copiedMsg, msg.getReceivedDate(), uniqueCase.getArchiveFileKey(), caseSvc, sysSvc, formsSvc, tags, blacklistedFileTypes, ignoreInline, minAttachmentSize, defaultNameTemplate, allPartyTypes);\n if (saved) {\n deleteMessages.add(msg);\n }\n foundInTo = true;\n break;\n }\n }\n }\n }\n if (foundInTo) {\n continue;\n }\n }\n if (!deleteMessages.isEmpty()) {\n if (!inboxFolder.isOpen()) {\n inboxFolder.open(Folder.READ_WRITE);\n }\n if (importFolder != null) {\n if (!importFolder.isOpen()) {\n importFolder.open(Folder.READ_WRITE);\n }\n Flags deleteFlags = new Flags(Flags.Flag.DELETED);\n Message[] toBeMoved = deleteMessages.toArray(new Message[0]);\n // move to \"imported\" folder\n inboxFolder.copyMessages(toBeMoved, importFolder);\n inboxFolder.setFlags(toBeMoved, deleteFlags, true);\n } else {\n log.error(\"message have been processed but the import folder does not exist, so they cannot be moved\");\n }\n }\n try {\n if (inboxFolder.isOpen()) {\n inboxFolder.close();\n }\n } catch (Throwable t) {\n log.warn(\"unable to close inbox folder\", t);\n }\n try {\n if (importFolder != null && importFolder.isOpen()) {\n importFolder.close();\n }\n } catch (Throwable t) {\n log.warn(\"unable to close import folder\", t);\n }\n try {\n store.close();\n } catch (Throwable t) {\n log.warn(\"unable to close mailbox store\", t);\n }\n } catch (Exception ex) {\n log.error(\"Error connecting to server \" + server, ex);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private boolean evalBetaNode(PathMemory pmem, NetworkNode node, Memory nodeMem, SegmentMemory[] smems, int smemIndex, TupleSets trgTuples, ActivationsManager activationsManager, LinkedList stack, boolean processRian, RuleExecutor executor, TupleSets srcTuples, TupleSets stagedLeftTuples, LeftTupleSinkNode sink){\r\n BetaNode betaNode = (BetaNode) node;\r\n BetaMemory bm;\r\n AccumulateMemory am = null;\r\n if (NodeTypeEnums.AccumulateNode == node.getType()) {\r\n am = (AccumulateMemory) nodeMem;\r\n bm = am.getBetaMemory();\r\n } else {\r\n bm = (BetaMemory) nodeMem;\r\n }\r\n if (processRian && betaNode.isRightInputIsRiaNode()) {\r\n doRiaNode(activationsManager, pmem, srcTuples, betaNode, sink, smems, smemIndex, nodeMem, bm, stack, executor);\r\n return true;\r\n }\r\n switchOnDoBetaNode(node, trgTuples, activationsManager.getReteEvaluator(), srcTuples, stagedLeftTuples, sink, bm, am);\r\n return false;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static RexNode shiftFilter(int start, int end, int offset, RexBuilder rexBuilder, List joinFields, int nTotalFields, List rightFields, RexNode filter){\r\n int[] adjustments = new int[nTotalFields];\r\n for (int i = start; i < end; i++) {\r\n adjustments[i] = offset;\r\n }\r\n return filter.accept(new RexInputConverter(rexBuilder, joinFields, rightFields, adjustments));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RexNode makeOver(RelDataType type, SqlAggFunction operator, List exprs, List partitionKeys, ImmutableList orderKeys, RexWindowBound lowerBound, RexWindowBound upperBound, boolean rows, boolean allowPartial, boolean nullWhenCountZero, boolean distinct, boolean ignoreNulls){\r\n final RexWindow window = makeWindow(partitionKeys, orderKeys, lowerBound, upperBound, rows);\r\n final RexOver over = new RexOver(type, operator, exprs, window, distinct, ignoreNulls);\r\n RexNode result = over;\r\n if (nullWhenCountZero) {\r\n final RelDataType bigintType = typeFactory.createSqlType(SqlTypeName.BIGINT);\r\n result = makeCall(SqlStdOperatorTable.CASE, makeCall(SqlStdOperatorTable.GREATER_THAN, new RexOver(bigintType, SqlStdOperatorTable.COUNT, exprs, window, distinct, ignoreNulls), makeLiteral(BigDecimal.ZERO, bigintType, SqlTypeName.DECIMAL)), ensureType(type, new RexOver(typeFactory.createTypeWithNullability(type, false), operator, exprs, window, distinct, ignoreNulls), false), makeNullLiteral(type));\r\n }\r\n if (!allowPartial) {\r\n Preconditions.checkArgument(rows, \"DISALLOW PARTIAL over RANGE\");\r\n final RelDataType bigintType = typeFactory.createSqlType(SqlTypeName.BIGINT);\r\n result = makeCall(SqlStdOperatorTable.CASE, makeCall(SqlStdOperatorTable.GREATER_THAN_OR_EQUAL, new RexOver(bigintType, SqlStdOperatorTable.COUNT, ImmutableList.of(), window, distinct, ignoreNulls), makeLiteral(BigDecimal.valueOf(2), bigintType, SqlTypeName.DECIMAL)), result, constantNull);\r\n }\r\n return result;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List makeArgs(String jar, String mainClass, String libjars, String files, List jarArgs, List defines, String statusdir, boolean usesHcatalog, String completedUrl, boolean enablelog, Boolean enableJobReconnect, JobType jobType) throws BadParam, IOException, InterruptedException{\r\n ArrayList args = new ArrayList();\r\n try {\r\n ArrayList allFiles = new ArrayList();\r\n allFiles.add(TempletonUtils.hadoopFsFilename(jar, appConf, runAs));\r\n args.addAll(makeLauncherArgs(appConf, statusdir, completedUrl, allFiles, enablelog, enableJobReconnect, jobType));\r\n args.add(\"--\");\r\n if (usesHcatalog) {\r\n addHiveMetaStoreTokenArg();\r\n }\r\n args.add(appConf.clusterHadoop());\r\n args.add(\"jar\");\r\n args.add(TempletonUtils.hadoopFsPath(jar, appConf, runAs).getName());\r\n if (TempletonUtils.isset(mainClass)) {\r\n args.add(mainClass);\r\n }\r\n if (TempletonUtils.isset(libjars)) {\r\n String libjarsListAsString = TempletonUtils.hadoopFsListAsString(libjars, appConf, runAs);\r\n args.add(\"-libjars\");\r\n args.add(libjarsListAsString);\r\n }\r\n if (TempletonUtils.isset(files)) {\r\n String filesListAsString = TempletonUtils.hadoopFsListAsString(files, appConf, runAs);\r\n args.add(\"-files\");\r\n args.add(filesListAsString);\r\n }\r\n args.add(\"-D\");\r\n args.add(TempletonControllerJob.TOKEN_FILE_ARG_PLACEHOLDER);\r\n args.add(\"-D\");\r\n args.add(TempletonControllerJob.MAPREDUCE_JOB_TAGS_ARG_PLACEHOLDER);\r\n for (String d : defines) {\r\n args.add(\"-D\");\r\n args.add(d);\r\n }\r\n for (String arg : jarArgs) {\r\n args.add(arg);\r\n }\r\n } catch (FileNotFoundException e) {\r\n throw new BadParam(e.getMessage());\r\n } catch (URISyntaxException e) {\r\n throw new BadParam(e.getMessage());\r\n }\r\n return args;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static LogicalMatch create(RelNode input, RelDataType rowType, RexNode pattern, boolean strictStart, boolean strictEnd, Map patternDefinitions, Map measures, RexNode after, Map> subsets, boolean allRows, ImmutableBitSet partitionKeys, RelCollation orderKeys, @Nullable RexNode interval){\r\n final RelOptCluster cluster = input.getCluster();\r\n final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE);\r\n return create(cluster, traitSet, input, rowType, pattern, strictStart, strictEnd, patternDefinitions, measures, after, subsets, allRows, partitionKeys, orderKeys, interval);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Launch a new UAM, using the provided uamId and appId.\n *\n * @param uamId uam Id\n * @param conf configuration for this UAM\n * @param appId application id for the UAM\n * @param queueName queue of the application\n * @param submitter submitter name of the UAM\n * @param appNameSuffix application name suffix for the UAM\n * @param keepContainersAcrossApplicationAttempts keep container flag for UAM\n * recovery.\n * @param rmName name of the YarnRM\n * @param originalAppSubmissionContext AppSubmissionContext\n * @see ApplicationSubmissionContext\n * #setKeepContainersAcrossApplicationAttempts(boolean)\n * @return UAM token\n * @throws YarnException if fails\n * @throws IOException if fails\n */\npublic Token launchUAM(String uamId, Configuration conf, ApplicationId appId, String queueName, String submitter, String appNameSuffix, boolean keepContainersAcrossApplicationAttempts, String rmName, ApplicationSubmissionContext originalAppSubmissionContext) throws YarnException, IOException {\n if (this.unmanagedAppMasterMap.containsKey(uamId)) {\n throw new YarnException(\"UAM \" + uamId + \" already exists\");\n }\n UnmanagedApplicationManager uam = createUAM(conf, appId, queueName, submitter, appNameSuffix, keepContainersAcrossApplicationAttempts, rmName, originalAppSubmissionContext);\n // Put the UAM into map first before initializing it to avoid additional UAM\n // for the same uamId being created concurrently\n this.unmanagedAppMasterMap.put(uamId, uam);\n Token amrmToken;\n try {\n LOG.info(\"Launching UAM id {} for application {}\", uamId, appId);\n amrmToken = uam.launchUAM();\n } catch (Exception e) {\n // Add the map earlier and remove here if register failed because we want\n // to make sure there is only one uam instance per uamId at any given time\n this.unmanagedAppMasterMap.remove(uamId);\n throw e;\n }\n this.appIdMap.put(uamId, uam.getAppId());\n return amrmToken;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void addParameterAnnotation(final int parameter, final String desc, final List nameRU, final List tags, final List values, final List caseArrayN, final List nestTypeRS, final List nestNameRU, final List nestPairN){\r\n annoN[parameter]++;\r\n typeRS.add(desc);\r\n pairN.add(nameRU.size());\r\n this.nameRU.addAll(nameRU);\r\n this.tags.addAll(tags);\r\n this.values.addAll(values);\r\n this.caseArrayN.addAll(caseArrayN);\r\n this.nestTypeRS.addAll(nestTypeRS);\r\n this.nestNameRU.addAll(nestNameRU);\r\n this.nestPairN.addAll(nestPairN);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query6Def query(String pkg, String name, Class type1, Class type2, Class type3, Class type4, Class type5, Class type6){\r\n return new Query6DefImpl<>(VIEW_BUILDER, pkg, name, type1, type2, type3, type4, type5, type6);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final String url, final Long productId, final Long creditBureauId, final Long organisationCreditBureauId, final String jobName) {\n return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subresourceId, null, null, null, null, null, url, productId, creditBureauId, organisationCreditBureauId, jobName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Initiate download of a public template\n * @param id unique id.\n * @param url the url from where to download from\n * @param hvm whether the template is a hardware virtual machine\n * @param accountId the accountId of the iso owner (null if public iso)\n * @param descr description of the template\n * @param userName username used for authentication to the server\n * @param passwd password used for authentication to the server\n * @param maxDownloadSizeInBytes (optional) max download size for the template, in bytes.\n * @param resourceType signifying the type of resource like template, volume etc.\n * @param followRedirects whether downloader follows redirections\n * @return job-id that can be used to interrogate the status of the download.\n */\npublic String downloadPublicTemplate(long id, String url, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum, String installPathPrefix, String templatePath, String userName, String passwd, long maxDownloadSizeInBytes, Proxy proxy, ResourceType resourceType, boolean followRedirects);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private static Enumerable hashJoinWithPredicate_(final Enumerable outer, final Enumerable inner, final Function1 outerKeySelector, final Function1 innerKeySelector, final Function2 resultSelector, @Nullable final EqualityComparer comparer, final boolean generateNullsOnLeft, final boolean generateNullsOnRight, final Predicate2 predicate){\r\n return new AbstractEnumerable() {\r\n\r\n @Override\r\n public Enumerator enumerator() {\r\n final Enumerable innerToLookUp = generateNullsOnLeft ? Linq4j.asEnumerable(inner.toList()) : inner;\r\n final Lookup innerLookup = comparer == null ? innerToLookUp.toLookup(innerKeySelector) : innerToLookUp.toLookup(innerKeySelector, comparer);\r\n return new Enumerator() {\r\n\r\n Enumerator outers = outer.enumerator();\r\n\r\n Enumerator inners = Linq4j.emptyEnumerator();\r\n\r\n @Nullable\r\n List innersUnmatched = generateNullsOnLeft ? new ArrayList<>(innerToLookUp.toList()) : null;\r\n\r\n @Override\r\n public TResult current() {\r\n return resultSelector.apply(outers.current(), inners.current());\r\n }\r\n\r\n @Override\r\n public boolean moveNext() {\r\n for (; ; ) {\r\n if (inners.moveNext()) {\r\n return true;\r\n }\r\n if (!outers.moveNext()) {\r\n if (innersUnmatched != null) {\r\n inners = Linq4j.enumerator(innersUnmatched);\r\n outers.close();\r\n outers = Linq4j.singletonNullEnumerator();\r\n outers.moveNext();\r\n innersUnmatched = null;\r\n continue;\r\n }\r\n return false;\r\n }\r\n final TSource outer = outers.current();\r\n Enumerable innerEnumerable;\r\n if (outer == null) {\r\n innerEnumerable = null;\r\n } else {\r\n final TKey outerKey = outerKeySelector.apply(outer);\r\n if (outerKey == null) {\r\n innerEnumerable = null;\r\n } else {\r\n innerEnumerable = innerLookup.get(outerKey);\r\n if (innerEnumerable != null) {\r\n final List matchedInners = new ArrayList<>();\r\n try (Enumerator innerEnumerator = innerEnumerable.enumerator()) {\r\n while (innerEnumerator.moveNext()) {\r\n final TInner inner = innerEnumerator.current();\r\n if (predicate.apply(outer, inner)) {\r\n matchedInners.add(inner);\r\n }\r\n }\r\n }\r\n innerEnumerable = Linq4j.asEnumerable(matchedInners);\r\n if (innersUnmatched != null) {\r\n innersUnmatched.removeAll(matchedInners);\r\n }\r\n }\r\n }\r\n }\r\n if (innerEnumerable == null || !innerEnumerable.any()) {\r\n if (generateNullsOnRight) {\r\n inners = Linq4j.singletonNullEnumerator();\r\n } else {\r\n inners = Linq4j.emptyEnumerator();\r\n }\r\n } else {\r\n inners = innerEnumerable.enumerator();\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void reset() {\r\n outers.reset();\r\n }\r\n\r\n @Override\r\n public void close() {\r\n outers.close();\r\n }\r\n };\r\n }\r\n };\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doTransforms(FloatBuffer bindBufPos, FloatBuffer bindBufNorm, FloatBuffer bindBufTangents, FloatBuffer bufPos, FloatBuffer bufNorm, FloatBuffer bufTangents, int start, int end, Matrix4f transform) {\n TempVars vars = TempVars.get();\n Vector3f pos = vars.vect1;\n Vector3f norm = vars.vect2;\n Vector3f tan = vars.vect3;\n validateTempFloatArrays(end - start);\n int length = (end - start) * 3;\n int tanLength = (end - start) * 4;\n // offset is given in element units\n // convert to be in component units\n int offset = start * 3;\n int tanOffset = start * 4;\n bindBufPos.rewind();\n bindBufPos.get(tmpFloat, 0, length);\n if (bindBufNorm != null) {\n bindBufNorm.rewind();\n bindBufNorm.get(tmpFloatN, 0, length);\n }\n if (bindBufTangents != null) {\n bindBufTangents.rewind();\n bindBufTangents.get(tmpFloatT, 0, tanLength);\n }\n int index = 0;\n int tanIndex = 0;\n int index1, index2, tanIndex1, tanIndex2;\n while (index < length) {\n index1 = index + 1;\n index2 = index + 2;\n pos.x = tmpFloat[index];\n pos.y = tmpFloat[index1];\n pos.z = tmpFloat[index2];\n transform.mult(pos, pos);\n tmpFloat[index] = pos.x;\n tmpFloat[index1] = pos.y;\n tmpFloat[index2] = pos.z;\n if (bindBufNorm != null) {\n norm.x = tmpFloatN[index];\n norm.y = tmpFloatN[index1];\n norm.z = tmpFloatN[index2];\n transform.multNormal(norm, norm);\n tmpFloatN[index] = norm.x;\n tmpFloatN[index1] = norm.y;\n tmpFloatN[index2] = norm.z;\n }\n index += 3;\n if (bindBufTangents != null) {\n tanIndex1 = tanIndex + 1;\n tanIndex2 = tanIndex + 2;\n tan.x = tmpFloatT[tanIndex];\n tan.y = tmpFloatT[tanIndex1];\n tan.z = tmpFloatT[tanIndex2];\n transform.multNormal(tan, tan);\n tmpFloatT[tanIndex] = tan.x;\n tmpFloatT[tanIndex1] = tan.y;\n tmpFloatT[tanIndex2] = tan.z;\n tanIndex += 4;\n }\n }\n vars.release();\n //using bulk put as it's faster\n bufPos.position(offset);\n bufPos.put(tmpFloat, 0, length);\n if (bindBufNorm != null) {\n bufNorm.position(offset);\n bufNorm.put(tmpFloatN, 0, length);\n }\n if (bindBufTangents != null) {\n bufTangents.position(tanOffset);\n bufTangents.put(tmpFloatT, 0, tanLength);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "private Money penaltyChargesDueWithin(final LocalDate periodStart, final LocalDate periodEnd, final LoanCharge loanCharge, final MonetaryCurrency currency, LoanRepaymentScheduleInstallment period, final Money totalPrincipal, final Money totalInterest, boolean isInstallmentChargeApplicable, boolean isFirstPeriod) {\n if (loanCharge.isPenaltyCharge()) {\n boolean isDue = loanChargeIsDue(periodStart, periodEnd, isFirstPeriod, loanCharge);\n if (loanCharge.isInstalmentFee() && isInstallmentChargeApplicable) {\n return Money.of(currency, getInstallmentFee(currency, period, loanCharge));\n } else if (loanCharge.isOverdueInstallmentCharge() && isDue && loanCharge.getChargeCalculation().isPercentageBased()) {\n return Money.of(currency, loanCharge.chargeAmount());\n } else if (isDue && loanCharge.getChargeCalculation().isPercentageBased()) {\n BigDecimal amount = BigDecimal.ZERO;\n if (loanCharge.getChargeCalculation().isPercentageOfAmountAndInterest()) {\n amount = amount.add(totalPrincipal.getAmount()).add(totalInterest.getAmount());\n } else if (loanCharge.getChargeCalculation().isPercentageOfInterest()) {\n amount = amount.add(totalInterest.getAmount());\n } else {\n amount = amount.add(totalPrincipal.getAmount());\n }\n BigDecimal loanChargeAmt = amount.multiply(loanCharge.getPercentage()).divide(BigDecimal.valueOf(100));\n return Money.of(currency, loanChargeAmt);\n } else if (isDue) {\n return Money.of(currency, loanCharge.amount());\n }\n }\n return Money.zero(currency);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private void doRiaNode(ActivationsManager activationsManager, PathMemory pmem, TupleSets srcTuples, BetaNode betaNode, LeftTupleSinkNode sink, SegmentMemory[] smems, int smemIndex, Memory nodeMem, BetaMemory bm, LinkedList stack, RuleExecutor executor){\r\n RiaPathMemory pathMem = bm.getRiaRuleMemory();\r\n SegmentMemory[] subnetworkSmems = pathMem.getSegmentMemories();\r\n SegmentMemory subSmem = null;\r\n for (int i = 0; subSmem == null; i++) {\r\n subSmem = subnetworkSmems[i];\r\n }\r\n StackEntry stackEntry = new StackEntry(betaNode, bm.getNodePosMaskBit(), sink, pmem, nodeMem, smems, smemIndex, srcTuples, false, false);\r\n stack.add(stackEntry);\r\n if (log.isTraceEnabled()) {\r\n int offset = getOffset(betaNode);\r\n log.trace(\"{} RiaQueue {} {}\", indent(offset), betaNode.toString(), srcTuples.toStringSizes());\r\n }\r\n TupleSets subLts = subSmem.getStagedLeftTuples().takeAll();\r\n innerEval(pathMem, subSmem.getRootNode(), 1, subSmem.getNodeMemories()[0], subnetworkSmems, subSmem.getPos(), subLts, activationsManager, stack, true, executor);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List makeArgs(List inputs, String inputreader, String output, String mapper, String reducer, String combiner, List fileList, List cmdenvs, List jarArgs) throws BadParam{\r\n ArrayList args = new ArrayList();\r\n for (String input : inputs) {\r\n args.add(\"-input\");\r\n args.add(input);\r\n }\r\n args.add(\"-output\");\r\n args.add(output);\r\n args.add(\"-mapper\");\r\n args.add(mapper);\r\n args.add(\"-reducer\");\r\n args.add(reducer);\r\n if (inputreader != null && !inputreader.isEmpty()) {\r\n args.add(\"-inputreader\");\r\n args.add(inputreader);\r\n }\r\n if (TempletonUtils.isset(combiner)) {\r\n args.add(\"-combiner\");\r\n args.add(combiner);\r\n }\r\n for (String f : fileList) {\r\n args.add(\"-file\");\r\n args.add(f);\r\n }\r\n for (String e : cmdenvs) {\r\n args.add(\"-cmdenv\");\r\n args.add(e);\r\n }\r\n for (String arg : jarArgs) {\r\n args.add(arg);\r\n }\r\n return args;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get the clipping planes (positions at unit distance) for a surface
\n * seen by an eye of a viewer
\n * in a display config.
\n * This is only for use in integrations that cannot accept a fully-formulated
\n * projection matrix as returned by
\n * osvrClientGetViewerEyeSurfaceProjectionMatrixf() or
\n * osvrClientGetViewerEyeSurfaceProjectionMatrixd(), and may not necessarily
\n * provide the same optimizations.
\n * As all the planes are given at unit (1) distance, before passing these
\n * planes to a consuming function in your application/engine, you will typically
\n * divide them by your near clipping plane distance.
\n * @param disp Display config object
\n * @param viewer Viewer ID
\n * @param eye Eye ID
\n * @param surface Surface ID
\n * @param left Distance to left clipping plane
\n * @param right Distance to right clipping plane
\n * @param bottom Distance to bottom clipping plane
\n * @param top Distance to top clipping plane
\n * @return OSVR_RETURN_FAILURE if invalid parameters were passed, in which case
\n * the output arguments are unmodified.
\n * Original signature : OSVR_ReturnCode osvrClientGetViewerEyeSurfaceProjectionClippingPlanes(OSVR_DisplayConfig, OSVR_ViewerCount, OSVR_EyeCount, OSVR_SurfaceCount, double*, double*, double*, double*)\n */\npublic static native byte osvrClientGetViewerEyeSurfaceProjectionClippingPlanes(OsvrDisplayLibrary.OSVR_DisplayConfig disp, int viewer, byte eye, int surface, DoubleBuffer left, DoubleBuffer right, DoubleBuffer bottom, DoubleBuffer top);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "/**\n * Executes the operation.\n *\n * @param name The name of the attribute to put.\n * @param value The value of the attribute. Use this parameter, or\n * expression, or body.\n * @param expression The expression to calculate the value from. Use this\n * parameter, or value, or body.\n * @param role A comma-separated list of roles. If present, the attribute\n * will be rendered only if the current user belongs to one of the roles.\n * @param type The type (renderer) of the attribute.\n * @param cascade If true the attribute will be cascaded to all nested attributes.\n * @param request The request.\n * @param modelBody The body.\n * @throws IOException If the body cannot be evaluated.\n * @since 2.2.0\n */\npublic void execute(@Parameter(required = true) String name, Object value, String expression, String role, String type, boolean cascade, Request request, ModelBody modelBody) throws IOException {\n Deque composeStack = ComposeStackUtil.getComposeStack(request);\n Attribute attribute = new Attribute();\n composeStack.push(attribute);\n String currentBody = modelBody.evaluateAsString();\n TilesContainer container = TilesAccess.getCurrentContainer(request);\n attribute = (Attribute) composeStack.pop();\n putAttributeInParent(attribute, container, composeStack, name, value, expression, currentBody, role, type, cascade, request);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_struts", "language": "java"} {"function": "public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6){\r\n Map m = new HashMap<>();\r\n m.put(k1, v1);\r\n m.put(k2, v2);\r\n m.put(k3, v3);\r\n m.put(k4, v4);\r\n m.put(k5, v5);\r\n m.put(k6, v6);\r\n return m;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Applies requested ElementNames and typeNames.\n *

\n * For ElementNames, several strategies are implemented. Clients can determine the behaviour by\n * sending attribute \"elementname_strategy\" with one of the following values:\n *

\n * csw202 relaxed context geonetwork26\n *

\n * The default is 'relaxed'. The strategies cause the following behaviour:\n *

\n * csw202 -- compliant to the CSW2.0.2 specification. In particular this means that complete\n * metadata are returned that match the requested ElementNames, only if they are valid for their\n * XSD. This is because GeoNetwork only supports OutputFormat=application/xml, which mandates\n * that valid documents are returned. Because possibly not many of the catalog's metadata are\n * valid, this is not the default.\n *

\n * relaxed -- like csw202, but dropped the requirement to only include valid metadata. So this\n * returns complete metadata that match the requested ElementNames. This is the default\n * strategy.\n *

\n * context -- does not return complete metadata but only the elements matching the request, in\n * their context (i.e. all ancestor elements up to the root of the document are retained). This\n * strategy is similar to geonetwork26 but the context allows clients to determine which of the\n * elements returned corresponds to which of the elements requested (in case they have the same\n * name).\n *

\n * geonetwork26 -- behaviour as in GeoNetwork 2.6. Just return the requested elements, stripped\n * of any context. This can make it impossible for the client to determine which of the elements\n * returned corresponds to which of the elements requested; for example if the client asks for\n * gmd:title, the response may contain various gmd:title elements taken from different locations\n * in the metadata document.\n *

\n * ------------------------------------------------- Relevant sections of specification about\n * typeNames:\n *

\n * OGC 07-006 10.8.4.8: The typeNames parameter is a list of one or more names of queryable\n * entities in the catalogue's information model that may be constrained in the predicate of the\n * query. In the case of XML realization of the OGC core metadata properties (Subclause 10.2.5),\n * the element csw:Record is the only queryable entity. Other information models may include\n * more than one queryable component. For example, queryable components for the XML realization\n * of the ebRIM include rim:Service, rim:ExtrinsicObject and rim:Association. In such cases the\n * application profile shall describe how multiple typeNames values should be processed. In\n * addition, all or some of the these queryable entity names may be specified in the query to\n * define which metadata record elements the query should present in the response to the\n * GetRecords operation.\n *

\n * OGC 07-045:\n *

\n * 8.2.2.1.1 Request (GetRecords) TypeNames. Must support *one* of \u201ccsw:Record\u201d or\n * \u201cgmd:MD_Metadata\u201d in a query. Default value is \u201ccsw:Record\u201d.\n *

\n * So, in OGC 07-045, exactly one of csw:Record or gmd:MD_Metadata is mandated for typeName.\n *

\n * ---------------------------------- Relevant specs about ElementNames:\n *

\n * OGC 07-006 10.8.4.9: The ElementName parameter is used to specify one or more metadata record\n * elements, from the output schema specified using the outputSchema parameter, that the query\n * shall present in the response to the a GetRecords operation. Since clause 10.2.5 realizes the\n * core metadata properties using XML schema, the value of the ElementName parameter would be an\n * XPath expression perhaps using qualified names. In the general case, a complete XPath\n * expression may be required to correctly reference an element in the information model of the\n * catalog.\n *

\n * However, in the case where the typeNames attribute on the Query element contains a single\n * value, the catalogue can infer the first step in the path expression and it can be omitted.\n * This is usually the case when querying the core metadata properties since the only queryable\n * target is csw:Record.\n *

\n * If the metadata record element names are not from the schema specified using the outputSchema\n * parameter, then the service shall raise an exception as described in Subclause 10.3.7.\n *

\n * OGC 07-045: Usage of the ELEMENTNAME is not further specified here.\n *

\n * ---------------------------------- Relevant specs about outputFormat:\n *

\n * OGC 07-006 10.8.4.4 outputFormat parameter: In the case where the output format is\n * application/xml, the CSW shall generate an XML document that validates against a schema\n * document that is specified in the output document via the xsi:schemaLocation attribute\n * defined in XML.\n *\n * @param context servicecontext everywhere\n * @param elementNames requested ElementNames\n * @param typeName requested typeName\n * @param schemaManager schemamanager\n * @param schema schema\n * @param result result\n * @param resultType requested ResultType\n * @param info ?\n * @param strategy - which ElementNames strategy to use (see Javadoc)\n * @return results of applying ElementNames filter\n * @throws InvalidParameterValueEx hmm\n */\nprivate static Element applyElementNames(ServiceContext context, Set elementNames, String typeName, SchemaManager schemaManager, String schema, Element result, ResultType resultType, Element info, String strategy) throws InvalidParameterValueEx {\n if (elementNames != null) {\n if (StringUtils.isEmpty(strategy)) {\n strategy = DEFAULT_ELEMENTNAMES_STRATEGY;\n }\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"SearchController dealing with # \" + elementNames.size() + \" elementNames using strategy \" + strategy);\n MetadataSchema mds = schemaManager.getSchema(schema);\n List namespaces = mds.getSchemaNS();\n Element matchingMetadata = (Element) result.clone();\n if (strategy.equals(\"context\") || strategy.equals(\"geonetwork26\")) {\n // these strategies do not return complete metadata\n matchingMetadata.removeContent();\n }\n boolean metadataContainsAllRequestedElementNames = true;\n List nodes = new ArrayList<>();\n for (String elementName : elementNames) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"SearchController dealing with elementName: \" + elementName);\n try {\n //\n // OGC 07-006:\n // In certain cases, such as when the typeNames attribute on the Query element only contains the\n // name of a single entity, the root path step may be omitted since the catalogue is able to infer\n // what the first step in the path would be.\n //\n // heikki: since in OGC 07-045 only 1 value for typeNames is allowed, the interpreation is as\n // follows:\n // case 1: elementname start with / : use it as the xpath as is;\n // case 2: elementname does not start with / :\n // case 2a: elementname starts with one of the supported typeNames (csw:Record or gmd:MD_Metadata) : prepend /\n // case 2b: elementname does not start with one of the supported typeNames : prepend with /typeName//\n //\n String xpath;\n // case 1: elementname starts with /\n if (elementName.startsWith(\"/\")) {\n // use it as the xpath as is;\n xpath = elementName;\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"elementname start with root: \" + elementName);\n } else // case 2: elementname does not start with /\n {\n // case 2a: elementname starts with one of the supported typeNames (csw:Record or gmd:MD_Metadata)\n // TODO do not hardcode namespace prefixes\n if (elementName.startsWith(\"csw:Record\") || elementName.startsWith(\"gmd:MD_Metadata\")) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"elementname starts with one of the supported typeNames : \" + elementName);\n // prepend /\n xpath = \"/\" + elementName;\n } else // case 2b: elementname does not start with one of the supported typeNames\n {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"elementname does not start with one of the supported typeNames : \" + elementName);\n // prepend with /typeName/\n xpath = \"/\" + typeName + \"//\" + elementName;\n }\n }\n @SuppressWarnings(\"unchecked\")\n List elementsMatching = (List) Xml.selectDocumentNodes(result, xpath, namespaces);\n if (strategy.equals(\"context\")) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH)) {\n Log.debug(Geonet.CSW_SEARCH, \"strategy is context, constructing context to root\");\n }\n List elementsInContextMatching = new ArrayList<>();\n for (Element match : elementsMatching) {\n Element parent = match.getParentElement();\n while (parent != null) {\n parent.removeContent();\n parent.addContent((Element) match.clone());\n match = (Element) parent.clone();\n parent = parent.getParentElement();\n }\n elementsInContextMatching.add(match);\n }\n elementsMatching = elementsInContextMatching;\n }\n nodes.addAll(elementsMatching);\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"elemName \" + elementName + \" matched # \" + nodes.size() + \" nodes\");\n if (nodes.size() == 0) {\n metadataContainsAllRequestedElementNames = false;\n break;\n }\n } catch (Exception x) {\n Log.error(Geonet.CSW_SEARCH, x.getMessage(), x);\n throw new InvalidParameterValueEx(\"elementName has invalid XPath : \" + elementName, x.getMessage());\n }\n }\n if (metadataContainsAllRequestedElementNames) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"metadata containa all requested elementnames: included in response\");\n if (strategy.equals(\"context\") || strategy.equals(\"geonetwork26\")) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"adding only the matching fragments to result\");\n for (Element node : nodes) {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"adding node:\\n\" + Xml.getString(node));\n matchingMetadata.addContent((Content) node.clone());\n }\n } else {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"adding the complete metadata to results\");\n if (strategy.equals(\"csw202\")) {\n GeonetContext geonetContext = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);\n DataManager dataManager = geonetContext.getBean(DataManager.class);\n boolean valid = dataManager.validate(result);\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"strategy csw202: only valid metadata is returned. This one is valid? \" + valid);\n if (!valid) {\n return null;\n }\n }\n matchingMetadata = result;\n }\n result = matchingMetadata;\n } else {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"metadata does not contain all requested elementnames: not included in response\");\n return null;\n }\n } else {\n if (Log.isDebugEnabled(Geonet.CSW_SEARCH))\n Log.debug(Geonet.CSW_SEARCH, \"No ElementNames to apply\");\n }\n return result;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "DiskProfile updateImportedVolume(Type type, DiskOffering offering, VirtualMachine vm, VirtualMachineTemplate template, Long deviceId, Long poolId, String path, String chainInfo, DiskProfile diskProfile);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Allocates a new virtual machine instance in the CloudStack DB. This\n * orchestrates the creation of all virtual resources needed in CloudStack\n * DB to bring up a VM.\n *\n * @param vmInstanceName Instance name of the VM. This name uniquely\n * a VM in CloudStack's deploy environment. The caller gets to\n * define this VM but it must be unique for all of CloudStack.\n * @param template The template this VM is based on.\n * @param serviceOffering The service offering that specifies the offering this VM should provide.\n * @param defaultNetwork The default network for the VM.\n * @param rootDiskOffering For created VMs not based on templates, root disk offering specifies the root disk.\n * @param dataDiskOfferings Data disks to attach to the VM.\n * @param auxiliaryNetworks additional networks to attach the VMs to.\n * @param plan How to deploy the VM.\n * @param hyperType Hypervisor type\n * @param datadiskTemplateToDiskOfferingMap data disks to be created from datadisk templates and attached to the VM\n * @throws InsufficientCapacityException If there are insufficient capacity to deploy this vm.\n */\nvoid allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering, DiskOfferingInfo rootDiskOfferingInfo, List dataDiskOfferings, LinkedHashMap> auxiliaryNetworks, DeploymentPlan plan, HypervisorType hyperType, Map> extraDhcpOptions, Map datadiskTemplateToDiskOfferingMap) throws InsufficientCapacityException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private void processTypeAndName(MessageTree tree, Transaction t, TransactionType type, TransactionName name, int total, int fail, long sum, DurationMeta durations){\r\n String messageId = tree.getMessageId();\r\n if (type.getSuccessMessageUrl() == null) {\r\n type.setSuccessMessageUrl(messageId);\r\n }\r\n if (name.getSuccessMessageUrl() == null) {\r\n name.setSuccessMessageUrl(messageId);\r\n }\r\n if (type.getLongestMessageUrl() == null) {\r\n type.setLongestMessageUrl(messageId);\r\n }\r\n if (name.getLongestMessageUrl() == null) {\r\n name.setLongestMessageUrl(messageId);\r\n }\r\n type.incTotalCount(total);\r\n name.incTotalCount(total);\r\n type.incFailCount(fail);\r\n name.incFailCount(fail);\r\n type.setSum(type.getSum() + sum);\r\n name.setSum(name.getSum() + sum);\r\n long current = t.getTimestamp() / 1000 / 60;\r\n int min = (int) (current % (60));\r\n processTypeRange(type, min, total, fail, sum);\r\n processNameGraph(name, min, total, fail, sum, durations);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E... others){\r\n @SuppressWarnings(\"unchecked\")\r\n E[] array = (E[]) new Object[8 + others.length];\r\n array[0] = e1;\r\n array[1] = e2;\r\n array[2] = e3;\r\n array[3] = e4;\r\n array[4] = e5;\r\n array[5] = e6;\r\n array[6] = e7;\r\n array[7] = e8;\r\n System.arraycopy(others, 0, array, 8, others.length);\r\n return new ImmutableNullableList<>(array);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query5Def query(String pkg, String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name){\r\n return new Query5DefImpl<>(VIEW_BUILDER, pkg, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void downloadLargeMessages(final SyncConfig syncConfig, final Pop3Folder remoteFolder, final BackendFolder backendFolder, List largeMessages, final AtomicInteger progress, final AtomicInteger newMessages, final int todo, FetchProfile fp, SyncListener listener) throws MessagingException {\n final String folder = remoteFolder.getServerId();\n Timber.d(\"SYNC: Fetching large messages for folder %s\", folder);\n int maxDownloadSize = syncConfig.getMaximumAutoDownloadMessageSize();\n remoteFolder.fetch(largeMessages, fp, null, maxDownloadSize);\n for (Pop3Message message : largeMessages) {\n downloadSaneBody(syncConfig, remoteFolder, backendFolder, message);\n String messageServerId = message.getUid();\n Timber.v(\"About to notify listeners that we got a new large message %s:%s:%s\", accountName, folder, messageServerId);\n // Update the listener with what we've found\n progress.incrementAndGet();\n // TODO do we need to re-fetch this here?\n Set flags = backendFolder.getMessageFlags(messageServerId);\n // Increment the number of \"new messages\" if the newly downloaded message is\n // not marked as read.\n if (!flags.contains(Flag.SEEN)) {\n newMessages.incrementAndGet();\n }\n listener.syncProgress(folder, progress.get(), todo);\n boolean isOldMessage = isOldMessage(backendFolder, message);\n listener.syncNewMessage(folder, messageServerId, isOldMessage);\n }\n Timber.d(\"SYNC: Done fetching large messages for folder %s\", folder);\n}", "smellKey": "S107", "smellId": null, "repo": "wmontwe_thunderbird-android", "language": "java"} {"function": "@Nullable\npublic static Geometry ST_MakePolygon(Geometry shell, Geometry hole0, Geometry hole1, Geometry hole2, Geometry hole3, Geometry hole4, Geometry hole5, Geometry hole6, Geometry hole7, Geometry hole8, Geometry hole9){\r\n return makePolygon(shell, hole0, hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void createCashBasedCreditJournalEntriesAndReversalsForSavings(final Office office, final String currencyCode, final Integer accountTypeToBeCredited, final Long savingsProductId, final Long paymentTypeId, final Long savingsId, final String transactionId, final LocalDate transactionDate, final BigDecimal amount, final Boolean isReversal) {\n // reverse debits and credits for reversals\n if (isReversal) {\n createDebitJournalEntriesForSavings(office, currencyCode, accountTypeToBeCredited, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount);\n } else {\n createCreditJournalEntriesForSavings(office, currencyCode, accountTypeToBeCredited, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Creates a LogicalMatch.\n */\npublic static LogicalMatch create(RelNode input, RelDataType rowType, RexNode pattern, boolean strictStart, boolean strictEnd, Map patternDefinitions, Map measures, RexNode after, Map> subsets, boolean allRows, ImmutableBitSet partitionKeys, RelCollation orderKeys, @Nullable RexNode interval) {\n final RelOptCluster cluster = input.getCluster();\n final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE);\n return create(cluster, traitSet, input, rowType, pattern, strictStart, strictEnd, patternDefinitions, measures, after, subsets, allRows, partitionKeys, orderKeys, interval);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd, String vmName, long volumeId, String poolId, String volumePath, String secStorageUrl, String workerVmName, String nfsVersion) throws Exception {\n String volumeFolder = String.valueOf(volumeId) + \"/\";\n VirtualMachineMO workerVm = null;\n VirtualMachineMO vmMo = null;\n String exportName = UUID.randomUUID().toString();\n String searchExcludedFolders = cmd.getContextParam(\"searchexludefolders\");\n try {\n ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolId);\n if (morDs == null) {\n String msg = \"Unable to find volumes's storage pool for copy volume operation\";\n logger.error(msg);\n throw new Exception(msg);\n }\n boolean clonedWorkerVMNeeded = true;\n vmMo = hyperHost.findVmOnHyperHost(vmName);\n if (vmMo == null) {\n // create a dummy worker vm for attaching the volume\n DatastoreMO dsMo = new DatastoreMO(hyperHost.getContext(), morDs);\n workerVm = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVmName, null);\n if (workerVm == null) {\n String msg = \"Unable to create worker VM to execute CopyVolumeCommand\";\n logger.error(msg);\n throw new Exception(msg);\n }\n //attach volume to worker VM\n String datastoreVolumePath = getVolumePathInDatastore(dsMo, volumePath + \".vmdk\", searchExcludedFolders);\n workerVm.attachDisk(new String[] { datastoreVolumePath }, morDs);\n vmMo = workerVm;\n clonedWorkerVMNeeded = false;\n } else {\n vmMo.createSnapshot(exportName, \"Temporary snapshot for copy-volume command\", false, false);\n }\n exportVolumeToSecondaryStorage(vmMo, volumePath, secStorageUrl, \"volumes/\" + volumeFolder, exportName, hostService.getWorkerName(hyperHost.getContext(), cmd, 1, null), nfsVersion, clonedWorkerVMNeeded);\n return new Pair(volumeFolder, exportName);\n } finally {\n if (vmMo != null && vmMo.getSnapshotMor(exportName) != null) {\n vmMo.removeSnapshot(exportName, false);\n }\n if (workerVm != null) {\n workerVm.detachAllDisksAndDestroy();\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static Map unmodifiable(final K k1, final V v1, final K k2, final V v2, final K k3, final V v3, final K k4, final V v4){\r\n final LinkedHashMap mapPreservingOrder = newLinkedHashMap();\r\n mapPreservingOrder.put(k1, v1);\r\n mapPreservingOrder.put(k2, v2);\r\n mapPreservingOrder.put(k3, v3);\r\n mapPreservingOrder.put(k4, v4);\r\n return Collections.unmodifiableMap(mapPreservingOrder);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processBinding(RuleBuildContext context, BaseDescr descr, Declaration[] params, QueryArgument[] arguments, List requiredDeclarations, ReadAccessor arrayReader, Pattern pattern, BindingDescr bind){\r\n Declaration declr = context.getDeclarationResolver().getDeclaration(bind.getVariable());\r\n if (declr != null) {\r\n int pos = getPos(bind.getExpression(), params);\r\n if (pos >= 0) {\r\n String slot = bind.getExpression();\r\n String var = bind.getVariable();\r\n bind.setVariable(slot);\r\n bind.setExpression(var);\r\n } else {\r\n }\r\n }\r\n int pos = getPos(bind.getVariable(), params);\r\n if (pos >= 0) {\r\n declr = context.getDeclarationResolver().getDeclaration(bind.getExpression());\r\n if (declr != null) {\r\n requiredDeclarations.add(declr);\r\n arguments[pos] = new QueryArgument.Declr(declr);\r\n } else {\r\n DrlExprParser parser = new DrlExprParser(context.getConfiguration().getOption(LanguageLevelOption.KEY));\r\n ConstraintConnectiveDescr bresult = parser.parse(bind.getExpression());\r\n if (parser.hasErrors()) {\r\n for (DroolsParserException error : parser.getErrors()) {\r\n context.addError(new DescrBuildError(context.getParentDescr(), descr, null, \"Unable to parser pattern expression:\\n\" + error.getMessage()));\r\n }\r\n return;\r\n }\r\n arguments[pos] = getLiteralQueryArgument(context, descr, bresult);\r\n }\r\n } else {\r\n pos = getPos(bind.getExpression(), params);\r\n if (pos < 0) {\r\n context.addError(new DescrBuildError(context.getParentDescr(), descr, null, \"named argument does not exist:\\n\" + bind.getExpression()));\r\n return;\r\n }\r\n arguments[pos] = getVariableQueryArgument(arrayReader, params, pos, pattern, bind.getVariable());\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void assertPrepare(Connection connection, String sql, int limit, boolean materializationsEnabled, List> hooks, Consumer resultChecker, Consumer updateChecker, Consumer exceptionChecker, PreparedStatementConsumer consumer){\r\n try (Closer closer = new Closer()) {\r\n if (connection.isWrapperFor(CalciteConnection.class)) {\r\n final CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);\r\n final Properties properties = calciteConnection.getProperties();\r\n properties.setProperty(CalciteConnectionProperty.MATERIALIZATIONS_ENABLED.camelName(), Boolean.toString(materializationsEnabled));\r\n properties.setProperty(CalciteConnectionProperty.CREATE_MATERIALIZATIONS.camelName(), Boolean.toString(materializationsEnabled));\r\n if (!properties.containsKey(CalciteConnectionProperty.TIME_ZONE.camelName())) {\r\n properties.setProperty(CalciteConnectionProperty.TIME_ZONE.camelName(), DateTimeUtils.UTC_ZONE.getID());\r\n }\r\n }\r\n for (Pair hook : hooks) {\r\n closer.add(hook.left.addThread(hook.right));\r\n }\r\n PreparedStatement statement = connection.prepareStatement(sql);\r\n statement.setMaxRows(Math.max(limit, 0));\r\n ResultSet resultSet = null;\r\n Integer updateCount = null;\r\n try {\r\n consumer.accept(statement);\r\n if (updateChecker == null) {\r\n resultSet = statement.executeQuery();\r\n } else {\r\n updateCount = statement.executeUpdate(sql);\r\n }\r\n if (exceptionChecker != null) {\r\n exceptionChecker.accept(null);\r\n return;\r\n }\r\n } catch (Exception | Error e) {\r\n if (exceptionChecker != null) {\r\n exceptionChecker.accept(e);\r\n return;\r\n }\r\n throw e;\r\n }\r\n if (resultChecker != null) {\r\n resultChecker.accept(resultSet);\r\n }\r\n if (updateChecker != null) {\r\n updateChecker.accept(updateCount);\r\n }\r\n if (resultSet != null) {\r\n resultSet.close();\r\n }\r\n statement.close();\r\n connection.close();\r\n } catch (Throwable e) {\r\n String message = \"With materializationsEnabled=\" + materializationsEnabled + \", limit=\" + limit;\r\n if (!TestUtil.hasMessage(e, sql)) {\r\n message += \", sql=\" + sql;\r\n }\r\n throw TestUtil.rethrow(e, message);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static FixedDepositProductData instance(final DepositProductData depositProductData, final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest, final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm, final Integer maxDepositTerm, final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm, final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal minDepositAmount, final BigDecimal depositAmount, final BigDecimal maxDepositAmount) {\n final Map accountingMappings = null;\n final Collection paymentChannelToFundSourceMappings = null;\n final Collection currencyOptions = null;\n final Collection interestCompoundingPeriodTypeOptions = null;\n final Collection interestPostingPeriodTypeOptions = null;\n final Collection interestCalculationTypeOptions = null;\n final Collection interestCalculationDaysInYearTypeOptions = null;\n final Collection lockinPeriodFrequencyTypeOptions = null;\n final Collection withdrawalFeeTypeOptions = null;\n final Collection paymentTypeOptions = null;\n final Collection accountingRuleOptions = null;\n final Map> accountingMappingOptions = null;\n final Collection chargeOptions = null;\n final Collection penaltyOptions = null;\n final Collection charges = null;\n final Collection feeToIncomeAccountMappings = null;\n final Collection penaltyToIncomeAccountMappings = null;\n final Collection interestRateCharts = null;\n final InterestRateChartData chartTemplate = null;\n final Collection preClosurePenalInterestOnTypeOptions = null;\n final Collection periodFrequencyTypeOptions = null;\n final Collection taxGroupOptions = null;\n return new FixedDepositProductData(depositProductData.id, depositProductData.name, depositProductData.shortName, depositProductData.description, depositProductData.currency, depositProductData.nominalAnnualInterestRate, depositProductData.interestCompoundingPeriodType, depositProductData.interestPostingPeriodType, depositProductData.interestCalculationType, depositProductData.interestCalculationDaysInYearType, depositProductData.lockinPeriodFrequency, depositProductData.lockinPeriodFrequencyType, depositProductData.minBalanceForInterestCalculation, depositProductData.accountingRule, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, preClosurePenalApplicable, preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, minDepositAmount, depositAmount, maxDepositAmount, periodFrequencyTypeOptions, depositProductData.withHoldTax, depositProductData.taxGroup, taxGroupOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private Element process(ApplicationContext applicationContext, String process, HttpServletRequest request, AbstractMetadata metadata, boolean save, ServiceContext context, SettingManager sm, XsltMetadataProcessingReport report) throws Exception {\n boolean forEditing = false, withValidationErrors = false, keepXlinkAttributes = true;\n Element processedMetadata;\n Element beforeMetadata = dm.getMetadata(context, Integer.toString(metadata.getId()), false, false, false);\n try {\n final String siteURL = sm.getSiteURL(context);\n processedMetadata = XslProcessUtils.process(context, String.valueOf(metadata.getId()), process, save, true, true, report, siteURL, request.getParameterMap());\n if (processedMetadata == null) {\n throw new BadParameterEx(\"Processing failed\", \"Not found:\" + report.getNumberOfRecordNotFound() + \", Not owner:\" + report.getNumberOfRecordsNotEditable() + \", No process found:\" + report.getNoProcessFoundCount() + \".\");\n } else {\n UserSession userSession = context.getUserSession();\n if (userSession != null) {\n XMLOutputter outp = new XMLOutputter();\n String xmlAfter = outp.outputString(processedMetadata);\n String xmlBefore = outp.outputString(beforeMetadata);\n new RecordProcessingChangeEvent(metadata.getId(), Integer.parseInt(userSession.getUserId()), xmlBefore, xmlAfter, process).publish(ApplicationContextHolder.get());\n }\n }\n } catch (Exception e) {\n throw e;\n }\n return processedMetadata;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "private static int doBootstrap(JavaSparkContext jsc, String tableName, String tableType, String basePath, String sourcePath, String recordKeyCols, String partitionFields, String parallelism, String schemaProviderClass, String bootstrapIndexClass, String selectorClass, String keyGenerator, String fullBootstrapInputProvider, String payloadClassName, String enableHiveSync, String propsFilePath, List configs) throws IOException {\n TypedProperties properties = propsFilePath == null ? buildProperties(configs) : readConfig(jsc.hadoopConfiguration(), new Path(propsFilePath), configs).getProps(true);\n properties.setProperty(HoodieBootstrapConfig.BASE_PATH.key(), sourcePath);\n if (!StringUtils.isNullOrEmpty(keyGenerator) && KeyGeneratorType.getNames().contains(keyGenerator.toUpperCase(Locale.ROOT))) {\n properties.setProperty(HoodieWriteConfig.KEYGENERATOR_TYPE.key(), keyGenerator.toUpperCase(Locale.ROOT));\n } else {\n properties.setProperty(DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME().key(), keyGenerator);\n }\n properties.setProperty(HoodieBootstrapConfig.FULL_BOOTSTRAP_INPUT_PROVIDER_CLASS_NAME.key(), fullBootstrapInputProvider);\n properties.setProperty(HoodieBootstrapConfig.PARALLELISM_VALUE.key(), parallelism);\n properties.setProperty(HoodieBootstrapConfig.MODE_SELECTOR_CLASS_NAME.key(), selectorClass);\n properties.setProperty(DataSourceWriteOptions.RECORDKEY_FIELD().key(), recordKeyCols);\n properties.setProperty(DataSourceWriteOptions.PARTITIONPATH_FIELD().key(), partitionFields);\n HoodieStreamer.Config cfg = new HoodieStreamer.Config();\n cfg.targetTableName = tableName;\n cfg.targetBasePath = basePath;\n cfg.tableType = tableType;\n cfg.schemaProviderClassName = schemaProviderClass;\n cfg.bootstrapIndexClass = bootstrapIndexClass;\n cfg.payloadClassName = payloadClassName;\n cfg.enableHiveSync = Boolean.valueOf(enableHiveSync);\n new BootstrapExecutor(cfg, jsc, HadoopFSUtils.getFs(basePath, jsc.hadoopConfiguration()), jsc.hadoopConfiguration(), properties).execute();\n return 0;\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "/**\n * Creates a new REST producer.\n *\n * @param camelContext the camel context\n * @param host host in the syntax scheme:hostname:port, such as http:myserver:8080\n * @param verb HTTP verb such as GET, POST\n * @param basePath base path\n * @param uriTemplate uri template\n * @param queryParameters uri query parameters\n * @param consumes media-types for what the REST service consume as input (accept-type), is null or\n * */* for anything\n * @param produces media-types for what the REST service produces as output, can be null\n * @param configuration REST configuration\n * @param parameters additional parameters\n * @return a newly created REST producer\n * @throws Exception can be thrown\n */\nProducer createProducer(CamelContext camelContext, String host, String verb, String basePath, String uriTemplate, String queryParameters, String consumes, String produces, RestConfiguration configuration, Map parameters) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public static SavingsProductData template(final CurrencyData currency, final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final EnumOptionData accountingRule, final Collection currencyOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, final Map> accountingMappingOptions, final Collection chargeOptions, final Collection penaltyOptions, final Collection taxGroupOptions, final String accountMappingForPayment) {\n final Long id = null;\n final String name = null;\n final String shortName = null;\n final String description = null;\n final BigDecimal nominalAnnualInterestRate = null;\n final BigDecimal minRequiredOpeningBalance = null;\n final Integer lockinPeriodFrequency = null;\n final EnumOptionData lockinPeriodFrequencyType = null;\n final boolean withdrawalFeeForTransfers = false;\n final Map accountingMappings = null;\n final Collection paymentChannelToFundSourceMappings = null;\n final Collection charges = null;\n final Collection feeToIncomeAccountMappings = null;\n final Collection penaltyToIncomeAccountMappings = null;\n final boolean allowOverdraft = false;\n final BigDecimal overdraftLimit = null;\n final BigDecimal minRequiredBalance = null;\n final boolean enforceMinRequiredBalance = false;\n final BigDecimal maxAllowedLienLimit = null;\n final boolean lienAllowed = false;\n final BigDecimal minBalanceForInterestCalculation = null;\n final BigDecimal nominalAnnualInterestRateOverdraft = null;\n final BigDecimal minOverdraftForInterestCalculation = null;\n final boolean withHoldTax = false;\n final TaxGroupData taxGroup = null;\n final Boolean isDormancyTrackingActive = false;\n final Long daysToInactive = null;\n final Long daysToDormancy = null;\n final Long daysToEscheat = null;\n return new SavingsProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, accountingRule, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, allowOverdraft, overdraftLimit, minRequiredBalance, enforceMinRequiredBalance, maxAllowedLienLimit, lienAllowed, minBalanceForInterestCalculation, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup, taxGroupOptions, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat, accountMappingForPayment);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * @param BankAccount\n * @param BPartner\n * @param DocumentNo\n * @param DateFrom\n * @param DateTo\n * @param AmtFrom\n * @param AmtTo\n * @param DocType\n * @param TenderType\n * @param AuthCode\n * @param gridTab\n * @return list of bank account records\n */\nprotected Vector> getBankAccountData(Integer BankAccount, Integer BPartner, String DocumentNo, Timestamp DateFrom, Timestamp DateTo, BigDecimal AmtFrom, BigDecimal AmtTo, Integer DocType, String TenderType, String AuthCode, GridTab gridTab) {\n if (log.isLoggable(Level.CONFIG))\n log.config(\"C_BankAccount_ID=\" + BankAccount);\n Vector> data = new Vector>();\n StringBuilder sql = new StringBuilder();\n sql.append(\"SELECT py.C_DepositBatch_ID, db.DocumentNo, db.DateDeposit, db.C_BankAccount_ID, ba.AccountNo,\");\n sql.append(\"SUM(currencyConvertPayment(p.C_Payment_ID,ba.C_Currency_ID)) AS amount,\");\n sql.append(\"SUM(p.PayAmt) AS amountoriginal\");\n sql.append(\" FROM C_BankAccount ba\");\n sql.append(\" INNER JOIN C_Payment_v p ON (p.C_BankAccount_ID=ba.C_BankAccount_ID)\");\n sql.append(\" INNER JOIN C_Currency c ON (p.C_Currency_ID=c.C_Currency_ID)\");\n sql.append(\" INNER JOIN C_Payment py ON (py.C_Payment_ID=p.C_Payment_ID)\");\n sql.append(\" INNER JOIN C_DepositBatch db ON (py.C_DepositBatch_ID = db.C_DepositBatch_ID) \");\n sql.append(getSQLWhere(BPartner, DocumentNo, DateFrom, DateTo, AmtFrom, AmtTo, DocType, TenderType, AuthCode));\n sql.append(\" AND py.C_DepositBatch_ID <> 0\");\n sql.append(\" AND db.Processed = 'Y'\");\n sql.append(\" GROUP BY py.C_DepositBatch_ID,db.DocumentNo,db.DateDeposit, db.C_BankAccount_ID,ba.AccountNo\");\n PreparedStatement pstmt = null;\n ResultSet rs = null;\n try {\n pstmt = DB.prepareStatement(sql.toString(), null);\n setParameters(pstmt, BankAccount, BPartner, DocumentNo, DateFrom, DateTo, AmtFrom, AmtTo, DocType, TenderType, AuthCode, gridTab);\n rs = pstmt.executeQuery();\n while (rs.next()) {\n Vector line = new Vector(5);\n // 0-Selection\n line.add(Boolean.FALSE);\n // 1-DateDeposit\n line.add(rs.getTimestamp(3));\n KeyNamePair pp = new KeyNamePair(rs.getInt(1), rs.getString(2));\n // 2-C_DepositBatch\n line.add(pp);\n // 3-PayAmt\n line.add(rs.getBigDecimal(7));\n // 4-Conv Amt\n line.add(rs.getBigDecimal(6));\n pp = new KeyNamePair(rs.getInt(4), rs.getString(5));\n // 5-Bank Account\n line.add(pp);\n data.add(line);\n }\n } catch (SQLException e) {\n log.log(Level.SEVERE, sql.toString(), e);\n } finally {\n DB.close(rs, pstmt);\n rs = null;\n pstmt = null;\n }\n return data;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private void fetchAndSendResults(AsyncSendNode node, AsyncSendMemory memory, ReteEvaluator reteEvaluator, ContextEntry[] context, BetaConstraints betaConstraints, AlphaNodeFieldConstraint[] alphaConstraints, DataProvider dataProvider, Class resultClass, LeftTuple leftTuple, PropagationContext propagationContext){\r\n for (final java.util.Iterator it = dataProvider.getResults(leftTuple, reteEvaluator, memory.providerContext); it.hasNext(); ) {\r\n final Object object = it.next();\r\n if ((object == null) || !resultClass.isAssignableFrom(object.getClass())) {\r\n continue;\r\n }\r\n InternalFactHandle factHandle = node.createFactHandle(leftTuple, propagationContext, reteEvaluator, object);\r\n if (isAllowed(factHandle, alphaConstraints, reteEvaluator)) {\r\n propagate(node, reteEvaluator, factHandle, betaConstraints, context);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void insertEmbeddingOperation(Message message, Embedding embedding, String vectorFieldName, String textFieldName, TextSegment text, String collectionName, Object keyValue, String keyName) {\n List fields = new ArrayList<>();\n ArrayList list = new ArrayList<>();\n list.add(embedding.vectorAsList());\n fields.add(new InsertParam.Field(vectorFieldName, list));\n fields.add(new InsertParam.Field(textFieldName, Collections.singletonList(text.text())));\n if (ObjectHelper.isNotEmpty(keyValue) && ObjectHelper.isNotEmpty(keyName)) {\n ArrayList keyValues = new ArrayList<>();\n keyValues.add(keyValue);\n fields.add(new InsertParam.Field(keyName, keyValues));\n }\n InsertParam insertParam = InsertParam.newBuilder().withCollectionName(collectionName).withFields(fields).build();\n message.setBody(insertParam);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private static Task loadTable(URI fromURI, ImportTableDesc tblDesc, boolean replace, Path tgtPath, ReplicationSpec replicationSpec, EximUtil.SemanticAnalyzerWrapperContext x, Long writeId, int stmtId) throws HiveException {\n return loadTable(fromURI, tblDesc, replace, tgtPath, replicationSpec, x, writeId, stmtId, null, null);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public R execute(final MethodReferences.Call5 action, final Class callingClass, final String methodName, final A0 arg0, final A1 arg1, final A2 arg2, final A3 arg3, final A4 arg4){\r\n if (isIgnoreCache()) {\r\n return action.call(arg0, arg1, arg2, arg3, arg4);\r\n }\r\n final Key cacheKey = new Key(callingClass, methodName, arg0, arg1, arg2, arg3, arg4);\r\n return executeWithCaching(() -> action.call(arg0, arg1, arg2, arg3, arg4), cacheKey);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "// private OpenBitSet getDocs(DocumentSet docs, IndexSearcher searcher) throws IOException {\n// OpenBitSet bits = new OpenBitSet(searcher.getIndexReader().maxDoc());\n// for (Iterator i = docs.getDocumentIterator(); i.hasNext(); ) {\n// DocumentImpl nextDoc = (DocumentImpl) i.next();\n// Term dt = new Term(FIELD_DOC_ID, NumericUtils.intToPrefixCoded(nextDoc.getDocId()));\n// TermDocs td = searcher.getIndexReader().termDocs(dt);\n// while (td.next()) {\n// bits.set(td.doc());\n// }\n// td.close();\n// }\n// return bits;\n// }\nprivate NodeSet doQuery(final int contextId, final DocumentSet docs, final NodeSet contextSet, final int axis, IndexSearcher searcher, final short nodeType, Query query, Filter filter) throws IOException {\n SearchCollector collector = new SearchCollector(docs, contextSet, nodeType, axis, contextId);\n searcher.search(query, filter, collector);\n return collector.getResultSet();\n}", "smellKey": "S107", "smellId": null, "repo": "eXist-db_exist", "language": "java"} {"function": "/**\n * Same as\n * {@link #logAuditEvent(boolean, String, InetAddress, String, String, String,\n * FileStatus)} with additional parameters related to logging delegation token\n * tracking IDs.\n *\n * @param succeeded Whether authorization succeeded.\n * @param userName Name of the user executing the request.\n * @param addr Remote address of the request.\n * @param cmd The requested command.\n * @param src Path of affected source file.\n * @param dst Path of affected destination file (if any).\n * @param stat File information for operations that change the file's metadata\n * (permissions, owner, times, etc).\n * @param callerContext Context information of the caller\n * @param ugi UserGroupInformation of the current user, or null if not logging\n * token tracking information\n * @param dtSecretManager The token secret manager, or null if not logging\n * token tracking information\n */\npublic abstract void logAuditEvent(boolean succeeded, String userName, InetAddress addr, String cmd, String src, String dst, FileStatus stat, CallerContext callerContext, UserGroupInformation ugi, DelegationTokenSecretManager dtSecretManager);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static Event persistActionEvent(Long userId, Long accountId, Long domainId, String level, String type, Event.State state, boolean eventDisplayEnabled, String description, Long resourceId, String resourceType, Long startEventId) {\n EventVO event = new EventVO();\n event.setUserId(userId);\n event.setAccountId(accountId);\n event.setType(type);\n event.setState(state);\n event.setDescription(description);\n event.setDisplay(eventDisplayEnabled);\n if (domainId != null) {\n event.setDomainId(domainId);\n } else {\n event.setDomainId(getDomainId(accountId));\n }\n if (resourceId != null) {\n event.setResourceId(resourceId);\n }\n if (resourceType != null) {\n event.setResourceType(resourceType);\n }\n if (level != null && !level.isEmpty()) {\n event.setLevel(level);\n }\n if (startEventId != null) {\n event.setStartId(startEventId);\n }\n event = s_eventDao.persist(event);\n return event;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "/**\n * Applies postprocessing stylesheet if available.\n *

\n * Postprocessing files should be in the present/csw folder of the schema and have this naming:\n *

\n * For default CSW service\n *

\n * 1) gmd-csw-postprocessing.xsl : Postprocessing xsl applied for CSW service when requesting iso (gmd) output\n * 2) csw-csw-postprocessing.xsl : Postprocessing xsl applied for CSW service when requesting ogc (csw) output\n *

\n * For a custom sub-portal named inspire\n *

\n * 1) gmd-inspire-postprocessing.xsl : Postprocessing xsl applied for custom inspire sub-portal when requesting iso output\n * 2) csw-inspire-postprocessing.xsl : Postprocessing xsl applied for custom inspire sub-portal when requesting ogc (csw) output\n *\n * @param context Service context\n * @param schemaManager schemamanager\n * @param schema schema\n * @param result result\n * @param outputSchema requested OutputSchema\n * @param elementSetName requested ElementSetName\n * @param resultType requested ResultTYpe\n * @param id metadata id\n * @param displayLanguage language to use in response\n * @return metadata\n * @throws InvalidParameterValueEx hmm\n */\nprivate static Element applyPostProcessing(ServiceContext context, SchemaManager schemaManager, String schema, Element result, String outputSchema, ElementSetName elementSetName, ResultType resultType, String id, String displayLanguage) throws InvalidParameterValueEx {\n Path schemaDir = schemaManager.getSchemaCSWPresentDir(schema);\n final NodeInfo nodeInfo = ApplicationContextHolder.get().getBean(NodeInfo.class);\n Path styleSheet = schemaDir.resolve(outputSchema + \"-\" + (context.getService().equals(\"csw\") ? nodeInfo.getId() : context.getService()) + \"-postprocessing.xsl\");\n if (Files.exists(styleSheet)) {\n Map params = new HashMap<>();\n params.put(\"lang\", displayLanguage);\n try {\n result = Xml.transform(result, styleSheet, params);\n } catch (Exception e) {\n context.error(\"Error while transforming metadata with id : \" + id + \" using \" + styleSheet);\n context.error(\" (C) StackTrace:\\n\" + Util.getStackTrace(e));\n return null;\n }\n }\n return result;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static void propagate(LeftTupleSink sink, Tuple leftTuple, RightTuple rightTuple, BetaConstraints betaConstraints, PropagationContext propagationContext, ContextEntry[] context, boolean useLeftMemory, TupleSets trgLeftTuples, TupleSets stagedLeftTuples){\r\n if (betaConstraints.isAllowedCachedLeft(context, rightTuple.getFactHandleForEvaluation())) {\r\n if (rightTuple.getFirstChild() == null) {\r\n LeftTuple childLeftTuple = sink.createLeftTuple((LeftTuple) leftTuple, rightTuple, null, null, sink, useLeftMemory);\r\n childLeftTuple.setPropagationContext(propagationContext);\r\n trgLeftTuples.addInsert(childLeftTuple);\r\n } else {\r\n LeftTuple childLeftTuple = rightTuple.getFirstChild();\r\n childLeftTuple.setPropagationContext(propagationContext);\r\n updateChildLeftTuple(childLeftTuple, stagedLeftTuples, trgLeftTuples);\r\n }\r\n } else {\r\n deleteChildLeftTuple(propagationContext, trgLeftTuples, stagedLeftTuples, rightTuple.getFirstChild());\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query7Def query(String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name, Class type6, String arg6name, Class type7, String arg7name){\r\n return new Query7DefImpl<>(VIEW_BUILDER, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name, type6, arg6name, type7, arg7name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Host updateHost(Long hostId, String name, Long guestOSCategoryId, String allocationState, String url, List hostTags, Boolean isTagARule, String annotation, boolean isUpdateFromHostHealthCheck) throws NoTransitionException {\n // Verify that the host exists\n final HostVO host = _hostDao.findById(hostId);\n if (host == null) {\n throw new InvalidParameterValueException(\"Host with id \" + hostId + \" doesn't exist\");\n }\n boolean isUpdateHostAllocation = false;\n if (StringUtils.isNotBlank(allocationState)) {\n isUpdateHostAllocation = updateHostAllocationState(host, allocationState, isUpdateFromHostHealthCheck);\n }\n if (StringUtils.isNotBlank(name)) {\n updateHostName(host, name);\n }\n if (guestOSCategoryId != null) {\n updateHostGuestOSCategory(hostId, guestOSCategoryId);\n }\n if (hostTags != null) {\n updateHostTags(host, hostId, hostTags, isTagARule);\n }\n if (url != null) {\n _storageMgr.updateSecondaryStorage(hostId, url);\n }\n try {\n _storageMgr.enableHost(hostId);\n } catch (StorageUnavailableException | StorageConflictException e) {\n logger.error(String.format(\"Failed to setup host %s when enabled\", host));\n }\n final HostVO updatedHost = _hostDao.findById(hostId);\n sendAlertAndAnnotationForAutoEnableDisableKVMHostFeature(host, allocationState, isUpdateFromHostHealthCheck, isUpdateHostAllocation, annotation);\n return updatedHost;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static Specification findScrittoBy(String numeroProtocollo, String nome, String cognome, String ragioneSociale, List cnmDAmbitoList, Date dataScrittoDa, Date dataScrittoA, String tipoRicerca){\r\n return new Specification() {\r\n\r\n @Override\r\n public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) {\r\n List predicates = new ArrayList<>();\r\n if (tipoRicerca != null && tipoRicerca.equals(\"ASSOCIA_SCRITTO\")) {\r\n }\r\n if (StringUtils.isNotEmpty(numeroProtocollo)) {\r\n predicates.add(builder.equal(root.get(\"numeroProtocollo\"), numeroProtocollo));\r\n }\r\n if (nome != null && cognome != null) {\r\n predicates.add(builder.equal(root.get(\"nome\"), nome.toUpperCase()));\r\n predicates.add(builder.equal(root.get(\"cognome\"), cognome.toUpperCase()));\r\n }\r\n if (ragioneSociale != null) {\r\n predicates.add(builder.equal(root.get(\"ragioneSociale\"), ragioneSociale.toUpperCase()));\r\n }\r\n if (dataScrittoDa != null && dataScrittoA != null) {\r\n Predicate date = builder.between(root.get(\"dataOraInsert\"), dataScrittoDa, dataScrittoA);\r\n predicates.add(date);\r\n }\r\n query.distinct(true);\r\n return builder.and(predicates.toArray(new Predicate[0]));\r\n }\r\n };\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Write KeyValue format into a byte array.\n *\n * @param row row key\n * @param roffset row offset\n * @param rlength row length\n * @param family family name\n * @param foffset family offset\n * @param flength family length\n * @param qualifier column qualifier\n * @param qoffset qualifier offset\n * @param qlength qualifier length\n * @param timestamp version timestamp\n * @param type key type\n * @param value column value\n * @param voffset value offset\n * @param vlength value length\n * @return The newly created byte array.\n */\nprivate static byte[] createByteArray(byte[] row, int roffset, int rlength, byte[] family, int foffset, int flength, byte[] qualifier, int qoffset, int qlength, long timestamp, Type type, byte[] value, int voffset, int vlength) {\n int keyLength = validateAndGetKeyLength(row, rlength, family, flength, qualifier, qlength);\n // Value length\n vlength = value == null ? 0 : vlength;\n // Allocate right-sized byte array.\n byte[] bytes = new byte[KEYVALUE_INFRASTRUCTURE_SIZE + keyLength + vlength];\n // Write key, value and key row length.\n int pos = 0;\n pos = Bytes.putInt(bytes, pos, keyLength);\n pos = Bytes.putInt(bytes, pos, vlength);\n pos = writeKey(row, roffset, rlength, family, foffset, flength, qualifier, qoffset, qlength, timestamp, type, bytes, pos);\n if (value != null && value.length > 0) {\n Bytes.putBytes(bytes, pos, value, voffset, vlength);\n }\n return bytes;\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "/**\n * Add type descriptor.\n *\n * @param clsName Class name.\n * @param mapper Mapper.\n * @param serializer Serializer.\n * @param identity Key hashing mode.\n * @param affKeyFieldName Affinity key field name.\n * @param isEnum Enum flag.\n * @param enumMap Enum constants mapping.\n * @param canOverride Whether this descriptor can be override.\n * @throws BinaryObjectException If failed.\n */\nprivate void add(String clsName, BinaryInternalMapper mapper, BinarySerializer serializer, BinaryIdentityResolver identity, String affKeyFieldName, boolean isEnum, Map enumMap, boolean canOverride) throws BinaryObjectException {\n TypeDescriptor desc = new TypeDescriptor(clsName, mapper, serializer, identity, affKeyFieldName, isEnum, enumMap, canOverride);\n TypeDescriptor oldDesc = descs.get(clsName);\n if (oldDesc == null)\n descs.put(clsName, desc);\n else\n oldDesc.override(desc);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * Process a metadata with a database SQL query.\n * Checks that the result of the query is still XML valid.\n */\npublic static Element process(ServiceContext context, String id, boolean useRegexp, String search, String replace, String flags, boolean save, boolean index, boolean updateDateStamp, MetadataReplacementProcessingReport report) throws Exception {\n AccessManager accessMan = context.getBean(AccessManager.class);\n DataManager dataMan = context.getBean(DataManager.class);\n IMetadataUtils metadataUtils = context.getBean(IMetadataUtils.class);\n MetadataRepository metadataRepository = context.getBean(MetadataRepository.class);\n report.incrementProcessedRecords();\n // When a record is deleted the UUID is in the selection manager\n // and when retrieving id, return null\n if (id == null) {\n report.incrementNullRecords();\n return null;\n }\n int iId = Integer.valueOf(id);\n AbstractMetadata info = metadataUtils.findOne(id);\n if (info == null) {\n report.addNotFoundMetadataId(iId);\n } else if (!accessMan.canEdit(context, id)) {\n report.addNotEditableMetadataId(iId);\n } else {\n Element wellFormedXml = null;\n try {\n Lib.resource.checkEditPrivilege(context, id);\n String updatedXml = useRegexp ? (StringUtils.isNotEmpty(flags) ? metadataRepository.selectOneWithRegexSearchAndReplaceWithFlags(info.getUuid(), search, replace, flags) : metadataRepository.selectOneWithRegexSearchAndReplace(info.getUuid(), search, replace)) : metadataRepository.selectOneWithSearchAndReplace(info.getUuid(), search, replace);\n // Check XML is still well formed.\n wellFormedXml = Xml.loadString(updatedXml, false);\n String beforeProcessXML = info.getData();\n if (beforeProcessXML.equals(updatedXml)) {\n report.incrementUnchangedRecords();\n } else {\n // --- save metadata and return status\n if (save) {\n boolean validate = false;\n boolean ufo = true;\n String language = context.getLanguage();\n dataMan.updateMetadata(context, id, wellFormedXml, validate, ufo, language, new ISODate().toString(), updateDateStamp, index ? IndexingMode.full : IndexingMode.none);\n if (index) {\n dataMan.indexMetadata(id, true);\n }\n }\n }\n report.addMetadataId(iId);\n // TODO : it could be relevant to list at least\n // if there was any change in the record or not.\n // Using hash on processMd and metadata ?\n } catch (Exception e) {\n report.addMetadataError(info, e);\n context.error(\" Processing failed with error \" + e.getMessage());\n context.error(e);\n }\n return wellFormedXml;\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "/**\n * Creates a call to an aggregate function with all applicable operands.\n */\nprotected AggCall aggregateCall(SqlAggFunction aggFunction, boolean distinct, boolean approximate, boolean ignoreNulls, @Nullable RexNode filter, @Nullable ImmutableList distinctKeys, ImmutableList orderKeys, @Nullable String alias, ImmutableList preOperands, ImmutableList operands) {\n return new AggCallImpl(SqlParserPos.ZERO, aggFunction, distinct, approximate, ignoreNulls, filter, alias, preOperands, operands, distinctKeys, orderKeys);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "PublicIp getAvailablePublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List vlanDbIds, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private SearchRequest getScrollRequest(@Nonnull OperationContext opContext, @Nullable String scrollId, @Nullable String keepAlive, String[] indexArray, int size, @Nullable Filter postFilters, List entitySpecs, String finalInput, List sortCriteria, @Nullable List facets) {\n String pitId = null;\n Object[] sort = null;\n if (scrollId != null) {\n SearchAfterWrapper searchAfterWrapper = SearchAfterWrapper.fromScrollId(scrollId);\n sort = searchAfterWrapper.getSort();\n if (supportsPointInTime()) {\n if (System.currentTimeMillis() + 10000 <= searchAfterWrapper.getExpirationTime()) {\n pitId = searchAfterWrapper.getPitId();\n } else if (keepAlive != null) {\n pitId = createPointInTime(indexArray, keepAlive);\n }\n }\n } else if (supportsPointInTime() && keepAlive != null) {\n pitId = createPointInTime(indexArray, keepAlive);\n }\n return SearchRequestHandler.getBuilder(entitySpecs, searchConfiguration, customSearchConfiguration, queryFilterRewriteChain).getSearchRequest(opContext, finalInput, postFilters, sortCriteria, sort, pitId, keepAlive, size, facets);\n}", "smellKey": "S107", "smellId": null, "repo": "patotskiy_datahub", "language": "java"} {"function": "private boolean getKeyRecords(byte[] rawKey, byte[] rawEndKey, List resultKeys, List resultValues, MutableLong numKvs, RangeOption rangeOption, long limit, boolean countOnly){\r\n try (RocksIterator iter = db.newIterator(dataCfHandle)) {\r\n iter.seek(rawKey);\r\n boolean eor = false;\r\n while (iter.isValid() && (limit < 0 || resultKeys.size() < limit)) {\r\n byte[] key = iter.key();\r\n if (COMPARATOR.compare(rawEndKey, key) < 0) {\r\n eor = true;\r\n break;\r\n }\r\n MVCCRecord val = recordCoder.decode(iter.value());\r\n if (val.expired()) {\r\n val.recycle();\r\n continue;\r\n }\r\n processRecord(key, val, resultKeys, resultValues, numKvs, rangeOption, countOnly);\r\n iter.next();\r\n }\r\n if (eor) {\r\n return false;\r\n } else {\r\n return iter.isValid();\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Specification findSoggettoBy(String numeroDeterminazione, String numeroProtocolloAllegato, Long tipoAllegato, String numeroProtocolloPiano, Boolean ordinanzaProtocollata, Boolean ordinanzeSollecitate, Long idStatoSentenza, Date dataNotifica, Date dataNotificaA, Long idStatoOrdinanza, Date dataSentenzaDa, Date dataSentenzaA, String tipoRicerca, boolean isPregresso, VerbaleSearchParam parametriVerbale, Date dataCreazionePianoDa, Date dataCreazionePianoA){\r\n return new Specification() {\r\n\r\n @Override\r\n public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) {\r\n List predicates = new ArrayList<>();\r\n final Join cnmTOrdinanzaJoin = root.join(\"cnmTOrdinanza\");\r\n final Join cnmDStatoOrdVerbSogJoin = root.join(\"cnmDStatoOrdVerbSog\");\r\n final Join cnmDStatoOrdinanzaJoin = cnmTOrdinanzaJoin.join(\"cnmDStatoOrdinanza\");\r\n if (!isPregresso) {\r\n final Join cnmDTipoOrdinanzaJoin = cnmTOrdinanzaJoin.join(\"cnmDTipoOrdinanza\");\r\n predicates.add(builder.notEqual(cnmDTipoOrdinanzaJoin.get(\"idTipoOrdinanza\"), 1));\r\n if (ordinanzaProtocollata) {\r\n final Join cnmRAllegatoOrdinanzaJoin = cnmTOrdinanzaJoin.join(\"cnmRAllegatoOrdinanzas\");\r\n final Join cnmTAllegatoJoin = cnmRAllegatoOrdinanzaJoin.join(\"cnmTAllegato\");\r\n final Join cnmDTipoAllegatoJoin = cnmTAllegatoJoin.join(\"cnmDTipoAllegato\");\r\n Predicate p1 = builder.equal(cnmDTipoAllegatoJoin.get(\"idTipoAllegato\"), TipoAllegato.LETTERA_ORDINANZA.getId());\r\n Predicate p2 = builder.isNotNull(cnmTAllegatoJoin.get(\"numeroProtocollo\"));\r\n predicates.add(builder.and(p1, p2));\r\n }\r\n }\r\n if (parametriVerbale != null) {\r\n final Join cnmRVerbaleSoggettoJoin = root.join(\"cnmRVerbaleSoggetto\");\r\n final Join cnmRVerbaleJoin = cnmRVerbaleSoggettoJoin.join(\"cnmTVerbale\");\r\n if (StringUtils.isNotEmpty(parametriVerbale.getNumeroVerbale())) {\r\n Subquery subqueryROrdinanzaVerbaleSoggetto = query.subquery(CnmROrdinanzaVerbSog.class);\r\n Root rootsubqueryROrdinanzaVerbaleSoggetto = subqueryROrdinanzaVerbaleSoggetto.from(CnmROrdinanzaVerbSog.class);\r\n Predicate predicate = builder.equal(cnmRVerbaleJoin.get(\"numVerbale\"), parametriVerbale.getNumeroVerbale().toUpperCase());\r\n subqueryROrdinanzaVerbaleSoggetto.select(rootsubqueryROrdinanzaVerbaleSoggetto.get(\"cnmTOrdinanza\")).where(predicate).distinct(true);\r\n predicates.add(root.in(subqueryROrdinanzaVerbaleSoggetto));\r\n }\r\n if (parametriVerbale.getLettera() != null && !parametriVerbale.getLettera().isEmpty()) {\r\n final Join cnmRVerbaleIllecitoJoin = cnmRVerbaleJoin.join(\"cnmRVerbaleIllecitos\");\r\n final Join cnmDLetteraJoin = cnmRVerbaleIllecitoJoin.join(\"cnmDLettera\");\r\n predicates.add(cnmDLetteraJoin.in(parametriVerbale.getLettera()));\r\n }\r\n if (parametriVerbale.getStatoManuale() != null && !parametriVerbale.getStatoManuale().isEmpty()) {\r\n final Join cnmDStatoManualeJoin = cnmRVerbaleJoin.join(\"cnmDStatoManuale\");\r\n List idList = new ArrayList();\r\n for (CnmDStatoManuale statoManuale : parametriVerbale.getStatoManuale()) {\r\n idList.add(statoManuale.getId());\r\n }\r\n predicates.add(cnmDStatoManualeJoin.get(\"id\").in(idList));\r\n }\r\n }\r\n if (tipoRicerca != null && (tipoRicerca.equals(\"CREA_PIANO\") || tipoRicerca != null && tipoRicerca.equals(\"RICERCA_SOLLECITO\") || tipoRicerca != null && tipoRicerca.equals(\"RICERCA_SOLLECITO_RATE\"))) {\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 2));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 3));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 7));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 8));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 9));\r\n } else if (tipoRicerca != null && (tipoRicerca.equals(\"RICERCA_RISCOSSIONE_COATTIVA\"))) {\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 2));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 3));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 7));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 8));\r\n predicates.add(builder.notEqual(cnmDStatoOrdVerbSogJoin.get(\"idStatoOrdVerbSog\"), 9));\r\n predicates.add(builder.notEqual(cnmDStatoOrdinanzaJoin.get(\"idStatoOrdinanza\"), 1));\r\n predicates.add(builder.notEqual(cnmDStatoOrdinanzaJoin.get(\"idStatoOrdinanza\"), 3));\r\n predicates.add(builder.notEqual(cnmDStatoOrdinanzaJoin.get(\"idStatoOrdinanza\"), 5));\r\n predicates.add(builder.notEqual(cnmDStatoOrdinanzaJoin.get(\"idStatoOrdinanza\"), 6));\r\n final Join CnmTRiscossioneJoin = root.join(\"cnmTRiscossione\", JoinType.LEFT);\r\n predicates.add(builder.isNull(CnmTRiscossioneJoin.get(\"idRiscossione\")));\r\n }\r\n if (tipoRicerca != null && tipoRicerca.equals(\"CREA_PIANO\")) {\r\n final Join CnmRSoggRataJoin = root.join(\"cnmRSoggRatas\", JoinType.LEFT);\r\n predicates.add(builder.isNull(CnmRSoggRataJoin.get(\"cnmROrdinanzaVerbSog\")));\r\n }\r\n if (StringUtils.isNotEmpty(numeroDeterminazione))\r\n predicates.add(builder.equal(cnmTOrdinanzaJoin.get(\"numDeterminazione\"), numeroDeterminazione.toUpperCase()));\r\n if (StringUtils.isNotEmpty(numeroProtocolloAllegato) || idStatoSentenza != null) {\r\n final Join cnmRAllegatoOrdVerbSogJoin = root.join(\"cnmRAllegatoOrdVerbSogs\");\r\n final Join cnmTAllegatoJoin = cnmRAllegatoOrdVerbSogJoin.join(\"cnmTAllegato\");\r\n final Join cnmDTipoAllegatoJoin = cnmTAllegatoJoin.join(\"cnmDTipoAllegato\");\r\n if (StringUtils.isNotEmpty(numeroProtocolloAllegato)) {\r\n Predicate p1 = builder.equal(cnmTAllegatoJoin.get(\"numeroProtocollo\"), numeroProtocolloAllegato.toUpperCase());\r\n Predicate p2 = builder.equal(cnmDTipoAllegatoJoin.get(\"idTipoAllegato\"), tipoAllegato);\r\n predicates.add(builder.and(p1, p2));\r\n }\r\n if (idStatoSentenza != null) {\r\n final Join cnmTAllegatoFieldJoin = cnmTAllegatoJoin.join(\"cnmTAllegatoFields\");\r\n final Join cnmCFieldJoin = cnmTAllegatoFieldJoin.join(\"cnmCField\");\r\n final Join cnmDElementoElencoJoin = cnmDStatoOrdVerbSogJoin.join(\"cnmDElementoElenco\");\r\n Predicate p1 = builder.equal(cnmCFieldJoin.get(\"idField\"), Constants.ID_FIELD_ESITO_SENTENZA);\r\n Predicate p2 = builder.equal(cnmDTipoAllegatoJoin.get(\"idTipoAllegato\"), tipoAllegato);\r\n Predicate p3 = builder.equal(cnmTAllegatoFieldJoin.get(\"valoreNumber\"), idStatoSentenza);\r\n Predicate p4 = builder.equal(cnmDElementoElencoJoin.get(\"idElementoElenco\"), cnmTAllegatoFieldJoin.get(\"valoreNumber\"));\r\n predicates.add(builder.and(p1, p2, p3, p4));\r\n }\r\n }\r\n if (dataSentenzaDa != null && dataSentenzaA != null) {\r\n final Join cnmRAllegatoOrdVerbSogJoin = root.join(\"cnmRAllegatoOrdVerbSogs\");\r\n final Join cnmTAllegatoJoin = cnmRAllegatoOrdVerbSogJoin.join(\"cnmTAllegato\");\r\n final Join cnmTAllegatoFieldJoin = cnmTAllegatoJoin.join(\"cnmTAllegatoFields\");\r\n final Join cnmCFieldJoin = cnmTAllegatoFieldJoin.join(\"cnmCField\");\r\n Predicate p1 = builder.equal(cnmCFieldJoin.get(\"idField\"), Constants.ID_FIELD_DATA_SENTENZA);\r\n Predicate p2 = builder.between(cnmTAllegatoFieldJoin.get(\"valoreData\"), dataSentenzaDa, dataSentenzaA);\r\n predicates.add(builder.and(p1, p2));\r\n }\r\n if (tipoRicerca != null && tipoRicerca.equals(\"RICERCA_SOLLECITO_RATE\")) {\r\n final Join cnmRSoggRataJoin = root.join(\"cnmRSoggRatas\");\r\n final Join cnmDStatoRataJoin = cnmRSoggRataJoin.join(\"cnmDStatoRata\");\r\n predicates.add(builder.equal(cnmDStatoRataJoin.get(\"idStatoRata\"), Constants.ID_STATO_RATA_NON_PAGATO));\r\n if (dataCreazionePianoDa != null && dataCreazionePianoA != null) {\r\n final Join cnmTRataJoin = cnmRSoggRataJoin.join(\"cnmTRata\");\r\n final Join cnmTPianoRateJoin = cnmTRataJoin.join(\"cnmTPianoRate\");\r\n predicates.add(builder.between(cnmTPianoRateJoin.get(\"dataOraInsert\"), dataCreazionePianoDa, dataCreazionePianoA));\r\n }\r\n if (numeroProtocolloPiano != null && StringUtils.isNotBlank(numeroProtocolloPiano)) {\r\n final Join cnmTRataJoin = cnmRSoggRataJoin.join(\"cnmTRata\");\r\n final Join cnmTPianoRateJoin = cnmTRataJoin.join(\"cnmTPianoRate\");\r\n final Join cnmRAllegatoPianoRateJoin = cnmTPianoRateJoin.join(\"cnmRAllegatoPianoRates\");\r\n final Join cnmTAllegatoJoin = cnmRAllegatoPianoRateJoin.join(\"cnmTAllegato\");\r\n predicates.add(builder.equal(cnmTAllegatoJoin.get(\"numeroProtocollo\"), numeroProtocolloPiano.toUpperCase()));\r\n }\r\n }\r\n if (ordinanzeSollecitate != null && ordinanzeSollecitate) {\r\n root.join(\"cnmTSollecitos\");\r\n query.distinct(true);\r\n }\r\n if (idStatoOrdinanza != null) {\r\n final Join cnmTStatoOrdinanzaJoin = cnmTOrdinanzaJoin.join(\"cnmDStatoOrdinanza\");\r\n predicates.add(builder.equal(cnmTStatoOrdinanzaJoin.get(\"idStatoOrdinanza\"), idStatoOrdinanza));\r\n }\r\n if (dataNotifica != null && dataNotificaA != null) {\r\n final Join cnmTNotificaJoin = cnmTOrdinanzaJoin.join(\"cnmTNotificas\");\r\n Predicate date = builder.between(cnmTNotificaJoin.get(\"dataNotifica\"), dataNotifica, dataNotificaA);\r\n predicates.add(date);\r\n }\r\n query.distinct(true);\r\n return builder.and(predicates.toArray(new Predicate[0]));\r\n }\r\n };\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addMoveTask(ASTNode root, Table table, Map partitionSpec, Path oldPartitionLocation, Path newPartitionLocation, ListBucketingCtx lbCtx, Path queryTmpdir, Task truncateTask, TableDesc tableDesc) throws SemanticException {\n // Write the output to temporary directory and move it to the final location at the end\n // so the operation is atomic.\n LoadTableDesc loadTableDesc = new LoadTableDesc(queryTmpdir, tableDesc, partitionSpec == null ? new HashMap<>() : partitionSpec);\n loadTableDesc.setLbCtx(lbCtx);\n Task moveTask = TaskFactory.get(new MoveWork(null, null, loadTableDesc, null, false));\n truncateTask.addDependentTask(moveTask);\n addStatTask(root, table, oldPartitionLocation, newPartitionLocation, loadTableDesc, moveTask);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected boolean updateRecordWithExpiry(Data key, Object value, R record, long expiryTime, long now, boolean disableWriteThrough, int completionId, UUID source){\r\n return updateRecordWithExpiry(key, value, record, expiryTime, now, disableWriteThrough, completionId, source, null);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create a metadata folder according to MEF {@link Version} 2 specification. If current record\n * is based on an ISO profil, the stylesheet /convert/to19139.xsl is used to map to ISO. Both\n * files are included in MEF file. Export relevant information according to format parameter.\n *\n * @param zipFs Zip file to add new record\n */\nprivate static void createMetadataFolder(ServiceContext context, AbstractMetadata metadata, FileSystem zipFs, boolean skipUUID, Path stylePath, Format format, boolean resolveXlink, boolean removeXlinkAttribute, boolean addSchemaLocation) throws Exception {\n final Path metadataRootDir = zipFs.getPath(metadata.getUuid());\n Files.createDirectories(metadataRootDir);\n Pair recordAndMetadataForExport = MEFLib.retrieveMetadata(context, metadata, resolveXlink, removeXlinkAttribute, addSchemaLocation);\n AbstractMetadata record = recordAndMetadataForExport.one();\n String xmlDocumentAsString = recordAndMetadataForExport.two();\n String id = \"\" + record.getId();\n String isTemp = record.getDataInfo().getType().codeString;\n final Path metadataXmlDir = metadataRootDir.resolve(MD_DIR);\n Files.createDirectories(metadataXmlDir);\n for (Pair output : ExportFormat.getFormats(context, record)) {\n Files.write(metadataXmlDir.resolve(output.one()), output.two().getBytes(CHARSET));\n }\n // --- save native metadata\n Files.write(metadataXmlDir.resolve(FILE_METADATA), xmlDocumentAsString.getBytes(CHARSET));\n // --- save Feature Catalog\n String ftUUID = getFeatureCatalogID(context, record.getId());\n if (!ftUUID.equals(\"\")) {\n Pair ftrecordAndMetadata = MEFLib.retrieveMetadata(context, record, resolveXlink, removeXlinkAttribute, addSchemaLocation);\n Path featureMdDir = metadataRootDir.resolve(SCHEMA);\n Files.createDirectories(featureMdDir);\n Files.write(featureMdDir.resolve(FILE_METADATA), ftrecordAndMetadata.two().getBytes(CHARSET));\n }\n final Store store = context.getBean(\"resourceStore\", Store.class);\n final List publicResources = store.getResources(context, metadata.getUuid(), MetadataResourceVisibility.PUBLIC, null, true);\n // --- save thumbnails and maps\n if (format == Format.PARTIAL || format == Format.FULL) {\n StoreUtils.extract(context, metadata.getUuid(), publicResources, metadataRootDir.resolve(\"public\"), true);\n }\n List privateResources = null;\n if (format == Format.FULL) {\n try {\n Lib.resource.checkPrivilege(context, id, ReservedOperation.download);\n privateResources = store.getResources(context, metadata.getUuid(), MetadataResourceVisibility.PRIVATE, null, true);\n StoreUtils.extract(context, metadata.getUuid(), privateResources, metadataRootDir.resolve(\"private\"), true);\n } catch (Exception e) {\n // Current user could not download private data\n }\n }\n // --- save info file\n byte[] binData = MEFLib.buildInfoFile(context, record, format, publicResources, privateResources, skipUUID).getBytes(Constants.ENCODING);\n Files.write(metadataRootDir.resolve(FILE_INFO), binData);\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "private Pair importDisk(UnmanagedInstanceTO.Disk disk, VirtualMachine vm, Cluster cluster, DiskOffering diskOffering, Volume.Type type, String name, Long diskSize, Long minIops, Long maxIops, VirtualMachineTemplate template, Account owner, Long deviceId) {\n final DataCenter zone = dataCenterDao.findById(vm.getDataCenterId());\n final String path = StringUtils.isEmpty(disk.getFileBaseName()) ? disk.getImagePath() : disk.getFileBaseName();\n String chainInfo = disk.getChainInfo();\n if (vm.getHypervisorType() == Hypervisor.HypervisorType.VMware && StringUtils.isEmpty(chainInfo)) {\n VirtualMachineDiskInfo diskInfo = new VirtualMachineDiskInfo();\n diskInfo.setDiskDeviceBusName(String.format(\"%s%d:%d\", disk.getController(), disk.getControllerUnit(), disk.getPosition()));\n diskInfo.setDiskChain(new String[] { disk.getImagePath() });\n chainInfo = gson.toJson(diskInfo);\n }\n StoragePool storagePool = getStoragePool(disk, zone, cluster);\n DiskProfile profile = volumeManager.importVolume(type, name, diskOffering, diskSize, minIops, maxIops, vm.getDataCenterId(), vm.getHypervisorType(), vm, template, owner, deviceId, storagePool.getId(), path, chainInfo);\n return new Pair(profile, storagePool);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static LoanRescheduleModelRepaymentPeriod instance(final int periodNumber, final int oldPeriodNumber, LocalDate fromDate, final LocalDate dueDate, final Money principalDue, final Money outstandingLoanBalance, final Money interestDue, final Money feeChargesDue, final Money penaltyChargesDue, final Money totalDue, final boolean isNew) {\n return new LoanRescheduleModelRepaymentPeriod(periodNumber, oldPeriodNumber, fromDate, dueDate, principalDue, outstandingLoanBalance, interestDue, feeChargesDue, penaltyChargesDue, totalDue, isNew);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public EnqueueBean run(String user, Map userArgs, String command, String optionsFile, String otherFiles, String statusdir, String callback, String completedUrl, boolean enablelog, Boolean enableJobReconnect, String libdir) throws NotAuthorizedException, BadParam, BusyException, QueueException, IOException, InterruptedException, TooManyRequestsException {\n if (TempletonUtils.isset(appConf.sqoopArchive())) {\n if (!TempletonUtils.isset(appConf.sqoopPath()) && !TempletonUtils.isset(appConf.sqoopHome())) {\n throw new IllegalStateException(\"If '\" + AppConfig.SQOOP_ARCHIVE_NAME + \"' is defined, '\" + AppConfig.SQOOP_PATH_NAME + \"' and '\" + AppConfig.SQOOP_HOME_PATH + \"' must be defined\");\n }\n }\n runAs = user;\n List args = makeArgs(command, optionsFile, otherFiles, statusdir, completedUrl, enablelog, enableJobReconnect, libdir);\n return enqueueController(user, userArgs, callback, args);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Add the given filename to the fs.\n * @return the new INodesInPath instance that contains the new INode\n */\nprivate static INodesInPath addFile(FSDirectory fsd, INodesInPath existing, byte[] localName, PermissionStatus permissions, short replication, long preferredBlockSize, String clientName, String clientMachine, boolean shouldReplicate, String ecPolicyName, String storagePolicy) throws IOException {\n Preconditions.checkNotNull(existing);\n long modTime = now();\n INodesInPath newiip;\n fsd.writeLock();\n try {\n boolean isStriped = false;\n ErasureCodingPolicy ecPolicy = null;\n byte storagepolicyid = 0;\n if (storagePolicy != null && !storagePolicy.isEmpty()) {\n BlockStoragePolicy policy = fsd.getBlockManager().getStoragePolicy(storagePolicy);\n if (policy == null) {\n throw new HadoopIllegalArgumentException(\"Cannot find a block policy with the name \" + storagePolicy);\n }\n storagepolicyid = policy.getId();\n }\n if (!shouldReplicate) {\n ecPolicy = FSDirErasureCodingOp.getErasureCodingPolicy(fsd.getFSNamesystem(), ecPolicyName, existing);\n if (ecPolicy != null && (!ecPolicy.isReplicationPolicy())) {\n isStriped = true;\n }\n }\n final BlockType blockType = isStriped ? BlockType.STRIPED : BlockType.CONTIGUOUS;\n final Short replicationFactor = (!isStriped ? replication : null);\n final Byte ecPolicyID = (isStriped ? ecPolicy.getId() : null);\n INodeFile newNode = newINodeFile(fsd.allocateNewInodeId(), permissions, modTime, modTime, replicationFactor, ecPolicyID, preferredBlockSize, storagepolicyid, blockType);\n newNode.setLocalName(localName);\n newNode.toUnderConstruction(clientName, clientMachine);\n newiip = fsd.addINode(existing, newNode, permissions.getPermission());\n } finally {\n fsd.writeUnlock();\n }\n if (newiip == null) {\n NameNode.stateChangeLog.info(\"DIR* addFile: failed to add \" + existing.getPath() + \"/\" + DFSUtil.bytes2String(localName));\n return null;\n }\n if (NameNode.stateChangeLog.isDebugEnabled()) {\n NameNode.stateChangeLog.debug(\"DIR* addFile: \" + DFSUtil.bytes2String(localName) + \" is added\");\n }\n return newiip;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void writeMetadatatoPdf(List loaded, String filesAndCitekeys, XmpPreferences xmpPreferences, FilePreferences filePreferences, BibDatabaseMode databaseMode, BibEntryTypesManager entryTypesManager, FieldPreferences fieldPreferences, boolean writeXMP, boolean embeddBibfile){\r\n if (loaded.isEmpty()) {\r\n LOGGER.error(\"The write xmp option depends on a valid import option.\");\r\n return;\r\n }\r\n ParserResult pr = loaded.get(loaded.size() - 1);\r\n BibDatabaseContext databaseContext = pr.getDatabaseContext();\r\n BibDatabase dataBase = pr.getDatabase();\r\n XmpPdfExporter xmpPdfExporter = new XmpPdfExporter(xmpPreferences);\r\n EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter = new EmbeddedBibFilePdfExporter(databaseMode, entryTypesManager, fieldPreferences);\r\n if (\"all\".equals(filesAndCitekeys)) {\r\n for (BibEntry entry : dataBase.getEntries()) {\r\n writeMetadatatoPDFsOfEntry(databaseContext, entry.getCitationKey().orElse(\"\"), entry, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, writeXMP, embeddBibfile);\r\n }\r\n return;\r\n }\r\n List citeKeys = new ArrayList<>();\r\n List pdfs = new ArrayList<>();\r\n for (String fileOrCiteKey : filesAndCitekeys.split(\",\")) {\r\n if (fileOrCiteKey.toLowerCase(Locale.ROOT).endsWith(\".pdf\")) {\r\n pdfs.add(fileOrCiteKey);\r\n } else {\r\n citeKeys.add(fileOrCiteKey);\r\n }\r\n }\r\n writeMetadatatoPdfByCitekey(databaseContext, dataBase, citeKeys, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, writeXMP, embeddBibfile);\r\n writeMetadatatoPdfByFileNames(databaseContext, dataBase, pdfs, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, writeXMP, embeddBibfile);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "void fireAfterVariableChanged(String name, String id, Object oldValue, Object newValue, List tags, KogitoProcessInstance processInstance, KogitoNodeInstance nodeInstance, KieRuntime kruntime);", "smellKey": "S107", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public static Long onCompletedActionEvent(Long userId, Long accountId, String level, String type, boolean eventDisplayEnabled, String description, Long resourceId, String resourceType, long startEventId) {\n Ternary resourceDetails = getResourceDetails(resourceId, resourceType, type);\n Event event = persistActionEvent(userId, accountId, null, level, type, Event.State.Completed, eventDisplayEnabled, description, resourceDetails.first(), resourceDetails.third(), startEventId);\n publishOnEventBus(event, userId, accountId, EventCategory.ACTION_EVENT.getName(), type, com.cloud.event.Event.State.Completed, description, resourceDetails.second(), resourceDetails.third());\n return event.getId();\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "protected boolean doHasIndexOnColumns(Connection conn, String schemaOwner, String tableName, List columns, String indexTableName, String indexColumnTableName, String tableOwnerColumnName, String tableNameColumnName, String indexNameColumnName, String columnNameColumnName, String columPositionColumnName) {\n StringBuilder query = new StringBuilder(\"select count(*) from \" + indexTableName + \" ai\");\n for (int i = 1; i <= columns.size(); i++) {\n query.append(\", \").append(indexColumnTableName).append(\" aic\").append(i);\n }\n query.append(\" where ai.\").append(tableNameColumnName).append(\"='\").append(tableName).append(\"'\");\n if (tableOwnerColumnName != null) {\n query.append(\" and ai.\").append(tableOwnerColumnName).append(\"='\").append(schemaOwner).append(\"'\");\n }\n for (int i = 1; i <= columns.size(); i++) {\n query.append(\" and ai.\").append(indexNameColumnName).append(\"=aic\").append(i).append(\".\").append(indexNameColumnName);\n query.append(\" and aic\").append(i).append(\".\").append(columnNameColumnName).append(\"='\").append(columns.get(i - 1)).append(\"'\");\n query.append(\" and aic\").append(i).append(\".\").append(columPositionColumnName).append(\"=\").append(i);\n }\n try {\n return DbmsUtil.executeIntQuery(conn, query.toString()) >= 1;\n } catch (Exception e) {\n log.warn(\"could not determine presence of index columns on table [{}] using query [{}]\", tableName, query, e);\n return false;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "Network createPrivateNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, boolean bypassVlanOverlapCheck, Account owner, PhysicalNetwork pNtwk, Long vpcId) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "/**\n * Writes a daylight savings time transition to a POSIX timezone\n * description.\n *\n * @param tz Timezone\n * @param buf Buffer to append to\n * @param mode Transition mode\n * @param day Day of transition\n * @param month Month of transition\n * @param dayOfWeek Day of week of transition\n * @param time Time of transition in millis\n * @param timeMode Mode of time transition\n * @param verbose Verbose\n * @param isEnd Whether this transition is leaving DST\n */\nprivate static void appendPosixDaylightTransition(TimeZone tz, StringBuilder buf, int mode, int day, int month, int dayOfWeek, int time, int timeMode, boolean verbose, boolean isEnd) {\n buf.append(',');\n int week = day;\n switch(mode) {\n case // SimpleTimeZone.DOM_MODE\n 1:\n throw Util.needToImplement(0);\n case // SimpleTimeZone.DOW_GE_DOM_MODE\n 3:\n // If the day is 1, 8, 15, 22, we can translate this to case 2.\n switch(day) {\n case 1:\n // 1st week of month\n week = 1;\n break;\n case 8:\n // 2nd week of month\n week = 2;\n break;\n case 15:\n // 3rd week of month\n week = 3;\n break;\n case 22:\n // 4th week of month\n week = 4;\n break;\n default:\n throw new AssertionError(\"POSIX timezone format cannot represent \" + tz);\n }\n // fall through\n case // SimpleTimeZone.DOW_IN_MONTH_MODE\n 2:\n buf.append('M');\n // 1 <= m <= 12\n buf.append(month + 1);\n buf.append('.');\n if (week == -1) {\n // java represents 'last week' differently from POSIX\n week = 5;\n }\n // 1 <= n <= 5, 5 means 'last'\n buf.append(week);\n buf.append('.');\n // 0 <= d <= 6, 0=Sunday\n buf.append(dayOfWeek - 1);\n break;\n case // SimpleTimeZone.DOW_LE_DOM_MODE\n 4:\n throw Util.needToImplement(0);\n default:\n throw new AssertionError(\"unexpected value: \" + mode);\n }\n switch(timeMode) {\n case // SimpleTimeZone.WALL_TIME\n 0:\n break;\n case // SimpleTimeZone.STANDARD_TIME, e.g. Australia/Sydney\n 1:\n if (isEnd) {\n time += tz.getDSTSavings();\n }\n break;\n case // SimpleTimeZone.UTC_TIME, e.g. Europe/Paris\n 2:\n time += tz.getRawOffset();\n if (isEnd) {\n time += tz.getDSTSavings();\n }\n break;\n default:\n break;\n }\n if (verbose || (time != 7200000)) {\n // POSIX allows us to omit the time if it is 2am (the default)\n buf.append('/');\n appendPosixTime(buf, time);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public static LocalDate getNewRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate oldRepaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays, final boolean isSkipRepaymentOnFirstDayOfMonth, final Integer numberOfDays) {\n final Recur recur = CalendarUtils.getICalRecur(recurringRule);\n if (recur == null) {\n return null;\n }\n if (isValidRecurringDate(recur, seedDate, oldRepaymentDate, isSkipRepaymentOnFirstDayOfMonth, numberOfDays)) {\n return oldRepaymentDate;\n }\n LocalDate nextRepaymentDate = getNextRepaymentMeetingDate(recurringRule, seedDate, oldRepaymentDate, loanRepaymentInterval, frequency, workingDays, isSkipRepaymentOnFirstDayOfMonth, numberOfDays);\n return nextRepaymentDate;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private static void generateGet(EnumerableRelImplementor implementor, PhysType physType, BlockBuilder builder, ParameterExpression resultSet_, int i, Expression target, @Nullable Expression calendar_, SqlDialect.CalendarPolicy calendarPolicy) {\n final Primitive primitive = Primitive.ofBoxOr(physType.fieldClass(i));\n final RelDataType fieldType = physType.getRowType().getFieldList().get(i).getType();\n final List dateTimeArgs = new ArrayList<>();\n dateTimeArgs.add(Expressions.constant(i + 1));\n SqlTypeName sqlTypeName = fieldType.getSqlTypeName();\n boolean offset = false;\n switch(calendarPolicy) {\n case LOCAL:\n requireNonNull(calendar_, \"calendar_\");\n dateTimeArgs.add(calendar_);\n break;\n case NULL:\n // We don't specify a calendar at all, so we don't add an argument and\n // instead use the version of the getXXX that doesn't take a Calendar\n break;\n case DIRECT:\n sqlTypeName = SqlTypeName.ANY;\n break;\n case SHIFT:\n switch(sqlTypeName) {\n case TIMESTAMP:\n case DATE:\n offset = true;\n break;\n default:\n break;\n }\n break;\n default:\n break;\n }\n final Expression source;\n switch(sqlTypeName) {\n case DATE:\n case TIME:\n case TIMESTAMP:\n source = Expressions.call(getMethod(sqlTypeName, fieldType.isNullable(), offset), Expressions.list().append(Expressions.call(resultSet_, getMethod2(sqlTypeName), dateTimeArgs)).appendIf(offset, getTimeZoneExpression(implementor)));\n break;\n case ARRAY:\n final Expression x = Expressions.convert_(Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1)), java.sql.Array.class);\n source = Expressions.call(BuiltInMethod.JDBC_ARRAY_TO_LIST.method, x);\n break;\n case NULL:\n source = RexImpTable.NULL_EXPR;\n break;\n default:\n source = Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1));\n }\n builder.add(Expressions.statement(Expressions.assign(target, source)));\n // [CALCITE-596] If primitive type columns contain null value, returns null\n // object\n if (primitive != null) {\n builder.add(Expressions.ifThen(Expressions.call(resultSet_, \"wasNull\"), Expressions.statement(Expressions.assign(target, Expressions.constant(null)))));\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "private HttpEntity getExtent(String metadataUuid, String srs, Integer width, Integer height, String background, String fillColor, String strokeColor, Integer extentOrderOfAppearance, Boolean approved, NativeWebRequest nativeWebRequest, HttpServletRequest request) throws Exception {\n AbstractMetadata metadata = ApiUtils.canViewRecord(metadataUuid, approved, request);\n ServiceContext context = ApiUtils.createServiceContext(request);\n if (width != null && height != null) {\n throw new BadParameterEx(WIDTH_PARAM, WIDTH_AND_HEIGHT_BOTH_DEFINED_MESSAGE);\n }\n if (width == null && height == null) {\n throw new BadParameterEx(WIDTH_PARAM, WIDTH_AND_HEIGHT_BOTH_MISSING_MESSAGE);\n }\n if ((background != null) && (background.startsWith(\"http\")) && (disableFullUrlBackgroundMapServices)) {\n throw new BadParameterEx(BACKGROUND_PARAM, \"Background layers from provided are not supported, \" + \"use a preconfigured background layers map service.\");\n }\n String regionId;\n if (extentOrderOfAppearance == null) {\n regionId = String.format(\"metadata:@id%s\", metadata.getId());\n } else {\n regionId = String.format(\"metadata:@id%s:@xpath(%s)[%d]\", metadata.getId(), EXTENT_XPATH, extentOrderOfAppearance);\n }\n Request searchRequest = metadataRegionDAO.createSearchRequest(context).id(regionId);\n if (searchRequest.getLastModified().isPresent() && nativeWebRequest.checkNotModified(searchRequest.getLastModified().get())) {\n return null;\n }\n MapRenderer renderer = new MapRenderer(context);\n BufferedImage image = renderer.render(regionId, srs, width, height, background, null, null, null, fillColor, strokeColor);\n if (image == null) {\n return null;\n }\n try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {\n ImageIO.write(image, \"png\", out);\n MultiValueMap headers = new HttpHeaders();\n headers.add(HttpHeaders.CONTENT_DISPOSITION, String.format(\"inline; filename=\\\"%s-extent.png\\\"\", metadataUuid));\n headers.add(HttpHeaders.CACHE_CONTROL, \"no-cache\");\n headers.add(HttpHeaders.CONTENT_TYPE, \"image/png\");\n return new HttpEntity<>(out.toByteArray(), headers);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "/**\n * convert a regular join to a a map-side join.\n *\n * @param op\n * join operator\n * @param mapJoinPos\n * position of the source to be read as part of map-reduce framework. All other sources\n * are cached in memory\n * @param noCheckOuterJoin\n * @param validateMapJoinTree\n */\npublic MapJoinOperator convertMapJoin(HiveConf conf, JoinOperator op, boolean leftInputJoin, String[] baseSrc, List mapAliases, int mapJoinPos, boolean noCheckOuterJoin, boolean validateMapJoinTree) throws SemanticException {\n // outer join cannot be performed on a table which is being cached\n JoinDesc desc = op.getConf();\n JoinCondDesc[] condns = desc.getConds();\n if (!noCheckOuterJoin) {\n if (checkMapJoin(mapJoinPos, condns) < 0) {\n throw new SemanticException(ErrorMsg.NO_OUTER_MAPJOIN.getMsg());\n }\n }\n // Walk over all the sources (which are guaranteed to be reduce sink\n // operators).\n // The join outputs a concatenation of all the inputs.\n List> parentOps = op.getParentOperators();\n List> newParentOps = new ArrayList>();\n List> oldReduceSinkParentOps = new ArrayList>();\n // found a source which is not to be stored in memory\n if (leftInputJoin) {\n // assert mapJoinPos == 0;\n Operator parentOp = parentOps.get(0);\n assert parentOp.getParentOperators().size() == 1;\n Operator grandParentOp = parentOp.getParentOperators().get(0);\n oldReduceSinkParentOps.add(parentOp);\n newParentOps.add(grandParentOp);\n }\n byte pos = 0;\n // Remove parent reduce-sink operators\n for (String src : baseSrc) {\n if (src != null) {\n Operator parentOp = parentOps.get(pos);\n assert parentOp.getParentOperators().size() == 1;\n Operator grandParentOp = parentOp.getParentOperators().get(0);\n oldReduceSinkParentOps.add(parentOp);\n newParentOps.add(grandParentOp);\n }\n pos++;\n }\n // create the map-join operator\n MapJoinOperator mapJoinOp = convertJoinOpMapJoinOp(conf, op, leftInputJoin, baseSrc, mapAliases, mapJoinPos, noCheckOuterJoin);\n if (mapJoinOp == null) {\n return null;\n }\n // remove old parents\n for (pos = 0; pos < newParentOps.size(); pos++) {\n newParentOps.get(pos).replaceChild(oldReduceSinkParentOps.get(pos), mapJoinOp);\n }\n mapJoinOp.getParentOperators().removeAll(oldReduceSinkParentOps);\n mapJoinOp.setParentOperators(newParentOps);\n // make sure only map-joins can be performed.\n if (validateMapJoinTree) {\n validateMapJoinTypes(mapJoinOp);\n }\n // change the children of the original join operator to point to the map\n // join operator\n return mapJoinOp;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public SR getIscsiSR(final Connection conn, final String srNameLabel, final String target, String path, final String chapInitiatorUsername, final String chapInitiatorPassword, final boolean resignature, final boolean ignoreIntroduceException) {\n return getIscsiSR(conn, srNameLabel, target, path, chapInitiatorUsername, chapInitiatorPassword, resignature, SRType.LVMOISCSI.toString(), ignoreIntroduceException);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "//\tconvert\n/**\n * \tConvert an amount\n * \t@param ctx context\n * @param Amt amount to be converted\n * @param CurFrom_ID The C_Currency_ID FROM\n * @param CurTo_ID The C_Currency_ID TO\n * @param ConvDate conversion date - if null - use current date\n * @param C_ConversionType_ID conversion rate type - if 0 - use Default\n * \t@param AD_Client_ID client\n * \t@param AD_Org_ID organization\n * \t@param isCosting use for costing\n * @return converted amount or null if no rate\n */\npublic static BigDecimal convert(Properties ctx, BigDecimal Amt, int CurFrom_ID, int CurTo_ID, Timestamp ConvDate, int C_ConversionType_ID, int AD_Client_ID, int AD_Org_ID, boolean isCosting) {\n if (Amt == null)\n throw new IllegalArgumentException(\"Required parameter missing - Amt\");\n if (CurFrom_ID == CurTo_ID || Amt.compareTo(Env.ZERO) == 0)\n return Amt;\n //\tGet Rate\n BigDecimal retValue = getRate(CurFrom_ID, CurTo_ID, ConvDate, C_ConversionType_ID, AD_Client_ID, AD_Org_ID);\n if (retValue == null)\n return null;\n //\tGet Amount in Currency Precision\n retValue = retValue.multiply(Amt);\n int stdPrecision = isCosting ? MCurrency.getCostingPrecision(ctx, CurTo_ID) : MCurrency.getStdPrecision(ctx, CurTo_ID);\n if (retValue.scale() > stdPrecision)\n retValue = retValue.setScale(stdPrecision, RoundingMode.HALF_UP);\n return retValue;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public static Page readAndTransformPaginatedItems(ResponseT response, TableSchema tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension, Function>> getItems, Function> getLastEvaluatedKey, Function count, Function scannedCount, Function consumedCapacity){\r\n List collect = getItems.apply(response).stream().map(itemMap -> readAndTransformSingleItem(itemMap, tableSchema, operationContext, dynamoDbEnhancedClientExtension)).collect(Collectors.toList());\r\n Page.Builder pageBuilder = Page.builder(tableSchema.itemType().rawClass()).items(collect).count(count.apply(response)).scannedCount(scannedCount.apply(response)).consumedCapacity(consumedCapacity.apply(response));\r\n if (getLastEvaluatedKey.apply(response) != null && !getLastEvaluatedKey.apply(response).isEmpty()) {\r\n pageBuilder.lastEvaluatedKey(getLastEvaluatedKey.apply(response));\r\n }\r\n return pageBuilder.build();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Execute clustering to write inputRecords into new files as defined by rules in strategy parameters.\n * The number of new file groups created is bounded by numOutputGroups.\n * Note that commit is not done as part of strategy. Commit is callers responsibility.\n */\npublic abstract Iterator> performClusteringWithRecordsIterator(final Iterator> records, final int numOutputGroups, final String instantTime, final Map strategyParams, final Schema schema, final List fileGroupIdList, final boolean preserveHoodieMetadata, final TaskContextSupplier taskContextSupplier);", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "//************************************************************************************************\n// Decimal Multiply.\nprivate static boolean doMultiply(int leftSignum, long leftFast0, long leftFast1, long leftFast2, int leftIntegerDigitCount, int leftScale, int rightSignum, long rightFast0, long rightFast1, long rightFast2, int rightIntegerDigitCount, int rightScale, FastHiveDecimal fastResult) {\n // Set signum before; if result is zero, fastMultiply will set signum to 0.\n fastResult.fastSignum = (leftSignum == rightSignum ? 1 : -1);\n int resultScale = leftScale + rightScale;\n /*\n * For multiplicands with scale 0, trim trailing zeroes.\n */\n if (leftScale == 0) {\n // Pretend like it has fractional digits so we can get the trailing zero count.\n final int leftTrailingZeroCount = fastTrailingDecimalZeroCount(leftFast0, leftFast1, leftFast2, 0, leftIntegerDigitCount);\n if (leftTrailingZeroCount > 0) {\n doFastScaleDown(leftFast0, leftFast1, leftFast2, leftTrailingZeroCount, fastResult);\n resultScale -= leftTrailingZeroCount;\n leftFast0 = fastResult.fast0;\n leftFast1 = fastResult.fast1;\n leftFast2 = fastResult.fast2;\n }\n }\n if (rightScale == 0) {\n // Pretend like it has fractional digits so we can get the trailing zero count.\n final int rightTrailingZeroCount = fastTrailingDecimalZeroCount(rightFast0, rightFast1, rightFast2, 0, rightIntegerDigitCount);\n if (rightTrailingZeroCount > 0) {\n doFastScaleDown(rightFast0, rightFast1, rightFast2, rightTrailingZeroCount, fastResult);\n resultScale -= rightTrailingZeroCount;\n rightFast0 = fastResult.fast0;\n rightFast1 = fastResult.fast1;\n rightFast2 = fastResult.fast2;\n }\n }\n boolean largeOverflow = !fastMultiply5x5HalfWords(leftFast0, leftFast1, leftFast2, rightFast0, rightFast1, rightFast2, fastResult);\n if (largeOverflow) {\n return false;\n }\n if (fastResult.fastSignum == 0) {\n fastResult.fastScale = 0;\n return true;\n }\n if (resultScale < 0) {\n if (-resultScale >= HiveDecimal.MAX_SCALE) {\n return false;\n }\n if (!fastScaleUp(fastResult.fast0, fastResult.fast1, fastResult.fast2, -resultScale, fastResult)) {\n return false;\n }\n resultScale = 0;\n }\n int precision;\n if (fastResult.fast2 != 0) {\n precision = TWO_X_LONGWORD_DECIMAL_DIGITS + fastLongWordPrecision(fastResult.fast2);\n } else if (fastResult.fast1 != 0) {\n precision = LONGWORD_DECIMAL_DIGITS + fastLongWordPrecision(fastResult.fast1);\n } else {\n precision = fastLongWordPrecision(fastResult.fast0);\n }\n int integerDigitCount = Math.max(0, precision - resultScale);\n if (integerDigitCount > HiveDecimal.MAX_PRECISION) {\n // Integer is too large -- cannot recover by trimming fractional digits.\n return false;\n }\n if (precision > HiveDecimal.MAX_PRECISION || resultScale > HiveDecimal.MAX_SCALE) {\n // Trim off lower fractional digits but with NO ROUNDING.\n final int maxScale = HiveDecimal.MAX_SCALE - integerDigitCount;\n final int scaleDown = resultScale - maxScale;\n if (!fastScaleDownNoRound(fastResult.fastSignum, fastResult.fast0, fastResult.fast1, fastResult.fast2, scaleDown, fastResult)) {\n // Round fractional must be 0. Not allowed to throw away digits.\n return false;\n }\n resultScale -= scaleDown;\n }\n fastResult.fastScale = resultScale;\n // This assume no round up...\n fastResult.fastIntegerDigitCount = integerDigitCount;\n if (fastResult.fastScale > HiveDecimal.MAX_SCALE) {\n // We are not allowed to lose digits in multiply to be compatible with OldHiveDecimal\n // behavior, so overflow.\n // CONSIDER: Does it make sense to be so restrictive. If we just did repeated addition,\n // it would succeed...\n return false;\n }\n final int resultTrailingZeroCount = fastTrailingDecimalZeroCount(fastResult.fast0, fastResult.fast1, fastResult.fast2, fastResult.fastIntegerDigitCount, fastResult.fastScale);\n if (resultTrailingZeroCount > 0) {\n doFastScaleDown(fastResult, resultTrailingZeroCount, fastResult);\n if (fastResult.fastSignum == 0) {\n fastResult.fastScale = 0;\n } else {\n fastResult.fastScale -= resultTrailingZeroCount;\n }\n }\n return true;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static ExprViewItem expr(Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Variable var11, Predicate11 predicate){\r\n return new Expr11ViewItemImpl<>(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, new Predicate11.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param depMode Deployment mode.\n * @param rsrcName Resource name (could be task name).\n * @param clsName Class name.\n * @param userVer User version.\n * @param sndNodeId Sender node ID.\n * @param clsLdrId Class loader ID.\n * @param participants Node class loader participant map.\n * @param nodeFilter Node filter for class loader.\n * @return Deployment class if found.\n */\n@Nullable\npublic GridDeployment getGlobalDeployment(DeploymentMode depMode, String rsrcName, String clsName, String userVer, UUID sndNodeId, IgniteUuid clsLdrId, Map participants, @Nullable IgnitePredicate nodeFilter) {\n if (locDep != null)\n return locDep;\n String lambdaEnclosingClsName = U.lambdaEnclosingClassName(clsName);\n if (lambdaEnclosingClsName != null)\n clsName = lambdaEnclosingClsName;\n GridDeploymentMetadata meta = new GridDeploymentMetadata();\n meta.deploymentMode(depMode);\n meta.className(clsName);\n meta.alias(rsrcName);\n meta.userVersion(userVer);\n meta.senderNodeId(sndNodeId);\n meta.classLoaderId(clsLdrId);\n meta.participants(participants);\n meta.nodeFilter(nodeFilter);\n if (!ctx.config().isPeerClassLoadingEnabled()) {\n meta.record(true);\n return locStore.getDeployment(meta);\n }\n // In shared mode, if class is locally available, we never load\n // from remote node simply because the class loader needs to be \"shared\".\n if (isPerVersionMode(meta.deploymentMode())) {\n meta.record(true);\n boolean reuse = true;\n // Check local exclusions.\n if (!sndNodeId.equals(ctx.localNodeId())) {\n String[] p2pExc = ctx.config().getPeerClassLoadingLocalClassPathExclude();\n if (p2pExc != null) {\n for (String rsrc : p2pExc) {\n // Remove star (*) at the end.\n if (rsrc.endsWith(\"*\"))\n rsrc = rsrc.substring(0, rsrc.length() - 1);\n if (meta.alias().startsWith(rsrc) || meta.className().startsWith(rsrc)) {\n if (log.isDebugEnabled())\n log.debug(\"Will not reuse local deployment because resource is excluded [meta=\" + meta + ']');\n reuse = false;\n break;\n }\n }\n }\n }\n GridDeployment dep = verStore.searchDeploymentCache(meta);\n if (dep != null)\n return dep;\n if (reuse) {\n GridDeployment locDep = locStore.getDeployment(meta);\n if (locDep == null && participants != null && participants.containsKey(ctx.localNodeId()))\n locDep = locStore.getDeployment(participants.get(ctx.localNodeId()));\n if (locDep != null) {\n if (!isPerVersionMode(locDep.deployMode())) {\n U.warn(log, \"Failed to deploy class in SHARED or CONTINUOUS mode (class is locally deployed \" + \"in some other mode). Either change IgniteConfiguration.getDeploymentMode() property to \" + \"SHARED or CONTINUOUS or remove class from local classpath and any of \" + \"the local GAR deployments that may have it [cls=\" + meta.className() + \", depMode=\" + locDep.deployMode() + ']');\n return null;\n }\n if (!locDep.userVersion().equals(meta.userVersion())) {\n U.warn(log, \"Failed to deploy class in SHARED or CONTINUOUS mode for given user version \" + \"(class is locally deployed for a different user version) [cls=\" + meta.className() + \", localVer=\" + locDep.userVersion() + \", otherVer=\" + meta.userVersion() + ']');\n return null;\n }\n if (log.isDebugEnabled())\n log.debug(\"Reusing local deployment for SHARED or CONTINUOUS mode: \" + locDep);\n return locDep;\n }\n }\n return verStore.getDeployment(meta);\n }\n // Private or Isolated mode.\n meta.record(false);\n GridDeployment dep = ldrStore.searchDeploymentCache(meta);\n if (dep != null)\n return dep;\n dep = locStore.getDeployment(meta);\n if (sndNodeId.equals(ctx.localNodeId())) {\n if (dep == null)\n U.warn(log, \"Task got undeployed while deployment was in progress: \" + meta);\n // For local execution, return the same deployment as for the task.\n return dep;\n }\n if (dep != null)\n meta.parentLoader(dep.classLoader());\n meta.record(true);\n return ldrStore.getDeployment(meta);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public static SavingsAccountData importInstanceGroup(Long groupId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate, BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodTypeEnum, EnumOptionData interestPostingPeriodTypeEnum, EnumOptionData interestCalculationTypeEnum, EnumOptionData interestCalculationDaysInYearTypeEnum, BigDecimal minRequiredOpeningBalance, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyTypeEnum, boolean applyWithdrawalFeeForTransfers, Integer rowIndex, String externalId, Collection charges, boolean allowOverdraft, BigDecimal overdraftLimit, String locale, String dateFormat) {\n return new SavingsAccountData(groupId, productId, fieldOfficerId, submittedOnDate, nominalAnnualInterestRate, interestCompoundingPeriodTypeEnum, interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyTypeEnum, applyWithdrawalFeeForTransfers, rowIndex, externalId, charges, allowOverdraft, overdraftLimit, null, locale, dateFormat);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public IBaseResource resourceById(String resourceClass, String stringId, String ifVersionMatches, String version, Boolean returnNull, IBaseResource returnResource, Boolean throwError, Map extraParameters){\r\n IReadTyped resource = client.read().resource(resourceClass);\r\n IReadExecutable readExecutable = readWithOptionalVersion(stringId, resource, version);\r\n ExtraParameters.process(extraParameters, readExecutable);\r\n return processOptionalParams(ifVersionMatches, returnNull, returnResource, throwError, readExecutable);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected DiskOfferingVO createDiskOffering(final Long userId, final List domainIds, final List zoneIds, final String name, final String description, final String provisioningType, final Long numGibibytes, String tags, boolean isCustomized, final boolean localStorageRequired, final boolean isDisplayOfferingEnabled, final Boolean isCustomizedIops, Long minIops, Long maxIops, Long bytesReadRate, Long bytesReadRateMax, Long bytesReadRateMaxLength, Long bytesWriteRate, Long bytesWriteRateMax, Long bytesWriteRateMaxLength, Long iopsReadRate, Long iopsReadRateMax, Long iopsReadRateMaxLength, Long iopsWriteRate, Long iopsWriteRateMax, Long iopsWriteRateMaxLength, final Integer hypervisorSnapshotReserve, String cacheMode, final Map details, final Long storagePolicyID, final boolean diskSizeStrictness, final boolean encrypt) {\n // special case for custom disk offerings\n long diskSize = 0;\n long maxVolumeSizeInGb = VolumeOrchestrationService.MaxVolumeSize.value();\n if (numGibibytes != null && numGibibytes <= 0) {\n throw new InvalidParameterValueException(\"Please specify a disk size of at least 1 GB.\");\n } else if (numGibibytes != null && numGibibytes > maxVolumeSizeInGb) {\n throw new InvalidParameterValueException(String.format(\"The maximum size for a disk is %d GB.\", maxVolumeSizeInGb));\n }\n final ProvisioningType typedProvisioningType = ProvisioningType.getProvisioningType(provisioningType);\n if (numGibibytes != null) {\n diskSize = numGibibytes * 1024 * 1024 * 1024;\n }\n if (diskSize == 0) {\n isCustomized = true;\n }\n if (Boolean.TRUE.equals(isCustomizedIops) || isCustomizedIops == null) {\n minIops = null;\n maxIops = null;\n } else {\n if (minIops == null && maxIops == null) {\n minIops = 0L;\n maxIops = 0L;\n } else {\n if (minIops == null || minIops <= 0) {\n throw new InvalidParameterValueException(\"The min IOPS must be greater than 0.\");\n }\n if (maxIops == null) {\n maxIops = 0L;\n }\n if (minIops > maxIops) {\n throw new InvalidParameterValueException(\"The min IOPS must be less than or equal to the max IOPS.\");\n }\n }\n }\n // Filter child domains when both parent and child domains are present\n List filteredDomainIds = filterChildSubDomains(domainIds);\n // Check if user exists in the system\n final User user = _userDao.findById(userId);\n if (user == null || user.getRemoved() != null) {\n throw new InvalidParameterValueException(\"Unable to find active user by id \" + userId);\n }\n final Account account = _accountDao.findById(user.getAccountId());\n if (account.getType() == Account.Type.DOMAIN_ADMIN) {\n if (filteredDomainIds.isEmpty()) {\n throw new InvalidParameterValueException(String.format(\"Unable to create public disk offering by admin: %s because it is domain-admin\", user.getUuid()));\n }\n if (StringUtils.isNotBlank(tags) && !ALLOW_DOMAIN_ADMINS_TO_CREATE_TAGGED_OFFERINGS.valueIn(account.getAccountId())) {\n throw new InvalidParameterValueException(String.format(\"User [%s] is unable to create disk offerings with storage tags.\", user.getUuid()));\n }\n for (Long domainId : filteredDomainIds) {\n if (domainId == null || !_domainDao.isChildDomain(account.getDomainId(), domainId)) {\n throw new InvalidParameterValueException(String.format(\"Unable to create disk offering by another domain-admin: %s for domain: %s\", user.getUuid(), _entityMgr.findById(Domain.class, domainId).getUuid()));\n }\n }\n } else if (account.getType() != Account.Type.ADMIN) {\n throw new InvalidParameterValueException(String.format(\"Unable to create disk offering by user: %s because it is not root-admin or domain-admin\", user.getUuid()));\n }\n tags = com.cloud.utils.StringUtils.cleanupTags(tags);\n final DiskOfferingVO newDiskOffering = new DiskOfferingVO(name, description, typedProvisioningType, diskSize, tags, isCustomized, isCustomizedIops, minIops, maxIops);\n newDiskOffering.setUseLocalStorage(localStorageRequired);\n newDiskOffering.setDisplayOffering(isDisplayOfferingEnabled);\n setBytesRate(newDiskOffering, bytesReadRate, bytesReadRateMax, bytesReadRateMaxLength, bytesWriteRate, bytesWriteRateMax, bytesWriteRateMaxLength);\n setIopsRate(newDiskOffering, iopsReadRate, iopsReadRateMax, iopsReadRateMaxLength, iopsWriteRate, iopsWriteRateMax, iopsWriteRateMaxLength);\n if (cacheMode != null) {\n newDiskOffering.setCacheMode(DiskOffering.DiskCacheMode.valueOf(cacheMode.toUpperCase()));\n }\n if (hypervisorSnapshotReserve != null && hypervisorSnapshotReserve < 0) {\n throw new InvalidParameterValueException(\"If provided, Hypervisor Snapshot Reserve must be greater than or equal to 0.\");\n }\n newDiskOffering.setEncrypt(encrypt);\n newDiskOffering.setHypervisorSnapshotReserve(hypervisorSnapshotReserve);\n newDiskOffering.setDiskSizeStrictness(diskSizeStrictness);\n CallContext.current().setEventDetails(\"Disk offering id=\" + newDiskOffering.getId());\n final DiskOfferingVO offering = _diskOfferingDao.persist(newDiskOffering);\n if (offering != null) {\n List detailsVO = new ArrayList<>();\n for (Long domainId : filteredDomainIds) {\n detailsVO.add(new DiskOfferingDetailVO(offering.getId(), ApiConstants.DOMAIN_ID, String.valueOf(domainId), false));\n }\n if (CollectionUtils.isNotEmpty(zoneIds)) {\n for (Long zoneId : zoneIds) {\n detailsVO.add(new DiskOfferingDetailVO(offering.getId(), ApiConstants.ZONE_ID, String.valueOf(zoneId), false));\n }\n }\n if (MapUtils.isNotEmpty(details)) {\n details.forEach((key, value) -> {\n boolean displayDetail = !StringUtils.equalsAny(key, Volume.BANDWIDTH_LIMIT_IN_MBPS, Volume.IOPS_LIMIT);\n detailsVO.add(new DiskOfferingDetailVO(offering.getId(), key, value, displayDetail));\n });\n }\n if (storagePolicyID != null) {\n detailsVO.add(new DiskOfferingDetailVO(offering.getId(), ApiConstants.STORAGE_POLICY, String.valueOf(storagePolicyID), false));\n }\n if (!detailsVO.isEmpty()) {\n diskOfferingDetailsDao.saveDetails(detailsVO);\n }\n CallContext.current().setEventDetails(\"Disk offering id=\" + newDiskOffering.getId());\n CallContext.current().putContextParameter(DiskOffering.class, newDiskOffering.getId());\n return offering;\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private void createOrUpdateSchedule(User user, long projectCode, long workflowCode, String schedule, boolean onlineSchedule, String workerGroup, String warningType, int warningGroupId){\r\n Schedule scheduleObj = scheduleMapper.queryByProcessDefinitionCode(workflowCode);\r\n int scheduleId;\r\n if (scheduleObj == null) {\r\n processDefinitionService.releaseProcessDefinition(user, projectCode, workflowCode, ReleaseState.ONLINE);\r\n Map result = schedulerService.insertSchedule(user, projectCode, workflowCode, schedule, WarningType.valueOf(warningType), warningGroupId, DEFAULT_FAILURE_STRATEGY, DEFAULT_PRIORITY, workerGroup, user.getTenantCode(), DEFAULT_ENVIRONMENT_CODE);\r\n scheduleId = (int) result.get(\"scheduleId\");\r\n } else {\r\n scheduleId = scheduleObj.getId();\r\n processDefinitionService.releaseProcessDefinition(user, projectCode, workflowCode, ReleaseState.OFFLINE);\r\n schedulerService.updateSchedule(user, projectCode, scheduleId, schedule, WarningType.valueOf(warningType), warningGroupId, DEFAULT_FAILURE_STRATEGY, DEFAULT_PRIORITY, workerGroup, user.getTenantCode(), DEFAULT_ENVIRONMENT_CODE);\r\n }\r\n if (onlineSchedule) {\r\n processDefinitionService.releaseProcessDefinition(user, projectCode, workflowCode, ReleaseState.ONLINE);\r\n schedulerService.setScheduleState(user, projectCode, scheduleId, ReleaseState.ONLINE);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ApplicationWithPrograms deployApp(NamespaceId namespaceId, @Nullable String appName, @Nullable String appVersion, @Nullable String configStr, @Nullable ChangeSummary changeSummary, @Nullable SourceControlMeta sourceControlMeta, ProgramTerminator programTerminator, ArtifactDetail artifactDetail, @Nullable KerberosPrincipalId ownerPrincipal, boolean updateSchedules, boolean isPreview, boolean skipMarkingLatest, Map userProps) throws Exception {\n // Now to deploy an app, we need ADMIN privilege on the owner principal if it is present, and also ADMIN on the app\n // But since at this point, app name is unknown to us, so the enforcement on the app is happening in the deploy\n // pipeline - LocalArtifactLoaderStage\n // need to enforce on the principal id if impersonation is involved\n KerberosPrincipalId effectiveOwner = SecurityUtil.getEffectiveOwner(ownerAdmin, namespaceId, ownerPrincipal == null ? null : ownerPrincipal.getPrincipal());\n Principal requestingUser = authenticationContext.getPrincipal();\n // enforce that the current principal, if not the same as the owner principal, has the admin privilege on the\n // impersonated principal\n if (effectiveOwner != null) {\n accessEnforcer.enforce(effectiveOwner, requestingUser, AccessPermission.SET_OWNER);\n }\n ApplicationClass appClass = Iterables.getFirst(artifactDetail.getMeta().getClasses().getApps(), null);\n if (appClass == null) {\n throw new InvalidArtifactException(String.format(\"No application class found in artifact '%s' in namespace '%s'.\", artifactDetail.getDescriptor().getArtifactId(), namespaceId));\n }\n if (!NamespaceId.SYSTEM.equals(namespaceId)) {\n capabilityReader.checkAllEnabled(appClass.getRequirements().getCapabilities());\n }\n // TODO @sansans : Fetch owner info JIRA: CDAP-19491\n ChangeDetail change = new ChangeDetail(changeSummary == null ? null : changeSummary.getDescription(), changeSummary == null ? null : changeSummary.getParentVersion(), requestingUser == null ? null : requestingUser.getName(), System.currentTimeMillis());\n // deploy application with newly added artifact\n AppDeploymentInfo deploymentInfo = AppDeploymentInfo.builder().setArtifactId(Artifacts.toProtoArtifactId(namespaceId, artifactDetail.getDescriptor().getArtifactId())).setArtifactLocation(artifactDetail.getDescriptor().getLocation()).setApplicationClass(appClass).setNamespaceId(namespaceId).setAppName(appName).setAppVersion(appVersion).setConfigString(configStr).setOwnerPrincipal(ownerPrincipal).setUpdateSchedules(updateSchedules).setRuntimeInfo(isPreview ? new AppDeploymentRuntimeInfo(null, userProps, Collections.emptyMap()) : null).setChangeDetail(change).setSourceControlMeta(sourceControlMeta).setSkipMarkingLatest(skipMarkingLatest).build();\n Manager manager = managerFactory.create(programTerminator);\n // TODO: (CDAP-3258) Manager needs MUCH better error handling.\n ApplicationWithPrograms applicationWithPrograms;\n try {\n applicationWithPrograms = manager.deploy(deploymentInfo).get();\n } catch (ExecutionException e) {\n Throwables.propagateIfPossible(e.getCause(), Exception.class);\n throw Throwables.propagate(e.getCause());\n }\n adminEventPublisher.publishAppCreation(applicationWithPrograms.getApplicationId(), applicationWithPrograms.getSpecification());\n return applicationWithPrograms;\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "public static InteropQuoteResponseData build(Long commandId, @NotNull String transactionCode, @NotNull InteropActionState state, LocalDateTime expiration, List extensionList, @NotNull String quoteCode, MoneyData fspFee, MoneyData fspCommission) {\n return new InteropQuoteResponseData(null, null, commandId, null, transactionCode, state, expiration, extensionList, quoteCode, fspFee, fspCommission);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private Map getUnmanagedNicNetworkMap(String instanceName, List nics, final Map callerNicNetworkMap, final Map callerNicIpAddressMap, final DataCenter zone, final String hostName, final Account owner, Hypervisor.HypervisorType hypervisorType) throws ServerApiException {\n Map nicNetworkMap = new HashMap<>();\n String nicAdapter = null;\n for (int i = 0; i < nics.size(); i++) {\n UnmanagedInstanceTO.Nic nic = nics.get(i);\n if (StringUtils.isEmpty(nicAdapter)) {\n nicAdapter = nic.getAdapterType();\n } else {\n if (!nicAdapter.equals(nic.getAdapterType())) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Multiple network adapter of different type (%s, %s) are not supported for import. Please make sure that all network adapters are of the same type\", nicAdapter, nic.getAdapterType()));\n }\n }\n Network network = null;\n Network.IpAddresses ipAddresses = null;\n if (MapUtils.isNotEmpty(callerNicIpAddressMap) && callerNicIpAddressMap.containsKey(nic.getNicId())) {\n ipAddresses = callerNicIpAddressMap.get(nic.getNicId());\n }\n if (!callerNicNetworkMap.containsKey(nic.getNicId())) {\n if (nic.getVlan() != null && nic.getVlan() != 0) {\n // Find a suitable network\n List networks = networkDao.listByZone(zone.getId());\n for (NetworkVO networkVO : networks) {\n if (networkVO.getTrafficType() == Networks.TrafficType.None || Networks.TrafficType.isSystemNetwork(networkVO.getTrafficType())) {\n continue;\n }\n try {\n checkUnmanagedNicAndNetworkForImport(instanceName, nic, networkVO, zone, owner, true, hypervisorType);\n network = networkVO;\n } catch (Exception e) {\n logger.error(String.format(\"Error when checking NIC [%s] of unmanaged instance to import due to [%s].\", nic.getNicId(), e.getMessage()), e);\n }\n if (network != null) {\n checkUnmanagedNicAndNetworkHostnameForImport(instanceName, nic, network, hostName);\n checkUnmanagedNicIpAndNetworkForImport(instanceName, nic, network, ipAddresses);\n break;\n }\n }\n }\n } else {\n network = networkDao.findById(callerNicNetworkMap.get(nic.getNicId()));\n boolean autoImport = false;\n if (hypervisorType == Hypervisor.HypervisorType.KVM) {\n autoImport = ipAddresses != null && ipAddresses.getIp4Address() != null && ipAddresses.getIp4Address().equalsIgnoreCase(\"auto\");\n }\n checkUnmanagedNicAndNetworkForImport(instanceName, nic, network, zone, owner, autoImport, hypervisorType);\n checkUnmanagedNicAndNetworkHostnameForImport(instanceName, nic, network, hostName);\n checkUnmanagedNicIpAndNetworkForImport(instanceName, nic, network, ipAddresses);\n }\n if (network == null) {\n throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format(\"Suitable network for nic(ID: %s) not found during VM import\", nic.getNicId()));\n }\n nicNetworkMap.put(nic.getNicId(), network.getId());\n }\n return nicNetworkMap;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "Pair, Integer> searchForIdsAndCount(Long storagePoolId, String storagePoolName, Long zoneId, String path, Long podId, Long clusterId, String address, ScopeType scopeType, StoragePoolStatus status, String keyword, Filter searchFilter);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private DiskProfile allocateTemplatedVolume(Type type, String name, DiskOffering offering, Long rootDisksize, Long minIops, Long maxIops, VirtualMachineTemplate template, VirtualMachine vm, Account owner, long deviceId, String configurationId) {\n assert (template.getFormat() != ImageFormat.ISO) : \"ISO is not a template.\";\n Long size = _tmpltMgr.getTemplateSize(template.getId(), vm.getDataCenterId());\n if (rootDisksize != null) {\n if (template.isDeployAsIs()) {\n // Volume size specified from template deploy-as-is\n size = rootDisksize;\n } else {\n rootDisksize = rootDisksize * 1024 * 1024 * 1024;\n if (rootDisksize > size) {\n logger.debug(\"Using root disk size of [{}] bytes for the volume [{}].\", toHumanReadableSize(rootDisksize), name);\n size = rootDisksize;\n } else {\n logger.debug(\"The specified root disk size of [{}] bytes is smaller than the template. Using root disk size of [{}] bytes for the volume [{}].\", toHumanReadableSize(rootDisksize), size, name);\n }\n }\n }\n minIops = minIops != null ? minIops : offering.getMinIops();\n maxIops = maxIops != null ? maxIops : offering.getMaxIops();\n VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), offering.getProvisioningType(), size, minIops, maxIops, null);\n vol.setFormat(getSupportedImageFormatForCluster(template.getHypervisorType()));\n if (vm != null) {\n vol.setInstanceId(vm.getId());\n }\n vol.setTemplateId(template.getId());\n vol.setDeviceId(deviceId);\n if (type.equals(Type.ROOT) && !vm.getType().equals(VirtualMachine.Type.User)) {\n vol.setRecreatable(true);\n }\n if (vm.getType() == VirtualMachine.Type.User) {\n UserVmVO userVm = _userVmDao.findById(vm.getId());\n vol.setDisplayVolume(userVm.isDisplayVm());\n }\n vol = _volsDao.persist(vol);\n saveVolumeDetails(offering.getId(), vol.getId());\n if (StringUtils.isNotBlank(configurationId)) {\n VolumeDetailVO deployConfigurationDetail = new VolumeDetailVO(vol.getId(), VmDetailConstants.DEPLOY_AS_IS_CONFIGURATION, configurationId, false);\n _volDetailDao.persist(deployConfigurationDetail);\n }\n // Create event and update resource count for volumes if vm is a user vm\n if (vm.getType() == VirtualMachine.Type.User) {\n Long offeringId = null;\n if (!offering.isComputeOnly()) {\n offeringId = offering.getId();\n }\n UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offeringId, vol.getTemplateId(), size, Volume.class.getName(), vol.getUuid(), vol.isDisplayVolume());\n _resourceLimitMgr.incrementVolumeResourceCount(vm.getAccountId(), vol.isDisplayVolume(), vol.getSize(), offering);\n }\n return toDiskProfile(vol, offering);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public TupleSets evalNode(PathMemory pmem, NetworkNode node, long bit, Memory nodeMem, SegmentMemory[] smems, int smemIndex, ActivationsManager activationsManager, LinkedList stack, boolean processRian, RuleExecutor executor, TupleSets srcTuples, SegmentMemory smem, TupleSets stagedLeftTuples, LeftTupleSinkNode sink){\r\n TupleSets trgTuples = new TupleSetsImpl<>();\r\n if (NodeTypeEnums.isBetaNode(node)) {\r\n boolean exitInnerEval = evalBetaNode(pmem, node, nodeMem, smems, smemIndex, trgTuples, activationsManager, stack, processRian, executor, srcTuples, stagedLeftTuples, sink);\r\n if (exitInnerEval) {\r\n return null;\r\n }\r\n } else {\r\n boolean exitInnerEval = false;\r\n switch(node.getType()) {\r\n case NodeTypeEnums.EvalConditionNode:\r\n {\r\n pEvalNode.doNode((EvalConditionNode) node, (EvalMemory) nodeMem, sink, activationsManager.getReteEvaluator(), srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.FromNode:\r\n {\r\n pFromNode.doNode((FromNode) node, (FromMemory) nodeMem, sink, activationsManager.getReteEvaluator(), srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.ReactiveFromNode:\r\n {\r\n pReactiveFromNode.doNode((ReactiveFromNode) node, (ReactiveFromNode.ReactiveFromMemory) nodeMem, sink, activationsManager.getReteEvaluator(), srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.QueryElementNode:\r\n {\r\n exitInnerEval = evalQueryNode(pmem, node, bit, nodeMem, smems, smemIndex, trgTuples, activationsManager.getReteEvaluator(), stack, srcTuples, sink, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.TimerConditionNode:\r\n {\r\n pTimerNode.doNode((TimerNode) node, (TimerNodeMemory) nodeMem, pmem, smem, sink, activationsManager, srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.ConditionalBranchNode:\r\n {\r\n pBranchNode.doNode((ConditionalBranchNode) node, (ConditionalBranchMemory) nodeMem, sink, activationsManager, srcTuples, trgTuples, stagedLeftTuples, executor);\r\n break;\r\n }\r\n case NodeTypeEnums.AsyncSendNode:\r\n {\r\n pSendNode.doNode((AsyncSendNode) node, (AsyncSendMemory) nodeMem, activationsManager.getReteEvaluator(), srcTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.AsyncReceiveNode:\r\n {\r\n pReceiveNode.doNode((AsyncReceiveNode) node, (AsyncReceiveMemory) nodeMem, sink, activationsManager.getReteEvaluator(), srcTuples, trgTuples);\r\n break;\r\n }\r\n }\r\n if (exitInnerEval && trgTuples.isEmpty()) {\r\n return null;\r\n }\r\n }\r\n return trgTuples;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean applyTungstenPortForwarding(boolean isAdd, String publicNetworkUuid, String floatingIpPoolName, String floatingIpName, String vmiUuid, String protocol, int publicPort, int privatePort) {\n try {\n FloatingIp floatingIp;\n VirtualNetwork virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, publicNetworkUuid);\n VirtualMachineInterface virtualMachineInterface = (VirtualMachineInterface) apiConnector.findById(VirtualMachineInterface.class, vmiUuid);\n FloatingIpPool floatingIpPool = (FloatingIpPool) apiConnector.find(FloatingIpPool.class, virtualNetwork, floatingIpPoolName);\n if (isAdd) {\n floatingIp = addFloatingIp(virtualMachineInterface, floatingIpPool, floatingIpName, protocol, publicPort, privatePort);\n } else {\n floatingIp = removeFloatingIp(virtualMachineInterface, floatingIpPool, floatingIpName, protocol, publicPort, privatePort);\n }\n Status status = apiConnector.update(floatingIp);\n status.ifFailure(errorHandler);\n return status.isSuccess();\n } catch (IOException e) {\n return false;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private boolean drawTour_10_InTile(final GC gcTile, final Map2 map, final Tile tile, final TourData tourData, final int numParts, final Color systemColorBlue, final boolean isGeoCompareRefTour, final int refTourStartIndex, final int refTourEndIndex) {\n final MP mp = map.getMapProvider();\n final int projectionHash = mp.getProjection().getId().hashCode();\n final int mapZoomLevel = map.getZoom();\n if (numParts == 1) {\n // basic drawing method is used -> optimize performance\n if (isInTile_Tour(tourData, mp, mapZoomLevel, tile, projectionHash) == false) {\n return false;\n }\n }\n boolean isTourInTile = false;\n final int tileSize = mp.getTileSize();\n final int devPartOffset = ((numParts - 1) / 2) * tileSize;\n // get viewport for the current tile\n final int tileWorldPixelX = tile.getX() * tileSize;\n final int tileWorldPixelY = tile.getY() * tileSize;\n final int tileWidth = tileSize;\n final int tileHeight = tileSize;\n final double[] latitudeSerie = tourData.latitudeSerie;\n final double[] longitudeSerie = tourData.longitudeSerie;\n final boolean[] visibleDataPointSerie = tourData.visibleDataPointSerie;\n final boolean isMultipleTours = tourData.isMultipleTours();\n final Long[] allMultipleTourIds = tourData.multipleTourIds;\n final int[] allMultipleTour_StartIndex = tourData.multipleTourStartIndex;\n final int numTimeSlices = latitudeSerie.length;\n final int numMultipleTours = isMultipleTours && allMultipleTourIds != null ? allMultipleTourIds.length : 0;\n final int nextTour_StartIndex = isMultipleTours ? numMultipleTours > 1 ? allMultipleTour_StartIndex[1] : numTimeSlices : -1;\n int subTourIndex = 0;\n Long tourId = isMultipleTours ? allMultipleTourIds[0] : tourData.getTourId();\n boolean isVisibleDataPoint_AfterIsWasHidden = false;\n boolean isPreviousVisibleDataPoint = false;\n /*\n * World positions are cached to optimize performance when multiple tours are selected\n */\n Point[] allTour_WorldPixelPos = tourData.getWorldPositionForTour(projectionHash, mapZoomLevel);\n if ((allTour_WorldPixelPos == null)) {\n allTour_WorldPixelPos = setupWorldPixel_Tour(tourData, mp, mapZoomLevel, latitudeSerie, longitudeSerie, projectionHash);\n }\n gcTile.setForeground(systemColorBlue);\n gcTile.setBackground(systemColorBlue);\n int lastInsideIndex = -99;\n boolean isBorder;\n // index == 0: paint border\n // index == 1: paint tour symbol\n for (int lineIndex = 0; lineIndex < 2; lineIndex++) {\n if (lineIndex == 0) {\n if (_prefIsWithBorder == false) {\n // skip border\n continue;\n }\n isBorder = true;\n // draw line border\n _symbolSize = _prefLineWidth + (_prefBorderWidth * 2);\n } else if (lineIndex == 1) {\n isBorder = false;\n // draw within the border\n _symbolSize = _prefLineWidth;\n } else {\n break;\n }\n if (isGeoCompareRefTour) {\n // draw it more visible\n _symbolSize = _prefGeoCompare_LineWidth;\n }\n _symbolSize2 = _symbolSize / 2;\n // ensure that the margin in not larger than a max size\n _symbolHoveredMargin = Map2.EXPANDED_HOVER_SIZE - _symbolSize > 0 ? Map2.EXPANDED_HOVER_SIZE - _symbolSize : 0;\n _symbolHoveredMargin2 = _symbolHoveredMargin / 2;\n gcTile.setLineWidth(_symbolSize);\n int devFrom_WithOffsetX = 0;\n int devFrom_WithOffsetY = 0;\n Color lastVisibleColor = null;\n for (int serieIndex = 0; serieIndex < longitudeSerie.length; serieIndex++) {\n if (_isFastPainting) {\n serieIndex += _fastPainting_SkippedValues;\n if (serieIndex >= longitudeSerie.length) {\n serieIndex = longitudeSerie.length - 1;\n }\n }\n final Point tourWorldPixel = allTour_WorldPixelPos[serieIndex];\n final int tourWorldPixelX = tourWorldPixel.x;\n final int tourWorldPixelY = tourWorldPixel.y;\n int devX = tourWorldPixelX - tileWorldPixelX;\n int devY = tourWorldPixelY - tileWorldPixelY;\n boolean isInRefTourPart = false;\n if (isGeoCompareRefTour) {\n // paint ref tour part with a different color\n isInRefTourPart = serieIndex >= refTourStartIndex && serieIndex <= refTourEndIndex;\n }\n if (_prefIsDrawLine && _isFastPainting == false) {\n // draw as a line\n // get positions with the part offset\n final int devTo_WithOffsetX = devX + devPartOffset;\n final int devTo_WithOffsetY = devY + devPartOffset;\n if (serieIndex == 0) {\n // keep position\n devFrom_WithOffsetX = devTo_WithOffsetX;\n devFrom_WithOffsetY = devTo_WithOffsetY;\n continue;\n }\n /*\n * Check visible points\n */\n boolean isVisibleDataPoint = true;\n if (visibleDataPointSerie != null) {\n // visible data points are available -> use it\n isVisibleDataPoint = visibleDataPointSerie[serieIndex];\n if (isPreviousVisibleDataPoint == false && isVisibleDataPoint) {\n isVisibleDataPoint_AfterIsWasHidden = true;\n }\n }\n /*\n * Get sub tour id\n */\n if (isMultipleTours) {\n if (serieIndex >= nextTour_StartIndex) {\n // advance to the next sub tour\n for (; subTourIndex < numMultipleTours; subTourIndex++) {\n final int nextSubTour_StartIndex = allMultipleTour_StartIndex[subTourIndex];\n if (serieIndex < nextSubTour_StartIndex) {\n break;\n }\n }\n tourId = subTourIndex >= numMultipleTours ? allMultipleTourIds[numMultipleTours - 1] : allMultipleTourIds[subTourIndex];\n }\n }\n // if (serieIndex == 1146) {\n // int a = 0;\n // a++;\n // }\n Color color = null;\n /*\n * Check if position is in the viewport, this condition is an inline for:\n * -\n * tileViewport.contains(tileWorldPos.x, tileWorldPos.y)\n */\n if ((tourWorldPixelX >= tileWorldPixelX) && (tourWorldPixelY >= tileWorldPixelY) && tourWorldPixelX < (tileWorldPixelX + tileWidth) && tourWorldPixelY < (tileWorldPixelY + tileHeight)) {\n // current position is inside the tile\n // check if position has changed\n if (devTo_WithOffsetX != devFrom_WithOffsetX || devTo_WithOffsetY != devFrom_WithOffsetY) {\n isTourInTile = true;\n if (isVisibleDataPoint) {\n color = getTourColor(tourData, serieIndex, isBorder, true, isGeoCompareRefTour, isInRefTourPart);\n lastVisibleColor = color;\n if (isVisibleDataPoint_AfterIsWasHidden) {\n // draw starting point after a pause/break\n drawTour_40_Dot(gcTile, devFrom_WithOffsetX, devFrom_WithOffsetY, color, tile, tourId, // adjust to the previous index otherwise the index is wrong\n serieIndex - 1);\n }\n drawTour_20_Line(gcTile, devFrom_WithOffsetX, devFrom_WithOffsetY, devTo_WithOffsetX, devTo_WithOffsetY, color, tile, tourId, serieIndex);\n }\n }\n lastInsideIndex = serieIndex;\n }\n // check first outside point\n if (isVisibleDataPoint && serieIndex == lastInsideIndex + 1) {\n /*\n * This position is the first which is outside of the tile, draw a line from\n * the last inside to the first outside position\n */\n if (isVisibleDataPoint_AfterIsWasHidden) {\n if (lastVisibleColor == null) {\n lastVisibleColor = getTourColor(tourData, serieIndex, isBorder, true, isGeoCompareRefTour, isInRefTourPart);\n }\n drawTour_40_Dot(gcTile, devFrom_WithOffsetX, devFrom_WithOffsetY, lastVisibleColor, tile, tourId, // adjust to the previous index otherwise the index is wrong\n serieIndex - 1);\n }\n drawTour_20_Line(gcTile, devFrom_WithOffsetX, devFrom_WithOffsetY, devTo_WithOffsetX, devTo_WithOffsetY, lastVisibleColor, tile, tourId, serieIndex);\n }\n // keep positions\n devFrom_WithOffsetX = devTo_WithOffsetX;\n devFrom_WithOffsetY = devTo_WithOffsetY;\n isPreviousVisibleDataPoint = isVisibleDataPoint;\n } else {\n // draw tour with dots/squares\n // this is an inline for: tileViewport.contains(tileWorldPos.x, tileWorldPos.y)\n // check if position is in the viewport\n if ((tourWorldPixelX >= tileWorldPixelX) && (tourWorldPixelY >= tileWorldPixelY) && tourWorldPixelX < (tileWorldPixelX + tileWidth) && tourWorldPixelY < (tileWorldPixelY + tileHeight)) {\n // current position is inside the tile\n // optimize drawing: check if position has changed\n if (!(devX == devFrom_WithOffsetX && devY == devFrom_WithOffsetY)) {\n /*\n * Check visible points\n */\n boolean isVisibleDataPoint = true;\n if (visibleDataPointSerie != null) {\n isVisibleDataPoint = visibleDataPointSerie[serieIndex];\n }\n if (isVisibleDataPoint) {\n isTourInTile = true;\n /*\n * Get sub tour\n */\n if (isMultipleTours) {\n if (serieIndex >= nextTour_StartIndex) {\n // advance to the next sub tour\n for (; subTourIndex < numMultipleTours; subTourIndex++) {\n final int nextSubTour_StartIndex = allMultipleTour_StartIndex[subTourIndex];\n if (serieIndex < nextSubTour_StartIndex) {\n break;\n }\n }\n tourId = subTourIndex >= numMultipleTours ? allMultipleTourIds[numMultipleTours - 1] : allMultipleTourIds[subTourIndex];\n }\n }\n // adjust positions with the part offset\n devX += devPartOffset;\n devY += devPartOffset;\n final Color color = getTourColor(tourData, serieIndex, isBorder, false, isGeoCompareRefTour, isInRefTourPart);\n if (_prefIsDrawSquare == false || _isFastPainting) {\n drawTour_40_Dot(gcTile, devX, devY, color, tile, tourId, serieIndex);\n } else {\n drawTour_30_Square(gcTile, devX, devY, color, tile, tourId, serieIndex);\n }\n // set previous pixel\n devFrom_WithOffsetX = devX;\n devFrom_WithOffsetY = devY;\n }\n } else {\n // System.out.println((UI.timeStampNano() + \" [\" + getClass().getSimpleName() + \"] ()\")\n // + (\"\\tskipped: \" + devX + \" \" + devY)\n //// + (\"\\t: \" + )\n // );\n }\n }\n }\n }\n }\n return isTourInTile;\n}", "smellKey": "S107", "smellId": null, "repo": "wolfgang-ch_mytourbook", "language": "java"} {"function": "/**\n * @param index\n * @param type\n * @param mustFilter\n * @param mustNotFilter\n * @param shouldFilter\n * @param aggsFilter\n * @return\n */\npublic Map getTotalDistributionForIndexAndTypeBySize(String index, String type, Map mustFilter, Map mustNotFilter, HashMultimap shouldFilter, String aggsFilter, int size, int from, String searchText) throws Exception {\n StringBuilder urlToQueryBuffer = new StringBuilder(esUrl).append(FORWARD_SLASH).append(index);\n if (!Strings.isNullOrEmpty(type)) {\n urlToQueryBuffer.append(FORWARD_SLASH).append(type);\n }\n urlToQueryBuffer.append(FORWARD_SLASH).append(_SEARCH);\n if (size > 0 && from >= 0) {\n urlToQueryBuffer.append(\"?\").append(\"size=\").append(size).append(\"&\").append(\"from=\").append(from);\n }\n String urlToQuery = urlToQueryBuffer.toString();\n Map requestBody = new HashMap();\n Map matchFilters = Maps.newHashMap();\n Map distribution = new HashMap();\n if (mustFilter == null) {\n matchFilters.put(MATCH_ALL, new HashMap());\n } else {\n matchFilters.putAll(mustFilter);\n }\n if (null != mustFilter) {\n requestBody.put(QUERY, buildQuery(matchFilters, mustNotFilter, shouldFilter, searchText, null, null));\n requestBody.put(AGGS, buildAggs(aggsFilter, size));\n } else {\n requestBody.put(QUERY, matchFilters);\n }\n String responseDetails = null;\n Gson gson = new GsonBuilder().create();\n try {\n String requestJson = gson.toJson(requestBody, Object.class);\n responseDetails = PacHttpUtils.doHttpPost(urlToQuery, requestJson);\n Map response = (Map) gson.fromJson(responseDetails, Map.class);\n Map aggregations = (Map) response.get(AGGREGATIONS);\n Map name = (Map) aggregations.get(NAME);\n List> buckets = (List>) name.get(BUCKETS);\n for (int i = 0; i < buckets.size(); i++) {\n Map bucket = buckets.get(i);\n distribution.put(bucket.get(\"key\").toString(), ((Double) bucket.get(\"doc_count\")).longValue());\n }\n } catch (Exception e) {\n LOGGER.error(ERROR_RETRIEVING_INVENTORY_FROM_ES, e);\n throw e;\n }\n return distribution;\n}", "smellKey": "S107", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "/**\n * Send ediMessage to trading partner.\n *\n * @param ediMessage - EDI message to transport\n * @param requestUri - resource location to deliver message\n * @param subject - message subject\n * @param from - RFC2822 address of sender\n * @param as2From - AS2 name of sender\n * @param as2To - AS2 name of recipient\n * @param as2MessageStructure - the structure of AS2 to send; see {@link AS2MessageStructure}\n * @param ediMessageContentType - the content type of EDI message\n * @param ediMessageTransferEncoding - the transfer encoding used to transport EDI message\n * @param signingAlgorithm - the algorithm used to sign the message or null if sending EDI\n * message unsigned\n * @param signingCertificateChain - the chain of certificates used to sign the message or null if\n * sending EDI message unsigned\n * @param signingPrivateKey - the private key used to sign EDI message\n * @param compressionAlgorithm - the algorithm used to compress the message or null if sending\n * EDI message uncompressed\n * @param dispositionNotificationTo - an RFC2822 address to request a receipt or null if no receipt\n * requested\n * @param signedReceiptMicAlgorithms - the senders list of signing algorithms for signing receipt, in preferred\n * order, or null if requesting an unsigned receipt.\n * @param encryptingAlgorithm - the algorithm used to encrypt the message or null if sending\n * EDI message unencrypted\n * @param encryptingCertificateChain - the chain of certificates used to encrypt the message or null\n * if sending EDI message unencrypted\n * @param attachedFileName - the name of the attached file or null if user doesn't want to\n * specify it\n * @return {@link HttpCoreContext} containing request and response used to send EDI\n * message\n * @throws HttpException when things go wrong.\n */\npublic HttpCoreContext send(String ediMessage, String requestUri, String subject, String from, String as2From, String as2To, AS2MessageStructure as2MessageStructure, ContentType ediMessageContentType, String ediMessageTransferEncoding, AS2SignatureAlgorithm signingAlgorithm, Certificate[] signingCertificateChain, PrivateKey signingPrivateKey, AS2CompressionAlgorithm compressionAlgorithm, String dispositionNotificationTo, String[] signedReceiptMicAlgorithms, AS2EncryptionAlgorithm encryptingAlgorithm, Certificate[] encryptingCertificateChain, String attachedFileName, String receiptDeliveryOption) throws HttpException {\n ObjectHelper.notNull(ediMessage, \"EDI Message\");\n ObjectHelper.notNull(requestUri, \"Request URI\");\n ObjectHelper.notNull(subject, \"Subject\");\n ObjectHelper.notNull(from, \"From\");\n ObjectHelper.notNull(as2From, \"AS2From\");\n ObjectHelper.notNull(as2To, \"AS2To\");\n ObjectHelper.notNull(as2MessageStructure, \"AS2 Message Structure\");\n ObjectHelper.notNull(ediMessageContentType, \"EDI Message Content Type\");\n // Add Context attributes\n HttpCoreContext httpContext = HttpCoreContext.create();\n httpContext.setAttribute(AS2ClientManager.REQUEST_URI, requestUri);\n httpContext.setAttribute(AS2ClientManager.SUBJECT, subject);\n httpContext.setAttribute(AS2ClientManager.FROM, from);\n httpContext.setAttribute(AS2ClientManager.AS2_FROM, as2From);\n httpContext.setAttribute(AS2ClientManager.AS2_TO, as2To);\n httpContext.setAttribute(AS2ClientManager.AS2_MESSAGE_STRUCTURE, as2MessageStructure);\n httpContext.setAttribute(AS2ClientManager.EDI_MESSAGE_CONTENT_TYPE, ediMessageContentType);\n httpContext.setAttribute(AS2ClientManager.EDI_MESSAGE_TRANSFER_ENCODING, ediMessageTransferEncoding);\n httpContext.setAttribute(AS2ClientManager.SIGNING_ALGORITHM, signingAlgorithm);\n httpContext.setAttribute(AS2ClientManager.SIGNING_CERTIFICATE_CHAIN, signingCertificateChain);\n httpContext.setAttribute(AS2ClientManager.SIGNING_PRIVATE_KEY, signingPrivateKey);\n httpContext.setAttribute(AS2ClientManager.COMPRESSION_ALGORITHM, compressionAlgorithm);\n httpContext.setAttribute(AS2ClientManager.DISPOSITION_NOTIFICATION_TO, dispositionNotificationTo);\n httpContext.setAttribute(AS2ClientManager.SIGNED_RECEIPT_MIC_ALGORITHMS, signedReceiptMicAlgorithms);\n httpContext.setAttribute(AS2ClientManager.ENCRYPTING_ALGORITHM, encryptingAlgorithm);\n httpContext.setAttribute(AS2ClientManager.ENCRYPTING_CERTIFICATE_CHAIN, encryptingCertificateChain);\n httpContext.setAttribute(AS2ClientManager.RECEIPT_DELIVERY_OPTION, receiptDeliveryOption);\n BasicClassicHttpRequest request = new BasicClassicHttpRequest(\"POST\", requestUri);\n request.setVersion(new ProtocolVersion(\"HTTP\", 1, 1));\n httpContext.setAttribute(HTTP_REQUEST, request);\n // Create Message Body\n ApplicationEntity applicationEntity;\n try {\n applicationEntity = EntityUtils.createEDIEntity(ediMessage, ediMessageContentType, ediMessageTransferEncoding, false, attachedFileName);\n } catch (Exception e) {\n throw new HttpException(\"Failed to create EDI message entity\", e);\n }\n switch(as2MessageStructure) {\n case PLAIN:\n {\n plain(applicationEntity, request);\n break;\n }\n case SIGNED:\n {\n signed(httpContext, applicationEntity, request);\n break;\n }\n case ENCRYPTED:\n {\n encrypted(httpContext, applicationEntity, request);\n break;\n }\n case SIGNED_ENCRYPTED:\n {\n signedEncrypted(httpContext, applicationEntity, request);\n break;\n }\n case PLAIN_COMPRESSED:\n {\n plainCompressed(httpContext, applicationEntity, request);\n break;\n }\n case SIGNED_COMPRESSED:\n {\n signedCompressed(httpContext, applicationEntity, request);\n break;\n }\n case COMPRESSED_SIGNED:\n {\n compressedSigned(httpContext, applicationEntity, request);\n break;\n }\n case ENCRYPTED_COMPRESSED:\n {\n encryptedCompressed(httpContext, applicationEntity, request);\n break;\n }\n case ENCRYPTED_COMPRESSED_SIGNED:\n {\n encryptedCompressedSigned(httpContext, applicationEntity, request);\n break;\n }\n case ENCRYPTED_SIGNED_COMPRESSED:\n {\n encryptedSignedCompressed(httpContext, applicationEntity, request);\n break;\n }\n default:\n throw new HttpException(\"Unknown AS2 Message Structure\");\n }\n final HttpResponse response = sendRequest(httpContext, request);\n httpContext.setAttribute(HTTP_RESPONSE, response);\n return httpContext;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public static ICreateTimeSeriesPlan getCreateTimeSeriesPlan(PartialPath path, TSDataType dataType, TSEncoding encoding, CompressionType compressor, Map props, Map tags, Map attributes, String alias){\r\n return new CreateTimeSeriesPlanImpl(path, dataType, encoding, compressor, props, tags, attributes, alias);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Produces auto-generated output of string presentation for given object and its declaration class.\n *\n * @param Type of the object.\n * @param cls Declaration class of the object. Note that this should not be a runtime class.\n * @param obj Object to get a string presentation for.\n * @param name0 Additional parameter name.\n * @param val0 Additional parameter value.\n * @param name1 Additional parameter name.\n * @param val1 Additional parameter value.\n * @param name2 Additional parameter name.\n * @param val2 Additional parameter value.\n * @param name3 Additional parameter name.\n * @param val3 Additional parameter value.\n * @param name4 Additional parameter name.\n * @param val4 Additional parameter value.\n * @param name5 Additional parameter name.\n * @param val5 Additional parameter value.\n * @param name6 Additional parameter name.\n * @param val6 Additional parameter value.\n * @return String presentation of the given object.\n */\npublic static String toString(Class cls, T obj, String name0, Object val0, String name1, Object val1, String name2, Object val2, String name3, Object val3, String name4, Object val4, String name5, Object val5, String name6, Object val6) {\n return toString(cls, obj, name0, val0, false, name1, val1, false, name2, val2, false, name3, val3, false, name4, val4, false, name5, val5, false, name6, val6, false);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, String volumePath, String snapshotUuid, String secStorageUrl, String prevSnapshotUuid, String prevBackupUuid, String workerVmName, String nfsVersion) throws Exception {\n String backupUuid = UUID.randomUUID().toString();\n exportVolumeToSecondaryStorage(vmMo, volumePath, secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName, nfsVersion, true);\n return backupUuid + \"/\" + backupUuid;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private CnmTAllegato salvaAllegatoPiano(CnmTPianoRate cnmTPianoRate, byte[] file, CnmTUser cnmTUser, String nomeFile, TipoAllegato tipoAllegato, boolean protocolla, boolean isProtocollazioneInUscita, boolean isMaster){\r\n if (cnmTPianoRate == null)\r\n throw new IllegalArgumentException(\"id ==null\");\r\n if (nomeFile == null)\r\n throw new IllegalArgumentException(\"nomeFile ==null\");\r\n if (cnmTUser == null)\r\n throw new IllegalArgumentException(\"cnmTUser ==null\");\r\n if (tipoAllegato == null)\r\n throw new IllegalArgumentException(\"tipoAllegato ==null\");\r\n String tipoActa = null;\r\n if (tipoAllegato.getId() == TipoAllegato.LETTERA_RATEIZZAZIONE.getId()) {\r\n tipoActa = StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_USCITA_SENZA_ALLEGATI_GENERERATI;\r\n }\r\n String folder = null;\r\n String idEntitaFruitore = null;\r\n TipoProtocolloAllegato tipoProtocolloAllegato = TipoProtocolloAllegato.NON_PROTOCOLLARE;\r\n String soggettoActa = null;\r\n String rootActa = null;\r\n List cnmTSoggettoList = null;\r\n if (protocolla) {\r\n folder = utilsDoqui.createOrGetfolder(cnmTPianoRate);\r\n idEntitaFruitore = utilsDoqui.createIdEntitaFruitore(cnmTPianoRate, cnmDTipoAllegatoRepository.findOne(tipoAllegato.getId()));\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.PROTOCOLLARE;\r\n soggettoActa = utilsDoqui.getSoggettoActa(cnmTPianoRate);\r\n rootActa = utilsDoqui.getRootActa(cnmTPianoRate);\r\n List cnmTRataList = cnmTRataRepository.findByCnmTPianoRateOrderByNumeroRataAsc(cnmTPianoRate);\r\n List cnmROrdinanzaVerbSogList = cnmRSoggRataRepository.findDistinctCnmROrdinanzaVerbSogByCnmTRataIn(cnmTRataList);\r\n List cnmRVerbaleSoggettoList = cnmRVerbaleSoggettoRepository.findByCnmROrdinanzaVerbSogsIn(cnmROrdinanzaVerbSogList);\r\n cnmTSoggettoList = cnmTSoggettoRepository.findByCnmRVerbaleSoggettosIn(cnmRVerbaleSoggettoList);\r\n }\r\n CnmTAllegato cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), null, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, tipoActa, cnmTSoggettoList);\r\n CnmRAllegatoPianoRatePK cnmRAllegatoPianoRatePK = new CnmRAllegatoPianoRatePK();\r\n cnmRAllegatoPianoRatePK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoPianoRatePK.setIdPianoRate(cnmTPianoRate.getIdPianoRate());\r\n CnmRAllegatoPianoRate cnmRAllegatoPianoRate = new CnmRAllegatoPianoRate();\r\n cnmRAllegatoPianoRate.setId(cnmRAllegatoPianoRatePK);\r\n cnmRAllegatoPianoRate.setCnmTAllegato(cnmTAllegato);\r\n cnmRAllegatoPianoRate.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoPianoRate.setCnmTUser(cnmTUser);\r\n cnmRAllegatoPianoRateRepository.save(cnmRAllegatoPianoRate);\r\n return cnmTAllegato;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ScanApplicationsRequest getScanRequest(String namespaceId, String artifactVersion, String pageToken, Integer pageSize, SortOrder orderBy, String nameFilter, Set names, NameFilterType nameFilterType, Boolean latestOnly, Boolean sortCreationTime) {\n ScanApplicationsRequest.Builder builder = ScanApplicationsRequest.builder();\n builder.setNamespaceId(new NamespaceId(namespaceId));\n if (pageSize != null) {\n builder.setLimit(pageSize);\n }\n if (nameFilter != null && !nameFilter.isEmpty()) {\n if (nameFilterType != null) {\n switch(nameFilterType) {\n case EQUALS:\n builder.setApplicationReference(new ApplicationReference(namespaceId, nameFilter));\n break;\n case CONTAINS:\n builder.addFilter(new ApplicationFilter.ApplicationIdContainsFilter(nameFilter));\n break;\n case EQUALS_IGNORE_CASE:\n builder.addFilter(new ApplicationFilter.ApplicationIdEqualsFilter(nameFilter));\n }\n } else {\n // if null, default to use contains\n builder.addFilter(new ApplicationFilter.ApplicationIdContainsFilter(nameFilter));\n }\n }\n builder.addFilters(applicationLifecycleService.getAppFilters(names, artifactVersion));\n if (orderBy != null) {\n builder.setSortOrder(orderBy);\n }\n if (latestOnly != null) {\n builder.setLatestOnly(latestOnly);\n }\n if (sortCreationTime != null) {\n builder.setSortCreationTime(sortCreationTime);\n }\n if (pageToken != null && !pageToken.isEmpty()) {\n builder.setScanFrom(ApplicationId.fromIdParts(Iterables.concat(Collections.singleton(namespaceId), Arrays.asList(EntityId.IDSTRING_PART_SEPARATOR_PATTERN.split(pageToken)))));\n }\n return builder.build();\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "// getFavouriteTreeNodeFromMenuID\n/**\n * Create and save tree favorite node\n *\n * @param AD_Client_ID\n * @param AD_Org_ID\n * @param AD_Tree_Favorite_ID\n * @param AD_Menu_ID\n * @param Parent_ID\n * @param SeqNo\n * @param folderName\n * @param isSummary\n * @param isCollapsible\n * @param isFavourite\n * @return new {@link MTreeFavoriteNode} instance\n */\npublic static MTreeFavoriteNode create(int AD_Client_ID, int AD_Org_ID, int AD_Tree_Favorite_ID, int AD_Menu_ID, int Parent_ID, int SeqNo, String folderName, boolean isSummary, boolean isCollapsible, boolean isFavourite) {\n MTreeFavoriteNode favNode = (MTreeFavoriteNode) MTable.get(Env.getCtx(), MTreeFavoriteNode.Table_ID).getPO(0, null);\n favNode.set_ValueOfColumn(I_AD_Tree_Favorite_Node.COLUMNNAME_AD_Client_ID, AD_Client_ID);\n favNode.setAD_Org_ID(AD_Org_ID);\n favNode.setAD_Tree_Favorite_ID(AD_Tree_Favorite_ID);\n favNode.setAD_Menu_ID(AD_Menu_ID);\n favNode.setParent_ID(Parent_ID);\n favNode.setSeqNo(SeqNo);\n if (isSummary)\n favNode.setName(folderName);\n favNode.setIsSummary(isSummary);\n favNode.setIsCollapsible(isCollapsible);\n favNode.setIsFavourite(isFavourite);\n if (!favNode.save()) {\n throw new AdempiereException(Msg.getMsg(Env.getCtx(), \"NodeNotCreate\"));\n }\n return favNode;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "/**\n * @param failOnParseError if set to true, parsing failure on any line will cause parsing to be\n * terminated; when set to false, parsing failure on a given line will not prevent remaining\n * lines from being parsed - this allows us to analyze fields, even if some field is\n * mis-configured and causes a parsing error for the values of that field.\n */\npublic static final Object[] convertLineToRow(ILogChannel log, TextFileLine textFileLine, TextFileInputMeta info, Object[] passThruFields, int nrPassThruFields, IRowMeta outputRowMeta, IRowMeta convertRowMeta, String fname, long rowNr, String delimiter, String enclosure, String escapeCharacter, IFileErrorHandler errorHandler, BaseFileInputAdditionalField additionalOutputFields, String shortFilename, String path, boolean hidden, Date modificationDateTime, String uri, String rooturi, String extension, Long size, final boolean failOnParseError) throws HopException {\n if (textFileLine == null || textFileLine.line == null) {\n return null;\n }\n Object[] r = RowDataUtil.allocateRowData(// over-allocate a bit in the row producing\n outputRowMeta.size());\n // transforms...\n int nrFields = info.inputFields.length;\n int fieldnr;\n Long errorCount = null;\n if (info.errorHandling.errorIgnored && info.getErrorCountField() != null && info.getErrorCountField().length() > 0) {\n errorCount = Long.valueOf(0L);\n }\n String errorFields = null;\n if (info.errorHandling.errorIgnored && info.getErrorFieldsField() != null && info.getErrorFieldsField().length() > 0) {\n errorFields = \"\";\n }\n String errorText = null;\n if (info.errorHandling.errorIgnored && info.getErrorTextField() != null && info.getErrorTextField().length() > 0) {\n errorText = \"\";\n }\n try {\n String[] strings = convertLineToStrings(log, textFileLine.line, info, delimiter, enclosure, escapeCharacter);\n int shiftFields = (passThruFields == null ? 0 : nrPassThruFields);\n for (fieldnr = 0; fieldnr < nrFields; fieldnr++) {\n BaseFileField f = info.inputFields[fieldnr];\n int valuenr = shiftFields + fieldnr;\n IValueMeta valueMeta = outputRowMeta.getValueMeta(valuenr);\n IValueMeta convertMeta = convertRowMeta.getValueMeta(valuenr);\n Object value;\n String nullif = fieldnr < nrFields ? f.getNullString() : \"\";\n String ifnull = fieldnr < nrFields ? f.getIfNullValue() : \"\";\n int trimType = fieldnr < nrFields ? f.getTrimType() : IValueMeta.TRIM_TYPE_NONE;\n if (fieldnr < strings.length) {\n String pol = strings[fieldnr];\n try {\n if (valueMeta.isNull(pol) || !Utils.isEmpty(nullif) && nullif.equals(pol)) {\n pol = null;\n }\n value = valueMeta.convertDataFromString(pol, convertMeta, nullif, ifnull, trimType);\n } catch (Exception e) {\n // OK, give some feedback!\n // when getting fields, failOnParseError will be set to false, as we do not want one\n // mis-configured field\n // to prevent us from analyzing other fields, we simply leave the string value as is\n if (failOnParseError) {\n String message = BaseMessages.getString(PKG, \"TextFileInput.Log.CoundNotParseField\", valueMeta.toStringMeta(), \"\" + pol, valueMeta.getConversionMask(), \"\" + rowNr);\n if (info.errorHandling.errorIgnored) {\n log.logDetailed(fname, BaseMessages.getString(PKG, \"TextFileInput.Log.Warning\") + \": \" + message + \" : \" + e.getMessage());\n value = null;\n if (errorCount != null) {\n errorCount = Long.valueOf(errorCount.longValue() + 1L);\n }\n if (errorFields != null) {\n StringBuilder sb = new StringBuilder(errorFields);\n if (sb.length() > 0) {\n // TODO document this change\n sb.append(\"\\t\");\n }\n sb.append(valueMeta.getName());\n errorFields = sb.toString();\n }\n if (errorText != null) {\n StringBuilder sb = new StringBuilder(errorText);\n if (sb.length() > 0) {\n sb.append(Const.CR);\n }\n sb.append(message);\n errorText = sb.toString();\n }\n if (errorHandler != null) {\n errorHandler.handleLineError(textFileLine.lineNumber, AbstractFileErrorHandler.NO_PARTS);\n }\n if (info.isErrorLineSkipped()) {\n // compensates for stmt: r.setIgnore()\n r = null;\n }\n } else {\n throw new HopException(message, e);\n }\n } else {\n value = pol;\n }\n }\n } else {\n // No data found: TRAILING NULLCOLS: add null value...\n value = null;\n }\n // Now add value to the row (if we're not skipping the row)\n if (r != null) {\n r[valuenr] = value;\n }\n }\n // none of this applies if we're skipping the row\n if (r != null) {\n // Support for trailing nullcols!\n // Should be OK at allocation time, but it doesn't hurt :-)\n if (fieldnr < nrFields) {\n for (int i = fieldnr; i < info.inputFields.length; i++) {\n r[shiftFields + i] = null;\n }\n }\n // Add the error handling fields...\n int index = shiftFields + nrFields;\n if (errorCount != null) {\n r[index] = errorCount;\n index++;\n }\n if (errorFields != null) {\n r[index] = errorFields;\n index++;\n }\n if (errorText != null) {\n r[index] = errorText;\n index++;\n }\n // Possibly add a filename...\n if (info.content.includeFilename) {\n r[index] = fname;\n index++;\n }\n // Possibly add a row number...\n if (info.content.includeRowNumber) {\n r[index] = rowNr;\n index++;\n }\n // Possibly add short filename...\n if (additionalOutputFields.shortFilenameField != null) {\n r[index] = shortFilename;\n index++;\n }\n // Add Extension\n if (additionalOutputFields.extensionField != null) {\n r[index] = extension;\n index++;\n }\n // add path\n if (additionalOutputFields.pathField != null) {\n r[index] = path;\n index++;\n }\n // Add Size\n if (additionalOutputFields.sizeField != null) {\n r[index] = size;\n index++;\n }\n // add Hidden\n if (additionalOutputFields.hiddenField != null) {\n r[index] = hidden;\n index++;\n }\n // Add modification date\n if (additionalOutputFields.lastModificationField != null) {\n r[index] = modificationDateTime;\n index++;\n }\n // Add Uri\n if (additionalOutputFields.uriField != null) {\n r[index] = uri;\n index++;\n }\n // Add RootUri\n if (additionalOutputFields.rootUriField != null) {\n r[index] = rooturi;\n index++;\n }\n }\n // End if r != null\n } catch (Exception e) {\n throw new HopException(BaseMessages.getString(PKG, \"TextFileInput.Log.Error.ErrorConvertingLineText\"), e);\n }\n if (r != null && passThruFields != null) {\n // Simply add all fields from source files transform\n for (int i = 0; i < nrPassThruFields; i++) {\n r[i] = passThruFields[i];\n }\n }\n return r;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Get partition fields for the query using direct SQL queries, to avoid bazillion\n * queries created by DN retrieving stuff for each object individually.\n * @param catName MetaStore catalog name\n * @param dbName MetaStore db name\n * @param tblName MetaStore table name\n * @param partColumns part fields want to get\n * @param sqlFilter SQL filter to use. Better be SQL92-compliant.\n * @param paramsForFilter params for ?-s in SQL filter text. Params must be in order.\n * @param joinsForFilter if the filter needs additional join statement, they must be in\n * this list. Better be SQL92-compliant.\n * @param max The maximum number of partitions to return.\n * @return List of partition objects.\n */\npublic List getPartitionFieldsViaSqlFilter(String catName, String dbName, String tblName, List partColumns, String sqlFilter, List paramsForFilter, List joinsForFilter, Integer max) throws MetaException {\n boolean doTrace = LOG.isDebugEnabled();\n final String dbNameLcase = dbName.toLowerCase();\n final String tblNameLcase = tblName.toLowerCase();\n final String catNameLcase = normalizeSpace(catName).toLowerCase();\n // We have to be mindful of order during filtering if we are not returning all partitions.\n String orderForFilter = (max != null) ? \" order by \" + MetastoreConf.getVar(conf, ConfVars.PARTITION_ORDER_EXPR) : \"\";\n String columns = partColumns.stream().map(col -> PARTITIONS + \".\" + col).collect(Collectors.joining(\",\"));\n String queryText = \"select \" + columns + \" from \" + PARTITIONS + \"\" + \" inner join \" + TBLS + \" on \" + PARTITIONS + \".\\\"TBL_ID\\\" = \" + TBLS + \".\\\"TBL_ID\\\" \" + \" and \" + TBLS + \".\\\"TBL_NAME\\\" = ? \" + \" inner join \" + DBS + \" on \" + TBLS + \".\\\"DB_ID\\\" = \" + DBS + \".\\\"DB_ID\\\" \" + \" and \" + DBS + \".\\\"NAME\\\" = ? \" + join(joinsForFilter, ' ') + \" where \" + DBS + \".\\\"CTLG_NAME\\\" = ? \" + (StringUtils.isBlank(sqlFilter) ? \"\" : (\" and \" + sqlFilter)) + orderForFilter;\n Object[] params = new Object[paramsForFilter.size() + 3];\n params[0] = tblNameLcase;\n params[1] = dbNameLcase;\n params[2] = catNameLcase;\n for (int i = 0; i < paramsForFilter.size(); ++i) {\n params[i + 3] = paramsForFilter.get(i);\n }\n long start = doTrace ? System.nanoTime() : 0;\n try (QueryWrapper query = new QueryWrapper(pm.newQuery(\"javax.jdo.query.SQL\", queryText))) {\n List sqlResult = executeWithArray(query.getInnerQuery(), params, queryText, ((max == null) ? -1 : max.intValue()));\n long queryTime = doTrace ? System.nanoTime() : 0;\n MetastoreDirectSqlUtils.timingTrace(doTrace, queryText, start, queryTime);\n List result = new ArrayList<>(sqlResult);\n return result;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void createJournalEntriesForPurchase(final Long shareAccountId, final Long shareProductId, final String currencyCode, SharesTransactionDTO transactionDTO, final LocalDate transactionDate, final String transactionId, final Office office, final Long paymentTypeId, final BigDecimal amount, final BigDecimal chargeAmount, final List feePayments) {\n if (transactionDTO.getTransactionStatus().isApplied()) {\n if (chargeAmount == null || chargeAmount.compareTo(BigDecimal.ZERO) <= 0) {\n this.helper.createJournalEntriesForShares(office, currencyCode, CashAccountsForShares.SHARES_REFERENCE.getValue(), CashAccountsForShares.SHARES_SUSPENSE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount);\n } else {\n this.helper.createDebitJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount);\n this.helper.createCreditJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount.subtract(chargeAmount));\n this.helper.createCashBasedJournalEntryForSharesCharges(office, currencyCode, CashAccountsForShares.INCOME_FROM_FEES, shareProductId, shareAccountId, transactionId, transactionDate, chargeAmount, feePayments);\n }\n } else if (transactionDTO.getTransactionStatus().isApproved()) {\n BigDecimal amountForJE = amount;\n if (chargeAmount != null && chargeAmount.compareTo(BigDecimal.ZERO) > 0) {\n amountForJE = amount.subtract(chargeAmount);\n }\n this.helper.createJournalEntriesForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), CashAccountsForShares.SHARES_EQUITY.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amountForJE);\n } else if (transactionDTO.getTransactionStatus().isRejected()) {\n if (chargeAmount != null && chargeAmount.compareTo(BigDecimal.ZERO) > 0) {\n this.helper.revertCashBasedJournalEntryForSharesCharges(office, currencyCode, CashAccountsForShares.INCOME_FROM_FEES, shareProductId, shareAccountId, transactionId, transactionDate, chargeAmount, feePayments);\n this.helper.createDebitJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount.subtract(chargeAmount));\n this.helper.createCreditJournalEntryForShares(office, currencyCode, CashAccountsForShares.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount);\n } else {\n this.helper.createJournalEntriesForShares(office, currencyCode, CashAccountsForShares.SHARES_SUSPENSE.getValue(), CashAccountsForShares.SHARES_REFERENCE.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, amount);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Creates a User VM in Advanced Zone (Security Group feature is enabled) in\n * the database and returns the VM to the caller.\n *\n * @param zone\n * - availability zone for the virtual machine\n * @param serviceOffering\n * - the service offering for the virtual machine\n * @param template\n * - the template for the virtual machine\n * @param networkIdList\n * - list of network ids used by virtual machine\n * @param securityGroupIdList\n * - comma separated list of security groups id that going to be\n * applied to the virtual machine\n * @param hostName\n * - host name for the virtual machine\n * @param displayName\n * - an optional user generated name for the virtual machine\n * @param diskOfferingId\n * - the ID of the disk offering for the virtual machine. If the\n * template is of ISO format, the diskOfferingId is for the root\n * disk volume. Otherwise this parameter is used to indicate the\n * offering for the data disk volume. If the templateId parameter\n * passed is from a Template object, the diskOfferingId refers to\n * a DATA Disk Volume created. If the templateId parameter passed\n * is from an ISO object, the diskOfferingId refers to a ROOT\n * Disk Volume created\n * @param diskSize\n * - the arbitrary size for the DATADISK volume. Mutually\n * exclusive with diskOfferingId\n * @param group\n * - an optional group for the virtual machine\n * @param hypervisor\n * - the hypervisor on which to deploy the virtual machine\n * @param userData\n * - an optional binary data that can be sent to the virtual\n * machine upon a successful deployment. This binary data must be\n * base64 encoded before adding it to the request. Currently only\n * HTTP GET is supported. Using HTTP GET (via querystring), you\n * can send up to 2KB of data after base64 encoding\n * @param userDataId\n * @param userDataDetails\n * @param requestedIps\n * TODO\n * @param defaultIps\n * TODO\n * @param displayVm\n * - Boolean flag whether to the display the vm to the end user or not\n * @param affinityGroupIdList\n * @param customId\n * @param dhcpOptionMap\n * - Maps the dhcp option code and the dhcp value to the network uuid\n * @param dataDiskTemplateToDiskOfferingMap\n * - Datadisk template to Disk offering Map\n * an optional parameter that creates additional data disks for the virtual machine\n * For each of the templates in the map, a data disk will be created from the corresponding\n * disk offering obtained from the map\n * @return UserVm object if successful.\n *\n * @throws InsufficientCapacityException\n * if there is insufficient capacity to deploy the VM.\n * @throws ConcurrentOperationException\n * if there are multiple users working on the same VM or in the\n * same environment.\n * @throws ResourceUnavailableException\n * if the resources required to deploy the VM is not currently\n * available.\n */\nUserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "/**\n * Util for generating partitioned {@link ParquetColumnarRowSplitReader}.\n */\npublic static ParquetColumnarRowSplitReader genPartColumnarRowReader(boolean utcTimestamp, boolean caseSensitive, Configuration conf, String[] fullFieldNames, DataType[] fullFieldTypes, Map partitionSpec, int[] selectedFields, int batchSize, Path path, long splitStart, long splitLength, FilterPredicate filterPredicate, UnboundRecordFilter recordFilter) throws IOException {\n ValidationUtils.checkState(Arrays.stream(selectedFields).noneMatch(x -> x == -1), \"One or more specified columns does not exist in the hudi table.\");\n List selNonPartNames = Arrays.stream(selectedFields).mapToObj(i -> fullFieldNames[i]).filter(n -> !partitionSpec.containsKey(n)).collect(Collectors.toList());\n int[] selParquetFields = Arrays.stream(selectedFields).filter(i -> !partitionSpec.containsKey(fullFieldNames[i])).toArray();\n ParquetColumnarRowSplitReader.ColumnBatchGenerator gen = readVectors -> {\n // create and initialize the row batch\n ColumnVector[] vectors = new ColumnVector[selectedFields.length];\n for (int i = 0; i < vectors.length; i++) {\n String name = fullFieldNames[selectedFields[i]];\n LogicalType type = fullFieldTypes[selectedFields[i]].getLogicalType();\n vectors[i] = createVector(readVectors, selNonPartNames, name, type, partitionSpec, batchSize);\n }\n return new VectorizedColumnBatch(vectors);\n };\n return new ParquetColumnarRowSplitReader(utcTimestamp, caseSensitive, conf, Arrays.stream(selParquetFields).mapToObj(i -> fullFieldTypes[i].getLogicalType()).toArray(LogicalType[]::new), selNonPartNames.toArray(new String[0]), gen, batchSize, new org.apache.hadoop.fs.Path(path.toUri()), splitStart, splitLength, filterPredicate, recordFilter);\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "/**\n * Get a list of partition values as one big struct.\n * @param catName catalog name.\n * @param db_name database name.\n * @param tbl_name table name.\n * @param cols partition key columns\n * @param applyDistinct whether to apply distinct to the list\n * @param filter filter to apply to the partition names\n * @param ascending whether to put in ascending order\n * @param order whether to order\n * @param maxParts maximum number of parts to return, or -1 for all\n * @return struct with all of the partition value information\n * @throws MetaException error access the RDBMS\n */\nPartitionValuesResponse listPartitionValues(String catName, String db_name, String tbl_name, List cols, boolean applyDistinct, String filter, boolean ascending, List order, long maxParts) throws MetaException;", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * @param hasNear {@code True} if originating node has near cache.\n * @param firstEntryIdx Index of the first entry in the request keys collection.\n * @param entries Entries to update.\n * @param ver Version to set.\n * @param nearNode Originating node.\n * @param writeVals Write values.\n * @param putMap Values to put.\n * @param rmvKeys Keys to remove.\n * @param entryProcessorMap Entry processors.\n * @param req Request.\n * @param res Response.\n * @param replicate Whether replication is enabled.\n * @param dhtUpdRes Batch update result.\n * @param taskName Task name.\n * @param expiry Expiry policy.\n * @param sndPrevVal If {@code true} sends previous value to backups.\n */\n@Nullable\nprivate void updatePartialBatch(final boolean hasNear, final int firstEntryIdx, final List entries, final GridCacheVersion ver, final ClusterNode nearNode, @Nullable final List writeVals, @Nullable final Map putMap, @Nullable final Collection rmvKeys, @Nullable final Map> entryProcessorMap, final GridNearAtomicAbstractUpdateRequest req, final GridNearAtomicUpdateResponse res, final boolean replicate, final DhtAtomicUpdateResult dhtUpdRes, final String taskName, @Nullable final IgniteCacheExpiryPolicy expiry, final boolean sndPrevVal) {\n assert putMap == null ^ rmvKeys == null;\n assert req.conflictVersions() == null : \"Cannot be called when there are conflict entries in the batch.\";\n AffinityTopologyVersion topVer = req.topologyVersion();\n CacheStorePartialUpdateException storeErr = null;\n try {\n GridCacheOperation op;\n if (putMap != null) {\n try {\n Map> view = F.viewReadOnly(putMap, new C1>() {\n\n @Override\n public IgniteBiTuple apply(CacheObject val) {\n return F.t(val, ver);\n }\n });\n ctx.store().putAll(null, view);\n } catch (CacheStorePartialUpdateException e) {\n storeErr = e;\n }\n op = UPDATE;\n } else {\n try {\n ctx.store().removeAll(null, rmvKeys);\n } catch (CacheStorePartialUpdateException e) {\n storeErr = e;\n }\n op = DELETE;\n }\n boolean intercept = ctx.config().getInterceptor() != null;\n AffinityAssignment affAssignment = ctx.affinity().assignment(topVer);\n final GridDhtAtomicAbstractUpdateFuture dhtFut = dhtUpdRes.dhtFuture();\n Collection failedToUnwrapKeys = null;\n // Avoid iterator creation.\n for (int i = 0; i < entries.size(); i++) {\n GridDhtCacheEntry entry = entries.get(i);\n assert entry.lockedByCurrentThread();\n if (entry.obsolete()) {\n assert req.operation() == DELETE : \"Entry can become obsolete only after remove: \" + entry;\n continue;\n }\n if (storeErr != null) {\n Object key = entry.key();\n try {\n key = entry.key().value(ctx.cacheObjectContext(), false);\n } catch (BinaryInvalidTypeException e) {\n if (log.isDebugEnabled()) {\n if (failedToUnwrapKeys == null)\n failedToUnwrapKeys = new ArrayList<>();\n // To limit keys count in log message.\n if (failedToUnwrapKeys.size() < 5)\n failedToUnwrapKeys.add(key);\n }\n }\n if (storeErr.failedKeys().contains(key))\n continue;\n }\n try {\n // We are holding java-level locks on entries at this point.\n CacheObject writeVal = op == UPDATE ? writeVals.get(i) : null;\n assert writeVal != null || op == DELETE : \"null write value found.\";\n // Get readers before innerUpdate (reader cleared after remove).\n GridDhtCacheEntry.ReaderId[] readers = entry.readersLocked();\n EntryProcessor entryProc = entryProcessorMap == null ? null : entryProcessorMap.get(entry.key());\n boolean readRepairRecovery = op == TRANSFORM && req.entryProcessor(i) instanceof AtomicReadRepairEntryProcessor;\n GridCacheUpdateAtomicResult updRes = entry.innerUpdate(ver, nearNode.id(), locNodeId, op, writeVal, null, /*write-through*/\n false, /*read-through*/\n false, /*retval*/\n sndPrevVal, req.keepBinary(), expiry, /*event*/\n true, /*metrics*/\n true, /*primary*/\n true, /*verCheck*/\n false, readRepairRecovery, topVer, null, replicate ? DR_PRIMARY : DR_NONE, CU.TTL_NOT_CHANGED, CU.EXPIRE_TIME_CALCULATE, null, /*conflict resolve*/\n false, /*intercept*/\n false, taskName, null, null, dhtFut, entryProc != null);\n assert !updRes.success() || updRes.newTtl() == CU.TTL_NOT_CHANGED || expiry != null : \"success=\" + updRes.success() + \", newTtl=\" + updRes.newTtl() + \", expiry=\" + expiry;\n if (intercept) {\n if (op == UPDATE) {\n ctx.config().getInterceptor().onAfterPut(new CacheLazyEntry(ctx, entry.key(), updRes.newValue(), req.keepBinary()));\n } else {\n assert op == DELETE : op;\n // Old value should be already loaded for 'CacheInterceptor.onBeforeRemove'.\n ctx.config().getInterceptor().onAfterRemove(new CacheLazyEntry(ctx, entry.key(), updRes.oldValue(), req.keepBinary()));\n }\n }\n dhtUpdRes.addDeleted(entry, updRes, entries);\n if (dhtFut != null) {\n dhtFut.addWriteEntry(affAssignment, entry, writeVal, entryProc, updRes.newTtl(), CU.EXPIRE_TIME_CALCULATE, null, sndPrevVal, updRes.oldValue(), updRes.updateCounter(), op, readRepairRecovery);\n if (readers != null)\n dhtFut.addNearWriteEntries(nearNode, readers, entry, writeVal, entryProc, updRes.newTtl(), CU.EXPIRE_TIME_CALCULATE, readRepairRecovery);\n }\n if (hasNear) {\n if (!ctx.affinity().partitionBelongs(nearNode, entry.partition(), topVer)) {\n int idx = firstEntryIdx + i;\n if (req.operation() == TRANSFORM) {\n res.addNearValue(idx, writeVal, updRes.newTtl(), CU.EXPIRE_TIME_CALCULATE);\n } else\n res.addNearTtl(idx, updRes.newTtl(), CU.EXPIRE_TIME_CALCULATE);\n if (writeVal != null || entry.hasValue()) {\n IgniteInternalFuture f = entry.addReader(nearNode.id(), req.messageId(), topVer);\n assert f == null : f;\n }\n } else if (GridDhtCacheEntry.ReaderId.contains(readers, nearNode.id())) {\n // Reader became primary or backup.\n entry.removeReader(nearNode.id(), req.messageId());\n } else\n res.addSkippedIndex(firstEntryIdx + i);\n }\n } catch (GridCacheEntryRemovedException e) {\n assert false : \"Entry cannot become obsolete while holding lock.\";\n e.printStackTrace();\n }\n dhtUpdRes.processedEntriesCount(firstEntryIdx + i + 1);\n }\n if (failedToUnwrapKeys != null) {\n log.warning(\"Failed to get values of keys: \" + failedToUnwrapKeys + \" (the binary objects will be used instead).\");\n }\n } catch (IgniteCheckedException e) {\n res.addFailedKeys(putMap != null ? putMap.keySet() : rmvKeys, e);\n }\n if (storeErr != null) {\n ArrayList failed = new ArrayList<>(storeErr.failedKeys().size());\n for (Object failedKey : storeErr.failedKeys()) failed.add(ctx.toCacheKeyObject(failedKey));\n res.addFailedKeys(failed, storeErr.getCause());\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "UserVm updateVirtualMachine(long id, String displayName, String group, Boolean ha, Boolean isDisplayVmEnabled, Boolean deleteProtection, Long osTypeId, String userData, Long userDataId, String userDataDetails, Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId, String hostName, String instanceName, List securityGroupIdList, Map> extraDhcpOptionsMap) throws ResourceUnavailableException, InsufficientCapacityException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Loads the action and executes it. This method first creates the action\n * context from the given parameters then loads an ActionProxy\n * from the given action name and namespace. After that, the action is\n * executed and output channels throught the response object.\n *\n * @param request the HttpServletRequest object.\n * @param response the HttpServletResponse object.\n * @param requestMap a Map of request attributes.\n * @param parameterMap a Map of request parameters.\n * @param sessionMap a Map of all session attributes.\n * @param applicationMap a Map of all application attributes.\n * @param portletNamespace the namespace or context of the action.\n * @param phase The portlet phase (render or action, see {@link PortletConstants})\n * @throws PortletException in case of errors\n */\npublic void serviceAction(PortletRequest request, PortletResponse response, Map requestMap, Map parameterMap, Map sessionMap, Map applicationMap, String portletNamespace, PortletPhase phase) throws PortletException {\n if (LOG.isDebugEnabled())\n LOG.debug(\"serviceAction\");\n Dispatcher.setInstance(dispatcherUtils);\n String actionName = null;\n String namespace;\n try {\n HttpServletRequest servletRequest = new PortletServletRequest(request, getPortletContext());\n HttpServletResponse servletResponse = createPortletServletResponse(response);\n if (phase.isAction()) {\n servletRequest = dispatcherUtils.wrapRequest(servletRequest);\n if (servletRequest instanceof MultiPartRequestWrapper) {\n // Multipart request. Request parameters are encoded in the multipart data,\n // so we need to manually add them to the parameter map.\n parameterMap.putAll(servletRequest.getParameterMap());\n }\n }\n container.inject(servletRequest);\n ActionMapping mapping = getActionMapping(request, servletRequest);\n actionName = mapping.getName();\n if (\"renderDirect\".equals(actionName)) {\n namespace = request.getParameter(PortletConstants.RENDER_DIRECT_NAMESPACE);\n } else {\n namespace = mapping.getNamespace();\n }\n Map extraContext = createContextMap(requestMap, parameterMap, sessionMap, applicationMap, request, response, servletRequest, servletResponse, servletContext, getPortletConfig(), phase);\n extraContext.put(PortletConstants.ACTION_MAPPING, mapping);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Creating action proxy for name = \" + actionName + \", namespace = \" + namespace);\n }\n ActionProxy proxy = factory.createActionProxy(namespace, actionName, mapping.getMethod(), extraContext);\n request.setAttribute(\"struts.valueStack\", proxy.getInvocation().getStack());\n proxy.execute();\n } catch (ConfigurationException e) {\n if (LOG.isErrorEnabled()) {\n LOG.error(\"Could not find action\", e);\n }\n throw new PortletException(\"Could not find action \" + actionName, e);\n } catch (Exception e) {\n if (LOG.isErrorEnabled()) {\n LOG.error(\"Could not execute action\", e);\n }\n throw new PortletException(\"Error executing action \" + actionName, e);\n } finally {\n Dispatcher.clearInstance();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_struts", "language": "java"} {"function": "public static String generateCreateDDL(String tableName, MessageType storageSchema, HiveSyncConfig config, String inputFormatClass, String outputFormatClass, String serdeClass, Map serdeProperties, Map tableProperties) throws IOException {\n Map hiveSchema = convertParquetSchemaToHiveSchema(storageSchema, config.getBoolean(HIVE_SUPPORT_TIMESTAMP_TYPE));\n String columns = generateSchemaString(storageSchema, config.getSplitStrings(META_SYNC_PARTITION_FIELDS), config.getBoolean(HIVE_SUPPORT_TIMESTAMP_TYPE));\n List partitionFields = new ArrayList<>();\n for (String partitionKey : config.getSplitStrings(META_SYNC_PARTITION_FIELDS)) {\n String partitionKeyWithTicks = tickSurround(partitionKey);\n partitionFields.add(new StringBuilder().append(partitionKeyWithTicks).append(\" \").append(getPartitionKeyType(hiveSchema, partitionKeyWithTicks)).toString());\n }\n String partitionsStr = String.join(\",\", partitionFields);\n StringBuilder sb = new StringBuilder();\n if (config.getBoolean(HIVE_CREATE_MANAGED_TABLE)) {\n sb.append(\"CREATE TABLE IF NOT EXISTS \");\n } else {\n sb.append(\"CREATE EXTERNAL TABLE IF NOT EXISTS \");\n }\n sb.append(HIVE_ESCAPE_CHARACTER).append(config.getStringOrDefault(META_SYNC_DATABASE_NAME)).append(HIVE_ESCAPE_CHARACTER).append(\".\").append(HIVE_ESCAPE_CHARACTER).append(tableName).append(HIVE_ESCAPE_CHARACTER);\n sb.append(\"( \").append(columns).append(\")\");\n if (!config.getSplitStrings(META_SYNC_PARTITION_FIELDS).isEmpty()) {\n sb.append(\" PARTITIONED BY (\").append(partitionsStr).append(\")\");\n }\n if (config.getString(HIVE_SYNC_BUCKET_SYNC_SPEC) != null) {\n sb.append(' ' + config.getString(HIVE_SYNC_BUCKET_SYNC_SPEC) + ' ');\n }\n sb.append(\" ROW FORMAT SERDE '\").append(serdeClass).append(\"'\");\n if (serdeProperties != null && !serdeProperties.isEmpty()) {\n sb.append(\" WITH SERDEPROPERTIES (\").append(propertyToString(serdeProperties)).append(\")\");\n }\n sb.append(\" STORED AS INPUTFORMAT '\").append(inputFormatClass).append(\"'\");\n sb.append(\" OUTPUTFORMAT '\").append(outputFormatClass).append(\"' LOCATION '\").append(config.getAbsoluteBasePath()).append(\"'\");\n if (tableProperties != null && !tableProperties.isEmpty()) {\n sb.append(\" TBLPROPERTIES(\").append(propertyToString(tableProperties)).append(\")\");\n }\n return sb.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "String addMetadata(Element xml, String uuid, String schema, GroupMapper localGroups, final CategoryMapper localCateg, String createDate, BaseAligner aligner, boolean index) throws Exception {\n log.debug(\" - Adding metadata with remote uuid: \" + uuid);\n Element md = xml;\n AbstractMetadata metadata = new Metadata();\n metadata.setUuid(uuid);\n MetadataType metadataType = MetadataType.lookup(params.recordType);\n String xmlUuid = null;\n if (metadataType == MetadataType.METADATA) {\n xmlUuid = metadataUtils.extractUUID(schema, md);\n } else if (metadataType == MetadataType.SUB_TEMPLATE) {\n xmlUuid = md.getAttributeValue(\"uuid\");\n } else if (metadataType == MetadataType.TEMPLATE_OF_SUB_TEMPLATE) {\n xmlUuid = md.getAttributeValue(\"uuid\");\n }\n if (!uuid.equals(xmlUuid)) {\n md = metadataUtils.setUUID(schema, uuid, md);\n }\n // Translate metadata\n if (params.isTranslateContent()) {\n md = aligner.translateMetadataContent(context, md, schema);\n }\n metadata.getDataInfo().setSchemaId(schema).setRoot(xml.getQualifiedName()).setType(metadataType).setCreateDate(new ISODate(createDate)).setChangeDate(new ISODate(createDate));\n metadata.getSourceInfo().setSourceId(params.getUuid()).setOwner(aligner.getOwner()).setGroupOwner(Integer.valueOf(params.getOwnerIdGroup()));\n metadata.getHarvestInfo().setHarvested(true).setUuid(params.getUuid());\n aligner.addCategories(metadata, params.getCategories(), localCateg, context, null, false);\n metadata = metadataManager.insertMetadata(context, metadata, md, IndexingMode.none, false, UpdateDatestamp.NO, false, false);\n String id = String.valueOf(metadata.getId());\n aligner.addPrivileges(id, params.getPrivileges(), localGroups, context);\n metadataManager.flush();\n if (index) {\n dataMan.indexMetadata(id, true);\n }\n return id;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public String doRequest(URI baseURI, String verb, String set, String from, String until, String metadataPrefix, String token, String identifier) throws IOException, URISyntaxException{\r\n try (CloseableHttpClient httpclient = getCloseableHttpClient()) {\r\n URIBuilder builder = new URIBuilder();\r\n builder.setScheme(baseURI.getScheme()).setHost(baseURI.getHost()).setPort(baseURI.getPort()).setPath(baseURI.getPath()).addParameter(\"verb\", verb).addParameters(URLEncodedUtils.parse(baseURI, Charset.defaultCharset()));\r\n if (identifier != null) {\r\n builder.addParameter(\"identifier\", identifier);\r\n }\r\n if (token != null) {\r\n builder.addParameter(\"resumptionToken\", token);\r\n } else {\r\n if (metadataPrefix != null) {\r\n builder.addParameter(\"metadataPrefix\", metadataPrefix);\r\n }\r\n if (set != null) {\r\n builder.addParameter(\"set\", set);\r\n }\r\n if (from != null) {\r\n builder.addParameter(\"from\", from);\r\n }\r\n if (until != null) {\r\n builder.addParameter(\"until\", until);\r\n }\r\n }\r\n HttpGet httpget = new HttpGet(builder.build());\r\n LOG.info(\"Executing request: {} \", httpget);\r\n HttpClientResponseHandler responseHandler = new HttpClientResponseHandler() {\r\n\r\n @Override\r\n public String handleResponse(final ClassicHttpResponse response) throws HttpException, IOException {\r\n int status = response.getCode();\r\n if (status >= 200 && status < 300) {\r\n HttpEntity entity = response.getEntity();\r\n if (entity == null) {\r\n throw new IOException(\"No response received\");\r\n }\r\n return EntityUtils.toString(entity, StandardCharsets.UTF_8);\r\n } else {\r\n throw new ClientProtocolException(\"Unexpected response status: \" + status);\r\n }\r\n }\r\n };\r\n String responseBody = httpclient.execute(httpget, responseHandler);\r\n LOG.debug(\"Response received: {}\", responseBody);\r\n return responseBody;\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create a load balancer rule from the given ipAddress/port to the given private port\n * @param openFirewall\n * TODO\n * @param forDisplay TODO\n * @param cmd\n * the command specifying the ip address, public port, protocol, private port, and algorithm\n *\n * @return the newly created LoadBalancerVO if successful, null otherwise\n * @throws InsufficientAddressCapacityException\n */\nLoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm, long networkId, long lbOwnerId, boolean openFirewall, String lbProtocol, Boolean forDisplay) throws NetworkRuleConflictException, InsufficientAddressCapacityException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private void doLeftUpdatesProcessChildren(AccumulateNode accNode, AccumulateMemory am, ReteEvaluator reteEvaluator, BetaMemory bm, Accumulate accumulate, BetaConstraints constraints, FastIterator rightIt, LeftTuple leftTuple, final BaseAccumulation accctx, RightTuple rightTuple, LeftTuple match){\r\n if (match == null) {\r\n for (; rightTuple != null; rightTuple = (RightTuple) rightIt.next(rightTuple)) {\r\n if (constraints.isAllowedCachedLeft(bm.getContext(), rightTuple.getFactHandleForEvaluation())) {\r\n addMatch(accNode, accumulate, leftTuple, rightTuple, null, null, reteEvaluator, am, accctx, true, true);\r\n }\r\n }\r\n } else {\r\n boolean isDirty = false;\r\n for (; rightTuple != null; rightTuple = (RightTuple) rightIt.next(rightTuple)) {\r\n if (constraints.isAllowedCachedLeft(bm.getContext(), rightTuple.getFactHandleForEvaluation())) {\r\n if (match == null || match.getRightParent() != rightTuple) {\r\n addMatch(accNode, accumulate, leftTuple, rightTuple, match, null, reteEvaluator, am, accctx, true, true);\r\n } else {\r\n LeftTuple temp = match.getHandleNext();\r\n match.reAddRight();\r\n match = temp;\r\n isDirty = accumulate.hasRequiredDeclarations();\r\n }\r\n } else if (match != null && match.getRightParent() == rightTuple) {\r\n LeftTuple temp = match.getHandleNext();\r\n boolean reversed = removeMatch(accNode, accumulate, rightTuple, match, reteEvaluator, am, accctx, false);\r\n match = temp;\r\n isDirty = !reversed;\r\n }\r\n }\r\n if (isDirty) {\r\n reaccumulateForLeftTuple(accNode, accumulate, leftTuple, null, null, reteEvaluator, am, accctx, true);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Given a source directory name of the load path, load all dynamically generated partitions\n * into the specified table and return a list of strings that represent the dynamic partition\n * paths.\n * @param tbd table descriptor\n * @param numLB number of buckets\n * @param isAcid true if this is an ACID operation\n * @param writeId writeId, can be 0 unless isAcid == true\n * @param stmtId statementId\n * @param resetStatistics if true, reset statistics. Do not reset statistics otherwise.\n * @param operation ACID operation type\n * @param partitionDetailsMap full dynamic partition specification\n * @return partition map details (PartitionSpec and Partition)\n * @throws HiveException\n */\npublic Map, Partition> loadDynamicPartitions(final LoadTableDesc tbd, final int numLB, final boolean isAcid, final long writeId, final int stmtId, final boolean resetStatistics, final AcidUtils.Operation operation, Map partitionDetailsMap) throws HiveException {\n PerfLogger perfLogger = SessionState.getPerfLogger();\n perfLogger.perfLogBegin(\"MoveTask\", PerfLogger.LOAD_DYNAMIC_PARTITIONS);\n final Path loadPath = tbd.getSourcePath();\n final Table tbl = getTable(tbd.getTable().getTableName());\n final Map partSpec = tbd.getPartitionSpec();\n final AtomicInteger partitionsLoaded = new AtomicInteger(0);\n final boolean inPlaceEligible = conf.getLong(\"fs.trash.interval\", 0) <= 0 && InPlaceUpdate.canRenderInPlace(conf) && !SessionState.getConsole().getIsSilent();\n final PrintStream ps = (inPlaceEligible) ? SessionState.getConsole().getInfoStream() : null;\n final SessionState parentSession = SessionState.get();\n List> tasks = Lists.newLinkedList();\n boolean fetchPartitionInfo = true;\n final boolean scanPartitionsByName = HiveConf.getBoolVar(conf, HIVE_LOAD_DYNAMIC_PARTITIONS_SCAN_SPECIFIC_PARTITIONS);\n // ACID table can be a bigger change. Filed HIVE-25817 for an appropriate fix for ACID tables\n // For now, for ACID tables, skip getting all partitions for a table from HMS (since that\n // can degrade performance for large partitioned tables) and instead make getPartition() call\n // for every dynamic partition\n if (scanPartitionsByName && !tbd.isDirectInsert() && !AcidUtils.isTransactionalTable(tbl)) {\n //Fetch only relevant partitions from HMS for checking old partitions\n List partitionNames = new LinkedList<>();\n for (PartitionDetails details : partitionDetailsMap.values()) {\n if (details.fullSpec != null && !details.fullSpec.isEmpty()) {\n partitionNames.add(Warehouse.makeDynamicPartNameNoTrailingSeperator(details.fullSpec));\n }\n }\n List partitions = Hive.get().getPartitionsByNames(tbl, partitionNames);\n for (Partition partition : partitions) {\n LOG.debug(\"HMS partition spec: {}\", partition.getSpec());\n partitionDetailsMap.entrySet().parallelStream().filter(entry -> entry.getValue().fullSpec.equals(partition.getSpec())).findAny().ifPresent(entry -> {\n entry.getValue().partition = partition;\n entry.getValue().hasOldPartition = true;\n });\n }\n // no need to fetch partition again in tasks since we have already fetched partitions\n // info in getPartitionsByNames()\n fetchPartitionInfo = false;\n }\n boolean isTxnTable = AcidUtils.isTransactionalTable(tbl);\n AcidUtils.TableSnapshot tableSnapshot = isTxnTable ? getTableSnapshot(tbl, writeId) : null;\n for (Entry entry : partitionDetailsMap.entrySet()) {\n boolean getPartitionFromHms = fetchPartitionInfo;\n tasks.add(() -> {\n PartitionDetails partitionDetails = entry.getValue();\n Map fullPartSpec = partitionDetails.fullSpec;\n try {\n SessionState.setCurrentSessionState(parentSession);\n if (getPartitionFromHms) {\n // didn't fetch partition info from HMS. Getting from HMS now.\n Partition existing = getPartition(tbl, fullPartSpec, false);\n if (existing != null) {\n partitionDetails.partition = existing;\n partitionDetails.hasOldPartition = true;\n }\n }\n LOG.info(\"New loading path = \" + entry.getKey() + \" withPartSpec \" + fullPartSpec);\n Partition oldPartition = partitionDetails.partition;\n List newFiles = null;\n if (partitionDetails.newFiles != null) {\n // If we already know the files from the direct insert manifest, use them\n newFiles = partitionDetails.newFiles;\n } else if (conf.getBoolVar(ConfVars.FIRE_EVENTS_FOR_DML) && !tbl.isTemporary()) {\n // Otherwise only collect them, if we are going to fire write notifications\n newFiles = Collections.synchronizedList(new ArrayList<>());\n }\n // load the partition\n Partition partition = loadPartitionInternal(entry.getKey(), tbl, fullPartSpec, oldPartition, tbd.getLoadFileType(), true, false, numLB > 0, false, isAcid, resetStatistics, writeId, stmtId, tbd.isInsertOverwrite(), isTxnTable, newFiles, tbd.isDirectInsert());\n // if the partition already existed before the loading, no need to add it again to the\n // metastore\n if (tableSnapshot != null) {\n partition.getTPartition().setWriteId(tableSnapshot.getWriteId());\n }\n partitionDetails.tableSnapshot = tableSnapshot;\n if (oldPartition == null) {\n partitionDetails.newFiles = newFiles;\n partitionDetails.partition = partition;\n }\n if (inPlaceEligible) {\n synchronized (ps) {\n InPlaceUpdate.rePositionCursor(ps);\n partitionsLoaded.incrementAndGet();\n InPlaceUpdate.reprintLine(ps, \"Loaded : \" + partitionsLoaded.get() + \"/\" + partitionDetailsMap.size() + \" partitions.\");\n }\n }\n return partition;\n } catch (Exception e) {\n LOG.error(\"Exception when loading partition with parameters \" + \" partPath=\" + entry.getKey() + \", \" + \" table=\" + tbl.getTableName() + \", \" + \" partSpec=\" + fullPartSpec + \", \" + \" loadFileType=\" + tbd.getLoadFileType().toString() + \", \" + \" listBucketingLevel=\" + numLB + \", \" + \" isAcid=\" + isAcid + \", \" + \" resetStatistics=\" + resetStatistics, e);\n throw e;\n } finally {\n // get(conf).getMSC can be called in this task, Close the HMS connection right after use, do not wait for finalizer to close it.\n closeCurrent();\n }\n });\n }\n int poolSize = conf.getInt(ConfVars.HIVE_LOAD_DYNAMIC_PARTITIONS_THREAD_COUNT.varname, 1);\n ExecutorService executor = Executors.newFixedThreadPool(poolSize, new ThreadFactoryBuilder().setDaemon(true).setNameFormat(\"load-dynamic-partitionsToAdd-%d\").build());\n List> futures = Lists.newLinkedList();\n Map, Partition> result = Maps.newLinkedHashMap();\n try {\n futures = executor.invokeAll(tasks);\n LOG.info(\"Number of partitionsToAdd to be added is \" + futures.size());\n for (Future future : futures) {\n Partition partition = future.get();\n result.put(partition.getSpec(), partition);\n }\n // add new partitions in batch\n addPartitionsToMetastore(partitionDetailsMap.entrySet().stream().filter(entry -> !entry.getValue().hasOldPartition).map(entry -> entry.getValue().partition).collect(Collectors.toList()), resetStatistics, tbl, partitionDetailsMap.entrySet().stream().filter(entry -> !entry.getValue().hasOldPartition).map(entry -> entry.getValue().tableSnapshot).collect(Collectors.toList()));\n // For acid table, add the acid_write event with file list at the time of load itself. But\n // it should be done after partition is created.\n List requestList = new ArrayList<>();\n int maxBatchSize = conf.getIntVar(HIVE_WRITE_NOTIFICATION_MAX_BATCH_SIZE);\n for (Entry entry : partitionDetailsMap.entrySet()) {\n PartitionDetails partitionDetails = entry.getValue();\n if (isTxnTable && partitionDetails.newFiles != null) {\n addWriteNotificationLog(tbl, partitionDetails.fullSpec, partitionDetails.newFiles, writeId, requestList);\n if (requestList != null && requestList.size() >= maxBatchSize) {\n // If the first call returns that the HMS does not supports batching, avoid batching\n // for later requests.\n boolean batchSupported = addWriteNotificationLogInBatch(tbl, requestList);\n if (batchSupported) {\n requestList.clear();\n } else {\n requestList = null;\n }\n }\n }\n }\n if (requestList != null && requestList.size() > 0) {\n addWriteNotificationLogInBatch(tbl, requestList);\n }\n setStatsPropAndAlterPartitions(resetStatistics, tbl, partitionDetailsMap.entrySet().stream().filter(entry -> entry.getValue().hasOldPartition).map(entry -> entry.getValue().partition).collect(Collectors.toList()), tableSnapshot);\n } catch (InterruptedException | ExecutionException e) {\n throw new HiveException(\"Exception when loading \" + partitionDetailsMap.size() + \" partitions\" + \" in table \" + tbl.getTableName() + \" with loadPath=\" + loadPath, e);\n } catch (TException e) {\n LOG.error(\"Failed loadDynamicPartitions\", e);\n throw new HiveException(e);\n } catch (Exception e) {\n StringBuffer logMsg = new StringBuffer();\n logMsg.append(\"Exception when loading partitionsToAdd with parameters \");\n logMsg.append(\"partPaths=\");\n partitionDetailsMap.keySet().forEach(path -> logMsg.append(path + \", \"));\n logMsg.append(\"table=\" + tbl.getTableName() + \", \").append(\"partSpec=\" + partSpec + \", \").append(\"loadFileType=\" + tbd.getLoadFileType().toString() + \", \").append(\"listBucketingLevel=\" + numLB + \", \").append(\"isAcid=\" + isAcid + \", \").append(\"resetStatistics=\" + resetStatistics);\n LOG.error(logMsg.toString(), e);\n throw e;\n } finally {\n LOG.debug(\"Cancelling \" + futures.size() + \" dynamic loading tasks\");\n executor.shutdownNow();\n }\n if (HiveConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST) && HiveConf.getBoolVar(conf, ConfVars.HIVE_TEST_MODE_FAIL_LOAD_DYNAMIC_PARTITION)) {\n throw new HiveException(HiveConf.ConfVars.HIVE_TEST_MODE_FAIL_LOAD_DYNAMIC_PARTITION.name() + \"=true\");\n }\n try {\n if (isTxnTable) {\n List partNames = result.values().stream().map(Partition::getName).collect(Collectors.toList());\n getMSC().addDynamicPartitions(parentSession.getTxnMgr().getCurrentTxnId(), writeId, tbl.getDbName(), tbl.getTableName(), partNames, AcidUtils.toDataOperationType(operation));\n }\n LOG.info(\"Loaded \" + result.size() + \"partitionsToAdd\");\n perfLogger.perfLogEnd(\"MoveTask\", PerfLogger.LOAD_DYNAMIC_PARTITIONS);\n return result;\n } catch (TException te) {\n LOG.error(\"Failed loadDynamicPartitions\", te);\n throw new HiveException(\"Exception updating metastore for acid table \" + tbd.getTable().getTableName() + \" with partitions \" + result.values(), te);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void doLeftUpdates(TimerNode timerNode, TimerNodeMemory tm, PathMemory pmem, SegmentMemory smem, LeftTupleSink sink, ActivationsManager activationsManager, TupleSets srcLeftTuples, TupleSets trgLeftTuples, TupleSets stagedLeftTuples){\r\n Timer timer = timerNode.getTimer();\r\n TimerService timerService = activationsManager.getReteEvaluator().getTimerService();\r\n long timestamp = timerService.getCurrentTime();\r\n String[] calendarNames = timerNode.getCalendarNames();\r\n Calendars calendars = activationsManager.getReteEvaluator().getCalendars();\r\n for (LeftTuple leftTuple = srcLeftTuples.getUpdateFirst(); leftTuple != null; ) {\r\n LeftTuple next = leftTuple.getStagedNext();\r\n DefaultJobHandle jobHandle = (DefaultJobHandle) leftTuple.getContextObject();\r\n if (jobHandle != null) {\r\n timerService.removeJob(jobHandle);\r\n }\r\n scheduleLeftTuple(timerNode, tm, pmem, smem, sink, activationsManager, timer, timerService, timestamp, calendarNames, calendars, leftTuple, trgLeftTuples, stagedLeftTuples);\r\n leftTuple.clearStaged();\r\n leftTuple = next;\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "// Used by tests only\npublic static NMContainerStatus newInstance(ContainerId containerId, int version, ContainerState containerState, Resource allocatedResource, String diagnostics, int containerExitStatus, Priority priority, long creationTime) {\n return newInstance(containerId, version, containerState, allocatedResource, diagnostics, containerExitStatus, priority, creationTime, CommonNodeLabelsManager.NO_LABEL, ExecutionType.GUARANTEED, -1);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static String constructFragmentStartString(String applicationIdStr, String containerIdStr, String hostname, String queryId, int dagIdentifier, String vertexName, int taskId, int attemptId){\r\n HistoryLineBuilder lb = new HistoryLineBuilder(EVENT_TYPE_FRAGMENT_START);\r\n lb.addHostName(hostname);\r\n lb.addAppid(applicationIdStr);\r\n lb.addContainerId(containerIdStr);\r\n lb.addQueryId(queryId);\r\n lb.addDagId(dagIdentifier);\r\n lb.addVertexName(vertexName);\r\n lb.addTaskId(taskId);\r\n lb.addTaskAttemptId(attemptId);\r\n lb.addTime(HISTORY_SUBMIT_TIME);\r\n return lb.toString();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static NodeReport newNodeReport(NodeId nodeId, NodeState nodeState, String httpAddress, String rackName, Resource used, Resource capability, int numContainers, String healthReport, long lastHealthReportTime) {\n return newNodeReport(nodeId, nodeState, httpAddress, rackName, used, capability, numContainers, healthReport, lastHealthReportTime, null, null, null);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Creates a Basic Zone User VM in the database and returns the VM to the\n * caller.\n *\n * @param zone\n * - availability zone for the virtual machine\n * @param serviceOffering\n * - the service offering for the virtual machine\n * @param template\n * - the template for the virtual machine\n * @param securityGroupIdList\n * - comma separated list of security groups id that going to be\n * applied to the virtual machine\n * @param hostName\n * - host name for the virtual machine\n * @param displayName\n * - an optional user generated name for the virtual machine\n * @param diskOfferingId\n * - the ID of the disk offering for the virtual machine. If the\n * template is of ISO format, the diskOfferingId is for the root\n * disk volume. Otherwise this parameter is used to indicate the\n * offering for the data disk volume. If the templateId parameter\n * passed is from a Template object, the diskOfferingId refers to\n * a DATA Disk Volume created. If the templateId parameter passed\n * is from an ISO object, the diskOfferingId refers to a ROOT\n * Disk Volume created\n * @param diskSize\n * - the arbitrary size for the DATADISK volume. Mutually\n * exclusive with diskOfferingId\n * @param group\n * - an optional group for the virtual machine\n * @param hypervisor\n * - the hypervisor on which to deploy the virtual machine\n * @param userData\n * - an optional binary data that can be sent to the virtual\n * machine upon a successful deployment. This binary data must be\n * base64 encoded before adding it to the request. Currently only\n * HTTP GET is supported. Using HTTP GET (via querystring), you\n * can send up to 2KB of data after base64 encoding\n * @param userDataId\n * @param userDataDetails\n * @param requestedIps\n * TODO\n * @param defaultIp\n * TODO\n * @param displayVm\n * - Boolean flag whether to the display the vm to the end user or not\n * @param affinityGroupIdList\n * @param customId\n * @param dhcpOptionMap\n * - Maps the dhcp option code and the dhcp value to the network uuid\n * @param dataDiskTemplateToDiskOfferingMap\n * - Datadisk template to Disk offering Map\n * an optional parameter that creates additional data disks for the virtual machine\n * For each of the templates in the map, a data disk will be created from the corresponding\n * disk offering obtained from the map\n *\n * @return UserVm object if successful.\n * @throws InsufficientCapacityException\n * if there is insufficient capacity to deploy the VM.\n * @throws ConcurrentOperationException\n * if there are multiple users working on the same VM or in the\n * same environment.\n * @throws ResourceUnavailableException\n * if the resources required to deploy the VM is not currently\n * available.\n */\nUserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParameter, String customId, Map> dhcpOptionMap, Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static void handleDirectInsertTableFinalPath(Path specPath, String unionSuffix, Configuration hconf, boolean success, int dpLevels, int lbLevels, MissingBucketsContext mbc, long writeId, int stmtId, Reporter reporter, boolean isMmTable, boolean isMmCtas, boolean isInsertOverwrite, boolean isDirectInsert, String staticSpec, AcidUtils.Operation acidOperation, FileSinkDesc conf) throws IOException, HiveException {\n FileSystem fs = specPath.getFileSystem(hconf);\n boolean isDelete = AcidUtils.Operation.DELETE.equals(acidOperation);\n Path manifestDir = getManifestDir(specPath, writeId, stmtId, unionSuffix, isInsertOverwrite, staticSpec, isDelete);\n if (!success) {\n AcidUtils.IdPathFilter filter = new AcidUtils.IdPathFilter(writeId, stmtId);\n tryDeleteAllDirectInsertFiles(fs, specPath, manifestDir, dpLevels, lbLevels, filter, writeId, stmtId, hconf, acidOperation);\n return;\n }\n Utilities.FILE_OP_LOGGER.debug(\"Looking for manifests in: {} ({})\", manifestDir, writeId);\n List manifests = new ArrayList<>();\n try {\n FileStatus[] manifestFiles = fs.listStatus(manifestDir);\n manifests = selectManifestFiles(manifestFiles);\n } catch (FileNotFoundException ex) {\n Utilities.FILE_OP_LOGGER.info(\"No manifests found in directory {} - query produced no output\", manifestDir);\n manifestDir = null;\n if (!fs.exists(specPath)) {\n // Empty insert to new partition\n fs.mkdirs(specPath);\n }\n }\n Map> dynamicPartitionSpecs = new HashMap<>();\n Set committed = Collections.newSetFromMap(new ConcurrentHashMap<>());\n Set directInsertDirectories = new HashSet<>();\n for (Path mfp : manifests) {\n Utilities.FILE_OP_LOGGER.info(\"Looking at manifest file: {}\", mfp);\n try (FSDataInputStream mdis = fs.open(mfp)) {\n if (dpLevels > 0) {\n int partitionCount = mdis.readInt();\n for (int i = 0; i < partitionCount; ++i) {\n String nextPart = mdis.readUTF();\n Utilities.FILE_OP_LOGGER.debug(\"Looking at dynamic partition {}\", nextPart);\n if (!dynamicPartitionSpecs.containsKey(nextPart)) {\n dynamicPartitionSpecs.put(nextPart, new ArrayList<>());\n }\n }\n }\n int fileCount = mdis.readInt();\n for (int i = 0; i < fileCount; ++i) {\n String nextFile = mdis.readUTF();\n Utilities.FILE_OP_LOGGER.debug(\"Looking at committed file {}\", nextFile);\n Path path = fs.makeQualified(new Path(nextFile));\n if (!committed.add(path)) {\n throw new HiveException(nextFile + \" was specified in multiple manifests\");\n }\n dynamicPartitionSpecs.entrySet().stream().filter(dynpath -> path.toString().contains(dynpath.getKey())).findAny().ifPresent(dynPath -> dynPath.getValue().add(path));\n Path parentDirPath = path.getParent();\n while (AcidUtils.isChildOfDelta(parentDirPath, specPath)) {\n // Some cases there are other directory layers between the delta and the datafiles\n // (export-import mm table, insert with union all to mm table, skewed tables).\n parentDirPath = parentDirPath.getParent();\n }\n directInsertDirectories.add(parentDirPath);\n }\n }\n }\n if (manifestDir != null) {\n Utilities.FILE_OP_LOGGER.info(\"Deleting manifest directory {}\", manifestDir);\n tryDelete(fs, manifestDir);\n if (unionSuffix != null) {\n // Also delete the parent directory if we are the last union FSOP to execute.\n manifestDir = manifestDir.getParent();\n FileStatus[] remainingFiles = fs.listStatus(manifestDir);\n if (remainingFiles == null || remainingFiles.length == 0) {\n Utilities.FILE_OP_LOGGER.info(\"Deleting manifest directory {}\", manifestDir);\n tryDelete(fs, manifestDir);\n }\n }\n }\n if (!directInsertDirectories.isEmpty()) {\n cleanDirectInsertDirectoriesConcurrently(directInsertDirectories, committed, fs, hconf, unionSuffix, lbLevels);\n }\n conf.setDynPartitionValues(dynamicPartitionSpecs);\n if (!committed.isEmpty()) {\n throw new HiveException(\"The following files were committed but not found: \" + committed);\n }\n if (directInsertDirectories.isEmpty()) {\n return;\n }\n // TODO: see HIVE-14886 - removeTempOrDuplicateFiles is broken for list bucketing,\n // so maintain parity here by not calling it at all.\n if (lbLevels != 0) {\n return;\n }\n if (!isDirectInsert) {\n // Create fake file statuses to avoid querying the file system. removeTempOrDuplicateFiles\n // doesn't need to check anything except path and directory status for MM directories.\n FileStatus[] finalResults = directInsertDirectories.stream().map(PathOnlyFileStatus::new).toArray(FileStatus[]::new);\n List emptyBuckets = Utilities.removeTempOrDuplicateFiles(fs, finalResults, unionSuffix, dpLevels, mbc == null ? 0 : mbc.numBuckets, hconf, writeId, stmtId, isMmTable, null, isInsertOverwrite);\n // create empty buckets if necessary\n if (!emptyBuckets.isEmpty()) {\n assert mbc != null;\n Utilities.createEmptyBuckets(hconf, emptyBuckets, mbc.isCompressed, mbc.tableInfo, reporter);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static TTransport getSSLSocket(String host, int port, int loginTimeout, String trustStorePath, String trustStorePassWord, String trustStoreType, String trustStoreAlgorithm, int maxMessageSize) throws TTransportException{\r\n TSSLTransportParameters params = new TSSLTransportParameters();\r\n String tStoreType = trustStoreType.isEmpty() ? KeyStore.getDefaultType() : trustStoreType;\r\n String tStoreAlgorithm = trustStoreAlgorithm.isEmpty() ? TrustManagerFactory.getDefaultAlgorithm() : trustStoreAlgorithm;\r\n params.setTrustStore(trustStorePath, trustStorePassWord, tStoreAlgorithm, tStoreType);\r\n params.requireClientAuth(true);\r\n return getSSLSocket(host, port, loginTimeout, params, maxMessageSize);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get the projection matrix for a surface seen by an eye of a viewer
\n * in a display config. (double version)
\n * @param disp Display config object
\n * @param viewer Viewer ID
\n * @param eye Eye ID
\n * @param surface Surface ID
\n * @param near Distance from viewpoint to near clipping plane - must be
\n * positive.
\n * @param far Distance from viewpoint to far clipping plane - must be positive
\n * and not equal to near, typically greater than near.
\n * @param flags Bitwise OR of matrix convention flags (see @ref MatrixFlags)
\n * @param matrix Output projection matrix: supply an array of 16
\n * (::OSVR_MATRIX_SIZE) doubles.
\n * @return OSVR_RETURN_FAILURE if invalid parameters were passed, in which case
\n * the output argument is unmodified.
\n * Original signature : OSVR_ReturnCode osvrClientGetViewerEyeSurfaceProjectionMatrixd(OSVR_DisplayConfig, OSVR_ViewerCount, OSVR_EyeCount, OSVR_SurfaceCount, double, double, OSVR_MatrixConventions, double*)\n */\npublic static native byte osvrClientGetViewerEyeSurfaceProjectionMatrixd(OsvrDisplayLibrary.OSVR_DisplayConfig disp, int viewer, byte eye, int surface, double near, double far, short flags, DoubleBuffer matrix);", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "/**\n * Method to get the remaining basic application information based on a filter for a requested page.\n *\n * @param expectedFilteredAuthorizedAppInfoList List of filtered authorized {@link ApplicationBasicInfo} instances.\n * @param authorizedUserTenantDomain Tenant domain.\n * @param authorizedUser Authorized user.\n * @param filter Application name filter.\n * @param offset Starting index of the count.\n * @param chunkSize Chunk size configured for DB fetching.\n * @param expectedAuthorizedAppInfoCount Total filtered authorized app info count needed to decide apps to be\n * displayed for a requested page.\n * @param totalFilteredSystemAppCount Count of all applications in the system for a matching filter.\n * @return List of remaining authorized {@link ApplicationBasicInfo} instances for pagination.\n * @throws IdentityApplicationManagementException Error in getting remaining basic application information.\n */\nprivate List getFilteredAuthorizedAppBasicInfo(List expectedFilteredAuthorizedAppInfoList, String authorizedUserTenantDomain, String authorizedUser, String filter, int offset, int chunkSize, int expectedAuthorizedAppInfoCount, int totalFilteredSystemAppCount) throws IdentityApplicationManagementException {\n ApplicationBasicInfo[] applicationBasicInfos;\n if (expectedAuthorizedAppInfoCount > chunkSize) {\n applicationBasicInfos = ApplicationManagementService.getInstance().getApplicationBasicInfo(authorizedUserTenantDomain, authorizedUser, filter, offset, chunkSize);\n offset += chunkSize;\n } else {\n applicationBasicInfos = ApplicationManagementService.getInstance().getApplicationBasicInfo(authorizedUserTenantDomain, authorizedUser, filter, offset, expectedAuthorizedAppInfoCount);\n offset += expectedAuthorizedAppInfoCount;\n }\n List authorizedAppBasicInfo = getAuthorizedApplicationBasicInfo(applicationBasicInfos, authorizedUser);\n if (authorizedAppBasicInfo.size() == expectedAuthorizedAppInfoCount) {\n expectedFilteredAuthorizedAppInfoList.addAll(authorizedAppBasicInfo);\n return expectedFilteredAuthorizedAppInfoList;\n } else if (authorizedAppBasicInfo.size() > expectedAuthorizedAppInfoCount) {\n expectedFilteredAuthorizedAppInfoList.addAll(authorizedAppBasicInfo.subList(0, expectedAuthorizedAppInfoCount));\n return expectedFilteredAuthorizedAppInfoList;\n } else {\n expectedFilteredAuthorizedAppInfoList.addAll(authorizedAppBasicInfo);\n if (log.isDebugEnabled()) {\n log.debug(\"No. of authorized app information found for user \" + authorizedUser + \" in tenant domain \" + authorizedUserTenantDomain + \": \" + expectedFilteredAuthorizedAppInfoList.size());\n }\n if (offset >= totalFilteredSystemAppCount) {\n return expectedFilteredAuthorizedAppInfoList;\n }\n expectedAuthorizedAppInfoCount = expectedAuthorizedAppInfoCount - authorizedAppBasicInfo.size();\n if (log.isDebugEnabled()) {\n log.debug(\"No. of remaining authorized app information needed to be fetched from the DB for user \" + authorizedUser + \" in tenant domain \" + authorizedUserTenantDomain + \": \" + expectedAuthorizedAppInfoCount);\n }\n return getFilteredAuthorizedAppBasicInfo(expectedFilteredAuthorizedAppInfoList, authorizedUserTenantDomain, authorizedUser, filter, offset, chunkSize, expectedAuthorizedAppInfoCount, totalFilteredSystemAppCount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public static Specification findSoggettoBy(String numeroDeterminazione, String numeroProtocolloAllegato, Long tipoAllegato, Boolean ordinanzaProtocollata, Boolean ordinanzeSollecitate, Long idStatoSentenza, Date dataNotifica, Date dataNotificaA, Long idStatoOrdinanza, Date dataSentenzaDa, Date dataSentenzaA, String tipoRicerca, VerbaleSearchParam parametriVerbale){\r\n return findSoggettoBy(numeroDeterminazione, numeroProtocolloAllegato, tipoAllegato, null, ordinanzaProtocollata, ordinanzeSollecitate, idStatoSentenza, dataNotifica, dataNotificaA, idStatoOrdinanza, dataSentenzaDa, dataSentenzaA, tipoRicerca, false, parametriVerbale, null, null);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Puts information into the schema information hashtables.\n *\n * @param id schema id (uuid)\n * @param version schema version\n * @param name schema name\n * @param mds MetadataSchema object with details of XML schema info\n * @param schemaDir path name of schema directory\n * @param sugg SchemaSuggestions object\n * @param adElems List of autodetect XML elements (as JDOM Elements)\n * @param xfMap Map containing XML localized info files (as Jeeves XmlFiles)\n * @param isPlugin true if schema is a plugin schema\n * @param schemaLocation namespaces and URLs of their xsds\n * @param convElems List of elements in conversion file\n * @param dependElems List of depend XML elements (as JDOM Elements)\n */\nprivate void putSchemaInfo(String name, String id, String version, MetadataSchema mds, Path schemaDir, SchemaSuggestions sugg, List adElems, Map xfMap, boolean isPlugin, String schemaLocation, List convElems, List dependElems) {\n Schema schema = new Schema();\n schema.setId(id);\n schema.setVersion(version);\n schema.setMetadataSchema(mds);\n schema.setDir(schemaDir);\n schema.setSuggestions(sugg);\n schema.setAutodetectElements(adElems);\n schema.setInfo(xfMap);\n schema.setPluginSchema(isPlugin);\n schema.setSchemaLocation(schemaLocation);\n schema.setConversionElements(convElems);\n schema.setDependElements(dependElems);\n hmSchemas.put(name, schema);\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static DepositAccountInterestRateChartData withTemplate(DepositAccountInterestRateChartData interestRateChartData, Collection periodTypes, final Collection entityTypeOptions, final Collection attributeNameOptions, final Collection conditionTypeOptions, final Collection incentiveTypeOptions, final Collection genderOptions, final Collection clientTypeOptions, final Collection clientClassificationOptions) {\n return new DepositAccountInterestRateChartData(interestRateChartData.id, interestRateChartData.name, interestRateChartData.description, interestRateChartData.fromDate, interestRateChartData.endDate, interestRateChartData.isPrimaryGroupingByAmount, interestRateChartData.accountId, interestRateChartData.accountNumber, interestRateChartData.chartSlabs, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private SqlResult query0(QueryId queryId, String schema, String sql, List args, long timeout, int pageSize, SqlExpectedResultType expectedResultType, SqlSecurityContext securityContext){\r\n if (sql == null || sql.isEmpty()) {\r\n throw QueryException.error(\"SQL statement cannot be empty.\");\r\n }\r\n List args0 = new ArrayList<>(args);\r\n if (timeout < 0) {\r\n throw QueryException.error(\"Timeout cannot be negative: \" + timeout);\r\n }\r\n if (pageSize <= 0) {\r\n throw QueryException.error(\"Page size must be positive: \" + pageSize);\r\n }\r\n SqlPlan plan = prepare(schema, sql, args0, expectedResultType);\r\n if (securityContext.isSecurityEnabled()) {\r\n plan.checkPermissions(securityContext);\r\n }\r\n return plan.execute(queryId, args0, timeout);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Copy a part of an image to a texture 2d.\n * @param dest The destination image, where the source will be copied\n * @param src The source image that contains the data to copy\n * @param destX First pixel of the destination image from where the src image will be drawn (x component)\n * @param destY First pixel of the destination image from where the src image will be drawn (y component)\n * @param srcX First pixel to copy (x component)\n * @param srcY First pixel to copy (y component)\n * @param areaW Width of the area to copy\n * @param areaH Height of the area to copy\n */\npublic void modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH) {\n final int textureUnitIndex = 0;\n try {\n setTexture(textureUnitIndex, dest);\n } catch (TextureUnitException exception) {\n throw new RuntimeException(\"Renderer lacks texture units?\");\n }\n if (caps.contains(Caps.OpenGLES20) && src.getFormat() != dest.getImage().getFormat()) {\n logger.log(Level.WARNING, \"Incompatible texture subimage\");\n }\n int target = convertTextureType(dest.getType(), src.getMultiSamples(), -1);\n texUtil.uploadSubTexture(target, src, 0, destX, destY, srcX, srcY, areaW, areaH, linearizeSrgbImages);\n}", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, Long size, Map details) {\n UsageEventVO usageEventVO = new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size);\n s_usageEventDao.persist(usageEventVO);\n if (MapUtils.isNotEmpty(details)) {\n s_usageEventDao.saveDetails(usageEventVO.getId(), details);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static LoanScheduleModel from(final List periods, final ApplicationCurrency applicationCurrency, final int loanTermInDays, final Money principalDisbursed, final BigDecimal totalPrincipalExpected, final BigDecimal totalPrincipalPaid, final BigDecimal totalInterestCharged, final BigDecimal totalFeeChargesCharged, final BigDecimal totalPenaltyChargesCharged, final BigDecimal totalRepaymentExpected, final BigDecimal totalOutstanding) {\n return new LoanScheduleModel(periods, applicationCurrency, loanTermInDays, principalDisbursed, totalPrincipalExpected, totalPrincipalPaid, totalInterestCharged, totalFeeChargesCharged, totalPenaltyChargesCharged, totalRepaymentExpected, totalOutstanding);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private Partition constructPartition(JobContext context, OutputJobInfo jobInfo, String partLocnRoot, String dynPartPath, Map partKVs, HCatSchema outputSchema, Map params, Table table, FileSystem fs, HiveConf conf, HdfsUtils.HadoopFileStatus status) throws IOException{\r\n Partition partition = new Partition();\r\n partition.setDbName(table.getDbName());\r\n partition.setTableName(table.getTableName());\r\n partition.setSd(new StorageDescriptor(table.getTTable().getSd()));\r\n List fields = new ArrayList();\r\n for (HCatFieldSchema fieldSchema : outputSchema.getFields()) {\r\n fields.add(HCatSchemaUtils.getFieldSchema(fieldSchema));\r\n }\r\n partition.getSd().setCols(fields);\r\n partition.setValues(FileOutputFormatContainer.getPartitionValueList(table, partKVs));\r\n partition.setParameters(params);\r\n Path partPath;\r\n if (customDynamicLocationUsed) {\r\n partPath = new Path(dynPartPath);\r\n } else if (!dynamicPartitioningUsed && Boolean.parseBoolean((String) table.getProperty(\"EXTERNAL\")) && jobInfo.getLocation() != null && jobInfo.getLocation().length() > 0) {\r\n String jobLocation = jobInfo.getLocation();\r\n String finalLocn = jobLocation.replaceAll(Path.SEPARATOR + SCRATCH_DIR_NAME + \"\\\\d\\\\.?\\\\d+\", \"\");\r\n partPath = new Path(finalLocn);\r\n } else {\r\n partPath = new Path(partLocnRoot);\r\n FileSystem partFs = partPath.getFileSystem(context.getConfiguration());\r\n int i = 0;\r\n for (FieldSchema partKey : table.getPartitionKeys()) {\r\n if (i++ != 0) {\r\n partFs.mkdirs(partPath);\r\n HdfsUtils.setFullFileStatus(conf, status, status.getFileStatus().getGroup(), fs, partPath, false);\r\n }\r\n partPath = constructPartialPartPath(partPath, partKey.getName().toLowerCase(), partKVs);\r\n }\r\n }\r\n FileSystem partFs = partPath.getFileSystem(context.getConfiguration());\r\n partFs.mkdirs(partPath);\r\n if (dynamicPartitioningUsed) {\r\n String dynamicPartitionDestination = getFinalDynamicPartitionDestination(table, partKVs, jobInfo);\r\n if (harProcessor.isEnabled()) {\r\n harProcessor.exec(context, partition, partPath);\r\n partition.getSd().setLocation(harProcessor.getProcessedLocation(new Path(dynamicPartitionDestination)));\r\n } else {\r\n partition.getSd().setLocation(dynamicPartitionDestination);\r\n }\r\n } else {\r\n partition.getSd().setLocation(partPath.toString());\r\n }\r\n return partition;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean addNetworkRules(String vmName, String vmId, String guestIp, String signature, String seqno, String vifMacAddress, String rules, String vifDeviceName, String bridgeName) throws XmlRpcException {\n if (!_canBridgeFirewall) {\n return false;\n }\n String newRules = rules.replace(\" \", \";\");\n return OvmSecurityGroup.addNetworkRules(_conn, vmName, vmId, guestIp, signature, seqno, vifMacAddress, newRules, vifDeviceName, bridgeName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private boolean removeMatch(final AccumulateNode accNode, final Accumulate accumulate, final RightTuple rightTuple, final LeftTuple match, final ReteEvaluator reteEvaluator, final AccumulateMemory am, final BaseAccumulation accctx, final boolean reaccumulate){\r\n LeftTuple leftParent = match.getLeftParent();\r\n RightTuple rightParent = match.getRightParent();\r\n match.unlinkFromLeftParent();\r\n match.unlinkFromRightParent();\r\n FactHandle handle = rightTuple.getFactHandle();\r\n LeftTuple tuple = leftParent;\r\n if (accNode.isRightInputIsRiaNode()) {\r\n tuple = (LeftTuple) rightTuple;\r\n handle = rightTuple.getFactHandleForEvaluation();\r\n }\r\n boolean reversed = accumulate.tryReverse(am.workingMemoryContext, accctx, tuple, handle, match, reteEvaluator);\r\n if (!reversed) {\r\n reaccumulateForLeftTuple(accNode, accumulate, leftParent, rightParent, match, reteEvaluator, am, accctx, reaccumulate);\r\n }\r\n return reversed;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String buildFilename(final IVariables variables, final String transformnr, final String partnr, final String splitnr, final boolean beamContext, final String transformId, final int bundleNr, final boolean ziparchive, final boolean showSamples) {\n String realFileName = variables.resolve(fileName);\n String realExtension = variables.resolve(extension);\n return buildFilename(realFileName, realExtension, transformnr, partnr, splitnr, beamContext, transformId, bundleNr, new Date(), ziparchive, showSamples);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * @param part Partition.\n * @param key Key for the event.\n * @param evtNodeId Node ID.\n * @param owner Possible surrounding lock.\n * @param type Event type.\n * @param newVal New value.\n * @param hasNewVal Whether new value is present or not.\n * @param oldVal Old value.\n * @param hasOldVal Whether old value is present or not.\n * @param cloClsName Closure class name.\n * @param taskName Task name.\n */\npublic void addEvent(int part, KeyCacheObject key, UUID evtNodeId, @Nullable GridCacheMvccCandidate owner, int type, @Nullable CacheObject newVal, boolean hasNewVal, CacheObject oldVal, boolean hasOldVal, String cloClsName, String taskName, boolean keepBinary) {\n IgniteInternalTx tx = owner == null ? null : cctx.tm().tx(owner.version());\n addEvent(part, key, evtNodeId, tx, null, owner == null ? null : owner.version(), type, newVal, hasNewVal, oldVal, hasOldVal, cloClsName, taskName, keepBinary);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private void switchOnDoBetaNode(NetworkNode node, TupleSets trgTuples, ReteEvaluator reteEvaluator, TupleSets srcTuples, TupleSets stagedLeftTuples, LeftTupleSinkNode sink, BetaMemory bm, AccumulateMemory am){\r\n if (log.isTraceEnabled()) {\r\n int offset = getOffset(node);\r\n log.trace(\"{} rightTuples {}\", indent(offset), bm.getStagedRightTuples().toStringSizes());\r\n }\r\n switch(node.getType()) {\r\n case NodeTypeEnums.JoinNode:\r\n {\r\n pJoinNode.doNode((JoinNode) node, sink, bm, reteEvaluator, srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.NotNode:\r\n {\r\n pNotNode.doNode((NotNode) node, sink, bm, reteEvaluator, srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.ExistsNode:\r\n {\r\n pExistsNode.doNode((ExistsNode) node, sink, bm, reteEvaluator, srcTuples, trgTuples, stagedLeftTuples);\r\n break;\r\n }\r\n case NodeTypeEnums.AccumulateNode:\r\n {\r\n AccumulateNode accumulateNode = (AccumulateNode) node;\r\n if (accumulateNode.getAccumulate().isGroupBy()) {\r\n pGroupByNode.doNode(accumulateNode, sink, am, reteEvaluator, srcTuples, trgTuples, stagedLeftTuples);\r\n } else {\r\n pAccNode.doNode(accumulateNode, sink, am, reteEvaluator, srcTuples, trgTuples, stagedLeftTuples);\r\n }\r\n break;\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Uncompresses part of the stream. RGs can overlap, so we cannot just go and decompress\n * and remove what we have returned. We will keep iterator as a \"hint\" point.\n * @param baseOffset Absolute offset of boundaries and ranges relative to file, for cache keys.\n * @param start Ordered ranges containing file data. Helpful if they point close to cOffset.\n * @param cOffset Start offset to decompress.\n * @param endCOffset End offset to decompress; estimate, partial CBs will be ignored.\n * @param csd Stream data, to add the results.\n * @param unlockUntilCOffset The offset until which the buffers can be unlocked in cache, as\n * they will not be used in future calls (see the class comment in\n * EncodedReaderImpl about refcounts).\n * @return Last buffer cached during decompression. Cache buffers are never removed from\n * the master list, so they are safe to keep as iterators for various streams.\n */\npublic DiskRangeList readEncodedStream(long baseOffset, DiskRangeList start, long cOffset, long endCOffset, ColumnStreamData csd, long unlockUntilCOffset, long streamOffset, IdentityHashMap toRelease) throws IOException {\n if (csd.getCacheBuffers() == null) {\n csd.setCacheBuffers(new ArrayList());\n } else {\n csd.getCacheBuffers().clear();\n }\n if (cOffset == endCOffset)\n return null;\n List toDecompress = null;\n List badEstimates = null;\n List toReleaseCopies = null;\n if (isCompressed) {\n toReleaseCopies = new ArrayList<>();\n toDecompress = new ArrayList<>();\n badEstimates = new ArrayList<>();\n }\n // 1. Find our bearings in the stream. Normally, iter will already point either to where we\n // want to be, or just before. However, RGs can overlap due to encoding, so we may have\n // to return to a previous block.\n DiskRangeList current = findExactPosition(start, cOffset);\n if (isTracingEnabled) {\n LOG.trace(\"Starting read for [\" + cOffset + \",\" + endCOffset + \") at \" + current);\n }\n trace.logStartRead(current);\n CacheChunk lastUncompressed = null;\n // 2. Go thru the blocks; add stuff to results and prepare the decompression work (see below).\n try {\n lastUncompressed = isCompressed ? prepareRangesForCompressedRead(cOffset, endCOffset, streamOffset, unlockUntilCOffset, current, csd, toRelease, toReleaseCopies, toDecompress, badEstimates) : prepareRangesForUncompressedRead(cOffset, endCOffset, streamOffset, unlockUntilCOffset, current, csd);\n } catch (Exception ex) {\n LOG.error(\"Failed \" + (isCompressed ? \"\" : \"un\") + \"compressed read; cOffset \" + cOffset + \", endCOffset \" + endCOffset + \", streamOffset \" + streamOffset + \", unlockUntilCOffset \" + unlockUntilCOffset + \"; ranges passed in \" + RecordReaderUtils.stringifyDiskRanges(start) + \"; ranges passed to prepare \" + // Don't log exception here.\n RecordReaderUtils.stringifyDiskRanges(current));\n throw (ex instanceof IOException) ? (IOException) ex : new IOException(ex);\n }\n // 2.5. Remember the bad estimates for future reference.\n if (badEstimates != null && !badEstimates.isEmpty()) {\n // Relies on the fact that cache does not actually store these.\n DiskRange[] cacheKeys = badEstimates.toArray(new DiskRange[badEstimates.size()]);\n long[] result = cacheWrapper.putFileData(fileKey, cacheKeys, null, baseOffset, tag);\n // We don't expect conflicts from bad estimates.\n assert result == null;\n }\n if (toDecompress == null || toDecompress.isEmpty()) {\n releaseBuffers(toReleaseCopies, false);\n // Nothing to do.\n return lastUncompressed;\n }\n // 3. Allocate the buffers, prepare cache keys.\n // At this point, we have read all the CBs we need to read. cacheBuffers contains some cache\n // data and some unallocated membufs for decompression. toDecompress contains all the work we\n // need to do, and each item points to one of the membufs in cacheBuffers as target. The iter\n // has also been adjusted to point to these buffers instead of compressed data for the ranges.\n MemoryBuffer[] targetBuffers = new MemoryBuffer[toDecompress.size()];\n DiskRange[] cacheKeys = new DiskRange[toDecompress.size()];\n int ix = 0;\n for (ProcCacheChunk chunk : toDecompress) {\n // Relies on the fact that cache does not actually store these.\n cacheKeys[ix] = chunk;\n targetBuffers[ix] = chunk.getBuffer();\n ++ix;\n }\n boolean isAllocated = false;\n try {\n allocateMultiple(targetBuffers, bufferSize);\n isAllocated = true;\n } finally {\n // toDecompress/targetBuffers contents are actually already added to some structures that\n // will be cleaned up on error. Remove the unallocated buffers; keep the cached buffers in.\n if (!isAllocated) {\n // Inefficient - this only happens during cleanup on errors.\n for (MemoryBuffer buf : targetBuffers) {\n csd.getCacheBuffers().remove(buf);\n }\n for (ProcCacheChunk chunk : toDecompress) {\n chunk.buffer = null;\n }\n }\n }\n // 4. Now decompress (or copy) the data into cache buffers.\n int decompressedIx = 0;\n try {\n while (decompressedIx < toDecompress.size()) {\n ProcCacheChunk chunk = toDecompress.get(decompressedIx);\n ByteBuffer dest = chunk.getBuffer().getByteBufferRaw();\n if (chunk.isOriginalDataCompressed) {\n boolean isOk = false;\n try {\n decompressChunk(chunk.originalData, codec, dest);\n isOk = true;\n } finally {\n if (!isOk) {\n isCodecFailure = true;\n }\n }\n } else {\n copyUncompressedChunk(chunk.originalData, dest);\n }\n if (isTracingEnabled) {\n LOG.trace(\"Locking \" + chunk.getBuffer() + \" due to reuse (after decompression)\");\n }\n // After we set originalData to null, we incref the buffer and the cleanup would decref it.\n // Note that this assumes the failure during incref means incref didn't occur.\n try {\n cacheWrapper.reuseBuffer(chunk.getBuffer());\n } finally {\n chunk.originalData = null;\n }\n ++decompressedIx;\n }\n } finally {\n // This will only execute on error. Deallocate the remaining allocated buffers explicitly.\n // The ones that were already incref-ed will be cleaned up with the regular cache buffers.\n while (decompressedIx < toDecompress.size()) {\n ProcCacheChunk chunk = toDecompress.get(decompressedIx);\n csd.getCacheBuffers().remove(chunk.getBuffer());\n try {\n cacheWrapper.getAllocator().deallocate(chunk.getBuffer());\n } catch (Throwable t) {\n LOG.error(\"Ignoring the cleanup error after another error\", t);\n }\n chunk.setBuffer(null);\n ++decompressedIx;\n }\n }\n // 5. Release the copies we made directly to the cleaner.\n releaseBuffers(toReleaseCopies, false);\n // 6. Finally, put uncompressed data to cache.\n if (fileKey != null) {\n long[] collisionMask = cacheWrapper.putFileData(fileKey, cacheKeys, targetBuffers, baseOffset, tag);\n processCacheCollisions(collisionMask, toDecompress, targetBuffers, csd.getCacheBuffers());\n }\n // 7. It may happen that we know we won't use some cache buffers anymore (the alternative\n // is that we will use the same buffers for other streams in separate calls).\n // Release initial refcounts.\n for (ProcCacheChunk chunk : toDecompress) {\n ponderReleaseInitialRefcount(unlockUntilCOffset, streamOffset, chunk);\n }\n return lastUncompressed;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void printSequenceAlignmentWeb(StringBuilder s, int counter, String idFormat, boolean seqIndexPre, String seqIndexFormatPre, boolean seqIndexPost, String seqIndexFormatPost, int start, int end){\r\n AlignedSequence as1 = list.get(0), as2 = list.get(1), as = list.get(counter - 1);\r\n if (idFormat != null) {\r\n s.append(String.format(idFormat, as.getAccession()));\r\n }\r\n if (seqIndexPre) {\r\n s.append(String.format(seqIndexFormatPre, as.getSequenceIndexAt(start)));\r\n }\r\n String mySeq = as.getSubSequence(start, end).getSequenceAsString();\r\n String s1 = as1.getSubSequence(start, end).getSequenceAsString();\r\n String s2 = as2.getSubSequence(start, end).getSequenceAsString();\r\n for (int i = 0; i < s1.length(); i++) {\r\n if (i >= s2.length() || i >= mySeq.length())\r\n break;\r\n char c1 = s1.charAt(i);\r\n char c2 = s2.charAt(i);\r\n char c = mySeq.charAt(i);\r\n s.append(IOUtils.getPDBCharacter(true, c1, c2, isSimilar(c1, c2), c));\r\n }\r\n if (seqIndexPost) {\r\n s.append(String.format(seqIndexFormatPost, as.getSequenceIndexAt(end)));\r\n }\r\n s.append(String.format(\"%n\"));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "TungstenFabricRuleResponse addTungstenPolicyRule(final long zoneId, final String policyUuid, final String action, final String direction, final String protocol, final String srcNetwork, final String srcIpPrefix, final int srcIpPrefixLen, final int srcStartPort, final int srcEndPort, final String destNetwork, final String destIpPrefix, final int destIpPrefixLen, final int destStartPort, final int destEndPort);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static EnumerableMatch create(RelNode input, RelDataType rowType, RexNode pattern, boolean strictStart, boolean strictEnd, Map patternDefinitions, Map measures, RexNode after, Map> subsets, boolean allRows, ImmutableBitSet partitionKeys, RelCollation orderKeys, @Nullable RexNode interval){\r\n final RelOptCluster cluster = input.getCluster();\r\n final RelTraitSet traitSet = cluster.traitSetOf(EnumerableConvention.INSTANCE);\r\n return new EnumerableMatch(cluster, traitSet, input, rowType, pattern, strictStart, strictEnd, patternDefinitions, measures, after, subsets, allRows, partitionKeys, orderKeys, interval);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Prepares network (for non-standard virtual switch) for the VM NIC based on the parameters.\n * Can create a new portgroup or update an existing.\n * @return Pair of network's ManagedObjectReference and name\n * @throws Exception\n */\npublic static Pair prepareNetwork(String physicalNetwork, String namePrefix, HostMO hostMo, String vlanId, String secondaryvlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts, String gateway, boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType, Map vsmCredentials, Map details, String netName) throws Exception {\n ManagedObjectReference morNetwork = null;\n VmwareContext context = hostMo.getContext();\n ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter();\n DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);\n DistributedVirtualSwitchMO dvSwitchMo = null;\n ManagedObjectReference morEthernetPortProfile = null;\n String ethPortProfileName = null;\n ManagedObjectReference morDvSwitch = null;\n String dvSwitchName = null;\n boolean bWaitPortGroupReady = false;\n boolean createGCTag = false;\n String vcApiVersion;\n String minVcApiVersionSupportingAutoExpand;\n boolean autoExpandSupported;\n String networkName;\n Integer vid = null;\n // secondary pvlan id\n Integer spvlanid = null;\n /**\n * This is the list of BroadcastDomainTypes we can actually\n * prepare networks for in this function.\n */\n BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan, BroadcastDomainType.NSX };\n if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {\n throw new InvalidParameterValueException(\"BroadcastDomainType \" + broadcastDomainType + \" it not supported on a VMWare hypervisor at this time.\");\n }\n if (broadcastDomainType == BroadcastDomainType.Lswitch) {\n if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {\n throw new InvalidParameterValueException(\"Nexus Distributed Virtualswitch is not supported with BroadcastDomainType \" + broadcastDomainType);\n }\n /**\n * Nicira NVP requires all vms to be connected to a single port-group.\n * A unique vlan needs to be set per port. This vlan is specific to\n * this implementation and has no reference to other vlans in CS\n */\n // FIXME Should be set via a configuration item in CS\n networkName = \"br-int\";\n // No doubt about this, depending on vid=null to avoid lots of code below\n vid = null;\n } else {\n if (vlanId != null) {\n vlanId = vlanId.replace(\"vlan://\", \"\");\n }\n networkName = composeCloudNetworkName(namePrefix, vlanId, secondaryvlanId, networkRateMbps, physicalNetwork);\n if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId) && !StringUtils.containsAny(vlanId, \",-\")) {\n createGCTag = true;\n vid = Integer.parseInt(vlanId);\n }\n if (vlanId != null && StringUtils.containsAny(vlanId, \",-\")) {\n createGCTag = true;\n }\n if (secondaryvlanId != null) {\n spvlanid = Integer.parseInt(secondaryvlanId);\n }\n }\n if (vSwitchType == VirtualSwitchType.VMwareDistributedVirtualSwitch) {\n vcApiVersion = getVcenterApiVersion(context);\n minVcApiVersionSupportingAutoExpand = \"5.0\";\n autoExpandSupported = isFeatureSupportedInVcenterApiVersion(vcApiVersion, minVcApiVersionSupportingAutoExpand);\n dvSwitchName = physicalNetwork;\n // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types\n // and switch types.\n if (dvSwitchName == null) {\n LOGGER.warn(\"Detected null dvSwitch. Defaulting to dvSwitch0\");\n dvSwitchName = \"dvSwitch0\";\n }\n morDvSwitch = dataCenterMo.getDvSwitchMor(dvSwitchName);\n if (morDvSwitch == null) {\n String msg = \"Unable to find distributed vSwitch \" + dvSwitchName;\n LOGGER.error(msg);\n throw new Exception(msg);\n }\n dvSwitchMo = new DistributedVirtualSwitchMO(context, morDvSwitch);\n String dvSwitchVersion = dvSwitchMo.getDVSProductVersion(morDvSwitch);\n LOGGER.debug(String.format(\"Found distributed vSwitch: %s with product version: %s\", dvSwitchName, dvSwitchVersion));\n if (broadcastDomainType == BroadcastDomainType.Lswitch) {\n if (!dataCenterMo.hasDvPortGroup(networkName)) {\n throw new InvalidParameterValueException(\"NVP integration port-group \" + networkName + \" does not exist on the DVS \" + dvSwitchName);\n }\n bWaitPortGroupReady = false;\n } else if (BroadcastDomainType.NSX == broadcastDomainType && Objects.nonNull(netName)) {\n networkName = netName;\n bWaitPortGroupReady = false;\n } else {\n boolean dvSwitchSupportNewPolicies = (isFeatureSupportedInVcenterApiVersion(vcApiVersion, MINIMUM_VCENTER_API_VERSION_WITH_DVS_NEW_POLICIES_SUPPORT) && isVersionEqualOrHigher(dvSwitchVersion, MINIMUM_DVS_VERSION_WITH_NEW_POLICIES_SUPPORT));\n DVSTrafficShapingPolicy shapingPolicy = getDVSShapingPolicy(networkRateMbps);\n DVSSecurityPolicy secPolicy = createDVSSecurityPolicy(details);\n DVSMacManagementPolicy macManagementPolicy = createDVSMacManagementPolicy(details);\n // First, if both vlan id and pvlan id are provided, we need to\n // reconfigure the DVSwitch to have a tuple of\n // type isolated.\n String pvlanType = MapUtils.isNotEmpty(details) ? details.get(NetworkOffering.Detail.pvlanType) : null;\n if (vid != null && spvlanid != null) {\n setupPVlanPair(dvSwitchMo, morDvSwitch, vid, spvlanid, pvlanType);\n }\n VMwareDVSPortgroupPolicy portGroupPolicy = null;\n // Next, create the port group. For this, we need to create a VLAN spec.\n createPortGroup(physicalNetwork, networkName, vlanId, vid, spvlanid, dataCenterMo, shapingPolicy, secPolicy, macManagementPolicy, portGroupPolicy, dvSwitchMo, numPorts, autoExpandSupported, dvSwitchSupportNewPolicies);\n bWaitPortGroupReady = true;\n }\n } else if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {\n ethPortProfileName = physicalNetwork;\n // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types\n // and switch types.\n if (ethPortProfileName == null) {\n LOGGER.warn(\"Detected null ethrenet port profile. Defaulting to epp0.\");\n ethPortProfileName = \"epp0\";\n }\n morEthernetPortProfile = dataCenterMo.getDvPortGroupMor(ethPortProfileName);\n if (morEthernetPortProfile == null) {\n String msg = \"Unable to find Ethernet port profile \" + ethPortProfileName;\n LOGGER.error(msg);\n throw new Exception(msg);\n } else {\n LOGGER.info(\"Found Ethernet port profile \" + ethPortProfileName);\n }\n long averageBandwidth = 0L;\n if (networkRateMbps != null && networkRateMbps.intValue() > 0) {\n averageBandwidth = networkRateMbps.intValue() * 1024L * 1024L;\n }\n // We chose 50% higher allocation than average bandwidth.\n // TODO(sateesh): Optionally let user specify the peak coefficient\n long peakBandwidth = (long) (averageBandwidth * 1.5);\n // TODO(sateesh): Optionally let user specify the burst coefficient\n long burstSize = 5 * averageBandwidth / 8;\n if (vsmCredentials != null) {\n LOGGER.info(\"Stocking credentials of Nexus VSM\");\n context.registerStockObject(\"vsmcredentials\", vsmCredentials);\n }\n if (!dataCenterMo.hasDvPortGroup(networkName)) {\n LOGGER.info(\"Port profile \" + networkName + \" not found.\");\n createPortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize, gateway, configureVServiceInNexus);\n bWaitPortGroupReady = true;\n } else {\n LOGGER.info(\"Port profile \" + networkName + \" found.\");\n updatePortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize);\n }\n }\n // Wait for dvPortGroup on vCenter\n if (bWaitPortGroupReady)\n morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs);\n else\n morNetwork = dataCenterMo.getDvPortGroupMor(networkName);\n if (morNetwork == null) {\n String msg = \"Failed to create guest network \" + networkName;\n LOGGER.error(msg);\n throw new Exception(msg);\n }\n if (createGCTag) {\n NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);\n networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, \"true\");\n LOGGER.debug(\"Added custom field : \" + CustomFieldConstants.CLOUD_GC_DVP);\n }\n return new Pair(morNetwork, networkName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Classifies filters according to where they should be processed. They\n * either stay where they are, are pushed to the join (if they originated\n * from above the join), or are pushed to one of the children. Filters that\n * are pushed are added to list passed in as input parameters.\n *\n * @param joinRel join node\n * @param filters filters to be classified\n * @param pushInto whether filters can be pushed into the join\n * @param pushLeft true if filters can be pushed to the left\n * @param pushRight true if filters can be pushed to the right\n * @param joinFilters list of filters to push to the join\n * @param leftFilters list of filters to push to the left child\n * @param rightFilters list of filters to push to the right child\n * @return whether at least one filter was pushed\n */\npublic static boolean classifyFilters(RelNode joinRel, List filters, boolean pushInto, boolean pushLeft, boolean pushRight, List joinFilters, List leftFilters, List rightFilters) {\n RexBuilder rexBuilder = joinRel.getCluster().getRexBuilder();\n List joinFields = joinRel.getRowType().getFieldList();\n // joinRel.getSystemFieldList().size();\n final int nSysFields = 0;\n final List leftFields = joinRel.getInputs().get(0).getRowType().getFieldList();\n final int nFieldsLeft = leftFields.size();\n final List rightFields = joinRel.getInputs().get(1).getRowType().getFieldList();\n final int nFieldsRight = rightFields.size();\n final int nTotalFields = nFieldsLeft + nFieldsRight;\n // set the reference bitmaps for the left and right children\n ImmutableBitSet leftBitmap = ImmutableBitSet.range(nSysFields, nSysFields + nFieldsLeft);\n ImmutableBitSet rightBitmap = ImmutableBitSet.range(nSysFields + nFieldsLeft, nTotalFields);\n final List filtersToRemove = new ArrayList<>();\n for (RexNode filter : filters) {\n final InputFinder inputFinder = InputFinder.analyze(filter);\n final ImmutableBitSet inputBits = inputFinder.build();\n // REVIEW - are there any expressions that need special handling\n // and therefore cannot be pushed?\n if (pushLeft && leftBitmap.contains(inputBits)) {\n // ignore filters that always evaluate to true\n if (!filter.isAlwaysTrue()) {\n // adjust the field references in the filter to reflect\n // that fields in the left now shift over by the number\n // of system fields\n final RexNode shiftedFilter = shiftFilter(nSysFields, nSysFields + nFieldsLeft, -nSysFields, rexBuilder, joinFields, nTotalFields, leftFields, filter);\n leftFilters.add(shiftedFilter);\n }\n filtersToRemove.add(filter);\n } else if (pushRight && rightBitmap.contains(inputBits)) {\n if (!filter.isAlwaysTrue()) {\n // adjust the field references in the filter to reflect\n // that fields in the right now shift over to the left\n final RexNode shiftedFilter = shiftFilter(nSysFields + nFieldsLeft, nTotalFields, -(nSysFields + nFieldsLeft), rexBuilder, joinFields, nTotalFields, rightFields, filter);\n rightFilters.add(shiftedFilter);\n }\n filtersToRemove.add(filter);\n } else {\n // If the filter can't be pushed to either child, we may push them into the join\n if (pushInto) {\n if (!joinFilters.contains(filter)) {\n joinFilters.add(filter);\n }\n filtersToRemove.add(filter);\n }\n }\n }\n // Remove filters after the loop, to prevent concurrent modification.\n if (!filtersToRemove.isEmpty()) {\n filters.removeAll(filtersToRemove);\n }\n // Did anything change?\n return !filtersToRemove.isEmpty();\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public ManagedObjectReference prepareManagedStorage(VmwareContext context, VmwareHypervisorHost hyperHost, String diskUuid, String iScsiName, String storageHost, int storagePort, String volumeName, String chapInitiatorUsername, String chapInitiatorSecret, String chapTargetUsername, String chapTargetSecret, long size, Command cmd) throws Exception {\n ManagedObjectReference morDs = prepareManagedDatastore(context, hyperHost, diskUuid, iScsiName, storageHost, storagePort, chapInitiatorUsername, chapInitiatorSecret, chapTargetUsername, chapTargetSecret);\n DatastoreMO dsMo = new DatastoreMO(hostService.getServiceContext(null), morDs);\n String volumeDatastorePath = String.format(\"[%s] %s.vmdk\", dsMo.getName(), volumeName != null ? volumeName : dsMo.getName());\n if (!dsMo.fileExists(volumeDatastorePath)) {\n createVmdk(cmd, dsMo, volumeDatastorePath, size);\n }\n return morDs;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "@Nullable\npublic static SqlOperator lookupRoutine(SqlOperatorTable opTab, RelDataTypeFactory typeFactory, SqlIdentifier funcName, List argTypes, @Nullable List argNames, @Nullable SqlFunctionCategory category, SqlSyntax syntax, SqlKind sqlKind, SqlNameMatcher nameMatcher, boolean coerce){\r\n Iterator list = lookupSubjectRoutines(opTab, typeFactory, funcName, argTypes, argNames, syntax, sqlKind, category, nameMatcher, coerce);\r\n if (list.hasNext()) {\r\n return list.next();\r\n }\r\n return null;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ExprViewItem expr(Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Predicate9 predicate){\r\n return new Expr9ViewItemImpl<>(var1, var2, var3, var4, var5, var6, var7, var8, var9, new Predicate9.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Imports an existing volume for a VM into database. Useful while ingesting an unmanaged VM.\n * @param type Type of the volume - ROOT, DATADISK, etc\n * @param name Name of the volume\n * @param offering DiskOffering for the volume\n * @param sizeInBytes size of the volume in bytes\n * @param minIops minimum IOPS for the disk, if not passed DiskOffering value will be used\n * @param maxIops maximum IOPS for the disk, if not passed DiskOffering value will be used\n * @param vm VirtualMachine this volume is attached to\n * @param template Template of the VM of the volume\n * @param owner owner Account for the volume\n * @param deviceId device ID of the virtual disk\n * @param poolId ID of pool in which volume is stored\n * @param path image path of the volume\n * @param chainInfo chain info for the volume. Hypervisor specific.\n * @return DiskProfile of imported volume\n */\nDiskProfile importVolume(Type type, String name, DiskOffering offering, Long sizeInBytes, Long minIops, Long maxIops, Long zoneId, HypervisorType hypervisorType, VirtualMachine vm, VirtualMachineTemplate template, Account owner, Long deviceId, Long poolId, String path, String chainInfo);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * @param lsnrCol Listeners to notify.\n * @param key Key.\n * @param newVal New value.\n * @param oldVal Old value.\n * @param internal Internal entry (internal key or not user cache),\n * @param partId Partition.\n * @param primary {@code True} if called on primary node.\n * @param preload Whether update happened during preloading.\n * @param updateCntr Update counter.\n * @param topVer Topology version.\n * @param fut Dht atomic future.\n * @throws IgniteCheckedException In case of error.\n */\npublic void onEntryUpdated(Map lsnrCol, KeyCacheObject key, CacheObject newVal, CacheObject oldVal, boolean internal, int partId, boolean primary, boolean preload, long updateCntr, @Nullable GridDhtAtomicAbstractUpdateFuture fut, AffinityTopologyVersion topVer) throws IgniteCheckedException {\n assert key != null;\n assert lsnrCol != null;\n boolean hasNewVal = newVal != null;\n boolean hasOldVal = oldVal != null;\n if (!hasNewVal && !hasOldVal) {\n skipUpdateEvent(lsnrCol, key, partId, updateCntr, primary, topVer);\n return;\n }\n EventType evtType = !hasNewVal ? REMOVED : !hasOldVal ? CREATED : UPDATED;\n boolean initialized = false;\n boolean recordIgniteEvt = primary && !internal && cctx.events().isRecordable(EVT_CACHE_QUERY_OBJECT_READ);\n for (CacheContinuousQueryListener lsnr : lsnrCol.values()) {\n if (preload && !lsnr.notifyExisting() || lsnr.isPrimaryOnly() && !primary)\n continue;\n if (!initialized) {\n if (lsnr.oldValueRequired()) {\n oldVal = (CacheObject) cctx.unwrapTemporary(oldVal);\n if (oldVal != null)\n oldVal.finishUnmarshal(cctx.cacheObjectContext(), cctx.deploy().globalLoader());\n }\n if (newVal != null)\n newVal.finishUnmarshal(cctx.cacheObjectContext(), cctx.deploy().globalLoader());\n initialized = true;\n }\n CacheContinuousQueryEntry e0 = new CacheContinuousQueryEntry(cctx.cacheId(), evtType, key, newVal, lsnr.oldValueRequired() ? oldVal : null, lsnr.keepBinary(), partId, updateCntr, topVer, (byte) 0);\n IgniteCacheProxy jcache = cctx.kernalContext().cache().jcacheProxy(cctx.name(), true);\n assert jcache != null : \"Failed to get cache proxy [name=\" + cctx.name() + \", locStart=\" + cctx.startTopologyVersion() + \", locNode=\" + cctx.localNode() + \", stopping=\" + cctx.kernalContext().isStopping();\n CacheContinuousQueryEvent evt = new CacheContinuousQueryEvent<>(jcache, cctx, e0);\n lsnr.onEntryUpdated(evt, primary, recordIgniteEvt, fut);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public static AP newAnyPanel(final String panelClass, final String id, final AnyTypeTO anyTypeTO, final RealmTO realmTO, final AnyLayout anyLayout, final boolean enableSearch, final AnyPanel.DirectoryPanelSupplier directoryPanelSupplier, final PageReference pageRef){\r\n try {\r\n @SuppressWarnings(\"unchecked\")\r\n Class clazz = (Class) ClassUtils.forName(panelClass, ClassUtils.getDefaultClassLoader());\r\n return clazz.getConstructor(String.class, AnyTypeTO.class, RealmTO.class, AnyLayout.class, boolean.class, AnyPanel.DirectoryPanelSupplier.class, PageReference.class).newInstance(id, anyTypeTO, realmTO, anyLayout, enableSearch, directoryPanelSupplier, pageRef);\r\n } catch (Exception e) {\r\n throw new IllegalArgumentException(\"Could not instantiate \" + panelClass, e);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void createEntityFDandWrite(FileSystem fs, Path logPath, ObjectMapper objMapper, ApplicationAttemptId attemptId, TimelineEntityGroupId groupId, List entities, boolean isAppendSupported, Map> logFDs) throws IOException {\n entityTableLocker.lock();\n try {\n if (serviceStopped) {\n return;\n }\n HashMap logFDMap = logFDs.get(attemptId);\n if (logFDMap == null) {\n logFDMap = new HashMap();\n }\n EntityLogFD logFD = logFDMap.get(groupId);\n if (logFD == null) {\n logFD = new EntityLogFD(fs, logPath, objMapper, isAppendSupported);\n }\n logFD.lock();\n try {\n logFD.writeEntities(entities);\n entityTableCopyLocker.lock();\n try {\n logFDMap.put(groupId, logFD);\n logFDs.put(attemptId, logFDMap);\n } finally {\n entityTableCopyLocker.unlock();\n }\n } finally {\n logFD.unlock();\n }\n } finally {\n entityTableLocker.unlock();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static MTreeBelowSGCachedImpl loadFromSnapshot(File snapshotDir, String storageGroupFullPath, int schemaRegionId, CachedSchemaRegionStatistics regionStatistics, SchemaRegionCachedMetric metric, Consumer> measurementProcess, Consumer> deviceProcess, Function, Map> tagGetter, Function, Map> attributeGetter, Runnable flushCallback) throws IOException, MetadataException {\n return new MTreeBelowSGCachedImpl(new PartialPath(storageGroupFullPath), PBTreeFactory.getInstance().createCachedMTreeStoreFromSnapshot(snapshotDir, storageGroupFullPath, schemaRegionId, regionStatistics, metric, flushCallback), measurementProcess, deviceProcess, tagGetter, attributeGetter, regionStatistics);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected QuerySpec getQuery(RelDataType rowType, Filter filter, @Nullable Project project, @Nullable ImmutableBitSet groupSet, @Nullable List aggCalls, @Nullable List aggNames, @Nullable List collationIndexes, @Nullable List collationDirections, ImmutableBitSet numericCollationIndexes, @Nullable Integer fetch, @Nullable Project postProject, @Nullable Filter havingFilter) {\n // Handle filter\n @Nullable\n final DruidJsonFilter jsonFilter = computeFilter(filter);\n if (groupSet == null) {\n // It is Scan Query since no Grouping\n assert aggCalls == null;\n assert aggNames == null;\n assert collationIndexes == null || collationIndexes.isEmpty();\n assert collationDirections == null || collationDirections.isEmpty();\n final List scanColumnNames;\n final List virtualColumnList = new ArrayList<>();\n if (project != null) {\n // project some fields only\n Pair, List> projectResult = computeProjectAsScan(project, project.getInput().getRowType(), this);\n scanColumnNames = projectResult.left;\n virtualColumnList.addAll(projectResult.right);\n } else {\n // Scan all the fields\n scanColumnNames = rowType.getFieldNames();\n }\n final ScanQuery scanQuery = new ScanQuery(druidTable.dataSource, intervals, jsonFilter, virtualColumnList, scanColumnNames, fetch);\n return new QuerySpec(QueryType.SCAN, scanQuery.toQuery(), scanColumnNames);\n }\n // At this Stage we have a valid Aggregate thus Query is one of Timeseries, TopN, or GroupBy\n // Handling aggregate and sort is more complex, since\n // we need to extract the conditions to know whether the query will be executed as a\n // Timeseries, TopN, or GroupBy in Druid\n requireNonNull(aggCalls, \"aggCalls\");\n requireNonNull(aggNames, \"aggNames\");\n checkArgument(aggCalls.size() == aggNames.size());\n final List postAggs = new ArrayList<>();\n final JsonLimit limit;\n final RelDataType aggInputRowType = table.getRowType();\n final List aggregateStageFieldNames = new ArrayList<>();\n Pair, List> projectGroupSet = computeProjectGroupSet(project, groupSet, aggInputRowType, this);\n requireNonNull(projectGroupSet, \"projectGroupSet\");\n final List groupByKeyDims = projectGroupSet.left;\n final List virtualColumnList = projectGroupSet.right;\n for (DimensionSpec dim : groupByKeyDims) {\n aggregateStageFieldNames.add(dim.getOutputName());\n }\n final List aggregations = computeDruidJsonAgg(aggCalls, aggNames, project, this);\n requireNonNull(aggregations, \"aggregations\");\n for (JsonAggregation jsonAgg : aggregations) {\n aggregateStageFieldNames.add(jsonAgg.name);\n }\n @Nullable\n final DruidJsonFilter havingJsonFilter;\n if (havingFilter != null) {\n havingJsonFilter = DruidJsonFilter.toDruidFilters(havingFilter.getCondition(), havingFilter.getInput().getRowType(), this, getCluster().getRexBuilder());\n } else {\n havingJsonFilter = null;\n }\n // Then we handle projects after aggregates as Druid Post Aggregates\n final List postAggregateStageFieldNames;\n if (postProject != null) {\n final List postProjectDimListBuilder = new ArrayList<>();\n final RelDataType postAggInputRowType = getCluster().getTypeFactory().createStructType(Pair.right(postProject.getInput().getRowType().getFieldList()), aggregateStageFieldNames);\n final Set existingAggFieldsNames = new HashSet<>(aggregateStageFieldNames);\n // this is an index of existing columns coming out aggregate layer. Will use this index to:\n // filter out any project down the road that doesn't change values e.g inputRef/identity cast\n Map existingProjects = Maps.uniqueIndex(aggregateStageFieldNames, DruidExpressions::fromColumn);\n for (Pair pair : postProject.getNamedProjects()) {\n final RexNode postProjectRexNode = pair.left;\n String expression = DruidExpressions.toDruidExpression(postProjectRexNode, postAggInputRowType, this);\n final String existingFieldName = existingProjects.get(expression);\n if (existingFieldName != null) {\n // simple input ref or Druid runtime identity cast will skip it, since it is here already\n postProjectDimListBuilder.add(existingFieldName);\n } else {\n final String uniquelyProjectFieldName = SqlValidatorUtil.uniquify(pair.right, existingAggFieldsNames, SqlValidatorUtil.EXPR_SUGGESTER);\n postAggs.add(new JsonExpressionPostAgg(uniquelyProjectFieldName, expression, null));\n postProjectDimListBuilder.add(uniquelyProjectFieldName);\n existingAggFieldsNames.add(uniquelyProjectFieldName);\n }\n }\n postAggregateStageFieldNames = postProjectDimListBuilder;\n } else {\n postAggregateStageFieldNames = null;\n }\n // final Query output row field names.\n final List queryOutputFieldNames = postAggregateStageFieldNames == null ? aggregateStageFieldNames : postAggregateStageFieldNames;\n // handle sort all together\n limit = computeSort(fetch, collationIndexes, collationDirections, numericCollationIndexes, queryOutputFieldNames);\n final String timeSeriesQueryString = planAsTimeSeries(groupByKeyDims, jsonFilter, virtualColumnList, aggregations, postAggs, limit, havingJsonFilter);\n if (timeSeriesQueryString != null) {\n final String timeExtractColumn = groupByKeyDims.isEmpty() ? null : groupByKeyDims.get(0).getOutputName();\n if (timeExtractColumn != null) {\n // Case we have transformed the group by time to druid timeseries with Granularity.\n // Need to replace the name of the column with druid timestamp field name.\n final List timeseriesFieldNames = Util.transform(queryOutputFieldNames, input -> {\n if (timeExtractColumn.equals(input)) {\n return \"timestamp\";\n }\n return input;\n });\n return new QuerySpec(QueryType.TIMESERIES, timeSeriesQueryString, timeseriesFieldNames);\n }\n return new QuerySpec(QueryType.TIMESERIES, timeSeriesQueryString, queryOutputFieldNames);\n }\n final String topNQuery = planAsTopN(groupByKeyDims, jsonFilter, virtualColumnList, aggregations, postAggs, limit, havingJsonFilter);\n if (topNQuery != null) {\n return new QuerySpec(QueryType.TOP_N, topNQuery, queryOutputFieldNames);\n }\n final String groupByQuery = planAsGroupBy(groupByKeyDims, jsonFilter, virtualColumnList, aggregations, postAggs, limit, havingJsonFilter);\n if (groupByQuery == null) {\n throw new IllegalStateException(\"Cannot plan Druid Query\");\n }\n return new QuerySpec(QueryType.GROUP_BY, groupByQuery, queryOutputFieldNames);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "/**\n * Executes a \"find\" operation on the underlying index.\n *\n * @param ops List of operations represented as Json strings.\n * @param fields List of fields to project; or null to return map\n * @param sort list of fields to sort and their direction (asc/desc)\n * @param aggregations aggregation functions\n * @return Enumerator of results\n */\nprivate Enumerable find(List ops, List> fields, List> sort, List groupBy, List> aggregations, Map mappings, Long offset, Long fetch) throws IOException {\n if (!aggregations.isEmpty() || !groupBy.isEmpty()) {\n // process aggregations separately\n return aggregate(ops, fields, sort, groupBy, aggregations, mappings, offset, fetch);\n }\n final ObjectNode query = mapper.createObjectNode();\n // manually parse from previously concatenated string\n for (String op : ops) {\n query.setAll((ObjectNode) mapper.readTree(op));\n }\n if (!sort.isEmpty()) {\n ArrayNode sortNode = query.withArray(\"sort\");\n sort.forEach(e -> sortNode.add(mapper.createObjectNode().put(e.getKey(), e.getValue().isDescending() ? \"desc\" : \"asc\")));\n }\n if (offset != null) {\n query.put(\"from\", offset);\n }\n if (fetch != null) {\n query.put(\"size\", fetch);\n }\n final Function1 getter = ElasticsearchEnumerators.getter(fields, ImmutableMap.copyOf(mappings));\n Iterable iter;\n if (offset == null) {\n // apply scrolling when there is no offsets\n iter = () -> new Scrolling(transport).query(query);\n } else {\n final ElasticsearchJson.Result search = transport.search().apply(query);\n iter = () -> search.searchHits().hits().iterator();\n }\n return Linq4j.asEnumerable(iter).select(getter);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "/**\n * @return a new instance of the LoanRescheduleRequest class\n */\npublic static LoanRescheduleRequest instance(final Loan loan, final Integer statusEnum, final Integer rescheduleFromInstallment, final LocalDate rescheduleFromDate, final Boolean recalculateInterest, final CodeValue rescheduleReasonCodeValue, final String rescheduleReasonComment, final LocalDate submittedOnDate, final AppUser submittedByUser, final LocalDate approvedOnDate, final AppUser approvedByUser, final LocalDate rejectedOnDate, AppUser rejectedByUser) {\n return new LoanRescheduleRequest(loan, statusEnum, rescheduleFromInstallment, rescheduleFromDate, recalculateInterest, rescheduleReasonCodeValue, rescheduleReasonComment, submittedOnDate, submittedByUser, approvedOnDate, approvedByUser, rejectedOnDate, rejectedByUser);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * /** Inserts a metadata into the database, optionally indexing it, and optionally applying automatic changes to it\n * (update-fixed-info).\n *\n * @param context\n * @param newMetadata\n * @param metadataXml\n * @param indexingMode\n * @param updateFixedInfo\n * @param updateDatestamp\n * @param fullRightsForGroup\n * @param forceRefreshReaders\n * @return\n * @throws Exception\n */\nAbstractMetadata insertMetadata(ServiceContext context, AbstractMetadata newMetadata, Element metadataXml, IndexingMode indexingMode, boolean updateFixedInfo, UpdateDatestamp updateDatestamp, boolean fullRightsForGroup, boolean forceRefreshReaders) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static SavingsAccountTransactionData create(final Long id, final SavingsAccountTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final Long savingsId, final String savingsAccountNo, final LocalDate date, final CurrencyData currency, final BigDecimal amount, final BigDecimal outstandingChargeAmount, final BigDecimal runningBalance, final boolean reversed, final AccountTransferData transfer, final LocalDate submittedOnDate, final boolean interestedPostedAsOn, final String submittedByUsername, final String note, final Boolean isReversal, final Long originalTransactionId, final Boolean lienTransaction, final Long releaseTransactionId, final String reasonForBlock) {\n return new SavingsAccountTransactionData(id, transactionType, paymentDetailData, savingsId, savingsAccountNo, date, currency, amount, outstandingChargeAmount, runningBalance, reversed, transfer, null, submittedOnDate, interestedPostedAsOn, submittedByUsername, note, isReversal, originalTransactionId, false, lienTransaction, releaseTransactionId, reasonForBlock);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private T asTrait(K core, TraitableBean inner, Class trait, boolean needsProxy, boolean hasTrait, boolean needsUpdate, TraitFactoryImpl builder, boolean logical, InternalMatch internalMatch) throws LogicalTypeInconsistencyException{\r\n T thing;\r\n if (needsProxy) {\r\n thing = (T) inner;\r\n inner.addTrait(trait.getName(), (Thing) core);\r\n } else if (hasTrait) {\r\n thing = (T) inner.getTrait(trait.getName());\r\n } else {\r\n thing = (T) builder.getProxy(inner, trait, logical);\r\n }\r\n if (needsUpdate) {\r\n InternalFactHandle h = (InternalFactHandle) lookupFactHandle(core);\r\n if (h == null) {\r\n h = lookupHandleForWrapper(core);\r\n }\r\n if (h == null) {\r\n h = (InternalFactHandle) this.workingMemory.insert(core, false, internalMatch.getRule(), internalMatch.getTuple().getTupleSink());\r\n }\r\n if (!h.isTraitOrTraitable()) {\r\n throw new IllegalStateException(\"A traited working memory element is being used with a default fact handle. \" + \"Please verify that its class was declared as @Traitable : \" + core.getClass().getName());\r\n }\r\n this.update(h, inner, internalMatch);\r\n }\r\n return thing;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public JournalEntry createCreditJournalEntryOrReversalForInvestor(final Office office, final String currencyCode, final Long loanId, final Long transactionId, final LocalDate transactionDate, final BigDecimal amount, final Boolean isReversalOrder, final GLAccount account) {\n if (isReversalOrder) {\n return createDebitJournalEntryForInvestor(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n } else {\n return createCreditJournalEntryForInvestor(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public Pair> validateIpRange(final String startIP, final String endIP, final String newVlanGateway, final String newVlanNetmask, final List vlans, final boolean ipv4, final boolean ipv6, String ip6Gateway, String ip6Cidr, final String startIPv6, final String endIPv6, final Network network) {\n String vlanGateway = null;\n String vlanNetmask = null;\n boolean sameSubnet = false;\n if (CollectionUtils.isNotEmpty(vlans)) {\n for (final VlanVO vlan : vlans) {\n vlanGateway = vlan.getVlanGateway();\n vlanNetmask = vlan.getVlanNetmask();\n sameSubnet = hasSameSubnet(ipv4, vlanGateway, vlanNetmask, newVlanGateway, newVlanNetmask, startIP, endIP, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);\n if (sameSubnet)\n break;\n }\n } else if (network.getGateway() != null && network.getCidr() != null) {\n vlanGateway = network.getGateway();\n vlanNetmask = NetUtils.getCidrNetmask(network.getCidr());\n sameSubnet = hasSameSubnet(ipv4, vlanGateway, vlanNetmask, newVlanGateway, newVlanNetmask, startIP, endIP, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);\n }\n if (newVlanGateway == null && newVlanNetmask == null && !sameSubnet) {\n throw new InvalidParameterValueException(\"The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet\");\n }\n Pair vlanDetails = null;\n if (sameSubnet) {\n vlanDetails = new Pair(vlanGateway, vlanNetmask);\n } else {\n vlanDetails = new Pair(newVlanGateway, newVlanNetmask);\n }\n // check if the gatewayip is the part of the ip range being added.\n if (ipv4 && NetUtils.ipRangesOverlap(startIP, endIP, vlanDetails.first(), vlanDetails.first())) {\n throw new InvalidParameterValueException(\"The gateway ip should not be the part of the ip range being added.\");\n }\n return new Pair>(sameSubnet, vlanDetails);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "@Nullable\npublic static Geometry ST_MakePolygon(Geometry shell, Geometry hole0, Geometry hole1, Geometry hole2, Geometry hole3, Geometry hole4, Geometry hole5, Geometry hole6){\r\n return makePolygon(shell, hole0, hole1, hole2, hole3, hole4, hole5, hole6);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private UserVm deploySharedFSVM(Long zoneId, Account owner, List networkIds, String name, Long serviceOfferingId, Long diskOfferingId, SharedFS.FileSystemType fileSystem, Long size, Long minIops, Long maxIops) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {\n ServiceOffering serviceOffering = serviceOfferingDao.findById(serviceOfferingId);\n DataCenter zone = dataCenterDao.findById(zoneId);\n List hypervisors = resourceMgr.getSupportedHypervisorTypes(zoneId, false, null);\n if (hypervisors.size() > 0) {\n Collections.shuffle(hypervisors);\n } else {\n throw new CloudRuntimeException(String.format(\"No supported hypervisor found for zone %s.\", zone.toString()));\n }\n String hostName = getStorageVmName(name);\n Network.IpAddresses addrs = new Network.IpAddresses(null, null);\n Map customParameterMap = new HashMap();\n if (minIops != null) {\n customParameterMap.put(\"minIopsDo\", minIops.toString());\n customParameterMap.put(\"maxIopsDo\", maxIops.toString());\n }\n List keypairs = new ArrayList();\n for (final Iterator iter = hypervisors.iterator(); iter.hasNext(); ) {\n final Hypervisor.HypervisorType hypervisor = iter.next();\n VMTemplateVO template = templateDao.findSystemVMReadyTemplate(zoneId, hypervisor);\n if (template == null && !iter.hasNext()) {\n throw new CloudRuntimeException(String.format(\"Unable to find the systemvm template for %s or it was not downloaded in %s.\", hypervisor.toString(), zone.toString()));\n }\n LaunchPermissionVO existingPermission = launchPermissionDao.findByTemplateAndAccount(template.getId(), owner.getId());\n if (existingPermission == null) {\n LaunchPermissionVO launchPermission = new LaunchPermissionVO(template.getId(), owner.getId());\n launchPermissionDao.persist(launchPermission);\n }\n UserVm vm = null;\n String fsVmConfig = getStorageVmConfig(fileSystem.toString().toLowerCase(), hypervisor.toString().toLowerCase(), SharedFSPath);\n String base64UserData = Base64.encodeBase64String(fsVmConfig.getBytes(com.cloud.utils.StringUtils.getPreferredCharset()));\n CallContext vmContext = CallContext.register(CallContext.current(), ApiCommandResourceType.VirtualMachine);\n try {\n vm = userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, networkIds, owner, hostName, hostName, diskOfferingId, size, null, Hypervisor.HypervisorType.None, BaseCmd.HTTPMethod.POST, base64UserData, null, null, keypairs, null, addrs, null, null, null, customParameterMap, null, null, null, null, true, UserVmManager.SHAREDFSVM, null);\n vmContext.setEventResourceId(vm.getId());\n userVmService.startVirtualMachine(vm);\n } catch (InsufficientCapacityException ex) {\n if (vm != null) {\n expungeVm(vm.getId());\n }\n if (iter.hasNext()) {\n continue;\n } else {\n throw ex;\n }\n } finally {\n CallContext.unregister();\n }\n return vm;\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static EmailCampaignData instance(final Long id, final String campaignName, final Integer campaignType, final Long businessRuleId, final String paramValue, final EnumOptionData campaignStatus, final String emailSubject, final String message, final String emailAttachmentFileFormat, final Long stretchyReportId, final String stretchyReportParamMap, final ZonedDateTime nextTriggerDate, final LocalDate lastTriggerDate, final EmailCampaignTimeLine emailCampaignTimeLine, final ZonedDateTime recurrenceStartDate, final String recurrence) {\n return new EmailCampaignData().setId(id).setCampaignName(campaignName).setCampaignType(campaignType).setBusinessRuleId(businessRuleId).setParamValue(paramValue).setCampaignStatus(campaignStatus).setEmailSubject(emailSubject).setEmailMessage(message).setEmailAttachmentFileFormat(emailAttachmentFileFormat).setStretchyReportId(stretchyReportId).setStretchyReportParamMap(stretchyReportParamMap).setNextTriggerDate(nextTriggerDate).setLastTriggerDate(lastTriggerDate).setEmailCampaignTimeLine(emailCampaignTimeLine).setRecurrenceStartDate(recurrenceStartDate).setRecurrence(recurrence);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static ClientData template(final Long officeId, final LocalDate joinedDate, final Collection officeOptions, final Collection staffOptions, final Collection narrations, final Collection genderOptions, final Collection savingProductOptions, final Collection clientTypeOptions, final Collection clientClassificationOptions, final Collection clientNonPersonConstitutionOptions, final Collection clientNonPersonMainBusinessLineOptions, final List clientLegalFormOptions, final ClientFamilyMembersData familyMemberOptions, final Collection address, final Boolean isAddressEnabled, final List datatables) {\n final String accountNo = null;\n final EnumOptionData status = null;\n final CodeValueData subStatus = null;\n final String officeName = null;\n final Long transferToOfficeId = null;\n final String transferToOfficeName = null;\n final Long id = null;\n final String firstname = null;\n final String middlename = null;\n final String lastname = null;\n final String fullname = null;\n final String displayName = null;\n final ExternalId externalId = ExternalId.empty();\n final String mobileNo = null;\n final String emailAddress = null;\n final LocalDate dateOfBirth = null;\n final CodeValueData gender = null;\n final Long imageId = null;\n final Long staffId = null;\n final String staffName = null;\n final Collection groups = null;\n final ClientTimelineData timeline = null;\n final Long savingsProductId = null;\n final String savingsProductName = null;\n final Long savingsAccountId = null;\n final Collection savingAccountOptions = null;\n final CodeValueData clientType = null;\n final CodeValueData clientClassification = null;\n final EnumOptionData legalForm = null;\n final Boolean isStaff = false;\n final ClientNonPersonData clientNonPersonDetails = null;\n final Set clientCollateralManagements = null;\n return new ClientData(accountNo, status, subStatus, officeId, officeName, transferToOfficeId, transferToOfficeName, id, firstname, middlename, lastname, fullname, displayName, externalId, mobileNo, emailAddress, dateOfBirth, gender, joinedDate, imageId, staffId, staffName, officeOptions, groups, staffOptions, narrations, genderOptions, timeline, savingProductOptions, savingsProductId, savingsProductName, savingsAccountId, savingAccountOptions, clientType, clientClassification, clientTypeOptions, clientClassificationOptions, clientNonPersonConstitutionOptions, clientNonPersonMainBusinessLineOptions, clientNonPersonDetails, clientLegalFormOptions, familyMemberOptions, legalForm, address, isAddressEnabled, datatables, isStaff, clientCollateralManagements);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public List ofNullable(@Nullable final T e0, @Nullable final T e1, @Nullable final T e2, @Nullable final T e3, @Nullable final T e4, @Nullable final T e5, @Nullable final T e6, @Nullable final T e7){\r\n val list = new ArrayList(8);\r\n list.add(e0);\r\n list.add(e1);\r\n list.add(e2);\r\n list.add(e3);\r\n list.add(e4);\r\n list.add(e5);\r\n list.add(e6);\r\n list.add(e7);\r\n return Collections.unmodifiableList(list);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * This method supports three modes to set a property:\n *\n * 1. Setting a Map property where the property name refers to a map via name[aKey] where aKey is the map key to\n * use.\n *\n * 2. Setting a property that has already been resolved, this is the case when {@code context} and {@code refName}\n * are NULL and {@code value} is non-NULL.\n *\n * 3. Setting a property that has not yet been resolved, the property will be resolved based on the suitable methods\n * found matching the property name on the {@code target} bean. For this mode to be triggered the parameters\n * {@code context} and {@code refName} must NOT be NULL, and {@code value} MUST be NULL.\n */\nboolean setProperty(CamelContext context, TypeConverter typeConverter, Object target, String name, Object value, String refName, boolean allowBuilderPattern, boolean allowPrivateSetter, boolean ignoreCase) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "/**\n * Check whether current user have permissions to access the path. For more\n * details of the parameters, see\n * {@link FSPermissionChecker#checkPermission}.\n */\nvoid checkPermission(FSPermissionChecker pc, INodesInPath iip, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException {\n if (pc.isSuperUser()) {\n // call the external enforcer for audit\n pc.checkSuperuserPrivilege(iip.getPath());\n } else {\n readLock();\n try {\n pc.checkPermission(iip, doCheckOwner, ancestorAccess, parentAccess, access, subAccess, ignoreEmptyDir);\n } finally {\n readUnlock();\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static TokenAuthEvent success(String ip, String subjectID, String cuid, String msn, String op, String tokenType, String appletVersion, String authManagerID) {\n TokenAuthEvent event = new TokenAuthEvent(SUCCESS);\n event.setAttribute(\"IP\", ip);\n event.setAttribute(\"SubjectID\", subjectID);\n event.setAttribute(\"CUID\", cuid);\n event.setAttribute(\"MSN\", msn);\n event.setAttribute(\"Outcome\", ILogger.SUCCESS);\n event.setAttribute(\"OP\", op);\n event.setAttribute(\"tokenType\", tokenType);\n event.setAttribute(\"AppletVersion\", appletVersion);\n event.setAttribute(\"AuthMgr\", authManagerID);\n return event;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "public static ImmutableMap of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4){\r\n Map map = new HashMap<>();\r\n putAndWarnDuplicateKeys(map, k0, v0);\r\n putAndWarnDuplicateKeys(map, k1, v1);\r\n putAndWarnDuplicateKeys(map, k2, v2);\r\n putAndWarnDuplicateKeys(map, k3, v3);\r\n putAndWarnDuplicateKeys(map, k4, v4);\r\n return new ImmutableMap<>(map);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void createCreditJournalEntryForShares(final Office office, final String currencyCode, final int accountTypeToCreditId, final Long shareProductId, final Long paymentTypeId, final Long shareAccountId, final String transactionId, final LocalDate transactionDate, final BigDecimal amount) {\n final GLAccount creditAccount = getLinkedGLAccountForShareProduct(shareProductId, accountTypeToCreditId, paymentTypeId);\n createCreditJournalEntryForShares(office, currencyCode, creditAccount, shareAccountId, transactionId, transactionDate, amount);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "//\tinRange\n/**\n * \tIs start..end include one of the days ?\n * @param start start day\n * @param end end day (not including)\n * @param OnMonday true if OK\n * @param OnTuesday true if OK\n * @param OnWednesday true if OK\n * @param OnThursday true if OK\n * @param OnFriday true if OK\n * @param OnSaturday true if OK\n * @param OnSunday true if OK\n * @return true if on one of the days\n */\nstatic public boolean inRange(Timestamp start, Timestamp end, boolean OnMonday, boolean OnTuesday, boolean OnWednesday, boolean OnThursday, boolean OnFriday, boolean OnSaturday, boolean OnSunday) {\n //\tare there restrictions?\n if (OnSaturday && OnSunday && OnMonday && OnTuesday && OnWednesday && OnThursday && OnFriday)\n return false;\n GregorianCalendar calStart = new GregorianCalendar();\n calStart.setTimeInMillis(start.getTime());\n int dayStart = calStart.get(Calendar.DAY_OF_WEEK);\n //\n GregorianCalendar calEnd = new GregorianCalendar();\n calEnd.setTimeInMillis(end.getTime());\n //\tnot including\n calEnd.add(Calendar.DAY_OF_YEAR, -1);\n int dayEnd = calEnd.get(Calendar.DAY_OF_WEEK);\n //\tOn same day\n if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR) && calStart.get(Calendar.MONTH) == calEnd.get(Calendar.MONTH) && calStart.get(Calendar.DAY_OF_MONTH) == calEnd.get(Calendar.DAY_OF_MONTH)) {\n if ((OnSaturday && dayStart == Calendar.SATURDAY) || (OnSunday && dayStart == Calendar.SUNDAY) || (OnMonday && dayStart == Calendar.MONDAY) || (OnTuesday && dayStart == Calendar.TUESDAY) || (OnWednesday && dayStart == Calendar.WEDNESDAY) || (OnThursday && dayStart == Calendar.THURSDAY) || (OnFriday && dayStart == Calendar.FRIDAY)) {\n return true;\n }\n return false;\n }\n //\tCalendar.SUNDAY=1 ... SATURDAY=7\n BitSet days = new BitSet(8);\n //\tSet covered days in BitArray\n if (dayEnd <= dayStart)\n dayEnd += 7;\n for (int i = dayStart; i <= dayEnd; i++) {\n int index = i;\n if (index > 7)\n index -= 7;\n days.set(index);\n }\n //\tCompare days to availability\n if ((OnSaturday && days.get(Calendar.SATURDAY)) || (OnSunday && days.get(Calendar.SUNDAY)) || (OnMonday && days.get(Calendar.MONDAY)) || (OnTuesday && days.get(Calendar.TUESDAY)) || (OnWednesday && days.get(Calendar.WEDNESDAY)) || (OnThursday && days.get(Calendar.THURSDAY)) || (OnFriday && days.get(Calendar.FRIDAY))) {\n return true;\n }\n return false;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public static JsonCommand fromExistingCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final String transactionId, final String url, final Long productId, Long creditBureauId, final Long organisationCreditBureauId, final String jobName) {\n return new JsonCommand(commandId, jsonCommand, parsedCommand, fromApiJsonHelper, entityName, resourceId, subresourceId, groupId, clientId, loanId, savingsId, transactionId, url, productId, creditBureauId, organisationCreditBureauId, jobName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static RPC.Server startProtocolServer(int srvPort, int numHandlers, AtomicReference bindAddress, Configuration conf, BlockingService impl, Class protocolClass, SecretManager secretManager, PolicyProvider provider, ConfVars... aclVars){\r\n InetSocketAddress addr = new InetSocketAddress(srvPort);\r\n RPC.Server server;\r\n try {\r\n server = createRpcServer(protocolClass, addr, conf, numHandlers, impl, secretManager, provider, aclVars);\r\n server.start();\r\n } catch (IOException e) {\r\n LOG.error(\"Failed to run RPC Server on port: \" + srvPort, e);\r\n throw new RuntimeException(e);\r\n }\r\n InetSocketAddress serverBindAddress = NetUtils.getConnectAddress(server);\r\n InetSocketAddress bindAddressVal = NetUtils.createSocketAddrForHost(serverBindAddress.getAddress().getCanonicalHostName(), serverBindAddress.getPort());\r\n if (bindAddress != null) {\r\n bindAddress.set(bindAddressVal);\r\n }\r\n LOG.info(\"Instantiated \" + protocolClass.getSimpleName() + \" at \" + bindAddressVal);\r\n return server;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Load a directory into a Hive Table Partition - Alters existing content of\n * the partition with the contents of loadPath. - If the partition does not\n * exist - one is created - files in loadPath are moved into Hive. But the\n * directory itself is not removed.\n *\n * @param loadPath\n * Directory containing files to load into Table\n * @param tbl\n * name of table to be loaded.\n * @param partSpec\n * defines which partition needs to be loaded\n * @param loadFileType\n * if REPLACE_ALL - replace files in the table,\n * otherwise add files to table (KEEP_EXISTING, OVERWRITE_EXISTING)\n * @param inheritTableSpecs if true, on [re]creating the partition, take the\n * location/inputformat/outputformat/serde details from table spec\n * @param isSrcLocal\n * If the source directory is LOCAL\n * @param isAcidIUDoperation\n * true if this is an ACID operation Insert/Update/Delete operation\n * @param resetStatistics\n * if true, reset the statistics. If false, do not reset statistics.\n * @param writeId write ID allocated for the current load operation\n * @param stmtId statement ID of the current load statement\n * @param isInsertOverwrite\n * @return Partition object being loaded with data\n */\npublic Partition loadPartition(Path loadPath, Table tbl, Map partSpec, LoadFileType loadFileType, boolean inheritTableSpecs, boolean inheritLocation, boolean isSkewedStoreAsSubdir, boolean isSrcLocal, boolean isAcidIUDoperation, boolean resetStatistics, Long writeId, int stmtId, boolean isInsertOverwrite, boolean isDirectInsert) throws HiveException {\n PerfLogger perfLogger = SessionState.getPerfLogger();\n perfLogger.perfLogBegin(\"MoveTask\", PerfLogger.LOAD_PARTITION);\n // Get the partition object if it already exists\n Partition oldPart = getPartition(tbl, partSpec, false);\n boolean isTxnTable = AcidUtils.isTransactionalTable(tbl);\n // If config is set, table is not temporary and partition being inserted exists, capture\n // the list of files added. For not yet existing partitions (insert overwrite to new partition\n // or dynamic partition inserts), the add partition event will capture the list of files added.\n List newFiles = null;\n if (conf.getBoolVar(ConfVars.FIRE_EVENTS_FOR_DML) && !tbl.isTemporary()) {\n newFiles = Collections.synchronizedList(new ArrayList<>());\n }\n Partition newTPart = loadPartitionInternal(loadPath, tbl, partSpec, oldPart, loadFileType, inheritTableSpecs, inheritLocation, isSkewedStoreAsSubdir, isSrcLocal, isAcidIUDoperation, resetStatistics, writeId, stmtId, isInsertOverwrite, isTxnTable, newFiles, isDirectInsert);\n AcidUtils.TableSnapshot tableSnapshot = isTxnTable ? getTableSnapshot(tbl, writeId) : null;\n if (tableSnapshot != null) {\n newTPart.getTPartition().setWriteId(tableSnapshot.getWriteId());\n }\n if (oldPart == null) {\n addPartitionToMetastore(newTPart, resetStatistics, tbl, tableSnapshot);\n // For acid table, add the acid_write event with file list at the time of load itself. But\n // it should be done after partition is created.\n if (isTxnTable && (null != newFiles)) {\n addWriteNotificationLog(tbl, partSpec, newFiles, writeId, null);\n }\n } else {\n try {\n setStatsPropAndAlterPartition(resetStatistics, tbl, newTPart, tableSnapshot);\n } catch (TException e) {\n LOG.error(\"Error loading partitions\", e);\n throw new HiveException(e);\n }\n }\n perfLogger.perfLogEnd(\"MoveTask\", PerfLogger.LOAD_PARTITION);\n return newTPart;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void createAccrualBasedCreditJournalEntriesAndReversalsForSavings(final Office office, final String currencyCode, final Integer accountTypeToBeCredited, final Long savingsProductId, final Long paymentTypeId, final Long savingsId, final String transactionId, final LocalDate transactionDate, final BigDecimal amount, final Boolean isReversal) {\n // reverse debits and credits for reversals\n if (isReversal) {\n createDebitJournalEntriesForSavings(office, currencyCode, accountTypeToBeCredited, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount);\n } else {\n createCreditJournalEntriesForSavings(office, currencyCode, accountTypeToBeCredited, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private VolumeVO createVolume(VirtualDisk disk, VirtualMachineMO vmToImport, long domainId, long zoneId, long accountId, long instanceId, Long poolId, long templateId, Backup backup, boolean isImport) throws Exception {\n VMInstanceVO vm = virtualMachineDao.findByIdIncludingRemoved(backup.getVmId());\n if (vm == null) {\n throw new CloudRuntimeException(\"Failed to find the backup volume information from the VM backup\");\n }\n List backedUpVolumes = vm.getBackupVolumeList();\n Volume.Type type = Volume.Type.DATADISK;\n Long size = disk.getCapacityInBytes();\n if (isImport) {\n for (Backup.VolumeInfo volumeInfo : backedUpVolumes) {\n if (volumeInfo.getSize().equals(disk.getCapacityInBytes())) {\n type = volumeInfo.getType();\n }\n }\n }\n VirtualDeviceBackingInfo backing = disk.getBacking();\n checkBackingInfo(backing);\n VirtualDiskFlatVer2BackingInfo info = (VirtualDiskFlatVer2BackingInfo) backing;\n String volumeName = getVolumeName(disk, vmToImport);\n Storage.ProvisioningType provisioningType = getProvisioningType(info);\n long diskOfferingId = getDiskOfferingId(size, provisioningType);\n Integer unitNumber = disk.getUnitNumber();\n VirtualMachineDiskInfo diskInfo = getDiskInfo(vmToImport, poolId, volumeName);\n return createVolumeRecord(type, volumeName, zoneId, domainId, accountId, diskOfferingId, provisioningType, size, instanceId, poolId, templateId, unitNumber, diskInfo);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public void buildContainerEnvironment(AbstractLauncher launcher, Service service, ComponentInstance instance, SliderFileSystem fileSystem, Configuration yarnConf, Container container, ContainerLaunchService.ComponentLaunchContext compLaunchContext, Map tokensForSubstitution) throws IOException, SliderException {\n // Set the environment variables in launcher\n launcher.putEnv(ServiceUtils.buildEnvMap(compLaunchContext.getConfiguration(), tokensForSubstitution));\n launcher.setEnv(\"WORK_DIR\", ApplicationConstants.Environment.PWD.$());\n launcher.setEnv(\"LOG_DIR\", ApplicationConstants.LOG_DIR_EXPANSION_VAR);\n if (System.getenv(HADOOP_USER_NAME) != null) {\n launcher.setEnv(HADOOP_USER_NAME, System.getenv(HADOOP_USER_NAME));\n }\n launcher.setEnv(\"LANG\", \"en_US.UTF-8\");\n launcher.setEnv(\"LC_ALL\", \"en_US.UTF-8\");\n launcher.setEnv(\"LANGUAGE\", \"en_US.UTF-8\");\n for (Entry entry : launcher.getEnv().entrySet()) {\n tokensForSubstitution.put($(entry.getKey()), entry.getValue());\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static LoanTransactionData importInstance(BigDecimal repaymentAmount, LocalDate repaymentDate, Long repaymentTypeId, String accountNumber, Integer checkNumber, Integer routingCode, Integer receiptNumber, Integer bankNumber, Long loanAccountId, String transactionType, Integer rowIndex, String locale, String dateFormat) {\n return new LoanTransactionData(repaymentAmount, repaymentDate, repaymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber, loanAccountId, \"\", rowIndex, locale, dateFormat);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private static String getPolygonJmol(int index, Point3d center, Vector3d referenceAxis, Vector3d axis, int n, String color, double radius, String name){\r\n StringBuilder s = new StringBuilder();\r\n s.append(\"draw axesSymbol\");\r\n s.append(name);\r\n s.append(index);\r\n s.append(\" \");\r\n s.append(\"polygon\");\r\n s.append(\" \");\r\n s.append(n + 1);\r\n s.append(getJmolPoint(center));\r\n Vector3d[] vertexes = getPolygonVertices(axis, referenceAxis, center, n, radius);\r\n for (Vector3d v : vertexes) {\r\n s.append(getJmolPoint(v));\r\n }\r\n s.append(n);\r\n for (int i = 1; i <= n; i++) {\r\n s.append(\"[\");\r\n s.append(0);\r\n s.append(\" \");\r\n s.append(i);\r\n s.append(\" \");\r\n if (i < n) {\r\n s.append(i + 1);\r\n } else {\r\n s.append(1);\r\n }\r\n s.append(\" \");\r\n s.append(7);\r\n s.append(\"]\");\r\n }\r\n if (n == 2) {\r\n s.append(\"mesh off\");\r\n }\r\n s.append(\" color \");\r\n s.append(color);\r\n s.append(\" off;\");\r\n return s.toString();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create a readable and parseable audit log string for a failed event.\n *\n * @param user User who made the service request.\n * @param operation Operation requested by the user.\n * @param perm Target permissions.\n * @param target The target on which the operation is being performed.\n * @param description Some additional information as to why the operation\n * failed.\n * @param appId Application Id in which operation was performed.\n * @param containerId Container Id in which operation was performed.\n * @param resource Resources associated with container.\n *\n *

\n * Note that the {@link RMAuditLogger} uses tabs ('\\t') as a key-val delimiter\n * and hence the value fields should not contains tabs ('\\t').\n */\npublic static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId, ContainerId containerId, Resource resource) {\n if (LOG.isWarnEnabled()) {\n LOG.warn(createFailureLog(user, operation, perm, target, description, appId, null, containerId, resource));\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private SQLBuilder getExtraCriteria(final String actionName, final String entityName, final Long resourceId, final Long makerId, final String makerDateTimeFrom, final String makerDateTimeTo, final Long checkerId, final String checkerDateTimeFrom, final String checkerDateTimeTo, final Integer status, final Integer officeId, final Integer groupId, final Integer clientId, final Integer loanId, final Integer savingsAccountId) {\n SQLBuilder extraCriteria = new SQLBuilder();\n extraCriteria.addNonNullCriteria(\"aud.action_name = \", actionName);\n if (entityName != null) {\n extraCriteria.addCriteria(\"aud.entity_name like\", entityName + \"%\");\n }\n extraCriteria.addNonNullCriteria(\"aud.resource_id = \", resourceId);\n extraCriteria.addNonNullCriteria(\"aud.maker_id = \", makerId);\n extraCriteria.addNonNullCriteria(\"aud.checker_id = \", checkerId);\n extraCriteria.addNonNullCriteria(\"aud.made_on_date >= \", makerDateTimeFrom);\n extraCriteria.addNonNullCriteria(\"aud.made_on_date <= \", makerDateTimeTo);\n extraCriteria.addNonNullCriteria(\"aud.checked_on_date >= \", checkerDateTimeFrom);\n extraCriteria.addNonNullCriteria(\"aud.checked_on_date <= \", checkerDateTimeTo);\n extraCriteria.addNonNullCriteria(\"aud.status = \", status);\n extraCriteria.addNonNullCriteria(\"aud.office_id = \", officeId);\n extraCriteria.addNonNullCriteria(\"aud.group_id = \", groupId);\n extraCriteria.addNonNullCriteria(\"aud.client_id = \", clientId);\n extraCriteria.addNonNullCriteria(\"aud.loan_id = \", loanId);\n extraCriteria.addNonNullCriteria(\"aud.savings_account_id = \", savingsAccountId);\n return extraCriteria;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Loop table in database.\n * @param exec {@link ExecutionContext}\n * @param cp {@link CredentialsProvider}\n * @param data the data rows with the parameters to loop over\n * @param rowCount the number of input rows or -1 if unknown\n * @param failIfException flag that indicates if the method should thrown an exception on error\n * @param appendInputColumns true if parameter input columns should be appended\n * @param includeEmptyResults true if a row should be added for parameters that do not return a result\n * @param retainAllColumns true all input columns should be retained\n * @param columns the parameter column names\n * @return {@link BufferedDataTableRowOutput} containing the loop result\n * @throws Exception\n * @since 3.2\n */\nBufferedDataTableRowOutput loopTable(final ExecutionContext exec, final CredentialsProvider cp, final RowInput data, final long rowCount, final boolean failIfException, final boolean appendInputColumns, final boolean includeEmptyResults, final boolean retainAllColumns, final String... columns) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "KNIME_knime-core", "language": "java"} {"function": "ApplicationLoadBalancerRule createApplicationLoadBalancer(String name, String description, Scheme scheme, long sourceIpNetworkId, String sourceIp, int sourcePort, int instancePort, String algorithm, long networkId, long lbOwnerId, Boolean forDisplay) throws InsufficientAddressCapacityException, NetworkRuleConflictException, InsufficientVirtualNetworkCapacityException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static RecurringDepositAccountData withTemplateOptions(final RecurringDepositAccountData account, final Collection productOptions, final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection transactions, final Collection charges, final Collection chargeOptions, final Collection preClosurePenalInterestOnTypeOptions, final Collection periodFrequencyTypeOptions) {\n return new RecurringDepositAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName, account.clientId, account.clientName, account.depositProductId, account.depositProductName, account.fieldOfficerId, account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.minBalanceForInterestCalculation, account.summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest, account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm, account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate, account.depositPeriod, account.depositPeriodFrequency, account.mandatoryRecommendedDepositAmount, periodFrequencyTypeOptions, account.depositType, account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, account.savingsAccounts, account.expectedFirstDepositOnDate, account.totalOverdueAmount, account.noOfOverdueInstallments, account.isMandatoryDeposit, account.allowWithdrawal, account.adjustAdvanceTowardsFuturePayments, account.isCalendarInherited, account.recurringFrequency, account.recurringFrequencyType, account.withHoldTax, account.taxGroup);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static MockModifiableViewRelOptTable create(MockModifiableViewTable modifiableViewTable, MockCatalogReader catalogReader, String catalogName, String schemaName, String name, boolean stream, double rowCount, ColumnResolver resolver){\r\n final Table underlying = modifiableViewTable.unwrap(Table.class);\r\n final InitializerExpressionFactory initializerExpressionFactory = underlying instanceof Wrapper ? ((Wrapper) underlying).unwrap(InitializerExpressionFactory.class) : NullInitializerExpressionFactory.INSTANCE;\r\n return new MockModifiableViewRelOptTable(modifiableViewTable, catalogReader, catalogName, schemaName, name, stream, rowCount, resolver, Util.first(initializerExpressionFactory, NullInitializerExpressionFactory.INSTANCE));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create and persist volume\n */\nprivate VolumeVO createVolumeRecord(Volume.Type type, String volumeName, long zoneId, long domainId, long accountId, long diskOfferingId, Storage.ProvisioningType provisioningType, Long size, long instanceId, Long poolId, long templateId, Integer unitNumber, VirtualMachineDiskInfo diskInfo) {\n VolumeVO volumeVO = new VolumeVO(type, volumeName, zoneId, domainId, accountId, diskOfferingId, provisioningType, size, null, null, null);\n volumeVO.setFormat(Storage.ImageFormat.OVA);\n volumeVO.setPath(volumeName);\n volumeVO.setState(Volume.State.Ready);\n volumeVO.setInstanceId(instanceId);\n volumeVO.setPoolId(poolId);\n volumeVO.setTemplateId(templateId);\n volumeVO.setAttached(new Date());\n volumeVO.setRemoved(null);\n volumeVO.setChainInfo(GSON.toJson(diskInfo));\n if (unitNumber != null) {\n volumeVO.setDeviceId(unitNumber.longValue());\n }\n return _volumeDao.persist(volumeVO);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Add document action message\n * @param docActionValues\n * @param docActionNames\n * @param reversedStatusName\n * @param updated\n * @param user\n * @param fromStatus\n * @param toStatus\n * @param windowNo\n */\nprivate void buildDocActionMessage(ArrayList docActionValues, ArrayList docActionNames, String reversedStatusName, Timestamp updated, MUser user, String fromStatus, String toStatus, int windowNo) {\n String docAction = null;\n if (DocAction.STATUS_Completed.equals(toStatus)) {\n docAction = DocAction.ACTION_Complete;\n } else if (DocAction.STATUS_Approved.equals(toStatus)) {\n docAction = DocAction.ACTION_Approve;\n } else if (DocAction.STATUS_Voided.equals(toStatus)) {\n docAction = DocAction.ACTION_Void;\n } else if (DocAction.STATUS_Reversed.equals(toStatus)) {\n docAction = DocAction.ACTION_Reverse_Accrual;\n } else if (DocAction.STATUS_NotApproved.equals(toStatus)) {\n docAction = DocAction.ACTION_Reject;\n } else if (DocAction.STATUS_InProgress.equals(toStatus)) {\n if (DocAction.STATUS_Completed.equals(fromStatus)) {\n docAction = DocAction.ACTION_ReActivate;\n } else if (DocAction.STATUS_Drafted.equals(fromStatus) || DocAction.STATUS_Invalid.equals(fromStatus)) {\n docAction = DocAction.ACTION_Prepare;\n }\n } else if (DocAction.STATUS_Closed.equals(toStatus)) {\n docAction = DocAction.ACTION_Close;\n } else if (DocAction.STATUS_Invalid.equals(toStatus)) {\n docAction = DocAction.ACTION_Invalidate;\n }\n if (docAction == null)\n return;\n String docActionName = null;\n if (DocAction.ACTION_Reverse_Accrual.equals(docAction) || DocAction.ACTION_Reverse_Correct.equals(docAction)) {\n docActionName = reversedStatusName;\n } else {\n for (int i = 0; i < docActionValues.size(); i++) {\n if (docActionValues.get(i).equals(docAction)) {\n docActionName = docActionNames.get(i);\n break;\n }\n }\n }\n StringBuilder sb = new StringBuilder(\"\").append(docActionName).append(\"\").append(\" \").append(Env.getContext(Env.getCtx(), windowNo, \"_WinInfo_WindowName\", true));\n buildActivityMessage(updated, sb.toString(), user);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private void handleRequest(ServiceContext context, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response, String sUrl, String endPoint, String requestBody, boolean addPermissions, String selectionBucket, RelatedItemType[] relatedTypes) throws Exception {\n try {\n URL url = new URL(sUrl);\n // open communication between proxy and final host\n // all actions before the connection can be taken now\n HttpURLConnection connectionWithFinalHost = (HttpURLConnection) url.openConnection();\n try {\n connectionWithFinalHost.setRequestMethod(request.getMethod());\n // copy headers from client's request to request that will be send to the final host\n copyHeadersToConnection(request, connectionWithFinalHost);\n if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {\n String auth = username + \":\" + password;\n byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));\n String authHeaderValue = \"Basic \" + new String(encodedAuth);\n connectionWithFinalHost.setRequestProperty(\"Authorization\", authHeaderValue);\n }\n connectionWithFinalHost.setDoOutput(true);\n connectionWithFinalHost.getOutputStream().write(requestBody.getBytes(Constants.ENCODING));\n // connect to remote host\n // interactions with the resource are enabled now\n connectionWithFinalHost.connect();\n // send remote host's response to client\n String contentEncoding = getContentEncoding(connectionWithFinalHost.getHeaderFields());\n int code = connectionWithFinalHost.getResponseCode();\n if (code != 200) {\n InputStream errorDetails = \"gzip\".equalsIgnoreCase(contentEncoding) ? new GZIPInputStream(connectionWithFinalHost.getErrorStream()) : connectionWithFinalHost.getErrorStream();\n response.sendError(code, String.format(\"Error is: %s.\\nRequest:\\n%s.\\nError:\\n%s.\", connectionWithFinalHost.getResponseMessage(), requestBody, IOUtils.toString(errorDetails)));\n return;\n }\n // get content type\n String contentType = connectionWithFinalHost.getContentType();\n if (contentType == null) {\n response.sendError(HttpServletResponse.SC_FORBIDDEN, \"Host url has been validated by proxy but content type given by remote host is null\");\n return;\n }\n // content type has to be valid\n if (!isContentTypeValid(contentType)) {\n if (connectionWithFinalHost.getResponseMessage() != null) {\n if (connectionWithFinalHost.getResponseMessage().equalsIgnoreCase(\"Not Found\")) {\n // content type was not valid because it was a not found page (text/html)\n response.sendError(HttpServletResponse.SC_NOT_FOUND, \"Remote host not found\");\n return;\n }\n }\n response.sendError(HttpServletResponse.SC_FORBIDDEN, \"The content type of the remote host's response \\\"\" + contentType + \"\\\" is not allowed by the proxy rules\");\n return;\n }\n // copy headers from the remote server's response to the response to send to the client\n copyHeadersFromConnectionToResponse(response, connectionWithFinalHost, proxyHeadersIgnoreList);\n if (!contentType.split(\";\")[0].equals(\"application/json\")) {\n addPermissions = false;\n }\n final InputStream streamFromServer;\n final OutputStream streamToClient;\n if (contentEncoding == null || !addPermissions) {\n // A simple stream can do the job for data that is not in content encoded\n // but also for data content encoded with a known charset\n streamFromServer = connectionWithFinalHost.getInputStream();\n streamToClient = response.getOutputStream();\n } else if (\"gzip\".equalsIgnoreCase(contentEncoding)) {\n // the charset is unknown and the data are compressed in gzip\n // we add the gzip wrapper to be able to read/write the stream content\n streamFromServer = new GZIPInputStream(connectionWithFinalHost.getInputStream());\n streamToClient = new GZIPOutputStream(response.getOutputStream());\n } else if (\"deflate\".equalsIgnoreCase(contentEncoding)) {\n // same but with deflate\n streamFromServer = new DeflaterInputStream(connectionWithFinalHost.getInputStream());\n streamToClient = new DeflaterOutputStream(response.getOutputStream());\n } else {\n throw new UnsupportedOperationException(\"Please handle the stream when it is encoded in \" + contentEncoding);\n }\n try {\n processResponse(context, httpSession, streamFromServer, streamToClient, endPoint, selectionBucket, addPermissions, relatedTypes);\n streamToClient.flush();\n } finally {\n IOUtils.closeQuietly(streamFromServer);\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n } finally {\n connectionWithFinalHost.disconnect();\n }\n } catch (IOException e) {\n // connection problem with the host\n e.printStackTrace();\n throw new Exception(String.format(\"Failed to request Es at URL %s. \" + \"Check Es configuration.\", sUrl), e);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static void createAndFillCitationGroup(OOFrontend frontend, XTextDocument doc, List citationKeys, List> pageInfos, CitationType citationType, OOText citationText, XTextCursor position, OOBibStyle style, boolean insertSpaceAfter) throws NotRemoveableException, WrappedTargetException, PropertyVetoException, IllegalArgumentException, CreationException, NoDocumentException, IllegalTypeException{\r\n Objects.requireNonNull(pageInfos);\r\n if (pageInfos.size() != citationKeys.size()) {\r\n throw new IllegalArgumentException(\"pageInfos.size != citationKeys.size\");\r\n }\r\n CitationGroup group = frontend.createCitationGroup(doc, citationKeys, pageInfos, citationType, position, insertSpaceAfter);\r\n final boolean withText = citationType.withText();\r\n if (withText) {\r\n XTextCursor fillCursor = frontend.getFillCursorForCitationGroup(doc, group);\r\n UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style);\r\n frontend.cleanFillCursorForCitationGroup(doc, group);\r\n }\r\n position.collapseToEnd();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void publishUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, String entityType, String entityUUID, boolean diplayResource) {\n if (diplayResource) {\n saveUsageEvent(usageType, accountId, zoneId, resourceId, resourceName);\n publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public RelBuilder match(RexNode pattern, boolean strictStart, boolean strictEnd, Map patternDefinitions, Iterable measureList, RexNode after, Map> subsets, boolean allRows, Iterable partitionKeys, Iterable orderKeys, RexNode interval){\r\n final Registrar registrar = new Registrar(fields(), peek().getRowType().getFieldNames());\r\n final List fieldCollations = registrar.registerFieldCollations(orderKeys);\r\n final ImmutableBitSet partitionBitSet = ImmutableBitSet.of(registrar.registerExpressions(partitionKeys));\r\n final RelDataTypeFactory.Builder typeBuilder = cluster.getTypeFactory().builder();\r\n for (RexNode partitionKey : partitionKeys) {\r\n typeBuilder.add(partitionKey.toString(), partitionKey.getType());\r\n }\r\n if (allRows) {\r\n for (RexNode orderKey : orderKeys) {\r\n if (!typeBuilder.nameExists(orderKey.toString())) {\r\n typeBuilder.add(orderKey.toString(), orderKey.getType());\r\n }\r\n }\r\n final RelDataType inputRowType = peek().getRowType();\r\n for (RelDataTypeField fs : inputRowType.getFieldList()) {\r\n if (!typeBuilder.nameExists(fs.getName())) {\r\n typeBuilder.add(fs);\r\n }\r\n }\r\n }\r\n final ImmutableMap.Builder measures = ImmutableMap.builder();\r\n for (RexNode measure : measureList) {\r\n List operands = ((RexCall) measure).getOperands();\r\n String alias = operands.get(1).toString();\r\n typeBuilder.add(alias, operands.get(0).getType());\r\n measures.put(alias, operands.get(0));\r\n }\r\n final RelNode match = struct.matchFactory.createMatch(peek(), pattern, typeBuilder.build(), strictStart, strictEnd, patternDefinitions, measures.build(), after, subsets, allRows, partitionBitSet, RelCollations.of(fieldCollations), interval);\r\n stack.push(new Frame(match));\r\n return this;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Count importEntity(final Workbook workbook, final List glAccounts, final List glTransactions, final List credits, final List debits, final boolean flagForOpBal, final String locale, final String dateFormat) {\n Sheet chartOfAccountsSheet = workbook.getSheet(TemplatePopulateImportConstants.CHART_OF_ACCOUNTS_SHEET_NAME);\n GsonBuilder gsonBuilder = GoogleGsonSerializerHelper.createGsonBuilder();\n gsonBuilder.registerTypeAdapter(EnumOptionData.class, new EnumOptionDataIdSerializer());\n gsonBuilder.registerTypeAdapter(CodeValueData.class, new CodeValueDataIdSerializer());\n gsonBuilder.registerTypeAdapter(LocalDate.class, new DateSerializer(dateFormat));\n gsonBuilder.registerTypeAdapter(CurrencyData.class, new CurrencyDateCodeSerializer());\n int successCount = 0;\n int errorCount = 0;\n String errorMessage = \"\";\n if (glAccounts != null) {\n for (GLAccountData glAccount : glAccounts) {\n try {\n String payload = gsonBuilder.create().toJson(glAccount);\n final CommandWrapper commandRequest = //\n new CommandWrapperBuilder().//\n createGLAccount().withJson(//\n payload).//\n build();\n commandsSourceWritePlatformService.logCommandSource(commandRequest);\n successCount++;\n Cell statusCell = chartOfAccountsSheet.getRow(glAccount.getRowIndex()).createCell(ChartOfAcountsConstants.STATUS_COL);\n statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);\n statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN));\n } catch (RuntimeException ex) {\n errorCount++;\n LOG.error(\"Problem occurred in importEntity function\", ex);\n errorMessage = ImportHandlerUtils.getErrorMessage(ex);\n ImportHandlerUtils.writeErrorMessage(chartOfAccountsSheet, glAccount.getRowIndex(), errorMessage, ChartOfAcountsConstants.STATUS_COL);\n }\n }\n if (flagForOpBal) {\n try {\n readExcelFileForOpBal(workbook, glTransactions, credits, debits, locale, dateFormat);\n JournalEntryData transaction = glTransactions.get(glTransactions.size() - 1);\n String payload = gsonBuilder.create().toJson(transaction);\n final CommandWrapper commandRequest = new CommandWrapperBuilder().defineOpeningBalanceForJournalEntry().withJson(payload).build();\n commandsSourceWritePlatformService.logCommandSource(commandRequest);\n successCount++;\n Cell statusCell = chartOfAccountsSheet.getRow(1).createCell(ChartOfAcountsConstants.STATUS_COL);\n statusCell.setCellValue(TemplatePopulateImportConstants.STATUS_CELL_IMPORTED);\n statusCell.setCellStyle(ImportHandlerUtils.getCellStyle(workbook, IndexedColors.LIGHT_GREEN));\n } catch (RuntimeException ex) {\n errorCount++;\n LOG.error(\"Problem occurred in importEntity function\", ex);\n errorMessage = ImportHandlerUtils.getErrorMessage(ex);\n ImportHandlerUtils.writeErrorMessage(chartOfAccountsSheet, 1, errorMessage, ChartOfAcountsConstants.STATUS_COL);\n }\n }\n chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);\n ImportHandlerUtils.writeString(ChartOfAcountsConstants.STATUS_COL, chartOfAccountsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER);\n return Count.instance(successCount, errorCount);\n }\n chartOfAccountsSheet.setColumnWidth(ChartOfAcountsConstants.STATUS_COL, TemplatePopulateImportConstants.SMALL_COL_SIZE);\n ImportHandlerUtils.writeString(ChartOfAcountsConstants.STATUS_COL, chartOfAccountsSheet.getRow(TemplatePopulateImportConstants.ROWHEADER_INDEX), TemplatePopulateImportConstants.STATUS_COLUMN_HEADER);\n return Count.instance(successCount, errorCount);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Invoke this method to preempt container based on resToObtain.\n *\n * @param rc\n * resource calculator\n * @param context\n * preemption context\n * @param resourceToObtainByPartitions\n * map to hold resource to obtain per partition\n * @param rmContainer\n * container\n * @param clusterResource\n * total resource\n * @param preemptMap\n * map to hold preempted containers\n * @param totalPreemptionAllowed\n * total preemption allowed per round\n * @param conservativeDRF\n * should we do conservativeDRF preemption or not.\n * When true:\n * stop preempt container when any major resource type\n * {@literal <=} 0 for to-preempt.\n * This is default preemption behavior of intra-queue preemption\n * When false:\n * stop preempt container when: all major resource type\n * {@literal <=} 0 for to-preempt.\n * This is default preemption behavior of inter-queue preemption\n * @param curCandidates RMContainer Set.\n * @return should we preempt rmContainer. If we should, deduct from\n * resourceToObtainByPartition\n */\npublic static boolean tryPreemptContainerAndDeductResToObtain(ResourceCalculator rc, CapacitySchedulerPreemptionContext context, Map resourceToObtainByPartitions, RMContainer rmContainer, Resource clusterResource, Map> preemptMap, Map> curCandidates, Resource totalPreemptionAllowed, boolean conservativeDRF) {\n ApplicationAttemptId attemptId = rmContainer.getApplicationAttemptId();\n // We will not account resource of a container twice or more\n if (preemptMapContains(preemptMap, attemptId, rmContainer)) {\n return false;\n }\n String nodePartition = getPartitionByNodeId(context, rmContainer.getAllocatedNode());\n Resource toObtainByPartition = resourceToObtainByPartitions.get(nodePartition);\n if (null == toObtainByPartition) {\n return false;\n }\n // If a toObtain resource type == 0, set it to -1 to avoid 0 resource\n // type affect following doPreemption check: isAnyMajorResourceZero\n for (ResourceInformation ri : toObtainByPartition.getResources()) {\n if (ri.getValue() == 0) {\n ri.setValue(-1);\n }\n }\n if (rc.isAnyMajorResourceAboveZero(toObtainByPartition) && Resources.fitsIn(rc, rmContainer.getAllocatedResource(), totalPreemptionAllowed)) {\n boolean doPreempt;\n // How much resource left after preemption happen.\n Resource toObtainAfterPreemption = Resources.subtract(toObtainByPartition, rmContainer.getAllocatedResource());\n if (conservativeDRF) {\n doPreempt = !rc.isAnyMajorResourceZeroOrNegative(toObtainByPartition);\n } else {\n // When we want to do more aggressive preemption, we will do preemption\n // only if:\n // - The preempt of the container makes positive contribution to the\n // to-obtain resource. Positive contribution means any positive\n // resource type decreases.\n //\n // This is example of positive contribution:\n // * before: <30, 10, 5>, after <20, 10, -10>\n // But this not positive contribution:\n // * before: <30, 10, 0>, after <30, 10, -15>\n doPreempt = Resources.lessThan(rc, clusterResource, Resources.componentwiseMax(toObtainAfterPreemption, Resources.none()), Resources.componentwiseMax(toObtainByPartition, Resources.none()));\n }\n if (!doPreempt) {\n return false;\n }\n Resources.subtractFrom(toObtainByPartition, rmContainer.getAllocatedResource());\n Resources.subtractFrom(totalPreemptionAllowed, rmContainer.getAllocatedResource());\n // When we have no more resource need to obtain, remove from map.\n if (Resources.lessThanOrEqual(rc, clusterResource, toObtainByPartition, Resources.none())) {\n resourceToObtainByPartitions.remove(nodePartition);\n }\n // Add to preemptMap\n addToPreemptMap(preemptMap, curCandidates, attemptId, rmContainer);\n return true;\n }\n return false;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Upload a new file to parent folder.\n *\n * @param parentFolderId - the id of parent folder.\n * @param content - a stream containing contents of the file to upload.\n * @param fileName the name to give the uploaded file.\n * @param created - the content created date that will be given to the uploaded file.\n * @param modified - the content modified date that will be given to the uploaded file.\n * @param size - the size of the file's content used for monitoring the upload's progress.\n * @param check - if the file name is already used, call the uploadNewVersion instead.\n * @param listener - a listener for monitoring the upload's progress.\n * @return The uploaded file.\n */\npublic BoxFile uploadFile(String parentFolderId, InputStream content, String fileName, Date created, Date modified, Long size, Boolean check, ProgressListener listener) {\n try {\n LOG.debug(\"Uploading file with name '{}}' to parent_folder(id={}})\", fileName, parentFolderId);\n BoxHelper.notNull(parentFolderId, BoxHelper.PARENT_FOLDER_ID);\n BoxHelper.notNull(content, BoxHelper.CONTENT);\n BoxHelper.notNull(fileName, BoxHelper.FILE_NAME);\n BoxFile boxFile = null;\n boolean uploadNewFile = true;\n if (check != null && check) {\n BoxFolder folder = null;\n try {\n folder = new BoxFolder(boxConnection, parentFolderId);\n // check if the file can be uploaded\n // otherwise upload a new revision of the existing file\n folder.canUpload(fileName, 0);\n } catch (BoxAPIResponseException boxException) {\n // https://developer.box.com/en/reference/options-files-content/\n // error 409, filename exists, get the file info to upload a new revision\n if (409 == boxException.getResponseCode()) {\n // the box search api relies on a folder index to search for items, however our tests\n // noticed the folder (box service) can take 11 minutes to reindex\n // for a recently uploaded file, the folder search will return empty as the file was not indexed yet.\n // see https://community.box.com/t5/Platform-and-Development-Forum/Box-Search-Delay/m-p/40072\n // this check operation uses the folder list item as fallback mechanism to check if the file really exists\n // it is slower than the search api, but reliable\n // for faster results, we recommend the folder to contain no more than 500 items\n // otherwise it can take more time to iterate over all items to check if the filename exists\n // display a WARN if the delay is higher than 5s\n final StopWatch watch = new StopWatch();\n int delayLimit = 5;\n boolean exists = false;\n BoxItem.Info existingFile = null;\n if (folder != null) {\n // returns only the name and type fields of each folder item\n for (BoxItem.Info itemInfo : folder.getChildren(\"name\", BoxFolder.SortDirection.ASC, \"name\", \"type\")) {\n // check if the filename exists\n exists = \"file\".equals(itemInfo.getType()) && fileName.equals(itemInfo.getName());\n if (exists) {\n existingFile = itemInfo;\n break;\n }\n }\n }\n long elapsed = watch.taken();\n if (elapsed > delayLimit) {\n LOG.warn(\"The upload operation, checks if the file exists by using the Box list folder, however it took {}\" + \" seconds to verify, try to reduce the size of the folder items for faster results.\", elapsed);\n }\n if (exists) {\n boxFile = uploadNewFileVersion(existingFile.getID(), content, modified, size, listener);\n uploadNewFile = false;\n }\n } else {\n throw boxException;\n }\n }\n }\n if (uploadNewFile) {\n BoxFolder parentFolder = new BoxFolder(boxConnection, parentFolderId);\n FileUploadParams uploadParams = new FileUploadParams();\n uploadParams.setName(fileName);\n uploadParams.setContent(content);\n if (created != null) {\n uploadParams.setCreated(created);\n }\n if (modified != null) {\n uploadParams.setModified(modified);\n }\n if (size != null) {\n uploadParams.setSize(size);\n }\n if (listener != null) {\n uploadParams.setProgressListener(listener);\n }\n boxFile = parentFolder.uploadFile(uploadParams).getResource();\n }\n return boxFile;\n } catch (BoxAPIException e) {\n throw new RuntimeCamelException(BoxHelper.buildBoxApiErrorMessage(e), e);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "/**\n *

Reference Page

\n *

\n * Specifies a two-dimensional texture image.\n *\n * @param target the texture target.\n * @param level the level-of-detail number.\n * @param internalFormat the texture internal format.\n * @param width the texture width.\n * @param height the texture height.\n * @param border the texture border width.\n * @param format the texel data format.\n * @param type the texel data type.\n * @param data the texel data.\n */\npublic void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, String userUUID, User.Source source);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "protected static void setMapperConf(boolean isMap, Configuration jobConf, Class inputKeyClass, Class inputValueClass, Class outputKeyClass, Class outputValueClass, Configuration mapperConf, int index, String prefix) {\n // if the Mapper does not have a configuration, create an empty one\n if (mapperConf == null) {\n // using a Configuration without defaults to make it lightweight.\n // still the chain's conf may have all defaults and this conf is\n // overlapped to the chain configuration one.\n mapperConf = new Configuration(true);\n }\n // store the input/output classes of the mapper in the mapper conf\n mapperConf.setClass(MAPPER_INPUT_KEY_CLASS, inputKeyClass, Object.class);\n mapperConf.setClass(MAPPER_INPUT_VALUE_CLASS, inputValueClass, Object.class);\n mapperConf.setClass(MAPPER_OUTPUT_KEY_CLASS, outputKeyClass, Object.class);\n mapperConf.setClass(MAPPER_OUTPUT_VALUE_CLASS, outputValueClass, Object.class);\n // serialize the mapper configuration in the chain configuration.\n Stringifier stringifier = new DefaultStringifier(jobConf, Configuration.class);\n try {\n jobConf.set(prefix + CHAIN_MAPPER_CONFIG + index, stringifier.toString(new Configuration(mapperConf)));\n } catch (IOException ioEx) {\n throw new RuntimeException(ioEx);\n }\n // increment the chain counter\n jobConf.setInt(prefix + CHAIN_MAPPER_SIZE, index + 1);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static String getPDBString(boolean web, char c1, char c2, boolean similar, String m, String sm, String dm, String qg){\r\n if (c1 == c2)\r\n return web ? \"\" + m + \"\" : m;\r\n else if (similar)\r\n return web ? \"\" + sm + \"\" : sm;\r\n else if (c1 == '-' || c2 == '-')\r\n return web ? \"\" + dm + \"\" : dm;\r\n else\r\n return web ? \"\" + qg + \"\" : qg;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query8Def query(String name, Class type1, Class type2, Class type3, Class type4, Class type5, Class type6, Class type7, Class type8){\r\n return new Query8DefImpl<>(VIEW_BUILDER, name, type1, type2, type3, type4, type5, type6, type7, type8);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateDbNameForTable(Statement stmt, String tableName, String tableColumnName, String fromCat, String toCat, String fromDb, String toDb, String hiveTblName) throws HiveMetaException, SQLException {\n String update = String.format(schemaTool.quote(UPDATE_DB_NAME_STMT), tableName, toCat, toDb, fromCat, fromDb, tableColumnName, hiveTblName);\n LOG.debug(\"Going to run \" + update);\n int numUpdated = stmt.executeUpdate(update);\n if (numUpdated > 1 || numUpdated < 0) {\n throw new HiveMetaException(\"Failed to properly update the \" + tableName + \" table. Expected to update 1 row but instead updated \" + numUpdated);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static Query9Def query(String pkg, String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name, Class type6, String arg6name, Class type7, String arg7name, Class type8, String arg8name, Class type9, String arg9name){\r\n return new Query9DefImpl<>(VIEW_BUILDER, pkg, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name, type6, arg6name, type7, arg7name, type8, arg8name, type9, arg9name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public VariableResolverFactory getFactory(final Object knowledgeHelper, final Declaration[] prevDecl, final Rule rule, final FactHandle rightHandle, final BaseTuple tuple, final Object[] otherVars, final ValueResolver valueResolver, final GlobalResolver globals){\r\n VariableResolverFactory factory = createFactory();\r\n updateFactory(knowledgeHelper, prevDecl, rule, rightHandle, rightHandle != null ? rightHandle.getObject() : null, tuple, otherVars, valueResolver, globals, factory);\r\n return factory;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n *

\n * Replaces the row key by the values of the column with the given name and appends a new column with the old key\n * values if the newColName variable is a non empty String.\n *

\n *

\n * Call the {@link RowKeyUtil2#getDuplicatesCounter()} and {@link RowKeyUtil2#getMissingValueCounter()} methods to\n * get information about the replaced duplicates and missing values after this method is completed.\n *

\n * @param inData in data rows a {@link RowInput}\n * @param outData output as {@link RowOutput}\n * @param exec the {@link ExecutionContext} to check for cancel and to provide status messages\n * @param selRowKeyColName the name of the column which should replace the row key or null if a new one\n * should be created\n * @param appendColumn true if a new column should be created\n * @param newColSpec the {@link DataColumnSpec} of the new column or null if no column should be\n * created at all\n * @param ensureUniqueness if set to true the method ensures the uniqueness of the row key even if the\n * values of the selected row aren't unique\n * @param replaceMissingVals if set to true the method replaces missing values with ?\n * @param removeRowKeyCol removes the selected row key column if set to true\n * @param hiliteMap true if a map should be maintained that maps the new row id to the old row id\n * @param totalNoOfOutColumns number of columns in the output table\n * @param totalNoOfRows number of rows in the data table, -1 if not available\n * @throws Exception if the cancel button was pressed or the input data isn't valid.\n * @since 3.1\n */\nvoid changeRowKey(final RowInput inData, final RowOutput outData, final ExecutionContext exec, final String selRowKeyColName, final boolean appendColumn, final DataColumnSpec newColSpec, final boolean ensureUniqueness, final boolean replaceMissingVals, final boolean removeRowKeyCol, final boolean hiliteMap, final int totalNoOfOutColumns, final int totalNoOfRows) throws Exception {\n LOGGER.debug(\"Entering changeRowKey(inData, exec, selRowKeyColName, \" + \"newColName) of class RowKeyUtil.\");\n final DataTableSpec inSpec = inData.getDataTableSpec();\n final int newRowKeyColIdx;\n if (selRowKeyColName != null) {\n newRowKeyColIdx = inSpec.findColumnIndex(selRowKeyColName);\n if (newRowKeyColIdx < 0) {\n throw new InvalidSettingsException(\"Column name not found.\");\n }\n } else {\n newRowKeyColIdx = -1;\n }\n if (hiliteMap) {\n m_hiliteMapping = new HashMap>(totalNoOfRows);\n }\n final Map vals = new HashMap(totalNoOfRows > 0 ? totalNoOfRows : 100);\n final double progressPerRow = 1.0 / totalNoOfRows;\n //update the progress monitor every percent\n final int checkPoint = Math.max((totalNoOfRows / 1000), 1);\n int rowCounter = 0;\n exec.setProgress(0.0, \"Processing data...\");\n m_missingValueCounter = 0;\n m_duplicatesCounter = 0;\n DataRow row;\n while ((row = inData.poll()) != null) {\n rowCounter++;\n final DataCell[] cells = new DataCell[totalNoOfOutColumns];\n int newCellCounter = 0;\n for (int i = 0, length = inSpec.getNumColumns(); i < length; i++) {\n if (removeRowKeyCol && i == newRowKeyColIdx) {\n continue;\n }\n cells[newCellCounter++] = row.getCell(i);\n }\n if (appendColumn) {\n cells[totalNoOfOutColumns - 1] = new StringCell(row.getKey().getString());\n }\n final RowKey newKeyVal;\n if (newRowKeyColIdx >= 0) {\n final DataCell keyCell = row.getCell(newRowKeyColIdx);\n String key = null;\n if (keyCell.isMissing()) {\n if (replaceMissingVals) {\n key = MISSING_VALUE_REPLACEMENT;\n m_missingValueCounter++;\n } else {\n throw new InvalidSettingsException(\"Missing value found in row \" + rowCounter);\n }\n } else {\n key = keyCell.toString();\n }\n if (ensureUniqueness) {\n if (vals.containsKey(key)) {\n if (!keyCell.isMissing()) {\n m_duplicatesCounter++;\n }\n StringBuilder uniqueKey = new StringBuilder(key);\n final MutableInteger index = vals.get(uniqueKey.toString());\n while (vals.containsKey(uniqueKey.toString())) {\n index.inc();\n uniqueKey = new StringBuilder(key);\n uniqueKey.append(\"(\");\n uniqueKey.append(index.toString());\n uniqueKey.append(\")\");\n }\n key = uniqueKey.toString();\n }\n //put the current key which is new into the values map\n final MutableInteger index = new MutableInteger(0);\n vals.put(key, index);\n }\n newKeyVal = new RowKey(key);\n } else {\n newKeyVal = RowKey.createRowKey(rowCounter - 1);\n }\n final DefaultRow newRow = new DefaultRow(newKeyVal, cells);\n outData.push(newRow);\n if (hiliteMap) {\n final Set oldKeys = new HashSet(1);\n oldKeys.add(row.getKey());\n m_hiliteMapping.put(newKeyVal, oldKeys);\n }\n exec.checkCanceled();\n if (rowCounter % checkPoint == 0) {\n if (totalNoOfRows > 0) {\n exec.setProgress(progressPerRow * rowCounter, rowCounter + \" rows of \" + totalNoOfRows + \" rows processed.\");\n } else {\n exec.setProgress(progressPerRow * rowCounter, rowCounter + \" rows processed.\");\n }\n }\n }\n exec.setProgress(1.0, \"Finished\");\n outData.close();\n}", "smellKey": "S107", "smellId": null, "repo": "KNIME_knime-base", "language": "java"} {"function": "@Nullable\npublic static Geometry ST_MakePolygon(Geometry shell, Geometry hole0, Geometry hole1, Geometry hole2, Geometry hole3, Geometry hole4, Geometry hole5, Geometry hole6, Geometry hole7, Geometry hole8){\r\n return makePolygon(shell, hole0, hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "// vmdkDatastorePath: [datastore name] vmdkFilePath\npublic static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, VirtualDisk device, int controllerKey, String[] vmdkDatastorePathChain, ManagedObjectReference morDs, int deviceNumber, int contextNumber, Long maxIops) throws Exception {\n LOGGER.debug(LogUtils.logGsonWithoutException(\"Trying to prepare disk device to virtual machine [%s], using the following details: Virtual device [%s], \" + \"ManagedObjectReference [%s], ControllerKey [%s], VMDK path chain [%s], DeviceNumber [%s], ContextNumber [%s] and max IOPS [%s].\", vmMo, device, morDs, controllerKey, vmdkDatastorePathChain, deviceNumber, contextNumber, maxIops));\n assert (vmdkDatastorePathChain != null);\n assert (vmdkDatastorePathChain.length >= 1);\n VirtualDisk disk;\n VirtualDiskFlatVer2BackingInfo backingInfo;\n if (device != null) {\n disk = device;\n backingInfo = (VirtualDiskFlatVer2BackingInfo) disk.getBacking();\n } else {\n disk = new VirtualDisk();\n backingInfo = new VirtualDiskFlatVer2BackingInfo();\n backingInfo.setDatastore(morDs);\n backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.value());\n disk.setBacking(backingInfo);\n int ideControllerKey = vmMo.getIDEDeviceControllerKey();\n if (controllerKey < 0)\n controllerKey = ideControllerKey;\n if (deviceNumber < 0) {\n deviceNumber = vmMo.getNextDeviceNumber(controllerKey);\n }\n disk.setControllerKey(controllerKey);\n disk.setKey(-contextNumber);\n disk.setUnitNumber(deviceNumber);\n if (maxIops != null && maxIops > 0) {\n LOGGER.debug(LogUtils.logGsonWithoutException(\"Defining [%s] as the max IOPS of disk [%s].\", maxIops, disk));\n StorageIOAllocationInfo storageIOAllocationInfo = new StorageIOAllocationInfo();\n storageIOAllocationInfo.setLimit(maxIops);\n disk.setStorageIOAllocation(storageIOAllocationInfo);\n }\n VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo();\n connectInfo.setConnected(true);\n connectInfo.setStartConnected(true);\n disk.setConnectable(connectInfo);\n }\n backingInfo.setFileName(vmdkDatastorePathChain[0]);\n if (vmdkDatastorePathChain.length > 1) {\n String[] parentDisks = Arrays.copyOfRange(vmdkDatastorePathChain, 1, vmdkDatastorePathChain.length);\n setParentBackingInfo(backingInfo, morDs, parentDisks);\n }\n LOGGER.debug(LogUtils.logGsonWithoutException(\"Prepared disk device, to attach to virtual machine [%s], has the following details: Virtual device [%s], \" + \"ManagedObjectReference [%s], ControllerKey [%s], VMDK path chain [%s], DeviceNumber [%s], ContextNumber [%s] and max IOPS [%s], is: [%s].\", vmMo, device, morDs, controllerKey, vmdkDatastorePathChain, deviceNumber, contextNumber, maxIops, disk));\n return disk;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private static Task alterSinglePartition(ImportTableDesc tblDesc, Table table, Warehouse wh, AlterTableAddPartitionDesc addPartitionDesc, ReplicationSpec replicationSpec, org.apache.hadoop.hive.ql.metadata.Partition ptn, EximUtil.SemanticAnalyzerWrapperContext x, boolean isReplication, String dumpRoot, ReplicationMetricCollector metricCollector) throws MetaException, IOException, HiveException {\n if ((replicationSpec != null) && (replicationSpec.isInReplicationScope())) {\n addPartitionDesc.setReplicationSpec(replicationSpec);\n }\n AlterTableAddPartitionDesc.PartitionDesc partSpec = addPartitionDesc.getPartitions().get(0);\n if (ptn == null) {\n fixLocationInPartSpec(tblDesc, table, wh, replicationSpec, partSpec, x);\n } else if (!externalTablePartition(tblDesc, replicationSpec)) {\n // use existing location\n partSpec.setLocation(ptn.getLocation());\n }\n return TaskFactory.get(new DDLWork(x.getInputs(), x.getOutputs(), addPartitionDesc, isReplication, dumpRoot, metricCollector), x.getConf());\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void implementGuestNetwork(ArrayList cmdList, GuestNetworkType type, Long publicVlanTag, String publicIp, long privateVlanTag, String privateGateway, String privateSubnet, long privateCidrNumber) throws ExecutionException {\n privateSubnet = privateSubnet + \"/\" + privateCidrNumber;\n managePrivateInterface(cmdList, PaloAltoPrimative.ADD, privateVlanTag, privateGateway + \"/\" + privateCidrNumber);\n if (type.equals(GuestNetworkType.SOURCE_NAT)) {\n managePublicInterface(cmdList, PaloAltoPrimative.ADD, publicVlanTag, publicIp + \"/32\", privateVlanTag);\n manageSrcNatRule(cmdList, PaloAltoPrimative.ADD, type, publicVlanTag, publicIp + \"/32\", privateVlanTag, privateGateway + \"/\" + privateCidrNumber);\n manageNetworkIsolation(cmdList, PaloAltoPrimative.ADD, privateVlanTag, privateSubnet, privateGateway);\n }\n String msg = \"Implemented guest network with type \" + type + \". Guest VLAN tag: \" + privateVlanTag + \", guest gateway: \" + privateGateway + \"/\" + privateCidrNumber;\n msg += type.equals(GuestNetworkType.SOURCE_NAT) ? \", source NAT IP: \" + publicIp : \"\";\n logger.debug(msg);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public void createBins(GraphReadMethods graph, GraphElementType elementType, String attribute, Map bins, int[] binElements, ElementSet filter, BinFormatter formatter, PluginParameters binFormatterParameters) {\n if (representative != null) {\n createElementBins(graph, representative, bin.create(), elementType, attribute, bins, binElements, filter, formatter, binFormatterParameters);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": " static QueueEntry create(ByteBuf entry, boolean ackBeforeSync, long ledgerId, long entryId, WriteCallback cb, Object ctx, long enqueueTime, OpStatsLogger journalAddEntryStats, Counter journalCbQueueSize, Counter callbackTime){\r\n QueueEntry qe = RECYCLER.get();\r\n qe.entry = entry;\r\n qe.ackBeforeSync = ackBeforeSync;\r\n qe.cb = cb;\r\n qe.ctx = ctx;\r\n qe.ledgerId = ledgerId;\r\n qe.entryId = entryId;\r\n qe.enqueueTime = enqueueTime;\r\n qe.journalAddEntryStats = journalAddEntryStats;\r\n qe.journalCbQueueSize = journalCbQueueSize;\r\n qe.callbackTime = callbackTime;\r\n return qe;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": " void addEntry(final long ledgerId, byte[] masterKey, final long entryId, ByteBufList toSend, WriteCallback cb, Object ctx, final int options, boolean allowFastFail, final EnumSet writeFlags){\r\n Object request = null;\r\n CompletionKey completionKey = null;\r\n if (useV2WireProtocol) {\r\n if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) {\r\n LOG.error(\"invalid writeflags {} for v2 protocol\", writeFlags);\r\n executor.executeOrdered(ledgerId, () -> {\r\n cb.writeComplete(BKException.Code.IllegalOpException, ledgerId, entryId, bookieId, ctx);\r\n });\r\n return;\r\n }\r\n completionKey = acquireV2Key(ledgerId, entryId, OperationType.ADD_ENTRY);\r\n request = BookieProtocol.AddRequest.create(BookieProtocol.CURRENT_PROTOCOL_VERSION, ledgerId, entryId, (short) options, masterKey, toSend);\r\n } else {\r\n final long txnId = getTxnId();\r\n completionKey = new V3CompletionKey(txnId, OperationType.ADD_ENTRY);\r\n BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE).setOperation(OperationType.ADD_ENTRY).setTxnId(txnId);\r\n if (((short) options & BookieProtocol.FLAG_HIGH_PRIORITY) == BookieProtocol.FLAG_HIGH_PRIORITY) {\r\n headerBuilder.setPriority(DEFAULT_HIGH_PRIORITY_VALUE);\r\n }\r\n ByteString body = null;\r\n if (toSend.hasArray()) {\r\n body = UnsafeByteOperations.unsafeWrap(toSend.array(), toSend.arrayOffset(), toSend.readableBytes());\r\n } else {\r\n for (int i = 0; i < toSend.size(); i++) {\r\n ByteString piece = UnsafeByteOperations.unsafeWrap(toSend.getBuffer(i).nioBuffer());\r\n body = (body == null) ? piece : body.concat(piece);\r\n }\r\n }\r\n AddRequest.Builder addBuilder = AddRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId).setMasterKey(UnsafeByteOperations.unsafeWrap(masterKey)).setBody(body);\r\n if (((short) options & BookieProtocol.FLAG_RECOVERY_ADD) == BookieProtocol.FLAG_RECOVERY_ADD) {\r\n addBuilder.setFlag(AddRequest.Flag.RECOVERY_ADD);\r\n }\r\n if (!writeFlags.isEmpty()) {\r\n addBuilder.setWriteFlags(WriteFlag.getWriteFlagsValue(writeFlags));\r\n }\r\n request = withRequestContext(Request.newBuilder()).setHeader(headerBuilder).setAddRequest(addBuilder).build();\r\n }\r\n putCompletionKeyValue(completionKey, acquireAddCompletion(completionKey, cb, ctx, ledgerId, entryId));\r\n final Channel c = channel;\r\n if (c == null) {\r\n errorOut(completionKey);\r\n ReferenceCountUtil.safeRelease(toSend);\r\n return;\r\n } else {\r\n writeAndFlush(c, completionKey, request, allowFastFail);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void writeAndEmptyDataSet(List paths, List dataTypes, List encodings, List compressors, List> propsList, List> tagsList, List> attributesList, List measurementAliasList, int retryTime) throws StatementExecutionException {\n try {\n session.createMultiTimeseries(paths, dataTypes, encodings, compressors, propsList, tagsList, attributesList, measurementAliasList);\n } catch (IoTDBConnectionException e) {\n if (retryTime > 0) {\n try {\n session.open();\n } catch (IoTDBConnectionException ex) {\n ioTPrinter.println(INSERT_CSV_MEET_ERROR_MSG + e.getMessage());\n }\n writeAndEmptyDataSet(paths, dataTypes, encodings, compressors, propsList, tagsList, attributesList, measurementAliasList, --retryTime);\n }\n } catch (StatementExecutionException e) {\n try {\n session.close();\n } catch (IoTDBConnectionException ex) {\n // do nothing\n }\n throw e;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "/**\n * Returns an aggregated log file belonging to a container.\n *\n * @param req the {@link HttpServletRequest}\n * @param containerIdStr container id\n * @param filename the name of the file\n * @param format the format of the response\n * @param size the size of bytes of the log file that should be returned\n * @param nmId NodeManager id\n * @param redirectedFromNode whether the request was redirected\n * @param clusterId the id of the cluster\n * @param manualRedirection whether to return a response with a Location\n * instead of an automatic redirection\n * @return {@link Response} object containing information about the logs\n */\npublic Response getLogFile(HttpServletRequest req, String containerIdStr, String filename, String format, String size, String nmId, boolean redirectedFromNode, String clusterId, boolean manualRedirection) {\n ContainerId containerId;\n try {\n containerId = ContainerId.fromString(containerIdStr);\n } catch (IllegalArgumentException ex) {\n return LogWebServiceUtils.createBadResponse(Status.NOT_FOUND, \"Invalid ContainerId: \" + containerIdStr);\n }\n LogAggregationFileControllerFactory factory = getOrCreateFactory();\n final long length = LogWebServiceUtils.parseLongParam(size);\n ApplicationId appId = containerId.getApplicationAttemptId().getApplicationId();\n BasicAppInfo appInfo;\n try {\n appInfo = appInfoProvider.getApp(req, appId.toString(), clusterId);\n } catch (Exception ex) {\n LOG.warn(\"Could not obtain appInfo object from provider.\", ex);\n return LogWebServiceUtils.sendStreamOutputResponse(factory, appId, null, null, containerIdStr, filename, format, length, false);\n }\n String appOwner = appInfo.getUser();\n if (Apps.isApplicationFinalState(appInfo.getAppState())) {\n // directly find logs from HDFS.\n return LogWebServiceUtils.sendStreamOutputResponse(factory, appId, appOwner, null, containerIdStr, filename, format, length, false);\n }\n if (LogWebServiceUtils.isRunningState(appInfo.getAppState())) {\n String nodeHttpAddress = null;\n if (nmId != null && !nmId.isEmpty()) {\n try {\n nodeHttpAddress = getNMWebAddressFromRM(nmId);\n } catch (Exception ex) {\n LOG.debug(\"Exception happened during obtaining NM web address \" + \"from RM.\", ex);\n }\n }\n if (nodeHttpAddress == null || nodeHttpAddress.isEmpty()) {\n try {\n nodeHttpAddress = appInfoProvider.getNodeHttpAddress(req, appId.toString(), containerId.getApplicationAttemptId().toString(), containerId.toString(), clusterId);\n } catch (Exception ex) {\n LOG.warn(\"Could not obtain node HTTP address from provider.\", ex);\n // output the aggregated logs\n return LogWebServiceUtils.sendStreamOutputResponse(factory, appId, appOwner, null, containerIdStr, filename, format, length, true);\n }\n // make sure nodeHttpAddress is not null and not empty. Otherwise,\n // we would only get aggregated logs instead of re-directing the\n // request.\n // If this is the redirect request from NM, we should not re-direct the\n // request back. Simply output the aggregated logs.\n if (nodeHttpAddress == null || nodeHttpAddress.isEmpty() || redirectedFromNode) {\n // output the aggregated logs\n return LogWebServiceUtils.sendStreamOutputResponse(factory, appId, appOwner, null, containerIdStr, filename, format, length, true);\n }\n }\n String uri = \"/\" + containerId.toString() + \"/logs/\" + filename;\n String resURI = JOINER.join(LogWebServiceUtils.getAbsoluteNMWebAddress(getConf(), nodeHttpAddress), NM_DOWNLOAD_URI_STR, uri);\n String query = req.getQueryString();\n if (query != null && !query.isEmpty()) {\n resURI += \"?\" + query;\n }\n if (manualRedirection) {\n return createLocationResponse(resURI, createEmptyStream());\n }\n Response.ResponseBuilder response = Response.status(HttpServletResponse.SC_TEMPORARY_REDIRECT);\n response.header(\"Location\", resURI);\n return response.build();\n } else {\n return LogWebServiceUtils.createBadResponse(Status.NOT_FOUND, \"The application is not at Running or Finished State.\");\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static Query10Def query(String pkg, String name, Class type1, Class type2, Class type3, Class type4, Class type5, Class type6, Class type7, Class type8, Class type9, Class type10){\r\n return new Query10DefImpl<>(VIEW_BUILDER, pkg, name, type1, type2, type3, type4, type5, type6, type7, type8, type9, type10);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private UserVm getCheckedUserVmResource(DataCenter zone, String hostName, String displayName, Account owner, Long diskOfferingId, Long diskSize, List networkList, List securityGroupIdList, String group, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Account caller, Map requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, Map datadiskTemplateToDiskOfferringMap, Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, VMTemplateVO template, HypervisorType hypervisorType, long accountId, ServiceOfferingVO offering, boolean isIso, Long rootDiskOfferingId, long volumesSize, long additionalDiskSize) throws ResourceAllocationException {\n if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {\n List resourceLimitHostTags = resourceLimitService.getResourceLimitHostTags(offering, template);\n try (CheckedReservation vmReservation = new CheckedReservation(owner, ResourceType.user_vm, resourceLimitHostTags, 1l, reservationDao, resourceLimitService);\n CheckedReservation cpuReservation = new CheckedReservation(owner, ResourceType.cpu, resourceLimitHostTags, Long.valueOf(offering.getCpu()), reservationDao, resourceLimitService);\n CheckedReservation memReservation = new CheckedReservation(owner, ResourceType.memory, resourceLimitHostTags, Long.valueOf(offering.getRamSize()), reservationDao, resourceLimitService)) {\n return getUncheckedUserVmResource(zone, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, httpmethod, userData, userDataId, userDataDetails, sshKeyPairs, caller, requestedIps, defaultIps, isDisplayVm, keyboard, affinityGroupIdList, customParameters, customId, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, vmType, template, hypervisorType, accountId, offering, isIso, rootDiskOfferingId, volumesSize, additionalDiskSize);\n } catch (ResourceAllocationException | CloudRuntimeException e) {\n throw e;\n } catch (Exception e) {\n logger.error(\"error during resource reservation and allocation\", e);\n throw new CloudRuntimeException(e);\n }\n } else {\n return getUncheckedUserVmResource(zone, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, httpmethod, userData, userDataId, userDataDetails, sshKeyPairs, caller, requestedIps, defaultIps, isDisplayVm, keyboard, affinityGroupIdList, customParameters, customId, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, vmType, template, hypervisorType, accountId, offering, isIso, rootDiskOfferingId, volumesSize, additionalDiskSize);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private static boolean remapJoinReferences(LoptMultiJoin multiJoin, int factor, List newJoinOrder, int newPos, int[] adjustments, int offset, int newOffset, boolean alwaysUseDefault){\r\n boolean needAdjust = false;\r\n int defaultAdjustment = -offset + newOffset;\r\n if (!alwaysUseDefault && multiJoin.isRightFactorInRemovableSelfJoin(factor) && (newPos != 0) && newJoinOrder.get(newPos - 1).equals(multiJoin.getOtherSelfJoinFactor(factor))) {\r\n int nLeftFields = multiJoin.getNumFieldsInJoinFactor(newJoinOrder.get(newPos - 1));\r\n for (int i = 0; i < multiJoin.getNumFieldsInJoinFactor(factor); i++) {\r\n Integer leftOffset = multiJoin.getRightColumnMapping(factor, i);\r\n if (leftOffset == null) {\r\n adjustments[i + offset] = defaultAdjustment;\r\n } else {\r\n adjustments[i + offset] = -(offset + i) + (newOffset - nLeftFields) + leftOffset;\r\n }\r\n if (adjustments[i + offset] != 0) {\r\n needAdjust = true;\r\n }\r\n }\r\n } else {\r\n if (defaultAdjustment != 0) {\r\n needAdjust = true;\r\n for (int i = 0; i < multiJoin.getNumFieldsInJoinFactor(newJoinOrder.get(newPos)); i++) {\r\n adjustments[i + offset] = defaultAdjustment;\r\n }\r\n }\r\n }\r\n return needAdjust;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Handle heartbeat from datanodes.\n */\npublic DatanodeCommand[] handleHeartbeat(DatanodeRegistration nodeReg, StorageReport[] reports, final String blockPoolId, long cacheCapacity, long cacheUsed, int xceiverCount, int xmitsInProgress, int failedVolumes, VolumeFailureSummary volumeFailureSummary, @Nonnull SlowPeerReports slowPeers, @Nonnull SlowDiskReports slowDisks) throws IOException {\n final DatanodeDescriptor nodeinfo;\n try {\n nodeinfo = getDatanode(nodeReg);\n } catch (UnregisteredNodeException e) {\n return new DatanodeCommand[] { RegisterCommand.REGISTER };\n }\n // Check if this datanode should actually be shutdown instead.\n if (nodeinfo != null && nodeinfo.isDisallowed()) {\n setDatanodeDead(nodeinfo);\n throw new DisallowedDatanodeException(nodeinfo);\n }\n if (nodeinfo == null || !nodeinfo.isRegistered()) {\n return new DatanodeCommand[] { RegisterCommand.REGISTER };\n }\n heartbeatManager.updateHeartbeat(nodeinfo, reports, cacheCapacity, cacheUsed, xceiverCount, failedVolumes, volumeFailureSummary);\n // If we are in safemode, do not send back any recovery / replication\n // requests. Don't even drain the existing queue of work.\n if (namesystem.isInSafeMode()) {\n return new DatanodeCommand[0];\n }\n // block recovery command\n final BlockRecoveryCommand brCommand = getBlockRecoveryCommand(blockPoolId, nodeinfo);\n if (brCommand != null) {\n return new DatanodeCommand[] { brCommand };\n }\n final List cmds = new ArrayList<>();\n // Allocate _approximately_ maxTransfers pending tasks to DataNode.\n // NN chooses pending tasks based on the ratio between the lengths of\n // replication and erasure-coded block queues.\n int replicationBlocks = nodeinfo.getNumberOfReplicateBlocks();\n int ecBlocksToBeReplicated = nodeinfo.getNumberOfECBlocksToBeReplicated();\n int ecBlocksToBeErasureCoded = nodeinfo.getNumberOfBlocksToBeErasureCoded();\n int totalBlocks = replicationBlocks + ecBlocksToBeReplicated + ecBlocksToBeErasureCoded;\n if (totalBlocks > 0) {\n int maxTransfers = blockManager.getMaxReplicationStreams() - xmitsInProgress;\n int maxECReplicatedTransfers;\n if (nodeinfo.isDecommissionInProgress()) {\n maxECReplicatedTransfers = blockManager.getReplicationStreamsHardLimit() - xmitsInProgress;\n } else {\n maxECReplicatedTransfers = maxTransfers;\n }\n int numReplicationTasks = (int) Math.ceil((double) replicationBlocks * maxTransfers / totalBlocks);\n int numEcReplicatedTasks = (int) Math.ceil((double) ecBlocksToBeReplicated * maxECReplicatedTransfers / totalBlocks);\n int numECReconstructedTasks = (int) Math.ceil((double) ecBlocksToBeErasureCoded * maxTransfers / totalBlocks);\n LOG.debug(\"Pending replication tasks: {} ec to be replicated tasks: {} \" + \"ec reconstruction tasks: {}.\", numReplicationTasks, numEcReplicatedTasks, numECReconstructedTasks);\n // check pending replication tasks\n List pendingReplicationList = nodeinfo.getReplicationCommand(numReplicationTasks);\n List pendingECReplicatedList = nodeinfo.getECReplicatedCommand(numEcReplicatedTasks);\n List pendingList = new ArrayList();\n if (pendingReplicationList != null && !pendingReplicationList.isEmpty()) {\n pendingList.addAll(pendingReplicationList);\n }\n if (pendingECReplicatedList != null && !pendingECReplicatedList.isEmpty()) {\n pendingList.addAll(pendingECReplicatedList);\n }\n if (!pendingList.isEmpty()) {\n // If the block is deleted, the block size will become\n // BlockCommand.NO_ACK (LONG.MAX_VALUE) . This kind of block we don't\n // need\n // to send for replication or reconstruction\n Iterator iterator = pendingList.iterator();\n while (iterator.hasNext()) {\n BlockTargetPair cmd = iterator.next();\n if (cmd.block != null && cmd.block.getNumBytes() == BlockCommand.NO_ACK) {\n // block deleted\n DatanodeStorageInfo.decrementBlocksScheduled(cmd.targets);\n iterator.remove();\n }\n }\n if (!pendingList.isEmpty()) {\n cmds.add(new BlockCommand(DatanodeProtocol.DNA_TRANSFER, blockPoolId, pendingList));\n }\n }\n // check pending erasure coding tasks\n List pendingECList = nodeinfo.getErasureCodeCommand(numECReconstructedTasks);\n if (pendingECList != null && !pendingECList.isEmpty()) {\n cmds.add(new BlockECReconstructionCommand(DNA_ERASURE_CODING_RECONSTRUCTION, pendingECList));\n }\n }\n // check block invalidation\n Block[] blks = nodeinfo.getInvalidateBlocks(blockInvalidateLimit);\n if (blks != null) {\n cmds.add(new BlockCommand(DatanodeProtocol.DNA_INVALIDATE, blockPoolId, blks));\n }\n // cache commands\n addCacheCommands(blockPoolId, nodeinfo, cmds);\n // key update command\n blockManager.addKeyUpdateCommand(cmds, nodeinfo);\n // check for balancer bandwidth update\n if (nodeinfo.getBalancerBandwidth() > 0) {\n cmds.add(new BalancerBandwidthCommand(nodeinfo.getBalancerBandwidth()));\n // set back to 0 to indicate that datanode has been sent the new value\n nodeinfo.setBalancerBandwidth(0);\n }\n Preconditions.checkNotNull(slowPeerTracker, \"slowPeerTracker should not be un-assigned\");\n if (slowPeerTracker.isSlowPeerTrackerEnabled()) {\n final Map slowPeersMap = slowPeers.getSlowPeers();\n if (!slowPeersMap.isEmpty()) {\n LOG.debug(\"DataNode {} reported slow peers: {}.\", nodeReg, slowPeersMap);\n for (Map.Entry slowNodeEntry : slowPeersMap.entrySet()) {\n slowPeerTracker.addReport(slowNodeEntry.getKey(), nodeReg.getIpcAddr(false), slowNodeEntry.getValue());\n }\n }\n }\n if (slowDiskTracker != null) {\n if (!slowDisks.getSlowDisks().isEmpty()) {\n LOG.debug(\"DataNode {} reported slow disks: {}.\", nodeReg, slowDisks.getSlowDisks());\n slowDiskTracker.addSlowDiskReport(nodeReg.getIpcAddr(false), slowDisks);\n }\n slowDiskTracker.checkAndUpdateReportIfNecessary();\n }\n if (!cmds.isEmpty()) {\n return cmds.toArray(new DatanodeCommand[cmds.size()]);\n }\n return new DatanodeCommand[0];\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Applies stylesheet according to ElementSetName and schema.\n *\n * @param context Service context\n * @param schemaManager schemamanager\n * @param schema schema\n * @param result result\n * @param outputSchema requested OutputSchema\n * @param elementSetName requested ElementSetName\n * @param resultType requested ResultTYpe\n * @param id metadata id\n * @return metadata\n * @throws InvalidParameterValueEx hmm\n */\npublic Element applyElementSetName(ServiceContext context, SchemaManager schemaManager, String schema, Element result, String outputSchema, ElementSetName elementSetName, ResultType resultType, String id, String displayLanguage) throws InvalidParameterValueEx {\n Path schemaDir = schemaManager.getSchemaCSWPresentDir(schema);\n Path styleSheet = schemaDir.resolve(outputSchema + \"-\" + elementSetName + \".xsl\");\n if (!Files.exists(styleSheet)) {\n context.warning(String.format(\"OutputSchema '%s' not supported for metadata with '%s' (%s). Corresponding XSL transformation '%s' does not exist. The record will not be returned in response.\", outputSchema, id, schema, styleSheet.toString()));\n return null;\n } else {\n Map params = new HashMap<>();\n params.put(\"lang\", displayLanguage);\n try {\n result = Xml.transform(result, styleSheet, params);\n } catch (Exception e) {\n context.error(\"Error while transforming metadata with id : \" + id + \" using \" + styleSheet);\n context.error(\" (C) StackTrace:\\n\" + Util.getStackTrace(e));\n return null;\n }\n return result;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "/**\n * Create the reduce sink descriptor.\n *\n * @param keyCols\n * The columns to be stored in the key\n * @param valueCols\n * The columns to be stored in the value\n * @param outputColumnNames\n * The output columns names\n * @param tag\n * The tag for this reducesink\n * @param numPartitionFields\n * The first numPartitionFields of keyCols will be partition columns.\n * If numPartitionFields=-1, then partition randomly.\n * @param numReducers\n * The number of reducers, set to -1 for automatic inference based on\n * input data size.\n * @param writeType Whether this is an Acid write, and if so whether it is insert, update,\n * or delete.\n * @return The reduceSinkDesc object.\n */\npublic static ReduceSinkDesc getReduceSinkDesc(List keyCols, List valueCols, List outputColumnNames, boolean includeKey, int tag, int numPartitionFields, int numReducers, AcidUtils.Operation writeType, NullOrdering defaultNullOrder) throws SemanticException {\n return getReduceSinkDesc(keyCols, keyCols.size(), valueCols, new ArrayList>(), includeKey ? outputColumnNames.subList(0, keyCols.size()) : new ArrayList(), includeKey ? outputColumnNames.subList(keyCols.size(), outputColumnNames.size()) : outputColumnNames, includeKey, tag, numPartitionFields, numReducers, writeType, defaultNullOrder);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * @param newRootPageAddr New root page address.\n * @param newRootId New root ID.\n * @param leftChildId Left child ID.\n * @param row Moved up row.\n * @param rowBytes Bytes.\n * @param rightChildId Right child ID.\n * @param pageSize Page size.\n * @param needRowBytes If we need row bytes back.\n * @return Row bytes.\n * @throws IgniteCheckedException If failed.\n */\npublic byte[] initNewRoot(long newRootPageAddr, long newRootId, long leftChildId, L row, byte[] rowBytes, long rightChildId, int pageSize, boolean needRowBytes, PageMetrics metrics) throws IgniteCheckedException {\n initNewPage(newRootPageAddr, newRootId, pageSize, metrics);\n setCount(newRootPageAddr, 1);\n setLeft(newRootPageAddr, 0, leftChildId);\n rowBytes = store(newRootPageAddr, 0, row, rowBytes, needRowBytes);\n setRight(newRootPageAddr, 0, rightChildId);\n return rowBytes;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * This is a lightweight representation of the legacy Jeeves XML processed by\n * XSLT. Only element required for the editor are created.\n */\nprivate void buildEditorForm(String tab, HttpSession session, Map allRequestParams, HttpServletRequest request, Element xml, String schema, ServiceContext context, ApplicationContext applicationContext, boolean isEmbedded, boolean embedded, HttpServletResponse response) throws Exception {\n UserSession userSession = ApiUtils.getUserSession(session);\n Element root = buildResourceDocument(applicationContext, context, userSession);\n root.addContent(xml);\n Element gui = root.getChild(\"gui\");\n gui.addContent(new Element(\"currTab\").setText(tab));\n // This flag is used to generate top tool bar or not\n gui.addContent(new Element(\"reqService\").setText(embedded ? \"embedded\" : \"md.edit\"));\n String iso3langCode = languageUtils.getIso3langCode(request.getLocales());\n gui.addContent(new Element(\"language\").setText(iso3langCode));\n gui.addContent(getSchemaStrings(schema, context));\n Element requestParams = new Element(\"request\");\n for (Map.Entry e : allRequestParams.entrySet()) {\n requestParams.addContent(new Element(e.getKey()).setText(e.getValue()));\n }\n root.addContent(requestParams);\n GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class);\n Path xslt = dataDirectory.getWebappDir().resolve(isEmbedded ? \"xslt/ui-metadata/edit/edit-embedded.xsl\" : \"xslt/ui-metadata/edit/edit.xsl\");\n Xml.transform(root, xslt, response.getOutputStream());\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static FastCheckPrecisionScaleStatus fastCheckPrecisionScale(int fastSignum, long fast0, long fast1, long fast2, int fastIntegerDigitCount, int fastScale, int maxPrecision, int maxScale) {\n if (fastSignum == 0) {\n return FastCheckPrecisionScaleStatus.NO_CHANGE;\n }\n final int maxIntegerDigitCount = maxPrecision - maxScale;\n if (fastIntegerDigitCount > maxIntegerDigitCount) {\n return FastCheckPrecisionScaleStatus.OVERFLOW;\n }\n if (fastScale > maxScale) {\n return FastCheckPrecisionScaleStatus.UPDATE_SCALE_DOWN;\n }\n return FastCheckPrecisionScaleStatus.NO_CHANGE;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "boolean handleSystemVMStart(long vmId, String privateIpAddress, String privateMacAddress, String privateNetMask, long dcId, long podId, String name, String vmType, String url);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public void asyncCreateLedger(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map customMetadata){\r\n if (writeQuorumSize < ackQuorumSize) {\r\n throw new IllegalArgumentException(\"Write quorum must be larger than ack quorum\");\r\n }\r\n closeLock.readLock().lock();\r\n try {\r\n if (closed) {\r\n cb.createComplete(BKException.Code.ClientClosedException, null, ctx);\r\n return;\r\n }\r\n new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, WriteFlag.NONE, clientStats).initiate();\r\n } finally {\r\n closeLock.readLock().unlock();\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": " Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, RestConfiguration configuration, Map parameters, boolean api) throws Exception{\r\n String path = basePath;\r\n if (uriTemplate != null) {\r\n if (uriTemplate.startsWith(\"/\")) {\r\n path = path + uriTemplate;\r\n } else {\r\n path = path + \"/\" + uriTemplate;\r\n }\r\n }\r\n path = FileUtil.stripLeadingSeparator(path);\r\n String scheme = \"http\";\r\n String host = \"\";\r\n int port = 0;\r\n RestConfiguration config = configuration;\r\n if (config == null) {\r\n config = CamelContextHelper.getRestConfiguration(getCamelContext(), \"netty-http\");\r\n }\r\n if (config.getScheme() != null) {\r\n scheme = config.getScheme();\r\n }\r\n if (config.getHost() != null) {\r\n host = config.getHost();\r\n }\r\n int num = config.getPort();\r\n if (num > 0) {\r\n port = num;\r\n }\r\n String contextPath = config.getContextPath();\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n contextPath = FileUtil.stripTrailingSeparator(contextPath);\r\n contextPath = FileUtil.stripLeadingSeparator(contextPath);\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n path = contextPath + \"/\" + path;\r\n }\r\n }\r\n if (ObjectHelper.isEmpty(host)) {\r\n host = RestComponentHelper.resolveRestHostName(host, config);\r\n }\r\n Map map = RestComponentHelper.initRestEndpointProperties(\"netty-http\", config);\r\n boolean cors = config.isEnableCORS();\r\n if (api) {\r\n map.put(\"matchOnUriPrefix\", \"true\");\r\n }\r\n RestComponentHelper.addHttpRestrictParam(map, verb, cors);\r\n String url = RestComponentHelper.createRestConsumerUrl(\"netty-http\", scheme, host, port, path, map);\r\n NettyHttpEndpoint endpoint = (NettyHttpEndpoint) camelContext.getEndpoint(url, parameters);\r\n Consumer consumer = endpoint.createConsumer(processor);\r\n if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {\r\n setProperties(camelContext, consumer, config.getConsumerProperties());\r\n }\r\n return consumer;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Map processVertices(final ImportDefinition definition, final GraphWriteMethods graph, final List data, final AttributeType attributeType, final boolean initialiseWithSchema, final boolean skipInvalidRows, final PluginInteraction interaction, final String source) throws InterruptedException, PluginException {\n final List attributeDefinitions = definition.getDefinitions(attributeType);\n addAttributes(graph, GraphElementType.VERTEX, attributeDefinitions);\n int currentRow = 0;\n int importedRows = 0;\n int skippedRow = 0;\n final Map results = new HashMap<>();\n final int totalRows = data.size() - definition.getFirstRow();\n final RowFilter filter = definition.getRowFilter();\n for (int i = definition.getFirstRow(); i < data.size(); i++) {\n interaction.setProgress(++currentRow, totalRows, \"Importing Vertices: \" + source, true);\n final String[] row = data.get(i);\n int vertexId = -1;\n try {\n if (filter == null || filter.passesFilter(i - 1, row)) {\n vertexId = graph.addVertex();\n for (final ImportAttributeDefinition attributeDefinition : attributeDefinitions) {\n attributeDefinition.setValue(graph, vertexId, row, (i - 1));\n }\n if (initialiseWithSchema && graph.getSchema() != null) {\n graph.getSchema().completeVertex(graph, vertexId);\n }\n // Count the number of processed rows to notify in the status message\n ++importedRows;\n }\n } catch (final DateTimeException | IllegalArgumentException | SecurityException ex) {\n if (skipInvalidRows) {\n if (vertexId != -1) {\n graph.removeVertex(vertexId);\n }\n ++skippedRow;\n } else {\n final PluginException plugEx = new PluginException(PluginNotificationLevel.ERROR, \"Unable to complete import due to error with data. \" + ex.getMessage() + \". The file can be imported if you select the Skip Invalid Rows checkbox next to the Import button.\");\n plugEx.setStackTrace(ex.getStackTrace());\n throw plugEx;\n }\n }\n }\n results.put(IMPORTED_ROWS, importedRows);\n results.put(SKIPPED_ROWS, skippedRow);\n return results;\n}", "smellKey": "S107", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "private VirtualMachineDiskInfo getMatchingExistingDiskWithVolumeDetails(VirtualMachineDiskInfoBuilder diskInfoBuilder, String volumePath, String chainInfo, boolean isManaged, String iScsiName, String datastoreUUID, VmwareHypervisorHost hyperHost, VmwareContext context) throws Exception {\n Pair dsNameAndFileName = getVMDiskInfo(volumePath, isManaged, iScsiName, datastoreUUID, hyperHost, context);\n String dsName = dsNameAndFileName.first();\n String diskBackingFileBaseName = dsNameAndFileName.second();\n VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(diskBackingFileBaseName, dsName);\n if (diskInfo != null) {\n logger.info(\"Found existing disk info from volume path: \" + volumePath);\n return diskInfo;\n } else {\n if (chainInfo != null) {\n VirtualMachineDiskInfo infoInChain = _gson.fromJson(chainInfo, VirtualMachineDiskInfo.class);\n if (infoInChain != null) {\n String[] disks = infoInChain.getDiskChain();\n if (disks.length > 0) {\n for (String diskPath : disks) {\n DatastoreFile file = new DatastoreFile(diskPath);\n diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(file.getFileBaseName(), dsName);\n if (diskInfo != null) {\n logger.info(\"Found existing disk from chain info: \" + diskPath);\n return diskInfo;\n }\n }\n }\n if (diskInfo == null) {\n diskInfo = diskInfoBuilder.getDiskInfoByDeviceBusName(infoInChain.getDiskDeviceBusName());\n if (diskInfo != null) {\n logger.info(\"Found existing disk from chain device bus information: \" + infoInChain.getDiskDeviceBusName());\n return diskInfo;\n }\n }\n }\n }\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static ConsequenceBuilder._18 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18){\r\n return new ConsequenceBuilder._18(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ImmutablePair, Set> updateRecordFieldListWithImports(List required, List recordFieldList, Map.Entry> field, Schema fieldSchema, NodeList schemaDocNodes, IdentifierToken fieldName, TypeDescriptorNode fieldTypeName, PrintStream outStream){\r\n MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(schemaDocNodes);\r\n Set imports = new HashSet<>();\r\n AnnotationNode constraintNode = generateConstraintNode(fieldName.text(), fieldSchema);\r\n MetadataNode metadataNode;\r\n boolean isConstraintSupport = constraintNode != null && fieldSchema.getNullable() != null && fieldSchema.getNullable() || (fieldSchema instanceof ComposedSchema && (fieldSchema.getOneOf() != null || fieldSchema.getAnyOf() != null));\r\n boolean nullable = GeneratorMetaData.getInstance().isNullable();\r\n if (nullable) {\r\n constraintNode = null;\r\n } else if (isConstraintSupport) {\r\n outStream.printf(\"WARNING: constraints in the OpenAPI contract will be ignored for the \" + \"field `%s`, as constraints are not supported on Ballerina union types%n\", fieldName.toString().trim());\r\n constraintNode = null;\r\n }\r\n if (constraintNode == null) {\r\n metadataNode = createMetadataNode(documentationNode, createEmptyNodeList());\r\n } else {\r\n metadataNode = createMetadataNode(documentationNode, createNodeList(constraintNode));\r\n }\r\n if (required != null) {\r\n setRequiredFields(required, recordFieldList, field, fieldSchema, fieldName, fieldTypeName, metadataNode);\r\n } else {\r\n RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null, fieldTypeName, fieldName, createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN));\r\n recordFieldList.add(recordFieldNode);\r\n }\r\n if (constraintNode != null) {\r\n ImportDeclarationNode constraintImport = GeneratorUtils.getImportDeclarationNode(BALLERINA, CONSTRAINT);\r\n constraintImport.toSourceCode();\r\n imports.add(constraintImport.toSourceCode());\r\n }\r\n return new ImmutablePair<>(recordFieldList, imports);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected long insertNic(Connection conn, long networkId, long instanceId, boolean running, String macAddress, String ipAddress, String netmask, String strategy, String gateway, String vnet, String guru, boolean defNic, int deviceId, String mode, String reservationId) throws SQLException {\n try (PreparedStatement pstmt = conn.prepareStatement(\"INSERT INTO nics (instance_id, network_id, mac_address, ip4_address, netmask, strategy, ip_type, broadcast_uri, mode, reserver_name, reservation_id, device_id, update_time, isolation_uri, ip6_address, default_nic, created, removed, state, gateway) \" + \"VALUES (?, ?, ?, ?, ?, ?, 'Ip4', ?, ?, ?, ?, ?, now(), ?, NULL, ?, now(), NULL, ?, ?)\", Statement.RETURN_GENERATED_KEYS)) {\n int i = 1;\n String isolationUri = null;\n String broadcast = null;\n if (vnet != null) {\n broadcast = \"vlan://\" + vnet;\n if (vnet.equalsIgnoreCase(\"untagged\")) {\n isolationUri = \"ec2://\" + vnet;\n } else {\n isolationUri = broadcast;\n }\n }\n pstmt.setLong(i++, instanceId);\n pstmt.setLong(i++, networkId);\n pstmt.setString(i++, macAddress);\n pstmt.setString(i++, ipAddress);\n pstmt.setString(i++, netmask);\n pstmt.setString(i++, strategy);\n pstmt.setString(i++, broadcast);\n pstmt.setString(i++, mode);\n pstmt.setString(i++, guru);\n pstmt.setString(i++, reservationId);\n pstmt.setInt(i++, deviceId);\n pstmt.setString(i++, isolationUri);\n pstmt.setBoolean(i++, defNic);\n pstmt.setString(i++, running ? \"Reserved\" : \"Allocated\");\n pstmt.setString(i++, gateway);\n pstmt.executeUpdate();\n try (ResultSet rs = pstmt.getGeneratedKeys()) {\n long nicId = 0;\n if (!rs.next()) {\n throw new CloudRuntimeException(\"Unable to get id for nic\");\n }\n nicId = rs.getLong(1);\n return nicId;\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Correlates the elements of two sequences based on\n * matching keys. A specified {@code EqualityComparer} is used to\n * compare keys.\n */\npublic static Enumerable hashJoin(Enumerable outer, Enumerable inner, Function1 outerKeySelector, Function1 innerKeySelector, Function2 resultSelector, @Nullable EqualityComparer comparer, boolean generateNullsOnLeft, boolean generateNullsOnRight) {\n return hashEquiJoin_(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, generateNullsOnLeft, generateNullsOnRight);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "/**\n * Same as {@link #create(String, FsPermission, EnumSet, boolean, short, long,\n * Progressable, int, ChecksumOpt, InetSocketAddress[], String)}\n * with the storagePolicy that is used to specify a specific storage policy\n * instead of inheriting any policy from this new file's parent directory.\n * This policy will be persisted in HDFS. A value of null means inheriting\n * parent groups' whatever policy.\n */\npublic DFSOutputStream create(String src, FsPermission permission, EnumSet flag, boolean createParent, short replication, long blockSize, Progressable progress, int buffersize, ChecksumOpt checksumOpt, InetSocketAddress[] favoredNodes, String ecPolicyName, String storagePolicy) throws IOException {\n checkOpen();\n final FsPermission masked = applyUMask(permission);\n LOG.debug(\"{}: masked={}\", src, masked);\n final DFSOutputStream result = DFSOutputStream.newStreamForCreate(this, src, masked, flag, createParent, replication, blockSize, progress, dfsClientConf.createChecksum(checksumOpt), getFavoredNodesStr(favoredNodes), ecPolicyName, storagePolicy);\n beginFileLease(result.getUniqKey(), result);\n return result;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static DepositAccountOnHoldTransactionData instance(final Long id, final BigDecimal amount, final EnumOptionData transactionType, final LocalDate transactionDate, final boolean reversed, final Long savingsId, final String savingsAccountNo, final String savingsClientName, final Long loanId, final String loanAccountNo, final String loanClientName) {\n return new DepositAccountOnHoldTransactionData(id, amount, transactionType, transactionDate, reversed, savingsId, savingsAccountNo, savingsClientName, loanId, loanAccountNo, loanClientName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private DeployDestination deployInVmLastHost(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids, DeploymentPlanner planner, VirtualMachine vm, DataCenter dc, ServiceOffering offering, int cpuRequested, long ramRequested, boolean volumesRequireEncryption) throws InsufficientServerCapacityException {\n HostVO host = _hostDao.findById(vm.getLastHostId());\n if (canUseLastHost(host, avoids, plan, vm, offering, volumesRequireEncryption)) {\n _hostDao.loadHostTags(host);\n _hostDao.loadDetails(host);\n if (host.getStatus() != Status.Up) {\n logger.debug(\"Cannot deploy VM [{}] to the last host [{}] because this host is not in UP state or is not enabled. Host current status [{}] and resource status [{}].\", vm.getUuid(), host.getUuid(), host.getState().name(), host.getResourceState());\n return null;\n }\n if (checkVmProfileAndHost(vmProfile, host)) {\n long cluster_id = host.getClusterId();\n ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, \"cpuOvercommitRatio\");\n ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, \"memoryOvercommitRatio\");\n float cpuOvercommitRatio = Float.parseFloat(cluster_detail_cpu.getValue());\n float memoryOvercommitRatio = Float.parseFloat(cluster_detail_ram.getValue());\n boolean hostHasCpuCapability, hostHasCapacity = false;\n hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed());\n if (hostHasCpuCapability) {\n // first check from reserved capacity\n hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpuRequested, ramRequested, true, cpuOvercommitRatio, memoryOvercommitRatio, true);\n // if not reserved, check the free capacity\n if (!hostHasCapacity)\n hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpuRequested, ramRequested, false, cpuOvercommitRatio, memoryOvercommitRatio, true);\n }\n boolean displayStorage = getDisplayStorageFromVmProfile(vmProfile);\n if (!hostHasCapacity || !hostHasCpuCapability) {\n logger.debug(\"Cannot deploy VM [{}] to the last host [{}] because this host does not have enough capacity to deploy this VM.\", vm.getUuid(), host.getUuid());\n return null;\n }\n logger.debug(\"Last host [{}] of VM [{}] is UP and has enough capacity. Checking for suitable pools for this host under zone [{}], pod [{}] and cluster [{}].\", host.getUuid(), vm.getUuid(), host.getDataCenterId(), host.getPodId(), host.getClusterId());\n Pod pod = _podDao.findById(host.getPodId());\n Cluster cluster = _clusterDao.findById(host.getClusterId());\n if (vm.getHypervisorType() == HypervisorType.BareMetal) {\n DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<>(), displayStorage);\n logger.debug(\"Returning Deployment Destination: {}.\", dest);\n return dest;\n }\n // search for storage under the zone, pod, cluster\n // of\n // the last host.\n DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId(), null);\n Pair>, List> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);\n Map> suitableVolumeStoragePools = result.first();\n List readyAndReusedVolumes = result.second();\n // choose the potential pool for this VM for this\n // host\n if (suitableVolumeStoragePools.isEmpty()) {\n logger.debug(\"Cannot find suitable storage pools in host [{}] to deploy VM [{}]\", host.getUuid(), vm.getUuid());\n return null;\n }\n List suitableHosts = new ArrayList<>();\n suitableHosts.add(host);\n Pair> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools, avoids, getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes, plan.getPreferredHosts(), vm);\n if (potentialResources != null) {\n Map storageVolMap = potentialResources.second();\n // remove the reused vol<->pool from\n // destination, since we don't have to\n // prepare\n // this volume.\n for (Volume vol : readyAndReusedVolumes) {\n storageVolMap.remove(vol);\n }\n DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap, displayStorage);\n logger.debug(\"Returning Deployment Destination: {}\", dest);\n return dest;\n }\n }\n }\n logger.debug(\"Cannot choose the last host to deploy this VM {}.\", vm);\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private VlanVO commitUpdateVlanAndIpRange(final Long id, final String newStartIP, final String newEndIP, final String currentStartIP, final String currentEndIP, final String gateway, final String netmask, final boolean ipv4, final Boolean isRangeForSystemVM, final Boolean forSystemvms) {\n return Transaction.execute(new TransactionCallback() {\n\n @Override\n public VlanVO doInTransaction(final TransactionStatus status) {\n VlanVO vlanRange = _vlanDao.findById(id);\n logger.debug(\"Updating vlan range \" + vlanRange.getId());\n if (ipv4) {\n vlanRange.setIpRange(newStartIP + \"-\" + newEndIP);\n vlanRange.setVlanGateway(gateway);\n vlanRange.setVlanNetmask(netmask);\n _vlanDao.update(vlanRange.getId(), vlanRange);\n if (!updatePublicIPRange(newStartIP, currentStartIP, newEndIP, currentEndIP, vlanRange.getDataCenterId(), vlanRange.getId(), vlanRange.getNetworkId(), vlanRange.getPhysicalNetworkId(), isRangeForSystemVM, forSystemvms)) {\n throw new CloudRuntimeException(\"Failed to update IPv4 range. Please contact Cloud Support.\");\n }\n } else {\n if (ObjectUtils.allNotNull(newStartIP, newEndIP)) {\n vlanRange.setIp6Range(newStartIP + \"-\" + newEndIP);\n } else {\n vlanRange.setIp6Range(null);\n }\n vlanRange.setIp6Gateway(gateway);\n vlanRange.setIp6Cidr(netmask);\n _vlanDao.update(vlanRange.getId(), vlanRange);\n }\n return vlanRange;\n }\n });\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static ConsequenceBuilder._13 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13){\r\n return new ConsequenceBuilder._13(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void setupMapJoin(HiveConf hiveConf, long seed, int rowCount, VectorMapJoinVariation vectorMapJoinVariation, MapJoinTestImplementation mapJoinImplementation, String[] bigTableColumnNames, TypeInfo[] bigTableTypeInfos, int[] bigTableKeyColumnNums, String[] smallTableValueColumnNames, TypeInfo[] smallTableValueTypeInfos, int[] bigTableRetainColumnNums, int[] smallTableRetainKeyColumnNums, int[] smallTableRetainValueColumnNums, SmallTableGenerationParameters smallTableGenerationParameters) throws Exception{\r\n this.vectorMapJoinVariation = vectorMapJoinVariation;\r\n this.mapJoinImplementation = mapJoinImplementation;\r\n testDesc = new MapJoinTestDescription(hiveConf, vectorMapJoinVariation, bigTableTypeInfos, bigTableKeyColumnNums, smallTableValueTypeInfos, smallTableRetainKeyColumnNums, smallTableGenerationParameters, MapJoinPlanVariation.DYNAMIC_PARTITION_HASH_JOIN);\r\n testData = new MapJoinTestData(rowCount, testDesc, seed);\r\n ObjectRegistryImpl objectRegistry = new ObjectRegistryImpl();\r\n ObjectCache.setupObjectRegistry(objectRegistry);\r\n operator = setupBenchmarkImplementation(mapJoinImplementation, testDesc, testData);\r\n isVectorOutput = isVectorOutput(mapJoinImplementation);\r\n if (!isVectorOutput) {\r\n bigTableRows = testData.getBigTableBatchSource().getRandomRows();\r\n } else {\r\n ArrayList bigTableBatchList = new ArrayList();\r\n VectorRandomBatchSource batchSource = testData.getBigTableBatchSource();\r\n batchSource.resetBatchIteration();\r\n while (true) {\r\n VectorizedRowBatch batch = testData.createBigTableBatch(testDesc);\r\n if (!batchSource.fillNextBatch(batch)) {\r\n break;\r\n }\r\n bigTableBatchList.add(batch);\r\n }\r\n bigTableBatches = bigTableBatchList.toArray(new VectorizedRowBatch[0]);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates an immutable list of 8 or more elements.\n */\npublic static List of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E... others) {\n @SuppressWarnings(\"unchecked\")\n E[] array = (E[]) new Object[8 + others.length];\n array[0] = e1;\n array[1] = e2;\n array[2] = e3;\n array[3] = e4;\n array[4] = e5;\n array[5] = e6;\n array[6] = e7;\n array[7] = e8;\n System.arraycopy(others, 0, array, 8, others.length);\n return new ImmutableNullableList<>(array);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public static ConsequenceBuilder._15 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15){\r\n return new ConsequenceBuilder._15(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "List getTimeseriesAspectValues(@Nonnull OperationContext opContext, @Nonnull String urn, @Nonnull String entity, @Nonnull String aspect, @Nullable Long startTimeMillis, @Nullable Long endTimeMillis, @Nullable Integer limit, @Nullable Filter filter, @Nullable SortCriterion sort) throws RemoteInvocationException;", "smellKey": "S107", "smellId": null, "repo": "patotskiy_datahub", "language": "java"} {"function": "public static native void glReadPixels2(int vpX, int vpY, int vpW, int vpH, int format, int type, byte[] pixels, int offset, int size);", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": " ProcessInstance createProcessInstance(Process process, String businessKey, T model, Map> headers, String startFromNodeId, String trigger, String kogitoReferenceId, CompositeCorrelation correlation);", "smellKey": "S107", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public static native void glCompressedTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int size, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "private void rewrite(final Mode mode, final RelNode inputToKeep, final RelNode inputToRemove, final Join join, List topProjExprs, RelOptRuleCall call, final Project project, List nullableNodes) {\n RexBuilder rexBuilder = join.getCluster().getRexBuilder();\n final RelNode leftInput = join.getLeft();\n final RelNode rightInput = join.getRight();\n // If we reach here, we trigger the transform\n if (mode == Mode.REMOVE) {\n if (inputToKeep == join.getRight()) {\n // First, if FK is the right input, we need to shift\n nullableNodes = nullableNodes.stream().map(node -> RexUtil.shift(node, 0, -leftInput.getRowType().getFieldCount())).collect(Collectors.toList());\n topProjExprs = topProjExprs.stream().map(node -> RexUtil.shift(node, 0, -leftInput.getRowType().getFieldCount())).collect(Collectors.toList());\n }\n // Fix nullability in references to the input node\n topProjExprs = HiveCalciteUtil.fixNullability(rexBuilder, topProjExprs, RelOptUtil.getFieldTypeList(inputToKeep.getRowType()));\n // Trigger transformation\n if (nullableNodes.isEmpty()) {\n call.transformTo(call.builder().push(inputToKeep).project(topProjExprs).convert(project.getRowType(), false).build());\n } else {\n RexNode newFilterCond;\n if (nullableNodes.size() == 1) {\n newFilterCond = rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, nullableNodes.get(0));\n } else {\n List isNotNullConds = new ArrayList<>();\n for (RexNode nullableNode : nullableNodes) {\n isNotNullConds.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, nullableNode));\n }\n newFilterCond = rexBuilder.makeCall(SqlStdOperatorTable.AND, isNotNullConds);\n }\n call.transformTo(call.builder().push(inputToKeep).filter(newFilterCond).project(topProjExprs).convert(project.getRowType(), false).build());\n }\n } else {\n // Mode.TRANSFORM\n // Trigger transformation\n call.transformTo(call.builder().push(leftInput).push(rightInput).join(JoinRelType.INNER, join.getCondition()).convert(call.rel(1).getRowType(), // Preserve nullability\n false).project(project.getProjects()).build());\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected double getScore2(int jse1, int jse2, double[][] traceScore, int traceIndex_, int[] traceIndex, int winSizeComb1, int winSizeComb2, double score0, double score1){\r\n double val = 0;\r\n if (nTrace > 1)\r\n val = traceScore[nTrace - 2][traceIndex[nTrace - 1]];\r\n else\r\n val = score0;\r\n double score2 = (val * traceIndexContainer[nTrace - 1] + score1 * (traceIndexContainer[nTrace] - traceIndexContainer[nTrace - 1])) / traceIndexContainer[nTrace];\r\n return score2;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateVlanAndIpv4Range(final long id, final VlanVO vlanRange, String startIp, String endIp, String gateway, String netmask, final Boolean isRangeForSystemVM, final Boolean forSystemVms) {\n final List listAllocatedIPs = _publicIpAddressDao.listByVlanIdAndState(id, IpAddress.State.Allocated);\n if (gateway != null && !gateway.equals(vlanRange.getVlanGateway()) && CollectionUtils.isNotEmpty(listAllocatedIPs)) {\n throw new InvalidParameterValueException(String.format(\"Unable to change gateway to %s because some IPs are in use\", gateway));\n }\n if (netmask != null && !netmask.equals(vlanRange.getVlanNetmask()) && CollectionUtils.isNotEmpty(listAllocatedIPs)) {\n throw new InvalidParameterValueException(String.format(\"Unable to change netmask to %s because some IPs are in use\", netmask));\n }\n gateway = MoreObjects.firstNonNull(gateway, vlanRange.getVlanGateway());\n netmask = MoreObjects.firstNonNull(netmask, vlanRange.getVlanNetmask());\n final String[] existingVlanIPRangeArray = vlanRange.getIpRange().split(\"-\");\n final String currentStartIP = existingVlanIPRangeArray[0];\n final String currentEndIP = existingVlanIPRangeArray[1];\n startIp = MoreObjects.firstNonNull(startIp, currentStartIP);\n endIp = MoreObjects.firstNonNull(endIp, currentEndIP);\n final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);\n if (StringUtils.isEmpty(cidr)) {\n throw new InvalidParameterValueException(String.format(\"Invalid gateway (%s) or netmask (%s)\", gateway, netmask));\n }\n final String cidrAddress = getCidrAddress(cidr);\n final long cidrSize = getCidrSize(cidr);\n checkIpRange(startIp, endIp, cidrAddress, cidrSize);\n checkGatewayOverlap(startIp, endIp, gateway);\n checkAllocatedIpsAreWithinVlanRange(listAllocatedIPs, startIp, endIp, forSystemVms);\n try {\n final String newStartIP = startIp;\n final String newEndIP = endIp;\n VlanVO range = _vlanDao.acquireInLockTable(id, 30);\n if (range == null) {\n throw new CloudRuntimeException(\"Unable to acquire vlan configuration: \" + id);\n }\n if (logger.isDebugEnabled()) {\n logger.debug(\"lock vlan \" + id + \" is acquired\");\n }\n commitUpdateVlanAndIpRange(id, newStartIP, newEndIP, currentStartIP, currentEndIP, gateway, netmask, true, isRangeForSystemVM, forSystemVms);\n } catch (final Exception e) {\n logger.error(\"Unable to edit VlanRange due to \" + e.getMessage(), e);\n throw new CloudRuntimeException(\"Failed to edit VlanRange. Please contact Cloud Support.\");\n } finally {\n _vlanDao.releaseFromLockTable(id);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private void readExcelFile(final Workbook workbook, final List loans, final List approvalDates, final List loanRepayments, final List disbursalDates, List statuses, final String locale, final String dateFormat) {\n Sheet loanSheet = workbook.getSheet(TemplatePopulateImportConstants.LOANS_SHEET_NAME);\n Integer noOfEntries = ImportHandlerUtils.getNumberOfRows(loanSheet, TemplatePopulateImportConstants.FIRST_COLUMN_INDEX);\n for (int rowIndex = 1; rowIndex <= noOfEntries; rowIndex++) {\n Row row;\n row = loanSheet.getRow(rowIndex);\n if (ImportHandlerUtils.isNotImported(row, LoanConstants.STATUS_COL)) {\n loans.add(readLoan(workbook, row, statuses, locale, dateFormat));\n approvalDates.add(readLoanApproval(row, locale, dateFormat));\n disbursalDates.add(readDisbursalData(row, locale, dateFormat));\n loanRepayments.add(readLoanRepayment(workbook, row, locale, dateFormat));\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "protected RackawareEnsemblePlacementPolicyImpl initialize(DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, boolean reorderReadsRandom, int stabilizePeriodSeconds, int reorderThresholdPendingRequests, boolean isWeighted, int maxWeightMultiple, int minNumRacksPerWriteQuorum, boolean enforceMinNumRacksPerWriteQuorum, boolean ignoreLocalNodeInPlacementPolicy, StatsLogger statsLogger, BookieAddressResolver bookieAddressResolver){\r\n checkNotNull(statsLogger, \"statsLogger should not be null, use NullStatsLogger instead.\");\r\n this.statsLogger = statsLogger;\r\n this.bookieAddressResolver = bookieAddressResolver;\r\n this.bookiesJoinedCounter = statsLogger.getOpStatsLogger(BOOKIES_JOINED);\r\n this.bookiesLeftCounter = statsLogger.getOpStatsLogger(BOOKIES_LEFT);\r\n this.readReorderedCounter = statsLogger.getOpStatsLogger(READ_REQUESTS_REORDERED);\r\n this.failedToResolveNetworkLocationCounter = statsLogger.getCounter(FAILED_TO_RESOLVE_NETWORK_LOCATION_COUNT);\r\n this.numWritableBookiesInDefaultRack = new Gauge() {\r\n\r\n @Override\r\n public Integer getDefaultValue() {\r\n return 0;\r\n }\r\n\r\n @Override\r\n public Integer getSample() {\r\n rwLock.readLock().lock();\r\n try {\r\n return topology.countNumOfAvailableNodes(getDefaultRack(), Collections.emptySet());\r\n } finally {\r\n rwLock.readLock().unlock();\r\n }\r\n }\r\n };\r\n this.statsLogger.registerGauge(NUM_WRITABLE_BOOKIES_IN_DEFAULT_RACK, numWritableBookiesInDefaultRack);\r\n this.reorderReadsRandom = reorderReadsRandom;\r\n this.stabilizePeriodSeconds = stabilizePeriodSeconds;\r\n this.reorderThresholdPendingRequests = reorderThresholdPendingRequests;\r\n this.dnsResolver = new DNSResolverDecorator(dnsResolver, () -> this.getDefaultRack(), failedToResolveNetworkLocationCounter);\r\n this.timer = timer;\r\n this.minNumRacksPerWriteQuorum = minNumRacksPerWriteQuorum;\r\n this.enforceMinNumRacksPerWriteQuorum = enforceMinNumRacksPerWriteQuorum;\r\n this.ignoreLocalNodeInPlacementPolicy = ignoreLocalNodeInPlacementPolicy;\r\n if (stabilizePeriodSeconds > 0) {\r\n this.topology = new StabilizeNetworkTopology(timer, stabilizePeriodSeconds);\r\n } else {\r\n this.topology = new NetworkTopologyImpl();\r\n }\r\n BookieNode bn = null;\r\n if (!ignoreLocalNodeInPlacementPolicy) {\r\n try {\r\n bn = createDummyLocalBookieNode(InetAddress.getLocalHost().getHostAddress());\r\n } catch (IOException e) {\r\n LOG.error(\"Failed to get local host address : \", e);\r\n }\r\n } else {\r\n LOG.info(\"Ignoring LocalNode in Placementpolicy\");\r\n }\r\n localNode = bn;\r\n LOG.info(\"Initialize rackaware ensemble placement policy @ {} @ {} : {}.\", localNode, null == localNode ? \"Unknown\" : localNode.getNetworkLocation(), dnsResolver.getClass().getName());\r\n this.isWeighted = isWeighted;\r\n if (this.isWeighted) {\r\n this.maxWeightMultiple = maxWeightMultiple;\r\n this.weightedSelection = new WeightedRandomSelectionImpl(this.maxWeightMultiple);\r\n LOG.info(\"Weight based placement with max multiple of \" + this.maxWeightMultiple);\r\n } else {\r\n LOG.info(\"Not weighted\");\r\n }\r\n return this;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setInfo(BeanConfig openApiConfig, String version, String title, String description, String termsOfService, String licenseName, String licenseUrl, String contactName, String contactUrl, String contactEmail){\r\n Info info = new Info().version(version).title(title).description(description).termsOfService(termsOfService);\r\n if (licenseName != null || licenseUrl != null) {\r\n License license = new License().name(licenseName).url(licenseUrl);\r\n info.setLicense(license);\r\n }\r\n if (contactName != null || contactUrl != null || contactEmail != null) {\r\n Contact contact = new Contact().name(contactName).url(contactUrl).email(contactEmail);\r\n info.setContact(contact);\r\n }\r\n openApiConfig.setInfo(info);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static RecurringDepositAccount createNewApplicationForSubmittal(final Client client, final Group group, final SavingsProduct product, final Staff fieldOfficer, final String accountNo, final ExternalId externalId, final AccountType accountType, final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal interestRate, final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final Set savingsAccountCharges, final DepositAccountTermAndPreClosure accountTermAndPreClosure, final DepositAccountRecurringDetail recurringDetail, final DepositAccountInterestRateChart chart, final boolean withHoldTax) {\n final boolean allowOverdraft = false;\n final BigDecimal overdraftLimit = new BigDecimal(0);\n final SavingsAccountStatusType status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL;\n return new RecurringDepositAccount(client, group, product, fieldOfficer, accountNo, externalId, status, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, accountTermAndPreClosure, recurringDetail, chart, allowOverdraft, overdraftLimit, withHoldTax);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private int createCommand(Long triggerCode, CommandType commandType, long processDefineCode, TaskDependType nodeDep, FailureStrategy failureStrategy, String startNodeList, String schedule, WarningType warningType, int executorId, Integer warningGroupId, RunMode runMode, Priority processInstancePriority, String workerGroup, String tenantCode, Long environmentCode, Map startParams, Integer expectedParallelismNumber, int dryRun, int testFlag, ComplementDependentMode complementDependentMode, boolean allLevelDependent, ExecutionOrder executionOrder){\r\n Command command = new Command();\r\n Map cmdParam = new HashMap<>();\r\n if (commandType == null) {\r\n command.setCommandType(CommandType.START_PROCESS);\r\n } else {\r\n command.setCommandType(commandType);\r\n }\r\n command.setProcessDefinitionCode(processDefineCode);\r\n if (nodeDep != null) {\r\n command.setTaskDependType(nodeDep);\r\n }\r\n if (failureStrategy != null) {\r\n command.setFailureStrategy(failureStrategy);\r\n }\r\n if (!StringUtils.isEmpty(startNodeList)) {\r\n cmdParam.put(CMD_PARAM_START_NODES, startNodeList);\r\n }\r\n if (warningType != null) {\r\n command.setWarningType(warningType);\r\n }\r\n if (startParams != null && startParams.size() > 0) {\r\n cmdParam.put(CMD_PARAM_START_PARAMS, JSONUtils.toJsonString(startParams));\r\n }\r\n command.setCommandParam(JSONUtils.toJsonString(cmdParam));\r\n command.setExecutorId(executorId);\r\n command.setWarningGroupId(warningGroupId);\r\n command.setProcessInstancePriority(processInstancePriority);\r\n command.setWorkerGroup(workerGroup);\r\n command.setTenantCode(tenantCode);\r\n command.setEnvironmentCode(environmentCode);\r\n command.setDryRun(dryRun);\r\n command.setTestFlag(testFlag);\r\n ProcessDefinition processDefinition = processService.findProcessDefinitionByCode(processDefineCode);\r\n if (processDefinition != null) {\r\n command.setProcessDefinitionVersion(processDefinition.getVersion());\r\n }\r\n command.setProcessInstanceId(0);\r\n if (commandType == CommandType.COMPLEMENT_DATA) {\r\n if (schedule == null || StringUtils.isEmpty(schedule)) {\r\n log.error(\"Create {} type command error because parameter schedule is invalid.\", command.getCommandType().getDescp());\r\n return 0;\r\n }\r\n if (!isValidateScheduleTime(schedule)) {\r\n return 0;\r\n }\r\n try {\r\n log.info(\"Start to create {} command, processDefinitionCode:{}.\", command.getCommandType().getDescp(), processDefineCode);\r\n return createComplementCommandList(triggerCode, schedule, runMode, command, expectedParallelismNumber, complementDependentMode, allLevelDependent, executionOrder);\r\n } catch (CronParseException cronParseException) {\r\n return 0;\r\n }\r\n } else {\r\n command.setCommandParam(JSONUtils.toJsonString(cmdParam));\r\n int count = commandService.createCommand(command);\r\n if (count > 0) {\r\n triggerRelationService.saveTriggerToDb(ApiTriggerType.COMMAND, triggerCode, command.getId());\r\n }\r\n return count;\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected long insertNetwork(Connection conn, String name, String displayText, String trafficType, String broadcastDomainType, String broadcastUri, String gateway, String cidr, String mode, long networkOfferingId, long dataCenterId, String guruName, String state, long domainId, long accountId, String dns1, String dns2, String guestType, boolean shared, String networkDomain, boolean isDefault, String reservationId) {\n String getNextNetworkSequenceSql = \"SELECT value from sequence where name='networks_seq'\";\n String advanceNetworkSequenceSql = \"UPDATE sequence set value=value+1 where name='networks_seq'\";\n String insertNetworkSql = \"INSERT INTO networks(id, name, display_text, traffic_type, broadcast_domain_type, gateway, cidr, mode, network_offering_id, data_center_id, guru_name, state, domain_id, account_id, dns1, dns2, guest_type, shared, is_default, created, network_domain, related, reservation_id, broadcast_uri) \" + \"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(), ?, ?, ?, ?)\";\n try (PreparedStatement getNextNetworkSequence = conn.prepareStatement(getNextNetworkSequenceSql);\n ResultSet rs = getNextNetworkSequence.executeQuery()) {\n rs.next();\n long seq = rs.getLong(1);\n try (PreparedStatement insertNetworkSequence = conn.prepareStatement(advanceNetworkSequenceSql)) {\n insertNetworkSequence.executeUpdate();\n }\n try (PreparedStatement insertNetwork = conn.prepareStatement(insertNetworkSql)) {\n int i = 1;\n insertNetwork.setLong(i++, seq);\n insertNetwork.setString(i++, name);\n insertNetwork.setString(i++, displayText);\n insertNetwork.setString(i++, trafficType);\n insertNetwork.setString(i++, broadcastDomainType);\n insertNetwork.setString(i++, gateway);\n insertNetwork.setString(i++, cidr);\n insertNetwork.setString(i++, mode);\n insertNetwork.setLong(i++, networkOfferingId);\n insertNetwork.setLong(i++, dataCenterId);\n insertNetwork.setString(i++, guruName);\n insertNetwork.setString(i++, state);\n insertNetwork.setLong(i++, domainId);\n insertNetwork.setLong(i++, accountId);\n insertNetwork.setString(i++, dns1);\n insertNetwork.setString(i++, dns2);\n insertNetwork.setString(i++, guestType);\n insertNetwork.setBoolean(i++, shared);\n insertNetwork.setBoolean(i++, isDefault);\n insertNetwork.setString(i++, networkDomain);\n insertNetwork.setLong(i++, seq);\n insertNetwork.setString(i++, reservationId);\n insertNetwork.setString(i++, broadcastUri);\n insertNetwork.executeUpdate();\n }\n try (PreparedStatement insertNetworks = conn.prepareStatement(\"INSERT INTO op_networks(id, mac_address_seq, nics_count, gc, check_for_gc) VALUES(?, ?, ?, ?, ?)\")) {\n insertNetworks.setLong(1, seq);\n insertNetworks.setLong(2, 0);\n insertNetworks.setLong(3, 0);\n if (trafficType.equals(\"Guest\")) {\n insertNetworks.setBoolean(4, true);\n } else {\n insertNetworks.setBoolean(4, false);\n }\n insertNetworks.setBoolean(5, false);\n insertNetworks.executeUpdate();\n }\n try (PreparedStatement insertAccountNetworkRef = conn.prepareStatement(\"INSERT INTO account_network_ref (account_id, network_id, is_owner) VALUES (?, ?, 1)\")) {\n insertAccountNetworkRef.setLong(1, accountId);\n insertAccountNetworkRef.setLong(2, seq);\n insertAccountNetworkRef.executeUpdate();\n }\n return seq;\n } catch (SQLException e) {\n throw new CloudRuntimeException(\"Unable to create network\", e);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static JComponent getDocumentViewer(ArchiveFileBean caseDto, String id, String fileName, boolean readOnly, DocumentPreviewProvider previewProvider, byte[] content, int width, int height, DocumentPreviewSaveCallback saveCallback) {\n String lFileName = fileName.toLowerCase();\n if (lFileName.endsWith(\".pdf\")) {\n PdfImageScrollingPanel pdfP = new PdfImageScrollingPanel(fileName, content, saveCallback);\n pdfP.setSize(new Dimension(width, height));\n pdfP.setMaximumSize(new Dimension(width, height));\n pdfP.setPreferredSize(new Dimension(width, height));\n pdfP.showContent(id, content);\n return pdfP;\n } else if (lFileName.endsWith(\".jpg\") || lFileName.endsWith(\".jpeg\") || lFileName.endsWith(\".gif\") || lFileName.endsWith(\".png\")) {\n GifJpegPngImagePanel ip = new GifJpegPngImagePanel(content);\n ip.setSize(width, height);\n ip.setMaximumSize(new Dimension(width, height));\n ip.setPreferredSize(new Dimension(width, height));\n ip.showContent(id, content);\n return ip;\n } else if (lFileName.endsWith(\".bmp\") || lFileName.endsWith(\".tif\") || lFileName.endsWith(\".tiff\")) {\n BmpTiffImagePanel ip = new BmpTiffImagePanel(content);\n ip.setSize(width, height);\n ip.setMaximumSize(new Dimension(width, height));\n ip.setPreferredSize(new Dimension(width, height));\n ip.showContent(id, content);\n return ip;\n } else if (lFileName.endsWith(\".txt\")) {\n PlaintextPanel ptp = new PlaintextPanel();\n ptp.setSize(new Dimension(width, height));\n ptp.setMaximumSize(new Dimension(width, height));\n ptp.setPreferredSize(new Dimension(width, height));\n try {\n ptp.showContent(id, previewProvider.getPreview().getBytes());\n } catch (Exception ex) {\n ptp.showContent(id, (\"FEHLER: \" + ex.getMessage()).getBytes());\n }\n return ptp;\n } else if (lFileName.endsWith(\".md\")) {\n MarkdownPanel mdp = new MarkdownPanel(id, readOnly);\n mdp.setSize(new Dimension(width, height));\n mdp.setMaximumSize(new Dimension(width, height));\n mdp.setPreferredSize(new Dimension(width, height));\n try {\n mdp.showContent(id, previewProvider.getPreview().getBytes());\n } catch (Exception ex) {\n mdp.showContent(id, (\"FEHLER: \" + ex.getMessage()).getBytes());\n }\n return mdp;\n } else if (lFileName.endsWith(\".wav\") || lFileName.endsWith(\".ogg\") || lFileName.endsWith(\".mp3\")) {\n SoundplayerPanel spp = new SoundplayerPanel(id, readOnly, saveCallback);\n spp.setSize(new Dimension(width, height));\n spp.setMaximumSize(new Dimension(width, height));\n spp.setPreferredSize(new Dimension(width, height));\n try {\n spp.showContent(id, content);\n } catch (Exception ex) {\n spp.showStatus(\"FEHLER: \" + ex.getMessage());\n }\n return spp;\n } else if (lFileName.endsWith(\".html\") || lFileName.endsWith(\".htm\")) {\n HtmlPanel hp = new HtmlPanel(id, readOnly);\n hp.setSize(new Dimension(width, height));\n hp.setFileName(fileName);\n hp.setMaximumSize(new Dimension(width, height));\n hp.setPreferredSize(new Dimension(width, height));\n hp.showContent(id, content);\n return hp;\n } else if (lFileName.endsWith(\".xml\") && (lFileName.contains(\"xjustiz\"))) {\n XjustizPanel xjp = new XjustizPanel(id, fileName);\n xjp.setSize(new Dimension(width, height));\n xjp.setMaximumSize(new Dimension(width, height));\n xjp.setPreferredSize(new Dimension(width, height));\n xjp.showContent(id, content);\n return xjp;\n } else if (lFileName.endsWith(\".xml\") && EInvoiceUtils.isEInvoice(new String(content))) {\n XRechnungPanel xmlp = new XRechnungPanel();\n xmlp.setSize(new Dimension(width, height));\n xmlp.setMaximumSize(new Dimension(width, height));\n xmlp.setPreferredSize(new Dimension(width, height));\n xmlp.showContent(id, content);\n return xmlp;\n } else if (lFileName.endsWith(\".xml\")) {\n XmlPanel xmlp = new XmlPanel();\n xmlp.setSize(new Dimension(width, height));\n xmlp.setMaximumSize(new Dimension(width, height));\n xmlp.setPreferredSize(new Dimension(width, height));\n xmlp.showContent(id, content);\n return xmlp;\n } else if (lFileName.endsWith(\".eml\")) {\n try {\n InputStream source = new ByteArrayInputStream(content);\n MimeMessage message = new MimeMessage(null, source);\n // need to set this to avoid sending read receipts\n message.setFlag(Flag.SEEN, true);\n EmailPanel ep = new EmailPanel();\n ep.setSize(new Dimension(width, height));\n ep.setMaximumSize(new Dimension(width, height));\n ep.setPreferredSize(new Dimension(width, height));\n MailboxSetup ms = EmailUtils.getMailboxSetup(message);\n ep.setMessage(id, new MessageContainer(message, message.getSubject(), true), ms);\n ep.setCaseContext(caseDto);\n return ep;\n } catch (Throwable t) {\n EmailPanel ep = new EmailPanel();\n ep.setSize(new Dimension(width, height));\n ep.setMaximumSize(new Dimension(width, height));\n ep.setPreferredSize(new Dimension(width, height));\n ep.showStatus(STR_PREVIEWFAIL);\n return ep;\n }\n } else if (lFileName.endsWith(\".msg\")) {\n try {\n InputStream source = new ByteArrayInputStream(content);\n OutlookMessage om = new OutlookMessageParser().parseMsg(source);\n OutlookMessagePanel op = new OutlookMessagePanel();\n op.setSize(new Dimension(width, height));\n op.setMaximumSize(new Dimension(width, height));\n op.setPreferredSize(new Dimension(width, height));\n //MailboxSetup ms = EmailUtils.getMailboxSetup(message);\n op.setMessage(id, om);\n op.setCaseContext(caseDto);\n return op;\n } catch (Throwable t) {\n EmailPanel ep = new EmailPanel();\n ep.setSize(new Dimension(width, height));\n ep.setMaximumSize(new Dimension(width, height));\n ep.setPreferredSize(new Dimension(width, height));\n ep.showStatus(STR_PREVIEWFAIL);\n return ep;\n }\n // } else if (lFileName.endsWith(\".odt\") || lFileName.endsWith(\".ods\")) {\n // try {\n // String tempPath=FileUtils.createTempFile(fileName, content);\n // InputStream in = new FileInputStream(tempPath);\n // OdfDocument document = OdfDocument.loadDocument(in);\n //\n // PdfOptions options = PdfOptions.create();\n //\n // File tempPdf=File.createTempFile(\"\" + System.currentTimeMillis(), \".pdf\");\n // OutputStream out = new FileOutputStream(tempPdf);\n // PdfConverter.getInstance().convert(document, out, options);\n //\n // byte[] pdfContent=FileUtils.readFile(tempPdf);\n // FileUtils.cleanupTempFile(tempPath);\n // FileUtils.cleanupTempFile(tempPdf.getPath());\n // PdfImagePanel pdfP = new PdfImagePanel(pdfContent);\n // pdfP.setSize(new Dimension(width, height));\n // pdfP.showContent(pdfContent);\n // return pdfP;\n // } catch (Throwable t) {\n // log.error(\"could not convert file to PDF: \" + fileName, t);\n // }\n } else if (lFileName.endsWith(\".odt\") || lFileName.endsWith(\".ods\")) {\n try {\n byte[] thumbBytes = null;\n ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));\n //get the zipped file list entry\n ZipEntry ze = zis.getNextEntry();\n while (ze != null) {\n String thumbName = ze.getName();\n if (thumbName.toLowerCase().endsWith(\"thumbnail.png\")) {\n byte[] buffer = new byte[1024];\n //create all non exists folders\n //else you will hit FileNotFoundException for compressed folder\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n int len;\n while ((len = zis.read(buffer)) > 0) {\n bos.write(buffer, 0, len);\n }\n bos.close();\n thumbBytes = bos.toByteArray();\n break;\n }\n ze = zis.getNextEntry();\n }\n zis.closeEntry();\n zis.close();\n if (thumbBytes != null) {\n GifJpegPngImageWithTextPanel ip = new GifJpegPngImageWithTextPanel(thumbBytes, previewProvider.getPreview().getBytes());\n ip.setSize(width, height);\n ip.setMaximumSize(new Dimension(width, height));\n ip.setPreferredSize(new Dimension(width, height));\n ip.showContent(id, thumbBytes);\n return ip;\n }\n } catch (Throwable t) {\n log.error(\"Error extracting thumbnail from \" + fileName, t);\n }\n } else if (lFileName.endsWith(\".bea\")) {\n try {\n BeaPanel bp = new BeaPanel(id);\n bp.setSize(new Dimension(width, height));\n bp.setMaximumSize(new Dimension(width, height));\n bp.setPreferredSize(new Dimension(width, height));\n bp.showContent(id, content);\n bp.setCaseContext(caseDto);\n return bp;\n } catch (Throwable t) {\n log.error(t);\n BeaPanel bp = new BeaPanel(null);\n bp.setSize(new Dimension(width, height));\n bp.setMaximumSize(new Dimension(width, height));\n bp.setPreferredSize(new Dimension(width, height));\n bp.showStatus(STR_PREVIEWFAIL);\n return bp;\n }\n } else if (LauncherFactory.supportedByLibreOffice(fileName)) {\n // double clicking the documents table will fire the mouse event twice - one with clickount=1, then with clickcount=2\n // this cases LO to launch twice, which seems to fail...\n // try {\n // FileConverter conv=FileConverter.getInstance();\n // String tempPath=FileUtils.createTempFile(fileName, content);\n //\n // try {\n // Thread.sleep(1500);\n // } catch (Throwable t) {\n //\n // }\n //\n // String tempPdfPath=conv.convertToPDF(tempPath);\n // byte[] pdfContent=FileUtils.readFile(new File(tempPdfPath));\n // FileUtils.cleanupTempFile(tempPath);\n // FileUtils.cleanupTempFile(tempPdfPath);\n // PdfImagePanel pdfP = new PdfImagePanel(pdfContent);\n // pdfP.setSize(new Dimension(width, height));\n // pdfP.showContent(pdfContent);\n // return pdfP;\n // } catch (Throwable t) {\n // log.error(t);\n // // fall back to text preview\n // }\n }\n // plain text preview is default\n PlaintextPanel ptp = new PlaintextPanel();\n ptp.setSize(new Dimension(width, height));\n ptp.setMaximumSize(new Dimension(width, height));\n ptp.setPreferredSize(new Dimension(width, height));\n //ptp.showStatus(\"Vorschau wird geladen...\");\n // we just reuse the showStatus method because it is doing the same thing\n //ptp.showStatus(previewContent);\n try {\n ptp.showContent(id, previewProvider.getPreview().getBytes());\n } catch (Exception ex) {\n ptp.showContent(id, (\"FEHLER: \" + ex.getMessage()).getBytes());\n }\n return ptp;\n}", "smellKey": "S107", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static List getFunctionalIndexRecordsUsingBloomFilter(HoodieTableMetaClient metaClient, Schema readerSchema, List fileSlices, String partition, HoodieFunctionalIndex functionalIndex, String columnToIndex, SQLContext sqlContext, HoodieWriteConfig metadataWriteConfig) {\n List bloomFilterMetadataList = new ArrayList<>();\n for (FileSlice fileSlice : fileSlices) {\n if (fileSlice.getBaseFile().isPresent()) {\n HoodieBaseFile baseFile = fileSlice.getBaseFile().get();\n buildBloomFilterMetadata(metaClient, readerSchema, functionalIndex, columnToIndex, sqlContext, bloomFilterMetadataList, baseFile.getStoragePath(), metadataWriteConfig, partition, baseFile.getCommitTime(), true);\n }\n // Handle log files\n fileSlice.getLogFiles().forEach(logFile -> buildBloomFilterMetadata(metaClient, readerSchema, functionalIndex, columnToIndex, sqlContext, bloomFilterMetadataList, logFile.getPath(), metadataWriteConfig, partition, logFile.getDeltaCommitTime(), false));\n }\n return bloomFilterMetadataList;\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "static SnapshotDiffReportListing getSnapshotDiffReportListing(FSDirectory fsd, FSPermissionChecker pc, SnapshotManager snapshotManager, String path, String fromSnapshot, String toSnapshot, byte[] startPath, int index, int snapshotDiffReportLimit) throws IOException {\n SnapshotDiffReportListing diffs;\n fsd.readLock();\n try {\n INodesInPath iip = fsd.resolvePath(pc, path, DirOp.READ);\n if (fsd.isPermissionEnabled()) {\n checkSubtreeReadPermission(fsd, pc, path, fromSnapshot);\n checkSubtreeReadPermission(fsd, pc, path, toSnapshot);\n }\n diffs = snapshotManager.diff(iip, path, fromSnapshot, toSnapshot, startPath, index, snapshotDiffReportLimit);\n } catch (Exception e) {\n throw e;\n } finally {\n fsd.readUnlock();\n }\n return diffs;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void updateLastCache(String database, PartialPath devicePath, String[] measurements, MeasurementSchema[] measurementSchemas, boolean isAligned, Function timeValuePairProvider, Function shouldUpdateProvider, boolean highPriorityUpdate, Long latestFlushedTime){\r\n timeSeriesSchemaCache.updateLastCache(database, devicePath, measurements, measurementSchemas, isAligned, timeValuePairProvider, shouldUpdateProvider, highPriorityUpdate, latestFlushedTime);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected abstract IoTDBSyncClientManager constructClient(final List nodeUrls, final boolean useSSL, final String trustStorePath, final String trustStorePwd, final boolean useLeaderCache, final String loadBalanceStrategy, final boolean shouldReceiverConvertOnTypeMismatch, final String loadTsFileStrategy);", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected void onUpdate(Data key, Object value, R record, ExpiryPolicy expiryPolicy, long now, boolean disableWriteThrough, int completionId, boolean saved){\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Enumerable find(List ops, List> fields, List> sort, List groupBy, List> aggregations, Map mappings, Long offset, Long fetch) throws IOException{\r\n if (!aggregations.isEmpty() || !groupBy.isEmpty()) {\r\n return aggregate(ops, fields, sort, groupBy, aggregations, mappings, offset, fetch);\r\n }\r\n final ObjectNode query = mapper.createObjectNode();\r\n for (String op : ops) {\r\n query.setAll((ObjectNode) mapper.readTree(op));\r\n }\r\n if (!sort.isEmpty()) {\r\n ArrayNode sortNode = query.withArray(\"sort\");\r\n sort.forEach(e -> sortNode.add(mapper.createObjectNode().put(e.getKey(), e.getValue().isDescending() ? \"desc\" : \"asc\")));\r\n }\r\n if (offset != null) {\r\n query.put(\"from\", offset);\r\n }\r\n if (fetch != null) {\r\n query.put(\"size\", fetch);\r\n }\r\n final Function1 getter = ElasticsearchEnumerators.getter(fields, ImmutableMap.copyOf(mappings));\r\n Iterable iter;\r\n if (offset == null) {\r\n iter = () -> new Scrolling(transport).query(query);\r\n } else {\r\n final ElasticsearchJson.Result search = transport.search().apply(query);\r\n iter = () -> search.searchHits().hits().iterator();\r\n }\r\n return Linq4j.asEnumerable(iter).select(getter);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void writeMetadatatoPDFsOfEntry(BibDatabaseContext databaseContext, String citeKey, BibEntry entry, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter, boolean writeXMP, boolean embeddBibfile){\r\n try {\r\n if (writeXMP) {\r\n if (xmpPdfExporter.exportToAllFilesOfEntry(databaseContext, filePreferences, entry, List.of(entry))) {\r\n System.out.printf(\"Successfully written XMP metadata on at least one linked file of %s%n\", citeKey);\r\n } else {\r\n System.err.printf(\"Cannot write XMP metadata on any linked files of %s. Make sure there is at least one linked file and the path is correct.%n\", citeKey);\r\n }\r\n }\r\n if (embeddBibfile) {\r\n if (embeddedBibFilePdfExporter.exportToAllFilesOfEntry(databaseContext, filePreferences, entry, List.of(entry))) {\r\n System.out.printf(\"Successfully embedded metadata on at least one linked file of %s%n\", citeKey);\r\n } else {\r\n System.out.printf(\"Cannot embedd metadata on any linked files of %s. Make sure there is at least one linked file and the path is correct.%n\", citeKey);\r\n }\r\n }\r\n } catch (Exception e) {\r\n LOGGER.error(\"Failed writing metadata on a linked file of {}.\", citeKey);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, String displayName, Account owner, Long diskOfferingId, Long diskSize, List networkList, List securityGroupIdList, String group, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Account caller, Map requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, Map datadiskTemplateToDiskOfferringMap, Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, VMTemplateVO template, HypervisorType hypervisorType, long accountId, ServiceOfferingVO offering, boolean isIso, Long rootDiskOfferingId, long volumesSize, long additionalDiskSize) throws ResourceAllocationException {\n List rootResourceLimitStorageTags = getResourceLimitStorageTags(rootDiskOfferingId != null ? rootDiskOfferingId : offering.getDiskOfferingId());\n List additionalResourceLimitStorageTags = diskOfferingId != null ? getResourceLimitStorageTags(diskOfferingId) : null;\n try (CheckedReservation rootVolumeReservation = new CheckedReservation(owner, ResourceType.volume, rootResourceLimitStorageTags, 1L, reservationDao, resourceLimitService);\n CheckedReservation additionalVolumeReservation = diskOfferingId != null ? new CheckedReservation(owner, ResourceType.volume, additionalResourceLimitStorageTags, 1L, reservationDao, resourceLimitService) : null;\n CheckedReservation rootPrimaryStorageReservation = new CheckedReservation(owner, ResourceType.primary_storage, rootResourceLimitStorageTags, volumesSize, reservationDao, resourceLimitService);\n CheckedReservation additionalPrimaryStorageReservation = diskOfferingId != null ? new CheckedReservation(owner, ResourceType.primary_storage, additionalResourceLimitStorageTags, additionalDiskSize, reservationDao, resourceLimitService) : null) {\n // verify security group ids\n if (securityGroupIdList != null) {\n for (Long securityGroupId : securityGroupIdList) {\n SecurityGroup sg = _securityGroupDao.findById(securityGroupId);\n if (sg == null) {\n throw new InvalidParameterValueException(\"Unable to find security group by id \" + securityGroupId);\n } else {\n // verify permissions\n _accountMgr.checkAccess(caller, null, true, owner, sg);\n }\n }\n }\n if (datadiskTemplateToDiskOfferringMap != null && !datadiskTemplateToDiskOfferringMap.isEmpty()) {\n for (Entry datadiskTemplateToDiskOffering : datadiskTemplateToDiskOfferringMap.entrySet()) {\n VMTemplateVO dataDiskTemplate = _templateDao.findById(datadiskTemplateToDiskOffering.getKey());\n DiskOffering dataDiskOffering = datadiskTemplateToDiskOffering.getValue();\n if (dataDiskTemplate == null || (!dataDiskTemplate.getTemplateType().equals(TemplateType.DATADISK)) && (dataDiskTemplate.getState().equals(VirtualMachineTemplate.State.Active))) {\n throw new InvalidParameterValueException(\"Invalid template id specified for Datadisk template\" + datadiskTemplateToDiskOffering.getKey());\n }\n long dataDiskTemplateId = datadiskTemplateToDiskOffering.getKey();\n if (!dataDiskTemplate.getParentTemplateId().equals(template.getId())) {\n throw new InvalidParameterValueException(\"Invalid Datadisk template. Specified Datadisk template\" + dataDiskTemplateId + \" doesn't belong to template \" + template.getId());\n }\n if (dataDiskOffering == null) {\n throw new InvalidParameterValueException(\"Invalid disk offering id \" + datadiskTemplateToDiskOffering.getValue().getId() + \" specified for datadisk template \" + dataDiskTemplateId);\n }\n if (dataDiskOffering.isCustomized()) {\n throw new InvalidParameterValueException(\"Invalid disk offering id \" + dataDiskOffering.getId() + \" specified for datadisk template \" + dataDiskTemplateId + \". Custom Disk offerings are not supported for Datadisk templates\");\n }\n if (dataDiskOffering.getDiskSize() < dataDiskTemplate.getSize()) {\n throw new InvalidParameterValueException(\"Invalid disk offering id \" + dataDiskOffering.getId() + \" specified for datadisk template \" + dataDiskTemplateId + \". Disk offering size should be greater than or equal to the template size\");\n }\n _templateDao.loadDetails(dataDiskTemplate);\n resourceLimitService.checkVolumeResourceLimit(owner, true, dataDiskOffering.getDiskSize(), dataDiskOffering);\n }\n }\n // check that the affinity groups exist\n if (affinityGroupIdList != null) {\n for (Long affinityGroupId : affinityGroupIdList) {\n AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);\n if (ag == null) {\n throw new InvalidParameterValueException(\"Unable to find affinity group \" + ag);\n } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {\n throw new InvalidParameterValueException(\"Affinity group type is not supported for group: \" + ag + \" ,type: \" + ag.getType() + \" , Please try again after removing the affinity group\");\n } else {\n // verify permissions\n if (ag.getAclType() == ACLType.Domain) {\n _accountMgr.checkAccess(caller, null, false, owner, ag);\n // Root admin has access to both VM and AG by default,\n // but\n // make sure the owner of these entities is same\n if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {\n if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {\n throw new PermissionDeniedException(\"Affinity Group \" + ag + \" does not belong to the VM's domain\");\n }\n }\n } else {\n _accountMgr.checkAccess(caller, null, true, owner, ag);\n // Root admin has access to both VM and AG by default,\n // but\n // make sure the owner of these entities is same\n if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {\n if (ag.getAccountId() != owner.getAccountId()) {\n throw new PermissionDeniedException(\"Affinity Group \" + ag + \" does not belong to the VM's account\");\n }\n }\n }\n }\n }\n }\n if (hypervisorType != HypervisorType.BareMetal) {\n // check if we have available pools for vm deployment\n long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);\n if (availablePools < 1) {\n throw new StorageUnavailableException(\"There are no available pools in the UP state for vm deployment\", -1);\n }\n }\n if (template.getTemplateType().equals(TemplateType.SYSTEM) && !CKS_NODE.equals(vmType) && !SHAREDFSVM.equals(vmType)) {\n throw new InvalidParameterValueException(\"Unable to use system template \" + template.getId() + \" to deploy a user vm\");\n }\n List listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());\n if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {\n throw new InvalidParameterValueException(\"The template \" + template.getId() + \" is not available for use\");\n }\n if (isIso && !template.isBootable()) {\n throw new InvalidParameterValueException(\"Installing from ISO requires an ISO that is bootable: \" + template.getId());\n }\n // Check templates permissions\n _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);\n // check if the user data is correct\n userData = userDataManager.validateUserData(userData, httpmethod);\n // Find an SSH public key corresponding to the key pair name, if one is\n // given\n String sshPublicKeys = \"\";\n String keypairnames = \"\";\n if (!sshKeyPairs.isEmpty()) {\n List pairs = _sshKeyPairDao.findByNames(owner.getAccountId(), owner.getDomainId(), sshKeyPairs);\n if (pairs == null || pairs.size() != sshKeyPairs.size()) {\n throw new InvalidParameterValueException(\"Not all specified keypairs exist\");\n }\n sshPublicKeys = pairs.stream().map(p -> p.getPublicKey()).collect(Collectors.joining(\"\\n\"));\n keypairnames = String.join(\",\", sshKeyPairs);\n }\n LinkedHashMap> networkNicMap = new LinkedHashMap<>();\n short defaultNetworkNumber = 0;\n boolean securityGroupEnabled = false;\n int networkIndex = 0;\n for (NetworkVO network : networkList) {\n if ((network.getDataCenterId() != zone.getId())) {\n if (!network.isStrechedL2Network()) {\n throw new InvalidParameterValueException(\"Network id=\" + network.getId() + \" doesn't belong to zone \" + zone.getId());\n }\n NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());\n Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());\n String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);\n if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {\n throw new InvalidParameterValueException(\"Network in which is VM getting deployed could not be\" + \" streched to the zone, as we could not find a valid physical network\");\n }\n }\n _accountMgr.checkAccess(owner, AccessType.UseEntry, false, network);\n IpAddresses requestedIpPair = null;\n if (requestedIps != null && !requestedIps.isEmpty()) {\n requestedIpPair = requestedIps.get(network.getId());\n }\n if (requestedIpPair == null) {\n requestedIpPair = new IpAddresses(null, null);\n } else {\n _networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair);\n }\n NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());\n profile.setOrderIndex(networkIndex);\n if (defaultNetworkNumber == 0) {\n defaultNetworkNumber++;\n // if user requested specific ip for default network, add it\n if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {\n _networkModel.checkRequestedIpAddresses(network.getId(), defaultIps);\n profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());\n } else if (defaultIps.getMacAddress() != null) {\n profile = new NicProfile(null, null, defaultIps.getMacAddress());\n }\n profile.setDefaultNic(true);\n if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {\n if ((userData != null) && (!userData.isEmpty())) {\n throw new InvalidParameterValueException(String.format(\"Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for %s service in the default network %s/%s.\", Service.UserData.getName(), network.getName(), network.getUuid()));\n }\n if ((sshPublicKeys != null) && (!sshPublicKeys.isEmpty())) {\n throw new InvalidParameterValueException(String.format(\"Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for %s service in the default network %s/%s\", Service.UserData.getName(), network.getName(), network.getUuid()));\n }\n if (template.isEnablePassword()) {\n throw new InvalidParameterValueException(String.format(\"Unable to deploy VM as template %s is password enabled, but there is no support for %s service in the default network %s/%s\", template.getId(), Service.UserData.getName(), network.getName(), network.getUuid()));\n }\n }\n }\n if (_networkModel.isSecurityGroupSupportedInNetwork(network)) {\n securityGroupEnabled = true;\n }\n List profiles = networkNicMap.get(network.getUuid());\n if (CollectionUtils.isEmpty(profiles)) {\n profiles = new ArrayList<>();\n }\n profiles.add(profile);\n networkNicMap.put(network.getUuid(), profiles);\n networkIndex++;\n }\n if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) {\n throw new InvalidParameterValueException(\"Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network\");\n }\n // Verify network information - network default network has to be set;\n // and vm can't have more than one default network\n // This is a part of business logic because default network is required\n // by Agent Manager in order to configure default\n // gateway for the vm\n if (defaultNetworkNumber == 0) {\n throw new InvalidParameterValueException(\"At least 1 default network has to be specified for the vm\");\n } else if (defaultNetworkNumber > 1) {\n throw new InvalidParameterValueException(\"Only 1 default network per vm is supported\");\n }\n long id = _vmDao.getNextInSequence(Long.class, \"id\");\n if (hostName != null) {\n // Check is hostName is RFC compliant\n checkNameForRFCCompliance(hostName);\n }\n String instanceName = null;\n String instanceSuffix = _instance;\n String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);\n if (_instanceNameFlag && HypervisorType.VMware.equals(hypervisorType)) {\n if (StringUtils.isNotEmpty(hostName)) {\n instanceSuffix = hostName;\n }\n if (hostName == null) {\n if (displayName != null) {\n hostName = displayName;\n } else {\n hostName = generateHostName(uuidName);\n }\n }\n // If global config vm.instancename.flag is set to true, then CS will set guest VM's name as it appears on the hypervisor, to its hostname.\n // In case of VMware since VM name must be unique within a DC, check if VM with the same hostname already exists in the zone.\n VMInstanceVO vmByHostName = _vmInstanceDao.findVMByHostNameInZone(hostName, zone.getId());\n if (vmByHostName != null && vmByHostName.getState() != State.Expunging) {\n throw new InvalidParameterValueException(\"There already exists a VM by the name: \" + hostName + \".\");\n }\n } else {\n if (hostName == null) {\n //Generate name using uuid and instance.name global config\n hostName = generateHostName(uuidName);\n }\n }\n if (hostName != null) {\n // Check is hostName is RFC compliant\n checkNameForRFCCompliance(hostName);\n }\n instanceName = VirtualMachineName.getVmName(id, owner.getId(), instanceSuffix);\n if (_instanceNameFlag && HypervisorType.VMware.equals(hypervisorType) && !instanceSuffix.equals(_instance)) {\n customParameters.put(VmDetailConstants.NAME_ON_HYPERVISOR, instanceName);\n }\n // Check if VM with instanceName already exists.\n VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);\n if (vmObj != null && vmObj.getState() != State.Expunging) {\n throw new InvalidParameterValueException(\"There already exists a VM by the display name supplied\");\n }\n checkIfHostNameUniqueInNtwkDomain(hostName, networkList);\n long userId = CallContext.current().getCallingUserId();\n if (CallContext.current().getCallingAccount().getId() != owner.getId()) {\n List userVOs = _userDao.listByAccount(owner.getAccountId());\n if (!userVOs.isEmpty()) {\n userId = userVOs.get(0).getId();\n }\n }\n dynamicScalingEnabled = dynamicScalingEnabled && checkIfDynamicScalingCanBeEnabled(null, offering, template, zone.getId());\n UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, userDataId, userDataDetails, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKeys, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, vmType, rootDiskOfferingId, keypairnames);\n assignInstanceToGroup(group, id);\n return vm;\n } catch (ResourceAllocationException | CloudRuntimeException e) {\n throw e;\n } catch (Exception e) {\n logger.error(\"error during resource reservation and allocation\", e);\n throw new CloudRuntimeException(e);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": " static QueueEntry create(ByteBuf entry, boolean ackBeforeSync, long ledgerId, long entryId, WriteCallback cb, Object ctx, long enqueueTime, OpStatsLogger journalAddEntryStats, Counter journalCbQueueSize, Counter cbThreadPoolQueueSize, OpStatsLogger journalCbQueuedLatency, Counter callbackTime){\r\n QueueEntry qe = RECYCLER.get();\r\n qe.entry = entry;\r\n qe.ackBeforeSync = ackBeforeSync;\r\n qe.cb = cb;\r\n qe.ctx = ctx;\r\n qe.ledgerId = ledgerId;\r\n qe.entryId = entryId;\r\n qe.enqueueTime = enqueueTime;\r\n qe.journalAddEntryStats = journalAddEntryStats;\r\n qe.journalCbQueuedLatency = journalCbQueuedLatency;\r\n qe.journalCbQueueSize = journalCbQueueSize;\r\n qe.cbThreadPoolQueueSize = cbThreadPoolQueueSize;\r\n qe.callbackTime = callbackTime;\r\n return qe;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void createPortProfile(VmwareContext context, String ethPortProfileName, String networkName, Integer vlanId, Integer networkRateMbps, long peakBandwidth, long burstSize, String gateway, boolean configureVServiceInNexus) throws Exception {\n Map vsmCredentials = getValidatedVsmCredentials(context);\n String vsmIp = vsmCredentials.get(\"vsmip\");\n String vsmUserName = vsmCredentials.get(\"vsmusername\");\n String vsmPassword = vsmCredentials.get(\"vsmpassword\");\n String msg;\n NetconfHelper netconfClient;\n try {\n LOGGER.info(\"Connecting to Nexus 1000v: \" + vsmIp);\n netconfClient = new NetconfHelper(vsmIp, vsmUserName, vsmPassword);\n LOGGER.info(\"Successfully connected to Nexus 1000v : \" + vsmIp);\n } catch (CloudRuntimeException e) {\n msg = \"Failed to connect to Nexus 1000v \" + vsmIp + \" with credentials of user \" + vsmUserName + \". Exception: \" + e.toString();\n LOGGER.error(msg);\n throw new CloudRuntimeException(msg);\n }\n String policyName = s_policyNamePrefix;\n int averageBandwidth = 0;\n if (networkRateMbps != null) {\n averageBandwidth = networkRateMbps.intValue();\n policyName += averageBandwidth;\n }\n try {\n // TODO(sateesh): Change the type of peakBandwidth & burstRate in\n // PolicyMap to long.\n if (averageBandwidth > 0) {\n LOGGER.debug(\"Adding policy map \" + policyName);\n netconfClient.addPolicyMap(policyName, averageBandwidth, (int) peakBandwidth, (int) burstSize);\n }\n } catch (CloudRuntimeException e) {\n msg = \"Failed to add policy map of \" + policyName + \" with parameters \" + \"committed rate = \" + averageBandwidth + \"peak bandwidth = \" + peakBandwidth + \"burst size = \" + burstSize + \". Exception: \" + e.toString();\n LOGGER.error(msg);\n if (netconfClient != null) {\n netconfClient.disconnect();\n LOGGER.debug(\"Disconnected Nexus 1000v session.\");\n }\n throw new CloudRuntimeException(msg);\n }\n List> params = new ArrayList>();\n if (vlanId != null) {\n // No need to update ethernet port profile for untagged vlans\n params.add(new Pair(OperationType.addvlanid, vlanId.toString()));\n try {\n LOGGER.info(\"Updating Ethernet port profile \" + ethPortProfileName + \" with VLAN \" + vlanId);\n netconfClient.updatePortProfile(ethPortProfileName, SwitchPortMode.trunk, params);\n LOGGER.info(\"Added \" + vlanId + \" to Ethernet port profile \" + ethPortProfileName);\n } catch (CloudRuntimeException e) {\n msg = \"Failed to update Ethernet port profile \" + ethPortProfileName + \" with VLAN \" + vlanId + \". Exception: \" + e.toString();\n LOGGER.error(msg);\n if (netconfClient != null) {\n netconfClient.disconnect();\n LOGGER.debug(\"Disconnected Nexus 1000v session.\");\n }\n throw new CloudRuntimeException(msg);\n }\n }\n try {\n if (vlanId == null) {\n LOGGER.info(\"Adding port profile configured over untagged VLAN.\");\n netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, 0);\n } else {\n if (!configureVServiceInNexus) {\n LOGGER.info(\"Adding port profile configured over VLAN : \" + vlanId.toString());\n netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, vlanId.intValue());\n } else {\n String tenant = \"vlan-\" + vlanId.intValue();\n String vdc = \"root/\" + tenant + \"/VDC-\" + tenant;\n String esp = \"ESP-\" + tenant;\n LOGGER.info(\"Adding vservice node in Nexus VSM for VLAN : \" + vlanId.toString());\n netconfClient.addVServiceNode(vlanId.toString(), gateway);\n LOGGER.info(\"Adding port profile with vservice details configured over VLAN : \" + vlanId.toString());\n netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, vlanId.intValue(), vdc, esp);\n }\n }\n } catch (CloudRuntimeException e) {\n msg = \"Failed to add vEthernet port profile \" + networkName + \".\" + \". Exception: \" + e.toString();\n LOGGER.error(msg);\n if (netconfClient != null) {\n netconfClient.disconnect();\n LOGGER.debug(\"Disconnected Nexus 1000v session.\");\n }\n throw new CloudRuntimeException(msg);\n }\n try {\n if (averageBandwidth > 0) {\n LOGGER.info(\"Associating policy map \" + policyName + \" with port profile \" + networkName + \".\");\n netconfClient.attachServicePolicy(policyName, networkName);\n }\n } catch (CloudRuntimeException e) {\n msg = \"Failed to associate policy map \" + policyName + \" with port profile \" + networkName + \". Exception: \" + e.toString();\n LOGGER.error(msg);\n throw new CloudRuntimeException(msg);\n } finally {\n if (netconfClient != null) {\n netconfClient.disconnect();\n LOGGER.debug(\"Disconnected Nexus 1000v session.\");\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "protected final void propagateResult(AccumulateNode accNode, LeftTupleSink sink, LeftTuple leftTuple, PropagationContext context, ReteEvaluator reteEvaluator, AccumulateMemory memory, TupleSets trgLeftTuples, TupleSets stagedLeftTuples, Object key, Object result, AccumulateContextEntry accPropCtx, PropagationContext propagationContext, boolean allowNullPropagation){\r\n if (!allowNullPropagation && result == null) {\r\n if (accPropCtx.isPropagated()) {\r\n trgLeftTuples.addDelete((LeftTuple) accPropCtx.getResultLeftTuple());\r\n accPropCtx.setPropagated(false);\r\n }\r\n return;\r\n }\r\n if (accPropCtx.getResultFactHandle() == null) {\r\n InternalFactHandle handle = accNode.createResultFactHandle(context, reteEvaluator, leftTuple, createResult(accNode, key, result));\r\n accPropCtx.setResultFactHandle(handle);\r\n accPropCtx.setResultLeftTuple(sink.createLeftTuple(handle, leftTuple, sink));\r\n } else {\r\n ((InternalFactHandle) accPropCtx.getResultFactHandle()).setObject(createResult(accNode, key, result));\r\n }\r\n AlphaNodeFieldConstraint[] resultConstraints = accNode.getResultConstraints();\r\n BetaConstraints resultBinder = accNode.getResultBinder();\r\n boolean isAllowed = true;\r\n for (AlphaNodeFieldConstraint resultConstraint : resultConstraints) {\r\n if (!resultConstraint.isAllowed(accPropCtx.getResultFactHandle(), reteEvaluator)) {\r\n isAllowed = false;\r\n break;\r\n }\r\n }\r\n if (isAllowed) {\r\n resultBinder.updateFromTuple(memory.resultsContext, reteEvaluator, leftTuple);\r\n if (!resultBinder.isAllowedCachedLeft(memory.resultsContext, accPropCtx.getResultFactHandle())) {\r\n isAllowed = false;\r\n }\r\n resultBinder.resetTuple(memory.resultsContext);\r\n }\r\n LeftTuple childLeftTuple = (LeftTuple) accPropCtx.getResultLeftTuple();\r\n childLeftTuple.setPropagationContext(propagationContext != null ? propagationContext : leftTuple.getPropagationContext());\r\n if (accPropCtx.isPropagated()) {\r\n normalizeStagedTuples(stagedLeftTuples, childLeftTuple);\r\n if (isAllowed) {\r\n trgLeftTuples.addUpdate(childLeftTuple);\r\n } else {\r\n trgLeftTuples.addDelete(childLeftTuple);\r\n accPropCtx.setPropagated(false);\r\n }\r\n } else if (isAllowed) {\r\n trgLeftTuples.addInsert(childLeftTuple);\r\n accPropCtx.setPropagated(true);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "//\taddRestriction\n/**\n * \tAdd Range Restriction (BETWEEN)\n * \t@param ColumnName ColumnName\n * \t@param Code from value, e.g 0, All%\n * \t@param Code_to to value, e.g 0, All%\n * @param InfoName Display Name\n * \t@param InfoDisplay Display of Code (Lookup)\n * \t@param InfoDisplay_to Display of Code_to (Lookup)\n * @param andCondition true=and, false=or\n * @param depth number of parenthesis\n */\npublic void addRangeRestriction(String ColumnName, Object Code, Object Code_to, String InfoName, String InfoDisplay, String InfoDisplay_to, boolean andCondition, int depth) {\n addRangeRestriction(ColumnName, Code, Code_to, InfoName, InfoDisplay, InfoDisplay_to, andCondition ? \"AND\" : \"OR\", depth);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public String layoutCompoundLabel(FontMetrics fm, String text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) {\n /* Initialize the icon bounds rectangle iconR.\n \t */\n if (icon != null) {\n iconR.width = icon.getIconWidth();\n iconR.height = icon.getIconHeight();\n } else {\n iconR.width = iconR.height = 0;\n }\n /* Initialize the text bounds rectangle textR. If a null\n \t * or and empty String was specified we substitute \"\" here\n \t * and use 0,0,0,0 for textR.\n \t */\n boolean textIsEmpty = (text == null) || text.equals(\"\");\n /* Unless both text and icon are non-null, we effectively ignore\n \t * the value of textIconGap. The code that follows uses the\n \t * value of gap instead of textIconGap.\n \t */\n int gap = (textIsEmpty || (icon == null)) ? 0 : textIconGap;\n /* NOTE: break up the text into multiple lines */\n /* TODO: clean up parseTextV and wrapString */\n if (!_parsed) {\n textVector = new Vector<>();\n if (preferredSize != null) {\n /* remove newline before calling wrapString\n if (!textIsEmpty) {\n text = text.replace('\\n', ' ');\n }\n textVector.addElement(text);\n */\n int iconW;\n iconW = (icon == null) ? 0 : icon.getIconWidth();\n Vector tmp = new Vector<>();\n //Debug.println(\"calling parseTextV with \" + text);\n parseTextV(text, tmp);\n for (Enumeration e = tmp.elements(); e.hasMoreElements(); ) {\n String subs = e.nextElement();\n //Debug.println(\"parseTextV returns \" + subs);\n textVector.addElement(subs);\n wrapString(textVector, fm, preferredSize.width - gap - iconW, SEPARATORS);\n }\n } else {\n parseTextV(text, textVector);\n }\n _parsed = true;\n }\n widthArray = new int[textVector.size()];\n offsetArray = new int[widthArray.length];\n if (textIsEmpty) {\n textR.width = textR.height = 0;\n text = \"\";\n } else {\n textR.width = computeStringVWidth(fm, textVector, widthArray);\n textR.height = fm.getHeight() * textVector.size();\n }\n /* NOTE: we need to handle clipped case\n \tif (!textIsEmpty) {\n\n \t int availTextWidth;\n\n \t if (horizontalTextPosition == CENTER) {\n \t\tavailTextWidth = viewR.width;\n \t }\n \t else {\n \t\tavailTextWidth = viewR.width - (iconR.width + gap);\n \t }\n\n\n \t if (textR.width > availTextWidth) {\n \t\tString clipString = \"...\";\n \t\tint totalWidth = computeStringWidth(fm,clipString);\n \t\tint nChars;\n \t\tfor(nChars = 0; nChars < text.length(); nChars++) {\n \t\t totalWidth += fm.charWidth(text.charAt(nChars));\n \t\t if (totalWidth > availTextWidth) {\n \t\t\tbreak;\n \t\t }\n \t\t}\n \t\ttext = text.substring(0, nChars) + clipString;\n \t\ttextR.width = computeStringWidth(fm,text);\n \t }\n \t}\n */\n /* Compute textR.x,y given the verticalTextPosition and\n \t * horizontalTextPosition properties\n \t */\n if (verticalTextPosition == SwingUtilities.TOP) {\n if (horizontalTextPosition != SwingUtilities.CENTER) {\n textR.y = 0;\n } else {\n textR.y = -(textR.height + gap);\n }\n } else if (verticalTextPosition == SwingUtilities.CENTER) {\n textR.y = (iconR.height / 2) - (textR.height / 2);\n } else {\n // (verticalTextPosition == SwingUtilities.BOTTOM)\n if (horizontalTextPosition != SwingUtilities.CENTER) {\n textR.y = iconR.height - textR.height;\n } else {\n textR.y = (iconR.height + gap);\n }\n }\n if (horizontalTextPosition == SwingUtilities.LEFT) {\n textR.x = -(textR.width + gap);\n } else if (horizontalTextPosition == SwingUtilities.CENTER) {\n textR.x = (iconR.width / 2) - (textR.width / 2);\n } else {\n // (verticalTextPosition == SwingUtilities.RIGHT)\n textR.x = (iconR.width + gap);\n }\n /* labelR is the rectangle that contains iconR and textR.\n \t * Move it to its proper position given the labelAlignment\n \t * properties.\n \t */\n Rectangle labelR = iconR.union(textR);\n int dx, dy;\n if (verticalAlignment == SwingUtilities.TOP) {\n dy = viewR.y - labelR.y;\n } else if (verticalAlignment == SwingUtilities.CENTER) {\n dy = (viewR.y + (viewR.height / 2)) - (labelR.y + (labelR.height / 2));\n } else {\n // (verticalAlignment == SwingUtilities.BOTTOM)\n dy = (viewR.y + viewR.height) - (labelR.y + labelR.height);\n }\n if (horizontalAlignment == SwingUtilities.LEFT) {\n dx = viewR.x - labelR.x;\n } else if (horizontalAlignment == SwingUtilities.CENTER) {\n dx = (viewR.x + (viewR.width / 2)) - (labelR.x + (labelR.width / 2));\n } else {\n // (horizontalAlignment == SwingUtilities.RIGHT)\n dx = (viewR.x + viewR.width) - (labelR.x + labelR.width);\n }\n /* Translate textR and glypyR by dx,dy.\n \t */\n textR.x += dx;\n textR.y += dy;\n iconR.x += dx;\n iconR.y += dy;\n /* NOTE: calculate string offsets based on the string width and\n \t * horizontal alignment\n \t */\n computeOffset(textR, horizontalAlignment, widthArray, offsetArray);\n //Debug.println(\"layoutCompound: \" + text + \" \" + textR);\n return text;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "public static ImmutableMap of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3){\r\n Map map = new HashMap<>();\r\n putAndWarnDuplicateKeys(map, k0, v0);\r\n putAndWarnDuplicateKeys(map, k1, v1);\r\n putAndWarnDuplicateKeys(map, k2, v2);\r\n putAndWarnDuplicateKeys(map, k3, v3);\r\n return new ImmutableMap<>(map);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Add one buffer with compressed data the results for addOneCompressionBuffer (see javadoc).\n * @param fullCompressionBlock (fCB) Entire compression block, sliced or copied from disk data.\n * @param isUncompressed Whether the data in the block is uncompressed.\n * @param cbStartOffset Compressed start offset of the fCB.\n * @param cbEndOffset Compressed end offset of the fCB.\n * @param lastChunkLength The number of compressed bytes consumed from last *chunk* into fullCompressionBlock.\n * @param lastChunk\n * @param toDecompress See addOneCompressionBuffer.\n * @param cacheBuffers See addOneCompressionBuffer.\n * @return New cache buffer.\n */\nprivate ProcCacheChunk addOneCompressionBlockByteBuffer(ByteBuffer fullCompressionBlock, boolean isUncompressed, long cbStartOffset, long cbEndOffset, int lastChunkLength, BufferChunk lastChunk, List toDecompress, List cacheBuffers, boolean doTrace) {\n // Prepare future cache buffer.\n MemoryBuffer futureAlloc = cacheWrapper.getDataBufferFactory().create();\n // Add it to result in order we are processing.\n cacheBuffers.add(futureAlloc);\n // Add it to the list of work to decompress.\n ProcCacheChunk cc = new ProcCacheChunk(cbStartOffset, cbEndOffset, !isUncompressed, fullCompressionBlock, futureAlloc, cacheBuffers.size() - 1);\n toDecompress.add(cc);\n // Adjust the compression block position.\n if (isTracingEnabled) {\n LOG.trace(\"Adjusting \" + lastChunk + \" to consume \" + lastChunkLength + \" compressed bytes\");\n }\n if (doTrace) {\n trace.logCompositeOrcCb(lastChunkLength, lastChunk.getData().remaining(), cc);\n }\n lastChunk.getData().position(lastChunk.getData().position() + lastChunkLength);\n // Finally, put it in the ranges list for future use (if shared between RGs).\n // Before anyone else accesses it, it would have been allocated and decompressed locally.\n if (lastChunk.getData().remaining() <= 0) {\n if (isTracingEnabled) {\n LOG.trace(\"Replacing \" + lastChunk + \" with \" + cc + \" in the buffers\");\n }\n lastChunk.replaceSelfWith(cc);\n } else {\n if (isTracingEnabled) {\n LOG.trace(\"Adding \" + cc + \" before \" + lastChunk + \" in the buffers\");\n }\n lastChunk.insertPartBefore(cc);\n }\n return cc;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public PrincipalInterest calculateTotalInterestForPeriod(final PaymentPeriodsInOneYearCalculator calculator, final BigDecimal interestCalculationGraceOnRepaymentPeriodFraction, final int periodNumber, final MathContext mc, final Money cumulatingInterestPaymentDueToGrace, final Money outstandingBalance, final LocalDate periodStartDate, final LocalDate periodEndDate) {\n Money interestForInstallment = this.principal.zero();\n Money interestBroughtForwardDueToGrace = cumulatingInterestPaymentDueToGrace.copy();\n InterestMethod interestMethod = this.interestMethod;\n if (this.isEqualAmortization() && this.totalInterestDue != null) {\n interestMethod = InterestMethod.FLAT;\n }\n switch(interestMethod) {\n case FLAT:\n if (this.isEqualAmortization() && this.totalInterestDue != null && this.interestMethod.isDecliningBalance()) {\n interestForInstallment = flatInterestPerInstallment(mc, this.totalInterestDue);\n } else {\n switch(this.amortizationMethod) {\n case EQUAL_INSTALLMENTS:\n // average out outstanding interest over remaining\n // instalments where interest is applicable\n interestForInstallment = calculateTotalFlatInterestForInstallmentAveragingOutGracePeriods(calculator, periodNumber, mc);\n break;\n case EQUAL_PRINCIPAL:\n // interest follows time-value of money and is\n // brought\n // forward to next applicable interest payment\n // period\n final PrincipalInterest result = calculateTotalFlatInterestForPeriod(calculator, periodNumber, mc, interestBroughtForwardDueToGrace);\n interestForInstallment = result.interest();\n interestBroughtForwardDueToGrace = result.interestPaymentDueToGrace();\n break;\n case INVALID:\n break;\n }\n }\n break;\n case DECLINING_BALANCE:\n final Money interestForThisInstallmentBeforeGrace = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace(calculator, mc, outstandingBalance, periodStartDate, periodEndDate);\n final Money interestForThisInstallmentAfterGrace = calculateDecliningInterestDueForInstallmentAfterApplyingGrace(calculator, interestCalculationGraceOnRepaymentPeriodFraction, mc, outstandingBalance, periodNumber, periodStartDate, periodEndDate);\n interestForInstallment = interestForThisInstallmentAfterGrace;\n if (interestForThisInstallmentAfterGrace.isGreaterThanZero()) {\n interestForInstallment = interestBroughtForwardDueToGrace.plus(interestForThisInstallmentAfterGrace);\n interestBroughtForwardDueToGrace = interestBroughtForwardDueToGrace.zero();\n } else if (isInterestFreeGracePeriod(periodNumber)) {\n interestForInstallment = interestForInstallment.zero();\n } else {\n interestBroughtForwardDueToGrace = interestBroughtForwardDueToGrace.plus(interestForThisInstallmentBeforeGrace);\n }\n break;\n case INVALID:\n break;\n }\n return new PrincipalInterest(null, interestForInstallment, interestBroughtForwardDueToGrace);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "protected boolean updateRecordWithExpiry(Data key, Object value, R record, ExpiryPolicy expiryPolicy, long now, boolean disableWriteThrough, int completionId, UUID source){\r\n return updateRecordWithExpiry(key, value, record, expiryPolicy, now, disableWriteThrough, completionId, source, null);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void verifyChunkedSumsByteArray(int bytesPerSum, int checksumType, byte[] sums, int sumsOffset, byte[] data, int dataOffset, int dataLength, String fileName, long basePos) throws ChecksumException {\n nativeComputeChunkedSumsByteArray(bytesPerSum, checksumType, sums, sumsOffset, data, dataOffset, dataLength, fileName, basePos, true);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void doNode(TimerNode timerNode, TimerNodeMemory tm, PathMemory pmem, SegmentMemory smem, LeftTupleSink sink, ActivationsManager activationsManager, TupleSets srcLeftTuples, TupleSets trgLeftTuples, TupleSets stagedLeftTuples){\r\n if (srcLeftTuples.getDeleteFirst() != null) {\r\n doLeftDeletes(timerNode, tm, pmem, sink, activationsManager, srcLeftTuples, trgLeftTuples, stagedLeftTuples);\r\n }\r\n if (srcLeftTuples.getUpdateFirst() != null) {\r\n doLeftUpdates(timerNode, tm, pmem, smem, sink, activationsManager, srcLeftTuples, trgLeftTuples, stagedLeftTuples);\r\n }\r\n if (srcLeftTuples.getInsertFirst() != null) {\r\n doLeftInserts(timerNode, tm, pmem, smem, sink, activationsManager, srcLeftTuples, trgLeftTuples);\r\n }\r\n doPropagateChildLeftTuples(tm, sink, trgLeftTuples, stagedLeftTuples);\r\n srcLeftTuples.resetAll();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprivate static LoptJoinTree addFactorToTree(RelMetadataQuery mq, RelBuilder relBuilder, LoptMultiJoin multiJoin, LoptSemiJoinOptimizer semiJoinOpt, @Nullable LoptJoinTree joinTree, int factorToAdd, BitSet factorsNeeded, List filtersToAdd, boolean selfJoin){\r\n if (multiJoin.isRemovableOuterJoinFactor(factorToAdd)) {\r\n return createReplacementJoin(relBuilder, multiJoin, semiJoinOpt, requireNonNull(joinTree, \"joinTree\"), -1, factorToAdd, ImmutableIntList.of(), null, filtersToAdd);\r\n }\r\n if (multiJoin.getJoinRemovalFactor(factorToAdd) != null) {\r\n return createReplacementSemiJoin(relBuilder, multiJoin, semiJoinOpt, joinTree, factorToAdd, filtersToAdd);\r\n }\r\n if (joinTree == null) {\r\n return new LoptJoinTree(semiJoinOpt.getChosenSemiJoin(factorToAdd), factorToAdd);\r\n }\r\n final List tmpFilters = new ArrayList<>(filtersToAdd);\r\n LoptJoinTree topTree = addToTop(mq, relBuilder, multiJoin, semiJoinOpt, joinTree, factorToAdd, filtersToAdd, selfJoin);\r\n LoptJoinTree pushDownTree = pushDownFactor(mq, relBuilder, multiJoin, semiJoinOpt, joinTree, factorToAdd, factorsNeeded, (topTree == null) ? filtersToAdd : tmpFilters, selfJoin);\r\n LoptJoinTree bestTree;\r\n RelOptCost costPushDown = null;\r\n RelOptCost costTop = null;\r\n if (pushDownTree != null) {\r\n costPushDown = mq.getCumulativeCost(pushDownTree.getJoinTree());\r\n }\r\n if (topTree != null) {\r\n costTop = mq.getCumulativeCost(topTree.getJoinTree());\r\n }\r\n if (pushDownTree == null) {\r\n bestTree = topTree;\r\n } else if (topTree == null) {\r\n bestTree = pushDownTree;\r\n } else {\r\n requireNonNull(costPushDown, \"costPushDown\");\r\n requireNonNull(costTop, \"costTop\");\r\n if (costPushDown.isEqWithEpsilon(costTop)) {\r\n if (rowWidthCost(pushDownTree.getJoinTree()) < rowWidthCost(topTree.getJoinTree())) {\r\n bestTree = pushDownTree;\r\n } else {\r\n bestTree = topTree;\r\n }\r\n } else if (costPushDown.isLt(costTop)) {\r\n bestTree = pushDownTree;\r\n } else {\r\n bestTree = topTree;\r\n }\r\n }\r\n return bestTree;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Enumerable aggregate(List ops, List> fields, List> sort, List groupBy, List> aggregations, Map mapping, Long offset, Long fetch) throws IOException {\n if (!groupBy.isEmpty() && offset != null) {\n String message = \"Currently ES doesn't support generic pagination \" + \"with aggregations. You can still use LIMIT keyword (without OFFSET). \" + \"For more details see https://github.com/elastic/elasticsearch/issues/4915\";\n throw new IllegalStateException(message);\n }\n final ObjectNode query = mapper.createObjectNode();\n // manually parse into JSON from previously concatenated strings\n for (String op : ops) {\n query.setAll((ObjectNode) mapper.readTree(op));\n }\n // remove / override attributes which are not applicable to aggregations\n query.put(\"_source\", false);\n query.put(\"size\", 0);\n query.remove(\"script_fields\");\n // set _source = false and size = 0, `FetchPhase` would still be executed\n // to fetch the metadata fields and visit the Lucene stored_fields,\n // which would lead to performance declined dramatically.\n // `stored_fields = _none` can prohibit such behavior entirely\n query.put(\"stored_fields\", \"_none_\");\n // allows to detect aggregation for count(*)\n final Predicate> isCountStar = e -> e.getValue().contains(\"\\\"\" + ElasticsearchConstants.ID + \"\\\"\");\n // list of expressions which are count(*)\n final Set countAll = aggregations.stream().filter(isCountStar).map(Map.Entry::getKey).collect(Collectors.toSet());\n final Map fieldMap = new HashMap<>();\n // due to ES aggregation format. fields in \"order by\" clause should go first\n // if \"order by\" is missing. order in \"group by\" is un-important\n final Set orderedGroupBy = new LinkedHashSet<>();\n orderedGroupBy.addAll(sort.stream().map(Map.Entry::getKey).collect(Collectors.toList()));\n orderedGroupBy.addAll(groupBy);\n // construct nested aggregations node(s)\n ObjectNode parent = query.withObject(\"/\" + AGGREGATIONS);\n for (String name : orderedGroupBy) {\n final String aggName = \"g_\" + name;\n fieldMap.put(aggName, name);\n final ObjectNode section = parent.withObject(\"/\" + aggName);\n final ObjectNode terms = section.withObject(\"/terms\");\n terms.put(\"field\", name);\n transport.mapping.missingValueFor(name).ifPresent(m -> {\n // expose missing terms. each type has a different missing value\n terms.set(\"missing\", m);\n });\n if (fetch != null) {\n terms.put(\"size\", fetch);\n }\n sort.stream().filter(e -> e.getKey().equals(name)).findAny().ifPresent(s -> terms.withObject(\"/order\").put(\"_key\", s.getValue().isDescending() ? \"desc\" : \"asc\"));\n parent = section.withObject(\"/\" + AGGREGATIONS);\n }\n // simple version for queries like \"select count(*), max(col1) from table\" (no GROUP BY cols)\n if (!groupBy.isEmpty() || !aggregations.stream().allMatch(isCountStar)) {\n for (Map.Entry aggregation : aggregations) {\n JsonNode value = mapper.readTree(aggregation.getValue());\n parent.set(aggregation.getKey(), value);\n }\n }\n final Consumer emptyAggRemover = new Consumer() {\n\n @Override\n public void accept(JsonNode node) {\n if (!node.has(AGGREGATIONS)) {\n node.elements().forEachRemaining(this);\n return;\n }\n JsonNode agg = node.get(AGGREGATIONS);\n if (agg.isEmpty()) {\n ((ObjectNode) node).remove(AGGREGATIONS);\n } else {\n this.accept(agg);\n }\n }\n };\n // cleanup query. remove empty AGGREGATIONS element (if empty)\n emptyAggRemover.accept(query);\n // This must be set to true or else in 7.X and 6/7 mixed clusters\n // will return lower bounded count values instead of an accurate count.\n if (groupBy.isEmpty() && version.elasticVersionMajor() >= ElasticsearchVersion.ES6.elasticVersionMajor()) {\n query.put(\"track_total_hits\", true);\n }\n ElasticsearchJson.Result res = transport.search(Collections.emptyMap()).apply(query);\n final List> result = new ArrayList<>();\n if (res.aggregations() != null) {\n // collect values\n ElasticsearchJson.visitValueNodes(res.aggregations(), m -> {\n // using 'Collectors.toMap' will trigger Java 8 bug here\n Map newMap = new LinkedHashMap<>();\n for (String key : m.keySet()) {\n newMap.put(fieldMap.getOrDefault(key, key), m.get(key));\n }\n result.add(newMap);\n });\n } else {\n // probably no group by. add single result\n result.add(new LinkedHashMap<>());\n }\n // elastic exposes total number of documents matching a query in \"/hits/total\" path\n // this can be used for simple \"select count(*) from table\"\n final long total = res.searchHits().total().value();\n if (groupBy.isEmpty()) {\n // put totals automatically for count(*) expression(s), unless they contain group by\n for (String expr : countAll) {\n result.forEach(m -> m.put(expr, total));\n }\n }\n final Function1 getter = ElasticsearchEnumerators.getter(fields, ImmutableMap.copyOf(mapping));\n ElasticsearchJson.SearchHits hits = new ElasticsearchJson.SearchHits(res.searchHits().total(), result.stream().map(r -> new ElasticsearchJson.SearchHit(\"_id\", r, null)).collect(Collectors.toList()));\n return Linq4j.asEnumerable(hits.hits()).select(getter);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public SR getIscsiSR(final Connection conn, final String srNameLabel, final String target, String path, final String chapInitiatorUsername, final String chapInitiatorPassword, final boolean resignature, final String srType, final boolean ignoreIntroduceException) {\n synchronized (srNameLabel.intern()) {\n final Map deviceConfig = new HashMap();\n try {\n if (path.endsWith(\"/\")) {\n path = path.substring(0, path.length() - 1);\n }\n final String[] tmp = path.split(\"/\");\n if (tmp.length != 3) {\n final String msg = \"Wrong iscsi path \" + path + \" it should be /targetIQN/LUN\";\n logger.warn(msg);\n throw new CloudRuntimeException(msg);\n }\n final String targetiqn = tmp[1].trim();\n final String lunid = tmp[2].trim();\n String scsiid = \"\";\n //Throws an exception if SR already exists and is attached\n checkIfIscsiSrExisits(conn, srNameLabel, target, targetiqn, lunid);\n // We now know the SR is not attached to the XenServer. We probe the\n // LUN to see if an SR was already exists on it, if so, we just\n // attach it or else we create a brand new SR\n deviceConfig.put(\"target\", target);\n deviceConfig.put(\"targetIQN\", targetiqn);\n if (StringUtils.isNoneBlank(chapInitiatorUsername, chapInitiatorPassword)) {\n deviceConfig.put(\"chapuser\", chapInitiatorUsername);\n deviceConfig.put(\"chappassword\", chapInitiatorPassword);\n }\n final Host host = Host.getByUuid(conn, _host.getUuid());\n final Map smConfig = new HashMap();\n SR sr = null;\n String pooluuid = null;\n if (SRType.LVMOISCSI.equals(srType)) {\n scsiid = probeScisiId(conn, host, deviceConfig, srType, srNameLabel, lunid, smConfig);\n deviceConfig.put(\"SCSIid\", scsiid);\n String result = SR.probe(conn, host, deviceConfig, srType, smConfig);\n if (result.indexOf(\"\") != -1) {\n pooluuid = result.substring(result.indexOf(\"\") + 6, result.indexOf(\"\")).trim();\n }\n }\n if (pooluuid == null || pooluuid.length() != 36) {\n sr = SR.create(conn, host, deviceConfig, new Long(0), srNameLabel, srNameLabel, srType, \"user\", true, smConfig);\n } else {\n if (resignature) {\n // We resignature the SR for managed storage if needed. At the end of this\n // we have an SR which is ready to be attached. For VHDoISCSI SR,\n // we don't need to resignature\n pooluuid = resignatureIscsiSr(conn, host, deviceConfig, srNameLabel, smConfig);\n }\n sr = introduceAndPlugIscsiSr(conn, pooluuid, srNameLabel, srType, smConfig, deviceConfig, ignoreIntroduceException);\n }\n sr.scan(conn);\n return sr;\n } catch (final XenAPIException e) {\n final String msg = \"Unable to create Iscsi SR \" + deviceConfig + \" due to \" + e.toString();\n logger.warn(msg, e);\n throw new CloudRuntimeException(msg, e);\n } catch (final Exception e) {\n final String msg = \"Unable to create Iscsi SR \" + deviceConfig + \" due to \" + e.getMessage();\n logger.warn(msg, e);\n throw new CloudRuntimeException(msg, e);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, String consumes, String produces, RestConfiguration configuration, Map parameters, boolean api) throws Exception{\r\n String path = basePath;\r\n if (uriTemplate != null) {\r\n if (uriTemplate.startsWith(\"/\")) {\r\n path = path + uriTemplate;\r\n } else {\r\n path = path + \"/\" + uriTemplate;\r\n }\r\n }\r\n path = FileUtil.stripLeadingSeparator(path);\r\n RestConfiguration config = configuration;\r\n if (config == null) {\r\n config = CamelContextHelper.getRestConfiguration(getCamelContext(), PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME);\r\n }\r\n String contextPath = config.getContextPath();\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n contextPath = FileUtil.stripTrailingSeparator(contextPath);\r\n contextPath = FileUtil.stripLeadingSeparator(contextPath);\r\n if (ObjectHelper.isNotEmpty(contextPath)) {\r\n path = contextPath + \"/\" + path;\r\n }\r\n }\r\n Map map = RestComponentHelper.initRestEndpointProperties(PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME, config);\r\n boolean cors = config.isEnableCORS();\r\n if (api) {\r\n map.put(\"matchOnUriPrefix\", \"true\");\r\n }\r\n RestComponentHelper.addHttpRestrictParam(map, verb, cors);\r\n String url = RestComponentHelper.createRestConsumerUrl(\"platform-http\", path, map);\r\n PlatformHttpEndpoint endpoint = (PlatformHttpEndpoint) camelContext.getEndpoint(url, parameters);\r\n endpoint.setConsumes(consumes);\r\n endpoint.setProduces(produces);\r\n Consumer consumer = endpoint.createConsumer(processor);\r\n if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {\r\n setProperties(camelContext, consumer, config.getConsumerProperties());\r\n }\r\n return consumer;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create Depreciation Entries\n * @param assetwk\n * @param PeriodNo\n * @param dateAcct\n * @param amt\n * @param amt_F\n * @param accumAmt\n * @param accumAmt_F\n * @param help\n * @param trxName\n * @return collection of MDepreciationExp records\n */\npublic static Collection createDepreciation(MDepreciationWorkfile assetwk, int PeriodNo, Timestamp dateAcct, BigDecimal amt, BigDecimal amt_F, BigDecimal accumAmt, BigDecimal accumAmt_F, String help, String trxName) {\n ArrayList list = new ArrayList();\n Properties ctx = assetwk.getCtx();\n MAssetAcct assetAcct = assetwk.getA_AssetAcct(dateAcct, trxName);\n MDepreciationExp depexp = null;\n depexp = createEntry(ctx, A_ENTRY_TYPE_Depreciation, assetwk.getA_Asset_ID(), PeriodNo, dateAcct, assetwk.getPostingType(), assetAcct.getA_Depreciation_Acct(), assetAcct.getA_Accumdepreciation_Acct(), amt, \"@AssetDepreciationAmt@\", assetwk);\n if (depexp != null) {\n // added by zuhri\n depexp.setAD_Org_ID(assetwk.getA_Asset().getAD_Org_ID());\n if (accumAmt != null)\n depexp.setA_Accumulated_Depr(accumAmt);\n if (accumAmt_F != null)\n depexp.setA_Accumulated_Depr_F(accumAmt_F);\n if (help != null && help.length() > 0)\n depexp.setHelp(help);\n depexp.setExpense_F(amt_F);\n depexp.setA_Accumulated_Depr_Delta(amt);\n depexp.setA_Accumulated_Depr_F_Delta(amt_F);\n depexp.saveEx(assetwk.get_TrxName());\n list.add(depexp);\n }\n return list;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "//SCP03 wrap a session key with AES kek key.\npublic byte[] encryptData_SCP03(String selectedToken, String keyNickName, byte[] data, byte[] keyInfo, byte nistSP800_108KdfOnKeyVersion, boolean nistSP800_108KdfUseCuidAsKdd, byte[] xCUID, byte[] xKDD, byte[] kekKeyArray, String useSoftToken_s, String keySet, GPParams params) throws EBaseException {\n String method = \"SecureChannelProtocol.encryptData_SCP03:\";\n logger.debug(method + \" Entering ....\");\n String transportKeyName = SecureChannelProtocol.getSharedSecretKeyName(null);\n if (keyInfo == null || keySet == null || (keyInfo == null || keyInfo.length < 2) || params == null) {\n throw new EBaseException(method + \"Invalid input!\");\n }\n if (xCUID == null || xCUID.length <= 0) {\n throw new EBaseException(method + \"CUID invalid size!\");\n }\n if (xKDD == null || xKDD.length != NistSP800_108KDF.KDD_SIZE_BYTES) {\n throw new EBaseException(method + \"KDD invalid size!\");\n }\n SymmetricKey kekKey = computeSessionKey_SCP03(selectedToken, keyNickName, keyInfo, kekType, kekKeyArray, keySet, xCUID, xKDD, null, null, transportKeyName, params);\n byte[] output = null;\n output = computeAES_CBCEncryption(kekKey, selectedToken, data, null);\n //debugByteArray(output, method + \" encryptData: Output: \");\n return output;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "//\tpaint\n/**\n * \tPrint non zero width Column\n * \t@param g2D graphics\n * \t@param col column index\n * \t@param origX start X\n * \t@param origY start Y\n * @param leftVline if true print left vertical line (for first column)\n * \t@param firstRow first row index\n * \t@param nextPageRow row index of next page\n * @param isView true if online view (IDs are links)\n */\nprivate void printColumn(Graphics2D g2D, int col, final int origX, final int origY, boolean leftVline, final int firstRow, final int nextPageRow, boolean isView) {\n int curX = origX;\n //\tstart from top\n int curY = origY;\n //\n //\tincludes 2*Gaps+Line\n float colWidth = ((Float) m_columnWidths.get(col)).floatValue();\n float netWidth = colWidth - (2 * H_GAP) - m_tFormat.getVLineStroke().floatValue();\n if (leftVline)\n netWidth -= m_tFormat.getVLineStroke().floatValue();\n float rowHeight = m_headerHeight;\n float netHeight = rowHeight - (4 * m_tFormat.getLineStroke().floatValue()) + (2 * V_GAP);\n if (DEBUG_PRINT)\n if (log.isLoggable(Level.FINER))\n log.finer(\"#\" + col + \" - x=\" + curX + \", y=\" + curY + \", width=\" + colWidth + \"/\" + netWidth + \", HeaderHeight=\" + rowHeight + \"/\" + netHeight);\n String alignment = m_columnJustification[col];\n //\tpaint header\t***************************************************\n if (//\tdraw left | line\n leftVline) {\n g2D.setPaint(m_tFormat.getVLine_Color());\n g2D.setStroke(m_tFormat.getVLine_Stroke());\n if (//\t -> | (left)\n m_tFormat.isPaintBoundaryLines())\n g2D.drawLine(origX, (int) (origY + m_tFormat.getLineStroke().floatValue()), origX, (int) (origY + rowHeight - (4 * m_tFormat.getLineStroke().floatValue())));\n curX += m_tFormat.getVLineStroke().floatValue();\n }\n //\tX - start line\n if (m_tFormat.isPaintHeaderLines()) {\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(m_tFormat.getHeader_Stroke());\n //\t -> - (top)\n g2D.//\t -> - (top)\n drawLine(//\t -> - (top)\n origX, //\t -> - (top)\n origY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), origY);\n }\n //\tthick\n curY += (2 * m_tFormat.getLineStroke().floatValue());\n //\tBackground\n Color bg = getBackground(HEADER_ROW, col);\n if (!bg.equals(Color.white)) {\n g2D.setPaint(bg);\n g2D.fillRect(curX, (int) (curY - m_tFormat.getLineStroke().floatValue()), (int) (colWidth - m_tFormat.getVLineStroke().floatValue()), (int) (rowHeight - (4 * m_tFormat.getLineStroke().floatValue())));\n }\n int tempCurY = curY;\n //\tupper left gap\n curX += H_GAP;\n curY += V_GAP;\n //\tHeader\n AttributedString aString = null;\n AttributedCharacterIterator iter = null;\n LineBreakMeasurer measurer = null;\n float usedHeight = 0;\n // Calculate column header height - teo_sarca [ 1673429 ]\n String headerString = m_columnHeader[col].toString();\n if (headerString.length() == 0)\n headerString = \" \";\n //if (m_columnHeader[col].toString().length() > 0)\n {\n aString = new AttributedString(headerString);\n aString.addAttribute(TextAttribute.FONT, getFont(HEADER_ROW, col));\n aString.addAttribute(TextAttribute.FOREGROUND, getColor(HEADER_ROW, col));\n //\n boolean fastDraw = LayoutEngine.s_FASTDRAW;\n if (fastDraw && !isView && !Util.is8Bit(headerString))\n fastDraw = false;\n iter = aString.getIterator();\n measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext());\n while (//\tprint header\n measurer.getPosition() < iter.getEndIndex()) {\n TextLayout layout = measurer.nextLayout(netWidth + 2);\n if (iter.getEndIndex() != measurer.getPosition())\n fastDraw = false;\n if (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_Block)) {\n layout = layout.getJustifiedLayout(netWidth + 2);\n fastDraw = false;\n }\n curY += layout.getAscent();\n float penX = curX;\n if (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_Center))\n penX += (netWidth - layout.getAdvance()) / 2;\n else if ((alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight) && layout.isLeftToRight()) || (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_LeadingLeft) && !layout.isLeftToRight()))\n penX += netWidth - layout.getAdvance();\n //\n if (fastDraw) {\n //\tBug - set Font/Color explicitly\n g2D.setFont(getFont(HEADER_ROW, col));\n g2D.setColor(getColor(HEADER_ROW, col));\n g2D.drawString(iter, penX, curY);\n } else\n //\t-> text\n layout.draw(g2D, penX, curY);\n curY += layout.getDescent() + layout.getLeading();\n usedHeight += layout.getAscent() + layout.getDescent();\n if (//\tone line only\n !m_multiLineHeader)\n break;\n }\n }\n curX += netWidth + H_GAP;\n curY = tempCurY + (int) (rowHeight - (4 * m_tFormat.getLineStroke().floatValue()));\n //\tY end line\n g2D.setPaint(m_tFormat.getVLine_Color());\n g2D.setStroke(m_tFormat.getVLine_Stroke());\n if (//\t -> | (right)\n m_tFormat.isPaintVLines())\n g2D.drawLine(curX, (int) (origY + m_tFormat.getLineStroke().floatValue()), curX, (int) (origY + rowHeight - (4 * m_tFormat.getLineStroke().floatValue())));\n curX += m_tFormat.getVLineStroke().floatValue();\n //\tX end line\n if (m_tFormat.isPaintHeaderLines()) {\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(m_tFormat.getHeader_Stroke());\n //\t -> - (button)\n g2D.//\t -> - (button)\n drawLine(//\t -> - (button)\n origX, //\t -> - (button)\n curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n }\n //\tthick\n curY += (2 * m_tFormat.getLineStroke().floatValue());\n //\tpaint Data\t\t***************************************************\n for (int row = firstRow; row < nextPageRow; row++) {\n //\tincludes 2*Gaps+Line\n rowHeight = m_rowHeights.get(row);\n netHeight = rowHeight - (2 * V_GAP) - m_tFormat.getLineStroke().floatValue();\n int rowYstart = curY;\n curX = origX;\n if (//\tdraw left | line\n leftVline) {\n g2D.setPaint(m_tFormat.getVLine_Color());\n g2D.setStroke(m_tFormat.getVLine_Stroke());\n if (m_tFormat.isPaintBoundaryLines())\n //\t -> | (left)\n g2D.//\t -> | (left)\n drawLine(//\t -> | (left)\n curX, //\t -> | (left)\n rowYstart, curX, (int) (rowYstart + rowHeight - m_tFormat.getLineStroke().floatValue()));\n curX += m_tFormat.getVLineStroke().floatValue();\n }\n //\tBackground\n bg = getBackground(row, col);\n if (!bg.equals(Color.white)) {\n g2D.setPaint(bg);\n g2D.fillRect(curX, curY, (int) (colWidth - m_tFormat.getVLineStroke().floatValue()), (int) (rowHeight - m_tFormat.getLineStroke().floatValue()));\n }\n // Over Line\n MReportLine rLine = getReportLine(row, col);\n if (rLine != null) {\n if (rLine.getOverline() > 1) {\n curY -= V_GAP + m_tFormat.getVLineStroke().floatValue();\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(rLine.getOverlineStroke(m_tFormat.getVLineStroke()));\n g2D.drawLine(curX, (int) (curY + m_tFormat.getVLineStroke().floatValue()), (int) (curX + colWidth - m_tFormat.getVLineStroke().floatValue()), (int) (curY + m_tFormat.getVLineStroke().floatValue()));\n curY += V_GAP + m_tFormat.getVLineStroke().floatValue();\n }\n if (rLine.getOverline() > 0) {\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(rLine.getOverlineStroke(m_tFormat.getVLineStroke()));\n g2D.drawLine(curX, curY, (int) (curX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n curY += m_tFormat.getVLineStroke().floatValue();\n }\n }\n //\tupper left gap\n curX += H_GAP;\n curY += V_GAP;\n //\tactual data\n Object[] printItems = getPrintItems(row, col);\n float penY = curY;\n // suppress repeated values\n boolean suppress = false;\n if (m_colSuppressRepeats[col] && row > 0 && row != firstRow) {\n Object[] lastItems = {};\n lastItems = getPrintItems(row - 1, col);\n if (Arrays.equals(lastItems, printItems))\n suppress = true;\n }\n if (!suppress) {\n if (m_tablePrintData != null && m_pageLogics != null && col < m_pageLogics.size()) {\n String pageLogic = m_pageLogics.get(col);\n if (!Util.isEmpty(pageLogic, true)) {\n m_tablePrintData.setRowIndex(row);\n PrintDataEvaluatee evaluatee = new PrintDataEvaluatee(getCurrentPage(), m_tablePrintData);\n boolean display = Evaluator.evaluateLogic(evaluatee, pageLogic);\n if (!display)\n suppress = true;\n }\n }\n }\n if (!suppress) {\n for (int index = 0; index < printItems.length; index++) {\n if (printItems[index] == null)\n ;\n else if (printItems[index] instanceof ImageElement) {\n Image imageToDraw = ((ImageElement) printItems[index]).getImage();\n if (// teo_sarca [ 1674706 ]\n imageToDraw != null) {\n // Draw image using the scale factor - teo_sarca, [ 1673548 ] Image is not scaled in a report table cell\n double scale = ((ImageElement) printItems[index]).getScaleFactor();\n if (scale != 1.0) {\n AffineTransform transform = new AffineTransform();\n transform.translate(curX, penY);\n transform.scale(scale, scale);\n g2D.drawImage(imageToDraw, transform, this);\n } else {\n g2D.drawImage(imageToDraw, curX, (int) penY, this);\n }\n }\n } else if (printItems[index] instanceof BarcodeElement) {\n BarcodeElement barcodeElement = (BarcodeElement) printItems[index];\n barcodeElement.paint(g2D, curX, (int) penY);\n } else if (printItems[index] instanceof Boolean) {\n //\tcenter\n int penX = curX + (int) ((netWidth - LayoutEngine.IMAGE_SIZE.width) / 2);\n if (((Boolean) printItems[index]).booleanValue())\n g2D.drawImage(LayoutEngine.IMAGE_TRUE, penX, (int) penY, this);\n else\n g2D.drawImage(LayoutEngine.IMAGE_FALSE, penX, (int) penY, this);\n penY += LayoutEngine.IMAGE_SIZE.height;\n } else if (printItems[index] instanceof HTMLRenderer) {\n HTMLRenderer renderer = (HTMLRenderer) printItems[index];\n Rectangle allocation = new Rectangle((int) colWidth, (int) netHeight);\n //\tlog.finest( \"printColumn HTML - \" + allocation);\n g2D.translate(curX, penY);\n renderer.paint(g2D, allocation);\n g2D.translate(-curX, -penY);\n penY += allocation.getHeight();\n } else {\n String str = printItems[index].toString();\n if (DEBUG_PRINT)\n if (log.isLoggable(Level.FINE))\n log.fine(\"row=\" + row + \",col=\" + col + \" - \" + str + \" 8Bit=\" + Util.is8Bit(str));\n if (str.length() > 0) {\n usedHeight = 0;\n String[] lines = Pattern.compile(\"\\n\", Pattern.MULTILINE).split(str);\n for (int lineNo = 0; lineNo < lines.length; lineNo++) {\n String thisLine = lines[lineNo];\n if (thisLine.length() == 0)\n thisLine = \" \";\n aString = new AttributedString(thisLine);\n aString.addAttribute(TextAttribute.FONT, getFont(row, col));\n if (//\tID\n isView && printItems[index] instanceof NamePair) {\n aString.addAttribute(TextAttribute.FOREGROUND, LINK_COLOR);\n aString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL, 0, str.length());\n } else\n aString.addAttribute(TextAttribute.FOREGROUND, getColor(row, col));\n //\n iter = aString.getIterator();\n boolean fastDraw = LayoutEngine.s_FASTDRAW;\n if (fastDraw && !isView && !Util.is8Bit(thisLine))\n fastDraw = false;\n measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext());\n while (//\tprint element\n measurer.getPosition() < iter.getEndIndex()) {\n TextLayout layout = measurer.nextLayout(netWidth + 2);\n if (iter.getEndIndex() != measurer.getPosition())\n fastDraw = false;\n float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();\n if ((m_columnMaxHeight[col] <= 0 || (usedHeight + lineHeight) <= m_columnMaxHeight[col]) && (usedHeight + lineHeight) <= netHeight) {\n if (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_Block) && measurer.getPosition() < iter.getEndIndex()) {\n layout = layout.getJustifiedLayout(netWidth + 2);\n fastDraw = false;\n }\n penY += layout.getAscent();\n float penX = curX;\n if (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_Center))\n penX += (netWidth - layout.getAdvance()) / 2;\n else if ((alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight) && layout.isLeftToRight()) || (alignment.equals(MPrintFormatItem.FIELDALIGNMENTTYPE_LeadingLeft) && !layout.isLeftToRight()))\n penX += netWidth - layout.getAdvance();\n //\n if (fastDraw) {\n //\tBug - set Font/Color explicitly\n g2D.setFont(getFont(row, col));\n if (//\tID\n isView && printItems[index] instanceof NamePair) {\n g2D.setColor(LINK_COLOR);\n //\tTextAttribute.UNDERLINE\n } else\n g2D.setColor(getColor(row, col));\n g2D.drawString(iter, penX, penY);\n } else\n //\t-> text\n layout.draw(g2D, penX, penY);\n if (DEBUG_PRINT)\n if (log.isLoggable(Level.FINE))\n log.fine(\"row=\" + row + \",col=\" + col + \" - \" + str + \" - x=\" + penX + \",y=\" + penY);\n penY += layout.getDescent() + layout.getLeading();\n usedHeight += lineHeight;\n //\n if (//\tFirstLineOny\n m_columnMaxHeight[col] == -1)\n break;\n }\n }\n //\tprint element\n }\n //\tfor all lines\n }\n //\tlength > 0\n }\n //\tnon boolean\n }\n //\tfor all print items\n }\n // not suppressed\n curY += netHeight + V_GAP;\n curX += netWidth + H_GAP;\n //\tY end line\n g2D.setPaint(m_tFormat.getVLine_Color());\n g2D.setStroke(m_tFormat.getVLine_Stroke());\n if (m_tFormat.isPaintVLines())\n //\t -> | (right)\n g2D.//\t -> | (right)\n drawLine(//\t -> | (right)\n curX, //\t -> | (right)\n rowYstart, curX, (int) (rowYstart + rowHeight - m_tFormat.getLineStroke().floatValue()));\n curX += m_tFormat.getVLineStroke().floatValue();\n // Under Line\n if (rLine != null && rLine.getUnderline() > 0) {\n if (rLine.getUnderline() > 1) {\n curY -= V_GAP + m_tFormat.getVLineStroke().floatValue();\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(rLine.getUnderlineStroke(m_tFormat.getVLineStroke()));\n g2D.drawLine(origX, curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n curY += V_GAP + m_tFormat.getVLineStroke().floatValue();\n }\n if (rLine.getUnderline() > 0) {\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(rLine.getUnderlineStroke(m_tFormat.getVLineStroke()));\n g2D.drawLine(origX, curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n }\n }\n // Maintain financial report detail and column section Y position\n if ((int) (rowYstart + rowHeight) > curY) {\n curY = (int) (rowYstart + rowHeight);\n }\n // X end line\n if (// last Line\n row == m_data.getRowCount() - 1) {\n // left some space between underline and last line\n curY += 2 * V_GAP;\n /**\n * Bug fix - Bottom line was always displayed whether or not header lines was set to be visible\n * @author ashley\n */\n if (m_tFormat.isPaintHeaderLines()) {\n g2D.setPaint(m_tFormat.getHeaderLine_Color());\n g2D.setStroke(m_tFormat.getHeader_Stroke());\n // -> - (last line)\n g2D.// -> - (last line)\n drawLine(// -> - (last line)\n origX, // -> - (last line)\n curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n // thick\n curY += (2 * m_tFormat.getLineStroke().floatValue());\n } else {\n curY += m_tFormat.getLineStroke().floatValue();\n }\n } else {\n // next line is a function column -> underline this\n boolean nextIsFunction = m_functionRows.contains(Integer.valueOf(row + 1));\n if (nextIsFunction && m_functionRows.contains(Integer.valueOf(row)))\n // this is a function line too\n nextIsFunction = false;\n MReportLine nextLine = getReportLine(row + 1, col);\n if (nextIsFunction || (m_finReportSumRows.contains(Integer.valueOf(row + 1)) && nextLine != null && nextLine.getOverline() == 0)) {\n g2D.setPaint(m_tFormat.getFunctFG_Color());\n g2D.setStroke(m_tFormat.getHLine_Stroke());\n // -> - (bottom)\n g2D.// -> - (bottom)\n drawLine(// -> - (bottom)\n origX, // -> - (bottom)\n curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n } else if (m_tFormat.isPaintHLines()) {\n g2D.setPaint(m_tFormat.getHLine_Color());\n g2D.setStroke(m_tFormat.getHLine_Stroke());\n // -> - (bottom)\n g2D.// -> - (bottom)\n drawLine(// -> - (bottom)\n origX, // -> - (bottom)\n curY, (int) (origX + colWidth - m_tFormat.getVLineStroke().floatValue()), curY);\n }\n curY += m_tFormat.getLineStroke().floatValue();\n }\n }\n // for all rows\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public ApiObjectBase createTungstenFirewallRule(String uuid, String firewallPolicyUuid, String name, String action, String serviceGroupUuid, String srcTagUuid, String srcAddressGroupUuid, String srcNetworkUuid, String direction, String destTagUuid, String destAddressGroupUuid, String destNetworkUuid, String tagTypeUuid, int sequence) {\n try {\n String policyManagementUuid = apiConnector.findByName(PolicyManagement.class, new ConfigRoot(), TUNGSTEN_DEFAULT_POLICY_MANAGEMENT);\n PolicyManagement policyManagement = (PolicyManagement) apiConnector.findById(PolicyManagement.class, policyManagementUuid);\n if (policyManagement == null) {\n return null;\n }\n FirewallPolicy firewallPolicy = (FirewallPolicy) apiConnector.findById(FirewallPolicy.class, firewallPolicyUuid);\n if (firewallPolicy == null) {\n return null;\n }\n ServiceGroup serviceGroup = (ServiceGroup) apiConnector.findById(ServiceGroup.class, serviceGroupUuid);\n AddressGroup srcAddressGroup = (AddressGroup) apiConnector.findById(AddressGroup.class, srcAddressGroupUuid);\n AddressGroup destAddressGroup = (AddressGroup) apiConnector.findById(AddressGroup.class, destAddressGroupUuid);\n VirtualNetwork srcNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, srcNetworkUuid);\n VirtualNetwork destNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, destNetworkUuid);\n Tag srcTag = (Tag) apiConnector.findById(Tag.class, srcTagUuid);\n Tag destTag = (Tag) apiConnector.findById(Tag.class, destTagUuid);\n TagType tagType = (TagType) apiConnector.findById(TagType.class, tagTypeUuid);\n if (serviceGroup == null) {\n return null;\n }\n if (srcAddressGroup == null && srcTag == null && srcNetwork == null) {\n return null;\n }\n if (destAddressGroup == null && destTag == null && destNetwork == null) {\n return null;\n }\n FirewallRule firewallRule = new FirewallRule();\n firewallRule.setUuid(uuid);\n firewallRule.setName(name);\n firewallRule.setParent(policyManagement);\n firewallRule.setActionList(new ActionListType(action));\n firewallRule.setServiceGroup(serviceGroup);\n FirewallRuleEndpointType srcFirewallRuleEndpointType = new FirewallRuleEndpointType();\n if (srcTag != null) {\n srcFirewallRuleEndpointType.addTags(\"global:\" + srcTag.getName());\n srcFirewallRuleEndpointType.addTagIds(Integer.decode(srcTag.getId()));\n }\n if (srcAddressGroup != null) {\n String srcAddressGroupName = StringUtils.join(srcAddressGroup.getQualifiedName(), \":\");\n srcFirewallRuleEndpointType.setAddressGroup(srcAddressGroupName);\n }\n if (srcNetwork != null) {\n srcFirewallRuleEndpointType.setVirtualNetwork(StringUtils.join(srcNetwork.getQualifiedName(), \":\"));\n }\n FirewallRuleEndpointType destFirewallRuleEndpointType = new FirewallRuleEndpointType();\n if (destTag != null) {\n destFirewallRuleEndpointType.addTags(\"global:\" + destTag.getName());\n destFirewallRuleEndpointType.addTagIds(Integer.decode(destTag.getId()));\n }\n if (destAddressGroup != null) {\n String destAddressGroupName = StringUtils.join(destAddressGroup.getQualifiedName(), \":\");\n destFirewallRuleEndpointType.setAddressGroup(destAddressGroupName);\n }\n if (destNetwork != null) {\n destFirewallRuleEndpointType.setVirtualNetwork(StringUtils.join(destNetwork.getQualifiedName(), \":\"));\n }\n firewallRule.setEndpoint1(srcFirewallRuleEndpointType);\n firewallRule.setDirection(direction);\n firewallRule.setEndpoint2(destFirewallRuleEndpointType);\n FirewallRuleMatchTagsType firewallRuleMatchTagsType = new FirewallRuleMatchTagsType();\n if (tagType != null) {\n firewallRuleMatchTagsType.addTag(tagType.getName());\n firewallRule.setMatchTags(firewallRuleMatchTagsType);\n }\n return createFirewallRule(firewallPolicy, firewallRule, sequence);\n } catch (IOException e) {\n return null;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private Snapshot takeSnapshotInternal(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm, Snapshot.LocationType locationType, boolean asyncBackup, List zoneIds) throws ResourceAllocationException {\n Account caller = CallContext.current().getCallingAccount();\n VolumeInfo volume = volFactory.getVolume(volumeId);\n if (volume == null) {\n throw new InvalidParameterValueException(\"Creating snapshot failed due to volume:\" + volumeId + \" doesn't exist\");\n }\n if (policyId != null && policyId > 0) {\n if (CollectionUtils.isNotEmpty(zoneIds)) {\n throw new InvalidParameterValueException(String.format(\"%s can not be specified for snapshots linked with snapshot policy\", ApiConstants.ZONE_ID_LIST));\n }\n List details = snapshotPolicyDetailsDao.findDetails(policyId, ApiConstants.ZONE_ID);\n zoneIds = details.stream().map(d -> Long.valueOf(d.getValue())).collect(Collectors.toList());\n }\n if (CollectionUtils.isNotEmpty(zoneIds)) {\n for (Long destZoneId : zoneIds) {\n DataCenterVO dstZone = _dcDao.findById(destZoneId);\n if (dstZone == null) {\n throw new InvalidParameterValueException(\"Please specify a valid destination zone.\");\n }\n }\n }\n _accountMgr.checkAccess(caller, null, true, volume);\n if (volume.getState() != Volume.State.Ready) {\n throw new InvalidParameterValueException(\"VolumeId: \" + volumeId + \" is not in \" + Volume.State.Ready + \" state but \" + volume.getState() + \". Cannot take snapshot.\");\n }\n StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId());\n if (storagePoolVO.isManaged() && locationType == null) {\n locationType = Snapshot.LocationType.PRIMARY;\n }\n VMInstanceVO vm = null;\n if (volume.getInstanceId() != null) {\n vm = _vmInstanceDao.findById(volume.getInstanceId());\n }\n if (vm != null) {\n _accountMgr.checkAccess(caller, null, true, vm);\n // serialize VM operation\n AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();\n if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {\n // avoid re-entrance\n VmWorkJobVO placeHolder = null;\n placeHolder = createPlaceHolderWork(vm.getId());\n try {\n return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm, locationType, asyncBackup, zoneIds);\n } finally {\n _workJobDao.expunge(placeHolder.getId());\n }\n } else {\n Outcome outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm, locationType, asyncBackup, zoneIds);\n try {\n outcome.get();\n } catch (InterruptedException e) {\n throw new RuntimeException(\"Operation is interrupted\", e);\n } catch (ExecutionException e) {\n throw new RuntimeException(\"Execution excetion\", e);\n }\n Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());\n if (jobResult != null) {\n if (jobResult instanceof ConcurrentOperationException) {\n throw (ConcurrentOperationException) jobResult;\n } else if (jobResult instanceof ResourceAllocationException) {\n throw (ResourceAllocationException) jobResult;\n } else if (jobResult instanceof Throwable) {\n throw new RuntimeException(\"Unexpected exception\", (Throwable) jobResult);\n }\n }\n return _snapshotDao.findById(snapshotId);\n }\n } else {\n CreateSnapshotPayload payload = new CreateSnapshotPayload();\n payload.setSnapshotId(snapshotId);\n payload.setSnapshotPolicyId(policyId);\n payload.setAccount(account);\n payload.setQuiescevm(quiescevm);\n payload.setAsyncBackup(asyncBackup);\n if (CollectionUtils.isNotEmpty(zoneIds)) {\n payload.setZoneIds(zoneIds);\n }\n volume.addPayload(payload);\n return volService.takeSnapshot(volume);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static LoanSchedulePeriodData periodWithPayments(@SuppressWarnings(\"unused\") final Long loanId, final Integer periodNumber, final LocalDate fromDate, final LocalDate dueDate, final LocalDate obligationsMetOnDate, final boolean complete, final BigDecimal principalOriginalDue, final BigDecimal principalPaid, final BigDecimal principalWrittenOff, final BigDecimal principalOutstanding, final BigDecimal outstandingPrincipalBalanceOfLoan, final BigDecimal interestDueOnPrincipalOutstanding, final BigDecimal interestPaid, final BigDecimal interestWaived, final BigDecimal interestWrittenOff, final BigDecimal interestOutstanding, final BigDecimal feeChargesDue, final BigDecimal feeChargesPaid, final BigDecimal feeChargesWaived, final BigDecimal feeChargesWrittenOff, final BigDecimal feeChargesOutstanding, final BigDecimal penaltyChargesDue, final BigDecimal penaltyChargesPaid, final BigDecimal penaltyChargesWaived, final BigDecimal penaltyChargesWrittenOff, final BigDecimal penaltyChargesOutstanding, final BigDecimal totalDueForPeriod, final BigDecimal totalPaid, final BigDecimal totalPaidInAdvanceForPeriod, final BigDecimal totalPaidLateForPeriod, final BigDecimal totalWaived, final BigDecimal totalWrittenOff, final BigDecimal totalOutstanding, final BigDecimal totalActualCostOfLoanForPeriod, final BigDecimal totalInstallmentAmountForPeriod, final BigDecimal totalCredits, final boolean isDownPayment, final BigDecimal totalAccruedInterest) {\n return new LoanSchedulePeriodData(periodNumber, fromDate, dueDate, obligationsMetOnDate, complete, principalOriginalDue, principalPaid, principalWrittenOff, principalOutstanding, outstandingPrincipalBalanceOfLoan, interestDueOnPrincipalOutstanding, interestPaid, interestWaived, interestWrittenOff, interestOutstanding, feeChargesDue, feeChargesPaid, feeChargesWaived, feeChargesWrittenOff, feeChargesOutstanding, penaltyChargesDue, penaltyChargesPaid, penaltyChargesWaived, penaltyChargesWrittenOff, penaltyChargesOutstanding, totalDueForPeriod, totalPaid, totalPaidInAdvanceForPeriod, totalPaidLateForPeriod, totalWaived, totalWrittenOff, totalOutstanding, totalActualCostOfLoanForPeriod, totalInstallmentAmountForPeriod, totalCredits, isDownPayment, totalAccruedInterest);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static CompilationPhase of(PackageRegistry pkgRegistry, PackageDescr packageDescr, InternalKnowledgeBase kBase, int parallelRulesBuildThreshold, AssetFilter assetFilter, Map packageAttributes, Resource resource, TypeDeclarationContext typeDeclarationContext){\r\n if (kBase == null) {\r\n return new ImmutableRuleCompilationPhase(pkgRegistry, packageDescr, parallelRulesBuildThreshold, packageAttributes, resource, typeDeclarationContext);\r\n } else {\r\n return new RuleCompilationPhase(pkgRegistry, packageDescr, kBase, parallelRulesBuildThreshold, assetFilter, packageAttributes, resource, typeDeclarationContext);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static native void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter);", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "/**\n * A helper api for creating an audit log for a failure event.\n */\nstatic String createFailureLog(String user, String operation, String perm, String target, String description, ApplicationId appId, ApplicationAttemptId attemptId, ContainerId containerId, Resource resource, CallerContext callerContext, String queueName, String partition) {\n StringBuilder b = createStringBuilderForFailureLog(user, operation, target, description, perm);\n if (appId != null) {\n add(Keys.APPID, appId.toString(), b);\n }\n if (attemptId != null) {\n add(Keys.APPATTEMPTID, attemptId.toString(), b);\n }\n if (containerId != null) {\n add(Keys.CONTAINERID, containerId.toString(), b);\n }\n if (resource != null) {\n add(Keys.RESOURCE, resource.toString(), b);\n }\n appendCallerContext(b, callerContext);\n if (queueName != null) {\n add(Keys.QUEUENAME, queueName, b);\n }\n if (partition != null) {\n add(Keys.NODELABEL, partition, b);\n }\n return b.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static StandingInstructionData instance(final Long id, final Long accountDetailId, final String name, final OfficeData fromOffice, final OfficeData toOffice, final ClientData fromClient, final ClientData toClient, final EnumOptionData fromAccountType, final PortfolioAccountData fromAccount, final EnumOptionData toAccountType, final PortfolioAccountData toAccount, final EnumOptionData transferType, final EnumOptionData priority, final EnumOptionData instructionType, final EnumOptionData status, final BigDecimal amount, final LocalDate validFrom, final LocalDate validTill, final EnumOptionData recurrenceType, final EnumOptionData recurrenceFrequency, final Integer recurrenceInterval, final MonthDay recurrenceOnMonthDay) {\n final Page transactions = null;\n final Collection fromOfficeOptions = null;\n final Collection fromClientOptions = null;\n final Collection fromAccountTypeOptions = null;\n final Collection fromAccountOptions = null;\n final Collection toOfficeOptions = null;\n final Collection toClientOptions = null;\n final Collection toAccountTypeOptions = null;\n final Collection toAccountOptions = null;\n final Collection transferTypeOptions = null;\n final Collection statusOptions = null;\n final Collection instructionTypeOptions = null;\n final Collection priorityOptions = null;\n final Collection recurrenceTypeOptions = null;\n final Collection recurrenceFrequencyOptions = null;\n return new StandingInstructionData(id, accountDetailId, name, fromOffice, fromClient, fromAccountType, fromAccount, toOffice, toClient, toAccountType, toAccount, transferType, priority, instructionType, status, amount, validFrom, validTill, recurrenceType, recurrenceFrequency, recurrenceInterval, recurrenceOnMonthDay, transactions, fromOfficeOptions, fromClientOptions, fromAccountTypeOptions, fromAccountOptions, toOfficeOptions, toClientOptions, toAccountTypeOptions, toAccountOptions, transferTypeOptions, statusOptions, instructionTypeOptions, priorityOptions, recurrenceTypeOptions, recurrenceFrequencyOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Instantiates a MetaColumn.\n */\nMetaColumn createColumn(Table table, String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, @Nullable Integer decimalDigits, int numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable);", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "//************************************************************************************************\n// Emulate BigInteger serialization used by LazyBinary, Avro, Parquet, and possibly others.\npublic static int fastBigIntegerBytes(final int fastSignum, long fast0, long fast1, long fast2, int fastIntegerDigitCount, int fastScale, int fastSerializeScale, long[] scratchLongs, byte[] buffer) {\n if (fastSerializeScale != -1) {\n return fastBigIntegerBytesScaled(fastSignum, fast0, fast1, fast2, fastIntegerDigitCount, fastScale, fastSerializeScale, scratchLongs, buffer);\n } else {\n return fastBigIntegerBytesUnscaled(fastSignum, fast0, fast1, fast2, scratchLongs, buffer);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static ExprViewItem expr(String exprId, Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Predicate8 predicate){\r\n return new Expr8ViewItemImpl<>(exprId, var1, var2, var3, var4, var5, var6, var7, var8, new Predicate8.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void reaccumulateForLeftTuple(final AccumulateNode accNode, final Accumulate accumulate, final LeftTuple leftParent, final RightTuple unused1, final LeftTuple unused2, final ReteEvaluator reteEvaluator, final AccumulateMemory am, final BaseAccumulation accctx, final boolean reaccumulate){\r\n if (reaccumulate) {\r\n reinit(accumulate, leftParent, reteEvaluator, am, accctx);\r\n for (LeftTuple childMatch = leftParent.getFirstChild(); childMatch != null; childMatch = childMatch.getHandleNext()) {\r\n RightTuple rightTuple = childMatch.getRightParent();\r\n FactHandle childHandle = rightTuple.getFactHandle();\r\n LeftTuple tuple = leftParent;\r\n if (accNode.isRightInputIsRiaNode()) {\r\n tuple = (LeftTuple) rightTuple;\r\n childHandle = rightTuple.getFactHandleForEvaluation();\r\n }\r\n Object value = accumulate.accumulate(am.workingMemoryContext, accctx, tuple, childHandle, reteEvaluator);\r\n postAccumulate(accNode, accctx, childMatch);\r\n childMatch.setContextObject(value);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SqlWindow create(@Nullable SqlIdentifier declName, @Nullable SqlIdentifier refName, SqlNodeList partitionList, SqlNodeList orderList, SqlLiteral isRows, @Nullable SqlNode lowerBound, @Nullable SqlNode upperBound, @Nullable SqlLiteral allowPartial, SqlParserPos pos){\r\n if (upperBound == null && lowerBound != null && lowerBound.getKind() == SqlKind.FOLLOWING) {\r\n upperBound = lowerBound;\r\n lowerBound = null;\r\n }\r\n return new SqlWindow(pos, declName, refName, partitionList, orderList, isRows, lowerBound, upperBound, allowPartial);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param keys Keys.\n * @param forcePrimary Force primary.\n * @param skipTx Skip tx.\n * @param taskName Task name.\n * @param deserializeBinary Deserialize binary.\n * @param recovery Recovery mode flag.\n * @param skipVals Skip values.\n * @param needVer Need version.\n * @return Future for the get operation.\n * @see GridCacheAdapter#getAllAsync(Collection)\n */\npublic IgniteInternalFuture> repairableGetAllAsync(@Nullable Collection keys, boolean forcePrimary, boolean skipTx, String taskName, boolean deserializeBinary, boolean recovery, ReadRepairStrategy readRepairStrategy, boolean skipVals, final boolean needVer) {\n IgniteInternalFuture> fut = getAllAsync(keys, forcePrimary, skipTx, taskName, deserializeBinary, recovery, readRepairStrategy, skipVals, needVer);\n if (readRepairStrategy != null) {\n CacheOperationContext opCtx = ctx.operationContextPerCall();\n return getWithRepairAsync(fut, (e) -> repairAsync(e, opCtx, skipVals), () -> repairableGetAllAsync(keys, forcePrimary, skipTx, taskName, deserializeBinary, recovery, readRepairStrategy, skipVals, needVer));\n }\n return fut;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "protected HttpProcessor initProtocolProcessor(String as2Version, String originServer, String serverFqdn, AS2SignatureAlgorithm signatureAlgorithm, Certificate[] signingCertificateChain, PrivateKey signingPrivateKey, PrivateKey decryptingPrivateKey, String mdnMessageTemplate, Certificate[] validateSigningCertificateChain) {\n return HttpProcessorBuilder.create().add(new ResponseContent(true)).add(new ResponseServer(originServer)).add(new ResponseDate()).add(new ResponseConnControl()).add(new ResponseMDN(as2Version, serverFqdn, signatureAlgorithm, signingCertificateChain, signingPrivateKey, decryptingPrivateKey, mdnMessageTemplate, validateSigningCertificateChain)).build();\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5){\r\n Map m = new HashMap<>();\r\n m.put(k1, v1);\r\n m.put(k2, v2);\r\n m.put(k3, v3);\r\n m.put(k4, v4);\r\n m.put(k5, v5);\r\n return m;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "// public void getETag() {\n// // Create a set of Dav Properties to query\n//\t\tDavPropertyNameSet properties = new DavPropertyNameSet();\n//\t\tproperties.add(DavPropertyName.GETETAG);\n//\n//\t\t// Create a Component filter for VCALENDAR and VEVENT\n//\t\tCompFilter vcalendar = new CompFilter(Calendar.VCALENDAR);\n//\t\tvcalendar.addCompFilter(new CompFilter(Component.VEVENT));\n//\n//\t\t// Create a Query XML object with the above properties\n//\t\tCalendarQuery query = new CalendarQuery(properties, vcalendar, new CalendarData(), false, false);\n//\n//\t\t/*\n//\t\t\n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t \n//\t\t\n//\t\t*/\n//\t\t// Print to STDOUT the generated Query\n//\t\tSystem.out.println(XMLUtils.prettyPrint(query));\n//\n//\t\tHttpCalDAVReportMethod method = null;\n//\n//\t\ttry {\n//\t\t\tmethod = new HttpCalDAVReportMethod(\"path://to/caldav/calendar\", query, CalDAVConstants.DEPTH_1);\n// CloseableHttpClient client = HttpClients.createDefault();\n//\n//\t\t\t// Execute the method\n//\t\t\tHttpResponse httpResponse = client.execute(method);\n//\n//\t\t\t// If successful\n//\t\t\tif (method.succeeded(httpResponse)) {\n//\t\t\t\t// Retrieve all multistatus responses\n//\t\t\t\tMultiStatusResponse[] multiStatusResponses = method.getResponseBodyAsMultiStatus(httpResponse).getResponses();\n//\n//\t\t\t\t// Iterate through all responses\n//\t\t\t\tfor (MultiStatusResponse response : multiStatusResponses) {\n//\t\t\t\t\t// If the individual calendar request was succesful\n//\t\t\t\t\tif (response.getStatus()[0].getStatusCode() == SC_OK) {\n//\t\t\t\t\t\t// Retrieve ETag and Calendar from response\n//\t\t\t\t\t\tString etag = CalendarDataProperty.getEtagfromResponse(response);\n//\t\t\t\t\t\tCalendar ical = CalendarDataProperty.getCalendarfromResponse(response);\n//\n//\t\t\t\t\t\t// Print to output\n//\t\t\t\t\t\tSystem.out.println(\"Calendar at \" + response.getHref() + \" with ETag: \" + etag);\n//\t\t\t\t\t\tSystem.out.println(ical);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t} catch (Exception e) {\n//\t\t\t// No-op\n//\t\t} finally {\n//\t\t\tif (method != null) {\n//\t\t\t\tmethod.reset();\n//\t\t\t}\n//\t\t}\n// }\npublic String createEvent(String uid, String calendarHref, String summary, String description, String location, Date start, Date end, boolean allDayEvent) {\n return this.putEvent(uid, calendarHref, null, summary, description, location, start, end, allDayEvent);\n}", "smellKey": "S107", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * @param keys Keys.\n * @param readerArgs Near cache reader will be added if not null.\n * @param readThrough Read-through flag.\n * @param taskName Task name/\n * @param deserializeBinary Deserialize binary flag.\n * @param expiry Expiry policy.\n * @param skipVals Skip values flag.\n * @param keepCacheObjects Keep cache objects.\n * @param needVer If {@code true} returns values as tuples containing value and version.\n * @param txLbl Transaction label.\n * @return Future.\n */\nprivate IgniteInternalFuture> getAllAsync0(@Nullable final Collection keys, @Nullable final ReaderArguments readerArgs, final boolean readThrough, final String taskName, final boolean deserializeBinary, @Nullable final IgniteCacheExpiryPolicy expiry, final boolean skipVals, final boolean keepCacheObjects, final boolean recovery, final boolean needVer, @Nullable String txLbl) {\n if (F.isEmpty(keys))\n return new GridFinishedFuture<>(Collections.emptyMap());\n Map misses = null;\n Set newLocEntries = null;\n ctx.shared().database().checkpointReadLock();\n try {\n int keysSize = keys.size();\n GridDhtTopologyFuture topFut = ctx.shared().exchange().lastFinishedFuture();\n Throwable ex = topFut != null ? topFut.validateCache(ctx, recovery, /*read*/\n true, null, keys) : null;\n if (ex != null)\n return new GridFinishedFuture<>(ex);\n final Map map = keysSize == 1 ? (Map) new IgniteBiTuple<>() : U.newHashMap(keysSize);\n final boolean storeEnabled = !skipVals && readThrough && ctx.readThrough();\n boolean readNoEntry = ctx.readNoEntry(expiry, readerArgs != null);\n for (KeyCacheObject key : keys) {\n while (true) {\n try {\n EntryGetResult res = null;\n boolean evt = !skipVals;\n boolean updateMetrics = !skipVals;\n GridCacheEntryEx entry = null;\n boolean skipEntry = readNoEntry;\n if (readNoEntry) {\n CacheDataRow row = ctx.offheap().read(ctx, key);\n if (row != null) {\n long expireTime = row.expireTime();\n if (expireTime != 0) {\n if (expireTime > U.currentTimeMillis()) {\n res = new EntryGetWithTtlResult(row.value(), row.version(), false, expireTime, 0);\n } else\n skipEntry = false;\n } else\n res = new EntryGetResult(row.value(), row.version(), false);\n }\n if (res != null) {\n if (evt) {\n ctx.events().readEvent(key, null, txLbl, row.value(), taskName, !deserializeBinary);\n }\n if (updateMetrics && ctx.statisticsEnabled())\n ctx.cache().metrics0().onRead(true);\n } else if (storeEnabled)\n skipEntry = false;\n }\n if (!skipEntry) {\n boolean isNewLocEntry = this.map.getEntry(ctx, key) == null;\n entry = entryEx(key);\n if (entry == null) {\n if (!skipVals && ctx.statisticsEnabled())\n ctx.cache().metrics0().onRead(false);\n break;\n }\n if (isNewLocEntry) {\n if (newLocEntries == null)\n newLocEntries = new HashSet<>();\n newLocEntries.add(entry);\n }\n if (storeEnabled) {\n res = entry.innerGetAndReserveForLoad(updateMetrics, evt, taskName, expiry, !deserializeBinary, readerArgs);\n assert res != null;\n if (res.value() == null) {\n if (misses == null)\n misses = new HashMap<>();\n misses.put(key, res);\n res = null;\n }\n } else {\n res = entry.innerGetVersioned(null, null, updateMetrics, evt, null, taskName, expiry, !deserializeBinary, readerArgs);\n if (res == null)\n entry.touch();\n }\n }\n if (res != null) {\n ctx.addResult(map, key, res, skipVals, keepCacheObjects, deserializeBinary, true, needVer);\n if (entry != null)\n entry.touch();\n if (keysSize == 1)\n // Safe to return because no locks are required in READ_COMMITTED mode.\n return new GridFinishedFuture<>(map);\n }\n break;\n } catch (GridCacheEntryRemovedException ignored) {\n if (log.isDebugEnabled())\n log.debug(\"Got removed entry in getAllAsync(..) method (will retry): \" + key);\n }\n }\n }\n if (storeEnabled && misses != null) {\n final Map loadKeys = misses;\n final Collection loaded = new HashSet<>();\n return new GridEmbeddedFuture(ctx.closures().callLocalSafe(ctx.projectSafe(new GPC>() {\n\n @Override\n public Map call() throws Exception {\n ctx.store().loadAll(null, /*tx*/\n loadKeys.keySet(), new CI2() {\n\n @Override\n public void apply(KeyCacheObject key, Object val) {\n EntryGetResult res = loadKeys.get(key);\n if (res == null || val == null)\n return;\n loaded.add(key);\n CacheObject cacheVal = ctx.toCacheObject(val);\n while (true) {\n GridCacheEntryEx entry = null;\n try {\n ctx.shared().database().ensureFreeSpace(ctx.dataRegion());\n } catch (IgniteCheckedException e) {\n // Wrap errors (will be unwrapped).\n throw new GridClosureException(e);\n }\n ctx.shared().database().checkpointReadLock();\n try {\n entry = entryEx(key);\n entry.unswap();\n GridCacheVersion newVer = nextVersion();\n EntryGetResult verVal = entry.versionedValue(cacheVal, res.version(), newVer, expiry, readerArgs);\n if (log.isDebugEnabled())\n log.debug(\"Set value loaded from store into entry [\" + \"oldVer=\" + res.version() + \", newVer=\" + verVal.version() + \", \" + \"entry=\" + entry + ']');\n // Don't put key-value pair into result map if value is null.\n if (verVal.value() != null) {\n ctx.addResult(map, key, verVal, skipVals, keepCacheObjects, deserializeBinary, true, needVer);\n } else {\n ctx.addResult(map, key, new EntryGetResult(cacheVal, res.version()), skipVals, keepCacheObjects, deserializeBinary, false, needVer);\n }\n entry.touch();\n break;\n } catch (GridCacheEntryRemovedException ignore) {\n if (log.isDebugEnabled())\n log.debug(\"Got removed entry during getAllAsync (will retry): \" + entry);\n } catch (IgniteCheckedException e) {\n // Wrap errors (will be unwrapped).\n throw new GridClosureException(e);\n } finally {\n ctx.shared().database().checkpointReadUnlock();\n }\n }\n }\n });\n clearReservationsIfNeeded(loadKeys, loaded);\n return map;\n }\n }), true), new C2, Exception, IgniteInternalFuture>>() {\n\n @Override\n public IgniteInternalFuture> apply(Map map, Exception e) {\n if (e != null) {\n clearReservationsIfNeeded(loadKeys, loaded);\n return new GridFinishedFuture<>(e);\n }\n Collection notFound = new HashSet<>(loadKeys.keySet());\n notFound.removeAll(loaded);\n // Touch entries that were not found in store.\n for (KeyCacheObject key : notFound) {\n GridCacheEntryEx entry = peekEx(key);\n if (entry != null)\n entry.touch();\n }\n // There were no misses.\n return new GridFinishedFuture<>(Collections.emptyMap());\n }\n }, new C2, Exception, Map>() {\n\n @Override\n public Map apply(Map loaded, Exception e) {\n if (e == null)\n map.putAll(loaded);\n return map;\n }\n });\n } else\n // Misses can be non-zero only if store is enabled.\n assert misses == null;\n return new GridFinishedFuture<>(map);\n } catch (RuntimeException | AssertionError e) {\n if (misses != null) {\n for (KeyCacheObject key0 : misses.keySet()) {\n GridCacheEntryEx entry = peekEx(key0);\n if (entry != null)\n entry.touch();\n }\n }\n if (newLocEntries != null) {\n for (GridCacheEntryEx entry : newLocEntries) removeEntry(entry);\n }\n return new GridFinishedFuture<>(e);\n } catch (IgniteCheckedException e) {\n return new GridFinishedFuture<>(e);\n } finally {\n ctx.shared().database().checkpointReadUnlock();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private void invoke(boolean isRemove, OperationService operationService, Address address, String name, Data key, Data value, long ttl, VersionResponsePair response){\r\n Operation op = new ReplicateUpdateOperation(name, key, value, ttl, response, isRemove, getCallerAddress()).setPartitionId(getPartitionId()).setValidateTarget(false);\r\n operationService.createInvocationBuilder(getServiceName(), op, address).setTryCount(INVOCATION_TRY_COUNT).invoke();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param username TODO\n * @param password TODO\n * @param useSSL TODO\n */\nprivate void setUp(String server, int port, String username, String password, boolean useSSL, boolean useTLS, boolean ignoreSslCertificateErrors, String from, String fromDescr, String to, String subject, String message) throws EmailException {\n email.setHostName(server);\n email.setSmtpPort(port);\n email.setFrom(from, fromDescr);\n if (!\"\".equals(username)) {\n email.setAuthentication(username, password);\n }\n if (useTLS) {\n email.setStartTLSEnabled(true);\n email.setStartTLSRequired(true);\n email.setSSLCheckServerIdentity(true);\n }\n if (useSSL) {\n email.setSSLOnConnect(true);\n email.setSslSmtpPort(port + \"\");\n email.setSSLCheckServerIdentity(true);\n }\n email.addTo(to);\n email.setSubject(subject);\n if ((message == null) || (message.length() == 0)) {\n throw new EmailException(\"Invalid message supplied\");\n }\n email.setContent(message, \"text/plain; charset=UTF-8\");\n if (ignoreSslCertificateErrors) {\n email.getMailSession().getProperties().setProperty(\"mail.smtp.ssl.trust\", \"*\");\n }\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "private void doUpgrade(String name, final StorageDirectory bpSd, NamespaceInfo nsInfo, final File bpPrevDir, final File bpTmpDir, final File bpCurDir, final int oldLV, Configuration conf) throws IOException {\n // 3. Create new /current with block files hardlinks and VERSION\n linkAllBlocks(bpTmpDir, bpCurDir, oldLV, conf);\n this.layoutVersion = DataNodeLayoutVersion.getCurrentLayoutVersion();\n assert this.namespaceID == nsInfo.getNamespaceID() : \"Data-node and name-node layout versions must be the same.\";\n this.cTime = nsInfo.getCTime();\n writeProperties(bpSd);\n // 4.rename /current//previous.tmp to\n // /current//previous\n rename(bpTmpDir, bpPrevDir);\n LOG.info(\"Upgrade of {} is complete\", name);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * @param map Map.\n * @param key Key.\n * @param val Value.\n * @param skipVals Skip values.\n * @param keepCacheObjects Keep CacheObject.\n * @param deserializeBinary Deserialize binary.\n * @param cpy Copy flag.\n * @param getRes EntryGetResult.\n * @param ver Version.\n * @param expireTime Entry expire time.\n * @param ttl Entry TTL.\n * @param needVer Need version flag.\n * @param ldr Class loader, used for deserialization from binary representation.\n */\npublic void addResult(Map map, KeyCacheObject key, CacheObject val, boolean skipVals, boolean keepCacheObjects, boolean deserializeBinary, boolean cpy, @Nullable EntryGetResult getRes, final GridCacheVersion ver, final long expireTime, final long ttl, boolean needVer, @Nullable ClassLoader ldr) {\n assert key != null;\n assert val != null || skipVals;\n if (!keepCacheObjects) {\n Object key0 = unwrapBinaryIfNeeded(key, !deserializeBinary, cpy, ldr);\n Object val0 = skipVals ? true : unwrapBinaryIfNeeded(val, !deserializeBinary, cpy, ldr);\n assert key0 != null : key;\n assert val0 != null : val;\n V1 v = createValue(ver, expireTime, ttl, val0, getRes, needVer);\n map.put((K1) key0, v);\n } else {\n Object val0 = skipVals ? true : val;\n V1 v = createValue(ver, expireTime, ttl, val0, getRes, needVer);\n map.put((K1) key, v);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "// /**\n// * Creates a new service offering\n// *\n// * @param name\n// * @param cpu\n// * @param ramSize\n// * @param speed\n// * @param displayText\n// * @param localStorageRequired\n// * @param offerHA\n// * @param domainId\n// * @param volatileVm\n// * @param hostTag\n// * @param networkRate\n// * @param id\n// * @param useVirtualNetwork\n// * @param deploymentPlanner\n// * @param details\n// * @param bytesReadRate\n// * @param bytesWriteRate\n// * @param iopsReadRate\n// * @param iopsWriteRate\n// * @return ID\n// */\n// ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_typeType, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired,\n// boolean offerHA, boolean limitResourceUse, boolean volatileVm, String tags, Long domainId, String hostTag, Integer networkRate, String deploymentPlanner, Map details,\n// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);\n// /**\n// * Creates a new disk offering\n// *\n// * @param domainId\n// * @param name\n// * @param description\n// * @param numGibibytes\n// * @param tags\n// * @param isCustomized\n// * @param localStorageRequired\n// * @param isDisplayOfferingEnabled\n// * @param isCustomizedIops (is admin allowing users to set custom iops?)\n// * @param minIops\n// * @param maxIops\n// * @param bytesReadRate\n// * @param bytesWriteRate\n// * @param iopsReadRate\n// * @param iopsWriteRate\n// * @return newly created disk offering\n// */\n// DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized,\n// boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,\n// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);\n/**\n * Creates a new pod\n *\n * @param userId\n * @param podName\n * @param zone\n * @param gateway\n * @param cidr\n * @param startIp\n * @param endIp\n * @param allocationState\n * @param skipGatewayOverlapCheck\n * (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD)\n * @return Pod\n */\nHostPodVO createPod(long userId, String podName, DataCenter zone, String gateway, String cidr, String startIp, String endIp, String allocationState, boolean skipGatewayOverlapCheck);", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static Specification filter(String urlPartToContain, Integer state, List associatedRecords, Integer[] groupPublishedIds, Integer[] groupOwnerIds, Integer[] httpStatusValueFilter, boolean excludeHarvestedMetadataFilter, Integer[] editingGroupIds) {\n return (root, query, cb) -> {\n List predicates = new ArrayList<>();\n if (state != null) {\n Path statePath = root.get(Link_.lastState);\n predicates.add(cb.equal(statePath, state));\n }\n if (urlPartToContain != null) {\n Path urlPath = root.get(Link_.url);\n predicates.add(cb.like(urlPath, cb.literal(String.format(\"%%%s%%\", urlPartToContain))));\n }\n if (associatedRecords != null) {\n Join metadataJoin = root.join(Link_.records, JoinType.INNER);\n predicates.add(metadataJoin.get(\"metadataUuid\").in(associatedRecords));\n }\n if (excludeHarvestedMetadataFilter) {\n Join metadataJoin = root.join(Link_.records, JoinType.INNER);\n Subquery subquery = query.subquery(Integer.class);\n final Root metadataRoot = subquery.from(Metadata.class);\n Path isHarvestedAttributePath = metadataRoot.get(AbstractMetadata_.harvestInfo).get(MetadataHarvestInfo_.harvested_JPAWorkaround);\n Predicate equalHarvestPredicate = cb.equal(isHarvestedAttributePath, cb.literal(Constants.toYN_EnabledChar(false)));\n subquery.where(equalHarvestPredicate);\n Path metadataId = metadataRoot.get(AbstractMetadata_.id);\n subquery.select(metadataId);\n predicates.add(metadataJoin.get(MetadataLink_.metadataId).in(subquery));\n query.distinct(true);\n }\n if (httpStatusValueFilter != null && httpStatusValueFilter.length > 0) {\n Join linkLinkStatusJoin = root.join(Link_.linkStatus, JoinType.LEFT);\n Integer[] valuesIn = Arrays.stream(httpStatusValueFilter).filter(i -> i >= 0).toArray(Integer[]::new);\n Set setValuesNotIn = Sets.newHashSet(httpStatusValueFilter);\n setValuesNotIn.removeAll(Arrays.asList(valuesIn));\n Integer[] valuesNotIn = setValuesNotIn.stream().map(i -> -1 * i).toArray(Integer[]::new);\n if (valuesIn.length > 0) {\n predicates.add(cb.and(cb.equal(linkLinkStatusJoin.get(LinkStatus_.checkDate), root.get(Link_.lastCheck)), linkLinkStatusJoin.get((LinkStatus_.statusValue)).in(Arrays.asList(Arrays.stream(valuesIn).map(String::valueOf).toArray()))));\n }\n if (valuesNotIn.length > 0) {\n predicates.add(cb.and(cb.equal(linkLinkStatusJoin.get(LinkStatus_.checkDate), root.get(Link_.lastCheck)), cb.not(linkLinkStatusJoin.get((LinkStatus_.statusValue)).in(Arrays.asList(Arrays.stream(valuesNotIn).map(String::valueOf).toArray())))));\n }\n }\n Join metadataJoin = root.join(Link_.records, JoinType.INNER);\n Subquery subquery = query.subquery(Integer.class);\n final Root opAllowRoot = subquery.from(OperationAllowed.class);\n final Root metadataRoot = subquery.from(Metadata.class);\n boolean editinGroupQuery = editingGroupIds != null && editingGroupIds.length > 0;\n boolean groupPublishedQuery = groupPublishedIds != null && groupPublishedIds.length > 0;\n boolean groupOwnerQuery = groupOwnerIds != null && groupOwnerIds.length > 0;\n List subQueryPredicates = new ArrayList<>();\n if (editinGroupQuery) {\n final Predicate groupOwnerPredicate = metadataRoot.get(Metadata_.sourceInfo).get(MetadataSourceInfo_.groupOwner).in(editingGroupIds);\n final Predicate metadataOperations = cb.equal(metadataRoot.get(Metadata_.id), opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.metadataId));\n Predicate editableGroups = opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.groupId).in(Arrays.asList(editingGroupIds));\n Predicate operationTypeEdit = cb.equal(opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.operationId), cb.literal(ReservedOperation.editing.getId()));\n subQueryPredicates.add(cb.or(cb.and(metadataOperations, groupOwnerPredicate), cb.and(editableGroups, operationTypeEdit)));\n }\n if (groupPublishedQuery) {\n Predicate publishedToIndicatedGroup = opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.groupId).in(groupPublishedIds);\n Predicate operationTypeView = cb.equal(opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.operationId), cb.literal(ReservedOperation.view.getId()));\n subQueryPredicates.add(cb.and(publishedToIndicatedGroup, operationTypeView));\n }\n if (groupOwnerQuery) {\n final Predicate groupOwnerPredicate = metadataRoot.get(Metadata_.sourceInfo).get(MetadataSourceInfo_.groupOwner).in(groupOwnerIds);\n subQueryPredicates.add(groupOwnerPredicate);\n }\n if (subQueryPredicates.size() > 0) {\n subquery.where(subQueryPredicates.toArray(new Predicate[] {}));\n Path opAllowedMetadataId = opAllowRoot.get(OperationAllowed_.id).get(OperationAllowedId_.metadataId);\n subquery.select(opAllowedMetadataId);\n predicates.add(metadataJoin.get(MetadataLink_.metadataId).in(subquery));\n }\n query.distinct(true);\n return cb.and(predicates.toArray(new Predicate[] {}));\n };\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static native void glTexImage3D(int target, int level, int internalFormat, int width, int height, int depth, int border, int format, int type, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "/**\n * Get cost range.\n *\n * @param ses Session.\n * @param masks Condition masks.\n * @param rowCount Total row count.\n * @param filters Filters array.\n * @param filter Filter array index.\n * @param sortOrder Sort order.\n * @param isScanIndex Flag if current index is a scan index.\n * @param allColumnsSet All columns to select.\n * @return The cost.\n */\npublic long getCostRangeIndex(Session ses, int[] masks, long rowCount, TableFilter[] filters, int filter, SortOrder sortOrder, boolean isScanIndex, HashSet allColumnsSet) {\n ObjectStatisticsImpl locTblStats = (ObjectStatisticsImpl) tbl.tableStatistics();\n if (locTblStats != null)\n rowCount = locTblStats.rowCount();\n // Small increment to account statistics outdates.\n rowCount += 1000;\n TableFilter tableFilter = (filters == null) ? null : filters[filter];\n long rowsCost = rowCost(ses, tableFilter, masks, rowCount, locTblStats);\n // If the ORDER BY clause matches the ordering of this index,\n // it will be cheaper than another index, so adjust the cost\n // accordingly.\n long sortingCost = sortingCost(rowCount, filters, filter, sortOrder, isScanIndex);\n boolean skipColumnsIntersection = false;\n if (filters != null && tableFilter != null && columns != null) {\n skipColumnsIntersection = true;\n ArrayList idxConds = tableFilter.getIndexConditions();\n // Only pk with _key used.\n if (F.isEmpty(idxConds))\n skipColumnsIntersection = false;\n for (IndexCondition cond : idxConds) {\n if (cond.getColumn() == columns[0]) {\n skipColumnsIntersection = false;\n break;\n }\n }\n }\n // If we have two indexes with the same cost, and one of the indexes can\n // satisfy the query without needing to read from the primary table\n // (scan index), make that one slightly lower cost.\n boolean needsToReadFromScanIdx = true;\n if (!isScanIndex && allColumnsSet != null && !skipColumnsIntersection && !allColumnsSet.isEmpty()) {\n boolean foundAllColumnsWeNeed = true;\n for (Column c : allColumnsSet) {\n if (!c.getTable().equals(getTable()))\n continue;\n boolean found = false;\n for (Column c2 : columns) {\n if (c == c2) {\n found = true;\n break;\n }\n }\n if (!found) {\n foundAllColumnsWeNeed = false;\n break;\n }\n }\n if (foundAllColumnsWeNeed)\n needsToReadFromScanIdx = false;\n }\n long rc;\n if (isScanIndex)\n rc = rowsCost + sortingCost + 20;\n else if (needsToReadFromScanIdx)\n rc = rowsCost + rowsCost + sortingCost + 20;\n else\n // The (20-x) calculation makes sure that when we pick a covering\n // index, we pick the covering index that has the smallest number of\n // columns (the more columns we have in index - the higher cost).\n // This is faster because a smaller index will fit into fewer data\n // blocks.\n rc = rowsCost + sortingCost + columns.length;\n return rc;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private LoanTermVariations createLoanTermVariations(LoanRescheduleRequest loanRescheduleRequest, final Integer termType, final Loan loan, LocalDate rescheduleFromDate, LocalDate adjustedDueDate, List loanRescheduleRequestToTermVariationMappings, final Boolean isActive, final boolean isSpecificToInstallment, final BigDecimal decimalValue, LoanTermVariations parent) {\n LoanTermVariations loanTermVariation = new LoanTermVariations(termType, rescheduleFromDate, decimalValue, adjustedDueDate, isSpecificToInstallment, loan, loan.getStatus().getValue(), isActive, parent);\n loan.getLoanTermVariations().add(loanTermVariation);\n loanRescheduleRequestToTermVariationMappings.add(LoanRescheduleRequestToTermVariationMapping.createNew(loanRescheduleRequest, loanTermVariation));\n return loanTermVariation;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static ConsequenceBuilder._22 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18, Variable arg19, Variable arg20, Variable arg21, Variable arg22){\r\n return new ConsequenceBuilder._22(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21, arg22);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void updateMetricsFromWorker(String dbName, String tableName, String partitionName, CompactionType type, int preWorkerActiveDeltaCount, int preWorkerDeleteDeltaCount, Configuration conf, IMetaStoreClient client) {\n if (!(MetastoreConf.getBoolVar(conf, MetastoreConf.ConfVars.METRICS_ENABLED) && MetastoreConf.getBoolVar(conf, MetastoreConf.ConfVars.METASTORE_ACIDMETRICS_THREAD_ON))) {\n LOG.debug(\"Acid metric collection is not enabled. To turn it on, \\\"metastore.acidmetrics.thread.on\\\" and \" + \"\\\"metastore.metrics.enabled\\\" must be set to true and HS2/HMS restarted.\");\n return;\n }\n LOG.debug(\"Updating delta file metrics from worker\");\n int deltasThreshold = MetastoreConf.getIntVar(conf, MetastoreConf.ConfVars.METASTORE_DELTAMETRICS_DELTA_NUM_THRESHOLD);\n int obsoleteDeltasThreshold = MetastoreConf.getIntVar(conf, MetastoreConf.ConfVars.METASTORE_DELTAMETRICS_OBSOLETE_DELTA_NUM_THRESHOLD);\n try {\n // we have an instance of the AcidDirectory before the compaction worker was started\n // from this we can get how many delta directories existed\n // the previously active delta directories are now moved to obsolete\n updateDeltaMetrics(dbName, tableName, partitionName, CompactionMetricsMetricType.NUM_OBSOLETE_DELTAS, preWorkerActiveDeltaCount, obsoleteDeltasThreshold, client);\n // We don't know the size of the newly create delta directories, that would require a fresh AcidDirectory\n // Clear the small delta num counter from the cache for this key\n removeDeltaMetrics(dbName, tableName, partitionName, CompactionMetricsMetricType.NUM_SMALL_DELTAS, client);\n // The new number of active delta dirs are either 0, 1 or 2.\n // If we ran MAJOR compaction, no new delta is created, just base dir\n // If we ran MINOR compaction, we can have 1 or 2 new delta dirs, depending on whether we had deltas or\n // delete deltas.\n if (type == CompactionType.MAJOR) {\n removeDeltaMetrics(dbName, tableName, partitionName, CompactionMetricsMetricType.NUM_DELTAS, client);\n } else {\n int numNewDeltas = 0;\n // check whether we had deltas\n if (preWorkerDeleteDeltaCount > 0) {\n numNewDeltas++;\n }\n // if the size of the current dirs is bigger than the size of delete deltas, it means we have active deltas\n if (preWorkerActiveDeltaCount > preWorkerDeleteDeltaCount) {\n numNewDeltas++;\n }\n // recalculate the delta count\n updateDeltaMetrics(dbName, tableName, partitionName, CompactionMetricsMetricType.NUM_DELTAS, numNewDeltas, deltasThreshold, client);\n }\n LOG.debug(\"Finished updating delta file metrics from worker.\\n deltasThreshold = {}, \" + \"obsoleteDeltasThreshold = {}, numObsoleteDeltas = {}\", deltasThreshold, obsoleteDeltasThreshold, preWorkerActiveDeltaCount);\n } catch (Throwable t) {\n LOG.warn(\"Unknown throwable caught while updating delta metrics. Metrics will not be updated.\", t);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private Snapshot orchestrateTakeVolumeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm, Snapshot.LocationType locationType, boolean asyncBackup, List zoneIds) throws ResourceAllocationException {\n VolumeInfo volume = volFactory.getVolume(volumeId);\n if (volume == null) {\n throw new InvalidParameterValueException(\"Creating snapshot failed due to volume:\" + volumeId + \" doesn't exist\");\n }\n if (volume.getState() != Volume.State.Ready) {\n throw new InvalidParameterValueException(\"VolumeId: \" + volumeId + \" is not in \" + Volume.State.Ready + \" state but \" + volume.getState() + \". Cannot take snapshot.\");\n }\n boolean isSnapshotOnStorPoolOnly = volume.getStoragePoolType() == StoragePoolType.StorPool && BooleanUtils.toBoolean(_configDao.getValue(\"sp.bypass.secondary.storage\"));\n if (volume.getEncryptFormat() != null && volume.getAttachedVM() != null && volume.getAttachedVM().getState() != State.Stopped && !isSnapshotOnStorPoolOnly) {\n logger.debug(String.format(\"Refusing to take snapshot of encrypted volume (%s) on running VM (%s)\", volume, volume.getAttachedVM()));\n throw new UnsupportedOperationException(\"Volume snapshots for encrypted volumes are not supported if VM is running\");\n }\n CreateSnapshotPayload payload = new CreateSnapshotPayload();\n payload.setSnapshotId(snapshotId);\n payload.setSnapshotPolicyId(policyId);\n payload.setAccount(account);\n payload.setQuiescevm(quiescevm);\n payload.setLocationType(locationType);\n payload.setAsyncBackup(asyncBackup);\n if (CollectionUtils.isNotEmpty(zoneIds)) {\n payload.setZoneIds(zoneIds);\n }\n volume.addPayload(payload);\n return volService.takeSnapshot(volume);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Creates a new metadata duplicating an existing template with an specified uuid.\n *\n * @param isTemplate\n * @param fullRightsForGroup\n */\nString createMetadata(ServiceContext context, String templateId, String groupOwner, String source, int owner, String parentUuid, String isTemplate, boolean fullRightsForGroup, String uuid) throws Exception;", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "public static MockRelViewTable create(ViewTable viewTable, MockCatalogReader catalogReader, String catalogName, String schemaName, String name, boolean stream, double rowCount, ColumnResolver resolver){\r\n Table underlying = viewTable.unwrap(Table.class);\r\n InitializerExpressionFactory initializerExpressionFactory = underlying instanceof Wrapper ? ((Wrapper) underlying).unwrap(InitializerExpressionFactory.class) : NullInitializerExpressionFactory.INSTANCE;\r\n return new MockRelViewTable(viewTable, catalogReader, catalogName, schemaName, name, stream, rowCount, resolver, Util.first(initializerExpressionFactory, NullInitializerExpressionFactory.INSTANCE));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates a LogicalJoin given left and right operands and a join condition.\n * Swaps the operands if beneficial.\n *\n * @param multiJoin join factors being optimized\n * @param left left operand\n * @param right right operand\n * @param condition join condition\n * @param joinType the join type\n * @param fullAdjust true if the join condition reflects the original join\n * ordering and therefore has not gone through any type of adjustment yet;\n * otherwise, the condition has already been partially adjusted and only\n * needs to be further adjusted if swapping is done\n * @param filtersToAdd additional filters that may be added on top of the\n * resulting LogicalJoin, if the join is a left or right outer join\n * @param selfJoin true if the join being created is a self-join that's\n * removable\n *\n * @return created LogicalJoin\n */\nprivate static LoptJoinTree createJoinSubtree(RelMetadataQuery mq, RelBuilder relBuilder, LoptMultiJoin multiJoin, LoptJoinTree left, LoptJoinTree right, RexNode condition, JoinRelType joinType, List filtersToAdd, boolean fullAdjust, boolean selfJoin) {\n RexBuilder rexBuilder = multiJoin.getMultiJoinRel().getCluster().getRexBuilder();\n // swap the inputs if beneficial\n if (swapInputs(mq, multiJoin, left, right, selfJoin)) {\n LoptJoinTree tmp = right;\n right = left;\n left = tmp;\n if (!fullAdjust) {\n condition = swapFilter(rexBuilder, multiJoin, right, left, condition);\n }\n if ((joinType != JoinRelType.INNER) && (joinType != JoinRelType.FULL)) {\n joinType = (joinType == JoinRelType.LEFT) ? JoinRelType.RIGHT : JoinRelType.LEFT;\n }\n }\n if (fullAdjust) {\n int[] adjustments = new int[multiJoin.getNumTotalFields()];\n if (needsAdjustment(multiJoin, adjustments, left, right, selfJoin)) {\n condition = condition.accept(new RelOptUtil.RexInputConverter(rexBuilder, multiJoin.getMultiJoinFields(), left.getJoinTree().getRowType().getFieldList(), right.getJoinTree().getRowType().getFieldList(), adjustments));\n }\n }\n relBuilder.push(left.getJoinTree()).push(right.getJoinTree()).join(joinType, condition);\n // if this is a left or right outer join, and additional filters can\n // be applied to the resulting join, then they need to be applied\n // as a filter on top of the outer join result\n if ((joinType == JoinRelType.LEFT) || (joinType == JoinRelType.RIGHT)) {\n assert !selfJoin;\n addAdditionalFilters(relBuilder, multiJoin, left, right, filtersToAdd);\n }\n return new LoptJoinTree(relBuilder.build(), left.getFactorTree(), right.getFactorTree(), selfJoin);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "private void allocateContainersInternal(long rmIdentifier, AllocationParams appParams, ContainerIdGenerator idCounter, Set blacklist, Set allocatedNodes, ApplicationAttemptId id, Map allNodes, String userName, Map> allocations, EnrichedResourceRequest enrichedAsk, int maxAllocations) throws YarnException {\n if (allNodes.size() == 0) {\n LOG.info(\"No nodes currently available to \" + \"allocate OPPORTUNISTIC containers.\");\n return;\n }\n ResourceRequest anyAsk = enrichedAsk.getRequest();\n int toAllocate = anyAsk.getNumContainers() - (allocations.isEmpty() ? 0 : allocations.get(anyAsk.getCapability()).size());\n toAllocate = Math.min(toAllocate, appParams.getMaxAllocationsPerSchedulerKeyPerRound());\n if (maxAllocations >= 0) {\n toAllocate = Math.min(maxAllocations, toAllocate);\n }\n int numAllocated = 0;\n // Node Candidates are selected as follows:\n // * Node local candidates selected in loop == 0\n // * Rack local candidates selected in loop == 1\n // * From loop == 2 onwards, we revert to off switch allocations.\n int loopIndex = OFF_SWITCH_LOOP;\n if (enrichedAsk.getNodeMap().size() > 0) {\n loopIndex = NODE_LOCAL_LOOP;\n }\n while (numAllocated < toAllocate) {\n Collection nodeCandidates = findNodeCandidates(loopIndex, allNodes, blacklist, allocatedNodes, enrichedAsk);\n for (RemoteNode rNode : nodeCandidates) {\n String rNodeHost = rNode.getNodeId().getHost();\n // Ignore black list\n if (blacklist.contains(rNodeHost)) {\n LOG.info(\"Nodes for scheduling has a blacklisted node\" + \" [\" + rNodeHost + \"]..\");\n continue;\n }\n String location = ResourceRequest.ANY;\n if (loopIndex == NODE_LOCAL_LOOP) {\n if (enrichedAsk.getNodeMap().containsKey(rNodeHost)) {\n location = rNodeHost;\n } else {\n continue;\n }\n } else if (allocatedNodes.contains(rNodeHost)) {\n LOG.info(\"Opportunistic container has already been allocated on {}.\", rNodeHost);\n continue;\n }\n if (loopIndex == RACK_LOCAL_LOOP) {\n if (enrichedAsk.getRackMap().containsKey(rNode.getRackName())) {\n location = rNode.getRackName();\n } else {\n continue;\n }\n }\n Container container = createContainer(rmIdentifier, appParams, idCounter, id, userName, allocations, location, anyAsk, rNode);\n numAllocated++;\n updateMetrics(loopIndex);\n allocatedNodes.add(rNodeHost);\n LOG.info(\"Allocated [\" + container.getId() + \"] as opportunistic at \" + \"location [\" + location + \"]\");\n if (numAllocated >= toAllocate) {\n break;\n }\n }\n if (loopIndex == NODE_LOCAL_LOOP && enrichedAsk.getRackMap().size() > 0) {\n loopIndex = RACK_LOCAL_LOOP;\n } else {\n loopIndex++;\n }\n // Handle case where there are no nodes remaining after blacklist is\n // considered.\n if (loopIndex > OFF_SWITCH_LOOP && numAllocated == 0) {\n LOG.warn(\"Unable to allocate any opportunistic containers.\");\n break;\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public List search(final String key, final int page, final int size, final AuditElements.EventCategoryType type, final String category, final List events, final AuditElements.Result result, final SortParam sort){\r\n AuditQuery query = new AuditQuery.Builder().entityKey(key).size(size).page(page).type(type).category(category).events(events).result(result).orderBy(toOrderBy(sort)).build();\r\n return getService(AuditService.class).search(query).getResult();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readEntryInternal(final long ledgerId, final long entryId, final Long previousLAC, final Long timeOutInMillis, final boolean piggyBackEntry, final ReadEntryCallback cb, final Object ctx, int flags, byte[] masterKey, boolean allowFastFail){\r\n Object request = null;\r\n CompletionKey completionKey = null;\r\n if (useV2WireProtocol) {\r\n request = new BookieProtocol.ReadRequest(BookieProtocol.CURRENT_PROTOCOL_VERSION, ledgerId, entryId, (short) flags, masterKey);\r\n completionKey = acquireV2Key(ledgerId, entryId, OperationType.READ_ENTRY);\r\n } else {\r\n final long txnId = getTxnId();\r\n completionKey = new V3CompletionKey(txnId, OperationType.READ_ENTRY);\r\n BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE).setOperation(OperationType.READ_ENTRY).setTxnId(txnId);\r\n if (((short) flags & BookieProtocol.FLAG_HIGH_PRIORITY) == BookieProtocol.FLAG_HIGH_PRIORITY) {\r\n headerBuilder.setPriority(DEFAULT_HIGH_PRIORITY_VALUE);\r\n }\r\n ReadRequest.Builder readBuilder = ReadRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId);\r\n if (null != previousLAC) {\r\n readBuilder = readBuilder.setPreviousLAC(previousLAC);\r\n }\r\n if (null != timeOutInMillis) {\r\n if (null == previousLAC) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder = readBuilder.setTimeOut(timeOutInMillis);\r\n }\r\n if (piggyBackEntry) {\r\n if (null == previousLAC) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder = readBuilder.setFlag(ReadRequest.Flag.ENTRY_PIGGYBACK);\r\n }\r\n if (((short) flags & BookieProtocol.FLAG_DO_FENCING) == BookieProtocol.FLAG_DO_FENCING) {\r\n readBuilder.setFlag(ReadRequest.Flag.FENCE_LEDGER);\r\n if (masterKey == null) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder.setMasterKey(ByteString.copyFrom(masterKey));\r\n }\r\n request = withRequestContext(Request.newBuilder()).setHeader(headerBuilder).setReadRequest(readBuilder).build();\r\n }\r\n ReadCompletion readCompletion = new ReadCompletion(completionKey, cb, ctx, ledgerId, entryId);\r\n putCompletionKeyValue(completionKey, readCompletion);\r\n writeAndFlush(channel, completionKey, request, allowFastFail);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, RestConfiguration configuration, Map parameters, boolean api) throws Exception {\n String path = basePath;\n if (uriTemplate != null) {\n // make sure to avoid double slashes\n if (uriTemplate.startsWith(\"/\")) {\n path = path + uriTemplate;\n } else {\n path = path + \"/\" + uriTemplate;\n }\n }\n path = FileUtil.stripLeadingSeparator(path);\n String scheme = \"http\";\n String host = \"\";\n int port = 0;\n // if no explicit port/host configured, then use port from rest configuration\n RestConfiguration config = configuration;\n if (config == null) {\n config = CamelContextHelper.getRestConfiguration(getCamelContext(), \"jetty\");\n }\n if (config.getScheme() != null) {\n scheme = config.getScheme();\n }\n if (config.getHost() != null) {\n host = config.getHost();\n }\n int num = config.getPort();\n if (num > 0) {\n port = num;\n }\n // prefix path with context-path if configured in rest-dsl configuration\n String contextPath = config.getContextPath();\n if (ObjectHelper.isNotEmpty(contextPath)) {\n contextPath = FileUtil.stripTrailingSeparator(contextPath);\n contextPath = FileUtil.stripLeadingSeparator(contextPath);\n if (ObjectHelper.isNotEmpty(contextPath)) {\n path = contextPath + \"/\" + path;\n }\n }\n // if no explicit hostname set then resolve the hostname\n if (ObjectHelper.isEmpty(host)) {\n host = RestComponentHelper.resolveRestHostName(host, config);\n }\n Map map = RestComponentHelper.initRestEndpointProperties(\"jetty\", config);\n boolean cors = config.isEnableCORS();\n if (cors) {\n // allow HTTP Options as we want to handle CORS in rest-dsl\n map.put(\"optionsEnabled\", \"true\");\n }\n if (api) {\n map.put(\"matchOnUriPrefix\", \"true\");\n }\n RestComponentHelper.addHttpRestrictParam(map, verb, cors);\n String url = RestComponentHelper.createRestConsumerUrl(\"jetty\", scheme, host, port, path, map);\n JettyHttpEndpoint endpoint = (JettyHttpEndpoint) camelContext.getEndpoint(url, parameters);\n if (!map.containsKey(\"httpBindingRef\")) {\n // use the rest binding, if not using a custom http binding\n endpoint.setHttpBinding(new JettyRestHttpBinding(endpoint));\n // disable this filter as we want to use ours\n endpoint.setEnableMultipartFilter(false);\n }\n // configure consumer properties\n Consumer consumer = endpoint.createConsumer(processor);\n if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {\n setProperties(camelContext, consumer, config.getConsumerProperties());\n }\n // the endpoint must be started before creating the producer\n ServiceHelper.startService(endpoint);\n return consumer;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public static SmsCampaignData template(final Collection smsProviderOptions, final Collection campaignTypeOptions, final Collection businessRulesOptions, final Collection triggerTypeOptions, final Collection months, final Collection weekDays, final Collection frequencyTypeOptions, final Collection periodFrequencyOptions) {\n final Long id = null;\n final String campaignName = null;\n final EnumOptionData campaignType = null;\n final Long runReportId = null;\n final String paramValue = null;\n final EnumOptionData campaignStatus = null;\n final String message = null;\n final ZonedDateTime nextTriggerDate = null;\n final LocalDate lastTriggerDate = null;\n final SmsCampaignTimeLine smsCampaignTimeLine = null;\n final ZonedDateTime recurrenceStartDate = null;\n final String recurrence = null;\n final EnumOptionData triggerType = null;\n final String reportName = null;\n final Long providerId = null;\n final boolean isNotification = false;\n return new SmsCampaignData(id, campaignName, campaignType, triggerType, runReportId, reportName, paramValue, campaignStatus, message, nextTriggerDate, lastTriggerDate, smsCampaignTimeLine, recurrenceStartDate, recurrence, providerId, businessRulesOptions, smsProviderOptions, campaignTypeOptions, triggerTypeOptions, months, weekDays, frequencyTypeOptions, periodFrequencyOptions, isNotification);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static void writeRow(ArrayBuilder rows, IDbmsSupport dbmsSupport, ResultSet rs, ResultSetMetaData rsmeta, String blobCharset, boolean decompressBlobs, String nullValue, boolean trimSpaces, boolean getBlobSmart) throws SenderException, SQLException, SAXException {\n try (INodeBuilder nodeBuilder = rows.addElement()) {\n try (ObjectBuilder row = nodeBuilder.startObject()) {\n for (int i = 1; i <= rsmeta.getColumnCount(); i++) {\n String columnName = rsmeta.getColumnName(i);\n if (convertFieldnamesToUppercase) {\n columnName = columnName.toUpperCase();\n }\n try {\n String value = JdbcUtil.getValue(dbmsSupport, rs, i, rsmeta, blobCharset, decompressBlobs, nullValue, trimSpaces, getBlobSmart, false);\n if (rs.wasNull()) {\n row.add(columnName, (String) null);\n } else {\n if (JdbcUtil.isSQLTypeNumeric(rsmeta.getColumnType(i))) {\n row.addNumber(columnName, value);\n } else {\n row.add(columnName, value);\n }\n }\n } catch (Exception e) {\n throw new SenderException(\"error getting fieldvalue column [\" + i + \"] fieldType [\" + getFieldType(rsmeta.getColumnType(i)) + \"]\", e);\n }\n }\n //JdbcUtil.warningsToXml(rs.getWarnings(), row);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "//\tincludeFormat\n/**\n * \tCreate String Element\n *\n * \t@param content string to be printed\n * \t@param AD_PrintColor_ID color\n * \t@param AD_PrintFont_ID font\n * \t@param maxWidth max width\n * \t@param maxHeight max height\n * \t@param isHeightOneLine onle line only\n * \t@param FieldAlignmentType alignment type (MPrintFormatItem.FIELD_ALIGN_*)\n * @param isTranslated if true and content contaiins @variable@, it is dynamically translated during print\n * \t@return Print Element\n */\nprivate PrintElement createStringElement(String content, int AD_PrintColor_ID, int AD_PrintFont_ID, int maxWidth, int maxHeight, boolean isHeightOneLine, String FieldAlignmentType, boolean isTranslated) {\n if (content == null || content.length() == 0)\n return null;\n //\tColor / Font\n //\tdefault\n Color color = getColor();\n if (AD_PrintColor_ID != 0 && m_printColor.get_ID() != AD_PrintColor_ID) {\n MPrintColor c = MPrintColor.get(getCtx(), AD_PrintColor_ID);\n if (c.getColor() != null)\n color = c.getColor();\n }\n //\tdefault\n Font font = m_printFont.getFont();\n if (AD_PrintFont_ID != 0 && m_printFont.get_ID() != AD_PrintFont_ID) {\n MPrintFont f = MPrintFont.get(AD_PrintFont_ID);\n if (f.getFont() != null)\n font = f.getFont();\n }\n PrintElement e = new StringElement(content, font, color, null, isTranslated);\n e.layout(maxWidth, maxHeight, isHeightOneLine, FieldAlignmentType);\n return e;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "/**\n * Creates a new Grid object.\n *\n * @param \n * the generic type\n * @param panelContent\n * the panel content\n * @param dataType\n * the data type\n * @param datasource\n * the datasource\n * @param caption\n * the caption\n * @param columnOrder\n * the column order\n * @param hideColumns\n * the hide columns\n * @param listener\n * the listener\n * @param actionId\n * the action id\n * @param collectionPropertyConverters\n * the collection property converters\n */\n void createBasicBeanItemGrid(AbstractOrderedLayout panelContent, Class dataType, List datasource, String caption, String[] columnOrder, String[] hideColumns, PageItemRendererClickListener listener, String actionId, ListPropertyConverter[] collectionPropertyConverters);", "smellKey": "S107", "smellId": null, "repo": "Hack23_cia", "language": "java"} {"function": "public Long createOrUpdateWorkflow(String userName, String projectName, String name, String description, String globalParams, String schedule, boolean onlineSchedule, String warningType, int warningGroupId, int timeout, String workerGroup, int releaseState, String taskRelationJson, String taskDefinitionJson, String otherParamsJson, String executionType){\r\n User user = usersService.queryUser(userName);\r\n if (user.getTenantCode() == null) {\r\n throw new RuntimeException(\"Can not create or update workflow for user who not related to any tenant.\");\r\n }\r\n Project project = projectMapper.queryByName(projectName);\r\n long projectCode = project.getCode();\r\n ProcessDefinition processDefinition = getWorkflow(user, projectCode, name);\r\n ProcessExecutionTypeEnum executionTypeEnum = ProcessExecutionTypeEnum.valueOf(executionType);\r\n long processDefinitionCode;\r\n if (processDefinition != null) {\r\n processDefinitionCode = processDefinition.getCode();\r\n processDefinitionService.releaseProcessDefinition(user, projectCode, processDefinitionCode, ReleaseState.OFFLINE);\r\n processDefinitionService.updateProcessDefinition(user, projectCode, name, processDefinitionCode, description, globalParams, null, timeout, taskRelationJson, taskDefinitionJson, otherParamsJson, executionTypeEnum);\r\n } else {\r\n Map result = processDefinitionService.createProcessDefinition(user, projectCode, name, description, globalParams, null, timeout, taskRelationJson, taskDefinitionJson, otherParamsJson, executionTypeEnum);\r\n if (result.get(Constants.STATUS) != Status.SUCCESS) {\r\n log.error(result.get(Constants.MSG).toString());\r\n throw new ServiceException(result.get(Constants.MSG).toString());\r\n }\r\n processDefinition = (ProcessDefinition) result.get(Constants.DATA_LIST);\r\n processDefinitionCode = processDefinition.getCode();\r\n }\r\n if (schedule != null) {\r\n createOrUpdateSchedule(user, projectCode, processDefinitionCode, schedule, onlineSchedule, workerGroup, warningType, warningGroupId);\r\n }\r\n processDefinitionService.releaseProcessDefinition(user, projectCode, processDefinitionCode, ReleaseState.getEnum(releaseState));\r\n return processDefinitionCode;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Element configPortProfileDetails(Document doc, String name, PortProfileType type, BindingType binding, SwitchPortMode mode, int vlanid, String vdc, String espName) {\n // In mode, exec_configure.\n Element configure = doc.createElementNS(s_ciscons, \"nxos:configure\");\n Element modeConfigure = doc.createElement(\"nxos:\" + s_configuremode);\n configure.appendChild(modeConfigure);\n // Port profile name and type configuration.\n Element portProfile = doc.createElement(\"port-profile\");\n modeConfigure.appendChild(portProfile);\n // Port profile type.\n Element portDetails = doc.createElement(\"name\");\n switch(type) {\n case none:\n portProfile.appendChild(portDetails);\n break;\n case ethernet:\n {\n Element typetag = doc.createElement(\"type\");\n Element ethernettype = doc.createElement(\"ethernet\");\n portProfile.appendChild(typetag);\n typetag.appendChild(ethernettype);\n ethernettype.appendChild(portDetails);\n }\n break;\n case vethernet:\n {\n Element typetag = doc.createElement(\"type\");\n Element ethernettype = doc.createElement(\"vethernet\");\n portProfile.appendChild(typetag);\n typetag.appendChild(ethernettype);\n ethernettype.appendChild(portDetails);\n }\n break;\n }\n // Port profile name.\n Element value = doc.createElement(s_paramvalue);\n value.setAttribute(\"isKey\", \"true\");\n value.setTextContent(name);\n portDetails.appendChild(value);\n // element for port prof mode.\n Element portProf = doc.createElement(s_portprofmode);\n portDetails.appendChild(portProf);\n // Binding type.\n if (binding != BindingType.none) {\n portProf.appendChild(getBindingType(doc, binding));\n }\n if (mode != SwitchPortMode.none) {\n // Switchport mode.\n portProf.appendChild(getSwitchPortMode(doc, mode));\n // Adding vlan details.\n if (vlanid > 0) {\n portProf.appendChild(getAddVlanDetails(doc, mode, Integer.toString(vlanid)));\n }\n }\n // Command \"vmware port-group\".\n Element vmware = doc.createElement(\"vmware\");\n Element portgroup = doc.createElement(\"port-group\");\n vmware.appendChild(portgroup);\n portProf.appendChild(vmware);\n // org %vdc%\n // vservice node profile \n Element vdcValue = doc.createElement(s_paramvalue);\n vdcValue.setAttribute(\"isKey\", \"true\");\n vdcValue.setTextContent(vdc);\n Element org = doc.createElement(\"org\");\n org.appendChild(doc.createElement(\"orgname\")).appendChild(vdcValue);\n portProf.appendChild(org);\n String asaNodeName = \"ASA_\" + vlanid;\n Element vservice = doc.createElement(\"vservice\");\n vservice.appendChild(doc.createElement(\"node\")).appendChild(doc.createElement(asaNodeName)).appendChild(doc.createElement(\"profile\")).appendChild(doc.createElement(espName));\n portProf.appendChild(vservice);\n // no shutdown.\n Element no = doc.createElement(\"no\");\n Element shutdown = doc.createElement(\"shutdown\");\n no.appendChild(shutdown);\n portProf.appendChild(no);\n // Enable the port profile.\n Element state = doc.createElement(\"state\");\n Element enabled = doc.createElement(\"enabled\");\n state.appendChild(enabled);\n portProf.appendChild(state);\n // Persist the configuration across reboots.\n modeConfigure.appendChild(persistConfiguration(doc));\n return configure;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private Optional> buildNode(Workflow workflow, ParserContext context, RuleFlowNodeContainerFactory embeddedSubProcess, FunctionDefinition functionDef, FunctionRef functionRef, VariableInfo varInfo, AsyncInfo asyncInfo, String operationId) {\n for (Entry entry : asyncInfo.getOperation2Channel().entrySet()) {\n if (operationId.equals(entry.getKey())) {\n AsyncChannelInfo channelInfo = entry.getValue();\n return Optional.of(channelInfo.isPublish() ? buildPublishNode(workflow, context, embeddedSubProcess, functionDef, functionRef, varInfo, channelInfo) : buildSubscribeNode(context, embeddedSubProcess, functionDef, varInfo, channelInfo));\n }\n }\n return Optional.empty();\n}", "smellKey": "S107", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "void discoverFields(IVariables variables, MongoDbConnection connection, String collection, String query, String fields, boolean isPipeline, int docsToSample, MongoDbInputMeta transform, DiscoverFieldsCallback discoverFieldsCallback) throws HopException;", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Attaches or detaches a disk to an instance.\n * @param conn libvirt connection\n * @param attach boolean that determines whether the device will be attached or detached\n * @param vmName instance name\n * @param attachingDisk kvm physical disk\n * @param devId device id in instance\n * @param serial\n * @param bytesReadRate bytes read rate\n * @param bytesReadRateMax bytes read rate max\n * @param bytesReadRateMaxLength bytes read rate max length\n * @param bytesWriteRate bytes write rate\n * @param bytesWriteRateMax bytes write rate amx\n * @param bytesWriteRateMaxLength bytes write rate max length\n * @param iopsReadRate iops read rate\n * @param iopsReadRateMax iops read rate max\n * @param iopsReadRateMaxLength iops read rate max length\n * @param iopsWriteRate iops write rate\n * @param iopsWriteRateMax iops write rate max\n * @param iopsWriteRateMaxLength iops write rate max length\n * @param cacheMode cache mode\n * @param encryptDetails encrypt details\n * @throws LibvirtException\n * @throws InternalErrorException\n */\nprotected synchronized void attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KVMPhysicalDisk attachingDisk, final int devId, final String serial, final Long bytesReadRate, final Long bytesReadRateMax, final Long bytesReadRateMaxLength, final Long bytesWriteRate, final Long bytesWriteRateMax, final Long bytesWriteRateMaxLength, final Long iopsReadRate, final Long iopsReadRateMax, final Long iopsReadRateMaxLength, final Long iopsWriteRate, final Long iopsWriteRateMax, final Long iopsWriteRateMaxLength, final String cacheMode, final DiskDef.LibvirtDiskEncryptDetails encryptDetails, Map details) throws LibvirtException, InternalErrorException {\n attachOrDetachDisk(conn, attach, vmName, attachingDisk, devId, serial, bytesReadRate, bytesReadRateMax, bytesReadRateMaxLength, bytesWriteRate, bytesWriteRateMax, bytesWriteRateMaxLength, iopsReadRate, iopsReadRateMax, iopsReadRateMaxLength, iopsWriteRate, iopsWriteRateMax, iopsWriteRateMaxLength, cacheMode, encryptDetails, 0l, details);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static CashierTransactionData instance(final Long id, final Long cashierId, CashierTxnType txnType, final BigDecimal txnAmount, final LocalDate txnDate, final String txnNote, final String entityType, final Long entityId, final OffsetDateTime createdDate, final Long officeId, final String officeName, final Long tellerId, final String tellerName, final String cashierName, final CashierData cashierData, LocalDate startDate, LocalDate endDate) {\n return new CashierTransactionData().setId(id).setCashierId(cashierId).setTxnType(txnType).setTxnAmount(txnAmount).setTxnDate(txnDate).setTxnNote(txnNote).setEntityType(entityType).setEntityId(entityId).setCreatedDate(createdDate).setOfficeId(officeId).setOfficeName(officeName).setTellerId(tellerId).setTellerName(tellerName).setCashierName(cashierName).setCashierData(cashierData).setStartDate(startDate).setEndDate(endDate);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Creates a new Grid object.\n *\n * @param \n * the generic type\n * @param panelContent\n * the panel content\n * @param dataType\n * the data type\n * @param datasource\n * the datasource\n * @param caption\n * the caption\n * @param nestedProperties\n * the nested properties\n * @param columnOrder\n * the column order\n * @param hideColumns\n * the hide columns\n * @param listener\n * the listener\n * @param actionId\n * the action id\n * @param collectionPropertyConverters\n * the collection property converters\n */\n void createBasicBeanItemNestedPropertiesGrid(AbstractOrderedLayout panelContent, Class dataType, List datasource, String caption, String[] nestedProperties, String[] columnOrder, String[] hideColumns, PageItemRendererClickListener listener, String actionId, ListPropertyConverter[] collectionPropertyConverters);", "smellKey": "S107", "smellId": null, "repo": "Hack23_cia", "language": "java"} {"function": "public static BinaryExternalSorter getBinaryExternalSorter(final Object owner, MemoryManager memoryManager, long reservedMemorySize, IOManager ioManager, AbstractRowDataSerializer inputSerializer, BinaryRowDataSerializer serializer, NormalizedKeyComputer normalizedKeyComputer, RecordComparator comparator, Configuration conf) {\n return new BinaryExternalSorter(owner, memoryManager, reservedMemorySize, ioManager, inputSerializer, serializer, normalizedKeyComputer, comparator, conf.get(ExecutionConfigOptions.TABLE_EXEC_SORT_MAX_NUM_FILE_HANDLES), conf.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_ENABLED), (int) conf.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_BLOCK_SIZE).getBytes(), conf.get(ExecutionConfigOptions.TABLE_EXEC_SORT_ASYNC_MERGE_ENABLED));\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": " static Table create(DruidSchema druidSchema, String dataSourceName, List intervals, Map fieldMap, Set metricNameSet, String timestampColumnName, DruidConnectionImpl connection, Map> complexMetrics){\r\n assert connection != null;\r\n connection.metadata(dataSourceName, timestampColumnName, intervals, fieldMap, metricNameSet, complexMetrics);\r\n return DruidTable.create(druidSchema, dataSourceName, intervals, fieldMap, metricNameSet, timestampColumnName, complexMetrics);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": " LogSegmentMetadata completeAndCloseLogSegment(String inprogressZnodeName, long logSegmentSeqNo, long logSegmentId, long firstTxId, long lastTxId, int recordCount, long lastEntryId, long lastSlotId) throws IOException{\r\n Stopwatch stopwatch = Stopwatch.createStarted();\r\n boolean success = false;\r\n try {\r\n LogSegmentMetadata completedLogSegment = doCompleteAndCloseLogSegment(inprogressZnodeName, logSegmentSeqNo, logSegmentId, firstTxId, lastTxId, recordCount, lastEntryId, lastSlotId);\r\n success = true;\r\n return completedLogSegment;\r\n } finally {\r\n if (success) {\r\n closeOpStats.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);\r\n } else {\r\n closeOpStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private TimelineEntities doGetEntities(String entityType, NameValuePair primaryFilter, Collection secondaryFilter, Long windowStart, Long windowEnd, String fromId, Long fromTs, Long limit, EnumSet fields, UserGroupInformation callerUGI) throws YarnException, IOException {\n TimelineEntities entities = null;\n entities = store.getEntities(entityType, limit, windowStart, windowEnd, fromId, fromTs, primaryFilter, secondaryFilter, fields, new CheckAclImpl(callerUGI));\n if (entities == null) {\n return new TimelineEntities();\n }\n return entities;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static List doImport(String fileType, final MEFLib.UuidAction uuidAction, final String style, final String source, final MetadataType isTemplate, final String[] category, final String groupId, final boolean validate, final boolean assign, final ServiceContext context, final Path mefFile) throws Exception {\n ApplicationContext applicationContext = ApplicationContextHolder.get();\n final DataManager dm = applicationContext.getBean(DataManager.class);\n final SettingManager sm = applicationContext.getBean(SettingManager.class);\n // Load preferred schema and set to iso19139 by default\n String preferredSchema = applicationContext.getBean(ServiceConfig.class).getValue(\"preferredSchema\", \"iso19139\");\n final List metadataIdMap = new ArrayList<>();\n final List md = new ArrayList<>();\n final List fc = new ArrayList<>();\n // Try to define MEF version from mef file not from parameter\n if (fileType.equals(\"mef\")) {\n MEFLib.Version version = MEFLib.getMEFVersion(mefFile);\n if (version != null && version.equals(MEFLib.Version.V2)) {\n fileType = \"mef2\";\n }\n }\n IVisitor visitor;\n if (fileType.equals(\"single\"))\n visitor = new XmlVisitor();\n else if (fileType.equals(\"mef\"))\n visitor = new MEFVisitor();\n else if (fileType.equals(\"mef2\"))\n visitor = new MEF2Visitor();\n else\n throw new BadArgumentException(\"Bad file type parameter.\");\n // --- import metadata from MEF, Xml, ZIP files\n final String finalPreferredSchema = preferredSchema;\n MEFLib.visit(mefFile, visitor, new IMEFVisitor() {\n\n public void handleMetadata(Element metadata, int index) throws Exception {\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Collecting metadata:\\n\" + Xml.getString(metadata));\n md.add(index, metadata);\n }\n\n public void handleMetadataFiles(DirectoryStream metadataXmlFiles, Element info, int index) throws Exception {\n String infoSchema = \"_none_\";\n String uuid = null;\n if (info != null && info.getContentSize() != 0) {\n Element general = info.getChild(\"general\");\n if (general != null && general.getContentSize() != 0) {\n if (general.getChildText(\"schema\") != null) {\n infoSchema = general.getChildText(\"schema\");\n }\n if (general.getChildText(\"uuid\") != null) {\n uuid = general.getChildText(\"uuid\");\n }\n }\n }\n Path lastUnknownMetadataFolderName = null;\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"info.xml says schema should be \" + infoSchema);\n Element metadataValidForImport;\n Map> mdFiles = new HashMap<>();\n for (Path file : metadataXmlFiles) {\n if (file != null && java.nio.file.Files.isRegularFile(file)) {\n Element metadata = Xml.loadFile(file);\n // Important folder name to identify metadata should be ../../\n lastUnknownMetadataFolderName = file.getParent().getParent().relativize(file);\n try {\n String metadataSchema = dm.autodetectSchema(metadata, null);\n // If local node doesn't know metadata\n // schema try to load next xml file.\n if (metadataSchema == null) {\n continue;\n }\n String currFile = \"Found metadata file \" + file.getParent().getParent().relativize(file);\n mdFiles.put(metadataSchema, Pair.read(currFile, metadata));\n } catch (NoSchemaMatchesException e) {\n Log.debug(Geonet.MEF, \"No schema match for \" + lastUnknownMetadataFolderName + \".\");\n }\n }\n }\n if (mdFiles.size() == 0) {\n throw new BadFormatEx(uuid + \" / No valid metadata file found\" + ((lastUnknownMetadataFolderName == null) ? \"\" : (\" in \" + lastUnknownMetadataFolderName)) + \".\");\n }\n // 1st: Select metadata with schema in info file\n Pair mdInform = mdFiles.get(infoSchema);\n if (mdInform != null) {\n if (Log.isDebugEnabled(Geonet.MEF)) {\n Log.debug(Geonet.MEF, mdInform.one() + \" with info.xml schema (\" + infoSchema + \").\");\n }\n metadataValidForImport = mdInform.two();\n handleMetadata(metadataValidForImport, index);\n return;\n }\n // 2nd: Select metadata with preferredSchema\n mdInform = mdFiles.get(finalPreferredSchema);\n if (mdInform != null) {\n if (Log.isDebugEnabled(Geonet.MEF)) {\n Log.debug(Geonet.MEF, mdInform.one() + \" with preferred schema (\" + finalPreferredSchema + \").\");\n }\n metadataValidForImport = mdInform.two();\n handleMetadata(metadataValidForImport, index);\n return;\n }\n // Lastly: Select the first metadata in the map\n String metadataSchema = (String) mdFiles.keySet().toArray()[0];\n mdInform = mdFiles.get(metadataSchema);\n if (Log.isDebugEnabled(Geonet.MEF)) {\n Log.debug(Geonet.MEF, mdInform.one() + \" with known schema (\" + metadataSchema + \").\");\n }\n metadataValidForImport = mdInform.two();\n // Import valid metadata\n handleMetadata(metadataValidForImport, index);\n }\n\n // --------------------------------------------------------------------\n public void handleFeatureCat(Element featureCat, int index) throws Exception {\n if (featureCat != null) {\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Collecting feature catalog:\\n\" + Xml.getString(featureCat));\n }\n fc.add(index, featureCat);\n }\n\n // --------------------------------------------------------------------\n /**\n * Record is not a template by default. No category attached to\n * record by default. No stylesheet used by default. If no site\n * identifier provided, use current node id by default. No\n * validation by default.\n *

\n * If record is a template and not a MEF file always generate a new\n * UUID.\n */\n public void handleInfo(Element info, int index) throws Exception {\n String uuid = null;\n String createDate = null;\n String changeDate = null;\n String sourceName = null;\n Map sourceTranslations = Maps.newHashMap();\n // Schema in info.xml is not used here anymore.\n // It is used in handleMetadataFiles as the first option to pick a\n // metadata file from those in a metadata dir in a MEF2\n // String schema = null;\n String rating = null;\n String popularity = null;\n Element categs = null;\n final Element privileges;\n // Apply a stylesheet transformation if requested\n if (!style.equals(\"_none_\")) {\n FilePathChecker.verify(style);\n final GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class);\n Path xsltPath = dataDirectory.getXsltConversion(style);\n if (Files.exists(xsltPath)) {\n md.add(index, Xml.transform(md.get(index), xsltPath));\n } else {\n throw new Exception(String.format(\"XSL transformation '%s' not found.\", style));\n }\n }\n final Element metadata = md.get(index);\n String schema = dm.autodetectSchema(metadata, null);\n if (schema == null)\n throw new Exception(\"Unknown schema\");\n // Handle non MEF files insertion\n if (info.getChildren().isEmpty()) {\n if (category != null) {\n categs = new Element(\"categories\");\n for (String c : category) {\n // TODO: convert id to name ?\n categs.addContent((new Element(\"category\")).setAttribute(\"name\", c));\n }\n }\n privileges = new Element(\"group\");\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"view\"));\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"editing\"));\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"download\"));\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"notify\"));\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"dynamic\"));\n privileges.addContent(new Element(\"operation\").setAttribute(\"name\", \"featured\"));\n if (isTemplate == MetadataType.METADATA) {\n // Get the Metadata uuid if it's not a template.\n uuid = dm.extractUUID(schema, md.get(index));\n } else if (isTemplate == MetadataType.SUB_TEMPLATE) {\n // Get subtemplate uuid if defined in @uuid at root\n uuid = md.get(index).getAttributeValue(\"uuid\");\n } else if (isTemplate == MetadataType.TEMPLATE_OF_SUB_TEMPLATE) {\n // Get subtemplate uuid if defined in @uuid at root\n uuid = md.get(index).getAttributeValue(\"uuid\");\n }\n } else {\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Collecting info file:\\n\" + Xml.getString(info));\n categs = info.getChild(\"categories\");\n privileges = info.getChild(\"privileges\");\n Element general = info.getChild(\"general\");\n uuid = general.getChildText(\"uuid\");\n createDate = general.getChildText(\"createDate\");\n changeDate = general.getChildText(\"changeDate\");\n // If \"assign\" checkbox is set to true, we assign the metadata to the current catalog siteID/siteName\n if (assign) {\n if (Log.isDebugEnabled(Geonet.MEF)) {\n Log.debug(Geonet.MEF, \"Assign to local catalog\");\n }\n } else {\n // --- If siteId is not set, set to current node\n sourceName = general.getChildText(\"siteName\");\n sourceTranslations = translationXmlToLangMap(general.getChildren(\"siteTranslations\"));\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Assign to catalog: \" + source);\n }\n rating = general.getChildText(\"rating\");\n popularity = general.getChildText(\"popularity\");\n }\n if (schema.startsWith(\"iso19139\")) {\n // In GeoNetwork 3.x, links to resources changed:\n // * thumbnails contains full URL instead of file name only\n // * API mode change old URL structure.\n try {\n MetadataResourceDatabaseMigration.updateMetadataResourcesLink(metadata, null, sm);\n } catch (UnsupportedOperationException ex) {\n // Ignore, this is triggered when importing templates with empty gmd:fileIdentifier, should not fail.\n }\n }\n if (validate) {\n Integer groupIdVal = null;\n if (org.apache.commons.lang.StringUtils.isNotEmpty(groupId)) {\n groupIdVal = Integer.parseInt(groupId);\n }\n // Validate xsd and schematron\n DataManager.validateExternalMetadata(schema, metadata, context, groupIdVal);\n }\n try {\n importRecord(uuid, uuidAction, md, schema, index, source, sourceName, sourceTranslations, context, metadataIdMap, createDate, changeDate, groupId, isTemplate);\n } catch (Exception e) {\n throw new Exception(\"Failed to import metadata with uuid '\" + uuid + \"'. \" + e.getLocalizedMessage(), e);\n }\n if (!fc.isEmpty() && fc.get(index) != null) {\n // UUID is set as @uuid in root element\n uuid = UUID.randomUUID().toString();\n fc.add(index, dm.setUUID(\"iso19110\", uuid, fc.get(index)));\n //\n // insert metadata\n //\n int userid = context.getUserSession().getUserIdAsInt();\n String group = null;\n String docType = null;\n String title = null;\n String category = null;\n boolean ufo = false;\n String fcId = dm.insertMetadata(context, \"iso19110\", fc.get(index), uuid, userid, group, source, isTemplate.codeString, docType, category, createDate, changeDate, ufo, IndexingMode.full);\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Adding Feature catalog with uuid: \" + uuid);\n // Create database relation between metadata and feature\n // catalog\n String mdId = metadataIdMap.get(index);\n final MetadataRelationRepository relationRepository = context.getBean(MetadataRelationRepository.class);\n final MetadataRelation relation = new MetadataRelation();\n relation.setId(new MetadataRelationId(Integer.valueOf(mdId), Integer.valueOf(fcId)));\n relationRepository.save(relation);\n metadataIdMap.add(fcId);\n // TODO : privileges not handled for feature catalog ...\n }\n final int iMetadataId = Integer.valueOf(metadataIdMap.get(index));\n final String finalPopularity = popularity;\n final String finalRating = rating;\n final Element finalCategs = categs;\n final String finalGroupId = groupId;\n context.getBean(IMetadataManager.class).update(iMetadataId, new Updater() {\n\n @Override\n public void apply(@Nonnull final Metadata metadata) {\n final MetadataDataInfo dataInfo = metadata.getDataInfo();\n if (finalPopularity != null) {\n dataInfo.setPopularity(Integer.valueOf(finalPopularity));\n }\n if (finalRating != null) {\n dataInfo.setRating(Integer.valueOf(finalRating));\n }\n dataInfo.setType(isTemplate);\n metadata.getHarvestInfo().setHarvested(false);\n addCategoriesToMetadata(metadata, finalCategs, context);\n if (finalGroupId == null || finalGroupId.equals(\"\")) {\n Group ownerGroup = addPrivileges(context, dm, iMetadataId, privileges);\n if (ownerGroup != null) {\n metadata.getSourceInfo().setGroupOwner(ownerGroup.getId());\n }\n } else {\n final OperationAllowedRepository allowedRepository = context.getBean(OperationAllowedRepository.class);\n final Set allowedSet = addOperations(context, dm, privileges, iMetadataId, Integer.valueOf(finalGroupId));\n allowedRepository.saveAll(allowedSet);\n }\n }\n });\n if (validate) {\n java.util.Optional md = context.getBean(MetadataRepository.class).findById(iMetadataId);\n if (md.isPresent()) {\n // Persist the validation status\n IMetadataValidator metadataValidator = context.getBean(IMetadataValidator.class);\n metadataValidator.doValidate(md.get(), context.getLanguage());\n }\n }\n dm.indexMetadata(metadataIdMap.get(index), true);\n }\n\n // --------------------------------------------------------------------\n public void handlePublicFile(String file, String changeDate, InputStream is, int index) throws Exception {\n if (Log.isDebugEnabled(Geonet.MEF)) {\n Log.debug(Geonet.MEF, \"Adding public file with name=\" + file);\n }\n saveFile(context, metadataIdMap.get(index), MetadataResourceVisibility.PUBLIC, file, changeDate, is);\n }\n\n // --------------------------------------------------------------------\n public void handlePrivateFile(String file, String changeDate, InputStream is, int index) throws Exception {\n if (Log.isDebugEnabled(Geonet.MEF))\n Log.debug(Geonet.MEF, \"Adding private file with name=\" + file);\n saveFile(context, metadataIdMap.get(index), MetadataResourceVisibility.PRIVATE, file, changeDate, is);\n }\n });\n return metadataIdMap;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "private boolean readContainerLog(String compressAlgo, Block html, FileStatus thisNodeFile, long start, long end, List candidates, long startTime, long endTime, boolean foundLog, String logEntity) throws IOException {\n Algorithm compressName = Compression.getCompressionAlgorithmByName(compressAlgo);\n Decompressor decompressor = compressName.getDecompressor();\n FileContext fileContext = FileContext.getFileContext(thisNodeFile.getPath().toUri(), conf);\n try (FSDataInputStream fsin = fileContext.open(thisNodeFile.getPath())) {\n int bufferSize = 65536;\n for (IndexedFileLogMeta candidate : candidates) {\n if (candidate.getLastModifiedTime() < startTime || candidate.getLastModifiedTime() > endTime) {\n continue;\n }\n byte[] cbuf = new byte[bufferSize];\n InputStream in = null;\n try {\n in = compressName.createDecompressionStream(new BoundedRangeFileInputStream(fsin, candidate.getStartIndex(), candidate.getFileCompressedSize()), decompressor, LogAggregationIndexedFileController.getFSInputBufferSize(conf));\n long logLength = candidate.getFileSize();\n html.pre().__(\"\\n\\n\").__();\n html.p().__(\"Log Type: \" + candidate.getFileName()).__();\n html.p().__(\"Log Upload Time: \" + Times.format(candidate.getLastModifiedTime())).__();\n html.p().__(\"Log Length: \" + Long.toString(logLength)).__();\n long[] range = checkParseRange(html, start, end, startTime, endTime, logLength, candidate.getFileName());\n processContainerLog(html, range, in, bufferSize, cbuf);\n foundLog = true;\n } catch (Exception ex) {\n LOG.error(\"Error getting logs for \" + logEntity, ex);\n continue;\n } finally {\n IOUtils.closeStream(in);\n }\n }\n }\n return foundLog;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public boolean addTungstenNetworkSubnetCommand(String networkUuid, String ipPrefix, int ipPrefixLen, String gateway, boolean dhcpEnable, String dnsServer, String allocationStart, String allocationEnd, boolean ipFromStart, String subnetName) {\n try {\n VirtualNetwork virtualNetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, networkUuid);\n if (virtualNetwork == null) {\n return false;\n }\n Project project = (Project) apiConnector.findById(Project.class, virtualNetwork.getParentUuid());\n NetworkIpam networkIpam = getDefaultProjectNetworkIpam(project);\n if (networkIpam == null) {\n return false;\n }\n IpamSubnetType ipamSubnetType = getIpamSubnetType(ipPrefix, ipPrefixLen, gateway, dhcpEnable, ipFromStart, allocationStart, allocationEnd, subnetName, dnsServer);\n List> objectReferenceList = virtualNetwork.getNetworkIpam();\n if (objectReferenceList != null && objectReferenceList.size() == 1) {\n VnSubnetsType vnSubnetsType = objectReferenceList.get(0).getAttr();\n vnSubnetsType.addIpamSubnets(ipamSubnetType);\n } else {\n VnSubnetsType vnSubnetsType = new VnSubnetsType();\n vnSubnetsType.addIpamSubnets(ipamSubnetType);\n virtualNetwork.addNetworkIpam(networkIpam, vnSubnetsType);\n }\n virtualNetwork.setPerms2(null);\n Status status = apiConnector.update(virtualNetwork);\n status.ifFailure(errorHandler);\n return status.isSuccess();\n } catch (IOException e) {\n return false;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static void mvFileToFinalPath(Path specPath, String unionSuffix, Configuration hconf, boolean success, Logger log, DynamicPartitionCtx dpCtx, FileSinkDesc conf, Reporter reporter) throws IOException, HiveException {\n // There are following two paths this could could take based on the value of shouldAvoidRename\n // shouldAvoidRename indicate if tmpPath should be renamed/moved or now.\n // if false:\n // Skip renaming/moving the tmpPath\n // Deduplicate and keep a list of files\n // Pass on the list of files to conf (to be used later by fetch operator)\n // if true:\n // 1) Rename tmpPath to a new directory name to prevent additional files\n // from being added by runaway processes.\n // 2) Remove duplicates from the temp directory\n // 3) Rename/move the temp directory to specPath\n FileSystem fs = specPath.getFileSystem(hconf);\n Path tmpPath = Utilities.toTempPath(specPath);\n Path taskTmpPath = Utilities.toTaskTempPath(specPath);\n if (!StringUtils.isEmpty(unionSuffix)) {\n specPath = specPath.getParent();\n }\n PerfLogger perfLogger = SessionState.getPerfLogger();\n boolean isBlobStorage = BlobStorageUtils.isBlobStorageFileSystem(hconf, fs);\n boolean avoidRename = false;\n boolean shouldAvoidRename = shouldAvoidRename(conf, hconf);\n if (isBlobStorage && (shouldAvoidRename || ((conf != null) && conf.isCTASorCM())) || (!isBlobStorage && shouldAvoidRename)) {\n avoidRename = true;\n }\n if (success) {\n if (!avoidRename && fs.exists(tmpPath)) {\n // 1) Rename tmpPath to a new directory name to prevent additional files\n // from being added by runaway processes.\n // this is only done for all statements except SELECT, CTAS and Create MV\n Path tmpPathOriginal = tmpPath;\n tmpPath = new Path(tmpPath.getParent(), tmpPath.getName() + \".moved\");\n LOG.debug(\"shouldAvoidRename is false therefore moving/renaming \" + tmpPathOriginal + \" to \" + tmpPath);\n perfLogger.perfLogBegin(\"FileSinkOperator\", \"rename\");\n Utilities.rename(fs, tmpPathOriginal, tmpPath);\n perfLogger.perfLogEnd(\"FileSinkOperator\", \"rename\");\n }\n // Remove duplicates from tmpPath\n List statusList = HiveStatsUtils.getFileStatusRecurse(tmpPath, ((dpCtx == null) ? 1 : dpCtx.getNumDPCols()), fs);\n FileStatus[] statuses = statusList.toArray(new FileStatus[statusList.size()]);\n if (statuses != null && statuses.length > 0) {\n Set filesKept = new HashSet<>();\n perfLogger.perfLogBegin(\"FileSinkOperator\", \"RemoveTempOrDuplicateFiles\");\n // remove any tmp file or double-committed output files\n int dpLevels = dpCtx == null ? 0 : dpCtx.getNumDPCols(), numBuckets = (conf != null && conf.getTable() != null) ? conf.getTable().getNumBuckets() : 0;\n List emptyBuckets = removeTempOrDuplicateFiles(fs, statuses, unionSuffix, dpLevels, numBuckets, hconf, null, 0, false, filesKept, false);\n perfLogger.perfLogEnd(\"FileSinkOperator\", \"RemoveTempOrDuplicateFiles\");\n // create empty buckets if necessary\n if (!emptyBuckets.isEmpty()) {\n perfLogger.perfLogBegin(\"FileSinkOperator\", \"CreateEmptyBuckets\");\n createEmptyBuckets(hconf, emptyBuckets, conf.getCompressed(), conf.getTableInfo(), reporter);\n for (Path p : emptyBuckets) {\n FileStatus[] items = fs.listStatus(p);\n filesKept.addAll(Arrays.asList(items));\n }\n perfLogger.perfLogEnd(\"FileSinkOperator\", \"CreateEmptyBuckets\");\n }\n // move to the file destination\n Utilities.FILE_OP_LOGGER.trace(\"Moving tmp dir: {} to: {}\", tmpPath, specPath);\n if (shouldAvoidRename(conf, hconf)) {\n // for SELECT statements\n LOG.debug(\"Skipping rename/move files. Files to be kept are: \" + filesKept.toString());\n conf.getFilesToFetch().addAll(filesKept);\n } else if (conf != null && conf.isCTASorCM() && isBlobStorage) {\n // for CTAS or Create MV statements\n perfLogger.perfLogBegin(\"FileSinkOperator\", \"moveSpecifiedFileStatus\");\n LOG.debug(\"CTAS/Create MV: Files being renamed: \" + filesKept.toString());\n if (conf.getTable() != null && conf.getTable().getTableType().equals(TableType.EXTERNAL_TABLE)) {\n // Do this optimisation only for External tables.\n createFileList(filesKept, tmpPath, specPath, fs);\n } else {\n Set filesKeptPaths = filesKept.stream().map(x -> x.getPath().toString()).collect(Collectors.toSet());\n moveSpecifiedFilesInParallel(hconf, fs, tmpPath, specPath, filesKeptPaths);\n }\n perfLogger.perfLogEnd(\"FileSinkOperator\", \"moveSpecifiedFileStatus\");\n } else {\n // for rest of the statement e.g. INSERT, LOAD etc\n perfLogger.perfLogBegin(\"FileSinkOperator\", \"RenameOrMoveFiles\");\n LOG.debug(\"Final renaming/moving. Source: \" + tmpPath + \" .Destination: \" + specPath);\n renameOrMoveFilesInParallel(hconf, fs, tmpPath, specPath);\n perfLogger.perfLogEnd(\"FileSinkOperator\", \"RenameOrMoveFiles\");\n }\n }\n } else {\n Utilities.FILE_OP_LOGGER.trace(\"deleting tmpPath {}\", tmpPath);\n fs.delete(tmpPath, true);\n }\n Utilities.FILE_OP_LOGGER.trace(\"deleting taskTmpPath {}\", taskTmpPath);\n fs.delete(taskTmpPath, true);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": " QueryCallViewItem call(Argument var1, Argument var2, Argument var3, Argument var4, Argument var5, Argument var6, Argument var7, Argument var8){\r\n return call(true, var1, var2, var3, var4, var5, var6, var7, var8);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private KeywordSearchParamsBuilder parseBuilder(String uiLang, String searchTerm, String maxResults, String offset, List targetLangs, List thesauri, String thesauriDomainName, String typeSearch, String keywordUriCode, IsoLanguagesMapper mapper) {\n KeywordSearchParamsBuilder parsedParams = new KeywordSearchParamsBuilder(mapper).lenient(true);\n if (searchTerm != null) {\n KeywordSearchType searchType = KeywordSearchType.parseString(typeSearch);\n parsedParams.keyword(searchTerm, searchType, true);\n }\n if (keywordUriCode != null) {\n parsedParams.uri(keywordUriCode);\n }\n if (maxResults != null) {\n parsedParams.maxResults(Integer.parseInt(maxResults));\n }\n if (offset != null) {\n parsedParams.offset(Integer.parseInt(offset));\n }\n if (thesauriDomainName != null) {\n parsedParams.thesauriDomainName(thesauriDomainName);\n }\n if (thesauri == null) {\n ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get();\n ThesaurusManager thesaurusMan = applicationContext.getBean(ThesaurusManager.class);\n Map listOfThesaurus = thesaurusMan.getThesauriMap();\n for (String t : listOfThesaurus.keySet()) {\n parsedParams.addThesaurus(listOfThesaurus.get(t).getKey());\n }\n } else {\n for (String thesaurusName : thesauri) {\n if (!thesaurusName.trim().isEmpty()) {\n parsedParams.addThesaurus(thesaurusName.trim());\n }\n }\n }\n boolean addedLang = false;\n for (String targetLang : targetLangs) {\n if (!targetLang.trim().isEmpty()) {\n parsedParams.addLang(targetLang.trim());\n addedLang = true;\n }\n }\n if (!addedLang) {\n parsedParams.addLang(uiLang);\n }\n return parsedParams;\n}", "smellKey": "S107", "smellId": null, "repo": "geonetwork_core-geonetwork", "language": "java"} {"function": "private void updateVlanAndIpv6Range(final long id, final VlanVO vlanRange, String startIpv6, String endIpv6, String ip6Gateway, String ip6Cidr, final Boolean isRangeForSystemVM, final Boolean forSystemVms) {\n final List listAllocatedIPs = _ipv6Dao.listByVlanIdAndState(id, IpAddress.State.Allocated);\n if (ip6Gateway != null && !ip6Gateway.equals(vlanRange.getIp6Gateway()) && (CollectionUtils.isNotEmpty(listAllocatedIPs) || CollectionUtils.isNotEmpty(ipv6Service.getAllocatedIpv6FromVlanRange(vlanRange)))) {\n throw new InvalidParameterValueException(String.format(\"Unable to change ipv6 gateway to %s because some IPs are in use\", ip6Gateway));\n }\n if (ip6Cidr != null && !ip6Cidr.equals(vlanRange.getIp6Cidr()) && (CollectionUtils.isNotEmpty(listAllocatedIPs) || CollectionUtils.isNotEmpty(ipv6Service.getAllocatedIpv6FromVlanRange(vlanRange)))) {\n throw new InvalidParameterValueException(String.format(\"Unable to change ipv6 cidr to %s because some IPs are in use\", ip6Cidr));\n }\n ip6Gateway = MoreObjects.firstNonNull(ip6Gateway, vlanRange.getIp6Gateway());\n ip6Cidr = MoreObjects.firstNonNull(ip6Cidr, vlanRange.getIp6Cidr());\n final String[] existingVlanIPRangeArray = StringUtils.isNotEmpty(vlanRange.getIp6Range()) ? vlanRange.getIp6Range().split(\"-\") : null;\n final String currentStartIPv6 = existingVlanIPRangeArray != null ? existingVlanIPRangeArray[0] : null;\n final String currentEndIPv6 = existingVlanIPRangeArray != null ? existingVlanIPRangeArray[1] : null;\n startIpv6 = ObjectUtils.allNull(startIpv6, currentStartIPv6) ? null : MoreObjects.firstNonNull(startIpv6, currentStartIPv6);\n endIpv6 = ObjectUtils.allNull(endIpv6, currentEndIPv6) ? null : MoreObjects.firstNonNull(endIpv6, currentEndIPv6);\n _networkModel.checkIp6Parameters(startIpv6, endIpv6, ip6Gateway, ip6Cidr);\n final Network network = _networkModel.getNetwork(vlanRange.getNetworkId());\n if (!GuestType.Shared.equals(network.getGuestType())) {\n _networkModel.checkIp6CidrSizeEqualTo64(ip6Cidr);\n }\n if (!ObjectUtils.allNull(startIpv6, endIpv6) && ObjectUtils.anyNull(startIpv6, endIpv6)) {\n throw new InvalidParameterValueException(String.format(\"Invalid IPv6 range %s-%s\", startIpv6, endIpv6));\n }\n if (ObjectUtils.allNotNull(startIpv6, endIpv6) && (!startIpv6.equals(currentStartIPv6) || !endIpv6.equals(currentEndIPv6))) {\n checkAllocatedIpv6sAreWithinVlanRange(listAllocatedIPs, startIpv6, endIpv6);\n }\n try {\n VlanVO range = _vlanDao.acquireInLockTable(id, 30);\n if (range == null) {\n throw new CloudRuntimeException(\"Unable to acquire vlan configuration: \" + id);\n }\n if (logger.isDebugEnabled()) {\n logger.debug(\"lock vlan \" + id + \" is acquired\");\n }\n commitUpdateVlanAndIpRange(id, startIpv6, endIpv6, currentStartIPv6, currentEndIPv6, ip6Gateway, ip6Cidr, false, isRangeForSystemVM, forSystemVms);\n } catch (final Exception e) {\n logger.error(\"Unable to edit VlanRange due to \" + e.getMessage(), e);\n throw new CloudRuntimeException(\"Failed to edit VlanRange. Please contact Cloud Support.\");\n } finally {\n _vlanDao.releaseFromLockTable(id);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * \tCreate or Get On Hand Storage\n * \t@param ctx context\n * \t@param M_Locator_ID locator\n * \t@param M_Product_ID product\n * \t@param M_AttributeSetInstance_ID instance\n * @param dateMPolicy optional DateMaterialPolicy filter\n * \t@param trxName transaction\n * @param forUpdate true to acquire DB lock with FOR UPDATE clause\n * @param timeout if forUpdate is true, value for query timeout (0 for no timeout).\n * \t@return existing or new MStorageOnHand\n */\npublic static MStorageOnHand getCreate(Properties ctx, int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID, Timestamp dateMPolicy, String trxName, boolean forUpdate, int timeout) {\n if (M_Locator_ID == 0)\n throw new IllegalArgumentException(\"M_Locator_ID=0\");\n if (M_Product_ID == 0)\n throw new IllegalArgumentException(\"M_Product_ID=0\");\n if (dateMPolicy != null)\n dateMPolicy = Util.removeTime(dateMPolicy);\n MStorageOnHand retValue = get(ctx, M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID, dateMPolicy, trxName);\n if (retValue != null) {\n if (forUpdate)\n DB.getDatabase().forUpdate(retValue, timeout);\n return retValue;\n }\n //\tInsert row based on locator\n MLocator locator = new MLocator(ctx, M_Locator_ID, trxName);\n if (locator.get_ID() != M_Locator_ID)\n throw new IllegalArgumentException(\"Not found M_Locator_ID=\" + M_Locator_ID);\n //\n if (dateMPolicy == null) {\n dateMPolicy = new Timestamp(new Date().getTime());\n dateMPolicy = Util.removeTime(dateMPolicy);\n }\n retValue = new MStorageOnHand(locator, M_Product_ID, M_AttributeSetInstance_ID, dateMPolicy);\n retValue.saveEx(trxName);\n if (s_log.isLoggable(Level.FINE))\n s_log.fine(\"New \" + retValue);\n return retValue;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private BuildInfo apply(String version, String build, String revision, int buildNumber, boolean enterprise, byte serialVersion, String commitId, BuildInfo upstreamBuildInfo){\r\n if (buildNo != -1) {\r\n build = String.valueOf(buildNo);\r\n buildNumber = buildNo;\r\n }\r\n if (this.version != null) {\r\n LOGGER.info(\"Overriding hazelcast version with system property value \" + this.version);\r\n version = this.version;\r\n }\r\n if (this.enterprise != null) {\r\n LOGGER.info(\"Overriding hazelcast enterprise flag with system property value \" + this.enterprise);\r\n enterprise = this.enterprise;\r\n }\r\n return new BuildInfo(version, build, revision, buildNumber, enterprise, serialVersion, commitId, upstreamBuildInfo);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int allocateFast(MemoryBuffer[] dest, long[] destHeaders, int destIx, int destCount, int freeListIx, int allocSize, int startArenaIx, int arenaCount){\r\n int index = startArenaIx;\r\n do {\r\n int newDestIx = arenas[index].allocateFast(freeListIx, dest, destHeaders, destIx, destCount, allocSize);\r\n if (newDestIx == destCount)\r\n return newDestIx;\r\n assert newDestIx != -1;\r\n destIx = newDestIx;\r\n index = getNextIx(index, arenaCount, 1);\r\n } while (index != startArenaIx);\r\n return destIx;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param storageTypes storage types that should be used as targets.\n */\npublic DatanodeStorageInfo[] chooseTarget(String srcPath, int numOfReplicas, Node writer, List chosen, boolean returnChosenNodes, Set excludedNodes, long blocksize, BlockStoragePolicy storagePolicy, EnumSet flags, EnumMap storageTypes) {\n return chooseTarget(srcPath, numOfReplicas, writer, chosen, returnChosenNodes, excludedNodes, blocksize, storagePolicy, flags);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public NodeSet queryField(XQueryContext context, int contextId, DocumentSet docs, NodeSet contextSet, String field, String queryString, int axis, QueryOptions options) throws IOException, XPathException {\n return index.withSearcher(searcher -> {\n NodeSet resultSet = new NewArrayNodeSet();\n boolean returnAncestor = axis == NodeSet.ANCESTOR;\n LuceneConfig config = getLuceneConfig(context.getBroker(), docs);\n Analyzer analyzer = getQueryAnalyzer(config, field, null, options);\n LOG.debug(\"Using analyzer {} for {}\", analyzer, queryString);\n QueryParserWrapper parser = getQueryParser(field, analyzer, docs);\n options.configureParser(parser.getConfiguration());\n Query query = parser.parse(queryString);\n searchAndProcess(contextId, null, docs, contextSet, resultSet, returnAncestor, searcher, query, config);\n return resultSet;\n });\n}", "smellKey": "S107", "smellId": null, "repo": "eXist-db_exist", "language": "java"} {"function": "private synchronized void addAutoScalePolicy(final String timerName, final String policyName, final long priority, final String policyExpression, final String action, final int duration, final int interval, final boolean isCleanUp) throws Exception {\n // Adding a autoscale policy\n // add timer policy lb_policy_scaleUp_cpu_mem -rule - (SYS.CUR_VSERVER.METRIC_TABLE(cpu).AVG_VAL.GT(80)-\n // -action lb_scaleUpAction\n final autoscalepolicy timerPolicy = new autoscalepolicy();\n try {\n timerPolicy.set_name(policyName);\n timerPolicy.set_action(action);\n timerPolicy.set_rule(policyExpression);\n autoscalepolicy.add(_netscalerService, timerPolicy);\n } catch (final Exception e) {\n // Ignore Exception on cleanup\n if (!isCleanUp) {\n throw e;\n }\n }\n // bind timer policy\n // For now it is bound globally.\n // bind timer trigger lb_astimer -policyName lb_policy_scaleUp -vserver lb -priority 1 -samplesize 5\n // TODO: later bind to lbvserver. bind timer trigger lb_astimer -policyName lb_policy_scaleUp -vserver lb\n // -priority 1 -samplesize 5\n // -thresholdsize 5\n final nstimer_autoscalepolicy_binding timer_policy_binding = new nstimer_autoscalepolicy_binding();\n final int sampleSize = duration / interval;\n try {\n timer_policy_binding.set_name(timerName);\n timer_policy_binding.set_policyname(policyName);\n timer_policy_binding.set_samplesize(sampleSize);\n // We are not exposing this parameter as of now.\n timer_policy_binding.set_threshold(sampleSize);\n // i.e. n(m) is not exposed to CS user. So thresholdSize == sampleSize\n timer_policy_binding.set_priority(priority);\n nstimer_autoscalepolicy_binding.add(_netscalerService, timer_policy_binding);\n } catch (final Exception e) {\n // Ignore Exception on cleanup\n if (!isCleanUp) {\n throw e;\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Creates a program builder with the same contents as a program, applying a\n * shuttle first.\n *\n *

TODO: Refactor the above create method in terms of this one.\n *\n * @param rexBuilder Rex builder\n * @param inputRowType Input row type\n * @param exprList Common expressions\n * @param projectRefList Projections\n * @param conditionRef Condition, or null\n * @param outputRowType Output row type\n * @param shuttle Shuttle to apply to each expression before adding it\n * to the program builder\n * @param updateRefs Whether to update references that changes as a result\n * of rewrites made by the shuttle\n * @return A program builder\n */\npublic static RexProgramBuilder create(RexBuilder rexBuilder, final RelDataType inputRowType, final List exprList, final List projectRefList, @Nullable final RexLocalRef conditionRef, final RelDataType outputRowType, final RexShuttle shuttle, final boolean updateRefs) {\n final RexProgramBuilder progBuilder = new RexProgramBuilder(inputRowType, rexBuilder);\n progBuilder.add(exprList, projectRefList, conditionRef, outputRowType, shuttle, updateRefs);\n return progBuilder;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public static SqlWindow create(@Nullable SqlIdentifier declName, @Nullable SqlIdentifier refName, SqlNodeList partitionList, SqlNodeList orderList, SqlLiteral isRows, @Nullable SqlNode lowerBound, @Nullable SqlNode upperBound, @Nullable SqlLiteral allowPartial, SqlParserPos pos) {\n return create(declName, refName, partitionList, orderList, isRows, lowerBound, upperBound, allowPartial, createExcludeNoOthers(SqlParserPos.ZERO), pos);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public EnqueueBean run(String user, Map userArgs, String jar, String mainClass, String libjars, String files, List jarArgs, List defines, String statusdir, String callback, boolean usesHcatalog, String completedUrl, boolean enablelog, Boolean enableJobReconnect, JobType jobType) throws NotAuthorizedException, BadParam, BusyException, QueueException, ExecuteException, IOException, InterruptedException, TooManyRequestsException {\n runAs = user;\n List args = makeArgs(jar, mainClass, libjars, files, jarArgs, defines, statusdir, usesHcatalog, completedUrl, enablelog, enableJobReconnect, jobType);\n return enqueueController(user, userArgs, callback, args);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void addMatch(final AccumulateNode accNode, final Accumulate accumulate, final LeftTuple leftTuple, final RightTuple rightTuple, final LeftTuple currentLeftChild, final LeftTuple currentRightChild, final ReteEvaluator reteEvaluator, final AccumulateMemory am, final BaseAccumulation accctx, final boolean useLeftMemory, final boolean leftPropagation){\r\n LeftTuple tuple = leftTuple;\r\n InternalFactHandle handle = (InternalFactHandle) rightTuple.getFactHandle();\r\n if (accNode.isRightInputIsRiaNode()) {\r\n tuple = (LeftTuple) rightTuple;\r\n handle = rightTuple.getFactHandleForEvaluation();\r\n }\r\n if (leftPropagation && handle.isExpired()) {\r\n return;\r\n }\r\n accctx.setPropagationContext(rightTuple.getPropagationContext());\r\n Object value = accumulate.accumulate(am.workingMemoryContext, accctx, tuple, handle, reteEvaluator);\r\n if (useLeftMemory) {\r\n LeftTuple match = accNode.createLeftTuple(leftTuple, rightTuple, currentLeftChild, currentRightChild, accNode, true);\r\n postAccumulate(accNode, accctx, match);\r\n match.setContextObject(value);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static CalendarData instance(final Long id, final Long calendarInstanceId, final Long entityId, final EnumOptionData entityType, final String title, final String description, final String location, final LocalDate startDate, final LocalDate endDate, final Integer duration, final EnumOptionData type, final boolean repeating, final String recurrence, final EnumOptionData frequency, final Integer interval, final EnumOptionData repeatsOnDay, final EnumOptionData repeatsOnNthDayOfMonth, final EnumOptionData remindBy, final Integer firstReminder, final Integer secondReminder, final String humanReadable, final OffsetDateTime createdDate, final OffsetDateTime lastUpdatedDate, final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId, final String lastUpdatedByUsername, final LocalTime meetingTime, final Integer repeatsOnDayOfMonth) {\n final Collection recurringDates = null;\n final Collection nextTenRecurringDates = null;\n final LocalDate recentEligibleMeetingDate = null;\n final List entityTypeOptions = null;\n final List calendarTypeOptions = null;\n final List remindByOptions = null;\n final List frequencyOptions = null;\n final List repeatsOnDayOptions = null;\n final List frequencyNthDayTypeOptions = null;\n return new CalendarData(id, calendarInstanceId, entityId, entityType, title, description, location, startDate, endDate, duration, type, repeating, recurrence, frequency, interval, repeatsOnDay, repeatsOnNthDayOfMonth, remindBy, firstReminder, secondReminder, recurringDates, nextTenRecurringDates, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId, createdByUsername, lastUpdatedByUserId, lastUpdatedByUsername, repeatsOnDayOfMonth, entityTypeOptions, calendarTypeOptions, remindByOptions, frequencyOptions, repeatsOnDayOptions, meetingTime, frequencyNthDayTypeOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private void updateSchedule(Map result, Schedule schedule, ProcessDefinition processDefinition, String scheduleExpression, WarningType warningType, int warningGroupId, FailureStrategy failureStrategy, Priority processInstancePriority, String workerGroup, String tenantCode, long environmentCode){\r\n if (checkValid(result, schedule.getReleaseState() == ReleaseState.ONLINE, Status.SCHEDULE_CRON_ONLINE_FORBID_UPDATE)) {\r\n log.warn(\"Schedule can not be updated due to schedule is {}, scheduleId:{}.\", ReleaseState.ONLINE.getDescp(), schedule.getId());\r\n return;\r\n }\r\n Date now = new Date();\r\n checkValidTenant(tenantCode);\r\n schedule.setTenantCode(tenantCode);\r\n if (!StringUtils.isEmpty(scheduleExpression)) {\r\n ScheduleParam scheduleParam = JSONUtils.parseObject(scheduleExpression, ScheduleParam.class);\r\n if (scheduleParam == null) {\r\n log.warn(\"Parameter scheduleExpression is invalid, so parse cron error.\");\r\n putMsg(result, Status.PARSE_TO_CRON_EXPRESSION_ERROR);\r\n return;\r\n }\r\n if (DateUtils.differSec(scheduleParam.getStartTime(), scheduleParam.getEndTime()) == 0) {\r\n log.warn(\"The start time must not be the same as the end or time can not be null.\");\r\n putMsg(result, Status.SCHEDULE_START_TIME_END_TIME_SAME);\r\n return;\r\n }\r\n if (scheduleParam.getStartTime().getTime() > scheduleParam.getEndTime().getTime()) {\r\n log.warn(\"The start time must smaller than end time\");\r\n putMsg(result, Status.START_TIME_BIGGER_THAN_END_TIME_ERROR);\r\n return;\r\n }\r\n schedule.setStartTime(scheduleParam.getStartTime());\r\n schedule.setEndTime(scheduleParam.getEndTime());\r\n if (!CronUtils.isValidExpression(scheduleParam.getCrontab())) {\r\n log.error(\"Schedule crontab verify failure, crontab:{}.\", scheduleParam.getCrontab());\r\n putMsg(result, Status.SCHEDULE_CRON_CHECK_FAILED, scheduleParam.getCrontab());\r\n return;\r\n }\r\n schedule.setCrontab(scheduleParam.getCrontab());\r\n schedule.setTimezoneId(scheduleParam.getTimezoneId());\r\n }\r\n if (warningType != null) {\r\n schedule.setWarningType(warningType);\r\n }\r\n schedule.setWarningGroupId(warningGroupId);\r\n if (failureStrategy != null) {\r\n schedule.setFailureStrategy(failureStrategy);\r\n }\r\n schedule.setWorkerGroup(workerGroup);\r\n schedule.setEnvironmentCode(environmentCode);\r\n schedule.setUpdateTime(now);\r\n schedule.setProcessInstancePriority(processInstancePriority);\r\n scheduleMapper.updateById(schedule);\r\n processDefinition.setWarningGroupId(warningGroupId);\r\n processDefinitionMapper.updateById(processDefinition);\r\n log.info(\"Schedule update complete, projectCode:{}, processDefinitionCode:{}, scheduleId:{}.\", processDefinition.getProjectCode(), processDefinition.getCode(), schedule.getId());\r\n putMsg(result, Status.SUCCESS);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Rewrites the query using the given view query.\n *\n *

The input node is a Scan on the view table and possibly a compensation Filter\n * on top. If a rewriting can be produced, we return that rewriting. If it cannot\n * be produced, we will return null.\n */\n@Nullable\nprotected abstract RelNode rewriteView(RelBuilder relBuilder, RexBuilder rexBuilder, RexSimplify simplify, RelMetadataQuery mq, MatchModality matchModality, boolean unionRewriting, RelNode input, @Nullable Project topProject, RelNode node, @Nullable Project topViewProject, RelNode viewNode, BiMap queryToViewTableMapping, EquivalenceClasses queryEC);", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "protected List getUpdateTasks(final Any any, final String password, final boolean changePwd, final Boolean enable, final PropagationByResource propByRes, final PropagationByResource> propByLinkedAccount, final Collection vAttrs, final Collection noPropResourceKeys){\r\n if (noPropResourceKeys != null) {\r\n if (propByRes != null) {\r\n propByRes.removeAll(noPropResourceKeys);\r\n }\r\n if (propByLinkedAccount != null) {\r\n propByLinkedAccount.get(ResourceOperation.CREATE).removeIf(account -> noPropResourceKeys.contains(account.getLeft()));\r\n propByLinkedAccount.get(ResourceOperation.UPDATE).removeIf(account -> noPropResourceKeys.contains(account.getLeft()));\r\n propByLinkedAccount.get(ResourceOperation.DELETE).removeIf(account -> noPropResourceKeys.contains(account.getLeft()));\r\n }\r\n }\r\n return createTasks(any, password, changePwd, enable, Optional.ofNullable(propByRes).orElseGet(PropagationByResource::new), propByLinkedAccount, vAttrs);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "// cmd_process\n/**\n * Fill match to\n * @param xMatchedTable Match from table, to get line id from selected row\n * @param xMatchedToTable\n * @param displayString Match from, to populate xMatchedToTable\n * @param matchToType Document to match with displayString (MATCH_* constant)\n * @param sameBPartner\n * @param sameProduct\n * @param sameQty\n * @param matched true for partial or fully match, false for not matched\n */\npublic IMiniTable cmd_searchTo(IMiniTable xMatchedTable, IMiniTable xMatchedToTable, String displayString, int matchToType, boolean sameBPartner, boolean sameProduct, boolean sameQty, boolean matched) {\n int row = xMatchedTable.getSelectedRow();\n if (log.isLoggable(Level.CONFIG))\n log.config(\"Row=\" + row);\n // ** Create SQL **\n int display = MATCH_INVOICE;\n if (displayString.equals(m_matchOptions[MATCH_SHIPMENT]))\n display = MATCH_SHIPMENT;\n else if (displayString.equals(m_matchOptions[MATCH_ORDER]))\n display = MATCH_ORDER;\n KeyNamePair lineMatched = (KeyNamePair) xMatchedTable.getValueAt(row, I_Line);\n //\tsets m_sql\n tableInit(display, matchToType, matched, lineMatched);\n // ** Add Where Clause **\n KeyNamePair BPartner = (KeyNamePair) xMatchedTable.getValueAt(row, I_BPartner);\n KeyNamePair Product = (KeyNamePair) xMatchedTable.getValueAt(row, I_Product);\n if (log.isLoggable(Level.FINE))\n log.fine(\"BPartner=\" + BPartner + \" - Product=\" + Product);\n //\n if (sameBPartner)\n m_sql.append(\" AND hdr.C_BPartner_ID=\").append(BPartner.getKey());\n if (sameProduct)\n m_sql.append(\" AND lin.M_Product_ID=\").append(Product.getKey());\n // calculate qty\n double docQty = ((Double) xMatchedTable.getValueAt(row, I_QTY)).doubleValue();\n if (sameQty)\n m_sql.append(\" AND \").append(m_qtyColumn).append(\"=\").append(docQty);\n // ** Load Table **\n tableLoad(xMatchedToTable);\n return xMatchedToTable;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": " void autoCreateTimeSeries(ClusterSchemaTree schemaTree, List devicePathList, List indexOfTargetDevices, List> indexOfTargetMeasurementsList, List measurementsList, List tsDataTypesList, List isAlignedList, MPPQueryContext context){\r\n Map> devicesNeedAutoCreateTimeSeries = new HashMap<>();\r\n int deviceIndex;\r\n PartialPath devicePath;\r\n List indexOfTargetMeasurements;\r\n for (int i = 0, size = indexOfTargetDevices.size(); i < size; i++) {\r\n deviceIndex = indexOfTargetDevices.get(i);\r\n devicePath = devicePathList.get(deviceIndex);\r\n indexOfTargetMeasurements = indexOfTargetMeasurementsList.get(i);\r\n int finalDeviceIndex = deviceIndex;\r\n List finalIndexOfMeasurementsNotInTemplate = indexOfTargetMeasurements;\r\n devicesNeedAutoCreateTimeSeries.compute(devicePath, (k, v) -> {\r\n if (v == null) {\r\n v = new Pair<>(isAlignedList.get(finalDeviceIndex), new MeasurementGroup());\r\n }\r\n MeasurementGroup measurementGroup = v.right;\r\n String[] measurements = measurementsList.get(finalDeviceIndex);\r\n TSDataType[] tsDataTypes = tsDataTypesList.get(finalDeviceIndex);\r\n for (int measurementIndex : finalIndexOfMeasurementsNotInTemplate) {\r\n if (tsDataTypes[measurementIndex] == null) {\r\n continue;\r\n }\r\n measurementGroup.addMeasurement(measurements[measurementIndex], tsDataTypes[measurementIndex], getDefaultEncoding(tsDataTypes[measurementIndex]), TSFileDescriptor.getInstance().getConfig().getCompressor());\r\n }\r\n return v;\r\n });\r\n }\r\n if (!devicesNeedAutoCreateTimeSeries.isEmpty()) {\r\n internalCreateTimeSeries(schemaTree, devicesNeedAutoCreateTimeSeries, context);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Set the datanode information.\n *\n * @param numLive Number of live nodes.\n * @param numDead Number of dead nodes.\n * @param numStale Number of stale nodes.\n * @param numDecom Number of decommissioning nodes.\n * @param numLiveDecom Number of decommissioned live nodes.\n * @param numDeadDecom Number of decommissioned dead nodes.\n * @param numInMaintenanceLive Number of in maintenance live nodes.\n * @param numInMaintenanceDead Number of in maintenance dead nodes.\n * @param numEnteringMaintenance Number of entering maintenance nodes.\n * @param numScheduledReplicationBlocks Number of scheduled rep. blocks.\n */\npublic void setDatanodeInfo(int numLive, int numDead, int numStale, int numDecom, int numLiveDecom, int numDeadDecom, int numInMaintenanceLive, int numInMaintenanceDead, int numEnteringMaintenance, long numScheduledReplicationBlocks) {\n this.liveDatanodes = numLive;\n this.deadDatanodes = numDead;\n this.staleDatanodes = numStale;\n this.decomDatanodes = numDecom;\n this.liveDecomDatanodes = numLiveDecom;\n this.deadDecomDatanodes = numDeadDecom;\n this.inMaintenanceLiveDataNodes = numInMaintenanceLive;\n this.inMaintenanceDeadDataNodes = numInMaintenanceDead;\n this.enteringMaintenanceDataNodes = numEnteringMaintenance;\n this.statsValid = true;\n this.scheduledReplicationBlocks = numScheduledReplicationBlocks;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public EntryOperator init(Data dataKey, Object oldValue, Object newValue, Data result, EntryEventType eventType, Boolean locked, boolean changeExpiryOnUpdate, long ttl){\r\n this.dataKey = dataKey;\r\n this.oldValue = oldValue;\r\n this.eventType = eventType;\r\n this.result = result;\r\n this.didMatchPredicate = true;\r\n this.entry.init(ss, dataKey, newValue != null ? newValue : oldValue, mapContainer.getExtractors(), locked, ttl, changeExpiryOnUpdate);\r\n return this;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static EncodingWriter create(InputFormat sourceIf, Deserializer serDe, Map parts, Configuration daemonConf, Configuration jobConf, Path splitPath, StructObjectInspector sourceOi, List sourceIncludes, boolean[] cacheIncludes, int allocSize, ExecutorService encodeExecutor) throws IOException{\r\n if (!HiveConf.getBoolVar(daemonConf, ConfVars.LLAP_IO_ENCODE_VECTOR_SERDE_ENABLED) || !HiveConf.getBoolVar(jobConf, ConfVars.LLAP_IO_ENCODE_VECTOR_SERDE_ENABLED) || !(sourceIf instanceof TextInputFormat) || !(serDe instanceof LazySimpleSerDe)) {\r\n return new DeserializerOrcWriter(serDe, sourceOi, allocSize);\r\n }\r\n Path path = splitPath.getFileSystem(daemonConf).makeQualified(splitPath);\r\n PartitionDesc partDesc = HiveFileFormatUtils.getFromPathRecursively(parts, path, null);\r\n if (partDesc == null) {\r\n LlapIoImpl.LOG.info(\"Not using VertorDeserializeOrcWriter: no partition desc for \" + path);\r\n return new DeserializerOrcWriter(serDe, sourceOi, allocSize);\r\n }\r\n Properties tblProps = partDesc.getTableDesc().getProperties();\r\n if (\"true\".equalsIgnoreCase(tblProps.getProperty(serdeConstants.SERIALIZATION_LAST_COLUMN_TAKES_REST))) {\r\n LlapIoImpl.LOG.info(\"Not using VertorDeserializeOrcWriter due to \" + serdeConstants.SERIALIZATION_LAST_COLUMN_TAKES_REST);\r\n return new DeserializerOrcWriter(serDe, sourceOi, allocSize);\r\n }\r\n for (StructField sf : sourceOi.getAllStructFieldRefs()) {\r\n Category c = sf.getFieldObjectInspector().getCategory();\r\n if (c != Category.PRIMITIVE) {\r\n LlapIoImpl.LOG.info(\"Not using VertorDeserializeOrcWriter: \" + c + \" is not supported\");\r\n return new DeserializerOrcWriter(serDe, sourceOi, allocSize);\r\n }\r\n }\r\n LlapIoImpl.LOG.info(\"Creating VertorDeserializeOrcWriter for \" + path);\r\n return new VectorDeserializeOrcWriter(jobConf, tblProps, sourceOi, sourceIncludes, cacheIncludes, allocSize, encodeExecutor);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static MockModifiableViewRelOptTable create(MockModifiableViewTable modifiableViewTable, MockCatalogReader catalogReader, String catalogName, String schemaName, String name, boolean stream, double rowCount, @Nullable ColumnResolver resolver) {\n final Table underlying = modifiableViewTable.unwrap(Table.class);\n final InitializerExpressionFactory initializerExpressionFactory = underlying instanceof Wrapper ? ((Wrapper) underlying).unwrap(InitializerExpressionFactory.class) : NullInitializerExpressionFactory.INSTANCE;\n return new MockModifiableViewRelOptTable(modifiableViewTable, catalogReader, catalogName, schemaName, name, stream, rowCount, resolver, Util.first(initializerExpressionFactory, NullInitializerExpressionFactory.INSTANCE));\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "public static LogicalMatch create(RelOptCluster cluster, RelTraitSet traitSet, RelNode input, RelDataType rowType, RexNode pattern, boolean strictStart, boolean strictEnd, Map patternDefinitions, Map measures, RexNode after, Map> subsets, boolean allRows, ImmutableBitSet partitionKeys, RelCollation orderKeys, @Nullable RexNode interval){\r\n return new LogicalMatch(cluster, traitSet, input, rowType, pattern, strictStart, strictEnd, patternDefinitions, measures, after, subsets, allRows, partitionKeys, orderKeys, interval);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": " static CompactionEntryLog recoverLog(int srcLogId, int dstLogId, File ledgerDir, int readBufferSize, int maxSaneEntrySize, NativeIO nativeIO, ByteBufAllocator allocator, OpStatsLogger readBlockStats, Slogger slog){\r\n return new RecoveredDirectCompactionEntryLog(srcLogId, dstLogId, ledgerDir, readBufferSize, maxSaneEntrySize, nativeIO, allocator, readBlockStats, slog);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected LogSegmentMetadata doCompleteAndCloseLogSegment(String inprogressZnodeName, long logSegmentSeqNo, long logSegmentId, long firstTxId, long lastTxId, int recordCount, long lastEntryId, long lastSlotId) throws IOException{\r\n CompletableFuture promise = new CompletableFuture();\r\n doCompleteAndCloseLogSegment(inprogressZnodeName, logSegmentSeqNo, logSegmentId, firstTxId, lastTxId, recordCount, lastEntryId, lastSlotId, promise);\r\n return Utils.ioResult(promise);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private SearchCriteria createStoragePoolSearchCriteria(Long storagePoolId, String storagePoolName, Long zoneId, String path, Long podId, Long clusterId, String address, ScopeType scopeType, StoragePoolStatus status, String keyword) {\n SearchBuilder sb = createSearchBuilder();\n // select distinct\n sb.select(null, SearchCriteria.Func.DISTINCT, sb.entity().getId());\n // ids\n sb.and(\"id\", sb.entity().getId(), SearchCriteria.Op.EQ);\n sb.and(\"name\", sb.entity().getName(), SearchCriteria.Op.EQ);\n sb.and(\"path\", sb.entity().getPath(), SearchCriteria.Op.EQ);\n sb.and(\"dataCenterId\", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);\n sb.and(\"podId\", sb.entity().getPodId(), SearchCriteria.Op.EQ);\n sb.and(\"clusterId\", sb.entity().getClusterId(), SearchCriteria.Op.EQ);\n sb.and(\"hostAddress\", sb.entity().getHostAddress(), SearchCriteria.Op.EQ);\n sb.and(\"scope\", sb.entity().getScope(), SearchCriteria.Op.EQ);\n sb.and(\"status\", sb.entity().getStatus(), SearchCriteria.Op.EQ);\n sb.and(\"parent\", sb.entity().getParent(), SearchCriteria.Op.EQ);\n SearchCriteria sc = sb.create();\n if (keyword != null) {\n SearchCriteria ssc = createSearchCriteria();\n ssc.addOr(\"name\", SearchCriteria.Op.LIKE, \"%\" + keyword + \"%\");\n ssc.addOr(\"poolType\", SearchCriteria.Op.LIKE, new Storage.StoragePoolType(\"%\" + keyword + \"%\"));\n sc.addAnd(\"name\", SearchCriteria.Op.SC, ssc);\n }\n if (storagePoolId != null) {\n sc.setParameters(\"id\", storagePoolId);\n }\n if (storagePoolName != null) {\n sc.setParameters(\"name\", storagePoolName);\n }\n if (path != null) {\n sc.setParameters(\"path\", path);\n }\n if (zoneId != null) {\n sc.setParameters(\"dataCenterId\", zoneId);\n }\n if (podId != null) {\n SearchCriteria ssc = createSearchCriteria();\n ssc.addOr(\"podId\", SearchCriteria.Op.EQ, podId);\n ssc.addOr(\"podId\", SearchCriteria.Op.NULL);\n sc.addAnd(\"podId\", SearchCriteria.Op.SC, ssc);\n }\n if (address != null) {\n sc.setParameters(\"hostAddress\", address);\n }\n if (clusterId != null) {\n SearchCriteria ssc = createSearchCriteria();\n ssc.addOr(\"clusterId\", SearchCriteria.Op.EQ, clusterId);\n ssc.addOr(\"clusterId\", SearchCriteria.Op.NULL);\n sc.addAnd(\"clusterId\", SearchCriteria.Op.SC, ssc);\n }\n if (scopeType != null) {\n sc.setParameters(\"scope\", scopeType.toString());\n }\n if (status != null) {\n sc.setParameters(\"status\", status.toString());\n }\n sc.setParameters(\"parent\", 0);\n return sc;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private static native void nativeComputeChunkedSumsByteArray(int bytesPerSum, int checksumType, byte[] sums, int sumsOffset, byte[] data, int dataOffset, int dataLength, String fileName, long basePos, boolean verify);", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void createDebitJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final int accountMappingTypeId, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final LocalDate transactionDate, final BigDecimal amount, final Boolean isReversal) {\n final GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId);\n if (isReversal) {\n createCreditJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n } else {\n createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static ConsequenceBuilder._20 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18, Variable arg19, Variable arg20){\r\n return new ConsequenceBuilder._20(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SqlWindow create(@Nullable SqlIdentifier declName, @Nullable SqlIdentifier refName, SqlNodeList partitionList, SqlNodeList orderList, SqlLiteral isRows, @Nullable SqlNode lowerBound, @Nullable SqlNode upperBound, @Nullable SqlLiteral allowPartial, SqlLiteral exclude, SqlParserPos pos) {\n // If there's only one bound and it's 'FOLLOWING', make it the upper\n // bound.\n if (upperBound == null && lowerBound != null && lowerBound.getKind() == SqlKind.FOLLOWING) {\n upperBound = lowerBound;\n lowerBound = null;\n }\n return new SqlWindow(pos, declName, refName, partitionList, orderList, isRows, lowerBound, upperBound, allowPartial, exclude);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_calcite", "language": "java"} {"function": "/**\n * Does the given line segment intersect the given axis-aligned rectangle?\n *

\n * We assume that the ends of the line segment are outside of the rectangle.\n *\n * @param x1 x-coordinate of first end of line segment\n * @param y1 y-coordinate of first end line segment\n * @param x2 x-coordinate of second end of line segment\n * @param y2 y-coordinate of second end of line segment\n * @param minX min x-coordinate of rectangle\n * @param minY min y-coordinate of rectangle\n * @param maxX max x-coordinate of rectangle\n * @param maxY max y-coordinate of rectangle\n * @return\n */\nprivate static boolean lineSegmentIntersectsRectangle(final float x1, final float y1, final float x2, final float y2, final float minX, final float minY, final float maxX, final float maxY) {\n // Completely outside.\n if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) {\n return false;\n }\n // // Either end completely inside.\n // // Not required if it is assumed that endpoints are outside the rectangle.\n // // if((x1 > minX && x1 < maxX && y1 > minY && y1 < maxY) || (x2 > minX && x2 < maxX && y2 > minY && y2 < maxY))\n // {\n // return true;\n // }\n // Vertical line.\n // We know now that the end-points are outside the rectangle, so we only have to worry\n // that the line is between the sides.\n if (x1 == x2) {\n // At this point minX <= x1 is always true\n return x1 <= maxX;\n }\n // Slope of line segment.\n final float m = (y2 - y1) / (x2 - x1);\n float y = m * (minX - x1) + y1;\n if (y > minY && y < maxY) {\n return true;\n }\n y = m * (maxX - x1) + y1;\n if (y > minY && y < maxY) {\n return true;\n }\n float x = (minY - y1) / m + x1;\n if (x > minX && x < maxX) {\n return true;\n }\n x = (maxY - y1) / m + x1;\n return x > minX && x < maxX;\n}", "smellKey": "S107", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "private String backupSnapshot(final Connection conn, final String primaryStorageSRUuid, final String localMountPoint, final String path, final String secondaryStorageMountPath, final String snapshotUuid, String prevBackupUuid, final Boolean isISCSI, final int wait) {\n String backupSnapshotUuid = null;\n if (prevBackupUuid == null) {\n prevBackupUuid = \"\";\n }\n // Each argument is put in a separate line for readability.\n // Using more lines does not harm the environment.\n final String backupUuid = UUID.randomUUID().toString();\n final String results = hypervisorResource.callHostPluginAsync(conn, \"vmopsSnapshot\", \"backupSnapshot\", wait, \"primaryStorageSRUuid\", primaryStorageSRUuid, \"path\", path, \"secondaryStorageMountPath\", secondaryStorageMountPath, \"snapshotUuid\", snapshotUuid, \"prevBackupUuid\", prevBackupUuid, \"backupUuid\", backupUuid, \"isISCSI\", isISCSI.toString(), \"localMountPoint\", localMountPoint);\n String errMsg = null;\n if (results == null || results.isEmpty()) {\n errMsg = \"Could not copy backupUuid: \" + backupSnapshotUuid + \" from primary storage \" + primaryStorageSRUuid + \" to secondary storage \" + secondaryStorageMountPath + \" due to null\";\n } else {\n final String[] tmp = results.split(\"#\");\n final String status = tmp[0];\n backupSnapshotUuid = tmp[1];\n // status == \"1\" if and only if backupSnapshotUuid != null\n // So we don't rely on status value but return backupSnapshotUuid as an\n // indicator of success.\n if (status != null && status.equalsIgnoreCase(\"1\") && backupSnapshotUuid != null) {\n logger.debug(\"Successfully copied backupUuid: \" + backupSnapshotUuid + \" to secondary storage\");\n return results;\n } else {\n errMsg = \"Could not copy backupUuid: \" + backupSnapshotUuid + \" from primary storage \" + primaryStorageSRUuid + \" to secondary storage \" + secondaryStorageMountPath + \" due to \" + tmp[1];\n }\n }\n final String source = backupUuid + \".vhd\";\n hypervisorResource.killCopyProcess(conn, source);\n logger.warn(errMsg);\n throw new CloudRuntimeException(errMsg);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "//////////////////////////////////////////////////////////////////////////////\n// Factory-like methods to create/read/write appropriate TaskStatus objects\n//////////////////////////////////////////////////////////////////////////////\nstatic TaskStatus createTaskStatus(DataInput in, TaskAttemptID taskId, float progress, int numSlots, State runState, String diagnosticInfo, String stateString, String taskTracker, Phase phase, Counters counters) throws IOException {\n boolean isMap = in.readBoolean();\n return createTaskStatus(isMap, taskId, progress, numSlots, runState, diagnosticInfo, stateString, taskTracker, phase, counters);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//\tgetCharge\n/**\n * @param ctx\n * @param M_Product_ID\n * @param billDate\n * @param shipDate\n * @param AD_Org_ID\n * @param M_Warehouse_ID\n * @param billC_BPartner_Location_ID\n * @param shipC_BPartner_Location_ID\n * @param IsSOTrx\n * @return\n * @deprecated\n */\npublic static int getProduct(Properties ctx, int M_Product_ID, Timestamp billDate, Timestamp shipDate, int AD_Org_ID, int M_Warehouse_ID, int billC_BPartner_Location_ID, int shipC_BPartner_Location_ID, boolean IsSOTrx) {\n return getProduct(ctx, M_Product_ID, billDate, shipDate, AD_Org_ID, M_Warehouse_ID, billC_BPartner_Location_ID, shipC_BPartner_Location_ID, IsSOTrx, null);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private void writeMetadatatoPdfByCitekey(BibDatabaseContext databaseContext, BibDatabase dataBase, List citeKeys, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter, boolean writeXMP, boolean embeddBibfile){\r\n for (String citeKey : citeKeys) {\r\n List bibEntryList = dataBase.getEntriesByCitationKey(citeKey);\r\n if (bibEntryList.isEmpty()) {\r\n System.err.printf(\"Skipped - Cannot find %s in library.%n\", citeKey);\r\n continue;\r\n }\r\n for (BibEntry entry : bibEntryList) {\r\n writeMetadatatoPDFsOfEntry(databaseContext, citeKey, entry, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, writeXMP, embeddBibfile);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void publishUsageEvent(String usageType, long accountId, long zoneId, long ipAddressId, String ipAddress, boolean isSourceNat, String guestType, boolean isSystem, boolean usageHidden, String entityType, String entityUUID) {\n saveUsageEvent(usageType, accountId, zoneId, ipAddressId, ipAddress, isSourceNat, guestType, isSystem, usageHidden);\n publishUsageEvent(usageType, accountId, zoneId, entityType, entityUUID);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static Query3Def query(String pkg, String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name){\r\n return new Query3DefImpl<>(VIEW_BUILDER, pkg, name, type1, arg1name, type2, arg2name, type3, arg3name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String generateNewTsFilePathWithMkdir(boolean sequence, String logicalStorageGroup, String virtualStorageGroup, long timePartitionId, long time, long version, int innerSpaceCompactionCount, int crossSpaceCompactionCount) throws DiskSpaceInsufficientException {\n return generateNewTsFilePathWithMkdir(sequence, logicalStorageGroup, virtualStorageGroup, timePartitionId, time, version, innerSpaceCompactionCount, crossSpaceCompactionCount, 0, TsFileConstant.TSFILE_SUFFIX);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected List getUpdateTasks(final Any any, final String password, final boolean changePwd, final Boolean enable, final PropagationByResource propByRes, final PropagationByResource> propByLinkedAccount, final Collection vAttrs, final Collection excludedResources){\r\n if (excludedResources != null) {\r\n if (propByRes != null) {\r\n propByRes.removeAll(excludedResources);\r\n }\r\n if (propByLinkedAccount != null) {\r\n propByLinkedAccount.get(ResourceOperation.CREATE).removeIf(account -> excludedResources.contains(account.getLeft()));\r\n propByLinkedAccount.get(ResourceOperation.UPDATE).removeIf(account -> excludedResources.contains(account.getLeft()));\r\n propByLinkedAccount.get(ResourceOperation.DELETE).removeIf(account -> excludedResources.contains(account.getLeft()));\r\n }\r\n }\r\n return createTasks(any, password, changePwd, enable, Optional.ofNullable(propByRes).orElseGet(PropagationByResource::new), propByLinkedAccount, vAttrs);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void publishOnEventBus(Event eventRecord, long userId, long accountId, Long domainId, String eventCategory, String eventType, Event.State state, String description, String resourceUuid, String resourceType) {\n String configKey = Config.PublishActionEvent.key();\n String value = s_configDao.getValue(configKey);\n boolean configValue = Boolean.parseBoolean(value);\n if (!configValue)\n return;\n try {\n eventDistributor = ComponentContext.getComponent(EventDistributor.class);\n } catch (NoSuchBeanDefinitionException nbe) {\n // no provider is configured to provide events bus, so just return\n return;\n }\n org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, resourceType, resourceUuid);\n event.setEventId(eventRecord.getId());\n event.setEventUuid(eventRecord.getUuid());\n Map eventDescription = new HashMap();\n Project project = s_projectDao.findByProjectAccountId(accountId);\n Account account = s_accountDao.findById(accountId);\n User user = s_userDao.findById(userId);\n // if account has been deleted, this might be called during cleanup of resources and results in null pointer\n if (account == null)\n return;\n if (user == null)\n return;\n if (project != null)\n eventDescription.put(\"project\", project.getUuid());\n event.setResourceAccountId(accountId);\n event.setResourceAccountUuid(account.getUuid());\n event.setResourceDomainId(domainId == null ? account.getDomainId() : domainId);\n eventDescription.put(\"user\", user.getUuid());\n eventDescription.put(\"account\", account.getUuid());\n eventDescription.put(\"event\", eventType);\n eventDescription.put(\"status\", state.toString());\n eventDescription.put(\"entity\", resourceType);\n eventDescription.put(\"entityuuid\", resourceUuid);\n //Put all the first class entities that are touched during the action. For now at least put in the vmid.\n populateFirstClassEntities(eventDescription);\n eventDescription.put(\"description\", description);\n String eventDate = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss Z\").format(new Date());\n eventDescription.put(\"eventDateTime\", eventDate);\n event.setDescription(eventDescription);\n eventDistributor.publish(event);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "private void scheduleLeftTuple(final TimerNode timerNode, final TimerNodeMemory tm, final PathMemory pmem, final SegmentMemory smem, final LeftTupleSink sink, final ActivationsManager activationsManager, final Timer timer, final TimerService timerService, final long timestamp, final String[] calendarNames, final Calendars calendars, final LeftTuple leftTuple, final TupleSets trgLeftTuples, final TupleSets stagedLeftTuples){\r\n ReteEvaluator reteEvaluator = activationsManager.getReteEvaluator();\r\n if (leftTuple.getPropagationContext().getReaderContext() == null) {\r\n final Trigger trigger = createTrigger(timerNode, reteEvaluator, timer, timestamp, calendarNames, calendars, leftTuple);\r\n scheduleTimer(timerNode, tm, smem, sink, reteEvaluator, timerService, timestamp, leftTuple, trgLeftTuples, stagedLeftTuples, trigger);\r\n } else {\r\n Scheduler scheduler = new Scheduler() {\r\n\r\n @Override\r\n public void schedule(Trigger t) {\r\n scheduleTimer(timerNode, tm, smem, sink, reteEvaluator, timerService, timestamp, leftTuple, trgLeftTuples, stagedLeftTuples, t);\r\n evaluate(pmem, activationsManager, sink, tm, trgLeftTuples);\r\n }\r\n\r\n @Override\r\n public Trigger getTrigger() {\r\n return createTrigger(timerNode, reteEvaluator, timer, timestamp, calendarNames, calendars, leftTuple);\r\n }\r\n };\r\n TupleKey key = TupleKey.createTupleKey(leftTuple);\r\n leftTuple.getPropagationContext().getReaderContext().addTimerNodeScheduler(timerNode.getId(), key, scheduler);\r\n leftTuple.setContextObject(key);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Compare columnFamily, qualifier, timestamp, and key type (everything except the row). This\n * method is used both in the normal comparator and the \"same-prefix\" comparator. Note that we\n * are assuming that row portions of both KVs have already been parsed and found identical, and\n * we don't validate that assumption here.\n *\n * @param commonPrefix the length of the common prefix of the two key-values being compared,\n * including row length and row\n */\nprivate int compareWithoutRow(int commonPrefix, byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength, short rowlength) {\n /**\n * KeyValue Format and commonLength:\n * |_keyLen_|_valLen_|_rowLen_|_rowKey_|_famiLen_|_fami_|_Quali_|....\n * ------------------|-------commonLength--------|--------------\n */\n int commonLength = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + rowlength;\n // commonLength + TIMESTAMP_TYPE_SIZE\n int commonLengthWithTSAndType = TIMESTAMP_TYPE_SIZE + commonLength;\n // ColumnFamily + Qualifier length.\n int lcolumnlength = llength - commonLengthWithTSAndType;\n int rcolumnlength = rlength - commonLengthWithTSAndType;\n byte ltype = left[loffset + (llength - 1)];\n byte rtype = right[roffset + (rlength - 1)];\n // If the column is not specified, the \"minimum\" key type appears the\n // latest in the sorted order, regardless of the timestamp. This is used\n // for specifying the last key/value in a given row, because there is no\n // \"lexicographically last column\" (it would be infinitely long). The\n // \"maximum\" key type does not need this behavior.\n if (lcolumnlength == 0 && ltype == Type.Minimum.getCode()) {\n // left is \"bigger\", i.e. it appears later in the sorted order\n return 1;\n }\n if (rcolumnlength == 0 && rtype == Type.Minimum.getCode()) {\n return -1;\n }\n int lfamilyoffset = commonLength + loffset;\n int rfamilyoffset = commonLength + roffset;\n // Column family length.\n int lfamilylength = left[lfamilyoffset - 1];\n int rfamilylength = right[rfamilyoffset - 1];\n // If left family size is not equal to right family size, we need not\n // compare the qualifiers.\n boolean sameFamilySize = (lfamilylength == rfamilylength);\n int common = 0;\n if (commonPrefix > 0) {\n common = Math.max(0, commonPrefix - commonLength);\n if (!sameFamilySize) {\n // Common should not be larger than Math.min(lfamilylength,\n // rfamilylength).\n common = Math.min(common, Math.min(lfamilylength, rfamilylength));\n } else {\n common = Math.min(common, Math.min(lcolumnlength, rcolumnlength));\n }\n }\n if (!sameFamilySize) {\n // comparing column family is enough.\n return Bytes.compareTo(left, lfamilyoffset + common, lfamilylength - common, right, rfamilyoffset + common, rfamilylength - common);\n }\n // Compare family & qualifier together.\n final int comparison = Bytes.compareTo(left, lfamilyoffset + common, lcolumnlength - common, right, rfamilyoffset + common, rcolumnlength - common);\n if (comparison != 0) {\n return comparison;\n }\n return compareTimestampAndType(left, loffset, llength, right, roffset, rlength, ltype, rtype);\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "public static AggregateCall create(SqlAggFunction aggFunction, boolean distinct, boolean approximate, boolean ignoreNulls, List rexList, List argList, int filterArg, @Nullable ImmutableBitSet distinctKeys, RelCollation collation, RelDataType type, @Nullable String name){\r\n final boolean distinct2 = distinct && (aggFunction.getDistinctOptionality() != Optionality.IGNORED);\r\n return new AggregateCall(aggFunction, distinct2, approximate, ignoreNulls, rexList, argList, filterArg, distinctKeys, collation, type, name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void transform(Column firstColumn, Column secondColumn, Column thirdColumn, ColumnBuilder builder, Type firstType, Type secondType, Type thirdType, int i) {\n String currentValue = firstType.getBinary(firstColumn, i).getStringValue(TSFileConfig.STRING_CHARSET);\n int beginPosition = secondType.getInt(secondColumn, i);\n int length = thirdType.getInt(thirdColumn, i);\n int endPosition;\n if (length < 0) {\n throw new SemanticException(\"Argument exception,the scalar function substring length must not be less than 0\");\n }\n if (beginPosition > Integer.MAX_VALUE - length) {\n endPosition = Integer.MAX_VALUE;\n } else {\n endPosition = beginPosition + length - 1;\n }\n if (beginPosition > currentValue.length()) {\n throw new SemanticException(\"Argument exception,the scalar function substring beginPosition must not be greater than the string length\");\n } else {\n int maxMin = Math.max(1, beginPosition);\n int minMax = Math.min(currentValue.length(), endPosition);\n if (maxMin > minMax) {\n currentValue = EMPTY_STRING;\n } else {\n currentValue = currentValue.substring(maxMin - 1, minMax);\n }\n }\n builder.writeBinary(BytesUtils.valueOf(currentValue));\n}", "smellKey": "S107", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public static GLAccountData importInstance(String name, Long parentId, String glCode, Boolean manualEntriesAllowed, EnumOptionData type, EnumOptionData usage, String description, CodeValueData tagId, Integer rowIndex) {\n return new GLAccountData().setName(name).setParentId(parentId).setGlCode(glCode).setManualEntriesAllowed(manualEntriesAllowed).setType(type).setUsage(usage).setDescription(description).setTagId(tagId).setRowIndex(rowIndex);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "int apply(long ulOverlayHandle, int eInputMode, int eLineInputMode, Pointer pchDescription, int unCharMax, Pointer pchExistingText, byte bUseMinimalMode, long uUserValue);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "BigDecimal calculateInterest(SavingsCompoundingInterestPeriodType compoundingInterestPeriodType, SavingsInterestCalculationType interestCalculationType, BigDecimal interestFromPreviousPostingPeriod, BigDecimal interestRateAsFraction, long daysInYear, BigDecimal minBalanceForInterestCalculation, BigDecimal overdraftInterestRateAsFraction, BigDecimal minOverdraftForInterestCalculation);", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public void uploadSubTexture(int target, Image src, int index, int targetX, int targetY, int areaX, int areaY, int areaWidth, int areaHeight, boolean linearizeSrgb) {\n if (target != GL.GL_TEXTURE_2D || src.getDepth() > 1) {\n throw new UnsupportedOperationException(\"Updating non-2D texture is not supported\");\n }\n if (src.getMipMapSizes() != null) {\n throw new UnsupportedOperationException(\"Updating mip-mapped images is not supported\");\n }\n if (src.getMultiSamples() > 1) {\n throw new UnsupportedOperationException(\"Updating multisampled images is not supported\");\n }\n Image.Format jmeFormat = src.getFormat();\n if (jmeFormat.isCompressed()) {\n throw new UnsupportedOperationException(\"Updating compressed images is not supported\");\n } else if (jmeFormat.isDepthFormat()) {\n throw new UnsupportedOperationException(\"Updating depth images is not supported\");\n }\n boolean getSrgbFormat = src.getColorSpace() == ColorSpace.sRGB && linearizeSrgb;\n GLImageFormat oglFormat = getImageFormatWithError(jmeFormat, getSrgbFormat);\n ByteBuffer data = src.getData(index);\n if (data == null) {\n throw new IndexOutOfBoundsException(\"The image index \" + index + \" is not valid for the given image\");\n }\n int Bpp = src.getFormat().getBitsPerPixel() / 8;\n int srcWidth = src.getWidth();\n int cpos = data.position();\n int skip = areaX;\n skip += areaY * srcWidth;\n skip *= Bpp;\n data.position(skip);\n boolean needsStride = srcWidth != areaWidth;\n if (needsStride && (!supportUnpackRowLength)) {\n // doesn't support stride, copy row by row (slower).\n for (int i = 0; i < areaHeight; i++) {\n data.position(skip + (srcWidth * Bpp * i));\n gl.glTexSubImage2D(target, 0, targetX, targetY + i, areaWidth, 1, oglFormat.format, oglFormat.dataType, data);\n }\n } else {\n if (needsStride)\n gl2.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, srcWidth);\n gl.glTexSubImage2D(target, 0, targetX, targetY, areaWidth, areaHeight, oglFormat.format, oglFormat.dataType, data);\n if (needsStride)\n gl2.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0);\n }\n data.position(cpos);\n}", "smellKey": "S107", "smellId": null, "repo": "hanif-ali_jmonkeyengineFall2024", "language": "java"} {"function": "private static void createUsageRecord(long zoneId, long runningTime, Date startDate, Date endDate, AccountVO account, long ipId, String ipAddress, boolean isSourceNat, boolean isSystem, boolean isHidden) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Total usage time \" + runningTime + \"ms\");\n }\n float usage = runningTime / 1000f / 60f / 60f;\n DecimalFormat dFormat = new DecimalFormat(\"#.######\");\n String usageDisplay = dFormat.format(usage);\n LOGGER.debug(\"Creating IP usage record with id [{}], usage [{}], startDate [{}], and endDate [{}], for account [{}].\", ipId, usageDisplay, DateUtil.displayDateInTimezone(UsageManagerImpl.getUsageAggregationTimeZone(), startDate), DateUtil.displayDateInTimezone(UsageManagerImpl.getUsageAggregationTimeZone(), endDate), account.getId());\n String usageDesc = \"IPAddress: \" + ipAddress;\n // Create the usage record\n UsageVO usageRecord = new UsageVO(zoneId, account.getAccountId(), account.getDomainId(), usageDesc, usageDisplay + \" Hrs\", UsageTypes.IP_ADDRESS, new Double(usage), ipId, (isSystem ? 1 : 0), (isSourceNat ? \"SourceNat\" : \"\"), startDate, endDate, isHidden);\n s_usageDao.persist(usageRecord);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "/**\n * Process cert status change request\n *

\n *\n * (Certificate Request - either an \"agent\" cert status change request, or an \"EE\" cert status change request)\n *

\n *\n * (Certificate Request Processed - either an \"agent\" cert status change request, or an \"EE\" cert status change\n * request)\n *

\n *\n *

    \n *
  • signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when a cert status change request (e. g. -\n * \"revocation\") is made (before approval process)\n *
  • signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a certificate status is\n * changed (revoked, expired, on-hold, off-hold)\n *
\n *\n * @param argSet CMS template parameters\n * @param header argument block\n * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,\n * 2 - CA key compromised; should not be used, 3 - Affiliation changed,\n * 4 - Certificate superceded, 5 - Cessation of operation, or\n * 6 - Certificate is on hold)\n * @param invalidityDate certificate validity date\n * @param initiative string containing the audit format\n * @param req HTTP servlet request\n * @param resp HTTP servlet response\n * @param verifiedRecordCount number of verified records\n * @param revokeAll string containing information on all of the\n * certificates to be revoked\n * @param totalRecordCount total number of records (verified and unverified)\n * @param eeSerialNumber BigInteger containing the end-entity certificate\n * serial number\n * @param eeSubjectDN string containing the end-entity certificate subject\n * distinguished name (DN)\n * @param comments string containing certificate comments\n * @param locale the system locale\n * @exception EBaseException an error has occurred\n */\nprivate void process(CMSTemplateParams argSet, ArgBlock header, int reason, Date invalidityDate, String initiative, HttpServletRequest req, HttpServletResponse resp, int verifiedRecordCount, String revokeAll, int totalRecordCount, BigInteger eeSerialNumber, String eeSubjectDN, String comments, Locale locale) throws EBaseException {\n logger.debug(\"DoRevoke: eeSerialNumber: \" + eeSerialNumber);\n long startTime = new Date().getTime();\n CAEngine engine = CAEngine.getInstance();\n RevocationProcessor processor = new RevocationProcessor(servletConfig.getServletName(), getLocale(req));\n processor.setCMSEngine(engine);\n processor.init();\n processor.setStartTime(startTime);\n processor.setInitiative(initiative);\n processor.setSerialNumber(eeSerialNumber == null ? null : new CertId(eeSerialNumber));\n RevocationReason revReason = RevocationReason.valueOf(reason);\n processor.setRevocationReason(revReason);\n processor.setRequestType(processor.getRevocationReason() == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE);\n processor.setInvalidityDate(invalidityDate);\n processor.setComments(comments);\n Hashtable nonceMap = new Hashtable<>();\n X509Certificate clientCert = getSSLClientCertificate(req);\n processor.setAuthority(engine.getCA());\n if (engine.getEnableNonces()) {\n String nonces = req.getParameter(\"nonce\");\n if (nonces == null) {\n throw new ForbiddenException(\"Missing nonce.\");\n }\n // parse serial numbers and nonces\n for (String s : nonces.split(\",\")) {\n String[] elements = s.split(\":\");\n BigInteger serialNumber = new BigInteger(elements[0].trim());\n Long nonce = Long.valueOf(elements[1].trim());\n nonceMap.put(serialNumber, nonce);\n }\n }\n try {\n processor.createCRLExtension();\n Enumeration e = mCertDB.searchCertificates(revokeAll, totalRecordCount, mTimeLimits);\n while (e != null && e.hasMoreElements()) {\n CertRecord targetRecord = e.nextElement();\n X509CertImpl targetCert = targetRecord.getCertificate();\n // Verify end-entity cert is not revoked.\n // TODO: This should be checked during authentication.\n if (eeSerialNumber != null && eeSerialNumber.equals(targetCert.getSerialNumber()) && targetRecord.getStatus().equals(CertRecord.STATUS_REVOKED)) {\n String message = CMS.getLogMessage(\"CA_CERTIFICATE_ALREADY_REVOKED_1\", targetRecord.getSerialNumber().toString(16));\n logger.error(message);\n throw new ECMSGWException(CMS.getLogMessage(\"CMSGW_UNAUTHORIZED\"));\n }\n ArgBlock rarg = new ArgBlock();\n rarg.addStringValue(\"serialNumber\", targetCert.getSerialNumber().toString(16));\n try {\n if (engine.getEnableNonces() && !processor.isMemberOfSubsystemGroup(clientCert)) {\n // validate nonce for each certificate\n Long nonce = nonceMap.get(targetRecord.getSerialNumber());\n processor.validateNonce(req, \"cert-revoke\", targetRecord.getSerialNumber(), nonce);\n }\n processor.validateCertificateToRevoke(eeSubjectDN, targetRecord, false);\n processor.addCertificateToRevoke(targetCert);\n rarg.addStringValue(\"error\", null);\n } catch (PKIException ex) {\n rarg.addStringValue(\"error\", ex.getMessage());\n }\n argSet.addRepeatRecord(rarg);\n }\n int count = processor.getCertificates().size();\n if (count == 0) {\n logger.warn(\"Unable to pre-process revocation request: certificate not found\");\n throw new ECMSGWException(CMS.getLogMessage(\"CMSGW_REVOCATION_ERROR_CERT_NOT_FOUND\"));\n }\n header.addIntegerValue(\"totalRecordCount\", count);\n processor.createRevocationRequest();\n processor.auditChangeRequest(ILogger.SUCCESS);\n } catch (ForbiddenException e) {\n logger.warn(\"Unable to pre-process revocation request: \" + e.getMessage());\n throw new EAuthzException(CMS.getUserMessage(locale, \"CMS_AUTHORIZATION_ERROR\"));\n } catch (EBaseException e) {\n logger.error(\"Unable to pre-process revocation request: \" + e.getMessage(), e);\n processor.auditChangeRequest(ILogger.FAILURE);\n throw e;\n } catch (IOException e) {\n logger.error(\"Unable to pre-process revocation request: \" + e.getMessage(), e);\n processor.auditChangeRequest(ILogger.FAILURE);\n throw new ECMSGWException(CMS.getLogMessage(\"CMSGW_ERROR_MARKING_CERT_REVOKED\"));\n }\n // change audit processing from \"REQUEST\" to \"REQUEST_PROCESSED\"\n // to distinguish which type of signed audit log message to save\n // as a failure outcome in case an exception occurs\n try {\n processor.processRevocationRequest();\n Request revReq = processor.getRequest();\n // retrieve the request status\n RequestStatus status = revReq.getRequestStatus();\n processor.setRequestStatus(status);\n String type = revReq.getRequestType();\n // The SVC_PENDING check has been added for the Cloned CA request\n // that is meant for the Master CA. From Clone's point of view\n // the request is complete\n if (status == RequestStatus.COMPLETE || status == RequestStatus.SVC_PENDING && type.equals(Request.CLA_CERT4CRL_REQUEST)) {\n header.addStringValue(\"revoked\", \"yes\");\n Integer updateCRLResult = revReq.getExtDataInInteger(Request.CRL_UPDATE_STATUS);\n if (updateCRLResult != null) {\n header.addStringValue(\"updateCRL\", \"yes\");\n if (updateCRLResult.equals(Request.RES_SUCCESS)) {\n header.addStringValue(\"updateCRLSuccess\", \"yes\");\n } else {\n header.addStringValue(\"updateCRLSuccess\", \"no\");\n String crlError = revReq.getExtDataInString(Request.CRL_UPDATE_ERROR);\n if (crlError != null)\n header.addStringValue(\"updateCRLError\", crlError);\n }\n // let known crl publishing status too.\n Integer publishCRLResult = revReq.getExtDataInInteger(Request.CRL_PUBLISH_STATUS);\n if (publishCRLResult != null) {\n if (publishCRLResult.equals(Request.RES_SUCCESS)) {\n header.addStringValue(\"publishCRLSuccess\", \"yes\");\n } else {\n header.addStringValue(\"publishCRLSuccess\", \"no\");\n String publError = revReq.getExtDataInString(Request.CRL_PUBLISH_ERROR);\n if (publError != null)\n header.addStringValue(\"publishCRLError\", publError);\n }\n }\n }\n // let known update and publish status of all crls.\n for (CRLIssuingPoint crl : engine.getCRLIssuingPoints()) {\n String crlId = crl.getId();\n if (crlId.equals(CertificateAuthority.PROP_MASTER_CRL))\n continue;\n String updateStatusStr = crl.getCrlUpdateStatusStr();\n Integer updateResult = revReq.getExtDataInInteger(updateStatusStr);\n if (updateResult != null) {\n if (updateResult.equals(Request.RES_SUCCESS)) {\n logger.debug(\"DoRevoke: \" + CMS.getLogMessage(\"ADMIN_SRVLT_ADDING_HEADER\", updateStatusStr));\n header.addStringValue(updateStatusStr, \"yes\");\n } else {\n String updateErrorStr = crl.getCrlUpdateErrorStr();\n logger.debug(\"DoRevoke: \" + CMS.getLogMessage(\"ADMIN_SRVLT_ADDING_HEADER_NO\", updateStatusStr));\n header.addStringValue(updateStatusStr, \"no\");\n String error = revReq.getExtDataInString(updateErrorStr);\n if (error != null)\n header.addStringValue(updateErrorStr, error);\n }\n String publishStatusStr = crl.getCrlPublishStatusStr();\n Integer publishResult = revReq.getExtDataInInteger(publishStatusStr);\n if (publishResult == null)\n continue;\n if (publishResult.equals(Request.RES_SUCCESS)) {\n header.addStringValue(publishStatusStr, \"yes\");\n } else {\n String publishErrorStr = crl.getCrlPublishErrorStr();\n header.addStringValue(publishStatusStr, \"no\");\n String error = revReq.getExtDataInString(publishErrorStr);\n if (error != null)\n header.addStringValue(publishErrorStr, error);\n }\n }\n }\n if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {\n header.addStringValue(\"dirEnabled\", \"yes\");\n Integer[] ldapPublishStatus = revReq.getExtDataInIntegerArray(\"ldapPublishStatus\");\n int certsToUpdate = 0;\n int certsUpdated = 0;\n if (ldapPublishStatus != null) {\n certsToUpdate = ldapPublishStatus.length;\n for (int i = 0; i < certsToUpdate; i++) {\n if (ldapPublishStatus[i] == Request.RES_SUCCESS) {\n certsUpdated++;\n }\n }\n }\n header.addIntegerValue(\"certsUpdated\", certsUpdated);\n header.addIntegerValue(\"certsToUpdate\", certsToUpdate);\n // add crl publishing status.\n String publError = revReq.getExtDataInString(Request.CRL_PUBLISH_ERROR);\n if (publError != null) {\n header.addStringValue(\"crlPublishError\", publError);\n }\n } else {\n header.addStringValue(\"dirEnabled\", \"no\");\n }\n header.addStringValue(\"error\", null);\n } else {\n if (status == RequestStatus.PENDING || status == RequestStatus.REJECTED) {\n header.addStringValue(\"revoked\", status.toString());\n } else {\n header.addStringValue(\"revoked\", \"no\");\n }\n Vector errors = revReq.getExtDataInStringVector(Request.ERRORS);\n if (errors != null) {\n StringBuilder errInfo = new StringBuilder();\n for (int i = 0; i < errors.size(); i++) {\n errInfo.append(errors.elementAt(i));\n errInfo.append(\"\\n\");\n }\n header.addStringValue(\"error\", errInfo.toString());\n } else if (status == RequestStatus.PENDING) {\n header.addStringValue(\"error\", \"Request Pending\");\n } else {\n header.addStringValue(\"error\", null);\n }\n }\n processor.auditChangeRequestProcessed(ILogger.SUCCESS);\n } catch (EBaseException e) {\n logger.error(\"Unable to revoke certificate: \" + e.getMessage(), e);\n processor.auditChangeRequestProcessed(ILogger.FAILURE);\n throw e;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "/**\n * Get ID from column value for a table with a parent id reference.\n *\n * @param tableName\n * @param name\n * @param tableNameMaster\n * @param masterID\n * @param trxName\n */\npublic static Object findIdByColumnAndParentId(String tableName, String columnName, String name, String tableNameMaster, Object masterID, int AD_Client_ID, boolean ignoreCase, String trxName) {\n //check cache\n String key = tableName + \".\" + columnName + \"=\" + name + tableNameMaster + \"=\" + masterID;\n if (idCache.containsKey(key))\n return idCache.get(key);\n Object id = null;\n MTable table = MTable.get(Env.getCtx(), tableName, trxName);\n String keycol;\n if (table.isUUIDKeyTable())\n keycol = PO.getUUIDColumnName(tableName);\n else\n keycol = tableName + \"_ID\";\n MTable tableMaster = MTable.get(Env.getCtx(), tableNameMaster, trxName);\n String keycolMaster;\n if (tableMaster.isUUIDKeyTable())\n keycolMaster = PO.getUUIDColumnName(tableNameMaster);\n else\n keycolMaster = tableNameMaster + \"_ID\";\n StringBuilder sqlB = new StringBuilder(\"SELECT \").append(keycol).append(\" FROM \").append(tableName).append(\" WHERE \");\n if (ignoreCase) {\n sqlB.append(\"UPPER(\").append(columnName).append(\") = ? AND \");\n } else {\n sqlB.append(columnName).append(\" = ? AND \");\n }\n sqlB.append(keycolMaster + \" = ? AND AD_Client_ID IN (0, ?) \").append(\"ORDER BY AD_Client_ID Desc \");\n if (log.isLoggable(Level.INFO))\n log.info(sqlB.toString());\n PreparedStatement pstmt = null;\n ResultSet rs = null;\n try {\n pstmt = DB.prepareStatement(sqlB.toString(), trxName);\n if (ignoreCase) {\n pstmt.setString(1, name.toUpperCase());\n } else {\n pstmt.setString(1, name);\n }\n if (tableMaster.isUUIDKeyTable())\n pstmt.setString(2, (String) masterID);\n else\n pstmt.setInt(2, ((Number) masterID).intValue());\n pstmt.setInt(3, AD_Client_ID);\n rs = pstmt.executeQuery();\n if (rs.next()) {\n id = rs.getObject(1);\n }\n } catch (Exception e) {\n throw new DatabaseAccessException(e);\n } finally {\n DB.close(rs, pstmt);\n }\n //update cache\n if (id != null)\n idCache.put(key, id);\n return id;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public boolean checkOrWaitForTheFile(FileSystem srcFs, Path src, Path dest, Configuration conf, Object notifier, int waitAttempts, long sleepInterval, boolean doLog) throws IOException {\n for (int i = 0; i < waitAttempts; i++) {\n if (checkPreExisting(srcFs, src, dest, conf)) {\n return true;\n }\n if (doLog && i == 0) {\n LOG.info(\"Waiting for the file \" + dest + \" (\" + waitAttempts + \" attempts, with \" + sleepInterval + \"ms interval)\");\n }\n try {\n if (notifier != null) {\n // The writing thread has given us an object to wait on.\n synchronized (notifier) {\n notifier.wait(sleepInterval);\n }\n } else {\n // Some other process is probably writing the file. Just sleep.\n Thread.sleep(sleepInterval);\n }\n } catch (InterruptedException interruptedException) {\n throw new IOException(interruptedException);\n }\n }\n // One last check.\n return checkPreExisting(srcFs, src, dest, conf);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "PublicIp assignSourceNatPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem, boolean forSystemVms) throws InsufficientAddressCapacityException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static Query7Def query(String pkg, String name, Class type1, String arg1name, Class type2, String arg2name, Class type3, String arg3name, Class type4, String arg4name, Class type5, String arg5name, Class type6, String arg6name, Class type7, String arg7name){\r\n return new Query7DefImpl<>(VIEW_BUILDER, pkg, name, type1, arg1name, type2, arg2name, type3, arg3name, type4, arg4name, type5, arg5name, type6, arg6name, type7, arg7name);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Add default properties for table property. If a default parameter exists\n * in the tblProp, the value in tblProp will be kept.\n *\n * @param tblProp\n * property map\n * @return Modified table property map\n */\nprivate Map validateAndAddDefaultProperties(Map tblProp, boolean isExt, StorageFormat storageFormat, String qualifiedTableName, List sortCols, boolean isMaterialization, boolean isTemporaryTable, boolean isTransactional, boolean isManaged, String[] qualifiedTabName, boolean isTableTypeChanged) throws SemanticException {\n Map retValue = Optional.ofNullable(tblProp).orElseGet(HashMap::new);\n String paraString = HiveConf.getVar(conf, ConfVars.NEW_TABLE_DEFAULT_PARA);\n if (paraString != null && !paraString.isEmpty()) {\n for (String keyValuePair : paraString.split(\",\")) {\n String[] keyValue = keyValuePair.split(\"=\", 2);\n if (keyValue.length != 2) {\n continue;\n }\n if (!retValue.containsKey(keyValue[0])) {\n retValue.put(keyValue[0], keyValue[1]);\n }\n }\n }\n if (!retValue.containsKey(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL) && retValue.containsKey(hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES)) {\n throw new SemanticException(\"Cannot specify \" + hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES + \" without \" + hive_metastoreConstants.TABLE_IS_TRANSACTIONAL);\n }\n isExt = isExternalTableChanged(retValue, isTransactional, isExt, isTableTypeChanged);\n if (isExt && HiveConf.getBoolVar(conf, ConfVars.HIVE_EXTERNALTABLE_PURGE_DEFAULT)) {\n if (retValue.get(MetaStoreUtils.EXTERNAL_TABLE_PURGE) == null) {\n retValue.put(MetaStoreUtils.EXTERNAL_TABLE_PURGE, \"true\");\n }\n }\n boolean makeInsertOnly = !isTemporaryTable && HiveConf.getBoolVar(conf, ConfVars.HIVE_CREATE_TABLES_AS_INSERT_ONLY);\n boolean makeAcid = !isTemporaryTable && makeAcid();\n // if not specify managed table and create.table.as.external is true\n // ignore makeInsertOnly and makeAcid.\n if (!isManaged && HiveConf.getBoolVar(conf, ConfVars.CREATE_TABLE_AS_EXTERNAL)) {\n makeInsertOnly = false;\n makeAcid = false;\n }\n if ((makeInsertOnly || makeAcid || isTransactional || isManaged) && !isExt && !isMaterialization && StringUtils.isBlank(storageFormat.getStorageHandler()) && //don't overwrite user choice if transactional attribute is explicitly set\n !retValue.containsKey(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL)) {\n if (makeInsertOnly || isTransactional) {\n retValue.put(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL, \"true\");\n retValue.put(hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES, TransactionalValidationListener.INSERTONLY_TRANSACTIONAL_PROPERTY);\n }\n if (makeAcid || isTransactional || (isManaged && !makeInsertOnly)) {\n retValue = convertToAcidByDefault(storageFormat, qualifiedTableName, sortCols, retValue);\n }\n }\n if (!isExt) {\n addDbAndTabToOutputs(qualifiedTabName, TableType.MANAGED_TABLE, isTemporaryTable, retValue, storageFormat);\n } else {\n addDbAndTabToOutputs(qualifiedTabName, TableType.EXTERNAL_TABLE, isTemporaryTable, retValue, storageFormat);\n }\n if (isIcebergTable(retValue)) {\n SessionStateUtil.addResourceOrThrow(conf, SessionStateUtil.DEFAULT_TABLE_LOCATION, getDefaultLocation(qualifiedTabName[0], qualifiedTabName[1], true));\n }\n return retValue;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "abstract void showDataConnectorDescription(DataOutputStream out, String connector, String type, String url, String ownerName, PrincipalType ownerType, String comment, Map params) throws HiveException;", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static MTreeBelowSGCachedImpl loadFromSnapshot(File snapshotDir, String storageGroupFullPath, int schemaRegionId, CachedSchemaRegionStatistics regionStatistics, Consumer> measurementProcess, Consumer> deviceProcess, Function, Map> tagGetter, Runnable flushCallback) throws IOException, MetadataException{\r\n return new MTreeBelowSGCachedImpl(new PartialPath(storageGroupFullPath), CachedMTreeStore.loadFromSnapshot(snapshotDir, storageGroupFullPath, schemaRegionId, regionStatistics, flushCallback), measurementProcess, deviceProcess, tagGetter, regionStatistics);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Choose target datanodes for creating a new block.\n *\n * @throws IOException\n * if the number of targets {@literal <} minimum replication.\n * @see BlockPlacementPolicy#chooseTarget(String, int, Node,\n * Set, long, List, BlockStoragePolicy, EnumSet)\n */\npublic DatanodeStorageInfo[] chooseTarget4NewBlock(final String src, final int numOfReplicas, final Node client, final Set excludedNodes, final long blocksize, final List favoredNodes, final byte storagePolicyID, final BlockType blockType, final ErasureCodingPolicy ecPolicy, final EnumSet flags) throws IOException {\n List favoredDatanodeDescriptors = getDatanodeDescriptors(favoredNodes);\n final BlockStoragePolicy storagePolicy = storagePolicySuite.getPolicy(storagePolicyID);\n final BlockPlacementPolicy blockplacement = placementPolicies.getPolicy(blockType);\n final DatanodeStorageInfo[] targets = blockplacement.chooseTarget(src, numOfReplicas, client, excludedNodes, blocksize, favoredDatanodeDescriptors, storagePolicy, flags);\n final String errorMessage = \"File %s could only be written to %d of \" + \"the %d %s. There are %d datanode(s) running and %s \" + \"node(s) are excluded in this operation.\";\n if (blockType == BlockType.CONTIGUOUS && targets.length < minReplication) {\n throw new IOException(String.format(errorMessage, src, targets.length, minReplication, \"minReplication nodes\", getDatanodeManager().getNetworkTopology().getNumOfLeaves(), (excludedNodes == null ? \"no\" : excludedNodes.size())));\n } else if (blockType == BlockType.STRIPED && targets.length < ecPolicy.getNumDataUnits()) {\n throw new IOException(String.format(errorMessage, src, targets.length, ecPolicy.getNumDataUnits(), String.format(\"required nodes for %s\", ecPolicy.getName()), getDatanodeManager().getNetworkTopology().getNumOfLeaves(), (excludedNodes == null ? \"no\" : excludedNodes.size())));\n }\n return targets;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static Task loadTable(URI fromURI, ImportTableDesc tblDesc, boolean replace, Path tgtPath, ReplicationSpec replicationSpec, EximUtil.SemanticAnalyzerWrapperContext x, Long writeId, int stmtId, String dumpRoot, ReplicationMetricCollector metricCollector) throws HiveException {\n Path dataPath = new Path(fromURI.toString(), EximUtil.DATA_PATH_NAME);\n DeferredWorkContext resolver = new DeferredWorkContext(replace, tgtPath, writeId, stmtId, x.getHive(), x.getCtx(), tblDesc, replicationSpec.isInReplicationScope());\n Task copyTask;\n // Corresponding work instances are not complete yet. Some of the values will be calculated and assigned when task\n // is being executed.\n if (replicationSpec.isInReplicationScope()) {\n boolean copyAtLoad = x.getConf().getBoolVar(HiveConf.ConfVars.REPL_RUN_DATA_COPY_TASKS_ON_TARGET);\n copyTask = ReplCopyTask.getLoadCopyTask(replicationSpec, dataPath, null, x.getConf(), false, false, copyAtLoad, dumpRoot, metricCollector);\n } else {\n copyTask = TaskFactory.get(new CopyWork(dataPath, null, false, dumpRoot, metricCollector, true));\n }\n copyTask.setDeferredWorkContext(resolver);\n MoveWork moveWork = new MoveWork(x.getInputs(), x.getOutputs(), null, null, false, dumpRoot, metricCollector, true);\n //if Importing into existing table, FileFormat is checked by\n // ImportSemanticAnalyzer.checked checkTable()\n Task loadTableTask = TaskFactory.get(moveWork, x.getConf());\n loadTableTask.setDeferredWorkContext(resolver);\n copyTask.addDependentTask(loadTableTask);\n x.getTasks().add(copyTask);\n return loadTableTask;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private UserVmVO commitUserVm(final DataCenter zone, final VirtualMachineTemplate template, final String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final String userData, Long userDataId, String userDataDetails, final Account caller, final Boolean isDisplayVm, final String keyboard, final long accountId, final long userId, final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKeys, final LinkedHashMap> networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, final Map customParameters, final Map> extraDhcpOptionMap, final Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFPropertiesMap, final boolean dynamicScalingEnabled, String vmType, final Long rootDiskOfferingId, String sshkeypairs) throws InsufficientCapacityException {\n return commitUserVm(false, zone, null, null, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, userDataId, userDataDetails, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKeys, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, extraDhcpOptionMap, dataDiskTemplateToDiskOfferingMap, userVmOVFPropertiesMap, null, dynamicScalingEnabled, vmType, rootDiskOfferingId, sshkeypairs);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "protected Query getQuery(final String entityKey, final AuditElements.EventCategoryType type, final String category, final String subcategory, final List events, final AuditElements.Result result, final OffsetDateTime before, final OffsetDateTime after){\r\n List queries = new ArrayList<>();\r\n if (entityKey != null) {\r\n queries.add(new Query.Builder().multiMatch(QueryBuilders.multiMatch().fields(\"message.before\", \"message.inputs\", \"message.output\", \"message.throwable\").type(TextQueryType.Phrase).query(entityKey).build()).build());\r\n }\r\n if (type != null) {\r\n queries.add(new Query.Builder().term(QueryBuilders.term().field(\"message.logger.type\").value(type.name()).build()).build());\r\n }\r\n if (StringUtils.isNotBlank(category)) {\r\n queries.add(new Query.Builder().term(QueryBuilders.term().field(\"message.logger.category\").value(category).build()).build());\r\n }\r\n if (StringUtils.isNotBlank(subcategory)) {\r\n queries.add(new Query.Builder().term(QueryBuilders.term().field(\"message.logger.subcategory\").value(subcategory).build()).build());\r\n }\r\n List eventQueries = events.stream().map(event -> new Query.Builder().term(QueryBuilders.term().field(\"message.logger.event\").value(event).build()).build()).collect(Collectors.toList());\r\n if (!eventQueries.isEmpty()) {\r\n queries.add(new Query.Builder().disMax(QueryBuilders.disMax().queries(eventQueries).build()).build());\r\n }\r\n if (result != null) {\r\n queries.add(new Query.Builder().term(QueryBuilders.term().field(\"message.logger.result\").value(result.name()).build()).build());\r\n }\r\n if (before != null) {\r\n queries.add(new Query.Builder().range(QueryBuilders.range().field(\"instant\").lte(JsonData.of(before.toInstant().toEpochMilli())).build()).build());\r\n }\r\n if (after != null) {\r\n queries.add(new Query.Builder().range(QueryBuilders.range().field(\"instant\").gte(JsonData.of(after.toInstant().toEpochMilli())).build()).build());\r\n }\r\n return new Query.Builder().bool(QueryBuilders.bool().must(queries).build()).build();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets a list of documents that match given search request that is related to the input entity\n *\n * @param sourceUrn Urn of the source entity\n * @param direction Direction of the relationship\n * @param entities list of entities to search (If empty, searches across all entities)\n * @param input the search input text\n * @param maxHops the max number of hops away to search for. If null, searches all hops.\n * @param filter the request map with fields and values as filters to be applied to search hits\n * @param sortCriteria list of {@link SortCriterion} to be applied to search results\n * @param start index to start the search from\n * @param count the number of search hits to return\n * @return a {@link SearchResult} that contains a list of matched documents and related search\n * result metadata\n */\nLineageSearchResult searchAcrossLineage(@Nonnull OperationContext opContext, @Nonnull Urn sourceUrn, @Nonnull LineageDirection direction, @Nonnull List entities, @Nonnull String input, @Nullable Integer maxHops, @Nullable Filter filter, List sortCriteria, int start, int count) throws RemoteInvocationException;", "smellKey": "S107", "smellId": null, "repo": "patotskiy_datahub", "language": "java"} {"function": "public static List search(final String key, final int page, final int size, final AuditElements.EventCategoryType type, final String category, final List events, final AuditElements.Result result, final SortParam sort){\r\n AuditQuery query = new AuditQuery.Builder().entityKey(key).size(size).page(page).type(type).category(category).events(events).result(result).orderBy(toOrderBy(sort)).build();\r\n return getService(AuditService.class).search(query).getResult();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4){\r\n Map m = new HashMap<>();\r\n m.put(k1, v1);\r\n m.put(k2, v2);\r\n m.put(k3, v3);\r\n m.put(k4, v4);\r\n return m;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Money updateCompoundingDetailsForPartialScheduleGeneration(final LoanRepaymentScheduleInstallment installment, LoanApplicationTerms loanApplicationTerms, Map principalMap, final Map> compoundingDateVariations, final Money uncompoundedAmount, final Collection applicableTransactions, LocalDate lastRestDate, HolidayDetailDTO holidayDetailDTO) {\n Money uncompounded = uncompoundedAmount;\n MonetaryCurrency currency = uncompoundedAmount.getCurrency();\n for (RecalculationDetail detail : applicableTransactions) {\n LocalDate applicableDate = getNextRestScheduleDate(detail.getTransactionDate().minusDays(1), loanApplicationTerms, holidayDetailDTO);\n adjustCompoundedAmountWithPaidDetail(principalMap, lastRestDate, applicableDate, detail.getTransaction(), loanApplicationTerms, currency);\n }\n Money amountCharged = getIncomeForCompounding(loanApplicationTerms, currency, installment);\n final Set details = installment.getLoanCompoundingDetails();\n Money totalCompounded = Money.zero(currency);\n Map compoundingMap = new TreeMap<>();\n for (LoanInterestRecalcualtionAdditionalDetails additionalDetails : details) {\n LocalDate effectiveDate = additionalDetails.getEffectiveDate();\n if (loanApplicationTerms.allowCompoundingOnEod()) {\n effectiveDate = effectiveDate.plusDays(1);\n }\n compoundingMap.put(effectiveDate, Money.of(currency, additionalDetails.getAmount()));\n totalCompounded = totalCompounded.plus(additionalDetails.getAmount());\n updateMapWithAmount(principalMap, Money.of(currency, additionalDetails.getAmount()).negated(), effectiveDate);\n }\n compoundingDateVariations.put(installment.getFromDate(), compoundingMap);\n if (totalCompounded.isGreaterThanZero()) {\n final boolean isPastDate = DateUtils.isBeforeBusinessDate(installment.getDueDate());\n final LocalDate restDate = getNextRestScheduleDate(installment.getDueDate().minusDays(1), loanApplicationTerms, holidayDetailDTO);\n if (isPastDate) {\n updateMapWithAmount(principalMap, totalCompounded, lastRestDate);\n } else {\n updateMapWithAmount(principalMap, totalCompounded, restDate);\n }\n uncompounded = amountCharged.plus(uncompounded).minus(totalCompounded);\n } else {\n uncompounded = uncompounded.plus(amountCharged);\n }\n return uncompounded;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n *

\n * Moves a file from one {@link Path} to another. If {@code isRenameAllowed} is true then the\n * {@link FileSystem#rename(Path, Path)} method is used to move the file. If its false then the data is copied, if\n * {@code isSrcLocal} is true then the {@link FileSystem#copyFromLocalFile(Path, Path)} method is used, else\n * {@link FileUtils#copy(FileSystem, Path, FileSystem, Path, boolean, boolean, HiveConf)} is used.\n *

\n *\n *

\n * If the destination file already exists, then {@code _copy_[counter]} is appended to the file name, where counter\n * is an integer starting from 1.\n *

\n *\n * @param conf the {@link HiveConf} to use if copying data\n * @param sourceFs the {@link FileSystem} where the source file exists\n * @param sourcePath the {@link Path} to move\n * @param destFs the {@link FileSystem} to move the file to\n * @param destDirPath the {@link Path} to move the file to\n * @param isSrcLocal if the source file is on the local filesystem\n * @param isOverwrite if true, then overwrite destination file if exist else make a duplicate copy\n * @param isRenameAllowed true if the data should be renamed and not copied, false otherwise\n *\n * @return the {@link Path} the source file was moved to\n *\n * @throws IOException if there was an issue moving the file\n */\nprivate static Path mvFile(HiveConf conf, FileSystem sourceFs, Path sourcePath, FileSystem destFs, Path destDirPath, boolean isSrcLocal, boolean isOverwrite, boolean isRenameAllowed, int taskId) throws IOException {\n // Strip off the file type, if any so we don't make:\n // 000000_0.gz -> 000000_0.gz_copy_1\n final String fullname = sourcePath.getName();\n final String name;\n if (taskId == -1) {\n // non-acid\n name = FilenameUtils.getBaseName(sourcePath.getName());\n } else {\n // acid\n name = getPathName(taskId);\n }\n final String type = FilenameUtils.getExtension(sourcePath.getName());\n // Incase of ACID, the file is ORC so the extension is not relevant and should not be inherited.\n Path destFilePath = new Path(destDirPath, taskId == -1 ? fullname : name);\n /*\n * The below loop may perform bad when the destination file already exists and it has too many _copy_\n * files as well. A desired approach was to call listFiles() and get a complete list of files from\n * the destination, and check whether the file exists or not on that list. However, millions of files\n * could live on the destination directory, and on concurrent situations, this can cause OOM problems.\n *\n * I'll leave the below loop for now until a better approach is found.\n */\n for (int counter = 1; destFs.exists(destFilePath); counter++) {\n if (isOverwrite) {\n destFs.delete(destFilePath, false);\n break;\n }\n destFilePath = new Path(destDirPath, name + (Utilities.COPY_KEYWORD + counter) + ((taskId == -1 && !type.isEmpty()) ? \".\" + type : \"\"));\n }\n if (isRenameAllowed) {\n destFs.rename(sourcePath, destFilePath);\n } else if (isSrcLocal) {\n destFs.copyFromLocalFile(sourcePath, destFilePath);\n } else {\n if (!FileUtils.copy(sourceFs, sourcePath, destFs, destFilePath, // delete source\n false, // overwrite destination\n false, conf, new DataCopyStatistics())) {\n LOG.error(\"Copy failed for source: \" + sourcePath + \" to destination: \" + destFilePath);\n throw new IOException(\"File copy failed.\");\n }\n // Source file delete may fail because of permission issue as executing user might not\n // have permission to delete the files in the source path. Ignore this failure.\n try {\n if (!sourceFs.delete(sourcePath, true)) {\n LOG.warn(\"Delete source failed for source: \" + sourcePath + \" during copy to destination: \" + destFilePath);\n }\n } catch (Exception e) {\n LOG.warn(\"Delete source failed for source: \" + sourcePath + \" during copy to destination: \" + destFilePath, e);\n }\n }\n return destFilePath;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private static void executeCheckSig(ScriptExecutionState state, Tx txContainingThis, int index, ScriptStream script, ScriptStack stack, int lastCodeSepLocation, int opcode, Coin value, Set verifyFlags, boolean allowFakeChecksig) throws ScriptExecutionException{\r\n final boolean requireCanonical = !allowFakeChecksig && (verifyFlags.contains(ScriptVerifyFlag.STRICTENC) || verifyFlags.contains(ScriptVerifyFlag.DERSIG) || verifyFlags.contains(ScriptVerifyFlag.LOW_S));\r\n if (stack.size() < 2)\r\n throw new ScriptExecutionException(state, \"Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2\");\r\n StackItem pubKey = stack.pollLast();\r\n StackItem sigBytes = stack.pollLast();\r\n boolean sigValid = false;\r\n byte[] connectedScript = script.getProgramFrom(script.getLastCodeSepIndex());\r\n UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length() + 1);\r\n try {\r\n ScriptChunk.writeBytes(outStream, sigBytes.bytes());\r\n } catch (IOException e) {\r\n throw new RuntimeException(e);\r\n }\r\n connectedScript = SigHash.removeAllInstancesOf(connectedScript, outStream.toByteArray());\r\n try {\r\n TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes.bytes(), requireCanonical, verifyFlags.contains(ScriptVerifyFlag.LOW_S));\r\n Sha256Hash hash = sig.useForkId() ? SigHash.hashForForkIdSignature(txContainingThis, index, connectedScript, value, sig.sigHashMode(), sig.anyoneCanPay()) : SigHash.hashForLegacySignature(txContainingThis, index, connectedScript, (byte) sig.sighashFlags);\r\n sigValid = allowFakeChecksig ? true : ECDSA.verify(hash.getBytes(), sig, pubKey.bytes());\r\n } catch (Exception e1) {\r\n if (!e1.getMessage().contains(\"Reached past end of ASN.1 stream\"))\r\n log.warn(\"Signature checking failed!\", e1);\r\n }\r\n if (opcode == OP_CHECKSIG)\r\n stack.add(Type.BOOL, sigValid ? new byte[] { 1 } : new byte[] {}, pubKey, sigBytes);\r\n else if (opcode == OP_CHECKSIGVERIFY)\r\n if (!sigValid)\r\n throw new ScriptExecutionException(state, \"Script failed OP_CHECKSIGVERIFY\");\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "String buildUrl(String action, HttpServletRequest request, HttpServletResponse response, Map params, String scheme, boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort);", "smellKey": "S107", "smellId": null, "repo": "apache_struts", "language": "java"} {"function": "/**\n * Internal routine for putAll(..)\n *\n * @param cacheCtx Cache context.\n * @param keys Keys to enlist.\n * @param expiryPlc Explicitly specified expiry policy for entry.\n * @param lookup Value lookup map ({@code null} for remove).\n * @param invokeMap Map with entry processors for invoke operation.\n * @param invokeArgs Optional arguments for EntryProcessor.\n * @param retval Flag indicating whether a value should be returned.\n * @param filter User filters.\n * @param ret Return value.\n * @param enlisted Collection of keys enlisted into this transaction.\n * @param drPutMap DR put map (optional).\n * @param drRmvMap DR remove map (optional).\n * @param skipStore Skip store flag.\n * @param singleRmv {@code True} for single key remove operation ({@link Cache#remove(Object)}.\n * @param keepBinary Keep binary flag.\n * @param recovery Recovery flag.\n * @param dataCenterId Optional data center ID.\n * @return Future for enlisting writes.\n */\nprivate IgniteInternalFuture enlistWrite(final GridCacheContext cacheCtx, @Nullable AffinityTopologyVersion entryTopVer, Collection keys, @Nullable ExpiryPolicy expiryPlc, @Nullable Map lookup, @Nullable Map> invokeMap, @Nullable Object[] invokeArgs, final boolean retval, final CacheEntryPredicate[] filter, final GridCacheReturn ret, Collection enlisted, @Nullable Map drPutMap, @Nullable Map drRmvMap, boolean skipStore, final boolean singleRmv, final boolean keepBinary, final boolean recovery, Byte dataCenterId) {\n assert retval || invokeMap == null;\n try (TraceSurroundings ignored2 = MTC.support(context().kernalContext().tracing().create(TX_NEAR_ENLIST_WRITE, MTC.span()))) {\n GridFutureAdapter enlistFut = new GridFutureAdapter<>();\n if (!updateLockFuture(null, enlistFut))\n return finishFuture(enlistFut, timedOut() ? timeoutException() : rollbackException(), false);\n try {\n addActiveCache(cacheCtx, recovery);\n } catch (IgniteCheckedException e) {\n return finishFuture(enlistFut, e, false);\n }\n boolean rmv = lookup == null && invokeMap == null;\n final boolean hasFilters = !F.isEmptyOrNulls(filter) && !F.isAlwaysTrue(filter);\n final boolean needVal = singleRmv || retval || hasFilters;\n final boolean needReadVer = needVal && (serializable() && optimistic());\n try {\n // Set transform flag for transaction.\n if (invokeMap != null)\n transform = true;\n Set missedForLoad = null;\n for (Object key : keys) {\n if (isRollbackOnly())\n return finishFuture(enlistFut, timedOut() ? timeoutException() : rollbackException(), false);\n if (key == null) {\n rollback();\n throw new NullPointerException(\"Null key.\");\n }\n Object val = rmv || lookup == null ? null : lookup.get(key);\n EntryProcessor entryProc = invokeMap == null ? null : invokeMap.get(key);\n GridCacheVersion drVer;\n long drTtl;\n long drExpireTime;\n if (drPutMap != null) {\n GridCacheDrInfo info = drPutMap.get(key);\n assert info != null;\n drVer = info.version();\n drTtl = info.ttl();\n drExpireTime = info.expireTime();\n } else if (drRmvMap != null) {\n assert drRmvMap.get(key) != null;\n drVer = drRmvMap.get(key);\n drTtl = -1L;\n drExpireTime = -1L;\n } else if (dataCenterId != null) {\n drVer = cacheCtx.cache().nextVersion(dataCenterId);\n drTtl = -1L;\n drExpireTime = -1L;\n } else {\n drVer = null;\n drTtl = -1L;\n drExpireTime = -1L;\n }\n if (!rmv && val == null && entryProc == null) {\n setRollbackOnly();\n throw new NullPointerException(\"Null value.\");\n }\n KeyCacheObject cacheKey = cacheCtx.toCacheKeyObject(key);\n boolean loadMissed = enlistWriteEntry(cacheCtx, entryTopVer, cacheKey, val, entryProc, invokeArgs, expiryPlc, retval, filter, drVer, drTtl, drExpireTime, ret, enlisted, skipStore, singleRmv, hasFilters, needVal, needReadVer, keepBinary);\n if (loadMissed) {\n if (missedForLoad == null)\n missedForLoad = new HashSet<>();\n missedForLoad.add(cacheKey);\n }\n }\n if (missedForLoad != null) {\n AffinityTopologyVersion topVer = topologyVersionSnapshot();\n if (topVer == null)\n topVer = entryTopVer;\n IgniteInternalFuture loadFut = loadMissing(cacheCtx, topVer != null ? topVer : topologyVersion(), missedForLoad, filter, ret, needReadVer, singleRmv, hasFilters, /*read through*/\n (invokeMap != null || cacheCtx.config().isLoadPreviousValue()) && !skipStore, retval, keepBinary, recovery, expiryPlc);\n loadFut.listen(() -> {\n try {\n loadFut.get();\n finishFuture(enlistFut, null, true);\n } catch (IgniteCheckedException e) {\n finishFuture(enlistFut, e, true);\n }\n });\n return enlistFut;\n }\n return finishFuture(enlistFut, null, true);\n } catch (IgniteCheckedException e) {\n return finishFuture(enlistFut, e, true);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private VmDataCommand generateVmDataCommand(final VirtualRouter router, final String vmPrivateIpAddress, final String userData, String userDataDetails, final String serviceOffering, final String zoneName, final String publicIpAddress, final String vmName, final String vmInstanceName, final long vmId, final String vmUuid, final String publicKey, final long guestNetworkId, String hostname) {\n final VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName, _networkModel.getExecuteInSeqNtwkElmtCmd());\n cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));\n cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));\n cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());\n final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());\n cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());\n cmd.addVmData(\"userdata\", \"user-data\", userData);\n cmd.addVmData(\"metadata\", \"service-offering\", StringUtils.unicodeEscape(serviceOffering));\n cmd.addVmData(\"metadata\", \"availability-zone\", StringUtils.unicodeEscape(zoneName));\n cmd.addVmData(\"metadata\", \"local-ipv4\", vmPrivateIpAddress);\n cmd.addVmData(\"metadata\", \"local-hostname\", StringUtils.unicodeEscape(vmName));\n addUserDataDetailsToCommand(cmd, userDataDetails);\n Network network = _networkDao.findById(guestNetworkId);\n if (dcVo.getNetworkType() == NetworkType.Basic || network.getGuestType() == Network.GuestType.Shared) {\n cmd.addVmData(\"metadata\", \"public-ipv4\", vmPrivateIpAddress);\n cmd.addVmData(\"metadata\", \"public-hostname\", StringUtils.unicodeEscape(vmName));\n } else {\n if (publicIpAddress != null) {\n cmd.addVmData(\"metadata\", \"public-ipv4\", publicIpAddress);\n cmd.addVmData(\"metadata\", \"public-hostname\", publicIpAddress);\n } else if (router.getPublicIpAddress() != null) {\n cmd.addVmData(\"metadata\", \"public-ipv4\", router.getPublicIpAddress());\n cmd.addVmData(\"metadata\", \"public-hostname\", router.getPublicIpAddress());\n }\n }\n if (vmUuid == null) {\n cmd.addVmData(\"metadata\", \"instance-id\", vmInstanceName);\n cmd.addVmData(\"metadata\", \"vm-id\", String.valueOf(vmId));\n } else {\n cmd.addVmData(\"metadata\", \"instance-id\", vmUuid);\n cmd.addVmData(\"metadata\", \"vm-id\", vmUuid);\n }\n cmd.addVmData(\"metadata\", \"public-keys\", publicKey);\n String cloudIdentifier = _configDao.getValue(\"cloud.identifier\");\n if (cloudIdentifier == null) {\n cloudIdentifier = \"\";\n } else {\n cloudIdentifier = \"CloudStack-{\" + cloudIdentifier + \"}\";\n }\n cmd.addVmData(\"metadata\", \"cloud-identifier\", cloudIdentifier);\n cmd.addVmData(\"metadata\", \"hypervisor-host-name\", hostname);\n return cmd;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static String generateNewTsFilePathWithMkdir(boolean sequence, String logicalStorageGroup, String virtualStorageGroup, long timePartitionId, long time, long version, int innerSpaceCompactionCount, int crossSpaceCompactionCount) throws DiskSpaceInsufficientException{\r\n String tsFileDir = generateTsFileDir(sequence, logicalStorageGroup, virtualStorageGroup, timePartitionId);\r\n fsFactory.getFile(tsFileDir).mkdirs();\r\n return tsFileDir + File.separator + generateNewTsFileName(time, version, innerSpaceCompactionCount, crossSpaceCompactionCount);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ISchemaTree validate(ISchemaFetcher schemaFetcher, List devicePaths, List measurements, List dataTypes, List encodings, List compressionTypes, List isAlignedList, MPPQueryContext context){\r\n return schemaFetcher.fetchSchemaListWithAutoCreate(devicePaths, measurements, dataTypes, encodings, compressionTypes, isAlignedList, context);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Pair prepareNetwork(String vSwitchName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid, Map nicDetails) throws Exception {\n HostVirtualSwitch vSwitch;\n if (vSwitchName == null) {\n LOGGER.info(\"Detected vswitch name as undefined. Defaulting to vSwitch0\");\n vSwitchName = \"vSwitch0\";\n }\n vSwitch = hostMo.getHostVirtualSwitchByName(vSwitchName);\n if (vSwitch == null) {\n String msg = \"Unable to find vSwitch\" + vSwitchName;\n LOGGER.error(msg);\n throw new Exception(msg);\n }\n boolean createGCTag = false;\n String networkName;\n Integer vid = null;\n /**\n * This is the list of BroadcastDomainTypes we can actually\n * prepare networks for in this function.\n */\n BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan, BroadcastDomainType.NSX };\n if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {\n throw new InvalidParameterValueException(\"BroadcastDomainType \" + broadcastDomainType + \" it not supported on a VMWare hypervisor at this time.\");\n }\n if (broadcastDomainType == BroadcastDomainType.Lswitch) {\n /**\n * Nicira NVP requires each vm to have its own port-group with a dedicated\n * vlan. We'll set the name of the pg to the uuid of the nic.\n */\n networkName = nicUuid;\n // No doubt about this, depending on vid=null to avoid lots of code below\n vid = null;\n } else {\n networkName = composeCloudNetworkName(namePrefix, vlanId, null, networkRateMbps, vSwitchName);\n if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {\n createGCTag = true;\n vid = Integer.parseInt(vlanId);\n }\n }\n HostNetworkSecurityPolicy secPolicy = createVSSecurityPolicy(nicDetails);\n HostNetworkTrafficShapingPolicy shapingPolicy = null;\n if (networkRateMbps != null && networkRateMbps.intValue() > 0) {\n shapingPolicy = new HostNetworkTrafficShapingPolicy();\n shapingPolicy.setEnabled(true);\n shapingPolicy.setAverageBandwidth(networkRateMbps.intValue() * 1024L * 1024L);\n //\n // TODO : people may have different opinion on how to set the following\n //\n // give 50% premium to peek\n shapingPolicy.setPeakBandwidth((long) (shapingPolicy.getAverageBandwidth() * 1.5));\n // allow 5 seconds of burst transfer\n shapingPolicy.setBurstSize(5 * shapingPolicy.getAverageBandwidth() / 8);\n }\n boolean bWaitPortGroupReady = false;\n if (broadcastDomainType == BroadcastDomainType.Lswitch) {\n //if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour\n if (NiciraNvpApiVersion.isApiVersionLowerThan(\"4.2\")) {\n //Previous behaviour\n if (!hostMo.hasPortGroup(vSwitch, networkName)) {\n createNvpPortGroup(hostMo, vSwitch, networkName, shapingPolicy);\n bWaitPortGroupReady = true;\n } else {\n bWaitPortGroupReady = false;\n }\n }\n } else {\n if (!hostMo.hasPortGroup(vSwitch, networkName)) {\n hostMo.createPortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy, timeOutMs);\n // Setting flag \"bWaitPortGroupReady\" to false.\n // This flag indicates whether we need to wait for portgroup on vCenter.\n // Above createPortGroup() method itself ensures creation of portgroup as well as wait for portgroup.\n bWaitPortGroupReady = false;\n } else {\n HostPortGroupSpec spec = hostMo.getPortGroupSpec(networkName);\n if (!isSpecMatch(spec, vid, secPolicy, shapingPolicy)) {\n hostMo.updatePortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy);\n bWaitPortGroupReady = true;\n }\n }\n }\n ManagedObjectReference morNetwork = null;\n if (broadcastDomainType != BroadcastDomainType.Lswitch || (broadcastDomainType == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan(\"4.2\"))) {\n if (bWaitPortGroupReady)\n morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);\n else\n morNetwork = hostMo.getNetworkMor(networkName);\n if (morNetwork == null) {\n String msg = \"Failed to create guest network \" + networkName;\n LOGGER.error(msg);\n throw new Exception(msg);\n }\n if (createGCTag) {\n NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);\n networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, \"true\");\n }\n }\n if (syncPeerHosts) {\n ManagedObjectReference morParent = hostMo.getParentMor();\n if (morParent != null && morParent.getType().equals(\"ClusterComputeResource\")) {\n // to be conservative, lock cluster\n GlobalLock lock = GlobalLock.getInternLock(\"ClusterLock.\" + morParent.getValue());\n try {\n if (lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {\n try {\n List hosts = hostMo.getContext().getVimClient().getDynamicProperty(morParent, \"host\");\n if (hosts != null) {\n for (ManagedObjectReference otherHost : hosts) {\n if (!otherHost.getValue().equals(hostMo.getMor().getValue())) {\n HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);\n try {\n if (LOGGER.isDebugEnabled())\n LOGGER.debug(\"Prepare network on other host, vlan: \" + vlanId + \", host: \" + otherHostMo.getHostName());\n prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId, networkRateMbps, networkRateMulticastMbps, timeOutMs, false, broadcastDomainType, nicUuid, nicDetails);\n } catch (Exception e) {\n LOGGER.warn(\"Unable to prepare network on other host, vlan: \" + vlanId + \", host: \" + otherHostMo.getHostName());\n }\n }\n }\n }\n } finally {\n lock.unlock();\n }\n } else {\n LOGGER.warn(\"Unable to lock cluster to prepare guest network, vlan: \" + vlanId);\n }\n } finally {\n lock.releaseRef();\n }\n }\n }\n LOGGER.info(\"Network \" + networkName + \" is ready on vSwitch \" + vSwitchName);\n return new Pair(morNetwork, networkName);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private void auditRecovery(String subjectID, AppletInfo aInfo, String status, String keyVersion, BigInteger serial, String caConnId, String kraConnId, String info) {\n TPSEngine engine = TPSEngine.getInstance();\n Auditor auditor = engine.getAuditor();\n String serialNum = \"\";\n if (serial.compareTo(BigInteger.ZERO) > 0)\n serialNum = serial.toString();\n String auditMessage = CMS.getLogMessage(AuditEvent.TOKEN_KEY_RECOVERY, (session != null) ? session.getIpAddress() : null, subjectID, aInfo.getCUIDhexStringPlain(), status, getSelectedTokenType(), keyVersion, serialNum, caConnId, kraConnId, info);\n auditor.log(auditMessage);\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "private static void compute(PrintStream output, String header, String sequence, String delimiter, AminoAcidCompositionTable aaTable, List propertyList, List specificList, int decimalPlace) throws CompoundNotFoundException{\r\n ProteinSequence pSequence;\r\n CompoundSet aaSet;\r\n if (aaTable != null) {\r\n sequence = Utils.checkSequence(sequence, aaTable.getSymbolSet());\r\n pSequence = new ProteinSequence(sequence, aaTable.getAminoAcidCompoundSet());\r\n aaSet = aaTable.getAminoAcidCompoundSet();\r\n } else {\r\n sequence = Utils.checkSequence(sequence);\r\n pSequence = new ProteinSequence(sequence);\r\n aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet();\r\n }\r\n IPeptideProperties pp = new PeptidePropertiesImpl();\r\n int specificCount = 0;\r\n List dList = new ArrayList();\r\n for (Character c : propertyList) {\r\n switch(c) {\r\n case '1':\r\n if (aaTable == null)\r\n dList.add(pp.getMolecularWeight(pSequence));\r\n else\r\n dList.add(pp.getMolecularWeight(pSequence));\r\n break;\r\n case '2':\r\n dList.add(pp.getAbsorbance(pSequence, true));\r\n dList.add(pp.getAbsorbance(pSequence, false));\r\n break;\r\n case '3':\r\n dList.add(pp.getExtinctionCoefficient(pSequence, true));\r\n dList.add(pp.getExtinctionCoefficient(pSequence, false));\r\n break;\r\n case '4':\r\n dList.add(pp.getInstabilityIndex(pSequence));\r\n break;\r\n case '5':\r\n dList.add(pp.getApliphaticIndex(pSequence));\r\n break;\r\n case '6':\r\n dList.add(pp.getAvgHydropathy(pSequence));\r\n break;\r\n case '7':\r\n dList.add(pp.getIsoelectricPoint(pSequence));\r\n break;\r\n case '8':\r\n dList.add(pp.getNetCharge(pSequence));\r\n break;\r\n case '9':\r\n Map aaCompound2Double = pp.getAAComposition(pSequence);\r\n dList.add(aaCompound2Double.get(Constraints.A));\r\n dList.add(aaCompound2Double.get(Constraints.R));\r\n dList.add(aaCompound2Double.get(Constraints.N));\r\n dList.add(aaCompound2Double.get(Constraints.D));\r\n dList.add(aaCompound2Double.get(Constraints.C));\r\n dList.add(aaCompound2Double.get(Constraints.E));\r\n dList.add(aaCompound2Double.get(Constraints.Q));\r\n dList.add(aaCompound2Double.get(Constraints.G));\r\n dList.add(aaCompound2Double.get(Constraints.H));\r\n dList.add(aaCompound2Double.get(Constraints.I));\r\n dList.add(aaCompound2Double.get(Constraints.L));\r\n dList.add(aaCompound2Double.get(Constraints.K));\r\n dList.add(aaCompound2Double.get(Constraints.M));\r\n dList.add(aaCompound2Double.get(Constraints.F));\r\n dList.add(aaCompound2Double.get(Constraints.P));\r\n dList.add(aaCompound2Double.get(Constraints.S));\r\n dList.add(aaCompound2Double.get(Constraints.T));\r\n dList.add(aaCompound2Double.get(Constraints.W));\r\n dList.add(aaCompound2Double.get(Constraints.Y));\r\n dList.add(aaCompound2Double.get(Constraints.V));\r\n break;\r\n case '0':\r\n dList.add(pp.getEnrichment(pSequence, aaSet.getCompoundForString(\"\" + specificList.get(specificCount++))));\r\n break;\r\n }\r\n }\r\n output.print(header.replace(delimiter, \"_\"));\r\n dList.stream().forEach(item -> output.print(delimiter + Utils.roundToDecimals(item, decimalPlace)));\r\n output.println();\r\n output.flush();\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Query9Def query(String name, Class type1, Class type2, Class type3, Class type4, Class type5, Class type6, Class type7, Class type8, Class type9){\r\n return new Query9DefImpl<>(VIEW_BUILDER, name, type1, type2, type3, type4, type5, type6, type7, type8, type9);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Add change log message\n * @param gridTab\n * @param docActionValues\n * @param docActionNames\n * @param reversedStatusName\n * @param columns\n * @param currentDocStatusOld\n * @param currentDocStatusNew\n * @param updated\n * @param userId\n * @param changes\n * @param columnIds\n */\npublic void buildChangeLogMessage(GridTab gridTab, ArrayList docActionValues, ArrayList docActionNames, String reversedStatusName, List columns, String currentDocStatusOld, String currentDocStatusNew, Timestamp updated, int userId, List> changes, List columnIds) {\n if (currentDocStatusOld != null && currentDocStatusNew != null) {\n buildDocActionMessage(docActionValues, docActionNames, reversedStatusName, updated, new MUser(Env.getCtx(), userId, (String) null), currentDocStatusOld, currentDocStatusNew, gridTab.getWindowNo());\n } else if (columns != null && columns.size() > 0) {\n StringBuilder sb = new StringBuilder(\" \");\n sb.append(Msg.getMsg(Env.getCtx(), \"Updated\")).append(\" \");\n for (int i = 0; i < columns.size(); i++) {\n if (i > 0) {\n if (i + 1 == columns.size()) {\n sb.append(\" \").append(Msg.getMsg(Env.getCtx(), \"AND\").toLowerCase()).append(\" \");\n } else {\n sb.append(\", \");\n }\n }\n MColumn column = MColumn.get(Env.getCtx(), columnIds.get(i));\n Pair change = changes.get(i);\n String oldValue = change.getX();\n String newValue = change.getY();\n if (oldValue != null && oldValue.equals(MChangeLog.NULL))\n oldValue = null;\n if (newValue != null && newValue.equals(MChangeLog.NULL))\n newValue = null;\n String showOldValue = oldValue;\n String showNewValue = newValue;\n try {\n if (DisplayType.isText(column.getAD_Reference_ID()))\n ;\n else if (column.getAD_Reference_ID() == DisplayType.YesNo) {\n if (oldValue != null) {\n boolean yes = oldValue.equals(\"true\") || oldValue.equals(\"Y\");\n showOldValue = Msg.getMsg(Env.getCtx(), yes ? \"Y\" : \"N\");\n }\n if (newValue != null) {\n boolean yes = newValue.equals(\"true\") || newValue.equals(\"Y\");\n showNewValue = Msg.getMsg(Env.getCtx(), yes ? \"Y\" : \"N\");\n }\n } else if (column.getAD_Reference_ID() == DisplayType.Amount) {\n if (oldValue != null)\n showOldValue = m_amtFormat.format(new BigDecimal(oldValue));\n if (newValue != null)\n showNewValue = m_amtFormat.format(new BigDecimal(newValue));\n } else if (column.getAD_Reference_ID() == DisplayType.Integer) {\n if (oldValue != null)\n showOldValue = m_intFormat.format(Integer.valueOf(oldValue));\n if (newValue != null)\n showNewValue = m_intFormat.format(Integer.valueOf(newValue));\n } else if (DisplayType.isNumeric(column.getAD_Reference_ID())) {\n if (oldValue != null)\n showOldValue = m_numberFormat.format(new BigDecimal(oldValue));\n if (newValue != null)\n showNewValue = m_numberFormat.format(new BigDecimal(newValue));\n } else if (column.getAD_Reference_ID() == DisplayType.Date) {\n if (oldValue != null)\n showOldValue = m_dateFormat.format(Timestamp.valueOf(oldValue));\n if (newValue != null)\n showNewValue = m_dateFormat.format(Timestamp.valueOf(newValue));\n } else if (column.getAD_Reference_ID() == DisplayType.DateTime) {\n if (oldValue != null)\n showOldValue = m_dateTimeFormat.format(Timestamp.valueOf(oldValue));\n if (newValue != null)\n showNewValue = m_dateTimeFormat.format(Timestamp.valueOf(newValue));\n } else if (DisplayType.isLookup(column.getAD_Reference_ID())) {\n MLookup lookup = MLookupFactory.get(Env.getCtx(), 0, column.getAD_Column_ID(), column.getAD_Reference_ID(), Env.getLanguage(Env.getCtx()), column.getColumnName(), column.getAD_Reference_Value_ID(), column.isParent(), null);\n if (oldValue != null) {\n Object key = oldValue;\n NamePair pp = lookup.get(key);\n if (pp != null)\n showOldValue = pp.getName();\n }\n if (newValue != null) {\n Object key = newValue;\n NamePair pp = lookup.get(key);\n if (pp != null)\n showNewValue = pp.getName();\n }\n } else if (DisplayType.isLOB(column.getAD_Reference_ID()))\n ;\n } catch (Exception e) {\n CLogger.getCLogger(getClass()).log(Level.WARNING, oldValue + \"->\" + newValue, e);\n }\n sb.append(\"\").append(columns.get(i));\n sb.append(\" (\").append(showOldValue != null ? showOldValue : \"\").append(\" > \").append(showNewValue != null ? showNewValue : \"\").append(\")\");\n sb.append(\"\");\n }\n buildActivityMessage(updated, sb.toString(), new MUser(Env.getCtx(), userId, (String) null));\n }\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "/**\n * \tGet On Hand Storage for Warehouse or locator\n * \t@param ctx context\n * \t@param M_Warehouse_ID ignore if M_Locator_ID > 0\n * \t@param M_Product_ID product\n * \t@param M_AttributeSetInstance_ID instance id, 0 to retrieve storages that don't have asi, -1 to retrieve all instance\n * \t@param minGuaranteeDate optional minimum guarantee date filter. ignore if M_AttributeSetInstance_ID != 0\n * \t@param FiFo true for first in-first-out, false for LIFO\n * @param M_Locator_ID optional locator id\n * \t@param trxName transaction\n * @param forUpdate true to acquire DB lock with FOR UPDATE clause\n * \t@return array of MStorageOnHand - ordered by location priority (desc) and/or guarantee date\n */\npublic static MStorageOnHand[] getWarehouseNegative(Properties ctx, int M_Warehouse_ID, int M_Product_ID, int M_AttributeSetInstance_ID, Timestamp minGuaranteeDate, boolean FiFo, int M_Locator_ID, String trxName, boolean forUpdate) {\n return getWarehouseNegative(ctx, M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID, minGuaranteeDate, FiFo, M_Locator_ID, trxName, forUpdate, 0);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "/**\n * Get Reduce Keys for RS following MapSide GB\n *\n * @param reduceKeys\n * assumed to be deduped list of exprs\n * @param outputKeyColumnNames\n * @param colExprMap\n * @return List of ExprNodeDesc of ReduceKeys\n * @throws SemanticException\n */\nprivate static ArrayList getReduceKeysForRS(Operator inOp, int startPos, int endPos, List outputKeyColumnNames, boolean addOnlyOneKeyColName, ArrayList colInfoLst, Map colExprMap, boolean addEmptyTabAlias, boolean setColToNonVirtual) throws SemanticException {\n ArrayList reduceKeys = null;\n if (endPos < 0) {\n reduceKeys = new ArrayList();\n } else {\n reduceKeys = ExprNodeDescUtils.genExprNodeDesc(inOp, startPos, endPos, addEmptyTabAlias, setColToNonVirtual);\n int outColNameIndx = startPos;\n for (int i = 0; i < reduceKeys.size(); ++i) {\n String outputColName = SemanticAnalyzer.getColumnInternalName(outColNameIndx);\n outColNameIndx++;\n if (!addOnlyOneKeyColName || i == 0) {\n outputKeyColumnNames.add(outputColName);\n }\n // TODO: Verify if this is needed (Why can't it be always null/empty\n String tabAlias = addEmptyTabAlias ? \"\" : null;\n ColumnInfo colInfo = new ColumnInfo(Utilities.ReduceField.KEY.toString() + \".\" + outputColName, reduceKeys.get(i).getTypeInfo(), tabAlias, false);\n colInfoLst.add(colInfo);\n colExprMap.put(colInfo.getInternalName(), reduceKeys.get(i));\n }\n }\n return reduceKeys;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static ConsequenceBuilder._21 on(Variable arg1, Variable arg2, Variable arg3, Variable arg4, Variable arg5, Variable arg6, Variable arg7, Variable arg8, Variable arg9, Variable arg10, Variable arg11, Variable arg12, Variable arg13, Variable arg14, Variable arg15, Variable arg16, Variable arg17, Variable arg18, Variable arg19, Variable arg20, Variable arg21){\r\n return new ConsequenceBuilder._21(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20, arg21);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List vlanDbIds, Long networkId, String requestedIp, String requestedGateway, boolean isSystem) throws InsufficientAddressCapacityException;", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static ExprViewItem
expr(Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Predicate7 predicate){\r\n return new Expr7ViewItemImpl<>(var1, var2, var3, var4, var5, var6, var7, new Predicate7.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param part Partition.\n * @param key Key.\n * @param evtNodeId Event node ID.\n * @param type Event type.\n * @param newVal New value.\n * @param hasNewVal Has new value flag.\n * @param oldVal Old values.\n * @param hasOldVal Has old value flag.\n * @param keepBinary Keep binary flag.\n */\npublic void addCacheEvent(int part, KeyCacheObject key, UUID evtNodeId, int type, @Nullable CacheObject newVal, boolean hasNewVal, @Nullable CacheObject oldVal, boolean hasOldVal, boolean keepBinary) {\n List> caches = this.caches;\n for (GridCacheContext cctx : caches) if (!cctx.config().isEventsDisabled())\n cctx.events().addEvent(part, key, evtNodeId, null, null, null, type, newVal, hasNewVal, oldVal, hasOldVal, null, null, keepBinary);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * Implementation of chunked verification specifically on byte arrays. This\n * is to avoid the copy when dealing with ByteBuffers that have array backing.\n */\nstatic void verifyChunked(final Type type, final Checksum algorithm, final byte[] data, final int dataOffset, final int dataLength, final int bytesPerCrc, final byte[] crcs, final int crcsOffset, final String filename, final long basePos) throws ChecksumException {\n final int dataEnd = dataOffset + dataLength;\n int i = dataOffset;\n int j = crcsOffset;\n for (final int n = dataEnd - bytesPerCrc + 1; i < n; i += bytesPerCrc, j += 4) {\n algorithm.reset();\n algorithm.update(data, i, bytesPerCrc);\n final int computed = (int) algorithm.getValue();\n final int expected = ((crcs[j] << 24) + ((crcs[j + 1] << 24) >>> 8)) + (((crcs[j + 2] << 24) >>> 16) + ((crcs[j + 3] << 24) >>> 24));\n if (computed != expected) {\n final long errPos = basePos + i - dataOffset;\n throwChecksumException(type, algorithm, filename, errPos, expected, computed);\n }\n }\n final int remainder = dataEnd - i;\n if (remainder > 0) {\n algorithm.reset();\n algorithm.update(data, i, remainder);\n final int computed = (int) algorithm.getValue();\n final int expected = ((crcs[j] << 24) + ((crcs[j + 1] << 24) >>> 8)) + (((crcs[j + 2] << 24) >>> 16) + ((crcs[j + 3] << 24) >>> 24));\n if (computed != expected) {\n final long errPos = basePos + i - dataOffset;\n throwChecksumException(type, algorithm, filename, errPos, expected, computed);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void populateHeaders(List mapIds, String jobId, int dagId, String user, int reduce, HttpResponse response, boolean keepAliveParam, Map mapOutputInfoMap) throws IOException {\n // Reads the index file for each requested mapId, and figures out the overall\n // length of the response - which is populated into the response header.\n long contentLength = 0;\n for (String mapId : mapIds) {\n MapOutputInfo outputInfo = getMapOutputInfo(jobId, dagId, mapId, reduce, user);\n // mapOutputInfoMap is used to share the lookups with the caller\n if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {\n mapOutputInfoMap.put(mapId, outputInfo);\n }\n ShuffleHeader header = new ShuffleHeader(mapId, outputInfo.indexRecord.getPartLength(), outputInfo.indexRecord.getRawLength(), reduce);\n DataOutputBuffer dob = new DataOutputBuffer();\n header.write(dob);\n contentLength += outputInfo.indexRecord.getPartLength();\n contentLength += dob.getLength();\n }\n // Now set the response headers.\n setResponseHeaders(response, keepAliveParam, contentLength);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Get all Storages for Product where QtyOnHand != 0\n * @param ctx context\n * @param M_Product_ID product\n * @param M_Locator_ID locator, 0 to match all locator\n * @param locatorPriority If true, sort descending by locator Priority No\n * @param fifo Sort ascending(FIFO) or descending(LIFO) by date material policy, m_attributesetinstance_id\n * @param trxName transaction\n * @param forUpdate If true, acquire DB lock with FOR UPDATE clause\n * @param timeout query timeout if forUpdate is true (0 for no timeout)\n * @return array of MStorageOnHand\n */\npublic static MStorageOnHand[] getAll(Properties ctx, int M_Product_ID, int M_Locator_ID, boolean locatorPriority, boolean fifo, String trxName, boolean forUpdate, int timeout) {\n String sqlWhere = \"M_Product_ID=? AND QtyOnHand <> 0\";\n if (M_Locator_ID > 0)\n sqlWhere = sqlWhere + \" AND M_Locator_ID=? \";\n Query query = new Query(ctx, MStorageOnHand.Table_Name, sqlWhere, trxName);\n if (M_Locator_ID > 0)\n query.setParameters(M_Product_ID, M_Locator_ID);\n else\n query.setParameters(M_Product_ID);\n MProduct product = MProduct.get(ctx, M_Product_ID);\n StringBuilder orderBy = new StringBuilder();\n if (locatorPriority) {\n query.addJoinClause(\"JOIN M_Locator locator ON (M_StorageOnHand.M_Locator_ID=locator.M_Locator_ID) \");\n orderBy.append(\"locator.PriorityNo DESC, \");\n }\n if (product.isUseGuaranteeDateForMPolicy()) {\n query.addJoinClause(\" LEFT OUTER JOIN M_AttributeSetInstance asi ON (M_StorageOnHand.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID) \");\n orderBy.append(\"asi.\").append(I_M_AttributeSetInstance.COLUMNNAME_GuaranteeDate);\n if (!fifo)\n orderBy.append(\" DESC\");\n orderBy.append(\", \");\n orderBy.append(MStorageOnHand.Table_Name).append(\".\").append(MStorageOnHand.COLUMNNAME_M_AttributeSetInstance_ID);\n if (!fifo)\n orderBy.append(\" DESC\");\n query.setOrderBy(orderBy.toString());\n } else {\n orderBy.append(MStorageOnHand.Table_Name).append(\".\").append(MStorageOnHand.COLUMNNAME_DateMaterialPolicy);\n if (!fifo)\n orderBy.append(\" DESC\");\n orderBy.append(\", \");\n orderBy.append(MStorageOnHand.Table_Name).append(\".\").append(MStorageOnHand.COLUMNNAME_M_AttributeSetInstance_ID);\n if (!fifo)\n orderBy.append(\" DESC\");\n query.setOrderBy(orderBy.toString());\n }\n if (forUpdate) {\n query.setForUpdate(forUpdate);\n if (timeout > 0) {\n query.setQueryTimeout(timeout);\n }\n }\n List list = query.list();\n MStorageOnHand[] retValue = new MStorageOnHand[list.size()];\n list.toArray(retValue);\n return retValue;\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "/**\n * @return an instance of the LoanRescheduleRequestData class\n */\npublic static LoanRescheduleRequestData instance(Long id, Long loanId, LoanRescheduleRequestStatusEnumData statusEnum, final String clientName, final String loanAccountNumber, final Long clientId, final LocalDate rescheduleFromDate, final CodeValueData rescheduleReasonCodeValue) {\n return new LoanRescheduleRequestData(id, loanId, statusEnum, clientName, loanAccountNumber, clientId, rescheduleFromDate, rescheduleReasonCodeValue);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "protected RackawareEnsemblePlacementPolicyImpl initialize(DNSToSwitchMapping dnsResolver, HashedWheelTimer timer, boolean reorderReadsRandom, int stabilizePeriodSeconds, int reorderThresholdPendingRequests, boolean isWeighted, int maxWeightMultiple, int minNumRacksPerWriteQuorum, boolean enforceMinNumRacksPerWriteQuorum, boolean ignoreLocalNodeInPlacementPolicy, StatsLogger statsLogger, BookieAddressResolver bookieAddressResolver){\r\n checkNotNull(statsLogger, \"statsLogger should not be null, use NullStatsLogger instead.\");\r\n this.statsLogger = statsLogger;\r\n this.bookieAddressResolver = bookieAddressResolver;\r\n this.bookiesJoinedCounter = statsLogger.getOpStatsLogger(BOOKIES_JOINED);\r\n this.bookiesLeftCounter = statsLogger.getOpStatsLogger(BOOKIES_LEFT);\r\n this.readReorderedCounter = statsLogger.getOpStatsLogger(READ_REQUESTS_REORDERED);\r\n this.failedToResolveNetworkLocationCounter = statsLogger.getCounter(FAILED_TO_RESOLVE_NETWORK_LOCATION_COUNTER);\r\n this.numWritableBookiesInDefaultRack = new Gauge() {\r\n\r\n @Override\r\n public Integer getDefaultValue() {\r\n return 0;\r\n }\r\n\r\n @Override\r\n public Integer getSample() {\r\n rwLock.readLock().lock();\r\n try {\r\n return topology.countNumOfAvailableNodes(getDefaultRack(), Collections.emptySet());\r\n } finally {\r\n rwLock.readLock().unlock();\r\n }\r\n }\r\n };\r\n this.statsLogger.registerGauge(NUM_WRITABLE_BOOKIES_IN_DEFAULT_RACK, numWritableBookiesInDefaultRack);\r\n this.reorderReadsRandom = reorderReadsRandom;\r\n this.stabilizePeriodSeconds = stabilizePeriodSeconds;\r\n this.reorderThresholdPendingRequests = reorderThresholdPendingRequests;\r\n this.dnsResolver = new DNSResolverDecorator(dnsResolver, () -> this.getDefaultRack(), failedToResolveNetworkLocationCounter);\r\n this.timer = timer;\r\n this.minNumRacksPerWriteQuorum = minNumRacksPerWriteQuorum;\r\n this.enforceMinNumRacksPerWriteQuorum = enforceMinNumRacksPerWriteQuorum;\r\n this.ignoreLocalNodeInPlacementPolicy = ignoreLocalNodeInPlacementPolicy;\r\n if (stabilizePeriodSeconds > 0) {\r\n this.topology = new StabilizeNetworkTopology(timer, stabilizePeriodSeconds);\r\n } else {\r\n this.topology = new NetworkTopologyImpl();\r\n }\r\n BookieNode bn = null;\r\n if (!ignoreLocalNodeInPlacementPolicy) {\r\n try {\r\n bn = createDummyLocalBookieNode(InetAddress.getLocalHost().getHostAddress());\r\n } catch (IOException e) {\r\n LOG.error(\"Failed to get local host address : \", e);\r\n }\r\n } else {\r\n LOG.info(\"Ignoring LocalNode in Placementpolicy\");\r\n }\r\n localNode = bn;\r\n LOG.info(\"Initialize rackaware ensemble placement policy @ {} @ {} : {}.\", localNode, null == localNode ? \"Unknown\" : localNode.getNetworkLocation(), dnsResolver.getClass().getName());\r\n this.isWeighted = isWeighted;\r\n if (this.isWeighted) {\r\n this.maxWeightMultiple = maxWeightMultiple;\r\n this.weightedSelection = new WeightedRandomSelectionImpl(this.maxWeightMultiple);\r\n LOG.info(\"Weight based placement with max multiple of \" + this.maxWeightMultiple);\r\n } else {\r\n LOG.info(\"Not weighted\");\r\n }\r\n return this;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "//\tgetWarehouse\n/**\n * \tGet On Hand Storage for Warehouse or locator\n * \t@param ctx context\n * \t@param M_Warehouse_ID ignore if M_Locator_ID > 0\n * \t@param M_Product_ID product\n * \t@param M_AttributeSetInstance_ID instance id, 0 to retrieve all instance\n * \t@param minGuaranteeDate optional minimum guarantee date filter. ignore if M_AttributeSetInstance_ID != 0\n * \t@param FiFo true for first in-first-out, false for LIFO\n * @param M_Locator_ID optional locator id\n * \t@param trxName transaction\n * \t@return array of MStorageOnHand - ordered by location priority (desc) and/or guarantee date\n */\npublic static MStorageOnHand[] getWarehouseNegative(Properties ctx, int M_Warehouse_ID, int M_Product_ID, int M_AttributeSetInstance_ID, Timestamp minGuaranteeDate, boolean FiFo, int M_Locator_ID, String trxName) {\n return getWarehouseNegative(ctx, M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID, minGuaranteeDate, FiFo, M_Locator_ID, trxName, false);\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "private static boolean migratePropertiesAndDatabase(String oldMSKey, String oldDBKey, String newMSKey, String newDBKey, String newEncryptorVersion, boolean loadNewMsKeyFromEnv, boolean forced, boolean skipped) {\n final File dbPropsFile = PropertiesUtil.findConfigFile(\"db.properties\");\n final Properties dbProps = new Properties();\n EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger();\n PropertiesConfiguration backupDBProps = null;\n System.out.println(\"Parsing db.properties file\");\n try (FileInputStream dbPropFstream = new FileInputStream(dbPropsFile)) {\n dbProps.load(dbPropFstream);\n backupDBProps = new PropertiesConfiguration(dbPropsFile);\n } catch (FileNotFoundException e) {\n System.out.println(\"db.properties file not found while reading DB secret key: \" + e.getMessage());\n return false;\n } catch (IOException e) {\n System.out.println(\"Error while reading DB secret key from db.properties: \" + e.getMessage());\n return false;\n } catch (ConfigurationException e) {\n System.out.println(\"Error while getting configurations from db.properties: \" + e.getMessage());\n return false;\n }\n try {\n EncryptionSecretKeyChecker.initEncryptor(oldMSKey);\n EncryptionSecretKeyChecker.decryptAnyProperties(dbProps);\n } catch (CloudRuntimeException e) {\n System.out.println(\"Error: Incorrect Management Secret Key\");\n return false;\n }\n String dbSecretKey = dbProps.getProperty(\"db.cloud.encrypt.secret\");\n if (!oldDBKey.equals(dbSecretKey)) {\n System.out.println(\"Error: Incorrect DB Secret Key\");\n return false;\n }\n System.out.println(\"DB Secret key provided matched the key in db.properties\");\n final String encryptionType = dbProps.getProperty(\"db.cloud.encryption.type\");\n final String oldEncryptorVersion = dbProps.getProperty(\"db.cloud.encryptor.version\");\n // validate old and new encryptor versions\n try {\n CloudStackEncryptor.EncryptorVersion.fromString(oldEncryptorVersion);\n CloudStackEncryptor.EncryptorVersion.fromString(newEncryptorVersion);\n } catch (CloudRuntimeException ex) {\n System.out.println(ex.getMessage());\n return false;\n }\n if (loadNewMsKeyFromEnv) {\n newMSKey = System.getenv(ENV_NEW_MANAGEMENT_KEY);\n }\n if (newMSKey == null) {\n newMSKey = oldMSKey;\n }\n if (newDBKey == null) {\n newDBKey = oldDBKey;\n }\n boolean isMSKeyChanged = !newMSKey.equals(oldMSKey);\n boolean isDBKeyChanged = !newDBKey.equals(oldDBKey);\n if (newEncryptorVersion == null && (isDBKeyChanged || forced) && !skipped) {\n if (StringUtils.isNotEmpty(oldEncryptorVersion)) {\n newEncryptorVersion = oldEncryptorVersion;\n } else {\n newEncryptorVersion = CloudStackEncryptor.EncryptorVersion.defaultVersion().name();\n }\n }\n boolean isEncryptorVersionChanged = false;\n if (newEncryptorVersion != null) {\n isEncryptorVersionChanged = !newEncryptorVersion.equalsIgnoreCase(oldEncryptorVersion);\n }\n if (isMSKeyChanged || isDBKeyChanged || isEncryptorVersionChanged) {\n System.out.println(\"INFO: Migrate properties with DB encryptor version: \" + newEncryptorVersion);\n if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey, newEncryptorVersion)) {\n System.out.println(\"Failed to update db.properties\");\n return false;\n }\n if (!keyChanger.migrateServerProperties(newMSKey)) {\n System.out.println(\"Failed to update server.properties\");\n return false;\n }\n //db.properties updated successfully\n if (encryptionType.equals(\"file\")) {\n //update key file with new MS key\n try (FileWriter fwriter = new FileWriter(KEY_FILE);\n BufferedWriter bwriter = new BufferedWriter(fwriter)) {\n bwriter.write(newMSKey);\n } catch (IOException e) {\n System.out.printf(\"Please update the file %s manually. Failed to write new secret to file with error %s %n\", KEY_FILE, e.getMessage());\n return false;\n }\n }\n } else {\n System.out.println(\"No changes with Management Secret Key, DB Secret Key and DB encryptor version. Skipping migrating db.properties\");\n }\n boolean success = false;\n if (isDBKeyChanged || isEncryptorVersionChanged || forced) {\n if (skipped) {\n System.out.println(\"Skipping Data Migration as '-s' or '--skip-database-migration' is passed\");\n return true;\n }\n EncryptionSecretKeyChecker.initEncryptor(newMSKey);\n try {\n success = keyChanger.migrateData(oldDBKey, newDBKey, oldEncryptorVersion, newEncryptorVersion);\n } catch (Exception e) {\n System.out.println(\"Error during data migration\");\n e.printStackTrace();\n }\n } else {\n System.out.println(\"No changes with DB Secret Key and DB encryptor version. Skipping Data Migration\");\n return true;\n }\n if (success) {\n System.out.println(\"Successfully updated secret key(s)\");\n } else {\n System.out.println(\"Data Migration failed. Reverting db.properties\");\n //revert db.properties\n try {\n backupDBProps.save();\n } catch (ConfigurationException e) {\n e.printStackTrace();\n }\n if (encryptionType.equals(\"file\")) {\n //revert secret key in file\n try (FileWriter fwriter = new FileWriter(KEY_FILE);\n BufferedWriter bwriter = new BufferedWriter(fwriter)) {\n bwriter.write(oldMSKey);\n } catch (IOException e) {\n System.out.println(\"Failed to revert to old secret to file. Please update the file manually\");\n }\n }\n return false;\n }\n return true;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static void outputContainerLogThroughZeroCopy(String containerId, String nodeId, String fileName, long fileLength, long outputSize, String lastModifiedTime, FileInputStream fis, OutputStream os, ContainerLogAggregationType logType) throws IOException {\n long toSkip = 0;\n long totalBytesToRead = fileLength;\n if (outputSize < 0) {\n long absBytes = Math.abs(outputSize);\n if (absBytes < fileLength) {\n toSkip = fileLength - absBytes;\n totalBytesToRead = absBytes;\n }\n } else {\n if (outputSize < fileLength) {\n totalBytesToRead = outputSize;\n }\n }\n // output log summary\n byte[] b = formatContainerLogHeader(containerId, nodeId, logType, fileName, lastModifiedTime, fileLength);\n os.write(b, 0, b.length);\n if (totalBytesToRead > 0) {\n // output log content\n FileChannel inputChannel = fis.getChannel();\n WritableByteChannel outputChannel = Channels.newChannel(os);\n long position = toSkip;\n while (totalBytesToRead > 0) {\n long transferred = inputChannel.transferTo(position, totalBytesToRead, outputChannel);\n totalBytesToRead -= transferred;\n position += transferred;\n }\n os.flush();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private CnmTAllegato salvaAllegatoVerbaleSoggettoEsterni(CnmTVerbale cnmTVerbale, byte[] file, CnmTUser cnmTUser, String nomeFile, TipoAllegato tipoAllegato, boolean protocolla, boolean isProtocollazioneInUscita, boolean isMaster, List cnmTSoggettoList){\r\n if (cnmTVerbale == null)\r\n throw new IllegalArgumentException(\"cnmTVerbale ==null\");\r\n if (nomeFile == null)\r\n throw new IllegalArgumentException(\"nomeFile ==null\");\r\n if (cnmTUser == null)\r\n throw new IllegalArgumentException(\"cnmTUser ==null\");\r\n if (tipoAllegato == null)\r\n throw new IllegalArgumentException(\"tipoAllegato ==null\");\r\n String folder = null;\r\n String idEntitaFruitore = null;\r\n TipoProtocolloAllegato tipoProtocolloAllegato = TipoProtocolloAllegato.NON_PROTOCOLLARE;\r\n String soggettoActa = null;\r\n String rootActa = null;\r\n if (protocolla) {\r\n folder = utilsDoqui.createOrGetfolder(cnmTVerbale);\r\n idEntitaFruitore = utilsDoqui.createIdEntitaFruitore(cnmTVerbale, cnmDTipoAllegatoRepository.findOne(tipoAllegato.getId()));\r\n soggettoActa = utilsDoqui.getSoggettoActa(cnmTVerbale);\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.PROTOCOLLARE;\r\n rootActa = utilsDoqui.getRootActa(cnmTVerbale);\r\n }\r\n CnmTAllegato cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), null, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_USCITA_SENZA_ALLEGATI_GENERERATI, cnmTSoggettoList);\r\n return cnmTAllegato;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Call {@link #create(String, FsPermission, EnumSet, boolean, short,\n * long, Progressable, int, ChecksumOpt)} with createParent\n * set to true.\n */\npublic DFSOutputStream create(String src, FsPermission permission, EnumSet flag, short replication, long blockSize, Progressable progress, int buffersize, ChecksumOpt checksumOpt) throws IOException {\n return create(src, permission, flag, true, replication, blockSize, progress, buffersize, checksumOpt, null);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static VMTemplateVO createSystemIso(Long id, String uniqueName, String name, boolean isPublic, String url, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId) {\n return new VMTemplateVO(id, uniqueName, name, ImageFormat.ISO, isPublic, false, TemplateType.SYSTEM, url, null, requiresHvm, bits, accountId, cksum, displayText, enablePassword, guestOSId, false, null);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "private VolumeVO commitVolume(final CreateVolumeCmd cmd, final Account caller, final Account owner, final Boolean displayVolume, final Long zoneId, final Long diskOfferingId, final Storage.ProvisioningType provisioningType, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume, final String userSpecifiedName, final String uuid, final Map details) {\n return Transaction.execute(new TransactionCallback() {\n\n @Override\n public VolumeVO doInTransaction(TransactionStatus status) {\n VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, provisioningType, 0, Volume.Type.DATADISK);\n volume.setPoolId(null);\n volume.setUuid(uuid);\n volume.setDataCenterId(zoneId);\n volume.setPodId(null);\n volume.setAccountId(owner.getId());\n volume.setDomainId(owner.getDomainId());\n volume.setDiskOfferingId(diskOfferingId);\n volume.setSize(size);\n volume.setMinIops(minIops);\n volume.setMaxIops(maxIops);\n volume.setInstanceId(null);\n volume.setUpdated(new Date());\n volume.setDisplayVolume(displayVolume);\n if (parentVolume != null) {\n volume.setTemplateId(parentVolume.getTemplateId());\n volume.setFormat(parentVolume.getFormat());\n } else {\n volume.setTemplateId(null);\n }\n volume = _volsDao.persist(volume);\n if (cmd.getSnapshotId() == null && displayVolume) {\n // for volume created from snapshot, create usage event after volume creation\n UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId, null, size, Volume.class.getName(), volume.getUuid(), displayVolume);\n }\n if (volume != null && details != null) {\n List volumeDetailsVO = new ArrayList();\n if (details.containsKey(Volume.BANDWIDTH_LIMIT_IN_MBPS)) {\n volumeDetailsVO.add(new VolumeDetailVO(volume.getId(), Volume.BANDWIDTH_LIMIT_IN_MBPS, details.get(Volume.BANDWIDTH_LIMIT_IN_MBPS), false));\n }\n if (details.containsKey(Volume.IOPS_LIMIT)) {\n volumeDetailsVO.add(new VolumeDetailVO(volume.getId(), Volume.IOPS_LIMIT, details.get(Volume.IOPS_LIMIT), false));\n }\n if (!volumeDetailsVO.isEmpty()) {\n _volsDetailsDao.saveDetails(volumeDetailsVO);\n }\n }\n CallContext.current().setEventDetails(\"Volume Id: \" + volume.getUuid());\n CallContext.current().putContextParameter(Volume.class, volume.getId());\n // Increment resource count during allocation; if actual creation fails,\n // decrement it\n _resourceLimitMgr.incrementVolumeResourceCount(volume.getAccountId(), displayVolume, volume.getSize(), _diskOfferingDao.findById(volume.getDiskOfferingId()));\n return volume;\n }\n });\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public void createCashBasedJournalEntriesForSharesCharges(final Office office, final String currencyCode, final CashAccountsForShares accountTypeToBeDebited, final CashAccountsForShares accountTypeToBeCredited, final Long shareProductId, final Long paymentTypeId, final Long shareAccountId, final String transactionId, final LocalDate transactionDate, final BigDecimal totalAmount, final List chargePaymentDTOs) {\n createDebitJournalEntryForShares(office, currencyCode, accountTypeToBeDebited.getValue(), shareProductId, paymentTypeId, shareAccountId, transactionId, transactionDate, totalAmount);\n createCashBasedJournalEntryForSharesCharges(office, currencyCode, accountTypeToBeCredited, shareProductId, shareAccountId, transactionId, transactionDate, totalAmount, chargePaymentDTOs);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public void createDebitJournalEntryForShares(final Office office, final String currencyCode, final int accountTypeToDebitId, final Long shareProductId, final Long paymentTypeId, final Long shareAccountId, final String transactionId, final LocalDate transactionDate, final BigDecimal amount) {\n final GLAccount debitAccount = getLinkedGLAccountForShareProduct(shareProductId, accountTypeToDebitId, paymentTypeId);\n createDebitJournalEntryForShares(office, currencyCode, debitAccount, shareAccountId, transactionId, transactionDate, amount);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * \n *

\n * Respecifies a cubic subregion of an existing 3D texel array. No change is made to the internalformat, width, height, depth, or border parameters of\n * the specified texel array, nor is any change made to texel values outside the specified subregion.\n *\n * @param target the texture target.\n * @param level the level-of-detail-number.\n * @param xoffset the x coordinate of the texel subregion.\n * @param yoffset the y coordinate of the texel subregion.\n * @param zoffset the z coordinate of the texel subregion.\n * @param width the subregion width.\n * @param height the subregion height.\n * @param depth the subregion depth.\n * @param format the pixel data format.\n * @param type the pixel data type.\n * @param data the pixel data.\n */\npublic void glTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int type, ByteBuffer data);", "smellKey": "S107", "smellId": null, "repo": "apurba-das_jmonkeyengineFall2024", "language": "java"} {"function": "/**\n * Creates a {@link AbstractHoodieRowData} instance based on the given configuration.\n */\npublic static AbstractHoodieRowData create(String commitTime, String commitSeqNumber, String recordKey, String partitionPath, String fileName, RowData row, boolean withOperation, boolean withMetaFields) {\n return withMetaFields ? new HoodieRowDataWithMetaFields(commitTime, commitSeqNumber, recordKey, partitionPath, fileName, row, withOperation) : new HoodieRowData(commitTime, commitSeqNumber, recordKey, partitionPath, fileName, row, withOperation);\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private int compareTimestampAndType(byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength, byte ltype, byte rtype) {\n int compare;\n if (!this.ignoreTimestamp) {\n // Get timestamps.\n long ltimestamp = Bytes.toLong(left, loffset + (llength - TIMESTAMP_TYPE_SIZE));\n long rtimestamp = Bytes.toLong(right, roffset + (rlength - TIMESTAMP_TYPE_SIZE));\n compare = compareTimestamps(ltimestamp, rtimestamp);\n if (compare != 0) {\n return compare;\n }\n }\n if (!this.ignoreType) {\n // Compare types. Let the delete types sort ahead of puts; i.e. types\n // of higher numbers sort before those of lesser numbers. Maximum (255)\n // appears ahead of everything, and minimum (0) appears after\n // everything.\n return (0xff & rtype) - (0xff & ltype);\n }\n return 0;\n}", "smellKey": "S107", "smellId": null, "repo": "cdapio_cdap", "language": "java"} {"function": "public static ExprViewItem expr(String exprId, Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Predicate10 predicate){\r\n return new Expr10ViewItemImpl<>(exprId, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, new Predicate10.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CnmTAllegato salvaAllegatoOrdinanza(CnmTOrdinanza cnmTOrdinanza, byte[] file, CnmTUser cnmTUser, String nomeFile, List configAllegato, TipoAllegato tipoAllegato, boolean protocolla, boolean isProtocollazioneInUscita, boolean isMaster){\r\n if (cnmTOrdinanza == null)\r\n throw new IllegalArgumentException(\"cnmTOrdinanza ==null\");\r\n if (nomeFile == null)\r\n throw new IllegalArgumentException(\"nomeFile ==null\");\r\n if (cnmTUser == null)\r\n throw new IllegalArgumentException(\"cnmTUser ==null\");\r\n if (tipoAllegato == null)\r\n throw new IllegalArgumentException(\"tipoAllegato ==null\");\r\n String tipoActa = null;\r\n if (tipoAllegato.getId() == TipoAllegato.COMUNICAZIONI_ALLA_CANCELLERIA.getId()) {\r\n tipoActa = StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_USCITA_SENZA_ALLEGATI_CARICATI;\r\n } else if (tipoAllegato.getId() == TipoAllegato.COMUNICAZIONI_DALLA_CANCELLERIA.getId() || tipoAllegato.getId() == TipoAllegato.ISTANZA_RATEIZZAZIONE.getId() || tipoAllegato.getId() == TipoAllegato.OPPOSIZIONE_GIURISDIZIONALE.getId() || tipoAllegato.getId() == TipoAllegato.DISPOSIZIONE_DEL_GIUDICE.getId()) {\r\n tipoActa = StadocServiceFacade.TIPOLOGIA_DOC_ACTA_DOC_INGRESSO_SENZA_ALLEGATI;\r\n } else if (tipoAllegato.getId() == TipoAllegato.LETTERA_ORDINANZA.getId()) {\r\n tipoActa = StadocServiceFacade.TIPOLOGIA_DOC_ACTA_MASTER_USCITA_CON_ALLEGATI;\r\n }\r\n String folder = null;\r\n String idEntitaFruitore = null;\r\n TipoProtocolloAllegato tipoProtocolloAllegato = TipoProtocolloAllegato.NON_PROTOCOLLARE;\r\n String soggettoActa = null;\r\n String rootActa = null;\r\n CnmTAllegato cnmTAllegato = null;\r\n if (protocolla) {\r\n folder = utilsDoqui.createOrGetfolder(cnmTOrdinanza);\r\n idEntitaFruitore = utilsDoqui.createIdEntitaFruitore(cnmTOrdinanza, cnmDTipoAllegatoRepository.findOne(tipoAllegato.getId()));\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.PROTOCOLLARE;\r\n soggettoActa = utilsDoqui.getSoggettoActa(cnmTOrdinanza);\r\n rootActa = utilsDoqui.getRootActa(cnmTOrdinanza);\r\n List cnmTSoggettoList = null;\r\n List cnmROrdinanzaVerbSogList = cnmROrdinanzaVerbSogRepository.findByCnmTOrdinanza(cnmTOrdinanza);\r\n if (cnmROrdinanzaVerbSogList == null || cnmROrdinanzaVerbSogList.size() == 0) {\r\n List cnmRAllegatoOrdVerbSogList = cnmRAllegatoOrdVerbSogRepository.findByCnmTAllegato(cnmTAllegato);\r\n cnmROrdinanzaVerbSogList = cnmROrdinanzaVerbSogRepository.findByCnmRAllegatoOrdVerbSogsIn(cnmRAllegatoOrdVerbSogList);\r\n }\r\n List cnmRVerbaleSoggettoList = cnmRVerbaleSoggettoRepository.findByCnmROrdinanzaVerbSogsIn(cnmROrdinanzaVerbSogList);\r\n cnmTSoggettoList = cnmTSoggettoRepository.findByCnmRVerbaleSoggettosIn(cnmRVerbaleSoggettoList);\r\n if (tipoAllegato.getId() == TipoAllegato.LETTERA_ORDINANZA.getId()) {\r\n tipoProtocolloAllegato = TipoProtocolloAllegato.SALVA_MULTI_SENZA_PROTOCOLARE;\r\n }\r\n cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), configAllegato, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, tipoActa, cnmTSoggettoList);\r\n } else {\r\n cnmTAllegato = commonAllegatoService.salvaAllegato(file, nomeFile, tipoAllegato.getId(), configAllegato, cnmTUser, tipoProtocolloAllegato, folder, idEntitaFruitore, isMaster, isProtocollazioneInUscita, soggettoActa, rootActa, 0, 0, tipoActa, null);\r\n }\r\n CnmRAllegatoOrdinanzaPK cnmRAllegatoOrdinanzaPK = new CnmRAllegatoOrdinanzaPK();\r\n cnmRAllegatoOrdinanzaPK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoOrdinanzaPK.setIdOrdinanza(cnmTOrdinanza.getIdOrdinanza());\r\n CnmRAllegatoOrdinanza cnmRAllegatoOrdinanza = new CnmRAllegatoOrdinanza();\r\n cnmRAllegatoOrdinanza.setId(cnmRAllegatoOrdinanzaPK);\r\n cnmRAllegatoOrdinanza.setCnmTAllegato(cnmTAllegato);\r\n cnmRAllegatoOrdinanza.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoOrdinanza.setCnmTUser(cnmTUser);\r\n cnmRAllegatoOrdinanzaRepository.save(cnmRAllegatoOrdinanza);\r\n return cnmTAllegato;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ExprViewItem expr(Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Predicate10 predicate){\r\n return new Expr10ViewItemImpl<>(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, new Predicate10.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ContextMenu create(BibEntryTableViewModel entry, KeyBindingRepository keyBindingRepository, LibraryTab libraryTab, DialogService dialogService, StateManager stateManager, PreferencesService preferencesService, UndoManager undoManager, ClipBoardManager clipBoardManager, TaskExecutor taskExecutor, BibEntryTypesManager entryTypesManager){\r\n ActionFactory factory = new ActionFactory(keyBindingRepository);\r\n ContextMenu contextMenu = new ContextMenu();\r\n contextMenu.getItems().addAll(factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY, libraryTab.frame(), stateManager)), createCopySubMenu(factory, dialogService, stateManager, preferencesService, clipBoardManager, taskExecutor), factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE, libraryTab.frame(), stateManager)), factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT, libraryTab.frame(), stateManager)), factory.createMenuItem(StandardActions.MERGE_ENTRIES, new MergeEntriesAction(dialogService, stateManager, preferencesService.getBibEntryPreferences())), factory.createMenuItem(StandardActions.DELETE_ENTRY, new EditAction(StandardActions.DELETE_ENTRY, libraryTab.frame(), stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SEND_AS_EMAIL, new SendAsEMailAction(dialogService, preferencesService, stateManager)), new SeparatorMenuItem(), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.RANKING, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.RELEVANCE, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.QUALITY, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.PRINTED, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.PRIORITY, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.READ_STATUS, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.ATTACH_FILE, new AttachFileAction(libraryTab, dialogService, stateManager, preferencesService.getFilePreferences())), factory.createMenuItem(StandardActions.ATTACH_FILE_FROM_URL, new AttachFileFromURLAction(dialogService, stateManager, taskExecutor, preferencesService)), factory.createMenuItem(StandardActions.OPEN_FOLDER, new OpenFolderAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.OPEN_EXTERNAL_FILE, new OpenExternalFileAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.OPEN_URL, new OpenUrlAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.SEARCH_SHORTSCIENCE, new SearchShortScienceAction(dialogService, stateManager, preferencesService)), new SeparatorMenuItem(), new ChangeEntryTypeMenu(libraryTab.getSelectedEntries(), libraryTab.getBibDatabaseContext(), libraryTab.getUndoManager(), keyBindingRepository, entryTypesManager).asSubMenu(), factory.createMenuItem(StandardActions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(libraryTab, dialogService, stateManager, taskExecutor, preferencesService)));\r\n return contextMenu;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static KFPushMessage constructKFPushMessage(long fromUid, long pubUid, long[] toUids, String[] receivers, String fromName, short appId, short toAppId, long cts, String extension, XBody body){\r\n KFPushMessage kfPushMessage = new KFPushMessage();\r\n kfPushMessage.setFromUid(fromUid);\r\n kfPushMessage.setToUids(toUids);\r\n kfPushMessage.setReceivers(receivers);\r\n kfPushMessage.setFromName(fromName);\r\n kfPushMessage.setMessageType(body.messageType());\r\n kfPushMessage.setAppId(appId);\r\n kfPushMessage.setToAppId(toAppId);\r\n kfPushMessage.setPubUid(pubUid);\r\n kfPushMessage.setBody(body);\r\n kfPushMessage.setCts(cts);\r\n if (extension != null) {\r\n kfPushMessage.setExtension(extension);\r\n }\r\n return kfPushMessage;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static Boolean setDocument(Collection collection, String id, int expiry, Object obj, PersistTo persistTo, ReplicateTo replicateTo, long writeQueryTimeout, long producerRetryPause){\r\n UpsertOptions options = UpsertOptions.upsertOptions().expiry(Duration.ofSeconds(expiry)).durability(persistTo, replicateTo).timeout(Duration.ofMillis(writeQueryTimeout)).retryStrategy(BestEffortRetryStrategy.withExponentialBackoff(Duration.ofMillis(producerRetryPause), Duration.ofMillis(producerRetryPause), 1));\r\n MutationResult result = collection.upsert(id, obj, options);\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(result.toString());\r\n }\r\n return true;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ExprViewItem groupBy(ViewItem viewItem, Variable var1, Variable var2, Variable var3, Variable var4, Variable varKey, Function4 groupingFunction, AccumulateFunction... accFunctions){\r\n return new GroupByExprViewItem<>(viewItem, new Variable[] { var1, var2, var3, var4 }, varKey, toFunctionN(groupingFunction), accFunctions);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String buildFilename(String filename, String extension, IVariables variables, int transformnr, String partnr, int splitnr, boolean beamContext, String transformId, int bundleNr, boolean ziparchive, TextFileOutputMeta meta) {\n final String realFileName = variables.resolve(filename);\n final String realExtension = variables.resolve(extension);\n return buildFilename(variables, realFileName, realExtension, Integer.toString(transformnr), partnr, Integer.toString(splitnr), beamContext, transformId, bundleNr, new Date(), ziparchive, true, meta);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public ReduceSinkOperator getReduceSinkOp(List partitionPositions, List sortPositions, List sortOrder, List sortNullOrder, List, ExprNodeDesc>> customSortExprs, List customSortOrder, List customSortNullOrder, ArrayList allCols, ArrayList bucketColumns, int numBuckets, Operator parent, AcidUtils.Operation writeType) {\n // Order of KEY columns, if custom sort is present partition and bucket columns are disregarded:\n // 0) Custom sort expressions\n // 1) Partition columns\n // 2) Bucket number column\n // 3) Sort columns\n boolean customSortExprPresent = customSortExprs != null && !customSortExprs.isEmpty();\n Set keyColsPosInVal = Sets.newLinkedHashSet();\n ArrayList keyCols = Lists.newArrayList();\n List newSortOrder = Lists.newArrayList();\n List newSortNullOrder = Lists.newArrayList();\n if (customSortExprPresent) {\n partitionPositions = new ArrayList<>();\n bucketColumns = new ArrayList<>();\n numBuckets = -1;\n }\n keyColsPosInVal.addAll(partitionPositions);\n if (bucketColumns != null && !bucketColumns.isEmpty()) {\n keyColsPosInVal.add(-1);\n }\n keyColsPosInVal.addAll(sortPositions);\n Integer order = 1;\n // by default partition and bucket columns are sorted in ascending order\n if (sortOrder != null && !sortOrder.isEmpty()) {\n if (sortOrder.get(0) == 0) {\n order = 0;\n }\n }\n for (Integer ignored : keyColsPosInVal) {\n newSortOrder.add(order);\n }\n if (customSortExprPresent) {\n for (int i = 0; i < customSortExprs.size() - customSortOrder.size(); i++) {\n newSortOrder.add(order);\n }\n newSortOrder.addAll(customSortOrder);\n }\n String orderStr = \"\";\n for (Integer i : newSortOrder) {\n if (i == 1) {\n orderStr += \"+\";\n } else {\n orderStr += \"-\";\n }\n }\n // if partition and bucket columns are sorted in ascending order, by default\n // nulls come first; otherwise nulls come last\n Integer nullOrder = order == 1 ? 0 : 1;\n if (sortNullOrder != null && !sortNullOrder.isEmpty()) {\n if (sortNullOrder.get(0) == 0) {\n nullOrder = 0;\n } else {\n nullOrder = 1;\n }\n }\n for (Integer ignored : keyColsPosInVal) {\n newSortNullOrder.add(nullOrder);\n }\n if (customSortExprPresent) {\n for (int i = 0; i < customSortExprs.size() - customSortNullOrder.size(); i++) {\n newSortNullOrder.add(nullOrder);\n }\n newSortNullOrder.addAll(customSortNullOrder);\n }\n String nullOrderStr = \"\";\n for (Integer i : newSortNullOrder) {\n if (i == 0) {\n nullOrderStr += \"a\";\n } else {\n nullOrderStr += \"z\";\n }\n }\n Map colExprMap = Maps.newHashMap();\n ArrayList partCols = Lists.newArrayList();\n for (Function, ExprNodeDesc> customSortExpr : customSortExprs) {\n ExprNodeDesc colExpr = customSortExpr.apply(allCols);\n // Custom sort expressions are marked as KEYs, which is required for sorting the rows that are going for\n // a particular reducer instance. They also need to be marked as 'partition' columns for MapReduce shuffle\n // phase, in order to gather the same keys to the same reducer instances.\n keyCols.add(colExpr);\n partCols.add(colExpr);\n }\n // we will clone here as RS will update bucket column key with its\n // corresponding with bucket number and hence their OIs\n for (Integer idx : keyColsPosInVal) {\n if (idx == -1) {\n keyCols.add(BUCKET_SORT_EXPRESSION.apply(allCols));\n } else {\n keyCols.add(allCols.get(idx).clone());\n }\n }\n ArrayList valCols = Lists.newArrayList();\n for (int i = 0; i < allCols.size(); i++) {\n if (!keyColsPosInVal.contains(i)) {\n valCols.add(allCols.get(i).clone());\n }\n }\n for (Integer idx : partitionPositions) {\n partCols.add(allCols.get(idx).clone());\n }\n // in the absence of SORTED BY clause, the sorted dynamic partition insert\n // should honor the ordering of records provided by ORDER BY in SELECT statement\n ReduceSinkOperator parentRSOp = OperatorUtils.findSingleOperatorUpstream(parent, ReduceSinkOperator.class);\n if (parentRSOp != null && parseCtx.getQueryProperties().hasOuterOrderBy()) {\n String parentRSOpOrder = parentRSOp.getConf().getOrder();\n String parentRSOpNullOrder = parentRSOp.getConf().getNullOrder();\n if (parentRSOpOrder != null && !parentRSOpOrder.isEmpty() && sortPositions.isEmpty()) {\n keyCols.addAll(parentRSOp.getConf().getKeyCols());\n orderStr += parentRSOpOrder;\n nullOrderStr += parentRSOpNullOrder;\n }\n }\n // map _col0 to KEY._col0, etc\n Map nameMapping = new HashMap<>();\n ArrayList keyColNames = Lists.newArrayList();\n Set computedFields = new HashSet<>();\n for (ExprNodeDesc keyCol : keyCols) {\n String keyColName = keyCol.getExprString();\n keyColNames.add(keyColName);\n colExprMap.put(Utilities.ReduceField.KEY + \".\" + keyColName, keyCol);\n nameMapping.put(keyColName, Utilities.ReduceField.KEY + \".\" + keyColName);\n }\n ArrayList valColNames = Lists.newArrayList();\n for (ExprNodeDesc valCol : valCols) {\n String colName = valCol.getExprString();\n valColNames.add(colName);\n colExprMap.put(Utilities.ReduceField.VALUE + \".\" + colName, valCol);\n if (nameMapping.containsKey(colName)) {\n computedFields.add(nameMapping.get(colName));\n }\n nameMapping.put(colName, Utilities.ReduceField.VALUE + \".\" + colName);\n }\n // Create Key/Value TableDesc. When the operator plan is split into MR tasks,\n // the reduce operator will initialize Extract operator with information\n // from Key and Value TableDesc\n List fields = PlanUtils.getFieldSchemasFromColumnList(keyCols, keyColNames, 0, \"\");\n TableDesc keyTable = PlanUtils.getReduceKeyTableDesc(fields, orderStr, nullOrderStr);\n List valFields = PlanUtils.getFieldSchemasFromColumnList(valCols, valColNames, 0, \"\");\n TableDesc valueTable = PlanUtils.getReduceValueTableDesc(valFields);\n List> distinctColumnIndices = Lists.newArrayList();\n // Number of reducers is set to default (-1)\n ReduceSinkDesc rsConf = new ReduceSinkDesc(keyCols, keyCols.size(), valCols, keyColNames, distinctColumnIndices, valColNames, -1, partCols, -1, keyTable, valueTable, writeType);\n rsConf.setBucketCols(bucketColumns);\n rsConf.setNumBuckets(numBuckets);\n rsConf.getComputedFields().addAll(computedFields);\n ArrayList signature = new ArrayList<>();\n for (int index = 0; index < parent.getSchema().getSignature().size(); index++) {\n ColumnInfo colInfo = new ColumnInfo(parent.getSchema().getSignature().get(index));\n colInfo.setInternalName(nameMapping.get(colInfo.getInternalName()));\n signature.add(colInfo);\n }\n ReduceSinkOperator op = (ReduceSinkOperator) OperatorFactory.getAndMakeChild(rsConf, new RowSchema(signature), parent);\n rsConf.addComputedField(Utilities.ReduceField.KEY + \".\" + BUCKET_SORT_EXPRESSION.apply(allCols).getExprString());\n for (Function, ExprNodeDesc> customSortExpr : customSortExprs) {\n rsConf.addComputedField(Utilities.ReduceField.KEY + \".\" + customSortExpr.apply(allCols).getExprString());\n }\n op.setColumnExprMap(colExprMap);\n return op;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void createSplitJournalEntriesAndReversalsForLoan(Office office, String currencyCode, List splitAccountsHolder, JournalAmountHolder totalAccountHolder, Long loanProductId, Long paymentTypeId, Long loanId, String transactionId, LocalDate transactionDate, Boolean isReversal) {\n splitAccountsHolder.forEach(journalItemHolder -> {\n final GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, journalItemHolder.getAccountType(), paymentTypeId);\n if (isReversal) {\n createCreditJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, journalItemHolder.getAmount());\n } else {\n createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, journalItemHolder.getAmount());\n }\n });\n final GLAccount totalAccount = getLinkedGLAccountForLoanProduct(loanProductId, totalAccountHolder.getAccountType(), paymentTypeId);\n if (isReversal) {\n createDebitJournalEntryForLoan(office, currencyCode, totalAccount, loanId, transactionId, transactionDate, totalAccountHolder.getAmount());\n } else {\n createCreditJournalEntryForLoan(office, currencyCode, totalAccount, loanId, transactionId, transactionDate, totalAccountHolder.getAmount());\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "/**\n * Updates an existing incident's status.\n */\npublic Urn raiseIncident(@Nonnull OperationContext opContext, @Nonnull final IncidentType type, @Nullable final String customType, @Nullable final Integer priority, @Nullable final String title, @Nullable final String description, @Nonnull final List entityUrns, @Nullable final IncidentSource source, @Nonnull final Urn actor, @Nullable final String message) throws Exception {\n Objects.requireNonNull(type, \"type must not be null\");\n Objects.requireNonNull(entityUrns, \"entityUrns must not be null\");\n Objects.requireNonNull(actor, \"actor must not be null\");\n final IncidentKey key = new IncidentKey();\n final String id = UUID.randomUUID().toString();\n key.setId(id);\n final Urn urn = EntityKeyUtils.convertEntityKeyToUrn(key, Constants.INCIDENT_ENTITY_NAME);\n final IncidentInfo newInfo = new IncidentInfo();\n newInfo.setType(type);\n newInfo.setCustomType(customType, SetMode.IGNORE_NULL);\n newInfo.setPriority(priority, SetMode.IGNORE_NULL);\n newInfo.setTitle(title, SetMode.IGNORE_NULL);\n newInfo.setDescription(description, SetMode.IGNORE_NULL);\n newInfo.setEntities(new UrnArray(entityUrns));\n newInfo.setSource(source, SetMode.IGNORE_NULL);\n newInfo.setStatus(new IncidentStatus().setState(IncidentState.ACTIVE).setMessage(message, SetMode.IGNORE_NULL).setLastUpdated(new AuditStamp().setActor(actor).setTime(System.currentTimeMillis())));\n newInfo.setCreated(new AuditStamp().setActor(actor).setTime(System.currentTimeMillis()));\n this.entityClient.ingestProposal(opContext, AspectUtils.buildMetadataChangeProposal(urn, Constants.INCIDENT_INFO_ASPECT_NAME, newInfo), false);\n return urn;\n}", "smellKey": "S107", "smellId": null, "repo": "patotskiy_datahub", "language": "java"} {"function": "/**\n * As more resources are needed for preemption, saved AMContainers has to be\n * rescanned. Such AMContainers can be preemptionCandidates based on resToObtain, but\n * maxAMCapacityForThisQueue resources will be still retained.\n *\n * @param clusterResource\n * @param preemptMap\n * @param skippedAMContainerlist\n * @param skippedAMSize\n * @param maxAMCapacityForThisQueue\n */\nprivate void preemptAMContainers(Resource clusterResource, Map> preemptMap, Map> curCandidates, List skippedAMContainerlist, Map resToObtainByPartition, Resource skippedAMSize, Resource maxAMCapacityForThisQueue, Resource totalPreemptionAllowed) {\n for (RMContainer c : skippedAMContainerlist) {\n // Got required amount of resources for preemption, can stop now\n if (resToObtainByPartition.isEmpty()) {\n break;\n }\n // Once skippedAMSize reaches down to maxAMCapacityForThisQueue,\n // container selection iteration for preemption will be stopped.\n if (Resources.lessThanOrEqual(rc, clusterResource, skippedAMSize, maxAMCapacityForThisQueue)) {\n break;\n }\n boolean preempted = CapacitySchedulerPreemptionUtils.tryPreemptContainerAndDeductResToObtain(rc, preemptionContext, resToObtainByPartition, c, clusterResource, preemptMap, curCandidates, totalPreemptionAllowed, preemptionContext.getCrossQueuePreemptionConservativeDRF());\n if (preempted) {\n Resources.subtractFrom(skippedAMSize, c.getAllocatedResource());\n }\n }\n skippedAMContainerlist.clear();\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private SnapshotUtils.SnapshotCopyMode createSnapshotsAtSource(Path sourcePath, String snapshotPrefix, boolean isSnapshotEnabled, HiveConf conf, SnapshotUtils.ReplSnapshotCount replSnapshotCount, FileList snapPathFileList, ArrayList prevSnaps, boolean isBootstrap) throws IOException {\n if (!isSnapshotEnabled) {\n LOG.info(\"Snapshot copy not enabled for path {} Will use normal distCp for copying data.\", sourcePath);\n return FALLBACK_COPY;\n }\n DistributedFileSystem sourceDfs = SnapshotUtils.getDFS(sourcePath, conf);\n try {\n if (isBootstrap) {\n // Delete any pre existing snapshots.\n SnapshotUtils.deleteSnapshotIfExists(sourceDfs, sourcePath, firstSnapshot(snapshotPrefix), conf);\n SnapshotUtils.deleteSnapshotIfExists(sourceDfs, sourcePath, secondSnapshot(snapshotPrefix), conf);\n allowAndCreateInitialSnapshot(sourcePath, snapshotPrefix, conf, replSnapshotCount, snapPathFileList, sourceDfs);\n return INITIAL_COPY;\n }\n if (prevSnaps.contains(sourcePath.toString())) {\n // We already created a snapshot for this, just refresh the latest snapshot and leave.\n sourceDfs.deleteSnapshot(sourcePath, secondSnapshot(snapshotPrefix));\n replSnapshotCount.incrementNumDeleted();\n SnapshotUtils.createSnapshot(sourceDfs, sourcePath, secondSnapshot(snapshotPrefix), conf);\n replSnapshotCount.incrementNumCreated();\n snapPathFileList.add(sourcePath.toString());\n return SnapshotUtils.isSnapshotAvailable(sourceDfs, sourcePath, snapshotPrefix, OLD_SNAPSHOT, conf) ? DIFF_COPY : INITIAL_COPY;\n }\n // check if second snapshot exists.\n boolean isSecondSnapAvlb = SnapshotUtils.isSnapshotAvailable(sourceDfs, sourcePath, snapshotPrefix, OLD_SNAPSHOT, conf);\n if (isSecondSnapAvlb) {\n sourceDfs.deleteSnapshot(sourcePath, firstSnapshot(snapshotPrefix));\n replSnapshotCount.incrementNumDeleted();\n sourceDfs.renameSnapshot(sourcePath, secondSnapshot(snapshotPrefix), firstSnapshot(snapshotPrefix));\n SnapshotUtils.createSnapshot(sourceDfs, sourcePath, secondSnapshot(snapshotPrefix), conf);\n replSnapshotCount.incrementNumCreated();\n snapPathFileList.add(sourcePath.toString());\n return DIFF_COPY;\n } else {\n // Check if first snapshot is available\n boolean isFirstSnapshotAvailable = SnapshotUtils.isSnapshotAvailable(sourceDfs, sourcePath, snapshotPrefix, NEW_SNAPSHOT, conf);\n if (isFirstSnapshotAvailable) {\n sourceDfs.renameSnapshot(sourcePath, secondSnapshot(snapshotPrefix), firstSnapshot(snapshotPrefix));\n SnapshotUtils.createSnapshot(sourceDfs, sourcePath, secondSnapshot(snapshotPrefix), conf);\n replSnapshotCount.incrementNumCreated();\n snapPathFileList.add(sourcePath.toString());\n return DIFF_COPY;\n } else {\n allowAndCreateInitialSnapshot(sourcePath, snapshotPrefix, conf, replSnapshotCount, snapPathFileList, sourceDfs);\n return INITIAL_COPY;\n }\n }\n } catch (FileNotFoundException fnf) {\n // Source deleted is already handled and is not an abnormal scenario, log and return.\n LOG.debug(\"Can not enable snapshot for path: {}\", sourcePath, fnf);\n return FALLBACK_COPY;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static SavingsAccountTransactionData importInstance(BigDecimal transactionAmount, LocalDate transactionDate, Long paymentTypeId, String accountNumber, String checkNumber, String routingCode, String receiptNumber, String bankNumber, Long savingsAccountId, SavingsAccountTransactionEnumData transactionType, Integer rowIndex, String locale, String dateFormat) {\n SavingsAccountTransactionData data = createImport(transactionType, null, savingsAccountId, accountNumber, transactionDate, transactionAmount, false, transactionDate, false, false);\n data.rowIndex = rowIndex;\n data.paymentTypeId = paymentTypeId;\n data.checkNumber = checkNumber;\n data.routingCode = routingCode;\n data.receiptNumber = receiptNumber;\n data.bankNumber = bankNumber;\n data.locale = locale;\n data.dateFormat = dateFormat;\n return data;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static String restoreIndices(@Nonnull OperationContext systemOperationContext, @Nonnull ResourceContext resourceContext, @Nonnull String aspectName, @Nullable String urn, @Nullable String urnLike, @Nullable Integer start, @Nullable Integer batchSize, @Nullable Integer limit, @Nullable Long gePitEpochMs, @Nullable Long lePitEpochMs, @Nonnull Authorizer authorizer, @Nonnull EntityService entityService) {\n EntitySpec resourceSpec = null;\n if (StringUtils.isNotBlank(urn)) {\n Urn resource = UrnUtils.getUrn(urn);\n resourceSpec = new EntitySpec(resource.getEntityType(), resource.toString());\n }\n final Authentication auth = AuthenticationContext.getAuthentication();\n final OperationContext opContext = OperationContext.asSession(systemOperationContext, RequestContext.builder().buildRestli(auth.getActor().toUrnStr(), resourceContext, \"restoreIndices\", List.of()), authorizer, auth, true);\n if (!isAPIAuthorized(opContext, PoliciesConfig.RESTORE_INDICES_PRIVILEGE, resourceSpec)) {\n throw new RestLiServiceException(HttpStatus.S_403_FORBIDDEN, \"User is unauthorized to restore indices.\");\n }\n RestoreIndicesArgs args = new RestoreIndicesArgs().aspectName(aspectName).urnLike(urnLike).urn(urn).start(start).batchSize(batchSize).limit(limit).gePitEpochMs(gePitEpochMs).lePitEpochMs(lePitEpochMs);\n Map result = new HashMap<>();\n result.put(\"args\", args);\n result.put(\"result\", entityService.restoreIndices(opContext, args, log::info).stream().map(RestoreIndicesResult::toString).collect(Collectors.joining(\"\\n\")));\n return result.toString();\n}", "smellKey": "S107", "smellId": null, "repo": "patotskiy_datahub", "language": "java"} {"function": "private LogicalPlanBuilder convergeAggregationSource(List sourceNodeList, AggregationStep curStep, Ordering scanOrder, GroupByTimeParameter groupByTimeParameter, Set aggregationExpressions, LinkedHashMap> crossGroupByExpressions, List tagKeys, Map, LinkedHashMap>> tagValuesToGroupedTimeseriesOperands){\r\n if (curStep.isOutputPartial()) {\r\n if (groupByTimeParameter != null && groupByTimeParameter.hasOverlap()) {\r\n curStep = crossGroupByExpressions != null ? AggregationStep.INTERMEDIATE : AggregationStep.FINAL;\r\n this.root = convergeWithTimeJoin(sourceNodeList, scanOrder);\r\n this.root = createSlidingWindowAggregationNode(this.getRoot(), aggregationExpressions, groupByTimeParameter, curStep, scanOrder);\r\n if (crossGroupByExpressions != null) {\r\n curStep = AggregationStep.FINAL;\r\n if (tagKeys != null) {\r\n this.root = createGroupByTagNode(tagKeys, tagValuesToGroupedTimeseriesOperands, crossGroupByExpressions.keySet(), Collections.singletonList(this.getRoot()), curStep, groupByTimeParameter, scanOrder);\r\n } else {\r\n this.root = createGroupByTLevelNode(Collections.singletonList(this.getRoot()), crossGroupByExpressions, curStep, groupByTimeParameter, scanOrder);\r\n }\r\n }\r\n } else {\r\n if (tagKeys != null) {\r\n curStep = AggregationStep.FINAL;\r\n this.root = createGroupByTagNode(tagKeys, tagValuesToGroupedTimeseriesOperands, crossGroupByExpressions.keySet(), sourceNodeList, curStep, groupByTimeParameter, scanOrder);\r\n } else if (crossGroupByExpressions != null) {\r\n curStep = AggregationStep.FINAL;\r\n this.root = createGroupByTLevelNode(sourceNodeList, crossGroupByExpressions, curStep, groupByTimeParameter, scanOrder);\r\n }\r\n }\r\n } else {\r\n this.root = convergeWithTimeJoin(sourceNodeList, scanOrder);\r\n }\r\n return this;\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Producer createHttpProducer(CamelContext camelContext, OpenAPI openApi, Operation operation, String host, String verb, String path, String queryParameters, String consumes, String produces, String componentName, Map parameters) throws Exception{\r\n LOG.debug(\"Using OpenApi operation: {} with {} {}\", operation, verb, path);\r\n RestProducerFactory factory = (RestProducerFactory) parameters.remove(\"restProducerFactory\");\r\n if (factory != null) {\r\n LOG.debug(\"Using RestProducerFactory: {}\", factory);\r\n if (produces == null) {\r\n StringJoiner producesBuilder = new StringJoiner(\",\");\r\n List list = new ArrayList<>();\r\n if (operation.getResponses() != null) {\r\n for (ApiResponse response : operation.getResponses().values()) {\r\n if (response.getContent() != null) {\r\n for (String mediaType : response.getContent().keySet()) {\r\n producesBuilder.add(mediaType);\r\n }\r\n }\r\n }\r\n }\r\n produces = producesBuilder.length() == 0 ? null : producesBuilder.toString();\r\n }\r\n if (consumes == null) {\r\n StringJoiner consumesBuilder = new StringJoiner(\",\");\r\n if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {\r\n for (String mediaType : operation.getRequestBody().getContent().keySet()) {\r\n consumesBuilder.add(mediaType);\r\n }\r\n }\r\n consumes = consumesBuilder.length() == 0 ? null : consumesBuilder.toString();\r\n }\r\n String basePath;\r\n String uriTemplate;\r\n if (host == null) {\r\n host = RestOpenApiSupport.getHostFromOasDocument(openApi);\r\n basePath = RestOpenApiSupport.getBasePathFromOasDocument(openApi);\r\n uriTemplate = path;\r\n } else {\r\n basePath = path;\r\n uriTemplate = null;\r\n }\r\n RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, null, componentName);\r\n return factory.createProducer(camelContext, host, verb, basePath, uriTemplate, queryParameters, consumes, produces, config, parameters);\r\n } else {\r\n throw new IllegalStateException(\"Cannot find RestProducerFactory in Registry or as a Component to use\");\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ApplicationAttemptStateData newInstance(ApplicationAttemptId attemptId, Container container, Credentials attemptTokens, long startTime, RMAppAttemptState finalState, String finalTrackingUrl, String diagnostics, FinalApplicationStatus amUnregisteredFinalStatus, int exitStatus, long finishTime, Map resourceSecondsMap, Map preemptedResourceSecondsMap, int totalAllocatedContainers) {\n ApplicationAttemptStateData attemptStateData = Records.newRecord(ApplicationAttemptStateData.class);\n attemptStateData.setAttemptId(attemptId);\n attemptStateData.setMasterContainer(container);\n attemptStateData.setAppAttemptTokens(attemptTokens);\n attemptStateData.setState(finalState);\n attemptStateData.setFinalTrackingUrl(finalTrackingUrl);\n attemptStateData.setDiagnostics(diagnostics == null ? \"\" : diagnostics);\n attemptStateData.setStartTime(startTime);\n attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus);\n attemptStateData.setAMContainerExitStatus(exitStatus);\n attemptStateData.setFinishTime(finishTime);\n attemptStateData.setMemorySeconds(RMServerUtils.getOrDefault(resourceSecondsMap, ResourceInformation.MEMORY_MB.getName(), 0L));\n attemptStateData.setVcoreSeconds(RMServerUtils.getOrDefault(resourceSecondsMap, ResourceInformation.VCORES.getName(), 0L));\n attemptStateData.setPreemptedMemorySeconds(RMServerUtils.getOrDefault(preemptedResourceSecondsMap, ResourceInformation.MEMORY_MB.getName(), 0L));\n attemptStateData.setPreemptedVcoreSeconds(RMServerUtils.getOrDefault(preemptedResourceSecondsMap, ResourceInformation.VCORES.getName(), 0L));\n attemptStateData.setResourceSecondsMap(resourceSecondsMap);\n attemptStateData.setPreemptedResourceSecondsMap(preemptedResourceSecondsMap);\n attemptStateData.setTotalAllocatedContainers(totalAllocatedContainers);\n return attemptStateData;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private List fetchFilesFromInstant(HoodieInstant instantToRollback, String partitionPath, String basePath, String baseFileExtension, HoodieStorage storage, Option commitMetadataOptional, Boolean isCommitMetadataCompleted, HoodieTableType tableType) throws IOException {\n // go w/ commit metadata only for COW table. for MOR, we need to get associated log files when commit corresponding to base file is rolledback.\n if (isCommitMetadataCompleted && tableType == HoodieTableType.COPY_ON_WRITE) {\n return fetchFilesFromCommitMetadata(instantToRollback, partitionPath, basePath, commitMetadataOptional.get(), baseFileExtension, storage);\n } else {\n return fetchFilesFromListFiles(instantToRollback, partitionPath, basePath, baseFileExtension, storage);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private void scheduleTimer(TimerNode timerNode, TimerNodeMemory tm, SegmentMemory smem, LeftTupleSink sink, ReteEvaluator reteEvaluator, TimerService timerService, long timestamp, LeftTuple leftTuple, TupleSets trgLeftTuples, TupleSets stagedLeftTuples, Trigger trigger){\r\n if (trigger.hasNextFireTime() == null) {\r\n return;\r\n }\r\n if (trigger.hasNextFireTime().getTime() <= timestamp) {\r\n if (log.isTraceEnabled()) {\r\n log.trace(\"Timer Fire Now {}\", leftTuple);\r\n }\r\n LeftTuple childLeftTuple = doPropagateChildLeftTuple(sink, trgLeftTuples, stagedLeftTuples, leftTuple);\r\n if (childLeftTuple.getStagedType() != LeftTuple.NONE) {\r\n childLeftTuple.setContextObject(Boolean.TRUE);\r\n }\r\n trigger.nextFireTime();\r\n Date nextFireTime = trigger.hasNextFireTime();\r\n if (nextFireTime != null && nextFireTime.getTime() <= timestamp) {\r\n throw new IllegalStateException(\"Trigger.nextFireTime is not increasing\");\r\n }\r\n }\r\n if (trigger.hasNextFireTime() != null) {\r\n TimerNodeJob job = new TimerNodeJob();\r\n TimerNodeJobContext jobCtx = new TimerNodeJobContext(timerNode.getId(), trigger, leftTuple, tm, sink, smem.getPathMemories(), reteEvaluator);\r\n DefaultJobHandle jobHandle = (DefaultJobHandle) timerService.scheduleJob(job, jobCtx, trigger);\r\n leftTuple.setContextObject(jobHandle);\r\n if (log.isTraceEnabled()) {\r\n log.trace(\"Timer Scheduled {}\", leftTuple);\r\n }\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected String buildFilename(final IVariables variables, final String realFileName, final String realExtension, final String transformnr, final String partnr, final String splitnr, final boolean beamContext, final String transformId, final int bundleNr, final Date date, final boolean ziparchive, final boolean showSamples, final TextFileOutputMeta meta) {\n SimpleDateFormat daf = new SimpleDateFormat();\n // Replace possible environment variables...\n String retval = realFileName;\n if (meta.isFileAsCommand()) {\n return retval;\n }\n Date now = date == null ? new Date() : date;\n if (meta.isSpecifyingFormat() && !Utils.isEmpty(meta.getDateTimeFormat())) {\n daf.applyPattern(meta.getDateTimeFormat());\n String dt = daf.format(now);\n retval += dt;\n } else {\n if (meta.isDateInFilename()) {\n if (showSamples) {\n daf.applyPattern(\"yyyMMdd\");\n String d = daf.format(now);\n retval += \"_\" + d;\n } else {\n retval += \"_\";\n }\n }\n if (meta.isTimeInFilename()) {\n if (showSamples) {\n daf.applyPattern(\"HHmmss\");\n String t = daf.format(now);\n retval += \"_\" + t;\n } else {\n retval += \"_\";\n }\n }\n }\n if (meta.isTransformNrInFilename()) {\n retval += \"_\" + transformnr;\n }\n if (meta.isPartNrInFilename()) {\n retval += \"_\" + partnr;\n }\n if (meta.getSplitEvery(variables) > 0) {\n retval += \"_\" + splitnr;\n }\n // In a Beam context, always add the transform ID and bundle number\n //\n if (beamContext) {\n retval += \"_\" + transformId + \"_\" + bundleNr;\n }\n if (\"Zip\".equals(meta.getFileCompression())) {\n if (ziparchive) {\n retval += \".zip\";\n } else {\n if (realExtension != null && realExtension.length() != 0) {\n retval += \".\" + realExtension;\n }\n }\n } else {\n if (realExtension != null && realExtension.length() != 0) {\n retval += \".\" + realExtension;\n }\n if (\"GZip\".equals(meta.getFileCompression())) {\n retval += \".gz\";\n }\n }\n return retval;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone, String userUUID, User.Source source) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Creating user: \" + userName + \", accountId: \" + accountId + \" timezone:\" + timezone);\n }\n passwordPolicy.verifyIfPasswordCompliesWithPasswordPolicies(password, userName, getAccount(accountId).getDomainId());\n String encodedPassword = null;\n for (UserAuthenticator authenticator : _userPasswordEncoders) {\n encodedPassword = authenticator.encode(password);\n if (encodedPassword != null) {\n break;\n }\n }\n if (encodedPassword == null) {\n throw new CloudRuntimeException(\"Failed to encode password\");\n }\n if (userUUID == null) {\n userUUID = UUID.randomUUID().toString();\n }\n UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone, userUUID, source));\n CallContext.current().putContextParameter(User.class, user.getUuid());\n return user;\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "/**\n * createPKIData creates PKIData\n *\n * @param rValue CRMF/PKCS10 request.\n * @param format either crmf or pkcs10\n * @return request in PKIData\n */\nstatic PKIData createPKIData(String useSharedSecret, String[] rValue, String format, String transactionMgtEnable, String transactionMgtId, String identificationEnable, String identification, String identityProofEnable, String identityProofSharedSecret, String witnessSharedSecret, String identityProofV2Enable, String identityProofV2hashAlg, String identityProofV2macAlg, String popLinkWitnessV2Enable, String popLinkWitnessV2keyGenAlg, String popLinkWitnessV2macAlg, SEQUENCE controlSeq, SEQUENCE otherMsgSeq, int bpid, CryptoToken token, PrivateKey privk) {\n String method = \"createPKIData: \";\n System.out.println(method + \"begins\");\n PKIData pkidata = null;\n try {\n TaggedRequest trq = null;\n PKCS10 pkcs = null;\n CertReqMsg certReqMsg = null;\n CertReqMsg new_certReqMsg = null;\n CertRequest new_certreq = null;\n PopLinkWitnessV2 popLinkWitnessV2Control = null;\n if (popLinkWitnessV2Enable.equals(\"true\")) {\n popLinkWitnessV2Control = createPopLinkWitnessV2Attr(bpid, controlSeq, witnessSharedSecret, popLinkWitnessV2keyGenAlg, popLinkWitnessV2macAlg, (identificationEnable.equals(\"true\")) ? identification : null);\n if (popLinkWitnessV2Control == null) {\n System.out.println(method + \"createPopLinkWitnessV2Attr returned null...exit\");\n System.exit(1);\n }\n }\n // create CMC req\n SEQUENCE reqSequence = new SEQUENCE();\n try {\n for (int k = 0; k < rValue.length; k++) {\n System.out.println(\"k=\" + k);\n String asciiBASE64Blob = rValue[k];\n byte[] decodedBytes = Utils.base64decode(asciiBASE64Blob);\n if (format.equals(\"crmf\")) {\n System.out.println(method + \" format: crmf\");\n ByteArrayInputStream reqBlob = new ByteArrayInputStream(decodedBytes);\n SEQUENCE crmfMsgs = null;\n try {\n crmfMsgs = (SEQUENCE) new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(reqBlob);\n } catch (InvalidBERException ee) {\n System.out.println(method + \" This is not a crmf request. Or this request has an error.\");\n System.exit(1);\n }\n certReqMsg = (CertReqMsg) crmfMsgs.elementAt(0);\n CertRequest certReq = certReqMsg.getCertReq();\n CertTemplate certTemplate = certReq.getCertTemplate();\n if (useSharedSecret.equals(\"true\")) {\n skiExtn = (SubjectKeyIdentifierExtension) CryptoUtil.getExtensionFromCertTemplate(certTemplate, PKIXExtensions.SubjectKey_Id);\n if (skiExtn != null) {\n System.out.println(method + \" SubjectKeyIdentifier extension found in use_shared_secret request\");\n } else {\n System.out.println(method + \" SubjectKeyIdentifier extension missing in use_shared_secret request\");\n System.exit(1);\n }\n }\n if (popLinkWitnessV2Enable.equals(\"true\")) {\n System.out.println(method + \"popLinkWitnessV2 enabled. reconstructing crmf\");\n //crmf reconstruction to include PopLinkWitnessV2 control\n INTEGER certReqId = certReq.getCertReqId();\n SEQUENCE controls = certReq.getControls();\n controls.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_popLinkWitnessV2, popLinkWitnessV2Control));\n new_certreq = new CertRequest(certReqId, certTemplate, controls);\n // recalculate signing POP, if it had one\n ProofOfPossession new_pop = null;\n if (certReqMsg.hasPop()) {\n if (privk == null) {\n System.out.println(method + \"privateKey not found; can't regenerate new POP\");\n System.exit(1);\n }\n if (token == null) {\n System.out.println(method + \"token not found; can't regenerate new POP\");\n System.exit(1);\n }\n new_pop = createNewPOP(certReqMsg, new_certreq, token, privk);\n } else {\n // !hasPop\n System.out.println(method + \"old certReqMsg has no pop, so will the new certReqMsg\");\n }\n new_certReqMsg = new CertReqMsg(new_certreq, new_pop, null);\n SEQUENCE seq = new SEQUENCE();\n seq.addElement(new_certReqMsg);\n byte[] encodedNewCrmfMessage = ASN1Util.encode(seq);\n String b64String = Utils.base64encode(encodedNewCrmfMessage, true);\n System.out.println(method + \"new CRMF b64encode completes.\");\n System.out.println(Cert.REQUEST_HEADER);\n System.out.println(b64String);\n System.out.println(Cert.REQUEST_FOOTER);\n System.out.println(\"\");\n trq = new TaggedRequest(TaggedRequest.CRMF, null, new_certReqMsg);\n } else {\n // !popLinkWitnessV2Enable\n trq = new TaggedRequest(TaggedRequest.CRMF, null, certReqMsg);\n }\n } else if (format.equals(\"pkcs10\")) {\n System.out.println(method + \" format: pkcs10\");\n try {\n pkcs = new PKCS10(decodedBytes, true);\n } catch (Exception e2) {\n System.out.println(method + \" Excception:\" + e2.toString());\n System.exit(1);\n }\n if (useSharedSecret.equals(\"true\")) {\n try {\n skiExtn = (SubjectKeyIdentifierExtension) CryptoUtil.getExtensionFromPKCS10(pkcs, \"SubjectKeyIdentifier\");\n } catch (IOException e) {\n System.out.println(method + \"getting SubjectKeyIdentifiere...\" + e);\n }\n if (skiExtn != null) {\n System.out.println(method + \" SubjectKeyIdentifier extension found\");\n } else {\n System.out.println(method + \" SubjectKeyIdentifier extension missing\");\n System.exit(1);\n }\n }\n ByteArrayInputStream crInputStream = new ByteArrayInputStream(pkcs.toByteArray());\n CertificationRequest cr = (CertificationRequest) CertificationRequest.getTemplate().decode(crInputStream);\n if (popLinkWitnessV2Enable.equals(\"true\")) {\n System.out.println(method + \"popLinkWitnessV2 enabled. reconstructing pkcs#10\");\n //pkcs#10 reconstruction to include PopLinkWitnessV2 control\n CertificationRequestInfo certReqInfo = cr.getInfo();\n INTEGER version = certReqInfo.getVersion();\n Name subject = certReqInfo.getSubject();\n SubjectPublicKeyInfo spkInfo = certReqInfo.getSubjectPublicKeyInfo();\n /*\n AlgorithmIdentifier alg = spkInfo.getAlgorithmIdentifier();\n SignatureAlgorithm signAlg = SignatureAlgorithm.fromOID(alg.getOID());\n if (signAlg == SignatureAlgorithm.RSASignatureWithSHA256Digest) {\n System.out.println(method +\n \"signAlg == SignatureAlgorithm.RSASignatureWithSHA256Digest\");\n } else {\n System.out.println(method +\n \"signAlg == \" + signAlg.toString());\n }\n */\n Attribute attr = new Attribute(OBJECT_IDENTIFIER.id_cmc_popLinkWitnessV2, popLinkWitnessV2Control);\n SET attrs = certReqInfo.getAttributes();\n if (attrs == null) {\n attrs = new SET();\n }\n attrs.addElement(attr);\n System.out.println(method + \" new pkcs#10 Attribute created for id_cmc_popLinkWitnessV2.\");\n SignatureAlgorithm signAlg = getSigningAlgFromPrivate(privk);\n if (signAlg == null) {\n System.out.println(method + \"signAlg not found\");\n System.exit(1);\n }\n CertificationRequestInfo new_certReqInfo = new CertificationRequestInfo(version, subject, spkInfo, attrs);\n System.out.println(method + \" new pkcs#10 CertificationRequestInfo created.\");\n CertificationRequest new_certRequest = new CertificationRequest(new_certReqInfo, privk, signAlg);\n System.out.println(method + \"new pkcs#10 CertificationRequest created.\");\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n new_certRequest.encode(bos);\n byte[] bb = bos.toByteArray();\n System.out.println(method + \"calling Utils.b64encode.\");\n String b64String = Utils.base64encode(bb, true);\n System.out.println(method + \"new PKCS#10 b64encode completes.\");\n System.out.println(Cert.REQUEST_HEADER);\n System.out.println(b64String);\n System.out.println(Cert.REQUEST_FOOTER);\n System.out.println(\"\");\n TaggedCertificationRequest tcr = new TaggedCertificationRequest(new INTEGER(bpid++), new_certRequest);\n trq = new TaggedRequest(TaggedRequest.PKCS10, tcr, null);\n } else {\n // !popLinkWitnessV2Enable\n TaggedCertificationRequest tcr = new TaggedCertificationRequest(new INTEGER(bpid++), cr);\n trq = new TaggedRequest(TaggedRequest.PKCS10, tcr, null);\n }\n } else {\n System.out.println(method + \" Unrecognized request format: \" + format);\n System.exit(1);\n }\n reqSequence.addElement(trq);\n }\n } catch (Exception e) {\n System.out.println(method + \" Exception:\" + e);\n System.exit(1);\n }\n if (transactionMgtEnable.equals(\"true\"))\n bpid = addTransactionAttr(bpid, controlSeq, transactionMgtId, format, pkcs, certReqMsg);\n if (identificationEnable.equals(\"true\")) {\n bpid = addIdentificationAttr(bpid, controlSeq, identification);\n }\n // for identityProof, it's either V2 or not V2; can't be both\n // if both, V2 takes precedence\n if (identityProofV2Enable.equals(\"true\")) {\n bpid = addIdentityProofV2Attr(bpid, controlSeq, reqSequence, witnessSharedSecret, (identificationEnable.equals(\"true\")) ? identification : null, identityProofV2hashAlg, identityProofV2macAlg);\n } else if (identityProofEnable.equals(\"true\")) {\n bpid = addIdentityProofAttr(bpid, controlSeq, reqSequence, identityProofSharedSecret);\n }\n pkidata = new PKIData(controlSeq, reqSequence, new SEQUENCE(), otherMsgSeq);\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n return pkidata;\n}", "smellKey": "S107", "smellId": null, "repo": "dogtagpki_pki", "language": "java"} {"function": "private Long restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, String secStorageUrl, String secStorageDir, String backupName, long wait, String nfsVersion) throws Exception {\n String secondaryMountPoint = mountService.getMountPoint(secStorageUrl, null);\n String srcOVAFileName;\n String srcOVFFileName;\n srcOVAFileName = secondaryMountPoint + \"/\" + secStorageDir + \"/\" + backupName + \".\" + ImageFormat.OVA.getFileExtension();\n srcOVFFileName = secondaryMountPoint + \"/\" + secStorageDir + \"/\" + backupName + \".ovf\";\n String snapshotDir = \"\";\n if (backupName.contains(\"/\")) {\n snapshotDir = backupName.split(\"/\")[0];\n }\n File ovafile = new File(srcOVAFileName);\n File ovfFile = new File(srcOVFFileName);\n // String srcFileName = getOVFFilePath(srcOVAFileName);\n if (!ovfFile.exists()) {\n srcOVFFileName = getOVFFilePath(srcOVAFileName);\n if (srcOVFFileName == null && ovafile.exists()) {\n // volss: ova file exists; o/w can't do tar\n Script command = new Script(\"tar\", wait, logger);\n command.add(\"--no-same-owner\");\n command.add(\"-xf\", srcOVAFileName);\n command.setWorkDir(secondaryMountPoint + \"/\" + secStorageDir + \"/\" + snapshotDir);\n logger.info(\"Executing command: \" + command.toString());\n String result = command.execute();\n if (result != null) {\n String msg = \"Unable to unpack snapshot OVA file at: \" + srcOVAFileName;\n logger.error(msg);\n throw new Exception(msg);\n }\n srcOVFFileName = getOVFFilePath(srcOVAFileName);\n } else if (srcOVFFileName == null) {\n String msg = \"Unable to find snapshot OVA file at: \" + srcOVAFileName;\n logger.error(msg);\n throw new Exception(msg);\n }\n }\n if (srcOVFFileName == null) {\n String msg = \"Unable to locate OVF file in template package directory: \" + srcOVAFileName;\n logger.error(msg);\n throw new Exception(msg);\n }\n VirtualMachineMO workerVm = null;\n try {\n hyperHost.importVmFromOVF(srcOVFFileName, newVolumeName, primaryDsMo, \"thin\", null);\n workerVm = hyperHost.findVmOnHyperHost(newVolumeName);\n if (workerVm == null) {\n throw new Exception(\"Unable to create container VM for volume creation\");\n }\n workerVm.tagAsWorkerVM();\n if (!primaryDsMo.getDatastoreType().equalsIgnoreCase(\"VVOL\")) {\n HypervisorHostHelper.createBaseFolderInDatastore(primaryDsMo, primaryDsMo.getDataCenterMor());\n workerVm.moveAllVmDiskFiles(primaryDsMo, HypervisorHostHelper.VSPHERE_DATASTORE_BASE_FOLDER, false);\n }\n workerVm.detachAllDisks();\n return _storage.getSize(srcOVFFileName);\n } finally {\n if (workerVm != null) {\n workerVm.detachAllDisksAndDestroy();\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "java"} {"function": "public static Path[] getDirectInsertDirectoryCandidates(FileSystem fs, Path path, int dpLevels, PathFilter filter, long writeId, int stmtId, Configuration conf, Boolean isBaseDir, AcidUtils.Operation acidOperation) throws IOException {\n int skipLevels = dpLevels;\n if (filter == null) {\n filter = new AcidUtils.IdPathFilter(writeId, stmtId);\n }\n if (skipLevels == 0) {\n return statusToPath(fs.listStatus(path, filter));\n }\n // TODO: for some reason, globStatus doesn't work for masks like \"...blah/*/delta_0000007_0000007*\"\n // the last star throws it off. So, for now, if stmtId is missing use recursion.\n // For the same reason, we cannot use it if we don't know isBaseDir. Currently, we don't\n // /want/ to know isBaseDir because that is error prone; so, it ends up never being used.\n if (stmtId < 0 || isBaseDir == null || (HiveConf.getBoolVar(conf, ConfVars.HIVE_MM_AVOID_GLOBSTATUS_ON_S3) && isS3(fs))) {\n return getDirectInsertDirectoryCandidatesRecursive(fs, path, skipLevels, filter);\n }\n return getDirectInsertDirectoryCandidatesGlobStatus(fs, path, skipLevels, filter, writeId, stmtId, isBaseDir, acidOperation);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static void displayForumsList(JspWriter out, MultiSilverpeasBundle resources, boolean admin, boolean moderator, boolean reader, int currentForumId, String call, ForumsSessionController fsc, String categoryId, String nom, String description, boolean isSubscriberByInheritance){\r\n try {\r\n Forum[] forums = fsc.getForumsListByCategory(categoryId);\r\n if (forums != null) {\r\n out.println(\"\");\r\n out.print(\"\" + nom);\r\n if (description != null && description.length() > 0) {\r\n out.print(\" - \" + description + \"\");\r\n }\r\n out.println(\"\");\r\n if (admin || moderator) {\r\n out.print(\"\");\r\n if (categoryId != null) {\r\n out.print(\"\");\r\n out.print(\"\\\"\"\");\r\n out.print(\"  \");\r\n out.print(\"\");\r\n out.print(\"\\\"\"\");\r\n out.print(\" \");\r\n out.print(\"\");\r\n }\r\n out.println(\"\");\r\n }\r\n out.println(\"\");\r\n scanForum(forums, resources, out, currentForumId, call, admin, moderator, reader, currentForumId, 0, fsc, isSubscriberByInheritance);\r\n }\r\n } catch (IOException ioe) {\r\n SilverLogger.getLogger(ForumListHelper.class).error(ioe);\r\n }\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Append formatted value to outStr buffer\n * @param ctx\n * @param po\n * @param trxName\n * @param useColumnDateFormat\n * @param useMsgForBoolean\n * @param token\n * @param format\n * @param colToken\n * @param value\n * @param outStr\n */\nprivate static void appendValue(Properties ctx, PO po, String trxName, boolean useColumnDateFormat, boolean useMsgForBoolean, String token, String format, MColumn colToken, Object value, StringBuilder outStr) {\n if (format != null && format.length() > 0) {\n String foreignTable = colToken != null ? colToken.getReferenceTableName() : null;\n if (value instanceof String && token.endsWith(\"_ID\") && Env.isGlobalVariable(token)) {\n try {\n int id = Integer.parseInt((String) value);\n value = id;\n foreignTable = token.substring(1);\n foreignTable = foreignTable.substring(0, foreignTable.length() - 3);\n if (MTable.get(Env.getCtx(), foreignTable) == null)\n foreignTable = null;\n } catch (Exception ex) {\n }\n }\n if (value instanceof Integer && (Integer) value >= 0 && (!Util.isEmpty(foreignTable) || token.equalsIgnoreCase(po.get_TableName() + \"_ID\"))) {\n int tblIndex = format.indexOf(\".\");\n String tableName = null;\n if (tblIndex > 0)\n tableName = format.substring(0, tblIndex);\n else\n tableName = foreignTable;\n MTable table = MTable.get(ctx, tableName);\n String keyCol = tableName + \"_ID\";\n boolean isSubTypeTable = false;\n if (!Util.isEmpty(foreignTable) && !tableName.equalsIgnoreCase(foreignTable)) {\n // verify if is a subtype table\n if (table.getKeyColumns() != null && table.getKeyColumns().length == 1 && table.getKeyColumns()[0].equals(foreignTable + \"_ID\")) {\n isSubTypeTable = true;\n keyCol = foreignTable + \"_ID\";\n }\n }\n if (table != null && (isSubTypeTable || tableName.equalsIgnoreCase(foreignTable) || tableName.equalsIgnoreCase(po.get_TableName()))) {\n String columnName = tblIndex > 0 ? format.substring(tblIndex + 1) : format;\n MColumn column = table.getColumn(columnName);\n if (column != null) {\n if (column.isSecure()) {\n outStr.append(\"********\");\n } else {\n String strValue = DB.getSQLValueString(trxName, \"SELECT \" + columnName + \" FROM \" + tableName + \" WHERE \" + keyCol + \"=?\", (Integer) value);\n if (strValue != null)\n outStr.append(strValue);\n }\n }\n }\n } else if (value instanceof String && !Util.isEmpty((String) value) && !Util.isEmpty(foreignTable) && foreignTable.equals(MRefList.Table_Name) && !Util.isEmpty(format)) {\n int refID = colToken.getAD_Reference_Value_ID();\n if (format.equals(\"Name\"))\n outStr.append(MRefList.getListName(getCtx(), refID, (String) value));\n else if (format.equals(\"Description\"))\n outStr.append(MRefList.getListDescription(getCtx(), DB.getSQLValueStringEx(null, \"SELECT Name FROM AD_Reference WHERE AD_Reference_ID = ?\", refID), (String) value));\n } else if (value instanceof Date) {\n SimpleDateFormat df = new SimpleDateFormat(format);\n outStr.append(df.format((Date) value));\n } else if (value instanceof Number) {\n DecimalFormat df = new DecimalFormat(format);\n outStr.append(df.format(((Number) value).doubleValue()));\n } else {\n MessageFormat mf = new MessageFormat(format);\n outStr.append(mf.format(value));\n }\n } else {\n if (colToken != null && colToken.isSecure()) {\n value = \"********\";\n } else if (colToken != null && colToken.getAD_Reference_ID() == DisplayType.YesNo && value instanceof Boolean) {\n if (useMsgForBoolean) {\n if (((Boolean) value).booleanValue())\n value = Msg.getMsg(Env.getCtx(), \"Yes\");\n else\n value = Msg.getMsg(Env.getCtx(), \"No\");\n } else {\n value = ((Boolean) value).booleanValue() ? \"Y\" : \"N\";\n }\n } else if (colToken != null && DisplayType.isDate(colToken.getAD_Reference_ID()) && value instanceof Date && useColumnDateFormat) {\n SimpleDateFormat sdf = DisplayType.getDateFormat(colToken.getAD_Reference_ID());\n value = sdf.format(value);\n } else if (value instanceof BigDecimal) {\n int precision = MClient.get(Env.getCtx()).getAcctSchema().getStdPrecision();\n value = ((BigDecimal) value).setScale(precision, RoundingMode.HALF_UP).toPlainString();\n }\n outStr.append(value.toString());\n }\n}", "smellKey": "S107", "smellId": null, "repo": "idempiere_idempiere", "language": "java"} {"function": "public static Query7Def query(String pkg, String name, Class type1, Class type2, Class type3, Class type4, Class type5, Class type6, Class type7){\r\n return new Query7DefImpl<>(VIEW_BUILDER, pkg, name, type1, type2, type3, type4, type5, type6, type7);\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "void fireBeforeVariableChanged(String id, String instanceId, Object oldValue, Object newValue, List tags, KogitoProcessInstance processInstance, KogitoNodeInstance nodeInstance, KieRuntime kruntime);", "smellKey": "S107", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "private ColumnStreamData createRgColumnStreamData(int rgIx, boolean isLastRg, int colIx, StreamContext sctx, long cOffset, long endCOffset, boolean isCompressed, long unlockUntilCOffset) {\n ColumnStreamData cb = POOLS.csdPool.take();\n cb.incRef();\n if (isTracingEnabled) {\n LOG.trace(\"Getting data for column \" + colIx + \" \" + (isLastRg ? \"last \" : \"\") + \"RG \" + rgIx + \" stream \" + sctx.kind + \" at \" + sctx.offset + \", \" + sctx.length + \" index position \" + sctx.streamIndexOffset + \": \" + (isCompressed ? \"\" : \"un\") + \"compressed [\" + cOffset + \", \" + endCOffset + \")\");\n }\n trace.logStartStream(sctx.kind, cOffset, endCOffset, unlockUntilCOffset);\n return cb;\n}", "smellKey": "S107", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Stores a cookie to the response.\n *\n * @param req Incoming HttpServletRequest.\n * @param resp Outgoing HttpServletResponse.\n * @param cookieName Name of the cookie to be stored.\n * @param value Value of the cookie.\n * @param age Max age of the cookie.\n * @param sameSite SameSite attribute value for the cookie.\n * @param domain Domain of the cookie.\n */\npublic static void setCookie(HttpServletRequest req, HttpServletResponse resp, String cookieName, String value, Integer age, SameSiteCookie sameSite, String path, String domain) {\n CookieBuilder cookieBuilder = new CookieBuilder(cookieName, value);\n IdentityCookieConfig cookieConfig = IdentityUtil.getIdentityCookieConfig(cookieName);\n if (cookieConfig != null) {\n updateCookieConfig(cookieBuilder, cookieConfig, age, path, sameSite, domain);\n } else {\n cookieBuilder.setSecure(true).setHttpOnly(true).setPath(StringUtils.isNotBlank(path) ? path : ROOT_DOMAIN).setDomain(domain).setSameSite(sameSite);\n if (age != null && age > 0) {\n cookieBuilder.setMaxAge(age);\n }\n }\n resp.addCookie(cookieBuilder.build());\n}", "smellKey": "S107", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public static ApplicationSubmissionContext newApplicationSubmissionContext(ApplicationId applicationId, String applicationName, String queue, Priority priority, ContainerLaunchContext amContainer, boolean isUnmanagedAM, boolean cancelTokensWhenComplete, int maxAppAttempts, Resource resource) {\n return newApplicationSubmissionContext(applicationId, applicationName, queue, priority, amContainer, isUnmanagedAM, cancelTokensWhenComplete, maxAppAttempts, resource, null);\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public boolean updateLoadBalancerHealthMonitor(String projectUuid, String healthMonitorName, String type, int retry, int timeout, int interval, String httpMethod, String expectedCode, String urlPath) {\n try {\n Project project = (Project) getTungstenObject(Project.class, projectUuid);\n LoadbalancerHealthmonitor loadbalancerHealthmonitor = (LoadbalancerHealthmonitor) apiConnector.find(LoadbalancerHealthmonitor.class, project, healthMonitorName);\n LoadbalancerHealthmonitorType loadbalancerHealthmonitorType = new LoadbalancerHealthmonitorType();\n loadbalancerHealthmonitorType.setMonitorType(type);\n loadbalancerHealthmonitorType.setMaxRetries(retry);\n loadbalancerHealthmonitorType.setTimeout(timeout);\n loadbalancerHealthmonitorType.setDelay(interval);\n loadbalancerHealthmonitorType.setHttpMethod(httpMethod);\n loadbalancerHealthmonitorType.setExpectedCodes(expectedCode);\n loadbalancerHealthmonitorType.setUrlPath(urlPath);\n loadbalancerHealthmonitorType.setAdminState(true);\n loadbalancerHealthmonitor.setProperties(loadbalancerHealthmonitorType);\n Status status = apiConnector.update(loadbalancerHealthmonitor);\n status.ifFailure(errorHandler);\n return status.isSuccess();\n } catch (IOException e) {\n return false;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "apache_cloudstack", "language": "java"} {"function": "public static ExprViewItem expr(Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Variable var11, Variable var12, Predicate12 predicate){\r\n return new Expr12ViewItemImpl<>(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, new Predicate12.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Response delete(final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final DeleteOpParam op, final RecursiveParam recursive, final SnapshotNameParam snapshotName) throws IOException {\n final ClientProtocol cp = getRpcClientProtocol();\n switch(op.getValue()) {\n case DELETE:\n {\n final boolean b = cp.delete(fullpath, recursive.getValue());\n final String js = JsonUtil.toJsonString(\"boolean\", b);\n return Response.ok(js).type(MediaType.APPLICATION_JSON).build();\n }\n case DELETESNAPSHOT:\n {\n validateOpParams(op, snapshotName);\n cp.deleteSnapshot(fullpath, snapshotName.getValue());\n return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();\n }\n default:\n throw new UnsupportedOperationException(op + \" is not supported\");\n }\n}", "smellKey": "S107", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static ExprViewItem expr(String exprId, Variable var1, Variable var2, Variable var3, Variable var4, Variable var5, Variable var6, Variable var7, Variable var8, Variable var9, Variable var10, Variable var11, Variable var12, Variable var13, Predicate13 predicate){\r\n return new Expr13ViewItemImpl<>(exprId, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13, new Predicate13.Impl<>(predicate));\r\n}", "smellKey": "S107", "smellId": null, "repo": NaN, "language": "java"} {"function": "public NodeSet find(final XQueryWatchDog watchDog, final Comparison comparison, final DocumentSet docs, final NodeSet contextSet, final int axis, final QName qname, final Indexable value, final boolean mixedIndex) throws TerminatedException {\n final NodeSet result = new NewArrayNodeSet();\n if (qname == null) {\n findAll(watchDog, comparison, docs, contextSet, axis, null, value, result);\n } else {\n final List qnames = Collections.singletonList(qname);\n findAll(watchDog, comparison, docs, contextSet, axis, qnames, value, result);\n if (mixedIndex) {\n findAll(watchDog, comparison, docs, contextSet, axis, null, value, result);\n }\n }\n return result;\n}", "smellKey": "S107", "smellId": null, "repo": "eXist-db_exist", "language": "java"} {"function": "public static InterestRateChartSlabData template(final Collection periodTypes, final Collection entityTypeOptions, final Collection attributeNameOptions, final Collection conditionTypeOptions, final Collection incentiveTypeOptions, final Collection genderOptions, final Collection clientTypeOptions, final Collection clientClassificationOptions) {\n final Long id = null;\n final String description = null;\n final EnumOptionData periodType = null;\n final Integer fromPeriod = null;\n final Integer toPeriod = null;\n final BigDecimal amountRangeFrom = null;\n final BigDecimal amountRangeTo = null;\n final BigDecimal annualInterestRate = null;\n final CurrencyData currency = null;\n final Set incentivesData = null;\n return new InterestRateChartSlabData(id, description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currency, incentivesData, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "public static AppUserData importInstance(Long officeId, Long staffId, String username, String firstname, String lastname, String email, Boolean sendPasswordToEmail, Boolean passwordNeverExpires, List roleIds, Integer rowIndex) {\n return new AppUserData(officeId, staffId, username, firstname, lastname, email, sendPasswordToEmail, passwordNeverExpires, roleIds, rowIndex);\n}", "smellKey": "S107", "smellId": null, "repo": "apache_fineract", "language": "java"} {"function": "private void processingSqlBySettingAutoCommit(Exchange exchange) throws Exception{\r\n String sql = exchange.getIn().getBody(String.class);\r\n Connection conn = null;\r\n boolean autoCommit = false;\r\n boolean shouldCloseResources = true;\r\n try {\r\n conn = connectionStrategy.getConnection(dataSource);\r\n autoCommit = conn.getAutoCommit();\r\n if (autoCommit) {\r\n conn.setAutoCommit(false);\r\n }\r\n shouldCloseResources = createAndExecuteSqlStatement(exchange, sql, conn);\r\n conn.commit();\r\n } catch (Exception e) {\r\n try {\r\n if (conn != null) {\r\n conn.rollback();\r\n }\r\n } catch (Exception sqle) {\r\n LOG.warn(\"Error occurred during JDBC rollback. This exception will be ignored.\", sqle);\r\n }\r\n throw e;\r\n } finally {\r\n if (shouldCloseResources) {\r\n resetAutoCommit(conn, autoCommit);\r\n closeQuietly(conn);\r\n } else {\r\n final Connection finalConn = conn;\r\n final boolean finalAutoCommit = autoCommit;\r\n exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() {\r\n\r\n @Override\r\n public void onDone(Exchange exchange) {\r\n resetAutoCommit(finalConn, finalAutoCommit);\r\n closeQuietly(finalConn);\r\n }\r\n\r\n @Override\r\n public int getOrder() {\r\n return LOWEST + 200;\r\n }\r\n });\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean prePollCheck() throws Exception{\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Void run() {\n try {\n wrapped.open();\n } catch (TTransportException tte) {\n // Wrap the transport exception in an RTE, since UGI.doAs() then goes\n // and unwraps this for us out of the doAs block. We then unwrap one\n // more time in our catch clause to get back the TTE. (ugh)\n throw new RuntimeException(tte);\n }\n return null;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public byte[] exportSheets(List sheetNames) throws Exception {\n for (String sheetName : sheetNames) {\n Table t = findSheet(sheetName);\n if (t != null) {\n exportTable(t);\n } else {\n throw new Exception(\"Tabelle mit Namen '\" + sheetName + \"' kann nicht in der Exportdatei gefunden werden.\");\n }\n }\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n this.ods.save(bout);\n return bout.toByteArray();\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void notifyChannelOpen(ChannelFuture channelFuture) throws Exception{\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Channel open finished with {}\", channelFuture);\r\n }\r\n if (channelFuture.isSuccess()) {\r\n Channel answer = channelFuture.channel();\r\n allChannels.add(answer);\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Creating connector to address: {}\", configuration.getAddress());\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void init() throws Exception{\r\n SelfSignedCertificate ssc = new SelfSignedCertificate();\r\n sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();\r\n bootstrap = new ServerBootstrap().channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.DEBUG)).group(group).childHandler(this);\r\n serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void mergeAccounts() throws Exception{\r\n UserTO mergingUserTO = model.getMergingUser();\r\n UserUR userUR = new UserUR();\r\n userUR.setKey(model.getBaseUser().getUsername());\r\n mergingUserTO.getLinkedAccounts().forEach(acct -> {\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(acct.getResource(), acct.getConnObjectKeyValue()).password(acct.getPassword()).suspended(acct.isSuspended()).username(acct.getUsername()).build();\r\n linkedAccount.getPlainAttrs().addAll(acct.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(acct.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n });\r\n mergingUserTO.getResources().forEach(resource -> {\r\n String connObjectKeyValue = resourceRestClient.getConnObjectKeyValue(resource, mergingUserTO.getType(), mergingUserTO.getKey());\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(resource, connObjectKeyValue).build();\r\n linkedAccount.getPlainAttrs().addAll(mergingUserTO.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(mergingUserTO.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n });\r\n String connObjectKeyValue = resourceRestClient.getConnObjectKeyValue(model.getResource().getKey(), mergingUserTO.getType(), mergingUserTO.getKey());\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(model.getResource().getKey(), connObjectKeyValue).password(mergingUserTO.getPassword()).suspended(mergingUserTO.isSuspended()).username(mergingUserTO.getUsername()).build();\r\n linkedAccount.getPlainAttrs().addAll(mergingUserTO.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(mergingUserTO.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n BatchRequest batchRequest = SyncopeConsoleSession.get().batch();\r\n BatchRequestItem deleteRequest = new BatchRequestItem();\r\n deleteRequest.setMethod(HttpMethod.DELETE);\r\n deleteRequest.setRequestURI(\"/users/\" + mergingUserTO.getKey());\r\n deleteRequest.getHeaders().put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON));\r\n batchRequest.getItems().add(deleteRequest);\r\n String updateUserPayload = MAPPER.writeValueAsString(userUR);\r\n BatchRequestItem updateUser = new BatchRequestItem();\r\n updateUser.setMethod(HttpMethod.PATCH);\r\n updateUser.setRequestURI(\"/users/\" + model.getBaseUser().getUsername());\r\n updateUser.setHeaders(new HashMap<>());\r\n updateUser.getHeaders().put(RESTHeaders.PREFER, List.of(Preference.RETURN_NO_CONTENT.toString()));\r\n updateUser.getHeaders().put(HttpHeaders.ACCEPT, List.of(MediaType.APPLICATION_JSON));\r\n updateUser.getHeaders().put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON));\r\n updateUser.getHeaders().put(HttpHeaders.CONTENT_LENGTH, List.of(updateUserPayload.length()));\r\n updateUser.setContent(updateUserPayload);\r\n batchRequest.getItems().add(updateUser);\r\n Map batchResponse = userRestClient.batch(batchRequest);\r\n batchResponse.forEach((key, value) -> {\r\n if (!value.equalsIgnoreCase(\"success\")) {\r\n throw new IllegalArgumentException(\"Unable to report a success operation status for \" + key);\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static LinkedHashMap readInputFile(String inputLocation, AminoAcidCompositionTable aaTable) throws Exception{\r\n FileInputStream inStream = new FileInputStream(inputLocation);\r\n CompoundSet set;\r\n if (aaTable == null) {\r\n set = CaseFreeAminoAcidCompoundSet.getAminoAcidCompoundSet();\r\n } else {\r\n set = aaTable.getAminoAcidCompoundSet();\r\n }\r\n LinkedHashMap ret;\r\n if (inputLocation.toLowerCase().contains(\".gb\")) {\r\n GenbankReader genbankReader = new GenbankReader(inStream, new GenericGenbankHeaderParser(), new ProteinSequenceCreator(set));\r\n ret = genbankReader.process();\r\n } else {\r\n FastaReader fastaReader = new FastaReader(inStream, new GenericFastaHeaderParser(), new ProteinSequenceCreator(set));\r\n ret = fastaReader.process();\r\n }\r\n return ret;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void run() throws Exception{\r\n Path servicesRoot = mavenProjectRoot.resolve(\"services\");\r\n Path templateModulePath = servicesRoot.resolve(\"new-service-template\");\r\n Path newServiceModulePath = servicesRoot.resolve(serviceModuleName);\r\n createNewModuleFromTemplate(templateModulePath, newServiceModulePath);\r\n replaceTemplatePlaceholders(newServiceModulePath);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create a collection in the current database\n *\n * @param collectionName the name of the collection to create\n * @throws Exception if a problem occurs\n */\npublic void createCollection(String db, String collectionName) throws Exception {\n if (clientWrapper == null) {\n throw new Exception(BaseMessages.getString(PKG, \"MongoDbOutput.Messages.Error.NoDatabaseSet\"));\n }\n clientWrapper.createCollection(db, collectionName);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `id` to the URL query string\n if (getId() != null) {\n try {\n joiner.add(String.format(\"%sid%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getId()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `nodes` to the URL query string\n if (getNodes() != null) {\n for (int i = 0; i < getNodes().size(); i++) {\n try {\n joiner.add(String.format(\"%snodes%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getNodes().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private void openStream() throws Exception{\r\n if (outputStream != null) {\r\n return;\r\n }\r\n if (\"out\".equals(uri)) {\r\n outputStream = System.out;\r\n } else if (\"err\".equals(uri)) {\r\n outputStream = System.err;\r\n } else if (\"file\".equals(uri)) {\r\n outputStream = resolveStreamFromFile();\r\n }\r\n count.set(outputStream == null ? 0 : endpoint.getAutoCloseCount());\r\n LOG.debug(\"Opened stream '{}'\", endpoint.getEndpointKey());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ParserResult loadDatabase(Path file) throws Exception{\r\n Path fileToLoad = file.toAbsolutePath();\r\n dialogService.notify(Localization.lang(\"Opening\") + \": '\" + file + \"'\");\r\n preferencesService.getFilePreferences().setWorkingDirectory(fileToLoad.getParent());\r\n Path backupDir = preferencesService.getFilePreferences().getBackupDirectory();\r\n ParserResult parserResult = null;\r\n if (BackupManager.backupFileDiffers(fileToLoad, backupDir)) {\r\n parserResult = BackupUIManager.showRestoreBackupDialog(dialogService, fileToLoad, preferencesService, fileUpdateMonitor).orElse(null);\r\n }\r\n try {\r\n if (parserResult == null) {\r\n parserResult = OpenDatabase.loadDatabase(fileToLoad, preferencesService.getImportFormatPreferences(), fileUpdateMonitor);\r\n }\r\n if (parserResult.hasWarnings()) {\r\n String content = Localization.lang(\"Please check your library file for wrong syntax.\") + \"\\n\\n\" + parserResult.getErrorMessage();\r\n DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showWarningDialogAndWait(Localization.lang(\"Open library error\"), content));\r\n }\r\n } catch (IOException e) {\r\n parserResult = ParserResult.fromError(e);\r\n LOGGER.error(\"Error opening file '{}'\", fileToLoad, e);\r\n }\r\n if (parserResult.getDatabase().isShared()) {\r\n try {\r\n new SharedDatabaseUIManager(frame, preferencesService, fileUpdateMonitor).openSharedDatabaseFromParserResult(parserResult);\r\n } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) {\r\n parserResult.getDatabaseContext().clearDatabasePath();\r\n parserResult.getDatabase().clearSharedDatabaseID();\r\n LOGGER.error(\"Connection error\", e);\r\n throw e;\r\n }\r\n }\r\n return parserResult;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " RestClient createRestClient(final Map properties) throws Exception{\r\n final SalesforceEndpointConfig modifiedConfig = Optional.ofNullable(config).map(SalesforceEndpointConfig::copy).orElseGet(() -> new SalesforceEndpointConfig());\r\n final CamelContext camelContext = getCamelContext();\r\n PropertyBindingSupport.bindProperties(camelContext, modifiedConfig, properties);\r\n return createRestClientFor(modifiedConfig);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List results() throws Exception{\r\n List result = new ArrayList<>(futures.size());\r\n for (CompletionStage f : futures) {\r\n result.add(f.toCompletableFuture().get());\r\n }\r\n return result;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Path getTempSubFolder(final Path folder) throws Exception{\r\n return java.nio.file.Files.createTempDirectory(folder, null);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get a path suffix.\n *\n * @param f The string to get the suffix for.\n * @param prefix The prefix we're stripping off.\n *\n * @return A suffix such that prefix + suffix = f\n */\nprivate static String getSuffix(String f, String prefix) {\n if (f.startsWith(prefix)) {\n return f.substring(prefix.length());\n }\n throw new RuntimeException(prefix + \" is not a prefix of \" + f);\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private String getZKBaseJdbcURL() throws Exception{\r\n HiveConf hiveConf = getServerConf();\r\n if (hiveConf != null) {\r\n String zkEnsemble = hiveConf.getZKConfig().getQuorumServers();\r\n return \"jdbc:hive2://\" + zkEnsemble + \"/\";\r\n }\r\n throw new Exception(\"Server's HiveConf is null. Unable to read ZooKeeper configs.\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void preWriteCheck(Exchange exchange) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static byte[] F(String P, String S, int c, int i) throws Exception{\r\n byte[] U_LAST = null;\r\n byte[] U_XOR = null;\r\n SecretKeySpec key = new SecretKeySpec(P.getBytes(\"UTF-8\"), \"HmacSHA512\");\r\n Mac mac = Mac.getInstance(key.getAlgorithm());\r\n mac.init(key);\r\n for (int j = 0; j < c; j++) {\r\n if (j == 0) {\r\n byte[] baS = S.getBytes(\"UTF-8\");\r\n byte[] baI = INT(i);\r\n byte[] baU = new byte[baS.length + baI.length];\r\n System.arraycopy(baS, 0, baU, 0, baS.length);\r\n System.arraycopy(baI, 0, baU, baS.length, baI.length);\r\n U_XOR = mac.doFinal(baU);\r\n U_LAST = U_XOR;\r\n mac.reset();\r\n } else {\r\n byte[] baU = mac.doFinal(U_LAST);\r\n mac.reset();\r\n for (int k = 0; k < U_XOR.length; k++) {\r\n U_XOR[k] = (byte) (U_XOR[k] ^ baU[k]);\r\n }\r\n U_LAST = baU;\r\n }\r\n }\r\n return U_XOR;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nprotected SparkDataTable prepareDataTable(final ExecutionMonitor exec) throws Exception {\n if (m_connectionInfo != null && m_contextId != null) {\n final NodeSettings tmpSettings = new NodeSettings(\"preview\");\n saveSettingsTo(tmpSettings);\n final GenericDataSource2SparkSettings prevSettings = m_settings.newInstance();\n prevSettings.loadSettings(tmpSettings);\n return GenericDataSource2SparkNodeModel.preparePreview(prevSettings, m_contextId, m_connectionInfo, exec);\n } else {\n throw new RuntimeException(\"Unable to load preview. Connection required.\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "public SerializedBytes serialize(long key) throws IOException {\n keyBinarySortableSerializeWrite.reset();\n switch(hashTableKeyType) {\n case BOOLEAN:\n keyBinarySortableSerializeWrite.writeBoolean(key == 1);\n break;\n case BYTE:\n keyBinarySortableSerializeWrite.writeByte((byte) key);\n break;\n case SHORT:\n keyBinarySortableSerializeWrite.writeShort((short) key);\n break;\n case INT:\n keyBinarySortableSerializeWrite.writeInt((int) key);\n break;\n case DATE:\n keyBinarySortableSerializeWrite.writeDate((int) key);\n break;\n case LONG:\n keyBinarySortableSerializeWrite.writeLong(key);\n break;\n default:\n throw new RuntimeException(\"Unexpected hash table key type \" + hashTableKeyType.name());\n }\n // byte[] bytes = Arrays.copyOf(output.getData(), output.getLength());\n // LOG.debug(\"VectorMapJoinOptimizedLongCommon serialize key \" + key + \" hashTableKeyType \" + hashTableKeyType.name() + \" hex \" + Hex.encodeHexString(bytes));\n serializedBytes.bytes = output.getData();\n serializedBytes.offset = 0;\n serializedBytes.length = output.getLength();\n return serializedBytes;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Note: The caller needs to ensure that the constructor corresponds to the class, or the cast\n * might fail.\n */\n@SuppressWarnings(\"unchecked\")\npublic static V newErrorHandler(Class targetClass, Constructor constructor, Object... args) throws Exception {\n return ByteBuddyEnhancer.createProxy(targetClass, constructor, args);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public void disconnect() throws Exception{\r\n if (client != null) {\r\n LOG.debug(\"Disconnecting from JIRA\");\r\n client.close();\r\n client = null;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void shutdown() throws Exception{\r\n server.shutdown();\r\n ledgerManager.close();\r\n lmFactory.close();\r\n registrationManager.close();\r\n metadataDriver.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean isDynamicServiceDiscovery() throws Exception{\r\n HiveConf hiveConf = getServerConf();\r\n if (hiveConf == null) {\r\n throw new Exception(\"Server's HiveConf is null. Unable to read ZooKeeper configs.\");\r\n }\r\n if (hiveConf.getBoolVar(ConfVars.HIVE_SERVER2_SUPPORT_DYNAMIC_SERVICE_DISCOVERY)) {\r\n return true;\r\n }\r\n return false;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleForceStart(HttpPostCommand cmd) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n boolean success = getNode().getNodeExtension().getInternalHotRestartService().triggerForceStart();\r\n prepareResponse(cmd, response(success ? SUCCESS : FAIL));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Element getParentForEnvelopedCase(Document doc, Message inMessage) throws Exception{\r\n if (getConfiguration().getParentXpath() != null) {\r\n XPathFilterParameterSpec xp = getConfiguration().getParentXpath();\r\n XPathExpression exp;\r\n try {\r\n exp = XmlSignatureHelper.getXPathExpression(xp);\r\n } catch (XPathExpressionException e) {\r\n throw new XmlSignatureException(\"The parent XPath \" + getConfiguration().getParentXpath().getXPath() + \" is wrongly configured: The XPath \" + xp.getXPath() + \" is invalid.\", e);\r\n }\r\n NodeList list = (NodeList) exp.evaluate(doc.getDocumentElement(), XPathConstants.NODESET);\r\n if (list == null || list.getLength() == 0) {\r\n throw new XmlSignatureException(\"The parent XPath \" + xp.getXPath() + \" returned no result. Check the configuration of the XML signer component.\");\r\n }\r\n int length = list.getLength();\r\n for (int i = 0; i < length; i++) {\r\n Node node = list.item(i);\r\n if (node.getNodeType() == Node.ELEMENT_NODE) {\r\n return (Element) node;\r\n }\r\n }\r\n throw new XmlSignatureException(\"The parent XPath \" + xp.getXPath() + \" returned no element. Check the configuration of the XML signer component.\");\r\n } else {\r\n NodeList parents = doc.getElementsByTagNameNS(getConfiguration().getParentNamespace(), getConfiguration().getParentLocalName());\r\n if (parents == null || parents.getLength() == 0) {\r\n throw new XmlSignatureFormatException(String.format(\"Incoming message has wrong format: The parent element with the local name %s and the namespace %s was not found in the message to build an enveloped XML signature.\", getConfiguration().getParentLocalName(), getConfiguration().getParentNamespace()));\r\n }\r\n return (Element) parents.item(0);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RangerExportPolicyList importRangerPoliciesPlain(String jsonRangerExportPolicyList, String rangerPoliciesJsonFileName, String serviceMapJsonFileName, String jsonServiceMap, String finalUrl, RangerExportPolicyList rangerExportPolicyList, HiveConf hiveConf) throws Exception {\n ClientResponse clientResp = null;\n StreamDataBodyPart filePartPolicies = new StreamDataBodyPart(\"file\", new ByteArrayInputStream(jsonRangerExportPolicyList.getBytes(StandardCharsets.UTF_8)), rangerPoliciesJsonFileName);\n StreamDataBodyPart filePartServiceMap = new StreamDataBodyPart(\"servicesMapJson\", new ByteArrayInputStream(jsonServiceMap.getBytes(StandardCharsets.UTF_8)), serviceMapJsonFileName);\n FormDataMultiPart formDataMultiPart = new FormDataMultiPart();\n MultiPart multipartEntity = null;\n try {\n multipartEntity = formDataMultiPart.bodyPart(filePartPolicies).bodyPart(filePartServiceMap);\n WebResource.Builder builder = getRangerResourceBuilder(finalUrl, hiveConf);\n clientResp = builder.accept(MediaType.APPLICATION_JSON).type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, multipartEntity);\n if (clientResp != null) {\n if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) {\n LOG.debug(\"Ranger policy import finished successfully\");\n } else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {\n throw new RuntimeException(ErrorMsg.RANGER_AUTHENTICATION_FAILED.getMsg());\n } else {\n throw new Exception(\"Ranger policy import failed, Please refer target Ranger admin logs.\");\n }\n }\n } finally {\n try {\n if (filePartPolicies != null) {\n filePartPolicies.cleanup();\n }\n if (filePartServiceMap != null) {\n filePartServiceMap.cleanup();\n }\n if (formDataMultiPart != null) {\n formDataMultiPart.close();\n }\n if (multipartEntity != null) {\n multipartEntity.close();\n }\n } catch (IOException e) {\n LOG.error(\"Exception occurred while closing resources: {}\", e);\n }\n }\n return rangerExportPolicyList;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected X509Certificate[] getSigningCertificateChain() throws Exception{\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void reportError(Context context, String routeId, GtfsException ex, String filenameInfo) throws Exception{\r\n if (!exceptions.add(ex))\r\n return;\r\n ActionReporter reporter = ActionReporter.Factory.getInstance();\r\n ValidationReporter validationReporter = ValidationReporter.Factory.getInstance();\r\n String name = name(filenameInfo);\r\n String filenameInfo2 = \"\";\r\n String checkPointName = \"\";\r\n String fieldName = \"\";\r\n String fieldName2 = \"\";\r\n String value = \"\";\r\n switch(ex.getError()) {\r\n case INVALID_HEADER_FILE_FORMAT:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.INVALID_HEADER_FILE_FORMAT);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The first line in file \\\"\" + filenameInfo + \"\\\" must comply with CSV (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, 1, ex.getColumn()), filenameInfo);\r\n throw ex;\r\n case EMPTY_HEADER_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.EMPTY_HEADER_FIELD);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"Header fields in file \\\"\" + filenameInfo + \"\\\" could not be empty (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, 1, ex.getColumn()), filenameInfo);\r\n throw ex;\r\n case DUPLICATE_HEADER_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_HEADER_FIELD);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The header fields in file \\\"\" + filenameInfo + \"\\\" could not be duplicated (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, 1, ex.getColumn()), filenameInfo);\r\n throw ex;\r\n case INVALID_FILE_FORMAT:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.INVALID_FILE_FORMAT);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"Line number \" + ex.getId() + \" in file \\\"\" + filenameInfo + \"\\\" must comply with CSV (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), filenameInfo);\r\n throw ex;\r\n case HTML_TAG_IN_HEADER_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.HTML_TAG_IN_HEADER_FIELD);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"HTML tags in field names are not allowed (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), filenameInfo);\r\n throw ex;\r\n case EXTRA_SPACE_IN_FIELD:\r\n case EXTRA_SPACE_IN_HEADER_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.EXTRA_SPACE_IN_HEADER_FIELD);\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), ex.getValue(), ex.getField());\r\n break;\r\n case MISSING_FILE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_FILE);\r\n reporter.addFileReport(context, filenameInfo, IO_TYPE.INPUT);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.FILE_NOT_FOUND, \"The file \\\"\" + filenameInfo + \"\\\" must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo), filenameInfo);\r\n throw ex;\r\n case MISSING_FILES:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_FILES);\r\n filenameInfo = \"calendar.txt\";\r\n filenameInfo2 = \"calendar_dates.txt\";\r\n reporter.addFileReport(context, filenameInfo, IO_TYPE.INPUT);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.FILE_NOT_FOUND, \"One of the files \\\"\" + filenameInfo + \"\\\" or \\\"\" + filenameInfo2 + \"\\\"must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo), filenameInfo + \",\" + filenameInfo2);\r\n throw ex;\r\n case MISSING_OPTIONAL_FILE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_OPTIONAL_FILE);\r\n reporter.addFileReport(context, filenameInfo, IO_TYPE.INPUT);\r\n reporter.setFileState(context, filenameInfo, IO_TYPE.INPUT, FILE_STATE.IGNORED);\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo), filenameInfo);\r\n break;\r\n case UNUSED_FILE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.UNUSED_FILE);\r\n reporter.addFileReport(context, filenameInfo, IO_TYPE.INPUT);\r\n reporter.setFileState(context, filenameInfo, IO_TYPE.INPUT, FILE_STATE.IGNORED);\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo), filenameInfo);\r\n break;\r\n case FILE_WITH_NO_ENTRY:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.FILE_WITH_NO_ENTRY);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The file \\\"\" + filenameInfo + \"\\\" must contain at least one entry (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), 0), \"\");\r\n throw ex;\r\n case FILES_WITH_NO_ENTRY:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.FILES_WITH_NO_ENTRY);\r\n fieldName = ex.getField();\r\n filenameInfo = \"calendar.txt\";\r\n filenameInfo2 = \"calendar_dates.txt\";\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"One of the files \\\"\" + filenameInfo + \"\\\" or \\\"\" + filenameInfo2 + \"\\\" must contain at least one entry (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), 0), \"\");\r\n throw ex;\r\n case DUPLICATE_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_FIELD);\r\n fieldName = ex.getField();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The field \\\"\" + fieldName + \"\\\" must be unique (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), ex.getValue(), fieldName);\r\n throw ex;\r\n case MISSING_REQUIRED_FIELDS:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_REQUIRED_FIELDS);\r\n fieldName = ex.getField();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The column \\\"\" + fieldName + \"\\\" of file \\\"\" + filenameInfo + \"\\\" must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n throw ex;\r\n case MISSING_REQUIRED_FIELDS2:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_REQUIRED_FIELDS2);\r\n fieldName = ex.getField();\r\n fieldName2 = fieldName.replaceFirst(\"long\", \"short\");\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"One of the fields \\\"\" + fieldName + \"\\\" or \\\"\" + fieldName2 + \"\\\" must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), fieldName + \",\" + fieldName2);\r\n break;\r\n case MISSING_OPTIONAL_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_OPTIONAL_FIELD);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"Optional field is not present (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), ex.getField());\r\n break;\r\n case EXTRA_HEADER_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.EXTRA_HEADER_FIELD);\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), ex.getField());\r\n break;\r\n case MISSING_REQUIRED_VALUES:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_REQUIRED_VALUES);\r\n fieldName = ex.getField();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The value \\\"\" + fieldName + \"\\\" must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case MISSING_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_FIELD);\r\n fieldName = ex.getField();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The file \\\"\" + filenameInfo + \"\\\" must provide a non empty \\\"\" + name + \"_id\\\" for each \" + name + \" (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), fieldName);\r\n throw ex;\r\n case MISSING_REQUIRED_VALUES2:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_REQUIRED_VALUES2);\r\n fieldName = ex.getField();\r\n fieldName2 = fieldName.replaceFirst(\"long\", \"short\");\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"One of the values \\\"\" + fieldName + \"\\\" or \\\"\" + fieldName2 + \"\\\" must be provided (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName + \",\" + fieldName2);\r\n break;\r\n case ALL_DAYS_ARE_INVALID:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.ALL_DAYS_ARE_INVALID);\r\n fieldName = ex.getField();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"At least one day must be valid (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), \"At least one day must be valid\");\r\n break;\r\n case DUPLICATE_DEFAULT_KEY_FIELD:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_DEFAULT_KEY_FIELD);\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"At most only one Agency can have default value \\\"agency_id\\\" (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), ex.getField());\r\n throw ex;\r\n case DEFAULT_VALUE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DEFAULT_VALUE);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case MISSING_ARRIVAL_TIME:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_ARRIVAL_TIME);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, \"1\", buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case MISSING_DEPARTURE_TIME:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_DEPARTURE_TIME);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, \"2\", buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case MISSING_TRANSFER_TIME:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.MISSING_TRANSFER_TIME);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, \"3\", buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case START_DATE_AFTER_END_DATE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.START_DATE_AFTER_END_DATE);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), fieldName);\r\n break;\r\n case INVALID_FORMAT:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.INVALID_FORMAT);\r\n fieldName = ex.getField();\r\n value = ex.getValue();\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"The value \\\"\" + value + \"\\\" is invalid for field \" + fieldName + \" (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), value, fieldName);\r\n break;\r\n case DUPLICATE_STOP_SEQUENCE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_STOP_SEQUENCE);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getField()), routeId), ex.getValue(), ex.getField());\r\n throw ex;\r\n case UNREFERENCED_ID:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.UNREFERENCED_ID);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, fieldName, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue(), ex.getField());\r\n break;\r\n case UNUSED_ID:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.UNUSED_ID);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn()), routeId), ex.getValue(), fieldName);\r\n break;\r\n case DUPLICATE_DOUBLE_KEY:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_DOUBLE_KEY);\r\n fieldName = ex.getField();\r\n fieldName2 = \"date\";\r\n reporter.addFileErrorInReport(context, filenameInfo, FILE_ERROR_CODE.INVALID_FORMAT, \"Duplicate (\" + fieldName + \") values (rule \" + checkPointName + \")\");\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getField()), routeId), ex.getValue(), ex.getField());\r\n throw ex;\r\n case SHARED_VALUE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.SHARED_VALUE);\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue(), ex.getField());\r\n break;\r\n case BAD_REFERENCED_ID:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.BAD_REFERENCED_ID);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue());\r\n break;\r\n case NO_LOCATION_TYPE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.NO_LOCATION_TYPE);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, filenameInfo, ex.getId(), ex.getColumn(), ex.getField()), routeId));\r\n break;\r\n case BAD_VALUE:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.BAD_VALUE);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue());\r\n throw ex;\r\n case NO_PARENT_FOR_STATION:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.NO_PARENT_FOR_STATION);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue());\r\n break;\r\n case DUPLICATE_ROUTE_NAMES:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.DUPLICATE_ROUTE_NAMES);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue());\r\n break;\r\n case CONTAINS_ROUTE_NAMES:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.CONTAINS_ROUTE_NAMES);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue(), ex.getRefValue());\r\n break;\r\n case BAD_COLOR:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.BAD_COLOR);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), \"\");\r\n break;\r\n case INVERSE_DUPLICATE_ROUTE_NAMES:\r\n checkPointName = checkPointName(name, GtfsException.ERROR.INVERSE_DUPLICATE_ROUTE_NAMES);\r\n fieldName = ex.getField();\r\n validationReporter.addCheckPointReportError(context, checkPointName, buildDataLocation(context, new DataLocation(filenameInfo, ex.getId(), ex.getColumn(), ex.getCode()), routeId), ex.getValue());\r\n break;\r\n case MISSING_FOREIGN_KEY:\r\n case SYSTEM:\r\n default:\r\n break;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void restore() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void findOffsets(Response response, BiConsumer consumer) throws Exception{\r\n List links = response.getStringHeaders().get(HttpHeaders.LINK);\r\n if (links != null) {\r\n for (String link : links) {\r\n String[] parts = link.split(\";\");\r\n if (parts.length != 2) {\r\n continue;\r\n }\r\n String uri = StringHelper.between(parts[0], \"<\", \">\");\r\n String rel = StringHelper.removeQuotes(StringHelper.after(parts[1], \"=\"));\r\n Map query = URISupport.parseQuery(uri);\r\n Object offset = query.get(ServiceNowParams.SYSPARM_OFFSET.getId());\r\n if (offset != null) {\r\n switch(rel) {\r\n case ServiceNowConstants.LINK_FIRST:\r\n consumer.accept(ServiceNowConstants.OFFSET_FIRST, offset);\r\n break;\r\n case ServiceNowConstants.LINK_LAST:\r\n consumer.accept(ServiceNowConstants.OFFSET_LAST, offset);\r\n break;\r\n case ServiceNowConstants.LINK_NEXT:\r\n consumer.accept(ServiceNowConstants.OFFSET_NEXT, offset);\r\n break;\r\n case ServiceNowConstants.LINK_PREV:\r\n consumer.accept(ServiceNowConstants.OFFSET_PREV, offset);\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Method getFactoryMethod(String className, Configuration conf) throws Exception{\r\n Class clazz = conf.getClassByName(className);\r\n return clazz.getMethod(\"parseFrom\", byte[].class);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Load required {@link SparkSQLFunctionFactory}s\n */\n@SuppressWarnings(\"unchecked\")\nprivate void ensureFunctionFactoriesLoaded(final SparkSQLFunctionJobInput[] functions) throws Exception {\n for (SparkSQLFunctionJobInput agg : functions) {\n if (!m_factories.containsKey(agg.getFactoryName())) {\n final Object obj = getClass().getClassLoader().loadClass(agg.getFactoryName()).newInstance();\n if (obj instanceof SparkSQLFunctionFactory) {\n m_factories.put(agg.getFactoryName(), (SparkSQLFunctionFactory) obj);\n } else {\n throw new IllegalArgumentException(\"Unknown aggregation function factory type\");\n }\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "protected void checkRun(String path) throws Exception{\r\n final File inFile;\r\n final File outFile;\r\n final File f = new File(path);\r\n if (f.isAbsolute()) {\r\n inFile = f;\r\n outFile = new File(path + \".out\");\r\n } else {\r\n final URL inUrl = QuidemTest.class.getResource(\"/\" + n2u(path));\r\n inFile = Sources.of(requireNonNull(inUrl, \"inUrl\")).file();\r\n outFile = replaceDir(inFile, \"resources\", \"quidem\");\r\n }\r\n Util.discard(outFile.getParentFile().mkdirs());\r\n try (Reader reader = Util.reader(inFile);\r\n Writer writer = Util.printWriter(outFile);\r\n Closer closer = new Closer()) {\r\n final Quidem.Config config = Quidem.configBuilder().withReader(reader).withWriter(writer).withConnectionFactory(createConnectionFactory()).withCommandHandler(createCommandHandler()).withPropertyHandler((propertyName, value) -> {\r\n if (propertyName.equals(\"bindable\")) {\r\n final boolean b = value instanceof Boolean && (Boolean) value;\r\n closer.add(Hook.ENABLE_BINDABLE.addThread(Hook.propertyJ(b)));\r\n }\r\n if (propertyName.equals(\"expand\")) {\r\n final boolean b = value instanceof Boolean && (Boolean) value;\r\n closer.add(Prepare.THREAD_EXPAND.push(b));\r\n }\r\n if (propertyName.equals(\"insubquerythreshold\")) {\r\n int thresholdValue = ((BigDecimal) value).intValue();\r\n closer.add(Prepare.THREAD_INSUBQUERY_THRESHOLD.push(thresholdValue));\r\n }\r\n }).withEnv(QuidemTest::getEnv).build();\r\n new Quidem(config).execute();\r\n }\r\n final String diff = DiffTestCase.diff(inFile, outFile);\r\n if (!diff.isEmpty()) {\r\n fail(\"Files differ: \" + outFile + \" \" + inFile + \"\\n\" + diff);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"writeArchiveFileRole\" })\npublic ArchiveFileDocumentsBean addDocumentFromTemplate(String archiveFileId, String fileName, String letterHead, String templateFolder, String templateName, HashMap placeHolderValues, String dictateSign, String externalId) throws Exception {\n if (fileName == null || \"\".equals(fileName)) {\n throw new Exception(\"Dokumentname darf nicht leer sein!\");\n }\n StringGenerator idGen = new StringGenerator();\n ArchiveFileBean aFile = this.archiveFileFacade.find(archiveFileId);\n SecurityUtils.checkGroupsForCase(context.getCallerPrincipal().getName(), aFile, this.securityFacade, this.getAllowedGroups(aFile));\n List formTypesForCase = this.formsFacade.getFormsForCase(archiveFileId);\n ArrayList formsPrefixes = new ArrayList<>();\n if (formTypesForCase != null) {\n for (ArchiveFileFormsBean form : formTypesForCase) {\n formsPrefixes.add(form.getPlaceHolder());\n }\n }\n String localBaseDir = System.getProperty(\"jlawyer.server.basedirectory\");\n localBaseDir = localBaseDir.trim();\n if (!localBaseDir.endsWith(System.getProperty(\"file.separator\"))) {\n localBaseDir = localBaseDir + System.getProperty(\"file.separator\");\n }\n String src = localBaseDir + \"templates\" + templateFolder + System.getProperty(\"file.separator\") + templateName;\n String dst = localBaseDir + \"archivefiles\" + System.getProperty(\"file.separator\") + aFile.getId() + System.getProperty(\"file.separator\");\n String ext = \"\";\n try {\n ext = templateName.substring(templateName.lastIndexOf('.'));\n } catch (Throwable t) {\n log.warn(\"Template without file extension: \" + templateName);\n }\n fileName = fileName + ext;\n ArchiveFileDocumentsBean existingDoc = this.archiveFileDocumentsFacade.findByArchiveFileKey(aFile, fileName);\n if (existingDoc != null) {\n throw new Exception(\"Dokument \" + fileName + \" existiert bereits in der Akte oder deren Papierkorb - bitte einen anderen Namen w\u00e4hlen!\");\n }\n String docId = idGen.getID().toString();\n this.migrateDocument(dst, docId, fileName);\n String dstId = dst + docId;\n if (new File(dstId).exists()) {\n throw new Exception(\"Dokument \" + fileName + \" existiert bereits in der Akte oder deren Papierkorb - bitte einen anderen Namen w\u00e4hlen!\");\n }\n if (ServerStringUtils.isEmpty(letterHead)) {\n // new document equals the body template\n ServerFileUtils.copyFile(src, dstId);\n } else {\n // new document equals the head template\n String srcHead = localBaseDir + \"letterheads\" + System.getProperty(\"file.separator\") + letterHead;\n ServerFileUtils.copyFile(srcHead, dstId);\n if (!(new File(srcHead).exists())) {\n throw new Exception(\"Briefkopf \" + letterHead + \" existiert nicht!\");\n }\n // migrate body template into head template\n LibreOfficeAccess.mergeDocuments(dstId, src);\n }\n try {\n LibreOfficeAccess.setPlaceHolders(archiveFileId, dstId, fileName, placeHolderValues, formsPrefixes);\n } catch (Exception ex) {\n log.error(\"could not set placeholders in file \" + dstId, ex);\n }\n ArchiveFileDocumentsBean db = new ArchiveFileDocumentsBean();\n db.setId(docId);\n db.setExternalId(externalId);\n db.setVersion(1);\n db.setDictateSign(dictateSign);\n db.setArchiveFileKey(aFile);\n Date created = new Date();\n db.setCreationDate(created);\n db.setChangeDate(created);\n db.setName(fileName);\n db.setFolder(aFile.getRootFolder());\n if (new File(dstId).exists()) {\n db.setSize(new File(dstId).length());\n } else {\n db.setSize(-1);\n }\n db.setFavorite(false);\n db.setDeleted(false);\n db.setDeletedBy(null);\n db.setDeletionDate(null);\n this.archiveFileDocumentsFacade.create(db);\n this.addCaseHistory(idGen.getID().toString(), aFile, \"Dokument hinzugef\u00fcgt: \" + fileName);\n String preview = \"\";\n try {\n PreviewGenerator pg = new PreviewGenerator(this.archiveFileDocumentsFacade);\n preview = pg.createPreview(archiveFileId, docId, fileName);\n } catch (Throwable t) {\n log.error(\"Error creating document preview\", t);\n }\n try {\n SearchIndexRequest req = new SearchIndexRequest(SearchIndexRequest.ACTION_ADD);\n req.setArchiveFileId(archiveFileId);\n req.setArchiveFileName(aFile.getName());\n req.setArchiveFileNumber(aFile.getFileNumber());\n req.setFileName(fileName);\n req.setId(docId);\n req.setText(preview);\n this.publishSearchIndexRequest(req);\n } catch (Throwable t) {\n log.error(\"Error publishing search index request ADD\", t);\n }\n DocumentCreatedEvent evt = new DocumentCreatedEvent();\n evt.setDocumentId(docId);\n evt.setCaseId(aFile.getId());\n evt.setDocumentName(fileName);\n this.newDocumentEvent.fireAsync(evt);\n return this.archiveFileDocumentsFacade.find(docId);\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void processCurrentLocation(Exchange exchange) throws Exception{\r\n LOG.debug(\"Geolocation for current location\");\r\n GeolocationPayload payload = new GeolocationPayload();\r\n payload.considerIp = true;\r\n GeolocationResult result = GeolocationApi.geolocate(context, payload).await();\r\n LOG.debug(\"Geolocation response {}\", result);\r\n exchange.getIn().setHeader(GeoCoderConstants.STATUS, GeocoderStatus.OK);\r\n String resLatlng = result.location.toString();\r\n exchange.getIn().setHeader(GeoCoderConstants.LATLNG, resLatlng);\r\n LOG.debug(\"Geocode - reverse geocode for location {}\", resLatlng);\r\n GeocodingResult[] results = GeocodingApi.reverseGeocode(context, result.location).await();\r\n LOG.debug(\"Geocode response {}\", results);\r\n if (results != null) {\r\n extractGeoResult(results, exchange);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Stores the serializable table data in the configuration.\n * Currently the following is handled:\n *

\n * @param configuration The configuration storing the catalog information\n * @param tableDesc The table which we want to store to the configuration\n * @param map The map of the configuration properties which we append with the serialized data\n */\n@VisibleForTesting\nstatic void overlayTableProperties(Configuration configuration, TableDesc tableDesc, Map map) {\n Properties props = tableDesc.getProperties();\n Maps.fromProperties(props).entrySet().stream().filter(// map overrides tableDesc properties\n entry -> !map.containsKey(entry.getKey())).forEach(entry -> map.put(entry.getKey(), entry.getValue()));\n String location;\n Schema schema;\n PartitionSpec spec;\n try {\n Table table = IcebergTableUtil.getTable(configuration, props);\n location = table.location();\n schema = table.schema();\n spec = table.spec();\n // serialize table object into config\n Table serializableTable = SerializableTable.copyOf(table);\n checkAndSkipIoConfigSerialization(configuration, serializableTable);\n map.put(InputFormatConfig.SERIALIZED_TABLE_PREFIX + tableDesc.getTableName(), SerializationUtil.serializeToBase64(serializableTable));\n } catch (NoSuchTableException ex) {\n if (!HiveTableUtil.isCtas(props)) {\n throw ex;\n }\n if (!Catalogs.hiveCatalog(configuration, props)) {\n throw new UnsupportedOperationException(HiveIcebergSerDe.CTAS_EXCEPTION_MSG);\n }\n location = map.get(hive_metastoreConstants.META_TABLE_LOCATION);\n map.put(InputFormatConfig.SERIALIZED_TABLE_PREFIX + tableDesc.getTableName(), SerializationUtil.serializeToBase64(null));\n try {\n AbstractSerDe serDe = tableDesc.getDeserializer(configuration);\n HiveIcebergSerDe icebergSerDe = (HiveIcebergSerDe) serDe;\n schema = icebergSerDe.getTableSchema();\n spec = IcebergTableUtil.spec(configuration, icebergSerDe.getTableSchema());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n map.put(InputFormatConfig.TABLE_IDENTIFIER, props.getProperty(Catalogs.NAME));\n if (StringUtils.isNotBlank(location)) {\n map.put(InputFormatConfig.TABLE_LOCATION, location);\n }\n String schemaJson = SchemaParser.toJson(schema);\n map.put(InputFormatConfig.TABLE_SCHEMA, schemaJson);\n // save schema into table props as well to avoid repeatedly hitting the HMS during serde initializations\n // this is an exception to the interface documentation, but it's a safe operation to add this property\n props.put(InputFormatConfig.TABLE_SCHEMA, schemaJson);\n if (spec == null) {\n spec = PartitionSpec.unpartitioned();\n }\n props.put(InputFormatConfig.PARTITION_SPEC, PartitionSpecParser.toJson(spec));\n // We need to remove this otherwise the job.xml will be invalid as column comments are separated with '\\0' and\n // the serialization utils fail to serialize this character\n map.remove(\"columns.comments\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private static void loadData() throws Exception{\r\n File file = new File(\"./sales.txt\");\r\n BufferedReader br = new BufferedReader(new FileReader(file));\r\n data = new HashMap();\r\n String line = br.readLine();\r\n while (line != null) {\r\n String[] parts = line.split(\"\\t\", 2);\r\n if (parts.length == 2) {\r\n data.put(parts[0], Integer.valueOf(parts[1]));\r\n }\r\n line = br.readLine();\r\n }\r\n br.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create the location folders for the partitions. For each partition a separate thread will be\n * started to create the folder. The method will wait until all threads are finished and returns\n * the partitions whose folders were created successfully. If an error occurs during the\n * execution of a thread, a MetaException will be thrown.\n * @param partitionsToAdd\n * @param table\n * @param addedPartitions\n * @return\n * @throws MetaException\n */\nprivate List createPartitionFolders(final List partitionsToAdd, final Table table, final Map addedPartitions, EnvironmentContext envContext) throws MetaException {\n final AtomicBoolean failureOccurred = new AtomicBoolean(false);\n final List> partFutures = new ArrayList<>(partitionsToAdd.size());\n final Map addedParts = new ConcurrentHashMap<>();\n final UserGroupInformation ugi;\n try {\n ugi = UserGroupInformation.getCurrentUser();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n for (final Partition partition : partitionsToAdd) {\n initializePartitionParameters(table, partition);\n partFutures.add(threadPool.submit(() -> {\n if (failureOccurred.get()) {\n return null;\n }\n ugi.doAs((PrivilegedExceptionAction) () -> {\n try {\n boolean madeDir = createLocationForAddedPartition(table, partition);\n addedParts.put(new PartValEqWrapperLite(partition), madeDir);\n initializeAddedPartition(table, partition, madeDir, envContext);\n } catch (MetaException e) {\n throw new IOException(e.getMessage(), e);\n }\n return null;\n });\n return partition;\n }));\n }\n List newParts = new ArrayList<>(partitionsToAdd.size());\n String errorMessage = null;\n for (Future partFuture : partFutures) {\n try {\n Partition part = partFuture.get();\n if (part != null && !failureOccurred.get()) {\n newParts.add(part);\n }\n } catch (ExecutionException e) {\n // If an exception is thrown in the execution of a task, set the failureOccurred flag to\n // true. This flag is visible in the tasks and if its value is true, the partition\n // folders won't be created.\n // Then iterate through the remaining tasks and wait for them to finish. The tasks which\n // are started before the flag got set will then finish creating the partition folders.\n // The tasks which are started after the flag got set, won't create the partition\n // folders, to avoid unnecessary work.\n // This way it is sure that all tasks are finished, when entering the finally part where\n // the partition folders are cleaned up. It won't happen that a task is still running\n // when cleaning up the folders, so it is sure we won't have leftover folders.\n // Canceling the other tasks would be also an option but during testing it turned out\n // that it is not a trustworthy solution to avoid leftover folders.\n failureOccurred.compareAndSet(false, true);\n errorMessage = e.getMessage();\n } catch (InterruptedException e) {\n failureOccurred.compareAndSet(false, true);\n errorMessage = e.getMessage();\n // Restore interruption status of the corresponding thread\n Thread.currentThread().interrupt();\n }\n }\n addedPartitions.putAll(addedParts);\n if (failureOccurred.get()) {\n throw new MetaException(errorMessage);\n }\n return newParts;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected boolean acceptInboundMessage(Object msg) throws Exception{\r\n return matcher.match(msg);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addOrFail(ReliableTopicMessage message) throws Exception{\r\n long sequenceId = ringbuffer.addAsync(message, OverflowPolicy.FAIL).toCompletableFuture().get();\r\n if (sequenceId == -1) {\r\n throw new TopicOverloadException(\"Failed to publish message: \" + message + \" on topic:\" + name);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean exportedkeys(String line) throws Exception{\r\n return metadata(\"getExportedKeys\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"table name\") });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List> exportVulnerabilities(UUID exportId, ExportStatus exportStatus) throws TenableDataImportException {\n List> response = new ArrayList<>();\n if (exportStatus != null) {\n for (Integer chunkId : exportStatus.getChunkIds()) {\n log.info(\"Exporting Vulnerabilities Chunk -> {}\", chunkId);\n Map params = new HashMap() {\n\n {\n put(\"export_id\", exportId.toString());\n put(\"chunk_id\", chunkId.toString());\n }\n };\n String vulnerabilityExportApiUrl = getTenableApiUrl(\"vulnerabilityExport\", params);\n Map input = getBaseTenableInput();\n try {\n String responseString = HttpUtil.get(vulnerabilityExportApiUrl, input);\n List> parsedResponse = (List>) Util.getJsonBuilder().fromJson(responseString, List.class);\n log.info(\"Exported Vulnerabilities Chunk -> Id:{}, Size:{}\", chunkId, parsedResponse.size());\n if (!parsedResponse.isEmpty()) {\n parsedResponse.stream().forEach(vulnerability -> ((Map) vulnerability.get(\"asset\")).put(\"instanceId\", assetMap.get(UUID.fromString(((Map) vulnerability.get(\"asset\")).get(\"uuid\").toString()))));\n response.addAll(parsedResponse);\n } else {\n throw new TenableDataImportException(\"Unable to exports Vulnerabilities\");\n }\n } catch (IOException | UnAuthorisedException e) {\n throw new RuntimeException(e);\n }\n }\n } else {\n throw new TenableDataImportException(\"Unable to exports Vulnerabilities\");\n }\n return response;\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "public void load() throws IOException {\n if (finalize) {\n throw new RuntimeException(\"trying to modify finalized config\");\n }\n finalize = true;\n try (InputStream configStream = new FileInputStream(configFile)) {\n loadedProps.loadFromXML(configStream);\n }\n if (StringUtils.isNullOrEmpty(globalHiveSyncConfigParams.globallyReplicatedTimeStamp)) {\n throw new RuntimeException(\"globally replicated timestamp not set\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private void initSchemaPartition() throws Exception{\r\n File workingDirectory = service.getInstanceLayout().getPartitionsDirectory();\r\n File schemaRepository = new File(workingDirectory, \"schema\");\r\n SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(workingDirectory);\r\n try {\r\n extractor.extractOrCopy();\r\n } catch (IOException ioe) {\r\n }\r\n SchemaLoader loader = new LdifSchemaLoader(schemaRepository);\r\n SchemaManager schemaManager = new DefaultSchemaManager(loader);\r\n schemaManager.loadAllEnabled();\r\n ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry();\r\n for (LdapComparator comparator : comparatorRegistry) {\r\n if (comparator instanceof NormalizingComparator) {\r\n ((NormalizingComparator) comparator).setOnServer();\r\n }\r\n }\r\n service.setSchemaManager(schemaManager);\r\n LdifPartition ldifPartition = new LdifPartition(schemaManager, service.getDnFactory());\r\n ldifPartition.setPartitionPath(new File(workingDirectory, \"schema\").toURI());\r\n SchemaPartition schemaPartition = new SchemaPartition(schemaManager);\r\n schemaPartition.setWrappedPartition(ldifPartition);\r\n service.setSchemaPartition(schemaPartition);\r\n List errors = schemaManager.getErrors();\r\n if (!errors.isEmpty()) {\r\n throw new IllegalStateException(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors)));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get list of configured NameNode proxy addresses.\n * Randomize the list if requested.\n */\nprotected List> getProxyAddresses(URI uri, String addressKey) {\n final List> proxies = new ArrayList>();\n Map> map = DFSUtilClient.getAddresses(conf, null, addressKey);\n Map addressesInNN = map.get(uri.getHost());\n if (addressesInNN == null || addressesInNN.size() == 0) {\n throw new RuntimeException(\"Could not find any configured addresses \" + \"for URI \" + uri);\n }\n Collection addressesOfNns = addressesInNN.values();\n try {\n addressesOfNns = getResolvedHostsIfNecessary(addressesOfNns, uri);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n for (InetSocketAddress address : addressesOfNns) {\n proxies.add(new NNProxyInfo(address));\n }\n // Randomize the list to prevent all clients pointing to the same one\n boolean randomized = getRandomOrder(conf, uri);\n if (randomized) {\n Collections.shuffle(proxies);\n }\n // The client may have a delegation token set for the logical\n // URI of the cluster. Clone this token to apply to each of the\n // underlying IPC addresses so that the IPC code can find it.\n HAUtilClient.cloneDelegationTokenForLogicalUri(ugi, uri, addressesOfNns);\n return proxies;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void doPreSetup() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void flush() throws Exception{\r\n if (batchSize > 0) {\r\n synchronized (batchList) {\r\n if (!batchList.isEmpty()) {\r\n List deviceIds = new ArrayList<>();\r\n List timestamps = new ArrayList<>();\r\n List> measurementsList = new ArrayList<>();\r\n List> typesList = new ArrayList<>();\r\n List> valuesList = new ArrayList<>();\r\n for (Event event : batchList) {\r\n convertText(event.getDevice(), event.getMeasurements(), event.getValues());\r\n deviceIds.add(event.getDevice());\r\n timestamps.add(event.getTimestamp());\r\n measurementsList.add(event.getMeasurements());\r\n typesList.add(event.getTypes());\r\n valuesList.add(event.getValues());\r\n }\r\n pool.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList);\r\n LOG.debug(\"send event successfully\");\r\n batchList.clear();\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void produce(Context context) throws Exception{\r\n NetexprofileExportParameters parameters = (NetexprofileExportParameters) context.get(Constant.CONFIGURATION);\r\n ActionReporter reporter = ActionReporter.Factory.getInstance();\r\n JobData jobData = (JobData) context.get(JOB_DATA);\r\n Path outputPath = Paths.get(jobData.getPathName(), OUTPUT);\r\n ExportableData exportableData = (ExportableData) context.get(EXPORTABLE_DATA);\r\n ExportableNetexData exportableNetexData = (ExportableNetexData) context.get(EXPORTABLE_NETEX_DATA);\r\n mobi.chouette.model.Line neptuneLine = exportableData.getLine();\r\n produceAndCollectLineData(context, exportableData, exportableNetexData);\r\n produceAndCollectSharedData(context, exportableData, exportableNetexData);\r\n String fileName = ExportedFilenamer.createLineFilename(context, neptuneLine);\r\n reporter.addFileReport(context, fileName, IO_TYPE.OUTPUT);\r\n Path filePath = new File(outputPath.toFile(), fileName).toPath();\r\n Marshaller marshaller = (Marshaller) context.get(MARSHALLER);\r\n NetexFileWriter writer = new NetexFileWriter();\r\n writer.writeXmlFile(context, filePath, exportableData, exportableNetexData, NetexFragmentMode.LINE, marshaller);\r\n if (parameters.isAddMetadata()) {\r\n Metadata metadata = (Metadata) context.get(METADATA);\r\n if (metadata != null) {\r\n metadata.getResources().add(new Metadata.Resource(fileName, NeptuneObjectPresenter.getName(neptuneLine.getNetwork()), NeptuneObjectPresenter.getName(neptuneLine)));\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"writeArchiveFileRole\" })\npublic InvoicePosition addInvoicePosition(String invoiceId, InvoicePosition position) throws Exception {\n String principalId = context.getCallerPrincipal().getName();\n Invoice invoice = this.invoicesFacade.find(invoiceId);\n if (invoice == null) {\n throw new Exception(MSG_MISSING_INVOICE);\n }\n ArchiveFileBean aFile = this.archiveFileFacade.find(invoice.getArchiveFileKey().getId());\n boolean allowed = false;\n if (principalId != null) {\n List userGroups = new ArrayList<>();\n try {\n userGroups = this.securityFacade.getGroupsForUser(principalId);\n } catch (Throwable t) {\n log.error(\"Unable to determine groups for user \" + principalId, t);\n }\n if (SecurityUtils.checkGroupsForCase(userGroups, aFile, this.caseGroupsFacade)) {\n allowed = true;\n }\n } else {\n allowed = true;\n }\n if (allowed) {\n StringGenerator idGen = new StringGenerator();\n position.setId(idGen.getID().toString());\n position.setInvoice(invoice);\n this.invoicePositionsFacade.create(position);\n this.updateInvoiceTotal(invoiceId);\n return this.invoicePositionsFacade.find(position.getId());\n } else {\n throw new Exception(MSG_MISSINGPRIVILEGE_CASE);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private X509Certificate[] getCertificateChain() throws Exception{\r\n KeyStore keystore = getKeyStore();\r\n if (keystore == null) {\r\n return null;\r\n }\r\n String alias = getAlias();\r\n if (alias == null) {\r\n return null;\r\n }\r\n Certificate[] certs = keystore.getCertificateChain(alias);\r\n if (certs == null) {\r\n return null;\r\n }\r\n ArrayList certList = new ArrayList<>(certs.length);\r\n for (Certificate cert : certs) {\r\n if (cert instanceof X509Certificate) {\r\n certList.add((X509Certificate) cert);\r\n }\r\n }\r\n return certList.toArray(new X509Certificate[certList.size()]);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void beforeProcess(Exchange exchange) throws Exception{\r\n List attributes = accessPolicy.getConfigAttributes();\r\n try {\r\n Authentication authToken = getAuthentication(exchange.getIn());\r\n if (authToken == null) {\r\n throw new CamelAuthorizationException(\"Cannot find the Authentication instance.\", exchange);\r\n }\r\n Authentication authenticated = authenticateIfRequired(authToken);\r\n try {\r\n this.accessDecisionManager.decide(authenticated, exchange, attributes);\r\n } catch (AccessDeniedException accessDeniedException) {\r\n exchange.getIn().setHeader(Exchange.AUTHENTICATION_FAILURE_POLICY_ID, getId());\r\n AuthorizationFailureEvent event = new AuthorizationFailureEvent(exchange, attributes, authenticated, accessDeniedException);\r\n publishEvent(event);\r\n throw accessDeniedException;\r\n }\r\n publishEvent(new AuthorizedEvent(exchange, attributes, authenticated));\r\n } catch (RuntimeException exception) {\r\n exchange.getIn().setHeader(Exchange.AUTHENTICATION_FAILURE_POLICY_ID, getId());\r\n throw new CamelAuthorizationException(\"Cannot access the processor which has been protected.\", exchange, exception);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Consul createConsulClient() throws Exception{\r\n return createConsulClient(null);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"writeArchiveFileRole\" })\npublic void moveDocumentsToFolder(Collection documentIds, String folderId) throws Exception {\n CaseFolder target = this.caseFolderFacade.find(folderId);\n if (target == null) {\n log.error(\"There is no folder with ID \" + folderId);\n throw new Exception(\"Ordner existiert nicht!\");\n }\n // check if folder and documents are in same case\n String caseId = null;\n ArrayList documents = new ArrayList<>();\n for (String docId : documentIds) {\n ArchiveFileDocumentsBean doc = this.archiveFileDocumentsFacade.find(docId);\n if (doc == null) {\n log.error(\"There is no document with ID \" + folderId);\n throw new Exception(\"Dokument existiert nicht!\");\n }\n documents.add(doc);\n if (caseId == null) {\n caseId = doc.getArchiveFileKey().getId();\n } else {\n if (!(doc.getArchiveFileKey().getId().equals(caseId))) {\n throw new Exception(\"Alle zu verschiebenden Dokumente m\u00fcssen zur selben Akte geh\u00f6ren!\");\n }\n }\n }\n ArchiveFileBean afb = this.archiveFileFacade.find(caseId);\n if (afb == null) {\n log.error(\"There is no case with ID \" + caseId);\n throw new Exception(\"Akte existiert nicht!\");\n }\n CaseFolder rootFolder = afb.getRootFolder();\n if (!containsFolder(rootFolder, folderId)) {\n log.error(\"Case \" + afb.getId() + \" \" + afb.getFileNumber() + \" does not contain a folder with id \" + folderId);\n throw new Exception(\"Akte \" + afb.getFileNumber() + \" enth\u00e4lt keinen Ordner mit ID \" + folderId);\n }\n StringGenerator idGen = new StringGenerator();\n for (ArchiveFileDocumentsBean doc : documents) {\n doc.setFolder(target);\n doc.bumpVersion(false);\n this.archiveFileDocumentsFacade.edit(doc);\n this.addCaseHistory(idGen.getID().toString(), afb, \"Dokument \" + doc.getName() + \" in den Ordner \" + target.getName() + \" verschoben\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public HiveIntervalDayTime getIntervalDayTime(int i) {\n throw new RuntimeException(\"Not implemented\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic Set getDevices(String tsFilePath, TsFileResource tsFileResource) {\n tsFileResource.readLock();\n try (InputStream inputStream = FSFactoryProducer.getFSFactory().getBufferedInputStream(tsFilePath + TsFileResource.RESOURCE_SUFFIX)) {\n // The first byte is VERSION_NUMBER, second byte is timeIndexType.\n byte[] bytes = ReadWriteIOUtils.readBytes(inputStream, 2);\n if (bytes[1] == ARRAY_DEVICE_TIME_INDEX_TYPE) {\n return ArrayDeviceTimeIndex.getDevices(inputStream);\n } else {\n return PlainDeviceTimeIndex.getDevices(inputStream);\n }\n } catch (NoSuchFileException e) {\n // deleted by ttl\n if (tsFileResource.isDeleted()) {\n return Collections.emptySet();\n } else {\n logger.error(\"Can't read file {} from disk \", tsFilePath + TsFileResource.RESOURCE_SUFFIX, e);\n throw new RuntimeException(\"Can't read file \" + tsFilePath + TsFileResource.RESOURCE_SUFFIX + \" from disk\");\n }\n } catch (Exception e) {\n logger.error(\"Failed to get devices from tsfile: {}\", tsFilePath + TsFileResource.RESOURCE_SUFFIX, e);\n throw new RuntimeException(\"Failed to get devices from tsfile: \" + tsFilePath + TsFileResource.RESOURCE_SUFFIX);\n } finally {\n tsFileResource.readUnlock();\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "/**\n * Validate an email address This code is from : http://www.rgagnon.com/javadetails/java-0452.html\n */\npublic static MailValidationResult isAddressValid(ILogChannel log, String address, String senderAddress, String defaultSMTPServer, int timeout, boolean deepCheck) {\n MailValidationResult result = new MailValidationResult();\n if (!isRegExValid(address)) {\n result.setErrorMessage(BaseMessages.getString(PKG, \"MailValidator.MalformedAddress\", address));\n return result;\n }\n // Find the separator for the domain name\n int pos = address.indexOf('@');\n // If the address does not contain an '@', it's not valid\n if (pos == -1) {\n return result;\n }\n if (!deepCheck) {\n result.setValide(true);\n return result;\n }\n // Isolate the domain/machine name and get a list of mail exchangers\n String domain = address.substring(++pos);\n // Maybe user want to switch to a default SMTP server?\n // In that case, we will ignore the domain\n // extracted from email address\n ArrayList mxList = new ArrayList<>();\n if (Utils.isEmpty(defaultSMTPServer)) {\n try {\n mxList = getMX(domain);\n // Just because we can send mail to the domain, doesn't mean that the\n // address is valid, but if we can't, it's a sure sign that it isn't\n if (mxList == null || mxList.isEmpty()) {\n result.setErrorMessage(BaseMessages.getString(PKG, \"MailValidator.NoMachinesInDomain\", domain));\n return result;\n }\n } catch (Exception ex) {\n result.setErrorMessage(BaseMessages.getString(PKG, \"MailValidator.ErrorGettingMachinesInDomain\", ex.getMessage()));\n return result;\n }\n } else {\n mxList.add(defaultSMTPServer);\n }\n if (log.isDebug()) {\n log.logDebug(BaseMessages.getString(PKG, \"MailValidator.ExchangersFound\", \"\" + mxList.size()));\n }\n // Now, do the SMTP validation, try each mail exchanger until we get\n // a positive acceptance. It *MAY* be possible for one MX to allow\n // a message [store and forwarder for example] and another [like\n // the actual mail server] to reject it. This is why we REALLY ought\n // to take the preference into account.\n for (int mx = 0; mx < mxList.size(); mx++) {\n boolean valid = false;\n BufferedReader rdr = null;\n BufferedWriter wtr = null;\n Socket skt = null;\n try {\n String exhanger = mxList.get(mx);\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.TryingExchanger\", exhanger));\n }\n int res;\n skt = new Socket(exhanger, 25);\n // set timeout (milliseconds)\n if (timeout > 0) {\n skt.setSoTimeout(timeout);\n }\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.ConnectingTo\", exhanger, \"25\", skt.isConnected() + \"\"));\n }\n rdr = new BufferedReader(new InputStreamReader(skt.getInputStream()));\n wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));\n res = hear(rdr);\n if (res != 220) {\n throw new Exception(BaseMessages.getString(PKG, \"MailValidator.InvalidHeader\"));\n }\n // say HELLO it's me\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.SayHello\", domain));\n }\n say(wtr, \"EHLO \" + domain);\n res = hear(rdr);\n if (res != 250) {\n throw new Exception(\"Not ESMTP\");\n }\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.ServerReplied\", \"\" + res));\n }\n // validate the sender address\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.CheckSender\", senderAddress));\n }\n say(wtr, \"MAIL FROM: <\" + senderAddress + \">\");\n res = hear(rdr);\n if (res != 250) {\n throw new Exception(BaseMessages.getString(PKG, \"MailValidator.SenderRejected\"));\n }\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.SenderAccepted\", \"\" + res));\n }\n // Validate receiver\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.CheckReceiver\", address));\n }\n say(wtr, \"RCPT TO: <\" + address + \">\");\n res = hear(rdr);\n // be polite\n say(wtr, \"RSET\");\n hear(rdr);\n say(wtr, \"QUIT\");\n hear(rdr);\n if (res != 250) {\n throw new Exception(BaseMessages.getString(PKG, \"MailValidator.AddressNotValid\", address));\n }\n if (log.isDebug()) {\n log.logDebug(className(), BaseMessages.getString(PKG, \"MailValidator.ReceiverAccepted\", address, \"\" + res));\n }\n valid = true;\n } catch (Exception ex) {\n // Do nothing but try next host\n result.setValide(false);\n result.setErrorMessage(ex.getMessage());\n } finally {\n if (rdr != null) {\n try {\n rdr.close();\n } catch (Exception e) {\n // ignore this\n }\n }\n if (wtr != null) {\n try {\n wtr.close();\n } catch (Exception e) {\n // ignore this\n }\n }\n if (skt != null) {\n try {\n skt.close();\n } catch (Exception e) {\n // ignore this\n }\n }\n if (valid) {\n result.setValide(true);\n result.setErrorMessage(null);\n if (log.isDebug()) {\n log.logDebug(className(), \"=============================================\");\n }\n return result;\n }\n }\n }\n if (log.isDebug()) {\n log.logDebug(className(), \"=============================================\");\n }\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * create temporary file and register it to delete-on-exit hook.\n * File.deleteOnExit is not used for possible memory leakage.\n *\n * Make sure to use {@link #deleteTmpFile(File)} after the file is no longer required,\n * and has been deleted to avoid a memory leak.\n */\npublic static File createTempFile(String lScratchDir, String prefix, String suffix) throws IOException {\n File tmpDir = lScratchDir == null ? null : new File(lScratchDir);\n if (tmpDir != null && !tmpDir.exists() && !tmpDir.mkdirs()) {\n // Do another exists to check to handle possible race condition\n // Another thread might have created the dir, if that is why\n // mkdirs returned false, that is fine\n if (!tmpDir.exists()) {\n throw new RuntimeException(\"Unable to create temp directory \" + lScratchDir);\n }\n }\n File tmpFile = File.createTempFile(prefix, suffix, tmpDir);\n ShutdownHookManager.deleteOnExit(tmpFile);\n return tmpFile;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private Map readParts(MultipartFormDataInput input) throws Exception{\r\n Map result = new HashMap();\r\n for (InputPart part : input.getParts()) {\r\n MultivaluedMap headers = part.getHeaders();\r\n String header = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);\r\n String filename = getFilename(header);\r\n if (filename == null) {\r\n throw new ServiceException(ServiceExceptionCode.INVALID_REQUEST, \"missing filename in part\");\r\n }\r\n filename = removeSpecialChars(filename);\r\n result.put(filename, part.getBody(InputStream.class, null));\r\n }\r\n return result;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void checkSearchValueNotNull(Input input) throws Exception{\r\n LOG.debug(\"Searching for output element with search value '{}' and sarch type {}\", input.getOutputNodeSearch(), input.getOutputNodeSearchType());\r\n if (input.getOutputNodeSearch() == null) {\r\n throw new XMLSignatureException(String.format(\"Wrong configuration: Value is missing for output node search %s.\", input.getOutputNodeSearchType()));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@POST\n@Path(KMSRESTConstants.KEYS_RESOURCE)\n@Consumes(MediaType.APPLICATION_JSON)\n@Produces(MediaType.APPLICATION_JSON + \"; \" + JettyUtils.UTF_8)\n@SuppressWarnings(\"unchecked\")\npublic Response createKey(Map jsonKey) throws Exception {\n try {\n LOG.trace(\"Entering createKey Method.\");\n KMSWebApp.getAdminCallsMeter().mark();\n UserGroupInformation user = HttpUserGroupInformation.get();\n final String name = (String) jsonKey.get(KMSRESTConstants.NAME_FIELD);\n checkNotEmpty(name, KMSRESTConstants.NAME_FIELD);\n assertAccess(KMSACLs.Type.CREATE, user, KMSOp.CREATE_KEY, name);\n String cipher = (String) jsonKey.get(KMSRESTConstants.CIPHER_FIELD);\n final String material;\n material = (String) jsonKey.get(KMSRESTConstants.MATERIAL_FIELD);\n int length = (jsonKey.containsKey(KMSRESTConstants.LENGTH_FIELD)) ? (Integer) jsonKey.get(KMSRESTConstants.LENGTH_FIELD) : 0;\n String description = (String) jsonKey.get(KMSRESTConstants.DESCRIPTION_FIELD);\n LOG.debug(\"Creating key with name {}, cipher being used{}, \" + \"length of key {}, description of key {}\", name, cipher, length, description);\n Map attributes = (Map) jsonKey.get(KMSRESTConstants.ATTRIBUTES_FIELD);\n if (material != null) {\n assertAccess(KMSACLs.Type.SET_KEY_MATERIAL, user, KMSOp.CREATE_KEY, name);\n }\n final KeyProvider.Options options = new KeyProvider.Options(KMSWebApp.getConfiguration());\n if (cipher != null) {\n options.setCipher(cipher);\n }\n if (length != 0) {\n options.setBitLength(length);\n }\n options.setDescription(description);\n options.setAttributes(attributes);\n KeyProvider.KeyVersion keyVersion = user.doAs(new PrivilegedExceptionAction() {\n\n @Override\n public KeyVersion run() throws Exception {\n KeyProvider.KeyVersion keyVersion = (material != null) ? provider.createKey(name, Base64.decodeBase64(material), options) : provider.createKey(name, options);\n provider.flush();\n return keyVersion;\n }\n });\n kmsAudit.ok(user, KMSOp.CREATE_KEY, name, \"UserProvidedMaterial:\" + (material != null) + \" Description:\" + description);\n if (!KMSWebApp.getACLs().hasAccess(KMSACLs.Type.GET, user)) {\n keyVersion = removeKeyMaterial(keyVersion);\n }\n Map json = KMSUtil.toJSON(keyVersion);\n String requestURL = KMSMDCFilter.getURL();\n int idx = requestURL.lastIndexOf(KMSRESTConstants.KEYS_RESOURCE);\n requestURL = requestURL.substring(0, idx);\n LOG.trace(\"Exiting createKey Method.\");\n return Response.created(getKeyURI(KMSRESTConstants.SERVICE_VERSION, name)).type(MediaType.APPLICATION_JSON).header(\"Location\", getKeyURI(requestURL, name)).entity(json).build();\n } catch (Exception e) {\n LOG.debug(\"Exception in createKey.\", e);\n throw e;\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public Enum boolean2enum(Class enumClass, Boolean v) throws HopValueException {\n throw new RuntimeException(CONST_CONVERSION_NOT_SUPPORTED);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected void removeNotificationListeners() throws Exception{\r\n getServerConnection().removeNotificationListener(mJmxEndpoint.getJMXObjectName(), this);\r\n if (mConnectionNotificationListener != null) {\r\n mConnector.removeConnectionNotificationListener(mConnectionNotificationListener);\r\n mConnectionNotificationListener = null;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `value` to the URL query string\n if (getValue() != null) {\n try {\n joiner.add(String.format(\"%svalue%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getValue()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `schema` to the URL query string\n if (getSchema() != null) {\n try {\n joiner.add(String.format(\"%sschema%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getSchema()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": " boolean processLog(String logName) throws Exception{\r\n DistributedLogManager dlm = getNamespace().openLog(logName);\r\n try {\r\n List segments = dlm.getLogSegments();\r\n for (LogSegmentMetadata segment : segments) {\r\n if (getLedgerID() == segment.getLogSegmentId()) {\r\n System.out.println(\"Found ledger \" + getLedgerID() + \" at log segment \" + segment + \" for stream '\" + logName + \"'\");\r\n return true;\r\n }\r\n }\r\n return false;\r\n } finally {\r\n dlm.close();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int querySequenceTable(String sequenceName, boolean isUpdate) {\n Connection connection = null;\n try {\n connection = getConnection(false);\n FederationQueryRunner runner = new FederationQueryRunner();\n return runner.selectOrUpdateSequenceTable(connection, sequenceName, isUpdate);\n } catch (Exception e) {\n throw new RuntimeException(\"Could not query sequence table!!\", e);\n } finally {\n // Return to the pool the CallableStatement\n try {\n FederationStateStoreUtils.returnToPool(LOG, null, connection);\n } catch (YarnException e) {\n LOG.error(\"close connection error.\", e);\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void innerBeforeRun() throws Exception{\r\n if (recordStore != null && !tieredStoreOffloadEnabled) {\r\n recordStore.beforeOperation();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed(value = { \"loginRole\" })\npublic void duplicateEmailTemplate(String templateName, String duplicateName) throws Exception {\n String localBaseDir = System.getProperty(\"jlawyer.server.basedirectory\");\n localBaseDir = localBaseDir.trim();\n if (!localBaseDir.endsWith(System.getProperty(\"file.separator\"))) {\n localBaseDir = localBaseDir + System.getProperty(\"file.separator\");\n }\n localBaseDir = localBaseDir + \"emailtemplates\" + System.getProperty(\"file.separator\");\n File f = new File(localBaseDir + templateName);\n if (!f.exists()) {\n throw new Exception(\"Datei existiert nicht: \" + templateName);\n }\n File fNew = new File(localBaseDir + duplicateName);\n if (fNew.exists()) {\n throw new Exception(\"Dateiname bereits vergeben: \" + duplicateName);\n }\n Path originalPath = Paths.get(localBaseDir + templateName);\n Path copied = Paths.get(localBaseDir + duplicateName);\n Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);\n boolean duplicated = fNew.exists();\n if (!duplicated) {\n throw new Exception(\"Duplizieren der Vorlage fehlgeschlagen\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static HttpEntity asHttpEntity(byte[] data, Exchange exchange) throws Exception{\r\n AbstractHttpEntity entity;\r\n String contentEncoding = null;\r\n ContentType contentType = null;\r\n if (exchange != null) {\r\n contentEncoding = exchange.getIn().getHeader(HttpConstants.CONTENT_ENCODING, String.class);\r\n String contentTypeAsString = ExchangeHelper.getContentType(exchange);\r\n if (contentTypeAsString != null) {\r\n contentType = ContentType.parse(contentTypeAsString);\r\n }\r\n }\r\n if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {\r\n boolean gzip = GZIPHelper.isGzip(contentEncoding);\r\n if (gzip) {\r\n InputStream stream = GZIPHelper.compressGzip(contentEncoding, data);\r\n int available = stream.available();\r\n entity = new InputStreamEntity(stream, stream instanceof ByteArrayInputStream ? available != 0 ? available : -1 : -1, contentType, contentEncoding);\r\n } else {\r\n entity = new ByteArrayEntity(data, contentType, contentEncoding);\r\n }\r\n } else {\r\n entity = new ByteArrayEntity(data, contentType, contentEncoding);\r\n }\r\n return entity;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Properties getConnectionPoolProperties(Configuration conf) throws Exception{\r\n Properties dbProperties = getDefaultDBCPProperties();\r\n Map userProperties = conf.getValByRegex(DBCP_CONFIG_PREFIX + \"\\\\.*\");\r\n if ((userProperties != null) && (!userProperties.isEmpty())) {\r\n for (Entry entry : userProperties.entrySet()) {\r\n dbProperties.put(removeDbcpPrefix(entry.getKey()), entry.getValue());\r\n }\r\n }\r\n String passwd = JdbcStorageConfigManager.getPasswordFromProperties(dbProperties, GenericJdbcDatabaseAccessor::removeDbcpPrefix);\r\n if (passwd != null) {\r\n dbProperties.put(removeDbcpPrefix(JdbcStorageConfigManager.CONFIG_PWD), passwd);\r\n }\r\n dbProperties.put(\"url\", conf.get(JdbcStorageConfig.JDBC_URL.getPropertyName()));\r\n dbProperties.put(\"driverClassName\", conf.get(JdbcStorageConfig.JDBC_DRIVER_CLASS.getPropertyName()));\r\n dbProperties.put(\"type\", \"javax.sql.DataSource\");\r\n return dbProperties;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ReplyManager createReplyManager(String replyTo) throws Exception{\r\n ReplyManager replyManager = new QueueReplyManager(getEndpoint().getCamelContext());\r\n replyManager.setEndpoint(getEndpoint());\r\n String name = \"JmsReplyManagerTimeoutChecker[\" + replyTo + \"]\";\r\n ScheduledExecutorService replyManagerScheduledExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(name, name);\r\n replyManager.setScheduledExecutorService(replyManagerScheduledExecutorService);\r\n name = \"JmsReplyManagerOnTimeout[\" + replyTo + \"]\";\r\n int max = getEndpoint().getComponent().getReplyToOnTimeoutMaxConcurrentConsumers();\r\n if (max <= 0) {\r\n throw new IllegalArgumentException(\"The option replyToOnTimeoutMaxConcurrentConsumers must be >= 1\");\r\n }\r\n ExecutorService replyManagerExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newThreadPool(replyManager, name, 0, max);\r\n replyManager.setOnTimeoutExecutorService(replyManagerExecutorService);\r\n ServiceHelper.startService(replyManager);\r\n return replyManager;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) throws Exception{\r\n if (cdsSequenceHashMap.containsKey(accession.getID())) {\r\n throw new Exception(\"Duplicate accession id \" + accession.getID());\r\n }\r\n CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase);\r\n cdsSequence.setAccession(accession);\r\n cdsSequenceList.add(cdsSequence);\r\n Collections.sort(cdsSequenceList, new CDSComparator());\r\n cdsSequenceHashMap.put(accession.getID(), cdsSequence);\r\n return cdsSequence;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void nextEvent() throws Exception {\n ArrayList persons = new ArrayList<>();\n ArrayList clients = (ArrayList) data.get(\"clients.addressbeans\");\n ArrayList allParties = (ArrayList) data.get(\"clients.allparties\");\n if (allParties == null)\n allParties = new ArrayList<>();\n DefaultTableModel dm = (DefaultTableModel) this.tblClients.getModel();\n for (int i = 0; i < dm.getRowCount(); i++) {\n Boolean enabled = (Boolean) dm.getValueAt(i, 0);\n if (enabled) {\n // user chose to submit this client\n AddressBean ab = clients.get(i);\n PartyTypeBean ptb = com.jdimension.jlawyer.client.drebis.DrebisUtils.getType(ab, allParties);\n if (ptb != null) {\n // will only store ONE type of party\n ServerSettings.getInstance().setSetting(\"drebis.\" + this.getClass().getName() + \".selectedtype\", ptb.getId());\n }\n // columns: 0 submit, 1 name, 2 firstname, 3 company, 4 street, 5 zip, 6 city, 7 countrycode, 8 phone, 9 fax, 10 email\n DrebisPerson p = new DrebisPerson();\n if (dm.getValueAt(i, 6) != null)\n p.setCity(dm.getValueAt(i, 6).toString());\n if (dm.getValueAt(i, 3) != null)\n p.setCompany(dm.getValueAt(i, 3).toString());\n if (dm.getValueAt(i, 7) != null)\n p.setCountryCode(dm.getValueAt(i, 7).toString());\n if (dm.getValueAt(i, 10) != null)\n p.setEmail(dm.getValueAt(i, 10).toString());\n if (dm.getValueAt(i, 9) != null)\n p.setFax(dm.getValueAt(i, 9).toString());\n if (dm.getValueAt(i, 2) != null)\n p.setFirstName(dm.getValueAt(i, 2).toString());\n if (dm.getValueAt(i, 1) != null)\n p.setName(dm.getValueAt(i, 1).toString());\n if (dm.getValueAt(i, 8) != null)\n p.setPhone(dm.getValueAt(i, 8).toString());\n if (dm.getValueAt(i, 4) != null)\n p.setStreet(dm.getValueAt(i, 4).toString());\n if (dm.getValueAt(i, 5) != null)\n p.setZipCode(dm.getValueAt(i, 5).toString());\n p.validate();\n persons.add(p);\n }\n }\n if (persons.isEmpty())\n throw new Exception(\"Es muss mindestens ein zu \u00fcbertragender Mandant angegeben werden\");\n if (this.cmbInsurances.getSelectedItem() == null) {\n throw new Exception(\"Es muss ein von Drebis unterst\u00fctztes Versicherungsunternehmen gew\u00e4hlt werden\");\n }\n // default \"\" insurance (empty insurance) has been selected\n if (this.cmbInsurances.getSelectedItem() instanceof String)\n throw new Exception(\"Es muss ein von Drebis unterst\u00fctztes Versicherungsunternehmen gew\u00e4hlt werden\");\n if (!(this.cmbInsurance.getSelectedItem() == null) && !(\"\".equals(this.cmbInsurance.getSelectedItem().toString().trim()))) {\n String regex = ((InsuranceInfo) this.cmbInsurances.getSelectedItem()).getPolicyNumberRegEx();\n if (regex != null && !(\"\".equals(regex))) {\n if (!this.cmbInsurance.getSelectedItem().toString().matches(regex)) {\n throw new Exception(\"Versicherungsschein inkorrekt - bitte beachten Sie die Hinweise hinter dem Eingabefeld\" + System.getProperty(\"line.separator\") + ((InsuranceInfo) this.cmbInsurances.getSelectedItem()).getPolicyNumberRegEx());\n }\n }\n }\n if (this.txtFileNumber.getText() == null || \"\".equalsIgnoreCase(this.txtFileNumber.getText().trim()))\n throw new Exception(\"Aktenzeichen darf nicht leer sein!\");\n if (this.txtName.getText() == null || \"\".equalsIgnoreCase(this.txtName.getText().trim()))\n throw new Exception(\"Kurzrubrum darf nicht leer sein!\");\n this.data.put(\"clients.drebispersons\", persons);\n this.data.put(\"clients.archivefilename\", this.txtName.getText());\n this.data.put(\"clients.archivefilenumber\", this.txtFileNumber.getText());\n this.data.put(\"clients.insurance\", this.cmbInsurances.getSelectedItem());\n this.data.put(\"clients.insurancepolicy\", this.cmbInsurance.getSelectedItem().toString());\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Driver findLocalDriver(String url) throws Exception{\r\n Objects.requireNonNull(url);\r\n Collection currentDrivers = drivers == null ? Collections.emptyList() : drivers;\r\n for (Driver d : currentDrivers) {\r\n try {\r\n String clazzName = d.getClass().getName();\r\n Driver driver = (Driver) Class.forName(clazzName, true, Thread.currentThread().getContextClassLoader()).newInstance();\r\n if (driver.acceptsURL(url) && isSupportedLocalDriver(driver)) {\r\n return driver;\r\n }\r\n } catch (SQLException e) {\r\n throw e;\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static InputStream openInputStream(CamelContext camelContext, String uri) throws Exception{\r\n if (camelContext != null) {\r\n uri = camelContext.resolvePropertyPlaceholders(uri);\r\n return ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri);\r\n }\r\n return Thread.currentThread().getContextClassLoader().getResourceAsStream(uri);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private InputStream initializeStreamRawMode() throws Exception{\r\n IOHelper.close(inputStreamToClose);\r\n if (urlConnectionToClose != null) {\r\n closeURLConnection(urlConnectionToClose);\r\n }\r\n if (\"in\".equals(uri)) {\r\n inputStream = System.in;\r\n inputStreamToClose = null;\r\n } else if (\"file\".equals(uri)) {\r\n inputStream = resolveStreamFromFile();\r\n inputStreamToClose = inputStream;\r\n } else if (\"http\".equals(uri)) {\r\n inputStream = resolveStreamFromUrl();\r\n inputStreamToClose = inputStream;\r\n }\r\n return inputStream;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@GetMapping(value = \"/checkToken\", headers = \"Accept=*/*\", produces = { \"application/json\", \"text/xml\" })\n@ResponseBody\nprotected CheckedToken token(HttpServletRequest request, HttpServletResponse response) throws Exception {\n logger.debug(\"checkToken\");\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "private static void storeOpenOfficeFile(Path file, InputStream source) throws Exception{\r\n try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(file)))) {\r\n ZipEntry zipEntry = new ZipEntry(\"content.xml\");\r\n out.putNextEntry(zipEntry);\r\n int c;\r\n while ((c = source.read()) >= 0) {\r\n out.write(c);\r\n }\r\n out.closeEntry();\r\n OpenOfficeDocumentCreator.addResourceFile(\"meta.xml\", \"/resource/openoffice/meta.xml\", out);\r\n OpenOfficeDocumentCreator.addResourceFile(\"mimetype\", \"/resource/openoffice/mimetype\", out);\r\n OpenOfficeDocumentCreator.addResourceFile(\"META-INF/manifest.xml\", \"/resource/openoffice/manifest.xml\", out);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean indexes(String line) throws Exception{\r\n return metadata(\"getIndexInfo\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"table name\"), false + \"\", true + \"\" });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void closeInternal() throws Exception{\r\n if (task != null) {\r\n task.cancel(true);\r\n }\r\n if (lock != null) {\r\n lock.release();\r\n }\r\n closeLockFile();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic HivePolicyProvider next() {\n try {\n if (currentAuthorizerPosition < authorizers.size()) {\n return authorizers.get(currentAuthorizerPosition++).getHivePolicyProvider();\n } else {\n return authorizationProviders.get(authorizationProviderPosition++).getHivePolicyProvider();\n }\n } catch (HiveAuthzPluginException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void appendZooKeeperConf(List newLines, File tmpDir) throws Exception{\r\n try (FileWriter f = new FileWriter(tmpDir.getAbsolutePath() + \"/conf/zoo.cfg\", true);\r\n BufferedWriter b = new BufferedWriter(f);\r\n PrintWriter p = new PrintWriter(b)) {\r\n p.println(\"\");\r\n for (String line : newLines) {\r\n p.println(line);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@VisibleForTesting\nInputDataInformationEvent write(int count, MRSplitProto mrSplit) {\n InputDataInformationEvent diEvent;\n Path filePath = getSerializedFilePath(count);\n Runnable task = () -> {\n if (!anyTaskFailed.get()) {\n try {\n writeSplit(count, mrSplit, filePath);\n } catch (IOException e) {\n anyTaskFailed.set(true);\n throw new RuntimeException(e);\n }\n }\n };\n asyncTasks.add(CompletableFuture.runAsync(task, executor));\n return InputDataInformationEvent.createWithSerializedPath(count, filePath.toString());\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void disconnect(HttpConsumer consumer) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void include(String content) throws Exception{\r\n InputStream input = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));\r\n HplsqlLexer lexer = new HplsqlLexer(new ANTLRInputStream(input));\r\n CommonTokenStream tokens = new CommonTokenStream(lexer);\r\n HplsqlParser parser = newParser(tokens);\r\n ParseTree tree = parser.program();\r\n visit(tree);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected String buildCustomConfigCommand() throws Exception{\r\n String config = buildCustomConfigContent();\r\n String filePath = buildConfigFilePath();\r\n createConfigFileIfNotExists(config, filePath);\r\n return filePath;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@GET\n@Path(\"{processId}/source\")\n@Produces(MediaType.TEXT_PLAIN)\npublic Response getSourceFileByProcessId(@PathParam(\"processId\") String processId) throws Exception {\n Optional sourceFile = sourceFilesProvider.getProcessSourceFile(processId);\n if (sourceFile.isEmpty()) {\n return Response.status(Response.Status.NOT_FOUND).build();\n }\n return Response.ok(sourceFile.get().readContents()).build();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": " void onDrop() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Object callStaticMethod(String className, String methodName, ArrayList args) throws Exception{\r\n Class klass = Class.forName(className, true, classloader);\r\n try {\r\n Class[] paramTypes = args.stream().map((a) -> a.getClass()).toArray(Class[]::new);\r\n return klass.getMethod(methodName, paramTypes).invoke(null, args.stream().toArray(Object[]::new));\r\n } catch (NoSuchMethodException nsme) {\r\n Class[] paramTypes = args.stream().map((a) -> {\r\n Class k = a.getClass();\r\n try {\r\n Object type = k.getField(\"TYPE\").get(null);\r\n if (type instanceof Class) {\r\n return (Class) type;\r\n } else {\r\n return k;\r\n }\r\n } catch (IllegalAccessException | NoSuchFieldException nsfe) {\r\n return k;\r\n }\r\n }).toArray(Class[]::new);\r\n return klass.getMethod(methodName, paramTypes).invoke(null, args.stream().toArray(Object[]::new));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void close() throws Exception{\r\n reader.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void commit() throws Exception{\r\n throw new UnsupportedOperationException();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doPostTearDown() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void launchDockerContainer() throws Exception {\n runCmdAndPrintStreams(buildRmCmd(), 600);\n if (runCmdAndPrintStreams(buildRunCmd(), 600).rc != 0) {\n printDockerEvents();\n throw new RuntimeException(\"Unable to start docker container\");\n }\n long startTime = System.currentTimeMillis();\n ProcessResults pr;\n do {\n Thread.sleep(1000);\n pr = runCmdAndPrintStreams(buildLogCmd(), 30);\n if (pr.rc != 0) {\n printDockerEvents();\n throw new RuntimeException(\"Failed to get docker logs\");\n }\n } while (startTime + MAX_STARTUP_WAIT >= System.currentTimeMillis() && !isContainerReady(pr));\n if (startTime + MAX_STARTUP_WAIT < System.currentTimeMillis()) {\n printDockerEvents();\n throw new RuntimeException(String.format(\"Container initialization failed within %d seconds. Please check the hive logs.\", MAX_STARTUP_WAIT / 1000));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@ProcessElement\npublic void processElement(ProcessContext processContext) {\n try {\n KV> element = processContext.element();\n KV value = element.getValue();\n HopRow leftValue = value.getKey();\n HopRow rightValue = value.getValue();\n Object[] outputRow = new Object[leftRowMeta.size() + rightRowMeta.size()];\n for (int i = 0; i < leftRowMeta.size(); i++) {\n // Only add key for inner and left-outer join types\n // Otherwise, leave this field blank to match up with default Hop behavior of the transform.\n // If the left-hand side row is empty, we don't want to add keys or values\n //\n if (leftValue.isNotEmpty()) {\n Integer keyIndex = leftKeyIndexes.get(i);\n if (keyIndex != null) {\n outputRow[i] = leftValue.getRow()[keyIndex];\n }\n Integer valueIndex = leftValueIndexes.get(i);\n if (valueIndex != null) {\n outputRow[i] = leftValue.getRow()[valueIndex];\n }\n }\n }\n for (int i = 0; i < rightRowMeta.size(); i++) {\n // If the right-hand side row is empty, we don't want to add keys or values\n //\n if (rightValue.isNotEmpty()) {\n Integer keyIndex = rightKeyIndexes.get(i);\n if (keyIndex != null) {\n outputRow[leftRowMeta.size() + i] = rightValue.getRow()[keyIndex];\n }\n Integer valueIndex = rightValueIndexes.get(i);\n if (valueIndex != null) {\n outputRow[leftRowMeta.size() + i] = rightValue.getRow()[valueIndex];\n }\n }\n }\n processContext.output(new HopRow(outputRow));\n writtenCounter.inc();\n } catch (Exception e) {\n errorCounter.inc();\n LOG.error(\"Error assembling rows\", e);\n throw new RuntimeException(\"Error assembling output KV>\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * @param remoteFile the file to read\n * @param context the execution context\n * @param outputDataTypeMappingConfiguration\n * @param useKerberos\n * @return the reader object\n * @throws Exception thrown if doAs user does not work\n */\nprivate AbstractFileFormatReader getReader(final RemoteFile remoteFile, final ExecutionContext context, final DataTypeMappingConfiguration outputDataTypeMappingConfiguration, final boolean useKerberos) throws Exception {\n final AbstractFileFormatReader reader;\n reader = m_settings.getFormatFactory().getReader(remoteFile, context, outputDataTypeMappingConfiguration, useKerberos);\n return reader;\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "private void logCoverageSummary(ManagedCamelContextMBean managedCamelContext, ModelCamelContext context) throws Exception{\r\n StringBuilder builder = new StringBuilder(\"\\nCoverage summary\\n\");\r\n int routes = managedCamelContext.getTotalRoutes();\r\n long contextExchangesTotal = managedCamelContext.getExchangesTotal();\r\n List uncoveredRoutes = new ArrayList<>();\r\n StringBuilder routesSummary = new StringBuilder();\r\n routesSummary.append(\"\\tProcessor coverage\\n\");\r\n MBeanServer server = context.getManagementStrategy().getManagementAgent().getMBeanServer();\r\n Map> processorsForRoute = findProcessorsForEachRoute(server, context);\r\n for (Route route : context.getRoutes()) {\r\n ManagedRouteMBean managedRoute = context.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class).getManagedRoute(route.getId());\r\n if (managedRoute.getExchangesTotal() == 0) {\r\n uncoveredRoutes.add(route.getId());\r\n }\r\n long routeCoveragePercentage = Math.round((double) managedRoute.getExchangesTotal() / contextExchangesTotal * 100);\r\n routesSummary.append(\"\\t\\tRoute \").append(route.getId()).append(\" total: \").append(managedRoute.getExchangesTotal()).append(\" (\").append(routeCoveragePercentage).append(\"%)\\n\");\r\n if (server != null) {\r\n List processors = processorsForRoute.get(route.getId());\r\n if (processors != null) {\r\n for (ManagedProcessorMBean managedProcessor : processors) {\r\n String processorId = managedProcessor.getProcessorId();\r\n long processorExchangesTotal = managedProcessor.getExchangesTotal();\r\n long processorCoveragePercentage = Math.round((double) processorExchangesTotal / contextExchangesTotal * 100);\r\n routesSummary.append(\"\\t\\t\\tProcessor \").append(processorId).append(\" total: \").append(processorExchangesTotal).append(\" (\").append(processorCoveragePercentage).append(\"%)\\n\");\r\n }\r\n }\r\n }\r\n }\r\n int used = routes - uncoveredRoutes.size();\r\n long contextPercentage = Math.round((double) used / routes * 100);\r\n builder.append(\"\\tRoute coverage: \").append(used).append(\" out of \").append(routes).append(\" routes used (\").append(contextPercentage).append(\"%)\\n\");\r\n builder.append(\"\\t\\tCamelContext (\").append(managedCamelContext.getCamelId()).append(\") total: \").append(contextExchangesTotal).append(\"\\n\");\r\n if (!uncoveredRoutes.isEmpty()) {\r\n builder.append(\"\\t\\tUncovered routes: \").append(String.join(\", \", uncoveredRoutes)).append(\"\\n\");\r\n }\r\n builder.append(routesSummary);\r\n LOG.info(builder.toString());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void copyToFile(HplsqlParser.Copy_stmtContext ctx, QueryResult query) throws Exception{\r\n String filename = null;\r\n if (ctx.copy_target().expr() != null) {\r\n filename = evalPop(ctx.copy_target().expr()).toString();\r\n } else {\r\n filename = ctx.copy_target().getText();\r\n }\r\n byte[] del = delimiter.getBytes();\r\n byte[] rowdel = \"\\n\".getBytes();\r\n byte[] nullstr = \"NULL\".getBytes();\r\n int cols = query.columnCount();\r\n int rows = 0;\r\n long bytes = 0;\r\n if (trace || info) {\r\n String mes = \"Query executed: \" + cols + \" columns, output file: \" + filename;\r\n if (trace) {\r\n trace(ctx, mes);\r\n } else {\r\n info(ctx, mes);\r\n }\r\n }\r\n java.io.File file = null;\r\n File hdfsFile = null;\r\n if (ctx.T_HDFS() == null) {\r\n file = new java.io.File(filename);\r\n } else {\r\n hdfsFile = new File();\r\n }\r\n OutputStream out = null;\r\n timer.start();\r\n try {\r\n if (file != null) {\r\n if (!file.exists()) {\r\n file.createNewFile();\r\n }\r\n out = new FileOutputStream(file, false);\r\n } else {\r\n out = hdfsFile.create(filename, true);\r\n }\r\n String col;\r\n String sql = \"\";\r\n if (sqlInsert) {\r\n sql = \"INSERT INTO \" + sqlInsertName + \" VALUES (\";\r\n rowdel = \");\\n\".getBytes();\r\n }\r\n while (query.next()) {\r\n if (sqlInsert) {\r\n out.write(sql.getBytes());\r\n }\r\n for (int i = 0; i < cols; i++) {\r\n if (i > 0) {\r\n out.write(del);\r\n bytes += del.length;\r\n }\r\n col = query.column(i, String.class);\r\n if (col != null) {\r\n if (sqlInsert) {\r\n col = Utils.quoteString(col);\r\n }\r\n byte[] b = col.getBytes();\r\n out.write(b);\r\n bytes += b.length;\r\n } else if (sqlInsert) {\r\n out.write(nullstr);\r\n }\r\n }\r\n out.write(rowdel);\r\n bytes += rowdel.length;\r\n rows++;\r\n }\r\n exec.setRowCount(rows);\r\n } finally {\r\n if (out != null) {\r\n out.close();\r\n }\r\n }\r\n long elapsed = timer.stop();\r\n if (info) {\r\n DecimalFormat df = new DecimalFormat(\"#,##0.00\");\r\n df.setRoundingMode(RoundingMode.HALF_UP);\r\n info(ctx, \"COPY completed: \" + rows + \" row(s), \" + Utils.formatSizeInBytes(bytes) + \", \" + timer.format() + \", \" + df.format(rows / (elapsed / 1000.0)) + \" rows/sec\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean nativesql(String sql) throws Exception{\r\n if (sql.startsWith(BeeLine.COMMAND_PREFIX)) {\r\n sql = sql.substring(1);\r\n }\r\n if (sql.startsWith(\"native\")) {\r\n sql = sql.substring(\"native\".length() + 1);\r\n }\r\n String nat = beeLine.getConnection().nativeSQL(sql);\r\n beeLine.output(nat);\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Load schemas from root element in the XML configuration file.\n * @param root root element\n * @return EC schema map\n */\nprivate Map loadSchemas(Element root) {\n NodeList elements = root.getElementsByTagName(\"schemas\").item(0).getChildNodes();\n Map schemas = new HashMap();\n for (int i = 0; i < elements.getLength(); i++) {\n Node node = elements.item(i);\n if (node instanceof Element) {\n Element element = (Element) node;\n if (\"schema\".equals(element.getTagName())) {\n String schemaId = element.getAttribute(\"id\");\n ECSchema schema = loadSchema(element);\n if (!schemas.containsValue(schema)) {\n schemas.put(schemaId, schema);\n } else {\n throw new RuntimeException(\"Repetitive schemas in EC policy\" + \" configuration file: \" + schemaId);\n }\n } else {\n throw new RuntimeException(\"Bad element in EC policy\" + \" configuration file: \" + element.getTagName());\n }\n }\n }\n return schemas;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private Map> getTimeseriesMetadataMapWithReader(TsFileSelfCheckToolReader reader) throws Exception {\n Map> timeseriesMetadataMap = null;\n timeseriesMetadataMap = reader.getAllTimeseriesMetadataWithOffset();\n return timeseriesMetadataMap;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public void addColumnComparator(int keyIndex, int columnTypeSpecificIndex, ColumnVector.Type columnVectorType, char sortOrder, char nullOrder) {\n Comparator comparator;\n switch(columnVectorType) {\n case LONG:\n case DECIMAL_64:\n comparator = (o1, o2) -> Long.compare(o1.getLongValue(columnTypeSpecificIndex), o2.getLongValue(columnTypeSpecificIndex));\n break;\n case DOUBLE:\n comparator = (o1, o2) -> Double.compare(o1.getDoubleValue(columnTypeSpecificIndex), o2.getDoubleValue(columnTypeSpecificIndex));\n break;\n case BYTES:\n comparator = (o1, o2) -> StringExpr.compare(o1.getBytes(columnTypeSpecificIndex), o1.getByteStart(columnTypeSpecificIndex), o1.getByteLength(columnTypeSpecificIndex), o2.getBytes(columnTypeSpecificIndex), o2.getByteStart(columnTypeSpecificIndex), o2.getByteLength(columnTypeSpecificIndex));\n break;\n case DECIMAL:\n comparator = (o1, o2) -> o1.getDecimal(columnTypeSpecificIndex).compareTo(o2.getDecimal(columnTypeSpecificIndex));\n break;\n case TIMESTAMP:\n comparator = (o1, o2) -> o1.getTimestamp(columnTypeSpecificIndex).compareTo(o2.getTimestamp(columnTypeSpecificIndex));\n break;\n case INTERVAL_DAY_TIME:\n comparator = (o1, o2) -> o1.getIntervalDayTime(columnTypeSpecificIndex).compareTo(o2.getIntervalDayTime(columnTypeSpecificIndex));\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector columnVectorType \" + columnVectorType);\n }\n comparators[keyIndex] = (new VectorHashKeyWrapperBaseComparator(keyIndex, sortOrder == '-' ? comparator.reversed() : comparator, nullOrder));\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private Optional parseUsingGrobid(String plainText) throws RuntimeException{\r\n try {\r\n return grobidService.processCitation(plainText, importFormatPreferences, GrobidService.ConsolidateCitations.WITH_METADATA);\r\n } catch (SocketTimeoutException e) {\r\n String msg = \"Connection timed out.\";\r\n LOGGER.debug(msg, e);\r\n throw new RuntimeException(msg, e);\r\n } catch (IOException | ParseException e) {\r\n String msg = \"Could not process citation. \" + e.getMessage();\r\n LOGGER.debug(msg, e);\r\n return Optional.empty();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Writable serialize(Object obj, ObjectInspector objInspector) throws Exception{\r\n if (objInspector.getCategory() != ObjectInspector.Category.STRUCT) {\r\n throw new SerDeException(getClass().toString() + \" can only serialize struct types, but we got: \" + objInspector.getTypeName());\r\n }\r\n StructObjectInspector soi = (StructObjectInspector) objInspector;\r\n List fields = soi.getAllStructFieldRefs();\r\n List values = soi.getStructFieldsDataAsList(obj);\r\n StructField field = fields.get(keyIndex);\r\n Object value = values.get(keyIndex);\r\n byte[] key = keyFactory.serializeKey(value, field);\r\n if (key == null) {\r\n throw new SerDeException(\"HBase row key cannot be NULL\");\r\n }\r\n long timestamp = putTimestamp;\r\n if (timestamp < 0 && timestampIndex >= 0) {\r\n ObjectInspector inspector = fields.get(timestampIndex).getFieldObjectInspector();\r\n value = values.get(timestampIndex);\r\n if (inspector instanceof LongObjectInspector) {\r\n timestamp = ((LongObjectInspector) inspector).get(value);\r\n } else {\r\n PrimitiveObjectInspector primitive = (PrimitiveObjectInspector) inspector;\r\n timestamp = PrimitiveObjectInspectorUtils.getTimestamp(value, primitive).toEpochMilli();\r\n }\r\n }\r\n Put put = timestamp >= 0 ? new Put(key, timestamp) : new Put(key);\r\n for (int i = 0; i < fields.size(); i++) {\r\n if (i == keyIndex || i == timestampIndex) {\r\n continue;\r\n }\r\n field = fields.get(i);\r\n value = values.get(i);\r\n serializeField(value, field, columnMappings[i], put);\r\n }\r\n return new PutWritable(put);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " OpenAPI loadOpenApiModel(String apiDoc) throws Exception{\r\n final OpenAPIParser openApiParser = new OpenAPIParser();\r\n final SwaggerParseResult openApi = openApiParser.readLocation(apiDoc, null, null);\r\n if (openApi != null && openApi.getOpenAPI() != null) {\r\n return openApi.getOpenAPI();\r\n }\r\n throw new IllegalArgumentException(\"The given OpenApi specification could not be loaded from `\" + apiDoc + \"`.\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static URI createDLMURI(String zkServers, String path) throws Exception{\r\n return URI.create(\"distributedlog://\" + zkServers + DLOG_NAMESPACE + path);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"loginRole\" })\npublic void addObservedFile(String fileName, byte[] content, String source) throws Exception {\n if (fileName == null || \"\".equals(fileName)) {\n throw new Exception(\"Dokumentname darf nicht leer sein!\");\n }\n ServerSettingsBean mode = settingsFacade.find(\"jlawyer.server.observe.directory\");\n if (mode == null || \"\".equals(mode.getSettingValue())) {\n log.error(\"No server directory configured for scans\");\n throw new Exception(\"No server directory configured for scans\");\n }\n String scanDir = mode.getSettingValue();\n if (scanDir == null || \"\".equals(scanDir)) {\n log.error(\"No server directory configured for scans\");\n throw new Exception(\"No server directory configured for scans\");\n }\n File scanDirectory = new File(scanDir);\n if (!scanDirectory.exists()) {\n log.error(\"Server directory for scans does not exist: \" + scanDir);\n throw new Exception(\"Server directory for scans does not exist: \" + scanDir);\n }\n if (!scanDirectory.isDirectory()) {\n log.error(\"Server directory for scans is not a directory: \" + scanDir);\n throw new Exception(\"Server directory for scans is not a directory: \" + scanDir);\n }\n File[] children = scanDirectory.listFiles();\n if (children.length > 5000) {\n log.error(\"Scan directory has exceeded maximum of 5000 files!\");\n throw new Exception(\"Scan directory has exceeded maximum of 5000 files!\");\n }\n String fullDir = scanDir;\n if (!scanDir.endsWith(File.separator)) {\n fullDir = fullDir + File.separator;\n }\n String fullPath = fullDir + fileName;\n File uploadFile = new File(fullPath);\n if (uploadFile.exists()) {\n int copy = 1;\n while (uploadFile.exists()) {\n copy = copy + 1;\n if (copy == 6) {\n log.warn(\"observed file \" + fileName + \" can not be stored, already has more than 5 copies\");\n return;\n }\n fullPath = fullDir + \"(\" + copy + \") \" + fileName;\n uploadFile = new File(fullPath);\n }\n }\n try (FileOutputStream fout = new FileOutputStream(uploadFile)) {\n fout.write(content);\n }\n OcrRequest req = new OcrRequest();\n if (!OcrUtils.hasMetadata(uploadFile)) {\n FileMetadata newMetadata = OcrUtils.generateMetadata(uploadFile, context.getCallerPrincipal().getName(), source);\n if (newMetadata.getOcrStatus() == FileMetadata.OCRSTATUS_OPEN) {\n // send request to perform OCR\n req.getAbsolutePaths().add(uploadFile.getAbsolutePath());\n }\n }\n if (!req.getAbsolutePaths().isEmpty()) {\n this.publishOcrRequest(req);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "@Override\npublic void launch(boolean autoCloseExistingDocument) throws Exception {\n if (isDocumentOpen(store.getDocumentIdentifier()))\n throw new Exception(\"Dokument \" + store.getFileName() + \" ist bereits ge\u00f6ffnet\");\n try {\n ObservedDocument odoc = new ObservedDocument(url, store, this);\n DocumentObserver observer = DocumentObserver.getInstance();\n odoc.setStatus(ObservedDocument.STATUS_LAUNCHING);\n observer.addDocument(odoc);\n MessageExport mex = new MessageExport();\n byte[] content = FileUtils.readFile(new File(url));\n mex.setContent(content);\n Message msg = BeaAccess.getMessageFromExport(mex);\n ArchiveFileBean archiveFile = null;\n if (this.store instanceof CaseDocumentStore) {\n archiveFile = ((CaseDocumentStore) store).getCase();\n }\n ViewBeaDialog view = null;\n if (this.parent == null)\n view = new ViewBeaDialog(EditorsRegistry.getInstance().getMainWindow(), archiveFile, odoc);\n else\n view = new ViewBeaDialog(parent, archiveFile, odoc);\n view.setMessage(msg);\n try {\n view.setTitle(msg.getSubject());\n } catch (Throwable t) {\n log.error(t);\n view.setTitle(\"beA-Nachrichtenansicht\");\n }\n view.setVisible(true);\n odoc.setStatus(ObservedDocument.STATUS_OPEN);\n } catch (Exception ex) {\n log.error(ex);\n throw ex;\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static IMetaStoreClient getHiveMetaClient(String serverUri, String serverKerberosPrincipal, Class clazz, Job job) throws Exception {\n // The job configuration is passed in so the configuration will be cloned\n // from the pig job configuration. This is necessary for overriding\n // metastore configuration arguments like the metastore jdbc connection string\n // and password, in the case of an embedded metastore, which you get when\n // hive.metastore.uris = \"\".\n HiveConf hiveConf = new HiveConf(job.getConfiguration(), clazz);\n if (serverUri != null) {\n hiveConf.setVar(HiveConf.ConfVars.METASTORE_URIS, serverUri.trim());\n }\n if (serverKerberosPrincipal != null) {\n hiveConf.setBoolVar(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL, true);\n hiveConf.setVar(HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL, serverKerberosPrincipal);\n }\n try {\n return HCatUtil.getHiveMetastoreClient(hiveConf);\n } catch (Exception e) {\n throw new Exception(\"Could not instantiate a HiveMetaStoreClient connecting to server uri:[\" + serverUri + \"]\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Set the proxy of this socket factory as described in the string\n * parameter\n *\n * @param proxyStr the proxy address using the format \"host:port\"\n */\nprivate void setProxy(String proxyStr) {\n String[] strs = proxyStr.split(\":\", 2);\n if (strs.length != 2)\n throw new RuntimeException(\"Bad SOCKS proxy parameter: \" + proxyStr);\n String host = strs[0];\n int port = Integer.parseInt(strs[1]);\n this.proxy = new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(host, port));\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void handleChangeClusterVersion(HttpPostCommand cmd) throws Throwable{\r\n String[] params = decodeParamsAndAuthenticate(cmd, 3);\r\n ClusterService clusterService = getNode().getClusterService();\r\n Version version = Version.of(params[2]);\r\n clusterService.changeClusterVersion(version);\r\n JsonObject rsp = response(SUCCESS, \"version\", clusterService.getClusterVersion().toString());\r\n prepareResponse(cmd, rsp);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " Map invoke() throws Exception{\r\n return this.invokeAsync().get();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void enableMultipartFilter(HttpCommonEndpoint endpoint, Server server) throws Exception{\r\n ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class);\r\n CamelContext camelContext = this.getCamelContext();\r\n FilterHolder filterHolder = new FilterHolder();\r\n filterHolder.setInitParameter(\"deleteFiles\", \"true\");\r\n if (ObjectHelper.isNotEmpty(camelContext.getGlobalOption(TMP_DIR))) {\r\n File file = new File(camelContext.getGlobalOption(TMP_DIR));\r\n if (!file.isDirectory()) {\r\n throw new RuntimeCamelException(\"The temp file directory of camel-jetty is not exists, please recheck it with directory name :\" + camelContext.getGlobalOptions().get(TMP_DIR));\r\n }\r\n context.setAttribute(\"jakarta.servlet.context.tempdir\", file);\r\n }\r\n Filter filter = ((JettyHttpEndpoint) endpoint).getMultipartFilter();\r\n if (filter == null) {\r\n filter = new MultiPartFilter();\r\n }\r\n filterHolder.setFilter(new CamelFilterWrapper(filter));\r\n String pathSpec = endpoint.getPath();\r\n if (pathSpec == null || pathSpec.isEmpty()) {\r\n pathSpec = \"/\";\r\n }\r\n if (endpoint.isMatchOnUriPrefix()) {\r\n pathSpec = pathSpec.endsWith(\"/\") ? pathSpec + \"*\" : pathSpec + \"/*\";\r\n }\r\n addFilter(context, filterHolder, pathSpec);\r\n LOG.debug(\"using multipart filter implementation {} for path {}\", filter.getClass().getName(), pathSpec);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doInitXQuery() throws Exception{\r\n LOG.debug(\"{} using schema resource: {}\", this, resourceUri);\r\n InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), resourceUri);\r\n this.xquery = XQueryBuilder.xquery(is);\r\n this.xquery.setConfiguration(getConfiguration());\r\n this.xquery.setConfigurationProperties(getConfigurationProperties());\r\n this.xquery.setStaticQueryContext(getStaticQueryContext());\r\n this.xquery.setParameters(getParameters());\r\n this.xquery.setNamespaces(namespacePrefixes);\r\n this.xquery.setResultsFormat(getResultsFormat());\r\n this.xquery.setProperties(getProperties());\r\n this.xquery.setResultType(getResultType());\r\n this.xquery.setStripsAllWhiteSpace(isStripsAllWhiteSpace());\r\n this.xquery.setAllowStAX(isAllowStAX());\r\n this.xquery.setHeaderName(getHeaderName());\r\n this.xquery.setPropertyName(getPropertyName());\r\n this.xquery.setModuleURIResolver(getModuleURIResolver());\r\n this.xquery.init(getCamelContext());\r\n setProcessor(xquery);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void closeParser() throws Exception{\r\n raf.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean unloadDataset(String table, CliDriver cliDriver) throws Exception{\r\n try {\r\n CommandProcessorResponse result = cliDriver.processLine(\"drop table \" + table);\r\n LOG.info(\"Result from cliDrriver.processLine in initFromDatasets=\" + result);\r\n } catch (CommandProcessorException e) {\r\n Assert.fail(\"Failed during initFromDatasets processLine with code=\" + e);\r\n }\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\npublic Cache getCache(String name, Class keyType, Class valueType) throws Exception {\n CacheConfiguration cacheConfiguration = null;\n if (configuration != null) {\n if (configuration.hasConfiguration(name)) {\n LOGGER.debug(\"Using custom cache configuration for cache {}\", name);\n cacheConfiguration = CacheConfiguration.class.cast(configuration.getConfigurations().get(name));\n } else if (configuration.hasConfiguration()) {\n LOGGER.debug(\"Using global cache configuration for cache {}\", name);\n cacheConfiguration = CacheConfiguration.class.cast(configuration.getConfiguration());\n }\n }\n if (keyType == null && valueType == null) {\n if (cacheConfiguration != null) {\n keyType = cacheConfiguration.getKeyType();\n valueType = cacheConfiguration.getValueType();\n } else {\n keyType = (Class) Object.class;\n valueType = (Class) Object.class;\n }\n }\n Cache cache = cacheManager.getCache(name, keyType, valueType);\n if (cache == null && configuration != null && configuration.isCreateCacheIfNotExist()) {\n if (cacheConfiguration != null) {\n if (keyType != cacheConfiguration.getKeyType() || valueType != cacheConfiguration.getValueType()) {\n LOGGER.info(\"Mismatch keyType / valueType configuration for cache {}\", name);\n CacheConfigurationBuilder builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(keyType, valueType, cacheConfiguration.getResourcePools()).withClassLoader(cacheConfiguration.getClassLoader()).withEvictionAdvisor(cacheConfiguration.getEvictionAdvisor()).withExpiry(cacheConfiguration.getExpiryPolicy());\n for (ServiceConfiguration serviceConfig : cacheConfiguration.getServiceConfigurations()) {\n builder = builder.withService(serviceConfig);\n }\n cacheConfiguration = builder.build();\n }\n cache = cacheManager.createCache(name, cacheConfiguration);\n } else {\n // If a cache configuration is not provided, create a User Managed\n // Cache\n LOGGER.debug(\"Using a UserManagedCache for cache {} as no configuration has been found\", name);\n Class kt = keyType;\n Class vt = valueType;\n cache = Cache.class.cast(userCaches.computeIfAbsent(name, key -> UserManagedCacheBuilder.newUserManagedCacheBuilder(kt, vt).build(true)));\n }\n }\n if (cache == null) {\n throw new RuntimeCamelException(\"Unable to retrieve the cache \" + name + \" from cache manager \" + cacheManager);\n }\n return cache;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private void writeToFile(File template, Document document) throws Exception{\r\n Transformer transformer = TransformerFactory.newInstance().newTransformer();\r\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\r\n transformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\r\n DOMSource source = new DOMSource(document);\r\n StreamResult result = new StreamResult(template);\r\n transformer.transform(source, result);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setBucketPolicy(String bucketName) throws Exception{\r\n LOG.trace(\"Updating bucket {} with policy...\", bucketName);\r\n minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(getConfiguration().getPolicy()).build());\r\n LOG.trace(\"Bucket policy updated\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Class getAnalyzerClass(ASTNode root, QueryState queryState) {\n if (TYPE_TO_ANALYZER.containsKey(root.getType())) {\n return TYPE_TO_ANALYZER.get(root.getType());\n }\n if (TYPE_TO_ANALYZERCATEGORY.containsKey(root.getType())) {\n Class analyzerCategoryClass = TYPE_TO_ANALYZERCATEGORY.get(root.getType());\n try {\n DDLSemanticAnalyzerCategory analyzerCategory = analyzerCategoryClass.newInstance();\n int actualType = analyzerCategory.getType(root);\n if (TYPE_TO_ANALYZER.containsKey(actualType)) {\n if (queryState != null) {\n queryState.setCommandType(HiveOperation.operationForToken(actualType));\n }\n return TYPE_TO_ANALYZER.get(actualType);\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n return null;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public boolean canConnect(HttpConsumer consumer) throws Exception{\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void serialize(WriteBuffer writeBuffer) throws SerializationException {\n writeBuffer.pushContext(\"PlcReadResponse\");\n writeBuffer.pushContext(\"request\");\n if (request instanceof Serializable) {\n ((Serializable) request).serialize(writeBuffer);\n }\n writeBuffer.popContext(\"request\");\n writeBuffer.pushContext(\"values\", WithRenderAsList(true));\n for (Map.Entry> valueEntry : values.entrySet()) {\n String tagName = valueEntry.getKey();\n writeBuffer.pushContext(tagName);\n PlcResponseItem valueResponse = valueEntry.getValue();\n if (!(valueResponse instanceof Serializable)) {\n throw new RuntimeException(\"Error serializing. PlcResponseItem doesn't implement Serializable\");\n }\n ((Serializable) valueResponse).serialize(writeBuffer);\n writeBuffer.popContext(tagName);\n }\n writeBuffer.popContext(\"values\");\n if (metadata != null && !metadata.isEmpty()) {\n writeBuffer.pushContext(\"metadata\", WithRenderAsList(true));\n for (Entry entry : metadata.entrySet()) {\n if (entry.getValue() instanceof Serializable) {\n writeBuffer.pushContext(entry.getKey());\n ((Serializable) entry.getValue()).serialize(writeBuffer);\n writeBuffer.popContext(entry.getKey());\n }\n }\n writeBuffer.popContext(\"metadata\");\n }\n writeBuffer.popContext(\"PlcReadResponse\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "/**\n * @param schemaVersionNumber the version number of the {@link ISchemaVersion}\n * desired. This must be a registered schema version number.\n * @return The {@link ISchemaVersion} for the given number. This will never\n * be null.\n */\npublic static ISchemaVersion getSchemaVersion(final int schemaVersionNumber) {\n if (schemaVersionNumber >= REGISTERED_SCHEMA_VERSIONS.length || schemaVersionNumber < 0)\n throw new RuntimeException(\"Invalid schema version number \" + schemaVersionNumber);\n final ISchemaVersion schemaVer = REGISTERED_SCHEMA_VERSIONS[schemaVersionNumber];\n if (schemaVer == null)\n throw new RuntimeException(\"Unknown schema version number \" + schemaVersionNumber);\n return schemaVer;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": " void validate(Cache cache, Exchange exchange) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void stop() throws Exception{\r\n if (log.isInfoEnabled()) {\r\n log.info(\"Stopping MongoDB Tailable Cursor consumer, bound to collection: {}\", String.format(\"db: %s, col: %s\", endpoint.getDatabase(), endpoint.getCollection()));\r\n }\r\n keepRunning = false;\r\n if (cursor != null) {\r\n cursor.close();\r\n }\r\n awaitStopped();\r\n if (log.isInfoEnabled()) {\r\n log.info(\"Stopped MongoDB Tailable Cursor consumer, bound to collection: {}\", String.format(\"db: %s, col: %s\", endpoint.getDatabase(), endpoint.getCollection()));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BeanProcessor createBeanProcessor(SqlSession session) throws Exception{\r\n Class clazz = session.getConfiguration().getTypeAliasRegistry().resolveAlias(endpoint.getBeanName());\r\n if (clazz == null) {\r\n clazz = getEndpoint().getCamelContext().getClassResolver().resolveMandatoryClass(endpoint.getBeanName());\r\n }\r\n LOG.debug(\"Resolved MyBatis Bean: {} as class: {}\", endpoint.getBeanName(), clazz);\r\n Object mapper = session.getMapper(clazz);\r\n if (mapper == null) {\r\n throw new IllegalArgumentException(\"No Mapper with typeAlias or class name: \" + endpoint.getBeanName() + \" in MyBatis configuration.\");\r\n }\r\n LOG.debug(\"Resolved MyBatis Bean mapper: {}\", mapper);\r\n BeanProcessor answer = new BeanProcessor(mapper, getEndpoint().getCamelContext());\r\n answer.setMethod(endpoint.getMethodName());\r\n return answer;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void bindToRegistryAfterInjections(Registry registry) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String convertTo(String url, String targetFileExtension) throws Exception {\n if (!this.supportsInputFormat(url)) {\n throw new Exception(\"Format nicht unterst\u00fctzt: \" + new File(url).getName());\n }\n if (targetFileExtension == null) {\n throw new Exception(\"Es muss ein Zielformat angegeben werden\");\n }\n targetFileExtension = targetFileExtension.toLowerCase();\n targetFileExtension = targetFileExtension.replaceAll(\"\\\\.\", \"\");\n if (!OUTPUTTYPES.contains(targetFileExtension)) {\n throw new Exception(\"Konvertierung nach \" + targetFileExtension + \" ist nicht verf\u00fcgbar!\");\n }\n String clientLocation = System.getenv(\"JLAWYERCLIENTHOME\");\n if (clientLocation == null) {\n log.error(\"JLAWYERCLIENTHOME environment variable not set - document conversion not possible\");\n throw new Exception(\"Umgebungsvariable JLAWYERCLIENTHOME nicht gesetzt - Dokumentkonvertierung nicht m\u00f6glich.\");\n }\n if (!clientLocation.endsWith(File.separator)) {\n clientLocation = clientLocation + File.separator;\n }\n Process p = Runtime.getRuntime().exec(new String[] { \"python.exe\", clientLocation + \"unoconv-master\\\\unoconv\", \"-f\", targetFileExtension, url });\n int exit = p.waitFor();\n if (exit != 0) {\n log.error(\"Conversion failed with exit code \" + exit + \", command line was 'python.exe \" + clientLocation + \"unoconv-master\\\\unoconv -f \" + targetFileExtension + \" \" + url);\n throw new Exception(\"Konvertierung fehlgeschlagen: \" + exit);\n }\n File org = new File(url);\n String orgName = org.getName();\n String path = url.substring(0, url.indexOf(orgName));\n String newPath = path + orgName.substring(0, orgName.lastIndexOf('.')) + \".\" + targetFileExtension;\n if (!(new File(newPath).exists())) {\n throw new Exception(\"Konvertierung kann nur durchgef\u00fchrt werden wenn kein soffice.exe/soffice.bin l\u00e4uft!\");\n }\n return newPath;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * A helpful method that checks that some class is available on the class-path. If it fails to load, it will throw an\n * exception based on why it failed to load. This should be used in cases where certain dependencies are optional, but the\n * dependency is used at compile-time for strong typing\n */\npublic static void requireClass(String classPath, String module, String feature) {\n try {\n ClassLoaderHelper.loadClass(classPath, false);\n } catch (ClassNotFoundException e) {\n LOG.debug(() -> \"Cannot find the \" + classPath + \" class: \", e);\n String msg = String.format(\"Could not load class. You must add a dependency on the '%s' module to enable the %s \" + \"feature: \", module, feature);\n throw new RuntimeException(msg, e);\n } catch (Exception e) {\n throw new RuntimeException(String.format(\"Could not load class (%s): \", classPath), e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "aws_aws-sdk-java-v2", "language": "java"} {"function": "public void processSingleOp(final Exchange exchange) throws Exception{\r\n PutObjectRequest.Builder putObjectRequest = PutObjectRequest.builder();\r\n Map objectMetadata = determineMetadata(exchange);\r\n long contentLength = exchange.getIn().getHeader(AWS2S3Constants.CONTENT_LENGTH, -1, Long.class);\r\n Object obj = exchange.getIn().getMandatoryBody();\r\n InputStream inputStream = null;\r\n File filePayload = null;\r\n try {\r\n if (obj instanceof WrappedFile) {\r\n obj = ((WrappedFile) obj).getFile();\r\n }\r\n if (obj instanceof File) {\r\n filePayload = (File) obj;\r\n contentLength = filePayload.length();\r\n } else {\r\n inputStream = exchange.getIn().getMandatoryBody(InputStream.class);\r\n if (contentLength <= 0) {\r\n contentLength = AWS2S3Utils.determineLengthInputStream(inputStream);\r\n if (contentLength == -1) {\r\n LOG.debug(\"The content length is not defined. It needs to be determined by reading the data into memory\");\r\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n IOHelper.copyAndCloseInput(inputStream, baos);\r\n byte[] arr = baos.toByteArray();\r\n contentLength = arr.length;\r\n inputStream = new ByteArrayInputStream(arr);\r\n }\r\n }\r\n }\r\n doPutObject(exchange, putObjectRequest, objectMetadata, filePayload, inputStream, contentLength);\r\n } finally {\r\n IOHelper.close(inputStream);\r\n }\r\n if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {\r\n FileUtil.deleteFile(filePayload);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected HttpClientConfigurer createHttpClientConfigurer(Map parameters, boolean secure) throws Exception{\r\n HttpClientConfigurer configurer = resolveAndRemoveReferenceParameter(parameters, \"httpClientConfigurer\", HttpClientConfigurer.class);\r\n if (configurer == null) {\r\n configurer = getHttpClientConfigurer();\r\n }\r\n HttpCredentialsHelper credentialsProvider = new HttpCredentialsHelper();\r\n configurer = configureBasicAuthentication(parameters, configurer, credentialsProvider);\r\n configurer = configureHttpProxy(parameters, configurer, secure, credentialsProvider);\r\n return configurer;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ProcessElement\npublic void processElement(ProcessContext processContext) {\n try {\n PubsubMessage message = processContext.element();\n inputCounter.inc();\n Object[] outputRow = new Object[rowMeta.size()];\n // Serializable\n outputRow[0] = message;\n processContext.output(new HopRow(outputRow));\n writtenCounter.inc();\n } catch (Exception e) {\n numErrors.inc();\n LOG.error(\"Error in pub/sub publish messages function\", e);\n throw new RuntimeException(\"Error in pub/sub publish messages function\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private void uploadOnceFromMemory(List latencies) throws Exception{\r\n SimplePublisher publisher = new SimplePublisher<>();\r\n long partSizeInBytes = config.partSizeInMb() * MB;\r\n byte[] bytes = new byte[(int) partSizeInBytes];\r\n UploadRequest uploadRequest = UploadRequest.builder().putObjectRequest(r -> r.bucket(bucket).key(key).contentLength(config.contentLengthInMb() * MB).checksumAlgorithm(config.checksumAlgorithm())).requestBody(AsyncRequestBody.fromPublisher(publisher)).build();\r\n Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> {\r\n long remaining = config.contentLengthInMb() * MB;\r\n while (remaining > 0) {\r\n publisher.send(ByteBuffer.wrap(bytes));\r\n remaining -= partSizeInBytes;\r\n }\r\n publisher.complete();\r\n });\r\n Upload upload = transferManager.upload(uploadRequest);\r\n uploadThread.start();\r\n long start = System.currentTimeMillis();\r\n upload.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS);\r\n long end = System.currentTimeMillis();\r\n latencies.add((end - start) / 1000.0);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AS400 connect() throws Exception{\r\n AS400 iSeries = getISeriesEndpoint().getSystem();\r\n if (!iSeries.isConnected(AS400.COMMAND)) {\r\n LOG.debug(\"Connecting to {}\", getISeriesEndpoint());\r\n iSeries.connectService(AS400.COMMAND);\r\n }\r\n return iSeries;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ServiceClient createServiceClient(Configuration conf) throws Exception{\r\n ServiceClient serviceClient = new ServiceClient();\r\n serviceClient.init(conf);\r\n serviceClient.start();\r\n return serviceClient;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void onCreate(TriggerAttributes attributes) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String deCompress(String messageBody) {\n byte[] decodedBytes = Base64.getDecoder().decode(messageBody.getBytes(StandardCharsets.UTF_8));\n try (ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);\n GZIPInputStream is = new GZIPInputStream(in)) {\n byte[] bytes = IOUtils.toByteArray(is);\n return new String(bytes, StandardCharsets.UTF_8);\n } catch (IOException e) {\n LOG.error(\"cannot decode the stream\", e);\n LOG.debug(\"base64 encoded String\", messageBody);\n throw new RuntimeException(\"cannot decode the stream \", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private boolean doCreateAndExecuteSqlStatement(Exchange exchange, String sql, Connection conn) throws Exception{\r\n Statement stmt = null;\r\n ResultSet rs = null;\r\n boolean shouldCloseResources = true;\r\n try {\r\n stmt = conn.createStatement();\r\n bindParameters(exchange, stmt);\r\n LOG.debug(\"Executing JDBC Statement: {}\", sql);\r\n boolean shouldRetrieveGeneratedKeys = exchange.getIn().getHeader(JdbcConstants.JDBC_RETRIEVE_GENERATED_KEYS, false, Boolean.class);\r\n boolean stmtExecutionResult;\r\n if (shouldRetrieveGeneratedKeys) {\r\n Object expectedGeneratedColumns = exchange.getIn().getHeader(JdbcConstants.JDBC_GENERATED_COLUMNS);\r\n if (expectedGeneratedColumns == null) {\r\n stmtExecutionResult = stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);\r\n } else if (expectedGeneratedColumns instanceof String[]) {\r\n stmtExecutionResult = stmt.execute(sql, (String[]) expectedGeneratedColumns);\r\n } else if (expectedGeneratedColumns instanceof int[]) {\r\n stmtExecutionResult = stmt.execute(sql, (int[]) expectedGeneratedColumns);\r\n } else {\r\n throw new IllegalArgumentException(\"Header specifying expected returning columns isn't an instance of String[] or int[] but \" + expectedGeneratedColumns.getClass());\r\n }\r\n } else {\r\n stmtExecutionResult = stmt.execute(sql);\r\n }\r\n if (stmtExecutionResult) {\r\n rs = stmt.getResultSet();\r\n shouldCloseResources = setResultSet(exchange, conn, rs);\r\n } else {\r\n int updateCount = stmt.getUpdateCount();\r\n exchange.getMessage().setHeader(JdbcConstants.JDBC_UPDATE_COUNT, updateCount);\r\n }\r\n if (shouldRetrieveGeneratedKeys) {\r\n setGeneratedKeys(exchange, conn, stmt.getGeneratedKeys());\r\n }\r\n } finally {\r\n if (shouldCloseResources) {\r\n closeQuietly(rs);\r\n closeQuietly(stmt);\r\n } else {\r\n final Statement finalStmt = stmt;\r\n final ResultSet finalRs = rs;\r\n exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() {\r\n\r\n @Override\r\n public void onDone(Exchange exchange) {\r\n closeQuietly(finalRs);\r\n closeQuietly(finalStmt);\r\n }\r\n\r\n @Override\r\n public int getOrder() {\r\n return LOWEST + 100;\r\n }\r\n });\r\n }\r\n }\r\n return shouldCloseResources;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleGetClusterState(HttpPostCommand cmd) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n ClusterService clusterService = getNode().getClusterService();\r\n ClusterState clusterState = clusterService.getClusterState();\r\n prepareResponse(cmd, response(SUCCESS, \"state\", lowerCaseInternal(clusterState.toString())));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "// ========================================================================\n// Cardinality\n/**\n * Computes the cardinality of the HLL.\n *\n * @return the cardinality of HLL. This will never be negative.\n */\npublic long cardinality() {\n switch(type) {\n case EMPTY:\n return 0;\n case EXPLICIT:\n return explicitStorage.size();\n case SPARSE:\n return (long) Math.ceil(sparseProbabilisticAlgorithmCardinality());\n case FULL:\n return (long) Math.ceil(fullProbabilisticAlgorithmCardinality());\n default:\n throw new RuntimeException(\"Unsupported HLL type \" + type);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private ObjectMapper resolveObjectMapper(CamelContext camelContext) throws Exception{\r\n Set mappers = camelContext.getRegistry().findByType(ObjectMapper.class);\r\n if (mappers.size() == 1) {\r\n return mappers.iterator().next();\r\n }\r\n if (defaultMapper == null) {\r\n synchronized (lock) {\r\n if (defaultMapper == null) {\r\n ObjectMapper mapper = new ObjectMapper();\r\n if (moduleClassNames != null) {\r\n for (Object o : ObjectHelper.createIterable(moduleClassNames)) {\r\n Class type = camelContext.getClassResolver().resolveMandatoryClass(o.toString(), Module.class);\r\n Module module = camelContext.getInjector().newInstance(type);\r\n LOG.debug(\"Registering module: {} -> {}\", o, module);\r\n mapper.registerModule(module);\r\n }\r\n }\r\n defaultMapper = mapper;\r\n }\r\n }\r\n }\r\n return defaultMapper;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Object evaluate(DeferredObject[] arguments) throws HiveException {\n if (arguments[0] == null) {\n return null;\n }\n Object input = arguments[0].get();\n if (input == null) {\n return null;\n }\n input = converter.convert(input);\n if (input == null) {\n return null;\n }\n switch(resultOI.getPrimitiveCategory()) {\n case BYTE:\n byteWritable.set((byte) -(((ByteWritable) input).get()));\n return byteWritable;\n case SHORT:\n shortWritable.set((short) -(((ShortWritable) input).get()));\n return shortWritable;\n case INT:\n intWritable.set(-(((IntWritable) input).get()));\n return intWritable;\n case LONG:\n longWritable.set(-(((LongWritable) input).get()));\n return longWritable;\n case FLOAT:\n floatWritable.set(-(((FloatWritable) input).get()));\n return floatWritable;\n case DOUBLE:\n doubleWritable.set(-(((DoubleWritable) input).get()));\n return doubleWritable;\n case DECIMAL:\n decimalWritable.set((HiveDecimalWritable) input);\n decimalWritable.mutateNegate();\n return decimalWritable;\n case INTERVAL_YEAR_MONTH:\n HiveIntervalYearMonth intervalYearMonth = ((HiveIntervalYearMonthWritable) input).getHiveIntervalYearMonth();\n this.intervalYearMonthWritable.set(intervalYearMonth.negate());\n return this.intervalYearMonthWritable;\n case INTERVAL_DAY_TIME:\n HiveIntervalDayTime intervalDayTime = ((HiveIntervalDayTimeWritable) input).getHiveIntervalDayTime();\n this.intervalDayTimeWritable.set(intervalDayTime.negate());\n return intervalDayTimeWritable;\n default:\n // Should never happen.\n throw new RuntimeException(\"Unexpected type in evaluating \" + opName + \": \" + resultOI.getPrimitiveCategory());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private FileMetadata putSingleFile(File inputFile, String dropboxPath, DropboxUploadMode mode) throws Exception{\r\n try (FileInputStream inputStream = new FileInputStream(inputFile)) {\r\n WriteMode uploadMode;\r\n if (mode == DropboxUploadMode.force) {\r\n uploadMode = WriteMode.OVERWRITE;\r\n } else {\r\n uploadMode = WriteMode.ADD;\r\n }\r\n return client.files().uploadBuilder(dropboxPath).withMode(uploadMode).uploadAndFinish(inputStream, inputFile.length());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void process(DataQueue queue, Exchange exchange) throws Exception{\r\n if (endpoint.getFormat() == Jt400Configuration.Format.binary) {\r\n queue.write(exchange.getIn().getBody(byte[].class));\r\n } else {\r\n queue.write(exchange.getIn().getBody(String.class));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AvroSchema computeIfAbsent(Exchange exchange) {\n if (this.schema != null) {\n return this.schema;\n }\n AvroSchema answer = exchange.getProperty(SchemaHelper.CONTENT_SCHEMA, AvroSchema.class);\n if (answer == null && exchange.getProperties().containsKey(SchemaHelper.SCHEMA)) {\n String schemaJson = exchange.getProperty(SchemaHelper.SCHEMA, String.class);\n Schema raw = new Schema.Parser().setValidate(validate).parse(schemaJson);\n answer = new AvroSchema(raw);\n }\n if (answer == null) {\n String contentClass = SchemaHelper.resolveContentClass(exchange, this.contentClass);\n if (contentClass != null) {\n answer = this.schemes.computeIfAbsent(contentClass, t -> {\n Resource res = PluginHelper.getResourceLoader(exchange.getContext()).resolveResource(\"classpath:schemas/\" + SchemaType.AVRO.name().toLowerCase(Locale.US) + \"/\" + t + \".\" + SchemaType.AVRO.type());\n try {\n if (res.exists()) {\n try (InputStream is = res.getInputStream()) {\n if (is != null) {\n return Avro.mapper().schemaFrom(is);\n }\n }\n }\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to load Avro schema for type: \" + t + \", resource: \" + res.getLocation(), e);\n }\n try {\n return Avro.mapper().schemaFor(Class.forName(contentClass));\n } catch (JsonMappingException | ClassNotFoundException e) {\n throw new RuntimeException(\"Unable to compute Avro schema for type: \" + t, e);\n }\n });\n }\n }\n if (answer != null) {\n this.schema = answer;\n }\n return answer;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private void deleteBucket(MinioClient minioClient, Exchange exchange) throws Exception{\r\n final String bucketName = determineBucketName(exchange);\r\n if (getConfiguration().isPojoRequest()) {\r\n RemoveBucketArgs.Builder payload = exchange.getIn().getMandatoryBody(RemoveBucketArgs.Builder.class);\r\n if (isNotEmpty(payload)) {\r\n minioClient.removeBucket(payload.build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(\"ok\");\r\n }\r\n } else {\r\n minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(\"ok\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object getKey(final Message message) throws Exception{\r\n String value = message.getHeader(CaffeineConstants.KEY, String.class);\r\n if (value == null) {\r\n value = configuration.getKey();\r\n }\r\n if (value == null) {\r\n throw new CamelExchangeException(\"No value provided in header or as default value (\" + CaffeineConstants.KEY + \")\", message.getExchange());\r\n }\r\n return value;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Object getRequestBody(Exchange exchange) throws Exception{\r\n Object body = NettyPayloadHelper.getIn(getEndpoint(), exchange);\r\n if (body == null) {\r\n return null;\r\n }\r\n if (getConfiguration().isTextline()) {\r\n body = NettyHelper.getTextlineBody(body, exchange, getConfiguration().getDelimiter(), getConfiguration().isAutoAppendDelimiter());\r\n }\r\n return body;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@SuppressWarnings(\"unchecked\")\n@Override\npublic boolean test(Map ctx) throws Exception {\n Set accountIds = new TreeSet<>();\n int accNum = args.batch();\n while (accountIds.size() < accNum) accountIds.add(nextRandom(args.range()));\n try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {\n Map accounts = (Map) cache.getAll(accountIds);\n if (accounts.size() != accNum)\n throw new Exception(\"Failed to find accounts: \" + accountIds);\n Integer fromId = accountIds.iterator().next();\n int fromBalance = accounts.get(fromId).balance();\n for (Integer id : accountIds) {\n if (id.equals(fromId))\n continue;\n Account account = accounts.get(id);\n if (fromBalance > 0) {\n fromBalance--;\n cache.put(id, new Account(account.balance() + 1));\n }\n }\n cache.put(fromId, new Account(fromBalance));\n tx.commit();\n }\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "/**\n * Return true if we have the result of this timeRange.\n */\n@Override\nprotected boolean calculateAggregationResultForCurrentTimeRange() {\n try {\n if (calcFromCachedData()) {\n updateResultTsBlock();\n checkIfAllAggregatorHasFinalResult();\n return true;\n }\n if (readAndCalcFromPage()) {\n updateResultTsBlock();\n checkIfAllAggregatorHasFinalResult();\n return true;\n }\n // only when all the page data has been consumed, we need to read the chunk data\n if (!seriesScanUtil.hasNextPage() && readAndCalcFromChunk()) {\n updateResultTsBlock();\n checkIfAllAggregatorHasFinalResult();\n return true;\n }\n // only when all the page and chunk data has been consumed, we need to read the file data\n if (!seriesScanUtil.hasNextPage() && !seriesScanUtil.hasNextChunk() && readAndCalcFromFile()) {\n updateResultTsBlock();\n checkIfAllAggregatorHasFinalResult();\n return true;\n }\n // If the TimeRange is (Long.MIN_VALUE, Long.MAX_VALUE), for Aggregators like countAggregator,\n // we have to consume all the data before we finish the aggregation calculation.\n if (seriesScanUtil.hasNextPage() || seriesScanUtil.hasNextChunk() || seriesScanUtil.hasNextFile()) {\n return false;\n } else {\n // all data of current device has been consumed\n updateResultTsBlock();\n timeIterator.resetCurTimeRange();\n nextDevice();\n }\n if (currentDeviceIndex < deviceCount) {\n // construct AlignedSeriesScanUtil for next device\n constructAlignedSeriesScanUtil();\n queryDataSource.reset();\n this.seriesScanUtil.initQueryDataSource(queryDataSource);\n }\n if (currentDeviceIndex >= deviceCount) {\n // all devices have been consumed\n timeIterator.setFinished();\n return true;\n } else {\n return false;\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error while scanning the file\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "@Override\npublic void check() {\n if (timeInterval <= 0) {\n throw new RuntimeException(String.format(\"Parameter timeInterval(%d) should be positive.\", timeInterval));\n }\n if (slidingStep <= 0) {\n throw new RuntimeException(String.format(\"Parameter slidingStep(%d) should be positive.\", slidingStep));\n }\n if (displayWindowEnd < displayWindowBegin) {\n throw new RuntimeException(String.format(\"displayWindowEnd(%d) < displayWindowBegin(%d)\", displayWindowEnd, displayWindowBegin));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public static T invokeMethod(Object object, String methodName) throws RuntimeException{\r\n try {\r\n Method method = object.getClass().getMethod(methodName);\r\n method.setAccessible(true);\r\n return (T) method.invoke(object);\r\n } catch (Exception e) {\r\n throw ExceptionUtil.rethrow(e);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void validateMepAndReplyTo(Map parameters) throws Exception{\r\n boolean replyToSet = parameters.containsKey(\"replyTo\");\r\n boolean mepSet = parameters.containsKey(\"exchangePattern\");\r\n if (replyToSet && mepSet) {\r\n if (!parameters.get(\"exchangePattern\").equals(ExchangePattern.InOut.toString())) {\r\n String replyTo = (String) parameters.get(\"replyTo\");\r\n ExchangePattern mep = ExchangePattern.valueOf((String) parameters.get(\"exchangePattern\"));\r\n throw new CamelException(\"Setting parameter replyTo=\" + replyTo + \" requires a MEP of type InOut. Parameter exchangePattern is set to \" + mep);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected JAXBContext createContext() throws Exception{\r\n if (contextPath != null) {\r\n ClassLoader cl = camelContext.getApplicationContextClassLoader();\r\n if (cl != null) {\r\n if (contextPathIsClassName) {\r\n LOG.debug(\"Creating JAXBContext with className: {} and ApplicationContextClassLoader: {}\", contextPath, cl);\r\n Class clazz = camelContext.getClassResolver().resolveMandatoryClass(contextPath, cl);\r\n return JAXBContext.newInstance(clazz);\r\n } else {\r\n LOG.debug(\"Creating JAXBContext with contextPath: {} and ApplicationContextClassLoader: {}\", contextPath, cl);\r\n return JAXBContext.newInstance(contextPath, cl);\r\n }\r\n } else {\r\n if (contextPathIsClassName) {\r\n LOG.debug(\"Creating JAXBContext with className: {}\", contextPath);\r\n Class clazz = camelContext.getClassResolver().resolveMandatoryClass(contextPath);\r\n return JAXBContext.newInstance(clazz);\r\n } else {\r\n LOG.debug(\"Creating JAXBContext with contextPath: {}\", contextPath);\r\n return JAXBContext.newInstance(contextPath);\r\n }\r\n }\r\n } else {\r\n LOG.debug(\"Creating JAXBContext\");\r\n return JAXBContext.newInstance();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void downloadOnceToFile(List latencies) throws Exception{\r\n Path downloadPath = new File(this.path).toPath();\r\n long start = System.currentTimeMillis();\r\n FileDownload download = transferManager.downloadFile(b -> b.getObjectRequest(r -> r.bucket(bucket).key(key)).destination(downloadPath));\r\n download.completionFuture().get(10, TimeUnit.MINUTES);\r\n long end = System.currentTimeMillis();\r\n latencies.add((end - start) / 1000.0);\r\n runAndLogError(logger.logger(), \"Deleting file failed\", () -> Files.delete(downloadPath));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ArrayList getAllowedCasesForUser(String principalId, SecurityServiceLocal securityFacade) throws Exception {\n JDBCUtils utils = new JDBCUtils();\n ArrayList list = new ArrayList<>();\n List userGroups = new ArrayList<>();\n try {\n userGroups = securityFacade.getGroupsForUser(principalId);\n } catch (Throwable t) {\n log.error(\"Unable to determine groups for user \" + principalId, t);\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"'dummy'\");\n for (Group g : userGroups) {\n sb.append(\", '\").append(g.getId()).append(\"'\");\n }\n String inClause = sb.toString();\n //select distinct (t1.id) from (\n // -- cases where the user is owner\n //select id from cases where owner_group in ('6a7776fc7f00010136d79a4449cbc199','6a778e437f000101216f38d814330959', '9d3ac0e07f00010160456b7ffc12fbf8', '9d3aa8a17f00010129a7683d54ee39de', 'b869f3e87f00010110962348ac1e4cb9', 'b86a19417f00010125870b81e0fdf216')\n //union\n // -- cases that are unprotected\n //select id from cases where owner_group is null\n //union\n // -- cases where the user is in an allowed group\n //select distinct case_id id from case_groups where group_id in ('6a7776fc7f00010136d79a4449cbc199','6a778e437f000101216f38d814330959', '9d3ac0e07f00010160456b7ffc12fbf8', '9d3aa8a17f00010129a7683d54ee39de', 'b869f3e87f00010110962348ac1e4cb9', 'b86a19417f00010125870b81e0fdf216')\n //union\n // -- cases where there is restriction (althoug there is an owner)\n //select id from cases where id not in (select case_id from case_groups)\n //) t1\n String sql = \"select distinct (t1.id) from (\\n\" + \"select id from cases where owner_group in (\" + inClause + \")\\n\" + \"union \\n\" + \"select id from cases where owner_group is null \\n\" + \"union \\n\" + \"select distinct case_id id from case_groups where group_id in (\" + inClause + \")\\n\" + \"union \\n\" + \"select id from cases where id not in (select case_id from case_groups)\\n\" + \") t1\";\n try (Connection con = utils.getConnection();\n PreparedStatement st = con.prepareStatement(sql);\n ResultSet rs = st.executeQuery()) {\n while (rs.next()) {\n String id = rs.getString(1);\n list.add(id);\n }\n } catch (SQLException sqle) {\n log.error(\"Error finding cases accessible by the user\", sqle);\n throw new Exception(\"Could not determine cases accessible to the user\", sqle);\n }\n return list;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private List getLocalIps() throws Exception{\r\n List localIps = new ArrayList<>();\r\n Enumeration networkInterfacesEnumeration = NetworkInterface.getNetworkInterfaces();\r\n while (networkInterfacesEnumeration.hasMoreElements()) {\r\n NetworkInterface networkInterface = networkInterfacesEnumeration.nextElement();\r\n Enumeration inetAddressesEnumeration = networkInterface.getInetAddresses();\r\n while (inetAddressesEnumeration.hasMoreElements()) {\r\n InetAddress inetAddress = inetAddressesEnumeration.nextElement();\r\n String ip = inetAddress.getHostAddress();\r\n LOG.debug(\"Local ip: {}\", ip);\r\n localIps.add(ip);\r\n }\r\n }\r\n return localIps;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Boolean createReplicationTask() throws Exception{\r\n log.info(\"createReplicationTask ......\");\r\n CreateReplicationTaskRequest request = new CreateReplicationTaskRequest().withReplicationTaskIdentifier(replicationTaskIdentifier).withSourceEndpointArn(sourceEndpointArn).withTargetEndpointArn(targetEndpointArn).withReplicationInstanceArn(replicationInstanceArn).withMigrationType(migrationType).withTableMappings(tableMappings).withReplicationTaskSettings(replicationTaskSettings).withCdcStartTime(cdcStartTime).withCdcStartPosition(cdcStartPosition).withCdcStopPosition(cdcStopPosition).withTags(tags).withTaskData(taskData).withResourceIdentifier(resourceIdentifier);\r\n request.setTableMappings(replaceFileParameters(request.getTableMappings()));\r\n request.setReplicationTaskSettings(replaceFileParameters(request.getReplicationTaskSettings()));\r\n CreateReplicationTaskResult result = client.createReplicationTask(request);\r\n replicationTaskIdentifier = result.getReplicationTask().getReplicationTaskIdentifier();\r\n replicationTaskArn = result.getReplicationTask().getReplicationTaskArn();\r\n log.info(\"replicationTaskIdentifier: {}, replicationTaskArn: {}\", replicationTaskIdentifier, replicationTaskArn);\r\n return awaitReplicationTaskStatus(STATUS.READY);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `name` to the URL query string\n if (getName() != null) {\n try {\n joiner.add(String.format(\"%sname%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getName()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `values` to the URL query string\n if (getValues() != null) {\n for (int i = 0; i < getValues().size(); i++) {\n if (getValues().get(i) != null) {\n joiner.add(getValues().get(i).toUrlQueryString(String.format(\"%svalues%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `is_union` to the URL query string\n if (getIsUnion() != null) {\n try {\n joiner.add(String.format(\"%sis_union%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getIsUnion()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `underlying_type` to the URL query string\n if (getUnderlyingType() != null) {\n joiner.add(getUnderlyingType().toUrlQueryString(prefix + \"underlying_type\" + suffix));\n }\n // add `attributes` to the URL query string\n if (getAttributes() != null) {\n for (int i = 0; i < getAttributes().size(); i++) {\n if (getAttributes().get(i) != null) {\n joiner.add(getAttributes().get(i).toUrlQueryString(String.format(\"%sattributes%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `documentation` to the URL query string\n if (getDocumentation() != null) {\n for (int i = 0; i < getDocumentation().size(); i++) {\n try {\n joiner.add(String.format(\"%sdocumentation%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getDocumentation().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private double uploadFromMemory() throws Exception{\r\n if (contentLengthInMb == null) {\r\n throw new UnsupportedOperationException(\"Java upload benchmark - contentLengthInMb required for upload from memory\");\r\n }\r\n long partSizeInBytes = partSizeInMb * MB;\r\n SimplePublisher publisher = new SimplePublisher<>();\r\n byte[] bytes = new byte[(int) partSizeInBytes];\r\n Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> {\r\n long remaining = contentLengthInMb * MB;\r\n while (remaining > 0) {\r\n publisher.send(ByteBuffer.wrap(bytes));\r\n remaining -= partSizeInBytes;\r\n }\r\n publisher.complete();\r\n });\r\n CompletableFuture responseFuture = s3AsyncClient.putObject(r -> r.bucket(bucket).key(key).contentLength(contentLengthInMb * MB).checksumAlgorithm(checksumAlgorithm), AsyncRequestBody.fromPublisher(publisher));\r\n uploadThread.start();\r\n long start = System.currentTimeMillis();\r\n responseFuture.get(timeout.getSeconds(), TimeUnit.SECONDS);\r\n long end = System.currentTimeMillis();\r\n return (end - start) / 1000.0;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `name` to the URL query string\n if (getName() != null) {\n try {\n joiner.add(String.format(\"%sname%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getName()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `request` to the URL query string\n if (getRequest() != null) {\n joiner.add(getRequest().toUrlQueryString(prefix + \"request\" + suffix));\n }\n // add `response` to the URL query string\n if (getResponse() != null) {\n joiner.add(getResponse().toUrlQueryString(prefix + \"response\" + suffix));\n }\n // add `attributes` to the URL query string\n if (getAttributes() != null) {\n for (int i = 0; i < getAttributes().size(); i++) {\n if (getAttributes().get(i) != null) {\n joiner.add(getAttributes().get(i).toUrlQueryString(String.format(\"%sattributes%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `documentation` to the URL query string\n if (getDocumentation() != null) {\n for (int i = 0; i < getDocumentation().size(); i++) {\n try {\n joiner.add(String.format(\"%sdocumentation%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getDocumentation().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public Integer run(String[] args) throws Exception{\r\n if (!parseArguments(args)) {\r\n return -1;\r\n }\r\n init();\r\n try {\r\n parseAndEval(arguments);\r\n } finally {\r\n close();\r\n }\r\n return getProgramReturnCode();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void handleFailedWrite(Exchange exchange, Exception exception) throws Exception{\r\n throw exception;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void cleanUp() throws Exception{\r\n if (!isSessionStateStarted) {\r\n startSessionState(qTestResultProcessor.canReuseSession());\r\n }\r\n if (System.getenv(QTEST_LEAVE_FILES) != null) {\r\n return;\r\n }\r\n conf.setBoolean(\"hive.test.shutdown.phase\", true);\r\n clearKeysCreatedInTests();\r\n String metastoreDb = QTestSystemProperties.getMetaStoreDb();\r\n if (metastoreDb == null || \"derby\".equalsIgnoreCase(metastoreDb)) {\r\n cleanupFromFile();\r\n }\r\n Path p = new Path(testWarehouse);\r\n FileSystem fs = p.getFileSystem(conf);\r\n try {\r\n FileStatus[] ls = fs.listStatus(p);\r\n for (int i = 0; (ls != null) && (i < ls.length); i++) {\r\n fs.delete(ls[i].getPath(), true);\r\n }\r\n } catch (FileNotFoundException e) {\r\n }\r\n FunctionRegistry.unregisterTemporaryUDF(\"test_udaf\");\r\n FunctionRegistry.unregisterTemporaryUDF(\"test_error\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private SslHandler configureClientSSLOnDemand() throws Exception{\r\n if (!producer.getConfiguration().isSsl()) {\r\n return null;\r\n }\r\n if (producer.getConfiguration().getSslHandler() != null) {\r\n return producer.getConfiguration().getSslHandler();\r\n } else if (sslContext != null) {\r\n URI uri = new URI(producer.getEndpoint().getEndpointUri());\r\n SSLEngine engine = sslContext.createSSLEngine(uri.getHost(), uri.getPort());\r\n engine.setUseClientMode(true);\r\n SSLParameters sslParameters = engine.getSSLParameters();\r\n sslParameters.setServerNames(sniServerNames != null ? sniServerNames : Arrays.asList(new SNIHostName(uri.getHost())));\r\n engine.setSSLParameters(sslParameters);\r\n if (producer.getConfiguration().getSslContextParameters() == null) {\r\n engine.setEnabledProtocols(producer.getConfiguration().getEnabledProtocols().split(\",\"));\r\n }\r\n return new SslHandler(engine);\r\n }\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Channel openChannel(final ChannelFuture channelFuture) throws Exception{\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Waiting for operation to complete {} for {} millis\", channelFuture, configuration.getConnectTimeout());\r\n }\r\n channelFuture.awaitUninterruptibly();\r\n if (!channelFuture.isDone() || !channelFuture.isSuccess()) {\r\n if (configuration.isReconnect()) {\r\n scheduleReconnect(channelFuture);\r\n return null;\r\n } else {\r\n ConnectException cause = new ConnectException(\"Cannot connect to \" + configuration.getAddress());\r\n if (channelFuture.cause() != null) {\r\n cause.initCause(channelFuture.cause());\r\n }\r\n throw cause;\r\n }\r\n }\r\n Channel answer = channelFuture.channel();\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Creating connector to address: {}\", configuration.getAddress());\r\n }\r\n if (configuration.isReconnect()) {\r\n answer.closeFuture().addListener(new ChannelFutureListener() {\r\n\r\n @Override\r\n public void operationComplete(ChannelFuture future) throws Exception {\r\n scheduleReconnect(channelFuture);\r\n }\r\n });\r\n }\r\n return answer;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Invokes some method on {@code sun.misc.Unsafe} instance.\n *\n * @param mtd Method.\n * @param args Arguments.\n */\npublic static Object invoke(Method mtd, Object... args) {\n try {\n return mtd.invoke(UNSAFE, args);\n } catch (IllegalAccessException | InvocationTargetException e) {\n throw new RuntimeException(\"Unsafe invocation failed [cls=\" + UNSAFE.getClass() + \", mtd=\" + mtd + ']', e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private void initNewStore(NetworkParameters params) throws Exception{\r\n byte[] header;\r\n header = HEADER_MAGIC.getBytes(\"US-ASCII\");\r\n buffer.put(header);\r\n lock.lock();\r\n try {\r\n setRingCursor(buffer, FILE_PROLOGUE_BYTES);\r\n } finally {\r\n lock.unlock();\r\n }\r\n Block genesis = Genesis_legacy.getFor(params).cloneAsHeader();\r\n StoredBlock_legacy storedGenesis = new StoredBlock_legacy(genesis, genesis.getWork(), 0);\r\n put(storedGenesis);\r\n setChainHead(storedGenesis);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private HMACAccumulator getMessageAuthenticationCode(Key key) throws Exception{\r\n return shouldAppendHMAC ? new HMACAccumulator(key, macAlgorithm, cryptoProvider, bufferSize) : new HMACAccumulator() {\r\n\r\n byte[] empty = new byte[0];\r\n\r\n @Override\r\n public void encryptUpdate(byte[] buffer, int read) {\r\n }\r\n\r\n @Override\r\n public void decryptUpdate(byte[] buffer, int read) throws IOException {\r\n outputStream.write(buffer, 0, read);\r\n }\r\n\r\n @Override\r\n public void validate() {\r\n }\r\n\r\n @Override\r\n public byte[] getCalculatedMac() {\r\n return empty;\r\n }\r\n };\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean tables(String line) throws Exception{\r\n return metadata(\"getTables\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"table name\", \"%\"), null });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ChatScriptMessage createMessage(String message) throws Exception{\r\n ChatScriptMessage ret = null;\r\n try {\r\n ret = mapper.readValue(message, ChatScriptMessage.class);\r\n } catch (Exception e) {\r\n throw new Exception(\"Unable to parse the input message. Error Message\" + e.getMessage(), e);\r\n }\r\n return ret;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String dumpDRL(DrlPackage drl) throws Exception{\r\n Template temp = CONFIGURATION.getTemplate(\"drl.ftl\");\r\n Writer out = new StringWriter();\r\n temp.process(drl, out);\r\n String result = out.toString();\r\n out.close();\r\n return result;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void maskPatterns(String fname) throws Exception{\r\n String line;\r\n BufferedReader in;\r\n BufferedWriter out;\r\n File file = new File(fname);\r\n File fileOrig = new File(fname + \".orig\");\r\n FileUtils.copyFile(file, fileOrig);\r\n in = new BufferedReader(new InputStreamReader(new FileInputStream(fileOrig), \"UTF-8\"));\r\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), \"UTF-8\"));\r\n boolean lastWasMasked = false;\r\n while (null != (line = in.readLine())) {\r\n LineProcessingResult result = processLine(line);\r\n if (result.line.equals(MASK_PATTERN)) {\r\n if (!lastWasMasked) {\r\n out.write(result.line);\r\n out.write(\"\\n\");\r\n lastWasMasked = true;\r\n result.partialMaskWasMatched = false;\r\n }\r\n } else {\r\n out.write(result.line);\r\n out.write(\"\\n\");\r\n lastWasMasked = false;\r\n result.partialMaskWasMatched = false;\r\n }\r\n }\r\n in.close();\r\n out.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void executeBeforeMigrations() throws Exception{\r\n PartitionMigrationEvent event = getMigrationEvent();\r\n Throwable t = null;\r\n for (MigrationAwareService service : getMigrationAwareServices()) {\r\n try {\r\n service.beforeMigration(event);\r\n } catch (Throwable e) {\r\n getLogger().warning(\"Error while executing beforeMigration()\", e);\r\n t = e;\r\n }\r\n }\r\n if (t != null) {\r\n throw ExceptionUtil.rethrow(t);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nvoid serialize(RandomAccessOutput byteStream, Object obj, ObjectInspector objInspector, boolean skipLengthPrefix, BooleanRef warnedOnceNullMapKey) {\n BinaryObjectInspector baoi = (BinaryObjectInspector) objInspector;\n BytesWritable bw = baoi.getPrimitiveWritableObject(obj);\n int length = bw.getLength();\n if (!skipLengthPrefix) {\n LazyBinaryUtils.writeVInt(byteStream, length);\n } else {\n if (length == 0) {\n throw new RuntimeException(\"LazyBinaryColumnarSerde cannot serialize a non-null zero \" + \"length binary field. Consider using either LazyBinarySerde or ColumnarSerde.\");\n }\n }\n byteStream.write(bw.getBytes(), 0, length);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected void handleSetLicense(HttpPostCommand cmd) throws Throwable{\r\n prepareResponse(cmd, response(SUCCESS));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Object digestType(String type) throws Exception{\r\n String className = \"org.apache.bookkeeper.client.BookKeeper$DigestType\";\r\n for (Object o : classloader.loadClass(className).getEnumConstants()) {\r\n if (o.toString().equals(type)) {\r\n return o;\r\n }\r\n }\r\n throw new ClassNotFoundException(\"No such digest type \" + type);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void getObject(MinioClient minioClient, Exchange exchange) throws Exception{\r\n if (getConfiguration().isPojoRequest()) {\r\n GetObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(GetObjectArgs.Builder.class);\r\n if (isNotEmpty(payload)) {\r\n InputStream respond = minioClient.getObject(payload.build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(respond);\r\n }\r\n } else {\r\n final String bucketName = determineBucketName(exchange);\r\n final String sourceKey = determineObjectName(exchange);\r\n InputStream respond = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(sourceKey).build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(respond);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Kills all jobs tagged with the given tag that have been started after the\n * given timestamp.\n */\n@Override\npublic void killJobs(String tag, long timestamp) {\n try {\n LOG.info(\"Looking for jobs to kill...\");\n Set childJobs = getYarnChildJobs(tag, timestamp);\n if (childJobs.isEmpty()) {\n LOG.info(\"No jobs found from\");\n return;\n } else {\n LOG.info(String.format(\"Found MR jobs count: %d\", childJobs.size()));\n LOG.info(\"Killing all found jobs\");\n YarnClient yarnClient = YarnClient.createYarnClient();\n yarnClient.init(conf);\n yarnClient.start();\n for (ApplicationId app : childJobs) {\n LOG.info(String.format(\"Killing job: %s ...\", app));\n yarnClient.killApplication(app);\n LOG.info(String.format(\"Job %s killed\", app));\n }\n }\n } catch (YarnException ye) {\n throw new RuntimeException(\"Exception occurred while killing child job(s)\", ye);\n } catch (IOException ioe) {\n throw new RuntimeException(\"Exception occurred while killing child job(s)\", ioe);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private int getBitPosition(long timestamp) {\n if (maxBitPosition <= minBitPosition) {\n throw new RuntimeException(\"Error: minBitPosition is bigger than maxBitPosition\");\n }\n int range = maxBitPosition - minBitPosition;\n return minBitPosition + hashMod(String.format(\"%s%d%s\", secretKey, timestamp, secretKey), range);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "@ProcessElement\npublic void processElement(ProcessContext processContext) {\n try {\n HopRow hopRow = processContext.element();\n inputCounter.inc();\n String key = rowMeta.getString(hopRow.getRow(), keyIndex);\n GenericRecord value = (GenericRecord) hopRow.getRow()[valueIndex];\n processContext.output(KV.of(key, value));\n writtenCounter.inc();\n } catch (Exception e) {\n numErrors.inc();\n LOG.error(\"Error in HopRow to KV function\", e);\n throw new RuntimeException(\"Error in HopRow to KV function\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "@Override\npublic Operator visitTransform(TransformNode node, LocalExecutionPlanContext context) {\n final OperatorContext operatorContext = context.getDriverContext().addOperatorContext(context.getNextOperatorId(), node.getPlanNodeId(), TransformOperator.class.getSimpleName());\n final Operator inputOperator = generateOnlyChildOperator(node, context);\n final List inputDataTypes = getInputColumnTypes(node, context.getTypeProvider());\n final Map> inputLocations = makeLayout(node);\n final Expression[] projectExpressions = node.getOutputExpressions();\n final Map, TSDataType> expressionTypes = new HashMap<>();\n for (Expression projectExpression : projectExpressions) {\n if (context.isBuildPlanUseTemplate()) {\n ExpressionTypeAnalyzer.analyzeExpression(expressionTypes, projectExpression, new ExpressionTypeAnalyzer.TemplateTypeProvider(context.getTemplatedInfo().getSchemaMap()));\n } else {\n ExpressionTypeAnalyzer.analyzeExpression(expressionTypes, projectExpression, new ExpressionTypeAnalyzer.TypeProviderWrapper(context.getTypeProvider().getTreeModelTypeMap()));\n }\n }\n boolean hasNonMappableUDF = false;\n for (Expression expression : projectExpressions) {\n if (!expression.isMappable(expressionTypes)) {\n hasNonMappableUDF = true;\n break;\n }\n }\n // Use FilterAndProject Operator when project expressions are all mappable\n if (!hasNonMappableUDF) {\n // init project UDTFContext\n UDTFContext projectContext = new UDTFContext(context.getZoneId());\n projectContext.constructUdfExecutors(projectExpressions);\n List projectOutputTransformerList = new ArrayList<>();\n Map projectExpressionColumnTransformerMap = new HashMap<>();\n // records LeafColumnTransformer of project expressions\n List projectLeafColumnTransformerList = new ArrayList<>();\n ColumnTransformerVisitor visitor = new ColumnTransformerVisitor();\n ColumnTransformerVisitor.ColumnTransformerVisitorContext projectColumnTransformerContext = new ColumnTransformerVisitor.ColumnTransformerVisitorContext(projectContext, expressionTypes, projectLeafColumnTransformerList, inputLocations, projectExpressionColumnTransformerMap, ImmutableMap.of(), ImmutableList.of(), inputDataTypes, inputLocations.size() - 1, null);\n for (Expression expression : projectExpressions) {\n projectOutputTransformerList.add(visitor.process(expression, projectColumnTransformerContext));\n }\n return new FilterAndProjectOperator(operatorContext, inputOperator, inputDataTypes, ImmutableList.of(), null, ImmutableList.of(), projectLeafColumnTransformerList, projectOutputTransformerList, false, false);\n }\n try {\n return new TransformOperator(operatorContext, inputOperator, inputDataTypes, inputLocations, node.getOutputExpressions(), node.isKeepNull(), context.getZoneId(), expressionTypes, node.getScanOrder() == ASC);\n } catch (QueryProcessException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "@Override\npublic Analysis visitAlterTimeSeries(AlterTimeSeriesStatement alterTimeSeriesStatement, MPPQueryContext context) {\n context.setQueryType(QueryType.WRITE);\n Analysis analysis = new Analysis();\n analysis.setRealStatement(alterTimeSeriesStatement);\n Pair templateInfo = schemaFetcher.checkTemplateSetAndPreSetInfo(alterTimeSeriesStatement.getPath(), alterTimeSeriesStatement.getAlias());\n if (templateInfo != null) {\n throw new RuntimeException(new TemplateIncompatibleException(String.format(\"Cannot alter template timeseries [%s] since device template [%s] already set on path [%s].\", alterTimeSeriesStatement.getPath().getFullPath(), templateInfo.left.getName(), templateInfo.right)));\n }\n PathPatternTree patternTree = new PathPatternTree();\n patternTree.appendFullPath(alterTimeSeriesStatement.getPath());\n SchemaPartition schemaPartitionInfo;\n schemaPartitionInfo = partitionFetcher.getSchemaPartition(patternTree);\n analysis.setSchemaPartitionInfo(schemaPartitionInfo);\n return analysis;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected Object invoke(Operation operation, int partitionId) throws Throwable{\r\n Future future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);\r\n Object response = future.get();\r\n Object result = toObject(response);\r\n if (result instanceof Throwable) {\r\n throw (Throwable) result;\r\n }\r\n return result;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Map factory() throws Exception{\r\n Map mapModel = new HashMap<>();\r\n for (Class cl : models) {\r\n Object obj = ObjectHelper.newInstance(cl);\r\n mapModel.put(obj.getClass().getName(), obj);\r\n }\r\n return mapModel;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void setupStartupSummary() throws Exception{\r\n camelContext.addStartupListener(new StartupListener() {\r\n\r\n private volatile Set last;\r\n\r\n @Override\r\n public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception {\r\n camelContext.getManagementStrategy().addEventNotifier(new SimpleEventNotifierSupport() {\r\n\r\n @Override\r\n public boolean isEnabled(CamelEvent event) {\r\n return event instanceof CamelEvent.CamelContextStartedEvent || event instanceof CamelEvent.RouteReloadedEvent;\r\n }\r\n\r\n @Override\r\n public void notify(CamelEvent event) throws Exception {\r\n if (event instanceof CamelEvent.RouteReloadedEvent) {\r\n CamelEvent.RouteReloadedEvent re = (CamelEvent.RouteReloadedEvent) event;\r\n if (re.getIndex() < re.getTotal()) {\r\n return;\r\n }\r\n }\r\n Set endpoints = platformHttpComponent.getHttpEndpoints();\r\n if (endpoints.isEmpty()) {\r\n return;\r\n }\r\n if (last == null || last.size() != endpoints.size() || !last.containsAll(endpoints)) {\r\n LOG.info(\"HTTP endpoints summary\");\r\n for (HttpEndpointModel u : endpoints) {\r\n String line = \"http://0.0.0.0:\" + (server != null ? server.getPort() : getPort()) + u.getUri();\r\n if (u.getVerbs() != null) {\r\n line += \" (\" + u.getVerbs() + \")\";\r\n }\r\n LOG.info(\" {}\", line);\r\n }\r\n }\r\n last = new HashSet<>(endpoints);\r\n }\r\n });\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Map getBookieStats(LogSegmentMetadata segment) throws Exception{\r\n Map stats = new HashMap();\r\n LedgerHandle lh = bkc.client().get().openLedgerNoRecovery(segment.getLogSegmentId(), BookKeeper.DigestType.CRC32, getConf().getBKDigestPW().getBytes(UTF_8));\r\n long eidFirst = 0;\r\n for (SortedMap.Entry> entry : LedgerReader.bookiesForLedger(lh).entrySet()) {\r\n long eidLast = entry.getKey();\r\n long count = eidLast - eidFirst + 1;\r\n for (BookieId bookie : entry.getValue()) {\r\n merge(stats, bookie, (int) count);\r\n }\r\n eidFirst = eidLast;\r\n }\r\n return stats;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public LinkedHashMap getProteinSequences() throws Exception{\r\n LinkedHashMap proteinSequenceList = new LinkedHashMap();\r\n ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), \"prediction/gene/protein\");\r\n logger.info(\"{} hits\", elementList.size());\r\n for (Element proteinElement : elementList) {\r\n Element geneElement = (Element) proteinElement.getParentNode();\r\n String sequence = proteinElement.getTextContent().replaceAll(\"\\\\W\", \"\");\r\n ProteinSequence proteinSequence = new ProteinSequence(sequence);\r\n String idGene = geneElement.getAttribute(\"idGene\");\r\n proteinSequence.setAccession(new AccessionID(idGene));\r\n proteinSequenceList.put(idGene, proteinSequence);\r\n }\r\n return proteinSequenceList;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get a connection\n * @throws Exception\n */\nsynchronized Connection getConnection(String connName) throws Exception {\n Stack connStack = connections.get(connName);\n String connStr = connStrings.get(connName);\n if (connStr == null) {\n throw new Exception(\"Unknown connection profile: \" + connName);\n }\n if (connStack != null && !connStack.empty()) {\n // Reuse an existing connection\n return connStack.pop();\n }\n Connection c = openConnection(connStr);\n // Run initialization statements on the connection\n ArrayList sqls = connInits.get(connName);\n if (sqls != null) {\n Statement s = c.createStatement();\n for (String sql : sqls) {\n s.execute(sql);\n }\n s.close();\n }\n return c;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// Store the bucket path to bucket number mapping in the table scan operator.\n// Although one mapper per file is used (BucketizedInputHiveInput), it is possible that\n// any mapper can pick up any file (depending on the size of the files). The bucket number\n// corresponding to the input file is stored to name the output bucket file appropriately.\nprivate void storeBucketPathMapping(TableScanOperator tsOp, FileStatus[] srcs) {\n Map bucketFileNameMapping = new HashMap();\n for (int pos = 0; pos < srcs.length; pos++) {\n if (ShimLoader.getHadoopShims().isDirectory(srcs[pos])) {\n throw new RuntimeException(\"Was expecting '\" + srcs[pos].getPath() + \"' to be bucket file.\");\n }\n bucketFileNameMapping.put(srcs[pos].getPath().getName(), pos);\n }\n tsOp.getConf().setBucketFileNameMapping(bucketFileNameMapping);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic void handle(SchedulerEvent event) {\n switch(event.getType()) {\n case NODE_ADDED:\n if (!(event instanceof NodeAddedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent) event;\n addNode(nodeAddedEvent.getContainerReports(), nodeAddedEvent.getAddedRMNode());\n break;\n case NODE_REMOVED:\n if (!(event instanceof NodeRemovedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent) event;\n removeNode(nodeRemovedEvent.getRemovedRMNode());\n break;\n case NODE_UPDATE:\n if (!(event instanceof NodeUpdateSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n NodeUpdateSchedulerEvent nodeUpdatedEvent = (NodeUpdateSchedulerEvent) event;\n nodeUpdate(nodeUpdatedEvent.getRMNode());\n break;\n case APP_ADDED:\n if (!(event instanceof AppAddedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent) event;\n String queueName = resolveReservationQueueName(appAddedEvent.getQueue(), appAddedEvent.getApplicationId(), appAddedEvent.getReservationID(), appAddedEvent.getIsAppRecovering());\n if (queueName != null) {\n addApplication(appAddedEvent.getApplicationId(), queueName, appAddedEvent.getUser(), appAddedEvent.getIsAppRecovering(), appAddedEvent.getPlacementContext());\n }\n break;\n case APP_REMOVED:\n if (!(event instanceof AppRemovedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent) event;\n removeApplication(appRemovedEvent.getApplicationID(), appRemovedEvent.getFinalState());\n break;\n case NODE_RESOURCE_UPDATE:\n if (!(event instanceof NodeResourceUpdateSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n NodeResourceUpdateSchedulerEvent nodeResourceUpdatedEvent = (NodeResourceUpdateSchedulerEvent) event;\n updateNodeResource(nodeResourceUpdatedEvent.getRMNode(), nodeResourceUpdatedEvent.getResourceOption());\n break;\n case APP_ATTEMPT_ADDED:\n if (!(event instanceof AppAttemptAddedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n AppAttemptAddedSchedulerEvent appAttemptAddedEvent = (AppAttemptAddedSchedulerEvent) event;\n addApplicationAttempt(appAttemptAddedEvent.getApplicationAttemptId(), appAttemptAddedEvent.getTransferStateFromPreviousAttempt(), appAttemptAddedEvent.getIsAttemptRecovering());\n break;\n case APP_ATTEMPT_REMOVED:\n if (!(event instanceof AppAttemptRemovedSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent = (AppAttemptRemovedSchedulerEvent) event;\n removeApplicationAttempt(appAttemptRemovedEvent.getApplicationAttemptID(), appAttemptRemovedEvent.getFinalAttemptState(), appAttemptRemovedEvent.getKeepContainersAcrossAppAttempts());\n break;\n case RELEASE_CONTAINER:\n if (!(event instanceof ReleaseContainerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n RMContainer container = ((ReleaseContainerEvent) event).getContainer();\n completedContainer(container, SchedulerUtils.createAbnormalContainerStatus(container.getContainerId(), SchedulerUtils.RELEASED_CONTAINER), RMContainerEventType.RELEASED);\n break;\n case CONTAINER_EXPIRED:\n if (!(event instanceof ContainerExpiredSchedulerEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n ContainerExpiredSchedulerEvent containerExpiredEvent = (ContainerExpiredSchedulerEvent) event;\n ContainerId containerId = containerExpiredEvent.getContainerId();\n super.completedContainer(getRMContainer(containerId), SchedulerUtils.createAbnormalContainerStatus(containerId, SchedulerUtils.EXPIRED_CONTAINER), RMContainerEventType.EXPIRE);\n break;\n case MARK_CONTAINER_FOR_PREEMPTION:\n if (!(event instanceof ContainerPreemptEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n ContainerPreemptEvent preemptContainerEvent = (ContainerPreemptEvent) event;\n ApplicationAttemptId appId = preemptContainerEvent.getAppId();\n RMContainer preemptedContainer = preemptContainerEvent.getContainer();\n FSAppAttempt app = getApplicationAttempt(appId);\n app.trackContainerForPreemption(preemptedContainer);\n break;\n case MARK_CONTAINER_FOR_KILLABLE:\n if (!(event instanceof ContainerPreemptEvent)) {\n throw new RuntimeException(\"Unexpected event type: \" + event);\n }\n ContainerPreemptEvent containerKillableEvent = (ContainerPreemptEvent) event;\n RMContainer killableContainer = containerKillableEvent.getContainer();\n completedContainer(killableContainer, SchedulerUtils.createPreemptedContainerStatus(killableContainer.getContainerId(), SchedulerUtils.PREEMPTED_CONTAINER), RMContainerEventType.KILL);\n break;\n default:\n LOG.error(\"Unknown event arrived at FairScheduler: {}\", event);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "@Override\npublic PDone expand(PCollection input) {\n try {\n // Only initialize once on this node/vm\n //\n BeamHop.init();\n // Inflate the metadata on the node where this is running...\n //\n IRowMeta rowMeta = JsonRowMeta.fromJson(rowMetaJson);\n int messageIndex = rowMeta.indexOfValue(dataField);\n if (messageIndex < 0) {\n throw new HopException(\"Unable to find message field \" + dataField + \" in input row: \" + rowMeta.toString());\n }\n if (!\"String\".equals(dataType)) {\n throw new HopException(\"For now, only Strings are supported as Kinesis data messages\");\n }\n // Add custom configuration options to this map:\n Properties producerProperties = new Properties();\n for (KinesisConfigOption configOption : configOptions) {\n producerProperties.put(configOption.getParameter(), configOption.getValue());\n }\n // Convert to PCollection of KV\n //\n PCollection messages = input.apply(ParDo.of(new HopRowToMessage(transformName, rowMetaJson, messageIndex)));\n // Write to Kinesis stream with \n //\n KinesisIO.Write write = KinesisIO.write().withAWSClientsProvider(accessKey, secretKey, regions).withStreamName(streamName).withPartitionKey(partitionKey).withProducerProperties(producerProperties);\n return messages.apply(write);\n } catch (Exception e) {\n numErrors.inc();\n LOG.error(\"Error in Beam Kinesis Produce transform\", e);\n throw new RuntimeException(\"Error in Beam Kinesis Produce transform\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private boolean doCreateAndExecuteSqlStatementWithHeaders(Exchange exchange, String sql, Connection conn) throws Exception{\r\n PreparedStatement ps = null;\r\n ResultSet rs = null;\r\n boolean shouldCloseResources = true;\r\n try {\r\n final String preparedQuery = getEndpoint().getPrepareStatementStrategy().prepareQuery(sql, getEndpoint().isAllowNamedParameters());\r\n boolean shouldRetrieveGeneratedKeys = exchange.getIn().getHeader(JdbcConstants.JDBC_RETRIEVE_GENERATED_KEYS, false, Boolean.class);\r\n if (shouldRetrieveGeneratedKeys) {\r\n Object expectedGeneratedColumns = exchange.getIn().getHeader(JdbcConstants.JDBC_GENERATED_COLUMNS);\r\n if (expectedGeneratedColumns == null) {\r\n ps = conn.prepareStatement(preparedQuery, Statement.RETURN_GENERATED_KEYS);\r\n } else if (expectedGeneratedColumns instanceof String[]) {\r\n ps = conn.prepareStatement(preparedQuery, (String[]) expectedGeneratedColumns);\r\n } else if (expectedGeneratedColumns instanceof int[]) {\r\n ps = conn.prepareStatement(preparedQuery, (int[]) expectedGeneratedColumns);\r\n } else {\r\n throw new IllegalArgumentException(\"Header specifying expected returning columns isn't an instance of String[] or int[] but \" + expectedGeneratedColumns.getClass());\r\n }\r\n } else {\r\n ps = conn.prepareStatement(preparedQuery);\r\n }\r\n bindParameters(exchange, ps);\r\n int expectedCount = ps.getParameterMetaData().getParameterCount();\r\n if (expectedCount > 0) {\r\n Iterator it = getEndpoint().getPrepareStatementStrategy().createPopulateIterator(sql, preparedQuery, expectedCount, exchange, exchange.getIn().getBody());\r\n getEndpoint().getPrepareStatementStrategy().populateStatement(ps, it, expectedCount);\r\n }\r\n LOG.debug(\"Executing JDBC PreparedStatement: {}\", sql);\r\n boolean stmtExecutionResult = ps.execute();\r\n if (stmtExecutionResult) {\r\n rs = ps.getResultSet();\r\n shouldCloseResources = setResultSet(exchange, conn, rs);\r\n } else {\r\n int updateCount = ps.getUpdateCount();\r\n exchange.getMessage().setHeader(JdbcConstants.JDBC_UPDATE_COUNT, updateCount);\r\n }\r\n if (shouldRetrieveGeneratedKeys) {\r\n setGeneratedKeys(exchange, conn, ps.getGeneratedKeys());\r\n }\r\n } finally {\r\n if (shouldCloseResources) {\r\n closeQuietly(rs);\r\n closeQuietly(ps);\r\n } else {\r\n final Statement finalPs = ps;\r\n final ResultSet finalRs = rs;\r\n exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() {\r\n\r\n @Override\r\n public void onDone(Exchange exchange) {\r\n closeQuietly(finalRs);\r\n closeQuietly(finalPs);\r\n }\r\n\r\n @Override\r\n public int getOrder() {\r\n return LOWEST + 100;\r\n }\r\n });\r\n }\r\n }\r\n return shouldCloseResources;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private FileMetadata putSingleBody(Exchange exchange, String dropboxPath, DropboxUploadMode mode) throws Exception{\r\n byte[] data = exchange.getIn().getMandatoryBody(byte[].class);\r\n try (InputStream is = new ByteArrayInputStream(data)) {\r\n final WriteMode uploadMode;\r\n if (mode == DropboxUploadMode.force) {\r\n uploadMode = WriteMode.OVERWRITE;\r\n } else {\r\n uploadMode = WriteMode.ADD;\r\n }\r\n return client.files().uploadBuilder(dropboxPath).withMode(uploadMode).uploadAndFinish(is, data.length);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Session createSession(Connection connection, SjmsEndpoint endpoint) throws Exception{\r\n return connection.createSession(endpoint.isTransacted(), endpoint.getAcknowledgementMode().intValue());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void startLldpPoll(long period) {\n for (Map.Entry entry : openHandles.entrySet()) {\n PcapHandle handle = entry.getValue();\n MacAddress macAddress = entry.getKey();\n Function lldpTimer = message -> {\n // Construct and send the LLDP Probe\n TlvOrgSpecificProfibus portStatus = new TlvOrgSpecificProfibus(new TlvProfibusSubTypePortStatus(0x00, false, false, (byte) 0x00));\n TlvOrgSpecificProfibus chassisMac = new TlvOrgSpecificProfibus(new TlvProfibusSubTypeChassisMac(macAddress));\n TlvOrgSpecificIeee8023 ieee = new TlvOrgSpecificIeee8023(new TlvIeee8023MacPhyConfigStatus((short) 0x03, 0x0020, 0x0010));\n Ethernet_Frame identificationRequest = null;\n try {\n identificationRequest = new Ethernet_Frame(LLDP_BROADCAST_MAC_ADDRESS, macAddress, new Ethernet_FramePayload_LLDP(new Lldp_Pdu(Arrays.asList(new TlvChassisId((short) (PLC4X_LLDP_IDENTIFIER.length() + 1), (short) 7, PLC4X_LLDP_IDENTIFIER), new TlvPortId((short) (PLC4X_LLDP_PORT.length() + 1), (short) 7, PLC4X_LLDP_PORT), new TlvTimeToLive((short) 2, 20), new TlvOrganizationSpecific((short) portStatus.getLengthInBytes(), portStatus), new TlvOrganizationSpecific((short) chassisMac.getLengthInBytes(), chassisMac), new TlvOrganizationSpecific((short) ieee.getLengthInBytes(), ieee), new TlvManagementAddress((short) 12, ManagementAddressSubType.IPV4, // 192.168.90.110\n new IpAddress(Hex.decodeHex(\"c0a85a6e\")), (short) 0x03, 0x01L, (short) 0x00), new EndOfLldp((short) 0)))));\n } catch (DecoderException e) {\n throw new RuntimeException(e);\n }\n WriteBufferByteBased buffer = new WriteBufferByteBased(identificationRequest.getLengthInBytes());\n try {\n identificationRequest.serialize(buffer);\n Packet packet = EthernetPacket.newPacket(buffer.getBytes(), 0, identificationRequest.getLengthInBytes());\n handle.sendPacket(packet);\n } catch (PcapNativeException | NotOpenException | SerializationException | IllegalRawDataException e) {\n throw new RuntimeException(e);\n }\n return null;\n };\n Timer timer = new Timer();\n periodicTimers.add(timer);\n // Schedule to run after every 3 second(3000 millisecond)\n timer.scheduleAtFixedRate(new PeriodicTask(handle, lldpTimer), 0, period);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public void beforeRun() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void createSources() throws Exception{\r\n if (!isSessionStateStarted) {\r\n startSessionState(qTestResultProcessor.canReuseSession());\r\n }\r\n getCliDriver().processLine(\"set test.data.dir=\" + testFiles + \";\");\r\n conf.setBoolean(\"hive.test.init.phase\", true);\r\n initFromScript();\r\n conf.setBoolean(\"hive.test.init.phase\", false);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Node getMessageBodyNode(Message message) throws Exception{\r\n InputStream is = message.getMandatoryBody(InputStream.class);\r\n Boolean isPlainText = isPlainText(message);\r\n Node node;\r\n if (isPlainText != null && isPlainText) {\r\n node = getTextNode(message, is);\r\n } else {\r\n ValidatorErrorHandler errorHandler = new DefaultValidationErrorHandler();\r\n Schema schema = getSchemaForSigner(message, errorHandler);\r\n Document doc = parseInput(is, getConfiguration().getDisallowDoctypeDecl(), schema, errorHandler);\r\n errorHandler.handleErrors(message.getExchange(), schema, null);\r\n node = doc.getDocumentElement();\r\n LOG.debug(\"Root element of document to be signed: {}\", node);\r\n }\r\n return node;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Acquire privileged resources (i.e., the privileged ports) for the data\n * node. The privileged resources consist of the port of the RPC server and\n * the port of HTTP (not HTTPS) server.\n */\n@VisibleForTesting\npublic static SecureResources getSecureResources(Configuration conf) throws Exception {\n HttpConfig.Policy policy = DFSUtil.getHttpPolicy(conf);\n boolean isSaslEnabled = DataTransferSaslUtil.getSaslPropertiesResolver(conf) != null;\n boolean isRpcPrivileged;\n boolean isHttpPrivileged = false;\n System.err.println(\"isSaslEnabled:\" + isSaslEnabled);\n // Obtain secure port for data streaming to datanode\n InetSocketAddress streamingAddr = DataNode.getStreamingAddr(conf);\n int socketWriteTimeout = conf.getInt(DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY, HdfsConstants.WRITE_TIMEOUT);\n int backlogLength = conf.getInt(CommonConfigurationKeysPublic.IPC_SERVER_LISTEN_QUEUE_SIZE_KEY, CommonConfigurationKeysPublic.IPC_SERVER_LISTEN_QUEUE_SIZE_DEFAULT);\n ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();\n try {\n ss.bind(streamingAddr, backlogLength);\n } catch (BindException e) {\n BindException newBe = appendMessageToBindException(e, streamingAddr.toString());\n throw newBe;\n }\n // Check that we got the port we need\n if (ss.getLocalPort() != streamingAddr.getPort()) {\n throw new RuntimeException(\"Unable to bind on specified streaming port in secure \" + \"context. Needed \" + streamingAddr.getPort() + \", got \" + ss.getLocalPort());\n }\n isRpcPrivileged = SecurityUtil.isPrivilegedPort(ss.getLocalPort());\n System.err.println(\"Opened streaming server at \" + streamingAddr);\n // Bind a port for the web server. The code intends to bind HTTP server to\n // privileged port only, as the client can authenticate the server using\n // certificates if they are communicating through SSL.\n final ServerSocketChannel httpChannel;\n if (policy.isHttpEnabled()) {\n httpChannel = ServerSocketChannel.open();\n InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);\n try {\n httpChannel.socket().bind(infoSocAddr);\n } catch (BindException e) {\n BindException newBe = appendMessageToBindException(e, infoSocAddr.toString());\n throw newBe;\n }\n InetSocketAddress localAddr = (InetSocketAddress) httpChannel.socket().getLocalSocketAddress();\n if (localAddr.getPort() != infoSocAddr.getPort()) {\n throw new RuntimeException(\"Unable to bind on specified info port in \" + \"secure context. Needed \" + infoSocAddr.getPort() + \", got \" + ss.getLocalPort());\n }\n System.err.println(\"Successfully obtained privileged resources (streaming port = \" + ss + \" ) (http listener port = \" + localAddr.getPort() + \")\");\n isHttpPrivileged = SecurityUtil.isPrivilegedPort(localAddr.getPort());\n System.err.println(\"Opened info server at \" + infoSocAddr);\n } else {\n httpChannel = null;\n }\n return new SecureResources(ss, httpChannel, isSaslEnabled, isRpcPrivileged, isHttpPrivileged);\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static Class getClassByName(String className) {\n Class retv = null;\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n retv = Class.forName(className, true, classLoader);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return retv;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private synchronized Expression getTransform(Message msg) throws Exception{\r\n final String jsltStringFromHeader = allowTemplateFromHeader ? msg.getHeader(JsltConstants.HEADER_JSLT_STRING, String.class) : null;\r\n final boolean useTemplateFromUri = jsltStringFromHeader == null;\r\n if (useTemplateFromUri && transform != null) {\r\n return transform;\r\n }\r\n final Collection functions = Objects.requireNonNullElse(((JsltComponent) getComponent()).getFunctions(), Collections.emptyList());\r\n final JsonFilter objectFilter = Objects.requireNonNullElse(((JsltComponent) getComponent()).getObjectFilter(), DEFAULT_JSON_FILTER);\r\n final String transformSource;\r\n final InputStream stream;\r\n if (useTemplateFromUri) {\r\n transformSource = getResourceUri();\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Jslt content read from resource {} with resourceUri: {} for endpoint {}\", transformSource, transformSource, getEndpointUri());\r\n }\r\n stream = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), transformSource);\r\n if (stream == null) {\r\n throw new JsltException(\"Cannot load resource '\" + transformSource + \"': not found\");\r\n }\r\n } else {\r\n stream = new ByteArrayInputStream(jsltStringFromHeader.getBytes(StandardCharsets.UTF_8));\r\n transformSource = \"\";\r\n }\r\n final Expression transform;\r\n try {\r\n transform = new Parser(new InputStreamReader(stream)).withFunctions(functions).withObjectFilter(objectFilter).withSource(transformSource).compile();\r\n } finally {\r\n IOHelper.close(stream);\r\n }\r\n if (useTemplateFromUri) {\r\n this.transform = transform;\r\n }\r\n return transform;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `value` to the URL query string\n if (getValue() != null) {\n for (int i = 0; i < getValue().size(); i++) {\n try {\n joiner.add(String.format(\"%svalue%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getValue().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private void downloadOnce(List latencies) throws Exception{\r\n Path downloadPath = new File(this.path).toPath();\r\n long start = System.currentTimeMillis();\r\n DirectoryDownload download = transferManager.downloadDirectory(b -> b.bucket(bucket).destination(downloadPath).listObjectsV2RequestTransformer(l -> l.prefix(config.prefix())));\r\n CompletedDirectoryDownload completedDirectoryDownload = download.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS);\r\n if (completedDirectoryDownload.failedTransfers().isEmpty()) {\r\n long end = System.currentTimeMillis();\r\n latencies.add((end - start) / 1000.0);\r\n } else {\r\n logger.error(() -> \"Some transfers failed: \" + completedDirectoryDownload.failedTransfers());\r\n }\r\n runAndLogError(logger.logger(), \"Deleting directory failed \" + downloadPath, () -> FileUtils.cleanUpTestDirectory(downloadPath));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Format getFormat(FormattingOptions formattingOptions) throws Exception{\r\n if (formattingOptions.getBindyConverter() != null) {\r\n return formattingOptions.getBindyConverter().value().newInstance();\r\n }\r\n return doGetFormat(formattingOptions);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Parse the given string into Date object.\n * @param str String\n * @return Date\n */\npublic Date parseDate(String str) {\n try {\n return dateFormat.parse(str);\n } catch (java.text.ParseException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "@Override\npublic void check() {\n if (sessionTimeGap < 0) {\n throw new RuntimeException(String.format(\"Parameter sessionTimeGap(%d) should be equal to or greater than zero.\", sessionTimeGap));\n }\n if (displayWindowEnd < displayWindowBegin) {\n throw new RuntimeException(String.format(\"displayWindowEnd(%d) < displayWindowBegin(%d)\", displayWindowEnd, displayWindowBegin));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "public ASTNode parseQuery() throws Exception{\r\n return pd.parse(inputContent).getTree();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void pauseTrigger() throws Exception{\r\n Scheduler scheduler = getComponent().getScheduler();\r\n boolean isClustered = scheduler.getMetaData().isJobStoreClustered();\r\n if (jobPaused.get() || isClustered) {\r\n return;\r\n }\r\n jobPaused.set(true);\r\n if (!scheduler.isShutdown()) {\r\n LOG.info(\"Pausing trigger {}\", triggerKey);\r\n scheduler.pauseTrigger(triggerKey);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process() throws Exception{\r\n byte[] lineSep = System.getProperty(\"line.separator\").getBytes();\r\n for (GeneSequence sequence : sequences) {\r\n String header = headerFormat.getHeader(sequence);\r\n os.write('>');\r\n os.write(header.getBytes());\r\n os.write(lineSep);\r\n int compoundCount = 0;\r\n String seq = \"\";\r\n seq = sequence.getSequence5PrimeTo3Prime().getSequenceAsString();\r\n if (showExonUppercase) {\r\n StringBuilder sb = new StringBuilder(seq.toLowerCase());\r\n int geneBioBegin = sequence.getBioBegin();\r\n int geneBioEnd = sequence.getBioEnd();\r\n for (ExonSequence exonSequence : sequence.getExonSequences()) {\r\n int featureBioBegin = 0;\r\n int featureBioEnd = 0;\r\n if (sequence.getStrand() != Strand.NEGATIVE) {\r\n featureBioBegin = exonSequence.getBioBegin() - geneBioBegin;\r\n featureBioEnd = exonSequence.getBioEnd() - geneBioBegin;\r\n } else {\r\n featureBioBegin = geneBioEnd - exonSequence.getBioEnd();\r\n featureBioEnd = geneBioEnd - exonSequence.getBioBegin();\r\n }\r\n if (featureBioBegin < 0 || featureBioEnd < 0 || featureBioEnd > sb.length() || featureBioBegin > sb.length()) {\r\n logger.warn(\"Bad Feature, Accession: {}, Sequence Strand: {}, Gene Begin: {}, Gene End: {}, Exon Begin: {}, Exon End: {}\", sequence.getAccession().toString(), sequence.getStrand(), geneBioBegin, geneBioEnd, exonSequence.getBioBegin(), exonSequence.getBioEnd());\r\n } else {\r\n for (int i = featureBioBegin; i <= featureBioEnd; i++) {\r\n char ch = sb.charAt(i);\r\n String temp = String.valueOf(ch);\r\n ch = temp.toUpperCase().charAt(0);\r\n sb.setCharAt(i, ch);\r\n }\r\n }\r\n }\r\n seq = sb.toString();\r\n }\r\n for (int i = 0; i < seq.length(); i++) {\r\n os.write(seq.charAt(i));\r\n compoundCount++;\r\n if (compoundCount == lineLength) {\r\n os.write(lineSep);\r\n compoundCount = 0;\r\n }\r\n }\r\n if ((sequence.getLength() % getLineLength()) != 0) {\r\n os.write(lineSep);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void sendToConsumers(final Exchange exchange) throws Exception{\r\n int size = getEndpoint().getConsumers().size();\r\n if (size > 1 && !getEndpoint().isMultipleConsumersSupported()) {\r\n throw new IllegalStateException(\"Multiple consumers for the same endpoint is not allowed: \" + getEndpoint());\r\n }\r\n if (getEndpoint().isMultipleConsumersSupported()) {\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Multicasting to {} consumers for Exchange: {}\", size, exchange);\r\n }\r\n final List completions = exchange.getExchangeExtension().handoverCompletions();\r\n AsyncProcessor mp = getEndpoint().getConsumerMulticastProcessor();\r\n ObjectHelper.notNull(mp, \"ConsumerMulticastProcessor\", this);\r\n mp.process(exchange, doneSync -> {\r\n UnitOfWorkHelper.doneSynchronizations(exchange, completions);\r\n });\r\n } else {\r\n getAsyncProcessor().process(exchange, EmptyAsyncCallback.get());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doInTransactionTemplate(final Exchange exchange) throws Throwable{\r\n transactionPolicy.run(new JtaTransactionPolicy.Runnable() {\r\n\r\n @Override\r\n public void run() throws Throwable {\r\n Throwable rce;\r\n processByErrorHandler(exchange);\r\n if (exchange.getException() != null || exchange.isRollbackOnly()) {\r\n if (exchange.getException() != null) {\r\n rce = exchange.getException();\r\n } else {\r\n rce = new TransactionRolledbackException();\r\n }\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Throwing runtime exception to force transaction to rollback on {}\", transactionPolicy);\r\n }\r\n throw rce;\r\n }\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"loginRole\" })\npublic String nextInvoiceNumber(InvoicePool pool) throws Exception {\n InvoicePool ip = this.invoicePools.find(pool.getId());\n if (ip == null) {\n log.error(\"invalid invoice pool with id \" + pool.getId());\n throw new Exception(\"Ung\u00fcltiger Rechnungsnummernkreis\");\n }\n int startFrom = ip.getLastIndex() + 1;\n if (ip.getStartIndex() > startFrom) {\n startFrom = ip.getStartIndex();\n }\n ip.setLastIndex(startFrom);\n Date now = new Date();\n try {\n String next = InvoiceNumberGenerator.getNextInvoiceNumber(ip.getPattern(), now, startFrom);\n this.invoicePools.edit(ip);\n return next;\n } catch (InvalidSchemaPatternException isp) {\n log.error(\"invalid invoice schema pattern \" + ip.getPattern(), isp);\n throw new Exception(isp.getMessage());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void handleBackupInterrupt(HttpPostCommand cmd, boolean deprecated) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n getNode().getNodeExtension().getHotRestartService().interruptBackupTask();\r\n if (deprecated) {\r\n Map headers = new HashMap<>();\r\n headers.put(\"Content-Type\", CONTENT_TYPE_JSON);\r\n headers.put(\"Deprecation\", \"true\");\r\n headers.put(\"Warning\", \"299 - \\\"Deprecated API\\\". Please use\" + \" /hazelcast/rest/management/cluster/backupInterrupt instead. This API will be removed\" + \" in future releases.\");\r\n cmd.setResponseWithHeaders(SC_200, headers, stringToBytes(response(SUCCESS).toString()));\r\n } else {\r\n prepareResponse(cmd, response(SUCCESS));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Load a EC policy from a policy element in the XML configuration file.\n * @param element EC policy element\n * @param schemas all valid schemas of the EC policy file\n * @return EC policy\n */\nprivate ErasureCodingPolicy loadPolicy(Element element, Map schemas) {\n NodeList fields = element.getChildNodes();\n ECSchema schema = null;\n int cellSize = 0;\n for (int i = 0; i < fields.getLength(); i++) {\n Node fieldNode = fields.item(i);\n if (fieldNode instanceof Element) {\n Element field = (Element) fieldNode;\n String tagName = field.getTagName();\n // Get the nonnull text value.\n Text text = (Text) field.getFirstChild();\n if (text != null) {\n if (!text.isElementContentWhitespace()) {\n String value = text.getData().trim();\n if (\"schema\".equals(tagName)) {\n schema = schemas.get(value);\n } else if (\"cellsize\".equals(tagName)) {\n try {\n cellSize = Integer.parseInt(value);\n } catch (NumberFormatException e) {\n throw new IllegalArgumentException(\"Bad EC policy cellsize\" + \" value \" + value + \" is found. It should be an integer\");\n }\n } else {\n LOG.warn(\"Invalid tagName: \" + tagName);\n }\n }\n } else {\n throw new IllegalArgumentException(\"Value of <\" + tagName + \"> is null\");\n }\n }\n }\n if (schema != null && cellSize > 0) {\n return new ErasureCodingPolicy(schema, cellSize);\n } else {\n throw new RuntimeException(\"Bad policy is found in\" + \" EC policy configuration file\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void downloadOnceToMemory(List latencies) throws Exception{\r\n long start = System.currentTimeMillis();\r\n AsyncResponseTransformer responseTransformer = new NoOpResponseTransformer<>();\r\n transferManager.download(DownloadRequest.builder().getObjectRequest(req -> req.bucket(bucket).key(key)).responseTransformer(responseTransformer).build()).completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS);\r\n long end = System.currentTimeMillis();\r\n latencies.add((end - start) / 1000.0);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void validateBackupDirectory(BackupProgressCallback progress) throws Exception {\n File dir = new File(this.backupDirectory);\n if (progress != null) {\n progress.onProgress(\"Pr\u00fcfe Datensicherungsverzeichnis \" + dir.getAbsolutePath());\n }\n ArrayList subDirs = new ArrayList<>();\n if (!dir.exists()) {\n throw new Exception(\"Verzeichnis '\" + this.backupDirectory + \"' existiert nicht!\");\n }\n if (!dir.isDirectory()) {\n throw new Exception(\"'\" + this.backupDirectory + \"' ist kein Verzeichnis!\");\n }\n if (!dir.canRead()) {\n throw new Exception(\"Verzeichnis '\" + this.backupDirectory + \"' ist nicht lesbar!\");\n }\n boolean dumpExists = false;\n for (File f : dir.listFiles()) {\n if (f.isDirectory()) {\n subDirs.add(f.getName());\n } else if (f.isFile()) {\n if (\"jlawyerdb-dump.sql.zip\".equals(f.getName()) || \"jlawyerdb-dump-encrypted.sql.zip\".equals(f.getName())) {\n dumpExists = true;\n }\n }\n }\n if (!subDirs.contains(\"archivefiles\") || !subDirs.contains(\"templates\") || !subDirs.contains(\"mastertemplates\") || !subDirs.contains(\"emailtemplates\") || !subDirs.contains(DIR_LETTERHEADS)) {\n throw new Exception(\"Verzeichnis unvollst\u00e4ndig - ben\u00f6tigt werden Unterverzeichnisse: archivefiles, templates, emailtemplates, mastertemplates, letterheads\");\n }\n if (!dumpExists) {\n throw new Exception(\"Datenbanksicherung 'jlawyerdb-dump.sql' fehlt!\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Retrieves registered Identity providers for a given tenant by Identity Provider name\n *\n * @param filter\n * @return List of FederatedIdentityProvider. IdP names, primary IdP and home realm\n * identifiers of each IdP\n * @throws Exception Error when getting list of Identity Providers\n */\npublic List getIdPsSearch(String filter) throws Exception {\n try {\n IdentityProvider[] identityProviders = idPMgtStub.getAllIdPsSearch(filter);\n if (identityProviders != null && identityProviders.length > 0) {\n return Arrays.asList(identityProviders);\n } else {\n return new ArrayList();\n }\n } catch (Exception e) {\n log.error(\"Error in retrieving the Identity Provider\", e);\n throw new Exception(\"Error occurred while retrieving Identity Providers\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "/**\n * See the comments for HiveDecimal.serializationUtilsWrite.\n */\n@HiveDecimalWritableVersionV2\npublic boolean serializationUtilsWrite(OutputStream outputStream, long[] scratchLongs) throws IOException {\n if (!isSet()) {\n throw new RuntimeException(\"no value set\");\n }\n return fastSerializationUtilsWrite(outputStream, scratchLongs);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Obtains the value of the last reserved sequence number.\n * @return Last reserved sequence number.\n */\n@Override\npublic int getDelegationTokenSeqNum() {\n try {\n return selectSequenceNum();\n } catch (SQLException e) {\n throw new RuntimeException(\"Failed to get token sequence number in SQL secret manager\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private long readFourBytes() throws Exception{\r\n long ret = 0;\r\n if (!reverse) {\r\n ret = raf.read();\r\n ret += raf.read() * 0x100;\r\n ret += raf.read() * 0x10000;\r\n ret += raf.read() * 0x1000000;\r\n } else {\r\n ret = raf.read() * 0x1000000;\r\n ret += raf.read() * 0x10000;\r\n ret += raf.read() * 0x100;\r\n ret += raf.read();\r\n }\r\n return ret;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void copyObject(MinioClient minioClient, Exchange exchange) throws Exception{\r\n if (getConfiguration().isPojoRequest()) {\r\n CopyObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(CopyObjectArgs.Builder.class);\r\n if (isNotEmpty(payload)) {\r\n ObjectWriteResponse result = minioClient.copyObject(payload.build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(result);\r\n }\r\n } else {\r\n final String bucketName = determineBucketName(exchange);\r\n final String sourceKey = determineObjectName(exchange);\r\n final String destinationKey = exchange.getIn().getHeader(MinioConstants.DESTINATION_OBJECT_NAME, String.class);\r\n final String destinationBucketName = exchange.getIn().getHeader(MinioConstants.DESTINATION_BUCKET_NAME, String.class);\r\n if (isEmpty(destinationBucketName)) {\r\n throw new IllegalArgumentException(\"Bucket Name Destination must be specified for copyObject Operation\");\r\n }\r\n if (isEmpty(destinationKey)) {\r\n throw new IllegalArgumentException(\"Destination Key must be specified for copyObject Operation\");\r\n }\r\n CopySource.Builder copySourceBuilder = CopySource.builder().bucket(bucketName).object(sourceKey);\r\n CopyObjectArgs.Builder copyObjectRequest = CopyObjectArgs.builder().bucket(destinationBucketName).object(destinationKey).source(copySourceBuilder.build());\r\n ObjectWriteResponse copyObjectResult = minioClient.copyObject(copyObjectRequest.build());\r\n Message message = getMessageForResponse(exchange);\r\n if (isNotEmpty(copyObjectResult.versionId())) {\r\n message.setHeader(MinioConstants.VERSION_ID, copyObjectResult.versionId());\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Bucket createClient() throws Exception{\r\n List hosts = Arrays.asList(makeBootstrapURI());\r\n String connectionString;\r\n if (bucket == null || bucket.isEmpty()) {\r\n throw new CamelException(COUCHBASE_URI_ERROR);\r\n }\r\n ClusterEnvironment.Builder cfb = ClusterEnvironment.builder();\r\n if (queryTimeout != DEFAULT_QUERY_TIMEOUT) {\r\n cfb.timeoutConfig().connectTimeout(Duration.ofMillis(connectTimeout)).queryTimeout(Duration.ofMillis(queryTimeout));\r\n }\r\n ClusterEnvironment env = cfb.build();\r\n String addHosts = hosts.stream().map(URI::getHost).collect(Collectors.joining(\",\"));\r\n if (!addHosts.isEmpty()) {\r\n connectionString = addHosts;\r\n } else {\r\n connectionString = hostname;\r\n }\r\n Cluster cluster = Cluster.connect(connectionString, ClusterOptions.clusterOptions(username, password).environment(env));\r\n return cluster.bucket(bucket);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * This method retrieves the cluster user information, and it is reachable by using\n * {@link RMWSConsts#CLUSTER_USER_INFO}.\n *\n * In Federation mode, we will return a ClusterUserInfo object,\n * which contains a set of ClusterUserInfo.\n *\n * @param hsr the servlet request\n * @return the cluster user information\n */\n@Override\npublic ClusterUserInfo getClusterUserInfo(HttpServletRequest hsr) {\n try {\n long startTime = Time.now();\n Collection subClustersActive = federationFacade.getActiveSubClusters();\n final HttpServletRequest hsrCopy = clone(hsr);\n Class[] argsClasses = new Class[] { HttpServletRequest.class };\n Object[] args = new Object[] { hsrCopy };\n ClientMethod remoteMethod = new ClientMethod(\"getClusterUserInfo\", argsClasses, args);\n Map subClusterInfoMap = invokeConcurrent(subClustersActive, remoteMethod, ClusterUserInfo.class);\n FederationClusterUserInfo federationClusterUserInfo = new FederationClusterUserInfo();\n subClusterInfoMap.forEach((subClusterInfo, clusterUserInfo) -> {\n SubClusterId subClusterId = subClusterInfo.getSubClusterId();\n clusterUserInfo.setSubClusterId(subClusterId.getId());\n federationClusterUserInfo.getList().add(clusterUserInfo);\n });\n long stopTime = Time.now();\n RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_CLUSTERUSERINFO, TARGET_WEB_SERVICE);\n routerMetrics.succeededGetClusterUserInfoRetrieved(stopTime - startTime);\n return federationClusterUserInfo;\n } catch (NotFoundException e) {\n routerMetrics.incrGetClusterUserInfoFailedRetrieved();\n RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTERUSERINFO, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage());\n RouterServerUtil.logAndThrowRunTimeException(\"Get all active sub cluster(s) error.\", e);\n } catch (YarnException | IOException e) {\n routerMetrics.incrGetClusterUserInfoFailedRetrieved();\n RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTERUSERINFO, UNKNOWN, TARGET_WEB_SERVICE, e.getLocalizedMessage());\n RouterServerUtil.logAndThrowRunTimeException(\"getClusterUserInfo error.\", e);\n }\n routerMetrics.incrGetClusterUserInfoFailedRetrieved();\n RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_CLUSTERUSERINFO, UNKNOWN, TARGET_WEB_SERVICE, \"getClusterUserInfo error.\");\n throw new RuntimeException(\"getClusterUserInfo error.\");\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Checks if this connection information object fits to the URI.\n *\n * @param uri The URI to check against\n * @throws Exception If something is incompatible\n */\n@Override\npublic void fitsToURI(final URI uri) throws Exception {\n final RemoteFileHandler fileHandler = RemoteFileHandlerRegistry.getRemoteFileHandler(getProtocol());\n if (fileHandler == null) {\n throw new Exception(\"No file handler found for protocol: \" + getProtocol());\n }\n final String scheme = uri.getScheme().toLowerCase();\n final Protocol[] protocols = fileHandler.getSupportedProtocols();\n boolean supportedProtocol = false;\n for (final Protocol protocol : protocols) {\n if (protocol.getName().equals(scheme)) {\n supportedProtocol = true;\n break;\n }\n }\n if (!supportedProtocol) {\n throw new Exception(\"Protocol \" + scheme + \" incompatible with connection information protcol \" + getProtocol());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "private void replayEventsOverResultSet(QueryResult queryResult) throws Exception{\r\n Map> future = readAccumulators();\r\n for (Map.Entry> entry : future.entrySet()) {\r\n int partitionId = entry.getKey();\r\n Object eventsInOneAcc = entry.getValue().get();\r\n if (eventsInOneAcc == null) {\r\n continue;\r\n }\r\n eventsInOneAcc = getContext().toObject(eventsInOneAcc);\r\n List eventDataList = (List) eventsInOneAcc;\r\n for (QueryCacheEventData eventData : eventDataList) {\r\n if (eventData.getDataKey() == null) {\r\n removePartitionResults(queryResult, partitionId);\r\n } else {\r\n add(queryResult, newQueryResultRow(eventData));\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Long executeSQL(JobId jobId, String translatedQuery, Map queryParameters) throws Exception{\r\n QueryJobConfiguration.Builder builder = QueryJobConfiguration.newBuilder(translatedQuery).setUseLegacySql(false);\r\n setQueryParameters(queryParameters, builder);\r\n QueryJobConfiguration queryJobConfiguration = builder.build();\r\n try {\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Sending query to bigquery standard sql: {}\", translatedQuery);\r\n }\r\n JobId queryJobId;\r\n if (ObjectHelper.isNotEmpty(jobId)) {\r\n queryJobId = jobId;\r\n } else {\r\n queryJobId = JobId.of(configuration.getProjectId(), UUID.randomUUID().toString());\r\n }\r\n Job job = bigquery.create(JobInfo.of(queryJobId, queryJobConfiguration)).waitFor();\r\n JobStatistics.QueryStatistics statistics = job.getStatistics();\r\n TableResult result = job.getQueryResults();\r\n Long numAffectedRows = statistics.getNumDmlAffectedRows();\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Query {} - Affected rows {} - Result {}\", translatedQuery, numAffectedRows, result);\r\n }\r\n if (numAffectedRows != null) {\r\n return numAffectedRows;\r\n }\r\n return result.getTotalRows();\r\n } catch (JobException e) {\r\n throw new Exception(\"Query \" + translatedQuery + \" failed: \" + e.getErrors(), e);\r\n } catch (BigQueryException e) {\r\n throw new Exception(\"Query \" + translatedQuery + \" failed: \" + e.getError(), e);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void commitIfNeeded(Session session, Message message) throws Exception{\r\n try {\r\n if (session.getTransacted()) {\r\n SjmsHelper.commitIfNecessary(session);\r\n } else if (message != null && session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {\r\n message.acknowledge();\r\n }\r\n } catch (jakarta.jms.TransactionInProgressException | jakarta.jms.IllegalStateException ex) {\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "static Runnable unchecked(ThrowingRunnable r) {\n return () -> {\n try {\n r.run();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n };\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected ReplyManager createReplyManager(String replyTo) throws Exception{\r\n ReplyManager replyManager = new QueueReplyManager(getEndpoint().getCamelContext());\r\n replyManager.setEndpoint(getEndpoint());\r\n String name = \"JmsReplyManagerTimeoutChecker[\" + replyTo + \"]\";\r\n ScheduledExecutorService replyManagerScheduledExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(name, name);\r\n replyManager.setScheduledExecutorService(replyManagerScheduledExecutorService);\r\n name = \"JmsReplyManagerOnTimeout[\" + replyTo + \"]\";\r\n int max = getEndpoint().getReplyToOnTimeoutMaxConcurrentConsumers();\r\n if (max <= 0) {\r\n throw new IllegalArgumentException(\"The option replyToOnTimeoutMaxConcurrentConsumers must be >= 1\");\r\n }\r\n ExecutorService replyManagerExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newThreadPool(replyManager, name, 0, max);\r\n replyManager.setOnTimeoutExecutorService(replyManagerExecutorService);\r\n ServiceHelper.startService(replyManager);\r\n return replyManager;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Fire on one or more of the specified events with the provided subject.\n *\n * @param eventSubject The subject to pass in the event\n * @param all Set to true if you want to fire on all the given eventIds. Use false if you only\n * want to stop after you found the first registered listener\n * @param eventIds The event IDs to look up\n * @param The type of the event subject\n * @throws HopException In case something goes wrong executing the listener lambdas.\n */\npublic void fire(T eventSubject, boolean all, String... eventIds) throws HopException {\n if (eventIds == null || eventIds.length == 0) {\n throw new RuntimeException(\"Please provide the IDs of the events you want to fire\");\n }\n for (String eventId : eventIds) {\n if (StringUtils.isEmpty(eventId)) {\n throw new RuntimeException(CONST_PLEASE_ONLY_USE_EVENT_IDS_WHICH_ARE_NOT_NULL_OR_EMPTY);\n }\n }\n // Execute the listeners for the given event IDs in all the parts of the GUI\n //\n for (Map eventListenerMap : guiEventListenerMap.values()) {\n for (String eventId : eventIds) {\n IHopGuiEventListener listener = eventListenerMap.get(eventId);\n if (listener != null) {\n // We found the listener for the event ID! Fire it!\n //\n listener.event(new HopGuiEvent<>(eventId, eventSubject));\n if (!all) {\n // Only execute once per GUI component\n break;\n }\n }\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public static CommandArgs emptyArgs(final Implementation impl) throws Exception{\r\n if (!IdRepoImplementationType.COMMAND.equals(impl.getType())) {\r\n throw new IllegalArgumentException(\"This method can be only called on implementations\");\r\n }\r\n Class commandClass = getClass(impl).getLeft();\r\n Class commandArgsClass = findCommandArgsClass(commandClass);\r\n if (commandArgsClass != null && (commandArgsClass.getEnclosingClass() == null || Modifier.isStatic(commandArgsClass.getModifiers()))) {\r\n return commandArgsClass.getDeclaredConstructor().newInstance();\r\n }\r\n throw new IllegalArgumentException(CommandArgs.class.getName() + \" shall be either declared as independent or nested static\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static ClosableIterator createSecondaryIndexGenerator(HoodieTableMetaClient metaClient, EngineType engineType, List logFilePaths, Schema tableSchema, String partition, Option dataFilePath, HoodieIndexDefinition indexDefinition, String instantTime) throws Exception {\n final String basePath = metaClient.getBasePath().toString();\n final StorageConfiguration storageConf = metaClient.getStorageConf();\n HoodieRecordMerger recordMerger = HoodieRecordUtils.createRecordMerger(basePath, engineType, Collections.emptyList(), metaClient.getTableConfig().getRecordMergeStrategyId());\n HoodieMergedLogRecordScanner mergedLogRecordScanner = HoodieMergedLogRecordScanner.newBuilder().withStorage(metaClient.getStorage()).withBasePath(metaClient.getBasePath()).withLogFilePaths(logFilePaths).withReaderSchema(tableSchema).withLatestInstantTime(instantTime).withReverseReader(false).withMaxMemorySizeInBytes(storageConf.getLong(MAX_MEMORY_FOR_COMPACTION.key(), DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES)).withBufferSize(HoodieMetadataConfig.MAX_READER_BUFFER_SIZE_PROP.defaultValue()).withSpillableMapBasePath(FileIOUtils.getDefaultSpillableMapBasePath()).withPartition(partition).withOptimizedLogBlocksScan(storageConf.getBoolean(\"hoodie\" + HoodieMetadataConfig.OPTIMIZED_LOG_BLOCKS_SCAN, false)).withDiskMapType(storageConf.getEnum(SPILLABLE_DISK_MAP_TYPE.key(), SPILLABLE_DISK_MAP_TYPE.defaultValue())).withBitCaskDiskMapCompressionEnabled(storageConf.getBoolean(DISK_MAP_BITCASK_COMPRESSION_ENABLED.key(), DISK_MAP_BITCASK_COMPRESSION_ENABLED.defaultValue())).withRecordMerger(recordMerger).withTableMetaClient(metaClient).build();\n Option baseFileReader = Option.empty();\n if (dataFilePath.isPresent()) {\n baseFileReader = Option.of(HoodieIOFactory.getIOFactory(metaClient.getStorage()).getReaderFactory(recordMerger.getRecordType()).getFileReader(getReaderConfigs(storageConf), dataFilePath.get()));\n }\n HoodieFileSliceReader fileSliceReader = new HoodieFileSliceReader(baseFileReader, mergedLogRecordScanner, tableSchema, metaClient.getTableConfig().getPreCombineField(), recordMerger, metaClient.getTableConfig().getProps(), Option.empty());\n ClosableIterator fileSliceIterator = ClosableIterator.wrap(fileSliceReader);\n return new ClosableIterator() {\n\n private HoodieRecord nextValidRecord;\n\n @Override\n public void close() {\n fileSliceIterator.close();\n }\n\n @Override\n public boolean hasNext() {\n // As part of hasNext() we try to find the valid non-delete record that has a secondary key.\n if (nextValidRecord != null) {\n return true;\n }\n // Secondary key is null when there is a delete record, and we only have the record key.\n // This can happen when the record is deleted in the log file.\n // In this case, we need not index the record because for the given record key,\n // we have already prepared the delete record before reaching this point.\n // NOTE: Delete record should not happen when initializing the secondary index i.e. when called from readSecondaryKeysFromFileSlices,\n // because from that call, we get the merged records as of some committed instant. So, delete records must have been filtered out.\n // Loop to find the next valid record or exhaust the iterator.\n while (fileSliceIterator.hasNext()) {\n HoodieRecord record = fileSliceIterator.next();\n String secondaryKey = getSecondaryKey(record);\n if (secondaryKey != null) {\n nextValidRecord = HoodieMetadataPayload.createSecondaryIndexRecord(record.getRecordKey(tableSchema, HoodieRecord.RECORD_KEY_METADATA_FIELD), secondaryKey, indexDefinition.getIndexName(), false);\n return true;\n }\n }\n // If no valid records are found\n return false;\n }\n\n @Override\n public HoodieRecord next() {\n if (!hasNext()) {\n throw new NoSuchElementException(\"No more valid records available.\");\n }\n HoodieRecord result = nextValidRecord;\n // Reset for the next call\n nextValidRecord = null;\n return result;\n }\n\n private String getSecondaryKey(HoodieRecord record) {\n try {\n if (record.toIndexedRecord(tableSchema, CollectionUtils.emptyProps()).isPresent()) {\n GenericRecord genericRecord = (GenericRecord) (record.toIndexedRecord(tableSchema, CollectionUtils.emptyProps()).get()).getData();\n String secondaryKeyFields = String.join(\".\", indexDefinition.getSourceFields());\n return HoodieAvroUtils.getNestedFieldValAsString(genericRecord, secondaryKeyFields, true, false);\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to fetch records: \" + e);\n }\n return null;\n }\n };\n}", "smellKey": "S112", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "protected Object doInvoke(final Method method, final Exchange exchange) throws Throwable{\r\n final boolean isFuture = method.getReturnType() == Future.class;\r\n FutureTask task = new FutureTask<>(new Callable() {\r\n\r\n public Object call() throws Exception {\r\n LOG.trace(\"Proxied method call {} invoking producer: {}\", method.getName(), producer);\r\n producer.process(exchange);\r\n Object answer = afterInvoke(method, exchange, isFuture);\r\n LOG.trace(\"Proxied method call {} returning: {}\", method.getName(), answer);\r\n return answer;\r\n }\r\n });\r\n if (isFuture) {\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Submitting task for exchange id {}\", exchange.getExchangeId());\r\n }\r\n getExecutorService(exchange.getContext()).submit(task);\r\n return task;\r\n } else {\r\n try {\r\n task.run();\r\n return task.get();\r\n } catch (ExecutionException e) {\r\n throw e.getCause();\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void cleanupResources() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean handle(ServerConfiguration conf, SanityFlags cmdFlags) throws Exception{\r\n try {\r\n return handleAsync(conf, cmdFlags).get();\r\n } catch (Exception e) {\r\n LOG.warn(\"Error in bookie sanity test\", e);\r\n return false;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "// We provide this public method to help EXPLAIN VECTORIZATION show the evaluator classes.\npublic static VectorPTFEvaluatorBase getEvaluator(SupportedFunctionType functionType, boolean isDistinct, WindowFrameDef windowFrameDef, Type[] columnVectorTypes, VectorExpression[] inputVectorExpressions, int outputColumnNum) {\n final boolean isRowEndCurrent = (windowFrameDef.getWindowType() == WindowType.ROWS && windowFrameDef.getEnd().isCurrentRow());\n /*\n * we should only stream when the window start is unbounded and the end row is the current,\n * because that's the way how streaming evaluation works: calculate from the very-first row then\n * create result for the current row on the fly, so with other words: currently we cannot force\n * a boundary on a streaming evaluator\n */\n final boolean canStream = windowFrameDef.getStart().isUnbounded() && isRowEndCurrent;\n // most of the evaluators will use only first argument\n VectorExpression inputVectorExpression = inputVectorExpressions[0];\n Type columnVectorType = columnVectorTypes[0];\n VectorPTFEvaluatorBase evaluator;\n switch(functionType) {\n case ROW_NUMBER:\n evaluator = new VectorPTFEvaluatorRowNumber(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case RANK:\n evaluator = new VectorPTFEvaluatorRank(windowFrameDef, outputColumnNum);\n break;\n case DENSE_RANK:\n evaluator = new VectorPTFEvaluatorDenseRank(windowFrameDef, outputColumnNum);\n break;\n case MIN:\n switch(columnVectorType) {\n case LONG:\n evaluator = !canStream ? new VectorPTFEvaluatorLongMin(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingLongMin(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = !canStream ? new VectorPTFEvaluatorDoubleMin(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDoubleMin(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = !canStream ? new VectorPTFEvaluatorDecimalMin(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDecimalMin(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case MAX:\n switch(columnVectorType) {\n case LONG:\n evaluator = !canStream ? new VectorPTFEvaluatorLongMax(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingLongMax(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = !canStream ? new VectorPTFEvaluatorDoubleMax(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDoubleMax(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = !canStream ? new VectorPTFEvaluatorDecimalMax(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDecimalMax(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case SUM:\n switch(columnVectorType) {\n case LONG:\n evaluator = !canStream ? new VectorPTFEvaluatorLongSum(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingLongSum(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = !canStream ? new VectorPTFEvaluatorDoubleSum(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDoubleSum(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = !canStream ? new VectorPTFEvaluatorDecimalSum(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDecimalSum(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case AVG:\n switch(columnVectorType) {\n case LONG:\n evaluator = !canStream ? new VectorPTFEvaluatorLongAvg(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingLongAvg(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = !canStream ? new VectorPTFEvaluatorDoubleAvg(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDoubleAvg(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = !canStream ? new VectorPTFEvaluatorDecimalAvg(windowFrameDef, inputVectorExpression, outputColumnNum) : new VectorPTFEvaluatorStreamingDecimalAvg(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case FIRST_VALUE:\n switch(columnVectorType) {\n case LONG:\n evaluator = new VectorPTFEvaluatorLongFirstValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = new VectorPTFEvaluatorDoubleFirstValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = new VectorPTFEvaluatorDecimalFirstValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case LAST_VALUE:\n switch(columnVectorType) {\n case LONG:\n evaluator = new VectorPTFEvaluatorLongLastValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = new VectorPTFEvaluatorDoubleLastValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = new VectorPTFEvaluatorDecimalLastValue(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case COUNT:\n if (inputVectorExpression == null) {\n evaluator = new VectorPTFEvaluatorCountStar(windowFrameDef, inputVectorExpression, outputColumnNum);\n } else {\n if (isDistinct) {\n switch(columnVectorType) {\n case BYTES:\n evaluator = new VectorPTFEvaluatorBytesCountDistinct(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n //Decimal64ColumnVector is a LongColumnVector\n case DECIMAL_64:\n case LONG:\n evaluator = new VectorPTFEvaluatorLongCountDistinct(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DOUBLE:\n evaluator = new VectorPTFEvaluatorDoubleCountDistinct(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case DECIMAL:\n evaluator = new VectorPTFEvaluatorDecimalCountDistinct(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n case TIMESTAMP:\n evaluator = new VectorPTFEvaluatorTimestampCountDistinct(windowFrameDef, inputVectorExpression, outputColumnNum);\n break;\n default:\n throw new RuntimeException(\"Unexpected column type for ptf count distinct: \" + columnVectorType);\n }\n } else {\n evaluator = new VectorPTFEvaluatorCount(windowFrameDef, inputVectorExpression, outputColumnNum);\n }\n }\n break;\n case LAG:\n // lag(column, constant, ...)\n int amt = inputVectorExpressions.length > 1 ? (int) ((ConstantVectorExpression) inputVectorExpressions[1]).getLongValue() : 1;\n // lag(column, constant, constant/column)\n VectorExpression defaultValueExpression = inputVectorExpressions.length > 2 ? inputVectorExpressions[2] : null;\n switch(columnVectorType) {\n case LONG:\n case DOUBLE:\n case DECIMAL:\n evaluator = new VectorPTFEvaluatorLag(windowFrameDef, inputVectorExpression, outputColumnNum, columnVectorType, amt, defaultValueExpression);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n case LEAD:\n // lead(column, constant, ...)\n amt = inputVectorExpressions.length > 1 ? (int) ((ConstantVectorExpression) inputVectorExpressions[1]).getLongValue() : 1;\n // lead(column, constant, constant/column)\n defaultValueExpression = inputVectorExpressions.length > 2 ? inputVectorExpressions[2] : null;\n switch(columnVectorType) {\n case LONG:\n case DOUBLE:\n case DECIMAL:\n evaluator = new VectorPTFEvaluatorLead(windowFrameDef, inputVectorExpression, outputColumnNum, columnVectorType, amt, defaultValueExpression);\n break;\n default:\n throw new RuntimeException(\"Unexpected column vector type \" + columnVectorType + \" for \" + functionType);\n }\n break;\n default:\n throw new RuntimeException(\"Unexpected function type \" + functionType);\n }\n return evaluator;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected static ConsoleApp create() throws Exception{\r\n Config config = Config.load();\r\n for (int i = 1; i <= LOAD_EXECUTORS_COUNT; i++) {\r\n config.addExecutorConfig(new ExecutorConfig(EXECUTOR_NAMESPACE + \" \" + i).setPoolSize(i));\r\n }\r\n HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);\r\n return new ConsoleApp(instance, System.out);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Object newInstance(String className, Class[] parameterTypes, Object... parameterValues) throws Exception{\r\n Class targetType = Class.forName(className);\r\n Constructor constructor = targetType.getConstructor(parameterTypes);\r\n return constructor.newInstance(parameterValues);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Object deserialize(S3LogStruct c, String row) throws Exception{\r\n Matcher match = regexpat.matcher(row);\r\n int t = 1;\r\n try {\r\n match.matches();\r\n c.bucketowner = match.group(t++);\r\n c.bucketname = match.group(t++);\r\n } catch (Exception e) {\r\n throw new SerDeException(\"S3 Log Regex did not match:\" + row, e);\r\n }\r\n c.rdatetime = match.group(t++);\r\n c.rip = match.group(t++);\r\n c.requester = match.group(t++);\r\n c.requestid = match.group(t++);\r\n c.operation = match.group(t++);\r\n c.rkey = match.group(t++);\r\n c.requesturi = match.group(t++);\r\n c.httpstatus = toInt(match.group(t++));\r\n c.errorcode = match.group(t++);\r\n c.bytessent = toInt(match.group(t++));\r\n c.objsize = toInt(match.group(t++));\r\n c.totaltime = toInt(match.group(t++));\r\n c.turnaroundtime = toInt(match.group(t++));\r\n c.referer = match.group(t++);\r\n c.useragent = match.group(t++);\r\n return (c);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `title` to the URL query string\n if (getTitle() != null) {\n try {\n joiner.add(String.format(\"%stitle%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getTitle()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `status` to the URL query string\n if (getStatus() != null) {\n try {\n joiner.add(String.format(\"%sstatus%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getStatus()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `detail` to the URL query string\n if (getDetail() != null) {\n try {\n joiner.add(String.format(\"%sdetail%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDetail()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `instance` to the URL query string\n if (getInstance() != null) {\n try {\n joiner.add(String.format(\"%sinstance%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getInstance()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `code` to the URL query string\n if (getCode() != null) {\n try {\n joiner.add(String.format(\"%scode%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getCode()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `mainDiagnosisCode` to the URL query string\n if (getMainDiagnosisCode() != null) {\n try {\n joiner.add(String.format(\"%smainDiagnosisCode%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getMainDiagnosisCode()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `detailedDiagnosisCode` to the URL query string\n if (getDetailedDiagnosisCode() != null) {\n try {\n joiner.add(String.format(\"%sdetailedDiagnosisCode%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDetailedDiagnosisCode()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `dynamicDescription` to the URL query string\n if (getDynamicDescription() != null) {\n try {\n joiner.add(String.format(\"%sdynamicDescription%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDynamicDescription()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `severity` to the URL query string\n if (getSeverity() != null) {\n try {\n joiner.add(String.format(\"%sseverity%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getSeverity()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `links` to the URL query string\n if (getLinks() != null) {\n for (int i = 0; i < getLinks().size(); i++) {\n if (getLinks().get(i) != null) {\n try {\n joiner.add(String.format(\"%slinks%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getLinks().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n }\n // add `moreInfo` to the URL query string\n if (getMoreInfo() != null) {\n for (String _key : getMoreInfo().keySet()) {\n try {\n joiner.add(String.format(\"%smoreInfo%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, _key, containerSuffix), getMoreInfo().get(_key), URLEncoder.encode(String.valueOf(getMoreInfo().get(_key)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public static String getPidsStr(int processId) throws Exception{\r\n List pidList = new ArrayList<>();\r\n Matcher mat = null;\r\n if (SystemUtils.IS_OS_MAC) {\r\n String pids = OSUtils.exeCmd(String.format(\"%s -sp %d\", Constants.PSTREE, processId));\r\n if (null != pids) {\r\n mat = MACPATTERN.matcher(pids);\r\n }\r\n } else {\r\n String pids = OSUtils.exeCmd(String.format(\"%s -p %d\", Constants.PSTREE, processId));\r\n if (null != pids) {\r\n mat = WINDOWSATTERN.matcher(pids);\r\n }\r\n }\r\n if (null != mat) {\r\n while (mat.find()) {\r\n pidList.add(mat.group(1));\r\n }\r\n }\r\n if (OSUtils.isSudoEnable() && !pidList.isEmpty()) {\r\n pidList = pidList.subList(1, pidList.size());\r\n }\r\n return String.join(\" \", pidList).trim();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nvoid close() {\n // check if there are IOExceptions\n if (!isAborted()) {\n setAborted(execContext.getIoCxt().getIOExceptions());\n }\n if (cache != null) {\n for (String k : cacheKeys) {\n cache.release(k);\n }\n }\n if (dynamicValueCache != null) {\n for (String k : dynamicValueCacheKeys) {\n dynamicValueCache.release(k);\n }\n }\n // detecting failed executions by exceptions thrown by the operator tree\n try {\n if (mapOp == null || mapWork == null) {\n return;\n }\n boolean abort = isAborted();\n mapOp.close(abort);\n if (mergeMapOpList.isEmpty() == false) {\n for (AbstractMapOperator mergeMapOp : mergeMapOpList) {\n mergeMapOp.close(abort);\n }\n }\n // Need to close the dummyOps as well. The operator pipeline\n // is not considered \"closed/done\" unless all operators are\n // done. For broadcast joins that includes the dummy parents.\n List dummyOps = mapWork.getDummyOps();\n if (dummyOps != null) {\n for (Operator dummyOp : dummyOps) {\n dummyOp.close(abort);\n }\n }\n ReportStats rps = new ReportStats(reporter, jconf);\n mapOp.preorderMap(rps);\n return;\n } catch (Exception e) {\n if (!isAborted()) {\n // signal new failure to map-reduce\n LOG.error(\"Hit error while closing operators - failing tree\");\n throw new RuntimeException(\"Hive Runtime Error while closing operators\", e);\n }\n } finally {\n Utilities.clearWorkMap(jconf);\n MapredContext.close();\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected Registry createCamelRegistry() throws Exception{\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void initConf() throws Exception{\r\n if (QTestSystemProperties.isVectorizationEnabled()) {\r\n conf.setBoolVar(ConfVars.HIVE_VECTORIZATION_ENABLED, true);\r\n }\r\n conf.setVar(ConfVars.METASTORE_RAW_STORE_IMPL, \"org.apache.hadoop.hive.metastore.VerifyingObjectStore\");\r\n miniClusters.initConf(conf);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String getStringFromInputStream(InputStream in) throws Exception{\r\n CachedOutputStream bos = new CachedOutputStream();\r\n IOUtils.copy(in, bos);\r\n in.close();\r\n bos.close();\r\n return bos.getOut().toString();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void marshalUrlSafe(Exchange exchange, Object graph, OutputStream stream) throws Exception{\r\n byte[] decoded = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);\r\n Base64 codec = new Base64(lineLength, lineSeparator, true);\r\n byte[] encoded = codec.encode(decoded);\r\n stream.write(encoded);\r\n stream.flush();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private GoogleCredentials createFromFile() throws Exception{\r\n if (camelContext == null) {\r\n throw new CamelException(\"CamelContext is null, but must be set when creating GoogleBigQueryConnectionFactory.\");\r\n }\r\n try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, serviceAccountKeyFile)) {\r\n GoogleCredentials credentials = GoogleCredentials.fromStream(is);\r\n if (credentials.createScopedRequired()) {\r\n credentials = credentials.createScoped(BigqueryScopes.all());\r\n }\r\n return credentials;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleAddWanConfig(HttpPostCommand cmd) throws Throwable{\r\n String[] params = decodeParamsAndAuthenticate(cmd, 3);\r\n String wanConfigJson = params[2];\r\n WanReplicationConfigDTO dto = new WanReplicationConfigDTO(new WanReplicationConfig());\r\n dto.fromJson(Json.parse(wanConfigJson).asObject());\r\n AddWanConfigResult result = getNode().getNodeEngine().getWanReplicationService().addWanReplicationConfig(dto.getConfig());\r\n JsonObject res = response(SUCCESS, \"message\", \"WAN configuration added.\");\r\n res.add(\"addedPublisherIds\", Json.array(result.getAddedPublisherIds().toArray(new String[] {})));\r\n res.add(\"ignoredPublisherIds\", Json.array(result.getIgnoredPublisherIds().toArray(new String[] {})));\r\n prepareResponse(cmd, res);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String formatXml(Document xmlDocument) throws Exception{\r\n Transformer transformer = newSecureTransformerFactory().newTransformer();\r\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\r\n StreamResult result = new StreamResult(new StringWriter());\r\n DOMSource source = new DOMSource(xmlDocument);\r\n transformer.transform(source, result);\r\n try (Writer writer = result.getWriter()) {\r\n return writer.toString();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " boolean fire(Tablet tablet) throws Exception{\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private LongColumnVector toDateArray(VectorizedRowBatch batch, TypeInfo typeInfo, ColumnVector inputColVector, LongColumnVector dateVector) {\n PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();\n int size = batch.size;\n if (primitiveCategory == PrimitiveCategory.DATE) {\n return (LongColumnVector) inputColVector;\n }\n if (size > dateVector.vector.length) {\n if (dateVector1 == dateVector) {\n dateVector1 = new LongColumnVector(size * 2);\n dateVector = dateVector1;\n } else {\n dateVector2 = new LongColumnVector(size * 2);\n dateVector = dateVector2;\n }\n }\n switch(primitiveCategory) {\n case TIMESTAMP:\n TimestampColumnVector tcv = (TimestampColumnVector) inputColVector;\n copySelected(tcv, batch.selectedInUse, batch.selected, batch.size, dateVector);\n return dateVector;\n case STRING:\n case CHAR:\n case VARCHAR:\n BytesColumnVector bcv = (BytesColumnVector) inputColVector;\n copySelected(bcv, batch.selectedInUse, batch.selected, batch.size, dateVector);\n return dateVector;\n default:\n throw new Error(\"Unsupported input type \" + primitiveCategory.name());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic SituationReportResource updateSituationReport(SituationReportResource report, WebAdeAuthentication webAdeAuthentication, FactoryContext factoryContext) throws ValidationFailureException, ConflictException, NotFoundException, Exception {\n SituationReportResource response = null;\n long effectiveAsOfMillis = report.getCreatedTimestamp() == null ? System.currentTimeMillis() : report.getCreatedTimestamp().getTime();\n try {\n List errors = this.modelValidator.validateReport(report, effectiveAsOfMillis);\n if (!errors.isEmpty()) {\n throw new Exception(\"Validation failed for report: \" + errors.toString());\n }\n SituationReportResource currentReport = getSituationReport(report.getReportGuid(), factoryContext);\n if (currentReport != null) {\n SituationReportDto dto = new SituationReportDto(report);\n try {\n dto.setUpdateDate(new Date());\n if (dto.getCreateDate() == null)\n dto.setCreateDate(new Date());\n if (dto.getCreatedTimestamp() == null)\n dto.setCreatedTimestamp(new Date());\n if (webAdeAuthentication != null && webAdeAuthentication.getUserId() != null)\n dto.setUpdateUser(webAdeAuthentication.getUserId());\n if (webAdeAuthentication != null && webAdeAuthentication.getUserId() != null)\n dto.setCreateUser(webAdeAuthentication.getUserId());\n this.situationReportDao.update(dto);\n } catch (DaoException e) {\n throw new ServiceException(e.getMessage(), e);\n }\n SituationReportDto updatedDto = this.situationReportDao.fetch(dto.getReportGuid());\n response = this.situationReportFactory.getSituationReport(updatedDto, factoryContext);\n }\n } catch (IntegrityConstraintViolatedDaoException e) {\n throw new ConflictException(e.getMessage());\n } catch (NotFoundDaoException e) {\n throw new NotFoundException(e.getMessage());\n } catch (DaoException e) {\n throw new ServiceException(e.getMessage(), e);\n } catch (Exception e) {\n throw new Exception(e.getMessage(), e);\n }\n logger.debug(\">updateSituationReport\");\n return response;\n}", "smellKey": "S112", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "private Path readResourceAsPath(final String path) throws Exception{\r\n return Path.of(Objects.requireNonNull(this.getClass().getResource(path)).toURI());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Long executeSQL(JobId jobId, String translatedQuery, Map queryParameters) throws Exception {\n QueryJobConfiguration.Builder builder = QueryJobConfiguration.newBuilder(translatedQuery).setUseLegacySql(false);\n setQueryParameters(queryParameters, builder);\n QueryJobConfiguration queryJobConfiguration = builder.build();\n try {\n if (LOG.isTraceEnabled()) {\n LOG.trace(\"Sending query to bigquery standard sql: {}\", translatedQuery);\n }\n JobId queryJobId;\n if (ObjectHelper.isNotEmpty(jobId)) {\n queryJobId = jobId;\n } else {\n queryJobId = JobId.of(configuration.getProjectId(), UUID.randomUUID().toString());\n }\n Job job = bigquery.create(JobInfo.of(queryJobId, queryJobConfiguration)).waitFor();\n JobStatistics.QueryStatistics statistics = job.getStatistics();\n TableResult result = job.getQueryResults();\n Long numAffectedRows = statistics.getNumDmlAffectedRows();\n if (LOG.isTraceEnabled()) {\n LOG.trace(\"Query {} - Affected rows {} - Result {}\", translatedQuery, numAffectedRows, result);\n }\n //numAffectedRows is present only for DML statements INSERT, UPDATE or DELETE.\n if (numAffectedRows != null) {\n return numAffectedRows;\n }\n //in other cases (SELECT), the number of affected rows is returned\n return result.getTotalRows();\n } catch (JobException e) {\n throw new Exception(\"Query \" + translatedQuery + \" failed: \" + e.getErrors(), e);\n } catch (BigQueryException e) {\n throw new Exception(\"Query \" + translatedQuery + \" failed: \" + e.getError(), e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "@Override\npublic List listTables(Namespace namespace) {\n Preconditions.checkArgument(isValidateNamespace(namespace), \"Missing database in namespace: %s\", namespace);\n String database = namespace.level(0);\n try {\n List tableNames = clients.run(client -> client.getAllTables(database));\n List tableIdentifiers;\n if (listAllTables) {\n tableIdentifiers = tableNames.stream().map(t -> TableIdentifier.of(namespace, t)).collect(Collectors.toList());\n } else {\n tableIdentifiers = listIcebergTables(tableNames, namespace, BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE);\n }\n LOG.debug(\"Listing of namespace: {} resulted in the following tables: {}\", namespace, tableIdentifiers);\n return tableIdentifiers;\n } catch (UnknownDBException e) {\n throw new NoSuchNamespaceException(\"Namespace does not exist: %s\", namespace);\n } catch (TException e) {\n throw new RuntimeException(\"Failed to list all tables under namespace \" + namespace, e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new RuntimeException(\"Interrupted in call to listTables\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private DbType getCurrentDbType(DataSource dataSource) throws Exception{\r\n try (Connection conn = dataSource.getConnection()) {\r\n String name = conn.getMetaData().getDatabaseProductName().toUpperCase();\r\n return DbType.valueOf(name);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " Connection openConnection(String connStr) throws Exception{\r\n String driver = \"org.apache.hadoop.hive.jdbc.HiveDriver\";\r\n StringBuilder url = new StringBuilder();\r\n String usr = \"\";\r\n String pwd = \"\";\r\n if (connStr != null) {\r\n String[] c = connStr.split(\";\");\r\n if (c.length >= 1) {\r\n driver = c[0];\r\n }\r\n if (c.length >= 2) {\r\n url.append(c[1]);\r\n } else {\r\n url.append(\"jdbc:hive://\");\r\n }\r\n for (int i = 2; i < c.length; i++) {\r\n if (c[i].contains(\"=\")) {\r\n url.append(\";\");\r\n url.append(c[i]);\r\n } else if (usr.isEmpty()) {\r\n usr = c[i];\r\n } else if (pwd.isEmpty()) {\r\n pwd = c[i];\r\n }\r\n }\r\n }\r\n Class.forName(driver);\r\n timer.start();\r\n Connection conn = DriverManager.getConnection(url.toString().trim(), usr, pwd);\r\n timer.stop();\r\n if (info) {\r\n exec.info(null, \"Open connection: \" + url + \" (\" + timer.format() + \")\");\r\n }\r\n return conn;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " List getLocations() throws Exception{\r\n if (isOld) {\r\n return Arrays.asList(oldSplit.getLocations());\r\n } else {\r\n return Arrays.asList(newSplit.getLocations());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String doMessage(String msg) throws Exception{\r\n String resp = \"\";\r\n try (Socket echoSocket = new Socket(this.host, this.port)) {\r\n try (PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true)) {\r\n try (BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()))) {\r\n out.println(msg);\r\n resp = in.readLine();\r\n }\r\n }\r\n } catch (IOException e) {\r\n throw new Exception(\"Unable to send message to ChatScript Server. Reason:\" + e.getMessage(), e);\r\n }\r\n return resp;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ProcessElement\npublic void processElement(ProcessContext processContext) {\n try {\n HopRow hopRow = processContext.element();\n readCounter.inc();\n try {\n String string = rowMeta.getString(hopRow.getRow(), fieldIndex);\n processContext.output(string);\n outputCounter.inc();\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to pass string\", e);\n }\n } catch (Exception e) {\n numErrors.inc();\n LOG.error(\"Error in pub/sub publish messages function\", e);\n throw new RuntimeException(\"Error in pub/sub publish messages function\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public BeregningsresultatEntitet beregnYtelse(BehandlingReferanse referanse) {\n // Map til regelmodell\n var regelmodell = mapBeregningsresultatFraVLTilRegel.mapFra(referanse);\n // Verifiser input til regel\n if (andelerIBeregningM\u00e5LiggeIUttak(referanse)) {\n BeregningsresultatInputVerifiserer.verifiserAlleAndelerIBeregningErIUttak(regelmodell);\n } else {\n BeregningsresultatInputVerifiserer.verifiserAndelerIUttakLiggerIBeregning(regelmodell);\n }\n // Kalle regeltjeneste\n var beregningsresultat = fastsettBeregningsresultat(regelmodell);\n // Verifiser beregningsresultat\n try {\n BeregningsresultatOutputVerifiserer.verifiserOutput(beregningsresultat);\n } catch (Exception e) {\n log(regelmodell);\n throw new RuntimeException(\"Validering av beregningsresultat feilet\", e);\n }\n return beregningsresultat;\n}", "smellKey": "S112", "smellId": null, "repo": "navikt_fp-sak", "language": "java"} {"function": " void waitForFinish() throws Exception{\r\n for (Map.Entry> task : tasks.entrySet()) {\r\n long t1 = System.nanoTime();\r\n task.getValue().get();\r\n long t2 = System.nanoTime();\r\n LOG.debug(task.getKey() + \" waited for \" + (t2 - t1) + \" ns\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create the thread monitoring the socket for inbound UDP requests.\n *\n * @param addr host address.\n * @param port host port.\n * @throws Exception if the UDP listener creation generates an error.\n */\npublic void addNIOUDP(final InetAddress addr, final int port) throws Exception {\n final DatagramChannel udpChannel = openUDPChannel(addr, port);\n executor.submit(new Callable() {\n\n @Override\n public Boolean call() throws Exception {\n try {\n serveNIOUDP(udpChannel, addr, port);\n } catch (Exception e) {\n LOG.error(\"Error initializing DNS UDP listener\", e);\n throw e;\n }\n return true;\n }\n });\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void setupClientSocketProtocol(MinaConfiguration configuration) throws Exception{\r\n boolean minaLogger = configuration.isMinaLogger();\r\n long timeout = configuration.getTimeout();\r\n List filters = configuration.getFilters();\r\n address = new InetSocketAddress(configuration.getHost(), configuration.getPort());\r\n final int processorCount = Runtime.getRuntime().availableProcessors() + 1;\r\n connector = new NioSocketConnector(processorCount);\r\n workerPool = createThreadPool(configuration);\r\n connector.getFilterChain().addLast(\"threadPool\", new ExecutorFilter(workerPool));\r\n if (minaLogger) {\r\n connector.getFilterChain().addLast(\"logger\", new LoggingFilter());\r\n }\r\n appendIoFiltersToChain(filters, connector.getFilterChain());\r\n if (configuration.getSslContextParameters() != null) {\r\n SslFilter filter = new SslFilter(configuration.getSslContextParameters().createSSLContext(getEndpoint().getCamelContext()));\r\n connector.getFilterChain().addFirst(\"sslFilter\", filter);\r\n }\r\n configureCodecFactory(\"MinaConsumer\", connector, configuration);\r\n connector.setConnectTimeoutMillis(timeout);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleListNodes(HttpPostCommand cmd) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n ClusterService clusterService = getNode().getClusterService();\r\n final String responseTxt = clusterService.getMembers().toString() + \"\\n\" + getNode().getBuildInfo().getVersion() + \"\\n\" + System.getProperty(\"java.version\");\r\n prepareResponse(cmd, response(SUCCESS, \"response\", responseTxt));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void createMessageListenerContainer() throws Exception{\r\n listenerContainer = getEndpoint().createMessageListenerContainer();\r\n getEndpoint().configureListenerContainer(listenerContainer, this);\r\n listenerContainer.setMessageListener(getEndpointMessageListener());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param topNodes Cache nodes.\n * @param topVer Topology version.\n * @param futId Future ID.\n * @param remapKeys Keys to remap.\n * @return Mapping.\n * @throws Exception If failed.\n */\nprivate Map mapUpdate(Collection topNodes, AffinityTopologyVersion topVer, Long futId, @Nullable Collection remapKeys, boolean mappingKnown) throws Exception {\n Iterator it = null;\n if (vals != null)\n it = vals.iterator();\n Iterator conflictPutValsIt = null;\n if (conflictPutVals != null)\n conflictPutValsIt = conflictPutVals.iterator();\n Iterator conflictRmvValsIt = null;\n if (conflictRmvVals != null)\n conflictRmvValsIt = conflictRmvVals.iterator();\n Map pendingMappings = U.newHashMap(topNodes.size());\n // Create mappings first, then send messages.\n for (Object key : keys) {\n if (key == null)\n throw new NullPointerException(\"Null key.\");\n Object val;\n GridCacheVersion conflictVer;\n long conflictTtl;\n long conflictExpireTime;\n if (vals != null) {\n val = it.next();\n conflictVer = null;\n conflictTtl = CU.TTL_NOT_CHANGED;\n conflictExpireTime = CU.EXPIRE_TIME_CALCULATE;\n if (val == null)\n throw new NullPointerException(\"Null value.\");\n } else if (conflictPutVals != null) {\n GridCacheDrInfo conflictPutVal = conflictPutValsIt.next();\n val = conflictPutVal.valueEx();\n conflictVer = conflictPutVal.version();\n conflictTtl = conflictPutVal.ttl();\n conflictExpireTime = conflictPutVal.expireTime();\n } else if (conflictRmvVals != null) {\n val = null;\n conflictVer = conflictRmvValsIt.next();\n conflictTtl = CU.TTL_NOT_CHANGED;\n conflictExpireTime = CU.EXPIRE_TIME_CALCULATE;\n } else {\n val = null;\n conflictVer = null;\n conflictTtl = CU.TTL_NOT_CHANGED;\n conflictExpireTime = CU.EXPIRE_TIME_CALCULATE;\n }\n if (val == null && op != GridCacheOperation.DELETE)\n continue;\n KeyCacheObject cacheKey = cctx.toCacheKeyObject(key);\n if (remapKeys != null && !remapKeys.contains(cacheKey))\n continue;\n if (op != TRANSFORM) {\n val = cctx.toCacheObject(val);\n if (op == CREATE || op == UPDATE)\n cctx.validateKeyAndValue(cacheKey, (CacheObject) val);\n } else\n val = EntryProcessorResourceInjectorProxy.wrap(cctx.kernalContext(), (EntryProcessor) val);\n List nodes = cctx.affinity().nodesByKey(cacheKey, topVer);\n if (F.isEmpty(nodes))\n throw new ClusterTopologyServerNotFoundException(\"Failed to map keys for cache \" + \"(all partition nodes left the grid).\");\n ClusterNode primary = nodes.get(0);\n boolean needPrimaryRes = !mappingKnown || primary.isLocal() || nearEnabled;\n UUID nodeId = primary.id();\n PrimaryRequestState mapped = pendingMappings.get(nodeId);\n if (mapped == null) {\n byte flags = GridNearAtomicAbstractUpdateRequest.flags(nearEnabled, topLocked, retval, mappingKnown, needPrimaryRes, skipStore, keepBinary, recovery);\n GridNearAtomicFullUpdateRequest req = new GridNearAtomicFullUpdateRequest(cctx.cacheId(), nodeId, futId, topVer, syncMode, op, expiryPlc, invokeArgs, filter, taskNameHash, flags, cctx.deploymentEnabled(), keys.size());\n mapped = new PrimaryRequestState(req, nodes, false);\n pendingMappings.put(nodeId, mapped);\n }\n if (mapped.req.initMappingLocally())\n mapped.addMapping(nodes);\n mapped.req.addUpdateEntry(cacheKey, val, conflictTtl, conflictExpireTime, conflictVer);\n }\n return pendingMappings;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public static void suppressing(Runnable r) throws Exception{\r\n suppressing(r, true, true);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param rest\n * URL for HTTPS POST method\n * @param rest\n * URL Parameters for HTTPS POST method\n * @return String\n * @throws Exception\n */\npublic static String doHttpSecureFormPost(final String url, final String urlParameters) throws Exception {\n byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);\n int postDataLength = postData.length;\n if (Strings.isNullOrEmpty(url)) {\n throw new Exception(\"service endpoint cannot be blank\");\n }\n URL serviceUrl = null;\n try {\n serviceUrl = new URL(url);\n } catch (MalformedURLException malformedURLException) {\n LOGGER.error(malformedURLException.getMessage());\n throw malformedURLException;\n }\n HttpsURLConnection.setDefaultSSLSocketFactory(CommonUtils.createNoSSLContext().getSocketFactory());\n HttpsURLConnection con = null;\n try {\n con = (HttpsURLConnection) serviceUrl.openConnection();\n con.setDoOutput(true);\n con.setInstanceFollowRedirects(false);\n con.setRequestMethod(\"POST\");\n con.setRequestProperty(CONTENT_TYPE, \"application/x-www-form-urlencoded\");\n con.setRequestProperty(\"cache-control\", \"no-cache\");\n con.setRequestProperty(\"Content-Length\", Integer.toString(postDataLength));\n DataOutputStream wr = new DataOutputStream(con.getOutputStream());\n wr.write(postData);\n } catch (IOException ioException) {\n LOGGER.error(ioException.getMessage());\n throw ioException;\n }\n StringBuilder response = new StringBuilder();\n if (con != null) {\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));\n String input;\n while ((input = br.readLine()) != null) {\n response.append(input);\n }\n br.close();\n con.disconnect();\n } catch (IOException ioException) {\n LOGGER.error(ioException.getMessage());\n throw ioException;\n }\n }\n return response.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "public WaitStrategy createWaitStrategyInstance() throws Exception{\r\n return waitStrategyClass.getConstructor().newInstance();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Exchange createExchange(ChannelHandlerContext ctx, Object message) throws Exception{\r\n Exchange exchange = consumer.createExchange(false);\r\n consumer.getEndpoint().updateMessageHeader(exchange.getIn(), ctx);\r\n NettyPayloadHelper.setIn(exchange, message);\r\n return exchange;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected SignedInfo createSignedInfo(XMLSignatureFactory fac, List refs) throws Exception{\r\n return fac.newSignedInfo(fac.newCanonicalizationMethod(getConfiguration().getCanonicalizationMethod().getAlgorithm(), (C14NMethodParameterSpec) getConfiguration().getCanonicalizationMethod().getParameterSpec()), getSignatureMethod(getConfiguration().getSignatureAlgorithm(), fac), refs);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void createConnection() throws Exception{\r\n synchronized (this.connectionLock) {\r\n if (this.connection == null) {\r\n Connection con = null;\r\n try {\r\n con = endpoint.getConnectionFactory().createConnection();\r\n String cid = clientId != null ? clientId : endpoint.getClientId();\r\n if (cid != null) {\r\n con.setClientID(cid);\r\n }\r\n con.setExceptionListener(this);\r\n } catch (JMSException e) {\r\n closeConnection(con);\r\n throw e;\r\n }\r\n this.connection = con;\r\n LOG.debug(\"Created JMS Connection\");\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Pair runZookeeperOnAnyPort(int basePort, File zkDir) throws Exception{\r\n final int maxRetries = 20;\r\n final int minPort = 1025;\r\n final int maxPort = 65535;\r\n ZooKeeperServerShim zks = null;\r\n int zkPort = basePort;\r\n boolean success = false;\r\n int retries = 0;\r\n while (!success) {\r\n try {\r\n LOG.info(\"zk trying to bind to port \" + zkPort);\r\n zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkDir);\r\n success = true;\r\n } catch (BindException be) {\r\n retries++;\r\n if (retries > maxRetries) {\r\n throw be;\r\n }\r\n zkPort++;\r\n if (zkPort > maxPort) {\r\n zkPort = minPort;\r\n }\r\n }\r\n }\r\n return Pair.of(zks, zkPort);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic boolean test(Map ctx) throws Exception {\n double salary = ThreadLocalRandom.current().nextDouble() * args.range() * 1000;\n double maxSalary = salary + 1000;\n Collection> entries = executeQuery(salary, maxSalary);\n for (Cache.Entry entry : entries) {\n PersonNoIndex p = (PersonNoIndex) entry.getValue();\n if (p.getSalary() < salary || p.getSalary() > maxSalary)\n throw new Exception(\"Invalid person retrieved [min=\" + salary + \", max=\" + maxSalary + \", person=\" + p + ']');\n }\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private byte[] readMimePart(InputStream mimePartStream) throws Exception{\r\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\r\n IOHelper.copyAndCloseInput(mimePartStream, bos);\r\n return bos.toByteArray();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Create an instance of the given class\n * @param className the name of the class\n * @return a dynamically created instance of the given class\n */\npublic static Object createInstance(String className) {\n Object retv = null;\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Class theFilterClass = Class.forName(className, true, classLoader);\n Constructor meth = theFilterClass.getDeclaredConstructor(argArray);\n meth.setAccessible(true);\n retv = meth.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return retv;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static V executeWithDeadline(Future future, long timeoutNanos) throws Exception{\r\n if (timeoutNanos <= 0) {\r\n if (future.isDone() || future.isCancelled()) {\r\n return retrieveValue(future);\r\n } else {\r\n throw new TimeoutException();\r\n }\r\n }\r\n return future.get(timeoutNanos, TimeUnit.NANOSECONDS);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "// Find the record identifier column (if there) and return a possibly new ObjectInspector that\n// will strain out the record id for the underlying writer.\nprivate ObjectInspector findRecId(ObjectInspector inspector, int rowIdColNum) {\n if (!(inspector instanceof StructObjectInspector)) {\n throw new RuntimeException(\"Serious problem, expected a StructObjectInspector, but got a \" + inspector.getClass().getName());\n }\n if (rowIdColNum < 0) {\n return inspector;\n } else {\n RecIdStrippingObjectInspector newInspector = new RecIdStrippingObjectInspector(inspector, rowIdColNum);\n recIdField = newInspector.getRecId();\n List fields = ((StructObjectInspector) recIdField.getFieldObjectInspector()).getAllStructFieldRefs();\n // Go by position, not field name, as field names aren't guaranteed. The order of fields\n // in RecordIdentifier is writeId, bucketId, rowId\n originalWriteIdField = fields.get(0);\n origWriteIdInspector = (LongObjectInspector) originalWriteIdField.getFieldObjectInspector();\n bucketField = fields.get(1);\n bucketInspector = (IntObjectInspector) bucketField.getFieldObjectInspector();\n rowIdField = fields.get(2);\n rowIdInspector = (LongObjectInspector) rowIdField.getFieldObjectInspector();\n recIdInspector = (StructObjectInspector) recIdField.getFieldObjectInspector();\n return newInspector;\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected void initializeChannel() throws Exception{\r\n NettyChannelBuilder channelBuilder;\r\n if (!ObjectHelper.isEmpty(configuration.getHost()) && !ObjectHelper.isEmpty(configuration.getPort())) {\r\n LOG.info(\"Creating channel to the remote gRPC server {}:{}\", configuration.getHost(), configuration.getPort());\r\n channelBuilder = NettyChannelBuilder.forAddress(configuration.getHost(), configuration.getPort());\r\n } else {\r\n throw new IllegalArgumentException(\"No connection properties (host or port) specified\");\r\n }\r\n if (configuration.getNegotiationType() == NegotiationType.TLS) {\r\n ObjectHelper.notNull(configuration.getKeyCertChainResource(), \"keyCertChainResource\");\r\n ObjectHelper.notNull(configuration.getKeyResource(), \"keyResource\");\r\n SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient().keyManager(ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getKeyCertChainResource()), ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getKeyResource()), configuration.getKeyPassword());\r\n if (ObjectHelper.isNotEmpty(configuration.getTrustCertCollectionResource())) {\r\n sslContextBuilder = sslContextBuilder.trustManager(ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getTrustCertCollectionResource()));\r\n }\r\n channelBuilder = channelBuilder.sslContext(GrpcSslContexts.configure(sslContextBuilder).build());\r\n }\r\n channel = channelBuilder.negotiationType(configuration.getNegotiationType()).flowControlWindow(configuration.getFlowControlWindow()).userAgent(configuration.getUserAgent()).maxInboundMessageSize(configuration.getMaxMessageSize()).intercept(configuration.getClientInterceptors()).build();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void addSuperTenantIdp() throws Exception {\n try {\n IdentityProvider identityProvider = new IdentityProvider();\n identityProvider.setIdentityProviderName(IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME);\n identityProvider.setHomeRealmId(IdentityUtil.getHostName());\n identityProvider.setPrimary(true);\n IdentityProviderManager.getInstance().addResidentIdP(identityProvider, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);\n } catch (Throwable e) {\n throw new Exception(\"Error when adding Resident Identity Provider entry for super tenant \", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "@Override\npublic void check() {\n if (windowSize <= 0) {\n throw new RuntimeException(String.format(\"Parameter windowSize(%d) should be positive.\", windowSize));\n }\n if (slidingStep <= 0) {\n throw new RuntimeException(String.format(\"Parameter slidingStep(%d) should be positive.\", slidingStep));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "@Override\npublic HCatRecord next() {\n try {\n return curRecReader.getCurrentValue();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Call this method from your application whenever you\n * want to dump the heap snapshot into a file.\n *\n * @param fileName name of the heap dump file\n * @param live flag that tells whether to dump\n * only the live objects\n */\npublic static void dumpHeap(String fileName, boolean live) {\n // initialize hotspot diagnostic MBean\n initHotspotMBean();\n File f = new File(fileName);\n if (f.exists())\n f.delete();\n try {\n hotspotMBean.dumpHeap(fileName, live);\n } catch (RuntimeException re) {\n throw re;\n } catch (Exception exp) {\n throw new RuntimeException(exp);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "@Override\nvoid init(MRTaskReporter mrReporter, Map inputs, Map outputs) throws Exception {\n perfLogger.perfLogBegin(CLASS_NAME, PerfLogger.TEZ_INIT_OPERATORS);\n super.init(mrReporter, inputs, outputs);\n checkAbortCondition();\n String key = processorContext.getTaskVertexName() + MAP_PLAN_KEY;\n cacheKeys.add(key);\n // create map and fetch operators\n if (!isInCompaction) {\n mapWork = cache.retrieve(key, () -> Utilities.getMapWork(jconf));\n } else {\n // During query-based compaction, we don't want to retrieve old MapWork from the cache, we want a new mapper\n // and new UDF validate_acid_sort_order instance for each bucket, otherwise validate_acid_sort_order will fail.\n mapWork = Utilities.getMapWork(jconf);\n }\n // TODO HIVE-14042. Cleanup may be required if exiting early.\n Utilities.setMapWork(jconf, mapWork);\n for (PartitionDesc part : mapWork.getAliasToPartnInfo().values()) {\n TableDesc tableDesc = part.getTableDesc();\n Utilities.copyJobSecretToTableProperties(tableDesc);\n }\n String prefixes = jconf.get(DagUtils.TEZ_MERGE_WORK_FILE_PREFIXES);\n if (prefixes != null) {\n mergeWorkList = new ArrayList<>();\n for (final String prefix : prefixes.split(\",\")) {\n if (prefix == null || prefix.isEmpty()) {\n continue;\n }\n key = processorContext.getTaskVertexName() + prefix;\n cacheKeys.add(key);\n checkAbortCondition();\n mergeWorkList.add((MapWork) cache.retrieve(key, () -> Utilities.getMergeWork(jconf, prefix)));\n }\n }\n MapredContext.init(true, new JobConf(jconf));\n ((TezContext) MapredContext.get()).setInputs(inputs);\n ((TezContext) MapredContext.get()).setTezProcessorContext(processorContext);\n // Update JobConf using MRInput, info like filename comes via this\n checkAbortCondition();\n legacyMRInput = getMRInput(inputs);\n if (legacyMRInput != null) {\n Configuration updatedConf = legacyMRInput.getConfigUpdates();\n if (updatedConf != null) {\n for (Entry entry : updatedConf) {\n jconf.set(entry.getKey(), entry.getValue());\n }\n }\n }\n checkAbortCondition();\n createOutputMap();\n // Start all the Outputs.\n for (Entry outputEntry : outputs.entrySet()) {\n LOG.debug(\"Starting Output: \" + outputEntry.getKey());\n outputEntry.getValue().start();\n ((TezKVOutputCollector) outMap.get(outputEntry.getKey())).initialize();\n }\n checkAbortCondition();\n try {\n CompilationOpContext runtimeCtx = new CompilationOpContext();\n if (mapWork.getVectorMode()) {\n mapOp = new VectorMapOperator(runtimeCtx);\n } else {\n mapOp = new MapOperator(runtimeCtx);\n }\n // Not synchronizing creation of mapOp with an invocation. Check immediately\n // after creation in case abort has been set.\n // Relying on the regular flow to clean up the actual operator. i.e. If an exception is\n // thrown, an attempt will be made to cleanup the op.\n // If we are here - exit out via an exception. If we're in the middle of the opeartor.initialize\n // call further down, we rely upon op.abort().\n checkAbortCondition();\n mapOp.clearConnectedOperators();\n mapOp.setExecContext(execContext);\n boolean fromCache = false;\n if (mergeWorkList != null) {\n AbstractMapOperator mergeMapOp = null;\n for (BaseWork mergeWork : mergeWorkList) {\n // TODO HIVE-14042. What is mergeWork, and why is it not part of the regular operator chain.\n // The mergeMapOp.initialize call further down can block, and will not receive information\n // about an abort request.\n MapWork mergeMapWork = (MapWork) mergeWork;\n if (mergeMapWork.getVectorMode()) {\n mergeMapOp = new VectorMapOperator(runtimeCtx);\n } else {\n mergeMapOp = new MapOperator(runtimeCtx);\n }\n mergeMapOpList.add(mergeMapOp);\n // initialize the merge operators first.\n if (mergeMapOp != null) {\n mergeMapOp.setConf(mergeMapWork);\n LOG.info(\"Input name is {}\", mergeMapWork.getName());\n jconf.set(Utilities.INPUT_NAME, mergeMapWork.getName());\n mergeMapOp.initialize(jconf, null);\n // if there are no files/partitions to read, we need to skip trying to read\n MultiMRInput multiMRInput = multiMRInputMap.get(mergeMapWork.getName());\n boolean skipRead = false;\n if (multiMRInput == null) {\n LOG.info(\"Multi MR Input for work {} is null. Skipping read.\", mergeMapWork.getName());\n skipRead = true;\n } else {\n Collection keyValueReaders = multiMRInput.getKeyValueReaders();\n if ((keyValueReaders == null) || (keyValueReaders.isEmpty())) {\n LOG.info(\"Key value readers are null or empty and hence skipping read. \" + \"KeyValueReaders = {}\", keyValueReaders);\n skipRead = true;\n }\n }\n if (skipRead) {\n List> children = new ArrayList<>();\n children.addAll(mergeMapOp.getConf().getAliasToWork().values());\n // do the same thing as setChildren when there is nothing to read.\n // the setChildren method initializes the object inspector needed by the operators\n // based on path and partition information which we don't have in this case.\n mergeMapOp.initEmptyInputChildren(children, jconf);\n } else {\n // the setChildren method initializes the object inspector needed by the operators\n // based on path and partition information.\n mergeMapOp.setChildren(jconf);\n }\n Operator finalOp = getFinalOp(mergeMapOp);\n if (finalOp instanceof TezDummyStoreOperator) {\n // we ensure that we don't try to read any data in case of skip read.\n ((TezDummyStoreOperator) finalOp).setFetchDone(skipRead);\n mapOp.setConnectedOperators(mergeMapWork.getTag(), (DummyStoreOperator) finalOp);\n } else {\n // found the plan is already connected which means this is derived from the cache.\n fromCache = true;\n }\n mergeMapOp.passExecContext(new ExecMapperContext(jconf));\n mergeMapOp.initializeLocalWork(jconf);\n }\n }\n }\n if (!fromCache) {\n // if not from cache, we still need to hook up the plans.\n ((TezContext) (MapredContext.get())).setDummyOpsMap(mapOp.getConnectedOperators());\n }\n // initialize map operator\n mapOp.setConf(mapWork);\n LOG.info(\"Main input name is \" + mapWork.getName());\n jconf.set(Utilities.INPUT_NAME, mapWork.getName());\n mapOp.initialize(jconf, null);\n checkAbortCondition();\n mapOp.setChildren(jconf);\n mapOp.passExecContext(execContext);\n LOG.info(mapOp.dump(0));\n // set memory available for operators\n long memoryAvailableToTask = processorContext.getTotalMemoryAvailableToTask();\n if (mapOp.getConf() != null) {\n mapOp.getConf().setMaxMemoryAvailable(memoryAvailableToTask);\n LOG.info(\"Memory available for operators set to {}\", LlapUtil.humanReadableByteCount(memoryAvailableToTask));\n }\n OperatorUtils.setMemoryAvailable(mapOp.getChildOperators(), memoryAvailableToTask);\n mapOp.initializeLocalWork(jconf);\n // Setup values registry\n checkAbortCondition();\n String valueRegistryKey = DynamicValue.DYNAMIC_VALUE_REGISTRY_CACHE_KEY;\n // On LLAP dynamic value registry might already be cached.\n final DynamicValueRegistryTez registryTez = dynamicValueCache.retrieve(valueRegistryKey, () -> new DynamicValueRegistryTez());\n dynamicValueCacheKeys.add(valueRegistryKey);\n RegistryConfTez registryConf = new RegistryConfTez(jconf, mapWork, processorContext, inputs);\n registryTez.init(registryConf);\n checkAbortCondition();\n initializeMapRecordSources();\n mapOp.initializeMapOperator(jconf);\n if ((mergeMapOpList != null) && !mergeMapOpList.isEmpty()) {\n for (AbstractMapOperator mergeMapOp : mergeMapOpList) {\n jconf.set(Utilities.INPUT_NAME, mergeMapOp.getConf().getName());\n // TODO HIVE-14042. abort handling: Handling of mergeMapOp\n mergeMapOp.initializeMapOperator(jconf);\n }\n }\n // Initialization isn't finished until all parents of all operators\n // are initialized. For broadcast joins that means initializing the\n // dummy parent operators as well.\n List dummyOps = mapWork.getDummyOps();\n jconf.set(Utilities.INPUT_NAME, mapWork.getName());\n if (dummyOps != null) {\n for (Operator dummyOp : dummyOps) {\n dummyOp.setExecContext(execContext);\n // TODO HIVE-14042. Handling of dummyOps, and propagating abort information to them\n dummyOp.initialize(jconf, null);\n }\n }\n OperatorUtils.setChildrenCollector(mapOp.getChildOperators(), outMap);\n mapOp.setReporter(reporter);\n MapredContext.get().setReporter(reporter);\n } catch (Throwable e) {\n setAborted(true);\n if (e instanceof OutOfMemoryError) {\n // will this be true here?\n // Don't create a new object if we are already out of memory\n throw (OutOfMemoryError) e;\n } else if (e instanceof InterruptedException) {\n LOG.info(\"Hit an interrupt while initializing MapRecordProcessor. Message={}\", e.getMessage());\n throw (InterruptedException) e;\n } else {\n throw new RuntimeException(\"Map operator initialization failed\", e);\n }\n }\n perfLogger.perfLogEnd(CLASS_NAME, PerfLogger.TEZ_INIT_OPERATORS);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void ensureInitialized() throws Exception{\r\n if (!engine.isInitialized()) {\r\n synchronized (engine) {\r\n if (!engine.isInitialized()) {\r\n engine.initializeEngine();\r\n ServiceHelper.startService(engine);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Make a copy of a writable object using serialization to a buffer.\n *\n * @param Generics Type T.\n * @param orig The object to copy\n * @param conf input Configuration.\n * @return The copied object\n */\npublic static T clone(T orig, Configuration conf) {\n try {\n // Unchecked cast from Class to Class\n @SuppressWarnings(\"unchecked\")\n T newInst = ReflectionUtils.newInstance((Class) orig.getClass(), conf);\n ReflectionUtils.copy(conf, orig, newInst);\n return newInst;\n } catch (IOException e) {\n throw new RuntimeException(\"Error writing/reading clone buffer\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void scanEntryLog(ServerConfiguration conf, long logId, final boolean printMsg) throws Exception{\r\n LOG.info(\"Scan entry log \" + logId + \" (\" + Long.toHexString(logId) + \".log)\");\r\n scanEntryLog(conf, logId, new EntryLogger.EntryLogScanner() {\r\n\r\n @Override\r\n public boolean accept(long ledgerId) {\r\n return true;\r\n }\r\n\r\n @Override\r\n public void process(long ledgerId, long startPos, ByteBuf entry) {\r\n FormatUtil.formatEntry(startPos, entry, printMsg, ledgerIdFormatter, entryFormatter);\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean handle(ServerConfiguration bkConf) throws Exception{\r\n LOG.info(\"=== Converting DbLedgerStorage ===\");\r\n ServerConfiguration conf = new ServerConfiguration(bkConf);\r\n DiskChecker diskChecker = new DiskChecker(bkConf.getDiskUsageThreshold(), bkConf.getDiskUsageWarnThreshold());\r\n LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(bkConf, bkConf.getLedgerDirs(), diskChecker);\r\n LedgerDirsManager indexDirsManager = BookieResources.createIndexDirsManager(conf, diskChecker, NullStatsLogger.INSTANCE, ledgerDirsManager);\r\n DbLedgerStorage dbStorage = new DbLedgerStorage();\r\n InterleavedLedgerStorage interleavedStorage = new InterleavedLedgerStorage();\r\n CheckpointSource checkpointSource = new CheckpointSource() {\r\n\r\n @Override\r\n public Checkpoint newCheckpoint() {\r\n return Checkpoint.MAX;\r\n }\r\n\r\n @Override\r\n public void checkpointComplete(Checkpoint checkpoint, boolean compact) {\r\n }\r\n };\r\n Checkpointer checkpointer = new Checkpointer() {\r\n\r\n @Override\r\n public void startCheckpoint(CheckpointSource.Checkpoint checkpoint) {\r\n }\r\n\r\n @Override\r\n public void start() {\r\n }\r\n };\r\n dbStorage.initialize(conf, null, ledgerDirsManager, indexDirsManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT);\r\n dbStorage.setCheckpointSource(checkpointSource);\r\n dbStorage.setCheckpointer(checkpointer);\r\n interleavedStorage.initialize(conf, null, ledgerDirsManager, indexDirsManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT);\r\n interleavedStorage.setCheckpointSource(checkpointSource);\r\n interleavedStorage.setCheckpointer(checkpointer);\r\n LedgerCache interleavedLedgerCache = interleavedStorage.getLedgerCache();\r\n int convertedLedgers = 0;\r\n for (long ledgerId : dbStorage.getActiveLedgersInRange(0, Long.MAX_VALUE)) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Converting ledger {}\", ledgerIdFormatter.formatLedgerId(ledgerId));\r\n }\r\n interleavedStorage.setMasterKey(ledgerId, dbStorage.readMasterKey(ledgerId));\r\n if (dbStorage.isFenced(ledgerId)) {\r\n interleavedStorage.setFenced(ledgerId);\r\n }\r\n long lastEntryInLedger = dbStorage.getLastEntryInLedger(ledgerId);\r\n for (long entryId = 0; entryId <= lastEntryInLedger; entryId++) {\r\n try {\r\n long location = dbStorage.getLocation(ledgerId, entryId);\r\n if (location != 0L) {\r\n interleavedLedgerCache.putEntryOffset(ledgerId, entryId, location);\r\n }\r\n } catch (Bookie.NoEntryException e) {\r\n }\r\n }\r\n if (++convertedLedgers % 1000 == 0) {\r\n LOG.info(\"Converted {} ledgers\", convertedLedgers);\r\n }\r\n }\r\n dbStorage.shutdown();\r\n interleavedLedgerCache.flushLedger(true);\r\n interleavedStorage.flush();\r\n interleavedStorage.shutdown();\r\n String baseDir = ledgerDirsManager.getAllLedgerDirs().get(0).toString();\r\n Files.move(FileSystems.getDefault().getPath(baseDir, \"ledgers\"), FileSystems.getDefault().getPath(baseDir, \"ledgers.backup\"));\r\n Files.move(FileSystems.getDefault().getPath(baseDir, \"locations\"), FileSystems.getDefault().getPath(baseDir, \"locations.backup\"));\r\n LOG.info(\"---- Done Converting {} ledgers ----\", convertedLedgers);\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleChangeClusterState(HttpPostCommand cmd) throws Throwable{\r\n String[] params = decodeParamsAndAuthenticate(cmd, 3);\r\n ClusterService clusterService = getNode().getClusterService();\r\n ClusterState state = ClusterState.valueOf(upperCaseInternal(params[2]));\r\n if (!state.equals(clusterService.getClusterState())) {\r\n clusterService.changeClusterState(state);\r\n JsonObject res = response(SUCCESS, \"state\", state.toString().toLowerCase(StringUtil.LOCALE_INTERNAL));\r\n prepareResponse(cmd, res);\r\n } else {\r\n JsonObject res = response(FAIL, \"state\", state.toString().toLowerCase(StringUtil.LOCALE_INTERNAL));\r\n prepareResponse(cmd, res);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void additionalWarmup() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void addFilter(Filter filter) throws Exception{\r\n Class clazz = filter.getClass();\r\n clazz.getMethod(\"parseFrom\", byte[].class);\r\n filterDescs.add(new FilterDesc(clazz.getName(), filter.toByteArray()));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " ValidBetween getValidBetween(List validBetweenList) throws Exception{\r\n if (CollectionUtils.isEmpty(validBetweenList)) {\r\n return null;\r\n }\r\n return validBetweenList.get(0);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Function tryLoadingSchemaFromResourceLoader(Exchange exchange) {\n return t -> {\n Resource res = PluginHelper.getResourceLoader(exchange.getContext()).resolveResource(\"classpath:schemas/\" + SchemaType.JSON.type() + \"/\" + t + \".\" + SchemaType.JSON.type());\n try {\n if (res.exists()) {\n try (InputStream is = res.getInputStream()) {\n if (is != null) {\n return Json.mapper().readTree(is);\n }\n }\n }\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to load Json schema for type: \" + t + \", resource: \" + res.getLocation(), e);\n }\n return null;\n };\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private String getInstanceName(Map parameters) throws Exception{\r\n String instanceName = (String) parameters.get(\"instanceName\");\r\n if (ObjectHelper.isEmpty(instanceName) && ObjectHelper.isNotEmpty(getComponent())) {\r\n instanceName = getComponent(ServiceNowComponent.class).getInstanceName();\r\n }\r\n if (ObjectHelper.isEmpty(instanceName)) {\r\n throw new NoSuchOptionException(\"instanceName\");\r\n }\r\n return instanceName;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic T get() {\n try {\n return passedInCallableFut.get();\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public void callInternal() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseFileLog(String line) {\n if (line.length() <= RepairLogger.cannotRepairFileLogPrefix.length()) {\n throw new RuntimeException(String.format(\"String '%s' is not a legal repair log\", line));\n }\n String filePath = line.substring(RepairLogger.cannotRepairFileLogPrefix.length());\n File f = new File(filePath.trim());\n currentTimePartitionCannotRepairFiles.add(f.getName());\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected int insertHelper(final CamelContext camelContext, final String key, final Exchange exchange, final String sql, final Long version, final boolean completed) throws Exception {\n final byte[] data = jdbcCamelCodec.marshallExchange(exchange, isAllowSerializedHeaders());\n Integer insertCount = super.jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(getLobHandler()) {\n\n @Override\n protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {\n int totalParameterIndex = 0;\n lobCreator.setBlobAsBytes(ps, ++totalParameterIndex, data);\n ps.setString(++totalParameterIndex, key);\n ps.setLong(++totalParameterIndex, version);\n if (isStoreBodyAsText()) {\n ps.setString(++totalParameterIndex, exchange.getIn().getBody(String.class));\n }\n if (hasHeadersToStoreAsText()) {\n for (String headerName : getHeadersToStoreAsText()) {\n String headerValue = exchange.getIn().getHeader(headerName, String.class);\n ps.setString(++totalParameterIndex, headerValue);\n }\n }\n if (completed && isRecoveryByInstance()) {\n ps.setString(++totalParameterIndex, instanceId);\n }\n }\n });\n return insertCount == null ? 0 : insertCount;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "public void preTest(HiveConf conf) throws Exception{\r\n if (zooKeeperCluster == null) {\r\n File tmpDir = Files.createTempDirectory(Paths.get(QTestSystemProperties.getTempDir()), \"tmp_\").toFile();\r\n zooKeeperCluster = new MiniZooKeeperCluster();\r\n zkPort = zooKeeperCluster.startup(tmpDir);\r\n }\r\n if (zooKeeper != null) {\r\n zooKeeper.close();\r\n }\r\n int sessionTimeout = (int) conf.getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT, TimeUnit.MILLISECONDS);\r\n zooKeeper = new ZooKeeper(\"localhost:\" + zkPort, sessionTimeout, new Watcher() {\r\n\r\n @Override\r\n public void process(WatchedEvent arg0) {\r\n }\r\n });\r\n String zkServer = \"localhost\";\r\n conf.set(\"hive.zookeeper.quorum\", zkServer);\r\n conf.set(\"hive.zookeeper.client.port\", \"\" + zkPort);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected List getReferencesForMessageMapping(Input input) throws Exception{\r\n return input.getReferences();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void close() throws Exception{\r\n out.close();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void waitForMemory() throws Exception{\r\n if (!waitForMemory(80, 5))\r\n throw new Exception(\"Not enought memory to process\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Setup\npublic void setup() {\n sizes = new int[DEFAULT_DATA_SIZE];\n offsets = new int[sizes.length];\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n Random r = new Random();\n int len = 0;\n // 1959\n final long base = -320000000L * 1000L;\n for (int i = 0; i < DEFAULT_DATA_SIZE; i++) {\n // -ve dates are also valid Timestamps - dates are within 1959 to 2027\n Date dt = new Date(base + (Math.abs(r.nextLong()) % (Integer.MAX_VALUE * 1000L)));\n byte[] ds = String.format(\"%s 00:00:01\", dt.toString()).getBytes();\n sizes[i] = ds.length;\n offsets[i] = len;\n len += ds.length;\n try {\n bos.write(ds);\n } catch (IOException e) {\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n ref.setData(bos.toByteArray());\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void applySecurityPolicy(Exchange exchange) throws Exception{\r\n ByteSource encryptedToken;\r\n String username = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME, String.class);\r\n String password = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD, String.class);\r\n if (username != null && password != null) {\r\n ShiroSecurityToken token = new ShiroSecurityToken(username, password);\r\n if (policy.isBase64()) {\r\n ByteSource bytes = ShiroSecurityHelper.encrypt(token, policy.getPassPhrase(), policy.getCipherService());\r\n String base64 = bytes.toBase64();\r\n exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, base64);\r\n } else {\r\n exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, token);\r\n }\r\n exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME);\r\n exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD);\r\n }\r\n Object token = ExchangeHelper.getMandatoryHeader(exchange, ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, Object.class);\r\n if (token instanceof ShiroSecurityToken) {\r\n ShiroSecurityToken sst = (ShiroSecurityToken) token;\r\n encryptedToken = ShiroSecurityHelper.encrypt(sst, policy.getPassPhrase(), policy.getCipherService());\r\n exchange.getIn().removeHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN);\r\n exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, encryptedToken);\r\n } else if (token instanceof String) {\r\n String data = (String) token;\r\n if (policy.isBase64()) {\r\n byte[] bytes = Base64.decode(data);\r\n encryptedToken = ByteSource.Util.bytes(bytes);\r\n } else {\r\n encryptedToken = ByteSource.Util.bytes(data);\r\n }\r\n } else if (token instanceof ByteSource) {\r\n encryptedToken = (ByteSource) token;\r\n } else {\r\n throw new CamelExchangeException(\"Shiro security header \" + ShiroSecurityConstants.SHIRO_SECURITY_TOKEN + \" is unsupported type: \" + ObjectHelper.classCanonicalName(token), exchange);\r\n }\r\n ByteSource decryptedToken = policy.getCipherService().decrypt(encryptedToken.getBytes(), policy.getPassPhrase());\r\n ShiroSecurityToken securityToken = ShiroSecurityHelper.deserialize(decryptedToken.getBytes());\r\n Subject currentUser = SecurityUtils.getSubject();\r\n try {\r\n authenticateUser(currentUser, securityToken);\r\n authorizeUser(currentUser, exchange);\r\n } finally {\r\n if (policy.isAlwaysReauthenticate()) {\r\n currentUser.logout();\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean processRow(Object value) {\n try {\n if (mapOp.getDone()) {\n // done\n return false;\n } else {\n // Since there is no concept of a group, we don't invoke\n // startGroup/endGroup for a mapper\n mapOp.process((Writable) value);\n }\n } catch (Throwable e) {\n if (e instanceof OutOfMemoryError) {\n // Don't create a new object if we are already out of memory\n throw (OutOfMemoryError) e;\n } else {\n LOG.error(\"Failed to process row\", e);\n closeReader();\n throw new RuntimeException(e);\n }\n }\n // give me more\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private ConfigReplacer createReplacer(Node node) throws Exception{\r\n String replacerClass = getAttribute(node, \"class-name\");\r\n Properties properties = new Properties();\r\n for (Node n : childElements(node)) {\r\n String value = cleanNodeName(n);\r\n if (\"properties\".equals(value)) {\r\n fillProperties(n, properties);\r\n }\r\n }\r\n ConfigReplacer replacer = (ConfigReplacer) Class.forName(replacerClass).newInstance();\r\n replacer.init(properties);\r\n return replacer;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void process(KeyedDataQueue queue, Exchange exchange) throws Exception{\r\n if (endpoint.getFormat() == Jt400Configuration.Format.binary) {\r\n queue.write(exchange.getIn().getHeader(Jt400Endpoint.KEY, byte[].class), exchange.getIn().getBody(byte[].class));\r\n } else {\r\n queue.write(exchange.getIn().getHeader(Jt400Endpoint.KEY, String.class), exchange.getIn().getBody(String.class));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getDateTimePieceOfFileName(String fName) throws Exception{\r\n if (fName == null || fName.isEmpty() || fName.length() < 12) {\r\n throw new Exception(\"File name must end with .yyyymmddhhmm \");\r\n }\r\n int index = fName.lastIndexOf('.');\r\n if (index == -1) {\r\n throw new Exception(\"File name must end with .yyyymmddhhmm \");\r\n }\r\n index++;\r\n if (fName.length() <= index) {\r\n throw new Exception(\"File name must end with .yyyymmddhhmm \");\r\n }\r\n String datePiece = fName.substring(index);\r\n if (datePiece.length() != 12) {\r\n throw new Exception(\"File name must end date in the format .yyyymmddhhmm \");\r\n }\r\n return datePiece;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static WritableComparator get(Object key, boolean nullSafe, NullOrdering nullOrdering) {\n if (key instanceof List) {\n // STRUCT or ARRAY are expressed as java.util.List\n return new HiveStructComparator(nullSafe, nullOrdering);\n } else if (key instanceof Map) {\n // TODO : https://issues.apache.org/jira/browse/HIVE-25042\n throw new RuntimeException(\"map datatype is not supported for SMB and Merge Join\");\n } else if (key instanceof StandardUnion) {\n throw new RuntimeException(\"union datatype is not supported for SMB and Merge Join\");\n } else {\n return new HiveWritableComparator(nullSafe, nullOrdering);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public boolean columns(String line) throws Exception{\r\n return metadata(\"getColumns\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"table name\"), \"%\" });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void dumpLedgers(Set ledgers, File targetFile) throws Exception{\r\n PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(targetFile), UTF_8.name()));\r\n try {\r\n for (Long ledger : ledgers) {\r\n pw.println(ledger);\r\n }\r\n } finally {\r\n pw.close();\r\n }\r\n System.out.println(\"Dump \" + ledgers.size() + \" ledgers to file : \" + targetFile);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean harvest() throws Exception{\r\n boolean hasNext = false;\r\n if (!this.empty) {\r\n String responseXML = httpClient.doRequest(this.baseURI, this.verb, this.set, this.from, this.until, this.metadata, this.resumptionToken, this.identifier);\r\n OAIPMHResponse oaipmhResponse = new OAIPMHResponse(responseXML);\r\n this.oaipmhResponseHandler.process(oaipmhResponse);\r\n Optional resumptionToken = oaipmhResponse.getResumptionToken();\r\n if (resumptionToken.isPresent() && !resumptionToken.get().isEmpty()) {\r\n this.resumptionToken = resumptionToken.get();\r\n hasNext = true;\r\n } else {\r\n this.resumptionToken = null;\r\n this.empty = true;\r\n }\r\n }\r\n return hasNext;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String getAnyBookie() throws Exception{\r\n Optional bookie = allBookies().stream().findAny();\r\n if (bookie.isPresent()) {\r\n return bookie.get();\r\n } else {\r\n throw new Exception(\"No bookie is available\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean handler(ServerConfiguration configuration) throws Exception{\r\n ClientConfiguration adminConf = new ClientConfiguration(configuration);\r\n BookKeeperAdmin admin = new BookKeeperAdmin(adminConf);\r\n try {\r\n admin.triggerAudit();\r\n } finally {\r\n if (admin != null) {\r\n admin.close();\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processWatchResult(CuratorEvent event) throws Exception{\r\n if (event.getResultCode() != KeeperException.Code.NONODE.intValue())\r\n return;\r\n LOG.info(\"Trying to reacquire because of the NONODE event\");\r\n startCreateCurrentNode();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int executeChangeApplicationQueueCommand(CommandLine cliParser, String title, Options opts) throws Exception {\n int exitCode = -1;\n if (!cliParser.hasOption(APP_ID)) {\n printUsage(title, opts);\n return exitCode;\n }\n moveApplicationAcrossQueues(cliParser.getOptionValue(APP_ID), cliParser.getOptionValue(CHANGE_APPLICATION_QUEUE));\n return 0;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static Map> getChildrenNodesMap(String fullXml, String containerNodeName, String childNodeName) throws Exception{\r\n Document document = getDocument(fullXml);\r\n return getChildrenNodesMap(document, containerNodeName, childNodeName);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized Consul getConsul() throws Exception{\r\n if (consul == null && ObjectHelper.isEmpty(getConfiguration().getConsulClient())) {\r\n consul = configuration.createConsulClient(getCamelContext());\r\n } else if (ObjectHelper.isNotEmpty(getConfiguration().getConsulClient())) {\r\n consul = getConfiguration().getConsulClient();\r\n }\r\n return consul;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseTariffZoneRefs(TariffZoneRefs_RelStructure tariffZonesStruct, StopArea stopArea) throws Exception{\r\n List tariffZoneRefs = tariffZonesStruct.getTariffZoneRef();\r\n for (TariffZoneRef tariffZoneRef : tariffZoneRefs) {\r\n Properties properties = tariffZoneProperties.get(tariffZoneRef.getRef());\r\n if (properties != null) {\r\n String tariffName = properties.getProperty(NAME);\r\n if (tariffName != null) {\r\n try {\r\n stopArea.setFareCode(Integer.parseInt(tariffName));\r\n } catch (Exception ignored) {\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `valueChange` to the URL query string\n if (getValueChange() != null) {\n try {\n joiner.add(String.format(\"%svalueChange%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getValueChange()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `browselistChange` to the URL query string\n if (getBrowselistChange() != null) {\n try {\n joiner.add(String.format(\"%sbrowselistChange%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getBrowselistChange()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `metadataChange` to the URL query string\n if (getMetadataChange() != null) {\n try {\n joiner.add(String.format(\"%smetadataChange%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getMetadataChange()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private static int getNumPartFieldsForMapSideRS(GBInfo gbInfo) {\n int numPartFields = 0;\n switch(gbInfo.gbPhysicalPipelineMode) {\n case MAP_SIDE_GB_NO_SKEW_NO_ADD_MR_JOB:\n case MAP_SIDE_GB_NO_SKEW_ADD_MR_JOB:\n case MAP_SIDE_GB_SKEW_GBKEYS_AND_DIST_UDAF_NOT_PRESENT:\n case NO_MAP_SIDE_GB_NO_SKEW:\n numPartFields += gbInfo.gbKeys.size();\n break;\n case NO_MAP_SIDE_GB_SKEW:\n case MAP_SIDE_GB_SKEW_GBKEYS_OR_DIST_UDAF_PRESENT:\n if (gbInfo.containsDistinctAggr) {\n numPartFields = Integer.MAX_VALUE;\n } else {\n numPartFields = -1;\n }\n break;\n default:\n throw new RuntimeException(\"Unable to determine Number of Partition Fields - Invalid Physical Mode: \" + gbInfo.gbPhysicalPipelineMode);\n }\n return numPartFields;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": " void createDirs() throws Exception{\r\n if (!rawFs.mkdirs(tezDir)) {\r\n LOG.warn(\"mkdirs for \" + tezDir + \" returned false\");\r\n }\r\n if (!rawFs.mkdirs(udfDir)) {\r\n LOG.warn(\"mkdirs for \" + udfDir + \" returned false\");\r\n }\r\n if (!rawFs.mkdirs(confDir)) {\r\n LOG.warn(\"mkdirs for \" + confDir + \" returned false\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String resultProcess(ResultSet resultSet) throws Exception{\r\n ArrayNode resultJSONArray = JSONUtils.createArrayNode();\r\n if (resultSet != null) {\r\n ResultSetMetaData md = resultSet.getMetaData();\r\n int num = md.getColumnCount();\r\n int rowCount = 0;\r\n int limit = sqlParameters.getLimit() == 0 ? QUERY_LIMIT : sqlParameters.getLimit();\r\n while (resultSet.next()) {\r\n if (rowCount == limit) {\r\n log.info(\"sql result limit : {} exceeding results are filtered\", limit);\r\n break;\r\n }\r\n ObjectNode mapOfColValues = JSONUtils.createObjectNode();\r\n for (int i = 1; i <= num; i++) {\r\n mapOfColValues.set(md.getColumnLabel(i), JSONUtils.toJsonNode(resultSet.getObject(i)));\r\n }\r\n resultJSONArray.add(mapOfColValues);\r\n rowCount++;\r\n }\r\n int displayRows = sqlParameters.getDisplayRows() > 0 ? sqlParameters.getDisplayRows() : TaskConstants.DEFAULT_DISPLAY_ROWS;\r\n displayRows = Math.min(displayRows, rowCount);\r\n log.info(\"display sql result {} rows as follows:\", displayRows);\r\n for (int i = 0; i < displayRows; i++) {\r\n String row = JSONUtils.toJsonString(resultJSONArray.get(i));\r\n log.info(\"row {} : {}\", i + 1, row);\r\n }\r\n }\r\n String result = resultJSONArray.isEmpty() ? JSONUtils.toJsonString(generateEmptyRow(resultSet)) : JSONUtils.toJsonString(resultJSONArray);\r\n if (Boolean.TRUE.equals(sqlParameters.getSendEmail())) {\r\n sendAttachment(sqlParameters.getGroupId(), StringUtils.isNotEmpty(sqlParameters.getTitle()) ? sqlParameters.getTitle() : taskExecutionContext.getTaskName() + \" query result sets\", result);\r\n }\r\n log.debug(\"execute sql result : {}\", result);\r\n return result;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean handle(ServerConfiguration bkConf) throws Exception{\r\n LOG.info(\"=== Converting DbLedgerStorage ===\");\r\n ServerConfiguration conf = new ServerConfiguration(bkConf);\r\n LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(bkConf, bkConf.getLedgerDirs(), new DiskChecker(bkConf.getDiskUsageThreshold(), bkConf.getDiskUsageWarnThreshold()));\r\n LedgerDirsManager ledgerIndexManager = new LedgerDirsManager(bkConf, bkConf.getLedgerDirs(), new DiskChecker(bkConf.getDiskUsageThreshold(), bkConf.getDiskUsageWarnThreshold()));\r\n DbLedgerStorage dbStorage = new DbLedgerStorage();\r\n InterleavedLedgerStorage interleavedStorage = new InterleavedLedgerStorage();\r\n CheckpointSource checkpointSource = new CheckpointSource() {\r\n\r\n @Override\r\n public Checkpoint newCheckpoint() {\r\n return Checkpoint.MAX;\r\n }\r\n\r\n @Override\r\n public void checkpointComplete(Checkpoint checkpoint, boolean compact) {\r\n }\r\n };\r\n Checkpointer checkpointer = new Checkpointer() {\r\n\r\n @Override\r\n public void startCheckpoint(CheckpointSource.Checkpoint checkpoint) {\r\n }\r\n\r\n @Override\r\n public void start() {\r\n }\r\n };\r\n dbStorage.initialize(conf, null, ledgerDirsManager, ledgerIndexManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT);\r\n dbStorage.setCheckpointSource(checkpointSource);\r\n dbStorage.setCheckpointer(checkpointer);\r\n interleavedStorage.initialize(conf, null, ledgerDirsManager, ledgerIndexManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT);\r\n interleavedStorage.setCheckpointSource(checkpointSource);\r\n interleavedStorage.setCheckpointer(checkpointer);\r\n LedgerCache interleavedLedgerCache = interleavedStorage.getLedgerCache();\r\n int convertedLedgers = 0;\r\n for (long ledgerId : dbStorage.getActiveLedgersInRange(0, Long.MAX_VALUE)) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Converting ledger {}\", ledgerIdFormatter.formatLedgerId(ledgerId));\r\n }\r\n interleavedStorage.setMasterKey(ledgerId, dbStorage.readMasterKey(ledgerId));\r\n if (dbStorage.isFenced(ledgerId)) {\r\n interleavedStorage.setFenced(ledgerId);\r\n }\r\n long lastEntryInLedger = dbStorage.getLastEntryInLedger(ledgerId);\r\n for (long entryId = 0; entryId <= lastEntryInLedger; entryId++) {\r\n try {\r\n long location = dbStorage.getLocation(ledgerId, entryId);\r\n if (location != 0L) {\r\n interleavedLedgerCache.putEntryOffset(ledgerId, entryId, location);\r\n }\r\n } catch (Bookie.NoEntryException e) {\r\n }\r\n }\r\n if (++convertedLedgers % 1000 == 0) {\r\n LOG.info(\"Converted {} ledgers\", convertedLedgers);\r\n }\r\n }\r\n dbStorage.shutdown();\r\n interleavedLedgerCache.flushLedger(true);\r\n interleavedStorage.flush();\r\n interleavedStorage.shutdown();\r\n String baseDir = ledgerDirsManager.getAllLedgerDirs().get(0).toString();\r\n Files.move(FileSystems.getDefault().getPath(baseDir, \"ledgers\"), FileSystems.getDefault().getPath(baseDir, \"ledgers.backup\"));\r\n Files.move(FileSystems.getDefault().getPath(baseDir, \"locations\"), FileSystems.getDefault().getPath(baseDir, \"locations.backup\"));\r\n LOG.info(\"---- Done Converting {} ledgers ----\", convertedLedgers);\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic DeletePoliciesConfigurationsResponse deleteAllPoliciesConfigurations(DeletePoliciesConfigurationsRequest request) throws Exception {\n Connection connection = null;\n try {\n connection = getConnection(false);\n FederationQueryRunner runner = new FederationQueryRunner();\n LOG.info(\"delete table = policies start.\");\n runner.truncateTable(connection, \"policies\");\n LOG.info(\"delete table = policies finished.\");\n } catch (Exception e) {\n throw new RuntimeException(\"Could not delete table (policies)!\", e);\n } finally {\n // Return to the pool the CallableStatement\n try {\n FederationStateStoreUtils.returnToPool(LOG, null, connection);\n } catch (YarnException e) {\n LOG.error(\"close connection error.\", e);\n }\n }\n return DeletePoliciesConfigurationsResponse.newInstance();\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void beforeClassSpec() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void printEntry(Entry.Reader reader) throws Exception{\r\n LogRecordWithDLSN record = reader.nextRecord();\r\n while (null != record) {\r\n System.out.println(\"\\t\" + record);\r\n if (!skipPayload) {\r\n if (printHex) {\r\n System.out.println(Hex.encodeHexString(record.getPayload()));\r\n } else {\r\n System.out.println(new String(record.getPayload(), UTF_8));\r\n }\r\n }\r\n System.out.println(\"\");\r\n record = reader.nextRecord();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public User deleteUser(String userName, int id) throws Exception{\r\n User user = usersService.queryUser(userName);\r\n usersService.deleteUserById(user, id);\r\n return usersService.queryUser(userName);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleBackup(HttpPostCommand cmd, boolean deprecated) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n getNode().getNodeExtension().getHotRestartService().backup();\r\n if (deprecated) {\r\n Map headers = new HashMap<>();\r\n headers.put(\"Content-Type\", \"application/json\");\r\n headers.put(\"Deprecation\", \"true\");\r\n headers.put(\"Warning\", \"299 - \\\"Deprecated API\\\". Please use /hazelcast/rest/management/cluster/backup\" + \" instead. This API will be removed in future releases.\");\r\n cmd.setResponseWithHeaders(SC_200, headers, stringToBytes(response(SUCCESS).toString()));\r\n } else {\r\n prepareResponse(cmd, response(SUCCESS));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String translateThisVid(String oldVid) throws Exception{\r\n if (old2NewVidMap == null) {\r\n throw new Exception(\" ERROR - null old2NewVidMap found in translateThisVid. \");\r\n }\r\n if (old2NewVidMap.containsKey(oldVid)) {\r\n return old2NewVidMap.get(oldVid);\r\n } else {\r\n throw new Exception(\" ERROR - could not find VID translation for original VID = \" + oldVid);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void init(@Nonnull Context context) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public LinkedHashMap getDNACodingSequences() throws Exception{\r\n LinkedHashMap dnaSequenceList = new LinkedHashMap();\r\n ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), \"prediction/gene/cDNA\");\r\n logger.info(\"{} hits\", elementList.size());\r\n for (Element dnaElement : elementList) {\r\n Element geneElement = (Element) dnaElement.getParentNode();\r\n String sequence = dnaElement.getTextContent().replaceAll(\"\\\\W\", \"\");\r\n DNASequence dnaSequence = new DNASequence(sequence);\r\n String idGene = geneElement.getAttribute(\"idGene\");\r\n dnaSequence.setAccession(new AccessionID(idGene));\r\n dnaSequenceList.put(idGene, dnaSequence);\r\n }\r\n return dnaSequenceList;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void init(Configuration hconf) throws SerDeException, HiveException {\n VectorPartitionDesc vectorPartDesc = partDesc.getVectorPartitionDesc();\n // This type information specifies the data types the partition needs to read.\n TypeInfo[] dataTypeInfos = vectorPartDesc.getDataTypeInfos();\n // We need to provide the minimum number of columns to be read so\n // LazySimpleDeserializeRead's separator parser does not waste time.\n //\n Preconditions.checkState(dataColumnsToIncludeTruncated != null);\n TypeInfo[] minimalDataTypeInfos;\n if (dataColumnsToIncludeTruncated.length < dataTypeInfos.length) {\n minimalDataTypeInfos = Arrays.copyOf(dataTypeInfos, dataColumnsToIncludeTruncated.length);\n } else {\n minimalDataTypeInfos = dataTypeInfos;\n }\n readerColumnCount = minimalDataTypeInfos.length;\n switch(vectorPartDesc.getVectorDeserializeType()) {\n case LAZY_SIMPLE:\n {\n LazySerDeParameters simpleSerdeParams = new LazySerDeParameters(hconf, partDesc.getTableDesc().getProperties(), LazySimpleSerDe.class.getName());\n LazySimpleDeserializeRead lazySimpleDeserializeRead = new LazySimpleDeserializeRead(minimalDataTypeInfos, batchContext.getRowdataTypePhysicalVariations(), /* useExternalBuffer */\n true, simpleSerdeParams);\n vectorDeserializeRow = new VectorDeserializeRow(lazySimpleDeserializeRead);\n // Initialize with data row type conversion parameters.\n vectorDeserializeRow.initConversion(tableRowTypeInfos, dataColumnsToIncludeTruncated);\n deserializeRead = lazySimpleDeserializeRead;\n }\n break;\n case LAZY_BINARY:\n {\n LazyBinaryDeserializeRead lazyBinaryDeserializeRead = new LazyBinaryDeserializeRead(dataTypeInfos, /* useExternalBuffer */\n true);\n vectorDeserializeRow = new VectorDeserializeRow(lazyBinaryDeserializeRead);\n // Initialize with data row type conversion parameters.\n vectorDeserializeRow.initConversion(tableRowTypeInfos, dataColumnsToIncludeTruncated);\n deserializeRead = lazyBinaryDeserializeRead;\n }\n break;\n default:\n throw new RuntimeException(\"Unexpected vector deserialize row type \" + vectorPartDesc.getVectorDeserializeType().name());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void setRemoteMacAddress(MacAddress remoteMacAddress) {\n this.remoteMacAddress = remoteMacAddress;\n // Update the filter expression, if the handle is already open.\n if ((receiveHandle != null) && (receiveHandle.isOpen())) {\n MacAddress tempRemoteMacAddress = remoteMacAddress != null ? remoteMacAddress : MacAddress.getByAddress(new byte[] { 0, 0, 0, 0, 0, 0 });\n String filter = config.getMacBasedFilterString(localMacAddress, tempRemoteMacAddress);\n if (!filter.isEmpty()) {\n try {\n receiveHandle.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);\n } catch (NotOpenException | PcapNativeException e) {\n throw new RuntimeException(\"Error updating filter expression\");\n }\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public void postInit() throws Exception{\r\n miniClusters.postInit(conf);\r\n sem = new SemanticAnalyzer(new QueryState.Builder().withHiveConf(conf).build());\r\n testWarehouse = conf.getVar(HiveConf.ConfVars.METASTOREWAREHOUSE);\r\n db = Hive.get(conf);\r\n pd = new ParseDriver();\r\n initMaterializedViews();\r\n firstStartSessionState();\r\n if (conf.getBoolVar(ConfVars.MSC_CACHE_ENABLED)) {\r\n HiveMetaStoreClientWithLocalCache.init(conf);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void schemaValidation(Document doc) throws Exception{\r\n ArrayList schemas = new ArrayList<>();\r\n InputStream inputStream = null;\r\n String schemaLocation = doc.getDocumentElement().getAttribute(\"xsi:schemaLocation\");\r\n schemaLocation = schemaLocation.replaceAll(\"^ +| +$| (?= )\", \"\");\r\n String[] xsdLocations = schemaLocation.split(\"(? 0) {\r\n signer.update(buffer, 0, read);\r\n }\r\n } finally {\r\n IOHelper.close(payloadStream);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void makeBucket(String bucketName) throws Exception{\r\n MakeBucketArgs.Builder makeBucketRequest = MakeBucketArgs.builder().bucket(bucketName).objectLock(getConfiguration().isObjectLock());\r\n if (isNotEmpty(getConfiguration().getRegion())) {\r\n makeBucketRequest.region(getConfiguration().getRegion());\r\n }\r\n getMinioClient().makeBucket(makeBucketRequest.build());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object getValue(final Message message, final String type) throws Exception{\r\n Object value = message.getHeader(CaffeineConstants.VALUE);\r\n if (value == null) {\r\n if (type != null) {\r\n Class clazz = getEndpoint().getCamelContext().getClassResolver().resolveClass(type);\r\n value = message.getBody(clazz);\r\n } else {\r\n value = message.getBody();\r\n }\r\n }\r\n if (value == null) {\r\n throw new CamelExchangeException(\"No value provided in header or body (\" + CaffeineConstants.VALUE + \")\", message.getExchange());\r\n }\r\n return value;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Perform a check to determine if the user is able to access the file passed in.\n * If the user name passed in is different from the current user, this method will\n * attempt to do impersonate the user to do the check; the current user should be\n * able to create proxy users in this case.\n * @param fs FileSystem of the path to check\n * @param stat FileStatus representing the file\n * @param action FsAction that will be checked\n * @param user User name of the user that will be checked for access. If the user name\n * is null or the same as the current user, no user impersonation will be done\n * and the check will be done as the current user. Otherwise the file access\n * check will be performed within a doAs() block to use the access privileges\n * of this user. In this case the user must be configured to impersonate other\n * users, otherwise this check will fail with error.\n * @param children List of children to be collected. If this is null, no children are collected.\n * To be set only if this is a directory\n * @throws IOException\n * @throws AccessControlException\n * @throws InterruptedException\n * @throws Exception\n */\npublic static void checkFileAccessWithImpersonation(final FileSystem fs, final FileStatus stat, final FsAction action, final String user, final List children, final FileSystem fsAsUser) throws IOException, AccessControlException, InterruptedException, Exception {\n UserGroupInformation ugi = Utils.getUGI();\n String currentUser = ugi.getShortUserName();\n if (user == null || currentUser.equals(user)) {\n // No need to impersonate user, do the checks as the currently configured user.\n ShimLoader.getHadoopShims().checkFileAccess(fs, stat, action);\n addChildren(fs, stat.getPath(), children);\n return;\n }\n // Otherwise, try user impersonation. Current user must be configured to do user impersonation.\n UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());\n proxyUser.doAs(new PrivilegedExceptionAction() {\n\n @Override\n public Object run() throws Exception {\n ShimLoader.getHadoopShims().checkFileAccess(fsAsUser, stat, action);\n addChildren(fsAsUser, stat.getPath(), children);\n return null;\n }\n });\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Create a hierarchical ObjectInspector for LazyObject with the given typeInfo.\n *\n * @param typeInfo The type information for the LazyObject\n * @param separatorIndex The current level (for separators). List(array), struct uses 1 level of\n * separator, and map uses 2 levels: the first one for delimiting entries, the second one\n * for delimiting key and values.\n * @param lazyParams Params for lazy types\n * @param option the {@link ObjectInspectorOptions}\n * @return The ObjectInspector\n * @throws SerDeException\n */\npublic static ObjectInspector createLazyObjectInspector(TypeInfo typeInfo, int separatorIndex, LazyObjectInspectorParameters lazyParams, ObjectInspectorOptions option) throws SerDeException {\n ObjectInspector.Category c = typeInfo.getCategory();\n switch(c) {\n case PRIMITIVE:\n return LazyPrimitiveObjectInspectorFactory.getLazyObjectInspector((PrimitiveTypeInfo) typeInfo, lazyParams);\n case MAP:\n return LazyObjectInspectorFactory.getLazySimpleMapObjectInspector(createLazyObjectInspector(((MapTypeInfo) typeInfo).getMapKeyTypeInfo(), separatorIndex + 2, lazyParams, option), createLazyObjectInspector(((MapTypeInfo) typeInfo).getMapValueTypeInfo(), separatorIndex + 2, lazyParams, option), LazyUtils.getSeparator(lazyParams.getSeparators(), separatorIndex), LazyUtils.getSeparator(lazyParams.getSeparators(), separatorIndex + 1), lazyParams);\n case LIST:\n return LazyObjectInspectorFactory.getLazySimpleListObjectInspector(createLazyObjectInspector(((ListTypeInfo) typeInfo).getListElementTypeInfo(), separatorIndex + 1, lazyParams, option), LazyUtils.getSeparator(lazyParams.getSeparators(), separatorIndex), lazyParams);\n case STRUCT:\n StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;\n List fieldNames = structTypeInfo.getAllStructFieldNames();\n List fieldTypeInfos = structTypeInfo.getAllStructFieldTypeInfos();\n List fieldObjectInspectors = new ArrayList(fieldTypeInfos.size());\n for (int i = 0; i < fieldTypeInfos.size(); i++) {\n fieldObjectInspectors.add(createLazyObjectInspector(fieldTypeInfos.get(i), separatorIndex + 1, lazyParams, option));\n }\n return LazyObjectInspectorFactory.getLazySimpleStructObjectInspector(fieldNames, fieldObjectInspectors, null, LazyUtils.getSeparator(lazyParams.getSeparators(), separatorIndex), lazyParams, option);\n case UNION:\n UnionTypeInfo unionTypeInfo = (UnionTypeInfo) typeInfo;\n List lazyOIs = new ArrayList();\n for (TypeInfo uti : unionTypeInfo.getAllUnionObjectTypeInfos()) {\n lazyOIs.add(createLazyObjectInspector(uti, separatorIndex + 1, lazyParams, option));\n }\n return LazyObjectInspectorFactory.getLazyUnionObjectInspector(lazyOIs, LazyUtils.getSeparator(lazyParams.getSeparators(), separatorIndex), lazyParams);\n }\n throw new RuntimeException(\"Hive LazySerDe Internal error.\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// ------------------------------------------------------------------------\n// Storage helper\n/**\n * Initializes storage for the specified {@link HLLType} and changes the\n * instance's {@link #type}.\n *\n * @param type the {@link HLLType} to initialize storage for. This cannot be\n * null and must be an instantiable type. (For instance,\n * it cannot be {@link HLLType#UNDEFINED}.)\n */\nprivate void initializeStorage(final HLLType type) {\n this.type = type;\n switch(type) {\n case EMPTY:\n // nothing to be done\n break;\n case EXPLICIT:\n this.explicitStorage = new HashSet<>();\n break;\n case SPARSE:\n this.sparseProbabilisticStorage = new HashMap<>();\n break;\n case FULL:\n this.probabilisticStorage = new BitVector(regwidth, m);\n break;\n default:\n throw new RuntimeException(\"Unsupported HLL type \" + type);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private WebSocketClient receiveRealtimeLog(final String tisHost, String dataXName, int taskId) throws Exception{\r\n final String applyURI = config.getJobLogsFetchUrl(tisHost, dataXName, taskId);\r\n log.info(\"apply ws connection,uri:{}\", applyURI);\r\n WebSocketClient webSocketClient = new WebSocketClient(new URI(applyURI)) {\r\n\r\n @Override\r\n public void onOpen(ServerHandshake handshakedata) {\r\n log.info(\"start to receive remote execute log\");\r\n }\r\n\r\n @Override\r\n public void onMessage(String message) {\r\n ExecLog execLog = JSONUtils.parseObject(message, ExecLog.class);\r\n log.info(execLog.getMsg());\r\n }\r\n\r\n @Override\r\n public void onClose(int code, String reason, boolean remote) {\r\n log.info(\"stop to receive remote log,reason:{},taskId:{}\", reason, taskId);\r\n }\r\n\r\n @Override\r\n public void onError(Exception t) {\r\n log.error(t.getMessage(), t);\r\n }\r\n };\r\n webSocketClient.connect();\r\n return webSocketClient;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void send(MessageProducer producer, Message message) throws Exception{\r\n if (preserveMessageQos) {\r\n long ttl = message.getJMSExpiration();\r\n if (ttl != 0) {\r\n ttl = ttl - System.currentTimeMillis();\r\n if (ttl <= 0) {\r\n ttl = 1;\r\n }\r\n }\r\n int priority = message.getJMSPriority();\r\n if (priority < 0 || priority > 9) {\r\n priority = this.priority;\r\n }\r\n int resolvedDeliveryMode = resolveDeliveryMode(message);\r\n producer.send(message, resolvedDeliveryMode, priority, ttl);\r\n } else if (explicitQosEnabled) {\r\n producer.send(message, deliveryMode, priority, timeToLive);\r\n } else {\r\n producer.send(message);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Object stringTreeToValue(String value, JavaType javaType) {\n try {\n if (Objects.isNull(value) || Objects.isNull(javaType)) {\n return null;\n }\n return OBJECT_MAPPER.readValue(value, javaType);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "protected void testForResponseCodeUsingHttps(SdkHttpClient client, int returnCode) throws Exception{\r\n SdkHttpMethod sdkHttpMethod = SdkHttpMethod.POST;\r\n stubForMockRequest(returnCode);\r\n SdkHttpFullRequest req = mockSdkRequest(\"https://localhost:\" + mockServer.httpsPort(), sdkHttpMethod);\r\n HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder().request(req).contentStreamProvider(req.contentStreamProvider().orElse(null)).build()).call();\r\n validateResponse(rsp, returnCode, sdkHttpMethod);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic List listNamespaces(Namespace namespace) {\n if (!isValidateNamespace(namespace) && !namespace.isEmpty()) {\n throw new NoSuchNamespaceException(\"Namespace does not exist: %s\", namespace);\n }\n if (!namespace.isEmpty()) {\n return ImmutableList.of();\n }\n try {\n List namespaces = clients.run(IMetaStoreClient::getAllDatabases).stream().map(Namespace::of).collect(Collectors.toList());\n LOG.debug(\"Listing namespace {} returned tables: {}\", namespace, namespaces);\n return namespaces;\n } catch (TException e) {\n throw new RuntimeException(\"Failed to list all namespace: \" + namespace + \" in Hive Metastore\", e);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new RuntimeException(\"Interrupted in call to getAllDatabases() \" + namespace + \" in Hive Metastore\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private static void insertBasicFactories(XSet xSet, XImplementationLoader xImpLoader) throws Exception{\r\n xSet.insert(xImpLoader.activate(\"com.sun.star.comp.loader.JavaLoader\", null, null, null));\r\n xSet.insert(xImpLoader.activate(\"com.sun.star.comp.urlresolver.UrlResolver\", null, null, null));\r\n xSet.insert(xImpLoader.activate(\"com.sun.star.comp.bridgefactory.BridgeFactory\", null, null, null));\r\n xSet.insert(xImpLoader.activate(\"com.sun.star.comp.connections.Connector\", null, null, null));\r\n xSet.insert(xImpLoader.activate(\"com.sun.star.comp.connections.Acceptor\", null, null, null));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void parseURI(URI uri) throws Exception{\r\n String protocol = uri.getScheme();\r\n if (!protocol.equalsIgnoreCase(\"lpr\")) {\r\n throw new IllegalArgumentException(\"Unrecognized Print protocol: \" + protocol + \" for uri: \" + uri);\r\n }\r\n setUri(uri);\r\n setHostname(uri.getHost());\r\n setPort(uri.getPort());\r\n String path = uri.getPath();\r\n path = StringHelper.removeStartingCharacters(path, '/');\r\n path = StringHelper.removeStartingCharacters(path, '\\\\');\r\n setPrintername(path);\r\n Map printSettings = URISupport.parseParameters(uri);\r\n setFlavor((String) printSettings.get(\"flavor\"));\r\n setMimeType((String) printSettings.get(\"mimeType\"));\r\n setDocFlavor(assignDocFlavor(flavor, mimeType));\r\n setPrinterPrefix((String) printSettings.get(\"printerPrefix\"));\r\n if (printSettings.containsKey(\"copies\")) {\r\n setCopies(Integer.valueOf((String) printSettings.get(\"copies\")));\r\n }\r\n setMediaSize((String) printSettings.get(\"mediaSize\"));\r\n setSides((String) printSettings.get(\"sides\"));\r\n setOrientation((String) printSettings.get(\"orientation\"));\r\n setMediaSizeName(assignMediaSize(mediaSize));\r\n setInternalSides(assignSides(sides));\r\n setInternalOrientation(assignOrientation(orientation));\r\n if (printSettings.containsKey(\"sendToPrinter\")) {\r\n if (!(Boolean.parseBoolean((String) printSettings.get(\"sendToPrinter\")))) {\r\n setSendToPrinter(false);\r\n }\r\n }\r\n if (printSettings.containsKey(\"mediaTray\")) {\r\n setMediaTray((String) printSettings.get(\"mediaTray\"));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void addInjectionProperty(Injection metaInj, BeanLevelInfo leaf) {\n if (StringUtils.isBlank(metaInj.name())) {\n throw new RuntimeException(\"Property name shouldn't be blank in the \" + clazz);\n }\n String propertyName = calcPropertyName(metaInj, leaf);\n if (properties.containsKey(propertyName)) {\n throw new RuntimeException(\"Property '\" + propertyName + \"' already defined for \" + clazz);\n }\n // probably hidden\n if (hideProperties.contains(propertyName)) {\n return;\n }\n String injectionKeyDescription = clazzAnnotation.localizationPrefix() + propertyName;\n Property prop = new Property(propertyName, injectionKeyDescription, metaInj.group(), leaf.createCallStack(), false);\n properties.put(prop.key, prop);\n Group gr = groupsMap.get(metaInj.group());\n if (gr == null) {\n throw new RuntimeException(\"Group '\" + metaInj.group() + \"' for property '\" + metaInj.name() + \"' is not defined \" + clazz);\n }\n gr.properties.add(prop);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private ASTNode pkFkHint(int fkTableIndex, boolean nonFkSideIsFiltered) {\n ParseDriver parseDriver = new ParseDriver();\n try {\n return parseDriver.parseHint(String.format(\"PKFK_JOIN(%d, %s)\", fkTableIndex, nonFkSideIsFiltered ? NON_FK_FILTERED : NON_FK_NOT_FILTERED));\n } catch (ParseException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n */\nprivate static void forEachLine(String file, Consumer lineProc) {\n InputStream stream = IgniteAbbrevationsRule.class.getResourceAsStream(file);\n try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(\"#\"))\n continue;\n lineProc.accept(line);\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public Polygon getEnveloppe(ValidationParameters parameters) throws Exception{\r\n String perimeter = parameters.getStopAreasArea();\r\n if (perimeter == null || perimeter.isEmpty() || !perimeter.startsWith(\"[\")) {\r\n perimeter = DEFAULT_ENVELOPPE;\r\n }\r\n JSONArray array = new JSONArray(perimeter);\r\n List listCoordinates = new ArrayList();\r\n for (int i = 0; i < array.length(); i++) {\r\n JSONArray coords = array.getJSONArray(i);\r\n Coordinate coord = new Coordinate(coords.getDouble(0), coords.getDouble(1));\r\n listCoordinates.add(coord);\r\n }\r\n if (!listCoordinates.get(0).equals(listCoordinates.get(listCoordinates.size() - 1))) {\r\n listCoordinates.add(listCoordinates.get(0));\r\n }\r\n Coordinate[] coordinates = listCoordinates.toArray(new Coordinate[0]);\r\n LinearRing shell = getGeometryFactory().createLinearRing(coordinates);\r\n LinearRing[] holes = null;\r\n Polygon polygon = getGeometryFactory().createPolygon(shell, holes);\r\n return polygon;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Deserializes the HLL (in {@link #toBytes(ISchemaVersion)} format) serialized\n * into bytes.

\n *\n * @param bytes the serialized bytes of new HLL\n * @return the deserialized HLL. This will never be null.\n *\n * @see #toBytes(ISchemaVersion)\n */\npublic static HLL fromBytes(final byte[] bytes) {\n final ISchemaVersion schemaVer = SerializationUtil.getSchemaVersion(bytes);\n final IHLLMetadata metadata = schemaVer.readMetadata(bytes);\n final HLLType type = metadata.HLLType();\n final int regwidth = metadata.registerWidth();\n final int log2m = metadata.registerCountLog2();\n final boolean sparseon = metadata.sparseEnabled();\n final int expthresh;\n if (metadata.explicitAuto())\n expthresh = -1;\n else if (metadata.explicitOff())\n expthresh = 0;\n else {\n // NOTE: take into account that the postgres-compatible constructor\n // subtracts one before taking a power of two.\n expthresh = metadata.log2ExplicitCutoff() + 1;\n }\n final HLL hll = new HLL(log2m, regwidth, expthresh, sparseon, type);\n // Short-circuit on empty, which needs no other deserialization.\n if (HLLType.EMPTY.equals(type))\n return hll;\n final int wordLength;\n switch(type) {\n case EXPLICIT:\n wordLength = Long.SIZE;\n break;\n case SPARSE:\n wordLength = hll.shortWordLength;\n break;\n case FULL:\n wordLength = hll.regwidth;\n break;\n default:\n throw new RuntimeException(\"Unsupported HLL type \" + type);\n }\n final IWordDeserializer deserializer = schemaVer.getDeserializer(type, wordLength, bytes);\n switch(type) {\n case EXPLICIT:\n // NOTE: This should not exceed expthresh and this will always\n // be exactly the number of words that were encoded,\n // because the word length is at least a byte wide.\n // SEE: IWordDeserializer#totalWordCount()\n for (int i = 0; i < deserializer.totalWordCount(); i++) hll.explicitStorage.add(deserializer.readWord());\n break;\n case SPARSE:\n // NOTE: If the shortWordLength were smaller than 8 bits\n // (1 byte) there would be a possibility (because of\n // padding arithmetic) of having one or more extra\n // registers read. However, this is not relevant as the\n // extra registers will be all zeroes, which are ignored\n // in the sparse representation.\n for (int i = 0; i < deserializer.totalWordCount(); i++) {\n final long shortWord = deserializer.readWord();\n final byte registerVal = (byte) (shortWord & hll.valueMask);\n // Only set non-zero registers.\n if (registerVal != 0)\n hll.sparseProbabilisticStorage.put((int) (shortWord >>> hll.regwidth), registerVal);\n }\n break;\n case FULL:\n // NOTE: Iteration is done using m (register count) and NOT\n // deserializer#totalWordCount() because regwidth may be\n // less than 8 and as such the padding on the 'last' byte\n // may be larger than regwidth, causing an extra register\n // to be read.\n // SEE: IWordDeserializer#totalWordCount()\n for (long i = 0; i < hll.m; i++) hll.probabilisticStorage.setRegister(i, deserializer.readWord());\n break;\n default:\n throw new RuntimeException(\"Unsupported HLL type \" + type);\n }\n return hll;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": " void validate(TriggerAttributes attributes) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected RoutesBuilder createRouteBuilder() throws Exception{\r\n return new RouteBuilder() {\r\n\r\n @Override\r\n public void configure() {\r\n }\r\n };\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `address` to the URL query string\n if (getAddress() != null) {\n try {\n joiner.add(String.format(\"%saddress%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getAddress()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `timestamp` to the URL query string\n if (getTimestamp() != null) {\n try {\n joiner.add(String.format(\"%stimestamp%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getTimestamp()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `result` to the URL query string\n if (getResult() != null) {\n try {\n joiner.add(String.format(\"%sresult%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getResult()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `value` to the URL query string\n if (getValue() != null) {\n try {\n joiner.add(String.format(\"%svalue%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getValue()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private boolean expandStorage(ServerConfiguration bkConf) throws Exception{\r\n return runFunctionWithMetadataBookieDriver(bkConf, driver -> {\r\n List allLedgerDirs = Lists.newArrayList();\r\n allLedgerDirs.addAll(Arrays.asList(ledgerDirectories));\r\n if (indexDirectories != ledgerDirectories) {\r\n allLedgerDirs.addAll(Arrays.asList(indexDirectories));\r\n }\r\n try (RegistrationManager registrationManager = driver.createRegistrationManager()) {\r\n LegacyCookieValidation validation = new LegacyCookieValidation(bkConf, registrationManager);\r\n List dirs = Lists.newArrayList();\r\n dirs.addAll(Arrays.asList(journalDirectories));\r\n dirs.addAll(allLedgerDirs);\r\n validation.checkCookies(dirs);\r\n return true;\r\n } catch (BookieException e) {\r\n LOG.error(\"Exception while updating cookie for storage expansion\", e);\r\n return false;\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void parseURI(URI uri, Map parameters, LuceneComponent component) throws Exception{\r\n String protocol = uri.getScheme();\r\n if (!protocol.equalsIgnoreCase(\"lucene\")) {\r\n throw new IllegalArgumentException(\"Unrecognized Lucene protocol: \" + protocol + \" for uri: \" + uri);\r\n }\r\n this.uri = uri;\r\n this.authority = uri.getAuthority();\r\n if (!isValidAuthority()) {\r\n throw new URISyntaxException(uri.toASCIIString(), \"Incorrect URI syntax and/or Operation specified for the Lucene endpoint.\" + \" Please specify the syntax as \\\"lucene:[Endpoint Name]:[Operation]?[Query]\\\"\");\r\n }\r\n setHost(retrieveTokenFromAuthority(\"hostname\"));\r\n String op = retrieveTokenFromAuthority(\"operation\");\r\n if (op != null) {\r\n op = op.toLowerCase();\r\n }\r\n setOperation(LuceneOperation.valueOf(op));\r\n srcDir = component.resolveAndRemoveReferenceParameter(parameters, \"srcDir\", File.class, null);\r\n indexDir = component.resolveAndRemoveReferenceParameter(parameters, \"indexDir\", File.class, new File(\"file:///./indexDirectory\"));\r\n analyzer = component.resolveAndRemoveReferenceParameter(parameters, \"analyzer\", Analyzer.class, new StandardAnalyzer());\r\n setMaxHits(component.getAndRemoveParameter(parameters, \"maxHits\", Integer.class, 10));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Tries to find the base indent for supplied fragment\n *\n * @param xmlDocument where to look for the fragment\n * @param xmlFragment the fragment to look up\n * @return the found indent\n */\npublic static String determineIndent(String xmlDocument, String xmlFragment) {\n assert xmlDocument != null;\n assert xmlFragment != null;\n Pattern pattern = getPatternForFragment(xmlFragment);\n Matcher matcher = pattern.matcher(xmlDocument);\n if (!matcher.find()) {\n throw new RuntimeException(\"Could not match\");\n }\n return matcher.group(1);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private boolean bucketExists(String bucketName) throws Exception{\r\n return getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected DefaultMessageListenerContainer createDefaultListenerContainer() throws Exception{\r\n DefaultMessageListenerContainer answer;\r\n ReplyToType type = endpoint.getConfiguration().getReplyToType();\r\n if (type == null) {\r\n type = ReplyToType.Shared;\r\n }\r\n if (ReplyToType.Shared == type) {\r\n String replyToSelectorName = endpoint.getReplyToDestinationSelectorName();\r\n if (replyToSelectorName != null) {\r\n replyToSelectorValue = \"ID:\" + new BigInteger(24 * 8, new Random()).toString(16);\r\n String fixedMessageSelector = replyToSelectorName + \"='\" + replyToSelectorValue + \"'\";\r\n answer = new SharedQueueMessageListenerContainer(endpoint, fixedMessageSelector);\r\n log.debug(\"Using shared queue: {} with fixed message selector [{}] as reply listener: {}\", endpoint.getReplyTo(), fixedMessageSelector, answer);\r\n } else {\r\n dynamicMessageSelector = new MessageSelectorCreator(correlation);\r\n answer = new SharedQueueMessageListenerContainer(endpoint, dynamicMessageSelector);\r\n log.debug(\"Using shared queue: {} with dynamic message selector as reply listener: {}\", endpoint.getReplyTo(), answer);\r\n }\r\n log.warn(\"{} is using a shared reply queue, which is not as fast as alternatives.\" + \" See more detail at the section 'Request-reply over JMS' in the JMS component documentation\", endpoint);\r\n } else if (ReplyToType.Exclusive == type) {\r\n answer = new ExclusiveQueueMessageListenerContainer(endpoint);\r\n log.debug(\"Using exclusive queue: {} as reply listener: {}\", endpoint.getReplyTo(), answer);\r\n } else {\r\n throw new IllegalArgumentException(\"ReplyToType \" + type + \" is not supported for reply queues\");\r\n }\r\n String replyToCacheLevelName = endpoint.getConfiguration().getReplyToCacheLevelName();\r\n if (replyToCacheLevelName != null) {\r\n answer.setCacheLevelName(replyToCacheLevelName);\r\n log.debug(\"Setting the replyCacheLevel to be {}\", replyToCacheLevelName);\r\n }\r\n DestinationResolver resolver = endpoint.getDestinationResolver();\r\n if (resolver == null) {\r\n resolver = answer.getDestinationResolver();\r\n }\r\n answer.setDestinationResolver(new DestinationResolverDelegate(resolver));\r\n answer.setDestinationName(endpoint.getReplyTo());\r\n answer.setAutoStartup(true);\r\n answer.setIdleConsumerLimit(endpoint.getIdleConsumerLimit());\r\n answer.setIdleTaskExecutionLimit(endpoint.getIdleTaskExecutionLimit());\r\n if (endpoint.getMaxMessagesPerTask() >= 0) {\r\n answer.setMaxMessagesPerTask(endpoint.getMaxMessagesPerTask());\r\n }\r\n answer.setMessageListener(this);\r\n answer.setPubSubDomain(false);\r\n answer.setSubscriptionDurable(false);\r\n answer.setConcurrentConsumers(endpoint.getReplyToConcurrentConsumers());\r\n if (endpoint.getReplyToMaxConcurrentConsumers() > 0) {\r\n answer.setMaxConcurrentConsumers(endpoint.getReplyToMaxConcurrentConsumers());\r\n }\r\n answer.setConnectionFactory(endpoint.getConfiguration().getOrCreateConnectionFactory());\r\n setupClientId(endpoint, answer);\r\n answer.setSessionTransacted(false);\r\n if (endpoint.getExceptionListener() != null) {\r\n answer.setExceptionListener(endpoint.getExceptionListener());\r\n }\r\n if (endpoint.getErrorHandler() != null) {\r\n answer.setErrorHandler(endpoint.getErrorHandler());\r\n } else {\r\n answer.setErrorHandler(new DefaultSpringErrorHandler(endpoint.getCamelContext(), QueueReplyManager.class, endpoint.getErrorHandlerLoggingLevel(), endpoint.isErrorHandlerLogStackTrace()));\r\n }\r\n if (endpoint.getReceiveTimeout() >= 0) {\r\n answer.setReceiveTimeout(endpoint.getReceiveTimeout());\r\n }\r\n if (endpoint.getRecoveryInterval() >= 0) {\r\n answer.setRecoveryInterval(endpoint.getRecoveryInterval());\r\n }\r\n if (endpoint.getTaskExecutor() != null) {\r\n log.debug(\"Using custom TaskExecutor: {} on listener container: {}\", endpoint.getTaskExecutor(), answer);\r\n answer.setTaskExecutor(endpoint.getTaskExecutor());\r\n }\r\n String name = \"QueueReplyManager[\" + answer.getDestinationName() + \"]\";\r\n answer.setBeanName(name);\r\n if (answer.getConcurrentConsumers() > 1) {\r\n if (ReplyToType.Shared == type) {\r\n log.warn(\"Using {}-{} concurrent consumer on {} with shared queue {} may not work properly with all message brokers.\", answer.getConcurrentConsumers(), answer.getMaxConcurrentConsumers(), name, endpoint.getReplyTo());\r\n } else {\r\n log.info(\"Using {}-{} concurrent consumers on {}\", answer.getConcurrentConsumers(), answer.getMaxConcurrentConsumers(), name);\r\n }\r\n }\r\n return answer;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic URI getUri() {\n try {\n return new URI(getBase());\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `base_type` to the URL query string\n if (getBaseType() != null) {\n try {\n joiner.add(String.format(\"%sbase_type%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getBaseType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `element` to the URL query string\n if (getElement() != null) {\n try {\n joiner.add(String.format(\"%selement%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getElement()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `index` to the URL query string\n if (getIndex() != null) {\n try {\n joiner.add(String.format(\"%sindex%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getIndex()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private String getTheVidForThisLine(String graphSonLine) throws Exception{\r\n if (graphSonLine == null) {\r\n throw new Exception(\" ERROR - null graphSonLine passed to getTheVidForThisLine. \");\r\n }\r\n int x = graphSonLine.indexOf(':') + 1;\r\n int y = graphSonLine.indexOf(',');\r\n String initialVid = graphSonLine.substring(x, y);\r\n if (initialVid != null && !initialVid.isEmpty() && initialVid.matches(\"^[0-9]+$\")) {\r\n return initialVid;\r\n } else {\r\n throw new Exception(\" ERROR - could not determine initial VID for graphSonLine: \" + graphSonLine);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * A recursive function that serialize an object to a byte buffer based on its\n * object inspector.\n *\n * @param byteStream\n * the byte stream storing the serialization data\n * @param obj\n * the object to serialize\n * @param objInspector\n * the object inspector\n * @param skipLengthPrefix a boolean indicating whether length prefix is\n * needed for list/map/struct\n * @param warnedOnceNullMapKey a boolean indicating whether a warning\n * has been issued once already when encountering null map keys\n */\npublic static void serialize(RandomAccessOutput byteStream, Object obj, ObjectInspector objInspector, boolean skipLengthPrefix, BooleanRef warnedOnceNullMapKey) throws SerDeException {\n // do nothing for null object\n if (null == obj) {\n return;\n }\n switch(objInspector.getCategory()) {\n case PRIMITIVE:\n {\n PrimitiveObjectInspector poi = (PrimitiveObjectInspector) objInspector;\n switch(poi.getPrimitiveCategory()) {\n case VOID:\n {\n return;\n }\n case BOOLEAN:\n {\n boolean v = ((BooleanObjectInspector) poi).get(obj);\n byteStream.write((byte) (v ? 1 : 0));\n return;\n }\n case BYTE:\n {\n ByteObjectInspector boi = (ByteObjectInspector) poi;\n byte v = boi.get(obj);\n byteStream.write(v);\n return;\n }\n case SHORT:\n {\n ShortObjectInspector spoi = (ShortObjectInspector) poi;\n short v = spoi.get(obj);\n byteStream.write((byte) (v >> 8));\n byteStream.write((byte) (v));\n return;\n }\n case INT:\n {\n IntObjectInspector ioi = (IntObjectInspector) poi;\n int v = ioi.get(obj);\n LazyBinaryUtils.writeVInt(byteStream, v);\n return;\n }\n case LONG:\n {\n LongObjectInspector loi = (LongObjectInspector) poi;\n long v = loi.get(obj);\n LazyBinaryUtils.writeVLong(byteStream, v);\n return;\n }\n case FLOAT:\n {\n FloatObjectInspector foi = (FloatObjectInspector) poi;\n int v = Float.floatToIntBits(foi.get(obj));\n byteStream.write((byte) (v >> 24));\n byteStream.write((byte) (v >> 16));\n byteStream.write((byte) (v >> 8));\n byteStream.write((byte) (v));\n return;\n }\n case DOUBLE:\n {\n DoubleObjectInspector doi = (DoubleObjectInspector) poi;\n LazyBinaryUtils.writeDouble(byteStream, doi.get(obj));\n return;\n }\n case STRING:\n {\n StringObjectInspector soi = (StringObjectInspector) poi;\n Text t = soi.getPrimitiveWritableObject(obj);\n serializeText(byteStream, t, skipLengthPrefix);\n return;\n }\n case CHAR:\n {\n HiveCharObjectInspector hcoi = (HiveCharObjectInspector) poi;\n Text t = hcoi.getPrimitiveWritableObject(obj).getTextValue();\n serializeText(byteStream, t, skipLengthPrefix);\n return;\n }\n case VARCHAR:\n {\n HiveVarcharObjectInspector hcoi = (HiveVarcharObjectInspector) poi;\n Text t = hcoi.getPrimitiveWritableObject(obj).getTextValue();\n serializeText(byteStream, t, skipLengthPrefix);\n return;\n }\n case BINARY:\n {\n BinaryObjectInspector baoi = (BinaryObjectInspector) poi;\n BytesWritable bw = baoi.getPrimitiveWritableObject(obj);\n int length = bw.getLength();\n if (!skipLengthPrefix) {\n LazyBinaryUtils.writeVInt(byteStream, length);\n } else {\n if (length == 0) {\n throw new RuntimeException(\"LazyBinaryColumnarSerde cannot serialize a non-null zero \" + \"length binary field. Consider using either LazyBinarySerde or ColumnarSerde.\");\n }\n }\n byteStream.write(bw.getBytes(), 0, length);\n return;\n }\n case DATE:\n {\n DateWritableV2 d = ((DateObjectInspector) poi).getPrimitiveWritableObject(obj);\n writeDateToByteStream(byteStream, d);\n return;\n }\n case TIMESTAMP:\n {\n TimestampObjectInspector toi = (TimestampObjectInspector) poi;\n TimestampWritableV2 t = toi.getPrimitiveWritableObject(obj);\n t.writeToByteStream(byteStream);\n return;\n }\n case TIMESTAMPLOCALTZ:\n {\n TimestampLocalTZWritable t = ((TimestampLocalTZObjectInspector) poi).getPrimitiveWritableObject(obj);\n t.writeToByteStream(byteStream);\n return;\n }\n case INTERVAL_YEAR_MONTH:\n {\n HiveIntervalYearMonthWritable intervalYearMonth = ((HiveIntervalYearMonthObjectInspector) poi).getPrimitiveWritableObject(obj);\n intervalYearMonth.writeToByteStream(byteStream);\n return;\n }\n case INTERVAL_DAY_TIME:\n {\n HiveIntervalDayTimeWritable intervalDayTime = ((HiveIntervalDayTimeObjectInspector) poi).getPrimitiveWritableObject(obj);\n intervalDayTime.writeToByteStream(byteStream);\n return;\n }\n case DECIMAL:\n {\n HiveDecimalObjectInspector bdoi = (HiveDecimalObjectInspector) poi;\n HiveDecimalWritable t = bdoi.getPrimitiveWritableObject(obj);\n if (t == null) {\n return;\n }\n writeToByteStream(byteStream, t);\n return;\n }\n default:\n {\n throw new RuntimeException(\"Unrecognized type: \" + poi.getPrimitiveCategory());\n }\n }\n }\n case LIST:\n {\n ListObjectInspector loi = (ListObjectInspector) objInspector;\n ObjectInspector eoi = loi.getListElementObjectInspector();\n int byteSizeStart = 0;\n int listStart = 0;\n if (!skipLengthPrefix) {\n // 1/ reserve spaces for the byte size of the list\n // which is a integer and takes four bytes\n byteSizeStart = byteStream.getLength();\n byteStream.reserve(4);\n listStart = byteStream.getLength();\n }\n // 2/ write the size of the list as a VInt\n int size = loi.getListLength(obj);\n LazyBinaryUtils.writeVInt(byteStream, size);\n // 3/ write the null bytes\n byte nullByte = 0;\n for (int eid = 0; eid < size; eid++) {\n // set the bit to 1 if an element is not null\n if (null != loi.getListElement(obj, eid)) {\n nullByte |= 1 << (eid % 8);\n }\n // store the byte every eight elements or\n // if this is the last element\n if (7 == eid % 8 || eid == size - 1) {\n byteStream.write(nullByte);\n nullByte = 0;\n }\n }\n // 4/ write element by element from the list\n for (int eid = 0; eid < size; eid++) {\n serialize(byteStream, loi.getListElement(obj, eid), eoi, false, warnedOnceNullMapKey);\n }\n if (!skipLengthPrefix) {\n // 5/ update the list byte size\n int listEnd = byteStream.getLength();\n int listSize = listEnd - listStart;\n writeSizeAtOffset(byteStream, byteSizeStart, listSize);\n }\n return;\n }\n case MAP:\n {\n MapObjectInspector moi = (MapObjectInspector) objInspector;\n ObjectInspector koi = moi.getMapKeyObjectInspector();\n ObjectInspector voi = moi.getMapValueObjectInspector();\n Map map = moi.getMap(obj);\n int byteSizeStart = 0;\n int mapStart = 0;\n if (!skipLengthPrefix) {\n // 1/ reserve spaces for the byte size of the map\n // which is a integer and takes four bytes\n byteSizeStart = byteStream.getLength();\n byteStream.reserve(4);\n mapStart = byteStream.getLength();\n }\n // 2/ write the size of the map which is a VInt\n int size = map.size();\n LazyBinaryUtils.writeVInt(byteStream, size);\n // 3/ write the null bytes\n int b = 0;\n byte nullByte = 0;\n for (Map.Entry entry : map.entrySet()) {\n // set the bit to 1 if a key is not null\n if (null != entry.getKey()) {\n nullByte |= 1 << (b % 8);\n } else if (warnedOnceNullMapKey != null) {\n if (!warnedOnceNullMapKey.value) {\n LOG.warn(\"Null map key encountered! Ignoring similar problems.\");\n }\n warnedOnceNullMapKey.value = true;\n }\n b++;\n // set the bit to 1 if a value is not null\n if (null != entry.getValue()) {\n nullByte |= 1 << (b % 8);\n }\n b++;\n // write the byte to stream every 4 key-value pairs\n // or if this is the last key-value pair\n if (0 == b % 8 || b == size * 2) {\n byteStream.write(nullByte);\n nullByte = 0;\n }\n }\n // 4/ write key-value pairs one by one\n for (Map.Entry entry : map.entrySet()) {\n serialize(byteStream, entry.getKey(), koi, false, warnedOnceNullMapKey);\n serialize(byteStream, entry.getValue(), voi, false, warnedOnceNullMapKey);\n }\n if (!skipLengthPrefix) {\n // 5/ update the byte size of the map\n int mapEnd = byteStream.getLength();\n int mapSize = mapEnd - mapStart;\n writeSizeAtOffset(byteStream, byteSizeStart, mapSize);\n }\n return;\n }\n case STRUCT:\n case UNION:\n {\n int byteSizeStart = 0;\n int typeStart = 0;\n if (!skipLengthPrefix) {\n // 1/ reserve spaces for the byte size of the struct\n // which is a integer and takes four bytes\n byteSizeStart = byteStream.getLength();\n byteStream.reserve(4);\n typeStart = byteStream.getLength();\n }\n if (ObjectInspector.Category.STRUCT.equals(objInspector.getCategory())) {\n // 2/ serialize the struct\n serializeStruct(byteStream, obj, (StructObjectInspector) objInspector, warnedOnceNullMapKey);\n } else {\n // 2/ serialize the union\n serializeUnion(byteStream, obj, (UnionObjectInspector) objInspector, warnedOnceNullMapKey);\n }\n if (!skipLengthPrefix) {\n // 3/ update the byte size of the struct\n int typeEnd = byteStream.getLength();\n int typeSize = typeEnd - typeStart;\n writeSizeAtOffset(byteStream, byteSizeStart, typeSize);\n }\n return;\n }\n default:\n {\n throw new RuntimeException(\"Unrecognized type: \" + objInspector.getCategory());\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "static ObjectInspector getReflectionObjectInspector(Type t, ObjectInspectorOptions options, boolean ensureInited) {\n ObjectInspector oi = objectInspectorCache.asMap().get(t);\n if (oi == null) {\n oi = getReflectionObjectInspectorNoCache(t, options, ensureInited);\n ObjectInspector prev = objectInspectorCache.asMap().putIfAbsent(t, oi);\n if (prev != null) {\n oi = prev;\n }\n }\n if (ensureInited && oi instanceof ReflectionStructObjectInspector) {\n ReflectionStructObjectInspector soi = (ReflectionStructObjectInspector) oi;\n synchronized (soi) {\n HashSet checkedTypes = new HashSet();\n while (!soi.isFullyInited(checkedTypes)) {\n try {\n // Wait for up to 3 seconds before checking if any init error.\n // Init should be fast if no error, no need to make this configurable.\n soi.wait(3000);\n } catch (InterruptedException e) {\n throw new RuntimeException(\"Interrupted while waiting for \" + soi.getClass().getName() + \" to initialize\", e);\n }\n }\n }\n }\n verifyObjectInspector(options, oi, ObjectInspectorOptions.JAVA, new Class[] { ThriftStructObjectInspector.class, ProtocolBuffersStructObjectInspector.class });\n verifyObjectInspector(options, oi, ObjectInspectorOptions.THRIFT, new Class[] { ReflectionStructObjectInspector.class, ProtocolBuffersStructObjectInspector.class });\n verifyObjectInspector(options, oi, ObjectInspectorOptions.PROTOCOL_BUFFERS, new Class[] { ThriftStructObjectInspector.class, ReflectionStructObjectInspector.class });\n return oi;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic Map next() {\n try {\n Map record = new HashMap(hiveColumnNames.length);\n for (int i = 0; i < hiveColumnNames.length; i++) {\n String key = hiveColumnNames[i];\n Object value = null;\n if (!(hiveColumnTypesList.get(i) instanceof PrimitiveTypeInfo)) {\n throw new RuntimeException(\"date type of column \" + hiveColumnNames[i] + \":\" + hiveColumnTypesList.get(i).getTypeName() + \" is not supported\");\n }\n try {\n switch(((PrimitiveTypeInfo) hiveColumnTypesList.get(i)).getPrimitiveCategory()) {\n case INT:\n case SHORT:\n case BYTE:\n value = rs.getInt(i + 1);\n break;\n case LONG:\n value = rs.getLong(i + 1);\n break;\n case FLOAT:\n value = rs.getFloat(i + 1);\n break;\n case DOUBLE:\n value = rs.getDouble(i + 1);\n break;\n case DECIMAL:\n value = rs.getBigDecimal(i + 1);\n break;\n case BOOLEAN:\n boolean b = rs.getBoolean(i + 1);\n if (b && rs.getMetaData().getColumnType(i + 1) == Types.CHAR) {\n // also accept Y/N in case of CHAR(1) - datanucleus stores booleans in CHAR(1) fields for derby\n b = !\"N\".equals(rs.getString(i + 1));\n }\n value = b;\n break;\n case CHAR:\n case VARCHAR:\n case STRING:\n value = rs.getString(i + 1);\n break;\n case DATE:\n value = rs.getDate(i + 1);\n break;\n case TIMESTAMP:\n value = rs.getTimestamp(i + 1);\n break;\n default:\n LOGGER.error(\"date type of column \" + hiveColumnNames[i] + \":\" + ((PrimitiveTypeInfo) hiveColumnTypesList.get(i)).getPrimitiveCategory() + \" is not supported\");\n value = null;\n break;\n }\n if (value != null && !rs.wasNull()) {\n record.put(key, value);\n } else {\n record.put(key, null);\n }\n } catch (SQLDataException e) {\n record.put(key, null);\n }\n }\n return record;\n } catch (Exception e) {\n LOGGER.warn(\"next() threw exception\", e);\n if (e instanceof SQLException) {\n throw new RuntimeException(e);\n }\n return null;\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `node` to the URL query string\n if (getNode() != null) {\n try {\n joiner.add(String.format(\"%snode%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getNode()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `schema` to the URL query string\n if (getSchema() != null) {\n try {\n joiner.add(String.format(\"%sschema%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getSchema()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `value` to the URL query string\n if (getValue() != null) {\n try {\n joiner.add(String.format(\"%svalue%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getValue()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `timestamp` to the URL query string\n if (getTimestamp() != null) {\n try {\n joiner.add(String.format(\"%stimestamp%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getTimestamp()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "/**\n * Set to contain the contents of a string.\n * @param string input string.\n */\npublic void set(String string) {\n if (string.length() > 0xffff / 3) {\n // maybe too long\n LOG.warn(\"truncating long string: \" + string.length() + \" chars, starting with \" + string.substring(0, 20));\n string = string.substring(0, 0xffff / 3);\n }\n // compute length\n length = utf8Length(string);\n if (// double-check length\n length > 0xffff)\n throw new RuntimeException(\"string too long!\");\n if (// grow buffer\n bytes == null || length > bytes.length)\n bytes = new byte[length];\n try {\n // avoid sync'd allocations\n DataOutputBuffer obuf = OBUF_FACTORY.get();\n obuf.reset();\n writeChars(obuf, string, 0, string.length());\n System.arraycopy(obuf.getData(), 0, bytes, 0, length);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private Serializer createSerializerInstanceWithFallback(Class serializationType, String className) throws Exception{\r\n Class clazz = ClassLoaderUtil.loadClass(classLoader, className);\r\n try {\r\n Constructor constructor = clazz.getDeclaredConstructor(Class.class);\r\n constructor.setAccessible(true);\r\n return (Serializer) constructor.newInstance(serializationType);\r\n } catch (NoSuchMethodException e) {\r\n Constructor constructor = clazz.getDeclaredConstructor();\r\n constructor.setAccessible(true);\r\n return (Serializer) constructor.newInstance();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\npublic static Map fetchConfigProperties() throws Exception {\n Map properties = new HashMap<>();\n String base64Creds = System.getenv(Constants.CONFIG_CREDS);\n ObjectMapper objectMapper = new ObjectMapper();\n try {\n Map jobSchedulerProps = new HashMap<>();\n Map response = objectMapper.readValue(Util.httpGetMethodWithHeaders(configUrl, Util.getHeader(base64Creds)), new TypeReference>() {\n });\n List> propertySources = (List>) response.get(\"propertySources\");\n for (Map propertySource : propertySources) {\n if (propertySource.get(Constants.NAME).toString().contains(Constants.JOB_SCHEDULER)) {\n jobSchedulerProps.putAll((Map) propertySource.get(Constants.SOURCE));\n }\n properties.putAll(jobSchedulerProps);\n }\n } catch (Exception e) {\n log.error(\"Error in fetchConfigProperties\", e);\n throw e;\n }\n if (properties.isEmpty()) {\n throw new Exception(\"No config properties fetched from \" + configUrl);\n }\n log.info(\"Config are fetched from {}\", configUrl);\n return properties;\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "public boolean importedkeys(String line) throws Exception{\r\n return metadata(\"getImportedKeys\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"table name\") });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception{\r\n Class clazz = testInstance.getClass();\r\n java.util.List fields = hierarchy(clazz).map(Class::getDeclaredFields).flatMap(Stream::of).filter(f -> isAnnotated(f, Parameter.class)).sorted(Comparator.comparing(f -> (Integer) f.getAnnotation(Parameter.class).value())).toList();\r\n if (params.length != fields.size()) {\r\n throw new TestInstantiationException(\"Expected \" + fields.size() + \" parameters bug got \" + params.length + \" when instantiating \" + clazz.getName());\r\n }\r\n for (int i = 0; i < fields.size(); i++) {\r\n Field f = fields.get(i);\r\n f.setAccessible(true);\r\n f.set(testInstance, DefaultArgumentConverter.INSTANCE.convert(params[i], f.getType(), getContext()));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean tryProcess(int ordinal, @Nonnull Object item) throws Exception{\r\n throw new UnsupportedOperationException(\"Missing implementation in \" + getClass());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Configuration validateConfigBeforeCtor(Configuration conf) {\n // Ensure there's no threadlocal. We don't expect one.\n setCurator(null);\n // We don't ever want to create key paths with world visibility. Why is that even an option?!!\n String authType = conf.get(ZK_DTSM_ZK_AUTH_TYPE);\n if (!\"sasl\".equals(authType)) {\n throw new RuntimeException(\"Inconsistent configuration: secure cluster, but ZK auth is \" + authType + \" instead of sasl\");\n }\n return conf;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Sets a key-value pair on the RecordStore.\n *\n * @param key must start with \"source.\", \"transaction.\" or \"destination.\"\n * @param value the value to associate with the key.\n */\n@Override\npublic void set(final String key, final String value) {\n int dividerPosition = key.indexOf('.');\n int typeStartPosition = key.indexOf('<');\n int typeEndPosition = key.indexOf('>');\n String keyDescriptor = key.substring(0, dividerPosition);\n String keyAttribute;\n String keyType;\n if (typeStartPosition == -1) {\n keyAttribute = key.substring(dividerPosition + 1);\n keyType = \"string\";\n } else {\n keyAttribute = key.substring(dividerPosition + 1, typeStartPosition);\n keyType = key.substring(typeStartPosition + 1, typeEndPosition);\n }\n int id;\n GraphElementType elementType;\n switch(keyDescriptor) {\n case \"source\":\n id = currentSourceVertex;\n elementType = GraphElementType.VERTEX;\n break;\n case \"destination\":\n id = currentDestinationVertex;\n elementType = GraphElementType.VERTEX;\n break;\n case \"transaction\":\n id = currentTransaction;\n elementType = GraphElementType.TRANSACTION;\n break;\n default:\n throw new RuntimeException(\"key must start with source, transaction or destination.\");\n }\n int attribute = getAttribute(elementType, keyAttribute);\n if (attribute == Graph.NOT_FOUND) {\n attribute = getSchema().getFactory().ensureAttribute(this, elementType, keyAttribute);\n if (attribute == Graph.NOT_FOUND) {\n attribute = addAttribute(elementType, keyType, keyAttribute, \"\", null, null);\n }\n }\n setStringValue(attribute, id, value);\n}", "smellKey": "S112", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "// This method tries to merge the join with its left child. The left\n// child should be a join for this to happen.\nprivate static RelNode mergeJoin(HiveJoin join, RelNode left, RelNode right) {\n final RexBuilder rexBuilder = join.getCluster().getRexBuilder();\n // We check whether the join can be combined with any of its children\n final List newInputs = Lists.newArrayList();\n final List newJoinCondition = Lists.newArrayList();\n final List> joinInputs = Lists.newArrayList();\n final List joinTypes = Lists.newArrayList();\n final List joinFilters = Lists.newArrayList();\n // Left child\n if (left instanceof HiveJoin || left instanceof HiveMultiJoin) {\n final RexNode leftCondition;\n final List> leftJoinInputs;\n final List leftJoinTypes;\n final List leftJoinFilters;\n boolean combinable;\n if (left instanceof HiveJoin) {\n HiveJoin hj = (HiveJoin) left;\n leftCondition = hj.getCondition();\n leftJoinInputs = ImmutableList.of(Pair.of(0, 1));\n leftJoinTypes = ImmutableList.of(hj.getJoinType());\n leftJoinFilters = ImmutableList.of(hj.getJoinFilter());\n try {\n combinable = isCombinableJoin(join, hj);\n } catch (CalciteSemanticException e) {\n LOG.trace(\"Failed to merge join-join\", e);\n combinable = false;\n }\n } else {\n HiveMultiJoin hmj = (HiveMultiJoin) left;\n leftCondition = hmj.getCondition();\n leftJoinInputs = hmj.getJoinInputs();\n leftJoinTypes = hmj.getJoinTypes();\n leftJoinFilters = hmj.getJoinFilters();\n try {\n combinable = isCombinableJoin(join, hmj);\n } catch (CalciteSemanticException e) {\n LOG.trace(\"Failed to merge join-multijoin\", e);\n combinable = false;\n }\n }\n if (combinable) {\n newJoinCondition.add(leftCondition);\n for (int i = 0; i < leftJoinInputs.size(); i++) {\n joinInputs.add(leftJoinInputs.get(i));\n joinTypes.add(leftJoinTypes.get(i));\n joinFilters.add(leftJoinFilters.get(i));\n }\n newInputs.addAll(left.getInputs());\n } else {\n // The join operation in the child is not on the same keys\n return null;\n }\n } else {\n // The left child is not a join or multijoin operator\n return null;\n }\n final int numberLeftInputs = newInputs.size();\n // Right child\n newInputs.add(right);\n // If we cannot combine any of the children, we bail out\n newJoinCondition.add(join.getCondition());\n if (newJoinCondition.size() == 1) {\n return null;\n }\n final List systemFieldList = ImmutableList.of();\n List> joinKeyExprs = new ArrayList>();\n List filterNulls = new ArrayList();\n for (int i = 0; i < newInputs.size(); i++) {\n joinKeyExprs.add(new ArrayList());\n }\n RexNode filters;\n try {\n filters = HiveRelOptUtil.splitHiveJoinCondition(systemFieldList, newInputs, join.getCondition(), joinKeyExprs, filterNulls, null);\n } catch (CalciteSemanticException e) {\n LOG.trace(\"Failed to merge joins\", e);\n return null;\n }\n ImmutableBitSet.Builder keysInInputsBuilder = ImmutableBitSet.builder();\n for (int i = 0; i < newInputs.size(); i++) {\n List partialCondition = joinKeyExprs.get(i);\n if (!partialCondition.isEmpty()) {\n keysInInputsBuilder.set(i);\n }\n }\n // If we cannot merge, we bail out\n ImmutableBitSet keysInInputs = keysInInputsBuilder.build();\n ImmutableBitSet leftReferencedInputs = keysInInputs.intersect(ImmutableBitSet.range(numberLeftInputs));\n ImmutableBitSet rightReferencedInputs = keysInInputs.intersect(ImmutableBitSet.range(numberLeftInputs, newInputs.size()));\n if (join.getJoinType() != JoinRelType.INNER && (leftReferencedInputs.cardinality() > 1 || rightReferencedInputs.cardinality() > 1)) {\n return null;\n }\n // Otherwise, we add to the join specs\n if (join.getJoinType() != JoinRelType.INNER) {\n int leftInput = keysInInputs.nextSetBit(0);\n int rightInput = keysInInputs.nextSetBit(numberLeftInputs);\n joinInputs.add(Pair.of(leftInput, rightInput));\n joinTypes.add(join.getJoinType());\n joinFilters.add(filters);\n } else {\n for (int i : leftReferencedInputs) {\n for (int j : rightReferencedInputs) {\n joinInputs.add(Pair.of(i, j));\n joinTypes.add(join.getJoinType());\n joinFilters.add(filters);\n }\n }\n }\n // We can now create a multijoin operator\n RexNode newCondition = RexUtil.flatten(rexBuilder, RexUtil.composeConjunction(rexBuilder, newJoinCondition, false));\n List newInputsArray = Lists.newArrayList(newInputs);\n JoinPredicateInfo joinPredInfo = null;\n try {\n joinPredInfo = HiveCalciteUtil.JoinPredicateInfo.constructJoinPredicateInfo(newInputsArray, systemFieldList, newCondition);\n } catch (CalciteSemanticException e) {\n throw new RuntimeException(e);\n }\n // If the number of joins < number of input tables-1, this is not a star join.\n if (joinPredInfo.getEquiJoinPredicateElements().size() < newInputs.size() - 1) {\n return null;\n }\n // Validate that the multi-join is a valid star join before returning it.\n for (int i = 0; i < newInputs.size(); i++) {\n List joinKeys = null;\n for (int j = 0; j < joinPredInfo.getEquiJoinPredicateElements().size(); j++) {\n List currJoinKeys = joinPredInfo.getEquiJoinPredicateElements().get(j).getJoinExprs(i);\n if (currJoinKeys.isEmpty()) {\n continue;\n }\n if (joinKeys == null) {\n joinKeys = currJoinKeys;\n } else {\n // If we join on different keys on different tables, we can no longer apply\n // multi-join conversion as this is no longer a valid star join.\n // Bail out if this is the case.\n if (!joinKeys.containsAll(currJoinKeys) || !currJoinKeys.containsAll(joinKeys)) {\n return null;\n }\n }\n }\n }\n return new HiveMultiJoin(join.getCluster(), newInputsArray, newCondition, join.getRowType(), joinInputs, joinTypes, joinFilters, joinPredInfo);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@HiveDecimalWritableVersionV2\npublic int scale() {\n if (!isSet()) {\n throw new RuntimeException(\"no value set\");\n }\n return fastScale();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static long deserializeLongKey(BinarySortableDeserializeRead keyBinarySortableDeserializeRead, HashTableKeyType hashTableKeyType) throws RuntimeException {\n long key = 0;\n switch(hashTableKeyType) {\n case BOOLEAN:\n key = (keyBinarySortableDeserializeRead.currentBoolean ? 1 : 0);\n break;\n case BYTE:\n key = (long) keyBinarySortableDeserializeRead.currentByte;\n break;\n case SHORT:\n key = (long) keyBinarySortableDeserializeRead.currentShort;\n break;\n case INT:\n key = (long) keyBinarySortableDeserializeRead.currentInt;\n break;\n case DATE:\n key = (long) keyBinarySortableDeserializeRead.currentDateWritable.getDays();\n break;\n case LONG:\n key = keyBinarySortableDeserializeRead.currentLong;\n break;\n default:\n throw new RuntimeException(\"Unexpected hash table key type \" + hashTableKeyType.name());\n }\n return key;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private int executeIncrementalLoad(long loadStartTime) throws Exception {\n // If replication policy is changed between previous and current repl load, then drop the tables\n // that are excluded in the new replication policy.\n if (work.replScopeModified) {\n dropTablesExcludedInReplScope(work.currentReplScope);\n }\n Database targetDb = getHive().getDatabase(work.dbNameToLoadIn);\n Map props = new HashMap<>();\n // check if db is set READ_ONLY, if not then set it. Basically this ensures backward\n // compatibility.\n if (!isDbReadOnly(targetDb) && isReadOnlyHookRegistered()) {\n setDbReadOnly();\n }\n // Check if it is a optimised bootstrap failover.\n if (work.isFirstFailover) {\n // Check it should be marked as target of replication & not source of replication.\n if (MetaStoreUtils.isTargetOfReplication(targetDb)) {\n LOG.error(\"The database {} is already marked as target for replication\", targetDb.getName());\n throw new Exception(\"Failover target is already marked as target\");\n }\n if (!ReplChangeManager.isSourceOfReplication(targetDb)) {\n LOG.error(\"The database {} is already source of replication.\", targetDb.getName());\n throw new Exception(\"Failover target was not source of replication\");\n }\n Map params = targetDb.getParameters();\n if (params == null) {\n params = new HashMap<>();\n }\n long failbackStartTime = System.currentTimeMillis();\n params.put(ReplConst.REPL_METRICS_LAST_FAILBACK_STARTTIME, Long.toString(failbackStartTime));\n LOG.info(\"Replication Metrics: Setting replication metrics failback starttime for database: {} to: {} \", targetDb.getName(), failbackStartTime);\n if (!MetaStoreUtils.isDbBeingPlannedFailedOver(targetDb)) {\n // if this is failback due to unplanned failover\n LOG.info(\"Replication Metrics: Setting last failover type for database: {} to: {} \", targetDb.getName(), ReplConst.FailoverType.UNPLANNED.toString());\n params.put(ReplConst.REPL_METRICS_LAST_FAILOVER_TYPE, ReplConst.FailoverType.UNPLANNED.toString());\n int failoverCount = 1 + NumberUtils.toInt(params.getOrDefault(ReplConst.REPL_METRICS_FAILOVER_COUNT, \"0\"), 0);\n LOG.info(\"Replication Metrics: Setting replication metrics failover count for database: {} to: {} \", targetDb.getName(), failoverCount);\n params.put(ReplConst.REPL_METRICS_FAILOVER_COUNT, Integer.toString(failoverCount));\n }\n work.getMetricCollector().reportStageStart(STAGE_NAME, new HashMap<>());\n boolean isTableDiffPresent = checkFileExists(new Path(work.dumpDirectory).getParent(), conf, TABLE_DIFF_COMPLETE_DIRECTORY);\n boolean isAbortTxnsListPresent = checkFileExists(new Path(work.dumpDirectory).getParent(), conf, OptimisedBootstrapUtils.ABORT_TXNS_FILE);\n Long eventId = Long.parseLong(getEventIdFromFile(new Path(work.dumpDirectory).getParent(), conf)[0]);\n List notificationEvents = OptimisedBootstrapUtils.getListOfNotificationEvents(eventId, getHive(), work);\n if (!isAbortTxnsListPresent) {\n //Abort the ongoing transactions(opened prior to failover) for the target database.\n HiveTxnManager hiveTxnManager = getTxnMgr();\n ValidTxnList validTxnList = hiveTxnManager.getValidTxns(excludedTxns);\n Set allOpenTxns = new HashSet<>(ReplUtils.getOpenTxns(validTxnList));\n abortOpenTxnsForDatabase(hiveTxnManager, validTxnList, work.dbNameToLoadIn, getHive());\n //Re-fetch the list of notification events post failover eventId.\n notificationEvents = OptimisedBootstrapUtils.getListOfNotificationEvents(eventId, getHive(), work);\n OptimisedBootstrapUtils.prepareAbortTxnsFile(notificationEvents, allOpenTxns, new Path(work.dumpDirectory).getParent(), conf);\n }\n if (!isTableDiffPresent) {\n prepareTableDiffFile(notificationEvents, getHive(), work, conf);\n }\n if (this.childTasks == null) {\n this.childTasks = new ArrayList<>();\n }\n createReplLoadCompleteAckTask();\n work.getMetricCollector().reportStageEnd(STAGE_NAME, Status.SUCCESS);\n if (Boolean.parseBoolean(targetDb.getParameters().get(REPL_RESUME_STARTED_AFTER_FAILOVER))) {\n work.getMetricCollector().reportEnd(Status.RESUME_READY);\n } else {\n work.getMetricCollector().reportEnd(Status.SUCCESS);\n }\n targetDb.setParameters(params);\n getHive().alterDatabase(work.dbNameToLoadIn, targetDb);\n return 0;\n } else if (work.isSecondFailover) {\n // DROP the tables extra on target, which are not on source cluster.\n Hive db = getHive();\n for (String table : work.tablesToDrop) {\n LOG.info(\"Dropping table {} for optimised bootstrap\", work.dbNameToLoadIn + \".\" + table);\n db.dropTable(work.dbNameToLoadIn + \".\" + table, true);\n }\n //This sourceDb was the actual target prior to failover.\n Database sourceDb = getSourceDbMetadata();\n Map sourceDbProps = sourceDb.getParameters();\n Map targetDbProps = new HashMap<>(targetDb.getParameters());\n for (String key : MetaStoreUtils.getReplicationDbProps()) {\n //Replication Props will be handled separately as part of preAckTask.\n targetDbProps.remove(key);\n }\n for (Map.Entry currProp : targetDbProps.entrySet()) {\n String actualVal = sourceDbProps.get(currProp.getKey());\n if (!currProp.getValue().equals(actualVal)) {\n props.put(currProp.getKey(), (actualVal == null) ? \"\" : actualVal);\n }\n }\n AlterDatabaseSetOwnerDesc alterDbDesc = new AlterDatabaseSetOwnerDesc(sourceDb.getName(), new PrincipalDesc(sourceDb.getOwnerName(), sourceDb.getOwnerType()), null);\n DDLWork ddlWork = new DDLWork(new HashSet<>(), new HashSet<>(), alterDbDesc, true, (new Path(work.dumpDirectory)).getParent().toString(), work.getMetricCollector());\n if (this.childTasks == null) {\n this.childTasks = new ArrayList<>();\n }\n this.childTasks.add(TaskFactory.get(ddlWork, conf));\n }\n if (!MetaStoreUtils.isTargetOfReplication(targetDb)) {\n props.put(ReplConst.TARGET_OF_REPLICATION, ReplConst.TRUE);\n }\n if (!work.shouldFailover() && MetaStoreUtils.isDbBeingPlannedFailedOver(targetDb)) {\n props.put(ReplConst.REPL_FAILOVER_ENDPOINT, \"\");\n }\n if (!props.isEmpty()) {\n AlterDatabaseSetPropertiesDesc setTargetDesc = new AlterDatabaseSetPropertiesDesc(work.dbNameToLoadIn, props, null);\n Task addReplTargetPropTask = TaskFactory.get(new DDLWork(new HashSet<>(), new HashSet<>(), setTargetDesc, true, work.dumpDirectory, work.getMetricCollector()), conf);\n if (this.childTasks == null) {\n this.childTasks = new ArrayList<>();\n }\n this.childTasks.add(addReplTargetPropTask);\n }\n IncrementalLoadTasksBuilder builder = work.incrementalLoadTasksBuilder();\n // If incremental events are already applied, then check and perform if need to bootstrap any tables.\n if (!builder.hasMoreWork() && work.isLastReplIDUpdated()) {\n if (work.hasBootstrapLoadTasks()) {\n LOG.debug(\"Current incremental dump have tables to be bootstrapped. Switching to bootstrap \" + \"mode after applying all events.\");\n return executeBootStrapLoad();\n }\n }\n List> childTasks = new ArrayList<>();\n int maxTasks = conf.getIntVar(HiveConf.ConfVars.REPL_APPROX_MAX_LOAD_TASKS);\n TaskTracker tracker = new TaskTracker(maxTasks);\n addLazyDataCopyTask(tracker, builder.getReplLogger());\n childTasks.add(builder.build(context, getHive(), LOG, tracker));\n // If there are no more events to be applied, add a task to update the last.repl.id of the\n // target database to the event id of the last event considered by the dump. Next\n // incremental cycle won't consider the events in this dump again if it starts from this id.\n if (!builder.hasMoreWork()) {\n // The name of the database to be loaded into is either specified directly in REPL LOAD\n // command i.e. when dbNameToLoadIn has a valid dbname or is available through dump\n // metadata during table level replication.\n String dbName = work.dbNameToLoadIn;\n if (dbName == null || StringUtils.isBlank(dbName)) {\n if (work.currentReplScope != null) {\n String replScopeDbName = work.currentReplScope.getDbName();\n if (replScopeDbName != null && !\"*\".equals(replScopeDbName)) {\n dbName = replScopeDbName;\n }\n }\n }\n // If we are replicating to multiple databases at a time, it's not\n // possible to know which all databases we are replicating into and hence we can not\n // update repl id in all those databases.\n if (StringUtils.isNotBlank(dbName)) {\n String lastEventid = builder.eventTo().toString();\n Map mapProp = new HashMap<>();\n mapProp.put(ReplicationSpec.KEY.CURR_STATE_ID_SOURCE.toString(), lastEventid);\n AlterDatabaseSetPropertiesDesc alterDbDesc = new AlterDatabaseSetPropertiesDesc(dbName, mapProp, new ReplicationSpec(lastEventid, lastEventid));\n Task updateReplIdTask = TaskFactory.get(new DDLWork(new HashSet<>(), new HashSet<>(), alterDbDesc, true, (new Path(work.dumpDirectory).getParent()).toString(), work.getMetricCollector()), conf);\n DAGTraversal.traverse(childTasks, new AddDependencyToLeaves(updateReplIdTask));\n work.setLastReplIDUpdated(true);\n LOG.debug(\"Added task to set last repl id of db \" + dbName + \" to \" + lastEventid);\n }\n }\n // Once all the incremental events are applied, enable bootstrap of tables if exist.\n if (builder.hasMoreWork() || work.hasBootstrapLoadTasks()) {\n DAGTraversal.traverse(childTasks, new AddDependencyToLeaves(TaskFactory.get(work, conf)));\n }\n if (this.childTasks == null) {\n this.childTasks = new ArrayList<>();\n }\n this.childTasks.addAll(childTasks);\n createReplLoadCompleteAckTask();\n // Clean-up snapshots\n if (conf.getBoolVar(REPL_SNAPSHOT_DIFF_FOR_EXTERNAL_TABLE_COPY)) {\n cleanupSnapshots(new Path(work.getDumpDirectory()).getParent().getParent().getParent(), work.getSourceDbName().toLowerCase(), conf, null, true);\n }\n //pass the current time at the end of repl-load stage as the starting time of the first event.\n long currentTimestamp = System.currentTimeMillis();\n ((IncrementalLoadLogger) work.incrementalLoadTasksBuilder().getReplLogger()).initiateEventTimestamp(currentTimestamp);\n LOG.info(\"REPL_INCREMENTAL_LOAD stage duration : {} ms\", currentTimestamp - loadStartTime);\n return 0;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * We will truncate the tables, iterate through each table individually,\n * and then clean the tables.\n */\nprivate void truncateTable() {\n Connection connection = null;\n try {\n connection = getConnection(false);\n FederationQueryRunner runner = new FederationQueryRunner();\n for (String table : TABLES) {\n LOG.info(\"truncate table = {} start.\", table);\n runner.truncateTable(connection, table);\n LOG.info(\"truncate table = {} finished.\", table);\n }\n } catch (Exception e) {\n throw new RuntimeException(\"Could not truncate table!\", e);\n } finally {\n // Return to the pool the CallableStatement\n try {\n FederationStateStoreUtils.returnToPool(LOG, null, connection);\n } catch (YarnException e) {\n LOG.error(\"close connection error.\", e);\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected Cache doGetCache(JCacheProvider jcacheProvider) throws Exception{\r\n if (cache == null) {\r\n String uri = configuration.getConfigurationUri();\r\n if (uri != null && camelContext != null) {\r\n uri = camelContext.resolvePropertyPlaceholders(uri);\r\n }\r\n provider = ObjectHelper.isNotEmpty(jcacheProvider.className()) ? Caching.getCachingProvider(jcacheProvider.className()) : Caching.getCachingProvider();\r\n manager = provider.getCacheManager(ObjectHelper.isNotEmpty(uri) ? URI.create(uri) : null, null, configuration.getCacheConfigurationProperties());\r\n cache = manager.getCache(cacheName);\r\n if (cache == null) {\r\n if (!configuration.isCreateCacheIfNotExists()) {\r\n throw new IllegalStateException(\"Cache \" + cacheName + \" does not exist and should not be created (createCacheIfNotExists=false)\");\r\n }\r\n cache = manager.createCache(cacheName, getOrCreateCacheConfiguration());\r\n }\r\n }\r\n return cache;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void write(DataOutput out) throws IOException {\n throw new RuntimeException(\"Not supported.\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private String readImage(final Exchange exchange, final InputStream stream) throws Exception{\r\n final MultiFormatReader reader = new MultiFormatReader();\r\n final BufferedInputStream in = exchange.getContext().getTypeConverter().mandatoryConvertTo(BufferedInputStream.class, stream);\r\n final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(in))));\r\n final Result result = reader.decode(bitmap, readerHintMap);\r\n exchange.getOut().setHeader(Barcode.BARCODE_FORMAT, result.getBarcodeFormat());\r\n if (result.getResultMetadata() != null) {\r\n result.getResultMetadata().forEach((k, v) -> {\r\n exchange.getOut().setHeader(k.toString(), v);\r\n });\r\n }\r\n return result.getText();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/* Release all locks - including PERSISTENT locks */\npublic static void releaseAllLocks(HiveConf conf) throws Exception {\n try {\n String parent = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_NAMESPACE);\n List locks = getLocks(conf, null, parent, false, false);\n Exception lastExceptionGot = null;\n if (locks != null) {\n for (HiveLock lock : locks) {\n try {\n unlockPrimitive(lock, parent, curatorFramework);\n } catch (Exception e) {\n lastExceptionGot = e;\n }\n }\n }\n // if we got exception during doing the unlock, rethrow it here\n if (lastExceptionGot != null) {\n throw lastExceptionGot;\n }\n } catch (Exception e) {\n LOG.error(\"Failed to release all locks: \", e);\n throw new Exception(ErrorMsg.ZOOKEEPER_CLIENT_COULD_NOT_BE_INITIALIZED.getMsg());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic void run() {\n while (true) {\n try {\n jvmMetrics.setJvmMetrics();\n exposeMetricsToOTEL();\n } catch (Throwable e) {\n LOG.error(\"Exception occurred in OTELExporter thread \", e);\n }\n try {\n Thread.sleep(frequency);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private boolean bucketExists(String bucketName) throws Exception{\r\n return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void initNewStore(NetworkParameters params) throws Exception{\r\n byte[] header;\r\n header = HEADER_MAGIC.getBytes(\"US-ASCII\");\r\n buffer.put(header);\r\n lock.lock();\r\n try {\r\n setRingCursor(buffer, FILE_PROLOGUE_BYTES);\r\n } finally {\r\n lock.unlock();\r\n }\r\n LiteBlock genesis = Genesis.getHeaderFor(params.getNet());\r\n put(genesis);\r\n setChainHead(genesis);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public final Iterator iterator() {\n ensureOpen();\n // load the volume descriptors if necessary\n if (null == this.volumeDescriptorSet) {\n try {\n loadVolumeDescriptors();\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n return iterator(this.volumeDescriptorSet.getRootEntry());\n}", "smellKey": "S112", "smellId": null, "repo": "ihhub_fheroes2", "language": "java"} {"function": "public int compareTo(Item item) {\n if (item == null) {\n // 1.0 == 1, 1.1 > 1\n return BIG_INTEGER_ZERO.equals(value) ? 0 : 1;\n }\n switch(item.getType()) {\n case INTEGER_ITEM:\n return value.compareTo(((IntegerItem) item).value);\n case STRING_ITEM:\n // 1.1 > 1-sp\n return 1;\n case LIST_ITEM:\n // 1.1 > 1-1\n return 1;\n default:\n throw new RuntimeException(\"invalid item: \" + item.getClass());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void testForResponseCode(int returnCode, SdkHttpMethod method) throws Exception{\r\n SdkHttpClient client = createSdkHttpClient();\r\n stubForMockRequest(returnCode);\r\n SdkHttpFullRequest req = mockSdkRequest(\"http://localhost:\" + mockServer.port(), method);\r\n HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder().request(req).contentStreamProvider(req.contentStreamProvider().orElse(null)).build()).call();\r\n validateResponse(rsp, returnCode, method);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@VisibleForTesting\nvoid inlineJoinOp() throws Exception {\n // inline map join operator\n if (this.type == OpType.MAPJOIN) {\n // get the map for posToVertex\n Map posToVertex = new LinkedHashMap<>();\n if (opObject.has(\"input vertices:\")) {\n JSONObject vertexObj = opObject.getJSONObject(\"input vertices:\");\n for (String pos : JSONObject.getNames(vertexObj)) {\n String vertexName = vertexObj.getString(pos);\n // update the connection\n Connection c = null;\n for (Connection connection : vertex.parentConnections) {\n if (connection.from.name.equals(vertexName)) {\n posToVertex.put(pos, connection.from);\n c = connection;\n break;\n }\n }\n if (c != null) {\n parser.addInline(this, c);\n }\n }\n // update the attrs\n this.attrs.remove(\"input vertices:\");\n }\n // update the keys to use operator name\n JSONObject keys = opObject.getJSONObject(\"keys:\");\n // find out the vertex for the big table\n Set parentVertexes = new HashSet<>();\n for (Connection connection : vertex.parentConnections) {\n parentVertexes.add(connection.from);\n }\n parentVertexes.removeAll(posToVertex.values());\n Map posToOpId = new LinkedHashMap<>();\n if (keys.length() != 0) {\n for (String key : JSONObject.getNames(keys)) {\n // first search from the posToVertex\n if (posToVertex.containsKey(key)) {\n Vertex v = posToVertex.get(key);\n if (v.outputOps.size() == 1) {\n posToOpId.put(key, v.outputOps.get(0).operatorId);\n } else if ((v.outputOps.size() == 0 && v.vertexType == VertexType.UNION)) {\n posToOpId.put(key, v.name);\n } else {\n Op joinRSOp = v.getJoinRSOp(vertex);\n if (joinRSOp != null) {\n posToOpId.put(key, joinRSOp.operatorId);\n } else {\n throw new Exception(\"Can not find join reduceSinkOp for \" + v.name + \" to join \" + vertex.name + \" when hive explain user is trying to identify the operator id.\");\n }\n }\n } else // then search from parent\n if (parent != null) {\n posToOpId.put(key, parent.operatorId);\n } else // then assume it is from its own vertex\n if (parentVertexes.size() == 1) {\n Vertex v = parentVertexes.iterator().next();\n parentVertexes.clear();\n if (v.outputOps.size() == 1) {\n posToOpId.put(key, v.outputOps.get(0).operatorId);\n } else if ((v.outputOps.size() == 0 && v.vertexType == VertexType.UNION)) {\n posToOpId.put(key, v.name);\n } else {\n Op joinRSOp = v.getJoinRSOp(vertex);\n if (joinRSOp != null) {\n posToOpId.put(key, joinRSOp.operatorId);\n } else {\n throw new Exception(\"Can not find join reduceSinkOp for \" + v.name + \" to join \" + vertex.name + \" when hive explain user is trying to identify the operator id.\");\n }\n }\n } else // finally throw an exception\n {\n throw new Exception(\"Can not find the source operator on one of the branches of map join.\");\n }\n }\n }\n this.attrs.remove(\"keys:\");\n StringBuilder sb = new StringBuilder();\n JSONArray conditionMap = opObject.getJSONArray(\"condition map:\");\n for (int index = 0; index < conditionMap.length(); index++) {\n JSONObject cond = conditionMap.getJSONObject(index);\n String k = (String) cond.keys().next();\n JSONObject condObject = new JSONObject((String) cond.get(k));\n String type = condObject.getString(\"type\");\n String left = condObject.getString(\"left\");\n String right = condObject.getString(\"right\");\n if (keys.length() != 0) {\n sb.append(posToOpId.get(left) + \".\" + keys.get(left) + \"=\" + posToOpId.get(right) + \".\" + keys.get(right) + \"(\" + type + \"),\");\n } else {\n // probably a cross product\n sb.append(\"(\" + type + \"),\");\n }\n }\n this.attrs.remove(\"condition map:\");\n this.attrs.put(\"Conds:\", sb.substring(0, sb.length() - 1));\n } else // should be merge join\n {\n Map posToOpId = new LinkedHashMap<>();\n if (vertex.mergeJoinDummyVertices.isEmpty()) {\n for (Entry entry : vertex.tagToInput.entrySet()) {\n Connection c = null;\n for (Connection connection : vertex.parentConnections) {\n if (connection.from.name.equals(entry.getValue())) {\n Vertex v = connection.from;\n if (v.outputOps.size() == 1) {\n posToOpId.put(entry.getKey(), v.outputOps.get(0).operatorId);\n } else if ((v.outputOps.size() == 0 && v.vertexType == VertexType.UNION)) {\n posToOpId.put(entry.getKey(), v.name);\n } else {\n Op joinRSOp = v.getJoinRSOp(vertex);\n if (joinRSOp != null) {\n posToOpId.put(entry.getKey(), joinRSOp.operatorId);\n } else {\n throw new Exception(\"Can not find join reduceSinkOp for \" + v.name + \" to join \" + vertex.name + \" when hive explain user is trying to identify the operator id.\");\n }\n }\n c = connection;\n break;\n }\n }\n if (c == null) {\n throw new Exception(\"Can not find \" + entry.getValue() + \" while parsing keys of merge join operator\");\n }\n }\n } else {\n posToOpId.put(vertex.tag, this.parent.operatorId);\n for (Vertex v : vertex.mergeJoinDummyVertices) {\n if (v.outputOps.size() != 1) {\n throw new Exception(\"Can not find a single root operators in a single vertex \" + v.name + \" when hive explain user is trying to identify the operator id.\");\n }\n posToOpId.put(v.tag, v.outputOps.get(0).operatorId);\n }\n }\n // update the keys to use operator name\n JSONObject keys = opObject.getJSONObject(\"keys:\");\n if (keys.length() != 0) {\n for (String key : JSONObject.getNames(keys)) {\n if (!posToOpId.containsKey(key)) {\n throw new Exception(\"Can not find the source operator on one of the branches of merge join.\");\n }\n }\n // inline merge join operator in a self-join\n for (Vertex v : this.vertex.mergeJoinDummyVertices) {\n parser.addInline(this, new Connection(null, v));\n }\n }\n // update the attrs\n this.attrs.remove(\"keys:\");\n StringBuilder sb = new StringBuilder();\n JSONArray conditionMap = opObject.getJSONArray(\"condition map:\");\n for (int index = 0; index < conditionMap.length(); index++) {\n JSONObject cond = conditionMap.getJSONObject(index);\n String k = (String) cond.keys().next();\n JSONObject condObject = new JSONObject((String) cond.get(k));\n String type = condObject.getString(\"type\");\n String left = condObject.getString(\"left\");\n String right = condObject.getString(\"right\");\n if (keys.length() != 0) {\n sb.append(posToOpId.get(left) + \".\" + keys.get(left) + \"=\" + posToOpId.get(right) + \".\" + keys.get(right) + \"(\" + type + \"),\");\n } else {\n // probably a cross product\n sb.append(\"(\" + type + \"),\");\n }\n }\n this.attrs.remove(\"condition map:\");\n this.attrs.put(\"Conds:\", sb.substring(0, sb.length() - 1));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static JaxbNeptuneFileConverter getInstance() throws Exception{\r\n if (instance == null)\r\n instance = new JaxbNeptuneFileConverter();\r\n return instance;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ReplyManager createReplyManager() throws Exception{\r\n ReplyManager replyManager = new TemporaryQueueReplyManager(getEndpoint().getCamelContext());\r\n replyManager.setEndpoint(getEndpoint());\r\n String name = \"JmsReplyManagerTimeoutChecker[\" + getEndpoint().getEndpointConfiguredDestinationName() + \"]\";\r\n ScheduledExecutorService replyManagerScheduledExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(name, name);\r\n replyManager.setScheduledExecutorService(replyManagerScheduledExecutorService);\r\n name = \"JmsReplyManagerOnTimeout[\" + getEndpoint().getEndpointConfiguredDestinationName() + \"]\";\r\n int max = getEndpoint().getReplyToOnTimeoutMaxConcurrentConsumers();\r\n if (max <= 0) {\r\n throw new IllegalArgumentException(\"The option replyToOnTimeoutMaxConcurrentConsumers must be >= 1\");\r\n }\r\n ExecutorService replyManagerExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newThreadPool(replyManager, name, 0, max);\r\n replyManager.setOnTimeoutExecutorService(replyManagerExecutorService);\r\n ServiceHelper.startService(replyManager);\r\n return replyManager;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected FTPClient createFtpClient() throws Exception{\r\n FTPClient client = new FTPClient();\r\n ClassResolver cr = getCamelContext().getClassResolver();\r\n client.setParserFactory(new CamelFTPParserFactory(cr));\r\n return client;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void printSpaceUsage(Map spaceMap) throws Exception{\r\n for (Map.Entry entry : spaceMap.entrySet()) {\r\n System.out.println(entry.getKey() + \"\\t\" + entry.getValue());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Returns the PrimitiveWritableObjectInspector for the PrimitiveCategory.\n *\n * @param primitiveCategory primitive category input to be looked up.\n */\npublic static AbstractPrimitiveWritableObjectInspector getPrimitiveWritableObjectInspector(PrimitiveCategory primitiveCategory) {\n AbstractPrimitiveWritableObjectInspector result = primitiveCategoryToWritableOI.get(primitiveCategory);\n if (result == null) {\n throw new RuntimeException(\"Internal error: Cannot find ObjectInspector \" + \" for \" + primitiveCategory);\n }\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static PrivateKey loadPrivateKey(Path keyFile) throws Exception{\r\n if (StringUtils.lowerCase(keyFile.toString()).endsWith(\".pem\")) {\r\n try (InputStream is = Files.newInputStream(keyFile)) {\r\n return Pem.readPrivateKey(is);\r\n }\r\n }\r\n if (StringUtils.lowerCase(keyFile.toString()).endsWith(\".der\")) {\r\n try (InputStream is = Files.newInputStream(keyFile)) {\r\n return Rsa.privateKeyFromPkcs8(IoUtils.toByteArray(is));\r\n }\r\n }\r\n throw SdkClientException.create(\"Unsupported file type for private key\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void loadLibraryFromJar(String path) throws Exception{\r\n checkArgument(path.startsWith(\"/\"), \"absolute path must start with /\");\r\n String[] parts = path.split(\"/\");\r\n String filename = (parts.length > 0) ? parts[parts.length - 1] : null;\r\n File dir = File.createTempFile(\"native\", \"\");\r\n dir.delete();\r\n if (!(dir.mkdir())) {\r\n throw new IOException(\"Failed to create temp directory \" + dir.getAbsolutePath());\r\n }\r\n dir.deleteOnExit();\r\n File temp = new File(dir, filename);\r\n temp.deleteOnExit();\r\n byte[] buffer = new byte[1024];\r\n int read;\r\n InputStream input = NativeUtils.class.getResourceAsStream(path);\r\n if (input == null) {\r\n throw new FileNotFoundException(\"Couldn't find file into jar \" + path);\r\n }\r\n try {\r\n OutputStream out = new FileOutputStream(temp);\r\n try {\r\n while ((read = input.read(buffer)) != -1) {\r\n out.write(buffer, 0, read);\r\n }\r\n } finally {\r\n out.close();\r\n }\r\n } finally {\r\n input.close();\r\n }\r\n if (!temp.exists()) {\r\n throw new FileNotFoundException(\"Failed to copy file from jar at \" + temp.getAbsolutePath());\r\n }\r\n System.load(temp.getAbsolutePath());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addWithBackoff(Collection messages) throws Exception{\r\n long timeoutMs = INITIAL_BACKOFF_MS;\r\n for (; ; ) {\r\n long result = ringbuffer.addAllAsync(messages, OverflowPolicy.FAIL).toCompletableFuture().get();\r\n if (result != -1) {\r\n break;\r\n }\r\n MILLISECONDS.sleep(timeoutMs);\r\n timeoutMs *= 2;\r\n if (timeoutMs > MAX_BACKOFF) {\r\n timeoutMs = MAX_BACKOFF;\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean number2booleanPrimitive(Double v) throws HopValueException {\n throw new RuntimeException(CONST_CONVERSION_NOT_SUPPORTED);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public void track(String taskId) throws Exception{\r\n int logN = 0;\r\n String pid;\r\n logger.info(\"Remote shell task log:\");\r\n do {\r\n pid = getTaskPid(taskId);\r\n String trackCommand = String.format(COMMAND.TRACK_COMMAND, logN + 1, getRemoteShellHome(), taskId);\r\n String log = runRemote(trackCommand);\r\n if (StringUtils.isEmpty(log)) {\r\n Thread.sleep(TRACK_INTERVAL);\r\n } else {\r\n logN += log.split(\"\\n\").length;\r\n setVarPool(log);\r\n logger.info(log);\r\n }\r\n } while (StringUtils.isNotEmpty(pid));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Test\n void testParseWithReader() throws Exception{\r\n String query = \"select * from dual\";\r\n SqlParser sqlParserReader = sqlParser(new StringReader(query), b -> b);\r\n SqlNode node1 = sqlParserReader.parseQuery();\r\n SqlNode node2 = sql(query).node();\r\n assertEquals(node2.toString(), node1.toString());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void stop() throws Exception{\r\n accepted.close().awaitUninterruptibly(10, TimeUnit.SECONDS);\r\n if (bossGroup != null) {\r\n bossGroup.shutdownGracefully();\r\n }\r\n if (workerGroup != null) {\r\n workerGroup.shutdownGracefully();\r\n }\r\n destroyPipeline();\r\n if (dirWatcher != null) {\r\n dirWatcher.stop();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private synchronized void printThrowExceptions() throws Exception{\r\n if (!errors.isEmpty()) {\r\n for (Exception e : errors) {\r\n System.out.format(\"Error found: %s%n\", e.toString());\r\n e.printStackTrace();\r\n }\r\n throw errors.poll();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"writeArchiveFileRole\" })\npublic boolean setDocumentContent(String id, byte[] content) throws Exception {\n ArchiveFileDocumentsBean db = this.archiveFileDocumentsFacade.find(id);\n if (db.isLocked() && !context.getCallerPrincipal().getName().equals(db.getLockedBy())) {\n throw new Exception(db.getName() + \" ist gesperrt f\u00fcr Nutzer '\" + db.getLockedBy() + \"'\");\n }\n String aId = db.getArchiveFileKey().getId();\n SecurityUtils.checkGroupsForCase(context.getCallerPrincipal().getName(), db.getArchiveFileKey(), this.securityFacade, this.getAllowedGroups(aId));\n if (content != null) {\n db.setSize(content.length);\n db.bumpVersion(true);\n this.archiveFileDocumentsFacade.edit(db);\n }\n String localBaseDir = System.getProperty(\"jlawyer.server.basedirectory\");\n localBaseDir = localBaseDir.trim();\n if (!localBaseDir.endsWith(System.getProperty(\"file.separator\"))) {\n localBaseDir = localBaseDir + System.getProperty(\"file.separator\");\n }\n String dst = localBaseDir + \"archivefiles\" + System.getProperty(\"file.separator\") + aId + System.getProperty(\"file.separator\");\n this.migrateDocument(dst, id, db.getName());\n String dstId = dst + id;\n File dstFile = new File(dstId);\n if (!(dstFile.exists())) {\n throw new Exception(\"Dokument \" + db.getName() + \" existiert nicht!\");\n }\n ServerFileUtils.writeFile(dstFile, content);\n String preview = \"\";\n try {\n PreviewGenerator pg = new PreviewGenerator(this.archiveFileDocumentsFacade);\n preview = pg.updatePreview(aId, db.getId(), db.getName());\n } catch (Throwable t) {\n log.error(\"Error updating document preview\", t);\n }\n try {\n SearchIndexRequest req = new SearchIndexRequest(SearchIndexRequest.ACTION_UPDATE);\n req.setArchiveFileId(aId);\n req.setArchiveFileName(db.getArchiveFileKey().getName());\n req.setArchiveFileNumber(db.getArchiveFileKey().getFileNumber());\n req.setFileName(db.getName());\n req.setId(db.getId());\n req.setText(preview);\n this.publishSearchIndexRequest(req);\n } catch (Throwable t) {\n log.error(\"Error publishing search index request UPDATE\", t);\n }\n StringGenerator idGen = new StringGenerator();\n this.addCaseHistory(idGen.getID().toString(), db.getArchiveFileKey(), \"Dokument ge\u00e4ndert: \" + db.getName());\n DocumentUpdatedEvent evt = new DocumentUpdatedEvent();\n evt.setDocumentId(id);\n evt.setCaseId(aId);\n evt.setDocumentName(db.getName());\n this.updatedDocumentEvent.fireAsync(evt);\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void watchAndReportChanges(Namespace namespace) throws Exception{\r\n namespace.registerNamespaceListener(this);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Object newInstance(String className, Object... args) throws Exception{\r\n Class klass = Class.forName(className, true, classloader);\r\n return klass.getConstructor(Arrays.stream(args).map((a) -> a.getClass()).toArray(Class[]::new)).newInstance(args);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic HiveResourceACLs getResourceACLs(HivePrivilegeObject hiveObject) {\n HiveResourceACLs acls = null;\n try {\n switch(hiveObject.getType()) {\n case DATABASE:\n Database db = Hive.get().getDatabase(hiveObject.getDbname());\n acls = getResourceACLs(new Path(db.getLocationUri()));\n break;\n case TABLE_OR_VIEW:\n case COLUMN:\n Table table = Hive.get().getTable(hiveObject.getDbname(), hiveObject.getObjectName());\n acls = getResourceACLs(new Path(table.getTTable().getSd().getLocation()));\n break;\n default:\n // Shall never happen\n throw new RuntimeException(\"Unknown request type:\" + hiveObject.getType());\n }\n } catch (Exception e) {\n }\n return acls;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private Endpoint createEndpoint(String uri, MinaConfiguration config) throws Exception{\r\n ObjectHelper.notNull(getCamelContext(), \"camelContext\");\r\n String protocol = config.getProtocol();\r\n MinaEndpoint endpoint = null;\r\n if (protocol != null) {\r\n if (protocol.equals(\"tcp\") || config.isDatagramProtocol() || protocol.equals(\"vm\")) {\r\n endpoint = new MinaEndpoint(uri, this, config);\r\n }\r\n }\r\n if (endpoint == null) {\r\n throw new IllegalArgumentException(\"Unrecognised MINA protocol: \" + protocol + \" for uri: \" + uri);\r\n }\r\n if (config.isSync()) {\r\n endpoint.setExchangePattern(ExchangePattern.InOut);\r\n } else {\r\n endpoint.setExchangePattern(ExchangePattern.InOnly);\r\n }\r\n return endpoint;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public LinkedHashMap> getHitsQueryDef(double maxEScore) throws Exception{\r\n LinkedHashMap> hitsHashMap = new LinkedHashMap>();\r\n logger.info(\"Query for hits\");\r\n ArrayList elementList = XMLHelper.selectElements(blastDoc.getDocumentElement(), \"BlastOutput_iterations/Iteration[Iteration_hits]\");\r\n logger.info(\"{} hits\", elementList.size());\r\n for (Element element : elementList) {\r\n Element iterationquerydefElement = XMLHelper.selectSingleElement(element, \"Iteration_query-def\");\r\n String querydef = iterationquerydefElement.getTextContent();\r\n Element iterationHitsElement = XMLHelper.selectSingleElement(element, \"Iteration_hits\");\r\n ArrayList hitList = XMLHelper.selectElements(iterationHitsElement, \"Hit\");\r\n for (Element hitElement : hitList) {\r\n Element hitaccessionElement = XMLHelper.selectSingleElement(hitElement, \"Hit_accession\");\r\n String hitaccession = hitaccessionElement.getTextContent();\r\n Element hithspsElement = XMLHelper.selectSingleElement(hitElement, \"Hit_hsps\");\r\n ArrayList hspList = XMLHelper.selectElements(hithspsElement, \"Hsp\");\r\n for (Element hspElement : hspList) {\r\n Element evalueElement = XMLHelper.selectSingleElement(hspElement, \"Hsp_evalue\");\r\n String value = evalueElement.getTextContent();\r\n double evalue = Double.parseDouble(value);\r\n if (evalue <= maxEScore) {\r\n ArrayList hits = hitsHashMap.get(querydef);\r\n if (hits == null) {\r\n hits = new ArrayList();\r\n hitsHashMap.put(querydef, hits);\r\n }\r\n hits.add(hitaccession);\r\n }\r\n }\r\n }\r\n }\r\n return hitsHashMap;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void clearUDFsCreatedDuringTests() throws Exception{\r\n if (System.getenv(QTEST_LEAVE_FILES) != null) {\r\n return;\r\n }\r\n for (String udfName : db.getFunctions(DEFAULT_DATABASE_NAME, \".*\")) {\r\n if (!srcUDFs.contains(udfName)) {\r\n db.dropFunction(DEFAULT_DATABASE_NAME, udfName);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void cleanupDockerContainer() throws IOException, InterruptedException {\n if (runCmdAndPrintStreams(buildRmCmd(), 600).rc != 0) {\n throw new RuntimeException(\"Unable to remove docker container\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic PlcDiscoveryRequest.Builder discoveryRequestBuilder() {\n // TODO: This should actually happen in the execute method of the discoveryRequest and not here ...\n try {\n ProfinetChannel channel = new ProfinetChannel(Pcaps.findAllDevs());\n S7PlcDiscoverer discoverer = new S7PlcDiscoverer(channel);\n return new DefaultPlcDiscoveryRequest.Builder(discoverer);\n } catch (PcapNativeException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public Object createCallback(String interfaceName, Closure closure) throws Exception{\r\n final Constructor constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);\r\n constructor.setAccessible(true);\r\n return Proxy.newProxyInstance(classloader, new Class[] { Class.forName(interfaceName, true, classloader) }, new InvocationHandler() {\r\n\r\n @Override\r\n public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {\r\n if (args.length == closure.getMaximumNumberOfParameters()) {\r\n return closure.call(args);\r\n } else {\r\n final Class declaringClass = m.getDeclaringClass();\r\n return constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE).unreflectSpecial(m, declaringClass).bindTo(proxy).invokeWithArguments(args);\r\n }\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doReleaseExclusiveReadLock(GenericFile file, Exchange exchange) throws Exception{\r\n if (!markerFile) {\r\n return;\r\n }\r\n boolean acquired = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_ACQUIRED), false, Boolean.class);\r\n if (acquired) {\r\n String lockFileName = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_NAME), String.class);\r\n File lock = new File(lockFileName);\r\n if (lock.exists()) {\r\n LOG.trace(\"Unlocking file: {}\", lockFileName);\r\n boolean deleted = FileUtil.deleteFile(lock);\r\n LOG.trace(\"Lock file: {} was deleted: {}\", lockFileName, deleted);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void read(final InputStream in) throws IOException, Error, Pack200Exception{\r\n final int[] word = decodeScalar(\"archive_magic_word\", in, Codec.BYTE1, magic.length);\r\n for (int m = 0; m < magic.length; m++) {\r\n if (word[m] != magic[m]) {\r\n throw new Error(\"Bad header\");\r\n }\r\n }\r\n setArchiveMinorVersion(decodeScalar(\"archive_minver\", in, Codec.UNSIGNED5));\r\n setArchiveMajorVersion(decodeScalar(\"archive_majver\", in, Codec.UNSIGNED5));\r\n options = new SegmentOptions(decodeScalar(\"archive_options\", in, Codec.UNSIGNED5));\r\n parseArchiveFileCounts(in);\r\n parseArchiveSpecialCounts(in);\r\n parseCpCounts(in);\r\n parseClassCounts(in);\r\n if (getBandHeadersSize() > 0) {\r\n final byte[] bandHeaders = new byte[getBandHeadersSize()];\r\n readFully(in, bandHeaders);\r\n setBandHeadersData(bandHeaders);\r\n }\r\n archiveSizeOffset = archiveSizeOffset - in.available();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Properties loadProperties() throws Exception{\r\n URL url = DropboxPropertyManager.class.getResource(\"/dropbox.properties\");\r\n try (InputStream inStream = url.openStream()) {\r\n properties = new Properties();\r\n try {\r\n properties.load(inStream);\r\n } catch (IOException e) {\r\n throw new DropboxException(\"dropbox.properties can't be read\", e);\r\n }\r\n } catch (IOException e) {\r\n throw new DropboxException(\"dropbox.properties could not be found\", e);\r\n }\r\n return properties;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void enableSessionSupport(Server server, String connectorKey) throws Exception{\r\n ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class);\r\n if (context.getSessionHandler() == null) {\r\n SessionHandler sessionHandler = new SessionHandler();\r\n if (context.isStarted()) {\r\n throw new IllegalStateException(\"Server has already been started. Cannot enabled sessionSupport on \" + connectorKey);\r\n } else {\r\n context.setSessionHandler(sessionHandler);\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/*\n * Setup the context for reading from the next partition file.\n */\nprivate void setupPartitionContextVars(Path nominalPath) throws HiveException {\n currentVectorPartContext = fileToPartitionContextMap.get(nominalPath);\n if (currentVectorPartContext == null) {\n return;\n }\n PartitionDesc partDesc = currentVectorPartContext.getPartDesc();\n VectorPartitionDesc vectorPartDesc = partDesc.getVectorPartitionDesc();\n currentReadType = vectorPartDesc.getVectorMapOperatorReadType();\n /*\n * Setup for 3 different kinds of vectorized reading supported:\n *\n * 1) Read the Vectorized Input File Format which returns VectorizedRowBatch as the row.\n *\n * 2) Read using VectorDeserializeRow to deserialize each row into the VectorizedRowBatch.\n *\n * 3) And read using the regular partition deserializer to get the row object and assigning\n * the row object into the VectorizedRowBatch with VectorAssignRow.\n */\n if (currentReadType == VectorMapOperatorReadType.VECTORIZED_INPUT_FILE_FORMAT) {\n /*\n * The Vectorized Input File Format reader is responsible for setting the partition column\n * values, resetting and filling in the batch, etc.\n */\n /*\n * Clear all the reading variables.\n */\n currentDataColumnCount = 0;\n currentDeserializeRead = null;\n currentVectorDeserializeRow = null;\n currentPartDeserializer = null;\n currentPartRawRowObjectInspector = null;\n currentVectorAssign = null;\n } else {\n /*\n * We will get \"regular\" single rows from the Input File Format reader that we will need\n * to {vector|row} deserialize.\n */\n Preconditions.checkState(currentReadType == VectorMapOperatorReadType.VECTOR_DESERIALIZE || currentReadType == VectorMapOperatorReadType.ROW_DESERIALIZE);\n /*\n * Clear out any rows in the batch from previous partition since we are going to change\n * the repeating partition column values.\n */\n if (!flushDeserializerBatch()) {\n // Operator tree is now done.\n return;\n }\n /*\n * For this particular file, how many columns will we actually read?\n */\n currentDataColumnCount = currentVectorPartContext.getReaderDataColumnCount();\n if (currentDataColumnCount < dataColumnCount) {\n /*\n * Default any additional data columns to NULL once for the file (if they are present).\n */\n for (int i = currentDataColumnCount; i < dataColumnCount; i++) {\n ColumnVector colVector = deserializerBatch.cols[i];\n if (colVector != null) {\n colVector.isNull[0] = true;\n colVector.noNulls = false;\n colVector.isRepeating = true;\n }\n }\n }\n if (batchContext.getPartitionColumnCount() > 0) {\n /*\n * The partition columns are set once for the partition and are marked repeating.\n */\n VectorizedRowBatchCtx.getPartitionValues(batchContext, partDesc, partitionValues);\n batchContext.addPartitionColsToBatch(deserializerBatch, partitionValues);\n }\n if (hasRowIdentifier) {\n // No ACID in code path -- set ROW__ID to NULL.\n setRowIdentiferToNull(deserializerBatch);\n }\n /*\n * Set or clear the rest of the reading variables based on {vector|row} deserialization.\n */\n switch(currentReadType) {\n case VECTOR_DESERIALIZE:\n {\n VectorDeserializePartitionContext vectorDeserPartContext = (VectorDeserializePartitionContext) currentVectorPartContext;\n // Set ours.\n currentDeserializeRead = vectorDeserPartContext.getDeserializeRead();\n currentVectorDeserializeRow = vectorDeserPartContext.getVectorDeserializeRow();\n // Clear the other ones.\n currentPartDeserializer = null;\n currentPartRawRowObjectInspector = null;\n currentVectorAssign = null;\n }\n break;\n case ROW_DESERIALIZE:\n {\n RowDeserializePartitionContext rowDeserPartContext = (RowDeserializePartitionContext) currentVectorPartContext;\n // Clear the other ones.\n currentDeserializeRead = null;\n currentVectorDeserializeRow = null;\n // Set ours.\n currentPartDeserializer = rowDeserPartContext.getPartDeserializer();\n currentPartRawRowObjectInspector = rowDeserPartContext.getPartRawRowObjectInspector();\n currentVectorAssign = rowDeserPartContext.getVectorAssign();\n }\n break;\n default:\n throw new RuntimeException(\"Unexpected VectorMapOperator read type \" + currentReadType.name());\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static String doHttpPost(final String url, final String requestBody, Map headers) throws Exception {\n try {\n CloseableHttpClient client = getHttpClient();\n HttpPost httppost = new HttpPost(url);\n if (requestBody == null || requestBody.isEmpty()) {\n httppost.setHeader(\"Content-Type\", ContentType.APPLICATION_FORM_URLENCODED.toString());\n } else {\n httppost.setHeader(\"Content-Type\", ContentType.APPLICATION_JSON.toString());\n }\n headers.entrySet().stream().forEach(entry -> httppost.setHeader(entry.getKey(), entry.getValue()));\n StringEntity jsonEntity = new StringEntity(requestBody);\n httppost.setEntity(jsonEntity);\n HttpResponse httpresponse = client.execute(httppost);\n int statusCode = httpresponse.getStatusLine().getStatusCode();\n if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {\n return EntityUtils.toString(httpresponse.getEntity());\n } else {\n logger.error(\"{} --- {}\", httpresponse.getStatusLine().getStatusCode(), httpresponse.getStatusLine().getReasonPhrase());\n throw new Exception(\"unable to execute post request because \" + httpresponse.getStatusLine().getReasonPhrase());\n }\n } catch (ParseException parseException) {\n logger.error(\"ParseException in getHttpPost : {}\", parseException.getMessage());\n throw new ParseException(parseException.getMessage());\n } catch (Exception exception) {\n logger.error(\"Exception in getHttpPost : {}\", exception.getMessage());\n throw new Exception(exception.getMessage());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "public void process() throws Exception{\r\n PrintWriter writer = new PrintWriter(os);\r\n for (S sequence : sequences) {\r\n String header = headerFormat.getHeader(sequence);\r\n writer.print(header);\r\n writer.println();\r\n String data = sequence.getSequenceAsString().toLowerCase();\r\n int seq_len = data.length();\r\n writer.println(\"ORIGIN\");\r\n for (int line_number = 0; line_number < seq_len; line_number += lineLength) {\r\n writer.print(StringManipulationHelper.padLeft(Integer.toString(line_number + 1), SEQUENCE_INDENT));\r\n for (int words = line_number; words < Math.min(line_number + lineLength, seq_len); words += 10) {\r\n if ((words + 10) > data.length()) {\r\n writer.print((\" \" + data.substring(words)));\r\n } else {\r\n writer.print((\" \" + data.substring(words, words + 10)));\r\n }\r\n }\r\n writer.println();\r\n }\r\n writer.println(\"//\");\r\n }\r\n writer.flush();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void configureConsumer(MessageConsumer consumer, Session session) throws Exception{\r\n consumer.setMessageListener(new SimpleMessageListener(messageListener, session));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static int getNumBitVectorsForNDVEstimation(Configuration conf) throws Exception{\r\n int numBitVectors;\r\n float percentageError = HiveConf.getFloatVar(conf, HiveConf.ConfVars.HIVE_STATS_NDV_ERROR);\r\n if (percentageError < 0.0) {\r\n throw new Exception(\"hive.stats.ndv.error can't be negative\");\r\n } else if (percentageError <= 2.4) {\r\n numBitVectors = 1024;\r\n LOG.info(\"Lowest error achievable is 2.4% but error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 1024 bit vectors..\");\r\n } else if (percentageError <= 3.4) {\r\n numBitVectors = 1024;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 1024 bit vectors..\");\r\n } else if (percentageError <= 4.8) {\r\n numBitVectors = 512;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 512 bit vectors..\");\r\n } else if (percentageError <= 6.8) {\r\n numBitVectors = 256;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 256 bit vectors..\");\r\n } else if (percentageError <= 9.7) {\r\n numBitVectors = 128;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 128 bit vectors..\");\r\n } else if (percentageError <= 13.8) {\r\n numBitVectors = 64;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 64 bit vectors..\");\r\n } else if (percentageError <= 19.6) {\r\n numBitVectors = 32;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 32 bit vectors..\");\r\n } else if (percentageError <= 28.2) {\r\n numBitVectors = 16;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 16 bit vectors..\");\r\n } else if (percentageError <= 40.9) {\r\n numBitVectors = 8;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 8 bit vectors..\");\r\n } else if (percentageError <= 61.0) {\r\n numBitVectors = 4;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 4 bit vectors..\");\r\n } else {\r\n numBitVectors = 2;\r\n LOG.info(\"Error requested is \" + percentageError + \"%\");\r\n LOG.info(\"Choosing 2 bit vectors..\");\r\n }\r\n return numBitVectors;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void initializeServer() throws Exception{\r\n NettyServerBuilder serverBuilder;\r\n BindableService bindableService = getBindableServiceFactory().createBindableService(this);\r\n ServerInterceptor headerInterceptor = new GrpcHeaderInterceptor();\r\n if (!ObjectHelper.isEmpty(configuration.getHost()) && !ObjectHelper.isEmpty(configuration.getPort())) {\r\n LOG.debug(\"Building gRPC server on {}:{}\", configuration.getHost(), configuration.getPort());\r\n serverBuilder = NettyServerBuilder.forAddress(new InetSocketAddress(configuration.getHost(), configuration.getPort()));\r\n } else {\r\n throw new IllegalArgumentException(\"No server start properties (host, port) specified\");\r\n }\r\n if (configuration.isRouteControlledStreamObserver() && configuration.getConsumerStrategy() == GrpcConsumerStrategy.AGGREGATION) {\r\n throw new IllegalArgumentException(\"Consumer strategy AGGREGATION and routeControlledStreamObserver are not compatible. Set the consumer strategy to PROPAGATION\");\r\n }\r\n if (configuration.getNegotiationType() == NegotiationType.TLS) {\r\n ObjectHelper.notNull(configuration.getKeyCertChainResource(), \"keyCertChainResource\");\r\n ObjectHelper.notNull(configuration.getKeyResource(), \"keyResource\");\r\n SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getKeyCertChainResource()), ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getKeyResource()), configuration.getKeyPassword()).clientAuth(ClientAuth.REQUIRE);\r\n if (ObjectHelper.isNotEmpty(configuration.getTrustCertCollectionResource())) {\r\n sslContextBuilder = sslContextBuilder.trustManager(ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), configuration.getTrustCertCollectionResource()));\r\n }\r\n serverBuilder = serverBuilder.sslContext(GrpcSslContexts.configure(sslContextBuilder).build());\r\n }\r\n if (configuration.getAuthenticationType() == GrpcAuthType.JWT) {\r\n ObjectHelper.notNull(configuration.getJwtSecret(), \"jwtSecret\");\r\n serverBuilder = serverBuilder.intercept(new JwtServerInterceptor(configuration.getJwtAlgorithm(), configuration.getJwtSecret(), configuration.getJwtIssuer(), configuration.getJwtSubject()));\r\n }\r\n for (ServerInterceptor si : configuration.getServerInterceptors()) {\r\n serverBuilder.intercept(si);\r\n }\r\n server = serverBuilder.addService(ServerInterceptors.intercept(bindableService, headerInterceptor)).maxInboundMessageSize(configuration.getMaxMessageSize()).flowControlWindow(configuration.getFlowControlWindow()).maxConcurrentCallsPerConnection(configuration.getMaxConcurrentCallsPerConnection()).build();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static LinkedHashMap getProteinSequences(Collection chromosomeSequences) throws Exception{\r\n LinkedHashMap proteinSequenceHashMap = new LinkedHashMap();\r\n for (ChromosomeSequence dnaSequence : chromosomeSequences) {\r\n for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) {\r\n for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {\r\n try {\r\n ProteinSequence proteinSequence = transcriptSequence.getProteinSequence();\r\n if (proteinSequenceHashMap.containsKey(proteinSequence.getAccession().getID())) {\r\n throw new Exception(\"Duplicate protein sequence id=\" + proteinSequence.getAccession().getID() + \" found at Gene id=\" + geneSequence.getAccession().getID());\r\n } else {\r\n proteinSequenceHashMap.put(proteinSequence.getAccession().getID(), proteinSequence);\r\n }\r\n } catch (Exception e) {\r\n logger.error(\"Exception: \", e);\r\n }\r\n }\r\n }\r\n }\r\n return proteinSequenceHashMap;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void getObjectStat(String objectName, Message message) throws Exception{\r\n String bucketName = getConfiguration().getBucketName();\r\n StatObjectArgs.Builder statObjectRequest = StatObjectArgs.builder().bucket(bucketName).object(objectName);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getServerSideEncryptionCustomerKey, statObjectRequest::ssec);\r\n MinioChecks.checkLengthAndSetConfig(getConfiguration()::getOffset, statObjectRequest::offset);\r\n MinioChecks.checkLengthAndSetConfig(getConfiguration()::getLength, statObjectRequest::length);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getVersionId, statObjectRequest::versionId);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getMatchETag, statObjectRequest::matchETag);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getNotMatchETag, statObjectRequest::notMatchETag);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getModifiedSince, statObjectRequest::modifiedSince);\r\n MinioChecks.checkIfConfigIsNotEmptyAndSetAndConfig(getConfiguration()::getUnModifiedSince, statObjectRequest::unmodifiedSince);\r\n StatObjectResponse stat = minioClient.statObject(statObjectRequest.build());\r\n message.setHeader(MinioConstants.OBJECT_NAME, stat.object());\r\n message.setHeader(MinioConstants.BUCKET_NAME, stat.bucket());\r\n message.setHeader(MinioConstants.E_TAG, stat.etag());\r\n message.setHeader(MinioConstants.LAST_MODIFIED, stat.headers().get(\"last-modified\"));\r\n message.setHeader(MinioConstants.VERSION_ID, stat.headers().get(\"x-amz-version-id\"));\r\n message.setHeader(MinioConstants.CONTENT_TYPE, stat.contentType());\r\n message.setHeader(MinioConstants.CONTENT_LENGTH, stat.size());\r\n message.setHeader(MinioConstants.CONTENT_ENCODING, stat.headers().get(\"content-encoding\"));\r\n message.setHeader(MinioConstants.CONTENT_DISPOSITION, stat.headers().get(\"content-disposition\"));\r\n message.setHeader(MinioConstants.CACHE_CONTROL, stat.headers().get(\"cache-control\"));\r\n message.setHeader(MinioConstants.SERVER_SIDE_ENCRYPTION, stat.headers().get(\"x-amz-server-side-encryption\"));\r\n message.setHeader(MinioConstants.EXPIRATION_TIME, stat.headers().get(\"x-amz-expiration\"));\r\n message.setHeader(MinioConstants.REPLICATION_STATUS, stat.headers().get(\"x-amz-replication-status\"));\r\n message.setHeader(MinioConstants.STORAGE_CLASS, stat.headers().get(\"x-amz-storage-class\"));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setUpLoggerConfig() throws Exception{\r\n URL logger = conf.getResource(LlapConstants.LOG4j2_PROPERTIES_FILE);\r\n if (null == logger) {\r\n throw new Exception(\"Unable to find required config file: llap-daemon-log4j2.properties\");\r\n }\r\n InputStream loggerContent = logger.openStream();\r\n IOUtils.copyBytes(loggerContent, rawFs.create(new Path(confDir, \"llap-daemon-log4j2.properties\"), true), conf, true);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setOutParameter(int index, CallableStatement stmt, DataType dataType, String value) throws Exception{\r\n int sqlType;\r\n switch(dataType) {\r\n case VARCHAR:\r\n sqlType = Types.VARCHAR;\r\n break;\r\n case INTEGER:\r\n case LONG:\r\n sqlType = Types.INTEGER;\r\n break;\r\n case FLOAT:\r\n sqlType = Types.FLOAT;\r\n break;\r\n case DOUBLE:\r\n sqlType = Types.DOUBLE;\r\n break;\r\n case DATE:\r\n sqlType = Types.DATE;\r\n break;\r\n case TIME:\r\n sqlType = Types.TIME;\r\n break;\r\n case TIMESTAMP:\r\n sqlType = Types.TIMESTAMP;\r\n break;\r\n case BOOLEAN:\r\n sqlType = Types.BOOLEAN;\r\n break;\r\n default:\r\n throw new IllegalStateException(\"Unexpected value: \" + dataType);\r\n }\r\n if (StringUtils.isEmpty(value)) {\r\n stmt.registerOutParameter(index, sqlType);\r\n } else {\r\n stmt.registerOutParameter(index, sqlType, value);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Webhook createWebhook(Long workspaceId, WebhookCreationCommand command) {\n String payload;\n try {\n payload = MAPPER.writeValueAsString(command);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n var pathname = \"/team/\" + workspaceId + \"/webhook\";\n var request = HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(payload)).uri(URI.create(this.baseUrl + pathname)).header(\"Content-Type\", \"application/json\").header(\"Authorization\", this.authorizationToken).build();\n HttpResponse response;\n try {\n response = this.httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n } catch (IOException | InterruptedException e) {\n throw new RuntimeException(e);\n }\n WebhookCreationResult result;\n try {\n String body = response.body();\n result = MAPPER.readValue(body, WebhookCreationResult.class);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n if (result.isError()) {\n switch(result.getErrorCode()) {\n case WEBHOOK_CREATION_ERROR_WEBHOOK_ALREADY_EXISTS:\n throw new WebhookAlreadyExistsException();\n }\n throw new RuntimeException(\"The error \" + result.getErrorCode() + \" has occurred during the webhook registration: \" + result.getError());\n }\n return result.getWebhook();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private Object getValueInternal(Object target, String fieldPath, boolean useLazyDeserialization) throws Exception{\r\n InternalGenericRecord record;\r\n if (target instanceof PortableGenericRecord) {\r\n record = (InternalGenericRecord) target;\r\n } else {\r\n record = serializationService.readAsInternalGenericRecord((Data) target);\r\n }\r\n GenericRecordQueryReader reader = new GenericRecordQueryReader(record, useLazyDeserialization);\r\n return reader.read(fieldPath);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public int boolean2intPrimitive(Boolean v) throws HopValueException {\n throw new RuntimeException(CONST_CONVERSION_NOT_SUPPORTED);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Resolve the context of an entry. This is an effective test of\n * JAAS setup, because it will relay detected problems up\n * @param context context name\n * @return the entry\n * @throws RuntimeException if there is no context entry found\n */\npublic static AppConfigurationEntry[] validateContext(String context) {\n if (context == null) {\n throw new RuntimeException(\"Null context argument\");\n }\n if (context.isEmpty()) {\n throw new RuntimeException(\"Empty context argument\");\n }\n javax.security.auth.login.Configuration configuration = javax.security.auth.login.Configuration.getConfiguration();\n AppConfigurationEntry[] entries = configuration.getAppConfigurationEntry(context);\n if (entries == null) {\n throw new RuntimeException(String.format(\"Entry \\\"%s\\\" not found; \" + \"JAAS config = %s\", context, describeProperty(Environment.JAAS_CONF_KEY)));\n }\n return entries;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void resumeTrigger() throws Exception{\r\n if (!jobPaused.get()) {\r\n return;\r\n }\r\n jobPaused.set(false);\r\n Scheduler scheduler = getComponent().getScheduler();\r\n if (scheduler != null) {\r\n LOG.info(\"Resuming trigger {}\", triggerKey);\r\n scheduler.resumeTrigger(triggerKey);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void mergeAccounts() throws Exception{\r\n UserTO mergingUserTO = model.getMergingUser();\r\n UserUR userUR = new UserUR();\r\n userUR.setKey(model.getBaseUser().getUsername());\r\n mergingUserTO.getLinkedAccounts().forEach(acct -> {\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(acct.getResource(), acct.getConnObjectKeyValue()).password(acct.getPassword()).suspended(acct.isSuspended()).username(acct.getUsername()).build();\r\n linkedAccount.getPlainAttrs().addAll(acct.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(acct.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n });\r\n mergingUserTO.getResources().forEach(resource -> {\r\n String connObjectKeyValue = ResourceRestClient.getConnObjectKeyValue(resource, mergingUserTO.getType(), mergingUserTO.getKey());\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(resource, connObjectKeyValue).build();\r\n linkedAccount.getPlainAttrs().addAll(mergingUserTO.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(mergingUserTO.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n });\r\n String connObjectKeyValue = ResourceRestClient.getConnObjectKeyValue(model.getResource().getKey(), mergingUserTO.getType(), mergingUserTO.getKey());\r\n LinkedAccountTO linkedAccount = new LinkedAccountTO.Builder(model.getResource().getKey(), connObjectKeyValue).password(mergingUserTO.getPassword()).suspended(mergingUserTO.isSuspended()).username(mergingUserTO.getUsername()).build();\r\n linkedAccount.getPlainAttrs().addAll(mergingUserTO.getPlainAttrs());\r\n linkedAccount.getPrivileges().addAll(mergingUserTO.getPrivileges());\r\n LinkedAccountUR patch = new LinkedAccountUR.Builder().linkedAccountTO(linkedAccount).operation(PatchOperation.ADD_REPLACE).build();\r\n userUR.getLinkedAccounts().add(patch);\r\n BatchRequest batchRequest = SyncopeConsoleSession.get().batch();\r\n BatchRequestItem deleteRequest = new BatchRequestItem();\r\n deleteRequest.setMethod(HttpMethod.DELETE);\r\n deleteRequest.setRequestURI(\"/users/\" + mergingUserTO.getKey());\r\n deleteRequest.getHeaders().put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON));\r\n batchRequest.getItems().add(deleteRequest);\r\n String updateUserPayload = MAPPER.writeValueAsString(userUR);\r\n BatchRequestItem updateUser = new BatchRequestItem();\r\n updateUser.setMethod(HttpMethod.PATCH);\r\n updateUser.setRequestURI(\"/users/\" + model.getBaseUser().getUsername());\r\n updateUser.setHeaders(new HashMap<>());\r\n updateUser.getHeaders().put(RESTHeaders.PREFER, List.of(Preference.RETURN_NO_CONTENT.toString()));\r\n updateUser.getHeaders().put(HttpHeaders.ACCEPT, List.of(MediaType.APPLICATION_JSON));\r\n updateUser.getHeaders().put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON));\r\n updateUser.getHeaders().put(HttpHeaders.CONTENT_LENGTH, List.of(updateUserPayload.length()));\r\n updateUser.setContent(updateUserPayload);\r\n batchRequest.getItems().add(updateUser);\r\n Map batchResponse = UserRestClient.batch(batchRequest);\r\n batchResponse.forEach((key, value) -> {\r\n if (!value.equalsIgnoreCase(\"success\")) {\r\n throw new IllegalArgumentException(\"Unable to report a success operation status for \" + key);\r\n }\r\n });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Parser createParser(Exchange exchange) throws Exception{\r\n Reader bodyReader = null;\r\n try {\r\n if (FlatpackType.fixed == type) {\r\n bodyReader = exchange.getIn().getMandatoryBody(Reader.class);\r\n return createFixedParser(resourceUri, bodyReader);\r\n } else {\r\n return createDelimitedParser(exchange);\r\n }\r\n } catch (Exception e) {\r\n IOHelper.close(bodyReader);\r\n throw e;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void addState(Class id, State state) {\n if (pool.containsKey(id.getName())) {\n throw new RuntimeException(\"State '\" + state.getName() + \"' added for the\" + \" class \" + id.getName() + \" already exists!\");\n }\n isUpdated = true;\n pool.put(id.getName(), new StatePair(state));\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Returns the size of the word in {@link RandomTextDataGenerator}'s\n * dictionary that can generate text with the desired compression ratio.\n *\n * @throws RuntimeException If ratio is less than {@value #MIN_RATIO} or\n * greater than {@value #MAX_RATIO}.\n */\nint getWordSizeForRatio(float ratio) {\n ratio = standardizeCompressionRatio(ratio);\n if (ratio >= MIN_RATIO && ratio <= MAX_RATIO) {\n return map.get(ratio);\n } else {\n throw new RuntimeException(\"Compression ratio should be in the range [\" + MIN_RATIO + \",\" + MAX_RATIO + \"]. Configured compression ratio is \" + ratio + \".\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": " HttpHandler wrapHttpHandler(HttpHandler httpHandler) throws Exception{\r\n return httpHandler;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void read(final InputStream in) throws IOException, Error, Pack200Exception{\r\n final int[] word = decodeScalar(\"archive_magic_word\", in, Codec.BYTE1, magic.length);\r\n for (int m = 0; m < magic.length; ++m) {\r\n if (word[m] != magic[m]) {\r\n throw new Error(\"Bad header\");\r\n }\r\n }\r\n setArchiveMinorVersion(decodeScalar(\"archive_minver\", in, Codec.UNSIGNED5));\r\n setArchiveMajorVersion(decodeScalar(\"archive_majver\", in, Codec.UNSIGNED5));\r\n options = new SegmentOptions(decodeScalar(\"archive_options\", in, Codec.UNSIGNED5));\r\n parseArchiveFileCounts(in);\r\n parseArchiveSpecialCounts(in);\r\n parseCpCounts(in);\r\n parseClassCounts(in);\r\n if (getBandHeadersSize() > 0) {\r\n final byte[] bandHeaders = new byte[getBandHeadersSize()];\r\n readFully(in, bandHeaders);\r\n setBandHeadersData(bandHeaders);\r\n }\r\n archiveSizeOffset = archiveSizeOffset - in.available();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void printImage(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception{\r\n final String payload = ExchangeHelper.convertToMandatoryType(exchange, String.class, graph);\r\n final MultiFormatWriter writer = new MultiFormatWriter();\r\n final String type = this.params.getType().toString();\r\n final BitMatrix matrix = writer.encode(payload, this.params.getFormat(), this.params.getWidth(), this.params.getHeight(), writerHintMap);\r\n MatrixToImageWriter.writeToStream(matrix, type, stream);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String configTomlAsString(final File file) throws Exception{\r\n return Resources.toString(file.toURI().toURL(), UTF_8);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static SessionSettings loadSettings(CamelContext camelContext, String settingsResourceName) throws Exception{\r\n InputStream inputStream = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, settingsResourceName);\r\n return new SessionSettings(inputStream);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Long addOrOverwrite(ReliableTopicMessage message) throws Exception{\r\n return ringbuffer.addAsync(message, OverflowPolicy.OVERWRITE).toCompletableFuture().get();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean matchFullPath(IDeviceID deviceID, String measurement) {\n // TODO change this way\n PartialPath devicePath;\n try {\n devicePath = new PartialPath(deviceID.toString());\n } catch (IllegalPathException e) {\n throw new RuntimeException(e);\n }\n return matchPath(devicePath.concatAsMeasurementPath(measurement).getNodes(), 0, 0, false, false);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "/**\n * apply a model to the given data\n *\n * @param aNumericData - data to be used for prediction (must be compatible to the model)\n * @param rowRDD - original data\n * @param aModel - model to be applied\n * @return original data with appended column containing predictions\n * @throws Exception thrown when model type cannot be handled\n */\n@Deprecated\npublic static JavaRDD predict(final JavaRDD aNumericData, final JavaRDD rowRDD, final T aModel) throws Exception {\n //use only the column indices when converting to vector\n aNumericData.cache();\n final JavaRDD predictions;\n if (aModel instanceof KMeansModel) {\n LOGGER.fine(\"KMeansModel found for prediction\");\n predictions = ((KMeansModel) aModel).predict(aNumericData);\n } else if (aModel instanceof DecisionTreeModel) {\n LOGGER.fine(\"DecisionTreeModel found for prediction\");\n predictions = ((DecisionTreeModel) aModel).predict(aNumericData);\n } else if (aModel instanceof RandomForestModel) {\n LOGGER.fine(\"RandomForestModel found for prediction\");\n predictions = ((RandomForestModel) aModel).predict(aNumericData);\n } else if (aModel instanceof GradientBoostedTreesModel) {\n LOGGER.fine(\"GradientBoostedTreesModel found for prediction\");\n predictions = ((GradientBoostedTreesModel) aModel).predict(aNumericData);\n } else if (aModel instanceof SVMModel) {\n LOGGER.fine(\"SVMModel found for prediction\");\n predictions = ((SVMModel) aModel).predict(aNumericData);\n } else if (aModel instanceof LinearRegressionModel) {\n LOGGER.fine(\"LinearRegressionModel found for prediction\");\n predictions = ((LinearRegressionModel) aModel).predict(aNumericData);\n } else if (aModel instanceof LogisticRegressionModel) {\n LOGGER.fine(\"LogisticRegressionModel found for prediction\");\n predictions = ((LogisticRegressionModel) aModel).predict(aNumericData);\n } else if (aModel instanceof NaiveBayesModel) {\n LOGGER.fine(\"NaiveBayesModel found for prediction\");\n predictions = ((NaiveBayesModel) aModel).predict(aNumericData);\n } else {\n throw new Exception(\"Unknown model type: \" + aModel.getClass());\n }\n return addColumn(rowRDD.zip(predictions));\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "/**\n * Reads the next byteWidth little endian int.\n */\nprivate int readIntLittleEndianPaddedOnBitWidth() throws IOException {\n switch(bytesWidth) {\n case 0:\n return 0;\n case 1:\n return in.read();\n case 2:\n {\n int ch2 = in.read();\n int ch1 = in.read();\n return (ch1 << 8) + ch2;\n }\n case 3:\n {\n int ch3 = in.read();\n int ch2 = in.read();\n int ch1 = in.read();\n return (ch1 << 16) + (ch2 << 8) + ch3;\n }\n case 4:\n {\n return readIntLittleEndian();\n }\n default:\n throw new RuntimeException(\"Unreachable\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "/**\n * Apply steps applies the current step on to a volumeSet so that we can\n * compute next steps until we reach the desired goals.\n *\n * @param nextStep - nextStep or Null\n * @param currentSet - Current Disk BalancerVolume Set we are operating upon\n * @param lowVolume - volume\n * @param highVolume - volume\n */\nprivate void applyStep(Step nextStep, DiskBalancerVolumeSet currentSet, DiskBalancerVolume lowVolume, DiskBalancerVolume highVolume) throws Exception {\n long used;\n if (nextStep != null) {\n used = lowVolume.getUsed() + nextStep.getBytesToMove();\n lowVolume.setUsed(used);\n used = highVolume.getUsed() - nextStep.getBytesToMove();\n highVolume.setUsed(used);\n }\n // since the volume data changed , we need to recompute the DataDensity.\n currentSet.computeVolumeDataDensity();\n printQueue(currentSet.getSortedQueue());\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void launchDockerContainer() throws Exception{\r\n runCmdAndPrintStreams(buildRmCmd(), 600);\r\n if (runCmdAndPrintStreams(buildRunCmd(), 600).rc != 0) {\r\n printDockerEvents();\r\n throw new RuntimeException(\"Unable to start docker container\");\r\n }\r\n long startTime = System.currentTimeMillis();\r\n ProcessResults pr;\r\n do {\r\n Thread.sleep(1000);\r\n pr = runCmdAndPrintStreams(buildLogCmd(), 30);\r\n if (pr.rc != 0) {\r\n printDockerEvents();\r\n throw new RuntimeException(\"Failed to get docker logs\");\r\n }\r\n } while (startTime + MAX_STARTUP_WAIT >= System.currentTimeMillis() && !isContainerReady(pr));\r\n if (startTime + MAX_STARTUP_WAIT < System.currentTimeMillis()) {\r\n printDockerEvents();\r\n throw new RuntimeException(String.format(\"Container initialization failed within %d seconds. Please check the hive logs.\", MAX_STARTUP_WAIT / 1000));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ProcessElement\npublic void processElement(ProcessContext processContext) {\n try {\n KV kv = processContext.element();\n inputCounter.inc();\n Object[] outputRow = new Object[rowMeta.size()];\n // String\n outputRow[0] = kv.getKey();\n // Avro Record (GenericRecord)\n outputRow[1] = kv.getValue();\n processContext.output(new HopRow(outputRow));\n writtenCounter.inc();\n } catch (Exception e) {\n numErrors.inc();\n LOG.error(\"Error in KV to Hop Row conversion function\", e);\n throw new RuntimeException(\"Error in KV to Hop Row conversion function\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public boolean initDataset(String table, CliDriver cliDriver) throws Exception{\r\n File tableFile = new File(new File(datasetDir, table), Dataset.INIT_FILE_NAME);\r\n String commands = null;\r\n try {\r\n commands = FileUtils.readFileToString(tableFile);\r\n } catch (IOException e) {\r\n throw new RuntimeException(String.format(\"dataset file not found %s\", tableFile), e);\r\n }\r\n try {\r\n CommandProcessorResponse result = cliDriver.processLine(commands);\r\n LOG.info(\"Result from cliDrriver.processLine in initFromDatasets=\" + result);\r\n } catch (CommandProcessorException e) {\r\n Assert.fail(\"Failed during initFromDatasets processLine with code=\" + e);\r\n }\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get the integer value out of a primitive object. Note that\n * NullPointerException will be thrown if o is null. Note that\n * NumberFormatException will be thrown if o is not a valid number.\n */\npublic static int getInt(Object o, PrimitiveObjectInspector oi) {\n int result = 0;\n switch(oi.getPrimitiveCategory()) {\n case VOID:\n {\n result = 0;\n break;\n }\n case BOOLEAN:\n {\n result = (((BooleanObjectInspector) oi).get(o) ? 1 : 0);\n break;\n }\n case BYTE:\n {\n result = ((ByteObjectInspector) oi).get(o);\n break;\n }\n case SHORT:\n {\n result = ((ShortObjectInspector) oi).get(o);\n break;\n }\n case INT:\n {\n result = ((IntObjectInspector) oi).get(o);\n break;\n }\n case LONG:\n {\n result = (int) ((LongObjectInspector) oi).get(o);\n break;\n }\n case FLOAT:\n {\n result = (int) ((FloatObjectInspector) oi).get(o);\n break;\n }\n case DOUBLE:\n {\n result = (int) ((DoubleObjectInspector) oi).get(o);\n break;\n }\n case STRING:\n {\n StringObjectInspector soi = (StringObjectInspector) oi;\n if (soi.preferWritable()) {\n Text t = soi.getPrimitiveWritableObject(o);\n result = LazyInteger.parseInt(t.getBytes(), 0, t.getLength());\n } else {\n String s = soi.getPrimitiveJavaObject(o);\n result = Integer.parseInt(s);\n }\n break;\n }\n case CHAR:\n case VARCHAR:\n {\n result = Integer.parseInt(getString(o, oi));\n break;\n }\n case TIMESTAMP:\n result = (int) (((TimestampObjectInspector) oi).getPrimitiveWritableObject(o).getSeconds());\n break;\n case DECIMAL:\n {\n HiveDecimal dec = ((HiveDecimalObjectInspector) oi).getPrimitiveJavaObject(o);\n if (!dec.isInt()) {\n throw new NumberFormatException();\n }\n result = dec.intValue();\n }\n break;\n // unsupported conversion\n case DATE:\n default:\n {\n throw new RuntimeException(\"Hive 2 Internal error: unsupported conversion from type: \" + oi.getTypeName());\n }\n }\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected String getAlias(Exchange exchange) throws Exception{\r\n KeyStore keystore = config.getKeystore();\r\n if (keystore != null) {\r\n String alias = exchange.getIn().getHeader(DigitalSignatureConstants.KEYSTORE_ALIAS, String.class);\r\n if (alias == null) {\r\n alias = config.getAlias();\r\n }\r\n if (alias == null && keystore.size() == 1) {\r\n alias = keystore.aliases().nextElement();\r\n }\r\n return alias;\r\n }\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object getKey(final Message message) throws Exception{\r\n Object value;\r\n if (configuration.getKeyType() != null) {\r\n Class clazz = getEndpoint().getCamelContext().getClassResolver().resolveClass(configuration.getKeyType());\r\n value = message.getHeader(EhcacheConstants.KEY, clazz);\r\n } else {\r\n value = message.getHeader(EhcacheConstants.KEY);\r\n }\r\n if (value == null) {\r\n value = configuration.getKey();\r\n }\r\n if (value == null) {\r\n throw new CamelExchangeException(\"No value provided in header or as default value (\" + EhcacheConstants.KEY + \")\", message.getExchange());\r\n }\r\n return value;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean lazyCompare(TypeInfo typeInfo, Object lazyObject, Object expectedObject) {\n if (expectedObject == null) {\n if (lazyObject != null) {\n throw new RuntimeException(\"Expected object is null but object is not null \" + lazyObject.toString() + \" typeInfo \" + typeInfo.toString());\n }\n return true;\n } else if (lazyObject == null) {\n throw new RuntimeException(\"Expected object is not null \\\"\" + expectedObject.toString() + \"\\\" typeInfo \" + typeInfo.toString() + \" but object is null\");\n }\n if (lazyObject instanceof Writable) {\n if (!lazyObject.equals(expectedObject)) {\n throw new RuntimeException(\"Expected object \" + expectedObject.toString() + \" and actual object \" + lazyObject.toString() + \" is not equal typeInfo \" + typeInfo.toString());\n }\n return true;\n }\n if (lazyObject instanceof LazyPrimitive) {\n Object primitiveObject = ((LazyPrimitive) lazyObject).getObject();\n PrimitiveTypeInfo primitiveTypeInfo = (PrimitiveTypeInfo) typeInfo;\n switch(primitiveTypeInfo.getPrimitiveCategory()) {\n case BOOLEAN:\n {\n if (!(primitiveObject instanceof LazyBoolean)) {\n throw new RuntimeException(\"Expected LazyBoolean\");\n }\n boolean value = ((LazyBoolean) primitiveObject).getWritableObject().get();\n boolean expected = ((BooleanWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Boolean field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case BYTE:\n {\n if (!(primitiveObject instanceof LazyByte)) {\n throw new RuntimeException(\"Expected LazyByte\");\n }\n byte value = ((LazyByte) primitiveObject).getWritableObject().get();\n byte expected = ((ByteWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Byte field mismatch (expected \" + (int) expected + \" found \" + (int) value + \")\");\n }\n }\n break;\n case SHORT:\n {\n if (!(primitiveObject instanceof LazyShort)) {\n throw new RuntimeException(\"Expected LazyShort\");\n }\n short value = ((LazyShort) primitiveObject).getWritableObject().get();\n short expected = ((ShortWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Short field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case INT:\n {\n if (!(primitiveObject instanceof LazyInteger)) {\n throw new RuntimeException(\"Expected LazyInteger\");\n }\n int value = ((LazyInteger) primitiveObject).getWritableObject().get();\n int expected = ((IntWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Int field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case LONG:\n {\n if (!(primitiveObject instanceof LazyLong)) {\n throw new RuntimeException(\"Expected LazyLong\");\n }\n long value = ((LazyLong) primitiveObject).getWritableObject().get();\n long expected = ((LongWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Long field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case FLOAT:\n {\n if (!(primitiveObject instanceof LazyFloat)) {\n throw new RuntimeException(\"Expected LazyFloat\");\n }\n float value = ((LazyFloat) primitiveObject).getWritableObject().get();\n float expected = ((FloatWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Float field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case DOUBLE:\n {\n if (!(primitiveObject instanceof LazyDouble)) {\n throw new RuntimeException(\"Expected LazyDouble\");\n }\n double value = ((LazyDouble) primitiveObject).getWritableObject().get();\n double expected = ((DoubleWritable) expectedObject).get();\n if (value != expected) {\n throw new RuntimeException(\"Double field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case STRING:\n {\n if (!(primitiveObject instanceof LazyString)) {\n throw new RuntimeException(\"Text expected writable not Text\");\n }\n Text value = ((LazyString) primitiveObject).getWritableObject();\n Text expected = ((Text) expectedObject);\n if (!value.equals(expected)) {\n throw new RuntimeException(\"String field mismatch (expected '\" + expected + \"' found '\" + value + \"')\");\n }\n }\n break;\n case CHAR:\n {\n if (!(primitiveObject instanceof LazyHiveChar)) {\n throw new RuntimeException(\"Expected LazyHiveChar\");\n }\n HiveChar value = ((LazyHiveChar) primitiveObject).getWritableObject().getHiveChar();\n HiveChar expected = ((HiveCharWritable) expectedObject).getHiveChar();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"HiveChar field mismatch (expected '\" + expected + \"' found '\" + value + \"')\");\n }\n }\n break;\n case VARCHAR:\n {\n if (!(primitiveObject instanceof LazyHiveVarchar)) {\n throw new RuntimeException(\"Expected LazyHiveVarchar\");\n }\n HiveVarchar value = ((LazyHiveVarchar) primitiveObject).getWritableObject().getHiveVarchar();\n HiveVarchar expected = ((HiveVarcharWritable) expectedObject).getHiveVarchar();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"HiveVarchar field mismatch (expected '\" + expected + \"' found '\" + value + \"')\");\n }\n }\n break;\n case DECIMAL:\n {\n if (!(primitiveObject instanceof LazyHiveDecimal)) {\n throw new RuntimeException(\"Expected LazyDecimal\");\n }\n HiveDecimal value = ((LazyHiveDecimal) primitiveObject).getWritableObject().getHiveDecimal();\n HiveDecimal expected = ((HiveDecimalWritable) expectedObject).getHiveDecimal();\n if (!value.equals(expected)) {\n DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) primitiveTypeInfo;\n int precision = decimalTypeInfo.getPrecision();\n int scale = decimalTypeInfo.getScale();\n throw new RuntimeException(\"Decimal field mismatch (expected \" + expected.toString() + \" found \" + value.toString() + \") precision \" + precision + \", scale \" + scale);\n }\n }\n break;\n case DATE:\n {\n if (!(primitiveObject instanceof LazyDate)) {\n throw new RuntimeException(\"Expected LazyDate\");\n }\n Date value = ((LazyDate) primitiveObject).getWritableObject().get();\n Date expected = ((DateWritableV2) expectedObject).get();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"Date field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case TIMESTAMP:\n {\n if (!(primitiveObject instanceof LazyTimestamp)) {\n throw new RuntimeException(\"TimestampWritableV2 expected writable not TimestampWritableV2\");\n }\n Timestamp value = ((LazyTimestamp) primitiveObject).getWritableObject().getTimestamp();\n Timestamp expected = ((TimestampWritableV2) expectedObject).getTimestamp();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"Timestamp field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case INTERVAL_YEAR_MONTH:\n {\n if (!(primitiveObject instanceof LazyHiveIntervalYearMonth)) {\n throw new RuntimeException(\"Expected LazyHiveIntervalYearMonth\");\n }\n HiveIntervalYearMonth value = ((LazyHiveIntervalYearMonth) primitiveObject).getWritableObject().getHiveIntervalYearMonth();\n HiveIntervalYearMonth expected = ((HiveIntervalYearMonthWritable) expectedObject).getHiveIntervalYearMonth();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"HiveIntervalYearMonth field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case INTERVAL_DAY_TIME:\n {\n if (!(primitiveObject instanceof LazyHiveIntervalDayTime)) {\n throw new RuntimeException(\"Expected writable LazyHiveIntervalDayTime\");\n }\n HiveIntervalDayTime value = ((LazyHiveIntervalDayTime) primitiveObject).getWritableObject().getHiveIntervalDayTime();\n HiveIntervalDayTime expected = ((HiveIntervalDayTimeWritable) expectedObject).getHiveIntervalDayTime();\n if (!value.equals(expected)) {\n throw new RuntimeException(\"HiveIntervalDayTime field mismatch (expected \" + expected + \" found \" + value + \")\");\n }\n }\n break;\n case BINARY:\n {\n if (!(primitiveObject instanceof LazyBinary)) {\n throw new RuntimeException(\"Expected LazyBinary\");\n }\n BytesWritable bytesWritable = ((LazyBinary) primitiveObject).getWritableObject();\n byte[] value = Arrays.copyOfRange(bytesWritable.getBytes(), 0, bytesWritable.getLength());\n BytesWritable bytesWritableExpected = (BytesWritable) expectedObject;\n byte[] expected = Arrays.copyOfRange(bytesWritableExpected.getBytes(), 0, bytesWritableExpected.getLength());\n if (value.length != expected.length) {\n throw new RuntimeException(\"Byte Array field mismatch (expected \" + Arrays.toString(expected) + \" found \" + Arrays.toString(value) + \")\");\n }\n for (int b = 0; b < value.length; b++) {\n if (value[b] != expected[b]) {\n throw new RuntimeException(\"Byte Array field mismatch (expected \" + Arrays.toString(expected) + \" found \" + Arrays.toString(value) + \")\");\n }\n }\n }\n break;\n default:\n throw new Error(\"Unknown primitive category \" + primitiveTypeInfo.getPrimitiveCategory());\n }\n } else if (lazyObject instanceof LazyArray) {\n LazyArray lazyArray = (LazyArray) lazyObject;\n List list = lazyArray.getList();\n List expectedList = (List) expectedObject;\n ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;\n if (list.size() != expectedList.size()) {\n throw new RuntimeException(\"SerDe deserialized list length does not match (list \" + list.toString() + \" list.size() \" + list.size() + \" expectedList \" + expectedList.toString() + \" expectedList.size() \" + expectedList.size() + \")\" + \" elementTypeInfo \" + listTypeInfo.getListElementTypeInfo().toString());\n }\n return lazyCompareList((ListTypeInfo) typeInfo, list, expectedList);\n } else if (typeInfo instanceof ListTypeInfo) {\n List list;\n if (lazyObject instanceof LazyBinaryArray) {\n list = ((LazyBinaryArray) lazyObject).getList();\n } else {\n list = (List) lazyObject;\n }\n List expectedList = (List) expectedObject;\n if (list.size() != expectedList.size()) {\n throw new RuntimeException(\"SerDe deserialized list length does not match (list \" + list.toString() + \" list.size() \" + list.size() + \" expectedList \" + expectedList.toString() + \" expectedList.size() \" + expectedList.size() + \")\");\n }\n return lazyCompareList((ListTypeInfo) typeInfo, list, expectedList);\n } else if (lazyObject instanceof LazyMap) {\n LazyMap lazyMap = (LazyMap) lazyObject;\n Map map = lazyMap.getMap();\n Map expectedMap = (Map) expectedObject;\n return lazyCompareMap((MapTypeInfo) typeInfo, map, expectedMap);\n } else if (typeInfo instanceof MapTypeInfo) {\n Map map;\n Map expectedMap = (Map) expectedObject;\n if (lazyObject instanceof LazyBinaryMap) {\n map = ((LazyBinaryMap) lazyObject).getMap();\n } else {\n map = (Map) lazyObject;\n }\n return lazyCompareMap((MapTypeInfo) typeInfo, map, expectedMap);\n } else if (lazyObject instanceof LazyStruct) {\n LazyStruct lazyStruct = (LazyStruct) lazyObject;\n List fields = lazyStruct.getFieldsAsList();\n List expectedFields = (List) expectedObject;\n StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;\n return lazyCompareStruct(structTypeInfo, fields, expectedFields);\n } else if (typeInfo instanceof StructTypeInfo) {\n ArrayList fields;\n if (lazyObject instanceof LazyBinaryStruct) {\n fields = ((LazyBinaryStruct) lazyObject).getFieldsAsList();\n } else {\n fields = (ArrayList) lazyObject;\n }\n List expectedFields = (List) expectedObject;\n StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;\n return lazyCompareStruct(structTypeInfo, fields, expectedFields);\n } else if (lazyObject instanceof LazyUnion) {\n LazyUnion union = (LazyUnion) lazyObject;\n StandardUnionObjectInspector.StandardUnion expectedUnion = (StandardUnionObjectInspector.StandardUnion) expectedObject;\n UnionTypeInfo unionTypeInfo = (UnionTypeInfo) typeInfo;\n return lazyCompareUnion(unionTypeInfo, union, expectedUnion);\n } else if (typeInfo instanceof UnionTypeInfo) {\n StandardUnionObjectInspector.StandardUnion expectedUnion = (StandardUnionObjectInspector.StandardUnion) expectedObject;\n UnionTypeInfo unionTypeInfo = (UnionTypeInfo) typeInfo;\n if (lazyObject instanceof LazyBinaryUnion) {\n return lazyCompareUnion(unionTypeInfo, (LazyBinaryUnion) lazyObject, expectedUnion);\n } else {\n return lazyCompareUnion(unionTypeInfo, (UnionObject) lazyObject, expectedUnion);\n }\n } else {\n System.err.println(\"Not implemented \" + typeInfo.getClass().getName());\n }\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void checkMapSize(int size) {\n if (size > MAP_SIZE_THRESHOLD) {\n throw new RuntimeException(String.format(\"distinct values has exceeded the threshold %s when calculate Mode in one group\", MAP_SIZE_THRESHOLD));\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "private void validateDataDirectory(BackupProgressCallback progress) throws Exception {\n File dir = new File(this.dataDirectory);\n if (progress != null) {\n progress.onProgress(\"Pr\u00fcfe Datenverzeichnis \" + dir.getAbsolutePath());\n }\n ArrayList subDirs = new ArrayList<>();\n if (!dir.exists()) {\n throw new Exception(\"Verzeichnis '\" + this.dataDirectory + \"' existiert nicht!\");\n }\n if (!dir.isDirectory()) {\n throw new Exception(\"'\" + this.dataDirectory + \"' ist kein Verzeichnis!\");\n }\n if (!dir.canRead()) {\n throw new Exception(\"Verzeichnis '\" + this.dataDirectory + \"' ist nicht lesbar!\");\n }\n if (!dir.canWrite()) {\n throw new Exception(\"Verzeichnis '\" + this.dataDirectory + \"' ist nicht schreibbar!\");\n }\n boolean dumpExists = false;\n for (File f : dir.listFiles()) {\n if (f.isDirectory()) {\n subDirs.add(f.getName());\n } else if (f.isFile()) {\n if (\"jlawyerdb-dump.sql\".equals(f.getName())) {\n dumpExists = true;\n }\n }\n }\n if (!subDirs.contains(\"archivefiles\") || !subDirs.contains(\"templates\") || !subDirs.contains(\"mastertemplates\") || !subDirs.contains(\"emailtemplates\") || !subDirs.contains(DIR_LETTERHEADS)) {\n throw new Exception(\"Verzeichnis unvollst\u00e4ndig - ben\u00f6tigt werden Unterverzeichnisse: archivefiles, templates, emailtemplates, mastertemplates, letterheads\");\n }\n if (dumpExists) {\n throw new Exception(\"Datenbanksicherung 'jlawyerdb-dump.sql' im Datenverzeichnis gefunden! Wurde aus Versehen das Backupverzeichnis gew\u00e4hlt?\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private Exchange receive(DataQueue queue, long timeout) throws Exception{\r\n DataQueueEntry entry;\r\n if (timeout >= 0) {\r\n int seconds = (int) timeout / 1000;\r\n LOG.trace(\"Reading from data queue: {} with {} seconds timeout\", queue.getName(), seconds);\r\n entry = queue.read(seconds);\r\n } else {\r\n LOG.trace(\"Reading from data queue: {} with no timeout\", queue.getName());\r\n entry = queue.read(-1);\r\n }\r\n Exchange exchange = getEndpoint().createExchange();\r\n if (entry != null) {\r\n exchange.getIn().setHeader(Jt400Endpoint.SENDER_INFORMATION, entry.getSenderInformation());\r\n if (getEndpoint().getFormat() == Jt400Configuration.Format.binary) {\r\n exchange.getIn().setBody(entry.getData());\r\n } else {\r\n exchange.getIn().setBody(entry.getString());\r\n }\r\n return exchange;\r\n }\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Ensure index and type for annotation.\n *\n * @param annotation the annotation\n * @param createIndexIfNotFound the create index if not found\n * @throws Exception the exception\n */\npublic static void ensureIndexAndTypeForAnnotation(Annotation annotation, Boolean createIndexIfNotFound) throws Exception {\n String esUrl = getEsUrl();\n if (Strings.isNullOrEmpty(esUrl)) {\n throw new Exception(\"ES host cannot be null\");\n }\n String indexName = buildIndexNameFromAnnotation(annotation);\n if (!Strings.isNullOrEmpty(indexName)) {\n indexName = indexName.toLowerCase();\n } else\n throw new Exception(\"Index/datasource/pac_ds name cannot be null or blank\");\n if (!isValidIndex(esUrl, indexName)) {\n // createIndex(esUrl, indexName);\n // DO NOT CREATE INDEX, this responsibility is delegated to pacman\n // cloud discovery, if you will create the index, parent , child\n // relation will be lost\n throw new Exception(\"Index is not yet ready to publish the data\");\n }\n String parentType, type;\n if (!Strings.isNullOrEmpty(annotation.get(PacmanSdkConstants.TARGET_TYPE).toString()) && !Strings.isNullOrEmpty(annotation.get(PacmanSdkConstants.TYPE).toString())) {\n parentType = annotation.get(PacmanSdkConstants.TARGET_TYPE).toString();\n type = getIssueTypeFromAnnotation(annotation);\n } else\n throw new Exception(\"targetType name cannot be null or blank\");\n if (!isValidType(esUrl, indexName, type)) {\n // createMappingWithParent(esUrl, indexName, type,parentType);do not\n // create now, this responsibility is delegated to Inventory\n // collector\n throw new Exception(\"Index exists but unable to find type to publish the data\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "public SubscriptionHelper getSubscriptionHelper() throws Exception{\r\n if (subscriptionHelper == null) {\r\n subscriptionHelper = new SubscriptionHelper(this);\r\n }\r\n return subscriptionHelper;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `address` to the URL query string\n if (getAddress() != null) {\n try {\n joiner.add(String.format(\"%saddress%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getAddress()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `type` to the URL query string\n if (getType() != null) {\n try {\n joiner.add(String.format(\"%stype%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `value` to the URL query string\n if (getValue() != null) {\n try {\n joiner.add(String.format(\"%svalue%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getValue()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "@Override\nprotected PreparedStatement initialValue() {\n try {\n Connection locConn = conn.get();\n PreparedStatement sel = locConn.prepareStatement(testedSqlQuery());\n toClose.add(sel);\n return sel;\n } catch (SQLException e) {\n throw new RuntimeException(\"Can't create thread local statement.\", e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private static boolean doAddSameScale(int leftSignum, long leftFast0, long leftFast1, long leftFast2, int rightSignum, long rightFast0, long rightFast1, long rightFast2, int scale, FastHiveDecimal fastResult) {\n if (leftSignum == rightSignum) {\n if (!doAddSameScaleSameSign(/* resultSignum */\n leftSignum, leftFast0, leftFast1, leftFast2, rightFast0, rightFast1, rightFast2, fastResult)) {\n // Handle overflow precision issue.\n if (scale > 0) {\n if (!fastRoundFractionalHalfUp(fastResult.fastSignum, fastResult.fast0, fastResult.fast1, fastResult.fast2, 1, fastResult)) {\n return false;\n }\n scale--;\n } else {\n // Overflow.\n return false;\n }\n }\n fastResult.fastScale = scale;\n } else {\n // Just compare the magnitudes (i.e. signums set to 1).\n int compareTo = fastCompareTo(1, leftFast0, leftFast1, leftFast2, 0, 1, rightFast0, rightFast1, rightFast2, 0);\n if (compareTo == 0) {\n // They cancel each other.\n fastResult.fastReset();\n return true;\n }\n if (compareTo == 1) {\n if (!doSubtractSameScaleNoUnderflow(/* resultSignum */\n leftSignum, leftFast0, leftFast1, leftFast2, rightFast0, rightFast1, rightFast2, fastResult)) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else {\n if (!doSubtractSameScaleNoUnderflow(/* resultSignum */\n rightSignum, rightFast0, rightFast1, rightFast2, leftFast0, leftFast1, leftFast2, fastResult)) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n }\n fastResult.fastScale = scale;\n }\n if (fastResult.fastSignum != 0) {\n final int precision = fastRawPrecision(fastResult);\n fastResult.fastIntegerDigitCount = Math.max(0, precision - fastResult.fastScale);\n }\n final int resultTrailingZeroCount = fastTrailingDecimalZeroCount(fastResult.fast0, fastResult.fast1, fastResult.fast2, fastResult.fastIntegerDigitCount, fastResult.fastScale);\n if (resultTrailingZeroCount > 0) {\n doFastScaleDown(fastResult, resultTrailingZeroCount, fastResult);\n if (fastResult.fastSignum == 0) {\n fastResult.fastScale = 0;\n } else {\n fastResult.fastScale -= resultTrailingZeroCount;\n }\n }\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public String getDriverClassPath() throws Error{\r\n return this.driverPath;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Login using kerberos and also updates the current logged in user\n *\n * @param principal - kerberos principal\n * @param keytabFile - keytab file\n * @throws IOException - if keytab file cannot be found\n */\npublic static void loginWithKerberosAndUpdateCurrentUser(String principal, String keytabFile) throws IOException {\n if (!UserGroupInformation.isSecurityEnabled()) {\n return;\n }\n if (principal == null || principal.isEmpty() || keytabFile == null || keytabFile.isEmpty()) {\n throw new RuntimeException(\"Kerberos principal and/or keytab is null or empty\");\n }\n final String serverPrincipal = SecurityUtil.getServerPrincipal(principal, \"0.0.0.0\");\n LOG.info(\"Logging in as \" + serverPrincipal + \" via \" + keytabFile + \" and updating current logged in user\");\n UserGroupInformation.loginUserFromKeytab(serverPrincipal, keytabFile);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void processingSqlWithoutSettingAutoCommit(Exchange exchange) throws Exception{\r\n String sql = exchange.getIn().getBody(String.class);\r\n Connection conn = null;\r\n boolean shouldCloseResources = true;\r\n try {\r\n conn = connectionStrategy.getConnection(dataSource);\r\n shouldCloseResources = createAndExecuteSqlStatement(exchange, sql, conn);\r\n } finally {\r\n if (shouldCloseResources && !connectionStrategy.isConnectionTransactional(conn, dataSource)) {\r\n closeQuietly(conn);\r\n } else {\r\n final Connection finalConn = conn;\r\n exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() {\r\n\r\n @Override\r\n public void onDone(Exchange exchange) {\r\n closeQuietly(finalConn);\r\n }\r\n\r\n @Override\r\n public int getOrder() {\r\n return LOWEST + 200;\r\n }\r\n });\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@VisibleForTesting\nstatic StartupOption parseArguments(String[] args) {\n int argsLen = (args == null) ? 0 : args.length;\n StartupOption startOpt = StartupOption.REGULAR;\n for (int i = 0; i < argsLen; i++) {\n String cmd = args[i];\n if (StartupOption.FORMAT.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.FORMAT;\n for (i = i + 1; i < argsLen; i++) {\n if (args[i].equalsIgnoreCase(StartupOption.CLUSTERID.getName())) {\n i++;\n if (i >= argsLen) {\n // if no cluster id specified, return null\n LOG.error(\"Must specify a valid cluster ID after the \" + StartupOption.CLUSTERID.getName() + \" flag\");\n return null;\n }\n String clusterId = args[i];\n // Make sure an id is specified and not another flag\n if (clusterId.isEmpty() || clusterId.equalsIgnoreCase(StartupOption.FORCE.getName()) || clusterId.equalsIgnoreCase(StartupOption.NONINTERACTIVE.getName())) {\n LOG.error(\"Must specify a valid cluster ID after the \" + StartupOption.CLUSTERID.getName() + \" flag\");\n return null;\n }\n startOpt.setClusterId(clusterId);\n }\n if (args[i].equalsIgnoreCase(StartupOption.FORCE.getName())) {\n startOpt.setForceFormat(true);\n }\n if (args[i].equalsIgnoreCase(StartupOption.NONINTERACTIVE.getName())) {\n startOpt.setInteractiveFormat(false);\n }\n }\n } else if (StartupOption.GENCLUSTERID.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.GENCLUSTERID;\n } else if (StartupOption.REGULAR.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.REGULAR;\n } else if (StartupOption.BACKUP.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.BACKUP;\n } else if (StartupOption.CHECKPOINT.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.CHECKPOINT;\n } else if (StartupOption.OBSERVER.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.OBSERVER;\n } else if (StartupOption.UPGRADE.getName().equalsIgnoreCase(cmd) || StartupOption.UPGRADEONLY.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.UPGRADE.getName().equalsIgnoreCase(cmd) ? StartupOption.UPGRADE : StartupOption.UPGRADEONLY;\n /* Can be followed by CLUSTERID with a required parameter or\n * RENAMERESERVED with an optional parameter\n */\n while (i + 1 < argsLen) {\n String flag = args[i + 1];\n if (flag.equalsIgnoreCase(StartupOption.CLUSTERID.getName())) {\n if (i + 2 < argsLen) {\n i += 2;\n startOpt.setClusterId(args[i]);\n } else {\n LOG.error(\"Must specify a valid cluster ID after the \" + StartupOption.CLUSTERID.getName() + \" flag\");\n return null;\n }\n } else if (flag.equalsIgnoreCase(StartupOption.RENAMERESERVED.getName())) {\n if (i + 2 < argsLen) {\n FSImageFormat.setRenameReservedPairs(args[i + 2]);\n i += 2;\n } else {\n FSImageFormat.useDefaultRenameReservedPairs();\n i += 1;\n }\n } else {\n LOG.error(\"Unknown upgrade flag: {}\", flag);\n return null;\n }\n }\n } else if (StartupOption.ROLLINGUPGRADE.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.ROLLINGUPGRADE;\n ++i;\n if (i >= argsLen) {\n LOG.error(\"Must specify a rolling upgrade startup option \" + RollingUpgradeStartupOption.getAllOptionString());\n return null;\n }\n startOpt.setRollingUpgradeStartupOption(args[i]);\n } else if (StartupOption.ROLLBACK.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.ROLLBACK;\n } else if (StartupOption.IMPORT.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.IMPORT;\n } else if (StartupOption.BOOTSTRAPSTANDBY.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.BOOTSTRAPSTANDBY;\n return startOpt;\n } else if (StartupOption.INITIALIZESHAREDEDITS.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.INITIALIZESHAREDEDITS;\n for (i = i + 1; i < argsLen; i++) {\n if (StartupOption.NONINTERACTIVE.getName().equals(args[i])) {\n startOpt.setInteractiveFormat(false);\n } else if (StartupOption.FORCE.getName().equals(args[i])) {\n startOpt.setForceFormat(true);\n } else {\n LOG.error(\"Invalid argument: \" + args[i]);\n return null;\n }\n }\n return startOpt;\n } else if (StartupOption.RECOVER.getName().equalsIgnoreCase(cmd)) {\n if (startOpt != StartupOption.REGULAR) {\n throw new RuntimeException(\"Can't combine -recover with \" + \"other startup options.\");\n }\n startOpt = StartupOption.RECOVER;\n while (++i < argsLen) {\n if (args[i].equalsIgnoreCase(StartupOption.FORCE.getName())) {\n startOpt.setForce(MetaRecoveryContext.FORCE_FIRST_CHOICE);\n } else {\n throw new RuntimeException(\"Error parsing recovery options: \" + \"can't understand option \\\"\" + args[i] + \"\\\"\");\n }\n }\n } else if (StartupOption.METADATAVERSION.getName().equalsIgnoreCase(cmd)) {\n startOpt = StartupOption.METADATAVERSION;\n } else {\n return null;\n }\n }\n return startOpt;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void startConnection() throws Exception{\r\n synchronized (this.connectionLock) {\r\n this.connectionStarted = true;\r\n if (this.connection != null) {\r\n try {\r\n this.connection.start();\r\n } catch (jakarta.jms.IllegalStateException e) {\r\n }\r\n }\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return the http(s) URL for Livy without credentials\n */\npublic String getLivyUrlWithoutAuthentication() {\n final URI uri = URI.create(m_livyUrl);\n try {\n return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()).toString();\n } catch (URISyntaxException e) {\n // should never happen (validated in model)\n throw new RuntimeException(\"Unable to build Livy URL: \" + e, e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "public boolean procedures(String line) throws Exception{\r\n return metadata(\"getProcedures\", new String[] { beeLine.getConnection().getCatalog(), null, arg1(line, \"procedure name pattern\", \"%\") });\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Exchange receive(KeyedDataQueue queue, long timeout) throws Exception{\r\n String key = getEndpoint().getSearchKey();\r\n String searchType = getEndpoint().getSearchType().name();\r\n KeyedDataQueueEntry entry;\r\n if (timeout >= 0) {\r\n int seconds = (int) timeout / 1000;\r\n LOG.trace(\"Reading from data queue: {} with {} seconds timeout\", queue.getName(), seconds);\r\n entry = queue.read(key, seconds, searchType);\r\n } else {\r\n LOG.trace(\"Reading from data queue: {} with no timeout\", queue.getName());\r\n entry = queue.read(key, -1, searchType);\r\n }\r\n Exchange exchange = createExchange(true);\r\n if (entry != null) {\r\n exchange.getIn().setHeader(Jt400Endpoint.SENDER_INFORMATION, entry.getSenderInformation());\r\n if (getEndpoint().getFormat() == Jt400Configuration.Format.binary) {\r\n exchange.getIn().setBody(entry.getData());\r\n exchange.getIn().setHeader(Jt400Endpoint.KEY, entry.getKey());\r\n } else {\r\n exchange.getIn().setBody(entry.getString());\r\n exchange.getIn().setHeader(Jt400Endpoint.KEY, entry.getKeyString());\r\n }\r\n return exchange;\r\n }\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public int[] getNonDictionaryPageWork(Column[] columns) {\n int lastPosition = 0;\n int positionCount = columns[0].getPositionCount();\n int[] groupIds = new int[positionCount];\n checkState(lastPosition <= positionCount, \"position count out of bound\");\n int remainingPositions = positionCount - lastPosition;\n long[] hashes = getHashesBufferArray();\n while (remainingPositions != 0) {\n int batchSize = min(remainingPositions, hashes.length);\n if (!flatHash.ensureAvailableCapacity(batchSize)) {\n throw new RuntimeException(\"Memory for flatHash is not enough\");\n }\n flatHash.computeHashes(columns, hashes, lastPosition, batchSize);\n for (int i = 0, position = lastPosition; i < batchSize; i++, position++) {\n groupIds[position] = flatHash.putIfAbsent(columns, lastPosition + i, hashes[i]);\n }\n lastPosition += batchSize;\n remainingPositions -= batchSize;\n }\n verify(lastPosition == positionCount);\n return groupIds;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "private static ObjectInspector getReflectionObjectInspectorNoCache(Type t, ObjectInspectorOptions options, boolean ensureInited) {\n if (t instanceof GenericArrayType) {\n GenericArrayType at = (GenericArrayType) t;\n return getStandardListObjectInspector(getReflectionObjectInspector(at.getGenericComponentType(), options, ensureInited));\n }\n if (t instanceof ParameterizedType) {\n ParameterizedType pt = (ParameterizedType) t;\n // List?\n if (List.class.isAssignableFrom((Class) pt.getRawType()) || Set.class.isAssignableFrom((Class) pt.getRawType())) {\n return getStandardListObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0], options, ensureInited));\n }\n // Map?\n if (Map.class.isAssignableFrom((Class) pt.getRawType())) {\n return getStandardMapObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0], options, ensureInited), getReflectionObjectInspector(pt.getActualTypeArguments()[1], options, ensureInited));\n }\n // Otherwise convert t to RawType so we will fall into the following if\n // block.\n t = pt.getRawType();\n }\n // Must be a class.\n if (!(t instanceof Class)) {\n throw new RuntimeException(ObjectInspectorFactory.class.getName() + \" internal error:\" + t);\n }\n Class c = (Class) t;\n // Java Primitive Type?\n if (PrimitiveObjectInspectorUtils.isPrimitiveJavaType(c)) {\n return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaType(c).primitiveCategory);\n }\n // Java Primitive Class?\n if (PrimitiveObjectInspectorUtils.isPrimitiveJavaClass(c)) {\n return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaClass(c).primitiveCategory);\n }\n // Primitive Writable class?\n if (PrimitiveObjectInspectorUtils.isPrimitiveWritableClass(c)) {\n return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveWritableClass(c).primitiveCategory);\n }\n // Enum class?\n if (Enum.class.isAssignableFrom(c)) {\n return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING);\n }\n // Must be struct because List and Map need to be ParameterizedType\n assert (!List.class.isAssignableFrom(c));\n assert (!Map.class.isAssignableFrom(c));\n // Create StructObjectInspector\n ReflectionStructObjectInspector oi;\n switch(options) {\n case JAVA:\n oi = new ReflectionStructObjectInspector();\n break;\n case THRIFT:\n oi = TUnion.class.isAssignableFrom(c) ? new ThriftUnionObjectInspector() : new ThriftStructObjectInspector();\n break;\n case PROTOCOL_BUFFERS:\n oi = new ProtocolBuffersStructObjectInspector();\n break;\n default:\n throw new RuntimeException(ObjectInspectorFactory.class.getName() + \": internal error.\");\n }\n // put it into the cache BEFORE it is initialized to make sure we can catch\n // recursive types.\n ReflectionStructObjectInspector prev = (ReflectionStructObjectInspector) objectInspectorCache.asMap().putIfAbsent(t, oi);\n if (prev != null) {\n oi = prev;\n } else {\n try {\n oi.init(t, c, options);\n } finally {\n if (!oi.inited) {\n // Failed to init, remove it from cache\n objectInspectorCache.asMap().remove(t, oi);\n }\n }\n }\n return oi;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `name` to the URL query string\n if (getName() != null) {\n try {\n joiner.add(String.format(\"%sname%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getName()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `fields` to the URL query string\n if (getFields() != null) {\n for (int i = 0; i < getFields().size(); i++) {\n if (getFields().get(i) != null) {\n joiner.add(getFields().get(i).toUrlQueryString(String.format(\"%sfields%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `is_struct` to the URL query string\n if (getIsStruct() != null) {\n try {\n joiner.add(String.format(\"%sis_struct%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getIsStruct()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `minalign` to the URL query string\n if (getMinalign() != null) {\n try {\n joiner.add(String.format(\"%sminalign%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getMinalign()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `bytesize` to the URL query string\n if (getBytesize() != null) {\n try {\n joiner.add(String.format(\"%sbytesize%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getBytesize()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `attributes` to the URL query string\n if (getAttributes() != null) {\n for (int i = 0; i < getAttributes().size(); i++) {\n if (getAttributes().get(i) != null) {\n joiner.add(getAttributes().get(i).toUrlQueryString(String.format(\"%sattributes%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `documentation` to the URL query string\n if (getDocumentation() != null) {\n for (int i = 0; i < getDocumentation().size(); i++) {\n try {\n joiner.add(String.format(\"%sdocumentation%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getDocumentation().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": " int countFromStartToEnd(DistributedLogManager dlm) throws Exception{\r\n int count = 0;\r\n try {\r\n LogReader reader = dlm.getInputStream(startDLSN);\r\n try {\r\n LogRecordWithDLSN record = reader.readNext(false);\r\n LogRecordWithDLSN preRecord = record;\r\n System.out.println(\"first record : \" + record);\r\n while (null != record) {\r\n if (record.getDlsn().compareTo(endDLSN) > 0) {\r\n break;\r\n }\r\n ++count;\r\n if (count % 1000 == 0) {\r\n logger.info(\"read {} records from {}...\", count, getStreamName());\r\n }\r\n preRecord = record;\r\n record = reader.readNext(false);\r\n }\r\n System.out.println(\"last record : \" + preRecord);\r\n } finally {\r\n reader.close();\r\n }\r\n } finally {\r\n dlm.close();\r\n }\r\n return count;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getOutputMessages(ProgramCall pgmCall) throws Exception{\r\n StringBuilder outputMsg = new StringBuilder();\r\n AS400Message[] messageList = pgmCall.getMessageList();\r\n for (int i = 0; i < messageList.length; ++i) {\r\n messageList[i].load();\r\n outputMsg.append(i).append(\") \");\r\n outputMsg.append(messageList[i].getText());\r\n outputMsg.append(\" - \");\r\n outputMsg.append(messageList[i].getHelp());\r\n outputMsg.append('\\n');\r\n }\r\n return outputMsg.toString();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Given a future, evaluate it.\n *

\n * Any exception generated in the future is\n * extracted and rethrown.\n *

\n * If this thread is interrupted while waiting for the future to complete,\n * an {@code InterruptedIOException} is raised.\n * However, if the future is cancelled, a {@code CancellationException}\n * is raised in the {code Future.get()} call. This is\n * passed up as is -so allowing the caller to distinguish between\n * thread interruption (such as when speculative task execution is aborted)\n * and future cancellation.\n * @param future future to evaluate\n * @param type of the result.\n * @return the result, if all went well.\n * @throws InterruptedIOException waiting for future completion was interrupted\n * @throws CancellationException if the future itself was cancelled\n * @throws IOException if something went wrong\n * @throws RuntimeException any nested RTE thrown\n */\npublic static T awaitFuture(final Future future) throws InterruptedIOException, IOException, CancellationException, RuntimeException {\n try {\n return future.get();\n } catch (CancellationException e) {\n LOG.debug(\"Future {} was cancelled\", future, e);\n throw e;\n } catch (InterruptedException e) {\n throw (InterruptedIOException) new InterruptedIOException(e.toString()).initCause(e);\n } catch (ExecutionException e) {\n return raiseInnerCause(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private SdkHttpFullRequest signRequest(SdkHttpFullRequest request, RequestExecutionContext context) throws Exception{\r\n updateInterceptorContext(request, context.executionContext());\r\n Signer signer = context.signer();\r\n MetricCollector metricCollector = context.attemptMetricCollector();\r\n if (shouldSign(signer)) {\r\n adjustForClockSkew(context.executionAttributes());\r\n Pair measuredSign = MetricUtils.measureDuration(() -> signer.sign(request, context.executionAttributes()));\r\n metricCollector.reportMetric(CoreMetric.SIGNING_DURATION, measuredSign.right());\r\n SdkHttpFullRequest signedRequest = measuredSign.left();\r\n if (signer instanceof AsyncRequestBodySigner) {\r\n AsyncRequestBody transformedRequestProvider = ((AsyncRequestBodySigner) signer).signAsyncRequestBody(signedRequest, context.requestProvider(), context.executionAttributes());\r\n context.requestProvider(transformedRequestProvider);\r\n }\r\n updateInterceptorContext(signedRequest, context.executionContext());\r\n return signedRequest;\r\n }\r\n return request;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\nvoid init(MRTaskReporter mrReporter, Map inputs, Map outputs) throws Exception {\n // TODO HIVE-14042. Abort handling.\n perfLogger.perfLogBegin(CLASS_NAME, PerfLogger.TEZ_INIT_OPERATORS);\n super.init(mrReporter, inputs, outputs);\n execContext = new ExecMapperContext(jconf);\n //Update JobConf using MRInput, info like filename comes via this\n mrInput = getMRInput(inputs);\n Configuration updatedConf = mrInput.getConfigUpdates();\n if (updatedConf != null) {\n for (Map.Entry entry : updatedConf) {\n jconf.set(entry.getKey(), entry.getValue());\n }\n }\n createOutputMap();\n // Start all the Outputs.\n for (Map.Entry outputEntry : outputs.entrySet()) {\n outputEntry.getValue().start();\n ((TezProcessor.TezKVOutputCollector) outMap.get(outputEntry.getKey())).initialize();\n }\n String queryId = HiveConf.getVar(jconf, HiveConf.ConfVars.HIVE_QUERY_ID);\n cache = ObjectCacheFactory.getCache(jconf, queryId, true);\n try {\n execContext.setJc(jconf);\n cacheKey = MAP_PLAN_KEY;\n MapWork mapWork = (MapWork) cache.retrieve(cacheKey, new Callable() {\n\n @Override\n public Object call() {\n return Utilities.getMapWork(jconf);\n }\n });\n Utilities.setMapWork(jconf, mapWork);\n if (mapWork instanceof MergeFileWork) {\n mfWork = (MergeFileWork) mapWork;\n } else {\n throw new RuntimeException(\"MapWork should be an instance of MergeFileWork.\");\n }\n String alias = mfWork.getAliasToWork().keySet().iterator().next();\n mergeOp = mfWork.getAliasToWork().get(alias);\n LOG.info(mergeOp.dump(0));\n MapredContext.init(true, new JobConf(jconf));\n ((TezContext) MapredContext.get()).setInputs(inputs);\n mergeOp.passExecContext(execContext);\n mergeOp.initializeLocalWork(jconf);\n mergeOp.initialize(jconf, null);\n OperatorUtils.setChildrenCollector(mergeOp.getChildOperators(), outMap);\n mergeOp.setReporter(reporter);\n MapredContext.get().setReporter(reporter);\n } catch (Throwable e) {\n if (e instanceof OutOfMemoryError) {\n // will this be true here?\n // Don't create a new object if we are already out of memory\n throw (OutOfMemoryError) e;\n } else if (e instanceof InterruptedException) {\n LOG.info(\"Hit an interrupt while initializing MergeFileRecordProcessor. Message={}\", e.getMessage());\n throw (InterruptedException) e;\n } else {\n throw new RuntimeException(\"Map operator initialization failed\", e);\n }\n }\n perfLogger.perfLogEnd(CLASS_NAME, PerfLogger.TEZ_INIT_OPERATORS);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * As we know that this list of {@link LoggedTask} objects is actually a list\n * of {@link ParsedTask} objects, we go ahead and cast them.\n * @return the list of {@link ParsedTask} objects\n */\nprivate List convertTasks(List tasks) {\n List result = new ArrayList();\n for (LoggedTask t : tasks) {\n if (t instanceof ParsedTask) {\n result.add((ParsedTask) t);\n } else {\n throw new RuntimeException(\"Unexpected type of tasks in the list...\");\n }\n }\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private boolean handle(ServerConfiguration conf, SanityFlags cmdFlags) throws Exception{\r\n ClientConfiguration clientConf = new ClientConfiguration();\r\n clientConf.addConfiguration(conf);\r\n clientConf.setEnsemblePlacementPolicy(LocalBookieEnsemblePlacementPolicy.class);\r\n clientConf.setAddEntryTimeout(cmdFlags.timeout);\r\n clientConf.setReadEntryTimeout(cmdFlags.timeout);\r\n BookKeeper bk = new BookKeeper(clientConf);\r\n LedgerHandle lh = null;\r\n try {\r\n lh = bk.createLedger(1, 1, BookKeeper.DigestType.MAC, new byte[0]);\r\n LOG.info(\"Create ledger {}\", lh.getId());\r\n for (int i = 0; i < cmdFlags.entries; i++) {\r\n String content = \"entry-\" + i;\r\n lh.addEntry(content.getBytes(UTF_8));\r\n }\r\n LOG.info(\"Written {} entries in ledger {}\", cmdFlags.entries, lh.getId());\r\n lh = bk.openLedger(lh.getId(), BookKeeper.DigestType.MAC, new byte[0]);\r\n if (lh.getLastAddConfirmed() != (cmdFlags.entries - 1)) {\r\n throw new Exception(\"Invalid last entry found on ledger. expecting: \" + (cmdFlags.entries - 1) + \" -- found: \" + lh.getLastAddConfirmed());\r\n }\r\n Enumeration entries = lh.readEntries(0, cmdFlags.entries - 1);\r\n int i = 0;\r\n while (entries.hasMoreElements()) {\r\n LedgerEntry entry = entries.nextElement();\r\n String actualMsg = new String(entry.getEntry(), UTF_8);\r\n String expectedMsg = \"entry-\" + (i++);\r\n if (!expectedMsg.equals(actualMsg)) {\r\n throw new Exception(\"Failed validation of received message - Expected: \" + expectedMsg + \", Actual: \" + actualMsg);\r\n }\r\n }\r\n LOG.info(\"Read {} entries from ledger {}\", i, lh.getId());\r\n } catch (Exception e) {\r\n LOG.warn(\"Error in bookie sanity test\", e);\r\n return false;\r\n } finally {\r\n if (lh != null) {\r\n bk.deleteLedger(lh.getId());\r\n LOG.info(\"Deleted ledger {}\", lh.getId());\r\n }\r\n bk.close();\r\n }\r\n LOG.info(\"Bookie sanity test succeeded\");\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SearchResult fetchSearchResultsAndSetTotal(String ag, String domain, boolean includeAllAssets, String targetType, String searchText, Map> lowLevelFilters, int from, int size, SearchResult result, String searchCategory) throws DataException {\n if (categoryToRefineByMap.size() == 0 || categoryToReturnFieldsMap.size() == 0) {\n fetchConfigFromDB();\n }\n Map mustFilter = new LinkedHashMap<>();\n Map mustTermsFilter = new LinkedHashMap<>();\n lowLevelFilters.forEach((displayName, valueList) -> {\n String esFieldName = getFieldMappingsForSearch(targetType, false, searchCategory).get(displayName) + \".keyword\";\n mustTermsFilter.put(esFieldName, valueList);\n });\n String esType = null;\n if (AssetConstants.ASSETS.equals(searchCategory)) {\n if (!includeAllAssets) {\n mustFilter.put(Constants.LATEST, Constants.TRUE);\n }\n mustFilter.put(AssetConstants.UNDERSCORE_ENTITY, Constants.TRUE);\n if (null == targetType) {\n mustTermsFilter.put(AssetConstants.UNDERSCORE_ENTITY_TYPE_KEYWORD, getTypesForDomain(ag, domain));\n }\n esType = targetType;\n }\n if (AssetConstants.POLICY_VIOLATIONS.equals(searchCategory)) {\n mustFilter.put(\"type.keyword\", \"issue\");\n mustTermsFilter.put(\"issueStatus.keyword\", Arrays.asList(\"open\", \"exempted\"));\n if (null == targetType) {\n esType = null;\n mustTermsFilter.put(\"targetType.keyword\", getTypesForDomain(ag, domain));\n } else {\n esType = \"issue_\" + targetType;\n }\n }\n if (AssetConstants.VULNERABILITIES.equals(searchCategory)) {\n mustFilter.put(Constants.LATEST, Constants.TRUE);\n mustTermsFilter.put(Constants.SEVEITY_LEVEL + \".keyword\", Arrays.asList(Constants.THREE, Constants.FOUR, Constants.FIVE));\n if (null != targetType) {\n mustFilter.put(\"_index\", \"aws_\" + targetType);\n }\n esType = Constants.VULN_INFO;\n }\n long start = System.currentTimeMillis();\n // if (!Strings.isNullOrEmpty(searchText)) {\n // searchText = \"\\\"\" + searchText + \"\\\"\";\n // }\n List> results = new ArrayList<>();\n if (!AssetConstants.VULNERABILITIES.equals(searchCategory)) {\n List> sortFieldsMapList = new ArrayList<>();\n Map resourceIdSort = new HashMap<>();\n resourceIdSort.put(\"_resourceid.keyword\", \"asc\");\n sortFieldsMapList.add(resourceIdSort);\n StringBuilder urlToQuery = new StringBuilder(PROTOCOL + esHost + \":\" + esPort + \"/\" + ag);\n if (!Strings.isNullOrEmpty(esType)) {\n mustFilter.put(AssetConstants.DOC_TYPE_KEYWORD, esType);\n }\n urlToQuery.append(\"/\").append(\"_search?from=\").append(from).append(\"&size=\").append(size);\n String resultJson = null;\n try {\n resultJson = getSearchResults(mustFilter, searchText, mustTermsFilter, getReturnFieldsForSearch(targetType, searchCategory), ag, searchCategory, size);\n } catch (Exception e) {\n LOGGER.error(\"Exception occurred for search category {} with message - {}\", searchCategory, e.getMessage());\n throw new RuntimeException(e);\n }\n JsonObject responseJson = null;\n if (!Objects.isNull(resultJson)) {\n responseJson = (JsonObject) JsonParser.parseString(resultJson);\n }\n if (responseJson != null && responseJson.has(AssetConstants.HITS) && responseJson.get(AssetConstants.HITS).getAsJsonObject().has(AssetConstants.TOTAL) && responseJson.get(AssetConstants.HITS).getAsJsonObject().get(AssetConstants.TOTAL).isJsonObject() && responseJson.get(AssetConstants.HITS).getAsJsonObject().get(AssetConstants.TOTAL).getAsJsonObject().has(AssetConstants.VALUE) && responseJson.get(AssetConstants.HITS).getAsJsonObject().get(AssetConstants.TOTAL).getAsJsonObject().get(AssetConstants.VALUE).isJsonPrimitive()) {\n result.setTotal(responseJson.get(AssetConstants.HITS).getAsJsonObject().get(AssetConstants.TOTAL).getAsJsonObject().get(AssetConstants.VALUE).getAsLong());\n }\n esRepository.processResponseAndSendTheScrollBack(resultJson, results);\n } else {\n List returnFields = getReturnFieldsForSearch(targetType, searchCategory);\n String docQueryString = \"\";\n docQueryString = new StringBuilder(docQueryString).append(\"[\").toString();\n int count = 0;\n for (String returnField : returnFields) {\n if (count == 0) {\n docQueryString = new StringBuilder(docQueryString).append(\"doc['\").append(returnField).append(\"'].value\").toString();\n } else {\n docQueryString = new StringBuilder(docQueryString).append(\"doc['\").append(returnField).append(\".keyword'].value\").toString();\n }\n count++;\n if (count < returnFields.size()) {\n docQueryString = new StringBuilder(docQueryString).append(\" +'~'+\").toString();\n }\n }\n docQueryString = docQueryString + \"]\";\n String url = PROTOCOL + esHost + \":\" + esPort + \"/\" + ag + \"/\" + Constants.VULN_INFO + \"/\" + Constants.SEARCH;\n Map query = new HashMap<>();\n query.put(\"query\", esRepository.buildQuery(mustFilter, null, null, searchText, mustTermsFilter, null));\n String queryString = new Gson().toJson(query);\n String payload = queryString.substring(0, queryString.length() - 1) + \", \\\"aggs\\\": {\\\"qids\\\": {\\\"terms\\\": {\\\"script\\\": \\\"\" + docQueryString + \"\\\",\\\"size\\\": 10000}}}}\";\n String responseJson = \"\";\n try {\n long startAggs = System.currentTimeMillis();\n LOGGER.debug(\"To get vuln aggs without dups, url is: {} and payload is: {}\", url, payload);\n responseJson = PacHttpUtils.doHttpPost(url, payload);\n LOGGER.debug(AssetConstants.DEBUG_RESPONSEJSON, responseJson);\n long endAggs = System.currentTimeMillis();\n LOGGER.debug(\"Time taken for ES call(vuln aggs sans dups) is: {}\", (endAggs - startAggs));\n results = getDistFromVulnAggsResult(responseJson, returnFields);\n } catch (Exception e) {\n LOGGER.error(\"Failed to retrieve vuln aggs for omni search \", e);\n }\n }\n results = pruneResults(results, targetType, searchCategory);\n if (AssetConstants.VULNERABILITIES.equals(searchCategory)) {\n result.setTotal(results.size());\n int end = from + size;\n if (end > (results.size())) {\n from = 0;\n end = results.size();\n }\n results = results.subList(from, end);\n }\n result.setResults(results);\n long end = System.currentTimeMillis();\n LOGGER.debug(\"Time taken to perform search for Search Category {} is: {}\", searchCategory, (end - start));\n return result;\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\npublic R invokeChecked(Object target, Object... args) throws Exception {\n try {\n if (argLength < 0) {\n return (R) method.invoke(target, args);\n } else {\n if (argLength != args.length) {\n LOG.error(\"expected {} arguments but got {}\", argLength, args.length);\n }\n return (R) method.invoke(target, Arrays.copyOfRange(args, 0, argLength));\n }\n } catch (InvocationTargetException e) {\n throwIfInstance(e.getCause(), Exception.class);\n throwIfInstance(e.getCause(), RuntimeException.class);\n throw new RuntimeException(e.getCause());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void validateUri(String uri) throws Exception{\r\n String[] s = uri.split(\":\");\r\n if (s.length < 2) {\r\n throw new IllegalArgumentException(INVALID_URI);\r\n }\r\n String[] t = s[1].split(\"\\\\?\");\r\n if (t.length < 1) {\r\n throw new IllegalArgumentException(INVALID_URI);\r\n }\r\n this.uri = t[0].trim();\r\n if (this.uri.startsWith(\"//\")) {\r\n this.uri = this.uri.substring(2);\r\n }\r\n if (!TYPES_LIST.contains(this.uri)) {\r\n throw new IllegalArgumentException(INVALID_URI);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "static AbstractSerDe createDelegate(String className) {\n final Class clazz;\n try {\n //noinspection unchecked\n clazz = (Class) Class.forName(className);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n // we are not setting conf thus null is okay\n return ReflectionUtil.newInstance(clazz, null);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": " void release() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ReplyManager createReplyManager() throws Exception{\r\n ReplyManager temporaryQueueReplyManager = new TemporaryQueueReplyManager(getEndpoint().getCamelContext());\r\n temporaryQueueReplyManager.setEndpoint(getEndpoint());\r\n String name = \"JmsReplyManagerTimeoutChecker[\" + getEndpoint().getEndpointConfiguredDestinationName() + \"]\";\r\n ScheduledExecutorService replyManagerScheduledExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(name, name);\r\n temporaryQueueReplyManager.setScheduledExecutorService(replyManagerScheduledExecutorService);\r\n name = \"JmsReplyManagerOnTimeout[\" + getEndpoint().getEndpointConfiguredDestinationName() + \"]\";\r\n int max = getEndpoint().getComponent().getReplyToOnTimeoutMaxConcurrentConsumers();\r\n if (max <= 0) {\r\n throw new IllegalArgumentException(\"The option replyToOnTimeoutMaxConcurrentConsumers must be >= 1\");\r\n }\r\n ExecutorService replyManagerExecutorService = getEndpoint().getCamelContext().getExecutorServiceManager().newThreadPool(temporaryQueueReplyManager, name, 0, max);\r\n temporaryQueueReplyManager.setOnTimeoutExecutorService(replyManagerExecutorService);\r\n ServiceHelper.startService(temporaryQueueReplyManager);\r\n return temporaryQueueReplyManager;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private KnativeConfiguration getKnativeConfiguration() throws Exception{\r\n final String envConfig = System.getenv(KnativeConstants.CONFIGURATION_ENV_VARIABLE);\r\n final KnativeConfiguration conf = configuration.copy();\r\n if (conf.getTransportOptions() == null) {\r\n conf.setTransportOptions(new HashMap<>());\r\n }\r\n if (conf.getFilters() == null) {\r\n conf.setFilters(new HashMap<>());\r\n }\r\n if (conf.getCeOverride() == null) {\r\n conf.setCeOverride(new HashMap<>());\r\n }\r\n if (conf.getEnvironment() == null) {\r\n KnativeEnvironment env;\r\n if (environmentPath != null) {\r\n env = KnativeEnvironment.mandatoryLoadFromResource(getCamelContext(), this.environmentPath);\r\n } else if (envConfig != null) {\r\n env = envConfig.startsWith(\"file:\") || envConfig.startsWith(\"classpath:\") ? KnativeEnvironment.mandatoryLoadFromResource(getCamelContext(), envConfig) : KnativeEnvironment.mandatoryLoadFromSerializedString(envConfig);\r\n } else {\r\n env = CamelContextHelper.findSingleByType(getCamelContext(), KnativeEnvironment.class);\r\n }\r\n if (env == null) {\r\n throw new IllegalStateException(\"Cannot load Knative configuration from file or env variable\");\r\n }\r\n conf.setEnvironment(env);\r\n }\r\n return conf;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @return Instance of Unsafe class.\n */\nstatic Unsafe unsafe() {\n try {\n return Unsafe.getUnsafe();\n } catch (SecurityException ignored) {\n try {\n return AccessController.doPrivileged(new PrivilegedExceptionAction() {\n\n @Override\n public Unsafe run() throws Exception {\n Field f = Unsafe.class.getDeclaredField(\"theUnsafe\");\n f.setAccessible(true);\n return (Unsafe) f.get(null);\n }\n });\n } catch (PrivilegedActionException e) {\n throw new RuntimeException(\"Could not initialize intrinsics.\", e.getCause());\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public void createKeyspace(String keyspaceName, boolean ifNotExists, Map createOptions) throws Exception {\n CreateKeyspaceStart keyspaceStart = SchemaBuilder.createKeyspace(keyspaceName);\n if (ifNotExists) {\n keyspaceStart = keyspaceStart.ifNotExists();\n }\n CreateKeyspace createKeyspace = keyspaceStart.withReplicationOptions(createOptions);\n // Execute this\n try (CqlSession session = getSessionBuilder().build()) {\n session.execute(createKeyspace.build());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private void applyReplaceRouteFromWith(ModelCamelContext context, CamelMainTest annotation) throws Exception{\r\n for (final String fromEndpoint : annotation.replaceRouteFromWith()) {\r\n final int index = fromEndpoint.indexOf('=');\r\n if (index == -1) {\r\n throw new RuntimeCamelException(\"The attribute replaceRouteFromWith doesn't have the expected format, it should be of type \\\"route-id-1=new-uri-1\\\", ...\");\r\n }\r\n AdviceWith.adviceWith(context.getRouteDefinition(fromEndpoint.substring(0, index)), context, new AdviceWithRouteBuilder() {\r\n\r\n @Override\r\n public void configure() {\r\n replaceFromWith(fromEndpoint.substring(index + 1));\r\n }\r\n });\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Class getUdfClass() {\n try {\n return getUdfClassInternal();\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected void addNotificationListener() throws Exception{\r\n JMXEndpoint ep = getEndpoint();\r\n NotificationFilter nf = ep.getNotificationFilter();\r\n if (nf == null && ep.getObservedAttribute() != null) {\r\n LOG.debug(\"Observing attribute: {}\", ep.getObservedAttribute());\r\n boolean match = !ep.isNotifyDiffer();\r\n nf = new JMXConsumerNotificationFilter(ep.getObservedAttribute(), ep.getStringToCompare(), match);\r\n }\r\n ObjectName objectName = ep.getJMXObjectName();\r\n getServerConnection().addNotificationListener(objectName, this, nf, ep.getHandback());\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getHadoopVersion() {\n if (hadoopVersion == null) {\n System.out.println(\"detecting hadoop.version from loaded libs\");\n try {\n String hadoopPropsLoc = \"/META-INF/maven/org.apache.hadoop/hadoop-hdfs/pom.properties\";\n URL hadoopPropsURL = getClass().getResource(hadoopPropsLoc);\n if (hadoopPropsURL == null) {\n throw new RuntimeException(\"failed to get hadoop properties: \" + hadoopPropsLoc);\n }\n try (InputStream is = hadoopPropsURL.openStream()) {\n Properties props = new Properties();\n props.load(is);\n hadoopVersion = props.getProperty(\"version\");\n if (hadoopVersion == null) {\n throw new RuntimeException(\"version property not found\");\n }\n } catch (IOException e) {\n throw new RuntimeException(\"unable to extract hadoop.version from: \" + hadoopPropsURL, e);\n }\n } catch (Exception e) {\n throw new RuntimeException(\"can't get hadoop.version ; specify manually using hadoop.version property!\");\n }\n }\n return hadoopVersion;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static KeyStore getSelfSignedKeyStore() throws Exception{\r\n URL selfSignedJks = SdkHttpClientTestSuite.class.getResource(\"/selfSigned.jks\");\r\n KeyStore keyStore = KeyStore.getInstance(\"jks\");\r\n try (InputStream stream = selfSignedJks.openStream()) {\r\n keyStore.load(stream, \"changeit\".toCharArray());\r\n }\r\n return keyStore;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected X509Certificate getSigningCertificate() throws Exception{\r\n return null;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * start a new map-reduce job to do the truncation, almost the same as ExecDriver.\n */\n@Override\npublic int execute() {\n HiveConf.setVar(job, HiveConf.ConfVars.HIVE_INPUT_FORMAT, BucketizedHiveInputFormat.class.getName());\n success = true;\n HiveFileFormatUtils.prepareJobOutput(job);\n job.setOutputFormat(HiveOutputFormatImpl.class);\n job.setMapperClass(work.getMapperClass());\n Context ctx = context;\n boolean ctxCreated = false;\n if (ctx == null) {\n ctx = new Context(job);\n ctxCreated = true;\n }\n job.setMapOutputKeyClass(NullWritable.class);\n job.setMapOutputValueClass(NullWritable.class);\n if (work.getNumMapTasks() != null) {\n job.setNumMapTasks(work.getNumMapTasks());\n }\n // zero reducers\n job.setNumReduceTasks(0);\n // HIVE-23354 enforces that MR speculative execution is disabled\n job.setBoolean(MRJobConfig.REDUCE_SPECULATIVE, false);\n job.setBoolean(MRJobConfig.MAP_SPECULATIVE, false);\n if (work.getMinSplitSize() != null) {\n HiveConf.setLongVar(job, HiveConf.ConfVars.MAPRED_MIN_SPLIT_SIZE, work.getMinSplitSize().longValue());\n }\n if (work.getInputformat() != null) {\n HiveConf.setVar(job, HiveConf.ConfVars.HIVE_INPUT_FORMAT, work.getInputformat());\n }\n String inpFormat = HiveConf.getVar(job, HiveConf.ConfVars.HIVE_INPUT_FORMAT);\n LOG.info(\"Using \" + inpFormat);\n try {\n job.setInputFormat(JavaUtils.loadClass(inpFormat));\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n Path outputPath = this.work.getOutputDir();\n Path tempOutPath = Utilities.toTempPath(outputPath);\n try {\n FileSystem fs = tempOutPath.getFileSystem(job);\n if (!fs.exists(tempOutPath)) {\n fs.mkdirs(tempOutPath);\n }\n } catch (IOException e) {\n setException(e);\n LOG.error(\"Can't make path \" + outputPath, e);\n return 6;\n }\n job.setOutputKeyClass(NullWritable.class);\n job.setOutputValueClass(NullWritable.class);\n int returnVal = 0;\n RunningJob rj = null;\n boolean noName = StringUtils.isEmpty(job.get(MRJobConfig.JOB_NAME));\n String jobName = null;\n if (noName && this.getQueryPlan() != null) {\n int maxlen = conf.getIntVar(HiveConf.ConfVars.HIVE_JOBNAME_LENGTH);\n jobName = Utilities.abbreviate(this.getQueryPlan().getQueryStr(), maxlen - 6);\n }\n if (noName) {\n // This is for a special case to ensure unit tests pass\n job.set(MRJobConfig.JOB_NAME, jobName != null ? jobName : \"JOB\" + ThreadLocalRandom.current().nextInt());\n }\n try {\n addInputPaths(job, work);\n MapredWork mrWork = new MapredWork();\n mrWork.setMapWork(work);\n Utilities.setMapRedWork(job, mrWork, ctx.getMRTmpPath());\n // remove the pwd from conf file so that job tracker doesn't show this\n // logs\n String pwd = HiveConf.getVar(job, HiveConf.ConfVars.METASTORE_PWD);\n if (pwd != null) {\n HiveConf.setVar(job, HiveConf.ConfVars.METASTORE_PWD, \"HIVE\");\n }\n JobClient jc = new JobClient(job);\n String addedJars = Utilities.getResourceFiles(job, SessionState.ResourceType.JAR);\n if (!addedJars.isEmpty()) {\n job.set(\"tmpjars\", addedJars);\n }\n // make this client wait if job trcker is not behaving well.\n Throttle.checkJobTracker(job, LOG);\n // Finally SUBMIT the JOB!\n rj = jc.submitJob(job);\n this.jobID = rj.getJobID();\n returnVal = jobExecHelper.progress(rj, jc, ctx);\n success = (returnVal == 0);\n } catch (Exception e) {\n String mesg = rj != null ? (\"Ended Job = \" + rj.getJobID()) : \"Job Submission failed\";\n // Has to use full name to make sure it does not conflict with\n // org.apache.commons.lang3.StringUtils\n LOG.error(mesg, e);\n setException(e);\n success = false;\n returnVal = 1;\n } finally {\n try {\n if (ctxCreated) {\n ctx.clear();\n }\n if (rj != null) {\n if (returnVal != 0) {\n rj.killJob();\n }\n }\n ColumnTruncateMapper.jobClose(outputPath, success, job, console, work.getDynPartCtx(), null);\n } catch (Exception e) {\n LOG.warn(\"Failed while cleaning up \", e);\n } finally {\n HadoopJobExecHelper.runningJobs.remove(rj);\n }\n }\n return (returnVal);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected Object getPayload(Exchange exchange, NitriteEndpoint endpoint) throws Exception{\r\n Class targetClass = endpoint.getRepositoryClass() != null ? endpoint.getRepositoryClass() : Document.class;\r\n Object payload = expression.evaluate(exchange, Object.class);\r\n return endpoint.getCamelContext().getTypeConverter().mandatoryConvertTo(targetClass, exchange, payload);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void wireInParallel(int wireListSize) throws Exception{\r\n final int parallelThread = Runtime.getRuntime().availableProcessors();\r\n CompletionService ecs = ExecutorProviderFactory.getExecutorProvider().getCompletionService();\r\n int size = wireListSize / parallelThread;\r\n for (int i = 1; i <= parallelThread; i++) {\r\n List subList = wireList.subList((i - 1) * size, i == parallelThread ? wireListSize : i * size);\r\n ecs.submit(new WiringExecutor(classLoader, invokerLookups, subList));\r\n }\r\n for (int i = 1; i <= parallelThread; i++) {\r\n ecs.take().get();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ZooKeeper zookeeperClient(DockerClient docker) throws Exception{\r\n String connectString = BookKeeperClusterUtils.zookeeperConnectString(docker);\r\n CompletableFuture future = new CompletableFuture<>();\r\n ZooKeeper zk = new ZooKeeper(connectString, 10000, (e) -> {\r\n if (e.getState().equals(KeeperState.SyncConnected)) {\r\n future.complete(null);\r\n }\r\n });\r\n future.get();\r\n return zk;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": " void init(@Nonnull Context context) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SyndFeed createFeed(String feedUri, ClassLoader classLoader) throws Exception{\r\n ClassLoader tccl = Thread.currentThread().getContextClassLoader();\r\n try {\r\n Thread.currentThread().setContextClassLoader(classLoader);\r\n return createSyndFeed(feedUri);\r\n } finally {\r\n Thread.currentThread().setContextClassLoader(tccl);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/*\n * This method should be implemented by all SequenceSpaceInnerSelector and UnsequenceSpaceInnerSelector.\n * It takes the list of tsfile in a time partition as input, and returns a list of list. Each list in\n * the returned list is the source files of one compaction tasks.\n */\ndefault List selectInnerSpaceTask(List resources) {\n throw new RuntimeException(\"This kind of selector cannot be used to select inner space task\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected HazelcastInstance getOrCreateHzInstance(CamelContext context, Map parameters) throws Exception{\r\n HazelcastInstance hzInstance = null;\r\n Config config = null;\r\n hzInstance = resolveAndRemoveReferenceParameter(parameters, HAZELCAST_INSTANCE_PARAM, HazelcastInstance.class);\r\n if (hzInstance == null && parameters.get(HAZELCAST_INSTANCE_NAME_PARAM) != null) {\r\n hzInstance = Hazelcast.getHazelcastInstanceByName((String) parameters.get(HAZELCAST_INSTANCE_NAME_PARAM));\r\n }\r\n if (hzInstance == null) {\r\n config = resolveAndRemoveReferenceParameter(parameters, HAZELCAST_CONFIGU_PARAM, Config.class);\r\n if (config == null) {\r\n String configUri = getAndRemoveParameter(parameters, HAZELCAST_CONFIGU_URI_PARAM, String.class);\r\n if (configUri != null) {\r\n configUri = getCamelContext().resolvePropertyPlaceholders(configUri);\r\n }\r\n if (configUri != null) {\r\n InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, configUri);\r\n config = new XmlConfigBuilder(is).build();\r\n }\r\n }\r\n if (hazelcastInstance == null && config == null) {\r\n config = new XmlConfigBuilder().build();\r\n config.getProperties().setProperty(\"hazelcast.version.check.enabled\", \"false\");\r\n config.getProperties().setProperty(\"hazelcast.phone.home.enabled\", \"false\");\r\n hzInstance = Hazelcast.newHazelcastInstance(config);\r\n } else if (config != null) {\r\n if (ObjectHelper.isNotEmpty(config.getInstanceName())) {\r\n hzInstance = Hazelcast.getOrCreateHazelcastInstance(config);\r\n } else {\r\n hzInstance = Hazelcast.newHazelcastInstance(config);\r\n }\r\n }\r\n if (hzInstance != null) {\r\n if (this.customHazelcastInstances.add(hzInstance)) {\r\n LOGGER.debug(\"Add managed HZ instance {}\", hzInstance.getName());\r\n }\r\n }\r\n }\r\n return hzInstance == null ? hazelcastInstance : hzInstance;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private software.amazon.awssdk.services.ses.model.RawMessage createRawMessage(Exchange exchange) throws Exception{\r\n software.amazon.awssdk.services.ses.model.RawMessage.Builder message = software.amazon.awssdk.services.ses.model.RawMessage.builder();\r\n jakarta.mail.Message content = exchange.getIn().getBody(jakarta.mail.Message.class);\r\n OutputStream byteOutput = new ByteArrayOutputStream();\r\n try {\r\n content.writeTo(byteOutput);\r\n } catch (Exception e) {\r\n LOG.error(\"Cannot write to byte Array\");\r\n throw e;\r\n }\r\n byte[] messageByteArray = ((ByteArrayOutputStream) byteOutput).toByteArray();\r\n message.data(SdkBytes.fromByteBuffer(ByteBuffer.wrap(messageByteArray)));\r\n return message.build();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List topologicalSort() throws Exception{\r\n lock.readLock().lock();\r\n try {\r\n Map.Entry> entry = topologicalSortImpl();\r\n if (entry.getKey()) {\r\n return entry.getValue();\r\n }\r\n throw new Exception(\"serious error: graph has cycle ! \");\r\n } finally {\r\n lock.readLock().unlock();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic CompletableFuture browseWithInterceptor(PlcBrowseRequest browseRequest, PlcBrowseRequestInterceptor interceptor) {\n CompletableFuture future = new CompletableFuture<>();\n executorService.execute(() -> {\n int numQueries = browseRequest.getQueryNames().size();\n // Initialize the response structures.\n Map responseCodes = new HashMap<>(numQueries);\n Map> responseItems = new HashMap<>(numQueries);\n Map matchers = new HashMap<>(numQueries);\n for (String queryName : browseRequest.getQueryNames()) {\n responseCodes.put(queryName, PlcResponseCode.OK);\n responseItems.put(queryName, new ArrayList<>());\n PlcQuery query = browseRequest.getQuery(queryName);\n if (query instanceof CtrlXQuery) {\n CtrlXQuery ctrlXQuery = (CtrlXQuery) query;\n matchers.put(queryName, ctrlXQuery.getMatcher());\n } else {\n future.completeExceptionally(new PlcInvalidTagException(\"Invalid query type: \" + query.getClass().getName()));\n }\n }\n // Now walk through the tree and for each leaf-node, check which queries it matches.\n // Start by initializing the list with the lists of all normal and real-time nodes.\n Queue uncheckedNodeList = new LinkedList<>();\n try {\n // Initialize the list with all normal node names\n BrowseData nodeNames = dataLayerApi.getNodeNames();\n if (nodeNames.getValue() != null) {\n uncheckedNodeList.addAll(nodeNames.getValue());\n }\n // Then add all real-time node names.\n BrowseData realtimeNodeNames = dataLayerApi.getRealtimeNodeNames();\n if (realtimeNodeNames.getValue() != null) {\n uncheckedNodeList.addAll(realtimeNodeNames.getValue());\n }\n } catch (ApiException e) {\n throw new RuntimeException(e);\n }\n // Now keep on resolving paths till the list is empty.\n while (!uncheckedNodeList.isEmpty()) {\n String curNode = uncheckedNodeList.poll();\n try {\n ReadNode200Response readNode200Response = nodesApi.readNode(curNode, \"browse\");\n List children = readNode200Response.getValue();\n // If this node has no children, then this is a leaf-node,\n // and it's a potential match for any of the queries.\n if (children.isEmpty()) {\n List matchingQueryNames = matchers.entrySet().stream().filter(entry -> entry.getValue().matches(curNode)).map(Map.Entry::getKey).collect(Collectors.toList());\n // If there's at least one matching query, read the \"metadata\", which contains information\n // on if the property is readable or writable.\n if (!matchingQueryNames.isEmpty()) {\n // TODO: Implement the reading of \"metadate\" as this contains information on if the\n // tag is readable or writable.\n /*try {\n ReadNode200Response metaDataResponse = nodesApi.readNode(curNode, \"metadata\");\n System.out.println(metaDataResponse);\n } catch (ApiException e) {\n e.printStackTrace();\n }*/\n matchingQueryNames.forEach(queryName -> responseItems.get(queryName).add(new DefaultPlcBrowseItem(new CtrlXTag(curNode, PlcValueType.BOOL, Collections.emptyList()), curNode, true, true, true, false, Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap())));\n }\n } else // If this node has children, then it's branch, and we need to add its children to the queue.\n {\n // Add all children to the list.\n uncheckedNodeList.addAll(children.stream().map(child -> curNode + \"/\" + child).collect(Collectors.toList()));\n }\n } catch (ApiException e) {\n // Ignore ...\n }\n }\n future.complete(new DefaultPlcBrowseResponse(browseRequest, responseCodes, responseItems));\n });\n return future;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private String createDynamicAllocationSummary() {\n final int driverMemoryMb = estimateDriverMemoryMb();\n final int driverCores = getDriverCores();\n final int executorMemoryMb = estimateExecutorMemoryMb();\n final int executorCores = m_settings.getExecutorResources().getCores();\n final int minExecutors = m_settings.getDynamicExecutorsMin();\n final int maxExecutors = m_settings.getDynamicExecutorsMax();\n final int totalCoresMin = driverCores + minExecutors * executorCores;\n final int totalCoresMax = driverCores + maxExecutors * executorCores;\n final int totalMemoryMinMb = driverMemoryMb + minExecutors * executorMemoryMb;\n final int totalMemoryMaxMb = driverMemoryMb + maxExecutors * executorMemoryMb;\n final MemoryUnit containerDisplayMemoryUnit = chooseConvenientMemoryUnit(Math.max(driverMemoryMb, executorMemoryMb));\n final MemoryUnit totalDisplayMemoryUnit = chooseConvenientMemoryUnit(Math.max(totalMemoryMinMb, totalMemoryMaxMb));\n final Map reps = new HashMap<>();\n reps.put(\"driver.memory\", renderMemoryForDisplay(driverMemoryMb, containerDisplayMemoryUnit));\n reps.put(\"driver.cores\", Integer.toString(driverCores));\n reps.put(\"executors.min\", Integer.toString(minExecutors));\n reps.put(\"executors.max\", Integer.toString(maxExecutors));\n reps.put(\"executor.memory\", renderMemoryForDisplay(executorMemoryMb, containerDisplayMemoryUnit));\n reps.put(\"executor.cores\", Integer.toString(executorCores));\n reps.put(\"total.memory.min\", renderMemoryForDisplay(totalMemoryMinMb, totalDisplayMemoryUnit));\n reps.put(\"total.memory.max\", renderMemoryForDisplay(totalMemoryMaxMb, totalDisplayMemoryUnit));\n reps.put(\"total.cores.min\", Integer.toString(totalCoresMin));\n reps.put(\"total.cores.max\", Integer.toString(totalCoresMax));\n reps.put(\"memory.unit.containers\", containerDisplayMemoryUnit.toString());\n reps.put(\"memory.unit.total\", totalDisplayMemoryUnit.toString());\n try (InputStream r = getClass().getResourceAsStream(\"resource_summary_dynamic_allocation.template\")) {\n return TextTemplateUtil.fillOutTemplate(r, reps);\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to read context description template\");\n }\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "protected Object doExecute(Object executor, String methodName, Map properties) throws Exception{\r\n Method method = executor.getClass().getDeclaredMethod(methodName, TwilioRestClient.class);\r\n return method.invoke(executor, properties.getOrDefault(\"client\", getRestClient()));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private GoogleCredentials createDefault() throws Exception{\r\n GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();\r\n Collection scopes = Collections.singletonList(BigqueryScopes.BIGQUERY);\r\n if (credentials.createScopedRequired()) {\r\n credentials = credentials.createScoped(scopes);\r\n }\r\n return credentials;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\nprivate List getResources() throws Exception {\n applyConcurrentTaskLimits();\n // will be null the first time\n Resource headRoom = Resources.clone(getAvailableResources());\n AllocateResponse response;\n /*\n * If contact with RM is lost, the AM will wait MR_AM_TO_RM_WAIT_INTERVAL_MS\n * milliseconds before aborting. During this interval, AM will still try\n * to contact the RM.\n */\n try {\n response = makeRemoteRequest();\n // Reset retry count if no exception occurred.\n retrystartTime = System.currentTimeMillis();\n } catch (ApplicationAttemptNotFoundException e) {\n // This can happen if the RM has been restarted. If it is in that state,\n // this application must clean itself up.\n eventHandler.handle(new JobEvent(this.getJob().getID(), JobEventType.JOB_AM_REBOOT));\n throw new RMContainerAllocationException(\"Resource Manager doesn't recognize AttemptId: \" + this.getContext().getApplicationAttemptId(), e);\n } catch (ApplicationMasterNotRegisteredException e) {\n LOG.info(\"ApplicationMaster is out of sync with ResourceManager,\" + \" hence resync and send outstanding requests.\");\n // RM may have restarted, re-register with RM.\n lastResponseID = 0;\n register();\n addOutstandingRequestOnResync();\n return null;\n } catch (InvalidLabelResourceRequestException e) {\n // If Invalid label exception is received means the requested label doesnt\n // have access so killing job in this case.\n String diagMsg = \"Requested node-label-expression is invalid: \" + StringUtils.stringifyException(e);\n LOG.info(diagMsg);\n JobId jobId = this.getJob().getID();\n eventHandler.handle(new JobDiagnosticsUpdateEvent(jobId, diagMsg));\n eventHandler.handle(new JobEvent(jobId, JobEventType.JOB_KILL));\n throw e;\n } catch (Exception e) {\n // This can happen when the connection to the RM has gone down. Keep\n // re-trying until the retryInterval has expired.\n if (System.currentTimeMillis() - retrystartTime >= retryInterval) {\n LOG.error(\"Could not contact RM after \" + retryInterval + \" milliseconds.\");\n eventHandler.handle(new JobEvent(this.getJob().getID(), JobEventType.JOB_AM_REBOOT));\n throw new RMContainerAllocationException(\"Could not contact RM after \" + retryInterval + \" milliseconds.\");\n }\n // Throw this up to the caller, which may decide to ignore it and\n // continue to attempt to contact the RM.\n throw e;\n }\n Resource newHeadRoom = getAvailableResources();\n List newContainers = response.getAllocatedContainers();\n // Setting NMTokens\n if (response.getNMTokens() != null) {\n for (NMToken nmToken : response.getNMTokens()) {\n NMTokenCache.setNMToken(nmToken.getNodeId().toString(), nmToken.getToken());\n }\n }\n // Setting AMRMToken\n if (response.getAMRMToken() != null) {\n updateAMRMToken(response.getAMRMToken());\n }\n List finishedContainers = response.getCompletedContainersStatuses();\n // propagate preemption requests\n final PreemptionMessage preemptReq = response.getPreemptionMessage();\n if (preemptReq != null) {\n preemptionPolicy.preempt(new PreemptionContext(assignedRequests), preemptReq);\n }\n if (newContainers.size() + finishedContainers.size() > 0 || !headRoom.equals(newHeadRoom)) {\n //something changed\n recalculateReduceSchedule = true;\n if (LOG.isDebugEnabled() && !headRoom.equals(newHeadRoom)) {\n LOG.debug(\"headroom=\" + newHeadRoom);\n }\n }\n if (LOG.isDebugEnabled()) {\n for (Container cont : newContainers) {\n LOG.debug(\"Received new Container :\" + cont);\n }\n }\n //Called on each allocation. Will know about newly blacklisted/added hosts.\n computeIgnoreBlacklisting();\n handleUpdatedNodes(response);\n handleJobPriorityChange(response);\n // Handle receiving the timeline collector address and token for this app.\n MRAppMaster.RunningAppContext appContext = (MRAppMaster.RunningAppContext) this.getContext();\n if (appContext.getTimelineV2Client() != null) {\n appContext.getTimelineV2Client().setTimelineCollectorInfo(response.getCollectorInfo());\n }\n for (ContainerStatus cont : finishedContainers) {\n processFinishedContainer(cont);\n }\n return newContainers;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private int truncateStreams(final Namespace namespace) throws Exception{\r\n Iterator streamCollection = namespace.getLogs();\r\n final List streams = new ArrayList();\r\n while (streamCollection.hasNext()) {\r\n String s = streamCollection.next();\r\n if (null != streamPrefix) {\r\n if (s.startsWith(streamPrefix)) {\r\n streams.add(s);\r\n }\r\n } else {\r\n streams.add(s);\r\n }\r\n }\r\n if (0 == streams.size()) {\r\n return 0;\r\n }\r\n System.out.println(\"Streams : \" + streams);\r\n if (!getForce() && !IOUtils.confirmPrompt(\"Do you want to truncate \" + streams.size() + \" streams ?\")) {\r\n return 0;\r\n }\r\n numThreads = Math.min(streams.size(), numThreads);\r\n final int numStreamsPerThreads = streams.size() / numThreads + 1;\r\n Thread[] threads = new Thread[numThreads];\r\n for (int i = 0; i < numThreads; i++) {\r\n final int tid = i;\r\n threads[i] = new Thread(\"Truncate-\" + i) {\r\n\r\n @Override\r\n public void run() {\r\n try {\r\n truncateStreams(namespace, streams, tid, numStreamsPerThreads);\r\n System.out.println(\"Thread \" + tid + \" finished.\");\r\n } catch (IOException e) {\r\n System.err.println(\"Thread \" + tid + \" quits with exception : \" + e.getMessage());\r\n }\r\n }\r\n };\r\n threads[i].start();\r\n }\r\n for (int i = 0; i < numThreads; i++) {\r\n threads[i].join();\r\n }\r\n return 0;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void startWithCalcite() throws Exception{\r\n final String[] args = { CalciteChinookMetaFactory.class.getName() };\r\n this.server = Main.start(args, 0, AvaticaProtobufHandler::new);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List collect(SubscriptionVH subscription) {\n List diagnosticSettingVHList = new ArrayList<>();\n try {\n String apiUrlTemplate = \"https://management.azure.com/%s/providers/Microsoft.Insights/diagnosticSettings?api-version=2021-05-01-preview\";\n String accessToken = azureCredentialProvider.getToken(subscription.getTenant());\n String url = String.format(apiUrlTemplate, URLEncoder.encode(\"/subscriptions/\" + subscription.getSubscriptionId(), java.nio.charset.StandardCharsets.UTF_8.toString()));\n String response = CommonUtils.doHttpGet(url, \"Bearer\", accessToken);\n JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject();\n JsonArray diagnosticSettings = responseObj.getAsJsonArray(\"value\");\n for (JsonElement diagnosticSetting : diagnosticSettings) {\n DiagnosticSettingVH diagnosticSettingVH = new DiagnosticSettingVH();\n diagnosticSettingVH.setId(diagnosticSetting.getAsJsonObject().getAsJsonPrimitive(\"id\").getAsString());\n diagnosticSettingVH.setName(diagnosticSetting.getAsJsonObject().getAsJsonPrimitive(\"name\").getAsString());\n diagnosticSettingVH.setSubscriptionName(subscription.getSubscriptionName());\n diagnosticSettingVH.setSubscription(subscription.getSubscriptionId());\n diagnosticSettingVH.setResourceGroupName(subscription.getResourceGroupName());\n diagnosticSettingVH.setSubscriptionId(subscription.getSubscriptionId());\n diagnosticSettingVH.setRegion(Util.getRegionValue(subscription, diagnosticSetting.getAsJsonObject().getAsJsonPrimitive(\"location\").getAsString()));\n JsonObject properties = diagnosticSetting.getAsJsonObject().getAsJsonObject(\"properties\");\n JsonArray logs = properties.getAsJsonArray(\"logs\");\n Set enabledCategories = new HashSet();\n for (JsonElement diagnosticLog : logs) {\n if (diagnosticLog.getAsJsonObject().getAsJsonPrimitive(\"enabled\").getAsBoolean()) {\n enabledCategories.add(diagnosticLog.getAsJsonObject().getAsJsonPrimitive(\"category\").getAsString());\n }\n }\n diagnosticSettingVH.setEnabledCategories(enabledCategories);\n diagnosticSettingVHList.add(diagnosticSettingVH);\n }\n log.info(\"Size of diagnostic settings: {}\", diagnosticSettingVHList.size());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n return diagnosticSettingVHList;\n}", "smellKey": "S112", "smellId": null, "repo": "PaladinCloud_CE", "language": "java"} {"function": "private Response invoke(WebClient client, String httpMethod, Object body) throws Exception{\r\n Response response = client.invoke(httpMethod, body);\r\n int code = response.getStatus();\r\n switch(code) {\r\n case 200:\r\n case 201:\r\n case 204:\r\n break;\r\n case 400:\r\n case 401:\r\n case 403:\r\n case 404:\r\n case 405:\r\n case 406:\r\n case 415:\r\n ServiceNowExceptionModel model = response.readEntity(ServiceNowExceptionModel.class);\r\n throw new ServiceNowException(code, model.getStatus(), model.getError().get(\"message\"), model.getError().get(\"detail\"));\r\n default:\r\n throw new ServiceNowException(code, response.readEntity(Map.class));\r\n }\r\n return response;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean fastUpdatePrecisionScale(final int fastSignum, long fast0, long fast1, long fast2, int fastIntegerDigitCount, int fastScale, int maxPrecision, int maxScale, FastCheckPrecisionScaleStatus status, FastHiveDecimal fastResult) {\n switch(status) {\n case UPDATE_SCALE_DOWN:\n {\n fastResult.fastSignum = fastSignum;\n // Throw away lower digits.\n if (!fastRoundFractionalHalfUp(fastSignum, fast0, fast1, fast2, fastScale - maxScale, fastResult)) {\n return false;\n }\n fastResult.fastScale = maxScale;\n // CONSIDER: For now, recompute integerDigitCount...\n fastResult.fastIntegerDigitCount = Math.max(0, fastRawPrecision(fastResult) - fastResult.fastScale);\n // And, round up may cause us to exceed our precision/scale...\n final int maxIntegerDigitCount = maxPrecision - maxScale;\n if (fastResult.fastIntegerDigitCount > maxIntegerDigitCount) {\n return false;\n }\n // Scaling down may have opened up trailing zeroes...\n final int trailingZeroCount = fastTrailingDecimalZeroCount(fastResult.fast0, fastResult.fast1, fastResult.fast2, fastResult.fastIntegerDigitCount, fastResult.fastScale);\n if (trailingZeroCount > 0) {\n // Scale down again.\n doFastScaleDown(fastResult, trailingZeroCount, fastResult);\n fastResult.fastScale -= trailingZeroCount;\n }\n }\n break;\n default:\n throw new RuntimeException(\"Unexpected fast check precision scale status \" + status);\n }\n return true;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static CompactionResponse initiateCompactionForPartition(Table table, Partition partition, CompactionRequest compactionRequest, String hostName, TxnStore txnHandler, HiveConf inputConf) throws MetaException {\n ValidTxnList validTxnList = TxnCommonUtils.createValidReadTxnList(txnHandler.getOpenTxns(), 0);\n HiveConf conf = new HiveConf(inputConf);\n conf.set(ValidTxnList.VALID_TXNS_KEY, validTxnList.writeToString());\n CompactionResponse compactionResponse;\n CompactionInfo compactionInfo = new CompactionInfo(table.getDbName(), table.getTableName(), compactionRequest.getPartitionname(), compactionRequest.getType());\n compactionInfo.initiatorId = compactionRequest.getInitiatorId();\n compactionInfo.orderByClause = compactionRequest.getOrderByClause();\n compactionInfo.initiatorVersion = compactionRequest.getInitiatorVersion();\n if (compactionRequest.getNumberOfBuckets() > 0) {\n compactionInfo.numberOfBuckets = compactionRequest.getNumberOfBuckets();\n }\n compactionInfo.poolName = compactionRequest.getPoolName();\n try {\n StorageDescriptor sd = resolveStorageDescriptor(table, partition);\n String runAs = TxnUtils.findUserToRunAs(sd.getLocation(), table, conf);\n LOG.info(\"Checking to see if we should compact partition {} of table {}.{}\", compactionInfo.partName, table.getDbName(), table.getTableName());\n compactionResponse = scheduleCompactionIfRequired(compactionInfo, table, partition, runAs, false, hostName, txnHandler, conf);\n } catch (IOException | InterruptedException | MetaException e) {\n LOG.error(\"Error occurred while Checking if we should compact partition {} of table {}.{} Exception: {}\", compactionInfo.partName, table.getDbName(), table.getTableName(), e.getMessage());\n throw new RuntimeException(e);\n }\n return compactionResponse;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@HiveDecimalWritableVersionV2\npublic int rawPrecision() {\n if (!isSet()) {\n throw new RuntimeException(\"no value set\");\n }\n return fastRawPrecision();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void process(MessageQueue queue, Exchange exchange) throws Exception{\r\n String msgText = exchange.getIn().getBody(String.class);\r\n byte[] messageKey = exchange.getIn().getHeader(Jt400Constants.MESSAGE_REPLYTO_KEY, byte[].class);\r\n if (ObjectHelper.isNotEmpty(messageKey) && ObjectHelper.isNotEmpty(msgText)) {\r\n queue.reply(messageKey, msgText);\r\n } else {\r\n queue.sendInformational(msgText);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ZoneId parseTimeZone(String timeZoneStr) {\n if (timeZoneStr == null || timeZoneStr.trim().isEmpty() || timeZoneStr.trim().toLowerCase().equals(\"local\")) {\n // default\n return ZoneId.systemDefault();\n }\n try {\n return ZoneId.of(timeZoneStr);\n } catch (DateTimeException e1) {\n // default\n throw new RuntimeException(\"Invalid time zone displacement value\", e1);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Invoke the corresponding Java method for this step\n * @param mapping from current request\n * @param form from current request\n * @param ctx from current request\n * @param response from current request\n * @param target enclosing Struts action\n * @return Struts forward corresponding to this wizard step\n * @throws Exception something bad happened hopefully handled upstream\n */\npublic final ActionForward invoke(ActionMapping mapping, ActionForm form, RequestContext ctx, HttpServletResponse response, Action target) throws Exception {\n Object[] args = new Object[5];\n args[0] = mapping;\n args[1] = form;\n args[2] = ctx;\n args[3] = response;\n args[4] = this;\n return (ActionForward) this.wizardMethod.invoke(target, args);\n}", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": " void begin() throws Exception{\r\n throw new UnsupportedOperationException(\"Resource without transaction support\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@ShellMethod(key = \"show logfile metadata\", value = \"Read commit metadata from log files\")\npublic String showLogFileCommits(@ShellOption(value = \"--logFilePathPattern\", help = \"Fully qualified path for the log file\") final String logFilePathPattern, @ShellOption(value = { \"--limit\" }, help = \"Limit commits\", defaultValue = \"-1\") final Integer limit, @ShellOption(value = { \"--sortBy\" }, help = \"Sorting Field\", defaultValue = \"\") final String sortByField, @ShellOption(value = { \"--desc\" }, help = \"Ordering\", defaultValue = \"false\") final boolean descending, @ShellOption(value = { \"--headeronly\" }, help = \"Print Header Only\", defaultValue = \"false\") final boolean headerOnly) throws IOException {\n HoodieStorage storage = HoodieCLI.getTableMetaClient().getStorage();\n List logFilePaths = FSUtils.getGlobStatusExcludingMetaFolder(storage, new StoragePath(logFilePathPattern)).stream().map(status -> status.getPath().toString()).collect(Collectors.toList());\n Map, Tuple2, Map>, Integer>>> commitCountAndMetadata = new HashMap<>();\n int numCorruptBlocks = 0;\n int dummyInstantTimeCount = 0;\n String basePath = HoodieCLI.basePath;\n for (String logFilePath : logFilePaths) {\n StoragePath path = new StoragePath(logFilePath);\n String pathString = path.toString();\n String fileName;\n if (pathString.contains(basePath)) {\n String[] split = pathString.split(basePath);\n fileName = split[split.length - 1];\n } else {\n fileName = path.getName();\n }\n Schema writerSchema = TableSchemaResolver.readSchemaFromLogFile(storage, path);\n try (Reader reader = HoodieLogFormat.newReader(storage, new HoodieLogFile(path), writerSchema)) {\n // read the avro blocks\n while (reader.hasNext()) {\n HoodieLogBlock n = reader.next();\n String instantTime;\n AtomicInteger recordCount = new AtomicInteger(0);\n if (n instanceof HoodieCorruptBlock) {\n try {\n instantTime = n.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME);\n if (instantTime == null) {\n throw new Exception(\"Invalid instant time \" + instantTime);\n }\n } catch (Exception e) {\n numCorruptBlocks++;\n instantTime = \"corrupt_block_\" + numCorruptBlocks;\n // could not read metadata for corrupt block\n }\n } else {\n instantTime = n.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME);\n if (instantTime == null) {\n // This can happen when reading archived commit files since they were written without any instant time\n dummyInstantTimeCount++;\n instantTime = \"dummy_instant_time_\" + dummyInstantTimeCount;\n }\n if (n instanceof HoodieDataBlock) {\n try (ClosableIterator> recordItr = ((HoodieDataBlock) n).getRecordIterator(HoodieRecordType.AVRO)) {\n recordItr.forEachRemaining(r -> recordCount.incrementAndGet());\n }\n }\n }\n if (commitCountAndMetadata.containsKey(instantTime)) {\n commitCountAndMetadata.get(instantTime).add(new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()), new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));\n } else {\n List, Tuple2, Map>, Integer>> list = new ArrayList<>();\n list.add(new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()), new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));\n commitCountAndMetadata.put(instantTime, list);\n }\n }\n }\n }\n List rows = new ArrayList<>();\n ObjectMapper objectMapper = new ObjectMapper();\n for (Map.Entry, Tuple2, Map>, Integer>>> entry : commitCountAndMetadata.entrySet()) {\n String instantTime = entry.getKey();\n for (Tuple3, Tuple2, Map>, Integer> tuple3 : entry.getValue()) {\n Comparable[] output = new Comparable[6];\n output[0] = tuple3._1()._1();\n output[1] = instantTime;\n output[2] = tuple3._3();\n output[3] = tuple3._1()._2().toString();\n output[4] = objectMapper.writeValueAsString(tuple3._2()._1());\n output[5] = objectMapper.writeValueAsString(tuple3._2()._2());\n rows.add(output);\n }\n }\n TableHeader header = new TableHeader().addTableHeaderField(HoodieTableHeaderFields.HEADER_FILE_PATH).addTableHeaderField(HoodieTableHeaderFields.HEADER_INSTANT_TIME).addTableHeaderField(HoodieTableHeaderFields.HEADER_RECORD_COUNT).addTableHeaderField(HoodieTableHeaderFields.HEADER_BLOCK_TYPE).addTableHeaderField(HoodieTableHeaderFields.HEADER_HEADER_METADATA).addTableHeaderField(HoodieTableHeaderFields.HEADER_FOOTER_METADATA);\n return HoodiePrintHelper.print(header, new HashMap<>(), sortByField, descending, limit, headerOnly, rows);\n}", "smellKey": "S112", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "public void startWithRaw() throws Exception{\r\n final String[] args = { RawChinookMetaFactory.class.getName() };\r\n this.server = Main.start(args, 0, AvaticaProtobufHandler::new);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\npublic Pair> passThroughTraits(RelTraitSet required) {\n throw new RuntimeException(getClass().getName() + \"#passThroughTraits() is not implemented.\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public boolean typeinfo(String line) throws Exception{\r\n return metadata(\"getTypeInfo\", new String[0]);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "static DefaultExchangeHolder deserialize(byte[] bytes) {\n try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n ObjectInputStream ois = new ClassLoadingAwareObjectInputStream(bais)) {\n return (DefaultExchangeHolder) ois.readObject();\n } catch (IOException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "@Override\npublic boolean hasNext() {\n if (eventCount >= maxEvents) {\n // If we've already satisfied the number of events we were supposed to deliver, we end it.\n return false;\n }\n if ((batchIter != null) && (batchIter.hasNext())) {\n // If we have a valid batchIter and it has more elements, return them.\n return true;\n }\n // If we're here, we want more events, and either batchIter is null, or batchIter\n // has reached the end of the current batch. Let's fetch the next batch.\n try {\n fetchNextBatch();\n } catch (IOException e) {\n // Regrettable that we have to wrap the IOException into a RuntimeException,\n // but throwing the exception is the appropriate result here, and hasNext()\n // signature will only allow RuntimeExceptions. Iterator.hasNext() really\n // should have allowed IOExceptions\n throw new RuntimeException(e.getMessage(), e);\n }\n // New batch has been fetched. If it's not empty, we have more elements to process.\n return !batch.isEmpty();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": " void close() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Benchmark\npublic void syncRead(FileSystemChoice fsChoice, Blackhole blackhole) throws Exception {\n FSDataInputStream stream = fsChoice.fs.open(DATA_PATH);\n List result = new ArrayList<>();\n for (int m = 0; m < 100; ++m) {\n byte[] buffer = new byte[READ_SIZE];\n stream.readFully(m * SEEK_SIZE, buffer);\n result.add(buffer);\n }\n blackhole.consume(result);\n stream.close();\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void bindToRegistry(Registry registry) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static org.mustangproject.Invoice getEInvoice(com.jdimension.jlawyer.persistence.Invoice caseInvoice, AppUserBean senderUser) throws Exception {\n SimpleDateFormat df = new SimpleDateFormat(\"dd.MM.yyyy\");\n org.mustangproject.Invoice i = new org.mustangproject.Invoice();\n i.setNumber(caseInvoice.getInvoiceNumber());\n i.setDueDate(caseInvoice.getDueDate());\n i.setIssueDate(caseInvoice.getCreationDate());\n i.setDetailedDeliveryPeriod(caseInvoice.getPeriodFrom(), caseInvoice.getPeriodTo());\n i.setDeliveryDate(caseInvoice.getPeriodTo());\n if (StringUtils.isEmpty(senderUser.getCompany()) || StringUtils.isEmpty(senderUser.getStreet()) || StringUtils.isEmpty(senderUser.getZipCode()) || StringUtils.isEmpty(senderUser.getCity()) || StringUtils.isEmpty(senderUser.getCountryCodeInvoicing())) {\n throw new Exception(\"Informationen des Rechnungssenders unvollst\u00e4ndig: Adresse. Bitte im Men\u00fc 'Administration' - 'Nutzerverwaltung' erg\u00e4nzen\");\n }\n TradeParty sender = new TradeParty(senderUser.getCompany(), senderUser.getStreet(), senderUser.getZipCode(), senderUser.getCity(), senderUser.getCountryCodeInvoicing());\n if (!StringUtils.isEmpty(senderUser.getAdjunct())) {\n sender.setAdditionalAddressExtension(senderUser.getAdjunct());\n }\n if (!StringUtils.isEmpty(senderUser.getTaxNr())) {\n sender.addTaxID(senderUser.getTaxNr());\n }\n if (!StringUtils.isEmpty(senderUser.getTaxVatId())) {\n sender.addVATID(senderUser.getTaxVatId());\n }\n if (StringUtils.isEmpty(senderUser.getBankBic()) || StringUtils.isEmpty(senderUser.getBankIban())) {\n throw new Exception(\"Informationen des Rechnungssenders unvollst\u00e4ndig: Bankverbindung. Bitte im Men\u00fc 'Administration' - 'Nutzerverwaltung' erg\u00e4nzen\");\n }\n if (com.jdimension.jlawyer.persistence.Invoice.PAYMENTTYPE_BANKTRANSFER.equals(caseInvoice.getPaymentType())) {\n i.setPaymentTermDescription(\"Bitte \u00fcberweisen Sie den Rechnungsbetrag bis zum \" + df.format(caseInvoice.getDueDate()) + \".\");\n } else if (com.jdimension.jlawyer.persistence.Invoice.PAYMENTTYPE_DIRECTDEBIT.equals(caseInvoice.getPaymentType())) {\n i.setPaymentTermDescription(\"Den Rechnungsbetrag wird sp\u00e4testens zum \" + df.format(caseInvoice.getDueDate()) + \" per Lastschrift (Mandatsreferenz \" + caseInvoice.getContact().getSepaReference() + \") von Ihrem Konto \" + caseInvoice.getContact().getBankAccount() + \" eingezogen.\");\n } else {\n i.setPaymentTermDescription(\"Die Rechnung ist zahlbar bis zum \" + df.format(caseInvoice.getDueDate()) + \".\");\n }\n // zahlung per \u00fcberweisung\n BankDetails senderBank = new BankDetails(senderUser.getBankIban(), senderUser.getBankBic());\n senderBank.setAccountName(senderUser.getBankName());\n sender.addBankDetails(senderBank);\n // zahlug per lastschrift\n //sender.addDebitDetails(debitDetail);\n if (StringUtils.isEmpty(senderUser.getDisplayName()) || StringUtils.isEmpty(senderUser.getPhone()) || StringUtils.isEmpty(senderUser.getEmail())) {\n throw new Exception(\"Informationen des Rechnungssenders unvollst\u00e4ndig: Anzeigename/Telefon/E-Mail. Bitte im Men\u00fc 'Administration' - 'Nutzerverwaltung' erg\u00e4nzen\");\n }\n sender.setContact(new Contact(senderUser.getDisplayName(), senderUser.getPhone(), senderUser.getEmail()));\n i.setSender(sender);\n if (caseInvoice.getContact() == null) {\n throw new Exception(\"Rechnungsempf\u00e4nger fehlt.\");\n }\n if (StringUtils.isEmpty(caseInvoice.getContact().toDisplayName()) || StringUtils.isEmpty(caseInvoice.getContact().getStreet()) || StringUtils.isEmpty(caseInvoice.getContact().getZipCode()) || StringUtils.isEmpty(caseInvoice.getContact().getCity())) {\n throw new Exception(\"Informationen des Rechnungsempf\u00e4ngers unvollst\u00e4ndig: Adresse.\");\n }\n i.setRecipient(new TradeParty(caseInvoice.getContact().toDisplayName(), caseInvoice.getContact().getStreet() + \" \" + caseInvoice.getContact().getStreetNumber(), caseInvoice.getContact().getZipCode(), caseInvoice.getContact().getCity(), \"DE\"));\n if (!StringUtils.isEmpty(caseInvoice.getContact().getLeitwegId()))\n i.setReferenceNumber(caseInvoice.getContact().getLeitwegId());\n List positions = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n positions = locator.lookupArchiveFileServiceRemote().getInvoicePositions(caseInvoice.getId());\n } catch (Exception ex) {\n log.error(\"error getting invoice positions\", ex);\n throw new Exception(\"Fehler beim Laden der Rechnungspositionen: \" + ex.getMessage());\n }\n // line items\n for (InvoicePosition pos : positions) {\n BigDecimal taxRate = pos.getTaxRate();\n if (!caseInvoice.isSmallBusiness()) {\n taxRate = BigDecimal.ZERO;\n }\n i.addItem(new Item(new Product(pos.getName(), pos.getDescription(), \"C62\", taxRate), /*price*/\n pos.getUnitPrice(), /*qty*/\n pos.getUnits()));\n }\n return i;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void printEppStatsHeader(DistributedLogManager dlm) throws Exception{\r\n String label = \"Ledger Placement :\";\r\n System.out.println(label);\r\n Map totals = new HashMap();\r\n List segments = dlm.getLogSegments();\r\n for (LogSegmentMetadata segment : segments) {\r\n if (include(segment)) {\r\n merge(totals, getBookieStats(segment));\r\n }\r\n }\r\n List> entries = new ArrayList>(totals.entrySet());\r\n Collections.sort(entries, new Comparator>() {\r\n\r\n @Override\r\n public int compare(Map.Entry o1, Map.Entry o2) {\r\n return o2.getValue() - o1.getValue();\r\n }\r\n });\r\n int width = 0;\r\n int totalEntries = 0;\r\n for (Map.Entry entry : entries) {\r\n width = Math.max(width, label.length() + 1 + entry.getKey().toString().length());\r\n totalEntries += entry.getValue();\r\n }\r\n for (Map.Entry entry : entries) {\r\n System.out.println(String.format(\"%\" + width + \"s\\t%6.2f%%\\t\\t%d\", entry.getKey(), entry.getValue() * 1.0 / totalEntries, entry.getValue()));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object getKey(final Message message) throws Exception{\r\n String value;\r\n value = message.getHeader(CaffeineConstants.KEY, String.class);\r\n if (value == null) {\r\n value = configuration.getKey();\r\n }\r\n if (value == null) {\r\n throw new CamelExchangeException(\"No value provided in header or as default value (\" + CaffeineConstants.KEY + \")\", message.getExchange());\r\n }\r\n return value;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static byte[] encodeDelegationTokenInformation(DelegationTokenInformation token) {\n try {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(bos);\n WritableUtils.writeVInt(out, token.password.length);\n out.write(token.password);\n out.writeLong(token.renewDate);\n out.flush();\n return bos.toByteArray();\n } catch (IOException ex) {\n throw new RuntimeException(\"Failed to encode token.\", ex);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public Fact[] loadMetaModel(JarInputStream jis) throws Exception{\r\n JarEntry entry;\r\n while ((entry = jis.getNextJarEntry()) != null) {\r\n if (entry.getName().equals(\"factmodel.xml\")) {\r\n return fromXML(jis);\r\n }\r\n }\r\n throw new IllegalArgumentException(\"This is not a valid drools model jar - no factmodel.xml found.\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void readXmlFileToMapWithFileInputStream(String type, String filename, InputStream fileInputStream, Map map) throws IOException {\n Document dom;\n try {\n DocumentBuilderFactory builder = XMLUtils.newSecureDocumentBuilderFactory();\n DocumentBuilder db = builder.newDocumentBuilder();\n dom = db.parse(fileInputStream);\n // Examples:\n // host1\n // host2123\n // host3-1\n // host4, host5,host61800\n Element doc = dom.getDocumentElement();\n NodeList nodes = doc.getElementsByTagName(\"host\");\n for (int i = 0; i < nodes.getLength(); i++) {\n Node node = nodes.item(i);\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element e = (Element) node;\n // Support both single host and comma-separated list of hosts.\n String v = readFirstTagValue(e, \"name\");\n String[] hosts = StringUtils.getTrimmedStrings(v);\n String str = readFirstTagValue(e, \"timeout\");\n Integer timeout = (str == null) ? null : Integer.parseInt(str);\n for (String host : hosts) {\n map.put(host, timeout);\n LOG.info(\"Adding a node \\\"\" + host + \"\\\" to the list of \" + type + \" hosts from \" + filename);\n }\n }\n }\n } catch (IOException | SAXException | ParserConfigurationException e) {\n LOG.error(\"error parsing \" + filename, e);\n throw new RuntimeException(e);\n } finally {\n fileInputStream.close();\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private byte[] transform(int cryptMode, byte[] value, byte[] salt, int iterations) throws Exception{\r\n checkPositive(iterations, \"Count of iterations has to be positive number.\");\r\n SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKeyFactoryAlgorithm);\r\n char[] password = getPassword();\r\n checkTrue(password != null && password.length > 0, \"Empty password is not supported\");\r\n PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, iterations, keyLengthBits);\r\n byte[] tmpKey = factory.generateSecret(pbeKeySpec).getEncoded();\r\n SecretKeySpec secretKeySpec = new SecretKeySpec(tmpKey, secretKeyAlgorithm);\r\n Cipher cipher = securityProvider == null ? Cipher.getInstance(cipherAlgorithm) : Cipher.getInstance(cipherAlgorithm, securityProvider);\r\n cipher.init(cryptMode, secretKeySpec);\r\n return cipher.doFinal(value);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private LogAggregationFileController createFileControllerInstance(Configuration conf, String fileController, DeterminedControllerClassName className) {\n Class clazz = conf.getClass(className.configKey, null, LogAggregationFileController.class);\n if (clazz == null) {\n throw new RuntimeException(\"No class defined for \" + fileController);\n }\n LogAggregationFileController instance = ReflectionUtils.newInstance(clazz, conf);\n if (instance == null) {\n throw new RuntimeException(\"No object created for \" + className.value);\n }\n return instance;\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public final PGConnection initJdbc() throws Exception{\r\n PGConnection conn;\r\n if (this.getDatasource() != null) {\r\n conn = PgEventHelper.toPGConnection(this.getDatasource().getConnection());\r\n } else {\r\n ClassResolver classResolver = getCamelContext().getClassResolver();\r\n classResolver.resolveMandatoryClass(PGDriver.class.getName(), PgEventComponent.class.getClassLoader());\r\n conn = (PGConnection) DriverManager.getConnection(\"jdbc:pgsql://\" + this.getHost() + \":\" + this.getPort() + \"/\" + this.getDatabase(), this.getUser(), this.getPass());\r\n }\r\n return conn;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void checkStringSarchValueNotEmpty(String searchValue, String outputNodeSearchType) throws Exception{\r\n if (searchValue.isEmpty()) {\r\n throw new XMLSignatureException(String.format(\"Wrong configuration: Value for output node search %s is empty.\", outputNodeSearchType));\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Connection createConnection() throws Exception{\r\n return connectionFactory.createConnection();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Gets an OutputStream that uses the snappy codec and wraps the supplied base output stream.\n *\n * @param bufferSize the buffer size for the codec to use (in bytes)\n * @param out the base output stream to wrap around\n * @return a OutputStream that uses the Snappy codec\n * @throws Exception if snappy is not available or an error occurs during reflection\n */\npublic static OutputStream getSnappyOutputStream(int bufferSize, OutputStream out) throws Exception {\n if (!HadoopSnappyCompressionProvider.isHadoopSnappyAvailable()) {\n throw new Exception(\"Hadoop-snappy does not seem to be available\");\n }\n Object snappyShim = HadoopSnappyCompressionProvider.getActiveSnappyShim();\n Method getSnappyOutputStream = snappyShim.getClass().getMethod(\"getSnappyOutputStream\", int.class, OutputStream.class);\n return (OutputStream) getSnappyOutputStream.invoke(snappyShim, bufferSize, out);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "@Override\npublic void onConnect(ConversationContext context) {\n InetAddress localIpAddress;\n try {\n RawSocketChannel channel = (RawSocketChannel) context.getChannel();\n String localAddress = channel.getLocalAddress().toString().substring(1).split(\":\")[0];\n localIpAddress = InetAddress.getByName(localAddress);\n PcapNetworkInterface devByAddress = Pcaps.getDevByAddress(localIpAddress);\n profinetDriverContext.setChannel(new ProfinetChannel(Collections.singletonList(devByAddress), devices));\n profinetDriverContext.getChannel().setConfiguredDevices(devices);\n // Set both the network-interface and the channel for this device\n // TODO: Find out what they are needed for ...\n for (Map.Entry entry : devices.entrySet()) {\n entry.getValue().getDeviceContext().setNetworkInterface(new ProfinetNetworkInterface(devByAddress));\n entry.getValue().getDeviceContext().setChannel(profinetDriverContext.getChannel());\n }\n } catch (PcapNativeException | UnknownHostException e) {\n throw new RuntimeException(e);\n }\n // Resolve missing information such as the remote ethernet mac address using LLDP or DCP auto-discovery.\n try {\n onDeviceDiscovery();\n } catch (PlcException | InterruptedException e) {\n throw new RuntimeException(e);\n }\n try {\n for (Map.Entry device : devices.entrySet()) {\n device.getValue().onConnect();\n }\n context.fireConnected();\n } catch (ExecutionException | InterruptedException | TimeoutException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "private void verifyBlockGroup(LocatedStripedBlock blockGroup) throws Exception {\n final LocatedBlock[] indexedBlocks = StripedBlockUtil.parseStripedBlockGroup(blockGroup, cellSize, dataBlkNum, parityBlkNum);\n int blockNumExpected = Math.min(dataBlkNum, (int) ((blockGroup.getBlockSize() - 1) / cellSize + 1)) + parityBlkNum;\n if (blockGroup.getBlockIndices().length < blockNumExpected) {\n throw new Exception(\"Block group is under-erasure-coded.\");\n }\n long maxBlockLen = 0L;\n DataChecksum checksum = null;\n for (int i = 0; i < dataBlkNum + parityBlkNum; i++) {\n LocatedBlock block = indexedBlocks[i];\n if (block == null) {\n blockReaders[i] = null;\n continue;\n }\n if (block.getBlockSize() > maxBlockLen) {\n maxBlockLen = block.getBlockSize();\n }\n BlockReader blockReader = createBlockReader(block.getBlock(), block.getLocations()[0], block.getBlockToken());\n if (checksum == null) {\n checksum = blockReader.getDataChecksum();\n } else {\n assert checksum.equals(blockReader.getDataChecksum());\n }\n blockReaders[i] = blockReader;\n }\n assert checksum != null;\n int bytesPerChecksum = checksum.getBytesPerChecksum();\n int bufferSize = stripedReadBufferSize < bytesPerChecksum ? bytesPerChecksum : stripedReadBufferSize - stripedReadBufferSize % bytesPerChecksum;\n final ByteBuffer[] buffers = new ByteBuffer[dataBlkNum + parityBlkNum];\n final ByteBuffer[] outputs = new ByteBuffer[parityBlkNum];\n for (int i = 0; i < dataBlkNum + parityBlkNum; i++) {\n buffers[i] = ByteBuffer.allocate(bufferSize);\n }\n for (int i = 0; i < parityBlkNum; i++) {\n outputs[i] = ByteBuffer.allocate(bufferSize);\n }\n long positionInBlock = 0L;\n while (positionInBlock < maxBlockLen) {\n final int toVerifyLen = (int) Math.min(bufferSize, maxBlockLen - positionInBlock);\n List> futures = new ArrayList<>(dataBlkNum + parityBlkNum);\n for (int i = 0; i < dataBlkNum + parityBlkNum; i++) {\n final int fi = i;\n futures.add(this.readService.submit(() -> {\n BlockReader blockReader = blockReaders[fi];\n ByteBuffer buffer = buffers[fi];\n buffer.clear();\n buffer.limit(toVerifyLen);\n int readLen = 0;\n if (blockReader != null) {\n int toRead = buffer.remaining();\n while (readLen < toRead) {\n int nread = blockReader.read(buffer);\n if (nread <= 0) {\n break;\n }\n readLen += nread;\n }\n }\n while (buffer.hasRemaining()) {\n buffer.put((byte) 0);\n }\n buffer.flip();\n return readLen;\n }));\n }\n for (int i = 0; i < dataBlkNum + parityBlkNum; i++) {\n futures.get(i).get(1, TimeUnit.MINUTES);\n }\n ByteBuffer[] inputs = new ByteBuffer[dataBlkNum];\n System.arraycopy(buffers, 0, inputs, 0, dataBlkNum);\n for (int i = 0; i < parityBlkNum; i++) {\n outputs[i].clear();\n outputs[i].limit(toVerifyLen);\n }\n this.encoder.encode(inputs, outputs);\n for (int i = 0; i < parityBlkNum; i++) {\n if (!buffers[dataBlkNum + i].equals(outputs[i])) {\n throw new Exception(\"EC compute result not match.\");\n }\n }\n positionInBlock += toVerifyLen;\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static void writeBinaryCheckpoints(TreeMap checkpoints, File file) throws Exception{\r\n final FileOutputStream fileOutputStream = new FileOutputStream(file, false);\r\n MessageDigest digest = Sha256Hash.newDigest();\r\n final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);\r\n digestOutputStream.on(false);\r\n final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);\r\n dataOutputStream.writeBytes(\"CHECKPOINTS 1\");\r\n dataOutputStream.writeInt(0);\r\n digestOutputStream.on(true);\r\n dataOutputStream.writeInt(checkpoints.size());\r\n ByteBuffer buffer = ByteBuffer.allocate(StoredBlock_legacy.COMPACT_SERIALIZED_SIZE);\r\n for (StoredBlock_legacy block : checkpoints.values()) {\r\n block.serializeCompact(buffer);\r\n dataOutputStream.write(buffer.array());\r\n buffer.position(0);\r\n }\r\n dataOutputStream.close();\r\n Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());\r\n System.out.println(\"Hash of checkpoints data is \" + checkpointsHash);\r\n digestOutputStream.close();\r\n fileOutputStream.close();\r\n System.out.println(\"Checkpoints written to '\" + file.getCanonicalPath() + \"'.\");\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Convert the instance into URL query string.\n *\n * @param prefix prefix of the query string\n * @return URL query string\n */\npublic String toUrlQueryString(String prefix) {\n String suffix = \"\";\n String containerSuffix = \"\";\n String containerPrefix = \"\";\n if (prefix == null) {\n // style=form, explode=true, e.g. /pet?name=cat&type=manx\n prefix = \"\";\n } else {\n // deepObject style e.g. /pet?id[name]=cat&id[type]=manx\n prefix = prefix + \"[\";\n suffix = \"]\";\n containerSuffix = \"]\";\n containerPrefix = \"[\";\n }\n StringJoiner joiner = new StringJoiner(\"&\");\n // add `name` to the URL query string\n if (getName() != null) {\n try {\n joiner.add(String.format(\"%sname%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getName()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `type` to the URL query string\n if (getType() != null) {\n joiner.add(getType().toUrlQueryString(prefix + \"type\" + suffix));\n }\n // add `id` to the URL query string\n if (getId() != null) {\n try {\n joiner.add(String.format(\"%sid%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getId()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `offset` to the URL query string\n if (getOffset() != null) {\n try {\n joiner.add(String.format(\"%soffset%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getOffset()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `default_integer` to the URL query string\n if (getDefaultInteger() != null) {\n try {\n joiner.add(String.format(\"%sdefault_integer%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDefaultInteger()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `default_real` to the URL query string\n if (getDefaultReal() != null) {\n try {\n joiner.add(String.format(\"%sdefault_real%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDefaultReal()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `deprecated` to the URL query string\n if (getDeprecated() != null) {\n try {\n joiner.add(String.format(\"%sdeprecated%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getDeprecated()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `required` to the URL query string\n if (getRequired() != null) {\n try {\n joiner.add(String.format(\"%srequired%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getRequired()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `key` to the URL query string\n if (getKey() != null) {\n try {\n joiner.add(String.format(\"%skey%s=%s\", prefix, suffix, URLEncoder.encode(String.valueOf(getKey()), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n // add `attributes` to the URL query string\n if (getAttributes() != null) {\n for (int i = 0; i < getAttributes().size(); i++) {\n if (getAttributes().get(i) != null) {\n joiner.add(getAttributes().get(i).toUrlQueryString(String.format(\"%sattributes%s%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix))));\n }\n }\n }\n // add `documentation` to the URL query string\n if (getDocumentation() != null) {\n for (int i = 0; i < getDocumentation().size(); i++) {\n try {\n joiner.add(String.format(\"%sdocumentation%s%s=%s\", prefix, suffix, \"\".equals(suffix) ? \"\" : String.format(\"%s%d%s\", containerPrefix, i, containerSuffix), URLEncoder.encode(String.valueOf(getDocumentation().get(i)), \"UTF-8\").replaceAll(\"\\\\+\", \"%20\")));\n } catch (UnsupportedEncodingException e) {\n // Should never happen, UTF-8 is always supported\n throw new RuntimeException(e);\n }\n }\n }\n return joiner.toString();\n}", "smellKey": "S112", "smellId": null, "repo": "apache_plc4x", "language": "java"} {"function": "public static Storage create(CamelContext context, GoogleCloudStorageConfiguration configuration) throws Exception{\r\n if (!Strings.isNullOrEmpty(configuration.getServiceAccountKey())) {\r\n InputStream resolveMandatoryResourceAsInputStream = ResourceHelper.resolveMandatoryResourceAsInputStream(context, configuration.getServiceAccountKey());\r\n return StorageOptions.newBuilder().setCredentials(ServiceAccountCredentials.fromStream(resolveMandatoryResourceAsInputStream)).build().getService();\r\n } else {\r\n return StorageOptions.getDefaultInstance().getService();\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void reconnect() throws Exception{\r\n close();\r\n getConnection();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@RolesAllowed({ \"readArchiveFileRole\" })\npublic Collection getAllWithMissingCalendarEntries(int type) throws Exception {\n if (type != ArchiveFileReviewsBean.EVENTTYPE_EVENT && type != ArchiveFileReviewsBean.EVENTTYPE_RESPITE && type != ArchiveFileReviewsBean.EVENTTYPE_FOLLOWUP)\n throw new Exception(\"Ung\u00fcltige Typangabe f\u00fcr Kalendereintr\u00e4ge!\");\n JDBCUtils utils = new JDBCUtils();\n ArrayList list = new ArrayList<>();\n ArrayList allowedCases = null;\n try {\n allowedCases = SecurityUtils.getAllowedCasesForUser(context.getCallerPrincipal().getName(), this.securityFacade);\n } catch (Exception ex) {\n log.error(\"Unable to determine allowed cases for user \" + context.getCallerPrincipal().getName(), ex);\n throw new EJBException(\"Akten f\u00fcr Nutzer \" + context.getCallerPrincipal().getName() + \"' konnten nicht ermittelt werden.\", ex);\n }\n try (Connection con = utils.getConnection();\n PreparedStatement st = con.prepareStatement(\"select id from cases where archived=0 and id not in (select archiveFileKey from case_events where done=0 and eventType=?) order by fileNumber asc\")) {\n st.setInt(1, type);\n ResultSet rs = st.executeQuery();\n while (rs.next()) {\n String id = rs.getString(1);\n if (allowedCases.contains(id)) {\n ArchiveFileBean dto = this.archiveFileFacade.find(id);\n list.add(dto);\n }\n }\n try {\n rs.close();\n } catch (Throwable t) {\n log.error(\"unable to close resultset: \" + t.getMessage());\n }\n } catch (SQLException sqle) {\n log.error(\"Error finding archive files\", sqle);\n throw new EJBException(\"Wiedervorlagensuche konnte nicht ausgef\u00fchrt werden.\", sqle);\n }\n return list;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private Status updateStatus(StatusUpdate status) throws Exception{\r\n Status response = endpoint.getProperties().getTwitter().v1().tweets().updateStatus(status);\r\n LOG.debug(\"Updated status: {}\", status);\r\n LOG.debug(\"Status id: {}\", response.getId());\r\n return response;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addOrFail(ReliableTopicMessage message) throws Exception{\r\n long sequenceId = ringbuffer.addAsync(message, OverflowPolicy.FAIL).toCompletableFuture().get();\r\n if (sequenceId == -1) {\r\n throw new TopicOverloadException(\"Failed to publish message: \" + message + \" on topic:\" + getName());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Filter API resource collections.\n *\n * @param apiResourceCollectionsMap API resource collection map.\n * @param filter Filter string.\n * @return Map of API resource collection.\n * @throws APIResourceCollectionMgtClientException Error when validate filters.\n */\npublic static Map filterAPIResourceCollections(Map apiResourceCollectionsMap, String filter) throws APIResourceCollectionMgtClientException, APIResourceCollectionMgtServerException {\n try {\n List expressionNodes = getExpressionNodes(filter);\n return apiResourceCollectionsMap.entrySet().stream().filter(entry -> {\n try {\n return matchesFilter(entry.getValue(), expressionNodes);\n } catch (APIResourceCollectionMgtClientException e) {\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n } catch (RuntimeException e) {\n if (e.getCause() instanceof APIResourceCollectionMgtClientException) {\n throw (APIResourceCollectionMgtClientException) e.getCause();\n } else {\n throw handleServerException(APIResourceCollectionManagementConstants.ErrorMessages.ERROR_CODE_WHILE_FILTERING_API_RESOURCE_COLLECTIONS, e);\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public void connect(HttpConsumer consumer) throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void main(String[] args) throws Exception {\n if (args.length < 4) {\n System.out.println(\"Arguments: \" + \" []+\");\n System.exit(1);\n }\n File workDir = new File(args[0]);\n if (!workDir.exists()) {\n throw new RuntimeException(\"Specified work directory does not exists: \" + workDir.getAbsolutePath());\n }\n Properties conf = createConf();\n File file = new File(args[1]);\n if (!file.exists()) {\n throw new RuntimeException(\"Specified configuration does not exists: \" + file.getAbsolutePath());\n }\n Properties userConf = new Properties();\n InputStreamReader r = null;\n try {\n r = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);\n userConf.load(r);\n } finally {\n if (r != null) {\n r.close();\n }\n }\n for (Map.Entry entry : userConf.entrySet()) {\n conf.put(entry.getKey(), entry.getValue());\n }\n final MiniKdc miniKdc = new MiniKdc(conf, workDir);\n miniKdc.start();\n File krb5conf = new File(workDir, \"krb5.conf\");\n if (miniKdc.getKrb5conf().renameTo(krb5conf)) {\n File keytabFile = new File(args[2]).getAbsoluteFile();\n String[] principals = new String[args.length - 3];\n System.arraycopy(args, 3, principals, 0, args.length - 3);\n miniKdc.createPrincipal(keytabFile, principals);\n System.out.println();\n System.out.println(\"Standalone MiniKdc Running\");\n System.out.println(\"---------------------------------------------------\");\n System.out.println(\" Realm : \" + miniKdc.getRealm());\n System.out.println(\" Running at : \" + miniKdc.getHost() + \":\" + miniKdc.getHost());\n System.out.println(\" krb5conf : \" + krb5conf);\n System.out.println();\n System.out.println(\" created keytab : \" + keytabFile);\n System.out.println(\" with principals : \" + Arrays.asList(principals));\n System.out.println();\n System.out.println(\" Do or kill to stop it\");\n System.out.println(\"---------------------------------------------------\");\n System.out.println();\n Runtime.getRuntime().addShutdownHook(new Thread() {\n\n @Override\n public void run() {\n miniKdc.stop();\n }\n });\n } else {\n throw new RuntimeException(\"Cannot rename KDC's krb5conf to \" + krb5conf.getAbsolutePath());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "@Override\npublic LockResponse execute(MultiDataSourceJdbcResource jdbcResource) throws MetaException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Acquiring lock for materialization rebuild with {} for {}\", JavaUtils.txnIdToString(txnId), TableName.getDbTable(dbName, tableName));\n }\n /**\n * MUTEX_KEY.MaterializationRebuild lock ensures that there is only 1 entry in\n * Initiated/Working state for any resource. This ensures we do not run concurrent\n * rebuild operations on any materialization.\n */\n try (TxnStore.MutexAPI.LockHandle ignored = mutexAPI.acquireLock(TxnStore.MUTEX_KEY.MaterializationRebuild.name())) {\n MapSqlParameterSource params = new MapSqlParameterSource().addValue(\"dbName\", dbName).addValue(\"tableName\", tableName);\n String selectQ = \"SELECT \\\"MRL_TXN_ID\\\" FROM \\\"MATERIALIZATION_REBUILD_LOCKS\\\" WHERE\" + \" \\\"MRL_DB_NAME\\\" = :dbName AND \\\"MRL_TBL_NAME\\\" = :tableName\";\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Going to execute query {}\", selectQ);\n }\n boolean found = Boolean.TRUE.equals(jdbcResource.getJdbcTemplate().query(selectQ, params, ResultSet::next));\n if (found) {\n LOG.info(\"Ignoring request to rebuild {}/{} since it is already being rebuilt\", dbName, tableName);\n return new LockResponse(txnId, LockState.NOT_ACQUIRED);\n }\n String insertQ = \"INSERT INTO \\\"MATERIALIZATION_REBUILD_LOCKS\\\" \" + \"(\\\"MRL_TXN_ID\\\", \\\"MRL_DB_NAME\\\", \\\"MRL_TBL_NAME\\\", \\\"MRL_LAST_HEARTBEAT\\\") \" + \"VALUES (:txnId, :dbName, :tableName, \" + Instant.now().toEpochMilli() + \")\";\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Going to execute update {}\", insertQ);\n }\n jdbcResource.getJdbcTemplate().update(insertQ, params.addValue(\"txnId\", txnId));\n return new LockResponse(txnId, LockState.ACQUIRED);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private BufferedReader initializeStreamLineMode() throws Exception{\r\n IOHelper.close(inputStreamToClose);\r\n if (urlConnectionToClose != null) {\r\n closeURLConnection(urlConnectionToClose);\r\n }\r\n if (\"in\".equals(uri)) {\r\n inputStream = System.in;\r\n inputStreamToClose = null;\r\n } else if (\"file\".equals(uri)) {\r\n inputStream = resolveStreamFromFile();\r\n inputStreamToClose = inputStream;\r\n } else if (\"http\".equals(uri)) {\r\n inputStream = resolveStreamFromUrl();\r\n inputStreamToClose = inputStream;\r\n }\r\n if (inputStream != null) {\r\n if (\"http\".equals(uri)) {\r\n return IOHelper.buffered(new InputStreamReader(inputStream));\r\n } else {\r\n Charset charset = endpoint.getCharset();\r\n return IOHelper.buffered(new InputStreamReader(inputStream, charset));\r\n }\r\n } else {\r\n return null;\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Object afterInvoke(Method method, Exchange exchange, boolean isFuture) throws Exception{\r\n Exception cause = exchange.getException();\r\n if (cause != null) {\r\n Throwable found = findSuitableException(cause, method);\r\n if (found != null) {\r\n if (found instanceof Exception) {\r\n throw (Exception) found;\r\n } else {\r\n throw new CamelExchangeException(\"Error processing exchange\", exchange, cause);\r\n }\r\n }\r\n if (cause instanceof RuntimeCamelException) {\r\n if (cause.getCause() instanceof RuntimeException) {\r\n throw (RuntimeException) cause.getCause();\r\n }\r\n throw cause;\r\n }\r\n throw cause;\r\n }\r\n Class to = isFuture ? getGenericType(exchange.getContext(), method.getGenericReturnType()) : method.getReturnType();\r\n if (to == Void.TYPE) {\r\n return null;\r\n }\r\n return getBody(exchange, to);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Handle decimal subtraction when the values have different scales.\n */\nprivate static boolean fastSubtractDifferentScale(long leftFast0, long leftFast1, long leftFast2, int leftIntegerDigitCount, int leftScale, long rightFast0, long rightFast1, long rightFast2, int rightIntegerDigitCount, int rightScale, FastHiveDecimal fastResult) {\n int diffScale;\n int resultScale;\n long result0 = 0;\n long result1 = 0;\n long result2 = 0;\n long result3 = 0;\n long result4 = 0;\n // Since subtraction is not commutative, we can must subtract in the order passed in.\n if (leftScale > rightScale) {\n // Since left has a longer digit tail and it doesn't move; we will shift the right digits\n // as we do our addition into the result.\n diffScale = leftScale - rightScale;\n resultScale = leftScale;\n if (diffScale < LONGWORD_DECIMAL_DIGITS) {\n final long divideFactor = powerOfTenTable[LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale];\n final long r0 = leftFast0 - (rightFast0 % divideFactor) * multiplyFactor;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = leftFast1 - rightFast0 / divideFactor - (rightFast1 % divideFactor) * multiplyFactor - 1;\n } else {\n result0 = r0;\n r1 = leftFast1 - rightFast0 / divideFactor - (rightFast1 % divideFactor) * multiplyFactor;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast2 - rightFast1 / divideFactor - (rightFast2 % divideFactor) * multiplyFactor - 1;\n } else {\n result1 = r1;\n r2 = leftFast2 - rightFast1 / divideFactor - (rightFast2 % divideFactor) * multiplyFactor;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = -(rightFast2 / divideFactor) - 1;\n } else {\n result2 = r2;\n r3 = -(rightFast2 / divideFactor);\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -1;\n } else {\n result3 = r3;\n r4 = 0;\n }\n if (r4 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else if (diffScale == LONGWORD_DECIMAL_DIGITS) {\n result0 = leftFast0;\n final long r1 = leftFast1 - rightFast0;\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast2 - rightFast1 - 1;\n } else {\n result1 = r1;\n r2 = leftFast2 - rightFast1;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = -rightFast2 - 1;\n } else {\n result2 = r2;\n r3 = -rightFast2;\n }\n if (r3 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else if (diffScale < TWO_X_LONGWORD_DECIMAL_DIGITS) {\n final long divideFactor = powerOfTenTable[TWO_X_LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale - LONGWORD_DECIMAL_DIGITS];\n result0 = leftFast0;\n final long r1 = leftFast1 - (rightFast0 % divideFactor) * multiplyFactor;\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast2 - rightFast0 / divideFactor - (rightFast1 % divideFactor) * multiplyFactor - 1;\n } else {\n result1 = r1;\n r2 = leftFast2 - rightFast0 / divideFactor - (rightFast1 % divideFactor) * multiplyFactor;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = -rightFast1 / divideFactor - (rightFast2 % divideFactor) * multiplyFactor - 1;\n } else {\n result2 = r2;\n r3 = -rightFast1 / divideFactor - (rightFast2 % divideFactor) * multiplyFactor;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -rightFast2 / divideFactor - 1;\n } else {\n result3 = r3;\n r4 = -rightFast2 / divideFactor;\n }\n long r5;\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n r5 = -1;\n } else {\n result4 = r4;\n r5 = 0;\n }\n if (r5 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else if (diffScale == TWO_X_LONGWORD_DECIMAL_DIGITS) {\n result0 = leftFast0;\n result1 = leftFast1;\n final long r2 = leftFast2 - rightFast0;\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = -rightFast1 - 1;\n } else {\n result2 = r2;\n r3 = -rightFast1;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -rightFast2 - 1;\n } else {\n result3 = r3;\n r4 = -rightFast2;\n }\n long r5;\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n r5 = -1;\n } else {\n result4 = r4;\n r5 = 0;\n }\n if (r5 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else {\n final long divideFactor = powerOfTenTable[THREE_X_LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale - TWO_X_LONGWORD_DECIMAL_DIGITS];\n result0 = leftFast0;\n result1 = leftFast1;\n final long r2 = leftFast2 - (rightFast0 % divideFactor) * multiplyFactor;\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = -(rightFast0 / divideFactor) - (rightFast1 % divideFactor) * multiplyFactor - 1;\n } else {\n result2 = r2;\n r3 = -(rightFast0 / divideFactor) - (rightFast1 % divideFactor) * multiplyFactor;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -(rightFast1 / divideFactor) - (rightFast2 % divideFactor) * multiplyFactor - 1;\n } else {\n result3 = r3;\n r4 = -(rightFast1 / divideFactor) - (rightFast2 % divideFactor) * multiplyFactor;\n }\n long r5;\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n r5 = -(rightFast2 / divideFactor) - 1;\n } else {\n result4 = r4;\n r5 = -(rightFast2 / divideFactor);\n }\n if (r5 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n }\n } else {\n // Since right has a longer digit tail and it doesn't move; we will shift the left digits\n // as we do our addition into the result.\n diffScale = rightScale - leftScale;\n resultScale = rightScale;\n if (diffScale < LONGWORD_DECIMAL_DIGITS) {\n final long divideFactor = powerOfTenTable[LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale];\n final long r0 = (leftFast0 % divideFactor) * multiplyFactor - rightFast0;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor - rightFast1 - 1;\n } else {\n result0 = r0;\n r1 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor - rightFast1;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor - rightFast2 - 1;\n } else {\n result1 = r1;\n r2 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor - rightFast2;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = leftFast2 / divideFactor - 1;\n } else {\n result2 = r2;\n r3 = leftFast2 / divideFactor;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -1;\n } else {\n result3 = r3;\n r4 = 0;\n }\n if (r4 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else if (diffScale == LONGWORD_DECIMAL_DIGITS) {\n final long r0 = -rightFast0;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = leftFast0 - rightFast1 - 1;\n } else {\n result0 = r0;\n r1 = leftFast0 - rightFast1;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast1 - rightFast2 - 1;\n } else {\n result1 = r1;\n r2 = leftFast1 - rightFast2;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = leftFast2 - 1;\n } else {\n result2 = r2;\n r3 = leftFast2;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = -1;\n } else {\n result3 = r3;\n r4 = 0;\n }\n if (r4 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else if (diffScale < TWO_X_LONGWORD_DECIMAL_DIGITS) {\n final long divideFactor = powerOfTenTable[TWO_X_LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale - LONGWORD_DECIMAL_DIGITS];\n final long r0 = -rightFast0;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = (leftFast0 % divideFactor) * multiplyFactor - rightFast1 - 1;\n } else {\n result0 = r0;\n r1 = (leftFast0 % divideFactor) * multiplyFactor - rightFast1;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor - rightFast2 - 1;\n } else {\n result1 = r1;\n r2 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor - rightFast2;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor - 1;\n } else {\n result2 = r2;\n r3 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = leftFast2 / divideFactor - 1;\n } else {\n result3 = r3;\n r4 = leftFast2 / divideFactor;\n }\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n } else {\n result4 = r4;\n }\n } else if (diffScale == TWO_X_LONGWORD_DECIMAL_DIGITS) {\n final long r0 = -rightFast0;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = -rightFast1 - 1;\n } else {\n result0 = r0;\n r1 = -rightFast1;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = leftFast0 - rightFast2 - 1;\n } else {\n result1 = r1;\n r2 = leftFast0 - rightFast2;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = leftFast1 - 1;\n } else {\n result2 = r2;\n r3 = leftFast1;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = leftFast2 - 1;\n } else {\n result3 = r3;\n r4 = leftFast2;\n }\n long r5;\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n r5 = -1;\n } else {\n result4 = r4;\n r5 = 0;\n }\n if (r5 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n } else {\n final long divideFactor = powerOfTenTable[THREE_X_LONGWORD_DECIMAL_DIGITS - diffScale];\n final long multiplyFactor = powerOfTenTable[diffScale - TWO_X_LONGWORD_DECIMAL_DIGITS];\n final long r0 = -rightFast0;\n long r1;\n if (r0 < 0) {\n result0 = r0 + MULTIPLER_LONGWORD_DECIMAL;\n r1 = -rightFast1 - 1;\n } else {\n result0 = r0;\n r1 = -rightFast1;\n }\n long r2;\n if (r1 < 0) {\n result1 = r1 + MULTIPLER_LONGWORD_DECIMAL;\n r2 = (leftFast0 % divideFactor) * multiplyFactor - rightFast2 - 1;\n } else {\n result1 = r1;\n r2 = (leftFast0 % divideFactor) * multiplyFactor - rightFast2;\n }\n long r3;\n if (r2 < 0) {\n result2 = r2 + MULTIPLER_LONGWORD_DECIMAL;\n r3 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor - 1;\n } else {\n result2 = r2;\n r3 = leftFast0 / divideFactor + (leftFast1 % divideFactor) * multiplyFactor;\n }\n long r4;\n if (r3 < 0) {\n result3 = r3 + MULTIPLER_LONGWORD_DECIMAL;\n r4 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor - 1;\n } else {\n result3 = r3;\n r4 = leftFast1 / divideFactor + (leftFast2 % divideFactor) * multiplyFactor;\n }\n long r5;\n if (r4 < 0) {\n result4 = r4 + MULTIPLER_LONGWORD_DECIMAL;\n r5 = leftFast2 / divideFactor - 1;\n } else {\n result4 = r4;\n r5 = leftFast2 / divideFactor;\n }\n if (r5 != 0) {\n throw new RuntimeException(\"Unexpected underflow\");\n }\n }\n }\n return doFinishAddSubtractDifferentScale(result0, result1, result2, result3, result4, resultScale, fastResult);\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected ServerConnector getSslSocketConnector(Server server) throws Exception{\r\n ServerConnector sslSocketConnector = null;\r\n SSLContextParameters sslParams = this.sslContextParameters;\r\n if (sslParams == null) {\r\n sslParams = retrieveGlobalSslContextParameters();\r\n }\r\n SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\r\n sslContextFactory.setEndpointIdentificationAlgorithm(null);\r\n if (sslParams != null) {\r\n sslContextFactory.setSslContext(sslParams.createSSLContext(getCamelContext()));\r\n } else {\r\n sslContextFactory.setKeyStorePassword(sslKeyPassword);\r\n sslContextFactory.setKeyManagerPassword(sslPassword);\r\n if (sslKeystore != null) {\r\n sslContextFactory.setKeyStorePath(sslKeystore);\r\n }\r\n }\r\n sslSocketConnector = new ServerConnector(server, sslContextFactory);\r\n return sslSocketConnector;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void copyOnce(List latencies) throws Exception{\r\n long start = System.currentTimeMillis();\r\n Copy copy = transferManager.copy(b -> b.copyObjectRequest(c -> c.sourceBucket(bucket).sourceKey(key).destinationBucket(bucket).destinationKey(key + COPY_SUFFIX)));\r\n copy.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS);\r\n long end = System.currentTimeMillis();\r\n latencies.add((end - start) / 1000.0);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Certificate getCertificate(String alias) throws Exception{\r\n Certificate cert = null;\r\n if (alias != null && keystore != null) {\r\n cert = keystore.getCertificate(alias);\r\n }\r\n if (cert == null) {\r\n cert = certificate;\r\n }\r\n return cert;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Path to the common orphaned_tests.txt file.\n */\nprivate static Path orphanedTestsFilePath() {\n try {\n return Paths.get(OrphanedTestCollection.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent().resolve(\"orphaned_tests.txt\");\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public void teardown() throws Exception{\r\n if (bkStartupThread != null) {\r\n bkStartupThread.interrupt();\r\n bkStartupThread.join();\r\n }\r\n for (File dir : tmpDirs) {\r\n FileUtils.forceDeleteOnExit(dir);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Field getField(org.apache.avro.Schema fieldSchema, String name, boolean nullable) {\n final Field.Mode fieldMode = nullable ? Field.Mode.NULLABLE : Field.Mode.REQUIRED;\n StandardSQLTypeName standardSQLTypeName;\n switch(fieldSchema.getType()) {\n case INT:\n case LONG:\n LogicalType logicalType = fieldSchema.getLogicalType();\n if (logicalType == null) {\n standardSQLTypeName = StandardSQLTypeName.INT64;\n } else if (logicalType.equals(LogicalTypes.date())) {\n standardSQLTypeName = StandardSQLTypeName.DATE;\n } else if (logicalType.equals(LogicalTypes.timeMillis()) || logicalType.equals(LogicalTypes.timeMicros())) {\n standardSQLTypeName = StandardSQLTypeName.TIME;\n } else if (logicalType.equals(LogicalTypes.timestampMillis()) || logicalType.equals(LogicalTypes.timestampMicros())) {\n standardSQLTypeName = StandardSQLTypeName.TIMESTAMP;\n // Due to older avro support, we need to use strings for local timestamp logical types\n } else if (logicalType.getName().equals(\"local-timestamp-millis\") || logicalType.getName().equals(\"local-timestamp-micros\")) {\n standardSQLTypeName = StandardSQLTypeName.INT64;\n } else {\n throw new IllegalArgumentException(\"Unexpected logical type in schema: \" + logicalType);\n }\n break;\n case ENUM:\n case STRING:\n standardSQLTypeName = StandardSQLTypeName.STRING;\n break;\n case BOOLEAN:\n standardSQLTypeName = StandardSQLTypeName.BOOL;\n break;\n case DOUBLE:\n case FLOAT:\n standardSQLTypeName = StandardSQLTypeName.FLOAT64;\n break;\n case BYTES:\n case FIXED:\n LogicalType bytesLogicalType = fieldSchema.getLogicalType();\n if (bytesLogicalType == null) {\n standardSQLTypeName = StandardSQLTypeName.BYTES;\n } else if (bytesLogicalType instanceof LogicalTypes.Decimal) {\n standardSQLTypeName = StandardSQLTypeName.NUMERIC;\n } else {\n throw new IllegalArgumentException(\"Unexpected logical type in schema: \" + bytesLogicalType);\n }\n break;\n case RECORD:\n return Field.newBuilder(name, StandardSQLTypeName.STRUCT, FieldList.of(getFields(fieldSchema))).setMode(fieldMode).build();\n case ARRAY:\n Field arrayField = getField(fieldSchema.getElementType(), \"array\", true);\n return Field.newBuilder(name, arrayField.getType(), arrayField.getSubFields()).setMode(Field.Mode.REPEATED).build();\n case MAP:\n Field keyField = Field.newBuilder(\"key\", StandardSQLTypeName.STRING).setMode(Field.Mode.REQUIRED).build();\n Field valueField = getField(fieldSchema.getValueType(), \"value\", false);\n Field keyValueField = Field.newBuilder(\"key_value\", StandardSQLTypeName.STRUCT, keyField, valueField).setMode(Field.Mode.REPEATED).build();\n return Field.newBuilder(name, StandardSQLTypeName.STRUCT, keyValueField).setMode(Field.Mode.NULLABLE).build();\n case UNION:\n List subTypes = fieldSchema.getTypes();\n validateUnion(subTypes);\n org.apache.avro.Schema fieldSchemaFromUnion = subTypes.get(0).getType() == org.apache.avro.Schema.Type.NULL ? subTypes.get(1) : subTypes.get(0);\n nullable = true;\n return getField(fieldSchemaFromUnion, name, nullable);\n default:\n throw new RuntimeException(\"Unexpected field type: \" + fieldSchema.getType());\n }\n return Field.newBuilder(name, standardSQLTypeName).setMode(fieldMode).build();\n}", "smellKey": "S112", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": " boolean flush() throws Exception{\r\n return true;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "static Supplier getStructuredJsonFactory(BaseAwsJsonProtocolFactory factory) {\n return () -> {\n try {\n Method method = BaseAwsJsonProtocolFactory.class.getDeclaredMethod(\"getSdkFactory\");\n method.setAccessible(true);\n return (StructuredJsonFactory) method.invoke(factory);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n };\n}", "smellKey": "S112", "smellId": null, "repo": "aws_aws-sdk-java-v2", "language": "java"} {"function": "private boolean checkValuePresentOnCodeTable(String value, String codeTableName) throws Exception {\n loadCodeTables();\n boolean present = false;\n List codeTableList = codeTables.getCodeTableList();\n List codeTableNames = new ArrayList();\n CodeTableResource relevantTable = new CodeTableResource();\n for (CodeTableResource codeTable : codeTableList) {\n codeTableNames.add(codeTable.getCodeTableName());\n }\n if (!codeTableNames.contains(codeTableName)) {\n throw new Exception(\"Exception finding Report of Fire code table: \" + codeTableName);\n } else {\n for (CodeTableResource codeTable : codeTableList) {\n if (codeTable.getCodeTableName().equalsIgnoreCase(codeTableName)) {\n relevantTable = codeTable;\n break;\n }\n }\n }\n if (relevantTable.getCodes() != null) {\n for (Code code : relevantTable.getCodes()) {\n if (code.getCode().equalsIgnoreCase(value)) {\n present = true;\n break;\n }\n }\n }\n return present;\n}", "smellKey": "S112", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "public void index(Exchange exchange) throws Exception{\r\n LOG.debug(\"Indexing {}\", exchange);\r\n openIndexWriter();\r\n Map headers = exchange.getIn().getHeaders();\r\n add(\"exchangeId\", exchange.getExchangeId(), true);\r\n for (Entry entry : headers.entrySet()) {\r\n String field = entry.getKey();\r\n String value = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, entry.getValue());\r\n add(field, value, true);\r\n }\r\n add(\"contents\", exchange.getIn().getMandatoryBody(String.class), true);\r\n closeIndexWriter();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected synchronized void doClose() throws Exception{\r\n if (!isClosed.get()) {\r\n subscribers.forEach(BonsaiStorageSubscriber::onCloseStorage);\r\n composedWorldStateStorage.close();\r\n trieLogStorage.close();\r\n isClosed.set(true);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void prepareDirs() throws Exception{\r\n File hiveRootDir = new File(HIVE_ROOT);\r\n if (!hiveRootDir.exists()) {\r\n throw new RuntimeException(\"Hive Root Directory \" + hiveRootDir.getCanonicalPath() + \" does not exist\");\r\n }\r\n File logDir = new File(logDirectory);\r\n if (!logDir.exists()) {\r\n FileUtils.forceMkdir(logDir);\r\n }\r\n File resultsDir = new File(resultsDirectory);\r\n if (!resultsDir.exists()) {\r\n FileUtils.forceMkdir(resultsDir);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void attachment(String title, String content, String partContent) throws Exception{\r\n MimeMessage msg = getMimeMessage();\r\n attachContent(title, content, partContent, msg);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void nextEvent() throws Exception {\n ArrayList persons = new ArrayList<>();\n ArrayList clients = (ArrayList) data.get(\"clients.addressbeans\");\n ArrayList allParties = (ArrayList) data.get(\"clients.allparties\");\n if (allParties == null)\n allParties = new ArrayList<>();\n DefaultTableModel dm = (DefaultTableModel) this.tblClients.getModel();\n for (int i = 0; i < dm.getRowCount(); i++) {\n Boolean enabled = (Boolean) dm.getValueAt(i, 0);\n if (enabled) {\n // user chose to submit this client\n AddressBean ab = clients.get(i);\n PartyTypeBean ptb = com.jdimension.jlawyer.client.drebis.DrebisUtils.getType(ab, allParties);\n if (ptb != null) {\n // will only store ONE type of party\n ServerSettings.getInstance().setSetting(\"drebis.\" + this.getClass().getName() + \".selectedtype\", ptb.getId());\n }\n // columns: 0 submit, 1 name, 2 firstname, 3 company, 4 street, 5 zip, 6 city, 7 countrycode, 8 phone, 9 fax, 10 email\n DrebisPerson p = new DrebisPerson();\n if (dm.getValueAt(i, 6) != null)\n p.setCity(dm.getValueAt(i, 6).toString());\n if (dm.getValueAt(i, 3) != null)\n p.setCompany(dm.getValueAt(i, 3).toString());\n if (dm.getValueAt(i, 7) != null)\n p.setCountryCode(dm.getValueAt(i, 7).toString());\n if (dm.getValueAt(i, 10) != null)\n p.setEmail(dm.getValueAt(i, 10).toString());\n if (dm.getValueAt(i, 9) != null)\n p.setFax(dm.getValueAt(i, 9).toString());\n if (dm.getValueAt(i, 2) != null)\n p.setFirstName(dm.getValueAt(i, 2).toString());\n if (dm.getValueAt(i, 1) != null)\n p.setName(dm.getValueAt(i, 1).toString());\n if (dm.getValueAt(i, 8) != null)\n p.setPhone(dm.getValueAt(i, 8).toString());\n if (dm.getValueAt(i, 4) != null)\n p.setStreet(dm.getValueAt(i, 4).toString());\n if (dm.getValueAt(i, 5) != null)\n p.setZipCode(dm.getValueAt(i, 5).toString());\n p.validate();\n persons.add(p);\n }\n }\n if (persons.isEmpty())\n throw new Exception(\"Es muss mindestens ein zu \u00fcbertragender Mandant angegeben werden\");\n if (this.cmbInsurances.getSelectedItem() == null) {\n throw new Exception(\"Es muss ein von Drebis unterst\u00fctztes Versicherungsunternehmen gew\u00e4hlt werden\");\n }\n // default \"\" insurance (empty insurance) has been selected\n if (this.cmbInsurances.getSelectedItem() instanceof String)\n throw new Exception(\"Es muss ein von Drebis unterst\u00fctztes Versicherungsunternehmen gew\u00e4hlt werden\");\n if (this.cmbInsurance.getSelectedItem() == null) {\n throw new Exception(\"Es muss ein Versicherungsschein angegeben werden\");\n }\n if (\"\".equals(this.cmbInsurance.getSelectedItem().toString().trim())) {\n throw new Exception(\"Es muss ein Versicherungsschein angegeben werden\");\n }\n String regex = ((InsuranceInfo) this.cmbInsurances.getSelectedItem()).getPolicyNumberRegEx();\n if (regex != null && !(\"\".equals(regex))) {\n if (!this.cmbInsurance.getSelectedItem().toString().matches(regex)) {\n throw new Exception(\"Versicherungsschein inkorrekt - bitte beachten Sie die Hinweise hinter dem Eingabefeld\" + System.getProperty(\"line.separator\") + ((InsuranceInfo) this.cmbInsurances.getSelectedItem()).getPolicyNumberRegEx());\n }\n }\n if (this.txtFileNumber.getText() == null || \"\".equalsIgnoreCase(this.txtFileNumber.getText().trim()))\n throw new Exception(\"Aktenzeichen darf nicht leer sein!\");\n if (this.txtName.getText() == null || \"\".equalsIgnoreCase(this.txtName.getText().trim()))\n throw new Exception(\"Kurzrubrum darf nicht leer sein!\");\n this.data.put(\"clients.drebispersons\", persons);\n this.data.put(\"clients.archivefilename\", this.txtName.getText());\n this.data.put(\"clients.archivefilenumber\", this.txtFileNumber.getText());\n this.data.put(\"clients.insurance\", this.cmbInsurances.getSelectedItem());\n this.data.put(\"clients.insurancepolicy\", this.cmbInsurance.getSelectedItem().toString());\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void deleteObjects(MinioClient minioClient, Exchange exchange) throws Exception{\r\n if (getConfiguration().isPojoRequest()) {\r\n RemoveObjectsArgs.Builder payload = exchange.getIn().getMandatoryBody(RemoveObjectsArgs.Builder.class);\r\n if (isNotEmpty(payload)) {\r\n minioClient.removeObjects(payload.build()).iterator().hasNext();\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(true);\r\n }\r\n } else {\r\n throw new IllegalArgumentException(\"Cannot delete multiple objects without a POJO request\");\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int executeSaveCommand(CommandLine cliParser, String title, Options opts) throws Exception {\n int exitCode = -1;\n if (hasAnyOtherCLIOptions(cliParser, opts, SAVE_CMD, APP_TYPE_CMD, UPDATE_LIFETIME, CHANGE_APPLICATION_QUEUE)) {\n printUsage(title, opts);\n return exitCode;\n }\n String appType = getSingleAppTypeFromCLI(cliParser);\n Long lifetime = null;\n if (cliParser.hasOption(UPDATE_LIFETIME)) {\n lifetime = Long.parseLong(cliParser.getOptionValue(UPDATE_LIFETIME));\n }\n String queue = null;\n if (cliParser.hasOption(CHANGE_APPLICATION_QUEUE)) {\n queue = cliParser.getOptionValue(CHANGE_APPLICATION_QUEUE);\n }\n String[] nameAndFile = cliParser.getOptionValues(SAVE_CMD);\n return AppAdminClient.createAppAdminClient(appType, getConf()).actionSave(nameAndFile[1], nameAndFile[0], lifetime, queue);\n}", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static List getAllUrls(String zookeeperBasedHS2Url) throws Exception{\r\n JdbcConnectionParams params = Utils.parseURL(zookeeperBasedHS2Url, new Properties());\r\n if (params.getZooKeeperEnsemble() == null || ZooKeeperHiveClientHelper.isZkHADynamicDiscoveryMode(params.getSessionVars())) {\r\n return Collections.singletonList(params);\r\n }\r\n return ZooKeeperHiveClientHelper.getDirectParamsList(params);\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void writeConfigJson(JSONObject configs) throws Exception{\r\n try (FSDataOutputStream fsdos = fs.create(new Path(tmpDir, \"config.json\"));\r\n OutputStreamWriter w = new OutputStreamWriter(fsdos, Charset.defaultCharset())) {\r\n configs.write(w);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * {@inheritDoc}\n */\n@Override\nprotected Void run(CdcDeleteLostSegmentLinksCommandArg arg) throws IgniteException {\n FileWriteAheadLogManager wal = (FileWriteAheadLogManager) ignite.context().cache().context().wal(true);\n File walCdcDir = wal.walCdcDirectory();\n if (walCdcDir == null)\n throw new IgniteException(\"CDC is not configured.\");\n CdcFileLockHolder lock = new CdcFileLockHolder(walCdcDir.getAbsolutePath(), \"Delete lost segments job\", log);\n try {\n lock.tryLock(1);\n try (Stream cdcFiles = Files.list(walCdcDir.toPath())) {\n Set delete = new HashSet<>();\n AtomicLong lastSgmnt = new AtomicLong(-1);\n cdcFiles.filter(p -> WAL_SEGMENT_FILE_FILTER.accept(p.toFile())).sorted(Comparator.comparingLong(FileWriteAheadLogManager::segmentIndex).// Sort by segment index.\n reversed()).forEach(path -> {\n long idx = FileWriteAheadLogManager.segmentIndex(path);\n if (lastSgmnt.get() == -1 || lastSgmnt.get() - idx == 1) {\n lastSgmnt.set(idx);\n return;\n }\n delete.add(path.toFile());\n });\n if (delete.isEmpty()) {\n log.info(\"Lost segment CDC links were not found.\");\n return null;\n }\n log.info(\"Found lost segment CDC links. The following links will be deleted: \" + delete);\n delete.forEach(file -> {\n if (!file.delete()) {\n throw new IgniteException(\"Failed to delete lost segment CDC link [file=\" + file.getAbsolutePath() + ']');\n }\n log.info(\"Segment CDC link deleted [file=\" + file.getAbsolutePath() + ']');\n });\n Path stateDir = walCdcDir.toPath().resolve(STATE_DIR);\n if (stateDir.toFile().exists()) {\n File walState = stateDir.resolve(WAL_STATE_FILE_NAME).toFile();\n if (walState.exists() && !walState.delete()) {\n throw new IgniteException(\"Failed to delete wal state file [file=\" + walState.getAbsolutePath() + ']');\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to delete lost segment CDC links.\", e);\n }\n } catch (IgniteCheckedException e) {\n throw new RuntimeException(\"Failed to delete lost segment CDC links. \" + \"Unable to acquire lock to lock CDC folder. Make sure a CDC app is shut down \" + \"[dir=\" + walCdcDir.getAbsolutePath() + \", reason=\" + e.getMessage() + ']');\n } finally {\n U.closeQuiet(lock);\n }\n return null;\n}", "smellKey": "S112", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "@Override\npublic Boolean visitLocalRef(RexLocalRef localRef) {\n throw new RuntimeException(\"Not expected to be called.\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@SuppressWarnings(\"unchecked\")\n@Override\npublic void configure(String name, DataFormat target) {\n ObjectHelper.notNull(name, \"data format name\");\n ObjectHelper.notNull(target, \"data format instance\");\n try {\n consumer.accept(name, (T) target);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_camel", "language": "java"} {"function": "private void handlePartialStart(HttpPostCommand cmd) throws Throwable{\r\n decodeParamsAndAuthenticate(cmd, 2);\r\n boolean success = getNode().getNodeExtension().getInternalHotRestartService().triggerPartialStart();\r\n prepareResponse(cmd, response(success ? SUCCESS : FAIL));\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ClientMessage invoke(ClientMessage request, ClientConnection connection) throws Exception{\r\n ClientInvocationFuture fut = invokeAsync(request, connection);\r\n return fut.get();\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void mergeStripeInfos(StripeData to, StripeData from) {\n if (LlapIoImpl.CACHE_LOGGER.isTraceEnabled()) {\n LlapIoImpl.CACHE_LOGGER.trace(\"Merging slices data: old \" + to + \" and new \" + from);\n }\n to.knownTornStart = Math.min(to.knownTornStart, from.knownTornStart);\n if (from.encodings.length != to.encodings.length) {\n throw new RuntimeException(\"Different encodings \" + from + \"; \" + to);\n }\n for (int colIx = 0; colIx < from.encodings.length; ++colIx) {\n if (to.encodings[colIx] == null) {\n to.encodings[colIx] = from.encodings[colIx];\n } else if (from.encodings[colIx] != null && !to.encodings[colIx].equals(from.encodings[colIx])) {\n throw new RuntimeException(\"Different encodings at \" + colIx + \": \" + from + \"; \" + to);\n }\n LlapSerDeDataBuffer[][] fromColData = from.data[colIx];\n if (fromColData != null) {\n if (to.data[colIx] != null) {\n // Note: we assume here that the data that was returned to the caller from cache will not\n // be passed back in via put. Right now it's safe since we don't do anything. But if we\n // evict proactively, we will have to compare objects all the way down.\n handleRemovedColumnData(to.data[colIx]);\n }\n to.data[colIx] = fromColData;\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private Vertex getVertexFromDbForVid(String vtxIdStr) throws Exception{\r\n Vertex thisVertex = null;\r\n Long vtxIdL = 0L;\r\n try {\r\n vtxIdL = Long.parseLong(vtxIdStr);\r\n Iterator vItr = jg.vertices(vtxIdL);\r\n while (vItr.hasNext()) {\r\n thisVertex = vItr.next();\r\n }\r\n } catch (Exception e) {\r\n String emsg = \"Error finding vertex for vid = \" + vtxIdStr + \"[\" + e.getMessage() + \"]\";\r\n throw new Exception(emsg);\r\n }\r\n if (thisVertex == null) {\r\n String emsg = \"Could not find vertex for passed vid = \" + vtxIdStr;\r\n throw new Exception(emsg);\r\n }\r\n return thisVertex;\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public GraphWriteMethods getWritableGraph() {\n if (writableGraph == null) {\n throw new RuntimeException(\"GraphWrapper must be constructed with a GraphWriteMethods to do write operations.\");\n }\n return writableGraph;\n}", "smellKey": "S112", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "public void run() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void afterRun() throws Exception{\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates an encryption zone using the parameters passed through the 'create_zone' action.\n *\n * @param params Parameters passed to the 'create_zone' command action.\n * @throws Exception If zone creation failed.\n */\nprivate void createEncryptionZone(String[] params) throws Exception {\n CommandLine args = parseCommandArgs(CREATE_ZONE_OPTIONS, params);\n String keyName = args.getOptionValue(\"keyName\");\n String cryptoZoneStr = args.getOptionValue(\"path\");\n if (cryptoZoneStr == null) {\n throw new Exception(\"Cannot create encryption zone: Invalid path 'null'\");\n }\n Path cryptoZone = new Path(cryptoZoneStr);\n try {\n encryptionShim.createEncryptionZone(cryptoZone, keyName);\n } catch (IOException e) {\n throw new Exception(\"Cannot create encryption zone: \" + e.getMessage());\n }\n writeTestOutput(\"Encryption zone created: '\" + cryptoZone + \"' using key: '\" + keyName + \"'\");\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected Object getResponseBody(Exchange exchange) throws Exception{\r\n boolean exception = exchange.getException() != null && !consumer.getEndpoint().getConfiguration().isTransferExchange();\r\n if (exception) {\r\n return exchange.getException();\r\n }\r\n if (exchange.hasOut()) {\r\n return NettyPayloadHelper.getOut(consumer.getEndpoint(), exchange);\r\n } else {\r\n return NettyPayloadHelper.getIn(consumer.getEndpoint(), exchange);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setupConf(Properties propsDirectOptions) throws Exception{\r\n for (String f : LlapDaemonConfiguration.DAEMON_CONFIGS) {\r\n conf.addResource(f);\r\n if (conf.getResource(f) == null) {\r\n throw new Exception(\"Unable to find required config file: \" + f);\r\n }\r\n }\r\n for (String f : LlapDaemonConfiguration.SSL_DAEMON_CONFIGS) {\r\n conf.addResource(f);\r\n }\r\n conf.reloadConfiguration();\r\n populateConfWithLlapProperties(conf, cl.getConfig());\r\n if (cl.getName() != null) {\r\n conf.set(ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname, \"@\" + cl.getName());\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname, \"@\" + cl.getName());\r\n }\r\n if (cl.getLogger() != null) {\r\n HiveConf.setVar(conf, ConfVars.LLAP_DAEMON_LOGGER, cl.getLogger());\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_LOGGER.varname, cl.getLogger());\r\n }\r\n boolean isDirect = HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_ALLOCATOR_DIRECT);\r\n String cacheStr = LlapUtil.humanReadableByteCount(cl.getCache());\r\n String sizeStr = LlapUtil.humanReadableByteCount(cl.getSize());\r\n String xmxStr = LlapUtil.humanReadableByteCount(cl.getXmx());\r\n if (cl.getSize() != -1) {\r\n if (cl.getCache() != -1) {\r\n if (!HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_ALLOCATOR_MAPPED)) {\r\n Preconditions.checkArgument(cl.getCache() < cl.getSize(), \"Cache size (\" + cacheStr + \") has to be smaller\" + \" than the container sizing (\" + sizeStr + \")\");\r\n } else if (cl.getCache() < cl.getSize()) {\r\n LOG.warn(\"Note that this might need YARN physical memory monitoring to be turned off \" + \"(yarn.nodemanager.pmem-check-enabled=false)\");\r\n }\r\n }\r\n if (cl.getXmx() != -1) {\r\n Preconditions.checkArgument(cl.getXmx() < cl.getSize(), \"Working memory (Xmx=\" + xmxStr + \") has to be\" + \" smaller than the container sizing (\" + sizeStr + \")\");\r\n }\r\n if (isDirect && !HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_ALLOCATOR_MAPPED)) {\r\n Preconditions.checkArgument(cl.getXmx() + cl.getCache() <= cl.getSize(), \"Working memory (Xmx=\" + xmxStr + \") + cache size (\" + cacheStr + \") has to be smaller than the container sizing (\" + sizeStr + \")\");\r\n }\r\n }\r\n if (cl.getExecutors() != -1) {\r\n conf.setLong(ConfVars.LLAP_DAEMON_NUM_EXECUTORS.varname, cl.getExecutors());\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_NUM_EXECUTORS.varname, String.valueOf(cl.getExecutors()));\r\n }\r\n if (cl.getIoThreads() != -1) {\r\n conf.setLong(ConfVars.LLAP_IO_THREADPOOL_SIZE.varname, cl.getIoThreads());\r\n propsDirectOptions.setProperty(ConfVars.LLAP_IO_THREADPOOL_SIZE.varname, String.valueOf(cl.getIoThreads()));\r\n }\r\n long cache = cl.getCache();\r\n if (cache != -1) {\r\n conf.set(HiveConf.ConfVars.LLAP_IO_MEMORY_MAX_SIZE.varname, Long.toString(cache));\r\n propsDirectOptions.setProperty(HiveConf.ConfVars.LLAP_IO_MEMORY_MAX_SIZE.varname, Long.toString(cache));\r\n }\r\n long xmx = cl.getXmx();\r\n if (xmx != -1) {\r\n long xmxMb = (xmx / (1024L * 1024L));\r\n conf.setLong(ConfVars.LLAP_DAEMON_MEMORY_PER_INSTANCE_MB.varname, xmxMb);\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_MEMORY_PER_INSTANCE_MB.varname, String.valueOf(xmxMb));\r\n }\r\n long containerSize = cl.getSize();\r\n if (containerSize == -1) {\r\n long heapSize = xmx;\r\n if (!isDirect) {\r\n heapSize += cache;\r\n }\r\n containerSize = Math.min((long) (heapSize * 1.2), heapSize + 1024L * 1024 * 1024);\r\n if (isDirect) {\r\n containerSize += cache;\r\n }\r\n }\r\n long containerSizeMB = containerSize / (1024 * 1024);\r\n long minAllocMB = conf.getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, -1);\r\n String containerSizeStr = LlapUtil.humanReadableByteCount(containerSize);\r\n Preconditions.checkArgument(containerSizeMB >= minAllocMB, \"Container size (\" + containerSizeStr + \") should be \" + \"greater than minimum allocation(\" + LlapUtil.humanReadableByteCount(minAllocMB * 1024L * 1024L) + \")\");\r\n conf.setLong(ConfVars.LLAP_DAEMON_YARN_CONTAINER_MB.varname, containerSizeMB);\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_YARN_CONTAINER_MB.varname, String.valueOf(containerSizeMB));\r\n LOG.info(\"Memory settings: container memory: {} executor memory: {} cache memory: {}\", containerSizeStr, xmxStr, cacheStr);\r\n if (!StringUtils.isEmpty(cl.getLlapQueueName())) {\r\n conf.set(ConfVars.LLAP_DAEMON_QUEUE_NAME.varname, cl.getLlapQueueName());\r\n propsDirectOptions.setProperty(ConfVars.LLAP_DAEMON_QUEUE_NAME.varname, cl.getLlapQueueName());\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void executeStrategy(Split split, String type) {\n // TODO make different strategies for each type\n switch(split.getType()) {\n case Split.TYPE_AND:\n triggerCompleted(Node.CONNECTION_DEFAULT_TYPE, true);\n break;\n case Split.TYPE_XOR:\n List outgoing = split.getDefaultOutgoingConnections();\n int priority = Integer.MAX_VALUE;\n Connection selected = null;\n for (final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {\n final Connection connection = iterator.next();\n Collection constraints = split.getConstraints(connection);\n if (constraints != null) {\n for (Constraint constraint : constraints) {\n if (constraint instanceof ConstraintEvaluator && constraint.getPriority() < priority && !constraint.isDefault()) {\n try {\n if (((ConstraintEvaluator) constraint).evaluate(this, connection, constraint)) {\n selected = connection;\n priority = constraint.getPriority();\n }\n } catch (RuntimeException e) {\n throw new RuntimeException(\"Exception when trying to evaluate constraint \" + constraint.getName() + \" in split \" + split.getName(), e);\n }\n }\n }\n }\n }\n ((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);\n if (selected == null) {\n for (final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {\n final Connection connection = iterator.next();\n if (split.isDefault(connection)) {\n selected = connection;\n break;\n }\n }\n }\n if (selected == null) {\n throw new IllegalArgumentException(\"XOR split could not find at least one valid outgoing connection for split \" + getSplit().getName());\n }\n if (!hasLoop(selected.getTo(), split)) {\n setLevel(1);\n ((NodeInstanceContainer) getNodeInstanceContainer()).setCurrentLevel(1);\n }\n triggerConnection(selected);\n break;\n case Split.TYPE_OR:\n ((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);\n outgoing = split.getDefaultOutgoingConnections();\n boolean found = false;\n List nodeInstances = new ArrayList<>();\n List outgoingCopy = new ArrayList<>(outgoing);\n while (!outgoingCopy.isEmpty()) {\n priority = Integer.MAX_VALUE;\n Connection selectedConnection = null;\n ConstraintEvaluator selectedConstraint = null;\n for (final Iterator iterator = outgoingCopy.iterator(); iterator.hasNext(); ) {\n final Connection connection = iterator.next();\n Collection constraints = split.getConstraints(connection);\n if (constraints != null) {\n for (Constraint constraint : constraints) {\n if (constraint instanceof ConstraintEvaluator && constraint.getPriority() < priority && !constraint.isDefault()) {\n priority = constraint.getPriority();\n selectedConnection = connection;\n selectedConstraint = (ConstraintEvaluator) constraint;\n }\n }\n }\n }\n if (selectedConstraint == null) {\n break;\n }\n if (selectedConstraint.evaluate(this, selectedConnection, selectedConstraint)) {\n nodeInstances.add(new NodeInstanceTrigger(followConnection(selectedConnection), selectedConnection.getToType()));\n found = true;\n }\n outgoingCopy.remove(selectedConnection);\n }\n for (NodeInstanceTrigger nodeInstance : nodeInstances) {\n // stop if this process instance has been aborted / completed\n if (getProcessInstance().getState() != KogitoProcessInstance.STATE_ACTIVE) {\n return;\n }\n triggerNodeInstance(nodeInstance.getNodeInstance(), nodeInstance.getToType());\n }\n if (!found) {\n final Iterator iterator = outgoing.iterator();\n while (!found && iterator.hasNext()) {\n final Connection connection = iterator.next();\n Collection constraints = split.getConstraints(connection);\n if (constraints != null) {\n for (Constraint constraint : constraints) {\n if (constraint != null && constraint.isDefault()) {\n triggerConnection(connection);\n found = true;\n break;\n }\n }\n }\n if (!found && split.isDefault(connection)) {\n triggerConnection(connection);\n found = true;\n }\n }\n }\n if (!found) {\n throw new IllegalArgumentException(\"OR split could not find at least one valid outgoing connection for split \" + getSplit().getName());\n }\n break;\n case Split.TYPE_XAND:\n ((org.jbpm.workflow.instance.NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);\n org.kie.api.definition.process.Node node = getNode();\n List connections = null;\n if (node != null) {\n connections = node.getOutgoingConnections(type);\n }\n if (connections == null || connections.isEmpty()) {\n ((org.jbpm.workflow.instance.NodeInstanceContainer) getNodeInstanceContainer()).nodeInstanceCompleted(this, type);\n } else {\n ExclusiveGroupInstance groupInstance = new ExclusiveGroupInstance();\n org.kie.api.runtime.process.NodeInstanceContainer parent = getNodeInstanceContainer();\n if (parent instanceof ContextInstanceContainer) {\n ((ContextInstanceContainer) parent).addContextInstance(ExclusiveGroup.EXCLUSIVE_GROUP, groupInstance);\n } else {\n throw new IllegalArgumentException(\"An Exclusive AND is only possible if the parent is a context instance container\");\n }\n Map nodeInstancesMap = new HashMap<>();\n for (Connection connection : connections) {\n nodeInstancesMap.put(followConnection(connection), connection.getToType());\n }\n for (KogitoNodeInstance nodeInstance : nodeInstancesMap.keySet()) {\n groupInstance.addNodeInstance(nodeInstance);\n }\n for (Map.Entry entry : nodeInstancesMap.entrySet()) {\n // stop if this process instance has been aborted / completed\n if (getProcessInstance().getState() != KogitoProcessInstance.STATE_ACTIVE) {\n return;\n }\n boolean hidden = false;\n if (getNode().getMetaData().get(\"hidden\") != null) {\n hidden = true;\n }\n leaveTime = new Date();\n InternalKnowledgeRuntime kruntime = getProcessInstance().getKnowledgeRuntime();\n if (!hidden) {\n ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireBeforeNodeLeft(this, kruntime);\n }\n (entry.getKey()).trigger(this, entry.getValue());\n if (!hidden) {\n ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireAfterNodeLeft(this, kruntime);\n }\n }\n }\n break;\n default:\n throw new IllegalArgumentException(\"Illegal split type \" + split.getType());\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public synchronized void reload() throws RuntimeException{\r\n final ArrayList currentAccountsList = new ArrayList<>(accountAllowlist);\r\n accountAllowlist.clear();\r\n try {\r\n final LocalPermissioningConfiguration updatedConfig = PermissioningConfigurationBuilder.permissioningConfiguration(configuration.isNodeAllowlistEnabled(), configuration.getEnodeDnsConfiguration(), configuration.getNodePermissioningConfigFilePath(), configuration.isAccountAllowlistEnabled(), configuration.getAccountPermissioningConfigFilePath());\r\n readAccountsFromConfig(updatedConfig);\r\n configuration = updatedConfig;\r\n } catch (Exception e) {\r\n accountAllowlist.clear();\r\n accountAllowlist.addAll(currentAccountsList);\r\n throw new IllegalStateException(\"Error reloading permissions file. In-memory accounts allowlist will be reverted to previous valid configuration\", e);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Verify that we don't have an unexpected type of object inspector.\n * @param option The option to verify\n * @param oi The ObjectInspector to verify\n * @param checkOption We're only interested in this option type\n * @param classes ObjectInspector should not be of these types\n */\nprivate static void verifyObjectInspector(ObjectInspectorOptions option, ObjectInspector oi, ObjectInspectorOptions checkOption, Class[] classes) {\n if (option.equals(checkOption)) {\n for (Class checkClass : classes) {\n if (oi.getClass().equals(checkClass)) {\n throw new RuntimeException(\"Cannot call getObjectInspectorByReflection with more then one of \" + Arrays.toString(ObjectInspectorOptions.values()) + \"!\");\n }\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "@Override\npublic FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {\n ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(file).toString());\n try {\n zs.putNextEntry(zipEntry);\n Files.copy(file, zs);\n zs.closeEntry();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return FileVisitResult.CONTINUE;\n}", "smellKey": "S112", "smellId": null, "repo": "KNIME_knime-bigdata", "language": "java"} {"function": "private RaftClientReply transferLeader(RaftGroup group, RaftPeer newLeader) throws Exception{\r\n try (RatisClient client = getRaftClient(group)) {\r\n return client.getRaftClient().admin().transferLeadership(newLeader != null ? newLeader.getId() : null, 10000);\r\n }\r\n}", "smellKey": "S112", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String convertTo(String url, String targetFileExtension) throws Exception {\n if (!this.supportsInputFormat(url)) {\n throw new Exception(\"Format nicht unterst\u00fctzt: \" + new File(url).getName());\n }\n if (targetFileExtension == null) {\n throw new Exception(\"Es muss ein Zielformat angegeben werden\");\n }\n targetFileExtension = targetFileExtension.toLowerCase();\n targetFileExtension = targetFileExtension.replaceAll(\"\\\\.\", \"\");\n if (!OUTPUTTYPES.contains(targetFileExtension)) {\n throw new Exception(\"Konvertierung nach \" + targetFileExtension + \" ist nicht verf\u00fcgbar!\");\n }\n Process p = Runtime.getRuntime().exec(new String[] { \"/Applications/LibreOffice.app/Contents/Resources/python\", \"unoconv-master/unoconv\", \"-f\", targetFileExtension, url });\n int exit = p.waitFor();\n if (exit != 0) {\n throw new Exception(\"Konvertierung nach \" + targetFileExtension + \" fehlgeschlagen: \" + exit);\n }\n File org = new File(url);\n String orgName = org.getName();\n String path = url.substring(0, url.indexOf(orgName));\n return path + orgName.substring(0, orgName.lastIndexOf('.')) + \".\" + targetFileExtension;\n}", "smellKey": "S112", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n int row = this.tblMappingTables.getSelectedRow();\n if (row >= 0) {\n MappingTable mt = (MappingTable) this.tblMappingTables.getValueAt(row, 0);\n mt.setTableName(this.txtTableName.getText());\n mt.setKey1Name(this.txtKey1.getText());\n mt.setKey2Name(this.txtKey2.getText());\n mt.setKey3Name(this.txtKey3.getText());\n mt.setSystemTable(this.chkSystemTable.isSelected());\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n MappingTable savedTable = locator.lookupSystemManagementRemote().updateMappingTable(mt);\n row = this.tblMappingTables.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblMappingTables.getModel()).setValueAt(savedTable, row, 0);\n ((DefaultTableModel) this.tblMappingTables.getModel()).setValueAt(savedTable.isSystemTable(), row, 1);\n } catch (Exception ex) {\n log.error(\"Error updating mapping table\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void writeDouble(double d, String tag) throws IOException{\n out.writeDouble(d);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean allowDelete(final Item> rowItem){\r\n return true;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean notifyEnabled(int arg0){\r\n return false;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Perform any steps that must succeed across all storage dirs/JournalManagers\n * involved in an upgrade before proceeding onto the actual upgrade stage. If\n * a call to any JM's or local storage dir's doPreUpgrade method fails, then\n * doUpgrade will not be called for any JM. The existing current dir is\n * renamed to previous.tmp, and then a new, empty current dir is created.\n *\n * @param conf configuration for creating {@link EditLogFileOutputStream}\n * @param sd the storage directory to perform the pre-upgrade procedure.\n * @throws IOException in the event of error\n */\nstatic void doPreUpgrade(Configuration conf, StorageDirectory sd) throws IOException {\n LOG.info(\"Starting upgrade of storage directory \" + sd.getRoot());\n // rename current to tmp\n renameCurToTmp(sd);\n final Path curDir = sd.getCurrentDir().toPath();\n final Path tmpDir = sd.getPreviousTmp().toPath();\n Files.walkFileTree(tmpDir, /* do not follow links */\n Collections.emptySet(), 1, new SimpleFileVisitor() {\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n String name = file.getFileName().toString();\n if (Files.isRegularFile(file) && name.startsWith(NNStorage.NameNodeFile.EDITS.getName())) {\n Path newFile = curDir.resolve(name);\n Files.createLink(newFile, file);\n }\n return super.visitFile(file, attrs);\n }\n });\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void unsetRoleManagementListener(RoleManagementListener roleManagementListener) {\n RoleManagementServiceComponentHolder.getInstance().setRoleManagementListenerList(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmbToActionPerformed\nprivate void formComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_formComponentResized\n ComponentUtils.storeDialogSize(this);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void initializeRecordStore(String mapName, RecordStore recordStore){\n recordStore.reset();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_mnuFindAddressOSMActionPerformed\nprivate void mnuFindRouteToAddressGoogleActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuFindRouteToAddressGoogleActionPerformed\n if (this.a != null) {\n String startAddress = getMapStartAddress();\n String destinationAddress = getMapDestinationAddress();\n try {\n GoogleMapsUtils.openBrowserWithRoute(startAddress, destinationAddress);\n } catch (Exception e) {\n log.error(\"Unable to get route from Google Maps: \" + startAddress + \" TO \" + destinationAddress, e);\n JOptionPane.showMessageDialog(this, \"Route konnte nicht ermittelt werden: \" + e.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void initializeHierarchyUnencrypted(DeterministicKey baseKey){\n externalParentKey = hierarchy.deriveChild(getAccountPath(), false, false, ChildNumber.ZERO);\n internalParentKey = hierarchy.deriveChild(getAccountPath(), false, false, ChildNumber.ONE);\n addToBasicChain(externalParentKey);\n addToBasicChain(internalParentKey);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdRotateLeftActionPerformed\nprivate void cmdRotateRightActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRotateRightActionPerformed\n this.documentContainer.rotatePage(new int[] { this.pageIndex }, 90);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void cmdCancelActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCancelActionPerformed\n this.result = null;\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private List createActionList(User user, Action... actions) {\n List returnList = new LinkedList<>();\n for (Action actionIn : actions) {\n returnList.add(actionIn);\n }\n return returnList;\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public static EdgeType determineEdgeType(BaseWork preceedingWork, BaseWork followingWork, ReduceSinkOperator reduceSinkOperator) {\n // The 1-1 edge should also work for sorted cases, however depending on the details of the shuffle\n // this might end up writing multiple compressed files or end up using an in-memory partitioned kv writer\n // the condition about ordering = false can be removed at some point with a tweak to the unordered writer\n // to never split a single output across multiple files (and never attempt a final merge)\n if (reduceSinkOperator.getConf().isForwarding() && !reduceSinkOperator.getConf().isOrdering()) {\n return EdgeType.ONE_TO_ONE_EDGE;\n }\n if (followingWork instanceof ReduceWork) {\n // Ideally there should be a better way to determine that the followingWork contains\n // a dynamic partitioned hash join, but in some cases (createReduceWork()) it looks like\n // the work must be created/connected first, before the GenTezProcContext can be updated\n // with the mapjoin/work relationship.\n ReduceWork reduceWork = (ReduceWork) followingWork;\n if (reduceWork.getReducer() instanceof MapJoinOperator) {\n MapJoinOperator joinOp = (MapJoinOperator) reduceWork.getReducer();\n if (joinOp.getConf().isDynamicPartitionHashJoin()) {\n return EdgeType.CUSTOM_SIMPLE_EDGE;\n }\n }\n }\n if (!reduceSinkOperator.getConf().isOrdering()) {\n //if no sort keys are specified, use an edge that does not sort\n return EdgeType.CUSTOM_SIMPLE_EDGE;\n }\n return EdgeType.SIMPLE_EDGE;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdOKActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdOKActionPerformed\n JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/configuration/FontSizeConfigDialog\").getString(\"dialog.restartrequired\"), java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/configuration/FontSizeConfigDialog\").getString(\"dialog.title\"), JOptionPane.INFORMATION_MESSAGE);\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Double getSelectivity(RelNode rel, RelMetadataQuery mq, @Nullable RexNode predicate){\n return RelMdUtil.guessSelectivity(predicate);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Set getBookiesToConsiderAfterExcludingZonesAndUDs(int ensembleSize, int writeQuorumSize, List currentEnsemble, int bookieToReplaceIndex, Set excludeBookies, Set excludeZones){\n Set bookiesToConsiderAfterExcludingZonesAndUDs = new HashSet();\n HashMap> excludingUDsOfZonesToConsider = new HashMap>();\n Set bookiesToConsiderAfterExcludingZones = getBookiesToConsider(getExcludedZonesString(excludeZones), excludeBookies);\n if (!bookiesToConsiderAfterExcludingZones.isEmpty()) {\n Set zonesToConsider = getZonesOfBookies(bookiesToConsiderAfterExcludingZones);\n for (String zoneToConsider : zonesToConsider) {\n Set upgradeDomainsOfAZoneInNeighboringNodes = getUpgradeDomainsOfAZoneInNeighboringNodes(currentEnsemble, bookieToReplaceIndex, writeQuorumSize, zoneToConsider);\n excludingUDsOfZonesToConsider.put(zoneToConsider, upgradeDomainsOfAZoneInNeighboringNodes);\n }\n updateBookiesToConsiderAfterExcludingZonesAndUDs(bookiesToConsiderAfterExcludingZonesAndUDs, bookiesToConsiderAfterExcludingZones, excludingUDsOfZonesToConsider);\n if (bookiesToConsiderAfterExcludingZonesAndUDs.isEmpty()) {\n excludingUDsOfZonesToConsider.clear();\n for (String zoneToConsider : zonesToConsider) {\n Set udsToExcludeToMaintainMinUDsInWriteQuorums = getUDsToExcludeToMaintainMinUDsInWriteQuorums(currentEnsemble, bookieToReplaceIndex, writeQuorumSize, zoneToConsider);\n excludingUDsOfZonesToConsider.put(zoneToConsider, udsToExcludeToMaintainMinUDsInWriteQuorums);\n }\n updateBookiesToConsiderAfterExcludingZonesAndUDs(bookiesToConsiderAfterExcludingZonesAndUDs, bookiesToConsiderAfterExcludingZones, excludingUDsOfZonesToConsider);\n }\n }\n return bookiesToConsiderAfterExcludingZonesAndUDs;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void wsdlValidate(String wsdl, String soapBody, String testSoap, String testXml, String testJsonStraight, String testJsonCompact, String targetContent1, String targetContent2) throws Exception {\n WsdlXmlValidator val = configuration.createBean(WsdlXmlValidator.class);\n val.setWsdl(wsdl);\n // val.setSoapBody(\"TradePriceRequest\");\n val.setThrowException(true);\n val.addForward(new PipeForward(\"success\", null));\n val.setSoapBody(soapBody);\n val.setValidateJsonToRootElementOnly(false);\n val.configure();\n val.start();\n boolean compactJsonArrays = false;\n validate(\"Validate XML\", val, getTestXml(testSoap), null, compactJsonArrays, targetContent1, targetContent2);\n validate(\"XML to JSON\", val, getTestXml(testSoap), \"json\", compactJsonArrays, targetContent1, targetContent2);\n validate(\"JSON to XML\", val, getTestXml(testJsonStraight), \"xml\", compactJsonArrays, targetContent1, targetContent2);\n validate(\"JSON to JSON\", val, getTestXml(testJsonStraight), \"json\", compactJsonArrays, targetContent1, targetContent2);\n compactJsonArrays = true;\n validate(\"Validate XML\", val, getTestXml(testSoap), null, compactJsonArrays, targetContent1, targetContent2);\n validate(\"XML to JSON\", val, getTestXml(testSoap), \"json\", compactJsonArrays, targetContent1, targetContent2);\n // basic json Parsing compactJsonArrays=true\n validate(\"JSON to XML\", val, getTestXml(testJsonCompact), \"xml\", compactJsonArrays, targetContent1, targetContent2);\n validate(\"JSON to JSON\", val, getTestXml(testJsonCompact), \"json\", compactJsonArrays, targetContent1, targetContent2);\n validate(\"JSON to XML, extra spaces\", val, \" \" + getTestXml(testJsonCompact), \"xml\", compactJsonArrays, targetContent1, targetContent2);\n // check compatibiliy of compactJsonArrays=true with straight json\n validate(\"straight JSON to XML\", val, getTestXml(testJsonStraight), \"xml\", compactJsonArrays, targetContent1, targetContent2);\n validate(\"straight JSON to JSON\", val, getTestXml(testJsonStraight), \"json\", compactJsonArrays, targetContent1, targetContent2);\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdOpenActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdOpenActionPerformed\n InvoiceDialog dlg = new InvoiceDialog(this.caseView, this.caseDto, EditorsRegistry.getInstance().getMainWindow(), true, this.addresses);\n dlg.setEntry(this.getInvoice());\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n this.setEntry(caseDto, dlg.getEntry(), addresses);\n this.setPaidTotal(dlg.getEntry().getTotalGross(), BigDecimal.valueOf(Float.MIN_VALUE), dlg.getEntry().getCurrency());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static int getScale(int gadgetId){\r\n return 0;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ScannableTable eval(boolean b){\n return new ScannableTable() {\n\n @Override\n public Enumerable<@Nullable Object[]> scan(DataContext root) {\n return Processes.processLines(\"jps\", \"-m\", \"-l\", \"-v\").select(a0 -> {\n final String[] fields = a0.split(\" \");\n return new Object[] { Long.valueOf(fields[0]), fields[1] };\n });\n }\n\n @Override\n public RelDataType getRowType(RelDataTypeFactory typeFactory) {\n return typeFactory.builder().add(\"pid\", SqlTypeName.BIGINT).add(\"info\", SqlTypeName.VARCHAR).build();\n }\n\n @Override\n public Statistic getStatistic() {\n return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));\n }\n\n @Override\n public Schema.TableType getJdbcTableType() {\n return Schema.TableType.TABLE;\n }\n\n @Override\n public boolean isRolledUp(String column) {\n return false;\n }\n\n @Override\n public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable CalciteConnectionConfig config) {\n return true;\n }\n };\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static MinimumProgressIndex deserializeFrom(ByteBuffer byteBuffer) {\n return INSTANCE;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "//GEN-LAST:event_cmdMovePosUpActionPerformed\nprivate void cmdMovePosDownActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdMovePosDownActionPerformed\n int index = this.getParent().getComponentZOrder(this);\n if (index < this.getParent().getComponentCount() - 1) {\n this.position.setPosition(index + 1);\n this.updatePosition();\n this.getParent().setComponentZOrder(this, ++index);\n this.getParent().doLayout();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n TemplateManagementUIServiceDataHolder.getInstance().setRealmService(null);\n if (log.isDebugEnabled()) {\n log.debug(\"RealmService is unregistered in ConsentManager service.\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n int row = this.tblTemplates.getSelectedRow();\n if (row >= 0) {\n CalendarEntryTemplate tpl = (CalendarEntryTemplate) this.tblTemplates.getValueAt(row, 0);\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupCalendarServiceRemote().removeCalendarEntryTemplate(tpl);\n row = this.tblTemplates.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblTemplates.getModel()).removeRow(row);\n this.resetDetails();\n } catch (Exception ex) {\n log.error(\"Error removing calendar entry template\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static List estimateStats(Table table, List schema, List neededColumns, HiveConf conf, long nr) {\n List stats = new ArrayList(neededColumns.size());\n for (int i = 0; i < neededColumns.size(); i++) {\n ColStatistics cs = estimateColStats(nr, neededColumns.get(i), conf, schema);\n stats.add(cs);\n }\n return stats;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n int row = this.tblAssistants.getSelectedRow();\n if (row >= 0) {\n AssistantConfig ac = (AssistantConfig) this.tblAssistants.getValueAt(row, 0);\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupIntegrationServiceRemote().removeAssistantConfig(ac);\n row = this.tblAssistants.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblAssistants.getModel()).removeRow(row);\n this.resetDetails();\n } catch (Exception ex) {\n log.error(\"Error removing assistant config\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void registerTaskAllocated(String[] requestedHosts, String[] requestedRacks, String allocatedHost){\n if (requestedHosts != null && requestedHosts.length != 0) {\n Set requestedHostSet = new HashSet<>(Arrays.asList(requestedHosts));\n if (requestedHostSet.contains(allocatedHost)) {\n numLocalAllocations++;\n _registerAllocationInHostMap(allocatedHost, localityBasedNumAllocationsPerHost);\n } else {\n numNonLocalAllocations++;\n }\n } else {\n numAllocationsNoLocalityRequest++;\n }\n numTotalAllocations++;\n _registerAllocationInHostMap(allocatedHost, numAllocationsPerHost);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private HeartbeatReport getReport(String domain, String ipAddress, long date, ModelPeriod period){\n ModelRequest request = new ModelRequest(domain, date).setProperty(\"ip\", ipAddress);\n if (m_service.isEligable(request)) {\n ModelResponse response = m_service.invoke(request);\n HeartbeatReport report = response.getModel();\n return report;\n } else {\n throw new RuntimeException(\"Internal error: no eligable ip service registered for \" + request + \"!\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void cmdPageBackwardActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdPageBackwardActionPerformed\n this.currentPage = this.currentPage - 1;\n this.showPage(this.content, this.currentPage, this.zoomFactor);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public StringAndPos toSql(boolean withCaret){\r\n return expression ? StringAndPos.of(AbstractSqlTester.buildQuery(sap.addCarets())) : sap;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doRowFilterCompareTest(TypeInfo typeInfo1, TypeInfo typeInfo2, List columns, List children, ExprNodeGenericFuncDesc exprDesc, Comparison comparison, Object[][] randomRows, ColumnScalarMode columnScalarMode, ObjectInspector rowInspector, TypeInfo outputTypeInfo, Object[] resultObjects) throws Exception {\n /*\n System.out.println(\n \"*DEBUG* typeInfo \" + typeInfo1.toString() +\n \" typeInfo2 \" + typeInfo2 +\n \" filterCompareTestMode ROW_MODE\" +\n \" columnScalarMode \" + columnScalarMode +\n \" exprDesc \" + exprDesc.toString());\n */\n HiveConf hiveConf = new HiveConf();\n ExprNodeEvaluator evaluator = ExprNodeEvaluatorFactory.get(exprDesc, hiveConf);\n evaluator.initialize(rowInspector);\n ObjectInspector objectInspector = TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(outputTypeInfo);\n final int rowCount = randomRows.length;\n for (int i = 0; i < rowCount; i++) {\n Object[] row = randomRows[i];\n Object result = evaluator.evaluate(row);\n Object copyResult = null;\n try {\n copyResult = ObjectInspectorUtils.copyToStandardObject(result, objectInspector, ObjectInspectorCopyOption.WRITABLE);\n } catch (Exception e) {\n Assert.fail(e.toString());\n }\n resultObjects[i] = copyResult;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected InputStream getInputStream(Message message, PipeLineSession session) throws PipeRunException {\n try {\n if (isProcessFile()) {\n String filename = message.asString();\n try {\n return new FileInputStream(filename);\n } catch (FileNotFoundException e) {\n throw new PipeRunException(this, \"could not find file [\" + filename + \"]\", e);\n }\n } else if (!message.isBinary()) {\n log.warn(\"expected binary message, encountered character data. Do you need to set processFile=\\\"true\\\"?\");\n }\n return message.asInputStream();\n } catch (IOException e) {\n throw new PipeRunException(this, \"cannot open stream\", e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "private void contentPanelComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_contentPanelComponentResized\n tp.setBounds(0, 0, this.contentPanel.getWidth(), this.contentPanel.getHeight());\n SwingUtilities.updateComponentTreeUI(tp);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdToCaseActionPerformed\nprivate void cmdViewReportActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdViewReportActionPerformed\n Object value = null;\n if (this.tblQueue.getSelectedRowCount() == 1) {\n value = this.tblQueue.getValueAt(this.tblQueue.getSelectedRow(), 0);\n }\n if (value instanceof EpostQueueEntry) {\n String report = ((EpostQueueEntry) value).getEntry().toReport();\n GenericTextViewer v = new GenericTextViewer(EditorsRegistry.getInstance().getMainWindow(), true, \"Sendungsnummer:\", ((EpostQueueEntry) value).getIdentifier(), report);\n v.setTitle(\"E-POST-Sendungsstatus\");\n FrameUtils.centerDialog(v, EditorsRegistry.getInstance().getMainWindow());\n v.setVisible(true);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Response invoke(HttpMethod method, String url, Map headers, Output writer, BindingSession session) {\n //Prepare the message. We will overwrite things later...\n int responseCode = -1;\n try (PipeLineSession pls = new PipeLineSession()) {\n pls.put(\"writer\", writer);\n pls.put(\"url\", url);\n pls.put(\"method\", method);\n pls.put(\"headers\", headers);\n try {\n // Message is unused, we use 'Output writer' instead\n SenderResult ignored = sendMessage(Message.nullMessage(), pls);\n // close our nullMessage\n ignored.getResult().close();\n return (Response) pls.get(\"__response\");\n } catch (Exception e) {\n throw new CmisConnectionException(getUrl(), responseCode, e);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "private static boolean processQueryNode(QueryElementNode queryNode, ReteEvaluator reteEvaluator, LeftTupleSource segmentRoot, SegmentMemory smem, List memories, long nodePosMask){\r\n SegmentMemory querySmem = getQuerySegmentMemory(reteEvaluator, queryNode);\r\n QueryElementNode.QueryElementNodeMemory queryNodeMem = smem.createNodeMemory(queryNode, reteEvaluator);\r\n queryNodeMem.setNodePosMaskBit(nodePosMask);\r\n queryNodeMem.setQuerySegmentMemory(querySmem);\r\n queryNodeMem.setSegmentMemory(smem);\r\n memories.add(queryNodeMem);\r\n return !queryNode.getQueryElement().isAbductive();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdImportActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdImportActionPerformed\n new Thread(new ImportZipCodesThread(this, this.progBar, this.cmdClose, this.cmdImport)).start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Provide whether the user referred is the logged-in user.\n *\n * @param currentUsername logged in username.\n * @param username provided username.\n * @param userRealmInfo User realm info.\n * @return Returns 'true' if the provided user is the logged-in user.\n */\npublic static boolean isCurrentUser(String currentUsername, String username, UserRealmInfo userRealmInfo) {\n if (username.contains(UserCoreConstants.DOMAIN_SEPARATOR)) {\n // username case sensitiveness can be changed in the database level or using the user-store configuration.\n // So always consider username as case insensitive.\n return currentUsername.equalsIgnoreCase(username);\n }\n if (currentUsername.contains(UserCoreConstants.DOMAIN_SEPARATOR) && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(UserCoreUtil.extractDomainFromName(currentUsername))) {\n return false;\n }\n // username case sensitiveness can be changed in the database level or using the user-store configuration.\n // So always consider username as case insensitive.\n return UserCoreUtil.removeDomainFromName(currentUsername).equalsIgnoreCase(username);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public byte[] addRandomExisting(byte[] value, Random r) {\n Preconditions.checkState(count > 0);\n int index = r.nextInt(count);\n array[index].incrementMultiSetCount();\n return array[index].getKey();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public PTLinkType produce(PTLink ptLink, boolean addExtension){\n PTLinkType jaxbPTLink = tridentFactory.createPTLinkType();\n populateFromModel(jaxbPTLink, ptLink);\n jaxbPTLink.setName(ptLink.getName());\n jaxbPTLink.setStartOfLink(getNonEmptyObjectId(ptLink.getStartOfLink()));\n jaxbPTLink.setEndOfLink(getNonEmptyObjectId(ptLink.getEndOfLink()));\n jaxbPTLink.setLinkDistance(ptLink.getLinkDistance());\n return jaxbPTLink;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ErrorMessageFactory shouldMatch(T actual, Predicate predicate, PredicateDescription predicateDescription){\n requireNonNull(predicateDescription, \"The predicate description must not be null\");\n return new ShouldMatch(actual, predicateDescription);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// no-op\npublic Builder profileName(String profileName) {\n return this;\n}", "smellKey": "S1172", "smellId": null, "repo": "aws_aws-sdk-java-v2", "language": "java"} {"function": "public static String escapeSql(IValueMeta metaA, Object dataA) {\n if (dataA == null) {\n return null;\n }\n return Const.escapeSql(dataA.toString());\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected ActionsPanel getActions(final IModel model){\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCancelActionPerformed\nprivate void cmdUnknownActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdUnknownActionPerformed\n this.selectedAuthority = LegalAuthorities.getDefaultAuthority();\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2){\r\n String dateFormatAsString = format.format(new Date(src.getTime()));\r\n return new JsonPrimitive(dateFormatAsString);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public FlaggedName[] listUsers(ClaimValue claimValue, String filter, int maxLimit) throws UserAdminException {\n try {\n String[] usersWithClaim = null;\n if (claimValue.getClaimURI() != null && claimValue.getValue() != null) {\n usersWithClaim = realm.getUserStoreManager().getUserList(claimValue.getClaimURI(), claimValue.getValue(), null);\n }\n int i = 0;\n FlaggedName[] flaggedNames = new FlaggedName[0];\n if (usersWithClaim != null) {\n flaggedNames = new FlaggedName[usersWithClaim.length + 1];\n Arrays.sort(usersWithClaim);\n // Check whether to use the display name claim when filtering users.\n String showDisplayName = IdentityUtil.getProperty(IdentityConstants.SHOW_DISPLAY_NAME);\n boolean isShowDisplayNameEnabled = Boolean.parseBoolean(showDisplayName);\n // Check for display name attribute mappings and retrieve the relevant claim uri.\n String displayNameAttribute = realm.getRealmConfiguration().getUserStoreProperty(DISPLAY_NAME_ATTRIBUTE);\n String displayNameClaimURI = DISPLAY_NAME_CLAIM;\n if (StringUtils.isNotBlank(displayNameAttribute)) {\n ClaimMapping[] claimMappings = realm.getClaimManager().getAllClaimMappings();\n if (claimMappings != null) {\n for (ClaimMapping claimMapping : claimMappings) {\n if (displayNameAttribute.equals(claimMapping.getMappedAttribute())) {\n displayNameClaimURI = claimMapping.getClaim().getClaimUri();\n break;\n }\n }\n }\n }\n for (String user : usersWithClaim) {\n flaggedNames[i] = new FlaggedName();\n flaggedNames[i].setItemName(user);\n // Retrieving the displayName.\n String displayName = null;\n if (StringUtils.isNotBlank(displayNameAttribute) || isShowDisplayNameEnabled) {\n displayName = realm.getUserStoreManager().getUserClaimValue(user, displayNameClaimURI, null);\n }\n if (StringUtils.isNotBlank(displayName)) {\n int index = user.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);\n if (index > 0) {\n flaggedNames[i].setItemDisplayName(user.substring(0, index + 1) + displayName);\n } else {\n flaggedNames[i].setItemDisplayName(displayName);\n }\n } else {\n flaggedNames[i].setItemDisplayName(user);\n }\n int index1 = flaggedNames[i].getItemName() != null ? flaggedNames[i].getItemName().indexOf(CarbonConstants.DOMAIN_SEPARATOR) : -1;\n boolean domainProvided = index1 > 0;\n String domain = domainProvided ? flaggedNames[i].getItemName().substring(0, index1) : null;\n if (domain != null && !UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(domain) && !UserMgtConstants.APPLICATION_DOMAIN.equalsIgnoreCase(domain)) {\n UserStoreManager secondaryUM = realm.getUserStoreManager().getSecondaryUserStoreManager(domain);\n if (secondaryUM != null && secondaryUM.isReadOnly()) {\n flaggedNames[i].setEditable(false);\n } else {\n flaggedNames[i].setEditable(true);\n }\n } else {\n if (realm.getUserStoreManager().isReadOnly()) {\n flaggedNames[i].setEditable(false);\n } else {\n flaggedNames[i].setEditable(true);\n }\n }\n i++;\n }\n if (usersWithClaim.length > 0) {\n //tail flagged name is added to handle pagination\n FlaggedName flaggedName = new FlaggedName();\n flaggedName.setItemName(FALSE);\n flaggedName.setDomainName(\"\");\n flaggedNames[flaggedNames.length - 1] = flaggedName;\n }\n }\n return flaggedNames;\n } catch (UserStoreException e) {\n log.error(e.getMessage(), e);\n throw new UserAdminException(e.getMessage(), e);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new UserAdminException(e.getMessage(), e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdCloneTemplateActionPerformed\nprivate void mnuRenameFolderActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuRenameFolderActionPerformed\n DefaultMutableTreeNode tn = (DefaultMutableTreeNode) this.treeFolders.getSelectionPath().getLastPathComponent();\n DocumentFolder gn = (DocumentFolder) tn.getUserObject();\n ClientSettings settings = ClientSettings.getInstance();\n String newFolderName = gn.getName();\n Object newNameObject = JOptionPane.showInputDialog(this, \"neuer Name: \", \"Ordner umbenennen\", JOptionPane.QUESTION_MESSAGE, null, null, newFolderName);\n if (newNameObject == null) {\n return;\n }\n newFolderName = newNameObject.toString();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n DocumentFolder updatedFolderNode = locator.lookupArchiveFileServiceRemote().renameFolderInTemplate(gn.getId(), newFolderName);\n tn.setUserObject(updatedFolderNode);\n this.cmbTemplatesActionPerformed(null);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Umbenennen des Ordners: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_mnuSendBeaDocumentActionPerformed\nprivate void mnuSendBeaDocumentPDFActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSendBeaDocumentPDFActionPerformed\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n ArrayList open = this.getDocumentsOpenForWrite(selectedDocs);\n if (open.size() > 0) {\n String question = \"Soll die Aktion auf ge\u00f6ffnete Dokumente ausgef\u00fchrt werden? Es besteht das Risiko fehlender / inkonsistenter Inhalte.
    \";\n for (String o : open) {\n question = question + \"
  • \" + o + \"
  • \";\n }\n question = question + \"
\";\n int response = JOptionPane.showConfirmDialog(this, question, \"Aktion auf offene Dokumente ausf\u00fchren\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n return;\n }\n }\n if (!BeaAccess.hasInstance()) {\n BeaLoginCallback callback = null;\n try {\n callback = (BeaLoginCallback) EditorsRegistry.getInstance().getEditor(BeaInboxPanel.class.getName());\n } catch (Throwable t) {\n log.error(t);\n }\n BeaLoginDialog loginPanel = new BeaLoginDialog(EditorsRegistry.getInstance().getMainWindow(), true, callback);\n loginPanel.setVisible(true);\n if (!BeaAccess.hasInstance()) {\n return;\n }\n }\n if (!this.readOnly) {\n this.saveFormData();\n this.saveInvolvements();\n }\n SendBeaMessageDialog dlg = new SendBeaMessageDialog(EditorsRegistry.getInstance().getMainWindow(), false);\n dlg.setArchiveFile(dto);\n dlg.setInvolvedInCase(this.pnlInvolvedParties.getInvolvedParties());\n for (ArchiveFileAddressesBean aab : this.pnlInvolvedParties.getInvolvedParties()) {\n dlg.addParty(aab);\n }\n ProgressIndicator pi = new ProgressIndicator(EditorsRegistry.getInstance().getMainWindow(), true);\n pi.setShowCancelButton(selectedDocs.size() > 1);\n SendPDFAction a = new SendPDFAction(pi, this.caseFolderPanel1, dlg);\n a.start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public boolean registerResourceToBuild(String kBaseName, String resource){\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static StaticAttributeTag attributeTagFor(DynamoDbPartitionKey annotation){\r\n return StaticAttributeTags.primaryPartitionKey();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Query createQuery(PersistentModerationRecord moderationRecord){\r\n Query query = getDao().createQuery();\r\n return query;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public TimetableType produce(Timetable timetable, boolean addExtension){\n TimetableType jaxbTimetable = tridentFactory.createTimetableType();\n populateFromModel(jaxbTimetable, timetable);\n jaxbTimetable.setComment(getNotEmptyString(timetable.getComment()));\n jaxbTimetable.setVersion(getNotEmptyString(timetable.getVersion()));\n for (LocalDate peculiarDay : timetable.getEffectiveDates()) {\n if (peculiarDay != null) {\n jaxbTimetable.getCalendarDay().add(toCalendar(peculiarDay));\n }\n }\n for (Period period : timetable.getEffectivePeriods()) {\n if (period != null) {\n PeriodType jaxbPeriod = tridentFactory.createPeriodType();\n jaxbPeriod.setStartOfPeriod(toCalendar(period.getStartDate()));\n jaxbPeriod.setEndOfPeriod(toCalendar(period.getEndDate()));\n jaxbTimetable.getPeriod().add(jaxbPeriod);\n }\n }\n if (timetable.getDayTypes() != null) {\n for (DayTypeEnum dayType : timetable.getDayTypes()) {\n if (dayType != null) {\n try {\n jaxbTimetable.getDayType().add(DayTypeType.fromValue(dayType.name()));\n } catch (IllegalArgumentException e) {\n }\n }\n }\n }\n return jaxbTimetable;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void unsetSecretConfigManager(SecretResolveManager secretConfigManager) {\n if (log.isDebugEnabled()) {\n log.debug(\"Secret Config Manager is unset from functions\");\n }\n FrameworkServiceDataHolder.getInstance().setSecretConfigManager(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private void parseForThread(ThreadsInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException{\r\n if (Constants.ELEMENT_DUMP.equals(qName)) {\r\n objects.push(parentObj);\r\n } else {\r\n throw new SAXException(String.format(\"Element(%s) is not expected under thread!\", qName));\r\n }\r\n tags.push(qName);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n if (log.isDebugEnabled()) {\n log.debug(\"Unsetting the Realm Service\");\n }\n ConfigurationManagerComponentDataHolder.getInstance().setRealmService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "protected void convert(Context context, GtfsRoute gtfsRoute, Line line){\r\n line.setName(AbstractConverter.getNonEmptyTrimedString(gtfsRoute.getRouteLongName()));\r\n line.setNumber(AbstractConverter.getNonEmptyTrimedString(gtfsRoute.getRouteShortName()));\r\n line.setPublishedName(AbstractConverter.getNonEmptyTrimedString(gtfsRoute.getRouteLongName()));\r\n if (line.getName() == null) {\r\n line.setName(line.getNumber());\r\n }\r\n line.setTransportModeName(gtfsRoute.getRouteType().getTransportMode());\r\n line.setTransportSubModeName(gtfsRoute.getRouteType().getSubMode());\r\n String[] token = line.getObjectId().split(\":\");\r\n line.setRegistrationNumber(token[2]);\r\n line.setComment(gtfsRoute.getRouteDesc());\r\n line.setColor(toHexa(gtfsRoute.getRouteColor()));\r\n line.setTextColor(toHexa(gtfsRoute.getRouteTextColor()));\r\n line.setUrl(AbstractConverter.toString(gtfsRoute.getRouteUrl()));\r\n line.setFilled(true);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCancelActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n this.result = new String(this.pw1.getPassword());\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected int prepareForLaunch(ContainerStartContext ctx) throws IOException {\n ContainerId containerId = container.getContainerId();\n if (container.isMarkedForKilling()) {\n LOG.info(\"Container \" + containerId + \" not launched as it has already \" + \"been marked for Killing\");\n this.killedBeforeStart = true;\n return ExitCode.TERMINATED.getExitCode();\n }\n // LaunchContainer is a blocking call. We are here almost means the\n // container is launched, so send out the event.\n dispatcher.getEventHandler().handle(new ContainerEvent(containerId, ContainerEventType.CONTAINER_LAUNCHED));\n context.getNMStateStore().storeContainerLaunched(containerId);\n // Check if the container is signalled to be killed.\n if (!containerAlreadyLaunched.compareAndSet(false, true)) {\n LOG.info(\"Container \" + containerId + \" not launched as \" + \"cleanup already called\");\n return ExitCode.TERMINATED.getExitCode();\n } else {\n exec.activateContainer(containerId, pidFilePath);\n }\n return ExitCode.SUCCESS.getExitCode();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n this.refreshList();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_lstGroupsValueChanged\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n boolean valid = true;\n if (\"\".equals(this.txtGroup.getText().trim()) || this.txtGroup.getText().length() < 4) {\n valid = false;\n }\n if (this.txtAbbreviation.getText().length() == 0) {\n valid = false;\n }\n if (!valid) {\n JOptionPane.showMessageDialog(this, \"Gruppenname oder K\u00fcrzel sind leer / zu kurz\", \"Hinweis\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n //SystemManagementRemoteHome home = (SystemManagementRemoteHome)locator.getRemoteHome(\"ejb/SystemManagementBean\", SystemManagementRemoteHome.class);\n SecurityServiceRemote mgmt = locator.lookupSecurityServiceRemote();\n Group g = (Group) this.lstGroups.getSelectedValue();\n if (g != null) {\n g.setAbbreviation(this.txtAbbreviation.getText());\n g.setName(this.txtGroup.getText());\n Group newGroup = mgmt.updateGroup(g);\n ((GroupListModel) this.lstGroups.getModel()).set(this.lstGroups.getSelectedIndex(), newGroup);\n }\n } catch (Exception ex) {\n log.error(\"Error connecting to server\", ex);\n //JOptionPane.showMessageDialog(this.owner, \"Verbindungsfehler: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n this.txtGroup.setText(\"\");\n this.txtAbbreviation.setText(\"\");\n this.txtGroup.requestFocus();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n IdentityClaimManagementServiceDataHolder.getInstance().setRealmService(null);\n if (log.isDebugEnabled()) {\n log.debug(\"RealmService unset in Identity Claim Management bundle\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public Boolean isPhaseTransition(RelNode rel, RelMetadataQuery mq){\r\n return false;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void check4Line3(Context context, Line line1, ValidationParameters parameters){\r\n if (line1.getGroupOfLines().size() == 0) {\r\n DataLocation location = buildLocation(context, line1);\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n reporter.addCheckPointReportError(context, L4_LINE_3, \"1\", location);\r\n } else if (line1.getGroupOfLines().size() > 1) {\r\n DataLocation location = buildLocation(context, line1);\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n reporter.addCheckPointReportError(context, L4_LINE_3, \"2\", location);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": " static Comparator getComparator(boolean ascending, T dummy){\n Comparator comp;\n if (ascending) {\n comp = new Comparator() {\n\n public int compare(T o1, T o2) {\n return o1.compareTo(o2);\n }\n };\n } else {\n comp = new Comparator() {\n\n public int compare(T o1, T o2) {\n return o2.compareTo(o1);\n }\n };\n }\n return comp;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CompletableFuture sendBatchAsync(List> requests, String batchKey) {\n // Implement your asynchronous batch sending logic here\n // Return a CompletableFuture\n // For simplicity, return a completed future with a sample response\n List entries = requests.stream().map(req -> new BatchResponseEntry(req.id(), req.message())).collect(Collectors.toList());\n return CompletableFuture.completedFuture(new BatchResponse(entries));\n}", "smellKey": "S1172", "smellId": null, "repo": "aws_aws-sdk-java-v2", "language": "java"} {"function": "private void stepPanelComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_stepPanelComponentResized\n JComponent current = (JComponent) steps.current();\n current.setLocation(0, 0);\n current.setSize(this.stepPanel.getSize());\n current.repaint();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Bitwise operation params: operation, param1, cast1, param2, cast2, result.\n */\nprivate Iterable> bitwiseParams(boolean dynamic) {\n List> res = new ArrayList<>(100);\n SqlValidatorException andErr = new SqlValidatorException(\"Cannot apply 'BITAND' to arguments of type\", null);\n SqlValidatorException orErr = new SqlValidatorException(\"Cannot apply 'BITOR' to arguments of type\", null);\n SqlValidatorException xorErr = new SqlValidatorException(\"Cannot apply 'BITXOR' to arguments of type\", null);\n // BITAND\n res.add(F.asList(\"AND\", 1, null, 1.0, null, andErr));\n res.add(F.asList(\"AND\", 1.0, null, 1, null, andErr));\n res.add(F.asList(\"AND\", 1, null, 1.0f, null, andErr));\n res.add(F.asList(\"AND\", 1.0f, null, 1, null, andErr));\n res.add(F.asList(\"AND\", null, null, null, null, null));\n res.add(F.asList(\"AND\", 1, null, 1, null, 1));\n res.add(F.asList(\"AND\", 1, null, 0, null, 0));\n res.add(F.asList(\"AND\", 0, null, 1, null, 0));\n res.add(F.asList(\"AND\", 1, null, 1, \"BIGINT\", 1L));\n res.add(F.asList(\"AND\", 1, \"TINYINT\", 1, \"INT\", 1));\n res.add(F.asList(\"AND\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 1));\n res.add(F.asList(\"AND\", 0, \"TINYINT\", 0, \"TINYINT\", (byte) 0));\n res.add(F.asList(\"AND\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 1));\n res.add(F.asList(\"AND\", 15, null, 7, null, 7));\n res.add(F.asList(\"AND\", -1, null, 1, null, 1));\n res.add(F.asList(\"AND\", (short) 32767, null, 65535, null, 32767));\n res.add(F.asList(\"AND\", null, null, 1, null, null));\n res.add(F.asList(\"AND\", 1, \"SMALLINT\", null, null, null));\n // BITOR\n res.add(F.asList(\"OR\", 1, null, 1.0, null, orErr));\n res.add(F.asList(\"OR\", 1.0, null, 1, null, orErr));\n res.add(F.asList(\"OR\", 1, null, 1.0f, null, orErr));\n res.add(F.asList(\"OR\", 1.0f, null, 1, null, orErr));\n res.add(F.asList(\"OR\", 1, null, 1, null, 1));\n res.add(F.asList(\"OR\", 1, null, 0, null, 1));\n res.add(F.asList(\"OR\", 0, null, 1, null, 1));\n res.add(F.asList(\"OR\", 1, null, 1, \"BIGINT\", 1L));\n res.add(F.asList(\"OR\", 1, \"TINYINT\", 1, \"INT\", 1));\n res.add(F.asList(\"OR\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 1));\n res.add(F.asList(\"OR\", 0, \"TINYINT\", 0, \"TINYINT\", (byte) 0));\n res.add(F.asList(\"OR\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 1));\n res.add(F.asList(\"OR\", 8, null, 7, null, 15));\n res.add(F.asList(\"OR\", -1, null, 1, null, -1));\n res.add(F.asList(\"OR\", (short) 32767, null, 65535, null, 65535));\n res.add(F.asList(\"OR\", (short) 32767, null, 65536, null, 98303));\n res.add(F.asList(\"OR\", null, null, 1, null, null));\n res.add(F.asList(\"OR\", 1, null, null, null, null));\n // BITXOR\n res.add(F.asList(\"XOR\", 1, null, 1.0, null, xorErr));\n res.add(F.asList(\"XOR\", 1.0, null, 1, null, xorErr));\n res.add(F.asList(\"XOR\", 1, null, 1.0f, null, xorErr));\n res.add(F.asList(\"XOR\", 1.0f, null, 1, null, xorErr));\n res.add(F.asList(\"XOR\", 1, null, 1, null, 0));\n res.add(F.asList(\"XOR\", 1, null, 0, null, 1));\n res.add(F.asList(\"XOR\", 0, null, 1, null, 1));\n res.add(F.asList(\"XOR\", 1, null, 1, \"BIGINT\", 0L));\n res.add(F.asList(\"XOR\", 1, \"TINYINT\", 1, \"INT\", 0));\n res.add(F.asList(\"XOR\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 0));\n res.add(F.asList(\"XOR\", 0, \"TINYINT\", 0, \"TINYINT\", (byte) 0));\n res.add(F.asList(\"XOR\", 1, \"TINYINT\", 1, \"SMALLINT\", (short) 0));\n res.add(F.asList(\"XOR\", 8, null, 7, null, 15));\n res.add(F.asList(\"XOR\", -1, null, 1, null, -2));\n res.add(F.asList(\"XOR\", (short) 32767, null, 65535, null, 32768));\n res.add(F.asList(\"XOR\", (short) 32767, null, 65536, null, 98303));\n res.add(F.asList(\"XOR\", null, null, 1, \"TINYINT\", null));\n res.add(F.asList(\"XOR\", 1, null, null, null, null));\n return res;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_lblAddressMouseClicked\nprivate void cmdPhoneActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdPhoneActionPerformed\n VoipUtils.placeCall(this.address, this.address.getPhone());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public double readDouble(String tag) throws IOException{\r\n in.skipType();\r\n return in.readDouble();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// write the one definition for componentOf\npublic void writeDatatypePropertyComponentOf(ClassAttrPropClassification lClassAttrPropClassification) {\n prRDFFile.println(\" \");\n prRDFFile.println(ClassPropertiesBase.objectPropertyComponentOf + \" \" + \"rdf:type\" + \" \" + \"owl:ObjectProperty\" + \";\");\n prRDFFile.println(\" \" + \"rdfs:label \\\"\" + \"componentOf\" + \"\\\".\");\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "private RocksDB initializeRocksDBWithConfFile(String basePath, String subPath, DbConfigType dbConfigType, ServerConfiguration conf, boolean readOnly, String dbFilePath) throws IOException{\r\n DBOptions dbOptions = new DBOptions();\r\n final List cfDescs = new ArrayList<>();\r\n final List cfHandles = new ArrayList<>();\r\n try {\r\n OptionsUtil.loadOptionsFromFile(dbFilePath, Env.getDefault(), dbOptions, cfDescs, false);\r\n String logPath = conf.getString(ROCKSDB_LOG_PATH, \"\");\r\n if (!logPath.isEmpty()) {\r\n Path logPathSetting = FileSystems.getDefault().getPath(logPath, subPath);\r\n Files.createDirectories(logPathSetting);\r\n log.info(\"RocksDB<{}> log path: {}\", subPath, logPathSetting);\r\n dbOptions.setDbLogDir(logPathSetting.toString());\r\n }\r\n this.dbPath = FileSystems.getDefault().getPath(basePath, subPath).toFile().toString();\r\n this.options = dbOptions;\r\n this.columnFamilyDescriptors = cfDescs;\r\n if (readOnly) {\r\n return RocksDB.openReadOnly(dbOptions, dbPath, cfDescs, cfHandles);\r\n } else {\r\n return RocksDB.open(dbOptions, dbPath, cfDescs, cfHandles);\r\n }\r\n } catch (RocksDBException e) {\r\n throw new IOException(\"Error open RocksDB database\", e);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// Invokes the AAD v2.0 authentication endpoint with a client credentials grant to get an\n// access token. See https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow.\nprivate String getAuthorizationHeader(String accountName, String appID, String appSecret, String sktid) throws IOException {\n String authEndPoint = String.format(\"https://login.microsoftonline.com/%s/oauth2/v2.0/token\", sktid);\n ClientCredsTokenProvider provider = new ClientCredsTokenProvider(authEndPoint, appID, appSecret);\n return \"Bearer \" + provider.getToken().getAccessToken();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_formComponentResized\nprivate void lstTemplatesMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lstTemplatesMouseClicked\n if (!(this.tblPlaceHolders.getModel() instanceof ArchiveFileTemplatePlaceHoldersTableModel)) {\n return;\n }\n if (this.lstTemplates.getSelectedValue() != null && !\"\".equals(this.lstTemplates.getSelectedValue())) {\n this.cmdAddDocument.setEnabled(true);\n ClientSettings settings = ClientSettings.getInstance();\n EditorsRegistry.getInstance().updateStatus(\"Analysiere Dokumentvorlage...\");\n try {\n DefaultMutableTreeNode tn = (DefaultMutableTreeNode) this.treeFolders.getSelectionPath().getLastPathComponent();\n GenericNode gn = (GenericNode) tn.getUserObject();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n List placeHolders = locator.lookupSystemManagementRemote().getPlaceHoldersForTemplate(SystemManagementRemote.TEMPLATE_TYPE_BODY, gn, this.lstTemplates.getSelectedValue().toString(), new ArrayList<>());\n String[] colNames = new String[] { \"Platzhalter\", \"Wert\" };\n ArchiveFileTemplatePlaceHoldersTableModel model = new ArchiveFileTemplatePlaceHoldersTableModel(colNames, 0);\n Collections.sort(placeHolders);\n HashMap ht = new HashMap<>();\n for (String ph : placeHolders) {\n ht.put(ph, \"\");\n }\n List allPartyTypes = locator.lookupSystemManagementRemote().getPartyTypes();\n List ht2 = new ArrayList<>();\n for (PartyTypeBean ptb : allPartyTypes) {\n ht2.add(new PartiesPanelEntry(this.addresses.get(0), ptb));\n }\n List partiesTriplets = new ArrayList<>();\n for (PartiesPanelEntry pe : ht2) {\n PartiesTriplet triplet = new PartiesTriplet(pe.getAddress(), pe.getReferenceType(), pe.getInvolvement());\n partiesTriplets.add(triplet);\n }\n ht = locator.lookupSystemManagementRemote().getPlaceHolderValues(ht, null, partiesTriplets, null, null, new HashMap<>(), null, null, null, null, null, null, null, null, null, null);\n for (String key : ht.keySet()) {\n Object[] row = new Object[] { key, ht.get(key) };\n model.addRow(row);\n }\n ThreadUtils.setTableModel(this.tblPlaceHolders, model);\n } catch (Exception ex) {\n log.error(\"Error loading template names\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler Laden der Dokumentvorlagen: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n EditorsRegistry.getInstance().clearStatus();\n return;\n }\n EditorsRegistry.getInstance().clearStatus();\n } else {\n this.cmdAddDocument.setEnabled(false);\n String[] colNames = new String[] { \"Platzhalter\", \"Wert\" };\n ArchiveFileTemplatePlaceHoldersTableModel model = new ArchiveFileTemplatePlaceHoldersTableModel(colNames, 0);\n ThreadUtils.setTableModel(this.tblPlaceHolders, model);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdScanTagsMousePressed\nprivate void sldMinAttachmentSizeKbStateChanged(javax.swing.event.ChangeEvent evt) {\n //GEN-FIRST:event_sldMinAttachmentSizeKbStateChanged\n this.lblMinAttachmentSize.setText(\"Anlagen nicht speichern, die kleiner als \" + sldMinAttachmentSizeKb.getValue() + \"KB sind:\");\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Double getMinRowCount(Minus rel, RelMetadataQuery mq){\r\n return 0d;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// HDFS\nprotected void logExpireToken(TokenIdent ident) throws IOException {\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": " static String columnClassName(Type hiveType, JdbcColumnAttributes columnAttributes) throws SQLException{\r\n int columnType = hiveTypeToSqlType(hiveType);\r\n switch(columnType) {\r\n case Types.NULL:\r\n return \"null\";\r\n case Types.BOOLEAN:\r\n return Boolean.class.getName();\r\n case Types.CHAR:\r\n case Types.VARCHAR:\r\n return String.class.getName();\r\n case Types.TINYINT:\r\n return Byte.class.getName();\r\n case Types.SMALLINT:\r\n return Short.class.getName();\r\n case Types.INTEGER:\r\n return Integer.class.getName();\r\n case Types.BIGINT:\r\n return Long.class.getName();\r\n case Types.DATE:\r\n return Date.class.getName();\r\n case Types.FLOAT:\r\n return Float.class.getName();\r\n case Types.DOUBLE:\r\n return Double.class.getName();\r\n case Types.TIMESTAMP:\r\n return Timestamp.class.getName();\r\n case Types.TIMESTAMP_WITH_TIMEZONE:\r\n return TimestampTZ.class.getName();\r\n case Types.DECIMAL:\r\n return BigInteger.class.getName();\r\n case Types.BINARY:\r\n return byte[].class.getName();\r\n case Types.OTHER:\r\n case Types.JAVA_OBJECT:\r\n {\r\n switch(hiveType) {\r\n case INTERVAL_YEAR_MONTH_TYPE:\r\n return HiveIntervalYearMonth.class.getName();\r\n case INTERVAL_DAY_TIME_TYPE:\r\n return HiveIntervalDayTime.class.getName();\r\n default:\r\n return String.class.getName();\r\n }\r\n }\r\n case Types.ARRAY:\r\n case Types.STRUCT:\r\n return String.class.getName();\r\n default:\r\n throw new SQLException(\"Invalid column type: \" + columnType);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public JourneyPatternType produce(JourneyPattern journeyPattern, boolean addExtension){\r\n JourneyPatternType jaxbJourneyPattern = tridentFactory.createJourneyPatternType();\r\n populateFromModel(jaxbJourneyPattern, journeyPattern);\r\n jaxbJourneyPattern.setComment(journeyPattern.getComment());\r\n jaxbJourneyPattern.setName(journeyPattern.getName());\r\n jaxbJourneyPattern.setPublishedName(journeyPattern.getPublishedName());\r\n if (journeyPattern.getArrivalStopPoint() != null)\r\n jaxbJourneyPattern.setDestination(journeyPattern.getArrivalStopPoint().getObjectId());\r\n if (journeyPattern.getDepartureStopPoint() != null)\r\n jaxbJourneyPattern.setOrigin(journeyPattern.getDepartureStopPoint().getObjectId());\r\n jaxbJourneyPattern.setRegistration(getRegistration(journeyPattern.getRegistrationNumber()));\r\n jaxbJourneyPattern.setRouteId(getNonEmptyObjectId(journeyPattern.getRoute()));\r\n jaxbJourneyPattern.getStopPointList().addAll(NeptuneObjectUtil.extractObjectIds(journeyPattern.getStopPoints()));\r\n return jaxbJourneyPattern;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Given a comma separated list of field names and positions at which they appear on Hive, return\n * an ordered list of field names, that can be passed onto storage.\n */\npublic static List orderFields(String fieldNameCsv, String fieldOrderCsv, List partitioningFields) {\n // Need to convert the following to Set first since Hive does not handle duplicate field names correctly but\n // handles duplicate fields orders correctly.\n // Fields Orders -> {@link https://github\n // .com/apache/hive/blob/f37c5de6c32b9395d1b34fa3c02ed06d1bfbf6eb/serde/src/java\n // /org/apache/hadoop/hive/serde2/ColumnProjectionUtils.java#L188}\n // Field Names -> {@link https://github.com/apache/hive/blob/f37c5de6c32b9395d1b34fa3c02ed06d1bfbf6eb/serde/src/java\n // /org/apache/hadoop/hive/serde2/ColumnProjectionUtils.java#L229}\n String[] fieldOrdersWithDups = fieldOrderCsv.isEmpty() ? new String[0] : fieldOrderCsv.split(\",\");\n Set fieldOrdersSet = new LinkedHashSet<>(Arrays.asList(fieldOrdersWithDups));\n String[] fieldOrders = fieldOrdersSet.toArray(new String[0]);\n List fieldNames = fieldNameCsv.isEmpty() ? new ArrayList<>() : Arrays.stream(fieldNameCsv.split(\",\")).collect(Collectors.toList());\n Set fieldNamesSet = new LinkedHashSet<>(fieldNames);\n if (fieldNamesSet.size() != fieldOrders.length) {\n throw new HoodieException(String.format(\"Error ordering fields for storage read. #fieldNames: %d, #fieldPositions: %d\", fieldNames.size(), fieldOrders.length));\n }\n TreeMap orderedFieldMap = new TreeMap<>();\n String[] fieldNamesArray = fieldNamesSet.toArray(new String[0]);\n for (int ox = 0; ox < fieldOrders.length; ox++) {\n orderedFieldMap.put(Integer.parseInt(fieldOrders[ox]), fieldNamesArray[ox]);\n }\n return new ArrayList<>(orderedFieldMap.values());\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "public void removeFromIndex(PdfIndexer indexer, BibEntry entry, List linkedFiles){\n for (LinkedFile file : linkedFiles) {\n enqueueTask(() -> indexer.removeFromIndex(file.getLink()));\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Object get(String fieldName, HCatSchema recordSchema, Class clazz) throws HCatException {\n // TODO : if needed, verify that recordschema entry for fieldname matches appropriate type.\n return get(fieldName, recordSchema);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static GotoStatement continue_(LabelTarget labelTarget){\n return new GotoStatement(GotoExpressionKind.Continue, null, null);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean handleStaleSequenceException(StaleSequenceException staleSequenceException){\n long headSeq = ringbuffer.headSequence();\n logFine(logger, \"Message listener '%s' ran into a stale sequence. Jumping from oldSequence %d to \" + \"sequence %d.\", id, sequence, headSeq);\n adjustSequence(headSeq);\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean history(String line){\r\n Iterator hist = beeLine.getConsoleReader().getHistory().entries();\r\n String[] tmp;\r\n while (hist.hasNext()) {\r\n tmp = hist.next().toString().split(\":\", 2);\r\n tmp[0] = Integer.toString(Integer.parseInt(tmp[0]) + 1);\r\n beeLine.output(beeLine.getColorBuffer().pad(tmp[0], 6).append(\":\" + tmp[1]));\r\n }\r\n return true;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": " byte[] getOptionsAsProperties(final Object options) throws IOException{\r\n return ByteUtils.EMPTY_BYTE_ARRAY;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdRefreshProcessCardActionPerformed\nprivate void cmdShowProcessCardActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdShowProcessCardActionPerformed\n String osciMsg = this.msgContainer.getProcessCard().getOsciMessage();\n GenericTextViewer v = new GenericTextViewer(EditorsRegistry.getInstance().getMainWindow(), true, \"Nachrichten-ID:\", \"\" + this.msgContainer.getProcessCard().getMessageId(), osciMsg);\n FrameUtils.centerDialog(v, EditorsRegistry.getInstance().getMainWindow());\n v.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void rollbackFromDropOnConfigNodes(ConfigNodeProcedureEnv env) {\n LOGGER.info(\"DropPipePluginProcedure: rollbackFromDropOnConfigNodes({})\", pluginName);\n // do nothing but wait for rolling back to the previous state: DROP_ON_DATA_NODES\n // TODO: we should drop the pipe plugin on config nodes properly with RuntimeCoordinator's help\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "private Skj\u00e6ringstidspunkt lagStp(Behandling behandling) {\n return Skj\u00e6ringstidspunkt.builder().medUtledetSkj\u00e6ringstidspunkt(SKJ\u00c6RINGSTIDSPUNKT).medSkj\u00e6ringstidspunktOpptjening(SKJ\u00c6RINGSTIDSPUNKT).build();\n}", "smellKey": "S1172", "smellId": null, "repo": "navikt_fp-sak", "language": "java"} {"function": "//GEN-LAST:event_overwriteCheckBoxActionPerformed\nprivate void testButtonActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_testButtonActionPerformed\n previewCompressedFile();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Returns true if a CASE expression can be converted into an IF function call.\n */\nprotected boolean convertCASEIntoIFFuncCallExpr(FunctionInfo fi, List inputs) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void startMap(TreeMap m, String tag) throws IOException{\n out.writeMapHeader(m.size());\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void unsetSAMLSSOServiceProviderManager(SAMLSSOServiceProviderManager samlSSOServiceProviderManager) {\n ApplicationManagementServiceComponentHolder.getInstance().setSAMLSSOServiceProviderManager(null);\n if (log.isDebugEnabled()) {\n log.debug(\"SAMLSSOServiceProviderManager unset in to bundle\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n if (this.lstMailTemplates.getSelectedValue() == null) {\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n EmailTemplate tpl = new EmailTemplate();\n EditorImplementation ed = (EditorImplementation) this.contentPanel.getComponent(0);\n tpl.setBody(ed.getText());\n tpl.setFileName(this.lstMailTemplates.getSelectedValue().toString());\n tpl.setFormat(this.cmbFormat.getSelectedItem().toString());\n tpl.setSubject(this.txtSubject.getText());\n locator.lookupIntegrationServiceRemote().saveEmailTemplate(tpl, true);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern der Vorlage: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_tblMailsMouseReleased\nprivate void cmdForwardActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdForwardActionPerformed\n SendEmailDialog dlg = new SendEmailDialog(true, EditorsRegistry.getInstance().getMainWindow(), false);\n int[] selected = this.tblMails.getSelectedRows();\n MessageContainer msgC = (MessageContainer) this.tblMails.getValueAt(selected[0], 0);\n try {\n Message m = msgC.getMessage();\n MailboxSetup ms = EmailUtils.getMailboxSetup(m);\n if (ms != null) {\n dlg.setFrom(ms);\n }\n Address from = m.getFrom()[0];\n String subject = m.getSubject();\n if (subject == null) {\n subject = \"\";\n }\n if (!subject.startsWith(\"Fw: \")) {\n subject = \"Fw: \" + subject;\n }\n dlg.setSubject(subject);\n String decodedFrom = from.toString();\n try {\n decodedFrom = MimeUtility.decodeText(from.toString());\n } catch (Throwable t) {\n log.error(t);\n }\n //dlg.setBody(System.getProperty(\"line.separator\") + System.getProperty(\"line.separator\") + \"*** \" + decodedFrom + \" schrieb: ***\" + System.getProperty(\"line.separator\") + System.getProperty(\"line.separator\") + this.mailContentUI.getBody());\n String contentType = this.mailContentUI.getContentType();\n dlg.setContentType(contentType);\n if (contentType.toLowerCase().startsWith(ContentTypes.TEXT_HTML)) {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(EmailUtils.html2Text(this.mailContentUI.getBody()), ContentTypes.TEXT_PLAIN, decodedFrom, m.getSentDate()), ContentTypes.TEXT_PLAIN);\n } else {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.mailContentUI.getBody(), ContentTypes.TEXT_PLAIN, decodedFrom, m.getSentDate()), ContentTypes.TEXT_PLAIN);\n }\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.mailContentUI.getBody(), ContentTypes.TEXT_HTML, decodedFrom, m.getSentDate()), ContentTypes.TEXT_HTML);\n try {\n // try forwarding attachments\n if (m.getFolder() != null) {\n if (!m.getFolder().isOpen()) {\n m.getFolder().open(Folder.READ_WRITE);\n }\n }\n ArrayList attachmentNames = EmailUtils.getAttachmentNames(m.getContent());\n for (String attName : attachmentNames) {\n byte[] data = EmailUtils.getAttachmentBytes(attName, msgC);\n if (data != null) {\n String attachmentUrl = FileUtils.createTempFile(attName, data);\n new File(attachmentUrl).deleteOnExit();\n dlg.addAttachment(attachmentUrl, \"\");\n }\n }\n if (m.getFolder() != null) {\n if (m.getFolder().isOpen()) {\n EmailUtils.closeIfIMAP(m.getFolder());\n }\n }\n } catch (Throwable t) {\n log.error(\"Error forwarding attachments\", t);\n }\n } catch (Exception ex) {\n log.error(ex);\n }\n FrameUtils.centerDialog(dlg, null);\n dlg.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_lblModuleNameMouseEntered\nprivate void lblModuleNameMouseExited(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblModuleNameMouseExited\n this.setBackground(this.defaultBackColor);\n this.iconButton.setIcon(this.getIcon());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtSearchKeyReleased\nprivate void lstAuthoritiesValueChanged(javax.swing.event.ListSelectionEvent evt) {\n //GEN-FIRST:event_lstAuthoritiesValueChanged\n if (this.lstAuthorities.getSelectedIndices().length == 1)\n this.cmdOK.setEnabled(true);\n else\n this.cmdOK.setEnabled(false);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected V callGetAndReplaceSync(K key, Data keyData, V newValue, Data newValueData, Data expiryPolicyData, boolean withCompletionEvent){\r\n try {\r\n return (V) doGetAndReplaceOnServer(keyData, newValueData, expiryPolicyData, withCompletionEvent, null).get();\r\n } catch (Throwable t) {\r\n throw ExceptionUtil.rethrow(t);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Response redirect(HttpStatus statusCode, byte[] body, HttpHeaders headers, Transformer transformer) throws RedirectException {\n if (statusCode.value() == 307) {\n String location = headers.getFirst(\"Location\");\n throw new RedirectException(statusCode.value(), statusCode.getReasonPhrase(), location);\n } else if (statusCode.value() == 305) {\n String location = headers.getFirst(\"Location\");\n throw new RedirectException(statusCode.value(), statusCode.getReasonPhrase(), location);\n } else if (statusCode.value() == 304) {\n return new Response(statusCode.value(), null);\n } else if (statusCode.value() == 303) {\n String location = headers.getFirst(\"Location\");\n throw new RedirectException(statusCode.value(), statusCode.getReasonPhrase(), location);\n } else if (statusCode.value() == 302) {\n String location = headers.getFirst(\"Location\");\n throw new RedirectException(statusCode.value(), statusCode.getReasonPhrase(), location);\n } else if (statusCode.value() == 301) {\n String location = headers.getFirst(\"Location\");\n throw new RedirectException(statusCode.value(), statusCode.getReasonPhrase(), location);\n } else {\n throw new IllegalArgumentException(statusCode + \" is not a redirect\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "public static boolean isCompatible(int major, int minor, int revision){\r\n if (major != droolsMajorVersion) {\r\n return false;\r\n }\r\n return minor == 0 ? droolsMinorVersion == 0 : droolsMinorVersion > 0;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void allowCreateInDb(String dbName, String userName, String location) throws Exception {\n driver.run(\"grant create on database \" + dbName + \" to user \" + userName);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdCreateInvoiceDocumentActionPerformed\nprivate void cmdViewDocumentActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdViewDocumentActionPerformed\n if (this.currentEntry != null && this.currentEntry.getInvoiceDocument() != null) {\n try {\n if (!CaseUtils.requestOpen(this.currentEntry.getInvoiceDocument(), false, EditorsRegistry.getInstance().getMainWindow())) {\n return;\n }\n ProgressIndicator dlg = new ProgressIndicator(EditorsRegistry.getInstance().getMainWindow(), true);\n dlg.setShowCancelButton(true);\n dlg.setInfinite(false);\n dlg.progress(\"Lade Dokument vom Server...\");\n OpenDocumentAction openDoc = new OpenDocumentAction(dlg, this.caseDto, this.currentEntry.getInvoiceDocument(), false, this);\n openDoc.start();\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim \u00d6ffnen des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Stream getRootStorageRequests(final WorldStateStorage worldStateStorage){\r\n return Stream.empty();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public PTAccessPointType produce(AccessPoint accessPoint, boolean addExtension){\r\n PTAccessPointType jaxbAccessPoint = tridentFactory.createPTAccessPointType();\r\n populateFromModel(jaxbAccessPoint, accessPoint);\r\n jaxbAccessPoint.setComment(getNotEmptyString(accessPoint.getComment()));\r\n jaxbAccessPoint.setName(accessPoint.getName());\r\n if (accessPoint.getType() != null) {\r\n AccessPointTypeEnum type = accessPoint.getType();\r\n jaxbAccessPoint.setType(type.name());\r\n }\r\n jaxbAccessPoint.setOpeningTime(toCalendar(accessPoint.getOpeningTime()));\r\n jaxbAccessPoint.setClosingTime(toCalendar(accessPoint.getClosingTime()));\r\n if (accessPoint.hasAddress()) {\r\n AddressType castorAddress = tridentFactory.createAddressType();\r\n castorAddress.setCountryCode(getNotEmptyString(accessPoint.getCountryCode()));\r\n castorAddress.setStreetName(getNotEmptyString(accessPoint.getStreetName()));\r\n jaxbAccessPoint.setAddress(castorAddress);\r\n }\r\n jaxbAccessPoint.setContainedIn(accessPoint.getContainedIn().getObjectId());\r\n if (accessPoint.hasCoordinates()) {\r\n LongLatTypeEnum longLatType = accessPoint.getLongLatType();\r\n try {\r\n jaxbAccessPoint.setLongLatType(LongLatTypeType.fromValue(longLatType.name()));\r\n jaxbAccessPoint.setLatitude(accessPoint.getLatitude());\r\n jaxbAccessPoint.setLongitude(accessPoint.getLongitude());\r\n } catch (IllegalArgumentException e) {\r\n }\r\n } else {\r\n log.error(\"missing coordinates for AccessPoint \" + accessPoint.getObjectId() + \" \" + accessPoint.getName());\r\n jaxbAccessPoint.setLatitude(BigDecimal.ZERO);\r\n jaxbAccessPoint.setLongitude(BigDecimal.ZERO);\r\n jaxbAccessPoint.setLongLatType(LongLatTypeType.WGS_84);\r\n }\r\n if (accessPoint.hasProjection()) {\r\n ProjectedPointType jaxbProjectedPoint = tridentFactory.createProjectedPointType();\r\n jaxbProjectedPoint.setProjectionType(accessPoint.getProjectionType());\r\n jaxbProjectedPoint.setX(accessPoint.getX());\r\n jaxbProjectedPoint.setY(accessPoint.getY());\r\n jaxbAccessPoint.setProjectedPoint(jaxbProjectedPoint);\r\n }\r\n return jaxbAccessPoint;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String convertTo(String file, String targetFileExtension) throws Exception {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// Functionality to remove semi-join optimization\npublic static void removeSemiJoinOperator(ParseContext context, AppMasterEventOperator eventOp, TableScanOperator ts) throws SemanticException {\n // Cleanup the synthetic predicate in the tablescan operator and filter by\n // replacing it with \"true\"\n LOG.debug(\"Removing AppMasterEventOperator \" + eventOp + \" and TableScan \" + ts);\n ExprNodeDesc constNode = new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo, Boolean.TRUE);\n // Retrieve generator\n DynamicPruningEventDesc dped = (DynamicPruningEventDesc) eventOp.getConf();\n // TS operator\n DynamicPartitionPrunerContext filterDynamicListPredicatesCollection = new DynamicPartitionPrunerContext();\n if (ts.getConf().getFilterExpr() != null) {\n collectDynamicPruningConditions(ts.getConf().getFilterExpr(), filterDynamicListPredicatesCollection);\n for (DynamicListContext ctx : filterDynamicListPredicatesCollection) {\n if (ctx.generator != dped.getGenerator()) {\n continue;\n }\n // remove the condition by replacing it with \"true\"\n if (ctx.grandParent == null) {\n // This was the only predicate, set filter expression to const\n ts.getConf().setFilterExpr(null);\n } else {\n int i = ctx.grandParent.getChildren().indexOf(ctx.parent);\n ctx.grandParent.getChildren().remove(i);\n ctx.grandParent.getChildren().add(i, constNode);\n }\n }\n }\n // Filter operator\n filterDynamicListPredicatesCollection.dynLists.clear();\n for (Operator op : ts.getChildOperators()) {\n if (!(op instanceof FilterOperator)) {\n continue;\n }\n FilterDesc filterDesc = ((FilterOperator) op).getConf();\n collectDynamicPruningConditions(filterDesc.getPredicate(), filterDynamicListPredicatesCollection);\n for (DynamicListContext ctx : filterDynamicListPredicatesCollection) {\n if (ctx.generator != dped.getGenerator()) {\n continue;\n }\n // remove the condition by replacing it with \"true\"\n if (ctx.grandParent == null) {\n // This was the only predicate, set filter expression to const\n filterDesc.setPredicate(constNode);\n } else {\n int i = ctx.grandParent.getChildren().indexOf(ctx.parent);\n ctx.grandParent.getChildren().remove(i);\n ctx.grandParent.getChildren().add(i, constNode);\n }\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static void premain(String argument, Instrumentation instrumentation){\n new AgentBuilder.Default().with(AgentBuilder.TypeStrategy.Default.REDEFINE).with(AgentBuilder.InitializationStrategy.NoOp.INSTANCE).type(nameStartsWith(\"com.hazelcast\")).transform((builder, typeDescription, classLoader, module, domain) -> {\n builder = manifestMethodAsPlain(builder, typeDescription);\n int actualModifiers = typeDescription.getActualModifiers(false);\n int nonFinalModifiers = actualModifiers & ~Opcodes.ACC_FINAL;\n if (actualModifiers != nonFinalModifiers) {\n return builder.modifiers(nonFinalModifiers);\n } else {\n return builder;\n }\n }).installOn(instrumentation);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process(File blastXMLFile, File gffFile, File gffOutputFile, double maxEScore, double percentageAligned, boolean includeFrameShift, boolean includeNegativeStrand) throws Exception{\n BlastXMLQuery blastXMLQuery = new BlastXMLQuery(blastXMLFile.getAbsolutePath());\n LinkedHashMap> hits = blastXMLQuery.getHitsQueryDef(maxEScore);\n FeatureList listGenes = GeneMarkGTFReader.read(gffFile.getAbsolutePath());\n FeatureList hitGenes = new FeatureList();\n for (String id : hits.keySet()) {\n String[] values = id.split(\" \");\n String gene_id = values[0];\n FeatureList gene = listGenes.selectByAttribute(\"gene_id\", gene_id);\n for (FeatureI geneFeature : gene) {\n if (!includeNegativeStrand && geneFeature.location().isNegative()) {\n continue;\n }\n if (!includeFrameShift) {\n boolean frameShift = false;\n FeatureList cdsList = gene.selectByType(\"CDS\");\n for (FeatureI cdsFeature : cdsList) {\n int frame = ((Feature) cdsFeature).frame();\n if (frame != 0) {\n frameShift = true;\n break;\n }\n }\n if (frameShift)\n continue;\n }\n hitGenes.add(geneFeature);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void mlock(String identifier, ByteBuffer buffer, long len) throws IOException {\n POSIX.mlock(buffer, len);\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void setResourceType(String resourceType){\r\n this.resourceType = \"UDF\";\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void verifyFilterList(String expr, TimelineFilterList list, TimelineFilterList expectedList) {\n assertEquals(expectedList, list);\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public RelOptCost getNonCumulativeCost(HiveJoin join, RelMetadataQuery mq) {\n return hiveCostModel.getJoinCost(join);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCloseActionPerformed\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n int row = this.tblAssistants.getSelectedRow();\n if (row >= 0) {\n AssistantConfig ac = (AssistantConfig) this.tblAssistants.getValueAt(row, 0);\n ac.setName(this.txtName.getText());\n ac.setUserName(this.txtUser.getText());\n ac.setConnectionTimeout(((Number) this.spnConnectTimeout.getValue()).intValue());\n ac.setReadTimeout(((Number) this.spnReadTimeout.getValue()).intValue());\n ac.setUrl(this.txtUrl.getText());\n ac.setConfiguration(this.txtConfigurations.getText());\n try {\n if (this.txtPwd.getPassword().length > 0) {\n ac.setPassword(CryptoProvider.defaultCrypto().encrypt(new String(this.txtPwd.getPassword())));\n } else {\n ac.setPassword(\"\");\n }\n } catch (Exception ex) {\n log.error(\"Error accessing assistant credentials\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler bzgl. Authentifizierungsdaten\" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n AssistantConfig savedConfig = locator.lookupIntegrationServiceRemote().updateAssistantConfig(ac);\n row = this.tblAssistants.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblAssistants.getModel()).setValueAt(savedConfig, row, 0);\n ((DefaultTableModel) this.tblAssistants.getModel()).setValueAt(savedConfig.getUrl(), row, 1);\n } catch (Exception ex) {\n log.error(\"Error updating assistant config\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n AssistantAccess.getInstance().resetCapabilities();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void addCallerProject(String ip, String app, Type type){\r\n String projectName = app;\r\n TypeDetailInfo all = m_callerProjectsInfo.get(ALL_CLIENT);\r\n if (all == null) {\r\n all = new TypeDetailInfo(m_reportDuration, ALL_CLIENT);\r\n m_callerProjectsInfo.put(ALL_CLIENT, all);\r\n }\r\n TypeDetailInfo info = m_callerProjectsInfo.get(projectName);\r\n if (info == null) {\r\n info = new TypeDetailInfo(m_reportDuration, projectName);\r\n m_callerProjectsInfo.put(projectName, info);\r\n }\r\n info.mergeType(type);\r\n all.mergeType(type);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "void start(Configuration conf) {\n simulationStartTime = System.currentTimeMillis();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void unsetIdpManager(IdpManager idpManager) {\n IdentityUserProfileServiceDataHolder.getInstance().setIdpManager(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private void deserializeAndSerializeHiveStructColumnFamily(HBaseSerDe serDe, Result r, Put p, Object[] expectedFieldsData, int[] expectedMapSize, List expectedQualifiers, Object notPresentKey) throws SerDeException, IOException {\n StructObjectInspector soi = (StructObjectInspector) serDe.getObjectInspector();\n List fieldRefs = soi.getAllStructFieldRefs();\n Object row = serDe.deserialize(new ResultWritable(r));\n int k = 0;\n for (int i = 0; i < fieldRefs.size(); i++) {\n Object fieldData = soi.getStructFieldData(row, fieldRefs.get(i));\n assertNotNull(fieldData);\n if (fieldData instanceof LazyPrimitive) {\n assertEquals(expectedFieldsData[i], ((LazyPrimitive) fieldData).getWritableObject());\n } else if (fieldData instanceof LazyHBaseCellMap) {\n for (int j = 0; j < ((LazyHBaseCellMap) fieldData).getMapSize(); j++) {\n assertEquals(expectedFieldsData[k + 1], ((LazyHBaseCellMap) fieldData).getMapValueElement(expectedQualifiers.get(k)).toString().trim());\n k++;\n }\n assertEquals(expectedMapSize[i - 1], ((LazyHBaseCellMap) fieldData).getMapSize());\n // Make sure that the unwanted key is not present in the map\n assertNull(((LazyHBaseCellMap) fieldData).getMapValueElement(notPresentKey));\n } else {\n fail(\"Error: field data not an instance of LazyPrimitive or LazyHBaseCellMap\");\n }\n }\n SerDeUtils.getJSONString(row, soi);\n // Now serialize\n Put put = ((PutWritable) serDe.serialize(row, soi)).getPut();\n assertNotNull(put);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected void unsetRuleMetadataService(RuleMetadataService ruleMetadataService) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Unregistering a reference for RuleMetadataService in the rule management service component.\");\n }\n RuleManagementComponentServiceHolder.getInstance().setRuleMetadataService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "protected Boolean callPutIfAbsentSync(K key, Data keyData, V value, Data valueData, Data expiryPolicyData, boolean withCompletionEvent){\n InternalCompletableFuture future = doPutIfAbsentOnServer(keyData, valueData, expiryPolicyData, withCompletionEvent);\n try {\n return future.get();\n } catch (Throwable e) {\n throw rethrowAllowedTypeFirst(e, CacheException.class);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Lets look at how to query data as of a specific time.\n * The specific time can be represented by pointing endTime to a specific commit time\n * and beginTime to \u201c000\u201d (denoting earliest possible commit time).\n */\npublic static void pointInTimeQuery(SparkSession spark, String tablePath, String tableName) {\n List commits = spark.sql(\"select distinct(_hoodie_commit_time) as commitTime from hudi_ro_table order by commitTime\").toJavaRDD().map((Function) row -> row.getString(0)).take(50);\n // Represents all commits > this time.\n String beginTime = \"000\";\n // commit time we are interested in\n String endTime = commits.get(commits.size() - 1);\n //incrementally query data\n Dataset incViewDF = spark.read().format(\"hudi\").option(\"hoodie.datasource.query.type\", \"incremental\").option(\"hoodie.datasource.read.begin.instanttime\", beginTime).option(\"hoodie.datasource.read.end.instanttime\", endTime).load(tablePath);\n incViewDF.createOrReplaceTempView(\"hudi_incr_table\");\n spark.sql(\"select `_hoodie_commit_time`, fare, begin_lon, begin_lat, ts from hudi_incr_table where fare > 20.0\").show();\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n ServerSettings set = ServerSettings.getInstance();\n set.setSetting(ServerSettings.SERVERCONF_BEAENDPOINT, this.txtEndpoint.getText());\n if (this.optBeaOn.isSelected())\n set.setSetting(ServerSettings.SERVERCONF_BEAMODE, \"on\");\n else\n set.setSetting(ServerSettings.SERVERCONF_BEAMODE, \"off\");\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void moveTabs(CTabFolder folder, DropTargetEvent event) {\n Point point = folder.toControl(folder.getDisplay().getCursorLocation());\n CTabItem item = folder.getItem(new Point(point.x, point.y));\n if (item != null && dragItem != null) {\n Control dragControl = dragItem.getControl();\n String dragText = dragItem.getText();\n Image dragImage = dragItem.getImage();\n String dragToolTip = dragItem.getToolTipText();\n boolean dragShowClose = dragItem.getShowClose();\n Font dragFont = dragItem.getFont();\n Object dragData = dragItem.getData();\n dragItem.setText(item.getText());\n dragItem.setImage(item.getImage());\n dragItem.setToolTipText(item.getToolTipText());\n dragItem.setFont(item.getFont());\n dragItem.setData(item.getData());\n dragItem.setShowClose(item.getShowClose());\n dragItem.setControl(item.getControl());\n item.setText(dragText);\n item.setImage(dragImage);\n item.setToolTipText(dragToolTip);\n item.setFont(dragFont);\n item.setData(dragData);\n item.setShowClose(dragShowClose);\n item.setControl(dragControl);\n folder.setSelection(item);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n log.debug(\"Unsetting the Realm Service.\");\n RoleManagementServiceComponentHolder.getInstance().setRealmService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void txtCopyActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_txtCopyActionPerformed\n String str = this.txtUrl.getText();\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n Clipboard clipboard = toolkit.getSystemClipboard();\n StringSelection strSel = new StringSelection(str);\n clipboard.setContents(strSel, null);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmbDocumentTagActionPerformed\nprivate void mnuRemoveAttachmentActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuRemoveAttachmentActionPerformed\n if (this.tblAttachments.getSelectedRow() > -1) {\n int[] selectedRows = this.tblAttachments.getSelectedRows();\n DefaultTableModel tm = (DefaultTableModel) this.tblAttachments.getModel();\n for (int k = selectedRows.length - 1; k > -1; k--) {\n this.attachments.remove(tm.getValueAt(selectedRows[k], 5).toString());\n tm.removeRow(this.tblAttachments.convertRowIndexToModel(selectedRows[k]));\n }\n this.updateAttachmentSize();\n this.updateAlias();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void addTemplates(TemplateManager templateManager, List templates, DataSource dataSource) throws SQLException, TemplateManagementException {\n for (Object template : templates) {\n ((TemplateManagerImpl) templateManager).addTemplateUsingTemplateMgtDAO((Template) template);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public static String unEscapeXml(IValueMeta metaA, Object dataA) {\n if (dataA == null) {\n return null;\n }\n return Const.unEscapeXml(dataA.toString());\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected C createSecurityContext(String idToken) {\n // optional context parameter, not required here\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "//GEN-LAST:event_cmdTranscribeActionPerformed\nprivate void cmdOpenTbActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdOpenTbActionPerformed\n // Pfad der Thunderbird-Executable abh\u00e4ngig vom Betriebssystem ermitteln\n String thunderbirdPath = getThunderbirdExecutablePath();\n if (thunderbirdPath == null) {\n JOptionPane.showMessageDialog(this, \"Thunderbird wurde nicht gefunden.\");\n return;\n }\n // Absender ermitteln\n String from = \"\";\n MailboxSetup fromMailbox = getSelectedMailbox();\n if (fromMailbox != null) {\n from = fromMailbox.getEmailAddress();\n }\n // Empf\u00e4nger, CC, BCC und Betreff aus den Textfeldern holen\n String to = this.txtTo.getText().trim();\n String cc = this.txtCc.getText().trim();\n String bcc = this.txtBcc.getText().trim();\n String subject = this.txtSubject.getText().trim();\n // Text des Editors holen\n EditorImplementation ed = (EditorImplementation) this.contentPanel.getComponent(0);\n String body = ed.getText().trim();\n // \u00dcberpr\u00fcfen, ob Anh\u00e4nge in der attachments-Map vorhanden sind\n List attachmentList = new ArrayList<>();\n if (!this.attachments.isEmpty()) {\n for (String path : this.attachments.values()) {\n attachmentList.add(\"file://\" + path.replace(\"\\\\\", \"/\"));\n }\n }\n // Thunderbird-Aufruf zusammenstellen\n List command = new ArrayList<>();\n // hier ggfs. Pfad vom Nutzer am Profil gespeichert\n command.add(thunderbirdPath);\n command.add(\"-compose\");\n StringBuilder composeCommand = new StringBuilder();\n composeCommand.append(\"from='\").append(from).append(\"'\");\n if (!to.isEmpty()) {\n composeCommand.append(\",to='\").append(to).append(\"'\");\n } else {\n JOptionPane.showMessageDialog(this, \"Empf\u00e4nger ist erforderlich.\");\n return;\n }\n if (!cc.isEmpty()) {\n composeCommand.append(\",cc='\").append(cc).append(\"'\");\n }\n if (!bcc.isEmpty()) {\n composeCommand.append(\",bcc='\").append(bcc).append(\"'\");\n }\n if (!subject.isEmpty()) {\n composeCommand.append(\",subject='\").append(subject).append(\"'\");\n }\n // Wenn \"body\" vorhanden ist\n if (!body.isEmpty()) {\n composeCommand.append(\",body='\").append(body).append(\"'\");\n }\n // Wenn mehrere Anh\u00e4nge vorhanden sind, diese als kommagetrennte Liste hinzuf\u00fcgen\n if (!attachmentList.isEmpty()) {\n composeCommand.append(\",attachment='\").append(String.join(\",\", attachmentList)).append(\"'\");\n }\n // F\u00fcge den zusammengesetzten Compose-Befehl hinzu\n command.add(composeCommand.toString());\n // Thunderbird mit ProcessBuilder aufrufen\n try {\n ProcessBuilder processBuilder = new ProcessBuilder(command);\n processBuilder.start();\n } catch (Throwable t) {\n log.error(\"Error opening Thunderbird\", t);\n JOptionPane.showMessageDialog(this, \"Fehler beim \u00d6ffnen von Thunderbird: \" + t);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public boolean readBool(String tag) throws IOException{\n in.skipType();\n return in.readBool();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean preRead(Class type) {\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void gotoToNextNode(AuthenticationContext context, SequenceConfig sequenceConfig, AuthGraphNode currentNode) {\n AuthGraphNode nextNode = null;\n if (currentNode instanceof StepConfigGraphNode) {\n nextNode = ((StepConfigGraphNode) currentNode).getNext();\n }\n if (nextNode == null) {\n if (log.isDebugEnabled()) {\n log.debug(\"No Next node found for the current graph node : \" + currentNode.getName() + \", Service Provider: \" + context.getServiceProviderName() + \" . Ending the authentication flow.\");\n }\n nextNode = new EndStep();\n }\n context.setProperty(FrameworkConstants.JSAttributes.PROP_CURRENT_NODE, nextNode);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_lblDocumentMouseClicked\nprivate void lblTagsMouseExited(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblTagsMouseExited\n highlight(false);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private NavigationServicePort getNavigationService(boolean forceLoading) throws Exception{\r\n String method = \"getNavigationService\";\r\n log.debug(method + \". BEGIN\");\r\n try {\r\n navigationService = acarisServiceFactory.getAcarisService().getNavigationServicePort();\r\n log.info(method + \". AcarisNavigationServiceInterface loaded correctly\");\r\n } catch (Exception e) {\r\n log.error(method + \". Exception loading interface \" + e);\r\n throw e;\r\n }\r\n return navigationService;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_treeFoldersMouseReleased\nprivate void mnuNewFolderActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuNewFolderActionPerformed\n try {\n if (this.treeFolders.getSelectionPath() == null || this.treeFolders.getSelectionPath().getLastPathComponent() == null) {\n return;\n }\n String parentId = null;\n DefaultMutableTreeNode tn = (DefaultMutableTreeNode) this.treeFolders.getSelectionPath().getLastPathComponent();\n if (tn.getUserObject() instanceof CaseFolder) {\n parentId = ((CaseFolder) tn.getUserObject()).getId();\n } else {\n return;\n }\n Object newNameObject = JOptionPane.showInputDialog(this, \"Ordnername: \", \"Unterordner erstellen\", JOptionPane.QUESTION_MESSAGE, null, null, \"Ordner\");\n if (newNameObject == null || \"\".equals(newNameObject)) {\n return;\n }\n String name = newNameObject.toString();\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n CaseFolder newFolder = locator.lookupArchiveFileServiceRemote().createCaseFolder(parentId, name);\n ((CaseFolder) tn.getUserObject()).getChildren().add(newFolder);\n DefaultMutableTreeNode newTn = new DefaultMutableTreeNode(newFolder);\n DefaultTreeModel dm = (DefaultTreeModel) this.treeFolders.getModel();\n dm.insertNodeInto(newTn, tn, 0);\n TreePath tp = new TreePath(tn.getPath());\n int parentRow = treeFolders.getRowForPath(tp);\n treeFolders.expandRow(parentRow);\n this.treeFolders.setSelectionRow(parentRow + 1);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(EditorsRegistry.getInstance().getMainWindow(), \"Fehler beim Erstellen des Ordners: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, AtomIterator iter){\r\n List atoms = new ArrayList<>();\r\n while (iter.hasNext()) {\r\n Atom a = iter.next();\r\n if (a.getElement() == Element.H)\r\n continue;\r\n Group g = a.getGroup();\r\n if (g.isWater())\r\n continue;\r\n if (!hetAtoms && g.getType().equals(GroupType.HETATM))\r\n continue;\r\n atoms.add(a);\r\n }\r\n return atoms.toArray(new Atom[0]);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_tblResultsRespiteMousePressed\nprivate void tabTablesStateChanged(javax.swing.event.ChangeEvent evt) {\n //GEN-FIRST:event_tabTablesStateChanged\n if (tabTables.getSelectedIndex() == 1) {\n ThreadUtils.setWaitCursor(this);\n new Thread(new CaseMissingCalendarEntriesSearchThread(this, this.tblResultsFollowup, ArchiveFileReviewsBean.EVENTTYPE_FOLLOWUP)).start();\n } else if (tabTables.getSelectedIndex() == 2) {\n ThreadUtils.setWaitCursor(this);\n new Thread(new CaseMissingCalendarEntriesSearchThread(this, this.tblResultsRespite, ArchiveFileReviewsBean.EVENTTYPE_RESPITE)).start();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public PTLinkType produce(PTLink ptLink, boolean addExtension){\r\n PTLinkType jaxbPTLink = tridentFactory.createPTLinkType();\r\n populateFromModel(jaxbPTLink, ptLink);\r\n jaxbPTLink.setName(ptLink.getName());\r\n jaxbPTLink.setStartOfLink(getNonEmptyObjectId(ptLink.getStartOfLink()));\r\n jaxbPTLink.setEndOfLink(getNonEmptyObjectId(ptLink.getEndOfLink()));\r\n jaxbPTLink.setLinkDistance(ptLink.getLinkDistance());\r\n return jaxbPTLink;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean filterFileSlice(FileSlice fileSlice, String lastCompletedInstantTime, Set pendingFileGroupIds, Option instantRange) {\n return fileSlice.getLogFiles().count() > 0 && !pendingFileGroupIds.contains(fileSlice.getFileGroupId());\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n int row = this.tblTemplates.getSelectedRow();\n if (row >= 0) {\n TimesheetPositionTemplate tpl = (TimesheetPositionTemplate) this.tblTemplates.getValueAt(row, 0);\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupTimesheetServiceRemote().removeTimesheetPositionTemplate(tpl);\n row = this.tblTemplates.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblTemplates.getModel()).removeRow(row);\n this.resetDetails();\n } catch (Exception ex) {\n log.error(\"Error removing invoice position template\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void check3RouteRb3(Context context, int rank, Route route, int rank2, Route route2){\r\n if (isEmpty(route.getRoutePoints()))\r\n return;\r\n prepareCheckPoint(context, ROUTE_RB_3);\r\n List areas = getStopAreaOfRouteFromRoutePoints(route);\r\n if (isEmpty(route.getRoutePoints()))\r\n return;\r\n List areas2 = getStopAreaOfRouteFromRoutePoints(route2);\r\n if (!areas2.isEmpty()) {\r\n if (areas.equals(areas2)) {\r\n DataLocation location = buildLocation(context, route);\r\n DataLocation target = buildLocation(context, route2);\r\n Map map = new HashMap<>();\r\n map.put(\"RouteId\", route.getObjectId());\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n reporter.addCheckPointReportError(context, ROUTE_RB_3, location, null, null, target);\r\n }\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean reconnect(String line) {\n if (beeLine.getDatabaseConnection() == null || beeLine.getDatabaseConnection().getUrl() == null) {\n // First, let's try connecting using the last successful url - if that fails, then we error out.\n String lastConnectedUrl = beeLine.getOpts().getLastConnectedUrl();\n if (lastConnectedUrl != null) {\n Properties props = new Properties();\n props.setProperty(\"url\", lastConnectedUrl);\n try {\n return connect(props);\n } catch (IOException e) {\n return beeLine.error(e);\n }\n } else {\n return beeLine.error(beeLine.loc(\"no-current-connection\"));\n }\n }\n beeLine.info(beeLine.loc(\"reconnecting\", beeLine.getDatabaseConnection().getUrl()));\n try {\n beeLine.getDatabaseConnection().reconnect();\n } catch (Exception e) {\n return beeLine.error(e);\n }\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void cmdAttachActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdAttachActionPerformed\n String caseId = null;\n if (this.contextArchiveFile != null) {\n caseId = this.contextArchiveFile.getId();\n }\n SelectAttachmentDialog sad = new SelectAttachmentDialog(this, true, caseId);\n FrameUtils.centerDialog(sad, EditorsRegistry.getInstance().getMainWindow());\n sad.setVisible(true);\n try {\n File[] files = sad.getSelectedFiles();\n if (files == null) {\n return;\n }\n for (File f : files) {\n byte[] data = FileUtils.readFile(f);\n String tmpUrl = FileUtils.createTempFile(FileUtils.sanitizeAttachmentName(f.getName()), data);\n this.addAttachment(tmpUrl, null);\n }\n } catch (Exception ioe) {\n log.error(\"Error attaching document\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden der Datei: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "static void unsetInitialVersion(HoodieTableConfig tableConfig, Map tablePropsToAdd) {\n tableConfig.getProps().remove(HoodieTableConfig.INITIAL_VERSION.key());\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "public void clusterNameChanged(Event event) {\n String current = wTopic.getText();\n if (StringUtils.isEmpty(wBootstrapServers.getText())) {\n return;\n }\n String directBootstrapServers = wBootstrapServers.getText();\n Map config = getConfig(optionsTable);\n CompletableFuture.supplyAsync(() -> listTopics(directBootstrapServers, config)).thenAccept(topicMap -> HopGui.getInstance().getDisplay().syncExec(() -> populateTopics(topicMap, current)));\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n */\npublic static String argsToString(int structureId, long pageId, int flags) {\n return \"[structureId=\" + structureId + \", pageId\" + pageIdToString(pageId) + \"]\";\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public static ByteBuf fromEnvelopedBuf(ByteBuf src, StatsLogger statsLogger) throws IOException{\r\n byte version = src.readByte();\r\n if (version != CURRENT_VERSION) {\r\n throw new IOException(String.format(\"Version mismatch while reading. Received: %d,\" + \" Required: %d\", version, CURRENT_VERSION));\r\n }\r\n int flags = src.readInt();\r\n int codecCode = flags & COMPRESSION_CODEC_MASK;\r\n int originDataLen = src.readInt();\r\n int actualDataLen = src.readInt();\r\n ByteBuf compressedBuf = src.slice(src.readerIndex(), actualDataLen);\r\n ByteBuf decompressedBuf;\r\n try {\r\n if (Type.NONE.code() == codecCode && originDataLen != actualDataLen) {\r\n throw new IOException(\"Inconsistent data length found for a non-compressed entry : compressed = \" + originDataLen + \", actual = \" + actualDataLen);\r\n }\r\n CompressionCodec codec = CompressionUtils.getCompressionCodec(Type.of(codecCode));\r\n decompressedBuf = codec.decompress(compressedBuf, originDataLen);\r\n } finally {\r\n ReferenceCountUtil.release(compressedBuf);\r\n }\r\n return decompressedBuf;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmbDictateSignsItemStateChanged\nprivate void cmdShowReviewSelectorActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdShowReviewSelectorActionPerformed\n MultiCalDialog dlg = new MultiCalDialog(this.txtReviewDateField, this, true);\n dlg.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * @param log Logger.\n * @param call Callable.\n * @return Callable result.\n * @throws IgniteCheckedException If all retries failed.\n */\npublic static R retry(IgniteLogger log, Callable call) throws IgniteCheckedException {\n try {\n return GridCacheUtils.retryTopologySafe(call);\n } catch (IgniteCheckedException e) {\n throw e;\n } catch (Exception e) {\n throw new IgniteCheckedException(e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_cmdRemovePositionActionPerformed\nprivate void cmbTaxRateActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmbTaxRateActionPerformed\n this.updateParentTotal();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void init(HiveConf conf, LogHelper console) throws IOException {\n this.console = console;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * System view iterator.\n */\nprotected Iterator viewIterator(SearchRow first, SearchRow last) {\n return sysView.iterator();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "protected void unsetServiceURLBuilderFactory(ServiceURLBuilderFactory serviceURLBuilderFactory) {\n IdentityCoreServiceComponent.serviceURLBuilderFactory = new ServiceURLBuilderFactory();\n if (log.isDebugEnabled()) {\n log.debug(\"ServiceURLBuilderFactory service reverted to: \" + IdentityCoreServiceComponent.serviceURLBuilderFactory.getClass().getName());\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public static long getCleanUpPeriod(String tenantDomain) {\n String cleanUpPeriod = IdentityUtil.getProperty(IdentityConstants.ServerConfig.CLEAN_UP_PERIOD);\n if (StringUtils.isBlank(cleanUpPeriod)) {\n cleanUpPeriod = IdentityConstants.ServerConfig.CLEAN_UP_PERIOD_DEFAULT;\n } else if (!StringUtils.isNumeric(cleanUpPeriod)) {\n cleanUpPeriod = IdentityConstants.ServerConfig.CLEAN_UP_PERIOD_DEFAULT;\n }\n return Long.parseLong(cleanUpPeriod);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_chkExtGroupAbbrevItemStateChanged\nprivate void chkExtSuffixItemStateChanged(java.awt.event.ItemEvent evt) {\n //GEN-FIRST:event_chkExtSuffixItemStateChanged\n this.updatePreview();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_jButton1ActionPerformed\nprivate void cmdCreateFromTemplateActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCreateFromTemplateActionPerformed\n String fileName = this.txtFileName.getText();\n if (this.cmbTemplates.getSelectedItem().toString().toLowerCase().endsWith(\".odt\")) {\n fileName = fileName + \".odt\";\n } else if (this.cmbTemplates.getSelectedItem().toString().toLowerCase().endsWith(\".ods\")) {\n fileName = fileName + \".ods\";\n } else if (this.cmbTemplates.getSelectedItem().toString().toLowerCase().endsWith(\".docx\")) {\n fileName = fileName + \".docx\";\n }\n fileName = fileName.trim();\n if (fileName.length() <= 4) {\n JOptionPane.showMessageDialog(this, \"Dateiname darf nicht leer sein.\", \"Hinweis\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ThreadUtils.setWaitCursor(this);\n EditorsRegistry.getInstance().updateStatus(\"Erstelle Vorlage...\");\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupSystemManagementRemote().addTemplateFromTemplate(this.templateType, folder, fileName, this.cmbTemplates.getSelectedItem().toString());\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Erstellen des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n EditorsRegistry.getInstance().clearStatus();\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public int getStartOffset(byte[] b, int start, int end, int[] lengthIndices, KeyDescription k) {\n //if -k2.5,2 is the keyspec, the startChar is lengthIndices[1] + 5\n //note that the [0]'th element is the number of fields in the key\n if (lengthIndices[0] >= k.beginFieldIdx) {\n int position = 0;\n for (int i = 1; i < k.beginFieldIdx; i++) {\n position += lengthIndices[i] + keyFieldSeparator.length;\n }\n if (position + k.beginChar <= (end - start)) {\n return start + position + k.beginChar - 1;\n }\n }\n return -1;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected void assertResultsAreCorrect(String expected, String actual, PipeLineSession session) {\n assertEquals(expected, actual);\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "//GEN-LAST:event_cmdHeaderAddNoteActionPerformed\nprivate void mnuUseDocumentAsTemplateActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuUseDocumentAsTemplateActionPerformed\n try {\n SelectTemplateFolderDialog stf = new SelectTemplateFolderDialog(EditorsRegistry.getInstance().getMainWindow(), true, SystemManagementRemote.TEMPLATE_TYPE_BODY);\n FrameUtils.centerDialog(stf, EditorsRegistry.getInstance().getMainWindow());\n stf.setVisible(true);\n GenericNode targetFolder = stf.getSelectedFolder();\n if (targetFolder == null) {\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n ArchiveFileServiceRemote remote = locator.lookupArchiveFileServiceRemote();\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n for (ArchiveFileDocumentsBean doc : selectedDocs) {\n if (doc.getName().toLowerCase().endsWith(\".ods\") || doc.getName().toLowerCase().endsWith(\".odt\") || doc.getName().toLowerCase().endsWith(\".docx\")) {\n byte[] content = remote.getDocumentContent(doc.getId());\n String newName = FileUtils.getNewFileName(dto, doc.getName(), new Date(), false, this, \"Dokument als Vorlage speichern\");\n if (newName == null || \"\".equals(newName)) {\n this.lastPopupClosed = System.currentTimeMillis();\n continue;\n }\n if (newName.length() == 0) {\n JOptionPane.showMessageDialog(this, \"Dateiname darf nicht leer sein.\", \"Hinweis\", JOptionPane.INFORMATION_MESSAGE);\n this.lastPopupClosed = System.currentTimeMillis();\n continue;\n }\n locator.lookupSystemManagementRemote().addTemplate(SystemManagementRemote.TEMPLATE_TYPE_BODY, targetFolder, newName, content);\n }\n }\n } catch (Exception ioe) {\n log.error(\"Error adding templates\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Kopieren des Dokuments: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.lastPopupClosed = System.currentTimeMillis();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static String getChildEnvProp(JobConf jobConf, boolean isMap) {\n if (isMap) {\n return JobConf.MAPRED_MAP_TASK_ENV;\n }\n return JobConf.MAPRED_REDUCE_TASK_ENV;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected static boolean emptyStringToNull(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types, boolean autoConvert) {\n boolean modified = false;\n for (int i = 0; i < types.length; i++) {\n // type is string (VARCHAR) and state is empty string\n if ((types[i] instanceof StringType) && \"\".equals(state[i])) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Object {} is setting empty string {}\", entity.getClass().getCanonicalName(), propertyNames[i]);\n }\n if (autoConvert) {\n state[i] = null;\n modified = true;\n }\n }\n }\n return modified;\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public HttpIdentityResponse.HttpIdentityResponseBuilder handleException(FrameworkException exception) {\n HttpIdentityResponse.HttpIdentityResponseBuilder builder = new HttpIdentityResponse.HttpIdentityResponseBuilder();\n builder.setStatusCode(500);\n return builder;\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "/**\n * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}\n */\npublic FragmentMapping fragmentMapping(IgniteTableScan rel, RelMetadataQuery mq, MappingQueryContext ctx) {\n return FragmentMapping.create(rel.sourceId(), rel.getTable().unwrap(IgniteTable.class).colocationGroup(ctx));\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private static ChannelSelectionResult handleDefaultBaseChannelChange(Date earliest, User user, Server srv, Set srvChanges) {\n Optional guessedChannel = ChannelManager.guessServerBaseChannel(user, srv.getId());\n if (!guessedChannel.isPresent()) {\n LOG.error(\"Could not guess base channel for serverId={} user={}\", srv.getId(), user.getLogin());\n return new ChannelSelectionResult(srv, \"no_base_channel_guess\");\n }\n Optional srvChange = getChangeByDefaultBase(srvChanges, guessedChannel.get());\n if (srvChange.isPresent()) {\n Channel newBaseChannel = ChannelFactory.lookupById(srvChange.get().getNewBaseId().get());\n Set childChannels = getChildChannelsForChange(user, srv, srvChange.get(), newBaseChannel);\n return new ChannelSelectionResult(srv, new ChannelSelection(Optional.of(newBaseChannel), childChannels));\n } else {\n LOG.warn(\"No base channel change found for serverId={}\", srv.getId());\n return new ChannelSelectionResult(srv, \"no_base_change_found\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public Shuttle preVisit(DeclarationStatement declarationStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n this.refreshList();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": " void layout(final Graphics2D g, final int min_y, final int max_y){\n width = LIFELINE_WIDTH;\n x_left = participant.getX_middle() - LIFELINE_WIDTH / 2;\n x_right = x_left + width;\n y_top = startAt != null ? startAt.y_bottom : min_y;\n y_bottom = endAt != null ? endAt.y_bottom : max_y;\n height = y_bottom - y_top;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": " SqlResult execute(DmlPlan plan, QueryId queryId, List arguments, long timeout){\r\n List args = prepareArguments(plan.getParameterMetadata(), arguments);\r\n JobConfig jobConfig = new JobConfig().setArgument(SQL_ARGUMENTS_KEY_NAME, args).setArgument(KEY_SQL_QUERY_TEXT, plan.getQuery()).setArgument(KEY_SQL_UNBOUNDED, plan.isInfiniteRows()).setTimeoutMillis(timeout);\r\n Job job = hazelcastInstance.getJet().newLightJob(plan.getDag(), jobConfig);\r\n job.join();\r\n return UpdateSqlResultImpl.createUpdateCountResult(0);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmbFolderActionPerformed\nprivate void cmbFolderKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_cmbFolderKeyReleased\n this.checkFolder();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels){\n bcCodes.add(TABLESWITCH);\n bcLabel.add(dflt);\n bcLabelRelativeOffsets.add(byteCodeOffset);\n bcCaseValue.add(min);\n final int count = labels.length;\n bcCaseCount.add(count);\n for (int i = 0; i < count; i++) {\n bcLabel.add(labels[i]);\n bcLabelRelativeOffsets.add(byteCodeOffset);\n }\n final int padding = byteCodeOffset % 4 == 0 ? 0 : 4 - (byteCodeOffset % 4);\n byteCodeOffset += (padding + 12 + 4 * labels.length);\n updateRenumbering();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int getSLAComplianceForNodeInstance(String processInstanceId, org.jbpm.workflow.instance.NodeInstance nodeInstance, int logType) {\n int slaCompliance = nodeInstance.getSlaCompliance();\n return slaCompliance;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public void printRow(Rows rows, Rows.Row header, Rows.Row row){\n String[] head = header.values;\n String[] vals = row.values;\n int headwidth = 0;\n for (int i = 0; i < head.length && i < vals.length; i++) {\n headwidth = Math.max(headwidth, head[i].length());\n }\n headwidth += 2;\n for (int i = 0; i < head.length && i < vals.length; i++) {\n beeLine.output(beeLine.getColorBuffer().bold(beeLine.getColorBuffer().pad(head[i], headwidth).getMono()).append(vals[i] == null ? \"\" : vals[i]));\n }\n beeLine.output(\"\");\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ExecutionMode getExecutionMode(QueryPlan plan, List mrTasks, List tezTasks) {\n if (tezTasks.size() > 0) {\n // Need to go in and check if any of the tasks is running in LLAP mode.\n for (TezTask tezTask : tezTasks) {\n if (tezTask.getWork().getLlapMode()) {\n return ExecutionMode.LLAP;\n }\n }\n return ExecutionMode.TEZ;\n } else if (mrTasks.size() > 0) {\n return ExecutionMode.MR;\n } else {\n return ExecutionMode.NONE;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public static List getStatsRegistry(Configuration conf) {\n List l = new ArrayList();\n l.add(RAWDATASIZE);\n return l;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// write the attribute as an element definition, a component of the element that represents the\n// class\npublic void writeClassAttribute(DOMClass lClass, DOMProp lProp, PrintWriter prXML) throws java.io.IOException {\n // capture the data types that are used; will write only those used.\n ISOClassOAIS11179 lDOMObject = lProp.hasDOMObject;\n DOMAttr lAttr = (DOMAttr) lDOMObject;\n String lValueType = lAttr.valueType;\n if (lValueType == null) {\n lValueType = \"ASCII_Short_String_Collapsed\";\n }\n // convert the max cardinality for XML Schema\n String cmin = lAttr.cardMin;\n String cmax = lAttr.cardMax;\n if (cmax.compareTo(\"*\") == 0) {\n cmax = \"unbounded\";\n }\n if ((choiceBlockOpen) && (!lProp.isChoice || lProp.groupName.compareTo(lGroupName) != 0)) {\n downIndentSpaces();\n prXML.println(indentSpaces() + \"\");\n choiceBlockOpen = false;\n lGroupName = \"TBD_groupName\";\n }\n if ((lProp.isChoice) && (!choiceBlockOpen)) {\n // set the cardinalities of Master Choice block attributes to (1,1)\n if (lProp.isChoice && !lProp.isFromLDD) {\n cmin = lProp.cardMin;\n cmax = lProp.cardMax;\n if (cmax.compareTo(\"*\") == 0) {\n cmax = \"unbounded\";\n }\n }\n prXML.println(indentSpaces() + \"<\" + pNS + \"choice minOccurs=\\\"\" + cmin + \"\\\" maxOccurs=\\\"\" + cmax + \"\\\">\");\n upIndentSpaces();\n choiceBlockOpen = true;\n lGroupName = lProp.groupName;\n }\n String minMaxOccursClause = \" minOccurs=\\\"\" + cmin + \"\\\"\" + \" maxOccurs=\\\"\" + cmax + \"\\\"\";\n if (choiceBlockOpen) {\n minMaxOccursClause = \"\";\n }\n String nilableClause = \"\";\n if (lAttr.isNilable) {\n nilableClause = \" nillable=\\\"true\\\"\";\n }\n // write the XML schema statement\n if (!DMDocument.LDDToolFlag) {\n prXML.println(indentSpaces() + \"<\" + pNS + \"element name=\\\"\" + lAttr.XMLSchemaName + \"\\\"\" + nilableClause + \" type=\\\"\" + lAttr.nameSpaceId + lAttr.XMLSchemaName + \"\\\"\" + minMaxOccursClause + \"> \");\n } else if (!(lAttr.isExposed || lAttr.title.compareTo(\"local_identifier\") == 0)) {\n prXML.println(indentSpaces() + \"<\" + pNS + \"element name=\\\"\" + lAttr.XMLSchemaName + \"\\\"\" + nilableClause + \" type=\\\"\" + lAttr.nameSpaceId + lAttr.XMLSchemaName + \"\\\"\" + minMaxOccursClause + \"> \");\n } else {\n prXML.println(indentSpaces() + \"<\" + pNS + \"element ref=\\\"\" + lAttr.nameSpaceId + lAttr.XMLSchemaName + \"\\\"\" + nilableClause + minMaxOccursClause + \"> \");\n }\n // save the attribute's schema name for writing the simpleType statements\n if (!allAttrTypeIdArr.contains(lAttr.XMLSchemaName)) {\n allAttrTypeIdArr.add(lAttr.XMLSchemaName);\n allAttrTypeMap.put(lAttr.XMLSchemaName, lProp);\n }\n // if LDDTool write out annotation with the definition\n if (DMDocument.LDDToolAnnotateDefinitionFlag) {\n prXML.println(indentSpaces() + \"<\" + pNS + \"annotation>\");\n prXML.println(indentSpaces() + \" <\" + pNS + \"documentation>\");\n prXML.println(indentSpaces() + lProp.definition + \"\");\n prXML.println(indentSpaces() + \"\");\n }\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "protected boolean onEventDropped(final DroppedEvent event, final CalendarResponse response){\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void startResize(MouseEvent evt){\r\n origX = window.getX();\r\n origY = window.getY();\r\n origW = window.getWidth();\r\n origH = window.getHeight();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Creates and starts the server.\n * @param conf\n * @return the server port\n * @throws Exception\n */\nprotected int createServer(Configuration conf) throws Exception {\n return 0;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Mock an idempotency failure by executing the normal operation, then\n * raising an IOE.\n * @param normalRestOp the rest operation used to sign the requests.\n * @param failingOperation failing operation\n * @param normalOp good operation\n * @throws IOException failure\n */\nprivate void executeThenFail(final AbfsClient client, final AbfsRestOperation normalRestOp, final AbfsHttpOperation failingOperation, final AbfsHttpOperation normalOp) throws IOException {\n Mockito.doAnswer(answer -> {\n LOG.info(\"Executing first attempt with post-operation fault injection\");\n final byte[] buffer = answer.getArgument(0);\n final int offset = answer.getArgument(1);\n final int length = answer.getArgument(2);\n normalRestOp.signRequest(normalOp, length);\n normalOp.sendPayload(buffer, offset, length);\n normalOp.processResponse(buffer, offset, length);\n LOG.info(\"Actual outcome is {} \\\"{}\\\" \\\"{}\\\"; injecting failure\", normalOp.getStatusCode(), normalOp.getStorageErrorCode(), normalOp.getStorageErrorMessage());\n throw new SocketException(\"connection-reset\");\n }).when(failingOperation).sendPayload(Mockito.nullable(byte[].class), Mockito.nullable(int.class), Mockito.nullable(int.class));\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public boolean brief(String line) {\n beeLine.info(\"verbose: off\");\n return set(\"set verbose false\");\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void mnuOpenArchiveFileActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuOpenArchiveFileActionPerformed\n JTable sourceTable = this.getActiveTable();\n int row = sourceTable.getSelectedRow();\n QuickArchiveFileSearchRowIdentifier id = (QuickArchiveFileSearchRowIdentifier) sourceTable.getValueAt(row, 0);\n Object editor = null;\n try {\n editor = EditorsRegistry.getInstance().getEditor(this.detailsEditorClass);\n if (editor instanceof ThemeableEditor) {\n // inherit the background to newly created child editors\n ((ThemeableEditor) editor).setBackgroundImage(this.backgroundImage);\n }\n if (editor instanceof PopulateOptionsEditor) {\n ((PopulateOptionsEditor) editor).populateOptions();\n }\n ((ArchiveFilePanel) editor).setArchiveFileDTO(id.getArchiveFileDTO());\n ((ArchiveFilePanel) editor).setOpenedFromEditorClass(this.getClass().getName());\n EditorsRegistry.getInstance().setMainEditorsPaneView((Component) editor);\n } catch (Exception ex) {\n log.error(\"Error creating editor from class \" + this.detailsEditorClass, ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Editors: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtSearchDocumentNamesKeyReleased\nprivate void mnuToggleFavoriteActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuToggleFavoriteActionPerformed\n try {\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n ArchiveFileServiceRemote remote = locator.lookupArchiveFileServiceRemote();\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n for (ArchiveFileDocumentsBean doc : selectedDocs) {\n Boolean favorite = doc.isFavorite();\n boolean newValue = !favorite.booleanValue();\n remote.setDocumentFavorite(doc.getId(), newValue);\n doc.setFavorite(newValue);\n this.caseFolderPanel1.updateDocument(doc);\n }\n this.updateFavoriteDocuments();\n } catch (Exception ioe) {\n log.error(\"Error setting document date\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static Boolean isUdf(@SuppressWarnings(\"unused\") SqlOperator operator){\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": " void init(final RepresentationType representationType){\r\n ensureDomainModelQueryParamSupported();\r\n this.followLinks = Collections.unmodifiableList(getArg(RequestParameter.FOLLOW_LINKS));\r\n this.validateOnly = getArg(RequestParameter.VALIDATE_ONLY);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_txtPatternKeyReleased\nprivate void spnStartIndexStateChanged(javax.swing.event.ChangeEvent evt) {\n //GEN-FIRST:event_spnStartIndexStateChanged\n if (this.tblPools.getSelectedRow() > -1)\n this.updatePreview();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void writeBool(boolean b, String tag) throws IOException {\n out.writeBool(b);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void readData(Node transformNode, IHopMetadataProvider metadataProvider) throws HopXmlException {\n try {\n script = XmlHandler.getTagValue(transformNode, \"script\");\n matcher = XmlHandler.getTagValue(transformNode, \"matcher\");\n resultfieldname = XmlHandler.getTagValue(transformNode, \"resultfieldname\");\n usevar = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"usevar\"));\n allowcapturegroups = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"allowcapturegroups\"));\n replacefields = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"replacefields\"));\n canoneq = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"canoneq\"));\n caseinsensitive = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"caseinsensitive\"));\n comment = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"comment\"));\n dotall = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"dotall\"));\n multiline = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"multiline\"));\n unicode = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"unicode\"));\n unix = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"unix\"));\n Node fields = XmlHandler.getSubNode(transformNode, \"fields\");\n int nrFields = XmlHandler.countNodes(fields, \"field\");\n allocate(nrFields);\n for (int i = 0; i < nrFields; i++) {\n Node fnode = XmlHandler.getSubNodeByNr(fields, \"field\", i);\n fieldName[i] = XmlHandler.getTagValue(fnode, \"name\");\n final String stype = XmlHandler.getTagValue(fnode, \"type\");\n fieldFormat[i] = XmlHandler.getTagValue(fnode, \"format\");\n fieldGroup[i] = XmlHandler.getTagValue(fnode, \"group\");\n fieldDecimal[i] = XmlHandler.getTagValue(fnode, \"decimal\");\n fieldCurrency[i] = XmlHandler.getTagValue(fnode, \"currency\");\n final String slen = XmlHandler.getTagValue(fnode, \"length\");\n final String sprc = XmlHandler.getTagValue(fnode, \"precision\");\n fieldNullIf[i] = XmlHandler.getTagValue(fnode, \"nullif\");\n fieldIfNull[i] = XmlHandler.getTagValue(fnode, \"ifnull\");\n final String trim = XmlHandler.getTagValue(fnode, \"trimtype\");\n fieldType[i] = ValueMetaFactory.getIdForValueMeta(stype);\n fieldLength[i] = Const.toInt(slen, -1);\n fieldPrecision[i] = Const.toInt(sprc, -1);\n fieldTrimType[i] = ValueMetaBase.getTrimTypeByCode(trim);\n }\n } catch (Exception e) {\n throw new HopXmlException(BaseMessages.getString(PKG, \"RegexEvalMeta.Exception.UnableToLoadTransformMetaFromXML\"), e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "//GEN-LAST:event_txtEventBeginDateFieldMouseClicked\nprivate void cmdEventBeginDateSelectorActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdEventBeginDateSelectorActionPerformed\n MultiCalDialog dlg = new MultiCalDialog(this.txtEventBeginDateField, EditorsRegistry.getInstance().getMainWindow(), true);\n dlg.setVisible(true);\n if (this.radioEventTypeEvent.isSelected())\n this.txtEventEndDateField.setText(this.txtEventBeginDateField.getText());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private List messages(InputJson input, OutputJson output) {\n return output.getMessages().stream().filter(m -> !m.getType().equals(\"unsatisfied_pinned_match\")).map(m -> new MessageJson(m.getType(), m.getData())).collect(toList());\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "//GEN-LAST:event_jButton1ActionPerformed\nprivate void cmdCreateActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCreateActionPerformed\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtFilterKeyTyped\nprivate void txtFilterKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtFilterKeyReleased\n this.pnlSharesList.removeAll();\n if (this.txtFilter.getText().length() > 0) {\n ShareInfoPanel initialSelection = null;\n for (Share s : this.currentShares) {\n if (s.getPath().toLowerCase().contains(this.txtFilter.getText().toLowerCase())) {\n ShareInfoPanel p = new ShareInfoPanel(s, this.pnlSharesList, this);\n this.pnlSharesList.add(p);\n if (initialSelection == null) {\n initialSelection = p;\n p.setSelected(true);\n }\n }\n }\n } else {\n ShareInfoPanel initialSelection = null;\n for (Share s : this.currentShares) {\n ShareInfoPanel p = new ShareInfoPanel(s, this.pnlSharesList, this);\n this.pnlSharesList.add(p);\n if (initialSelection == null) {\n initialSelection = p;\n p.setSelected(true);\n }\n }\n }\n this.pnlSharesList.revalidate();\n this.pnlSharesList.doLayout();\n this.pnlSharesList.updateUI();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n if (this.cmbTemplates.getSelectedItem() == null) {\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n String name = this.cmbTemplates.getSelectedItem().toString();\n locator.lookupArchiveFileServiceRemote().removeFolderTemplate(name);\n this.cmbTemplates.removeItem(name);\n } catch (Exception ex) {\n log.error(\"Error connecting to server\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected PostAuthnHandlerFlowStatus handlePostAuthenticationForMissingClaimsRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {\n String[] missingClaims = FrameworkUtils.getMissingClaims(context);\n DiagnosticLog.DiagnosticLogBuilder diagnosticLogBuilder = new DiagnosticLog.DiagnosticLogBuilder(FrameworkConstants.LogConstants.AUTHENTICATION_FRAMEWORK, FrameworkConstants.LogConstants.ActionIDs.HANDLE_MISSING_CLAIMS).logDetailLevel(DiagnosticLog.LogDetailLevel.APPLICATION);\n if (StringUtils.isNotBlank(missingClaims[0])) {\n if (log.isDebugEnabled()) {\n log.debug(\"Mandatory claims missing for the application : \" + missingClaims[0]);\n }\n if (LoggerUtils.isDiagnosticLogsEnabled()) {\n diagnosticLogBuilder.inputParam(LogConstants.InputKeys.TENANT_DOMAIN, context.getTenantDomain()).inputParam(FrameworkConstants.LogConstants.MISSING_CLAIMS, missingClaims).resultStatus(DiagnosticLog.ResultStatus.SUCCESS).resultMessage(\"Mandatory claims missing for the application: \" + context.getServiceProviderName());\n // Adding application related details to diagnostic log.\n FrameworkUtils.getApplicationResourceId(context).ifPresent(applicationId -> diagnosticLogBuilder.inputParam(LogConstants.InputKeys.APPLICATION_ID, applicationId));\n FrameworkUtils.getApplicationName(context).ifPresent(applicationName -> diagnosticLogBuilder.inputParam(LogConstants.InputKeys.APPLICATION_NAME, applicationName));\n LoggerUtils.triggerDiagnosticLogEvent(diagnosticLogBuilder);\n }\n try {\n // If there are read only claims marked as mandatory and they are missing, we cannot proceed further.\n // We have to end the flow and show an error message to user.\n ClaimManager claimManager = getUserRealm(context.getTenantDomain()).getClaimManager();\n Map missingClaimMap = FrameworkUtils.getMissingClaimsMap(context);\n for (Map.Entry missingClaim : missingClaimMap.entrySet()) {\n Claim claimObj = claimManager.getClaim(missingClaim.getValue());\n if (claimObj != null && claimObj.isReadOnly()) {\n if (LoggerUtils.isDiagnosticLogsEnabled()) {\n diagnosticLogBuilder.inputParam(FrameworkConstants.LogConstants.READ_ONLY_CLAIMS, claimObj.getClaimUri()).resultStatus(DiagnosticLog.ResultStatus.FAILED).resultMessage(\"One or more read-only claims are missing in the \" + \"requested claim set.\");\n LoggerUtils.triggerDiagnosticLogEvent(diagnosticLogBuilder);\n }\n throw new PostAuthenticationFailedException(\"One or more read-only claim is missing in the \" + \"requested claim set. Please contact your administrator for more information about \" + \"this issue.\", \"One or more read-only claim is missing in the requested claim set\");\n }\n }\n List localClaims = getClaimMetadataManagementService().getLocalClaims(context.getTenantDomain());\n String displayNames = getMissingClaimsDisplayNames(missingClaimMap, localClaims);\n URIBuilder uriBuilder = new URIBuilder(ConfigurationFacade.getInstance().getAuthenticationEndpointMissingClaimsURL());\n uriBuilder.addParameter(FrameworkConstants.MISSING_CLAIMS, missingClaims[0]);\n uriBuilder.addParameter(FrameworkConstants.DISPLAY_NAMES, displayNames);\n uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());\n uriBuilder.addParameter(FrameworkConstants.REQUEST_PARAM_SP, context.getSequenceConfig().getApplicationConfig().getApplicationName());\n if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR) != null) {\n uriBuilder.addParameter(\"errorMessage\", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR).toString());\n context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR);\n }\n if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE) != null) {\n uriBuilder.addParameter(\"errorCode\", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE).toString());\n context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE);\n }\n response.sendRedirect(uriBuilder.build().toString());\n context.setProperty(POST_AUTHENTICATION_REDIRECTION_TRIGGERED, true);\n if (log.isDebugEnabled()) {\n log.debug(\"Redirecting to outside to pick mandatory claims\");\n }\n if (LoggerUtils.isDiagnosticLogsEnabled()) {\n diagnosticLogBuilder.resultMessage(\"Redirecting to outside to pick mandatory claims from the \" + \"user.\").resultStatus(DiagnosticLog.ResultStatus.SUCCESS);\n LoggerUtils.triggerDiagnosticLogEvent(diagnosticLogBuilder);\n }\n } catch (IOException e) {\n throw new PostAuthenticationFailedException(\"Error while handling missing mandatory claims\", \"Error \" + \"while redirecting to request claims page\", e);\n } catch (URISyntaxException e) {\n throw new PostAuthenticationFailedException(\"Error while handling missing mandatory claims. \" + \"Error in redirect URI.\", \"Error while building redirect URI\", e);\n } catch (org.wso2.carbon.user.api.UserStoreException e) {\n throw new PostAuthenticationFailedException(\"Error while handling missing mandatory claims. \" + \"Error in retrieving claim.\", \"Error while retrieving claim from claim URI.\", e);\n } catch (ClaimMetadataException e) {\n throw new PostAuthenticationFailedException(\"Error while handling missing mandatory claims\", \"Error while retrieving claim metadata.\", e);\n }\n return PostAuthnHandlerFlowStatus.INCOMPLETE;\n } else {\n return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdToPdfActionPerformed\nprivate void cmdVerifySignaturesActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdVerifySignaturesActionPerformed\n if (this.msgContainer == null) {\n return;\n }\n try {\n String vHtml = \"\";\n String vStatus = VerificationResult.STATUS_FAILED;\n if (StringUtils.isEmpty(this.msgContainer.getVerificationHtml()) || StringUtils.isEmpty(this.msgContainer.getVerificationStatus())) {\n if (!BeaAccess.hasInstance()) {\n BeaLoginCallback callback = null;\n try {\n callback = (BeaLoginCallback) EditorsRegistry.getInstance().getEditor(BeaInboxPanel.class.getName());\n } catch (Throwable t) {\n log.error(t);\n }\n BeaLoginDialog loginPanel = new BeaLoginDialog(EditorsRegistry.getInstance().getMainWindow(), true, callback);\n loginPanel.setVisible(true);\n if (!BeaAccess.hasInstance()) {\n ThreadUtils.showErrorDialog(this, \"beA-Login fehlgeschlagen\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR);\n return;\n }\n }\n BeaAccess bea = BeaAccess.getInstance();\n VerificationResult vr = bea.verifyMessage(this.msgContainer.getId());\n vHtml = vr.getHtml();\n vStatus = vr.getStatus();\n } else {\n vHtml = this.msgContainer.getVerificationHtml();\n vStatus = this.msgContainer.getVerificationStatus();\n }\n BeaSignaturesVerificationDialog dlg = new BeaSignaturesVerificationDialog(EditorsRegistry.getInstance().getMainWindow(), true);\n dlg.setHtml(vHtml);\n dlg.setStatus(vStatus);\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n } catch (Throwable t) {\n ThreadUtils.showErrorDialog(this, \"Fehler bei der Signaturpr\u00fcfung: \" + t.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * @return Whether the SerDe that can store schema both inside and outside of\n * metastore does, in fact, store it inside metastore, based on table\n * parameters.\n */\npublic boolean shouldStoreFieldsInMetastore(Map tableParams) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_contentPanelComponentResized\nprivate void cmbFormatItemStateChanged(java.awt.event.ItemEvent evt) {\n //GEN-FIRST:event_cmbFormatItemStateChanged\n String sel = (String) this.cmbFormat.getSelectedItem();\n if (sel == null)\n sel = ContentTypes.TEXT_PLAIN;\n if (sel.toLowerCase().contains(\"html\")) {\n this.contentPanel.remove(0);\n this.contentPanel.add(hp);\n hp.setBounds(0, 0, this.contentPanel.getWidth(), this.contentPanel.getHeight());\n tp.setBounds(0, 0, this.contentPanel.getWidth(), this.contentPanel.getHeight());\n SwingUtilities.updateComponentTreeUI(tp);\n SwingUtilities.updateComponentTreeUI(hp);\n } else {\n this.contentPanel.remove(0);\n this.contentPanel.add(tp);\n tp.setBounds(0, 0, this.contentPanel.getWidth(), this.contentPanel.getHeight());\n hp.setBounds(0, 0, this.contentPanel.getWidth(), this.contentPanel.getHeight());\n SwingUtilities.updateComponentTreeUI(tp);\n SwingUtilities.updateComponentTreeUI(hp);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void assertAppFinalStateSaved(RMApp application) {\n verify(store, times(1)).updateApplicationState(any(ApplicationStateData.class));\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_lstToMousePressed\nprivate void cmdSaveDraftActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveDraftActionPerformed\n if (this.attachments.isEmpty() && this.chkEeb.isSelected()) {\n JOptionPane.showMessageDialog(this, \"Ein eEB kann nur f\u00fcr Nachrichten angefordert werden die mindestens einen Anhang enthalten.\", \"beA-Nachricht mit eEB senden\", JOptionPane.WARNING_MESSAGE);\n return;\n }\n if (this.lstTo.getModel().getSize() == 0) {\n JOptionPane.showMessageDialog(this, \"Es muss mindestens ein Empf\u00e4nger angegeben werden\", \"beA-Nachricht senden\", JOptionPane.WARNING_MESSAGE);\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n if (this.chkSaveAsDocument.isSelected()) {\n settings.setConfiguration(ClientSettings.CONF_BEA_SAVETOARCHIVEFILE, \"1\");\n } else {\n settings.setConfiguration(ClientSettings.CONF_BEA_SAVETOARCHIVEFILE, \"0\");\n }\n if (this.authority == null) {\n this.requestLegalAuthority();\n }\n String createDocumentTag = null;\n if (this.chkDocumentTagging.isSelected()) {\n Object selectedTag = this.cmbDocumentTag.getSelectedItem();\n if (selectedTag != null) {\n if (!\"\".equals(selectedTag.toString())) {\n createDocumentTag = selectedTag.toString();\n }\n }\n }\n ProgressIndicator dlg = new ProgressIndicator(this, true);\n EditorImplementation ed = (EditorImplementation) this.contentPanel.getComponent(0);\n String fromSafeId = ((Identity) this.cmbFrom.getSelectedItem()).getSafeId();\n SaveBeaMessageAction a = null;\n CaseFolder folder = null;\n if (this.chkSaveAsDocument.isSelected() || !(this.radioReviewTypeNone.isSelected())) {\n if (this.contextArchiveFile == null) {\n SearchAndAssignDialog saDlg = new SearchAndAssignDialog(this, true, \"\" + this.cmbAzRecipient.getEditor().getItem().toString() + this.txtAzSender.getText() + this.txtSubject.getText(), null);\n saDlg.setVisible(true);\n this.contextArchiveFile = saDlg.getCaseSelection();\n folder = saDlg.getFolderSelection();\n saDlg.dispose();\n }\n }\n Identity recipient = null;\n if (this.lstTo.getModel().getSize() > 0) {\n recipient = (Identity) ((DefaultListModel) this.lstTo.getModel()).elements().nextElement();\n }\n BeaListItem priority = null;\n if (this.cmbPriorities.getSelectedItem() instanceof BeaListItem)\n // first index is a string (no priority selected)\n priority = (BeaListItem) this.cmbPriorities.getSelectedItem();\n ArrayList attachmentMetadata = this.getAttachmentMetdata();\n try {\n if (this.contextArchiveFile != null)\n CaseUtils.optionalUnarchiveCase(this.contextArchiveFile, this);\n } catch (Exception ex) {\n log.error(\"Unable to unarchive case \" + this.contextArchiveFile.getFileNumber(), ex);\n }\n if (!(this.radioReviewTypeNone.isSelected()) && this.contextArchiveFile != null) {\n if (this.txtReviewDateField.getText().length() != 10) {\n JOptionPane.showMessageDialog(this, \"Wiedervorlagedatum ung\u00fcltig\", \"beA-Nachricht als Entwurf speichern\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n Date d = null;\n try {\n SimpleDateFormat df = new SimpleDateFormat(\"dd.MM.yyyy\");\n d = df.parse(this.txtReviewDateField.getText());\n } catch (Throwable t) {\n JOptionPane.showMessageDialog(this, \"Wiedervorlagedatum ung\u00fcltig\", \"beA-Nachricht als Entwurf speichern\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ArchiveFileReviewsBean reviewDto = new ArchiveFileReviewsBean();\n reviewDto.setEventType(ArchiveFileReviewsBean.EVENTTYPE_FOLLOWUP);\n if (this.radioReviewTypeRespite.isSelected()) {\n reviewDto.setEventType(ArchiveFileReviewsBean.EVENTTYPE_RESPITE);\n }\n reviewDto.setDone(false);\n reviewDto.setBeginDate(d);\n reviewDto.setAssignee(this.cmbReviewAssignee.getSelectedItem().toString());\n reviewDto.setSummary(this.cmbReviewReason.getEditor().getItem().toString());\n reviewDto.setCalendarSetup(this.calendarSelectionButton1.getSelectedSetup());\n if (CalendarUtils.checkForConflicts(this, reviewDto)) {\n try {\n CalendarUtils.getInstance().storeCalendarEntry(reviewDto, this.contextArchiveFile, (CalendarEntryTemplate) this.cmbReviewReason.getItemAt(this.cmbReviewReason.getSelectedIndex()), this);\n } catch (Exception ex) {\n log.error(\"Error adding review\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern des Kalendereintrages: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n }\n if (this.chkSaveAsDocument.isSelected()) {\n a = new SaveBeaMessageAction(dlg, this, fromSafeId, attachmentMetadata, this.cu, this.chkEeb.isSelected(), this.authority, recipient, this.txtSubject.getText(), ed.getText(), this.contextArchiveFile, createDocumentTag, this.txtAzSender.getText(), this.cmbAzRecipient.getEditor().getItem().toString(), folder, priority);\n } else {\n a = new SaveBeaMessageAction(dlg, this, fromSafeId, attachmentMetadata, this.cu, this.chkEeb.isSelected(), this.authority, recipient, this.txtSubject.getText(), ed.getText(), createDocumentTag, this.txtAzSender.getText(), this.cmbAzRecipient.getEditor().getItem().toString(), priority);\n }\n a.start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static GotoStatement break_(LabelTarget labelTarget, Expression expression){\n return new GotoStatement(GotoExpressionKind.Break, null, expression);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Merge old and new metadata payloads. By default, it returns the newer payload.\n * Implementations can override this method to merge the payloads depending on the partition type.\n */\npublic HoodieMetadataPayload combineMetadataPayloads(HoodieMetadataPayload older, HoodieMetadataPayload newer) {\n return newer;\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private void processXmlJavaTypeAdapter(final ProcessMethodContext processMethodContext, final XmlAccessType accessType){\n val xmlJavaTypeAdapterIfAny = processMethodContext.synthesizeOnMethod(XmlJavaTypeAdapter.class);\n if (!xmlJavaTypeAdapterIfAny.isPresent()) {\n return;\n }\n val facetHolder = processMethodContext.getFacetHolder();\n addFacet(new XmlJavaTypeAdapterFacetDefault(facetHolder, xmlJavaTypeAdapterIfAny.get().value()));\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean extractIncludeJdbcDrivers(T annotation) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "//GEN-LAST:event_lstTemplatesMouseClicked\nprivate void cmdNewODTActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdNewODTActionPerformed\n String fileName = JOptionPane.showInputDialog(this, \"Dateiname ohne Verzeichnis und Erweiterung: \", \"neue Master-Vorlage (Text)\", JOptionPane.QUESTION_MESSAGE);\n fileName = fileName.replaceAll(\" \", \"-\");\n fileName = fileName + \".odt\";\n if (fileName.length() == 0) {\n JOptionPane.showMessageDialog(this, \"Dateiname darf nicht leer sein.\", \"Hinweis\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n TreePath tp = this.treeFolders.getSelectionPath();\n if (tp == null) {\n log.error(\"no folder selected - returning...\");\n return;\n }\n DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) tp.getLastPathComponent();\n GenericNode folder = (GenericNode) selNode.getUserObject();\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupSystemManagementRemote().addFromMasterTemplate(this.templateType, fileName, \"j-lawyer-allgemeine-Mastervorlage.odt\", folder);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Erstellen des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.refreshList();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public T relativeAfter(long duration){\n return (T) this;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n ClientSettings set = ClientSettings.getInstance();\n String maxPreviewBytesString = this.cmbSize.getSelectedItem().toString();\n if ((\"1 MB\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 1l * 1024l * 1024l);\n } else if ((\"2 MB\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 2l * 1024l * 1024l);\n } else if ((\"3 MB\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 3l * 1024l * 1024l);\n } else if ((\"5 MB\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 5l * 1024l * 1024l);\n } else if ((\"10 MB\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 10l * 1024l * 1024l);\n } else if ((\"unbegrenzt\").equals(maxPreviewBytesString)) {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + Long.MAX_VALUE);\n } else {\n set.setConfiguration(ClientSettings.CONF_DOCUMENTS_MAXPREVIEWBYTES, \"\" + 2l * 1024l * 1024l);\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public HashMap getCountsFromGraphsonSnapshot(String databaseName, String fileNamePart, String srcDir) throws Exception{\n final JsonParser jsonParser = new JsonParser();\n final Set uris = new HashSet<>();\n final Set uuids = new HashSet<>();\n final Map idToUri = new HashMap<>();\n final Map idToType = new HashMap<>();\n final Map idToUuid = new HashMap<>();\n final Set> idIdLabelOfEdges = new HashSet<>();\n final HashMap tableCountHash = new HashMap<>();\n String sourceDir = DEFAULT_SRC_DIR;\n if (srcDir != null && srcDir.length() > 1) {\n sourceDir = srcDir;\n }\n String graphsonDir = sourceDir + \"/\";\n if (fileNamePart == null || fileNamePart.trim().isEmpty()) {\n String msg = \"ERROR -- fileName is required to be passed in. \";\n LOGGER.error(msg);\n System.out.println(msg);\n throw new Exception(msg);\n }\n final List graphsons = Files.walk(Paths.get(graphsonDir)).filter(Files::isRegularFile).map(Path::toFile).sorted().collect(Collectors.toList());\n int skippedNodeCount = 0;\n int nodeCounter = 0;\n int edgeCounter = 0;\n for (File graphson : graphsons) {\n if (!graphson.getName().contains(fileNamePart)) {\n continue;\n }\n try (BufferedReader reader = new BufferedReader(new FileReader(graphson))) {\n String msg = \"Processing snapshot file \" + graphson.getName();\n LOGGER.debug(msg);\n System.out.println(msg);\n String line;\n while ((line = reader.readLine()) != null) {\n JsonObject vertex = jsonParser.parse(line).getAsJsonObject();\n long id = vertex.get(\"id\").getAsLong();\n if ((vertex.get(\"properties\") == null) || !vertex.get(\"properties\").getAsJsonObject().has(\"aai-uri\") || !vertex.get(\"properties\").getAsJsonObject().has(\"aai-node-type\") || !vertex.get(\"properties\").getAsJsonObject().has(\"aai-uuid\")) {\n msg = \"DEBUG -- Could not find keys for this line: [\" + line + \"] ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n skippedNodeCount++;\n continue;\n }\n String uri = vertex.get(\"properties\").getAsJsonObject().get(\"aai-uri\").getAsJsonArray().get(0).getAsJsonObject().get(\"value\").getAsString();\n String nodeType = vertex.get(\"properties\").getAsJsonObject().get(\"aai-node-type\").getAsJsonArray().get(0).getAsJsonObject().get(\"value\").getAsString();\n String nodeTypeKey = nodeType.replaceAll(\"-\", \"_\");\n String uuid = vertex.get(\"properties\").getAsJsonObject().get(\"aai-uuid\").getAsJsonArray().get(0).getAsJsonObject().get(\"value\").getAsString();\n try {\n loader.introspectorFromName(nodeType);\n } catch (Exception e) {\n msg = \"DEBUG -- loader introspector for nodeType error: [\" + e.getMessage() + \"], [\" + e.getLocalizedMessage() + \"]------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n skippedNodeCount++;\n continue;\n }\n if (uris.contains(uri)) {\n msg = \"DEBUG -- SKIP Uri because it has been seen before: [\" + uri + \"] ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n skippedNodeCount++;\n continue;\n } else if (uuids.contains(uuid)) {\n msg = \"DEBUG -- SKIP UUID because it has been seen before: [\" + uuid + \"] ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n skippedNodeCount++;\n continue;\n }\n uris.add(uri);\n uuids.add(uuid);\n idToUri.put(id, uri);\n idToType.put(id, nodeType);\n idToUuid.put(id, uuid);\n if (vertex.has(\"inE\")) {\n vertex.get(\"inE\").getAsJsonObject().entrySet().forEach(es -> {\n String label = es.getKey();\n es.getValue().getAsJsonArray().forEach(e -> {\n long otherId = e.getAsJsonObject().get(\"outV\").getAsLong();\n idIdLabelOfEdges.add(new Triplet<>(id, otherId, label));\n });\n });\n }\n if (!tableCountHash.containsKey(nodeTypeKey)) {\n int ct = 1;\n tableCountHash.put(nodeTypeKey, ct);\n } else {\n int tmpCt = tableCountHash.get(nodeTypeKey);\n tmpCt++;\n tableCountHash.remove(nodeTypeKey);\n tableCountHash.put(nodeTypeKey, tmpCt);\n }\n nodeCounter++;\n }\n } catch (IOException e) {\n String msg = \"DEBUG -- Error while processing nodes ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n }\n }\n String msg = \"DEBUG -- Found this many Kinds of nodes: \" + tableCountHash.size();\n LOGGER.debug(msg);\n System.out.println(msg);\n msg = \"DEBUG -- Found this many total nodes: \" + nodeCounter;\n LOGGER.debug(msg);\n System.out.println(msg);\n msg = \" >> Skipped a total of \" + skippedNodeCount + \" Node Records ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n msg = \"DEBUG -- Begin Processing Edges ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n int edgeTableCounter = 0;\n int edgeSkipCounter = 0;\n Map edgeKeys = this.getEdgeMapKeys();\n for (Triplet edge : idIdLabelOfEdges) {\n if (!idToType.containsKey(edge.getValue0())) {\n LOGGER.info(\" Edge Skipped because ID not found: [\" + edge.getValue0() + \"]\");\n System.out.println(\" Edge Skipped because ID not found: [\" + edge.getValue0() + \"]\");\n edgeSkipCounter++;\n continue;\n } else if (!idToType.containsKey(edge.getValue1())) {\n System.out.println(\" Edge Skipped because ID not found: [\" + edge.getValue1() + \"]\");\n LOGGER.info(\" Edge Skipped because ID not found: [\" + edge.getValue1() + \"]\");\n edgeSkipCounter++;\n continue;\n } else {\n String colA = idToType.get(edge.getValue1()).replace(\"-\", \"_\");\n String colB = idToType.get(edge.getValue0()).replace(\"-\", \"_\");\n String edLabel = edge.getValue2();\n String edKey = colA + \"__\" + colB;\n String tcEdKey = \"\";\n if (!edgeKeys.containsKey(edKey)) {\n tcEdKey = edgeKeys.get(colB + \"__\" + colA);\n } else {\n tcEdKey = edgeKeys.get(edKey);\n }\n if (!tableCountHash.containsKey(tcEdKey)) {\n int ct = 1;\n tableCountHash.put(tcEdKey, ct);\n edgeTableCounter++;\n } else {\n int tmpCt = tableCountHash.get(tcEdKey);\n tmpCt++;\n tableCountHash.remove(tcEdKey);\n tableCountHash.put(tcEdKey, tmpCt);\n }\n edgeCounter++;\n }\n }\n msg = \" Processed a total of \" + edgeCounter + \" Edge Records ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n msg = \" Found data for this many edgeTables: \" + edgeTableCounter;\n LOGGER.debug(msg);\n System.out.println(msg);\n msg = \" >> Skipped a total of \" + edgeSkipCounter + \" Edge Records ------\";\n LOGGER.debug(msg);\n System.out.println(msg);\n return tableCountHash;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void extractOperands(final OperandManager operandManager, final Segment segment, final int codeLength){\n final ByteCodeForm currentByteCodeForm = getByteCodeForm();\n currentByteCodeForm.setByteCodeOperands(this, operandManager, codeLength);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean processFirstRow(MultiMergeJoinMeta smi, MultiMergeJoinData sdi) throws HopException {\n PipelineHopMeta pipelineHopMeta;\n ITransformIOMeta transformIOMeta = meta.getTransformIOMeta();\n List infoStreams = transformIOMeta.getInfoStreams();\n IStream stream;\n TransformMeta toTransformMeta = meta.getParentTransformMeta();\n TransformMeta fromTransformMeta;\n ArrayList inputTransformNameList = new ArrayList<>();\n String[] inputTransformNames = meta.getInputTransforms();\n String inputTransformName;\n for (int i = 0; i < infoStreams.size(); i++) {\n inputTransformName = inputTransformNames[i];\n stream = infoStreams.get(i);\n fromTransformMeta = stream.getTransformMeta();\n if (fromTransformMeta == null) {\n // should not arrive here, shoud typically have been caught by init.\n throw new HopException(BaseMessages.getString(PKG, CONST_MULTI_MERGE_JOIN_LOG_UNABLE_TO_FIND_REFERENCE_STREAM, inputTransformName));\n }\n // check the hop\n pipelineHopMeta = getPipelineMeta().findPipelineHop(fromTransformMeta, toTransformMeta, true);\n // there is no hop: this is unexpected.\n if (pipelineHopMeta == null) {\n // should not arrive here, shoud typically have been caught by init.\n throw new HopException(BaseMessages.getString(PKG, CONST_MULTI_MERGE_JOIN_LOG_UNABLE_TO_FIND_REFERENCE_STREAM, inputTransformName));\n } else if (pipelineHopMeta.isEnabled()) {\n inputTransformNameList.add(inputTransformName);\n } else {\n logDetailed(BaseMessages.getString(PKG, \"MultiMergeJoin.Log.IgnoringTransform\", inputTransformName));\n }\n }\n int streamSize = inputTransformNameList.size();\n if (streamSize == 0) {\n return false;\n }\n String keyField;\n data.rowSets = new IRowSet[streamSize];\n IRowSet rowSet;\n Object[] row;\n data.rows = new Object[streamSize][];\n data.metas = new IRowMeta[streamSize];\n data.rowLengths = new int[streamSize];\n MultiMergeJoinData.QueueComparator comparator = new MultiMergeJoinData.QueueComparator(data);\n data.queue = new PriorityQueue<>(streamSize, comparator);\n data.results = new ArrayList<>(streamSize);\n MultiMergeJoinData.QueueEntry queueEntry;\n data.queueEntries = new MultiMergeJoinData.QueueEntry[streamSize];\n data.drainIndices = new int[streamSize];\n data.keyNrs = new int[streamSize][];\n data.dummy = new Object[streamSize][];\n IRowMeta rowMeta;\n data.outputRowMeta = new RowMeta();\n for (int i = 0, j = 0; i < inputTransformNames.length; i++) {\n inputTransformName = inputTransformNames[i];\n if (!inputTransformNameList.contains(inputTransformName)) {\n // ignore transform with disabled hop.\n continue;\n }\n queueEntry = new MultiMergeJoinData.QueueEntry();\n queueEntry.index = j;\n data.queueEntries[j] = queueEntry;\n data.results.add(new ArrayList<>());\n rowSet = findInputRowSet(inputTransformName);\n if (rowSet == null) {\n throw new HopException(BaseMessages.getString(PKG, \"MultiMergeJoin.Exception.UnableToFindSpecifiedTransform\", inputTransformName));\n }\n data.rowSets[j] = rowSet;\n row = getRowFrom(rowSet);\n data.rows[j] = row;\n if (row == null) {\n rowMeta = getPipelineMeta().getTransformFields(this, inputTransformName);\n data.metas[j] = rowMeta;\n } else {\n queueEntry.row = row;\n rowMeta = rowSet.getRowMeta();\n keyField = meta.getKeyFields()[i];\n String[] keyFieldParts = keyField.split(\",\");\n String keyFieldPart;\n data.keyNrs[j] = new int[keyFieldParts.length];\n for (int k = 0; k < keyFieldParts.length; k++) {\n keyFieldPart = keyFieldParts[k];\n data.keyNrs[j][k] = rowMeta.indexOfValue(keyFieldPart);\n if (data.keyNrs[j][k] < 0) {\n String message = BaseMessages.getString(PKG, \"MultiMergeJoin.Exception.UnableToFindFieldInReferenceStream\", keyFieldPart, inputTransformName);\n logError(message);\n throw new HopTransformException(message);\n }\n }\n data.metas[j] = rowMeta;\n data.queue.add(data.queueEntries[j]);\n }\n data.outputRowMeta.mergeRowMeta(rowMeta.clone());\n data.rowLengths[j] = rowMeta.size();\n data.dummy[j] = RowDataUtil.allocateRowData(rowMeta.size());\n j++;\n }\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected void unsetClaimMetaMgtService(ClaimMetadataManagementService claimMetaMgtService) {\n InputValidationDataHolder.getInstance().setClaimMetadataManagementService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public List getAllRows(IVariables variables, ILogChannel log) throws HopException {\n return DataSetCsvUtil.getAllRows(variables, this);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "//GEN-LAST:event_tblAttachmentsMousePressed\nprivate void cmdAttachmentUpActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdAttachmentUpActionPerformed\n TableUtils.moveUpwards(tblAttachments);\n this.updateAlias();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static Builder builder(Class itemClass){\n return new BuilderImpl<>();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// write the TTL file\npublic void writeDOMRDFTTLFile(String lClassificationType, ClassAttrPropClassification lClassAttrPropClassification) throws java.io.IOException {\n String lFileName = DMDocument.masterPDSSchemaFileDefn.relativeFileSpecOWLRDF_DOM;\n lFileName = DOMInfoModel.replaceString(lFileName, \".rdf\", \"_IKG.ttl\");\n prRDFFile = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(lFileName)), \"UTF-8\"));\n // set the namespaceid to be used as the RDF prefix\n masterNameSpaceIdNC = ClassAttrPropClassification.getMasterNameSpaceIdNC();\n // write the Header\n writeRDFHdr(lClassAttrPropClassification);\n // write the Body\n writeRDFBody(lClassAttrPropClassification);\n // write the Footer and close\n writeRDFFtr();\n prRDFFile.close();\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "//GEN-LAST:event_txtDividerExtKeyReleased\nprivate void txtExtPrefixKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtExtPrefixKeyReleased\n this.updatePreview();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private Object field(@SuppressWarnings(\"unused\") String field, String value){\r\n if (value.isEmpty()) {\r\n return 0;\r\n }\r\n if (value.endsWith(\".\")) {\r\n return Long.parseLong(value);\r\n }\r\n return Long.parseLong(value);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * See {@link IgniteMdFragmentMapping#fragmentMapping(RelNode, RelMetadataQuery, MappingQueryContext)}\n */\npublic FragmentMapping fragmentMapping(IgniteValues rel, RelMetadataQuery mq, MappingQueryContext ctx) {\n return FragmentMapping.create();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "public void initializeStreaming(Configuration cfg, StructObjectInspector inputOI, boolean isMapSide) throws HiveException {\n canAcceptInputAsStream = false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private TaskReport[] getTaskReports(JobID jobId, TaskType type) {\n return new TaskReport[] { new TaskReport(), new TaskReport() };\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected Stream visitCustomFields(T compositeContextNode, VariableScope variableScope) {\n return Stream.empty();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public static Builder builder(Class clzz){\r\n return new Builder<>();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void test(String testClient) throws Exception {\n ZKClient client = new ZKClient(hostPort);\n client.registerService(\"/nodemanager\", \"hostPort\");\n client.unregisterService(\"/nodemanager\");\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void setupXframeFilter(Builder b, Map params) {\n FilterHolder holder = new FilterHolder();\n holder.setClassName(QuotingInputFilter.class.getName());\n holder.setInitParameters(params);\n ServletHandler handler = webAppContext.getServletHandler();\n handler.addFilterWithMapping(holder, \"/*\", FilterMapping.ALL);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected Shuffle getShuffle(Configuration conf){\n return shuffle;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void mnuOpenArchiveFileActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuOpenArchiveFileActionPerformed\n int row = this.tblResults.getSelectedRow();\n ArchiveFileReviewsRowIdentifier id = (ArchiveFileReviewsRowIdentifier) this.tblResults.getValueAt(row, 0);\n Object editor = null;\n try {\n editor = EditorsRegistry.getInstance().getEditor(this.detailsEditorClass);\n if (editor instanceof ThemeableEditor) {\n // inherit the background to newly created child editors\n ((ThemeableEditor) editor).setBackgroundImage(this.backgroundImage);\n }\n if (editor instanceof PopulateOptionsEditor) {\n ((PopulateOptionsEditor) editor).populateOptions();\n }\n ((ArchiveFilePanel) editor).setArchiveFileDTO(id.getArchiveFileDTO());\n ((ArchiveFilePanel) editor).setOpenedFromEditorClass(this.getClass().getName());\n EditorsRegistry.getInstance().setMainEditorsPaneView((Component) editor);\n ((ArchiveFilePanel) editor).selectEvent(id.getReviewDTO().getId());\n } catch (Exception ex) {\n log.error(\"Error creating editor from class \" + this.detailsEditorClass, ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Editors: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// potential instrumentation interface methods\npublic void submittedJob(Job job) {\n jobsSubmitted.incr();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public boolean shouldCorruptAByte(File localfile) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private static Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, AtomIterator iter){\n List atoms = new ArrayList<>();\n while (iter.hasNext()) {\n Atom a = iter.next();\n if (a.getElement() == Element.H)\n continue;\n Group g = a.getGroup();\n if (g.isWater())\n continue;\n if (!hetAtoms && g.getType().equals(GroupType.HETATM))\n continue;\n atoms.add(a);\n }\n return atoms.toArray(new Atom[0]);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Shuttle preVisit(ForEachStatement forEachStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdGetCloudCalendarsActionPerformed\nprivate void formWindowClosing(java.awt.event.WindowEvent evt) {\n //GEN-FIRST:event_formWindowClosing\n this.saveGlobalFlags();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static Multimap getAllMap(BibDatabaseContext databaseContext, FilePreferences filePreferences, JournalAbbreviationRepository abbreviationRepository, boolean allowIntegerEdition){\n ArrayListMultimap fieldCheckers = ArrayListMultimap.create(50, 10);\n for (Field field : FieldFactory.getPersonNameFields()) {\n fieldCheckers.put(field, new PersonNamesChecker(databaseContext));\n }\n fieldCheckers.put(StandardField.BOOKTITLE, new BooktitleChecker());\n fieldCheckers.put(StandardField.TITLE, new BracketChecker());\n fieldCheckers.put(StandardField.TITLE, new TitleChecker(databaseContext));\n fieldCheckers.put(StandardField.DOI, new DoiValidityChecker());\n fieldCheckers.put(StandardField.EDITION, new EditionChecker(databaseContext, allowIntegerEdition));\n fieldCheckers.put(StandardField.FILE, new FileChecker(databaseContext, filePreferences));\n fieldCheckers.put(StandardField.HOWPUBLISHED, new HowPublishedChecker(databaseContext));\n fieldCheckers.put(StandardField.ISBN, new ISBNChecker());\n fieldCheckers.put(StandardField.ISSN, new ISSNChecker());\n fieldCheckers.put(StandardField.MONTH, new MonthChecker(databaseContext));\n fieldCheckers.put(StandardField.MONTHFILED, new MonthChecker(databaseContext));\n fieldCheckers.put(StandardField.NOTE, new NoteChecker(databaseContext));\n fieldCheckers.put(StandardField.PAGES, new PagesChecker(databaseContext));\n fieldCheckers.put(StandardField.URL, new UrlChecker());\n fieldCheckers.put(StandardField.YEAR, new YearChecker());\n fieldCheckers.put(StandardField.KEY, new ValidCitationKeyChecker());\n fieldCheckers.put(InternalField.KEY_FIELD, new ValidCitationKeyChecker());\n if (databaseContext.isBiblatexMode()) {\n fieldCheckers.put(StandardField.DATE, new DateChecker());\n fieldCheckers.put(StandardField.URLDATE, new DateChecker());\n fieldCheckers.put(StandardField.EVENTDATE, new DateChecker());\n fieldCheckers.put(StandardField.ORIGDATE, new DateChecker());\n }\n return fieldCheckers;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private InputSource resolveSchema(final String publicId, final String systemId) throws SAXException, IOException {\n // Schema files must end with xsd\n if (!systemId.toLowerCase().endsWith(\"xsd\")) {\n return null;\n }\n // Try and get the index for the filename, else return null\n String xsd;\n int index = systemId.lastIndexOf(\"/\");\n if (index == -1) {\n index = systemId.lastIndexOf(\"\\\\\");\n }\n if (index != -1) {\n xsd = systemId.substring(index + 1);\n } else {\n xsd = systemId;\n }\n // Try looking at root of classpath\n {\n InputStream is = ExtensibleXmlParser.class.getResourceAsStream(\"/\" + xsd);\n if (is != null) {\n return new InputSource(is);\n }\n }\n // Try looking in /META-INF\n {\n final InputStream is = ExtensibleXmlParser.class.getResourceAsStream(\"/META-INF/\" + xsd);\n if (is != null) {\n return new InputSource(is);\n }\n }\n // Try looking in META-INF\n {\n final InputStream is = ExtensibleXmlParser.class.getResourceAsStream(\"META-INF/\" + xsd);\n if (is != null) {\n return new InputSource(is);\n }\n }\n // Try current working directory\n {\n final File file = new File(xsd);\n if (file.exists()) {\n return new InputSource(new BufferedInputStream(new FileInputStream(file)));\n }\n }\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "public void verifyHSInfo(JSONObject info, AppContext ctx) throws JSONException {\n assertEquals(\"incorrect number of elements\", 4, info.length());\n verifyHsInfoGeneric(info.getString(\"hadoopVersionBuiltOn\"), info.getString(\"hadoopBuildVersion\"), info.getString(\"hadoopVersion\"), info.getLong(\"startedOn\"));\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmbTimesheetIntervalActionPerformed\nprivate void cmdAllowedPositionsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdAllowedPositionsActionPerformed\n if (this.currentEntry == null) {\n boolean saved = this.save();\n if (!saved)\n return;\n }\n TimesheetAllowedPositionsDialog dlg = new TimesheetAllowedPositionsDialog(this, true, this.currentEntry.getId());\n dlg.setTitle(\"erlaubte Positionsvorlagen ausw\u00e4hlen\");\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n this.updateAllowedPositions();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * @param grpId Group ID.\n * @return WAL enabled flag.\n */\npublic boolean walEnabled(int grpId, boolean local) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_mnuSearchRecipientActionPerformed\nprivate void cmdRecipientsCcActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRecipientsCcActionPerformed\n this.popRecipientsCc.show(this.cmdRecipientsCc, 0, 0);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public boolean quit(String line) {\n beeLine.setExit(true);\n close(null);\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_lblFolderNameMouseClicked\nprivate void lblExpandedMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblExpandedMouseClicked\n setSelected(!isSelected());\n this.parent.selectionChanged();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void cmdUseSelectionActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdUseSelectionActionPerformed\n if ((this.txtName.getText() == null || \"\".equals(this.txtName.getText())) && (this.txtCompany.getText() == null || \"\".equals(this.txtCompany.getText()))) {\n JOptionPane.showMessageDialog(this, \"Es muss mindestens ein Name oder ein Firmenname angegeben werden, um eine Adresse zu speichern.\", \"Adressen - G\u00fcltigkeitspr\u00fcfung\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n EditorsRegistry.getInstance().updateStatus(\"Adresse wird gespeichert...\");\n try {\n //InitialContext context = new InitialContext(settings.getLookupProperties());\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n AddressServiceRemote addressService = locator.lookupAddressServiceRemote();\n this.result = new AddressBean();\n this.fillDTO(this.result);\n List similarAddresses = addressService.similaritySearch(this.result, 0.85f);\n if (!similarAddresses.isEmpty()) {\n StringBuilder html = new StringBuilder();\n html.append(\"Es wurden ähnliche Einträge gefunden - trotzdem speichern?
\");\n html.append(\"
    \");\n for (AddressBean s : similarAddresses) {\n html.append(\"
  • \").append(s.toShortHtml(false)).append(\"
  • \");\n }\n html.append(\"
\");\n html.append(\"\");\n int simResponse = JOptionPane.showConfirmDialog(this, html.toString(), \"\u00c4hnlichkeitssuche\", JOptionPane.YES_NO_OPTION);\n if (simResponse == JOptionPane.NO_OPTION) {\n this.result = null;\n }\n }\n if (this.result != null) {\n this.result = addressService.createAddress(this.result);\n EditorsRegistry.getInstance().updateStatus(\"Adresse gespeichert.\", 5000);\n }\n } catch (Exception ex) {\n log.error(\"Error saving address\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n EditorsRegistry.getInstance().clearStatus();\n return;\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Process a 'restriction' element whose parent is 'simpleContent'.\n *\n * @param simpleRestriction\n */\nprivate void processSimpleRestriction(Element simpleRestriction) {\n // annotation?, simpleType?, (enumeration | length | maxExclusive | maxInclusive\n // | maxLength | minExclusive | minInclusive | minLength | pattern | fractionDigits\n // | totalDigits | whiteSpace)*, (attribute | attributeGroup)*, anyAttribute?\n // *** noop ***\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "private static void ST_MakeGridPoints(final Geometry geom, final BigDecimal deltaX, final BigDecimal deltaY){\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n String wordProcessor = ClientSettings.CONF_APPS_WORDPROCESSOR_VALUE_LO;\n if (this.rdMicrosoftOffice.isSelected()) {\n wordProcessor = ClientSettings.CONF_APPS_WORDPROCESSOR_VALUE_MSO;\n }\n ClientSettings.getInstance().setConfiguration(ClientSettings.CONF_APPS_WORDPROCESSOR_KEY, wordProcessor);\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void handlePartitions(String[] args){\r\n Set partitions = hazelcast.getPartitionService().getPartitions();\r\n Map partitionCounts = new HashMap<>();\r\n for (Partition partition : partitions) {\r\n Member owner = partition.getOwner();\r\n if (owner != null) {\r\n Integer count = partitionCounts.get(owner);\r\n int newCount = 1;\r\n if (count != null) {\r\n newCount = count + 1;\r\n }\r\n partitionCounts.put(owner, newCount);\r\n }\r\n println(partition);\r\n }\r\n Set> entries = partitionCounts.entrySet();\r\n for (Map.Entry entry : entries) {\r\n println(entry.getKey() + \": \" + entry.getValue());\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Iterator transformRawInputIterator(PTFPartitionIterator pItr) throws HiveException {\n if (!canIterateOutput()) {\n throw new HiveException(\"Internal error: iterator called on a PTF that cannot provide its output as an Iterator\");\n }\n throw new HiveException(String.format(\"Internal error: PTF %s, provides no iterator method\", getClass().getName()));\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_chkShowExternalUsersActionPerformed\nprivate void cmdPopulateFromCompanyProfileActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdPopulateFromCompanyProfileActionPerformed\n ServerSettings set = ServerSettings.getInstance();\n this.txtCity.setText(set.getSetting(ServerSettings.PROFILE_COMPANYCITY, \"\"));\n this.txtEmail.setText(set.getSetting(ServerSettings.PROFILE_COMPANYEMAIL, \"\"));\n this.txtFax.setText(set.getSetting(ServerSettings.PROFILE_COMPANYFAX, \"\"));\n this.txtMobile.setText(set.getSetting(ServerSettings.PROFILE_COMPANYMOBILE, \"\"));\n this.txtCompany.setText(set.getSetting(ServerSettings.PROFILE_COMPANYNAME, \"\"));\n this.txtPhone.setText(set.getSetting(ServerSettings.PROFILE_COMPANYPHONE, \"\"));\n this.txtStreet.setText(set.getSetting(ServerSettings.PROFILE_COMPANYSTREET, \"\"));\n this.txtAdjunct.setText(set.getSetting(ServerSettings.PROFILE_COMPANYSTREET2, \"\"));\n this.txtWebsite.setText(set.getSetting(ServerSettings.PROFILE_COMPANYWWW, \"\"));\n this.txtZipCode.setText(set.getSetting(ServerSettings.PROFILE_COMPANYZIP, \"\"));\n this.txtTaxNr.setText(set.getSetting(ServerSettings.PROFILE_COMPANYTAXID, \"\"));\n this.txtUstId.setText(set.getSetting(ServerSettings.PROFILE_COMPANYUSTID, \"\"));\n this.txtBank.setText(set.getSetting(ServerSettings.PROFILE_COMPANYBANK, \"\"));\n this.txtBic.setText(set.getSetting(ServerSettings.PROFILE_COMPANYBANKCODE, \"\"));\n this.txtIban.setText(set.getSetting(ServerSettings.PROFILE_COMPANYACCOUNTNO, \"\"));\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Main skeleton for list bucketing pruning.\n *\n * @param ctx\n * @param part\n * @param pruner\n * @return\n * @throws SemanticException\n */\nprivate static Path[] execute(ParseContext ctx, Partition part, ExprNodeDesc pruner) throws SemanticException {\n Path[] finalPaths;\n List selectedPaths = new ArrayList();\n if (ListBucketingPrunerUtils.isUnknownState(pruner)) {\n // Use full partition path for error case.\n LOG.warn(\"List bucketing pruner is either null or in unknown state \" + \" so that it uses full partition scan :\" + Arrays.toString(part.getPath()));\n finalPaths = part.getPath();\n } else {\n // Retrieve skewed columns.\n List> sVals = part.getSkewedColValues();\n assert ((sVals != null) && (sVals.size() > 0)) : part.getName() + \" skewed metadata is corrupted. No skewed value information.\";\n // Calculate collection.\n List> indexCollection = DynamicMultiDimensionalCollection.generateCollection(sVals);\n assert (indexCollection != null) : \"Collection is null.\";\n // Calculate unique skewed elements for each skewed column.\n List> uniqSkewValues = DynamicMultiDimensionalCollection.uniqueSkewedValueList(sVals);\n // Decide skewed value directory selection.\n List nonSkewedValueMatchResult = decideSkewedValueDirSelection(part, pruner, selectedPaths, indexCollection, uniqSkewValues);\n // Decide default directory selection.\n decideDefaultDirSelection(part, selectedPaths, nonSkewedValueMatchResult);\n // Finalize paths.\n finalPaths = generateFinalPath(part, selectedPaths);\n }\n return finalPaths;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public Operator getReducer(MapWork work) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void printReplacedSql(String content, String formatSql, String rgex, Map sqlParamsMap){\r\n log.info(\"after replace sql , preparing : {}\", formatSql);\r\n StringBuilder logPrint = new StringBuilder(\"replaced sql , parameters:\");\r\n if (sqlParamsMap == null) {\r\n log.info(\"printReplacedSql: sqlParamsMap is null.\");\r\n } else {\r\n for (int i = 1; i <= sqlParamsMap.size(); i++) {\r\n logPrint.append(sqlParamsMap.get(i).getValue()).append(\"(\").append(sqlParamsMap.get(i).getType()).append(\")\");\r\n }\r\n }\r\n log.info(\"Sql Params are {}\", logPrint);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Define any additional actions after getting all applications' basic information with pagination.\n * This method will be included in ApplicationMgtListener interface when Java 8 is supported.\n *\n * @param appDAO\n * @param tenantDomain\n * @param username\n * @return\n * @throws IdentityApplicationManagementException\n * @Deprecated The logic in pagination is improved to use an offset and a limit. Hence deprecating this method to\n * use {@link AbstractApplicationMgtListener#doPreGetApplicationBasicInfo(String, String, int, int)} method.\n */\npublic boolean doPostGetPaginatedApplicationBasicInfo(ApplicationDAO appDAO, String tenantDomain, String username, int pageNumber) throws IdentityApplicationManagementException {\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private HoodieCommitMetadata createCommitMetadata(String instantTime, String writeFileName, String partition) {\n HoodieCommitMetadata commitMetadata = new HoodieCommitMetadata();\n commitMetadata.addMetadata(\"test\", \"test\");\n HoodieWriteStat writeStat = new HoodieWriteStat();\n writeStat.setFileId(writeFileName);\n commitMetadata.addWriteStat(partition, writeStat);\n commitMetadata.setOperationType(WriteOperationType.INSERT);\n return commitMetadata;\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private List makeBasicArgs(String execute, String srcFile, String otherFiles, String statusdir, String completedUrl, boolean enablelog, Boolean enableJobReconnect) throws URISyntaxException, IOException, InterruptedException{\r\n ArrayList args = new ArrayList();\r\n ArrayList allFiles = new ArrayList();\r\n if (TempletonUtils.isset(srcFile)) {\r\n allFiles.add(TempletonUtils.hadoopFsFilename(srcFile, appConf, runAs));\r\n }\r\n if (TempletonUtils.isset(otherFiles)) {\r\n String[] ofs = TempletonUtils.hadoopFsListAsArray(otherFiles, appConf, runAs);\r\n allFiles.addAll(Arrays.asList(ofs));\r\n }\r\n args.addAll(makeLauncherArgs(appConf, statusdir, completedUrl, allFiles, enablelog, enableJobReconnect, JobType.HIVE));\r\n if (appConf.hiveArchive() != null && !appConf.hiveArchive().equals(\"\")) {\r\n args.add(ARCHIVES);\r\n args.add(appConf.hiveArchive());\r\n }\r\n String extras = appConf.get(AppConfig.HIVE_EXTRA_FILES);\r\n if (extras != null && extras.length() > 0) {\r\n boolean foundFiles = false;\r\n for (int i = 0; i < args.size(); i++) {\r\n if (FILES.equals(args.get(i))) {\r\n String value = args.get(i + 1);\r\n args.set(i + 1, value + \",\" + extras);\r\n foundFiles = true;\r\n }\r\n }\r\n if (!foundFiles) {\r\n args.add(FILES);\r\n args.add(extras);\r\n }\r\n String[] extraFiles = appConf.getStrings(AppConfig.HIVE_EXTRA_FILES);\r\n StringBuilder extraFileNames = new StringBuilder();\r\n for (String file : extraFiles) {\r\n Path p = new Path(file);\r\n extraFileNames.append(p.getName()).append(\",\");\r\n }\r\n addDef(args, JobSubmissionConstants.HADOOP_CLASSPATH_EXTRAS, extraFileNames.toString());\r\n }\r\n return args;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Shuttle preVisit(MethodDeclaration methodDeclaration){\n return this;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_formComponentResized\nprivate void chkOnlyMineActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_chkOnlyMineActionPerformed\n if (this.chkOnlyMine.isSelected()) {\n this.principalId = UserSettings.getInstance().getCurrentUser().getPrincipalId();\n } else {\n this.principalId = null;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void extractOperands(final OperandManager operandManager, final Segment segment, final int codeLength){\r\n final ByteCodeForm currentByteCodeForm = getByteCodeForm();\r\n currentByteCodeForm.setByteCodeOperands(this, operandManager, codeLength);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected URI getDefaultFaultAction(Object endpoint, MessageAddressingProperties requestMap){\n URI requestAction = requestMap.getAction();\n if (requestAction != null) {\n return URI.create(requestAction.toString() + getFaultActionSuffix());\n } else {\n return null;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseForProperty(Property parentObj, String parentTag, String qName, Attributes attributes) throws SAXException{\r\n objects.push(parentObj);\r\n tags.push(qName);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static RexNode swapColumnTableReferences(final RexBuilder rexBuilder, final RexNode node, final Map> ec, @Nullable final Map tableMapping){\r\n RexShuttle visitor = new RexShuttle() {\r\n\r\n @Override\r\n public RexNode visitTableInputRef(RexTableInputRef inputRef) {\r\n if (ec != null) {\r\n Set s = ec.get(inputRef);\r\n if (s != null) {\r\n inputRef = s.iterator().next();\r\n }\r\n }\r\n if (tableMapping != null) {\r\n RexTableInputRef inputRefFinal = inputRef;\r\n inputRef = RexTableInputRef.of(requireNonNull(tableMapping.get(inputRef.getTableRef()), () -> \"tableMapping.get(...) for \" + inputRefFinal.getTableRef()), inputRef.getIndex(), inputRef.getType());\r\n }\r\n return inputRef;\r\n }\r\n };\r\n return visitor.apply(node);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Adds the minimal amount of packages to the channel for the channel to be a\n * valid kickstart channel.\n * @param c The channel to which to add kickstart packages.\n * @param rhel2 Whether to include rhel2 required packages.\n * @throws Exception for creating packages.\n */\npublic static void addKickstartPackagesToChannel(Channel c, boolean rhel2) throws Exception {\n addPackages(c, KickstartFormatter.UPDATE_PKG_NAMES);\n PackageManagerTest.addPackageToChannel(ConfigDefaults.get().getKickstartPackageNames().get(0) + \"testy\", c);\n PackageManagerTest.addPackageToChannel(KickstartData.LEGACY_KICKSTART_PACKAGE_NAME + KickstartableTreeTest.TEST_BOOT_PATH, c);\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "/**\n * Check arrays equality as well as objects equality.\n */\nprotected static void assertEqualsArraysAware(String msg, Object exp, Object actual) {\n if (exp instanceof Object[] && actual instanceof Object[])\n Assert.assertArrayEquals((Object[]) exp, (Object[]) actual);\n else if (U.isPrimitiveArray(exp) && U.isPrimitiveArray(actual))\n // Hack to compare primitive arrays.\n Assert.assertArrayEquals(new Object[] { exp }, new Object[] { actual });\n else\n Assert.assertEquals(exp, actual);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private void convert(Context context, GtfsAgency gtfsAgency, Company company, OrganisationTypeEnum organisationType){\r\n company.setName(AbstractConverter.getNonEmptyTrimedString(gtfsAgency.getAgencyName()));\r\n company.setUrl(AbstractConverter.toString(gtfsAgency.getAgencyUrl()));\r\n company.setPhone(AbstractConverter.getNonEmptyTrimedString(gtfsAgency.getAgencyPhone()));\r\n String[] token = company.getObjectId().split(\":\");\r\n company.setRegistrationNumber(token[2]);\r\n company.setTimeZone(AbstractConverter.toString(gtfsAgency.getAgencyTimezone()));\r\n company.setOrganisationType(organisationType);\r\n company.setFilled(true);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdToEditModeActionPerformed\nprivate void cmdBackToSearchActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdBackToSearchActionPerformed\n try {\n Object editor = EditorsRegistry.getInstance().getEditor(this.openedFromEditorClass);\n EditorsRegistry.getInstance().setMainEditorsPaneView((Component) editor);\n } catch (Exception ex) {\n log.error(\"Error creating editor from class \" + this.openedFromEditorClass, ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Editors: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdArchiveActionPerformed\nprivate void chkCalendarActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_chkCalendarActionPerformed\n this.enableArchival();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n */\nprotected RelNode originalLogicalTree(String sql, IgniteSchema publicSchema, String... disabledRules) throws Exception {\n PlanningContext ctx = plannerCtx(sql, publicSchema);\n RelRoot relRoot;\n try (IgnitePlanner planner = ctx.planner()) {\n assertNotNull(planner);\n String qry = ctx.query();\n assertNotNull(qry);\n // Parse\n SqlNode sqlNode = planner.parse(qry);\n // Validate\n sqlNode = planner.validate(sqlNode);\n // Convert to Relational operators graph\n relRoot = planner.rel(sqlNode);\n RelNode rel = relRoot.rel;\n assertNotNull(rel);\n return rel;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private static FullBlock createGenesis(Net n){\n FullBlock genesis = new FullBlockBean();\n genesis.setVersion(BitcoinJ.BLOCK_VERSION_GENESIS);\n genesis.setDifficultyTarget(0x1d07fff8L);\n genesis.setPrevBlockHash(Sha256Hash.ZERO_HASH);\n genesis.setTime(System.currentTimeMillis() / 1000);\n Tx coinbase = new TxBean(genesis);\n try {\n byte[] bytes = Utils.HEX.decode(\"04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73\");\n TxInput input = new TxInputBean(coinbase);\n TxOutPoint outPoint = new TxOutPointBean(input);\n outPoint.setHash(Sha256Hash.ZERO_HASH);\n outPoint.setIndex(TxOutPoint.UNCONNECTED);\n input.setScriptBytes(bytes);\n input.setSequenceNumber(TxInput.NO_SEQUENCE);\n input.setOutpoint(outPoint);\n coinbase.getInputs().add(input);\n ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();\n ScriptChunk.writeBytes(scriptPubKeyBytes, Utils.HEX.decode(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f\"));\n scriptPubKeyBytes.write(ScriptOpCodes.OP_CHECKSIG);\n TxOutput output = new TxOutputBean(coinbase);\n output.setScriptBytes(scriptPubKeyBytes.toByteArray());\n output.setValue(Coin.FIFTY_COINS);\n coinbase.getOutputs().add(output);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n genesis.getTransactions().add(coinbase);\n return genesis;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_treeFoldersMouseReleased\nprivate void mnuNewFolderActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuNewFolderActionPerformed\n DefaultMutableTreeNode tn = (DefaultMutableTreeNode) this.treeFolders.getSelectionPath().getLastPathComponent();\n FolderContainer folderC = (FolderContainer) tn.getUserObject();\n Object newNameObject = JOptionPane.showInputDialog(this, \"Name des Ordners: \", \"Neuen Ordner anlegen\", JOptionPane.QUESTION_MESSAGE, null, null, \"neuer Ordner\");\n if (newNameObject == null) {\n return;\n }\n try {\n Folder f = folderC.getFolder();\n if (!f.isOpen()) {\n f.open(Folder.READ_WRITE);\n }\n Folder newFolder = f.getFolder(newNameObject.toString());\n boolean created = false;\n if (!newFolder.exists()) {\n created = newFolder.create(Folder.HOLDS_MESSAGES);\n }\n if (created) {\n FolderContainer fc = new FolderContainer(newFolder);\n DefaultMutableTreeNode newTn = new DefaultMutableTreeNode(fc);\n DefaultTreeModel dm = (DefaultTreeModel) this.treeFolders.getModel();\n dm.insertNodeInto(newTn, tn, 0);\n }\n try {\n EmailUtils.closeIfIMAP(f);\n } catch (Throwable t) {\n log.error(t);\n }\n } catch (Exception ex) {\n log.error(ex);\n JOptionPane.showMessageDialog(this, \"Ordner anlegen fehlgeschlagen: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected boolean onEventDropped(final DroppedEvent event, final CalendarResponse response){\r\n return false;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n int[] rows = this.tblMappingTables.getSelectedRows();\n Arrays.sort(rows);\n for (int i = rows.length - 1; i > -1; i--) {\n int r = rows[i];\n r = this.tblMappingTables.convertRowIndexToModel(r);\n ((DefaultTableModel) this.tblMappingTables.getModel()).removeRow(r);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtDirectoryKeyTyped\nprivate void radioSmbItemStateChanged(java.awt.event.ItemEvent evt) {\n //GEN-FIRST:event_radioSmbItemStateChanged\n this.updateTarget();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void collectParentEvidence(JunctionTreeClique clique, JunctionTreeSeparator sep, JunctionTreeClique child, JunctionTreeClique startClique){\r\n if (clique.getParentSeparator() != null) {\r\n collectParentEvidence(clique.getParentSeparator().getParent(), clique.getParentSeparator(), clique, startClique);\r\n }\r\n List seps = clique.getChildren();\r\n for (JunctionTreeSeparator childSep : seps) {\r\n if (childSep.getChild() == child) {\r\n continue;\r\n }\r\n collectChildEvidence(childSep.getChild(), startClique);\r\n }\r\n passMessage(clique, child.getParentSeparator(), child);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException{\r\n response.setContentType(\"text/html;charset=UTF-8\");\r\n try {\r\n Thread.sleep(60000);\r\n } catch (InterruptedException ignore) {\r\n }\r\n try (PrintWriter out = response.getWriter()) {\r\n out.println(\"OK\");\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_lblDescriptionMouseClicked\nprivate void cmdRenameActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRenameActionPerformed\n this.executor.renameCallback();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void updateRecord(Data key, CacheRecord record, long expiryTime, long now, UUID origin){\n record.setExpirationTime(expiryTime);\n invalidateEntry(key, origin);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Builder builder(Class itemClass, Class builderClass, Class attributeClass){\n return new Builder<>(EnhancedType.of(attributeClass));\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void removeMemberObject(String name) {\n LOG.warn(\"Step is readonly, hence the can't remove the member.\");\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdSearchRecipientMousePressed\nprivate void cmdCreateInvoiceDocumentActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCreateInvoiceDocumentActionPerformed\n if (this.caseView != null) {\n if (this.currentEntry != null) {\n this.save();\n }\n if (this.currentEntry.getSender() == null) {\n JOptionPane.showMessageDialog(this, \"Es ist kein Rechnungssender definiert, E-Rechnung kann nicht erstellt werden.\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_WARNING, JOptionPane.WARNING_MESSAGE);\n return;\n }\n // by default, create document from document template\n int choice = 0;\n // if the invoice type indicates a real invoice where there is a turnover, we need to create an electronic invoice\n if (this.currentEntry.getInvoiceType().isTurnOver()) {\n // Options to display\n String[] options = { \"Elektronische Rechnung (an Unternehmen)\", \"XRechnung (an \u00f6ffentliche Auftraggeber)\" };\n // Show option dialog\n choice = JOptionPane.showOptionDialog(// Parent component (null for no parent)\n this, // Message to display\n \"Rechnung erstellen als:\", // Title of the dialog\n \"Rechnungsdokument erstellen\", // Option type (default for custom buttons)\n JOptionPane.DEFAULT_OPTION, // Message type (question icon)\n JOptionPane.QUESTION_MESSAGE, // Icon (null for default icon)\n null, // Options array\n options, // Initial value (default selection)\n options[0]);\n if (choice < 0) {\n return;\n }\n }\n AppUserBean senderUser = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n senderUser = locator.lookupSystemManagementRemote().getUser(currentEntry.getSender());\n if (senderUser == null) {\n JOptionPane.showMessageDialog(this, \"Rechnungssender '\" + currentEntry.getSender() + \" kann nicht gefunden werden.\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_WARNING, JOptionPane.WARNING_MESSAGE);\n return;\n }\n } catch (Exception ex) {\n log.error(\"error getting invoice sender\", ex);\n JOptionPane.showMessageDialog(this, \"Rechnungssender '\" + currentEntry.getSender() + \" kann nicht gefunden werden: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n if (choice == 0) {\n // generate document via template system\n // upon PDF creation, embed XRechnung XML\n StyledCalculationTable timesheetPosTable = null;\n StyledCalculationTable timesheetSummaryTable = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n List times = locator.lookupArchiveFileServiceRemote().getTimesheetPositionsForInvoice(this.currentEntry.getId());\n timesheetPosTable = this.getTimesheetPositionsAsTable(times, this.cmbTableHeadersLanguage.getSelectedItem().toString());\n timesheetSummaryTable = this.getTimesheetSummaryAsTable(times, this.cmbTableHeadersLanguage.getSelectedItem().toString());\n } catch (Exception ex) {\n log.error(\"error getting timesheet positions table\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden Zeiterfassungspositionen: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n byte[] giroCode = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n if (this.currentEntry != null) {\n giroCode = locator.lookupInvoiceServiceRemote().getGiroCode(this.currentEntry.getSender(), this.currentEntry.getTotalGross(), this.currentEntry.getInvoiceNumber());\n }\n } catch (Exception ex) {\n log.error(\"error generating girocode\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n ArchiveFileDocumentsBean invoiceDoc = this.caseView.newDocumentDialog(null, currentEntry, senderUser, this.getInvoicePositionsAsTable(this.cmbTableHeadersLanguage.getSelectedItem().toString()), timesheetPosTable, timesheetSummaryTable, giroCode, null);\n if (invoiceDoc != null && this.currentEntry != null) {\n this.save();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n ArchiveFileDocumentsBean doc = locator.lookupArchiveFileServiceRemote().getInvoiceDocument(currentEntry.getId());\n currentEntry.setInvoiceDocument(doc);\n this.lblInvoiceDocument.setText(doc.getName());\n this.lblInvoiceDocument.setIcon(FileUtils.getInstance().getFileTypeIcon(doc.getName()));\n this.lblInvoiceDocumentChanged.setText(df.format(doc.getChangeDate()));\n this.lblInvoiceDocumentCreated.setText(df.format(doc.getCreationDate()));\n } catch (Exception ex) {\n log.error(\"error loading invoice document\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Belegdokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.cmdViewDocument.setEnabled(true);\n this.cmdNavigateToDocument.setEnabled(true);\n }\n } else {\n org.mustangproject.Invoice i = null;\n try {\n i = EInvoiceUtils.getEInvoice(this.currentEntry, senderUser);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n ZUGFeRD2PullProvider zf2p = new ZUGFeRD2PullProvider();\n zf2p.setProfile(Profiles.getByName(\"XRechnung\"));\n zf2p.generateXML(i);\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n ArchiveFileServiceRemote afs = locator.lookupArchiveFileServiceRemote();\n String newName = FileUtils.sanitizeFileName(\"XRechnung-\" + this.currentEntry.getInvoiceNumber() + \".xml\");\n String updatedName = newName;\n boolean documentExists = afs.doesDocumentExist(this.currentEntry.getArchiveFileKey().getId(), newName);\n while (documentExists) {\n updatedName = FileUtils.getNewFileName(this.currentEntry.getArchiveFileKey(), newName, new Date(), true, this, \"neuer Dateiname\");\n if (updatedName == null || \"\".equals(updatedName)) {\n EditorsRegistry.getInstance().clearStatus(true);\n break;\n }\n documentExists = afs.doesDocumentExist(this.currentEntry.getArchiveFileKey().getId(), updatedName);\n }\n if (!StringUtils.isEmpty(updatedName)) {\n final ArchiveFileDocumentsBean doc = afs.addDocument(this.currentEntry.getArchiveFileKey().getId(), updatedName, zf2p.getXML(), null, null);\n afs.linkInvoiceDocument(doc.getId(), this.currentEntry.getId());\n currentEntry.setInvoiceDocument(doc);\n this.lblInvoiceDocument.setText(doc.getName());\n this.lblInvoiceDocument.setIcon(FileUtils.getInstance().getFileTypeIcon(doc.getName()));\n this.lblInvoiceDocumentChanged.setText(df.format(doc.getChangeDate()));\n this.lblInvoiceDocumentCreated.setText(df.format(doc.getCreationDate()));\n EventBroker eb = EventBroker.getInstance();\n eb.publishEvent(new DocumentAddedEvent(doc, this.currentEntry));\n }\n this.cmdViewDocument.setEnabled(true);\n this.cmdNavigateToDocument.setEnabled(true);\n } catch (Exception ex) {\n log.error(\"Error storing XRechnung document\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern der elektronischen Rechnung: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void runningJob(Job job) {\n jobsRunning.incr();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n * Check if specified filter compare specified column to not null.\n *\n * @param ses Session to resolve values.\n * @param column Column to check.\n * @param filter Table filter.\n * @return {@code true} if column value should be null, {@code falce} otherwise (or if it not sure).\n */\nprivate boolean isNotNullFilter(Session ses, Column column, TableFilter filter) {\n // TODO: IGNITE-14813 check not null expression (TableFilter contains only fullCondition without getter to check it)\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void txtBodyKeyPressed(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtBodyKeyPressed\n if (txtBody.getText().length() > 460)\n txtBody.setText(txtBody.getText().substring(0, 459));\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * RS-Gb1\n *\n * @param inputOpAf\n * @param aggRel\n * @param gbInfo\n * @return\n * @throws SemanticException\n */\nprivate static OpAttr genNoMapSideGBNoSkew(OpAttr inputOpAf, HiveAggregate aggRel, GBInfo gbInfo) throws SemanticException {\n OpAttr mapSideRS = null;\n OpAttr reduceSideGB1NoMapGB = null;\n // 1. Insert MapSide RS\n mapSideRS = genMapSideRS(inputOpAf, gbInfo);\n // 2. Insert ReduceSide GB\n reduceSideGB1NoMapGB = genReduceSideGB1NoMapGB(mapSideRS, gbInfo, GroupByDesc.Mode.COMPLETE);\n return reduceSideGB1NoMapGB;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public int getSilverObjectId(String objectId){\n return Integer.parseInt(getCurrentCardContentId());\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setLinks(String guid, StatisticsResource resource, URI baseUri) {\n // no links needed\n}", "smellKey": "S1172", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "protected void unsetAPIResourceManagementService(APIResourceManager apiResourceManagementService) {\n APIResourceCollectionMgtServiceDataHolder.getInstance().setAPIResourceManagementService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "/**\n * Returns EXPLAIN EXTENDED output for a semantically analyzed query.\n *\n * @param sem semantic analyzer for analyzed query\n * @param plan query plan\n * @param astTree AST tree dump\n */\npublic static String getExplainOutput(BaseSemanticAnalyzer sem, QueryPlan plan, ASTNode astTree, QueryState queryState, Context context, HiveConf conf) throws IOException {\n String ret = null;\n ExplainTask task = new ExplainTask();\n task.initialize(queryState, plan, null, context);\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n PrintStream ps = new PrintStream(baos);\n try {\n List> rootTasks = sem.getAllRootTasks();\n if (conf.getBoolVar(ConfVars.HIVE_SERVER2_WEBUI_SHOW_GRAPH)) {\n JSONObject jsonPlan = task.getJSONPlan(null, rootTasks, sem.getFetchTask(), true, conf.getBoolVar(ConfVars.HIVE_LOG_EXPLAIN_OUTPUT_INCLUDE_EXTENDED), true, sem.getCboInfo(), plan.getOptimizedCBOPlan(), plan.getOptimizedQueryString());\n if (jsonPlan.getJSONObject(ExplainTask.STAGE_DEPENDENCIES) != null && jsonPlan.getJSONObject(ExplainTask.STAGE_DEPENDENCIES).length() <= conf.getIntVar(ConfVars.HIVE_SERVER2_WEBUI_MAX_GRAPH_SIZE)) {\n ret = jsonPlan.toString();\n } else {\n ret = null;\n }\n } else {\n task.getJSONPlan(ps, rootTasks, sem.getFetchTask(), false, true, true, sem.getCboInfo(), plan.getOptimizedCBOPlan(), plan.getOptimizedQueryString());\n ret = baos.toString();\n }\n } catch (Exception e) {\n LOG.warn(\"Exception generating explain output: \" + e, e);\n }\n return ret;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_selectAll\nprivate void cmdToCaseActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdToCaseActionPerformed\n Object value = null;\n if (this.tblQueue.getSelectedRowCount() == 1) {\n value = this.tblQueue.getValueAt(this.tblQueue.getSelectedRow(), 0);\n }\n String caseId = null;\n if (value instanceof MailingQueueEntry) {\n MailingQueueEntry mqe = (MailingQueueEntry) value;\n if (mqe.getCase() != null) {\n caseId = mqe.getCase().getId();\n }\n }\n if (caseId == null)\n return;\n try {\n Object editor = null;\n if (UserSettings.getInstance().isCurrentUserInRole(UserSettings.ROLE_WRITECASE)) {\n editor = EditorsRegistry.getInstance().getEditor(EditArchiveFileDetailsPanel.class.getName());\n } else {\n editor = EditorsRegistry.getInstance().getEditor(ViewArchiveFileDetailsPanel.class.getName());\n }\n Object opener = EditorsRegistry.getInstance().getEditor(this.getClass().getName());\n if (editor instanceof ThemeableEditor && opener instanceof ThemeableEditor) {\n // inherit the background to newly created child editors\n ((ThemeableEditor) editor).setBackgroundImage(((ThemeableEditor) opener).getBackgroundImage());\n }\n if (editor instanceof PopulateOptionsEditor) {\n ((PopulateOptionsEditor) editor).populateOptions();\n }\n ArchiveFileBean aFile = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n ArchiveFileServiceRemote fileService = locator.lookupArchiveFileServiceRemote();\n aFile = fileService.getArchiveFile(caseId);\n } catch (Exception ex) {\n log.error(\"Error loading archive file from server\", ex);\n JOptionPane.showMessageDialog(this, java.text.MessageFormat.format(java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/editors/addresses/CaseForContactEntryPanel\").getString(\"error.loadingcase\"), new Object[] { ex.getMessage() }), java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/editors/addresses/CaseForContactEntryPanel\").getString(\"dialog.error\"), JOptionPane.ERROR_MESSAGE);\n }\n if (aFile == null) {\n return;\n }\n ((ArchiveFilePanel) editor).setArchiveFileDTO(aFile);\n ((ArchiveFilePanel) editor).setOpenedFromEditorClass(this.getClass().getName());\n EditorsRegistry.getInstance().setMainEditorsPaneView((Component) editor);\n } catch (Exception ex) {\n log.error(\"Error creating editor from class \" + this.getClass().getName(), ex);\n JOptionPane.showMessageDialog(this, java.text.MessageFormat.format(java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/editors/addresses/CaseForContactEntryPanel\").getString(\"error.loadingeditor\"), new Object[] { ex.getMessage() }), java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/editors/addresses/CaseForContactEntryPanel\").getString(\"dialog.error\"), JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void writeLong(long l, String tag) throws IOException {\n out.writeLong(l);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_mnuCopyFilesToClipboardActionPerformed\nprivate void mnuSendEpostLetterActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSendEpostLetterActionPerformed\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n ArrayList open = this.getDocumentsOpenForWrite(selectedDocs);\n if (!open.isEmpty()) {\n String question = \"Soll die Aktion auf ge\u00f6ffnete Dokumente ausgef\u00fchrt werden? Es besteht das Risiko fehlender / inkonsistenter Inhalte.
    \";\n for (String o : open) {\n question = question + \"
  • \" + o + \"
  • \";\n }\n question = question + \"
\";\n int response = JOptionPane.showConfirmDialog(this, question, \"Aktion auf offene Dokumente ausf\u00fchren\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n return;\n }\n }\n EpostWizardDialog dlg = new EpostWizardDialog(EditorsRegistry.getInstance().getMainWindow(), true);\n WizardSteps steps = new WizardSteps(dlg);\n WizardDataContainer data = steps.getData();\n data.put(\"epost.letter.documents\", selectedDocs);\n data.put(\"epost.letter.caseid\", this.dto.getId());\n List addresses = new ArrayList<>();\n for (ArchiveFileAddressesBean aab : this.pnlInvolvedParties.getInvolvedParties()) {\n addresses.add(aab.getAddressKey());\n }\n data.put(\"epost.letter.addresses\", addresses);\n steps.addStep(new EpostPdfConversionStep());\n steps.addStep(new EpostPdfOrderingStep());\n steps.addStep(new EpostPdfMergeStep());\n steps.addStep(new EpostLetterValidationStep());\n steps.addStep(new EpostLetterSendStep());\n steps.addStep(new EpostLetterSendStatus());\n dlg.setSteps(steps);\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdNameTemplateMouseReleased\nprivate void txtNewNameFocusGained(java.awt.event.FocusEvent evt) {\n //GEN-FIRST:event_txtNewNameFocusGained\n int dotPos = this.txtNewName.getText().lastIndexOf(\".\");\n this.txtNewName.requestFocusInWindow();\n if (dotPos > -1) {\n this.txtNewName.setSelectionStart(0);\n this.txtNewName.setSelectionEnd(dotPos);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Build a map of all of the pipelines in the project.\n *\n * @throws IOException\n */\nprivate void buildPipelineMap(IVariables variables) throws IOException, HopFileException {\n pipelineTransformsMap = new HashMap<>();\n pipelinePaths = new ArrayList<>();\n File projectFolder = new File(String.valueOf(HopVfs.getFileObject(configFilename).getParent().getPath()));\n if (projectFolder.isDirectory()) {\n try (Stream walk = Files.walk(projectFolder.toPath())) {\n pipelinePaths = walk.filter(p -> !Files.isDirectory(p)).filter(f -> f.getFileName().toString().toLowerCase().endsWith(\"hpl\")).collect(Collectors.toList());\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected void defaultClick(Driver driver, WebElement element){\r\n element.click();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean init(ITransform transformMetaInterface, ITransformData iTransformData) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public boolean isExpired(final SnapSyncProcessState snapSyncState){\r\n return false;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_mnuDisableCaseSyncActionPerformed\nprivate void mnuDuplicateSelectedArchiveFilesWithFormsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuDuplicateSelectedArchiveFilesWithFormsActionPerformed\n this.duplicateSelectedArchiveFiles(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void getExtractFromAttr(DOMClass lClass, PrintWriter prPVL) {\n if (lClass.steward.compareTo(\"ops\") == 0) {\n return;\n }\n DOMAttr lAttr = null;\n for (Iterator i = lClass.ownedAttrArr.iterator(); i.hasNext(); ) {\n DOMProp lProp = i.next();\n if (!lProp.isAttribute) {\n continue;\n }\n lAttr = (DOMAttr) lProp.hasDOMObject;\n if (lAttr.title.indexOf(\"standard_id\") < 0) {\n continue;\n }\n if (!lAttr.permValueArr.isEmpty()) {\n for (Iterator j = lAttr.permValueArr.iterator(); j.hasNext(); ) {\n PermValueDefn lPermValueDefn = j.next();\n // PVLStmt = lClass.title + \" - \" + lAttr.title + \" - \" + lPermValueDefn.value + \" - \" +\n // lPermValueDefn.value_meaning;\n // PVLStmt = lPermValueDefn.value + \" - \" + lPermValueDefn.value_meaning + \" - \" +\n // lClass.title + \" - \" + lAttr.title;\n PVLStmt = delBeg + lPermValueDefn.value + del + lPermValueDefn.value_meaning + del + lClass.title + del + lAttr.title + delEnd;\n lineNum++;\n lineNumI = new Integer(lineNum);\n // lReportStatementMap.put(lPermValueDefn.value + \".\" + lineNumI, PVLStmt);\n lReportStatementMap.put(PVLStmt, PVLStmt);\n // prPVL.println(PVLStmt);\n }\n }\n }\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "private void buildPartial0(org.jbpm.flow.serialization.protobuf.KogitoTypesProtobuf.WorkflowContext result) {\n int from_bitField0_ = bitField0_;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "private void prepareOnFirstRow(Object[] row) throws HopException {\n data.rowParametersList = new ArrayList<>();\n data.inputRowsList = new ArrayList<>();\n data.outputRowMeta = getInputRowMeta().clone();\n meta.getFields(data.outputRowMeta, getTransformName(), null, null, this, metadataProvider);\n // Go over all the rowParameters, see where they are in the input row.\n //\n data.parameterIndexes = new ArrayList<>();\n data.parameterTypes = new ArrayList<>();\n for (Parameter parameter : meta.getParameters()) {\n int index = getInputRowMeta().indexOfValue(parameter.getInputFieldName());\n if (index < 0) {\n throw new HopException(\"Input field of parameter \" + parameter.getName() + \" could not be found\");\n }\n data.parameterIndexes.add(index);\n // This defaults to String\n GraphPropertyType propertyType = GraphPropertyType.parseCode(Const.NVL(parameter.getNeoType(), \"\"));\n if (propertyType == null) {\n throw new HopException(\"Unable to convert to unknown property type for parameter '\" + parameter.getName() + \"', input field: \" + parameter.getInputFieldName());\n }\n data.parameterTypes.add(propertyType);\n }\n data.unwindAlias = resolve(meta.getUnwindAlias());\n // Look for return values in the operations...\n //\n data.outputValues = new ArrayList<>();\n data.outputIndexes = new ArrayList<>();\n data.neoTypes = new ArrayList<>();\n int startIndex;\n if (StringUtils.isEmpty(data.unwindAlias)) {\n startIndex = getInputRowMeta().size();\n } else {\n startIndex = 0;\n }\n for (int index = startIndex; index < data.outputRowMeta.size(); index++) {\n data.outputIndexes.add(index);\n IValueMeta valueMeta = data.outputRowMeta.getValueMeta(index);\n data.outputValues.add(valueMeta);\n // No error here, defaults to String\n GraphPropertyDataType neoType = GraphPropertyDataType.parseCode(valueMeta.getComments());\n data.neoTypes.add(neoType);\n }\n data.batchSize = Const.toInt(resolve(meta.getBatchSize()), 1);\n data.cypher = meta.getCypher(this);\n data.needsWriteTransaction = meta.needsWriteTransaction();\n int retries = Const.toInt(resolve(meta.getRetries()), 0);\n if (retries < 0) {\n throw new HopException(\"The number of retries on an error should be larger than or equal to 0, not \" + retries);\n }\n data.attempts = 1 + retries;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected final PipeForward determineForward(ValidationResult validationResult, PipeLineSession session, boolean responseMode, Supplier errorMessageProvider) throws PipeRunException {\n throwEvent(validationResult.getEvent());\n PipeForward forward = null;\n switch(validationResult) {\n case VALID_WITH_WARNINGS:\n if (responseMode) {\n forward = findForward(\"outputWarnings\");\n }\n if (forward == null) {\n forward = findForward(\"warnings\");\n }\n if (forward == null) {\n forward = getSuccessForward();\n }\n return forward;\n case VALID:\n return getSuccessForward();\n case PARSER_ERROR:\n if (responseMode) {\n forward = findForward(\"outputParserError\");\n }\n if (forward == null) {\n forward = findForward(\"parserError\");\n }\n //$FALL-THROUGH$\n case INVALID:\n if (forward == null) {\n if (responseMode) {\n forward = findForward(\"outputFailure\");\n }\n if (forward == null) {\n forward = findForward(\"failure\");\n }\n }\n if (forward == null) {\n if (isForwardFailureToSuccess()) {\n forward = getSuccessForward();\n } else {\n throw new PipeRunException(this, errorMessageProvider.get());\n }\n }\n return forward;\n default:\n throw new IllegalStateException(\"Unknown validationResult [\" + validationResult + \"]\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "public static ScannableTable eval(boolean b){\n return new ScannableTable() {\n\n @Override\n public Enumerable scan(DataContext root) {\n final InputStream is = DataContext.Variable.STDIN.get(root);\n return new AbstractEnumerable() {\n\n final InputStreamReader in = new InputStreamReader(is, StandardCharsets.UTF_8);\n\n final BufferedReader br = new BufferedReader(in);\n\n @Override\n public Enumerator enumerator() {\n return new Enumerator() {\n\n @Nullable\n String line;\n\n int i;\n\n @Override\n public Object[] current() {\n if (line == null) {\n throw new NoSuchElementException();\n }\n return new Object[] { i, line };\n }\n\n @Override\n public boolean moveNext() {\n try {\n line = br.readLine();\n ++i;\n return line != null;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public void reset() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void close() {\n try {\n br.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n };\n }\n };\n }\n\n @Override\n public RelDataType getRowType(RelDataTypeFactory typeFactory) {\n return typeFactory.builder().add(\"ordinal\", SqlTypeName.INTEGER).add(\"line\", SqlTypeName.VARCHAR).build();\n }\n\n @Override\n public Statistic getStatistic() {\n return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));\n }\n\n @Override\n public Schema.TableType getJdbcTableType() {\n return Schema.TableType.TABLE;\n }\n\n @Override\n public boolean isRolledUp(String column) {\n return false;\n }\n\n @Override\n public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable CalciteConnectionConfig config) {\n return true;\n }\n };\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_lblTagsMouseExited\nprivate void lblTagsMouseEntered(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblTagsMouseEntered\n highlight(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": " static String columnClassName(Type hiveType, JdbcColumnAttributes columnAttributes) throws SQLException{\n int columnType = hiveTypeToSqlType(hiveType);\n switch(columnType) {\n case Types.NULL:\n return \"null\";\n case Types.BOOLEAN:\n return Boolean.class.getName();\n case Types.CHAR:\n case Types.VARCHAR:\n return String.class.getName();\n case Types.TINYINT:\n return Byte.class.getName();\n case Types.SMALLINT:\n return Short.class.getName();\n case Types.INTEGER:\n return Integer.class.getName();\n case Types.BIGINT:\n return Long.class.getName();\n case Types.DATE:\n return Date.class.getName();\n case Types.FLOAT:\n return Float.class.getName();\n case Types.DOUBLE:\n return Double.class.getName();\n case Types.TIMESTAMP:\n return Timestamp.class.getName();\n case Types.TIMESTAMP_WITH_TIMEZONE:\n return TimestampTZ.class.getName();\n case Types.DECIMAL:\n return BigInteger.class.getName();\n case Types.BINARY:\n return byte[].class.getName();\n case Types.OTHER:\n case Types.JAVA_OBJECT:\n {\n switch(hiveType) {\n case INTERVAL_YEAR_MONTH_TYPE:\n return HiveIntervalYearMonth.class.getName();\n case INTERVAL_DAY_TIME_TYPE:\n return HiveIntervalDayTime.class.getName();\n default:\n return String.class.getName();\n }\n }\n case Types.ARRAY:\n case Types.STRUCT:\n return String.class.getName();\n default:\n throw new SQLException(\"Invalid column type: \" + columnType);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n try {\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n SearchServiceRemote ss = locator.lookupSearchServiceRemote();\n this.lblIndexCount.setText(\"\" + ss.getNumberOfDocs());\n this.lblDocCount.setText(\"\" + locator.lookupArchiveFileServiceRemote().getDocumentCount());\n } catch (Exception ex) {\n log.error(\"error getting document count\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler Ermitteln der Dokumentanzahl: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// RM\nprotected void storeNewToken(TokenIdent ident, long renewDate) throws IOException {\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public BigDecimal randHiveBigDecimalInverse(Random r, BigDecimal bigDecimal) {\n if (bigDecimal.signum() == 0) {\n return bigDecimal;\n }\n return BigDecimal.ONE.divide(bigDecimal);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmbFormatItemStateChanged\nprivate void jSplitPane1ComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_jSplitPane1ComponentResized\n this.jSplitPane1.setDividerLocation(0.8d);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected Reader getReader(Message input, PipeLineSession session, Map threadContext) throws SenderException {\n if (input == null) {\n throw new SenderException(\"cannot obtain reader from null input\");\n }\n try {\n return input.asReader();\n } catch (Exception e) {\n throw new SenderException(\"cannot open stream\", e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "/**\n */\nprotected void endOfSet(int setIdx) {\n rowsCnt = 0;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_cmdRefreshActionPerformed\nprivate void rdAllStatusesActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_rdAllStatusesActionPerformed\n this.cmdRefreshActionPerformed(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Returns a function that maps from a {@link ShapeMarshaller} to a set of protocol metadata constants that we codegen.\n */\npublic ProtocolMetadataConstants protocolMetadata(ShapeMarshaller shapeMarshaller) {\n return new DefaultProtocolMetadataConstants();\n}", "smellKey": "S1172", "smellId": null, "repo": "aws_aws-sdk-java-v2", "language": "java"} {"function": "//GEN-LAST:event_lblFileNameMouseExited\nprivate void lblFileIconMouseEntered(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblFileIconMouseEntered\n this.lblFileName.setForeground(DefaultColorTheme.COLOR_LOGO_BLUE);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdAdHocBackupActionPerformed\nprivate void cmdSaveSyncActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveSyncActionPerformed\n ServerSettings set = ServerSettings.getInstance();\n set.setSetting(ServerSettings.SERVERCONF_BACKUP_SYNCTARGET, this.txtTarget.getText());\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public boolean quit(String line){\r\n beeLine.setExit(true);\r\n close(null);\r\n return true;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void combinerUnsupported(T ignored, T ignored2){\n throw new UnsupportedOperationException(\"parallelStream() is not supported\");\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// write a class\n//\tpublic void writeClassDefn (ClassPropertiesOWL lClassPropertiesOWL, ClassAttrPropClassification lClassAttrPropClassification, boolean useISA) {\npublic void writeClassDefn(ClassPropertiesOWL lClassPropertiesOWL, ClassAttrPropClassification lClassAttrPropClassification) {\n //\t\tSystem.out.println(\"debug writeClassDefn -PARENT- lClassPropertiesOWL.identifier:\" + lClassPropertiesOWL.identifier + \" -- lClassPropertiesOWL.theClass.identifier:\" + lClassPropertiesOWL.theClass.identifier);\n // write each class only once; two or more instances can occur as children\n if (writtenClassIdArr.contains(lClassPropertiesOWL.theClass.identifier))\n return;\n writtenClassIdArr.add(lClassPropertiesOWL.theClass.identifier);\n String preISA = \"rdfs\";\n //\t\tif (useISA) preISA = masterNameSpaceIdNC;\n prRDFFile.println(\" \");\n prRDFFile.println(\"### Class (Selected):\" + lClassPropertiesOWL.theClass.identifier + \" ###\");\n prRDFFile.println(lClassPropertiesOWL.iri + \" \" + \"rdf:type\" + \" \" + \"rdfs:Class\" + \";\");\n prRDFFile.println(\" \" + \"rdfs:label \\\"\" + lClassPropertiesOWL.title + \"\\\";\");\n prRDFFile.println(\" \" + \"owl:versionInfo \\\"\" + lClassPropertiesOWL.versionId + \"\\\";\");\n prRDFFile.println(\" \" + preISA + \":subClassOf \" + lClassPropertiesOWL.subClassOfIRI + \";\");\n prRDFFile.println(\" \" + \"rdfs:comment \\\"\" + escapeXMLChar(lClassPropertiesOWL.definition) + \"\\\".\");\n // ensure the subclass of this class is ultimately defined\n ClassPropertiesOWL lClassPropertiesOWLSubclass = new ClassPropertiesOWL(lClassPropertiesOWL.subClassOf);\n referencedClassIdMap.put(lClassPropertiesOWLSubclass.theClass.identifier, lClassPropertiesOWLSubclass);\n // write the RDF for classes associated with the class.\n writeAssociatedClasses(lClassPropertiesOWL);\n // write the RDF for each subclass of this class and its properties (e.g., Instrument.type = Accelerometer)\n //\t\twriteTypesAsSubClasses (lClassPropertiesOWL, lClassAttrPropClassification, 1);\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveProfileActionPerformed\nprivate void cmdDeleteProfileActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdDeleteProfileActionPerformed\n String selected = this.cmbProfile.getSelectedItem().toString();\n this.connections.removeProfile(selected);\n ((DefaultComboBoxModel) this.cmbProfile.getModel()).removeElement(selected);\n ((DefaultComboBoxModel) this.cmbCurrentConnection.getModel()).removeElement(selected);\n this.cmbCurrentConnection.setSelectedItem(this.cmbCurrentConnection.getSelectedItem());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected Operator addOperatorArgument(RuleContext context, MethodCallExpr methodCallExpr, String opName){\r\n Operator operator = Operator.Register.getOperator(opName);\r\n try {\r\n operator.getClass().getField(\"INSTANCE\");\r\n methodCallExpr.addArgument(operator.getClass().getCanonicalName() + \".INSTANCE\");\r\n } catch (NoSuchFieldException e) {\r\n methodCallExpr.addArgument(toStringLiteral(opName));\r\n }\r\n return operator;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// RM\nprotected void storeNewMasterKey(DelegationKey key) throws IOException {\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void parseForProperty(Property parentObj, String parentTag, String qName, Attributes attributes) throws SAXException{\n objects.push(parentObj);\n tags.push(qName);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSubmitActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSubmitActionPerformed\n SwingUtilities.invokeLater(this::startBackgroundTask);\n // List params = new ArrayList<>();\n // if (capability.getParameters() != null && !capability.getParameters().isEmpty()) {\n // params = getParameters();\n // if (params == null) {\n // // user cancelled parameters dialog\n // return;\n // }\n // }\n //\n // final List fParams = params;\n //\n // this.progress.setIndeterminate(true);\n // AtomicReference resultRef = new AtomicReference<>();\n //\n // CountDownLatch latch = new CountDownLatch(1);\n // new Thread(() -> {\n // ClientSettings settings = ClientSettings.getInstance();\n // try {\n // JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n //\n // AiRequestStatus status = locator.lookupIntegrationServiceRemote().submitAssistantRequest(config, capability.getRequestType(), capability.getModelType(), this.taPrompt.getText(), fParams, this.inputAdapter.getInputs(capability));\n // resultRef.set(status);\n //\n // } catch (Throwable t) {\n // log.error(\"Error processing AI request\", t);\n // } finally {\n // latch.countDown(); // Signal that the task is done\n // }\n // }).start();\n //\n // try {\n // latch.await(); // Wait until the task is finished\n // } catch (InterruptedException e) {\n // // Handle interruption\n // }\n //\n // AiRequestStatus status = resultRef.get();\n // if (status != null) {\n // if (status.getStatus().equalsIgnoreCase(\"error\")) {\n // this.taResult.setText(status.getStatus() + \": \" + status.getStatusDetails());\n // } else {\n // StringBuilder result = new StringBuilder();\n // for (OutputData o : status.getResponse().getOutputData()) {\n // if (o.getType().equalsIgnoreCase(\"string\")) {\n // result.append(o.getStringData()).append(System.lineSeparator()).append(System.lineSeparator());\n // }\n //\n // }\n // this.taResult.setText(result.toString());\n // }\n // }\n //\n // this.progress.setIndeterminate(false);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public boolean manual(String line) throws IOException {\n InputStream in = BeeLine.class.getResourceAsStream(\"manual.txt\");\n if (in == null) {\n return beeLine.error(beeLine.loc(\"no-manual\"));\n }\n BufferedReader breader = new BufferedReader(new InputStreamReader(in));\n String man;\n int index = 0;\n while ((man = breader.readLine()) != null) {\n index++;\n beeLine.output(man);\n // silly little pager\n if (index % (beeLine.getOpts().getMaxHeight() - 1) == 0) {\n String ret = beeLine.getConsoleReader().readLine(beeLine.loc(\"enter-for-more\"));\n if (ret != null && ret.startsWith(\"q\")) {\n break;\n }\n }\n }\n breader.close();\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public int getSplitEvery(IVariables variables) {\n return getSplitEvery();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected SqlFunction getCeilSqlFunction(TimeUnitRange flag){\n return SqlStdOperatorTable.CEIL;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public float readFloat(String tag) throws IOException{\r\n in.skipType();\r\n return in.readFloat();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void pruneOperator(NodeProcessorCtx ctx, Operator op, List cols) throws SemanticException {\n // the pruning needs to preserve the order of columns in the input schema\n RowSchema inputSchema = op.getSchema();\n if (inputSchema != null) {\n ArrayList rs = new ArrayList();\n RowSchema oldRS = op.getSchema();\n for (ColumnInfo i : oldRS.getSignature()) {\n if (lookupColumn(cols, i.getInternalName()) != null) {\n rs.add(i);\n } else {\n Map columnExprMap = op.getColumnExprMap();\n if (columnExprMap != null) {\n columnExprMap.remove(i.getInternalName());\n }\n }\n }\n op.getSchema().setSignature(rs);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "/**\n * Check the commit status with the given offset\n * @param commitOffset the offset to commit\n * @param channel the channel to return response\n * @param xid the xid of the commit request\n * @param preOpAttr the preOp attribute\n * @param fromRead whether the commit is triggered from read request\n * @return one commit status: COMMIT_FINISHED, COMMIT_WAIT,\n * COMMIT_INACTIVE_CTX, COMMIT_INACTIVE_WITH_PENDING_WRITE, COMMIT_ERROR\n */\npublic COMMIT_STATUS checkCommit(DFSClient dfsClient, long commitOffset, Channel channel, int xid, Nfs3FileAttributes preOpAttr, boolean fromRead) {\n if (!fromRead) {\n Preconditions.checkState(channel != null && preOpAttr != null);\n // Keep stream active\n updateLastAccessTime();\n }\n Preconditions.checkState(commitOffset >= 0);\n COMMIT_STATUS ret = checkCommitInternal(commitOffset, channel, xid, preOpAttr, fromRead);\n LOG.debug(\"Got commit status: {}\", ret.name());\n // Do the sync outside the lock\n if (ret == COMMIT_STATUS.COMMIT_DO_SYNC || ret == COMMIT_STATUS.COMMIT_FINISHED) {\n try {\n // Sync file data and length\n fos.hsync(EnumSet.of(SyncFlag.UPDATE_LENGTH));\n // Remove COMMIT_DO_SYNC status\n ret = COMMIT_STATUS.COMMIT_FINISHED;\n // Nothing to do for metadata since attr related change is pass-through\n } catch (ClosedChannelException cce) {\n if (pendingWrites.isEmpty()) {\n ret = COMMIT_STATUS.COMMIT_FINISHED;\n } else {\n ret = COMMIT_STATUS.COMMIT_ERROR;\n }\n } catch (IOException e) {\n LOG.error(\"Got stream error during data sync\", e);\n // Do nothing. Stream will be closed eventually by StreamMonitor.\n // status = Nfs3Status.NFS3ERR_IO;\n ret = COMMIT_STATUS.COMMIT_ERROR;\n }\n }\n return ret;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_lblGitHubLinkMouseExited\nprivate void lblGitHubLinkMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblGitHubLinkMouseClicked\n DesktopUtils.openBrowser(this.lblGitHubLink.getText());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void writeMPartitionColumnStatistics(Table table, Partition partition, MPartitionColumnStatistics mStatsObj, MPartitionColumnStatistics oldStats) {\n String catName = mStatsObj.getPartition().getTable().getDatabase().getCatalogName();\n String dbName = mStatsObj.getPartition().getTable().getDatabase().getName();\n String tableName = mStatsObj.getPartition().getTable().getTableName();\n String partName = mStatsObj.getPartition().getPartitionName();\n String colName = mStatsObj.getColName();\n Preconditions.checkState(this.currentTransaction.isActive());\n LOG.info(\"Updating partition level column statistics for table=\" + TableName.getQualified(catName, dbName, tableName) + \" partName=\" + partName + \" colName=\" + colName);\n boolean foundCol = false;\n List colList = partition.getSd().getCols();\n for (FieldSchema col : colList) {\n if (col.getName().equals(mStatsObj.getColName())) {\n foundCol = true;\n break;\n }\n }\n if (!foundCol) {\n LOG.warn(\"Column \" + colName + \" for which stats gathering is requested doesn't exist.\");\n }\n if (oldStats != null) {\n StatObjectConverter.setFieldsIntoOldStats(mStatsObj, oldStats);\n } else {\n pm.makePersistent(mStatsObj);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private ReaderContext runsInMaster(Map config, boolean bogus) throws HCatException {\n ReadEntity entity = new ReadEntity.Builder().withTable(\"mytbl\").build();\n HCatReader reader = DataTransferFactory.getHCatReader(entity, config);\n ReaderContext cntxt = reader.prepareRead();\n return cntxt;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n ServerSettings set = ServerSettings.getInstance();\n set.setSetting(this.categoryKey + \"1\", this.txtCustom1.getText());\n set.setSetting(this.categoryKey + \"2\", this.txtCustom2.getText());\n set.setSetting(this.categoryKey + \"3\", this.txtCustom3.getText());\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void writeFloat(float f, String tag) throws IOException {\n out.writeFloat(f);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n int row = this.tblPrompts.getSelectedRow();\n if (row >= 0) {\n AssistantPrompt ap = (AssistantPrompt) this.tblPrompts.getValueAt(row, 0);\n ap.setName(this.txtName.getText());\n ap.setRequestType(this.cmbRequestType.getSelectedItem().toString());\n ap.setPrompt(this.taPrompt.getText());\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n AssistantPrompt savedPrompt = locator.lookupIntegrationServiceRemote().updateAssistantPrompt(ap);\n AssistantAccess.getInstance().flushCustomPrompts();\n row = this.tblPrompts.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblPrompts.getModel()).setValueAt(savedPrompt, row, 0);\n ((DefaultTableModel) this.tblPrompts.getModel()).setValueAt(savedPrompt.getRequestType(), row, 1);\n } catch (Exception ex) {\n log.error(\"Error updating prompt\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n AssistantAccess.getInstance().resetCapabilities();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void clear(Driver driver, WebElement input){\r\n input.clear();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void error(UserGroupInformation user, String method, String url, String extraMsg) {\n op(OpStatus.ERROR, null, user, null, \"Unknown\", \"Method:'\" + method + \"' Exception:'\" + extraMsg + \"'\");\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void recoverInternal(String streamIdentifier) throws IOException{\r\n checkClosedOrInError(\"recoverInternal\");\r\n BKLogWriteHandler ledgerHandler = createWriteHandler(true);\r\n try {\r\n Utils.ioResult(ledgerHandler.recoverIncompleteLogSegments());\r\n } finally {\r\n Utils.closeQuietly(ledgerHandler);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static MetaTableSchema create(Class itemClass){\n return new MetaTableSchema<>();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Set getUniqueKeys(Union rel, RelMetadataQuery mq, boolean ignoreNulls){\r\n if (!rel.all) {\r\n return ImmutableSet.of(ImmutableBitSet.range(rel.getRowType().getFieldCount()));\r\n }\r\n return ImmutableSet.of();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// Catch-all rule when none of the others apply.\npublic RelNode align(RelNode rel, List collations) {\n ImmutableList.Builder newInputs = new ImmutableList.Builder<>();\n for (RelNode input : rel.getInputs()) {\n newInputs.add(dispatchAlign(input, ImmutableList.of()));\n }\n return rel.copy(rel.getTraitSet(), newInputs.build());\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n try {\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n SystemManagementRemote sys = locator.lookupSystemManagementRemote();\n boolean valid = sys.validateFileOnServer(new File(this.txtServerDir.getText()), true);\n if (!valid) {\n JOptionPane.showMessageDialog(this, \"Verzeichnis existiert am Server nicht: \" + this.txtServerDir.getText(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n } catch (Exception ex) {\n log.error(\"error validating scanner options\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n ServerSettings set = ServerSettings.getInstance();\n set.setSetting(set.SERVERCONF_SCANNER_SERVERDIR, this.txtServerDir.getText());\n set.setSetting(set.SERVERCONF_SCANNER_OCRCMD, this.txtOcrCommandline.getText());\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetOrganizationManager(OrganizationManager organizationManager) {\n APIResourceManagementServiceComponentHolder.getInstance().setOrganizationManager(null);\n LOG.debug(\"OrganizationManager unset in API Resource Management bundle.\");\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "protected String extractForumUrl(T annotation) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": " void setPartitioningStrategy(PartitioningStrategy partitioningStrategy){\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void postInit(NodeEngine nodeEngine, Properties properties, boolean metricsEnabled){\r\n if (metricsEnabled) {\r\n ((NodeEngineImpl) nodeEngine).getMetricsRegistry().registerDynamicMetricsProvider(this);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void convert(Context context, GtfsTrip gtfsTrip, VehicleJourney vehicleJourney){\n if (gtfsTrip.getTripShortName() != null) {\n vehicleJourney.setPrivateCode(gtfsTrip.getTripShortName());\n }\n if (StringUtils.trimToNull(gtfsTrip.getTripHeadSign()) != null) {\n vehicleJourney.setPublishedJourneyName(gtfsTrip.getTripHeadSign());\n }\n if (gtfsTrip.getWheelchairAccessible() != null) {\n switch(gtfsTrip.getWheelchairAccessible()) {\n case NoInformation:\n vehicleJourney.setMobilityRestrictedSuitability(null);\n break;\n case NoAllowed:\n vehicleJourney.setMobilityRestrictedSuitability(Boolean.FALSE);\n break;\n case Allowed:\n vehicleJourney.setMobilityRestrictedSuitability(Boolean.TRUE);\n break;\n }\n }\n vehicleJourney.setFilled(true);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void startVector(ArrayList v, String tag) throws IOException{\r\n out.writeVectorHeader(v.size());\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmbInsuranceActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmbInsuranceActionPerformed\n ArrayList others = (ArrayList) data.get(\"others.addressbeans\");\n ArrayList clients = (ArrayList) data.get(\"clients.addressbeans\");\n if (cmbInsurance.getSelectedItem() == null) {\n return;\n }\n String insNo = cmbInsurance.getSelectedItem().toString();\n for (AddressBean oth : others) {\n if (insNo.equalsIgnoreCase(oth.getMotorInsuranceNumber())) {\n this.selectInsurance(oth.getMotorInsuranceName());\n this.lblInsDescription.setText(\"Versicherungsschein von \" + oth.toDisplayName() + \" (Kraftfahrtversicherung)\");\n return;\n }\n }\n for (AddressBean cli : clients) {\n if (insNo.equalsIgnoreCase(cli.getMotorInsuranceNumber())) {\n this.selectInsurance(cli.getMotorInsuranceName());\n this.lblInsDescription.setText(\"Versicherungsschein von \" + cli.toDisplayName() + \" (Kraftfahrtversicherung)\");\n return;\n }\n }\n this.lblInsDescription.setText(\"\");\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_tblPoolsKeyReleased\nprivate void txtPatternKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtPatternKeyReleased\n if (this.tblPools.getSelectedRow() > -1)\n this.updatePreview();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_mnuDocumentNameTemplatesActionPerformed\nprivate void mnuImportFromSheetActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuImportFromSheetActionPerformed\n if (checkAdmin()) {\n ImportFromSheetsDialog dlg = new ImportFromSheetsDialog(this, true);\n FrameUtils.centerDialog(dlg, this);\n dlg.setVisible(true);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void handleRemovedColumnData(LlapSerDeDataBuffer[][] removed){\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdApplyActionPerformed\nprivate void cmdSelectAllActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSelectAllActionPerformed\n this.setAllSelection(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveSyncActionPerformed\nprivate void cmdCancel2ActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCancel2ActionPerformed\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_formMouseExited\nprivate void lblTagsMouseEntered(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblTagsMouseEntered\n highlight(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static synchronized TemplateRegistry getInvokerTemplateRegistry(ClassLoader cl){\n if (!INVOKER_REGISTRY.contains(\"invokers\")) {\n InputStream javaInvokersMvelStream = JavaRuleBuilderHelper.class.getResourceAsStream(JAVA_INVOKERS_MVEL);\n INVOKER_REGISTRY.addNamedTemplate(\"invokers\", TemplateCompiler.compileTemplate(javaInvokersMvelStream));\n try {\n javaInvokersMvelStream.close();\n } catch (IOException ex) {\n logger.debug(\"Failed to close stream!\", ex);\n }\n TemplateRuntime.execute(INVOKER_REGISTRY.getNamedTemplate(\"invokers\"), null, INVOKER_REGISTRY);\n }\n return INVOKER_REGISTRY;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void replaceCommandType(SetCommand setCommand, String mapName, String key, Object value, int ttl){\r\n boolean replaced = (textCommandService.replace(mapName, key, value) != null);\r\n if (replaced) {\r\n setCommand.setResponse(TextCommandConstants.STORED);\r\n } else {\r\n setCommand.setResponse(TextCommandConstants.NOT_STORED);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Initializes the size class table by calculating the memory block sizes for each size class.\n *\n * @param minSize The minimum memory block size.\n * @param maxSize The maximum memory block size.\n */\nprivate void initializeSizeClasses(int minSize, int maxSize) {\n int nDeltaLimit = 1 << log2SizeClassGroup;\n int log2Group = log2MinSize;\n int log2Delta = log2MinSize - log2SizeClassGroup;\n int sizeCount = 0;\n int size = calculateSize(log2Group, 0, log2Delta);\n // Initial size\n sizeIdx2sizeTab[sizeCount++] = size;\n // Iterate through the remaining size classes and calculate their sizes\n for (; size < maxSize; log2Group++, log2Delta++) {\n for (int nDelta = 1; nDelta <= nDeltaLimit && size <= maxSize; nDelta++) {\n size = calculateSize(log2Group, nDelta, log2Delta);\n sizeIdx2sizeTab[sizeCount++] = size;\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "protected void crawlPreparation(Path studyRepositoryRoot) throws IOException, GitAPIException{\r\n frame.closeCurrentTab();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static final Server addProxy(User user, Server s) throws Exception {\n Server proxy = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled(), ServerFactoryTest.TYPE_SERVER_PROXY);\n proxy.setHostname(\"proxy\");\n ServerFactory.save(proxy);\n TestUtils.flushAndEvict(proxy);\n assertEquals(1, SystemManager.listProxies(user.getOrg()).size());\n return proxy;\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public T field(Types.Field field, T fieldResult) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "/**\n * This method creates a constant expression to replace the given dynamic expression.\n * @param dynamicExpr Expression node representing Dynamic expression\n * @param typeInfo Type info used to create constant expression from ASTNode\n * @param parameterMap Integer to AST node map\n */\nprivate ExprNodeConstantDesc getConstant(ExprDynamicParamDesc dynamicExpr, TypeInfo typeInfo, Map parameterMap) throws SemanticException {\n Preconditions.checkArgument(parameterMap.containsKey(dynamicExpr.getIndex()), \"Paramter index not found\");\n ASTNode paramNode = parameterMap.get(dynamicExpr.getIndex());\n TypeCheckCtx typeCheckCtx = new TypeCheckCtx(null);\n ExprNodeDesc node = ExprNodeTypeCheck.genExprNode(paramNode, typeCheckCtx).get(paramNode);\n Preconditions.checkArgument(node instanceof ExprNodeConstantDesc, \"Invalid expression created\");\n return (ExprNodeConstantDesc) node;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public double readDouble(String tag) throws IOException {\n in.skipType();\n return in.readDouble();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n this.refresh(0);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void onUpdateRecord(Data key, R record, Object value, Data oldDataValue){\n compositeCacheRSMutationObserver.onUpdate(key, oldDataValue, value);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void fireAfterFunctionRemoved(final InternalKnowledgePackage pkg, final String function){\n if (hasListeners()) {\n AfterFunctionRemovedEvent event = new AfterFunctionRemovedEventImpl(this.kBase, function);\n notifyAllListeners(event, (l, e) -> l.afterFunctionRemoved(e));\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * returns false, when the bytes definitely cannot be parsed into a date/timestamp.\n *\n * Y2k requirements and dash requirements say the string has to be at least\n * yyyy-m-m = 8 bytes or more minimum; Timestamp needs to be at least 1 byte longer,\n * but the Date check is necessary, but not sufficient.\n */\npublic static boolean isDateMaybe(byte[] buf, int offset, int len) {\n // maybe valid - too expensive to check without a parse\n return len >= 8;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private String _get_date(S sequence){\n Date sysdate = Calendar.getInstance().getTime();\n String default_date = new SimpleDateFormat(\"dd-MMM-yyyy\").format(sysdate);\n return default_date;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Shuttle preVisit(IndexExpression indexExpression){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void handleQTake(String[] args){\n try {\n println(getQueue().take());\n } catch (InterruptedException e) {\n currentThread().interrupt();\n e.printStackTrace();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_lblFileNameMouseExited\nprivate void cmdEditArchiveFileActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdEditArchiveFileActionPerformed\n try {\n Object editor = null;\n if (UserSettings.getInstance().isCurrentUserInRole(UserSettings.ROLE_WRITECASE)) {\n editor = EditorsRegistry.getInstance().getEditor(EditArchiveFileDetailsPanel.class.getName());\n } else {\n editor = EditorsRegistry.getInstance().getEditor(ViewArchiveFileDetailsPanel.class.getName());\n }\n Object searcheditor = EditorsRegistry.getInstance().getEditor(DocumentSearchPanel.class.getName());\n Image bgi = ((DocumentSearchPanel) searcheditor).getBackgroundImage();\n if (editor instanceof ThemeableEditor) {\n // inherit the background to newly created child editors\n ((ThemeableEditor) editor).setBackgroundImage(bgi);\n }\n if (editor instanceof PopulateOptionsEditor) {\n ((PopulateOptionsEditor) editor).populateOptions();\n }\n ArchiveFileBean aFile = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(ClientSettings.getInstance().getLookupProperties());\n ArchiveFileServiceRemote fileService = locator.lookupArchiveFileServiceRemote();\n aFile = fileService.getArchiveFile(this.hit.getArchiveFileId());\n } catch (Exception ex) {\n log.error(\"Error loading archive file from server\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden der Akte: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n if (aFile == null) {\n return;\n }\n ((ArchiveFilePanel) editor).setArchiveFileDTO(aFile, hit.getFileName());\n ((ArchiveFilePanel) editor).setOpenedFromEditorClass(DocumentSearchPanel.class.getName());\n EditorsRegistry.getInstance().setMainEditorsPaneView((Component) editor);\n } catch (Exception ex) {\n log.error(\"Error creating editor from class \" + this.getClass().getName(), ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Editors: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static ScannableTable eval(boolean b){\r\n return new ScannableTable() {\r\n\r\n @Override\r\n public Enumerable<@Nullable Object[]> scan(DataContext root) {\r\n return Processes.processLines(\"jps\", \"-m\", \"-l\", \"-v\").select(a0 -> {\r\n final String[] fields = a0.split(\" \");\r\n return new Object[] { Long.valueOf(fields[0]), fields[1] };\r\n });\r\n }\r\n\r\n @Override\r\n public RelDataType getRowType(RelDataTypeFactory typeFactory) {\r\n return typeFactory.builder().add(\"pid\", SqlTypeName.BIGINT).add(\"info\", SqlTypeName.VARCHAR).build();\r\n }\r\n\r\n @Override\r\n public Statistic getStatistic() {\r\n return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));\r\n }\r\n\r\n @Override\r\n public Schema.TableType getJdbcTableType() {\r\n return Schema.TableType.TABLE;\r\n }\r\n\r\n @Override\r\n public boolean isRolledUp(String column) {\r\n return false;\r\n }\r\n\r\n @Override\r\n public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable CalciteConnectionConfig config) {\r\n return true;\r\n }\r\n };\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_tblCalendarsKeyPressed\nprivate void tblCalendarsKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_tblCalendarsKeyReleased\n int row = this.tblCalendars.getSelectedRow();\n if (row < 0) {\n this.resetDetails();\n } else {\n CalendarSetup cs = (CalendarSetup) this.tblCalendars.getValueAt(row, 0);\n this.updatedUI(cs);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_chkTimesheetLimitStateChanged\nprivate void cmbTimesheetIntervalActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmbTimesheetIntervalActionPerformed\n for (Component c : this.pnlTimesheetPositions.getComponents()) {\n if (c instanceof TimesheetPositionEntryPanel) {\n ((TimesheetPositionEntryPanel) c).updateEntryTotal(Integer.parseInt(this.cmbTimesheetInterval.getSelectedItem().toString()));\n }\n }\n this.updateTotals(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Serialize this object to the given array, putting only 32 bits data.\n *\n * @param array\n * array to write values to\n * @param offset\n * offset of the int array\n */\npublic void serializeTo32(int[] array, int offset) {\n assert (v[1] == 0);\n assert (v[2] == 0);\n assert (v[3] == 0);\n array[0] = v[0];\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void doTestSubtract(Random r, BigDecimal bigDecimal, BigDecimal bigDecimal2) {\n HiveDecimalV1 oldDec = HiveDecimalV1.create(bigDecimal);\n if (oldDec != null && isTenPowerBug(oldDec.toString())) {\n return;\n }\n HiveDecimal dec = HiveDecimal.create(bigDecimal);\n if (oldDec == null) {\n assertTrue(dec == null);\n return;\n }\n assertTrue(dec != null);\n dec.validate();\n HiveDecimalV1 oldDec2 = HiveDecimalV1.create(bigDecimal2);\n if (oldDec2 != null && isTenPowerBug(oldDec2.toString())) {\n return;\n }\n HiveDecimal dec2 = HiveDecimal.create(bigDecimal2);\n if (oldDec2 == null) {\n assertTrue(dec2 == null);\n return;\n }\n assertTrue(dec2 != null);\n dec.validate();\n // Verify.\n Assert.assertEquals(oldDec.toString(), dec.toString());\n Assert.assertEquals(oldDec2.toString(), dec2.toString());\n // Subtract from self.\n HiveDecimalV1 oldSubtractDec;\n HiveDecimal subtractDec;\n oldSubtractDec = oldDec.subtract(oldDec);\n Assert.assertEquals(0, oldSubtractDec.signum());\n subtractDec = dec.subtract(dec);\n Assert.assertEquals(0, subtractDec.signum());\n boolean isEqual;\n oldSubtractDec = oldDec.subtract(oldDec2);\n if (oldSubtractDec == null) {\n subtractDec = dec.subtract(dec2);\n assertTrue(subtractDec == null);\n return;\n } else {\n subtractDec = dec.subtract(dec2);\n if (subtractDec == null) {\n if (isTenPowerBug(oldSubtractDec.toString())) {\n return;\n }\n Assert.fail();\n }\n subtractDec.validate();\n isEqual = oldSubtractDec.toString().equals(subtractDec.toString());\n if (!isEqual) {\n Assert.fail();\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_lblInvoiceDocumentMouseExited\nprivate void lblInvoiceDocumentMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblInvoiceDocumentMouseClicked\n if (this.cmdViewDocument.isEnabled()) {\n this.cmdViewDocumentActionPerformed(null);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void buildPartial0(org.jbpm.flow.serialization.protobuf.KogitoNodeInstanceContentsProtobuf.JoinNodeInstanceContent result) {\n int from_bitField0_ = bitField0_;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void cmdRemoveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRemoveActionPerformed\n int row = this.tblPools.getSelectedRow();\n if (row >= 0) {\n InvoicePool ip = (InvoicePool) this.tblPools.getValueAt(row, 0);\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n locator.lookupInvoiceServiceRemote().removeInvoicePool(ip);\n row = this.tblPools.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblPools.getModel()).removeRow(row);\n this.resetDetails();\n } catch (Exception ex) {\n log.error(\"Error removing invoice pool\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void addEvents(TezTaskAttemptID taskAttemptID, Collection events){\n if (events != null && !events.isEmpty()) {\n eventsToSend.addAll(events);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static StackItem wrapDerived(byte[] bytes, Type type, boolean derived){\r\n return new StackItem(ScriptData.of(bytes), type, true);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void compareEqualLastReplicatedTimeStamp(HiveSyncGlobalCommitParams config) throws Exception {\n assertEquals(localCluster.getHMSClient().getTable(DB_NAME, TBL_NAME).getParameters().get(GLOBALLY_CONSISTENT_READ_TIMESTAMP), remoteCluster.getHMSClient().getTable(DB_NAME, TBL_NAME).getParameters().get(GLOBALLY_CONSISTENT_READ_TIMESTAMP), \"compare replicated timestamps\");\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "private void txtFileNameNewKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtFileNameNewKeyReleased\n this.fileNameChanged();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static void backdateKickstartSession(Session session, KickstartSession ksession, int days) {\n HibernateFactory.getSession().doWork(connection -> {\n try (Statement statement = connection.createStatement()) {\n statement.execute(\"UPDATE rhnKickstartSession \" + \"SET last_action = current_timestamp - interval '\" + days + \"' day \" + \"WHERE id = \" + ksession.getId());\n }\n });\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public void logPartialUncompressedData(long partOffset, long candidateEnd, boolean fromCache) {\n if (log == null)\n return;\n int offset = this.offset;\n if (offset + 2 > log.length)\n return;\n log[offset] = makeIntPair(PARTIAL_UNCOMPRESSED_DATA, (int) (candidateEnd - partOffset));\n log[offset + 1] = partOffset;\n this.offset += 2;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_mnuSendDocumentPDFActionPerformed\nprivate void mnuOpenInExternalMailerActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuOpenInExternalMailerActionPerformed\n try {\n ArrayList selectedRows = this.caseFolderPanel1.getSelectedDocuments();\n if (selectedRows.size() != 1) {\n return;\n }\n ArchiveFileDocumentsBean value = selectedRows.get(0);\n if (value != null) {\n ClientSettings settings = ClientSettings.getInstance();\n byte[] content = null;\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n content = locator.lookupArchiveFileServiceRemote().getDocumentContent(value.getId());\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Laden des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n try {\n ReadOnlyDocumentStore store = new ReadOnlyDocumentStore(\"externalmaillaunch-\" + value.getName(), value.getName());\n Launcher launcher = LauncherFactory.getLauncher(value.getName(), content, store, EditorsRegistry.getInstance().getMainWindow());\n launcher.launch(false);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim \u00d6ffnen des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim \u00d6ffnen des Dokuments: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void mnuDownloadActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuDownloadActionPerformed\n try {\n String[] depends = this.plugin.getDependsOn();\n this.callback.installRequested(this.plugin.getId(), depends);\n if (this.plugin.getState() == FormPlugin.STATE_NOT_INSTALLED) {\n this.plugin.setState(FormPlugin.STATE_INSTALLING);\n this.setEntry(this.plugin);\n this.plugin.install();\n this.lblVersionInstalled.setText(this.lblVersionAvailable.getText());\n } else if (this.plugin.getState() == FormPlugin.STATE_INSTALLED_UPDATEAVAILABLE) {\n this.plugin.setState(FormPlugin.STATE_INSTALLING);\n this.setEntry(this.plugin);\n this.plugin.update();\n this.lblVersionInstalled.setText(this.lblVersionAvailable.getText());\n }\n this.plugin.setState(FormPlugin.STATE_INSTALLED);\n this.setEntry(this.plugin);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(EditorsRegistry.getInstance().getMainWindow(), \"Fehler beim Laden des Plugins: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public RecordReader getVectorizedRecordReader(Path inputPath) throws Exception {\n Configuration conf = new Configuration();\n conf.set(IOConstants.COLUMNS, getColumnNames(DEFAULT_COLUMN_TYPES));\n conf.set(IOConstants.COLUMNS_TYPES, DEFAULT_COLUMN_TYPES);\n // TODO: VectorizedParquetRecordReader doesn't support map, array now, the value of\n // ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR should be updated after support these data\n // types.\n conf.setBoolean(ColumnProjectionUtils.READ_ALL_COLUMNS, false);\n conf.set(ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR, \"0,1,2,3,6\");\n return VectorizedColumnReaderTestBase.createTestParquetReader(\"test schema\", conf);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private void rollbackFromDropOnDataNodes(ConfigNodeProcedureEnv env){\n LOGGER.info(\"DropPipePluginProcedure: rollbackFromDropOnDataNodes({})\", pluginName);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdSelectAllActionPerformed\nprivate void cmdSelectNoneActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSelectNoneActionPerformed\n this.foldersListPanel.selectAll(false);\n this.foldersListPanel.selectionChanged();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) {\n if (log.isDebugEnabled()) {\n log.debug(\"Tenant Registry Loader is unset in the SAML SSO bundle\");\n }\n IdentityTenantUtil.setTenantRegistryLoader(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private List ordered(final List propertyIds){\r\n return Arrays.asList(\"timestamp\", \"target\", \"logicalMemberIdentifier\", \"username\", \"duration\", \"interactionId\", \"sequence\");\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ErrorMessageFactory shouldNotMatch(T actual, Predicate predicate, PredicateDescription predicateDescription){\n requireNonNull(predicateDescription, \"The predicate description must not be null\");\n return new ShouldNotMatch(actual, predicateDescription);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Long getSnapshotID(RequestContext context) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "private void configureWeights(ConfigExtractor e) {\n weights = new HashMap();\n weights.put(Distribution.UNIFORM, new UniformWeight());\n // weights.put(Distribution.BEG, new BeginWeight());\n // weights.put(Distribution.END, new EndWeight());\n // weights.put(Distribution.MID, new MidWeight());\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_mnuEditReviewActionPerformed\nprivate void mnuSetDocumentDateActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSetDocumentDateActionPerformed\n try {\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n for (ArchiveFileDocumentsBean doc : selectedDocs) {\n DateTimePickerDialog dlg = new DateTimePickerDialog(EditorsRegistry.getInstance().getMainWindow(), false, doc, this.caseFolderPanel1);\n FrameUtils.centerDialog(dlg, null);\n dlg.setVisible(true);\n break;\n }\n } catch (Exception ioe) {\n log.error(\"Error setting document date\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void processXmlTransient(final ProcessMethodContext processMethodContext, final XmlAccessType accessType){\n val xmlTransientIfAny = processMethodContext.synthesizeOnMethod(XmlTransient.class);\n if (!xmlTransientIfAny.isPresent()) {\n return;\n }\n val facetHolder = processMethodContext.getFacetHolder();\n addFacet(new XmlTransientFacetDefault(facetHolder));\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param nodes Nodes count.\n * @throws Exception On error.\n */\nprivate void startGridAndPopulateCache(int nodes) throws Exception {\n startGrids(NODE_CNT);\n IgniteCache cache = grid(0).cache(CACHE_NAME);\n for (int i = 0; i < KEY_CNT; i++) cache.put((long) i, String.valueOf(i));\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n // in case of manual refreshs use current date as max\n // perform search here\n ThreadUtils.setWaitCursor(this);\n this.upperDate = new Date();\n this.lblMaxDate.setText(df.format(this.upperDate));\n this.intervalMax = this.upperDate;\n this.historyIntervalSlider.setUpperValue(this.historyIntervalSlider.getMaximum());\n long intervalDiff = this.intervalMax.getTime() - this.intervalMin.getTime();\n float percentage = (4f * 7f * 24f * 60f * 60f * 1000f) / (float) intervalDiff;\n this.historyIntervalSlider.setValue(this.historyIntervalSlider.getMaximum() - Math.max((int) (percentage * 100), 1));\n new Thread(new HistorySearchThread(this, this.pnlEntries, this.principalId, this.lowerDate, this.upperDate, Integer.parseInt(this.cmbMaxEntries.getSelectedItem().toString()))).start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// RM\nprotected void updateStoredToken(TokenIdent ident, long renewDate) throws IOException {\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_txtSearchStringKeyPressed\nprivate void cmdQuickSearchActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdQuickSearchActionPerformed\n // perform search here\n ThreadUtils.setWaitCursor(this);\n EditorsRegistry.getInstance().updateStatus(\"Suche Akten...\");\n this.renderer.setCaseIdsSyncedForUser(null);\n new Thread(new QuickArchiveFileSearchThread(this, this.txtSearchString.getText(), this.chkIncludeArchive.isSelected(), TagUtils.getSelectedTags(this.popTagFilter), TagUtils.getSelectedTags(this.popDocumentTagFilter), this.tblResults)).start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void killedJob(Job job) {\n jobsKilled.incr();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "/**\n */\nprivate void doAtomicOrImplicitTxPutAll(final Map values, int expAtomicCacheSize) throws Exception {\n executeWithAllCaches(new TestClosure() {\n\n @Override\n public void run() throws Exception {\n Throwable t = GridTestUtils.assertThrowsWithCause(new Callable() {\n\n @Override\n public Object call() throws Exception {\n cache.putAll(values);\n return null;\n }\n }, IgniteSQLException.class);\n IgniteSQLException ex = X.cause(t, IgniteSQLException.class);\n assertNotNull(ex);\n assertTrue(ex.getMessage().contains(ERR_MSG));\n assertEquals(0, cache.size());\n }\n });\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n ServerSettings set = ServerSettings.getInstance();\n set.setSetting(ServerSettings.PROFILE_COMPANYCITY, this.txtCity.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYCOUNTRY, this.txtCountry.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYEMAIL, this.txtEmail.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYFAX, this.txtFax.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYMOBILE, this.txtMobile.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYNAME, this.txtCompany.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYPHONE, this.txtPhone.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYSTREET, this.txtStreet.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYSTREET2, this.txtStreet2.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYWWW, this.txtWWW.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYZIP, this.txtZip.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYTAXID, this.txtTaxId.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYUSTID, this.txtUstId.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYBANK, this.txtBank.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYBANKCODE, this.txtBankCode.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYACCOUNTNO, this.txtAccountId.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYBANK_AK, this.txtBankAK.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYBANKCODE_AK, this.txtBankCodeAK.getText());\n set.setSetting(ServerSettings.PROFILE_COMPANYACCOUNTNO_AK, this.txtAccountIdAK.getText());\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void handleDecisionPoint(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, SequenceConfig sequenceConfig, DynamicDecisionNode dynamicDecisionNode) throws FrameworkException {\n if (dynamicDecisionNode == null) {\n log.error(\"Dynamic decision node is null\");\n return;\n }\n AuthenticatorFlowStatus flowStatus = (AuthenticatorFlowStatus) request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);\n if (flowStatus != null) {\n switch(flowStatus) {\n case SUCCESS_COMPLETED:\n executeFunction(\"onSuccess\", dynamicDecisionNode, context);\n break;\n case FAIL_COMPLETED:\n if (dynamicDecisionNode.getGenericFunctionMap().get(\"onFail\") != null) {\n executeFunction(\"onFail\", dynamicDecisionNode, context);\n } else {\n if (context.isRetrying()) {\n AuthGraphNode nextNode = dynamicDecisionNode.getParent();\n context.setProperty(FrameworkConstants.JSAttributes.PROP_CURRENT_NODE, nextNode);\n return;\n }\n }\n if (dynamicDecisionNode.getDefaultEdge() instanceof EndStep) {\n dynamicDecisionNode.setDefaultEdge(new FailNode());\n }\n break;\n case FALLBACK:\n executeFunction(\"onFallback\", dynamicDecisionNode, context);\n break;\n case USER_ABORT:\n executeFunction(\"onUserAbort\", dynamicDecisionNode, context);\n break;\n }\n }\n AuthGraphNode nextNode = dynamicDecisionNode.getDefaultEdge();\n context.setProperty(FrameworkConstants.JSAttributes.PROP_CURRENT_NODE, nextNode);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_cmdNewRvgMousePressed\nprivate void mnuDuplicateDocumentAsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuDuplicateDocumentAsActionPerformed\n if (LoadDocumentPreviewThread.isRunning()) {\n JOptionPane.showMessageDialog(this, \"Bitte warten Sie bis die Dokumentvorschau abgeschlossen ist.\", \"Hinweis\", JOptionPane.PLAIN_MESSAGE);\n return;\n }\n try {\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n ArchiveFileServiceRemote remote = locator.lookupArchiveFileServiceRemote();\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n String[] list = FileConverter.OUTPUTTYPES.toArray(new String[0]);\n JComboBox jcb = new JComboBox(list);\n jcb.setEditable(false);\n int returnValue = JOptionPane.showConfirmDialog(this, jcb, \"Zielformat\", JOptionPane.OK_CANCEL_OPTION);\n if (returnValue == JOptionPane.CANCEL_OPTION || returnValue == JOptionPane.CLOSED_OPTION) {\n this.lastPopupClosed = System.currentTimeMillis();\n return;\n }\n Object response = jcb.getSelectedItem();\n if (response == null) {\n this.lastPopupClosed = System.currentTimeMillis();\n return;\n }\n String targetFormat = response.toString();\n for (ArchiveFileDocumentsBean doc : selectedDocs) {\n String currentExt = \"\";\n for (String ext : LauncherFactory.LO_OFFICEFILETYPES) {\n ext = ext.toLowerCase();\n if (doc.getName().toLowerCase().endsWith(ext)) {\n currentExt = ext;\n }\n }\n final String curExt = currentExt;\n ProgressableActionCallback callback = () -> {\n try {\n byte[] content = remote.getDocumentContent(doc.getId());\n String newName = doc.getName().substring(0, doc.getName().length() - curExt.length()) + \".\" + targetFormat;\n if (newName.length() == 0) {\n JOptionPane.showMessageDialog(EditorsRegistry.getInstance().getMainWindow(), \"Dateiname darf nicht leer sein.\", \"Hinweis\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n FileConverter conv = FileConverter.getInstance();\n String tempPath = FileUtils.createTempFile(doc.getName(), content);\n String tempTargetPath = conv.convertTo(tempPath, targetFormat);\n byte[] targetContent = FileUtils.readFile(new File(tempTargetPath));\n FileUtils.cleanupTempFile(tempPath);\n FileUtils.cleanupTempFile(tempTargetPath);\n ArchiveFileDocumentsBean newDoc = remote.addDocument(dto.getId(), newName, targetContent, doc.getDictateSign(), null);\n if (doc.getFolder() != null) {\n newDoc.setFolder(doc.getFolder());\n ArrayList documentIds = new ArrayList<>();\n documentIds.add(newDoc.getId());\n remote.moveDocumentsToFolder(documentIds, doc.getFolder().getId());\n } else {\n log.warn(\"document folder of source document is null when duplicating as \" + targetFormat);\n }\n caseFolderPanel1.addDocument(newDoc, null);\n } catch (Exception ioe) {\n log.error(\"Error duplicating document\", ioe);\n JOptionPane.showMessageDialog(EditorsRegistry.getInstance().getMainWindow(), \"Fehler beim Konvertieren des Dokuments: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n };\n this.waitForOpenDocument(doc, callback);\n this.lastPopupClosed = System.currentTimeMillis();\n }\n } catch (Exception ioe) {\n log.error(\"Error duplicating document\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Konvertieren des Dokuments: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void lstTemplatesMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lstTemplatesMouseClicked\n this.templateSelection();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private String runTool(Configuration conf, String[] args, boolean success) throws Exception {\n ByteArrayOutputStream o = new ByteArrayOutputStream();\n PrintStream out = new PrintStream(o, true);\n try {\n int ret = ToolRunner.run(getTool(out), args);\n assertEquals(success, ret == 0);\n return o.toString();\n } finally {\n o.close();\n out.close();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static ScannableTable parks(boolean b){\r\n return eval(PARK_ROWS);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Boolean isUdf(@SuppressWarnings(\"unused\") SqlOperator operator){\r\n return false;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected FileStatus createFileStatusUnchecked(FileSlice fileSlice, Option latestCompletedInstantOpt, String tableBasePath, HoodieTableMetaClient metaClient) {\n Option baseFileOpt = fileSlice.getBaseFile();\n if (baseFileOpt.isPresent()) {\n return getFileStatusUnchecked(baseFileOpt.get());\n } else {\n throw new IllegalStateException(\"Invalid state: base-file has to be present\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "public static String checkVersion(File metaFile) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private int ascertainParentFingerprint(DeterministicKey parentKey, int parentFingerprint) throws IllegalArgumentException{\n if (parentFingerprint != 0) {\n if (parent != null)\n checkArgument(parent.getFingerprint() == parentFingerprint, \"parent fingerprint mismatch\", Integer.toHexString(parent.getFingerprint()), Integer.toHexString(parentFingerprint));\n return parentFingerprint;\n } else\n return 0;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void start(BundleContext bc, RegistryService registryService) throws Exception {\n PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();\n carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);\n carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);\n addPermissions(registryService);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "private void rollbackFromDropOnDataNodes(ConfigNodeProcedureEnv env) {\n LOGGER.info(\"DropPipePluginProcedure: rollbackFromDropOnDataNodes({})\", pluginName);\n // do nothing but wait for rolling back to the previous state: LOCK\n // TODO: we should drop the pipe plugin on data nodes properly with RuntimeAgent's help\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "/**\n * Parse end index from html.\n * @param html the html\n * @param endStr the end index string\n * @return the endIndex\n */\npublic static long getLogEndIndex(Block html, String endStr) throws NumberFormatException {\n long end = Long.MAX_VALUE;\n if (endStr != null && !endStr.isEmpty()) {\n end = Long.parseLong(endStr);\n }\n return end;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmdShowBeaIdentityActionPerformed\nprivate void cmdGetDataFromBeaActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdGetDataFromBeaActionPerformed\n if (!BeaAccess.hasInstance()) {\n BeaLoginDialog loginPanel = new BeaLoginDialog(EditorsRegistry.getInstance().getMainWindow(), true, this);\n loginPanel.setVisible(true);\n if (!BeaAccess.hasInstance()) {\n return;\n }\n }\n try {\n BeaIdentitySearchDialog dlg = new BeaIdentitySearchDialog(EditorsRegistry.getInstance().getMainWindow(), true, null, null, this.txtFirstName.getText(), this.txtName.getText(), this.txtZipCode.getText(), this.txtCity.getText());\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n Identity i = dlg.getSelection();\n if (i != null) {\n Object[] options = { \"alle verf\u00fcgbaren\", \"nur Safe-ID\" };\n int response = JOptionPane.showOptionDialog(this, \"Sollen alle Daten oder nur die Safe-ID \u00fcbernommen werden?\", \"Daten aus beA \u00fcbernehmen\", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);\n if (response == JOptionPane.NO_OPTION) {\n // use just the SafeID\n this.txtBeaSafeId.setText(StringUtils.nonEmpty(i.getSafeId()));\n } else {\n // accept any data provided by the beA API\n if (!StringUtils.isEmpty(i.getCity())) {\n this.txtCity.setText(StringUtils.nonEmpty(i.getCity()));\n }\n if (!StringUtils.isEmpty(i.getCountry())) {\n this.cmbCountry.setSelectedItem(StringUtils.nonEmpty(i.getCountry()));\n }\n if (!StringUtils.isEmpty(i.getEmail())) {\n this.txtEmail.setText(StringUtils.nonEmpty(i.getEmail()));\n }\n if (!StringUtils.isEmpty(i.getFax())) {\n this.txtFax.setText(StringUtils.nonEmpty(i.getFax()));\n }\n this.txtFirstName.setText(StringUtils.nonEmpty(i.getFirstName()));\n if (!StringUtils.isEmpty(i.getMobile())) {\n this.txtMobile.setText(StringUtils.nonEmpty(i.getMobile()));\n }\n if (!StringUtils.isEmpty(i.getOrganization())) {\n this.txtCompany.setText(StringUtils.nonEmpty(i.getOrganization()));\n }\n if (!StringUtils.isEmpty(i.getPhone())) {\n this.txtPhone.setText(StringUtils.nonEmpty(i.getPhone()));\n }\n this.txtBeaSafeId.setText(StringUtils.nonEmpty(i.getSafeId()));\n if (!StringUtils.isEmpty(i.getStreet())) {\n this.txtStreet.setText(StringUtils.nonEmpty(i.getStreet()));\n }\n if (!StringUtils.isEmpty(i.getStreetNumber())) {\n this.txtStreetNr.setText(StringUtils.nonEmpty(i.getStreetNumber()));\n }\n if (!StringUtils.isEmpty(i.getOfficeName())) {\n this.txtCompany.setText(StringUtils.nonEmpty(i.getOfficeName()));\n }\n this.txtName.setText(StringUtils.nonEmpty(i.getSurName()));\n this.txtZipCode.setText(StringUtils.nonEmpty(i.getZipCode()));\n }\n }\n } catch (Throwable t) {\n log.error(t);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static String formatTime(DataContext ctx, String fmtString, int time){\n return internalFormatDatetime(fmtString, internalToTime(time));\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": " void executeBeginGroup(HepInstruction.BeginGroup instruction, HepInstruction.BeginGroup.State state){\r\n checkArgument(state.programState.group == null);\r\n state.programState.group = state.endGroup;\r\n LOGGER.trace(\"Entering group\");\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readData(Node transformNode, IHopMetadataProvider metadataProvider) throws HopXmlException {\n try {\n connection = XmlHandler.getTagValue(transformNode, \"connection\");\n schemaName = XmlHandler.getTagValue(transformNode, \"schema\");\n tableName = XmlHandler.getTagValue(transformNode, \"table\");\n truncateTable = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"truncate\"));\n createTable = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"create\"));\n encoding = XmlHandler.getTagValue(transformNode, \"encoding\");\n dateformat = XmlHandler.getTagValue(transformNode, \"dateformat\");\n addToResult = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"AddToResult\"));\n startNewLine = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"StartNewLine\"));\n fileName = XmlHandler.getTagValue(transformNode, \"file\", \"name\");\n createparentfolder = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"create_parent_folder\"));\n extension = XmlHandler.getTagValue(transformNode, \"file\", \"extention\");\n fileAppended = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"append\"));\n transformNrInFilename = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"split\"));\n partNrInFilename = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"haspartno\"));\n dateInFilename = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"add_date\"));\n timeInFilename = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"add_time\"));\n splitEvery = Const.toInt(XmlHandler.getTagValue(transformNode, \"file\", \"splitevery\"), 0);\n doNotOpenNewFileInit = \"Y\".equalsIgnoreCase(XmlHandler.getTagValue(transformNode, \"file\", \"DoNotOpenNewFileInit\"));\n } catch (Exception e) {\n throw new HopXmlException(\"Unable to load transform info from XML\", e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Whether the evaluator can calculate the result for a given range. The optimization is supposed\n * to save CPU/IO cost in case of evaluators that can provide the result without iterating through\n * the batches of a range. This method is called before every single calculation, so it lets the\n * evaluator store state whether it's able to run an optimized calculation in a given point of\n * time.\n */\npublic boolean canRunOptimizedCalculation(int rowNum, Range range) {\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void stopRunning(ITransform transformMetaInterface, ITransformData iTransformData) throws HopException {\n parent.stopRunningImpl(transformMetaInterface, data);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "/**\n * Satisfy storage policy function which will add the entry to SPS call queue\n * and will perform satisfaction async way.\n *\n * @param fsd\n * fs directory\n * @param bm\n * block manager\n * @param src\n * source path\n * @param logRetryCache\n * whether to record RPC ids in editlog for retry cache rebuilding\n * @return file status info\n * @throws IOException\n */\nstatic FileStatus satisfyStoragePolicy(FSDirectory fsd, BlockManager bm, String src, boolean logRetryCache) throws IOException {\n assert fsd.getFSNamesystem().hasWriteLock();\n FSPermissionChecker pc = fsd.getPermissionChecker();\n INodesInPath iip;\n fsd.writeLock();\n try {\n // check operation permission.\n iip = fsd.resolvePath(pc, src, DirOp.WRITE);\n if (fsd.isPermissionEnabled()) {\n fsd.checkPathAccess(pc, iip, FsAction.WRITE);\n }\n INode inode = FSDirectory.resolveLastINode(iip);\n if (inode.isFile() && inode.asFile().numBlocks() == 0) {\n if (NameNode.LOG.isInfoEnabled()) {\n NameNode.LOG.info(\"Skipping satisfy storage policy on path:{} as \" + \"this file doesn't have any blocks!\", inode.getFullPathName());\n }\n } else if (inodeHasSatisfyXAttr(inode)) {\n NameNode.LOG.warn(\"Cannot request to call satisfy storage policy on path: \" + inode.getFullPathName() + \", as this file/dir was already called for satisfying \" + \"storage policy.\");\n } else {\n XAttr satisfyXAttr = XAttrHelper.buildXAttr(XATTR_SATISFY_STORAGE_POLICY);\n List xAttrs = Arrays.asList(satisfyXAttr);\n List existingXAttrs = XAttrStorage.readINodeXAttrs(inode);\n List newXAttrs = FSDirXAttrOp.setINodeXAttrs(fsd, existingXAttrs, xAttrs, EnumSet.of(XAttrSetFlag.CREATE));\n XAttrStorage.updateINodeXAttrs(inode, newXAttrs, iip.getLatestSnapshotId());\n fsd.getEditLog().logSetXAttrs(src, xAttrs, logRetryCache);\n // Adding directory in the pending queue, so FileInodeIdCollector\n // process directory child in batch and recursively\n StoragePolicySatisfyManager spsManager = fsd.getBlockManager().getSPSManager();\n if (spsManager != null) {\n spsManager.addPathId(inode.getId());\n }\n }\n } finally {\n fsd.writeUnlock();\n }\n return fsd.getAuditFileInfo(iip);\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void removeFromIndex(PdfIndexer indexer, BibEntry entry, List linkedFiles){\r\n for (LinkedFile file : linkedFiles) {\r\n enqueueTask(() -> indexer.removeFromIndex(file.getLink()));\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n */\npublic static void checkDumpWithCommand(IgniteEx ign, String name, int backups) throws Exception {\n CacheGroupContext gctx = ign.context().cache().cacheGroup(CU.cacheId(DEFAULT_CACHE_NAME));\n for (GridCacheContext cctx : gctx.caches()) assertNull(cctx.dumpListener());\n gctx = ign.context().cache().cacheGroup(CU.cacheId(GRP));\n for (GridCacheContext cctx : gctx.caches()) assertNull(cctx.dumpListener());\n assertEquals(\"The check procedure has finished, no conflicts have been found.\\n\\n\", invokeCheckCommand(ign, name));\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_cmdCallActionPerformed\nprivate void cmbOwnUrisActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmbOwnUrisActionPerformed\n Object sel = this.cmbOwnUris.getSelectedItem();\n if (sel != null && sel instanceof SipUri) {\n SipUri uri = (SipUri) sel;\n this.lblFax.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/cancel.png\")));\n this.lblVoice.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/cancel.png\")));\n this.lblText.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/cancel.png\")));\n ArrayList tosList = uri.getTypeOfService();\n for (String tos : tosList) {\n if (SipUtils.TOS_FAX.equals(tos))\n this.lblFax.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/agt_action_success.png\")));\n if (SipUtils.TOS_TEXT.equals(tos))\n this.lblText.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/agt_action_success.png\")));\n if (SipUtils.TOS_VOICE.equals(tos))\n this.lblVoice.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/icons/agt_action_success.png\")));\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n if (log.isDebugEnabled()) {\n log.debug(\"Unsetting the RealmService\");\n }\n this.realmService = null;\n SecurityServiceHolder.setRealmService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public void checkPermissionRetention(Configuration conf, String ourUrl, Path path) throws Exception {\n KeyProvider provider = KeyProviderFactory.getProviders(conf).get(0);\n // let's add a new key and flush and check that permissions are still set to 777\n byte[] key = new byte[16];\n for (int i = 0; i < key.length; ++i) {\n key[i] = (byte) i;\n }\n // create a new key\n try {\n provider.createKey(\"key5\", key, KeyProvider.options(conf));\n } catch (Exception e) {\n e.printStackTrace();\n throw e;\n }\n provider.flush();\n // get a new instance of the provider to ensure it was saved correctly\n provider = KeyProviderFactory.getProviders(conf).get(0);\n assertArrayEquals(key, provider.getCurrentKey(\"key5\").getMaterial());\n FileSystem fs = path.getFileSystem(conf);\n FileStatus s = fs.getFileStatus(path);\n assertEquals(\"Permissions should have been retained from the preexisting \" + \"keystore.\", \"rwxrwxrwx\", s.getPermission().toString());\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "private void checkEnvironment(RegistrationManager registrationManager) throws BookieException, IOException, InterruptedException{\r\n List allLedgerDirs = new ArrayList(ledgerDirsManager.getAllLedgerDirs().size() + indexDirsManager.getAllLedgerDirs().size());\r\n allLedgerDirs.addAll(ledgerDirsManager.getAllLedgerDirs());\r\n if (indexDirsManager != ledgerDirsManager) {\r\n allLedgerDirs.addAll(indexDirsManager.getAllLedgerDirs());\r\n }\r\n for (File journalDirectory : journalDirectories) {\r\n checkDirectoryStructure(journalDirectory);\r\n }\r\n for (File dir : allLedgerDirs) {\r\n checkDirectoryStructure(dir);\r\n }\r\n checkIfDirsOnSameDiskPartition(allLedgerDirs);\r\n checkIfDirsOnSameDiskPartition(journalDirectories);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RepositoryServicePort getRepositoryService(boolean forceLoading) throws Exception{\n String method = \"getRepositoryService\";\n log.debug(method + \". BEGIN\");\n try {\n if (repositoryService == null) {\n repositoryService = acarisServiceFactory.getAcarisService().getRepositoryServicePort();\n }\n log.info(method + \". AcarisRepositoryServiceInterface loaded correctly\");\n } catch (Exception e) {\n log.error(method + \". Exception loading interface \" + e);\n throw e;\n }\n return repositoryService;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void updateRecord(Data key, CacheRecord record, long expiryTime, long now, UUID origin){\r\n record.setExpirationTime(expiryTime);\r\n invalidateEntry(key, origin);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Optional getActivityHandlerAs(ActivityType type, Class clazz){\r\n return getActivityHandler(type).map(x -> (T) x);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Optional fieldForGetter(final Class type, final Method getterCandidate){\r\n return Optional.ofNullable(findFieldForGetter(getterCandidate));\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ScannableTable states(boolean b){\n return eval(STATE_ROWS);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmbOwnUrisActionPerformed\nprivate void formComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_formComponentResized\n ComponentUtils.storeDialogSize(this);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public final void notifyEvicted(MemoryBuffer buffer){\r\n newEvictions.incrementAndGet();\r\n synchronized (newEvictions) {\r\n newEvictions.notifyAll();\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_radioReviewTypeRespiteActionPerformed\nprivate void formComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_formComponentResized\n ComponentUtils.storeDialogSize(this);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void processNewBinding(Optional optNewBinding, MethodCallExpr accumulateDSL){\r\n optNewBinding.ifPresent(newBinding -> {\r\n final List allExpressions = context.getExpressions();\r\n final MethodCallExpr newBindingExpression = newBinding.bindExpression;\r\n if (newBinding.patternBinding.size() == 1) {\r\n new PatternToReplace(context, newBinding.patternBinding).findFromPattern().ifPresent(pattern -> addBindAsLastChainCall(newBindingExpression, pattern));\r\n String binding = newBinding.patternBinding.iterator().next();\r\n composeTwoBindings(binding, newBindingExpression);\r\n } else if (newBinding.patternBinding.size() == 2) {\r\n String binding = newBinding.patternBinding.iterator().next();\r\n composeTwoBindings(binding, newBindingExpression);\r\n } else {\r\n final MethodCallExpr lastPattern = DrlxParseUtil.findLastPattern(allExpressions).orElseThrow(() -> new RuntimeException(\"Need the last pattern to add the binding\"));\r\n final MethodCallExpr replacedBinding = replaceBindingWithPatternBinding(newBindingExpression, lastPattern);\r\n addBindAsLastChainCall(replacedBinding, lastPattern);\r\n }\r\n });\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean isValid(Logger log){\r\n return true;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n int row = this.tblMailboxes.getSelectedRow();\n if (row >= 0) {\n if (StringUtils.isEmpty(this.txtEmailAddress.getText()) || StringUtils.isEmpty(this.txtInServer.getText()) || StringUtils.isEmpty(this.txtInUser.getText()) || StringUtils.isEmpty(new String(this.pwdInPassword.getPassword()))) {\n JOptionPane.showMessageDialog(this, \"Postfachangaben sind unvollst\u00e4ndig\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_WARNING, JOptionPane.WARNING_MESSAGE);\n return;\n }\n MailboxSetup ms = (MailboxSetup) this.tblMailboxes.getValueAt(row, 0);\n ms.setDisplayName(this.txtDisplayName.getText());\n ms.setEmailAddress(this.txtEmailAddress.getText());\n ms.setEmailInType(this.cmbAccountType.getSelectedItem().toString());\n ms.setEmailSenderName(this.txtEmailSender.getText());\n ms.setEmailSignature(this.htmlEmailSig.getText());\n ms.setEmailInServer(this.txtInServer.getText());\n ms.setEmailInUser(this.txtInUser.getText());\n ms.setEmailOutServer(this.txtOutServer.getText());\n ms.setEmailOutPort(this.txtOutPort.getText());\n ms.setEmailOutUser(this.txtOutUsername.getText());\n ms.setEmailInSsl(this.chkEmailInSsl.isSelected());\n ms.setEmailOutSsl(this.chkEmailOutSsl.isSelected());\n ms.setEmailStartTls(this.chkEmailStartTls.isSelected());\n ms.setMsExchange(this.chkMsExchange.isSelected());\n ms.setClientId(this.txtClientId.getText());\n ms.setClientSecret(this.txtClientSecret.getText());\n ms.setTenantId(this.txtTenantId.getText());\n ms.setScanInbox(this.chkScanInbox.isSelected());\n ms.setScanBlacklistedTypes(this.txtScanBlacklist.getText());\n ms.setScanExclusionList(this.txtScanExclusionList.getText());\n ms.setScanIgnoreInline(this.chkIgnoreInlineAttachments.isSelected());\n ms.setScanMinAttachmentSize(this.sldMinAttachmentSizeKb.getValue() * 1024);\n List al = ComponentUtils.getSelectedPopupMenuItems(popScanTags);\n ms.setScanDocumentTagsArray(al.toArray(String[]::new));\n ClientSettings settings = ClientSettings.getInstance();\n try {\n ms.setEmailOutPwd(CryptoProvider.defaultCrypto().encrypt(new String(this.pwdOutPassword.getPassword())));\n ms.setEmailInPwd(CryptoProvider.defaultCrypto().encrypt(new String(this.pwdInPassword.getPassword())));\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n MailboxSetup savedMailbox = locator.lookupSecurityServiceRemote().updateMailboxSetup(ms);\n row = this.tblMailboxes.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblMailboxes.getModel()).setValueAt(savedMailbox, row, 0);\n ((DefaultTableModel) this.tblMailboxes.getModel()).setValueAt(savedMailbox.getEmailAddress(), row, 1);\n UserSettings.getInstance().invalidateMailboxes(UserSettings.getInstance().getCurrentUser().getPrincipalId());\n } catch (Exception ex) {\n log.error(\"Error updating mailbox setup\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public RelNode convert(Sort sort, CassandraFilter filter){\n final RelTraitSet traitSet = sort.getTraitSet().replace(CassandraRel.CONVENTION).replace(sort.getCollation());\n return new CassandraSort(sort.getCluster(), traitSet, convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)), sort.getCollation());\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean dropall(String line){\n if (beeLine.getDatabaseConnection() == null || beeLine.getDatabaseConnection().getUrl() == null) {\n return beeLine.error(beeLine.loc(\"no-current-connection\"));\n }\n try {\n if (!(beeLine.getConsoleReader().readLine(beeLine.loc(\"really-drop-all\")).equals(\"y\"))) {\n return beeLine.error(\"abort-drop-all\");\n }\n List cmds = new LinkedList();\n ResultSet rs = beeLine.getTables();\n try {\n while (rs.next()) {\n cmds.add(\"DROP TABLE \" + rs.getString(\"TABLE_NAME\") + beeLine.getOpts().getDelimiter());\n }\n } finally {\n try {\n rs.close();\n } catch (Exception e) {\n beeLine.error(e);\n }\n }\n return beeLine.runCommands(cmds) == cmds.size();\n } catch (Exception e) {\n return beeLine.error(e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addServiceProject(String ip, String app, Type type){\r\n String projectName = app;\r\n TypeDetailInfo all = m_serviceProjectsInfo.get(ALL_CLIENT);\r\n if (all == null) {\r\n all = new TypeDetailInfo(m_reportDuration, ALL_CLIENT);\r\n m_serviceProjectsInfo.put(ALL_CLIENT, all);\r\n }\r\n TypeDetailInfo info = m_serviceProjectsInfo.get(projectName);\r\n if (info == null) {\r\n info = new TypeDetailInfo(m_reportDuration, projectName);\r\n m_serviceProjectsInfo.put(projectName, info);\r\n }\r\n info.mergeType(type);\r\n all.mergeType(type);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Builder builder(Class itemClass){\n return new Builder<>();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_mnuRemoveReviewActionPerformed\nprivate void mnuSetReviewOpenActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSetReviewOpenActionPerformed\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = null;\n try {\n locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n } catch (Exception ex) {\n log.error(\"Error updating review\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n EditorsRegistry.getInstance().clearStatus();\n return;\n }\n CalendarServiceRemote calService = locator.lookupCalendarServiceRemote();\n EditorsRegistry.getInstance().updateStatus(\"Wiedervorlage/Frist wird gespeichert...\");\n int[] selectedRows = this.tblReviewReasons.getSelectedRows();\n ArchiveFileReviewsBean relevantEvent = null;\n for (int i = 0; i < selectedRows.length; i++) {\n ArchiveFileReviewsBean review = (ArchiveFileReviewsBean) this.tblReviewReasons.getValueAt(selectedRows[i], 0);\n review.setDone(false);\n if (DateUtils.containsToday(review.getBeginDate(), review.getEndDate()) && relevantEvent == null) {\n relevantEvent = review;\n }\n if (CalendarUtils.checkForConflicts(EditorsRegistry.getInstance().getMainWindow(), review)) {\n try {\n calService.updateReview(this.dto.getId(), review);\n } catch (Exception ex) {\n log.error(\"Error removing review\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n EditorsRegistry.getInstance().clearStatus();\n return;\n }\n EditorsRegistry.getInstance().updateStatus(\"Wiedervorlage/Frist gespeichert.\", 5000);\n this.tblReviewReasons.setValueAt(Boolean.FALSE, selectedRows[i], 4);\n }\n }\n if (relevantEvent != null) {\n EventBroker eb = EventBroker.getInstance();\n eb.publishEvent(new ReviewUpdatedEvent(null, null, relevantEvent));\n }\n EditorsRegistry.getInstance().clearStatus();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCloseActionPerformed\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n settings.setCalendarEntryTemplates(locator.lookupCalendarServiceRemote().getCalendarEntryTemplates());\n } catch (Exception ex) {\n log.error(\"Error refreshing calendar entry templates\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public long readLong(String tag) throws IOException {\n in.skipType();\n return in.readLong();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public Shuttle preVisit(WhileStatement whileStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Body parseBodyText(MotivationTypes motivation, String bodyText) throws JsonParseException{\n Body body = BodyObjectFactory.getInstance().createObjectInstance(BodyInternalTypes.TAG);\n body.setValue(bodyText);\n body.setContentType(WebAnnotationModelKeywords.MIME_TYPE_TEXT_PLAIN);\n return body;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * @param msg Message.\n * @throws Exception If failed.\n */\nprivate void processNoServersMessage(ZkNoServersMessage msg) throws Exception {\n assert locNode.isClient() : locNode;\n throw localNodeFail(\"All server nodes failed, client node disconnected \" + \"(received 'no-servers' message) [locId=\" + locNode.id() + ']', true);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "private int handleReplaceLabelsOnNodes(String[] args, String cmd, boolean isHAEnabled) throws IOException, YarnException, ParseException {\n Options opts = new Options();\n opts.addOption(\"replaceLabelsOnNode\", true, \"Replace label on node.\");\n opts.addOption(\"failOnUnknownNodes\", false, \"Fail on unknown nodes.\");\n opts.addOption(\"directlyAccessNodeLabelStore\", false, \"Directly access node label store.\");\n opts.addOption(OPTION_SUBCLUSTERID);\n int exitCode = -1;\n CommandLine cliParser = null;\n try {\n cliParser = new GnuParser().parse(opts, args);\n } catch (MissingArgumentException ex) {\n System.err.println(NO_MAPPING_ERR_MSG);\n printUsage(args[0], isHAEnabled);\n return exitCode;\n }\n Map> map = buildNodeLabelsMapFromStr(cliParser.getOptionValue(\"replaceLabelsOnNode\"));\n String subClusterId = parseSubClusterId(cliParser);\n return replaceLabelsOnNodes(map, cliParser.hasOption(\"failOnUnknownNodes\"), cliParser.hasOption(\"directlyAccessNodeLabelStore\"), subClusterId);\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "protected MethodSpec.Builder applyVisitSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder, MethodSpec.Builder methodBuilder, MemberModel event){\r\n ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName());\r\n String javadocs = new DocumentationBuilder().description(\"Invoked when a {@link $T} is encountered. If this is not overridden, the event will \" + \"be given to {@link #visitDefault($T)}.\").param(\"event\", \"Event being visited\").build();\r\n return methodBuilder.addModifiers(Modifier.DEFAULT).addStatement(\"visitDefault(event)\").addJavadoc(javadocs, eventSubType, eventStreamBaseClass);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void writeRegRIM4regObjType(DOMClass lClass, String delimiter, PrintWriter prRIM) {\n String pCode = DMDocument.replaceString(lClass.title, \"/\", \"_\");\n prRIM.println(\" \");\n}", "smellKey": "S1172", "smellId": null, "repo": "NASA-PDS_pds4-information-model", "language": "java"} {"function": "protected KieBuilder createKieBuilder(KieServices ks, KieModuleModel model, ReleaseId releaseId, boolean failIfBuildError, KieFile... stringRules){\r\n KieFileSystem kfs = ks.newKieFileSystem();\r\n if (model != null) {\r\n kfs.writeKModuleXML(model.toXML());\r\n }\r\n kfs.writePomXML(getPom(releaseId));\r\n for (int i = 0; i < stringRules.length; i++) {\r\n kfs.write(stringRules[i].path, stringRules[i].content);\r\n }\r\n KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll(ImpactAnalysisProject.class);\r\n return kieBuilder;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected BitMask setNodeConstraintsPropertyReactiveMask(BitMask mask, ObjectType objectType, List accessibleProperties){\r\n return mask;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Get Role Audience name.\n *\n * @param audience Audience.\n * @param audienceId Audience ID.\n * @param tenantDomain Tenant Domain.\n * @return role audience name.\n * @throws IdentityRoleManagementException IdentityRoleManagementException.\n */\nprivate String getAudienceName(String audience, String audienceId, String tenantDomain) throws IdentityRoleManagementException {\n if (ORGANIZATION.equalsIgnoreCase(audience)) {\n return getOrganizationName(audienceId);\n }\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public void startRecord(String tag) throws IOException{\r\n in.skipType();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmbFormTypeActionPerformed\nprivate void cmdFormsManagerActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdFormsManagerActionPerformed\n try {\n if (UserUtils.isCurrentUserAdmin()) {\n FormsManagementDialog dlg = new FormsManagementDialog(EditorsRegistry.getInstance().getMainWindow(), true);\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n } else {\n JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/JKanzleiGUI\").getString(\"msg.adminrequired\"), java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/JKanzleiGUI\").getString(\"msg.title.hint\"), JOptionPane.INFORMATION_MESSAGE);\n }\n } catch (Exception ex) {\n log.error(ex);\n JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/JKanzleiGUI\").getString(\"error.launchsettings\") + ex.getMessage(), java.util.ResourceBundle.getBundle(\"com/jdimension/jlawyer/client/JKanzleiGUI\").getString(\"msg.title.error\"), JOptionPane.INFORMATION_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Blob toBlob(final String name, final URL resource){\n byte[] bytes = getBytes(resource);\n return new Blob(\"unused\", ExcelService.XSLX_MIME_TYPE, bytes);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addCallProject(String ip, String app, Type type){\n String projectName = app;\n TypeDetailInfo all = m_callProjectsInfo.get(ALL_SERVER);\n if (all == null) {\n all = new TypeDetailInfo(m_reportDuration, ALL_SERVER);\n m_callProjectsInfo.put(ALL_SERVER, all);\n }\n TypeDetailInfo info = m_callProjectsInfo.get(projectName);\n if (info == null) {\n info = new TypeDetailInfo(m_reportDuration, projectName);\n m_callProjectsInfo.put(projectName, info);\n }\n info.mergeType(type);\n all.mergeType(type);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String action(NucleusUserException cause){\r\n return \"Did the Enhancer run correctly?\";\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processNewBinding(Optional optNewBinding, MethodCallExpr accumulateDSL){\n optNewBinding.ifPresent(newBinding -> {\n final List allExpressions = context.getExpressions();\n final MethodCallExpr newBindingExpression = newBinding.bindExpression;\n if (newBinding.patternBinding.size() == 1) {\n new PatternToReplace(context, newBinding.patternBinding).findFromPattern().ifPresent(pattern -> addBindAsLastChainCall(newBindingExpression, pattern));\n String binding = newBinding.patternBinding.iterator().next();\n composeTwoBindings(binding, newBindingExpression);\n } else if (newBinding.patternBinding.size() == 2) {\n String binding = newBinding.patternBinding.iterator().next();\n composeTwoBindings(binding, newBindingExpression);\n } else {\n final MethodCallExpr lastPattern = DrlxParseUtil.findLastPattern(allExpressions).orElseThrow(() -> new RuntimeException(\"Need the last pattern to add the binding\"));\n final MethodCallExpr replacedBinding = replaceBindingWithPatternBinding(newBindingExpression, lastPattern);\n addBindAsLastChainCall(replacedBinding, lastPattern);\n }\n });\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void serializeTo32(int[] array, int offset){\r\n assert (v[1] == 0);\r\n assert (v[2] == 0);\r\n assert (v[3] == 0);\r\n array[0] = v[0];\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean isOnSameNodeGroup(Node node1, Node node2){\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Shuttle preVisit(FunctionExpression functionExpression){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Integer checkNumDistributionKey(int cnd, int pnd) {\n // number of distribution keys of cRS is chosen only when numDistKeys of pRS\n // is 0 or less. In all other cases, distribution of the keys is based on\n // the pRS which is more generic than cRS.\n // Examples:\n // case 1: if pRS sort key is (a, b) and cRS sort key is (a, b, c) and number of\n // distribution keys are 2 and 3 resp. then after merge the sort keys will\n // be (a, b, c) while the number of distribution keys will be 2.\n // case 2: if pRS sort key is empty and number of distribution keys is 0\n // and if cRS sort key is (a, b) and number of distribution keys is 2 then\n // after merge new sort key will be (a, b) and number of distribution keys\n // will be 2.\n if (pnd <= 0) {\n return 1;\n }\n return 0;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_radioSmbItemStateChanged\nprivate void radioFtpItemStateChanged(java.awt.event.ItemEvent evt) {\n //GEN-FIRST:event_radioFtpItemStateChanged\n this.updateTarget();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdFirstPageActionPerformed\nprivate void cmdLastPageActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdLastPageActionPerformed\n this.currentPage = this.totalPages - 1;\n this.showPage(this.content, this.currentPage, this.zoomFactor);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected String getAttemptId(TaskId taskId, TaskAttemptInfo ta) {\n return ta.getId();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public Boolean isPhaseTransition(HiveSortLimit sort, RelMetadataQuery mq) {\n // As Exchange operator is introduced later on, we make a\n // sort operator create a new stage for the moment\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public void hintMapEvent(Address caller, String mapName, EntryEventType eventType, int numberOfEntriesAffected, int partitionId){\n Collection partitionAccumulatorRegistries = getPartitionAccumulatorRegistries(mapName);\n for (PartitionAccumulatorRegistry accumulatorRegistry : partitionAccumulatorRegistries) {\n Accumulator accumulator = accumulatorRegistry.getOrCreate(partitionId);\n QueryCacheEventData singleEventData = newQueryCacheEventDataBuilder(false).withPartitionId(partitionId).withEventType(eventType.getType()).build();\n accumulator.accumulate(singleEventData);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void handleQPeek(String[] args){\r\n println(getQueue().peek());\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void validateAndGetOldAndNewMeta(ConfigNodeProcedureEnv env) {\n subscriptionInfo.get().validateBeforeAlterConsumerGroup(updatedConsumerGroupMeta);\n existingConsumerGroupMeta = subscriptionInfo.get().getConsumerGroupMeta(updatedConsumerGroupMeta.getConsumerGroupId());\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_iotdb", "language": "java"} {"function": "private void handleMethodCall(int code){\r\n MethodDescriptor method = getMethodDescriptorOperand();\r\n SignatureParser signature = new SignatureParser(method.getSignature());\r\n Entry calledMethod = new SimpleEntry<>(method.getSlashedClassName(), method.getName());\r\n if (PROHIBITED_METHODS.contains(calledMethod) && signature.getNumParameters() == 0) {\r\n bugReporter.reportBug(new BugInstance(this, \"SDK_BAD_METHOD_CALL\", NORMAL_PRIORITY).addClassAndMethod(this).addSourceLine(this, getPC()));\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_togReview3MonthsActionPerformed\nprivate void togReview6MonthsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_togReview6MonthsActionPerformed\n this.toggleSelection(togReview6Months);\n this.updateTarget();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_rdFolderPartyCaseActionPerformed\nprivate void rdFolderCasePartyActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_rdFolderCasePartyActionPerformed\n this.updateFolder();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private Object argValueFor(final int i){\r\n return NullNode.getInstance();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdRefreshActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshActionPerformed\n this.renderReport();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected boolean isMergeable(C container){\r\n return true;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private HiveResourceACLs getResourceACLs(final FileSystem fs, final FileStatus stat) {\n String owner = stat.getOwner();\n String group = stat.getGroup();\n HiveResourceACLsImpl acls = new HiveResourceACLsImpl();\n FsPermission permission = stat.getPermission();\n if (permission.getUserAction().implies(FsAction.READ)) {\n acls.addUserEntry(owner, HiveResourceACLs.Privilege.SELECT, HiveResourceACLs.AccessResult.ALLOWED);\n }\n if (permission.getGroupAction().implies(FsAction.READ)) {\n acls.addGroupEntry(group, HiveResourceACLs.Privilege.SELECT, HiveResourceACLs.AccessResult.ALLOWED);\n }\n if (permission.getOtherAction().implies(FsAction.READ)) {\n acls.addGroupEntry(\"public\", HiveResourceACLs.Privilege.SELECT, HiveResourceACLs.AccessResult.ALLOWED);\n }\n return acls;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_cmdCloseActionPerformed\nprivate void lstUsersValueChanged(javax.swing.event.ListSelectionEvent evt) {\n //GEN-FIRST:event_lstUsersValueChanged\n AppUserBean u = (AppUserBean) this.lstUsers.getSelectedValue();\n if (u != null) {\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n SystemManagementRemote mgmt = locator.lookupSystemManagementRemote();\n List roles = mgmt.getRoles(u.getPrincipalId());\n this.setRoles(roles);\n this.chkLawyer.setSelected(u.isLawyer());\n this.chkAutoLockDocuments.setSelected(u.isAutoLockDocuments());\n CalendarUtils cu = CalendarUtils.getInstance();\n String countryId = null;\n for (CalendarRegion cr : this.countries) {\n if (cr.getCountryId().equals(u.getCountryCode())) {\n this.cmbCountry.setSelectedItem(cr.getCountryName());\n countryId = cr.getCountryId();\n break;\n }\n }\n ArrayList regions = cu.getRegionCodes(countryId);\n for (CalendarRegion cr : regions) {\n if (cr.getRegionId().equals(u.getAreaCode())) {\n this.cmbArea.setSelectedItem(cr.getRegionName());\n break;\n }\n }\n this.txtAbbreviation.setText(u.getAbbreviation());\n this.cmbPrimaryGroup.setSelectedItem(u.getPrimaryGroup());\n this.pnlCloudConnection.setCloudHost(u.getCloudHost());\n this.pnlCloudConnection.setCloudPath(u.getCloudPath());\n this.pnlCloudConnection.setCloudPort(u.getCloudPort());\n this.pnlCloudConnection.setCloudUser(u.getCloudUser());\n this.pnlCloudConnection.setCloudPassword(\"\");\n if (u.getCloudPassword() != null && !\"\".equals(u.getCloudPassword())) {\n this.pnlCloudConnection.setCloudPassword(CryptoProvider.defaultCrypto().decrypt(u.getCloudPassword()));\n }\n this.pnlCloudConnection.setSsl(u.isCloudSsl());\n this.txtVoipPassword.setText(u.getVoipPassword());\n this.txtVoipUser.setText(u.getVoipUser());\n this.cmbVoipId.removeAllItems();\n try {\n if (!ServerStringUtils.isEmpty(u.getVoipUser()) && !ServerStringUtils.isEmpty(u.getVoipPassword())) {\n String voipId = u.getVoipId();\n List voipUsers = locator.lookupVoipServiceRemote().getUsers(u.getVoipUser(), u.getVoipPassword());\n SipUser selectedVoipUser = null;\n for (SipUser su : voipUsers) {\n if (selectedVoipUser == null) {\n selectedVoipUser = su;\n }\n ((DefaultComboBoxModel) this.cmbVoipId.getModel()).addElement(su);\n if (su.getId().equals(voipId)) {\n selectedVoipUser = su;\n }\n }\n this.cmbVoipId.setSelectedItem(selectedVoipUser);\n }\n } catch (Exception ex) {\n log.error(\"Error connecting to server\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.txtEpostCustomer.setText(u.getEpostCustomer());\n this.txtEpostSecret.setText(u.getEpostSecret());\n try {\n this.pwdEpostPassword.setText(CryptoProvider.defaultCrypto().decrypt(u.getEpostPassword()));\n } catch (Throwable t) {\n log.warn(\"Unable to decrypt E-POST password, might be empty\", t);\n this.pwdEpostPassword.setText(\"\");\n }\n this.txtDisplayName.setText(u.getDisplayName());\n this.txtEmail.setText(u.getEmail());\n txtFirstName.setText(u.getFirstName());\n txtName.setText(u.getName());\n txtCompany.setText(u.getCompany());\n txtRole.setText(u.getRole());\n txtStreet.setText(u.getStreet());\n txtAdjunct.setText(u.getAdjunct());\n txtZipCode.setText(u.getZipCode());\n txtCity.setText(u.getCity());\n String cc = u.getCountryCodeInvoicing();\n if (cc == null)\n cc = CountryCodes.getDefaultCountry().getCode();\n CountryCode selectedCc = new CountryCode(cc, \"dummy\");\n cmbCountryCodeInvoicing.setSelectedItem(selectedCc);\n txtPhone.setText(u.getPhone());\n txtFax.setText(u.getFax());\n txtMobile.setText(u.getMobile());\n txtWebsite.setText(u.getWebsite());\n txtBank.setText(u.getBankName());\n txtBic.setText(u.getBankBic());\n txtIban.setText(u.getBankIban());\n txtTaxNr.setText(u.getTaxNr());\n txtUstId.setText(u.getTaxVatId());\n if (u.isBeaCertificateAutoLogin()) {\n this.rdAutoLogin.setSelected(true);\n this.rdManualLogin.setSelected(false);\n } else {\n this.rdAutoLogin.setSelected(false);\n this.rdManualLogin.setSelected(true);\n }\n try {\n this.pwdBeaCertificatePassword.setText(CryptoProvider.defaultCrypto().decrypt(u.getBeaCertificatePassword()));\n } catch (Throwable t) {\n log.warn(\"Unable to decrypt beA certificate password, might be empty\", t);\n this.pwdBeaCertificatePassword.setText(\"\");\n }\n this.currentCertificate = u.getBeaCertificate();\n if (u.getBeaCertificate() == null) {\n this.taBeaCertificate.setText(\"kein Zertifikat hinterlegt\");\n } else {\n this.taBeaCertificate.setText(\"\");\n Hashtable ht = BeaAccess.getCertificateInformation(u.getBeaCertificate(), CryptoProvider.defaultCrypto().decrypt(u.getBeaCertificatePassword()));\n for (Object key : ht.keySet()) {\n this.taBeaCertificate.setText(this.taBeaCertificate.getText() + key.toString() + \": \" + ht.get(key).toString() + System.getProperty(\"line.separator\"));\n }\n }\n List groups = locator.lookupSecurityServiceRemote().getGroupMembershipsForUser(u.getPrincipalId());\n for (int i = 0; i < this.tblGroups.getRowCount(); i++) {\n Group g = (Group) this.tblGroups.getValueAt(i, 1);\n this.tblGroups.setValueAt(false, i, 0);\n for (GroupMembership gm : groups) {\n if (g.getId().equals(gm.getGroupId())) {\n this.tblGroups.setValueAt(true, i, 0);\n break;\n }\n }\n }\n List calendars = locator.lookupSecurityServiceRemote().getCalendarAccessForUser(u.getPrincipalId());\n for (int i = 0; i < this.tblCalendars.getRowCount(); i++) {\n CalendarSetup cs = (CalendarSetup) this.tblCalendars.getValueAt(i, 1);\n this.tblCalendars.setValueAt(false, i, 0);\n for (CalendarAccess ca : calendars) {\n if (cs.getId().equals(ca.getCalendarId())) {\n this.tblCalendars.setValueAt(true, i, 0);\n break;\n }\n }\n }\n List invoicePools = locator.lookupSecurityServiceRemote().getInvoicePoolAccessForUser(u.getPrincipalId());\n for (int i = 0; i < this.tblInvoicePools.getRowCount(); i++) {\n InvoicePool ip = (InvoicePool) this.tblInvoicePools.getValueAt(i, 1);\n this.tblInvoicePools.setValueAt(false, i, 0);\n for (InvoicePoolAccess pa : invoicePools) {\n if (ip.getId().equals(pa.getPoolId())) {\n this.tblInvoicePools.setValueAt(true, i, 0);\n break;\n }\n }\n }\n List mailboxes = locator.lookupSecurityServiceRemote().getMailboxAccessForUser(u.getPrincipalId());\n for (int i = 0; i < this.tblMailboxes.getRowCount(); i++) {\n MailboxSetup ms = (MailboxSetup) this.tblMailboxes.getValueAt(i, 1);\n this.tblMailboxes.setValueAt(false, i, 0);\n for (MailboxAccess ma : mailboxes) {\n if (ms.getId().equals(ma.getMailboxId())) {\n this.tblMailboxes.setValueAt(true, i, 0);\n break;\n }\n }\n }\n } catch (Exception ex) {\n log.error(\"Error connecting to server\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n } else {\n this.chkLawyer.setSelected(false);\n this.chkAutoLockDocuments.setSelected(true);\n this.cmbCountry.setSelectedIndex(0);\n this.cmbArea.setSelectedIndex(0);\n this.txtAbbreviation.setText(\"\");\n this.cmbPrimaryGroup.setSelectedIndex(0);\n this.pnlCloudConnection.setCloudHost(\"\");\n this.pnlCloudConnection.setCloudPath(\"\");\n this.pnlCloudConnection.setCloudPort(443);\n this.pnlCloudConnection.setCloudUser(\"\");\n this.pnlCloudConnection.setCloudPassword(\"\");\n this.pnlCloudConnection.setSsl(true);\n this.txtVoipPassword.setText(\"\");\n this.txtVoipUser.setText(\"\");\n this.cmbVoipId.removeAllItems();\n this.txtEpostCustomer.setText(\"\");\n this.txtEpostSecret.setText(\"\");\n this.pwdEpostPassword.setText(\"\");\n this.txtDisplayName.setText(\"\");\n this.txtEmail.setText(\"\");\n this.rdAutoLogin.setSelected(false);\n this.rdManualLogin.setSelected(true);\n this.pwdBeaCertificatePassword.setText(\"\");\n this.currentCertificate = null;\n this.taBeaCertificate.setText(\"\");\n txtFirstName.setText(\"\");\n txtName.setText(\"\");\n txtCompany.setText(\"\");\n txtRole.setText(\"\");\n txtStreet.setText(\"\");\n txtAdjunct.setText(\"\");\n txtZipCode.setText(\"\");\n txtCity.setText(\"\");\n cmbCountryCodeInvoicing.setSelectedItem(CountryCodes.getDefaultCountry());\n txtPhone.setText(\"\");\n txtFax.setText(\"\");\n txtMobile.setText(\"\");\n txtWebsite.setText(\"\");\n txtBank.setText(\"\");\n txtBic.setText(\"\");\n txtIban.setText(\"\");\n txtTaxNr.setText(\"\");\n txtUstId.setText(\"\");\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdShowProcessCardActionPerformed\nprivate void cmdToPdfActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdToPdfActionPerformed\n if (this.msgContainer != null) {\n try {\n byte[] pdf = this.msgContainer.toPdf(\"j-lawyer.org \" + VersionUtils.getFullClientVersion());\n String fileName = \"beA-Nachricht-\" + this.msgContainer.getId() + \".pdf\";\n ReadOnlyDocumentStore store = new ReadOnlyDocumentStore(\"beacontentui-\" + fileName, fileName);\n Launcher launcher = LauncherFactory.getLauncher(fileName, pdf, store, EditorsRegistry.getInstance().getMainWindow());\n launcher.launch(false);\n } catch (Exception ex) {\n log.error(\"Could not generate PDF for beA message\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Erstellen des PDF: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void lblAddressMouseEntered(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblAddressMouseEntered\n this.lblAddress.setForeground(new Color(0, 0, 255));\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Create a SUSE product with arch == null. This is actually the case with\n * e.g. SLES for VMWARE.\n *\n * @param family the channel family\n * @return the channel product\n */\npublic static SUSEProduct createTestSUSEProductNoArch(ChannelFamily family) {\n SUSEProduct product = new SUSEProduct();\n String name = TestUtils.randomString().toLowerCase();\n product.setName(name);\n product.setVersion(\"1\");\n product.setFriendlyName(\"SUSE Test product \" + name);\n product.setArch(null);\n product.setRelease(\"test\");\n product.setReleaseStage(ReleaseStage.released);\n product.setProductId(0);\n TestUtils.saveAndFlush(product);\n return product;\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "public static String escapeXml(IValueMeta metaA, Object dataA) {\n if (dataA == null) {\n return null;\n }\n return Const.escapeXml(dataA.toString());\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "protected void convert(Context context, GtfsStopTime gtfsStopTime, GtfsTrip gtfsTrip, VehicleJourneyAtStop vehicleJourneyAtStop){\r\n Referential referential = (Referential) context.get(REFERENTIAL);\r\n GtfsImportParameters configuration = (GtfsImportParameters) context.get(CONFIGURATION);\r\n String vjasObjectId = AbstractConverter.composeObjectId(configuration, ObjectIdTypes.VEHICLE_JOURNEY_AT_STOP_KEY, UUID.randomUUID().toString(), log);\r\n vehicleJourneyAtStop.setObjectId(vjasObjectId);\r\n String objectId = gtfsStopTime.getStopId();\r\n StopPoint stopPoint = ObjectFactory.getStopPoint(referential, objectId);\r\n vehicleJourneyAtStop.setStopPoint(stopPoint);\r\n vehicleJourneyAtStop.setArrivalTime(gtfsStopTime.getArrivalTime().getTime());\r\n vehicleJourneyAtStop.setDepartureTime(gtfsStopTime.getDepartureTime().getTime());\r\n vehicleJourneyAtStop.setArrivalDayOffset(gtfsStopTime.getArrivalTime().getDay());\r\n vehicleJourneyAtStop.setDepartureDayOffset(gtfsStopTime.getDepartureTime().getDay());\r\n if (gtfsStopTime.getStopHeadsign() != null) {\r\n DestinationDisplay destinationDisplay = ObjectFactory.getDestinationDisplay(referential, gtfsStopTime.getTripId() + \"-\" + gtfsStopTime.getStopSequence() + \"-\" + gtfsStopTime.getStopId());\r\n destinationDisplay.setFrontText(gtfsStopTime.getStopHeadsign());\r\n stopPoint.setDestinationDisplay(destinationDisplay);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static ResourceScheduler createMockScheduler(Configuration conf) {\n ResourceScheduler mockSched = mock(ResourceScheduler.class);\n doReturn(Resources.createResource(512)).when(mockSched).getMinimumResourceCapability();\n doReturn(Resources.createResource(5120)).when(mockSched).getMaximumResourceCapability();\n return mockSched;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void endRunningJob(Job job) {\n jobsRunning.decr();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmdDownloadTemplateActionPerformed\nprivate void cmdUploadSheetActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdUploadSheetActionPerformed\n JFileChooser fc = new JFileChooser();\n fc.setFileFilter(new ODSFileFilter());\n fc.setMultiSelectionEnabled(false);\n if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {\n try {\n this.taLog.setText(\"\");\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = null;\n SystemManagementRemote sys = null;\n try {\n locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n sys = locator.lookupSystemManagementRemote();\n } catch (Exception ex) {\n log.error(\"Error connecting to server\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n File ods = fc.getSelectedFile();\n this.odsData = FileUtils.readFile(ods);\n List sheetNames = sys.listImportSheets(odsData, VersionUtils.getFullClientVersion());\n this.taLog.setText(\"\");\n for (String s : sheetNames) {\n this.taLog.append(\"Tabellenblatt gefunden: [\" + s + \"]\");\n this.taLog.append(System.lineSeparator());\n }\n this.cmdDryRun.setEnabled(true);\n this.cmdImport.setEnabled(true);\n } catch (Exception ex) {\n log.error(\"Error reading import file\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_mnuDeselectActionPerformed\nprivate void cmdCancelActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdCancelActionPerformed\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdCancelActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n try {\n this.entry = this.caseAccountEntryPanel1.getEntry();\n } catch (Exception ex) {\n log.error(\"error saving invoice\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern der Buchung: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private ContainerRequest assignToReduce(Container allocated) {\n ContainerRequest assigned = null;\n //try to assign to reduces if present\n if (assigned == null && reduces.size() > 0 && canAssignReduces()) {\n TaskAttemptId tId = reduces.keySet().iterator().next();\n assigned = reduces.remove(tId);\n LOG.info(\"Assigned to reduce\");\n }\n return assigned;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_sortNameMouseClicked\nprivate void sortFavoriteMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_sortFavoriteMouseClicked\n if (this.sortFavorite.getSortState() != SortButton.SORT_NONE) {\n this.sortCreationDate.setSortState(SortButton.SORT_NONE);\n this.sortChangeDate.setSortState(SortButton.SORT_NONE);\n this.sortName.setSortState(SortButton.SORT_NONE);\n this.sortSize.setSortState(SortButton.SORT_NONE);\n this.sortFolder.setSortState(SortButton.SORT_NONE);\n this.sortFileType.setSortState(SortButton.SORT_NONE);\n }\n if (this.sortCreationDate.getSortState() == SortButton.SORT_NONE && this.sortFileType.getSortState() == SortButton.SORT_NONE && this.sortFolder.getSortState() == SortButton.SORT_NONE && this.sortChangeDate.getSortState() == SortButton.SORT_NONE && this.sortFavorite.getSortState() == SortButton.SORT_NONE && this.sortName.getSortState() == SortButton.SORT_NONE && this.sortSize.getSortState() == SortButton.SORT_NONE) {\n this.sortChangeDate.setSortState(SortButton.SORT_DESC);\n }\n this.saveSortState();\n this.sort();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "Object process(Node nd, Stack stack, NodeProcessorCtx procCtx, boolean onlySyntheticJoinPredicate, Object... nodeOutputs) throws SemanticException {\n LOG.debug(\"Processing for {}\", nd.toString());\n OpWalkerInfo owi = (OpWalkerInfo) procCtx;\n Operator op = (Operator) nd;\n // if this filter is generated one, predicates need not to be extracted\n ExprWalkerInfo ewi = owi.getPrunedPreds(op);\n // Don't push a sampling predicate since createFilter() always creates filter\n // with isSamplePred = false. Also, the filterop with sampling pred is always\n // a child of TableScan, so there is no need to push this predicate.\n if (ewi == null && !((FilterOperator) op).getConf().getIsSamplingPred() && (!onlySyntheticJoinPredicate || ((FilterOperator) op).getConf().isSyntheticJoinPredicate())) {\n // get pushdown predicates for this operator's predicate\n ExprNodeDesc predicate = (((FilterOperator) nd).getConf()).getPredicate();\n ewi = ExprWalkerProcFactory.extractPushdownPreds(owi, op, predicate);\n if (!ewi.isDeterministic()) {\n /* predicate is not deterministic */\n if (op.getChildren() != null && op.getChildren().size() == 1) {\n createFilter(op, owi.getPrunedPreds((Operator) (op.getChildren().get(0))), owi);\n }\n return null;\n }\n logExpr(nd, ewi);\n owi.putPrunedPreds((Operator) nd, ewi);\n if (HiveConf.getBoolVar(owi.getParseContext().getConf(), HiveConf.ConfVars.HIVE_PPD_REMOVE_DUPLICATE_FILTERS)) {\n // add this filter for deletion, if it does not have non-final candidates\n owi.addCandidateFilterOp((FilterOperator) op);\n Map> residual = ewi.getResidualPredicates(true);\n createFilter(op, residual, owi);\n }\n }\n // merge it with children predicates\n boolean hasUnpushedPredicates = mergeWithChildrenPred(nd, owi, ewi, null);\n if (HiveConf.getBoolVar(owi.getParseContext().getConf(), HiveConf.ConfVars.HIVE_PPD_REMOVE_DUPLICATE_FILTERS)) {\n if (hasUnpushedPredicates) {\n ExprWalkerInfo unpushedPreds = mergeChildrenPred(nd, owi, null, false);\n return createFilter((Operator) nd, unpushedPreds, owi);\n }\n }\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public boolean commit(String line) throws SQLException{\r\n if (!(beeLine.assertConnection())) {\r\n return false;\r\n }\r\n if (!(beeLine.assertAutoCommit())) {\r\n return false;\r\n }\r\n try {\r\n long start = System.currentTimeMillis();\r\n beeLine.getDatabaseConnection().getConnection().commit();\r\n long end = System.currentTimeMillis();\r\n beeLine.showWarnings();\r\n beeLine.info(beeLine.loc(\"commit-complete\") + \" \" + beeLine.locElapsedTime(end - start));\r\n return true;\r\n } catch (Exception e) {\r\n return beeLine.error(e);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_lblDescriptionMouseClicked\nprivate void cmdSaveMessageAttachmentsOnlyActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveMessageAttachmentsOnlyActionPerformed\n boolean saved = this.executor.saveToCaseCallback(this.e.getId(), false, false, true);\n if (saved) {\n this.cmdSaveMessageAttachmentsOnly.setEnabled(false);\n this.cmdSaveMessageAttachmentsOnly.setBackground(Color.green.darker().darker());\n } else {\n this.cmdSaveMessageAttachmentsOnly.setBackground(Color.red.darker().darker());\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static Map toMap(String json, Class classK, Class classV){\n if (Strings.isNullOrEmpty(json)) {\n return Collections.emptyMap();\n }\n try {\n return objectMapper.readValue(json, new TypeReference>() {\n });\n } catch (Exception e) {\n log.error(\"json to map exception!\", e);\n }\n return Collections.emptyMap();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel opModel){\r\n return builder.addModifiers(DEFAULT).addStatement(\"throw new $T()\", UnsupportedOperationException.class);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static int processLocalCmd(String cmd, CommandProcessor proc, CliSessionState ss){\r\n int ret = 0;\r\n if (proc != null) {\r\n String firstToken = cmd.trim().split(\"\\\\s+\")[0];\r\n String cmd1 = cmd.trim().substring(firstToken.length()).trim();\r\n if (proc instanceof ResetProcessor || proc instanceof CompileProcessor || proc instanceof ReloadProcessor || proc instanceof CryptoProcessor || proc instanceof AddResourceProcessor || proc instanceof ListResourceProcessor || proc instanceof LlapClusterResourceProcessor || proc instanceof LlapCacheResourceProcessor) {\r\n if (cmd1.trim().split(\"\\\\s+\").length < 1) {\r\n ret = -1;\r\n }\r\n }\r\n if (proc instanceof SetProcessor) {\r\n if (!cmd1.contains(\"=\")) {\r\n ret = -1;\r\n }\r\n }\r\n if (proc instanceof DfsProcessor) {\r\n String[] argv = cmd1.trim().split(\"\\\\s+\");\r\n if (\"-put\".equals(firstToken) || \"-test\".equals(firstToken) || \"-copyFromLocal\".equals(firstToken) || \"-moveFromLocal\".equals(firstToken)) {\r\n if (argv.length < 3) {\r\n ret = -1;\r\n }\r\n } else if (\"-get\".equals(firstToken) || \"-copyToLocal\".equals(firstToken) || \"-moveToLocal\".equals(firstToken)) {\r\n if (argv.length < 3) {\r\n ret = -1;\r\n }\r\n } else if (\"-mv\".equals(firstToken) || \"-cp\".equals(firstToken)) {\r\n if (argv.length < 3) {\r\n ret = -1;\r\n }\r\n } else if (\"-rm\".equals(firstToken) || \"-rmr\".equals(firstToken) || \"-cat\".equals(firstToken) || \"-mkdir\".equals(firstToken) || \"-touchz\".equals(firstToken) || \"-stat\".equals(firstToken) || \"-text\".equals(firstToken)) {\r\n if (argv.length < 2) {\r\n ret = -1;\r\n }\r\n }\r\n }\r\n }\r\n return ret;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdNewDocumentActionPerformed\nprivate void mnuPromptAllActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuPromptAllActionPerformed\n this.taPrompt.insert(this.taInputString.getText(), this.taPrompt.getCaretPosition());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void commonPreHead(Page.HTML<__> html) {\n set(ACCORDION_ID, \"nav\");\n set(initID(ACCORDION, \"nav\"), \"{autoHeight:false, active:0}\");\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public static boolean mkdir(FileSystem fs, Path f, Configuration conf) throws IOException{\n LOG.info(\"Creating directory if it doesn't exist: \" + f);\n return fs.mkdirs(f);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdDocumentTagFilterMousePressed\nprivate void cmdDocumentTagFilterActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdDocumentTagFilterActionPerformed\n // TODO add your handling code here:\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdResetSyncActionPerformed\nprivate void cmdResetExportActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdResetExportActionPerformed\n this.txtExportTarget.setText(\"\");\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Compute disk space consumed by all the blocks in snapshots.\n */\nprivate long getDiskSpaceQuota(ContentCounts counts, FileWithSnapshotFeature sf, int lastSnapshotId) {\n FileDiffList fileDiffList = sf.getDiffs();\n int last = fileDiffList.getLastSnapshotId();\n if (lastSnapshotId == Snapshot.CURRENT_STATE_ID || last == Snapshot.CURRENT_STATE_ID) {\n return storagespaceConsumed(null).getStorageSpace();\n }\n final long ssDeltaNoReplication;\n short replication;\n if (last < lastSnapshotId) {\n ssDeltaNoReplication = computeFileSize(true, false);\n replication = getFileReplication();\n } else {\n int sid = fileDiffList.getSnapshotById(lastSnapshotId);\n ssDeltaNoReplication = computeFileSize(sid);\n replication = getFileReplication(sid);\n }\n return ssDeltaNoReplication * replication;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_tblMailsMousePressed\nprivate void mnuMarkReadActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuMarkReadActionPerformed\n this.markAsRead(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void registerTaskAllocated(String[] requestedHosts, String[] requestedRacks, String allocatedHost){\r\n if (requestedHosts != null && requestedHosts.length != 0) {\r\n Set requestedHostSet = new HashSet<>(Arrays.asList(requestedHosts));\r\n if (requestedHostSet.contains(allocatedHost)) {\r\n numLocalAllocations++;\r\n _registerAllocationInHostMap(allocatedHost, localityBasedNumAllocationsPerHost);\r\n } else {\r\n numNonLocalAllocations++;\r\n }\r\n } else {\r\n numAllocationsNoLocalityRequest++;\r\n }\r\n numTotalAllocations++;\r\n _registerAllocationInHostMap(allocatedHost, numAllocationsPerHost);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdCancelActionPerformed\nprivate void cmdOKActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdOKActionPerformed\n Date beginDate = null;\n SimpleDateFormat dformat = new SimpleDateFormat(\"dd.MM.yyyy HH:mm\");\n try {\n beginDate = dformat.parse(this.txtEventBeginDateField.getText() + \" \" + this.cmbEventBeginTime.getSelectedItem().toString());\n } catch (Throwable t) {\n log.error(t);\n JOptionPane.showMessageDialog(this, \"Ung\u00fcltiges Beginndatum / Zeit\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n Date endDate = null;\n if (this.txtEventEndDateField.getText().isEmpty() || !(targetReview.hasEndDateAndTime())) {\n this.txtEventEndDateField.setText(this.txtEventBeginDateField.getText());\n }\n try {\n endDate = dformat.parse(this.txtEventEndDateField.getText() + \" \" + this.cmbEventEndTime.getSelectedItem().toString());\n } catch (Throwable t) {\n log.error(t);\n JOptionPane.showMessageDialog(this, \"Ung\u00fcltiges Enddatum / Zeit\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n if (!targetReview.hasEndDateAndTime()) {\n endDate.setHours(23);\n endDate.setMinutes(59);\n }\n if (endDate.getTime() - beginDate.getTime() <= 0) {\n JOptionPane.showMessageDialog(this, \"Angaben ung\u00fcltig - Eintrag endet vor Start oder Termin dauert 0 Minuten?\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n return;\n }\n targetReview.setDone(false);\n targetReview.setBeginDate(beginDate);\n targetReview.setEndDate(endDate);\n targetReview.setSummary(this.cmbReviewReason.getEditor().getItem().toString());\n targetReview.setDescription(this.taEventDescription.getText());\n targetReview.setLocation(this.txtEventLocation.getText());\n targetReview.setAssignee(this.cmbAssignee.getSelectedItem().toString());\n targetReview.setCalendarSetup(this.calendarSelectionButton1.getSelectedSetup());\n if (CalendarUtils.checkForConflicts(this, targetReview)) {\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n CalendarServiceRemote calService = locator.lookupCalendarServiceRemote();\n if (this.mode == MODE_DUPLICATE) {\n // when duplicating, do not pass in the template because we do not want to handle adding related events\n targetReview = CalendarUtils.getInstance().storeCalendarEntry(targetReview, this.caseDto, null, this);\n } else if (this.mode == MODE_EDIT) {\n targetReview = calService.updateReview(this.caseDto.getId(), targetReview);\n EventBroker eb = EventBroker.getInstance();\n eb.publishEvent(new ReviewUpdatedEvent(oldBegin, oldEnd, targetReview));\n eb.publishEvent(new CasesChangedEvent());\n }\n } catch (Exception ex) {\n log.error(\"Error updating review\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n EditorsRegistry.getInstance().clearStatus();\n return;\n }\n ArchiveFileReviewReasonsTableModel model = (ArchiveFileReviewReasonsTableModel) this.tblReviewReasons.getModel();\n if (this.mode == MODE_EDIT) {\n for (int i = 0; i < model.getRowCount(); i++) {\n Object modelRev = model.getValueAt(i, 0);\n if (modelRev instanceof ArchiveFileReviewsBean) {\n if (((ArchiveFileReviewsBean) modelRev).getId().equals(targetReview.getId())) {\n model.setValueAt(targetReview, i, 0);\n model.setValueAt(targetReview.getEventTypeName(), i, 1);\n model.setValueAt(targetReview.getSummary(), i, 2);\n model.setValueAt(targetReview.getLocation(), i, 3);\n model.setValueAt(targetReview.isDone(), i, 4);\n model.setValueAt(targetReview.getAssignee(), i, 5);\n model.setValueAt(targetReview.getDescription(), i, 6);\n model.setValueAt(targetReview.getCalendarSetup().getDisplayName(), i, 7);\n }\n }\n }\n }\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private InsertAction processInsert(RuleContext context, MethodCallExpr consequenceExpr, MethodCallExpr statement, BlockStmt ruleVariablesBlock){\n Class actionClass = getActionClass(context, consequenceExpr, statement);\n InsertAction action = new InsertAction(actionClass);\n Expression insertedArgument = statement.getArgument(0);\n String insertedId = insertedArgument.toString();\n List insertedExprs = consequenceExpr.findAll(MethodCallExpr.class).stream().filter(m -> m.getScope().map(s -> s.toString().equals(insertedId) || s.toString().equals(\"(\" + insertedId + \")\")).orElse(false)).collect(Collectors.toList());\n for (MethodCallExpr expr : insertedExprs) {\n String methodName = expr.getNameAsString();\n String property = ClassUtils.setter2property(methodName);\n if (property != null) {\n Object value = getLiteralValue(context, expr.getArgument(0));\n action.addInsertedProperty(new InsertedProperty(property, value));\n }\n }\n if (isLiteral(actionClass) && insertedArgument.isLiteralExpr()) {\n action.addInsertedProperty(new InsertedProperty(\"this\", literalToValue(insertedArgument.asLiteralExpr())));\n }\n return action;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String encode(String cf, String cq){\r\n return cq + \":\" + cq;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Hudi also provides capability to obtain a stream of records that changed since given commit timestamp.\n * This can be achieved using Hudi\u2019s incremental view and providing a begin time from which changes need to be streamed.\n * We do not need to specify endTime, if we want all changes after the given commit (as is the common case).\n */\npublic static void incrementalQuery(SparkSession spark, String tablePath, String tableName) {\n List commits = spark.sql(\"select distinct(_hoodie_commit_time) as commitTime from hudi_ro_table order by commitTime\").toJavaRDD().map((Function) row -> row.getString(0)).take(50);\n // commit time we are interested in\n String beginTime = commits.get(commits.size() - 1);\n // incrementally query data\n Dataset incViewDF = spark.read().format(\"hudi\").option(\"hoodie.datasource.query.type\", \"incremental\").option(\"hoodie.datasource.read.begin.instanttime\", beginTime).load(tablePath);\n incViewDF.createOrReplaceTempView(\"hudi_incr_table\");\n spark.sql(\"select `_hoodie_commit_time`, fare, begin_lon, begin_lat, ts from hudi_incr_table where fare > 20.0\").show();\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "protected boolean checkExists(FileSystem fs, Path path, FsPermission fsPerm) throws IOException {\n boolean exists = true;\n try {\n FileStatus appDirStatus = fs.getFileStatus(path);\n if (fsSupportsChmod) {\n if (!APP_DIR_PERMISSIONS.equals(appDirStatus.getPermission())) {\n fs.setPermission(path, APP_DIR_PERMISSIONS);\n }\n }\n } catch (FileNotFoundException fnfe) {\n exists = false;\n }\n return exists;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmdRefreshActionPerformed\nprivate void tblHeadersMouseClicked(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_tblHeadersMouseClicked\n this.clear();\n int row = this.tblHeaders.getSelectedRow();\n if (row < 0) {\n return;\n }\n Object sel = this.tblHeaders.getValueAt(row, 0);\n DrebisMessagesHeader dmh = (DrebisMessagesHeader) sel;\n this.txtFileNumber.setText(dmh.getArchiveFileNumber());\n this.txtFileName.setText(dmh.getArchiveFileName());\n Object sel2 = this.tblHeaders.getValueAt(row, 3);\n DrebisMessagesEntry me = (DrebisMessagesEntry) sel2;\n this.txtFreeText.setText(me.getFreeText());\n this.txtClaimNumber.setText(\"\" + me.getClaimNumber());\n for (DrebisAttachment da : me.getAttachments()) {\n Vector aRow = new Vector();\n aRow.add(da);\n aRow.add(da.getSuffix());\n aRow.add(da.getDescription());\n ((DefaultTableModel) this.tblAttachments.getModel()).addRow(aRow);\n }\n ComponentUtils.autoSizeColumns(tblAttachments);\n this.cmdConfirm.setEnabled(true);\n this.cmdSaveConfirm.setEnabled(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdAddActionPerformed\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n int row = this.tblTypes.getSelectedRow();\n if (row >= 0) {\n InvoiceType it = (InvoiceType) this.tblTypes.getValueAt(row, 0);\n it.setDisplayName(this.txtDisplayName.getText());\n it.setDescription(this.txtDescription.getText());\n it.setTurnOver(this.chkTurnOver.isSelected());\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n InvoiceType savedType = locator.lookupInvoiceServiceRemote().updateInvoiceType(it);\n row = this.tblTypes.convertRowIndexToModel(row);\n ((DefaultTableModel) this.tblTypes.getModel()).setValueAt(savedType, row, 0);\n ((DefaultTableModel) this.tblTypes.getModel()).setValueAt(savedType.getDescription(), row, 1);\n } catch (Exception ex) {\n log.error(\"Error updating invoice type\", ex);\n JOptionPane.showMessageDialog(this, ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected Expression handleServiceCallResult(final BlockStmt executeWorkItemBody, final MethodCallExpr callService) {\n return callService;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "//GEN-LAST:event_lblHeaderInfoMousePressed\nprivate void cmdSelectDeathdayActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSelectDeathdayActionPerformed\n MultiCalDialog dlg = new MultiCalDialog(this.txtDeathDate, EditorsRegistry.getInstance().getMainWindow(), true, false);\n dlg.setVisible(true);\n this.updateAge();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public org.rutebanken.netex.model.DatedServiceJourney produce(Context context, DatedServiceJourney datedServiceJourney, Line line){\r\n ExportableData exportableData = (ExportableData) context.get(Constant.EXPORTABLE_DATA);\r\n ExportableNetexData exportableNetexData = (ExportableNetexData) context.get(Constant.EXPORTABLE_NETEX_DATA);\r\n org.rutebanken.netex.model.DatedServiceJourney netexDatedServiceJourney = netexFactory.createDatedServiceJourney();\r\n NetexProducerUtils.populateId(datedServiceJourney, netexDatedServiceJourney);\r\n LocalDate operatingDay = datedServiceJourney.getOperatingDay();\r\n NetexprofileExportParameters configuration = (NetexprofileExportParameters) context.get(Constant.CONFIGURATION);\r\n String operatingDayId = NetexProducerUtils.netexId(configuration.getDefaultCodespacePrefix(), \"OperatingDay\", operatingDay.toString());\r\n OperatingDayRefStructure operatingDayRefStructure = netexFactory.createOperatingDayRefStructure();\r\n operatingDayRefStructure.withRef(operatingDayId);\r\n netexDatedServiceJourney.setOperatingDayRef(operatingDayRefStructure);\r\n if (!exportableNetexData.getSharedOperatingDays().containsKey(operatingDayId)) {\r\n OperatingDay netexOperatingDay = netexFactory.createOperatingDay();\r\n netexOperatingDay.setVersion(\"1\");\r\n netexOperatingDay.setId(operatingDayId);\r\n netexOperatingDay.setCalendarDate(operatingDay.atStartOfDay());\r\n exportableNetexData.getSharedOperatingDays().put(netexOperatingDay.getId(), netexOperatingDay);\r\n }\r\n ServiceJourneyRefStructure serviceJourneyRefStructure = netexFactory.createServiceJourneyRefStructure();\r\n serviceJourneyRefStructure.setRef(datedServiceJourney.getVehicleJourney().getObjectId());\r\n NetexProducerUtils.populateReference(datedServiceJourney.getVehicleJourney(), serviceJourneyRefStructure, true);\r\n JAXBElement serviceJourneyRef = netexFactory.createServiceJourneyRef(serviceJourneyRefStructure);\r\n serviceJourneyRef.setValue(serviceJourneyRefStructure);\r\n netexDatedServiceJourney.getJourneyRef().add(serviceJourneyRef);\r\n if (!datedServiceJourney.getOriginalDatedServiceJourneys().isEmpty()) {\r\n for (DatedServiceJourney originalDatedServiceJourney : datedServiceJourney.getOriginalDatedServiceJourneys()) {\r\n DatedServiceJourneyRefStructure originalDatedServiceJourneyRefStructure = netexFactory.createDatedServiceJourneyRefStructure();\r\n NetexProducerUtils.populateReference(originalDatedServiceJourney, originalDatedServiceJourneyRefStructure, true);\r\n JAXBElement originalDatedServiceJourneyRefStructureJAXBElement = netexFactory.createDatedServiceJourneyRef(originalDatedServiceJourneyRefStructure);\r\n netexDatedServiceJourney.getJourneyRef().add(originalDatedServiceJourneyRefStructureJAXBElement);\r\n }\r\n }\r\n if (datedServiceJourney.getServiceAlteration() != null) {\r\n netexDatedServiceJourney.setServiceAlteration(ConversionUtil.toServiceAlterationEnumeration(datedServiceJourney.getServiceAlteration()));\r\n }\r\n return netexDatedServiceJourney;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Query getQueryForCustomConds(final SearchCond cond, final AnyTypeKind kind){\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateInterchanges(Context context, VehicleJourney oldValue, VehicleJourney newValue, List oldValueInterchanges, List newValueInterchanges, String method) throws Exception{\r\n Referential cache = (Referential) context.get(CACHE);\r\n Collection addedInterchange = CollectionUtil.substract(newValueInterchanges, oldValueInterchanges, NeptuneIdentifiedObjectComparator.INSTANCE);\r\n List interchanges = null;\r\n for (Interchange item : addedInterchange) {\r\n Interchange interchange = cache.getInterchanges().get(item.getObjectId());\r\n if (interchange == null) {\r\n if (interchanges == null) {\r\n interchanges = interchangeDAO.findByObjectId(UpdaterUtils.getObjectIds(addedInterchange));\r\n for (Interchange object : interchanges) {\r\n cache.getInterchanges().put(object.getObjectId(), object);\r\n }\r\n }\r\n interchange = cache.getInterchanges().get(item.getObjectId());\r\n }\r\n if (interchange == null) {\r\n interchange = ObjectFactory.getInterchange(cache, item.getObjectId());\r\n }\r\n BeanUtils.setProperty(interchange, method, oldValue);\r\n oldValueInterchanges.add(interchange);\r\n }\r\n Collection> modifiedInterchange = CollectionUtil.intersection(oldValueInterchanges, newValueInterchanges, NeptuneIdentifiedObjectComparator.INSTANCE);\r\n for (Pair pair : modifiedInterchange) {\r\n interchangeUpdater.update(context, pair.getLeft(), pair.getRight());\r\n }\r\n Collection removedInterchange = CollectionUtil.substract(oldValueInterchanges, newValueInterchanges, NeptuneIdentifiedObjectComparator.INSTANCE);\r\n for (Interchange interchange : removedInterchange) {\r\n BeanUtils.setProperty(interchange, method, oldValue);\r\n oldValueInterchanges.remove(interchange);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static void fixTopOBSchema(final RelNode rootRel, Pair topSelparentPair, List resultSchema, boolean replaceProject) throws CalciteSemanticException {\n if (!(topSelparentPair.getKey() instanceof Sort) || !HiveCalciteUtil.orderRelNode(topSelparentPair.getKey())) {\n return;\n }\n HiveSortLimit obRel = (HiveSortLimit) topSelparentPair.getKey();\n Project obChild = (Project) topSelparentPair.getValue();\n if (obChild.getRowType().getFieldCount() <= resultSchema.size()) {\n return;\n }\n RelDataType rt = obChild.getRowType();\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n Set collationInputRefs = new HashSet(RelCollations.ordinals(obRel.getCollation()));\n ImmutableMap.Builder inputRefToCallMapBldr = ImmutableMap.builder();\n for (int i = resultSchema.size(); i < rt.getFieldCount(); i++) {\n if (collationInputRefs.contains(i)) {\n RexNode obyExpr = obChild.getProjects().get(i);\n if (obyExpr instanceof RexCall) {\n LOG.debug(\"Old RexCall : \" + obyExpr);\n obyExpr = adjustOBSchema((RexCall) obyExpr, obChild, resultSchema);\n LOG.debug(\"New RexCall : \" + obyExpr);\n }\n inputRefToCallMapBldr.put(i, obyExpr);\n }\n }\n ImmutableMap inputRefToCallMap = inputRefToCallMapBldr.build();\n if ((obChild.getRowType().getFieldCount() - inputRefToCallMap.size()) != resultSchema.size()) {\n LOG.error(generateInvalidSchemaMessage(obChild, resultSchema, inputRefToCallMap.size()));\n throw new CalciteSemanticException(\"Result Schema didn't match Optimized Op Tree Schema\");\n }\n if (replaceProject) {\n // This removes order-by only expressions from the projections.\n HiveProject replacementProjectRel = HiveProject.create(obChild.getInput(), obChild.getProjects().subList(0, resultSchema.size()), obChild.getRowType().getFieldNames().subList(0, resultSchema.size()));\n obRel.replaceInput(0, replacementProjectRel);\n }\n obRel.setInputRefToCallMap(inputRefToCallMap);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "private NavigationServicePort getNavigationService(boolean forceLoading) throws Exception{\n String method = \"getNavigationService\";\n log.debug(method + \". BEGIN\");\n try {\n navigationService = acarisServiceFactory.getAcarisService().getNavigationServicePort();\n log.info(method + \". AcarisNavigationServiceInterface loaded correctly\");\n } catch (Exception e) {\n log.error(method + \". Exception loading interface \" + e);\n throw e;\n }\n return navigationService;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private long writeSegmentUntilCrash(MiniJournalCluster cluster, QuorumJournalManager qjm, long txid, int numTxns, Holder thrown) {\n long firstTxId = txid;\n long lastAcked = txid - 1;\n try {\n EditLogOutputStream stm = qjm.startLogSegment(txid, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);\n for (int i = 0; i < numTxns; i++) {\n QJMTestUtil.writeTxns(stm, txid++, 1);\n lastAcked++;\n }\n stm.close();\n qjm.finalizeLogSegment(firstTxId, lastAcked);\n } catch (Throwable t) {\n thrown.held = t;\n }\n return lastAcked;\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public Shuttle preVisit(TypeBinaryExpression typeBinaryExpression){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean validateGroupByOperator(GroupByOperator op, boolean isReduce, boolean isTez, VectorGroupByDesc vectorGroupByDesc) {\n GroupByDesc desc = op.getConf();\n if (desc.getMode() != GroupByDesc.Mode.HASH && desc.isDistinct()) {\n setOperatorIssue(\"DISTINCT not supported\");\n return false;\n }\n boolean ret = validateExprNodeDescNoComplex(desc.getKeys(), \"Key\");\n if (!ret) {\n return false;\n }\n /**\n * GROUP BY DEFINITIONS:\n *\n * GroupByDesc.Mode enumeration:\n *\n * The different modes of a GROUP BY operator.\n *\n * These descriptions are hopefully less cryptic than the comments for GroupByDesc.Mode.\n *\n * COMPLETE Aggregates original rows into full aggregation row(s).\n *\n * If the key length is 0, this is also called Global aggregation and\n * 1 output row is produced.\n *\n * When the key length is > 0, the original rows come in ALREADY GROUPED.\n *\n * An example for key length > 0 is a GROUP BY being applied to the\n * ALREADY GROUPED rows coming from an upstream JOIN operator. Or,\n * ALREADY GROUPED rows coming from upstream MERGEPARTIAL GROUP BY\n * operator.\n *\n * PARTIAL1 The first of 2 (or more) phases that aggregates ALREADY GROUPED\n * original rows into partial aggregations.\n *\n * Subsequent phases PARTIAL2 (optional) and MERGEPARTIAL will merge\n * the partial aggregations and output full aggregations.\n *\n * PARTIAL2 Accept ALREADY GROUPED partial aggregations and merge them into another\n * partial aggregation. Output the merged partial aggregations.\n *\n * (Haven't seen this one used)\n *\n * PARTIALS (Behaves for non-distinct the same as PARTIAL2; and behaves for\n * distinct the same as PARTIAL1.)\n *\n * FINAL Accept ALREADY GROUPED original rows and aggregate them into\n * full aggregations.\n *\n * Example is a GROUP BY being applied to rows from a sorted table, where\n * the group key is the table sort key (or a prefix).\n *\n * HASH Accept UNORDERED original rows and aggregate them into a memory table.\n * Output the partial aggregations on closeOp (or low memory).\n *\n * Similar to PARTIAL1 except original rows are UNORDERED.\n *\n * Commonly used in both Mapper and Reducer nodes. Always followed by\n * a Reducer with MERGEPARTIAL GROUP BY.\n *\n * MERGEPARTIAL Always first operator of a Reducer. Data is grouped by reduce-shuffle.\n *\n * (Behaves for non-distinct aggregations the same as FINAL; and behaves\n * for distinct aggregations the same as COMPLETE.)\n *\n * The output is full aggregation(s).\n *\n * Used in Reducers after a stage with a HASH GROUP BY operator.\n *\n * VectorGroupByDesc.ProcessingMode for VectorGroupByOperator:\n *\n * GLOBAL No key. All rows --> 1 full aggregation on end of input\n *\n * HASH Rows aggregated in to hash table on group key -->\n * 1 partial aggregation per key (normally, unless there is spilling)\n *\n * MERGE_PARTIAL As first operator in a REDUCER, partial aggregations come grouped from\n * reduce-shuffle -->\n * aggregate the partial aggregations and emit full aggregation on\n * endGroup / closeOp\n *\n * STREAMING Rows come from PARENT operator ALREADY GROUPED -->\n * aggregate the rows and emit full aggregation on key change / closeOp\n *\n * NOTE: Hash can spill partial result rows prematurely if it runs low on memory.\n * NOTE: Streaming has to compare keys where MergePartial gets an endGroup call.\n *\n * DECIDER: Which VectorGroupByDesc.ProcessingMode for VectorGroupByOperator?\n *\n * Decides using GroupByDesc.Mode and whether there are keys with the\n * VectorGroupByDesc.groupByDescModeToVectorProcessingMode method.\n *\n * Mode.COMPLETE --> (numKeys == 0 ? ProcessingMode.GLOBAL : ProcessingMode.STREAMING)\n *\n * Mode.HASH --> ProcessingMode.HASH\n *\n * Mode.MERGEPARTIAL --> (numKeys == 0 ? ProcessingMode.GLOBAL : ProcessingMode.MERGE_PARTIAL)\n *\n * Mode.PARTIAL1,\n * Mode.PARTIAL2,\n * Mode.PARTIALS,\n * Mode.FINAL --> ProcessingMode.STREAMING\n */\n boolean hasKeys = (desc.getKeys().size() > 0);\n ProcessingMode processingMode = VectorGroupByDesc.groupByDescModeToVectorProcessingMode(desc.getMode(), hasKeys);\n if (desc.isGroupingSetsPresent() && (processingMode != ProcessingMode.HASH && processingMode != ProcessingMode.STREAMING)) {\n setOperatorIssue(\"Vectorized GROUPING SETS only expected for HASH and STREAMING processing modes\");\n return false;\n }\n //TODO: isGroupingSetsPresent() is returning false, even though\n // ListGroupingSets is present. Need to check if there is hidden bug.\n boolean isGroupingSetsPresent = (desc.getListGroupingSets() != null && !desc.getListGroupingSets().isEmpty());\n if (!validateAggregationDescs(desc.getAggregators(), desc.getMode(), isGroupingSetsPresent, hasKeys)) {\n return false;\n }\n vectorGroupByDesc.setProcessingMode(processingMode);\n vectorGroupByDesc.setIsVectorizationComplexTypesEnabled(isVectorizationComplexTypesEnabled);\n vectorGroupByDesc.setIsVectorizationGroupByComplexTypesEnabled(isVectorizationGroupByComplexTypesEnabled);\n LOG.info(\"Vector GROUP BY operator will use processing mode \" + processingMode.name());\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n UserSettings settings = UserSettings.getInstance();\n String avatar = this.names[this.cmbAvatar.getSelectedIndex()].toString();\n settings.setSetting(UserSettings.USER_AVATAR, avatar);\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_EVENT_CALENDARENTRY, this.chkEventCalendarEntry.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_EVENT_CALENDARENTRY_REMINDER, this.chkEventCalendarEntryReminder.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_EVENT_INSTANTMESSAGEMENTION, this.chkEventInstantMessage.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_EVENT_INSTANTMESSAGEMENTION_DONE, this.chkEventInstantMessageDone.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_EVENT_INVOICE_DUE, this.chkEventInvoiceDue.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_SCHEDULED_DAILY_AGENDA, this.chkScheduledDailyAgenda.isSelected());\n settings.setSettingAsBoolean(UserSettings.NOTIFICATION_SCHEDULED_WEEKLY_DIGEST, this.chkScheduledWeeklyDigest.isSelected());\n settings.setSettingAsBoolean(UserSettings.CONF_MAIL_WARNSENDERUNKNOWN, this.chkWarnOnUnknownSenders.isSelected());\n try {\n Object desktop = EditorsRegistry.getInstance().getEditor(DesktopPanel.class.getName());\n ((DesktopPanel) desktop).updateUserIcon();\n } catch (Throwable t) {\n log.error(\"Error changing user icon\", t);\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static final Atom getCenterVector(Atom[] atomSet, Atom centroid){\n double[] coords = new double[3];\n coords[0] = 0 - centroid.getX();\n coords[1] = 0 - centroid.getY();\n coords[2] = 0 - centroid.getZ();\n Atom shiftVec = new AtomImpl();\n shiftVec.setCoords(coords);\n return shiftVec;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void writeCodespacesElement(XMLStreamWriter writer, ExportableData exportableData, ExportableNetexData exportableNetexData, NetexFragmentMode fragmentMode, Marshaller marshaller){\r\n try {\r\n writer.writeStartElement(CODESPACES);\r\n for (Codespace cs : exportableNetexData.getSharedCodespaces().values()) {\r\n writeCodespaceElement(writer, cs);\r\n }\r\n writer.writeEndElement();\r\n } catch (Exception e) {\r\n throw new RuntimeException(e);\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void registerRegionInGroupSuite(SceneGroup group, SceneSuite suite){\r\n suite.sceneRegions.stream().map(region -> new EntityRegion(this.getScene(), region)).forEach(this::registerRegion);\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void cmbDictateSignsItemStateChanged(java.awt.event.ItemEvent evt) {\n //GEN-FIRST:event_cmbDictateSignsItemStateChanged\n if (!(this.tblPlaceHolders.getModel() instanceof ArchiveFileTemplatePlaceHoldersTableModel)) {\n return;\n }\n ArchiveFileTemplatePlaceHoldersTableModel tm = (ArchiveFileTemplatePlaceHoldersTableModel) this.tblPlaceHolders.getModel();\n for (int i = 0; i < tm.getRowCount(); i++) {\n String key = tm.getValueAt(i, 0).toString();\n if (PlaceHolders.DOK_DZ.equals(key)) {\n tm.setValueAt(this.cmbDictateSigns.getSelectedItem().toString(), i, 1);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdYearForwardActionPerformed\nprivate void cmdMonthBackActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdMonthBackActionPerformed\n this.c1Cal.add(Calendar.MONTH, -3);\n this.c1.setCalendar(c1Cal);\n this.c2Cal.add(Calendar.MONTH, -3);\n this.c2.setCalendar(c2Cal);\n this.c3Cal.add(Calendar.MONTH, -3);\n this.c3.setCalendar(c3Cal);\n this.updateMonthLabels();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Returns the appropriate compiler to translate the operator tree\n * into executable units.\n */\npublic static TaskCompiler getCompiler(HiveConf conf, ParseContext parseContext) {\n if (HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_EXECUTION_ENGINE).equals(\"tez\")) {\n return new TezCompiler();\n } else {\n return new MapReduceCompiler();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "protected void dissociate(UnitOfWork unit) {\n currentUnitOfWork.set(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_incubator-kie-kogito-runtimes", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdExportTableActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdExportTableActionPerformed\n try {\n String fileName = FileUtils.sanitizeFileName(this.resultTable.getTableName() + \".csv\");\n TableUtils.exportAndLaunch(fileName, this.tblResult, this.decFormat);\n } catch (Exception ex) {\n log.error(\"Error exporting table to CSV\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Export: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void failFastIfNoChanges(Driver driver, DownloadsFolder folder, FileFilter filter, long start, long timeout, long incrementTimeout) throws FileNotFoundException{\n long lastFileUpdate = folder.lastModificationTime().orElse(-1L);\n long now = currentTimeMillis();\n long filesHasNotBeenUpdatedForMs = filesHasNotBeenUpdatedForMs(start, now, lastFileUpdate);\n if (filesHasNotBeenUpdatedForMs > incrementTimeout) {\n String message = String.format(\"Failed to download file%s in %d ms: files in %s haven't been modified for %s ms. \" + \"(started at: %s, lastFileUpdate: %s, now: %s, incrementTimeout: %s)\" + \"%nModification times: %s\", filter.description(), timeout, folder, filesHasNotBeenUpdatedForMs, start, lastFileUpdate, now, incrementTimeout, folder.modificationTimes());\n throw new FileNotFoundException(message);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void updateLeft(TupleSets srcLeftTuples, TupleSets trgLeftTuples, TupleSets stagedLeftTuples, TupleMemory ltm){\n for (LeftTuple leftTuple = srcLeftTuples.getUpdateFirst(); leftTuple != null; ) {\n LeftTuple next = leftTuple.getStagedNext();\n LeftTuple childLeftTuple = leftTuple.getFirstChild();\n if (!leftTuple.isExpired() && childLeftTuple != null && childLeftTuple.getStagedType() == Tuple.NONE) {\n childLeftTuple.setPropagationContext(leftTuple.getPropagationContext());\n updateChildLeftTuple(childLeftTuple, stagedLeftTuples, trgLeftTuples);\n }\n leftTuple.clearStaged();\n leftTuple = next;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n */\npublic List nodes(int part, Collection nodes) {\n return new ArrayList<>(nodes);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "//GEN-LAST:event_chkOnlyMyCasesActionPerformed\nprivate void cmdRefreshLastChangedActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdRefreshLastChangedActionPerformed\n Timer timer = new Timer();\n TimerTask lastChangedTask = new LastChangedTimerTask(this, this.pnlLastChanged, this.jSplitPane1, true);\n timer.schedule(lastChangedTask, 10);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_linkToggleStateChanged\nprivate void helpButtonMousePressed(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_helpButtonMousePressed\n final HelpCtx help = new HelpCtx(\"au.gov.asd.tac.constellation.views.histogram\");\n help.display();\n}", "smellKey": "S1172", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "public void registerTaskPreempted(String host){\n numPreemptedTasks++;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String dumpSchedulerLogs(String time, HttpServletRequest hsr) throws IOException {\n int period = Integer.parseInt(time);\n if (period <= 0) {\n throw new BadRequestException(\"Period must be greater than 0\");\n }\n return \"Capacity scheduler logs are being created.\";\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmdRemoveActionPerformed\nprivate void cmdColorActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdColorActionPerformed\n Color currentColor = JColorChooser.showDialog(this, \"Farbe w\u00e4hlen\", cmdColor.getBackground());\n if (currentColor != null) {\n cmdColor.setBackground(currentColor);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdSaveActionPerformed\nprivate void formComponentResized(java.awt.event.ComponentEvent evt) {\n //GEN-FIRST:event_formComponentResized\n ComponentUtils.storeDialogSize(this);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Double getMaxRowCount(Values values, RelMetadataQuery mq){\r\n return (double) values.getTuples().size();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public FlaggedName[] listUserByClaimWithPermission(ClaimValue claimValue, String filter, String permission, int limit) throws AxisFault {\n try {\n org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue newClaimValue = new org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue();\n newClaimValue.setClaimURI(newClaimValue.getClaimURI());\n newClaimValue.setValue(newClaimValue.getValue());\n return stub.listUserByClaimWithPermission(newClaimValue, filter, permission, limit);\n } catch (Exception e) {\n handleException(e);\n }\n return new FlaggedName[0];\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "protected void unsetRolePermissionManagementService(RolePermissionManagementService rolePermissionManagementService) {\n if (log.isDebugEnabled()) {\n log.debug(\"Role Permission Management Service is unset to Identity Provisioning bundle.\");\n }\n ProvisioningServiceDataHolder.getInstance().setRolePermissionManagementService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_jButton1ActionPerformed\n ProgressIndicator dlg = new ProgressIndicator(this, true);\n DummyAction a = new DummyAction(dlg, this.jList1);\n a.setInfinite(true);\n a.start();\n //dlg.setAction(a);\n //dlg.setShowCancelButton(false);\n //dlg.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Shuttle preVisit(TryStatement tryStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Builder builder(Class itemClass, Class builderClass, EnhancedType attributeType){\n return new Builder<>(attributeType);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized boolean payItems(Iterable costItems, int quantity, ActionReason reason){\n for (ItemParamData cost : costItems) if (getVirtualItemCount(cost.getId()) < (cost.getCount() * quantity))\n return false;\n costItems.forEach(cost -> this.payVirtualItem(cost.getId(), cost.getCount() * quantity));\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdSelectBirthdayActionPerformed\nprivate void txtBirthDateFocusLost(java.awt.event.FocusEvent evt) {\n //GEN-FIRST:event_txtBirthDateFocusLost\n this.updateAge();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected String[] getQueryTypes(QueryDescr queryDescr, QueryImpl query){\n return queryDescr.getParameterTypes();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void handleEntryEvent(Data keyData, Data valueData, Data oldValueData, Data mergingValue, int eventTypeId, UUID uuid, int numberOfAffectedEntries){\n Member member = getContext().getClusterService().getMember(uuid);\n EntryEventType eventType = EntryEventType.getByType(eventTypeId);\n EntryEvent entryEvent = new DataAwareEntryEvent<>(member, eventTypeId, name, keyData, valueData, oldValueData, null, getSerializationService());\n switch(eventType) {\n case ADDED:\n listener.entryAdded(entryEvent);\n break;\n case REMOVED:\n listener.entryRemoved(entryEvent);\n break;\n case UPDATED:\n listener.entryUpdated(entryEvent);\n break;\n case EVICTED:\n listener.entryEvicted(entryEvent);\n break;\n case CLEAR_ALL:\n MapEvent mapEvent = new MapEvent(getName(), member, eventTypeId, numberOfAffectedEntries);\n listener.mapCleared(mapEvent);\n break;\n default:\n throw new IllegalArgumentException(\"Not a known event type: \" + eventType);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void spawnMonstersByConfigId(SceneGroup group, int configId, int delayTime){\n var entity = scene.getEntityByConfigId(configId);\n if (entity != null && entity.getGroupId() == group.id) {\n Grasscutter.getLogger().debug(\"entity already exists failed in group {} with config {}\", group.id, configId);\n return;\n }\n entity = createMonster(group.id, group.block_id, group.monsters.get(configId));\n if (entity != null) {\n getScene().addEntity(entity);\n } else {\n Grasscutter.getLogger().warn(\"failed to create entity with group {} and config {}\", group.id, configId);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static ChannelSelectionResult handleExplicitBaseChannelChange(Date earliest, User user, Optional currentBase, Server srv, ChannelChangeDto srvChange) {\n boolean baseChange = (currentBase.isPresent() && !currentBase.get().getId().equals(srvChange.getNewBaseId().orElse(null))) || !(currentBase.isPresent() && srvChange.getNewBaseId().isPresent());\n boolean newBaseIsCompatible = true;\n if (baseChange) {\n if (currentBase.isPresent()) {\n Set compatibleBaseChannels = ChannelManager.listCompatibleBaseChannelsForChannel(user, currentBase.get());\n newBaseIsCompatible = // new base is in the compatible channels list\n compatibleBaseChannels.stream().anyMatch(cbc -> cbc.getId().equals(srvChange.getNewBaseId().orElse(null)));\n } else {\n // system doesn't have a base\n Set availableBaseChannels = ChannelManager.listBaseChannelsForSystem(user, srv);\n newBaseIsCompatible = availableBaseChannels.stream().anyMatch(abc -> abc.getId().equals(srvChange.getNewBaseId().orElse(null)));\n }\n }\n if (!newBaseIsCompatible) {\n String baseChannelId = Optional.ofNullable(srv.getBaseChannel()).map(b -> b.getId() + \"\").orElse(\"none\");\n LOG.error(\"New base id={} not compatible with base id={} for serverId={}\", srvChange.getNewBaseId().get(), baseChannelId, srv.getId());\n return new ChannelSelectionResult(srv, \"incompatible_base\");\n } else {\n Channel newBaseChannel = ChannelFactory.lookupById(srvChange.getNewBaseId().get());\n Set childChannels = getChildChannelsForChange(user, srv, srvChange, newBaseChannel);\n return new ChannelSelectionResult(srv, new ChannelSelection(Optional.of(newBaseChannel), childChannels));\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "uyuni-project_uyuni", "language": "java"} {"function": "// TODO Track stats of rejections etc per host\npublic void registerTaskPreempted(String host) {\n numPreemptedTasks++;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_mnuUseDocumentAsTemplateActionPerformed\nprivate void mnuSaveDocumentEncryptedActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSaveDocumentEncryptedActionPerformed\n try {\n ClientSettings settings = ClientSettings.getInstance();\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n ArrayList selectedDocs = this.caseFolderPanel1.getSelectedDocuments();\n for (ArchiveFileDocumentsBean doc : selectedDocs) {\n byte[] content = locator.lookupArchiveFileServiceRemote().getDocumentContent(doc.getId());\n String tmpUrl = FileUtils.createTempFile(doc.getName(), content);\n if (!(tmpUrl.toLowerCase().endsWith(\".pdf\"))) {\n FileConverter conv = FileConverter.getInstance();\n tmpUrl = conv.convertToPDF(tmpUrl, doc);\n }\n PDFEncryptionDialog encDlg = new PDFEncryptionDialog(EditorsRegistry.getInstance().getMainWindow(), true, tmpUrl);\n for (ArchiveFileAddressesBean aab : this.pnlInvolvedParties.getInvolvedParties()) {\n encDlg.addRecipient(aab.getAddressKey());\n }\n FrameUtils.centerDialog(encDlg, EditorsRegistry.getInstance().getMainWindow());\n encDlg.setVisible(true);\n return;\n }\n } catch (Exception ioe) {\n log.error(\"Error encrypting document\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Verschl\u00fcsseln des Dokuments: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtUsernameKeyReleased\nprivate void txtPasswordKeyReleased(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_txtPasswordKeyReleased\n this.updateTarget();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdMoreActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdMoreActionPerformed\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdCancel2ActionPerformed\nprivate void cmdGetExternalLocationActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdGetExternalLocationActionPerformed\n GetExternLocationDialog dlg = new GetExternLocationDialog(this, true, this.txtTarget);\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static void updateLeft(TupleSets srcLeftTuples, TupleSets trgLeftTuples, TupleSets stagedLeftTuples, TupleMemory ltm){\r\n for (LeftTuple leftTuple = srcLeftTuples.getUpdateFirst(); leftTuple != null; ) {\r\n LeftTuple next = leftTuple.getStagedNext();\r\n LeftTuple childLeftTuple = leftTuple.getFirstChild();\r\n if (!leftTuple.isExpired() && childLeftTuple != null && childLeftTuple.getStagedType() == Tuple.NONE) {\r\n childLeftTuple.setPropagationContext(leftTuple.getPropagationContext());\r\n updateChildLeftTuple(childLeftTuple, stagedLeftTuples, trgLeftTuples);\r\n }\r\n leftTuple.clearStaged();\r\n leftTuple = next;\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Shuffle getShuffle(Configuration conf){\r\n return shuffle;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_treeFoldersMousePressed\nprivate void mnuRenameFolderActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuRenameFolderActionPerformed\n DefaultMutableTreeNode tn = (DefaultMutableTreeNode) this.treeFolders.getSelectionPath().getLastPathComponent();\n GenericNode gn = (GenericNode) tn.getUserObject();\n String oldFolderName = gn.getName();\n ClientSettings settings = ClientSettings.getInstance();\n Object newNameObject = JOptionPane.showInputDialog(this, \"Name des Ordners: \", \"Ordner umbenennen\", JOptionPane.QUESTION_MESSAGE, null, null, oldFolderName);\n if (newNameObject == null) {\n return;\n }\n String newFolderName = newNameObject.toString();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n boolean renamed = locator.lookupSystemManagementRemote().renameTemplateFolder(this.templateType, gn.getParent(), oldFolderName, newFolderName);\n if (renamed) {\n gn.setName(newFolderName);\n tn.setUserObject(gn);\n DefaultTreeModel dm = (DefaultTreeModel) this.treeFolders.getModel();\n dm.reload(tn);\n }\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Erstellen des Ordners: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void mnuDuplicateDocumentAsPdfActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuDuplicateDocumentAsPdfActionPerformed\n if (LoadDocumentPreviewThread.isRunning()) {\n JOptionPane.showMessageDialog(this, \"Bitte warten Sie bis die Dokumentvorschau abgeschlossen ist.\", \"Hinweis\", JOptionPane.PLAIN_MESSAGE);\n return;\n }\n try {\n ArrayList selected = this.caseFolderPanel1.getSelectedDocuments();\n if (selected.isEmpty()) {\n return;\n }\n ArrayList open = this.getDocumentsOpenForWrite(selected);\n if (!open.isEmpty()) {\n String question = \"Soll die Aktion auf ge\u00f6ffnete Dokumente ausgef\u00fchrt werden? Es besteht das Risiko fehlender / inkonsistenter Inhalte.
    \";\n for (String o : open) {\n question = question + \"
  • \" + o + \"
  • \";\n }\n question = question + \"
\";\n int response = JOptionPane.showConfirmDialog(this, question, \"Aktion auf offene Dokumente ausf\u00fchren\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n return;\n }\n }\n for (ArchiveFileDocumentsBean doc : selected) {\n this.convertDocumentToPdf(doc);\n }\n } catch (Exception ioe) {\n log.error(\"Error duplicating document\", ioe);\n JOptionPane.showMessageDialog(this, \"Fehler beim Duplizieren des Dokuments: \" + ioe.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_renameButtonActionPerformed\nprivate void helpButtonActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_helpButtonActionPerformed\n new HelpCtx(PerspectiveBookmarkTopComponent.class.getName()).display();\n}", "smellKey": "S1172", "smellId": null, "repo": "constellation-app_constellation", "language": "java"} {"function": "protected String extractCasesUrl(T annotation) {\n return null;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hop", "language": "java"} {"function": "public Integer splitCount(RelNode rel, RelMetadataQuery mq){\r\n return 1;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n * Accept a visitor to visit this {@link INode}.\n */\npublic void accept(NamespaceVisitor visitor, int snapshot) {\n final Class clazz = visitor != null ? visitor.getClass() : NamespaceVisitor.class;\n throw new UnsupportedOperationException(getClass().getSimpleName() + \" does not support \" + clazz.getSimpleName());\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSaveActionPerformed\n ClientSettings settings = ClientSettings.getInstance();\n if (this.lstLaunchers.getSelectedIndex() < 0) {\n return;\n } else {\n if (!(this.lstLaunchers.getSelectedValue().equals(this.txtLauncherName.getText()))) {\n // launcher has been renamed - remove existing configuration\n settings.removeConfiguration(CL_PREFIX + \".\" + this.lstLaunchers.getSelectedValue() + \".\" + CL_SUFFIX_EXE);\n settings.removeConfiguration(CL_PREFIX + \".\" + this.lstLaunchers.getSelectedValue() + \".\" + CL_SUFFIX_RO);\n settings.removeConfiguration(CL_PREFIX + \".\" + this.lstLaunchers.getSelectedValue() + \".\" + CL_SUFFIX_RW);\n settings.removeConfiguration(CL_PREFIX + \".\" + this.lstLaunchers.getSelectedValue() + \".\" + CL_SUFFIX_EXTENSION);\n ((DefaultListModel) this.lstLaunchers.getModel()).addElement(this.txtLauncherName.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_EXE, this.txtExecutable.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_RO, this.txtParamsRo.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_RW, this.txtParamsRw.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_EXTENSION, this.txtExtension.getText());\n if (this.chkDefaultLauncher.isSelected())\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_DEFAULT, \"1\");\n else\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_DEFAULT, \"0\");\n ((DefaultListModel) this.lstLaunchers.getModel()).removeElement(this.lstLaunchers.getSelectedValue());\n } else {\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_EXE, this.txtExecutable.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_RO, this.txtParamsRo.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_RW, this.txtParamsRw.getText());\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_EXTENSION, this.txtExtension.getText());\n if (this.chkDefaultLauncher.isSelected())\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_DEFAULT, \"1\");\n else\n settings.setConfiguration(CL_PREFIX + \".\" + this.txtLauncherName.getText() + \".\" + CL_SUFFIX_DEFAULT, \"0\");\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdTimesheetPositionsActionPerformed\nprivate void cmdGiroCodeActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdGiroCodeActionPerformed\n try {\n BigDecimal amount = BigDecimal.ZERO;\n boolean validAmount = false;\n try {\n amount = BigDecimal.valueOf(cf.parse(this.lblInvoiceTotal.getText()).floatValue());\n validAmount = true;\n } catch (Throwable t) {\n log.error(\"error parsing invoice total: \" + this.lblInvoiceTotal.getText(), t);\n }\n if (validAmount) {\n GirocodeDialog gcd = new GirocodeDialog(this, true, this.cmbInvoiceSender.getSelectedItem().toString(), amount, this.lblInvoiceNumber.getText());\n FrameUtils.centerDialog(gcd, this);\n gcd.setVisible(true);\n } else {\n JOptionPane.showMessageDialog(this, \"Der Rechnungsbetrag ist ung\u00fcltig.\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_HINT, JOptionPane.INFORMATION_MESSAGE);\n }\n } catch (Exception ex) {\n log.error(\"error loading invoice document\", ex);\n JOptionPane.showMessageDialog(this, \"Girocode kann nicht erstellt werden: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_lblExtractedNumbersMouseEntered\nprivate void lblExtractedNumbersMouseExited(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblExtractedNumbersMouseExited\n this.lblExtractedNumbers.setForeground(Color.BLACK);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected V callPutSync(K key, Data keyData, V value, Data valueData, Data expiryPolicyData, boolean isGet) throws InterruptedException, ExecutionException{\r\n ClientInvocationFuture invocationFuture = putInternal(keyData, valueData, expiryPolicyData, isGet, true);\r\n ClientDelegatingFuture delegatingFuture = newDelegatingFuture(invocationFuture, CachePutCodec::decodeResponse);\r\n return delegatingFuture.get();\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static int eval(int x){\r\n return 1;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "/**\n */\npublic RelOptCost getCumulativeCost(RelSubset rel, RelMetadataQuery mq) {\n return VolcanoUtils.bestCost(rel);\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_ignite", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdPlayPauseActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdPlayPauseActionPerformed\n togglePlayPause();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void checkBootstrapResults(int totalRecords, Schema schema, String instant, boolean checkNumRawFiles, int expNumInstants, int numVersions, long expTimestamp, long expROTimestamp, boolean isDeltaCommit, List instantsWithValidRecords, boolean validateCommitRecords) throws Exception {\n metaClient.reloadActiveTimeline();\n assertEquals(expNumInstants, metaClient.getCommitsTimeline().filterCompletedInstants().countInstants());\n assertEquals(instant, metaClient.getActiveTimeline().getCommitsTimeline().filterCompletedInstants().lastInstant().get().requestedTime());\n Dataset bootstrapped = sqlContext.read().format(\"orc\").load(basePath);\n Dataset original = sqlContext.read().format(\"orc\").load(bootstrapBasePath);\n bootstrapped.registerTempTable(\"bootstrapped\");\n original.registerTempTable(\"original\");\n if (checkNumRawFiles) {\n List files = BootstrapUtils.getAllLeafFoldersWithFiles(metaClient.getTableConfig().getBaseFileFormat(), metaClient.getStorage(), bootstrapBasePath, context).stream().flatMap(x -> x.getValue().stream()).collect(Collectors.toList());\n assertEquals(files.size() * numVersions, sqlContext.sql(\"select distinct _hoodie_file_name from bootstrapped\").count());\n }\n if (!isDeltaCommit) {\n String predicate = String.join(\", \", instantsWithValidRecords.stream().map(p -> \"\\\"\" + p + \"\\\"\").collect(Collectors.toList()));\n if (validateCommitRecords) {\n assertEquals(totalRecords, sqlContext.sql(\"select * from bootstrapped where _hoodie_commit_time IN \" + \"(\" + predicate + \")\").count());\n }\n Dataset missingOriginal = sqlContext.sql(\"select a._row_key from original a where a._row_key not \" + \"in (select _hoodie_record_key from bootstrapped)\");\n assertEquals(0, missingOriginal.count());\n Dataset missingBootstrapped = sqlContext.sql(\"select a._hoodie_record_key from bootstrapped a \" + \"where a._hoodie_record_key not in (select _row_key from original)\");\n assertEquals(0, missingBootstrapped.count());\n //sqlContext.sql(\"select * from bootstrapped\").show(10, false);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "apachehudi-ci_hudi-mirror", "language": "java"} {"function": "//~ Methods ----------------------------------------------------------------\npublic Boolean isPhaseTransition(HiveJoin join, RelMetadataQuery mq) {\n return join.isPhaseTransition();\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_lstMailTemplatesMouseClicked\nprivate void cmdNewActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdNewActionPerformed\n String fileName = JOptionPane.showInputDialog(this, \"Name der neuen Vorlage: \", \"neue E-Mail - Vorlage\", JOptionPane.QUESTION_MESSAGE);\n if (fileName == null)\n return;\n fileName = fileName.replaceAll(\" \", \"-\");\n fileName = fileName + \".xml\";\n if (fileName.length() == 0) {\n JOptionPane.showMessageDialog(this, \"Dateiname darf nicht leer sein.\", CommonStrings.HINT, JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ClientSettings settings = ClientSettings.getInstance();\n try {\n JLawyerServiceLocator locator = JLawyerServiceLocator.getInstance(settings.getLookupProperties());\n EmailTemplate tpl = new EmailTemplate();\n tpl.setBody(\"\");\n tpl.setFileName(fileName);\n tpl.setFormat(\"\");\n tpl.setSubject(\"\");\n locator.lookupIntegrationServiceRemote().saveEmailTemplate(tpl, false);\n } catch (Exception ex) {\n JOptionPane.showMessageDialog(this, \"Fehler beim Erstellen der Vorlage: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n this.refreshList();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_cmdNewSmsActionPerformed\nprivate void cmdShowWebsiteActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdShowWebsiteActionPerformed\n if (this.txtWebsite.getText() != null && !\"\".equalsIgnoreCase(this.txtWebsite.getText())) {\n DesktopUtils.openBrowser(this.txtWebsite.getText());\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "/**\n * Try to locate the required token for the server.\n *\n * @param authType of the SASL client\n * @return Token for server, or null if no token available\n * @throws IOException - token selector cannot be instantiated\n */\nprivate Token getServerToken(SaslAuth authType) throws IOException {\n TokenInfo tokenInfo = SecurityUtil.getTokenInfo(protocol, conf);\n LOG.debug(\"Get token info proto:\" + protocol + \" info:\" + tokenInfo);\n if (tokenInfo == null) {\n // protocol has no support for tokens\n return null;\n }\n TokenSelector tokenSelector = null;\n try {\n tokenSelector = tokenInfo.value().newInstance();\n } catch (InstantiationException | IllegalAccessException e) {\n throw new IOException(e.toString(), e);\n }\n return tokenSelector.selectToken(SecurityUtil.buildTokenService(serverAddr), ugi.getTokens());\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public Shuttle preVisit(ConditionalStatement conditionalStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void taEditKeyTyped(java.awt.event.KeyEvent evt) {\n //GEN-FIRST:event_taEditKeyTyped\n markdownPane.setMarkdownText(this.taEdit.getText());\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_lblArchiveFileMouseClicked\nprivate void lblArchiveFileMouseEntered(java.awt.event.MouseEvent evt) {\n //GEN-FIRST:event_lblArchiveFileMouseEntered\n this.lblArchiveFile.setForeground(Color.ORANGE);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private static boolean run(String cmd, boolean errorOnFail, IDriver myDriver) throws RuntimeException {\n boolean success = false;\n try {\n myDriver.run(cmd);\n success = true;\n } catch (CommandProcessorException e) {\n LOG.warn(\"Error {} : {} running [{}].\", e.getErrorCode(), e.getMessage(), cmd);\n }\n return success;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "public List validateReport(SituationReport report, long effectiveAsOfMillis) throws DaoException {\n logger.debug(\"[] groups = new Class[] { SituationReportConstraints.class };\n List results = this.validate(report, groups);\n logger.debug(\">validateReport \" + results.size());\n return results;\n}", "smellKey": "S1172", "smellId": null, "repo": "bcgov_nr-bcws-wfnews", "language": "java"} {"function": "protected boolean collapse(RecordIdentifier recordIdentifier) {\n return true;\n}", "smellKey": "S1172", "smellId": null, "repo": "apache_hive", "language": "java"} {"function": "//GEN-LAST:event_mnuShowBeaIdentityActionPerformed\nprivate void mnuSendSmsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_mnuSendSmsActionPerformed\n if (this.a.getMobile() == null || \"\".equals(this.a.getMobile())) {\n JOptionPane.showMessageDialog(this, \"Zu diesem Kontakt ist keine Mobilnummer erfasst.\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n } else {\n if (UserSettings.getInstance().getCurrentUser().isVoipEnabled()) {\n SendSmsDialog dlg = new SendSmsDialog(EditorsRegistry.getInstance().getMainWindow(), true, this.a);\n FrameUtils.centerDialog(dlg, EditorsRegistry.getInstance().getMainWindow());\n dlg.setVisible(true);\n } else {\n JOptionPane.showMessageDialog(this, \"Voice-over-IP - Integration ist nicht aktiviert!\", \"SMS senden\", JOptionPane.INFORMATION_MESSAGE);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "private void check3StopArea3(Context context, int rank, StopArea stopArea, int rank2, StopArea stopArea2){\n if (!stopArea2.getAreaType().equals(stopArea.getAreaType()))\n return;\n if (!Objects.equals(stopArea.getName(), stopArea2.getName())) {\n return;\n }\n if (stopArea.getStreetName() != null && !stopArea.getStreetName().equals(stopArea2.getStreetName())) {\n return;\n }\n if (stopArea.getCountryCode() != null && !stopArea.getCountryCode().equals(stopArea2.getCountryCode())) {\n return;\n }\n Collection lines = getLines(context, stopArea);\n Collection lines2 = getLines(context, stopArea2);\n if (lines.containsAll(lines2) && lines2.containsAll(lines)) {\n DataLocation source = buildLocation(context, stopArea);\n DataLocation target = buildLocation(context, stopArea2);\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\n reporter.addCheckPointReportError(context, STOP_AREA_3, source, null, null, target);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String getClassName(@SuppressWarnings(\"unused\") RelDataType type){\n return Object.class.getName();\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void sequentialTest(FileSystem fs, TestType testType, // in bytes\nlong fileSize, int nrFiles) throws IOException {\n IOStatMapper ioer = null;\n switch(testType) {\n case TEST_TYPE_READ:\n ioer = new ReadMapper();\n break;\n case TEST_TYPE_WRITE:\n ioer = new WriteMapper();\n break;\n case TEST_TYPE_APPEND:\n ioer = new AppendMapper();\n break;\n case TEST_TYPE_READ_RANDOM:\n case TEST_TYPE_READ_BACKWARD:\n case TEST_TYPE_READ_SKIP:\n ioer = new RandomReadMapper();\n break;\n case TEST_TYPE_TRUNCATE:\n ioer = new TruncateMapper();\n break;\n default:\n return;\n }\n for (int i = 0; i < nrFiles; i++) ioer.doIO(Reporter.NULL, BASE_FILE_NAME + Integer.toString(i), fileSize);\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "public void writeBool(boolean b, String tag) throws IOException{\n out.writeBool(b);\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdSendActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdSendActionPerformed\n if (StringUtils.isEmpty(this.txtSubject.getText())) {\n int response = JOptionPane.showConfirmDialog(this, \"Nachricht ohne Betreff senden?\", \"leerer Betreff\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n this.txtSubject.requestFocus();\n return;\n }\n }\n MailboxSetup ms = this.getSelectedMailbox();\n ClientSettings settings = ClientSettings.getInstance();\n if (this.chkSaveAsDocument.isSelected()) {\n settings.setConfiguration(ClientSettings.CONF_MAIL_SAVETOARCHIVEFILE, \"1\");\n } else {\n settings.setConfiguration(ClientSettings.CONF_MAIL_SAVETOARCHIVEFILE, \"0\");\n }\n ProgressIndicator dlg = new ProgressIndicator(this, true);\n EditorImplementation ed = (EditorImplementation) this.contentPanel.getComponent(0);\n String contentType = ed.getContentType();\n ArrayList mails = EmailUtils.getAllMailAddressesFromString(this.txtTo.getText());\n mails.addAll(EmailUtils.getAllMailAddressesFromString(this.txtCc.getText()));\n mails.addAll(EmailUtils.getAllMailAddressesFromString(this.txtBcc.getText()));\n String editorContent = ed.getText();\n editorContent = editorContent.replaceAll(\"

[\\\\s ]*

\", \"

 

\");\n editorContent = editorContent.replaceAll(\"
[\\\\s ]*
\", \"
 
\");\n ed.setText(editorContent);\n if (mails.isEmpty()) {\n ThreadUtils.showErrorDialog(this, \"Liste der Empf\u00e4nger kann nicht leer sein.\", com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR);\n return;\n }\n if (this.chkSaveAsDocument.isSelected() || !(this.radioReviewTypeNone.isSelected())) {\n if (this.contextArchiveFile == null) {\n SearchAndAssignDialog saDlg = new SearchAndAssignDialog(this, true, \"\" + this.txtSubject.getText() + ed.getText(), null);\n saDlg.setCancelButtonCaption(\"Senden ohne zu speichern\", \"E-Mail wird gesendet, jedoch nicht zu einer Akte gespeichert\");\n saDlg.setConfirmButtonCaption(\"Senden und speichern\", \"E-Mail wird gesendet und zur gew\u00e4hlten Akte gespeichert\");\n saDlg.setVisible(true);\n this.contextArchiveFile = saDlg.getCaseSelection();\n this.contextArchiveFileFolder = saDlg.getFolderSelection();\n saDlg.dispose();\n }\n }\n String createDocumentTag = null;\n if (this.chkDocumentTagging.isSelected()) {\n Object selectedTag = this.cmbDocumentTag.getSelectedItem();\n if (selectedTag != null) {\n if (!\"\".equals(selectedTag.toString())) {\n createDocumentTag = selectedTag.toString();\n }\n }\n }\n if (!(this.radioReviewTypeNone.isSelected()) && this.contextArchiveFile != null) {\n if (this.txtReviewDateField.getText().length() != 10) {\n JOptionPane.showMessageDialog(this, \"Wiedervorlagedatum ung\u00fcltig\", \"E-Mail senden\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n Date d = null;\n try {\n SimpleDateFormat df = new SimpleDateFormat(\"dd.MM.yyyy\");\n d = df.parse(this.txtReviewDateField.getText());\n } catch (Throwable t) {\n JOptionPane.showMessageDialog(this, \"Wiedervorlagedatum ung\u00fcltig\", \"E-Mail senden\", JOptionPane.INFORMATION_MESSAGE);\n return;\n }\n ArchiveFileReviewsBean reviewDto = new ArchiveFileReviewsBean();\n reviewDto.setEventType(ArchiveFileReviewsBean.EVENTTYPE_FOLLOWUP);\n if (this.radioReviewTypeRespite.isSelected()) {\n reviewDto.setEventType(ArchiveFileReviewsBean.EVENTTYPE_RESPITE);\n }\n reviewDto.setDone(false);\n reviewDto.setBeginDate(d);\n reviewDto.setAssignee(this.cmbReviewAssignee.getSelectedItem().toString());\n reviewDto.setSummary(this.cmbReviewReason.getEditor().getItem().toString());\n reviewDto.setCalendarSetup(this.calendarSelectionButton1.getSelectedSetup());\n if (CalendarUtils.checkForConflicts(this, reviewDto)) {\n try {\n CalendarUtils.getInstance().storeCalendarEntry(reviewDto, this.contextArchiveFile, (CalendarEntryTemplate) this.cmbReviewReason.getItemAt(this.cmbReviewReason.getSelectedIndex()), this);\n } catch (Exception ex) {\n log.error(\"Error adding review\", ex);\n JOptionPane.showMessageDialog(this, \"Fehler beim Speichern des Kalendereintrages: \" + ex.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR, JOptionPane.ERROR_MESSAGE);\n }\n }\n }\n ProgressableAction a = null;\n if (this.chkSaveAsDocument.isSelected()) {\n try {\n if (this.contextArchiveFile != null) {\n CaseUtils.optionalUnarchiveCase(this.contextArchiveFile, this);\n }\n } catch (Exception ex) {\n log.error(\"Unable to unarchive case \" + this.contextArchiveFile.getFileNumber(), ex);\n }\n if (this.chkEncryption.isSelected()) {\n int crypto = 0;\n try {\n crypto = this.cryptoRecipients(mails);\n } catch (Throwable t) {\n ThreadUtils.showErrorDialog(this, \"Fehler: \" + t.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR);\n return;\n }\n if (crypto < mails.size()) {\n int response = JOptionPane.showConfirmDialog(this, \"Verschl\u00fcsselung f\u00fcr \" + crypto + \" von \" + mails.size() + \" Empf\u00e4ngern - fortfahren?\", \"Verschl\u00fcsselung\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n return;\n }\n }\n a = new SendEncryptedAction(dlg, this, new ArrayList<>(this.attachments.values()), ms, this.chkReadReceipt.isSelected(), this.txtTo.getText(), this.txtCc.getText(), this.txtBcc.getText(), this.txtSubject.getText(), ed.getText(), contentType, this.contextArchiveFile, createDocumentTag, this.contextArchiveFileFolder);\n } else {\n a = new SendAction(dlg, this, new ArrayList<>(this.attachments.values()), ms, this.chkReadReceipt.isSelected(), this.txtTo.getText(), this.txtCc.getText(), this.txtBcc.getText(), this.txtSubject.getText(), ed.getText(), contentType, this.contextArchiveFile, createDocumentTag, this.contextArchiveFileFolder);\n }\n } else if (this.chkEncryption.isSelected()) {\n int crypto = 0;\n try {\n crypto = this.cryptoRecipients(mails);\n } catch (Throwable t) {\n ThreadUtils.showErrorDialog(this, \"Fehler: \" + t.getMessage(), com.jdimension.jlawyer.client.utils.DesktopUtils.POPUP_TITLE_ERROR);\n return;\n }\n if (crypto < mails.size()) {\n int response = JOptionPane.showConfirmDialog(this, \"Verschl\u00fcsselung f\u00fcr \" + crypto + \" von \" + mails.size() + \" Empf\u00e4ngern - fortfahren?\", \"Verschl\u00fcsselung\", JOptionPane.YES_NO_OPTION);\n if (response == JOptionPane.NO_OPTION) {\n return;\n }\n }\n a = new SendEncryptedAction(dlg, this, new ArrayList<>(this.attachments.values()), ms, this.chkReadReceipt.isSelected(), this.txtTo.getText(), this.txtCc.getText(), this.txtBcc.getText(), this.txtSubject.getText(), ed.getText(), contentType, createDocumentTag);\n } else {\n a = new SendAction(dlg, this, new ArrayList<>(this.attachments.values()), ms, this.chkReadReceipt.isSelected(), this.txtTo.getText(), this.txtCc.getText(), this.txtBcc.getText(), this.txtSubject.getText(), ed.getText(), contentType, createDocumentTag);\n }\n a.start();\n UserSettings uset = UserSettings.getInstance();\n if (ms != null) {\n uset.setSetting(UserSettings.CONF_MAIL_LASTUSEDSETUP, ms.getDisplayName());\n }\n if (this.cmbTemplates.getSelectedItem() != null) {\n uset.setSetting(UserSettings.CONF_MAIL_LASTUSEDTEMPLATE, this.cmbTemplates.getSelectedItem().toString());\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void testXslt(String styleSheetName, String input, String expected, Boolean omitXmlDeclaration, Boolean indent, Boolean skipEmptyTags, Boolean removeNamespaces, Boolean xslt2) throws Exception {\n setStyleSheetName(styleSheetName);\n if (omitXmlDeclaration != null) {\n setOmitXmlDeclaration(omitXmlDeclaration);\n }\n if (indent != null) {\n setIndent(indent);\n }\n if (skipEmptyTags != null) {\n setSkipEmptyTags(skipEmptyTags);\n }\n if (removeNamespaces != null) {\n setRemoveNamespaces(removeNamespaces);\n }\n pipe.configure();\n pipe.start();\n PipeRunResult prr = doPipe(pipe, input, session);\n String result = prr.getResult().asString();\n assertResultsAreCorrect(expected, result.trim(), session);\n}", "smellKey": "S1172", "smellId": null, "repo": "ibissource_iaf", "language": "java"} {"function": "// //GEN-END:initComponents\nprivate void cmdImportActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdImportActionPerformed\n new Thread(new ImportBanksThread(this, this.progBar, this.cmdClose, this.cmdImport)).start();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "protected void unsetRealmService(RealmService realmService) {\n if (log.isDebugEnabled()) {\n log.debug(\"Unsetting the Realm Service.\");\n }\n RoleManagementServiceComponentHolder.getInstance().setRealmService(null);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "public boolean rehash(String line){\n try {\n if (!(beeLine.assertConnection())) {\n return false;\n }\n if (beeLine.getDatabaseConnection() != null) {\n beeLine.getDatabaseConnection().setCompletions(false);\n }\n return true;\n } catch (Exception e) {\n return beeLine.error(e);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "//GEN-LAST:event_cmdReplyActionPerformed\nprivate void cmdReplyAllActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdReplyAllActionPerformed\n SendEmailDialog dlg = new SendEmailDialog(true, EditorsRegistry.getInstance().getMainWindow(), false);\n dlg.setArchiveFile(this.contextArchiveFile, this.contextFolder);\n this.setPartiesToSendDialog(dlg, false);\n if (this.emlMsg != null) {\n MessageContainer msgC = this.emlMsg;\n try {\n Message origM = msgC.getMessage();\n MailboxSetup ms = EmailUtils.getMailboxSetup(origM);\n if (ms != null) {\n dlg.setFrom(ms);\n }\n Message m = origM.reply(true);\n try {\n Address[] to = m.getRecipients(RecipientType.TO);\n String toString = EmailUtils.getAddressesAsList(to);\n Address[] cc = m.getRecipients(RecipientType.CC);\n String ccString = EmailUtils.getAddressesAsList(cc);\n Address[] bcc = m.getRecipients(RecipientType.BCC);\n String bccString = EmailUtils.getAddressesAsList(bcc);\n dlg.setTo(toString);\n dlg.setCC(ccString);\n dlg.setBCC(bccString);\n } catch (Throwable t) {\n log.error(t);\n dlg.setTo(m.getRecipients(RecipientType.TO)[0].toString());\n }\n String subject = m.getSubject();\n if (subject == null) {\n subject = \"\";\n }\n if (!subject.startsWith(\"Re: \")) {\n subject = \"Re: \" + subject;\n }\n dlg.setSubject(subject);\n String decodedTo = origM.getFrom()[0].toString();\n try {\n decodedTo = MimeUtility.decodeText(origM.getFrom()[0].toString());\n } catch (Throwable t) {\n log.error(t);\n }\n String contentType = this.content.getContentType();\n dlg.setContentType(contentType);\n if (contentType.toLowerCase().startsWith(ContentTypes.TEXT_HTML)) {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(EmailUtils.html2Text(this.content.getBody()), ContentTypes.TEXT_PLAIN, decodedTo, origM.getSentDate()), ContentTypes.TEXT_PLAIN);\n } else {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.content.getBody(), ContentTypes.TEXT_PLAIN, decodedTo, origM.getSentDate()), ContentTypes.TEXT_PLAIN);\n }\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.content.getBody(), ContentTypes.TEXT_HTML, decodedTo, origM.getSentDate()), ContentTypes.TEXT_HTML);\n } catch (Exception ex) {\n log.error(ex);\n }\n } else {\n try {\n MailboxSetup ms = EmailUtils.getMailboxSetup(this.outlookMsg);\n if (ms != null) {\n dlg.setFrom(ms);\n }\n String subject = this.outlookMsg.getSubject();\n if (subject == null) {\n subject = \"\";\n }\n if (!subject.startsWith(\"Re: \")) {\n subject = \"Re: \" + subject;\n }\n dlg.setSubject(subject);\n String decodedTo = this.outlookMsg.getFromEmail();\n String contentType = this.content.getContentType();\n dlg.setContentType(contentType);\n if (contentType.toLowerCase().startsWith(ContentTypes.TEXT_HTML)) {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(EmailUtils.html2Text(this.content.getBody()), ContentTypes.TEXT_PLAIN, decodedTo, this.outlookMsg.getDate()), ContentTypes.TEXT_PLAIN);\n } else {\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.content.getBody(), ContentTypes.TEXT_PLAIN, decodedTo, this.outlookMsg.getDate()), ContentTypes.TEXT_PLAIN);\n }\n dlg.setBody(\"\", EmailUtils.getQuotedBody(this.content.getBody(), ContentTypes.TEXT_HTML, decodedTo, this.outlookMsg.getDate()), ContentTypes.TEXT_HTML);\n } catch (Exception ex) {\n log.error(ex);\n }\n }\n FrameUtils.centerDialog(dlg, null);\n dlg.setVisible(true);\n if (this.odoc != null) {\n this.odoc.setClosed(true);\n }\n this.setVisible(false);\n this.dispose();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "//GEN-LAST:event_txtReviewDateFieldMouseClicked\nprivate void cmdTranscribeActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdTranscribeActionPerformed\n if (!isRecording) {\n startRecording();\n ClientSettings.getInstance().setConfiguration(ClientSettings.CONF_SOUND_LASTRECORDINGDEVICE, (String) this.cmbDevices.getSelectedItem());\n } else {\n try {\n stopRecording();\n } catch (IOException ex) {\n java.util.logging.Logger.getLogger(AddNoteDialog.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public void setMember(String name, Object value) {\n Objects.requireNonNull(name);\n}", "smellKey": "S1172", "smellId": null, "repo": "wso2_carbon-identity-framework", "language": "java"} {"function": "//GEN-LAST:event_chkInvoicesActionPerformed\nprivate void chkTimesheetsActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_chkTimesheetsActionPerformed\n this.enableArchival();\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public static void createValidationFiles(URL url, File localDestination, URL hashURL, Hash hash){\r\n try {\r\n URLConnection resourceConnection = url.openConnection();\r\n createValidationFiles(resourceConnection, localDestination, hashURL, FileDownloadUtils.Hash.UNKNOWN);\r\n } catch (IOException e) {\r\n logger.warn(\"could not open connection to resource file due to exception: {}\", e.getMessage());\r\n }\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void createMapFile(Configuration conf, FileSystem fs, Path path, CompressionCodec codec, CompressionType type, int records) throws IOException {\n MapFile.Writer writer = new MapFile.Writer(conf, path, MapFile.Writer.keyClass(Text.class), MapFile.Writer.valueClass(Text.class), MapFile.Writer.compression(type, codec));\n Text key = new Text();\n for (int j = 0; j < records; j++) {\n key.set(String.format(\"%03d\", j));\n writer.append(key, key);\n }\n writer.close();\n}", "smellKey": "S1172", "smellId": null, "repo": "BTIGIT03_apache_hadoop", "language": "java"} {"function": "//GEN-LAST:event_cmdFirstPageActionPerformed\nprivate void cmdLastPageActionPerformed(java.awt.event.ActionEvent evt) {\n //GEN-FIRST:event_cmdLastPageActionPerformed\n this.scrollToPage(this.renderedPages - 1, true);\n}", "smellKey": "S1172", "smellId": null, "repo": "jlawyerorg_j-lawyer-org", "language": "java"} {"function": "public Shuttle preVisit(BlockStatement blockStatement){\r\n return this;\r\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void unregisterChildWatcher(String path, Watcher watcher, boolean removeFromServer){\n Set watchers = childWatches.get(path);\n if (null == watchers) {\n logger.warn(\"No watchers found on path {} while unregistering child watcher {}.\", path, watcher);\n return;\n }\n synchronized (watchers) {\n if (watchers.remove(watcher)) {\n allWatchesGauge.decrement();\n } else {\n logger.warn(\"Remove a non-registered child watcher {} from path {}\", watcher, path);\n }\n if (watchers.isEmpty()) {\n childWatches.remove(path, watchers);\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Shuttle preVisit(GotoStatement gotoStatement){\n return this;\n}", "smellKey": "S1172", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String buildStateMessage(long date, String ip){\r\n StateReport report = queryHourlyReport(date, ip);\r\n if (report != null) {\r\n int realSize = report.getMachines().size();\r\n List servers = queryAllServers();\r\n int excepeted = servers.size();\r\n Set errorServers = new HashSet();\r\n if (realSize != excepeted) {\r\n for (String serverIp : servers) {\r\n if (report.getMachines().get(serverIp) == null) {\r\n errorServers.add(serverIp);\r\n }\r\n }\r\n }\r\n for (Machine machine : report.getMachines().values()) {\r\n if (checkTooMuchLoss(machine)) {\r\n errorServers.add(machine.getIp());\r\n }\r\n }\r\n if (errorServers.size() > 0) {\r\n return errorServers.toString();\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final MultiJoin multiJoinRel = call.rel(0);\r\n final RexBuilder rexBuilder = multiJoinRel.getCluster().getRexBuilder();\r\n final RelBuilder relBuilder = call.builder();\r\n final RelMetadataQuery mq = call.getMetadataQuery();\r\n final LoptMultiJoin multiJoin = new LoptMultiJoin(multiJoinRel);\r\n final List vertexes = new ArrayList<>();\r\n int x = 0;\r\n for (int i = 0; i < multiJoin.getNumJoinFactors(); i++) {\r\n final RelNode rel = multiJoin.getJoinFactor(i);\r\n double cost = mq.getRowCount(rel);\r\n vertexes.add(new LeafVertex(i, rel, cost, x));\r\n x += rel.getRowType().getFieldCount();\r\n }\r\n assert x == multiJoin.getNumTotalFields();\r\n final List unusedEdges = new ArrayList<>();\r\n for (RexNode node : multiJoin.getJoinFilters()) {\r\n unusedEdges.add(multiJoin.createEdge(node));\r\n }\r\n final Comparator edgeComparator = new Comparator() {\r\n\r\n @Override\r\n public int compare(LoptMultiJoin.Edge e0, LoptMultiJoin.Edge e1) {\r\n return Double.compare(rowCountDiff(e0), rowCountDiff(e1));\r\n }\r\n\r\n private double rowCountDiff(LoptMultiJoin.Edge edge) {\r\n assert edge.factors.cardinality() == 2 : edge.factors;\r\n final int factor0 = edge.factors.nextSetBit(0);\r\n final int factor1 = edge.factors.nextSetBit(factor0 + 1);\r\n return Math.abs(vertexes.get(factor0).cost - vertexes.get(factor1).cost);\r\n }\r\n };\r\n final List usedEdges = new ArrayList<>();\r\n for (; ; ) {\r\n final int edgeOrdinal = chooseBestEdge(unusedEdges, edgeComparator);\r\n if (pw != null) {\r\n trace(vertexes, unusedEdges, usedEdges, edgeOrdinal, pw);\r\n }\r\n final int[] factors;\r\n if (edgeOrdinal == -1) {\r\n final Vertex lastVertex = Util.last(vertexes);\r\n final int z = lastVertex.factors.previousClearBit(lastVertex.id - 1);\r\n if (z < 0) {\r\n break;\r\n }\r\n factors = new int[] { z, lastVertex.id };\r\n } else {\r\n final LoptMultiJoin.Edge bestEdge = unusedEdges.get(edgeOrdinal);\r\n assert bestEdge.factors.cardinality() == 2;\r\n factors = bestEdge.factors.toArray();\r\n }\r\n final int majorFactor;\r\n final int minorFactor;\r\n if (vertexes.get(factors[0]).cost <= vertexes.get(factors[1]).cost) {\r\n majorFactor = factors[0];\r\n minorFactor = factors[1];\r\n } else {\r\n majorFactor = factors[1];\r\n minorFactor = factors[0];\r\n }\r\n final Vertex majorVertex = vertexes.get(majorFactor);\r\n final Vertex minorVertex = vertexes.get(minorFactor);\r\n final int v = vertexes.size();\r\n final ImmutableBitSet newFactors = majorVertex.factors.rebuild().addAll(minorVertex.factors).set(v).build();\r\n final List conditions = new ArrayList<>();\r\n final Iterator edgeIterator = unusedEdges.iterator();\r\n while (edgeIterator.hasNext()) {\r\n LoptMultiJoin.Edge edge = edgeIterator.next();\r\n if (newFactors.contains(edge.factors)) {\r\n conditions.add(edge.condition);\r\n edgeIterator.remove();\r\n usedEdges.add(edge);\r\n }\r\n }\r\n double cost = majorVertex.cost * minorVertex.cost * RelMdUtil.guessSelectivity(RexUtil.composeConjunction(rexBuilder, conditions));\r\n final Vertex newVertex = new JoinVertex(v, majorFactor, minorFactor, newFactors, cost, ImmutableList.copyOf(conditions));\r\n vertexes.add(newVertex);\r\n final ImmutableBitSet merged = ImmutableBitSet.of(minorFactor, majorFactor);\r\n for (int i = 0; i < unusedEdges.size(); i++) {\r\n final LoptMultiJoin.Edge edge = unusedEdges.get(i);\r\n if (edge.factors.intersects(merged)) {\r\n ImmutableBitSet newEdgeFactors = edge.factors.rebuild().removeAll(newFactors).set(v).build();\r\n assert newEdgeFactors.cardinality() == 2;\r\n final LoptMultiJoin.Edge newEdge = new LoptMultiJoin.Edge(edge.condition, newEdgeFactors, edge.columns);\r\n unusedEdges.set(i, newEdge);\r\n }\r\n }\r\n }\r\n List> relNodes = new ArrayList<>();\r\n for (Vertex vertex : vertexes) {\r\n if (vertex instanceof LeafVertex) {\r\n LeafVertex leafVertex = (LeafVertex) vertex;\r\n final Mappings.TargetMapping mapping = Mappings.offsetSource(Mappings.createIdentity(leafVertex.rel.getRowType().getFieldCount()), leafVertex.fieldOffset, multiJoin.getNumTotalFields());\r\n relNodes.add(Pair.of(leafVertex.rel, mapping));\r\n } else {\r\n JoinVertex joinVertex = (JoinVertex) vertex;\r\n final Pair leftPair = relNodes.get(joinVertex.leftFactor);\r\n RelNode left = leftPair.left;\r\n final Mappings.TargetMapping leftMapping = leftPair.right;\r\n final Pair rightPair = relNodes.get(joinVertex.rightFactor);\r\n RelNode right = rightPair.left;\r\n final Mappings.TargetMapping rightMapping = rightPair.right;\r\n final Mappings.TargetMapping mapping = Mappings.merge(leftMapping, Mappings.offsetTarget(rightMapping, left.getRowType().getFieldCount()));\r\n if (pw != null) {\r\n pw.println(\"left: \" + leftMapping);\r\n pw.println(\"right: \" + rightMapping);\r\n pw.println(\"combined: \" + mapping);\r\n pw.println();\r\n }\r\n final RexVisitor shuttle = new RexPermuteInputsShuttle(mapping, left, right);\r\n final RexNode condition = RexUtil.composeConjunction(rexBuilder, joinVertex.conditions);\r\n final RelNode join = relBuilder.push(left).push(right).join(JoinRelType.INNER, condition.accept(shuttle)).build();\r\n relNodes.add(Pair.of(join, mapping));\r\n }\r\n if (pw != null) {\r\n pw.println(Util.last(relNodes));\r\n }\r\n }\r\n final Pair top = Util.last(relNodes);\r\n relBuilder.push(top.left).project(relBuilder.fields(top.right));\r\n call.transformTo(relBuilder.build());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean membersReachableOnlyViaPublicAddress(Collection members){\r\n List shuffledList = new ArrayList<>(members);\r\n Collections.shuffle(shuffledList);\r\n Iterator iter = shuffledList.iterator();\r\n for (int i = 0; i < REACHABLE_CHECK_NUMBER; i++) {\r\n if (!iter.hasNext()) {\r\n iter = shuffledList.iterator();\r\n }\r\n Member member = iter.next();\r\n Address publicAddress = member.getAddressMap().get(CLIENT_PUBLIC_ENDPOINT_QUALIFIER);\r\n Address internalAddress = member.getAddress();\r\n if (publicAddress == null) {\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"The public address is not available on the member. The client will use internal addresses\");\r\n }\r\n return false;\r\n }\r\n if (isReachable(internalAddress, REACHABLE_ADDRESS_TIMEOUT_MILLIS)) {\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"The internal address is reachable. The client will use the internal addresses\");\r\n }\r\n return false;\r\n }\r\n if (!isReachable(publicAddress, NON_REACHABLE_ADDRESS_TIMEOUT_MILLIS)) {\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"Public address + \" + publicAddress + \" is not reachable. The client will use internal addresses\");\r\n }\r\n return false;\r\n }\r\n }\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"Members are accessible via only public addresses. The client will use public addresses\");\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Result visit(Match e){\r\n final RelNode input = e.getInput();\r\n final Result x = visitInput(e, 0);\r\n final Context context = matchRecognizeContext(x.qualifiedContext());\r\n SqlNode tableRef = x.asQueryOrValues();\r\n final RexBuilder rexBuilder = input.getCluster().getRexBuilder();\r\n final List partitionSqlList = new ArrayList<>();\r\n for (int key : e.getPartitionKeys()) {\r\n final RexInputRef ref = rexBuilder.makeInputRef(input, key);\r\n SqlNode sqlNode = context.toSql(null, ref);\r\n partitionSqlList.add(sqlNode);\r\n }\r\n final SqlNodeList partitionList = new SqlNodeList(partitionSqlList, POS);\r\n final List orderBySqlList = new ArrayList<>();\r\n if (e.getOrderKeys() != null) {\r\n for (RelFieldCollation fc : e.getOrderKeys().getFieldCollations()) {\r\n if (fc.nullDirection != RelFieldCollation.NullDirection.UNSPECIFIED) {\r\n boolean first = fc.nullDirection == RelFieldCollation.NullDirection.FIRST;\r\n SqlNode nullDirectionNode = dialect.emulateNullDirection(context.field(fc.getFieldIndex()), first, fc.direction.isDescending());\r\n if (nullDirectionNode != null) {\r\n orderBySqlList.add(nullDirectionNode);\r\n fc = new RelFieldCollation(fc.getFieldIndex(), fc.getDirection(), RelFieldCollation.NullDirection.UNSPECIFIED);\r\n }\r\n }\r\n orderBySqlList.add(context.toSql(fc));\r\n }\r\n }\r\n final SqlNodeList orderByList = new SqlNodeList(orderBySqlList, SqlParserPos.ZERO);\r\n final SqlLiteral rowsPerMatch = e.isAllRows() ? SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS.symbol(POS) : SqlMatchRecognize.RowsPerMatchOption.ONE_ROW.symbol(POS);\r\n final SqlNode after;\r\n if (e.getAfter() instanceof RexLiteral) {\r\n SqlMatchRecognize.AfterOption value = (SqlMatchRecognize.AfterOption) ((RexLiteral) e.getAfter()).getValue2();\r\n after = SqlLiteral.createSymbol(value, POS);\r\n } else {\r\n RexCall call = (RexCall) e.getAfter();\r\n String operand = requireNonNull(stringValue(call.getOperands().get(0)), () -> \"non-null string expected for 0th operand of AFTER call \" + call);\r\n after = call.getOperator().createCall(POS, new SqlIdentifier(operand, POS));\r\n }\r\n RexNode rexPattern = e.getPattern();\r\n final SqlNode pattern = context.toSql(null, rexPattern);\r\n final SqlLiteral strictStart = SqlLiteral.createBoolean(e.isStrictStart(), POS);\r\n final SqlLiteral strictEnd = SqlLiteral.createBoolean(e.isStrictEnd(), POS);\r\n RexLiteral rexInterval = (RexLiteral) e.getInterval();\r\n SqlIntervalLiteral interval = null;\r\n if (rexInterval != null) {\r\n interval = (SqlIntervalLiteral) context.toSql(null, rexInterval);\r\n }\r\n final SqlNodeList subsetList = new SqlNodeList(POS);\r\n for (Map.Entry> entry : e.getSubsets().entrySet()) {\r\n SqlNode left = new SqlIdentifier(entry.getKey(), POS);\r\n List rhl = new ArrayList<>();\r\n for (String right : entry.getValue()) {\r\n rhl.add(new SqlIdentifier(right, POS));\r\n }\r\n subsetList.add(SqlStdOperatorTable.EQUALS.createCall(POS, left, new SqlNodeList(rhl, POS)));\r\n }\r\n final SqlNodeList measureList = new SqlNodeList(POS);\r\n for (Map.Entry entry : e.getMeasures().entrySet()) {\r\n final String alias = entry.getKey();\r\n final SqlNode sqlNode = context.toSql(null, entry.getValue());\r\n measureList.add(as(sqlNode, alias));\r\n }\r\n final SqlNodeList patternDefList = new SqlNodeList(POS);\r\n for (Map.Entry entry : e.getPatternDefinitions().entrySet()) {\r\n final String alias = entry.getKey();\r\n final SqlNode sqlNode = context.toSql(null, entry.getValue());\r\n patternDefList.add(as(sqlNode, alias));\r\n }\r\n final SqlNode matchRecognize = new SqlMatchRecognize(POS, tableRef, pattern, strictStart, strictEnd, patternDefList, measureList, after, subsetList, rowsPerMatch, partitionList, orderByList, interval);\r\n return result(matchRecognize, Expressions.list(Clause.FROM), e, null);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseTarHeader(final Map globalPaxHeaders, final byte[] header, final ZipEncoding encoding, final boolean oldStyle, final boolean lenient) throws IOException{\r\n try {\r\n parseTarHeaderUnwrapped(globalPaxHeaders, header, encoding, oldStyle, lenient);\r\n } catch (final IllegalArgumentException ex) {\r\n throw new IOException(\"Corrupted TAR archive.\", ex);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic int lastIndexOf(@Nullable Object o){\r\n if (o == null) {\r\n if (t4 == null) {\r\n return 4;\r\n }\r\n if (t3 == null) {\r\n return 3;\r\n }\r\n if (t2 == null) {\r\n return 2;\r\n }\r\n if (t1 == null) {\r\n return 1;\r\n }\r\n if (t0 == null) {\r\n return 0;\r\n }\r\n } else {\r\n if (o.equals(t4)) {\r\n return 4;\r\n }\r\n if (o.equals(t3)) {\r\n return 3;\r\n }\r\n if (o.equals(t2)) {\r\n return 2;\r\n }\r\n if (o.equals(t1)) {\r\n return 1;\r\n }\r\n if (o.equals(t0)) {\r\n return 0;\r\n }\r\n }\r\n return -1;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void write(XTextDocument doc, XTextCursor position, OOText ootext) throws WrappedTargetException, CreationException{\r\n Objects.requireNonNull(doc);\r\n Objects.requireNonNull(ootext);\r\n Objects.requireNonNull(position);\r\n String lText = OOText.toString(ootext);\r\n LOGGER.debug(lText);\r\n XText text = position.getText();\r\n XTextCursor cursor = text.createTextCursorByRange(position);\r\n cursor.collapseToEnd();\r\n MyPropertyStack formatStack = new MyPropertyStack(cursor);\r\n Stack expectEnd = new Stack<>();\r\n int piv = 0;\r\n Matcher tagMatcher = HTML_TAG.matcher(lText);\r\n while (tagMatcher.find()) {\r\n String currentSubstring = lText.substring(piv, tagMatcher.start());\r\n if (!currentSubstring.isEmpty()) {\r\n cursor.setString(currentSubstring);\r\n }\r\n formatStack.apply(cursor);\r\n cursor.collapseToEnd();\r\n String endTagName = tagMatcher.group(1);\r\n String startTagName = tagMatcher.group(2);\r\n String attributeListPart = tagMatcher.group(3);\r\n boolean isStartTag = StringUtil.isNullOrEmpty(endTagName);\r\n String tagName = isStartTag ? startTagName : endTagName;\r\n Objects.requireNonNull(tagName);\r\n List> attributes = parseAttributes(attributeListPart);\r\n switch(tagName) {\r\n case \"b\":\r\n formatStack.pushLayer(setCharWeight(FontWeight.BOLD));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"i\":\r\n case \"em\":\r\n formatStack.pushLayer(setCharPosture(FontSlant.ITALIC));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"smallcaps\":\r\n formatStack.pushLayer(setCharCaseMap(CaseMap.SMALLCAPS));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"sup\":\r\n formatStack.pushLayer(setSuperScript(formatStack));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"sub\":\r\n formatStack.pushLayer(setSubScript(formatStack));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"u\":\r\n formatStack.pushLayer(setCharUnderline(FontUnderline.SINGLE));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"s\":\r\n formatStack.pushLayer(setCharStrikeout(FontStrikeout.SINGLE));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"/p\":\r\n break;\r\n case \"p\":\r\n insertParagraphBreak(text, cursor);\r\n cursor.collapseToEnd();\r\n for (OOPair pair : attributes) {\r\n String key = pair.a;\r\n String value = pair.b;\r\n switch(key) {\r\n case \"oo:ParaStyleName\":\r\n if (StringUtil.isNullOrEmpty(value)) {\r\n LOGGER.debug(\"oo:ParaStyleName inherited\");\r\n } else {\r\n if (setParagraphStyle(cursor, value)) {\r\n LOGGER.debug(String.format(\"oo:ParaStyleName=\\\"%s\\\" failed\", value));\r\n }\r\n }\r\n break;\r\n default:\r\n LOGGER.warn(String.format(\"Unexpected attribute '%s' for <%s>\", key, tagName));\r\n break;\r\n }\r\n }\r\n break;\r\n case \"oo:referenceToPageNumberOfReferenceMark\":\r\n for (OOPair pair : attributes) {\r\n String key = pair.a;\r\n String value = pair.b;\r\n switch(key) {\r\n case \"target\" ->\r\n UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor);\r\n default ->\r\n LOGGER.warn(String.format(\"Unexpected attribute '%s' for <%s>\", key, tagName));\r\n }\r\n }\r\n break;\r\n case \"tt\":\r\n formatStack.pushLayer(setCharStyleName(\"Example\"));\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"span\":\r\n List> settings = new ArrayList<>();\r\n for (OOPair pair : attributes) {\r\n String key = pair.a;\r\n String value = pair.b;\r\n switch(key) {\r\n case \"oo:CharStyleName\" ->\r\n settings.addAll(setCharStyleName(value));\r\n case \"lang\" ->\r\n settings.addAll(setCharLocale(value));\r\n case \"style\" ->\r\n {\r\n if (\"font-variant: small-caps\".equals(value)) {\r\n settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS));\r\n break;\r\n }\r\n LOGGER.warn(String.format(\"Unexpected value %s for attribute '%s' for <%s>\", value, key, tagName));\r\n }\r\n default ->\r\n LOGGER.warn(String.format(\"Unexpected attribute '%s' for <%s>\", key, tagName));\r\n }\r\n }\r\n formatStack.pushLayer(settings);\r\n expectEnd.push(\"/\" + tagName);\r\n break;\r\n case \"/b\":\r\n case \"/i\":\r\n case \"/em\":\r\n case \"/tt\":\r\n case \"/smallcaps\":\r\n case \"/sup\":\r\n case \"/sub\":\r\n case \"/u\":\r\n case \"/s\":\r\n case \"/span\":\r\n formatStack.popLayer();\r\n String expected = expectEnd.pop();\r\n if (!tagName.equals(expected)) {\r\n LOGGER.warn(String.format(\"expected '<%s>', found '<%s>' after '%s'\", expected, tagName, currentSubstring));\r\n }\r\n break;\r\n default:\r\n LOGGER.warn(String.format(\"ignoring unknown tag '<%s>'\", tagName));\r\n break;\r\n }\r\n piv = tagMatcher.end();\r\n }\r\n if (piv < lText.length()) {\r\n cursor.setString(lText.substring(piv));\r\n }\r\n formatStack.apply(cursor);\r\n cursor.collapseToEnd();\r\n if (!expectEnd.empty()) {\r\n StringBuilder rest = new StringBuilder();\r\n for (String s : expectEnd) {\r\n rest.insert(0, String.format(\"<%s>\", s));\r\n }\r\n LOGGER.warn(String.format(\"OOTextIntoOO.write: expectEnd stack is not empty at the end: %s%n\", rest));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseAdditionalFields(BibEntry be, boolean multilineUrlFieldAllowed, BufferedReader in) throws IOException{\r\n if ((this.lastLine != null) && \"\".equals(this.lastLine.trim())) {\r\n readLine(in);\r\n }\r\n while ((this.lastLine != null) && !isStartOfWorkingPaper() && (startsWithKeyword(RepecNepImporter.RECOGNIZED_FIELDS) || \"\".equals(this.lastLine))) {\r\n String keyword = \"\".equals(this.lastLine) ? \"\" : this.lastLine.substring(0, this.lastLine.indexOf(':')).trim();\r\n this.lastLine = \"\".equals(this.lastLine) ? \"\" : this.lastLine.substring(this.lastLine.indexOf(':') + 1).trim();\r\n if (\"Keywords\".equals(keyword)) {\r\n String content = readMultipleLines(in);\r\n String[] keywords = content.split(\"[,;]\");\r\n be.addKeywords(Arrays.asList(keywords), importFormatPreferences.bibEntryPreferences().getKeywordSeparator());\r\n } else if (\"JEL\".equals(keyword)) {\r\n be.setField(new UnknownField(\"jel\"), readMultipleLines(in));\r\n } else if (keyword.startsWith(\"Date\")) {\r\n String content = readMultipleLines(in);\r\n Date.parse(content).ifPresent(be::setDate);\r\n } else if (keyword.startsWith(\"URL\")) {\r\n String content;\r\n if (multilineUrlFieldAllowed) {\r\n content = readMultipleLines(in);\r\n } else {\r\n content = this.lastLine;\r\n readLine(in);\r\n }\r\n be.setField(StandardField.URL, content);\r\n } else if (keyword.startsWith(\"By\")) {\r\n parseAuthors(be, in);\r\n } else {\r\n readLine(in);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void checkSignature(Header _header, byte[] sessionbuff){\r\n KeyStoreHelper helper = KeyStoreHelper.get();\r\n boolean signed = _header.hasSignature();\r\n if (helper.isSigned() != signed) {\r\n throw new RuntimeException(\"This environment is configured to work with \" + (helper.isSigned() ? \"signed\" : \"unsigned\") + \" serialized objects, but the given object is \" + (signed ? \"signed\" : \"unsigned\") + \". Deserialization aborted.\");\r\n }\r\n if (signed) {\r\n if (helper.getPubKeyStore() == null) {\r\n throw new RuntimeException(\"The session was serialized with a signature. Please configure a public keystore with the public key to check the signature. Deserialization aborted.\");\r\n }\r\n try {\r\n if (!helper.checkDataWithPublicKey(_header.getSignature().getKeyAlias(), sessionbuff, _header.getSignature().getSignature().toByteArray())) {\r\n throw new RuntimeException(\"Signature does not match serialized package. This is a security violation. Deserialisation aborted.\");\r\n }\r\n } catch (InvalidKeyException e) {\r\n throw new RuntimeException(\"Invalid key checking signature: \" + e.getMessage(), e);\r\n } catch (KeyStoreException e) {\r\n throw new RuntimeException(\"Error accessing Key Store: \" + e.getMessage(), e);\r\n } catch (NoSuchAlgorithmException e) {\r\n throw new RuntimeException(\"No algorithm available: \" + e.getMessage(), e);\r\n } catch (SignatureException e) {\r\n throw new RuntimeException(\"Signature Exception: \" + e.getMessage(), e);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SyslogMessage parseMessage(byte[] bytes){\r\n ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);\r\n byteBuffer.put(bytes);\r\n cast(byteBuffer).rewind();\r\n Character charFound = (char) byteBuffer.get();\r\n SyslogFacility foundFacility = null;\r\n SyslogSeverity foundSeverity = null;\r\n while (charFound != '<') {\r\n charFound = (char) byteBuffer.get();\r\n }\r\n char priChar = 0;\r\n if (charFound == '<') {\r\n int facility = 0;\r\n while (Character.isDigit(priChar = (char) (byteBuffer.get() & 0xff))) {\r\n facility *= 10;\r\n facility += Character.digit(priChar, 10);\r\n }\r\n foundFacility = SyslogFacility.values()[facility >> 3];\r\n foundSeverity = SyslogSeverity.values()[facility & 0x07];\r\n }\r\n if (priChar != '>') {\r\n LOG.error(\"Invalid syslog message, missing a > in the Facility/Priority part\");\r\n }\r\n SyslogMessage syslogMessage = new SyslogMessage();\r\n boolean isRfc5424 = false;\r\n charFound = (char) byteBuffer.get();\r\n if (charFound == '1') {\r\n syslogMessage = new Rfc5424SyslogMessage();\r\n isRfc5424 = true;\r\n } else {\r\n byteBuffer.position(byteBuffer.position() - 1);\r\n }\r\n syslogMessage.setFacility(foundFacility);\r\n syslogMessage.setSeverity(foundSeverity);\r\n if (!isRfc5424) {\r\n syslogMessage.setTimestamp(parseRfc3164Date(byteBuffer));\r\n } else {\r\n charFound = (char) byteBuffer.get();\r\n if (charFound != ' ') {\r\n LOG.error(\"Invalid syslog message, missing a mandatory space after version\");\r\n }\r\n StringBuilder date = new StringBuilder();\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {\r\n date.append(charFound);\r\n }\r\n syslogMessage.setTimestamp(DatatypeConverter.parseDateTime(date.toString()));\r\n }\r\n StringBuilder host = new StringBuilder();\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {\r\n host.append(charFound);\r\n }\r\n syslogMessage.setHostname(host.toString());\r\n if (isRfc5424) {\r\n Rfc5424SyslogMessage rfc5424SyslogMessage = (Rfc5424SyslogMessage) syslogMessage;\r\n StringBuilder appName = new StringBuilder();\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {\r\n appName.append(charFound);\r\n }\r\n rfc5424SyslogMessage.setAppName(appName.toString());\r\n StringBuilder procId = new StringBuilder();\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {\r\n procId.append(charFound);\r\n }\r\n rfc5424SyslogMessage.setProcId(procId.toString());\r\n StringBuilder msgId = new StringBuilder();\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {\r\n msgId.append(charFound);\r\n }\r\n rfc5424SyslogMessage.setMsgId(msgId.toString());\r\n StringBuilder structuredData = new StringBuilder();\r\n boolean inblock = false;\r\n while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ' || inblock) {\r\n if (charFound == '[') {\r\n inblock = true;\r\n }\r\n if (charFound == ']') {\r\n inblock = false;\r\n }\r\n structuredData.append(charFound);\r\n }\r\n rfc5424SyslogMessage.setStructuredData(structuredData.toString());\r\n }\r\n StringBuilder msg = new StringBuilder();\r\n while (byteBuffer.hasRemaining()) {\r\n charFound = (char) (byteBuffer.get() & 0xff);\r\n msg.append(charFound);\r\n }\r\n syslogMessage.setLogMessage(msg.toString());\r\n LOG.trace(\"Syslog message : {}\", syslogMessage);\r\n return syslogMessage;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BaseDescr lhsUnary(final CEDescrBuilder ce, boolean allowOr) throws RecognitionException{\r\n BaseDescr result = null;\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.EXISTS)) {\r\n result = lhsExists(ce, allowOr);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.DO)) {\r\n namedConsequence(ce, null);\r\n }\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.NOT)) {\r\n result = lhsNot(ce, allowOr);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.DO)) {\r\n namedConsequence(ce, null);\r\n }\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.EVAL)) {\r\n result = lhsEval(ce);\r\n for (BaseDescr i = consequenceInvocation(ce); i != null; i = consequenceInvocation(ce)) ;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.FORALL)) {\r\n result = lhsForall(ce);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.ACCUMULATE) || helper.validateIdentifierKey(DroolsSoftKeywords.ACC)) {\r\n result = lhsAccumulate(ce);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.GROUPBY)) {\r\n result = lhsGroupBy(ce);\r\n } else if (input.LA(1) == DRL6Lexer.LEFT_PAREN) {\r\n result = lhsParen(ce, allowOr);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.DO)) {\r\n namedConsequence(ce, null);\r\n }\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.IF)) {\r\n result = conditionalBranch(ce, null);\r\n } else if (input.LA(1) == DRL6Lexer.ID || input.LA(1) == DRL6Lexer.QUESTION || input.LA(1) == DRL6Lexer.DIV) {\r\n result = lhsPatternBind(ce, allowOr);\r\n for (BaseDescr i = consequenceInvocation(ce); i != null; i = consequenceInvocation(ce)) ;\r\n } else {\r\n failMismatchedTokenException();\r\n }\r\n if (input.LA(1) == DRL6Lexer.SEMICOLON) {\r\n match(input, DRL6Lexer.SEMICOLON, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder mergeFrom(ServerState.StoredServerPaymentChannels other){\r\n if (other == ServerState.StoredServerPaymentChannels.getDefaultInstance())\r\n return this;\r\n if (channelsBuilder_ == null) {\r\n if (!other.channels_.isEmpty()) {\r\n if (channels_.isEmpty()) {\r\n channels_ = other.channels_;\r\n bitField0_ = (bitField0_ & ~0x00000001);\r\n } else {\r\n ensureChannelsIsMutable();\r\n channels_.addAll(other.channels_);\r\n }\r\n onChanged();\r\n }\r\n } else {\r\n if (!other.channels_.isEmpty()) {\r\n if (channelsBuilder_.isEmpty()) {\r\n channelsBuilder_.dispose();\r\n channelsBuilder_ = null;\r\n channels_ = other.channels_;\r\n bitField0_ = (bitField0_ & ~0x00000001);\r\n channelsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getChannelsFieldBuilder() : null;\r\n } else {\r\n channelsBuilder_.addAllMessages(other.channels_);\r\n }\r\n }\r\n }\r\n this.mergeUnknownFields(other.getUnknownFields());\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized void run() throws Exception{\r\n long start = System.currentTimeMillis();\r\n long testEnd = start + (duration * 1000);\r\n long testDrainEnd = testEnd + (drainTimeout * 1000);\r\n while (System.currentTimeMillis() < testEnd) {\r\n while (startRead() || startWrite()) {\r\n }\r\n long toWait = testEnd - System.currentTimeMillis();\r\n this.wait(toWait < 0 ? 0 : toWait);\r\n printThrowExceptions();\r\n }\r\n while ((System.currentTimeMillis() < testDrainEnd) && (outstandingReadCount > 0 || outstandingWriteCount > 0)) {\r\n System.out.format(\"reads: %d, writes: %d%n\", outstandingReadCount, outstandingWriteCount);\r\n System.out.format(\"openingLedgers:%n\");\r\n for (LedgerInfo li : openingLedgers) {\r\n System.out.format(\"Ledger %d has reads: %d, writes: %d%n\", li.ledgerID, li.readsInProgress, li.writesInProgress.size());\r\n }\r\n System.out.format(\"openLedgers:%n\");\r\n for (LedgerInfo li : openLedgers) {\r\n System.out.format(\"Ledger %d has reads: %d, writes: %d%n\", li.ledgerID, li.readsInProgress, li.writesInProgress.size());\r\n }\r\n System.out.format(\"liveLedgers:%n\");\r\n for (LedgerInfo li : liveLedgers) {\r\n System.out.format(\"Ledger %d has reads: %d, writes: %d%n\", li.ledgerID, li.readsInProgress, li.writesInProgress.size());\r\n }\r\n long toWait = testDrainEnd - System.currentTimeMillis();\r\n this.wait(toWait < 0 ? 0 : toWait);\r\n printThrowExceptions();\r\n }\r\n if (outstandingReadCount > 0 || outstandingWriteCount > 0) {\r\n throw new Exception(\"Failed to drain ops before timeout%n\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ArrayList getProteinCDSSequences(){\r\n ArrayList proteinSequenceList = new ArrayList();\r\n for (int i = 0; i < cdsSequenceList.size(); i++) {\r\n CDSSequence cdsSequence = cdsSequenceList.get(i);\r\n String codingSequence = cdsSequence.getCodingSequence();\r\n if (this.getStrand() == Strand.NEGATIVE) {\r\n if (cdsSequence.phase == 1) {\r\n codingSequence = codingSequence.substring(1, codingSequence.length());\r\n } else if (cdsSequence.phase == 2) {\r\n codingSequence = codingSequence.substring(2, codingSequence.length());\r\n }\r\n if (i < cdsSequenceList.size() - 1) {\r\n CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);\r\n if (nextCDSSequence.phase == 1) {\r\n String nextCodingSequence = nextCDSSequence.getCodingSequence();\r\n codingSequence = codingSequence + nextCodingSequence.substring(0, 1);\r\n } else if (nextCDSSequence.phase == 2) {\r\n String nextCodingSequence = nextCDSSequence.getCodingSequence();\r\n codingSequence = codingSequence + nextCodingSequence.substring(0, 2);\r\n }\r\n }\r\n } else {\r\n if (cdsSequence.phase == 1) {\r\n codingSequence = codingSequence.substring(1, codingSequence.length());\r\n } else if (cdsSequence.phase == 2) {\r\n codingSequence = codingSequence.substring(2, codingSequence.length());\r\n }\r\n if (i < cdsSequenceList.size() - 1) {\r\n CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1);\r\n if (nextCDSSequence.phase == 1) {\r\n String nextCodingSequence = nextCDSSequence.getCodingSequence();\r\n codingSequence = codingSequence + nextCodingSequence.substring(0, 1);\r\n } else if (nextCDSSequence.phase == 2) {\r\n String nextCodingSequence = nextCDSSequence.getCodingSequence();\r\n codingSequence = codingSequence + nextCodingSequence.substring(0, 2);\r\n }\r\n }\r\n }\r\n DNASequence dnaCodingSequence = null;\r\n try {\r\n dnaCodingSequence = new DNASequence(codingSequence.toUpperCase());\r\n } catch (CompoundNotFoundException e) {\r\n logger.error(\"Could not create DNA coding sequence, {}. This is most likely a bug.\", e.getMessage());\r\n }\r\n RNASequence rnaCodingSequence = dnaCodingSequence.getRNASequence(TranscriptionEngine.getDefault());\r\n ProteinSequence proteinSequence = rnaCodingSequence.getProteinSequence(TranscriptionEngine.getDefault());\r\n proteinSequence.setAccession(new AccessionID(cdsSequence.getAccession().getID()));\r\n proteinSequence.setParentDNASequence(cdsSequence, 1, cdsSequence.getLength());\r\n proteinSequenceList.add(proteinSequence);\r\n }\r\n return proteinSequenceList;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static InsertTabletStatement constructInsertTabletStatement(InsertTabletRequest insertTabletRequest) throws IllegalPathException, WriteProcessRejectException{\r\n InsertTabletStatement insertStatement = new InsertTabletStatement();\r\n insertStatement.setDevicePath(DataNodeDevicePathCache.getInstance().getPartialPath(insertTabletRequest.getDeviceId()));\r\n insertStatement.setMeasurements(insertTabletRequest.getMeasurements().toArray(new String[0]));\r\n List> rawData = insertTabletRequest.getValues();\r\n List rawDataType = insertTabletRequest.getDataTypes();\r\n int rowSize = insertTabletRequest.getTimestamps().size();\r\n int columnSize = rawDataType.size();\r\n Object[] columns = new Object[columnSize];\r\n BitMap[] bitMaps = new BitMap[columnSize];\r\n TSDataType[] dataTypes = new TSDataType[columnSize];\r\n for (int i = 0; i < columnSize; i++) {\r\n dataTypes[i] = TSDataType.valueOf(rawDataType.get(i).toUpperCase(Locale.ROOT));\r\n }\r\n for (int columnIndex = 0; columnIndex < columnSize; columnIndex++) {\r\n bitMaps[columnIndex] = new BitMap(rowSize);\r\n switch(dataTypes[columnIndex]) {\r\n case BOOLEAN:\r\n boolean[] booleanValues = new boolean[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n Object data = rawData.get(columnIndex).get(rowIndex);\r\n if (data == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n } else {\r\n if (\"1\".equals(data.toString())) {\r\n booleanValues[rowIndex] = true;\r\n } else if (\"0\".equals(data.toString())) {\r\n booleanValues[rowIndex] = false;\r\n } else {\r\n booleanValues[rowIndex] = (Boolean) data;\r\n }\r\n }\r\n }\r\n columns[columnIndex] = booleanValues;\r\n break;\r\n case INT32:\r\n int[] intValues = new int[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n Object object = rawData.get(columnIndex).get(rowIndex);\r\n if (object == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n } else if (object instanceof Integer) {\r\n intValues[rowIndex] = (int) object;\r\n } else {\r\n throw new WriteProcessRejectException(\"unsupported data type: \" + object.getClass().toString());\r\n }\r\n }\r\n columns[columnIndex] = intValues;\r\n break;\r\n case INT64:\r\n long[] longValues = new long[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n Object object = rawData.get(columnIndex).get(rowIndex);\r\n if (object == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n } else if (object instanceof Integer) {\r\n longValues[rowIndex] = (int) object;\r\n } else if (object instanceof Long) {\r\n longValues[rowIndex] = (long) object;\r\n } else {\r\n throw new WriteProcessRejectException(\"unsupported data type: \" + object.getClass().toString());\r\n }\r\n }\r\n columns[columnIndex] = longValues;\r\n break;\r\n case FLOAT:\r\n float[] floatValues = new float[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n Object data = rawData.get(columnIndex).get(rowIndex);\r\n if (data == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n } else {\r\n floatValues[rowIndex] = Float.valueOf(String.valueOf(data));\r\n }\r\n }\r\n columns[columnIndex] = floatValues;\r\n break;\r\n case DOUBLE:\r\n double[] doubleValues = new double[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n if (rawData.get(columnIndex).get(rowIndex) == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n } else {\r\n doubleValues[rowIndex] = Double.valueOf(String.valueOf(rawData.get(columnIndex).get(rowIndex)));\r\n }\r\n }\r\n columns[columnIndex] = doubleValues;\r\n break;\r\n case TEXT:\r\n Binary[] binaryValues = new Binary[rowSize];\r\n for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {\r\n if (rawData.get(columnIndex).get(rowIndex) == null) {\r\n bitMaps[columnIndex].mark(rowIndex);\r\n binaryValues[rowIndex] = new Binary(\"\".getBytes(StandardCharsets.UTF_8));\r\n } else {\r\n binaryValues[rowIndex] = new Binary(rawData.get(columnIndex).get(rowIndex).toString().getBytes(StandardCharsets.UTF_8));\r\n }\r\n }\r\n columns[columnIndex] = binaryValues;\r\n break;\r\n default:\r\n throw new IllegalArgumentException(\"Invalid input: \" + rawDataType.get(columnIndex));\r\n }\r\n }\r\n insertStatement.setTimes(insertTabletRequest.getTimestamps().stream().mapToLong(Long::longValue).toArray());\r\n insertStatement.setColumns(columns);\r\n insertStatement.setBitMaps(bitMaps);\r\n insertStatement.setRowCount(insertTabletRequest.getTimestamps().size());\r\n insertStatement.setDataTypes(dataTypes);\r\n insertStatement.setAligned(insertTabletRequest.getIsAligned());\r\n return insertStatement;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String[] addXsdModel(Resource resource, KnowledgeBuilderImpl kBuilder, Options xjcOpts, String systemId) throws IOException{\r\n InputSource source = new InputSource(new CachingRewindableReader(resource.getReader()));\r\n source.setSystemId(systemId.trim().startsWith(\".\") ? systemId : \".\" + systemId);\r\n xjcOpts.addGrammar(source);\r\n try {\r\n xjcOpts.parseArguments(new String[] { \"-npa\" });\r\n } catch (BadCommandLineException e) {\r\n throw new IllegalArgumentException(\"Unable to parse arguments\", e);\r\n }\r\n ErrorReceiver errorReceiver = new JaxbErrorReceiver4Drools();\r\n Model model = ModelLoader.load(xjcOpts, new JCodeModel(), errorReceiver);\r\n model.generateCode(xjcOpts, errorReceiver);\r\n MapVfsCodeWriter codeWriter = new MapVfsCodeWriter();\r\n model.codeModel.build(xjcOpts.createCodeWriter(codeWriter));\r\n MemoryResourceReader src = new MemoryResourceReader();\r\n boolean useProjectClassLoader = kBuilder.getRootClassLoader() instanceof ProjectClassLoader;\r\n List classNames = new ArrayList<>();\r\n List srcNames = new ArrayList<>();\r\n for (Entry entry : codeWriter.getMap().entrySet()) {\r\n String name = entry.getKey();\r\n int dotPos = name.lastIndexOf('.');\r\n String pkgName = name.substring(0, dotPos);\r\n if (!name.endsWith(\"package-info.java\")) {\r\n classNames.add(pkgName);\r\n }\r\n dotPos = pkgName.lastIndexOf('.');\r\n if (dotPos != -1) {\r\n pkgName = pkgName.substring(0, dotPos);\r\n }\r\n PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);\r\n if (pkgReg == null) {\r\n kBuilder.addPackage(new PackageDescr(pkgName));\r\n pkgReg = kBuilder.getPackageRegistry(pkgName);\r\n }\r\n if (useProjectClassLoader) {\r\n String srcName = convertToResource(entry.getKey());\r\n src.add(srcName, entry.getValue());\r\n srcNames.add(srcName);\r\n } else {\r\n Dialect dialect = pkgReg.getDialectCompiletimeRegistry().getDialect(\"java\");\r\n dialect.addSrc(convertToResource(entry.getKey()), entry.getValue());\r\n }\r\n }\r\n if (useProjectClassLoader) {\r\n ProjectJavaCompiler compiler = new ProjectJavaCompiler(kBuilder.getBuilderConfiguration());\r\n List results = compiler.compileAll((ProjectClassLoader) kBuilder.getRootClassLoader(), srcNames, src);\r\n for (String className : classNames) {\r\n Class clazz;\r\n try {\r\n clazz = Class.forName(className, true, kBuilder.getRootClassLoader());\r\n } catch (ClassNotFoundException e) {\r\n continue;\r\n }\r\n String pkgName = className.substring(0, className.lastIndexOf('.'));\r\n PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);\r\n pkgReg.getPackage().addTypeDeclaration(TypeDeclaration.createTypeDeclarationForBean(clazz));\r\n }\r\n kBuilder.updateResults(results);\r\n } else {\r\n kBuilder.compileAll();\r\n kBuilder.updateResults();\r\n }\r\n return classNames.toArray(new String[classNames.size()]);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Void performDataRead() throws IOException, InterruptedException{\r\n long startTime = counters.startTimeCounter();\r\n LlapIoImpl.LOG.info(\"Processing data for file {}: {}\", fileKey, split.getPath());\r\n if (processStop()) {\r\n recordReaderTime(startTime);\r\n return null;\r\n }\r\n counters.setDesc(QueryFragmentCounters.Desc.TABLE, cacheTag.getTableName());\r\n counters.setDesc(QueryFragmentCounters.Desc.FILE, split.getPath() + (fileKey == null ? \"\" : \" (\" + fileKey + \")\"));\r\n try {\r\n validateFileMetadata();\r\n determineStripesToRead();\r\n } catch (Throwable t) {\r\n handleReaderError(startTime, t);\r\n return null;\r\n }\r\n if (stripeRgs.length == 0) {\r\n consumer.setDone();\r\n recordReaderTime(startTime);\r\n tracePool.offer(trace);\r\n return null;\r\n }\r\n counters.setDesc(QueryFragmentCounters.Desc.STRIPES, stripeIxFrom + \",\" + stripeRgs.length);\r\n int stride = fileMetadata.getRowIndexStride();\r\n ArrayList stripeMetadatas = null;\r\n try {\r\n if (sarg != null && stride != 0) {\r\n int[] filterColumns = RecordReaderImpl.mapSargColumnsToOrcInternalColIdx(sarg.getLeaves(), evolution);\r\n sargColumns = new boolean[evolution.getFileSchema().getMaximumId() + 1];\r\n for (int i : filterColumns) {\r\n if (i > 0) {\r\n sargColumns[i] = true;\r\n }\r\n }\r\n stripeMetadatas = readStripesMetadata(fileIncludes, sargColumns);\r\n }\r\n boolean hasData = determineRgsToRead(stride, stripeMetadatas);\r\n if (!hasData) {\r\n consumer.setDone();\r\n recordReaderTime(startTime);\r\n tracePool.offer(trace);\r\n return null;\r\n }\r\n } catch (Throwable t) {\r\n handleReaderError(startTime, t);\r\n return null;\r\n }\r\n if (processStop()) {\r\n recordReaderTime(startTime);\r\n return null;\r\n }\r\n try {\r\n ensureDataReader();\r\n } catch (Throwable t) {\r\n handleReaderError(startTime, t);\r\n return null;\r\n }\r\n boolean hasFileId = this.fileKey != null;\r\n OrcBatchKey stripeKey = hasFileId ? new OrcBatchKey(fileKey, -1, 0) : null;\r\n pathCache.touch(fileKey, split.getPath().toUri().toString());\r\n for (int stripeIxMod = 0; stripeIxMod < stripeRgs.length; ++stripeIxMod) {\r\n if (processStop()) {\r\n recordReaderTime(startTime);\r\n return null;\r\n }\r\n int stripeIx = stripeIxFrom + stripeIxMod;\r\n boolean[] rgs = null;\r\n OrcStripeMetadata stripeMetadata = null;\r\n StripeInformation si;\r\n try {\r\n si = fileMetadata.getStripes().get(stripeIx);\r\n LlapIoImpl.ORC_LOGGER.trace(\"Reading stripe {}: {}, {}\", stripeIx, si.getOffset(), si.getLength());\r\n trace.logReadingStripe(stripeIx, si.getOffset(), si.getLength());\r\n rgs = stripeRgs[stripeIxMod];\r\n if (LlapIoImpl.ORC_LOGGER.isTraceEnabled()) {\r\n LlapIoImpl.ORC_LOGGER.trace(\"stripeRgs[{}]: {}\", stripeIxMod, Arrays.toString(rgs));\r\n }\r\n if (rgs == RecordReaderImpl.SargApplier.READ_NO_RGS)\r\n continue;\r\n if (stripeMetadatas != null) {\r\n stripeMetadata = stripeMetadatas.get(stripeIxMod);\r\n } else {\r\n stripeKey.stripeIx = stripeIx;\r\n OrcProto.StripeFooter footer = getStripeFooterFromCacheOrDisk(si, stripeKey);\r\n stripeMetadata = createOrcStripeMetadataObject(stripeIx, si, footer, fileIncludes, sargColumns);\r\n ensureDataReader();\r\n stripeReader.readIndexStreams(stripeMetadata.getIndex(), si, footer.getStreamsList(), fileIncludes, sargColumns);\r\n consumer.setStripeMetadata(stripeMetadata);\r\n }\r\n } catch (Throwable t) {\r\n handleReaderError(startTime, t);\r\n return null;\r\n }\r\n if (processStop()) {\r\n recordReaderTime(startTime);\r\n return null;\r\n }\r\n try {\r\n stripeReader.readEncodedColumns(stripeIx, si, stripeMetadata.getRowIndexes(), stripeMetadata.getEncodings(), stripeMetadata.getStreams(), fileIncludes, rgs, consumer);\r\n } catch (Throwable t) {\r\n handleReaderError(startTime, t);\r\n return null;\r\n }\r\n }\r\n recordReaderTime(startTime);\r\n consumer.setDone();\r\n LlapIoImpl.LOG.trace(\"done processing {}\", split);\r\n tracePool.offer(trace);\r\n cleanupReaders();\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private QueryExpression andOr(RexCall call){\r\n QueryExpression[] expressions = new QueryExpression[call.getOperands().size()];\r\n PredicateAnalyzerException firstError = null;\r\n boolean partial = false;\r\n for (int i = 0; i < call.getOperands().size(); i++) {\r\n try {\r\n Expression expr = call.getOperands().get(i).accept(this);\r\n if (expr instanceof NamedFieldExpression) {\r\n } else {\r\n expressions[i] = (QueryExpression) call.getOperands().get(i).accept(this);\r\n }\r\n partial |= expressions[i].isPartial();\r\n } catch (PredicateAnalyzerException e) {\r\n if (firstError == null) {\r\n firstError = e;\r\n }\r\n partial = true;\r\n }\r\n }\r\n switch(call.getKind()) {\r\n case OR:\r\n if (partial) {\r\n if (firstError != null) {\r\n throw firstError;\r\n } else {\r\n final String message = String.format(Locale.ROOT, \"Unable to handle call: [%s]\", call);\r\n throw new PredicateAnalyzerException(message);\r\n }\r\n }\r\n return CompoundQueryExpression.or(expressions);\r\n case AND:\r\n return CompoundQueryExpression.and(partial, expressions);\r\n default:\r\n String message = String.format(Locale.ROOT, \"Unable to handle call: [%s]\", call);\r\n throw new PredicateAnalyzerException(message);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String _insdc_feature_location_string(FeatureInterface, C> feature, int record_length){\r\n if (feature.getChildrenFeatures().isEmpty()) {\r\n if (feature.getLocations().getSubLocations().isEmpty()) {\r\n String location = _insdc_location_string_ignoring_strand_and_subfeatures(feature.getLocations(), record_length);\r\n if (feature.getLocations().getStrand() == Strand.NEGATIVE) {\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n formatter.format(\"complement(%s)\", location);\r\n String output = formatter.toString();\r\n formatter.close();\r\n location = output;\r\n }\r\n return location;\r\n } else if (feature.getLocations().getStrand() == Strand.NEGATIVE) {\r\n for (Location l : feature.getLocations().getSubLocations()) {\r\n if (l.getStrand() != Strand.NEGATIVE) {\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n formatter.format(\"Inconsistent strands: %s for parent, %s for child\", feature.getLocations().getStrand(), l.getStrand());\r\n String output = formatter.toString();\r\n formatter.close();\r\n throw new RuntimeException(output);\r\n }\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n ArrayList locations = new ArrayList();\r\n for (Location l : feature.getLocations().getSubLocations()) {\r\n locations.add(_insdc_location_string_ignoring_strand_and_subfeatures((AbstractLocation) l, record_length));\r\n }\r\n String location = StringManipulationHelper.join(locations, \",\");\r\n formatter.format(\"complement(%s(%s))\", \"join\", location);\r\n String output = formatter.toString();\r\n formatter.close();\r\n return output;\r\n } else {\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n ArrayList locations = new ArrayList();\r\n for (Location l : feature.getLocations().getSubLocations()) {\r\n locations.add(_insdc_location_string_ignoring_strand_and_subfeatures((AbstractLocation) l, record_length));\r\n }\r\n String location = StringManipulationHelper.join(locations, \",\");\r\n formatter.format(\"%s(%s)\", \"join\", location);\r\n String output = formatter.toString();\r\n formatter.close();\r\n return output;\r\n }\r\n }\r\n if (feature.getLocations().getStrand() == Strand.NEGATIVE) {\r\n for (FeatureInterface f : feature.getChildrenFeatures()) {\r\n if (f.getLocations().getStrand() != Strand.NEGATIVE) {\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n formatter.format(\"Inconsistent strands: %s for parent, %s for child\", feature.getLocations().getStrand(), f.getLocations().getStrand());\r\n String output = formatter.toString();\r\n formatter.close();\r\n throw new RuntimeException(output);\r\n }\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n ArrayList locations = new ArrayList();\r\n for (FeatureInterface, C> f : feature.getChildrenFeatures()) {\r\n locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length));\r\n }\r\n String location = StringManipulationHelper.join(locations, \",\");\r\n formatter.format(\"complement(%s(%s))\", \"join\", location);\r\n String output = formatter.toString();\r\n formatter.close();\r\n return output;\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n Formatter formatter = new Formatter(sb, Locale.US);\r\n ArrayList locations = new ArrayList();\r\n for (FeatureInterface, C> f : feature.getChildrenFeatures()) {\r\n locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length));\r\n }\r\n String location = StringManipulationHelper.join(locations, \",\");\r\n formatter.format(\"%s(%s)\", \"join\", location);\r\n String output = formatter.toString();\r\n formatter.close();\r\n return output;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List computeAlertForRule(String domain, String type, String name, String monitor, List configs){\r\n List results = new ArrayList();\r\n Pair> conditionPair = m_ruleConfigManager.convertConditions(configs);\r\n int minute = calAlreadyMinute();\r\n Map pars = new HashMap();\r\n pars.put(\"type\", type);\r\n pars.put(\"name\", name);\r\n if (conditionPair != null) {\r\n int maxMinute = conditionPair.getKey();\r\n List conditions = conditionPair.getValue();\r\n if (StringUtils.isEmpty(name)) {\r\n name = Constants.ALL;\r\n }\r\n if (minute >= maxMinute - 1) {\r\n int start = minute + 1 - maxMinute;\r\n int end = minute;\r\n pars.put(\"min\", String.valueOf(start));\r\n pars.put(\"max\", String.valueOf(end));\r\n TransactionReport report = fetchTransactionReport(domain, ModelPeriod.CURRENT, pars);\r\n if (report != null) {\r\n double[] data = buildArrayData(start, end, type, name, monitor, report);\r\n results.addAll(m_dataChecker.checkData(data, conditions, report.getIps()));\r\n }\r\n } else if (minute < 0) {\r\n int start = 60 + minute + 1 - (maxMinute);\r\n int end = 60 + minute;\r\n pars.put(\"min\", String.valueOf(start));\r\n pars.put(\"max\", String.valueOf(end));\r\n TransactionReport report = fetchTransactionReport(domain, ModelPeriod.LAST, pars);\r\n if (report != null) {\r\n double[] data = buildArrayData(start, end, type, name, monitor, report);\r\n results.addAll(m_dataChecker.checkData(data, conditions, report.getIps()));\r\n }\r\n } else {\r\n int currentStart = 0;\r\n int lastStart = 60 + 1 - (maxMinute - minute);\r\n int lastEnd = 59;\r\n pars.put(\"min\", String.valueOf(currentStart));\r\n pars.put(\"max\", String.valueOf(minute));\r\n TransactionReport currentReport = fetchTransactionReport(domain, ModelPeriod.CURRENT, pars);\r\n pars.put(\"min\", String.valueOf(lastStart));\r\n pars.put(\"max\", String.valueOf(lastEnd));\r\n TransactionReport lastReport = fetchTransactionReport(domain, ModelPeriod.LAST, pars);\r\n if (currentReport != null && lastReport != null) {\r\n double[] currentValue = buildArrayData(currentStart, minute, type, name, monitor, currentReport);\r\n double[] lastValue = buildArrayData(lastStart, lastEnd, type, name, monitor, lastReport);\r\n double[] data = mergerArray(lastValue, currentValue);\r\n results.addAll(m_dataChecker.checkData(data, conditions, lastReport.getIps()));\r\n }\r\n }\r\n }\r\n return results;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static MavenClassLoader createClassLoader(File[] jars){\r\n final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();\r\n URLClassLoader cl = new URLClassLoader(Arrays.stream(jars).map((f) -> {\r\n try {\r\n return f.toURI().toURL();\r\n } catch (Throwable t) {\r\n throw new RuntimeException(t);\r\n }\r\n }).toArray(URL[]::new), systemClassLoader) {\r\n\r\n @Override\r\n protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {\r\n Class loadedClass = findLoadedClass(name);\r\n if (loadedClass == null) {\r\n try {\r\n loadedClass = findClass(name);\r\n } catch (ClassNotFoundException ignored) {\r\n }\r\n if (loadedClass == null) {\r\n try {\r\n loadedClass = systemClassLoader.loadClass(name);\r\n } catch (ClassNotFoundException e) {\r\n }\r\n }\r\n }\r\n if (resolve && loadedClass != null) {\r\n resolveClass(loadedClass);\r\n }\r\n return loadedClass;\r\n }\r\n };\r\n return new MavenClassLoader(cl);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ImportDescr importStatement(PackageDescrBuilder pkg) throws RecognitionException{\r\n try {\r\n String kwd;\r\n if (helper.validateLT(2, kwd = DroolsSoftKeywords.ACC) || helper.validateLT(2, kwd = DroolsSoftKeywords.ACCUMULATE)) {\r\n AccumulateImportDescrBuilder imp = helper.start(pkg, AccumulateImportDescrBuilder.class, null);\r\n try {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.IMPORT, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n match(input, DRL6Lexer.ID, kwd, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n String target = qualifiedIdentifier();\r\n if (state.failed)\r\n return null;\r\n Token id = match(input, DRL6Lexer.ID, null, null, DroolsEditorType.IDENTIFIER);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n imp.target(target).functionName(id.getText());\r\n }\r\n return (imp != null) ? imp.getDescr() : null;\r\n } finally {\r\n helper.end(AccumulateImportDescrBuilder.class, imp);\r\n }\r\n } else {\r\n ImportDescrBuilder imp = helper.start(pkg, ImportDescrBuilder.class, null);\r\n try {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.IMPORT, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n if (helper.validateIdentifierKey(kwd = DroolsSoftKeywords.FUNCTION) || helper.validateIdentifierKey(kwd = DroolsSoftKeywords.STATIC)) {\r\n match(input, DRL6Lexer.ID, kwd, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n }\r\n String target = qualifiedIdentifier();\r\n if (state.failed)\r\n return null;\r\n if (input.LA(1) == DRL6Lexer.DOT && input.LA(2) == DRL6Lexer.STAR) {\r\n match(input, DRL6Lexer.DOT, null, null, DroolsEditorType.IDENTIFIER);\r\n if (state.failed)\r\n return null;\r\n match(input, DRL6Lexer.STAR, null, null, DroolsEditorType.IDENTIFIER);\r\n if (state.failed)\r\n return null;\r\n target += \".*\";\r\n }\r\n if (state.backtracking == 0)\r\n imp.target(target);\r\n return (imp != null) ? imp.getDescr() : null;\r\n } finally {\r\n helper.end(ImportDescrBuilder.class, imp);\r\n }\r\n }\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static TSStatus confirmNodeRestart(NodeType nodeType, String clusterName, int nodeId, Object nodeLocation, ConfigManager configManager){\r\n final String CONF_FILE_NAME = NodeType.ConfigNode.equals(nodeType) ? ConfigNodeConstant.CONF_FILE_NAME : IoTDBConstant.DATA_NODE_CONF_FILE_NAME;\r\n TSStatus status = new TSStatus();\r\n if (!CLUSTER_NAME.equals(clusterName)) {\r\n status.setCode(TSStatusCode.REJECT_NODE_START.getStatusCode());\r\n status.setMessage(String.format(\"Reject %s restart. Because the ClusterName of the current %s and the target cluster are inconsistent. \" + \"ClusterName of the current Node: %s, ClusterName of the target cluster: %s.\" + POSSIBLE_SOLUTIONS + \"\\t1. Change the target_config_node_list parameter in %s to join the correct cluster.\" + \"\\n\\t2. Change the cluster_name parameter in %s to match the target cluster\", nodeType.getNodeType(), nodeType.getNodeType(), clusterName, CLUSTER_NAME, CONF_FILE_NAME, CONF_FILE_NAME));\r\n return status;\r\n }\r\n if (nodeId < 0) {\r\n status.setCode(TSStatusCode.REJECT_NODE_START.getStatusCode());\r\n status.setMessage(String.format(\"Reject %s restart. Because the nodeId of the current %s is %d.\" + POSSIBLE_SOLUTIONS + \"\\t1. Delete \\\"data\\\" dir and retry.\", nodeType.getNodeType(), nodeType.getNodeType(), nodeId));\r\n return status;\r\n }\r\n Object matchedNodeLocation = null;\r\n switch(nodeType) {\r\n case ConfigNode:\r\n if (nodeLocation instanceof TConfigNodeLocation) {\r\n matchedNodeLocation = matchRegisteredConfigNode((TConfigNodeLocation) nodeLocation, configManager.getNodeManager().getRegisteredConfigNodes());\r\n }\r\n break;\r\n case DataNode:\r\n default:\r\n if (nodeLocation instanceof TDataNodeLocation) {\r\n matchedNodeLocation = matchRegisteredDataNode((TDataNodeLocation) nodeLocation, configManager.getNodeManager().getRegisteredDataNodes());\r\n }\r\n break;\r\n }\r\n if (matchedNodeLocation == null) {\r\n status.setCode(TSStatusCode.REJECT_NODE_START.getStatusCode());\r\n status.setMessage(String.format(\"Reject %s restart. Because there are no corresponding %s(whose nodeId=%d) in the cluster.\" + POSSIBLE_SOLUTIONS + \"\\t1. Maybe you've already removed the current %s(whose nodeId=%d). Please delete the useless 'data' dir and retry start.\", nodeType.getNodeType(), nodeType.getNodeType(), nodeId, nodeType.getNodeType(), nodeId));\r\n return status;\r\n }\r\n boolean acceptRestart = true;\r\n Set updatedTEndPoints = null;\r\n switch(nodeType) {\r\n case ConfigNode:\r\n if (nodeLocation instanceof TConfigNodeLocation) {\r\n updatedTEndPoints = checkUpdatedTEndPointOfConfigNode((TConfigNodeLocation) nodeLocation, (TConfigNodeLocation) matchedNodeLocation);\r\n if (!updatedTEndPoints.isEmpty()) {\r\n acceptRestart = false;\r\n }\r\n }\r\n break;\r\n case DataNode:\r\n default:\r\n if (nodeLocation instanceof TDataNodeLocation) {\r\n updatedTEndPoints = checkUpdatedTEndPointOfDataNode((TDataNodeLocation) nodeLocation, (TDataNodeLocation) matchedNodeLocation);\r\n if (updatedTEndPoints.stream().max(Integer::compare).orElse(-1) > 0) {\r\n acceptRestart = false;\r\n }\r\n }\r\n break;\r\n }\r\n if (!acceptRestart) {\r\n status.setCode(TSStatusCode.REJECT_NODE_START.getStatusCode());\r\n status.setMessage(String.format(\"Reject %s restart. Because the internal TEndPoints of this %s can't be modified.\" + POSSIBLE_SOLUTIONS + \"\\t1. Please keep the internal TEndPoints of this Node the same as before.\", nodeType.getNodeType(), nodeType.getNodeType()));\r\n return status;\r\n } else {\r\n return ACCEPT_NODE_RESTART;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String makeDirectJDBCUrlFromConnectionParams(JdbcConnectionParams cp){\r\n StringBuilder url = new StringBuilder(\"\");\r\n if (cp != null) {\r\n if (cp.getHost() != null) {\r\n url.append(cp.getHost());\r\n url.append(\":\");\r\n url.append(cp.getPort());\r\n url.append(\"/\");\r\n url.append(cp.getDbName());\r\n if ((cp.getSessionVars() != null) && (!cp.getSessionVars().isEmpty())) {\r\n for (Entry sessVar : cp.getSessionVars().entrySet()) {\r\n if ((sessVar.getKey().equalsIgnoreCase(JdbcConnectionParams.SERVICE_DISCOVERY_MODE)) || (sessVar.getKey().equalsIgnoreCase(JdbcConnectionParams.ZOOKEEPER_NAMESPACE))) {\r\n continue;\r\n }\r\n url.append(\";\");\r\n url.append(sessVar.getKey());\r\n url.append(\"=\");\r\n url.append(sessVar.getValue());\r\n }\r\n }\r\n if ((cp.getHiveConfs() != null) && (!cp.getHiveConfs().isEmpty())) {\r\n url.append(\"?\");\r\n boolean firstKV = true;\r\n for (Entry hiveConf : cp.getHiveConfs().entrySet()) {\r\n if (!firstKV) {\r\n url.append(\";\");\r\n } else {\r\n firstKV = false;\r\n }\r\n url.append(hiveConf.getKey());\r\n url.append(\"=\");\r\n url.append(hiveConf.getValue());\r\n }\r\n }\r\n if ((cp.getHiveVars() != null) && (!cp.getHiveVars().isEmpty())) {\r\n url.append(\"#\");\r\n boolean firstKV = true;\r\n for (Entry hiveVar : cp.getHiveVars().entrySet()) {\r\n if (!firstKV) {\r\n url.append(\";\");\r\n } else {\r\n firstKV = false;\r\n }\r\n url.append(hiveVar.getKey());\r\n url.append(\"=\");\r\n url.append(hiveVar.getValue());\r\n }\r\n }\r\n } else {\r\n return url.toString();\r\n }\r\n }\r\n return url.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Long getStatoAvanzabileByCnmTVerbale(CnmTVerbale cnmTVerbale, UserDetails userDetails){\r\n Long idStatoVerbale = cnmTVerbale.getCnmDStatoVerbale().getIdStatoVerbale();\r\n List soggetti = soggettoVerbaleService.getSoggettiByIdVerbale(cnmTVerbale.getIdVerbale(), userDetails, false);\r\n if (soggetti == null || soggetti.isEmpty())\r\n return null;\r\n List tipologiaAllegatiList = allegatoVerbaleService.getTipologiaAllegatiByCnmVerbale(cnmTVerbale);\r\n if (tipologiaAllegatiList == null || tipologiaAllegatiList.isEmpty())\r\n return null;\r\n List idAllegatoList = FluentIterable.from(tipologiaAllegatiList).transform(UtilsTipoAllegato.converTipoAllegatoToLong()).toList();\r\n Long idStato;\r\n long idProprietarioVerbale = cnmTVerbale.getCnmTUser2().getIdUser();\r\n long idUserConnesso = userDetails.getIdUser();\r\n Long idUserAssegnato = null;\r\n CnmRFunzionarioIstruttore istr = cnmRFunzionarioIstruttoreRepository.findByCnmTVerbaleAndDataAssegnazione(cnmTVerbale);\r\n if (istr != null)\r\n idUserAssegnato = istr.getCnmTUser().getIdUser();\r\n if (idStatoVerbale != Constants.STATO_VERBALE_IN_ATTESA_VERIFICA_PAGAMENTO) {\r\n if (!controllaPermessiAzione(idStatoVerbale, idProprietarioVerbale, idUserConnesso, idUserAssegnato))\r\n return null;\r\n }\r\n if (idStatoVerbale == Constants.STATO_VERBALE_INCOMPLETO || idStatoVerbale == Constants.STATO_VERBALE_IN_ATTESA_VERIFICA_PAGAMENTO) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ACQUISITO_CON_SCRITTI_DIFENSIVI, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ACQUISITO_CON_SCRITTI_DIFENSIVI);\r\n if (idStato == null) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ACQUISITO_CON_PAGAMENTO, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ACQUISITO_CON_PAGAMENTO);\r\n }\r\n if (idStato == null) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ACQUISITO, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ACQUISITO);\r\n }\r\n if (idStatoVerbale == Constants.STATO_VERBALE_IN_ATTESA_VERIFICA_PAGAMENTO && idStato != null) {\r\n BigDecimal importoPagato = cnmTAllegatoFieldRepository.getImportoPagatoByIdVerbale(cnmTVerbale.getIdVerbale());\r\n if (importoPagato == null) {\r\n importoPagato = new BigDecimal(0);\r\n }\r\n if (importoPagato.compareTo(cnmTVerbale.getImportoVerbale()) == 0) {\r\n idStato = Constants.STATO_VERBALE_ACQUISITO_CON_PAGAMENTO;\r\n } else {\r\n idStato = Constants.STATO_VERBALE_ACQUISITO;\r\n }\r\n }\r\n return idStato;\r\n } else if (idStatoVerbale == Constants.STATO_VERBALE_ACQUISITO) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ARCHIVIATO_IN_AUTOTUTELA, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ARCHIVIAZIONE);\r\n if (idStato == null) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ACQUISITO_CON_SCRITTI_DIFENSIVI, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ACQUISITO_CON_SCRITTI_DIFENSIVI);\r\n }\r\n if (idStato == null) {\r\n idStato = RegoleAllegatiCambiamentoStato.statoAvanzabile(Constants.STATO_VERBALE_ACQUISITO_CON_PAGAMENTO, idAllegatoList, RegoleAllegatiCambiamentoStato.STATO_VERBALE_ACQUISITO_CON_PAGAMENTO);\r\n if (idStato != null) {\r\n BigDecimal importoPagato = cnmTAllegatoFieldRepository.getImportoPagatoByIdVerbale(cnmTVerbale.getIdVerbale());\r\n if (importoPagato == null) {\r\n importoPagato = new BigDecimal(0);\r\n }\r\n if (importoPagato.compareTo(cnmTVerbale.getImportoVerbale()) != 0) {\r\n idStato = null;\r\n }\r\n }\r\n }\r\n return idStato;\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean isValid(Litmus litmus, Context context){\r\n if (!super.isValid(litmus, context)) {\r\n return false;\r\n }\r\n final String signature = signature();\r\n if (!isValidSignature(signature)) {\r\n return litmus.fail(\"invalid signature [{}]\", signature);\r\n }\r\n if (rels.isEmpty()) {\r\n return litmus.fail(\"must have at least one rel\");\r\n }\r\n for (int i = 0; i < rels.size(); i++) {\r\n final RelNode r = rels.get(i);\r\n if (i == 0) {\r\n if (!(r instanceof TableScan)) {\r\n return litmus.fail(\"first rel must be TableScan, was \", r);\r\n }\r\n if (r.getTable() != table) {\r\n return litmus.fail(\"first rel must be based on table table\");\r\n }\r\n } else {\r\n final List inputs = r.getInputs();\r\n if (inputs.size() != 1 || inputs.get(0) != rels.get(i - 1)) {\r\n return litmus.fail(\"each rel must have a single input\");\r\n }\r\n if (r instanceof Aggregate) {\r\n final Aggregate aggregate = (Aggregate) r;\r\n if (aggregate.getGroupSets().size() != 1) {\r\n return litmus.fail(\"no grouping sets\");\r\n }\r\n }\r\n if (r instanceof Filter) {\r\n final Filter filter = (Filter) r;\r\n final DruidJsonFilter druidJsonFilter = DruidJsonFilter.toDruidFilters(filter.getCondition(), filter.getInput().getRowType(), this, getCluster().getRexBuilder());\r\n if (druidJsonFilter == null) {\r\n return litmus.fail(\"invalid filter [{}]\", filter.getCondition());\r\n }\r\n }\r\n if (r instanceof Sort) {\r\n final Sort sort = (Sort) r;\r\n if (sort.offset != null && RexLiteral.intValue(sort.offset) != 0) {\r\n return litmus.fail(\"offset not supported\");\r\n }\r\n }\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static RestConsumerFactory locateRestConsumerFactory(CamelContext context, WebhookConfiguration configuration){\r\n RestConsumerFactory factory = null;\r\n if (configuration.getWebhookComponentName() != null) {\r\n Object comp = context.getRegistry().lookupByName(configuration.getWebhookComponentName());\r\n if (comp instanceof RestConsumerFactory) {\r\n factory = (RestConsumerFactory) comp;\r\n } else {\r\n comp = context.getComponent(configuration.getWebhookComponentName());\r\n if (comp instanceof RestConsumerFactory) {\r\n factory = (RestConsumerFactory) comp;\r\n }\r\n }\r\n if (factory == null) {\r\n if (comp != null) {\r\n throw new IllegalArgumentException(\"Component \" + configuration.getWebhookComponentName() + \" is not a RestConsumerFactory\");\r\n } else {\r\n throw new NoSuchBeanException(configuration.getWebhookComponentName(), RestConsumerFactory.class.getName());\r\n }\r\n }\r\n }\r\n if (factory == null) {\r\n for (String name : context.getComponentNames()) {\r\n Component comp = context.getComponent(name);\r\n if (comp instanceof RestConsumerFactory) {\r\n factory = (RestConsumerFactory) comp;\r\n break;\r\n }\r\n }\r\n }\r\n if (factory == null) {\r\n Set factories = context.getRegistry().findByType(RestConsumerFactory.class);\r\n if (factories != null && factories.size() == 1) {\r\n factory = factories.iterator().next();\r\n }\r\n }\r\n if (factory == null) {\r\n RestConsumerFactory found = null;\r\n for (String name : DEFAULT_REST_CONSUMER_COMPONENTS) {\r\n Object comp = context.getComponent(name, true);\r\n if (comp instanceof RestConsumerFactory) {\r\n if (found == null) {\r\n found = (RestConsumerFactory) comp;\r\n } else {\r\n throw new IllegalArgumentException(\"Multiple RestConsumerFactory found on classpath. Configure explicit which component to use\");\r\n }\r\n }\r\n }\r\n if (found != null) {\r\n factory = found;\r\n }\r\n }\r\n if (factory == null) {\r\n throw new IllegalStateException(\"Cannot find RestConsumerFactory in Registry or as a Component to use\");\r\n }\r\n return factory;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " synchronized void getReadWriteBookieInfo(){\r\n State queuedType = instanceState.getAndClearQueuedType();\r\n Collection toScan;\r\n if (queuedType == State.FULL) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Doing full scan\");\r\n }\r\n toScan = bookieInfoMap.getFullScanTargets();\r\n } else if (queuedType == State.PARTIAL) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Doing partial scan\");\r\n }\r\n toScan = bookieInfoMap.getPartialScanTargets();\r\n } else {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Invalid state, queuedType cannot be UNQUEUED in getReadWriteBookieInfo\");\r\n }\r\n assert (queuedType != State.UNQUEUED);\r\n return;\r\n }\r\n BookieClient bkc = bk.getBookieClient();\r\n final long requested = BookkeeperProtocol.GetBookieInfoRequest.Flags.TOTAL_DISK_CAPACITY_VALUE | BookkeeperProtocol.GetBookieInfoRequest.Flags.FREE_DISK_SPACE_VALUE;\r\n totalSent = 0;\r\n completedCnt = 0;\r\n errorCnt = 0;\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Getting bookie info for: {}\", toScan);\r\n }\r\n for (BookieId b : toScan) {\r\n bkc.getBookieInfo(b, requested, new GetBookieInfoCallback() {\r\n\r\n void processReadInfoComplete(int rc, BookieInfo bInfo, Object ctx) {\r\n synchronized (BookieInfoReader.this) {\r\n BookieId b = (BookieId) ctx;\r\n if (rc != BKException.Code.OK) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Reading bookie info from bookie {} failed due to {}\", b, BKException.codeLogger(rc));\r\n }\r\n bookieInfoMap.clearInfo(b);\r\n errorCnt++;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Bookie Info for bookie {} is {}\", b, bInfo);\r\n }\r\n bookieInfoMap.gotInfo(b, bInfo);\r\n }\r\n completedCnt++;\r\n if (totalSent == completedCnt) {\r\n onExit();\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void getBookieInfoComplete(final int rc, final BookieInfo bInfo, final Object ctx) {\r\n scheduler.submit(new Runnable() {\r\n\r\n @Override\r\n public void run() {\r\n processReadInfoComplete(rc, bInfo, ctx);\r\n }\r\n });\r\n }\r\n }, b);\r\n totalSent++;\r\n }\r\n if (totalSent == 0) {\r\n onExit();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " List getCmdList(String line, boolean entireLineAsCommand){\r\n if (entireLineAsCommand) {\r\n return Stream.of(line).collect(Collectors.toList());\r\n }\r\n List cmdList = new ArrayList();\r\n StringBuilder command = new StringBuilder();\r\n SectionType sectionType = null;\r\n int lastDelimiterIndex = 0;\r\n boolean wasPrevEscape = false;\r\n int index = 0;\r\n for (; index < line.length(); ) {\r\n if (!wasPrevEscape && sectionType == null && line.startsWith(\"'\", index)) {\r\n sectionType = SectionType.SINGLE_QUOTED;\r\n index++;\r\n } else if (!wasPrevEscape && sectionType == SectionType.SINGLE_QUOTED && line.startsWith(\"'\", index)) {\r\n sectionType = null;\r\n index++;\r\n } else if (!wasPrevEscape && sectionType == null && line.startsWith(\"\\\"\", index)) {\r\n sectionType = SectionType.DOUBLE_QUOTED;\r\n index++;\r\n } else if (!wasPrevEscape && sectionType == SectionType.DOUBLE_QUOTED && line.startsWith(\"\\\"\", index)) {\r\n sectionType = null;\r\n index++;\r\n } else if (sectionType == null && line.startsWith(\"--\", index)) {\r\n sectionType = SectionType.LINE_COMMENT;\r\n wasPrevEscape = false;\r\n index += 2;\r\n } else if (sectionType == SectionType.LINE_COMMENT && line.startsWith(\"\\n\", index)) {\r\n sectionType = null;\r\n wasPrevEscape = false;\r\n index++;\r\n } else if (sectionType == null && line.startsWith(\"/*\", index)) {\r\n sectionType = SectionType.BLOCK_COMMENT;\r\n wasPrevEscape = false;\r\n index += 2;\r\n } else if (sectionType == SectionType.BLOCK_COMMENT && line.startsWith(\"*/\", index)) {\r\n sectionType = null;\r\n wasPrevEscape = false;\r\n index += 2;\r\n } else if (line.startsWith(\"\\\\\", index)) {\r\n wasPrevEscape = !wasPrevEscape;\r\n index++;\r\n } else if (sectionType == null && line.startsWith(beeLine.getOpts().getDelimiter(), index)) {\r\n addCmdPart(cmdList, command, line.substring(lastDelimiterIndex, index));\r\n index += beeLine.getOpts().getDelimiter().length();\r\n lastDelimiterIndex = index;\r\n wasPrevEscape = false;\r\n } else {\r\n wasPrevEscape = false;\r\n index++;\r\n }\r\n }\r\n if (lastDelimiterIndex != index || line.length() == 0) {\r\n addCmdPart(cmdList, command, line.substring(lastDelimiterIndex, index));\r\n }\r\n return cmdList;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void tryStartJob(){\r\n JobCoordinationService coordinator = mc.coordinationService();\r\n MembersView membersView = Util.getMembersView(mc.nodeEngine());\r\n mc.coordinationService().submitToCoordinatorThread(() -> {\r\n try {\r\n executionStartTime = System.currentTimeMillis();\r\n JobExecutionRecord jobExecRec = mc.jobExecutionRecord();\r\n jobExecRec.markExecuted();\r\n DAG dag = resolveDag();\r\n if (dag == null) {\r\n return;\r\n }\r\n String dotRepresentation = dag.toDotString(defaultParallelism, defaultQueueSize);\r\n final long snapshotId = jobExecRec.snapshotId();\r\n final String snapshotName;\r\n final String snapshotMapName;\r\n if (snapshotId >= 0) {\r\n snapshotName = jobExecRec.exportedSnapshotName();\r\n snapshotMapName = jobExecRec.successfulSnapshotDataMapName();\r\n } else {\r\n snapshotName = mc.jobConfig().getInitialSnapshotName();\r\n snapshotMapName = snapshotName != null ? exportedSnapshotMapName(snapshotName) : null;\r\n }\r\n if (snapshotMapName != null) {\r\n rewriteDagWithSnapshotRestore(dag, snapshotId, snapshotMapName, snapshotName);\r\n } else {\r\n logger.info(\"Didn't find any snapshot to restore for \" + mc.jobIdString());\r\n }\r\n logger.info(\"Start executing \" + mc.jobIdString() + \", execution graph in DOT format:\\n\" + dotRepresentation + \"\\nHINT: You can use graphviz or http://viz-js.com to visualize the printed graph.\");\r\n logger.fine(\"Building execution plan for \" + mc.jobIdString());\r\n createExecutionPlans(dag, membersView).thenCompose(plans -> coordinator.submitToCoordinatorThread(() -> initExecution(membersView, plans))).whenComplete((r, e) -> {\r\n if (e != null) {\r\n finalizeExecution(peel(e));\r\n }\r\n });\r\n } catch (Throwable e) {\r\n finalizeExecution(e);\r\n }\r\n });\r\n if (mc.hasTimeout()) {\r\n long remainingTime = mc.remainingTime(Clock.currentTimeMillis());\r\n mc.coordinationService().scheduleJobTimeout(mc.jobId(), Math.max(1, remainingTime));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Object[] getParams(CxfEndpoint endpoint, Exchange exchange) throws org.apache.camel.InvalidPayloadException{\r\n Object[] params = null;\r\n if (endpoint.getDataFormat() == DataFormat.POJO) {\r\n Object body = exchange.getIn().getBody();\r\n if (body == null) {\r\n return new Object[0];\r\n }\r\n if (body instanceof Object[]) {\r\n params = (Object[]) body;\r\n } else if (body instanceof List) {\r\n params = ((List) body).toArray();\r\n } else {\r\n Iterator it = exchange.getIn().getBody(Iterator.class);\r\n if (it != null && it.hasNext()) {\r\n List list = exchange.getContext().getTypeConverter().convertTo(List.class, it);\r\n if (list != null) {\r\n params = list.toArray();\r\n }\r\n }\r\n if (params == null) {\r\n params = new Object[1];\r\n params[0] = exchange.getIn().getBody();\r\n }\r\n }\r\n checkParameterSize(endpoint, exchange, params);\r\n } else if (endpoint.getDataFormat() == DataFormat.PAYLOAD) {\r\n params = new Object[1];\r\n params[0] = exchange.getIn().getMandatoryBody(CxfPayload.class);\r\n } else if (endpoint.getDataFormat().dealias() == DataFormat.RAW) {\r\n params = new Object[1];\r\n params[0] = exchange.getIn().getMandatoryBody(InputStream.class);\r\n } else if (endpoint.getDataFormat().dealias() == DataFormat.CXF_MESSAGE) {\r\n params = new Object[1];\r\n params[0] = exchange.getIn().getBody();\r\n }\r\n if (LOG.isTraceEnabled()) {\r\n if (params != null) {\r\n for (int i = 0; i < params.length; i++) {\r\n LOG.trace(\"params[{}] = {}\", i, params[i]);\r\n }\r\n }\r\n }\r\n return params;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public TSStatus checkConfigNodeGlobalConfig(TConfigNodeRegisterReq req){\r\n final String errorPrefix = \"Reject register, please ensure that the parameter \";\r\n final String errorSuffix = \" is consistent with the Seed-ConfigNode.\";\r\n TSStatus errorStatus = new TSStatus(TSStatusCode.CONFIGURATION_ERROR.getStatusCode());\r\n TClusterParameters clusterParameters = req.getClusterParameters();\r\n if (!clusterParameters.getConfigNodeConsensusProtocolClass().equals(CONF.getConfigNodeConsensusProtocolClass())) {\r\n return errorStatus.setMessage(errorPrefix + \"config_node_consensus_protocol_class\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getDataRegionConsensusProtocolClass().equals(CONF.getDataRegionConsensusProtocolClass())) {\r\n return errorStatus.setMessage(errorPrefix + \"data_region_consensus_protocol_class\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getSchemaRegionConsensusProtocolClass().equals(CONF.getSchemaRegionConsensusProtocolClass())) {\r\n return errorStatus.setMessage(errorPrefix + \"schema_region_consensus_protocol_class\" + errorSuffix);\r\n }\r\n if (clusterParameters.getSeriesPartitionSlotNum() != CONF.getSeriesSlotNum()) {\r\n return errorStatus.setMessage(errorPrefix + \"series_partition_slot_num\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getSeriesPartitionExecutorClass().equals(CONF.getSeriesPartitionExecutorClass())) {\r\n return errorStatus.setMessage(errorPrefix + \"series_partition_executor_class\" + errorSuffix);\r\n }\r\n if (clusterParameters.getDefaultTTL() != CommonDescriptor.getInstance().getConfig().getDefaultTTLInMs()) {\r\n return errorStatus.setMessage(errorPrefix + \"default_ttl\" + errorSuffix);\r\n }\r\n if (clusterParameters.getTimePartitionInterval() != COMMON_CONF.getTimePartitionInterval()) {\r\n return errorStatus.setMessage(errorPrefix + \"time_partition_interval\" + errorSuffix);\r\n }\r\n if (clusterParameters.getSchemaReplicationFactor() != CONF.getSchemaReplicationFactor()) {\r\n return errorStatus.setMessage(errorPrefix + \"schema_replication_factor\" + errorSuffix);\r\n }\r\n if (clusterParameters.getDataReplicationFactor() != CONF.getDataReplicationFactor()) {\r\n return errorStatus.setMessage(errorPrefix + \"data_replication_factor\" + errorSuffix);\r\n }\r\n if (clusterParameters.getSchemaRegionPerDataNode() != CONF.getSchemaRegionPerDataNode()) {\r\n return errorStatus.setMessage(errorPrefix + \"schema_region_per_data_node\" + errorSuffix);\r\n }\r\n if (clusterParameters.getDataRegionPerDataNode() != CONF.getDataRegionPerDataNode()) {\r\n return errorStatus.setMessage(errorPrefix + \"data_region_per_data_node\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getReadConsistencyLevel().equals(CONF.getReadConsistencyLevel())) {\r\n return errorStatus.setMessage(errorPrefix + \"read_consistency_level\" + errorSuffix);\r\n }\r\n if (clusterParameters.getDiskSpaceWarningThreshold() != COMMON_CONF.getDiskSpaceWarningThreshold()) {\r\n return errorStatus.setMessage(errorPrefix + \"disk_space_warning_threshold\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getTimestampPrecision().equals(COMMON_CONF.getTimestampPrecision())) {\r\n return errorStatus.setMessage(errorPrefix + \"timestamp_precision\" + errorSuffix);\r\n }\r\n if (!clusterParameters.getSchemaEngineMode().equals(COMMON_CONF.getSchemaEngineMode())) {\r\n return errorStatus.setMessage(errorPrefix + \"schema_engine_mode\" + errorSuffix);\r\n }\r\n if (clusterParameters.getTagAttributeTotalSize() != COMMON_CONF.getTagAttributeTotalSize()) {\r\n return errorStatus.setMessage(errorPrefix + \"tag_attribute_total_size\" + errorSuffix);\r\n }\r\n if (clusterParameters.getDatabaseLimitThreshold() != COMMON_CONF.getDatabaseLimitThreshold()) {\r\n return errorStatus.setMessage(errorPrefix + \"database_limit_threshold\" + errorSuffix);\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void appendJmsProperty(Message jmsMessage, Exchange exchange, String headerName, Object headerValue) throws JMSException{\r\n if (isStandardJMSHeader(headerName)) {\r\n if (headerName.equals(JmsConstants.JMS_CORRELATION_ID)) {\r\n jmsMessage.setJMSCorrelationID(ExchangeHelper.convertToType(exchange, String.class, headerValue));\r\n } else if (headerName.equals(JmsConstants.JMS_REPLY_TO) && headerValue != null) {\r\n if (headerValue instanceof String) {\r\n headerValue = normalizeDestinationName((String) headerValue, true);\r\n }\r\n Destination replyTo = ExchangeHelper.convertToType(exchange, Destination.class, headerValue);\r\n JmsMessageHelper.setJMSReplyTo(jmsMessage, replyTo);\r\n } else if (headerName.equals(\"JMSType\")) {\r\n jmsMessage.setJMSType(ExchangeHelper.convertToType(exchange, String.class, headerValue));\r\n } else if (headerName.equals(\"JMSPriority\")) {\r\n jmsMessage.setJMSPriority(ExchangeHelper.convertToType(exchange, Integer.class, headerValue));\r\n } else if (headerName.equals(\"JMSDeliveryMode\")) {\r\n JmsMessageHelper.setJMSDeliveryMode(exchange, jmsMessage, headerValue);\r\n } else if (headerName.equals(\"JMSExpiration\")) {\r\n jmsMessage.setJMSExpiration(ExchangeHelper.convertToType(exchange, Long.class, headerValue));\r\n } else {\r\n LOG.trace(\"Ignoring JMS header: {} with value: {}\", headerName, headerValue);\r\n }\r\n } else if (shouldOutputHeader(headerName, headerValue, exchange)) {\r\n Object value = getValidJMSHeaderValue(headerName, headerValue);\r\n if (value != null) {\r\n String key = jmsJmsKeyFormatStrategy.encodeKey(headerName);\r\n JmsMessageHelper.setProperty(jmsMessage, key, value);\r\n } else if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ignoring non primitive header: {} of class: {} with value: {}\", headerName, headerValue.getClass().getName(), headerValue);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void checkAllLedgers() throws BKException, IOException, InterruptedException{\r\n final BookKeeper localClient = getBookKeeper(conf);\r\n final BookKeeperAdmin localAdmin = getBookKeeperAdmin(localClient);\r\n try {\r\n final LedgerChecker checker = new LedgerChecker(localClient, conf.getInFlightReadEntryNumInLedgerChecker());\r\n final CompletableFuture processFuture = new CompletableFuture<>();\r\n Processor checkLedgersProcessor = (ledgerId, callback) -> {\r\n try {\r\n if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) {\r\n LOG.info(\"Ledger rereplication has been disabled, aborting periodic check\");\r\n FutureUtils.complete(processFuture, null);\r\n return;\r\n }\r\n } catch (ReplicationException.NonRecoverableReplicationException nre) {\r\n LOG.error(\"Non Recoverable Exception while reading from ZK\", nre);\r\n submitShutdownTask();\r\n return;\r\n } catch (UnavailableException ue) {\r\n LOG.error(\"Underreplication manager unavailable running periodic check\", ue);\r\n FutureUtils.complete(processFuture, null);\r\n return;\r\n }\r\n try {\r\n if (!openLedgerNoRecoverySemaphore.tryAcquire(openLedgerNoRecoverySemaphoreWaitTimeoutMSec, TimeUnit.MILLISECONDS)) {\r\n LOG.warn(\"Failed to acquire semaphore for {} ms, ledgerId: {}\", openLedgerNoRecoverySemaphoreWaitTimeoutMSec, ledgerId);\r\n FutureUtils.complete(processFuture, null);\r\n return;\r\n }\r\n } catch (InterruptedException e) {\r\n LOG.error(\"Unable to acquire open ledger operation semaphore \", e);\r\n Thread.currentThread().interrupt();\r\n FutureUtils.complete(processFuture, null);\r\n return;\r\n }\r\n localAdmin.asyncOpenLedgerNoRecovery(ledgerId, (rc, lh, ctx) -> {\r\n openLedgerNoRecoverySemaphore.release();\r\n if (Code.OK == rc) {\r\n checker.checkLedger(lh, new ProcessLostFragmentsCb(lh, callback), conf.getAuditorLedgerVerificationPercentage());\r\n numFragmentsPerLedger.registerSuccessfulValue(lh.getNumFragments());\r\n numBookiesPerLedger.registerSuccessfulValue(lh.getNumBookies());\r\n numLedgersChecked.inc();\r\n } else if (Code.NoSuchLedgerExistsOnMetadataServerException == rc) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ledger {} was deleted before we could check it\", ledgerId);\r\n }\r\n callback.processResult(Code.OK, null, null);\r\n } else {\r\n LOG.error(\"Couldn't open ledger {} to check : {}\", ledgerId, BKException.getMessage(rc));\r\n callback.processResult(rc, null, null);\r\n }\r\n }, null);\r\n };\r\n ledgerManager.asyncProcessLedgers(checkLedgersProcessor, (rc, path, ctx) -> {\r\n if (Code.OK == rc) {\r\n FutureUtils.complete(processFuture, null);\r\n } else {\r\n FutureUtils.completeExceptionally(processFuture, BKException.create(rc));\r\n }\r\n }, null, BKException.Code.OK, BKException.Code.ReadException);\r\n FutureUtils.result(processFuture, BKException.HANDLER);\r\n try {\r\n ledgerUnderreplicationManager.setCheckAllLedgersCTime(System.currentTimeMillis());\r\n } catch (ReplicationException.NonRecoverableReplicationException nre) {\r\n LOG.error(\"Non Recoverable Exception while reading from ZK\", nre);\r\n submitShutdownTask();\r\n } catch (UnavailableException ue) {\r\n LOG.error(\"Got exception while trying to set checkAllLedgersCTime\", ue);\r\n }\r\n } finally {\r\n localAdmin.close();\r\n localClient.close();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Set visit(SqlCall call){\r\n boolean isSingle = false;\r\n Set vars = new HashSet<>();\r\n SqlKind kind = call.getKind();\r\n List operands = call.getOperandList();\r\n if (isSingleVarRequired(kind)) {\r\n isSingle = true;\r\n if (isPhysicalNavigation(kind)) {\r\n if (isMeasure) {\r\n throw newValidationError(call, Static.RESOURCE.patternPrevFunctionInMeasure(call.toString()));\r\n }\r\n if (firstLastCount != 0) {\r\n throw newValidationError(call, Static.RESOURCE.patternPrevFunctionOrder(call.toString()));\r\n }\r\n prevNextCount++;\r\n } else if (isLogicalNavigation(kind)) {\r\n if (firstLastCount != 0) {\r\n throw newValidationError(call, Static.RESOURCE.patternPrevFunctionOrder(call.toString()));\r\n }\r\n firstLastCount++;\r\n } else if (isAggregation(kind)) {\r\n if (firstLastCount != 0 || prevNextCount != 0) {\r\n throw newValidationError(call, Static.RESOURCE.patternAggregationInNavigation(call.toString()));\r\n }\r\n if (kind == SqlKind.COUNT && call.getOperandList().size() > 1) {\r\n throw newValidationError(call, Static.RESOURCE.patternCountFunctionArg());\r\n }\r\n aggregateCount++;\r\n }\r\n }\r\n if (isRunningOrFinal(kind) && !isMeasure) {\r\n throw newValidationError(call, Static.RESOURCE.patternRunningFunctionInDefine(call.toString()));\r\n }\r\n for (SqlNode node : operands) {\r\n if (node != null) {\r\n vars.addAll(requireNonNull(node.accept(new PatternValidator(isMeasure, firstLastCount, prevNextCount, aggregateCount)), () -> \"node.accept(PatternValidator) for node \" + node));\r\n }\r\n }\r\n if (isSingle) {\r\n switch(kind) {\r\n case COUNT:\r\n if (vars.size() > 1) {\r\n throw newValidationError(call, Static.RESOURCE.patternCountFunctionArg());\r\n }\r\n break;\r\n default:\r\n if (operands.size() == 0 || !(operands.get(0) instanceof SqlCall) || ((SqlCall) operands.get(0)).getOperator() != SqlStdOperatorTable.CLASSIFIER) {\r\n if (vars.isEmpty()) {\r\n throw newValidationError(call, Static.RESOURCE.patternFunctionNullCheck(call.toString()));\r\n }\r\n if (vars.size() != 1) {\r\n throw newValidationError(call, Static.RESOURCE.patternFunctionVariableCheck(call.toString()));\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n return vars;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void apply(RelOptRuleCall call, @Nullable Project postProject, final Aggregate aggregate, StarTable.StarTableScan scan){\r\n final RelOptPlanner planner = call.getPlanner();\r\n final Optional config = planner.getContext().maybeUnwrap(CalciteConnectionConfig.class);\r\n if (!(config.isPresent() && config.get().createMaterializations())) {\r\n return;\r\n }\r\n final RelOptCluster cluster = scan.getCluster();\r\n final RelOptTable table = scan.getTable();\r\n final RelOptLattice lattice = requireNonNull(planner.getLattice(table), () -> \"planner.getLattice(table) is null for \" + table);\r\n final List measures = lattice.lattice.toMeasures(aggregate.getAggCallList());\r\n final Pair pair = lattice.getAggregate(planner, aggregate.getGroupSet(), measures);\r\n if (pair == null) {\r\n return;\r\n }\r\n final RelBuilder relBuilder = call.builder();\r\n final CalciteSchema.TableEntry tableEntry = pair.left;\r\n final TileKey tileKey = pair.right;\r\n final RelMetadataQuery mq = call.getMetadataQuery();\r\n final double rowCount = aggregate.estimateRowCount(mq);\r\n final Table aggregateTable = tableEntry.getTable();\r\n final RelDataType aggregateTableRowType = aggregateTable.getRowType(cluster.getTypeFactory());\r\n final RelOptTable aggregateRelOptTable = RelOptTableImpl.create(table.getRelOptSchema(), aggregateTableRowType, tableEntry, rowCount);\r\n relBuilder.push(aggregateRelOptTable.toRel(ViewExpanders.simpleContext(cluster)));\r\n if (tileKey == null) {\r\n if (CalciteSystemProperty.DEBUG.value()) {\r\n System.out.println(\"Using materialization \" + aggregateRelOptTable.getQualifiedName() + \" (exact match)\");\r\n }\r\n } else if (!tileKey.dimensions.equals(aggregate.getGroupSet())) {\r\n if (CalciteSystemProperty.DEBUG.value()) {\r\n System.out.println(\"Using materialization \" + aggregateRelOptTable.getQualifiedName() + \", rolling up \" + tileKey.dimensions + \" to \" + aggregate.getGroupSet());\r\n }\r\n assert tileKey.dimensions.contains(aggregate.getGroupSet());\r\n final List aggCalls = new ArrayList<>();\r\n ImmutableBitSet.Builder groupSet = ImmutableBitSet.builder();\r\n for (int key : aggregate.getGroupSet()) {\r\n groupSet.set(tileKey.dimensions.indexOf(key));\r\n }\r\n for (AggregateCall aggCall : aggregate.getAggCallList()) {\r\n final AggregateCall copy = rollUp(groupSet.cardinality(), relBuilder, aggCall, tileKey);\r\n if (copy == null) {\r\n return;\r\n }\r\n aggCalls.add(copy);\r\n }\r\n relBuilder.push(aggregate.copy(aggregate.getTraitSet(), relBuilder.build(), groupSet.build(), null, aggCalls));\r\n } else if (!tileKey.measures.equals(measures)) {\r\n if (CalciteSystemProperty.DEBUG.value()) {\r\n System.out.println(\"Using materialization \" + aggregateRelOptTable.getQualifiedName() + \", right granularity, but different measures \" + aggregate.getAggCallList());\r\n }\r\n relBuilder.project(relBuilder.fields(new AbstractSourceMapping(tileKey.dimensions.cardinality() + tileKey.measures.size(), aggregate.getRowType().getFieldCount()) {\r\n\r\n @Override\r\n public int getSourceOpt(int source) {\r\n if (source < aggregate.getGroupCount()) {\r\n int in = tileKey.dimensions.nth(source);\r\n return aggregate.getGroupSet().indexOf(in);\r\n }\r\n Lattice.Measure measure = measures.get(source - aggregate.getGroupCount());\r\n int i = tileKey.measures.indexOf(measure);\r\n assert i >= 0;\r\n return tileKey.dimensions.cardinality() + i;\r\n }\r\n }.inverse()));\r\n }\r\n if (postProject != null) {\r\n relBuilder.push(postProject.copy(postProject.getTraitSet(), ImmutableList.of(relBuilder.peek())));\r\n }\r\n call.transformTo(relBuilder.build());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String trim(boolean left, boolean right, String seek, String s, boolean strict){\r\n if (strict && seek.length() != 1) {\r\n throw RESOURCE.trimError().ex();\r\n }\r\n int j = s.length();\r\n if (right) {\r\n for (; ; ) {\r\n if (j == 0) {\r\n return \"\";\r\n }\r\n if (seek.indexOf(s.charAt(j - 1)) < 0) {\r\n break;\r\n }\r\n --j;\r\n }\r\n }\r\n int i = 0;\r\n if (left) {\r\n for (; ; ) {\r\n if (i == j) {\r\n return \"\";\r\n }\r\n if (seek.indexOf(s.charAt(i)) < 0) {\r\n break;\r\n }\r\n ++i;\r\n }\r\n }\r\n return s.substring(i, j);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void operatorSub(HplsqlParser.ExprContext ctx){\r\n Var v1 = evalPop(ctx.expr(0));\r\n Var v2 = evalPop(ctx.expr(1));\r\n if (v1.value == null || v2.value == null) {\r\n evalNull();\r\n } else if (v1.type == Type.BIGINT && v2.type == Type.BIGINT) {\r\n exec.stackPush(new Var((long) v1.value - (long) v2.value));\r\n } else if (v1.type == Type.BIGINT && v2.type == Type.DECIMAL) {\r\n exec.stackPush(new Var((new BigDecimal((long) v1.value)).subtract((BigDecimal) v2.value)));\r\n } else if (v1.type == Type.BIGINT && v2.type == Type.DOUBLE) {\r\n exec.stackPush(new Var((long) v1.value - (double) v2.value));\r\n } else if (v1.type == Type.DECIMAL && v2.type == Type.DECIMAL) {\r\n exec.stackPush(new Var(((BigDecimal) v1.value).subtract((BigDecimal) v2.value)));\r\n } else if (v1.type == Type.DECIMAL && v2.type == Type.BIGINT) {\r\n exec.stackPush(new Var(((BigDecimal) v1.value).subtract(new BigDecimal((long) v2.value))));\r\n } else if (v1.type == Type.DECIMAL && v2.type == Type.DOUBLE) {\r\n exec.stackPush(new Var(((BigDecimal) v1.value).subtract(new BigDecimal((double) v2.value))));\r\n } else if (v1.type == Type.DOUBLE && v2.type == Type.DOUBLE) {\r\n exec.stackPush(new Var((double) v1.value - (double) v2.value));\r\n } else if (v1.type == Type.DOUBLE && v2.type == Type.DECIMAL) {\r\n exec.stackPush(new Var((new BigDecimal((double) v1.value)).subtract((BigDecimal) v2.value)));\r\n } else if (v1.type == Type.DOUBLE && v2.type == Type.BIGINT) {\r\n exec.stackPush(new Var(((double) v1.value) - (long) v2.value));\r\n } else if (v1.type == Type.DATE && v2.type == Type.BIGINT) {\r\n exec.stackPush(changeDateByInt((Date) v1.value, (long) v2.value, false));\r\n } else if (v1.type == Type.DATE && v2.type == Type.INTERVAL) {\r\n exec.stackPush(new Var(((Interval) v2.value).dateChange((Date) v1.value, false)));\r\n } else if (v1.type == Type.TIMESTAMP && v2.type == Type.INTERVAL) {\r\n exec.stackPush(new Var(((Interval) v2.value).timestampChange((Timestamp) v1.value, false), v1.scale));\r\n } else {\r\n unsupported(ctx, v1, v2, \"-\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void buildResourceType(ResourceBuilder resourceBuilder, ResourceType resourceType){\r\n List resourcesByType = this.resourcesByType.remove(resourceType);\r\n if (resourcesByType != null) {\r\n for (ResourceDescr resourceDescr : resourcesByType) {\r\n try {\r\n kBuilder.setAssetFilter(resourceDescr.getFilter());\r\n resourceBuilder.build(kBuilder, resourceDescr);\r\n } catch (RuntimeException e) {\r\n if (buildException == null) {\r\n buildException = e;\r\n }\r\n } catch (Exception e) {\r\n if (buildException == null) {\r\n buildException = new RuntimeException(e);\r\n }\r\n } finally {\r\n kBuilder.setAssetFilter(null);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List findAtomLinkages(final Group group1, final Group group2, List potentialNamesOfAtomOnGroup1, List potentialNamesOfAtomOnGroup2, final boolean ignoreNCLinkage, final double bondLengthTolerance){\r\n if (group1 == null || group2 == null) {\r\n throw new IllegalArgumentException(\"Null group(s).\");\r\n }\r\n if (bondLengthTolerance < 0) {\r\n throw new IllegalArgumentException(\"bondLengthTolerance cannot be negative.\");\r\n }\r\n List ret = new ArrayList();\r\n if (potentialNamesOfAtomOnGroup1 == null) {\r\n potentialNamesOfAtomOnGroup1 = getAtomNames(group1);\r\n }\r\n if (potentialNamesOfAtomOnGroup2 == null) {\r\n potentialNamesOfAtomOnGroup2 = getAtomNames(group2);\r\n }\r\n for (String namesOfAtomOnGroup1 : potentialNamesOfAtomOnGroup1) {\r\n for (String namesOfAtomOnGroup2 : potentialNamesOfAtomOnGroup2) {\r\n Atom[] atoms = findLinkage(group1, group2, namesOfAtomOnGroup1, namesOfAtomOnGroup2, bondLengthTolerance);\r\n if (atoms != null) {\r\n if (ignoreNCLinkage && ((atoms[0].getName().equals(\"N\") && atoms[1].getName().equals(\"C\")) || (atoms[0].getName().equals(\"C\") && atoms[1].getName().equals(\"N\")))) {\r\n continue;\r\n }\r\n ret.add(atoms);\r\n }\r\n }\r\n }\r\n return ret;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void check3StopArea6(Context context, StopArea stopArea, ValidationParameters parameters){\r\n if (stopArea.getStopAreaType() == null || stopArea.getTransportModeName() == null)\r\n return;\r\n if (stopArea.getTransportModeName() == null) {\r\n return;\r\n }\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n switch(stopArea.getStopAreaType()) {\r\n case Airport:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Air)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case CoachStation:\r\n case BusStation:\r\n case OnstreetBus:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Bus)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case FerryPort:\r\n case FerryStop:\r\n case HarbourPort:\r\n if (!EnumSet.of(TransportModeNameEnum.Water, TransportModeNameEnum.Ferry).contains(stopArea.getTransportModeName())) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case LiftStation:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Cableway)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case MetroStation:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Metro)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case TramStation:\r\n case OnstreetTram:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Tram)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n case RailStation:\r\n if (!stopArea.getTransportModeName().equals(TransportModeNameEnum.Rail)) {\r\n DataLocation location = buildLocation(context, stopArea);\r\n reporter.addCheckPointReportError(context, STOP_AREA_6, location);\r\n }\r\n break;\r\n default:\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private byte[] createLocalFileHeader(final ZipArchiveEntry ze, final ByteBuffer name, final boolean encodable, final boolean phased, final long archiveOffset){\r\n final ZipExtraField oldEx = ze.getExtraField(ResourceAlignmentExtraField.ID);\r\n if (oldEx != null) {\r\n ze.removeExtraField(ResourceAlignmentExtraField.ID);\r\n }\r\n final ResourceAlignmentExtraField oldAlignmentEx = oldEx instanceof ResourceAlignmentExtraField ? (ResourceAlignmentExtraField) oldEx : null;\r\n int alignment = ze.getAlignment();\r\n if (alignment <= 0 && oldAlignmentEx != null) {\r\n alignment = oldAlignmentEx.getAlignment();\r\n }\r\n if (alignment > 1 || oldAlignmentEx != null && !oldAlignmentEx.allowMethodChange()) {\r\n final int oldLength = LFH_FILENAME_OFFSET + name.limit() - name.position() + ze.getLocalFileDataExtra().length;\r\n final int padding = (int) (-archiveOffset - oldLength - ZipExtraField.EXTRAFIELD_HEADER_SIZE - ResourceAlignmentExtraField.BASE_SIZE & alignment - 1);\r\n ze.addExtraField(new ResourceAlignmentExtraField(alignment, oldAlignmentEx != null && oldAlignmentEx.allowMethodChange(), padding));\r\n }\r\n final byte[] extra = ze.getLocalFileDataExtra();\r\n final int nameLen = name.limit() - name.position();\r\n final int len = LFH_FILENAME_OFFSET + nameLen + extra.length;\r\n final byte[] buf = new byte[len];\r\n System.arraycopy(LFH_SIG, 0, buf, LFH_SIG_OFFSET, ZipConstants.WORD);\r\n final int zipMethod = ze.getMethod();\r\n final boolean dataDescriptor = usesDataDescriptor(zipMethod, phased);\r\n ZipShort.putShort(versionNeededToExtract(zipMethod, hasZip64Extra(ze), dataDescriptor), buf, LFH_VERSION_NEEDED_OFFSET);\r\n final GeneralPurposeBit generalPurposeBit = getGeneralPurposeBits(!encodable && fallbackToUTF8, dataDescriptor);\r\n generalPurposeBit.encode(buf, LFH_GPB_OFFSET);\r\n ZipShort.putShort(zipMethod, buf, LFH_METHOD_OFFSET);\r\n ZipUtil.toDosTime(ze.getTime(), buf, LFH_TIME_OFFSET);\r\n if (phased || !(zipMethod == DEFLATED || channel != null)) {\r\n ZipLong.putLong(ze.getCrc(), buf, LFH_CRC_OFFSET);\r\n } else {\r\n System.arraycopy(LZERO, 0, buf, LFH_CRC_OFFSET, ZipConstants.WORD);\r\n }\r\n if (hasZip64Extra(entry.entry)) {\r\n ZipLong.ZIP64_MAGIC.putLong(buf, LFH_COMPRESSED_SIZE_OFFSET);\r\n ZipLong.ZIP64_MAGIC.putLong(buf, LFH_ORIGINAL_SIZE_OFFSET);\r\n } else if (phased) {\r\n ZipLong.putLong(ze.getCompressedSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);\r\n ZipLong.putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);\r\n } else if (zipMethod == DEFLATED || channel != null) {\r\n System.arraycopy(LZERO, 0, buf, LFH_COMPRESSED_SIZE_OFFSET, ZipConstants.WORD);\r\n System.arraycopy(LZERO, 0, buf, LFH_ORIGINAL_SIZE_OFFSET, ZipConstants.WORD);\r\n } else {\r\n ZipLong.putLong(ze.getSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);\r\n ZipLong.putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);\r\n }\r\n ZipShort.putShort(nameLen, buf, LFH_FILENAME_LENGTH_OFFSET);\r\n ZipShort.putShort(extra.length, buf, LFH_EXTRA_LENGTH_OFFSET);\r\n System.arraycopy(name.array(), name.arrayOffset(), buf, LFH_FILENAME_OFFSET, nameLen);\r\n System.arraycopy(extra, 0, buf, LFH_FILENAME_OFFSET + nameLen, extra.length);\r\n return buf;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void visitChild(LeftTuple lt, boolean insert, InternalWorkingMemory wm, TerminalNode tn){\r\n LeftTuple prevLt = null;\r\n LeftTupleSinkNode sink = (LeftTupleSinkNode) lt.getTupleSink();\r\n for (; sink != null; sink = sink.getNextLeftTupleSinkNode()) {\r\n if (lt != null) {\r\n if (isAssociatedWith(lt.getTupleSink(), tn)) {\r\n if (lt.getTupleSink().getAssociatedTerminalsSize() > 1) {\r\n if (lt.getFirstChild() != null) {\r\n for (LeftTuple child = lt.getFirstChild(); child != null; child = child.getHandleNext()) {\r\n visitChild(child, insert, wm, tn);\r\n }\r\n } else if (lt.getTupleSink().getType() == NodeTypeEnums.RightInputAdapterNode) {\r\n insertPeerRightTuple(lt, wm, tn, insert);\r\n }\r\n } else if (!insert) {\r\n iterateLeftTuple(lt, wm);\r\n LeftTuple lt2 = null;\r\n for (LeftTuple peerLt = lt.getPeer(); peerLt != null && isAssociatedWith(peerLt.getTupleSink(), tn) && peerLt.getTupleSink().getAssociatedTerminalsSize() == 1; peerLt = peerLt.getPeer()) {\r\n iterateLeftTuple(peerLt, wm);\r\n lt2 = peerLt;\r\n }\r\n deleteLeftTuple(lt, lt2, prevLt);\r\n break;\r\n }\r\n }\r\n prevLt = lt;\r\n lt = lt.getPeer();\r\n } else {\r\n prevLt = insertPeerLeftTuple(prevLt, sink, wm, insert);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void visitLdcInsn(final Object cst){\r\n final CPConstant constant = cpBands.getConstant(cst);\r\n if (segment.lastConstantHadWideIndex() || constant instanceof CPLong || constant instanceof CPDouble) {\r\n byteCodeOffset += 3;\r\n if (constant instanceof CPInt) {\r\n bcCodes.add(237);\r\n bcIntref.add((CPInt) constant);\r\n } else if (constant instanceof CPFloat) {\r\n bcCodes.add(238);\r\n bcFloatRef.add((CPFloat) constant);\r\n } else if (constant instanceof CPLong) {\r\n bcCodes.add(20);\r\n bcLongRef.add((CPLong) constant);\r\n } else if (constant instanceof CPDouble) {\r\n bcCodes.add(239);\r\n bcDoubleRef.add((CPDouble) constant);\r\n } else if (constant instanceof CPString) {\r\n bcCodes.add(19);\r\n bcStringRef.add((CPString) constant);\r\n } else if (constant instanceof CPClass) {\r\n bcCodes.add(236);\r\n bcClassRef.add((CPClass) constant);\r\n } else {\r\n throw new IllegalArgumentException(\"Constant should not be null\");\r\n }\r\n } else {\r\n byteCodeOffset += 2;\r\n if (constant instanceof CPInt) {\r\n bcCodes.add(234);\r\n bcIntref.add((CPInt) constant);\r\n } else if (constant instanceof CPFloat) {\r\n bcCodes.add(235);\r\n bcFloatRef.add((CPFloat) constant);\r\n } else if (constant instanceof CPString) {\r\n bcCodes.add(18);\r\n bcStringRef.add((CPString) constant);\r\n } else if (constant instanceof CPClass) {\r\n bcCodes.add(233);\r\n bcClassRef.add((CPClass) constant);\r\n }\r\n }\r\n updateRenumbering();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static String replaceNationalCharactersWithASCIIEquivalent(String s){\r\n final StringBuilder sb = new StringBuilder(s.length() * 2);\r\n final StringCharacterIterator iterator = new StringCharacterIterator(s);\r\n char ch = iterator.current();\r\n while (ch != StringCharacterIterator.DONE) {\r\n if (Character.getNumericValue(ch) > 0) {\r\n sb.append(ch);\r\n } else {\r\n if (Character.toString(ch).equals(\"\u00c3\u0160\")) {\r\n sb.append(\"E\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u02c6\")) {\r\n sb.append(\"E\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00ab\")) {\r\n sb.append(\"e\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a9\")) {\r\n sb.append(\"e\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a8\")) {\r\n sb.append(\"e\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u201a\")) {\r\n sb.append(\"A\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u0178\")) {\r\n sb.append(\"ss\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u2021\")) {\r\n sb.append(\"C\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u2013\")) {\r\n sb.append(\"O\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u201c\")) {\r\n sb.append(\"O\");\r\n } else if (Character.toString(ch).equals(\"\u00c2\u00aa\")) {\r\n sb.append(\"\");\r\n } else if (Character.toString(ch).equals(\"\u00c2\u00ba\")) {\r\n sb.append(\"\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u2030\")) {\r\n sb.append(\"E\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u201e\")) {\r\n sb.append(\"A\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u2026\")) {\r\n sb.append(\"A\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a5\")) {\r\n sb.append(\"a\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a4\")) {\r\n sb.append(\"a\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u0153\")) {\r\n sb.append(\"U\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00b6\")) {\r\n sb.append(\"o\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00bc\")) {\r\n sb.append(\"u\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a1\")) {\r\n sb.append(\"a\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u2020\")) {\r\n sb.append(\"E\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00a6\")) {\r\n sb.append(\"e\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u02dc\")) {\r\n sb.append(\"O\");\r\n } else if (Character.toString(ch).equals(\"\u00c3\u00b8\")) {\r\n sb.append(\"o\");\r\n } else {\r\n sb.append(ch);\r\n }\r\n }\r\n ch = iterator.next();\r\n }\r\n return sb.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processClassWithoutByteCode(final Class clazz, final boolean includeFinalMethods){\r\n final List methods = Arrays.asList(clazz.getMethods());\r\n methods.sort((m1, m2) -> {\r\n String n1 = m1.getName();\r\n String n2 = m2.getName();\r\n if (n1.equals(n2) && m1.getDeclaringClass() != m2.getDeclaringClass()) {\r\n return m1.getDeclaringClass().isAssignableFrom(m2.getDeclaringClass()) ? -1 : 1;\r\n } else {\r\n return n1.compareTo(n2);\r\n }\r\n });\r\n final int mask = includeFinalMethods ? Modifier.PUBLIC : Modifier.PUBLIC | Modifier.FINAL;\r\n for (Method method : methods) {\r\n if ((method.getModifiers() & mask) == Opcodes.ACC_PUBLIC) {\r\n if (method.getParameterTypes().length == 0 && !method.getName().equals(\"\") && !method.getName().equals(\"\") && method.getReturnType() != void.class) {\r\n addToMapping(method, currentFieldIndex());\r\n } else if (method.getParameterTypes().length == 1 && method.getName().startsWith(\"set\")) {\r\n addToMapping(method, currentFieldIndex());\r\n }\r\n }\r\n }\r\n final List flds = Arrays.asList(clazz.getFields());\r\n Collections.sort(flds, Comparator.comparing(Field::getName));\r\n for (Field fld : flds) {\r\n if (!Modifier.isStatic(fld.getModifiers()) && !fieldNames.containsKey(fld.getName())) {\r\n this.fieldNames.put(fld.getName(), currentFieldIndex());\r\n this.fieldTypes.put(fld.getName(), fld.getType());\r\n this.fieldTypesField.put(fld.getName(), fld);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void validateServiceConfigurations(SimpleNotificationEndpoint simpleNotificationEndpoint, Exchange exchange, ClientConfigurations clientConfigurations){\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Inspecting exchange body\");\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getMessage().getBody())) {\r\n if (simpleNotificationEndpoint.getOperation().equals(\"publishAsTextMessage\")) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Found null/empty body. Cannot perform publish as text operation\");\r\n }\r\n throw new IllegalArgumentException(\"exchange body cannot be null / empty\");\r\n }\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Inspecting operation name\");\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.SMN_OPERATION)) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getOperation())) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Found null/empty operation name. Cannot proceed with Smn operations\");\r\n }\r\n throw new IllegalArgumentException(\"operation name not found\");\r\n } else {\r\n clientConfigurations.setOperation(exchange.getProperty(SmnProperties.SMN_OPERATION) != null ? (String) exchange.getProperty(SmnProperties.SMN_OPERATION) : simpleNotificationEndpoint.getOperation());\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Inspecting topic name\");\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME))) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Found null/empty topic name\");\r\n }\r\n throw new IllegalArgumentException(\"topic name not found\");\r\n } else {\r\n clientConfigurations.setTopicUrn(String.format(SmnConstants.TOPIC_URN_FORMAT, simpleNotificationEndpoint.getRegion(), simpleNotificationEndpoint.getProjectId(), exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME)));\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Inspecting notification subject value\");\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT))) {\r\n if (LOG.isWarnEnabled()) {\r\n LOG.warn(\"notification subject not found. defaulting to 'DEFAULT_SUBJECT'\");\r\n }\r\n clientConfigurations.setSubject(\"DEFAULT_SUBJECT\");\r\n } else {\r\n clientConfigurations.setSubject((String) exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT));\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Inspecting TTL\");\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TTL))) {\r\n if (LOG.isWarnEnabled()) {\r\n LOG.warn(\"TTL not found. defaulting to default value {}\", simpleNotificationEndpoint.getMessageTtl());\r\n }\r\n clientConfigurations.setMessageTtl(simpleNotificationEndpoint.getMessageTtl());\r\n } else {\r\n clientConfigurations.setMessageTtl((int) exchange.getProperty(SmnProperties.NOTIFICATION_TTL));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private GenericKieSessionMonitoringImpl getKnowledgeSessionBean(CBSKey cbsKey, KieRuntimeEventManager ksession){\r\n if (mbeansRefs.get(cbsKey) != null) {\r\n return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey);\r\n } else {\r\n if (ksession instanceof StatelessKieSession) {\r\n synchronized (mbeansRefs) {\r\n if (mbeansRefs.get(cbsKey) != null) {\r\n return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey);\r\n } else {\r\n try {\r\n GenericKieSessionMonitoringImpl mbean = RuntimeComponentFactory.get().createStatelessSessionMonitor(cbsKey);\r\n registerMBean(cbsKey, mbean, mbean.getName());\r\n mbeansRefs.put(cbsKey, mbean);\r\n return mbean;\r\n } catch (Exception e) {\r\n logger.error(\"Unable to instantiate and register StatelessKieSessionMonitoringMBean\");\r\n }\r\n return null;\r\n }\r\n }\r\n } else {\r\n synchronized (mbeansRefs) {\r\n if (mbeansRefs.get(cbsKey) != null) {\r\n return (GenericKieSessionMonitoringImpl) mbeansRefs.get(cbsKey);\r\n } else {\r\n try {\r\n GenericKieSessionMonitoringImpl mbean = RuntimeComponentFactory.get().createStatefulSessionMonitor(cbsKey);\r\n registerMBean(cbsKey, mbean, mbean.getName());\r\n mbeansRefs.put(cbsKey, mbean);\r\n return mbean;\r\n } catch (Exception e) {\r\n logger.error(\"Unable to instantiate and register (stateful) KieSessionMonitoringMBean\");\r\n }\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void appendBytesAsPrintFriendlyString(StringBuilder builder, byte[] phiBytes, int startPosition, int endPosition){\r\n if (builder == null) {\r\n throw new IllegalArgumentException(\"StringBuilder cannot be null\");\r\n }\r\n if (null == phiBytes) {\r\n builder.append(NULL_REPLACEMENT_VALUE);\r\n } else if (phiBytes.length == 0) {\r\n builder.append(EMPTY_REPLACEMENT_VALUE);\r\n } else if (startPosition <= endPosition) {\r\n if (startPosition < 0) {\r\n startPosition = 0;\r\n }\r\n if (startPosition < phiBytes.length) {\r\n if (endPosition >= -1) {\r\n if (endPosition == -1 || endPosition >= phiBytes.length) {\r\n endPosition = phiBytes.length;\r\n }\r\n int length = endPosition - startPosition;\r\n if (length > 0) {\r\n int conversionLength = (logPhiMaxBytes > 0) ? Integer.min(length, logPhiMaxBytes) : length;\r\n if (builder.capacity() - builder.length() < conversionLength + STRING_BUFFER_PAD_SIZE) {\r\n builder.ensureCapacity(builder.length() + conversionLength + STRING_BUFFER_PAD_SIZE);\r\n }\r\n for (int i = 0; i < conversionLength; ++i) {\r\n appendCharacterAsPrintFriendlyString(builder, (char) phiBytes[startPosition + i]);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String asParsedExpr(){\r\n List operands = getOperands();\r\n if (operators.isEmpty()) {\r\n return operands.get(0).asParsedExpr();\r\n } else {\r\n StringBuffer sbuff = new StringBuffer();\r\n for (int i = operators.size() - 1; i >= 0; --i) {\r\n sbuff.append(\"(\");\r\n sbuff.append(operators.get(i).getText());\r\n sbuff.append(\" \");\r\n }\r\n for (int i = 0; i < operators.size() + 1; ++i) {\r\n if (i < operands.size()) {\r\n sbuff.append(operands.get(i).asParsedExpr());\r\n } else {\r\n sbuff.append(\"?\");\r\n }\r\n if (i != 0) {\r\n sbuff.append(\")\");\r\n }\r\n if (i < operators.size()) {\r\n sbuff.append(\" \");\r\n }\r\n }\r\n return sbuff.toString();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List readSection(BufferedReader bufferedReader){\r\n List section = new ArrayList<>();\r\n String line;\r\n String currKey = null;\r\n StringBuilder currVal = new StringBuilder();\r\n boolean done = false;\r\n int linecount = 0;\r\n try {\r\n while (!done) {\r\n bufferedReader.mark(320);\r\n line = bufferedReader.readLine();\r\n String firstSecKey = section.isEmpty() ? \"\" : section.get(0)[0];\r\n if (line != null && line.matches(\"\\\\p{Space}*\")) {\r\n continue;\r\n }\r\n if (line == null || (!line.startsWith(\" \") && linecount++ > 0 && (!firstSecKey.equals(START_SEQUENCE_TAG) || line.startsWith(END_SEQUENCE_TAG)))) {\r\n section.add(new String[] { currKey, currVal.toString() });\r\n bufferedReader.reset();\r\n done = true;\r\n } else {\r\n Matcher m = sectp.matcher(line);\r\n if (m.matches()) {\r\n if (currKey != null) {\r\n section.add(new String[] { currKey, currVal.toString() });\r\n }\r\n currKey = m.group(2) == null ? (m.group(4) == null ? m.group(6) : m.group(4)) : m.group(2);\r\n currVal = new StringBuilder();\r\n currVal.append((m.group(2) == null ? (m.group(4) == null ? \"\" : m.group(5)) : m.group(3)).trim());\r\n } else {\r\n if (line.startsWith(START_SEQUENCE_TAG) || line.startsWith(END_SEQUENCE_TAG)) {\r\n currKey = line;\r\n } else {\r\n currVal.append(\"\\n\");\r\n currVal.append(currKey.charAt(0) == '/' ? line.substring(21) : line.substring(12));\r\n }\r\n }\r\n }\r\n }\r\n } catch (IOException | RuntimeException e) {\r\n throw new ParserException(e.getMessage());\r\n }\r\n return section;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode convertOver(Blackboard bb, SqlNode node){\r\n SqlCall call = (SqlCall) node;\r\n SqlCall aggCall = call.operand(0);\r\n boolean ignoreNulls = false;\r\n switch(aggCall.getKind()) {\r\n case IGNORE_NULLS:\r\n ignoreNulls = true;\r\n case RESPECT_NULLS:\r\n aggCall = aggCall.operand(0);\r\n break;\r\n default:\r\n break;\r\n }\r\n SqlNode windowOrRef = call.operand(1);\r\n final SqlWindow window = validator().resolveWindow(windowOrRef, bb.scope);\r\n SqlNode sqlLowerBound = window.getLowerBound();\r\n SqlNode sqlUpperBound = window.getUpperBound();\r\n boolean rows = window.isRows();\r\n SqlNodeList orderList = window.getOrderList();\r\n if (!aggCall.getOperator().allowsFraming()) {\r\n sqlLowerBound = SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO);\r\n sqlUpperBound = SqlWindow.createCurrentRow(SqlParserPos.ZERO);\r\n if (aggCall.getKind() == SqlKind.ROW_NUMBER) {\r\n rows = true;\r\n }\r\n } else if (orderList.size() == 0) {\r\n sqlLowerBound = SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO);\r\n sqlUpperBound = SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO);\r\n } else if (sqlLowerBound == null && sqlUpperBound == null) {\r\n sqlLowerBound = SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO);\r\n sqlUpperBound = SqlWindow.createCurrentRow(SqlParserPos.ZERO);\r\n } else if (sqlUpperBound == null) {\r\n sqlUpperBound = SqlWindow.createCurrentRow(SqlParserPos.ZERO);\r\n } else if (sqlLowerBound == null) {\r\n sqlLowerBound = SqlWindow.createCurrentRow(SqlParserPos.ZERO);\r\n }\r\n final SqlNodeList partitionList = window.getPartitionList();\r\n final ImmutableList.Builder partitionKeys = ImmutableList.builder();\r\n for (SqlNode partition : partitionList) {\r\n validator().deriveType(bb.scope, partition);\r\n partitionKeys.add(bb.convertExpression(partition));\r\n }\r\n final RexNode lowerBound = bb.convertExpression(requireNonNull(sqlLowerBound, \"sqlLowerBound\"));\r\n final RexNode upperBound = bb.convertExpression(requireNonNull(sqlUpperBound, \"sqlUpperBound\"));\r\n if (orderList.size() == 0 && !rows) {\r\n orderList = bb.scope.getOrderList();\r\n if (orderList == null) {\r\n throw new AssertionError(\"Relation should have sort key for implicit ORDER BY\");\r\n }\r\n }\r\n final ImmutableList.Builder orderKeys = ImmutableList.builder();\r\n for (SqlNode order : orderList) {\r\n orderKeys.add(bb.convertSortExpression(order, RelFieldCollation.Direction.ASCENDING, RelFieldCollation.NullDirection.UNSPECIFIED, bb::sortToRex));\r\n }\r\n try {\r\n checkArgument(bb.window == null, \"already in window agg mode\");\r\n bb.window = window;\r\n RexNode rexAgg = exprConverter.convertCall(bb, aggCall);\r\n rexAgg = rexBuilder.ensureType(validator().getValidatedNodeType(call), rexAgg, false);\r\n final SqlLiteral q = aggCall.getFunctionQuantifier();\r\n final boolean isDistinct = q != null && q.getValue() == SqlSelectKeyword.DISTINCT;\r\n final RexShuttle visitor = new HistogramShuttle(partitionKeys.build(), orderKeys.build(), rows, RexWindowBounds.create(sqlLowerBound, lowerBound), RexWindowBounds.create(sqlUpperBound, upperBound), window.isAllowPartial(), isDistinct, ignoreNulls);\r\n return rexAgg.accept(visitor);\r\n } finally {\r\n bb.window = null;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected final void appendOperands(StringBuilder sb){\r\n if (operands.isEmpty()) {\r\n return;\r\n }\r\n List operandDigests = new ArrayList<>(operands.size());\r\n for (int i = 0; i < operands.size(); i++) {\r\n RexNode operand = operands.get(i);\r\n if (!(operand instanceof RexLiteral)) {\r\n operandDigests.add(operand.toString());\r\n continue;\r\n }\r\n RexDigestIncludeType includeType = RexDigestIncludeType.OPTIONAL;\r\n if ((isA(SqlKind.AND) || isA(SqlKind.OR)) && operand.getType().getSqlTypeName() == SqlTypeName.BOOLEAN) {\r\n includeType = RexDigestIncludeType.NO_TYPE;\r\n }\r\n if (SqlKind.SIMPLE_BINARY_OPS.contains(getKind())) {\r\n RexNode otherArg = operands.get(1 - i);\r\n if ((!(otherArg instanceof RexLiteral) || digestSkipsType((RexLiteral) otherArg)) && SqlTypeUtil.equalSansNullability(operand.getType(), otherArg.getType())) {\r\n includeType = RexDigestIncludeType.NO_TYPE;\r\n }\r\n }\r\n operandDigests.add(computeDigest((RexLiteral) operand, includeType));\r\n }\r\n int totalLength = (operandDigests.size() - 1) * 2;\r\n for (String s : operandDigests) {\r\n totalLength += s.length();\r\n }\r\n sb.ensureCapacity(sb.length() + totalLength);\r\n for (int i = 0; i < operandDigests.size(); i++) {\r\n String op = operandDigests.get(i);\r\n if (i != 0) {\r\n sb.append(\", \");\r\n }\r\n sb.append(op);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List downloadAllegatoById_Doqui(Integer id){\r\n if (id == null)\r\n throw new IllegalArgumentException(\"id non valorizzato\");\r\n CnmTAllegato cnmTAllegato = cnmTAllegatoRepository.findOne(id);\r\n cnmTAllegato = validateRequestAllegato(cnmTAllegato);\r\n if (cnmTAllegato.getIdIndex() != null) {\r\n ResponseRicercaAllegato responseIndex = doquiServiceFacade.recuperaDocumentoIndex(cnmTAllegato.getIdIndex(), cnmTAllegato.getCnmDTipoAllegato().getIndexType());\r\n if (responseIndex != null && responseIndex.getDocumento() != null && responseIndex.getDocumento().getFile() != null) {\r\n List response = new ArrayList();\r\n DocumentoScaricatoVO doc = new DocumentoScaricatoVO();\r\n doc.setFile(responseIndex.getDocumento().getFile());\r\n response.add(doc);\r\n return response;\r\n } else {\r\n throw new RuntimeException(\"documento non trovato su index\");\r\n }\r\n } else if (cnmTAllegato.getIdActa() != null) {\r\n ResponseRicercaDocumentoMultiplo response = doquiServiceFacade.recuperaDocumentoActa(cnmTAllegato.getIdActa());\r\n if (response != null && response.getSottoDocumenti() != null) {\r\n if (Constants.DOCUMENTI_CREATI_DA_CONAM.contains(cnmTAllegato.getCnmDTipoAllegato().getIdTipoAllegato()) && !cnmTAllegato.isFlagDocumentoPregresso()) {\r\n for (int i = 0; i < response.getSottoDocumenti().size(); i++) {\r\n Documento doc = response.getSottoDocumenti().get(i);\r\n doc.setFile(addProtocolloToDocument(doc.getFile(), cnmTAllegato.getNumeroProtocollo(), cnmTAllegato.getCnmDTipoAllegato().getIdTipoAllegato()));\r\n response.getSottoDocumenti().set(i, doc);\r\n }\r\n }\r\n List docScaricatoVOList = new ArrayList();\r\n for (Documento doc : response.getSottoDocumenti()) {\r\n DocumentoScaricatoVO docScaricatoVO = new DocumentoScaricatoVO();\r\n docScaricatoVO.setFile(doc.getFile());\r\n docScaricatoVO.setNomeFile(doc.getNomeFile());\r\n docScaricatoVO.setObjectIdDocumentoFisico(doc.getObjectIdDocumentoFisico());\r\n docScaricatoVOList.add(docScaricatoVO);\r\n }\r\n return docScaricatoVOList;\r\n } else {\r\n throw new RuntimeException(\"documento non trovato su acta per parola chiave\");\r\n }\r\n } else if (cnmTAllegato.getObjectidSpostamentoActa() != null) {\r\n List response = downloadAllegatoByObjectIdDocumento(cnmTAllegato.getObjectidSpostamentoActa());\r\n if (response != null) {\r\n return response;\r\n } else {\r\n throw new RuntimeException(\"documento non trovato su acta per objectIdDocumento\");\r\n }\r\n } else {\r\n throw new RuntimeException(\"idIndex, idActa e objectIdSpostamentoActa non valorizzati\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean locateAllRefs(){\r\n RexUtil.apply(new InputSpecialOpFinder(projRefs, childBitmap, rightBitmap, requireNonNull(strongBitmap, \"strongBitmap\"), preserveExprCondition, childPreserveExprs, rightPreserveExprs), origProjExprs, origFilter);\r\n projRefs.set(nSysFields, nSysFields + nSysFields, true);\r\n projRefs.set(nSysFields + nFields, nSysFields + nFields + nSysFields, true);\r\n nSystemProject = 0;\r\n nProject = 0;\r\n nRightProject = 0;\r\n for (int bit : BitSets.toIter(projRefs)) {\r\n if (bit < nSysFields) {\r\n nSystemProject++;\r\n } else if (bit < nSysFields + nFields) {\r\n nProject++;\r\n } else {\r\n nRightProject++;\r\n }\r\n }\r\n assert nSystemProject + nProject + nRightProject == projRefs.cardinality();\r\n if ((childRel instanceof Join) || (childRel instanceof SetOp)) {\r\n if ((nProject == 0) && (childPreserveExprs.size() == 0)) {\r\n projRefs.set(0);\r\n nProject = 1;\r\n }\r\n if (childRel instanceof Join) {\r\n if ((nRightProject == 0) && (rightPreserveExprs.size() == 0)) {\r\n projRefs.set(nFields);\r\n nRightProject = 1;\r\n }\r\n }\r\n }\r\n boolean allFieldsReferenced = IntStream.range(0, nChildFields).allMatch(i -> projRefs.get(i));\r\n if (allFieldsReferenced && childPreserveExprs.size() == 0 && rightPreserveExprs.size() == 0) {\r\n return true;\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List> splitAndRegroupMeasurements(Map measurementGroupMap){\r\n List> result = new ArrayList<>();\r\n int tmpSum = 0;\r\n Map tmpMap = new HashMap<>();\r\n for (Map.Entry entry : measurementGroupMap.entrySet()) {\r\n if (entry.getValue().size() > SPLIT_SIZE) {\r\n for (MeasurementGroup splitMeasurementGroup : entry.getValue().split(SPLIT_SIZE)) {\r\n if (splitMeasurementGroup.size() == SPLIT_SIZE) {\r\n Map singletonMap = new HashMap<>();\r\n singletonMap.put(entry.getKey(), splitMeasurementGroup);\r\n result.add(singletonMap);\r\n } else {\r\n if (tmpSum + splitMeasurementGroup.size() > SPLIT_SIZE) {\r\n result.add(tmpMap);\r\n tmpMap = new HashMap<>();\r\n tmpSum = 0;\r\n }\r\n tmpSum += splitMeasurementGroup.size();\r\n tmpMap.put(entry.getKey(), splitMeasurementGroup);\r\n }\r\n }\r\n } else {\r\n if (tmpSum + entry.getValue().size() > SPLIT_SIZE) {\r\n result.add(tmpMap);\r\n tmpMap = new HashMap<>();\r\n tmpSum = 0;\r\n }\r\n tmpSum += entry.getValue().size();\r\n tmpMap.put(entry.getKey(), entry.getValue());\r\n }\r\n }\r\n if (!tmpMap.isEmpty()) {\r\n result.add(tmpMap);\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static AliasMap newAliasMap(@NonNull final Supplier> mapFactory){\r\n return new AliasMap() {\r\n\r\n final Map delegate = mapFactory.get();\r\n\r\n @Override\r\n public int size() {\r\n return delegate.size();\r\n }\r\n\r\n @Override\r\n public boolean isEmpty() {\r\n return delegate.isEmpty();\r\n }\r\n\r\n @Override\r\n public boolean containsValue(final Object value) {\r\n return delegate.containsValue(value);\r\n }\r\n\r\n @Override\r\n public Set keySet() {\r\n return delegate.keySet();\r\n }\r\n\r\n @Override\r\n public Collection values() {\r\n return delegate.values();\r\n }\r\n\r\n @Override\r\n public Set> entrySet() {\r\n return delegate.entrySet();\r\n }\r\n\r\n @Override\r\n public V put(final K key, final V value) {\r\n return this.put(key, Can.empty(), value);\r\n }\r\n\r\n @Override\r\n public void putAll(final Map other) {\r\n if (!_NullSafe.isEmpty(other)) {\r\n other.forEach((k, v) -> this.put(k, v));\r\n }\r\n }\r\n\r\n @Override\r\n public V put(final K key, final Can aliases, final V value) {\r\n putAliasKeys(key, aliases, false);\r\n return delegate.put(key, value);\r\n }\r\n\r\n @Override\r\n public V remap(final K key, final Can aliases, final V value) {\r\n putAliasKeys(key, aliases, true);\r\n return delegate.put(key, value);\r\n }\r\n\r\n @Override\r\n public boolean containsKey(final Object keyOrAliasKey) {\r\n return delegate.containsKey(keyOrAliasKey) || containsAliasKey(keyOrAliasKey);\r\n }\r\n\r\n @Override\r\n public V get(final Object keyOrAliasKey) {\r\n val v = delegate.get(keyOrAliasKey);\r\n if (v != null) {\r\n return v;\r\n }\r\n return getByAliasKey(keyOrAliasKey);\r\n }\r\n\r\n @Override\r\n public V remove(final Object key) {\r\n removeAliasKeysOf(key);\r\n return delegate.remove(key);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n delegate.clear();\r\n clearAliasKeys();\r\n }\r\n\r\n private final Map> pairByAliasKey = _Maps.newHashMap();\r\n\r\n private void putAliasKeys(final K key, final Can aliasKeys, final boolean remap) {\r\n if (aliasKeys.isNotEmpty()) {\r\n val keyPair = KeyPair.of(key, aliasKeys);\r\n for (val aliasKey : aliasKeys) {\r\n val existingKeyPair = pairByAliasKey.put(aliasKey, keyPair);\r\n if (existingKeyPair != null && !remap) {\r\n throw _Exceptions.illegalArgument(\"alias key collision on alias %s: existing-key=%s, new-key=%s\", aliasKey, existingKeyPair.key, keyPair.key);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private V getByAliasKey(final Object aliasKey) {\r\n val keyPair = pairByAliasKey.get(aliasKey);\r\n if (keyPair != null) {\r\n return delegate.get(keyPair.getKey());\r\n }\r\n return null;\r\n }\r\n\r\n private boolean containsAliasKey(final Object aliasKey) {\r\n return pairByAliasKey.containsKey(aliasKey);\r\n }\r\n\r\n private void removeAliasKeysOf(final Object key) {\r\n pairByAliasKey.entrySet().removeIf(entry -> {\r\n val keyPair = entry.getValue();\r\n return keyPair.getKey().equals(key);\r\n });\r\n }\r\n\r\n private void clearAliasKeys() {\r\n pairByAliasKey.clear();\r\n }\r\n };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int parseNumericTemporal(String substring, Token token){\r\n checkFormatExact(substring, token);\r\n if (token.temporalField == ChronoField.AMPM_OF_DAY) {\r\n return substring.toLowerCase().startsWith(\"a\") ? AM : PM;\r\n }\r\n if (token.temporalField == ChronoField.HOUR_OF_AMPM) {\r\n if (\"12\".equals(substring)) {\r\n return 0;\r\n }\r\n if (\"0\".equals(substring)) {\r\n throw new IllegalArgumentException(\"Value of hour of day (hh/hh12) in input is 0. \" + \"The value should be between 1 and 12.\");\r\n }\r\n }\r\n if (token.temporalField == ChronoField.YEAR || token.temporalField == IsoFields.WEEK_BASED_YEAR) {\r\n String currentYearString;\r\n if (token.temporalField == ChronoField.YEAR) {\r\n currentYearString = Integer.toString(this.now.or(LocalDateTime.now()).getYear());\r\n } else {\r\n currentYearString = Integer.toString(this.now.or(LocalDateTime.now()).get(IsoFields.WEEK_BASED_YEAR));\r\n }\r\n if (token.string.startsWith(\"r\") && substring.length() == 2) {\r\n int currFirst2Digits = Integer.parseInt(currentYearString.substring(0, 2));\r\n int currLast2Digits = Integer.parseInt(currentYearString.substring(2));\r\n int valLast2Digits = Integer.parseInt(substring);\r\n if (valLast2Digits < 50 && currLast2Digits >= 50) {\r\n currFirst2Digits += 1;\r\n } else if (valLast2Digits >= 50 && currLast2Digits < 50) {\r\n currFirst2Digits -= 1;\r\n }\r\n substring = Integer.toString(currFirst2Digits) + substring;\r\n } else {\r\n substring = currentYearString.substring(0, 4 - substring.length()) + substring;\r\n }\r\n } else if (token.temporalField == ChronoField.NANO_OF_SECOND) {\r\n int i = Integer.min(token.length, substring.length());\r\n substring += StringUtils.repeat(\"0\", NANOS_MAX_LENGTH - i);\r\n }\r\n try {\r\n return Integer.parseInt(substring);\r\n } catch (NumberFormatException e) {\r\n throw new IllegalArgumentException(\"Couldn't parse substring \\\"\" + substring + \"\\\" with token \" + token + \" to integer. Pattern is \" + pattern, e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List validateMissingBalResources(List operations, Map resources){\r\n boolean filterEnable = filter.getOperation() != null || filter.getTag() != null || filter.getExcludeTag() != null || filter.getExcludeOperation() != null;\r\n Iterator openAPIPathIterator = operations.iterator();\r\n while (openAPIPathIterator.hasNext()) {\r\n OpenAPIPathSummary operationPath = openAPIPathIterator.next();\r\n if (!resources.containsKey(operationPath.getPath())) {\r\n if (!filterEnable) {\r\n reportDiagnostic(context, CompilationError.MISSING_RESOURCE_PATH, context.node().location(), filter.getKind(), getNormalizedPath(operationPath.getPath()));\r\n }\r\n openAPIPathIterator.remove();\r\n } else {\r\n ResourcePathSummary resourcePath = resources.get(operationPath.getPath());\r\n Map resourceMethods = resourcePath.getMethods();\r\n Map methods = operationPath.getOperations();\r\n for (Map.Entry operation : methods.entrySet()) {\r\n if (!resourceMethods.containsKey(operation.getKey().trim())) {\r\n if (!filterEnable) {\r\n reportDiagnostic(context, CompilationError.MISSING_RESOURCE_FUNCTION, context.node().location(), filter.getKind(), operation.getKey().trim(), getNormalizedPath(operationPath.getPath()));\r\n }\r\n methods.remove(operation.getKey());\r\n }\r\n }\r\n }\r\n }\r\n return operations;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode simplifyCase(RexCall call, RexUnknownAs unknownAs){\r\n List inputBranches = CaseBranch.fromCaseOperands(rexBuilder, new ArrayList<>(call.getOperands()));\r\n RexSimplify condSimplifier = this.withPredicates(RelOptPredicateList.EMPTY);\r\n RexSimplify valueSimplifier = this;\r\n RelDataType caseType = call.getType();\r\n boolean conditionNeedsSimplify = false;\r\n CaseBranch lastBranch = null;\r\n List branches = new ArrayList<>();\r\n for (CaseBranch inputBranch : inputBranches) {\r\n RexNode newCond = condSimplifier.simplify(inputBranch.cond, RexUnknownAs.FALSE);\r\n if (newCond.isAlwaysFalse()) {\r\n continue;\r\n }\r\n RexNode newValue = valueSimplifier.simplify(inputBranch.value, unknownAs);\r\n if (lastBranch != null) {\r\n if (lastBranch.value.equals(newValue) && isSafeExpression(newCond)) {\r\n newCond = rexBuilder.makeCall(SqlStdOperatorTable.OR, lastBranch.cond, newCond);\r\n conditionNeedsSimplify = true;\r\n } else {\r\n CaseBranch branch = generateBranch(conditionNeedsSimplify, condSimplifier, lastBranch);\r\n if (!branch.cond.isAlwaysFalse()) {\r\n branches.add(branch);\r\n if (branch.cond.isAlwaysTrue()) {\r\n lastBranch = null;\r\n break;\r\n }\r\n }\r\n conditionNeedsSimplify = false;\r\n }\r\n }\r\n lastBranch = new CaseBranch(newCond, newValue);\r\n if (newCond.isAlwaysTrue()) {\r\n break;\r\n }\r\n }\r\n if (lastBranch != null) {\r\n CaseBranch branch = generateBranch(conditionNeedsSimplify, condSimplifier, lastBranch);\r\n if (!branch.cond.isAlwaysFalse()) {\r\n branches.add(branch);\r\n }\r\n }\r\n if (branches.size() == 1) {\r\n final RexNode value = branches.get(0).value;\r\n if (sameTypeOrNarrowsNullability(caseType, value.getType())) {\r\n return value;\r\n } else {\r\n return rexBuilder.makeAbstractCast(caseType, value, false);\r\n }\r\n }\r\n if (call.getType().getSqlTypeName() == SqlTypeName.BOOLEAN) {\r\n final RexNode result = simplifyBooleanCase(rexBuilder, branches, unknownAs, caseType);\r\n if (result != null) {\r\n if (sameTypeOrNarrowsNullability(caseType, result.getType())) {\r\n return simplify(result, unknownAs);\r\n } else {\r\n RexNode simplified = simplify(result, UNKNOWN);\r\n if (!simplified.getType().isNullable()) {\r\n return simplified;\r\n } else {\r\n return rexBuilder.makeCast(call.getType(), simplified);\r\n }\r\n }\r\n }\r\n }\r\n List newOperands = CaseBranch.toCaseOperands(branches);\r\n if (newOperands.equals(call.getOperands())) {\r\n return call;\r\n }\r\n return rexBuilder.makeCall(SqlStdOperatorTable.CASE, newOperands);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void updateTabTitle(boolean isChanged){\r\n boolean isAutosaveEnabled = preferencesService.getLibraryPreferences().shouldAutoSave();\r\n DatabaseLocation databaseLocation = bibDatabaseContext.getLocation();\r\n Optional file = bibDatabaseContext.getDatabasePath();\r\n StringBuilder tabTitle = new StringBuilder();\r\n StringBuilder toolTipText = new StringBuilder();\r\n if (file.isPresent()) {\r\n if (isChanged && !isAutosaveEnabled) {\r\n tabTitle.append('*');\r\n }\r\n Path databasePath = file.get();\r\n String fileName = databasePath.getFileName().toString();\r\n tabTitle.append(fileName);\r\n toolTipText.append(databasePath.toAbsolutePath().toString());\r\n if (databaseLocation == DatabaseLocation.SHARED) {\r\n tabTitle.append(\" \\u2013 \");\r\n addSharedDbInformation(tabTitle, bibDatabaseContext);\r\n toolTipText.append(' ');\r\n addSharedDbInformation(toolTipText, bibDatabaseContext);\r\n }\r\n addModeInfo(toolTipText, bibDatabaseContext);\r\n if (isChanged && !isAutosaveEnabled) {\r\n addChangedInformation(toolTipText, fileName);\r\n }\r\n Optional uniquePathPart = FileUtil.getUniquePathDirectory(stateManager.collectAllDatabasePaths(), databasePath);\r\n uniquePathPart.ifPresent(part -> tabTitle.append(\" \\u2013 \").append(part));\r\n } else {\r\n if (databaseLocation == DatabaseLocation.LOCAL) {\r\n tabTitle.append(Localization.lang(\"untitled\"));\r\n if (bibDatabaseContext.getDatabase().hasEntries()) {\r\n tabTitle.append('*');\r\n }\r\n } else {\r\n addSharedDbInformation(tabTitle, bibDatabaseContext);\r\n addSharedDbInformation(toolTipText, bibDatabaseContext);\r\n }\r\n addModeInfo(toolTipText, bibDatabaseContext);\r\n if ((databaseLocation == DatabaseLocation.LOCAL) && bibDatabaseContext.getDatabase().hasEntries()) {\r\n addChangedInformation(toolTipText, Localization.lang(\"untitled\"));\r\n }\r\n }\r\n DefaultTaskExecutor.runInJavaFXThread(() -> {\r\n textProperty().setValue(tabTitle.toString());\r\n setTooltip(new Tooltip(toolTipText.toString()));\r\n });\r\n if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) {\r\n indexingTaskManager.updateDatabaseName(tabTitle.toString());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readNextBlock() throws IOException{\r\n verifyLastChecksumAndReset();\r\n inUncompressedChunk = false;\r\n final int type = readOneByte();\r\n if (type == -1) {\r\n endReached = true;\r\n } else if (type == STREAM_IDENTIFIER_TYPE) {\r\n inputStream.unread(type);\r\n unreadBytes++;\r\n pushedBackBytes(1);\r\n readStreamIdentifier();\r\n readNextBlock();\r\n } else if (type == PADDING_CHUNK_TYPE || (type > MAX_UNSKIPPABLE_TYPE && type <= MAX_SKIPPABLE_TYPE)) {\r\n skipBlock();\r\n readNextBlock();\r\n } else if (type >= MIN_UNSKIPPABLE_TYPE && type <= MAX_UNSKIPPABLE_TYPE) {\r\n throw new IOException(\"Unskippable chunk with type \" + type + \" (hex \" + Integer.toHexString(type) + \")\" + \" detected.\");\r\n } else if (type == UNCOMPRESSED_CHUNK_TYPE) {\r\n inUncompressedChunk = true;\r\n uncompressedBytesRemaining = readSize() - 4;\r\n if (uncompressedBytesRemaining < 0) {\r\n throw new IOException(\"Found illegal chunk with negative size\");\r\n }\r\n expectedChecksum = unmask(readCrc());\r\n } else if (type == COMPRESSED_CHUNK_TYPE) {\r\n final boolean expectChecksum = dialect.usesChecksumWithCompressedChunks();\r\n final long size = readSize() - (expectChecksum ? 4L : 0L);\r\n if (size < 0) {\r\n throw new IOException(\"Found illegal chunk with negative size\");\r\n }\r\n if (expectChecksum) {\r\n expectedChecksum = unmask(readCrc());\r\n } else {\r\n expectedChecksum = -1;\r\n }\r\n currentCompressedChunk = new SnappyCompressorInputStream(new BoundedInputStream(inputStream, size), blockSize);\r\n count(currentCompressedChunk.getBytesRead());\r\n } else {\r\n throw new IOException(\"Unknown chunk type \" + type + \" detected.\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean waitUntilRegNodeExpired(String regPath, long leaseId) throws MetadataStoreException{\r\n ByteSequence regPathBs = ByteSequence.from(regPath, UTF_8);\r\n GetResponse getResp = msResult(kvClient.get(regPathBs));\r\n if (getResp.getCount() <= 0) {\r\n return false;\r\n } else {\r\n KeyValue kv = getResp.getKvs().get(0);\r\n if (kv.getLease() != leaseId) {\r\n Watch watchClient = client.getWatchClient();\r\n final CompletableFuture watchFuture = new CompletableFuture<>();\r\n Watcher watcher = watchClient.watch(regPathBs, WatchOption.newBuilder().withRevision(getResp.getHeader().getRevision() + 1).build(), response -> {\r\n for (WatchEvent event : response.getEvents()) {\r\n log.info(\"Received watch event on '{}' : EventType = {}, lease {}\", regPath, event.getEventType(), leaseId);\r\n if (EventType.DELETE == event.getEventType()) {\r\n watchFuture.complete(null);\r\n return;\r\n }\r\n }\r\n }, exception -> {\r\n log.warn(\"Exception in keepAlive for watch event on {}, lease {}\", regPath, leaseId, exception);\r\n watchFuture.completeExceptionally(new UncheckedExecutionException(\"Interrupted at waiting previous registration under \" + regPath + \" (lease = \" + kv.getLease() + \") to be expired\", exception));\r\n });\r\n log.info(\"Previous bookie registration (lease = {}) still exists at {}, \" + \"so new lease '{}' will be waiting previous lease for {} seconds to be expired\", kv.getLease(), regPath, leaseId, bkRegister.getTtlSeconds());\r\n try {\r\n msResult(watchFuture, 2 * bkRegister.getTtlSeconds(), TimeUnit.SECONDS);\r\n return false;\r\n } catch (TimeoutException e) {\r\n watchFuture.cancel(true);\r\n throw new MetadataStoreException(\"Previous bookie registration still exists at \" + regPath + \" (lease = \" + kv.getLease() + \") after \" + (2 * bkRegister.getTtlSeconds()) + \" seconds elapsed\");\r\n } catch (UncheckedExecutionException uee) {\r\n throw new MetadataStoreException(uee.getMessage(), uee.getCause());\r\n } finally {\r\n watcher.close();\r\n }\r\n } else {\r\n return true;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void tracciaSuCsiLogAudit(Map protocolliGestiti, CnmTAllegato cnmTAllegatoTs, List objectIdDocumentoToTraceList){\r\n if (objectIdDocumentoToTraceList != null) {\r\n for (String idToTrace : objectIdDocumentoToTraceList) {\r\n if (Constants.OPERAZIONE_COPIA_INCOLLA.equals(protocolliGestiti.get(cnmTAllegatoTs.getNumeroProtocollo()))) {\r\n if (cnmTAllegatoTs.isFlagDocumentoPregresso())\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(TraceOperation.INSERIMENTO_ALLEGATO_PREGRESSO_CI.getOperation(), Constants.OGGETTO_ACTA, \"objectIdDocumento=\" + idToTrace, Thread.currentThread().getStackTrace()[1].getMethodName(), \"copiaDocumentoSuNuovaStruttura\");\r\n else\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(TraceOperation.INSERIMENTO_ALLEGATO_CI.getOperation(), Constants.OGGETTO_ACTA, \"objectIdDocumento=\" + idToTrace, Thread.currentThread().getStackTrace()[1].getMethodName(), \"copiaDocumentoSuNuovaStruttura\");\r\n } else if (Constants.OPERAZIONE_TAGLIA_INCOLLA.equals(protocolliGestiti.get(cnmTAllegatoTs.getNumeroProtocollo()))) {\r\n if (cnmTAllegatoTs.isFlagDocumentoPregresso())\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(TraceOperation.INSERIMENTO_ALLEGATO_PREGRESSO_TI.getOperation(), Constants.OGGETTO_ACTA, \"objectIdDocumento=\" + idToTrace, Thread.currentThread().getStackTrace()[1].getMethodName(), \"spostaDocumentoSuNuovaStruttura\");\r\n else\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(TraceOperation.INSERIMENTO_ALLEGATO_TI.getOperation(), Constants.OGGETTO_ACTA, \"objectIdDocumento=\" + idToTrace, Thread.currentThread().getStackTrace()[1].getMethodName(), \"spostaDocumentoSuNuovaStruttura\");\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic RexNode expand(RexCall call){\r\n List operands = call.operands;\r\n assert call.isA(SqlKind.CAST);\r\n assert operands.size() == 1;\r\n assert !RexLiteral.isNullLiteral(operands.get(0));\r\n RexNode operand = operands.get(0);\r\n RelDataType fromType = operand.getType();\r\n RelDataType toType = call.getType();\r\n assert SqlTypeUtil.isDecimal(fromType) || SqlTypeUtil.isDecimal(toType);\r\n if (SqlTypeUtil.isIntType(toType)) {\r\n return ensureType(toType, scaleDown(decodeValue(operand), fromType.getScale()), false);\r\n } else if (SqlTypeUtil.isApproximateNumeric(toType)) {\r\n return ensureType(toType, scaleDownDouble(decodeValue(operand), fromType.getScale()), false);\r\n } else if (SqlTypeUtil.isApproximateNumeric(fromType)) {\r\n return encodeValue(ensureScale(operand, 0, toType.getScale()), toType, true);\r\n }\r\n if (!SqlTypeUtil.isExactNumeric(fromType) || !SqlTypeUtil.isExactNumeric(toType)) {\r\n throw Util.needToImplement(\"Cast from '\" + fromType.toString() + \"' to '\" + toType.toString() + \"'\");\r\n }\r\n int fromScale = fromType.getScale();\r\n int toScale = toType.getScale();\r\n int fromDigits = fromType.getPrecision() - fromScale;\r\n int toDigits = toType.getPrecision() - toScale;\r\n boolean checkOverflow = (toType.getPrecision() < 19) && (toDigits < fromDigits);\r\n if (SqlTypeUtil.isIntType(fromType)) {\r\n return encodeValue(ensureScale(operand, 0, toType.getScale()), toType, checkOverflow);\r\n } else if (SqlTypeUtil.isDecimal(fromType) && SqlTypeUtil.isDecimal(toType)) {\r\n RexNode value = decodeValue(operand);\r\n RexNode scaled;\r\n if (fromScale <= toScale) {\r\n scaled = ensureScale(value, fromScale, toScale);\r\n } else {\r\n if (toDigits == fromDigits) {\r\n checkOverflow = true;\r\n }\r\n scaled = scaleDown(value, fromScale - toScale);\r\n }\r\n return encodeValue(scaled, toType, checkOverflow);\r\n } else {\r\n throw Util.needToImplement(\"Reduce decimal cast from \" + fromType + \" to \" + toType);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " String signature(){\r\n final StringBuilder b = new StringBuilder();\r\n boolean flag = false;\r\n for (RelNode rel : rels) {\r\n b.append(rel instanceof TableScan ? 's' : (rel instanceof Project && flag) ? 'o' : (rel instanceof Filter && flag) ? 'h' : rel instanceof Aggregate ? 'a' : rel instanceof Filter ? 'f' : rel instanceof Sort ? 'l' : rel instanceof Project ? 'p' : '!');\r\n flag = flag || rel instanceof Aggregate;\r\n }\r\n return b.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Index validateCalendar(Context context) throws Exception{\r\n GtfsImporter importer = (GtfsImporter) context.get(PARSER);\r\n GtfsValidationReporter gtfsValidationReporter = (GtfsValidationReporter) context.get(GTFS_REPORTER);\r\n Index calendarParser = null;\r\n if (importer.hasCalendarImporter()) {\r\n gtfsValidationReporter.reportSuccess(context, GTFS_1_GTFS_Common_2, GTFS_CALENDAR_FILE);\r\n try {\r\n calendarParser = importer.getCalendarByService();\r\n } catch (Exception ex) {\r\n if (ex instanceof GtfsException) {\r\n gtfsValidationReporter.reportError(context, (GtfsException) ex, GTFS_CALENDAR_FILE);\r\n } else {\r\n gtfsValidationReporter.throwUnknownError(context, ex, GTFS_CALENDAR_FILE);\r\n }\r\n }\r\n gtfsValidationReporter.validateOkCSV(context, GTFS_CALENDAR_FILE);\r\n if (calendarParser == null) {\r\n gtfsValidationReporter.throwUnknownError(context, new Exception(\"Cannot instantiate CalendarByService class\"), GTFS_CALENDAR_FILE);\r\n } else {\r\n gtfsValidationReporter.validate(context, GTFS_CALENDAR_FILE, calendarParser.getOkTests());\r\n gtfsValidationReporter.validateUnknownError(context);\r\n }\r\n if (!calendarParser.getErrors().isEmpty()) {\r\n gtfsValidationReporter.reportErrors(context, calendarParser.getErrors(), GTFS_CALENDAR_FILE);\r\n calendarParser.getErrors().clear();\r\n }\r\n gtfsValidationReporter.validateOKGeneralSyntax(context, GTFS_CALENDAR_FILE);\r\n GtfsException fatalException = null;\r\n calendarParser.setWithValidation(true);\r\n for (GtfsCalendar bean : calendarParser) {\r\n try {\r\n calendarParser.validate(bean, importer);\r\n } catch (Exception ex) {\r\n if (ex instanceof GtfsException) {\r\n gtfsValidationReporter.reportError(context, (GtfsException) ex, GTFS_CALENDAR_FILE);\r\n } else {\r\n gtfsValidationReporter.throwUnknownError(context, ex, GTFS_CALENDAR_FILE);\r\n }\r\n }\r\n for (GtfsException ex : bean.getErrors()) {\r\n if (ex.isFatal())\r\n fatalException = ex;\r\n }\r\n gtfsValidationReporter.reportErrors(context, bean.getErrors(), GTFS_CALENDAR_FILE);\r\n gtfsValidationReporter.validate(context, GTFS_CALENDAR_FILE, bean.getOkTests());\r\n }\r\n calendarParser.setWithValidation(false);\r\n if (fatalException != null)\r\n throw fatalException;\r\n }\r\n return calendarParser;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setServerInfo(Swagger openApi2, List servers){\r\n for (Server server : servers) {\r\n String serverUrl = server.getUrl();\r\n if (serverUrl != null && !serverUrl.isEmpty()) {\r\n try {\r\n URL url = new URL(serverUrl);\r\n openApi2.setHost(url.getHost() + \":\" + url.getPort());\r\n openApi2.setBasePath(url.getPath());\r\n Scheme scheme = Scheme.forValue(url.getProtocol());\r\n if (scheme != null) {\r\n openApi2.addScheme(scheme);\r\n }\r\n } catch (MalformedURLException e) {\r\n log.warn(\"Malformed URL in configuration: {}\", serverUrl);\r\n int basePathIndex = serverUrl.lastIndexOf('/');\r\n if (basePathIndex > 0) {\r\n openApi2.setBasePath(serverUrl.substring(basePathIndex));\r\n } else {\r\n basePathIndex = serverUrl.length() - 1;\r\n }\r\n int protIndex = serverUrl.indexOf(\"://\");\r\n if (protIndex > 0) {\r\n String protocol = serverUrl.substring(0, protIndex);\r\n Scheme scheme = Scheme.forValue(protocol);\r\n if (scheme != null) {\r\n openApi2.addScheme(scheme);\r\n }\r\n openApi2.setHost(serverUrl.substring(protIndex + 3, basePathIndex));\r\n } else {\r\n openApi2.setHost(serverUrl.substring(0, basePathIndex));\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean handler(ServerConfiguration conf, ListLedgersFlags flags) throws UnknownHostException, MetadataException, ExecutionException{\r\n final BookieId bookieAddress = StringUtils.isBlank(flags.bookieId) ? null : BookieId.parse(flags.bookieId);\r\n runFunctionWithLedgerManagerFactory(conf, mFactory -> {\r\n try (LedgerManager ledgerManager = mFactory.newLedgerManager()) {\r\n final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK);\r\n final CountDownLatch processDone = new CountDownLatch(1);\r\n BookkeeperInternalCallbacks.Processor ledgerProcessor = (ledgerId, cb) -> {\r\n if (!flags.meta && (bookieAddress == null)) {\r\n printLedgerMetadata(ledgerId, null, false);\r\n cb.processResult(BKException.Code.OK, null, null);\r\n } else {\r\n ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadata, exception) -> {\r\n if (exception == null) {\r\n if ((bookieAddress == null) || BookKeeperAdmin.areEntriesOfLedgerStoredInTheBookie(ledgerId, bookieAddress, metadata.getValue())) {\r\n synchronized (ListLedgersCommand.this) {\r\n printLedgerMetadata(ledgerId, metadata.getValue(), flags.meta);\r\n }\r\n }\r\n cb.processResult(BKException.Code.OK, null, null);\r\n } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsException || BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) {\r\n cb.processResult(BKException.Code.OK, null, null);\r\n } else {\r\n LOG.error(\"Unable to read the ledger: {} information\", ledgerId);\r\n cb.processResult(BKException.getExceptionCode(exception), null, null);\r\n }\r\n });\r\n }\r\n };\r\n ledgerManager.asyncProcessLedgers(ledgerProcessor, (rc, s, obj) -> {\r\n returnCode.set(rc);\r\n processDone.countDown();\r\n }, null, BKException.Code.OK, BKException.Code.ReadException);\r\n processDone.await();\r\n if (returnCode.get() != BKException.Code.OK) {\r\n LOG.error(\"Received error return value while processing ledgers: {}\", returnCode.get());\r\n throw BKException.create(returnCode.get());\r\n }\r\n } catch (Exception ioe) {\r\n LOG.error(\"Received Exception while processing ledgers\", ioe);\r\n throw new UncheckedExecutionException(ioe);\r\n }\r\n return null;\r\n });\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static final ReferentialLockManager getLockManager(){\r\n if (LOCK_MANAGER == null) {\r\n synchronized (LOCK) {\r\n if (LOCK_MANAGER == null) {\r\n ContenerChecker contenerChecker = null;\r\n try {\r\n contenerChecker = CDI.current().select(ContenerChecker.class).get();\r\n } catch (Exception e) {\r\n log.warn(\"Failed to access CDI, using default fileStore impl\");\r\n }\r\n if (contenerChecker != null) {\r\n String implBeanName = System.getProperty(contenerChecker.getContext() + PropertyNames.REFERENTIAL_LOCK_MANAGER_IMPLEMENTATION);\r\n if (implBeanName != null) {\r\n Set> beans = CDI.current().getBeanManager().getBeans(implBeanName);\r\n if (beans.size() > 0) {\r\n Bean bean = (Bean) beans.iterator().next();\r\n CreationalContext ctx = CDI.current().getBeanManager().createCreationalContext(bean);\r\n LOCK_MANAGER = (ReferentialLockManager) CDI.current().getBeanManager().getReference(bean, ReferentialLockManager.class, ctx);\r\n } else {\r\n throw new IllegalArgumentException(\"Referential lock manager implementation with bean name: \" + implBeanName + \" not found\");\r\n }\r\n } else {\r\n log.warn(\"No Referential lock manager implementation defined, using LocalReferentialLockManager as default\");\r\n }\r\n }\r\n if (LOCK_MANAGER == null) {\r\n LOCK_MANAGER = new LocalReferentialLockManager();\r\n }\r\n }\r\n }\r\n }\r\n return LOCK_MANAGER;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void checkTypeAssignment(@Nullable SqlValidatorScope sourceScope, SqlValidatorTable table, RelDataType sourceRowType, RelDataType targetRowType, final SqlNode query){\r\n boolean isUpdateModifiableViewTable = false;\r\n if (query instanceof SqlUpdate) {\r\n final SqlNodeList targetColumnList = requireNonNull(((SqlUpdate) query).getTargetColumnList());\r\n final int targetColumnCount = targetColumnList.size();\r\n targetRowType = SqlTypeUtil.extractLastNFields(typeFactory, targetRowType, targetColumnCount);\r\n sourceRowType = SqlTypeUtil.extractLastNFields(typeFactory, sourceRowType, targetColumnCount);\r\n isUpdateModifiableViewTable = table.unwrap(ModifiableViewTable.class) != null;\r\n }\r\n if (SqlTypeUtil.equalAsStructSansNullability(typeFactory, sourceRowType, targetRowType, null)) {\r\n return;\r\n }\r\n if (config.typeCoercionEnabled() && !isUpdateModifiableViewTable) {\r\n boolean coerced = typeCoercion.querySourceCoercion(sourceScope, sourceRowType, targetRowType, query);\r\n if (coerced) {\r\n return;\r\n }\r\n }\r\n List sourceFields = sourceRowType.getFieldList();\r\n List targetFields = targetRowType.getFieldList();\r\n final int sourceCount = sourceFields.size();\r\n for (int i = 0; i < sourceCount; ++i) {\r\n RelDataType sourceType = sourceFields.get(i).getType();\r\n RelDataType targetType = targetFields.get(i).getType();\r\n if (!SqlTypeUtil.canAssignFrom(targetType, sourceType)) {\r\n SqlNode node = getNthExpr(query, i, sourceCount);\r\n if (node instanceof SqlDynamicParam) {\r\n continue;\r\n }\r\n String targetTypeString;\r\n String sourceTypeString;\r\n if (SqlTypeUtil.areCharacterSetsMismatched(sourceType, targetType)) {\r\n sourceTypeString = sourceType.getFullTypeString();\r\n targetTypeString = targetType.getFullTypeString();\r\n } else {\r\n sourceTypeString = sourceType.toString();\r\n targetTypeString = targetType.toString();\r\n }\r\n throw newValidationError(node, RESOURCE.typeNotAssignable(targetFields.get(i).getName(), targetTypeString, sourceFields.get(i).getName(), sourceTypeString));\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List getAttributes(){\r\n if (attributes == null) {\r\n attributes = new ArrayList<>();\r\n if (name_RU != null) {\r\n final Iterator name_RU_Iterator = Arrays.asList(name_RU).iterator();\r\n if (!type.equals(\"AD\")) {\r\n T_index = 0;\r\n }\r\n caseI_KI_Index = 0;\r\n caseD_KD_Index = 0;\r\n caseF_KF_Index = 0;\r\n caseJ_KJ_Index = 0;\r\n casec_RS_Index = 0;\r\n caseet_RS_Index = 0;\r\n caseec_RU_Index = 0;\r\n cases_RU_Index = 0;\r\n casearray_N_Index = 0;\r\n nesttype_RS_Index = 0;\r\n nestpair_N_Index = 0;\r\n nestname_RU_Iterator = Arrays.asList(nestname_RU).iterator();\r\n if (type.equals(\"RVA\") || type.equals(\"RIA\")) {\r\n for (int i = 0; i < anno_N.length; i++) {\r\n attributes.add(getAttribute(anno_N[i], type_RS[i], pair_N[i], name_RU_Iterator));\r\n }\r\n } else if (type.equals(\"RVPA\") || type.equals(\"RIPA\")) {\r\n anno_N_Index = 0;\r\n pair_N_Index = 0;\r\n for (final int element : param_NB) {\r\n attributes.add(getParameterAttribute(element, name_RU_Iterator));\r\n }\r\n }\r\n } else if (type.equals(\"AD\")) {\r\n for (final int element : T) {\r\n attributes.add(new AnnotationDefaultAttribute(new ElementValue(element, getNextValue(element))));\r\n }\r\n }\r\n }\r\n return attributes;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void propagateModifyObject(final InternalFactHandle factHandle, final ModifyPreviousTuples modifyPreviousTuples, final PropagationContext context, final ReteEvaluator reteEvaluator){\r\n final Object object = factHandle.getObject();\r\n if (this.hashedFieldIndexes != null) {\r\n for (FieldIndex fieldIndex : this.hashedFieldIndexes) {\r\n if (!fieldIndex.isHashed()) {\r\n continue;\r\n }\r\n final AlphaNode sink = this.hashedSinkMap.get(new HashKey(fieldIndex, object));\r\n if (sink != null) {\r\n sink.getObjectSinkPropagator().propagateModifyObject(factHandle, modifyPreviousTuples, context, reteEvaluator);\r\n }\r\n }\r\n }\r\n if (this.rangeIndexMap != null) {\r\n for (Map.Entry entry : this.rangeIndexMap.entrySet()) {\r\n if (!entry.getKey().isRangeIndexed()) {\r\n continue;\r\n }\r\n for (AlphaNode sink : entry.getValue().getMatchingAlphaNodes(object)) {\r\n sink.getObjectSinkPropagator().propagateModifyObject(factHandle, modifyPreviousTuples, context, reteEvaluator);\r\n }\r\n }\r\n }\r\n if (this.hashableSinks != null) {\r\n for (ObjectSinkNode sink : this.hashableSinks) {\r\n doPropagateModifyObject(factHandle, modifyPreviousTuples, context, reteEvaluator, sink);\r\n }\r\n }\r\n if (this.rangeIndexableSinks != null) {\r\n for (ObjectSinkNode sink : this.rangeIndexableSinks) {\r\n doPropagateModifyObject(factHandle, modifyPreviousTuples, context, reteEvaluator, sink);\r\n }\r\n }\r\n if (this.otherSinks != null) {\r\n for (ObjectSinkNode sink : this.otherSinks) {\r\n doPropagateModifyObject(factHandle, modifyPreviousTuples, context, reteEvaluator, sink);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized ZooKeeper get() throws ZooKeeperConnectionException, InterruptedException{\r\n try {\r\n FailpointUtils.checkFailPoint(FailpointUtils.FailPointName.FP_ZooKeeperConnectionLoss);\r\n } catch (IOException ioe) {\r\n throw new ZooKeeperConnectionException(\"Client \" + name + \" failed on establishing zookeeper connection\", ioe);\r\n }\r\n if (closed) {\r\n throw new ZooKeeperConnectionException(\"Client \" + name + \" has already been closed\");\r\n }\r\n if (zooKeeper != null && retryPolicy != null) {\r\n if (zooKeeper.getState().equals(ZooKeeper.States.CONNECTED)) {\r\n disconnectedStopwatch = null;\r\n } else {\r\n if (disconnectedStopwatch == null) {\r\n disconnectedStopwatch = Stopwatch.createStarted();\r\n } else {\r\n long disconnectedMs = disconnectedStopwatch.elapsed(TimeUnit.MILLISECONDS);\r\n if (disconnectedMs > defaultConnectionTimeoutMs) {\r\n closeInternal();\r\n authenticated = false;\r\n }\r\n }\r\n }\r\n }\r\n if (zooKeeper == null) {\r\n zooKeeper = buildZooKeeper();\r\n disconnectedStopwatch = null;\r\n }\r\n if (!authenticated) {\r\n credentials.authenticate(zooKeeper);\r\n authenticated = true;\r\n }\r\n return zooKeeper;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void verifyReferencesToCommonElements(Context context, List localRefs, Set localIds, Map> commonIds){\r\n ValidationReporter validationReporter = ValidationReporter.Factory.getInstance();\r\n Set nonVersionedLocalRefs = localRefs.stream().map(e -> e.getId()).collect(Collectors.toSet());\r\n Set nonVersionedLocalIds = localIds.stream().map(e -> e.getId()).collect(Collectors.toSet());\r\n Set unresolvedReferences = new HashSet<>(nonVersionedLocalRefs);\r\n unresolvedReferences.removeAll(nonVersionedLocalIds);\r\n for (ExternalReferenceValidator v : externalReferenceValidators) {\r\n Set ofSupportedTypes = v.isOfSupportedTypes(new HashSet<>(localRefs));\r\n unresolvedReferences.removeAll(ofSupportedTypes.stream().map(e -> e.getId()).collect(Collectors.toSet()));\r\n }\r\n if (commonIds != null) {\r\n Set commonIdsWithoutVersion = commonIds.keySet().stream().map(e -> e.getId()).collect(Collectors.toSet());\r\n if (commonIdsWithoutVersion.size() > 0) {\r\n for (String localRef : unresolvedReferences) {\r\n if (!commonIdsWithoutVersion.contains(localRef)) {\r\n IdVersion id = null;\r\n for (IdVersion i : localRefs) {\r\n if (i.getId().equals(localRef)) {\r\n id = i;\r\n break;\r\n }\r\n }\r\n validationReporter.addCheckPointReportError(context, _1_NETEX_UNRESOLVED_REFERENCE_TO_COMMON_ELEMENTS, null, DataLocationHelper.findDataLocation(id), id.getId());\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Unresolved reference to \" + localRef + \" in line file without any counterpart in the commonIds\");\r\n }\r\n }\r\n }\r\n } else {\r\n validationReporter.reportSuccess(context, _1_NETEX_UNRESOLVED_REFERENCE_TO_COMMON_ELEMENTS);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Pair enforcePolicies(final User user, final boolean disablePwdPolicyCheck, final String clearPassword){\r\n if (!disablePwdPolicyCheck) {\r\n LOG.debug(\"Password Policy enforcement\");\r\n try {\r\n int maxPPSpecHistory = 0;\r\n for (PasswordPolicy policy : ruleEnforcer.getPasswordPolicies(user.getRealm(), userDAO.findAllResources(user))) {\r\n if (clearPassword == null && !policy.isAllowNullPassword()) {\r\n throw new PasswordPolicyException(\"Password mandatory\");\r\n }\r\n ruleEnforcer.getPasswordRules(policy).forEach(rule -> {\r\n rule.enforce(user, clearPassword);\r\n user.getLinkedAccounts().stream().filter(account -> account.getPassword() != null).forEach(rule::enforce);\r\n });\r\n boolean matching = false;\r\n if (policy.getHistoryLength() > 0) {\r\n List pwdHistory = user.getPasswordHistory();\r\n matching = pwdHistory.subList(policy.getHistoryLength() >= pwdHistory.size() ? 0 : pwdHistory.size() - policy.getHistoryLength(), pwdHistory.size()).stream().map(old -> Encryptor.getInstance().verify(clearPassword, user.getCipherAlgorithm(), old)).reduce(matching, (accumulator, item) -> accumulator | item);\r\n }\r\n if (matching) {\r\n throw new PasswordPolicyException(\"Password value was used in the past: not allowed\");\r\n }\r\n if (policy.getHistoryLength() > maxPPSpecHistory) {\r\n maxPPSpecHistory = policy.getHistoryLength();\r\n }\r\n }\r\n if (maxPPSpecHistory > 0 && user.getPassword() != null && !user.getPasswordHistory().contains(user.getPassword())) {\r\n user.addToPasswordHistory(user.getPassword());\r\n }\r\n if (maxPPSpecHistory < user.getPasswordHistory().size()) {\r\n user.removeOldestEntriesFromPasswordHistory(user.getPasswordHistory().size() - maxPPSpecHistory);\r\n }\r\n } catch (InvalidEntityException e) {\r\n throw e;\r\n } catch (Exception e) {\r\n LOG.error(\"Invalid password for {}\", user, e);\r\n throw new InvalidEntityException(User.class, EntityViolationType.InvalidPassword, e.getMessage());\r\n }\r\n }\r\n LOG.debug(\"Account Policy enforcement\");\r\n boolean suspend = false;\r\n boolean propagateSuspension = false;\r\n try {\r\n if (user.getUsername() == null) {\r\n throw new AccountPolicyException(\"Null username\");\r\n }\r\n if (securityProperties.getAdminUser().equals(user.getUsername()) || securityProperties.getAnonymousUser().equals(user.getUsername())) {\r\n throw new AccountPolicyException(\"Not allowed: \" + user.getUsername());\r\n }\r\n List accountPolicies = ruleEnforcer.getAccountPolicies(user.getRealm(), userDAO.findAllResources(user));\r\n if (accountPolicies.isEmpty()) {\r\n if (!Entity.ID_PATTERN.matcher(user.getUsername()).matches()) {\r\n throw new AccountPolicyException(\"Character(s) not allowed: \" + user.getUsername());\r\n }\r\n user.getLinkedAccounts().stream().filter(account -> account.getUsername() != null).forEach(account -> {\r\n if (!Entity.ID_PATTERN.matcher(account.getUsername()).matches()) {\r\n throw new AccountPolicyException(\"Character(s) not allowed: \" + account.getUsername());\r\n }\r\n });\r\n } else {\r\n for (AccountPolicy policy : accountPolicies) {\r\n ruleEnforcer.getAccountRules(policy).forEach(rule -> {\r\n rule.enforce(user);\r\n user.getLinkedAccounts().stream().filter(account -> account.getUsername() != null).forEach(rule::enforce);\r\n });\r\n suspend |= user.getFailedLogins() != null && policy.getMaxAuthenticationAttempts() > 0 && user.getFailedLogins() > policy.getMaxAuthenticationAttempts() && !user.isSuspended();\r\n propagateSuspension |= policy.isPropagateSuspension();\r\n }\r\n }\r\n } catch (InvalidEntityException e) {\r\n throw e;\r\n } catch (Exception e) {\r\n LOG.error(\"Invalid username for {}\", user, e);\r\n throw new InvalidEntityException(User.class, EntityViolationType.InvalidUsername, e.getMessage());\r\n }\r\n return Pair.of(suspend, propagateSuspension);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doSetUp() throws Exception{\r\n LOG.debug(\"setUp test\");\r\n if (useJmx() || isRouteCoverageEnabled() || isCamelDebugPresent()) {\r\n enableJMX();\r\n } else {\r\n disableJMX();\r\n }\r\n context = (ModelCamelContext) createCamelContext();\r\n THREAD_CAMEL_CONTEXT.set(context);\r\n assertNotNull(context, \"No context found!\");\r\n bindToRegistry(context.getRegistry());\r\n context.getShutdownStrategy().setTimeout(getShutdownTimeout());\r\n if (isUseDebugger()) {\r\n if (context.getStatus().equals(ServiceStatus.Started)) {\r\n LOG.info(\"Cannot setting the Debugger to the starting CamelContext, stop the CamelContext now.\");\r\n context.stop();\r\n }\r\n context.setDebugging(true);\r\n context.setDebugger(new DefaultDebugger());\r\n context.getDebugger().addBreakpoint(breakpoint);\r\n }\r\n template = context.createProducerTemplate();\r\n template.start();\r\n fluentTemplate = context.createFluentProducerTemplate();\r\n fluentTemplate.start();\r\n consumer = context.createConsumerTemplate();\r\n consumer.start();\r\n THREAD_TEMPLATE.set(template);\r\n THREAD_FLUENT_TEMPLATE.set(fluentTemplate);\r\n THREAD_CONSUMER.set(consumer);\r\n String pattern = isMockEndpoints();\r\n if (pattern != null) {\r\n context.getCamelContextExtension().registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern));\r\n }\r\n pattern = isMockEndpointsAndSkip();\r\n if (pattern != null) {\r\n context.getCamelContextExtension().registerEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true));\r\n }\r\n PropertiesComponent pc = context.getPropertiesComponent();\r\n if (extra == null) {\r\n extra = useOverridePropertiesWithPropertiesComponent();\r\n }\r\n if (extra != null && !extra.isEmpty()) {\r\n pc.setOverrideProperties(extra);\r\n }\r\n pc.addPropertiesSource(new PropertiesSource() {\r\n\r\n @Override\r\n public String getName() {\r\n return \"junit-store\";\r\n }\r\n\r\n @Override\r\n public String getProperty(String name) {\r\n return globalStore.get(name, String.class);\r\n }\r\n });\r\n Boolean ignore = ignoreMissingLocationWithPropertiesComponent();\r\n if (ignore != null) {\r\n pc.setIgnoreMissingLocation(ignore);\r\n }\r\n String include = getRouteFilterIncludePattern();\r\n String exclude = getRouteFilterExcludePattern();\r\n if (include != null || exclude != null) {\r\n LOG.info(\"Route filtering pattern: include={}, exclude={}\", include, exclude);\r\n context.getCamelContextExtension().getContextPlugin(Model.class).setRouteFilterPattern(include, exclude);\r\n }\r\n postProcessTest();\r\n if (isUseRouteBuilder()) {\r\n RoutesBuilder[] builders = createRouteBuilders();\r\n for (RoutesBuilder builder : builders) {\r\n if (builder instanceof RouteConfigurationsBuilder) {\r\n LOG.debug(\"Using created route configuration: {}\", builder);\r\n context.addRoutesConfigurations((RouteConfigurationsBuilder) builder);\r\n }\r\n }\r\n for (RoutesBuilder builder : builders) {\r\n LOG.debug(\"Using created route builder to add routes: {}\", builder);\r\n context.addRoutes(builder);\r\n }\r\n for (RoutesBuilder builder : builders) {\r\n LOG.debug(\"Using created route builder to add templated routes: {}\", builder);\r\n context.addTemplatedRoutes(builder);\r\n }\r\n replaceFromEndpoints();\r\n boolean skip = \"true\".equalsIgnoreCase(System.getProperty(\"skipStartingCamelContext\"));\r\n if (skip) {\r\n LOG.info(\"Skipping starting CamelContext as system property skipStartingCamelContext is set to be true.\");\r\n } else if (isUseAdviceWith()) {\r\n LOG.info(\"Skipping starting CamelContext as isUseAdviceWith is set to true.\");\r\n } else {\r\n startCamelContext();\r\n }\r\n } else {\r\n replaceFromEndpoints();\r\n LOG.debug(\"Using route builder from the created context: {}\", context);\r\n }\r\n LOG.debug(\"Routing Rules are: {}\", context.getRoutes());\r\n assertValidContext(context);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static int[] getSpecifier(final Codec codec, final Codec defaultForBand){\r\n if (canonicalCodecsToSpecifiers == null) {\r\n final HashMap reverseMap = new HashMap<>(canonicalCodec.length);\r\n for (int i = 0; i < canonicalCodec.length; ++i) {\r\n reverseMap.put(canonicalCodec[i], Integer.valueOf(i));\r\n }\r\n canonicalCodecsToSpecifiers = reverseMap;\r\n }\r\n if (canonicalCodecsToSpecifiers.containsKey(codec)) {\r\n return new int[] { canonicalCodecsToSpecifiers.get(codec).intValue() };\r\n }\r\n if (codec instanceof BHSDCodec) {\r\n final BHSDCodec bhsdCodec = (BHSDCodec) codec;\r\n final int[] specifiers = new int[3];\r\n specifiers[0] = 116;\r\n specifiers[1] = (bhsdCodec.isDelta() ? 1 : 0) + 2 * bhsdCodec.getS() + 8 * (bhsdCodec.getB() - 1);\r\n specifiers[2] = bhsdCodec.getH() - 1;\r\n return specifiers;\r\n }\r\n if (codec instanceof RunCodec) {\r\n final RunCodec runCodec = (RunCodec) codec;\r\n final int k = runCodec.getK();\r\n int kb;\r\n int kx;\r\n if (k <= 256) {\r\n kb = 0;\r\n kx = k - 1;\r\n } else if (k <= 4096) {\r\n kb = 1;\r\n kx = k / 16 - 1;\r\n } else if (k <= 65536) {\r\n kb = 2;\r\n kx = k / 256 - 1;\r\n } else {\r\n kb = 3;\r\n kx = k / 4096 - 1;\r\n }\r\n final Codec aCodec = runCodec.getACodec();\r\n final Codec bCodec = runCodec.getBCodec();\r\n int abDef = 0;\r\n if (aCodec.equals(defaultForBand)) {\r\n abDef = 1;\r\n } else if (bCodec.equals(defaultForBand)) {\r\n abDef = 2;\r\n }\r\n final int first = 117 + kb + (kx == 3 ? 0 : 4) + (8 * abDef);\r\n final int[] aSpecifier = abDef == 1 ? new int[0] : getSpecifier(aCodec, defaultForBand);\r\n final int[] bSpecifier = abDef == 2 ? new int[0] : getSpecifier(bCodec, defaultForBand);\r\n final int[] specifier = new int[1 + (kx == 3 ? 0 : 1) + aSpecifier.length + bSpecifier.length];\r\n specifier[0] = first;\r\n int index = 1;\r\n if (kx != 3) {\r\n specifier[1] = kx;\r\n index++;\r\n }\r\n for (final int element : aSpecifier) {\r\n specifier[index] = element;\r\n index++;\r\n }\r\n for (final int element : bSpecifier) {\r\n specifier[index] = element;\r\n index++;\r\n }\r\n return specifier;\r\n }\r\n if (codec instanceof PopulationCodec) {\r\n final PopulationCodec populationCodec = (PopulationCodec) codec;\r\n final Codec tokenCodec = populationCodec.getTokenCodec();\r\n final Codec favouredCodec = populationCodec.getFavouredCodec();\r\n final Codec unfavouredCodec = populationCodec.getUnfavouredCodec();\r\n final int fDef = favouredCodec.equals(defaultForBand) ? 1 : 0;\r\n final int uDef = unfavouredCodec.equals(defaultForBand) ? 1 : 0;\r\n int tDefL = 0;\r\n final int[] favoured = populationCodec.getFavoured();\r\n if (favoured != null) {\r\n if (tokenCodec == Codec.BYTE1) {\r\n tDefL = 1;\r\n } else if (tokenCodec instanceof BHSDCodec) {\r\n final BHSDCodec tokenBHSD = (BHSDCodec) tokenCodec;\r\n if (tokenBHSD.getS() == 0) {\r\n final int[] possibleLValues = { 4, 8, 16, 32, 64, 128, 192, 224, 240, 248, 252 };\r\n final int l = 256 - tokenBHSD.getH();\r\n int index = Arrays.binarySearch(possibleLValues, l);\r\n if (index != -1) {\r\n tDefL = index++;\r\n }\r\n }\r\n }\r\n }\r\n final int first = 141 + fDef + (2 * uDef) + (4 * tDefL);\r\n final int[] favouredSpecifier = fDef == 1 ? new int[0] : getSpecifier(favouredCodec, defaultForBand);\r\n final int[] tokenSpecifier = tDefL != 0 ? new int[0] : getSpecifier(tokenCodec, defaultForBand);\r\n final int[] unfavouredSpecifier = uDef == 1 ? new int[0] : getSpecifier(unfavouredCodec, defaultForBand);\r\n final int[] specifier = new int[1 + favouredSpecifier.length + unfavouredSpecifier.length + tokenSpecifier.length];\r\n specifier[0] = first;\r\n int index = 1;\r\n for (final int element : favouredSpecifier) {\r\n specifier[index] = element;\r\n index++;\r\n }\r\n for (final int element : tokenSpecifier) {\r\n specifier[index] = element;\r\n index++;\r\n }\r\n for (final int element : unfavouredSpecifier) {\r\n specifier[index] = element;\r\n index++;\r\n }\r\n return specifier;\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ExitCode run(LlapStatusServiceCommandLine cl, long watchTimeoutMs){\r\n appStatusBuilder = new AppStatusBuilder();\r\n try {\r\n if (appName == null) {\r\n for (Map.Entry props : cl.getHiveConf().entrySet()) {\r\n conf.set((String) props.getKey(), (String) props.getValue());\r\n }\r\n appName = cl.getName();\r\n if (StringUtils.isEmpty(appName)) {\r\n appName = HiveConf.getVar(conf, HiveConf.ConfVars.LLAP_DAEMON_SERVICE_HOSTS);\r\n if (appName.startsWith(\"@\") && appName.length() > 1) {\r\n appName = appName.substring(1);\r\n } else {\r\n appName = null;\r\n }\r\n }\r\n if (StringUtils.isEmpty(appName)) {\r\n LOG.error(\"Invalid app name. This must be setup via config or passed in as a parameter.\" + \" This tool works with clusters deployed by YARN Service\");\r\n return ExitCode.INCORRECT_USAGE;\r\n }\r\n LOG.debug(\"Using appName: {}\", appName);\r\n llapRegistryConf.set(HiveConf.ConfVars.LLAP_DAEMON_SERVICE_HOSTS.varname, \"@\" + appName);\r\n }\r\n try {\r\n if (serviceClient == null) {\r\n serviceClient = LlapSliderUtils.createServiceClient(conf);\r\n }\r\n } catch (Exception e) {\r\n LlapStatusCliException le = new LlapStatusCliException(ExitCode.SERVICE_CLIENT_ERROR_CREATE_FAILED, \"Failed to create service client\", e);\r\n logError(le);\r\n return le.getExitCode();\r\n }\r\n ApplicationReport appReport;\r\n try {\r\n appReport = getAppReport(appName, cl.getFindAppTimeoutMs());\r\n } catch (LlapStatusCliException e) {\r\n logError(e);\r\n return e.getExitCode();\r\n }\r\n ExitCode ret;\r\n try {\r\n ret = processAppReport(appReport, appStatusBuilder);\r\n } catch (LlapStatusCliException e) {\r\n logError(e);\r\n return e.getExitCode();\r\n }\r\n if (ret != ExitCode.SUCCESS) {\r\n return ret;\r\n } else if (NO_YARN_SERVICE_INFO_STATES.contains(appStatusBuilder.getState())) {\r\n return ExitCode.SUCCESS;\r\n } else {\r\n try {\r\n ret = populateAppStatusFromServiceStatus(appName, serviceClient, appStatusBuilder);\r\n } catch (LlapStatusCliException e) {\r\n logError(e);\r\n return e.getExitCode();\r\n }\r\n }\r\n if (ret != ExitCode.SUCCESS) {\r\n return ret;\r\n } else {\r\n try {\r\n ret = populateAppStatusFromLlapRegistry(appStatusBuilder, watchTimeoutMs);\r\n } catch (LlapStatusCliException e) {\r\n logError(e);\r\n return e.getExitCode();\r\n }\r\n }\r\n return ret;\r\n } finally {\r\n LOG.debug(\"Final AppState: \" + appStatusBuilder.toString());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void scheduleCheckAllLedgersTask(){\r\n long interval = conf.getAuditorPeriodicCheckInterval();\r\n if (interval > 0) {\r\n LOG.info(\"Auditor periodic ledger checking enabled\" + \" 'auditorPeriodicCheckInterval' {} seconds\", interval);\r\n long checkAllLedgersLastExecutedCTime;\r\n long durationSinceLastExecutionInSecs;\r\n long initialDelay;\r\n try {\r\n checkAllLedgersLastExecutedCTime = ledgerUnderreplicationManager.getCheckAllLedgersCTime();\r\n } catch (ReplicationException.NonRecoverableReplicationException nre) {\r\n LOG.error(\"Non Recoverable Exception while reading from ZK\", nre);\r\n submitShutdownTask();\r\n return;\r\n } catch (UnavailableException ue) {\r\n LOG.error(\"Got UnavailableException while trying to get checkAllLedgersCTime\", ue);\r\n checkAllLedgersLastExecutedCTime = -1;\r\n }\r\n if (checkAllLedgersLastExecutedCTime == -1) {\r\n durationSinceLastExecutionInSecs = -1;\r\n initialDelay = 0;\r\n } else {\r\n durationSinceLastExecutionInSecs = (System.currentTimeMillis() - checkAllLedgersLastExecutedCTime) / 1000;\r\n if (durationSinceLastExecutionInSecs < 0) {\r\n durationSinceLastExecutionInSecs = 0;\r\n }\r\n initialDelay = durationSinceLastExecutionInSecs > interval ? 0 : (interval - durationSinceLastExecutionInSecs);\r\n }\r\n LOG.info(\"checkAllLedgers scheduling info. checkAllLedgersLastExecutedCTime: {} \" + \"durationSinceLastExecutionInSecs: {} initialDelay: {} interval: {}\", checkAllLedgersLastExecutedCTime, durationSinceLastExecutionInSecs, initialDelay, interval);\r\n executor.scheduleAtFixedRate(() -> {\r\n Stopwatch stopwatch = Stopwatch.createStarted();\r\n boolean checkSuccess = false;\r\n try {\r\n if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) {\r\n LOG.info(\"Ledger replication disabled, skipping checkAllLedgers\");\r\n return;\r\n }\r\n LOG.info(\"Starting checkAllLedgers\");\r\n checkAllLedgers();\r\n long checkAllLedgersDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);\r\n LOG.info(\"Completed checkAllLedgers in {} milliSeconds\", checkAllLedgersDuration);\r\n checkAllLedgersTime.registerSuccessfulEvent(checkAllLedgersDuration, TimeUnit.MILLISECONDS);\r\n checkSuccess = true;\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n LOG.error(\"Interrupted while running periodic check\", ie);\r\n } catch (BKException bke) {\r\n LOG.error(\"Exception running periodic check\", bke);\r\n } catch (IOException ioe) {\r\n LOG.error(\"I/O exception running periodic check\", ioe);\r\n } catch (ReplicationException.NonRecoverableReplicationException nre) {\r\n LOG.error(\"Non Recoverable Exception while reading from ZK\", nre);\r\n submitShutdownTask();\r\n } catch (ReplicationException.UnavailableException ue) {\r\n LOG.error(\"Underreplication manager unavailable running periodic check\", ue);\r\n } finally {\r\n if (!checkSuccess) {\r\n long checkAllLedgersDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);\r\n checkAllLedgersTime.registerFailedEvent(checkAllLedgersDuration, TimeUnit.MILLISECONDS);\r\n }\r\n }\r\n }, initialDelay, interval, TimeUnit.SECONDS);\r\n } else {\r\n LOG.info(\"Periodic checking disabled\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void removeOffsetFromDeletedLedgers() throws IOException{\r\n LongPairWrapper firstKeyWrapper = LongPairWrapper.get(-1, -1);\r\n LongPairWrapper lastKeyWrapper = LongPairWrapper.get(-1, -1);\r\n LongPairWrapper keyToDelete = LongPairWrapper.get(-1, -1);\r\n Set ledgersToDelete = deletedLedgers.items();\r\n if (ledgersToDelete.isEmpty()) {\r\n return;\r\n }\r\n log.info(\"Deleting indexes for ledgers: {}\", ledgersToDelete);\r\n long startTime = System.nanoTime();\r\n long deletedEntries = 0;\r\n long deletedEntriesInBatch = 0;\r\n Batch batch = locationsDb.newBatch();\r\n try {\r\n for (long ledgerId : ledgersToDelete) {\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Deleting indexes from ledger {}\", ledgerId);\r\n }\r\n firstKeyWrapper.set(ledgerId, 0);\r\n lastKeyWrapper.set(ledgerId, Long.MAX_VALUE);\r\n Entry firstKeyRes = locationsDb.getCeil(firstKeyWrapper.array);\r\n if (firstKeyRes == null || ArrayUtil.getLong(firstKeyRes.getKey(), 0) != ledgerId) {\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"No entries found for ledger {}\", ledgerId);\r\n }\r\n continue;\r\n }\r\n long firstEntryId = ArrayUtil.getLong(firstKeyRes.getKey(), 8);\r\n long lastEntryId;\r\n try {\r\n lastEntryId = getLastEntryInLedgerInternal(ledgerId);\r\n } catch (Bookie.NoEntryException nee) {\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"No last entry id found for ledger {}\", ledgerId);\r\n }\r\n continue;\r\n }\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Deleting index for ledger {} entries ({} -> {})\", ledgerId, firstEntryId, lastEntryId);\r\n }\r\n for (long entryId = firstEntryId; entryId <= lastEntryId; entryId++) {\r\n keyToDelete.set(ledgerId, entryId);\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Deleting index for ({}, {})\", keyToDelete.getFirst(), keyToDelete.getSecond());\r\n }\r\n batch.remove(keyToDelete.array);\r\n ++deletedEntriesInBatch;\r\n }\r\n if (deletedEntriesInBatch > DELETE_ENTRIES_BATCH_SIZE) {\r\n batch.flush();\r\n batch.clear();\r\n deletedEntriesInBatch = 0;\r\n }\r\n }\r\n } finally {\r\n try {\r\n batch.flush();\r\n batch.clear();\r\n } finally {\r\n firstKeyWrapper.recycle();\r\n lastKeyWrapper.recycle();\r\n keyToDelete.recycle();\r\n batch.close();\r\n }\r\n }\r\n log.info(\"Deleted indexes for {} entries from {} ledgers in {} seconds\", deletedEntries, ledgersToDelete.size(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) / 1000.0);\r\n for (long ledgerId : ledgersToDelete) {\r\n deletedLedgers.remove(ledgerId);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " AddressDefinition pickMatchingAddress(Collection interfaces) throws SocketException{\r\n List networkInterfaces = networkInterfacesEnumerator.getNetworkInterfaces();\r\n boolean preferIPv4Stack = preferIPv4Stack();\r\n boolean preferIPv6Addresses = preferIPv6Addresses();\r\n AddressDefinition matchingAddress = null;\r\n for (NetworkInterfaceInfo ni : networkInterfaces) {\r\n if (isEmpty(interfaces) && skipInterface(ni)) {\r\n continue;\r\n }\r\n for (InetAddress inetAddress : ni.getInetAddresses()) {\r\n if (preferIPv4Stack && inetAddress instanceof Inet6Address) {\r\n continue;\r\n }\r\n AddressDefinition address = getMatchingAddress(interfaces, inetAddress);\r\n if (address == null) {\r\n continue;\r\n }\r\n matchingAddress = address;\r\n if (preferIPv6Addresses) {\r\n if (inetAddress instanceof Inet6Address) {\r\n return matchingAddress;\r\n }\r\n } else if (inetAddress instanceof Inet4Address) {\r\n return matchingAddress;\r\n }\r\n }\r\n }\r\n return matchingAddress;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static VectorizedRowBatchCtx createVrbCtx(StructObjectInspector oi, final Properties tblProps, final Configuration conf) throws IOException{\r\n final boolean useDecimal64ColumnVectors = HiveConf.getVar(conf, ConfVars.HIVE_VECTORIZED_INPUT_FORMAT_SUPPORTS_ENABLED).equalsIgnoreCase(\"decimal_64\");\r\n final String serde = tblProps.getProperty(serdeConstants.SERIALIZATION_LIB);\r\n final String inputFormat = tblProps.getProperty(hive_metastoreConstants.FILE_INPUT_FORMAT);\r\n final boolean isTextFormat = inputFormat != null && inputFormat.equals(TextInputFormat.class.getName()) && serde != null && serde.equals(LazySimpleSerDe.class.getName());\r\n List dataTypePhysicalVariations = new ArrayList<>();\r\n if (isTextFormat) {\r\n StructTypeInfo structTypeInfo = (StructTypeInfo) TypeInfoUtils.getTypeInfoFromObjectInspector(oi);\r\n int dataColumnCount = structTypeInfo.getAllStructFieldTypeInfos().size();\r\n for (int i = 0; i < dataColumnCount; i++) {\r\n DataTypePhysicalVariation dataTypePhysicalVariation = DataTypePhysicalVariation.NONE;\r\n if (useDecimal64ColumnVectors) {\r\n TypeInfo typeInfo = structTypeInfo.getAllStructFieldTypeInfos().get(i);\r\n if (typeInfo instanceof DecimalTypeInfo) {\r\n DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;\r\n if (HiveDecimalWritable.isPrecisionDecimal64(decimalTypeInfo.precision())) {\r\n dataTypePhysicalVariation = DataTypePhysicalVariation.DECIMAL_64;\r\n }\r\n }\r\n }\r\n dataTypePhysicalVariations.add(dataTypePhysicalVariation);\r\n }\r\n }\r\n VectorizedRowBatchCtx vrbCtx = new VectorizedRowBatchCtx();\r\n try {\r\n vrbCtx.init(oi, new String[0]);\r\n } catch (HiveException e) {\r\n throw new IOException(e);\r\n }\r\n if (!dataTypePhysicalVariations.isEmpty()) {\r\n vrbCtx.setRowDataTypePhysicalVariations(dataTypePhysicalVariations.toArray(new DataTypePhysicalVariation[0]));\r\n }\r\n return vrbCtx;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public AttrCond createAttrCond(final String schema){\r\n AttrCond attrCond = null;\r\n if (schemaEquals(Resource.User, \"userName\", schema)) {\r\n attrCond = new AnyCond();\r\n attrCond.setSchema(\"username\");\r\n } else if (resource == Resource.Group && schemaEquals(Resource.Group, \"displayName\", schema)) {\r\n attrCond = new AnyCond();\r\n attrCond.setSchema(\"name\");\r\n } else if (schemaEquals(null, \"meta.created\", schema)) {\r\n attrCond = new AnyCond();\r\n attrCond.setSchema(\"creationDate\");\r\n } else if (schemaEquals(null, \"meta.lastModified\", schema)) {\r\n attrCond = new AnyCond();\r\n attrCond.setSchema(\"lastChangeDate\");\r\n }\r\n if (resource == Resource.User) {\r\n if (conf.getUserConf() != null) {\r\n if (conf.getUserConf().getName() != null) {\r\n for (Map.Entry entry : conf.getUserConf().getName().asMap().entrySet()) {\r\n if (schemaEquals(Resource.User, \"name.\" + entry.getKey(), schema)) {\r\n attrCond = new AttrCond();\r\n attrCond.setSchema(entry.getValue());\r\n }\r\n }\r\n }\r\n for (Map.Entry entry : conf.getUserConf().asMap().entrySet()) {\r\n if (schemaEquals(Resource.User, entry.getKey(), schema)) {\r\n attrCond = new AttrCond();\r\n attrCond.setSchema(entry.getValue());\r\n }\r\n }\r\n for (SCIMUserAddressConf address : conf.getUserConf().getAddresses()) {\r\n for (Map.Entry entry : address.asMap().entrySet()) {\r\n if (schemaEquals(Resource.User, \"addresses.\" + entry.getKey(), schema)) {\r\n attrCond = new AttrCond();\r\n attrCond.setSchema(entry.getValue());\r\n }\r\n }\r\n }\r\n }\r\n if (conf.getEnterpriseUserConf() != null) {\r\n for (Map.Entry entry : conf.getEnterpriseUserConf().asMap().entrySet()) {\r\n if (schemaEquals(Resource.EnterpriseUser, entry.getKey(), schema)) {\r\n attrCond = new AttrCond();\r\n attrCond.setSchema(entry.getValue());\r\n }\r\n }\r\n if (conf.getEnterpriseUserConf().getManager() != null && conf.getEnterpriseUserConf().getManager().getKey() != null) {\r\n attrCond = new AttrCond();\r\n attrCond.setSchema(conf.getEnterpriseUserConf().getManager().getKey());\r\n }\r\n }\r\n }\r\n if (attrCond == null) {\r\n throw new IllegalArgumentException(\"Could not match \" + schema + \" for \" + resource);\r\n }\r\n return attrCond;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Iterable toTabletInsertionEvents(){\r\n return () -> new Iterator() {\r\n\r\n private TsFileInsertionDataTabletIterator tabletIterator = null;\r\n\r\n @Override\r\n public boolean hasNext() {\r\n while (tabletIterator == null || !tabletIterator.hasNext()) {\r\n if (!deviceMeasurementsMapIterator.hasNext()) {\r\n return false;\r\n }\r\n final Map.Entry> entry = deviceMeasurementsMapIterator.next();\r\n try {\r\n tabletIterator = new TsFileInsertionDataTabletIterator(tsFileReader, measurementDataTypeMap, entry.getKey(), entry.getValue(), timeFilterExpression);\r\n } catch (IOException e) {\r\n close();\r\n throw new PipeException(\"failed to create TsFileInsertionDataTabletIterator\", e);\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n @Override\r\n public TabletInsertionEvent next() {\r\n if (!hasNext()) {\r\n close();\r\n throw new NoSuchElementException();\r\n }\r\n final Tablet tablet = tabletIterator.next();\r\n final boolean isAligned = deviceIsAlignedMap.getOrDefault(tablet.deviceId, false);\r\n final TabletInsertionEvent next = new PipeRawTabletInsertionEvent(tablet, isAligned);\r\n if (!hasNext()) {\r\n close();\r\n }\r\n return next;\r\n }\r\n };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Optional getSuffix(final String link, FilePreferences filePreferences){\r\n String strippedLink = link;\r\n try {\r\n URL url = new URL(link);\r\n if ((url.getQuery() != null) && (url.getQuery().length() < (link.length() - 1))) {\r\n strippedLink = link.substring(0, link.length() - url.getQuery().length() - 1);\r\n }\r\n } catch (MalformedURLException e) {\r\n }\r\n String suffix;\r\n int strippedLinkIndex = strippedLink.lastIndexOf('.');\r\n if ((strippedLinkIndex <= 0) || (strippedLinkIndex == (strippedLink.length() - 1))) {\r\n suffix = null;\r\n } else {\r\n suffix = strippedLink.substring(strippedLinkIndex + 1);\r\n }\r\n if (!ExternalFileTypes.isExternalFileTypeByExt(suffix, filePreferences)) {\r\n int index = link.lastIndexOf('.');\r\n if ((index <= 0) || (index == (link.length() - 1))) {\r\n if (strippedLink.substring(strippedLinkIndex + 1).indexOf('/') >= 1) {\r\n return Optional.empty();\r\n } else {\r\n return Optional.of(suffix);\r\n }\r\n } else {\r\n if (link.substring(index + 1).indexOf('/') >= 1) {\r\n return Optional.empty();\r\n } else {\r\n return Optional.of(link.substring(index + 1));\r\n }\r\n }\r\n } else {\r\n return Optional.ofNullable(suffix);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Set getNeedRepairedPlacementNotAdheringFragments(LedgerHandle lh){\r\n if (!conf.isRepairedPlacementPolicyNotAdheringBookieEnable()) {\r\n return Collections.emptySet();\r\n }\r\n long ledgerId = lh.getId();\r\n Set placementNotAdheringFragments = new HashSet<>();\r\n CompletableFuture> future = ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadataVer, exception) -> {\r\n if (exception == null) {\r\n LedgerMetadata metadata = metadataVer.getValue();\r\n int writeQuorumSize = metadata.getWriteQuorumSize();\r\n int ackQuorumSize = metadata.getAckQuorumSize();\r\n if (!metadata.isClosed()) {\r\n return;\r\n }\r\n Long curEntryId = null;\r\n EnsemblePlacementPolicy.PlacementPolicyAdherence previousSegmentAdheringToPlacementPolicy = null;\r\n for (Map.Entry> entry : metadata.getAllEnsembles().entrySet()) {\r\n if (curEntryId != null) {\r\n if (EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL == previousSegmentAdheringToPlacementPolicy) {\r\n LedgerFragment ledgerFragment = new LedgerFragment(lh, curEntryId, entry.getKey() - 1, new HashSet<>());\r\n ledgerFragment.setReplicateType(LedgerFragment.ReplicateType.DATA_NOT_ADHERING_PLACEMENT);\r\n placementNotAdheringFragments.add(ledgerFragment);\r\n }\r\n }\r\n previousSegmentAdheringToPlacementPolicy = admin.isEnsembleAdheringToPlacementPolicy(entry.getValue(), writeQuorumSize, ackQuorumSize);\r\n curEntryId = entry.getKey();\r\n }\r\n if (curEntryId != null) {\r\n if (EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL == previousSegmentAdheringToPlacementPolicy) {\r\n long lastEntry = lh.getLedgerMetadata().getLastEntryId();\r\n LedgerFragment ledgerFragment = new LedgerFragment(lh, curEntryId, lastEntry, new HashSet<>());\r\n ledgerFragment.setReplicateType(LedgerFragment.ReplicateType.DATA_NOT_ADHERING_PLACEMENT);\r\n placementNotAdheringFragments.add(ledgerFragment);\r\n }\r\n }\r\n } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ignoring replication of already deleted ledger {}\", ledgerId);\r\n }\r\n } else {\r\n LOG.warn(\"Unable to read the ledger: {} information\", ledgerId);\r\n }\r\n });\r\n try {\r\n FutureUtils.result(future);\r\n } catch (Exception e) {\r\n LOG.warn(\"Check ledger need repaired placement not adhering bookie failed\", e);\r\n return Collections.emptySet();\r\n }\r\n return placementNotAdheringFragments;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String getReturnType(Operation operation, boolean isSignature) throws BallerinaOpenApiException{\r\n Set returnTypes = new HashSet<>();\r\n boolean noContentResponseFound = false;\r\n if (operation.getResponses() != null) {\r\n ApiResponses responses = operation.getResponses();\r\n for (Map.Entry entry : responses.entrySet()) {\r\n String statusCode = entry.getKey();\r\n ApiResponse response = entry.getValue();\r\n if (statusCode.startsWith(\"2\")) {\r\n Content content = response.getContent();\r\n if (content != null && content.size() > 0) {\r\n Set> mediaTypes = content.entrySet();\r\n for (Map.Entry media : mediaTypes) {\r\n String type = \"\";\r\n if (media.getValue().getSchema() != null) {\r\n Schema schema = media.getValue().getSchema();\r\n type = getDataType(operation, isSignature, response, media, type, schema);\r\n } else {\r\n type = GeneratorUtils.getBallerinaMediaType(media.getKey().trim(), false);\r\n }\r\n returnTypes.add(type);\r\n break;\r\n }\r\n } else {\r\n noContentResponseFound = true;\r\n }\r\n }\r\n }\r\n }\r\n if (returnTypes.size() > 0) {\r\n StringBuilder finalReturnType = new StringBuilder();\r\n finalReturnType.append(String.join(PIPE_TOKEN.stringValue(), returnTypes));\r\n finalReturnType.append(PIPE_TOKEN.stringValue());\r\n finalReturnType.append(ERROR);\r\n if (noContentResponseFound) {\r\n finalReturnType.append(NILLABLE);\r\n }\r\n return finalReturnType.toString();\r\n } else {\r\n return DEFAULT_RETURN;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static void checkSpecialLiterals(SqlWindow window, SqlValidator validator){\r\n final SqlNode lowerBound = window.getLowerBound();\r\n final SqlNode upperBound = window.getUpperBound();\r\n Object lowerLitType = null;\r\n Object upperLitType = null;\r\n SqlOperator lowerOp = null;\r\n SqlOperator upperOp = null;\r\n if (null != lowerBound) {\r\n if (lowerBound.getKind() == SqlKind.LITERAL) {\r\n lowerLitType = ((SqlLiteral) lowerBound).getValue();\r\n if (Bound.UNBOUNDED_FOLLOWING == lowerLitType) {\r\n throw validator.newValidationError(lowerBound, RESOURCE.badLowerBoundary());\r\n }\r\n } else if (lowerBound instanceof SqlCall) {\r\n lowerOp = ((SqlCall) lowerBound).getOperator();\r\n }\r\n }\r\n if (null != upperBound) {\r\n if (upperBound.getKind() == SqlKind.LITERAL) {\r\n upperLitType = ((SqlLiteral) upperBound).getValue();\r\n if (Bound.UNBOUNDED_PRECEDING == upperLitType) {\r\n throw validator.newValidationError(upperBound, RESOURCE.badUpperBoundary());\r\n }\r\n } else if (upperBound instanceof SqlCall) {\r\n upperOp = ((SqlCall) upperBound).getOperator();\r\n }\r\n }\r\n if (Bound.CURRENT_ROW == lowerLitType) {\r\n if (null != upperOp) {\r\n if (upperOp == PRECEDING_OPERATOR) {\r\n throw validator.newValidationError(castNonNull(upperBound), RESOURCE.currentRowPrecedingError());\r\n }\r\n }\r\n } else if (null != lowerOp) {\r\n if (lowerOp == FOLLOWING_OPERATOR) {\r\n if (null != upperOp) {\r\n if (upperOp == PRECEDING_OPERATOR) {\r\n throw validator.newValidationError(castNonNull(upperBound), RESOURCE.followingBeforePrecedingError());\r\n }\r\n } else if (null != upperLitType) {\r\n if (Bound.CURRENT_ROW == upperLitType) {\r\n throw validator.newValidationError(castNonNull(upperBound), RESOURCE.currentRowFollowingError());\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BaseDescr lhsOr(final CEDescrBuilder ce, boolean allowOr) throws RecognitionException{\r\n BaseDescr result = null;\r\n if (allowOr && input.LA(1) == DRL5Lexer.LEFT_PAREN && helper.validateLT(2, DroolsSoftKeywords.OR)) {\r\n CEDescrBuilder or = null;\r\n if (state.backtracking == 0) {\r\n or = ce.or();\r\n result = or.getDescr();\r\n helper.start(or, CEDescrBuilder.class, null);\r\n }\r\n try {\r\n match(input, DRL5Lexer.LEFT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.OR, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n while (input.LA(1) == DRL5Lexer.AT) {\r\n annotation(or);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);\r\n }\r\n while (input.LA(1) != DRL5Lexer.RIGHT_PAREN) {\r\n lhsAnd(or, allowOr);\r\n if (state.failed)\r\n return null;\r\n }\r\n match(input, DRL5Lexer.RIGHT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n } finally {\r\n if (state.backtracking == 0) {\r\n helper.end(CEDescrBuilder.class, or);\r\n }\r\n }\r\n } else {\r\n CEDescrBuilder or = null;\r\n if (state.backtracking == 0) {\r\n or = ce.or();\r\n result = or.getDescr();\r\n helper.start(or, CEDescrBuilder.class, null);\r\n }\r\n try {\r\n lhsAnd(or, allowOr);\r\n if (state.failed)\r\n return null;\r\n if (allowOr && (helper.validateIdentifierKey(DroolsSoftKeywords.OR) || input.LA(1) == DRL5Lexer.DOUBLE_PIPE)) {\r\n while (helper.validateIdentifierKey(DroolsSoftKeywords.OR) || input.LA(1) == DRL5Lexer.DOUBLE_PIPE) {\r\n if (input.LA(1) == DRL5Lexer.DOUBLE_PIPE) {\r\n match(input, DRL5Lexer.DOUBLE_PIPE, null, null, DroolsEditorType.SYMBOL);\r\n } else {\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.OR, null, DroolsEditorType.KEYWORD);\r\n }\r\n if (state.failed)\r\n return null;\r\n while (input.LA(1) == DRL5Lexer.AT) {\r\n annotation(or);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);\r\n }\r\n lhsAnd(or, allowOr);\r\n if (state.failed)\r\n return null;\r\n }\r\n } else if (allowOr) {\r\n if (state.backtracking == 0) {\r\n ((ConditionalElementDescr) ce.getDescr()).getDescrs().remove(or.getDescr());\r\n for (BaseDescr base : or.getDescr().getDescrs()) {\r\n ((ConditionalElementDescr) ce.getDescr()).addDescr(base);\r\n }\r\n result = ce.getDescr();\r\n }\r\n }\r\n } finally {\r\n if (state.backtracking == 0) {\r\n helper.end(CEDescrBuilder.class, or);\r\n }\r\n }\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public long scanJournal(long journalId, long journalPos, JournalScanner scanner) throws IOException{\r\n JournalChannel recLog;\r\n if (journalPos <= 0) {\r\n recLog = new JournalChannel(journalDirectory, journalId, journalPreAllocSize, journalWriteBufferSize, conf, fileChannelProvider);\r\n } else {\r\n recLog = new JournalChannel(journalDirectory, journalId, journalPreAllocSize, journalWriteBufferSize, journalPos, conf, fileChannelProvider);\r\n }\r\n int journalVersion = recLog.getFormatVersion();\r\n try {\r\n ByteBuffer lenBuff = ByteBuffer.allocate(4);\r\n ByteBuffer recBuff = ByteBuffer.allocate(64 * 1024);\r\n while (true) {\r\n long offset = recLog.fc.position();\r\n lenBuff.clear();\r\n fullRead(recLog, lenBuff);\r\n if (lenBuff.remaining() != 0) {\r\n break;\r\n }\r\n lenBuff.flip();\r\n int len = lenBuff.getInt();\r\n if (len == 0) {\r\n break;\r\n }\r\n boolean isPaddingRecord = false;\r\n if (len < 0) {\r\n if (len == PADDING_MASK && journalVersion >= JournalChannel.V5) {\r\n lenBuff.clear();\r\n fullRead(recLog, lenBuff);\r\n if (lenBuff.remaining() != 0) {\r\n break;\r\n }\r\n lenBuff.flip();\r\n len = lenBuff.getInt();\r\n if (len == 0) {\r\n continue;\r\n }\r\n isPaddingRecord = true;\r\n } else {\r\n LOG.error(\"Invalid record found with negative length: {}\", len);\r\n throw new IOException(\"Invalid record found with negative length \" + len);\r\n }\r\n }\r\n recBuff.clear();\r\n if (recBuff.remaining() < len) {\r\n recBuff = ByteBuffer.allocate(len);\r\n }\r\n recBuff.limit(len);\r\n if (fullRead(recLog, recBuff) != len) {\r\n break;\r\n }\r\n recBuff.flip();\r\n if (!isPaddingRecord) {\r\n scanner.process(journalVersion, offset, recBuff);\r\n }\r\n }\r\n return recLog.fc.position();\r\n } finally {\r\n recLog.close();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void discoverKieModules(){\r\n PortablePath[] configFiles = { KieModuleModelImpl.KMODULE_JAR_PATH, KieModuleModelImpl.KMODULE_SPRING_JAR_PATH };\r\n for (PortablePath configFile : configFiles) {\r\n final Set resources = new HashSet<>();\r\n try {\r\n ClassLoader currentClassLoader = classLoader;\r\n while (currentClassLoader != null) {\r\n Enumeration list = currentClassLoader.getResources(configFile.asString());\r\n while (list.hasMoreElements()) {\r\n resources.add(list.nextElement());\r\n }\r\n currentClassLoader = currentClassLoader.getParent();\r\n }\r\n } catch (IOException exc) {\r\n log.error(\"Unable to find and build index of \" + configFile.asString() + \".\" + exc.getMessage());\r\n return;\r\n }\r\n for (URL url : resources) {\r\n notifyKieModuleFound(url);\r\n try {\r\n InternalKieModule kModule = fetchKModule(url);\r\n if (kModule != null) {\r\n ReleaseId releaseId = kModule.getReleaseId();\r\n kieModules.put(releaseId, kModule);\r\n log.debug(\"Discovered classpath module \" + releaseId.toExternalForm());\r\n kieRepository.addKieModule(kModule);\r\n }\r\n } catch (Exception exc) {\r\n log.error(\"Unable to build index of kmodule.xml url=\" + url.toExternalForm() + \"\\n\" + exc.getMessage());\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Object parseValue(TSDataType dataType, String value) throws QueryProcessException{\r\n try {\r\n if (\"null\".equals(value) || \"NULL\".equals(value)) {\r\n return null;\r\n }\r\n switch(dataType) {\r\n case BOOLEAN:\r\n return parseBoolean(value);\r\n case INT32:\r\n try {\r\n return Integer.parseInt(StringUtils.trim(value));\r\n } catch (NumberFormatException e) {\r\n throw new NumberFormatException(\"data type is not consistent, input \" + value + \", registered \" + dataType);\r\n }\r\n case INT64:\r\n try {\r\n return Long.parseLong(StringUtils.trim(value));\r\n } catch (NumberFormatException e) {\r\n throw new NumberFormatException(\"data type is not consistent, input \" + value + \", registered \" + dataType);\r\n }\r\n case FLOAT:\r\n float f;\r\n try {\r\n f = Float.parseFloat(value);\r\n } catch (NumberFormatException e) {\r\n throw new NumberFormatException(\"data type is not consistent, input \" + value + \", registered \" + dataType);\r\n }\r\n if (Float.isInfinite(f)) {\r\n throw new NumberFormatException(\"The input float value is Infinity\");\r\n }\r\n return f;\r\n case DOUBLE:\r\n double d;\r\n try {\r\n d = Double.parseDouble(value);\r\n } catch (NumberFormatException e) {\r\n throw new NumberFormatException(\"data type is not consistent, input \" + value + \", registered \" + dataType);\r\n }\r\n if (Double.isInfinite(d)) {\r\n throw new NumberFormatException(\"The input double value is Infinity\");\r\n }\r\n return d;\r\n case TEXT:\r\n if ((value.startsWith(SqlConstant.QUOTE) && value.endsWith(SqlConstant.QUOTE)) || (value.startsWith(SqlConstant.DQUOTE) && value.endsWith(SqlConstant.DQUOTE))) {\r\n if (value.length() == 1) {\r\n return new Binary(value);\r\n } else {\r\n return new Binary(value.substring(1, value.length() - 1));\r\n }\r\n }\r\n return new Binary(value);\r\n default:\r\n throw new QueryProcessException(\"Unsupported data type:\" + dataType);\r\n }\r\n } catch (NumberFormatException e) {\r\n throw new QueryProcessException(e.getMessage());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void addLogSegmentToCache(String name, LogSegmentMetadata metadata){\r\n metadataCache.put(metadata.getZkPath(), metadata);\r\n logSegmentCache.add(name, metadata);\r\n if (!metadata.isInProgress() && (lastLedgerRollingTimeMillis < metadata.getCompletionTime())) {\r\n lastLedgerRollingTimeMillis = metadata.getCompletionTime();\r\n }\r\n if (reportGetSegmentStats) {\r\n long ts = System.currentTimeMillis();\r\n if (metadata.isInProgress()) {\r\n long elapsedMillis = ts - metadata.getFirstTxId();\r\n long elapsedMicroSec = TimeUnit.MILLISECONDS.toMicros(elapsedMillis);\r\n if (elapsedMicroSec > 0) {\r\n if (elapsedMillis > metadataLatencyWarnThresholdMillis) {\r\n LOG.warn(\"{} received inprogress log segment in {} millis: {}\", getFullyQualifiedName(), elapsedMillis, metadata);\r\n }\r\n getInprogressSegmentStat.registerSuccessfulEvent(elapsedMicroSec, TimeUnit.MICROSECONDS);\r\n } else {\r\n negativeGetInprogressSegmentStat.registerSuccessfulEvent(-elapsedMicroSec, TimeUnit.MICROSECONDS);\r\n }\r\n } else {\r\n long elapsedMillis = ts - metadata.getCompletionTime();\r\n long elapsedMicroSec = TimeUnit.MILLISECONDS.toMicros(elapsedMillis);\r\n if (elapsedMicroSec > 0) {\r\n if (elapsedMillis > metadataLatencyWarnThresholdMillis) {\r\n LOG.warn(\"{} received completed log segment in {} millis : {}\", getFullyQualifiedName(), elapsedMillis, metadata);\r\n }\r\n getCompletedSegmentStat.registerSuccessfulEvent(elapsedMicroSec, TimeUnit.MICROSECONDS);\r\n } else {\r\n negativeGetCompletedSegmentStat.registerSuccessfulEvent(-elapsedMicroSec, TimeUnit.MICROSECONDS);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " boolean connect() throws SQLException{\r\n try {\r\n if (driver != null && driver.length() != 0) {\r\n Class.forName(driver);\r\n }\r\n } catch (ClassNotFoundException cnfe) {\r\n return beeLine.error(cnfe);\r\n }\r\n boolean isDriverRegistered = false;\r\n try {\r\n isDriverRegistered = DriverManager.getDriver(getUrl()) != null;\r\n } catch (Exception e) {\r\n }\r\n try {\r\n close();\r\n } catch (Exception e) {\r\n return beeLine.error(e);\r\n }\r\n Map hiveVars = beeLine.getOpts().getHiveVariables();\r\n if (hiveVars != null) {\r\n for (Map.Entry var : hiveVars.entrySet()) {\r\n info.put(HIVE_VAR_PREFIX + var.getKey(), var.getValue());\r\n }\r\n }\r\n Map hiveConfVars = beeLine.getOpts().getHiveConfVariables();\r\n if (hiveConfVars != null) {\r\n for (Map.Entry var : hiveConfVars.entrySet()) {\r\n info.put(HIVE_CONF_PREFIX + var.getKey(), var.getValue());\r\n }\r\n }\r\n if (isDriverRegistered) {\r\n setConnection(DriverManager.getConnection(getUrl(), info));\r\n } else {\r\n beeLine.debug(\"Use the driver from local added jar file.\");\r\n setConnection(getConnectionFromLocalDriver(getUrl(), info));\r\n }\r\n setDatabaseMetaData(getConnection().getMetaData());\r\n try {\r\n beeLine.info(beeLine.loc(\"connected\", new Object[] { getDatabaseMetaData().getDatabaseProductName(), getDatabaseMetaData().getDatabaseProductVersion() }));\r\n } catch (Exception e) {\r\n beeLine.handleException(e);\r\n }\r\n try {\r\n beeLine.info(beeLine.loc(\"driver\", new Object[] { getDatabaseMetaData().getDriverName(), getDatabaseMetaData().getDriverVersion() }));\r\n } catch (Exception e) {\r\n beeLine.handleException(e);\r\n }\r\n try {\r\n getConnection().setAutoCommit(beeLine.getOpts().getAutoCommit());\r\n } catch (Exception e) {\r\n beeLine.handleException(e);\r\n }\r\n try {\r\n beeLine.getCommands().isolation(\"isolation: \" + beeLine.getOpts().getIsolation());\r\n } catch (Exception e) {\r\n beeLine.handleException(e);\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void readLogSegmentsFromStore(final Versioned> logSegmentNames, final Comparator comparator, final LogSegmentFilter segmentFilter, final CompletableFuture>> readResult){\r\n Set segmentsReceived = new HashSet();\r\n segmentsReceived.addAll(segmentFilter.filter(logSegmentNames.getValue()));\r\n Set segmentsAdded;\r\n final Set removedSegments = Collections.synchronizedSet(new HashSet());\r\n final Map addedSegments = Collections.synchronizedMap(new HashMap());\r\n Pair, Set> segmentChanges = logSegmentCache.diff(segmentsReceived);\r\n segmentsAdded = segmentChanges.getLeft();\r\n removedSegments.addAll(segmentChanges.getRight());\r\n if (segmentsAdded.isEmpty()) {\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"No segments added for {}.\", getFullyQualifiedName());\r\n }\r\n updateLogSegmentCache(removedSegments, addedSegments);\r\n List segmentList;\r\n try {\r\n segmentList = getCachedLogSegments(comparator);\r\n } catch (UnexpectedException e) {\r\n readResult.completeExceptionally(e);\r\n return;\r\n }\r\n readResult.complete(new Versioned>(segmentList, logSegmentNames.getVersion()));\r\n return;\r\n }\r\n final AtomicInteger numChildren = new AtomicInteger(segmentsAdded.size());\r\n final AtomicInteger numFailures = new AtomicInteger(0);\r\n for (final String segment : segmentsAdded) {\r\n String logSegmentPath = logMetadata.getLogSegmentPath(segment);\r\n LogSegmentMetadata cachedSegment = metadataCache.get(logSegmentPath);\r\n if (null != cachedSegment) {\r\n addedSegments.put(segment, cachedSegment);\r\n completeReadLogSegmentsFromStore(removedSegments, addedSegments, comparator, readResult, logSegmentNames.getVersion(), numChildren, numFailures);\r\n continue;\r\n }\r\n metadataStore.getLogSegment(logSegmentPath).whenComplete(new FutureEventListener() {\r\n\r\n @Override\r\n public void onSuccess(LogSegmentMetadata result) {\r\n addedSegments.put(segment, result);\r\n complete();\r\n }\r\n\r\n @Override\r\n public void onFailure(Throwable cause) {\r\n if (cause instanceof LogSegmentNotFoundException) {\r\n removedSegments.add(segment);\r\n complete();\r\n } else {\r\n if (1 == numFailures.incrementAndGet()) {\r\n readResult.completeExceptionally(cause);\r\n return;\r\n }\r\n }\r\n }\r\n\r\n private void complete() {\r\n completeReadLogSegmentsFromStore(removedSegments, addedSegments, comparator, readResult, logSegmentNames.getVersion(), numChildren, numFailures);\r\n }\r\n });\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Result delete(final SyncDelta delta, final List matches, final Provision provision) throws JobExecutionException{\r\n if (!profile.getTask().isPerformDelete()) {\r\n LOG.debug(\"PullTask not configured for delete\");\r\n end(provision.getAnyType(), ResourceOperation.DELETE.name().toLowerCase(), Result.SUCCESS, null, null, delta);\r\n return Result.SUCCESS;\r\n }\r\n LOG.debug(\"About to delete {}\", matches);\r\n Result global = Result.SUCCESS;\r\n for (PullMatch match : matches) {\r\n Object output;\r\n Result resultStatus = Result.FAILURE;\r\n ProvisioningReport result = new ProvisioningReport();\r\n try {\r\n AnyTO before = getAnyTO(match.getAny());\r\n result.setKey(match.getAny().getKey());\r\n result.setName(getName(before));\r\n result.setOperation(ResourceOperation.DELETE);\r\n result.setAnyType(provision.getAnyType());\r\n result.setStatus(ProvisioningReport.Status.SUCCESS);\r\n result.setUidValue(delta.getUid().getUidValue());\r\n if (!profile.isDryRun()) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeDelete(profile, delta, before);\r\n }\r\n try {\r\n getProvisioningManager().delete(match.getAny().getKey(), Set.of(profile.getTask().getResource().getKey()), true, profile.getExecutor(), getContext());\r\n output = null;\r\n resultStatus = Result.SUCCESS;\r\n for (PullActions action : profile.getActions()) {\r\n action.after(profile, delta, before, result);\r\n }\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not delete {} {}\", provision.getAnyType(), match, e);\r\n output = e;\r\n if (profile.getTask().isRemediation()) {\r\n resultStatus = Result.SUCCESS;\r\n createRemediation(provision.getAnyType(), match.getAny().getKey(), null, null, result, delta);\r\n }\r\n }\r\n end(provision.getAnyType(), ResourceOperation.DELETE.name().toLowerCase(), resultStatus, before, output, delta);\r\n global = and(global, resultStatus);\r\n }\r\n profile.getResults().add(result);\r\n } catch (NotFoundException e) {\r\n LOG.error(\"Could not find {} {}\", provision.getAnyType(), match, e);\r\n } catch (DelegatedAdministrationException e) {\r\n LOG.error(\"Not allowed to read {} {}\", provision.getAnyType(), match, e);\r\n } catch (Exception e) {\r\n LOG.error(\"Could not delete {} {}\", provision.getAnyType(), match, e);\r\n }\r\n }\r\n return global;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Patch parseUnifiedDiff(List diff){\r\n boolean inPrelude = true;\r\n List rawChunk = new ArrayList<>();\r\n Patch patch = new Patch<>();\r\n int old_ln = 0, new_ln = 0;\r\n String tag;\r\n String rest;\r\n for (String line : diff) {\r\n if (inPrelude) {\r\n if (line.startsWith(\"+++\")) {\r\n inPrelude = false;\r\n }\r\n continue;\r\n }\r\n Matcher m = unifiedDiffChunkRe.matcher(line);\r\n if (m.find()) {\r\n if (rawChunk.size() != 0) {\r\n List oldChunkLines = new ArrayList<>();\r\n List newChunkLines = new ArrayList<>();\r\n for (String[] raw_line : rawChunk) {\r\n tag = raw_line[0];\r\n rest = raw_line[1];\r\n if (tag.equals(\" \") || tag.equals(\"-\")) {\r\n oldChunkLines.add(rest);\r\n }\r\n if (tag.equals(\" \") || tag.equals(\"+\")) {\r\n newChunkLines.add(rest);\r\n }\r\n }\r\n patch.addDelta(new ChangeDelta<>(new Chunk<>(old_ln - 1, oldChunkLines), new Chunk<>(new_ln - 1, newChunkLines)));\r\n rawChunk.clear();\r\n }\r\n old_ln = m.group(1) == null ? 1 : Integer.parseInt(m.group(1));\r\n new_ln = m.group(3) == null ? 1 : Integer.parseInt(m.group(3));\r\n if (old_ln == 0) {\r\n old_ln += 1;\r\n }\r\n if (new_ln == 0) {\r\n new_ln += 1;\r\n }\r\n } else {\r\n if (line.length() > 0) {\r\n tag = line.substring(0, 1);\r\n rest = line.substring(1);\r\n if (tag.equals(\" \") || tag.equals(\"+\") || tag.equals(\"-\")) {\r\n rawChunk.add(new String[] { tag, rest });\r\n }\r\n } else {\r\n rawChunk.add(new String[] { \" \", \"\" });\r\n }\r\n }\r\n }\r\n if (rawChunk.size() != 0) {\r\n List oldChunkLines = new ArrayList<>();\r\n List newChunkLines = new ArrayList<>();\r\n for (String[] raw_line : rawChunk) {\r\n tag = raw_line[0];\r\n rest = raw_line[1];\r\n if (tag.equals(\" \") || tag.equals(\"-\")) {\r\n oldChunkLines.add(rest);\r\n }\r\n if (tag.equals(\" \") || tag.equals(\"+\")) {\r\n newChunkLines.add(rest);\r\n }\r\n }\r\n patch.addDelta(new ChangeDelta<>(new Chunk<>(old_ln - 1, oldChunkLines), new Chunk<>(new_ln - 1, newChunkLines)));\r\n rawChunk.clear();\r\n }\r\n return patch;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ScheduledFuture scheduleIdleReaderTaskIfNecessary(){\r\n if (idleErrorThresholdMillis < Integer.MAX_VALUE) {\r\n long period = Math.max(idleErrorThresholdMillis / 10, 1000);\r\n period = Math.min(period, idleErrorThresholdMillis / 5);\r\n return scheduler.scheduleAtFixedRateOrdered(streamName, () -> {\r\n PendingReadRequest nextRequest = pendingRequests.peek();\r\n idleReaderCheckCount.inc();\r\n if (null == nextRequest) {\r\n return;\r\n }\r\n idleReaderCheckIdleReadRequestCount.inc();\r\n if (nextRequest.elapsedSinceEnqueue(TimeUnit.MILLISECONDS) < idleErrorThresholdMillis) {\r\n return;\r\n }\r\n ReadAheadEntryReader readAheadReader = getReadAheadReader();\r\n idleReaderCheckIdleReadAheadCount.inc();\r\n try {\r\n if (null == readAheadReader || (!hasMoreRecords() && readAheadReader.isReaderIdle(idleErrorThresholdMillis, TimeUnit.MILLISECONDS))) {\r\n markReaderAsIdle();\r\n return;\r\n } else if (lastProcessTime.elapsed(TimeUnit.MILLISECONDS) > idleErrorThresholdMillis) {\r\n markReaderAsIdle();\r\n }\r\n } catch (IOException e) {\r\n setLastException(e);\r\n return;\r\n }\r\n }, period, period, TimeUnit.MILLISECONDS);\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void requestMemberListUpdateIfUnknownMembersFound(Address sender, InternalPartition[] partitions){\r\n ClusterServiceImpl clusterService = node.clusterService;\r\n ClusterState clusterState = clusterService.getClusterState();\r\n Set unknownReplicas = new HashSet<>();\r\n for (InternalPartition partition : partitions) {\r\n for (int index = 0; index < InternalPartition.MAX_REPLICA_COUNT; index++) {\r\n PartitionReplica replica = partition.getReplica(index);\r\n if (replica == null) {\r\n continue;\r\n }\r\n if (node.clusterService.getMember(replica.address(), replica.uuid()) == null && (clusterState.isJoinAllowed() || !clusterService.isMissingMember(replica.address(), replica.uuid()))) {\r\n unknownReplicas.add(replica);\r\n }\r\n }\r\n }\r\n if (!unknownReplicas.isEmpty()) {\r\n if (logger.isWarningEnabled()) {\r\n StringBuilder s = new StringBuilder(\"Following unknown addresses are found in partition table\").append(\" sent from master[\").append(sender).append(\"].\").append(\" (Probably they have recently joined or left the cluster.)\").append(\" {\");\r\n for (PartitionReplica replica : unknownReplicas) {\r\n s.append(\"\\n\\t\").append(replica);\r\n }\r\n s.append(\"\\n}\");\r\n logger.warning(s.toString());\r\n }\r\n Address masterAddress = node.getClusterService().getMasterAddress();\r\n if (masterAddress != null && !masterAddress.equals(node.getThisAddress())) {\r\n nodeEngine.getOperationService().send(new TriggerMemberListPublishOp(), masterAddress);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void diff(final AnyTO updated, final AnyTO original, final AnyUR result, final boolean incremental){\r\n if (updated.getKey() == null && original.getKey() != null || (updated.getKey() != null && !updated.getKey().equals(original.getKey()))) {\r\n throw new IllegalArgumentException(\"AnyTO's key must be the same\");\r\n }\r\n result.setKey(updated.getKey());\r\n result.setRealm(replacePatchItem(updated.getRealm(), original.getRealm(), new StringReplacePatchItem()));\r\n result.getAuxClasses().clear();\r\n if (!incremental) {\r\n original.getAuxClasses().stream().filter(auxClass -> !updated.getAuxClasses().contains(auxClass)).forEach(auxClass -> result.getAuxClasses().add(new StringPatchItem.Builder().operation(PatchOperation.DELETE).value(auxClass).build()));\r\n }\r\n updated.getAuxClasses().stream().filter(auxClass -> !original.getAuxClasses().contains(auxClass)).forEach(auxClass -> result.getAuxClasses().add(new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value(auxClass).build()));\r\n Map updatedAttrs = EntityTOUtils.buildAttrMap(updated.getPlainAttrs());\r\n Map originalAttrs = EntityTOUtils.buildAttrMap(original.getPlainAttrs());\r\n result.getPlainAttrs().clear();\r\n if (!incremental) {\r\n originalAttrs.keySet().stream().filter(attr -> !updatedAttrs.containsKey(attr)).forEach(schema -> result.getPlainAttrs().add(new AttrPatch.Builder(new Attr.Builder(schema).build()).operation(PatchOperation.DELETE).build()));\r\n }\r\n updatedAttrs.values().forEach(attr -> {\r\n if (isEmpty(attr)) {\r\n if (!incremental) {\r\n result.getPlainAttrs().add(new AttrPatch.Builder(new Attr.Builder(attr.getSchema()).build()).operation(PatchOperation.DELETE).build());\r\n }\r\n } else if (!originalAttrs.containsKey(attr.getSchema()) || !originalAttrs.get(attr.getSchema()).getValues().equals(attr.getValues())) {\r\n AttrPatch patch = new AttrPatch.Builder(attr).operation(PatchOperation.ADD_REPLACE).build();\r\n if (!patch.isEmpty()) {\r\n result.getPlainAttrs().add(patch);\r\n }\r\n }\r\n });\r\n result.getVirAttrs().clear();\r\n result.getVirAttrs().addAll(updated.getVirAttrs());\r\n result.getResources().clear();\r\n if (!incremental) {\r\n original.getResources().stream().filter(resource -> !updated.getResources().contains(resource)).forEach(resource -> result.getResources().add(new StringPatchItem.Builder().operation(PatchOperation.DELETE).value(resource).build()));\r\n }\r\n updated.getResources().stream().filter(resource -> !original.getResources().contains(resource)).forEach(resource -> result.getResources().add(new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value(resource).build()));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List determineDifferences(Object a, Object b, List parentPath, Map> comparatorByPropertyOrField, TypeComparators comparatorByType){\r\n final Set visited = new HashSet<>();\r\n final Deque toCompare = initStack(a, b, parentPath, comparatorByPropertyOrField, comparatorByType);\r\n final List differences = new ArrayList<>();\r\n while (!toCompare.isEmpty()) {\r\n final DualKey dualKey = toCompare.removeFirst();\r\n visited.add(dualKey);\r\n final List currentPath = dualKey.getPath();\r\n final Object key1 = dualKey.key1;\r\n final Object key2 = dualKey.key2;\r\n if (key1 == key2) {\r\n continue;\r\n }\r\n if (hasCustomComparator(dualKey, comparatorByPropertyOrField, comparatorByType)) {\r\n if (propertyOrFieldValuesAreEqual(key1, key2, dualKey.getConcatenatedPath(), comparatorByPropertyOrField, comparatorByType))\r\n continue;\r\n }\r\n if (key1 == null || key2 == null) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n if (key1 instanceof Collection) {\r\n if (!(key2 instanceof Collection)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n } else if (key2 instanceof Collection) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n if (key1 instanceof SortedSet) {\r\n if (!(key2 instanceof SortedSet)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n } else if (key2 instanceof SortedSet) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n if (key1 instanceof SortedMap) {\r\n if (!(key2 instanceof SortedMap)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n } else if (key2 instanceof SortedMap) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n if (key1 instanceof Map) {\r\n if (!(key2 instanceof Map)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n } else if (key2 instanceof Map) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n if (key1.getClass().isArray()) {\r\n if (!compareArrays(key1, key2, currentPath, toCompare, visited)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (key1 instanceof SortedSet) {\r\n if (!compareOrderedCollection((Collection) key1, (Collection) key2, currentPath, toCompare, visited)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (key1 instanceof List) {\r\n if (!compareOrderedCollection((Collection) key1, (Collection) key2, currentPath, toCompare, visited)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (key1 instanceof Collection) {\r\n if (!compareUnorderedCollection((Collection) key1, (Collection) key2, currentPath, toCompare, visited, comparatorByPropertyOrField, comparatorByType)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (key1 instanceof SortedMap) {\r\n if (!compareSortedMap((SortedMap) key1, (SortedMap) key2, currentPath, toCompare, visited)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (key1 instanceof Map) {\r\n if (!compareUnorderedMap((Map) key1, (Map) key2, currentPath, toCompare, visited)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n if (hasCustomEquals(key1.getClass())) {\r\n if (!key1.equals(key2)) {\r\n differences.add(new Difference(currentPath, key1, key2));\r\n continue;\r\n }\r\n continue;\r\n }\r\n Set key1FieldsNames = getFieldsNames(getDeclaredFieldsIncludingInherited(key1.getClass()));\r\n Set key2FieldsNames = getFieldsNames(getDeclaredFieldsIncludingInherited(key2.getClass()));\r\n if (!key2FieldsNames.containsAll(key1FieldsNames)) {\r\n Set key1FieldsNamesNotInKey2 = newHashSet(key1FieldsNames);\r\n key1FieldsNamesNotInKey2.removeAll(key2FieldsNames);\r\n String missingFields = key1FieldsNamesNotInKey2.toString();\r\n String key2ClassName = key2.getClass().getName();\r\n String key1ClassName = key1.getClass().getName();\r\n String missingFieldsDescription = format(MISSING_FIELDS, key1ClassName, key2ClassName, key2.getClass().getSimpleName(), key1.getClass().getSimpleName(), missingFields);\r\n differences.add(new Difference(currentPath, key1, key2, missingFieldsDescription));\r\n } else {\r\n for (String fieldName : key1FieldsNames) {\r\n List path = new ArrayList<>(currentPath);\r\n path.add(fieldName);\r\n DualKey dk = new DualKey(path, COMPARISON.getSimpleValue(fieldName, key1), COMPARISON.getSimpleValue(fieldName, key2));\r\n if (!visited.contains(dk)) {\r\n toCompare.addFirst(dk);\r\n }\r\n }\r\n }\r\n }\r\n return differences;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected MethodCallExpr buildTemporalExpression(SingleDrlxParseSuccess drlxParseResult, MethodCallExpr exprDSL){\r\n boolean thisOnRight = isThisOnRight(drlxParseResult);\r\n if (thisOnRight) {\r\n if (drlxParseResult.getRight() != null && !drlxParseResult.getRight().getExpression().isNameExpr()) {\r\n exprDSL.addArgument(generateLambdaForTemporalConstraint(drlxParseResult.getRight(), drlxParseResult.getPatternType()));\r\n }\r\n } else {\r\n if (drlxParseResult.getLeft() != null && !drlxParseResult.getLeft().getExpression().isNameExpr()) {\r\n exprDSL.addArgument(generateLambdaForTemporalConstraint(drlxParseResult.getLeft(), drlxParseResult.getPatternType()));\r\n }\r\n }\r\n drlxParseResult.getUsedDeclarations().stream().filter(s -> !(drlxParseResult.isSkipThisAsParam() && s.equals(drlxParseResult.getPatternBinding()))).map(context::getVarExpr).forEach(exprDSL::addArgument);\r\n if (drlxParseResult.getRightLiteral() != null) {\r\n exprDSL.addArgument(\"\" + drlxParseResult.getRightLiteral());\r\n } else {\r\n if (thisOnRight) {\r\n if (drlxParseResult.getLeft() != null && !drlxParseResult.getLeft().getExpression().isNameExpr()) {\r\n exprDSL.addArgument(generateLambdaForTemporalConstraint(drlxParseResult.getLeft(), drlxParseResult.getPatternType()));\r\n }\r\n } else {\r\n if (drlxParseResult.getRight() != null && !drlxParseResult.getRight().getExpression().isNameExpr()) {\r\n exprDSL.addArgument(generateLambdaForTemporalConstraint(drlxParseResult.getRight(), drlxParseResult.getPatternType()));\r\n }\r\n }\r\n }\r\n if (thisOnRight) {\r\n exprDSL.addArgument(buildConstraintExpression(drlxParseResult, new MethodCallExpr(drlxParseResult.getExpr(), \"thisOnRight\")));\r\n } else {\r\n exprDSL.addArgument(buildConstraintExpression(drlxParseResult, drlxParseResult.getExpr()));\r\n }\r\n return exprDSL;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String unBox(String type){\r\n if (\"java.lang.Byte\".equals(type) || \"Byte\".equals(type)) {\r\n return getInternalType(\"byte\");\r\n } else if (\"java.lang.Character\".equals(type) || \"Character\".equals(type)) {\r\n return getInternalType(\"char\");\r\n } else if (\"java.lang.Double\".equals(type) || \"Double\".equals(type)) {\r\n return getInternalType(\"double\");\r\n } else if (\"java.lang.Float\".equals(type) || \"Float\".equals(type)) {\r\n return getInternalType(\"float\");\r\n } else if (\"java.lang.Integer\".equals(type) || \"Integer\".equals(type)) {\r\n return getInternalType(\"int\");\r\n } else if (\"java.lang.Long\".equals(type) || \"Long\".equals(type)) {\r\n return getInternalType(\"long\");\r\n } else if (\"java.lang.Short\".equals(type) || \"Short\".equals(type)) {\r\n return getInternalType(\"short\");\r\n } else if (\"java.lang.Boolean\".equals(type) || \"Boolean\".equals(type)) {\r\n return getInternalType(\"boolean\");\r\n } else {\r\n throw new RuntimeException(\"Unable to recognize boxed primitive type \" + type);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static int compare(EnumSet set1, EnumSet set2){\r\n final Iterator i1 = set1.iterator();\r\n final Iterator i2 = set2.iterator();\r\n int floor = MIN_PRIORITY;\r\n while (i1.hasNext() || i2.hasNext()) {\r\n int p1, p2;\r\n do {\r\n p1 = i1.hasNext() ? i1.next().getPriority() : MAX_PRIORITY;\r\n } while (p1 == floor);\r\n do {\r\n p2 = i2.hasNext() ? i2.next().getPriority() : MAX_PRIORITY;\r\n } while (p2 == floor);\r\n if (p1 < p2)\r\n return -1;\r\n if (p1 > p2)\r\n return 1;\r\n floor = p1;\r\n }\r\n return 0;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doExtract(final ContentHandler handler, final Any any, final Set missing, final Set misaligned) throws SAXException{\r\n AttributesImpl atts = new AttributesImpl();\r\n for (Feature feature : conf.getFeatures()) {\r\n String type = null;\r\n String value = null;\r\n switch(feature) {\r\n case key:\r\n type = ReportXMLConst.XSD_STRING;\r\n value = any.getKey();\r\n break;\r\n case username:\r\n if (any instanceof User) {\r\n type = ReportXMLConst.XSD_STRING;\r\n value = User.class.cast(any).getUsername();\r\n }\r\n break;\r\n case groupName:\r\n if (any instanceof Group) {\r\n type = ReportXMLConst.XSD_STRING;\r\n value = Group.class.cast(any).getName();\r\n }\r\n break;\r\n case status:\r\n type = ReportXMLConst.XSD_STRING;\r\n value = any.getStatus();\r\n break;\r\n case creationDate:\r\n type = ReportXMLConst.XSD_DATETIME;\r\n value = any.getCreationDate() == null ? StringUtils.EMPTY : FormatUtils.format(any.getCreationDate());\r\n break;\r\n case lastLoginDate:\r\n if (any instanceof User) {\r\n type = ReportXMLConst.XSD_DATETIME;\r\n value = User.class.cast(any).getLastLoginDate() == null ? StringUtils.EMPTY : FormatUtils.format(User.class.cast(any).getLastLoginDate());\r\n }\r\n break;\r\n case changePwdDate:\r\n if (any instanceof User) {\r\n type = ReportXMLConst.XSD_DATETIME;\r\n value = User.class.cast(any).getChangePwdDate() == null ? StringUtils.EMPTY : FormatUtils.format(User.class.cast(any).getChangePwdDate());\r\n }\r\n break;\r\n case passwordHistorySize:\r\n if (any instanceof User) {\r\n type = ReportXMLConst.XSD_INT;\r\n value = String.valueOf(User.class.cast(any).getPasswordHistory().size());\r\n }\r\n break;\r\n case failedLoginCount:\r\n if (any instanceof User) {\r\n type = ReportXMLConst.XSD_INT;\r\n value = String.valueOf(User.class.cast(any).getFailedLogins());\r\n }\r\n break;\r\n default:\r\n }\r\n if (type != null && value != null) {\r\n atts.addAttribute(\"\", \"\", feature.name(), type, value);\r\n }\r\n }\r\n handler.startElement(\"\", \"\", getAnyElementName(any.getType().getKind()), atts);\r\n for (Missing item : missing) {\r\n atts.clear();\r\n atts.addAttribute(\"\", \"\", \"resource\", ReportXMLConst.XSD_STRING, item.getResource());\r\n atts.addAttribute(\"\", \"\", \"connObjectKeyValue\", ReportXMLConst.XSD_STRING, item.getConnObjectKeyValue());\r\n handler.startElement(\"\", \"\", \"missing\", atts);\r\n handler.endElement(\"\", \"\", \"missing\");\r\n }\r\n for (Misaligned item : misaligned) {\r\n atts.clear();\r\n atts.addAttribute(\"\", \"\", \"resource\", ReportXMLConst.XSD_STRING, item.getResource());\r\n atts.addAttribute(\"\", \"\", \"connObjectKeyValue\", ReportXMLConst.XSD_STRING, item.getConnObjectKeyValue());\r\n atts.addAttribute(\"\", \"\", ReportXMLConst.ATTR_NAME, ReportXMLConst.XSD_STRING, item.getName());\r\n handler.startElement(\"\", \"\", \"misaligned\", atts);\r\n handler.startElement(\"\", \"\", \"onSyncope\", null);\r\n if (item.getOnSyncope() != null) {\r\n for (Object value : item.getOnSyncope()) {\r\n char[] asChars = value.toString().toCharArray();\r\n handler.startElement(\"\", \"\", \"value\", null);\r\n handler.characters(asChars, 0, asChars.length);\r\n handler.endElement(\"\", \"\", \"value\");\r\n }\r\n }\r\n handler.endElement(\"\", \"\", \"onSyncope\");\r\n handler.startElement(\"\", \"\", \"onResource\", null);\r\n if (item.getOnResource() != null) {\r\n for (Object value : item.getOnResource()) {\r\n char[] asChars = value.toString().toCharArray();\r\n handler.startElement(\"\", \"\", \"value\", null);\r\n handler.characters(asChars, 0, asChars.length);\r\n handler.endElement(\"\", \"\", \"value\");\r\n }\r\n }\r\n handler.endElement(\"\", \"\", \"onResource\");\r\n handler.endElement(\"\", \"\", \"misaligned\");\r\n }\r\n handler.endElement(\"\", \"\", getAnyElementName(any.getType().getKind()));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doProcess(Exchange exchange) throws Exception{\r\n if (session == null && !lazySessionCreation) {\r\n throw new IllegalStateException(\"Not started yet!\");\r\n }\r\n if (session == null || !session.isConnected()) {\r\n openConnection();\r\n }\r\n if (getEndpoint().getConfiguration().getCharsetName() != null) {\r\n exchange.setProperty(ExchangePropertyKey.CHARSET_NAME, IOHelper.normalizeCharset(getEndpoint().getConfiguration().getCharsetName()));\r\n }\r\n Object body = MinaPayloadHelper.getIn(getEndpoint(), exchange);\r\n if (body == null) {\r\n noReplyLogger.log(\"No payload to send for exchange: \" + exchange);\r\n return;\r\n }\r\n if (getEndpoint().getConfiguration().isTextline()) {\r\n body = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);\r\n }\r\n if (sync) {\r\n responseLatch = new CountDownLatch(1);\r\n handler.reset();\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n Object out = body;\r\n if (body instanceof byte[]) {\r\n out = exchange.getContext().getTypeConverter().convertTo(String.class, body);\r\n }\r\n LOG.debug(\"Writing body: {}\", out);\r\n }\r\n MinaHelper.writeBody(session, body, exchange, writeTimeout);\r\n if (sync) {\r\n LOG.debug(\"Waiting for response using timeout {} millis.\", timeout);\r\n boolean done = responseLatch.await(timeout, TimeUnit.MILLISECONDS);\r\n if (!done) {\r\n maybeDisconnectOnTimeout();\r\n throw new ExchangeTimedOutException(exchange, timeout);\r\n }\r\n if (handler.getCause() != null) {\r\n throw new CamelExchangeException(\"Error occurred in ResponseHandler\", exchange, handler.getCause());\r\n } else if (!handler.isMessageReceived()) {\r\n maybeDisconnectOnTimeout();\r\n throw new ExchangeTimedOutException(exchange, timeout);\r\n } else {\r\n if (ExchangeHelper.isOutCapable(exchange)) {\r\n MinaPayloadHelper.setOut(exchange, handler.getMessage());\r\n } else {\r\n MinaPayloadHelper.setIn(exchange, handler.getMessage());\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ClassFile buildClassFile(final int classNum){\r\n final ClassFile classFile = new ClassFile();\r\n final int[] major = classBands.getClassVersionMajor();\r\n final int[] minor = classBands.getClassVersionMinor();\r\n if (major != null) {\r\n classFile.major = major[classNum];\r\n classFile.minor = minor[classNum];\r\n } else {\r\n classFile.major = header.getDefaultClassMajorVersion();\r\n classFile.minor = header.getDefaultClassMinorVersion();\r\n }\r\n final ClassConstantPool cp = classFile.pool;\r\n final int fullNameIndexInCpClass = classBands.getClassThisInts()[classNum];\r\n final String fullName = cpBands.getCpClass()[fullNameIndexInCpClass];\r\n int i = fullName.lastIndexOf(\"/\") + 1;\r\n final List classAttributes = classBands.getClassAttributes()[classNum];\r\n SourceFileAttribute sourceFileAttribute = null;\r\n for (final Attribute classAttribute : classAttributes) {\r\n if (classAttribute.isSourceFileAttribute()) {\r\n sourceFileAttribute = ((SourceFileAttribute) classAttribute);\r\n }\r\n }\r\n if (sourceFileAttribute == null) {\r\n final AttributeLayout SOURCE_FILE = attrDefinitionBands.getAttributeDefinitionMap().getAttributeLayout(AttributeLayout.ATTRIBUTE_SOURCE_FILE, AttributeLayout.CONTEXT_CLASS);\r\n if (SOURCE_FILE.matches(classBands.getRawClassFlags()[classNum])) {\r\n int firstDollar = -1;\r\n for (int index = 0; index < fullName.length(); ++index) {\r\n if (fullName.charAt(index) <= '$') {\r\n firstDollar = index;\r\n }\r\n }\r\n String fileName = null;\r\n if (firstDollar > -1 && (i <= firstDollar)) {\r\n fileName = fullName.substring(i, firstDollar) + \".java\";\r\n } else {\r\n fileName = fullName.substring(i) + \".java\";\r\n }\r\n sourceFileAttribute = new SourceFileAttribute(cpBands.cpUTF8Value(fileName, false));\r\n classFile.attributes = new Attribute[] { (Attribute) cp.add(sourceFileAttribute) };\r\n } else {\r\n classFile.attributes = new Attribute[] {};\r\n }\r\n } else {\r\n classFile.attributes = new Attribute[] { (Attribute) cp.add(sourceFileAttribute) };\r\n }\r\n final List classAttributesWithoutSourceFileAttribute = new ArrayList<>(classAttributes.size());\r\n for (int index = 0; index < classAttributes.size(); ++index) {\r\n final Attribute attrib = classAttributes.get(index);\r\n if (!attrib.isSourceFileAttribute()) {\r\n classAttributesWithoutSourceFileAttribute.add(attrib);\r\n }\r\n }\r\n final Attribute[] originalAttributes = classFile.attributes;\r\n classFile.attributes = new Attribute[originalAttributes.length + classAttributesWithoutSourceFileAttribute.size()];\r\n System.arraycopy(originalAttributes, 0, classFile.attributes, 0, originalAttributes.length);\r\n for (int index = 0; index < classAttributesWithoutSourceFileAttribute.size(); ++index) {\r\n final Attribute attrib = (classAttributesWithoutSourceFileAttribute.get(index));\r\n cp.add(attrib);\r\n classFile.attributes[originalAttributes.length + index] = attrib;\r\n }\r\n final ClassFileEntry cfThis = cp.add(cpBands.cpClassValue(fullNameIndexInCpClass));\r\n final ClassFileEntry cfSuper = cp.add(cpBands.cpClassValue(classBands.getClassSuperInts()[classNum]));\r\n final ClassFileEntry[] cfInterfaces = new ClassFileEntry[classBands.getClassInterfacesInts()[classNum].length];\r\n for (i = 0; i < cfInterfaces.length; ++i) {\r\n cfInterfaces[i] = cp.add(cpBands.cpClassValue(classBands.getClassInterfacesInts()[classNum][i]));\r\n }\r\n final ClassFileEntry[] cfFields = new ClassFileEntry[classBands.getClassFieldCount()[classNum]];\r\n for (i = 0; i < cfFields.length; ++i) {\r\n final int descriptorIndex = classBands.getFieldDescrInts()[classNum][i];\r\n final int nameIndex = cpBands.getCpDescriptorNameInts()[descriptorIndex];\r\n final int typeIndex = cpBands.getCpDescriptorTypeInts()[descriptorIndex];\r\n final CPUTF8 name = cpBands.cpUTF8Value(nameIndex);\r\n final CPUTF8 descriptor = cpBands.cpSignatureValue(typeIndex);\r\n cfFields[i] = cp.add(new CPField(name, descriptor, classBands.getFieldFlags()[classNum][i], classBands.getFieldAttributes()[classNum][i]));\r\n }\r\n final ClassFileEntry[] cfMethods = new ClassFileEntry[classBands.getClassMethodCount()[classNum]];\r\n for (i = 0; i < cfMethods.length; ++i) {\r\n final int descriptorIndex = classBands.getMethodDescrInts()[classNum][i];\r\n final int nameIndex = cpBands.getCpDescriptorNameInts()[descriptorIndex];\r\n final int typeIndex = cpBands.getCpDescriptorTypeInts()[descriptorIndex];\r\n final CPUTF8 name = cpBands.cpUTF8Value(nameIndex);\r\n final CPUTF8 descriptor = cpBands.cpSignatureValue(typeIndex);\r\n cfMethods[i] = cp.add(new CPMethod(name, descriptor, classBands.getMethodFlags()[classNum][i], classBands.getMethodAttributes()[classNum][i]));\r\n }\r\n cp.addNestedEntries();\r\n boolean addInnerClassesAttr = false;\r\n final IcTuple[] icLocal = getClassBands().getIcLocal()[classNum];\r\n final boolean icLocalSent = icLocal != null;\r\n final InnerClassesAttribute innerClassesAttribute = new InnerClassesAttribute(\"InnerClasses\");\r\n final IcTuple[] icRelevant = getIcBands().getRelevantIcTuples(fullName, cp);\r\n final List ic_stored = computeIcStored(icLocal, icRelevant);\r\n for (final IcTuple icStored : ic_stored) {\r\n final int innerClassIndex = icStored.thisClassIndex();\r\n final int outerClassIndex = icStored.outerClassIndex();\r\n final int simpleClassNameIndex = icStored.simpleClassNameIndex();\r\n final String innerClassString = icStored.thisClassString();\r\n final String outerClassString = icStored.outerClassString();\r\n final String simpleClassName = icStored.simpleClassName();\r\n CPClass innerClass = null;\r\n CPUTF8 innerName = null;\r\n CPClass outerClass = null;\r\n innerClass = innerClassIndex != -1 ? cpBands.cpClassValue(innerClassIndex) : cpBands.cpClassValue(innerClassString);\r\n if (!icStored.isAnonymous()) {\r\n innerName = simpleClassNameIndex != -1 ? cpBands.cpUTF8Value(simpleClassNameIndex) : cpBands.cpUTF8Value(simpleClassName);\r\n }\r\n if (icStored.isMember()) {\r\n outerClass = outerClassIndex != -1 ? cpBands.cpClassValue(outerClassIndex) : cpBands.cpClassValue(outerClassString);\r\n }\r\n final int flags = icStored.F;\r\n innerClassesAttribute.addInnerClassesEntry(innerClass, outerClass, innerName, flags);\r\n addInnerClassesAttr = true;\r\n }\r\n if (icLocalSent && (icLocal.length == 0)) {\r\n addInnerClassesAttr = false;\r\n }\r\n if (!icLocalSent && (icRelevant.length == 0)) {\r\n addInnerClassesAttr = false;\r\n }\r\n if (addInnerClassesAttr) {\r\n final Attribute[] originalAttrs = classFile.attributes;\r\n final Attribute[] newAttrs = new Attribute[originalAttrs.length + 1];\r\n System.arraycopy(originalAttrs, 0, newAttrs, 0, originalAttrs.length);\r\n newAttrs[newAttrs.length - 1] = innerClassesAttribute;\r\n classFile.attributes = newAttrs;\r\n cp.addWithNestedEntries(innerClassesAttribute);\r\n }\r\n cp.resolve(this);\r\n classFile.accessFlags = (int) classBands.getClassFlags()[classNum];\r\n classFile.thisClass = cp.indexOf(cfThis);\r\n classFile.superClass = cp.indexOf(cfSuper);\r\n classFile.interfaces = new int[cfInterfaces.length];\r\n for (i = 0; i < cfInterfaces.length; ++i) {\r\n classFile.interfaces[i] = cp.indexOf(cfInterfaces[i]);\r\n }\r\n classFile.fields = cfFields;\r\n classFile.methods = cfMethods;\r\n return classFile;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean checkFileExistenceInZip(String fileName, Path filePath, String format){\r\n boolean isZipFileValid = true;\r\n String fileExtension = FilenameUtils.getExtension(fileName);\r\n if (fileExtension.equalsIgnoreCase(\"zip\")) {\r\n isZipFileValid = false;\r\n ZipFile zipFile = null;\r\n File file = null;\r\n try {\r\n file = File.createTempFile(\"archive\", \".zip\");\r\n FileUtils.copyInputStreamToFile(FileStoreFactory.getFileStore().getFileContent(filePath), file);\r\n zipFile = new ZipFile(file);\r\n if (isEmpty(zipFile)) {\r\n isZipFileValid = true;\r\n } else {\r\n for (Enumeration e = zipFile.entries(); e.hasMoreElements(); ) {\r\n ZipEntry ze = e.nextElement();\r\n String name = ze.getName();\r\n if (name.endsWith(\".\" + format) && !name.contains(\"metadata\")) {\r\n isZipFileValid = true;\r\n break;\r\n }\r\n }\r\n }\r\n } catch (IOException e) {\r\n log.error(\"Erreur ouverture fichier zip \" + fileName);\r\n } finally {\r\n if (file != null) {\r\n file.delete();\r\n }\r\n }\r\n }\r\n return isZipFileValid;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void doBeforeParse(Node node){\r\n if (node.getNodeType() == Node.ELEMENT_NODE) {\r\n Document doc = node.getOwnerDocument();\r\n if (node.getNamespaceURI().startsWith(SPRING_NS + \"/v\")) {\r\n doc.renameNode(node, SPRING_NS, node.getNodeName());\r\n }\r\n NamedNodeMap map = node.getAttributes();\r\n for (int i = 0; i < map.getLength(); i++) {\r\n Node att = map.item(i);\r\n if (att.getNodeName().equals(\"uri\") || att.getNodeName().endsWith(\"Uri\")) {\r\n final String value = att.getNodeValue();\r\n String before = StringHelper.before(value, \"?\");\r\n String after = StringHelper.after(value, \"?\");\r\n if (before != null && after != null) {\r\n String changed = after.replaceAll(\"\\\\s{2,}\", \"\");\r\n if (!after.equals(changed)) {\r\n String newAtr = before.trim() + \"?\" + changed.trim();\r\n LOG.debug(\"Removed whitespace noise from attribute {} -> {}\", value, newAtr);\r\n att.setNodeValue(newAtr);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n NodeList list = node.getChildNodes();\r\n for (int i = 0; i < list.getLength(); ++i) {\r\n doBeforeParse(list.item(i));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void copyOrMoveMessageIfRequired(MailConfiguration config, Message mail, String destinationFolder, boolean moveMessage) throws MessagingException{\r\n if (config.getProtocol().equals(MailUtils.PROTOCOL_IMAP) || config.getProtocol().equals(MailUtils.PROTOCOL_IMAPS)) {\r\n if (destinationFolder != null) {\r\n LOG.trace(\"IMAP message needs to be {} to {}\", moveMessage ? \"moved\" : \"copied\", destinationFolder);\r\n Folder destFolder = store.getFolder(destinationFolder);\r\n if (!destFolder.exists()) {\r\n destFolder.create(Folder.HOLDS_MESSAGES);\r\n }\r\n folder.copyMessages(new Message[] { mail }, destFolder);\r\n if (moveMessage) {\r\n mail.setFlag(Flags.Flag.DELETED, true);\r\n }\r\n LOG.trace(\"IMAP message {} {} to {}\", mail, moveMessage ? \"moved\" : \"copied\", destinationFolder);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void cleanup(){\r\n lock.lock();\r\n try {\r\n boolean dirty = false;\r\n for (Iterator i = pending.values().iterator(); i.hasNext(); ) {\r\n Transaction tx = i.next();\r\n if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) {\r\n log.debug(\"Found risky transaction {} in wallet during cleanup.\", tx.getHashAsString());\r\n if (!tx.isAnyOutputSpent()) {\r\n for (TransactionInput input : tx.getInputs()) {\r\n TransactionOutput output = input.getConnectedOutput();\r\n if (output == null)\r\n continue;\r\n if (TxHelper.isMineOrWatched(output, this))\r\n checkState(myUnspents.add(output));\r\n input.disconnect();\r\n }\r\n for (TransactionOutput output : tx.getOutputs()) myUnspents.remove(output);\r\n i.remove();\r\n transactions.remove(tx.getHash());\r\n dirty = true;\r\n log.info(\"Removed transaction {} from pending pool during cleanup.\", tx.getHashAsString());\r\n } else {\r\n log.info(\"Cannot remove transaction {} from pending pool during cleanup, as it's already spent partially.\", tx.getHashAsString());\r\n }\r\n }\r\n }\r\n if (dirty) {\r\n isConsistentOrThrow();\r\n saveLater();\r\n if (log.isInfoEnabled())\r\n log.info(\"Estimated balance is now: {}\", getBalance(BalanceType.ESTIMATED).toFriendlyString());\r\n }\r\n } finally {\r\n lock.unlock();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List parse(){\r\n List files = new ArrayList<>();\r\n if ((value == null) || value.trim().isEmpty()) {\r\n return files;\r\n }\r\n if (LinkedFile.isOnlineLink(value.trim())) {\r\n try {\r\n return List.of(new LinkedFile(new URL(value), \"\"));\r\n } catch (MalformedURLException e) {\r\n LOGGER.error(\"invalid url\", e);\r\n return files;\r\n }\r\n }\r\n List linkedFileData = new ArrayList<>();\r\n resetDataStructuresForNextElement();\r\n boolean inXmlChar = false;\r\n boolean escaped = false;\r\n for (int i = 0; i < value.length(); i++) {\r\n char c = value.charAt(i);\r\n if (!escaped && (c == '\\\\')) {\r\n if (windowsPath) {\r\n charactersOfCurrentElement.append(c);\r\n continue;\r\n } else {\r\n escaped = true;\r\n continue;\r\n }\r\n } else if (!escaped && (c == '&') && !inXmlChar) {\r\n charactersOfCurrentElement.append(c);\r\n if ((value.length() > (i + 1)) && (value.charAt(i + 1) == '#')) {\r\n inXmlChar = true;\r\n }\r\n } else if (!escaped && inXmlChar && (c == ';')) {\r\n charactersOfCurrentElement.append(c);\r\n inXmlChar = false;\r\n } else if (!escaped && (c == ':')) {\r\n if ((linkedFileData.size() == 1) && (charactersOfCurrentElement.length() == 1)) {\r\n charactersOfCurrentElement.append(c);\r\n windowsPath = true;\r\n } else {\r\n linkedFileData.add(charactersOfCurrentElement.toString());\r\n resetDataStructuresForNextElement();\r\n }\r\n } else if (!escaped && (c == ';') && !inXmlChar) {\r\n linkedFileData.add(charactersOfCurrentElement.toString());\r\n files.add(convert(linkedFileData));\r\n resetDataStructuresForNextElement();\r\n } else {\r\n charactersOfCurrentElement.append(c);\r\n }\r\n escaped = false;\r\n }\r\n if (charactersOfCurrentElement.length() > 0) {\r\n linkedFileData.add(charactersOfCurrentElement.toString());\r\n }\r\n if (!linkedFileData.isEmpty()) {\r\n files.add(convert(linkedFileData));\r\n }\r\n return files;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addJobInScheduler() throws Exception{\r\n Scheduler scheduler = getComponent().getScheduler();\r\n JobDetail jobDetail;\r\n Trigger oldTrigger = scheduler.getTrigger(triggerKey);\r\n boolean triggerExisted = oldTrigger != null;\r\n if (triggerExisted && !isRecoverableJob()) {\r\n ensureNoDupTriggerKey();\r\n }\r\n jobDetail = createJobDetail();\r\n Trigger trigger = createTrigger(jobDetail);\r\n QuartzHelper.updateJobDataMap(getCamelContext(), jobDetail, getEndpointUri(), isUsingFixedCamelContextName());\r\n boolean scheduled = true;\r\n if (triggerExisted) {\r\n if (hasTriggerChanged(oldTrigger, trigger)) {\r\n scheduler.rescheduleJob(triggerKey, trigger);\r\n }\r\n } else {\r\n try {\r\n Calendar cal = null;\r\n if (trigger.getCalendarName() != null) {\r\n cal = scheduler.getCalendar(trigger.getCalendarName());\r\n }\r\n OperableTrigger ot = (OperableTrigger) trigger;\r\n Date ft = ot.computeFirstFireTime(cal);\r\n if (ft == null && ignoreExpiredNextFireTime) {\r\n scheduled = false;\r\n LOG.warn(\"Job {} (cron={}, triggerType={}, jobClass={}) not scheduled, because it will never fire in the future\", trigger.getKey(), cron, trigger.getClass().getSimpleName(), jobDetail.getJobClass().getSimpleName());\r\n } else {\r\n scheduler.scheduleJob(jobDetail, trigger);\r\n }\r\n } catch (ObjectAlreadyExistsException ex) {\r\n if (!(getComponent().isClustered())) {\r\n throw ex;\r\n } else {\r\n trigger = scheduler.getTrigger(triggerKey);\r\n if (trigger == null) {\r\n throw new SchedulerException(\"Trigger could not be found in quartz scheduler.\");\r\n }\r\n }\r\n }\r\n }\r\n if (scheduled) {\r\n if (LOG.isInfoEnabled()) {\r\n Object nextFireTime = trigger.getNextFireTime();\r\n if (nextFireTime != null) {\r\n nextFireTime = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\").format(nextFireTime);\r\n }\r\n LOG.info(\"Job {} (cron={}, triggerType={}, jobClass={}) is scheduled. Next fire date is {}\", trigger.getKey(), cron, trigger.getClass().getSimpleName(), jobDetail.getJobClass().getSimpleName(), nextFireTime);\r\n }\r\n }\r\n AtomicInteger number = (AtomicInteger) scheduler.getContext().get(QuartzConstants.QUARTZ_CAMEL_JOBS_COUNT);\r\n if (number != null) {\r\n number.incrementAndGet();\r\n }\r\n jobAdded.set(true);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void removeFromTagInvertedIndex(IMeasurementMNode node) throws IOException{\r\n if (node.getOffset() < 0) {\r\n return;\r\n }\r\n Map tagMap = tagLogFile.readTag(COMMON_CONFIG.getTagAttributeTotalSize(), node.getOffset());\r\n if (tagMap != null) {\r\n for (Map.Entry entry : tagMap.entrySet()) {\r\n if (tagIndex.containsKey(entry.getKey()) && tagIndex.get(entry.getKey()).containsKey(entry.getValue())) {\r\n if (logger.isDebugEnabled()) {\r\n logger.debug(String.format(String.format(DEBUG_MSG, \"Delete\" + TAG_FORMAT, node.getFullPath()), entry.getKey(), entry.getValue(), node.getOffset()));\r\n }\r\n tagIndex.get(entry.getKey()).get(entry.getValue()).remove(node);\r\n if (tagIndex.get(entry.getKey()).get(entry.getValue()).isEmpty()) {\r\n tagIndex.get(entry.getKey()).remove(entry.getValue());\r\n if (tagIndex.get(entry.getKey()).isEmpty()) {\r\n tagIndex.remove(entry.getKey());\r\n }\r\n }\r\n } else {\r\n if (logger.isDebugEnabled()) {\r\n logger.debug(String.format(String.format(DEBUG_MSG_1, \"Delete\" + PREVIOUS_CONDITION, node.getFullPath()), entry.getKey(), entry.getValue(), node.getOffset(), tagIndex.containsKey(entry.getKey())));\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RelOptPredicateList getPredicates(Union union, RelMetadataQuery mq){\r\n final RexBuilder rexBuilder = union.getCluster().getRexBuilder();\r\n Set finalPredicates = new HashSet<>();\r\n final List finalResidualPredicates = new ArrayList<>();\r\n for (Ord input : Ord.zip(union.getInputs())) {\r\n RelOptPredicateList info = mq.getPulledUpPredicates(input.e);\r\n if (info.pulledUpPredicates.isEmpty()) {\r\n return RelOptPredicateList.EMPTY;\r\n }\r\n final Set predicates = new HashSet<>();\r\n final List residualPredicates = new ArrayList<>();\r\n for (RexNode pred : info.pulledUpPredicates) {\r\n if (input.i == 0) {\r\n predicates.add(pred);\r\n continue;\r\n }\r\n if (finalPredicates.contains(pred)) {\r\n predicates.add(pred);\r\n } else {\r\n residualPredicates.add(pred);\r\n }\r\n }\r\n finalResidualPredicates.add(RexUtil.composeConjunction(rexBuilder, residualPredicates));\r\n for (RexNode e : finalPredicates) {\r\n if (!predicates.contains(e)) {\r\n for (int j = 0; j < input.i; j++) {\r\n finalResidualPredicates.set(j, RexUtil.composeConjunction(rexBuilder, Arrays.asList(finalResidualPredicates.get(j), e)));\r\n }\r\n }\r\n }\r\n finalPredicates = predicates;\r\n }\r\n final List predicates = new ArrayList<>(finalPredicates);\r\n final RelOptCluster cluster = union.getCluster();\r\n final RexExecutor executor = Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR);\r\n RexNode disjunctivePredicate = new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, executor).simplifyUnknownAs(rexBuilder.makeCall(SqlStdOperatorTable.OR, finalResidualPredicates), RexUnknownAs.FALSE);\r\n if (!disjunctivePredicate.isAlwaysTrue()) {\r\n predicates.add(disjunctivePredicate);\r\n }\r\n return RelOptPredicateList.of(rexBuilder, predicates);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean equals(Object object1, Object object2){\r\n if (object1 == null || object2 == null) {\r\n return object1 == object2;\r\n }\r\n Triple t1 = (Triple) object1;\r\n Triple t2 = (Triple) object2;\r\n if (t1.getInstance() != Variable.v) {\r\n if (t1.getInstance() == null) {\r\n return false;\r\n } else if (t1.getInstance() instanceof String) {\r\n if (!t1.getInstance().equals(t2.getInstance())) {\r\n return false;\r\n }\r\n } else if (t1.getInstance() != t2.getInstance()) {\r\n return false;\r\n }\r\n }\r\n if (t1.getProperty() != Variable.v && !t1.getProperty().equals(t2.getProperty())) {\r\n return false;\r\n }\r\n if (t1.getValue() != Variable.v) {\r\n if (t1.getValue() == null) {\r\n return t2.getValue() == null;\r\n } else {\r\n return t1.getValue().equals(t2.getValue());\r\n }\r\n }\r\n if (t1.getClass() == TripleStore.TripleCollector.class) {\r\n ((TripleStore.TripleCollector) t1).list.add(t2);\r\n return false;\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected JmsMessageType getJMSMessageTypeForBody(Exchange exchange, Object body){\r\n boolean streamingEnabled = endpoint.getConfiguration().isStreamMessageTypeEnabled();\r\n JmsMessageType type = null;\r\n if (body instanceof Node || body instanceof String) {\r\n type = Text;\r\n } else if (body instanceof byte[] || body instanceof ByteBuffer) {\r\n type = Bytes;\r\n } else if (body instanceof WrappedFile || body instanceof File || body instanceof Reader || body instanceof InputStream || body instanceof StreamCache) {\r\n type = streamingEnabled ? Stream : Bytes;\r\n } else if (body instanceof Map) {\r\n type = Map;\r\n } else if (body instanceof Serializable) {\r\n type = Object;\r\n } else if (exchange.getContext().getTypeConverter().tryConvertTo(File.class, body) != null || exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, body) != null) {\r\n type = streamingEnabled ? Stream : Bytes;\r\n }\r\n if (type == Stream) {\r\n boolean artemis = endpoint.isArtemisStreamingEnabled();\r\n if (artemis) {\r\n type = Bytes;\r\n }\r\n }\r\n return type;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void validateMatchRecognize(SqlCall call){\r\n final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call;\r\n final MatchRecognizeScope scope = (MatchRecognizeScope) getMatchRecognizeScope(matchRecognize);\r\n final MatchRecognizeNamespace ns = getNamespaceOrThrow(call).unwrap(MatchRecognizeNamespace.class);\r\n assert ns.rowType == null;\r\n final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch();\r\n final boolean allRows = rowsPerMatch != null && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS;\r\n final RelDataTypeFactory.Builder typeBuilder = typeFactory.builder();\r\n SqlNodeList partitionBy = matchRecognize.getPartitionList();\r\n if (partitionBy != null) {\r\n for (SqlNode node : partitionBy) {\r\n SqlIdentifier identifier = (SqlIdentifier) node;\r\n identifier.validate(this, scope);\r\n RelDataType type = deriveType(scope, identifier);\r\n String name = identifier.names.get(1);\r\n typeBuilder.add(name, type);\r\n }\r\n }\r\n SqlNodeList orderBy = matchRecognize.getOrderList();\r\n if (orderBy != null) {\r\n for (SqlNode node : orderBy) {\r\n node.validate(this, scope);\r\n SqlIdentifier identifier;\r\n if (node instanceof SqlBasicCall) {\r\n identifier = ((SqlBasicCall) node).operand(0);\r\n } else {\r\n identifier = requireNonNull((SqlIdentifier) node, () -> \"order by field is null. All fields: \" + orderBy);\r\n }\r\n if (allRows) {\r\n RelDataType type = deriveType(scope, identifier);\r\n String name = identifier.names.get(1);\r\n if (!typeBuilder.nameExists(name)) {\r\n typeBuilder.add(name, type);\r\n }\r\n }\r\n }\r\n }\r\n if (allRows) {\r\n final SqlValidatorNamespace sqlNs = getNamespaceOrThrow(matchRecognize.getTableRef());\r\n final RelDataType inputDataType = sqlNs.getRowType();\r\n for (RelDataTypeField fs : inputDataType.getFieldList()) {\r\n if (!typeBuilder.nameExists(fs.getName())) {\r\n typeBuilder.add(fs);\r\n }\r\n }\r\n }\r\n SqlNode pattern = matchRecognize.getPattern();\r\n PatternVarVisitor visitor = new PatternVarVisitor(scope);\r\n pattern.accept(visitor);\r\n SqlLiteral interval = matchRecognize.getInterval();\r\n if (interval != null) {\r\n interval.validate(this, scope);\r\n if (((SqlIntervalLiteral) interval).signum() < 0) {\r\n String intervalValue = interval.toValue();\r\n throw newValidationError(interval, RESOURCE.intervalMustBeNonNegative(intervalValue != null ? intervalValue : interval.toString()));\r\n }\r\n if (orderBy == null || orderBy.size() == 0) {\r\n throw newValidationError(interval, RESOURCE.cannotUseWithinWithoutOrderBy());\r\n }\r\n SqlNode firstOrderByColumn = orderBy.get(0);\r\n SqlIdentifier identifier;\r\n if (firstOrderByColumn instanceof SqlBasicCall) {\r\n identifier = ((SqlBasicCall) firstOrderByColumn).operand(0);\r\n } else {\r\n identifier = (SqlIdentifier) requireNonNull(firstOrderByColumn, \"firstOrderByColumn\");\r\n }\r\n RelDataType firstOrderByColumnType = deriveType(scope, identifier);\r\n if (!SqlTypeUtil.isTimestamp(firstOrderByColumnType)) {\r\n throw newValidationError(interval, RESOURCE.firstColumnOfOrderByMustBeTimestamp());\r\n }\r\n SqlNode expand = expand(interval, scope);\r\n RelDataType type = deriveType(scope, expand);\r\n setValidatedNodeType(interval, type);\r\n }\r\n validateDefinitions(matchRecognize, scope);\r\n SqlNodeList subsets = matchRecognize.getSubsetList();\r\n if (subsets != null && subsets.size() > 0) {\r\n for (SqlNode node : subsets) {\r\n List operands = ((SqlCall) node).getOperandList();\r\n String leftString = ((SqlIdentifier) operands.get(0)).getSimple();\r\n if (scope.getPatternVars().contains(leftString)) {\r\n throw newValidationError(operands.get(0), RESOURCE.patternVarAlreadyDefined(leftString));\r\n }\r\n scope.addPatternVar(leftString);\r\n for (SqlNode right : (SqlNodeList) operands.get(1)) {\r\n SqlIdentifier id = (SqlIdentifier) right;\r\n if (!scope.getPatternVars().contains(id.getSimple())) {\r\n throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple()));\r\n }\r\n scope.addPatternVar(id.getSimple());\r\n }\r\n }\r\n }\r\n final SqlNode skipTo = matchRecognize.getAfter();\r\n if (skipTo instanceof SqlCall) {\r\n final SqlCall skipToCall = (SqlCall) skipTo;\r\n final SqlIdentifier id = skipToCall.operand(0);\r\n if (!scope.getPatternVars().contains(id.getSimple())) {\r\n throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple()));\r\n }\r\n }\r\n PairList measureColumns = validateMeasure(matchRecognize, scope, allRows);\r\n measureColumns.forEach((name, type) -> {\r\n if (!typeBuilder.nameExists(name)) {\r\n typeBuilder.add(name, type);\r\n }\r\n });\r\n final RelDataType rowType = typeBuilder.build();\r\n if (matchRecognize.getMeasureList().size() == 0) {\r\n ns.setType(getNamespaceOrThrow(matchRecognize.getTableRef()).getRowType());\r\n } else {\r\n ns.setType(rowType);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addCompleteDeferredProcessing(final BKTransmitPacket transmitPacket, final long entryId, final int rc){\r\n boolean cancelPendingPromises = false;\r\n EntryBuffer recordSet = transmitPacket.getRecordSet();\r\n synchronized (this) {\r\n if (transmitResultUpdater.compareAndSet(this, BKException.Code.OK, rc)) {\r\n cancelPendingPromises = (BKException.Code.OK != rc);\r\n } else {\r\n LOG.warn(\"Log segment {} entryId {}: Tried to set transmit result to ({}) but is already ({})\", fullyQualifiedLogSegment, entryId, rc, transmitResultUpdater.get(this));\r\n }\r\n if (transmitResultUpdater.get(this) != BKException.Code.OK) {\r\n if (recordSet.hasUserRecords()) {\r\n transmitDataPacketSize.registerFailedEvent(recordSet.getNumBytes(), TimeUnit.MICROSECONDS);\r\n }\r\n } else {\r\n if (recordSet.hasUserRecords()) {\r\n transmitDataPacketSize.registerSuccessfulEvent(recordSet.getNumBytes(), TimeUnit.MICROSECONDS);\r\n controlFlushNeeded = true;\r\n if (immediateFlushEnabled) {\r\n if (0 == minDelayBetweenImmediateFlushMs) {\r\n backgroundFlush(true);\r\n } else {\r\n scheduleFlushWithDelayIfNeeded(new Callable() {\r\n\r\n @Override\r\n public Void call() throws Exception {\r\n backgroundFlush(true);\r\n return null;\r\n }\r\n }, immFlushSchedFutureRefUpdater);\r\n }\r\n }\r\n }\r\n }\r\n if (BKException.Code.OK == transmitResultUpdater.get(this)) {\r\n DLSN lastDLSNInPacket = recordSet.finalizeTransmit(logSegmentSequenceNumber, entryId);\r\n if (recordSet.hasUserRecords()) {\r\n if (null != lastDLSNInPacket && lastDLSN.compareTo(lastDLSNInPacket) < 0) {\r\n lastDLSN = lastDLSNInPacket;\r\n }\r\n }\r\n }\r\n }\r\n if (BKException.Code.OK == transmitResultUpdater.get(this)) {\r\n recordSet.completeTransmit(logSegmentSequenceNumber, entryId);\r\n } else {\r\n recordSet.abortTransmit(Utils.transmitException(transmitResultUpdater.get(this)));\r\n }\r\n if (cancelPendingPromises) {\r\n final BKTransmitPacket packetCurrentSaved;\r\n synchronized (this) {\r\n packetCurrentSaved = new BKTransmitPacket(recordSetWriter);\r\n recordSetWriter = newRecordSetWriter();\r\n }\r\n packetCurrentSaved.getRecordSet().abortTransmit(new WriteCancelledException(streamName, Utils.transmitException(transmitResultUpdater.get(this))));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void createLocalFileList(HashMap> list, String path, String relativePath){\r\n java.io.File file = new java.io.File(path);\r\n if (file.exists()) {\r\n if (file.isDirectory()) {\r\n for (java.io.File i : file.listFiles()) {\r\n if (i.isDirectory()) {\r\n String rel;\r\n if (relativePath == null) {\r\n rel = i.getName();\r\n } else {\r\n rel = relativePath + java.io.File.separator + i.getName();\r\n }\r\n createLocalFileList(list, i.getAbsolutePath(), rel);\r\n } else {\r\n long size = i.length();\r\n list.put(i.getAbsolutePath(), Pair.of(relativePath, size));\r\n srcSizeInBytes += size;\r\n }\r\n }\r\n } else {\r\n long size = file.length();\r\n list.put(file.getAbsolutePath(), Pair.of(relativePath, size));\r\n srcSizeInBytes += size;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean doConnect(RemoteFileConfiguration configuration, Exchange exchange) throws GenericFileOperationFailedException{\r\n log.trace(\"Connecting using FTPClient: {}\", client);\r\n String host = configuration.getHost();\r\n String username = configuration.getUsername();\r\n String account = ((FtpConfiguration) configuration).getAccount();\r\n if (clientConfig != null) {\r\n log.trace(\"Configuring FTPClient with config: {}\", clientConfig);\r\n client.configure(clientConfig);\r\n }\r\n if (endpoint.getSoTimeout() > 0) {\r\n client.setDefaultTimeout(endpoint.getSoTimeout());\r\n }\r\n if (log.isTraceEnabled()) {\r\n log.trace(\"Connecting to {} using connection timeout: {}\", configuration.remoteServerInformation(), client.getConnectTimeout());\r\n }\r\n BlockingTask task = Tasks.foregroundTask().withBudget(Budgets.iterationBudget().withMaxIterations(Budgets.atLeastOnce(endpoint.getMaximumReconnectAttempts())).withInterval(Duration.ofMillis(endpoint.getReconnectDelay())).build()).build();\r\n TaskPayload payload = new TaskPayload(configuration);\r\n if (!task.run(this::tryConnect, payload)) {\r\n if (exchange != null) {\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE, client.getReplyCode());\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING, client.getReplyString());\r\n }\r\n if (payload.exception != null) {\r\n if (payload.exception instanceof GenericFileOperationFailedException) {\r\n throw (GenericFileOperationFailedException) payload.exception;\r\n } else {\r\n throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), payload.exception.getMessage(), payload.exception);\r\n }\r\n } else {\r\n throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), \"Server refused connection\");\r\n }\r\n }\r\n clientActivityListener.onConnected(host);\r\n if (configuration.isPassiveMode()) {\r\n log.trace(\"Using passive mode connections\");\r\n client.enterLocalPassiveMode();\r\n }\r\n if (endpoint.getSoTimeout() > 0) {\r\n log.trace(\"Using SoTimeout={}\", endpoint.getSoTimeout());\r\n try {\r\n client.setSoTimeout(endpoint.getSoTimeout());\r\n } catch (IOException e) {\r\n throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);\r\n }\r\n }\r\n try {\r\n clientActivityListener.onLogin(host);\r\n boolean login;\r\n if (username != null) {\r\n if (account != null) {\r\n log.trace(\"Attempting to login user: {} using password: ******** and account: {}\", username, account);\r\n login = client.login(username, configuration.getPassword(), account);\r\n } else {\r\n log.trace(\"Attempting to login user: {} using password: ********\", username);\r\n login = client.login(username, configuration.getPassword());\r\n }\r\n } else {\r\n if (account != null) {\r\n log.trace(\"Attempting to login anonymous using account: {}\", account);\r\n login = client.login(\"anonymous\", \"\", account);\r\n } else {\r\n log.trace(\"Attempting to login anonymous\");\r\n login = client.login(\"anonymous\", \"\");\r\n }\r\n }\r\n log.trace(\"User {} logged in: {}\", username != null ? username : \"anonymous\", login);\r\n if (!login) {\r\n String replyString = client.getReplyString();\r\n int replyCode = client.getReplyCode();\r\n clientActivityListener.onLoginFailed(replyCode, replyString);\r\n client.disconnect();\r\n throw new GenericFileOperationFailedException(replyCode, replyString);\r\n }\r\n clientActivityListener.onLoginComplete(host);\r\n client.setFileType(configuration.isBinary() ? FTP.BINARY_FILE_TYPE : FTP.ASCII_FILE_TYPE);\r\n } catch (IOException e) {\r\n throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);\r\n } finally {\r\n if (exchange != null) {\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE, client.getReplyCode());\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING, client.getReplyString());\r\n }\r\n }\r\n if (endpoint.getConfiguration().getSiteCommand() != null) {\r\n Iterator it = ObjectHelper.createIterator(endpoint.getConfiguration().getSiteCommand(), \"\\n\");\r\n while (it.hasNext()) {\r\n Object next = it.next();\r\n String command = endpoint.getCamelContext().getTypeConverter().convertTo(String.class, next);\r\n log.trace(\"Site command to send: {}\", command);\r\n if (command != null) {\r\n boolean result = sendSiteCommand(command);\r\n if (!result) {\r\n throw new GenericFileOperationFailedException(\"Site command: \" + command + \" returned false\");\r\n }\r\n }\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected JobTO getJobTO(final JobKey jobKey, final boolean includeCustom) throws SchedulerException{\r\n JobTO jobTO = null;\r\n if (scheduler.getScheduler().checkExists(jobKey)) {\r\n Triple reference = getReference(jobKey);\r\n if (reference != null) {\r\n jobTO = new JobTO();\r\n jobTO.setType(reference.getLeft());\r\n jobTO.setRefKey(reference.getMiddle());\r\n jobTO.setRefDesc(reference.getRight());\r\n } else if (includeCustom) {\r\n JobDetail jobDetail = scheduler.getScheduler().getJobDetail(jobKey);\r\n if (!TaskJob.class.isAssignableFrom(jobDetail.getJobClass()) && !ReportJob.class.isAssignableFrom(jobDetail.getJobClass()) && !SystemLoadReporterJob.class.isAssignableFrom(jobDetail.getJobClass()) && !NotificationJob.class.isAssignableFrom(jobDetail.getJobClass())) {\r\n jobTO = new JobTO();\r\n jobTO.setType(JobType.CUSTOM);\r\n jobTO.setRefKey(jobKey.getName());\r\n jobTO.setRefDesc(jobDetail.getJobClass().getName());\r\n }\r\n }\r\n if (jobTO != null) {\r\n List jobTriggers = scheduler.getScheduler().getTriggersOfJob(jobKey);\r\n if (jobTriggers.isEmpty()) {\r\n jobTO.setScheduled(false);\r\n } else {\r\n jobTO.setScheduled(true);\r\n jobTO.setStart(jobTriggers.get(0).getStartTime().toInstant().atOffset(FormatUtils.DEFAULT_OFFSET));\r\n }\r\n jobTO.setRunning(jobManager.isRunning(jobKey));\r\n jobTO.setStatus(\"UNKNOWN\");\r\n if (jobTO.isRunning()) {\r\n try {\r\n jobTO.setStatus(Optional.ofNullable(jobStatusDAO.find(jobTO.getRefDesc())).map(JobStatus::getStatus).orElse(jobTO.getStatus()));\r\n } catch (NoSuchBeanDefinitionException e) {\r\n LOG.warn(\"Could not find job {} implementation\", jobKey, e);\r\n }\r\n }\r\n }\r\n }\r\n return jobTO;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void validateTimeSeriesExistence(ConfigNodeProcedureEnv env){\r\n PathPatternTree patternTree = new PathPatternTree();\r\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\r\n DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);\r\n PartialPath path = null;\r\n try {\r\n path = new PartialPath(templateSetPath);\r\n patternTree.appendPathPattern(path);\r\n patternTree.appendPathPattern(path.concatNode(MULTI_LEVEL_PATH_WILDCARD));\r\n patternTree.serialize(dataOutputStream);\r\n } catch (IllegalPathException | IOException ignored) {\r\n }\r\n ByteBuffer patternTreeBytes = ByteBuffer.wrap(byteArrayOutputStream.toByteArray());\r\n Map relatedSchemaRegionGroup = env.getConfigManager().getRelatedSchemaRegionGroup(patternTree);\r\n List respList = new ArrayList<>();\r\n DataNodeRegionTaskExecutor regionTask = new DataNodeRegionTaskExecutor(env, relatedSchemaRegionGroup, false, DataNodeRequestType.CHECK_TIMESERIES_EXISTENCE, ((dataNodeLocation, consensusGroupIdList) -> new TCheckTimeSeriesExistenceReq(patternTreeBytes, consensusGroupIdList))) {\r\n\r\n @Override\r\n protected List processResponseOfOneDataNode(TDataNodeLocation dataNodeLocation, List consensusGroupIdList, TCheckTimeSeriesExistenceResp response) {\r\n respList.add(response);\r\n List failedRegionList = new ArrayList<>();\r\n if (response.getStatus().getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()) {\r\n return failedRegionList;\r\n }\r\n if (response.getStatus().getCode() == TSStatusCode.MULTIPLE_ERROR.getStatusCode()) {\r\n List subStatus = response.getStatus().getSubStatus();\r\n for (int i = 0; i < subStatus.size(); i++) {\r\n if (subStatus.get(i).getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode() && subStatus.get(i).getCode() != TSStatusCode.TIMESERIES_ALREADY_EXIST.getStatusCode()) {\r\n failedRegionList.add(consensusGroupIdList.get(i));\r\n }\r\n }\r\n } else {\r\n failedRegionList.addAll(consensusGroupIdList);\r\n }\r\n return failedRegionList;\r\n }\r\n\r\n @Override\r\n protected void onAllReplicasetFailure(TConsensusGroupId consensusGroupId, Set dataNodeLocationSet) {\r\n setFailure(new ProcedureException(new MetadataException(String.format(\"Set template %s to %s failed when [check timeseries existence on DataNode] because all replicaset of schemaRegion %s failed. %s\", templateName, templateSetPath, consensusGroupId.id, dataNodeLocationSet))));\r\n interruptTask();\r\n }\r\n };\r\n regionTask.execute();\r\n if (isFailed()) {\r\n return;\r\n }\r\n for (TCheckTimeSeriesExistenceResp resp : respList) {\r\n if (resp.isExists()) {\r\n setFailure(new ProcedureException(new TemplateIncompatibleException(templateName, path)));\r\n }\r\n }\r\n setNextState(SetTemplateState.COMMIT_SET);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void fillAttrQuery(final StringBuilder query, final PlainAttrValue attrValue, final PlainSchema schema, final AttrCond cond, final boolean not, final List parameters, final SearchSupport svs){\r\n if (not && schema.isMultivalue() && !(cond instanceof AnyCond) && cond.getType() != AttrCond.Type.ISNULL && cond.getType() != AttrCond.Type.ISNOTNULL) {\r\n query.append(\"any_id NOT IN (SELECT DISTINCT any_id FROM \");\r\n if (schema.isUniqueConstraint()) {\r\n query.append(svs.asSearchViewSupport().uniqueAttr().name);\r\n } else {\r\n query.append(svs.asSearchViewSupport().attr().name);\r\n }\r\n query.append(\" WHERE schema_id='\").append(schema.getKey());\r\n fillAttrQuery(query, attrValue, schema, cond, false, parameters, svs);\r\n query.append(')');\r\n } else {\r\n boolean ignoreCase = AttrCond.Type.ILIKE == cond.getType() || AttrCond.Type.IEQ == cond.getType();\r\n String column = (cond instanceof AnyCond) ? cond.getSchema() : key(schema.getType());\r\n if ((schema.getType() == AttrSchemaType.String || schema.getType() == AttrSchemaType.Enum) && ignoreCase) {\r\n column = \"LOWER (\" + column + ')';\r\n }\r\n if (!(cond instanceof AnyCond)) {\r\n column = \"' AND \" + column;\r\n }\r\n switch(cond.getType()) {\r\n case ISNULL:\r\n query.append(column).append(not ? \" IS NOT NULL\" : \" IS NULL\");\r\n break;\r\n case ISNOTNULL:\r\n query.append(column).append(not ? \" IS NULL\" : \" IS NOT NULL\");\r\n break;\r\n case ILIKE:\r\n case LIKE:\r\n if (schema.getType() == AttrSchemaType.String || schema.getType() == AttrSchemaType.Enum) {\r\n query.append(column);\r\n if (not) {\r\n query.append(\" NOT \");\r\n }\r\n query.append(\" LIKE \");\r\n if (ignoreCase) {\r\n query.append(\"LOWER(?\").append(setParameter(parameters, cond.getExpression())).append(')');\r\n } else {\r\n query.append('?').append(setParameter(parameters, cond.getExpression()));\r\n }\r\n } else {\r\n if (!(cond instanceof AnyCond)) {\r\n query.append(\"' AND\");\r\n }\r\n query.append(\" 1=2\");\r\n LOG.error(\"LIKE is only compatible with string or enum schemas\");\r\n }\r\n break;\r\n case IEQ:\r\n case EQ:\r\n query.append(column);\r\n if (not) {\r\n query.append(\"<>\");\r\n } else {\r\n query.append('=');\r\n }\r\n if ((schema.getType() == AttrSchemaType.String || schema.getType() == AttrSchemaType.Enum) && ignoreCase) {\r\n query.append(\"LOWER(?\").append(setParameter(parameters, attrValue.getValue())).append(')');\r\n } else {\r\n query.append('?').append(setParameter(parameters, attrValue.getValue()));\r\n }\r\n break;\r\n case GE:\r\n query.append(column);\r\n if (not) {\r\n query.append('<');\r\n } else {\r\n query.append(\">=\");\r\n }\r\n query.append('?').append(setParameter(parameters, attrValue.getValue()));\r\n break;\r\n case GT:\r\n query.append(column);\r\n if (not) {\r\n query.append(\"<=\");\r\n } else {\r\n query.append('>');\r\n }\r\n query.append('?').append(setParameter(parameters, attrValue.getValue()));\r\n break;\r\n case LE:\r\n query.append(column);\r\n if (not) {\r\n query.append('>');\r\n } else {\r\n query.append(\"<=\");\r\n }\r\n query.append('?').append(setParameter(parameters, attrValue.getValue()));\r\n break;\r\n case LT:\r\n query.append(column);\r\n if (not) {\r\n query.append(\">=\");\r\n } else {\r\n query.append('<');\r\n }\r\n query.append('?').append(setParameter(parameters, attrValue.getValue()));\r\n break;\r\n default:\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static UserTO patch(final UserTO userTO, final UserUR userUR){\r\n UserTO result = SerializationUtils.clone(userTO);\r\n patch(userTO, userUR, result);\r\n if (userUR.getPassword() != null) {\r\n result.setPassword(userUR.getPassword().getValue());\r\n }\r\n if (userUR.getUsername() != null) {\r\n result.setUsername(userUR.getUsername().getValue());\r\n }\r\n userUR.getRelationships().forEach(relPatch -> {\r\n if (relPatch.getRelationshipTO() == null) {\r\n LOG.warn(\"Invalid {} specified: {}\", RelationshipUR.class.getName(), relPatch);\r\n } else {\r\n result.getRelationships().remove(relPatch.getRelationshipTO());\r\n if (relPatch.getOperation() == PatchOperation.ADD_REPLACE) {\r\n result.getRelationships().add(relPatch.getRelationshipTO());\r\n }\r\n }\r\n });\r\n userUR.getMemberships().forEach(membPatch -> {\r\n if (membPatch.getGroup() == null) {\r\n LOG.warn(\"Invalid {} specified: {}\", MembershipUR.class.getName(), membPatch);\r\n } else {\r\n result.getMemberships().stream().filter(membership -> membPatch.getGroup().equals(membership.getGroupKey())).findFirst().ifPresent(memb -> result.getMemberships().remove(memb));\r\n if (membPatch.getOperation() == PatchOperation.ADD_REPLACE) {\r\n MembershipTO newMembershipTO = new MembershipTO.Builder(membPatch.getGroup()).plainAttrs(membPatch.getPlainAttrs()).virAttrs(membPatch.getVirAttrs()).build();\r\n result.getMemberships().add(newMembershipTO);\r\n }\r\n }\r\n });\r\n for (StringPatchItem rolePatch : userUR.getRoles()) {\r\n switch(rolePatch.getOperation()) {\r\n case ADD_REPLACE:\r\n result.getRoles().add(rolePatch.getValue());\r\n break;\r\n case DELETE:\r\n default:\r\n result.getRoles().remove(rolePatch.getValue());\r\n }\r\n }\r\n userUR.getLinkedAccounts().forEach(accountPatch -> {\r\n if (accountPatch.getLinkedAccountTO() == null) {\r\n LOG.warn(\"Invalid {} specified: {}\", LinkedAccountUR.class.getName(), accountPatch);\r\n } else {\r\n result.getLinkedAccounts().remove(accountPatch.getLinkedAccountTO());\r\n if (accountPatch.getOperation() == PatchOperation.ADD_REPLACE) {\r\n result.getLinkedAccounts().add(accountPatch.getLinkedAccountTO());\r\n }\r\n }\r\n });\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void removeJoin(LoptMultiJoin multiJoin, LogicalJoin semiJoin, int factIdx, int dimIdx){\r\n if (multiJoin.getJoinRemovalFactor(dimIdx) != null) {\r\n return;\r\n }\r\n final ImmutableBitSet dimKeys = ImmutableBitSet.of(semiJoin.analyzeCondition().rightKeys);\r\n final RelNode dimRel = multiJoin.getJoinFactor(dimIdx);\r\n if (!RelMdUtil.areColumnsDefinitelyUniqueWhenNullsFiltered(mq, dimRel, dimKeys)) {\r\n return;\r\n }\r\n ImmutableBitSet dimProjRefs = multiJoin.getProjFields(dimIdx);\r\n if (dimProjRefs == null) {\r\n int nDimFields = multiJoin.getNumFieldsInJoinFactor(dimIdx);\r\n dimProjRefs = ImmutableBitSet.range(0, nDimFields);\r\n }\r\n if (!dimKeys.contains(dimProjRefs)) {\r\n return;\r\n }\r\n int[] dimJoinRefCounts = multiJoin.getJoinFieldRefCounts(dimIdx);\r\n for (int i = 0; i < dimJoinRefCounts.length; i++) {\r\n if (dimJoinRefCounts[i] > 0) {\r\n if (!dimKeys.get(i)) {\r\n return;\r\n }\r\n }\r\n }\r\n multiJoin.setJoinRemovalFactor(dimIdx, factIdx);\r\n multiJoin.setJoinRemovalSemiJoin(dimIdx, semiJoin);\r\n if (dimProjRefs.cardinality() != 0) {\r\n return;\r\n }\r\n for (int i = 0; i < dimJoinRefCounts.length; i++) {\r\n if (dimJoinRefCounts[i] > 1) {\r\n return;\r\n } else if (dimJoinRefCounts[i] == 1) {\r\n if (!dimKeys.get(i)) {\r\n return;\r\n }\r\n }\r\n }\r\n int[] factJoinRefCounts = multiJoin.getJoinFieldRefCounts(factIdx);\r\n for (Integer key : semiJoin.analyzeCondition().leftKeys) {\r\n factJoinRefCounts[key]--;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void applyLogEntry(LogEntry entry){\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"Processing \" + entry);\r\n }\r\n Object response = null;\r\n Object operation = entry.operation();\r\n if (operation instanceof RaftGroupCmd) {\r\n if (operation instanceof DestroyRaftGroupCmd) {\r\n groupDestroyed();\r\n } else if (operation instanceof UpdateRaftGroupMembersCmd) {\r\n if (state.lastGroupMembers().index() < entry.index()) {\r\n setStatus(UPDATING_GROUP_MEMBER_LIST);\r\n UpdateRaftGroupMembersCmd op = (UpdateRaftGroupMembersCmd) operation;\r\n updateGroupMembers(entry.index(), op.getMembers());\r\n }\r\n assert status == UPDATING_GROUP_MEMBER_LIST : \"STATUS: \" + status;\r\n assert state.lastGroupMembers().index() == entry.index();\r\n state.commitGroupMembers();\r\n UpdateRaftGroupMembersCmd cmd = (UpdateRaftGroupMembersCmd) operation;\r\n if (cmd.getMember().equals(state.localEndpoint()) && cmd.getMode() == MembershipChangeMode.REMOVE) {\r\n setStatus(STEPPED_DOWN);\r\n invalidateFuturesUntil(entry.index() - 1, new LeaderDemotedException(state.localEndpoint(), null));\r\n } else {\r\n setStatus(ACTIVE);\r\n }\r\n response = entry.index();\r\n } else {\r\n response = new IllegalArgumentException(\"Invalid command: \" + operation);\r\n }\r\n } else {\r\n response = raftIntegration.runOperation(operation, entry.index());\r\n }\r\n if (response == PostponedResponse.INSTANCE) {\r\n return;\r\n }\r\n completeFuture(entry.index(), response);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic Frame decorrelateRel(Aggregate rel, boolean isCorVarDefined){\r\n assert !cm.mapRefRelToCorRef.containsKey(rel);\r\n final RelNode oldInput = rel.getInput();\r\n final Frame frame = getInvoke(oldInput, isCorVarDefined, rel);\r\n if (frame == null) {\r\n return null;\r\n }\r\n final RelNode newInput = frame.r;\r\n final Map outputMap = new HashMap<>();\r\n final Map mapNewInputToProjOutputs = new HashMap<>();\r\n final int oldGroupKeyCount = rel.getGroupSet().cardinality();\r\n final PairList projects = PairList.of();\r\n List newInputOutput = newInput.getRowType().getFieldList();\r\n int newPos = 0;\r\n final List groupKeyIndices = rel.getGroupSet().asList();\r\n final NavigableMap omittedConstants = new TreeMap<>();\r\n for (int i = 0; i < oldGroupKeyCount; i++) {\r\n final int idx = groupKeyIndices.get(i);\r\n final RexLiteral constant = projectedLiteral(newInput, idx);\r\n if (constant != null) {\r\n omittedConstants.put(idx, constant);\r\n continue;\r\n }\r\n outputMap.put(idx, newPos);\r\n int newInputPos = requireNonNull(frame.oldToNewOutputs.get(idx));\r\n RexInputRef.add2(projects, newInputPos, newInputOutput);\r\n mapNewInputToProjOutputs.put(newInputPos, newPos);\r\n newPos++;\r\n }\r\n final NavigableMap corDefOutputs = new TreeMap<>();\r\n if (!frame.corDefOutputs.isEmpty()) {\r\n for (Map.Entry entry : frame.corDefOutputs.entrySet()) {\r\n RexInputRef.add2(projects, entry.getValue(), newInputOutput);\r\n corDefOutputs.put(entry.getKey(), newPos);\r\n mapNewInputToProjOutputs.put(entry.getValue(), newPos);\r\n newPos++;\r\n }\r\n }\r\n final int newGroupKeyCount = newPos;\r\n for (int i = 0; i < newInputOutput.size(); i++) {\r\n if (!mapNewInputToProjOutputs.containsKey(i)) {\r\n RexInputRef.add2(projects, i, newInputOutput);\r\n mapNewInputToProjOutputs.put(i, newPos);\r\n newPos++;\r\n }\r\n }\r\n assert newPos == newInputOutput.size();\r\n RelNode newProject = relBuilder.push(newInput).projectNamed(projects.leftList(), projects.rightList(), true).build();\r\n Map combinedMap = new HashMap<>();\r\n for (Map.Entry entry : frame.oldToNewOutputs.entrySet()) {\r\n combinedMap.put(entry.getKey(), requireNonNull(mapNewInputToProjOutputs.get(entry.getValue()), () -> \"mapNewInputToProjOutputs.get(\" + entry.getValue() + \")\"));\r\n }\r\n register(oldInput, newProject, combinedMap, corDefOutputs);\r\n final ImmutableBitSet newGroupSet = ImmutableBitSet.range(newGroupKeyCount);\r\n List newAggCalls = new ArrayList<>();\r\n List oldAggCalls = rel.getAggCallList();\r\n final Iterable newGroupSets;\r\n if (rel.getGroupType() == Aggregate.Group.SIMPLE) {\r\n newGroupSets = null;\r\n } else {\r\n final ImmutableBitSet addedGroupSet = ImmutableBitSet.range(oldGroupKeyCount, newGroupKeyCount);\r\n newGroupSets = ImmutableBitSet.ORDERING.immutableSortedCopy(Util.transform(rel.getGroupSets(), bitSet -> bitSet.union(addedGroupSet)));\r\n }\r\n int oldInputOutputFieldCount = rel.getGroupSet().cardinality();\r\n int newInputOutputFieldCount = newGroupSet.cardinality();\r\n int i = -1;\r\n for (AggregateCall oldAggCall : oldAggCalls) {\r\n ++i;\r\n List oldAggArgs = oldAggCall.getArgList();\r\n List aggArgs = new ArrayList<>();\r\n for (int oldPos : oldAggArgs) {\r\n aggArgs.add(requireNonNull(combinedMap.get(oldPos), () -> \"combinedMap.get(\" + oldPos + \")\"));\r\n }\r\n final int filterArg = oldAggCall.filterArg < 0 ? oldAggCall.filterArg : requireNonNull(combinedMap.get(oldAggCall.filterArg), () -> \"combinedMap.get(\" + oldAggCall.filterArg + \")\");\r\n newAggCalls.add(oldAggCall.adaptTo(newProject, aggArgs, filterArg, oldGroupKeyCount, newGroupKeyCount));\r\n outputMap.put(oldInputOutputFieldCount + i, newInputOutputFieldCount + i);\r\n }\r\n relBuilder.push(newProject).aggregate(newGroupSets == null ? relBuilder.groupKey(newGroupSet) : relBuilder.groupKey(newGroupSet, newGroupSets), newAggCalls);\r\n if (!omittedConstants.isEmpty()) {\r\n final List postProjects = new ArrayList<>(relBuilder.fields());\r\n for (Map.Entry entry : omittedConstants.descendingMap().entrySet()) {\r\n int index = entry.getKey() + frame.corDefOutputs.size();\r\n postProjects.add(index, entry.getValue());\r\n shiftMapping(outputMap, index, 1);\r\n outputMap.put(entry.getKey(), index);\r\n }\r\n relBuilder.project(postProjects);\r\n }\r\n RelNode newRel = relBuilder.build();\r\n return register(rel, newRel, outputMap, corDefOutputs);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ReadAccessor getFieldReadAccessor(final RuleBuildContext context, final BaseDescr descr, final Pattern pattern, final ObjectType objectType, String fieldName, final AcceptsReadAccessor target, final boolean reportError){\r\n ReadAccessor reader;\r\n if (ValueType.FACTTEMPLATE_TYPE.equals(objectType.getValueType())) {\r\n final FactTemplate factTemplate = ((FactTemplateObjectType) objectType).getFactTemplate();\r\n reader = new FactTemplateFieldExtractor(factTemplate, fieldName);\r\n if (target != null) {\r\n target.setReadAccessor(reader);\r\n }\r\n return reader;\r\n }\r\n boolean isGetter = getterRegexp.matcher(fieldName).matches();\r\n if (isGetter) {\r\n fieldName = fieldName.substring(3, fieldName.indexOf('(')).trim();\r\n }\r\n if (isGetter || identifierRegexp.matcher(fieldName).matches()) {\r\n Declaration decl = context.getDeclarationResolver().getDeclarations(context.getRule()).get(fieldName);\r\n if (decl != null && decl.getExtractor() instanceof FieldNameSupplier && \"this\".equals(((FieldNameSupplier) decl.getExtractor()).getFieldName())) {\r\n return decl.getExtractor();\r\n }\r\n try {\r\n reader = context.getPkg().getReader(objectType.getClassName(), fieldName, target);\r\n } catch (final Exception e) {\r\n if (reportError && context.isTypesafe()) {\r\n registerDescrBuildError(context, descr, e, \"Unable to create Field Extractor for '\" + fieldName + \"'\" + e.getMessage());\r\n }\r\n reader = null;\r\n } finally {\r\n if (reportError) {\r\n Collection results = context.getPkg().getWiringResults(((ClassObjectType) objectType).getClassType(), fieldName);\r\n if (!results.isEmpty()) {\r\n for (KnowledgeBuilderResult res : results) {\r\n if (res.getSeverity() == ResultSeverity.ERROR) {\r\n context.addError(new DroolsErrorWrapper(res));\r\n } else {\r\n context.addWarning(new DroolsWarningWrapper(res));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } else {\r\n reader = ConstraintBuilder.get().buildMvelFieldReadAccessor(context, descr, pattern, objectType, fieldName, reportError);\r\n }\r\n return reader;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final Sort sort = call.rel(0);\r\n final RelCollation collation = sort.getCollation();\r\n final Union union = call.rel(1);\r\n final int unionInputsSize = union.getInputs().size();\r\n RexNode inputFetch = null;\r\n if (sort.fetch != null) {\r\n if (sort.offset == null) {\r\n inputFetch = sort.fetch;\r\n } else if (sort.fetch instanceof RexLiteral && sort.offset instanceof RexLiteral) {\r\n inputFetch = call.builder().literal(RexLiteral.intValue(sort.fetch) + RexLiteral.intValue(sort.offset));\r\n }\r\n }\r\n final RelBuilder builder = call.builder();\r\n final List unionFieldList = union.getRowType().getFieldList();\r\n final List inputs = new ArrayList<>(unionInputsSize);\r\n for (RelNode input : union.getInputs()) {\r\n final ImmutableBitSet.Builder fieldsRequiringCastBuilder = ImmutableBitSet.builder();\r\n for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {\r\n final int index = fieldCollation.getFieldIndex();\r\n final RelDataType unionType = unionFieldList.get(index).getType();\r\n final RelDataType inputType = input.getRowType().getFieldList().get(index).getType();\r\n if (!Objects.equals(unionType.getCollation(), inputType.getCollation())) {\r\n fieldsRequiringCastBuilder.set(index);\r\n }\r\n }\r\n final ImmutableBitSet fieldsRequiringCast = fieldsRequiringCastBuilder.build();\r\n final RelNode unsortedInput;\r\n if (fieldsRequiringCast.isEmpty()) {\r\n unsortedInput = input;\r\n } else {\r\n builder.push(input);\r\n final List fields = builder.fields();\r\n final List projFields = new ArrayList<>(fields.size());\r\n for (int i = 0; i < fields.size(); i++) {\r\n RexNode node = fields.get(i);\r\n if (fieldsRequiringCast.get(i)) {\r\n final RelDataType targetType = unionFieldList.get(i).getType();\r\n node = builder.getRexBuilder().makeCast(targetType, node);\r\n }\r\n projFields.add(node);\r\n }\r\n builder.project(projFields);\r\n unsortedInput = builder.build();\r\n }\r\n final RelNode newInput = sort.copy(sort.getTraitSet(), unsortedInput, collation, null, inputFetch);\r\n inputs.add(convert(call.getPlanner(), newInput, newInput.getTraitSet().replace(EnumerableConvention.INSTANCE)));\r\n }\r\n RelNode result = EnumerableMergeUnion.create(sort.getCollation(), inputs, union.all);\r\n if (sort.offset != null || sort.fetch != null) {\r\n result = EnumerableLimit.create(result, sort.offset, sort.fetch);\r\n }\r\n call.transformTo(result);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RelNode visit(RelNode p, int ordinal, @Nullable RelNode parent){\r\n final int pId = p.getId();\r\n RelNode prevVisit = visited.get(pId);\r\n if (prevVisit != null) {\r\n return prevVisit;\r\n }\r\n if (p instanceof RelSubset) {\r\n RelSubset subset = (RelSubset) p;\r\n RelNode cheapest = subset.best;\r\n if (cheapest == null) {\r\n StringWriter sw = new StringWriter();\r\n final PrintWriter pw = new PrintWriter(sw);\r\n pw.print(\"There are not enough rules to produce a node with desired properties\");\r\n RelTraitSet desiredTraits = subset.getTraitSet();\r\n String sep = \": \";\r\n for (RelTrait trait : desiredTraits) {\r\n pw.print(sep);\r\n pw.print(trait.getTraitDef().getSimpleName());\r\n pw.print(\"=\");\r\n pw.print(trait);\r\n sep = \", \";\r\n }\r\n pw.print(\".\");\r\n DeadEndFinder finder = new DeadEndFinder();\r\n finder.visit(subset);\r\n if (finder.deadEnds.isEmpty()) {\r\n pw.print(\" All the inputs have relevant nodes, however the cost is still infinite.\");\r\n } else {\r\n Map problemCounts = finder.deadEnds.stream().filter(deadSubset -> deadSubset.getOriginal() != null).map(x -> {\r\n RelNode original = castNonNull(x.getOriginal());\r\n return original.getClass().getSimpleName() + traitDiff(original.getTraitSet(), x.getTraitSet());\r\n }).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\r\n String problems = problemCounts.entrySet().stream().sorted(Comparator.comparingLong(Map.Entry::getValue).reversed()).map(e -> e.getKey() + (e.getValue() > 1 ? \" (\" + e.getValue() + \" cases)\" : \"\")).collect(Collectors.joining(\", \"));\r\n pw.println();\r\n pw.print(\"Missing conversion\");\r\n pw.print(finder.deadEnds.size() == 1 ? \" is \" : \"s are \");\r\n pw.print(problems);\r\n pw.println();\r\n if (finder.deadEnds.size() == 1) {\r\n pw.print(\"There is 1 empty subset: \");\r\n }\r\n if (finder.deadEnds.size() > 1) {\r\n pw.println(\"There are \" + finder.deadEnds.size() + \" empty subsets:\");\r\n }\r\n int i = 0;\r\n int rest = finder.deadEnds.size();\r\n for (RelSubset deadEnd : finder.deadEnds) {\r\n if (finder.deadEnds.size() > 1) {\r\n pw.print(\"Empty subset \");\r\n pw.print(i);\r\n pw.print(\": \");\r\n }\r\n pw.print(deadEnd);\r\n pw.println(\", the relevant part of the original plan is as follows\");\r\n RelNode original = deadEnd.getOriginal();\r\n if (original != null) {\r\n original.explain(new RelWriterImpl(pw, SqlExplainLevel.EXPPLAN_ATTRIBUTES, true));\r\n }\r\n i++;\r\n rest--;\r\n if (rest > 0) {\r\n pw.println();\r\n }\r\n if (i >= 10 && rest > 1) {\r\n pw.print(\"The rest \");\r\n pw.print(rest);\r\n pw.println(\" leafs are omitted.\");\r\n break;\r\n }\r\n }\r\n }\r\n pw.println();\r\n planner.dump(pw);\r\n pw.flush();\r\n final String dump = sw.toString();\r\n RuntimeException e = new RelOptPlanner.CannotPlanException(dump);\r\n LOGGER.trace(\"Caught exception in class={}, method=visit\", getClass().getName(), e);\r\n throw e;\r\n }\r\n p = cheapest;\r\n }\r\n if (ordinal != -1) {\r\n if (planner.getListener() != null) {\r\n RelOptListener.RelChosenEvent event = new RelOptListener.RelChosenEvent(planner, p);\r\n planner.getListener().relChosen(event);\r\n }\r\n }\r\n List oldInputs = p.getInputs();\r\n List inputs = new ArrayList<>();\r\n for (int i = 0; i < oldInputs.size(); i++) {\r\n RelNode oldInput = oldInputs.get(i);\r\n RelNode input = visit(oldInput, i, p);\r\n inputs.add(input);\r\n }\r\n if (!inputs.equals(oldInputs)) {\r\n final RelNode pOld = p;\r\n p = p.copy(p.getTraitSet(), inputs);\r\n planner.provenanceMap.put(p, new VolcanoPlanner.DirectProvenance(pOld));\r\n }\r\n visited.put(pId, p);\r\n return p;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ObjectResponseType recuperaChildren(ObjectIdType repositoryId, PrincipalIdType principalId, ObjectIdType objectId, boolean isGruppoAllegati) throws IntegrationException{\r\n String method = \"recuperaChildren\";\r\n log.debug(method + \". BEGIN\");\r\n PagingResponseType children = null;\r\n ObjectResponseType response = null;\r\n PropertyFilterType filter = new PropertyFilterType();\r\n filter.setFilterType(EnumPropertyFilter.ALL);\r\n try {\r\n children = getNavigationService().getChildren(repositoryId, objectId, principalId, filter, null, null);\r\n if (children != null) {\r\n log.debug(method + \". Il children esiste\");\r\n }\r\n } catch (it.doqui.acta.actasrv.util.acaris.wrapper.exception.AcarisException acEx) {\r\n log.error(method + \". AcarisException =\" + acEx + \" acEx.getCause(): \" + acEx.getCause());\r\n log.error(method + \". AcarisException.getMessage() = \" + acEx.getMessage());\r\n log.error(method + \". AcarisException.getFaultInfo() = \" + acEx.getFaultInfo());\r\n if (acEx.getFaultInfo() != null) {\r\n log.error(method + \". AcarisException.getFaultInfo().getErrorCode() = \" + acEx.getFaultInfo().getErrorCode());\r\n log.error(method + \". AcarisException.getFaultInfo().getPropertyName() = \" + acEx.getFaultInfo().getPropertyName());\r\n log.error(method + \". AcarisException.getFaultInfo().getObjectId() = \" + acEx.getFaultInfo().getObjectId());\r\n log.error(method + \". AcarisException.getFaultInfo().getExceptionType() = \" + acEx.getFaultInfo().getExceptionType());\r\n log.error(method + \". AcarisException.getFaultInfo().getClassName() = \" + acEx.getFaultInfo().getClassName());\r\n log.error(method + \". AcarisException.getFaultInfo().getTechnicalInfo = \" + acEx.getFaultInfo().getTechnicalInfo());\r\n throw new IntegrationException(\"AcarisException \", acEx);\r\n }\r\n } catch (Exception e) {\r\n log.error(method + \". Exception\" + e);\r\n log.error(method + \". e.getMessage() = \" + e.getMessage());\r\n throw new IntegrationException(\"Exception \", e);\r\n } finally {\r\n log.debug(method + \". END\");\r\n }\r\n if (isGruppoAllegati) {\r\n for (int i = 0; i < children.getObjectsLength(); i++) {\r\n PropertyType[] prop = children.getObjects(i).getProperties();\r\n for (int j = 0; j < prop.length; j++) {\r\n PropertyType propertyType = prop[j];\r\n if (propertyType.getQueryName().getClassName().equalsIgnoreCase(\"GruppoAllegatiPropertiesType\")) {\r\n response = children.getObjects(i);\r\n }\r\n }\r\n }\r\n } else {\r\n if (children.getObjectsLength() > 0)\r\n response = children.getObjects(0);\r\n }\r\n return response;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doHandshake(){\r\n if (isStoppingOrStopped()) {\r\n return;\r\n }\r\n LOG.info(\"Handshaking after unexpected disconnect from Salesforce...\");\r\n boolean abort = false;\r\n LOG.debug(\"Waiting to disconnect...\");\r\n while (!abort && !client.isDisconnected()) {\r\n try {\r\n Thread.sleep(DISCONNECT_INTERVAL);\r\n } catch (InterruptedException e) {\r\n LOG.error(\"Aborting handshake on interrupt!\");\r\n abort = true;\r\n }\r\n abort = abort || isStoppingOrStopped();\r\n }\r\n if (!abort) {\r\n final long backoff = handshakeBackoff.getAndAdd(backoffIncrement);\r\n if (backoff > maxBackoff) {\r\n LOG.error(\"Handshake aborted after exceeding {} msecs backoff\", maxBackoff);\r\n abort = true;\r\n } else {\r\n LOG.debug(\"Pausing for {} msecs before handshake attempt\", backoff);\r\n try {\r\n Thread.sleep(backoff);\r\n } catch (InterruptedException e) {\r\n LOG.error(\"Aborting handshake on interrupt!\");\r\n abort = true;\r\n }\r\n }\r\n if (!abort) {\r\n Exception lastError = new SalesforceException(\"Unknown error\", null);\r\n try {\r\n if (client != null) {\r\n client.disconnect();\r\n boolean disconnected = client.waitFor(timeout, State.DISCONNECTED);\r\n if (!disconnected) {\r\n LOG.warn(\"Could not disconnect client connected to: {} after: {} msec.\", getEndpointUrl(component), timeout);\r\n client.abort();\r\n }\r\n client.handshake();\r\n final long waitMs = MILLISECONDS.convert(CONNECT_TIMEOUT, SECONDS);\r\n client.waitFor(waitMs, BayeuxClient.State.CONNECTED);\r\n }\r\n } catch (Exception e) {\r\n LOG.error(\"Error handshaking: {}\", e.getMessage(), e);\r\n lastError = e;\r\n }\r\n if (client != null && client.isHandshook()) {\r\n LOG.debug(\"Successful handshake!\");\r\n handshakeBackoff.set(backoffIncrement);\r\n } else {\r\n LOG.error(\"Failed to handshake after pausing for {} msecs\", backoff);\r\n if ((backoff + backoffIncrement) > maxBackoff) {\r\n String abortMsg = \"Aborting handshake attempt due to: \" + lastError.getMessage();\r\n SalesforceException ex = new SalesforceException(abortMsg, lastError);\r\n for (StreamingApiConsumer consumer : listenerMap.keySet()) {\r\n consumer.handleException(abortMsg, ex);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void align(){\r\n if (!isReady()) {\r\n return;\r\n }\r\n long timeStart = System.nanoTime();\r\n int[] dim = getScoreMatrixDimensions();\r\n if (storingScoreMatrix) {\r\n scores = new int[dim[0]][dim[1]][dim[2]];\r\n } else {\r\n scores = new int[dim[0]][][];\r\n scores[0] = new int[dim[1]][dim[2]];\r\n scores[1] = new int[dim[1]][dim[2]];\r\n }\r\n boolean linear = (gapPenalty.getType() == GapPenalty.Type.LINEAR);\r\n Last[][][] traceback = new Last[dim[0]][][];\r\n List sx = new ArrayList(), sy = new ArrayList();\r\n if (!local) {\r\n xyMax = new int[] { dim[0] - 1, dim[1] - 1 };\r\n xyStart = new int[] { 0, 0 };\r\n score = 0;\r\n List problems = Subproblem.getSubproblems(anchors, xyMax[0], xyMax[1]);\r\n assert problems.size() == anchors.size() + 1;\r\n for (int i = 0; i < problems.size(); i++) {\r\n Subproblem subproblem = problems.get(i);\r\n for (int x = subproblem.getQueryStartIndex(); x <= subproblem.getQueryEndIndex(); x++) {\r\n traceback[x] = linear ? setScoreVector(x, subproblem, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores) : setScoreVector(x, subproblem, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores);\r\n }\r\n }\r\n setSteps(traceback, scores, sx, sy);\r\n score = Integer.MIN_VALUE;\r\n int[] finalScore = scores[xyMax[0]][xyMax[1]];\r\n for (int z = 0; z < finalScore.length; z++) {\r\n score = Math.max(score, finalScore[z]);\r\n }\r\n } else {\r\n for (int x = 0; x < dim[0]; x++) {\r\n traceback[x] = linear ? setScoreVector(x, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score) : setScoreVector(x, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score);\r\n if (xyMax[0] == x) {\r\n score = scores[x][xyMax[1]][0];\r\n }\r\n }\r\n xyStart = local ? setSteps(traceback, xyMax, sx, sy) : setSteps(traceback, scores, sx, sy);\r\n }\r\n setProfile(sx, sy);\r\n if (!storingScoreMatrix) {\r\n scores = null;\r\n }\r\n time = System.nanoTime() - timeStart;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprotected static List> extractRanges(RexNode node, boolean withNot){\r\n switch(node.getKind()) {\r\n case EQUALS:\r\n case LESS_THAN:\r\n case LESS_THAN_OR_EQUAL:\r\n case GREATER_THAN:\r\n case GREATER_THAN_OR_EQUAL:\r\n case DRUID_IN:\r\n case SEARCH:\r\n return leafToRanges((RexCall) node, withNot);\r\n case NOT:\r\n return extractRanges(((RexCall) node).getOperands().get(0), !withNot);\r\n case OR:\r\n {\r\n RexCall call = (RexCall) node;\r\n List> intervals = new ArrayList<>();\r\n for (RexNode child : call.getOperands()) {\r\n List> extracted = extractRanges(child, withNot);\r\n if (extracted != null) {\r\n intervals.addAll(extracted);\r\n }\r\n }\r\n return intervals;\r\n }\r\n case AND:\r\n {\r\n RexCall call = (RexCall) node;\r\n List> ranges = new ArrayList<>();\r\n for (RexNode child : call.getOperands()) {\r\n List> extractedRanges = extractRanges(child, false);\r\n if (extractedRanges == null || extractedRanges.isEmpty()) {\r\n return null;\r\n }\r\n if (ranges.isEmpty()) {\r\n ranges.addAll(extractedRanges);\r\n continue;\r\n }\r\n List> overlapped = new ArrayList<>();\r\n for (Range current : ranges) {\r\n for (Range interval : extractedRanges) {\r\n if (current.isConnected(interval)) {\r\n overlapped.add(current.intersection(interval));\r\n }\r\n }\r\n }\r\n ranges = overlapped;\r\n }\r\n return ranges;\r\n }\r\n default:\r\n return null;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void advance(){\r\n if (!advanced) {\r\n try {\r\n if (!recordReader.next(key, batch)) {\r\n batch.size = 0;\r\n }\r\n if (batch.size != 0 && recordReader instanceof RowPositionAwareVectorizedRecordReader) {\r\n rowOffset = ((RowPositionAwareVectorizedRecordReader) recordReader).getRowNumber();\r\n }\r\n if (partitionColIndices != null) {\r\n for (int i = 0; i < partitionColIndices.length; ++i) {\r\n int colIdx = partitionColIndices[i];\r\n if (batch.cols[colIdx] != null) {\r\n vrbCtx.addPartitionColsToBatch(batch.cols[colIdx], partitionValues[i], partitionColIndices[i]);\r\n }\r\n }\r\n }\r\n for (VirtualColumn vc : vrbCtx.getNeededVirtualColumns()) {\r\n Object value;\r\n int idx = vrbCtx.findVirtualColumnNum(vc);\r\n switch(vc) {\r\n case PARTITION_SPEC_ID:\r\n value = idToConstant.get(MetadataColumns.SPEC_ID.fieldId());\r\n vrbCtx.addPartitionColsToBatch(batch.cols[idx], value, idx);\r\n break;\r\n case PARTITION_HASH:\r\n value = IcebergAcidUtil.computeHash((StructProjection) idToConstant.get(MetadataColumns.PARTITION_COLUMN_ID));\r\n vrbCtx.addPartitionColsToBatch(batch.cols[idx], value, idx);\r\n break;\r\n case FILE_PATH:\r\n value = idToConstant.get(MetadataColumns.FILE_PATH.fieldId());\r\n BytesColumnVector bcv = (BytesColumnVector) batch.cols[idx];\r\n if (value == null) {\r\n bcv.noNulls = false;\r\n bcv.isNull[0] = true;\r\n bcv.isRepeating = true;\r\n } else {\r\n bcv.fill(((String) value).getBytes());\r\n }\r\n break;\r\n case ROW_POSITION:\r\n value = LongStream.range(rowOffset, rowOffset + batch.size).toArray();\r\n LongColumnVector lcv = (LongColumnVector) batch.cols[idx];\r\n lcv.noNulls = true;\r\n Arrays.fill(lcv.isNull, false);\r\n lcv.isRepeating = false;\r\n System.arraycopy(value, 0, lcv.vector, 0, batch.size);\r\n break;\r\n }\r\n }\r\n } catch (IOException ioe) {\r\n throw new RuntimeException(ioe);\r\n }\r\n advanced = true;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@Nullable\npublic String getLiteral(SqlTypeName typeName, boolean isPrefix){\r\n switch(typeName) {\r\n case VARBINARY:\r\n case VARCHAR:\r\n case CHAR:\r\n return \"'\";\r\n case BINARY:\r\n return isPrefix ? \"x'\" : \"'\";\r\n case TIMESTAMP:\r\n return isPrefix ? \"TIMESTAMP '\" : \"'\";\r\n case TIMESTAMP_WITH_LOCAL_TIME_ZONE:\r\n return isPrefix ? \"TIMESTAMP WITH LOCAL TIME ZONE '\" : \"'\";\r\n case INTERVAL_DAY:\r\n case INTERVAL_DAY_HOUR:\r\n case INTERVAL_DAY_MINUTE:\r\n case INTERVAL_DAY_SECOND:\r\n case INTERVAL_HOUR:\r\n case INTERVAL_HOUR_MINUTE:\r\n case INTERVAL_HOUR_SECOND:\r\n case INTERVAL_MINUTE:\r\n case INTERVAL_MINUTE_SECOND:\r\n case INTERVAL_SECOND:\r\n return isPrefix ? \"INTERVAL '\" : \"' DAY\";\r\n case INTERVAL_YEAR:\r\n case INTERVAL_YEAR_MONTH:\r\n case INTERVAL_MONTH:\r\n return isPrefix ? \"INTERVAL '\" : \"' YEAR TO MONTH\";\r\n case TIME:\r\n return isPrefix ? \"TIME '\" : \"'\";\r\n case TIME_WITH_LOCAL_TIME_ZONE:\r\n return isPrefix ? \"TIME WITH LOCAL TIME ZONE '\" : \"'\";\r\n case DATE:\r\n return isPrefix ? \"DATE '\" : \"'\";\r\n case ARRAY:\r\n return isPrefix ? \"(\" : \")\";\r\n default:\r\n return null;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized Service createService(CamelContext camelContext){\r\n final ServiceArgs args = new ServiceArgs();\r\n if (host != null) {\r\n args.setHost(host);\r\n }\r\n if (port > 0) {\r\n args.setPort(port);\r\n }\r\n if (scheme != null) {\r\n args.setScheme(scheme);\r\n }\r\n if (app != null) {\r\n args.setApp(app);\r\n }\r\n if (owner != null) {\r\n args.setOwner(owner);\r\n }\r\n if (username != null) {\r\n args.setUsername(username);\r\n }\r\n if (password != null && token == null) {\r\n args.setPassword(password);\r\n }\r\n if (token != null) {\r\n args.setToken(String.format(\"Bearer %s\", token));\r\n args.remove(\"username\");\r\n args.remove(\"password\");\r\n }\r\n if (isUseSunHttpsHandler()) {\r\n String sunHandlerClassName = \"sun.net.www.protocol.https.Handler\";\r\n Class clazz = camelContext.getClassResolver().resolveClass(sunHandlerClassName, URLStreamHandler.class);\r\n if (clazz != null) {\r\n URLStreamHandler handler = camelContext.getInjector().newInstance(clazz);\r\n args.setHTTPSHandler(handler);\r\n LOG.debug(\"using the URLStreamHandler {} for {}\", handler, args);\r\n } else {\r\n LOG.warn(\"could not resolve and use the URLStreamHandler class '{}'\", sunHandlerClassName);\r\n }\r\n }\r\n ExecutorService executor = camelContext.getExecutorServiceManager().newSingleThreadExecutor(this, \"DefaultSplunkConnectionFactory\");\r\n Future future = executor.submit(new Callable() {\r\n\r\n public Service call() throws Exception {\r\n if (Service.DEFAULT_SCHEME.equals(getScheme())) {\r\n LOG.debug(\"Https in use. Setting SSL protocol to {}\", getSslProtocol());\r\n HttpService.setSslSecurityProtocol(getSslProtocol());\r\n }\r\n return Service.connect(args);\r\n }\r\n });\r\n try {\r\n Service service = null;\r\n if (connectionTimeout > 0) {\r\n service = future.get(connectionTimeout, TimeUnit.MILLISECONDS);\r\n } else {\r\n service = future.get();\r\n }\r\n LOG.info(\"Successfully connected to Splunk\");\r\n return service;\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"could not connect to Splunk Server @ %s:%d - %s\", host, port, e.getMessage()), e);\r\n } finally {\r\n camelContext.getExecutorServiceManager().shutdownNow(executor);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List collectUpdatedEntries() throws IOException, SchemaFileLogCorruptedException{\r\n if (inputStream == null || inputStream.getChannel().size() == 0) {\r\n return Collections.emptyList();\r\n }\r\n List colBuffers = new ArrayList<>();\r\n byte[] tempBytes = new byte[SchemaFileConfig.PAGE_LENGTH];\r\n while (inputStream.available() > 0) {\r\n inputStream.read(tempBytes, 0, 1);\r\n if (tempBytes[0] == SchemaFileConfig.SF_COMMIT_MARK) {\r\n throw new SchemaFileLogCorruptedException(logFile.getAbsolutePath(), \"COMMIT_MARK without PREPARE_MARK\");\r\n }\r\n if (tempBytes[0] == SchemaFileConfig.SF_PREPARE_MARK) {\r\n if (inputStream.available() < 1) {\r\n return colBuffers;\r\n }\r\n inputStream.read(tempBytes, 0, 1);\r\n if (tempBytes[0] == SchemaFileConfig.SF_COMMIT_MARK) {\r\n colBuffers.clear();\r\n } else {\r\n throw new SchemaFileLogCorruptedException(logFile.getAbsolutePath(), \"an extraneous byte rather than \" + \"COMMIT_MARK after PREPARE_MARK\");\r\n }\r\n if (inputStream.read(tempBytes, 0, 1) < 0) {\r\n return Collections.emptyList();\r\n }\r\n }\r\n if (inputStream.read(tempBytes, 1, tempBytes.length - 1) < tempBytes.length - 2) {\r\n throw new SchemaFileLogCorruptedException(logFile.getAbsolutePath(), \"incomplete entry.\");\r\n }\r\n colBuffers.add(tempBytes);\r\n tempBytes = new byte[SchemaFileConfig.PAGE_LENGTH];\r\n }\r\n throw new SchemaFileLogCorruptedException(logFile.getAbsolutePath(), \"not ended by COMMIT_MARK nor PREPARE_MARK.\");\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void checkPropsInCreateTimeSeries(CreateTimeSeriesStatement createTimeSeriesStatement){\r\n Map props = createTimeSeriesStatement.getProps();\r\n if (props != null && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase())) {\r\n String datatypeString = props.get(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase()).toUpperCase();\r\n try {\r\n createTimeSeriesStatement.setDataType(TSDataType.valueOf(datatypeString));\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported datatype: %s\", datatypeString));\r\n }\r\n }\r\n if (createTimeSeriesStatement.getDataType() == null) {\r\n throw new SemanticException(\"datatype must be declared\");\r\n }\r\n final IoTDBDescriptor ioTDBDescriptor = IoTDBDescriptor.getInstance();\r\n createTimeSeriesStatement.setEncoding(ioTDBDescriptor.getDefaultEncodingByType(createTimeSeriesStatement.getDataType()));\r\n if (props != null && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase())) {\r\n String encodingString = props.get(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase()).toUpperCase();\r\n try {\r\n createTimeSeriesStatement.setEncoding(TSEncoding.valueOf(encodingString));\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported encoding: %s\", encodingString));\r\n }\r\n }\r\n createTimeSeriesStatement.setCompressor(TSFileDescriptor.getInstance().getConfig().getCompressor());\r\n if (props != null && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase())) {\r\n String compressionString = props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase()).toUpperCase();\r\n try {\r\n createTimeSeriesStatement.setCompressor(CompressionType.valueOf(compressionString));\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported compression: %s\", compressionString));\r\n }\r\n } else if (props != null && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase())) {\r\n String compressorString = props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase()).toUpperCase();\r\n try {\r\n createTimeSeriesStatement.setCompressor(CompressionType.valueOf(compressorString));\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported compression: %s\", compressorString));\r\n }\r\n }\r\n createTimeSeriesStatement.setProps(props);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static Map> getParameters(String query){\r\n Map> parameters = new LinkedHashMap<>();\r\n if (query != null && !query.isEmpty()) {\r\n for (String pair : query.split(AND)) {\r\n int equalIndex = pair.indexOf(EQUAL);\r\n String key = equalIndex == -1 ? pair : pair.substring(0, equalIndex);\r\n String value = equalIndex == -1 ? null : pair.substring(equalIndex + 1);\r\n try {\r\n key = URLDecoder.decode(key, UTF_8);\r\n } catch (UnsupportedEncodingException ex) {\r\n }\r\n if (value != null) {\r\n try {\r\n value = URLDecoder.decode(value, UTF_8);\r\n } catch (UnsupportedEncodingException ex) {\r\n }\r\n }\r\n if (!parameters.containsKey(key)) {\r\n parameters.put(key, new ArrayList<>());\r\n }\r\n parameters.get(key).add(value);\r\n }\r\n }\r\n return parameters;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void sanityCheckSubStreamsInfo(final ByteBuffer header, final ArchiveStatistics stats) throws IOException{\r\n int nid = getUnsignedByte(header);\r\n final List numUnpackSubStreamsPerFolder = new LinkedList<>();\r\n if (nid == NID.kNumUnpackStream) {\r\n for (int i = 0; i < stats.numberOfFolders; i++) {\r\n numUnpackSubStreamsPerFolder.add(assertFitsIntoNonNegativeInt(\"numStreams\", readUint64(header)));\r\n }\r\n stats.numberOfUnpackSubStreams = numUnpackSubStreamsPerFolder.stream().mapToLong(Integer::longValue).sum();\r\n nid = getUnsignedByte(header);\r\n } else {\r\n stats.numberOfUnpackSubStreams = stats.numberOfFolders;\r\n }\r\n assertFitsIntoNonNegativeInt(\"totalUnpackStreams\", stats.numberOfUnpackSubStreams);\r\n if (nid == NID.kSize) {\r\n for (final int numUnpackSubStreams : numUnpackSubStreamsPerFolder) {\r\n if (numUnpackSubStreams == 0) {\r\n continue;\r\n }\r\n for (int i = 0; i < numUnpackSubStreams - 1; i++) {\r\n final long size = readUint64(header);\r\n if (size < 0) {\r\n throw new IOException(\"negative unpackSize\");\r\n }\r\n }\r\n }\r\n nid = getUnsignedByte(header);\r\n }\r\n int numDigests = 0;\r\n if (numUnpackSubStreamsPerFolder.isEmpty()) {\r\n numDigests = stats.folderHasCrc == null ? stats.numberOfFolders : stats.numberOfFolders - stats.folderHasCrc.cardinality();\r\n } else {\r\n int folderIdx = 0;\r\n for (final int numUnpackSubStreams : numUnpackSubStreamsPerFolder) {\r\n if (numUnpackSubStreams != 1 || stats.folderHasCrc == null || !stats.folderHasCrc.get(folderIdx++)) {\r\n numDigests += numUnpackSubStreams;\r\n }\r\n }\r\n }\r\n if (nid == NID.kCRC) {\r\n assertFitsIntoNonNegativeInt(\"numDigests\", numDigests);\r\n final int missingCrcs = readAllOrBits(header, numDigests).cardinality();\r\n if (skipBytesFully(header, 4L * missingCrcs) < 4L * missingCrcs) {\r\n throw new IOException(\"invalid number of missing CRCs in SubStreamInfo\");\r\n }\r\n nid = getUnsignedByte(header);\r\n }\r\n if (nid != NID.kEnd) {\r\n throw new IOException(\"Badly terminated SubStreamsInfo\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void cacluateCompassBearings(Referential referential){\r\n for (StopArea boardingPosition : referential.getSharedStopAreas().values()) {\r\n if (boardingPosition.getAreaType() == ChouetteAreaEnum.BoardingPosition && boardingPosition.getCompassBearing() == null) {\r\n Set compassBearings = findCompassBearingForBoardingPosition(boardingPosition);\r\n if (compassBearings.size() > 1) {\r\n Integer min = Collections.min(compassBearings);\r\n Integer max = Collections.max(compassBearings);\r\n int angle = getAngle(min, max);\r\n if (Math.abs(angle) < MAX_DIFF_BEARING_DEGREES) {\r\n compassBearings.clear();\r\n compassBearings.add((max + (angle / 2)) % 360);\r\n log.info(\"Average compass bearing is \" + compassBearings.iterator().next() + \" for BoardingPosition \" + boardingPosition.getObjectId() + \" and name \" + boardingPosition.getName());\r\n }\r\n }\r\n if (compassBearings.size() == 1) {\r\n boardingPosition.setCompassBearing(compassBearings.iterator().next());\r\n } else if (compassBearings.size() > 1) {\r\n log.warn(\"Found at least 2 conflicting compass bearings \" + ToStringBuilder.reflectionToString(compassBearings.toArray(), ToStringStyle.SIMPLE_STYLE) + \" for BoardingPosition \" + boardingPosition.getObjectId() + \" and name \" + boardingPosition.getName());\r\n } else {\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static TServerSocket getServerSSLSocket(String hiveHost, int portNum, String keyStorePath, String keyStorePassWord, String keyStoreType, String keyStoreAlgorithm, List sslVersionBlacklist, String includeCipherSuites) throws TTransportException, UnknownHostException{\r\n TSSLTransportFactory.TSSLTransportParameters params = null;\r\n if (!includeCipherSuites.trim().isEmpty()) {\r\n Set includeCS = Sets.newHashSet(Splitter.on(\":\").trimResults().omitEmptyStrings().split(includeCipherSuites.trim()));\r\n int eSize = includeCS.size();\r\n if (eSize > 0) {\r\n params = new TSSLTransportFactory.TSSLTransportParameters(\"TLS\", includeCS.toArray(new String[eSize]));\r\n }\r\n }\r\n if (params == null) {\r\n params = new TSSLTransportFactory.TSSLTransportParameters();\r\n }\r\n String kStoreType = keyStoreType.isEmpty() ? KeyStore.getDefaultType() : keyStoreType;\r\n String kStoreAlgorithm = keyStoreAlgorithm.isEmpty() ? KeyManagerFactory.getDefaultAlgorithm() : keyStoreAlgorithm;\r\n params.setKeyStore(keyStorePath, keyStorePassWord, kStoreAlgorithm, kStoreType);\r\n InetSocketAddress serverAddress;\r\n if (hiveHost == null || hiveHost.isEmpty()) {\r\n serverAddress = new InetSocketAddress(portNum);\r\n } else {\r\n serverAddress = new InetSocketAddress(hiveHost, portNum);\r\n }\r\n TServerSocket thriftServerSocket = TSSLTransportFactory.getServerSocket(portNum, 0, serverAddress.getAddress(), params);\r\n if (thriftServerSocket.getServerSocket() instanceof SSLServerSocket) {\r\n List sslVersionBlacklistLocal = new ArrayList();\r\n for (String sslVersion : sslVersionBlacklist) {\r\n sslVersionBlacklistLocal.add(sslVersion.trim().toLowerCase());\r\n }\r\n SSLServerSocket sslServerSocket = (SSLServerSocket) thriftServerSocket.getServerSocket();\r\n List enabledProtocols = new ArrayList();\r\n for (String protocol : sslServerSocket.getEnabledProtocols()) {\r\n if (sslVersionBlacklistLocal.contains(protocol.toLowerCase())) {\r\n LOG.debug(\"Disabling SSL Protocol: \" + protocol);\r\n } else {\r\n enabledProtocols.add(protocol);\r\n }\r\n }\r\n sslServerSocket.setEnabledProtocols(enabledProtocols.toArray(new String[0]));\r\n LOG.info(\"SSL Server Socket Enabled Protocols: \" + Arrays.toString(sslServerSocket.getEnabledProtocols()));\r\n }\r\n return thriftServerSocket;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ObsClient initClient(){\r\n if (obsClient != null) {\r\n return obsClient;\r\n }\r\n if (ObjectHelper.isEmpty(getServiceKeys()) && ObjectHelper.isEmpty(getAccessKey())) {\r\n throw new IllegalArgumentException(\"Authentication parameter 'access key (AK)' not found\");\r\n }\r\n if (ObjectHelper.isEmpty(getServiceKeys()) && ObjectHelper.isEmpty(getSecretKey())) {\r\n throw new IllegalArgumentException(\"Authentication parameter 'secret key (SK)' not found\");\r\n }\r\n ObsConfiguration obsConfiguration = new ObsConfiguration();\r\n if (ObjectHelper.isNotEmpty(getEndpoint())) {\r\n obsConfiguration.setEndPoint(getEndpoint());\r\n } else if (ObjectHelper.isNotEmpty(getRegion())) {\r\n obsConfiguration.setEndPoint(OBSRegion.valueOf(getRegion()));\r\n } else {\r\n throw new IllegalArgumentException(\"Region/endpoint not found\");\r\n }\r\n if (ObjectHelper.isNotEmpty(getProxyHost()) && ObjectHelper.isNotEmpty(getProxyPort())) {\r\n HttpProxyConfiguration httpConfig = new HttpProxyConfiguration();\r\n httpConfig.setProxyAddr(getProxyHost());\r\n httpConfig.setProxyPort(getProxyPort());\r\n if (ObjectHelper.isNotEmpty(getProxyUser())) {\r\n httpConfig.setProxyUName(getProxyUser());\r\n if (ObjectHelper.isNotEmpty(getProxyPassword())) {\r\n httpConfig.setUserPaaswd(getProxyPassword());\r\n }\r\n }\r\n obsConfiguration.setHttpProxy(httpConfig);\r\n }\r\n obsConfiguration.setValidateCertificate(!isIgnoreSslVerification());\r\n String auth = getServiceKeys() != null ? getServiceKeys().getAccessKey() : getAccessKey();\r\n String secret = getServiceKeys() != null ? getServiceKeys().getSecretKey() : getSecretKey();\r\n return new ObsClient(auth, secret, obsConfiguration);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " final void mainSort(final BZip2CompressorOutputStream.Data dataShadow, final int lastShadow){\r\n final int[] runningOrder = this.mainSort_runningOrder;\r\n final int[] copy = this.mainSort_copy;\r\n final boolean[] bigDone = this.mainSort_bigDone;\r\n final int[] ftab = this.ftab;\r\n final byte[] block = dataShadow.block;\r\n final int[] fmap = dataShadow.fmap;\r\n final char[] quadrant = this.quadrant;\r\n final int workLimitShadow = this.workLimit;\r\n final boolean firstAttemptShadow = this.firstAttempt;\r\n Arrays.fill(ftab, 0);\r\n for (int i = 0; i < BZip2Constants.NUM_OVERSHOOT_BYTES; i++) {\r\n block[lastShadow + i + 2] = block[(i % (lastShadow + 1)) + 1];\r\n }\r\n for (int i = lastShadow + BZip2Constants.NUM_OVERSHOOT_BYTES + 1; --i >= 0; ) {\r\n quadrant[i] = 0;\r\n }\r\n block[0] = block[lastShadow + 1];\r\n int c1 = block[0] & 0xff;\r\n for (int i = 0; i <= lastShadow; i++) {\r\n final int c2 = block[i + 1] & 0xff;\r\n ftab[(c1 << 8) + c2]++;\r\n c1 = c2;\r\n }\r\n for (int i = 1; i <= 65536; i++) {\r\n ftab[i] += ftab[i - 1];\r\n }\r\n c1 = block[1] & 0xff;\r\n for (int i = 0; i < lastShadow; i++) {\r\n final int c2 = block[i + 2] & 0xff;\r\n fmap[--ftab[(c1 << 8) + c2]] = i;\r\n c1 = c2;\r\n }\r\n fmap[--ftab[((block[lastShadow + 1] & 0xff) << 8) + (block[1] & 0xff)]] = lastShadow;\r\n for (int i = 256; --i >= 0; ) {\r\n bigDone[i] = false;\r\n runningOrder[i] = i;\r\n }\r\n for (int h = 364; h != 1; ) {\r\n h /= 3;\r\n for (int i = h; i <= 255; i++) {\r\n final int vv = runningOrder[i];\r\n final int a = ftab[(vv + 1) << 8] - ftab[vv << 8];\r\n final int b = h - 1;\r\n int j = i;\r\n for (int ro = runningOrder[j - h]; (ftab[(ro + 1) << 8] - ftab[ro << 8]) > a; ro = runningOrder[j - h]) {\r\n runningOrder[j] = ro;\r\n j -= h;\r\n if (j <= b) {\r\n break;\r\n }\r\n }\r\n runningOrder[j] = vv;\r\n }\r\n }\r\n for (int i = 0; i <= 255; i++) {\r\n final int ss = runningOrder[i];\r\n for (int j = 0; j <= 255; j++) {\r\n final int sb = (ss << 8) + j;\r\n final int ftab_sb = ftab[sb];\r\n if ((ftab_sb & SETMASK) != SETMASK) {\r\n final int lo = ftab_sb & CLEARMASK;\r\n final int hi = (ftab[sb + 1] & CLEARMASK) - 1;\r\n if (hi > lo) {\r\n mainQSort3(dataShadow, lo, hi, 2, lastShadow);\r\n if (firstAttemptShadow && (this.workDone > workLimitShadow)) {\r\n return;\r\n }\r\n }\r\n ftab[sb] = ftab_sb | SETMASK;\r\n }\r\n }\r\n for (int j = 0; j <= 255; j++) {\r\n copy[j] = ftab[(j << 8) + ss] & CLEARMASK;\r\n }\r\n for (int j = ftab[ss << 8] & CLEARMASK, hj = (ftab[(ss + 1) << 8] & CLEARMASK); j < hj; j++) {\r\n final int fmap_j = fmap[j];\r\n c1 = block[fmap_j] & 0xff;\r\n if (!bigDone[c1]) {\r\n fmap[copy[c1]] = (fmap_j == 0) ? lastShadow : (fmap_j - 1);\r\n copy[c1]++;\r\n }\r\n }\r\n for (int j = 256; --j >= 0; ) {\r\n ftab[(j << 8) + ss] |= SETMASK;\r\n }\r\n bigDone[ss] = true;\r\n if (i < 255) {\r\n final int bbStart = ftab[ss << 8] & CLEARMASK;\r\n final int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart;\r\n int shifts = 0;\r\n while ((bbSize >> shifts) > 65534) {\r\n shifts++;\r\n }\r\n for (int j = 0; j < bbSize; j++) {\r\n final int a2update = fmap[bbStart + j];\r\n final char qVal = (char) (j >> shifts);\r\n quadrant[a2update] = qVal;\r\n if (a2update < BZip2Constants.NUM_OVERSHOOT_BYTES) {\r\n quadrant[a2update + lastShadow + 1] = qVal;\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CompletableFuture> readBookieServiceInfoAsync(BookieId bookieId){\r\n String pathAsWritable = bookieRegistrationPath + \"/\" + bookieId;\r\n String pathAsReadonly = bookieReadonlyRegistrationPath + \"/\" + bookieId;\r\n CompletableFuture> promise = new CompletableFuture<>();\r\n zk.getData(pathAsWritable, bookieServiceInfoCacheInvalidation, (int rc, String path, Object o, byte[] bytes, Stat stat) -> {\r\n if (KeeperException.Code.OK.intValue() == rc) {\r\n try {\r\n BookieServiceInfo bookieServiceInfo = deserializeBookieServiceInfo(bookieId, bytes);\r\n Versioned result = new Versioned<>(bookieServiceInfo, new LongVersion(stat.getCversion()));\r\n log.info(\"Update BookieInfoCache (writable bookie) {} -> {}\", bookieId, result.getValue());\r\n bookieServiceInfoCache.put(bookieId, result);\r\n promise.complete(result);\r\n } catch (IOException ex) {\r\n log.error(\"Cannot update BookieInfo for \", ex);\r\n promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path).initCause(ex));\r\n return;\r\n }\r\n } else if (KeeperException.Code.NONODE.intValue() == rc) {\r\n zk.getData(pathAsReadonly, bookieServiceInfoCacheInvalidation, (int rc2, String path2, Object o2, byte[] bytes2, Stat stat2) -> {\r\n if (KeeperException.Code.OK.intValue() == rc2) {\r\n try {\r\n BookieServiceInfo bookieServiceInfo = deserializeBookieServiceInfo(bookieId, bytes2);\r\n Versioned result = new Versioned<>(bookieServiceInfo, new LongVersion(stat2.getCversion()));\r\n log.info(\"Update BookieInfoCache (readonly bookie) {} -> {}\", bookieId, result.getValue());\r\n bookieServiceInfoCache.put(bookieId, result);\r\n promise.complete(result);\r\n } catch (IOException ex) {\r\n log.error(\"Cannot update BookieInfo for \", ex);\r\n promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc2), path2).initCause(ex));\r\n return;\r\n }\r\n } else {\r\n promise.completeExceptionally(BKException.create(BKException.Code.NoBookieAvailableException));\r\n }\r\n }, null);\r\n } else {\r\n promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path));\r\n }\r\n }, null);\r\n return promise;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static ByteString trim_(ByteString s, boolean left, boolean right){\r\n int j = s.length();\r\n if (right) {\r\n for (; ; ) {\r\n if (j == 0) {\r\n return ByteString.EMPTY;\r\n }\r\n if (s.byteAt(j - 1) != 0) {\r\n break;\r\n }\r\n --j;\r\n }\r\n }\r\n int i = 0;\r\n if (left) {\r\n for (; ; ) {\r\n if (i == j) {\r\n return ByteString.EMPTY;\r\n }\r\n if (s.byteAt(i) != 0) {\r\n break;\r\n }\r\n ++i;\r\n }\r\n }\r\n return s.substring(i, j);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void remove(){\r\n if (lastRet < 0) {\r\n throw new IllegalStateException();\r\n }\r\n --size;\r\n --cursor;\r\n if (end == start + 1) {\r\n final E[] prev = prev(currentChunk());\r\n final E[] next = ChunkList.next(currentChunk());\r\n if (next == null) {\r\n last = prev;\r\n if (prev == null) {\r\n first = null;\r\n } else {\r\n setNext(prev, null);\r\n }\r\n chunk = null;\r\n end = HEADER_SIZE;\r\n } else {\r\n if (prev == null) {\r\n chunk = first = next;\r\n setPrev(next, null);\r\n end = occupied(requireNonNull(chunk, \"chunk\"));\r\n } else {\r\n setNext(prev, next);\r\n setPrev(next, prev);\r\n chunk = prev;\r\n end = start;\r\n start -= occupied(requireNonNull(chunk, \"chunk\"));\r\n }\r\n }\r\n lastRet = -1;\r\n return;\r\n }\r\n final int r = lastRet;\r\n lastRet = -1;\r\n if (r < start) {\r\n E[] c = chunk;\r\n if (c == null) {\r\n c = last;\r\n }\r\n int o = occupied(castNonNull(c));\r\n if (o == 1) {\r\n final E[] prev = prev(c);\r\n if (prev == null) {\r\n if (chunk == null) {\r\n first = last = null;\r\n } else {\r\n first = chunk;\r\n setPrev(requireNonNull(chunk, \"chunk\"), null);\r\n }\r\n } else {\r\n setNext(requireNonNull(prev, \"prev\"), chunk);\r\n setPrev(requireNonNull(chunk, \"chunk\"), prev);\r\n }\r\n } else {\r\n --o;\r\n setElement(c, HEADER_SIZE + o, null);\r\n setOccupied(c, o);\r\n }\r\n } else {\r\n System.arraycopy(currentChunk(), HEADER_SIZE + r - start + 1, currentChunk(), HEADER_SIZE + r - start, end - r - 1);\r\n --end;\r\n final int o = end - start;\r\n setElement(currentChunk(), HEADER_SIZE + o, null);\r\n setOccupied(currentChunk(), o);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean isEncodingCanonical(byte[] signature){\r\n if (signature.length < 9 || signature.length > 73)\r\n return false;\r\n int hashType = (signature[signature.length - 1] & 0xff) & ~(SigHash.Flags.ANYONECANPAY.value | SigHash.Flags.FORKID.value);\r\n if (hashType < SigHash.Flags.ALL.value || hashType > SigHash.Flags.SINGLE.value)\r\n return false;\r\n if ((signature[0] & 0xff) != 0x30 || (signature[1] & 0xff) != signature.length - 3)\r\n return false;\r\n int lenR = signature[3] & 0xff;\r\n if (5 + lenR >= signature.length || lenR == 0)\r\n return false;\r\n int lenS = signature[5 + lenR] & 0xff;\r\n if (lenR + lenS + 7 != signature.length || lenS == 0)\r\n return false;\r\n if (signature[4 - 2] != 0x02 || (signature[4] & 0x80) == 0x80)\r\n return false;\r\n if (lenR > 1 && signature[4] == 0x00 && (signature[4 + 1] & 0x80) != 0x80)\r\n return false;\r\n if (signature[6 + lenR - 2] != 0x02 || (signature[6 + lenR] & 0x80) == 0x80)\r\n return false;\r\n if (lenS > 1 && signature[6 + lenR] == 0x00 && (signature[6 + lenR + 1] & 0x80) != 0x80)\r\n return false;\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ReadResponse getReadResponse(){\r\n final Stopwatch startTimeSw = Stopwatch.createStarted();\r\n final ReadResponse.Builder readResponse = ReadResponse.newBuilder().setLedgerId(ledgerId).setEntryId(entryId);\r\n try {\r\n if (RequestUtils.isFenceRequest(readRequest)) {\r\n LOG.info(\"Ledger fence request received for ledger: {} from address: {}\", ledgerId, channel.remoteAddress());\r\n if (!readRequest.hasMasterKey()) {\r\n LOG.error(\"Fence ledger request received without master key for ledger:{} from address: {}\", ledgerId, channel.remoteAddress());\r\n throw BookieException.create(BookieException.Code.UnauthorizedAccessException);\r\n } else {\r\n byte[] masterKey = readRequest.getMasterKey().toByteArray();\r\n fenceResult = requestProcessor.bookie.fenceLedger(ledgerId, masterKey);\r\n }\r\n }\r\n return readEntry(readResponse, entryId, startTimeSw);\r\n } catch (Bookie.NoLedgerException e) {\r\n if (RequestUtils.isFenceRequest(readRequest)) {\r\n LOG.info(\"No ledger found reading entry {} when fencing ledger {}\", entryId, ledgerId);\r\n } else if (entryId != BookieProtocol.LAST_ADD_CONFIRMED) {\r\n LOG.info(\"No ledger found while reading entry: {} from ledger: {}\", entryId, ledgerId);\r\n } else if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"No ledger found while reading entry: {} from ledger: {}\", entryId, ledgerId);\r\n }\r\n return buildResponse(readResponse, StatusCode.ENOLEDGER, startTimeSw);\r\n } catch (Bookie.NoEntryException e) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"No entry found while reading entry: {} from ledger: {}\", entryId, ledgerId);\r\n }\r\n return buildResponse(readResponse, StatusCode.ENOENTRY, startTimeSw);\r\n } catch (IOException e) {\r\n LOG.error(\"IOException while reading entry: {} from ledger {} \", entryId, ledgerId, e);\r\n return buildResponse(readResponse, StatusCode.EIO, startTimeSw);\r\n } catch (BookieException.DataUnknownException e) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ledger has unknown state for entry: {} from ledger {}\", entryId, ledgerId);\r\n }\r\n return buildResponse(readResponse, StatusCode.EUNKNOWNLEDGERSTATE, startTimeSw);\r\n } catch (BookieException e) {\r\n LOG.error(\"Unauthorized access to ledger:{} while reading entry:{} in request from address: {}\", ledgerId, entryId, channel.remoteAddress());\r\n return buildResponse(readResponse, StatusCode.EUA, startTimeSw);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static ConsumerBuilder getBuilder(final String name, final PulsarEndpoint pulsarEndpoint, final PulsarConsumer pulsarConsumer){\r\n final PulsarConfiguration endpointConfiguration = pulsarEndpoint.getPulsarConfiguration();\r\n ConsumerBuilder builder = pulsarEndpoint.getPulsarClient().newConsumer();\r\n if (endpointConfiguration.getKeySharedPolicy() != null) {\r\n if (\"AUTO_SPLIT\".equalsIgnoreCase(endpointConfiguration.getKeySharedPolicy())) {\r\n builder.keySharedPolicy(KeySharedPolicy.autoSplitHashRange());\r\n } else if (\"STICKY\".equalsIgnoreCase(endpointConfiguration.getKeySharedPolicy())) {\r\n builder.keySharedPolicy(KeySharedPolicy.stickyHashRange());\r\n } else {\r\n throw new IllegalArgumentException(\"Unsupported KeySharedPolicy: \" + endpointConfiguration.getKeySharedPolicy());\r\n }\r\n }\r\n if (endpointConfiguration.isTopicsPattern()) {\r\n builder.topicsPattern(pulsarEndpoint.getUri());\r\n if (endpointConfiguration.getSubscriptionTopicsMode() != null) {\r\n builder.subscriptionTopicsMode(endpointConfiguration.getSubscriptionTopicsMode());\r\n }\r\n } else {\r\n builder.topic(pulsarEndpoint.getUri());\r\n }\r\n builder.subscriptionName(endpointConfiguration.getSubscriptionName()).receiverQueueSize(endpointConfiguration.getConsumerQueueSize()).consumerName(name).ackTimeout(endpointConfiguration.getAckTimeoutMillis(), TimeUnit.MILLISECONDS).subscriptionInitialPosition(endpointConfiguration.getSubscriptionInitialPosition().toPulsarSubscriptionInitialPosition()).acknowledgmentGroupTime(endpointConfiguration.getAckGroupTimeMillis(), TimeUnit.MILLISECONDS).negativeAckRedeliveryDelay(endpointConfiguration.getNegativeAckRedeliveryDelayMicros(), TimeUnit.MICROSECONDS).readCompacted(endpointConfiguration.isReadCompacted());\r\n if (endpointConfiguration.isMessageListener()) {\r\n builder.messageListener(new PulsarMessageListener(pulsarEndpoint, pulsarConsumer));\r\n }\r\n if (endpointConfiguration.isEnableRetry()) {\r\n builder.enableRetry(true);\r\n DeadLetterPolicyBuilder policy = DeadLetterPolicy.builder().maxRedeliverCount(endpointConfiguration.getMaxRedeliverCount());\r\n if (endpointConfiguration.getRetryLetterTopic() != null) {\r\n policy.retryLetterTopic(endpointConfiguration.getRetryLetterTopic());\r\n }\r\n builder.deadLetterPolicy(policy.build());\r\n } else if (endpointConfiguration.getMaxRedeliverCount() != null) {\r\n DeadLetterPolicyBuilder policy = DeadLetterPolicy.builder().maxRedeliverCount(endpointConfiguration.getMaxRedeliverCount());\r\n if (endpointConfiguration.getDeadLetterTopic() != null) {\r\n policy.deadLetterTopic(endpointConfiguration.getDeadLetterTopic());\r\n }\r\n builder.deadLetterPolicy(policy.build());\r\n }\r\n if (ObjectHelper.isNotEmpty(endpointConfiguration.getAckTimeoutRedeliveryBackoff())) {\r\n builder.ackTimeoutRedeliveryBackoff(endpointConfiguration.getAckTimeoutRedeliveryBackoff());\r\n }\r\n if (ObjectHelper.isNotEmpty(endpointConfiguration.getNegativeAckRedeliveryBackoff())) {\r\n builder.negativeAckRedeliveryBackoff(endpointConfiguration.getNegativeAckRedeliveryBackoff());\r\n }\r\n return builder;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Method getMatchingAccessibleMethod(final Class cls, final String methodName, final Class... parameterTypes){\r\n try {\r\n return MemberUtils.setAccessibleWorkaround(cls.getMethod(methodName, parameterTypes));\r\n } catch (final NoSuchMethodException ignored) {\r\n }\r\n final Method[] methods = cls.getMethods();\r\n final List matchingMethods = Stream.of(methods).filter(method -> method.getName().equals(methodName) && MemberUtils.isMatchingMethod(method, parameterTypes)).collect(Collectors.toList());\r\n matchingMethods.sort(METHOD_BY_SIGNATURE);\r\n Method bestMatch = null;\r\n for (final Method method : matchingMethods) {\r\n final Method accessibleMethod = getAccessibleMethod(method);\r\n if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareMethodFit(accessibleMethod, bestMatch, parameterTypes) < 0)) {\r\n bestMatch = accessibleMethod;\r\n }\r\n }\r\n if (bestMatch != null) {\r\n MemberUtils.setAccessibleWorkaround(bestMatch);\r\n }\r\n if (bestMatch != null && bestMatch.isVarArgs() && bestMatch.getParameterTypes().length > 0 && parameterTypes.length > 0) {\r\n final Class[] methodParameterTypes = bestMatch.getParameterTypes();\r\n final Class methodParameterComponentType = methodParameterTypes[methodParameterTypes.length - 1].getComponentType();\r\n final String methodParameterComponentTypeName = ClassUtils.primitiveToWrapper(methodParameterComponentType).getName();\r\n final Class lastParameterType = parameterTypes[parameterTypes.length - 1];\r\n final String parameterTypeName = lastParameterType == null ? null : lastParameterType.getName();\r\n final String parameterTypeSuperClassName = lastParameterType == null ? null : lastParameterType.getSuperclass().getName();\r\n if (parameterTypeName != null && parameterTypeSuperClassName != null && !methodParameterComponentTypeName.equals(parameterTypeName) && !methodParameterComponentTypeName.equals(parameterTypeSuperClassName)) {\r\n return null;\r\n }\r\n }\r\n return bestMatch;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void processWithConnectedChannel(final Exchange exchange, final BodyReleaseCallback callback, final ChannelFuture channelFuture, final Object body){\r\n final Channel channel = channelFuture.channel();\r\n if (getConfiguration().isReuseChannel() && exchange.getProperty(NettyConstants.NETTY_CHANNEL) == null) {\r\n channel.attr(CORRELATION_MANAGER_ATTR).set(correlationManager);\r\n exchange.setProperty(NettyConstants.NETTY_CHANNEL, channel);\r\n exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() {\r\n\r\n @Override\r\n public void onComplete(Exchange exchange) {\r\n Boolean close;\r\n if (ExchangeHelper.isOutCapable(exchange)) {\r\n close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);\r\n } else {\r\n close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);\r\n }\r\n boolean disconnect = getConfiguration().isDisconnect();\r\n if (close != null) {\r\n disconnect = close;\r\n }\r\n if (disconnect) {\r\n LOG.trace(\"Closing channel {} as routing the Exchange is done\", channel);\r\n NettyHelper.close(channel);\r\n }\r\n releaseChannel(channelFuture);\r\n }\r\n });\r\n }\r\n final NettyCamelStateCorrelationManager channelCorrelationManager = Optional.ofNullable(channel.attr(CORRELATION_MANAGER_ATTR).get()).orElse(correlationManager);\r\n if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {\r\n long timeoutInMs = exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);\r\n ChannelHandler oldHandler = channel.pipeline().get(\"timeout\");\r\n ReadTimeoutHandler newHandler = new ReadTimeoutHandler(timeoutInMs, TimeUnit.MILLISECONDS);\r\n if (oldHandler == null) {\r\n channel.pipeline().addBefore(\"handler\", \"timeout\", newHandler);\r\n } else {\r\n channel.pipeline().replace(oldHandler, \"timeout\", newHandler);\r\n }\r\n }\r\n final AsyncCallback producerCallback;\r\n if (configuration.isReuseChannel()) {\r\n producerCallback = callback.getOriginalCallback();\r\n } else {\r\n producerCallback = new NettyProducerCallback(channelFuture, callback.getOriginalCallback());\r\n }\r\n final NettyCamelState state = new NettyCamelState(producerCallback, exchange);\r\n channelCorrelationManager.putState(channel, state);\r\n InetSocketAddress remoteAddress = null;\r\n if (!isTcp()) {\r\n remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());\r\n }\r\n NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, new ChannelFutureListener() {\r\n\r\n public void operationComplete(ChannelFuture channelFuture) throws Exception {\r\n LOG.trace(\"Operation complete {}\", channelFuture);\r\n if (!channelFuture.isSuccess()) {\r\n Throwable cause = null;\r\n try {\r\n channelFuture.get(0, TimeUnit.MILLISECONDS);\r\n } catch (Exception e) {\r\n cause = e.getCause();\r\n }\r\n if (cause != null) {\r\n exchange.setException(cause);\r\n }\r\n state.onExceptionCaughtOnce(false);\r\n return;\r\n }\r\n if (!configuration.isSync()) {\r\n try {\r\n Boolean close;\r\n if (ExchangeHelper.isOutCapable(exchange)) {\r\n close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);\r\n } else {\r\n close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);\r\n }\r\n boolean disconnect = getConfiguration().isDisconnect();\r\n if (close != null) {\r\n disconnect = close;\r\n }\r\n if (!configuration.isReuseChannel() && disconnect) {\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Closing channel when complete at address: {}\", getEndpoint().getConfiguration().getAddress());\r\n }\r\n NettyHelper.close(channel);\r\n }\r\n } finally {\r\n producerCallback.done(false);\r\n }\r\n }\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void parse(byte[] program) throws ScriptParseException{\r\n chunks = new ArrayList(5);\r\n ByteArrayInputStream bis = new ByteArrayInputStream(program);\r\n int initialSize = bis.available();\r\n while (bis.available() > 0) {\r\n int startLocationInProgram = initialSize - bis.available();\r\n int opcode = bis.read();\r\n long dataToRead = -1;\r\n if (opcode >= 0 && opcode < OP_PUSHDATA1) {\r\n dataToRead = opcode;\r\n } else if (opcode == OP_PUSHDATA1) {\r\n if (bis.available() < 1)\r\n throw new ScriptParseException(\"Unexpected end of script\");\r\n dataToRead = bis.read();\r\n } else if (opcode == OP_PUSHDATA2) {\r\n if (bis.available() < 2)\r\n throw new ScriptParseException(\"Unexpected end of script\");\r\n dataToRead = bis.read() | (bis.read() << 8);\r\n } else if (opcode == OP_PUSHDATA4) {\r\n if (bis.available() < 4)\r\n throw new ScriptParseException(\"Unexpected end of script\");\r\n dataToRead = ((long) bis.read()) | (((long) bis.read()) << 8) | (((long) bis.read()) << 16) | (((long) bis.read()) << 24);\r\n }\r\n ScriptChunk chunk;\r\n if (dataToRead == -1) {\r\n chunk = new ScriptChunk(opcode, null, startLocationInProgram);\r\n } else {\r\n if (dataToRead > bis.available())\r\n throw new ScriptParseException(\"Push of data element that is larger than remaining data\");\r\n byte[] data = new byte[(int) dataToRead];\r\n checkState(dataToRead == 0 || bis.read(data, 0, (int) dataToRead) == dataToRead);\r\n chunk = new ScriptChunk(opcode, data, startLocationInProgram);\r\n }\r\n for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {\r\n if (c.equals(chunk))\r\n chunk = c;\r\n }\r\n chunks.add(chunk);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ZooKeeper buildZooKeeper() throws ZooKeeperConnectionException, InterruptedException{\r\n Watcher watcher = new Watcher() {\r\n\r\n @Override\r\n public void process(WatchedEvent event) {\r\n switch(event.getType()) {\r\n case None:\r\n switch(event.getState()) {\r\n case Expired:\r\n if (null == retryPolicy) {\r\n LOG.info(\"ZooKeeper {}' session expired. Event: {}\", name, event);\r\n closeInternal();\r\n }\r\n authenticated = false;\r\n break;\r\n case Disconnected:\r\n if (null == retryPolicy) {\r\n LOG.info(\"ZooKeeper {} is disconnected from zookeeper now,\" + \" but it is OK unless we received EXPIRED event.\", name);\r\n }\r\n authenticated = false;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n try {\r\n for (Watcher watcher : watchers) {\r\n try {\r\n watcher.process(event);\r\n } catch (Throwable t) {\r\n LOG.warn(\"Encountered unexpected exception from watcher {} : \", watcher, t);\r\n }\r\n }\r\n } catch (Throwable t) {\r\n LOG.warn(\"Encountered unexpected exception when firing watched event {} : \", event, t);\r\n }\r\n }\r\n };\r\n Set watchers = new HashSet();\r\n watchers.add(watcher);\r\n ZooKeeper zk;\r\n try {\r\n RetryPolicy opRetryPolicy = null == retryPolicy ? new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0) : retryPolicy;\r\n RetryPolicy connectRetryPolicy = null == retryPolicy ? new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0) : new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, Integer.MAX_VALUE);\r\n zk = org.apache.bookkeeper.zookeeper.ZooKeeperClient.newBuilder().connectString(zooKeeperServers).sessionTimeoutMs(sessionTimeoutMs).watchers(watchers).operationRetryPolicy(opRetryPolicy).connectRetryPolicy(connectRetryPolicy).statsLogger(statsLogger).retryThreadCount(retryThreadCount).requestRateLimit(requestRateLimit).build();\r\n } catch (KeeperException e) {\r\n throw new ZooKeeperConnectionException(\"Problem connecting to servers: \" + zooKeeperServers, e);\r\n } catch (IOException e) {\r\n throw new ZooKeeperConnectionException(\"Problem connecting to servers: \" + zooKeeperServers, e);\r\n }\r\n return zk;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void validateAndInitializeSmnClient(SimpleNotificationEndpoint simpleNotificationEndpoint, ClientConfigurations clientConfigurations){\r\n if (simpleNotificationEndpoint.getSmnClient() != null) {\r\n if (LOG.isWarnEnabled()) {\r\n LOG.warn(\"Instance of SmnClient was set on the endpoint. Skipping creation of SmnClient from endpoint parameters\");\r\n }\r\n this.smnClient = simpleNotificationEndpoint.getSmnClient();\r\n return;\r\n }\r\n if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getSecretKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"secret key (SK) not found\");\r\n }\r\n throw new IllegalArgumentException(\"authentication parameter 'secret key (SK)' not found\");\r\n } else {\r\n clientConfigurations.setSecretKey(simpleNotificationEndpoint.getSecretKey() != null ? simpleNotificationEndpoint.getSecretKey() : simpleNotificationEndpoint.getServiceKeys().getSecretKey());\r\n }\r\n if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getAccessKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"access key (AK) not found\");\r\n }\r\n throw new IllegalArgumentException(\"authentication parameter 'access key (AK)' not found\");\r\n } else {\r\n clientConfigurations.setAccessKey(simpleNotificationEndpoint.getAccessKey() != null ? simpleNotificationEndpoint.getAccessKey() : simpleNotificationEndpoint.getServiceKeys().getAccessKey());\r\n }\r\n if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getProjectId())) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Project ID not found\");\r\n }\r\n throw new IllegalArgumentException(\"project ID not found\");\r\n } else {\r\n clientConfigurations.setProjectId(simpleNotificationEndpoint.getProjectId());\r\n }\r\n if (StringUtils.isNotEmpty(simpleNotificationEndpoint.getEndpoint())) {\r\n clientConfigurations.setServiceEndpoint(simpleNotificationEndpoint.getEndpoint());\r\n } else {\r\n String endpointUrl = SimpleNotificationUtils.resolveSmnServiceEndpoint(simpleNotificationEndpoint.getRegion());\r\n if (endpointUrl == null) {\r\n if (LOG.isErrorEnabled()) {\r\n LOG.error(\"Valid region not found\");\r\n }\r\n throw new IllegalArgumentException(\"enter a valid region\");\r\n } else {\r\n clientConfigurations.setServiceEndpoint(endpointUrl);\r\n }\r\n }\r\n boolean ignoreSslVerification = simpleNotificationEndpoint.isIgnoreSslVerification();\r\n if (ignoreSslVerification) {\r\n if (LOG.isWarnEnabled()) {\r\n LOG.warn(\"SSL verification is ignored. This is unsafe in production environment\");\r\n }\r\n clientConfigurations.setIgnoreSslVerification(ignoreSslVerification);\r\n }\r\n if (simpleNotificationEndpoint.getProxyHost() != null) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Reading http proxy configurations\");\r\n }\r\n clientConfigurations.setProxyHost(simpleNotificationEndpoint.getProxyHost());\r\n clientConfigurations.setProxyPort(simpleNotificationEndpoint.getProxyPort());\r\n clientConfigurations.setProxyUser(simpleNotificationEndpoint.getProxyUser());\r\n clientConfigurations.setProxyPassword(simpleNotificationEndpoint.getProxyPassword());\r\n }\r\n this.smnClient = initializeClient(clientConfigurations);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String getPathForVFS(URL url){\r\n Method m = null;\r\n try {\r\n m = Class.forName(\"org.jboss.vfs.VirtualFile\").getMethod(\"getPhysicalFile\");\r\n } catch (Exception e) {\r\n try {\r\n m = Class.forName(\"org.jboss.vfs.VirtualFile\", true, Thread.currentThread().getContextClassLoader()).getMethod(\"getPhysicalFile\");\r\n } catch (Exception e1) {\r\n log.warn(\"Found virtual file \" + url + \" but org.jboss.vfs.VirtualFile is not available on the classpath\");\r\n }\r\n }\r\n Method m2 = null;\r\n try {\r\n m2 = Class.forName(\"org.jboss.vfs.VFS\").getMethod(\"getChild\", URI.class);\r\n } catch (Exception e) {\r\n try {\r\n m2 = Class.forName(\"org.jboss.vfs.VFS\", true, Thread.currentThread().getContextClassLoader()).getMethod(\"getChild\", URI.class);\r\n } catch (Exception e1) {\r\n log.warn(\"Found virtual file \" + url + \" but org.jboss.vfs.VFS is not available on the classpath\");\r\n }\r\n }\r\n if (m == null || m2 == null) {\r\n return url.getPath();\r\n }\r\n String path = null;\r\n try {\r\n File f = (File) m.invoke(m2.invoke(null, url.toURI()));\r\n path = PortablePath.of(f.getPath()).asString();\r\n } catch (Exception e) {\r\n log.error(\"Error when reading virtual file from \" + url.toString(), e);\r\n }\r\n if (path == null) {\r\n return url.getPath();\r\n }\r\n String urlString = url.toString();\r\n if (!urlString.contains(\"/\" + KieModuleModelImpl.KMODULE_JAR_PATH.asString())) {\r\n return path;\r\n }\r\n int kModulePos = urlString.length() - (\"/\" + KieModuleModelImpl.KMODULE_JAR_PATH.asString()).length();\r\n boolean isInJar = urlString.startsWith(\".jar\", kModulePos - 4);\r\n try {\r\n if (isInJar && path.contains(\"contents/\")) {\r\n String jarName = urlString.substring(0, kModulePos);\r\n jarName = jarName.substring(jarName.lastIndexOf('/') + 1);\r\n String jarFolderPath = path.substring(0, path.length() - (\"contents/\" + KieModuleModelImpl.KMODULE_JAR_PATH.asString()).length());\r\n String jarPath = jarFolderPath + jarName;\r\n path = new File(jarPath).exists() ? jarPath : jarFolderPath + \"content\";\r\n } else if (path.endsWith(\"/\" + KieModuleModelImpl.KMODULE_FILE_NAME)) {\r\n path = path.substring(0, path.length() - (\"/\" + KieModuleModelImpl.KMODULE_JAR_PATH.asString()).length());\r\n }\r\n log.info(\"Virtual file physical path = \" + path);\r\n return path;\r\n } catch (Exception e) {\r\n log.error(\"Error when reading virtual file from \" + url, e);\r\n }\r\n return url.getPath();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private MethodCallExpr whenThenDSL(ConditionalBranchDescr desc, PatternDescr patternRelated, Class patternType, String callMethod, MethodCallExpr parentExpression){\r\n MethodCallExpr when = parentExpression == null ? createDslTopLevelMethod(callMethod) : new MethodCallExpr(parentExpression, callMethod);\r\n final String condition = desc.getCondition().toString();\r\n if (!condition.equals(\"true\")) {\r\n when.addArgument(new StringLiteralExpr(context.getConditionId(patternType, condition)));\r\n String identifier = patternRelated.getIdentifier();\r\n DrlxParseResult parseResult;\r\n if (identifier == null) {\r\n parseResult = ConstraintParser.defaultConstraintParser(context, packageModel).drlxParse(Object.class, \"\", condition);\r\n parseResult.accept((DrlxParseSuccess parseSuccess) -> {\r\n SingleDrlxParseSuccess parseSuccess1 = (SingleDrlxParseSuccess) parseSuccess;\r\n AccumulateDescr source = (AccumulateDescr) patternRelated.getSource();\r\n for (String usedDeclaration : parseSuccess1.getUsedDeclarations()) {\r\n for (AccumulateDescr.AccumulateFunctionCallDescr functionCallDescr : source.getFunctions()) {\r\n if (functionCallDescr.getBind().equals(usedDeclaration)) {\r\n addVariable(patternRelated, when, functionCallDescr);\r\n }\r\n }\r\n }\r\n when.addArgument(generateLambdaWithoutParameters(parseSuccess1.getUsedDeclarations(), parseSuccess.getExpr(), true, Optional.empty()));\r\n });\r\n } else {\r\n when.addArgument(context.getVarExpr(identifier));\r\n parseResult = ConstraintParser.defaultConstraintParser(context, packageModel).drlxParse(patternType, identifier, condition);\r\n Collection usedDeclarations = ((SingleDrlxParseSuccess) parseResult).getUsedDeclarations();\r\n if (usedDeclarations.isEmpty()) {\r\n parseResult.accept(parseSuccess -> when.addArgument(generateLambdaWithoutParameters(Collections.emptySortedSet(), parseSuccess.getExpr())));\r\n } else {\r\n parseResult.accept(parseSuccess -> when.addArgument(generateLambdaWithoutParameters(usedDeclarations, parseSuccess.getExpr(), true, Optional.empty())));\r\n }\r\n }\r\n }\r\n MethodCallExpr then = new MethodCallExpr(when, THEN_CALL);\r\n MethodCallExpr rhs = onDSL(desc.getConsequence());\r\n then.addArgument(rhs);\r\n return then;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized void writeTo(Socket socket) throws MllpSocketException{\r\n if (socket != null && socket.isConnected() && !socket.isClosed()) {\r\n LOG.trace(\"writeTo({}) - entering\", socket);\r\n if (!isEmpty()) {\r\n try {\r\n OutputStream socketOutputStream = socket.getOutputStream();\r\n if (hasStartOfBlock()) {\r\n if (hasEndOfData()) {\r\n socketOutputStream.write(buffer, startOfBlockIndex, endOfBlockIndex - startOfBlockIndex + 2);\r\n } else if (hasEndOfBlock()) {\r\n socketOutputStream.write(buffer, startOfBlockIndex, endOfBlockIndex - startOfBlockIndex + 1);\r\n socketOutputStream.write(MllpProtocolConstants.END_OF_DATA);\r\n } else {\r\n socketOutputStream.write(buffer, startOfBlockIndex, availableByteCount - startOfBlockIndex);\r\n socketOutputStream.write(MllpProtocolConstants.PAYLOAD_TERMINATOR);\r\n }\r\n } else {\r\n socketOutputStream.write(MllpProtocolConstants.START_OF_BLOCK);\r\n socketOutputStream.write(buffer, 0, availableByteCount);\r\n socketOutputStream.write(MllpProtocolConstants.PAYLOAD_TERMINATOR);\r\n }\r\n socketOutputStream.flush();\r\n } catch (IOException ioEx) {\r\n final String exceptionMessage = String.format(\"writeTo(%s) - IOException encountered\", socket);\r\n resetSocket(socket, exceptionMessage);\r\n throw new MllpSocketException(exceptionMessage, ioEx);\r\n }\r\n } else {\r\n LOG.warn(\"writeTo({}) - no data written because buffer is empty\", socket);\r\n }\r\n } else {\r\n LOG.warn(\"writeTo({}) - no data written because Socket is invalid\", socket);\r\n }\r\n LOG.trace(\"writeTo({}) - exiting\", socket);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void patternSource(PatternDescrBuilder pattern) throws RecognitionException{\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.FROM, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_FROM);\r\n }\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.ACCUMULATE)) {\r\n fromAccumulate(pattern);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.COLLECT)) {\r\n fromCollect(pattern);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.ENTRY) && helper.validateLT(2, \"-\") && helper.validateLT(3, DroolsSoftKeywords.POINT)) {\r\n fromEntryPoint(pattern);\r\n if (state.failed)\r\n return;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.WINDOW)) {\r\n fromWindow(pattern);\r\n } else {\r\n fromExpression(pattern);\r\n if (!lastTokenWasWhiteSpace() && input.LA(1) == DRL5Lexer.EOF) {\r\n helper.emit(Location.LOCATION_LHS_FROM);\r\n throw new RecognitionException();\r\n }\r\n if (state.failed)\r\n return;\r\n }\r\n if (input.LA(1) == DRL5Lexer.SEMICOLON) {\r\n match(input, DRL5Lexer.SEMICOLON, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@Nullable\nprotected ViewPartialRewriting compensateViewPartial(RelBuilder relBuilder, RexBuilder rexBuilder, RelMetadataQuery mq, RelNode input, @Nullable Project topProject, RelNode node, Set queryTableRefs, EquivalenceClasses queryEC, @Nullable Project topViewProject, RelNode viewNode, Set viewTableRefs){\r\n if (config.fastBailOut()) {\r\n for (RelNode joinInput : node.getInputs()) {\r\n Set tableReferences = mq.getTableReferences(joinInput);\r\n if (tableReferences == null || tableReferences.containsAll(viewTableRefs)) {\r\n return null;\r\n }\r\n }\r\n }\r\n final Set extraTableRefs = new HashSet<>();\r\n for (RelTableRef tRef : queryTableRefs) {\r\n if (!viewTableRefs.contains(tRef)) {\r\n extraTableRefs.add(tRef);\r\n }\r\n }\r\n Multimap, RelNode> nodeTypes = mq.getNodeTypes(node);\r\n if (nodeTypes == null) {\r\n return null;\r\n }\r\n Collection tableScanNodes = nodeTypes.get(TableScan.class);\r\n List newRels = new ArrayList<>();\r\n for (RelTableRef tRef : extraTableRefs) {\r\n int i = 0;\r\n for (RelNode relNode : tableScanNodes) {\r\n TableScan scan = (TableScan) relNode;\r\n if (tRef.getQualifiedName().equals(scan.getTable().getQualifiedName())) {\r\n if (tRef.getEntityNumber() == i++) {\r\n newRels.add(relNode);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n assert extraTableRefs.size() == newRels.size();\r\n relBuilder.push(input);\r\n for (RelNode newRel : newRels) {\r\n relBuilder.push(newRel);\r\n relBuilder.join(JoinRelType.INNER, rexBuilder.makeLiteral(true));\r\n }\r\n final RelNode newView = relBuilder.build();\r\n relBuilder.push(topViewProject != null ? topViewProject : viewNode);\r\n for (RelNode newRel : newRels) {\r\n relBuilder.push(newRel);\r\n relBuilder.join(JoinRelType.INNER, rexBuilder.makeLiteral(true));\r\n }\r\n final RelNode newViewNode = relBuilder.build();\r\n return ViewPartialRewriting.of(newView, null, newViewNode);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void updateHeader(final AjaxRequestTarget target, final Serializable modelObject){\r\n final String header;\r\n if (modelObject instanceof UserTO) {\r\n header = ((UserTO) modelObject).getUsername();\r\n } else if (modelObject instanceof UserWrapper) {\r\n header = ((UserWrapper) modelObject).getInnerObject().getUsername();\r\n } else if (modelObject instanceof GroupTO) {\r\n header = ((GroupTO) modelObject).getName();\r\n } else if (modelObject instanceof GroupWrapper) {\r\n header = ((GroupWrapper) modelObject).getInnerObject().getName();\r\n } else if (modelObject instanceof AnyObjectTO) {\r\n header = ((AnyObjectTO) modelObject).getName();\r\n } else if (modelObject instanceof AnyObjectWrapper) {\r\n header = ((AnyObjectWrapper) modelObject).getInnerObject().getName();\r\n } else if (modelObject instanceof Attr) {\r\n header = ((Attr) modelObject).getSchema();\r\n } else if (modelObject instanceof ConfParam) {\r\n header = ((ConfParam) modelObject).getSchema();\r\n } else if (modelObject instanceof PolicyTO) {\r\n header = ((PolicyTO) modelObject).getName();\r\n } else if (modelObject instanceof SecurityQuestionTO) {\r\n header = ((SecurityQuestionTO) modelObject).getContent();\r\n } else if (modelObject instanceof AccessTokenTO) {\r\n header = ((AccessTokenTO) modelObject).getOwner();\r\n } else if (modelObject instanceof ExecTO) {\r\n header = ((ExecTO) modelObject).getKey();\r\n } else if (modelObject instanceof StatusBean) {\r\n header = ((StatusBean) modelObject).getResource();\r\n } else if (modelObject instanceof PolicyRuleWrapper) {\r\n header = ((PolicyRuleWrapper) modelObject).getImplementationKey();\r\n } else if (modelObject instanceof CommandWrapper) {\r\n header = ((CommandWrapper) modelObject).getCommand().getKey();\r\n } else if (modelObject instanceof JobTO) {\r\n header = ((JobTO) modelObject).getRefKey() == null ? ((JobTO) modelObject).getRefDesc() : ((JobTO) modelObject).getRefKey();\r\n } else if (modelObject instanceof ToggleableTarget) {\r\n header = ((ToggleableTarget) modelObject).getAnyType();\r\n } else if (modelObject instanceof Domain) {\r\n header = ((Domain) modelObject).getKey();\r\n } else if (modelObject instanceof CommandTO) {\r\n header = ((CommandTO) modelObject).getKey();\r\n } else if (modelObject instanceof NamedEntityTO) {\r\n header = ((NamedEntityTO) modelObject).getName();\r\n } else if (modelObject instanceof EntityTO) {\r\n header = ((EntityTO) modelObject).getKey();\r\n } else if (modelObject instanceof EntityWrapper) {\r\n EntityTO inner = ((EntityWrapper) modelObject).getInnerObject();\r\n header = inner instanceof NamedEntityTO ? ((NamedEntityTO) inner).getName() : inner.getKey();\r\n } else {\r\n header = new ResourceModel(\"actions\", StringUtils.EMPTY).getObject();\r\n }\r\n setHeader(target, header);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private byte[] stampaTemplateByCodice(DatiTemplateRequest request, String codice, DatiTemplateVO dati, UserDetails user){\r\n DatiTemplateCompilatiVO datiTemplateCompilatiVO = request.getDatiTemplateCompilatiVO();\r\n if (datiTemplateCompilatiVO == null)\r\n throw new IllegalArgumentException(\"ddatiTemplateCompilatiVO = null\");\r\n byte[] report;\r\n Map jasperParam = new HashMap<>();\r\n jasperParam.put(\"oggetto\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getOggetto()));\r\n jasperParam.put(\"descrizione\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getDescrizione()));\r\n jasperParam.put(\"fn\", StringUtils.trimToEmpty(dati.getFn()));\r\n jasperParam.put(\"articolo\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getArticolo()));\r\n jasperParam.put(\"indirizzoAvvocato\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getIndirizzoAvvocato()));\r\n jasperParam.put(\"comuneAvvocato\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getComuneAvvocato()));\r\n jasperParam.put(\"mailAvvocato\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getMailAvvocato()));\r\n jasperParam.put(\"studioAvvocato\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getStudioAvvocato()));\r\n jasperParam.put(\"scadenzaPagamento\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getScadenzaPagamento()));\r\n jasperParam.put(\"riferimentoNormativo\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getRiferimentoNormativo()));\r\n troncaRagioneSociale(dati.getListaSoggetti());\r\n for (SoggettoVO soggetto : dati.getListaSoggetti()) {\r\n if (soggetto.getComuneResidenza() != null) {\r\n String cap = soggetto.getCap() != null ? soggetto.getCap() : \"\";\r\n String comune = soggetto.getComuneResidenza().getDenominazione() != null ? soggetto.getComuneResidenza().getDenominazione() : \"\";\r\n soggetto.getComuneResidenza().setDenominazione(cap + \" \" + comune);\r\n } else {\r\n soggetto.setComuneResidenza(new ComuneVO());\r\n soggetto.getComuneResidenza().setDenominazione(\"\");\r\n }\r\n if (soggetto.getProvinciaResidenza() != null) {\r\n String provincia = soggetto.getProvinciaResidenza().getSigla() != null ? soggetto.getProvinciaResidenza().getSigla() : \"\";\r\n soggetto.getProvinciaResidenza().setDenominazione(\"(\" + provincia + \")\");\r\n } else {\r\n soggetto.setProvinciaResidenza(new ProvinciaVO());\r\n soggetto.getProvinciaResidenza().setDenominazione(\"\");\r\n }\r\n if (soggetto.getCivicoResidenza() == null)\r\n soggetto.setCivicoResidenza(\"\");\r\n ;\r\n }\r\n jasperParam.put(\"listaSoggetti\", new JRBeanCollectionDataSource(dati.getListaSoggetti()));\r\n jasperParam.put(\"importoTotale\", dati.getImportoTotale());\r\n jasperParam.put(\"numeroRate\", dati.getNumeroRate());\r\n jasperParam.put(\"scadenzaDefinita\", dati.getScadenzaDefinita());\r\n jasperParam.put(\"importoPrimaRata\", dati.getImportoPrimaRata());\r\n jasperParam.put(\"scadenzaPrimaRata\", dati.getScadenzaPrimaRata());\r\n jasperParam.put(\"importoAltreRate\", dati.getImportoAltreRate());\r\n jasperParam.put(\"importoUltimaRata\", dati.getImportoUltimaRata());\r\n jasperParam.put(\"dirigente\", StringUtils.trimToEmpty(dati.getDirigente()));\r\n jasperParam.put(\"classificazione\", StringUtils.trimToEmpty(dati.getClassificazione()));\r\n CnmTUser cnmTUser = cnmTUserRepository.findOne(user.getIdUser());\r\n jasperParam.put(\"funzionario\", this.ricavaInizialiFunzionario(cnmTUser.getNome(), cnmTUser.getCognome()));\r\n jasperParam.put(\"idMailSettoreTributi\", dati.getMailSettoreTributi());\r\n jasperParam.put(\"processiVerbali\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getProcessiVerbali()));\r\n jasperParam.put(\"nomeAvvocato\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getNomeAvvocato()));\r\n jasperParam.put(\"indirizzo\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getIndirizzo()));\r\n jasperParam.put(\"oraInizio\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getOraInizio()));\r\n jasperParam.put(\"anno\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getAnno()));\r\n jasperParam.put(\"mese\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getMese()));\r\n jasperParam.put(\"giorno\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getGiorno()));\r\n jasperParam.put(\"dichiara\", StringUtils.trimToEmpty(datiTemplateCompilatiVO.getDichiara()));\r\n jasperParam.put(\"intestazione\", getIntestazioneSoggetti(dati.getListaSoggetti()));\r\n jasperParam.put(\"comparizione\", getComparizione(dati.getListaSoggetti()));\r\n jasperParam.put(\"soggettiString\", getSoggettiConcatenati(dati.getListaSoggetti()));\r\n if (codice.equals(Report.REPORT_LETTERA_ACCOMPAGNAMENTO_ANNULLAMENTO.getCodiceDB())) {\r\n jasperParam.put(\"direzioneLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDirezioneLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDirezioneLettera() : \"\");\r\n jasperParam.put(\"settoreLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSettoreLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSettoreLettera() : \"\");\r\n jasperParam.put(\"mailLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getMailLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getMailLettera() : \"\");\r\n jasperParam.put(\"dataLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDataLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDataLettera() : \"\");\r\n jasperParam.put(\"oggettoLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getOggettoLettera()) ? request.getDatiTemplateCompilatiVO().getOggettoLettera() : \"\");\r\n jasperParam.put(\"corpoLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getCorpoLettera()) ? request.getDatiTemplateCompilatiVO().getCorpoLettera() : \"\");\r\n jasperParam.put(\"salutiLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSalutiLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSalutiLettera() : \"\");\r\n jasperParam.put(\"dirigenteLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDirigenteLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getDirigenteLettera() : \"\");\r\n jasperParam.put(\"bloccoFirmaOmessa\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getBloccoFirmaOmessa()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getBloccoFirmaOmessa() : \"\");\r\n jasperParam.put(\"inizialiLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getInizialiLettera()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getInizialiLettera() : \"\");\r\n jasperParam.put(\"sedeEnteRiga1\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga1()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga1() : \"\");\r\n jasperParam.put(\"sedeEnteRiga2\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga2()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga2() : \"\");\r\n jasperParam.put(\"sedeEnteRiga3\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga3()) ? request.getDatiTemplateCompilatiVO().getDatiLetteraAnnullamento().getSedeEnteRiga3() : \"\");\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga1\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1() : \"\");\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga2\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2() : \"\");\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga3\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3() : \"\");\r\n jasperParam.put(\"testoLibero\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getTestoLibero()) ? request.getDatiTemplateCompilatiVO().getTestoLibero() : \"\");\r\n if (StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getTestoLibero())) {\r\n jasperParam.put(\"intestazioneOrganoAccertatore\", \"\");\r\n } else {\r\n jasperParam.put(\"intestazioneOrganoAccertatore\", \"e p.c.\");\r\n }\r\n }\r\n if (codice.equals(Report.REPORT_LETTERA_ACCOMPAGNAMENTO_ARCHIVIAZIONE.getCodiceDB())) {\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga1\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1() : \"\");\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga2\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2() : \"\");\r\n jasperParam.put(\"indirizzoOrganoAccertatoreRiga3\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3()) ? request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3() : \"\");\r\n jasperParam.put(\"testoLibero\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getTestoLibero()) ? request.getDatiTemplateCompilatiVO().getTestoLibero() : \"\");\r\n if (StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga1()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga2()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getIndirizzoOrganoAccertatoreRiga3()) && StringUtils.isBlank(request.getDatiTemplateCompilatiVO().getTestoLibero())) {\r\n jasperParam.put(\"intestazioneOrganoAccertatore\", \"\");\r\n } else {\r\n jasperParam.put(\"intestazioneOrganoAccertatore\", \"e p.c.\");\r\n }\r\n }\r\n if (codice.equals(Report.REPORT_LETTERA_SOLLECITO_RATE.getCodiceDB())) {\r\n jasperParam.put(\"oggettoLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getOggettoLettera()) ? request.getDatiTemplateCompilatiVO().getOggettoLettera() : \"\");\r\n jasperParam.put(\"corpoLettera\", StringUtils.isNotBlank(request.getDatiTemplateCompilatiVO().getCorpoLettera()) ? request.getDatiTemplateCompilatiVO().getCorpoLettera() : \"\");\r\n jasperParam.put(\"dirigenteLettera\", dati.getDirigenteLettera());\r\n }\r\n if (codice.equals(Report.REPORT_CONVOCAZIONE_AUDIZIONE.getCodiceDB())) {\r\n if (dati.getListaSoggetti().size() > 1) {\r\n jasperParam.put(\"sp1\", \"alle S.S.V.V.\");\r\n jasperParam.put(\"sp2\", \" sono convocati\");\r\n jasperParam.put(\"sp3\", \"le S.S.V.V. non comparissero\");\r\n } else {\r\n jasperParam.put(\"sp1\", \"alla S.V.\");\r\n jasperParam.put(\"sp2\", \" \u00c3\u00a8 convocata\");\r\n jasperParam.put(\"sp3\", \"la S.V. non comparisse\");\r\n }\r\n }\r\n try {\r\n report = utilsReport.printReportPDF(codice, jasperParam, null);\r\n } catch (PrintException | IOException | SQLException | JRException e) {\r\n throw new RuntimeException(e);\r\n }\r\n return report;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " V get(long key, int keyHash){\r\n int bucket = keyHash;\r\n long stamp = tryOptimisticRead();\r\n boolean acquiredLock = false;\r\n try {\r\n while (true) {\r\n int capacity = this.capacity;\r\n bucket = signSafeMod(bucket, capacity);\r\n long storedKey = keys[bucket];\r\n V storedValue = values[bucket];\r\n if (!acquiredLock && validate(stamp)) {\r\n if (storedKey == key) {\r\n return storedValue != DeletedValue ? storedValue : null;\r\n } else if (storedValue == EmptyValue) {\r\n return null;\r\n }\r\n } else {\r\n if (!acquiredLock) {\r\n stamp = readLock();\r\n acquiredLock = true;\r\n storedKey = keys[bucket];\r\n storedValue = values[bucket];\r\n }\r\n if (capacity != this.capacity) {\r\n bucket = keyHash;\r\n continue;\r\n }\r\n if (storedKey == key) {\r\n return storedValue != DeletedValue ? storedValue : null;\r\n } else if (storedValue == EmptyValue) {\r\n return null;\r\n }\r\n }\r\n ++bucket;\r\n }\r\n } finally {\r\n if (acquiredLock) {\r\n unlockRead(stamp);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private ReactivityType linkType(Constraint constraint, ModifiedProperty modifiedProperty){\r\n Object value = constraint.getValue();\r\n Object modifiedValue = modifiedProperty.getValue();\r\n if (modifiedValue == null || value == null) {\r\n return ReactivityType.UNKNOWN;\r\n }\r\n if (value instanceof Number && modifiedValue instanceof Number) {\r\n value = ((Number) value).doubleValue();\r\n modifiedValue = ((Number) modifiedValue).doubleValue();\r\n }\r\n switch(constraint.getType()) {\r\n case EQUAL:\r\n if (modifiedValue.equals(value)) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case NOT_EQUAL:\r\n if (!modifiedValue.equals(value)) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case GREATER_THAN:\r\n if (((Comparable) modifiedValue).compareTo(value) > 0) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case GREATER_OR_EQUAL:\r\n if (((Comparable) modifiedValue).compareTo(value) >= 0) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case LESS_THAN:\r\n if (((Comparable) modifiedValue).compareTo(value) < 0) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case LESS_OR_EQUAL:\r\n if (((Comparable) modifiedValue).compareTo(value) <= 0) {\r\n return ReactivityType.POSITIVE;\r\n } else {\r\n return ReactivityType.NEGATIVE;\r\n }\r\n case RANGE:\r\n break;\r\n case UNKNOWN:\r\n break;\r\n }\r\n return ReactivityType.UNKNOWN;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprivate static RelDataType consistentType(SqlRexContext cx, SqlOperandTypeChecker.Consistency consistency, List types){\r\n switch(consistency) {\r\n case COMPARE:\r\n if (SqlTypeUtil.areSameFamily(types)) {\r\n return null;\r\n }\r\n final List nonCharacterTypes = new ArrayList<>();\r\n for (RelDataType type : types) {\r\n if (type.getFamily() != SqlTypeFamily.CHARACTER) {\r\n nonCharacterTypes.add(type);\r\n }\r\n }\r\n if (!nonCharacterTypes.isEmpty()) {\r\n final int typeCount = types.size();\r\n types = nonCharacterTypes;\r\n if (nonCharacterTypes.size() < typeCount) {\r\n final RelDataTypeFamily family = nonCharacterTypes.get(0).getFamily();\r\n if (family instanceof SqlTypeFamily) {\r\n switch((SqlTypeFamily) family) {\r\n case INTEGER:\r\n case NUMERIC:\r\n nonCharacterTypes.add(cx.getTypeFactory().createSqlType(SqlTypeName.BIGINT));\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n case LEAST_RESTRICTIVE:\r\n return cx.getTypeFactory().leastRestrictive(types);\r\n default:\r\n return null;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprotected static Pair, List> computeProjectGroupSet(@Nullable Project projectNode, ImmutableBitSet groupSet, RelDataType inputRowType, DruidQuery druidQuery){\r\n final List dimensionSpecList = new ArrayList<>();\r\n final List virtualColumnList = new ArrayList<>();\r\n final Set usedFieldNames = new HashSet<>();\r\n for (int groupKey : groupSet) {\r\n final DimensionSpec dimensionSpec;\r\n final RexNode project;\r\n if (projectNode == null) {\r\n project = RexInputRef.of(groupKey, inputRowType);\r\n } else {\r\n project = projectNode.getProjects().get(groupKey);\r\n }\r\n Pair druidColumn = toDruidColumn(project, inputRowType, druidQuery);\r\n if (druidColumn.left != null && druidColumn.right == null) {\r\n dimensionSpec = new DefaultDimensionSpec(druidColumn.left, druidColumn.left, DruidExpressions.EXPRESSION_TYPES.get(project.getType().getSqlTypeName()));\r\n usedFieldNames.add(druidColumn.left);\r\n } else if (druidColumn.left != null && druidColumn.right != null) {\r\n final String columnPrefix;\r\n if (project.getKind() == SqlKind.EXTRACT) {\r\n columnPrefix = EXTRACT_COLUMN_NAME_PREFIX + \"_\" + requireNonNull(DruidDateTimeUtils.extractGranularity(project, druidQuery.getConnectionConfig().timeZone()).getType().lowerName);\r\n } else if (project.getKind() == SqlKind.FLOOR) {\r\n columnPrefix = FLOOR_COLUMN_NAME_PREFIX + \"_\" + requireNonNull(DruidDateTimeUtils.extractGranularity(project, druidQuery.getConnectionConfig().timeZone()).getType().lowerName);\r\n } else {\r\n columnPrefix = \"extract\";\r\n }\r\n final String uniqueExtractColumnName = SqlValidatorUtil.uniquify(columnPrefix, usedFieldNames, SqlValidatorUtil.EXPR_SUGGESTER);\r\n dimensionSpec = new ExtractionDimensionSpec(druidColumn.left, druidColumn.right, uniqueExtractColumnName);\r\n usedFieldNames.add(uniqueExtractColumnName);\r\n } else {\r\n final String expression = DruidExpressions.toDruidExpression(project, inputRowType, druidQuery);\r\n if (Strings.isNullOrEmpty(expression)) {\r\n return null;\r\n }\r\n final String name = SqlValidatorUtil.uniquify(\"vc\", usedFieldNames, SqlValidatorUtil.EXPR_SUGGESTER);\r\n VirtualColumn vc = new VirtualColumn(name, expression, DruidExpressions.EXPRESSION_TYPES.get(project.getType().getSqlTypeName()));\r\n virtualColumnList.add(vc);\r\n dimensionSpec = new DefaultDimensionSpec(name, name, DruidExpressions.EXPRESSION_TYPES.get(project.getType().getSqlTypeName()));\r\n usedFieldNames.add(name);\r\n }\r\n dimensionSpecList.add(dimensionSpec);\r\n }\r\n return Pair.of(dimensionSpecList, virtualColumnList);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BibEntry parseEntry(Element e){\r\n String author = null;\r\n String editor = null;\r\n String title = null;\r\n String publisher = null;\r\n String year = null;\r\n String address = null;\r\n String series = null;\r\n String edition = null;\r\n String isbn = null;\r\n String issn = null;\r\n String number = null;\r\n String pagetotal = null;\r\n String volume = null;\r\n String pages = null;\r\n String journal = null;\r\n String ppn = null;\r\n String booktitle = null;\r\n String url = null;\r\n String note = null;\r\n String quelle = \"\";\r\n String mak = \"\";\r\n String subtitle = \"\";\r\n EntryType entryType = StandardEntryType.Book;\r\n List datafields = getChildren(\"datafield\", e);\r\n for (Element datafield : datafields) {\r\n String tag = datafield.getAttribute(\"tag\");\r\n LOGGER.debug(\"tag: \" + tag);\r\n if (\"002@\".equals(tag)) {\r\n mak = getSubfield(\"0\", datafield);\r\n if (mak == null) {\r\n mak = \"\";\r\n }\r\n }\r\n if (\"003@\".equals(tag)) {\r\n ppn = getSubfield(\"0\", datafield);\r\n }\r\n if (\"028A\".equals(tag)) {\r\n String vorname = getSubfield(\"d\", datafield);\r\n String nachname = getSubfield(\"a\", datafield);\r\n if (author == null) {\r\n author = \"\";\r\n } else {\r\n author = author.concat(\" and \");\r\n }\r\n author = author.concat(vorname + \" \" + nachname);\r\n }\r\n if (\"028B\".equals(tag)) {\r\n String vorname = getSubfield(\"d\", datafield);\r\n String nachname = getSubfield(\"a\", datafield);\r\n if (author == null) {\r\n author = \"\";\r\n } else {\r\n author = author.concat(\" and \");\r\n }\r\n author = author.concat(vorname + \" \" + nachname);\r\n }\r\n if (\"028C\".equals(tag)) {\r\n String vorname = getSubfield(\"d\", datafield);\r\n String nachname = getSubfield(\"a\", datafield);\r\n if (editor == null) {\r\n editor = \"\";\r\n } else {\r\n editor = editor.concat(\" and \");\r\n }\r\n editor = editor.concat(vorname + \" \" + nachname);\r\n }\r\n if (\"021A\".equals(tag)) {\r\n title = getSubfield(\"a\", datafield);\r\n subtitle = getSubfield(\"d\", datafield);\r\n }\r\n if (\"033A\".equals(tag)) {\r\n publisher = getSubfield(\"n\", datafield);\r\n address = getSubfield(\"p\", datafield);\r\n }\r\n if (\"011@\".equals(tag)) {\r\n year = getSubfield(\"a\", datafield);\r\n }\r\n if (\"031A\".equals(tag)) {\r\n year = getSubfield(\"j\", datafield);\r\n volume = getSubfield(\"e\", datafield);\r\n number = getSubfield(\"a\", datafield);\r\n pages = getSubfield(\"h\", datafield);\r\n }\r\n if (\"036D\".equals(tag)) {\r\n if (title != null) {\r\n if (title.startsWith(\"@\")) {\r\n title = title.substring(1);\r\n }\r\n number = title;\r\n }\r\n title = getSubfield(\"a\", datafield);\r\n subtitle = getSubfield(\"d\", datafield);\r\n volume = getSubfield(\"l\", datafield);\r\n }\r\n if (\"036E\".equals(tag)) {\r\n series = getSubfield(\"a\", datafield);\r\n number = getSubfield(\"l\", datafield);\r\n String kor = getSubfield(\"b\", datafield);\r\n if (kor != null) {\r\n series = series + \" / \" + kor;\r\n }\r\n }\r\n if (\"037A\".equals(tag)) {\r\n note = getSubfield(\"a\", datafield);\r\n }\r\n if (\"032@\".equals(tag)) {\r\n edition = getSubfield(\"a\", datafield);\r\n }\r\n if (\"004A\".equals(tag)) {\r\n final String isbn10 = getSubfield(\"0\", datafield);\r\n final String isbn13 = getSubfield(\"A\", datafield);\r\n if (isbn10 != null) {\r\n isbn = isbn10;\r\n }\r\n if (isbn13 != null) {\r\n isbn = isbn13;\r\n }\r\n }\r\n if (\"037C\".equals(tag)) {\r\n if (address == null) {\r\n address = getSubfield(\"b\", datafield);\r\n if (address != null) {\r\n address = removeSortCharacters(address);\r\n }\r\n }\r\n String st = getSubfield(\"a\", datafield);\r\n if ((st != null) && st.contains(\"Diss\")) {\r\n entryType = StandardEntryType.PhdThesis;\r\n }\r\n }\r\n if (\"027D\".equals(tag)) {\r\n journal = getSubfield(\"a\", datafield);\r\n booktitle = getSubfield(\"a\", datafield);\r\n address = getSubfield(\"p\", datafield);\r\n publisher = getSubfield(\"n\", datafield);\r\n }\r\n if (\"034D\".equals(tag)) {\r\n pagetotal = getSubfield(\"a\", datafield);\r\n if (pagetotal != null) {\r\n pagetotal = pagetotal.replaceAll(\" S\\\\.?$\", \"\");\r\n }\r\n }\r\n if (\"030F\".equals(tag)) {\r\n address = getSubfield(\"k\", datafield);\r\n if (!\"proceedings\".equals(entryType)) {\r\n subtitle = getSubfield(\"a\", datafield);\r\n }\r\n entryType = StandardEntryType.Proceedings;\r\n }\r\n if (entryType.equals(StandardEntryType.PhdThesis) && (isbn != null)) {\r\n entryType = StandardEntryType.Book;\r\n }\r\n if (\"039B\".equals(tag)) {\r\n quelle = getSubfield(\"8\", datafield);\r\n }\r\n if (\"046R\".equals(tag) && ((quelle == null) || quelle.isEmpty())) {\r\n quelle = getSubfield(\"a\", datafield);\r\n }\r\n if (\"009P\".equals(tag) && (\"03\".equals(datafield.getAttribute(\"occurrence\")) || \"05\".equals(datafield.getAttribute(\"occurrence\"))) && (url == null)) {\r\n url = getSubfield(\"a\", datafield);\r\n }\r\n }\r\n if (quelle == null) {\r\n quelle = \"\";\r\n }\r\n if (author != null) {\r\n author = removeSortCharacters(author);\r\n }\r\n if (editor != null) {\r\n editor = removeSortCharacters(editor);\r\n }\r\n if (title != null) {\r\n title = removeSortCharacters(title);\r\n }\r\n if (subtitle != null) {\r\n subtitle = removeSortCharacters(subtitle);\r\n }\r\n if (mak.startsWith(\"As\")) {\r\n entryType = BibEntry.DEFAULT_TYPE;\r\n if (quelle.contains(\"ISBN\")) {\r\n entryType = StandardEntryType.InCollection;\r\n }\r\n if (quelle.contains(\"ZDB-ID\")) {\r\n entryType = StandardEntryType.Article;\r\n }\r\n } else if (mak.isEmpty()) {\r\n entryType = BibEntry.DEFAULT_TYPE;\r\n } else if (mak.startsWith(\"O\")) {\r\n entryType = BibEntry.DEFAULT_TYPE;\r\n }\r\n BibEntry result = new BibEntry(entryType);\r\n if (author != null) {\r\n result.setField(StandardField.AUTHOR, author);\r\n }\r\n if (editor != null) {\r\n result.setField(StandardField.EDITOR, editor);\r\n }\r\n if (title != null) {\r\n result.setField(StandardField.TITLE, title);\r\n }\r\n if (!Strings.isNullOrEmpty(subtitle)) {\r\n StringBuilder newSubtitle = new StringBuilder(Character.toString(Character.toUpperCase(subtitle.charAt(0))));\r\n if (subtitle.length() > 1) {\r\n newSubtitle.append(subtitle.substring(1));\r\n }\r\n result.setField(StandardField.SUBTITLE, newSubtitle.toString());\r\n }\r\n if (publisher != null) {\r\n result.setField(StandardField.PUBLISHER, publisher);\r\n }\r\n if (year != null) {\r\n result.setField(StandardField.YEAR, year);\r\n }\r\n if (address != null) {\r\n result.setField(StandardField.ADDRESS, address);\r\n }\r\n if (series != null) {\r\n result.setField(StandardField.SERIES, series);\r\n }\r\n if (edition != null) {\r\n result.setField(StandardField.EDITION, edition);\r\n }\r\n if (isbn != null) {\r\n result.setField(StandardField.ISBN, isbn);\r\n }\r\n if (issn != null) {\r\n result.setField(StandardField.ISSN, issn);\r\n }\r\n if (number != null) {\r\n result.setField(StandardField.NUMBER, number);\r\n }\r\n if (pagetotal != null) {\r\n result.setField(StandardField.PAGETOTAL, pagetotal);\r\n }\r\n if (pages != null) {\r\n result.setField(StandardField.PAGES, pages);\r\n }\r\n if (volume != null) {\r\n result.setField(StandardField.VOLUME, volume);\r\n }\r\n if (journal != null) {\r\n result.setField(StandardField.JOURNAL, journal);\r\n }\r\n if (ppn != null) {\r\n result.setField(new UnknownField(\"ppn_GVK\"), ppn);\r\n }\r\n if (url != null) {\r\n result.setField(StandardField.URL, url);\r\n }\r\n if (note != null) {\r\n result.setField(StandardField.NOTE, note);\r\n }\r\n if (\"article\".equals(entryType) && (journal != null)) {\r\n result.setField(StandardField.JOURNAL, journal);\r\n } else if (\"incollection\".equals(entryType) && (booktitle != null)) {\r\n result.setField(StandardField.BOOKTITLE, booktitle);\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String processAcknowledgment(byte[] hl7MessageBytes, byte[] hl7AcknowledgementBytes) throws MllpException{\r\n String acknowledgementType = \"\";\r\n if (hl7AcknowledgementBytes != null && hl7AcknowledgementBytes.length > 3) {\r\n byte fieldDelim = hl7AcknowledgementBytes[3];\r\n int msaStartIndex = -1;\r\n for (int i = 0; i < hl7AcknowledgementBytes.length; ++i) {\r\n if (MllpProtocolConstants.SEGMENT_DELIMITER == hl7AcknowledgementBytes[i]) {\r\n final byte bM = 77;\r\n final byte bS = 83;\r\n final byte bC = 67;\r\n final byte bA = 65;\r\n final byte bE = 69;\r\n final byte bR = 82;\r\n if (hl7AcknowledgementBytes.length > i + 7) {\r\n if (bM == hl7AcknowledgementBytes[i + 1] && bS == hl7AcknowledgementBytes[i + 2] && bA == hl7AcknowledgementBytes[i + 3] && fieldDelim == hl7AcknowledgementBytes[i + 4]) {\r\n msaStartIndex = i + 1;\r\n if (bA != hl7AcknowledgementBytes[i + 5] && bC != hl7AcknowledgementBytes[i + 5]) {\r\n String errorMessage = String.format(\"processAcknowledgment(hl7MessageBytes[%d], hl7AcknowledgementBytes[%d]) - unsupported acknowledgement type: '%s'\", hl7MessageBytes == null ? -1 : hl7MessageBytes.length, hl7AcknowledgementBytes.length, new String(hl7AcknowledgementBytes, i + 5, 2));\r\n throw new MllpInvalidAcknowledgementException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n } else {\r\n switch(hl7AcknowledgementBytes[i + 6]) {\r\n case bA:\r\n if (bA == hl7AcknowledgementBytes[i + 5]) {\r\n acknowledgementType = \"AA\";\r\n } else {\r\n acknowledgementType = \"CA\";\r\n }\r\n break;\r\n case bE:\r\n if (bA == hl7AcknowledgementBytes[i + 5]) {\r\n throw new MllpApplicationErrorAcknowledgementException(hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n } else {\r\n throw new MllpCommitErrorAcknowledgementException(hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n }\r\n case bR:\r\n if (bA == hl7AcknowledgementBytes[i + 5]) {\r\n throw new MllpApplicationRejectAcknowledgementException(hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n } else {\r\n throw new MllpCommitRejectAcknowledgementException(hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n }\r\n default:\r\n String errorMessage = \"Unsupported acknowledgement type: \" + new String(hl7AcknowledgementBytes, i + 5, 2);\r\n throw new MllpInvalidAcknowledgementException(errorMessage, hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (-1 == msaStartIndex && getConfiguration().isValidatePayload()) {\r\n throw new MllpInvalidAcknowledgementException(\"MSA Not found in acknowledgement\", hl7MessageBytes, hl7AcknowledgementBytes, logPhi);\r\n }\r\n }\r\n return acknowledgementType;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AttributeDescr salience(AttributeSupportBuilder as) throws RecognitionException{\r\n AttributeDescrBuilder attribute = null;\r\n try {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.SALIENCE, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n attribute = helper.start((DescrBuilder) as, AttributeDescrBuilder.class, DroolsSoftKeywords.SALIENCE);\r\n }\r\n boolean hasParen = input.LA(1) == DRL6Lexer.LEFT_PAREN;\r\n int first = input.index();\r\n if (hasParen) {\r\n match(input, DRL6Lexer.LEFT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n }\r\n String value = conditionalExpression();\r\n if (state.failed)\r\n return null;\r\n if (hasParen) {\r\n match(input, DRL6Lexer.RIGHT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0) {\r\n if (attribute != null) {\r\n if (hasParen) {\r\n value = input.toString(first, input.LT(-1).getTokenIndex());\r\n }\r\n attribute.value(value);\r\n attribute.type(AttributeDescr.Type.EXPRESSION);\r\n }\r\n }\r\n } finally {\r\n if (attribute != null) {\r\n helper.end(AttributeDescrBuilder.class, attribute);\r\n }\r\n }\r\n return attribute != null ? attribute.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ExpressionEvaluatorResult verifyList(ArrayNode json, List resultRaw){\r\n if (resultRaw == null) {\r\n return ExpressionEvaluatorResult.of(isListEmpty(json));\r\n }\r\n int elementNumber = 0;\r\n for (JsonNode node : json) {\r\n elementNumber++;\r\n boolean success = false;\r\n boolean simpleTypeNode = isSimpleTypeNode(node);\r\n for (Object result : resultRaw) {\r\n if (simpleTypeNode && internalUnaryEvaluation(getSimpleTypeNodeTextValue(node), result, result.getClass(), true)) {\r\n success = true;\r\n } else if (!simpleTypeNode && verifyObject((ObjectNode) node, result).isSuccessful()) {\r\n success = true;\r\n }\r\n if (success) {\r\n break;\r\n }\r\n }\r\n if (!success) {\r\n ExpressionEvaluatorResult evaluatorResult = ExpressionEvaluatorResult.ofFailed();\r\n if (simpleTypeNode) {\r\n evaluatorResult.setWrongValue(getSimpleTypeNodeTextValue(node));\r\n }\r\n evaluatorResult.addListItemStepToPath(elementNumber);\r\n return evaluatorResult;\r\n }\r\n }\r\n return ExpressionEvaluatorResult.ofSuccessful();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Queue createExchanges(List s3ObjectSummaries){\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Received {} messages in this poll\", s3ObjectSummaries.size());\r\n }\r\n Collection> s3Objects = new ArrayList<>();\r\n Queue answer = new LinkedList<>();\r\n try {\r\n for (S3Object s3ObjectSummary : s3ObjectSummaries) {\r\n Builder getRequest = GetObjectRequest.builder().bucket(getConfiguration().getBucketName()).key(s3ObjectSummary.key());\r\n if (getConfiguration().isUseCustomerKey()) {\r\n if (ObjectHelper.isNotEmpty(getConfiguration().getCustomerKeyId())) {\r\n getRequest.sseCustomerKey(getConfiguration().getCustomerKeyId());\r\n }\r\n if (ObjectHelper.isNotEmpty(getConfiguration().getCustomerKeyMD5())) {\r\n getRequest.sseCustomerKeyMD5(getConfiguration().getCustomerKeyMD5());\r\n }\r\n if (ObjectHelper.isNotEmpty(getConfiguration().getCustomerAlgorithm())) {\r\n getRequest.sseCustomerAlgorithm(getConfiguration().getCustomerAlgorithm());\r\n }\r\n }\r\n ResponseInputStream s3Object = getAmazonS3Client().getObject(getRequest.build(), ResponseTransformer.toInputStream());\r\n if (includeS3Object(s3Object)) {\r\n s3Objects.add(s3Object);\r\n Exchange exchange = createExchange(s3Object, s3ObjectSummary.key());\r\n answer.add(exchange);\r\n } else {\r\n IOHelper.close(s3Object);\r\n }\r\n }\r\n } catch (Exception e) {\r\n LOG.warn(\"Error getting S3Object due: {}\", e.getMessage(), e);\r\n s3Objects.forEach(IOHelper::close);\r\n throw e;\r\n }\r\n return answer;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void encodeWithPopulationCodec(final String name, final int[] band, final BHSDCodec defaultCodec, final BandData bandData, final BandAnalysisResults results) throws Pack200Exception{\r\n results.numCodecsTried += 3;\r\n final Map distinctValues = bandData.distinctValues;\r\n final List favored = new ArrayList<>();\r\n distinctValues.forEach((k, v) -> {\r\n if (v.intValue() > 2 || distinctValues.size() < 256) {\r\n favored.add(k);\r\n }\r\n });\r\n if (distinctValues.size() > 255) {\r\n favored.sort((arg0, arg1) -> distinctValues.get(arg1).compareTo(distinctValues.get(arg0)));\r\n }\r\n final Map favoredToIndex = new HashMap<>();\r\n for (int i = 0; i < favored.size(); i++) {\r\n favoredToIndex.put(favored.get(i), Integer.valueOf(i));\r\n }\r\n final IntList unfavoured = new IntList();\r\n final int[] tokens = new int[band.length];\r\n for (int i = 0; i < band.length; i++) {\r\n final Integer favouredIndex = favoredToIndex.get(Integer.valueOf(band[i]));\r\n if (favouredIndex == null) {\r\n tokens[i] = 0;\r\n unfavoured.add(band[i]);\r\n } else {\r\n tokens[i] = favouredIndex.intValue() + 1;\r\n }\r\n }\r\n favored.add(favored.get(favored.size() - 1));\r\n final int[] favouredBand = integerListToArray(favored);\r\n final int[] unfavouredBand = unfavoured.toArray();\r\n final BandAnalysisResults favouredResults = analyseBand(\"POPULATION\", favouredBand, defaultCodec);\r\n final BandAnalysisResults unfavouredResults = analyseBand(\"POPULATION\", unfavouredBand, defaultCodec);\r\n int tdefL = 0;\r\n int l = 0;\r\n Codec tokenCodec = null;\r\n byte[] tokensEncoded;\r\n final int k = favored.size() - 1;\r\n if (k < 256) {\r\n tdefL = 1;\r\n tokensEncoded = Codec.BYTE1.encode(tokens);\r\n } else {\r\n final BandAnalysisResults tokenResults = analyseBand(\"POPULATION\", tokens, defaultCodec);\r\n tokenCodec = tokenResults.betterCodec;\r\n tokensEncoded = tokenResults.encodedBand;\r\n if (tokenCodec == null) {\r\n tokenCodec = defaultCodec;\r\n }\r\n l = ((BHSDCodec) tokenCodec).getL();\r\n final int h = ((BHSDCodec) tokenCodec).getH();\r\n final int s = ((BHSDCodec) tokenCodec).getS();\r\n final int b = ((BHSDCodec) tokenCodec).getB();\r\n final int d = ((BHSDCodec) tokenCodec).isDelta() ? 1 : 0;\r\n if (s == 0 && d == 0) {\r\n boolean canUseTDefL = true;\r\n if (b > 1) {\r\n final BHSDCodec oneLowerB = new BHSDCodec(b - 1, h);\r\n if (oneLowerB.largest() >= k) {\r\n canUseTDefL = false;\r\n }\r\n }\r\n if (canUseTDefL) {\r\n switch(l) {\r\n case 4:\r\n tdefL = 1;\r\n break;\r\n case 8:\r\n tdefL = 2;\r\n break;\r\n case 16:\r\n tdefL = 3;\r\n break;\r\n case 32:\r\n tdefL = 4;\r\n break;\r\n case 64:\r\n tdefL = 5;\r\n break;\r\n case 128:\r\n tdefL = 6;\r\n break;\r\n case 192:\r\n tdefL = 7;\r\n break;\r\n case 224:\r\n tdefL = 8;\r\n break;\r\n case 240:\r\n tdefL = 9;\r\n break;\r\n case 248:\r\n tdefL = 10;\r\n break;\r\n case 252:\r\n tdefL = 11;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n final byte[] favouredEncoded = favouredResults.encodedBand;\r\n final byte[] unfavouredEncoded = unfavouredResults.encodedBand;\r\n final Codec favouredCodec = favouredResults.betterCodec;\r\n final Codec unfavouredCodec = unfavouredResults.betterCodec;\r\n int specifier = 141 + (favouredCodec == null ? 1 : 0) + (4 * tdefL) + (unfavouredCodec == null ? 2 : 0);\r\n final IntList extraBandMetadata = new IntList(3);\r\n if (favouredCodec != null) {\r\n IntStream.of(CodecEncoding.getSpecifier(favouredCodec, null)).forEach(extraBandMetadata::add);\r\n }\r\n if (tdefL == 0) {\r\n IntStream.of(CodecEncoding.getSpecifier(tokenCodec, null)).forEach(extraBandMetadata::add);\r\n }\r\n if (unfavouredCodec != null) {\r\n IntStream.of(CodecEncoding.getSpecifier(unfavouredCodec, null)).forEach(extraBandMetadata::add);\r\n }\r\n final int[] extraMetadata = extraBandMetadata.toArray();\r\n final byte[] extraMetadataEncoded = Codec.UNSIGNED5.encode(extraMetadata);\r\n if (defaultCodec.isSigned()) {\r\n specifier = -1 - specifier;\r\n } else {\r\n specifier = specifier + defaultCodec.getL();\r\n }\r\n final byte[] firstValueEncoded = defaultCodec.encode(new int[] { specifier });\r\n final int totalBandLength = firstValueEncoded.length + favouredEncoded.length + tokensEncoded.length + unfavouredEncoded.length;\r\n if (totalBandLength + extraMetadataEncoded.length < results.encodedBand.length) {\r\n results.saved += results.encodedBand.length - (totalBandLength + extraMetadataEncoded.length);\r\n final byte[] encodedBand = new byte[totalBandLength];\r\n System.arraycopy(firstValueEncoded, 0, encodedBand, 0, firstValueEncoded.length);\r\n System.arraycopy(favouredEncoded, 0, encodedBand, firstValueEncoded.length, favouredEncoded.length);\r\n System.arraycopy(tokensEncoded, 0, encodedBand, firstValueEncoded.length + favouredEncoded.length, tokensEncoded.length);\r\n System.arraycopy(unfavouredEncoded, 0, encodedBand, firstValueEncoded.length + favouredEncoded.length + tokensEncoded.length, unfavouredEncoded.length);\r\n results.encodedBand = encodedBand;\r\n results.extraMetadata = extraMetadata;\r\n if (l != 0) {\r\n results.betterCodec = new PopulationCodec(favouredCodec, l, unfavouredCodec);\r\n } else {\r\n results.betterCodec = new PopulationCodec(favouredCodec, tokenCodec, unfavouredCodec);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic int[] decodeInts(final int n, final InputStream in) throws IOException, Pack200Exception{\r\n lastBandLength = 0;\r\n favoured = new int[n];\r\n int[] result;\r\n int smallest = Integer.MAX_VALUE, absoluteSmallest;\r\n int last = 0;\r\n int value = 0, absoluteValue;\r\n int k = -1;\r\n while (true) {\r\n value = favouredCodec.decode(in, last);\r\n if (k > -1 && (value == smallest || value == last)) {\r\n break;\r\n }\r\n favoured[++k] = value;\r\n absoluteSmallest = Math.abs(smallest);\r\n absoluteValue = Math.abs(value);\r\n if (absoluteSmallest > absoluteValue) {\r\n smallest = value;\r\n } else if (absoluteSmallest == absoluteValue) {\r\n smallest = absoluteSmallest;\r\n }\r\n last = value;\r\n }\r\n lastBandLength += k;\r\n if (tokenCodec == null) {\r\n if (k < 256) {\r\n tokenCodec = Codec.BYTE1;\r\n } else {\r\n int b = 1;\r\n BHSDCodec codec = null;\r\n while (++b < 5) {\r\n codec = new BHSDCodec(b, 256 - l, 0);\r\n if (codec.encodes(k)) {\r\n tokenCodec = codec;\r\n break;\r\n }\r\n }\r\n if (tokenCodec == null) {\r\n throw new Pack200Exception(\"Cannot calculate token codec from \" + k + \" and \" + l);\r\n }\r\n }\r\n }\r\n lastBandLength += n;\r\n result = tokenCodec.decodeInts(n, in);\r\n last = 0;\r\n for (int i = 0; i < n; ++i) {\r\n final int index = result[i];\r\n if (index == 0) {\r\n lastBandLength++;\r\n result[i] = last = unfavouredCodec.decode(in, last);\r\n } else {\r\n result[i] = favoured[index - 1];\r\n }\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " Map translateAttributes(Map headers, Exchange exchange){\r\n Map result = new HashMap<>();\r\n HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy();\r\n for (Entry entry : headers.entrySet()) {\r\n if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) {\r\n Object value = entry.getValue();\r\n if (value instanceof String && !((String) value).isEmpty()) {\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"String\");\r\n mav.stringValue((String) value);\r\n result.put(entry.getKey(), mav.build());\r\n } else if (value instanceof Number) {\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"String\");\r\n mav.stringValue(value.toString());\r\n result.put(entry.getKey(), mav.build());\r\n } else if (value instanceof ByteBuffer) {\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"Binary\");\r\n mav.binaryValue(SdkBytes.fromByteBuffer((ByteBuffer) value));\r\n result.put(entry.getKey(), mav.build());\r\n } else if (value instanceof byte[]) {\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"Binary\");\r\n mav.binaryValue(SdkBytes.fromByteArray((byte[]) value));\r\n result.put(entry.getKey(), mav.build());\r\n } else if (value instanceof Date) {\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"String\");\r\n mav.stringValue(value.toString());\r\n result.put(entry.getKey(), mav.build());\r\n } else if (value instanceof List) {\r\n String resultString = ((List) value).stream().map(o -> o instanceof String ? String.format(\"\\\"%s\\\"\", o) : Objects.toString(o)).collect(Collectors.joining(\", \"));\r\n MessageAttributeValue.Builder mav = MessageAttributeValue.builder();\r\n mav.dataType(\"String.Array\");\r\n mav.stringValue(\"[\" + resultString + \"]\");\r\n result.put(entry.getKey(), mav.build());\r\n } else {\r\n LOG.warn(\"Cannot put the message header key={}, value={} into Sns MessageAttribute\", entry.getKey(), entry.getValue());\r\n }\r\n }\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void linkedAccount(final User user, final LinkedAccountTO accountTO, final AnyUtils anyUtils, final SyncopeClientException invalidValues){\r\n ExternalResource resource = resourceDAO.find(accountTO.getResource());\r\n if (resource == null) {\r\n LOG.debug(\"Ignoring invalid resource {}\", accountTO.getResource());\r\n } else {\r\n Optional found = user.getLinkedAccount(resource.getKey(), accountTO.getConnObjectKeyValue());\r\n LinkedAccount account = found.isPresent() ? found.get() : new Supplier() {\r\n\r\n @Override\r\n public LinkedAccount get() {\r\n LinkedAccount acct = entityFactory.newEntity(LinkedAccount.class);\r\n acct.setOwner(user);\r\n user.add(acct);\r\n acct.setConnObjectKeyValue(accountTO.getConnObjectKeyValue());\r\n acct.setResource(resource);\r\n return acct;\r\n }\r\n }.get();\r\n account.setUsername(accountTO.getUsername());\r\n if (StringUtils.isBlank(accountTO.getPassword())) {\r\n account.setEncodedPassword(null, null);\r\n } else if (!accountTO.getPassword().equals(account.getPassword())) {\r\n if (account.getCipherAlgorithm() == null) {\r\n account.setCipherAlgorithm(CipherAlgorithm.AES);\r\n }\r\n account.setPassword(accountTO.getPassword());\r\n }\r\n account.setSuspended(accountTO.isSuspended());\r\n accountTO.getPlainAttrs().stream().filter(attrTO -> !attrTO.getValues().isEmpty()).forEach(attrTO -> {\r\n PlainSchema schema = getPlainSchema(attrTO.getSchema());\r\n if (schema != null) {\r\n LAPlainAttr attr = account.getPlainAttr(schema.getKey()).orElse(null);\r\n if (attr == null) {\r\n attr = entityFactory.newEntity(LAPlainAttr.class);\r\n attr.setSchema(schema);\r\n attr.setOwner(user);\r\n attr.setAccount(account);\r\n }\r\n fillAttr(attrTO.getValues(), anyUtils, schema, attr, invalidValues);\r\n if (attr.getValuesAsStrings().isEmpty()) {\r\n attr.setOwner(null);\r\n } else {\r\n account.add(attr);\r\n }\r\n }\r\n });\r\n accountTO.getPrivileges().forEach(key -> {\r\n Privilege privilege = applicationDAO.findPrivilege(key);\r\n if (privilege == null) {\r\n LOG.debug(\"Invalid privilege {}, ignoring\", key);\r\n } else {\r\n account.add(privilege);\r\n }\r\n });\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic String toDruidExpression(RexNode rexNode, RelDataType topRel, DruidQuery druidQuery){\r\n final RexNode operand = ((RexCall) rexNode).getOperands().get(0);\r\n final String operandExpression = DruidExpressions.toDruidExpression(operand, topRel, druidQuery);\r\n if (operandExpression == null) {\r\n return null;\r\n }\r\n final SqlTypeName fromType = operand.getType().getSqlTypeName();\r\n String fromTypeString = dateTimeFormatString(fromType);\r\n final SqlTypeName toType = rexNode.getType().getSqlTypeName();\r\n final String timeZoneConf = druidQuery.getConnectionConfig().timeZone();\r\n final TimeZone timeZone = TimeZone.getTimeZone(timeZoneConf == null ? \"UTC\" : timeZoneConf);\r\n final boolean nullEqualToEmpty = druidQuery.getConnectionConfig().nullEqualToEmpty();\r\n if (fromTypeString == null) {\r\n fromTypeString = nullEqualToEmpty ? \"\" : null;\r\n }\r\n if (SqlTypeName.CHAR_TYPES.contains(fromType) && SqlTypeName.DATETIME_TYPES.contains(toType)) {\r\n return castCharToDateTime(toType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? timeZone : DateTimeUtils.UTC_ZONE, operandExpression, toType, fromTypeString);\r\n } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && SqlTypeName.CHAR_TYPES.contains(toType)) {\r\n return castDateTimeToChar(fromType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? timeZone : DateTimeUtils.UTC_ZONE, operandExpression, fromType);\r\n } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && toType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) {\r\n if (timeZone.equals(DateTimeUtils.UTC_ZONE)) {\r\n return operandExpression;\r\n }\r\n return castCharToDateTime(timeZone, castDateTimeToChar(DateTimeUtils.UTC_ZONE, operandExpression, fromType), toType, fromTypeString);\r\n } else if (fromType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE && SqlTypeName.DATETIME_TYPES.contains(toType)) {\r\n if (toType != SqlTypeName.DATE && timeZone.equals(DateTimeUtils.UTC_ZONE)) {\r\n return operandExpression;\r\n }\r\n return castCharToDateTime(DateTimeUtils.UTC_ZONE, castDateTimeToChar(timeZone, operandExpression, fromType), toType, fromTypeString);\r\n } else {\r\n final DruidType fromExprType = DruidExpressions.EXPRESSION_TYPES.get(fromType);\r\n final DruidType toExprType = DruidExpressions.EXPRESSION_TYPES.get(toType);\r\n if (fromExprType == null || toExprType == null) {\r\n return null;\r\n }\r\n final String typeCastExpression;\r\n if (fromExprType != toExprType) {\r\n typeCastExpression = DruidQuery.format(\"CAST(%s, '%s')\", operandExpression, toExprType.toString());\r\n } else {\r\n typeCastExpression = operandExpression;\r\n }\r\n if (toType == SqlTypeName.DATE) {\r\n return DruidExpressions.applyTimestampFloor(typeCastExpression, Period.days(1).toString(), \"\", TimeZone.getTimeZone(druidQuery.getConnectionConfig().timeZone()));\r\n } else {\r\n return typeCastExpression;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readEntryInternal(final long ledgerId, final long entryId, final Long previousLAC, final Long timeOutInMillis, final boolean piggyBackEntry, final ReadEntryCallback cb, final Object ctx, int flags, byte[] masterKey, boolean allowFastFail){\r\n Object request = null;\r\n CompletionKey completionKey = null;\r\n if (useV2WireProtocol) {\r\n request = BookieProtocol.ReadRequest.create(BookieProtocol.CURRENT_PROTOCOL_VERSION, ledgerId, entryId, (short) flags, masterKey);\r\n completionKey = acquireV2Key(ledgerId, entryId, OperationType.READ_ENTRY);\r\n } else {\r\n final long txnId = getTxnId();\r\n completionKey = new V3CompletionKey(txnId, OperationType.READ_ENTRY);\r\n BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE).setOperation(OperationType.READ_ENTRY).setTxnId(txnId);\r\n if (((short) flags & BookieProtocol.FLAG_HIGH_PRIORITY) == BookieProtocol.FLAG_HIGH_PRIORITY) {\r\n headerBuilder.setPriority(DEFAULT_HIGH_PRIORITY_VALUE);\r\n }\r\n ReadRequest.Builder readBuilder = ReadRequest.newBuilder().setLedgerId(ledgerId).setEntryId(entryId);\r\n if (null != previousLAC) {\r\n readBuilder = readBuilder.setPreviousLAC(previousLAC);\r\n }\r\n if (null != timeOutInMillis) {\r\n if (null == previousLAC) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder = readBuilder.setTimeOut(timeOutInMillis);\r\n }\r\n if (piggyBackEntry) {\r\n if (null == previousLAC) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder = readBuilder.setFlag(ReadRequest.Flag.ENTRY_PIGGYBACK);\r\n }\r\n if (((short) flags & BookieProtocol.FLAG_DO_FENCING) == BookieProtocol.FLAG_DO_FENCING) {\r\n readBuilder.setFlag(ReadRequest.Flag.FENCE_LEDGER);\r\n if (masterKey == null) {\r\n cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx);\r\n return;\r\n }\r\n readBuilder.setMasterKey(ByteString.copyFrom(masterKey));\r\n }\r\n request = withRequestContext(Request.newBuilder()).setHeader(headerBuilder).setReadRequest(readBuilder).build();\r\n }\r\n ReadCompletion readCompletion = new ReadCompletion(completionKey, cb, ctx, ledgerId, entryId);\r\n putCompletionKeyValue(completionKey, readCompletion);\r\n writeAndFlush(channel, completionKey, request, allowFastFail);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Integer getIdFormaDocumentaria(ObjectIdType repositoryId, PrincipalIdType principalId, UtenteActa utenteActa) throws IntegrationException{\r\n final String method = \"getIdFormaDocumentaria\";\r\n log.debug(method + \". BEGIN\");\r\n log.debug(method + \". FORMA DOCUMENTARIA= \" + utenteActa.getDescFormaDocumentaria());\r\n if (utenteActa.getDescFormaDocumentaria() == null) {\r\n log.debug(method + \". FORMA DOCUMENTARIA NON VALORIZZATA: restituiamo un valore nullo \");\r\n return null;\r\n }\r\n QueryableObjectType target = new QueryableObjectType();\r\n target.setObject(\"FormaDocumentariaDecodifica\");\r\n PropertyFilterType filter = new PropertyFilterType();\r\n filter.setFilterType(EnumPropertyFilter.ALL);\r\n QueryConditionType[] criteria = null;\r\n if (StringUtils.isEmpty(utenteActa.getDescEnte())) {\r\n criteria = new QueryConditionType[1];\r\n } else {\r\n criteria = new QueryConditionType[2];\r\n }\r\n QueryConditionType qctFormaDocumentaria = new QueryConditionType();\r\n qctFormaDocumentaria.setOperator(EnumQueryOperator.EQUALS);\r\n log.debug(method + \". descrizione = \" + utenteActa.getDescFormaDocumentaria());\r\n qctFormaDocumentaria.setPropertyName(\"descrizione\");\r\n qctFormaDocumentaria.setValue(utenteActa.getDescFormaDocumentaria());\r\n criteria[0] = qctFormaDocumentaria;\r\n if (StringUtils.isNotEmpty(utenteActa.getDescEnte())) {\r\n qctFormaDocumentaria = new QueryConditionType();\r\n qctFormaDocumentaria.setOperator(EnumQueryOperator.EQUALS);\r\n log.debug(method + \". descEnte = \" + utenteActa.getDescEnte());\r\n qctFormaDocumentaria.setPropertyName(\"descEnte\");\r\n qctFormaDocumentaria.setValue(utenteActa.getDescEnte());\r\n criteria[1] = qctFormaDocumentaria;\r\n }\r\n NavigationConditionInfoType navigationLimits = null;\r\n PagingResponseType result = null;\r\n Integer maxItems = null;\r\n Integer skipCount = new Integer(0);\r\n Integer resultIdFormaDocumentaria = null;\r\n try {\r\n result = acarisServiceFactory.getAcarisService().getObjectServicePort().query(repositoryId, principalId, target, filter, criteria, navigationLimits, maxItems, skipCount);\r\n if (result == null) {\r\n throw new IntegrationException(\"Impossibile recuperare la forma documentaria: result is null \");\r\n }\r\n if (result != null && result.getObjectsLength() > 0) {\r\n log.debug(method + \". result.getObjectsLength() = \" + result.getObjectsLength());\r\n for (int i = 0; i < result.getObjectsLength(); i++) {\r\n log.debug(method + \". result.getObjects(i).getObjectId().getValue() = \" + result.getObjects(i).getObjectId().getValue());\r\n if (result.getObjects(i).getPropertiesLength() > 0) {\r\n it.doqui.acta.actasrv.dto.acaris.type.common.PropertyType[] propertyType = result.getObjects(i).getProperties();\r\n log.debug(method + \". propertyType.length = \" + propertyType.length);\r\n for (int j = 0; j < propertyType.length; j++) {\r\n log.debug(method + \". propertyType.getPropertyName = \" + propertyType[j].getQueryName().getPropertyName());\r\n if (\"dbKey\".equals(propertyType[j].getQueryName().getPropertyName())) {\r\n log.debug(method + \". propertyType[\" + j + \"].getValue().getContent(0) = \" + propertyType[j].getValue().getContent(0));\r\n resultIdFormaDocumentaria = Integer.parseInt(propertyType[j].getValue().getContent(0));\r\n break;\r\n }\r\n if (\"descrizione\".equals(propertyType[j].getQueryName().getPropertyName())) {\r\n log.debug(method + \". propertyType[\" + j + \"].getValue().getContent(0) = \" + propertyType[j].getValue().getContent(0));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (utenteActa.getDescFormaDocumentaria() == null) {\r\n throw new IntegrationException(\"Impossibile recuperare la forma documentaria: descrizioneFormaDocumentaria is null \");\r\n }\r\n if (log.isDebugEnabled()) {\r\n log.debug(method + \". descrizioneFormaDocumentaria = \" + utenteActa.getDescFormaDocumentaria());\r\n }\r\n } catch (AcarisException acEx) {\r\n log.error(method + \". Si e' verificato un errore in fase di recupero della forma documentaria \" + acEx.getMessage());\r\n if (acEx.getFaultInfo() != null) {\r\n log.error(method + \". acEx.getFaultInfo().getErrorCode() = \" + acEx.getFaultInfo().getErrorCode());\r\n log.error(method + \". acEx.getFaultInfo().getPropertyName() = \" + acEx.getFaultInfo().getPropertyName());\r\n log.error(method + \". acEx.getFaultInfo().getObjectId() = \" + acEx.getFaultInfo().getObjectId());\r\n log.error(method + \". acEx.getFaultInfo().getExceptionType() = \" + acEx.getFaultInfo().getExceptionType());\r\n log.error(method + \". acEx.getFaultInfo().getClassName() = \" + acEx.getFaultInfo().getClassName());\r\n log.error(method + \". acEx.getFaultInfo().getTechnicalInfo() = \" + acEx.getFaultInfo().getTechnicalInfo());\r\n }\r\n throw new IntegrationException(\"Impossibile recuperare la forma documentaria \", acEx);\r\n } catch (Exception e) {\r\n log.error(method + \". Exception = \" + e.getMessage());\r\n throw new IntegrationException(\"Impossibile recuperare la forma documentaria \", e);\r\n } finally {\r\n log.debug(method + \". END\");\r\n }\r\n return resultIdFormaDocumentaria;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List> getCDSExonRangesReverse(GeneChromosomePosition chromPos, String responseType){\r\n List exonStarts = chromPos.getExonStarts();\r\n List exonEnds = chromPos.getExonEnds();\r\n List> data = new ArrayList<>();\r\n int cdsStart = chromPos.getCdsStart();\r\n int cdsEnd = chromPos.getCdsEnd();\r\n boolean inCoding = false;\r\n int codingLength = 0;\r\n if (cdsEnd < cdsStart) {\r\n int tmp = cdsEnd;\r\n cdsEnd = cdsStart;\r\n cdsStart = tmp;\r\n }\r\n java.lang.StringBuffer s = null;\r\n boolean debug = logger.isDebugEnabled();\r\n if (debug)\r\n s = new StringBuffer();\r\n for (int i = exonStarts.size() - 1; i >= 0; i--) {\r\n int end = exonStarts.get(i);\r\n int start = exonEnds.get(i);\r\n if (end < start) {\r\n int tmp = end;\r\n end = start;\r\n start = tmp;\r\n }\r\n if (start <= cdsEnd && end >= cdsEnd) {\r\n inCoding = true;\r\n int tmpstart = start;\r\n if (start < cdsStart) {\r\n tmpstart = cdsStart;\r\n }\r\n codingLength += (cdsEnd - tmpstart);\r\n if (debug) {\r\n s.append(\" UTR :\").append(format(cdsEnd + 1)).append(\" | \").append(format(end));\r\n s.append(newline);\r\n if (tmpstart == start)\r\n s.append(\" -> \");\r\n else\r\n s.append(\" <-> \");\r\n s.append(\"Exon :\").append(format(tmpstart + 1)).append(\" - \").append(format(cdsEnd)).append(\" | \").append(cdsEnd - tmpstart).append(\" | \").append(codingLength).append(\" | \").append(codingLength % 3);\r\n s.append(newline);\r\n if (tmpstart != start)\r\n s.append(\" UTR :\").append(format(cdsStart)).append(\" - \").append(format(start + 1));\r\n s.append(newline);\r\n }\r\n Range r;\r\n if (responseType.equals(CDS))\r\n r = Range.closed(0, codingLength);\r\n else\r\n r = Range.closed(tmpstart, cdsEnd);\r\n data.add(r);\r\n } else if (start <= cdsStart && end >= cdsStart) {\r\n inCoding = false;\r\n Range r;\r\n if (responseType.equals(CDS))\r\n r = Range.closed(codingLength, codingLength + (end - cdsStart));\r\n else\r\n r = Range.closed(cdsStart + 1, end);\r\n data.add(r);\r\n codingLength += (end - cdsStart);\r\n if (debug) {\r\n s.append(\" <- Exon : \" + format(cdsStart + 1) + \" - \" + format(end) + \" | \" + (end - cdsStart) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n s.append(newline);\r\n s.append(\" UTR : \").append(format(start + 1)).append(\" - \").append(format(cdsStart));\r\n s.append(newline);\r\n }\r\n } else if (inCoding) {\r\n Range r;\r\n if (responseType.equals(CDS))\r\n r = Range.closed(codingLength, codingLength + (end - start));\r\n else\r\n r = Range.closed(start, end);\r\n data.add(r);\r\n codingLength += (end - start);\r\n if (debug) {\r\n s.append(\" Exon : \" + format(start + 1) + \" - \" + format(end) + \" | \" + (end - start) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n s.append(newline);\r\n }\r\n } else {\r\n if (debug) {\r\n s.append(\" no translation! UTR: \" + format(start) + \" - \" + format(end));\r\n s.append(newline);\r\n }\r\n }\r\n }\r\n if (debug) {\r\n s.append(\"CDS length: \").append(Integer.toString(codingLength - 3));\r\n s.append(newline);\r\n logger.debug(s.toString());\r\n }\r\n return data;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void validateMandatoryValueSetOnServiceJourneyOrAllStopPointsInJourneyPattern(Context context, XPathCompiler xpath, XdmNode subLevel, String fieldName, String checkPointKey) throws SaxonApiException, XPathExpressionException{\r\n ValidationReporter validationReporter = ValidationReporter.Factory.getInstance();\r\n validateCheckpointExists(context, checkPointKey, validationReporter);\r\n List errorNodes = new ArrayList<>();\r\n if (evaluationExpression(xpath, subLevel, \"lines/FlexibleLine and lines/FlexibleLine[not(\" + fieldName + \")]\")) {\r\n XPathSelector selector = xpath.compile(\"journeyPatterns/*[self::JourneyPattern or self::ServiceJourneyPattern][pointsInSequence/StopPointInJourneyPattern[not(BookingArrangements/\" + fieldName + \")]]\").load();\r\n selector.setContextItem(subLevel);\r\n XdmValue nodes = selector.evaluate();\r\n for (XdmValue value : nodes) {\r\n if (value instanceof XdmNode) {\r\n XdmNode node = (XdmNode) value;\r\n String id = node.getAttributeValue(QName.fromEQName(\"id\"));\r\n String version = node.getAttributeValue(QName.fromEQName(\"version\"));\r\n XPathSelector sjSelector = xpath.compile(\"//vehicleJourneys/ServiceJourney[(not(FlexibleServiceProperties) or not(FlexibleServiceProperties/\" + fieldName + \")) and JourneyPatternRef/@ref='\" + id + \"' and @version='\" + version + \"']\").load();\r\n sjSelector.setContextItem(subLevel);\r\n XdmValue errorsForJP = sjSelector.evaluate();\r\n if (errorsForJP.size() > 0) {\r\n errorNodes.add(errorsForJP);\r\n }\r\n }\r\n }\r\n }\r\n if (errorNodes.size() == 0) {\r\n validationReporter.reportSuccess(context, checkPointKey);\r\n } else {\r\n for (XdmValue errorNode : errorNodes) {\r\n for (XdmItem item : errorNode) {\r\n validationReporter.addCheckPointReportError(context, checkPointKey, DataLocationHelper.findDataLocation(context, item));\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void deserialize(ByteBuffer byteBuffer){\r\n measurements = new ArrayList<>();\r\n int size = byteBuffer.getInt();\r\n for (int i = 0; i < size; i++) {\r\n measurements.add(ReadWriteIOUtils.readString(byteBuffer));\r\n }\r\n measurementSet.addAll(measurements);\r\n dataTypes = new ArrayList<>();\r\n for (int i = 0; i < size; i++) {\r\n dataTypes.add(TSDataType.values()[byteBuffer.get()]);\r\n }\r\n encodings = new ArrayList<>();\r\n for (int i = 0; i < size; i++) {\r\n encodings.add(TSEncoding.values()[byteBuffer.get()]);\r\n }\r\n compressors = new ArrayList<>();\r\n for (int i = 0; i < size; i++) {\r\n compressors.add(CompressionType.deserialize(byteBuffer.get()));\r\n }\r\n byte label = byteBuffer.get();\r\n if (label >= 0) {\r\n aliasList = new ArrayList<>();\r\n if (label == 1) {\r\n for (int i = 0; i < size; i++) {\r\n aliasList.add(ReadWriteIOUtils.readString(byteBuffer));\r\n }\r\n }\r\n }\r\n label = byteBuffer.get();\r\n if (label >= 0) {\r\n tagsList = new ArrayList<>();\r\n if (label == 1) {\r\n for (int i = 0; i < size; i++) {\r\n tagsList.add(ReadWriteIOUtils.readMap(byteBuffer));\r\n }\r\n }\r\n }\r\n label = byteBuffer.get();\r\n if (label >= 0) {\r\n attributesList = new ArrayList<>();\r\n if (label == 1) {\r\n for (int i = 0; i < size; i++) {\r\n attributesList.add(ReadWriteIOUtils.readMap(byteBuffer));\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readConfidence(final NetworkParameters params, final Transaction tx, final Protos.TransactionConfidence confidenceProto, final TransactionConfidence confidence) throws UnreadableWalletException{\r\n if (!confidenceProto.hasType()) {\r\n log.warn(\"Unknown confidence type for tx {}\", tx.getHashAsString());\r\n return;\r\n }\r\n ConfidenceType confidenceType;\r\n switch(confidenceProto.getType()) {\r\n case BUILDING:\r\n confidenceType = ConfidenceType.BUILDING;\r\n break;\r\n case DEAD:\r\n confidenceType = ConfidenceType.DEAD;\r\n break;\r\n case NOT_IN_BEST_CHAIN:\r\n confidenceType = ConfidenceType.PENDING;\r\n break;\r\n case PENDING:\r\n confidenceType = ConfidenceType.PENDING;\r\n break;\r\n case IN_CONFLICT:\r\n confidenceType = ConfidenceType.IN_CONFLICT;\r\n break;\r\n case UNKNOWN:\r\n default:\r\n confidenceType = ConfidenceType.UNKNOWN;\r\n break;\r\n }\r\n confidence.setConfidenceType(confidenceType);\r\n if (confidenceProto.hasAppearedAtHeight()) {\r\n if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {\r\n log.warn(\"Have appearedAtHeight but not BUILDING for tx {}\", tx.getHashAsString());\r\n return;\r\n }\r\n confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight());\r\n }\r\n if (confidenceProto.hasDepth()) {\r\n if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {\r\n log.warn(\"Have depth but not BUILDING for tx {}\", tx.getHashAsString());\r\n return;\r\n }\r\n confidence.setDepthInBlocks(confidenceProto.getDepth());\r\n }\r\n if (confidenceProto.hasOverridingTransaction()) {\r\n if (confidence.getConfidenceType() != ConfidenceType.DEAD) {\r\n log.warn(\"Have overridingTransaction but not OVERRIDDEN for tx {}\", tx.getHashAsString());\r\n return;\r\n }\r\n Transaction overridingTransaction = txMap.get(confidenceProto.getOverridingTransaction());\r\n if (overridingTransaction == null) {\r\n log.warn(\"Have overridingTransaction that is not in wallet for tx {}\", tx.getHashAsString());\r\n return;\r\n }\r\n confidence.setOverridingTransaction(overridingTransaction);\r\n }\r\n for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) {\r\n InetAddress ip;\r\n try {\r\n ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray());\r\n } catch (UnknownHostException e) {\r\n throw new UnreadableWalletException(\"Peer IP address does not have the right length\", e);\r\n }\r\n int port = proto.getPort();\r\n PeerAddress address = new PeerAddress(params, ip, port);\r\n address.setServices(BigInteger.valueOf(proto.getServices()));\r\n confidence.markBroadcastBy(address);\r\n }\r\n if (confidenceProto.hasLastBroadcastedAt())\r\n confidence.setLastBroadcastedAt(new Date(confidenceProto.getLastBroadcastedAt()));\r\n switch(confidenceProto.getSource()) {\r\n case SOURCE_SELF:\r\n confidence.setSource(TransactionConfidence.Source.SELF);\r\n break;\r\n case SOURCE_NETWORK:\r\n confidence.setSource(TransactionConfidence.Source.NETWORK);\r\n break;\r\n case SOURCE_UNKNOWN:\r\n default:\r\n confidence.setSource(TransactionConfidence.Source.UNKNOWN);\r\n break;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List importAndOpenFiles(){\r\n List loaded = new ArrayList<>();\r\n List toImport = new ArrayList<>();\r\n if (!cli.isBlank() && (!cli.getLeftOver().isEmpty())) {\r\n for (String aLeftOver : cli.getLeftOver()) {\r\n boolean bibExtension = aLeftOver.toLowerCase(Locale.ENGLISH).endsWith(\"bib\");\r\n ParserResult pr = new ParserResult();\r\n if (bibExtension) {\r\n try {\r\n pr = OpenDatabase.loadDatabase(Path.of(aLeftOver), preferencesService.getImportFormatPreferences(), fileUpdateMonitor);\r\n } catch (IOException ex) {\r\n pr = ParserResult.fromError(ex);\r\n LOGGER.error(\"Error opening file '{}'\", aLeftOver, ex);\r\n }\r\n }\r\n if (!bibExtension || (pr.isEmpty())) {\r\n if (startupMode == Mode.INITIAL_START) {\r\n toImport.add(aLeftOver);\r\n } else {\r\n loaded.add(importToOpenBase(aLeftOver).orElse(new ParserResult()));\r\n }\r\n } else {\r\n loaded.add(pr);\r\n }\r\n }\r\n }\r\n if (!cli.isBlank() && cli.isFileImport()) {\r\n toImport.add(cli.getFileImport());\r\n }\r\n for (String filenameString : toImport) {\r\n importFile(filenameString).ifPresent(loaded::add);\r\n }\r\n if (!cli.isBlank() && cli.isImportToOpenBase()) {\r\n importToOpenBase(cli.getImportToOpenBase()).ifPresent(loaded::add);\r\n }\r\n if (!cli.isBlank() && cli.isBibtexImport()) {\r\n importBibtexToOpenBase(cli.getBibtexImport(), preferencesService.getImportFormatPreferences()).ifPresent(loaded::add);\r\n }\r\n return loaded;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " LocalMultiMapStats createStats(String name){\r\n LocalMultiMapStatsImpl stats = getLocalMultiMapStatsImpl(name);\r\n long ownedEntryCount = 0;\r\n long backupEntryCount = 0;\r\n long hits = 0;\r\n long lockedEntryCount = 0;\r\n long lastAccessTime = 0;\r\n long lastUpdateTime = 0;\r\n ClusterService clusterService = nodeEngine.getClusterService();\r\n MultiMapConfig config = nodeEngine.getConfig().findMultiMapConfig(name);\r\n int backupCount = config.getTotalBackupCount();\r\n Address thisAddress = clusterService.getThisAddress();\r\n for (int partitionId = 0; partitionId < nodeEngine.getPartitionService().getPartitionCount(); partitionId++) {\r\n IPartition partition = nodeEngine.getPartitionService().getPartition(partitionId, false);\r\n MultiMapPartitionContainer partitionContainer = getPartitionContainer(partitionId);\r\n MultiMapContainer multiMapContainer = partitionContainer.getMultiMapContainer(name, false);\r\n if (multiMapContainer == null) {\r\n continue;\r\n }\r\n Address owner = partition.getOwnerOrNull();\r\n if (owner != null) {\r\n if (owner.equals(thisAddress)) {\r\n lockedEntryCount += multiMapContainer.getLockedCount();\r\n lastAccessTime = max(lastAccessTime, multiMapContainer.getLastAccessTime());\r\n lastUpdateTime = max(lastUpdateTime, multiMapContainer.getLastUpdateTime());\r\n for (MultiMapValue multiMapValue : multiMapContainer.getMultiMapValues().values()) {\r\n hits += multiMapValue.getHits();\r\n ownedEntryCount += multiMapValue.getCollection(false).size();\r\n }\r\n } else {\r\n for (int j = 1; j <= backupCount; j++) {\r\n Address replicaAddress = getReplicaAddress(partition, backupCount, j);\r\n if (replicaAddress != null && replicaAddress.equals(thisAddress)) {\r\n for (MultiMapValue multiMapValue : multiMapContainer.getMultiMapValues().values()) {\r\n backupEntryCount += multiMapValue.getCollection(false).size();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n stats.setOwnedEntryCount(ownedEntryCount);\r\n stats.setBackupEntryCount(backupEntryCount);\r\n stats.setHits(hits);\r\n stats.setLockedEntryCount(lockedEntryCount);\r\n stats.setBackupCount(backupCount);\r\n stats.setLastAccessTime(lastAccessTime);\r\n stats.setLastUpdateTime(lastUpdateTime);\r\n return stats;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected List sortByHierarchy(Collection unsortedDescrs, TypeDeclarationContext tdContext, BuildResultCollector results){\r\n taxonomy = new HashMap<>();\r\n Map cache = new HashMap<>();\r\n for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {\r\n cache.put(tdescr.getType(), tdescr);\r\n }\r\n for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {\r\n QualifiedName name = tdescr.getType();\r\n Collection supers = taxonomy.get(name);\r\n if (supers == null) {\r\n supers = new ArrayList<>();\r\n taxonomy.put(name, supers);\r\n } else {\r\n results.addBuilderResult(new TypeDeclarationError(tdescr, \"Found duplicate declaration for type \" + tdescr.getType()));\r\n }\r\n boolean circular = false;\r\n for (QualifiedName sup : tdescr.getSuperTypes()) {\r\n if (!Object.class.getName().equals(name.getFullName())) {\r\n if (!hasCircularDependency(tdescr.getType(), sup, taxonomy)) {\r\n if (cache.containsKey(sup)) {\r\n supers.add(sup);\r\n }\r\n } else {\r\n circular = true;\r\n results.addBuilderResult(new TypeDeclarationError(tdescr, \"Found circular dependency for type \" + tdescr.getTypeName()));\r\n break;\r\n }\r\n }\r\n }\r\n if (circular) {\r\n tdescr.getSuperTypes().clear();\r\n }\r\n }\r\n for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {\r\n for (TypeFieldDescr field : tdescr.getFields().values()) {\r\n QualifiedName name = tdescr.getType();\r\n QualifiedName typeName = new QualifiedName(field.getPattern().getGenericType().getRawType());\r\n if (!hasCircularDependency(name, typeName, taxonomy)) {\r\n if (cache.containsKey(typeName)) {\r\n taxonomy.get(name).add(typeName);\r\n }\r\n } else {\r\n field.setRecursive(true);\r\n }\r\n }\r\n }\r\n List sorted = new HierarchySorter().sort(taxonomy);\r\n ArrayList list = new ArrayList(sorted.size());\r\n for (QualifiedName name : sorted) {\r\n list.add(cache.get(name));\r\n }\r\n return list;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void run(String[] args) throws Exception{\r\n List propertyList = new ArrayList();\r\n List specificList = new ArrayList();\r\n String inputLocation = null;\r\n String outputLocation = null;\r\n String aminoAcidCompositionLocation = null;\r\n String elementMassLocation = null;\r\n String delimiter = \",\";\r\n int decimalPlace = 4;\r\n for (int i = 0; i < args.length; i++) {\r\n if (args[i].charAt(0) != '-' || args[i].length() != 2) {\r\n showHelp();\r\n throw new Error(\"Unknown option: \" + args[i]);\r\n } else {\r\n switch(args[i].charAt(1)) {\r\n case 'i':\r\n inputLocation = args[++i];\r\n break;\r\n case 'o':\r\n outputLocation = args[++i];\r\n break;\r\n case 'f':\r\n i++;\r\n if (args[i].equalsIgnoreCase(\"csv\"))\r\n delimiter = \",\";\r\n else if (args[i].equalsIgnoreCase(\"tsv\"))\r\n delimiter = \"\\t\";\r\n else\r\n throw new Error(\"Invalid value for -f: \" + args[i] + \". Please choose either csv or tsv only.\");\r\n break;\r\n case 'x':\r\n aminoAcidCompositionLocation = args[++i];\r\n break;\r\n case 'y':\r\n elementMassLocation = args[++i];\r\n break;\r\n case 'd':\r\n decimalPlace = Integer.parseInt(args[++i]);\r\n break;\r\n case 'a':\r\n propertyList.add('1');\r\n propertyList.add('2');\r\n propertyList.add('3');\r\n propertyList.add('4');\r\n propertyList.add('5');\r\n propertyList.add('6');\r\n propertyList.add('7');\r\n propertyList.add('8');\r\n propertyList.add('9');\r\n break;\r\n case '1':\r\n propertyList.add('1');\r\n break;\r\n case '2':\r\n propertyList.add('2');\r\n break;\r\n case '3':\r\n propertyList.add('3');\r\n break;\r\n case '4':\r\n propertyList.add('4');\r\n break;\r\n case '5':\r\n propertyList.add('5');\r\n break;\r\n case '6':\r\n propertyList.add('6');\r\n break;\r\n case '7':\r\n propertyList.add('7');\r\n break;\r\n case '8':\r\n propertyList.add('8');\r\n break;\r\n case '9':\r\n propertyList.add('9');\r\n break;\r\n case '0':\r\n propertyList.add('0');\r\n i++;\r\n if (args[i].length() != 1)\r\n throw new Error(\"Invalid value: \" + args[i] + \". Amino Acid Symbol should be of single character\");\r\n specificList.add(args[i].toUpperCase().charAt(0));\r\n break;\r\n default:\r\n showHelp();\r\n throw new Error(\"Unknown option: \" + args[i]);\r\n }\r\n }\r\n }\r\n AminoAcidCompositionTable aaTable = checkForValidityAndObtainAATable(inputLocation, propertyList.size(), aminoAcidCompositionLocation, elementMassLocation);\r\n readInputAndGenerateOutput(outputLocation, propertyList, specificList, delimiter, inputLocation, aaTable, decimalPlace);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void putTarget(Annotation annotation, JsonLdResource jsonLdResource){\r\n if (isJsonObjectInput(annotation.getTarget().getInputString())) {\r\n JsonLdProperty targetProperty = addTargetProperty(annotation);\r\n if (targetProperty != null)\r\n jsonLdResource.putProperty(targetProperty);\r\n } else {\r\n if (annotation.getInternalType().equals(AnnotationTypes.OBJECT_LINKING.name())) {\r\n if (annotation.getTarget().getValue() != null) {\r\n putStringProperty(WebAnnotationFields.TARGET, annotation.getTarget().getValue(), jsonLdResource);\r\n } else if (annotation.getTarget().getValues() != null && !annotation.getTarget().getValues().isEmpty()) {\r\n putListProperty(WebAnnotationFields.TARGET, annotation.getTarget().getValues(), jsonLdResource, true);\r\n }\r\n } else {\r\n if (annotation.getTarget().getInputString() != null)\r\n jsonLdResource.putProperty(WebAnnotationFields.TARGET, annotation.getTarget().getInputString());\r\n else\r\n jsonLdResource.putProperty(WebAnnotationFields.TARGET, annotation.getTarget().getHttpUri());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String translateType(NeptuneObject v){\r\n if (v instanceof Timetable) {\r\n return \"DayType\";\r\n } else if (v instanceof Company) {\r\n Company c = (Company) v;\r\n if (OrganisationTypeEnum.Authority.equals(c.getOrganisationType())) {\r\n return \"Authority\";\r\n } else if (OrganisationTypeEnum.Operator.equals(c.getOrganisationType())) {\r\n return \"Operator\";\r\n } else {\r\n return \"GeneralOrganisation\";\r\n }\r\n } else if (v instanceof VehicleJourney) {\r\n return \"ServiceJourney\";\r\n } else if (v instanceof JourneyPattern) {\r\n return \"JourneyPattern\";\r\n } else if (v instanceof StopArea) {\r\n StopArea sa = (StopArea) v;\r\n if (ChouetteAreaEnum.BoardingPosition.equals(sa.getAreaType())) {\r\n return \"Quay\";\r\n } else if (ChouetteAreaEnum.CommercialStopPoint.equals(sa.getAreaType())) {\r\n return \"StopPlace\";\r\n }\r\n } else if (v instanceof Footnote) {\r\n return \"Notice\";\r\n } else if (v instanceof StopPoint) {\r\n return \"StopPointInJourneyPattern\";\r\n } else if (v instanceof VehicleJourneyAtStop) {\r\n return \"TimetabledPassingTime\";\r\n } else if (v instanceof Network) {\r\n return \"Network\";\r\n } else if (v instanceof RouteSection) {\r\n return \"ServiceLink\";\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private synchronized void shutdownDisruptor(boolean isReconfiguring){\r\n LOGGER.debug(\"Shutting down disruptor {}, reconfiguring: {}\", this, isReconfiguring);\r\n Disruptor currentDisruptor = disruptor.getReference();\r\n disruptor.set(null, isReconfiguring);\r\n if (currentDisruptor != null) {\r\n if (handlers != null && handlers.length == 1 && handlers[0] instanceof BlockingExchangeEventHandler) {\r\n final BlockingExchangeEventHandler blockingExchangeEventHandler = (BlockingExchangeEventHandler) handlers[0];\r\n blockingExchangeEventHandler.unblock();\r\n }\r\n currentDisruptor.shutdown();\r\n for (final LifecycleAwareExchangeEventHandler eventHandler : handlers) {\r\n boolean eventHandlerFinished = false;\r\n while (!eventHandlerFinished) {\r\n try {\r\n if (!eventHandler.awaitStopped(10, TimeUnit.SECONDS)) {\r\n LOGGER.error(\"Disruptor/event handler failed to shut down properly, PLEASE REPORT\");\r\n }\r\n eventHandlerFinished = true;\r\n } catch (InterruptedException e) {\r\n }\r\n }\r\n }\r\n handlers = new LifecycleAwareExchangeEventHandler[0];\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens){\r\n if (str == null) {\r\n return null;\r\n }\r\n final int len = str.length();\r\n if (len == 0) {\r\n return ArrayUtils.EMPTY_STRING_ARRAY;\r\n }\r\n final List list = new ArrayList<>();\r\n int sizePlus1 = 1;\r\n int i = 0;\r\n int start = 0;\r\n boolean match = false;\r\n boolean lastMatch = false;\r\n if (separatorChars == null) {\r\n while (i < len) {\r\n if (Character.isWhitespace(str.charAt(i))) {\r\n if (match || preserveAllTokens) {\r\n lastMatch = true;\r\n if (sizePlus1++ == max) {\r\n i = len;\r\n lastMatch = false;\r\n }\r\n list.add(str.substring(start, i));\r\n match = false;\r\n }\r\n start = ++i;\r\n continue;\r\n }\r\n lastMatch = false;\r\n match = true;\r\n i++;\r\n }\r\n } else if (separatorChars.length() == 1) {\r\n final char sep = separatorChars.charAt(0);\r\n while (i < len) {\r\n if (str.charAt(i) == sep) {\r\n if (match || preserveAllTokens) {\r\n lastMatch = true;\r\n if (sizePlus1++ == max) {\r\n i = len;\r\n lastMatch = false;\r\n }\r\n list.add(str.substring(start, i));\r\n match = false;\r\n }\r\n start = ++i;\r\n continue;\r\n }\r\n lastMatch = false;\r\n match = true;\r\n i++;\r\n }\r\n } else {\r\n while (i < len) {\r\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\r\n if (match || preserveAllTokens) {\r\n lastMatch = true;\r\n if (sizePlus1++ == max) {\r\n i = len;\r\n lastMatch = false;\r\n }\r\n list.add(str.substring(start, i));\r\n match = false;\r\n }\r\n start = ++i;\r\n continue;\r\n }\r\n lastMatch = false;\r\n match = true;\r\n i++;\r\n }\r\n }\r\n if (match || preserveAllTokens && lastMatch) {\r\n list.add(str.substring(start, i));\r\n }\r\n return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static R map(Range range, Handler handler){\r\n if (range.hasLowerBound() && range.hasUpperBound()) {\r\n final C lower = range.lowerEndpoint();\r\n final C upper = range.upperEndpoint();\r\n if (range.lowerBoundType() == BoundType.OPEN) {\r\n if (range.upperBoundType() == BoundType.OPEN) {\r\n return handler.open(lower, upper);\r\n } else {\r\n return handler.openClosed(lower, upper);\r\n }\r\n } else {\r\n if (range.upperBoundType() == BoundType.OPEN) {\r\n return handler.closedOpen(lower, upper);\r\n } else {\r\n if (lower.equals(upper)) {\r\n return handler.singleton(lower);\r\n } else {\r\n return handler.closed(lower, upper);\r\n }\r\n }\r\n }\r\n } else if (range.hasLowerBound()) {\r\n final C lower = range.lowerEndpoint();\r\n if (range.lowerBoundType() == BoundType.OPEN) {\r\n return handler.greaterThan(lower);\r\n } else {\r\n return handler.atLeast(lower);\r\n }\r\n } else if (range.hasUpperBound()) {\r\n final C upper = range.upperEndpoint();\r\n if (range.upperBoundType() == BoundType.OPEN) {\r\n return handler.lessThan(upper);\r\n } else {\r\n return handler.atMost(upper);\r\n }\r\n } else {\r\n return handler.all();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void initialize(Class cls){\r\n hiveJar = (new JobConf(cls)).getJar();\r\n origProp = getAllProperties();\r\n addResource(getConfVarInputStream(), \"HiveConf.java\");\r\n if (hiveSiteURL != null) {\r\n addResource(hiveSiteURL);\r\n }\r\n String msUri = this.getVar(HiveConf.ConfVars.METASTOREURIS);\r\n if (msUri == null || msUri.isEmpty()) {\r\n msUri = this.get(\"metastore.thrift.uris\");\r\n }\r\n LOG.debug(\"Found metastore URI of \" + msUri);\r\n if (HiveConfUtil.isEmbeddedMetaStore(msUri)) {\r\n setLoadMetastoreConfig(true);\r\n }\r\n if (isLoadMetastoreConfig() && hivemetastoreSiteUrl != null) {\r\n addResource(hivemetastoreSiteUrl);\r\n }\r\n if (isLoadHiveServer2Config()) {\r\n set(ConfVars.METASTORE_CLIENT_CAPABILITIES.varname, \"EXTWRITE,EXTREAD,HIVEBUCKET2,HIVEFULLACIDREAD,\" + \"HIVEFULLACIDWRITE,HIVECACHEINVALIDATE,HIVEMANAGESTATS,HIVEMANAGEDINSERTWRITE,HIVEMANAGEDINSERTREAD,\" + \"HIVESQL,HIVEMQT,HIVEONLYMQTWRITE,ACCEPTS_UNMODIFIED_METADATA\");\r\n if (hiveServer2SiteUrl != null) {\r\n addResource(hiveServer2SiteUrl);\r\n }\r\n }\r\n String val = this.getVar(HiveConf.ConfVars.HIVE_ADDITIONAL_CONFIG_FILES);\r\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\r\n if (val != null && !val.isEmpty()) {\r\n String[] configFiles = val.split(\",\");\r\n for (String config : configFiles) {\r\n URL configURL = findConfigFile(classLoader, config, true);\r\n if (configURL != null) {\r\n addResource(configURL);\r\n }\r\n }\r\n }\r\n applySystemProperties();\r\n if ((this.get(\"hive.metastore.ds.retry.attempts\") != null) || this.get(\"hive.metastore.ds.retry.interval\") != null) {\r\n LOG.warn(\"DEPRECATED: hive.metastore.ds.retry.* no longer has any effect. \" + \"Use hive.hmshandler.retry.* instead\");\r\n }\r\n if (hiveJar == null) {\r\n hiveJar = this.get(ConfVars.HIVEJAR.varname);\r\n }\r\n if (auxJars == null) {\r\n auxJars = StringUtils.join(FileUtils.getJarFilesByPath(this.get(ConfVars.HIVEAUXJARS.varname), this), ',');\r\n }\r\n if (getBoolVar(ConfVars.METASTORE_SCHEMA_VERIFICATION)) {\r\n setBoolVar(ConfVars.METASTORE_AUTO_CREATE_ALL, false);\r\n }\r\n if (getBoolVar(HiveConf.ConfVars.HIVECONFVALIDATION)) {\r\n List trimmed = new ArrayList();\r\n for (Map.Entry entry : this) {\r\n String key = entry.getKey();\r\n if (key == null || !key.startsWith(\"hive.\")) {\r\n continue;\r\n }\r\n ConfVars var = HiveConf.getConfVars(key);\r\n if (var == null) {\r\n var = HiveConf.getConfVars(key.trim());\r\n if (var != null) {\r\n trimmed.add(key);\r\n }\r\n }\r\n if (var == null) {\r\n LOG.warn(\"HiveConf of name {} does not exist\", key);\r\n } else if (!var.isType(entry.getValue())) {\r\n LOG.warn(\"HiveConf {} expects {} type value\", var.varname, var.typeString());\r\n }\r\n }\r\n for (String key : trimmed) {\r\n set(key.trim(), getRaw(key));\r\n unset(key);\r\n }\r\n }\r\n setupSQLStdAuthWhiteList();\r\n setupRestrictList();\r\n hiddenSet.clear();\r\n hiddenSet.addAll(HiveConfUtil.getHiddenSet(this));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SCIMUser toSCIMUser(final UserTO userTO, final String location, final List attributes, final List excludedAttributes){\r\n SCIMConf conf = confManager.get();\r\n List schemas = new ArrayList<>();\r\n schemas.add(Resource.User.schema());\r\n if (conf.getEnterpriseUserConf() != null) {\r\n schemas.add(Resource.EnterpriseUser.schema());\r\n }\r\n SCIMUser user = new SCIMUser(userTO.getKey(), schemas, new Meta(Resource.User, userTO.getCreationDate(), Optional.ofNullable(userTO.getLastChangeDate()).orElse(userTO.getCreationDate()), userTO.getETagValue(), location), output(attributes, excludedAttributes, \"userName\", userTO.getUsername()), !userTO.isSuspended());\r\n Map attrs = new HashMap<>();\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getPlainAttrs()));\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getDerAttrs()));\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getVirAttrs()));\r\n attrs.put(\"username\", new Attr.Builder(\"username\").value(userTO.getUsername()).build());\r\n if (conf.getUserConf() != null) {\r\n if (output(attributes, excludedAttributes, \"externalId\") && conf.getUserConf().getExternalId() != null && attrs.containsKey(conf.getUserConf().getExternalId())) {\r\n user.setExternalId(attrs.get(conf.getUserConf().getExternalId()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"name\") && conf.getUserConf().getName() != null) {\r\n SCIMUserName name = new SCIMUserName();\r\n if (conf.getUserConf().getName().getFamilyName() != null && attrs.containsKey(conf.getUserConf().getName().getFamilyName())) {\r\n name.setFamilyName(attrs.get(conf.getUserConf().getName().getFamilyName()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getFormatted() != null && attrs.containsKey(conf.getUserConf().getName().getFormatted())) {\r\n name.setFormatted(attrs.get(conf.getUserConf().getName().getFormatted()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getGivenName() != null && attrs.containsKey(conf.getUserConf().getName().getGivenName())) {\r\n name.setGivenName(attrs.get(conf.getUserConf().getName().getGivenName()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getHonorificPrefix() != null && attrs.containsKey(conf.getUserConf().getName().getHonorificPrefix())) {\r\n name.setHonorificPrefix(attrs.get(conf.getUserConf().getName().getHonorificPrefix()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getHonorificSuffix() != null && attrs.containsKey(conf.getUserConf().getName().getHonorificSuffix())) {\r\n name.setHonorificSuffix(attrs.get(conf.getUserConf().getName().getHonorificSuffix()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getMiddleName() != null && attrs.containsKey(conf.getUserConf().getName().getMiddleName())) {\r\n name.setMiddleName(attrs.get(conf.getUserConf().getName().getMiddleName()).getValues().get(0));\r\n }\r\n if (!name.isEmpty()) {\r\n user.setName(name);\r\n }\r\n }\r\n if (output(attributes, excludedAttributes, \"displayName\") && conf.getUserConf().getDisplayName() != null && attrs.containsKey(conf.getUserConf().getDisplayName())) {\r\n user.setDisplayName(attrs.get(conf.getUserConf().getDisplayName()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"nickName\") && conf.getUserConf().getNickName() != null && attrs.containsKey(conf.getUserConf().getNickName())) {\r\n user.setNickName(attrs.get(conf.getUserConf().getNickName()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"profileUrl\") && conf.getUserConf().getProfileUrl() != null && attrs.containsKey(conf.getUserConf().getProfileUrl())) {\r\n user.setProfileUrl(attrs.get(conf.getUserConf().getProfileUrl()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"title\") && conf.getUserConf().getTitle() != null && attrs.containsKey(conf.getUserConf().getTitle())) {\r\n user.setTitle(attrs.get(conf.getUserConf().getTitle()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"userType\") && conf.getUserConf().getUserType() != null && attrs.containsKey(conf.getUserConf().getUserType())) {\r\n user.setUserType(attrs.get(conf.getUserConf().getUserType()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"preferredLanguage\") && conf.getUserConf().getPreferredLanguage() != null && attrs.containsKey(conf.getUserConf().getPreferredLanguage())) {\r\n user.setPreferredLanguage(attrs.get(conf.getUserConf().getPreferredLanguage()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"locale\") && conf.getUserConf().getLocale() != null && attrs.containsKey(conf.getUserConf().getLocale())) {\r\n user.setLocale(attrs.get(conf.getUserConf().getLocale()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"timezone\") && conf.getUserConf().getTimezone() != null && attrs.containsKey(conf.getUserConf().getTimezone())) {\r\n user.setTimezone(attrs.get(conf.getUserConf().getTimezone()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"emails\")) {\r\n fill(attrs, conf.getUserConf().getEmails(), user.getEmails());\r\n }\r\n if (output(attributes, excludedAttributes, \"phoneNumbers\")) {\r\n fill(attrs, conf.getUserConf().getPhoneNumbers(), user.getPhoneNumbers());\r\n }\r\n if (output(attributes, excludedAttributes, \"ims\")) {\r\n fill(attrs, conf.getUserConf().getIms(), user.getIms());\r\n }\r\n if (output(attributes, excludedAttributes, \"photos\")) {\r\n fill(attrs, conf.getUserConf().getPhotos(), user.getPhotos());\r\n }\r\n if (output(attributes, excludedAttributes, \"addresses\")) {\r\n conf.getUserConf().getAddresses().forEach(addressConf -> {\r\n SCIMUserAddress address = new SCIMUserAddress();\r\n if (addressConf.getFormatted() != null && attrs.containsKey(addressConf.getFormatted())) {\r\n address.setFormatted(attrs.get(addressConf.getFormatted()).getValues().get(0));\r\n }\r\n if (addressConf.getStreetAddress() != null && attrs.containsKey(addressConf.getStreetAddress())) {\r\n address.setStreetAddress(attrs.get(addressConf.getStreetAddress()).getValues().get(0));\r\n }\r\n if (addressConf.getLocality() != null && attrs.containsKey(addressConf.getLocality())) {\r\n address.setLocality(attrs.get(addressConf.getLocality()).getValues().get(0));\r\n }\r\n if (addressConf.getRegion() != null && attrs.containsKey(addressConf.getRegion())) {\r\n address.setRegion(attrs.get(addressConf.getRegion()).getValues().get(0));\r\n }\r\n if (addressConf.getCountry() != null && attrs.containsKey(addressConf.getCountry())) {\r\n address.setCountry(attrs.get(addressConf.getCountry()).getValues().get(0));\r\n }\r\n if (addressConf.getType() != null) {\r\n address.setType(addressConf.getType().name());\r\n }\r\n if (addressConf.isPrimary()) {\r\n address.setPrimary(true);\r\n }\r\n if (!address.isEmpty()) {\r\n user.getAddresses().add(address);\r\n }\r\n });\r\n }\r\n if (output(attributes, excludedAttributes, \"x509Certificates\")) {\r\n conf.getUserConf().getX509Certificates().stream().filter(attrs::containsKey).forEach(cert -> user.getX509Certificates().add(new Value(attrs.get(cert).getValues().get(0))));\r\n }\r\n }\r\n if (conf.getEnterpriseUserConf() != null) {\r\n SCIMEnterpriseInfo enterpriseInfo = new SCIMEnterpriseInfo();\r\n if (output(attributes, excludedAttributes, \"employeeNumber\") && conf.getEnterpriseUserConf().getEmployeeNumber() != null && attrs.containsKey(conf.getEnterpriseUserConf().getEmployeeNumber())) {\r\n enterpriseInfo.setEmployeeNumber(attrs.get(conf.getEnterpriseUserConf().getEmployeeNumber()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"costCenter\") && conf.getEnterpriseUserConf().getCostCenter() != null && attrs.containsKey(conf.getEnterpriseUserConf().getCostCenter())) {\r\n enterpriseInfo.setCostCenter(attrs.get(conf.getEnterpriseUserConf().getCostCenter()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"organization\") && conf.getEnterpriseUserConf().getOrganization() != null && attrs.containsKey(conf.getEnterpriseUserConf().getOrganization())) {\r\n enterpriseInfo.setOrganization(attrs.get(conf.getEnterpriseUserConf().getOrganization()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"division\") && conf.getEnterpriseUserConf().getDivision() != null && attrs.containsKey(conf.getEnterpriseUserConf().getDivision())) {\r\n enterpriseInfo.setDivision(attrs.get(conf.getEnterpriseUserConf().getDivision()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"department\") && conf.getEnterpriseUserConf().getDepartment() != null && attrs.containsKey(conf.getEnterpriseUserConf().getDepartment())) {\r\n enterpriseInfo.setDepartment(attrs.get(conf.getEnterpriseUserConf().getDepartment()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"manager\") && conf.getEnterpriseUserConf().getManager() != null) {\r\n SCIMUserManager manager = new SCIMUserManager();\r\n if (conf.getEnterpriseUserConf().getManager().getKey() != null && attrs.containsKey(conf.getEnterpriseUserConf().getManager().getKey())) {\r\n try {\r\n UserTO userManager = userLogic.read(attrs.get(conf.getEnterpriseUserConf().getManager().getKey()).getValues().get(0));\r\n manager.setValue(userManager.getKey());\r\n manager.setRef(StringUtils.substringBefore(location, \"/Users\") + \"/Users/\" + userManager.getKey());\r\n if (conf.getEnterpriseUserConf().getManager().getDisplayName() != null) {\r\n Attr displayName = userManager.getPlainAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n if (displayName == null) {\r\n displayName = userManager.getDerAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n }\r\n if (displayName == null) {\r\n displayName = userManager.getVirAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n }\r\n if (displayName != null) {\r\n manager.setDisplayName(displayName.getValues().get(0));\r\n }\r\n }\r\n } catch (Exception e) {\r\n LOG.error(\"Could not read user {}\", conf.getEnterpriseUserConf().getManager().getKey(), e);\r\n }\r\n }\r\n if (!manager.isEmpty()) {\r\n enterpriseInfo.setManager(manager);\r\n }\r\n }\r\n if (!enterpriseInfo.isEmpty()) {\r\n user.setEnterpriseInfo(enterpriseInfo);\r\n }\r\n }\r\n if (output(attributes, excludedAttributes, \"groups\")) {\r\n userTO.getMemberships().forEach(membership -> user.getGroups().add(new Group(membership.getGroupKey(), StringUtils.substringBefore(location, \"/Users\") + \"/Groups/\" + membership.getGroupKey(), membership.getGroupName(), Function.direct)));\r\n userTO.getDynMemberships().forEach(membership -> user.getGroups().add(new Group(membership.getGroupKey(), StringUtils.substringBefore(location, \"/Users\") + \"/Groups/\" + membership.getGroupKey(), membership.getGroupName(), Function.indirect)));\r\n }\r\n if (output(attributes, excludedAttributes, \"entitlements\")) {\r\n authDataAccessor.getAuthorities(userTO.getUsername(), null).forEach(authority -> user.getEntitlements().add(new Value(authority.getAuthority() + \" on Realm(s) \" + authority.getRealms())));\r\n }\r\n if (output(attributes, excludedAttributes, \"roles\")) {\r\n userTO.getRoles().forEach(role -> user.getRoles().add(new Value(role)));\r\n }\r\n return user;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processConstraintsAndBinds(RuleBuildContext context, PatternDescr patternDescr, Declaration xpathStartDeclaration, Pattern pattern){\r\n DumperContext mvelCtx = new DumperContext().setRuleContext(context);\r\n for (BaseDescr b : patternDescr.getDescrs()) {\r\n String expression;\r\n boolean isPositional = false;\r\n if (b instanceof BindingDescr) {\r\n BindingDescr bind = (BindingDescr) b;\r\n expression = bind.getVariable() + (bind.isUnification() ? \" := \" : \" : \") + bind.getExpression();\r\n } else if (b instanceof ExprConstraintDescr) {\r\n ExprConstraintDescr descr = (ExprConstraintDescr) b;\r\n expression = descr.getExpression();\r\n isPositional = descr.getType() == ExprConstraintDescr.Type.POSITIONAL;\r\n } else {\r\n expression = b.getText();\r\n }\r\n ConstraintConnectiveDescr result = parseExpression(context, patternDescr, b, expression);\r\n if (result == null) {\r\n return;\r\n }\r\n result.setNegated(b.isNegated());\r\n isPositional &= !(result.getDescrs().size() == 1 && result.getDescrs().get(0) instanceof BindingDescr);\r\n if (isPositional) {\r\n processPositional(context, patternDescr, xpathStartDeclaration, pattern, (ExprConstraintDescr) b);\r\n } else {\r\n List constraints = build(context, patternDescr, xpathStartDeclaration, pattern, result, mvelCtx);\r\n pattern.addConstraints(constraints);\r\n }\r\n }\r\n TypeDeclaration typeDeclaration = getTypeDeclaration(pattern, context);\r\n if (typeDeclaration != null && typeDeclaration.isPropertyReactive()) {\r\n for (String field : lookAheadFieldsOfIdentifier(context.getRuleDescr(), patternDescr)) {\r\n addFieldToPatternWatchlist(pattern, typeDeclaration, field);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void updateHeader(final AjaxRequestTarget target, final Serializable modelObject){\r\n final String header;\r\n if (modelObject == null) {\r\n header = new ResourceModel(\"actions\", StringUtils.EMPTY).getObject();\r\n } else if (modelObject instanceof UserTO) {\r\n header = ((UserTO) modelObject).getUsername();\r\n } else if (modelObject instanceof UserWrapper) {\r\n header = ((UserWrapper) modelObject).getInnerObject().getUsername();\r\n } else if (modelObject instanceof GroupTO) {\r\n header = ((GroupTO) modelObject).getName();\r\n } else if (modelObject instanceof GroupWrapper) {\r\n header = ((GroupWrapper) modelObject).getInnerObject().getName();\r\n } else if (modelObject instanceof AnyObjectTO) {\r\n header = ((AnyObjectTO) modelObject).getName();\r\n } else if (modelObject instanceof AnyWrapper && AnyWrapper.class.cast(modelObject).getInnerObject() instanceof AnyObjectTO) {\r\n header = ((AnyObjectTO) ((AnyWrapper) modelObject).getInnerObject()).getName();\r\n } else if (modelObject instanceof Attr) {\r\n header = ((Attr) modelObject).getSchema();\r\n } else if (modelObject instanceof ConfParam) {\r\n header = ((ConfParam) modelObject).getSchema();\r\n } else if (modelObject instanceof PolicyTO) {\r\n header = ((PolicyTO) modelObject).getName();\r\n } else if (modelObject instanceof SecurityQuestionTO) {\r\n header = ((SecurityQuestionTO) modelObject).getContent();\r\n } else if (modelObject instanceof AccessTokenTO) {\r\n header = ((AccessTokenTO) modelObject).getOwner();\r\n } else if (modelObject instanceof ExecTO) {\r\n header = ((ExecTO) modelObject).getKey();\r\n } else if (modelObject instanceof StatusBean) {\r\n header = ((StatusBean) modelObject).getResource();\r\n } else if (modelObject instanceof PolicyRuleWrapper) {\r\n header = ((PolicyRuleWrapper) modelObject).getImplementationKey();\r\n } else if (modelObject instanceof ReportletWrapper) {\r\n header = ((ReportletWrapper) modelObject).getImplementationKey();\r\n } else if (modelObject instanceof JobTO) {\r\n header = ((JobTO) modelObject).getRefKey() == null ? ((JobTO) modelObject).getRefDesc() : ((JobTO) modelObject).getRefKey();\r\n } else if (modelObject instanceof ToggleableTarget) {\r\n header = ((ToggleableTarget) modelObject).getAnyType();\r\n } else if (modelObject instanceof Domain) {\r\n header = ((Domain) modelObject).getKey();\r\n } else if (modelObject instanceof NamedEntityTO) {\r\n header = ((NamedEntityTO) modelObject).getName();\r\n } else if (modelObject instanceof EntityTO) {\r\n header = ((EntityTO) modelObject).getKey();\r\n } else {\r\n header = new ResourceModel(\"actions\", StringUtils.EMPTY).getObject();\r\n }\r\n setHeader(target, StringUtils.abbreviate(header, HEADER_FIRST_ABBREVIATION));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Iterable> createCacheEntryEvent(Collection keys){\r\n HashSet> evt = new HashSet>();\r\n for (CacheEventData cacheEventData : keys) {\r\n EventType eventType = CacheEventType.convertToEventType(cacheEventData.getCacheEventType());\r\n K key = toObject(cacheEventData.getDataKey());\r\n boolean hasNewValue = !(eventType == EventType.REMOVED || eventType == EventType.EXPIRED);\r\n final V newValue;\r\n final V oldValue;\r\n if (isOldValueRequired) {\r\n if (hasNewValue) {\r\n newValue = toObject(cacheEventData.getDataValue());\r\n oldValue = toObject(cacheEventData.getDataOldValue());\r\n } else {\r\n oldValue = toObject(cacheEventData.getDataValue());\r\n newValue = oldValue;\r\n }\r\n } else {\r\n if (hasNewValue) {\r\n newValue = toObject(cacheEventData.getDataValue());\r\n oldValue = null;\r\n } else {\r\n newValue = null;\r\n oldValue = null;\r\n }\r\n }\r\n final CacheEntryEventImpl event = new CacheEntryEventImpl(source, eventType, key, newValue, oldValue);\r\n if (filter == null || filter.evaluate(event)) {\r\n evt.add(event);\r\n }\r\n }\r\n return evt;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " TGetOperationStatusResp waitForOperationToComplete() throws SQLException{\r\n TGetOperationStatusResp statusResp = null;\r\n final TGetOperationStatusReq statusReq = new TGetOperationStatusReq(stmtHandle.get());\r\n statusReq.setGetProgressUpdate(inPlaceUpdateStream.isPresent());\r\n if (inPlaceUpdateStream.isPresent()) {\r\n inPlaceUpdateStream.get().getEventNotifier().progressBarCompleted();\r\n }\r\n LOG.debug(\"Waiting on operation to complete: Polling operation status\");\r\n do {\r\n try {\r\n if (Thread.currentThread().isInterrupted()) {\r\n throw new SQLException(CLIENT_POLLING_OPSTATUS_INTERRUPTED.getMsg(), CLIENT_POLLING_OPSTATUS_INTERRUPTED.getSQLState());\r\n }\r\n statusResp = client.GetOperationStatus(statusReq);\r\n LOG.debug(\"Status response: {}\", statusResp);\r\n if (!isOperationComplete && inPlaceUpdateStream.isPresent()) {\r\n inPlaceUpdateStream.get().update(statusResp.getProgressUpdateResponse());\r\n }\r\n Utils.verifySuccessWithInfo(statusResp.getStatus());\r\n if (statusResp.isSetOperationState()) {\r\n switch(statusResp.getOperationState()) {\r\n case CLOSED_STATE:\r\n case FINISHED_STATE:\r\n isOperationComplete = true;\r\n isLogBeingGenerated = false;\r\n break;\r\n case CANCELED_STATE:\r\n final String errMsg = statusResp.getErrorMessage();\r\n final String fullErrMsg = (errMsg == null || errMsg.isEmpty()) ? QUERY_CANCELLED_MESSAGE : QUERY_CANCELLED_MESSAGE + \" \" + errMsg;\r\n throw new SQLException(fullErrMsg, \"01000\");\r\n case TIMEDOUT_STATE:\r\n throw new SQLTimeoutException(\"Query timed out after \" + queryTimeout + \" seconds\");\r\n case ERROR_STATE:\r\n throw new SQLException(statusResp.getErrorMessage(), statusResp.getSqlState(), statusResp.getErrorCode());\r\n case UKNOWN_STATE:\r\n throw new SQLException(\"Unknown query\", \"HY000\");\r\n case INITIALIZED_STATE:\r\n case PENDING_STATE:\r\n case RUNNING_STATE:\r\n break;\r\n }\r\n }\r\n } catch (SQLException e) {\r\n isLogBeingGenerated = false;\r\n throw e;\r\n } catch (Exception e) {\r\n isLogBeingGenerated = false;\r\n throw new SQLException(\"Failed to wait for operation to complete\", \"08S01\", e);\r\n }\r\n } while (!isOperationComplete);\r\n if (inPlaceUpdateStream.isPresent()) {\r\n inPlaceUpdateStream.get().getEventNotifier().progressBarCompleted();\r\n }\r\n return statusResp;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public TypeDeclarationDescr typeDeclaration(DeclareDescrBuilder ddb, boolean isTrait) throws RecognitionException{\r\n TypeDeclarationDescrBuilder declare = null;\r\n try {\r\n declare = helper.start(ddb, TypeDeclarationDescrBuilder.class, null);\r\n declare.setTrait(isTrait);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.TYPE)) {\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.TYPE, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n }\r\n String type = qualifiedIdentifier();\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0)\r\n declare.name(type);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS)) {\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.EXTENDS, null, DroolsEditorType.KEYWORD);\r\n if (!state.failed) {\r\n String superType = qualifiedIdentifier();\r\n declare.superType(superType);\r\n while (input.LA(1) == DRL5Lexer.COMMA) {\r\n match(input, DRL5Lexer.COMMA, null, null, DroolsEditorType.SYMBOL);\r\n superType = qualifiedIdentifier();\r\n declare.superType(superType);\r\n }\r\n }\r\n }\r\n while (input.LA(1) == DRL5Lexer.AT) {\r\n annotation(declare);\r\n if (state.failed)\r\n return null;\r\n }\r\n while (input.LA(1) == DRL5Lexer.ID && !helper.validateIdentifierKey(DroolsSoftKeywords.END)) {\r\n field(declare);\r\n if (state.failed)\r\n return null;\r\n }\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.END, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n } finally {\r\n helper.end(TypeDeclarationDescrBuilder.class, declare);\r\n }\r\n return (declare != null) ? declare.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean requiresDecimalExpansion(RexNode expr, boolean recurse){\r\n if (!(expr instanceof RexCall)) {\r\n return false;\r\n }\r\n RexCall call = (RexCall) expr;\r\n boolean localCheck = true;\r\n switch(call.getKind()) {\r\n case REINTERPRET:\r\n case IS_NULL:\r\n localCheck = false;\r\n break;\r\n case CAST:\r\n RelDataType lhsType = call.getType();\r\n RelDataType rhsType = call.operands.get(0).getType();\r\n if (rhsType.getSqlTypeName() == SqlTypeName.NULL) {\r\n return false;\r\n }\r\n if (SqlTypeUtil.inCharFamily(lhsType) || SqlTypeUtil.inCharFamily(rhsType)) {\r\n localCheck = false;\r\n } else if (SqlTypeUtil.isDecimal(lhsType) && (lhsType != rhsType)) {\r\n return true;\r\n }\r\n break;\r\n default:\r\n localCheck = call.getOperator().requiresDecimalExpansion();\r\n }\r\n if (localCheck) {\r\n if (SqlTypeUtil.isDecimal(call.getType())) {\r\n return true;\r\n }\r\n for (int i = 0; i < call.operands.size(); i++) {\r\n if (SqlTypeUtil.isDecimal(call.operands.get(i).getType())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return recurse && requiresDecimalExpansion(call.operands, true);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Result update(final SyncDelta delta, final List realms, final boolean inLink) throws JobExecutionException{\r\n if (!profile.getTask().isPerformUpdate()) {\r\n LOG.debug(\"PullTask not configured for update\");\r\n end(MatchingRule.toEventName(MatchingRule.UPDATE), Result.SUCCESS, null, null, delta);\r\n return Result.SUCCESS;\r\n }\r\n LOG.debug(\"About to update {}\", realms);\r\n Result global = Result.SUCCESS;\r\n for (Realm realm : realms) {\r\n LOG.debug(\"About to update {}\", realm);\r\n ProvisioningReport result = new ProvisioningReport();\r\n result.setOperation(ResourceOperation.UPDATE);\r\n result.setAnyType(SyncopeConstants.REALM_ANYTYPE);\r\n result.setStatus(ProvisioningReport.Status.SUCCESS);\r\n result.setKey(realm.getKey());\r\n result.setName(realm.getFullPath());\r\n if (!profile.isDryRun()) {\r\n Result resultStatus;\r\n Object output;\r\n RealmTO before = binder.getRealmTO(realm, true);\r\n try {\r\n if (!inLink) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeUpdate(profile, delta, before, null);\r\n }\r\n }\r\n Map, Set> beforeAttrs = propagationManager.prepareAttrs(realm);\r\n PropagationByResource propByRes = binder.update(realm, before);\r\n realm = realmDAO.save(realm);\r\n RealmTO updated = binder.getRealmTO(realm, true);\r\n List taskInfos = propagationManager.setAttributeDeltas(propagationManager.createTasks(realm, propByRes, null), beforeAttrs, null);\r\n taskExecutor.execute(taskInfos, false, securityProperties.getAdminUser());\r\n for (PullActions action : profile.getActions()) {\r\n action.after(profile, delta, updated, result);\r\n }\r\n output = updated;\r\n resultStatus = Result.SUCCESS;\r\n result.setName(updated.getFullPath());\r\n LOG.debug(\"{} successfully updated\", updated);\r\n } catch (PropagationException e) {\r\n LOG.error(\"Could not propagate Realm {}\", delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not update Realm {}\", delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n }\r\n end(MatchingRule.toEventName(MatchingRule.UPDATE), resultStatus, before, output, delta);\r\n global = and(global, resultStatus);\r\n }\r\n profile.getResults().add(result);\r\n }\r\n return global;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void walkXmlTree(Node xmlNode, RestServiceDetails detail){\r\n if (\"rest\".equals(xmlNode.getNodeName())) {\r\n String lineNumber = (String) xmlNode.getUserData(XmlLineNumberParser.LINE_NUMBER);\r\n String lineNumberEnd = (String) xmlNode.getUserData(XmlLineNumberParser.LINE_NUMBER_END);\r\n detail.setLineNumber(lineNumber);\r\n detail.setLineNumberEnd(lineNumberEnd);\r\n extractAttributes(xmlNode, detail);\r\n }\r\n if (isParentRest(xmlNode)) {\r\n if (\"delete\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"delete\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n } else if (\"get\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"get\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n } else if (\"head\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"head\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n } else if (\"patch\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"patch\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n } else if (\"post\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"post\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n } else if (\"put\".equals(xmlNode.getNodeName())) {\r\n RestVerbDetails verb = new RestVerbDetails();\r\n verb.setMethod(\"put\");\r\n detail.addVerb(verb);\r\n extractAttributes(xmlNode, verb);\r\n }\r\n if (\"description\".equals(xmlNode.getNodeName())) {\r\n String value = xmlNode.getTextContent();\r\n RestVerbDetails verb = getLastVerb(detail);\r\n if (verb != null) {\r\n verb.setDescription(value);\r\n } else {\r\n detail.setDescription(value);\r\n }\r\n } else if (\"to\".equals(xmlNode.getNodeName())) {\r\n NamedNodeMap map = xmlNode.getAttributes();\r\n String uri = extractAttribute(map, \"uri\");\r\n RestVerbDetails verb = getLastVerb(detail);\r\n if (verb != null) {\r\n verb.setTo(uri);\r\n }\r\n }\r\n }\r\n NodeList children = xmlNode.getChildNodes();\r\n for (int i = 0; i < children.getLength(); i++) {\r\n Node child = children.item(i);\r\n if (child.getNodeType() == Node.ELEMENT_NODE) {\r\n walkXmlTree(child, detail);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void tryRemoveClassloadersForJob(long jobId, JobPhase phase){\r\n logFinest(logger, \"Try remove classloaders for jobId=%s, phase=%s\", idToString(jobId), phase);\r\n classLoaders.compute(jobId, (k, jobClassLoaders) -> {\r\n if (jobClassLoaders == null) {\r\n logger.warning(\"JobClassLoaders for jobId=\" + idToString(jobId) + \" already removed\");\r\n return null;\r\n }\r\n int phaseCount = jobClassLoaders.removePhase(phase);\r\n if (phaseCount == 0) {\r\n logFinest(logger, \"JobClassLoaders phaseCount = 0, removing classloaders for jobId=%s\", idToString(jobId));\r\n Map processorCls = jobClassLoaders.processorCls();\r\n if (processorCls != null) {\r\n for (ClassLoader cl : processorCls.values()) {\r\n try {\r\n ((ChildFirstClassLoader) cl).close();\r\n } catch (IOException e) {\r\n logger.warning(\"Exception when closing processor classloader\", e);\r\n }\r\n }\r\n }\r\n JetDelegatingClassLoader jobClassLoader = jobClassLoaders.jobClassLoader();\r\n jobClassLoader.shutdown();\r\n logFine(logger, \"Finish JobClassLoaders phaseCount = 0,\" + \" removing classloaders for jobId=%s\", idToString(jobId));\r\n return null;\r\n } else {\r\n logFinest(logger, \"JobClassLoaders refCount > 0, NOT removing classloaders for jobId=%s\", idToString(jobId));\r\n return jobClassLoaders;\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void writeGeneratedSources(List sources, Path srcPath, Path implPath, CmdConstants.GenType type) throws IOException{\r\n List listFiles = new ArrayList<>();\r\n if (Files.exists(srcPath)) {\r\n File[] files = new File(String.valueOf(srcPath)).listFiles();\r\n if (files != null) {\r\n listFiles.addAll(Arrays.asList(files));\r\n for (File file : files) {\r\n if (file.isDirectory() && file.getName().equals(\"tests\")) {\r\n File[] innerFiles = new File(srcPath + \"/tests\").listFiles();\r\n if (innerFiles != null) {\r\n listFiles.addAll(Arrays.asList(innerFiles));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n for (File file : listFiles) {\r\n for (GenSrcFile gFile : sources) {\r\n if (file.getName().equals(gFile.getFileName())) {\r\n if (System.console() != null) {\r\n String userInput = System.console().readLine(\"There is already a/an \" + file.getName() + \" in the location. Do you want to override the file? [y/N] \");\r\n if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), \"y\")) {\r\n int duplicateCount = 0;\r\n setGeneratedFileName(listFiles, gFile, duplicateCount);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n for (GenSrcFile file : sources) {\r\n Path filePath;\r\n if (!file.getType().isOverwritable()) {\r\n filePath = implPath.resolve(file.getFileName());\r\n if (Files.notExists(filePath)) {\r\n String fileContent = file.getContent();\r\n CodegenUtils.writeFile(filePath, fileContent);\r\n }\r\n } else {\r\n boolean isDuplicatedFileInTests = file.getFileName().matches(\"test.+[0-9]+.bal\") || file.getFileName().matches(\"Config.+[0-9]+.toml\");\r\n if (file.getFileName().equals(TEST_FILE_NAME) || file.getFileName().equals(CONFIG_FILE_NAME) || isDuplicatedFileInTests) {\r\n Files.createDirectories(Paths.get(srcPath + OAS_PATH_SEPARATOR + TEST_DIR));\r\n filePath = Paths.get(srcPath.resolve(TEST_DIR + OAS_PATH_SEPARATOR + file.getFileName()).toFile().getCanonicalPath());\r\n } else {\r\n filePath = Paths.get(srcPath.resolve(file.getFileName()).toFile().getCanonicalPath());\r\n }\r\n String fileContent = file.getContent();\r\n CodegenUtils.writeFile(filePath, fileContent);\r\n }\r\n }\r\n if (type.equals(GEN_SERVICE)) {\r\n outStream.println(\"Service generated successfully and the OpenAPI contract is copied to path \" + srcPath + \".\");\r\n } else if (type.equals(GEN_CLIENT)) {\r\n outStream.println(\"Client generated successfully.\");\r\n }\r\n outStream.println(\"Following files were created.\");\r\n Iterator iterator = sources.iterator();\r\n while (iterator.hasNext()) {\r\n outStream.println(\"-- \" + iterator.next().getFileName());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ChromPos getChromPosForward(int cdsPos, List exonStarts, List exonEnds, int cdsStart, int cdsEnd){\r\n boolean inCoding = false;\r\n int codingLength = 0;\r\n @SuppressWarnings(\"unused\")\r\n int lengthExons = 0;\r\n for (int i = 0; i < exonStarts.size(); i++) {\r\n int start = exonStarts.get(i);\r\n int end = exonEnds.get(i);\r\n lengthExons += end - start;\r\n if (start <= cdsStart + 1 && end >= cdsStart + 1) {\r\n if (codingLength + (end - cdsStart - 1) >= cdsPos) {\r\n int tmp = cdsPos - codingLength;\r\n logger.debug(cdsStart + \" | \" + codingLength + \" | \" + tmp);\r\n logger.debug(\" -> found position in UTR exon: #\" + (i + 1) + \" cdsPos:\" + cdsPos + \" return:\" + (cdsStart + 1 + tmp) + \" start:\" + format(start + 1) + \" \" + format(tmp) + \" \" + cdsStart + \" \" + codingLength);\r\n return new ChromPos((cdsStart + 1 + tmp), -1);\r\n }\r\n inCoding = true;\r\n codingLength += (end - cdsStart);\r\n logger.debug(\" UTR : \" + format(start + 1) + \" - \" + (cdsStart));\r\n logger.debug(\" -> Exon : \" + format(cdsStart + 1) + \" - \" + format(end) + \" | \" + format(end - cdsStart) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n } else if (start + 1 <= cdsEnd && end >= cdsEnd) {\r\n inCoding = false;\r\n if (codingLength + (cdsEnd - start - 1) >= cdsPos) {\r\n int tmp = cdsPos - codingLength;\r\n logger.debug(\" <- Exon : \" + format(start + 1) + \" - \" + format(cdsEnd) + \" | \" + format(cdsEnd - start) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n logger.debug(\" UTR : \" + format(cdsEnd + 1) + \" - \" + format(end));\r\n logger.debug(codingLength + \" | \" + tmp + \" | \" + format(start + 1));\r\n logger.debug(\" -> chromPosForward found position in non coding exon: \" + cdsPos + \" \" + format(start + 1) + \" \" + format(tmp) + \" \" + format(cdsStart) + \" \" + codingLength);\r\n return new ChromPos((start + 1 + tmp), cdsPos % 3);\r\n }\r\n codingLength += (cdsEnd - start - 1);\r\n logger.debug(\" <- Exon : \" + format(start + 1) + \" - \" + format(cdsEnd) + \" | \" + format(cdsEnd - start) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n logger.debug(\" UTR : \" + format(cdsEnd + 1) + \" - \" + format(end));\r\n } else if (inCoding) {\r\n if (codingLength + (end - start - 1) >= cdsPos) {\r\n int tmp = cdsPos - codingLength;\r\n logger.debug(\" Exon : \" + format(start + 1) + \" - \" + format(end) + \" | \" + format(end - start) + \" | \" + tmp + \" | \" + codingLength);\r\n logger.debug(\" -> found chr position in coding exon #\" + (i + 1) + \": cdsPos:\" + format(cdsPos) + \" s:\" + format(start) + \"-\" + format(end) + \" tmp:\" + format(tmp) + \" cdsStart:\" + format(cdsStart) + \" codingLength:\" + codingLength);\r\n return new ChromPos((start + 1 + tmp), cdsPos % 3);\r\n }\r\n codingLength += (end - start);\r\n logger.debug(\" Exon : \" + format(start + 1) + \" - \" + format(end) + \" | \" + format(end - start) + \" | \" + codingLength + \" | \" + (codingLength % 3));\r\n }\r\n }\r\n return new ChromPos(-1, -1);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean pollDirectory(File directory, List> fileList, int depth){\r\n depth++;\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Polling directory: {}, absolute path: {}\", directory.getPath(), directory.getAbsolutePath());\r\n }\r\n final File[] files = listFiles(directory);\r\n if (files == null || files.length == 0) {\r\n return true;\r\n }\r\n if (getEndpoint().isPreSort()) {\r\n Arrays.sort(files, Comparator.comparing(File::getAbsoluteFile));\r\n }\r\n for (File file : files) {\r\n if (!canPollMoreFiles(fileList)) {\r\n return false;\r\n }\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Found file: {} [isAbsolute: {}, isDirectory: {}, isFile: {}, isHidden: {}]\", file, file.isAbsolute(), file.isDirectory(), file.isFile(), file.isHidden());\r\n }\r\n GenericFile gf = asGenericFile(endpointPath, file, getEndpoint().getCharset(), getEndpoint().isProbeContentType());\r\n if (resumeStrategy != null) {\r\n ResumeAdapter adapter = resumeStrategy.getAdapter();\r\n LOG.trace(\"Checking the resume adapter: {}\", adapter);\r\n if (adapter instanceof FileOffsetResumeAdapter) {\r\n LOG.trace(\"The resume adapter is for offsets: {}\", adapter);\r\n ((FileOffsetResumeAdapter) adapter).setResumePayload(gf);\r\n adapter.resume();\r\n }\r\n if (adapter instanceof DirectoryEntriesResumeAdapter) {\r\n LOG.trace(\"Running the resume process for file {}\", file);\r\n if (((DirectoryEntriesResumeAdapter) adapter).resume(file)) {\r\n LOG.trace(\"Skipping file {} because it has been marked previously consumed\", file);\r\n continue;\r\n }\r\n }\r\n }\r\n if (file.isDirectory()) {\r\n if (endpoint.isRecursive() && depth < endpoint.getMaxDepth() && isValidFile(gf, true, files)) {\r\n boolean canPollMore = pollDirectory(file, fileList, depth);\r\n if (!canPollMore) {\r\n return false;\r\n }\r\n }\r\n } else {\r\n if (depth >= endpoint.minDepth && isValidFile(gf, false, files)) {\r\n LOG.trace(\"Adding valid file: {}\", file);\r\n if (extendedAttributes != null) {\r\n Path path = file.toPath();\r\n Map allAttributes = new HashMap<>();\r\n for (String attribute : extendedAttributes) {\r\n readAttributes(file, path, allAttributes, attribute);\r\n }\r\n gf.setExtendedAttributes(allAttributes);\r\n }\r\n fileList.add(gf);\r\n }\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean checkAndImport(User loginUser, long projectCode, Map result, DagDataSchedule dagDataSchedule, String otherParamsJson){\r\n if (!checkImportanceParams(dagDataSchedule, result)) {\r\n return false;\r\n }\r\n ProcessDefinition processDefinition = dagDataSchedule.getProcessDefinition();\r\n String processDefinitionName = recursionProcessDefinitionName(projectCode, processDefinition.getName(), 1);\r\n String importProcessDefinitionName = getNewName(processDefinitionName, IMPORT_SUFFIX);\r\n Map checkResult = verifyProcessDefinitionName(loginUser, projectCode, importProcessDefinitionName, 0);\r\n if (Status.SUCCESS.equals(checkResult.get(Constants.STATUS))) {\r\n putMsg(result, Status.SUCCESS);\r\n } else {\r\n result.putAll(checkResult);\r\n return false;\r\n }\r\n processDefinition.setName(importProcessDefinitionName);\r\n processDefinition.setId(null);\r\n processDefinition.setProjectCode(projectCode);\r\n processDefinition.setUserId(loginUser.getId());\r\n try {\r\n processDefinition.setCode(CodeGenerateUtils.getInstance().genCode());\r\n } catch (CodeGenerateException e) {\r\n log.error(\"Save process definition error because generate process definition code error, projectCode:{}.\", projectCode, e);\r\n putMsg(result, Status.CREATE_PROCESS_DEFINITION_ERROR);\r\n return false;\r\n }\r\n List taskDefinitionList = dagDataSchedule.getTaskDefinitionList();\r\n Map taskCodeMap = new HashMap<>();\r\n Date now = new Date();\r\n List taskDefinitionLogList = new ArrayList<>();\r\n for (TaskDefinition taskDefinition : taskDefinitionList) {\r\n TaskDefinitionLog taskDefinitionLog = new TaskDefinitionLog(taskDefinition);\r\n taskDefinitionLog.setName(taskDefinitionLog.getName());\r\n taskDefinitionLog.setProjectCode(projectCode);\r\n taskDefinitionLog.setUserId(loginUser.getId());\r\n taskDefinitionLog.setVersion(Constants.VERSION_FIRST);\r\n taskDefinitionLog.setCreateTime(now);\r\n taskDefinitionLog.setUpdateTime(now);\r\n taskDefinitionLog.setOperator(loginUser.getId());\r\n taskDefinitionLog.setOperateTime(now);\r\n try {\r\n long code = CodeGenerateUtils.getInstance().genCode();\r\n taskCodeMap.put(taskDefinitionLog.getCode(), code);\r\n taskDefinitionLog.setCode(code);\r\n } catch (CodeGenerateException e) {\r\n log.error(\"Generate task definition code error, projectCode:{}, processDefinitionCode:{}\", projectCode, processDefinition.getCode(), e);\r\n putMsg(result, Status.INTERNAL_SERVER_ERROR_ARGS, \"Error generating task definition code\");\r\n return false;\r\n }\r\n taskDefinitionLogList.add(taskDefinitionLog);\r\n }\r\n int insert = taskDefinitionMapper.batchInsert(taskDefinitionLogList);\r\n int logInsert = taskDefinitionLogMapper.batchInsert(taskDefinitionLogList);\r\n if ((logInsert & insert) == 0) {\r\n log.error(\"Save task definition error, projectCode:{}, processDefinitionCode:{}\", projectCode, processDefinition.getCode());\r\n putMsg(result, Status.CREATE_TASK_DEFINITION_ERROR);\r\n throw new ServiceException(Status.CREATE_TASK_DEFINITION_ERROR);\r\n }\r\n List taskRelationList = dagDataSchedule.getProcessTaskRelationList();\r\n List taskRelationLogList = new ArrayList<>();\r\n for (ProcessTaskRelation processTaskRelation : taskRelationList) {\r\n ProcessTaskRelationLog processTaskRelationLog = new ProcessTaskRelationLog(processTaskRelation);\r\n if (taskCodeMap.containsKey(processTaskRelationLog.getPreTaskCode())) {\r\n processTaskRelationLog.setPreTaskCode(taskCodeMap.get(processTaskRelationLog.getPreTaskCode()));\r\n }\r\n if (taskCodeMap.containsKey(processTaskRelationLog.getPostTaskCode())) {\r\n processTaskRelationLog.setPostTaskCode(taskCodeMap.get(processTaskRelationLog.getPostTaskCode()));\r\n }\r\n processTaskRelationLog.setPreTaskVersion(Constants.VERSION_FIRST);\r\n processTaskRelationLog.setPostTaskVersion(Constants.VERSION_FIRST);\r\n taskRelationLogList.add(processTaskRelationLog);\r\n }\r\n if (StringUtils.isNotEmpty(processDefinition.getLocations()) && JSONUtils.checkJsonValid(processDefinition.getLocations())) {\r\n ArrayNode arrayNode = JSONUtils.parseArray(processDefinition.getLocations());\r\n ArrayNode newArrayNode = JSONUtils.createArrayNode();\r\n for (int i = 0; i < arrayNode.size(); i++) {\r\n ObjectNode newObjectNode = newArrayNode.addObject();\r\n JsonNode jsonNode = arrayNode.get(i);\r\n Long taskCode = taskCodeMap.get(jsonNode.get(\"taskCode\").asLong());\r\n if (Objects.nonNull(taskCode)) {\r\n newObjectNode.put(\"taskCode\", taskCode);\r\n newObjectNode.set(\"x\", jsonNode.get(\"x\"));\r\n newObjectNode.set(\"y\", jsonNode.get(\"y\"));\r\n }\r\n }\r\n processDefinition.setLocations(newArrayNode.toString());\r\n }\r\n processDefinition.setCreateTime(new Date());\r\n processDefinition.setUpdateTime(new Date());\r\n Map createDagResult = createDagDefine(loginUser, taskRelationLogList, processDefinition, Lists.newArrayList(), otherParamsJson);\r\n if (Status.SUCCESS.equals(createDagResult.get(Constants.STATUS))) {\r\n putMsg(createDagResult, Status.SUCCESS);\r\n } else {\r\n result.putAll(createDagResult);\r\n log.error(\"Import process definition error, projectCode:{}, processDefinitionCode:{}.\", projectCode, processDefinition.getCode());\r\n throw new ServiceException(Status.IMPORT_PROCESS_DEFINE_ERROR);\r\n }\r\n Schedule schedule = dagDataSchedule.getSchedule();\r\n if (null != schedule) {\r\n ProcessDefinition newProcessDefinition = processDefinitionMapper.queryByCode(processDefinition.getCode());\r\n schedule.setProcessDefinitionCode(newProcessDefinition.getCode());\r\n schedule.setId(null);\r\n schedule.setUserId(loginUser.getId());\r\n schedule.setCreateTime(now);\r\n schedule.setUpdateTime(now);\r\n int scheduleInsert = scheduleMapper.insert(schedule);\r\n if (0 == scheduleInsert) {\r\n log.error(\"Import process definition error due to save schedule fail, projectCode:{}, processDefinitionCode:{}.\", projectCode, processDefinition.getCode());\r\n putMsg(result, Status.IMPORT_PROCESS_DEFINE_ERROR);\r\n throw new ServiceException(Status.IMPORT_PROCESS_DEFINE_ERROR);\r\n }\r\n }\r\n log.info(\"Import process definition complete, projectCode:{}, processDefinitionCode:{}.\", projectCode, processDefinition.getCode());\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public TaskResponse run(IShellInterceptorBuilder iShellInterceptorBuilder, TaskCallBack taskCallBack) throws Exception{\r\n TaskResponse result = new TaskResponse();\r\n int taskInstanceId = taskRequest.getTaskInstanceId();\r\n if (null == TaskExecutionContextCacheManager.getByTaskInstanceId(taskInstanceId)) {\r\n logger.warn(\"Cannot find the taskInstance: {} from TaskExecutionContextCacheManager, the task might already been killed\", taskInstanceId);\r\n result.setExitStatusCode(EXIT_CODE_KILL);\r\n return result;\r\n }\r\n iShellInterceptorBuilder = iShellInterceptorBuilder.shellDirectory(taskRequest.getExecutePath()).shellName(taskRequest.getTaskAppId());\r\n if (CollectionUtils.isNotEmpty(ShellUtils.ENV_SOURCE_LIST)) {\r\n ShellUtils.ENV_SOURCE_LIST.forEach(iShellInterceptorBuilder::appendSystemEnv);\r\n }\r\n if (StringUtils.isNotBlank(taskRequest.getEnvironmentConfig())) {\r\n iShellInterceptorBuilder.appendCustomEnvScript(taskRequest.getEnvironmentConfig());\r\n }\r\n if (taskRequest.getK8sTaskExecutionContext() != null) {\r\n iShellInterceptorBuilder.k8sConfigYaml(taskRequest.getK8sTaskExecutionContext().getConfigYaml());\r\n }\r\n iShellInterceptorBuilder.sudoMode(OSUtils.isSudoEnable());\r\n if (TenantConstants.DEFAULT_TENANT_CODE.equals(taskRequest.getTenantCode())) {\r\n iShellInterceptorBuilder.runUser(TenantConstants.BOOTSTRAPT_SYSTEM_USER);\r\n } else {\r\n iShellInterceptorBuilder.runUser(taskRequest.getTenantCode());\r\n }\r\n if (taskRequest.getCpuQuota() != null) {\r\n iShellInterceptorBuilder.cpuQuota(taskRequest.getCpuQuota());\r\n }\r\n if (taskRequest.getMemoryMax() != null) {\r\n iShellInterceptorBuilder.memoryQuota(taskRequest.getMemoryMax());\r\n }\r\n IShellInterceptor iShellInterceptor = iShellInterceptorBuilder.build();\r\n process = iShellInterceptor.execute();\r\n parseProcessOutput(this.process);\r\n collectPodLogIfNeeded();\r\n int processId = getProcessId(this.process);\r\n result.setProcessId(processId);\r\n taskRequest.setProcessId(processId);\r\n boolean updateTaskExecutionContextStatus = TaskExecutionContextCacheManager.updateTaskExecutionContext(taskRequest);\r\n if (Boolean.FALSE.equals(updateTaskExecutionContextStatus)) {\r\n result.setExitStatusCode(EXIT_CODE_KILL);\r\n cancelApplication();\r\n return result;\r\n }\r\n logger.info(\"process start, process id is: {}\", processId);\r\n long remainTime = getRemainTime();\r\n if (null != taskCallBack) {\r\n taskCallBack.updateTaskInstanceInfo(taskInstanceId);\r\n }\r\n boolean status = this.process.waitFor(remainTime, TimeUnit.SECONDS);\r\n TaskExecutionStatus kubernetesStatus = ProcessUtils.getApplicationStatus(taskRequest.getK8sTaskExecutionContext(), taskRequest.getTaskAppId());\r\n if (taskOutputFuture != null) {\r\n try {\r\n taskOutputFuture.get();\r\n } catch (ExecutionException e) {\r\n logger.error(\"Handle task log error\", e);\r\n }\r\n }\r\n if (podLogOutputFuture != null) {\r\n try {\r\n podLogOutputFuture.get();\r\n ProcessUtils.cancelApplication(taskRequest);\r\n } catch (ExecutionException e) {\r\n logger.error(\"Handle pod log error\", e);\r\n }\r\n }\r\n if (status && kubernetesStatus.isSuccess()) {\r\n result.setExitStatusCode(this.process.exitValue());\r\n } else {\r\n logger.error(\"process has failure, the task timeout configuration value is:{}, ready to kill ...\", taskRequest.getTaskTimeout());\r\n result.setExitStatusCode(EXIT_CODE_FAILURE);\r\n cancelApplication();\r\n }\r\n int exitCode = this.process.exitValue();\r\n String exitLogMessage = EXIT_CODE_KILL == exitCode ? \"process has killed.\" : \"process has exited.\";\r\n logger.info(\"{} execute path:{}, processId:{} ,exitStatusCode:{} ,processWaitForStatus:{} ,processExitValue:{}\", exitLogMessage, taskRequest.getExecutePath(), processId, result.getExitStatusCode(), status, exitCode);\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String handleMultiLineCmd(String line) throws IOException{\r\n line = HiveStringUtils.removeComments(line);\r\n Character mask = (System.getProperty(\"jline.terminal\", \"\").equals(\"jline.UnsupportedTerminal\")) ? null : jline.console.ConsoleReader.NULL_MASK;\r\n while (isMultiLine(line) && beeLine.getOpts().isAllowMultiLineCommand()) {\r\n StringBuilder prompt = new StringBuilder(beeLine.getPrompt());\r\n if (!beeLine.getOpts().isSilent()) {\r\n for (int i = 0; i < prompt.length() - 1; i++) {\r\n if (prompt.charAt(i) != '>') {\r\n prompt.setCharAt(i, i % 2 == 0 ? '.' : ' ');\r\n }\r\n }\r\n }\r\n String extra;\r\n if (beeLine.getConsoleReader() == null) {\r\n throw new RuntimeException(\"Console reader not initialized. This could happen when there \" + \"is a multi-line command using -e option and which requires further reading from console\");\r\n }\r\n if (beeLine.getOpts().isSilent() && beeLine.getOpts().getScriptFile() != null) {\r\n extra = beeLine.getConsoleReader().readLine(null, mask);\r\n } else {\r\n extra = beeLine.getConsoleReader().readLine(prompt.toString());\r\n }\r\n if (extra == null) {\r\n break;\r\n }\r\n extra = HiveStringUtils.removeComments(extra);\r\n if (extra != null && !extra.isEmpty()) {\r\n line += \"\\n\" + extra;\r\n }\r\n }\r\n return line;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void getActiveLedgers() throws IOException{\r\n for (File ledgerDirectory : ledgerDirsManager.getAllLedgerDirs()) {\r\n File[] grandParents = ledgerDirectory.listFiles();\r\n if (grandParents == null) {\r\n continue;\r\n }\r\n for (File grandParent : grandParents) {\r\n if (grandParent.isDirectory()) {\r\n File[] parents = grandParent.listFiles();\r\n if (parents == null) {\r\n continue;\r\n }\r\n for (File parent : parents) {\r\n if (parent.isDirectory()) {\r\n File[] indexFiles = parent.listFiles();\r\n if (indexFiles == null) {\r\n continue;\r\n }\r\n for (File index : indexFiles) {\r\n if (!index.isFile() || (!index.getName().endsWith(IDX) && !index.getName().endsWith(RLOC))) {\r\n continue;\r\n }\r\n String ledgerIdInHex = index.getName().replace(RLOC, \"\").replace(IDX, \"\");\r\n if (index.getName().endsWith(RLOC)) {\r\n if (findIndexFile(Long.parseLong(ledgerIdInHex)) != null) {\r\n if (!index.delete()) {\r\n LOG.warn(\"Deleting the rloc file \" + index + \" failed\");\r\n }\r\n continue;\r\n } else {\r\n File dest = new File(index.getParentFile(), ledgerIdInHex + IDX);\r\n if (!index.renameTo(dest)) {\r\n throw new IOException(\"Renaming rloc file \" + index + \" to index file has failed\");\r\n }\r\n }\r\n }\r\n activeLedgers.put(Long.parseLong(ledgerIdInHex, 16), true);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static SearchClause getPrimitiveSearchClause(final SearchCondition sc){\r\n SearchClause clause = new SearchClause();\r\n String property = sc.getCondition().getKeySet().iterator().next();\r\n clause.setProperty(property);\r\n String value = ENCODINGS.values().stream().reduce(sc.getCondition().get(property), (s, v) -> s.replace(v, ENCODINGS.getKey(v)));\r\n clause.setValue(value);\r\n LOG.debug(\"Condition: \" + sc.getCondition());\r\n if (SpecialAttr.ROLES.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.ROLE_MEMBERSHIP);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.PRIVILEGES.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.PRIVILEGE);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.RELATIONSHIPS.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.RELATIONSHIP);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.RELATIONSHIP_TYPES.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.RELATIONSHIP);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.GROUPS.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.GROUP_MEMBERSHIP);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.RESOURCES.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.RESOURCE);\r\n clause.setProperty(value);\r\n } else if (SpecialAttr.MEMBER.toString().equals(property)) {\r\n clause.setType(SearchClause.Type.GROUP_MEMBER);\r\n clause.setProperty(value);\r\n } else if (property.startsWith(\"$\")) {\r\n clause.setType(SearchClause.Type.CUSTOM);\r\n clause.setProperty(value);\r\n } else {\r\n clause.setType(SearchClause.Type.ATTRIBUTE);\r\n }\r\n ConditionType ct = sc.getConditionType();\r\n if (sc instanceof SyncopeFiqlSearchCondition && sc.getConditionType() == ConditionType.CUSTOM) {\r\n SyncopeFiqlSearchCondition sfsc = (SyncopeFiqlSearchCondition) sc;\r\n if (SyncopeFiqlParser.IEQ.equals(sfsc.getOperator())) {\r\n ct = ConditionType.EQUALS;\r\n } else if (SyncopeFiqlParser.NIEQ.equals(sfsc.getOperator())) {\r\n ct = ConditionType.NOT_EQUALS;\r\n }\r\n }\r\n switch(ct) {\r\n case EQUALS:\r\n if (SpecialAttr.RELATIONSHIP_TYPES.toString().equals(property)) {\r\n clause.setComparator(SpecialAttr.NULL.toString().equals(value) ? SearchClause.Comparator.EQUALS : SearchClause.Comparator.IS_NULL);\r\n } else {\r\n clause.setComparator(SpecialAttr.NULL.toString().equals(value) ? SearchClause.Comparator.IS_NULL : SearchClause.Comparator.EQUALS);\r\n }\r\n break;\r\n case NOT_EQUALS:\r\n if (SpecialAttr.RELATIONSHIP_TYPES.toString().equals(property)) {\r\n clause.setComparator(SpecialAttr.NULL.toString().equals(value) ? SearchClause.Comparator.NOT_EQUALS : SearchClause.Comparator.IS_NOT_NULL);\r\n } else {\r\n clause.setComparator(SpecialAttr.NULL.toString().equals(value) ? SearchClause.Comparator.IS_NOT_NULL : SearchClause.Comparator.NOT_EQUALS);\r\n }\r\n break;\r\n case GREATER_OR_EQUALS:\r\n clause.setComparator(SearchClause.Comparator.GREATER_OR_EQUALS);\r\n break;\r\n case GREATER_THAN:\r\n clause.setComparator(SearchClause.Comparator.GREATER_THAN);\r\n break;\r\n case LESS_OR_EQUALS:\r\n clause.setComparator(SearchClause.Comparator.LESS_OR_EQUALS);\r\n break;\r\n case LESS_THAN:\r\n clause.setComparator(SearchClause.Comparator.LESS_THAN);\r\n break;\r\n default:\r\n break;\r\n }\r\n return clause;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean equals(File file1, File file2, boolean checkName, boolean checkBytes){\r\n if (file1 == null)\r\n return file2 == null;\r\n if (file2 == null)\r\n return false;\r\n if (!(file1.exists() && file2.exists()))\r\n return false;\r\n if (checkName && !file1.getName().equals(file2.getName()))\r\n return false;\r\n if (file1.lastModified() != file2.lastModified())\r\n return false;\r\n if (file1.length() != file2.length())\r\n return false;\r\n if (checkBytes) {\r\n try {\r\n InputStream s1 = new FileInputStream(file1);\r\n InputStream s2 = new FileInputStream(file2);\r\n byte[] buf1 = new byte[1000];\r\n byte[] buf2 = new byte[1000];\r\n boolean finished = false;\r\n while (!finished) {\r\n int s1len = s1.read(buf1);\r\n int s2len = s2.read(buf2);\r\n if (s1len != s2len)\r\n return false;\r\n if (s1len == -1)\r\n finished = true;\r\n for (int i = 0; i < s1len; i++) {\r\n if (buf1[i] != buf2[i])\r\n return false;\r\n }\r\n }\r\n } catch (FileNotFoundException e) {\r\n return false;\r\n } catch (IOException e) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String createContextualToken(String token){\r\n StringBuilder sb = new StringBuilder();\r\n if (mode == 'w' && group == 1) {\r\n for (int i = 0; i < segments.size(); i++) {\r\n sb.append(segments.get(i));\r\n }\r\n sb.append(token);\r\n for (int i = path.size() - 1; i >= 0; i--) {\r\n QName q = path.get(i);\r\n sb.append(\"\");\r\n }\r\n } else if (mode == 'i') {\r\n final String stag = token.substring(0, token.indexOf('>') + 1);\r\n Set skip = new HashSet<>();\r\n Matcher matcher = NAMESPACE_PATTERN.matcher(stag);\r\n char quote = 0;\r\n while (matcher.find()) {\r\n String prefix = matcher.group(1);\r\n if (prefix.length() > 0) {\r\n prefix = prefix.substring(1);\r\n }\r\n skip.add(prefix);\r\n if (quote == 0) {\r\n quote = matcher.group(2).charAt(0);\r\n }\r\n }\r\n if (quote == 0) {\r\n quote = '\"';\r\n }\r\n boolean empty = stag.endsWith(\"/>\");\r\n sb.append(token, 0, stag.length() - (empty ? 2 : 1));\r\n for (Entry e : getCurrentNamespaceBindings().entrySet()) {\r\n if (!skip.contains(e.getKey())) {\r\n boolean defaultNS = e.getKey() == null || e.getKey().length() == 0;\r\n if (defaultNS) {\r\n sb.append(\" xmlns\").append(\"=\").append(quote).append(e.getValue()).append(quote);\r\n } else {\r\n sb.append(\" xmlns:\").append(e.getKey()).append(\"=\").append(quote).append(e.getValue()).append(quote);\r\n }\r\n }\r\n }\r\n sb.append(token, stag.length() - (empty ? 2 : 1), token.length());\r\n } else if (mode == 'u') {\r\n int bp = token.indexOf(\">\");\r\n int ep = token.lastIndexOf(\" 0 && ep > 0) {\r\n sb.append(token, bp + 1, ep);\r\n }\r\n } else if (mode == 't') {\r\n int bp = 0;\r\n for (; ; ) {\r\n int ep = token.indexOf('>', bp);\r\n bp = token.indexOf('<', ep);\r\n if (bp < 0) {\r\n break;\r\n }\r\n sb.append(token, ep + 1, bp);\r\n }\r\n } else {\r\n return token;\r\n }\r\n return sb.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void populateItems(final OIDCC4UIProviderTO opTO, final OIDCC4UIProvider op){\r\n SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();\r\n SyncopeClientException invalidMapping = SyncopeClientException.build(ClientExceptionType.InvalidMapping);\r\n SyncopeClientException requiredValuesMissing = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing);\r\n opTO.getItems().forEach(itemTO -> {\r\n if (itemTO == null) {\r\n LOG.error(\"Null {}\", ItemTO.class.getSimpleName());\r\n invalidMapping.getElements().add(\"Null \" + ItemTO.class.getSimpleName());\r\n } else if (itemTO.getIntAttrName() == null) {\r\n requiredValuesMissing.getElements().add(\"intAttrName\");\r\n scce.addException(requiredValuesMissing);\r\n } else {\r\n IntAttrName intAttrName = null;\r\n try {\r\n intAttrName = intAttrNameParser.parse(itemTO.getIntAttrName(), AnyTypeKind.USER);\r\n } catch (ParseException e) {\r\n LOG.error(\"Invalid intAttrName '{}' specified, ignoring\", itemTO.getIntAttrName(), e);\r\n }\r\n if (intAttrName == null || intAttrName.getSchemaType() == null && intAttrName.getField() == null) {\r\n LOG.error(\"'{}' not existing\", itemTO.getIntAttrName());\r\n invalidMapping.getElements().add('\\'' + itemTO.getIntAttrName() + \"' not existing\");\r\n } else {\r\n if (!JexlUtils.isExpressionValid(itemTO.getMandatoryCondition() == null ? \"false\" : itemTO.getMandatoryCondition())) {\r\n SyncopeClientException invalidMandatoryCondition = SyncopeClientException.build(ClientExceptionType.InvalidValues);\r\n invalidMandatoryCondition.getElements().add(itemTO.getMandatoryCondition());\r\n scce.addException(invalidMandatoryCondition);\r\n }\r\n OIDCC4UIProviderItem item = entityFactory.newEntity(OIDCC4UIProviderItem.class);\r\n item.setIntAttrName(itemTO.getIntAttrName());\r\n item.setExtAttrName(itemTO.getExtAttrName());\r\n item.setMandatoryCondition(itemTO.getMandatoryCondition());\r\n item.setConnObjectKey(itemTO.isConnObjectKey());\r\n item.setPassword(itemTO.isPassword());\r\n item.setPropagationJEXLTransformer(itemTO.getPropagationJEXLTransformer());\r\n item.setPullJEXLTransformer(itemTO.getPullJEXLTransformer());\r\n item.setOP(op);\r\n item.setPurpose(MappingPurpose.NONE);\r\n if (item.isConnObjectKey()) {\r\n if (intAttrName.getSchemaType() == SchemaType.VIRTUAL) {\r\n invalidMapping.getElements().add(\"Virtual attributes cannot be set as ConnObjectKey\");\r\n }\r\n if (\"password\".equals(intAttrName.getField())) {\r\n invalidMapping.getElements().add(\"Password attributes cannot be set as ConnObjectKey\");\r\n }\r\n op.setConnObjectKeyItem(item);\r\n } else {\r\n op.add(item);\r\n }\r\n }\r\n }\r\n });\r\n if (!invalidMapping.getElements().isEmpty()) {\r\n scce.addException(invalidMapping);\r\n }\r\n if (scce.hasExceptions()) {\r\n throw scce;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String[] tryGrammaticalAnalysisSqlColumnNames(DbType dbType, String sql){\r\n String[] columnNames;\r\n try {\r\n SQLStatementParser parser = DataxUtils.getSqlStatementParser(dbType, sql);\r\n if (parser == null) {\r\n log.warn(\"database driver [{}] is not support grammatical analysis sql\", dbType);\r\n return new String[0];\r\n }\r\n SQLStatement sqlStatement = parser.parseStatement();\r\n SQLSelectStatement sqlSelectStatement = (SQLSelectStatement) sqlStatement;\r\n SQLSelect sqlSelect = sqlSelectStatement.getSelect();\r\n List selectItemList = null;\r\n if (sqlSelect.getQuery() instanceof SQLSelectQueryBlock) {\r\n SQLSelectQueryBlock block = (SQLSelectQueryBlock) sqlSelect.getQuery();\r\n selectItemList = block.getSelectList();\r\n } else if (sqlSelect.getQuery() instanceof SQLUnionQuery) {\r\n SQLUnionQuery unionQuery = (SQLUnionQuery) sqlSelect.getQuery();\r\n SQLSelectQueryBlock block = (SQLSelectQueryBlock) unionQuery.getRight();\r\n selectItemList = block.getSelectList();\r\n }\r\n notNull(selectItemList, String.format(\"select query type [%s] is not support\", sqlSelect.getQuery().toString()));\r\n columnNames = new String[selectItemList.size()];\r\n for (int i = 0; i < selectItemList.size(); i++) {\r\n SQLSelectItem item = selectItemList.get(i);\r\n String columnName = null;\r\n if (item.getAlias() != null) {\r\n columnName = item.getAlias();\r\n } else if (item.getExpr() != null) {\r\n if (item.getExpr() instanceof SQLPropertyExpr) {\r\n SQLPropertyExpr expr = (SQLPropertyExpr) item.getExpr();\r\n columnName = expr.getName();\r\n } else if (item.getExpr() instanceof SQLIdentifierExpr) {\r\n SQLIdentifierExpr expr = (SQLIdentifierExpr) item.getExpr();\r\n columnName = expr.getName();\r\n }\r\n } else {\r\n throw new RuntimeException(String.format(\"grammatical analysis sql column [ %s ] failed\", item));\r\n }\r\n if (SELECT_ALL_CHARACTER.equals(item.toString())) {\r\n log.info(\"sql contains *, grammatical analysis failed\");\r\n return new String[0];\r\n }\r\n if (columnName == null) {\r\n throw new RuntimeException(String.format(\"grammatical analysis sql column [ %s ] failed\", item));\r\n }\r\n columnNames[i] = columnName;\r\n }\r\n } catch (Exception e) {\r\n log.warn(e.getMessage(), e);\r\n return new String[0];\r\n }\r\n return columnNames;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected int compareTypeDeclarations(TypeDeclaration oldDeclaration, TypeDeclaration newDeclaration) throws IncompatibleClassChangeError{\r\n if (!oldDeclaration.getFormat().equals(newDeclaration.getFormat())) {\r\n throw new IncompatibleClassChangeError(\"Type Declaration \" + newDeclaration.getTypeName() + \" has a different\" + \" format that its previous definition: \" + newDeclaration.getFormat() + \"!=\" + oldDeclaration.getFormat());\r\n }\r\n if (!oldDeclaration.getTypeClassDef().getSuperClass().equals(newDeclaration.getTypeClassDef().getSuperClass())) {\r\n if (oldDeclaration.getNature() != TypeDeclaration.Nature.DEFINITION || newDeclaration.getNature() != TypeDeclaration.Nature.DECLARATION || !Object.class.getName().equals(newDeclaration.getTypeClassDef().getSuperClass())) {\r\n throw new IncompatibleClassChangeError(\"Type Declaration \" + newDeclaration.getTypeName() + \" has a different\" + \" superclass that its previous definition: \" + newDeclaration.getTypeClassDef().getSuperClass() + \" != \" + oldDeclaration.getTypeClassDef().getSuperClass());\r\n }\r\n }\r\n if (!nullSafeEqualityComparison(oldDeclaration.getDurationAttribute(), newDeclaration.getDurationAttribute())) {\r\n throw new IncompatibleClassChangeError(\"Type Declaration \" + newDeclaration.getTypeName() + \" has a different\" + \" duration: \" + newDeclaration.getDurationAttribute() + \" != \" + oldDeclaration.getDurationAttribute());\r\n }\r\n if (newDeclaration.getNature().equals(TypeDeclaration.Nature.DEFINITION)) {\r\n if (oldDeclaration.getSetMask() != newDeclaration.getSetMask()) {\r\n throw new IncompatibleClassChangeError(\"Type Declaration \" + newDeclaration.getTypeName() + \" is incompatible with\" + \" the previous definition: \" + newDeclaration + \" != \" + oldDeclaration);\r\n }\r\n }\r\n List oldFields = oldDeclaration.getTypeClassDef().getFields();\r\n Map newFieldsMap = new HashMap<>();\r\n for (FactField factField : newDeclaration.getTypeClassDef().getFields()) {\r\n newFieldsMap.put(factField.getName(), factField);\r\n }\r\n boolean allFieldsInOldDeclarationAreStillPresent = true;\r\n for (FactField oldFactField : oldFields) {\r\n FactField newFactField = newFieldsMap.get(oldFactField.getName());\r\n if (newFactField != null) {\r\n String newFactType = ((FieldDefinition) newFactField).getTypeName();\r\n if (!newFactType.equals(((FieldDefinition) oldFactField).getTypeName())) {\r\n throw new IncompatibleClassChangeError(\"Type Declaration \" + newDeclaration.getTypeName() + \".\" + newFactField.getName() + \" has a different\" + \" type that its previous definition: \" + newFactType + \" != \" + oldFactField.getType().getCanonicalName());\r\n }\r\n } else {\r\n allFieldsInOldDeclarationAreStillPresent = false;\r\n }\r\n }\r\n if (oldFields.size() < newFieldsMap.size()) {\r\n return -1;\r\n }\r\n if (oldFields.size() > newFieldsMap.size()) {\r\n return 1;\r\n }\r\n if (allFieldsInOldDeclarationAreStillPresent) {\r\n return 0;\r\n }\r\n throw new IncompatibleClassChangeError(newDeclaration.getTypeName() + \" introduces\" + \" fields that are not present in its previous version.\");\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List parseLocationString(String string, int versus){\r\n Matcher m;\r\n List boundedLocationsCollection = new ArrayList();\r\n List tokens = splitString(string);\r\n for (String t : tokens) {\r\n m = genbankSplitPattern.matcher(t);\r\n if (!m.find()) {\r\n throw new ParserException(\"Cannot interpret split pattern \" + t + \"\\nin location string:\" + string);\r\n }\r\n String splitQualifier = m.group(1);\r\n String splitString = m.group(2);\r\n if (!splitQualifier.isEmpty()) {\r\n int localVersus = splitQualifier.equalsIgnoreCase(\"complement\") ? -1 : 1;\r\n List subLocations = parseLocationString(splitString, versus * localVersus);\r\n switch(complexFeaturesAppendMode) {\r\n case FLATTEN:\r\n boundedLocationsCollection.addAll(subLocations);\r\n break;\r\n case HIERARCHICAL:\r\n if (subLocations.size() == 1) {\r\n boundedLocationsCollection.addAll(subLocations);\r\n } else {\r\n Point min = Location.Tools.getMin(subLocations).getStart();\r\n Point max = Location.Tools.getMax(subLocations).getEnd();\r\n AbstractLocation motherLocation = new SimpleLocation(min, max);\r\n if (splitQualifier.equalsIgnoreCase(\"join\")) {\r\n motherLocation = new InsdcLocations.GroupLocation(subLocations);\r\n }\r\n if (splitQualifier.equalsIgnoreCase(\"order\")) {\r\n motherLocation = new InsdcLocations.OrderLocation(subLocations);\r\n }\r\n if (splitQualifier.equalsIgnoreCase(\"bond\")) {\r\n motherLocation = new InsdcLocations.BondLocation(subLocations);\r\n }\r\n motherLocation.setStrand(getGroupLocationStrand(subLocations));\r\n boundedLocationsCollection.add(motherLocation);\r\n }\r\n break;\r\n }\r\n } else {\r\n m = singleLocationPattern.matcher(splitString);\r\n if (!m.find()) {\r\n throw new ParserException(\"Cannot interpret location pattern \" + splitString + \"\\nin location string:\" + string);\r\n }\r\n String accession = m.group(1);\r\n Strand s = versus == 1 ? Strand.POSITIVE : Strand.NEGATIVE;\r\n int start = Integer.valueOf(m.group(3));\r\n int end = m.group(6) == null ? start : Integer.valueOf(m.group(6));\r\n if (featureGlobalStart > start) {\r\n featureGlobalStart = start;\r\n }\r\n if (featureGlobalEnd < end) {\r\n featureGlobalEnd = end;\r\n }\r\n AbstractLocation l;\r\n if (start <= end) {\r\n l = new SimpleLocation(start, end, s);\r\n } else {\r\n AbstractLocation l5prime = new SimpleLocation(1, end, Strand.UNDEFINED);\r\n AbstractLocation l3prime = new SimpleLocation(start, (int) sequenceLength, Strand.UNDEFINED);\r\n l = new InsdcLocations.GroupLocation(new SimplePoint(start), new SimplePoint(end), s, isSequenceCircular, l5prime, l3prime);\r\n }\r\n if (m.group(4) != null && m.group(4).equals(\"^\"))\r\n l.setBetweenCompounds(true);\r\n if (m.group(2).equals(\"<\")) {\r\n l.setPartialOn5prime(true);\r\n }\r\n if (m.group(5) != null && (m.group(5).equals(\">\") || m.group(7).equals(\">\"))) {\r\n l.setPartialOn3prime(true);\r\n }\r\n if (!(accession == null || \"\".equals(accession)))\r\n l.setAccession(new AccessionID(accession));\r\n boundedLocationsCollection.add(l);\r\n }\r\n }\r\n return boundedLocationsCollection;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List match(final SyncDelta syncDelta, final Provision provision){\r\n Optional correlationRule = provision.getResource().getPullPolicy() == null ? Optional.empty() : provision.getResource().getPullPolicy().getCorrelationRule(provision.getAnyType());\r\n Optional rule = Optional.empty();\r\n if (correlationRule.isPresent()) {\r\n try {\r\n rule = ImplementationManager.buildPullCorrelationRule(correlationRule.get().getImplementation());\r\n } catch (Exception e) {\r\n LOG.error(\"While building {}\", correlationRule.get().getImplementation(), e);\r\n }\r\n }\r\n List result = List.of();\r\n try {\r\n if (rule.isPresent()) {\r\n result = matchByCorrelationRule(syncDelta, provision, rule.get(), provision.getAnyType().getKind());\r\n } else {\r\n String connObjectKeyValue = null;\r\n Optional connObjectKeyItem = MappingUtils.getConnObjectKeyItem(provision);\r\n if (connObjectKeyItem.isPresent()) {\r\n Attribute connObjectKeyAttr = syncDelta.getObject().getAttributeByName(connObjectKeyItem.get().getExtAttrName());\r\n if (connObjectKeyAttr != null) {\r\n connObjectKeyValue = AttributeUtil.getStringValue(connObjectKeyAttr);\r\n }\r\n if (connObjectKeyValue == null) {\r\n connObjectKeyValue = syncDelta.getUid().getUidValue();\r\n }\r\n }\r\n if (connObjectKeyValue == null) {\r\n result = List.of(PullCorrelationRule.NO_MATCH);\r\n } else {\r\n result = matchByConnObjectKeyValue(connObjectKeyItem.get(), connObjectKeyValue, provision);\r\n }\r\n }\r\n } catch (RuntimeException e) {\r\n LOG.error(\"Could not match {} with any existing {}\", syncDelta, provision.getAnyType().getKey(), e);\r\n }\r\n if (result.size() == 1 && result.get(0).getMatchTarget() == MatchType.ANY) {\r\n virAttrHandler.setValues(result.get(0).getAny(), syncDelta.getObject());\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean matches(RelOptRuleCall call){\r\n final Sort sort = call.rel(0);\r\n final Join join = call.rel(1);\r\n final RelMetadataQuery mq = call.getMetadataQuery();\r\n final JoinInfo joinInfo = JoinInfo.of(join.getLeft(), join.getRight(), join.getCondition());\r\n if (join.getJoinType() == JoinRelType.LEFT) {\r\n if (sort.getCollation() != RelCollations.EMPTY) {\r\n for (RelFieldCollation relFieldCollation : sort.getCollation().getFieldCollations()) {\r\n if (relFieldCollation.getFieldIndex() >= join.getLeft().getRowType().getFieldCount()) {\r\n return false;\r\n }\r\n }\r\n }\r\n if (sort.offset != null && !RelMdUtil.areColumnsDefinitelyUnique(mq, join.getRight(), joinInfo.rightSet())) {\r\n return false;\r\n }\r\n } else if (join.getJoinType() == JoinRelType.RIGHT) {\r\n if (sort.getCollation() != RelCollations.EMPTY) {\r\n for (RelFieldCollation relFieldCollation : sort.getCollation().getFieldCollations()) {\r\n if (relFieldCollation.getFieldIndex() < join.getLeft().getRowType().getFieldCount()) {\r\n return false;\r\n }\r\n }\r\n }\r\n if (sort.offset != null && !RelMdUtil.areColumnsDefinitelyUnique(mq, join.getLeft(), joinInfo.leftSet())) {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void redoInsert(InsertNode node) throws WriteProcessException{\r\n if (!node.hasValidMeasurements()) {\r\n return;\r\n }\r\n if (tsFileResource != null) {\r\n String deviceId = node.isAligned() ? node.getDevicePath().getDevicePath().getFullPath() : node.getDevicePath().getFullPath();\r\n long lastEndTime = tsFileResource.getEndTime(deviceId);\r\n long minTimeInNode;\r\n if (node instanceof InsertRowNode) {\r\n minTimeInNode = ((InsertRowNode) node).getTime();\r\n } else {\r\n minTimeInNode = ((InsertTabletNode) node).getTimes()[0];\r\n }\r\n if (lastEndTime != Long.MIN_VALUE && lastEndTime >= minTimeInNode && sequence) {\r\n return;\r\n }\r\n }\r\n node.setDeviceID(DeviceIDFactory.getInstance().getDeviceID(node.getDevicePath()));\r\n if (node instanceof InsertRowNode) {\r\n if (node.isAligned()) {\r\n recoveryMemTable.insertAlignedRow((InsertRowNode) node);\r\n } else {\r\n recoveryMemTable.insert((InsertRowNode) node);\r\n }\r\n } else {\r\n if (node.isAligned()) {\r\n recoveryMemTable.insertAlignedTablet((InsertTabletNode) node, 0, ((InsertTabletNode) node).getRowCount());\r\n } else {\r\n recoveryMemTable.insertTablet((InsertTabletNode) node, 0, ((InsertTabletNode) node).getRowCount());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ResponseBuilder processInvalidEntityExceptions(final Exception ex){\r\n InvalidEntityException iee = null;\r\n if (ex instanceof InvalidEntityException) {\r\n iee = (InvalidEntityException) ex;\r\n }\r\n if (ex instanceof TransactionSystemException && ROLLBACK_EXCLASS.isAssignableFrom(ex.getCause().getClass()) && ex.getCause().getCause() instanceof InvalidEntityException) {\r\n iee = (InvalidEntityException) ex.getCause().getCause();\r\n }\r\n if (iee != null) {\r\n ClientExceptionType exType;\r\n if (iee.getEntityClassSimpleName().endsWith(\"Policy\")) {\r\n exType = ClientExceptionType.InvalidPolicy;\r\n } else if (iee.getEntityClassSimpleName().equals(PlainAttr.class.getSimpleName())) {\r\n exType = ClientExceptionType.InvalidValues;\r\n } else {\r\n try {\r\n exType = ClientExceptionType.valueOf(\"Invalid\" + iee.getEntityClassSimpleName());\r\n } catch (IllegalArgumentException e) {\r\n exType = ClientExceptionType.InvalidEntity;\r\n }\r\n }\r\n StringBuilder msg = new StringBuilder();\r\n for (Map.Entry, Set> violation : iee.getViolations().entrySet()) {\r\n for (EntityViolationType violationType : violation.getValue()) {\r\n msg.append(violationType.name()).append(\": \").append(violationType.getMessage()).append('\\n');\r\n }\r\n }\r\n return builder(exType, msg.toString());\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Node insert(K key){\r\n if (key == null) {\r\n if (nullNode == null) {\r\n nullNode = new Node<>(key);\r\n }\r\n return nullNode;\r\n }\r\n Node insertedNode;\r\n if (root == null) {\r\n insertedNode = new Node<>(key);\r\n root = insertedNode;\r\n } else {\r\n Node n = root;\r\n while (true) {\r\n int compResult = key.compareTo(n.key);\r\n if (compResult == 0) {\r\n return n;\r\n } else if (compResult < 0) {\r\n if (n.left == null) {\r\n insertedNode = new Node<>(key);\r\n n.left = insertedNode;\r\n break;\r\n } else {\r\n n = n.left;\r\n }\r\n } else {\r\n if (n.right == null) {\r\n insertedNode = new Node<>(key);\r\n n.right = insertedNode;\r\n break;\r\n } else {\r\n n = n.right;\r\n }\r\n }\r\n }\r\n insertedNode.parent = n;\r\n }\r\n insertCase1(insertedNode);\r\n return insertedNode;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CommandProcessorResponse processCmd1(String cmd) throws CommandProcessorException{\r\n CliSessionState ss = (CliSessionState) SessionState.get();\r\n String cmd_trimmed = HiveStringUtils.removeComments(cmd).trim();\r\n String[] tokens = tokenizeCmd(cmd_trimmed);\r\n CommandProcessorResponse response = new CommandProcessorResponse();\r\n if (cmd_trimmed.toLowerCase().equals(\"quit\") || cmd_trimmed.toLowerCase().equals(\"exit\")) {\r\n ss.close();\r\n System.exit(0);\r\n } else if (tokens[0].equalsIgnoreCase(\"source\")) {\r\n String cmd_1 = getFirstCmd(cmd_trimmed, tokens[0].length());\r\n cmd_1 = new VariableSubstitution(new HiveVariableSource() {\r\n\r\n @Override\r\n public Map getHiveVariable() {\r\n return SessionState.get().getHiveVariables();\r\n }\r\n }).substitute(ss.getConf(), cmd_1);\r\n File sourceFile = new File(cmd_1);\r\n if (!sourceFile.isFile()) {\r\n console.printError(\"File: \" + cmd_1 + \" is not a file.\");\r\n throw new CommandProcessorException(1);\r\n } else {\r\n try {\r\n response = processFile(cmd_1);\r\n } catch (IOException e) {\r\n console.printError(\"Failed processing file \" + cmd_1 + \" \" + e.getLocalizedMessage(), stringifyException(e));\r\n throw new CommandProcessorException(1);\r\n }\r\n }\r\n } else if (cmd_trimmed.startsWith(\"!\")) {\r\n String shell_cmd = cmd.trim().substring(1);\r\n shell_cmd = new VariableSubstitution(new HiveVariableSource() {\r\n\r\n @Override\r\n public Map getHiveVariable() {\r\n return SessionState.get().getHiveVariables();\r\n }\r\n }).substitute(ss.getConf(), shell_cmd);\r\n try {\r\n ShellCmdExecutor executor = new ShellCmdExecutor(shell_cmd, ss.out, ss.err);\r\n int responseCode = executor.execute();\r\n if (responseCode != 0) {\r\n console.printError(\"Command failed with exit code = \" + response);\r\n ss.resetThreadName();\r\n throw new CommandProcessorException(responseCode);\r\n }\r\n response = new CommandProcessorResponse();\r\n } catch (Exception e) {\r\n console.printError(\"Exception raised from Shell command \" + e.getLocalizedMessage(), stringifyException(e));\r\n throw new CommandProcessorException(1);\r\n }\r\n } else {\r\n try {\r\n try (CommandProcessor proc = CommandProcessorFactory.get(tokens, (HiveConf) conf)) {\r\n if (proc instanceof IDriver) {\r\n response = processLocalCmd(cmd, proc, ss);\r\n } else {\r\n response = processLocalCmd(cmd_trimmed, proc, ss);\r\n }\r\n }\r\n } catch (SQLException e) {\r\n console.printError(\"Failed processing command \" + tokens[0] + \" \" + e.getLocalizedMessage(), org.apache.hadoop.util.StringUtils.stringifyException(e));\r\n throw new CommandProcessorException(1);\r\n } catch (CommandProcessorException e) {\r\n throw e;\r\n } catch (Exception e) {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n return response;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void queryInitialMembersFromMetadataRaftGroup(){\r\n RaftOp op = new GetRaftGroupOp(groupId);\r\n InternalCompletableFuture f = invocationManager.query(getMetadataGroupId(), op, LEADER_LOCAL);\r\n f.whenCompleteAsync((group, throwable) -> {\r\n if (throwable == null) {\r\n if (group != null) {\r\n if (group.members().contains(getLocalCPMember())) {\r\n createRaftNode(groupId, group.initialMembers());\r\n } else {\r\n queryInitialMembersFromTargetRaftGroup();\r\n }\r\n } else if (logger.isFineEnabled()) {\r\n logger.fine(\"Cannot get initial members of \" + groupId + \" from the METADATA CP group\");\r\n }\r\n } else {\r\n if (throwable instanceof CPGroupDestroyedException) {\r\n CPGroupId destroyedGroupId = ((CPGroupDestroyedException) throwable).getGroupId();\r\n terminateRaftNode(destroyedGroupId, true);\r\n }\r\n if (logger.isFineEnabled()) {\r\n logger.fine(\"Cannot get initial members of \" + groupId + \" from the METADATA CP group\", throwable);\r\n }\r\n }\r\n }, internalAsyncExecutor);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static Method method(Object o, String methodName, Object[] args){\r\n for (Class aClass = o.getClass(); ; ) {\r\n loop: for (Method method1 : aClass.getMethods()) {\r\n if (method1.getName().equals(methodName) && method1.getParameterCount() == args.length && Modifier.isPublic(method1.getDeclaringClass().getModifiers())) {\r\n for (Pair pair : Pair.zip(args, (Class[]) method1.getParameterTypes())) {\r\n if (!pair.right.isInstance(pair.left)) {\r\n continue loop;\r\n }\r\n }\r\n return method1;\r\n }\r\n }\r\n if (aClass.getSuperclass() != null && aClass.getSuperclass() != Object.class) {\r\n aClass = aClass.getSuperclass();\r\n } else {\r\n final Class[] interfaces = aClass.getInterfaces();\r\n if (interfaces.length > 0) {\r\n aClass = interfaces[0];\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n throw new AssertionError(\"method \" + methodName + \" not found\");\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AttributeDescr enabled(AttributeSupportBuilder as) throws RecognitionException{\r\n AttributeDescrBuilder attribute = null;\r\n try {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.ENABLED, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n attribute = helper.start((DescrBuilder) as, AttributeDescrBuilder.class, DroolsSoftKeywords.ENABLED);\r\n }\r\n boolean hasParen = input.LA(1) == DRL6Lexer.LEFT_PAREN;\r\n int first = input.index();\r\n if (hasParen) {\r\n match(input, DRL6Lexer.LEFT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n }\r\n String value = conditionalExpression();\r\n if (state.failed)\r\n return null;\r\n if (hasParen) {\r\n match(input, DRL6Lexer.RIGHT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0) {\r\n if (attribute != null) {\r\n if (hasParen) {\r\n value = input.toString(first, input.LT(-1).getTokenIndex());\r\n }\r\n attribute.value(value);\r\n attribute.type(AttributeDescr.Type.EXPRESSION);\r\n }\r\n }\r\n } finally {\r\n if (attribute != null) {\r\n helper.end(AttributeDescrBuilder.class, attribute);\r\n }\r\n }\r\n return attribute != null ? attribute.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void appendObjectPathsAndDefinitions(){\r\n for (final ObjectSpecification objectSpec : specificationLoader.snapshotSpecifications()) {\r\n if (Facets.domainServiceIsPresent(objectSpec) || Facets.mixinIsPresent(objectSpec)) {\r\n continue;\r\n }\r\n if (visibility.isPublic() && !_Util.isVisibleForPublic(objectSpec)) {\r\n continue;\r\n }\r\n if (objectSpec.isAbstract()) {\r\n continue;\r\n }\r\n if (objectSpec.isValue()) {\r\n continue;\r\n }\r\n if (classExcluder.exclude(objectSpec)) {\r\n continue;\r\n }\r\n final List objectProperties = _Util.propertiesOf(objectSpec, visibility);\r\n final List objectCollections = _Util.collectionsOf(objectSpec, visibility);\r\n final List objectActions = _Util.actionsOf(objectSpec, visibility, classExcluder);\r\n if (objectProperties.isEmpty() && objectCollections.isEmpty()) {\r\n continue;\r\n }\r\n val causewayModel = appendObjectPathAndModelDefinitions(objectSpec);\r\n updateObjectModel(causewayModel, objectSpec, objectProperties, objectCollections);\r\n for (final OneToManyAssociation objectCollection : objectCollections) {\r\n appendCollectionTo(objectSpec, objectCollection);\r\n }\r\n for (final ObjectAction objectAction : objectActions) {\r\n appendObjectActionInvokePath(objectSpec, objectAction);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void unparse(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec){\r\n final SqlJoin join = (SqlJoin) call;\r\n join.left.unparse(writer, leftPrec, getLeftPrec());\r\n switch(join.getJoinType()) {\r\n case COMMA:\r\n writer.sep(\",\", true);\r\n break;\r\n case CROSS:\r\n writer.sep(join.isNatural() ? \"NATURAL CROSS JOIN\" : \"CROSS JOIN\");\r\n break;\r\n case FULL:\r\n writer.sep(join.isNatural() ? \"NATURAL FULL JOIN\" : \"FULL JOIN\");\r\n break;\r\n case INNER:\r\n writer.sep(join.isNatural() ? \"NATURAL INNER JOIN\" : \"INNER JOIN\");\r\n break;\r\n case LEFT:\r\n writer.sep(join.isNatural() ? \"NATURAL LEFT JOIN\" : \"LEFT JOIN\");\r\n break;\r\n case LEFT_SEMI_JOIN:\r\n writer.sep(join.isNatural() ? \"NATURAL LEFT SEMI JOIN\" : \"LEFT SEMI JOIN\");\r\n break;\r\n case RIGHT:\r\n writer.sep(join.isNatural() ? \"NATURAL RIGHT JOIN\" : \"RIGHT JOIN\");\r\n break;\r\n default:\r\n throw Util.unexpected(join.getJoinType());\r\n }\r\n join.right.unparse(writer, getRightPrec(), rightPrec);\r\n SqlNode joinCondition = join.condition;\r\n if (joinCondition != null) {\r\n switch(join.getConditionType()) {\r\n case USING:\r\n writer.keyword(\"USING\");\r\n assert joinCondition instanceof SqlNodeList : \"joinCondition should be SqlNodeList, got \" + joinCondition;\r\n final SqlWriter.Frame frame = writer.startList(FRAME_TYPE, \"(\", \")\");\r\n joinCondition.unparse(writer, 0, 0);\r\n writer.endList(frame);\r\n break;\r\n case ON:\r\n writer.keyword(\"ON\");\r\n joinCondition.unparse(writer, leftPrec, rightPrec);\r\n break;\r\n default:\r\n throw Util.unexpected(join.getConditionType());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateClientConfigs(Exchange exchange, ClientConfigurations clientConfigurations){\r\n if (ObjectHelper.isEmpty(exchange.getProperty(FunctionGraphProperties.OPERATION)) && ObjectHelper.isEmpty(endpoint.getOperation())) {\r\n throw new IllegalArgumentException(\"Operation name not found\");\r\n } else {\r\n clientConfigurations.setOperation(ObjectHelper.isNotEmpty(exchange.getProperty(FunctionGraphProperties.OPERATION)) ? (String) exchange.getProperty(FunctionGraphProperties.OPERATION) : endpoint.getOperation());\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(FunctionGraphProperties.FUNCTION_NAME)) && ObjectHelper.isEmpty(endpoint.getFunctionName())) {\r\n throw new IllegalArgumentException(\"Function name not found\");\r\n } else {\r\n clientConfigurations.setFunctionName(ObjectHelper.isNotEmpty(exchange.getProperty(FunctionGraphProperties.FUNCTION_NAME)) ? (String) exchange.getProperty(FunctionGraphProperties.FUNCTION_NAME) : endpoint.getFunctionName());\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(FunctionGraphProperties.FUNCTION_PACKAGE)) && ObjectHelper.isEmpty(endpoint.getFunctionPackage())) {\r\n clientConfigurations.setFunctionPackage(FunctionGraphConstants.DEFAULT_FUNCTION_PACKAGE);\r\n } else {\r\n clientConfigurations.setFunctionPackage(ObjectHelper.isNotEmpty(exchange.getProperty(FunctionGraphProperties.FUNCTION_PACKAGE)) ? (String) exchange.getProperty(FunctionGraphProperties.FUNCTION_PACKAGE) : endpoint.getFunctionPackage());\r\n }\r\n if (ObjectHelper.isEmpty(exchange.getProperty(FunctionGraphProperties.XCFFLOGTYPE))) {\r\n LOG.warn(\"No XCffLogType given\");\r\n } else {\r\n clientConfigurations.setXCffLogType((String) exchange.getProperty(FunctionGraphProperties.XCFFLOGTYPE));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process(LinkedHashMap> hits, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception{\r\n int size = hits.size();\r\n int index = 0;\r\n for (String accessionid : hits.keySet()) {\r\n index++;\r\n if (index == 12) {\r\n index = 12;\r\n }\r\n logger.error(accessionid + \" \" + index + \"/\" + size);\r\n try {\r\n String[] data = accessionid.split(\" \");\r\n String id = data[0];\r\n GeneSequence geneSequence = geneSequenceHashMap.get(id);\r\n if (geneSequence == null) {\r\n logger.error(\"Not found \" + id);\r\n continue;\r\n }\r\n ArrayList uniprotProteinHits = hits.get(accessionid);\r\n String uniprotBestHit = uniprotProteinHits.get(0);\r\n UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniprotBestHit, AminoAcidCompoundSet.getAminoAcidCompoundSet());\r\n ProteinSequence proteinSequence = new ProteinSequence(uniprotSequence);\r\n String hitSequence = proteinSequence.getSequenceAsString();\r\n for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {\r\n String predictedProteinSequence = transcriptSequence.getProteinSequence().getSequenceAsString();\r\n ArrayList cdsProteinList = transcriptSequence.getProteinCDSSequences();\r\n ArrayList cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values());\r\n String testSequence = \"\";\r\n for (ProteinSequence cdsProteinSequence : cdsProteinList) {\r\n testSequence = testSequence + cdsProteinSequence.getSequenceAsString();\r\n }\r\n if (!testSequence.equals(predictedProteinSequence) && (!predictedProteinSequence.equals(testSequence.substring(0, testSequence.length() - 1)))) {\r\n DNASequence codingSequence = transcriptSequence.getDNACodingSequence();\r\n logger.info(\"Coding Sequence: {}\", codingSequence.getSequenceAsString());\r\n logger.info(\"Sequence agreement error\");\r\n logger.info(\"CDS seq={}\", testSequence);\r\n logger.info(\"PRE seq={}\", predictedProteinSequence);\r\n logger.info(\"UNI seq={}\", hitSequence);\r\n }\r\n SequencePair alignment = Alignments.getPairwiseAlignment(transcriptSequence.getProteinSequence(), proteinSequence, PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), SimpleSubstitutionMatrix.getBlosum62());\r\n int proteinIndex = 0;\r\n int gff3Index = 0;\r\n for (int i = 0; i < cdsProteinList.size(); i++) {\r\n ProteinSequence peptideSequence = cdsProteinList.get(i);\r\n String seq = peptideSequence.getSequenceAsString();\r\n Integer startIndex = null;\r\n int offsetStartIndex = 0;\r\n for (int s = 0; s < seq.length(); s++) {\r\n startIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + s);\r\n if (startIndex != null) {\r\n startIndex = startIndex + 1;\r\n offsetStartIndex = s;\r\n break;\r\n }\r\n }\r\n Integer endIndex = null;\r\n int offsetEndIndex = 0;\r\n for (int e = 0; e < seq.length(); e++) {\r\n endIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + seq.length() - 1 - e);\r\n if (endIndex != null) {\r\n endIndex = endIndex + 1;\r\n offsetEndIndex = e;\r\n break;\r\n }\r\n }\r\n proteinIndex = proteinIndex + seq.length();\r\n if (startIndex != null && endIndex != null && !startIndex.equals(endIndex)) {\r\n CDSSequence cdsSequence = cdsSequenceList.get(i);\r\n String hitLabel = \"\";\r\n if (transcriptSequence.getStrand() == Strand.POSITIVE) {\r\n hitLabel = uniprotBestHit + \"_\" + startIndex + \"_\" + endIndex;\r\n } else {\r\n hitLabel = uniprotBestHit + \"_\" + endIndex + \"_\" + startIndex;\r\n }\r\n int dnaBeginIndex = cdsSequence.getBioBegin() + (3 * offsetStartIndex);\r\n int dnaEndIndex = cdsSequence.getBioEnd() - (3 * offsetEndIndex);\r\n String scaffold = geneSequence.getParentChromosomeSequence().getAccession().getID();\r\n String line = scaffold + \"\\t\" + geneSequence.getSource() + \"_\" + \"UNIPROT\\tmatch\\t\" + dnaBeginIndex + \"\\t\" + dnaEndIndex + \"\\t.\\t\" + transcriptSequence.getStrand().getStringRepresentation() + \"\\t.\\t\";\r\n if (gff3Index == 0) {\r\n FeaturesKeyWordInterface featureKeyWords = proteinSequence.getFeaturesKeyWord();\r\n String notes = \"\";\r\n if (featureKeyWords != null) {\r\n List keyWords = featureKeyWords.getKeyWords();\r\n if (keyWords.size() > 0) {\r\n notes = \";Note=\";\r\n for (String note : keyWords) {\r\n if (note.equals(\"Complete proteome\")) {\r\n continue;\r\n }\r\n if (note.equals(\"Direct protein sequencing\")) {\r\n continue;\r\n }\r\n notes = notes + \" \" + note;\r\n geneSequence.addNote(note);\r\n }\r\n }\r\n }\r\n DatabaseReferenceInterface databaseReferences = proteinSequence.getDatabaseReferences();\r\n if (databaseReferences != null) {\r\n Map> databaseReferenceHashMap = databaseReferences.getDatabaseReferences();\r\n List pfamList = databaseReferenceHashMap.get(\"Pfam\");\r\n List cazyList = databaseReferenceHashMap.get(\"CAZy\");\r\n List goList = databaseReferenceHashMap.get(\"GO\");\r\n List eccList = databaseReferenceHashMap.get(\"BRENDA\");\r\n if (pfamList != null && pfamList.size() > 0) {\r\n if (notes.length() == 0) {\r\n notes = \";Note=\";\r\n }\r\n for (DBReferenceInfo note : pfamList) {\r\n notes = notes + \" \" + note.getId();\r\n geneSequence.addNote(note.getId());\r\n }\r\n }\r\n if (cazyList != null && cazyList.size() > 0) {\r\n if (notes.length() == 0) {\r\n notes = \";Note=\";\r\n }\r\n for (DBReferenceInfo note : cazyList) {\r\n notes = notes + \" \" + note.getId();\r\n geneSequence.addNote(note.getId());\r\n }\r\n }\r\n if (eccList != null && eccList.size() > 0) {\r\n if (notes.length() == 0) {\r\n notes = \";Note=\";\r\n }\r\n for (DBReferenceInfo note : eccList) {\r\n String dbid = note.getId();\r\n dbid = dbid.replace(\".\", \"_\");\r\n notes = notes + \" \" + \"EC:\" + dbid;\r\n geneSequence.addNote(\"EC:\" + dbid);\r\n }\r\n }\r\n if (goList != null && goList.size() > 0) {\r\n if (notes.length() == 0) {\r\n notes = \";Note=\";\r\n }\r\n for (DBReferenceInfo note : goList) {\r\n notes = notes + \" \" + note.getId();\r\n geneSequence.addNote(note.getId());\r\n LinkedHashMap properties = note.getProperties();\r\n for (String propertytype : properties.keySet()) {\r\n if (propertytype.equals(\"evidence\")) {\r\n continue;\r\n }\r\n String property = properties.get(propertytype);\r\n if (property.startsWith(\"C:\")) {\r\n continue;\r\n }\r\n if (property.endsWith(\"...\")) {\r\n property = property.substring(0, property.length() - 3);\r\n }\r\n notes = notes + \" \" + property;\r\n geneSequence.addNote(property);\r\n }\r\n }\r\n }\r\n }\r\n line = line + \"Name=\" + hitLabel + \";Alias=\" + uniprotBestHit + notes + \"\\n\";\r\n } else {\r\n line = line + \"Name=\" + hitLabel + \"\\n\";\r\n }\r\n gff3Index++;\r\n gff3Output.write(line.getBytes());\r\n }\r\n }\r\n }\r\n } catch (Exception e) {\r\n logger.info(\"Accession Id: {}\", accessionid, e);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List splitExpression(String expression){\r\n List tokens = new ArrayList<>();\r\n int lastStart = -1;\r\n boolean isQuoted = false;\r\n for (int i = 0; i < expression.length(); i++) {\r\n if (lastStart == -1) {\r\n if (!isQuoted && Character.isJavaIdentifierStart(expression.charAt(i))) {\r\n lastStart = i;\r\n }\r\n } else if (!Character.isJavaIdentifierPart(expression.charAt(i))) {\r\n tokens.add(expression.subSequence(lastStart, i).toString());\r\n lastStart = -1;\r\n }\r\n if (expression.charAt(i) == '\"' || expression.charAt(i) == '\\'') {\r\n if (i == 0 || expression.charAt(i - 1) != '\\\\') {\r\n isQuoted = !isQuoted;\r\n }\r\n if (isQuoted) {\r\n lastStart = -1;\r\n }\r\n }\r\n }\r\n if (lastStart != -1) {\r\n tokens.add(expression.subSequence(lastStart, expression.length()).toString());\r\n }\r\n return tokens;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Object decode(Class returnType, Object value, TypeResolver resolver){\r\n if (returnType.isArray()) {\r\n int n = Array.getLength(value);\r\n Class targetType = returnType.getComponentType().isAnnotation() ? AnnotationDefinition.class : returnType.getComponentType();\r\n Object ar = java.lang.reflect.Array.newInstance(targetType, n);\r\n for (int j = 0; j < n; j++) {\r\n java.lang.reflect.Array.set(ar, j, decode(returnType.getComponentType(), Array.get(value, j), resolver));\r\n }\r\n return ar;\r\n } else if (returnType.isEnum()) {\r\n if (returnType.isAssignableFrom(value.getClass())) {\r\n return value;\r\n }\r\n try {\r\n String valueStr = value.toString().trim();\r\n if (valueStr.indexOf('.') > 0) {\r\n value = valueStr.substring(valueStr.lastIndexOf(\".\") + 1);\r\n }\r\n return returnType.getMethod(\"valueOf\", String.class).invoke(null, value);\r\n } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {\r\n throw new RuntimeException(e);\r\n }\r\n } else if (String.class.equals(returnType)) {\r\n return unquote(value.toString().trim());\r\n } else if (boolean.class.equals(returnType)) {\r\n return Boolean.valueOf(value.toString());\r\n } else if (int.class.equals(returnType)) {\r\n return Integer.valueOf(value.toString());\r\n } else if (double.class.equals(returnType)) {\r\n return Double.valueOf(value.toString());\r\n } else if (long.class.equals(returnType)) {\r\n return Long.valueOf(value.toString());\r\n } else if (float.class.equals(returnType)) {\r\n return Float.valueOf(value.toString());\r\n } else if (short.class.equals(returnType)) {\r\n return Short.valueOf(value.toString());\r\n } else if (char.class.equals(returnType)) {\r\n return unquote(value.toString()).charAt(0);\r\n } else if (Class.class.equals(returnType)) {\r\n if (value instanceof Class) {\r\n return value;\r\n }\r\n try {\r\n String cName = value.toString().trim().replace(\".class\", \"\");\r\n return resolver.resolveType(cName);\r\n } catch (ClassNotFoundException cnfe) {\r\n LOG.error(\"Exception\", cnfe);\r\n return Object.class;\r\n }\r\n } else if (returnType.isAnnotation()) {\r\n try {\r\n return build(returnType, ((Supplier>) value).get(), resolver);\r\n } catch (NoSuchMethodException e) {\r\n LOG.error(\"Exception\", e);\r\n return null;\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SqlValidatorFixture assertFieldOrigin(Matcher matcher){\r\n tester.validateAndThen(factory, toSql(false), (sap, validator, n) -> {\r\n final List> list = validator.getFieldOrigins(n);\r\n final StringBuilder buf = new StringBuilder(\"{\");\r\n int i = 0;\r\n for (List strings : list) {\r\n if (i++ > 0) {\r\n buf.append(\", \");\r\n }\r\n if (strings == null) {\r\n buf.append(\"null\");\r\n } else {\r\n int j = 0;\r\n for (String s : strings) {\r\n if (j++ > 0) {\r\n buf.append('.');\r\n }\r\n buf.append(s);\r\n }\r\n }\r\n }\r\n buf.append(\"}\");\r\n assertThat(buf, hasToString(matcher));\r\n });\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CompletionStage doExecute(HttpServletRequest req, HttpServletResponse res, HttpConsumer consumer) throws IOException, ServletException{\r\n if (consumer.isSuspended()) {\r\n log.debug(\"Consumer suspended, cannot service request {}\", req);\r\n res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);\r\n return null;\r\n }\r\n if (\"OPTIONS\".equals(req.getMethod()) && !consumer.isOptionsEnabled()) {\r\n String allowedMethods = METHODS.stream().filter(m -> getServletResolveConsumerStrategy().isHttpMethodAllowed(req, m, getConsumers())).collect(Collectors.joining(\",\"));\r\n if (allowedMethods == null && consumer.getEndpoint().getHttpMethodRestrict() != null) {\r\n allowedMethods = consumer.getEndpoint().getHttpMethodRestrict();\r\n }\r\n if (allowedMethods == null) {\r\n allowedMethods = \"GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH\";\r\n }\r\n if (!allowedMethods.contains(\"OPTIONS\")) {\r\n allowedMethods = allowedMethods + \",OPTIONS\";\r\n }\r\n res.addHeader(\"Allow\", allowedMethods);\r\n res.setStatus(HttpServletResponse.SC_OK);\r\n return null;\r\n }\r\n if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(req.getMethod())) {\r\n res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r\n return null;\r\n }\r\n if (\"TRACE\".equals(req.getMethod()) && !consumer.isTraceEnabled()) {\r\n res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r\n return null;\r\n }\r\n Exchange exchange = consumer.createExchange(false);\r\n exchange.setPattern(ExchangePattern.InOut);\r\n if (consumer.getEndpoint().isBridgeEndpoint()) {\r\n exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);\r\n exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE);\r\n }\r\n if (consumer.getEndpoint().isDisableStreamCache()) {\r\n exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);\r\n }\r\n ClassLoader oldTccl = overrideTccl(exchange);\r\n HttpHelper.setCharsetFromContentType(req.getContentType(), exchange);\r\n exchange.setIn(new HttpMessage(exchange, consumer.getEndpoint(), req, res));\r\n String contextPath = consumer.getEndpoint().getPath();\r\n exchange.getIn().setHeader(\"CamelServletContextPath\", contextPath);\r\n String httpPath = (String) exchange.getIn().getHeader(Exchange.HTTP_PATH);\r\n if (contextPath != null && httpPath.startsWith(contextPath)) {\r\n exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length()));\r\n }\r\n try {\r\n consumer.createUoW(exchange);\r\n } catch (Exception e) {\r\n log.error(\"Error processing request\", e);\r\n throw new ServletException(e);\r\n }\r\n boolean isAsync = false;\r\n CompletionStage result = null;\r\n try {\r\n if (log.isTraceEnabled()) {\r\n log.trace(\"Processing request for exchangeId: {}\", exchange.getExchangeId());\r\n }\r\n final Processor processor = consumer.getProcessor();\r\n isAsync = isAsync() && !forceAwait && AsyncProcessor.class.isInstance(processor);\r\n if (isAsync) {\r\n result = AsyncProcessor.class.cast(processor).processAsync(exchange).whenComplete((r, ex) -> {\r\n if (ex != null) {\r\n exchange.setException(ex);\r\n } else {\r\n try {\r\n afterProcess(res, consumer, exchange, false);\r\n } catch (final IOException | ServletException e) {\r\n exchange.setException(e);\r\n }\r\n }\r\n });\r\n } else {\r\n processor.process(exchange);\r\n }\r\n } catch (Exception e) {\r\n exchange.setException(e);\r\n }\r\n try {\r\n if (!isAsync) {\r\n afterProcess(res, consumer, exchange, true);\r\n }\r\n } finally {\r\n restoreTccl(exchange, oldTccl);\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RuleSourceResult getRulesSource(){\r\n boolean hasRuleUnit = !ruleUnits.isEmpty();\r\n CompilationUnit cu = new CompilationUnit();\r\n cu.setPackageDeclaration(name);\r\n manageImportForCompilationUnit(cu);\r\n ClassOrInterfaceDeclaration rulesClass = cu.addClass(rulesFileName);\r\n rulesClass.addImplementedType(Model.class.getCanonicalName());\r\n BodyDeclaration dateFormatter = parseBodyDeclaration(\"public final static java.time.format.DateTimeFormatter \" + DATE_TIME_FORMATTER_FIELD + \" = new java.time.format.DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(org.drools.util.DateUtils.getDateFormatMask()).toFormatter(java.util.Locale.ENGLISH);\\n\");\r\n rulesClass.addMember(dateFormatter);\r\n BodyDeclaration getNameMethod = parseBodyDeclaration(\" @Override\\n\" + \" public String getName() {\\n\" + \" return \\\"\" + name + \"\\\";\\n\" + \" }\\n\");\r\n rulesClass.addMember(getNameMethod);\r\n BodyDeclaration getGlobalsMethod = parseBodyDeclaration(\" @Override\\n\" + \" public java.util.List getGlobals() {\\n\" + \" return globals;\\n\" + \" }\\n\");\r\n rulesClass.addMember(getGlobalsMethod);\r\n BodyDeclaration getTypeMetaDataMethod = parseBodyDeclaration(\" @Override\\n\" + \" public java.util.List getTypeMetaDatas() {\\n\" + \" return typeMetaDatas;\\n\" + \" }\\n\");\r\n rulesClass.addMember(getTypeMetaDataMethod);\r\n for (Map.Entry dateField : dateFields.entrySet()) {\r\n FieldDeclaration f = rulesClass.addField(dateField.getValue().getJPType(), dateField.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());\r\n f.getVariables().get(0).setInitializer(dateField.getValue().getExpression());\r\n }\r\n for (Map.Entry windowReference : windowReferences.entrySet()) {\r\n FieldDeclaration f = rulesClass.addField(WINDOW_REFERENCE_TYPE, windowReference.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());\r\n f.getVariables().get(0).setInitializer(windowReference.getValue());\r\n }\r\n for (Map.Entry queryDef : queryDefWithType.entrySet()) {\r\n FieldDeclaration field = rulesClass.addField(queryDef.getValue().getQueryType(), queryDef.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());\r\n field.getVariables().get(0).setInitializer(queryDef.getValue().getMethodCallExpr());\r\n }\r\n InitializerDeclaration rulesListInitializer = new InitializerDeclaration();\r\n BlockStmt rulesListInitializerBody = new BlockStmt();\r\n rulesListInitializer.setBody(rulesListInitializerBody);\r\n for (Map.Entry g : globals.entrySet()) {\r\n addGlobalField(rulesClass, rulesListInitializerBody, getName(), g.getKey(), g.getValue());\r\n }\r\n rulesClass.addMember(generateListField(\"org.drools.model.Global\", \"globals\", globals.isEmpty() && !hasRuleUnit));\r\n if (!typeMetaDataExpressions.isEmpty()) {\r\n BodyDeclaration typeMetaDatasList = parseBodyDeclaration(\"java.util.List typeMetaDatas = new java.util.ArrayList<>();\");\r\n rulesClass.addMember(typeMetaDatasList);\r\n for (Expression expr : typeMetaDataExpressions) {\r\n addInitStatement(rulesListInitializerBody, expr, \"typeMetaDatas\");\r\n }\r\n } else {\r\n BodyDeclaration typeMetaDatasList = parseBodyDeclaration(\"java.util.List typeMetaDatas = java.util.Collections.emptyList();\");\r\n rulesClass.addMember(typeMetaDatasList);\r\n }\r\n functions.forEach(rulesClass::addMember);\r\n RuleSourceResult results = new RuleSourceResult(cu);\r\n if (hasRuleUnit) {\r\n rulesClass.addModifier(Modifier.Keyword.ABSTRACT);\r\n ruleUnitMembers.forEach((unitName, unitMembers) -> {\r\n String className = rulesFileName + \"_\" + unitName;\r\n ClassOrInterfaceDeclaration unitClass = createCompilationUnit(results).addClass(className);\r\n unitClass.addExtendedType(rulesFileName);\r\n InitializerDeclaration unitInitializer = new InitializerDeclaration();\r\n BlockStmt unitInitializerBody = new BlockStmt();\r\n unitInitializer.setBody(unitInitializerBody);\r\n generateRulesInUnit(unitName, unitMembers, unitInitializerBody, results, unitClass);\r\n unitClass.addMember(generateGetEntryPointsMethod(unitMembers.entryPoints));\r\n for (Map.Entry g : unitMembers.globals.entrySet()) {\r\n addGlobalField(unitClass, unitInitializerBody, getName(), g.getKey(), g.getValue());\r\n }\r\n Set queries = queriesByRuleUnit.get(unitName);\r\n Collection queryNames = queries == null ? Collections.emptyList() : queries.stream().map(QueryModel::getName).map(StringUtil::toId).map(name -> QUERY_METHOD_PREFIX + name).collect(toList());\r\n Collection queryImpls = queryNames.stream().map(queryMethods::get).collect(toList());\r\n generateQueriesInUnit(unitClass, unitInitializerBody, queryNames, queryImpls);\r\n if (!unitInitializerBody.getStatements().isEmpty()) {\r\n unitClass.addMember(unitInitializer);\r\n }\r\n });\r\n } else {\r\n generateRulesInUnit(DEFAULT_RULE_UNIT, ruleUnitMembers.get(DEFAULT_RULE_UNIT), rulesListInitializerBody, results, rulesClass);\r\n generateQueriesInUnit(rulesClass, rulesListInitializerBody, queryMethods.keySet(), queryMethods.values());\r\n rulesClass.addMember(generateGetEntryPointsMethod(entryPoints));\r\n }\r\n if (!rulesListInitializerBody.getStatements().isEmpty()) {\r\n rulesClass.addMember(rulesListInitializer);\r\n }\r\n return results;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static boolean cellValueEquals(final Cell cell, final Cell other){\r\n if (cell != null && other != null && cell.getCellType() == other.getCellType()) {\r\n switch(cell.getCellType()) {\r\n case BLANK:\r\n if (other.getCellType() == CellType.BLANK) {\r\n return true;\r\n }\r\n break;\r\n case BOOLEAN:\r\n if (cell.getBooleanCellValue() == other.getBooleanCellValue()) {\r\n return true;\r\n }\r\n break;\r\n case ERROR:\r\n if (cell.getErrorCellValue() == other.getErrorCellValue()) {\r\n return true;\r\n }\r\n break;\r\n case NUMERIC:\r\n if (cell.getNumericCellValue() == other.getNumericCellValue()) {\r\n return true;\r\n }\r\n break;\r\n case STRING:\r\n if (cell.getStringCellValue().equals(other.getStringCellValue())) {\r\n return true;\r\n }\r\n case FORMULA:\r\n case _NONE:\r\n break;\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void stateMachineStep(){\r\n switch(state) {\r\n case DRAIN:\r\n progTracker.notDone();\r\n if (pendingEntry != null) {\r\n if (!ssWriter.offer(pendingEntry)) {\r\n return;\r\n }\r\n progTracker.madeProgress();\r\n }\r\n pendingEntry = null;\r\n ProgressState result = inboundEdgeStream.drainTo(addToInboxFunction);\r\n if (result.isDone()) {\r\n assert ssWriter.isEmpty() : \"input is done, but we had some entries and not the barrier\";\r\n snapshotContext.storeSnapshotTaskletDone(pendingSnapshotId - 1, isHigherPrioritySource);\r\n state = DONE;\r\n progTracker.reset();\r\n }\r\n progTracker.madeProgress(result.isMadeProgress());\r\n if (hasReachedBarrier) {\r\n state = FLUSH;\r\n stateMachineStep();\r\n }\r\n break;\r\n case FLUSH:\r\n progTracker.notDone();\r\n if (ssWriter.flushAndResetMap()) {\r\n progTracker.madeProgress();\r\n state = REACHED_BARRIER;\r\n }\r\n break;\r\n case REACHED_BARRIER:\r\n if (ssWriter.hasPendingAsyncOps()) {\r\n progTracker.notDone();\r\n return;\r\n }\r\n Throwable error = ssWriter.getError();\r\n if (error != null) {\r\n logger.severe(\"Error writing to snapshot map\", error);\r\n snapshotContext.reportError(error);\r\n }\r\n progTracker.madeProgress();\r\n long bytes = ssWriter.getTotalPayloadBytes();\r\n long keys = ssWriter.getTotalKeys();\r\n long chunks = ssWriter.getTotalChunks();\r\n snapshotContext.phase1DoneForTasklet(bytes, keys, chunks);\r\n metrics.set(new LongLongAccumulator(bytes, keys));\r\n ssWriter.resetStats();\r\n pendingSnapshotId++;\r\n hasReachedBarrier = false;\r\n state = DRAIN;\r\n progTracker.notDone();\r\n break;\r\n default:\r\n throw new JetException(\"Unexpected state: \" + state);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void addGmodGFF3GeneFeatures(LinkedHashMap chromosomeSequenceList, FeatureList listGenes) throws Exception{\r\n FeatureList mRNAFeatures = listGenes.selectByType(\"mRNA\");\r\n LinkedHashMap featureIDHashMap = FeatureHelper.buildFeatureAtrributeIndex(\"ID\", listGenes);\r\n LinkedHashMap featureParentHashMap = FeatureHelper.buildFeatureAtrributeIndex(\"Parent\", listGenes);\r\n for (FeatureI f : mRNAFeatures) {\r\n String geneID;\r\n String geneNote = null;\r\n String geneSource = null;\r\n String sequenceName = null;\r\n ChromosomeSequence seq = null;\r\n GeneSequence geneSequence = null;\r\n Feature mRNAFeature = (Feature) f;\r\n String mRNAID = mRNAFeature.getAttribute(\"ID\");\r\n String mRNAsource = mRNAFeature.source();\r\n String mRNANote = mRNAFeature.getAttribute(\"Note\");\r\n String mRNAParent = mRNAFeature.getAttribute(\"Parent\");\r\n if (mRNAParent != null && mRNAParent.length() > 0) {\r\n FeatureList geneFeatureList = featureIDHashMap.get(mRNAParent);\r\n Feature geneFeature = (Feature) geneFeatureList.get(0);\r\n geneID = geneFeature.getAttribute(\"ID\");\r\n geneNote = geneFeature.getAttribute(\"Note\");\r\n geneSource = geneFeature.source();\r\n sequenceName = geneFeature.seqname();\r\n } else {\r\n geneID = mRNAID;\r\n geneSource = mRNAsource;\r\n sequenceName = mRNAFeature.seqname();\r\n }\r\n seq = chromosomeSequenceList.get(sequenceName);\r\n AccessionID geneAccessionID = new AccessionID(geneID);\r\n FeatureList mRNAChildren = featureParentHashMap.get(mRNAID);\r\n FeatureList cdsFeatures = mRNAChildren.selectByType(\"CDS\");\r\n FeatureI feature = cdsFeatures.get(0);\r\n Strand strand = Strand.POSITIVE;\r\n if (feature.location().isNegative()) {\r\n strand = Strand.NEGATIVE;\r\n }\r\n cdsFeatures = cdsFeatures.sortByStart();\r\n FeatureI startCodon = null;\r\n FeatureI stopCodon = null;\r\n Integer startCodonBegin = null;\r\n Integer stopCodonEnd = null;\r\n String startCodonName = \"\";\r\n String stopCodonName = \"\";\r\n FeatureList startCodonList = mRNAChildren.selectByType(\"five_prime_UTR\");\r\n if (startCodonList != null && startCodonList.size() > 0) {\r\n startCodon = startCodonList.get(0);\r\n if (strand == Strand.NEGATIVE) {\r\n startCodonBegin = startCodon.location().bioEnd();\r\n } else {\r\n startCodonBegin = startCodon.location().bioStart();\r\n }\r\n startCodonName = startCodon.getAttribute(\"ID\");\r\n }\r\n FeatureList stopCodonList = mRNAChildren.selectByType(\"three_prime_UTR\");\r\n if (stopCodonList != null && stopCodonList.size() > 0) {\r\n stopCodon = stopCodonList.get(0);\r\n if (strand == Strand.NEGATIVE) {\r\n stopCodonEnd = stopCodon.location().bioStart();\r\n } else {\r\n stopCodonEnd = stopCodon.location().bioEnd();\r\n }\r\n stopCodonName = stopCodon.getAttribute(\"ID\");\r\n }\r\n if (startCodonBegin == null) {\r\n if (strand == Strand.NEGATIVE) {\r\n FeatureI firstFeature = cdsFeatures.get(0);\r\n startCodonBegin = firstFeature.location().bioEnd();\r\n } else {\r\n FeatureI firstFeature = cdsFeatures.get(0);\r\n startCodonBegin = firstFeature.location().bioStart();\r\n }\r\n }\r\n if (stopCodonEnd == null) {\r\n if (strand == Strand.NEGATIVE) {\r\n FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);\r\n stopCodonEnd = lastFeature.location().bioStart();\r\n } else {\r\n FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);\r\n stopCodonEnd = lastFeature.location().bioEnd();\r\n }\r\n }\r\n if (startCodonBegin > stopCodonEnd) {\r\n int temp = startCodonBegin;\r\n startCodonBegin = stopCodonEnd;\r\n stopCodonEnd = temp;\r\n }\r\n AccessionID transcriptAccessionID = new AccessionID(mRNAID);\r\n geneSequence = seq.getGene(geneID);\r\n if (geneSequence == null) {\r\n geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);\r\n geneSequence.setSource(geneSource);\r\n if (geneNote != null && geneNote.length() > 0) {\r\n geneSequence.addNote(geneNote);\r\n }\r\n } else {\r\n if (startCodonBegin < geneSequence.getBioBegin()) {\r\n geneSequence.setBioBegin(startCodonBegin);\r\n }\r\n if (stopCodonEnd > geneSequence.getBioBegin()) {\r\n geneSequence.setBioEnd(stopCodonEnd);\r\n }\r\n }\r\n TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);\r\n transcriptSequence.setSource(mRNAsource);\r\n if (mRNANote != null && mRNANote.length() > 0) {\r\n transcriptSequence.addNote(mRNANote);\r\n }\r\n if (startCodon != null) {\r\n if (startCodonName == null || startCodonName.length() == 0) {\r\n startCodonName = mRNAID + \"-start_codon-\" + startCodon.location().bioStart() + \"-\" + startCodon.location().bioEnd();\r\n }\r\n transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());\r\n }\r\n if (stopCodon != null) {\r\n if (stopCodonName == null || stopCodonName.length() == 0) {\r\n stopCodonName = mRNAID + \"-stop_codon-\" + stopCodon.location().bioStart() + \"-\" + stopCodon.location().bioEnd();\r\n }\r\n transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());\r\n }\r\n for (FeatureI cdsFeature : cdsFeatures) {\r\n Feature cds = (Feature) cdsFeature;\r\n String cdsNote = cdsFeature.getAttribute(\"Note\");\r\n String cdsSource = cds.source();\r\n String cdsName = cds.getAttribute(\"ID\");\r\n if (cdsName == null || cdsName.length() == 0) {\r\n cdsName = mRNAID + \"-cds-\" + cds.location().bioStart() + \"-\" + cds.location().bioEnd();\r\n }\r\n AccessionID cdsAccessionID = new AccessionID(cdsName);\r\n ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());\r\n exonSequence.setSource(cdsSource);\r\n if (cdsNote != null && cdsNote.length() > 0) {\r\n exonSequence.addNote(cdsNote);\r\n }\r\n transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());\r\n }\r\n geneSequence.addIntronsUsingExons();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean forceEvictAndRun0(MapOperation mapOperation, double evictionPercentage, Runnable runnable){\r\n assert evictionPercentage > 0 && evictionPercentage <= 1;\r\n int partitionCount = numberOfPartitions(mapOperation);\r\n int threadCount = threadCount(mapOperation);\r\n int mod = mod(mapOperation, threadCount);\r\n ILogger logger = mapOperation.logger();\r\n int evictionRetryTimes = retryCount(evictionPercentage);\r\n for (int i = 0; i < evictionRetryTimes; i++) {\r\n try {\r\n for (int partitionId = 0; partitionId < partitionCount; partitionId++) {\r\n if ((partitionId % threadCount) != mod) {\r\n continue;\r\n }\r\n Collection recordStores = partitionMaps(mapOperation, partitionId).values();\r\n for (RecordStore recordStore : recordStores) {\r\n int sizeBeforeEviction = recordStore.size();\r\n MapContainer mapContainer = recordStore.getMapContainer();\r\n Evictor evictor = mapContainer.getEvictor();\r\n evictor.forceEvictByPercentage(recordStore, evictionPercentage);\r\n if (logger.isFineEnabled()) {\r\n logForcedEviction(logger, mapOperation, recordStore, evictionPercentage, (i + 1), sizeBeforeEviction);\r\n }\r\n }\r\n }\r\n if (runnable != null) {\r\n runnable.run();\r\n } else {\r\n mapOperation.runInternal();\r\n }\r\n return true;\r\n } catch (NativeOutOfMemoryError e) {\r\n if (evictionPercentage == 1D) {\r\n throw e;\r\n } else {\r\n ignore(e);\r\n }\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String replaceEscapedChars(String input) throws MalformedUnicodeEscape{\r\n final int length = input.length();\r\n if (length <= 1) {\r\n return input;\r\n }\r\n final StringBuilder builder = new StringBuilder(length);\r\n int endIdx;\r\n for (int i = 0; i < length; i++) {\r\n char currentChar = input.charAt(i);\r\n if (currentChar == '\\\\' && i + 1 < length) {\r\n char nextChar = input.charAt(i + 1);\r\n switch(nextChar) {\r\n case 'b':\r\n builder.append('\\b');\r\n i++;\r\n break;\r\n case 'f':\r\n builder.append('\\f');\r\n i++;\r\n break;\r\n case 'n':\r\n builder.append('\\n');\r\n i++;\r\n break;\r\n case 'r':\r\n builder.append('\\r');\r\n i++;\r\n break;\r\n case 't':\r\n builder.append('\\t');\r\n i++;\r\n break;\r\n case '\\\\':\r\n case '\\'':\r\n builder.append(nextChar);\r\n i++;\r\n break;\r\n case 'u':\r\n case 'U':\r\n final int charsToConsume = (nextChar == 'u') ? 4 : 8;\r\n if (i + 1 + charsToConsume >= length) {\r\n throw new MalformedUnicodeEscape(i);\r\n }\r\n endIdx = calculateMaxCharsInSequence(input, i + 2, charsToConsume, SqlParserUtil::isHexDigit);\r\n if (endIdx != i + 2 + charsToConsume) {\r\n throw new MalformedUnicodeEscape(i);\r\n }\r\n builder.appendCodePoint(parseInt(input.substring(i + 2, endIdx), 16));\r\n i = endIdx - 1;\r\n break;\r\n case 'x':\r\n endIdx = calculateMaxCharsInSequence(input, i + 2, 2, SqlParserUtil::isHexDigit);\r\n if (endIdx > i + 2) {\r\n builder.appendCodePoint(parseInt(input.substring(i + 2, endIdx), 16));\r\n i = endIdx - 1;\r\n } else {\r\n builder.append(nextChar);\r\n i++;\r\n }\r\n break;\r\n case '0':\r\n case '1':\r\n case '2':\r\n case '3':\r\n endIdx = calculateMaxCharsInSequence(input, i + 2, 2, SqlParserUtil::isOctalDigit);\r\n builder.appendCodePoint(parseInt(input.substring(i + 1, endIdx), 8));\r\n i = endIdx - 1;\r\n break;\r\n default:\r\n builder.append(currentChar);\r\n }\r\n } else {\r\n builder.append(currentChar);\r\n }\r\n }\r\n return builder.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void process(String uniprotDatFileName, String fastaFileName) throws Exception{\r\n FileReader fr = new FileReader(uniprotDatFileName);\r\n BufferedReader br = new BufferedReader(fr);\r\n String line = br.readLine();\r\n String id = \"\";\r\n StringBuffer sequence = new StringBuffer();\r\n ArrayList seqCodingRegionsList = new ArrayList();\r\n int count = 0;\r\n HashMap uniqueGenes = new HashMap();\r\n HashMap uniqueSpecies = new HashMap();\r\n while (line != null) {\r\n if (line.startsWith(\"ID\")) {\r\n String[] data = line.split(\" \");\r\n id = data[3];\r\n } else if (line.startsWith(\"SQ\")) {\r\n line = br.readLine();\r\n while (!line.startsWith(\"//\")) {\r\n for (int i = 0; i < line.length(); i++) {\r\n char aa = line.charAt(i);\r\n if ((aa >= 'A' && aa <= 'Z') || (aa >= 'a' && aa <= 'z')) {\r\n sequence.append(aa);\r\n }\r\n }\r\n line = br.readLine();\r\n }\r\n ProteinSequence seq = new ProteinSequence(sequence.toString());\r\n seq.setAccession(new AccessionID(id));\r\n seqCodingRegionsList.add(seq);\r\n sequence = new StringBuffer();\r\n count++;\r\n if (count % 100 == 0)\r\n logger.info(\"Count: \", count);\r\n String[] parts = id.split(\"_\");\r\n uniqueGenes.put(parts[0], \"\");\r\n uniqueSpecies.put(parts[1], \"\");\r\n }\r\n line = br.readLine();\r\n }\r\n FastaWriterHelper.writeProteinSequence(new File(fastaFileName), seqCodingRegionsList);\r\n br.close();\r\n fr.close();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static XMLStreamReader newXMLStreamReader(final InputStream is, final Set elementsToSkip) throws XMLStreamException{\r\n XMLInputFactory factory = getSecureXmlInputFactory();\r\n XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(is);\r\n if (elementsToSkip.size() == 0) {\r\n return xmlStreamReader;\r\n } else {\r\n XMLStreamReader fileteredStreamReader = factory.createFilteredReader(xmlStreamReader, new StreamFilter() {\r\n\r\n private boolean accept = true;\r\n\r\n private QName rootSkipStart = null;\r\n\r\n @Override\r\n public boolean accept(XMLStreamReader reader) {\r\n if (reader.isStartElement() && accept && elementsToSkip.contains(reader.getName())) {\r\n if (rootSkipStart == null) {\r\n rootSkipStart = reader.getName();\r\n }\r\n accept = false;\r\n return false;\r\n } else if (reader.isEndElement() && !accept && elementsToSkip.contains(reader.getName())) {\r\n if (rootSkipStart.equals(reader.getName())) {\r\n rootSkipStart = null;\r\n accept = true;\r\n return false;\r\n }\r\n }\r\n return accept;\r\n }\r\n });\r\n return fileteredStreamReader;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean isSimplePredicate(Node node){\r\n Node parent = node.getParentNode();\r\n if (parent == null) {\r\n return false;\r\n }\r\n String name = parent.getNodeName();\r\n if (name == null) {\r\n return false;\r\n }\r\n if (name.equals(\"completionPredicate\") || name.equals(\"completion\")) {\r\n return true;\r\n }\r\n if (name.equals(\"onWhen\") || name.equals(\"when\") || name.equals(\"handled\") || name.equals(\"continued\")) {\r\n return true;\r\n }\r\n if (name.equals(\"retryWhile\") || name.equals(\"filter\") || name.equals(\"validate\")) {\r\n return true;\r\n }\r\n if (name.equals(\"loop\")) {\r\n String doWhile = null;\r\n if (parent.getAttributes() != null) {\r\n Node attr = parent.getAttributes().getNamedItem(\"doWhile\");\r\n if (attr != null) {\r\n doWhile = attr.getTextContent();\r\n }\r\n }\r\n if (\"true\".equalsIgnoreCase(doWhile)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List unquoteTokens(List result, List separators, String quote){\r\n StringBuilder current = new StringBuilder();\r\n boolean inProgress = false;\r\n List answer = new ArrayList<>();\r\n int idxSeparator = 0;\r\n for (String s : result) {\r\n boolean canStart = false;\r\n boolean canClose = false;\r\n boolean cutStart = false;\r\n boolean cutEnd = false;\r\n if (s.startsWith(quote)) {\r\n if (s.length() == 1) {\r\n s = \"\";\r\n if (inProgress) {\r\n canClose = true;\r\n } else {\r\n canStart = true;\r\n }\r\n } else {\r\n cutStart = true;\r\n canStart = true;\r\n }\r\n }\r\n if (s.endsWith(quote)) {\r\n cutEnd = true;\r\n canClose = true;\r\n }\r\n if (cutEnd || cutStart) {\r\n s = s.substring(cutStart ? 1 : 0, cutEnd ? s.length() - 1 : s.length());\r\n }\r\n if (inProgress) {\r\n current.append(separators.get(idxSeparator));\r\n current.append(s);\r\n if (canClose) {\r\n answer.add(current.toString());\r\n current.setLength(0);\r\n inProgress = false;\r\n }\r\n } else {\r\n if (canStart && !canClose) {\r\n current.append(s);\r\n inProgress = true;\r\n } else {\r\n answer.add(s);\r\n }\r\n }\r\n idxSeparator++;\r\n }\r\n if (current.length() > 0) {\r\n answer.add(current.toString());\r\n current.setLength(0);\r\n }\r\n return answer;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void clearTablesCreatedDuringTests() throws Exception{\r\n if (System.getenv(QTEST_LEAVE_FILES) != null) {\r\n return;\r\n }\r\n conf.set(\"hive.metastore.filter.hook\", \"org.apache.hadoop.hive.metastore.DefaultMetaStoreFilterHookImpl\");\r\n db = Hive.get(conf);\r\n for (String dbName : db.getAllDatabases()) {\r\n SessionState.get().setCurrentDatabase(dbName);\r\n for (String tblName : db.getAllTables()) {\r\n Table tblObj = null;\r\n try {\r\n tblObj = db.getTable(tblName);\r\n } catch (InvalidTableException e) {\r\n LOG.warn(\"Trying to drop table \" + e.getTableName() + \". But it does not exist.\");\r\n continue;\r\n }\r\n if (!tblObj.isMaterializedView()) {\r\n continue;\r\n }\r\n db.dropTable(dbName, tblName, true, true, fsType == FsType.ENCRYPTED_HDFS);\r\n HiveMaterializedViewsRegistry.get().dropMaterializedView(tblObj.getDbName(), tblObj.getTableName());\r\n }\r\n }\r\n for (String dbName : db.getAllDatabases()) {\r\n SessionState.get().setCurrentDatabase(dbName);\r\n if (dbName.equalsIgnoreCase(\"tpch_0_001\")) {\r\n continue;\r\n }\r\n for (String tblName : db.getAllTables()) {\r\n if (!DEFAULT_DATABASE_NAME.equals(dbName) || !QTestDatasetHandler.isSourceTable(tblName)) {\r\n try {\r\n db.getTable(tblName);\r\n } catch (InvalidTableException e) {\r\n LOG.warn(\"Trying to drop table \" + e.getTableName() + \". But it does not exist.\");\r\n continue;\r\n }\r\n db.dropTable(dbName, tblName, true, true, miniClusters.fsNeedsPurge(fsType));\r\n }\r\n }\r\n if (!DEFAULT_DATABASE_NAME.equals(dbName)) {\r\n db.dropDatabase(dbName, true, true, true);\r\n }\r\n }\r\n try {\r\n Path p = new Path(testWarehouse);\r\n FileSystem fileSystem = p.getFileSystem(conf);\r\n if (fileSystem.exists(p)) {\r\n for (FileStatus status : fileSystem.listStatus(p)) {\r\n if (status.isDirectory() && !QTestDatasetHandler.isSourceTable(status.getPath().getName())) {\r\n fileSystem.delete(status.getPath(), true);\r\n }\r\n }\r\n }\r\n } catch (IllegalArgumentException e) {\r\n }\r\n SessionState.get().setCurrentDatabase(DEFAULT_DATABASE_NAME);\r\n List roleNames = db.getAllRoleNames();\r\n for (String roleName : roleNames) {\r\n if (!\"PUBLIC\".equalsIgnoreCase(roleName) && !\"ADMIN\".equalsIgnoreCase(roleName)) {\r\n db.dropRole(roleName);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static A getAnnotation(final Method method, final Class annotationCls, final boolean searchSupers, final boolean ignoreAccess){\r\n Objects.requireNonNull(method, \"method\");\r\n Objects.requireNonNull(annotationCls, \"annotationCls\");\r\n if (!ignoreAccess && !MemberUtils.isAccessible(method)) {\r\n return null;\r\n }\r\n A annotation = method.getAnnotation(annotationCls);\r\n if (annotation == null && searchSupers) {\r\n final Class mcls = method.getDeclaringClass();\r\n final List> classes = getAllSuperclassesAndInterfaces(mcls);\r\n for (final Class acls : classes) {\r\n final Method equivalentMethod = ignoreAccess ? MethodUtils.getMatchingMethod(acls, method.getName(), method.getParameterTypes()) : MethodUtils.getMatchingAccessibleMethod(acls, method.getName(), method.getParameterTypes());\r\n if (equivalentMethod != null) {\r\n annotation = equivalentMethod.getAnnotation(annotationCls);\r\n if (annotation != null) {\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return annotation;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static EmblRecord process(File file) throws IOException{\r\n EmblRecord emblRecord = new EmblRecord();\r\n StringBuilder sequence = new StringBuilder(\"\");\r\n LinkedList emblReferences = new LinkedList<>();\r\n EmblReference emblReference = new EmblReference();\r\n LinkedList accessionNumber = new LinkedList<>();\r\n LinkedList keyword = new LinkedList<>();\r\n if (file == null)\r\n throw new NullPointerException(\"file can't be null\");\r\n if (file.isDirectory())\r\n throw new IllegalArgumentException(\"the file can't be a directory\");\r\n try (FileReader fileReader = new FileReader(file)) {\r\n String line = \"\";\r\n String lineIdentifier;\r\n String lineInfo;\r\n try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {\r\n while ((line = bufferedReader.readLine()) != null) {\r\n if (line.length() > 1) {\r\n lineInfo = line.substring(2, line.length()).trim();\r\n lineIdentifier = line.substring(0, 2);\r\n if (lineIdentifier.equals(\"ID\"))\r\n emblRecord.setEmblId(populateID(lineInfo));\r\n else if (lineIdentifier.equals(\"AC\"))\r\n populateAccessionNumber(line, accessionNumber);\r\n else if (lineIdentifier.equals(\"DT\") && line.contains(\"Created\"))\r\n emblRecord.setCreatedDate(lineInfo);\r\n else if (lineIdentifier.equals(\"DT\") && line.contains(\"updated\"))\r\n emblRecord.setLastUpdatedDate(lineInfo);\r\n else if (lineIdentifier.equals(\"DE\"))\r\n emblRecord.setSequenceDescription(lineInfo);\r\n else if (lineIdentifier.equals(\"KW\"))\r\n keyword.add(lineInfo);\r\n else if (lineIdentifier.equals(\"OS\"))\r\n emblRecord.setOrganismSpecies(lineInfo);\r\n else if (lineIdentifier.equals(\"OC\"))\r\n emblRecord.setOrganismClassification(lineInfo);\r\n else if (lineIdentifier.equals(\"OG\"))\r\n emblRecord.setOrGanelle(lineInfo);\r\n else if (lineIdentifier.equals(\"RN\") || lineIdentifier.equals(\"RP\") || lineIdentifier.equals(\"RX\") || lineIdentifier.equals(\"RG\") || lineIdentifier.equals(\"RA\") || lineIdentifier.equals(\"RT\") || lineIdentifier.equals(\"RL\"))\r\n populateEmblReferences(lineIdentifier, lineInfo, emblReference, emblReferences);\r\n else if (lineIdentifier.equals(\"DR\"))\r\n emblRecord.setDatabaseCrossReference(lineInfo);\r\n else if (lineIdentifier.equals(\"AH\"))\r\n emblRecord.setAssemblyHeader(lineInfo);\r\n else if (lineIdentifier.equals(\"AS\"))\r\n emblRecord.setAssemblyInformation(lineInfo);\r\n else if (lineIdentifier.equals(\"CO\"))\r\n emblRecord.setConstructedSequence(lineInfo);\r\n else if (lineIdentifier.equals(\"FH\"))\r\n emblRecord.setFeatureHeader(lineInfo);\r\n else if (lineIdentifier.equals(\"FT\"))\r\n emblRecord.setFeatureTable(lineInfo);\r\n else if (lineIdentifier.equals(\"SQ\"))\r\n emblRecord.setSequenceHeader(lineInfo);\r\n else if (lineIdentifier.equals(\" \") && !lineIdentifier.equals(\"//\"))\r\n populateSequence(line, sequence);\r\n else if (lineIdentifier.equals(\"//\")) {\r\n emblRecord.setKeyword(keyword);\r\n emblRecord.setEmblReference(emblReferences);\r\n emblRecord.setAccessionNumber(accessionNumber);\r\n emblRecord.setSequence(sequence.toString());\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return emblRecord;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void putAgentProperties(Annotation annotation, JsonLdPropertyValue propertyValue){\r\n EdmAgent agentBody = (EdmAgent) ((EdmAgentBody) annotation.getBody()).getAgent();\r\n if (agentBody != null) {\r\n if (agentBody.getPrefLabel() != null && !StringUtils.isBlank(agentBody.getPrefLabel().toString()))\r\n addMapToPropertyValue(agentBody.getPrefLabel(), propertyValue, WebAnnotationFields.PREF_LABEL);\r\n if (agentBody.getPlaceOfBirth() != null && !StringUtils.isBlank(agentBody.getPlaceOfBirth().toString()))\r\n addMapToPropertyValue(agentBody.getPlaceOfBirth(), propertyValue, WebAnnotationFields.PLACE_OF_BIRTH);\r\n if (agentBody.getPlaceOfDeath() != null && !StringUtils.isBlank(agentBody.getPlaceOfDeath().toString()))\r\n addMapToPropertyValue(agentBody.getPlaceOfDeath(), propertyValue, WebAnnotationFields.PLACE_OF_DEATH);\r\n if (agentBody.getDateOfBirth() != null && !StringUtils.isBlank(agentBody.getDateOfBirth().toString()))\r\n addListToPropertyValue(agentBody.getDateOfBirth(), propertyValue, WebAnnotationFields.DATE_OF_BIRTH);\r\n if (agentBody.getDateOfDeath() != null && !StringUtils.isBlank(agentBody.getDateOfDeath().toString()))\r\n addListToPropertyValue(agentBody.getDateOfDeath(), propertyValue, WebAnnotationFields.DATE_OF_DEATH);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String findLocalIpAddress() throws IOException{\r\n String defaultIpOverride = System.getenv(\"CALCITE_LOCAL_IP\");\r\n if (defaultIpOverride != null) {\r\n return defaultIpOverride;\r\n } else {\r\n final InetAddress address = InetAddress.getLocalHost();\r\n if (address.isLoopbackAddress()) {\r\n for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {\r\n for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {\r\n final InetAddress addr = interfaceAddress.getAddress();\r\n if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr instanceof Inet4Address) {\r\n logWarning(\"Your hostname, \" + InetAddress.getLocalHost().getHostName() + \" resolves to a loopback address: \" + address.getHostAddress() + \"; using \" + addr.getHostAddress() + \" instead (on interface \" + ni.getName() + \")\");\r\n logWarning(\"Set CALCITE_LOCAL_IP if you need to bind to another address\");\r\n return addr.getHostAddress();\r\n }\r\n }\r\n }\r\n logWarning(\"Your hostname, \" + InetAddress.getLocalHost().getHostName() + \" resolves to a loopback address: \" + address.getHostAddress() + \", but we couldn't find any external IP address!\");\r\n logWarning(\"Set CALCITE_LOCAL_IP if you need to bind to another address\");\r\n }\r\n return address.getHostAddress();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void printMultiLine(StringBuffer buf, String lineStart, String data, char breakChar){\r\n if (lineStart.length() != 9)\r\n logger.info(\"lineStart != 9, there will be problems :\" + lineStart);\r\n if (data.length() < 58) {\r\n buf.append(lineStart);\r\n buf.append(\" \");\r\n buf.append(data);\r\n buf.append(newline);\r\n return;\r\n }\r\n String thisLine = \"\";\r\n int count = 1;\r\n while (data.length() > 57) {\r\n boolean charFound = false;\r\n for (int i = 57; i > -1; i--) {\r\n char c = data.charAt(i);\r\n if (c == breakChar) {\r\n thisLine = data.substring(0, i + 1);\r\n if (i == 0)\r\n i++;\r\n data = data.substring(i);\r\n charFound = true;\r\n break;\r\n }\r\n }\r\n if (!charFound) {\r\n thisLine = data.substring(0, 58);\r\n data = data.substring(57);\r\n }\r\n if ((breakChar == ',') && (data.charAt(0) == ',')) {\r\n data = data.substring(1);\r\n }\r\n buf.append(lineStart);\r\n if (count > 1) {\r\n buf.append(count);\r\n if (breakChar != ' ')\r\n buf.append(\" \");\r\n } else\r\n buf.append(\" \");\r\n buf.append(thisLine);\r\n int l = thisLine.length() + 10;\r\n while (l < 67) {\r\n l++;\r\n buf.append(\" \");\r\n }\r\n buf.append(newline);\r\n count++;\r\n }\r\n if (!data.trim().isEmpty()) {\r\n buf.append(lineStart);\r\n buf.append(count);\r\n int filledLeft = 10;\r\n if (breakChar != ' ') {\r\n buf.append(\" \");\r\n filledLeft++;\r\n }\r\n buf.append(data);\r\n int l = data.length() + filledLeft;\r\n fillLine(buf, l);\r\n buf.append(newline);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Result deprovision(final MatchingRule matchingRule, final SyncDelta delta, final List matches, final Provision provision) throws JobExecutionException{\r\n if (!profile.getTask().isPerformUpdate()) {\r\n LOG.debug(\"PullTask not configured for update\");\r\n end(provision.getAnyType(), MatchingRule.toEventName(matchingRule), Result.SUCCESS, null, null, delta);\r\n return Result.SUCCESS;\r\n }\r\n LOG.debug(\"About to deprovision {}\", matches);\r\n Result global = Result.SUCCESS;\r\n for (PullMatch match : matches) {\r\n LOG.debug(\"About to unassign resource {}\", match);\r\n ProvisioningReport result = new ProvisioningReport();\r\n result.setOperation(ResourceOperation.DELETE);\r\n result.setAnyType(provision.getAnyType());\r\n result.setStatus(ProvisioningReport.Status.SUCCESS);\r\n result.setKey(match.getAny().getKey());\r\n result.setUidValue(delta.getUid().getUidValue());\r\n AnyTO before = getAnyTO(match.getAny());\r\n if (before == null) {\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(String.format(\"Any '%s(%s)' not found\", provision.getAnyType(), match));\r\n }\r\n if (!profile.isDryRun()) {\r\n Object output;\r\n Result resultStatus;\r\n if (before == null) {\r\n resultStatus = Result.FAILURE;\r\n output = null;\r\n } else {\r\n result.setName(getName(before));\r\n try {\r\n if (matchingRule == MatchingRule.UNASSIGN) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeUnassign(profile, delta, before);\r\n }\r\n } else if (matchingRule == MatchingRule.DEPROVISION) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeDeprovision(profile, delta, before);\r\n }\r\n }\r\n PropagationByResource propByRes = new PropagationByResource<>();\r\n propByRes.add(ResourceOperation.DELETE, profile.getTask().getResource().getKey());\r\n taskExecutor.execute(propagationManager.getDeleteTasks(match.getAny().getType().getKind(), match.getAny().getKey(), propByRes, null, null), false, securityProperties.getAdminUser());\r\n AnyUR anyUR = null;\r\n if (matchingRule == MatchingRule.UNASSIGN) {\r\n anyUR = getAnyUtils().newAnyUR(match.getAny().getKey());\r\n anyUR.getResources().add(new StringPatchItem.Builder().operation(PatchOperation.DELETE).value(profile.getTask().getResource().getKey()).build());\r\n }\r\n if (anyUR == null) {\r\n output = getAnyTO(match.getAny());\r\n } else {\r\n output = doUpdate(before, anyUR, delta, result);\r\n }\r\n for (PullActions action : profile.getActions()) {\r\n action.after(profile, delta, AnyTO.class.cast(output), result);\r\n }\r\n resultStatus = Result.SUCCESS;\r\n LOG.debug(\"{} {} successfully updated\", provision.getAnyType(), match);\r\n } catch (PropagationException e) {\r\n LOG.error(\"Could not propagate {} {}\", provision.getAnyType(), delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not update {} {}\", provision.getAnyType(), delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n }\r\n }\r\n end(provision.getAnyType(), MatchingRule.toEventName(matchingRule), resultStatus, before, output, delta);\r\n global = and(global, resultStatus);\r\n }\r\n profile.getResults().add(result);\r\n }\r\n return global;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic RexNode visitCall(RexCall call){\r\n final SqlOperator op = call.getOperator();\r\n if (!(op instanceof SqlAggFunction)) {\r\n return super.visitCall(call);\r\n }\r\n final SqlAggFunction aggOp = (SqlAggFunction) op;\r\n final RelDataType type = call.getType();\r\n List exprs = call.getOperands();\r\n SqlFunction histogramOp = !ENABLE_HISTOGRAM_AGG ? null : getHistogramOp(aggOp);\r\n if (histogramOp != null) {\r\n final RelDataType histogramType = computeHistogramType(type);\r\n boolean reinterpretCast = type.getSqlTypeName() == SqlTypeName.DECIMAL;\r\n if (histogramType != type) {\r\n exprs = new ArrayList<>(exprs);\r\n exprs.set(0, reinterpretCast ? rexBuilder.makeReinterpretCast(histogramType, exprs.get(0), rexBuilder.makeLiteral(false)) : rexBuilder.makeCast(histogramType, exprs.get(0)));\r\n }\r\n RexNode over = relBuilder.aggregateCall(SqlStdOperatorTable.HISTOGRAM_AGG, exprs).distinct(distinct).ignoreNulls(ignoreNulls).over().partitionBy(partitionKeys).orderBy(orderKeys).let(c -> rows ? c.rowsBetween(lowerBound, upperBound) : c.rangeBetween(lowerBound, upperBound)).allowPartial(allowPartial).toRex();\r\n RexNode histogramCall = rexBuilder.makeCall(histogramType, histogramOp, ImmutableList.of(over));\r\n if (histogramType != type) {\r\n if (reinterpretCast) {\r\n histogramCall = rexBuilder.makeReinterpretCast(type, histogramCall, rexBuilder.makeLiteral(false));\r\n } else {\r\n histogramCall = rexBuilder.makeCast(type, histogramCall);\r\n }\r\n }\r\n return histogramCall;\r\n } else {\r\n boolean needSum0 = aggOp == SqlStdOperatorTable.SUM && type.isNullable();\r\n SqlAggFunction aggOpToUse = needSum0 ? SqlStdOperatorTable.SUM0 : aggOp;\r\n return relBuilder.aggregateCall(aggOpToUse, exprs).distinct(distinct).ignoreNulls(ignoreNulls).over().partitionBy(partitionKeys).orderBy(orderKeys).let(c -> rows ? c.rowsBetween(lowerBound, upperBound) : c.rangeBetween(lowerBound, upperBound)).allowPartial(allowPartial).nullWhenCountZero(needSum0).toRex();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " AnnotationDescr doNormalize(AnnotationDescr annotationDescr){\r\n Class annotationClass = null;\r\n try {\r\n annotationClass = typeResolver.resolveType(annotationDescr.getName(), TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);\r\n } catch (ClassNotFoundException | NoClassDefFoundError e) {\r\n String className = normalizeAnnotationNonStrictName(annotationDescr.getName());\r\n try {\r\n annotationClass = typeResolver.resolveType(className, TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);\r\n } catch (ClassNotFoundException | NoClassDefFoundError e1) {\r\n }\r\n }\r\n if (annotationClass != null) {\r\n annotationDescr.setFullyQualifiedName(annotationClass.getCanonicalName());\r\n for (String key : annotationDescr.getValueMap().keySet()) {\r\n try {\r\n Method m = annotationClass.getMethod(key);\r\n Object val = annotationDescr.getValue(key);\r\n if (val instanceof Object[] && !m.getReturnType().isArray()) {\r\n this.results.add(new AnnotationDeclarationError(annotationDescr, \"Wrong cardinality on property \" + key));\r\n return annotationDescr;\r\n }\r\n if (m.getReturnType().isArray() && !(val instanceof Object[])) {\r\n val = new Object[] { val };\r\n annotationDescr.setKeyValue(key, val);\r\n }\r\n if (m.getReturnType().isArray()) {\r\n int n = Array.getLength(val);\r\n for (int j = 0; j < n; j++) {\r\n if (Class.class.equals(m.getReturnType().getComponentType())) {\r\n String className = Array.get(val, j).toString().replace(\".class\", \"\");\r\n Array.set(val, j, typeResolver.resolveType(className).getName() + \".class\");\r\n } else if (m.getReturnType().getComponentType().isAnnotation()) {\r\n Array.set(val, j, doNormalize((AnnotationDescr) Array.get(val, j)));\r\n }\r\n }\r\n } else {\r\n if (Class.class.equals(m.getReturnType())) {\r\n String className = annotationDescr.getValueAsString(key).replace(\".class\", \"\");\r\n annotationDescr.setKeyValue(key, typeResolver.resolveType(className));\r\n } else if (m.getReturnType().isAnnotation()) {\r\n annotationDescr.setKeyValue(key, doNormalize((AnnotationDescr) annotationDescr.getValue(key)));\r\n }\r\n }\r\n } catch (NoSuchMethodException e) {\r\n this.results.add(new AnnotationDeclarationError(annotationDescr, \"Unknown annotation property \" + key));\r\n } catch (ClassNotFoundException | NoClassDefFoundError e) {\r\n this.results.add(new AnnotationDeclarationError(annotationDescr, \"Unknown class \" + annotationDescr.getValue(key) + \" used in property \" + key + \" of annotation \" + annotationDescr.getName()));\r\n }\r\n }\r\n }\r\n return annotationDescr;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateClientConfigurations(Exchange exchange, ClientConfigurations clientConfigurations){\r\n boolean isImageContentSet = true;\r\n boolean isImageUrlSet = true;\r\n String imageContent = exchange.getProperty(ImageRecognitionProperties.IMAGE_CONTENT, String.class);\r\n if (!StringUtils.isEmpty(imageContent)) {\r\n clientConfigurations.setImageContent(imageContent);\r\n } else if (!StringUtils.isEmpty(this.endpoint.getImageContent())) {\r\n clientConfigurations.setImageContent(this.endpoint.getImageContent());\r\n } else {\r\n isImageContentSet = false;\r\n }\r\n String imageUrl = exchange.getProperty(ImageRecognitionProperties.IMAGE_URL, String.class);\r\n if (!StringUtils.isEmpty(imageUrl)) {\r\n clientConfigurations.setImageUrl(imageUrl);\r\n } else if (!StringUtils.isEmpty(this.endpoint.getImageUrl())) {\r\n clientConfigurations.setImageUrl(this.endpoint.getImageUrl());\r\n } else {\r\n isImageUrlSet = false;\r\n }\r\n if (!isImageContentSet && !isImageUrlSet) {\r\n throw new IllegalArgumentException(\"either image content or image url should be set\");\r\n }\r\n String tagLanguageProperty = exchange.getProperty(ImageRecognitionProperties.TAG_LANGUAGE, String.class);\r\n clientConfigurations.setTagLanguage(StringUtils.isEmpty(tagLanguageProperty) ? this.endpoint.getTagLanguage() : tagLanguageProperty);\r\n if (!ImageRecognitionConstants.TAG_LANGUAGE_ZH.equals(clientConfigurations.getTagLanguage()) && !ImageRecognitionConstants.TAG_LANGUAGE_EN.equals(clientConfigurations.getTagLanguage())) {\r\n throw new IllegalArgumentException(\"tag language can only be 'zh' or 'en'\");\r\n }\r\n Integer tagLimitProperty = exchange.getProperty(ImageRecognitionProperties.TAG_LIMIT, Integer.class);\r\n clientConfigurations.setTagLimit(tagLimitProperty == null ? endpoint.getTagLimit() : tagLimitProperty);\r\n Float thresholdProperty = exchange.getProperty(ImageRecognitionProperties.THRESHOLD, Float.class);\r\n clientConfigurations.setThreshold(thresholdProperty == null ? endpoint.getThreshold() : thresholdProperty);\r\n if (clientConfigurations.getThreshold() == -1) {\r\n clientConfigurations.setThreshold(ImageRecognitionConstants.OPERATION_TAG_RECOGNITION.equals(endpoint.getOperation()) ? ImageRecognitionConstants.DEFAULT_TAG_RECOGNITION_THRESHOLD : ImageRecognitionConstants.DEFAULT_CELEBRITY_RECOGNITION_THRESHOLD);\r\n }\r\n validateThresholdValue(clientConfigurations.getThreshold(), endpoint.getOperation());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void buildMenuItems(final MetaModelContext mmc, final BSMenuBar menuBar, final MenuVisitor menuBuilder){\r\n val itemsPerSectionCounter = new LongAdder();\r\n val menuVisitor = MenuProcessor.of(mmc, menuBuilder);\r\n for (val menu : menuBar.getMenus()) {\r\n menuVisitor.addTopLevel(menu);\r\n for (val menuSection : menu.getSections()) {\r\n itemsPerSectionCounter.reset();\r\n for (val actionLayoutData : menuSection.getServiceActions()) {\r\n val serviceBeanName = actionLayoutData.getLogicalTypeName();\r\n val serviceAdapter = mmc.lookupServiceAdapterById(serviceBeanName);\r\n if (serviceAdapter == null) {\r\n continue;\r\n }\r\n val managedAction = ManagedAction.lookupAction(serviceAdapter, actionLayoutData.getId(), Where.EVERYWHERE).orElse(null);\r\n if (managedAction == null) {\r\n log.warn(\"No such action: bean-name '{}' action-id '{}'\", serviceBeanName, actionLayoutData.getId());\r\n continue;\r\n }\r\n val visibilityVeto = managedAction.checkVisibility();\r\n if (visibilityVeto.isPresent()) {\r\n continue;\r\n }\r\n val isFirstInSection = itemsPerSectionCounter.intValue() == 0;\r\n menuVisitor.addSubMenu(menuSection, managedAction, isFirstInSection, actionLayoutData);\r\n itemsPerSectionCounter.increment();\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static RelDataType deduceRowType(JavaTypeFactory typeFactory, Source source, @Nullable List fieldTypes, Boolean stream){\r\n final List types = new ArrayList<>();\r\n final List names = new ArrayList<>();\r\n if (stream) {\r\n names.add(FileSchemaFactory.ROWTIME_COLUMN_NAME);\r\n types.add(typeFactory.createSqlType(SqlTypeName.TIMESTAMP));\r\n }\r\n try (CSVReader reader = openCsv(source)) {\r\n String[] strings = reader.readNext();\r\n if (strings == null) {\r\n strings = new String[] { \"EmptyFileHasNoColumns:boolean\" };\r\n }\r\n for (String string : strings) {\r\n final String name;\r\n final RelDataType fieldType;\r\n final int colon = string.indexOf(':');\r\n if (colon >= 0) {\r\n name = string.substring(0, colon);\r\n String typeString = string.substring(colon + 1);\r\n Matcher decimalMatcher = DECIMAL_TYPE_PATTERN.matcher(typeString);\r\n if (decimalMatcher.matches()) {\r\n int precision = Integer.parseInt(decimalMatcher.group(1));\r\n int scale = Integer.parseInt(decimalMatcher.group(2));\r\n fieldType = parseDecimalSqlType(typeFactory, precision, scale);\r\n } else {\r\n switch(typeString) {\r\n case \"string\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.VARCHAR);\r\n break;\r\n case \"boolean\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.BOOLEAN);\r\n break;\r\n case \"byte\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.TINYINT);\r\n break;\r\n case \"char\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.CHAR);\r\n break;\r\n case \"short\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.SMALLINT);\r\n break;\r\n case \"int\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.INTEGER);\r\n break;\r\n case \"long\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.BIGINT);\r\n break;\r\n case \"float\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.REAL);\r\n break;\r\n case \"double\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.DOUBLE);\r\n break;\r\n case \"date\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.DATE);\r\n break;\r\n case \"timestamp\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.TIMESTAMP);\r\n break;\r\n case \"time\":\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.TIME);\r\n break;\r\n default:\r\n LOGGER.warn(\"Found unknown type: {} in file: {} for column: {}. Will assume the type of \" + \"column is string.\", typeString, source.path(), name);\r\n fieldType = toNullableRelDataType(typeFactory, SqlTypeName.VARCHAR);\r\n break;\r\n }\r\n }\r\n } else {\r\n name = string;\r\n fieldType = typeFactory.createSqlType(SqlTypeName.VARCHAR);\r\n }\r\n names.add(name);\r\n types.add(fieldType);\r\n if (fieldTypes != null) {\r\n fieldTypes.add(fieldType);\r\n }\r\n }\r\n } catch (IOException e) {\r\n }\r\n if (names.isEmpty()) {\r\n names.add(\"line\");\r\n types.add(typeFactory.createSqlType(SqlTypeName.VARCHAR));\r\n }\r\n return typeFactory.createStructType(Pair.zip(names, types));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void insertRight(BetaNode node, LeftTupleSink sink, TupleSets trgLeftTuples, TupleSets stagedLeftTuples, TupleSets srcRightTuples, boolean tupleMemoryEnabled){\r\n if (srcRightTuples.getInsertFirst() != null) {\r\n for (RightTuple rightTuple = srcRightTuples.getInsertFirst(); rightTuple != null; ) {\r\n RightTuple next = rightTuple.getStagedNext();\r\n LeftTuple leftTuple = node.getStartTuple((SubnetworkTuple) rightTuple);\r\n TupleList matches = (TupleList) leftTuple.getContextObject();\r\n if (matches == null) {\r\n matches = new TupleList<>();\r\n leftTuple.setContextObject(matches);\r\n }\r\n matches.add(rightTuple);\r\n if (matches.size() == 1) {\r\n if (node.getType() == NodeTypeEnums.ExistsNode) {\r\n if (!leftTuple.isExpired()) {\r\n boolean useTupleMemory = tupleMemoryEnabled || RuleNetworkEvaluator.useLeftMemory(node, rightTuple);\r\n trgLeftTuples.addInsert(sink.createLeftTuple(leftTuple, sink, leftTuple.getPropagationContext(), useTupleMemory));\r\n }\r\n } else {\r\n LeftTuple childLeftTuple = leftTuple.getFirstChild();\r\n if (childLeftTuple != null) {\r\n childLeftTuple.setPropagationContext(rightTuple.getPropagationContext());\r\n RuleNetworkEvaluator.unlinkAndDeleteChildLeftTuple(childLeftTuple, trgLeftTuples, stagedLeftTuples);\r\n }\r\n }\r\n }\r\n rightTuple.clearStaged();\r\n rightTuple = next;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Set findCompassBearingForBoardingPosition(StopArea sa){\r\n Set compassBearings = new TreeSet();\r\n List stopPoints = sa.getContainedScheduledStopPoints().stream().map(ScheduledStopPoint::getStopPoints).flatMap(List::stream).collect(Collectors.toList());\r\n for (StopPoint stop : stopPoints) {\r\n Route route = stop.getRoute();\r\n List journeyPatterns = route.getJourneyPatterns();\r\n for (JourneyPattern jp : journeyPatterns) {\r\n StopPoint previous = null;\r\n StopPoint next = null;\r\n List stopPointsInJourneyPattern = jp.getStopPoints();\r\n if (jp.getDepartureStopPoint().getScheduledStopPoint().getContainedInStopAreaRef().getObjectId().equals(stop.getScheduledStopPoint().getContainedInStopAreaRef().getObjectId())) {\r\n next = stopPointsInJourneyPattern.get(1);\r\n } else if (jp.getArrivalStopPoint().getScheduledStopPoint().getContainedInStopAreaRef().getObjectId().equals(stop.getScheduledStopPoint().getContainedInStopAreaRef().getObjectId())) {\r\n previous = stopPointsInJourneyPattern.get(stopPointsInJourneyPattern.size() - 2);\r\n } else {\r\n for (int i = 0; i < stopPointsInJourneyPattern.size(); i++) {\r\n if (stop.getScheduledStopPoint().getContainedInStopAreaRef().getObjectId().equals(stopPointsInJourneyPattern.get(i).getScheduledStopPoint().getContainedInStopAreaRef().getObjectId())) {\r\n previous = stopPointsInJourneyPattern.get(i - 1);\r\n next = stopPointsInJourneyPattern.get(i + 1);\r\n break;\r\n }\r\n }\r\n }\r\n Integer bearing = null;\r\n if (previous != null && next != null) {\r\n bearing = bearing(previous, next);\r\n } else if (previous != null) {\r\n bearing = bearing(previous, stop);\r\n } else {\r\n bearing = bearing(stop, next);\r\n }\r\n if (bearing != null) {\r\n compassBearings.add(bearing);\r\n }\r\n }\r\n }\r\n return compassBearings;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Schema modelTypeAsProperty(String typeName, OpenAPI openApi){\r\n Schema prop = null;\r\n boolean array = typeName.endsWith(\"[]\");\r\n if (array) {\r\n typeName = typeName.substring(0, typeName.length() - 2);\r\n }\r\n String ref = modelTypeAsRef(typeName, openApi);\r\n if (ref == null) {\r\n if (array && (\"byte\".equals(typeName) || \"java.lang.Byte\".equals(typeName))) {\r\n prop = new Schema().type(\"number\").format(\"byte\");\r\n array = false;\r\n } else if (\"string\".equalsIgnoreCase(typeName) || \"java.lang.String\".equals(typeName)) {\r\n prop = new StringSchema();\r\n } else if (\"int\".equals(typeName) || \"java.lang.Integer\".equals(typeName)) {\r\n prop = new IntegerSchema();\r\n } else if (\"long\".equals(typeName) || \"java.lang.Long\".equals(typeName)) {\r\n prop = new IntegerSchema().format(\"int64\");\r\n } else if (\"float\".equals(typeName) || \"java.lang.Float\".equals(typeName)) {\r\n prop = new NumberSchema().format(\"float\");\r\n } else if (\"double\".equals(typeName) || \"java.lang.Double\".equals(typeName)) {\r\n prop = new NumberSchema().format(\"double\");\r\n } else if (\"boolean\".equals(typeName) || \"java.lang.Boolean\".equals(typeName)) {\r\n prop = new NumberSchema().format(\"boolean\");\r\n } else if (\"file\".equals(typeName) || \"java.io.File\".equals(typeName)) {\r\n prop = new FileSchema();\r\n } else {\r\n prop = new StringSchema();\r\n }\r\n }\r\n if (array) {\r\n Schema items = new Schema<>();\r\n if (ref != null) {\r\n items.set$ref(OAS30_SCHEMA_DEFINITION_PREFIX + ref);\r\n }\r\n prop = new ArraySchema().items(items);\r\n } else if (prop == null) {\r\n prop = new Schema<>().$ref(OAS30_SCHEMA_DEFINITION_PREFIX + ref);\r\n }\r\n return prop;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void replicasCheck() throws ReplicationException.BKAuditException{\r\n ConcurrentHashMap ledgersWithMissingEntries = new ConcurrentHashMap();\r\n ConcurrentHashMap ledgersWithUnavailableBookies = new ConcurrentHashMap();\r\n LedgerManager.LedgerRangeIterator ledgerRangeIterator = ledgerManager.getLedgerRanges(zkOpTimeoutMs);\r\n final Semaphore maxConcurrentSemaphore = new Semaphore(MAX_CONCURRENT_REPLICAS_CHECK_LEDGER_REQUESTS);\r\n while (true) {\r\n LedgerManager.LedgerRange ledgerRange = null;\r\n try {\r\n if (ledgerRangeIterator.hasNext()) {\r\n ledgerRange = ledgerRangeIterator.next();\r\n } else {\r\n break;\r\n }\r\n } catch (IOException ioe) {\r\n LOG.error(\"Got IOException while iterating LedgerRangeIterator\", ioe);\r\n throw new ReplicationException.BKAuditException(\"Got IOException while iterating LedgerRangeIterator\", ioe);\r\n }\r\n ledgersWithMissingEntries.clear();\r\n ledgersWithUnavailableBookies.clear();\r\n numLedgersFoundHavingNoReplicaOfAnEntry.set(0);\r\n numLedgersFoundHavingLessThanAQReplicasOfAnEntry.set(0);\r\n numLedgersFoundHavingLessThanWQReplicasOfAnEntry.set(0);\r\n Set ledgersInRange = ledgerRange.getLedgers();\r\n int numOfLedgersInRange = ledgersInRange.size();\r\n final AtomicInteger resultCode = new AtomicInteger();\r\n final CountDownLatch replicasCheckLatch = new CountDownLatch(1);\r\n ReplicasCheckFinalCallback finalCB = new ReplicasCheckFinalCallback(resultCode, replicasCheckLatch);\r\n MultiCallback mcbForThisLedgerRange = new MultiCallback(numOfLedgersInRange, finalCB, null, BKException.Code.OK, BKException.Code.ReadException) {\r\n\r\n @Override\r\n public void processResult(int rc, String path, Object ctx) {\r\n try {\r\n super.processResult(rc, path, ctx);\r\n } finally {\r\n maxConcurrentSemaphore.release();\r\n }\r\n }\r\n };\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Number of ledgers in the current LedgerRange : {}\", numOfLedgersInRange);\r\n }\r\n for (Long ledgerInRange : ledgersInRange) {\r\n try {\r\n if (!maxConcurrentSemaphore.tryAcquire(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) {\r\n LOG.error(\"Timedout ({} secs) while waiting for acquiring semaphore\", REPLICAS_CHECK_TIMEOUT_IN_SECS);\r\n throw new ReplicationException.BKAuditException(\"Timedout while waiting for acquiring semaphore\");\r\n }\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n LOG.error(\"Got InterruptedException while acquiring semaphore for replicascheck\", ie);\r\n throw new ReplicationException.BKAuditException(\"Got InterruptedException while acquiring semaphore for replicascheck\", ie);\r\n }\r\n if (checkUnderReplicationForReplicasCheck(ledgerInRange, mcbForThisLedgerRange)) {\r\n continue;\r\n }\r\n ledgerManager.readLedgerMetadata(ledgerInRange).whenComplete(new ReadLedgerMetadataCallbackForReplicasCheck(ledgerInRange, mcbForThisLedgerRange, ledgersWithMissingEntries, ledgersWithUnavailableBookies));\r\n }\r\n try {\r\n if (!replicasCheckLatch.await(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) {\r\n LOG.error(\"For LedgerRange with num of ledgers : {} it didn't complete replicascheck\" + \" in {} secs, so giving up\", numOfLedgersInRange, REPLICAS_CHECK_TIMEOUT_IN_SECS);\r\n throw new ReplicationException.BKAuditException(\"Got InterruptedException while doing replicascheck\");\r\n }\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n LOG.error(\"Got InterruptedException while doing replicascheck\", ie);\r\n throw new ReplicationException.BKAuditException(\"Got InterruptedException while doing replicascheck\", ie);\r\n }\r\n reportLedgersWithMissingEntries(ledgersWithMissingEntries);\r\n reportLedgersWithUnavailableBookies(ledgersWithUnavailableBookies);\r\n int resultCodeIntValue = resultCode.get();\r\n if (resultCodeIntValue != BKException.Code.OK) {\r\n throw new ReplicationException.BKAuditException(\"Exception while doing replicas check\", BKException.create(resultCodeIntValue));\r\n }\r\n }\r\n try {\r\n ledgerUnderreplicationManager.setReplicasCheckCTime(System.currentTimeMillis());\r\n } catch (ReplicationException.NonRecoverableReplicationException nre) {\r\n LOG.error(\"Non Recoverable Exception while reading from ZK\", nre);\r\n submitShutdownTask();\r\n } catch (ReplicationException.UnavailableException ue) {\r\n LOG.error(\"Got exception while trying to set ReplicasCheckCTime\", ue);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public MetaData parse(MetaData metaData, Map data, Character keywordSeparator) throws ParseException{\r\n List defaultCiteKeyPattern = new ArrayList<>();\r\n Map> nonDefaultCiteKeyPatterns = new HashMap<>();\r\n List> entryList = new ArrayList<>(data.entrySet());\r\n entryList.sort(groupsLast());\r\n for (Map.Entry entry : entryList) {\r\n List values = getAsList(entry.getValue());\r\n if (entry.getKey().startsWith(MetaData.PREFIX_KEYPATTERN)) {\r\n EntryType entryType = EntryTypeFactory.parse(entry.getKey().substring(MetaData.PREFIX_KEYPATTERN.length()));\r\n nonDefaultCiteKeyPatterns.put(entryType, Collections.singletonList(getSingleItem(values)));\r\n } else if (entry.getKey().startsWith(MetaData.SELECTOR_META_PREFIX)) {\r\n metaData.addContentSelector(ContentSelectors.parse(FieldFactory.parseField(entry.getKey().substring(MetaData.SELECTOR_META_PREFIX.length())), StringUtil.unquote(entry.getValue(), MetaData.ESCAPE_CHARACTER)));\r\n } else if (entry.getKey().equals(MetaData.FILE_DIRECTORY)) {\r\n metaData.setDefaultFileDirectory(parseDirectory(entry.getValue()));\r\n } else if (entry.getKey().startsWith(MetaData.FILE_DIRECTORY + '-')) {\r\n String user = entry.getKey().substring(MetaData.FILE_DIRECTORY.length() + 1);\r\n metaData.setUserFileDirectory(user, parseDirectory(entry.getValue()));\r\n } else if (entry.getKey().startsWith(MetaData.FILE_DIRECTORY_LATEX)) {\r\n String user = entry.getKey().substring(MetaData.FILE_DIRECTORY_LATEX.length() + 1);\r\n Path path = Path.of(parseDirectory(entry.getValue())).normalize();\r\n metaData.setLatexFileDirectory(user, path);\r\n } else if (entry.getKey().equals(MetaData.SAVE_ACTIONS)) {\r\n metaData.setSaveActions(FieldFormatterCleanups.parse(values));\r\n } else if (entry.getKey().equals(MetaData.DATABASE_TYPE)) {\r\n metaData.setMode(BibDatabaseMode.parse(getSingleItem(values)));\r\n } else if (entry.getKey().equals(MetaData.KEYPATTERNDEFAULT)) {\r\n defaultCiteKeyPattern = Collections.singletonList(getSingleItem(values));\r\n } else if (entry.getKey().equals(MetaData.PROTECTED_FLAG_META)) {\r\n if (Boolean.parseBoolean(getSingleItem(values))) {\r\n metaData.markAsProtected();\r\n } else {\r\n metaData.markAsNotProtected();\r\n }\r\n } else if (entry.getKey().equals(MetaData.SAVE_ORDER_CONFIG)) {\r\n metaData.setSaveOrderConfig(SaveOrder.parse(values));\r\n } else if (entry.getKey().equals(MetaData.GROUPSTREE) || entry.getKey().equals(MetaData.GROUPSTREE_LEGACY)) {\r\n metaData.setGroups(GroupsParser.importGroups(values, keywordSeparator, fileMonitor, metaData));\r\n } else if (entry.getKey().equals(MetaData.VERSION_DB_STRUCT)) {\r\n metaData.setVersionDBStructure(getSingleItem(values));\r\n } else {\r\n metaData.putUnknownMetaDataItem(entry.getKey(), values);\r\n }\r\n }\r\n if (!defaultCiteKeyPattern.isEmpty() || !nonDefaultCiteKeyPatterns.isEmpty()) {\r\n metaData.setCiteKeyPattern(defaultCiteKeyPattern, nonDefaultCiteKeyPatterns);\r\n }\r\n return metaData;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void takeAll() throws InterruptedException{\r\n long iteration = 0;\r\n AtomicReference putStack = this.putStack;\r\n for (; ; ) {\r\n if (consumerThread.isInterrupted()) {\r\n putStack.compareAndSet(BLOCKED, null);\r\n throw new InterruptedException();\r\n }\r\n Node currentPutStackHead = putStack.get();\r\n if (currentPutStackHead == null) {\r\n if (idleStrategy != null) {\r\n idleStrategy.idle(iteration);\r\n continue;\r\n }\r\n if (!putStack.compareAndSet(null, BLOCKED)) {\r\n continue;\r\n }\r\n park();\r\n } else if (currentPutStackHead == BLOCKED) {\r\n park();\r\n } else {\r\n if (!putStack.compareAndSet(currentPutStackHead, null)) {\r\n continue;\r\n }\r\n copyIntoTakeStack(currentPutStackHead);\r\n break;\r\n }\r\n iteration++;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean save(StopArea neptuneObject, String prefix, Collection validParents, boolean keepOriginalId, boolean useTPEGRouteTypes){\r\n ChouetteAreaEnum chouetteAreaType = neptuneObject.getAreaType();\r\n if (chouetteAreaType.compareTo(ChouetteAreaEnum.BoardingPosition) == 0)\r\n stop.setLocationType(GtfsStop.LocationType.Stop);\r\n else if (chouetteAreaType.compareTo(ChouetteAreaEnum.Quay) == 0)\r\n stop.setLocationType(GtfsStop.LocationType.Stop);\r\n else if (chouetteAreaType.compareTo(ChouetteAreaEnum.CommercialStopPoint) == 0)\r\n stop.setLocationType(GtfsStop.LocationType.Station);\r\n else\r\n return false;\r\n stop.setStopId(toGtfsId(neptuneObject.getObjectId(), prefix, keepOriginalId));\r\n String name = neptuneObject.getName();\r\n if (name == null && neptuneObject.getParent() != null) {\r\n name = neptuneObject.getParent().getName();\r\n }\r\n if (name == null) {\r\n return false;\r\n }\r\n stop.setStopName(neptuneObject.getName());\r\n if (neptuneObject.getLatitude() == null) {\r\n return false;\r\n }\r\n stop.setStopLat(neptuneObject.getLatitude());\r\n if (neptuneObject.getLongitude() == null) {\r\n return false;\r\n }\r\n stop.setStopLon(neptuneObject.getLongitude());\r\n if (neptuneObject.getName().equals(neptuneObject.getComment())) {\r\n stop.setStopDesc(null);\r\n } else {\r\n stop.setStopDesc(neptuneObject.getComment());\r\n }\r\n stop.setStopUrl(getUrl(neptuneObject.getUrl()));\r\n stop.setStopTimezone(null);\r\n if (!isEmpty(neptuneObject.getTimeZone())) {\r\n TimeZone tz = TimeZone.getTimeZone(neptuneObject.getTimeZone());\r\n if (tz != null) {\r\n stop.setStopTimezone(tz);\r\n }\r\n }\r\n stop.setParentStation(null);\r\n if (stop.getLocationType().equals(GtfsStop.LocationType.Stop)) {\r\n if (neptuneObject.getParent() != null && validParents.contains(neptuneObject.getParent())) {\r\n stop.setParentStation(toGtfsId(neptuneObject.getParent().getObjectId(), prefix, keepOriginalId));\r\n }\r\n }\r\n if (neptuneObject.getMobilityRestrictedSuitable() != null) {\r\n if (neptuneObject.getMobilityRestrictedSuitable()) {\r\n stop.setWheelchairBoarding(WheelchairBoardingType.Allowed);\r\n } else {\r\n stop.setWheelchairBoarding(WheelchairBoardingType.NoAllowed);\r\n }\r\n } else {\r\n stop.setWheelchairBoarding(null);\r\n }\r\n stop.setPlatformCode(neptuneObject.getRegistrationNumber());\r\n if (neptuneObject.getTransportModeName() != null) {\r\n if (useTPEGRouteTypes) {\r\n stop.setVehicleType(RouteTypeEnum.from(neptuneObject.getTransportModeName(), null));\r\n } else {\r\n switch(neptuneObject.getTransportModeName()) {\r\n case Tram:\r\n stop.setVehicleType(RouteTypeEnum.Tram);\r\n break;\r\n case Metro:\r\n stop.setVehicleType(RouteTypeEnum.Subway);\r\n break;\r\n case Rail:\r\n stop.setVehicleType(RouteTypeEnum.Rail);\r\n break;\r\n case Water:\r\n case Ferry:\r\n stop.setVehicleType(RouteTypeEnum.Ferry);\r\n break;\r\n case Funicular:\r\n stop.setVehicleType(RouteTypeEnum.Funicular);\r\n break;\r\n case Cableway:\r\n stop.setVehicleType(RouteTypeEnum.Gondola);\r\n break;\r\n case TrolleyBus:\r\n case Coach:\r\n case Bus:\r\n default:\r\n stop.setVehicleType(RouteTypeEnum.Bus);\r\n }\r\n }\r\n } else {\r\n stop.setVehicleType(null);\r\n }\r\n try {\r\n getExporter().getStopExporter().export(stop);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n return false;\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private DrlxParseResult compileToJavaRecursive(Class patternType, String bindingId, ConstraintExpression constraint, Expression drlxExpr, boolean hasBind, boolean isPositional){\r\n boolean isEnclosed = false;\r\n SimpleName bind = null;\r\n if (drlxExpr instanceof FullyQualifiedInlineCastExpr) {\r\n drlxExpr = transformFullyQualifiedInlineCastExpr(context.getTypeResolver(), (FullyQualifiedInlineCastExpr) drlxExpr);\r\n }\r\n while (drlxExpr instanceof EnclosedExpr) {\r\n drlxExpr = ((EnclosedExpr) drlxExpr).getInner();\r\n isEnclosed = true;\r\n }\r\n if (drlxExpr instanceof DrlxExpression) {\r\n bind = ((DrlxExpression) drlxExpr).getBind();\r\n drlxExpr = ((DrlxExpression) drlxExpr).getExpr();\r\n }\r\n if (drlxExpr instanceof MethodCallExpr && ((MethodCallExpr) drlxExpr).getScope().isEmpty() && ((MethodCallExpr) drlxExpr).getNameAsString().equals(\"eval\")) {\r\n drlxExpr = ((MethodCallExpr) drlxExpr).getArgument(0);\r\n }\r\n if (drlxExpr instanceof MethodCallExpr) {\r\n Optional optFail = convertBigDecimalArithmetic((MethodCallExpr) drlxExpr, patternType, bindingId, isPositional);\r\n if (optFail.isPresent()) {\r\n return optFail.get();\r\n }\r\n }\r\n if (drlxExpr instanceof BinaryExpr) {\r\n DrlxParseResult result = parseBinaryExpr((BinaryExpr) drlxExpr, patternType, bindingId, constraint, drlxExpr, hasBind, isPositional, isEnclosed);\r\n if (result instanceof SingleDrlxParseSuccess && bind != null) {\r\n ((SingleDrlxParseSuccess) result).setExprBinding(bind.asString());\r\n }\r\n return result;\r\n }\r\n if (drlxExpr instanceof ConditionalExpr) {\r\n return parseConditionalExpr((ConditionalExpr) drlxExpr, patternType, bindingId, constraint, hasBind, isPositional);\r\n }\r\n if (drlxExpr instanceof UnaryExpr) {\r\n return parseUnaryExpr((UnaryExpr) drlxExpr, patternType, bindingId, constraint, drlxExpr, hasBind, isPositional);\r\n }\r\n if (drlxExpr instanceof PointFreeExpr) {\r\n return parsePointFreeExpr((PointFreeExpr) drlxExpr, patternType, bindingId, isPositional);\r\n }\r\n if (patternType == null && drlxExpr instanceof MethodCallExpr) {\r\n MethodCallExpr methodCallExpr = (MethodCallExpr) drlxExpr;\r\n Optional functionCall = packageModel.getFunctions().stream().filter(m -> m.getName().equals(methodCallExpr.getName())).findFirst();\r\n if (functionCall.isPresent()) {\r\n return parseFunctionInEval(methodCallExpr, patternType, bindingId, isPositional, functionCall);\r\n }\r\n }\r\n if (drlxExpr instanceof FieldAccessExpr) {\r\n return parseFieldAccessExpr((FieldAccessExpr) drlxExpr, patternType, bindingId);\r\n }\r\n String expression = constraint.getExpression();\r\n if (drlxExpr instanceof DrlNameExpr) {\r\n return parseNameExpr((DrlNameExpr) drlxExpr, patternType, bindingId, drlxExpr, hasBind, expression);\r\n }\r\n if (drlxExpr instanceof OOPathExpr) {\r\n return parseOOPathExpr((OOPathExpr) drlxExpr, patternType, bindingId, drlxExpr, hasBind, expression);\r\n }\r\n if (drlxExpr instanceof LiteralExpr) {\r\n Class literalExpressionType = getLiteralExpressionType(((LiteralExpr) drlxExpr));\r\n if (drlxExpr instanceof BigIntegerLiteralExpr) {\r\n drlxExpr = ((BigIntegerLiteralExpr) drlxExpr).convertToObjectCreationExpr();\r\n } else if (drlxExpr instanceof BigDecimalLiteralExpr) {\r\n drlxExpr = ((BigDecimalLiteralExpr) drlxExpr).convertToObjectCreationExpr();\r\n }\r\n return new SingleDrlxParseSuccess(patternType, bindingId, drlxExpr, literalExpressionType).setIsPredicate(isBooleanBoxedUnboxed(literalExpressionType));\r\n }\r\n if (patternType != null) {\r\n ExpressionTyperContext expressionTyperContext = new ExpressionTyperContext();\r\n ExpressionTyper expressionTyper = new ExpressionTyper(context, patternType, bindingId, isPositional, expressionTyperContext);\r\n TypedExpressionResult leftTypedExpressionResult = expressionTyper.toTypedExpression(drlxExpr);\r\n Optional optLeft = leftTypedExpressionResult.getTypedExpression();\r\n if (optLeft.isEmpty()) {\r\n return new DrlxParseFail();\r\n }\r\n TypedExpression left = optLeft.get();\r\n Expression combo = left.getExpression();\r\n Type exprType = left.getType();\r\n boolean isPredicate = isBooleanBoxedUnboxed(exprType);\r\n if (isPredicate) {\r\n combo = combineExpressions(leftTypedExpressionResult, combo);\r\n }\r\n return new SingleDrlxParseSuccess(patternType, bindingId, combo, exprType).setReactOnProperties(expressionTyperContext.getReactOnProperties()).setVariablesFromDifferentPattern(expressionTyperContext.getVariablesFromDifferentPattern()).setUsedDeclarations(expressionTyperContext.getUsedDeclarations()).setImplicitCastExpression(expressionTyperContext.getInlineCastExpression()).setNullSafeExpressions(expressionTyperContext.getNullSafeExpressions()).setIsPredicate(isPredicate);\r\n } else {\r\n final ExpressionTyperContext expressionTyperContext = new ExpressionTyperContext();\r\n final ExpressionTyper expressionTyper = new ExpressionTyper(context, null, bindingId, isPositional, expressionTyperContext);\r\n TypedExpressionResult leftTypedExpressionResult = expressionTyper.toTypedExpression(drlxExpr);\r\n Optional optLeft = leftTypedExpressionResult.getTypedExpression();\r\n if (optLeft.isEmpty()) {\r\n return new DrlxParseFail();\r\n }\r\n TypedExpression left = optLeft.get();\r\n return new SingleDrlxParseSuccess(null, bindingId, drlxExpr, left.getType()).setUsedDeclarations(expressionTyperContext.getUsedDeclarations()).setIsPredicate(true);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void manageComparsa(List allegati, CnmDStatoAllegato avvioSpostamentoActa){\r\n Timestamp now = utilsDate.asTimeStamp(LocalDateTime.now());\r\n String operationToTrace = null;\r\n if (!(allegati == null || allegati.isEmpty())) {\r\n allegati = allegatoScheduledService.updateCnmDStatoAllegatoInCoda(allegati);\r\n for (CnmTAllegato cnmTAllegato : allegati) {\r\n if (cnmTAllegato.getCnmDStatoAllegato().getIdStatoAllegato() == Constants.STATO_ALLEGATO_IN_CODA) {\r\n CnmTVerbale cnmTVerbale = cnmTVerbaleRepository.findByIdActa(cnmTAllegato.getIdActaMaster());\r\n CnmTAllegato cnmTAllegatoMaster = cnmTAllegatoRepository.findByIdActa(cnmTAllegato.getIdActaMaster());\r\n logger.info(\"Sposto allegato su acta con id\" + cnmTAllegato.getIdAllegato() + \" Nome file: \" + cnmTAllegato.getNomeFile());\r\n ResponseAggiungiAllegato responseAggiungiAllegato = null;\r\n try {\r\n responseAggiungiAllegato = doquiServiceFacade.aggiungiAllegato(null, cnmTAllegato.getNomeFile(), cnmTAllegato.getIdIndex(), cnmTAllegato.getIdActaMaster(), utilsDoqui.createIdEntitaFruitore(cnmTVerbale, cnmTAllegato.getCnmDTipoAllegato()), \"\", utilsDoqui.getSoggettoActa(cnmTVerbale), utilsDoqui.getRootActa(cnmTVerbale), cnmTAllegato.getCnmDTipoAllegato().getIdTipoAllegato(), DoquiServiceFacade.TIPOLOGIA_DOC_ACTA_ALLEGATI_AL_MASTER_USCITA, null, new Date(cnmTAllegato.getDataOraInsert().getTime()));\r\n } catch (Exception e) {\r\n logger.error(\"Non riesco ad aggiungere l'allegato al master\", e);\r\n cnmTAllegato.setCnmDStatoAllegato(avvioSpostamentoActa);\r\n CnmTUser cnmTUser = cnmTUserRepository.findByCodiceFiscaleAndFineValidita(DoquiConstants.USER_SCHEDULED_TASK);\r\n cnmTAllegato.setCnmTUser1(cnmTUser);\r\n cnmTAllegato.setDataOraUpdate(now);\r\n allegatoScheduledService.updateCnmDStatoAllegato(cnmTAllegato);\r\n }\r\n if (responseAggiungiAllegato != null) {\r\n logger.info(\"Spostato allegato con id\" + cnmTAllegato.getIdAllegato() + \"e di tipo:\" + cnmTAllegato.getCnmDTipoAllegato().getDescTipoAllegato());\r\n String idIndex = cnmTAllegato.getIdIndex();\r\n cnmTAllegato.setCnmDStatoAllegato(cnmDStatoAllegatoRepository.findOne(Constants.STATO_ALLEGATO_MULTI_NON_PROTOCOLLARE));\r\n cnmTAllegato.setIdActa(responseAggiungiAllegato.getIdDocumento());\r\n cnmTAllegato.setIdIndex(null);\r\n CnmTUser cnmTUser = cnmTUserRepository.findByCodiceFiscaleAndFineValidita(DoquiConstants.USER_SCHEDULED_TASK);\r\n cnmTAllegato.setCnmTUser1(cnmTUser);\r\n cnmTAllegato.setDataOraUpdate(now);\r\n allegatoScheduledService.updateCnmDStatoAllegato(cnmTAllegato);\r\n try {\r\n doquiServiceFacade.eliminaDocumentoIndex(idIndex);\r\n } catch (Exception e) {\r\n logger.error(\"Non riesco ad eliminare l'allegato con idIndex :: \" + idIndex);\r\n }\r\n String className = Thread.currentThread().getStackTrace()[1].getClassName().substring(Thread.currentThread().getStackTrace()[1].getClassName().lastIndexOf(\".\") + 1);\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(TraceOperation.SPOSTAMENTO_ALLEGATO_DA_INDEX.getOperation(), cnmTAllegato.getClass().getAnnotation(Table.class).name(), \"id_allegato=\" + cnmTAllegato.getIdAllegato(), className + \".\" + Thread.currentThread().getStackTrace()[1].getMethodName(), cnmTAllegato.getCnmDTipoAllegato().getDescTipoAllegato());\r\n operationToTrace = cnmTAllegato.isFlagDocumentoPregresso() ? TraceOperation.INSERIMENTO_ALLEGATO_PREGRESSO.getOperation() : TraceOperation.INSERIMENTO_ALLEGATO.getOperation();\r\n utilsTraceCsiLogAuditService.traceCsiLogAudit(operationToTrace, Constants.OGGETTO_ACTA, \"objectIdDocumento=\" + responseAggiungiAllegato.getObjectIdDocumento(), className + \".\" + Thread.currentThread().getStackTrace()[1].getMethodName(), cnmTAllegato.getCnmDTipoAllegato().getDescTipoAllegato());\r\n }\r\n CnmRAllegatoVerbale findByCnmTAllegato = cnmRAllegatoVerbaleRepository.findByCnmTAllegato(cnmTAllegato);\r\n if (findByCnmTAllegato == null || findByCnmTAllegato.getId() == null) {\r\n logger.info(\"Mi prendo il master x idActa :: \" + cnmTAllegato.getIdActa());\r\n CnmTVerbale master = cnmTVerbaleRepository.findByIdActa(cnmTAllegato.getIdActaMaster());\r\n logger.info(\"id verbale Master :: \" + master.getIdVerbale());\r\n CnmRAllegatoVerbale cnmRAllegatoVerbale = new CnmRAllegatoVerbale();\r\n CnmRAllegatoVerbalePK cnmRAllegatoVerbalePK = new CnmRAllegatoVerbalePK();\r\n cnmRAllegatoVerbalePK.setIdAllegato(cnmTAllegato.getIdAllegato());\r\n cnmRAllegatoVerbalePK.setIdVerbale(master.getIdVerbale());\r\n cnmRAllegatoVerbale.setCnmTUser(master.getCnmTUser2());\r\n cnmRAllegatoVerbale.setDataOraInsert(utilsDate.asTimeStamp(LocalDateTime.now()));\r\n cnmRAllegatoVerbale.setId(cnmRAllegatoVerbalePK);\r\n cnmRAllegatoVerbaleRepository.save(cnmRAllegatoVerbale);\r\n }\r\n if (protocollazioneDaAvviare(allegati, cnmTAllegatoMaster)) {\r\n CnmTUser cnmTUser = cnmTUserRepository.findByCodiceFiscaleAndFineValidita(DoquiConstants.USER_SCHEDULED_TASK);\r\n ResponseProtocollaDocumento responseProtocollaEsistente = commonAllegatoService.avviaProtocollazioneDocumentoEsistente(cnmTAllegatoMaster, cnmTUser);\r\n String numProtocollo = responseProtocollaEsistente.getProtocollo();\r\n for (CnmTAllegato cnmTAllegatoUpdate : allegati) {\r\n if (cnmTAllegatoUpdate.getIdActaMaster().equalsIgnoreCase(cnmTAllegatoMaster.getIdActa())) {\r\n cnmTAllegatoUpdate.setCnmDStatoAllegato(cnmDStatoAllegatoRepository.findOne(Constants.STATO_ALLEGATO_PROTOCOLLATO));\r\n cnmTAllegatoUpdate.setNumeroProtocollo(numProtocollo);\r\n cnmTAllegatoUpdate.setDataOraProtocollo(now);\r\n cnmTAllegatoUpdate.setCnmTUser1(cnmTUser);\r\n cnmTAllegatoUpdate.setDataOraUpdate(now);\r\n allegatoScheduledService.updateCnmDStatoAllegato(cnmTAllegatoUpdate);\r\n CnmTDocumento cnmTDocumento = cnmTDocumentoRepository.findOne(Integer.parseInt(cnmTAllegatoUpdate.getIdActa()));\r\n if (cnmTDocumento != null) {\r\n cnmTDocumento.setProtocolloFornitore(numProtocollo);\r\n cnmTDocumento.setCnmTUser1(cnmTUser);\r\n cnmTDocumento.setDataOraUpdate(now);\r\n cnmTDocumentoRepository.save(cnmTDocumento);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public EnumSet diff(HCatTable rhs, EnumSet attributesToCheck){\r\n EnumSet theDiff = EnumSet.noneOf(TableAttribute.class);\r\n for (TableAttribute attribute : attributesToCheck) {\r\n if (attribute.equals(TableAttribute.COLUMNS)) {\r\n if (!rhs.getCols().containsAll(getCols()) || !getCols().containsAll(rhs.getCols())) {\r\n theDiff.add(TableAttribute.COLUMNS);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.INPUT_FORMAT)) {\r\n if ((getInputFileFormat() == null && rhs.getInputFileFormat() != null) || (getInputFileFormat() != null && (rhs.getInputFileFormat() == null || !rhs.getInputFileFormat().equals(getInputFileFormat())))) {\r\n theDiff.add(TableAttribute.INPUT_FORMAT);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.OUTPUT_FORMAT)) {\r\n if ((getOutputFileFormat() == null && rhs.getOutputFileFormat() != null) || (getOutputFileFormat() != null && (rhs.getOutputFileFormat() == null || !rhs.getOutputFileFormat().equals(getOutputFileFormat())))) {\r\n theDiff.add(TableAttribute.OUTPUT_FORMAT);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.STORAGE_HANDLER)) {\r\n if ((getStorageHandler() == null && rhs.getStorageHandler() != null) || (getStorageHandler() != null && (rhs.getStorageHandler() == null || !rhs.getStorageHandler().equals(getStorageHandler())))) {\r\n theDiff.add(TableAttribute.STORAGE_HANDLER);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.SERDE)) {\r\n if ((getSerdeLib() == null && rhs.getSerdeLib() != null) || (getSerdeLib() != null && (rhs.getSerdeLib() == null || !rhs.getSerdeLib().equals(getSerdeLib())))) {\r\n theDiff.add(TableAttribute.SERDE);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.SERDE_PROPERTIES)) {\r\n if (!equivalent(sd.getSerdeInfo().getParameters(), rhs.sd.getSerdeInfo().getParameters())) {\r\n theDiff.add(TableAttribute.SERDE_PROPERTIES);\r\n }\r\n }\r\n if (attribute.equals(TableAttribute.TABLE_PROPERTIES)) {\r\n if (!equivalent(tblProps, rhs.tblProps)) {\r\n theDiff.add(TableAttribute.TABLE_PROPERTIES);\r\n }\r\n }\r\n }\r\n return theDiff;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Builder builder(RelNode rel, Set clauses){\r\n assert expectedClauses.containsAll(clauses);\r\n assert rel.equals(expectedRel);\r\n final Set clauses2 = ignoreClauses ? ImmutableSet.of() : clauses;\r\n final boolean needNew = needNewSubQuery(rel, this.clauses, clauses2);\r\n assert needNew == this.needNew;\r\n SqlSelect select;\r\n Expressions.FluentList clauseList = Expressions.list();\r\n if (needNew) {\r\n select = subSelect();\r\n } else {\r\n select = asSelect();\r\n clauseList.addAll(this.clauses);\r\n }\r\n clauseList.appendAll(clauses);\r\n final Context newContext;\r\n Map newAliases = null;\r\n final SqlNodeList selectList = select.getSelectList();\r\n if (!selectList.equals(SqlNodeList.SINGLETON_STAR)) {\r\n final boolean aliasRef = expectedClauses.contains(Clause.HAVING) && dialect.getConformance().isHavingAlias();\r\n newContext = new Context(dialect, selectList.size()) {\r\n\r\n @Override\r\n public SqlImplementor implementor() {\r\n return SqlImplementor.this;\r\n }\r\n\r\n @Override\r\n public SqlNode field(int ordinal) {\r\n final SqlNode selectItem = selectList.get(ordinal);\r\n switch(selectItem.getKind()) {\r\n case AS:\r\n final SqlCall asCall = (SqlCall) selectItem;\r\n SqlNode alias = asCall.operand(1);\r\n if (aliasRef && !SqlUtil.isGeneratedAlias(((SqlIdentifier) alias).getSimple())) {\r\n return alias;\r\n }\r\n return asCall.operand(0);\r\n default:\r\n break;\r\n }\r\n return selectItem;\r\n }\r\n\r\n @Override\r\n public SqlNode orderField(int ordinal) {\r\n final SqlNode node = super.orderField(ordinal);\r\n if (node instanceof SqlIdentifier && ((SqlIdentifier) node).isSimple()) {\r\n final String name = ((SqlIdentifier) node).getSimple();\r\n for (Ord selectItem : Ord.zip(selectList)) {\r\n if (selectItem.i != ordinal) {\r\n @Nullable\r\n final String alias = SqlValidatorUtil.alias(selectItem.e);\r\n if (name.equalsIgnoreCase(alias) && dialect.getConformance().isSortByAlias()) {\r\n return SqlLiteral.createExactNumeric(Integer.toString(ordinal + 1), SqlParserPos.ZERO);\r\n }\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n };\r\n } else {\r\n boolean qualified = !dialect.hasImplicitTableAlias() || aliases.size() > 1;\r\n if (needNew && neededAlias != null && (aliases.size() != 1 || !aliases.containsKey(neededAlias))) {\r\n newAliases = ImmutableMap.of(neededAlias, rel.getInput(0).getRowType());\r\n newContext = aliasContext(newAliases, qualified);\r\n } else {\r\n newContext = aliasContext(aliases, qualified);\r\n }\r\n }\r\n return new Builder(rel, clauseList, select, newContext, isAnon(), needNew && !aliases.containsKey(neededAlias) ? newAliases : aliases);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void setRequestBodyParameters(String operationId, RequestBody requestBody, List requestBodyDoc, List parameterList, List defaultable) throws BallerinaOpenApiException{\r\n Content requestBodyContent;\r\n String referencedRequestBodyName = \"\";\r\n if (requestBody.get$ref() != null) {\r\n referencedRequestBodyName = extractReferenceType(requestBody.get$ref()).trim();\r\n RequestBody referencedRequestBody = openAPI.getComponents().getRequestBodies().get(referencedRequestBodyName);\r\n requestBodyContent = referencedRequestBody.getContent();\r\n requestBody.setDescription(referencedRequestBody.getDescription());\r\n } else {\r\n requestBodyContent = requestBody.getContent();\r\n }\r\n Iterator> iterator = requestBodyContent.entrySet().iterator();\r\n while (iterator.hasNext()) {\r\n Map.Entry mediaTypeEntry = iterator.next();\r\n Schema schema = mediaTypeEntry.getValue().getSchema();\r\n String paramType = \"\";\r\n if (schema != null && GeneratorUtils.isSupportedMediaType(mediaTypeEntry)) {\r\n String mediaTypeEntryKey = mediaTypeEntry.getKey();\r\n if (mediaTypeEntryKey.equals(APPLICATION_OCTET_STREAM) || mediaTypeEntryKey.matches(\"application/.*\\\\+octet-stream\")) {\r\n paramType = getBallerinaMediaType(mediaTypeEntryKey, true);\r\n } else {\r\n if (schema.get$ref() != null) {\r\n paramType = getValidName(extractReferenceType(schema.get$ref().trim()), true);\r\n } else if (schema.getType() != null && !schema.getType().equals(ARRAY) && !schema.getType().equals(OBJECT)) {\r\n paramType = convertOpenAPITypeToBallerina(schema);\r\n } else if (schema instanceof ArraySchema) {\r\n ArraySchema arraySchema = (ArraySchema) schema;\r\n paramType = getRequestBodyParameterForArraySchema(operationId, mediaTypeEntry, arraySchema);\r\n } else if (schema instanceof ObjectSchema) {\r\n ObjectSchema objectSchema = (ObjectSchema) schema;\r\n paramType = getRequestBodyParameterForObjectSchema(referencedRequestBodyName, objectSchema);\r\n } else {\r\n paramType = getBallerinaMediaType(mediaTypeEntryKey, true);\r\n }\r\n }\r\n } else {\r\n paramType = getBallerinaMediaType(mediaTypeEntry.getKey(), true);\r\n }\r\n String paramName = paramType.equals(HTTP_REQUEST) ? REQUEST : PAYLOAD;\r\n if (!paramType.isBlank()) {\r\n List annotationNodes = new ArrayList<>();\r\n DocCommentsGenerator.extractDisplayAnnotation(requestBody.getExtensions(), annotationNodes);\r\n SimpleNameReferenceNode typeName = createSimpleNameReferenceNode(createIdentifierToken(paramType));\r\n IdentifierToken paramNameToken = createIdentifierToken(paramName);\r\n RequiredParameterNode payload = createRequiredParameterNode(createNodeList(annotationNodes), typeName, paramNameToken);\r\n if (requestBody.getDescription() != null && !requestBody.getDescription().isBlank()) {\r\n MarkdownDocumentationNode paramAPIDoc = DocCommentsGenerator.createAPIParamDocFromSring(escapeIdentifier(paramName), requestBody.getDescription().split(\"\\n\")[0]);\r\n requestBodyDoc.add(paramAPIDoc);\r\n }\r\n parameterList.add(payload);\r\n parameterList.add(createToken((COMMA_TOKEN)));\r\n }\r\n if (mediaTypeEntry.getKey().equals(javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA) && mediaTypeEntry.getValue().getEncoding() != null) {\r\n List headerList = new ArrayList<>();\r\n for (Map.Entry entry : mediaTypeEntry.getValue().getEncoding().entrySet()) {\r\n if (entry.getValue().getHeaders() != null) {\r\n for (Map.Entry header : entry.getValue().getHeaders().entrySet()) {\r\n if (!headerList.contains(header.getKey())) {\r\n Node headerParameter = getHeaderEncoding(header, requestBodyDoc);\r\n if (headerParameter instanceof RequiredParameterNode) {\r\n parameterList.add(headerParameter);\r\n parameterList.add(createToken((COMMA_TOKEN)));\r\n } else {\r\n defaultable.add(headerParameter);\r\n defaultable.add(createToken((COMMA_TOKEN)));\r\n }\r\n headerList.add(header.getKey());\r\n }\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Path getFinalPath(FileSystem fs, Path file, Path src, Path dest, final boolean immutable) throws IOException{\r\n URI taskOutputUri = file.toUri();\r\n URI relativePath = src.toUri().relativize(taskOutputUri);\r\n if (taskOutputUri == relativePath) {\r\n throw new HCatException(ErrorType.ERROR_MOVE_FAILED, \"Can not get the relative path: base = \" + src + \" child = \" + file);\r\n }\r\n if (relativePath.getPath().length() > 0) {\r\n Path itemDest = new Path(dest, relativePath.getPath());\r\n if (!immutable) {\r\n String name = relativePath.getPath();\r\n String filetype;\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n filetype = name.substring(index);\r\n name = name.substring(0, index);\r\n } else {\r\n filetype = \"\";\r\n }\r\n int counter = 1;\r\n for (; fs.exists(itemDest) && counter < maxAppendAttempts; counter++) {\r\n itemDest = new Path(dest, name + (APPEND_SUFFIX + counter) + filetype);\r\n }\r\n if (counter == maxAppendAttempts) {\r\n throw new HCatException(ErrorType.ERROR_MOVE_FAILED, \"Could not find a unique destination path for move: file = \" + file + \" , src = \" + src + \", dest = \" + dest);\r\n } else if (counter > APPEND_COUNTER_WARN_THRESHOLD) {\r\n LOG.warn(\"Append job used filename clash counter [\" + counter + \"] which is greater than warning limit [\" + APPEND_COUNTER_WARN_THRESHOLD + \"]. Please compact this table so that performance is not impacted.\" + \" Please see HIVE-9381 for details.\");\r\n }\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"FinalPath(file:\" + file + \":\" + src + \"->\" + dest + \"=\" + itemDest);\r\n }\r\n return itemDest;\r\n } else {\r\n return dest;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static void processProxyuserConfig(AppConfig conf){\r\n for (Map.Entry confEnt : conf) {\r\n if (confEnt.getKey().startsWith(CONF_PROXYUSER_PREFIX) && confEnt.getKey().endsWith(CONF_GROUPS_SUFFIX)) {\r\n String proxyUser = confEnt.getKey().substring(CONF_PROXYUSER_PREFIX.length(), confEnt.getKey().lastIndexOf(CONF_GROUPS_SUFFIX));\r\n Set groups;\r\n if (\"*\".equals(confEnt.getValue())) {\r\n groups = WILD_CARD;\r\n LOG.debug(\"User [{}] is authorized to do doAs any user.\", proxyUser);\r\n } else if (confEnt.getValue() != null && confEnt.getValue().trim().length() > 0) {\r\n groups = new HashSet(Arrays.asList(confEnt.getValue().trim().split(\",\")));\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"User [\" + proxyUser + \"] is authorized to do doAs for users in the following groups: [\" + confEnt.getValue().trim() + \"]\");\r\n }\r\n } else {\r\n groups = Collections.emptySet();\r\n LOG.debug(\"User [{}] is authorized to do doAs for users in the following groups: []\", proxyUser);\r\n }\r\n proxyUserGroups.put(proxyUser, groups);\r\n } else if (confEnt.getKey().startsWith(CONF_PROXYUSER_PREFIX) && confEnt.getKey().endsWith(CONF_HOSTS_SUFFIX)) {\r\n String proxyUser = confEnt.getKey().substring(CONF_PROXYUSER_PREFIX.length(), confEnt.getKey().lastIndexOf(CONF_HOSTS_SUFFIX));\r\n Set hosts;\r\n if (\"*\".equals(confEnt.getValue())) {\r\n hosts = WILD_CARD;\r\n LOG.debug(\"User [{}] is authorized to do doAs from any host.\", proxyUser);\r\n } else if (confEnt.getValue() != null && confEnt.getValue().trim().length() > 0) {\r\n String[] hostValues = confEnt.getValue().trim().split(\",\");\r\n hosts = new HashSet();\r\n for (String hostname : hostValues) {\r\n String nhn = normalizeHostname(hostname);\r\n if (nhn != null) {\r\n hosts.add(nhn);\r\n }\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"User [\" + proxyUser + \"] is authorized to do doAs from the following hosts: [\" + confEnt.getValue().trim() + \"]\");\r\n }\r\n } else {\r\n hosts = Collections.emptySet();\r\n LOG.debug(\"User [{}] is authorized to do doAs from the following hosts: []\", proxyUser);\r\n }\r\n proxyUserHosts.put(proxyUser, hosts);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean doStoreFile(String name, String targetName, Exchange exchange) throws GenericFileOperationFailedException{\r\n log.trace(\"doStoreFile({})\", targetName);\r\n boolean existFile = false;\r\n if (endpoint.getFileExist() == GenericFileExist.Ignore || endpoint.getFileExist() == GenericFileExist.Fail || endpoint.getFileExist() == GenericFileExist.Move || endpoint.getFileExist() == GenericFileExist.Append) {\r\n existFile = existsFile(targetName);\r\n if (existFile && endpoint.getFileExist() == GenericFileExist.Ignore) {\r\n log.trace(\"An existing file already exists: {}. Ignore and do not override it.\", name);\r\n return true;\r\n } else if (existFile && endpoint.getFileExist() == GenericFileExist.Fail) {\r\n throw new GenericFileOperationFailedException(\"File already exist: \" + name + \". Cannot write new file.\");\r\n } else if (existFile && endpoint.getFileExist() == GenericFileExist.Move) {\r\n this.endpoint.getMoveExistingFileStrategy().moveExistingFile(endpoint, this, targetName);\r\n }\r\n }\r\n InputStream is = null;\r\n if (exchange.getIn().getBody() == null) {\r\n if (endpoint.isAllowNullBody()) {\r\n log.trace(\"Writing empty file.\");\r\n is = new ByteArrayInputStream(new byte[] {});\r\n } else {\r\n throw new GenericFileOperationFailedException(\"Cannot write null body to file: \" + name);\r\n }\r\n }\r\n try {\r\n if (is == null) {\r\n String charset = endpoint.getCharset();\r\n if (charset != null) {\r\n is = new ByteArrayInputStream(exchange.getIn().getMandatoryBody(String.class).getBytes(charset));\r\n log.trace(\"Using InputStream {} with charset {}.\", is, charset);\r\n } else {\r\n is = exchange.getIn().getMandatoryBody(InputStream.class);\r\n }\r\n }\r\n final StopWatch watch = new StopWatch();\r\n boolean answer;\r\n log.debug(\"About to store file: {} using stream: {}\", targetName, is);\r\n if (existFile && endpoint.getFileExist() == GenericFileExist.Append) {\r\n log.trace(\"Client appendFile: {}\", targetName);\r\n answer = client.appendFile(targetName, is);\r\n } else {\r\n log.trace(\"Client storeFile: {}\", targetName);\r\n answer = client.storeFile(targetName, is);\r\n }\r\n if (log.isDebugEnabled()) {\r\n long time = watch.taken();\r\n log.debug(\"Took {} ({} millis) to store file: {} and FTP client returned: {}\", TimeUtils.printDuration(time, true), time, targetName, answer);\r\n }\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE, client.getReplyCode());\r\n exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING, client.getReplyString());\r\n String chmod = endpoint.getConfiguration().getChmod();\r\n if (org.apache.camel.util.ObjectHelper.isNotEmpty(chmod)) {\r\n log.debug(\"Setting chmod: {} on file: {}\", chmod, targetName);\r\n String command = \"chmod \" + chmod + \" \" + targetName;\r\n log.trace(\"Client sendSiteCommand: {}\", command);\r\n boolean success = client.sendSiteCommand(command);\r\n log.trace(\"Client sendSiteCommand successful: {}\", success);\r\n }\r\n return answer;\r\n } catch (IOException e) {\r\n throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);\r\n } catch (InvalidPayloadException e) {\r\n throw new GenericFileOperationFailedException(\"Cannot store file: \" + name, e);\r\n } finally {\r\n IOHelper.close(is, \"store: \" + name, log);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static List unwrap(String java){\r\n final List sqlList = new ArrayList<>();\r\n final StringBuilder b = new StringBuilder();\r\n hLoop: for (int h = 0; ; ) {\r\n final int i = java.indexOf(START, h);\r\n if (i < 0) {\r\n return sqlList;\r\n }\r\n for (int j = i + START.length(); j < java.length(); ) {\r\n char c = java.charAt(j++);\r\n switch(c) {\r\n case '\"':\r\n sqlList.add(b.toString());\r\n b.setLength(0);\r\n h = j;\r\n continue hLoop;\r\n case '\\\\':\r\n c = java.charAt(j++);\r\n if (c == 'n') {\r\n b.append('\\n');\r\n break;\r\n }\r\n if (c == 'r') {\r\n break;\r\n }\r\n default:\r\n b.append(c);\r\n }\r\n }\r\n return sqlList;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void addOneSystemProperty(String name){\r\n try {\r\n String propValue = System.getProperty(name);\r\n if (propValue != null && !name.equals(propValue)) {\r\n append(\"\" + name + \":\");\r\n boolean isReadable = true;\r\n for (int i = 0; i < propValue.length(); i++) {\r\n char c = propValue.charAt(i);\r\n if (isControlCharacter(c)) {\r\n isReadable = false;\r\n break;\r\n }\r\n }\r\n if (!isReadable) {\r\n for (int i = 0; i < propValue.length(); i++) {\r\n char c = propValue.charAt(i);\r\n if (Character.isLetterOrDigit(c)) {\r\n append(\" '\" + c + \"'\");\r\n } else {\r\n append(\" 0x\");\r\n if (c < 0x10) {\r\n append(\"0\");\r\n }\r\n append(Integer.toHexString(c));\r\n }\r\n }\r\n } else if (isURLProperty(name)) {\r\n StringBuffer fixed = new StringBuffer();\r\n int start = 0;\r\n int hit = 0;\r\n while ((hit = propValue.indexOf('%', start)) >= 0) {\r\n fixed.append(propValue.substring(start, hit));\r\n int value = Integer.parseInt(propValue.substring(hit + 1, hit + 3), 16);\r\n fixed.append(((char) value));\r\n start = hit + 3;\r\n }\r\n append(\" \\\"\" + fixed + \"\\\"\");\r\n } else {\r\n append(\" \" + propValue);\r\n }\r\n append(\"
\");\r\n }\r\n } catch (SecurityException e) {\r\n append(name + \": Security Exception\\n\");\r\n } catch (Exception e) {\r\n append(name + \": \" + e + \"\\n\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RuleDescr query(PackageDescrBuilder pkg) throws RecognitionException{\r\n QueryDescrBuilder query = null;\r\n try {\r\n query = helper.start(pkg, QueryDescrBuilder.class, null);\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.QUERY, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.WHEN) || helper.validateIdentifierKey(DroolsSoftKeywords.THEN) || helper.validateIdentifierKey(DroolsSoftKeywords.END)) {\r\n failMissingTokenException();\r\n return null;\r\n }\r\n String name = stringId();\r\n if (state.backtracking == 0)\r\n query.name(name);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_RULE_HEADER);\r\n }\r\n if (speculateParameters(true)) {\r\n parameters(query, true);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION);\r\n }\r\n } else if (speculateParameters(false)) {\r\n parameters(query, false);\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION);\r\n }\r\n }\r\n while (input.LA(1) == DRL5Lexer.AT) {\r\n annotation(query);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0 && input.LA(1) != DRL5Lexer.EOF) {\r\n helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION);\r\n }\r\n if (input.LA(1) != DRL5Lexer.EOF) {\r\n lhsExpression(query != null ? query.lhs() : null);\r\n }\r\n match(input, DRL5Lexer.ID, DroolsSoftKeywords.END, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n helper.emit(Location.LOCATION_RHS);\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n } finally {\r\n helper.end(QueryDescrBuilder.class, query);\r\n }\r\n return (query != null) ? query.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void close(Reporter reporter) throws IOException{\r\n LOG.debug(\"mutations written: {}, values written: {}\", this.mutCount, this.valCount);\r\n if (!this.simulate) {\r\n try {\r\n this.mtbw.close();\r\n } catch (MutationsRejectedException var7) {\r\n if (var7.getAuthorizationFailuresMap().size() > 0) {\r\n Map tables = new HashMap();\r\n Map.Entry ke;\r\n Object secCodes;\r\n for (Iterator itr = var7.getAuthorizationFailuresMap().entrySet().iterator(); itr.hasNext(); ((Set) secCodes).addAll((Collection) ke.getValue())) {\r\n ke = (Map.Entry) itr.next();\r\n secCodes = (Set) tables.get(((KeyExtent) ke.getKey()).getTableId().toString());\r\n if (secCodes == null) {\r\n secCodes = new HashSet();\r\n tables.put(((KeyExtent) ke.getKey()).getTableId().toString(), secCodes);\r\n }\r\n }\r\n LOG.error(\"Not authorized to write to tables {}\", tables);\r\n }\r\n if (var7.getConstraintViolationSummaries().size() > 0) {\r\n LOG.error(\"Constraint violations : {}\", var7.getConstraintViolationSummaries().size());\r\n }\r\n throw new IOException(var7);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void addSummaryRows(List> result, String[] detailColumns, List rowPrefix, String[] aggregateColumns, SummaryValue[] summaryValues){\r\n final ArrayList> rows = new ArrayList<>(summaryValues.length + 1);\r\n String rowCount = null;\r\n for (int i = 0; i < aggregateColumns.length; i++) {\r\n final String aggregate = aggregateColumns[i];\r\n final String valueLabel = summaryValues[i].getLabel();\r\n if (ROW_COUNT.equals(aggregate)) {\r\n rowCount = valueLabel;\r\n } else {\r\n final List summaryRow = rowPrefix == null ? new ArrayList<>() : new ArrayList<>(rowPrefix);\r\n rows.add(summaryRow);\r\n for (int j = rowPrefix == null ? 0 : rowPrefix.size(); j < detailColumns.length; j++) {\r\n final String columnName = detailColumns[j];\r\n if (aggregate.endsWith(\"!\" + columnName)) {\r\n final StringBuilder valueBuilder = new StringBuilder();\r\n if (aggregate.startsWith(\"a!\")) {\r\n valueBuilder.append(\"avg \");\r\n } else if (aggregate.startsWith(\"mx!\")) {\r\n valueBuilder.append(\"max \");\r\n } else if (aggregate.startsWith(\"m!\")) {\r\n valueBuilder.append(\"min \");\r\n }\r\n valueBuilder.append(valueLabel);\r\n summaryRow.add(valueBuilder.toString());\r\n } else {\r\n summaryRow.add(EMPTY_VALUE);\r\n }\r\n }\r\n }\r\n }\r\n final List grandTotal = new ArrayList<>();\r\n result.add(grandTotal);\r\n if (rowCount != null) {\r\n grandTotal.add(\"Grand Totals (\" + rowCount + \" records)\");\r\n } else {\r\n grandTotal.add(\"Grand Totals\");\r\n }\r\n result.addAll(rows);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateProcessDefinitionJsonResourceList(){\r\n ProcessDefinitionDao processDefinitionDao = new ProcessDefinitionDao();\r\n Map replaceProcessDefinitionMap = new HashMap<>();\r\n try (Connection connection = dataSource.getConnection()) {\r\n Map resourcesMap = listAllResources(connection);\r\n Map processDefinitionJsonMap = processDefinitionDao.queryAllProcessDefinition(connection);\r\n for (Map.Entry entry : processDefinitionJsonMap.entrySet()) {\r\n ObjectNode jsonObject = JSONUtils.parseObject(entry.getValue());\r\n ArrayNode tasks = JSONUtils.parseArray(jsonObject.get(\"tasks\").toString());\r\n for (int i = 0; i < tasks.size(); i++) {\r\n ObjectNode task = (ObjectNode) tasks.get(i);\r\n ObjectNode param = (ObjectNode) task.get(\"params\");\r\n if (param != null) {\r\n List resourceList = JSONUtils.toList(param.get(\"resourceList\").toString(), ResourceInfo.class);\r\n ResourceInfo mainJar = JSONUtils.parseObject(param.get(\"mainJar\").toString(), ResourceInfo.class);\r\n if (mainJar != null && mainJar.getId() == null) {\r\n String fullName = mainJar.getRes().startsWith(\"/\") ? mainJar.getRes() : String.format(\"/%s\", mainJar.getRes());\r\n if (resourcesMap.containsKey(fullName)) {\r\n mainJar.setId(resourcesMap.get(fullName));\r\n param.put(\"mainJar\", JSONUtils.parseObject(JSONUtils.toJsonString(mainJar)));\r\n }\r\n }\r\n if (CollectionUtils.isNotEmpty(resourceList)) {\r\n List newResourceList = resourceList.stream().map(resInfo -> {\r\n String fullName = resInfo.getRes().startsWith(\"/\") ? resInfo.getRes() : String.format(\"/%s\", resInfo.getRes());\r\n if (resInfo.getId() == null && resourcesMap.containsKey(fullName)) {\r\n resInfo.setId(resourcesMap.get(fullName));\r\n }\r\n return resInfo;\r\n }).collect(Collectors.toList());\r\n param.put(\"resourceList\", JSONUtils.parseObject(JSONUtils.toJsonString(newResourceList)));\r\n }\r\n }\r\n task.put(\"params\", param);\r\n }\r\n jsonObject.remove(\"tasks\");\r\n jsonObject.put(\"tasks\", tasks);\r\n replaceProcessDefinitionMap.put(entry.getKey(), jsonObject.toString());\r\n }\r\n if (replaceProcessDefinitionMap.size() > 0) {\r\n processDefinitionDao.updateProcessDefinitionJson(connection, replaceProcessDefinitionMap);\r\n }\r\n } catch (Exception e) {\r\n log.error(\"update process definition json resource list error\", e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void check3Route2(Context context, Route route){\r\n if (!hasOppositeRoute(route, log))\r\n return;\r\n List areas = getStopAreaOfRouteFromRoutePoints(route);\r\n if (areas.isEmpty())\r\n return;\r\n StopArea firstChild = areas.get(0);\r\n StopArea lastChild = areas.get(areas.size() - 1);\r\n if (firstChild == null || lastChild == null)\r\n return;\r\n StopArea first = firstChild.getParent();\r\n StopArea last = lastChild.getParent();\r\n if (first == null || last == null)\r\n return;\r\n Route routeWb = route.getOppositeRoute();\r\n List areasWb = getStopAreaOfRouteFromRoutePoints(routeWb);\r\n if (!areasWb.isEmpty()) {\r\n StopArea firstWbChild = areasWb.get(0);\r\n StopArea lastWbChild = areasWb.get(areasWb.size() - 1);\r\n if (firstWbChild == null || lastWbChild == null)\r\n return;\r\n StopArea firstWb = firstWbChild.getParent();\r\n StopArea lastWb = lastWbChild.getParent();\r\n if (firstWb == null || lastWb == null)\r\n return;\r\n prepareCheckPoint(context, ROUTE_2);\r\n if (first.equals(lastWb) && last.equals(firstWb))\r\n return;\r\n DataLocation location = buildLocation(context, route);\r\n DataLocation target1 = null;\r\n DataLocation target2 = null;\r\n if (!first.equals(lastWb)) {\r\n target1 = buildLocation(context, first);\r\n target2 = buildLocation(context, lastWb);\r\n } else {\r\n target1 = buildLocation(context, firstWb);\r\n target2 = buildLocation(context, last);\r\n }\r\n ValidationReporter reporter = ValidationReporter.Factory.getInstance();\r\n reporter.addCheckPointReportError(context, ROUTE_2, location, null, null, target1, target2);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public long[] getUsageStats(){\r\n long dataOnHeap = 0L;\r\n long dataOnList = 0L;\r\n long metaOnHeap = 0L;\r\n long metaOnList = 0L;\r\n long listSize = 0L;\r\n long lockedData = 0L;\r\n long lockedMeta = 0L;\r\n long bpWrapCount = 0L;\r\n long bpWrapDistinct = 0L;\r\n long bpWrapData = 0L;\r\n long bpWrapMeta = 0L;\r\n Set bpWrapperBuffers = new HashSet<>();\r\n for (BPWrapper bpWrapper : bpWrappers.values()) {\r\n bpWrapper.lock.lock();\r\n try {\r\n bpWrapCount += bpWrapper.count;\r\n for (int i = 0; i < bpWrapper.count; ++i) {\r\n bpWrapperBuffers.add(bpWrapper.buffers[i]);\r\n }\r\n } finally {\r\n bpWrapper.lock.unlock();\r\n }\r\n }\r\n heapLock.lock();\r\n try {\r\n for (int heapIdx = 0; heapIdx < heapSize; ++heapIdx) {\r\n LlapCacheableBuffer buff = heap[heapIdx];\r\n if (null != buff) {\r\n if (buff instanceof LlapMetadataBuffer) {\r\n metaOnHeap += buff.getMemoryUsage();\r\n if (buff.isLocked()) {\r\n lockedMeta += buff.getMemoryUsage();\r\n }\r\n } else {\r\n dataOnHeap += buff.getMemoryUsage();\r\n if (buff.isLocked()) {\r\n lockedData += buff.getMemoryUsage();\r\n }\r\n }\r\n bpWrapperBuffers.remove(buff);\r\n }\r\n }\r\n } finally {\r\n heapLock.unlock();\r\n }\r\n try {\r\n listLock.lock();\r\n LlapCacheableBuffer scan = listHead;\r\n while (null != scan) {\r\n if (scan instanceof LlapMetadataBuffer) {\r\n metaOnList += scan.getMemoryUsage();\r\n if (scan.isLocked()) {\r\n lockedMeta += scan.getMemoryUsage();\r\n }\r\n } else {\r\n dataOnList += scan.getMemoryUsage();\r\n if (scan.isLocked()) {\r\n lockedData += scan.getMemoryUsage();\r\n }\r\n }\r\n bpWrapperBuffers.remove(scan);\r\n ++listSize;\r\n scan = scan.next;\r\n }\r\n } finally {\r\n listLock.unlock();\r\n }\r\n for (LlapCacheableBuffer buff : bpWrapperBuffers) {\r\n if (buff instanceof LlapMetadataBuffer) {\r\n bpWrapMeta += buff.getMemoryUsage();\r\n } else {\r\n bpWrapData += buff.getMemoryUsage();\r\n }\r\n ++bpWrapDistinct;\r\n }\r\n return new long[] { dataOnHeap, dataOnList, metaOnHeap, metaOnList, listSize, lockedData, lockedMeta, bpWrapCount, bpWrapDistinct, bpWrapData, bpWrapMeta };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void bind(CamelContext camelContext, String recordStr, Map model, int line) throws Exception{\r\n int pos = 1;\r\n int counterMandatoryFields = 0;\r\n DataField dataField;\r\n String token;\r\n int offset = 1;\r\n int length;\r\n String delimiter;\r\n Field field;\r\n final UnicodeHelper record = new UnicodeHelper(recordStr, (this.countGrapheme) ? UnicodeHelper.Method.GRAPHEME : UnicodeHelper.Method.CODEPOINTS);\r\n Collection c = dataFields.values();\r\n Iterator itr = c.iterator();\r\n while (itr.hasNext()) {\r\n dataField = itr.next();\r\n length = dataField.length();\r\n delimiter = dataField.delimiter();\r\n if (length == 0 && dataField.lengthPos() != 0) {\r\n Field lengthField = annotatedFields.get(dataField.lengthPos());\r\n lengthField.setAccessible(true);\r\n Object modelObj = model.get(lengthField.getDeclaringClass().getName());\r\n Object lengthObj = lengthField.get(modelObj);\r\n length = ((Integer) lengthObj).intValue();\r\n }\r\n if (length < 1 && delimiter == null && dataField.lengthPos() == 0) {\r\n throw new IllegalArgumentException(\"Either length or delimiter must be specified for the field : \" + dataField.toString());\r\n }\r\n if (offset - 1 <= -1) {\r\n throw new IllegalArgumentException(\"Offset/Position of the field \" + dataField.toString() + \" cannot be negative\");\r\n }\r\n if (dataField.pos() > offset) {\r\n LOG.debug(\"skipping ahead [{}] chars.\", dataField.pos() - offset);\r\n offset = dataField.pos();\r\n }\r\n if (length > 0) {\r\n if (record.length() < offset) {\r\n token = \"\";\r\n } else {\r\n int endIndex = offset + length - 1;\r\n if (endIndex > record.length()) {\r\n endIndex = record.length();\r\n }\r\n token = record.substring(offset - 1, endIndex);\r\n }\r\n offset += length;\r\n } else if (!delimiter.isEmpty()) {\r\n final UnicodeHelper tempToken = new UnicodeHelper(record.substring(offset - 1, record.length()), (this.countGrapheme) ? UnicodeHelper.Method.GRAPHEME : UnicodeHelper.Method.CODEPOINTS);\r\n token = tempToken.substring(0, tempToken.indexOf(delimiter));\r\n offset += token.length() + 1;\r\n } else {\r\n token = \"\";\r\n }\r\n if (dataField.trim()) {\r\n token = trim(token, dataField, paddingChar);\r\n }\r\n if (dataField.required()) {\r\n ++counterMandatoryFields;\r\n if (token.isEmpty()) {\r\n throw new IllegalArgumentException(\"The mandatory field defined at the position \" + pos + \" is empty for the line: \" + line);\r\n }\r\n }\r\n field = annotatedFields.get(dataField.pos());\r\n field.setAccessible(true);\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Pos/Offset: {}, Data: {}, Field type: {}\", offset, token, field.getType());\r\n }\r\n FormattingOptions formattingOptions = ConverterUtils.convert(dataField, field.getType(), field.getAnnotation(BindyConverter.class), getLocale());\r\n Format format = formatFactory.getFormat(formattingOptions);\r\n Object modelField = model.get(field.getDeclaringClass().getName());\r\n Object value;\r\n if (token.isEmpty()) {\r\n token = dataField.defaultValue();\r\n }\r\n if (!token.isEmpty()) {\r\n try {\r\n value = format.parse(token);\r\n } catch (FormatException ie) {\r\n throw new IllegalArgumentException(ie.getMessage() + \", position: \" + offset + \", line: \" + line, ie);\r\n } catch (Exception e) {\r\n throw new IllegalArgumentException(\"Parsing error detected for field defined at the position/offset: \" + offset + \", line: \" + line, e);\r\n }\r\n } else {\r\n value = getDefaultValueForPrimitive(field.getType());\r\n }\r\n if (value != null && !dataField.method().isEmpty()) {\r\n Class clazz;\r\n if (dataField.method().contains(\".\")) {\r\n clazz = camelContext.getClassResolver().resolveMandatoryClass(dataField.method().substring(0, dataField.method().lastIndexOf('.')));\r\n } else {\r\n clazz = field.getType();\r\n }\r\n String methodName = dataField.method().substring(dataField.method().lastIndexOf('.') + 1, dataField.method().length());\r\n Method m = ReflectionHelper.findMethod(clazz, methodName, field.getType());\r\n if (m != null) {\r\n value = ObjectHelper.invokeMethod(m, null, value);\r\n } else {\r\n m = ReflectionHelper.findMethod(clazz, methodName);\r\n value = ObjectHelper.invokeMethod(m, value);\r\n }\r\n }\r\n field.set(modelField, value);\r\n ++pos;\r\n }\r\n if (offset <= record.length() && !(record.substring(offset - 1, record.length())).trim().isEmpty() && !isIgnoreTrailingChars()) {\r\n throw new IllegalArgumentException(\"Unexpected / unmapped characters found at the end of the fixed-length record at line : \" + line);\r\n }\r\n LOG.debug(\"Counter mandatory fields: {}\", counterMandatoryFields);\r\n if (pos < totalFields) {\r\n throw new IllegalArgumentException(\"Some fields are missing (optional or mandatory), line: \" + line);\r\n }\r\n if (counterMandatoryFields < numberMandatoryFields) {\r\n throw new IllegalArgumentException(\"Some mandatory fields are missing, line: \" + line);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private SqlValidatorNamespace resolveImpl(SqlIdentifier id){\r\n final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher();\r\n final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl();\r\n final List names = SqlIdentifier.toStar(id.names);\r\n try {\r\n parentScope.resolveTable(names, nameMatcher, SqlValidatorScope.Path.EMPTY, resolved);\r\n } catch (CyclicDefinitionException e) {\r\n if (e.depth == 1) {\r\n throw validator.newValidationError(id, RESOURCE.cyclicDefinition(id.toString(), SqlIdentifier.getString(e.path)));\r\n } else {\r\n throw new CyclicDefinitionException(e.depth - 1, e.path);\r\n }\r\n }\r\n SqlValidatorScope.Resolve previousResolve = null;\r\n if (resolved.count() == 1) {\r\n final SqlValidatorScope.Resolve resolve = previousResolve = resolved.only();\r\n if (resolve.remainingNames.isEmpty()) {\r\n return resolve.namespace;\r\n }\r\n if (!nameMatcher.isCaseSensitive()) {\r\n throw validator.newValidationError(id, RESOURCE.objectNotFoundWithin(resolve.remainingNames.get(0), SqlIdentifier.getString(resolve.path.stepNames())));\r\n }\r\n }\r\n if (nameMatcher.isCaseSensitive()) {\r\n final SqlNameMatcher liberalMatcher = SqlNameMatchers.liberal();\r\n resolved.clear();\r\n parentScope.resolveTable(names, liberalMatcher, SqlValidatorScope.Path.EMPTY, resolved);\r\n if (resolved.count() == 1) {\r\n final SqlValidatorScope.Resolve resolve = resolved.only();\r\n if (resolve.remainingNames.isEmpty() || previousResolve == null) {\r\n final int i = previousResolve == null ? 0 : previousResolve.path.stepCount();\r\n final int offset = resolve.path.stepCount() + resolve.remainingNames.size() - names.size();\r\n final List prefix = resolve.path.stepNames().subList(0, offset + i);\r\n final String next = resolve.path.stepNames().get(i + offset);\r\n if (prefix.isEmpty()) {\r\n throw validator.newValidationError(id, RESOURCE.objectNotFoundDidYouMean(names.get(i), next));\r\n } else {\r\n throw validator.newValidationError(id, RESOURCE.objectNotFoundWithinDidYouMean(names.get(i), SqlIdentifier.getString(prefix), next));\r\n }\r\n } else {\r\n throw validator.newValidationError(id, RESOURCE.objectNotFoundWithin(resolve.remainingNames.get(0), SqlIdentifier.getString(resolve.path.stepNames())));\r\n }\r\n }\r\n }\r\n throw validator.newValidationError(id, RESOURCE.objectNotFound(id.getComponent(0).toString()));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void splitCorrelatedFilterCondition(Filter filter, RexNode condition, List joinKeys, List correlatedJoinKeys, List nonEquiList, boolean extractCorrelatedFieldAccess){\r\n if (condition instanceof RexCall) {\r\n RexCall call = (RexCall) condition;\r\n if (call.getOperator().getKind() == SqlKind.AND) {\r\n for (RexNode operand : call.getOperands()) {\r\n splitCorrelatedFilterCondition(filter, operand, joinKeys, correlatedJoinKeys, nonEquiList, extractCorrelatedFieldAccess);\r\n }\r\n return;\r\n }\r\n if (call.getOperator().getKind() == SqlKind.EQUALS) {\r\n final List operands = call.getOperands();\r\n RexNode op0 = operands.get(0);\r\n RexNode op1 = operands.get(1);\r\n if (extractCorrelatedFieldAccess) {\r\n if (!RexUtil.containsFieldAccess(op0) && op1 instanceof RexFieldAccess) {\r\n joinKeys.add(op0);\r\n correlatedJoinKeys.add(op1);\r\n return;\r\n } else if (op0 instanceof RexFieldAccess && !RexUtil.containsFieldAccess(op1)) {\r\n correlatedJoinKeys.add(op0);\r\n joinKeys.add(op1);\r\n return;\r\n }\r\n } else {\r\n if (!RexUtil.containsInputRef(op0) && op1 instanceof RexInputRef) {\r\n correlatedJoinKeys.add(op0);\r\n joinKeys.add(op1);\r\n return;\r\n } else if (op0 instanceof RexInputRef && !RexUtil.containsInputRef(op1)) {\r\n joinKeys.add(op0);\r\n correlatedJoinKeys.add(op1);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n nonEquiList.add(condition);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static RelBuilder convertSingletonDistinct(RelBuilder relBuilder, Aggregate aggregate, Set, Integer>> argLists){\r\n Preconditions.checkArgument(argLists.size() == 1);\r\n relBuilder.push(aggregate.getInput());\r\n final List originalAggCalls = aggregate.getAggCallList();\r\n final ImmutableBitSet originalGroupSet = aggregate.getGroupSet();\r\n final NavigableSet bottomGroups = new TreeSet<>(aggregate.getGroupSet().asList());\r\n for (AggregateCall aggCall : originalAggCalls) {\r\n if (aggCall.isDistinct()) {\r\n bottomGroups.addAll(aggCall.getArgList());\r\n break;\r\n }\r\n }\r\n final ImmutableBitSet bottomGroupSet = ImmutableBitSet.of(bottomGroups);\r\n final List bottomAggregateCalls = new ArrayList<>();\r\n for (AggregateCall aggCall : originalAggCalls) {\r\n if (!aggCall.isDistinct()) {\r\n final AggregateCall newCall = AggregateCall.create(aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, aggCall.getArgList(), -1, aggCall.distinctKeys, aggCall.collation, bottomGroupSet.cardinality(), relBuilder.peek(), null, aggCall.name);\r\n bottomAggregateCalls.add(newCall);\r\n }\r\n }\r\n relBuilder.push(aggregate.copy(aggregate.getTraitSet(), relBuilder.build(), bottomGroupSet, null, bottomAggregateCalls));\r\n final List topAggregateCalls = new ArrayList<>();\r\n int nonDistinctAggCallProcessedSoFar = 0;\r\n for (AggregateCall aggCall : originalAggCalls) {\r\n final AggregateCall newCall;\r\n if (aggCall.isDistinct()) {\r\n List newArgList = new ArrayList<>();\r\n for (int arg : aggCall.getArgList()) {\r\n newArgList.add(bottomGroups.headSet(arg, false).size());\r\n }\r\n newCall = AggregateCall.create(aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, newArgList, -1, aggCall.distinctKeys, aggCall.collation, originalGroupSet.cardinality(), relBuilder.peek(), aggCall.getType(), aggCall.name);\r\n } else {\r\n final int arg = bottomGroups.size() + nonDistinctAggCallProcessedSoFar;\r\n final List newArgs = ImmutableList.of(arg);\r\n if (aggCall.getAggregation().getKind() == SqlKind.COUNT) {\r\n newCall = AggregateCall.create(new SqlSumEmptyIsZeroAggFunction(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, newArgs, -1, aggCall.distinctKeys, aggCall.collation, originalGroupSet.cardinality(), relBuilder.peek(), null, aggCall.getName());\r\n } else {\r\n newCall = AggregateCall.create(aggCall.getAggregation(), false, aggCall.isApproximate(), aggCall.ignoreNulls(), aggCall.rexList, newArgs, -1, aggCall.distinctKeys, aggCall.collation, originalGroupSet.cardinality(), relBuilder.peek(), null, aggCall.name);\r\n }\r\n nonDistinctAggCallProcessedSoFar++;\r\n }\r\n topAggregateCalls.add(newCall);\r\n }\r\n final Set topGroupSet = new HashSet<>();\r\n int groupSetToAdd = 0;\r\n for (int bottomGroup : bottomGroups) {\r\n if (originalGroupSet.get(bottomGroup)) {\r\n topGroupSet.add(groupSetToAdd);\r\n }\r\n groupSetToAdd++;\r\n }\r\n relBuilder.push(aggregate.copy(aggregate.getTraitSet(), relBuilder.build(), ImmutableBitSet.of(topGroupSet), null, topAggregateCalls));\r\n relBuilder.convert(aggregate.getRowType(), true);\r\n return relBuilder;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean isSingleValue(SqlCall call){\r\n if (call.getOperator() instanceof SqlAggFunction) {\r\n return true;\r\n } else if (call.getOperator() instanceof SqlValuesOperator || call.getOperator() instanceof SqlRowOperator) {\r\n List operands = call.getOperandList();\r\n if (operands.size() == 1) {\r\n SqlNode operand = operands.get(0);\r\n if (operand instanceof SqlLiteral) {\r\n return true;\r\n } else if (operand instanceof SqlCall) {\r\n return isSingleValue((SqlCall) operand);\r\n }\r\n }\r\n return false;\r\n } else {\r\n boolean isScalar = true;\r\n for (SqlNode operand : call.getOperandList()) {\r\n if (operand instanceof SqlLiteral) {\r\n continue;\r\n }\r\n if (!(operand instanceof SqlCall) || !Util.isSingleValue((SqlCall) operand)) {\r\n isScalar = false;\r\n break;\r\n }\r\n }\r\n return isScalar;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static AlignedTVList deserialize(DataInputStream stream) throws IOException{\r\n int dataTypeNum = stream.readInt();\r\n List dataTypes = new ArrayList<>(dataTypeNum);\r\n for (int columnIndex = 0; columnIndex < dataTypeNum; ++columnIndex) {\r\n dataTypes.add(ReadWriteIOUtils.readDataType(stream));\r\n }\r\n int rowCount = stream.readInt();\r\n long[] times = new long[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n times[rowIndex] = stream.readLong();\r\n }\r\n Object[] values = new Object[dataTypeNum];\r\n BitMap[] bitMaps = new BitMap[dataTypeNum];\r\n for (int columnIndex = 0; columnIndex < dataTypeNum; ++columnIndex) {\r\n BitMap bitMap = new BitMap(rowCount);\r\n Object valuesOfOneColumn;\r\n switch(dataTypes.get(columnIndex)) {\r\n case TEXT:\r\n Binary[] binaryValues = new Binary[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n binaryValues[rowIndex] = ReadWriteIOUtils.readBinary(stream);\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = binaryValues;\r\n break;\r\n case FLOAT:\r\n float[] floatValues = new float[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n floatValues[rowIndex] = stream.readFloat();\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = floatValues;\r\n break;\r\n case INT32:\r\n int[] intValues = new int[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n intValues[rowIndex] = stream.readInt();\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = intValues;\r\n break;\r\n case INT64:\r\n long[] longValues = new long[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n longValues[rowIndex] = stream.readLong();\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = longValues;\r\n break;\r\n case DOUBLE:\r\n double[] doubleValues = new double[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n doubleValues[rowIndex] = stream.readDouble();\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = doubleValues;\r\n break;\r\n case BOOLEAN:\r\n boolean[] booleanValues = new boolean[rowCount];\r\n for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {\r\n booleanValues[rowIndex] = ReadWriteIOUtils.readBool(stream);\r\n if (ReadWriteIOUtils.readBool(stream)) {\r\n bitMap.mark(rowIndex);\r\n }\r\n }\r\n valuesOfOneColumn = booleanValues;\r\n break;\r\n default:\r\n throw new UnsupportedOperationException(ERR_DATATYPE_NOT_CONSISTENT);\r\n }\r\n values[columnIndex] = valuesOfOneColumn;\r\n bitMaps[columnIndex] = bitMap;\r\n }\r\n AlignedTVList tvList = AlignedTVList.newAlignedList(dataTypes);\r\n tvList.putAlignedValues(times, values, bitMaps, 0, rowCount);\r\n return tvList;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Result link(final SyncDelta delta, final List realms, final boolean unlink) throws JobExecutionException{\r\n if (!profile.getTask().isPerformUpdate()) {\r\n LOG.debug(\"PullTask not configured for update\");\r\n end(unlink ? MatchingRule.toEventName(MatchingRule.UNLINK) : MatchingRule.toEventName(MatchingRule.LINK), Result.SUCCESS, null, null, delta);\r\n return Result.SUCCESS;\r\n }\r\n LOG.debug(\"About to link {}\", realms);\r\n Result global = Result.SUCCESS;\r\n for (Realm realm : realms) {\r\n LOG.debug(\"About to unassign resource {}\", realm);\r\n ProvisioningReport result = new ProvisioningReport();\r\n result.setOperation(ResourceOperation.NONE);\r\n result.setAnyType(SyncopeConstants.REALM_ANYTYPE);\r\n result.setStatus(ProvisioningReport.Status.SUCCESS);\r\n result.setKey(realm.getKey());\r\n result.setName(realm.getFullPath());\r\n if (!profile.isDryRun()) {\r\n Object output;\r\n Result resultStatus;\r\n RealmTO before = binder.getRealmTO(realm, true);\r\n try {\r\n if (unlink) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeUnlink(profile, delta, before);\r\n }\r\n } else {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeLink(profile, delta, before);\r\n }\r\n }\r\n if (unlink) {\r\n realm.getResources().remove(profile.getTask().getResource());\r\n } else {\r\n realm.add(profile.getTask().getResource());\r\n }\r\n output = update(delta, List.of(realm), true);\r\n resultStatus = Result.SUCCESS;\r\n LOG.debug(\"{} successfully updated\", realm);\r\n } catch (PropagationException e) {\r\n LOG.error(\"Could not propagate Realm {}\", delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not update Realm {}\", delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n }\r\n end(unlink ? MatchingRule.toEventName(MatchingRule.UNLINK) : MatchingRule.toEventName(MatchingRule.LINK), resultStatus, before, output, delta);\r\n global = and(global, resultStatus);\r\n }\r\n profile.getResults().add(result);\r\n }\r\n return global;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List> analyzeSelect(Analysis analysis, QueryStatement queryStatement, ISchemaTree schemaTree, List deviceSet){\r\n List> outputExpressions = new ArrayList<>();\r\n Map> deviceToSelectExpressions = new HashMap<>();\r\n ColumnPaginationController paginationController = new ColumnPaginationController(queryStatement.getSeriesLimit(), queryStatement.getSeriesOffset(), false);\r\n for (ResultColumn resultColumn : queryStatement.getSelectComponent().getResultColumns()) {\r\n Expression selectExpression = resultColumn.getExpression();\r\n Map> measurementToDeviceSelectExpressions = new LinkedHashMap<>();\r\n for (PartialPath device : deviceSet) {\r\n List selectExpressionsOfOneDevice = ExpressionAnalyzer.concatDeviceAndBindSchemaForExpression(selectExpression, device, schemaTree);\r\n if (selectExpressionsOfOneDevice.isEmpty()) {\r\n continue;\r\n }\r\n updateMeasurementToDeviceSelectExpressions(analysis, measurementToDeviceSelectExpressions, device, selectExpressionsOfOneDevice);\r\n }\r\n checkAliasUniqueness(resultColumn.getAlias(), measurementToDeviceSelectExpressions);\r\n for (Map.Entry> measurementDeviceSelectExpressionsEntry : measurementToDeviceSelectExpressions.entrySet()) {\r\n Expression measurementExpression = measurementDeviceSelectExpressionsEntry.getKey();\r\n Map deviceToSelectExpressionsOfOneMeasurement = measurementDeviceSelectExpressionsEntry.getValue();\r\n if (paginationController.hasCurOffset()) {\r\n paginationController.consumeOffset();\r\n } else if (paginationController.hasCurLimit()) {\r\n deviceToSelectExpressionsOfOneMeasurement.values().forEach(expression -> analyzeExpressionType(analysis, expression));\r\n checkDataTypeConsistencyInAlignByDevice(analysis, new ArrayList<>(deviceToSelectExpressionsOfOneMeasurement.values()));\r\n Expression normalizedMeasurementExpression = ExpressionAnalyzer.toLowerCaseExpression(measurementExpression);\r\n analyzeExpressionType(analysis, normalizedMeasurementExpression);\r\n outputExpressions.add(new Pair<>(normalizedMeasurementExpression, analyzeAlias(resultColumn.getAlias(), measurementExpression, normalizedMeasurementExpression)));\r\n updateDeviceToSelectExpressions(analysis, deviceToSelectExpressions, deviceToSelectExpressionsOfOneMeasurement);\r\n paginationController.consumeLimit();\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n Set noMeasurementDevices = new HashSet<>();\r\n for (PartialPath device : deviceSet) {\r\n if (!deviceToSelectExpressions.containsKey(device.getFullPath())) {\r\n noMeasurementDevices.add(device);\r\n }\r\n }\r\n deviceSet.removeAll(noMeasurementDevices);\r\n if (analysis.getDeviceToWhereExpression() != null) {\r\n noMeasurementDevices.forEach(devicePath -> analysis.getDeviceToWhereExpression().remove(devicePath.getFullPath()));\r\n }\r\n analysis.setDeviceToSelectExpressions(deviceToSelectExpressions);\r\n Set selectExpressions = new LinkedHashSet<>();\r\n selectExpressions.add(deviceExpression);\r\n if (queryStatement.isOutputEndTime()) {\r\n selectExpressions.add(endTimeExpression);\r\n }\r\n selectExpressions.addAll(outputExpressions.stream().map(Pair::getLeft).collect(Collectors.toCollection(LinkedHashSet::new)));\r\n analysis.setSelectExpressions(selectExpressions);\r\n return outputExpressions;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic RelOptPredicateList getAllPredicates(Join join, RelMetadataQuery mq){\r\n if (join.getJoinType().isOuterJoin()) {\r\n return null;\r\n }\r\n final RexBuilder rexBuilder = join.getCluster().getRexBuilder();\r\n final RexNode pred = join.getCondition();\r\n final Multimap, RelTableRef> qualifiedNamesToRefs = HashMultimap.create();\r\n RelOptPredicateList newPreds = RelOptPredicateList.EMPTY;\r\n for (RelNode input : join.getInputs()) {\r\n final RelOptPredicateList inputPreds = mq.getAllPredicates(input);\r\n if (inputPreds == null) {\r\n return null;\r\n }\r\n final Set tableRefs = mq.getTableReferences(input);\r\n if (tableRefs == null) {\r\n return null;\r\n }\r\n if (input == join.getLeft()) {\r\n for (RelTableRef leftRef : tableRefs) {\r\n qualifiedNamesToRefs.put(leftRef.getQualifiedName(), leftRef);\r\n }\r\n newPreds = newPreds.union(rexBuilder, inputPreds);\r\n } else {\r\n final Map currentTablesMapping = new HashMap<>();\r\n for (RelTableRef rightRef : tableRefs) {\r\n int shift = 0;\r\n Collection lRefs = qualifiedNamesToRefs.get(rightRef.getQualifiedName());\r\n if (lRefs != null) {\r\n shift = lRefs.size();\r\n }\r\n currentTablesMapping.put(rightRef, RelTableRef.of(rightRef.getTable(), shift + rightRef.getEntityNumber()));\r\n }\r\n final List updatedPreds = Util.transform(inputPreds.pulledUpPredicates, e -> RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping));\r\n newPreds = newPreds.union(rexBuilder, RelOptPredicateList.of(rexBuilder, updatedPreds));\r\n }\r\n }\r\n final Set inputExtraFields = new LinkedHashSet<>();\r\n final RelOptUtil.InputFinder inputFinder = new RelOptUtil.InputFinder(inputExtraFields);\r\n pred.accept(inputFinder);\r\n final ImmutableBitSet inputFieldsUsed = inputFinder.build();\r\n final Map> mapping = new LinkedHashMap<>();\r\n final RelDataType fullRowType = SqlValidatorUtil.createJoinType(rexBuilder.getTypeFactory(), join.getLeft().getRowType(), join.getRight().getRowType(), null, ImmutableList.of());\r\n for (int idx : inputFieldsUsed) {\r\n final RexInputRef inputRef = RexInputRef.of(idx, fullRowType.getFieldList());\r\n final Set originalExprs = mq.getExpressionLineage(join, inputRef);\r\n if (originalExprs == null) {\r\n return null;\r\n }\r\n final RexInputRef ref = RexInputRef.of(idx, fullRowType.getFieldList());\r\n mapping.put(ref, originalExprs);\r\n }\r\n final Set allExprs = RelMdExpressionLineage.createAllPossibleExpressions(rexBuilder, pred, mapping);\r\n if (allExprs == null) {\r\n return null;\r\n }\r\n return newPreds.union(rexBuilder, RelOptPredicateList.of(rexBuilder, allExprs));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void terminate(TerminationMode mode){\r\n if (mode != TerminationMode.CANCEL_FORCEFUL) {\r\n checkNotLightJob(mode.toString());\r\n }\r\n logger.fine(\"Sending \" + mode + \" request for job \" + idAndName());\r\n while (true) {\r\n try {\r\n try {\r\n invokeTerminateJob(mode).get();\r\n break;\r\n } catch (ExecutionException e) {\r\n if (!(e.getCause() instanceof JobNotFoundException) || !isLightJob()) {\r\n throw e;\r\n }\r\n if (submittingInstance) {\r\n assert joinedJob.get() : \"not joined\";\r\n if (getFuture().isDone()) {\r\n return;\r\n }\r\n } else {\r\n return;\r\n }\r\n }\r\n LockSupport.parkNanos(TERMINATE_RETRY_DELAY_NS);\r\n } catch (Exception e) {\r\n if (!isRestartable(e)) {\r\n throw rethrow(e);\r\n }\r\n logger.fine(\"Re-sending \" + mode + \" request for job \" + idAndName());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static MavenClassLoader createClassLoader(File[] jars){\r\n final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();\r\n URLClassLoader cl = AccessController.doPrivileged(new PrivilegedAction() {\r\n\r\n @Override\r\n public URLClassLoader run() {\r\n return new URLClassLoader(Arrays.stream(jars).map((f) -> {\r\n try {\r\n return f.toURI().toURL();\r\n } catch (Throwable t) {\r\n throw new RuntimeException(t);\r\n }\r\n }).toArray(URL[]::new), systemClassLoader) {\r\n\r\n @Override\r\n protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {\r\n Class loadedClass = findLoadedClass(name);\r\n if (loadedClass == null) {\r\n try {\r\n loadedClass = findClass(name);\r\n } catch (ClassNotFoundException ignored) {\r\n }\r\n if (loadedClass == null) {\r\n try {\r\n loadedClass = systemClassLoader.loadClass(name);\r\n } catch (ClassNotFoundException e) {\r\n }\r\n }\r\n }\r\n if (resolve && loadedClass != null) {\r\n resolveClass(loadedClass);\r\n }\r\n return loadedClass;\r\n }\r\n };\r\n }\r\n });\r\n return new MavenClassLoader(cl);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SqlMonotonicity getMonotonicity(SqlOperatorBinding call){\r\n final SqlMonotonicity mono0 = call.getOperandMonotonicity(0);\r\n final SqlMonotonicity mono1 = call.getOperandMonotonicity(1);\r\n if ((mono1 == SqlMonotonicity.CONSTANT) && (mono0 == SqlMonotonicity.CONSTANT)) {\r\n return SqlMonotonicity.CONSTANT;\r\n }\r\n if (mono1 == SqlMonotonicity.CONSTANT) {\r\n if (getName().equals(\"-\") || getName().equals(\"+\")) {\r\n return mono0;\r\n }\r\n assert getName().equals(\"*\");\r\n BigDecimal value = call.getOperandLiteralValue(1, BigDecimal.class);\r\n switch(value == null ? 1 : value.signum()) {\r\n case -1:\r\n return mono0.reverse();\r\n case 0:\r\n return SqlMonotonicity.CONSTANT;\r\n default:\r\n return mono0;\r\n }\r\n }\r\n if (mono0 == SqlMonotonicity.CONSTANT) {\r\n if (getName().equals(\"-\")) {\r\n return mono1.reverse();\r\n }\r\n if (getName().equals(\"+\")) {\r\n return mono1;\r\n }\r\n assert getName().equals(\"*\");\r\n if (!call.isOperandNull(0, true)) {\r\n BigDecimal value = call.getOperandLiteralValue(0, BigDecimal.class);\r\n switch(value == null ? 1 : value.signum()) {\r\n case -1:\r\n return mono1.reverse();\r\n case 0:\r\n return SqlMonotonicity.CONSTANT;\r\n default:\r\n return mono1;\r\n }\r\n }\r\n }\r\n if (getName().equals(\"+\")) {\r\n if (mono0 == mono1) {\r\n return mono0;\r\n } else if (mono0.unstrict() == mono1.unstrict()) {\r\n return mono0.unstrict();\r\n } else {\r\n return SqlMonotonicity.NOT_MONOTONIC;\r\n }\r\n }\r\n if (getName().equals(\"-\")) {\r\n if (mono0 == mono1.reverse()) {\r\n return mono0;\r\n } else if (mono0.unstrict() == mono1.reverse().unstrict()) {\r\n return mono0.unstrict();\r\n } else {\r\n return SqlMonotonicity.NOT_MONOTONIC;\r\n }\r\n }\r\n if (getName().equals(\"*\")) {\r\n return SqlMonotonicity.NOT_MONOTONIC;\r\n }\r\n return super.getMonotonicity(call);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " String determineHost(final OpenAPI openApi, Operation operation){\r\n if (isNotEmpty(host)) {\r\n return host;\r\n }\r\n final String componentHost = component().getHost();\r\n if (isNotEmpty(componentHost)) {\r\n return componentHost;\r\n }\r\n URI absoluteURI = null;\r\n URI relativeURI = null;\r\n Set operationURIs = getURIs(operation.getServers());\r\n Optional opURI = operationURIs.stream().filter(uri -> uri.isAbsolute()).findFirst();\r\n if (opURI.isEmpty()) {\r\n Set apiURIs = getURIs(openApi.getServers());\r\n for (URI uri : apiURIs) {\r\n if (uri.isAbsolute()) {\r\n absoluteURI = uri;\r\n } else {\r\n relativeURI = uri;\r\n }\r\n }\r\n for (URI uri : operationURIs) {\r\n if (absoluteURI != null) {\r\n absoluteURI = absoluteURI.resolve(uri);\r\n } else if (relativeURI != null && !relativeURI.equals(uri)) {\r\n relativeURI = relativeURI.resolve(uri);\r\n } else {\r\n relativeURI = uri;\r\n }\r\n }\r\n } else {\r\n absoluteURI = opURI.get();\r\n }\r\n if (absoluteURI != null) {\r\n return absoluteURI.toString();\r\n }\r\n final CamelContext camelContext = getCamelContext();\r\n final RestConfiguration globalRestConfiguration = CamelContextHelper.getRestConfiguration(camelContext, null, determineComponentName());\r\n final String globalConfigurationHost = hostFrom(globalRestConfiguration);\r\n if (globalConfigurationHost != null) {\r\n return globalConfigurationHost;\r\n }\r\n final String specificationScheme = specificationUri.getScheme();\r\n String prefix = \"http\";\r\n if (specificationUri.isAbsolute() && specificationScheme.regionMatches(true, 0, prefix, 0, prefix.length())) {\r\n try {\r\n return new URI(specificationUri.getScheme(), specificationUri.getUserInfo(), specificationUri.getHost(), specificationUri.getPort(), null, null, null).toString();\r\n } catch (final URISyntaxException e) {\r\n throw new IllegalStateException(\"Unable to create a new URI from: \" + specificationUri, e);\r\n }\r\n }\r\n throw new IllegalStateException(\"Unable to determine destination host for requests. The OpenApi specification\" + \" does not specify `scheme` and `host` parameters, the specification URI is not absolute with `http` or\" + \" `https` scheme, and no RestConfigurations configured with `scheme`, `host` and `port` were found for `\" + (determineComponentName() != null ? determineComponentName() : \"default\" + \"` component\") + \" and there is no global RestConfiguration with those properties\");\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void handleMapNode(Node parentNode, final MapConfig mapConfig) throws Exception{\r\n for (Node node : childElements(parentNode)) {\r\n String nodeName = cleanNodeName(node);\r\n if (matches(\"backup-count\", nodeName)) {\r\n mapConfig.setBackupCount(getIntegerValue(\"backup-count\", getTextContent(node)));\r\n } else if (matches(\"metadata-policy\", nodeName)) {\r\n mapConfig.setMetadataPolicy(MetadataPolicy.valueOf(upperCaseInternal(getTextContent(node))));\r\n } else if (matches(\"in-memory-format\", nodeName)) {\r\n mapConfig.setInMemoryFormat(InMemoryFormat.valueOf(upperCaseInternal(getTextContent(node))));\r\n } else if (matches(\"async-backup-count\", nodeName)) {\r\n mapConfig.setAsyncBackupCount(getIntegerValue(\"async-backup-count\", getTextContent(node)));\r\n } else if (matches(\"eviction\", nodeName)) {\r\n mapConfig.setEvictionConfig(getEvictionConfig(node, false, true));\r\n } else if (matches(\"time-to-live-seconds\", nodeName)) {\r\n mapConfig.setTimeToLiveSeconds(getIntegerValue(\"time-to-live-seconds\", getTextContent(node)));\r\n } else if (matches(\"max-idle-seconds\", nodeName)) {\r\n mapConfig.setMaxIdleSeconds(getIntegerValue(\"max-idle-seconds\", getTextContent(node)));\r\n } else if (matches(\"map-store\", nodeName)) {\r\n handleMapStoreConfig(node, mapConfig.getMapStoreConfig());\r\n } else if (matches(\"near-cache\", nodeName)) {\r\n mapConfig.setNearCacheConfig(handleNearCacheConfig(node, mapConfig.getNearCacheConfig()));\r\n } else if (matches(\"merge-policy\", nodeName)) {\r\n MergePolicyConfig mpConfig = createMergePolicyConfig(node, mapConfig.getMergePolicyConfig());\r\n mapConfig.setMergePolicyConfig(mpConfig);\r\n } else if (matches(\"merkle-tree\", nodeName)) {\r\n handleViaReflection(node, mapConfig, mapConfig.getMerkleTreeConfig());\r\n } else if (matches(\"event-journal\", nodeName)) {\r\n handleViaReflection(node, mapConfig, mapConfig.getEventJournalConfig());\r\n } else if (matches(\"hot-restart\", nodeName)) {\r\n mapConfig.setHotRestartConfig(createHotRestartConfig(node));\r\n } else if (matches(\"data-persistence\", nodeName)) {\r\n mapConfig.setDataPersistenceConfig(createDataPersistenceConfig(node));\r\n } else if (matches(\"read-backup-data\", nodeName)) {\r\n mapConfig.setReadBackupData(getBooleanValue(getTextContent(node)));\r\n } else if (matches(\"statistics-enabled\", nodeName)) {\r\n mapConfig.setStatisticsEnabled(getBooleanValue(getTextContent(node)));\r\n } else if (matches(\"per-entry-stats-enabled\", nodeName)) {\r\n mapConfig.setPerEntryStatsEnabled(getBooleanValue(getTextContent(node)));\r\n } else if (matches(\"cache-deserialized-values\", nodeName)) {\r\n CacheDeserializedValues cacheDeserializedValues = CacheDeserializedValues.parseString(getTextContent(node));\r\n mapConfig.setCacheDeserializedValues(cacheDeserializedValues);\r\n } else if (matches(\"wan-replication-ref\", nodeName)) {\r\n mapWanReplicationRefHandle(node, mapConfig);\r\n } else if (matches(\"indexes\", nodeName)) {\r\n mapIndexesHandle(node, mapConfig);\r\n } else if (matches(\"attributes\", nodeName)) {\r\n attributesHandle(node, mapConfig);\r\n } else if (matches(\"entry-listeners\", nodeName)) {\r\n handleEntryListeners(node, mapConfig::addEntryListenerConfig);\r\n } else if (matches(\"partition-lost-listeners\", nodeName)) {\r\n mapPartitionLostListenerHandle(node, mapConfig);\r\n } else if (matches(\"partition-strategy\", nodeName)) {\r\n mapConfig.setPartitioningStrategyConfig(new PartitioningStrategyConfig(getTextContent(node)));\r\n } else if (matches(\"split-brain-protection-ref\", nodeName)) {\r\n mapConfig.setSplitBrainProtectionName(getTextContent(node));\r\n } else if (matches(\"query-caches\", nodeName)) {\r\n mapQueryCacheHandler(node, mapConfig);\r\n } else if (matches(\"tiered-store\", nodeName)) {\r\n mapConfig.setTieredStoreConfig(createTieredStoreConfig(node));\r\n } else if (matches(\"partition-attributes\", nodeName)) {\r\n handlePartitionAttributes(node, mapConfig);\r\n }\r\n }\r\n config.addMapConfig(mapConfig);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static Class getEntityReference(final Class reference){\r\n return AccountPolicy.class.isAssignableFrom(reference) ? JPAAccountPolicy.class : PasswordPolicy.class.isAssignableFrom(reference) ? JPAPasswordPolicy.class : PropagationPolicy.class.isAssignableFrom(reference) ? JPAPropagationPolicy.class : PullPolicy.class.isAssignableFrom(reference) ? JPAPullPolicy.class : PushPolicy.class.isAssignableFrom(reference) ? JPAPushPolicy.class : AuthPolicy.class.isAssignableFrom(reference) ? JPAAuthPolicy.class : AccessPolicy.class.isAssignableFrom(reference) ? JPAAccessPolicy.class : AttrReleasePolicy.class.isAssignableFrom(reference) ? JPAAttrReleasePolicy.class : TicketExpirationPolicy.class.isAssignableFrom(reference) ? JPATicketExpirationPolicy.class : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public MethodInvocation createInvocation(Object pojo, Exchange exchange) throws AmbiguousMethodCallException, MethodNotFoundException{\r\n MethodInfo methodInfo = null;\r\n String methodName = exchange.getIn().getHeader(BeanConstants.BEAN_METHOD_NAME, String.class);\r\n if (methodName != null) {\r\n String name = methodName;\r\n if (methodName.contains(\"(\")) {\r\n name = StringHelper.before(methodName, \"(\");\r\n if (!methodName.endsWith(\")\")) {\r\n throw new IllegalArgumentException(\"Method should end with parenthesis, was \" + methodName);\r\n }\r\n if (StringHelper.betweenOuterPair(methodName, '(', ')') == null) {\r\n throw new IllegalArgumentException(\"Method should have even pair of parenthesis, was \" + methodName);\r\n }\r\n }\r\n boolean emptyParameters = methodName.endsWith(\"()\");\r\n if (\"class\".equals(name) || \"getClass\".equals(name)) {\r\n try {\r\n Method method = pojo.getClass().getMethod(\"getClass\");\r\n methodInfo = new MethodInfo(exchange.getContext(), pojo.getClass(), method, Collections.emptyList(), Collections.emptyList(), false, false);\r\n } catch (NoSuchMethodException e) {\r\n throw new MethodNotFoundException(exchange, pojo, \"getClass\");\r\n }\r\n } else if (\"length\".equals(name) && pojo.getClass().isArray()) {\r\n try {\r\n Method method = org.apache.camel.util.ObjectHelper.class.getMethod(\"arrayLength\", Object[].class);\r\n ParameterInfo pi = new ParameterInfo(0, Object[].class, null, ExpressionBuilder.mandatoryBodyExpression(Object[].class, true));\r\n List lpi = new ArrayList<>(1);\r\n lpi.add(pi);\r\n methodInfo = new MethodInfo(exchange.getContext(), pojo.getClass(), method, lpi, lpi, false, false);\r\n exchange.getIn().setBody(pojo);\r\n } catch (NoSuchMethodException e) {\r\n throw new MethodNotFoundException(exchange, pojo, \"getClass\");\r\n }\r\n } else {\r\n List methods = getOperations(name);\r\n if (methods != null && methods.size() == 1) {\r\n methodInfo = methods.get(0);\r\n if (emptyParameters && methodInfo.hasParameters()) {\r\n throw new MethodNotFoundException(exchange, pojo, methodName, \"(with no parameters)\");\r\n }\r\n } else if (methods != null) {\r\n methodInfo = chooseMethod(pojo, exchange, methodName);\r\n if (emptyParameters) {\r\n if (methodInfo == null || methodInfo.hasParameters()) {\r\n throw new MethodNotFoundException(exchange, pojo, methodName, \"(with no parameters)\");\r\n }\r\n }\r\n if (methodInfo == null || !name.equals(methodInfo.getMethod().getName())) {\r\n throw new AmbiguousMethodCallException(exchange, methods);\r\n }\r\n } else {\r\n throw new MethodNotFoundException(exchange, pojo, methodName);\r\n }\r\n }\r\n }\r\n if (methodInfo == null && methodMap.size() >= 2) {\r\n methodInfo = chooseMethod(pojo, exchange, null);\r\n }\r\n if (methodInfo == null) {\r\n methodInfo = defaultMethod;\r\n }\r\n if (methodInfo != null) {\r\n LOG.trace(\"Chosen method to invoke: {} on bean: {}\", methodInfo, pojo);\r\n return methodInfo.createMethodInvocation(pojo, methodInfo.hasParameters(), exchange);\r\n }\r\n LOG.debug(\"Cannot find suitable method to invoke on bean: {}\", pojo);\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void verifyRequest(Exchange exchange){\r\n if (exchange.getIn().getHeader(Exchange.SAGA_LONG_RUNNING_ACTION) == null) {\r\n throw new IllegalArgumentException(\"Missing \" + Exchange.SAGA_LONG_RUNNING_ACTION + \" header in received request\");\r\n }\r\n Set usedURIs = new HashSet<>();\r\n String compensationURI = exchange.getIn().getHeader(URL_COMPENSATION_KEY, String.class);\r\n if (compensationURI != null) {\r\n usedURIs.add(compensationURI);\r\n }\r\n String completionURI = exchange.getIn().getHeader(URL_COMPLETION_KEY, String.class);\r\n if (completionURI != null) {\r\n usedURIs.add(completionURI);\r\n }\r\n if (usedURIs.isEmpty()) {\r\n try {\r\n Map queryParams = URISupport.parseQuery(exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class));\r\n if (!queryParams.isEmpty()) {\r\n if (queryParams.get(URL_COMPENSATION_KEY) != null) {\r\n compensationURI = queryParams.get(URL_COMPENSATION_KEY).toString();\r\n usedURIs.add(compensationURI);\r\n exchange.getIn().setHeader(URL_COMPENSATION_KEY, compensationURI);\r\n }\r\n if (queryParams.get(URL_COMPLETION_KEY) != null) {\r\n completionURI = queryParams.get(URL_COMPLETION_KEY).toString();\r\n usedURIs.add(completionURI);\r\n exchange.getIn().setHeader(URL_COMPLETION_KEY, completionURI);\r\n }\r\n }\r\n } catch (URISyntaxException ex) {\r\n throw new RuntimeCamelException(\"URISyntaxException during \" + Exchange.HTTP_QUERY + \" header parsing\");\r\n }\r\n }\r\n for (String uri : usedURIs) {\r\n if (!sagaService.getRegisteredURIs().contains(uri)) {\r\n throw new IllegalArgumentException(\"URI \" + uri + \" is not allowed\");\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean handler(ServerConfiguration conf, QFlags flag) throws Exception{\r\n runFunctionWithLedgerManagerFactory(conf, mFactory -> {\r\n LedgerUnderreplicationManager underreplicationManager;\r\n LedgerManager ledgerManager = mFactory.newLedgerManager();\r\n List ledgerList = new LinkedList<>();\r\n try {\r\n underreplicationManager = mFactory.newLedgerUnderreplicationManager();\r\n } catch (ReplicationException e) {\r\n throw new UncheckedExecutionException(\"Failed to new ledger underreplicated manager\", e);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n throw new UncheckedExecutionException(\"Interrupted on newing ledger underreplicated manager\", e);\r\n }\r\n Iterator iter = underreplicationManager.listLedgersToRereplicate(null);\r\n while (iter.hasNext()) {\r\n UnderreplicatedLedger underreplicatedLedger = iter.next();\r\n long urLedgerId = underreplicatedLedger.getLedgerId();\r\n try {\r\n String replicationWorkerId = underreplicationManager.getReplicationWorkerIdRereplicatingLedger(urLedgerId);\r\n if (replicationWorkerId != null) {\r\n ledgerList.add(new LedgerRecoverInfo(urLedgerId, replicationWorkerId));\r\n }\r\n } catch (ReplicationException.UnavailableException e) {\r\n LOG.error(\"Failed to get ReplicationWorkerId rereplicating ledger {} -- {}\", urLedgerId, e.getMessage());\r\n }\r\n }\r\n LOG.info(\"CurrentRecoverLedgerInfo:\");\r\n if (!flag.verbose) {\r\n for (int i = 0; i < ledgerList.size(); i++) {\r\n LOG.info(\"\\tLedgerId:{}\\tBookieId:{}\", ledgerList.get(i).ledgerId, ledgerList.get(i).bookieId);\r\n }\r\n } else {\r\n for (int i = 0; i < ledgerList.size(); i++) {\r\n LedgerRecoverInfo info = ledgerList.get(i);\r\n ledgerManager.readLedgerMetadata(info.ledgerId).whenComplete((metadata, exception) -> {\r\n if (exception == null) {\r\n LOG.info(\"\\tLedgerId:{}\\tBookieId:{}\\tLedgerSize:{}\", info.ledgerId, info.bookieId, metadata.getValue().getLength());\r\n } else {\r\n LOG.error(\"Unable to read the ledger: {} information\", info.ledgerId);\r\n throw new UncheckedExecutionException(exception);\r\n }\r\n });\r\n }\r\n }\r\n if (ledgerList.size() == 0) {\r\n LOG.info(\"\\t No Ledger is being recovered.\");\r\n }\r\n return null;\r\n });\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean processInOnly(final Exchange exchange, final AsyncCallback callback){\r\n final org.apache.camel.Message in = exchange.getIn();\r\n String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class);\r\n if (destinationName != null) {\r\n in.removeHeader(JmsConstants.JMS_DESTINATION_NAME);\r\n }\r\n if (destinationName == null) {\r\n destinationName = endpoint.getDestinationName();\r\n }\r\n Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class);\r\n if (destination != null) {\r\n in.removeHeader(JmsConstants.JMS_DESTINATION);\r\n }\r\n if (destination != null) {\r\n destinationName = null;\r\n }\r\n final String to = destinationName != null ? destinationName : String.valueOf(destination);\r\n MessageSentCallback messageSentCallback = getEndpoint().getConfiguration().isIncludeSentJMSMessageID() ? new InOnlyMessageSentCallback(exchange) : null;\r\n MessageCreator messageCreator = new MessageCreator() {\r\n\r\n public Message createMessage(Session session) throws JMSException {\r\n Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null);\r\n Object jmsReplyTo = JmsMessageHelper.getJMSReplyTo(answer);\r\n if (endpoint.isDisableReplyTo()) {\r\n LOG.trace(\"ReplyTo is disabled on endpoint: {}\", endpoint);\r\n JmsMessageHelper.setJMSReplyTo(answer, null);\r\n } else {\r\n if (jmsReplyTo == null) {\r\n jmsReplyTo = exchange.getIn().getHeader(JmsConstants.JMS_HEADER_REPLY_TO, String.class);\r\n if (jmsReplyTo == null) {\r\n jmsReplyTo = endpoint.getReplyTo();\r\n }\r\n }\r\n }\r\n if (jmsReplyTo != null && !(endpoint.isPreserveMessageQos() || endpoint.isExplicitQosEnabled())) {\r\n LOG.debug(\"Disabling JMSReplyTo: {} for destination: {}. Use preserveMessageQos=true to force Camel to keep the JMSReplyTo on endpoint: {}\", jmsReplyTo, to, endpoint);\r\n jmsReplyTo = null;\r\n }\r\n if (jmsReplyTo instanceof String) {\r\n String replyTo = (String) jmsReplyTo;\r\n jmsReplyTo = resolveOrCreateDestination(replyTo, session);\r\n }\r\n Destination replyTo = null;\r\n String replyToOverride = endpoint.getConfiguration().getReplyToOverride();\r\n if (replyToOverride != null) {\r\n replyTo = resolveOrCreateDestination(replyToOverride, session);\r\n } else if (jmsReplyTo instanceof Destination) {\r\n replyTo = (Destination) jmsReplyTo;\r\n }\r\n if (replyTo != null) {\r\n LOG.debug(\"Using JMSReplyTo destination: {}\", replyTo);\r\n JmsMessageHelper.setJMSReplyTo(answer, replyTo);\r\n } else {\r\n LOG.trace(\"Not using JMSReplyTo\");\r\n JmsMessageHelper.setJMSReplyTo(answer, null);\r\n }\r\n LOG.trace(\"Created jakarta.jms.Message: {}\", answer);\r\n return answer;\r\n }\r\n };\r\n doSend(false, destinationName, destination, messageCreator, messageSentCallback);\r\n setMessageId(exchange);\r\n callback.done(true);\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void main(String[] args) throws IOException{\r\n if (!checkArgs(args)) {\r\n System.exit(1);\r\n }\r\n if (printToFile) {\r\n pw = new PrintWriter(new FileWriter(outFilePath));\r\n }\r\n if (printDetails) {\r\n printBoth(\"Start checking seq files ...\");\r\n }\r\n for (File f : fileList) {\r\n findUncorrectFiles(Collections.singletonList(f));\r\n }\r\n for (File seqDataDir : seqDataDirList) {\r\n if (!checkIsDirectory(seqDataDir)) {\r\n continue;\r\n }\r\n File[] sgDirs = seqDataDir.listFiles();\r\n for (File sgDir : Objects.requireNonNull(sgDirs)) {\r\n if (!checkIsDirectory(sgDir)) {\r\n continue;\r\n }\r\n if (printDetails) {\r\n printBoth(\"- Check files in database: \" + sgDir.getAbsolutePath());\r\n }\r\n File[] dataRegionDirs = sgDir.listFiles();\r\n for (File dataRegionDir : Objects.requireNonNull(dataRegionDirs)) {\r\n if (!checkIsDirectory(dataRegionDir)) {\r\n continue;\r\n }\r\n List timePartitionDirs = Arrays.asList(Objects.requireNonNull(dataRegionDir.listFiles())).stream().filter(file -> Pattern.compile(\"[0-9]*\").matcher(file.getName()).matches()).collect(Collectors.toList());\r\n timePartitionDirs.sort((f1, f2) -> Long.compareUnsigned(Long.parseLong(f1.getName()), Long.parseLong(f2.getName())));\r\n for (File timePartitionDir : Objects.requireNonNull(timePartitionDirs)) {\r\n if (!checkIsDirectory(timePartitionDir)) {\r\n continue;\r\n }\r\n List tsFiles = Arrays.asList(Objects.requireNonNull(timePartitionDir.listFiles(file -> file.getName().endsWith(TSFILE_SUFFIX))));\r\n tsFiles.sort((f1, f2) -> {\r\n int timeDiff = Long.compareUnsigned(Long.parseLong(f1.getName().split(\"-\")[0]), Long.parseLong(f2.getName().split(\"-\")[0]));\r\n return timeDiff == 0 ? Long.compareUnsigned(Long.parseLong(f1.getName().split(\"-\")[1]), Long.parseLong(f2.getName().split(\"-\")[1])) : timeDiff;\r\n });\r\n findUncorrectFiles(tsFiles);\r\n }\r\n clearMap(false);\r\n }\r\n }\r\n }\r\n if (printDetails) {\r\n printBoth(\"Finish checking successfully, totally find \" + badFileNum + \" bad files.\");\r\n }\r\n if (printToFile) {\r\n pw.close();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void normalise(final int[] band, final Codec codecUsed){\r\n if (codecUsed instanceof BHSDCodec) {\r\n final BHSDCodec bhsd = (BHSDCodec) codecUsed;\r\n if (bhsd.isDelta()) {\r\n final long cardinality = bhsd.cardinality();\r\n for (int i = 0; i < band.length; i++) {\r\n while (band[i] > bhsd.largest()) {\r\n band[i] -= cardinality;\r\n }\r\n while (band[i] < bhsd.smallest()) {\r\n band[i] = ExactMath.add(band[i], cardinality);\r\n }\r\n }\r\n }\r\n } else if (codecUsed instanceof PopulationCodec) {\r\n final PopulationCodec popCodec = (PopulationCodec) codecUsed;\r\n final int[] favoured = popCodec.getFavoured().clone();\r\n Arrays.sort(favoured);\r\n for (int i = 0; i < band.length; i++) {\r\n final boolean favouredValue = Arrays.binarySearch(favoured, band[i]) > -1;\r\n final Codec theCodec = favouredValue ? popCodec.getFavouredCodec() : popCodec.getUnfavouredCodec();\r\n if (theCodec instanceof BHSDCodec) {\r\n final BHSDCodec bhsd = (BHSDCodec) theCodec;\r\n if (bhsd.isDelta()) {\r\n final long cardinality = bhsd.cardinality();\r\n while (band[i] > bhsd.largest()) {\r\n band[i] -= cardinality;\r\n }\r\n while (band[i] < bhsd.smallest()) {\r\n band[i] = ExactMath.add(band[i], cardinality);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List concatExpressionWithSuffixPaths(Expression expression, List prefixPaths){\r\n Set resultPaths = new HashSet<>();\r\n if (expression instanceof TernaryExpression) {\r\n List firstExpressions = concatExpressionWithSuffixPaths(((TernaryExpression) expression).getFirstExpression(), prefixPaths);\r\n List secondExpressions = concatExpressionWithSuffixPaths(((TernaryExpression) expression).getSecondExpression(), prefixPaths);\r\n List thirdExpressions = concatExpressionWithSuffixPaths(((TernaryExpression) expression).getThirdExpression(), prefixPaths);\r\n resultPaths.addAll(firstExpressions);\r\n resultPaths.addAll(secondExpressions);\r\n resultPaths.addAll(thirdExpressions);\r\n return new ArrayList<>(resultPaths);\r\n } else if (expression instanceof BinaryExpression) {\r\n List leftExpressions = concatExpressionWithSuffixPaths(((BinaryExpression) expression).getLeftExpression(), prefixPaths);\r\n List rightExpressions = concatExpressionWithSuffixPaths(((BinaryExpression) expression).getRightExpression(), prefixPaths);\r\n resultPaths.addAll(leftExpressions);\r\n resultPaths.addAll(rightExpressions);\r\n return new ArrayList<>(resultPaths);\r\n } else if (expression instanceof UnaryExpression) {\r\n List childExpressions = concatExpressionWithSuffixPaths(((UnaryExpression) expression).getExpression(), prefixPaths);\r\n resultPaths.addAll(childExpressions);\r\n return new ArrayList<>(resultPaths);\r\n } else if (expression instanceof FunctionExpression) {\r\n for (Expression suffixExpression : expression.getExpressions()) {\r\n resultPaths.addAll(concatExpressionWithSuffixPaths(suffixExpression, prefixPaths));\r\n }\r\n return new ArrayList<>(resultPaths);\r\n } else if (expression instanceof TimeSeriesOperand) {\r\n PartialPath rawPath = ((TimeSeriesOperand) expression).getPath();\r\n List actualPaths = new ArrayList<>();\r\n if (rawPath.getFullPath().startsWith(SqlConstant.ROOT + TsFileConstant.PATH_SEPARATOR)) {\r\n actualPaths.add(rawPath);\r\n } else {\r\n for (PartialPath prefixPath : prefixPaths) {\r\n PartialPath concatPath = prefixPath.concatPath(rawPath);\r\n actualPaths.add(concatPath);\r\n }\r\n }\r\n return actualPaths;\r\n } else if (expression instanceof CaseWhenThenExpression) {\r\n return expression.getExpressions().stream().map(expression1 -> concatExpressionWithSuffixPaths(expression1, prefixPaths)).flatMap(Collection::stream).collect(Collectors.toList());\r\n } else if (expression instanceof TimestampOperand || expression instanceof ConstantOperand || expression instanceof NullOperand) {\r\n return new ArrayList<>();\r\n } else {\r\n throw new UnknownExpressionTypeException(expression.getExpressionType());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List hydrateContentPackage(byte[] payload) throws IOException{\r\n List pathDictionary = new ArrayList<>();\r\n List nodeDictionary = new ArrayList<>();\r\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n Inflater i = new Inflater();\r\n InflaterOutputStream ios = new InflaterOutputStream(baos, i);\r\n ios.write(payload);\r\n ios.finish();\r\n long read = i.getBytesRead();\r\n String name = \"\";\r\n int weight = 1;\r\n for (byte b : baos.toByteArray()) {\r\n if (b == '\\0') {\r\n pathDictionary.add(new HuffNode(name, weight++));\r\n name = \"\";\r\n } else {\r\n name += (char) b;\r\n }\r\n }\r\n pathDictionary.add(new HuffNode(END_NODE, weight));\r\n List triePathDictionary = new ArrayList<>(pathDictionary);\r\n HuffNode pathTrie = makeTrie(triePathDictionary);\r\n StringBuffer nodeBits = new StringBuffer();\r\n ByteArrayInputStream bais = new ByteArrayInputStream(payload, (int) read, (int) (payload.length - read));\r\n int value = bais.read();\r\n int nodeCount = value;\r\n if (value > 127) {\r\n int length = value - 128;\r\n int total = 0;\r\n if (length > 0) {\r\n byte[] count = new byte[length];\r\n int offset = 0;\r\n do {\r\n int bytesRead = bais.read(count, offset, length - offset);\r\n if (bytesRead != -1) {\r\n for (; bytesRead > 0; --bytesRead) {\r\n total = (total << 8) | (count[offset++] & 0xFF);\r\n }\r\n } else {\r\n break;\r\n }\r\n } while (offset < length);\r\n }\r\n nodeCount = total;\r\n }\r\n value = bais.read();\r\n while (value != -1) {\r\n String someBits = Integer.toString(value, 2);\r\n for (int pad = 0; pad < 8 - someBits.length(); pad++) {\r\n nodeBits.append(\"0\");\r\n }\r\n nodeBits.append(someBits);\r\n value = bais.read();\r\n }\r\n for (int j = 0; j < nodeCount; j++) {\r\n nodeDictionary.add(new HuffNode(new PathNode(), j));\r\n }\r\n List trieNodeDictionary = new ArrayList<>(nodeDictionary);\r\n HuffNode nodeTrie = makeTrie(trieNodeDictionary);\r\n Set pathNodes = populatePathNodes(nodeDictionary, pathTrie, nodeTrie, nodeBits);\r\n PathNode root = null;\r\n for (PathNode pn : pathNodes) {\r\n if (pn.getParents().size() == 0 && pn.getChildren().size() > 0) {\r\n root = pn;\r\n break;\r\n }\r\n }\r\n List urls = new ArrayList<>();\r\n StringBuffer aPath = new StringBuffer();\r\n makeURLs(root, urls, aPath);\r\n return urls;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SchemaDifference getSchemaDiff(Collection minuendCollection, Collection subtrahendCollection, boolean bothDirections){\r\n SchemaDifference difference = new SchemaDifference();\r\n for (FieldSchema first : minuendCollection) {\r\n boolean found = false;\r\n for (FieldSchema second : subtrahendCollection) {\r\n if (Objects.equals(first.getName(), second.getName())) {\r\n found = true;\r\n if (!Objects.equals(first.getType(), second.getType())) {\r\n difference.addTypeChanged(first);\r\n }\r\n if (!Objects.equals(first.getComment(), second.getComment())) {\r\n difference.addCommentChanged(first);\r\n }\r\n }\r\n }\r\n if (!found) {\r\n difference.addMissingFromSecond(first);\r\n }\r\n }\r\n if (bothDirections) {\r\n SchemaDifference otherWay = getSchemaDiff(subtrahendCollection, minuendCollection, false);\r\n otherWay.getMissingFromSecond().forEach(difference::addMissingFromFirst);\r\n }\r\n return difference;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void completeTx(SendRequest req) throws InsufficientMoneyException{\r\n lock.lock();\r\n try {\r\n checkArgument(!req.completed, \"Given SendRequest has already been completed.\");\r\n if (req.getUseForkId())\r\n req.tx.setVersion(Transaction.CURRENT_VERSION);\r\n Coin value = Coin.ZERO;\r\n for (TransactionOutput output : req.tx.getOutputs()) {\r\n value = value.add(output.getValue());\r\n }\r\n log.info(\"Completing send tx with {} outputs totalling {} and a fee of {}/kB\", req.tx.getOutputs().size(), value.toFriendlyString(), req.feePerKb.toFriendlyString());\r\n Coin totalInput = Coin.ZERO;\r\n for (TransactionInput input : req.tx.getInputs()) if (input.getConnectedOutput() != null)\r\n totalInput = totalInput.add(input.getConnectedOutput().getValue());\r\n else\r\n log.warn(\"SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee.\");\r\n value = value.subtract(totalInput);\r\n List originalInputs = new ArrayList(req.tx.getInputs());\r\n if (req.ensureMinRequiredFee && !req.emptyWallet) {\r\n int opReturnCount = 0;\r\n for (TransactionOutput output : req.tx.getOutputs()) {\r\n if (output.isDust())\r\n throw new DustySendRequested();\r\n if (output.getScriptPubKey().isOpReturnBeforeGenesis())\r\n ++opReturnCount;\r\n }\r\n if (opReturnCount > 1)\r\n throw new MultipleOpReturnRequested();\r\n }\r\n List candidates = calculateAllSpendCandidates(true, req.missingSigsMode == MissingSigsMode.THROW);\r\n CoinSelection bestCoinSelection;\r\n TransactionOutput bestChangeOutput = null;\r\n if (!req.emptyWallet) {\r\n FeeCalculation feeCalculation = calculateFee(req, value, originalInputs, req.ensureMinRequiredFee, candidates);\r\n bestCoinSelection = feeCalculation.bestCoinSelection;\r\n bestChangeOutput = feeCalculation.bestChangeOutput;\r\n } else {\r\n checkState(req.tx.getOutputs().size() == 1, \"Empty wallet TX must have a single output only.\");\r\n CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector;\r\n bestCoinSelection = selector.select(params.getMaxMoney(), candidates);\r\n candidates = null;\r\n req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered);\r\n log.info(\" emptying {}\", bestCoinSelection.valueGathered.toFriendlyString());\r\n }\r\n for (TransactionOutput output : bestCoinSelection.gathered) req.tx.addInput(output);\r\n if (req.emptyWallet) {\r\n final Coin feePerKb = req.feePerKb == null ? Coin.ZERO : req.feePerKb;\r\n if (!adjustOutputDownwardsForFee(req.tx, bestCoinSelection, feePerKb, req.ensureMinRequiredFee))\r\n throw new CouldNotAdjustDownwards();\r\n }\r\n if (bestChangeOutput != null) {\r\n req.tx.addOutput(bestChangeOutput);\r\n log.info(\" with {} change\", bestChangeOutput.getValue().toFriendlyString());\r\n }\r\n if (req.shuffleOutputs)\r\n req.tx.shuffleOutputs();\r\n if (req.signInputs)\r\n signTransaction(req);\r\n final int size = req.tx.unsafeBitcoinSerialize().length;\r\n if (size > Transaction.MAX_STANDARD_TX_SIZE)\r\n throw new ExceededMaxTransactionSize();\r\n TxHelper.getConfidence(req.tx).setSource(TransactionConfidence.Source.SELF);\r\n req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT);\r\n req.tx.setExchangeRate(req.exchangeRate);\r\n req.tx.setMemo(req.memo);\r\n req.completed = true;\r\n log.info(\" completed: {}\", req.tx);\r\n } finally {\r\n lock.unlock();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void sendTransactionData(){\r\n ConcurrentHashMap> transactions = getAndResetTransactions();\r\n boolean hasData = false;\r\n for (Map entry : transactions.values()) {\r\n for (TransactionData data : entry.values()) {\r\n if (data.getCount().get() > 0) {\r\n hasData = true;\r\n break;\r\n }\r\n }\r\n }\r\n if (hasData) {\r\n Transaction t = Cat.newTransaction(CatConstants.CAT_SYSTEM, this.getClass().getSimpleName());\r\n MessageTree tree = Cat.getManager().getThreadLocalMessageTree();\r\n tree.setDomain(getDomain());\r\n tree.setDiscardPrivate(false);\r\n for (Map entry : transactions.values()) {\r\n for (TransactionData data : entry.values()) {\r\n if (data.getCount().get() > 0) {\r\n Transaction tmp = Cat.newTransaction(data.getType(), data.getName());\r\n StringBuilder sb = new StringBuilder(32);\r\n sb.append(CatConstants.BATCH_FLAG).append(data.getCount().get()).append(CatConstants.SPLIT);\r\n sb.append(data.getFail().get()).append(CatConstants.SPLIT);\r\n sb.append(data.getSum().get()).append(CatConstants.SPLIT);\r\n sb.append(data.getDurationString()).append(CatConstants.SPLIT).append(data.getLongDurationString());\r\n tmp.addData(sb.toString());\r\n tmp.setSuccessStatus();\r\n tmp.complete();\r\n }\r\n }\r\n }\r\n t.setSuccessStatus();\r\n t.complete();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Message makeJmsMessage(Exchange exchange, org.apache.camel.Message camelMessage, Session session, Exception cause) throws JMSException{\r\n Message answer = null;\r\n boolean alwaysCopy = endpoint != null && endpoint.getConfiguration().isAlwaysCopyMessage();\r\n boolean force = endpoint != null && endpoint.getConfiguration().isForceSendOriginalMessage();\r\n if (!alwaysCopy && camelMessage instanceof JmsMessage) {\r\n JmsMessage jmsMessage = (JmsMessage) camelMessage;\r\n if (!jmsMessage.shouldCreateNewMessage() || force) {\r\n answer = jmsMessage.getJmsMessage();\r\n if (!force) {\r\n JmsMessageType type = endpoint != null ? endpoint.getConfiguration().getJmsMessageType() : null;\r\n if (type != null && answer != null) {\r\n if (type == JmsMessageType.Text) {\r\n answer = answer instanceof TextMessage ? answer : null;\r\n } else if (type == JmsMessageType.Bytes) {\r\n answer = answer instanceof BytesMessage ? answer : null;\r\n } else if (type == JmsMessageType.Map) {\r\n answer = answer instanceof MapMessage ? answer : null;\r\n } else if (type == JmsMessageType.Object) {\r\n answer = answer instanceof ObjectMessage ? answer : null;\r\n } else if (type == Stream) {\r\n answer = answer instanceof StreamMessage ? answer : null;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (answer == null) {\r\n if (cause != null) {\r\n LOG.debug(\"Will create JmsMessage with caused exception: {}\", cause.getMessage(), cause);\r\n answer = createJmsMessage(cause, session);\r\n } else {\r\n org.apache.camel.util.ObjectHelper.notNull(camelMessage, \"message\");\r\n answer = createJmsMessage(exchange, camelMessage, session, exchange.getContext());\r\n appendJmsProperties(answer, exchange, camelMessage);\r\n }\r\n }\r\n if (answer != null && messageCreatedStrategy != null) {\r\n messageCreatedStrategy.onMessageCreated(answer, session, exchange, null);\r\n }\r\n return answer;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void putObject(MinioClient minioClient, final Exchange exchange) throws Exception{\r\n if (getConfiguration().isPojoRequest()) {\r\n PutObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(PutObjectArgs.Builder.class);\r\n if (isNotEmpty(payload)) {\r\n ObjectWriteResponse putObjectResult = minioClient.putObject(payload.build());\r\n Message message = getMessageForResponse(exchange);\r\n message.setHeader(MinioConstants.E_TAG, putObjectResult.etag());\r\n if (isNotEmpty(putObjectResult.versionId())) {\r\n message.setHeader(MinioConstants.VERSION_ID, putObjectResult.versionId());\r\n }\r\n }\r\n } else {\r\n final String bucketName = determineBucketName(exchange);\r\n final String objectName = determineObjectName(exchange);\r\n Map objectMetadata = determineMetadata(exchange);\r\n Map extraHeaders = determineExtraHeaders(exchange);\r\n long contentLength = Long.parseLong(objectMetadata.getOrDefault(Exchange.CONTENT_LENGTH, \"-1\"));\r\n Object object = exchange.getIn().getMandatoryBody();\r\n InputStream inputStream = null;\r\n File filePayload = null;\r\n try {\r\n if (object instanceof WrappedFile) {\r\n object = ((WrappedFile) object).getFile();\r\n }\r\n if (object instanceof File) {\r\n filePayload = (File) object;\r\n inputStream = new FileInputStream(filePayload);\r\n contentLength = filePayload.length();\r\n } else {\r\n inputStream = exchange.getMessage().getMandatoryBody(InputStream.class);\r\n if (contentLength <= 0) {\r\n contentLength = determineLengthInputStream(inputStream);\r\n if (contentLength == -1) {\r\n LOG.debug(\"The content length is not defined. It needs to be determined by reading the data into memory\");\r\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n IOHelper.copyAndCloseInput(inputStream, baos);\r\n byte[] arr = baos.toByteArray();\r\n contentLength = arr.length;\r\n inputStream = new ByteArrayInputStream(arr);\r\n }\r\n }\r\n }\r\n if (contentLength > 0) {\r\n objectMetadata.put(Exchange.CONTENT_LENGTH, String.valueOf(contentLength));\r\n }\r\n doPutObject(exchange, bucketName, objectName, objectMetadata, extraHeaders, inputStream, contentLength);\r\n } finally {\r\n IOHelper.close(inputStream);\r\n }\r\n if (getConfiguration().isDeleteAfterWrite() && isNotEmpty(filePayload)) {\r\n FileUtil.deleteFile(filePayload);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void createQueue(SqsClient client) throws IOException{\r\n if (queueExists(client)) {\r\n return;\r\n }\r\n LOG.trace(\"Creating the a queue named '{}'\", configuration.getQueueName());\r\n CreateQueueRequest.Builder request = CreateQueueRequest.builder().queueName(configuration.getQueueName());\r\n Map attributes = new EnumMap<>(QueueAttributeName.class);\r\n if (getConfiguration().isFifoQueue()) {\r\n attributes.put(QueueAttributeName.FIFO_QUEUE, String.valueOf(true));\r\n boolean useContentBasedDeduplication = getConfiguration().getMessageDeduplicationIdStrategy() instanceof NullMessageDeduplicationIdStrategy;\r\n attributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, String.valueOf(useContentBasedDeduplication));\r\n }\r\n if (getConfiguration().getDefaultVisibilityTimeout() != null) {\r\n attributes.put(QueueAttributeName.VISIBILITY_TIMEOUT, String.valueOf(getConfiguration().getDefaultVisibilityTimeout()));\r\n }\r\n if (getConfiguration().getMaximumMessageSize() != null) {\r\n attributes.put(QueueAttributeName.MAXIMUM_MESSAGE_SIZE, String.valueOf(getConfiguration().getMaximumMessageSize()));\r\n }\r\n if (getConfiguration().getMessageRetentionPeriod() != null) {\r\n attributes.put(QueueAttributeName.MESSAGE_RETENTION_PERIOD, String.valueOf(getConfiguration().getMessageRetentionPeriod()));\r\n }\r\n if (getConfiguration().getPolicy() != null) {\r\n InputStream s = ResourceHelper.resolveMandatoryResourceAsInputStream(this.getCamelContext(), getConfiguration().getPolicy());\r\n String policy = IOUtils.toString(s, Charset.defaultCharset());\r\n attributes.put(QueueAttributeName.POLICY, policy);\r\n }\r\n if (getConfiguration().getReceiveMessageWaitTimeSeconds() != null) {\r\n attributes.put(QueueAttributeName.RECEIVE_MESSAGE_WAIT_TIME_SECONDS, String.valueOf(getConfiguration().getReceiveMessageWaitTimeSeconds()));\r\n }\r\n if (getConfiguration().getDelaySeconds() != null && getConfiguration().isDelayQueue()) {\r\n attributes.put(QueueAttributeName.DELAY_SECONDS, String.valueOf(getConfiguration().getDelaySeconds()));\r\n }\r\n if (getConfiguration().getRedrivePolicy() != null) {\r\n attributes.put(QueueAttributeName.REDRIVE_POLICY, getConfiguration().getRedrivePolicy());\r\n }\r\n if (getConfiguration().isServerSideEncryptionEnabled()) {\r\n if (getConfiguration().getKmsMasterKeyId() != null) {\r\n attributes.put(QueueAttributeName.KMS_MASTER_KEY_ID, getConfiguration().getKmsMasterKeyId());\r\n }\r\n if (getConfiguration().getKmsDataKeyReusePeriodSeconds() != null) {\r\n attributes.put(QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, String.valueOf(getConfiguration().getKmsDataKeyReusePeriodSeconds()));\r\n }\r\n }\r\n LOG.trace(\"Trying to create queue [{}] with request [{}]...\", configuration.getQueueName(), request);\r\n request.attributes(attributes);\r\n try {\r\n CreateQueueResponse queueResult = client.createQueue(request.build());\r\n queueUrl = queueResult.queueUrl();\r\n } catch (SqsException e) {\r\n if (queueExists(client)) {\r\n LOG.warn(\"The queue may have been created since last check and could not be created\");\r\n LOG.debug(\"AWS SDK error preventing queue creation: {}\", e.getMessage(), e);\r\n } else {\r\n throw e;\r\n }\r\n }\r\n LOG.trace(\"Queue created and available at: {}\", queueUrl);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void deleteLockFiles(File dir, boolean recursive, boolean hiddenFilesEnabled, String endpointPath, GenericFileFilter filter, GenericFileFilter antFilter, Pattern excludePattern, Pattern includePattern){\r\n File[] files = dir.listFiles();\r\n if (files == null || files.length == 0) {\r\n return;\r\n }\r\n for (File file : files) {\r\n if (!hiddenFilesEnabled && file.getName().startsWith(\".\")) {\r\n continue;\r\n }\r\n if (filter != null || antFilter != null || excludePattern != null || includePattern != null) {\r\n File targetFile = file;\r\n if (file.getName().endsWith(FileComponent.DEFAULT_LOCK_FILE_POSTFIX)) {\r\n String target = file.getName().substring(0, file.getName().length() - FileComponent.DEFAULT_LOCK_FILE_POSTFIX.length());\r\n if (file.getParent() != null) {\r\n targetFile = new File(file.getParent(), target);\r\n } else {\r\n targetFile = new File(target);\r\n }\r\n }\r\n boolean accept = acceptFile(targetFile, endpointPath, filter, antFilter, excludePattern, includePattern);\r\n if (!accept) {\r\n continue;\r\n }\r\n }\r\n if (file.getName().endsWith(FileComponent.DEFAULT_LOCK_FILE_POSTFIX)) {\r\n LOG.warn(\"Deleting orphaned lock file: {}\", file);\r\n FileUtil.deleteFile(file);\r\n } else if (recursive && file.isDirectory()) {\r\n deleteLockFiles(file, true, hiddenFilesEnabled, endpointPath, filter, antFilter, excludePattern, includePattern);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void unparse(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec){\r\n final SqlWriter.Frame frame = writer.startList(\"\", \"\");\r\n SqlCollation collation = null;\r\n for (Ord operand : Ord.zip(call.getOperandList())) {\r\n SqlLiteral rand = (SqlLiteral) operand.e;\r\n if (operand.i > 0) {\r\n writer.newlineAndIndent();\r\n }\r\n if (rand instanceof SqlCharStringLiteral) {\r\n final NlsString nls = rand.getValueAs(NlsString.class);\r\n if (operand.i == 0) {\r\n collation = nls.getCollation();\r\n writer.literal(nls.asSql(true, false, writer.getDialect()));\r\n } else {\r\n writer.literal(nls.asSql(false, false, writer.getDialect()));\r\n }\r\n } else if (operand.i == 0) {\r\n rand.unparse(writer, leftPrec, rightPrec);\r\n } else {\r\n if (rand.getTypeName() == SqlTypeName.BINARY) {\r\n BitString bs = rand.getValueAs(BitString.class);\r\n writer.literal(\"'\" + bs.toHexString() + \"'\");\r\n } else {\r\n writer.literal(\"'\" + rand.toValue() + \"'\");\r\n }\r\n }\r\n }\r\n if (collation != null) {\r\n collation.unparse(writer);\r\n }\r\n writer.endList(frame);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " String[] getCommands(File file) throws IOException{\r\n List cmds = new LinkedList();\r\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), \"UTF-8\"))) {\r\n StringBuilder cmd = null;\r\n while (true) {\r\n String scriptLine = reader.readLine();\r\n if (scriptLine == null) {\r\n break;\r\n }\r\n String trimmedLine = scriptLine.trim();\r\n if (getOpts().getTrimScripts()) {\r\n scriptLine = trimmedLine;\r\n }\r\n if (cmd != null) {\r\n cmd.append(\"\\n\");\r\n cmd.append(scriptLine);\r\n if (trimmedLine.endsWith(getOpts().getDelimiter())) {\r\n cmds.add(cmd.toString());\r\n cmd = null;\r\n }\r\n } else {\r\n if (needsContinuation(scriptLine)) {\r\n cmd = new StringBuilder(scriptLine);\r\n } else {\r\n cmds.add(scriptLine);\r\n }\r\n }\r\n }\r\n if (cmd != null) {\r\n cmd.append(getOpts().getDelimiter());\r\n cmds.add(cmd.toString());\r\n }\r\n }\r\n return cmds.toArray(new String[0]);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static SegmentMemory createSegmentMemory(LeftTupleSource segmentRoot, ReteEvaluator reteEvaluator){\r\n LeftTupleSource tupleSource = segmentRoot;\r\n SegmentMemory smem = new SegmentMemory(segmentRoot);\r\n long nodePosMask = 1;\r\n long allLinkedTestMask = 0;\r\n boolean updateNodeBit = true;\r\n int nodeTypesInSegment = 0;\r\n List memories = new ArrayList<>();\r\n while (true) {\r\n nodeTypesInSegment = updateNodeTypesMask(tupleSource, nodeTypesInSegment);\r\n if (NodeTypeEnums.isBetaNode(tupleSource)) {\r\n allLinkedTestMask = processBetaNode((BetaNode) tupleSource, reteEvaluator, smem, memories, nodePosMask, allLinkedTestMask, updateNodeBit);\r\n } else {\r\n switch(tupleSource.getType()) {\r\n case NodeTypeEnums.LeftInputAdapterNode:\r\n allLinkedTestMask = processLiaNode((LeftInputAdapterNode) tupleSource, reteEvaluator, smem, memories, nodePosMask, allLinkedTestMask);\r\n break;\r\n case NodeTypeEnums.EvalConditionNode:\r\n processEvalNode((EvalConditionNode) tupleSource, reteEvaluator, smem, memories);\r\n break;\r\n case NodeTypeEnums.ConditionalBranchNode:\r\n updateNodeBit = processBranchNode((ConditionalBranchNode) tupleSource, reteEvaluator, smem, memories);\r\n break;\r\n case NodeTypeEnums.FromNode:\r\n processFromNode((FromNode) tupleSource, reteEvaluator, smem, memories);\r\n break;\r\n case NodeTypeEnums.ReactiveFromNode:\r\n processReactiveFromNode((MemoryFactory) tupleSource, reteEvaluator, smem, memories, nodePosMask);\r\n break;\r\n case NodeTypeEnums.TimerConditionNode:\r\n processTimerNode((TimerNode) tupleSource, reteEvaluator, smem, memories, nodePosMask);\r\n break;\r\n case NodeTypeEnums.AsyncSendNode:\r\n processAsyncSendNode((AsyncSendNode) tupleSource, reteEvaluator, smem, memories);\r\n break;\r\n case NodeTypeEnums.AsyncReceiveNode:\r\n processAsyncReceiveNode((AsyncReceiveNode) tupleSource, reteEvaluator, smem, memories, nodePosMask);\r\n break;\r\n case NodeTypeEnums.QueryElementNode:\r\n updateNodeBit = processQueryNode((QueryElementNode) tupleSource, reteEvaluator, segmentRoot, smem, memories, nodePosMask);\r\n break;\r\n }\r\n }\r\n nodePosMask = nextNodePosMask(nodePosMask);\r\n if (tupleSource.getSinkPropagator().size() == 1) {\r\n LeftTupleSinkNode sink = tupleSource.getSinkPropagator().getFirstLeftTupleSink();\r\n if (NodeTypeEnums.isLeftTupleSource(sink)) {\r\n tupleSource = (LeftTupleSource) sink;\r\n } else {\r\n Memory memory = reteEvaluator.getNodeMemory((MemoryFactory) sink);\r\n if (sink.getType() == NodeTypeEnums.RightInputAdapterNode) {\r\n PathMemory riaPmem = (RightInputAdapterNode.RiaPathMemory) memory;\r\n memories.add(riaPmem);\r\n RightInputAdapterNode rian = (RightInputAdapterNode) sink;\r\n ObjectSink[] nodes = rian.getObjectSinkPropagator().getSinks();\r\n for (ObjectSink node : nodes) {\r\n if (NodeTypeEnums.isLeftTupleSource(node)) {\r\n getOrCreateSegmentMemory((LeftTupleSource) node, reteEvaluator);\r\n }\r\n }\r\n } else if (NodeTypeEnums.isTerminalNode(sink)) {\r\n memories.add(memory);\r\n }\r\n memory.setSegmentMemory(smem);\r\n smem.setTipNode(sink);\r\n break;\r\n }\r\n } else {\r\n smem.setTipNode(tupleSource);\r\n break;\r\n }\r\n }\r\n smem.setAllLinkedMaskTest(allLinkedTestMask);\r\n smem.setNodeMemories(memories.toArray(new Memory[memories.size()]));\r\n Memory lastMem = null;\r\n for (Memory mem : memories) {\r\n if (lastMem != null) {\r\n mem.setPrevious(lastMem);\r\n lastMem.setNext(mem);\r\n }\r\n lastMem = mem;\r\n }\r\n LeftTupleSource pathRoot = segmentRoot;\r\n int ruleSegmentPosMask = 1;\r\n int counter = 0;\r\n while (pathRoot.getType() != NodeTypeEnums.LeftInputAdapterNode) {\r\n LeftTupleSource leftTupleSource = pathRoot.getLeftTupleSource();\r\n if (isNonTerminalTipNode(leftTupleSource, null)) {\r\n ruleSegmentPosMask = ruleSegmentPosMask << 1;\r\n counter++;\r\n }\r\n pathRoot = leftTupleSource;\r\n }\r\n smem.setSegmentPosMaskBit(ruleSegmentPosMask);\r\n smem.setPos(counter);\r\n updateRiaAndTerminalMemory(tupleSource, tupleSource, smem, reteEvaluator, false, nodeTypesInSegment);\r\n reteEvaluator.getKnowledgeBase().registerSegmentPrototype(segmentRoot, smem.getSegmentPrototype().initFromSegmentMemory(smem));\r\n return smem;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder mergeFrom(KieModuleCache.CompilationData other){\r\n if (other == KieModuleCache.CompilationData.getDefaultInstance())\r\n return this;\r\n if (other.hasDialect()) {\r\n bitField0_ |= 0x00000001;\r\n dialect_ = other.dialect_;\r\n onChanged();\r\n }\r\n if (entryBuilder_ == null) {\r\n if (!other.entry_.isEmpty()) {\r\n if (entry_.isEmpty()) {\r\n entry_ = other.entry_;\r\n bitField0_ = (bitField0_ & ~0x00000002);\r\n } else {\r\n ensureEntryIsMutable();\r\n entry_.addAll(other.entry_);\r\n }\r\n onChanged();\r\n }\r\n } else {\r\n if (!other.entry_.isEmpty()) {\r\n if (entryBuilder_.isEmpty()) {\r\n entryBuilder_.dispose();\r\n entryBuilder_ = null;\r\n entry_ = other.entry_;\r\n bitField0_ = (bitField0_ & ~0x00000002);\r\n entryBuilder_ = alwaysUseFieldBuilders ? getEntryFieldBuilder() : null;\r\n } else {\r\n entryBuilder_.addAllMessages(other.entry_);\r\n }\r\n }\r\n }\r\n this.mergeUnknownFields(other.getUnknownFields());\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void preprocessSubstituteShapeReferencesInShape(String shapeName, Shape shape, ServiceModel serviceModel){\r\n if (shape.getMembers() != null) {\r\n for (Entry entry : shape.getMembers().entrySet()) {\r\n String memberName = entry.getKey();\r\n Member member = entry.getValue();\r\n String memberShapeName = member.getShape();\r\n Shape memberShape = serviceModel.getShapes().get(memberShapeName);\r\n if (Utils.isListShape(memberShape)) {\r\n Member nestedListMember = memberShape.getListMember();\r\n String nestedListMemberOriginalShape = nestedListMember.getShape();\r\n ShapeSubstitution appliedSubstitutionOnListMember = substituteMemberShape(nestedListMember);\r\n if (appliedSubstitutionOnListMember != null && appliedSubstitutionOnListMember.getEmitFromMember() != null) {\r\n trackListMemberSubstitution(shapeName, memberName, nestedListMemberOriginalShape);\r\n }\r\n } else {\r\n ShapeSubstitution appliedSubstitution = substituteMemberShape(member);\r\n if (appliedSubstitution != null && appliedSubstitution.getEmitFromMember() != null) {\r\n trackShapeMemberSubstitution(shapeName, memberName, memberShapeName);\r\n }\r\n }\r\n }\r\n } else if (shape.getMapKeyType() != null) {\r\n String mapKeyShape = shape.getMapKeyType().getShape();\r\n if (shapeSubstitutions.containsKey(mapKeyShape)) {\r\n throw new IllegalStateException(\"shapeSubstitution customization found for shape \" + mapKeyShape + \", but this shape is the key for a map shape.\");\r\n }\r\n } else if (shape.getMapValueType() != null) {\r\n String mapValShape = shape.getMapValueType().getShape();\r\n if (shapeSubstitutions.containsKey(mapValShape)) {\r\n throw new IllegalStateException(\"shapeSubstitution customization found for shape \" + mapValShape + \", but this shape is the value for a map shape.\");\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Type getJavaClass(RelDataType type){\r\n if (type instanceof JavaType) {\r\n JavaType javaType = (JavaType) type;\r\n return javaType.getJavaClass();\r\n }\r\n if (type instanceof BasicSqlType || type instanceof IntervalSqlType) {\r\n switch(type.getSqlTypeName()) {\r\n case VARCHAR:\r\n case CHAR:\r\n return String.class;\r\n case DATE:\r\n case TIME:\r\n case TIME_WITH_LOCAL_TIME_ZONE:\r\n case INTEGER:\r\n case INTERVAL_YEAR:\r\n case INTERVAL_YEAR_MONTH:\r\n case INTERVAL_MONTH:\r\n return type.isNullable() ? Integer.class : int.class;\r\n case TIMESTAMP:\r\n case TIMESTAMP_WITH_LOCAL_TIME_ZONE:\r\n case BIGINT:\r\n case INTERVAL_DAY:\r\n case INTERVAL_DAY_HOUR:\r\n case INTERVAL_DAY_MINUTE:\r\n case INTERVAL_DAY_SECOND:\r\n case INTERVAL_HOUR:\r\n case INTERVAL_HOUR_MINUTE:\r\n case INTERVAL_HOUR_SECOND:\r\n case INTERVAL_MINUTE:\r\n case INTERVAL_MINUTE_SECOND:\r\n case INTERVAL_SECOND:\r\n return type.isNullable() ? Long.class : long.class;\r\n case SMALLINT:\r\n return type.isNullable() ? Short.class : short.class;\r\n case TINYINT:\r\n return type.isNullable() ? Byte.class : byte.class;\r\n case DECIMAL:\r\n return BigDecimal.class;\r\n case BOOLEAN:\r\n return type.isNullable() ? Boolean.class : boolean.class;\r\n case DOUBLE:\r\n case FLOAT:\r\n return type.isNullable() ? Double.class : double.class;\r\n case REAL:\r\n return type.isNullable() ? Float.class : float.class;\r\n case BINARY:\r\n case VARBINARY:\r\n return ByteString.class;\r\n case GEOMETRY:\r\n return Geometry.class;\r\n case SYMBOL:\r\n return Enum.class;\r\n case ANY:\r\n return Object.class;\r\n case NULL:\r\n return Void.class;\r\n default:\r\n break;\r\n }\r\n }\r\n switch(type.getSqlTypeName()) {\r\n case ROW:\r\n assert type instanceof RelRecordType;\r\n if (type instanceof JavaRecordType) {\r\n return ((JavaRecordType) type).clazz;\r\n } else {\r\n return createSyntheticType((RelRecordType) type);\r\n }\r\n case MAP:\r\n return Map.class;\r\n case ARRAY:\r\n case MULTISET:\r\n return List.class;\r\n default:\r\n break;\r\n }\r\n return Object.class;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Object evaluate(Evaluator evaluator){\r\n switch(nodeType) {\r\n case AndAlso:\r\n return evaluateBoolean(evaluator, expression0) && evaluateBoolean(evaluator, expression1);\r\n case Add:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) + evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) + evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) + evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) + evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) + evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) + evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case Divide:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) / evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) / evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) / evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) / evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) / evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) / evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case Equal:\r\n return Objects.equals(expression0.evaluate(evaluator), expression1.evaluate(evaluator));\r\n case GreaterThan:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) > evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) > evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) > evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) > evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) > evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) > evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case GreaterThanOrEqual:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) >= evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) >= evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) >= evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) >= evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) >= evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) >= evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case LessThan:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) < evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) < evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) < evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) < evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) < evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) < evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case LessThanOrEqual:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) <= evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) <= evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) <= evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) <= evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) <= evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) <= evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case Multiply:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) * evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) * evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) * evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) * evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) * evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) * evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n case NotEqual:\r\n return !Objects.equals(expression0.evaluate(evaluator), expression1.evaluate(evaluator));\r\n case OrElse:\r\n return evaluateBoolean(evaluator, expression0) || evaluateBoolean(evaluator, expression1);\r\n case Subtract:\r\n if (primitive == null) {\r\n throw cannotEvaluate();\r\n }\r\n switch(primitive) {\r\n case INT:\r\n return evaluateInt(expression0, evaluator) - evaluateInt(expression1, evaluator);\r\n case SHORT:\r\n return evaluateShort(expression0, evaluator) - evaluateShort(expression1, evaluator);\r\n case BYTE:\r\n return evaluateByte(expression0, evaluator) - evaluateByte(expression1, evaluator);\r\n case FLOAT:\r\n return evaluateFloat(expression0, evaluator) - evaluateFloat(expression1, evaluator);\r\n case DOUBLE:\r\n return evaluateDouble(expression0, evaluator) - evaluateDouble(expression1, evaluator);\r\n case LONG:\r\n return evaluateLong(expression0, evaluator) - evaluateLong(expression1, evaluator);\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n default:\r\n throw cannotEvaluate();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean process(Context context, ProcessingCommands commands, ProgressionCommand progression, boolean continueLineProcesingOnError) throws Exception{\r\n boolean result = ERROR;\r\n ValidateParameters parameters = (ValidateParameters) context.get(CONFIGURATION);\r\n ActionReporter reporter = ActionReporter.Factory.getInstance();\r\n List preProcessingCommands = commands.getPreProcessingCommands(context, true);\r\n progression.initialize(context, preProcessingCommands.size() + 1);\r\n for (Command command : preProcessingCommands) {\r\n result = command.execute(context);\r\n if (!result) {\r\n reporter.setActionError(context, ActionReporter.ERROR_CODE.NO_DATA_FOUND, \"no data selected\");\r\n reportNoDataValidationError(context);\r\n progression.execute(context);\r\n return ERROR;\r\n }\r\n progression.execute(context);\r\n }\r\n String type = parameters.getReferencesType();\r\n if (type == null || type.isEmpty()) {\r\n type = \"line\";\r\n parameters.setIds(null);\r\n }\r\n type = type.toLowerCase();\r\n List ids = null;\r\n if (parameters.getIds() != null) {\r\n ids = new ArrayList(parameters.getIds());\r\n }\r\n Set lines = reader.loadLines(type, ids);\r\n if (lines.isEmpty()) {\r\n reporter.setActionError(context, ActionReporter.ERROR_CODE.NO_DATA_FOUND, \"no data selected\");\r\n reportNoDataValidationError(context);\r\n return ERROR;\r\n }\r\n progression.execute(context);\r\n progression.start(context, lines.size());\r\n int lineCount = 0;\r\n for (Long lineId : lines) {\r\n context.put(LINE_ID, lineId);\r\n boolean validateFailed = false;\r\n List lineProcessingCommands = commands.getLineProcessingCommands(context, true);\r\n for (Command command : lineProcessingCommands) {\r\n result = command.execute(context);\r\n if (!result) {\r\n validateFailed = true;\r\n break;\r\n }\r\n }\r\n progression.execute(context);\r\n ValidationData data = (ValidationData) context.get(VALIDATION_DATA);\r\n Line line = data.getCurrentLine();\r\n reporter.addObjectReport(context, line.getObjectId(), OBJECT_TYPE.LINE, NamingUtil.getName(line), OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, line.getObjectId(), OBJECT_TYPE.LINE, OBJECT_TYPE.LINE, 1);\r\n reporter.setStatToObjectReport(context, line.getObjectId(), OBJECT_TYPE.LINE, OBJECT_TYPE.JOURNEY_PATTERN, data.getJourneyPatterns().size());\r\n reporter.setStatToObjectReport(context, line.getObjectId(), OBJECT_TYPE.LINE, OBJECT_TYPE.ROUTE, data.getRoutes().size());\r\n reporter.setStatToObjectReport(context, line.getObjectId(), OBJECT_TYPE.LINE, OBJECT_TYPE.VEHICLE_JOURNEY, data.getVehicleJourneys().size());\r\n if (!validateFailed) {\r\n lineCount++;\r\n } else if (!continueLineProcesingOnError) {\r\n reporter.setActionError(context, ActionReporter.ERROR_CODE.INVALID_DATA, \"unable to validate data\");\r\n return ERROR;\r\n }\r\n }\r\n if (lineCount == 0) {\r\n progression.terminate(context, 1);\r\n reporter.setActionError(context, ActionReporter.ERROR_CODE.NO_DATA_PROCEEDED, \"no data validated\");\r\n reportNoDataValidationError(context);\r\n progression.execute(context);\r\n return ERROR;\r\n }\r\n List postProcessingCommands = commands.getPostProcessingCommands(context, true);\r\n progression.terminate(context, postProcessingCommands.size());\r\n for (Command command : postProcessingCommands) {\r\n result = command.execute(context);\r\n if (!result) {\r\n if (!reporter.hasActionError(context))\r\n reporter.setActionError(context, ActionReporter.ERROR_CODE.NO_DATA_PROCEEDED, \"no data exported\");\r\n reportNoDataValidationError(context);\r\n return ERROR;\r\n }\r\n progression.execute(context);\r\n }\r\n ValidationData data = (ValidationData) context.get(VALIDATION_DATA);\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.NETWORK, \"networks\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.NETWORK, OBJECT_TYPE.NETWORK, data.getNetworks().size());\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.COMPANY, \"companies\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.COMPANY, OBJECT_TYPE.COMPANY, data.getCompanies().size());\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.CONNECTION_LINK, \"connection links\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.CONNECTION_LINK, OBJECT_TYPE.CONNECTION_LINK, data.getConnectionLinks().size());\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.ACCESS_POINT, \"access points\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.ACCESS_POINT, OBJECT_TYPE.ACCESS_POINT, data.getAccessPoints().size());\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.STOP_AREA, \"stop areas\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.STOP_AREA, OBJECT_TYPE.STOP_AREA, data.getStopAreas().size());\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.TIMETABLE, \"calendars\", OBJECT_STATE.OK, IO_TYPE.INPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.TIMETABLE, OBJECT_TYPE.TIMETABLE, data.getTimetables().size());\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readDirectoryEntry(DumpArchiveEntry entry) throws IOException{\r\n long size = entry.getEntrySize();\r\n boolean first = true;\r\n while (first || DumpArchiveConstants.SEGMENT_TYPE.ADDR == entry.getHeaderType()) {\r\n if (!first) {\r\n raw.readRecord();\r\n }\r\n if (!names.containsKey(entry.getIno()) && DumpArchiveConstants.SEGMENT_TYPE.INODE == entry.getHeaderType()) {\r\n pending.put(entry.getIno(), entry);\r\n }\r\n final int datalen = DumpArchiveConstants.TP_SIZE * entry.getHeaderCount();\r\n if (blockBuffer.length < datalen) {\r\n blockBuffer = IOUtils.readRange(raw, datalen);\r\n if (blockBuffer.length != datalen) {\r\n throw new EOFException();\r\n }\r\n } else if (raw.read(blockBuffer, 0, datalen) != datalen) {\r\n throw new EOFException();\r\n }\r\n int reclen = 0;\r\n for (int i = 0; i < datalen - 8 && i < size - 8; i += reclen) {\r\n final int ino = DumpArchiveUtil.convert32(blockBuffer, i);\r\n reclen = DumpArchiveUtil.convert16(blockBuffer, i + 4);\r\n final byte type = blockBuffer[i + 6];\r\n final String name = DumpArchiveUtil.decode(zipEncoding, blockBuffer, i + 8, blockBuffer[i + 7]);\r\n if (\".\".equals(name) || \"..\".equals(name)) {\r\n continue;\r\n }\r\n final Dirent d = new Dirent(ino, entry.getIno(), type, name);\r\n names.put(ino, d);\r\n pending.forEach((k, v) -> {\r\n final String path = getPath(v);\r\n if (path != null) {\r\n v.setName(path);\r\n v.setSimpleName(names.get(k).getName());\r\n queue.add(v);\r\n }\r\n });\r\n queue.forEach(e -> pending.remove(e.getIno()));\r\n }\r\n final byte[] peekBytes = raw.peek();\r\n if (!DumpArchiveUtil.verify(peekBytes)) {\r\n throw new InvalidFormatException();\r\n }\r\n entry = DumpArchiveEntry.parse(peekBytes);\r\n first = false;\r\n size -= DumpArchiveConstants.TP_SIZE;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized void initFolders(){\r\n try {\r\n String strategyName = Class.forName(config.getMultiDirStrategyClassName()).getSimpleName();\r\n if (strategyName.equals(MaxDiskUsableSpaceFirstStrategy.class.getSimpleName())) {\r\n directoryStrategyType = DirectoryStrategyType.MAX_DISK_USABLE_SPACE_FIRST_STRATEGY;\r\n } else if (strategyName.equals(MinFolderOccupiedSpaceFirstStrategy.class.getSimpleName())) {\r\n directoryStrategyType = DirectoryStrategyType.MIN_FOLDER_OCCUPIED_SPACE_FIRST_STRATEGY;\r\n } else if (strategyName.equals(RandomOnDiskUsableSpaceStrategy.class.getSimpleName())) {\r\n directoryStrategyType = DirectoryStrategyType.RANDOM_ON_DISK_USABLE_SPACE_STRATEGY;\r\n }\r\n } catch (Exception e) {\r\n logger.error(\"Can't find strategy {} for mult-directories.\", config.getMultiDirStrategyClassName(), e);\r\n }\r\n config.updatePath();\r\n String[][] tierDirs = config.getTierDataDirs();\r\n for (int i = 0; i < tierDirs.length; ++i) {\r\n for (int j = 0; j < tierDirs[i].length; ++j) {\r\n switch(FSUtils.getFSType(tierDirs[i][j])) {\r\n case LOCAL:\r\n try {\r\n tierDirs[i][j] = new File(tierDirs[i][j]).getCanonicalPath();\r\n } catch (IOException e) {\r\n logger.error(\"Fail to get canonical path of data dir {}\", tierDirs[i][j], e);\r\n }\r\n break;\r\n case OBJECT_STORAGE:\r\n case HDFS:\r\n default:\r\n break;\r\n }\r\n }\r\n }\r\n for (int tierLevel = 0; tierLevel < tierDirs.length; ++tierLevel) {\r\n List seqDirs = Arrays.stream(tierDirs[tierLevel]).filter(Objects::nonNull).map(v -> FSFactoryProducer.getFSFactory().getFile(v, IoTDBConstant.SEQUENCE_FLODER_NAME).getPath()).collect(Collectors.toList());\r\n mkDataDirs(seqDirs);\r\n try {\r\n seqTiers.add(new FolderManager(seqDirs, directoryStrategyType));\r\n } catch (DiskSpaceInsufficientException e) {\r\n logger.error(\"All disks of tier {} are full.\", tierLevel, e);\r\n }\r\n for (String dir : seqDirs) {\r\n seqDir2TierLevel.put(dir, tierLevel);\r\n }\r\n List unSeqDirs = Arrays.stream(tierDirs[tierLevel]).filter(Objects::nonNull).map(v -> FSFactoryProducer.getFSFactory().getFile(v, IoTDBConstant.UNSEQUENCE_FLODER_NAME).getPath()).collect(Collectors.toList());\r\n mkDataDirs(unSeqDirs);\r\n try {\r\n unSeqTiers.add(new FolderManager(unSeqDirs, directoryStrategyType));\r\n } catch (DiskSpaceInsufficientException e) {\r\n logger.error(\"All disks of tier {} are full.\", tierLevel, e);\r\n }\r\n for (String dir : unSeqDirs) {\r\n unSeqDir2TierLevel.put(dir, tierLevel);\r\n }\r\n }\r\n tierDiskTotalSpace = getTierDiskSpace(DiskSpaceType.TOTAL);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void subscribe(final String topicName, final StreamingApiConsumer consumer, final boolean skipReplayId){\r\n final String channelName = getChannelName(topicName);\r\n if (!reconnecting && !skipReplayId) {\r\n setupReplay((SalesforceEndpoint) consumer.getEndpoint());\r\n }\r\n LOG.info(\"Subscribing to channel {}...\", channelName);\r\n final ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener() {\r\n\r\n @Override\r\n public void onMessage(ClientSessionChannel channel, Message message) {\r\n LOG.debug(\"Received Message: {}\", message);\r\n consumer.processMessage(channel, message);\r\n }\r\n };\r\n final ClientSessionChannel.MessageListener subscriptionListener = new ClientSessionChannel.MessageListener() {\r\n\r\n public void onMessage(ClientSessionChannel channel, Message message) {\r\n LOG.debug(\"[CHANNEL:META_SUBSCRIBE]: {}\", message);\r\n final String subscribedChannelName = message.get(SUBSCRIPTION_FIELD).toString();\r\n if (channelName.equals(subscribedChannelName)) {\r\n if (!message.isSuccessful()) {\r\n String error = (String) message.get(ERROR_FIELD);\r\n if (error == null) {\r\n error = \"Missing error message\";\r\n }\r\n Exception failure = getFailure(message);\r\n String msg = String.format(\"Error subscribing to %s: %s\", topicName, failure != null ? failure.getMessage() : error);\r\n boolean abort = true;\r\n if (isTemporaryError(message)) {\r\n LOG.warn(msg);\r\n final long backoff = handshakeBackoff.getAndAdd(backoffIncrement);\r\n if (backoff > maxBackoff) {\r\n LOG.error(\"Subscribe aborted after exceeding {} msecs backoff\", maxBackoff);\r\n } else {\r\n abort = false;\r\n try {\r\n LOG.debug(\"Pausing for {} msecs before subscribe attempt\", backoff);\r\n Thread.sleep(backoff);\r\n component.getHttpClient().getWorkerPool().execute(() -> subscribe(topicName, consumer));\r\n } catch (InterruptedException e) {\r\n LOG.warn(\"Aborting subscribe on interrupt!\", e);\r\n }\r\n }\r\n } else if (error.matches(INVALID_REPLAY_ID_PATTERN)) {\r\n abort = false;\r\n final Long fallBackReplayId = ((SalesforceEndpoint) consumer.getEndpoint()).getConfiguration().getFallBackReplayId();\r\n LOG.warn(error);\r\n LOG.warn(\"Falling back to replayId {} for channel {}\", fallBackReplayId, channelName);\r\n REPLAY_EXTENSION.addChannelReplayId(channelName, fallBackReplayId);\r\n subscribe(topicName, consumer, true);\r\n }\r\n if (abort && client != null) {\r\n consumer.handleException(msg, new SalesforceException(msg, failure));\r\n }\r\n } else {\r\n LOG.info(\"Subscribed to channel {}\", subscribedChannelName);\r\n listenerMap.put(consumer, listener);\r\n handshakeBackoff.set(0);\r\n }\r\n if (client != null) {\r\n client.getChannel(META_SUBSCRIBE).removeListener(this);\r\n } else {\r\n LOG.warn(\"Trying to handle a subscription message but the client is already destroyed\");\r\n }\r\n }\r\n }\r\n };\r\n client.getChannel(META_SUBSCRIBE).addListener(subscriptionListener);\r\n final ClientSessionChannel clientChannel = client.getChannel(channelName);\r\n clientChannel.subscribe(listener);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode convertCast(SqlCall call, Blackboard blackboard){\r\n SqlNode operand = call.operand(0);\r\n RexNode convertedOperand = blackboard.convertExpression(operand);\r\n RelDataType from = validator.getValidatedNodeType(operand);\r\n RelDataType to = validator.getValidatedNodeType(call);\r\n QueryDataType fromType = HazelcastTypeUtils.toHazelcastType(from);\r\n QueryDataType toType = HazelcastTypeUtils.toHazelcastType(to);\r\n Literal literal = LiteralUtils.literal(convertedOperand);\r\n if (literal != null && !isNullOrUnknown(((RexLiteral) convertedOperand).getTypeName())) {\r\n try {\r\n QueryDataType actualFromType = HazelcastTypeUtils.toHazelcastTypeFromSqlTypeName(literal.getTypeName());\r\n toType.getConverter().convertToSelf(actualFromType.getConverter(), literal.getValue());\r\n } catch (Exception e) {\r\n throw literalConversionException(validator, call, literal, toType, e);\r\n }\r\n if (SqlTypeName.CHAR_TYPES.contains(to.getSqlTypeName())) {\r\n return getRexBuilder().makeLiteral(literal.getStringValue(), to, true);\r\n }\r\n if (SqlTypeName.CHAR_TYPES.contains(from.getSqlTypeName()) && to.getSqlTypeName() == SqlTypeName.TIME) {\r\n LocalTime time = fromType.getConverter().asTime(literal.getStringValue());\r\n TimeString timeString = new TimeString(time.getHour(), time.getMinute(), time.getSecond());\r\n return getRexBuilder().makeLiteral(timeString, to, true);\r\n }\r\n if (fromType.getTypeFamily().isNumeric()) {\r\n if (toType.getTypeFamily().isNumericApproximate()) {\r\n Converter converter = Converters.getConverter(literal.getValue().getClass());\r\n Object convertedValue = toType.getConverter().convertToSelf(converter, literal.getValue());\r\n return getRexBuilder().makeLiteral(convertedValue, to, false);\r\n }\r\n }\r\n }\r\n if (literal != null && HazelcastTypeUtils.isJsonType(to)) {\r\n return getRexBuilder().makeCall(HazelcastJsonParseFunction.INSTANCE, convertedOperand);\r\n }\r\n if (toType.getTypeFamily().equals(QueryDataTypeFamily.JSON) && fromType.isCustomType()) {\r\n return getRexBuilder().makeCall(HazelcastUdtObjectToJsonFunction.INSTANCE, convertedOperand);\r\n }\r\n return getRexBuilder().makeCast(to, convertedOperand);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic boolean moveNext(){\r\n try {\r\n outer: for (; ; ) {\r\n if (cancelFlag.get()) {\r\n return false;\r\n }\r\n final String[] strings = reader.readNext();\r\n if (strings == null) {\r\n if (reader instanceof CsvStreamReader) {\r\n try {\r\n Thread.sleep(CsvStreamReader.DEFAULT_MONITOR_DELAY);\r\n } catch (InterruptedException e) {\r\n throw new RuntimeException(e);\r\n }\r\n continue;\r\n }\r\n current = null;\r\n reader.close();\r\n return false;\r\n }\r\n if (filterValues != null) {\r\n for (int i = 0; i < strings.length; i++) {\r\n String filterValue = filterValues.get(i);\r\n if (filterValue != null) {\r\n if (!filterValue.equals(strings[i])) {\r\n continue outer;\r\n }\r\n }\r\n }\r\n }\r\n current = rowConverter.convertRow(strings);\r\n return true;\r\n }\r\n } catch (IOException e) {\r\n throw new RuntimeException(e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readSubStreamsInfo(final ByteBuffer header, final Archive archive) throws IOException{\r\n for (final Folder folder : archive.folders) {\r\n folder.numUnpackSubStreams = 1;\r\n }\r\n long unpackStreamsCount = archive.folders.length;\r\n int nid = getUnsignedByte(header);\r\n if (nid == NID.kNumUnpackStream) {\r\n unpackStreamsCount = 0;\r\n for (final Folder folder : archive.folders) {\r\n final long numStreams = readUint64(header);\r\n folder.numUnpackSubStreams = (int) numStreams;\r\n unpackStreamsCount += numStreams;\r\n }\r\n nid = getUnsignedByte(header);\r\n }\r\n final int totalUnpackStreams = (int) unpackStreamsCount;\r\n final SubStreamsInfo subStreamsInfo = new SubStreamsInfo();\r\n subStreamsInfo.unpackSizes = new long[totalUnpackStreams];\r\n subStreamsInfo.hasCrc = new BitSet(totalUnpackStreams);\r\n subStreamsInfo.crcs = new long[totalUnpackStreams];\r\n int nextUnpackStream = 0;\r\n for (final Folder folder : archive.folders) {\r\n if (folder.numUnpackSubStreams == 0) {\r\n continue;\r\n }\r\n long sum = 0;\r\n if (nid == NID.kSize) {\r\n for (int i = 0; i < folder.numUnpackSubStreams - 1; i++) {\r\n final long size = readUint64(header);\r\n subStreamsInfo.unpackSizes[nextUnpackStream++] = size;\r\n sum += size;\r\n }\r\n }\r\n if (sum > folder.getUnpackSize()) {\r\n throw new IOException(\"sum of unpack sizes of folder exceeds total unpack size\");\r\n }\r\n subStreamsInfo.unpackSizes[nextUnpackStream++] = folder.getUnpackSize() - sum;\r\n }\r\n if (nid == NID.kSize) {\r\n nid = getUnsignedByte(header);\r\n }\r\n int numDigests = 0;\r\n for (final Folder folder : archive.folders) {\r\n if (folder.numUnpackSubStreams != 1 || !folder.hasCrc) {\r\n numDigests += folder.numUnpackSubStreams;\r\n }\r\n }\r\n if (nid == NID.kCRC) {\r\n final BitSet hasMissingCrc = readAllOrBits(header, numDigests);\r\n final long[] missingCrcs = new long[numDigests];\r\n for (int i = 0; i < numDigests; i++) {\r\n if (hasMissingCrc.get(i)) {\r\n missingCrcs[i] = 0xffffFFFFL & getInt(header);\r\n }\r\n }\r\n int nextCrc = 0;\r\n int nextMissingCrc = 0;\r\n for (final Folder folder : archive.folders) {\r\n if (folder.numUnpackSubStreams == 1 && folder.hasCrc) {\r\n subStreamsInfo.hasCrc.set(nextCrc, true);\r\n subStreamsInfo.crcs[nextCrc] = folder.crc;\r\n ++nextCrc;\r\n } else {\r\n for (int i = 0; i < folder.numUnpackSubStreams; i++) {\r\n subStreamsInfo.hasCrc.set(nextCrc, hasMissingCrc.get(nextMissingCrc));\r\n subStreamsInfo.crcs[nextCrc] = missingCrcs[nextMissingCrc];\r\n ++nextCrc;\r\n ++nextMissingCrc;\r\n }\r\n }\r\n }\r\n nid = getUnsignedByte(header);\r\n }\r\n archive.subStreamsInfo = subStreamsInfo;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List ruleMetaAttributes(RuleContext context, RuleDescr ruleDescr){\r\n List ruleMetaAttributes = new ArrayList<>();\r\n for (String metaAttr : ruleDescr.getAnnotationNames()) {\r\n MethodCallExpr metaAttributeCall = new MethodCallExpr(METADATA_CALL);\r\n metaAttributeCall.addArgument(toStringLiteral(metaAttr));\r\n AnnotationDescr ad = ruleDescr.getAnnotation(metaAttr);\r\n String adFqn = ad.getFullyQualifiedName();\r\n if (\"Propagation\".equals(metaAttr)) {\r\n metaAttributeCall.addArgument(parseExpression(org.kie.api.definition.rule.Propagation.Type.class.getCanonicalName() + \".\" + ad.getSingleValueAsString()));\r\n } else if (adFqn != null) {\r\n AnnotationDefinition annotationDefinition;\r\n try {\r\n annotationDefinition = AnnotationDefinition.build(context.getTypeResolver().resolveType(adFqn), ad.getValueMap(), context.getTypeResolver());\r\n } catch (NoSuchMethodException | ClassNotFoundException e) {\r\n throw new RuntimeException(e);\r\n }\r\n if (annotationDefinition.getValues().size() == 1 && annotationDefinition.getValues().containsKey(AnnotationDescr.VALUE)) {\r\n Object annValue = annotationDefinition.getPropertyValue(AnnotationDescr.VALUE);\r\n metaAttributeCall.addArgument(toStringLiteral(annValue.toString()));\r\n } else {\r\n Map map = new HashMap<>(annotationDefinition.getValues().size());\r\n for (String key : annotationDefinition.getValues().keySet()) {\r\n map.put(key, annotationDefinition.getPropertyValue(key));\r\n }\r\n metaAttributeCall.addArgument(objectAsJPExpression(map));\r\n }\r\n } else {\r\n if (ad.hasValue()) {\r\n if (ad.getValueMap().size() == 1) {\r\n metaAttributeCall.addArgument(annotationSingleValueExpression(ad));\r\n } else {\r\n metaAttributeCall.addArgument(objectAsJPExpression(ad.getValueMap()));\r\n }\r\n } else {\r\n metaAttributeCall.addArgument(new NullLiteralExpr());\r\n }\r\n }\r\n ruleMetaAttributes.add(metaAttributeCall);\r\n }\r\n return ruleMetaAttributes;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void handleAnys(final SyncDelta delta, final List matches, final Provision provision) throws JobExecutionException{\r\n if (matches.isEmpty()) {\r\n LOG.debug(\"Nothing to do\");\r\n return;\r\n }\r\n if (SyncDeltaType.CREATE_OR_UPDATE == delta.getDeltaType()) {\r\n if (matches.get(0).getAny() == null) {\r\n switch(profile.getTask().getUnmatchingRule()) {\r\n case ASSIGN:\r\n case PROVISION:\r\n profile.getResults().addAll(provision(profile.getTask().getUnmatchingRule(), delta, provision));\r\n break;\r\n case IGNORE:\r\n profile.getResults().addAll(ignore(delta, null, provision, false));\r\n break;\r\n default:\r\n }\r\n } else {\r\n virSchemaDAO.findByProvision(provision).forEach(schema -> {\r\n Attribute attr = delta.getObject().getAttributeByName(schema.getExtAttrName());\r\n matches.forEach(match -> {\r\n VirAttrCacheKey cacheKey = new VirAttrCacheKey(provision.getAnyType().getKey(), match.getAny().getKey(), schema.getKey());\r\n if (attr == null) {\r\n virAttrCache.expire(cacheKey);\r\n } else {\r\n virAttrCache.put(cacheKey, new VirAttrCacheValue(attr.getValue()));\r\n }\r\n });\r\n });\r\n switch(profile.getTask().getMatchingRule()) {\r\n case UPDATE:\r\n profile.getResults().addAll(update(delta, matches, provision));\r\n break;\r\n case DEPROVISION:\r\n case UNASSIGN:\r\n profile.getResults().addAll(deprovision(profile.getTask().getMatchingRule(), delta, matches, provision));\r\n break;\r\n case LINK:\r\n profile.getResults().addAll(link(delta, matches, provision, false));\r\n break;\r\n case UNLINK:\r\n profile.getResults().addAll(link(delta, matches, provision, true));\r\n break;\r\n case IGNORE:\r\n profile.getResults().addAll(ignore(delta, matches, provision, true));\r\n break;\r\n default:\r\n }\r\n }\r\n } else if (SyncDeltaType.DELETE == delta.getDeltaType()) {\r\n profile.getResults().addAll(delete(delta, matches, provision));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List decode(ClientMessage.Frame frame, int itemSizeInBytes, DecodeFunction decodeFunction){\r\n byte type = decodeByte(frame.content, 0);\r\n int count = decodeInt(frame.content, 1);\r\n ArrayList res = new ArrayList<>(count);\r\n switch(type) {\r\n case TYPE_NULL_ONLY:\r\n for (int i = 0; i < count; i++) {\r\n res.add(null);\r\n }\r\n break;\r\n case TYPE_NOT_NULL_ONLY:\r\n for (int i = 0; i < count; i++) {\r\n res.add(decodeFunction.decode(frame.content, HEADER_SIZE + i * itemSizeInBytes));\r\n }\r\n break;\r\n default:\r\n assert type == TYPE_MIXED;\r\n int position = HEADER_SIZE;\r\n int readCount = 0;\r\n while (readCount < count) {\r\n int bitmask = decodeByte(frame.content, position++);\r\n for (int i = 0; i < ITEMS_PER_BITMASK && readCount < count; i++) {\r\n int mask = 1 << i;\r\n if ((bitmask & mask) == mask) {\r\n res.add(decodeFunction.decode(frame.content, position));\r\n position += itemSizeInBytes;\r\n } else {\r\n res.add(null);\r\n }\r\n readCount++;\r\n }\r\n }\r\n assert readCount == res.size();\r\n }\r\n return res;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void parseAttributeClauseForSchemaTemplate(IoTDBSqlParser.AttributeClausesContext ctx, List dataTypes, List encodings, List compressors){\r\n if (ctx.aliasNodeName() != null) {\r\n throw new SemanticException(\"Schema template: alias is not supported yet.\");\r\n }\r\n TSDataType dataType = parseDataTypeAttribute(ctx);\r\n dataTypes.add(dataType);\r\n Map props = new HashMap<>();\r\n if (ctx.attributePair() != null) {\r\n for (int i = 0; i < ctx.attributePair().size(); i++) {\r\n props.put(parseAttributeKey(ctx.attributePair(i).attributeKey()).toLowerCase(), parseAttributeValue(ctx.attributePair(i).attributeValue()));\r\n }\r\n }\r\n TSEncoding encoding = IoTDBDescriptor.getInstance().getDefaultEncodingByType(dataType);\r\n if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase())) {\r\n String encodingString = props.get(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase()).toUpperCase();\r\n try {\r\n encoding = TSEncoding.valueOf(encodingString);\r\n encodings.add(encoding);\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported encoding: %s\", encodingString));\r\n }\r\n } else {\r\n encodings.add(encoding);\r\n }\r\n CompressionType compressor = TSFileDescriptor.getInstance().getConfig().getCompressor();\r\n if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase())) {\r\n String compressorString = props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase()).toUpperCase();\r\n try {\r\n compressor = CompressionType.valueOf(compressorString);\r\n compressors.add(compressor);\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported compressor: %s\", compressorString));\r\n }\r\n } else if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase())) {\r\n String compressionString = props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase()).toUpperCase();\r\n try {\r\n compressor = CompressionType.valueOf(compressionString);\r\n compressors.add(compressor);\r\n props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase());\r\n } catch (Exception e) {\r\n throw new SemanticException(String.format(\"Unsupported compression: %s\", compressionString));\r\n }\r\n } else {\r\n compressors.add(compressor);\r\n }\r\n if (props.size() > 0) {\r\n throw new SemanticException(\"Schema template: property is not supported yet.\");\r\n }\r\n if (ctx.tagClause() != null) {\r\n throw new SemanticException(\"Schema template: tag is not supported yet.\");\r\n }\r\n if (ctx.attributeClause() != null) {\r\n throw new SemanticException(\"Schema template: attribute is not supported yet.\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static SqlNode pushDownNotForIn(SqlValidatorScope scope, SqlNode sqlNode){\r\n if (!(sqlNode instanceof SqlCall) || !containsIn(sqlNode)) {\r\n return sqlNode;\r\n }\r\n final SqlCall sqlCall = (SqlCall) sqlNode;\r\n switch(sqlCall.getKind()) {\r\n case AND:\r\n case OR:\r\n final List operands = new ArrayList<>();\r\n for (SqlNode operand : sqlCall.getOperandList()) {\r\n operands.add(pushDownNotForIn(scope, operand));\r\n }\r\n final SqlCall newCall = sqlCall.getOperator().createCall(sqlCall.getParserPosition(), operands);\r\n return reg(scope, newCall);\r\n case NOT:\r\n assert sqlCall.operand(0) instanceof SqlCall;\r\n final SqlCall call = sqlCall.operand(0);\r\n switch(sqlCall.operand(0).getKind()) {\r\n case CASE:\r\n final SqlCase caseNode = (SqlCase) call;\r\n final SqlNodeList thenOperands = new SqlNodeList(SqlParserPos.ZERO);\r\n for (SqlNode thenOperand : caseNode.getThenOperands()) {\r\n final SqlCall not = SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, thenOperand);\r\n thenOperands.add(pushDownNotForIn(scope, reg(scope, not)));\r\n }\r\n SqlNode elseOperand = requireNonNull(caseNode.getElseOperand(), \"getElseOperand for \" + caseNode);\r\n if (!SqlUtil.isNull(elseOperand)) {\r\n final SqlCall not = SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, elseOperand);\r\n elseOperand = pushDownNotForIn(scope, reg(scope, not));\r\n }\r\n return reg(scope, SqlStdOperatorTable.CASE.createCall(SqlParserPos.ZERO, caseNode.getValueOperand(), caseNode.getWhenOperands(), thenOperands, elseOperand));\r\n case AND:\r\n final List orOperands = new ArrayList<>();\r\n for (SqlNode operand : call.getOperandList()) {\r\n orOperands.add(pushDownNotForIn(scope, reg(scope, SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, operand))));\r\n }\r\n return reg(scope, SqlStdOperatorTable.OR.createCall(SqlParserPos.ZERO, orOperands));\r\n case OR:\r\n final List andOperands = new ArrayList<>();\r\n for (SqlNode operand : call.getOperandList()) {\r\n andOperands.add(pushDownNotForIn(scope, reg(scope, SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, operand))));\r\n }\r\n return reg(scope, SqlStdOperatorTable.AND.createCall(SqlParserPos.ZERO, andOperands));\r\n case NOT:\r\n assert call.operandCount() == 1;\r\n return pushDownNotForIn(scope, call.operand(0));\r\n case NOT_IN:\r\n return reg(scope, SqlStdOperatorTable.IN.createCall(SqlParserPos.ZERO, call.getOperandList()));\r\n case IN:\r\n return reg(scope, SqlStdOperatorTable.NOT_IN.createCall(SqlParserPos.ZERO, call.getOperandList()));\r\n default:\r\n break;\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n return sqlNode;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AddResponse getAddResponse(){\r\n final long startTimeNanos = MathUtils.nowInNano();\r\n AddRequest addRequest = request.getAddRequest();\r\n long ledgerId = addRequest.getLedgerId();\r\n long entryId = addRequest.getEntryId();\r\n final AddResponse.Builder addResponse = AddResponse.newBuilder().setLedgerId(ledgerId).setEntryId(entryId);\r\n if (!isVersionCompatible()) {\r\n addResponse.setStatus(StatusCode.EBADVERSION);\r\n return addResponse.build();\r\n }\r\n if (requestProcessor.getBookie().isReadOnly() && !(RequestUtils.isHighPriority(request) && requestProcessor.getBookie().isAvailableForHighPriorityWrites())) {\r\n logger.warn(\"BookieServer is running as readonly mode, so rejecting the request from the client!\");\r\n addResponse.setStatus(StatusCode.EREADONLY);\r\n return addResponse.build();\r\n }\r\n BookkeeperInternalCallbacks.WriteCallback wcb = new BookkeeperInternalCallbacks.WriteCallback() {\r\n\r\n @Override\r\n public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {\r\n if (BookieProtocol.EOK == rc) {\r\n requestProcessor.getRequestStats().getAddEntryStats().registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS);\r\n } else {\r\n requestProcessor.getRequestStats().getAddEntryStats().registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS);\r\n }\r\n StatusCode status;\r\n switch(rc) {\r\n case BookieProtocol.EOK:\r\n status = StatusCode.EOK;\r\n break;\r\n case BookieProtocol.EIO:\r\n status = StatusCode.EIO;\r\n break;\r\n default:\r\n status = StatusCode.EUA;\r\n break;\r\n }\r\n addResponse.setStatus(status);\r\n Response.Builder response = Response.newBuilder().setHeader(getHeader()).setStatus(addResponse.getStatus()).setAddResponse(addResponse);\r\n Response resp = response.build();\r\n sendResponse(status, resp, requestProcessor.getRequestStats().getAddRequestStats());\r\n }\r\n };\r\n final EnumSet writeFlags;\r\n if (addRequest.hasWriteFlags()) {\r\n writeFlags = WriteFlag.getWriteFlags(addRequest.getWriteFlags());\r\n } else {\r\n writeFlags = WriteFlag.NONE;\r\n }\r\n final boolean ackBeforeSync = writeFlags.contains(WriteFlag.DEFERRED_SYNC);\r\n StatusCode status = null;\r\n byte[] masterKey = addRequest.getMasterKey().toByteArray();\r\n ByteBuf entryToAdd = Unpooled.wrappedBuffer(addRequest.getBody().asReadOnlyByteBuffer());\r\n try {\r\n if (RequestUtils.hasFlag(addRequest, AddRequest.Flag.RECOVERY_ADD)) {\r\n requestProcessor.getBookie().recoveryAddEntry(entryToAdd, wcb, channel, masterKey);\r\n } else {\r\n requestProcessor.getBookie().addEntry(entryToAdd, ackBeforeSync, wcb, channel, masterKey);\r\n }\r\n status = StatusCode.EOK;\r\n } catch (OperationRejectedException e) {\r\n requestProcessor.getRequestStats().getAddEntryRejectedCounter().inc();\r\n if (logger.isDebugEnabled()) {\r\n logger.debug(\"Operation rejected while writing {}\", request, e);\r\n }\r\n status = StatusCode.ETOOMANYREQUESTS;\r\n } catch (IOException e) {\r\n logger.error(\"Error writing entry:{} to ledger:{}\", entryId, ledgerId, e);\r\n status = StatusCode.EIO;\r\n } catch (BookieException.LedgerFencedException e) {\r\n logger.error(\"Ledger fenced while writing entry:{} to ledger:{}\", entryId, ledgerId, e);\r\n status = StatusCode.EFENCED;\r\n } catch (BookieException e) {\r\n logger.error(\"Unauthorized access to ledger:{} while writing entry:{}\", ledgerId, entryId, e);\r\n status = StatusCode.EUA;\r\n } catch (Throwable t) {\r\n logger.error(\"Unexpected exception while writing {}@{} : \", entryId, ledgerId, t);\r\n status = StatusCode.EBADREQ;\r\n }\r\n if (!status.equals(StatusCode.EOK)) {\r\n addResponse.setStatus(status);\r\n return addResponse.build();\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private SecuritySchemeDefinition convertSecurityScheme(SecurityScheme securityScheme){\r\n SecuritySchemeDefinition swaggerScheme = null;\r\n switch(securityScheme.getType()) {\r\n case HTTP:\r\n if (\"basic\".equals(securityScheme.getName())) {\r\n swaggerScheme = new BasicAuthDefinition();\r\n } else {\r\n throw new IllegalStateException(\"OpenAPI 2.0 does not support bearer token security schemes.\");\r\n }\r\n break;\r\n case APIKEY:\r\n if (securityScheme.getIn() == SecurityScheme.In.COOKIE) {\r\n throw new IllegalStateException(\"Invalid 'in' value for API Key security scheme\");\r\n } else {\r\n swaggerScheme = new ApiKeyAuthDefinition(securityScheme.getName(), In.forValue(securityScheme.getIn().name()));\r\n }\r\n break;\r\n case OAUTH2:\r\n OAuth2Definition oauth2 = new OAuth2Definition();\r\n OAuthFlows flows = securityScheme.getFlows();\r\n Scopes scopes = null;\r\n if (flows.getImplicit() != null) {\r\n oauth2.implicit(flows.getImplicit().getAuthorizationUrl());\r\n scopes = flows.getImplicit().getScopes();\r\n } else if (flows.getPassword() != null) {\r\n oauth2.password(flows.getPassword().getTokenUrl());\r\n scopes = flows.getPassword().getScopes();\r\n } else if (flows.getClientCredentials() != null) {\r\n oauth2.application(flows.getClientCredentials().getTokenUrl());\r\n scopes = flows.getClientCredentials().getScopes();\r\n } else if (flows.getAuthorizationCode() != null) {\r\n oauth2.accessCode(flows.getAuthorizationCode().getAuthorizationUrl(), flows.getAuthorizationCode().getTokenUrl());\r\n scopes = flows.getAuthorizationCode().getScopes();\r\n } else {\r\n }\r\n if (scopes != null) {\r\n for (Map.Entry entry : scopes.entrySet()) {\r\n oauth2.addScope(entry.getKey(), entry.getValue());\r\n }\r\n }\r\n swaggerScheme = oauth2;\r\n break;\r\n default:\r\n throw new IllegalStateException(\"Security scheme \" + securityScheme.getType().toString() + \"is not supported in OpenAPI 2\");\r\n }\r\n if (swaggerScheme != null && securityScheme.getDescription() != null) {\r\n swaggerScheme.setDescription(securityScheme.getDescription());\r\n }\r\n return swaggerScheme;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void expand(final ArchiveEntrySupplier supplier, final EntryWriter writer, final Path targetDirectory) throws IOException{\r\n final boolean nullTarget = targetDirectory == null;\r\n final Path targetDirPath = nullTarget ? null : targetDirectory.normalize();\r\n ArchiveEntry nextEntry = supplier.getNextReadableEntry();\r\n while (nextEntry != null) {\r\n final Path targetPath = nullTarget ? null : targetDirectory.resolve(nextEntry.getName());\r\n if (!nullTarget && !targetPath.normalize().startsWith(targetDirPath) && !Files.isSameFile(targetDirectory, targetPath)) {\r\n throw new IOException(\"Expanding \" + nextEntry.getName() + \" would create file outside of \" + targetDirectory);\r\n }\r\n if (nextEntry.isDirectory()) {\r\n if (!nullTarget && !Files.isDirectory(targetPath) && Files.createDirectories(targetPath) == null) {\r\n throw new IOException(\"Failed to create directory \" + targetPath);\r\n }\r\n } else {\r\n final Path parent = nullTarget ? null : targetPath.getParent();\r\n if (!nullTarget && !Files.isDirectory(parent) && Files.createDirectories(parent) == null) {\r\n throw new IOException(\"Failed to create directory \" + parent);\r\n }\r\n if (nullTarget) {\r\n writer.writeEntryDataTo(nextEntry, null);\r\n } else {\r\n try (OutputStream outputStream = Files.newOutputStream(targetPath)) {\r\n writer.writeEntryDataTo(nextEntry, outputStream);\r\n }\r\n }\r\n }\r\n nextEntry = supplier.getNextReadableEntry();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void checkLedger(final LedgerHandle lh, final GenericCallback> cb, long percentageOfLedgerFragmentToBeVerified){\r\n final Set fragments = new LinkedHashSet<>();\r\n Long curEntryId = null;\r\n List curEnsemble = null;\r\n for (Map.Entry> e : lh.getLedgerMetadata().getAllEnsembles().entrySet()) {\r\n if (curEntryId != null) {\r\n Set bookieIndexes = new HashSet();\r\n for (int i = 0; i < curEnsemble.size(); i++) {\r\n bookieIndexes.add(i);\r\n }\r\n fragments.add(new LedgerFragment(lh, curEntryId, e.getKey() - 1, bookieIndexes));\r\n }\r\n curEntryId = e.getKey();\r\n curEnsemble = e.getValue();\r\n }\r\n if (curEntryId != null) {\r\n long lastEntry = lh.getLastAddConfirmed();\r\n if (!lh.isClosed() && lastEntry < curEntryId) {\r\n lastEntry = curEntryId;\r\n }\r\n Set bookieIndexes = new HashSet();\r\n for (int i = 0; i < curEnsemble.size(); i++) {\r\n bookieIndexes.add(i);\r\n }\r\n final LedgerFragment lastLedgerFragment = new LedgerFragment(lh, curEntryId, lastEntry, bookieIndexes);\r\n if (curEntryId == lastEntry) {\r\n final long entryToRead = curEntryId;\r\n final CompletableFuture future = new CompletableFuture<>();\r\n future.whenCompleteAsync((re, ex) -> {\r\n checkFragments(fragments, cb, percentageOfLedgerFragmentToBeVerified);\r\n });\r\n final EntryExistsCallback eecb = new EntryExistsCallback(lh.getLedgerMetadata().getWriteQuorumSize(), new GenericCallback() {\r\n\r\n @Override\r\n public void operationComplete(int rc, Boolean result) {\r\n if (result) {\r\n fragments.add(lastLedgerFragment);\r\n }\r\n future.complete(null);\r\n }\r\n });\r\n DistributionSchedule ds = lh.getDistributionSchedule();\r\n for (int i = 0; i < ds.getWriteQuorumSize(); i++) {\r\n try {\r\n acquirePermit();\r\n BookieId addr = curEnsemble.get(ds.getWriteSetBookieIndex(entryToRead, i));\r\n bookieClient.readEntry(addr, lh.getId(), entryToRead, eecb, null, BookieProtocol.FLAG_NONE);\r\n } catch (InterruptedException e) {\r\n LOG.error(\"InterruptedException when checking entry : {}\", entryToRead, e);\r\n }\r\n }\r\n return;\r\n } else {\r\n fragments.add(lastLedgerFragment);\r\n }\r\n }\r\n checkFragments(fragments, cb, percentageOfLedgerFragmentToBeVerified);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void enumerative(EnumDeclarationDescrBuilder declare){\r\n EnumLiteralDescrBuilder literal = null;\r\n String lit = null;\r\n try {\r\n Token enumLit = match(input, DRL6Lexer.ID, null, null, DroolsEditorType.IDENTIFIER);\r\n lit = enumLit.getText();\r\n if (state.failed)\r\n return;\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n }\r\n try {\r\n literal = helper.start(declare, EnumLiteralDescrBuilder.class, lit);\r\n if (input.LA(1) == DRL6Lexer.LEFT_PAREN) {\r\n match(input, DRL6Lexer.LEFT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n boolean more;\r\n do {\r\n int first = input.index();\r\n exprParser.conditionalExpression();\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0 && input.index() > first) {\r\n String arg = input.toString(first, input.LT(-1).getTokenIndex());\r\n literal.constructorArg(arg);\r\n }\r\n more = input.LA(1) == DRL6Lexer.COMMA;\r\n if (more) {\r\n match(input, DRL6Lexer.COMMA, null, null, DroolsEditorType.SYMBOL);\r\n }\r\n } while (more);\r\n match(input, DRL6Lexer.RIGHT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n }\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n } finally {\r\n helper.end(FieldDescrBuilder.class, literal);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void scan() throws Exception{\r\n ManagedDescription descAnn = getClass().getAnnotation(ManagedDescription.class);\r\n if (descAnn != null) {\r\n description = descAnn.value();\r\n }\r\n for (Method method : getClass().getMethods()) {\r\n if (method.isAnnotationPresent(ManagedAnnotation.class)) {\r\n ManagedAnnotation ann = method.getAnnotation(ManagedAnnotation.class);\r\n String name = ann.value();\r\n if (name.isEmpty()) {\r\n throw new IllegalArgumentException(\"Name cannot be empty!\");\r\n }\r\n boolean operation = ann.operation();\r\n HashMap map = operation ? operationMap : attributeMap;\r\n if (map.containsKey(name)) {\r\n throw new IllegalArgumentException(\"Duplicate name: \" + name);\r\n }\r\n descAnn = method.getAnnotation(ManagedDescription.class);\r\n String desc = null;\r\n if (descAnn != null) {\r\n desc = descAnn.value();\r\n }\r\n map.put(name, new BeanInfo(name, desc, method));\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List validatePartitionSchema(Table table, HCatSchema partitionSchema) throws IOException{\r\n Map partitionKeyMap = new HashMap();\r\n for (FieldSchema field : table.getPartitionKeys()) {\r\n partitionKeyMap.put(field.getName().toLowerCase(), field);\r\n }\r\n List tableCols = table.getCols();\r\n List newFields = new ArrayList();\r\n for (int i = 0; i < partitionSchema.getFields().size(); i++) {\r\n FieldSchema field = HCatSchemaUtils.getFieldSchema(partitionSchema.getFields().get(i));\r\n FieldSchema tableField;\r\n if (i < tableCols.size()) {\r\n tableField = tableCols.get(i);\r\n if (!tableField.getName().equalsIgnoreCase(field.getName())) {\r\n throw new HCatException(ErrorType.ERROR_SCHEMA_COLUMN_MISMATCH, \"Expected column <\" + tableField.getName() + \"> at position \" + (i + 1) + \", found column <\" + field.getName() + \">\");\r\n }\r\n } else {\r\n tableField = partitionKeyMap.get(field.getName().toLowerCase());\r\n if (tableField != null) {\r\n throw new HCatException(ErrorType.ERROR_SCHEMA_PARTITION_KEY, \"Key <\" + field.getName() + \">\");\r\n }\r\n }\r\n if (tableField == null) {\r\n newFields.add(field);\r\n } else {\r\n TypeInfo partitionType = TypeInfoUtils.getTypeInfoFromTypeString(field.getType());\r\n TypeInfo tableType = TypeInfoUtils.getTypeInfoFromTypeString(tableField.getType());\r\n if (!partitionType.equals(tableType)) {\r\n String msg = \"Column <\" + field.getName() + \">, expected <\" + tableType.getTypeName() + \">, got <\" + partitionType.getTypeName() + \">\";\r\n LOG.warn(msg);\r\n throw new HCatException(ErrorType.ERROR_SCHEMA_TYPE_MISMATCH, msg);\r\n }\r\n }\r\n }\r\n return newFields;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void write(List logs, double writeRate, int maxOutstandingBytesForThisThread, long numRecordsForThisThread, long numBytesForThisThread) throws Exception{\r\n log.info(\"Write thread started with : logs = {}, rate = {},\" + \" num records = {}, num bytes = {}, max outstanding bytes = {}\", logs.stream().map(l -> l.getStreamName()).collect(Collectors.toList()), writeRate, numRecordsForThisThread, numBytesForThisThread, maxOutstandingBytesForThisThread);\r\n List> writerFutures = logs.stream().map(manager -> manager.openAsyncLogWriter()).collect(Collectors.toList());\r\n List writers = result(FutureUtils.collect(writerFutures));\r\n long txid = writers.stream().mapToLong(writer -> writer.getLastTxId()).max().orElse(0L);\r\n txid = Math.max(0L, txid);\r\n RateLimiter limiter;\r\n if (writeRate > 0) {\r\n limiter = RateLimiter.create(writeRate);\r\n } else {\r\n limiter = null;\r\n }\r\n final Semaphore semaphore;\r\n if (maxOutstandingBytesForThisThread > 0) {\r\n semaphore = new Semaphore(maxOutstandingBytesForThisThread);\r\n } else {\r\n semaphore = null;\r\n }\r\n if (limiter != null) {\r\n limiter.acquire((int) writeRate);\r\n }\r\n long totalWritten = 0L;\r\n long totalBytesWritten = 0L;\r\n final int numLogs = logs.size();\r\n while (true) {\r\n for (int i = 0; i < numLogs; i++) {\r\n if (numRecordsForThisThread > 0 && totalWritten >= numRecordsForThisThread) {\r\n markPerfDone();\r\n }\r\n if (numBytesForThisThread > 0 && totalBytesWritten >= numBytesForThisThread) {\r\n markPerfDone();\r\n }\r\n if (null != semaphore) {\r\n semaphore.acquire(payload.length);\r\n }\r\n totalWritten++;\r\n totalBytesWritten += payload.length;\r\n if (null != limiter) {\r\n limiter.acquire(payload.length);\r\n }\r\n final long sendTime = System.nanoTime();\r\n writers.get(i).write(new LogRecord(++txid, Unpooled.wrappedBuffer(payload))).thenAccept(dlsn -> {\r\n if (null != semaphore) {\r\n semaphore.release(payload.length);\r\n }\r\n recordsWritten.increment();\r\n bytesWritten.add(payload.length);\r\n long latencyMicros = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sendTime);\r\n recorder.recordValue(latencyMicros);\r\n cumulativeRecorder.recordValue(latencyMicros);\r\n }).exceptionally(cause -> {\r\n log.warn(\"Error at writing records\", cause);\r\n System.exit(-1);\r\n return null;\r\n });\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static int findLogSegmentNotLessThanTxnId(List segments, long transactionId){\r\n int found = -1;\r\n for (int i = segments.size() - 1; i >= 0; i--) {\r\n LogSegmentMetadata segment = segments.get(i);\r\n if (segment.getFirstTxId() <= transactionId) {\r\n found = i;\r\n break;\r\n }\r\n }\r\n if (found <= -1) {\r\n return -1;\r\n }\r\n if (found == 0 && segments.get(0).getFirstTxId() == transactionId) {\r\n return 0;\r\n }\r\n LogSegmentMetadata foundSegment = segments.get(found);\r\n if (foundSegment.getFirstTxId() == transactionId) {\r\n for (int i = found - 1; i >= 0; i--) {\r\n LogSegmentMetadata segment = segments.get(i);\r\n if (segment.isInProgress()) {\r\n break;\r\n }\r\n if (segment.getLastTxId() < transactionId) {\r\n break;\r\n }\r\n found = i;\r\n }\r\n return found;\r\n } else {\r\n if (foundSegment.isInProgress() || found == segments.size() - 1) {\r\n return found;\r\n }\r\n if (foundSegment.getLastTxId() >= transactionId) {\r\n return found;\r\n }\r\n return found + 1;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void tryRemoveRegistration(@Nonnull UUID instanceUuid, @Nonnull Address primaryAddress){\r\n uuidToAddresses.computeIfPresent(instanceUuid, (uuid, linkedAddressesRegistrationCountPair) -> {\r\n LinkedAddresses addresses = linkedAddressesRegistrationCountPair.getAddresses();\r\n if (addresses.contains(primaryAddress)) {\r\n AtomicInteger registrationCount = linkedAddressesRegistrationCountPair.getRegistrationCount();\r\n if (registrationCount.decrementAndGet() == 0) {\r\n Iterator iterator = addressToUuid.values().iterator();\r\n while (iterator.hasNext()) {\r\n UUID currUuid = iterator.next();\r\n if (currUuid.equals(instanceUuid)) {\r\n iterator.remove();\r\n }\r\n }\r\n if (logger.isFineEnabled()) {\r\n logger.fine(addresses + \" previously registered for the instance uuid=\" + instanceUuid + \" are removed from the registry\");\r\n }\r\n return null;\r\n }\r\n }\r\n return linkedAddressesRegistrationCountPair;\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void produceAndCollectRoutePoints(Context context, List routes, ExportableNetexData exportableNetexData){\r\n for (mobi.chouette.model.Route route : routes) {\r\n for (mobi.chouette.model.RoutePoint neptuneRoutePoint : route.getRoutePoints()) {\r\n if (neptuneRoutePoint != null) {\r\n if (isSet(neptuneRoutePoint.getScheduledStopPoint().getContainedInStopAreaRef().getObject())) {\r\n if (!exportableNetexData.getSharedRoutePoints().containsKey(neptuneRoutePoint.getObjectId())) {\r\n RoutePoint routePoint = createRoutePoint(context, neptuneRoutePoint);\r\n exportableNetexData.getSharedRoutePoints().put(routePoint.getId(), routePoint);\r\n }\r\n } else {\r\n throw new RuntimeException(\"RoutePoint \" + neptuneRoutePoint.getObjectId() + \" refers to a ScheduledStopPoint \" + neptuneRoutePoint.getScheduledStopPoint().getObjectId() + \" (\" + neptuneRoutePoint.getScheduledStopPoint().getName() + \") that is not contained in a StopArea.\");\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final Project project = call.rel(0);\r\n final Window window = call.rel(1);\r\n final RelOptCluster cluster = window.getCluster();\r\n final List rowTypeWindowInput = window.getInput().getRowType().getFieldList();\r\n final int windowInputColumn = rowTypeWindowInput.size();\r\n final ImmutableBitSet beReferred = findReference(project, window);\r\n if (beReferred.cardinality() == windowInputColumn) {\r\n return;\r\n }\r\n final List exps = new ArrayList<>();\r\n final RelDataTypeFactory.Builder builder = cluster.getTypeFactory().builder();\r\n for (int index : BitSets.toIter(beReferred)) {\r\n final RelDataTypeField relDataTypeField = rowTypeWindowInput.get(index);\r\n exps.add(new RexInputRef(index, relDataTypeField.getType()));\r\n builder.add(relDataTypeField);\r\n }\r\n final LogicalProject projectBelowWindow = new LogicalProject(cluster, window.getTraitSet(), ImmutableList.of(), window.getInput(), exps, builder.build(), ImmutableSet.of());\r\n final List groups = new ArrayList<>();\r\n final RexShuttle indexAdjustment = new RexShuttle() {\r\n\r\n @Override\r\n public RexNode visitInputRef(RexInputRef inputRef) {\r\n final int newIndex = getAdjustedIndex(inputRef.getIndex(), beReferred, windowInputColumn);\r\n return new RexInputRef(newIndex, inputRef.getType());\r\n }\r\n\r\n @Override\r\n public RexNode visitCall(final RexCall call) {\r\n if (call instanceof Window.RexWinAggCall) {\r\n final Window.RexWinAggCall aggCall = (Window.RexWinAggCall) call;\r\n boolean[] update = { false };\r\n final List clonedOperands = visitList(call.operands, update);\r\n if (update[0]) {\r\n return new Window.RexWinAggCall((SqlAggFunction) call.getOperator(), call.getType(), clonedOperands, aggCall.ordinal, aggCall.distinct, aggCall.ignoreNulls);\r\n } else {\r\n return call;\r\n }\r\n } else {\r\n return super.visitCall(call);\r\n }\r\n }\r\n };\r\n int aggCallIndex = windowInputColumn;\r\n final RelDataTypeFactory.Builder outputBuilder = cluster.getTypeFactory().builder();\r\n outputBuilder.addAll(projectBelowWindow.getRowType().getFieldList());\r\n for (Window.Group group : window.groups) {\r\n final ImmutableBitSet.Builder keys = ImmutableBitSet.builder();\r\n final List orderKeys = new ArrayList<>();\r\n final List aggCalls = new ArrayList<>();\r\n for (int index : group.keys) {\r\n keys.set(getAdjustedIndex(index, beReferred, windowInputColumn));\r\n }\r\n for (RelFieldCollation relFieldCollation : group.orderKeys.getFieldCollations()) {\r\n final int index = relFieldCollation.getFieldIndex();\r\n orderKeys.add(relFieldCollation.withFieldIndex(getAdjustedIndex(index, beReferred, windowInputColumn)));\r\n }\r\n for (Window.RexWinAggCall rexWinAggCall : group.aggCalls) {\r\n aggCalls.add((Window.RexWinAggCall) rexWinAggCall.accept(indexAdjustment));\r\n final RelDataTypeField relDataTypeField = window.getRowType().getFieldList().get(aggCallIndex);\r\n outputBuilder.add(relDataTypeField);\r\n ++aggCallIndex;\r\n }\r\n groups.add(new Window.Group(keys.build(), group.isRows, group.lowerBound, group.upperBound, RelCollations.of(orderKeys), aggCalls));\r\n }\r\n final LogicalWindow newLogicalWindow = LogicalWindow.create(window.getTraitSet(), projectBelowWindow, window.constants, outputBuilder.build(), groups);\r\n final List topProjExps = indexAdjustment.visitList(project.getProjects());\r\n final Project newTopProj = project.copy(newLogicalWindow.getTraitSet(), newLogicalWindow, topProjExps, project.getRowType());\r\n if (ProjectRemoveRule.isTrivial(newTopProj)) {\r\n call.transformTo(newLogicalWindow);\r\n } else {\r\n call.transformTo(newTopProj);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " long put(long key, long value, int keyHash, boolean onlyIfAbsent, LongLongFunction valueProvider){\r\n long stamp = writeLock();\r\n int bucket = signSafeMod(keyHash, capacity);\r\n int firstDeletedKey = -1;\r\n try {\r\n while (true) {\r\n long storedKey = table[bucket];\r\n long storedValue = table[bucket + 1];\r\n if (key == storedKey) {\r\n if (!onlyIfAbsent) {\r\n table[bucket + 1] = value;\r\n return storedValue;\r\n } else {\r\n return storedValue;\r\n }\r\n } else if (storedKey == EmptyKey) {\r\n if (firstDeletedKey != -1) {\r\n bucket = firstDeletedKey;\r\n } else {\r\n ++usedBuckets;\r\n }\r\n if (value == ValueNotFound) {\r\n value = valueProvider.apply(key);\r\n }\r\n table[bucket] = key;\r\n table[bucket + 1] = value;\r\n ++size;\r\n return valueProvider != null ? value : ValueNotFound;\r\n } else if (storedKey == DeletedKey) {\r\n if (firstDeletedKey == -1) {\r\n firstDeletedKey = bucket;\r\n }\r\n }\r\n bucket = (bucket + 2) & (table.length - 1);\r\n }\r\n } finally {\r\n if (usedBuckets > resizeThresholdUp) {\r\n try {\r\n int newCapacity = alignToPowerOfTwo((int) (capacity * expandFactor));\r\n rehash(newCapacity);\r\n } finally {\r\n unlockWrite(stamp);\r\n }\r\n } else {\r\n unlockWrite(stamp);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SCIMUser toSCIMUser(final UserTO userTO, final String location, final List attributes, final List excludedAttributes){\r\n SCIMConf conf = confManager.get();\r\n List schemas = new ArrayList<>();\r\n schemas.add(Resource.User.schema());\r\n if (conf.getEnterpriseUserConf() != null) {\r\n schemas.add(Resource.EnterpriseUser.schema());\r\n }\r\n SCIMUser user = new SCIMUser(userTO.getKey(), schemas, new Meta(Resource.User, userTO.getCreationDate(), userTO.getLastChangeDate() == null ? userTO.getCreationDate() : userTO.getLastChangeDate(), userTO.getETagValue(), location), output(attributes, excludedAttributes, \"userName\", userTO.getUsername()), !userTO.isSuspended());\r\n Map attrs = new HashMap<>();\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getPlainAttrs()));\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getDerAttrs()));\r\n attrs.putAll(EntityTOUtils.buildAttrMap(userTO.getVirAttrs()));\r\n attrs.put(\"username\", new Attr.Builder(\"username\").value(userTO.getUsername()).build());\r\n if (conf.getUserConf() != null) {\r\n if (output(attributes, excludedAttributes, \"name\") && conf.getUserConf().getName() != null) {\r\n SCIMUserName name = new SCIMUserName();\r\n if (conf.getUserConf().getName().getFamilyName() != null && attrs.containsKey(conf.getUserConf().getName().getFamilyName())) {\r\n name.setFamilyName(attrs.get(conf.getUserConf().getName().getFamilyName()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getFormatted() != null && attrs.containsKey(conf.getUserConf().getName().getFormatted())) {\r\n name.setFormatted(attrs.get(conf.getUserConf().getName().getFormatted()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getGivenName() != null && attrs.containsKey(conf.getUserConf().getName().getGivenName())) {\r\n name.setGivenName(attrs.get(conf.getUserConf().getName().getGivenName()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getHonorificPrefix() != null && attrs.containsKey(conf.getUserConf().getName().getHonorificPrefix())) {\r\n name.setHonorificPrefix(attrs.get(conf.getUserConf().getName().getHonorificPrefix()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getHonorificSuffix() != null && attrs.containsKey(conf.getUserConf().getName().getHonorificSuffix())) {\r\n name.setHonorificSuffix(attrs.get(conf.getUserConf().getName().getHonorificSuffix()).getValues().get(0));\r\n }\r\n if (conf.getUserConf().getName().getMiddleName() != null && attrs.containsKey(conf.getUserConf().getName().getMiddleName())) {\r\n name.setMiddleName(attrs.get(conf.getUserConf().getName().getMiddleName()).getValues().get(0));\r\n }\r\n if (!name.isEmpty()) {\r\n user.setName(name);\r\n }\r\n }\r\n if (output(attributes, excludedAttributes, \"displayName\") && conf.getUserConf().getDisplayName() != null && attrs.containsKey(conf.getUserConf().getDisplayName())) {\r\n user.setDisplayName(attrs.get(conf.getUserConf().getDisplayName()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"nickName\") && conf.getUserConf().getNickName() != null && attrs.containsKey(conf.getUserConf().getNickName())) {\r\n user.setNickName(attrs.get(conf.getUserConf().getNickName()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"profileUrl\") && conf.getUserConf().getProfileUrl() != null && attrs.containsKey(conf.getUserConf().getProfileUrl())) {\r\n user.setProfileUrl(attrs.get(conf.getUserConf().getProfileUrl()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"title\") && conf.getUserConf().getTitle() != null && attrs.containsKey(conf.getUserConf().getTitle())) {\r\n user.setTitle(attrs.get(conf.getUserConf().getTitle()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"userType\") && conf.getUserConf().getUserType() != null && attrs.containsKey(conf.getUserConf().getUserType())) {\r\n user.setUserType(attrs.get(conf.getUserConf().getUserType()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"preferredLanguage\") && conf.getUserConf().getPreferredLanguage() != null && attrs.containsKey(conf.getUserConf().getPreferredLanguage())) {\r\n user.setPreferredLanguage(attrs.get(conf.getUserConf().getPreferredLanguage()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"locale\") && conf.getUserConf().getLocale() != null && attrs.containsKey(conf.getUserConf().getLocale())) {\r\n user.setLocale(attrs.get(conf.getUserConf().getLocale()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"timezone\") && conf.getUserConf().getTimezone() != null && attrs.containsKey(conf.getUserConf().getTimezone())) {\r\n user.setTimezone(attrs.get(conf.getUserConf().getTimezone()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"emails\")) {\r\n fill(attrs, conf.getUserConf().getEmails(), user.getEmails());\r\n }\r\n if (output(attributes, excludedAttributes, \"phoneNumbers\")) {\r\n fill(attrs, conf.getUserConf().getPhoneNumbers(), user.getPhoneNumbers());\r\n }\r\n if (output(attributes, excludedAttributes, \"ims\")) {\r\n fill(attrs, conf.getUserConf().getIms(), user.getIms());\r\n }\r\n if (output(attributes, excludedAttributes, \"photos\")) {\r\n fill(attrs, conf.getUserConf().getPhotos(), user.getPhotos());\r\n }\r\n if (output(attributes, excludedAttributes, \"addresses\")) {\r\n conf.getUserConf().getAddresses().forEach(addressConf -> {\r\n SCIMUserAddress address = new SCIMUserAddress();\r\n if (addressConf.getFormatted() != null && attrs.containsKey(addressConf.getFormatted())) {\r\n address.setFormatted(attrs.get(addressConf.getFormatted()).getValues().get(0));\r\n }\r\n if (addressConf.getStreetAddress() != null && attrs.containsKey(addressConf.getStreetAddress())) {\r\n address.setStreetAddress(attrs.get(addressConf.getStreetAddress()).getValues().get(0));\r\n }\r\n if (addressConf.getLocality() != null && attrs.containsKey(addressConf.getLocality())) {\r\n address.setLocality(attrs.get(addressConf.getLocality()).getValues().get(0));\r\n }\r\n if (addressConf.getRegion() != null && attrs.containsKey(addressConf.getRegion())) {\r\n address.setRegion(attrs.get(addressConf.getRegion()).getValues().get(0));\r\n }\r\n if (addressConf.getCountry() != null && attrs.containsKey(addressConf.getCountry())) {\r\n address.setCountry(attrs.get(addressConf.getCountry()).getValues().get(0));\r\n }\r\n if (addressConf.getType() != null) {\r\n address.setType(addressConf.getType().name());\r\n }\r\n if (addressConf.isPrimary()) {\r\n address.setPrimary(true);\r\n }\r\n if (!address.isEmpty()) {\r\n user.getAddresses().add(address);\r\n }\r\n });\r\n }\r\n if (output(attributes, excludedAttributes, \"x509Certificates\")) {\r\n conf.getUserConf().getX509Certificates().stream().filter(attrs::containsKey).forEachOrdered(certificate -> user.getX509Certificates().add(new Value(attrs.get(certificate).getValues().get(0))));\r\n }\r\n if (conf.getEnterpriseUserConf() != null) {\r\n SCIMEnterpriseInfo enterpriseInfo = new SCIMEnterpriseInfo();\r\n if (output(attributes, excludedAttributes, \"employeeNumber\") && conf.getEnterpriseUserConf().getEmployeeNumber() != null && attrs.containsKey(conf.getEnterpriseUserConf().getEmployeeNumber())) {\r\n enterpriseInfo.setEmployeeNumber(attrs.get(conf.getEnterpriseUserConf().getEmployeeNumber()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"costCenter\") && conf.getEnterpriseUserConf().getCostCenter() != null && attrs.containsKey(conf.getEnterpriseUserConf().getCostCenter())) {\r\n enterpriseInfo.setCostCenter(attrs.get(conf.getEnterpriseUserConf().getCostCenter()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"organization\") && conf.getEnterpriseUserConf().getOrganization() != null && attrs.containsKey(conf.getEnterpriseUserConf().getOrganization())) {\r\n enterpriseInfo.setOrganization(attrs.get(conf.getEnterpriseUserConf().getOrganization()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"division\") && conf.getEnterpriseUserConf().getDivision() != null && attrs.containsKey(conf.getEnterpriseUserConf().getDivision())) {\r\n enterpriseInfo.setDivision(attrs.get(conf.getEnterpriseUserConf().getDivision()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"department\") && conf.getEnterpriseUserConf().getDepartment() != null && attrs.containsKey(conf.getEnterpriseUserConf().getDepartment())) {\r\n enterpriseInfo.setDepartment(attrs.get(conf.getEnterpriseUserConf().getDepartment()).getValues().get(0));\r\n }\r\n if (output(attributes, excludedAttributes, \"manager\") && conf.getEnterpriseUserConf().getManager() != null) {\r\n SCIMUserManager manager = new SCIMUserManager();\r\n if (conf.getEnterpriseUserConf().getManager().getKey() != null && attrs.containsKey(conf.getEnterpriseUserConf().getManager().getKey())) {\r\n try {\r\n UserTO userManager = userLogic.read(attrs.get(conf.getEnterpriseUserConf().getManager().getKey()).getValues().get(0));\r\n manager.setValue(userManager.getKey());\r\n manager.setRef(StringUtils.substringBefore(location, \"/Users\") + \"/Users/\" + userManager.getKey());\r\n if (conf.getEnterpriseUserConf().getManager().getDisplayName() != null) {\r\n Attr displayName = userManager.getPlainAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n if (displayName == null) {\r\n displayName = userManager.getDerAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n }\r\n if (displayName == null) {\r\n displayName = userManager.getVirAttr(conf.getEnterpriseUserConf().getManager().getDisplayName()).orElse(null);\r\n }\r\n if (displayName != null) {\r\n manager.setDisplayName(displayName.getValues().get(0));\r\n }\r\n }\r\n } catch (Exception e) {\r\n LOG.error(\"Could not read user {}\", conf.getEnterpriseUserConf().getManager().getKey(), e);\r\n }\r\n }\r\n if (!manager.isEmpty()) {\r\n enterpriseInfo.setManager(manager);\r\n }\r\n }\r\n if (!enterpriseInfo.isEmpty()) {\r\n user.setEnterpriseInfo(enterpriseInfo);\r\n }\r\n }\r\n if (output(attributes, excludedAttributes, \"groups\")) {\r\n userTO.getMemberships().forEach(membership -> user.getGroups().add(new Group(membership.getGroupKey(), StringUtils.substringBefore(location, \"/Users\") + \"/Groups/\" + membership.getGroupKey(), membership.getGroupName(), Function.direct)));\r\n userTO.getDynMemberships().forEach(membership -> user.getGroups().add(new Group(membership.getGroupKey(), StringUtils.substringBefore(location, \"/Users\") + \"/Groups/\" + membership.getGroupKey(), membership.getGroupName(), Function.indirect)));\r\n }\r\n if (output(attributes, excludedAttributes, \"entitlements\")) {\r\n authDataAccessor.getAuthorities(userTO.getUsername(), null).forEach(authority -> user.getEntitlements().add(new Value(authority.getAuthority() + \" on Realm(s) \" + authority.getRealms())));\r\n }\r\n if (output(attributes, excludedAttributes, \"roles\")) {\r\n userTO.getRoles().forEach(role -> user.getRoles().add(new Value(role)));\r\n }\r\n }\r\n return user;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " boolean put(long key1, long key2, long value1, long value2, int keyHash, boolean onlyIfAbsent){\r\n long stamp = writeLock();\r\n int bucket = signSafeMod(keyHash, capacity);\r\n int firstDeletedKey = -1;\r\n try {\r\n while (true) {\r\n long storedKey1 = table[bucket];\r\n long storedKey2 = table[bucket + 1];\r\n if (key1 == storedKey1 && key2 == storedKey2) {\r\n if (!onlyIfAbsent) {\r\n table[bucket + 2] = value1;\r\n table[bucket + 3] = value2;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else if (storedKey1 == EmptyKey) {\r\n if (firstDeletedKey != -1) {\r\n bucket = firstDeletedKey;\r\n } else {\r\n ++usedBuckets;\r\n }\r\n table[bucket] = key1;\r\n table[bucket + 1] = key2;\r\n table[bucket + 2] = value1;\r\n table[bucket + 3] = value2;\r\n ++size;\r\n return true;\r\n } else if (storedKey1 == DeletedKey) {\r\n if (firstDeletedKey == -1) {\r\n firstDeletedKey = bucket;\r\n }\r\n }\r\n bucket = (bucket + 4) & (table.length - 1);\r\n }\r\n } finally {\r\n if (usedBuckets > resizeThresholdUp) {\r\n try {\r\n int newCapacity = alignToPowerOfTwo((int) (capacity * expandFactor));\r\n rehash(newCapacity);\r\n } finally {\r\n unlockWrite(stamp);\r\n }\r\n } else {\r\n unlockWrite(stamp);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected int doIter0(int newBestTrace, double traceTotalScore, double bestTracesMax){\r\n if (nTrace > bestTracesN[newBestTrace] || (nTrace == bestTracesN[newBestTrace] && bestTracesScores[newBestTrace] > traceTotalScore)) {\r\n for (int itrace = 0; itrace < nTrace; itrace++) {\r\n bestTraces1[newBestTrace][itrace] = trace1[itrace];\r\n bestTraces2[newBestTrace][itrace] = trace2[itrace];\r\n bestTracesN[newBestTrace] = nTrace;\r\n bestTracesScores[newBestTrace] = traceTotalScore;\r\n }\r\n if (nTrace > nBestTrace)\r\n nBestTrace = nTrace;\r\n if (nBestTraces < bestTracesMax) {\r\n nBestTraces++;\r\n newBestTrace++;\r\n }\r\n if (nBestTraces == bestTracesMax) {\r\n newBestTrace = 0;\r\n double scoreTmp = bestTracesScores[0];\r\n int nTraceTmp = bestTracesN[0];\r\n for (int ir = 1; ir < nBestTraces; ir++) {\r\n if (bestTracesN[ir] < nTraceTmp || (bestTracesN[ir] == nTraceTmp && scoreTmp < bestTracesScores[ir])) {\r\n nTraceTmp = bestTracesN[ir];\r\n scoreTmp = bestTracesScores[ir];\r\n newBestTrace = ir;\r\n }\r\n }\r\n }\r\n }\r\n return newBestTrace;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean finalizeTransaction(UUID uuid, UUID txnId, TxBackupLog log){\r\n OperationService operationService = nodeEngine.getOperationService();\r\n if (!uuid.equals(log.callerUuid)) {\r\n return false;\r\n }\r\n if (log.state == ACTIVE) {\r\n if (logger.isFinestEnabled()) {\r\n logger.finest(\"Rolling-back transaction[id:\" + txnId + \", state:ACTIVE] of endpoint \" + uuid);\r\n }\r\n Collection memberList = nodeEngine.getClusterService().getMembers();\r\n Collection futures = new ArrayList<>(memberList.size());\r\n for (Member member : memberList) {\r\n Operation op = new BroadcastTxRollbackOperation(txnId);\r\n Future f = operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());\r\n futures.add(f);\r\n }\r\n long timeoutMillis = TransactionOptions.getDefault().getTimeoutMillis();\r\n waitWithDeadline(futures, timeoutMillis, TimeUnit.MILLISECONDS, finalizeExceptionHandler);\r\n } else {\r\n TransactionImpl tx;\r\n if (log.allowedDuringPassiveState) {\r\n tx = new AllowedDuringPassiveStateTransactionImpl(this, nodeEngine, txnId, log.records, log.timeoutMillis, log.startTime, log.callerUuid);\r\n } else {\r\n tx = new TransactionImpl(this, nodeEngine, txnId, log.records, log.timeoutMillis, log.startTime, log.callerUuid);\r\n }\r\n if (log.state == COMMITTING) {\r\n if (logger.isFinestEnabled()) {\r\n logger.finest(\"Committing transaction[id:\" + txnId + \", state:COMMITTING] of endpoint \" + uuid);\r\n }\r\n try {\r\n tx.commit();\r\n } catch (Throwable e) {\r\n logger.warning(\"Error during committing from tx backup!\", e);\r\n }\r\n } else {\r\n if (logger.isFinestEnabled()) {\r\n logger.finest(\"Rolling-back transaction[id:\" + txnId + \", state:\" + log.state + \"] of endpoint \" + uuid);\r\n }\r\n try {\r\n tx.rollback();\r\n } catch (Throwable e) {\r\n logger.warning(\"Error during rolling-back from tx backup!\", e);\r\n }\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void initChunkMetaFromTsBlock() throws QueryProcessException{\r\n Statistics statsByType = Statistics.getStatsByType(dataType);\r\n IChunkMetadata metaData = new ChunkMetadata(measurementUid, dataType, 0, statsByType);\r\n if (!isEmpty()) {\r\n switch(dataType) {\r\n case BOOLEAN:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getBoolean(i));\r\n }\r\n break;\r\n case TEXT:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getBinary(i));\r\n }\r\n break;\r\n case FLOAT:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getFloat(i));\r\n }\r\n break;\r\n case INT32:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getInt(i));\r\n }\r\n break;\r\n case INT64:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getLong(i));\r\n }\r\n break;\r\n case DOUBLE:\r\n for (int i = 0; i < tsBlock.getPositionCount(); i++) {\r\n statsByType.update(tsBlock.getTimeByIndex(i), tsBlock.getColumn(0).getDouble(i));\r\n }\r\n break;\r\n default:\r\n throw new QueryProcessException(\"Unsupported data type:\" + dataType);\r\n }\r\n }\r\n statsByType.setEmpty(isEmpty());\r\n metaData.setChunkLoader(new MemChunkLoader(this));\r\n metaData.setVersion(Long.MAX_VALUE);\r\n cachedMetaData = metaData;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean doRun() throws Exception{\r\n long waitTime = FIRST_WAIT_TIME;\r\n while (waitTime > 0) {\r\n long begin = System.currentTimeMillis();\r\n WaitSetEntry entry = (WaitSetEntry) delayQueue.poll(waitTime, MILLISECONDS);\r\n if (entry != null) {\r\n if (entry.isValid()) {\r\n invalidate(entry);\r\n }\r\n }\r\n long end = System.currentTimeMillis();\r\n waitTime -= (end - begin);\r\n if (waitTime > FIRST_WAIT_TIME) {\r\n waitTime = FIRST_WAIT_TIME;\r\n }\r\n }\r\n for (WaitSet waitSet : waitSetMap.values()) {\r\n if (Thread.interrupted()) {\r\n return true;\r\n }\r\n for (WaitSetEntry entry : waitSet) {\r\n if (entry.isValid() && entry.needsInvalidation()) {\r\n invalidate(entry);\r\n }\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean addTaskPreemptionCandidate(TreeMap> runningTasks, TaskInfo forTask, Set preemptHosts){\r\n NavigableMap> orderedMap = runningTasks.descendingMap();\r\n Iterator>> iterator = orderedMap.entrySet().iterator();\r\n while (iterator.hasNext()) {\r\n Entry> entryAtPriority = iterator.next();\r\n if (entryAtPriority.getKey() > forTask.priority.getPriority()) {\r\n Iterator taskInfoIterator = entryAtPriority.getValue().iterator();\r\n while (taskInfoIterator.hasNext()) {\r\n TaskInfo taskInfo = taskInfoIterator.next();\r\n if (preemptHosts != null && !preemptHosts.contains(taskInfo.getAssignedNode().getHost())) {\r\n continue;\r\n }\r\n Map> depInfo = getDependencyInfo(taskInfo.getAttemptId().getDAGID());\r\n Set vertexDepInfo = null;\r\n if (depInfo != null) {\r\n vertexDepInfo = depInfo.get(vertexNum(forTask));\r\n }\r\n if (depInfo != null && vertexDepInfo == null) {\r\n LOG.warn(\"Cannot find info for \" + vertexNum(forTask) + \" \" + depInfo);\r\n }\r\n if (vertexDepInfo != null && !vertexDepInfo.contains(vertexNum(taskInfo))) {\r\n continue;\r\n }\r\n if (taskInfo.getPreemptedTime() == 0) {\r\n LOG.debug(\"Preemption candidate={} for Task={} with potentialHosts={}\", taskInfo, forTask, preemptHosts);\r\n taskInfo.setPreemptedTime(clock.getTime());\r\n preemptionCandidates.add(taskInfo);\r\n return true;\r\n }\r\n }\r\n } else {\r\n LOG.debug(\"No tasks qualify as preempt candidates for priority {}. Current priority={}\", forTask.priority.getPriority(), entryAtPriority.getKey());\r\n break;\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final Aggregate aggregate = call.rel(0);\r\n final List aggCallList = aggregate.getAggCallList().stream().map(c -> unDistinct(c, aggregate.getInput()::fieldIsNullable)).collect(Util.toImmutableList());\r\n final Multimap argLists = ArrayListMultimap.create();\r\n final ImmutableBitSet notDistinct = ImmutableBitSet.of(aggregate.getInput().getRowType().getFieldCount());\r\n for (AggregateCall aggCall : aggCallList) {\r\n ImmutableBitSet distinctKeys = aggCall.distinctKeys;\r\n if (distinctKeys == null) {\r\n distinctKeys = notDistinct;\r\n } else {\r\n if (distinctKeys.intersects(aggregate.getGroupSet())) {\r\n distinctKeys = distinctKeys.rebuild().removeAll(aggregate.getGroupSet()).build();\r\n }\r\n }\r\n argLists.put(distinctKeys, aggCall);\r\n }\r\n final Set groupSetTreeSet = new TreeSet<>(ImmutableBitSet.ORDERING);\r\n for (ImmutableBitSet key : argLists.keySet()) {\r\n groupSetTreeSet.add((key == notDistinct) ? aggregate.getGroupSet() : ImmutableBitSet.of(key).union(aggregate.getGroupSet()));\r\n }\r\n final ImmutableList groupSets = ImmutableList.copyOf(groupSetTreeSet);\r\n final boolean hasMultipleGroupSets = groupSets.size() > 1;\r\n final ImmutableBitSet fullGroupSet = ImmutableBitSet.union(groupSets);\r\n final Set fullGroupOrderedSet = new LinkedHashSet<>();\r\n fullGroupOrderedSet.addAll(aggregate.getGroupSet().asSet());\r\n fullGroupOrderedSet.addAll(fullGroupSet.asSet());\r\n final ImmutableIntList fullGroupList = ImmutableIntList.copyOf(fullGroupOrderedSet);\r\n final RelBuilder b = call.builder();\r\n b.push(aggregate.getInput());\r\n final List aggCalls = new ArrayList<>();\r\n class Registrar {\r\n\r\n final int g = fullGroupSet.cardinality();\r\n\r\n final Map args = new HashMap<>();\r\n\r\n final Map aggs = new HashMap<>();\r\n\r\n final Map counts = new HashMap<>();\r\n\r\n List fields(List fields, int filterArg) {\r\n return Util.transform(fields, f -> this.field(f, filterArg));\r\n }\r\n\r\n int field(int field, int filterArg) {\r\n return Objects.requireNonNull(args.get(IntPair.of(field, filterArg)));\r\n }\r\n\r\n int register(int field, int filterArg) {\r\n return args.computeIfAbsent(IntPair.of(field, filterArg), j -> {\r\n final int ordinal = g + aggCalls.size();\r\n RelBuilder.AggCall groupedField = b.aggregateCall(SqlStdOperatorTable.MIN, b.field(field));\r\n aggCalls.add(filterArg < 0 ? groupedField : groupedField.filter(b.field(filterArg)));\r\n if (config.throwIfNotUnique()) {\r\n groupedField = b.aggregateCall(SqlStdOperatorTable.MAX, b.field(field));\r\n aggCalls.add(filterArg < 0 ? groupedField : groupedField.filter(b.field(filterArg)));\r\n }\r\n return ordinal;\r\n });\r\n }\r\n\r\n int registerAgg(int i, RelBuilder.AggCall aggregateCall) {\r\n final int ordinal = g + aggCalls.size();\r\n aggs.put(i, ordinal);\r\n aggCalls.add(aggregateCall);\r\n return ordinal;\r\n }\r\n\r\n int getAgg(int i) {\r\n return Objects.requireNonNull(aggs.get(i));\r\n }\r\n\r\n int registerCount(int filterArg) {\r\n assert filterArg >= 0;\r\n return counts.computeIfAbsent(filterArg, i -> {\r\n final int ordinal = g + aggCalls.size();\r\n aggCalls.add(b.aggregateCall(SqlStdOperatorTable.COUNT).filter(b.field(filterArg)));\r\n return ordinal;\r\n });\r\n }\r\n\r\n int getCount(int filterArg) {\r\n return Objects.requireNonNull(counts.get(filterArg));\r\n }\r\n }\r\n final Registrar registrar = new Registrar();\r\n Ord.forEach(aggCallList, (c, i) -> {\r\n if (c.distinctKeys == null) {\r\n registrar.registerAgg(i, b.aggregateCall(c.getAggregation(), b.fields(c.getArgList())));\r\n } else {\r\n for (int inputIdx : c.getArgList()) {\r\n registrar.register(inputIdx, c.filterArg);\r\n }\r\n if (mustBeCounted(c)) {\r\n registrar.registerCount(c.filterArg);\r\n }\r\n }\r\n });\r\n final int grouping = hasMultipleGroupSets ? registrar.registerAgg(-1, b.aggregateCall(SqlStdOperatorTable.GROUPING, b.fields(fullGroupList))) : -1;\r\n b.aggregate(b.groupKey(fullGroupSet, groupSets), aggCalls);\r\n aggCalls.clear();\r\n Ord.forEach(aggCallList, (c, i) -> {\r\n final List filters = new ArrayList<>();\r\n RexNode groupFilter = null;\r\n if (hasMultipleGroupSets) {\r\n groupFilter = b.equals(b.field(grouping), b.literal(groupValue(fullGroupList, union(aggregate.getGroupSet(), c.distinctKeys))));\r\n filters.add(groupFilter);\r\n }\r\n RelBuilder.AggCall aggCall;\r\n if (c.distinctKeys == null) {\r\n aggCall = b.aggregateCall(SqlStdOperatorTable.MIN, b.field(registrar.getAgg(i)));\r\n } else {\r\n aggCall = b.aggregateCall(c.getAggregation(), b.fields(registrar.fields(c.getArgList(), c.filterArg)));\r\n if (mustBeCounted(c)) {\r\n filters.add(b.greaterThan(b.field(registrar.getCount(c.filterArg)), b.literal(0)));\r\n }\r\n if (config.throwIfNotUnique()) {\r\n for (int j : c.getArgList()) {\r\n RexNode isUniqueCondition = b.isNotDistinctFrom(b.field(registrar.field(j, c.filterArg)), b.field(registrar.field(j, c.filterArg) + 1));\r\n if (groupFilter != null) {\r\n isUniqueCondition = b.or(b.not(groupFilter), isUniqueCondition);\r\n }\r\n String message = \"more than one distinct value in agg UNIQUE_VALUE\";\r\n filters.add(b.call(SqlInternalOperators.THROW_UNLESS, isUniqueCondition, b.literal(message)));\r\n }\r\n }\r\n }\r\n if (filters.size() > 0) {\r\n aggCall = aggCall.filter(b.and(filters));\r\n }\r\n aggCalls.add(aggCall);\r\n });\r\n b.aggregate(b.groupKey(remap(fullGroupSet, aggregate.getGroupSet()), remap(fullGroupSet, aggregate.getGroupSets())), aggCalls);\r\n b.convert(aggregate.getRowType(), false);\r\n call.transformTo(b.build());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void reserveDiscardBlocksBasedOnFreeList(int mergeListIx, DiscardContext ctx){\r\n if (data == null)\r\n return;\r\n FreeList freeList = freeLists[mergeListIx];\r\n freeList.lock.lock();\r\n try {\r\n int freeHeaderIx = freeList.listHead;\r\n while (freeHeaderIx >= 0) {\r\n boolean reserved = false;\r\n if (ctx.remainingToFind > 0) {\r\n int headerToFreeIx = getBuddyHeaderIx(mergeListIx, freeHeaderIx);\r\n long reserveResult = reserveBlockContents(mergeListIx, headerToFreeIx, ctx.victimHeaders, ctx.victimCount, true);\r\n int reservedCount = getFirstInt(reserveResult), moveSize = getSecondInt(reserveResult);\r\n reserved = (moveSize != FAILED_TO_RESERVE);\r\n if (!reserved) {\r\n prepareAbandonUnfinishedMoveAttempt(ctx, reservedCount);\r\n } else {\r\n ctx.victimCount += reservedCount;\r\n ctx.addBaseHeader(freeHeaderIx);\r\n }\r\n }\r\n int nextFreeHeaderIx = getNextFreeListItem(offsetFromHeaderIndex(freeHeaderIx));\r\n if (reserved) {\r\n removeBlockFromFreeList(freeList, freeHeaderIx, mergeListIx);\r\n if (assertsEnabled) {\r\n checkHeader(freeHeaderIx, mergeListIx, false);\r\n }\r\n setHeaderNoBufAlloc(freeHeaderIx, mergeListIx, CasLog.Src.NEW_BASE);\r\n }\r\n if (ctx.remainingToFind == 0)\r\n break;\r\n freeHeaderIx = nextFreeHeaderIx;\r\n }\r\n } finally {\r\n freeList.lock.unlock();\r\n }\r\n for (int i = 0; i < ctx.abandonedCount; ++i) {\r\n abandonOneHeaderBeingMoved(ctx.abandonedHeaders[i], CasLog.Src.ABANDON_AT_END);\r\n }\r\n ctx.abandonedCount = 0;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void saveStopAreas(Context context, Collection beans){\r\n GtfsExporter exporter = (GtfsExporter) context.get(GTFS_EXPORTER);\r\n Set physicalStops = new HashSet();\r\n Set commercialStops = new HashSet();\r\n Set connectionLinks = new HashSet();\r\n GtfsExtendedStopProducer stopProducer = new GtfsExtendedStopProducer(exporter);\r\n GtfsTransferProducer transferProducer = new GtfsTransferProducer(exporter);\r\n ActionReporter reporter = ActionReporter.Factory.getInstance();\r\n GtfsExportParameters configuration = (GtfsExportParameters) context.get(CONFIGURATION);\r\n String prefix = configuration.getObjectIdPrefix();\r\n String sharedPrefix = prefix;\r\n int stopCount = 0;\r\n for (StopArea area : beans) {\r\n if (area.getAreaType().equals(ChouetteAreaEnum.BoardingPosition) || area.getAreaType().equals(ChouetteAreaEnum.Quay)) {\r\n if (area.hasCoordinates()) {\r\n physicalStops.add(area);\r\n if (area.getConnectionStartLinks() != null)\r\n connectionLinks.addAll(area.getConnectionStartLinks());\r\n if (area.getConnectionEndLinks() != null)\r\n connectionLinks.addAll(area.getConnectionEndLinks());\r\n if (area.getParent() != null && area.getParent().hasCoordinates()) {\r\n commercialStops.add(area.getParent());\r\n if (area.getParent().getConnectionStartLinks() != null)\r\n connectionLinks.addAll(area.getParent().getConnectionStartLinks());\r\n if (area.getParent().getConnectionEndLinks() != null)\r\n connectionLinks.addAll(area.getParent().getConnectionEndLinks());\r\n }\r\n }\r\n }\r\n }\r\n for (Iterator iterator = commercialStops.iterator(); iterator.hasNext(); ) {\r\n StopArea stop = iterator.next();\r\n if (!stopProducer.save(stop, sharedPrefix, null, configuration.isKeepOriginalId())) {\r\n iterator.remove();\r\n } else {\r\n stopCount++;\r\n }\r\n }\r\n for (StopArea stop : physicalStops) {\r\n stopProducer.save(stop, sharedPrefix, commercialStops, configuration.isKeepOriginalId());\r\n stopCount++;\r\n }\r\n int connectionLinkCount = 0;\r\n for (ConnectionLink link : connectionLinks) {\r\n if (!physicalStops.contains(link.getStartOfLink()) && !commercialStops.contains(link.getStartOfLink())) {\r\n continue;\r\n } else if (!physicalStops.contains(link.getEndOfLink()) && !commercialStops.contains(link.getEndOfLink())) {\r\n continue;\r\n }\r\n transferProducer.save(link, sharedPrefix, configuration.isKeepOriginalId());\r\n connectionLinkCount++;\r\n }\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.CONNECTION_LINK, \"connection links\", OBJECT_STATE.OK, IO_TYPE.OUTPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.CONNECTION_LINK, OBJECT_TYPE.CONNECTION_LINK, connectionLinkCount);\r\n reporter.addObjectReport(context, \"merged\", OBJECT_TYPE.STOP_AREA, \"stop areas\", OBJECT_STATE.OK, IO_TYPE.OUTPUT);\r\n reporter.setStatToObjectReport(context, \"merged\", OBJECT_TYPE.STOP_AREA, OBJECT_TYPE.STOP_AREA, stopCount);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List extractAnswer(List items, QuestionForm form, String componentId, String subdir) throws IOException{\r\n List answers = new ArrayList<>();\r\n for (final FileItem item : items) {\r\n String mpName = item.getFieldName();\r\n if (item.isFormField() && mpName.startsWith(\"answer\")) {\r\n String answerInput = FileUploadUtil.getOldParameter(items, mpName, \"\");\r\n Answer answer = new Answer(null, null, answerInput, 0, false, null, 0, false, null, null);\r\n String id = mpName.substring(\"answer\".length());\r\n String nbPoints = FileUploadUtil.getOldParameter(items, \"nbPoints\" + id, \"0\");\r\n answer.setNbPoints(Integer.parseInt(nbPoints));\r\n if (Integer.parseInt(nbPoints) > 0) {\r\n answer.setIsSolution(true);\r\n }\r\n String comment = FileUploadUtil.getOldParameter(items, \"comment\" + id, \"\");\r\n answer.setComment(comment);\r\n String value = FileUploadUtil.getOldParameter(items, \"valueImageGallery\" + id, \"\");\r\n if (StringUtil.isDefined(value)) {\r\n if (!form.isFile()) {\r\n answer.setImage(value);\r\n }\r\n }\r\n FileItem image = FileUploadUtil.getFile(items, \"image\" + id);\r\n if (image != null) {\r\n addImageToAnswer(answer, image, form, componentId, subdir);\r\n }\r\n answers.add(answer);\r\n }\r\n }\r\n return answers;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SyntaxTree generateUtilSyntaxTree() throws IOException{\r\n Set functionNameList = new LinkedHashSet<>();\r\n if (requestBodyEncodingFound) {\r\n functionNameList.addAll(Arrays.asList(CREATE_FORM_URLENCODED_REQUEST_BODY, GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_SERIALIZED_RECORD_ARRAY));\r\n }\r\n if (queryParamsFound) {\r\n functionNameList.addAll(Arrays.asList(GET_DEEP_OBJECT_STYLE_REQUEST, GET_FORM_STYLE_REQUEST, GET_ENCODED_URI, GET_ORIGINAL_KEY, GET_SERIALIZED_ARRAY, GET_PATH_FOR_QUERY_PARAM, GET_SERIALIZED_RECORD_ARRAY));\r\n }\r\n if (headersFound) {\r\n functionNameList.add(GET_MAP_FOR_HEADERS);\r\n }\r\n if (pathParametersFound) {\r\n functionNameList.add(GET_ENCODED_URI);\r\n }\r\n if (requestBodyMultipartFormDatafound) {\r\n functionNameList.add(CREATE_MULTIPART_BODY_PARTS);\r\n }\r\n List memberDeclarationNodes = new ArrayList<>();\r\n getUtilTypeDeclarationNodes(memberDeclarationNodes);\r\n Path path = getResourceFilePath();\r\n Project project = ProjectLoader.loadProject(path);\r\n Package currentPackage = project.currentPackage();\r\n DocumentId docId = currentPackage.getDefaultModule().documentIds().iterator().next();\r\n SyntaxTree syntaxTree = currentPackage.getDefaultModule().document(docId).syntaxTree();\r\n ModulePartNode modulePartNode = syntaxTree.rootNode();\r\n NodeList members = modulePartNode.members();\r\n for (ModuleMemberDeclarationNode node : members) {\r\n if (node.kind().equals(SyntaxKind.FUNCTION_DEFINITION)) {\r\n for (ChildNodeEntry childNodeEntry : node.childEntries()) {\r\n if (childNodeEntry.name().equals(\"functionName\")) {\r\n if (functionNameList.contains(childNodeEntry.node().get().toString())) {\r\n memberDeclarationNodes.add(node);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n List imports = new ArrayList<>();\r\n if (functionNameList.contains(GET_ENCODED_URI)) {\r\n ImportDeclarationNode importForUrl = GeneratorUtils.getImportDeclarationNode(BALLERINA, URL);\r\n imports.add(importForUrl);\r\n }\r\n if (requestBodyMultipartFormDatafound) {\r\n ImportDeclarationNode importMime = GeneratorUtils.getImportDeclarationNode(BALLERINA, MIME);\r\n imports.add(importMime);\r\n }\r\n NodeList importsList = createNodeList(imports);\r\n ModulePartNode utilModulePartNode = createModulePartNode(importsList, createNodeList(memberDeclarationNodes), createToken(EOF_TOKEN));\r\n TextDocument textDocument = TextDocuments.from(\"\");\r\n SyntaxTree utilSyntaxTree = SyntaxTree.from(textDocument);\r\n return utilSyntaxTree.modifyWith(utilModulePartNode);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public RuleDescr rule(PackageDescrBuilder pkg) throws RecognitionException{\r\n RuleDescrBuilder rule = null;\r\n try {\r\n rule = helper.start(pkg, RuleDescrBuilder.class, null);\r\n setAnnotationsOn(rule);\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.RULE, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.WHEN) || helper.validateIdentifierKey(DroolsSoftKeywords.THEN) || helper.validateIdentifierKey(DroolsSoftKeywords.END)) {\r\n failMissingTokenException();\r\n return null;\r\n }\r\n String name = stringId();\r\n if (state.failed)\r\n return null;\r\n if (state.backtracking == 0) {\r\n rule.name(name);\r\n helper.setParaphrasesValue(DroolsParaphraseTypes.RULE, \"\\\"\" + name + \"\\\"\");\r\n helper.emit(Location.LOCATION_RULE_HEADER);\r\n }\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.EXTENDS)) {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.EXTENDS, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n String parent = stringId();\r\n if (state.backtracking == 0)\r\n rule.extendsRule(parent);\r\n if (state.failed)\r\n return null;\r\n }\r\n if (state.backtracking == 0 && input.LA(1) != DRL6Lexer.EOF) {\r\n helper.emit(Location.LOCATION_RULE_HEADER);\r\n }\r\n attributes(rule);\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.WHEN)) {\r\n lhs(rule);\r\n } else {\r\n rule.lhs();\r\n }\r\n rhs(rule);\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.END, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n } finally {\r\n helper.end(RuleDescrBuilder.class, rule);\r\n }\r\n return (rule != null) ? rule.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode convertIdentifier(Blackboard bb, SqlIdentifier identifier){\r\n final SqlCall call = bb.getValidator().makeNullaryCall(identifier);\r\n if (call != null) {\r\n return bb.convertExpression(call);\r\n }\r\n String pv = null;\r\n if (bb.isPatternVarRef && identifier.names.size() > 1) {\r\n pv = identifier.names.get(0);\r\n }\r\n final SqlQualified qualified = bb.scope.fullyQualify(identifier);\r\n final Pair> e0 = bb.lookupExp(qualified);\r\n RexNode e = e0.left;\r\n for (String name : qualified.suffix()) {\r\n if (e == e0.left && e0.right != null) {\r\n e = e0.right.apply(e, name);\r\n } else {\r\n final boolean caseSensitive = true;\r\n if (identifier.isStar() && bb.scope instanceof MatchRecognizeScope) {\r\n e = rexBuilder.makeFieldAccess(e, 0);\r\n } else {\r\n e = rexBuilder.makeFieldAccess(e, name, caseSensitive);\r\n }\r\n }\r\n }\r\n if (e instanceof RexInputRef) {\r\n e = adjustInputRef(bb, (RexInputRef) e);\r\n if (pv != null) {\r\n e = RexPatternFieldRef.of(pv, (RexInputRef) e);\r\n }\r\n }\r\n if (e0.left instanceof RexCorrelVariable) {\r\n assert e instanceof RexFieldAccess;\r\n final RexNode prev = bb.mapCorrelateToRex.put(((RexCorrelVariable) e0.left).id, (RexFieldAccess) e);\r\n assert prev == null;\r\n }\r\n return e;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Result update(final SyncDelta delta, final LinkedAccount account, final Provision provision) throws JobExecutionException{\r\n if (!profile.getTask().isPerformUpdate()) {\r\n LOG.debug(\"PullTask not configured for update\");\r\n end(AnyTypeKind.USER.name(), MatchingRule.toEventName(MatchingRule.UPDATE), Result.SUCCESS, null, null, delta);\r\n return Result.SUCCESS;\r\n }\r\n LOG.debug(\"About to update {}\", account);\r\n ProvisioningReport report = new ProvisioningReport();\r\n report.setOperation(ResourceOperation.UPDATE);\r\n report.setKey(account.getKey());\r\n report.setUidValue(account.getConnObjectKeyValue());\r\n report.setName(account.getConnObjectKeyValue());\r\n report.setAnyType(MatchType.LINKED_ACCOUNT.name());\r\n report.setStatus(ProvisioningReport.Status.SUCCESS);\r\n Result resultStatus = Result.SUCCESS;\r\n if (!profile.isDryRun()) {\r\n LinkedAccountTO before = userDataBinder.getLinkedAccountTO(account);\r\n UserTO owner = userDataBinder.getUserTO(account.getOwner(), false);\r\n UserCR connObject = connObjectUtils.getAnyCR(delta.getObject(), profile.getTask(), AnyTypeKind.USER, provision, false);\r\n LinkedAccountTO update = userDataBinder.getLinkedAccountTO(account);\r\n if (connObject.getUsername().equals(owner.getUsername())) {\r\n update.setUsername(null);\r\n } else if (!connObject.getUsername().equals(update.getUsername())) {\r\n update.setUsername(connObject.getUsername());\r\n }\r\n if (connObject.getPassword() != null) {\r\n update.setPassword(connObject.getPassword());\r\n }\r\n update.setSuspended(BooleanUtils.isTrue(BooleanUtils.negate(enabled(delta))));\r\n Set attrsToRemove = new HashSet<>();\r\n connObject.getPlainAttrs().forEach(connObjectAttr -> {\r\n Optional ownerAttr = owner.getPlainAttr(connObjectAttr.getSchema());\r\n if (ownerAttr.isPresent() && ownerAttr.get().getValues().equals(connObjectAttr.getValues())) {\r\n attrsToRemove.add(connObjectAttr.getSchema());\r\n } else {\r\n Optional updateAttr = update.getPlainAttr(connObjectAttr.getSchema());\r\n if (updateAttr.isEmpty() || !updateAttr.get().getValues().equals(connObjectAttr.getValues())) {\r\n attrsToRemove.add(connObjectAttr.getSchema());\r\n update.getPlainAttrs().add(connObjectAttr);\r\n }\r\n }\r\n });\r\n update.getPlainAttrs().removeIf(attr -> attrsToRemove.contains(attr.getSchema()));\r\n UserUR userUR = new UserUR();\r\n userUR.setKey(account.getOwner().getKey());\r\n userUR.getLinkedAccounts().add(new LinkedAccountUR.Builder().operation(PatchOperation.ADD_REPLACE).linkedAccountTO(update).build());\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeUpdate(profile, delta, before, userUR);\r\n }\r\n Object output;\r\n try {\r\n userProvisioningManager.update(userUR, report, null, Set.of(profile.getTask().getResource().getKey()), true, profile.getExecutor(), getContext());\r\n resultStatus = Result.SUCCESS;\r\n LinkedAccountTO updated = userDAO.find(userUR.getKey()).getLinkedAccount(account.getResource().getKey(), account.getConnObjectKeyValue()).map(acct -> userDataBinder.getLinkedAccountTO(acct)).orElse(null);\r\n output = updated;\r\n for (PullActions action : profile.getActions()) {\r\n action.after(profile, delta, updated, report);\r\n }\r\n LOG.debug(\"Linked account {} successfully updated\", account.getConnObjectKeyValue());\r\n } catch (PropagationException e) {\r\n LOG.error(\"Could not propagate linked acccount {}\", account.getConnObjectKeyValue());\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n report.setStatus(ProvisioningReport.Status.FAILURE);\r\n report.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not update linked account {}\", account, e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n if (profile.getTask().isRemediation()) {\r\n createRemediation(provision.getAnyType(), null, null, userUR, report, delta);\r\n }\r\n }\r\n end(AnyTypeKind.USER.name(), MatchingRule.toEventName(MatchingRule.UPDATE), resultStatus, before, output, delta);\r\n profile.getResults().add(report);\r\n }\r\n return resultStatus;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseClassAttrBands(final InputStream in) throws IOException, Pack200Exception{\r\n final String[] cpUTF8 = cpBands.getCpUTF8();\r\n final String[] cpClass = cpBands.getCpClass();\r\n classAttributes = new ArrayList[classCount];\r\n Arrays.setAll(classAttributes, i -> new ArrayList<>());\r\n classFlags = parseFlags(\"class_flags\", in, classCount, Codec.UNSIGNED5, options.hasClassFlagsHi());\r\n final int classAttrCount = SegmentUtils.countBit16(classFlags);\r\n final int[] classAttrCounts = decodeBandInt(\"class_attr_count\", in, Codec.UNSIGNED5, classAttrCount);\r\n final int[][] classAttrIndexes = decodeBandInt(\"class_attr_indexes\", in, Codec.UNSIGNED5, classAttrCounts);\r\n final int callCount = getCallCount(classAttrIndexes, new long[][] { classFlags }, AttributeLayout.CONTEXT_CLASS);\r\n final int[] classAttrCalls = decodeBandInt(\"class_attr_calls\", in, Codec.UNSIGNED5, callCount);\r\n final AttributeLayout deprecatedLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_DEPRECATED, AttributeLayout.CONTEXT_CLASS);\r\n final AttributeLayout sourceFileLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_SOURCE_FILE, AttributeLayout.CONTEXT_CLASS);\r\n final int sourceFileCount = SegmentUtils.countMatches(classFlags, sourceFileLayout);\r\n final int[] classSourceFile = decodeBandInt(\"class_SourceFile_RUN\", in, Codec.UNSIGNED5, sourceFileCount);\r\n final AttributeLayout enclosingMethodLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_ENCLOSING_METHOD, AttributeLayout.CONTEXT_CLASS);\r\n final int enclosingMethodCount = SegmentUtils.countMatches(classFlags, enclosingMethodLayout);\r\n final int[] enclosingMethodRC = decodeBandInt(\"class_EnclosingMethod_RC\", in, Codec.UNSIGNED5, enclosingMethodCount);\r\n final int[] enclosingMethodRDN = decodeBandInt(\"class_EnclosingMethod_RDN\", in, Codec.UNSIGNED5, enclosingMethodCount);\r\n final AttributeLayout signatureLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_SIGNATURE, AttributeLayout.CONTEXT_CLASS);\r\n final int signatureCount = SegmentUtils.countMatches(classFlags, signatureLayout);\r\n final int[] classSignature = decodeBandInt(\"class_Signature_RS\", in, Codec.UNSIGNED5, signatureCount);\r\n final int backwardsCallsUsed = parseClassMetadataBands(in, classAttrCalls);\r\n final AttributeLayout innerClassLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_INNER_CLASSES, AttributeLayout.CONTEXT_CLASS);\r\n final int innerClassCount = SegmentUtils.countMatches(classFlags, innerClassLayout);\r\n final int[] classInnerClassesN = decodeBandInt(\"class_InnerClasses_N\", in, Codec.UNSIGNED5, innerClassCount);\r\n final int[][] classInnerClassesRC = decodeBandInt(\"class_InnerClasses_RC\", in, Codec.UNSIGNED5, classInnerClassesN);\r\n final int[][] classInnerClassesF = decodeBandInt(\"class_InnerClasses_F\", in, Codec.UNSIGNED5, classInnerClassesN);\r\n int flagsCount = 0;\r\n for (final int[] element : classInnerClassesF) {\r\n for (final int element2 : element) {\r\n if (element2 != 0) {\r\n flagsCount++;\r\n }\r\n }\r\n }\r\n final int[] classInnerClassesOuterRCN = decodeBandInt(\"class_InnerClasses_outer_RCN\", in, Codec.UNSIGNED5, flagsCount);\r\n final int[] classInnerClassesNameRUN = decodeBandInt(\"class_InnerClasses_name_RUN\", in, Codec.UNSIGNED5, flagsCount);\r\n final AttributeLayout versionLayout = attrMap.getAttributeLayout(AttributeLayout.ATTRIBUTE_CLASS_FILE_VERSION, AttributeLayout.CONTEXT_CLASS);\r\n final int versionCount = SegmentUtils.countMatches(classFlags, versionLayout);\r\n final int[] classFileVersionMinorH = decodeBandInt(\"class_file_version_minor_H\", in, Codec.UNSIGNED5, versionCount);\r\n final int[] classFileVersionMajorH = decodeBandInt(\"class_file_version_major_H\", in, Codec.UNSIGNED5, versionCount);\r\n if (versionCount > 0) {\r\n classVersionMajor = new int[classCount];\r\n classVersionMinor = new int[classCount];\r\n }\r\n final int defaultVersionMajor = header.getDefaultClassMajorVersion();\r\n final int defaultVersionMinor = header.getDefaultClassMinorVersion();\r\n int backwardsCallIndex = backwardsCallsUsed;\r\n final int limit = options.hasClassFlagsHi() ? 62 : 31;\r\n final AttributeLayout[] otherLayouts = new AttributeLayout[limit + 1];\r\n final int[] counts = new int[limit + 1];\r\n final List[] otherAttributes = new List[limit + 1];\r\n for (int i = 0; i < limit; ++i) {\r\n final AttributeLayout layout = attrMap.getAttributeLayout(i, AttributeLayout.CONTEXT_CLASS);\r\n if (layout != null && !(layout.isDefaultLayout())) {\r\n otherLayouts[i] = layout;\r\n counts[i] = SegmentUtils.countMatches(classFlags, layout);\r\n }\r\n }\r\n for (int i = 0; i < counts.length; ++i) {\r\n if (counts[i] > 0) {\r\n final NewAttributeBands bands = attrMap.getAttributeBands(otherLayouts[i]);\r\n otherAttributes[i] = bands.parseAttributes(in, counts[i]);\r\n final int numBackwardsCallables = otherLayouts[i].numBackwardsCallables();\r\n if (numBackwardsCallables > 0) {\r\n final int[] backwardsCalls = new int[numBackwardsCallables];\r\n System.arraycopy(classAttrCalls, backwardsCallIndex, backwardsCalls, 0, numBackwardsCallables);\r\n bands.setBackwardsCalls(backwardsCalls);\r\n backwardsCallIndex += numBackwardsCallables;\r\n }\r\n }\r\n }\r\n int sourceFileIndex = 0;\r\n int enclosingMethodIndex = 0;\r\n int signatureIndex = 0;\r\n int innerClassIndex = 0;\r\n int innerClassC2NIndex = 0;\r\n int versionIndex = 0;\r\n icLocal = new IcTuple[classCount][];\r\n for (int i = 0; i < classCount; ++i) {\r\n final long flag = classFlags[i];\r\n if (deprecatedLayout.matches(classFlags[i])) {\r\n classAttributes[i].add(new DeprecatedAttribute());\r\n }\r\n if (sourceFileLayout.matches(flag)) {\r\n final long result = classSourceFile[sourceFileIndex];\r\n ClassFileEntry value = sourceFileLayout.getValue(result, cpBands.getConstantPool());\r\n if (value == null) {\r\n String className = classThis[i].substring(classThis[i].lastIndexOf('/') + 1);\r\n className = className.substring(className.lastIndexOf('.') + 1);\r\n final char[] chars = className.toCharArray();\r\n int index = -1;\r\n for (int j = 0; j < chars.length; ++j) {\r\n if (chars[j] <= 0x2D) {\r\n index = j;\r\n break;\r\n }\r\n }\r\n if (index > -1) {\r\n className = className.substring(0, index);\r\n }\r\n value = cpBands.cpUTF8Value(className + \".java\", true);\r\n }\r\n classAttributes[i].add(new SourceFileAttribute((CPUTF8) value));\r\n sourceFileIndex++;\r\n }\r\n if (enclosingMethodLayout.matches(flag)) {\r\n final CPClass theClass = cpBands.cpClassValue(enclosingMethodRC[enclosingMethodIndex]);\r\n CPNameAndType theMethod = null;\r\n if (enclosingMethodRDN[enclosingMethodIndex] != 0) {\r\n theMethod = cpBands.cpNameAndTypeValue(enclosingMethodRDN[enclosingMethodIndex] - 1);\r\n }\r\n classAttributes[i].add(new EnclosingMethodAttribute(theClass, theMethod));\r\n enclosingMethodIndex++;\r\n }\r\n if (signatureLayout.matches(flag)) {\r\n final long result = classSignature[signatureIndex];\r\n final CPUTF8 value = (CPUTF8) signatureLayout.getValue(result, cpBands.getConstantPool());\r\n classAttributes[i].add(new SignatureAttribute(value));\r\n signatureIndex++;\r\n }\r\n if (innerClassLayout.matches(flag)) {\r\n icLocal[i] = new IcTuple[classInnerClassesN[innerClassIndex]];\r\n for (int j = 0; j < icLocal[i].length; ++j) {\r\n final int icTupleCIndex = classInnerClassesRC[innerClassIndex][j];\r\n int icTupleC2Index = -1;\r\n int icTupleNIndex = -1;\r\n final String icTupleC = cpClass[icTupleCIndex];\r\n int icTupleF = classInnerClassesF[innerClassIndex][j];\r\n String icTupleC2 = null;\r\n String icTupleN = null;\r\n if (icTupleF != 0) {\r\n icTupleC2Index = classInnerClassesOuterRCN[innerClassC2NIndex];\r\n icTupleNIndex = classInnerClassesNameRUN[innerClassC2NIndex];\r\n icTupleC2 = cpClass[icTupleC2Index];\r\n icTupleN = cpUTF8[icTupleNIndex];\r\n innerClassC2NIndex++;\r\n } else {\r\n final IcBands icBands = segment.getIcBands();\r\n final IcTuple[] icAll = icBands.getIcTuples();\r\n for (final IcTuple element : icAll) {\r\n if (element.getC().equals(icTupleC)) {\r\n icTupleF = element.getF();\r\n icTupleC2 = element.getC2();\r\n icTupleN = element.getN();\r\n break;\r\n }\r\n }\r\n }\r\n final IcTuple icTuple = new IcTuple(icTupleC, icTupleF, icTupleC2, icTupleN, icTupleCIndex, icTupleC2Index, icTupleNIndex, j);\r\n icLocal[i][j] = icTuple;\r\n }\r\n innerClassIndex++;\r\n }\r\n if (versionLayout.matches(flag)) {\r\n classVersionMajor[i] = classFileVersionMajorH[versionIndex];\r\n classVersionMinor[i] = classFileVersionMinorH[versionIndex];\r\n versionIndex++;\r\n } else if (classVersionMajor != null) {\r\n classVersionMajor[i] = defaultVersionMajor;\r\n classVersionMinor[i] = defaultVersionMinor;\r\n }\r\n for (int j = 0; j < otherLayouts.length; ++j) {\r\n if (otherLayouts[j] != null && otherLayouts[j].matches(flag)) {\r\n classAttributes[i].add(otherAttributes[j].get(0));\r\n otherAttributes[j].remove(0);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean compatibleType(RelDataType t1, RelDataType t2){\r\n if (t1.isStruct() || t2.isStruct()) {\r\n if (!t1.isStruct() || !t2.isStruct()) {\r\n return false;\r\n }\r\n if (t1.getFieldCount() != t2.getFieldCount()) {\r\n return false;\r\n }\r\n List fields1 = t1.getFieldList();\r\n List fields2 = t2.getFieldList();\r\n for (int i = 0; i < fields1.size(); ++i) {\r\n if (!compatibleType(fields1.get(i).getType(), fields2.get(i).getType())) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n RelDataType comp1 = t1.getComponentType();\r\n RelDataType comp2 = t2.getComponentType();\r\n if ((comp1 != null) || (comp2 != null)) {\r\n if ((comp1 == null) || (comp2 == null)) {\r\n return false;\r\n }\r\n if (!compatibleType(comp1, comp2)) {\r\n return false;\r\n }\r\n }\r\n return t1.getSqlTypeName().getFamily() == t2.getSqlTypeName().getFamily();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static PGPPrivateKey findPrivateKeyWithkeyId(long keyid, String passphrase, PGPPassphraseAccessor passphraseAccessor, String provider, PGPSecretKeyRingCollection pgpSec) throws PGPException{\r\n for (Iterator i = pgpSec.getKeyRings(); i.hasNext(); ) {\r\n Object data = i.next();\r\n if (data instanceof PGPSecretKeyRing) {\r\n PGPSecretKeyRing keyring = (PGPSecretKeyRing) data;\r\n PGPSecretKey secKey = keyring.getSecretKey(keyid);\r\n if (secKey != null) {\r\n if (passphrase == null && passphraseAccessor != null) {\r\n @SuppressWarnings(\"unchecked\")\r\n Iterator userIDs = keyring.getSecretKey().getUserIDs();\r\n while (passphrase == null && userIDs.hasNext()) {\r\n passphrase = passphraseAccessor.getPassphrase(userIDs.next());\r\n }\r\n }\r\n if (passphrase != null) {\r\n PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider).build(passphrase.toCharArray()));\r\n if (privateKey != null) {\r\n return privateKey;\r\n }\r\n }\r\n if (passphrase == null && passphraseAccessor == null) {\r\n passphrase = \"\";\r\n PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider).build(passphrase.toCharArray()));\r\n if (privateKey != null) {\r\n return privateKey;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@PolyNull\nprotected SqlNode performUnconditionalRewrites(@PolyNull SqlNode node, boolean underFrom){\r\n if (node == null) {\r\n return null;\r\n }\r\n if (node instanceof SqlCall) {\r\n if (node instanceof SqlMerge) {\r\n validatingSqlMerge = true;\r\n }\r\n SqlCall call = (SqlCall) node;\r\n final SqlKind kind = call.getKind();\r\n final List operands = call.getOperandList();\r\n for (int i = 0; i < operands.size(); i++) {\r\n SqlNode operand = operands.get(i);\r\n boolean childUnderFrom;\r\n if (kind == SqlKind.SELECT) {\r\n childUnderFrom = i == SqlSelect.FROM_OPERAND;\r\n } else if (kind == SqlKind.AS && (i == 0)) {\r\n childUnderFrom = underFrom;\r\n } else {\r\n childUnderFrom = false;\r\n }\r\n SqlNode newOperand = performUnconditionalRewrites(operand, childUnderFrom);\r\n if (newOperand != null && newOperand != operand) {\r\n call.setOperand(i, newOperand);\r\n }\r\n }\r\n if (call.getOperator() instanceof SqlUnresolvedFunction) {\r\n assert call instanceof SqlBasicCall;\r\n final SqlUnresolvedFunction function = (SqlUnresolvedFunction) call.getOperator();\r\n final List overloads = new ArrayList<>();\r\n opTab.lookupOperatorOverloads(function.getNameAsId(), function.getFunctionType(), SqlSyntax.FUNCTION, overloads, catalogReader.nameMatcher());\r\n if (overloads.size() == 1) {\r\n ((SqlBasicCall) call).setOperator(overloads.get(0));\r\n }\r\n }\r\n if (config.callRewrite()) {\r\n node = call.getOperator().rewriteCall(this, call);\r\n }\r\n } else if (node instanceof SqlNodeList) {\r\n final SqlNodeList list = (SqlNodeList) node;\r\n for (int i = 0; i < list.size(); i++) {\r\n SqlNode operand = list.get(i);\r\n SqlNode newOperand = performUnconditionalRewrites(operand, false);\r\n if (newOperand != null) {\r\n list.set(i, newOperand);\r\n }\r\n }\r\n }\r\n final SqlKind kind = node.getKind();\r\n switch(kind) {\r\n case VALUES:\r\n return node;\r\n case ORDER_BY:\r\n {\r\n SqlOrderBy orderBy = (SqlOrderBy) node;\r\n handleOffsetFetch(orderBy.offset, orderBy.fetch);\r\n if (orderBy.query instanceof SqlSelect) {\r\n SqlSelect select = (SqlSelect) orderBy.query;\r\n if (select.getOrderList() == null) {\r\n select.setOrderBy(orderBy.orderList);\r\n select.setOffset(orderBy.offset);\r\n select.setFetch(orderBy.fetch);\r\n return select;\r\n }\r\n }\r\n if (orderBy.query instanceof SqlWith && ((SqlWith) orderBy.query).body instanceof SqlSelect) {\r\n SqlWith with = (SqlWith) orderBy.query;\r\n SqlSelect select = (SqlSelect) with.body;\r\n if (select.getOrderList() == null) {\r\n select.setOrderBy(orderBy.orderList);\r\n select.setOffset(orderBy.offset);\r\n select.setFetch(orderBy.fetch);\r\n return with;\r\n }\r\n }\r\n final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);\r\n selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));\r\n final SqlNodeList orderList;\r\n SqlSelect innerSelect = getInnerSelect(node);\r\n if (innerSelect != null && isAggregate(innerSelect)) {\r\n orderList = SqlNode.clone(orderBy.orderList);\r\n for (int i = 0; i < orderList.size(); i++) {\r\n SqlNode sqlNode = orderList.get(i);\r\n SqlNodeList selectList2 = SqlNonNullableAccessors.getSelectList(innerSelect);\r\n for (Ord sel : Ord.zip(selectList2)) {\r\n if (stripAs(sel.e).equalsDeep(sqlNode, Litmus.IGNORE)) {\r\n orderList.set(i, SqlLiteral.createExactNumeric(Integer.toString(sel.i + 1), SqlParserPos.ZERO));\r\n }\r\n }\r\n }\r\n } else {\r\n orderList = orderBy.orderList;\r\n }\r\n return new SqlSelect(SqlParserPos.ZERO, null, selectList, orderBy.query, null, null, null, null, null, orderList, orderBy.offset, orderBy.fetch, null);\r\n }\r\n case EXPLICIT_TABLE:\r\n {\r\n SqlCall call = (SqlCall) node;\r\n final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);\r\n selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));\r\n return new SqlSelect(SqlParserPos.ZERO, null, selectList, call.operand(0), null, null, null, null, null, null, null, null, null);\r\n }\r\n case DELETE:\r\n {\r\n SqlDelete call = (SqlDelete) node;\r\n SqlSelect select = createSourceSelectForDelete(call);\r\n call.setSourceSelect(select);\r\n break;\r\n }\r\n case UPDATE:\r\n {\r\n SqlUpdate call = (SqlUpdate) node;\r\n SqlSelect select = createSourceSelectForUpdate(call);\r\n call.setSourceSelect(select);\r\n if (!validatingSqlMerge) {\r\n SqlNode selfJoinSrcExpr = getSelfJoinExprForUpdate(call.getTargetTable(), UPDATE_SRC_ALIAS);\r\n if (selfJoinSrcExpr != null) {\r\n node = rewriteUpdateToMerge(call, selfJoinSrcExpr);\r\n }\r\n }\r\n break;\r\n }\r\n case MERGE:\r\n {\r\n SqlMerge call = (SqlMerge) node;\r\n rewriteMerge(call);\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n return node;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static AttributeType getAttributeType(Class klass){\r\n if (klass == String.class) {\r\n return AttributeType.STRING;\r\n } else if (klass == Integer.class) {\r\n return AttributeType.INTEGER;\r\n } else if (klass == Short.class) {\r\n return AttributeType.SHORT;\r\n } else if (klass == Long.class) {\r\n return AttributeType.LONG;\r\n } else if (klass == Boolean.class) {\r\n return AttributeType.BOOLEAN;\r\n } else if (klass == Double.class) {\r\n return AttributeType.DOUBLE;\r\n } else if (klass == BigDecimal.class) {\r\n return AttributeType.BIG_DECIMAL;\r\n } else if (klass == BigInteger.class) {\r\n return AttributeType.BIG_INTEGER;\r\n } else if (klass == Float.class) {\r\n return AttributeType.FLOAT;\r\n } else if (klass == Byte.class) {\r\n return AttributeType.BYTE;\r\n } else if (klass == Character.class) {\r\n return AttributeType.CHAR;\r\n } else if (klass == Timestamp.class) {\r\n return AttributeType.SQL_TIMESTAMP;\r\n } else if (klass == java.sql.Date.class) {\r\n return AttributeType.SQL_DATE;\r\n } else if (klass == Date.class) {\r\n return AttributeType.DATE;\r\n } else if (klass == LocalTime.class) {\r\n return AttributeType.SQL_LOCAL_TIME;\r\n } else if (klass == LocalDate.class) {\r\n return AttributeType.SQL_LOCAL_DATE;\r\n } else if (klass == LocalDateTime.class) {\r\n return AttributeType.SQL_LOCAL_DATE_TIME;\r\n } else if (klass == OffsetDateTime.class) {\r\n return AttributeType.SQL_OFFSET_DATE_TIME;\r\n } else if (klass.isEnum()) {\r\n return AttributeType.ENUM;\r\n } else if (klass == UUID.class) {\r\n return AttributeType.UUID;\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean isEqual(final byte[] buffer1, final int offset1, final int length1, final byte[] buffer2, final int offset2, final int length2, final boolean ignoreTrailingNulls){\r\n final int minLen = Math.min(length1, length2);\r\n for (int i = 0; i < minLen; ++i) {\r\n if (buffer1[offset1 + i] != buffer2[offset2 + i]) {\r\n return false;\r\n }\r\n }\r\n if (length1 == length2) {\r\n return true;\r\n }\r\n if (ignoreTrailingNulls) {\r\n if (length1 > length2) {\r\n for (int i = length2; i < length1; ++i) {\r\n if (buffer1[offset1 + i] != 0) {\r\n return false;\r\n }\r\n }\r\n } else {\r\n for (int i = length1; i < length2; ++i) {\r\n if (buffer2[offset2 + i] != 0) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void processExchange(Exchange exchange, String target) throws Exception{\r\n LOG.trace(\"Processing file: {} for exchange: {}\", target, exchange);\r\n try {\r\n preWriteCheck(exchange);\r\n boolean writeAsTempAndRename = ObjectHelper.isNotEmpty(endpoint.getTempFileName());\r\n String tempTarget = null;\r\n boolean targetExists;\r\n if (writeAsTempAndRename) {\r\n tempTarget = createTempFileName(exchange, target);\r\n LOG.trace(\"Writing using tempNameFile: {}\", tempTarget);\r\n if (endpoint.getFileExist() != GenericFileExist.TryRename && endpoint.isEagerDeleteTargetFile()) {\r\n targetExists = operations.existsFile(target);\r\n if (targetExists) {\r\n LOG.trace(\"EagerDeleteTargetFile, target exists\");\r\n if (endpoint.getFileExist() == GenericFileExist.Ignore) {\r\n LOG.trace(\"An existing file already exists: {}. Ignore and do not override it.\", target);\r\n return;\r\n } else if (endpoint.getFileExist() == GenericFileExist.Fail) {\r\n throw new GenericFileOperationFailedException(\"File already exist: \" + target + \". Cannot write new file.\");\r\n } else if (endpoint.getFileExist() == GenericFileExist.Move) {\r\n this.endpoint.getMoveExistingFileStrategy().moveExistingFile(endpoint, operations, target);\r\n } else if (endpoint.isEagerDeleteTargetFile() && endpoint.getFileExist() == GenericFileExist.Override) {\r\n LOG.trace(\"Eagerly deleting existing file: {}\", target);\r\n if (!operations.deleteFile(target)) {\r\n throw new GenericFileOperationFailedException(\"Cannot delete file: \" + target);\r\n }\r\n }\r\n }\r\n }\r\n if (endpoint.getFileExist() != GenericFileExist.TryRename && operations.existsFile(tempTarget)) {\r\n LOG.trace(\"Deleting existing temp file: {}\", tempTarget);\r\n if (!operations.deleteFile(tempTarget)) {\r\n throw new GenericFileOperationFailedException(\"Cannot delete file: \" + tempTarget);\r\n }\r\n }\r\n }\r\n writeFile(exchange, tempTarget != null ? tempTarget : target);\r\n if (tempTarget != null) {\r\n if (endpoint.getFileExist() != GenericFileExist.TryRename && !endpoint.isEagerDeleteTargetFile()) {\r\n targetExists = operations.existsFile(target);\r\n if (targetExists) {\r\n LOG.trace(\"Not using EagerDeleteTargetFile, target exists\");\r\n if (endpoint.getFileExist() == GenericFileExist.Ignore) {\r\n LOG.trace(\"An existing file already exists: {}. Ignore and do not override it.\", target);\r\n return;\r\n } else if (endpoint.getFileExist() == GenericFileExist.Fail) {\r\n throw new GenericFileOperationFailedException(\"File already exist: \" + target + \". Cannot write new file.\");\r\n } else if (endpoint.getFileExist() == GenericFileExist.Override) {\r\n LOG.trace(\"Deleting existing file: {}\", target);\r\n if (!operations.deleteFile(target)) {\r\n throw new GenericFileOperationFailedException(\"Cannot delete file: \" + target);\r\n }\r\n }\r\n }\r\n }\r\n LOG.trace(\"Renaming file: [{}] to: [{}]\", tempTarget, target);\r\n boolean renamed = operations.renameFile(tempTarget, target);\r\n if (!renamed) {\r\n throw new GenericFileOperationFailedException(\"Cannot rename file from: \" + tempTarget + \" to: \" + target);\r\n }\r\n }\r\n if (endpoint.getDoneFileName() != null) {\r\n String doneFileName = endpoint.createDoneFileName(target);\r\n StringHelper.notEmpty(doneFileName, \"doneFileName\", endpoint);\r\n Exchange empty = new DefaultExchange(exchange);\r\n empty.getIn().setBody(\"\");\r\n LOG.trace(\"Writing done file: [{}]\", doneFileName);\r\n if (operations.existsFile(doneFileName)) {\r\n if (!operations.deleteFile(doneFileName)) {\r\n throw new GenericFileOperationFailedException(\"Cannot delete existing done file: \" + doneFileName);\r\n }\r\n }\r\n writeFile(empty, doneFileName);\r\n }\r\n exchange.getIn().setHeader(FileConstants.FILE_NAME_PRODUCED, target);\r\n } catch (Exception e) {\r\n handleFailedWrite(exchange, e);\r\n }\r\n postWriteCheck(exchange);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Node getQueryParameters(Parameter parameter, NodeList parameterAnnotationNodeList) throws BallerinaOpenApiException{\r\n TypeDescriptorNode typeName;\r\n Schema parameterSchema = parameter.getSchema();\r\n String paramType = \"\";\r\n if (parameterSchema.get$ref() != null) {\r\n paramType = getValidName(extractReferenceType(parameterSchema.get$ref()), true);\r\n parameterSchema = openAPI.getComponents().getSchemas().get(paramType.trim());\r\n } else {\r\n paramType = convertOpenAPITypeToBallerina(parameterSchema);\r\n if (parameterSchema instanceof ArraySchema) {\r\n ArraySchema arraySchema = (ArraySchema) parameterSchema;\r\n if (arraySchema.getItems().getType() != null) {\r\n String itemType = arraySchema.getItems().getType();\r\n if (itemType.equals(STRING) || itemType.equals(INTEGER) || itemType.equals(BOOLEAN) || itemType.equals(NUMBER)) {\r\n if (arraySchema.getItems().getEnum() != null && !arraySchema.getItems().getEnum().isEmpty()) {\r\n paramType = OPEN_PAREN_TOKEN.stringValue() + convertOpenAPITypeToBallerina(arraySchema.getItems()) + CLOSE_PAREN_TOKEN.stringValue() + SQUARE_BRACKETS;\r\n } else {\r\n paramType = convertOpenAPITypeToBallerina(arraySchema.getItems()) + SQUARE_BRACKETS;\r\n }\r\n } else {\r\n throw new BallerinaOpenApiException(\"Unsupported parameter type is found in the parameter : \" + parameter.getName());\r\n }\r\n } else if (arraySchema.getItems().get$ref() != null) {\r\n paramType = getValidName(extractReferenceType(arraySchema.getItems().get$ref().trim()), true) + SQUARE_BRACKETS;\r\n } else {\r\n throw new BallerinaOpenApiException(\"Please define the array item type of the parameter : \" + parameter.getName());\r\n }\r\n }\r\n }\r\n if (parameter.getRequired()) {\r\n typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(paramType));\r\n IdentifierToken paramName = createIdentifierToken(getValidName(parameter.getName().trim(), false));\r\n return createRequiredParameterNode(parameterAnnotationNodeList, typeName, paramName);\r\n } else {\r\n IdentifierToken paramName = createIdentifierToken(getValidName(parameter.getName().trim(), false));\r\n if (parameterSchema.getDefault() != null) {\r\n typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(paramType));\r\n LiteralValueToken literalValueToken;\r\n if (parameterSchema.getType().equals(STRING)) {\r\n literalValueToken = createLiteralValueToken(null, '\"' + parameterSchema.getDefault().toString() + '\"', createEmptyMinutiaeList(), createEmptyMinutiaeList());\r\n } else {\r\n literalValueToken = createLiteralValueToken(null, parameterSchema.getDefault().toString(), createEmptyMinutiaeList(), createEmptyMinutiaeList());\r\n }\r\n return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, createToken(EQUAL_TOKEN), literalValueToken);\r\n } else {\r\n paramType = paramType.endsWith(NILLABLE) ? paramType : paramType + NILLABLE;\r\n typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(paramType));\r\n NilLiteralNode nilLiteralNode = createNilLiteralNode(createToken(OPEN_PAREN_TOKEN), createToken(CLOSE_PAREN_TOKEN));\r\n return createDefaultableParameterNode(parameterAnnotationNodeList, typeName, paramName, createToken(EQUAL_TOKEN), nilLiteralNode);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public String compareResults(HashMap gsonTableCounts, HashMap sqlNodeCounts, HashMap sqlEdgeCounts, String outputDir, String titleInfo) throws IOException{\r\n FormatDate fd = new FormatDate(\"yyyyMMddHHmm\", \"GMT\");\r\n String dteStr = fd.getDateTime();\r\n String fName = outputDir + \"/\" + \"gson-sql-audit\" + dteStr;\r\n File auditOutFile = new File(fName);\r\n auditOutFile.getParentFile().mkdirs();\r\n BufferedWriter outWriter = new BufferedWriter(new FileWriter(auditOutFile));\r\n outWriter.write(titleInfo);\r\n outWriter.newLine();\r\n outWriter.write(\"Totals from Graphson: \" + getGsonTotals(gsonTableCounts));\r\n outWriter.newLine();\r\n outWriter.write(\"Totals from mySql: \" + getMSqlTotals(sqlNodeCounts, sqlEdgeCounts));\r\n outWriter.newLine();\r\n outWriter.newLine();\r\n for (Map.Entry entry : gsonTableCounts.entrySet()) {\r\n String tblKey = entry.getKey();\r\n int gVal = entry.getValue();\r\n if (!sqlNodeCounts.containsKey(tblKey) && !sqlEdgeCounts.containsKey(tblKey)) {\r\n String msg = \"> Entry for Table: [\" + tblKey + \"] not found in the SQL db but had \" + gVal + \" entries in the GraphSon db\";\r\n LOGGER.error(msg);\r\n System.out.println(msg);\r\n outWriter.write(msg);\r\n outWriter.newLine();\r\n continue;\r\n }\r\n int sVal = 0;\r\n if (sqlNodeCounts.containsKey(tblKey)) {\r\n sVal = sqlNodeCounts.get(tblKey);\r\n } else {\r\n sVal = sqlEdgeCounts.get(tblKey);\r\n }\r\n if ((gVal > 0) && (sVal == 0)) {\r\n String msg = \"For Table [\" + tblKey + \"], GSon count = \" + gVal + \", zero found in SQL db.\";\r\n LOGGER.error(msg);\r\n System.out.println(msg);\r\n outWriter.write(msg);\r\n outWriter.newLine();\r\n }\r\n String msg = tblKey + \": gson/sql = \" + gVal + \"/\" + sVal;\r\n LOGGER.debug(msg);\r\n System.out.println(msg);\r\n outWriter.write(msg);\r\n outWriter.newLine();\r\n }\r\n for (Map.Entry entry : sqlNodeCounts.entrySet()) {\r\n String tblKey = entry.getKey();\r\n int sVal = entry.getValue();\r\n if (!gsonTableCounts.containsKey(tblKey)) {\r\n String msg = \" Entry for Table [\" + tblKey + \"] not found in the Graphson db, but had \" + sVal + \" entries in the SQL db.\";\r\n LOGGER.error(msg);\r\n System.out.println(msg);\r\n outWriter.write(msg);\r\n outWriter.newLine();\r\n continue;\r\n }\r\n }\r\n for (Map.Entry entry : sqlEdgeCounts.entrySet()) {\r\n String tblKey = entry.getKey();\r\n int sVal = entry.getValue();\r\n if (!gsonTableCounts.containsKey(tblKey)) {\r\n String msg = \" Entry for edge+Label combo [\" + tblKey + \"] not found in the Graphson db, but had \" + sVal + \" entries in the SQL db.\";\r\n LOGGER.error(msg);\r\n System.out.println(msg);\r\n outWriter.write(msg);\r\n outWriter.newLine();\r\n continue;\r\n }\r\n }\r\n outWriter.close();\r\n String msg = \"Audit Results written to: \" + fName;\r\n LOGGER.debug(msg);\r\n System.out.println(msg);\r\n return fName;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public T marginalize(){\r\n Object[] args = new Object[targetParameterMap.length];\r\n args[0] = this;\r\n for (int i = 1; i < targetParameterMap.length; i++) {\r\n int id = targetParameterMap[i];\r\n BayesVariableState varState = varStates[id];\r\n marginalize(varState);\r\n int highestIndex = 0;\r\n double highestValue = 0;\r\n int maximalCounts = 1;\r\n for (int j = 0, length = varState.getDistribution().length; j < length; j++) {\r\n if (varState.getDistribution()[j] > highestValue) {\r\n highestValue = varState.getDistribution()[j];\r\n highestIndex = j;\r\n maximalCounts = 1;\r\n } else if (j != 0 && varState.getDistribution()[j] == highestValue) {\r\n maximalCounts++;\r\n }\r\n }\r\n if (maximalCounts > 1) {\r\n int picked = randomGenerator.nextInt(maximalCounts);\r\n int count = 0;\r\n for (int j = 0, length = varState.getDistribution().length; j < length; j++) {\r\n if (varState.getDistribution()[j] == highestValue) {\r\n highestIndex = j;\r\n if (++count > picked) {\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n args[i] = varState.getOutcomes()[highestIndex];\r\n }\r\n try {\r\n return targetConstructor.newInstance(args);\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"Unable to instantiate \" + targetClass.getSimpleName() + \" \" + Arrays.asList(args), e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Fragment getResourceFragment(final TopologyNode node, final PageReference pageRef){\r\n Fragment fragment = new Fragment(\"actions\", \"resourceActions\", this);\r\n AjaxLink delete = new IndicatingOnConfirmAjaxLink<>(\"delete\", true) {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n try {\r\n ResourceRestClient.delete(node.getKey());\r\n target.appendJavaScript(String.format(\"jsPlumb.remove('%s');\", node.getKey()));\r\n SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));\r\n toggle(target, false);\r\n } catch (SyncopeClientException e) {\r\n LOG.error(\"While deleting resource {}\", node.getKey(), e);\r\n SyncopeConsoleSession.get().onException(e);\r\n }\r\n ((BaseWebPage) pageRef.getPage()).getNotificationPanel().refresh(target);\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(delete, RENDER, IdMEntitlement.RESOURCE_DELETE);\r\n fragment.add(delete);\r\n AjaxLink edit = new IndicatingAjaxLink<>(\"edit\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n ResourceTO resource = ResourceRestClient.read(node.getKey());\r\n ConnInstanceTO connInstance = ConnectorRestClient.read(resource.getConnector());\r\n IModel model = new CompoundPropertyModel<>(resource);\r\n modal.setFormModel(model);\r\n target.add(modal.setContent(new ResourceWizardBuilder(resource, pageRef).build(BaseModal.CONTENT_ID, SyncopeConsoleSession.get().owns(IdMEntitlement.RESOURCE_UPDATE, connInstance.getAdminRealm()) ? AjaxWizard.Mode.EDIT : AjaxWizard.Mode.READONLY)));\r\n modal.header(new Model<>(MessageFormat.format(getString(\"resource.edit\"), node.getKey())));\r\n modal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(edit, RENDER, IdMEntitlement.RESOURCE_READ);\r\n fragment.add(edit);\r\n AjaxLink status = new IndicatingAjaxLink<>(\"reconciliation\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n ResourceTO modelObject = ResourceRestClient.read(node.getKey());\r\n target.add(propTaskModal.setContent(new ResourceStatusModal(propTaskModal, pageRef, modelObject)));\r\n propTaskModal.header(new Model<>(MessageFormat.format(getString(\"resource.reconciliation\"), node.getKey())));\r\n propTaskModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(status, RENDER, IdRepoEntitlement.USER_UPDATE);\r\n fragment.add(status);\r\n AjaxLink provision = new IndicatingAjaxLink<>(\"provision\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n ResourceTO resource = ResourceRestClient.read(node.getKey());\r\n ConnInstanceTO connInstance = ConnectorRestClient.read(resource.getConnector());\r\n if (SyncopeConsoleSession.get().owns(IdMEntitlement.RESOURCE_UPDATE, connInstance.getAdminRealm())) {\r\n provisionModal.addSubmitButton();\r\n } else {\r\n provisionModal.removeSubmitButton();\r\n }\r\n IModel model = new CompoundPropertyModel<>(resource);\r\n provisionModal.setFormModel(model);\r\n target.add(provisionModal.setContent(new ResourceProvisionPanel(provisionModal, resource, connInstance.getAdminRealm(), pageRef)));\r\n provisionModal.header(new Model<>(MessageFormat.format(getString(\"resource.edit\"), node.getKey())));\r\n provisionModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(edit, RENDER, IdMEntitlement.RESOURCE_READ);\r\n fragment.add(provision);\r\n AjaxLink explore = new IndicatingAjaxLink<>(\"explore\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n ResourceTO resource = ResourceRestClient.read(node.getKey());\r\n target.add(propTaskModal.setContent(new ConnObjects(resource, pageRef)));\r\n propTaskModal.header(new StringResourceModel(\"resource.explore.list\", Model.of(node)));\r\n propTaskModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(explore, RENDER, IdMEntitlement.RESOURCE_LIST_CONNOBJECT);\r\n fragment.add(explore);\r\n AjaxLink propagation = new IndicatingAjaxLink<>(\"propagation\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n @SuppressWarnings(\"unchecked\")\r\n public void onClick(final AjaxRequestTarget target) {\r\n target.add(propTaskModal.setContent(new PropagationTasks(propTaskModal, node.getKey(), pageRef)));\r\n propTaskModal.header(new Model<>(MessageFormat.format(getString(\"task.propagation.list\"), node.getKey())));\r\n propTaskModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(propagation, RENDER, IdRepoEntitlement.TASK_LIST);\r\n fragment.add(propagation);\r\n AjaxLink pull = new IndicatingAjaxLink<>(\"pull\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n target.add(schedTaskModal.setContent(new PullTasks(schedTaskModal, pageRef, node.getKey())));\r\n schedTaskModal.header(new Model<>(MessageFormat.format(getString(\"task.pull.list\"), node.getKey())));\r\n schedTaskModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(pull, RENDER, IdRepoEntitlement.TASK_LIST);\r\n fragment.add(pull);\r\n AjaxLink push = new IndicatingAjaxLink<>(\"push\") {\r\n\r\n private static final long serialVersionUID = 3776750333491622263L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n target.add(schedTaskModal.setContent(new PushTasks(schedTaskModal, pageRef, node.getKey())));\r\n schedTaskModal.header(new Model<>(MessageFormat.format(getString(\"task.push.list\"), node.getKey())));\r\n schedTaskModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(push, RENDER, IdRepoEntitlement.TASK_LIST);\r\n fragment.add(push);\r\n AjaxLink history = new IndicatingAjaxLink<>(\"history\") {\r\n\r\n private static final long serialVersionUID = -1876519166660008562L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n ResourceTO modelObject = ResourceRestClient.read(node.getKey());\r\n target.add(historyModal.setContent(new AuditHistoryModal<>(historyModal, AuditElements.EventCategoryType.LOGIC, \"ResourceLogic\", modelObject, IdMEntitlement.RESOURCE_UPDATE, pageRef) {\r\n\r\n private static final long serialVersionUID = -3712506022627033811L;\r\n\r\n @Override\r\n protected void restore(final String json, final AjaxRequestTarget target) {\r\n try {\r\n ResourceTO updated = MAPPER.readValue(json, ResourceTO.class);\r\n ResourceRestClient.update(updated);\r\n SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));\r\n toggle(target, false);\r\n } catch (Exception e) {\r\n LOG.error(\"While restoring resource {}\", node.getKey(), e);\r\n SyncopeConsoleSession.get().onException(e);\r\n }\r\n ((BaseWebPage) pageRef.getPage()).getNotificationPanel().refresh(target);\r\n }\r\n }));\r\n historyModal.header(new Model<>(MessageFormat.format(getString(\"resource.menu.history\"), node.getDisplayName())));\r\n historyModal.show(true);\r\n }\r\n\r\n @Override\r\n public String getAjaxIndicatorMarkupId() {\r\n return Constants.VEIL_INDICATOR_MARKUP_ID;\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(history, RENDER, String.format(\"%s,%s\", IdMEntitlement.RESOURCE_READ, IdRepoEntitlement.AUDIT_LIST));\r\n fragment.add(history);\r\n AjaxLink clone = new IndicatingAjaxLink<>(\"clone\") {\r\n\r\n private static final long serialVersionUID = -7978723352517770644L;\r\n\r\n @Override\r\n public void onClick(final AjaxRequestTarget target) {\r\n try {\r\n ResourceTO resource = ResourceRestClient.read(node.getKey());\r\n resource.setKey(\"Copy of \" + node.getKey());\r\n if (resource.getOrgUnit() != null) {\r\n resource.getOrgUnit().setKey(null);\r\n for (ItemTO item : resource.getOrgUnit().getItems()) {\r\n item.setKey(null);\r\n }\r\n }\r\n for (ProvisionTO provision : resource.getProvisions()) {\r\n provision.setKey(null);\r\n if (provision.getMapping() != null) {\r\n for (ItemTO item : provision.getMapping().getItems()) {\r\n item.setKey(null);\r\n }\r\n provision.getMapping().getLinkingItems().clear();\r\n }\r\n provision.getVirSchemas().clear();\r\n }\r\n target.add(modal.setContent(new ResourceWizardBuilder(resource, pageRef).build(BaseModal.CONTENT_ID, AjaxWizard.Mode.CREATE)));\r\n modal.header(new Model<>(MessageFormat.format(getString(\"resource.clone\"), node.getKey())));\r\n modal.show(true);\r\n } catch (SyncopeClientException e) {\r\n LOG.error(\"While cloning resource {}\", node.getKey(), e);\r\n SyncopeConsoleSession.get().onException(e);\r\n }\r\n ((BaseWebPage) pageRef.getPage()).getNotificationPanel().refresh(target);\r\n }\r\n };\r\n MetaDataRoleAuthorizationStrategy.authorize(clone, RENDER, IdMEntitlement.RESOURCE_CREATE);\r\n fragment.add(clone);\r\n return fragment;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass, boolean readLocalsFromTuple, MVELCompilationUnit.Scope scope){\r\n Map resolvedInputs = new LinkedHashMap<>();\r\n List ids = new ArrayList<>();\r\n if (analysis.getBoundIdentifiers().getThisClass() != null || (localDeclarations != null && localDeclarations.length > 0)) {\r\n Class cls = analysis.getBoundIdentifiers().getThisClass();\r\n ids.add(\"this\");\r\n resolvedInputs.put(\"this\", (cls != null) ? cls : Object.class);\r\n }\r\n ids.add(contextIndeifier);\r\n resolvedInputs.put(contextIndeifier, kcontextClass);\r\n ids.add(\"kcontext\");\r\n resolvedInputs.put(\"kcontext\", kcontextClass);\r\n if (scope.hasRule()) {\r\n ids.add(\"rule\");\r\n resolvedInputs.put(\"rule\", Rule.class);\r\n }\r\n List strList = new ArrayList<>();\r\n for (String identifier : analysis.getIdentifiers()) {\r\n Type type = identifier.equals(WM_ARGUMENT) ? InternalWorkingMemory.class : analysis.getBoundIdentifiers().resolveVarType(identifier);\r\n if (type != null) {\r\n strList.add(identifier);\r\n ids.add(identifier);\r\n resolvedInputs.put(identifier, type);\r\n }\r\n }\r\n String[] globalIdentifiers = strList.toArray(new String[strList.size()]);\r\n strList.clear();\r\n for (String op : analysis.getBoundIdentifiers().getOperators().keySet()) {\r\n strList.add(op);\r\n ids.add(op);\r\n resolvedInputs.put(op, EvaluatorWrapper.class);\r\n }\r\n EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()];\r\n for (int i = 0; i < operators.length; i++) {\r\n operators[i] = analysis.getBoundIdentifiers().getOperators().get(strList.get(i));\r\n }\r\n if (previousDeclarations != null) {\r\n for (Declaration decl : previousDeclarations) {\r\n if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {\r\n ids.add(decl.getIdentifier());\r\n resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());\r\n }\r\n }\r\n }\r\n if (localDeclarations != null) {\r\n for (Declaration decl : localDeclarations) {\r\n if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {\r\n ids.add(decl.getIdentifier());\r\n resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());\r\n }\r\n }\r\n }\r\n strList = new ArrayList<>();\r\n if (otherInputVariables != null) {\r\n MVELAnalysisResult mvelAnalysis = (MVELAnalysisResult) analysis;\r\n for (Entry> stringClassEntry : otherInputVariables.entrySet()) {\r\n if ((!analysis.getNotBoundedIdentifiers().contains(stringClassEntry.getKey()) && !mvelAnalysis.getMvelVariables().containsKey(stringClassEntry.getKey())) || \"rule\".equals(stringClassEntry.getKey())) {\r\n continue;\r\n }\r\n ids.add(stringClassEntry.getKey());\r\n strList.add(stringClassEntry.getKey());\r\n resolvedInputs.put(stringClassEntry.getKey(), stringClassEntry.getValue());\r\n }\r\n }\r\n String[] otherIdentifiers = strList.toArray(new String[strList.size()]);\r\n String[] inputIdentifiers = new String[resolvedInputs.size()];\r\n String[] inputTypes = new String[resolvedInputs.size()];\r\n int i = 0;\r\n for (String id : ids) {\r\n inputIdentifiers[i] = id;\r\n Type inputType = resolvedInputs.get(id);\r\n inputTypes[i++] = inputType instanceof Class ? ((Class) inputType).getName() : inputType.getTypeName();\r\n }\r\n String name;\r\n if (context != null && context.getPkg() != null && context.getPkg().getName() != null) {\r\n if (context instanceof RuleBuildContext) {\r\n name = context.getPkg().getName() + \".\" + ((RuleBuildContext) context).getRuleDescr().getClassName();\r\n } else {\r\n name = context.getPkg().getName() + \".Unknown\";\r\n }\r\n } else {\r\n name = \"Unknown\";\r\n }\r\n return new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, analysis.isTypesafe(), readLocalsFromTuple);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Result visit(Values e){\r\n final List clauses = ImmutableList.of(Clause.SELECT);\r\n final Map pairs = ImmutableMap.of();\r\n final Context context = aliasContext(pairs, false);\r\n SqlNode query;\r\n final boolean rename = stack.size() <= 1 || !(Iterables.get(stack, 1).r instanceof TableModify);\r\n final List fieldNames = e.getRowType().getFieldNames();\r\n if (!dialect.supportsAliasedValues() && rename) {\r\n List list = new ArrayList<>();\r\n for (List tuple : e.getTuples()) {\r\n final List values2 = new ArrayList<>();\r\n final SqlNodeList exprList = exprList(context, tuple);\r\n for (Pair value : Pair.zip(exprList, fieldNames)) {\r\n values2.add(as(value.left, value.right));\r\n }\r\n list.add(new SqlSelect(POS, null, new SqlNodeList(values2, POS), getDual(), null, null, null, null, null, null, null, null, null));\r\n }\r\n if (list.isEmpty()) {\r\n final List nullColumnNames = new ArrayList<>(fieldNames.size());\r\n for (String fieldName : fieldNames) {\r\n SqlCall nullColumnName = as(SqlLiteral.createNull(POS), fieldName);\r\n nullColumnNames.add(nullColumnName);\r\n }\r\n final SqlIdentifier dual = getDual();\r\n if (dual == null) {\r\n query = new SqlSelect(POS, null, new SqlNodeList(nullColumnNames, POS), null, null, null, null, null, null, null, null, null, null);\r\n query = new SqlSelect(POS, null, SqlNodeList.SINGLETON_STAR, as(query, \"t\"), createAlwaysFalseCondition(), null, null, null, null, null, null, null, null);\r\n } else {\r\n query = new SqlSelect(POS, null, new SqlNodeList(nullColumnNames, POS), dual, createAlwaysFalseCondition(), null, null, null, null, null, null, null, null);\r\n }\r\n } else if (list.size() == 1) {\r\n query = list.get(0);\r\n } else {\r\n query = list.stream().map(select -> (SqlNode) select).reduce((l, r) -> SqlStdOperatorTable.UNION_ALL.createCall(POS, l, r)).get();\r\n }\r\n } else {\r\n final SqlNodeList selects = new SqlNodeList(POS);\r\n final boolean isEmpty = Values.isEmpty(e);\r\n if (isEmpty) {\r\n selects.add(SqlInternalOperators.ANONYMOUS_ROW.createCall(POS, Collections.nCopies(fieldNames.size(), SqlLiteral.createNull(POS))));\r\n } else {\r\n for (List tuple : e.getTuples()) {\r\n selects.add(SqlInternalOperators.ANONYMOUS_ROW.createCall(exprList(context, tuple)));\r\n }\r\n }\r\n query = SqlStdOperatorTable.VALUES.createCall(selects);\r\n if (rename) {\r\n query = as(query, \"t\", fieldNames.toArray(new String[0]));\r\n }\r\n if (isEmpty) {\r\n if (!rename) {\r\n query = as(query, \"t\");\r\n }\r\n query = new SqlSelect(POS, null, SqlNodeList.SINGLETON_STAR, query, createAlwaysFalseCondition(), null, null, null, null, null, null, null, null);\r\n }\r\n }\r\n return result(query, clauses, e, null);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Statement visit(ConditionalStatement conditionalStatement, List list){\r\n boolean optimal = true;\r\n for (int i = 0; i < list.size() - 1 && optimal; i += 2) {\r\n Boolean always = always((Expression) list.get(i));\r\n if (always == null) {\r\n continue;\r\n }\r\n if (i == 0 && always) {\r\n return (Statement) list.get(1);\r\n }\r\n optimal = false;\r\n }\r\n if (optimal) {\r\n return super.visit(conditionalStatement, list);\r\n }\r\n List newList = new ArrayList<>(list.size());\r\n for (int i = 0; i < list.size() - 1; i += 2) {\r\n Expression test = (Expression) list.get(i);\r\n Node stmt = list.get(i + 1);\r\n Boolean always = always(test);\r\n if (always == null) {\r\n newList.add(test);\r\n newList.add(stmt);\r\n continue;\r\n }\r\n if (always) {\r\n newList.add(stmt);\r\n break;\r\n }\r\n }\r\n if (list.size() == 1) {\r\n return (Statement) list.get(0);\r\n }\r\n if (newList.size() % 2 == 0 && list.size() % 2 == 1) {\r\n Node elseBlock = list.get(list.size() - 1);\r\n if (newList.isEmpty()) {\r\n return (Statement) elseBlock;\r\n }\r\n newList.add(elseBlock);\r\n }\r\n if (newList.isEmpty()) {\r\n return EMPTY_STATEMENT;\r\n }\r\n return super.visit(conditionalStatement, newList);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Expression visit(BinaryExpression binary, Expression expression0, Expression expression1){\r\n Expression result;\r\n switch(binary.getNodeType()) {\r\n case Assign:\r\n expression1 = skipNullCast(expression1);\r\n break;\r\n case AndAlso:\r\n case OrElse:\r\n if (eq(expression0, expression1)) {\r\n return expression0;\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n switch(binary.getNodeType()) {\r\n case Equal:\r\n case NotEqual:\r\n if (eq(expression0, expression1)) {\r\n return binary.getNodeType() == Equal ? TRUE_EXPR : FALSE_EXPR;\r\n } else if (expression0 instanceof ConstantExpression && expression1 instanceof ConstantExpression) {\r\n ConstantExpression c0 = (ConstantExpression) expression0;\r\n ConstantExpression c1 = (ConstantExpression) expression1;\r\n if (c0.getType() == c1.getType() || !(Primitive.is(c0.getType()) || Primitive.is(c1.getType()))) {\r\n return binary.getNodeType() == NotEqual ? TRUE_EXPR : FALSE_EXPR;\r\n }\r\n }\r\n if (expression0 instanceof TernaryExpression && expression0.getNodeType() == ExpressionType.Conditional) {\r\n TernaryExpression ternary = (TernaryExpression) expression0;\r\n Expression expr = null;\r\n if (eq(ternary.expression1, expression1)) {\r\n expr = Expressions.orElse(ternary.expression0, Expressions.equal(ternary.expression2, expression1));\r\n } else if (eq(ternary.expression2, expression1)) {\r\n expr = Expressions.orElse(Expressions.not(ternary.expression0), Expressions.equal(ternary.expression1, expression1));\r\n }\r\n if (expr != null) {\r\n if (binary.getNodeType() == ExpressionType.NotEqual) {\r\n expr = Expressions.not(expr);\r\n }\r\n return expr.accept(this);\r\n }\r\n }\r\n case AndAlso:\r\n case OrElse:\r\n result = visit0(binary, expression0, expression1);\r\n if (result != null) {\r\n return result;\r\n }\r\n result = visit0(binary, expression1, expression0);\r\n if (result != null) {\r\n return result;\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n return super.visit(binary, expression0, expression1);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static SearchTerm toSearchTerm(SimpleSearchTerm simple) throws ParseException{\r\n SearchTermBuilder builder = new SearchTermBuilder();\r\n if (simple.isUnseen()) {\r\n builder = builder.unseen();\r\n }\r\n if (simple.getSubjectOrBody() != null) {\r\n String text = simple.getSubjectOrBody();\r\n SearchTermBuilder builderTemp = new SearchTermBuilder();\r\n builderTemp = builderTemp.subject(text).body(SearchTermBuilder.Op.or, text);\r\n builder = builder.and(builderTemp.build());\r\n }\r\n if (simple.getSubject() != null) {\r\n builder = builder.subject(simple.getSubject());\r\n }\r\n if (simple.getBody() != null) {\r\n builder = builder.body(simple.getBody());\r\n }\r\n if (simple.getFrom() != null) {\r\n builder = builder.from(simple.getFrom());\r\n }\r\n if (simple.getTo() != null) {\r\n builder = builder.recipient(Message.RecipientType.TO, simple.getTo());\r\n }\r\n if (simple.getFromSentDate() != null) {\r\n String s = simple.getFromSentDate();\r\n if (s.startsWith(\"now\")) {\r\n long offset = extractOffset(s);\r\n builder = builder.and(new NowSearchTerm(SearchTermBuilder.Comparison.GE.asNum(), true, offset));\r\n } else {\r\n SimpleDateFormat sdf = new SimpleDateFormat(NOW_DATE_FORMAT);\r\n Date date = sdf.parse(s);\r\n builder = builder.sent(SearchTermBuilder.Comparison.GE, date);\r\n }\r\n }\r\n if (simple.getToSentDate() != null) {\r\n String s = simple.getToSentDate();\r\n if (s.startsWith(\"now\")) {\r\n long offset = extractOffset(s);\r\n builder = builder.and(new NowSearchTerm(SearchTermBuilder.Comparison.LE.asNum(), true, offset));\r\n } else {\r\n SimpleDateFormat sdf = new SimpleDateFormat(NOW_DATE_FORMAT);\r\n Date date = sdf.parse(s);\r\n builder = builder.sent(SearchTermBuilder.Comparison.LE, date);\r\n }\r\n }\r\n if (simple.getFromReceivedDate() != null) {\r\n String s = simple.getFromReceivedDate();\r\n if (s.startsWith(\"now\")) {\r\n long offset = extractOffset(s);\r\n builder = builder.and(new NowSearchTerm(SearchTermBuilder.Comparison.GE.asNum(), false, offset));\r\n } else {\r\n SimpleDateFormat sdf = new SimpleDateFormat(NOW_DATE_FORMAT);\r\n Date date = sdf.parse(s);\r\n builder = builder.received(SearchTermBuilder.Comparison.GE, date);\r\n }\r\n }\r\n if (simple.getToReceivedDate() != null) {\r\n String s = simple.getToReceivedDate();\r\n if (s.startsWith(\"now\")) {\r\n long offset = extractOffset(s);\r\n builder = builder.and(new NowSearchTerm(SearchTermBuilder.Comparison.LE.asNum(), false, offset));\r\n } else {\r\n SimpleDateFormat sdf = new SimpleDateFormat(NOW_DATE_FORMAT);\r\n Date date = sdf.parse(s);\r\n builder = builder.received(SearchTermBuilder.Comparison.LE, date);\r\n }\r\n }\r\n return builder.build();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String resolveContent(String result, Set usedIds, Set allUsedIds){\r\n String res = result;\r\n if (RESOLVE_CONTENT_PATTERN.matcher(res).matches()) {\r\n StringBuilder newRes = new StringBuilder();\r\n int piv = 0;\r\n int next;\r\n while ((next = res.indexOf(FieldWriter.BIBTEX_STRING_START_END_SYMBOL, piv)) >= 0) {\r\n if (next > 0) {\r\n newRes.append(res, piv, next);\r\n }\r\n int stringEnd = res.indexOf(FieldWriter.BIBTEX_STRING_START_END_SYMBOL, next + 1);\r\n if (stringEnd >= 0) {\r\n String refLabel = res.substring(next + 1, stringEnd);\r\n String resolved = resolveString(refLabel, usedIds, allUsedIds);\r\n if (resolved == null) {\r\n newRes.append(res, next, stringEnd + 1);\r\n } else {\r\n newRes.append(resolved);\r\n }\r\n piv = stringEnd + 1;\r\n } else {\r\n newRes.append(res.substring(next));\r\n piv = res.length();\r\n break;\r\n }\r\n }\r\n if (piv < (res.length() - 1)) {\r\n newRes.append(res.substring(piv));\r\n }\r\n res = newRes.toString();\r\n }\r\n return res;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void doMarshal(Exchange exchange, Object graph, OutputStream stream, Marshaller marshaller, String charset) throws Exception{\r\n Object element = graph;\r\n QName partNamespaceOnDataFormat = getPartNamespace();\r\n String partClassFromHeader = exchange.getIn().getHeader(JaxbConstants.JAXB_PART_CLASS, String.class);\r\n String partNamespaceFromHeader = exchange.getIn().getHeader(JaxbConstants.JAXB_PART_NAMESPACE, String.class);\r\n if ((partClass != null || partClassFromHeader != null) && (partNamespaceOnDataFormat != null || partNamespaceFromHeader != null)) {\r\n if (partClassFromHeader != null) {\r\n try {\r\n partClass = camelContext.getClassResolver().resolveMandatoryClass(partClassFromHeader, Object.class);\r\n } catch (ClassNotFoundException e) {\r\n throw new JAXBException(e);\r\n }\r\n }\r\n if (partNamespaceFromHeader != null) {\r\n partNamespaceOnDataFormat = QName.valueOf(partNamespaceFromHeader);\r\n }\r\n element = new JAXBElement<>(partNamespaceOnDataFormat, (Class) partClass, graph);\r\n }\r\n if (introspector.isElement(element)) {\r\n if (asXmlStreamWriter(exchange)) {\r\n XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, exchange, stream);\r\n if (needFiltering(exchange)) {\r\n writer = new FilteringXmlStreamWriter(writer, charset);\r\n }\r\n if (xmlStreamWriterWrapper != null) {\r\n writer = xmlStreamWriterWrapper.wrapWriter(writer);\r\n }\r\n marshaller.marshal(element, writer);\r\n } else {\r\n marshaller.marshal(element, stream);\r\n }\r\n return;\r\n } else if (objectFactory && element != null) {\r\n Method objectFactoryMethod = JaxbHelper.getJaxbElementFactoryMethod(camelContext, element.getClass());\r\n if (objectFactoryMethod != null) {\r\n try {\r\n Object instance = objectFactoryMethod.getDeclaringClass().newInstance();\r\n if (instance != null) {\r\n Object toMarshall = objectFactoryMethod.invoke(instance, element);\r\n if (asXmlStreamWriter(exchange)) {\r\n XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, exchange, stream);\r\n if (needFiltering(exchange)) {\r\n writer = new FilteringXmlStreamWriter(writer, charset);\r\n }\r\n if (xmlStreamWriterWrapper != null) {\r\n writer = xmlStreamWriterWrapper.wrapWriter(writer);\r\n }\r\n marshaller.marshal(toMarshall, writer);\r\n } else {\r\n marshaller.marshal(toMarshall, stream);\r\n }\r\n return;\r\n }\r\n } catch (Exception e) {\r\n if (MarshalException.class.isAssignableFrom(e.getClass()) && schema != null) {\r\n throw e;\r\n }\r\n LOG.debug(\"Unable to create JAXBElement object for type {} due to {}\", element.getClass(), e.getMessage(), e);\r\n }\r\n }\r\n }\r\n if (!mustBeJAXBElement) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Attempt to marshalling non JAXBElement with type {} as InputStream\", ObjectHelper.classCanonicalName(graph));\r\n }\r\n InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);\r\n IOHelper.copyAndCloseInput(is, stream);\r\n } else {\r\n throw new InvalidPayloadException(exchange, JAXBElement.class);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final Project oldTopProject = call.rel(0);\r\n final Project oldMiddleProject = call.rel(1);\r\n final Aggregate oldAgg = call.rel(2);\r\n final Project oldBottomProject = call.rel(3);\r\n final RelBuilder relBuilder = call.builder();\r\n if (oldAgg.getAggCallList().size() != 1 || oldAgg.getAggCallList().get(0).getAggregation().getKind() != SqlKind.COLLECT) {\r\n return;\r\n }\r\n final List pigAggUdfs = new ArrayList<>();\r\n boolean needGroupingCol = false;\r\n for (RexNode rex : oldTopProject.getProjects()) {\r\n PigAggUdfFinder udfVisitor = new PigAggUdfFinder(1);\r\n rex.accept(udfVisitor);\r\n if (!udfVisitor.pigAggCalls.isEmpty()) {\r\n for (RexCall pigAgg : udfVisitor.pigAggCalls) {\r\n if (!pigAggUdfs.contains(pigAgg)) {\r\n pigAggUdfs.add(pigAgg);\r\n }\r\n }\r\n } else if (udfVisitor.projectColReferred) {\r\n needGroupingCol = true;\r\n }\r\n }\r\n final List newBottomProjects = new ArrayList<>();\r\n relBuilder.push(oldBottomProject.getInput());\r\n for (int i = 0; i < oldAgg.getGroupCount(); i++) {\r\n newBottomProjects.add(oldBottomProject.getProjects().get(i));\r\n }\r\n if (needGroupingCol) {\r\n final RexNode row = relBuilder.getRexBuilder().makeCall(relBuilder.peek().getRowType(), SqlStdOperatorTable.ROW, relBuilder.fields());\r\n newBottomProjects.add(row);\r\n }\r\n final int groupCount = oldAgg.getGroupCount() + (needGroupingCol ? 1 : 0);\r\n final Map projectedAggColumns = new HashMap<>();\r\n for (int i = 0; i < newBottomProjects.size(); i++) {\r\n if (newBottomProjects.get(i) instanceof RexInputRef) {\r\n projectedAggColumns.put(((RexInputRef) newBottomProjects.get(i)).getIndex(), i);\r\n }\r\n }\r\n final Map> aggCallColumns = new HashMap<>();\r\n for (RexCall rexCall : pigAggUdfs) {\r\n final List requiredColumns = getAggColumns(rexCall);\r\n final List newColIndexes = new ArrayList<>();\r\n for (int col : requiredColumns) {\r\n Integer newCol = projectedAggColumns.get(col);\r\n if (newCol != null) {\r\n newColIndexes.add(newCol);\r\n } else {\r\n final RexCall rowCall = (RexCall) oldBottomProject.getProjects().get(oldAgg.getGroupCount());\r\n final RexInputRef columnRef = (RexInputRef) rowCall.getOperands().get(col);\r\n final int newIndex = newBottomProjects.size();\r\n newBottomProjects.add(columnRef);\r\n projectedAggColumns.put(columnRef.getIndex(), newIndex);\r\n newColIndexes.add(newIndex);\r\n }\r\n }\r\n aggCallColumns.put(rexCall, newColIndexes);\r\n }\r\n relBuilder.project(newBottomProjects);\r\n final RelBuilder.GroupKey groupKey = relBuilder.groupKey(oldAgg.getGroupSet(), oldAgg.groupSets);\r\n final List aggCalls = new ArrayList<>();\r\n if (needGroupingCol) {\r\n aggCalls.add(relBuilder.aggregateCall(SqlStdOperatorTable.COLLECT, relBuilder.field(groupCount - 1)));\r\n }\r\n for (RexCall rexCall : pigAggUdfs) {\r\n final List aggOperands = new ArrayList<>();\r\n for (int i : aggCallColumns.get(rexCall)) {\r\n aggOperands.add(relBuilder.field(i));\r\n }\r\n if (isMultisetProjection(rexCall)) {\r\n if (aggOperands.size() == 1) {\r\n aggCalls.add(relBuilder.aggregateCall(SqlStdOperatorTable.COLLECT, aggOperands));\r\n } else {\r\n final RelDataType rowType = createRecordType(relBuilder, aggCallColumns.get(rexCall));\r\n final RexNode row = relBuilder.getRexBuilder().makeCall(rowType, SqlStdOperatorTable.ROW, aggOperands);\r\n aggCalls.add(relBuilder.aggregateCall(SqlStdOperatorTable.COLLECT, row));\r\n }\r\n } else {\r\n final SqlAggFunction udf = PigRelUdfConverter.getSqlAggFuncForPigUdf(rexCall);\r\n aggCalls.add(relBuilder.aggregateCall(udf, aggOperands));\r\n }\r\n }\r\n relBuilder.aggregate(groupKey, aggCalls);\r\n final RelDataType aggType = relBuilder.peek().getRowType();\r\n final Map pigCallToNewProjections = new HashMap<>();\r\n for (int i = 0; i < pigAggUdfs.size(); i++) {\r\n final RexCall pigAgg = pigAggUdfs.get(i);\r\n final int colIndex = i + groupCount;\r\n final RelDataType fieldType = aggType.getFieldList().get(colIndex).getType();\r\n final RelDataType oldFieldType = pigAgg.getType();\r\n if (fieldType.equals(oldFieldType)) {\r\n pigCallToNewProjections.put(pigAgg, relBuilder.field(colIndex));\r\n } else {\r\n pigCallToNewProjections.put(pigAgg, relBuilder.getRexBuilder().makeCast(oldFieldType, relBuilder.field(colIndex)));\r\n }\r\n }\r\n final List newTopProjects = new ArrayList<>();\r\n final List oldUpperProjects = oldTopProject.getProjects();\r\n for (RexNode rexNode : oldUpperProjects) {\r\n int groupRefIndex = getGroupRefIndex(rexNode);\r\n if (groupRefIndex >= 0) {\r\n newTopProjects.add(relBuilder.field(groupRefIndex));\r\n } else if (rexNode instanceof RexInputRef && ((RexInputRef) rexNode).getIndex() == 0) {\r\n newTopProjects.add(oldMiddleProject.getProjects().get(0));\r\n } else {\r\n RexCallReplacer replacer = needGroupingCol ? new RexCallReplacer(relBuilder.getRexBuilder(), pigCallToNewProjections, 1, relBuilder.field(groupCount - 1)) : new RexCallReplacer(relBuilder.getRexBuilder(), pigCallToNewProjections);\r\n newTopProjects.add(rexNode.accept(replacer));\r\n }\r\n }\r\n relBuilder.project(newTopProjects, oldTopProject.getRowType().getFieldNames());\r\n call.transformTo(relBuilder.build());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AttributeDescr stringListAttribute(AttributeSupportBuilder as, String[] key) throws RecognitionException{\r\n AttributeDescrBuilder attribute = null;\r\n try {\r\n StringBuilder builder = new StringBuilder();\r\n for (String k : key) {\r\n if (\"-\".equals(k)) {\r\n match(input, DRL6Lexer.MINUS, k, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n } else {\r\n match(input, DRL6Lexer.ID, k, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n }\r\n builder.append(k);\r\n }\r\n if (state.backtracking == 0) {\r\n attribute = helper.start((DescrBuilder) as, AttributeDescrBuilder.class, builder.toString());\r\n }\r\n builder = new StringBuilder();\r\n builder.append(\"[ \");\r\n Token value = match(input, DRL6Lexer.STRING, null, null, DroolsEditorType.STRING_CONST);\r\n if (state.failed)\r\n return null;\r\n builder.append(value.getText());\r\n while (input.LA(1) == DRL6Lexer.COMMA) {\r\n match(input, DRL6Lexer.COMMA, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return null;\r\n builder.append(\", \");\r\n value = match(input, DRL6Lexer.STRING, null, null, DroolsEditorType.STRING_CONST);\r\n if (state.failed)\r\n return null;\r\n builder.append(value.getText());\r\n }\r\n builder.append(\" ]\");\r\n if (state.backtracking == 0) {\r\n if (attribute != null) {\r\n attribute.value(builder.toString());\r\n attribute.type(AttributeDescr.Type.LIST);\r\n }\r\n }\r\n } finally {\r\n if (attribute != null) {\r\n helper.end(AttributeDescrBuilder.class, attribute);\r\n }\r\n }\r\n return attribute != null ? attribute.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CompletableFuture byUpdatingNearCacheAsync(Supplier> remoteCallSupplier, K key, Data keyData, V value, Data valueData, BiConsumer statsCallback, boolean calledByBooleanMethod){\r\n Object nearCacheKey = toNearCacheKey(key, keyData);\r\n long reservationId = cacheOnUpdate ? nearCache.tryReserveForUpdate(nearCacheKey, keyData, WRITE_UPDATE) : NOT_RESERVED;\r\n CompletableFuture future = remoteCallSupplier.get();\r\n if (reservationId != NOT_RESERVED) {\r\n return future.whenCompleteAsync((response, throwable) -> {\r\n if (statsCallback != null) {\r\n statsCallback.accept(response, throwable);\r\n }\r\n if (throwable != null) {\r\n invalidateNearCache(nearCacheKey);\r\n } else if ((calledByBooleanMethod && response instanceof Boolean ? ((Boolean) response) : true)) {\r\n Object nearCacheValue = toNearCacheValue(value, valueData);\r\n tryPublishReserved(nearCacheKey, nearCacheValue, reservationId, false);\r\n } else {\r\n invalidateNearCache(nearCacheKey);\r\n }\r\n }, getDefaultAsyncExecutor());\r\n } else {\r\n return future.whenCompleteAsync((response, throwable) -> {\r\n if (statsCallback != null) {\r\n statsCallback.accept(response, throwable);\r\n }\r\n invalidateNearCache(nearCacheKey);\r\n }, getDefaultAsyncExecutor());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List> splitEqualSets(List rexNodes, List leftNodes){\r\n final List> equalSets = new ArrayList<>();\r\n for (RexNode rexNode : rexNodes) {\r\n if (rexNode.isA(SqlKind.EQUALS)) {\r\n final RexNode op1 = ((RexCall) rexNode).getOperands().get(0);\r\n final RexNode op2 = ((RexCall) rexNode).getOperands().get(1);\r\n if (op1 instanceof RexInputRef && op2 instanceof RexInputRef) {\r\n final RexInputRef in1 = (RexInputRef) op1;\r\n final RexInputRef in2 = (RexInputRef) op2;\r\n Set set = null;\r\n for (Set s : equalSets) {\r\n if (s.contains(in1) || s.contains(in2)) {\r\n set = s;\r\n break;\r\n }\r\n }\r\n if (set == null) {\r\n set = new LinkedHashSet<>();\r\n equalSets.add(set);\r\n }\r\n set.add(in1);\r\n set.add(in2);\r\n } else {\r\n leftNodes.add(rexNode);\r\n }\r\n } else {\r\n leftNodes.add(rexNode);\r\n }\r\n }\r\n return equalSets;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void doPlacementPolicyCheck(Long ledgerId, AsyncCallback.VoidCallback iterCallback, Versioned metadataVer){\r\n LedgerMetadata metadata = metadataVer.getValue();\r\n int writeQuorumSize = metadata.getWriteQuorumSize();\r\n int ackQuorumSize = metadata.getAckQuorumSize();\r\n if (metadata.isClosed()) {\r\n boolean foundSegmentNotAdheringToPlacementPolicy = false;\r\n boolean foundSegmentSoftlyAdheringToPlacementPolicy = false;\r\n for (Map.Entry> ensemble : metadata.getAllEnsembles().entrySet()) {\r\n long startEntryIdOfSegment = ensemble.getKey();\r\n List ensembleOfSegment = ensemble.getValue();\r\n EnsemblePlacementPolicy.PlacementPolicyAdherence segmentAdheringToPlacementPolicy = admin.isEnsembleAdheringToPlacementPolicy(ensembleOfSegment, writeQuorumSize, ackQuorumSize);\r\n if (segmentAdheringToPlacementPolicy == EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL) {\r\n foundSegmentNotAdheringToPlacementPolicy = true;\r\n LOG.warn(\"For ledger: {}, Segment starting at entry: {}, with ensemble: {} having \" + \"writeQuorumSize: {} and ackQuorumSize: {} is not adhering to \" + \"EnsemblePlacementPolicy\", ledgerId, startEntryIdOfSegment, ensembleOfSegment, writeQuorumSize, ackQuorumSize);\r\n } else if (segmentAdheringToPlacementPolicy == EnsemblePlacementPolicy.PlacementPolicyAdherence.MEETS_SOFT) {\r\n foundSegmentSoftlyAdheringToPlacementPolicy = true;\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"For ledger: {}, Segment starting at entry: {}, with ensemble: {}\" + \" having writeQuorumSize: {} and ackQuorumSize: {} is\" + \" softly adhering to EnsemblePlacementPolicy\", ledgerId, startEntryIdOfSegment, ensembleOfSegment, writeQuorumSize, ackQuorumSize);\r\n }\r\n }\r\n }\r\n if (foundSegmentNotAdheringToPlacementPolicy) {\r\n numOfLedgersFoundNotAdheringInPlacementPolicyCheck.incrementAndGet();\r\n if (conf.isRepairedPlacementPolicyNotAdheringBookieEnable()) {\r\n ledgerUnderreplicationManager.markLedgerUnderreplicatedAsync(ledgerId, Collections.emptyList()).whenComplete((res, e) -> {\r\n if (e != null) {\r\n LOG.error(\"For ledger: {}, the placement policy not adhering bookie \" + \"storage, mark it to under replication manager failed.\", ledgerId, e);\r\n return;\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"For ledger: {}, the placement policy not adhering bookie\" + \" storage, mark it to under replication manager\", ledgerId);\r\n }\r\n });\r\n }\r\n } else if (foundSegmentSoftlyAdheringToPlacementPolicy) {\r\n numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck.incrementAndGet();\r\n }\r\n numOfClosedLedgersAuditedInPlacementPolicyCheck.incrementAndGet();\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ledger: {} is not yet closed, so skipping the placementPolicy\" + \"check analysis for now\", ledgerId);\r\n }\r\n }\r\n iterCallback.processResult(BKException.Code.OK, null, null);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic SqlMonotonicity getMonotonicity(SqlOperatorBinding call){\r\n if (getName().equals(\"/\")) {\r\n if (call.isOperandNull(0, true) || call.isOperandNull(1, true)) {\r\n return SqlMonotonicity.CONSTANT;\r\n }\r\n final SqlMonotonicity mono0 = call.getOperandMonotonicity(0);\r\n final SqlMonotonicity mono1 = call.getOperandMonotonicity(1);\r\n if (mono1 == SqlMonotonicity.CONSTANT) {\r\n if (call.isOperandLiteral(1, false)) {\r\n BigDecimal value = call.getOperandLiteralValue(1, BigDecimal.class);\r\n if (value == null) {\r\n return SqlMonotonicity.CONSTANT;\r\n }\r\n switch(value.signum()) {\r\n case -1:\r\n return mono0.reverse().unstrict();\r\n case 0:\r\n return SqlMonotonicity.CONSTANT;\r\n default:\r\n return mono0.unstrict();\r\n }\r\n }\r\n }\r\n }\r\n return super.getMonotonicity(call);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String transformSpecialCharacter(long c){\r\n if (((192 <= c) && (c <= 197)) || (c == 256) || (c == 258) || (c == 260)) {\r\n return \"A\";\r\n }\r\n if (((224 <= c) && (c <= 229)) || (c == 257) || (c == 259) || (c == 261)) {\r\n return \"a\";\r\n }\r\n if ((199 == c) || (262 == c) || (264 == c) || (266 == c) || (268 == c)) {\r\n return \"C\";\r\n }\r\n if ((231 == c) || (263 == c) || (265 == c) || (267 == c) || (269 == c)) {\r\n return \"c\";\r\n }\r\n if ((208 == c) || (272 == c)) {\r\n return \"D\";\r\n }\r\n if ((240 == c) || (273 == c)) {\r\n return \"d\";\r\n }\r\n if (((200 <= c) && (c <= 203)) || (274 == c) || (276 == c) || (278 == c) || (280 == c) || (282 == c)) {\r\n return \"E\";\r\n }\r\n if (((232 <= c) && (c <= 235)) || (275 == c) || (277 == c) || (279 == c) || (281 == c) || (283 == c)) {\r\n return \"e\";\r\n }\r\n if (((284 == c) || (286 == c)) || (288 == c) || (290 == c) || (330 == c)) {\r\n return \"G\";\r\n }\r\n if ((285 == c) || (287 == c) || (289 == c) || (291 == c) || (331 == c)) {\r\n return \"g\";\r\n }\r\n if ((292 == c) || (294 == c)) {\r\n return \"H\";\r\n }\r\n if ((293 == c) || (295 == c)) {\r\n return \"h\";\r\n }\r\n if (((204 <= c) && (c <= 207)) || (296 == c) || (298 == c) || (300 == c) || (302 == c) || (304 == c)) {\r\n return \"I\";\r\n }\r\n if (((236 <= c) && (c <= 239)) || (297 == c) || (299 == c) || (301 == c) || (303 == c)) {\r\n return \"i\";\r\n }\r\n if (308 == c) {\r\n return \"J\";\r\n }\r\n if (309 == c) {\r\n return \"j\";\r\n }\r\n if (310 == c) {\r\n return \"K\";\r\n }\r\n if (311 == c) {\r\n return \"k\";\r\n }\r\n if ((313 == c) || (315 == c) || (319 == c)) {\r\n return \"L\";\r\n }\r\n if ((314 == c) || (316 == c) || (320 == c) || (322 == c)) {\r\n return \"l\";\r\n }\r\n if ((209 == c) || (323 == c) || (325 == c) || (327 == c)) {\r\n return \"N\";\r\n }\r\n if ((241 == c) || (324 == c) || (326 == c) || (328 == c)) {\r\n return \"n\";\r\n }\r\n if (((210 <= c) && (c <= 214)) || (c == 216) || (332 == c) || (334 == c)) {\r\n return \"O\";\r\n }\r\n if (((242 <= c) && (c <= 248) && (247 != c)) || (333 == c) || (335 == c)) {\r\n return \"o\";\r\n }\r\n if ((340 == c) || (342 == c) || (344 == c)) {\r\n return \"R\";\r\n }\r\n if ((341 == c) || (343 == c) || (345 == c)) {\r\n return \"r\";\r\n }\r\n if ((346 == c) || (348 == c) || (350 == c) || (352 == c)) {\r\n return \"S\";\r\n }\r\n if ((347 == c) || (349 == c) || (351 == c) || (353 == c)) {\r\n return \"s\";\r\n }\r\n if ((354 == c) || (356 == c) || (358 == c)) {\r\n return \"T\";\r\n }\r\n if ((355 == c) || (359 == c)) {\r\n return \"t\";\r\n }\r\n if (((217 <= c) && (c <= 220)) || (360 == c) || (362 == c) || (364 == c) || (366 == c) || (370 == c)) {\r\n return \"U\";\r\n }\r\n if (((249 <= c) && (c <= 251)) || (361 == c) || (363 == c) || (365 == c) || (367 == c) || (371 == c)) {\r\n return \"u\";\r\n }\r\n if (372 == c) {\r\n return \"W\";\r\n }\r\n if (373 == c) {\r\n return \"w\";\r\n }\r\n if ((374 == c) || (376 == c) || (221 == c)) {\r\n return \"Y\";\r\n }\r\n if ((375 == c) || (255 == c)) {\r\n return \"y\";\r\n }\r\n if ((377 == c) || (379 == c) || (381 == c)) {\r\n return \"Z\";\r\n }\r\n if ((378 == c) || (380 == c) || (382 == c)) {\r\n return \"z\";\r\n }\r\n if (198 == c) {\r\n return \"AE\";\r\n }\r\n if (230 == c) {\r\n return \"ae\";\r\n }\r\n if (338 == c) {\r\n return \"OE\";\r\n }\r\n if (339 == c) {\r\n return \"oe\";\r\n }\r\n if (222 == c) {\r\n return \"TH\";\r\n }\r\n if (223 == c) {\r\n return \"ss\";\r\n }\r\n if (161 == c) {\r\n return \"!\";\r\n }\r\n return \"?\";\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void cleanUpAltLocs(Structure structure){\r\n for (int i = 0; i < structure.nrModels(); i++) {\r\n for (Chain chain : structure.getModel(i)) {\r\n for (Group group : chain.getAtomGroups()) {\r\n for (Group altLocGroup : group.getAltLocs()) {\r\n for (Atom groupAtom : group.getAtoms()) {\r\n if (!altLocGroup.hasAtom(groupAtom.getName())) {\r\n if (altLocGroup.getPDBName().equals(group.getPDBName())) {\r\n if (!hasDeuteratedEquiv(groupAtom, altLocGroup)) {\r\n altLocGroup.addAtom(groupAtom);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " Boolean compare(QueryResult query1, QueryResult query2){\r\n if (query1.error()) {\r\n exec.signal(query1);\r\n return null;\r\n } else if (query2.error()) {\r\n exec.signal(query2);\r\n return null;\r\n }\r\n if (query1 == null || query2 == null) {\r\n exec.setSqlCode(SqlCodes.ERROR);\r\n return null;\r\n }\r\n boolean equal = true;\r\n tests = 0;\r\n failedTests = 0;\r\n try {\r\n Metadata rm1 = query1.metadata();\r\n Metadata rm2 = query2.metadata();\r\n int cnt1 = rm1.columnCount();\r\n int cnt2 = rm2.columnCount();\r\n tests = cnt1;\r\n while (query1.next() && query2.next()) {\r\n for (int i = 0; i < tests; i++) {\r\n Var v1 = new Var(Var.Type.DERIVED_TYPE);\r\n Var v2 = new Var(Var.Type.DERIVED_TYPE);\r\n v1.setValue(query1, i);\r\n if (i < cnt2) {\r\n v2.setValue(query2, i);\r\n }\r\n boolean e = true;\r\n if (!(v1.isNull() && v2.isNull()) && !v1.equals(v2)) {\r\n equal = false;\r\n e = false;\r\n failedTests++;\r\n }\r\n if (trace || info) {\r\n String m = rm1.columnName(i) + \"\\t\" + v1.toString() + \"\\t\" + v2.toString();\r\n if (!e) {\r\n m += \"\\tNot equal\";\r\n BigDecimal diff = v1.percentDiff(v2);\r\n if (diff != null) {\r\n if (diff.compareTo(BigDecimal.ZERO) != 0) {\r\n m += \", \" + diff + \"% difference\";\r\n failedTestsHighDiff++;\r\n if (diff.compareTo(BigDecimal.TEN) > 0) {\r\n failedTestsHighDiff10++;\r\n }\r\n } else {\r\n m += \", less then 0.01% difference\";\r\n }\r\n } else {\r\n failedTestsHighDiff++;\r\n failedTestsHighDiff10++;\r\n }\r\n }\r\n if (trace) {\r\n trace(null, m);\r\n } else {\r\n info(null, m);\r\n }\r\n }\r\n }\r\n if (equal) {\r\n exec.setSqlSuccess();\r\n } else {\r\n exec.setSqlCode(1);\r\n }\r\n }\r\n } catch (Exception e) {\r\n exec.signal(e);\r\n return null;\r\n }\r\n return Boolean.valueOf(equal);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void validateFrameBoundary(@Nullable SqlNode bound, boolean isRows, @Nullable SqlTypeFamily orderTypeFam, SqlValidator validator, SqlValidatorScope scope){\r\n if (null == bound) {\r\n return;\r\n }\r\n bound.validate(validator, scope);\r\n switch(bound.getKind()) {\r\n case LITERAL:\r\n break;\r\n case OTHER:\r\n case FOLLOWING:\r\n case PRECEDING:\r\n assert bound instanceof SqlCall;\r\n final SqlNode boundVal = ((SqlCall) bound).operand(0);\r\n if (isRows) {\r\n if (boundVal instanceof SqlNumericLiteral) {\r\n final SqlNumericLiteral boundLiteral = (SqlNumericLiteral) boundVal;\r\n if (!boundLiteral.isExact() || (boundLiteral.getScale() != null && boundLiteral.getScale() != 0) || (0 > boundLiteral.longValue(true))) {\r\n throw validator.newValidationError(boundVal, RESOURCE.rowMustBeNonNegativeIntegral());\r\n }\r\n } else {\r\n }\r\n }\r\n if (orderTypeFam != null && !isRows) {\r\n final RelDataType boundType = validator.deriveType(scope, boundVal);\r\n final SqlTypeFamily boundTypeFamily = boundType.getSqlTypeName().getFamily();\r\n final List allowableBoundTypeFamilies = orderTypeFam.allowableDifferenceTypes();\r\n if (allowableBoundTypeFamilies.isEmpty()) {\r\n throw validator.newValidationError(boundVal, RESOURCE.orderByDataTypeProhibitsRange());\r\n }\r\n if (!allowableBoundTypeFamilies.contains(boundTypeFamily)) {\r\n throw validator.newValidationError(boundVal, RESOURCE.orderByRangeMismatch());\r\n }\r\n }\r\n break;\r\n default:\r\n throw new AssertionError(\"Unexpected node type\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Enumerable aggregate(List ops, List> fields, List> sort, List groupBy, List> aggregations, Map mapping, Long offset, Long fetch) throws IOException{\r\n if (!groupBy.isEmpty() && offset != null) {\r\n String message = \"Currently ES doesn't support generic pagination \" + \"with aggregations. You can still use LIMIT keyword (without OFFSET). \" + \"For more details see https://github.com/elastic/elasticsearch/issues/4915\";\r\n throw new IllegalStateException(message);\r\n }\r\n final ObjectNode query = mapper.createObjectNode();\r\n for (String op : ops) {\r\n query.setAll((ObjectNode) mapper.readTree(op));\r\n }\r\n query.put(\"_source\", false);\r\n query.put(\"size\", 0);\r\n query.remove(\"script_fields\");\r\n query.put(\"stored_fields\", \"_none_\");\r\n final Predicate> isCountStar = e -> e.getValue().contains(\"\\\"\" + ElasticsearchConstants.ID + \"\\\"\");\r\n final Set countAll = aggregations.stream().filter(isCountStar).map(Map.Entry::getKey).collect(Collectors.toSet());\r\n final Map fieldMap = new HashMap<>();\r\n final Set orderedGroupBy = new LinkedHashSet<>();\r\n orderedGroupBy.addAll(sort.stream().map(Map.Entry::getKey).collect(Collectors.toList()));\r\n orderedGroupBy.addAll(groupBy);\r\n ObjectNode parent = query.withObject(\"/\" + AGGREGATIONS);\r\n for (String name : orderedGroupBy) {\r\n final String aggName = \"g_\" + name;\r\n fieldMap.put(aggName, name);\r\n final ObjectNode section = parent.withObject(\"/\" + aggName);\r\n final ObjectNode terms = section.withObject(\"/terms\");\r\n terms.put(\"field\", name);\r\n transport.mapping.missingValueFor(name).ifPresent(m -> {\r\n terms.set(\"missing\", m);\r\n });\r\n if (fetch != null) {\r\n terms.put(\"size\", fetch);\r\n }\r\n sort.stream().filter(e -> e.getKey().equals(name)).findAny().ifPresent(s -> terms.withObject(\"/order\").put(\"_key\", s.getValue().isDescending() ? \"desc\" : \"asc\"));\r\n parent = section.withObject(\"/\" + AGGREGATIONS);\r\n }\r\n if (!groupBy.isEmpty() || !aggregations.stream().allMatch(isCountStar)) {\r\n for (Map.Entry aggregation : aggregations) {\r\n JsonNode value = mapper.readTree(aggregation.getValue());\r\n parent.set(aggregation.getKey(), value);\r\n }\r\n }\r\n final Consumer emptyAggRemover = new Consumer() {\r\n\r\n @Override\r\n public void accept(JsonNode node) {\r\n if (!node.has(AGGREGATIONS)) {\r\n node.elements().forEachRemaining(this);\r\n return;\r\n }\r\n JsonNode agg = node.get(AGGREGATIONS);\r\n if (agg.size() == 0) {\r\n ((ObjectNode) node).remove(AGGREGATIONS);\r\n } else {\r\n this.accept(agg);\r\n }\r\n }\r\n };\r\n emptyAggRemover.accept(query);\r\n if (groupBy.isEmpty() && version.elasticVersionMajor() >= ElasticsearchVersion.ES6.elasticVersionMajor()) {\r\n query.put(\"track_total_hits\", true);\r\n }\r\n ElasticsearchJson.Result res = transport.search(Collections.emptyMap()).apply(query);\r\n final List> result = new ArrayList<>();\r\n if (res.aggregations() != null) {\r\n ElasticsearchJson.visitValueNodes(res.aggregations(), m -> {\r\n Map newMap = new LinkedHashMap<>();\r\n for (String key : m.keySet()) {\r\n newMap.put(fieldMap.getOrDefault(key, key), m.get(key));\r\n }\r\n result.add(newMap);\r\n });\r\n } else {\r\n result.add(new LinkedHashMap<>());\r\n }\r\n final long total = res.searchHits().total().value();\r\n if (groupBy.isEmpty()) {\r\n for (String expr : countAll) {\r\n result.forEach(m -> m.put(expr, total));\r\n }\r\n }\r\n final Function1 getter = ElasticsearchEnumerators.getter(fields, ImmutableMap.copyOf(mapping));\r\n ElasticsearchJson.SearchHits hits = new ElasticsearchJson.SearchHits(res.searchHits().total(), result.stream().map(r -> new ElasticsearchJson.SearchHit(\"_id\", r, null)).collect(Collectors.toList()));\r\n return Linq4j.asEnumerable(hits.hits()).select(getter);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List sort(Map> hierarchy){\r\n Node root = new Node<>(null);\r\n Map> map = new HashMap<>();\r\n for (K element : hierarchy.keySet()) {\r\n K key = element;\r\n Node node = map.get(key);\r\n if (node == null) {\r\n node = new Node(key, element);\r\n map.put(key, node);\r\n } else if (node.getData() == null) {\r\n node.setData(element);\r\n }\r\n Collection px = hierarchy.get(key);\r\n if (px.isEmpty()) {\r\n root.addChild(node);\r\n } else {\r\n for (K parentElement : px) {\r\n K superKey = parentElement;\r\n Node superNode = map.get(superKey);\r\n if (superNode == null) {\r\n superNode = new Node<>(superKey);\r\n map.put(superKey, superNode);\r\n }\r\n if (!superNode.children.contains(node)) {\r\n superNode.addChild(node);\r\n }\r\n }\r\n }\r\n }\r\n java.util.Iterator> iter = map.values().iterator();\r\n while (iter.hasNext()) {\r\n Node n = iter.next();\r\n if (n.getData() == null)\r\n root.addChild(n);\r\n }\r\n List sortedList = new java.util.LinkedList<>();\r\n root.accept(sortedList);\r\n return sortedList;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean containsAny(final CharSequence cs, final char... searchChars){\r\n if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {\r\n return false;\r\n }\r\n final int csLength = cs.length();\r\n final int searchLength = searchChars.length;\r\n final int csLast = csLength - 1;\r\n final int searchLast = searchLength - 1;\r\n for (int i = 0; i < csLength; i++) {\r\n final char ch = cs.charAt(i);\r\n for (int j = 0; j < searchLength; j++) {\r\n if (searchChars[j] == ch) {\r\n if (!Character.isHighSurrogate(ch)) {\r\n return true;\r\n }\r\n if (j == searchLast) {\r\n return true;\r\n }\r\n if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void openWithMetadata(Versioned versionedMetadata){\r\n LedgerMetadata metadata = versionedMetadata.getValue();\r\n final byte[] passwd;\r\n DigestType digestType;\r\n if (enableDigestAutodetection && metadata.hasPassword()) {\r\n digestType = fromApiDigestType(metadata.getDigestType());\r\n } else {\r\n digestType = suggestedDigestType;\r\n }\r\n if (administrativeOpen && metadata.hasPassword()) {\r\n passwd = metadata.getPassword();\r\n digestType = fromApiDigestType(metadata.getDigestType());\r\n } else {\r\n passwd = this.passwd;\r\n if (metadata.hasPassword()) {\r\n if (!Arrays.equals(passwd, metadata.getPassword())) {\r\n LOG.error(\"Provided passwd does not match that in metadata\");\r\n openComplete(BKException.Code.UnauthorizedAccessException, null);\r\n return;\r\n }\r\n if (suggestedDigestType != fromApiDigestType(metadata.getDigestType()) && !enableDigestAutodetection) {\r\n LOG.error(\"Provided digest does not match that in metadata\");\r\n openComplete(BKException.Code.DigestMatchException, null);\r\n return;\r\n }\r\n }\r\n }\r\n try {\r\n lh = new ReadOnlyLedgerHandle(bk.getClientCtx(), ledgerId, versionedMetadata, digestType, passwd, !doRecovery);\r\n } catch (GeneralSecurityException e) {\r\n LOG.error(\"Security exception while opening ledger: \" + ledgerId, e);\r\n openComplete(BKException.Code.DigestNotInitializedException, null);\r\n return;\r\n } catch (NumberFormatException e) {\r\n LOG.error(\"Incorrectly entered parameter throttle: \" + bk.getConf().getThrottleValue(), e);\r\n openComplete(BKException.Code.IncorrectParameterException, null);\r\n return;\r\n }\r\n if (metadata.isClosed()) {\r\n openComplete(BKException.Code.OK, lh);\r\n return;\r\n }\r\n if (doRecovery) {\r\n lh.recover(new OrderedGenericCallback(bk.getMainWorkerPool(), ledgerId) {\r\n\r\n @Override\r\n public void safeOperationComplete(int rc, Void result) {\r\n if (rc == BKException.Code.OK) {\r\n openComplete(BKException.Code.OK, lh);\r\n } else if (rc == BKException.Code.UnauthorizedAccessException) {\r\n closeLedgerHandle();\r\n openComplete(BKException.Code.UnauthorizedAccessException, null);\r\n } else {\r\n closeLedgerHandle();\r\n openComplete(bk.getReturnRc(BKException.Code.LedgerRecoveryException), null);\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return String.format(\"Recover(%d)\", ledgerId);\r\n }\r\n });\r\n } else {\r\n lh.asyncReadLastConfirmed(new ReadLastConfirmedCallback() {\r\n\r\n @Override\r\n public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) {\r\n if (rc != BKException.Code.OK) {\r\n closeLedgerHandle();\r\n openComplete(bk.getReturnRc(BKException.Code.ReadException), null);\r\n } else {\r\n lh.lastAddConfirmed = lh.lastAddPushed = lastConfirmed;\r\n openComplete(BKException.Code.OK, lh);\r\n }\r\n }\r\n }, null);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Optional handleRecordHasHttpTypeInclusionField(Map schema, TypeSymbol typeSymbol, OpenAPIComponentMapper componentMapper, RecordTypeSymbol returnRecord, List typeInclusions, Optional customMediaPrefix, Map headers){\r\n ApiResponses apiResponses = new ApiResponses();\r\n ApiResponse apiResponse = new ApiResponse();\r\n io.swagger.v3.oas.models.media.MediaType media = new io.swagger.v3.oas.models.media.MediaType();\r\n boolean isHttpModule = false;\r\n String mediaTypeString;\r\n for (TypeSymbol typeInSymbol : typeInclusions) {\r\n if (HTTP.equals(typeInSymbol.getModule().orElseThrow().getName().orElseThrow())) {\r\n isHttpModule = true;\r\n Optional code = generateApiResponseCode(typeInSymbol.getName().orElseThrow().trim());\r\n if (code.isEmpty()) {\r\n return Optional.empty();\r\n }\r\n Map fieldsOfRecord = returnRecord.fieldDescriptors();\r\n RecordFieldSymbol header = fieldsOfRecord.get(RESPONSE_HEADERS);\r\n extractResponseHeaders(headers, header);\r\n setCacheHeader(headers, apiResponse, code.get());\r\n if (code.get().equals(HTTP_204)) {\r\n apiResponse.description(typeInSymbol.getName().orElseThrow().trim());\r\n apiResponses.put(code.get(), apiResponse);\r\n return Optional.of(apiResponses);\r\n }\r\n RecordFieldSymbol body = fieldsOfRecord.get(BODY);\r\n TypeDescKind typeDescKind = body.typeDescriptor().typeKind();\r\n if (typeDescKind == TypeDescKind.TYPE_REFERENCE) {\r\n componentMapper.createComponentSchema(schema, body.typeDescriptor());\r\n errors.addAll(componentMapper.getDiagnostics());\r\n media.setSchema(new Schema<>().$ref(ConverterCommonUtils.unescapeIdentifier(body.typeDescriptor().getName().orElseThrow().trim())));\r\n mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + JSON_POSTFIX).orElse(APPLICATION_JSON);\r\n apiResponse.content(new Content().addMediaType(mediaTypeString, media));\r\n } else if (typeDescKind == TypeDescKind.STRING) {\r\n media.setSchema(new StringSchema());\r\n mediaTypeString = customMediaPrefix.map(s -> TEXT_PREFIX + s + TEXT_POSTFIX).orElse(MediaType.TEXT_PLAIN);\r\n apiResponse.content(new Content().addMediaType(mediaTypeString, media));\r\n } else if (typeDescKind == TypeDescKind.XML) {\r\n media.setSchema(new ObjectSchema());\r\n mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + XML_POSTFIX).orElse(MediaType.APPLICATION_XML);\r\n apiResponse.content(new Content().addMediaType(mediaTypeString, media));\r\n } else if (typeDescKind == TypeDescKind.MAP && (((MapTypeSymbol) body.typeDescriptor()).typeParam().typeKind() == TypeDescKind.STRING)) {\r\n mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + X_WWW_FORM_URLENCODED_POSTFIX).orElse(MediaType.APPLICATION_FORM_URLENCODED);\r\n Schema objectSchema = new ObjectSchema();\r\n objectSchema.additionalProperties(new StringSchema());\r\n media.setSchema(objectSchema);\r\n apiResponse.content(new Content().addMediaType(mediaTypeString, media));\r\n } else if (typeDescKind == TypeDescKind.UNION) {\r\n UnionTypeSymbol unionType = (UnionTypeSymbol) body.typeDescriptor();\r\n List typeSymbols = unionType.memberTypeDescriptors();\r\n Map contentDetails = new LinkedHashMap<>();\r\n for (TypeSymbol type : typeSymbols) {\r\n ImmutablePair mediaTypes = getMediaTypeForTypeReferenceTypeReturns(type, type.typeKind(), customMediaPrefix);\r\n mediaTypeString = customMediaPrefix.map(s -> APPLICATION_PREFIX + s + mediaTypes.getRight()).orElseGet(mediaTypes::getLeft);\r\n Schema mediaSchema = getOpenApiSchema(type.typeKind().getName());\r\n if (type.typeKind() == TypeDescKind.TYPE_REFERENCE) {\r\n componentMapper.createComponentSchema(schema, type);\r\n errors.addAll(componentMapper.getDiagnostics());\r\n String recordName = type.getName().orElseThrow().trim();\r\n mediaSchema.set$ref(ConverterCommonUtils.unescapeIdentifier(recordName));\r\n }\r\n if (contentDetails.containsKey(mediaTypeString)) {\r\n Schema oldSchema = contentDetails.get(mediaTypeString);\r\n if (oldSchema instanceof ComposedSchema && oldSchema.getOneOf() != null) {\r\n oldSchema.getOneOf().add(mediaSchema);\r\n contentDetails.put(mediaTypeString, oldSchema);\r\n } else {\r\n ComposedSchema composedSchema = new ComposedSchema();\r\n composedSchema.addOneOfItem(oldSchema);\r\n composedSchema.addOneOfItem(mediaSchema);\r\n contentDetails.put(mediaTypeString, composedSchema);\r\n }\r\n } else {\r\n contentDetails.put(mediaTypeString, mediaSchema);\r\n }\r\n }\r\n Content content = new Content();\r\n for (Map.Entry entry : contentDetails.entrySet()) {\r\n io.swagger.v3.oas.models.media.MediaType mediaType = new io.swagger.v3.oas.models.media.MediaType();\r\n mediaTypeString = entry.getKey();\r\n mediaType.setSchema(entry.getValue());\r\n content.addMediaType(mediaTypeString, mediaType);\r\n }\r\n apiResponse.content(content);\r\n }\r\n apiResponse.description(typeInSymbol.getName().orElseThrow().trim());\r\n apiResponses.put(code.get(), apiResponse);\r\n }\r\n }\r\n if (!isHttpModule) {\r\n componentMapper.createComponentSchema(schema, typeSymbol);\r\n errors.addAll(componentMapper.getDiagnostics());\r\n media.setSchema(new Schema<>().$ref(ConverterCommonUtils.unescapeIdentifier(typeSymbol.getName().get())));\r\n mediaTypeString = APPLICATION_JSON;\r\n if (customMediaPrefix.isPresent()) {\r\n mediaTypeString = APPLICATION_PREFIX + customMediaPrefix.get() + JSON_POSTFIX;\r\n }\r\n String statusCode = httpMethod.equals(POST) ? HTTP_201 : HTTP_200;\r\n String description = httpMethod.equals(POST) ? HTTP_201_DESCRIPTION : HTTP_200_DESCRIPTION;\r\n setCacheHeader(headers, apiResponse, statusCode);\r\n apiResponse.content(new Content().addMediaType(mediaTypeString, media));\r\n apiResponse.description(description);\r\n apiResponses.put(statusCode, apiResponse);\r\n }\r\n return Optional.of(apiResponses);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void makePossibleSemiJoins(LoptMultiJoin multiJoin){\r\n possibleSemiJoins.clear();\r\n if (multiJoin.getMultiJoinRel().isFullOuterJoin()) {\r\n return;\r\n }\r\n int nJoinFactors = multiJoin.getNumJoinFactors();\r\n for (int factIdx = 0; factIdx < nJoinFactors; factIdx++) {\r\n final Map> dimFilters = new HashMap<>();\r\n final Map semiJoinMap = new HashMap<>();\r\n for (RexNode joinFilter : multiJoin.getJoinFilters()) {\r\n int dimIdx = isSuitableFilter(multiJoin, joinFilter, factIdx);\r\n if (dimIdx == -1) {\r\n continue;\r\n }\r\n if (multiJoin.isNullGenerating(factIdx) || multiJoin.isNullGenerating(dimIdx)) {\r\n continue;\r\n }\r\n List currDimFilters = dimFilters.get(dimIdx);\r\n if (currDimFilters == null) {\r\n currDimFilters = new ArrayList<>();\r\n }\r\n currDimFilters.add(joinFilter);\r\n dimFilters.put(dimIdx, currDimFilters);\r\n }\r\n Set dimIdxes = dimFilters.keySet();\r\n for (Integer dimIdx : dimIdxes) {\r\n List joinFilters = dimFilters.get(dimIdx);\r\n if (joinFilters != null) {\r\n LogicalJoin semiJoin = findSemiJoinIndexByCost(multiJoin, joinFilters, factIdx, dimIdx);\r\n if (semiJoin != null) {\r\n semiJoinMap.put(dimIdx, semiJoin);\r\n possibleSemiJoins.put(factIdx, semiJoinMap);\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateUpstreamTask(Set allPreTaskCodeSet, long taskCode, long projectCode, long processDefinitionCode, User loginUser){\r\n List hadProcessTaskRelationList = processTaskRelationMapper.queryUpstreamByCode(projectCode, taskCode);\r\n Set removePreTaskSet = new HashSet<>();\r\n List removePreTaskList = new ArrayList<>();\r\n Set addPreTaskSet = new HashSet<>();\r\n List addPreTaskList = new ArrayList<>();\r\n List processTaskRelationLogList = new ArrayList<>();\r\n if (CollectionUtils.isNotEmpty(hadProcessTaskRelationList)) {\r\n for (ProcessTaskRelation processTaskRelation : hadProcessTaskRelationList) {\r\n if (processTaskRelation.getPreTaskCode() == 0) {\r\n continue;\r\n }\r\n if (allPreTaskCodeSet.contains(processTaskRelation.getPreTaskCode())) {\r\n allPreTaskCodeSet.remove(processTaskRelation.getPreTaskCode());\r\n } else {\r\n removePreTaskSet.add(processTaskRelation.getPreTaskCode());\r\n processTaskRelation.setPreTaskCode(0);\r\n processTaskRelation.setPreTaskVersion(0);\r\n removePreTaskList.add(processTaskRelation);\r\n processTaskRelationLogList.add(createProcessTaskRelationLog(loginUser, processTaskRelation));\r\n }\r\n }\r\n }\r\n if (allPreTaskCodeSet.size() != 0) {\r\n addPreTaskSet.addAll(allPreTaskCodeSet);\r\n }\r\n allPreTaskCodeSet.add(Long.valueOf(taskCode));\r\n List taskDefinitionList = taskDefinitionMapper.queryByCodeList(allPreTaskCodeSet);\r\n Map taskCodeMap = taskDefinitionList.stream().collect(Collectors.toMap(TaskDefinition::getCode, Function.identity(), (a, b) -> a));\r\n ProcessDefinition processDefinition = processDefinitionMapper.queryByCode(processDefinitionCode);\r\n TaskDefinition taskDefinition = taskCodeMap.get(taskCode);\r\n for (Long preTaskCode : addPreTaskSet) {\r\n TaskDefinition preTaskRelation = taskCodeMap.get(preTaskCode);\r\n ProcessTaskRelation processTaskRelation = new ProcessTaskRelation(null, processDefinition.getVersion(), projectCode, processDefinition.getCode(), preTaskRelation.getCode(), preTaskRelation.getVersion(), taskDefinition.getCode(), taskDefinition.getVersion(), ConditionType.NONE, \"{}\");\r\n addPreTaskList.add(processTaskRelation);\r\n processTaskRelationLogList.add(createProcessTaskRelationLog(loginUser, processTaskRelation));\r\n }\r\n int insert = 0;\r\n int remove = 0;\r\n int log = 0;\r\n if (CollectionUtils.isNotEmpty(addPreTaskList)) {\r\n insert = processTaskRelationMapper.batchInsert(addPreTaskList);\r\n }\r\n if (CollectionUtils.isNotEmpty(removePreTaskList)) {\r\n for (ProcessTaskRelation processTaskRelation : removePreTaskList) {\r\n remove += processTaskRelationMapper.updateById(processTaskRelation);\r\n }\r\n }\r\n if (CollectionUtils.isNotEmpty(processTaskRelationLogList)) {\r\n log = processTaskRelationLogDao.batchInsert(processTaskRelationLogList);\r\n }\r\n if (insert + remove != log) {\r\n throw new RuntimeException(\"updateUpstreamTask error\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic RelNode visit(RelNode relNode){\r\n if (relNode instanceof Aggregate) {\r\n final Aggregate agg = (Aggregate) relNode;\r\n return relBuilder.push(visit(agg.getInput())).aggregate(relBuilder.groupKey(agg.getGroupSet(), agg.groupSets), agg.getAggCallList()).build();\r\n }\r\n if (relNode instanceof TableScan) {\r\n return visit((TableScan) relNode);\r\n }\r\n if (relNode instanceof Filter) {\r\n final Filter filter = (Filter) relNode;\r\n return relBuilder.push(visit(filter.getInput())).filter(filter.getCondition()).build();\r\n }\r\n if (relNode instanceof Project) {\r\n final Project project = (Project) relNode;\r\n return relBuilder.push(visit(project.getInput())).project(project.getProjects(), project.getRowType().getFieldNames()).build();\r\n }\r\n if (relNode instanceof Union) {\r\n final Union union = (Union) relNode;\r\n for (RelNode rel : union.getInputs()) {\r\n relBuilder.push(visit(rel));\r\n }\r\n return relBuilder.union(union.all, union.getInputs().size()).build();\r\n }\r\n if (relNode instanceof Intersect) {\r\n final Intersect intersect = (Intersect) relNode;\r\n for (RelNode rel : intersect.getInputs()) {\r\n relBuilder.push(visit(rel));\r\n }\r\n return relBuilder.intersect(intersect.all, intersect.getInputs().size()).build();\r\n }\r\n if (relNode instanceof Minus) {\r\n final Minus minus = (Minus) relNode;\r\n for (RelNode rel : minus.getInputs()) {\r\n relBuilder.push(visit(rel));\r\n }\r\n return relBuilder.minus(minus.all, minus.getInputs().size()).build();\r\n }\r\n if (relNode instanceof Join) {\r\n final Join join = (Join) relNode;\r\n return relBuilder.push(visit(join.getLeft())).push(visit(join.getRight())).join(join.getJoinType(), join.getCondition()).build();\r\n }\r\n if (relNode instanceof Correlate) {\r\n final Correlate corr = (Correlate) relNode;\r\n return relBuilder.push(visit(corr.getLeft())).push(visit(corr.getRight())).join(corr.getJoinType(), relBuilder.literal(true), corr.getVariablesSet()).build();\r\n }\r\n if (relNode instanceof Values) {\r\n final Values values = (Values) relNode;\r\n return relBuilder.values(values.tuples, values.getRowType()).build();\r\n }\r\n if (relNode instanceof Sort) {\r\n final Sort sort = (Sort) relNode;\r\n return LogicalSort.create(visit(sort.getInput()), sort.getCollation(), sort.offset, sort.fetch);\r\n }\r\n if (relNode instanceof Window) {\r\n final Window window = (Window) relNode;\r\n final RelNode input = visit(window.getInput());\r\n return LogicalWindow.create(input.getTraitSet(), input, window.constants, window.getRowType(), window.groups);\r\n }\r\n if (relNode instanceof Calc) {\r\n final Calc calc = (Calc) relNode;\r\n return LogicalCalc.create(visit(calc.getInput()), calc.getProgram());\r\n }\r\n if (relNode instanceof TableModify) {\r\n final TableModify tableModify = (TableModify) relNode;\r\n final RelNode input = visit(tableModify.getInput());\r\n return LogicalTableModify.create(tableModify.getTable(), tableModify.getCatalogReader(), input, tableModify.getOperation(), tableModify.getUpdateColumnList(), tableModify.getSourceExpressionList(), tableModify.isFlattened());\r\n }\r\n if (relNode instanceof EnumerableInterpreter || relNode instanceof JdbcToEnumerableConverter) {\r\n return visit(((SingleRel) relNode).getInput());\r\n }\r\n if (relNode instanceof EnumerableLimit) {\r\n final EnumerableLimit limit = (EnumerableLimit) relNode;\r\n RelNode logicalInput = visit(limit.getInput());\r\n RelCollation collation = RelCollations.of();\r\n if (logicalInput instanceof Sort) {\r\n collation = ((Sort) logicalInput).collation;\r\n logicalInput = ((Sort) logicalInput).getInput();\r\n }\r\n return LogicalSort.create(logicalInput, collation, limit.offset, limit.fetch);\r\n }\r\n if (relNode instanceof Uncollect) {\r\n final Uncollect uncollect = (Uncollect) relNode;\r\n final RelNode input = visit(uncollect.getInput());\r\n return Uncollect.create(input.getTraitSet(), input, uncollect.withOrdinality, Collections.emptyList());\r\n }\r\n throw new AssertionError(\"Need to implement logical converter for \" + relNode.getClass().getName());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized TSStatus extendSchemaTemplate(TemplateExtendInfo templateExtendInfo){\r\n if (templateExtendInfo.getEncodings() != null) {\r\n for (int i = 0; i < templateExtendInfo.getDataTypes().size(); i++) {\r\n try {\r\n SchemaUtils.checkDataTypeWithEncoding(templateExtendInfo.getDataTypes().get(i), templateExtendInfo.getEncodings().get(i));\r\n } catch (MetadataException e) {\r\n return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());\r\n }\r\n }\r\n }\r\n TemplateInfoResp resp = clusterSchemaInfo.getTemplate(new GetSchemaTemplatePlan(templateExtendInfo.getTemplateName()));\r\n if (resp.getStatus().getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {\r\n return resp.getStatus();\r\n }\r\n Template template = resp.getTemplateList().get(0);\r\n List intersectionMeasurements = templateExtendInfo.updateAsDifferenceAndGetIntersection(template.getSchemaMap().keySet());\r\n if (templateExtendInfo.isEmpty()) {\r\n if (intersectionMeasurements.isEmpty()) {\r\n return RpcUtils.SUCCESS_STATUS;\r\n } else {\r\n return RpcUtils.getStatus(TSStatusCode.MEASUREMENT_ALREADY_EXISTS_IN_TEMPLATE, String.format(\"Measurement %s already exist in schemaengine template %s\", intersectionMeasurements, template.getName()));\r\n }\r\n }\r\n ExtendSchemaTemplatePlan extendSchemaTemplatePlan = new ExtendSchemaTemplatePlan(templateExtendInfo);\r\n TSStatus status;\r\n try {\r\n status = getConsensusManager().write(extendSchemaTemplatePlan);\r\n } catch (ConsensusException e) {\r\n LOGGER.warn(CONSENSUS_WRITE_ERROR, e);\r\n status = new TSStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode());\r\n status.setMessage(e.getMessage());\r\n }\r\n if (status.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {\r\n return status;\r\n }\r\n template = clusterSchemaInfo.getTemplate(new GetSchemaTemplatePlan(templateExtendInfo.getTemplateName())).getTemplateList().get(0);\r\n TUpdateTemplateReq updateTemplateReq = new TUpdateTemplateReq();\r\n updateTemplateReq.setType(TemplateInternalRPCUpdateType.UPDATE_TEMPLATE_INFO.toByte());\r\n updateTemplateReq.setTemplateInfo(TemplateInternalRPCUtil.generateUpdateTemplateInfoBytes(template));\r\n Map dataNodeLocationMap = configManager.getNodeManager().getRegisteredDataNodeLocations();\r\n AsyncClientHandler clientHandler = new AsyncClientHandler<>(DataNodeRequestType.UPDATE_TEMPLATE, updateTemplateReq, dataNodeLocationMap);\r\n AsyncDataNodeClientPool.getInstance().sendAsyncRequestToDataNodeWithRetry(clientHandler);\r\n Map statusMap = clientHandler.getResponseMap();\r\n for (Map.Entry entry : statusMap.entrySet()) {\r\n if (entry.getValue().getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {\r\n LOGGER.warn(\"Failed to sync template {} extension info to DataNode {}\", template.getName(), dataNodeLocationMap.get(entry.getKey()));\r\n return RpcUtils.getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR, String.format(\"Failed to sync template %s extension info to DataNode %s\", template.getName(), dataNodeLocationMap.get(entry.getKey())));\r\n }\r\n }\r\n if (intersectionMeasurements.isEmpty()) {\r\n return RpcUtils.SUCCESS_STATUS;\r\n } else {\r\n return RpcUtils.getStatus(TSStatusCode.MEASUREMENT_ALREADY_EXISTS_IN_TEMPLATE, String.format(\"Measurement %s already exist in schemaengine template %s\", intersectionMeasurements, template.getName()));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected ExpressionEvaluatorResult verifyObject(ObjectNode json, Object resultRaw){\r\n if (resultRaw == null) {\r\n return ExpressionEvaluatorResult.of(isObjectEmpty(json));\r\n }\r\n Iterator> fields = json.fields();\r\n while (fields.hasNext()) {\r\n Map.Entry element = fields.next();\r\n String key = element.getKey();\r\n JsonNode jsonNode = element.getValue();\r\n Object fieldValue = extractFieldValue(resultRaw, key);\r\n Class fieldClass = fieldValue != null ? fieldValue.getClass() : null;\r\n ExpressionEvaluatorResult evaluatorResult = ExpressionEvaluatorResult.ofFailed();\r\n if (isSimpleTypeNode(jsonNode)) {\r\n String nodeValue = getSimpleTypeNodeTextValue(jsonNode);\r\n if (!internalUnaryEvaluation(nodeValue, fieldValue, fieldClass, true)) {\r\n evaluatorResult.setWrongValue(nodeValue);\r\n evaluatorResult.addMapItemStepToPath(key);\r\n return evaluatorResult;\r\n }\r\n } else if (jsonNode.isArray()) {\r\n evaluatorResult = verifyList((ArrayNode) jsonNode, (List) fieldValue);\r\n if (!evaluatorResult.isSuccessful()) {\r\n evaluatorResult.addMapItemStepToPath(key);\r\n return evaluatorResult;\r\n }\r\n } else if (jsonNode.isObject()) {\r\n evaluatorResult = verifyObject((ObjectNode) jsonNode, fieldValue);\r\n if (!evaluatorResult.isSuccessful()) {\r\n if (resultRaw instanceof Map) {\r\n evaluatorResult.addMapItemStepToPath(key);\r\n } else {\r\n evaluatorResult.addFieldItemStepToPath(key);\r\n }\r\n return evaluatorResult;\r\n }\r\n } else {\r\n if (!internalUnaryEvaluation(jsonNode.textValue(), fieldValue, fieldClass, true)) {\r\n return ExpressionEvaluatorResult.ofFailed(jsonNode.textValue(), key);\r\n }\r\n }\r\n }\r\n return ExpressionEvaluatorResult.ofSuccessful();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Expression createParameterUnmarshalExpressionForAnnotation(Method method, Class parameterType, Annotation annotation){\r\n if (annotation instanceof ExchangeProperty) {\r\n ExchangeProperty propertyAnnotation = (ExchangeProperty) annotation;\r\n return ExpressionBuilder.exchangePropertyExpression(propertyAnnotation.value());\r\n } else if (annotation instanceof ExchangeProperties) {\r\n return ExpressionBuilder.exchangePropertiesExpression();\r\n } else if (annotation instanceof Header) {\r\n Header headerAnnotation = (Header) annotation;\r\n return ExpressionBuilder.headerExpression(headerAnnotation.value());\r\n } else if (annotation instanceof Headers) {\r\n return ExpressionBuilder.headersExpression();\r\n } else if (annotation instanceof ExchangeException) {\r\n return ExpressionBuilder.exchangeExceptionExpression(CastUtils.cast(parameterType, Exception.class));\r\n } else if (annotation instanceof PropertyInject) {\r\n PropertyInject propertyAnnotation = (PropertyInject) annotation;\r\n Expression inject = ExpressionBuilder.propertiesComponentExpression(propertyAnnotation.value(), propertyAnnotation.defaultValue());\r\n return ExpressionBuilder.convertToExpression(inject, parameterType);\r\n } else {\r\n LanguageAnnotation languageAnnotation = annotation.annotationType().getAnnotation(LanguageAnnotation.class);\r\n if (languageAnnotation != null) {\r\n Class type = languageAnnotation.factory();\r\n if (type == Object.class) {\r\n type = DefaultAnnotationExpressionFactory.class;\r\n }\r\n Object object = camelContext.getInjector().newInstance(type);\r\n if (object instanceof AnnotationExpressionFactory) {\r\n AnnotationExpressionFactory expressionFactory = (AnnotationExpressionFactory) object;\r\n return expressionFactory.createExpression(camelContext, annotation, languageAnnotation, parameterType);\r\n } else {\r\n LOG.warn(\"Ignoring bad annotation: {} on method: {} which declares a factory {} which does not implement {}\", languageAnnotation, method, type.getName(), AnnotationExpressionFactory.class.getName());\r\n }\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void handleCache(Node node){\r\n BeanDefinitionBuilder cacheConfigBuilder = createBeanBuilder(CacheSimpleConfig.class);\r\n Node attName = node.getAttributes().getNamedItem(\"name\");\r\n String name = getTextContent(attName);\r\n fillAttributeValues(node, cacheConfigBuilder);\r\n for (Node childNode : childElements(node)) {\r\n String nodeName = cleanNodeName(childNode);\r\n if (\"eviction\".equals(nodeName)) {\r\n cacheConfigBuilder.addPropertyValue(\"evictionConfig\", getEvictionConfig(childNode, false, false));\r\n } else if (\"expiry-policy-factory\".equals(cleanNodeName(childNode))) {\r\n cacheConfigBuilder.addPropertyValue(\"expiryPolicyFactoryConfig\", getExpiryPolicyFactoryConfig(childNode));\r\n } else if (\"cache-entry-listeners\".equals(nodeName)) {\r\n ManagedList listeners = new ManagedList<>();\r\n for (Node listenerNode : childElements(childNode)) {\r\n BeanDefinitionBuilder listenerConfBuilder = createBeanBuilder(CacheSimpleEntryListenerConfig.class);\r\n fillAttributeValues(listenerNode, listenerConfBuilder);\r\n listeners.add(listenerConfBuilder.getBeanDefinition());\r\n }\r\n cacheConfigBuilder.addPropertyValue(\"cacheEntryListeners\", listeners);\r\n } else if (\"wan-replication-ref\".equals(nodeName)) {\r\n handleWanReplicationRef(cacheConfigBuilder, childNode);\r\n } else if (\"partition-lost-listeners\".equals(nodeName)) {\r\n ManagedList listeners = parseListeners(childNode, CachePartitionLostListenerConfig.class);\r\n cacheConfigBuilder.addPropertyValue(\"partitionLostListenerConfigs\", listeners);\r\n } else if (\"split-brain-protection-ref\".equals(nodeName)) {\r\n cacheConfigBuilder.addPropertyValue(\"splitBrainProtectionName\", getTextContent(childNode));\r\n } else if (\"merge-policy\".equals(nodeName)) {\r\n handleMergePolicyConfig(childNode, cacheConfigBuilder);\r\n } else if (\"hot-restart\".equals(nodeName)) {\r\n handleHotRestartConfig(cacheConfigBuilder, childNode);\r\n } else if (\"data-persistence\".equals(nodeName)) {\r\n handleDataPersistenceConfig(cacheConfigBuilder, childNode);\r\n } else if (\"event-journal\".equals(nodeName)) {\r\n handleEventJournalConfig(cacheConfigBuilder, childNode);\r\n } else if (\"merkle-tree\".equals(nodeName)) {\r\n handleMerkleTreeConfig(cacheConfigBuilder, childNode);\r\n }\r\n }\r\n cacheConfigManagedMap.put(name, cacheConfigBuilder.getBeanDefinition());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean isValid(Litmus litmus){\r\n RelNode root = getRoot();\r\n if (root == null) {\r\n return true;\r\n }\r\n RelMetadataQuery metaQuery = root.getCluster().getMetadataQuerySupplier().get();\r\n for (RelSet set : allSets) {\r\n if (set.equivalentSet != null) {\r\n return litmus.fail(\"set [{}] has been merged: it should not be in the list\", set);\r\n }\r\n for (RelSubset subset : set.subsets) {\r\n if (subset.set != set) {\r\n return litmus.fail(\"subset [{}] is in wrong set [{}]\", subset, set);\r\n }\r\n if (subset.best != null) {\r\n if (!subset.set.rels.contains(subset.best)) {\r\n return litmus.fail(\"RelSubset [{}] does not contain its best RelNode [{}]\", subset, subset.best);\r\n }\r\n try {\r\n RelOptCost bestCost = getCostOrInfinite(subset.best, metaQuery);\r\n if (!subset.bestCost.equals(bestCost)) {\r\n return litmus.fail(\"RelSubset [\" + subset + \"] has wrong best cost \" + subset.bestCost + \". Correct cost is \" + bestCost);\r\n }\r\n } catch (CyclicMetadataException e) {\r\n }\r\n }\r\n for (RelNode rel : subset.getRels()) {\r\n try {\r\n RelOptCost relCost = getCost(rel, metaQuery);\r\n if (relCost != null && relCost.isLt(subset.bestCost)) {\r\n return litmus.fail(\"rel [{}] has lower cost {} than \" + \"best cost {} of subset [{}]\", rel, relCost, subset.bestCost, subset);\r\n }\r\n } catch (CyclicMetadataException e) {\r\n }\r\n }\r\n }\r\n }\r\n return litmus.succeed();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String removeComments(String line, int[] startQuote){\r\n if (line == null || line.isEmpty()) {\r\n return line;\r\n }\r\n if (startQuote[0] == -1 && isComment(line)) {\r\n return \"\";\r\n }\r\n StringBuilder builder = new StringBuilder();\r\n for (int index = 0; index < line.length(); ) {\r\n if (startQuote[0] == -1 && index < line.length() - 1 && line.charAt(index) == '-' && line.charAt(index + 1) == '-') {\r\n for (; index < line.length() && line.charAt(index) != '\\n'; ++index) ;\r\n continue;\r\n }\r\n char letter = line.charAt(index);\r\n if (startQuote[0] == letter && (index == 0 || line.charAt(index - 1) != '\\\\')) {\r\n startQuote[0] = -1;\r\n } else if (startQuote[0] == -1 && (letter == '\\'' || letter == '\"') && (index == 0 || line.charAt(index - 1) != '\\\\')) {\r\n startQuote[0] = letter;\r\n }\r\n builder.append(letter);\r\n index++;\r\n }\r\n return builder.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean listOrDeleteCookies(ServerConfiguration bkConf, boolean delete, boolean force) throws Exception{\r\n BookieId bookieAddress = BookieImpl.getBookieId(bkConf);\r\n File[] journalDirs = bkConf.getJournalDirs();\r\n File[] ledgerDirs = bkConf.getLedgerDirs();\r\n File[] indexDirs = bkConf.getIndexDirs();\r\n File[] allDirs = ArrayUtils.addAll(journalDirs, ledgerDirs);\r\n if (indexDirs != null) {\r\n allDirs = ArrayUtils.addAll(allDirs, indexDirs);\r\n }\r\n File[] allCurDirs = BookieImpl.getCurrentDirectories(allDirs);\r\n List allVersionFiles = new LinkedList();\r\n File versionFile;\r\n for (File curDir : allCurDirs) {\r\n versionFile = new File(curDir, BookKeeperConstants.VERSION_FILENAME);\r\n if (versionFile.exists()) {\r\n allVersionFiles.add(versionFile);\r\n }\r\n }\r\n if (!allVersionFiles.isEmpty()) {\r\n if (delete) {\r\n boolean confirm = force;\r\n if (!confirm) {\r\n confirm = IOUtils.confirmPrompt(\"Are you sure you want to delete Cookies locally?\");\r\n }\r\n if (confirm) {\r\n for (File verFile : allVersionFiles) {\r\n if (!verFile.delete()) {\r\n LOG.error(\"Failed to delete Local cookie file {}. So aborting deletecookie of Bookie: {}\", verFile, bookieAddress);\r\n return false;\r\n }\r\n }\r\n LOG.info(\"Deleted Local Cookies of Bookie: {}\", bookieAddress);\r\n } else {\r\n LOG.info(\"Skipping deleting local Cookies of Bookie: {}\", bookieAddress);\r\n }\r\n } else {\r\n LOG.info(\"Listing local Cookie Files of Bookie: {}\", bookieAddress);\r\n for (File verFile : allVersionFiles) {\r\n LOG.info(verFile.getCanonicalPath());\r\n }\r\n }\r\n } else {\r\n LOG.info(\"No local cookies for Bookie: {}\", bookieAddress);\r\n }\r\n return runFunctionWithRegistrationManager(bkConf, rm -> {\r\n try {\r\n Versioned cookie = null;\r\n try {\r\n cookie = Cookie.readFromRegistrationManager(rm, bookieAddress);\r\n } catch (BookieException.CookieNotFoundException nne) {\r\n LOG.info(\"No cookie for {} in metadata store\", bookieAddress);\r\n return true;\r\n }\r\n if (delete) {\r\n boolean confirm = force;\r\n if (!confirm) {\r\n confirm = IOUtils.confirmPrompt(\"Are you sure you want to delete Cookies from metadata store?\");\r\n }\r\n if (confirm) {\r\n cookie.getValue().deleteFromRegistrationManager(rm, bkConf, cookie.getVersion());\r\n LOG.info(\"Deleted Cookie from metadata store for Bookie: {}\", bookieAddress);\r\n } else {\r\n LOG.info(\"Skipping deleting cookie from metadata store for Bookie: {}\", bookieAddress);\r\n }\r\n }\r\n } catch (BookieException | IOException e) {\r\n return false;\r\n }\r\n return true;\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean cacheTime() throws IOException, QueryProcessException{\r\n boolean isFirstConstant = firstPointReader.isConstantPointReader();\r\n boolean isSecondConstant = secondPointReader.isConstantPointReader();\r\n boolean isThirdConstant = thirdPointReader.isConstantPointReader();\r\n long firstTime = isFirstConstant ? Long.MIN_VALUE : firstPointReader.currentTime();\r\n long secondTime = isSecondConstant ? Long.MIN_VALUE : secondPointReader.currentTime();\r\n long thirdTime = isThirdConstant ? Long.MIN_VALUE : secondPointReader.currentTime();\r\n while (firstTime != secondTime || firstTime != thirdTime) {\r\n if (firstTime < secondTime) {\r\n if (isFirstConstant) {\r\n firstTime = secondTime;\r\n } else {\r\n firstPointReader.readyForNext();\r\n if (!firstPointReader.next()) {\r\n return false;\r\n }\r\n firstTime = firstPointReader.currentTime();\r\n }\r\n } else if (secondTime < thirdTime) {\r\n if (isSecondConstant) {\r\n secondTime = thirdTime;\r\n } else {\r\n secondPointReader.readyForNext();\r\n if (!secondPointReader.next()) {\r\n return false;\r\n }\r\n secondTime = secondPointReader.currentTime();\r\n }\r\n } else {\r\n if (isThirdConstant) {\r\n thirdTime = firstTime;\r\n } else {\r\n thirdPointReader.readyForNext();\r\n if (!thirdPointReader.next()) {\r\n return false;\r\n }\r\n thirdTime = secondPointReader.currentTime();\r\n }\r\n }\r\n }\r\n if (firstTime != Long.MIN_VALUE) {\r\n cachedTime = firstTime;\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void writeObject(JsonGenerator jg, Object value) throws IOException{\r\n if (value == null) {\r\n jg.writeNull();\r\n } else {\r\n Class c = value.getClass();\r\n if (c.isArray()) {\r\n jg.writeStartArray();\r\n int len = Array.getLength(value);\r\n for (int j = 0; j < len; j++) {\r\n Object item = Array.get(value, j);\r\n writeObject(jg, item);\r\n }\r\n jg.writeEndArray();\r\n } else if (value instanceof Number) {\r\n Number n = (Number) value;\r\n jg.writeNumber(n.toString());\r\n } else if (value instanceof Boolean) {\r\n Boolean b = (Boolean) value;\r\n jg.writeBoolean(b);\r\n } else if (value instanceof CompositeData) {\r\n CompositeData cds = (CompositeData) value;\r\n CompositeType comp = cds.getCompositeType();\r\n Set keys = comp.keySet();\r\n jg.writeStartObject();\r\n for (String key : keys) {\r\n writeAttribute(jg, key, cds.get(key));\r\n }\r\n jg.writeEndObject();\r\n } else if (value instanceof TabularData) {\r\n TabularData tds = (TabularData) value;\r\n jg.writeStartArray();\r\n for (Object entry : tds.values()) {\r\n writeObject(jg, entry);\r\n }\r\n jg.writeEndArray();\r\n } else {\r\n jg.writeString(value.toString());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void populateDefinitionFromClass(ClassDefinition def, Resource resource, Class concrete, boolean asTrait){\r\n try {\r\n def.setClassName(concrete.getName());\r\n if (concrete.getSuperclass() != null) {\r\n def.setSuperClass(concrete.getSuperclass().getName());\r\n }\r\n ClassFieldInspector inspector = CoreComponentsBuilder.get().createClassFieldInspector(concrete);\r\n Map methods = inspector.getGetterMethods();\r\n Map setters = inspector.getSetterMethods();\r\n Map fields = new HashMap<>();\r\n for (String fieldName : methods.keySet()) {\r\n if (asTrait && (\"core\".equals(fieldName) || \"fields\".equals(fieldName))) {\r\n continue;\r\n }\r\n if (!inspector.isNonGetter(fieldName) && setters.containsKey(fieldName)) {\r\n Position position = null;\r\n if (!concrete.isInterface()) {\r\n try {\r\n Field fld = concrete.getDeclaredField(fieldName);\r\n position = fld.getAnnotation(Position.class);\r\n } catch (NoSuchFieldException nsfe) {\r\n }\r\n }\r\n Class ret = methods.get(fieldName).getReturnType();\r\n TypeFieldDescr field = new TypeFieldDescr();\r\n field.setResource(resource);\r\n field.setFieldName(fieldName);\r\n field.setPattern(new PatternDescr(ret.getName()));\r\n field.setIndex(position != null ? position.value() : -1);\r\n fields.put(fieldName, field);\r\n }\r\n }\r\n if (!fields.isEmpty()) {\r\n List fieldDefs = sortFields(fields, null, null, null);\r\n int i = 0;\r\n for (FieldDefinition fieldDef : fieldDefs) {\r\n fieldDef.setIndex(i++);\r\n def.addField(fieldDef);\r\n }\r\n }\r\n Set interfaces = new HashSet<>();\r\n Collections.addAll(interfaces, def.getInterfaces());\r\n for (Class iKlass : ClassUtils.getAllImplementedInterfaceNames(concrete)) {\r\n interfaces.add(iKlass.getName());\r\n }\r\n def.setInterfaces(interfaces.toArray(new String[interfaces.size()]));\r\n def.setDefinedClass(concrete);\r\n } catch (IOException e) {\r\n LOG.error(\"Exception\", e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void enumerative(EnumDeclarationDescrBuilder declare){\r\n EnumLiteralDescrBuilder literal = null;\r\n String lit = null;\r\n try {\r\n Token enumLit = match(input, DRL5Lexer.ID, null, null, DroolsEditorType.IDENTIFIER);\r\n lit = enumLit.getText();\r\n if (state.failed)\r\n return;\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n }\r\n try {\r\n literal = helper.start(declare, EnumLiteralDescrBuilder.class, lit);\r\n if (input.LA(1) == DRL5Lexer.LEFT_PAREN) {\r\n match(input, DRL5Lexer.LEFT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n boolean more;\r\n do {\r\n int first = input.index();\r\n exprParser.conditionalExpression();\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0 && input.index() > first) {\r\n String arg = input.toString(first, input.LT(-1).getTokenIndex());\r\n literal.constructorArg(arg);\r\n }\r\n more = input.LA(1) == DRL5Lexer.COMMA;\r\n if (more) {\r\n match(input, DRL5Lexer.COMMA, null, null, DroolsEditorType.SYMBOL);\r\n }\r\n } while (more);\r\n match(input, DRL5Lexer.RIGHT_PAREN, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n }\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n } finally {\r\n helper.end(FieldDescrBuilder.class, literal);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static UriInfoWithType parseUri(Edm edm, String resourcePath, Map queryParams){\r\n UriInfoWithType result;\r\n try {\r\n final List pathSegments = new ArrayList<>();\r\n final String[] segments = new URI(resourcePath).getPath().split(SEPARATOR);\r\n if (queryParams == null) {\r\n queryParams = Collections.emptyMap();\r\n }\r\n for (String segment : segments) {\r\n if (segment.indexOf(';') == -1) {\r\n pathSegments.add(new ODataPathSegmentImpl(segment, null));\r\n } else {\r\n final String[] splitSegment = segment.split(\";\");\r\n segment = splitSegment[0];\r\n Map> matrixParams = new HashMap<>();\r\n for (int i = 1; i < splitSegment.length; i++) {\r\n final String[] param = splitSegment[i].split(\"=\");\r\n List values = matrixParams.get(param[0]);\r\n if (values == null) {\r\n values = new ArrayList<>();\r\n matrixParams.put(param[0], values);\r\n }\r\n if (param[1].indexOf(',') == -1) {\r\n values.add(param[1]);\r\n } else {\r\n values.addAll(Arrays.asList(param[1].split(\",\")));\r\n }\r\n }\r\n pathSegments.add(new ODataPathSegmentImpl(segment, matrixParams));\r\n }\r\n }\r\n result = new UriInfoWithType(UriParser.parse(edm, pathSegments, queryParams), resourcePath);\r\n } catch (URISyntaxException | ODataException e) {\r\n throw new IllegalArgumentException(\"resourcePath: \" + e.getMessage(), e);\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ScannableTable eval(boolean b){\r\n return new ScannableTable() {\r\n\r\n @Override\r\n public Enumerable<@Nullable Object[]> scan(DataContext root) {\r\n JavaTypeFactory typeFactory = root.getTypeFactory();\r\n final RelDataType rowType = getRowType(typeFactory);\r\n final List fieldNames = ImmutableList.copyOf(rowType.getFieldNames());\r\n final String[] args;\r\n final String osName = System.getProperty(\"os.name\");\r\n final String osVersion = System.getProperty(\"os.version\");\r\n Util.discard(osVersion);\r\n switch(osName) {\r\n case \"Mac OS X\":\r\n args = new String[] { \"ps\", \"ax\", \"-o\", \"ppid=,pid=,pgid=,tpgid=,stat=,\" + \"user=,pcpu=,pmem=,vsz=,rss=,tty=,start=,time=,uid=,ruid=,\" + \"sess=,comm=\" };\r\n break;\r\n default:\r\n args = new String[] { \"ps\", \"--no-headers\", \"axo\", \"ppid,pid,pgrp,\" + \"tpgid,stat,user,pcpu,pmem,vsz,rss,tty,start_time,time,euid,\" + \"ruid,sess,comm\" };\r\n }\r\n return Processes.processLines(args).select(new Function1() {\r\n\r\n @Override\r\n public Object[] apply(String line) {\r\n final String[] fields = line.trim().split(\" +\");\r\n final Object[] values = new Object[fieldNames.size()];\r\n for (int i = 0; i < values.length; i++) {\r\n try {\r\n values[i] = field(fieldNames.get(i), fields[i]);\r\n } catch (RuntimeException e) {\r\n throw new RuntimeException(\"while parsing value [\" + fields[i] + \"] of field [\" + fieldNames.get(i) + \"] in line [\" + line + \"]\");\r\n }\r\n }\r\n return values;\r\n }\r\n\r\n private Object field(String field, String value) {\r\n switch(field) {\r\n case \"pid\":\r\n case \"ppid\":\r\n case \"pgrp\":\r\n case \"pgid\":\r\n case \"tpgid\":\r\n return Integer.valueOf(value);\r\n case \"pcpu\":\r\n case \"pmem\":\r\n return (int) (Float.valueOf(value) * 10f);\r\n case \"time\":\r\n final Matcher m1 = MINUTE_SECOND_MILLIS_PATTERN.matcher(value);\r\n if (m1.matches()) {\r\n final long h = Long.parseLong(m1.group(1));\r\n final long m = Long.parseLong(m1.group(2));\r\n final long s = Long.parseLong(m1.group(3));\r\n return h * 3600000L + m * 60000L + s * 1000L;\r\n }\r\n final Matcher m2 = HOUR_MINUTE_SECOND_PATTERN.matcher(value);\r\n if (m2.matches()) {\r\n final long m = Long.parseLong(m2.group(1));\r\n final long s = Long.parseLong(m2.group(2));\r\n String g3 = m2.group(3);\r\n while (g3.length() < 3) {\r\n g3 = g3 + \"0\";\r\n }\r\n final long millis = Long.parseLong(g3);\r\n return m * 60000L + s * 1000L + millis;\r\n }\r\n return 0L;\r\n case \"start_time\":\r\n case \"lstart\":\r\n case \"euid\":\r\n case \"uid\":\r\n default:\r\n return value;\r\n }\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public RelDataType getRowType(RelDataTypeFactory typeFactory) {\r\n return typeFactory.builder().add(\"pid\", SqlTypeName.INTEGER).add(\"ppid\", SqlTypeName.INTEGER).add(\"pgrp\", SqlTypeName.INTEGER).add(\"tpgid\", SqlTypeName.INTEGER).add(\"stat\", SqlTypeName.VARCHAR).add(\"user\", SqlTypeName.VARCHAR).add(\"pcpu\", SqlTypeName.DECIMAL, 3, 1).add(\"pmem\", SqlTypeName.DECIMAL, 3, 1).add(\"vsz\", SqlTypeName.INTEGER).add(\"rss\", SqlTypeName.INTEGER).add(\"tty\", SqlTypeName.VARCHAR).add(\"start_time\", SqlTypeName.VARCHAR).add(\"time\", TimeUnit.HOUR, -1, TimeUnit.SECOND, 0).add(\"euid\", SqlTypeName.VARCHAR).add(\"ruid\", SqlTypeName.VARCHAR).add(\"sess\", SqlTypeName.VARCHAR).add(\"command\", SqlTypeName.VARCHAR).build();\r\n }\r\n\r\n @Override\r\n public Statistic getStatistic() {\r\n return Statistics.of(1000d, ImmutableList.of(ImmutableBitSet.of(1)));\r\n }\r\n\r\n @Override\r\n public Schema.TableType getJdbcTableType() {\r\n return Schema.TableType.TABLE;\r\n }\r\n\r\n @Override\r\n public boolean isRolledUp(String column) {\r\n return false;\r\n }\r\n\r\n @Override\r\n public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, @Nullable SqlNode parent, @Nullable CalciteConnectionConfig config) {\r\n return true;\r\n }\r\n };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprivate String planAsTimeSeries(List groupByKeyDims, DruidJsonFilter jsonFilter, List virtualColumnList, List aggregations, List postAggregations, JsonLimit limit, DruidJsonFilter havingFilter){\r\n if (havingFilter != null) {\r\n return null;\r\n }\r\n if (groupByKeyDims.size() > 1) {\r\n return null;\r\n }\r\n if (limit.limit != null) {\r\n return null;\r\n }\r\n if (limit.collations != null && limit.collations.size() > 1) {\r\n return null;\r\n }\r\n final String sortDirection;\r\n if (limit.collations != null && limit.collations.size() == 1) {\r\n if (groupByKeyDims.isEmpty() || !limit.collations.get(0).dimension.equals(groupByKeyDims.get(0).getOutputName())) {\r\n return null;\r\n }\r\n sortDirection = limit.collations.get(0).direction;\r\n } else {\r\n sortDirection = null;\r\n }\r\n final Granularity timeseriesGranularity;\r\n if (groupByKeyDims.size() == 1) {\r\n DimensionSpec dimensionSpec = Iterables.getOnlyElement(groupByKeyDims);\r\n Granularity granularity = ExtractionDimensionSpec.toQueryGranularity(dimensionSpec);\r\n boolean hasExpressionOnTopOfTimeExtract = false;\r\n for (JsonExpressionPostAgg postAgg : postAggregations) {\r\n if (postAgg != null) {\r\n if (postAgg.expression.contains(groupByKeyDims.get(0).getOutputName())) {\r\n hasExpressionOnTopOfTimeExtract = true;\r\n }\r\n }\r\n }\r\n timeseriesGranularity = hasExpressionOnTopOfTimeExtract ? null : granularity;\r\n if (timeseriesGranularity == null) {\r\n return null;\r\n }\r\n } else {\r\n timeseriesGranularity = Granularities.all();\r\n }\r\n final boolean skipEmptyBuckets = Granularities.all() != timeseriesGranularity;\r\n final StringWriter sw = new StringWriter();\r\n final JsonFactory factory = new JsonFactory();\r\n try {\r\n final JsonGenerator generator = factory.createGenerator(sw);\r\n generator.writeStartObject();\r\n generator.writeStringField(\"queryType\", \"timeseries\");\r\n generator.writeStringField(\"dataSource\", druidTable.dataSource);\r\n generator.writeBooleanField(\"descending\", sortDirection != null && sortDirection.equals(\"descending\"));\r\n writeField(generator, \"granularity\", timeseriesGranularity);\r\n writeFieldIf(generator, \"filter\", jsonFilter);\r\n writeField(generator, \"aggregations\", aggregations);\r\n writeFieldIf(generator, \"virtualColumns\", virtualColumnList.size() > 0 ? virtualColumnList : null);\r\n writeFieldIf(generator, \"postAggregations\", postAggregations.size() > 0 ? postAggregations : null);\r\n writeField(generator, \"intervals\", intervals);\r\n generator.writeFieldName(\"context\");\r\n generator.writeStartObject();\r\n generator.writeBooleanField(\"skipEmptyBuckets\", skipEmptyBuckets);\r\n generator.writeEndObject();\r\n generator.close();\r\n } catch (IOException e) {\r\n throw new RuntimeException(e);\r\n }\r\n return sw.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder mergeFrom(org.bitcoin.protocols.payments.Protos.Payment other){\r\n if (other == org.bitcoin.protocols.payments.Protos.Payment.getDefaultInstance())\r\n return this;\r\n if (other.hasMerchantData()) {\r\n setMerchantData(other.getMerchantData());\r\n }\r\n if (!other.transactions_.isEmpty()) {\r\n if (transactions_.isEmpty()) {\r\n transactions_ = other.transactions_;\r\n bitField0_ = (bitField0_ & ~0x00000002);\r\n } else {\r\n ensureTransactionsIsMutable();\r\n transactions_.addAll(other.transactions_);\r\n }\r\n onChanged();\r\n }\r\n if (refundToBuilder_ == null) {\r\n if (!other.refundTo_.isEmpty()) {\r\n if (refundTo_.isEmpty()) {\r\n refundTo_ = other.refundTo_;\r\n bitField0_ = (bitField0_ & ~0x00000004);\r\n } else {\r\n ensureRefundToIsMutable();\r\n refundTo_.addAll(other.refundTo_);\r\n }\r\n onChanged();\r\n }\r\n } else {\r\n if (!other.refundTo_.isEmpty()) {\r\n if (refundToBuilder_.isEmpty()) {\r\n refundToBuilder_.dispose();\r\n refundToBuilder_ = null;\r\n refundTo_ = other.refundTo_;\r\n bitField0_ = (bitField0_ & ~0x00000004);\r\n refundToBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRefundToFieldBuilder() : null;\r\n } else {\r\n refundToBuilder_.addAllMessages(other.refundTo_);\r\n }\r\n }\r\n }\r\n if (other.hasMemo()) {\r\n bitField0_ |= 0x00000008;\r\n memo_ = other.memo_;\r\n onChanged();\r\n }\r\n this.mergeUnknownFields(other.getUnknownFields());\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseTarHeaderUnwrapped(final Map globalPaxHeaders, final byte[] header, final ZipEncoding encoding, final boolean oldStyle, final boolean lenient) throws IOException{\r\n int offset = 0;\r\n name = oldStyle ? TarUtils.parseName(header, offset, NAMELEN) : TarUtils.parseName(header, offset, NAMELEN, encoding);\r\n offset += NAMELEN;\r\n mode = (int) parseOctalOrBinary(header, offset, MODELEN, lenient);\r\n offset += MODELEN;\r\n userId = (int) parseOctalOrBinary(header, offset, UIDLEN, lenient);\r\n offset += UIDLEN;\r\n groupId = (int) parseOctalOrBinary(header, offset, GIDLEN, lenient);\r\n offset += GIDLEN;\r\n size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);\r\n if (size < 0) {\r\n throw new IOException(\"broken archive, entry with negative size\");\r\n }\r\n offset += SIZELEN;\r\n mTime = TimeUtils.unixTimeToFileTime(parseOctalOrBinary(header, offset, MODTIMELEN, lenient));\r\n offset += MODTIMELEN;\r\n checkSumOK = TarUtils.verifyCheckSum(header);\r\n offset += CHKSUMLEN;\r\n linkFlag = header[offset++];\r\n linkName = oldStyle ? TarUtils.parseName(header, offset, NAMELEN) : TarUtils.parseName(header, offset, NAMELEN, encoding);\r\n offset += NAMELEN;\r\n magic = TarUtils.parseName(header, offset, MAGICLEN);\r\n offset += MAGICLEN;\r\n version = TarUtils.parseName(header, offset, VERSIONLEN);\r\n offset += VERSIONLEN;\r\n userName = oldStyle ? TarUtils.parseName(header, offset, UNAMELEN) : TarUtils.parseName(header, offset, UNAMELEN, encoding);\r\n offset += UNAMELEN;\r\n groupName = oldStyle ? TarUtils.parseName(header, offset, GNAMELEN) : TarUtils.parseName(header, offset, GNAMELEN, encoding);\r\n offset += GNAMELEN;\r\n if (linkFlag == LF_CHR || linkFlag == LF_BLK) {\r\n devMajor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);\r\n offset += DEVLEN;\r\n devMinor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);\r\n offset += DEVLEN;\r\n } else {\r\n offset += 2 * DEVLEN;\r\n }\r\n final int type = evaluateType(globalPaxHeaders, header);\r\n switch(type) {\r\n case FORMAT_OLDGNU:\r\n {\r\n aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_GNU, lenient));\r\n offset += ATIMELEN_GNU;\r\n cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_GNU, lenient));\r\n offset += CTIMELEN_GNU;\r\n offset += OFFSETLEN_GNU;\r\n offset += LONGNAMESLEN_GNU;\r\n offset += PAD2LEN_GNU;\r\n sparseHeaders = new ArrayList<>(TarUtils.readSparseStructs(header, offset, SPARSE_HEADERS_IN_OLDGNU_HEADER));\r\n offset += SPARSELEN_GNU;\r\n isExtended = TarUtils.parseBoolean(header, offset);\r\n offset += ISEXTENDEDLEN_GNU;\r\n realSize = TarUtils.parseOctal(header, offset, REALSIZELEN_GNU);\r\n offset += REALSIZELEN_GNU;\r\n break;\r\n }\r\n case FORMAT_XSTAR:\r\n {\r\n final String xstarPrefix = oldStyle ? TarUtils.parseName(header, offset, PREFIXLEN_XSTAR) : TarUtils.parseName(header, offset, PREFIXLEN_XSTAR, encoding);\r\n offset += PREFIXLEN_XSTAR;\r\n if (!xstarPrefix.isEmpty()) {\r\n name = xstarPrefix + \"/\" + name;\r\n }\r\n aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_XSTAR, lenient));\r\n offset += ATIMELEN_XSTAR;\r\n cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_XSTAR, lenient));\r\n offset += CTIMELEN_XSTAR;\r\n break;\r\n }\r\n case FORMAT_POSIX:\r\n default:\r\n {\r\n final String prefix = oldStyle ? TarUtils.parseName(header, offset, PREFIXLEN) : TarUtils.parseName(header, offset, PREFIXLEN, encoding);\r\n offset += PREFIXLEN;\r\n if (isDirectory() && !name.endsWith(\"/\")) {\r\n name = name + \"/\";\r\n }\r\n if (!prefix.isEmpty()) {\r\n name = prefix + \"/\" + name;\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List summarizeOpenAPI(OpenAPI contract, SyntaxNodeAnalysisContext context, Filter filter){\r\n List openAPISummaries = new ArrayList<>();\r\n io.swagger.v3.oas.models.Paths paths = contract.getPaths();\r\n paths.forEach((path, value) -> {\r\n OpenAPIPathSummary openAPISummary = new OpenAPIPathSummary();\r\n if (value != null) {\r\n openAPISummary.setPath(path);\r\n if (value.getGet() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.GET, value.getGet(), filter, context);\r\n }\r\n if (value.getPost() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.POST, value.getPost(), filter, context);\r\n }\r\n if (value.getPut() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.PUT, value.getPut(), filter, context);\r\n }\r\n if (value.getDelete() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.DELETE, value.getDelete(), filter, context);\r\n }\r\n if (value.getHead() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.HEAD, value.getHead(), filter, context);\r\n }\r\n if (value.getPatch() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.PATCH, value.getPatch(), filter, context);\r\n }\r\n if (value.getOptions() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.OPTIONS, value.getOptions(), filter, context);\r\n }\r\n if (value.getTrace() != null) {\r\n addOpenAPISummary(openAPISummary, Constants.TRACE, value.getTrace(), filter, context);\r\n }\r\n }\r\n if (openAPISummary.getOperations().size() > 0) {\r\n openAPISummaries.add(openAPISummary);\r\n }\r\n });\r\n return openAPISummaries;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " Set solve(int x, int y){\r\n int c = y * width + x;\r\n final int target = regions.length - 1;\r\n Direction d = Direction.UP;\r\n final List list = new ArrayList<>();\r\n final Deque fromStack = new ArrayDeque<>();\r\n final Deque directionStack = new ArrayDeque<>();\r\n Direction from = Direction.BACKTRACK;\r\n int cNext = 0;\r\n Direction dNext = Direction.UP;\r\n boolean move = false;\r\n for (; ; ) {\r\n switch(d) {\r\n case UP:\r\n move = from != Direction.DOWN && ups[c];\r\n cNext = c - width;\r\n dNext = Direction.LEFT;\r\n break;\r\n case LEFT:\r\n move = from != Direction.RIGHT && lefts[c];\r\n cNext = c - 1;\r\n dNext = Direction.DOWN;\r\n break;\r\n case DOWN:\r\n move = from != Direction.UP && c + width < regions.length && ups[c + width];\r\n cNext = c + width;\r\n dNext = Direction.RIGHT;\r\n break;\r\n case RIGHT:\r\n move = from != Direction.LEFT && c % width < width - 1 && lefts[c + 1];\r\n cNext = c + 1;\r\n dNext = Direction.BACKTRACK;\r\n break;\r\n case BACKTRACK:\r\n move = false;\r\n do {\r\n c = list.remove(list.size() - 1);\r\n dNext = directionStack.pop();\r\n from = fromStack.pop();\r\n } while (dNext == Direction.BACKTRACK);\r\n break;\r\n default:\r\n break;\r\n }\r\n if (move) {\r\n directionStack.push(dNext);\r\n fromStack.push(from);\r\n list.add(c);\r\n if (cNext == target) {\r\n list.add(cNext);\r\n return new LinkedHashSet<>(list);\r\n }\r\n from = d;\r\n d = Direction.UP;\r\n c = cNext;\r\n } else {\r\n d = dNext;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void appendModels(Class clazz, OpenAPI openApi){\r\n RestModelConverters converters = new RestModelConverters();\r\n List> models = converters.readClass(openApi, clazz);\r\n if (models == null) {\r\n return;\r\n }\r\n if (openApi.getComponents() == null) {\r\n openApi.setComponents(new Components());\r\n }\r\n for (Schema newSchema : models) {\r\n boolean addSchema = true;\r\n if (openApi.getComponents().getSchemas() != null) {\r\n Schema existing = openApi.getComponents().getSchemas().get(newSchema.getName());\r\n if (existing != null) {\r\n Object oldClassName = getClassNameExtension(existing);\r\n Object newClassName = getClassNameExtension(newSchema);\r\n if (oldClassName != null) {\r\n addSchema = false;\r\n LOG.info(\"Duplicate schema found for with name {}; classname1={}, classname2={}\", newSchema.getName(), oldClassName, newClassName != null ? newClassName : \"none\");\r\n }\r\n }\r\n }\r\n if (addSchema) {\r\n openApi.getComponents().addSchemas(newSchema.getName(), newSchema);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private long reserveBlockContents(int freeListIx, int headerToFreeIx, int[] victimHeaders, int victimsOffset, boolean isDiscard){\r\n if (enableDefragShortcut) {\r\n LlapAllocatorBuffer buffer = buffers[headerToFreeIx];\r\n byte header = headers[headerToFreeIx];\r\n if (buffer != null && freeListFromHeader(header) == freeListIx) {\r\n FreeList freeList = freeLists[freeListIx];\r\n freeList.lock.lock();\r\n try {\r\n if (headers[headerToFreeIx] == header && buffer.startMoveOrDiscard(arenaIx, headerToFreeIx, isDiscard)) {\r\n if (assertsEnabled) {\r\n assertBufferLooksValid(freeListIx, buffer, arenaIx, headerToFreeIx);\r\n CasLog.logMove(arenaIx, headerToFreeIx, System.identityHashCode(buffer));\r\n }\r\n victimHeaders[victimsOffset] = headerToFreeIx;\r\n return makeIntPair(1, buffer.allocSize);\r\n }\r\n } finally {\r\n freeList.lock.unlock();\r\n }\r\n }\r\n }\r\n long[] stack = new long[freeListIx + 1];\r\n int stackSize = 1;\r\n stack[0] = makeIntPair(freeListIx, getBuddyHeaderIx(freeListIx, headerToFreeIx));\r\n int victimCount = 0;\r\n int totalMoveSize = 0;\r\n while (stackSize > 0) {\r\n --stackSize;\r\n long next = stack[stackSize];\r\n int listLevel = getFirstInt(next);\r\n int sourceHeaderIx = getSecondInt(next);\r\n int levelBuddyHeaderIx = getBuddyHeaderIx(listLevel, sourceHeaderIx);\r\n long result = prepareOneHeaderForMove(levelBuddyHeaderIx, isDiscard, freeListIx);\r\n if (result == -1) {\r\n return makeIntPair(victimCount, FAILED_TO_RESERVE);\r\n }\r\n int allocSize = getFirstInt(result);\r\n totalMoveSize += allocSize;\r\n victimHeaders[victimsOffset + victimCount] = levelBuddyHeaderIx;\r\n ++victimCount;\r\n int actualBuddyListIx = getSecondInt(result);\r\n for (int intermListIx = listLevel - 1; intermListIx >= actualBuddyListIx; --intermListIx) {\r\n stack[stackSize++] = makeIntPair(intermListIx, levelBuddyHeaderIx);\r\n }\r\n }\r\n return makeIntPair(victimCount, totalMoveSize);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doBracketedField(final int field) throws IOException{\r\n StringBuilder buffer = null;\r\n int currentCharacter;\r\n boolean start = false;\r\n while (!endOfFile) {\r\n currentCharacter = read();\r\n if (currentCharacter == -1) {\r\n endOfFile = true;\r\n if (buffer != null) {\r\n parsedEntries.add(new StringInt(buffer.toString(), field));\r\n }\r\n return;\r\n }\r\n if ((currentCharacter == '{') || (currentCharacter == '}')) {\r\n if (currentCharacter == '}') {\r\n if (buffer != null) {\r\n parsedEntries.add(new StringInt(buffer.toString(), field));\r\n return;\r\n }\r\n } else {\r\n start = true;\r\n }\r\n } else {\r\n if (buffer == null) {\r\n buffer = new StringBuilder(100);\r\n }\r\n if (start && (currentCharacter != '}')) {\r\n buffer.append((char) currentCharacter);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void patternSource(PatternDescrBuilder pattern) throws RecognitionException{\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.FROM, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0) {\r\n helper.emit(Location.LOCATION_LHS_FROM);\r\n }\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.ACCUMULATE) || helper.validateIdentifierKey(DroolsSoftKeywords.ACC)) {\r\n fromAccumulate(pattern);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.COLLECT)) {\r\n fromCollect(pattern);\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.ENTRY) && helper.validateLT(2, \"-\") && helper.validateLT(3, DroolsSoftKeywords.POINT)) {\r\n fromEntryPoint(pattern);\r\n if (state.failed)\r\n return;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.WINDOW)) {\r\n fromWindow(pattern);\r\n } else {\r\n fromExpression(pattern);\r\n if (!lastTokenWasWhiteSpace() && input.LA(1) == DRL6Lexer.EOF) {\r\n helper.emit(Location.LOCATION_LHS_FROM);\r\n throw new RecognitionException();\r\n }\r\n if (state.failed)\r\n return;\r\n }\r\n if (input.LA(1) == DRL6Lexer.SEMICOLON) {\r\n match(input, DRL6Lexer.SEMICOLON, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\n@Nullable\npublic RelDataType getTightestCommonType(@Nullable RelDataType type1, @Nullable RelDataType type2){\r\n if (type1 == null || type2 == null) {\r\n return null;\r\n }\r\n if (type1.equals(type2) || (type1.isNullable() != type2.isNullable() && factory.createTypeWithNullability(type1, type2.isNullable()).equals(type2))) {\r\n return factory.createTypeWithNullability(type1, type1.isNullable() || type2.isNullable());\r\n }\r\n if (SqlTypeUtil.isNull(type1)) {\r\n return type2;\r\n }\r\n if (SqlTypeUtil.isNull(type2)) {\r\n return type1;\r\n }\r\n RelDataType resultType = null;\r\n if (SqlTypeUtil.isString(type1) && SqlTypeUtil.isString(type2)) {\r\n resultType = factory.leastRestrictive(ImmutableList.of(type1, type2));\r\n }\r\n if (SqlTypeUtil.isNumeric(type1) && SqlTypeUtil.isNumeric(type2)) {\r\n if (!SqlTypeUtil.isDecimal(type1) && !SqlTypeUtil.isDecimal(type2)) {\r\n resultType = factory.leastRestrictive(ImmutableList.of(type1, type2));\r\n }\r\n }\r\n if (SqlTypeUtil.isDate(type1) && SqlTypeUtil.isTimestamp(type2)) {\r\n resultType = type2;\r\n }\r\n if (SqlTypeUtil.isDate(type2) && SqlTypeUtil.isTimestamp(type1)) {\r\n resultType = type1;\r\n }\r\n if (type1.isStruct() && type2.isStruct()) {\r\n if (SqlTypeUtil.equalAsStructSansNullability(factory, type1, type2, validator.getCatalogReader().nameMatcher())) {\r\n List fields = new ArrayList<>();\r\n List fieldNames = type1.getFieldNames();\r\n for (Pair pair : Pair.zip(type1.getFieldList(), type2.getFieldList())) {\r\n RelDataType leftType = pair.left.getType();\r\n RelDataType rightType = pair.right.getType();\r\n RelDataType dataType = getTightestCommonTypeOrThrow(leftType, rightType);\r\n boolean isNullable = leftType.isNullable() || rightType.isNullable();\r\n fields.add(factory.createTypeWithNullability(dataType, isNullable));\r\n }\r\n return factory.createStructType(type1.getStructKind(), fields, fieldNames);\r\n }\r\n }\r\n if (SqlTypeUtil.isArray(type1) && SqlTypeUtil.isArray(type2)) {\r\n if (SqlTypeUtil.equalSansNullability(factory, type1, type2)) {\r\n resultType = factory.createTypeWithNullability(type1, type1.isNullable() || type2.isNullable());\r\n }\r\n }\r\n if (SqlTypeUtil.isMap(type1) && SqlTypeUtil.isMap(type2)) {\r\n if (SqlTypeUtil.equalSansNullability(factory, type1, type2)) {\r\n RelDataType keyType = getTightestCommonTypeOrThrow(type1.getKeyType(), type2.getKeyType());\r\n RelDataType valType = getTightestCommonTypeOrThrow(type1.getValueType(), type2.getValueType());\r\n resultType = factory.createMapType(keyType, valType);\r\n }\r\n }\r\n return resultType;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public final void unregisterFactory(){\r\n if (null == bus) {\r\n return;\r\n }\r\n DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class);\r\n if (null != dfm && getTransportIds() != null) {\r\n for (String ns : getTransportIds()) {\r\n try {\r\n if (dfm.getDestinationFactory(ns) == this) {\r\n dfm.deregisterDestinationFactory(ns);\r\n }\r\n } catch (BusException e) {\r\n }\r\n }\r\n }\r\n ConduitInitiatorManager cim = bus.getExtension(ConduitInitiatorManager.class);\r\n if (cim != null && getTransportIds() != null) {\r\n for (String ns : getTransportIds()) {\r\n try {\r\n if (cim.getConduitInitiator(ns) == this) {\r\n cim.deregisterConduitInitiator(ns);\r\n }\r\n } catch (BusException e) {\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List> pageInfos, CitationType citationType, XTextCursor position, boolean insertSpaceAfter) throws CreationException, NoDocumentException, WrappedTargetException, NotRemoveableException, PropertyVetoException, IllegalTypeException{\r\n Objects.requireNonNull(pageInfos);\r\n if (pageInfos.size() != citationKeys.size()) {\r\n throw new IllegalArgumentException();\r\n }\r\n final int numberOfCitations = citationKeys.size();\r\n final int last = numberOfCitations - 1;\r\n List citations = new ArrayList<>(numberOfCitations);\r\n for (int i = 0; i < numberOfCitations; i++) {\r\n Citation cit = new Citation(citationKeys.get(i));\r\n citations.add(cit);\r\n Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(i));\r\n switch(dataModel) {\r\n case JabRef52:\r\n if (i == last) {\r\n cit.setPageInfo(pageInfo);\r\n } else {\r\n if (pageInfo.isPresent()) {\r\n LOGGER.warn(\"dataModel JabRef52\" + \" only supports pageInfo for the last citation of a group\");\r\n }\r\n }\r\n break;\r\n case JabRef60:\r\n cit.setPageInfo(pageInfo);\r\n break;\r\n default:\r\n throw new IllegalStateException(\"Unhandled dataModel in Backend52.createCitationGroup\");\r\n }\r\n }\r\n final String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), citationKeys, citationType);\r\n final CitationGroupId groupId = new CitationGroupId(markName);\r\n boolean withoutBrackets = citationType == CitationType.INVISIBLE_CIT;\r\n NamedRange namedRange = this.citationStorageManager.createNamedRange(doc, markName, position, insertSpaceAfter, withoutBrackets);\r\n switch(dataModel) {\r\n case JabRef52:\r\n Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last));\r\n if (pageInfo.isPresent()) {\r\n String pageInfoString = OOText.toString(pageInfo.get());\r\n UnoUserDefinedProperty.setStringProperty(doc, markName, pageInfoString);\r\n } else {\r\n UnoUserDefinedProperty.removeIfExists(doc, markName);\r\n }\r\n CitationGroup group = new CitationGroup(OODataModel.JabRef52, groupId, citationType, citations, Optional.of(markName));\r\n this.cgidToNamedRange.put(groupId, namedRange);\r\n return group;\r\n case JabRef60:\r\n throw new IllegalStateException(\"createCitationGroup for JabRef60 is not implemented yet\");\r\n default:\r\n throw new IllegalStateException(\"Unhandled dataModel in Backend52.createCitationGroup\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprivate ScopeChild findChild(List names, SqlNameMatcher nameMatcher){\r\n for (ScopeChild child : children) {\r\n String lastName = Util.last(names);\r\n if (child.name != null) {\r\n if (!nameMatcher.matches(child.name, lastName)) {\r\n continue;\r\n }\r\n if (names.size() == 1) {\r\n return child;\r\n }\r\n }\r\n final SqlValidatorTable table = child.namespace.getTable();\r\n if (table != null) {\r\n final ResolvedImpl resolved = new ResolvedImpl();\r\n resolveTable(names, nameMatcher, Path.EMPTY, resolved);\r\n if (resolved.count() == 1) {\r\n Resolve only = resolved.only();\r\n List qualifiedName = table.getQualifiedName();\r\n if (only.remainingNames.isEmpty() && only.namespace instanceof TableNamespace && Objects.equals(qualifiedName, getQualifiedName(only.namespace.getTable()))) {\r\n return child;\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Set getProductsToRemove(List allOwnerPoolsForGuest, Set tmpSet){\r\n Set productsToRemove = new HashSet<>();\r\n Map> providedProductIdsByPool = this.poolCurator.getProvidedProductIdsByPools(allOwnerPoolsForGuest);\r\n for (Pool pool : allOwnerPoolsForGuest) {\r\n if (pool == null || pool.getProduct() == null) {\r\n continue;\r\n }\r\n Product poolProduct = pool.getProduct();\r\n if (pool.hasAttribute(Pool.Attributes.VIRT_ONLY) || poolProduct.hasAttribute(Product.Attributes.VIRT_ONLY)) {\r\n if (tmpSet.contains(poolProduct.getId())) {\r\n productsToRemove.add(poolProduct.getId());\r\n }\r\n Set providedProductIds = providedProductIdsByPool.get(pool.getId());\r\n if (providedProductIds != null) {\r\n for (String pid : providedProductIds) {\r\n if (tmpSet.contains(pid)) {\r\n productsToRemove.add(pid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return productsToRemove;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Version parse(String version){\r\n if ((version == null) || \"\".equals(version) || version.equals(BuildInfo.UNKNOWN_VERSION) || \"${version}\".equals(version)) {\r\n return UNKNOWN_VERSION;\r\n }\r\n Version parsedVersion = new Version();\r\n Matcher ciSuffixMatcher = CI_SUFFIX_PATTERN.matcher(version);\r\n version = ciSuffixMatcher.replaceAll(\"\");\r\n parsedVersion.fullVersion = version;\r\n Matcher matcher = VERSION_PATTERN.matcher(version);\r\n if (matcher.find()) {\r\n try {\r\n parsedVersion.major = Integer.parseInt(matcher.group(\"major\"));\r\n String minorString = matcher.group(\"minor\");\r\n parsedVersion.minor = minorString == null ? 0 : Integer.parseInt(minorString);\r\n String patchString = matcher.group(\"patch\");\r\n parsedVersion.patch = patchString == null ? 0 : Integer.parseInt(patchString);\r\n String versionStageString = matcher.group(\"stage\");\r\n parsedVersion.developmentStage = versionStageString == null ? DevelopmentStage.STABLE : DevelopmentStage.parse(versionStageString);\r\n String stageNumString = matcher.group(\"num\");\r\n parsedVersion.developmentNum = stageNumString == null ? 0 : Integer.parseInt(stageNumString);\r\n parsedVersion.isDevelopmentVersion = matcher.group(\"dev\") != null;\r\n } catch (NumberFormatException e) {\r\n getLogger().warn(\"Invalid version string used: {}\", version, e);\r\n return UNKNOWN_VERSION;\r\n } catch (IllegalArgumentException e) {\r\n getLogger().warn(\"Invalid version pattern is used\", e);\r\n return UNKNOWN_VERSION;\r\n }\r\n } else {\r\n getLogger().warn(\"Version could not be recognized by the pattern\");\r\n return UNKNOWN_VERSION;\r\n }\r\n return parsedVersion;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List stringToList(String s){\r\n if (s.isEmpty()) {\r\n return ImmutableList.of();\r\n }\r\n final ImmutableList.Builder builder = ImmutableList.builder();\r\n final StringBuilder b = new StringBuilder();\r\n int i = 0;\r\n for (; ; ) {\r\n char c = s.charAt(i);\r\n if (c != '\"') {\r\n throw new IllegalArgumentException();\r\n }\r\n for (; ; ) {\r\n c = s.charAt(++i);\r\n if (c == '\"') {\r\n if (i == s.length() - 1) {\r\n break;\r\n }\r\n ++i;\r\n c = s.charAt(i);\r\n if (c == '.') {\r\n break;\r\n }\r\n if (c != '\"') {\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n b.append(c);\r\n }\r\n builder.add(b.toString());\r\n b.setLength(0);\r\n if (++i >= s.length()) {\r\n break;\r\n }\r\n }\r\n return builder.build();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized CoapServer getServer(int port, CoAPEndpoint endpoint) throws IOException, GeneralSecurityException{\r\n CoapServer server = servers.get(port);\r\n if (server == null && port == -1) {\r\n server = getServer(DEFAULT_PORT, endpoint);\r\n }\r\n if (server == null) {\r\n CoapEndpoint.Builder coapBuilder = new CoapEndpoint.Builder();\r\n NetworkConfig config = NetworkConfig.createStandardWithoutFile();\r\n InetSocketAddress address = new InetSocketAddress(port);\r\n coapBuilder.setNetworkConfig(config);\r\n if (CoAPEndpoint.enableDTLS(endpoint.getUri())) {\r\n DTLSConnector connector = endpoint.createDTLSConnector(address, false);\r\n coapBuilder.setConnector(connector);\r\n } else if (CoAPEndpoint.enableTCP(endpoint.getUri())) {\r\n int tcpThreads = config.getInt(NetworkConfig.Keys.TCP_WORKER_THREADS);\r\n int tcpIdleTimeout = config.getInt(NetworkConfig.Keys.TCP_CONNECTION_IDLE_TIMEOUT);\r\n TcpServerConnector tcpConnector = null;\r\n if (endpoint.getUri().getScheme().startsWith(\"coaps\")) {\r\n int tlsHandshakeTimeout = config.getInt(NetworkConfig.Keys.TLS_HANDSHAKE_TIMEOUT);\r\n SSLContext sslContext = endpoint.getSslContextParameters().createSSLContext(getCamelContext());\r\n TlsServerConnector.ClientAuthMode clientAuthMode = TlsServerConnector.ClientAuthMode.NONE;\r\n if (endpoint.isClientAuthenticationRequired()) {\r\n clientAuthMode = TlsServerConnector.ClientAuthMode.NEEDED;\r\n } else if (endpoint.isClientAuthenticationWanted()) {\r\n clientAuthMode = TlsServerConnector.ClientAuthMode.WANTED;\r\n }\r\n tcpConnector = new TlsServerConnector(sslContext, clientAuthMode, address, tcpThreads, tlsHandshakeTimeout, tcpIdleTimeout);\r\n } else {\r\n tcpConnector = new TcpServerConnector(address, tcpThreads, tcpIdleTimeout);\r\n }\r\n coapBuilder.setConnector(tcpConnector);\r\n } else {\r\n coapBuilder.setInetSocketAddress(address);\r\n }\r\n server = new CoapServer();\r\n server.addEndpoint(coapBuilder.build());\r\n servers.put(port, server);\r\n if (this.isStarted()) {\r\n server.start();\r\n }\r\n }\r\n return server;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void propagateHeadersFromCxfToCamel(Message cxfMessage, org.apache.camel.Message camelMessage, Exchange exchange){\r\n Map> cxfHeaders = CastUtils.cast((Map) cxfMessage.get(CxfConstants.PROTOCOL_HEADERS));\r\n Map camelHeaders = camelMessage.getHeaders();\r\n camelHeaders.put(CxfConstants.CAMEL_CXF_MESSAGE, cxfMessage);\r\n CxfHeaderHelper.copyHttpHeadersFromCxfToCamel(headerFilterStrategy, cxfMessage, camelMessage, exchange);\r\n if (cxfHeaders != null) {\r\n for (Map.Entry> entry : cxfHeaders.entrySet()) {\r\n if (!headerFilterStrategy.applyFilterToExternalHeaders(entry.getKey(), entry.getValue(), exchange)) {\r\n if (\"Content-Type\".compareToIgnoreCase(entry.getKey()) == 0 && entry.getValue().get(0) != null && entry.getValue().get(0).startsWith(\"multipart/related\")) {\r\n DataFormat dataFormat = exchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);\r\n if (dataFormat.equals(DataFormat.RAW)) {\r\n camelHeaders.put(entry.getKey(), getContentTypeString(entry.getValue()));\r\n } else {\r\n String contentType = replaceMultiPartContentType(entry.getValue().get(0));\r\n LOG.trace(\"Find the multi-part Conent-Type, and replace it with {}\", contentType);\r\n camelHeaders.put(entry.getKey(), contentType);\r\n }\r\n } else if (SoapBindingConstants.SOAP_ACTION.compareToIgnoreCase(entry.getKey()) == 0 && entry.getValue().get(0) != null) {\r\n String soapAction = entry.getValue().get(0);\r\n soapAction = StringHelper.removeLeadingAndEndingQuotes(soapAction);\r\n camelHeaders.put(SoapBindingConstants.SOAP_ACTION, soapAction);\r\n } else if (entry.getKey().startsWith(\":\")) {\r\n continue;\r\n } else {\r\n LOG.trace(\"Populate header from CXF header={} value={}\", entry.getKey(), entry.getValue());\r\n List values = entry.getValue();\r\n Object evalue;\r\n if (values.size() > 1) {\r\n final boolean headersMerged = exchange.getProperty(CxfConstants.CAMEL_CXF_PROTOCOL_HEADERS_MERGED, Boolean.FALSE, Boolean.class);\r\n if (headersMerged) {\r\n StringBuilder sb = new StringBuilder();\r\n for (Iterator it = values.iterator(); it.hasNext(); ) {\r\n sb.append(it.next());\r\n if (it.hasNext()) {\r\n sb.append(',').append(' ');\r\n }\r\n }\r\n evalue = sb.toString();\r\n } else {\r\n evalue = values;\r\n }\r\n } else if (values.size() == 1) {\r\n evalue = values.get(0);\r\n } else {\r\n evalue = null;\r\n }\r\n if (evalue != null) {\r\n camelHeaders.put(entry.getKey(), evalue);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n String key = Header.HEADER_LIST;\r\n Object value = cxfMessage.get(key);\r\n if (value != null) {\r\n if (!headerFilterStrategy.applyFilterToExternalHeaders(key, value, exchange)) {\r\n camelHeaders.put(key, value);\r\n LOG.trace(\"Populate header from CXF header={} value={}\", key, value);\r\n } else {\r\n ((List) value).clear();\r\n }\r\n }\r\n String soapAction = (String) camelHeaders.get(SoapBindingConstants.SOAP_ACTION);\r\n if (ObjectHelper.isEmpty(soapAction) || \"\\\"\\\"\".equals(soapAction)) {\r\n camelHeaders.remove(SoapBindingConstants.SOAP_ACTION);\r\n }\r\n soapAction = (String) cxfMessage.get(SoapBindingConstants.SOAP_ACTION);\r\n if (soapAction != null) {\r\n if (!headerFilterStrategy.applyFilterToExternalHeaders(SoapBindingConstants.SOAP_ACTION, soapAction, exchange)) {\r\n camelHeaders.put(SoapBindingConstants.SOAP_ACTION, soapAction);\r\n LOG.trace(\"Populate header from CXF header={} value={}\", SoapBindingConstants.SOAP_ACTION, soapAction);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void buildExtensionGraph(Map graphs, Entry> entry){\r\n String title = entry.getKey();\r\n if (title.equalsIgnoreCase(DAL)) {\r\n for (Entry subEntry : entry.getValue().entrySet()) {\r\n String key = subEntry.getKey();\r\n int pos = key.lastIndexOf('-');\r\n if (pos > 0) {\r\n String db = \"Dal \" + key.substring(0, pos);\r\n String subTitle = key.substring(pos + 1);\r\n ExtensionGroup extensitonGroup = graphs.get(db);\r\n if (extensitonGroup == null) {\r\n extensitonGroup = new ExtensionGroup();\r\n graphs.put(db, extensitonGroup);\r\n }\r\n if (!INDEX.containsKey(subTitle)) {\r\n INDEX.put(subTitle, INDEX_COUNTER.getAndIncrement());\r\n }\r\n String svg = m_builder.build(new HeartbeatSvgBuilder(INDEX.get(subTitle), subTitle, \"Minute\", \"Count\", subEntry.getValue()));\r\n extensitonGroup.getSvgs().put(subTitle, svg);\r\n }\r\n }\r\n } else {\r\n ExtensionGroup extensitonGroup = graphs.get(title);\r\n if (extensitonGroup == null) {\r\n extensitonGroup = new ExtensionGroup();\r\n graphs.put(title, extensitonGroup);\r\n }\r\n int i = 0;\r\n for (Entry item : entry.getValue().entrySet()) {\r\n String key = item.getKey();\r\n Metric metricConfig = m_manager.queryMetric(title, key);\r\n String svgTitle = key;\r\n String lable = \"\";\r\n if (metricConfig != null) {\r\n String configTitle = metricConfig.getTitle();\r\n if (configTitle != null) {\r\n svgTitle = configTitle;\r\n }\r\n lable = metricConfig.getLable();\r\n }\r\n String svg = m_builder.build(new HeartbeatSvgBuilder(i++, svgTitle, \"Minute\", lable, item.getValue()));\r\n extensitonGroup.getSvgs().put(key, svg);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public TypeName typeName(MemberModel model, TypeNameOptions options){\r\n if (model.isSdkBytesType() && options.useByteBufferTypes) {\r\n return ClassName.get(ByteBuffer.class);\r\n }\r\n if (model.getEnumType() != null && options.useEnumTypes) {\r\n return poetExtensions.getModelClass(model.getEnumType());\r\n }\r\n if (model.isSimple()) {\r\n return getTypeNameForSimpleType(model.getVariable().getVariableType());\r\n }\r\n if (model.isList()) {\r\n MemberModel entryModel = model.getListModel().getListMemberModel();\r\n TypeName entryType = typeName(entryModel, options);\r\n if (options.useSubtypeWildcardsForCollections && isContainerType(entryModel) || options.useSubtypeWildcardsForBuilders && entryModel.hasBuilder()) {\r\n entryType = WildcardTypeName.subtypeOf(entryType);\r\n }\r\n Class collectionType = options.useCollectionForList ? Collection.class : List.class;\r\n return ParameterizedTypeName.get(ClassName.get(collectionType), entryType);\r\n }\r\n if (model.isMap()) {\r\n MemberModel keyModel = model.getMapModel().getKeyModel();\r\n MemberModel valueModel = model.getMapModel().getValueModel();\r\n TypeName keyType = typeName(keyModel, options);\r\n TypeName valueType = typeName(valueModel, options);\r\n if (options.useSubtypeWildcardsForCollections && isContainerType(keyModel) || options.useSubtypeWildcardsForBuilders && keyModel.hasBuilder()) {\r\n keyType = WildcardTypeName.subtypeOf(keyType);\r\n }\r\n if (options.useSubtypeWildcardsForCollections && isContainerType(valueModel) || options.useSubtypeWildcardsForBuilders && valueModel.hasBuilder()) {\r\n valueType = WildcardTypeName.subtypeOf(valueType);\r\n }\r\n return ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType);\r\n }\r\n if (model.hasBuilder()) {\r\n ClassName shapeClass = poetExtensions.getModelClass(model.getC2jShape());\r\n switch(options.shapeTransformation) {\r\n case NONE:\r\n return shapeClass;\r\n case USE_BUILDER:\r\n return shapeClass.nestedClass(\"Builder\");\r\n case USE_BUILDER_IMPL:\r\n return shapeClass.nestedClass(\"BuilderImpl\");\r\n default:\r\n throw new IllegalStateException();\r\n }\r\n }\r\n throw new IllegalArgumentException(\"Unsupported member model: \" + model);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String expandLHS(final String lhs, int lineOffset){\r\n substitutions = new ArrayList<>();\r\n final StringBuilder buf = new StringBuilder();\r\n final String[] lines = lhs.split((lhs.indexOf(\"\\r\\n\") >= 0 ? \"\\r\\n\" : \"\\n\"), -1);\r\n final String[] expanded = new String[lines.length];\r\n int lastExpanded = -1;\r\n int lastPattern = -1;\r\n for (int i = 0; i < lines.length - 1; i++) {\r\n final String trimmed = lines[i].trim();\r\n expanded[++lastExpanded] = lines[i];\r\n if (trimmed.length() == 0 || trimmed.startsWith(\"#\") || trimmed.startsWith(\"//\")) {\r\n } else if (trimmed.startsWith(\">\")) {\r\n expanded[lastExpanded] = lines[i].replaceFirst(\">\", \" \");\r\n lastPattern = lastExpanded;\r\n } else {\r\n expanded[lastExpanded] = substitute(expanded[lastExpanded], this.condition, i + lineOffset, useWhen, showSteps);\r\n if (lines[i].equals(expanded[lastExpanded])) {\r\n this.addError(new ExpanderException(\"Unable to expand: \" + lines[i].replaceAll(\"[\\n\\r]\", \"\").trim(), i + lineOffset));\r\n }\r\n if (trimmed.startsWith(\"-\") && (!lines[i].equals(expanded[lastExpanded]))) {\r\n if (lastPattern >= 0) {\r\n ConstraintInformation c = ConstraintInformation.findConstraintInformationInPattern(expanded[lastPattern]);\r\n if (c.start > -1) {\r\n expanded[lastPattern] = expanded[lastPattern].substring(0, c.start) + c.constraints + ((c.constraints.trim().length() == 0) ? \"\" : \", \") + expanded[lastExpanded].trim() + expanded[lastPattern].substring(c.end);\r\n } else {\r\n this.addError(new ExpanderException(\"No pattern was found to add the constraint to: \" + lines[i].trim(), i + lineOffset));\r\n }\r\n }\r\n lastExpanded--;\r\n } else {\r\n lastPattern = lastExpanded;\r\n }\r\n }\r\n }\r\n for (int i = 0; i <= lastExpanded; i++) {\r\n buf.append(expanded[i]);\r\n buf.append(nl);\r\n }\r\n return buf.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void initTransactionManager(Environment env){\r\n Object tm = env.get(EnvironmentName.TRANSACTION_MANAGER);\r\n if (env.get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER) != null && env.get(EnvironmentName.TRANSACTION_MANAGER) != null) {\r\n this.txm = (TransactionManager) tm;\r\n this.jpm = (PersistenceContextManager) env.get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);\r\n } else {\r\n if (tm != null && isSpringTransactionManager(tm.getClass())) {\r\n try {\r\n logger.debug(\"Instantiating KieSpringTransactionManager\");\r\n Class cls = Class.forName(\"org.kie.spring.persistence.KieSpringTransactionManager\");\r\n Constructor con = cls.getConstructors()[0];\r\n this.txm = (TransactionManager) con.newInstance(tm);\r\n env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);\r\n cls = Class.forName(\"org.kie.spring.persistence.KieSpringJpaManager\");\r\n con = cls.getConstructors()[0];\r\n this.jpm = (PersistenceContextManager) con.newInstance(this.env);\r\n } catch (Exception e) {\r\n logger.warn(\"Could not instantiate KieSpringTransactionManager. Trying with DroolsSpringTransactionManager.\");\r\n try {\r\n logger.debug(\"Instantiating DroolsSpringTransactionManager\");\r\n Class cls = Class.forName(\"org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager\");\r\n Constructor con = cls.getConstructors()[0];\r\n this.txm = (TransactionManager) con.newInstance(tm);\r\n env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);\r\n cls = Class.forName(\"org.drools.container.spring.beans.persistence.DroolsSpringJpaManager\");\r\n con = cls.getConstructors()[0];\r\n this.jpm = (PersistenceContextManager) con.newInstance(this.env);\r\n } catch (Exception ex) {\r\n logger.warn(\"Could not instantiate DroolsSpringTransactionManager\");\r\n throw new RuntimeException(\"Could not instantiate org.kie.container.spring.beans.persistence.DroolsSpringTransactionManager\", ex);\r\n }\r\n }\r\n } else {\r\n logger.debug(\"Instantiating JtaTransactionManager\");\r\n this.txm = TransactionManagerFactory.get().newTransactionManager(env);\r\n env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);\r\n try {\r\n Class jpaPersistenceCtxMngrClass = Class.forName(\"org.jbpm.persistence.JpaProcessPersistenceContextManager\");\r\n Constructor jpaPersistenceCtxMngrCtor = jpaPersistenceCtxMngrClass.getConstructors()[0];\r\n this.jpm = (PersistenceContextManager) jpaPersistenceCtxMngrCtor.newInstance(this.env);\r\n } catch (ClassNotFoundException e) {\r\n this.jpm = new JpaPersistenceContextManager(this.env);\r\n } catch (Exception e) {\r\n throw new RuntimeException(\"Error creating JpaProcessPersistenceContextManager\", e);\r\n }\r\n }\r\n env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, this.jpm);\r\n env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " CSVFormat getActiveFormat(){\r\n CSVFormat answer = format;\r\n if (commentMarkerDisabled) {\r\n answer = answer.withCommentMarker(null);\r\n } else if (commentMarker != null) {\r\n answer = answer.withCommentMarker(commentMarker);\r\n }\r\n if (delimiter != null) {\r\n answer = answer.withDelimiter(delimiter);\r\n }\r\n if (escapeDisabled) {\r\n answer = answer.withEscape(null);\r\n } else if (escape != null) {\r\n answer = answer.withEscape(escape);\r\n }\r\n if (headerDisabled) {\r\n answer = answer.withHeader((String[]) null);\r\n } else if (header != null) {\r\n if (header.indexOf(',') != -1) {\r\n answer = answer.withHeader(header.split(\",\"));\r\n } else {\r\n answer = answer.withHeader(header);\r\n }\r\n }\r\n if (allowMissingColumnNames != null) {\r\n answer = answer.withAllowMissingColumnNames(allowMissingColumnNames);\r\n }\r\n if (ignoreEmptyLines != null) {\r\n answer = answer.withIgnoreEmptyLines(ignoreEmptyLines);\r\n }\r\n if (ignoreSurroundingSpaces != null) {\r\n answer = answer.withIgnoreSurroundingSpaces(ignoreSurroundingSpaces);\r\n }\r\n if (nullStringDisabled) {\r\n answer = answer.withNullString(null);\r\n } else if (nullString != null) {\r\n answer = answer.withNullString(nullString);\r\n }\r\n if (quoteDisabled) {\r\n answer = answer.withQuote(null);\r\n } else if (quote != null) {\r\n answer = answer.withQuote(quote);\r\n }\r\n if (quoteMode != null) {\r\n answer = answer.withQuoteMode(quoteMode);\r\n }\r\n if (recordSeparatorDisabled) {\r\n answer = answer.withRecordSeparator(null);\r\n } else if (recordSeparator != null) {\r\n answer = answer.withRecordSeparator(recordSeparator);\r\n }\r\n if (skipHeaderRecord != null) {\r\n answer = answer.withSkipHeaderRecord(skipHeaderRecord);\r\n }\r\n if (trim != null) {\r\n answer = answer.withTrim(trim);\r\n }\r\n if (ignoreHeaderCase != null) {\r\n answer = answer.withIgnoreHeaderCase(ignoreHeaderCase);\r\n }\r\n if (trailingDelimiter != null) {\r\n answer = answer.withTrailingDelimiter(trailingDelimiter);\r\n }\r\n return answer;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static Deque initStack(Object a, Object b, List parentPath, Map> comparatorByPropertyOrField, TypeComparators comparatorByType){\r\n Deque stack = new LinkedList<>();\r\n boolean isRootObject = parentPath == null;\r\n List currentPath = isRootObject ? new ArrayList<>() : parentPath;\r\n DualKey basicDualKey = new DualKey(currentPath, a, b);\r\n if (a != null && b != null && !isContainerType(a) && !isContainerType(b) && (isRootObject || !hasCustomComparator(basicDualKey, comparatorByPropertyOrField, comparatorByType))) {\r\n Set aFieldsNames = getFieldsNames(getDeclaredFieldsIncludingInherited(a.getClass()));\r\n if (!aFieldsNames.isEmpty()) {\r\n Set bFieldsNames = getFieldsNames(getDeclaredFieldsIncludingInherited(b.getClass()));\r\n if (!bFieldsNames.containsAll(aFieldsNames)) {\r\n stack.addFirst(basicDualKey);\r\n } else {\r\n for (String fieldName : aFieldsNames) {\r\n List fieldPath = new ArrayList<>(currentPath);\r\n fieldPath.add(fieldName);\r\n DualKey dk = new DualKey(fieldPath, COMPARISON.getSimpleValue(fieldName, a), COMPARISON.getSimpleValue(fieldName, b));\r\n stack.addFirst(dk);\r\n }\r\n }\r\n } else {\r\n stack.addFirst(basicDualKey);\r\n }\r\n } else {\r\n stack.addFirst(basicDualKey);\r\n }\r\n return stack;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void run(){\r\n Set subscriptions = new HashSet<>();\r\n for (Product product : products) {\r\n Collection subs = subAdapter.getSubscriptionsByProductId(product.getId());\r\n log.debug(\"Will refresh {} subscriptions in all orgs using product: {}\", subs.size(), product.getId());\r\n if (log.isDebugEnabled()) {\r\n for (SubscriptionInfo s : subs) {\r\n OwnerInfo so = s.getOwner();\r\n if (so == null || so.getKey() == null) {\r\n log.debug(\" Received a subscription without a well-defined owner: {}\", s.getId());\r\n continue;\r\n }\r\n if (!this.owners.containsKey(so.getKey())) {\r\n log.debug(\" {}\", s);\r\n }\r\n }\r\n }\r\n subscriptions.addAll(subs);\r\n }\r\n for (SubscriptionInfo subscription : subscriptions) {\r\n OwnerInfo so = subscription.getOwner();\r\n if (so == null || so.getKey() == null) {\r\n log.error(\"Received a subscription without a well-defined owner: {}\", subscription.getId());\r\n continue;\r\n }\r\n if (this.owners.containsKey(so.getKey())) {\r\n log.debug(\"Skipping subscription \\\"{}\\\" for owner: {}\", subscription.getId(), so);\r\n continue;\r\n }\r\n Pool primaryPool = poolManager.convertToPrimaryPool(subscription);\r\n poolManager.refreshPoolsForPrimaryPool(primaryPool, true, lazy, Collections.emptyMap());\r\n }\r\n for (Owner owner : this.owners.values()) {\r\n poolManager.refreshPoolsWithRegeneration(this.subAdapter, this.prodAdapter, owner, this.lazy);\r\n poolManager.recalculatePoolQuantitiesForOwner(owner);\r\n ownerManager.updateRefreshDate(owner);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Builder mergeFrom(KieModuleCache.KModuleCache other){\r\n if (other == KieModuleCache.KModuleCache.getDefaultInstance())\r\n return this;\r\n if (compilationDataBuilder_ == null) {\r\n if (!other.compilationData_.isEmpty()) {\r\n if (compilationData_.isEmpty()) {\r\n compilationData_ = other.compilationData_;\r\n bitField0_ = (bitField0_ & ~0x00000001);\r\n } else {\r\n ensureCompilationDataIsMutable();\r\n compilationData_.addAll(other.compilationData_);\r\n }\r\n onChanged();\r\n }\r\n } else {\r\n if (!other.compilationData_.isEmpty()) {\r\n if (compilationDataBuilder_.isEmpty()) {\r\n compilationDataBuilder_.dispose();\r\n compilationDataBuilder_ = null;\r\n compilationData_ = other.compilationData_;\r\n bitField0_ = (bitField0_ & ~0x00000001);\r\n compilationDataBuilder_ = alwaysUseFieldBuilders ? getCompilationDataFieldBuilder() : null;\r\n } else {\r\n compilationDataBuilder_.addAllMessages(other.compilationData_);\r\n }\r\n }\r\n }\r\n this.mergeUnknownFields(other.getUnknownFields());\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static T syncCallWithRetries(ZooKeeperClient client, ZooCallable proc, RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) throws KeeperException, InterruptedException{\r\n T result = null;\r\n boolean isDone = false;\r\n int attempts = 0;\r\n long startTimeNanos = MathUtils.nowInNano();\r\n while (!isDone) {\r\n try {\r\n if (null != client) {\r\n client.waitForConnection();\r\n }\r\n logger.debug(\"Execute {} at {} retry attempt.\", proc, attempts);\r\n if (null != rateLimiter) {\r\n rateLimiter.acquire();\r\n }\r\n result = proc.call();\r\n isDone = true;\r\n statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS);\r\n } catch (KeeperException e) {\r\n ++attempts;\r\n boolean rethrow = true;\r\n long elapsedTime = MathUtils.elapsedMSec(startTimeNanos);\r\n if (((null != client && isRecoverableException(e)) || null == client) && retryPolicy.allowRetry(attempts, elapsedTime)) {\r\n rethrow = false;\r\n }\r\n if (rethrow) {\r\n statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS);\r\n logger.debug(\"Stopped executing {} after {} attempts.\", proc, attempts);\r\n throw e;\r\n }\r\n TimeUnit.MILLISECONDS.sleep(retryPolicy.nextRetryWaitTime(attempts, elapsedTime));\r\n }\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private QueryParameter setOptionalQueryParameter(String queryParamName, OptionalTypeDescriptorNode typeNode, String isOptional){\r\n QueryParameter queryParameter = new QueryParameter();\r\n if (isOptional.equals(Constants.FALSE)) {\r\n queryParameter.setRequired(true);\r\n }\r\n queryParameter.setName(unescapeIdentifier(queryParamName));\r\n Node node = typeNode.typeDescriptor();\r\n if (node.kind() == SyntaxKind.ARRAY_TYPE_DESC) {\r\n ArraySchema arraySchema = new ArraySchema();\r\n arraySchema.setNullable(true);\r\n ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) node;\r\n TypeDescriptorNode itemTypeNode = arrayNode.memberTypeDesc();\r\n Schema itemSchema;\r\n if (arrayNode.memberTypeDesc().kind() == SIMPLE_NAME_REFERENCE) {\r\n itemSchema = getItemSchemaForReference(arrayNode);\r\n } else {\r\n itemSchema = ConverterCommonUtils.getOpenApiSchema(itemTypeNode.toString().trim());\r\n }\r\n arraySchema.setItems(itemSchema);\r\n queryParameter.schema(arraySchema);\r\n queryParameter.setName(unescapeIdentifier(queryParamName));\r\n if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName));\r\n }\r\n return queryParameter;\r\n } else if (node.kind() == SyntaxKind.MAP_TYPE_DESC) {\r\n queryParameter = createContentTypeForMapJson(queryParamName, true);\r\n if (isOptional.equals(Constants.FALSE)) {\r\n queryParameter.setRequired(true);\r\n }\r\n if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName));\r\n }\r\n return queryParameter;\r\n } else if (node.kind() == SIMPLE_NAME_REFERENCE) {\r\n Schema refSchema = handleReference(semanticModel, components, (SimpleNameReferenceNode) node);\r\n queryParameter.setSchema(refSchema);\r\n if (isOptional.equals(Constants.FALSE)) {\r\n queryParameter.setRequired(true);\r\n }\r\n if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName));\r\n }\r\n return queryParameter;\r\n } else {\r\n Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(node.toString().trim());\r\n openApiSchema.setNullable(true);\r\n queryParameter.setSchema(openApiSchema);\r\n if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName));\r\n }\r\n return queryParameter;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void invokeOnParticipant(Address address, Operation op, @Nullable Consumer> completionCallback, @Nullable Consumer errorCallback, ConcurrentMap collectedResponses, AtomicInteger remainingCount){\r\n InvocationFuture future = nodeEngine.getOperationService().createInvocationBuilder(JetServiceBackend.SERVICE_NAME, op, address).invoke();\r\n future.whenComplete((r, throwable) -> {\r\n Object response = r != null ? r : throwable != null ? peel(throwable) : NULL_OBJECT;\r\n if (throwable instanceof OperationTimeoutException) {\r\n logger.warning(\"Retrying \" + op.getClass().getSimpleName() + \" that failed with \" + OperationTimeoutException.class.getSimpleName() + \" in \" + jobIdString);\r\n invokeOnParticipant(address, op, completionCallback, errorCallback, collectedResponses, remainingCount);\r\n return;\r\n }\r\n if (errorCallback != null && throwable != null) {\r\n errorCallback.accept(throwable);\r\n }\r\n Object oldResponse = collectedResponses.put(address, response);\r\n assert oldResponse == null : \"Duplicate response for \" + address + \". Old=\" + oldResponse + \", new=\" + response;\r\n if (remainingCount.decrementAndGet() == 0 && completionCallback != null) {\r\n completionCallback.accept(collectedResponses.values().stream().map(o -> o == NULL_OBJECT ? null : o).collect(Collectors.toList()));\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void replicasCheck() throws BKAuditException{\r\n ConcurrentHashMap ledgersWithMissingEntries = new ConcurrentHashMap();\r\n ConcurrentHashMap ledgersWithUnavailableBookies = new ConcurrentHashMap();\r\n LedgerRangeIterator ledgerRangeIterator = ledgerManager.getLedgerRanges(zkOpTimeoutMs);\r\n final Semaphore maxConcurrentSemaphore = new Semaphore(MAX_CONCURRENT_REPLICAS_CHECK_LEDGER_REQUESTS);\r\n while (true) {\r\n LedgerRange ledgerRange = null;\r\n try {\r\n if (ledgerRangeIterator.hasNext()) {\r\n ledgerRange = ledgerRangeIterator.next();\r\n } else {\r\n break;\r\n }\r\n } catch (IOException ioe) {\r\n LOG.error(\"Got IOException while iterating LedgerRangeIterator\", ioe);\r\n throw new BKAuditException(\"Got IOException while iterating LedgerRangeIterator\", ioe);\r\n }\r\n ledgersWithMissingEntries.clear();\r\n ledgersWithUnavailableBookies.clear();\r\n numLedgersFoundHavingNoReplicaOfAnEntry.set(0);\r\n numLedgersFoundHavingLessThanAQReplicasOfAnEntry.set(0);\r\n numLedgersFoundHavingLessThanWQReplicasOfAnEntry.set(0);\r\n Set ledgersInRange = ledgerRange.getLedgers();\r\n int numOfLedgersInRange = ledgersInRange.size();\r\n final AtomicInteger resultCode = new AtomicInteger();\r\n final CountDownLatch replicasCheckLatch = new CountDownLatch(1);\r\n ReplicasCheckFinalCallback finalCB = new ReplicasCheckFinalCallback(resultCode, replicasCheckLatch);\r\n MultiCallback mcbForThisLedgerRange = new MultiCallback(numOfLedgersInRange, finalCB, null, BKException.Code.OK, BKException.Code.ReadException) {\r\n\r\n @Override\r\n public void processResult(int rc, String path, Object ctx) {\r\n try {\r\n super.processResult(rc, path, ctx);\r\n } finally {\r\n maxConcurrentSemaphore.release();\r\n }\r\n }\r\n };\r\n LOG.debug(\"Number of ledgers in the current LedgerRange : {}\", numOfLedgersInRange);\r\n for (Long ledgerInRange : ledgersInRange) {\r\n try {\r\n if (!maxConcurrentSemaphore.tryAcquire(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) {\r\n LOG.error(\"Timedout ({} secs) while waiting for acquiring semaphore\", REPLICAS_CHECK_TIMEOUT_IN_SECS);\r\n throw new BKAuditException(\"Timedout while waiting for acquiring semaphore\");\r\n }\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n LOG.error(\"Got InterruptedException while acquiring semaphore for replicascheck\", ie);\r\n throw new BKAuditException(\"Got InterruptedException while acquiring semaphore for replicascheck\", ie);\r\n }\r\n if (checkUnderReplicationForReplicasCheck(ledgerInRange, mcbForThisLedgerRange)) {\r\n continue;\r\n }\r\n ledgerManager.readLedgerMetadata(ledgerInRange).whenComplete(new ReadLedgerMetadataCallbackForReplicasCheck(ledgerInRange, mcbForThisLedgerRange, ledgersWithMissingEntries, ledgersWithUnavailableBookies));\r\n }\r\n try {\r\n if (!replicasCheckLatch.await(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) {\r\n LOG.error(\"For LedgerRange with num of ledgers : {} it didn't complete replicascheck\" + \" in {} secs, so giving up\", numOfLedgersInRange, REPLICAS_CHECK_TIMEOUT_IN_SECS);\r\n throw new BKAuditException(\"Got InterruptedException while doing replicascheck\");\r\n }\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n LOG.error(\"Got InterruptedException while doing replicascheck\", ie);\r\n throw new BKAuditException(\"Got InterruptedException while doing replicascheck\", ie);\r\n }\r\n reportLedgersWithMissingEntries(ledgersWithMissingEntries);\r\n reportLedgersWithUnavailableBookies(ledgersWithUnavailableBookies);\r\n int resultCodeIntValue = resultCode.get();\r\n if (resultCodeIntValue != BKException.Code.OK) {\r\n throw new BKAuditException(\"Exception while doing replicas check\", BKException.create(resultCodeIntValue));\r\n }\r\n }\r\n try {\r\n ledgerUnderreplicationManager.setReplicasCheckCTime(System.currentTimeMillis());\r\n } catch (UnavailableException ue) {\r\n LOG.error(\"Got exception while trying to set ReplicasCheckCTime\", ue);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parseAreaCentroid(Context context, BiMap map) throws Exception{\r\n XmlPullParser xpp = (XmlPullParser) context.get(PARSER);\r\n Referential referential = (Referential) context.get(REFERENTIAL);\r\n NeptuneObjectFactory factory = (NeptuneObjectFactory) context.get(NEPTUNE_OBJECT_FACTORY);\r\n xpp.require(XmlPullParser.START_TAG, null, \"AreaCentroid\");\r\n int columnNumber = xpp.getColumnNumber();\r\n int lineNumber = xpp.getLineNumber();\r\n AreaCentroidValidator validator = (AreaCentroidValidator) ValidatorFactory.create(AreaCentroidValidator.class.getName(), context);\r\n BiMap inverse = map.inverse();\r\n StopArea stopArea = null;\r\n AreaCentroid areaCentroid = null;\r\n String objectId = null;\r\n while (xpp.nextTag() == XmlPullParser.START_TAG) {\r\n if (xpp.getName().equals(\"objectId\")) {\r\n objectId = ParserUtils.getText(xpp.nextText());\r\n areaCentroid = factory.getAreaCentroid(objectId);\r\n String areaId = inverse.get(objectId);\r\n stopArea = ObjectFactory.getStopArea(referential, areaId);\r\n areaCentroid.setContainedIn(stopArea);\r\n } else if (xpp.getName().equals(\"name\")) {\r\n areaCentroid.setName(ParserUtils.getText(xpp.nextText()));\r\n if (stopArea.getName() == null)\r\n stopArea.setName(areaCentroid.getName());\r\n } else if (xpp.getName().equals(\"comment\")) {\r\n areaCentroid.setComment(ParserUtils.getText(xpp.nextText()));\r\n if (stopArea.getComment() == null)\r\n stopArea.setComment(areaCentroid.getComment());\r\n } else if (xpp.getName().equals(\"longLatType\")) {\r\n stopArea.setLongLatType(ParserUtils.getEnum(LongLatTypeEnum.class, xpp.nextText()));\r\n validator.addLongLatType(context, objectId, stopArea.getLongLatType());\r\n } else if (xpp.getName().equals(\"latitude\")) {\r\n stopArea.setLatitude(ParserUtils.getBigDecimal(xpp.nextText()));\r\n } else if (xpp.getName().equals(\"longitude\")) {\r\n stopArea.setLongitude(ParserUtils.getBigDecimal(xpp.nextText()));\r\n } else if (xpp.getName().equals(\"containedIn\")) {\r\n String containedIn = ParserUtils.getText(xpp.nextText());\r\n validator.addContainedIn(context, objectId, containedIn);\r\n } else if (xpp.getName().equals(\"address\")) {\r\n while (xpp.nextTag() == XmlPullParser.START_TAG) {\r\n if (xpp.getName().equals(\"countryCode\")) {\r\n stopArea.setCountryCode(ParserUtils.getText(xpp.nextText()));\r\n } else if (xpp.getName().equals(\"streetName\")) {\r\n stopArea.setStreetName(ParserUtils.getText(xpp.nextText()));\r\n } else {\r\n XPPUtil.skipSubTree(log, xpp);\r\n }\r\n }\r\n } else if (xpp.getName().equals(\"projectedPoint\")) {\r\n while (xpp.nextTag() == XmlPullParser.START_TAG) {\r\n if (xpp.getName().equals(\"X\")) {\r\n BigDecimal value = ParserUtils.getBigDecimal(xpp.nextText());\r\n stopArea.setX(value);\r\n } else if (xpp.getName().equals(\"Y\")) {\r\n BigDecimal value = ParserUtils.getBigDecimal(xpp.nextText());\r\n stopArea.setY(value);\r\n } else if (xpp.getName().equals(\"projectionType\")) {\r\n String value = ParserUtils.getText(xpp.nextText());\r\n stopArea.setProjectionType(value);\r\n } else {\r\n XPPUtil.skipSubTree(log, xpp);\r\n }\r\n }\r\n } else {\r\n XPPUtil.skipSubTree(log, xpp);\r\n }\r\n }\r\n validator.addLocation(context, areaCentroid, lineNumber, columnNumber);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprotected RexNode shuttleReferences(final RexBuilder rexBuilder, final RexNode expr, final Multimap exprsLineage, @Nullable final RelNode node, @Nullable final Multimap rewritingMapping){\r\n try {\r\n RexShuttle visitor = new RexShuttle() {\r\n\r\n @Override\r\n public RexNode visitTableInputRef(RexTableInputRef ref) {\r\n Collection c = exprsLineage.get(ref);\r\n if (c.isEmpty()) {\r\n throw Util.FoundOne.NULL;\r\n }\r\n int pos = c.iterator().next();\r\n if (rewritingMapping != null) {\r\n if (!rewritingMapping.containsKey(pos)) {\r\n throw Util.FoundOne.NULL;\r\n }\r\n pos = rewritingMapping.get(pos).iterator().next();\r\n }\r\n if (node != null) {\r\n return rexBuilder.makeInputRef(node, pos);\r\n }\r\n return rexBuilder.makeInputRef(ref.getType(), pos);\r\n }\r\n\r\n @Override\r\n public RexNode visitInputRef(RexInputRef inputRef) {\r\n Collection c = exprsLineage.get(inputRef);\r\n if (c.isEmpty()) {\r\n throw Util.FoundOne.NULL;\r\n }\r\n int pos = c.iterator().next();\r\n if (rewritingMapping != null) {\r\n if (!rewritingMapping.containsKey(pos)) {\r\n throw Util.FoundOne.NULL;\r\n }\r\n pos = rewritingMapping.get(pos).iterator().next();\r\n }\r\n if (node != null) {\r\n return rexBuilder.makeInputRef(node, pos);\r\n }\r\n return rexBuilder.makeInputRef(inputRef.getType(), pos);\r\n }\r\n\r\n @Override\r\n public RexNode visitCall(final RexCall call) {\r\n Collection c = exprsLineage.get(call);\r\n if (c.isEmpty()) {\r\n return super.visitCall(call);\r\n }\r\n int pos = c.iterator().next();\r\n if (rewritingMapping != null) {\r\n if (!rewritingMapping.containsKey(pos)) {\r\n return super.visitCall(call);\r\n }\r\n pos = rewritingMapping.get(pos).iterator().next();\r\n }\r\n if (node != null) {\r\n return rexBuilder.makeInputRef(node, pos);\r\n }\r\n return rexBuilder.makeInputRef(call.getType(), pos);\r\n }\r\n };\r\n return visitor.apply(expr);\r\n } catch (Util.FoundOne ex) {\r\n Util.swallow(ex, null);\r\n return null;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode transformNullSemantics(RexNode node){\r\n assert isParentsCount >= 0 : \"Cannot be negative\";\r\n if (!isBoolean(node)) {\r\n return node;\r\n }\r\n Boolean directlyUnderIs = null;\r\n if (node.isA(SqlKind.IS_TRUE)) {\r\n directlyUnderIs = Boolean.TRUE;\r\n isParentsCount++;\r\n } else if (node.isA(SqlKind.IS_FALSE)) {\r\n directlyUnderIs = Boolean.FALSE;\r\n isParentsCount++;\r\n }\r\n if (null != directlyUnderIs) {\r\n RexCall call = (RexCall) node;\r\n assert isParentsCount > 0 : \"Stack should not be empty\";\r\n assert 1 == call.operands.size();\r\n RexNode operand = call.operands.get(0);\r\n if (operand instanceof RexLiteral || operand instanceof RexInputRef || operand instanceof RexDynamicParam) {\r\n if (isNullable(node)) {\r\n RexNode notNullNode = rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, operand);\r\n RexNode boolNode = rexBuilder.makeLiteral(directlyUnderIs.booleanValue());\r\n RexNode eqNode = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, operand, boolNode);\r\n RexNode andBoolNode = rexBuilder.makeCall(SqlStdOperatorTable.AND, notNullNode, eqNode);\r\n return andBoolNode;\r\n } else {\r\n RexNode boolNode = rexBuilder.makeLiteral(directlyUnderIs.booleanValue());\r\n RexNode andBoolNode = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, node, boolNode);\r\n return andBoolNode;\r\n }\r\n }\r\n }\r\n if (node instanceof RexCall) {\r\n RexCall call = (RexCall) node;\r\n final ArrayList operands = new ArrayList<>();\r\n for (RexNode operand : call.operands) {\r\n operands.add(transformNullSemantics(operand));\r\n }\r\n if (null != directlyUnderIs) {\r\n isParentsCount--;\r\n directlyUnderIs = null;\r\n return operands.get(0);\r\n }\r\n if (transformableOperators.contains(call.getOperator())) {\r\n assert 2 == operands.size();\r\n final RexNode isNotNullOne;\r\n if (isTransformable(operands.get(0))) {\r\n isNotNullOne = rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, operands.get(0));\r\n } else {\r\n isNotNullOne = null;\r\n }\r\n final RexNode isNotNullTwo;\r\n if (isTransformable(operands.get(1))) {\r\n isNotNullTwo = rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, operands.get(1));\r\n } else {\r\n isNotNullTwo = null;\r\n }\r\n RexNode intoFinalAnd = null;\r\n if ((null != isNotNullOne) && (null != isNotNullTwo)) {\r\n intoFinalAnd = rexBuilder.makeCall(SqlStdOperatorTable.AND, isNotNullOne, isNotNullTwo);\r\n } else if (null != isNotNullOne) {\r\n intoFinalAnd = isNotNullOne;\r\n } else if (null != isNotNullTwo) {\r\n intoFinalAnd = isNotNullTwo;\r\n }\r\n if (null != intoFinalAnd) {\r\n RexNode andNullAndCheckNode = rexBuilder.makeCall(SqlStdOperatorTable.AND, intoFinalAnd, call.clone(call.getType(), operands));\r\n return andNullAndCheckNode;\r\n }\r\n }\r\n if (!operands.equals(call.operands)) {\r\n return call.clone(call.getType(), operands);\r\n }\r\n }\r\n return node;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected AbstractApplicationContext createDefaultApplicationContext(){\r\n ApplicationContext parentContext = getParentApplicationContext();\r\n if (getFileApplicationContextUri() != null) {\r\n String[] args = getFileApplicationContextUri().split(\";\");\r\n if (parentContext != null) {\r\n return new FileSystemXmlApplicationContext(args, parentContext);\r\n } else {\r\n return new FileSystemXmlApplicationContext(args);\r\n }\r\n }\r\n String[] args = getApplicationContextUri().split(\";\");\r\n if (parentContext != null) {\r\n return new ClassPathXmlApplicationContext(args, parentContext);\r\n } else {\r\n if (mainConfigurationProperties.getRoutesBuilderClasses() != null) {\r\n AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();\r\n ac.register(SpringCamelContext.class);\r\n Set packages = new LinkedHashSet<>();\r\n String[] classes = mainConfigurationProperties.getRoutesBuilderClasses().split(\",\");\r\n for (String clazz : classes) {\r\n if (clazz.contains(\".\")) {\r\n String packageName = clazz.substring(0, clazz.lastIndexOf('.'));\r\n packages.add(packageName);\r\n }\r\n }\r\n LOG.info(\"Using Spring annotation scanning in packages: {}\", packages);\r\n ac.scan(packages.toArray(new String[0]));\r\n ac.refresh();\r\n return ac;\r\n } else {\r\n return new ClassPathXmlApplicationContext(args);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ArArchiveEntry getNextArEntry() throws IOException{\r\n if (currentEntry != null) {\r\n final long entryEnd = entryOffset + currentEntry.getLength();\r\n final long skipped = IOUtils.skip(input, entryEnd - offset);\r\n trackReadBytes(skipped);\r\n currentEntry = null;\r\n }\r\n if (offset == 0) {\r\n final byte[] expected = ArchiveUtils.toAsciiBytes(ArArchiveEntry.HEADER);\r\n final byte[] realized = IOUtils.readRange(input, expected.length);\r\n final int read = realized.length;\r\n trackReadBytes(read);\r\n if (read != expected.length) {\r\n throw new IOException(\"Failed to read header. Occurred at byte: \" + getBytesRead());\r\n }\r\n if (!Arrays.equals(expected, realized)) {\r\n throw new IOException(\"Invalid header \" + ArchiveUtils.toAsciiString(realized));\r\n }\r\n }\r\n if (offset % 2 != 0) {\r\n if (input.read() < 0) {\r\n return null;\r\n }\r\n trackReadBytes(1);\r\n }\r\n {\r\n final int read = IOUtils.readFully(input, metaData);\r\n trackReadBytes(read);\r\n switch(read) {\r\n case 0:\r\n {\r\n return null;\r\n }\r\n default:\r\n break;\r\n }\r\n if (read < metaData.length) {\r\n throw new IOException(\"Truncated ar archive\");\r\n }\r\n }\r\n {\r\n final byte[] expected = ArchiveUtils.toAsciiBytes(ArArchiveEntry.TRAILER);\r\n final byte[] realized = IOUtils.readRange(input, expected.length);\r\n final int read = realized.length;\r\n trackReadBytes(read);\r\n if (read != expected.length) {\r\n throw new IOException(\"Failed to read entry trailer. Occurred at byte: \" + getBytesRead());\r\n }\r\n if (!Arrays.equals(expected, realized)) {\r\n throw new IOException(\"Invalid entry trailer. not read the content? Occurred at byte: \" + getBytesRead());\r\n }\r\n }\r\n entryOffset = offset;\r\n String temp = ArchiveUtils.toAsciiString(metaData, NAME_OFFSET, NAME_LEN).trim();\r\n if (isGNUStringTable(temp)) {\r\n currentEntry = readGNUStringTable(metaData, LENGTH_OFFSET, LENGTH_LEN);\r\n return getNextArEntry();\r\n }\r\n long len = asLong(metaData, LENGTH_OFFSET, LENGTH_LEN);\r\n if (temp.endsWith(\"/\")) {\r\n temp = temp.substring(0, temp.length() - 1);\r\n } else if (isGNULongName(temp)) {\r\n final int off = Integer.parseInt(temp.substring(1));\r\n temp = getExtendedName(off);\r\n } else if (isBSDLongName(temp)) {\r\n temp = getBSDLongName(temp);\r\n final int nameLen = temp.length();\r\n len -= nameLen;\r\n entryOffset += nameLen;\r\n }\r\n if (len < 0) {\r\n throw new IOException(\"broken archive, entry with negative size\");\r\n }\r\n currentEntry = new ArArchiveEntry(temp, len, asInt(metaData, USER_ID_OFFSET, USER_ID_LEN, true), asInt(metaData, GROUP_ID_OFFSET, GROUP_ID_LEN, true), asInt(metaData, FILE_MODE_OFFSET, FILE_MODE_LEN, 8), asLong(metaData, LAST_MODIFIED_OFFSET, LAST_MODIFIED_LEN));\r\n return currentEntry;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void parse(Configuration conf, String configProperty){\r\n String aclsStr = conf.get(configProperty);\r\n if (aclsStr == null || aclsStr.isEmpty()) {\r\n return;\r\n }\r\n if (isWildCard(aclsStr)) {\r\n allowedUsers.add(WILDCARD_ACL_VALUE);\r\n return;\r\n }\r\n final String[] splits = splitPattern.split(aclsStr);\r\n int counter = -1;\r\n String userListStr = null;\r\n String groupListStr = null;\r\n for (String s : splits) {\r\n if (s.isEmpty()) {\r\n if (userListStr != null) {\r\n continue;\r\n }\r\n }\r\n ++counter;\r\n if (counter == 0) {\r\n userListStr = s;\r\n } else if (counter == 1) {\r\n groupListStr = s;\r\n } else {\r\n LOG.warn(\"Invalid configuration specified for \" + configProperty + \", ignoring configured ACLs, value=\" + aclsStr);\r\n return;\r\n }\r\n }\r\n if (userListStr == null) {\r\n return;\r\n }\r\n if (userListStr.length() >= 1) {\r\n allowedUsers.addAll(org.apache.hadoop.util.StringUtils.getTrimmedStringCollection(userListStr));\r\n }\r\n if (groupListStr != null && groupListStr.length() >= 1) {\r\n allowedGroups.addAll(org.apache.hadoop.util.StringUtils.getTrimmedStringCollection(groupListStr));\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean splitWindowForStateWindow(TSDataType dataType, ValueRecorder valueRecorder, double delta, ElasticSerializableTVList tvList) throws IOException{\r\n boolean res;\r\n switch(dataType) {\r\n case INT32:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordInt(tvList.getInt(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = Math.abs(tvList.getInt(tvList.size() - 1) - valueRecorder.getInt()) > delta;\r\n if (res) {\r\n valueRecorder.recordInt(tvList.getInt(tvList.size() - 1));\r\n }\r\n break;\r\n case INT64:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordLong(tvList.getLong(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = Math.abs(tvList.getLong(tvList.size() - 1) - valueRecorder.getLong()) > delta;\r\n if (res) {\r\n valueRecorder.recordLong(tvList.getLong(tvList.size() - 1));\r\n }\r\n break;\r\n case FLOAT:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordFloat(tvList.getFloat(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = Math.abs(tvList.getFloat(tvList.size() - 1) - valueRecorder.getFloat()) > delta;\r\n if (res) {\r\n valueRecorder.recordFloat(tvList.getFloat(tvList.size() - 1));\r\n }\r\n break;\r\n case DOUBLE:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordDouble(tvList.getDouble(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = Math.abs(tvList.getDouble(tvList.size() - 1) - valueRecorder.getDouble()) > delta;\r\n if (res) {\r\n valueRecorder.recordDouble(tvList.getDouble(tvList.size() - 1));\r\n }\r\n break;\r\n case BOOLEAN:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordBoolean(tvList.getBoolean(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = tvList.getBoolean(tvList.size() - 1) != valueRecorder.getBoolean();\r\n if (res) {\r\n valueRecorder.recordBoolean(tvList.getBoolean(tvList.size() - 1));\r\n }\r\n break;\r\n case TEXT:\r\n if (!valueRecorder.hasRecorded()) {\r\n valueRecorder.recordString(tvList.getString(tvList.size() - 2));\r\n valueRecorder.setRecorded(true);\r\n }\r\n res = !tvList.getString(tvList.size() - 1).equals(valueRecorder.getString());\r\n if (res) {\r\n valueRecorder.recordString(tvList.getString(tvList.size() - 1));\r\n }\r\n break;\r\n default:\r\n throw new RuntimeException(\"The data type of the state window strategy is not valid.\");\r\n }\r\n return res;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic RelDataType implicitCast(RelDataType in, SqlTypeFamily expected){\r\n List numericFamilies = ImmutableList.of(SqlTypeFamily.NUMERIC, SqlTypeFamily.DECIMAL, SqlTypeFamily.APPROXIMATE_NUMERIC, SqlTypeFamily.EXACT_NUMERIC, SqlTypeFamily.INTEGER);\r\n List dateTimeFamilies = ImmutableList.of(SqlTypeFamily.DATE, SqlTypeFamily.TIME, SqlTypeFamily.TIMESTAMP);\r\n if (expected.getTypeNames().contains(in.getSqlTypeName())) {\r\n return in;\r\n }\r\n if (SqlTypeUtil.isNull(in)) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n if (SqlTypeUtil.isNumeric(in) && expected == SqlTypeFamily.DECIMAL) {\r\n return factory.decimalOf(in);\r\n }\r\n if (SqlTypeUtil.isApproximateNumeric(in) && expected == SqlTypeFamily.EXACT_NUMERIC) {\r\n return factory.decimalOf(in);\r\n }\r\n if (SqlTypeUtil.isDate(in) && expected == SqlTypeFamily.TIMESTAMP) {\r\n return factory.createSqlType(SqlTypeName.TIMESTAMP);\r\n }\r\n if (SqlTypeUtil.isTimestamp(in) && expected == SqlTypeFamily.DATE) {\r\n return factory.createSqlType(SqlTypeName.DATE);\r\n }\r\n if (SqlTypeUtil.isCharacter(in) && numericFamilies.contains(expected)) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n if (SqlTypeUtil.isCharacter(in) && dateTimeFamilies.contains(expected)) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n if (SqlTypeUtil.isCharacter(in) && expected == SqlTypeFamily.BINARY) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n if (SqlTypeUtil.isAtomic(in) && (expected == SqlTypeFamily.STRING || expected == SqlTypeFamily.CHARACTER)) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n if (SqlTypeUtil.isCharacter(in) && expected == SqlTypeFamily.GEO) {\r\n return expected.getDefaultConcreteType(factory);\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void sendMTFValues4() throws IOException{\r\n final boolean[] inUse = this.data.inUse;\r\n final boolean[] inUse16 = this.data.sentMTFValues4_inUse16;\r\n for (int i = 16; --i >= 0; ) {\r\n inUse16[i] = false;\r\n final int i16 = i * 16;\r\n for (int j = 16; --j >= 0; ) {\r\n if (inUse[i16 + j]) {\r\n inUse16[i] = true;\r\n break;\r\n }\r\n }\r\n }\r\n for (int i = 0; i < 16; i++) {\r\n bsW(1, inUse16[i] ? 1 : 0);\r\n }\r\n final OutputStream outShadow = this.out;\r\n int bsLiveShadow = this.bsLive;\r\n int bsBuffShadow = this.bsBuff;\r\n for (int i = 0; i < 16; i++) {\r\n if (inUse16[i]) {\r\n final int i16 = i * 16;\r\n for (int j = 0; j < 16; j++) {\r\n while (bsLiveShadow >= 8) {\r\n outShadow.write(bsBuffShadow >> 24);\r\n bsBuffShadow <<= 8;\r\n bsLiveShadow -= 8;\r\n }\r\n if (inUse[i16 + j]) {\r\n bsBuffShadow |= 1 << (32 - bsLiveShadow - 1);\r\n }\r\n bsLiveShadow++;\r\n }\r\n }\r\n }\r\n this.bsBuff = bsBuffShadow;\r\n this.bsLive = bsLiveShadow;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean isChangedBy(Product entity, ProductInfo update){\r\n if (entity == null) {\r\n throw new IllegalArgumentException(\"entity is null\");\r\n }\r\n if (update == null) {\r\n throw new IllegalArgumentException(\"update is null\");\r\n }\r\n if (update.getName() != null && !update.getName().equals(entity.getName())) {\r\n return true;\r\n }\r\n if (update.getMultiplier() != null && !update.getMultiplier().equals(entity.getMultiplier())) {\r\n return true;\r\n }\r\n Map attributes = update.getAttributes();\r\n if (attributes != null && !attributes.equals(entity.getAttributes())) {\r\n return true;\r\n }\r\n Collection dependentProductIds = update.getDependentProductIds();\r\n if (dependentProductIds != null && !Util.collectionsAreEqual(entity.getDependentProductIds(), dependentProductIds)) {\r\n return true;\r\n }\r\n if (update.getProductContent() != null) {\r\n Map entityContentMap = entity.getProductContent().stream().filter(pc -> pc != null && pc.getContent() != null).collect(Collectors.toMap(pc -> pc.getContent().getId(), pc -> pc.isEnabled()));\r\n Map updateContentMap = update.getProductContent().stream().filter(pc -> pc != null && pc.getContent() != null).collect(Collectors.toMap(pc -> pc.getContent().getId(), pc -> pc.isEnabled()));\r\n if (!entityContentMap.equals(updateContentMap)) {\r\n return true;\r\n }\r\n }\r\n ProductInfo derivedProduct = update.getDerivedProduct();\r\n Product existingDerived = entity.getDerivedProduct();\r\n if (derivedProduct != null) {\r\n if (existingDerived == null || !existingDerived.getId().equals(derivedProduct.getId())) {\r\n return true;\r\n }\r\n } else if (existingDerived != null) {\r\n return true;\r\n }\r\n Collection updateProvidedProducts = update.getProvidedProducts();\r\n if (updateProvidedProducts != null) {\r\n Set entityProvidedPids = entity.getProvidedProducts().stream().filter(Objects::nonNull).map(Product::getId).collect(Collectors.toSet());\r\n Set updateProvidedPids = updateProvidedProducts.stream().filter(Objects::nonNull).map(ProductInfo::getId).collect(Collectors.toSet());\r\n if (!entityProvidedPids.equals(updateProvidedPids)) {\r\n return true;\r\n }\r\n }\r\n Collection updateBranding = update.getBranding();\r\n if (updateBranding != null) {\r\n Function keybuilder = (brand) -> {\r\n return new StringBuilder().append(brand.getProductId()).append(brand.getType()).append(brand.getName()).toString();\r\n };\r\n Set entityBrandingKeys = entity.getBranding().stream().filter(Objects::nonNull).map(keybuilder).collect(Collectors.toSet());\r\n Set updateBrandingKeys = updateBranding.stream().filter(Objects::nonNull).map(keybuilder).collect(Collectors.toSet());\r\n if (!entityBrandingKeys.equals(updateBrandingKeys)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprotected RexNode generateEquivalenceClasses(RexBuilder rexBuilder, EquivalenceClasses sourceEC, EquivalenceClasses targetEC){\r\n if (sourceEC.getEquivalenceClasses().isEmpty() && targetEC.getEquivalenceClasses().isEmpty()) {\r\n return rexBuilder.makeLiteral(true);\r\n }\r\n if (sourceEC.getEquivalenceClasses().isEmpty() && !targetEC.getEquivalenceClasses().isEmpty()) {\r\n return null;\r\n }\r\n final List> sourceEquivalenceClasses = sourceEC.getEquivalenceClasses();\r\n final List> targetEquivalenceClasses = targetEC.getEquivalenceClasses();\r\n final Multimap mapping = extractPossibleMapping(sourceEquivalenceClasses, targetEquivalenceClasses);\r\n if (mapping == null) {\r\n return null;\r\n }\r\n RexNode compensationPredicate = rexBuilder.makeLiteral(true);\r\n for (int i = 0; i < sourceEquivalenceClasses.size(); i++) {\r\n if (!mapping.containsKey(i)) {\r\n Iterator it = sourceEquivalenceClasses.get(i).iterator();\r\n RexTableInputRef e0 = it.next();\r\n while (it.hasNext()) {\r\n RexNode equals = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, e0, it.next());\r\n compensationPredicate = rexBuilder.makeCall(SqlStdOperatorTable.AND, compensationPredicate, equals);\r\n }\r\n } else {\r\n for (int j : mapping.get(i)) {\r\n Set difference = new HashSet<>(sourceEquivalenceClasses.get(i));\r\n difference.removeAll(targetEquivalenceClasses.get(j));\r\n for (RexTableInputRef e : difference) {\r\n RexNode equals = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, e, targetEquivalenceClasses.get(j).iterator().next());\r\n compensationPredicate = rexBuilder.makeCall(SqlStdOperatorTable.AND, compensationPredicate, equals);\r\n }\r\n }\r\n }\r\n }\r\n return compensationPredicate;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CPSignature getCPSignature(final String signature){\r\n if (signature == null) {\r\n return null;\r\n }\r\n CPSignature cpS = stringsToCpSignature.get(signature);\r\n if (cpS == null) {\r\n final List cpClasses = new ArrayList<>();\r\n CPUTF8 signatureUTF8;\r\n if (signature.length() > 1 && signature.indexOf('L') != -1) {\r\n final List classes = new ArrayList<>();\r\n final char[] chars = signature.toCharArray();\r\n final StringBuilder signatureString = new StringBuilder();\r\n for (int i = 0; i < chars.length; i++) {\r\n signatureString.append(chars[i]);\r\n if (chars[i] == 'L') {\r\n final StringBuilder className = new StringBuilder();\r\n for (int j = i + 1; j < chars.length; j++) {\r\n final char c = chars[j];\r\n if (!Character.isLetter(c) && !Character.isDigit(c) && (c != '/') && (c != '$') && (c != '_')) {\r\n classes.add(className.toString());\r\n i = j - 1;\r\n break;\r\n }\r\n className.append(c);\r\n }\r\n }\r\n }\r\n removeCpUtf8(signature);\r\n for (String className : classes) {\r\n CPClass cpClass = null;\r\n if (className != null) {\r\n className = className.replace('.', '/');\r\n cpClass = stringsToCpClass.get(className);\r\n if (cpClass == null) {\r\n final CPUTF8 cpUtf8 = getCPUtf8(className);\r\n cpClass = new CPClass(cpUtf8);\r\n cp_Class.add(cpClass);\r\n stringsToCpClass.put(className, cpClass);\r\n }\r\n }\r\n cpClasses.add(cpClass);\r\n }\r\n signatureUTF8 = getCPUtf8(signatureString.toString());\r\n } else {\r\n signatureUTF8 = getCPUtf8(signature);\r\n }\r\n cpS = new CPSignature(signature, signatureUTF8, cpClasses);\r\n cp_Signature.add(cpS);\r\n stringsToCpSignature.put(signature, cpS);\r\n }\r\n return cpS;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public int compareToScaleTen(UnsignedInt128 o, short tenScale){\r\n if (tenScale == 0) {\r\n return compareTo(o);\r\n }\r\n if (o.isZero()) {\r\n return this.isZero() ? 0 : 1;\r\n } else if (this.isZero()) {\r\n if (tenScale > 0) {\r\n return -1;\r\n }\r\n if (tenScale < -SqlMathUtil.MAX_POWER_TEN_INT128) {\r\n return 0;\r\n } else {\r\n boolean oZero = o.compareTo(SqlMathUtil.ROUND_POWER_TENS_INT128[-tenScale]) < 0;\r\n return oZero ? 0 : -1;\r\n }\r\n }\r\n if (this.fitsInt32() && o.fitsInt32() && tenScale <= SqlMathUtil.MAX_POWER_TEN_INT31) {\r\n long v0Long = this.v[0] & SqlMathUtil.LONG_MASK;\r\n long o0;\r\n if (tenScale < 0) {\r\n if (tenScale < -SqlMathUtil.MAX_POWER_TEN_INT31) {\r\n o0 = 0L;\r\n } else {\r\n o0 = (o.v[0] & SqlMathUtil.LONG_MASK) / SqlMathUtil.POWER_TENS_INT31[-tenScale];\r\n long remainder = (o.v[0] & SqlMathUtil.LONG_MASK) % SqlMathUtil.POWER_TENS_INT31[-tenScale];\r\n if (remainder >= SqlMathUtil.ROUND_POWER_TENS_INT31[-tenScale]) {\r\n assert (o0 >= 0);\r\n ++o0;\r\n }\r\n }\r\n } else {\r\n o0 = (o.v[0] & SqlMathUtil.LONG_MASK) * (SqlMathUtil.POWER_TENS_INT31[tenScale] & SqlMathUtil.LONG_MASK);\r\n }\r\n return SqlMathUtil.compareUnsignedLong(v0Long, o0);\r\n }\r\n int[] ov = o.v.clone();\r\n if (tenScale < 0) {\r\n scaleDownTenArray4RoundUp(ov, (short) -tenScale);\r\n } else {\r\n boolean overflow = scaleUpTenArray(ov, tenScale);\r\n if (overflow) {\r\n return -1;\r\n }\r\n }\r\n return compareTo(ov);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BaseDescr conditionalBranch(CEDescrBuilder ce, ConditionalBranchDescrBuilder conditionalBranch) throws RecognitionException{\r\n if (conditionalBranch == null) {\r\n conditionalBranch = helper.start(ce, ConditionalBranchDescrBuilder.class, null);\r\n }\r\n try {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.IF, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n EvalDescrBuilder eval = conditionalBranch.condition();\r\n if (!parseEvalExpression(eval))\r\n return null;\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.DO)) {\r\n if (namedConsequence(null, conditionalBranch.consequence()) == null)\r\n return null;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.BREAK)) {\r\n if (breakingNamedConsequence(null, conditionalBranch.consequence()) == null)\r\n return null;\r\n } else {\r\n return null;\r\n }\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.ELSE)) {\r\n match(input, DRL6Lexer.ID, DroolsSoftKeywords.ELSE, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n ConditionalBranchDescrBuilder elseBranch = conditionalBranch.otherwise();\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.DO)) {\r\n if (namedConsequence(null, elseBranch.consequence()) == null)\r\n return null;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.BREAK)) {\r\n if (breakingNamedConsequence(null, elseBranch.consequence()) == null)\r\n return null;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.IF)) {\r\n if (conditionalBranch(null, elseBranch) == null)\r\n return null;\r\n } else {\r\n return null;\r\n }\r\n }\r\n } finally {\r\n helper.end(ConditionalBranchDescrBuilder.class, conditionalBranch);\r\n }\r\n return conditionalBranch.getDescr();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void removeNewPaths(InternalWorkingMemory wm, List pmems){\r\n Set visitedNodes = new HashSet<>();\r\n for (PathMemory pmem : pmems) {\r\n LeftTupleSink tipNode = pmem.getPathEndNode();\r\n LeftTupleNode child = tipNode;\r\n LeftTupleNode parent = tipNode.getLeftTupleSource();\r\n while (true) {\r\n if (child.getAssociatedTerminalsSize() == 1 && NodeTypeEnums.isBetaNode(child)) {\r\n deleteRightInputData((LeftTupleSink) child, wm);\r\n }\r\n if (parent != null && parent.getAssociatedTerminalsSize() != 1 && child.getAssociatedTerminalsSize() == 1) {\r\n if (!visitedNodes.contains(child.getId())) {\r\n Memory mem = wm.getNodeMemories().peekNodeMemory(parent);\r\n if (mem != null && mem.getSegmentMemory() != null) {\r\n SegmentMemory sm = mem.getSegmentMemory();\r\n if (sm.getFirst() != null) {\r\n SegmentMemory childSm = wm.getNodeMemories().peekNodeMemory(child).getSegmentMemory();\r\n sm.remove(childSm);\r\n }\r\n }\r\n }\r\n } else {\r\n Memory mem = wm.getNodeMemories().peekNodeMemory(child);\r\n if (mem != null) {\r\n SegmentMemory sm = mem.getSegmentMemory();\r\n if (sm != null && sm.getPathMemories().contains(pmem)) {\r\n mem.getSegmentMemory().removePathMemory(pmem);\r\n }\r\n }\r\n }\r\n if (parent == null) {\r\n break;\r\n }\r\n visitedNodes.add(child.getId());\r\n child = parent;\r\n parent = parent.getLeftTupleSource();\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Type defineType(String type){\r\n if (type == null) {\r\n return Type.NULL;\r\n } else if (type.equalsIgnoreCase(\"INT\") || type.equalsIgnoreCase(\"INTEGER\") || type.equalsIgnoreCase(\"BIGINT\") || type.equalsIgnoreCase(\"SMALLINT\") || type.equalsIgnoreCase(\"TINYINT\") || type.equalsIgnoreCase(\"BINARY_INTEGER\") || type.equalsIgnoreCase(\"PLS_INTEGER\") || type.equalsIgnoreCase(\"SIMPLE_INTEGER\") || type.equalsIgnoreCase(\"INT2\") || type.equalsIgnoreCase(\"INT4\") || type.equalsIgnoreCase(\"INT8\")) {\r\n return Type.BIGINT;\r\n } else if (type.equalsIgnoreCase(\"CHAR\") || type.equalsIgnoreCase(\"VARCHAR\") || type.equalsIgnoreCase(\"VARCHAR2\") || type.equalsIgnoreCase(\"STRING\") || type.equalsIgnoreCase(\"XML\") || type.equalsIgnoreCase(\"CHARACTER\")) {\r\n return Type.STRING;\r\n } else if (type.equalsIgnoreCase(\"DEC\") || type.equalsIgnoreCase(\"DECIMAL\") || type.equalsIgnoreCase(\"NUMERIC\") || type.equalsIgnoreCase(\"NUMBER\")) {\r\n return Type.DECIMAL;\r\n } else if (type.equalsIgnoreCase(\"REAL\") || type.equalsIgnoreCase(\"FLOAT\") || type.toUpperCase().startsWith(\"DOUBLE\") || type.equalsIgnoreCase(\"BINARY_FLOAT\") || type.toUpperCase().startsWith(\"BINARY_DOUBLE\") || type.equalsIgnoreCase(\"SIMPLE_FLOAT\") || type.toUpperCase().startsWith(\"SIMPLE_DOUBLE\")) {\r\n return Type.DOUBLE;\r\n } else if (type.equalsIgnoreCase(\"DATE\")) {\r\n return Type.DATE;\r\n } else if (type.equalsIgnoreCase(\"TIMESTAMP\")) {\r\n return Type.TIMESTAMP;\r\n } else if (type.equalsIgnoreCase(\"BOOL\") || type.equalsIgnoreCase(\"BOOLEAN\")) {\r\n return Type.BOOL;\r\n } else if (type.equalsIgnoreCase(\"SYS_REFCURSOR\")) {\r\n return Type.CURSOR;\r\n } else if (type.equalsIgnoreCase(\"UTL_FILE.FILE_TYPE\")) {\r\n return Type.FILE;\r\n } else if (type.toUpperCase().startsWith(\"RESULT_SET_LOCATOR\")) {\r\n return Type.RS_LOCATOR;\r\n } else if (type.equalsIgnoreCase(Var.DERIVED_TYPE)) {\r\n return Type.DERIVED_TYPE;\r\n } else if (type.equalsIgnoreCase(Type.HPL_OBJECT.name())) {\r\n return Type.HPL_OBJECT;\r\n } else if (type.equalsIgnoreCase(Type.ROW.name())) {\r\n return Type.ROW;\r\n }\r\n return Type.NULL;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void addAuthRelatedRecords(OpenAPI openAPI) throws BallerinaOpenApiException{\r\n List nodes = new ArrayList<>();\r\n if (openAPI.getComponents() != null) {\r\n if (openAPI.getComponents().getSecuritySchemes() != null) {\r\n Map securitySchemeMap = openAPI.getComponents().getSecuritySchemes();\r\n setAuthTypes(securitySchemeMap);\r\n }\r\n if (openAPI.getExtensions() != null && openAPI.getExtensions().containsKey(X_BALLERINA_HTTP_CONFIGURATIONS)) {\r\n LinkedHashMap extFields = (LinkedHashMap) openAPI.getExtensions().get(X_BALLERINA_HTTP_CONFIGURATIONS);\r\n if (extFields.containsKey(HTTP_VERIONS_EXT)) {\r\n String httpVersion = extFields.get(HTTP_VERIONS_EXT);\r\n if (httpVersion != null && HTTP_VERSION_MAP.containsKey(httpVersion)) {\r\n this.httpVersion = HTTP_VERSION_MAP.get(httpVersion);\r\n }\r\n }\r\n }\r\n TypeDefinitionNode connectionConfigRecord = generateConnectionConfigRecord();\r\n TypeDefinitionNode clientHttp1SettingsRecord = getClientHttp1SettingsRecord();\r\n TypeDefinitionNode customProxyConfigRecord = getCustomProxyRecord();\r\n nodes.addAll(Arrays.asList(connectionConfigRecord, clientHttp1SettingsRecord, customProxyConfigRecord));\r\n if (isApiKey()) {\r\n nodes.add(generateApiKeysConfig());\r\n }\r\n if (clientCredGrantTokenUrl != null) {\r\n nodes.add(getOAuth2ClientCredsGrantConfigRecord());\r\n }\r\n if (passwordGrantTokenUrl != null) {\r\n nodes.add(getOAuth2PasswordGrantConfigRecord());\r\n }\r\n if (refreshTokenUrl != null) {\r\n nodes.add(getOAuth2RefreshTokenGrantConfigRecord());\r\n }\r\n }\r\n this.authRelatedTypeDefinitionNodes = nodes;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static List getNumberAnnotFields(Schema numberSchema){\r\n List fields = new ArrayList<>();\r\n boolean isInt = numberSchema instanceof IntegerSchema;\r\n if (numberSchema.getMinimum() != null && numberSchema.getExclusiveMinimum() == null) {\r\n String value = numberSchema.getMinimum().toString();\r\n String fieldRef = GeneratorConstants.MINIMUM + GeneratorConstants.COLON + (isInt ? numberSchema.getMinimum().intValue() : value);\r\n fields.add(fieldRef);\r\n }\r\n if (numberSchema.getMaximum() != null && numberSchema.getExclusiveMaximum() == null) {\r\n String value = numberSchema.getMaximum().toString();\r\n String fieldRef = GeneratorConstants.MAXIMUM + GeneratorConstants.COLON + (isInt ? numberSchema.getMaximum().intValue() : value);\r\n fields.add(fieldRef);\r\n }\r\n if (numberSchema.getExclusiveMinimum() != null && numberSchema.getExclusiveMinimum() && numberSchema.getMinimum() != null) {\r\n String value = numberSchema.getMinimum().toString();\r\n String fieldRef = GeneratorConstants.EXCLUSIVE_MIN + GeneratorConstants.COLON + (isInt ? numberSchema.getMinimum().intValue() : value);\r\n fields.add(fieldRef);\r\n }\r\n if (numberSchema.getExclusiveMaximum() != null && numberSchema.getExclusiveMaximum() && numberSchema.getMaximum() != null) {\r\n String value = numberSchema.getMaximum().toString();\r\n String fieldRef = GeneratorConstants.EXCLUSIVE_MAX + GeneratorConstants.COLON + (isInt ? numberSchema.getMaximum().intValue() : value);\r\n fields.add(fieldRef);\r\n }\r\n return fields;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doRun(){\r\n BlockingQueue queue = getEndpoint().getQueue();\r\n while (queue != null && isRunAllowed()) {\r\n if (getEndpoint().getCamelContext().getStatus().isStarting()) {\r\n LOG.trace(\"CamelContext is starting so skip polling\");\r\n try {\r\n Thread.sleep(Math.min(pollTimeout, 1000));\r\n } catch (InterruptedException e) {\r\n LOG.debug(\"Sleep interrupted, are we stopping? {}\", isStopping() || isStopped());\r\n }\r\n continue;\r\n }\r\n if (isSuspending() || isSuspended() || isStarting()) {\r\n if (shutdownPending && queue.isEmpty()) {\r\n LOG.trace(\"Consumer is suspended and shutdown is pending, so this consumer thread is breaking out because the task queue is empty.\");\r\n break;\r\n } else {\r\n LOG.trace(\"Consumer is suspended so skip polling\");\r\n try {\r\n Thread.sleep(Math.min(pollTimeout, 1000));\r\n } catch (InterruptedException e) {\r\n LOG.debug(\"Sleep interrupted, are we stopping? {}\", isStopping() || isStopped());\r\n }\r\n continue;\r\n }\r\n }\r\n Exchange exchange = null;\r\n try {\r\n exchange = queue.poll(pollTimeout, TimeUnit.MILLISECONDS);\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\"Polled queue {} with timeout {} ms. -> {}\", ObjectHelper.getIdentityHashCode(queue), pollTimeout, exchange);\r\n }\r\n if (exchange != null) {\r\n try {\r\n Exchange newExchange = prepareExchange(exchange);\r\n sendToConsumers(newExchange);\r\n ExchangeHelper.copyResults(exchange, newExchange);\r\n if (exchange.getException() != null) {\r\n getExceptionHandler().handleException(\"Error processing exchange\", exchange, exchange.getException());\r\n }\r\n } catch (Exception e) {\r\n getExceptionHandler().handleException(\"Error processing exchange\", exchange, e);\r\n }\r\n } else if (shutdownPending && queue.isEmpty()) {\r\n LOG.trace(\"Shutdown is pending, so this consumer thread is breaking out because the task queue is empty.\");\r\n break;\r\n }\r\n } catch (InterruptedException e) {\r\n LOG.debug(\"Sleep interrupted, are we stopping? {}\", isStopping() || isStopped());\r\n continue;\r\n } catch (Exception e) {\r\n if (exchange != null) {\r\n getExceptionHandler().handleException(\"Error processing exchange\", exchange, e);\r\n } else {\r\n getExceptionHandler().handleException(e);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void createInstance(Exchange exchange, ClientConfigurations clientConfigurations) throws JsonProcessingException{\r\n CreateInstanceRequestBody body = null;\r\n Object exchangeBody = exchange.getMessage().getBody();\r\n if (exchangeBody instanceof CreateInstanceRequestBody) {\r\n body = (CreateInstanceRequestBody) exchangeBody;\r\n } else if (exchangeBody instanceof String) {\r\n String strBody = (String) exchangeBody;\r\n try {\r\n body = mapper.readValue(strBody, CreateInstanceRequestBody.class);\r\n } catch (JsonProcessingException e) {\r\n LOG.warn(\"String request body must be a valid JSON representation of a CreateInstanceRequestBody. Attempting to create an instance from endpoint parameters\");\r\n }\r\n }\r\n if (body == null) {\r\n if (ObjectHelper.isEmpty(clientConfigurations.getName())) {\r\n throw new IllegalArgumentException(\"Name is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getEngine())) {\r\n throw new IllegalArgumentException(\"Engine is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getEngineVersion())) {\r\n throw new IllegalArgumentException(\"Engine version is mandatory to create an instance\");\r\n }\r\n if (clientConfigurations.getEngine().equals(DMSConstants.KAFKA)) {\r\n if (ObjectHelper.isEmpty(clientConfigurations.getSpecification())) {\r\n throw new IllegalArgumentException(\"Specification is mandatory to create a Kafka instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getPartitionNum())) {\r\n throw new IllegalArgumentException(\"Partition number is mandatory to create a Kafka instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getKafkaManagerUser())) {\r\n throw new IllegalArgumentException(\"Kafka manager user is mandatory to create a Kafka instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getKafkaManagerPassword())) {\r\n throw new IllegalArgumentException(\"Kafka manager password is mandatory to create a Kafka instance\");\r\n }\r\n } else if (clientConfigurations.getEngine().equals(DMSConstants.RABBITMQ)) {\r\n if (ObjectHelper.isEmpty(clientConfigurations.getAccessUser())) {\r\n throw new IllegalArgumentException(\"Access user is mandatory to create a RabbitMQ instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getPassword())) {\r\n throw new IllegalArgumentException(\"Password is mandatory to create a RabbitMQ instance\");\r\n }\r\n } else {\r\n throw new IllegalArgumentException(\"Engine must be 'kafka' or 'rabbitmq'\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getStorageSpace())) {\r\n throw new IllegalArgumentException(\"Storage space is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getVpcId())) {\r\n throw new IllegalArgumentException(\"VPC ID is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getSecurityGroupId())) {\r\n throw new IllegalArgumentException(\"Security group ID is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getSubnetId())) {\r\n throw new IllegalArgumentException(\"Subnet ID is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getAvailableZones())) {\r\n throw new IllegalArgumentException(\"Available zones is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getProductId())) {\r\n throw new IllegalArgumentException(\"Product ID is mandatory to create an instance\");\r\n }\r\n if (ObjectHelper.isEmpty(clientConfigurations.getStorageSpecCode())) {\r\n throw new IllegalArgumentException(\"Storage spec code is mandatory to create an instance\");\r\n }\r\n body = new CreateInstanceRequestBody().withName(clientConfigurations.getName()).withEngine(clientConfigurations.getEngine()).withEngineVersion(clientConfigurations.getEngineVersion()).withSpecification(clientConfigurations.getSpecification()).withStorageSpace(clientConfigurations.getStorageSpace()).withPartitionNum(clientConfigurations.getPartitionNum()).withAccessUser(clientConfigurations.getAccessUser()).withPassword(clientConfigurations.getPassword()).withVpcId(clientConfigurations.getVpcId()).withSecurityGroupId(clientConfigurations.getSecurityGroupId()).withSubnetId(clientConfigurations.getSubnetId()).withAvailableZones(clientConfigurations.getAvailableZones()).withProductId(clientConfigurations.getProductId()).withKafkaManagerUser(clientConfigurations.getKafkaManagerUser()).withKafkaManagerPassword(clientConfigurations.getKafkaManagerPassword()).withStorageSpecCode(clientConfigurations.getStorageSpecCode());\r\n }\r\n CreateInstanceRequest request = new CreateInstanceRequest().withBody(body);\r\n CreateInstanceResponse response = dmsClient.createInstance(request);\r\n exchange.getMessage().setBody(mapper.writeValueAsString(response));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private MetadataBandGroup[] parseMetadata(final InputStream in, final String[] RxA, final int[] RxACount, final int[] backwardsCallCounts, final String contextName) throws IOException, Pack200Exception{\r\n final MetadataBandGroup[] mbg = new MetadataBandGroup[RxA.length];\r\n for (int i = 0; i < RxA.length; i++) {\r\n mbg[i] = new MetadataBandGroup(RxA[i], cpBands);\r\n final String rxa = RxA[i];\r\n if (rxa.indexOf('P') >= 0) {\r\n mbg[i].param_NB = decodeBandInt(contextName + \"_\" + rxa + \"_param_NB\", in, Codec.BYTE1, RxACount[i]);\r\n }\r\n int pairCount = 0;\r\n if (!rxa.equals(\"AD\")) {\r\n mbg[i].anno_N = decodeBandInt(contextName + \"_\" + rxa + \"_anno_N\", in, Codec.UNSIGNED5, RxACount[i]);\r\n mbg[i].type_RS = parseCPSignatureReferences(contextName + \"_\" + rxa + \"_type_RS\", in, Codec.UNSIGNED5, mbg[i].anno_N);\r\n mbg[i].pair_N = decodeBandInt(contextName + \"_\" + rxa + \"_pair_N\", in, Codec.UNSIGNED5, mbg[i].anno_N);\r\n for (final int[] element : mbg[i].pair_N) {\r\n for (final int element2 : element) {\r\n pairCount += element2;\r\n }\r\n }\r\n mbg[i].name_RU = parseCPUTF8References(contextName + \"_\" + rxa + \"_name_RU\", in, Codec.UNSIGNED5, pairCount);\r\n } else {\r\n pairCount = RxACount[i];\r\n }\r\n mbg[i].T = decodeBandInt(contextName + \"_\" + rxa + \"_T\", in, Codec.BYTE1, pairCount + backwardsCallCounts[i]);\r\n int ICount = 0, DCount = 0, FCount = 0, JCount = 0, cCount = 0, eCount = 0, sCount = 0, arrayCount = 0, atCount = 0;\r\n for (final int element : mbg[i].T) {\r\n final char c = (char) element;\r\n switch(c) {\r\n case 'B':\r\n case 'C':\r\n case 'I':\r\n case 'S':\r\n case 'Z':\r\n ICount++;\r\n break;\r\n case 'D':\r\n DCount++;\r\n break;\r\n case 'F':\r\n FCount++;\r\n break;\r\n case 'J':\r\n JCount++;\r\n break;\r\n case 'c':\r\n cCount++;\r\n break;\r\n case 'e':\r\n eCount++;\r\n break;\r\n case 's':\r\n sCount++;\r\n break;\r\n case '[':\r\n arrayCount++;\r\n break;\r\n case '@':\r\n atCount++;\r\n break;\r\n }\r\n }\r\n mbg[i].caseI_KI = parseCPIntReferences(contextName + \"_\" + rxa + \"_caseI_KI\", in, Codec.UNSIGNED5, ICount);\r\n mbg[i].caseD_KD = parseCPDoubleReferences(contextName + \"_\" + rxa + \"_caseD_KD\", in, Codec.UNSIGNED5, DCount);\r\n mbg[i].caseF_KF = parseCPFloatReferences(contextName + \"_\" + rxa + \"_caseF_KF\", in, Codec.UNSIGNED5, FCount);\r\n mbg[i].caseJ_KJ = parseCPLongReferences(contextName + \"_\" + rxa + \"_caseJ_KJ\", in, Codec.UNSIGNED5, JCount);\r\n mbg[i].casec_RS = parseCPSignatureReferences(contextName + \"_\" + rxa + \"_casec_RS\", in, Codec.UNSIGNED5, cCount);\r\n mbg[i].caseet_RS = parseReferences(contextName + \"_\" + rxa + \"_caseet_RS\", in, Codec.UNSIGNED5, eCount, cpBands.getCpSignature());\r\n mbg[i].caseec_RU = parseReferences(contextName + \"_\" + rxa + \"_caseec_RU\", in, Codec.UNSIGNED5, eCount, cpBands.getCpUTF8());\r\n mbg[i].cases_RU = parseCPUTF8References(contextName + \"_\" + rxa + \"_cases_RU\", in, Codec.UNSIGNED5, sCount);\r\n mbg[i].casearray_N = decodeBandInt(contextName + \"_\" + rxa + \"_casearray_N\", in, Codec.UNSIGNED5, arrayCount);\r\n mbg[i].nesttype_RS = parseCPUTF8References(contextName + \"_\" + rxa + \"_nesttype_RS\", in, Codec.UNSIGNED5, atCount);\r\n mbg[i].nestpair_N = decodeBandInt(contextName + \"_\" + rxa + \"_nestpair_N\", in, Codec.UNSIGNED5, atCount);\r\n int nestPairCount = 0;\r\n for (final int element : mbg[i].nestpair_N) {\r\n nestPairCount += element;\r\n }\r\n mbg[i].nestname_RU = parseCPUTF8References(contextName + \"_\" + rxa + \"_nestname_RU\", in, Codec.UNSIGNED5, nestPairCount);\r\n }\r\n return mbg;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void handleNode(Node node, String nodeName){\r\n if (matches(SECURITY.getName(), nodeName)) {\r\n handleSecurity(node);\r\n } else if (matches(PROXY_FACTORIES.getName(), nodeName)) {\r\n handleProxyFactories(node);\r\n } else if (matches(PROPERTIES.getName(), nodeName)) {\r\n fillProperties(node, clientConfig.getProperties());\r\n } else if (matches(SERIALIZATION.getName(), nodeName)) {\r\n handleSerialization(node);\r\n } else if (matches(NATIVE_MEMORY.getName(), nodeName)) {\r\n fillNativeMemoryConfig(node, clientConfig.getNativeMemoryConfig());\r\n } else if (matches(LISTENERS.getName(), nodeName)) {\r\n handleListeners(node);\r\n } else if (matches(NETWORK.getName(), nodeName)) {\r\n handleNetwork(node);\r\n } else if (matches(LOAD_BALANCER.getName(), nodeName)) {\r\n handleLoadBalancer(node);\r\n } else if (matches(NEAR_CACHE.getName(), nodeName)) {\r\n handleNearCache(node);\r\n } else if (matches(QUERY_CACHES.getName(), nodeName)) {\r\n queryCacheConfigBuilderHelper.handleQueryCache(clientConfig, node);\r\n } else if (matches(INSTANCE_NAME.getName(), nodeName)) {\r\n clientConfig.setInstanceName(getTextContent(node));\r\n } else if (matches(CONNECTION_STRATEGY.getName(), nodeName)) {\r\n handleConnectionStrategy(node);\r\n } else if (matches(USER_CODE_DEPLOYMENT.getName(), nodeName)) {\r\n handleUserCodeDeployment(node);\r\n } else if (matches(FLAKE_ID_GENERATOR.getName(), nodeName)) {\r\n handleFlakeIdGenerator(node);\r\n } else if (matches(RELIABLE_TOPIC.getName(), nodeName)) {\r\n handleReliableTopic(node);\r\n } else if (matches(LABELS.getName(), nodeName)) {\r\n handleLabels(node);\r\n } else if (matches(BACKUP_ACK_TO_CLIENT.getName(), nodeName)) {\r\n handleBackupAckToClient(node);\r\n } else if (matches(CLUSTER_NAME.getName(), nodeName)) {\r\n clientConfig.setClusterName(getTextContent(node));\r\n } else if (matches(METRICS.getName(), nodeName)) {\r\n handleMetrics(node);\r\n } else if (matches(INSTANCE_TRACKING.getName(), nodeName)) {\r\n handleInstanceTracking(node, clientConfig.getInstanceTrackingConfig());\r\n } else if (matches(SQL.getName(), nodeName)) {\r\n handleSql(node, clientConfig.getSqlConfig());\r\n } else if (matches(TPC.getName(), nodeName)) {\r\n handleTpc(node, clientConfig.getTpcConfig());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void applyProductContentChanges(Product entity, ProductInfo update, Map contentMap){\r\n Collection updateProductContent = update.getProductContent();\r\n if (updateProductContent != null) {\r\n Map productContentMap = new HashMap<>();\r\n for (ProductContentInfo pcinfo : updateProductContent) {\r\n if (pcinfo == null) {\r\n throw new IllegalStateException(\"product contains a null product-content reference\");\r\n }\r\n ContentInfo cinfo = pcinfo.getContent();\r\n if (cinfo == null || cinfo.getId() == null) {\r\n throw new IllegalStateException(\"product contains an incomplete product-content reference: \" + pcinfo);\r\n }\r\n Content resolved = contentMap.get(cinfo.getId());\r\n if (resolved == null) {\r\n throw new IllegalStateException(\"cannot resolve content reference: \" + cinfo);\r\n }\r\n boolean enabled = pcinfo.isEnabled() != null ? pcinfo.isEnabled() : false;\r\n productContentMap.put(resolved.getId(), new ProductContent(entity, resolved, enabled));\r\n }\r\n entity.setProductContent(productContentMap.values());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List generateFlowNodeListByStartNode(List taskNodeList, List startNodeNameList, List recoveryNodeCodeList, TaskDependType taskDependType){\r\n List destFlowNodeList = new ArrayList<>();\r\n List startNodeList = startNodeNameList;\r\n if (taskDependType != TaskDependType.TASK_POST && CollectionUtils.isEmpty(startNodeList)) {\r\n log.error(\"start node list is empty! cannot continue run the process \");\r\n return destFlowNodeList;\r\n }\r\n List destTaskNodeList = new ArrayList<>();\r\n List tmpTaskNodeList = new ArrayList<>();\r\n if (taskDependType == TaskDependType.TASK_POST && CollectionUtils.isNotEmpty(recoveryNodeCodeList)) {\r\n startNodeList = recoveryNodeCodeList;\r\n }\r\n if (CollectionUtils.isEmpty(startNodeList)) {\r\n tmpTaskNodeList = taskNodeList;\r\n } else {\r\n for (Long startNodeCode : startNodeList) {\r\n TaskNode startNode = findNodeByCode(taskNodeList, startNodeCode);\r\n List childNodeList = new ArrayList<>();\r\n if (startNode == null) {\r\n log.error(\"start node name [{}] is not in task node list [{}] \", startNodeCode, taskNodeList);\r\n continue;\r\n } else if (TaskDependType.TASK_POST == taskDependType) {\r\n List visitedNodeCodeList = new ArrayList<>();\r\n childNodeList = getFlowNodeListPost(startNode, taskNodeList, visitedNodeCodeList);\r\n } else if (TaskDependType.TASK_PRE == taskDependType) {\r\n List visitedNodeCodeList = new ArrayList<>();\r\n childNodeList = getFlowNodeListPre(startNode, recoveryNodeCodeList, taskNodeList, visitedNodeCodeList);\r\n } else {\r\n childNodeList.add(startNode);\r\n }\r\n tmpTaskNodeList.addAll(childNodeList);\r\n }\r\n }\r\n for (TaskNode taskNode : tmpTaskNodeList) {\r\n if (null == findNodeByCode(destTaskNodeList, taskNode.getCode())) {\r\n destTaskNodeList.add(taskNode);\r\n }\r\n }\r\n return destTaskNodeList;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List matchByConnObjectKeyValue(final Item connObjectKeyItem, final String connObjectKeyValue, final AnyTypeKind anyTypeKind, final boolean ignoreCaseMatch, final ExternalResource resource){\r\n String finalConnObjectKeyValue = connObjectKeyValue;\r\n for (ItemTransformer transformer : MappingUtils.getItemTransformers(connObjectKeyItem, getTransformers(connObjectKeyItem))) {\r\n List output = transformer.beforePull(connObjectKeyItem, null, List.of(finalConnObjectKeyValue));\r\n if (!CollectionUtils.isEmpty(output)) {\r\n finalConnObjectKeyValue = output.get(0).toString();\r\n }\r\n }\r\n List noMatchResult = List.of(PullCorrelationRule.NO_MATCH);\r\n IntAttrName intAttrName;\r\n try {\r\n intAttrName = intAttrNameParser.parse(connObjectKeyItem.getIntAttrName(), anyTypeKind);\r\n } catch (ParseException e) {\r\n LOG.error(\"Invalid intAttrName '{}' specified, ignoring\", connObjectKeyItem.getIntAttrName(), e);\r\n return noMatchResult;\r\n }\r\n AnyUtils anyUtils = anyUtilsFactory.getInstance(anyTypeKind);\r\n List> anys = new ArrayList<>();\r\n if (intAttrName.getField() != null) {\r\n switch(intAttrName.getField()) {\r\n case \"key\":\r\n Optional.ofNullable(anyUtils.dao().find(finalConnObjectKeyValue)).ifPresent(anys::add);\r\n break;\r\n case \"username\":\r\n if (anyTypeKind == AnyTypeKind.USER && ignoreCaseMatch) {\r\n AnyCond cond = new AnyCond(AttrCond.Type.IEQ);\r\n cond.setSchema(\"username\");\r\n cond.setExpression(finalConnObjectKeyValue);\r\n anys.addAll(anySearchDAO.search(SearchCond.getLeaf(cond), AnyTypeKind.USER));\r\n } else {\r\n Optional.ofNullable(userDAO.findByUsername(finalConnObjectKeyValue)).ifPresent(anys::add);\r\n }\r\n break;\r\n case \"name\":\r\n if (anyTypeKind == AnyTypeKind.GROUP && ignoreCaseMatch) {\r\n AnyCond cond = new AnyCond(AttrCond.Type.IEQ);\r\n cond.setSchema(\"name\");\r\n cond.setExpression(finalConnObjectKeyValue);\r\n anys.addAll(anySearchDAO.search(SearchCond.getLeaf(cond), AnyTypeKind.GROUP));\r\n } else {\r\n Optional.ofNullable(groupDAO.findByName(finalConnObjectKeyValue)).ifPresent(anys::add);\r\n }\r\n if (anyTypeKind == AnyTypeKind.ANY_OBJECT && ignoreCaseMatch) {\r\n AnyCond cond = new AnyCond(AttrCond.Type.IEQ);\r\n cond.setSchema(\"name\");\r\n cond.setExpression(finalConnObjectKeyValue);\r\n anys.addAll(anySearchDAO.search(SearchCond.getLeaf(cond), AnyTypeKind.ANY_OBJECT));\r\n } else {\r\n anys.addAll(anyObjectDAO.findByName(finalConnObjectKeyValue));\r\n }\r\n break;\r\n default:\r\n }\r\n } else if (intAttrName.getSchemaType() != null) {\r\n switch(intAttrName.getSchemaType()) {\r\n case PLAIN:\r\n PlainAttrValue value = intAttrName.getSchema().isUniqueConstraint() ? anyUtils.newPlainAttrUniqueValue() : anyUtils.newPlainAttrValue();\r\n try {\r\n value.parseValue((PlainSchema) intAttrName.getSchema(), finalConnObjectKeyValue);\r\n } catch (ParsingValidationException e) {\r\n LOG.error(\"While parsing provided {} {}\", Uid.NAME, value, e);\r\n value.setStringValue(finalConnObjectKeyValue);\r\n }\r\n if (intAttrName.getSchema().isUniqueConstraint()) {\r\n anyUtils.dao().findByPlainAttrUniqueValue((PlainSchema) intAttrName.getSchema(), (PlainAttrUniqueValue) value, ignoreCaseMatch).ifPresent(anys::add);\r\n } else {\r\n anys.addAll(anyUtils.dao().findByPlainAttrValue((PlainSchema) intAttrName.getSchema(), value, ignoreCaseMatch));\r\n }\r\n break;\r\n case DERIVED:\r\n anys.addAll(anyUtils.dao().findByDerAttrValue((DerSchema) intAttrName.getSchema(), finalConnObjectKeyValue, ignoreCaseMatch));\r\n break;\r\n default:\r\n }\r\n }\r\n List result = anys.stream().map(any -> new PullMatch(MatchType.ANY, any)).collect(Collectors.toList());\r\n if (resource != null) {\r\n userDAO.findLinkedAccount(resource, finalConnObjectKeyValue).map(account -> new PullMatch(MatchType.LINKED_ACCOUNT, account)).ifPresent(result::add);\r\n }\r\n return result.isEmpty() ? noMatchResult : result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateStoreOnExecution(RootProcedureStack rootProcStack, Procedure proc, Procedure[] subprocs){\r\n if (subprocs != null && !proc.isFailed()) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Stored {}, children {}\", proc, Arrays.toString(subprocs));\r\n }\r\n store.update(subprocs);\r\n } else {\r\n LOG.debug(\"Store update {}\", proc);\r\n if (proc.isFinished() && !proc.hasParent()) {\r\n final long[] childProcIds = rootProcStack.getSubprocedureIds();\r\n if (childProcIds != null) {\r\n store.delete(childProcIds);\r\n for (long childProcId : childProcIds) {\r\n procedures.remove(childProcId);\r\n }\r\n } else {\r\n store.update(proc);\r\n }\r\n } else {\r\n store.update(proc);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Object freeze(ColumnLoader.ValueSet valueSet, int @Nullable [] sources){\r\n final int chunksPerWord = 64 / bitCount;\r\n final List<@Nullable Comparable> valueList = permuteList(valueSet.values, sources);\r\n final int valueCount = valueList.size();\r\n final int wordCount = (valueCount + (chunksPerWord - 1)) / chunksPerWord;\r\n final int remainingChunkCount = valueCount % chunksPerWord;\r\n final long[] longs = new long[wordCount];\r\n final int n = valueCount / chunksPerWord;\r\n int i;\r\n int k = 0;\r\n if (valueCount > 0 && valueList.get(0) instanceof Boolean) {\r\n @SuppressWarnings(\"unchecked\")\r\n final List booleans = (List) valueList;\r\n for (i = 0; i < n; i++) {\r\n long v = 0;\r\n for (int j = 0; j < chunksPerWord; j++) {\r\n v |= booleans.get(k++) ? (1 << (bitCount * j)) : 0;\r\n }\r\n longs[i] = v;\r\n }\r\n if (remainingChunkCount > 0) {\r\n long v = 0;\r\n for (int j = 0; j < remainingChunkCount; j++) {\r\n v |= booleans.get(k++) ? (1 << (bitCount * j)) : 0;\r\n }\r\n longs[i] = v;\r\n }\r\n } else {\r\n @SuppressWarnings(\"unchecked\")\r\n final List numbers = (List) valueList;\r\n for (i = 0; i < n; i++) {\r\n long v = 0;\r\n for (int j = 0; j < chunksPerWord; j++) {\r\n v |= numbers.get(k++).longValue() << (bitCount * j);\r\n }\r\n longs[i] = v;\r\n }\r\n if (remainingChunkCount > 0) {\r\n long v = 0;\r\n for (int j = 0; j < remainingChunkCount; j++) {\r\n v |= numbers.get(k++).longValue() << (bitCount * j);\r\n }\r\n longs[i] = v;\r\n }\r\n }\r\n return longs;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void write(OutputStream outputStream, LinkedHashMap chromosomeSequenceList) throws Exception{\r\n outputStream.write(\"##gff-version 3\\n\".getBytes());\r\n for (String key : chromosomeSequenceList.keySet()) {\r\n ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(key);\r\n String gff3line = \"\";\r\n for (GeneSequence geneSequence : chromosomeSequence.getGeneSequences().values()) {\r\n gff3line = key + \"\\t\" + geneSequence.getSource() + \"\\t\" + \"gene\" + \"\\t\" + geneSequence.getBioBegin() + \"\\t\" + geneSequence.getBioEnd() + \"\\t\";\r\n Double score = geneSequence.getSequenceScore();\r\n if (score == null) {\r\n gff3line = gff3line + \".\\t\";\r\n } else {\r\n gff3line = gff3line + score + \"\\t\";\r\n }\r\n gff3line = gff3line + geneSequence.getStrand().getStringRepresentation() + \"\\t\";\r\n gff3line = gff3line + \".\\t\";\r\n gff3line = gff3line + \"ID=\" + geneSequence.getAccession().getID() + \";Name=\" + geneSequence.getAccession().getID();\r\n gff3line = gff3line + getGFF3Note(geneSequence.getNotesList());\r\n gff3line = gff3line + \"\\n\";\r\n outputStream.write(gff3line.getBytes());\r\n int transcriptIndex = 0;\r\n for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {\r\n transcriptIndex++;\r\n gff3line = key + \"\\t\" + transcriptSequence.getSource() + \"\\t\" + \"mRNA\" + \"\\t\" + transcriptSequence.getBioBegin() + \"\\t\" + transcriptSequence.getBioEnd() + \"\\t\";\r\n score = transcriptSequence.getSequenceScore();\r\n if (score == null) {\r\n gff3line = gff3line + \".\\t\";\r\n } else {\r\n gff3line = gff3line + score + \"\\t\";\r\n }\r\n gff3line = gff3line + transcriptSequence.getStrand().getStringRepresentation() + \"\\t\";\r\n gff3line = gff3line + \".\\t\";\r\n String id = geneSequence.getAccession().getID() + \".\" + transcriptIndex;\r\n gff3line = gff3line + \"ID=\" + id + \";Parent=\" + geneSequence.getAccession().getID() + \";Name=\" + id;\r\n gff3line = gff3line + getGFF3Note(transcriptSequence.getNotesList());\r\n gff3line = gff3line + \"\\n\";\r\n outputStream.write(gff3line.getBytes());\r\n String transcriptParentName = geneSequence.getAccession().getID() + \".\" + transcriptIndex;\r\n ArrayList cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values());\r\n Collections.sort(cdsSequenceList, new SequenceComparator());\r\n for (CDSSequence cdsSequence : cdsSequenceList) {\r\n gff3line = key + \"\\t\" + cdsSequence.getSource() + \"\\t\" + \"CDS\" + \"\\t\" + cdsSequence.getBioBegin() + \"\\t\" + cdsSequence.getBioEnd() + \"\\t\";\r\n score = cdsSequence.getSequenceScore();\r\n if (score == null) {\r\n gff3line = gff3line + \".\\t\";\r\n } else {\r\n gff3line = gff3line + score + \"\\t\";\r\n }\r\n gff3line = gff3line + cdsSequence.getStrand().getStringRepresentation() + \"\\t\";\r\n gff3line = gff3line + cdsSequence.getPhase() + \"\\t\";\r\n gff3line = gff3line + \"ID=\" + cdsSequence.getAccession().getID() + \";Parent=\" + transcriptParentName;\r\n gff3line = gff3line + getGFF3Note(cdsSequence.getNotesList());\r\n gff3line = gff3line + \"\\n\";\r\n outputStream.write(gff3line.getBytes());\r\n }\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void startCQScheduler(){\r\n try {\r\n Thread.sleep(1000);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n }\r\n lock.writeLock().lock();\r\n try {\r\n try {\r\n if (executor != null) {\r\n executor.shutdown();\r\n }\r\n } catch (Exception t) {\r\n LOGGER.error(\"Error happened while shutting down previous cq schedule thread pool.\", t);\r\n }\r\n executor = IoTDBThreadPoolFactory.newScheduledThreadPool(CONF.getCqSubmitThread(), ThreadName.CQ_SCHEDULER.getName());\r\n List allCQs = null;\r\n while (configManager.getConsensusManager() == null) {\r\n try {\r\n LOGGER.info(\"consensus layer is not ready, sleep 1s...\");\r\n TimeUnit.SECONDS.sleep(1);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n LOGGER.warn(\"Unexpected interruption during waiting for consensus layer ready.\");\r\n }\r\n }\r\n while (needFetch(allCQs)) {\r\n try {\r\n DataSet response = configManager.getConsensusManager().read(new ShowCQPlan());\r\n allCQs = ((ShowCQResp) response).getCqList();\r\n } catch (ConsensusException e) {\r\n LOGGER.warn(\"Unexpected error happened while fetching cq list: \", e);\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n }\r\n }\r\n }\r\n if (allCQs != null) {\r\n for (CQInfo.CQEntry entry : allCQs) {\r\n if (entry.getState() == CQState.ACTIVE) {\r\n CQScheduleTask cqScheduleTask = new CQScheduleTask(entry, executor, configManager);\r\n cqScheduleTask.submitSelf();\r\n }\r\n }\r\n }\r\n } finally {\r\n lock.writeLock().unlock();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean send(AlertEntity alert){\r\n boolean result = false;\r\n String type = alert.getType().getName();\r\n String group = alert.getGroup();\r\n String level = alert.getLevel().getLevel();\r\n String alertKey = alert.getKey();\r\n String metric = alert.getMetric();\r\n List channels = m_policyManager.queryChannels(type, group, level);\r\n int suspendMinute = m_policyManager.querySuspendMinute(type, group, level);\r\n m_unrecoveredAlerts.put(alertKey, alert);\r\n alert.setMetric(this.resolveMetric(metric));\r\n Pair pair = m_decoratorManager.generateTitleAndContent(alert);\r\n String title = pair.getKey();\r\n if (suspendMinute > 0) {\r\n if (isSuspend(alertKey, suspendMinute)) {\r\n return true;\r\n } else {\r\n m_sendedAlerts.put(alertKey, alert);\r\n }\r\n }\r\n SendMessageEntity message = null;\r\n String linkDate = getLinkDateFormat().format(alert.getDate());\r\n String host = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();\r\n String port = CatPropertyProvider.INST.getProperty(\"server.port\", \"8080\");\r\n String viewLink = MessageFormat.format(AlertType.parseViewLink(type), host, port, group, linkDate, TOTAL_STRING.equals(alert.getMetric()) ? \"\" : Splitters.by(\"-\").split(alert.getMetric()).get(0));\r\n String settingsLink = MessageFormat.format(AlertType.parseSettingsLink(type), host, port, group, metric.replaceAll(\"-\", \";\"));\r\n for (AlertChannel channel : channels) {\r\n String contactGroup = alert.getContactGroup();\r\n List receivers = m_contactorManager.queryReceivers(contactGroup, channel, type);\r\n removeDuplicate(receivers);\r\n if (receivers.size() > 0) {\r\n String rawContent = pair.getValue();\r\n if (suspendMinute > 0) {\r\n rawContent = rawContent + \"
\u00e6\u017d\u00a8\u00e9\u20ac\ufffd\u00e9\u2014\u00b4\u00e9\u0161\u201d\u00ef\u00bc\u0161\" + suspendMinute + \"\u00e5\u02c6\u2020\u00e9\u2019\u0178\";\r\n }\r\n rawContent = rawContent + buildContactInfo(alert.getDomain());\r\n String content = m_splitterManager.process(rawContent, channel);\r\n message = new SendMessageEntity(group, title, type, content, receivers);\r\n message.setViewLink(viewLink);\r\n message.setSettingsLink(settingsLink);\r\n message.setLevel(alert.getLevel());\r\n if (m_senderManager.sendAlert(channel, message)) {\r\n result = true;\r\n }\r\n } else {\r\n Cat.logEvent(\"NoneReceiver:\" + channel, type + \":\" + contactGroup, Event.SUCCESS, null);\r\n }\r\n }\r\n String dbContent = Pattern.compile(\")\", Pattern.DOTALL).matcher(pair.getValue()).replaceAll(\"\");\r\n if (message == null) {\r\n message = new SendMessageEntity(group, title, type, \"\", null);\r\n }\r\n message.setContent(dbContent);\r\n m_alertService.insert(alert, message);\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void onSnapshotPhase1CompleteWithStartResponses(Collection> responses, long executionId, long snapshotId, SnapshotRequest requestedSnapshot, SnapshotPhase1Result mergedResult, List> missingResponses){\r\n mc.coordinationService().submitToCoordinatorThread(() -> {\r\n final boolean isSuccess;\r\n boolean skipPhase2 = false;\r\n SnapshotStats stats;\r\n mc.lock();\r\n try {\r\n if (!missingResponses.isEmpty()) {\r\n LoggingUtil.logFine(logger, \"%s all awaited responses to StartExecutionOperation received or \" + \"were already received\", mc.jobIdString());\r\n }\r\n if (executionId != mc.executionId()) {\r\n LoggingUtil.logFine(logger, \"%s: ignoring responses for snapshot %s phase 1: \" + \"the responses are from a different execution: %s. Responses: %s\", mc.jobIdString(), snapshotId, idToString(executionId), responses);\r\n return;\r\n }\r\n for (CompletableFuture response : missingResponses) {\r\n assert response.isDone() : \"response not done\";\r\n try {\r\n response.get();\r\n } catch (ExecutionException e) {\r\n mergedResult.merge(new SnapshotPhase1Result(0, 0, 0, e.getCause()));\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n }\r\n }\r\n String mapName = requestedSnapshot.mapName();\r\n IMap snapshotMap = safeImap(mc.nodeEngine().getHazelcastInstance().getMap(mapName));\r\n try {\r\n SnapshotValidationRecord validationRecord = new SnapshotValidationRecord(snapshotId, mergedResult.getNumChunks(), mergedResult.getNumBytes(), mc.jobExecutionRecord().ongoingSnapshotStartTime(), mc.jobId(), mc.jobName(), mc.jobRecord().getDagJson());\r\n Object oldValue = snapshotMap.put(SnapshotValidationRecord.KEY, validationRecord);\r\n if (requestedSnapshot.isExport()) {\r\n assert requestedSnapshot.snapshotName != null;\r\n mc.jobRepository().cacheValidationRecord(requestedSnapshot.snapshotName, validationRecord);\r\n }\r\n if (oldValue != null) {\r\n logger.severe(\"SnapshotValidationRecord overwritten after writing to '\" + mapName + \"' for \" + mc.jobIdString() + \": snapshot data might be corrupted\");\r\n }\r\n } catch (Exception e) {\r\n mergedResult.merge(new SnapshotPhase1Result(0, 0, 0, e));\r\n }\r\n isSuccess = mergedResult.getError() == null;\r\n stats = mc.jobExecutionRecord().ongoingSnapshotDone(mergedResult.getNumBytes(), mergedResult.getNumKeys(), mergedResult.getNumChunks(), mergedResult.getError(), requestedSnapshot.isTerminal);\r\n if (isSuccess && !requestedSnapshot.isExportOnly()) {\r\n try {\r\n mc.writeJobExecutionRecordSafe(false);\r\n } catch (IndeterminateOperationStateException indeterminate) {\r\n skipPhase2 = true;\r\n logger.warning(mc.jobIdString() + \" snapshot \" + snapshotId + \" update of JobExecutionRecord \" + \"was indeterminate. Will restart the job forcefully.\", indeterminate);\r\n } catch (Exception otherError) {\r\n skipPhase2 = true;\r\n logger.warning(mc.jobIdString() + \" snapshot \" + snapshotId + \" update of JobExecutionRecord failed. Will restart the job forcefully.\", otherError);\r\n }\r\n } else {\r\n mc.writeJobExecutionRecord(false);\r\n }\r\n if (logger.isFineEnabled()) {\r\n logger.fine(String.format(\"Snapshot %d phase 1 for %s completed with status %s in %dms, \" + \"%,d bytes, %,d keys in %,d chunks, stored in '%s'%s\", snapshotId, mc.jobIdString(), (skipPhase2 ? \"INDETERMINATE/\" : \"\") + (isSuccess ? \"SUCCESS\" : \"FAILURE\"), stats.duration(), stats.numBytes(), stats.numKeys(), stats.numChunks(), mapName, (skipPhase2 ? \", skipping \" : \", proceeding to \") + \"phase 2\"));\r\n }\r\n if (!isSuccess) {\r\n logger.warning(mc.jobIdString() + \" snapshot \" + snapshotId + \" phase 1 failed on some \" + \"member(s), one of the failures: \" + mergedResult.getError());\r\n try {\r\n snapshotMap.clear();\r\n } catch (Exception e) {\r\n logger.warning(mc.jobIdString() + \": failed to clear snapshot map '\" + mapName + \"' after a failure\", e);\r\n }\r\n }\r\n if (isSuccess && !skipPhase2 && !requestedSnapshot.isExport()) {\r\n mc.jobRepository().clearSnapshotData(mc.jobId(), mc.jobExecutionRecord().ongoingDataMapIndex());\r\n }\r\n } finally {\r\n mc.unlock();\r\n }\r\n if (skipPhase2) {\r\n TerminationMode newMode = TerminationMode.RESTART_FORCEFUL;\r\n logger().fine(mc.jobIdString() + \": Terminating job without performing snapshot phase 2 with mode \" + newMode);\r\n mc.jobContext().handleTermination(newMode);\r\n requestedSnapshot.completeFuture(new JetException(\"Snapshot in unknown state\"));\r\n } else {\r\n Function factory = plan -> new SnapshotPhase2Operation(mc.jobId(), executionId, snapshotId, isSuccess && !requestedSnapshot.isExportOnly());\r\n mc.invokeOnParticipants(factory, responses2 -> onSnapshotPhase2Complete(mergedResult.getError(), responses2, executionId, snapshotId, requestedSnapshot, stats.startTime()), null, true);\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SqlNode toSql(@Nullable RexProgram program, RexNode rex){\r\n final RexSubQuery subQuery;\r\n final SqlNode sqlSubQuery;\r\n final RexLiteral literal;\r\n switch(rex.getKind()) {\r\n case LOCAL_REF:\r\n final int index = ((RexLocalRef) rex).getIndex();\r\n return toSql(program, requireNonNull(program, \"program\").getExprList().get(index));\r\n case INPUT_REF:\r\n return field(((RexInputRef) rex).getIndex());\r\n case FIELD_ACCESS:\r\n final Deque accesses = new ArrayDeque<>();\r\n RexNode referencedExpr = rex;\r\n while (referencedExpr.getKind() == SqlKind.FIELD_ACCESS) {\r\n accesses.offerLast((RexFieldAccess) referencedExpr);\r\n referencedExpr = ((RexFieldAccess) referencedExpr).getReferenceExpr();\r\n }\r\n SqlIdentifier sqlIdentifier;\r\n switch(referencedExpr.getKind()) {\r\n case CORREL_VARIABLE:\r\n final RexCorrelVariable variable = (RexCorrelVariable) referencedExpr;\r\n final Context correlAliasContext = getAliasContext(variable);\r\n final RexFieldAccess lastAccess = accesses.pollLast();\r\n assert lastAccess != null;\r\n sqlIdentifier = (SqlIdentifier) correlAliasContext.field(lastAccess.getField().getIndex());\r\n break;\r\n case ROW:\r\n final SqlNode expr = toSql(program, referencedExpr);\r\n sqlIdentifier = new SqlIdentifier(expr.toString(), POS);\r\n break;\r\n default:\r\n sqlIdentifier = (SqlIdentifier) toSql(program, referencedExpr);\r\n }\r\n int nameIndex = sqlIdentifier.names.size();\r\n RexFieldAccess access;\r\n while ((access = accesses.pollLast()) != null) {\r\n sqlIdentifier = sqlIdentifier.add(nameIndex++, access.getField().getName(), POS);\r\n }\r\n return sqlIdentifier;\r\n case PATTERN_INPUT_REF:\r\n final RexPatternFieldRef ref = (RexPatternFieldRef) rex;\r\n String pv = ref.getAlpha();\r\n SqlNode refNode = field(ref.getIndex());\r\n final SqlIdentifier id = (SqlIdentifier) refNode;\r\n if (id.names.size() > 1) {\r\n return id.setName(0, pv);\r\n } else {\r\n return new SqlIdentifier(ImmutableList.of(pv, id.names.get(0)), POS);\r\n }\r\n case LITERAL:\r\n return SqlImplementor.toSql(program, (RexLiteral) rex);\r\n case CASE:\r\n final RexCall caseCall = (RexCall) rex;\r\n final List caseNodeList = toSql(program, caseCall.getOperands());\r\n final SqlNode valueNode;\r\n final List whenList = Expressions.list();\r\n final List thenList = Expressions.list();\r\n final SqlNode elseNode;\r\n if (caseNodeList.size() % 2 == 0) {\r\n valueNode = caseNodeList.get(0);\r\n for (int i = 1; i < caseNodeList.size() - 1; i += 2) {\r\n whenList.add(caseNodeList.get(i));\r\n thenList.add(caseNodeList.get(i + 1));\r\n }\r\n } else {\r\n valueNode = null;\r\n for (int i = 0; i < caseNodeList.size() - 1; i += 2) {\r\n whenList.add(caseNodeList.get(i));\r\n thenList.add(caseNodeList.get(i + 1));\r\n }\r\n }\r\n elseNode = caseNodeList.get(caseNodeList.size() - 1);\r\n return new SqlCase(POS, valueNode, new SqlNodeList(whenList, POS), new SqlNodeList(thenList, POS), elseNode);\r\n case DYNAMIC_PARAM:\r\n final RexDynamicParam caseParam = (RexDynamicParam) rex;\r\n return new SqlDynamicParam(caseParam.getIndex(), POS);\r\n case IN:\r\n subQuery = (RexSubQuery) rex;\r\n sqlSubQuery = implementor().visitRoot(subQuery.rel).asQueryOrValues();\r\n final List operands = subQuery.operands;\r\n SqlNode op0;\r\n if (operands.size() == 1) {\r\n op0 = toSql(program, operands.get(0));\r\n } else {\r\n final List cols = toSql(program, operands);\r\n op0 = new SqlNodeList(cols, POS);\r\n }\r\n return subQuery.getOperator().createCall(POS, op0, sqlSubQuery);\r\n case SEARCH:\r\n final RexCall search = (RexCall) rex;\r\n if (search.operands.get(1).getKind() == SqlKind.LITERAL) {\r\n literal = (RexLiteral) search.operands.get(1);\r\n final Sarg sarg = castNonNull(literal.getValueAs(Sarg.class));\r\n return toSql(program, search.operands.get(0), literal.getType(), sarg);\r\n }\r\n return toSql(program, RexUtil.expandSearch(implementor().rexBuilder, program, search));\r\n case EXISTS:\r\n case UNIQUE:\r\n case SCALAR_QUERY:\r\n subQuery = (RexSubQuery) rex;\r\n sqlSubQuery = implementor().visitRoot(subQuery.rel).asQueryOrValues();\r\n return subQuery.getOperator().createCall(POS, sqlSubQuery);\r\n case NOT:\r\n RexNode operand = ((RexCall) rex).operands.get(0);\r\n final SqlNode node = toSql(program, operand);\r\n final SqlOperator inverseOperator = getInverseOperator(operand);\r\n if (inverseOperator != null) {\r\n switch(operand.getKind()) {\r\n case IN:\r\n assert operand instanceof RexSubQuery : \"scalar IN is no longer allowed in RexCall: \" + rex;\r\n break;\r\n default:\r\n break;\r\n }\r\n return inverseOperator.createCall(POS, ((SqlCall) node).getOperandList());\r\n } else {\r\n return SqlStdOperatorTable.NOT.createCall(POS, node);\r\n }\r\n default:\r\n if (rex instanceof RexOver) {\r\n return toSql(program, (RexOver) rex);\r\n }\r\n return callToSql(program, (RexCall) rex, false);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void applyOnRaftGroup(CountDownLatch latch, Map> changedGroups, CPGroupMembershipChange change){\r\n CompletableFuture future;\r\n if (change.getMemberToRemove() != null) {\r\n future = invocationManager.changeMembership(change.getGroupId(), change.getMembersCommitIndex(), change.getMemberToRemove(), MembershipChangeMode.REMOVE);\r\n } else {\r\n future = CompletableFuture.completedFuture(change.getMembersCommitIndex());\r\n }\r\n future.whenCompleteAsync((removeCommitIndex, t) -> {\r\n if (t == null) {\r\n if (change.getMemberToAdd() != null) {\r\n addMember(latch, changedGroups, change, removeCommitIndex);\r\n } else {\r\n changedGroups.put(change.getGroupId(), BiTuple.of(change.getMembersCommitIndex(), removeCommitIndex));\r\n latch.countDown();\r\n }\r\n } else {\r\n long commitIndex = checkMemberRemoveCommitIndex(changedGroups, change, t);\r\n if (commitIndex != NA_MEMBERS_COMMIT_INDEX) {\r\n if (change.getMemberToAdd() != null) {\r\n addMember(latch, changedGroups, change, commitIndex);\r\n } else {\r\n changedGroups.put(change.getGroupId(), BiTuple.of(change.getMembersCommitIndex(), commitIndex));\r\n latch.countDown();\r\n }\r\n } else {\r\n latch.countDown();\r\n }\r\n }\r\n }, internalAsyncExecutor);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage buildPartial(){\r\n org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage result = new org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage(this);\r\n int from_bitField0_ = bitField0_;\r\n int to_bitField0_ = 0;\r\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\r\n to_bitField0_ |= 0x00000001;\r\n }\r\n result.type_ = type_;\r\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\r\n to_bitField0_ |= 0x00000002;\r\n }\r\n if (clientVersionBuilder_ == null) {\r\n result.clientVersion_ = clientVersion_;\r\n } else {\r\n result.clientVersion_ = clientVersionBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\r\n to_bitField0_ |= 0x00000004;\r\n }\r\n if (serverVersionBuilder_ == null) {\r\n result.serverVersion_ = serverVersion_;\r\n } else {\r\n result.serverVersion_ = serverVersionBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\r\n to_bitField0_ |= 0x00000008;\r\n }\r\n if (initiateBuilder_ == null) {\r\n result.initiate_ = initiate_;\r\n } else {\r\n result.initiate_ = initiateBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000010) == 0x00000010)) {\r\n to_bitField0_ |= 0x00000010;\r\n }\r\n if (provideRefundBuilder_ == null) {\r\n result.provideRefund_ = provideRefund_;\r\n } else {\r\n result.provideRefund_ = provideRefundBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000020) == 0x00000020)) {\r\n to_bitField0_ |= 0x00000020;\r\n }\r\n if (returnRefundBuilder_ == null) {\r\n result.returnRefund_ = returnRefund_;\r\n } else {\r\n result.returnRefund_ = returnRefundBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000040) == 0x00000040)) {\r\n to_bitField0_ |= 0x00000040;\r\n }\r\n if (provideContractBuilder_ == null) {\r\n result.provideContract_ = provideContract_;\r\n } else {\r\n result.provideContract_ = provideContractBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000080) == 0x00000080)) {\r\n to_bitField0_ |= 0x00000080;\r\n }\r\n if (updatePaymentBuilder_ == null) {\r\n result.updatePayment_ = updatePayment_;\r\n } else {\r\n result.updatePayment_ = updatePaymentBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000100) == 0x00000100)) {\r\n to_bitField0_ |= 0x00000100;\r\n }\r\n if (paymentAckBuilder_ == null) {\r\n result.paymentAck_ = paymentAck_;\r\n } else {\r\n result.paymentAck_ = paymentAckBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000200) == 0x00000200)) {\r\n to_bitField0_ |= 0x00000200;\r\n }\r\n if (settlementBuilder_ == null) {\r\n result.settlement_ = settlement_;\r\n } else {\r\n result.settlement_ = settlementBuilder_.build();\r\n }\r\n if (((from_bitField0_ & 0x00000400) == 0x00000400)) {\r\n to_bitField0_ |= 0x00000400;\r\n }\r\n if (errorBuilder_ == null) {\r\n result.error_ = error_;\r\n } else {\r\n result.error_ = errorBuilder_.build();\r\n }\r\n result.bitField0_ = to_bitField0_;\r\n onBuilt();\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processZip64Extra(final ZipLong size, final ZipLong cSize) throws ZipException{\r\n final ZipExtraField extra = current.entry.getExtraField(Zip64ExtendedInformationExtraField.HEADER_ID);\r\n if (extra != null && !(extra instanceof Zip64ExtendedInformationExtraField)) {\r\n throw new ZipException(\"archive contains unparseable zip64 extra field\");\r\n }\r\n final Zip64ExtendedInformationExtraField z64 = (Zip64ExtendedInformationExtraField) extra;\r\n current.usesZip64 = z64 != null;\r\n if (!current.hasDataDescriptor) {\r\n if (z64 != null && (ZipLong.ZIP64_MAGIC.equals(cSize) || ZipLong.ZIP64_MAGIC.equals(size))) {\r\n if (z64.getCompressedSize() == null || z64.getSize() == null) {\r\n throw new ZipException(\"archive contains corrupted zip64 extra field\");\r\n }\r\n long s = z64.getCompressedSize().getLongValue();\r\n if (s < 0) {\r\n throw new ZipException(\"broken archive, entry with negative compressed size\");\r\n }\r\n current.entry.setCompressedSize(s);\r\n s = z64.getSize().getLongValue();\r\n if (s < 0) {\r\n throw new ZipException(\"broken archive, entry with negative size\");\r\n }\r\n current.entry.setSize(s);\r\n } else if (cSize != null && size != null) {\r\n if (cSize.getValue() < 0) {\r\n throw new ZipException(\"broken archive, entry with negative compressed size\");\r\n }\r\n current.entry.setCompressedSize(cSize.getValue());\r\n if (size.getValue() < 0) {\r\n throw new ZipException(\"broken archive, entry with negative size\");\r\n }\r\n current.entry.setSize(size.getValue());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public KnowledgeBuilder buildKnowledgePackages(KieBaseModelImpl kBaseModel, BuildContext buildContext, Predicate buildFilter){\r\n boolean useFolders = useFolders(kBaseModel);\r\n Set assets = new HashSet<>();\r\n boolean allIncludesAreValid = true;\r\n for (String include : getTransitiveIncludes(kBaseModel)) {\r\n if (StringUtils.isEmpty(include)) {\r\n continue;\r\n }\r\n InternalKieModule includeModule = getKieModuleForKBase(include);\r\n if (includeModule == null) {\r\n String text = \"Unable to build KieBase, could not find include: \" + include;\r\n log.error(text);\r\n buildContext.getMessages().addMessage(Message.Level.ERROR, KieModuleModelImpl.KMODULE_SRC_PATH.asString(), text).setKieBaseName(kBaseModel.getName());\r\n allIncludesAreValid = false;\r\n continue;\r\n }\r\n if (compileIncludedKieBases()) {\r\n addFiles(buildFilter, assets, getKieBaseModel(include), includeModule, useFolders);\r\n }\r\n }\r\n if (!allIncludesAreValid) {\r\n return null;\r\n }\r\n InternalKieModule kModule = getKieModuleForKBase(kBaseModel.getName());\r\n addFiles(buildFilter, assets, kBaseModel, kModule, useFolders);\r\n KnowledgeBuilder kbuilder;\r\n if (assets.isEmpty()) {\r\n if (buildFilter == BUILD_ALL) {\r\n log.warn(\"No files found for KieBase \" + kBaseModel.getName() + (kModule instanceof FileKieModule ? \", searching folder \" + kModule.getFile() : \"\"));\r\n }\r\n kbuilder = new InternalKnowledgeBuilder.Empty(getClassLoader(), () -> provideKnowledgeBuilder(kBaseModel, kModule, buildContext));\r\n } else {\r\n kbuilder = provideKnowledgeBuilder(kBaseModel, kModule, buildContext);\r\n if (kbuilder == null) {\r\n return null;\r\n }\r\n CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();\r\n for (Asset asset : assets) {\r\n if (buildContext.registerResourceToBuild(kBaseModel.getName(), asset.name)) {\r\n asset.kmodule.addResourceToCompiler(ckbuilder, kBaseModel, asset.name);\r\n }\r\n }\r\n ckbuilder.build();\r\n if (kbuilder.hasErrors()) {\r\n for (KnowledgeBuilderError error : kbuilder.getErrors()) {\r\n buildContext.getMessages().addMessage(error).setKieBaseName(kBaseModel.getName());\r\n }\r\n log.error(\"Unable to build KieBaseModel:\" + kBaseModel.getName() + \"\\n\" + kbuilder.getErrors().toString());\r\n }\r\n if (kbuilder.hasResults(ResultSeverity.WARNING)) {\r\n for (KnowledgeBuilderResult warn : kbuilder.getResults(ResultSeverity.WARNING)) {\r\n buildContext.getMessages().addMessage(warn).setKieBaseName(kBaseModel.getName());\r\n }\r\n log.warn(\"Warning : \" + kBaseModel.getName() + \"\\n\" + kbuilder.getResults(ResultSeverity.WARNING).toString());\r\n }\r\n }\r\n if (buildFilter == BUILD_ALL) {\r\n kModule.cacheKnowledgeBuilderForKieBase(kBaseModel.getName(), kbuilder);\r\n kModule.cacheResultsForKieBase(kBaseModel.getName(), buildContext.getMessages());\r\n }\r\n return kbuilder;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void clear(){\r\n if (releaseTaskMonitor != null) {\r\n releaseTaskMonitor.shutdownNow();\r\n while (true) {\r\n if (releaseTaskMonitor.isTerminated())\r\n break;\r\n }\r\n releaseTaskMonitor = null;\r\n }\r\n if (flushTaskMonitor != null) {\r\n flushTaskMonitor.shutdownNow();\r\n while (true) {\r\n if (flushTaskMonitor.isTerminated())\r\n break;\r\n }\r\n releaseTaskMonitor = null;\r\n }\r\n if (releaseTaskProcessor != null) {\r\n while (true) {\r\n if (!hasReleaseTask)\r\n break;\r\n }\r\n releaseTaskProcessor.shutdown();\r\n while (true) {\r\n if (releaseTaskProcessor.isTerminated())\r\n break;\r\n }\r\n releaseTaskProcessor = null;\r\n }\r\n if (flushTaskProcessor != null) {\r\n while (true) {\r\n if (!hasFlushTask)\r\n break;\r\n }\r\n flushTaskProcessor.shutdown();\r\n while (true) {\r\n if (flushTaskProcessor.isTerminated())\r\n break;\r\n }\r\n flushTaskProcessor = null;\r\n }\r\n storeList.clear();\r\n releaseFlushStrategy = null;\r\n engineStatistics = null;\r\n releaseSemaphore = null;\r\n flushSemaphore = null;\r\n engineMetric = null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public synchronized void readHeader() throws IOException{\r\n if (lf.exists()) {\r\n if (fc != null) {\r\n return;\r\n }\r\n fc = new RandomAccessFile(lf, mode).getChannel();\r\n size = fc.size();\r\n sizeSinceLastWrite = size;\r\n ByteBuffer bb = ByteBuffer.allocate((int) (Math.min(size, START_OF_DATA)));\r\n while (bb.hasRemaining()) {\r\n fc.read(bb);\r\n }\r\n bb.flip();\r\n if (bb.getInt() != SIGNATURE) {\r\n throw new IOException(\"Missing ledger signature while reading header for \" + lf);\r\n }\r\n int version = bb.getInt();\r\n if (version > CURRENT_HEADER_VERSION) {\r\n throw new IOException(\"Incompatible ledger version \" + version + \" while reading header for \" + lf);\r\n }\r\n this.headerVersion = version;\r\n int length = bb.getInt();\r\n if (length < 0) {\r\n throw new IOException(\"Length \" + length + \" is invalid while reading header for \" + lf);\r\n } else if (length > bb.remaining()) {\r\n throw new BufferUnderflowException();\r\n }\r\n masterKey = new byte[length];\r\n bb.get(masterKey);\r\n stateBits = bb.getInt();\r\n if (this.headerVersion >= V1) {\r\n int explicitLacBufLength = bb.getInt();\r\n if (explicitLacBufLength == 0) {\r\n explicitLac = null;\r\n } else if (explicitLacBufLength >= DigestManager.LAC_METADATA_LENGTH) {\r\n if (explicitLac == null) {\r\n explicitLac = ByteBuffer.allocate(explicitLacBufLength);\r\n }\r\n byte[] explicitLacBufArray = new byte[explicitLacBufLength];\r\n bb.get(explicitLacBufArray);\r\n explicitLac.put(explicitLacBufArray);\r\n explicitLac.rewind();\r\n } else {\r\n throw new IOException(\"ExplicitLacBufLength \" + explicitLacBufLength + \" is invalid while reading header for \" + lf);\r\n }\r\n }\r\n needFlushHeader = false;\r\n } else {\r\n throw new IOException(\"Ledger index file \" + lf + \" does not exist\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getFieldValue(ProcessInstanceRowRecord instance, Item[] items, String fieldName){\r\n String fieldString;\r\n try {\r\n Field field = instance.getFullProcessInstance().getField(fieldName);\r\n fieldString = field.getValue(getLanguage());\r\n if (!isDefined(fieldString) || !field.getTypeName().equals(DateField.TYPE)) {\r\n ItemImpl item = (ItemImpl) getItemByName(items, fieldName);\r\n if (item != null) {\r\n Map keyValuePairs = item.getKeyValuePairs();\r\n if (keyValuePairs != null && keyValuePairs.size() > 0) {\r\n StringBuilder newValue = new StringBuilder();\r\n if (isDefined(fieldString)) {\r\n final String delimiter = \"##\";\r\n if (fieldString.contains(delimiter)) {\r\n StringTokenizer tokenizer = new StringTokenizer(fieldString, delimiter);\r\n String token;\r\n while (tokenizer.hasMoreTokens()) {\r\n token = tokenizer.nextToken();\r\n token = keyValuePairs.get(token);\r\n newValue.append(token);\r\n if (tokenizer.hasMoreTokens()) {\r\n newValue.append(\", \");\r\n }\r\n }\r\n } else {\r\n newValue.append(keyValuePairs.get(fieldString));\r\n }\r\n }\r\n fieldString = newValue.toString();\r\n }\r\n }\r\n }\r\n } catch (WorkflowException we) {\r\n fieldString = \"\";\r\n }\r\n return fieldString;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void dedupWithTableInfo(){\r\n assert tableInfo != null : \"TableInfo can't be null at this point.\";\r\n if (partitionSchema != null) {\r\n if (partitionSchema.equals(tableInfo.getDataColumns())) {\r\n partitionSchema = null;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Can't suppress data-schema. Partition-schema and table-schema seem to differ! \" + \" partitionSchema: \" + partitionSchema.getFields() + \" tableSchema: \" + tableInfo.getDataColumns());\r\n }\r\n }\r\n }\r\n if (storageHandlerClassName != null) {\r\n if (storageHandlerClassName.equals(tableInfo.getStorerInfo().getStorageHandlerClass())) {\r\n storageHandlerClassName = null;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Partition's storageHandler (\" + storageHandlerClassName + \") \" + \"differs from table's storageHandler (\" + tableInfo.getStorerInfo().getStorageHandlerClass() + \").\");\r\n }\r\n }\r\n }\r\n if (inputFormatClassName != null) {\r\n if (inputFormatClassName.equals(tableInfo.getStorerInfo().getIfClass())) {\r\n inputFormatClassName = null;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Partition's InputFormat (\" + inputFormatClassName + \") \" + \"differs from table's InputFormat (\" + tableInfo.getStorerInfo().getIfClass() + \").\");\r\n }\r\n }\r\n }\r\n if (outputFormatClassName != null) {\r\n if (outputFormatClassName.equals(tableInfo.getStorerInfo().getOfClass())) {\r\n outputFormatClassName = null;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Partition's OutputFormat (\" + outputFormatClassName + \") \" + \"differs from table's OutputFormat (\" + tableInfo.getStorerInfo().getOfClass() + \").\");\r\n }\r\n }\r\n }\r\n if (serdeClassName != null) {\r\n if (serdeClassName.equals(tableInfo.getStorerInfo().getSerdeClass())) {\r\n serdeClassName = null;\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Partition's SerDe (\" + serdeClassName + \") \" + \"differs from table's SerDe (\" + tableInfo.getStorerInfo().getSerdeClass() + \").\");\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void normalizeForeignPackages(PackageDescr packageDescr){\r\n Map foreignPackages = null;\r\n for (AbstractClassTypeDeclarationDescr typeDescr : packageDescr.getClassAndEnumDeclarationDescrs()) {\r\n if (context.filterAccepts(ResourceChange.Type.DECLARATION, typeDescr.getNamespace(), typeDescr.getTypeName())) {\r\n if (!typeDescr.getNamespace().equals(packageDescr.getNamespace())) {\r\n PackageDescr altDescr;\r\n if (foreignPackages == null) {\r\n foreignPackages = new HashMap<>();\r\n }\r\n if (foreignPackages.containsKey(typeDescr.getNamespace())) {\r\n altDescr = foreignPackages.get(typeDescr.getNamespace());\r\n } else {\r\n altDescr = new PackageDescr(typeDescr.getNamespace());\r\n altDescr.setResource(packageDescr.getResource());\r\n foreignPackages.put(typeDescr.getNamespace(), altDescr);\r\n }\r\n if (typeDescr instanceof TypeDeclarationDescr) {\r\n altDescr.addTypeDeclaration((TypeDeclarationDescr) typeDescr);\r\n } else if (typeDescr instanceof EnumDeclarationDescr) {\r\n altDescr.addEnumDeclaration((EnumDeclarationDescr) typeDescr);\r\n }\r\n for (ImportDescr imp : packageDescr.getImports()) {\r\n altDescr.addImport(imp);\r\n }\r\n context.getOrCreatePackageRegistry(altDescr);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private BandAnalysisResults analyseBand(final String name, final int[] band, final BHSDCodec defaultCodec) throws Pack200Exception{\r\n final BandAnalysisResults results = new BandAnalysisResults();\r\n if (canonicalLargest == null) {\r\n canonicalLargest = new long[116];\r\n canonicalSmallest = new long[116];\r\n for (int i = 1; i < canonicalLargest.length; ++i) {\r\n canonicalLargest[i] = CodecEncoding.getCanonicalCodec(i).largest();\r\n canonicalSmallest[i] = CodecEncoding.getCanonicalCodec(i).smallest();\r\n }\r\n }\r\n final BandData bandData = new BandData(band);\r\n final byte[] encoded = defaultCodec.encode(band);\r\n results.encodedBand = encoded;\r\n if (encoded.length <= band.length + 23 - 2 * effort) {\r\n return results;\r\n }\r\n if (!bandData.anyNegatives() && bandData.largest <= Codec.BYTE1.largest()) {\r\n results.encodedBand = Codec.BYTE1.encode(band);\r\n results.betterCodec = Codec.BYTE1;\r\n return results;\r\n }\r\n if (effort > 3 && !name.equals(TEXT_EXCEPTION)) {\r\n final int numDistinctValues = bandData.numDistinctValues();\r\n final float distinctValuesAsProportion = (float) numDistinctValues / (float) band.length;\r\n if (numDistinctValues < 100 || distinctValuesAsProportion < 0.02 || (effort > 6 && distinctValuesAsProportion < 0.04)) {\r\n encodeWithPopulationCodec(name, band, defaultCodec, bandData, results);\r\n if (timeToStop(results)) {\r\n return results;\r\n }\r\n }\r\n }\r\n final List codecFamiliesToTry = new ArrayList<>();\r\n if (bandData.mainlyPositiveDeltas() && bandData.mainlySmallDeltas()) {\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs2);\r\n }\r\n if (bandData.wellCorrelated()) {\r\n if (bandData.mainlyPositiveDeltas()) {\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs5);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs5);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs2);\r\n } else {\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs2);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs5);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaSignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaSignedCodecs2);\r\n }\r\n } else if (bandData.anyNegatives()) {\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaSignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaSignedCodecs2);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs2);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaSignedCodecs5);\r\n } else {\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs5);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.nonDeltaUnsignedCodecs2);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs1);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs3);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs4);\r\n codecFamiliesToTry.add(CanonicalCodecFamilies.deltaUnsignedCodecs5);\r\n }\r\n if (name.equalsIgnoreCase(\"cpint\")) {\r\n System.out.print(\"\");\r\n }\r\n for (final BHSDCodec[] family : codecFamiliesToTry) {\r\n tryCodecs(name, band, defaultCodec, bandData, results, encoded, family);\r\n if (timeToStop(results)) {\r\n break;\r\n }\r\n }\r\n return results;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public SqlLiteral unescapeUnicode(char unicodeEscapeChar){\r\n if (unicodeEscapeChar == 0) {\r\n return this;\r\n }\r\n assert SqlTypeUtil.inCharFamily(getTypeName());\r\n NlsString ns = (NlsString) requireNonNull(value, \"value\");\r\n String s = ns.getValue();\r\n StringBuilder sb = new StringBuilder();\r\n int n = s.length();\r\n for (int i = 0; i < n; ++i) {\r\n char c = s.charAt(i);\r\n if (c == unicodeEscapeChar) {\r\n if (n > (i + 1)) {\r\n if (s.charAt(i + 1) == unicodeEscapeChar) {\r\n sb.append(unicodeEscapeChar);\r\n ++i;\r\n continue;\r\n }\r\n }\r\n if ((i + 5) > n) {\r\n throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i));\r\n }\r\n final String u = s.substring(i + 1, i + 5);\r\n final int v;\r\n try {\r\n v = Integer.parseInt(u, 16);\r\n } catch (NumberFormatException ex) {\r\n throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i));\r\n }\r\n sb.append((char) (v & 0xFFFF));\r\n i += 4;\r\n } else {\r\n sb.append(c);\r\n }\r\n }\r\n ns = new NlsString(sb.toString(), ns.getCharsetName(), ns.getCollation());\r\n return new SqlCharStringLiteral(ns, getParserPosition());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void constructMCFGraph(){\r\n this.maximumFlow = 0;\r\n this.minimumCost = 0;\r\n for (TRegionReplicaSet regionReplicaSet : regionReplicaSetMap.values()) {\r\n rNodeMap.put(regionReplicaSet.getRegionId(), maxNode++);\r\n for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) {\r\n if (!dNodeMap.containsKey(dataNodeLocation.getDataNodeId())) {\r\n dNodeMap.put(dataNodeLocation.getDataNodeId(), maxNode);\r\n dNodeReflect.put(maxNode, dataNodeLocation.getDataNodeId());\r\n maxNode += 1;\r\n }\r\n }\r\n }\r\n isNodeVisited = new boolean[maxNode];\r\n nodeMinimumCost = new int[maxNode];\r\n nodeCurrentEdge = new int[maxNode];\r\n nodeHeadEdge = new int[maxNode];\r\n Arrays.fill(nodeHeadEdge, -1);\r\n for (int rNode : rNodeMap.values()) {\r\n addAdjacentEdges(S_NODE, rNode, 1, 0);\r\n }\r\n for (TRegionReplicaSet regionReplicaSet : regionReplicaSetMap.values()) {\r\n int rNode = rNodeMap.get(regionReplicaSet.getRegionId());\r\n for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) {\r\n int dNode = dNodeMap.get(dataNodeLocation.getDataNodeId());\r\n int cost = regionLeaderMap.getOrDefault(regionReplicaSet.getRegionId(), -1) == dataNodeLocation.getDataNodeId() ? 0 : 1;\r\n addAdjacentEdges(rNode, dNode, 1, cost);\r\n }\r\n }\r\n Map maxLeaderCounter = new ConcurrentHashMap<>();\r\n regionReplicaSetMap.values().forEach(regionReplicaSet -> regionReplicaSet.getDataNodeLocations().forEach(dataNodeLocation -> maxLeaderCounter.computeIfAbsent(dataNodeLocation.getDataNodeId(), empty -> new AtomicInteger(0)).getAndIncrement()));\r\n for (Map.Entry dNodeEntry : dNodeMap.entrySet()) {\r\n int dataNodeId = dNodeEntry.getKey();\r\n int dNode = dNodeEntry.getValue();\r\n if (disabledDataNodeSet.contains(dataNodeId)) {\r\n continue;\r\n }\r\n int maxLeaderCount = maxLeaderCounter.get(dataNodeId).get();\r\n for (int extraEdge = 1; extraEdge <= maxLeaderCount; extraEdge++) {\r\n addAdjacentEdges(dNode, T_NODE, 1, extraEdge * extraEdge);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AccumulatorFactory getAccumulator(Compiler compiler, final AggregateCall call, boolean ignoreFilter){\r\n if (call.filterArg >= 0 && !ignoreFilter) {\r\n final AccumulatorFactory factory = getAccumulator(compiler, call, true);\r\n return () -> {\r\n final Accumulator accumulator = factory.get();\r\n return new FilterAccumulator(accumulator, call.filterArg);\r\n };\r\n }\r\n final SqlAggFunction op = call.getAggregation();\r\n if (op == SqlStdOperatorTable.COUNT) {\r\n return () -> new CountAccumulator(call);\r\n } else if (op == SqlStdOperatorTable.SUM || op == SqlStdOperatorTable.SUM0) {\r\n final Class clazz = sumClass(call);\r\n return new UdaAccumulatorFactory(getAggFunction(clazz), call, op == SqlStdOperatorTable.SUM, dataContext);\r\n } else if (op == SqlStdOperatorTable.MAX || op == SqlStdOperatorTable.MIN) {\r\n final Class clazz = maxMinClass(call);\r\n return new UdaAccumulatorFactory(getAggFunction(clazz), call, true, dataContext);\r\n } else if (op == SqlInternalOperators.LITERAL_AGG) {\r\n final Scalar scalar = compiler.compile(call.rexList, null);\r\n final Object value = scalar.execute(compiler.createContext());\r\n return () -> new LiteralAccumulator(value);\r\n } else {\r\n final JavaTypeFactory typeFactory = (JavaTypeFactory) rel.getCluster().getTypeFactory();\r\n int stateOffset = 0;\r\n final AggImpState agg = new AggImpState(0, call, false);\r\n int stateSize = requireNonNull(agg.state, \"agg.state\").size();\r\n final BlockBuilder builder2 = new BlockBuilder();\r\n final PhysType inputPhysType = PhysTypeImpl.of(typeFactory, rel.getInput().getRowType(), JavaRowFormat.ARRAY);\r\n final RelDataTypeFactory.Builder builder = typeFactory.builder();\r\n for (Expression expression : agg.state) {\r\n builder.add(\"a\", typeFactory.createJavaType((Class) expression.getType()));\r\n }\r\n final PhysType accPhysType = PhysTypeImpl.of(typeFactory, builder.build(), JavaRowFormat.ARRAY);\r\n final ParameterExpression inParameter = Expressions.parameter(inputPhysType.getJavaRowType(), \"in\");\r\n final ParameterExpression acc_ = Expressions.parameter(accPhysType.getJavaRowType(), \"acc\");\r\n List accumulator = new ArrayList<>(stateSize);\r\n for (int j = 0; j < stateSize; j++) {\r\n accumulator.add(accPhysType.fieldReference(acc_, j + stateOffset));\r\n }\r\n agg.state = accumulator;\r\n AggAddContext addContext = new AggAddContextImpl(builder2, accumulator) {\r\n\r\n @Override\r\n public List rexArguments() {\r\n List args = new ArrayList<>();\r\n for (int index : agg.call.getArgList()) {\r\n args.add(RexInputRef.of(index, inputPhysType.getRowType()));\r\n }\r\n return args;\r\n }\r\n\r\n @Override\r\n @Nullable\r\n public RexNode rexFilterArgument() {\r\n return agg.call.filterArg < 0 ? null : RexInputRef.of(agg.call.filterArg, inputPhysType.getRowType());\r\n }\r\n\r\n @Override\r\n public RexToLixTranslator rowTranslator() {\r\n final SqlConformance conformance = SqlConformanceEnum.DEFAULT;\r\n return RexToLixTranslator.forAggregation(typeFactory, currentBlock(), new RexToLixTranslator.InputGetterImpl(inParameter, inputPhysType), conformance);\r\n }\r\n };\r\n agg.implementor.implementAdd(requireNonNull(agg.context, \"agg.context\"), addContext);\r\n final ParameterExpression context_ = Expressions.parameter(Context.class, \"context\");\r\n final ParameterExpression outputValues_ = Expressions.parameter(Object[].class, \"outputValues\");\r\n final Scalar.Producer addScalarProducer = JaninoRexCompiler.baz(context_, outputValues_, builder2.toBlock(), ImmutableList.of());\r\n final Scalar initScalar = castNonNull(null);\r\n final Scalar addScalar = addScalarProducer.apply(dataContext);\r\n final Scalar endScalar = castNonNull(null);\r\n return new ScalarAccumulatorDef(initScalar, addScalar, endScalar, rel.getInput().getRowType().getFieldCount(), stateSize, dataContext);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ListenableFuture recalculateFastCatchupAndFilter(final FilterRecalculateMode mode){\r\n final SettableFuture future = SettableFuture.create();\r\n synchronized (inFlightRecalculations) {\r\n if (inFlightRecalculations.get(mode) != null)\r\n return inFlightRecalculations.get(mode);\r\n inFlightRecalculations.put(mode, future);\r\n }\r\n Runnable command = new Runnable() {\r\n\r\n @Override\r\n public void run() {\r\n try {\r\n go();\r\n } catch (Throwable e) {\r\n log.error(\"Exception when trying to recalculate Bloom filter\", e);\r\n }\r\n }\r\n\r\n public void go() {\r\n checkState(!lock.isHeldByCurrentThread());\r\n if ((chain != null && chain.shouldVerifyTransactions()) || !vBloomFilteringEnabled)\r\n return;\r\n FilterMerger.Result result = bloomFilterMerger.calculate(ImmutableList.copyOf(peerFilterProviders));\r\n boolean send;\r\n switch(mode) {\r\n case SEND_IF_CHANGED:\r\n send = result.changed;\r\n break;\r\n case DONT_SEND:\r\n send = false;\r\n break;\r\n case FORCE_SEND_FOR_REFRESH:\r\n send = true;\r\n break;\r\n default:\r\n throw new UnsupportedOperationException();\r\n }\r\n if (send) {\r\n for (Peer peer : peers) {\r\n peer.setBloomFilter(result.filter, mode != FilterRecalculateMode.FORCE_SEND_FOR_REFRESH);\r\n }\r\n if (chain != null)\r\n chain.resetFalsePositiveEstimate();\r\n }\r\n setFastCatchupTimeSecs(result.earliestKeyTimeSecs);\r\n synchronized (inFlightRecalculations) {\r\n inFlightRecalculations.put(mode, null);\r\n }\r\n future.set(result.filter);\r\n }\r\n };\r\n try {\r\n executor.execute(command);\r\n } catch (RejectedExecutionException e) {\r\n }\r\n return future;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected List deprovision(final MatchingRule matchingRule, final SyncDelta delta, final List matches, final Provision provision) throws JobExecutionException{\r\n if (!profile.getTask().isPerformUpdate()) {\r\n LOG.debug(\"PullTask not configured for update\");\r\n end(provision.getAnyType().getKind(), MatchingRule.toEventName(matchingRule), Result.SUCCESS, null, null, delta);\r\n return List.of();\r\n }\r\n LOG.debug(\"About to deprovision {}\", matches);\r\n List results = new ArrayList<>();\r\n for (PullMatch match : matches) {\r\n LOG.debug(\"About to unassign resource {}\", match);\r\n ProvisioningReport result = new ProvisioningReport();\r\n result.setOperation(ResourceOperation.DELETE);\r\n result.setAnyType(provision.getAnyType().getKey());\r\n result.setStatus(ProvisioningReport.Status.SUCCESS);\r\n result.setKey(match.getAny().getKey());\r\n result.setUidValue(delta.getUid().getUidValue());\r\n AnyTO before = getAnyTO(match.getAny());\r\n if (before == null) {\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(String.format(\"Any '%s(%s)' not found\", provision.getAnyType().getKey(), match));\r\n }\r\n if (!profile.isDryRun()) {\r\n Object output;\r\n Result resultStatus;\r\n if (before == null) {\r\n resultStatus = Result.FAILURE;\r\n output = null;\r\n } else {\r\n result.setName(getName(before));\r\n try {\r\n if (matchingRule == MatchingRule.UNASSIGN) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeUnassign(profile, delta, before);\r\n }\r\n } else if (matchingRule == MatchingRule.DEPROVISION) {\r\n for (PullActions action : profile.getActions()) {\r\n action.beforeDeprovision(profile, delta, before);\r\n }\r\n }\r\n PropagationByResource propByRes = new PropagationByResource<>();\r\n propByRes.add(ResourceOperation.DELETE, provision.getResource().getKey());\r\n taskExecutor.execute(propagationManager.getDeleteTasks(provision.getAnyType().getKind(), match.getAny().getKey(), propByRes, null, null), false, securityProperties.getAdminUser());\r\n AnyUR anyUR = null;\r\n if (matchingRule == MatchingRule.UNASSIGN) {\r\n anyUR = getAnyUtils().newAnyUR(match.getAny().getKey());\r\n anyUR.getResources().add(new StringPatchItem.Builder().operation(PatchOperation.DELETE).value(profile.getTask().getResource().getKey()).build());\r\n }\r\n if (anyUR == null) {\r\n output = getAnyTO(match.getAny());\r\n } else {\r\n output = doUpdate(before, anyUR, delta, result);\r\n }\r\n for (PullActions action : profile.getActions()) {\r\n action.after(profile, delta, AnyTO.class.cast(output), result);\r\n }\r\n resultStatus = Result.SUCCESS;\r\n LOG.debug(\"{} {} successfully updated\", provision.getAnyType().getKey(), match);\r\n } catch (PropagationException e) {\r\n LOG.error(\"Could not propagate {} {}\", provision.getAnyType().getKey(), delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n } catch (Exception e) {\r\n throwIgnoreProvisionException(delta, e);\r\n result.setStatus(ProvisioningReport.Status.FAILURE);\r\n result.setMessage(ExceptionUtils.getRootCauseMessage(e));\r\n LOG.error(\"Could not update {} {}\", provision.getAnyType().getKey(), delta.getUid().getUidValue(), e);\r\n output = e;\r\n resultStatus = Result.FAILURE;\r\n }\r\n }\r\n end(provision.getAnyType().getKind(), MatchingRule.toEventName(matchingRule), resultStatus, before, output, delta);\r\n }\r\n results.add(result);\r\n }\r\n return results;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\nprivate LcsTable validateKeys(RelNode factRel, List leftKeys, List rightKeys, List actualLeftKeys){\r\n int keyIdx = 0;\r\n RelOptTable theTable = null;\r\n ListIterator keyIter = leftKeys.listIterator();\r\n while (keyIter.hasNext()) {\r\n boolean removeKey = false;\r\n final RelColumnOrigin colOrigin = mq.getColumnOrigin(factRel, keyIter.next());\r\n if ((colOrigin == null || !colOrigin.isDerived()) || LucidDbSpecialOperators.isLcsRidColumnId(colOrigin.getOriginColumnOrdinal())) {\r\n removeKey = true;\r\n } else {\r\n RelOptTable table = colOrigin.getOriginTable();\r\n if (theTable == null) {\r\n if (!(table instanceof LcsTable)) {\r\n removeKey = true;\r\n } else {\r\n theTable = table;\r\n }\r\n } else {\r\n assert table == theTable;\r\n }\r\n }\r\n if (colOrigin != null && !removeKey) {\r\n actualLeftKeys.add(colOrigin.getOriginColumnOrdinal());\r\n keyIdx++;\r\n } else {\r\n keyIter.remove();\r\n rightKeys.remove(keyIdx);\r\n }\r\n }\r\n if (actualLeftKeys.isEmpty()) {\r\n return null;\r\n } else {\r\n return (LcsTable) theTable;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processNormalMessage(){\r\n while (true) {\r\n ChannelFuture channel = m_channelManager.channel();\r\n if (channel != null) {\r\n try {\r\n MessageTree tree = m_queue.poll();\r\n if (tree != null) {\r\n sendInternal(channel, tree);\r\n tree.setMessage(null);\r\n } else {\r\n try {\r\n Thread.sleep(5);\r\n } catch (Exception e) {\r\n m_active = false;\r\n }\r\n break;\r\n }\r\n } catch (Throwable t) {\r\n m_logger.error(\"Error when sending message over TCP socket!\", t);\r\n }\r\n } else {\r\n try {\r\n Thread.sleep(5);\r\n } catch (Exception e) {\r\n m_active = false;\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean copyToFile(File src, File dest, boolean overwrite){\r\n if (src == null || !src.exists() || !src.isFile() || dest == null)\r\n return false;\r\n if (!overwrite && dest.exists())\r\n return false;\r\n File parent = dest.getParentFile();\r\n if (parent == null || (!parent.exists() && !parent.mkdirs()))\r\n return false;\r\n try {\r\n if (src.getCanonicalPath().equals(dest.getCanonicalPath()))\r\n return false;\r\n } catch (IOException e1) {\r\n e1.printStackTrace();\r\n }\r\n InputStream in = null;\r\n OutputStream out = null;\r\n try {\r\n in = new FileInputStream(src);\r\n out = new FileOutputStream(dest);\r\n byte[] buf = new byte[1024];\r\n int len;\r\n while ((len = in.read(buf)) > 0) {\r\n out.write(buf, 0, len);\r\n }\r\n } catch (FileNotFoundException e) {\r\n e.printStackTrace();\r\n return false;\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n return false;\r\n } finally {\r\n if (in != null)\r\n try {\r\n in.close();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n return false;\r\n }\r\n if (out != null)\r\n ;\r\n try {\r\n out.close();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n return false;\r\n }\r\n }\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int functionCall(ParserRuleContext ctx, HplsqlParser.IdentContext ident, HplsqlParser.Expr_func_paramsContext params){\r\n String name = ident.getText();\r\n if (exec.buildSql) {\r\n exec.execSql(name, params);\r\n } else {\r\n name = name.toUpperCase();\r\n Package packCallContext = exec.getPackageCallContext();\r\n ArrayList qualified = exec.meta.splitIdentifier(name);\r\n boolean executed = false;\r\n if (qualified != null) {\r\n Package pack = findPackage(qualified.get(0));\r\n if (pack != null) {\r\n executed = pack.execFunc(qualified.get(1), params);\r\n }\r\n }\r\n if (!executed && packCallContext != null) {\r\n executed = packCallContext.execFunc(name, params);\r\n }\r\n if (!executed) {\r\n if (!exec.functions.exec(name, params)) {\r\n Var var = findVariable(name);\r\n if (var != null && var.type == Type.HPL_OBJECT) {\r\n stackPush(dispatch(ctx, (HplObject) var.value, __GETITEM__, params));\r\n } else {\r\n throw new UndefinedIdentException(ctx, name);\r\n }\r\n }\r\n }\r\n }\r\n return 0;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public MethodInvocation createMethodInvocation(final Object pojo, boolean hasParameters, final Exchange exchange){\r\n final Object[] arguments = initializeArguments(hasParameters, exchange);\r\n return new MethodInvocation() {\r\n\r\n public Method getMethod() {\r\n return method;\r\n }\r\n\r\n public Object[] getArguments() {\r\n return arguments;\r\n }\r\n\r\n public boolean proceed(AsyncCallback callback) {\r\n try {\r\n MessageHelper.resetStreamCache(exchange.getIn());\r\n return doProceed(callback);\r\n } catch (InvocationTargetException e) {\r\n exchange.setException(e.getTargetException());\r\n callback.done(true);\r\n return true;\r\n } catch (Exception e) {\r\n exchange.setException(e);\r\n callback.done(true);\r\n return true;\r\n }\r\n }\r\n\r\n private boolean doProceed(AsyncCallback callback) throws Exception {\r\n if (dynamicRouter != null) {\r\n if (!ServiceHelper.isStarted(dynamicRouter)) {\r\n ServiceHelper.startService(dynamicRouter);\r\n }\r\n Expression expression = new DynamicRouterExpression(pojo);\r\n expression.init(camelContext);\r\n exchange.setProperty(ExchangePropertyKey.EVALUATE_EXPRESSION_RESULT, expression);\r\n return dynamicRouter.process(exchange, callback);\r\n }\r\n if (LOG.isTraceEnabled()) {\r\n LOG.trace(\">>>> invoking: {} on bean: {} with arguments: {} for exchange: {}\", method, pojo, asString(arguments), exchange);\r\n }\r\n Object result = invoke(method, pojo, arguments, exchange);\r\n if (result instanceof Callable) {\r\n LOG.trace(\"Method returned Callback which will be called: {}\", result);\r\n Object callableResult = ((Callable) result).call();\r\n if (callableResult != null) {\r\n result = callableResult;\r\n } else {\r\n result = Void.TYPE;\r\n }\r\n }\r\n if (recipientList != null) {\r\n if (!ServiceHelper.isStarted(recipientList)) {\r\n ServiceHelper.startService(recipientList);\r\n }\r\n exchange.setProperty(ExchangePropertyKey.EVALUATE_EXPRESSION_RESULT, result);\r\n return recipientList.process(exchange, callback);\r\n }\r\n if (routingSlip != null) {\r\n if (!ServiceHelper.isStarted(routingSlip)) {\r\n ServiceHelper.startService(routingSlip);\r\n }\r\n exchange.setProperty(ExchangePropertyKey.EVALUATE_EXPRESSION_RESULT, result);\r\n return routingSlip.process(exchange, callback);\r\n }\r\n if (CompletionStage.class.isAssignableFrom(method.getReturnType())) {\r\n CompletionStage completionStage = (CompletionStage) result;\r\n completionStage.whenComplete((resultObject, e) -> {\r\n if (e != null) {\r\n exchange.setException(e);\r\n } else if (resultObject != null) {\r\n fillResult(exchange, resultObject);\r\n }\r\n callback.done(false);\r\n });\r\n return false;\r\n }\r\n if (result != Void.TYPE && !method.getReturnType().equals(Void.TYPE)) {\r\n fillResult(exchange, result);\r\n }\r\n callback.done(true);\r\n return true;\r\n }\r\n\r\n public Object getThis() {\r\n return pojo;\r\n }\r\n\r\n public AccessibleObject getStaticPart() {\r\n return method;\r\n }\r\n };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void emitBlock(List block, OOBibStyle style, int minGroupingCount, StringBuilder stringBuilder){\r\n final int blockSize = block.size();\r\n if (blockSize == 0) {\r\n throw new IllegalArgumentException(\"The block is empty\");\r\n }\r\n if (blockSize == 1) {\r\n CitationMarkerNumericEntry entry = block.get(0);\r\n final Optional num = entry.getNumber();\r\n stringBuilder.append(num.isEmpty() ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) : String.valueOf(num.get()));\r\n Optional pageInfo = entry.getPageInfo();\r\n if (pageInfo.isPresent()) {\r\n stringBuilder.append(style.getPageInfoSeparator());\r\n stringBuilder.append(OOText.toString(pageInfo.get()));\r\n }\r\n return;\r\n }\r\n if (blockSize >= 2) {\r\n if (block.stream().anyMatch(x -> x.getPageInfo().isPresent())) {\r\n throw new IllegalArgumentException(\"Found pageInfo in a block with more than one elements\");\r\n }\r\n if (block.stream().anyMatch(x -> x.getNumber().isEmpty())) {\r\n throw new IllegalArgumentException(\"Found unresolved entry in a block with more than one elements\");\r\n }\r\n for (int j = 1; j < blockSize; j++) {\r\n if ((block.get(j).getNumber().get() - block.get(j - 1).getNumber().get()) != 1) {\r\n throw new IllegalArgumentException(\"Numbers are not consecutive\");\r\n }\r\n }\r\n if (blockSize >= minGroupingCount) {\r\n int first = block.get(0).getNumber().get();\r\n int last = block.get(blockSize - 1).getNumber().get();\r\n if (last != (first + blockSize - 1)) {\r\n throw new IllegalArgumentException(\"blockSize and length of num range differ\");\r\n }\r\n stringBuilder.append(first);\r\n stringBuilder.append(style.getGroupedNumbersSeparator());\r\n stringBuilder.append(last);\r\n } else {\r\n for (int j = 0; j < blockSize; j++) {\r\n if (j > 0) {\r\n stringBuilder.append(style.getCitationSeparator());\r\n }\r\n stringBuilder.append(block.get(j).getNumber().get());\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void getCacheDataForOneSlice(int stripeIx, FileData cached, FileData result, BooleanRef gotAllData, boolean[] includes, LowLevelCacheCounters qfCounters){\r\n StripeData cStripe = cached.stripes.get(stripeIx);\r\n if (LlapIoImpl.CACHE_LOGGER.isTraceEnabled()) {\r\n LlapIoImpl.CACHE_LOGGER.trace(\"Got stripe in cache \" + cStripe);\r\n }\r\n StripeData stripe = StripeData.duplicateStructure(cStripe);\r\n result.stripes.add(stripe);\r\n boolean isMissed = false;\r\n for (int colIx = 0; colIx < cached.colCount; ++colIx) {\r\n if (!includes[colIx])\r\n continue;\r\n if (cStripe.encodings[colIx] == null || cStripe.data[colIx] == null) {\r\n if (cStripe.data[colIx] != null) {\r\n throw new AssertionError(cStripe);\r\n }\r\n isMissed = true;\r\n if (gotAllData != null) {\r\n gotAllData.value = false;\r\n }\r\n continue;\r\n }\r\n stripe.encodings[colIx] = cStripe.encodings[colIx];\r\n LlapSerDeDataBuffer[][] cColData = cStripe.data[colIx];\r\n assert cColData != null;\r\n for (int streamIx = 0; cColData != null && streamIx < cColData.length; ++streamIx) {\r\n LlapSerDeDataBuffer[] streamData = cColData[streamIx];\r\n if (streamData == null)\r\n continue;\r\n for (int i = 0; i < streamData.length; ++i) {\r\n if (!lockBuffer(streamData[i], true)) {\r\n LlapIoImpl.CACHE_LOGGER.info(\"Couldn't lock data for stripe at \" + stripeIx + \", colIx \" + colIx + \", stream type \" + streamIx);\r\n handleRemovedColumnData(cColData);\r\n cColData = null;\r\n isMissed = true;\r\n if (gotAllData != null) {\r\n gotAllData.value = false;\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n stripe.data[colIx] = cColData;\r\n if (cColData == null) {\r\n stripe.encodings[colIx] = null;\r\n }\r\n }\r\n doMetricsStuffForOneSlice(qfCounters, stripe, isMissed);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String replaceEach(String text, String[] searchList, String[] replacementList){\r\n if (isEmpty(text)) {\r\n return text;\r\n }\r\n int searchLength = searchList.length;\r\n int replacementLength = replacementList.length;\r\n if (searchLength != replacementLength) {\r\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\r\n }\r\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\r\n int textIndex = -1;\r\n int replaceIndex = -1;\r\n int tempIndex;\r\n for (int i = 0; i < searchLength; i++) {\r\n if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || replacementList[i] == null) {\r\n continue;\r\n }\r\n tempIndex = text.indexOf(searchList[i]);\r\n if (tempIndex == -1) {\r\n noMoreMatchesForReplIndex[i] = true;\r\n } else if (textIndex == -1 || tempIndex < textIndex) {\r\n textIndex = tempIndex;\r\n replaceIndex = i;\r\n }\r\n }\r\n if (textIndex == -1) {\r\n return text;\r\n }\r\n int start = 0;\r\n int increase = 0;\r\n for (int i = 0; i < searchList.length; i++) {\r\n if (searchList[i] == null || replacementList[i] == null) {\r\n continue;\r\n }\r\n int greater = replacementList[i].length() - searchList[i].length();\r\n if (greater > 0) {\r\n increase += 3 * greater;\r\n }\r\n }\r\n increase = Math.min(increase, text.length() / 5);\r\n StringBuilder buf = new StringBuilder(text.length() + increase);\r\n while (textIndex != -1) {\r\n for (int i = start; i < textIndex; i++) {\r\n buf.append(text.charAt(i));\r\n }\r\n buf.append(replacementList[replaceIndex]);\r\n start = textIndex + searchList[replaceIndex].length();\r\n textIndex = -1;\r\n replaceIndex = -1;\r\n for (int i = 0; i < searchLength; i++) {\r\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].isEmpty() || replacementList[i] == null) {\r\n continue;\r\n }\r\n tempIndex = text.indexOf(searchList[i], start);\r\n if (tempIndex == -1) {\r\n noMoreMatchesForReplIndex[i] = true;\r\n } else if (textIndex == -1 || tempIndex < textIndex) {\r\n textIndex = tempIndex;\r\n replaceIndex = i;\r\n }\r\n }\r\n }\r\n int textLength = text.length();\r\n for (int i = start; i < textLength; i++) {\r\n buf.append(text.charAt(i));\r\n }\r\n return buf.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Pair toUserUpdate(final UserTO before, final SCIMPatchOperation op){\r\n StatusR statusR = null;\r\n if (op.getPath() == null && op.getOp() != PatchOp.remove && !CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n SCIMUser after = (SCIMUser) op.getValue().get(0);\r\n if (after.getActive() != null && before.isSuspended() == after.isActive()) {\r\n statusR = new StatusR.Builder(before.getKey(), after.isActive() ? StatusRType.REACTIVATE : StatusRType.SUSPEND).build();\r\n }\r\n UserTO updated = toUserTO(after, false);\r\n updated.setKey(before.getKey());\r\n return Pair.of(AnyOperations.diff(updated, before, true), statusR);\r\n }\r\n UserUR userUR = new UserUR.Builder(before.getKey()).build();\r\n SCIMConf conf = confManager.get();\r\n if (conf == null) {\r\n return Pair.of(userUR, statusR);\r\n }\r\n switch(op.getPath().getAttribute()) {\r\n case \"externalId\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getExternalId(), op);\r\n break;\r\n case \"userName\":\r\n if (op.getOp() != PatchOp.remove && !CollectionUtils.isEmpty(op.getValue())) {\r\n userUR.setUsername(new StringReplacePatchItem.Builder().value(op.getValue().get(0).toString()).build());\r\n }\r\n break;\r\n case \"password\":\r\n if (op.getOp() != PatchOp.remove && !CollectionUtils.isEmpty(op.getValue())) {\r\n userUR.setPassword(new PasswordPatch.Builder().value(op.getValue().get(0).toString()).build());\r\n }\r\n break;\r\n case \"active\":\r\n if (!CollectionUtils.isEmpty(op.getValue())) {\r\n statusR = new StatusR.Builder(before.getKey(), (boolean) op.getValue().get(0) ? StatusRType.REACTIVATE : StatusRType.SUSPEND).build();\r\n }\r\n break;\r\n case \"name\":\r\n if (conf.getUserConf().getName() != null) {\r\n if (op.getPath().getSub() == null || \"familyName\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getFamilyName(), op);\r\n }\r\n if (op.getPath().getSub() == null || \"formatted\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getFormatted(), op);\r\n }\r\n if (op.getPath().getSub() == null || \"givenName\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getGivenName(), op);\r\n }\r\n if (op.getPath().getSub() == null || \"honorificPrefix\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getHonorificPrefix(), op);\r\n }\r\n if (op.getPath().getSub() == null || \"honorificSuffix\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getHonorificSuffix(), op);\r\n }\r\n if (op.getPath().getSub() == null || \"middleName\".equals(op.getPath().getSub())) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getName().getMiddleName(), op);\r\n }\r\n }\r\n break;\r\n case \"displayName\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getDisplayName(), op);\r\n break;\r\n case \"nickName\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getNickName(), op);\r\n break;\r\n case \"profileUrl\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getProfileUrl(), op);\r\n break;\r\n case \"title\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getTitle(), op);\r\n break;\r\n case \"userType\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getUserType(), op);\r\n break;\r\n case \"preferredLanguage\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getPreferredLanguage(), op);\r\n break;\r\n case \"locale\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getLocale(), op);\r\n break;\r\n case \"timezone\":\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getTimezone(), op);\r\n break;\r\n case \"emails\":\r\n if (!CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getEmails(), ((SCIMUser) op.getValue().get(0)).getEmails(), op.getOp());\r\n } else if (op.getPath().getFilter() != null) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getEmails(), op);\r\n }\r\n break;\r\n case \"phoneNumbers\":\r\n if (!CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getPhoneNumbers(), ((SCIMUser) op.getValue().get(0)).getPhoneNumbers(), op.getOp());\r\n } else if (op.getPath().getFilter() != null) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getPhoneNumbers(), op);\r\n }\r\n break;\r\n case \"ims\":\r\n if (!CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getIms(), ((SCIMUser) op.getValue().get(0)).getIms(), op.getOp());\r\n } else if (op.getPath().getFilter() != null) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getIms(), op);\r\n }\r\n break;\r\n case \"photos\":\r\n if (!CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getPhotos(), ((SCIMUser) op.getValue().get(0)).getPhotos(), op.getOp());\r\n } else if (op.getPath().getFilter() != null) {\r\n setAttribute(userUR.getPlainAttrs(), conf.getUserConf().getPhotos(), op);\r\n }\r\n break;\r\n case \"addresses\":\r\n if (!CollectionUtils.isEmpty(op.getValue()) && op.getValue().get(0) instanceof SCIMUser) {\r\n SCIMUser after = (SCIMUser) op.getValue().get(0);\r\n after.getAddresses().stream().filter(address -> address.getType() != null).forEach(address -> conf.getUserConf().getAddresses().stream().filter(object -> address.getType().equals(object.getType().name())).findFirst().ifPresent(addressConf -> setAttribute(userUR.getPlainAttrs(), addressConf, op)));\r\n } else if (op.getPath().getFilter() != null) {\r\n conf.getUserConf().getAddresses().stream().filter(addressConf -> BooleanUtils.toBoolean(JexlUtils.evaluate(filter2JexlExpression(op.getPath().getFilter()), new MapContext(Map.of(\"type\", addressConf.getType().name()))).toString())).findFirst().ifPresent(addressConf -> setAttribute(userUR.getPlainAttrs(), addressConf, op));\r\n }\r\n break;\r\n case \"employeeNumber\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getEmployeeNumber).orElse(null), op);\r\n break;\r\n case \"costCenter\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getCostCenter).orElse(null), op);\r\n break;\r\n case \"organization\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getOrganization).orElse(null), op);\r\n break;\r\n case \"division\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getDivision).orElse(null), op);\r\n break;\r\n case \"department\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getDepartment).orElse(null), op);\r\n break;\r\n case \"manager\":\r\n setAttribute(userUR.getPlainAttrs(), Optional.ofNullable(conf.getEnterpriseUserConf()).map(SCIMEnterpriseUserConf::getManager).map(SCIMManagerConf::getKey).orElse(null), op);\r\n break;\r\n default:\r\n }\r\n return Pair.of(userUR, statusR);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void load(){\r\n try {\r\n final Iterator hooks = ServiceLoader.iterator(SerializerHook.class, FACTORY_ID, classLoader);\r\n while (hooks.hasNext()) {\r\n final SerializerHook hook = hooks.next();\r\n final Class serializationType = hook.getSerializationType();\r\n if (serializationType != null) {\r\n serializers.put(serializationType, hook);\r\n }\r\n }\r\n } catch (Exception e) {\r\n throw ExceptionUtil.rethrow(e);\r\n }\r\n if (serializerConfigs != null) {\r\n for (SerializerConfig serializerConfig : serializerConfigs) {\r\n Serializer serializer = serializerConfig.getImplementation();\r\n Class serializationType = serializerConfig.getTypeClass();\r\n if (serializationType == null) {\r\n try {\r\n serializationType = ClassLoaderUtil.loadClass(classLoader, serializerConfig.getTypeClassName());\r\n } catch (ClassNotFoundException e) {\r\n throw new HazelcastSerializationException(e);\r\n }\r\n }\r\n if (serializer == null) {\r\n serializer = createSerializerInstance(serializerConfig, serializationType);\r\n }\r\n register(serializationType, serializer);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void onEventListener(final EventContext eventContext){\r\n boolean triggerReloading = false;\r\n ObjectMapper mapper = new ObjectMapper();\r\n final JsonNode actualObj = retrieveEventData(eventContext, mapper);\r\n for (int i = 0; i < actualObj.size(); i++) {\r\n String secret = actualObj.get(i).get(\"subject\").textValue();\r\n String eventType = actualObj.get(i).get(\"eventType\").textValue();\r\n if (ObjectHelper.isNotEmpty(secret) && ObjectHelper.isNotEmpty(eventType)) {\r\n if (eventType.equalsIgnoreCase(SECRET_VERSION_ADD)) {\r\n if (matchSecret(secret)) {\r\n if (ObjectHelper.isNotEmpty(eventContext.getEventData().getEnqueuedTime())) {\r\n updates.put(secret, eventContext.getEventData().getEnqueuedTime());\r\n }\r\n if (isReloadEnabled()) {\r\n LOG.info(\"Update for Azure secret: {} detected, triggering CamelContext reload\", secret);\r\n triggerReloading = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (triggerReloading) {\r\n ContextReloadStrategy reload = camelContext.hasService(ContextReloadStrategy.class);\r\n if (reload != null) {\r\n lastReloadTime = Instant.now();\r\n reload.onReload(this);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void sanityCheckFilesInfo(final ByteBuffer header, final ArchiveStatistics stats) throws IOException{\r\n stats.numberOfEntries = assertFitsIntoNonNegativeInt(\"numFiles\", readUint64(header));\r\n int emptyStreams = -1;\r\n while (true) {\r\n final int propertyType = getUnsignedByte(header);\r\n if (propertyType == 0) {\r\n break;\r\n }\r\n final long size = readUint64(header);\r\n switch(propertyType) {\r\n case NID.kEmptyStream:\r\n {\r\n emptyStreams = readBits(header, stats.numberOfEntries).cardinality();\r\n break;\r\n }\r\n case NID.kEmptyFile:\r\n {\r\n if (emptyStreams == -1) {\r\n throw new IOException(\"Header format error: kEmptyStream must appear before kEmptyFile\");\r\n }\r\n readBits(header, emptyStreams);\r\n break;\r\n }\r\n case NID.kAnti:\r\n {\r\n if (emptyStreams == -1) {\r\n throw new IOException(\"Header format error: kEmptyStream must appear before kAnti\");\r\n }\r\n readBits(header, emptyStreams);\r\n break;\r\n }\r\n case NID.kName:\r\n {\r\n final int external = getUnsignedByte(header);\r\n if (external != 0) {\r\n throw new IOException(\"Not implemented\");\r\n }\r\n final int namesLength = assertFitsIntoNonNegativeInt(\"file names length\", size - 1);\r\n if ((namesLength & 1) != 0) {\r\n throw new IOException(\"File names length invalid\");\r\n }\r\n int filesSeen = 0;\r\n for (int i = 0; i < namesLength; i += 2) {\r\n final char c = getChar(header);\r\n if (c == 0) {\r\n filesSeen++;\r\n }\r\n }\r\n if (filesSeen != stats.numberOfEntries) {\r\n throw new IOException(\"Invalid number of file names (\" + filesSeen + \" instead of \" + stats.numberOfEntries + \")\");\r\n }\r\n break;\r\n }\r\n case NID.kCTime:\r\n {\r\n final int timesDefined = readAllOrBits(header, stats.numberOfEntries).cardinality();\r\n final int external = getUnsignedByte(header);\r\n if (external != 0) {\r\n throw new IOException(\"Not implemented\");\r\n }\r\n if (skipBytesFully(header, 8L * timesDefined) < 8L * timesDefined) {\r\n throw new IOException(\"invalid creation dates size\");\r\n }\r\n break;\r\n }\r\n case NID.kATime:\r\n {\r\n final int timesDefined = readAllOrBits(header, stats.numberOfEntries).cardinality();\r\n final int external = getUnsignedByte(header);\r\n if (external != 0) {\r\n throw new IOException(\"Not implemented\");\r\n }\r\n if (skipBytesFully(header, 8L * timesDefined) < 8L * timesDefined) {\r\n throw new IOException(\"invalid access dates size\");\r\n }\r\n break;\r\n }\r\n case NID.kMTime:\r\n {\r\n final int timesDefined = readAllOrBits(header, stats.numberOfEntries).cardinality();\r\n final int external = getUnsignedByte(header);\r\n if (external != 0) {\r\n throw new IOException(\"Not implemented\");\r\n }\r\n if (skipBytesFully(header, 8L * timesDefined) < 8L * timesDefined) {\r\n throw new IOException(\"invalid modification dates size\");\r\n }\r\n break;\r\n }\r\n case NID.kWinAttributes:\r\n {\r\n final int attributesDefined = readAllOrBits(header, stats.numberOfEntries).cardinality();\r\n final int external = getUnsignedByte(header);\r\n if (external != 0) {\r\n throw new IOException(\"Not implemented\");\r\n }\r\n if (skipBytesFully(header, 4L * attributesDefined) < 4L * attributesDefined) {\r\n throw new IOException(\"invalid windows attributes size\");\r\n }\r\n break;\r\n }\r\n case NID.kStartPos:\r\n {\r\n throw new IOException(\"kStartPos is unsupported, please report\");\r\n }\r\n case NID.kDummy:\r\n {\r\n if (skipBytesFully(header, size) < size) {\r\n throw new IOException(\"Incomplete kDummy property\");\r\n }\r\n break;\r\n }\r\n default:\r\n {\r\n if (skipBytesFully(header, size) < size) {\r\n throw new IOException(\"Incomplete property of type \" + propertyType);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n stats.numberOfEntriesWithStream = stats.numberOfEntries - Math.max(emptyStreams, 0);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CloseableIterable filterBatch(CloseableIterable batches){\r\n SwappableHiveRowIterable deleteInputIterable = new SwappableHiveRowIterable();\r\n CloseableIterable deleteOutputIterable = filter(deleteInputIterable);\r\n CloseableIterator deleteOutputIterator = deleteOutputIterable.iterator();\r\n return new CloseableIterable() {\r\n\r\n @Override\r\n public CloseableIterator iterator() {\r\n CloseableIterator srcIterator = batches.iterator();\r\n return new CloseableIterator() {\r\n\r\n @Override\r\n public boolean hasNext() {\r\n return srcIterator.hasNext();\r\n }\r\n\r\n @Override\r\n public HiveBatchContext next() {\r\n try {\r\n if (!hasNext()) {\r\n throw new NoSuchElementException();\r\n }\r\n HiveBatchContext currentBatchContext = srcIterator.next();\r\n deleteInputIterable.currentRowIterator = currentBatchContext.rowIterator();\r\n VectorizedRowBatch batch = currentBatchContext.getBatch();\r\n int oldSize = batch.size;\r\n int newSize = 0;\r\n while (deleteOutputIterator.hasNext()) {\r\n HiveRow row = deleteOutputIterator.next();\r\n if (!row.isDeleted()) {\r\n batch.selected[newSize++] = row.physicalBatchIndex();\r\n }\r\n }\r\n if (newSize < oldSize) {\r\n batch.size = newSize;\r\n batch.selectedInUse = true;\r\n }\r\n return currentBatchContext;\r\n } catch (IOException e) {\r\n throw new UncheckedIOException(e);\r\n }\r\n }\r\n\r\n @Override\r\n public void close() throws IOException {\r\n srcIterator.close();\r\n }\r\n };\r\n }\r\n\r\n @Override\r\n public void close() throws IOException {\r\n batches.close();\r\n }\r\n };\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private CSLItemData bibEntryToCSLItemData(BibEntry originalBibEntry, BibDatabaseContext bibDatabaseContext, BibEntryTypesManager entryTypesManager){\r\n BibEntry bibEntry = (BibEntry) originalBibEntry.clone();\r\n String citeKey = bibEntry.getCitationKey().orElse(\"\");\r\n BibTeXEntry bibTeXEntry = new BibTeXEntry(new Key(bibEntry.getType().getName()), new Key(citeKey));\r\n RemoveNewlinesFormatter removeNewlinesFormatter = new RemoveNewlinesFormatter();\r\n Optional entryType = entryTypesManager.enrich(bibEntry.getType(), bibDatabaseContext.getMode());\r\n if (bibEntry.getType().equals(StandardEntryType.Article)) {\r\n if (bibDatabaseContext.isBiblatexMode()) {\r\n Optional numberField = bibEntry.getField(StandardField.NUMBER);\r\n numberField.ifPresent(number -> {\r\n bibEntry.setField(StandardField.ISSUE, number);\r\n bibEntry.clearField(StandardField.NUMBER);\r\n });\r\n bibEntry.getField(StandardField.EID).ifPresent(eid -> {\r\n if (!bibEntry.hasField(StandardField.NUMBER)) {\r\n bibEntry.setField(StandardField.NUMBER, eid);\r\n bibEntry.clearField(StandardField.EID);\r\n }\r\n });\r\n } else {\r\n bibEntry.getField(StandardField.NUMBER).ifPresent(number -> {\r\n bibEntry.setField(StandardField.ISSUE, number);\r\n bibEntry.clearField(StandardField.NUMBER);\r\n });\r\n bibEntry.getField(StandardField.PAGES).ifPresent(pages -> {\r\n if (pages.toLowerCase(Locale.ROOT).startsWith(\"article \")) {\r\n pages = pages.substring(\"Article \".length());\r\n bibEntry.setField(StandardField.NUMBER, pages);\r\n }\r\n });\r\n bibEntry.getField(StandardField.EID).ifPresent(eid -> {\r\n if (!bibEntry.hasField(StandardField.PAGES)) {\r\n bibEntry.setField(StandardField.PAGES, eid);\r\n bibEntry.clearField(StandardField.EID);\r\n }\r\n });\r\n }\r\n }\r\n Set fields = entryType.map(BibEntryType::getAllFields).orElse(bibEntry.getFields());\r\n fields.addAll(bibEntry.getFields());\r\n for (Field key : fields) {\r\n bibEntry.getResolvedFieldOrAlias(key, bibDatabaseContext.getDatabase()).map(removeNewlinesFormatter::format).map(LatexToUnicodeAdapter::format).ifPresent(value -> {\r\n if (StandardField.MONTH == key) {\r\n value = bibEntry.getMonth().map(Month::getShortName).orElse(value);\r\n }\r\n bibTeXEntry.addField(new Key(key.getName()), new DigitStringValue(value));\r\n });\r\n }\r\n return BIBTEX_CONVERTER.toItemData(bibTeXEntry);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void buildMetaAttributes(final RuleBuildContext context){\r\n RuleImpl rule = context.getRule();\r\n for (String metaAttr : context.getRuleDescr().getAnnotationNames()) {\r\n AnnotationDescr ad = context.getRuleDescr().getAnnotation(metaAttr);\r\n String adFqn = ad.getFullyQualifiedName();\r\n if (adFqn != null) {\r\n AnnotationDefinition annotationDefinition;\r\n try {\r\n annotationDefinition = AnnotationDefinition.build(context.getDialect().getTypeResolver().resolveType(adFqn), ad.getValueMap(), context.getDialect().getTypeResolver());\r\n } catch (NoSuchMethodException e) {\r\n throw new RuntimeException(e);\r\n } catch (ClassNotFoundException e) {\r\n throw new RuntimeException(e);\r\n }\r\n if (annotationDefinition.getValues().size() == 1 && annotationDefinition.getValues().containsKey(AnnotationDescr.VALUE)) {\r\n rule.addMetaAttribute(metaAttr, annotationDefinition.getPropertyValue(AnnotationDescr.VALUE));\r\n } else {\r\n Map map = new HashMap<>(annotationDefinition.getValues().size());\r\n for (String key : annotationDefinition.getValues().keySet()) {\r\n map.put(key, annotationDefinition.getPropertyValue(key));\r\n }\r\n rule.addMetaAttribute(metaAttr, map);\r\n }\r\n } else {\r\n if (ad.hasValue()) {\r\n if (ad.getValueMap().size() == 1) {\r\n rule.addMetaAttribute(metaAttr, resolveValue(ad.getSingleValueAsString()));\r\n } else {\r\n rule.addMetaAttribute(metaAttr, ad.getValueMap());\r\n }\r\n } else {\r\n rule.addMetaAttribute(metaAttr, null);\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void startServerBootstrap() throws Exception{\r\n EventLoopGroup bg = configuration.getBossGroup();\r\n EventLoopGroup wg = configuration.getWorkerGroup();\r\n if (bg == null) {\r\n bossGroup = new NettyServerBossPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withBossCount(configuration.getBossCount()).withName(\"NettyServerTCPBoss\").build();\r\n bg = bossGroup;\r\n }\r\n if (wg == null) {\r\n workerGroup = new NettyWorkerPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withWorkerCount(configuration.getWorkerCount()).withName(\"NettyServerTCPWorker\").build();\r\n wg = workerGroup;\r\n }\r\n serverBootstrap = new ServerBootstrap();\r\n if (configuration.getUnixDomainSocketPath() != null) {\r\n serverBootstrap.group(bg, wg).channel(EpollServerDomainSocketChannel.class);\r\n } else {\r\n if (configuration.isNativeTransport()) {\r\n serverBootstrap.group(bg, wg).channel(EpollServerSocketChannel.class);\r\n } else {\r\n serverBootstrap.group(bg, wg).channel(NioServerSocketChannel.class);\r\n }\r\n }\r\n serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());\r\n serverBootstrap.childOption(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());\r\n serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());\r\n serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());\r\n serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());\r\n if (configuration.getBacklog() > 0) {\r\n serverBootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());\r\n }\r\n Map options = configuration.getOptions();\r\n if (options != null) {\r\n for (Map.Entry entry : options.entrySet()) {\r\n String value = entry.getValue().toString();\r\n ChannelOption option = ChannelOption.valueOf(entry.getKey());\r\n if (EndpointHelper.isReferenceParameter(value)) {\r\n String name = value.substring(1);\r\n Object o = CamelContextHelper.mandatoryLookup(camelContext, name);\r\n serverBootstrap.option(option, o);\r\n } else {\r\n serverBootstrap.option(option, value);\r\n }\r\n }\r\n }\r\n serverBootstrap.childHandler(pipelineFactory);\r\n LOG.debug(\"Created ServerBootstrap {}\", serverBootstrap);\r\n SocketAddress socketAddress;\r\n if (configuration.getUnixDomainSocketPath() != null) {\r\n Path udsPath = Path.of(configuration.getUnixDomainSocketPath()).toAbsolutePath();\r\n LOG.info(\"ServerBootstrap binding to {}\", udsPath);\r\n socketAddress = new DomainSocketAddress(udsPath.toFile());\r\n } else {\r\n LOG.info(\"ServerBootstrap binding to {}:{}\", configuration.getHost(), configuration.getPort());\r\n socketAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());\r\n }\r\n ChannelFuture channelFuture = serverBootstrap.bind(socketAddress).sync();\r\n channel = channelFuture.channel();\r\n allChannels.add(channel);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getDefaultConnectionUrl(CommandLine cl) throws BeelineConfFileParseException{\r\n Properties mergedConnectionProperties = new Properties();\r\n JdbcConnectionParams jdbcConnectionParams = null;\r\n BeelineSiteParser beelineSiteParser = getUserBeelineSiteParser();\r\n UserHS2ConnectionFileParser userHS2ConnFileParser = getUserHS2ConnFileParser();\r\n Properties userConnectionProperties = new Properties();\r\n if (!userHS2ConnFileParser.configExists() && !beelineSiteParser.configExists()) {\r\n return null;\r\n }\r\n if (beelineSiteParser.configExists()) {\r\n String urlFromCommandLineOption = cl.getOptionValue(\"u\");\r\n if (urlFromCommandLineOption != null) {\r\n throw new BeelineSiteParseException(\"Not using beeline-site.xml since the user provided the url: \" + urlFromCommandLineOption);\r\n }\r\n Properties userNamedConnectionURLs = beelineSiteParser.getConnectionProperties();\r\n if (!userNamedConnectionURLs.isEmpty()) {\r\n String urlName = cl.getOptionValue(\"c\");\r\n String jdbcURL = HS2ConnectionFileUtils.getNamedUrl(userNamedConnectionURLs, urlName);\r\n if (jdbcURL != null) {\r\n try {\r\n jdbcConnectionParams = Utils.extractURLComponents(jdbcURL, new Properties());\r\n } catch (JdbcUriParseException e) {\r\n throw new BeelineSiteParseException(\"Error in parsing jdbc url: \" + jdbcURL + \" from beeline-site.xml\", e);\r\n }\r\n }\r\n }\r\n }\r\n if (userHS2ConnFileParser.configExists()) {\r\n userConnectionProperties = userHS2ConnFileParser.getConnectionProperties();\r\n }\r\n if (jdbcConnectionParams != null) {\r\n String userName = cl.getOptionValue(\"n\");\r\n if (userName != null) {\r\n jdbcConnectionParams.getSessionVars().put(JdbcConnectionParams.AUTH_USER, userName);\r\n }\r\n String password = cl.getOptionValue(\"p\");\r\n if (password != null) {\r\n jdbcConnectionParams.getSessionVars().put(JdbcConnectionParams.AUTH_PASSWD, password);\r\n }\r\n String auth = cl.getOptionValue(\"a\");\r\n if (auth != null) {\r\n jdbcConnectionParams.getSessionVars().put(JdbcConnectionParams.AUTH_TYPE, auth);\r\n }\r\n mergedConnectionProperties = HS2ConnectionFileUtils.mergeUserConnectionPropertiesAndBeelineSite(userConnectionProperties, jdbcConnectionParams);\r\n } else {\r\n mergedConnectionProperties = userConnectionProperties;\r\n }\r\n HS2ConnectionFileParser hiveSiteParser = getHiveSiteHS2ConnectionFileParser();\r\n Properties hiveSiteConnectionProperties = hiveSiteParser.getConnectionProperties();\r\n for (String key : mergedConnectionProperties.stringPropertyNames()) {\r\n if (hiveSiteConnectionProperties.containsKey(key)) {\r\n debug(\"Overriding connection url property \" + key + \" from user connection configuration file\");\r\n }\r\n hiveSiteConnectionProperties.setProperty(key, mergedConnectionProperties.getProperty(key));\r\n }\r\n return HS2ConnectionFileUtils.getUrl(hiveSiteConnectionProperties);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static void createMissingMetadata(final ZooKeeper zk, final String basePath, final String logRootPath, final List> metadatas, final List acl, final boolean ownAllocator, final boolean createIfNotExists, final CompletableFuture>> promise){\r\n final List pathsToCreate = Lists.newArrayListWithExpectedSize(metadatas.size());\r\n final List zkOps = Lists.newArrayListWithExpectedSize(metadatas.size());\r\n CreateMode createMode = CreateMode.PERSISTENT;\r\n String logRootParentPath = Utils.getParent(logRootPath);\r\n if (pathExists(metadatas.get(MetadataIndex.LOG_ROOT_PARENT))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(Op.create(logRootParentPath, EMPTY_BYTES, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.LOG_ROOT))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(Op.create(logRootPath, EMPTY_BYTES, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.MAX_TXID))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n byte[] zeroTxnIdData = DLUtils.serializeTransactionId(0L);\r\n pathsToCreate.add(zeroTxnIdData);\r\n zkOps.add(Op.create(logRootPath + MAX_TXID_PATH, zeroTxnIdData, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.VERSION))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n byte[] versionData = intToBytes(LAYOUT_VERSION);\r\n pathsToCreate.add(versionData);\r\n zkOps.add(Op.create(logRootPath + VERSION_PATH, versionData, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.LOCK))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(Op.create(logRootPath + LOCK_PATH, EMPTY_BYTES, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.READ_LOCK))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(Op.create(logRootPath + READ_LOCK_PATH, EMPTY_BYTES, acl, createMode));\r\n }\r\n if (pathExists(metadatas.get(MetadataIndex.LOGSEGMENTS))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n byte[] logSegmentsData = DLUtils.serializeLogSegmentSequenceNumber(DistributedLogConstants.UNASSIGNED_LOGSEGMENT_SEQNO);\r\n pathsToCreate.add(logSegmentsData);\r\n zkOps.add(Op.create(logRootPath + LOGSEGMENTS_PATH, logSegmentsData, acl, createMode));\r\n }\r\n if (ownAllocator) {\r\n if (pathExists(metadatas.get(MetadataIndex.ALLOCATION))) {\r\n pathsToCreate.add(null);\r\n } else {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(Op.create(logRootPath + ALLOCATION_PATH, EMPTY_BYTES, acl, createMode));\r\n }\r\n }\r\n if (zkOps.isEmpty()) {\r\n promise.complete(metadatas);\r\n return;\r\n }\r\n if (!createIfNotExists) {\r\n promise.completeExceptionally(new LogNotFoundException(\"Log \" + logRootPath + \" not found\"));\r\n return;\r\n }\r\n getMissingPaths(zk, basePath, Utils.getParent(logRootParentPath)).whenComplete(new FutureEventListener>() {\r\n\r\n @Override\r\n public void onSuccess(List paths) {\r\n for (String path : paths) {\r\n pathsToCreate.add(EMPTY_BYTES);\r\n zkOps.add(0, Op.create(path, EMPTY_BYTES, acl, createMode));\r\n }\r\n executeCreateMissingPathTxn(zk, zkOps, pathsToCreate, metadatas, logRootPath, promise);\r\n }\r\n\r\n @Override\r\n public void onFailure(Throwable cause) {\r\n promise.completeExceptionally(cause);\r\n return;\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void unsafeReinitializeLogSegments(List segments){\r\n logger.info(\"Reinitialize log segments with {}\", segments);\r\n int segmentIdx = 0;\r\n for (; segmentIdx < segments.size(); segmentIdx++) {\r\n LogSegmentMetadata segment = segments.get(segmentIdx);\r\n if (segment.getLogSegmentSequenceNumber() < currentSegmentSequenceNumber) {\r\n continue;\r\n }\r\n break;\r\n }\r\n if (segmentIdx >= segments.size()) {\r\n return;\r\n }\r\n LogSegmentMetadata segment = segments.get(segmentIdx);\r\n if (null != currentSegmentReader) {\r\n if (!updateLogSegmentMetadata(currentSegmentReader, segment)) {\r\n return;\r\n }\r\n } else {\r\n if (currentSegmentSequenceNumber != segment.getLogSegmentSequenceNumber()) {\r\n logger.error(\"Inconsistent state found in entry reader for {} : \" + \"current segment sn = {}, new segment sn = {}\", streamName, currentSegmentSequenceNumber, segment.getLogSegmentSequenceNumber());\r\n setLastException(new DLIllegalStateException(\"Inconsistent state found in entry reader for \" + streamName + \" : current segment sn = \" + currentSegmentSequenceNumber + \", new segment sn = \" + segment.getLogSegmentSequenceNumber()));\r\n return;\r\n }\r\n }\r\n segmentIdx++;\r\n if (segmentIdx >= segments.size()) {\r\n return;\r\n }\r\n segment = segments.get(segmentIdx);\r\n if (null != nextSegmentReader) {\r\n if (!updateLogSegmentMetadata(nextSegmentReader, segment)) {\r\n return;\r\n }\r\n segmentIdx++;\r\n }\r\n for (int readerIdx = 0; readerIdx < segmentReaders.size() && segmentIdx < segments.size(); readerIdx++, segmentIdx++) {\r\n SegmentReader reader = segmentReaders.get(readerIdx);\r\n segment = segments.get(segmentIdx);\r\n if (!updateLogSegmentMetadata(reader, segment)) {\r\n return;\r\n }\r\n }\r\n for (; segmentIdx < segments.size(); segmentIdx++) {\r\n segment = segments.get(segmentIdx);\r\n SegmentReader reader = new SegmentReader(segment, 0L);\r\n reader.openReader();\r\n segmentReaders.add(reader);\r\n }\r\n if (null == currentSegmentReader) {\r\n unsafeMoveToNextLogSegment();\r\n }\r\n scheduleRead();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void twoDatabaseStopPointThreeTest(ValidationReporter validationReporter, Context context, StopArea oldSA, StopArea newSA, ValidationData data){\r\n if (!NeptuneUtil.sameValue(oldSA, newSA)) {\r\n if (validationReporter == null) {\r\n log.error(\"ValidationReporter (validationReporter) is null\");\r\n }\r\n if (oldSA == null) {\r\n log.warn(\"StopArea (oldSA) is null\");\r\n }\r\n if (newSA == null) {\r\n log.warn(\"StopArea (newSA) is null\");\r\n }\r\n if (data == null) {\r\n log.error(\"ValidationData (data) is null\");\r\n } else if (data.getDataLocations() == null) {\r\n log.error(\"ValidationData.getDataLocations() is null\");\r\n } else if (oldSA != null && newSA != null && data.getDataLocations().get(newSA.getObjectId()) == null) {\r\n log.error(\"No data location for new stop area: \" + newSA.getObjectId() + \" unlike old stop area: \" + oldSA.getObjectId());\r\n }\r\n if (validationReporter != null && newSA != null && data != null && data.getDataLocations() != null) {\r\n validationReporter.addCheckPointReportError(context, DATABASE_STOP_POINT_3, data.getDataLocations().get(newSA.getObjectId()));\r\n }\r\n } else\r\n validationReporter.reportSuccess(context, DATABASE_STOP_POINT_3);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public final boolean isInitialized(){\r\n byte isInitialized = memoizedIsInitialized;\r\n if (isInitialized == 1)\r\n return true;\r\n if (isInitialized == 0)\r\n return false;\r\n if (!hasNetworkIdentifier()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n for (int i = 0; i < getKeyCount(); i++) {\r\n if (!getKey(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n for (int i = 0; i < getTransactionCount(); i++) {\r\n if (!getTransaction(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n for (int i = 0; i < getWatchedScriptCount(); i++) {\r\n if (!getWatchedScript(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n if (hasEncryptionParameters()) {\r\n if (!getEncryptionParameters().isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n for (int i = 0; i < getExtensionCount(); i++) {\r\n if (!getExtension(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n for (int i = 0; i < getTagsCount(); i++) {\r\n if (!getTags(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n for (int i = 0; i < getTransactionSignersCount(); i++) {\r\n if (!getTransactionSigners(i).isInitialized()) {\r\n memoizedIsInitialized = 0;\r\n return false;\r\n }\r\n }\r\n memoizedIsInitialized = 1;\r\n return true;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static Type gcd(Type... types){\r\n if (types.length == 0) {\r\n return Object.class;\r\n }\r\n Type best = types[0];\r\n Primitive bestPrimitive = Primitive.of(best);\r\n if (bestPrimitive != null) {\r\n for (int i = 1; i < types.length; i++) {\r\n final Primitive primitive = Primitive.of(types[i]);\r\n if (primitive == null) {\r\n return Object.class;\r\n }\r\n if (primitive.assignableFrom(bestPrimitive)) {\r\n bestPrimitive = primitive;\r\n } else if (bestPrimitive.assignableFrom(primitive)) {\r\n } else if (bestPrimitive == Primitive.CHAR || bestPrimitive == Primitive.BYTE) {\r\n bestPrimitive = Primitive.INT;\r\n --i;\r\n } else {\r\n return Object.class;\r\n }\r\n }\r\n return requireNonNull(bestPrimitive.primitiveClass);\r\n } else {\r\n for (int i = 1; i < types.length; i++) {\r\n if (types[i] != types[0]) {\r\n return Object.class;\r\n }\r\n }\r\n }\r\n return types[0];\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " int removeIf(LongObjectPredicate filter){\r\n long stamp = writeLock();\r\n int removedCount = 0;\r\n try {\r\n int capacity = this.capacity;\r\n for (int bucket = 0; bucket < capacity; bucket++) {\r\n long storedKey = keys[bucket];\r\n V storedValue = values[bucket];\r\n if (storedValue != EmptyValue && storedValue != DeletedValue) {\r\n if (filter.test(storedKey, storedValue)) {\r\n --size;\r\n ++removedCount;\r\n V nextValueInArray = values[signSafeMod(bucket + 1, capacity)];\r\n if (nextValueInArray == EmptyValue) {\r\n values[bucket] = (V) EmptyValue;\r\n --usedBuckets;\r\n cleanDeletedStatus(bucket);\r\n } else {\r\n values[bucket] = (V) DeletedValue;\r\n }\r\n }\r\n }\r\n }\r\n return removedCount;\r\n } finally {\r\n if (autoShrink && size < resizeThresholdBelow) {\r\n try {\r\n int newCapacity = alignToPowerOfTwo((int) (capacity / shrinkFactor));\r\n int newResizeThresholdUp = (int) (newCapacity * mapFillFactor);\r\n if (newCapacity < capacity && newResizeThresholdUp > size) {\r\n rehash(newCapacity);\r\n }\r\n } finally {\r\n unlockWrite(stamp);\r\n }\r\n } else {\r\n unlockWrite(stamp);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private AttributeDescr booleanAttribute(AttributeSupportBuilder as, String[] key) throws RecognitionException{\r\n AttributeDescrBuilder attribute = null;\r\n try {\r\n StringBuilder builder = new StringBuilder();\r\n for (String k : key) {\r\n if (\"-\".equals(k)) {\r\n match(input, DRL6Lexer.MINUS, k, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n } else {\r\n match(input, DRL6Lexer.ID, k, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n }\r\n builder.append(k);\r\n }\r\n if (state.backtracking == 0) {\r\n attribute = helper.start((DescrBuilder) as, AttributeDescrBuilder.class, builder.toString());\r\n }\r\n String value = \"true\";\r\n if (input.LA(1) == DRL6Lexer.BOOL) {\r\n Token bool = match(input, DRL6Lexer.BOOL, null, null, DroolsEditorType.KEYWORD);\r\n if (state.failed)\r\n return null;\r\n value = bool.getText();\r\n }\r\n if (state.backtracking == 0) {\r\n if (attribute != null) {\r\n attribute.value(value);\r\n attribute.type(AttributeDescr.Type.BOOLEAN);\r\n }\r\n }\r\n } finally {\r\n if (attribute != null) {\r\n helper.end(AttributeDescrBuilder.class, attribute);\r\n }\r\n }\r\n return attribute != null ? attribute.getDescr() : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public byte[] encodeBandInt(final String name, final int[] ints, final BHSDCodec defaultCodec) throws Pack200Exception{\r\n byte[] encodedBand = null;\r\n if (effort > 1 && (ints.length >= effortThresholds[effort])) {\r\n final BandAnalysisResults results = analyseBand(name, ints, defaultCodec);\r\n final Codec betterCodec = results.betterCodec;\r\n encodedBand = results.encodedBand;\r\n if (betterCodec != null) {\r\n if (betterCodec instanceof BHSDCodec) {\r\n final int[] specifierBand = CodecEncoding.getSpecifier(betterCodec, defaultCodec);\r\n int specifier = specifierBand[0];\r\n if (specifierBand.length > 1) {\r\n for (int i = 1; i < specifierBand.length; i++) {\r\n segmentHeader.appendBandCodingSpecifier(specifierBand[i]);\r\n }\r\n }\r\n if (defaultCodec.isSigned()) {\r\n specifier = -1 - specifier;\r\n } else {\r\n specifier = specifier + defaultCodec.getL();\r\n }\r\n final byte[] specifierEncoded = defaultCodec.encode(new int[] { specifier });\r\n final byte[] band = new byte[specifierEncoded.length + encodedBand.length];\r\n System.arraycopy(specifierEncoded, 0, band, 0, specifierEncoded.length);\r\n System.arraycopy(encodedBand, 0, band, specifierEncoded.length, encodedBand.length);\r\n return band;\r\n }\r\n if (betterCodec instanceof PopulationCodec) {\r\n IntStream.of(results.extraMetadata).forEach(segmentHeader::appendBandCodingSpecifier);\r\n return encodedBand;\r\n }\r\n if (betterCodec instanceof RunCodec) {\r\n }\r\n }\r\n }\r\n if (ints.length > 0) {\r\n if (encodedBand == null) {\r\n encodedBand = defaultCodec.encode(ints);\r\n }\r\n final int first = ints[0];\r\n if (defaultCodec.getB() != 1) {\r\n if (defaultCodec.isSigned() && first >= -256 && first <= -1) {\r\n final int specifier = -1 - CodecEncoding.getSpecifierForDefaultCodec(defaultCodec);\r\n final byte[] specifierEncoded = defaultCodec.encode(new int[] { specifier });\r\n final byte[] band = new byte[specifierEncoded.length + encodedBand.length];\r\n System.arraycopy(specifierEncoded, 0, band, 0, specifierEncoded.length);\r\n System.arraycopy(encodedBand, 0, band, specifierEncoded.length, encodedBand.length);\r\n return band;\r\n }\r\n if (!defaultCodec.isSigned() && first >= defaultCodec.getL() && first <= defaultCodec.getL() + 255) {\r\n final int specifier = CodecEncoding.getSpecifierForDefaultCodec(defaultCodec) + defaultCodec.getL();\r\n final byte[] specifierEncoded = defaultCodec.encode(new int[] { specifier });\r\n final byte[] band = new byte[specifierEncoded.length + encodedBand.length];\r\n System.arraycopy(specifierEncoded, 0, band, 0, specifierEncoded.length);\r\n System.arraycopy(encodedBand, 0, band, specifierEncoded.length, encodedBand.length);\r\n return band;\r\n }\r\n }\r\n return encodedBand;\r\n }\r\n return new byte[0];\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static List flattenScope(TypeResolver typeResolver, Expression expressionWithScope){\r\n List res = new ArrayList<>();\r\n if (expressionWithScope instanceof FullyQualifiedInlineCastExpr) {\r\n res.addAll(flattenScope(typeResolver, transformFullyQualifiedInlineCastExpr(typeResolver, (FullyQualifiedInlineCastExpr) expressionWithScope)));\r\n } else if (expressionWithScope instanceof FieldAccessExpr) {\r\n FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) expressionWithScope;\r\n res.addAll(flattenScope(typeResolver, fieldAccessExpr.getScope()));\r\n res.add(fieldAccessExpr.getName());\r\n } else if (expressionWithScope instanceof NullSafeFieldAccessExpr) {\r\n NullSafeFieldAccessExpr fieldAccessExpr = (NullSafeFieldAccessExpr) expressionWithScope;\r\n res.addAll(flattenScope(typeResolver, fieldAccessExpr.getScope()));\r\n res.add(fieldAccessExpr.getName());\r\n } else if (expressionWithScope instanceof MethodCallExpr) {\r\n MethodCallExpr methodCallExpr = (MethodCallExpr) expressionWithScope;\r\n if (methodCallExpr.getScope().isPresent()) {\r\n Expression scope = methodCallExpr.getScope().get();\r\n if (isFullyQualifiedClassName(typeResolver, scope)) {\r\n res.add(scope);\r\n } else {\r\n res.addAll(flattenScope(typeResolver, scope));\r\n }\r\n }\r\n res.add(methodCallExpr);\r\n } else if (expressionWithScope instanceof NullSafeMethodCallExpr) {\r\n NullSafeMethodCallExpr methodCallExpr = (NullSafeMethodCallExpr) expressionWithScope;\r\n if (methodCallExpr.getScope().isPresent()) {\r\n res.addAll(flattenScope(typeResolver, methodCallExpr.getScope().orElseThrow(() -> new IllegalStateException(\"Scope expression is not present!\"))));\r\n }\r\n res.add(methodCallExpr);\r\n } else if (expressionWithScope instanceof InlineCastExpr && ((InlineCastExpr) expressionWithScope).getExpression() instanceof FieldAccessExpr) {\r\n InlineCastExpr inlineCastExpr = (InlineCastExpr) expressionWithScope;\r\n Expression internalScope = ((FieldAccessExpr) inlineCastExpr.getExpression()).getScope();\r\n res.addAll(flattenScope(typeResolver, internalScope));\r\n res.add(expressionWithScope);\r\n } else if (expressionWithScope instanceof ArrayAccessExpr) {\r\n ArrayAccessExpr arrayAccessExpr = (ArrayAccessExpr) expressionWithScope;\r\n res.addAll(flattenScope(typeResolver, arrayAccessExpr.getName()));\r\n res.add(arrayAccessExpr);\r\n } else if (expressionWithScope instanceof EnclosedExpr) {\r\n res.addAll(flattenScope(typeResolver, ((EnclosedExpr) expressionWithScope).getInner()));\r\n } else {\r\n res.add(expressionWithScope);\r\n }\r\n return res;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void printArguments(final NodeList args, final Void arg){\r\n printer.print(\"(\");\r\n if (!isNullOrEmpty(args)) {\r\n boolean columnAlignParameters = (args.size() > 1) && configuration.get(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.COLUMN_ALIGN_PARAMETERS)).map(ConfigurationOption::asBoolean).orElse(false);\r\n if (columnAlignParameters) {\r\n printer.indentWithAlignTo(printer.getCursor().column);\r\n }\r\n for (final Iterator i = args.iterator(); i.hasNext(); ) {\r\n final Expression e = i.next();\r\n e.accept(this, arg);\r\n if (i.hasNext()) {\r\n printer.print(\",\");\r\n if (columnAlignParameters) {\r\n printer.println();\r\n } else {\r\n printer.print(\" \");\r\n }\r\n }\r\n }\r\n if (columnAlignParameters) {\r\n printer.unindent();\r\n }\r\n }\r\n printer.print(\")\");\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void run(){\r\n while (!ServerLifeCycleManager.isStopped()) {\r\n try {\r\n if (MapUtils.isEmpty(needToRetryMessages)) {\r\n Thread.sleep(MESSAGE_RETRY_WINDOW);\r\n }\r\n long now = System.currentTimeMillis();\r\n Iterator>> iterator = needToRetryMessages.entrySet().iterator();\r\n while (iterator.hasNext()) {\r\n Map.Entry> taskEntry = iterator.next();\r\n Integer taskInstanceId = taskEntry.getKey();\r\n List taskInstanceMessages = taskEntry.getValue();\r\n if (taskInstanceMessages.isEmpty()) {\r\n iterator.remove();\r\n continue;\r\n }\r\n LogUtils.setTaskInstanceIdMDC(taskInstanceId);\r\n try {\r\n for (TaskInstanceMessage taskInstanceMessage : taskInstanceMessages) {\r\n ITaskInstanceExecutionEvent.TaskInstanceExecutionEventType eventType = taskInstanceMessage.getEventType();\r\n ITaskInstanceExecutionEvent event = taskInstanceMessage.getEvent();\r\n if (now - event.getEventSendTime() > MESSAGE_RETRY_WINDOW) {\r\n log.info(\"Begin retry send message to master, event: {}\", event);\r\n event.setEventSendTime(now);\r\n messageSenderMap.get(eventType).sendEvent(event);\r\n log.info(\"Success send message to master, event: {}\", event);\r\n }\r\n }\r\n } catch (Exception e) {\r\n log.warn(\"Retry send message to master error\", e);\r\n } finally {\r\n LogUtils.removeTaskInstanceIdMDC();\r\n }\r\n }\r\n Thread.sleep(Constants.SLEEP_TIME_MILLIS);\r\n } catch (InterruptedException instance) {\r\n log.warn(\"The message retry thread is interrupted, will break this loop\", instance);\r\n Thread.currentThread().interrupt();\r\n break;\r\n } catch (Exception ex) {\r\n log.error(\"Retry send message failed, get an known exception.\", ex);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static float scalb(final float f, final int n){\r\n if ((n > -127) && (n < 128)) {\r\n return f * Float.intBitsToFloat((n + 127) << 23);\r\n }\r\n if (Float.isNaN(f) || Float.isInfinite(f) || (f == 0f)) {\r\n return f;\r\n }\r\n if (n < -277) {\r\n return (f > 0) ? 0.0f : -0.0f;\r\n }\r\n if (n > 276) {\r\n return (f > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;\r\n }\r\n final int bits = Float.floatToIntBits(f);\r\n final int sign = bits & 0x80000000;\r\n int exponent = (bits >>> 23) & 0xff;\r\n int mantissa = bits & 0x007fffff;\r\n int scaledExponent = exponent + n;\r\n if (n < 0) {\r\n if (scaledExponent > 0) {\r\n return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);\r\n } else if (scaledExponent > -24) {\r\n mantissa |= 1 << 23;\r\n final int mostSignificantLostBit = mantissa & (1 << (-scaledExponent));\r\n mantissa >>>= 1 - scaledExponent;\r\n if (mostSignificantLostBit != 0) {\r\n mantissa++;\r\n }\r\n return Float.intBitsToFloat(sign | mantissa);\r\n } else {\r\n return (sign == 0) ? 0.0f : -0.0f;\r\n }\r\n } else {\r\n if (exponent == 0) {\r\n while ((mantissa >>> 23) != 1) {\r\n mantissa <<= 1;\r\n --scaledExponent;\r\n }\r\n ++scaledExponent;\r\n mantissa &= 0x007fffff;\r\n if (scaledExponent < 255) {\r\n return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);\r\n } else {\r\n return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;\r\n }\r\n } else if (scaledExponent < 255) {\r\n return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);\r\n } else {\r\n return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static boolean isInCurlyBrackets(String toCheck){\r\n int count = 0;\r\n int brackets = 0;\r\n if ((toCheck == null) || toCheck.isEmpty()) {\r\n return false;\r\n } else {\r\n if ((toCheck.charAt(0) == '{') && (toCheck.charAt(toCheck.length() - 1) == '}')) {\r\n for (char c : toCheck.toCharArray()) {\r\n if (c == '{') {\r\n if (brackets == 0) {\r\n count++;\r\n }\r\n brackets++;\r\n } else if (c == '}') {\r\n brackets--;\r\n }\r\n }\r\n return count == 1;\r\n }\r\n return false;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void filterObjectNames(final Set objectNames, final String[] includes, final String includePattern, final String[] excludes, final String excludePattern, final Logger log) throws Exception{\r\n log.info(\"Looking for matching Object names...\");\r\n final Set includedNames = new HashSet<>();\r\n if (includes != null && includes.length > 0) {\r\n for (String name : includes) {\r\n name = name.trim();\r\n if (name.isEmpty()) {\r\n throw new RuntimeException(\"Invalid empty name in includes\");\r\n }\r\n includedNames.add(name);\r\n }\r\n }\r\n final Set excludedNames = new HashSet<>();\r\n if (excludes != null && excludes.length > 0) {\r\n for (String name : excludes) {\r\n name = name.trim();\r\n if (name.isEmpty()) {\r\n throw new RuntimeException(\"Invalid empty name in excludes\");\r\n }\r\n excludedNames.add(name);\r\n }\r\n }\r\n Pattern incPattern;\r\n if (includePattern != null && !includePattern.trim().isEmpty()) {\r\n incPattern = Pattern.compile(includePattern.trim());\r\n } else if (includedNames.isEmpty()) {\r\n incPattern = Defaults.MATCH_EVERYTHING_PATTERN;\r\n } else {\r\n incPattern = Defaults.MATCH_NOTHING_PATTERN;\r\n }\r\n Pattern excPattern;\r\n if (excludePattern != null && !excludePattern.trim().isEmpty()) {\r\n excPattern = Pattern.compile(excludePattern.trim());\r\n } else {\r\n excPattern = Defaults.MATCH_NOTHING_PATTERN;\r\n }\r\n final Set acceptedNames = new HashSet<>();\r\n for (final String name : objectNames) {\r\n if ((includedNames.contains(name) || incPattern.matcher(name).matches()) && !excludedNames.contains(name) && !excPattern.matcher(name).matches()) {\r\n acceptedNames.add(name);\r\n }\r\n }\r\n objectNames.clear();\r\n objectNames.addAll(acceptedNames);\r\n log.info(String.format(\"Found %s matching Objects\", objectNames.size()));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean connect(Properties props) throws IOException{\r\n String url = getProperty(props, new String[] { JdbcConnectionParams.PROPERTY_URL, \"javax.jdo.option.ConnectionURL\", \"ConnectionURL\" });\r\n String driver = getProperty(props, new String[] { JdbcConnectionParams.PROPERTY_DRIVER, \"javax.jdo.option.ConnectionDriverName\", \"ConnectionDriverName\" });\r\n String username = getProperty(props, new String[] { JdbcConnectionParams.AUTH_USER, \"javax.jdo.option.ConnectionUserName\", \"ConnectionUserName\" });\r\n String password = getProperty(props, new String[] { JdbcConnectionParams.AUTH_PASSWD, \"javax.jdo.option.ConnectionPassword\", \"ConnectionPassword\" });\r\n if (url == null || url.length() == 0) {\r\n return beeLine.error(\"Property \\\"url\\\" is required\");\r\n }\r\n if (driver == null || driver.length() == 0) {\r\n if (!beeLine.scanForDriver(url)) {\r\n return beeLine.error(beeLine.loc(\"no-driver\", url));\r\n }\r\n }\r\n String auth = getProperty(props, new String[] { JdbcConnectionParams.AUTH_TYPE });\r\n if (auth == null) {\r\n auth = beeLine.getOpts().getAuthType();\r\n if (auth != null) {\r\n props.setProperty(JdbcConnectionParams.AUTH_TYPE, auth);\r\n }\r\n }\r\n beeLine.info(\"Connecting to \" + url);\r\n if (Utils.parsePropertyFromUrl(url, JdbcConnectionParams.AUTH_PRINCIPAL) == null && !JdbcConnectionParams.AUTH_SSO_BROWSER_MODE.equals(auth)) {\r\n String urlForPrompt = url.substring(0, url.contains(\";\") ? url.indexOf(';') : url.length());\r\n if (username == null) {\r\n username = beeLine.getConsoleReader().readLine(\"Enter username for \" + urlForPrompt + \": \");\r\n }\r\n props.setProperty(JdbcConnectionParams.AUTH_USER, username);\r\n if (password == null) {\r\n password = beeLine.getConsoleReader().readLine(\"Enter password for \" + urlForPrompt + \": \", new Character('*'));\r\n }\r\n props.setProperty(JdbcConnectionParams.AUTH_PASSWD, password);\r\n }\r\n try {\r\n beeLine.getDatabaseConnections().setConnection(new DatabaseConnection(beeLine, driver, url, props));\r\n beeLine.getDatabaseConnection().getConnection();\r\n if (!beeLine.isBeeLine()) {\r\n beeLine.updateOptsForCli();\r\n }\r\n int initScriptExecutionResult = beeLine.runInit();\r\n if (initScriptExecutionResult != 0 && !beeLine.getOpts().getForce()) {\r\n return beeLine.error(\"init script execution failed.\");\r\n }\r\n beeLine.setCompletions();\r\n beeLine.getOpts().setLastConnectedUrl(url);\r\n return true;\r\n } catch (SQLException sqle) {\r\n beeLine.getDatabaseConnections().remove();\r\n return beeLine.error(sqle);\r\n } catch (IOException ioe) {\r\n return beeLine.error(ioe);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void updateTagsAndAttributes(Map tagsMap, Map attributesMap, IMeasurementMNode leafMNode) throws MetadataException, IOException{\r\n Pair, Map> pair = tagLogFile.read(COMMON_CONFIG.getTagAttributeTotalSize(), leafMNode.getOffset());\r\n if (tagsMap != null) {\r\n for (Map.Entry entry : tagsMap.entrySet()) {\r\n String key = entry.getKey();\r\n String value = entry.getValue();\r\n String beforeValue = pair.left.get(key);\r\n pair.left.put(key, value);\r\n if (beforeValue != null && !beforeValue.equals(value)) {\r\n if (tagIndex.containsKey(key) && tagIndex.get(key).containsKey(beforeValue)) {\r\n if (logger.isDebugEnabled()) {\r\n logger.debug(String.format(String.format(DEBUG_MSG, \"Upsert\" + TAG_FORMAT, leafMNode.getFullPath()), key, beforeValue, leafMNode.getOffset()));\r\n }\r\n removeIndex(key, beforeValue, leafMNode);\r\n } else {\r\n if (logger.isDebugEnabled()) {\r\n logger.debug(String.format(String.format(DEBUG_MSG_1, \"Upsert\" + PREVIOUS_CONDITION, leafMNode.getFullPath()), key, beforeValue, leafMNode.getOffset(), tagIndex.containsKey(key)));\r\n }\r\n }\r\n }\r\n if (beforeValue == null || !beforeValue.equals(value)) {\r\n addIndex(key, value, leafMNode);\r\n }\r\n }\r\n }\r\n if (attributesMap != null) {\r\n pair.right.putAll(attributesMap);\r\n }\r\n tagLogFile.write(pair.left, pair.right, leafMNode.getOffset());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private int sendMTFValues1(final int nGroups, final int alphaSize){\r\n final Data dataShadow = this.data;\r\n final int[][] rfreq = dataShadow.sendMTFValues_rfreq;\r\n final int[] fave = dataShadow.sendMTFValues_fave;\r\n final short[] cost = dataShadow.sendMTFValues_cost;\r\n final char[] sfmap = dataShadow.sfmap;\r\n final byte[] selector = dataShadow.selector;\r\n final byte[][] len = dataShadow.sendMTFValues_len;\r\n final byte[] len_0 = len[0];\r\n final byte[] len_1 = len[1];\r\n final byte[] len_2 = len[2];\r\n final byte[] len_3 = len[3];\r\n final byte[] len_4 = len[4];\r\n final byte[] len_5 = len[5];\r\n final int nMTFShadow = this.nMTF;\r\n int nSelectors = 0;\r\n for (int iter = 0; iter < N_ITERS; iter++) {\r\n for (int t = nGroups; --t >= 0; ) {\r\n fave[t] = 0;\r\n final int[] rfreqt = rfreq[t];\r\n for (int i = alphaSize; --i >= 0; ) {\r\n rfreqt[i] = 0;\r\n }\r\n }\r\n nSelectors = 0;\r\n for (int gs = 0; gs < this.nMTF; ) {\r\n final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1);\r\n final byte mask = (byte) 0xff;\r\n if (nGroups == N_GROUPS) {\r\n short cost0 = 0;\r\n short cost1 = 0;\r\n short cost2 = 0;\r\n short cost3 = 0;\r\n short cost4 = 0;\r\n short cost5 = 0;\r\n for (int i = gs; i <= ge; i++) {\r\n final int icv = sfmap[i];\r\n cost0 += (short) (len_0[icv] & mask);\r\n cost1 += (short) (len_1[icv] & mask);\r\n cost2 += (short) (len_2[icv] & mask);\r\n cost3 += (short) (len_3[icv] & mask);\r\n cost4 += (short) (len_4[icv] & mask);\r\n cost5 += (short) (len_5[icv] & mask);\r\n }\r\n cost[0] = cost0;\r\n cost[1] = cost1;\r\n cost[2] = cost2;\r\n cost[3] = cost3;\r\n cost[4] = cost4;\r\n cost[5] = cost5;\r\n } else {\r\n for (int t = nGroups; --t >= 0; ) {\r\n cost[t] = 0;\r\n }\r\n for (int i = gs; i <= ge; i++) {\r\n final int icv = sfmap[i];\r\n for (int t = nGroups; --t >= 0; ) {\r\n cost[t] += (short) (len[t][icv] & mask);\r\n }\r\n }\r\n }\r\n int bt = -1;\r\n for (int t = nGroups, bc = 999999999; --t >= 0; ) {\r\n final int cost_t = cost[t];\r\n if (cost_t < bc) {\r\n bc = cost_t;\r\n bt = t;\r\n }\r\n }\r\n fave[bt]++;\r\n selector[nSelectors] = (byte) bt;\r\n nSelectors++;\r\n final int[] rfreq_bt = rfreq[bt];\r\n for (int i = gs; i <= ge; i++) {\r\n rfreq_bt[sfmap[i]]++;\r\n }\r\n gs = ge + 1;\r\n }\r\n for (int t = 0; t < nGroups; t++) {\r\n hbMakeCodeLengths(len[t], rfreq[t], this.data, alphaSize, 20);\r\n }\r\n }\r\n return nSelectors;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void checkEx(@Nullable Throwable ex, @Nullable String expectedMsgPattern, StringAndPos sap, Stage stage){\r\n if (null == ex) {\r\n if (expectedMsgPattern == null) {\r\n return;\r\n } else {\r\n throw new AssertionError(\"Expected query to throw exception, \" + \"but it did not; query [\" + sap.sql + \"]; expected [\" + expectedMsgPattern + \"]\");\r\n }\r\n }\r\n Throwable actualException = ex;\r\n String actualMessage = actualException.getMessage();\r\n int actualLine = -1;\r\n int actualColumn = -1;\r\n int actualEndLine = 100;\r\n int actualEndColumn = 99;\r\n CalciteContextException ece = null;\r\n for (Throwable x = ex; x != null; x = x.getCause()) {\r\n if (x instanceof CalciteContextException) {\r\n ece = (CalciteContextException) x;\r\n break;\r\n }\r\n if (x.getCause() == x) {\r\n break;\r\n }\r\n }\r\n SqlParseException spe = null;\r\n for (Throwable x = ex; x != null; x = x.getCause()) {\r\n if ((x instanceof SqlParseException) && (((SqlParseException) x).getPos() != null)) {\r\n spe = (SqlParseException) x;\r\n break;\r\n }\r\n if (x.getCause() == x) {\r\n break;\r\n }\r\n }\r\n if (ece != null) {\r\n actualLine = ece.getPosLine();\r\n actualColumn = ece.getPosColumn();\r\n actualEndLine = ece.getEndPosLine();\r\n actualEndColumn = ece.getEndPosColumn();\r\n if (ece.getCause() != null) {\r\n actualException = ece.getCause();\r\n actualMessage = actualException.getMessage();\r\n }\r\n } else if (spe != null) {\r\n actualLine = spe.getPos().getLineNum();\r\n actualColumn = spe.getPos().getColumnNum();\r\n actualEndLine = spe.getPos().getEndLineNum();\r\n actualEndColumn = spe.getPos().getEndColumnNum();\r\n if (spe.getCause() != null) {\r\n actualException = spe.getCause();\r\n actualMessage = actualException.getMessage();\r\n }\r\n } else {\r\n final String message = ex.getMessage();\r\n if (message != null) {\r\n java.util.regex.Matcher matcher = LINE_COL_TWICE_PATTERN.matcher(message);\r\n if (matcher.matches()) {\r\n actualLine = Integer.parseInt(matcher.group(1));\r\n actualColumn = Integer.parseInt(matcher.group(2));\r\n actualEndLine = Integer.parseInt(matcher.group(3));\r\n actualEndColumn = Integer.parseInt(matcher.group(4));\r\n actualMessage = matcher.group(5);\r\n } else {\r\n matcher = LINE_COL_PATTERN.matcher(message);\r\n if (matcher.matches()) {\r\n actualLine = Integer.parseInt(matcher.group(1));\r\n actualColumn = Integer.parseInt(matcher.group(2));\r\n } else {\r\n if (expectedMsgPattern != null && actualMessage.matches(expectedMsgPattern)) {\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (null == expectedMsgPattern) {\r\n actualException.printStackTrace();\r\n fail(stage.componentName + \" threw unexpected exception\" + \"; query [\" + sap.sql + \"]; exception [\" + actualMessage + \"]; class [\" + actualException.getClass() + \"]; pos [line \" + actualLine + \" col \" + actualColumn + \" thru line \" + actualLine + \" col \" + actualColumn + \"]\");\r\n }\r\n final String sqlWithCarets;\r\n if (actualColumn <= 0 || actualLine <= 0 || actualEndColumn <= 0 || actualEndLine <= 0) {\r\n if (sap.pos != null) {\r\n throw new AssertionError(\"Expected error to have position,\" + \" but actual error did not: \" + \" actual pos [line \" + actualLine + \" col \" + actualColumn + \" thru line \" + actualEndLine + \" col \" + actualEndColumn + \"]\", actualException);\r\n }\r\n sqlWithCarets = sap.sql;\r\n } else {\r\n sqlWithCarets = SqlParserUtil.addCarets(sap.sql, actualLine, actualColumn, actualEndLine, actualEndColumn + 1);\r\n if (sap.pos == null) {\r\n throw new AssertionError(\"Actual error had a position, but expected \" + \"error did not. Add error position carets to sql:\\n\" + sqlWithCarets);\r\n }\r\n }\r\n if (actualMessage != null) {\r\n actualMessage = Util.toLinux(actualMessage);\r\n }\r\n if (actualMessage == null || !actualMessage.matches(expectedMsgPattern)) {\r\n actualException.printStackTrace();\r\n final String actualJavaRegexp = (actualMessage == null) ? \"null\" : TestUtil.quoteForJava(TestUtil.quotePattern(actualMessage));\r\n fail(stage.componentName + \" threw different \" + \"exception than expected; query [\" + sap.sql + \"];\\n\" + \" expected pattern [\" + expectedMsgPattern + \"];\\n\" + \" actual [\" + actualMessage + \"];\\n\" + \" actual as java regexp [\" + actualJavaRegexp + \"]; pos [\" + actualLine + \" col \" + actualColumn + \" thru line \" + actualEndLine + \" col \" + actualEndColumn + \"]; sql [\" + sqlWithCarets + \"]\");\r\n } else if (sap.pos != null && (actualLine != sap.pos.getLineNum() || actualColumn != sap.pos.getColumnNum() || actualEndLine != sap.pos.getEndLineNum() || actualEndColumn != sap.pos.getEndColumnNum())) {\r\n fail(stage.componentName + \" threw expected \" + \"exception [\" + actualMessage + \"];\\nbut at pos [line \" + actualLine + \" col \" + actualColumn + \" thru line \" + actualEndLine + \" col \" + actualEndColumn + \"];\\nsql [\" + sqlWithCarets + \"]\");\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void appendSingleMeasurement(PartialPath path, IMeasurementSchema schema, Map tagMap, String alias, boolean isAligned){\r\n String[] nodes = path.getNodes();\r\n SchemaNode cur = root;\r\n SchemaNode child;\r\n for (int i = 1; i < nodes.length; i++) {\r\n child = cur.getChild(nodes[i]);\r\n if (child == null) {\r\n if (i == nodes.length - 1) {\r\n SchemaMeasurementNode measurementNode = new SchemaMeasurementNode(nodes[i], schema);\r\n if (alias != null) {\r\n measurementNode.setAlias(alias);\r\n cur.getAsEntityNode().addAliasChild(alias, measurementNode);\r\n }\r\n measurementNode.setTagMap(tagMap);\r\n child = measurementNode;\r\n if (schema.isLogicalView()) {\r\n this.hasLogicalMeasurementPath = true;\r\n }\r\n } else if (i == nodes.length - 2) {\r\n SchemaEntityNode entityNode = new SchemaEntityNode(nodes[i]);\r\n entityNode.setAligned(isAligned);\r\n child = entityNode;\r\n } else {\r\n child = new SchemaInternalNode(nodes[i]);\r\n }\r\n cur.addChild(nodes[i], child);\r\n } else if (i == nodes.length - 2 && !child.isEntity()) {\r\n SchemaEntityNode entityNode = new SchemaEntityNode(nodes[i]);\r\n cur.replaceChild(nodes[i], entityNode);\r\n if (!entityNode.isAligned()) {\r\n entityNode.setAligned(isAligned);\r\n }\r\n child = entityNode;\r\n }\r\n cur = child;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static EntryLogMetadata read(LogReader reader) throws IOException{\r\n ByteBuf header = reader.readBufferAt(0, Header.LOGFILE_LEGACY_HEADER_SIZE);\r\n try {\r\n int headerVersion = Header.extractVersion(header);\r\n if (headerVersion < Header.HEADER_V1) {\r\n throw new IOException(exMsg(\"Old log file header\").kv(\"headerVersion\", headerVersion).toString());\r\n }\r\n long ledgerMapOffset = Header.extractLedgerMapOffset(header);\r\n if (ledgerMapOffset > Integer.MAX_VALUE) {\r\n throw new IOException(exMsg(\"ledgerMapOffset too high\").kv(\"ledgerMapOffset\", ledgerMapOffset).kv(\"maxOffset\", Integer.MAX_VALUE).toString());\r\n }\r\n if (ledgerMapOffset <= 0) {\r\n throw new IOException(exMsg(\"ledgerMap never written\").kv(\"ledgerMapOffset\", ledgerMapOffset).toString());\r\n }\r\n long offset = ledgerMapOffset;\r\n EntryLogMetadata meta = new EntryLogMetadata(reader.logId());\r\n while (offset < reader.maxOffset()) {\r\n int mapSize = reader.readIntAt((int) offset);\r\n if (mapSize >= LogMetadata.LEDGERS_MAP_MAX_MAP_SIZE) {\r\n throw new IOException(exMsg(\"ledgerMap too large\").kv(\"maxSize\", LogMetadata.LEDGERS_MAP_MAX_MAP_SIZE).kv(\"mapSize\", mapSize).toString());\r\n } else if (mapSize <= 0) {\r\n break;\r\n }\r\n offset += Integer.BYTES;\r\n ByteBuf ledgerMapBuffer = reader.readBufferAt(offset, mapSize);\r\n try {\r\n offset += mapSize;\r\n long ledgerId = ledgerMapBuffer.readLong();\r\n if (ledgerId != LogMetadata.INVALID_LID) {\r\n throw new IOException(exMsg(\"Bad ledgerID\").kv(\"ledgerId\", ledgerId).toString());\r\n }\r\n long entryId = ledgerMapBuffer.readLong();\r\n if (entryId != LogMetadata.LEDGERS_MAP_ENTRY_ID) {\r\n throw new IOException(exMsg(\"Unexpected entry ID. Expected special value\").kv(\"entryIdRead\", entryId).kv(\"entryIdExpected\", LogMetadata.LEDGERS_MAP_ENTRY_ID).toString());\r\n }\r\n int countInBatch = ledgerMapBuffer.readInt();\r\n for (int i = 0; i < countInBatch; i++) {\r\n ledgerId = ledgerMapBuffer.readLong();\r\n long size = ledgerMapBuffer.readLong();\r\n meta.addLedgerSize(ledgerId, size);\r\n }\r\n if (ledgerMapBuffer.isReadable()) {\r\n throw new IOException(exMsg(\"ledgerMapSize didn't match content\").kv(\"expectedCount\", countInBatch).kv(\"bufferSize\", mapSize).kv(\"bytesRemaining\", ledgerMapBuffer.readableBytes()).toString());\r\n }\r\n } finally {\r\n ReferenceCountUtil.safeRelease(ledgerMapBuffer);\r\n }\r\n }\r\n return meta;\r\n } catch (IOException ioe) {\r\n throw new IOException(exMsg(\"Error reading index\").kv(\"logId\", reader.logId()).kv(\"reason\", ioe.getMessage()).toString(), ioe);\r\n } finally {\r\n ReferenceCountUtil.safeRelease(header);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Object don(TraitType trait, Object defaultValue, TypeWrapper wrapper, boolean logical, WorkingMemory wm){\r\n disableExplicitSet();\r\n Class klass = wrapper.getKlass();\r\n if (defaultValue != null) {\r\n if (defaultValuesByTraits == null) {\r\n defaultValuesByTraits = new DefaultValueHierarchy();\r\n }\r\n defaultValuesByTraits.addMember(defaultValue, trait._getTypeCode());\r\n if (defaultValuesByTraits.getBottomCode() == null) {\r\n defaultValuesByTraits.setBottomCode((BitSet) trait._getTypeCode().clone());\r\n } else {\r\n defaultValuesByTraits.getBottomCode().or(trait._getTypeCode());\r\n }\r\n }\r\n try {\r\n rangeTypes.offer(wrapper);\r\n if (value != null) {\r\n if (klass.isInstance(value)) {\r\n } else if (value instanceof TraitableBean) {\r\n return donTraitable((TraitableBean) value, klass, logical, wm);\r\n } else if (value instanceof TraitProxyImpl) {\r\n TraitableBean core = ((TraitProxyImpl) value).getObject();\r\n return donTraitable(core, klass, logical, wm);\r\n } else {\r\n boolean isFullyTraitable = inspectForTraitability(value, wm);\r\n if (isFullyTraitable) {\r\n TraitProxyImpl proxy = (TraitProxyImpl) don(value, klass, logical, wm);\r\n value = proxy.getObject();\r\n return proxy;\r\n } else {\r\n manageInconsistentValue(klass);\r\n }\r\n }\r\n }\r\n } catch (IllegalStateException ise) {\r\n throw new UnsupportedOperationException(\"Unable to apply field traiting, incompatible type.\", ise);\r\n }\r\n if (!isExplicitlySet) {\r\n return getDefault();\r\n }\r\n return this.value;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ClientHook getHook(BeeLine beeLine, String cmdLine){\r\n if (!beeLine.isBeeLine()) {\r\n if (cmdLine.toLowerCase().startsWith(\"set\")) {\r\n if (cmdLine.contains(\"=\")) {\r\n return new SetCommandHook(cmdLine);\r\n } else {\r\n return null;\r\n }\r\n } else if (cmdLine.toLowerCase().startsWith(\"use\")) {\r\n return new UseCommandHook(cmdLine);\r\n } else {\r\n return null;\r\n }\r\n } else {\r\n if (beeLine.getOpts().getShowDbInPrompt()) {\r\n if (cmdLine.toLowerCase().startsWith(\"use\")) {\r\n return new UseCommandHook(cmdLine);\r\n } else if (cmdLine.toLowerCase().startsWith(\"connect\")) {\r\n return new ConnectCommandHook(cmdLine);\r\n } else if (cmdLine.toLowerCase().startsWith(\"go\")) {\r\n return new GoCommandHook(cmdLine);\r\n } else {\r\n return null;\r\n }\r\n } else {\r\n return null;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void doRightInserts(AccumulateNode accNode, AccumulateMemory am, ReteEvaluator reteEvaluator, TupleSets srcRightTuples, TupleSets trgLeftTuples){\r\n Accumulate accumulate = accNode.getAccumulate();\r\n BetaMemory bm = am.getBetaMemory();\r\n TupleMemory ltm = bm.getLeftTupleMemory();\r\n TupleMemory rtm = bm.getRightTupleMemory();\r\n ContextEntry[] contextEntry = bm.getContext();\r\n BetaConstraints constraints = accNode.getRawConstraints();\r\n if (srcRightTuples.getInsertSize() > 32 && rtm instanceof AbstractHashTable) {\r\n ((AbstractHashTable) rtm).ensureCapacity(srcRightTuples.getInsertSize());\r\n }\r\n boolean tupleMemoryEnabled = accNode.isLeftTupleMemoryEnabled();\r\n for (RightTuple rightTuple = srcRightTuples.getInsertFirst(); rightTuple != null; ) {\r\n RightTuple next = rightTuple.getStagedNext();\r\n boolean useTupleMemory = tupleMemoryEnabled || RuleNetworkEvaluator.useLeftMemory(accNode, rightTuple);\r\n if (useTupleMemory || !accNode.isRightInputIsRiaNode()) {\r\n rtm.add(rightTuple);\r\n }\r\n if (accNode.isRightInputIsRiaNode() || (ltm != null && ltm.size() > 0)) {\r\n constraints.updateFromFactHandle(contextEntry, reteEvaluator, rightTuple.getFactHandleForEvaluation());\r\n FastIterator leftIt = accNode.getLeftIterator(ltm);\r\n for (LeftTuple leftTuple = accNode.getFirstLeftTuple(rightTuple, ltm, leftIt); leftTuple != null; leftTuple = (LeftTuple) leftIt.next(leftTuple)) {\r\n if (constraints.isAllowedCachedRight(contextEntry, leftTuple)) {\r\n final BaseAccumulation accctx = (BaseAccumulation) leftTuple.getContextObject();\r\n addMatch(accNode, accumulate, leftTuple, rightTuple, null, null, reteEvaluator, am, accctx, true, false);\r\n if (leftTuple.getStagedType() == LeftTuple.NONE) {\r\n trgLeftTuples.addUpdate(leftTuple);\r\n }\r\n }\r\n }\r\n }\r\n rightTuple.clearStaged();\r\n rightTuple = next;\r\n }\r\n constraints.resetFactHandle(contextEntry);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void check(final LedgerDirsManager ldm){\r\n final ConcurrentMap diskUsages = ldm.getDiskUsages();\r\n boolean someDiskFulled = false;\r\n boolean highPriorityWritesAllowed = true;\r\n boolean someDiskRecovered = false;\r\n try {\r\n List writableDirs = ldm.getWritableLedgerDirs();\r\n for (File dir : writableDirs) {\r\n try {\r\n diskUsages.put(dir, diskChecker.checkDir(dir));\r\n } catch (DiskErrorException e) {\r\n LOG.error(\"Ledger directory {} failed on disk checking : \", dir, e);\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.diskFailed(dir);\r\n }\r\n } catch (DiskWarnThresholdException e) {\r\n diskUsages.compute(dir, (d, prevUsage) -> {\r\n if (null == prevUsage || e.getUsage() != prevUsage) {\r\n LOG.warn(\"Ledger directory {} is almost full : usage {}\", dir, e.getUsage());\r\n }\r\n return e.getUsage();\r\n });\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.diskAlmostFull(dir);\r\n }\r\n } catch (DiskOutOfSpaceException e) {\r\n diskUsages.compute(dir, (d, prevUsage) -> {\r\n if (null == prevUsage || e.getUsage() != prevUsage) {\r\n LOG.error(\"Ledger directory {} is out-of-space : usage {}\", dir, e.getUsage());\r\n }\r\n return e.getUsage();\r\n });\r\n ldm.addToFilledDirs(dir);\r\n someDiskFulled = true;\r\n }\r\n }\r\n ldm.getWritableLedgerDirs();\r\n } catch (NoWritableLedgerDirException e) {\r\n LOG.warn(\"LedgerDirsMonitor check process: All ledger directories are non writable\");\r\n try {\r\n ldm.getDirsAboveUsableThresholdSize(minUsableSizeForHighPriorityWrites, false);\r\n } catch (NoWritableLedgerDirException e1) {\r\n highPriorityWritesAllowed = false;\r\n }\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.allDisksFull(highPriorityWritesAllowed);\r\n }\r\n }\r\n List fullfilledDirs = new ArrayList(ldm.getFullFilledLedgerDirs());\r\n boolean makeWritable = ldm.hasWritableLedgerDirs();\r\n try {\r\n if (!makeWritable) {\r\n float totalDiskUsage = diskChecker.getTotalDiskUsage(ldm.getAllLedgerDirs());\r\n if (totalDiskUsage < conf.getDiskLowWaterMarkUsageThreshold()) {\r\n makeWritable = true;\r\n } else if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Current TotalDiskUsage: {} is greater than LWMThreshold: {}.\" + \" So not adding any filledDir to WritableDirsList\", totalDiskUsage, conf.getDiskLowWaterMarkUsageThreshold());\r\n }\r\n }\r\n for (File dir : fullfilledDirs) {\r\n try {\r\n diskUsages.put(dir, diskChecker.checkDir(dir));\r\n if (makeWritable) {\r\n ldm.addToWritableDirs(dir, true);\r\n }\r\n someDiskRecovered = true;\r\n } catch (DiskErrorException e) {\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.diskFailed(dir);\r\n }\r\n } catch (DiskWarnThresholdException e) {\r\n diskUsages.put(dir, e.getUsage());\r\n if (makeWritable) {\r\n ldm.addToWritableDirs(dir, false);\r\n }\r\n someDiskRecovered = true;\r\n } catch (DiskOutOfSpaceException e) {\r\n diskUsages.put(dir, e.getUsage());\r\n }\r\n }\r\n } catch (IOException ioe) {\r\n LOG.error(\"Got IOException while monitoring Dirs\", ioe);\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.fatalError();\r\n }\r\n }\r\n if (conf.isReadOnlyModeOnAnyDiskFullEnabled()) {\r\n if (someDiskFulled && !ldm.getFullFilledLedgerDirs().isEmpty()) {\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.anyDiskFull(highPriorityWritesAllowed);\r\n }\r\n }\r\n if (someDiskRecovered && ldm.getFullFilledLedgerDirs().isEmpty()) {\r\n for (LedgerDirsListener listener : ldm.getListeners()) {\r\n listener.allDisksWritable();\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected boolean processInOut(final Exchange exchange, final AsyncCallback callback){\r\n final org.apache.camel.Message in = exchange.getIn();\r\n String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class);\r\n in.removeHeader(JmsConstants.JMS_DESTINATION_NAME);\r\n if (destinationName == null) {\r\n destinationName = endpoint.getDestinationName();\r\n }\r\n Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class);\r\n in.removeHeader(JmsConstants.JMS_DESTINATION);\r\n if (destination != null) {\r\n destinationName = null;\r\n }\r\n initReplyManager();\r\n final long timeout = exchange.getIn().getHeader(JmsConstants.JMS_REQUEST_TIMEOUT, endpoint.getRequestTimeout(), long.class);\r\n final JmsConfiguration configuration = endpoint.getConfiguration();\r\n final boolean msgIdAsCorrId = configuration.isUseMessageIDAsCorrelationID();\r\n final String provisionalCorrelationId = msgIdAsCorrId ? getUuidGenerator().generateUuid() : null;\r\n MessageSentCallback messageSentCallback = null;\r\n if (msgIdAsCorrId) {\r\n messageSentCallback = new UseMessageIdAsCorrelationIdMessageSentCallback(replyManager, provisionalCorrelationId, timeout);\r\n }\r\n final String correlationProperty = configuration.getCorrelationProperty();\r\n final String correlationPropertyToUse = ofNullable(correlationProperty).orElse(JmsConstants.JMS_HEADER_CORRELATION_ID);\r\n final String originalCorrelationId = in.getHeader(correlationPropertyToUse, String.class);\r\n boolean generateFreshCorrId = ObjectHelper.isEmpty(originalCorrelationId) && !msgIdAsCorrId || originalCorrelationId != null && originalCorrelationId.startsWith(GENERATED_CORRELATION_ID_PREFIX);\r\n if (generateFreshCorrId) {\r\n in.setHeader(correlationPropertyToUse, GENERATED_CORRELATION_ID_PREFIX + getUuidGenerator().generateUuid());\r\n }\r\n MessageCreator messageCreator = new MessageCreator() {\r\n\r\n public Message createMessage(Session session) throws JMSException {\r\n Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null);\r\n Destination replyTo = null;\r\n String replyToOverride = configuration.getReplyToOverride();\r\n if (replyToOverride != null) {\r\n replyTo = resolveOrCreateDestination(replyToOverride, session);\r\n } else {\r\n replyTo = replyManager.getReplyTo();\r\n }\r\n if (replyTo == null) {\r\n throw new RuntimeExchangeException(\"Failed to resolve replyTo destination\", exchange);\r\n }\r\n JmsMessageHelper.setJMSReplyTo(answer, replyTo);\r\n replyManager.setReplyToSelectorHeader(in, answer);\r\n String correlationId = determineCorrelationId(answer, provisionalCorrelationId);\r\n replyManager.registerReply(replyManager, exchange, callback, originalCorrelationId, correlationId, timeout);\r\n if (correlationProperty != null) {\r\n replyManager.setCorrelationProperty(correlationProperty);\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Using {}: {}, JMSReplyTo destination: {}, with request timeout: {} ms.\", correlationPropertyToUse, correlationId, replyTo, timeout);\r\n }\r\n LOG.trace(\"Created jakarta.jms.Message: {}\", answer);\r\n return answer;\r\n }\r\n };\r\n doSend(true, destinationName, destination, messageCreator, messageSentCallback);\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public it.csi.conam.conambl.integration.beans.ResponseProtocollaDocumento protocollaDocumentoLogico(it.csi.conam.conambl.integration.beans.RequestProtocollaDocumentoLogico in0) throws java.rmi.RemoteException, it.csi.conam.conambl.integration.beans.UnrecoverableException, it.csi.conam.conambl.integration.beans.CSIException, it.csi.conam.conambl.integration.beans.SystemException, it.csi.conam.conambl.integration.beans.ProtocollaDocumentoException{\r\n if (super.cachedEndpoint == null) {\r\n throw new org.apache.axis.NoEndPointException();\r\n }\r\n org.apache.axis.client.Call _call = createCall();\r\n _call.setOperation(_operations[5]);\r\n _call.setUseSOAPAction(true);\r\n _call.setSOAPActionURI(\"\");\r\n _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);\r\n _call.setOperationName(new javax.xml.namespace.QName(\"http://stadoc.interfacecsi.stadoc.stacore.csi.it\", \"protocollaDocumentoLogico\"));\r\n setRequestHeaders(_call);\r\n setAttachments(_call);\r\n try {\r\n java.lang.Object _resp = _call.invoke(new java.lang.Object[] { in0 });\r\n if (_resp instanceof java.rmi.RemoteException) {\r\n throw (java.rmi.RemoteException) _resp;\r\n } else {\r\n extractAttachments(_call);\r\n try {\r\n return (it.csi.conam.conambl.integration.beans.ResponseProtocollaDocumento) _resp;\r\n } catch (java.lang.Exception _exception) {\r\n return (it.csi.conam.conambl.integration.beans.ResponseProtocollaDocumento) org.apache.axis.utils.JavaUtils.convert(_resp, it.csi.conam.conambl.integration.beans.ResponseProtocollaDocumento.class);\r\n }\r\n }\r\n } catch (org.apache.axis.AxisFault axisFaultException) {\r\n if (axisFaultException.detail != null) {\r\n if (axisFaultException.detail instanceof java.rmi.RemoteException) {\r\n throw (java.rmi.RemoteException) axisFaultException.detail;\r\n }\r\n if (axisFaultException.detail instanceof it.csi.conam.conambl.integration.beans.UnrecoverableException) {\r\n throw (it.csi.conam.conambl.integration.beans.UnrecoverableException) axisFaultException.detail;\r\n }\r\n if (axisFaultException.detail instanceof it.csi.conam.conambl.integration.beans.CSIException) {\r\n throw (it.csi.conam.conambl.integration.beans.CSIException) axisFaultException.detail;\r\n }\r\n if (axisFaultException.detail instanceof it.csi.conam.conambl.integration.beans.SystemException) {\r\n throw (it.csi.conam.conambl.integration.beans.SystemException) axisFaultException.detail;\r\n }\r\n if (axisFaultException.detail instanceof it.csi.conam.conambl.integration.beans.ProtocollaDocumentoException) {\r\n throw (it.csi.conam.conambl.integration.beans.ProtocollaDocumentoException) axisFaultException.detail;\r\n }\r\n }\r\n throw axisFaultException;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ChouetteFacilityType produce(Facility facility, boolean addExtension){\r\n ChouetteFacilityType jaxbFacility = tridentFactory.createChouetteFacilityType();\r\n populateFromModel(jaxbFacility, facility);\r\n jaxbFacility.setComment(getNotEmptyString(facility.getComment()));\r\n jaxbFacility.setName(facility.getName());\r\n if (facility.getLongLatType() != null && facility.getLatitude() != null && facility.getLongitude() != null) {\r\n FacilityLocation jaxbLocation = tridentFactory.createChouetteFacilityTypeFacilityLocation();\r\n jaxbFacility.setFacilityLocation(jaxbLocation);\r\n jaxbLocation.setContainedIn(facility.getContainedIn());\r\n jaxbLocation.setLatitude(facility.getLatitude());\r\n jaxbLocation.setLongitude(facility.getLongitude());\r\n LongLatTypeEnum longLatType = facility.getLongLatType();\r\n try {\r\n jaxbLocation.setLongLatType(LongLatTypeType.fromValue(longLatType.name()));\r\n } catch (IllegalArgumentException e) {\r\n }\r\n if (facility.getCountryCode() != null || facility.getStreetName() != null) {\r\n AddressType jaxbAddress = tridentFactory.createAddressType();\r\n jaxbAddress.setCountryCode(getNotEmptyString(facility.getCountryCode()));\r\n jaxbAddress.setStreetName(getNotEmptyString(facility.getStreetName()));\r\n jaxbLocation.setAddress(jaxbAddress);\r\n }\r\n if (facility.getProjectionType() != null && facility.getX() != null && facility.getY() != null) {\r\n ProjectedPointType jaxbProjectedPoint = tridentFactory.createProjectedPointType();\r\n jaxbProjectedPoint.setProjectionType(facility.getProjectionType());\r\n jaxbProjectedPoint.setX(facility.getX());\r\n jaxbProjectedPoint.setY(facility.getY());\r\n jaxbLocation.setProjectedPoint(jaxbProjectedPoint);\r\n }\r\n }\r\n if (facility.getConnectionLink() != null) {\r\n jaxbFacility.setConnectionLinkId(getNonEmptyObjectId(facility.getConnectionLink()));\r\n }\r\n if (facility.getLine() != null) {\r\n jaxbFacility.setLineId(getNonEmptyObjectId(facility.getLine()));\r\n }\r\n if (facility.getStopArea() != null) {\r\n jaxbFacility.setStopAreaId(getNonEmptyObjectId(facility.getStopArea()));\r\n }\r\n if (facility.getStopPoint() != null) {\r\n jaxbFacility.setStopPointId(getNonEmptyObjectId(facility.getStopPoint()));\r\n }\r\n jaxbFacility.setDescription(getNotEmptyString(facility.getDescription()));\r\n if (facility.getFreeAccess() != null)\r\n jaxbFacility.setFreeAccess(facility.getFreeAccess().booleanValue());\r\n List features = facility.getFacilityFeatures();\r\n for (FacilityFeature feature : features) {\r\n AllFacilitiesFeatureStructure facilityFeature = siriFactory.createAllFacilitiesFeatureStructure();\r\n int type = facilityEnumMap.get(feature.getChoiceValue().getClass()).intValue();\r\n switch(type) {\r\n case 0:\r\n facilityFeature.setAccessFacility(uk.org.siri.siri.AccessFacilityEnumeration.fromValue(feature.getAccessFacility().toString()));\r\n break;\r\n case 1:\r\n facilityFeature.setAccommodationFacility(uk.org.siri.siri.AccommodationFacilityEnumeration.fromValue(feature.getAccommodationFacility().name()));\r\n break;\r\n case 2:\r\n facilityFeature.setAssistanceFacility(uk.org.siri.siri.AssistanceFacilityEnumeration.fromValue(feature.getAssistanceFacility().name()));\r\n break;\r\n case 3:\r\n facilityFeature.setFareClassFacility(uk.org.siri.siri.FareClassFacilityEnumeration.fromValue(feature.getFareClassFacility().name()));\r\n break;\r\n case 4:\r\n facilityFeature.setHireFacility(uk.org.siri.siri.HireFacilityEnumeration.fromValue(feature.getHireFacility().name()));\r\n break;\r\n case 5:\r\n facilityFeature.setLuggageFacility(uk.org.siri.siri.LuggageFacilityEnumeration.fromValue(feature.getLuggageFacility().name()));\r\n break;\r\n case 6:\r\n facilityFeature.setMobilityFacility(uk.org.siri.siri.MobilityFacilityEnumeration.fromValue(feature.getMobilityFacility().name()));\r\n break;\r\n case 7:\r\n facilityFeature.setNuisanceFacility(uk.org.siri.siri.NuisanceFacilityEnumeration.fromValue(feature.getNuisanceFacility().name()));\r\n break;\r\n case 8:\r\n facilityFeature.setParkingFacility(uk.org.siri.siri.ParkingFacilityEnumeration.fromValue(feature.getParkingFacility().name()));\r\n break;\r\n case 9:\r\n facilityFeature.setPassengerCommsFacility(uk.org.siri.siri.PassengerCommsFacilityEnumeration.fromValue(feature.getPassengerCommsFacility().name()));\r\n break;\r\n case 10:\r\n facilityFeature.setPassengerInformationFacility(uk.org.siri.siri.PassengerInformationFacilityEnumeration.fromValue(feature.getPassengerInformationFacility().name()));\r\n break;\r\n case 11:\r\n facilityFeature.setRefreshmentFacility(uk.org.siri.siri.RefreshmentFacilityEnumeration.fromValue(feature.getRefreshmentFacility().name()));\r\n break;\r\n case 12:\r\n facilityFeature.setReservedSpaceFacility(uk.org.siri.siri.ReservedSpaceFacilityEnumeration.fromValue(feature.getReservedSpaceFacility().name()));\r\n break;\r\n case 13:\r\n facilityFeature.setRetailFacility(uk.org.siri.siri.RetailFacilityEnumeration.fromValue(feature.getRetailFacility().name()));\r\n break;\r\n case 14:\r\n facilityFeature.setSanitaryFacility(uk.org.siri.siri.SanitaryFacilityEnumeration.fromValue(feature.getSanitaryFacility().name()));\r\n break;\r\n case 15:\r\n facilityFeature.setTicketingFacility(uk.org.siri.siri.TicketingFacilityEnumeration.fromValue(feature.getTicketingFacility().name()));\r\n break;\r\n }\r\n jaxbFacility.getFacilityFeature().add(facilityFeature);\r\n }\r\n return jaxbFacility;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static String convert(String expression){\r\n char[] arr = expression.toCharArray();\r\n for (int i = 0; i < arr.length; i++) {\r\n if (arr[i] == SUBTRACT_CHAR) {\r\n if (i == 0) {\r\n arr[i] = N;\r\n } else {\r\n char c = arr[i - 1];\r\n if (c == ADD_CHAR || c == SUBTRACT_CHAR || c == MULTIPLY_CHAR || c == DIVISION_CHAR || c == LEFT_BRACE_CHAR) {\r\n arr[i] = N;\r\n }\r\n }\r\n } else if (arr[i] == ADD_CHAR) {\r\n if (i == 0) {\r\n arr[i] = P;\r\n } else {\r\n char c = arr[i - 1];\r\n if (c == ADD_CHAR || c == SUBTRACT_CHAR || c == MULTIPLY_CHAR || c == DIVISION_CHAR || c == LEFT_BRACE_CHAR) {\r\n arr[i] = P;\r\n }\r\n }\r\n }\r\n }\r\n return new String(arr);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static IndexConfig getIndexConfigFromXml(Node indexNode, boolean domLevel3, boolean strict){\r\n NamedNodeMap attrs = indexNode.getAttributes();\r\n String name = getTextContent(attrs.getNamedItem(\"name\"), domLevel3);\r\n if (name.isEmpty()) {\r\n name = null;\r\n }\r\n String typeStr = getTextContent(attrs.getNamedItem(\"type\"), domLevel3);\r\n IndexType type = getIndexTypeFromXmlName(typeStr);\r\n IndexConfig res = new IndexConfig().setName(name).setType(type);\r\n for (Node attributesNode : childElements(indexNode)) {\r\n if (\"attributes\".equals(cleanNodeName(attributesNode))) {\r\n for (Node attributeNode : childElements(attributesNode)) {\r\n if (\"attribute\".equals(cleanNodeName(attributeNode))) {\r\n String attribute = getTextContent(attributeNode, domLevel3);\r\n res.addAttribute(attribute);\r\n }\r\n }\r\n }\r\n }\r\n if (type == IndexType.BITMAP) {\r\n Node optionsNode = childElementWithName(indexNode, \"bitmap-index-options\", strict);\r\n if (optionsNode != null) {\r\n Node uniqueKeyNode = childElementWithName(optionsNode, \"unique-key\", strict);\r\n String uniqueKeyText = getTextContent(uniqueKeyNode, domLevel3);\r\n String uniqueKey = isNullOrEmpty(uniqueKeyText) ? BitmapIndexOptions.DEFAULT_UNIQUE_KEY : uniqueKeyText;\r\n Node uniqueKeyTransformationNode = childElementWithName(optionsNode, \"unique-key-transformation\", strict);\r\n String uniqueKeyTransformationText = getTextContent(uniqueKeyTransformationNode, domLevel3);\r\n UniqueKeyTransformation uniqueKeyTransformation = isNullOrEmpty(uniqueKeyTransformationText) ? BitmapIndexOptions.DEFAULT_UNIQUE_KEY_TRANSFORMATION : UniqueKeyTransformation.fromName(uniqueKeyTransformationText);\r\n res.getBitmapIndexOptions().setUniqueKey(uniqueKey);\r\n res.getBitmapIndexOptions().setUniqueKeyTransformation(uniqueKeyTransformation);\r\n }\r\n } else if (type == IndexType.SORTED) {\r\n Node optionsNode = childElementWithName(indexNode, \"btree-index\", strict);\r\n if (optionsNode != null) {\r\n Node pageSizeNode = childElementWithName(optionsNode, \"page-size\", strict);\r\n Node memoryTierNode = childElementWithName(optionsNode, \"memory-tier\", strict);\r\n Node memoryTierCapacityNode = childElementWithName(memoryTierNode, \"capacity\", strict);\r\n res.getBTreeIndexConfig().setPageSize(getCapacity(pageSizeNode, domLevel3));\r\n res.getBTreeIndexConfig().getMemoryTierConfig().setCapacity(getCapacity(memoryTierCapacityNode, domLevel3));\r\n }\r\n }\r\n return res;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic Set getExpressionLineage(Join rel, RelMetadataQuery mq, RexNode outputExpression){\r\n final RexBuilder rexBuilder = rel.getCluster().getRexBuilder();\r\n final RelNode leftInput = rel.getLeft();\r\n final RelNode rightInput = rel.getRight();\r\n final int nLeftColumns = leftInput.getRowType().getFieldList().size();\r\n final ImmutableBitSet inputFieldsUsed = extractInputRefs(outputExpression);\r\n if (rel.getJoinType().isOuterJoin()) {\r\n if (rel.getJoinType() == JoinRelType.LEFT) {\r\n ImmutableBitSet rightFields = ImmutableBitSet.range(nLeftColumns, rel.getRowType().getFieldCount());\r\n if (inputFieldsUsed.intersects(rightFields)) {\r\n return null;\r\n }\r\n } else if (rel.getJoinType() == JoinRelType.RIGHT) {\r\n ImmutableBitSet leftFields = ImmutableBitSet.range(0, nLeftColumns);\r\n if (inputFieldsUsed.intersects(leftFields)) {\r\n return null;\r\n }\r\n } else {\r\n return null;\r\n }\r\n }\r\n final Set leftTableRefs = mq.getTableReferences(leftInput);\r\n if (leftTableRefs == null) {\r\n return null;\r\n }\r\n final Set rightTableRefs = mq.getTableReferences(rightInput);\r\n if (rightTableRefs == null) {\r\n return null;\r\n }\r\n final Multimap, RelTableRef> qualifiedNamesToRefs = HashMultimap.create();\r\n final Map currentTablesMapping = new HashMap<>();\r\n for (RelTableRef leftRef : leftTableRefs) {\r\n qualifiedNamesToRefs.put(leftRef.getQualifiedName(), leftRef);\r\n }\r\n for (RelTableRef rightRef : rightTableRefs) {\r\n int shift = 0;\r\n Collection lRefs = qualifiedNamesToRefs.get(rightRef.getQualifiedName());\r\n if (lRefs != null) {\r\n shift = lRefs.size();\r\n }\r\n currentTablesMapping.put(rightRef, RelTableRef.of(rightRef.getTable(), shift + rightRef.getEntityNumber()));\r\n }\r\n final Map> mapping = new LinkedHashMap<>();\r\n for (int idx : inputFieldsUsed) {\r\n if (idx < nLeftColumns) {\r\n final RexInputRef inputRef = RexInputRef.of(idx, leftInput.getRowType().getFieldList());\r\n final Set originalExprs = mq.getExpressionLineage(leftInput, inputRef);\r\n if (originalExprs == null) {\r\n return null;\r\n }\r\n mapping.put(RexInputRef.of(idx, rel.getRowType().getFieldList()), originalExprs);\r\n } else {\r\n final RexInputRef inputRef = RexInputRef.of(idx - nLeftColumns, rightInput.getRowType().getFieldList());\r\n final Set originalExprs = mq.getExpressionLineage(rightInput, inputRef);\r\n if (originalExprs == null) {\r\n return null;\r\n }\r\n final RelDataType fullRowType = SqlValidatorUtil.createJoinType(rexBuilder.getTypeFactory(), rel.getLeft().getRowType(), rel.getRight().getRowType(), null, ImmutableList.of());\r\n final Set updatedExprs = ImmutableSet.copyOf(Util.transform(originalExprs, e -> RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping)));\r\n mapping.put(RexInputRef.of(idx, fullRowType), updatedExprs);\r\n }\r\n }\r\n return createAllPossibleExpressions(rexBuilder, outputExpression, mapping);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ClassDeclaration implementRoot(EnumerableRel rootRel, EnumerableRel.Prefer prefer){\r\n EnumerableRel.Result result;\r\n try {\r\n result = rootRel.implement(this, prefer);\r\n } catch (RuntimeException e) {\r\n IllegalStateException ex = new IllegalStateException(\"Unable to implement \" + RelOptUtil.toString(rootRel, SqlExplainLevel.ALL_ATTRIBUTES));\r\n ex.addSuppressed(e);\r\n throw ex;\r\n }\r\n switch(prefer) {\r\n case ARRAY:\r\n if (result.physType.getFormat() == JavaRowFormat.ARRAY && rootRel.getRowType().getFieldCount() == 1) {\r\n BlockBuilder bb = new BlockBuilder();\r\n Expression e = null;\r\n for (Statement statement : result.block.statements) {\r\n if (statement instanceof GotoStatement) {\r\n final GotoStatement gotoStatement = (GotoStatement) statement;\r\n e = bb.append(\"v\", requireNonNull(gotoStatement.expression, \"expression\"));\r\n } else {\r\n bb.add(statement);\r\n }\r\n }\r\n if (e != null) {\r\n bb.add(Expressions.return_(null, Expressions.call(null, BuiltInMethod.SLICE0.method, e)));\r\n }\r\n result = new EnumerableRel.Result(bb.toBlock(), result.physType, JavaRowFormat.SCALAR);\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n final List memberDeclarations = new ArrayList<>();\r\n new TypeRegistrar(memberDeclarations).go(result);\r\n final Collection stashed = Collections2.transform(stashedParameters.values(), input -> Expressions.declare(Modifier.FINAL, input, Expressions.convert_(Expressions.call(DataContext.ROOT, BuiltInMethod.DATA_CONTEXT_GET.method, Expressions.constant(input.name)), input.type)));\r\n final BlockStatement block = Expressions.block(Iterables.concat(stashed, result.block.statements));\r\n memberDeclarations.add(Expressions.methodDecl(Modifier.PUBLIC, Enumerable.class, BuiltInMethod.BINDABLE_BIND.method.getName(), Expressions.list(DataContext.ROOT), block));\r\n memberDeclarations.add(Expressions.methodDecl(Modifier.PUBLIC, Class.class, BuiltInMethod.TYPED_GET_ELEMENT_TYPE.method.getName(), ImmutableList.of(), Blocks.toFunctionBlock(Expressions.return_(null, Expressions.constant(result.physType.getJavaRowType())))));\r\n return Expressions.classDecl(Modifier.PUBLIC, \"Baz\", null, Collections.singletonList(Bindable.class), memberDeclarations);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void doClone(String operation) throws GitAPIException{\r\n Git result = null;\r\n if (ObjectHelper.isEmpty(endpoint.getLocalPath())) {\r\n throw new IllegalArgumentException(\"Local path must specified to execute \" + operation);\r\n }\r\n try {\r\n File localRepo = new File(endpoint.getLocalPath(), \"\");\r\n if (!localRepo.exists()) {\r\n if (ObjectHelper.isNotEmpty(endpoint.getUsername()) && ObjectHelper.isNotEmpty(endpoint.getPassword())) {\r\n UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(endpoint.getUsername(), endpoint.getPassword());\r\n if (ObjectHelper.isEmpty(endpoint.getBranchName())) {\r\n result = Git.cloneRepository().setCredentialsProvider(credentials).setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), \"\")).call();\r\n } else {\r\n result = Git.cloneRepository().setCredentialsProvider(credentials).setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), \"\")).setBranch(endpoint.getBranchName()).call();\r\n }\r\n } else {\r\n if (ObjectHelper.isEmpty(endpoint.getBranchName())) {\r\n result = Git.cloneRepository().setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), \"\")).call();\r\n } else {\r\n result = Git.cloneRepository().setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), \"\")).setBranch(endpoint.getBranchName()).call();\r\n }\r\n }\r\n } else {\r\n throw new IllegalArgumentException(\"The local repository directory already exists\");\r\n }\r\n } catch (GitAPIException e) {\r\n LOG.error(\"There was an error in Git {} operation\", operation);\r\n throw e;\r\n } finally {\r\n if (ObjectHelper.isNotEmpty(result)) {\r\n result.close();\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Nullable\npublic static String toDruidExpression(final RexNode rexNode, final RelDataType inputRowType, final DruidQuery druidRel){\r\n SqlKind kind = rexNode.getKind();\r\n SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName();\r\n if (kind == SqlKind.INPUT_REF) {\r\n final RexInputRef ref = (RexInputRef) rexNode;\r\n final String columnName = inputRowType.getFieldNames().get(ref.getIndex());\r\n if (columnName == null) {\r\n return null;\r\n }\r\n if (druidRel.getDruidTable().timestampFieldName.equals(columnName)) {\r\n return DruidExpressions.fromColumn(DruidTable.DEFAULT_TIMESTAMP_COLUMN);\r\n }\r\n return DruidExpressions.fromColumn(columnName);\r\n }\r\n if (rexNode instanceof RexCall) {\r\n final SqlOperator operator = ((RexCall) rexNode).getOperator();\r\n final DruidSqlOperatorConverter conversion = druidRel.getOperatorConversionMap().get(operator);\r\n if (conversion == null) {\r\n return null;\r\n } else {\r\n return conversion.toDruidExpression(rexNode, inputRowType, druidRel);\r\n }\r\n }\r\n if (kind == SqlKind.LITERAL) {\r\n if (RexLiteral.isNullLiteral(rexNode)) {\r\n return null;\r\n } else if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {\r\n return DruidExpressions.numberLiteral((Number) RexLiteral.value(rexNode));\r\n } else if (SqlTypeFamily.INTERVAL_DAY_TIME == sqlTypeName.getFamily()) {\r\n final long milliseconds = ((Number) RexLiteral.value(rexNode)).longValue();\r\n return DruidExpressions.numberLiteral(milliseconds);\r\n } else if (SqlTypeFamily.INTERVAL_YEAR_MONTH == sqlTypeName.getFamily()) {\r\n final long months = ((Number) RexLiteral.value(rexNode)).longValue();\r\n return DruidExpressions.numberLiteral(months);\r\n } else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) {\r\n return DruidExpressions.stringLiteral(RexLiteral.stringValue(rexNode));\r\n } else if (SqlTypeName.DATE == sqlTypeName || SqlTypeName.TIMESTAMP == sqlTypeName || SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE == sqlTypeName) {\r\n return DruidExpressions.numberLiteral(DruidDateTimeUtils.literalValue(rexNode));\r\n } else if (SqlTypeName.BOOLEAN == sqlTypeName) {\r\n return DruidExpressions.numberLiteral(RexLiteral.booleanValue(rexNode) ? 1 : 0);\r\n }\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static BinaryTree decode(final InputStream inputStream, final int totalNumberOfValues) throws IOException{\r\n if (totalNumberOfValues < 0) {\r\n throw new IllegalArgumentException(\"totalNumberOfValues must be bigger than 0, is \" + totalNumberOfValues);\r\n }\r\n final int size = inputStream.read() + 1;\r\n if (size == 0) {\r\n throw new IOException(\"Cannot read the size of the encoded tree, unexpected end of stream\");\r\n }\r\n final byte[] encodedTree = IOUtils.readRange(inputStream, size);\r\n if (encodedTree.length != size) {\r\n throw new EOFException();\r\n }\r\n int maxLength = 0;\r\n final int[] originalBitLengths = new int[totalNumberOfValues];\r\n int pos = 0;\r\n for (final byte b : encodedTree) {\r\n final int numberOfValues = ((b & 0xF0) >> 4) + 1;\r\n if (pos + numberOfValues > totalNumberOfValues) {\r\n throw new IOException(\"Number of values exceeds given total number of values\");\r\n }\r\n final int bitLength = (b & 0x0F) + 1;\r\n for (int j = 0; j < numberOfValues; j++) {\r\n originalBitLengths[pos++] = bitLength;\r\n }\r\n maxLength = Math.max(maxLength, bitLength);\r\n }\r\n final int oBitLengths = originalBitLengths.length;\r\n final int[] permutation = new int[oBitLengths];\r\n for (int k = 0; k < permutation.length; k++) {\r\n permutation[k] = k;\r\n }\r\n int c = 0;\r\n final int[] sortedBitLengths = new int[oBitLengths];\r\n for (int k = 0; k < oBitLengths; k++) {\r\n for (int l = 0; l < oBitLengths; l++) {\r\n if (originalBitLengths[l] == k) {\r\n sortedBitLengths[c] = k;\r\n permutation[c] = l;\r\n c++;\r\n }\r\n }\r\n }\r\n int code = 0;\r\n int codeIncrement = 0;\r\n int lastBitLength = 0;\r\n final int[] codes = new int[totalNumberOfValues];\r\n for (int i = totalNumberOfValues - 1; i >= 0; i--) {\r\n code = code + codeIncrement;\r\n if (sortedBitLengths[i] != lastBitLength) {\r\n lastBitLength = sortedBitLengths[i];\r\n codeIncrement = 1 << (16 - lastBitLength);\r\n }\r\n codes[permutation[i]] = code;\r\n }\r\n final BinaryTree tree = new BinaryTree(maxLength);\r\n for (int k = 0; k < codes.length; k++) {\r\n final int bitLength = originalBitLengths[k];\r\n if (bitLength > 0) {\r\n tree.addLeaf(0, Integer.reverse(codes[k] << 16), bitLength, k);\r\n }\r\n }\r\n return tree;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void verifyIdStructure(Context context, Set localIds, String regex, Set validCodespaces){\r\n Set validPrefixes = null;\r\n if (validCodespaces != null) {\r\n validPrefixes = new HashSet<>();\r\n for (Codespace codespace : validCodespaces) {\r\n validPrefixes.add(codespace.getXmlns());\r\n }\r\n }\r\n Pattern p = Pattern.compile(regex);\r\n ValidationReporter validationReporter = ValidationReporter.Factory.getInstance();\r\n boolean allIdStructuresValid = true;\r\n boolean allIdStructuresNameValid = true;\r\n boolean allCodespacesValid = true;\r\n for (IdVersion id : localIds) {\r\n Matcher m = p.matcher(id.getId());\r\n if (!m.matches()) {\r\n validationReporter.addCheckPointReportError(context, _1_NETEX_INVALID_ID_STRUCTURE, null, DataLocationHelper.findDataLocation(id), id.getId());\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Id \" + id + \" in line file have an invalid format. Correct format is \" + regex);\r\n }\r\n allIdStructuresValid = false;\r\n } else {\r\n if (!m.group(2).equals(id.getElementName())) {\r\n String expectedId = m.group(1) + \":\" + id.getElementName() + \":\" + m.group(3);\r\n validationReporter.addCheckPointReportError(context, _1_NETEX_INVALID_ID_STRUCTURE_NAME, null, DataLocationHelper.findDataLocation(id), id.getId(), expectedId);\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Id \" + id + \" in file have an invalid format for the name part. Expected \" + expectedId);\r\n }\r\n allIdStructuresNameValid = false;\r\n }\r\n if (validPrefixes != null) {\r\n String prefix = m.group(1);\r\n if (!validPrefixes.contains(prefix)) {\r\n validationReporter.addCheckPointReportError(context, _1_NETEX_USE_OF_UNAPPROVED_CODESPACE, null, DataLocationHelper.findDataLocation(id), id.getId());\r\n if (log.isDebugEnabled()) {\r\n log.debug(\"Id \" + id + \" in file are using an unaccepted codepsace prefix \" + prefix + \". Valid prefixes are \" + ToStringBuilder.reflectionToString(validPrefixes, ToStringStyle.SIMPLE_STYLE));\r\n }\r\n allCodespacesValid = false;\r\n }\r\n }\r\n }\r\n }\r\n if (allIdStructuresValid) {\r\n validationReporter.reportSuccess(context, _1_NETEX_INVALID_ID_STRUCTURE);\r\n }\r\n if (allIdStructuresNameValid) {\r\n validationReporter.reportSuccess(context, _1_NETEX_INVALID_ID_STRUCTURE_NAME);\r\n }\r\n if (allCodespacesValid) {\r\n validationReporter.reportSuccess(context, _1_NETEX_USE_OF_UNAPPROVED_CODESPACE);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected GetOperation newGetOperation(String path, String fields, String filter, RootJunctionEnum rootJunction, Map queryParams){\r\n GetOperation getOperation = dhis2Client.get(path);\r\n if (fields != null) {\r\n getOperation.withFields(fields);\r\n }\r\n if (filter != null) {\r\n getOperation.withFilter(filter);\r\n }\r\n if (rootJunction != null) {\r\n if (rootJunction.equals(RootJunctionEnum.AND)) {\r\n getOperation.withAndRootJunction();\r\n } else {\r\n getOperation.withOrRootJunction();\r\n }\r\n }\r\n if (queryParams != null) {\r\n for (Map.Entry queryParam : queryParams.entrySet()) {\r\n if (queryParam.getValue() instanceof List) {\r\n for (String queryValue : (List) queryParam.getValue()) {\r\n getOperation.withParameter(queryParam.getKey(), queryValue);\r\n }\r\n } else {\r\n getOperation.withParameter(queryParam.getKey(), (String) queryParam.getValue());\r\n }\r\n }\r\n }\r\n return getOperation;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected String getConsequenceCode(int first){\r\n while (input.LA(1) != DRL6Lexer.EOF) {\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.END)) {\r\n int next = input.LA(2) == DRL6Lexer.SEMICOLON ? 3 : 2;\r\n if (input.LA(next) == DRL6Lexer.EOF || input.LA(next) == DRL6Lexer.AT || helper.validateStatement(next)) {\r\n break;\r\n }\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.THEN)) {\r\n if (isNextTokenThenCompatible(input.LA(2))) {\r\n break;\r\n }\r\n }\r\n helper.emit(input.LT(1), DroolsEditorType.CODE_CHUNK);\r\n input.consume();\r\n }\r\n int last = input.LT(1).getTokenIndex();\r\n if (last <= first) {\r\n return \"\";\r\n }\r\n String chunk = input.toString(first, last);\r\n if (chunk.endsWith(DroolsSoftKeywords.END)) {\r\n chunk = chunk.substring(0, chunk.length() - DroolsSoftKeywords.END.length());\r\n } else if (chunk.endsWith(DroolsSoftKeywords.THEN)) {\r\n chunk = chunk.substring(0, chunk.length() - DroolsSoftKeywords.THEN.length());\r\n }\r\n return chunk;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected String createReport(final Collection provResults, final ExternalResource resource, final boolean dryRun){\r\n TraceLevel traceLevel = resource.getProvisioningTraceLevel();\r\n if (traceLevel == TraceLevel.NONE) {\r\n return null;\r\n }\r\n StringBuilder report = new StringBuilder();\r\n if (dryRun) {\r\n report.append(\"==> Dry run only, no modifications were made <==\\n\\n\");\r\n }\r\n if (interrupted) {\r\n report.append(\"==> Execution was interrupted <==\\n\\n\");\r\n }\r\n List rSuccCreate = new ArrayList<>();\r\n List rFailCreate = new ArrayList<>();\r\n List rSuccUpdate = new ArrayList<>();\r\n List rFailUpdate = new ArrayList<>();\r\n List rSuccDelete = new ArrayList<>();\r\n List rFailDelete = new ArrayList<>();\r\n List rSuccNone = new ArrayList<>();\r\n List rIgnore = new ArrayList<>();\r\n List uSuccCreate = new ArrayList<>();\r\n List uFailCreate = new ArrayList<>();\r\n List uSuccUpdate = new ArrayList<>();\r\n List uFailUpdate = new ArrayList<>();\r\n List uSuccDelete = new ArrayList<>();\r\n List uFailDelete = new ArrayList<>();\r\n List uSuccNone = new ArrayList<>();\r\n List uIgnore = new ArrayList<>();\r\n List gSuccCreate = new ArrayList<>();\r\n List gFailCreate = new ArrayList<>();\r\n List gSuccUpdate = new ArrayList<>();\r\n List gFailUpdate = new ArrayList<>();\r\n List gSuccDelete = new ArrayList<>();\r\n List gFailDelete = new ArrayList<>();\r\n List gSuccNone = new ArrayList<>();\r\n List gIgnore = new ArrayList<>();\r\n List aSuccCreate = new ArrayList<>();\r\n List aFailCreate = new ArrayList<>();\r\n List aSuccUpdate = new ArrayList<>();\r\n List aFailUpdate = new ArrayList<>();\r\n List aSuccDelete = new ArrayList<>();\r\n List aFailDelete = new ArrayList<>();\r\n List aSuccNone = new ArrayList<>();\r\n List aIgnore = new ArrayList<>();\r\n List laSuccCreate = new ArrayList<>();\r\n List laFailCreate = new ArrayList<>();\r\n List laSuccUpdate = new ArrayList<>();\r\n List laFailUpdate = new ArrayList<>();\r\n List laSuccDelete = new ArrayList<>();\r\n List laFailDelete = new ArrayList<>();\r\n List laSuccNone = new ArrayList<>();\r\n List laIgnore = new ArrayList<>();\r\n for (ProvisioningReport provResult : provResults) {\r\n switch(provResult.getStatus()) {\r\n case SUCCESS:\r\n switch(provResult.getOperation()) {\r\n case CREATE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rSuccCreate.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uSuccCreate.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laSuccCreate.add(provResult);\r\n break;\r\n case GROUP:\r\n gSuccCreate.add(provResult);\r\n break;\r\n default:\r\n aSuccCreate.add(provResult);\r\n }\r\n }\r\n break;\r\n case UPDATE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rSuccUpdate.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uSuccUpdate.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laSuccUpdate.add(provResult);\r\n break;\r\n case GROUP:\r\n gSuccUpdate.add(provResult);\r\n break;\r\n default:\r\n aSuccUpdate.add(provResult);\r\n }\r\n }\r\n break;\r\n case DELETE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rSuccDelete.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uSuccDelete.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laSuccDelete.add(provResult);\r\n break;\r\n case GROUP:\r\n gSuccDelete.add(provResult);\r\n break;\r\n default:\r\n aSuccDelete.add(provResult);\r\n }\r\n }\r\n break;\r\n case NONE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rSuccNone.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uSuccNone.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laSuccNone.add(provResult);\r\n break;\r\n case GROUP:\r\n gSuccNone.add(provResult);\r\n break;\r\n default:\r\n aSuccNone.add(provResult);\r\n }\r\n }\r\n break;\r\n default:\r\n }\r\n break;\r\n case FAILURE:\r\n switch(provResult.getOperation()) {\r\n case CREATE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rFailCreate.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uFailCreate.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laFailCreate.add(provResult);\r\n break;\r\n case GROUP:\r\n gFailCreate.add(provResult);\r\n break;\r\n default:\r\n aFailCreate.add(provResult);\r\n }\r\n }\r\n break;\r\n case UPDATE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rFailUpdate.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uFailUpdate.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laFailUpdate.add(provResult);\r\n break;\r\n case GROUP:\r\n gFailUpdate.add(provResult);\r\n break;\r\n default:\r\n aFailUpdate.add(provResult);\r\n }\r\n }\r\n break;\r\n case DELETE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rFailDelete.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uFailDelete.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laFailDelete.add(provResult);\r\n break;\r\n case GROUP:\r\n gFailDelete.add(provResult);\r\n break;\r\n default:\r\n aFailDelete.add(provResult);\r\n }\r\n }\r\n break;\r\n default:\r\n }\r\n break;\r\n case IGNORE:\r\n if (StringUtils.isBlank(provResult.getAnyType())) {\r\n rIgnore.add(provResult);\r\n } else {\r\n switch(provResult.getAnyType()) {\r\n case USER:\r\n uIgnore.add(provResult);\r\n break;\r\n case LINKED_ACCOUNT:\r\n laIgnore.add(provResult);\r\n break;\r\n case GROUP:\r\n gIgnore.add(provResult);\r\n break;\r\n default:\r\n aIgnore.add(provResult);\r\n }\r\n }\r\n break;\r\n default:\r\n }\r\n }\r\n boolean includeUser = resource.getProvisionByAnyType(AnyTypeKind.USER.name()).isPresent();\r\n boolean includeGroup = resource.getProvisionByAnyType(AnyTypeKind.GROUP.name()).isPresent();\r\n boolean includeAnyObject = resource.getProvisions().stream().anyMatch(provision -> !provision.getAnyType().equals(AnyTypeKind.USER.name()) && !provision.getAnyType().equals(AnyTypeKind.GROUP.name()));\r\n boolean includeRealm = resource.getOrgUnit() != null;\r\n if (includeUser) {\r\n report.append(\"Users \").append(\"[created/failures]: \").append(uSuccCreate.size()).append('/').append(uFailCreate.size()).append(' ').append(\"[updated/failures]: \").append(uSuccUpdate.size()).append('/').append(uFailUpdate.size()).append(' ').append(\"[deleted/failures]: \").append(uSuccDelete.size()).append('/').append(uFailDelete.size()).append(' ').append(\"[no operation/ignored]: \").append(uSuccNone.size()).append('/').append(uIgnore.size()).append('\\n');\r\n report.append(\"Accounts \").append(\"[created/failures]: \").append(laSuccCreate.size()).append('/').append(laFailCreate.size()).append(' ').append(\"[updated/failures]: \").append(laSuccUpdate.size()).append('/').append(laFailUpdate.size()).append(' ').append(\"[deleted/failures]: \").append(laSuccDelete.size()).append('/').append(laFailDelete.size()).append(' ').append(\"[no operation/ignored]: \").append(laSuccNone.size()).append('/').append(laIgnore.size()).append('\\n');\r\n }\r\n if (includeGroup) {\r\n report.append(\"Groups \").append(\"[created/failures]: \").append(gSuccCreate.size()).append('/').append(gFailCreate.size()).append(' ').append(\"[updated/failures]: \").append(gSuccUpdate.size()).append('/').append(gFailUpdate.size()).append(' ').append(\"[deleted/failures]: \").append(gSuccDelete.size()).append('/').append(gFailDelete.size()).append(' ').append(\"[no operation/ignored]: \").append(gSuccNone.size()).append('/').append(gIgnore.size()).append('\\n');\r\n }\r\n if (includeAnyObject) {\r\n report.append(\"Any objects \").append(\"[created/failures]: \").append(aSuccCreate.size()).append('/').append(aFailCreate.size()).append(' ').append(\"[updated/failures]: \").append(aSuccUpdate.size()).append('/').append(aFailUpdate.size()).append(' ').append(\"[deleted/failures]: \").append(aSuccDelete.size()).append('/').append(aFailDelete.size()).append(' ').append(\"[no operation/ignored]: \").append(aSuccNone.size()).append('/').append(aIgnore.size());\r\n }\r\n if (includeRealm) {\r\n report.append(\"Realms \").append(\"[created/failures]: \").append(rSuccCreate.size()).append('/').append(rFailCreate.size()).append(' ').append(\"[updated/failures]: \").append(rSuccUpdate.size()).append('/').append(rFailUpdate.size()).append(' ').append(\"[deleted/failures]: \").append(rSuccDelete.size()).append('/').append(rFailDelete.size()).append(' ').append(\"[no operation/ignored]: \").append(rSuccNone.size()).append('/').append(rIgnore.size());\r\n }\r\n if (traceLevel == TraceLevel.FAILURES || traceLevel == TraceLevel.ALL) {\r\n if (includeUser) {\r\n if (!uFailCreate.isEmpty()) {\r\n report.append(\"\\n\\nUsers failed to create: \");\r\n report.append(generate(uFailCreate, traceLevel));\r\n }\r\n if (!uFailUpdate.isEmpty()) {\r\n report.append(\"\\nUsers failed to update: \");\r\n report.append(generate(uFailUpdate, traceLevel));\r\n }\r\n if (!uFailDelete.isEmpty()) {\r\n report.append(\"\\nUsers failed to delete: \");\r\n report.append(generate(uFailDelete, traceLevel));\r\n }\r\n if (!laFailCreate.isEmpty()) {\r\n report.append(\"\\n\\nAccounts failed to create: \");\r\n report.append(generate(laFailCreate, traceLevel));\r\n }\r\n if (!laFailUpdate.isEmpty()) {\r\n report.append(\"\\nAccounts failed to update: \");\r\n report.append(generate(laFailUpdate, traceLevel));\r\n }\r\n if (!laFailDelete.isEmpty()) {\r\n report.append(\"\\nAccounts failed to delete: \");\r\n report.append(generate(laFailDelete, traceLevel));\r\n }\r\n }\r\n if (includeGroup) {\r\n if (!gFailCreate.isEmpty()) {\r\n report.append(\"\\n\\nGroups failed to create: \");\r\n report.append(generate(gFailCreate, traceLevel));\r\n }\r\n if (!gFailUpdate.isEmpty()) {\r\n report.append(\"\\nGroups failed to update: \");\r\n report.append(generate(gFailUpdate, traceLevel));\r\n }\r\n if (!gFailDelete.isEmpty()) {\r\n report.append(\"\\nGroups failed to delete: \");\r\n report.append(generate(gFailDelete, traceLevel));\r\n }\r\n }\r\n if (includeAnyObject && !aFailCreate.isEmpty()) {\r\n report.append(\"\\nAny objects failed to create: \");\r\n report.append(generate(aFailCreate, traceLevel));\r\n }\r\n if (includeAnyObject && !aFailUpdate.isEmpty()) {\r\n report.append(\"\\nAny objects failed to update: \");\r\n report.append(generate(aFailUpdate, traceLevel));\r\n }\r\n if (includeAnyObject && !aFailDelete.isEmpty()) {\r\n report.append(\"\\nAny objects failed to delete: \");\r\n report.append(generate(aFailDelete, traceLevel));\r\n }\r\n if (includeRealm) {\r\n if (!rFailCreate.isEmpty()) {\r\n report.append(\"\\nRealms failed to create: \");\r\n report.append(generate(rFailCreate, traceLevel));\r\n }\r\n if (!rFailUpdate.isEmpty()) {\r\n report.append(\"\\nRealms failed to update: \");\r\n report.append(generate(rFailUpdate, traceLevel));\r\n }\r\n if (!rFailDelete.isEmpty()) {\r\n report.append(\"\\nRealms failed to delete: \");\r\n report.append(generate(rFailDelete, traceLevel));\r\n }\r\n }\r\n }\r\n if (traceLevel == TraceLevel.ALL) {\r\n if (includeUser) {\r\n if (!uSuccCreate.isEmpty()) {\r\n report.append(\"\\n\\nUsers created:\\n\").append(generate(uSuccCreate, traceLevel));\r\n }\r\n if (!uSuccUpdate.isEmpty()) {\r\n report.append(\"\\nUsers updated:\\n\").append(generate(uSuccUpdate, traceLevel));\r\n }\r\n if (!uSuccDelete.isEmpty()) {\r\n report.append(\"\\nUsers deleted:\\n\").append(generate(uSuccDelete, traceLevel));\r\n }\r\n if (!uSuccNone.isEmpty()) {\r\n report.append(\"\\nUsers no operation:\\n\").append(generate(uSuccNone, traceLevel));\r\n }\r\n if (!uIgnore.isEmpty()) {\r\n report.append(\"\\nUsers ignored:\\n\").append(generate(uIgnore, traceLevel));\r\n }\r\n if (!laSuccCreate.isEmpty()) {\r\n report.append(\"\\n\\nAccounts created:\\n\").append(generate(laSuccCreate, traceLevel));\r\n }\r\n if (!laSuccUpdate.isEmpty()) {\r\n report.append(\"\\nAccounts updated:\\n\").append(generate(laSuccUpdate, traceLevel));\r\n }\r\n if (!laSuccDelete.isEmpty()) {\r\n report.append(\"\\nAccounts deleted:\\n\").append(generate(laSuccDelete, traceLevel));\r\n }\r\n if (!laSuccNone.isEmpty()) {\r\n report.append(\"\\nAccounts no operation:\\n\").append(generate(laSuccNone, traceLevel));\r\n }\r\n if (!laIgnore.isEmpty()) {\r\n report.append(\"\\nAccounts ignored:\\n\").append(generate(laIgnore, traceLevel));\r\n }\r\n }\r\n if (includeGroup) {\r\n if (!gSuccCreate.isEmpty()) {\r\n report.append(\"\\n\\nGroups created:\\n\").append(generate(gSuccCreate, traceLevel));\r\n }\r\n if (!gSuccUpdate.isEmpty()) {\r\n report.append(\"\\nGroups updated:\\n\").append(generate(gSuccUpdate, traceLevel));\r\n }\r\n if (!gSuccDelete.isEmpty()) {\r\n report.append(\"\\nGroups deleted:\\n\").append(generate(gSuccDelete, traceLevel));\r\n }\r\n if (!gSuccNone.isEmpty()) {\r\n report.append(\"\\nGroups no operation:\\n\").append(generate(gSuccNone, traceLevel));\r\n }\r\n if (!gIgnore.isEmpty()) {\r\n report.append(\"\\nGroups ignored:\\n\").append(generate(gIgnore, traceLevel));\r\n }\r\n }\r\n if (includeAnyObject) {\r\n if (!aSuccCreate.isEmpty()) {\r\n report.append(\"\\n\\nAny objects created:\\n\").append(generate(aSuccCreate, traceLevel));\r\n }\r\n if (!aSuccUpdate.isEmpty()) {\r\n report.append(\"\\nAny objects updated:\\n\").append(generate(aSuccUpdate, traceLevel));\r\n }\r\n if (!aSuccDelete.isEmpty()) {\r\n report.append(\"\\nAny objects deleted:\\n\").append(generate(aSuccDelete, traceLevel));\r\n }\r\n if (!aSuccNone.isEmpty()) {\r\n report.append(\"\\nAny objects no operation:\\n\").append(generate(aSuccNone, traceLevel));\r\n }\r\n if (!aIgnore.isEmpty()) {\r\n report.append(\"\\nAny objects ignored:\\n\").append(generate(aIgnore, traceLevel));\r\n }\r\n }\r\n if (includeRealm) {\r\n if (!rSuccCreate.isEmpty()) {\r\n report.append(\"\\n\\nRealms created:\\n\").append(generate(rSuccCreate, traceLevel));\r\n }\r\n if (!rSuccUpdate.isEmpty()) {\r\n report.append(\"\\nRealms updated:\\n\").append(generate(rSuccUpdate, traceLevel));\r\n }\r\n if (!rSuccDelete.isEmpty()) {\r\n report.append(\"\\nRealms deleted:\\n\").append(generate(rSuccDelete, traceLevel));\r\n }\r\n if (!rSuccNone.isEmpty()) {\r\n report.append(\"\\nRealms no operation:\\n\").append(generate(rSuccNone, traceLevel));\r\n }\r\n if (!rIgnore.isEmpty()) {\r\n report.append(\"\\nRealms ignored:\\n\").append(generate(rIgnore, traceLevel));\r\n }\r\n }\r\n }\r\n return report.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Pair extractGlobalTimeFilter(Expression predicate, boolean canRewrite, boolean isFirstOr){\r\n if (predicate.getExpressionType().equals(ExpressionType.LOGIC_AND)) {\r\n Pair leftResultPair = extractGlobalTimeFilter(((BinaryExpression) predicate).getLeftExpression(), canRewrite, isFirstOr);\r\n Pair rightResultPair = extractGlobalTimeFilter(((BinaryExpression) predicate).getRightExpression(), canRewrite, isFirstOr);\r\n if (canRewrite) {\r\n if (leftResultPair.left != null && !leftResultPair.right) {\r\n ((BinaryExpression) predicate).setLeftExpression(new ConstantOperand(TSDataType.BOOLEAN, \"true\"));\r\n }\r\n if (rightResultPair.left != null && !rightResultPair.right) {\r\n ((BinaryExpression) predicate).setRightExpression(new ConstantOperand(TSDataType.BOOLEAN, \"true\"));\r\n }\r\n }\r\n if (leftResultPair.left != null && rightResultPair.left != null) {\r\n return new Pair<>(FilterFactory.and(leftResultPair.left, rightResultPair.left), leftResultPair.right || rightResultPair.right);\r\n } else if (leftResultPair.left != null) {\r\n return new Pair<>(leftResultPair.left, true);\r\n } else if (rightResultPair.left != null) {\r\n return new Pair<>(rightResultPair.left, true);\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.LOGIC_OR)) {\r\n Pair leftResultPair = extractGlobalTimeFilter(((BinaryExpression) predicate).getLeftExpression(), false, false);\r\n Pair rightResultPair = extractGlobalTimeFilter(((BinaryExpression) predicate).getRightExpression(), false, false);\r\n if (leftResultPair.left != null && rightResultPair.left != null) {\r\n if (Boolean.TRUE.equals(isFirstOr && !leftResultPair.right && !rightResultPair.right)) {\r\n ((BinaryExpression) predicate).setLeftExpression(new ConstantOperand(TSDataType.BOOLEAN, \"true\"));\r\n ((BinaryExpression) predicate).setRightExpression(new ConstantOperand(TSDataType.BOOLEAN, \"true\"));\r\n }\r\n return new Pair<>(FilterFactory.or(leftResultPair.left, rightResultPair.left), leftResultPair.right || rightResultPair.right);\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.LOGIC_NOT)) {\r\n Pair childResultPair = extractGlobalTimeFilter(((UnaryExpression) predicate).getExpression(), canRewrite, isFirstOr);\r\n if (childResultPair.left != null) {\r\n return new Pair<>(FilterFactory.not(childResultPair.left), childResultPair.right);\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.isCompareBinaryExpression()) {\r\n Filter timeInLeftFilter = constructTimeFilter(predicate.getExpressionType(), ((BinaryExpression) predicate).getLeftExpression(), ((BinaryExpression) predicate).getRightExpression());\r\n if (timeInLeftFilter != null) {\r\n return new Pair<>(timeInLeftFilter, false);\r\n }\r\n Filter timeInRightFilter = constructTimeFilter(predicate.getExpressionType(), ((BinaryExpression) predicate).getRightExpression(), ((BinaryExpression) predicate).getLeftExpression());\r\n if (timeInRightFilter != null) {\r\n return new Pair<>(timeInRightFilter, false);\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.LIKE) || predicate.getExpressionType().equals(ExpressionType.REGEXP)) {\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.BETWEEN)) {\r\n Expression firstExpression = ((TernaryExpression) predicate).getFirstExpression();\r\n Expression secondExpression = ((TernaryExpression) predicate).getSecondExpression();\r\n Expression thirdExpression = ((TernaryExpression) predicate).getThirdExpression();\r\n if (firstExpression.getExpressionType().equals(ExpressionType.TIMESTAMP)) {\r\n return getPairFromBetweenTimeFirst(secondExpression, thirdExpression, ((BetweenExpression) predicate).isNotBetween());\r\n } else if (secondExpression.getExpressionType().equals(ExpressionType.TIMESTAMP)) {\r\n if (checkConstantSatisfy(firstExpression, thirdExpression)) {\r\n return getPairFromBetweenTimeSecond((BetweenExpression) predicate, firstExpression);\r\n } else {\r\n return new Pair<>(null, true);\r\n }\r\n } else if (thirdExpression.getExpressionType().equals(ExpressionType.TIMESTAMP)) {\r\n if (checkConstantSatisfy(secondExpression, firstExpression)) {\r\n return getPairFromBetweenTimeThird((BetweenExpression) predicate, firstExpression);\r\n } else {\r\n return new Pair<>(null, true);\r\n }\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.IS_NULL)) {\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.IN)) {\r\n Expression timeExpression = ((InExpression) predicate).getExpression();\r\n if (timeExpression.getExpressionType().equals(ExpressionType.TIMESTAMP)) {\r\n boolean not = ((InExpression) predicate).isNotIn();\r\n Set values = ((InExpression) predicate).getValues().stream().map(Long::parseLong).collect(Collectors.toSet());\r\n return new Pair<>(not ? TimeFilter.notIn(values) : TimeFilter.in(values), false);\r\n }\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.TIMESERIES) || predicate.getExpressionType().equals(ExpressionType.CONSTANT) || predicate.getExpressionType().equals(ExpressionType.NULL)) {\r\n return new Pair<>(null, true);\r\n } else if (predicate.getExpressionType().equals(ExpressionType.CASE_WHEN_THEN)) {\r\n return new Pair<>(null, true);\r\n } else {\r\n throw new UnknownExpressionTypeException(predicate.getExpressionType());\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void executeCreateMissingPathTxn(ZooKeeper zk, List zkOps, List pathsToCreate, List> metadatas, String logRootPath, CompletableFuture>> promise){\r\n zk.multi(zkOps, new AsyncCallback.MultiCallback() {\r\n\r\n @Override\r\n public void processResult(int rc, String path, Object ctx, List resultList) {\r\n if (KeeperException.Code.OK.intValue() == rc) {\r\n List> finalMetadatas = Lists.newArrayListWithExpectedSize(metadatas.size());\r\n for (int i = 0; i < pathsToCreate.size(); i++) {\r\n byte[] dataCreated = pathsToCreate.get(i);\r\n if (null == dataCreated) {\r\n finalMetadatas.add(metadatas.get(i));\r\n } else {\r\n finalMetadatas.add(new Versioned(dataCreated, new LongVersion(0)));\r\n }\r\n }\r\n promise.complete(finalMetadatas);\r\n } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {\r\n promise.completeExceptionally(new LogExistsException(\"Someone just created log \" + logRootPath));\r\n } else {\r\n if (LOG.isDebugEnabled()) {\r\n StringBuilder builder = new StringBuilder();\r\n for (OpResult result : resultList) {\r\n if (result instanceof OpResult.ErrorResult) {\r\n OpResult.ErrorResult errorResult = (OpResult.ErrorResult) result;\r\n builder.append(errorResult.getErr()).append(\",\");\r\n } else {\r\n builder.append(0).append(\",\");\r\n }\r\n }\r\n String resultCodeList = builder.substring(0, builder.length() - 1);\r\n LOG.debug(\"Failed to create log, full rc list = {}\", resultCodeList);\r\n }\r\n promise.completeExceptionally(new ZKException(\"Failed to create log \" + logRootPath, KeeperException.Code.get(rc)));\r\n }\r\n }\r\n }, null);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static void displayAllOperations(String id, KmeliaSessionController kmeliaScc, GraphicElementFactory gef, String action, MultiSilverpeasBundle resources, JspWriter out, boolean kmaxMode) throws IOException{\r\n String routerUrl = URLUtil.getApplicationURL() + URLUtil.getURL(kmeliaScc.getComponentRootName(), kmeliaScc.getSpaceId(), kmeliaScc.getComponentId());\r\n displayJavascriptAndFormToOperations(kmeliaScc, out);\r\n boolean enabled = StringUtil.isDefined(id);\r\n List invisibleTabs = kmeliaScc.getInvisibleTabs();\r\n TabbedPane tabbedPane = gef.getTabbedPane();\r\n PublicationDetail pubDetail = kmeliaScc.getSessionPublication().getDetail();\r\n PublicationDetail cloneDetail = null;\r\n if (kmeliaScc.getSessionClone() != null) {\r\n cloneDetail = kmeliaScc.getSessionClone().getDetail();\r\n }\r\n String decoration = \"\";\r\n String pubId = pubDetail.getPK().getId();\r\n String previewTabLabel = resources.getString(\"PublicationPreview\");\r\n String sureId = pubId;\r\n if (cloneDetail != null) {\r\n decoration = \" *\";\r\n sureId = cloneDetail.getId();\r\n previewTabLabel = resources.getString(\"kmelia.PublicPreview\");\r\n }\r\n if (invisibleTabs.indexOf(KmeliaSessionController.TAB_PREVIEW) == -1) {\r\n tabbedPane.addTab(previewTabLabel, routerUrl + \"ViewPublication?PubId=\" + pubId, \"View\".equals(action) || \"ViewPublication\".equals(action), enabled);\r\n }\r\n if (cloneDetail != null) {\r\n tabbedPane.addTab(resources.getString(\"kmelia.ClonePreview\") + decoration, routerUrl + \"ViewClone\", \"ViewClone\".equals(action), enabled);\r\n }\r\n if (invisibleTabs.indexOf(KmeliaSessionController.TAB_HEADER) == -1) {\r\n tabbedPane.addTab(kmeliaScc.getString(\"Header\") + decoration, routerUrl + \"ToUpdatePublicationHeader\", \"UpdateView\".equals(action) || \"New\".equals(action) || \"KmaxModifyPublication\".equals(action), enabled);\r\n }\r\n if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) {\r\n tabbedPane.addTab(resources.getString(\"Model\") + decoration, \"javaScript:onClick=goToOperation('\" + routerUrl + \"ToPubliContent', '\" + sureId + \"', 'ModelUpdateView')\", \"ModelUpdateView\".equals(action) || \"NewModel\".equals(action) || \"ModelChoice\".equals(action), enabled);\r\n }\r\n if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) {\r\n if (kmeliaScc.getComponentId().startsWith(\"toolbox\")) {\r\n decoration = \"\";\r\n tabbedPane.addTab(resources.getString(\"GML.attachments\") + decoration, \"javaScript:onClick=goToOperationByGet('\" + routerUrl + \"ViewAttachments', '\" + pubId + \"', 'ViewAttachments')\", \"ViewAttachments\".equals(action), enabled);\r\n }\r\n }\r\n if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ACCESS_PATHS) == -1 && !kmaxMode && !pubDetail.isAlias()) {\r\n tabbedPane.addTab(resources.getString(\"PubGererChemins\") + \" (\" + kmeliaScc.getPublicationLocations().size() + \")\", routerUrl + \"PublicationPaths?PubId=\" + pubId, \"ViewPath\".equals(action), enabled);\r\n }\r\n if (kmaxMode) {\r\n tabbedPane.addTab(kmeliaScc.getString(\"PubPositions\"), \"KmaxViewCombination?PubId=\" + pubId, action.equals(\"KmaxViewCombination\"), enabled);\r\n }\r\n if (invisibleTabs.indexOf(kmeliaScc.TAB_READER_LIST) == -1) {\r\n tabbedPane.addTab(resources.getString(\"PubGererControlesLecture\"), routerUrl + \"ReadingControl\", action.equals(\"ViewReadingControl\"), enabled);\r\n }\r\n if (kmeliaScc.isValidationTabVisible()) {\r\n tabbedPane.addTab(resources.getString(\"kmelia.validation\"), routerUrl + \"ViewValidationSteps\", \"ViewValidationSteps\".equals(action), enabled);\r\n }\r\n out.println(tabbedPane.print());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException{\r\n final JSch jsch = new JSch();\r\n JSch.setLogger(new JSchLogger(endpoint.getConfiguration().getJschLoggingLevel()));\r\n SftpConfiguration sftpConfig = (SftpConfiguration) configuration;\r\n if (isNotEmpty(sftpConfig.getCiphers())) {\r\n LOG.debug(\"Using ciphers: {}\", sftpConfig.getCiphers());\r\n Hashtable ciphers = new Hashtable<>();\r\n ciphers.put(\"cipher.s2c\", sftpConfig.getCiphers());\r\n ciphers.put(\"cipher.c2s\", sftpConfig.getCiphers());\r\n JSch.setConfig(ciphers);\r\n }\r\n if (isNotEmpty(sftpConfig.getKeyExchangeProtocols())) {\r\n LOG.debug(\"Using KEX: {}\", sftpConfig.getKeyExchangeProtocols());\r\n JSch.setConfig(\"kex\", sftpConfig.getKeyExchangeProtocols());\r\n }\r\n if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {\r\n LOG.debug(\"Using private keyfile: {}\", sftpConfig.getPrivateKeyFile());\r\n if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {\r\n jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());\r\n } else {\r\n jsch.addIdentity(sftpConfig.getPrivateKeyFile());\r\n }\r\n }\r\n if (sftpConfig.getPrivateKey() != null) {\r\n LOG.debug(\"Using private key information from byte array\");\r\n byte[] passphrase = null;\r\n if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {\r\n passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes(StandardCharsets.UTF_8);\r\n }\r\n jsch.addIdentity(\"ID\", sftpConfig.getPrivateKey(), null, passphrase);\r\n }\r\n if (sftpConfig.getPrivateKeyUri() != null) {\r\n LOG.debug(\"Using private key uri : {}\", sftpConfig.getPrivateKeyUri());\r\n byte[] passphrase = null;\r\n if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {\r\n passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes(StandardCharsets.UTF_8);\r\n }\r\n try {\r\n InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getPrivateKeyUri());\r\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\r\n IOHelper.copyAndCloseInput(is, bos);\r\n jsch.addIdentity(\"ID\", bos.toByteArray(), null, passphrase);\r\n } catch (IOException e) {\r\n throw new JSchException(\"Cannot read resource: \" + sftpConfig.getPrivateKeyUri(), e);\r\n }\r\n }\r\n if (sftpConfig.getKeyPair() != null) {\r\n LOG.debug(\"Using private key information from key pair\");\r\n KeyPair keyPair = sftpConfig.getKeyPair();\r\n if (keyPair.getPrivate() != null) {\r\n StringBuilder sb = new StringBuilder(256);\r\n sb.append(\"-----BEGIN PRIVATE KEY-----\").append(\"\\n\");\r\n sb.append(Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())).append(\"\\n\");\r\n sb.append(\"-----END PRIVATE KEY-----\").append(\"\\n\");\r\n jsch.addIdentity(\"ID\", sb.toString().getBytes(StandardCharsets.UTF_8), null, null);\r\n } else {\r\n LOG.warn(\"PrivateKey in the KeyPair must be filled\");\r\n }\r\n }\r\n if (isNotEmpty(sftpConfig.getKnownHostsFile())) {\r\n LOG.debug(\"Using knownhosts file: {}\", sftpConfig.getKnownHostsFile());\r\n jsch.setKnownHosts(sftpConfig.getKnownHostsFile());\r\n }\r\n if (isNotEmpty(sftpConfig.getKnownHostsUri())) {\r\n LOG.debug(\"Using known hosts uri: {}\", sftpConfig.getKnownHostsUri());\r\n try {\r\n InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getKnownHostsUri());\r\n jsch.setKnownHosts(is);\r\n } catch (IOException e) {\r\n throw new JSchException(\"Cannot read resource: \" + sftpConfig.getKnownHostsUri(), e);\r\n }\r\n }\r\n if (sftpConfig.getKnownHosts() != null) {\r\n LOG.debug(\"Using known hosts information from byte array\");\r\n jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));\r\n }\r\n String knownHostsFile = sftpConfig.getKnownHostsFile();\r\n if (knownHostsFile == null && sftpConfig.isUseUserKnownHostsFile()) {\r\n knownHostsFile = System.getProperty(\"user.home\") + \"/.ssh/known_hosts\";\r\n LOG.info(\"Known host file not configured, using user known host file: {}\", knownHostsFile);\r\n }\r\n if (ObjectHelper.isNotEmpty(knownHostsFile)) {\r\n LOG.debug(\"Using known hosts information from file: {}\", knownHostsFile);\r\n jsch.setKnownHosts(knownHostsFile);\r\n }\r\n final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());\r\n if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {\r\n LOG.debug(\"Using StrictHostKeyChecking: {}\", sftpConfig.getStrictHostKeyChecking());\r\n session.setConfig(\"StrictHostKeyChecking\", sftpConfig.getStrictHostKeyChecking());\r\n }\r\n session.setServerAliveInterval(sftpConfig.getServerAliveInterval());\r\n session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());\r\n if (sftpConfig.getCompression() > 0) {\r\n LOG.debug(\"Using compression: {}\", sftpConfig.getCompression());\r\n session.setConfig(\"compression.s2c\", \"zlib@openssh.com,zlib,none\");\r\n session.setConfig(\"compression.c2s\", \"zlib@openssh.com,zlib,none\");\r\n session.setConfig(\"compression_level\", Integer.toString(sftpConfig.getCompression()));\r\n }\r\n if (sftpConfig.getPreferredAuthentications() != null) {\r\n LOG.debug(\"Using PreferredAuthentications: {}\", sftpConfig.getPreferredAuthentications());\r\n session.setConfig(\"PreferredAuthentications\", sftpConfig.getPreferredAuthentications());\r\n }\r\n if (sftpConfig.getServerHostKeys() != null) {\r\n LOG.debug(\"Using ServerHostKeys: {}\", sftpConfig.getServerHostKeys());\r\n session.setConfig(\"server_host_key\", sftpConfig.getServerHostKeys());\r\n }\r\n if (sftpConfig.getPublicKeyAcceptedAlgorithms() != null) {\r\n LOG.debug(\"Using PublicKeyAcceptedAlgorithms: {}\", sftpConfig.getPublicKeyAcceptedAlgorithms());\r\n session.setConfig(\"PubkeyAcceptedAlgorithms\", sftpConfig.getPublicKeyAcceptedAlgorithms());\r\n }\r\n session.setUserInfo(new ExtendedUserInfo() {\r\n\r\n public String getPassphrase() {\r\n return null;\r\n }\r\n\r\n public String getPassword() {\r\n return configuration.getPassword();\r\n }\r\n\r\n public boolean promptPassword(String s) {\r\n return true;\r\n }\r\n\r\n public boolean promptPassphrase(String s) {\r\n return true;\r\n }\r\n\r\n public boolean promptYesNo(String s) {\r\n LOG.warn(\"Server asks for confirmation (yes|no): {}. Camel will answer no.\", s);\r\n return false;\r\n }\r\n\r\n public void showMessage(String s) {\r\n LOG.trace(\"Message received from Server: {}\", s);\r\n }\r\n\r\n public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {\r\n if (configuration.getPassword() == null) {\r\n return new String[0];\r\n } else {\r\n return new String[] { configuration.getPassword() };\r\n }\r\n }\r\n });\r\n if (sftpConfig.getServerAliveInterval() == 0) {\r\n if (configuration.getSoTimeout() > 0) {\r\n session.setTimeout(configuration.getSoTimeout());\r\n }\r\n } else {\r\n LOG.debug(\"The Server Alive Internal is already set, the socket timeout won't be considered to avoid overidding the provided Server alive interval value\");\r\n }\r\n if (proxy != null) {\r\n session.setProxy(proxy);\r\n }\r\n if (isNotEmpty(sftpConfig.getBindAddress())) {\r\n session.setSocketFactory(new SocketFactory() {\r\n\r\n @Override\r\n public OutputStream getOutputStream(Socket socket) throws IOException {\r\n return socket.getOutputStream();\r\n }\r\n\r\n @Override\r\n public InputStream getInputStream(Socket socket) throws IOException {\r\n return socket.getInputStream();\r\n }\r\n\r\n @Override\r\n public Socket createSocket(String host, int port) throws IOException {\r\n return createSocketUtil(host, port, sftpConfig.getBindAddress(), session.getTimeout());\r\n }\r\n });\r\n }\r\n return session;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void onMatch(RelOptRuleCall call){\r\n final Union union = call.rel(0);\r\n final RexBuilder rexBuilder = union.getCluster().getRexBuilder();\r\n final RelMetadataQuery mq = call.getMetadataQuery();\r\n final RelOptPredicateList predicates = mq.getPulledUpPredicates(union);\r\n if (RelOptPredicateList.isEmpty(predicates)) {\r\n return;\r\n }\r\n final Map constants = new HashMap<>();\r\n for (Map.Entry e : predicates.constantMap.entrySet()) {\r\n if (e.getKey() instanceof RexInputRef) {\r\n constants.put(((RexInputRef) e.getKey()).getIndex(), e.getValue());\r\n }\r\n }\r\n if (constants.isEmpty()) {\r\n return;\r\n }\r\n List fields = union.getRowType().getFieldList();\r\n List topChildExprs = new ArrayList<>();\r\n List topChildExprsFields = new ArrayList<>();\r\n List refs = new ArrayList<>();\r\n ImmutableBitSet.Builder refsIndexBuilder = ImmutableBitSet.builder();\r\n for (RelDataTypeField field : fields) {\r\n final RexNode constant = constants.get(field.getIndex());\r\n if (constant != null) {\r\n if (constant.getType().equals(field.getType())) {\r\n topChildExprs.add(constant);\r\n } else {\r\n topChildExprs.add(rexBuilder.makeCast(field.getType(), constant, true, false));\r\n }\r\n topChildExprsFields.add(field.getName());\r\n } else {\r\n final RexNode expr = rexBuilder.makeInputRef(union, field.getIndex());\r\n topChildExprs.add(expr);\r\n topChildExprsFields.add(field.getName());\r\n refs.add(expr);\r\n refsIndexBuilder.set(field.getIndex());\r\n }\r\n }\r\n ImmutableBitSet refsIndex = refsIndexBuilder.build();\r\n final Mappings.TargetMapping mapping = RelOptUtil.permutation(refs, union.getInput(0).getRowType()).inverse();\r\n topChildExprs = RexUtil.apply(mapping, topChildExprs);\r\n final RelBuilder relBuilder = call.builder();\r\n for (RelNode input : union.getInputs()) {\r\n List> newChildExprs = new ArrayList<>();\r\n for (int j : refsIndex) {\r\n newChildExprs.add(Pair.of(rexBuilder.makeInputRef(input, j), input.getRowType().getFieldList().get(j).getName()));\r\n }\r\n if (newChildExprs.isEmpty()) {\r\n newChildExprs.add(Pair.of(topChildExprs.get(0), topChildExprsFields.get(0)));\r\n }\r\n relBuilder.push(input);\r\n relBuilder.project(Pair.left(newChildExprs), Pair.right(newChildExprs));\r\n }\r\n relBuilder.union(union.all, union.getInputs().size());\r\n relBuilder.project(topChildExprs, topChildExprsFields);\r\n relBuilder.convert(union.getRowType(), false);\r\n call.transformTo(relBuilder.build());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String getBasePathFromOpenApi(final OpenAPI openApi){\r\n String basePath = null;\r\n if (openApi.getServers() != null) {\r\n for (Server server : openApi.getServers()) {\r\n if (server.getUrl() != null) {\r\n try {\r\n URI serverUrl = new URI(parseVariables(server.getUrl(), server));\r\n basePath = serverUrl.getPath();\r\n if (basePath.indexOf(\"//\") == 0) {\r\n basePath = basePath.substring(1);\r\n }\r\n if (\"/\".equals(basePath)) {\r\n basePath = \"\";\r\n }\r\n } catch (URISyntaxException e) {\r\n basePath = server.getUrl();\r\n }\r\n }\r\n }\r\n }\r\n return basePath;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void run() throws SQLException{\r\n final String url = \"jdbc:calcite:lex=JAVA;conformance=LENIENT\" + \";model=inline:\" + MODEL;\r\n final String help = \"Usage: sqlsh [OPTION]... SQL\\n\" + \"Execute a SQL command\\n\" + \"\\n\" + \"Options:\\n\" + \" -o FORMAT Print output in FORMAT; options are 'spaced' (the \" + \"default), 'csv',\\n\" + \" 'headers', 'json', 'mysql'\\n\" + \" -h --help Print this help\";\r\n final StringBuilder b = new StringBuilder();\r\n Format format = Format.SPACED;\r\n try (Enumerator args = Linq4j.asEnumerable(this.args).enumerator()) {\r\n while (args.moveNext()) {\r\n if (args.current().equals(\"-o\")) {\r\n if (args.moveNext()) {\r\n String formatString = args.current();\r\n try {\r\n format = Format.valueOf(formatString.toUpperCase(Locale.ROOT));\r\n } catch (IllegalArgumentException e) {\r\n throw new RuntimeException(\"unknown format: \" + formatString);\r\n }\r\n } else {\r\n throw new RuntimeException(\"missing format\");\r\n }\r\n } else if (args.current().equals(\"-h\") || args.current().equals(\"--help\")) {\r\n out.println(help);\r\n return;\r\n } else {\r\n if (b.length() > 0) {\r\n b.append(' ');\r\n }\r\n b.append(args.current());\r\n }\r\n }\r\n }\r\n try (Connection connection = DriverManager.getConnection(url);\r\n Statement s = connection.createStatement();\r\n Enumerator args = Linq4j.asEnumerable(this.args).enumerator()) {\r\n final ResultSet r = s.executeQuery(b.toString());\r\n format.output(out, r);\r\n r.close();\r\n } finally {\r\n out.flush();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Object fromMessageAttributeValue(MessageAttributeValue mav){\r\n if (mav == null) {\r\n return null;\r\n }\r\n if (mav.binaryValue() != null) {\r\n return mav.binaryValue();\r\n } else if (mav.stringValue() != null) {\r\n String s = mav.stringValue();\r\n String dt = mav.dataType();\r\n if (dt == null || \"String\".equals(dt)) {\r\n return s;\r\n } else if (\"Number.Boolean\".equals(dt)) {\r\n return \"1\".equals(s) ? Boolean.TRUE : Boolean.FALSE;\r\n } else if (\"Number.int\".equals(dt)) {\r\n return Integer.valueOf(s);\r\n } else if (\"Number.byte\".equals(dt)) {\r\n return Byte.valueOf(s);\r\n } else if (\"Number.double\".equals(dt)) {\r\n return Double.valueOf(s);\r\n } else if (\"Number.float\".equals(dt)) {\r\n return Float.valueOf(s);\r\n } else if (\"Number.long\".equals(dt)) {\r\n return Long.valueOf(s);\r\n } else if (\"Number.short\".equals(dt)) {\r\n return Short.valueOf(s);\r\n }\r\n return s;\r\n }\r\n return null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected OrderBySupport parseOrderBy(final SearchSupport svs, final List orderBy){\r\n AnyUtils anyUtils = anyUtilsFactory.getInstance(svs.anyTypeKind);\r\n OrderBySupport obs = new OrderBySupport();\r\n Set orderByUniquePlainSchemas = new HashSet<>();\r\n Set orderByNonUniquePlainSchemas = new HashSet<>();\r\n orderBy.forEach(clause -> {\r\n OrderBySupport.Item item = new OrderBySupport.Item();\r\n parseOrderByForCustom(svs, clause, item, obs);\r\n if (item.isEmpty()) {\r\n if (anyUtils.getField(clause.getField()) == null) {\r\n PlainSchema schema = plainSchemaDAO.find(clause.getField());\r\n if (schema != null) {\r\n if (schema.isUniqueConstraint()) {\r\n orderByUniquePlainSchemas.add(schema.getKey());\r\n } else {\r\n orderByNonUniquePlainSchemas.add(schema.getKey());\r\n }\r\n if (orderByUniquePlainSchemas.size() > 1 || orderByNonUniquePlainSchemas.size() > 1) {\r\n SyncopeClientException invalidSearch = SyncopeClientException.build(ClientExceptionType.InvalidSearchParameters);\r\n invalidSearch.getElements().add(\"Order by more than one attribute is not allowed; \" + \"remove one from \" + (orderByUniquePlainSchemas.size() > 1 ? orderByUniquePlainSchemas : orderByNonUniquePlainSchemas));\r\n throw invalidSearch;\r\n }\r\n parseOrderByForPlainSchema(svs, obs, item, clause, schema, clause.getField());\r\n }\r\n } else {\r\n String fieldName = \"key\".equals(clause.getField()) ? \"id\" : clause.getField();\r\n if (ArrayUtils.contains(RELATIONSHIP_FIELDS, fieldName)) {\r\n fieldName += \"_id\";\r\n }\r\n obs.views.add(svs.field());\r\n parseOrderByForField(svs, item, fieldName, clause);\r\n }\r\n }\r\n if (item.isEmpty()) {\r\n LOG.warn(\"Cannot build any valid clause from {}\", clause);\r\n } else {\r\n obs.items.add(item);\r\n }\r\n });\r\n return obs;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private synchronized void preload() throws IOException{\r\n while (nextRange == null && !iteratorDone) {\r\n boolean hasMoreElements = false;\r\n try {\r\n if (l1NodesIter == null) {\r\n List l1Nodes = zk.getChildren(ledgerRootPath, null);\r\n Collections.sort(l1Nodes);\r\n l1NodesIter = l1Nodes.iterator();\r\n hasMoreElements = nextL1Node();\r\n } else if (l2NodesIter == null || !l2NodesIter.hasNext()) {\r\n hasMoreElements = nextL1Node();\r\n } else {\r\n hasMoreElements = true;\r\n }\r\n } catch (KeeperException ke) {\r\n throw new IOException(\"Error preloading next range\", ke);\r\n } catch (InterruptedException ie) {\r\n Thread.currentThread().interrupt();\r\n throw new IOException(\"Interrupted while preloading\", ie);\r\n }\r\n if (hasMoreElements) {\r\n nextRange = getLedgerRangeByLevel(curL1Nodes, l2NodesIter.next());\r\n if (nextRange.size() == 0) {\r\n nextRange = null;\r\n }\r\n } else {\r\n iteratorDone = true;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public ZipArchiveEntry getNextZipEntry() throws IOException{\r\n uncompressedCount = 0;\r\n boolean firstEntry = true;\r\n if (closed || hitCentralDirectory) {\r\n return null;\r\n }\r\n if (current != null) {\r\n closeEntry();\r\n firstEntry = false;\r\n }\r\n final long currentHeaderOffset = getBytesRead();\r\n try {\r\n if (firstEntry) {\r\n readFirstLocalFileHeader();\r\n } else {\r\n readFully(lfhBuf);\r\n }\r\n } catch (final EOFException e) {\r\n return null;\r\n }\r\n final ZipLong sig = new ZipLong(lfhBuf);\r\n if (!sig.equals(ZipLong.LFH_SIG)) {\r\n if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) {\r\n hitCentralDirectory = true;\r\n skipRemainderOfArchive();\r\n return null;\r\n }\r\n throw new ZipException(String.format(\"Unexpected record signature: 0x%x\", sig.getValue()));\r\n }\r\n int off = WORD;\r\n current = new CurrentEntry();\r\n final int versionMadeBy = ZipShort.getValue(lfhBuf, off);\r\n off += SHORT;\r\n current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);\r\n final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off);\r\n final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();\r\n final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;\r\n current.hasDataDescriptor = gpFlag.usesDataDescriptor();\r\n current.entry.setGeneralPurposeBit(gpFlag);\r\n off += SHORT;\r\n current.entry.setMethod(ZipShort.getValue(lfhBuf, off));\r\n off += SHORT;\r\n final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off));\r\n current.entry.setTime(time);\r\n off += WORD;\r\n ZipLong size = null, cSize = null;\r\n if (!current.hasDataDescriptor) {\r\n current.entry.setCrc(ZipLong.getValue(lfhBuf, off));\r\n off += WORD;\r\n cSize = new ZipLong(lfhBuf, off);\r\n off += WORD;\r\n size = new ZipLong(lfhBuf, off);\r\n off += WORD;\r\n } else {\r\n off += 3 * WORD;\r\n }\r\n final int fileNameLen = ZipShort.getValue(lfhBuf, off);\r\n off += SHORT;\r\n final int extraLen = ZipShort.getValue(lfhBuf, off);\r\n off += SHORT;\r\n final byte[] fileName = readRange(fileNameLen);\r\n current.entry.setName(entryEncoding.decode(fileName), fileName);\r\n if (hasUTF8Flag) {\r\n current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);\r\n }\r\n final byte[] extraData = readRange(extraLen);\r\n try {\r\n current.entry.setExtra(extraData);\r\n } catch (final RuntimeException ex) {\r\n final ZipException z = new ZipException(\"Invalid extra data in entry \" + current.entry.getName());\r\n z.initCause(ex);\r\n throw z;\r\n }\r\n if (!hasUTF8Flag && useUnicodeExtraFields) {\r\n ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);\r\n }\r\n processZip64Extra(size, cSize);\r\n current.entry.setLocalHeaderOffset(currentHeaderOffset);\r\n current.entry.setDataOffset(getBytesRead());\r\n current.entry.setStreamContiguous(true);\r\n final ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod());\r\n if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {\r\n if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) {\r\n final InputStream bis = new BoundedInputStream(inputStream, current.entry.getCompressedSize());\r\n switch(m) {\r\n case UNSHRINKING:\r\n current.inputStream = new UnshrinkingInputStream(bis);\r\n break;\r\n case IMPLODING:\r\n try {\r\n current.inputStream = new ExplodingInputStream(current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), bis);\r\n } catch (final IllegalArgumentException ex) {\r\n throw new IOException(\"bad IMPLODE data\", ex);\r\n }\r\n break;\r\n case BZIP2:\r\n current.inputStream = new BZip2CompressorInputStream(bis);\r\n break;\r\n case ENHANCED_DEFLATED:\r\n current.inputStream = new Deflate64CompressorInputStream(bis);\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n } else if (m == ZipMethod.ENHANCED_DEFLATED) {\r\n current.inputStream = new Deflate64CompressorInputStream(inputStream);\r\n }\r\n entriesRead++;\r\n return current.entry;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static CommandPublishingFacet create(final Optional propertyIfAny, final CausewayConfiguration configuration, final FacetHolder holder, final ServiceInjector servicesInjector){\r\n val publishingPolicy = PropertyConfigOptions.propertyCommandPublishingPolicy(configuration);\r\n return propertyIfAny.filter(property -> property.commandPublishing() != Publishing.NOT_SPECIFIED).map(property -> {\r\n Publishing publishing = property.commandPublishing();\r\n val processorClass = property.commandDtoProcessor();\r\n val processor = newProcessorElseNull(processorClass);\r\n if (processor != null) {\r\n publishing = Publishing.ENABLED;\r\n }\r\n switch(publishing) {\r\n case AS_CONFIGURED:\r\n switch(publishingPolicy) {\r\n case NONE:\r\n return (CommandPublishingFacet) new CommandPublishingFacetForPropertyAnnotationAsConfigured.None(holder, servicesInjector);\r\n case ALL:\r\n return new CommandPublishingFacetForPropertyAnnotationAsConfigured.All(holder, servicesInjector);\r\n default:\r\n throw new IllegalStateException(String.format(\"configured property.commandpublishing policy '%s' not recognised\", publishingPolicy));\r\n }\r\n case DISABLED:\r\n return new CommandPublishingFacetForPropertyAnnotation.Disabled(processor, holder, servicesInjector);\r\n case ENABLED:\r\n return new CommandPublishingFacetForPropertyAnnotation.Enabled(processor, holder, servicesInjector);\r\n default:\r\n throw new IllegalStateException(String.format(\"@Property#commandPublishing '%s' not recognised\", publishing));\r\n }\r\n }).orElseGet(() -> {\r\n if (representsProperty(holder)) {\r\n switch(publishingPolicy) {\r\n case NONE:\r\n return new CommandPublishingFacetForPropertyFromConfiguration.None(holder, servicesInjector);\r\n case ALL:\r\n return new CommandPublishingFacetForPropertyFromConfiguration.All(holder, servicesInjector);\r\n default:\r\n throw new IllegalStateException(String.format(\"configured property.commandPublishing policy '%s' not recognised\", publishingPolicy));\r\n }\r\n } else {\r\n val actionPublishingPolicy = ActionConfigOptions.actionCommandPublishingPolicy(configuration);\r\n switch(actionPublishingPolicy) {\r\n case NONE:\r\n return new CommandPublishingFacetForActionFromConfiguration.None(holder, servicesInjector);\r\n case IGNORE_QUERY_ONLY:\r\n case IGNORE_SAFE:\r\n return CommandPublishingFacetForActionAnnotation.hasSafeSemantics(holder) ? new CommandPublishingFacetForActionFromConfiguration.IgnoreSafe(holder, servicesInjector) : new CommandPublishingFacetForActionFromConfiguration.IgnoreSafeYetNot(holder, servicesInjector);\r\n case ALL:\r\n return new CommandPublishingFacetForActionFromConfiguration.All(holder, servicesInjector);\r\n default:\r\n throw new IllegalStateException(String.format(\"configured action.commandPublishing policy '%s' not recognised\", actionPublishingPolicy));\r\n }\r\n }\r\n });\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static ColumnMappings parseColumnsMapping(String columnsMappingSpec, boolean doColumnRegexMatching, boolean hideColumnPrefix) throws SerDeException{\r\n if (columnsMappingSpec == null) {\r\n throw new SerDeException(\"Error: hbase.columns.mapping missing for this HBase table.\");\r\n }\r\n if (columnsMappingSpec.isEmpty() || columnsMappingSpec.equals(HBASE_KEY_COL)) {\r\n throw new SerDeException(\"Error: hbase.columns.mapping specifies only the HBase table\" + \" row key. A valid Hive-HBase table must specify at least one additional column.\");\r\n }\r\n int rowKeyIndex = -1;\r\n int timestampIndex = -1;\r\n List columnsMapping = new ArrayList();\r\n String[] columnSpecs = columnsMappingSpec.split(\",\");\r\n for (int i = 0; i < columnSpecs.length; i++) {\r\n String mappingSpec = columnSpecs[i].trim();\r\n String[] mapInfo = mappingSpec.split(\"#\");\r\n String colInfo = mapInfo[0];\r\n int idxFirst = colInfo.indexOf(\":\");\r\n int idxLast = colInfo.lastIndexOf(\":\");\r\n if (idxFirst < 0 || !(idxFirst == idxLast)) {\r\n throw new SerDeException(\"Error: the HBase columns mapping contains a badly formed \" + \"column family, column qualifier specification.\");\r\n }\r\n ColumnMapping columnMapping = new ColumnMapping();\r\n if (colInfo.equals(HBASE_KEY_COL)) {\r\n rowKeyIndex = i;\r\n columnMapping.familyName = colInfo;\r\n columnMapping.familyNameBytes = Bytes.toBytes(colInfo);\r\n columnMapping.qualifierName = null;\r\n columnMapping.qualifierNameBytes = null;\r\n columnMapping.hbaseRowKey = true;\r\n } else if (colInfo.equals(HBASE_TIMESTAMP_COL)) {\r\n timestampIndex = i;\r\n columnMapping.familyName = colInfo;\r\n columnMapping.familyNameBytes = Bytes.toBytes(colInfo);\r\n columnMapping.qualifierName = null;\r\n columnMapping.qualifierNameBytes = null;\r\n columnMapping.hbaseTimestamp = true;\r\n } else {\r\n String[] parts = colInfo.split(\":\");\r\n assert (parts.length > 0 && parts.length <= 2);\r\n columnMapping.familyName = parts[0];\r\n columnMapping.familyNameBytes = Bytes.toBytes(parts[0]);\r\n columnMapping.hbaseRowKey = false;\r\n columnMapping.hbaseTimestamp = false;\r\n if (parts.length == 2) {\r\n if (doColumnRegexMatching && parts[1].endsWith(\".*\")) {\r\n columnMapping.qualifierPrefix = parts[1].substring(0, parts[1].length() - 2);\r\n columnMapping.qualifierPrefixBytes = Bytes.toBytes(columnMapping.qualifierPrefix);\r\n columnMapping.doPrefixCut = hideColumnPrefix;\r\n columnMapping.qualifierName = null;\r\n columnMapping.qualifierNameBytes = null;\r\n } else {\r\n columnMapping.qualifierName = parts[1];\r\n columnMapping.qualifierNameBytes = Bytes.toBytes(parts[1]);\r\n columnMapping.doPrefixCut = false;\r\n }\r\n } else {\r\n columnMapping.qualifierName = null;\r\n columnMapping.qualifierNameBytes = null;\r\n }\r\n }\r\n columnMapping.mappingSpec = mappingSpec;\r\n columnsMapping.add(columnMapping);\r\n }\r\n if (rowKeyIndex == -1) {\r\n rowKeyIndex = 0;\r\n ColumnMapping columnMapping = new ColumnMapping();\r\n columnMapping.familyName = HBaseSerDe.HBASE_KEY_COL;\r\n columnMapping.familyNameBytes = Bytes.toBytes(HBaseSerDe.HBASE_KEY_COL);\r\n columnMapping.qualifierName = null;\r\n columnMapping.qualifierNameBytes = null;\r\n columnMapping.hbaseRowKey = true;\r\n columnMapping.mappingSpec = HBaseSerDe.HBASE_KEY_COL;\r\n columnsMapping.add(0, columnMapping);\r\n }\r\n return new ColumnMappings(columnsMapping, rowKeyIndex, timestampIndex);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List resolveAndValidateFields(List userFields, Map options, NodeEngine nodeEngine){\r\n final InternalSerializationService ss = (InternalSerializationService) nodeEngine.getSerializationService();\r\n final RelationsStorage relationsStorage = ((SqlServiceImpl) nodeEngine.getSqlService()).getOptimizer().relationsStorage();\r\n for (MappingField field : userFields) {\r\n String name = field.name();\r\n String externalName = field.externalName();\r\n if (externalName == null) {\r\n if (name.equals(KEY) || name.equals(VALUE)) {\r\n externalName = name;\r\n } else {\r\n externalName = VALUE_PREFIX + name;\r\n }\r\n field.setExternalName(name);\r\n }\r\n if ((name.equals(KEY) && !externalName.equals(KEY)) || (name.equals(VALUE) && !externalName.equals(VALUE))) {\r\n throw QueryException.error(\"Cannot rename field: '\" + name + '\\'');\r\n }\r\n if (!EXT_NAME_PATTERN.matcher(externalName).matches()) {\r\n throw QueryException.error(\"Invalid external name: \" + externalName);\r\n }\r\n }\r\n Stream keyFields = findMetadataResolver(options, true).resolveAndValidateFields(true, userFields, options, ss).filter(field -> !field.name().equals(KEY) || field.externalName().equals(KEY));\r\n Stream valueFields = findMetadataResolver(options, false).resolveAndValidateFields(false, userFields, options, ss).filter(field -> !field.name().equals(VALUE) || field.externalName().equals(VALUE));\r\n final TypeKind keyKind = TypesUtils.formatToTypeKind(getFormat(options, true));\r\n if (NESTED_FIELDS_SUPPORTED_FORMATS.contains(keyKind)) {\r\n keyFields = keyFields.peek(mappingField -> TypesUtils.enrichMappingFieldType(keyKind, mappingField, relationsStorage));\r\n }\r\n final TypeKind valueKind = TypesUtils.formatToTypeKind(getFormat(options, false));\r\n if (NESTED_FIELDS_SUPPORTED_FORMATS.contains(valueKind)) {\r\n valueFields = valueFields.peek(mappingField -> TypesUtils.enrichMappingFieldType(valueKind, mappingField, relationsStorage));\r\n }\r\n Map fields = concat(keyFields, valueFields).collect(LinkedHashMap::new, (map, field) -> map.putIfAbsent(field.name(), field), Map::putAll);\r\n if (fields.isEmpty()) {\r\n throw QueryException.error(\"The resolved field list is empty\");\r\n }\r\n return new ArrayList<>(fields.values());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public List dealWithConsumeAllChildrenPipelineBreaker(PlanNode node, LocalExecutionPlanContext context){\r\n List parentPipelineChildren = new ArrayList<>();\r\n int finalExchangeNum = context.getExchangeSumNum();\r\n if (context.getDegreeOfParallelism() == 1 || node.getChildren().size() == 1) {\r\n for (PlanNode localChild : node.getChildren()) {\r\n Operator childOperation = localChild.accept(this, context);\r\n parentPipelineChildren.add(childOperation);\r\n }\r\n } else {\r\n List afterwardsNodes = new ArrayList<>();\r\n int localChildrenSize = 0;\r\n int firstChildIndex = -1;\r\n for (int i = 0; i < node.getChildren().size(); i++) {\r\n if (!(node.getChildren().get(i) instanceof ExchangeNode)) {\r\n localChildrenSize++;\r\n firstChildIndex = firstChildIndex == -1 ? i : firstChildIndex;\r\n } else if (firstChildIndex == -1) {\r\n Operator childOperation = node.getChildren().get(i).accept(this, context);\r\n finalExchangeNum += 1;\r\n parentPipelineChildren.add(childOperation);\r\n afterwardsNodes.add(node.getChildren().get(i));\r\n }\r\n }\r\n if (firstChildIndex == -1) {\r\n context.setExchangeSumNum(finalExchangeNum);\r\n return parentPipelineChildren;\r\n }\r\n int dopForChild = Math.max(1, context.getDegreeOfParallelism() - localChildrenSize);\r\n if (context.getDegreeOfParallelism() > localChildrenSize) {\r\n for (int i = firstChildIndex; i < node.getChildren().size(); i++) {\r\n PlanNode childNode = node.getChildren().get(i);\r\n if (childNode instanceof ExchangeNode) {\r\n Operator childOperation = childNode.accept(this, context);\r\n finalExchangeNum += 1;\r\n parentPipelineChildren.add(childOperation);\r\n } else {\r\n LocalExecutionPlanContext subContext = context.createSubContext();\r\n subContext.setDegreeOfParallelism(dopForChild);\r\n int originPipeNum = context.getPipelineNumber();\r\n Operator sourceOperator = createNewPipelineForChildNode(context, subContext, childNode);\r\n parentPipelineChildren.add(sourceOperator);\r\n dopForChild = Math.max(1, dopForChild - (subContext.getPipelineNumber() - 1 - originPipeNum));\r\n finalExchangeNum += subContext.getExchangeSumNum() - context.getExchangeSumNum() + 1;\r\n }\r\n }\r\n } else {\r\n int[] childNumInEachPipeline = getChildNumInEachPipeline(node.getChildren(), localChildrenSize, context.getDegreeOfParallelism());\r\n int childGroupNum = Math.min(context.getDegreeOfParallelism(), localChildrenSize);\r\n int startIndex;\r\n int endIndex = firstChildIndex;\r\n for (int i = 0; i < childGroupNum; i++) {\r\n startIndex = endIndex;\r\n endIndex += childNumInEachPipeline[i];\r\n if (i == 0) {\r\n for (int j = startIndex; j < endIndex; j++) {\r\n context.setDegreeOfParallelism(1);\r\n Operator childOperation = node.getChildren().get(j).accept(this, context);\r\n parentPipelineChildren.add(childOperation);\r\n afterwardsNodes.add(node.getChildren().get(j));\r\n }\r\n continue;\r\n }\r\n LocalExecutionPlanContext subContext = context.createSubContext();\r\n subContext.setDegreeOfParallelism(1);\r\n PlanNode partialParentNode;\r\n if (endIndex - startIndex == 1) {\r\n partialParentNode = node.getChildren().get(startIndex);\r\n } else {\r\n partialParentNode = node.createSubNode(i, startIndex, endIndex);\r\n }\r\n Operator sourceOperator = createNewPipelineForChildNode(context, subContext, partialParentNode);\r\n parentPipelineChildren.add(sourceOperator);\r\n afterwardsNodes.add(partialParentNode);\r\n finalExchangeNum += subContext.getExchangeSumNum() - context.getExchangeSumNum() + 1;\r\n }\r\n ((MultiChildProcessNode) node).setChildren(afterwardsNodes);\r\n }\r\n }\r\n context.setExchangeSumNum(finalExchangeNum);\r\n return parentPipelineChildren;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RelBuilder aggregate_(GroupKeyImpl groupKey, final ImmutableList aggCalls){\r\n if (groupKey.nodes.isEmpty() && aggCalls.isEmpty() && config.pruneInputOfAggregate()) {\r\n if (config.preventEmptyFieldList()) {\r\n return values(new String[] { \"dummy\" }, true);\r\n } else {\r\n return values(ImmutableList.of(ImmutableList.of()), getTypeFactory().builder().build());\r\n }\r\n }\r\n final Registrar registrar = new Registrar(fields(), peek().getRowType().getFieldNames());\r\n final ImmutableBitSet groupSet = ImmutableBitSet.of(registrar.registerExpressions(groupKey.nodes));\r\n if (alreadyUnique(aggCalls, groupKey, groupSet, registrar.extraNodes)) {\r\n final List nodes = new ArrayList<>(fields(groupSet));\r\n aggCalls.forEach(c -> {\r\n final AggregateCall call = c.aggregateCall();\r\n final SqlStaticAggFunction staticFun = call.getAggregation().unwrapOrThrow(SqlStaticAggFunction.class);\r\n final RexNode node = staticFun.constant(getRexBuilder(), groupSet, ImmutableList.of(), call);\r\n nodes.add(aliasMaybe(requireNonNull(node, \"node\"), call.getName()));\r\n });\r\n return project(nodes);\r\n }\r\n ImmutableList groupSets;\r\n if (groupKey.nodeLists != null) {\r\n final int sizeBefore = registrar.extraNodes.size();\r\n final List groupSetList = new ArrayList<>();\r\n for (ImmutableList nodeList : groupKey.nodeLists) {\r\n final ImmutableBitSet groupSet2 = ImmutableBitSet.of(registrar.registerExpressions(nodeList));\r\n if (!groupSet.contains(groupSet2)) {\r\n throw new IllegalArgumentException(\"group set element \" + nodeList + \" must be a subset of group key\");\r\n }\r\n groupSetList.add(groupSet2);\r\n }\r\n final ImmutableSortedMultiset groupSetMultiset = ImmutableSortedMultiset.copyOf(ImmutableBitSet.COMPARATOR, groupSetList);\r\n if (aggCalls.stream().anyMatch(RelBuilder::isGroupId) || !ImmutableBitSet.ORDERING.isStrictlyOrdered(groupSetMultiset)) {\r\n return rewriteAggregateWithDuplicateGroupSets(groupSet, groupSetMultiset, aggCalls);\r\n }\r\n groupSets = ImmutableList.copyOf(groupSetMultiset.elementSet());\r\n if (registrar.extraNodes.size() > sizeBefore) {\r\n throw new IllegalArgumentException(\"group sets contained expressions \" + \"not in group key: \" + Util.skip(registrar.extraNodes, sizeBefore));\r\n }\r\n } else {\r\n groupSets = ImmutableList.of(groupSet);\r\n }\r\n aggCalls.forEach(aggCall -> aggCall.register(registrar));\r\n project(registrar.extraNodes);\r\n rename(registrar.names);\r\n final Frame frame = stack.pop();\r\n RelNode r = frame.rel;\r\n final List aggregateCalls = new ArrayList<>();\r\n for (AggCallPlus aggCall : aggCalls) {\r\n aggregateCalls.add(aggCall.aggregateCall(registrar, groupSet, r));\r\n }\r\n assert ImmutableBitSet.ORDERING.isStrictlyOrdered(groupSets) : groupSets;\r\n for (ImmutableBitSet set : groupSets) {\r\n assert groupSet.contains(set);\r\n }\r\n List inFields = frame.fields;\r\n final ImmutableBitSet groupSet2;\r\n final ImmutableList groupSets2;\r\n if (config.pruneInputOfAggregate() && r instanceof Project) {\r\n final Set fieldsUsed = RelOptUtil.getAllFields2(groupSet, aggregateCalls);\r\n if (fieldsUsed.isEmpty()) {\r\n r = ((Project) r).getInput();\r\n groupSet2 = groupSet;\r\n groupSets2 = groupSets;\r\n } else if (fieldsUsed.size() < r.getRowType().getFieldCount()) {\r\n final Map map = new HashMap<>();\r\n for (int source : fieldsUsed) {\r\n map.put(source, map.size());\r\n }\r\n groupSet2 = groupSet.permute(map);\r\n groupSets2 = ImmutableBitSet.ORDERING.immutableSortedCopy(ImmutableBitSet.permute(groupSets, map));\r\n final Mappings.TargetMapping targetMapping = Mappings.target(map, r.getRowType().getFieldCount(), fieldsUsed.size());\r\n final List oldAggregateCalls = new ArrayList<>(aggregateCalls);\r\n aggregateCalls.clear();\r\n for (AggregateCall aggregateCall : oldAggregateCalls) {\r\n aggregateCalls.add(aggregateCall.transform(targetMapping));\r\n }\r\n inFields = Mappings.permute(inFields, targetMapping.inverse());\r\n final Project project = (Project) r;\r\n final List newProjects = new ArrayList<>();\r\n final RelDataTypeFactory.Builder builder = cluster.getTypeFactory().builder();\r\n for (int i : fieldsUsed) {\r\n newProjects.add(project.getProjects().get(i));\r\n builder.add(project.getRowType().getFieldList().get(i));\r\n }\r\n r = project.copy(cluster.traitSet(), project.getInput(), newProjects, builder.build());\r\n } else {\r\n groupSet2 = groupSet;\r\n groupSets2 = groupSets;\r\n }\r\n } else {\r\n groupSet2 = groupSet;\r\n groupSets2 = groupSets;\r\n }\r\n if (!config.dedupAggregateCalls() || Util.isDistinct(aggregateCalls)) {\r\n return aggregate_(groupSet2, groupSets2, r, aggregateCalls, registrar.extraNodes, inFields);\r\n }\r\n final Set callSet = new HashSet<>();\r\n final PairList projects = PairList.of();\r\n Util.range(groupSet.cardinality()).forEach(i -> projects.add(i, null));\r\n final List distinctAggregateCalls = new ArrayList<>();\r\n for (AggregateCall aggregateCall : aggregateCalls) {\r\n final int i;\r\n if (callSet.add(aggregateCall)) {\r\n i = distinctAggregateCalls.size();\r\n distinctAggregateCalls.add(aggregateCall);\r\n } else {\r\n i = distinctAggregateCalls.indexOf(aggregateCall);\r\n assert i >= 0;\r\n }\r\n projects.add(groupSet.cardinality() + i, aggregateCall.name);\r\n }\r\n aggregate_(groupSet, groupSets, r, distinctAggregateCalls, registrar.extraNodes, inFields);\r\n return project(projects.transform((i, name) -> aliasMaybe(field(i), name)));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static XpathAnalysis analyze(String xpath){\r\n List parts = new ArrayList<>();\r\n boolean lazyPath = false;\r\n int i = 0;\r\n if (xpath.length() >= 1 && xpath.charAt(0) == '/') {\r\n i = 1;\r\n } else if (xpath.length() >= 2 && xpath.charAt(0) == '?' && xpath.charAt(1) == '/') {\r\n lazyPath = true;\r\n i = 2;\r\n } else {\r\n return new XpathAnalysis(parts, \"An oopath expression has to start with '/' or '?/'\");\r\n }\r\n List constraints = new ArrayList<>();\r\n String inlineCast = null;\r\n int index = -1;\r\n int lastStart = i;\r\n int nestedParam = 0;\r\n int nestedSquare = 0;\r\n boolean iterate = true;\r\n boolean isQuoted = false;\r\n boolean isDoubleQuoted = false;\r\n boolean isInlineCast = false;\r\n String field = null;\r\n String error = null;\r\n int partStart = 0;\r\n for (; i < xpath.length() && error == null; i++) {\r\n switch(xpath.charAt(i)) {\r\n case '/':\r\n case '.':\r\n if (!isQuoted && nestedParam == 0 && nestedSquare == 0) {\r\n if (field == null) {\r\n field = xpath.substring(lastStart, xpath.charAt(i - 1) == '?' ? i - 1 : i).trim();\r\n } else if (isInlineCast) {\r\n inlineCast = xpath.substring(lastStart, xpath.charAt(i - 1) == '?' ? i - 1 : i).trim();\r\n isInlineCast = false;\r\n }\r\n parts.add(new XpathPart(field, iterate, lazyPath, constraints, inlineCast, index, partStart));\r\n partStart = i;\r\n iterate = xpath.charAt(i) == '/';\r\n if (xpath.charAt(i - 1) == '?') {\r\n if (lazyPath) {\r\n error = \"It is not possible to have 2 non-reactive parts in the same oopath\";\r\n break;\r\n } else {\r\n lazyPath = true;\r\n }\r\n }\r\n constraints = new ArrayList<>();\r\n inlineCast = null;\r\n index = -1;\r\n lastStart = i + 1;\r\n field = null;\r\n }\r\n break;\r\n case '(':\r\n if (!isQuoted) {\r\n nestedParam++;\r\n }\r\n break;\r\n case ')':\r\n if (!isQuoted) {\r\n nestedParam--;\r\n if (nestedParam < 0) {\r\n error = \"Unbalanced parenthesis\";\r\n }\r\n }\r\n break;\r\n case '#':\r\n if (!isQuoted && nestedParam == 0 && nestedSquare == 0) {\r\n if (field == null) {\r\n field = xpath.substring(lastStart, i).trim();\r\n }\r\n lastStart = i + 1;\r\n isInlineCast = true;\r\n }\r\n break;\r\n case '[':\r\n if (!isQuoted && nestedParam == 0) {\r\n if (nestedSquare == 0) {\r\n if (field == null) {\r\n field = xpath.substring(lastStart, i).trim();\r\n } else if (isInlineCast) {\r\n inlineCast = xpath.substring(lastStart, i).trim();\r\n isInlineCast = false;\r\n }\r\n lastStart = i + 1;\r\n }\r\n nestedSquare++;\r\n }\r\n break;\r\n case ']':\r\n if (!isQuoted && nestedParam == 0) {\r\n nestedSquare--;\r\n if (nestedSquare == 0) {\r\n String constraint = xpath.substring(lastStart, i).trim();\r\n if (Character.isDigit(constraint.charAt(0))) {\r\n try {\r\n index = Integer.parseInt(constraint);\r\n } catch (Exception e) {\r\n constraints.add(constraint);\r\n }\r\n } else {\r\n constraints.add(constraint);\r\n }\r\n } else if (nestedSquare < 0) {\r\n error = \"Unbalanced square brackets\";\r\n }\r\n }\r\n break;\r\n case ',':\r\n if (!isQuoted && nestedParam == 0 && nestedSquare == 1) {\r\n String constraint = xpath.substring(lastStart, i).trim();\r\n constraints.add(constraint);\r\n lastStart = i + 1;\r\n }\r\n break;\r\n case '\"':\r\n if (isQuoted) {\r\n if (isDoubleQuoted) {\r\n isQuoted = false;\r\n isDoubleQuoted = false;\r\n }\r\n } else {\r\n isQuoted = true;\r\n isDoubleQuoted = true;\r\n }\r\n break;\r\n case '\\'':\r\n if (isQuoted) {\r\n if (!isDoubleQuoted) {\r\n isQuoted = false;\r\n }\r\n } else {\r\n isQuoted = true;\r\n }\r\n break;\r\n }\r\n }\r\n if (field == null) {\r\n field = xpath.substring(lastStart).trim();\r\n } else if (isInlineCast) {\r\n inlineCast = xpath.substring(lastStart).trim();\r\n isInlineCast = false;\r\n }\r\n parts.add(new XpathPart(field, iterate, lazyPath, constraints, inlineCast, index, partStart));\r\n return new XpathAnalysis(parts, error);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private List doImport(List files){\r\n List imports = new ArrayList<>();\r\n ImportFormatReader importFormatReader = new ImportFormatReader(preferencesService.getImporterPreferences(), preferencesService.getImportFormatPreferences(), fileUpdateMonitor);\r\n for (Path filename : files) {\r\n try {\r\n if (importer.isEmpty()) {\r\n DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {\r\n if (fileIsPdf(filename) && GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences())) {\r\n importFormatReader.reset();\r\n }\r\n frame.getDialogService().notify(Localization.lang(\"Importing in unknown format\") + \"...\");\r\n });\r\n imports.add(importFormatReader.importUnknownFormat(filename, fileUpdateMonitor));\r\n } else {\r\n DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {\r\n if (((importer.get() instanceof PdfGrobidImporter) || (importer.get() instanceof PdfMergeMetadataImporter)) && GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences())) {\r\n importFormatReader.reset();\r\n }\r\n frame.getDialogService().notify(Localization.lang(\"Importing in %0 format\", importer.get().getName()) + \"...\");\r\n });\r\n ParserResult pr = importer.get().importDatabase(filename);\r\n imports.add(new ImportFormatReader.UnknownFormatImport(importer.get().getName(), pr));\r\n }\r\n } catch (ImportException | IOException e) {\r\n importError = e;\r\n }\r\n }\r\n return imports;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public boolean isActive() throws Exception{\r\n if (resolvesTo.isEmpty()) {\r\n try {\r\n resolvesTo.addAll(getLocalIps());\r\n } catch (Exception e) {\r\n LOG.warn(\"Failed to get local ips and resolvesTo not specified. Identifying as inactive.\", e);\r\n throw e;\r\n }\r\n }\r\n LOG.debug(\"Resolving {}\", hostname);\r\n List hostnames = new ArrayList<>();\r\n hostnames.add(hostname);\r\n List resolved = new ArrayList<>();\r\n while (!hostnames.isEmpty()) {\r\n NamingEnumeration attributeEnumeration = null;\r\n try {\r\n String hostname = hostnames.remove(0);\r\n InetAddress inetAddress = InetAddress.getByName(hostname);\r\n InitialDirContext initialDirContext = new InitialDirContext();\r\n Attributes attributes = initialDirContext.getAttributes(\"dns:/\" + inetAddress.getHostName(), DNS_TYPES);\r\n attributeEnumeration = attributes.getAll();\r\n while (attributeEnumeration.hasMore()) {\r\n Attribute attribute = (Attribute) attributeEnumeration.next();\r\n String id = attribute.getID();\r\n String value = (String) attribute.get();\r\n if (resolvesTo.contains(value)) {\r\n LOG.debug(\"{} = {} matched. Identifying as active.\", id, value);\r\n return true;\r\n }\r\n LOG.debug(\"{} = {}\", id, value);\r\n if (id.equals(\"CNAME\") && !resolved.contains(value)) {\r\n hostnames.add(value);\r\n }\r\n resolved.add(value);\r\n }\r\n } catch (Exception e) {\r\n LOG.warn(hostname, e);\r\n throw e;\r\n } finally {\r\n if (attributeEnumeration != null) {\r\n try {\r\n attributeEnumeration.close();\r\n } catch (Exception e) {\r\n LOG.warn(\"Failed to close attributeEnumeration. Memory leak possible.\", e);\r\n }\r\n attributeEnumeration = null;\r\n }\r\n }\r\n }\r\n return false;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void deferLedgerLockRelease(final long ledgerId){\r\n long gracePeriod = this.openLedgerRereplicationGracePeriod;\r\n TimerTask timerTask = new TimerTask() {\r\n\r\n @Override\r\n public void run() {\r\n boolean isRecoveryOpen = false;\r\n LedgerHandle lh = null;\r\n try {\r\n lh = admin.openLedgerNoRecovery(ledgerId);\r\n if (isLastSegmentOpenAndMissingBookies(lh)) {\r\n lh.close();\r\n LOG.warn(\"Missing bookie(s) from last segment. Opening Ledger{} for Recovery.\", ledgerId);\r\n lh = admin.openLedger(ledgerId);\r\n isRecoveryOpen = true;\r\n }\r\n if (!isRecoveryOpen) {\r\n Set fragments = getUnderreplicatedFragments(lh, conf.getAuditorLedgerVerificationPercentage());\r\n for (LedgerFragment fragment : fragments) {\r\n if (!fragment.isClosed()) {\r\n lh.close();\r\n LOG.warn(\"Open Fragment{}. Opening Ledger{} for Recovery.\", fragment.getEnsemble(), ledgerId);\r\n lh = admin.openLedger(ledgerId);\r\n isRecoveryOpen = true;\r\n break;\r\n }\r\n }\r\n }\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n LOG.info(\"InterruptedException while fencing the ledger {}\" + \" for rereplication of postponed ledgers\", ledgerId, e);\r\n } catch (BKNoSuchLedgerExistsOnMetadataServerException bknsle) {\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Ledger {} was deleted, safe to continue\", ledgerId, bknsle);\r\n }\r\n } catch (BKException e) {\r\n LOG.error(\"BKException while fencing the ledger {}\" + \" for rereplication of postponed ledgers\", ledgerId, e);\r\n } finally {\r\n try {\r\n if (lh != null) {\r\n lh.close();\r\n }\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n LOG.info(\"InterruptedException while closing ledger {}\", ledgerId, e);\r\n } catch (BKException e) {\r\n LOG.warn(\"BKException while closing ledger {} \", ledgerId, e);\r\n } finally {\r\n try {\r\n underreplicationManager.releaseUnderreplicatedLedger(ledgerId);\r\n } catch (UnavailableException e) {\r\n LOG.error(\"UnavailableException while replicating fragments of ledger {}\", ledgerId, e);\r\n shutdown();\r\n }\r\n }\r\n }\r\n }\r\n };\r\n scheduleTaskWithDelay(timerTask, gracePeriod);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void checkFailure(org.apache.camel.Exchange camelExchange, Exchange cxfExchange) throws Fault{\r\n Throwable t = camelExchange.getException();\r\n if (t == null) {\r\n Object body = camelExchange.getMessage().getBody();\r\n if (body instanceof Throwable) {\r\n t = (Throwable) body;\r\n }\r\n }\r\n if (t != null) {\r\n cxfExchange.getInMessage().put(FaultMode.class, FaultMode.UNCHECKED_APPLICATION_FAULT);\r\n if (t instanceof Fault) {\r\n cxfExchange.getInMessage().put(FaultMode.class, FaultMode.CHECKED_APPLICATION_FAULT);\r\n throw (Fault) t;\r\n } else {\r\n Fault fault = new Fault(t);\r\n if (fault.getMessage() == null) {\r\n fault.setMessage(t.getClass().getSimpleName());\r\n }\r\n WebFault faultAnnotation = t.getClass().getAnnotation(WebFault.class);\r\n Object faultInfo = null;\r\n try {\r\n Method method = t.getClass().getMethod(\"getFaultInfo\");\r\n faultInfo = method.invoke(t, new Object[0]);\r\n } catch (Exception e) {\r\n }\r\n if (faultAnnotation != null && faultInfo == null) {\r\n Element detail = fault.getOrCreateDetail();\r\n Element faultDetails = detail.getOwnerDocument().createElementNS(faultAnnotation.targetNamespace(), faultAnnotation.name());\r\n detail.appendChild(faultDetails);\r\n }\r\n throw fault;\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected int drawScale(Graphics2D g2D, int y){\r\n Rectangle drawHere = g2D.getClipBounds();\r\n g2D.setColor(SCALE_COLOR);\r\n int aminosize = Math.round(1 * scale);\r\n if (aminosize < 1)\r\n aminosize = 1;\r\n int startpos = coordManager.getSeqPos(drawHere.x);\r\n int endpos = coordManager.getSeqPos(drawHere.x + drawHere.width);\r\n if (endpos > apos.size())\r\n endpos = apos.size();\r\n int l = endpos - startpos + 1;\r\n int drawStart = coordManager.getPanelPos(startpos);\r\n int drawEnd = coordManager.getPanelPos(l) - DEFAULT_X_START + aminosize;\r\n if (scale < SEQUENCE_SHOW) {\r\n g2D.setColor(SEQUENCE_COLOR);\r\n Rectangle seqline = new Rectangle(drawStart, y, drawEnd, LINE_HEIGHT);\r\n g2D.fill(seqline);\r\n }\r\n g2D.setColor(SCALE_COLOR);\r\n Rectangle baseline = new Rectangle(drawStart, y, drawEnd, 2);\r\n g2D.fill(baseline);\r\n int lineH = 11;\r\n if (scale <= 3)\r\n lineH = 8;\r\n for (int gap = startpos; ((gap <= endpos) && (gap < apos.size())); gap++) {\r\n int xpos = coordManager.getPanelPos(gap);\r\n AlignedPosition m = apos.get(gap);\r\n if (m.getPos(position) == -1) {\r\n g2D.setColor(GAP_COLOR);\r\n g2D.fillRect(xpos, y + 2, aminosize + 1, y + lineH);\r\n g2D.setColor(GAP_COLOR);\r\n continue;\r\n }\r\n int i = m.getPos(position);\r\n if (((i + 1) % 100) == 0) {\r\n if (scale > 0.1) {\r\n g2D.setColor(TEXT_SCALE_COLOR);\r\n g2D.fillRect(xpos, y + 2, aminosize, y + lineH);\r\n g2D.setColor(SCALE_COLOR);\r\n if (scale < SEQUENCE_SHOW)\r\n g2D.drawString(String.valueOf(i + 1), xpos, y + DEFAULT_Y_STEP);\r\n }\r\n } else if (((i + 1) % 50) == 0) {\r\n if (scale > 1.4) {\r\n g2D.setColor(TEXT_SCALE_COLOR);\r\n g2D.fillRect(xpos, y + 2, aminosize, y + lineH);\r\n g2D.setColor(SCALE_COLOR);\r\n if (scale < SEQUENCE_SHOW)\r\n g2D.drawString(String.valueOf(i + 1), xpos, y + DEFAULT_Y_STEP);\r\n }\r\n } else if (((i + 1) % 10) == 0) {\r\n if (scale > 3) {\r\n g2D.setColor(TEXT_SCALE_COLOR);\r\n g2D.fillRect(xpos, y + 2, aminosize, y + lineH);\r\n g2D.setColor(SCALE_COLOR);\r\n if (scale < SEQUENCE_SHOW)\r\n g2D.drawString(String.valueOf(i + 1), xpos, y + DEFAULT_Y_STEP);\r\n }\r\n }\r\n }\r\n int length = chainLength;\r\n if (endpos >= length - 1) {\r\n int endPanel = coordManager.getPanelPos(endpos);\r\n g2D.drawString(String.valueOf(length), endPanel + 10, y + DEFAULT_Y_STEP);\r\n }\r\n return y;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void readBeliefSet(MarshallerReaderContext context, TruthMaintenanceSystem tms, ProtobufMessages.EqualityKey _key) throws IOException, ClassNotFoundException{\r\n if (_key.hasBeliefSet()) {\r\n ProtobufMessages.BeliefSet _beliefSet = _key.getBeliefSet();\r\n InternalFactHandle handle = (InternalFactHandle) context.getHandles().get(_key.getHandleId());\r\n if (_beliefSet.getLogicalDependencyCount() > 0) {\r\n for (ProtobufMessages.LogicalDependency _logicalDependency : _beliefSet.getLogicalDependencyList()) {\r\n ProtobufMessages.Activation _activation = _logicalDependency.getActivation();\r\n ActivationKey activationKey = getActivationKey(context, _activation);\r\n InternalMatch internalMatch = (InternalMatch) ((PBActivationsFilter) context.getFilter()).getTuplesCache().get(activationKey);\r\n Object object = null;\r\n ObjectMarshallingStrategy strategy = null;\r\n if (_logicalDependency.hasObjectStrategyIndex()) {\r\n strategy = context.getUsedStrategies().get(_logicalDependency.getObjectStrategyIndex());\r\n object = strategy.unmarshal(context.getStrategyContexts().get(strategy), (ObjectInputStream) context, _logicalDependency.getObject().toByteArray(), (context.getKnowledgeBase() == null) ? null : context.getKnowledgeBase().getRootClassLoader());\r\n }\r\n Object value = null;\r\n if (_logicalDependency.hasValueStrategyIndex()) {\r\n strategy = context.getUsedStrategies().get(_logicalDependency.getValueStrategyIndex());\r\n value = strategy.unmarshal(context.getStrategyContexts().get(strategy), (ObjectInputStream) context, _logicalDependency.getValue().toByteArray(), (context.getKnowledgeBase() == null) ? null : context.getKnowledgeBase().getRootClassLoader());\r\n }\r\n ObjectTypeConf typeConf = context.getWorkingMemory().getObjectTypeConfigurationRegistry().getOrCreateObjectTypeConf(handle.getEntryPointId(), handle.getObject());\r\n tms.readLogicalDependency(handle, object, value, internalMatch, typeConf);\r\n }\r\n } else {\r\n ((TruthMaintenanceSystemEqualityKey) handle.getEqualityKey()).setBeliefSet(((TruthMaintenanceSystemImpl) tms).getBeliefSystem().newBeliefSet(handle));\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private boolean updatePartitionsAndFinalizeMigrations(InternalPartition[] partitions, Collection completedMigrations, Address sender){\r\n boolean applied = false;\r\n boolean accepted = false;\r\n for (int partitionId = 0; partitionId < partitionCount; partitionId++) {\r\n InternalPartition newPartition = partitions[partitionId];\r\n InternalPartitionImpl currentPartition = partitionStateManager.getPartitionImpl(partitionId);\r\n int currentVersion = currentPartition.version();\r\n int newVersion = newPartition.version();\r\n if (newVersion < currentVersion) {\r\n if (logger.isFinestEnabled()) {\r\n logger.finest(\"Already applied partition update. partitionId=\" + partitionId + \", local version: \" + currentVersion + \", master version: \" + newVersion + \", master: \" + sender);\r\n }\r\n continue;\r\n } else if (newVersion == currentVersion) {\r\n if (!currentPartition.equals(newPartition)) {\r\n throw new IllegalStateException(\"Partition updates are diverged! Local: \" + currentPartition + \", Received: \" + newPartition);\r\n }\r\n if (logger.isFinestEnabled()) {\r\n logger.finest(\"Already applied partition update. partitionId=\" + partitionId + \", version: \" + currentVersion + \", master: \" + sender);\r\n }\r\n accepted = true;\r\n continue;\r\n }\r\n applied = true;\r\n accepted = true;\r\n currentPartition.setReplicasAndVersion(newPartition);\r\n }\r\n for (MigrationInfo migration : completedMigrations) {\r\n boolean added = migrationManager.addCompletedMigration(migration);\r\n if (added) {\r\n migrationManager.scheduleActiveMigrationFinalization(migration);\r\n }\r\n }\r\n partitionStateManager.updateStamp();\r\n if (logger.isFineEnabled()) {\r\n if (applied) {\r\n logger.fine(\"Applied partition state update with stamp: \" + calculateStamp(partitions) + \", Local stamp is: \" + partitionStateManager.getStamp());\r\n } else {\r\n logger.fine(\"Already applied partition state update with stamp: \" + calculateStamp(partitions) + \", Local stamp is: \" + partitionStateManager.getStamp());\r\n }\r\n }\r\n migrationManager.retainCompletedMigrations(completedMigrations);\r\n if (!partitionStateManager.setInitialized()) {\r\n node.getNodeExtension().onPartitionStateChange();\r\n }\r\n return accepted;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " EntryLogMetadata extractEntryLogMetadataFromIndex(long entryLogId) throws IOException{\r\n Header header = getHeaderForLogId(entryLogId);\r\n if (header.version < HEADER_V1) {\r\n throw new IOException(\"Old log file header without ledgers map on entryLogId \" + entryLogId);\r\n }\r\n if (header.ledgersMapOffset == 0L) {\r\n throw new IOException(\"No ledgers map index found on entryLogId \" + entryLogId);\r\n }\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Recovering ledgers maps for log {} at offset: {}\", entryLogId, header.ledgersMapOffset);\r\n }\r\n BufferedReadChannel bc = getChannelForLogId(entryLogId);\r\n long offset = header.ledgersMapOffset;\r\n EntryLogMetadata meta = new EntryLogMetadata(entryLogId);\r\n final int maxMapSize = LEDGERS_MAP_HEADER_SIZE + LEDGERS_MAP_ENTRY_SIZE * LEDGERS_MAP_MAX_BATCH_SIZE;\r\n ByteBuf ledgersMap = allocator.directBuffer(maxMapSize);\r\n try {\r\n while (offset < bc.size()) {\r\n sizeBuffer.get().clear();\r\n bc.read(sizeBuffer.get(), offset);\r\n int ledgersMapSize = sizeBuffer.get().readInt();\r\n ledgersMap.clear();\r\n bc.read(ledgersMap, offset + 4, ledgersMapSize);\r\n long lid = ledgersMap.readLong();\r\n if (lid != INVALID_LID) {\r\n throw new IOException(\"Cannot deserialize ledgers map from ledger \" + lid);\r\n }\r\n long entryId = ledgersMap.readLong();\r\n if (entryId != LEDGERS_MAP_ENTRY_ID) {\r\n throw new IOException(\"Cannot deserialize ledgers map from entryId \" + entryId);\r\n }\r\n int ledgersCount = ledgersMap.readInt();\r\n for (int i = 0; i < ledgersCount; i++) {\r\n long ledgerId = ledgersMap.readLong();\r\n long size = ledgersMap.readLong();\r\n if (LOG.isDebugEnabled()) {\r\n LOG.debug(\"Recovering ledgers maps for log {} -- Found ledger: {} with size: {}\", entryLogId, ledgerId, size);\r\n }\r\n meta.addLedgerSize(ledgerId, size);\r\n }\r\n if (ledgersMap.isReadable()) {\r\n throw new IOException(\"Invalid entry size when reading ledgers map\");\r\n }\r\n offset += ledgersMapSize + 4;\r\n }\r\n } catch (IndexOutOfBoundsException e) {\r\n throw new IOException(e);\r\n } finally {\r\n ledgersMap.release();\r\n }\r\n if (meta.getLedgersMap().size() != header.ledgersCount) {\r\n throw new IOException(\"Not all ledgers were found in ledgers map index. expected: \" + header.ledgersCount + \" -- found: \" + meta.getLedgersMap().size() + \" -- entryLogId: \" + entryLogId);\r\n }\r\n return meta;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void mergePackage(InternalKnowledgePackage pkg, InternalKnowledgePackage newPkg, Collection workingMemories){\r\n final Map imports = pkg.getImports();\r\n imports.putAll(newPkg.getImports());\r\n for (String staticImport : newPkg.getStaticImports()) {\r\n pkg.addStaticImport(staticImport);\r\n }\r\n if (newPkg.getGlobals() != null && !newPkg.getGlobals().isEmpty()) {\r\n Map pkgGlobals = pkg.getGlobals();\r\n for (final Map.Entry entry : newPkg.getGlobals().entrySet()) {\r\n final String identifier = entry.getKey();\r\n final Type type = entry.getValue();\r\n if (pkgGlobals.containsKey(identifier) && !pkgGlobals.get(identifier).equals(type)) {\r\n throw new RuntimeException(pkg.getName() + \" cannot be integrated\");\r\n } else {\r\n pkg.addGlobal(identifier, type);\r\n addGlobal(identifier, type);\r\n }\r\n }\r\n }\r\n if (newPkg.getEntryPointIds() != null) {\r\n for (String ep : newPkg.getEntryPointIds()) {\r\n pkg.addEntryPointId(ep);\r\n }\r\n }\r\n if (newPkg.getTypeDeclarations() != null) {\r\n for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) {\r\n if (!pkg.getTypeDeclarations().containsKey(type.getTypeName())) {\r\n pkg.addTypeDeclaration(type);\r\n }\r\n }\r\n }\r\n if (newPkg.getWindowDeclarations() != null) {\r\n for (WindowDeclaration window : newPkg.getWindowDeclarations().values()) {\r\n if (!pkg.getWindowDeclarations().containsKey(window.getName()) || pkg.getWindowDeclarations().get(window.getName()).equals(window)) {\r\n pkg.addWindowDeclaration(window);\r\n } else {\r\n throw new RuntimeException(\"Unable to merge two conflicting window declarations for window named: \" + window.getName());\r\n }\r\n }\r\n }\r\n List rulesToBeRemoved = new ArrayList<>();\r\n for (Rule newRule : newPkg.getRules()) {\r\n RuleImpl oldRule = pkg.getRule(newRule.getName());\r\n if (oldRule != null) {\r\n rulesToBeRemoved.add(oldRule);\r\n }\r\n }\r\n if (!rulesToBeRemoved.isEmpty()) {\r\n kBaseInternal_removeRules(rulesToBeRemoved, workingMemories);\r\n }\r\n for (Rule newRule : newPkg.getRules()) {\r\n pkg.addRule((RuleImpl) newRule);\r\n }\r\n if (newPkg.getRuleFlows() != null) {\r\n for (Process flow : newPkg.getRuleFlows().values()) {\r\n pkg.addProcess(flow);\r\n }\r\n }\r\n if (!newPkg.getResourceTypePackages().isEmpty()) {\r\n KieWeavers weavers = KieService.load(KieWeavers.class);\r\n if (weavers == null) {\r\n throw new IllegalStateException(\"Unable to find KieWeavers implementation\");\r\n }\r\n for (ResourceTypePackage rtkKpg : newPkg.getResourceTypePackages().values()) {\r\n weavers.merge(pkg, rtkKpg);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private RexNode convertJsonValueCall(SqlCall call, Blackboard bb){\r\n RexNode target = bb.convertExpression(call.operand(0));\r\n RexNode path = bb.convertExpression(call.operand(1));\r\n SqlJsonValueEmptyOrErrorBehavior onError = SqlJsonValueEmptyOrErrorBehavior.NULL;\r\n SqlJsonValueEmptyOrErrorBehavior onEmpty = SqlJsonValueEmptyOrErrorBehavior.NULL;\r\n RelDataType returning = validator.getTypeFactory().createSqlType(SqlTypeName.VARCHAR);\r\n RexNode defaultValueOnError = getRexBuilder().makeNullLiteral(typeFactory.createSqlType(SqlTypeName.ANY));\r\n RexNode defaultValueOnEmpty = getRexBuilder().makeNullLiteral(typeFactory.createSqlType(SqlTypeName.ANY));\r\n int tokenIndex = 2;\r\n if (call.operandCount() > 2 && isJsonValueReturningClause(call.operand(tokenIndex))) {\r\n returning = validator.getValidatedNodeType(call.operand(tokenIndex + 1));\r\n tokenIndex += 2;\r\n }\r\n boolean onEmptyDefined = false;\r\n boolean onErrorDefined = false;\r\n while (tokenIndex < call.operandCount()) {\r\n if (!(call.operand(tokenIndex) instanceof SqlLiteral)) {\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Unsupported JSON_VALUE extended syntax\");\r\n }\r\n final SqlJsonValueEmptyOrErrorBehavior behavior = (SqlJsonValueEmptyOrErrorBehavior) ((SqlLiteral) call.operand(tokenIndex)).getValue();\r\n RexNode defaultExpr = getRexBuilder().makeNullLiteral(typeFactory.createSqlType(SqlTypeName.ANY));\r\n if (behavior == null) {\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Failed to extract ON behavior for JSON_VALUE call\");\r\n }\r\n switch(behavior) {\r\n case DEFAULT:\r\n defaultExpr = bb.convertExpression(call.operand(tokenIndex + 1));\r\n tokenIndex += 2;\r\n break;\r\n case NULL:\r\n case ERROR:\r\n tokenIndex++;\r\n break;\r\n default:\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Unsupported JSON_VALUE OnEmptyOrErrorBehavior\");\r\n }\r\n final SqlJsonEmptyOrError onTarget = (SqlJsonEmptyOrError) ((SqlLiteral) call.operand(tokenIndex)).getValue();\r\n if (onTarget == null) {\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Failed to extract ON-behavior target for JSON_VALUE call\");\r\n }\r\n switch(onTarget) {\r\n case EMPTY:\r\n if (onEmptyDefined) {\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Duplicate ON EMPTY clause in JSON_VALUE call\");\r\n }\r\n if (behavior == SqlJsonValueEmptyOrErrorBehavior.DEFAULT) {\r\n defaultValueOnEmpty = defaultExpr;\r\n }\r\n onEmpty = behavior;\r\n onEmptyDefined = true;\r\n break;\r\n case ERROR:\r\n if (onErrorDefined) {\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Duplicate ON ERROR clause in JSON_VALUE call\");\r\n }\r\n if (behavior == SqlJsonValueEmptyOrErrorBehavior.DEFAULT) {\r\n defaultValueOnError = defaultExpr;\r\n }\r\n onError = behavior;\r\n onErrorDefined = true;\r\n break;\r\n default:\r\n throw QueryException.error(SqlErrorCode.PARSING, \"Unsupported JSON_VALUE EmptyOrErrorBehavior target\");\r\n }\r\n tokenIndex++;\r\n }\r\n return getRexBuilder().makeCall(returning, HazelcastJsonValueFunction.INSTANCE, asList(target, path, defaultValueOnEmpty, defaultValueOnError, bb.convertLiteral(onEmpty.symbol(SqlParserPos.ZERO)), bb.convertLiteral(onError.symbol(SqlParserPos.ZERO))));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void updateAccessKey(IamClient iamClient, Exchange exchange) throws InvalidPayloadException{\r\n if (getConfiguration().isPojoRequest()) {\r\n Object payload = exchange.getIn().getMandatoryBody();\r\n if (payload instanceof UpdateAccessKeyRequest) {\r\n UpdateAccessKeyResponse result;\r\n try {\r\n result = iamClient.updateAccessKey((UpdateAccessKeyRequest) payload);\r\n } catch (AwsServiceException ase) {\r\n LOG.trace(\"Update Access Key command returned the error code {}\", ase.awsErrorDetails().errorCode());\r\n throw ase;\r\n }\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(result);\r\n }\r\n } else {\r\n UpdateAccessKeyRequest.Builder builder = UpdateAccessKeyRequest.builder();\r\n if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID))) {\r\n String accessKeyId = exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_ID, String.class);\r\n builder.accessKeyId(accessKeyId);\r\n } else {\r\n throw new IllegalArgumentException(\"Key Id must be specified\");\r\n }\r\n if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_STATUS))) {\r\n String status = exchange.getIn().getHeader(IAM2Constants.ACCESS_KEY_STATUS, String.class);\r\n builder.status(StatusType.fromValue(status));\r\n } else {\r\n throw new IllegalArgumentException(\"Access Key status must be specified\");\r\n }\r\n if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) {\r\n String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class);\r\n builder.userName(userName);\r\n }\r\n UpdateAccessKeyResponse result;\r\n try {\r\n result = iamClient.updateAccessKey(builder.build());\r\n } catch (AwsServiceException ase) {\r\n LOG.trace(\"Update Access Key command returned the error code {}\", ase.awsErrorDetails().errorCode());\r\n throw ase;\r\n }\r\n Message message = getMessageForResponse(exchange);\r\n message.setBody(result);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static Class getEntityReference(final Class reference){\r\n return AccountPolicy.class.isAssignableFrom(reference) ? JPAAccountPolicy.class : PasswordPolicy.class.isAssignableFrom(reference) ? JPAPasswordPolicy.class : PropagationPolicy.class.isAssignableFrom(reference) ? JPAPropagationPolicy.class : PullPolicy.class.isAssignableFrom(reference) ? JPAPullPolicy.class : PushPolicy.class.isAssignableFrom(reference) ? JPAPushPolicy.class : AuthPolicy.class.isAssignableFrom(reference) ? JPAAuthPolicy.class : AccessPolicy.class.isAssignableFrom(reference) ? JPAAccessPolicy.class : AttrReleasePolicy.class.isAssignableFrom(reference) ? JPAAttrReleasePolicy.class : null;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public BaseDescr statement(PackageDescrBuilder pkg) throws RecognitionException{\r\n BaseDescr descr = null;\r\n try {\r\n if (helper.validateIdentifierKey(DroolsSoftKeywords.IMPORT)) {\r\n descr = importStatement(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.GLOBAL)) {\r\n descr = globalStatement(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.DECLARE)) {\r\n descr = declare(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.RULE)) {\r\n descr = rule(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.QUERY)) {\r\n descr = query(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateIdentifierKey(DroolsSoftKeywords.FUNCTION)) {\r\n descr = function(pkg);\r\n if (state.failed)\r\n return descr;\r\n } else if (helper.validateAttribute(1)) {\r\n descr = attribute(pkg);\r\n if (state.failed)\r\n return descr;\r\n }\r\n } catch (RecognitionException e) {\r\n helper.reportError(e);\r\n } catch (Exception e) {\r\n helper.reportError(e);\r\n }\r\n return descr;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static Addresses getPossibleSocketAddresses(int port, String scopedAddress, int portTryCount, ClientConnectionProcessListenerRunner listenerRunner){\r\n InetAddress inetAddress = null;\r\n try {\r\n inetAddress = InetAddress.getByName(scopedAddress);\r\n } catch (UnknownHostException ignored) {\r\n Logger.getLogger(AddressHelper.class).finest(\"Address not available\", ignored);\r\n }\r\n int possiblePort = port;\r\n if (possiblePort == -1) {\r\n possiblePort = INITIAL_FIRST_PORT;\r\n }\r\n LinkedList
addressList = new LinkedList
();\r\n if (inetAddress == null) {\r\n for (int i = 0; i < portTryCount; i++) {\r\n try {\r\n addressList.add(new Address(scopedAddress, possiblePort + i));\r\n } catch (UnknownHostException ignored) {\r\n listenerRunner.onHostNotFound(scopedAddress);\r\n Logger.getLogger(AddressHelper.class).finest(\"Address not available\", ignored);\r\n }\r\n }\r\n } else if (inetAddress instanceof Inet4Address) {\r\n for (int i = 0; i < portTryCount; i++) {\r\n addressList.add(new Address(scopedAddress, inetAddress, possiblePort + i));\r\n }\r\n } else if (inetAddress instanceof Inet6Address) {\r\n Collection possibleInetAddresses = getPossibleInetAddressesFor((Inet6Address) inetAddress);\r\n for (Inet6Address inet6Address : possibleInetAddresses) {\r\n for (int i = 0; i < portTryCount; i++) {\r\n addressList.add(new Address(scopedAddress, inet6Address, possiblePort + i));\r\n }\r\n }\r\n }\r\n return toAddresses(addressList);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void processElement(final DeclarationScopeResolver resolver, final Deque contextList, final RuleConditionElement element){\r\n if (element instanceof Pattern) {\r\n Pattern pattern = (Pattern) element;\r\n for (RuleConditionElement ruleConditionElement : pattern.getNestedElements()) {\r\n processElement(resolver, contextList, ruleConditionElement);\r\n }\r\n for (Constraint constraint : pattern.getConstraints()) {\r\n if (constraint instanceof Declaration) {\r\n continue;\r\n }\r\n replaceDeclarations(resolver, pattern, constraint);\r\n }\r\n } else if (element instanceof EvalCondition) {\r\n processEvalCondition(resolver, (EvalCondition) element);\r\n } else if (element instanceof Accumulate) {\r\n for (RuleConditionElement rce : element.getNestedElements()) {\r\n processElement(resolver, contextList, rce);\r\n }\r\n Accumulate accumulate = (Accumulate) element;\r\n replaceDeclarations(resolver, accumulate);\r\n } else if (element instanceof From) {\r\n DataProvider provider = ((From) element).getDataProvider();\r\n Declaration[] decl = provider.getRequiredDeclarations();\r\n for (Declaration aDecl : decl) {\r\n Declaration resolved = resolver.getDeclaration(aDecl.getIdentifier());\r\n if (resolved != null && resolved != aDecl) {\r\n provider.replaceDeclaration(aDecl, resolved);\r\n } else if (resolved == null) {\r\n Pattern old = aDecl.getPattern();\r\n Pattern current = resolver.findPatternById(old.getPatternId());\r\n if (current != null && old != current) {\r\n resolved = aDecl.cloneWithPattern(current);\r\n provider.replaceDeclaration(aDecl, resolved);\r\n }\r\n }\r\n }\r\n } else if (element instanceof QueryElement) {\r\n QueryElement qe = (QueryElement) element;\r\n Pattern pattern = qe.getResultPattern();\r\n for (Entry entry : pattern.getInnerDeclarations().entrySet()) {\r\n Declaration resolved = resolver.getDeclaration(entry.getValue().getIdentifier());\r\n if (resolved != null && resolved != entry.getValue() && resolved.getPattern() != pattern) {\r\n entry.setValue(resolved);\r\n }\r\n }\r\n List varIndexes = asList(qe.getVariableIndexes());\r\n for (int i = 0; i < qe.getArguments().length; i++) {\r\n if (!(qe.getArguments()[i] instanceof QueryArgument.Declr)) {\r\n continue;\r\n }\r\n Declaration declr = ((QueryArgument.Declr) qe.getArguments()[i]).getDeclaration();\r\n Declaration resolved = resolver.getDeclaration(declr.getIdentifier());\r\n if (resolved != declr && resolved.getPattern() != pattern) {\r\n qe.getArguments()[i] = new QueryArgument.Declr(resolved);\r\n }\r\n if (ClassObjectType.DroolsQuery_ObjectType.isAssignableFrom(resolved.getPattern().getObjectType())) {\r\n declr = pattern.addDeclaration(declr.getIdentifier());\r\n ArrayElementReader reader = new ArrayElementReader(new SelfReferenceClassFieldReader(Object[].class), i, resolved.getDeclarationClass());\r\n declr.setReadAccessor(reader);\r\n varIndexes.add(i);\r\n }\r\n }\r\n qe.setVariableIndexes(toIntArray(varIndexes));\r\n } else if (element instanceof ConditionalBranch) {\r\n processBranch(resolver, (ConditionalBranch) element);\r\n } else {\r\n contextList.push(element);\r\n for (RuleConditionElement ruleConditionElement : element.getNestedElements()) {\r\n processElement(resolver, contextList, ruleConditionElement);\r\n }\r\n contextList.pop();\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void addDeletion(final Change pChange){\r\n if ((Change.TYPE_DELETE != pChange.type() && Change.TYPE_DELETE_DIR != pChange.type()) || pChange.targetFile() == null) {\r\n return;\r\n }\r\n final String source = pChange.targetFile();\r\n if (source != null && !changes.isEmpty()) {\r\n for (final Iterator it = changes.iterator(); it.hasNext(); ) {\r\n final Change change = it.next();\r\n if (change.type() == Change.TYPE_ADD && change.getEntry() != null) {\r\n final String target = change.getEntry().getName();\r\n if (target == null) {\r\n continue;\r\n }\r\n if (Change.TYPE_DELETE == pChange.type() && source.equals(target) || (Change.TYPE_DELETE_DIR == pChange.type() && target.matches(source + \"/.*\"))) {\r\n it.remove();\r\n }\r\n }\r\n }\r\n }\r\n changes.add(pChange);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void validateAggregateParams(SqlCall aggCall, @Nullable SqlNode filter, @Nullable SqlNodeList distinctList, @Nullable SqlNodeList orderList, SqlValidatorScope scope){\r\n final AggFinder a;\r\n if (inWindow) {\r\n a = overFinder;\r\n } else {\r\n a = aggOrOverFinder;\r\n }\r\n for (SqlNode param : aggCall.getOperandList()) {\r\n if (a.findAgg(param) != null) {\r\n throw newValidationError(aggCall, RESOURCE.nestedAggIllegal());\r\n }\r\n }\r\n if (filter != null) {\r\n if (a.findAgg(filter) != null) {\r\n throw newValidationError(filter, RESOURCE.aggregateInFilterIllegal());\r\n }\r\n }\r\n if (distinctList != null) {\r\n for (SqlNode param : distinctList) {\r\n if (a.findAgg(param) != null) {\r\n throw newValidationError(aggCall, RESOURCE.aggregateInWithinDistinctIllegal());\r\n }\r\n }\r\n }\r\n if (orderList != null) {\r\n for (SqlNode param : orderList) {\r\n if (a.findAgg(param) != null) {\r\n throw newValidationError(aggCall, RESOURCE.aggregateInWithinGroupIllegal());\r\n }\r\n }\r\n }\r\n final SqlAggFunction op = (SqlAggFunction) aggCall.getOperator();\r\n switch(op.requiresGroupOrder()) {\r\n case MANDATORY:\r\n if (orderList == null || orderList.size() == 0) {\r\n throw newValidationError(aggCall, RESOURCE.aggregateMissingWithinGroupClause(op.getName()));\r\n }\r\n break;\r\n case OPTIONAL:\r\n break;\r\n case IGNORED:\r\n if (orderList != null) {\r\n orderList.clear();\r\n }\r\n break;\r\n case FORBIDDEN:\r\n if (orderList != null && orderList.size() != 0) {\r\n throw newValidationError(aggCall, RESOURCE.withinGroupClauseIllegalInAggregate(op.getName()));\r\n }\r\n break;\r\n default:\r\n throw new AssertionError(op);\r\n }\r\n if (op.isPercentile()) {\r\n switch(aggCall.operandCount()) {\r\n case 1:\r\n assert op.requiresGroupOrder() == Optionality.MANDATORY;\r\n assert orderList != null;\r\n if (orderList.size() != 1) {\r\n throw newValidationError(orderList, RESOURCE.orderByRequiresOneKey(op.getName()));\r\n }\r\n SqlNode node = orderList.get(0);\r\n assert node != null;\r\n final RelDataType type = deriveType(scope, node);\r\n @Nullable\r\n final SqlTypeFamily family = type.getSqlTypeName().getFamily();\r\n if (family == null || family.allowableDifferenceTypes().isEmpty()) {\r\n throw newValidationError(orderList, RESOURCE.unsupportedTypeInOrderBy(type.getSqlTypeName().getName(), op.getName()));\r\n }\r\n break;\r\n case 2:\r\n assert op.allowsNullTreatment();\r\n assert op.requiresOver();\r\n assert op.requiresGroupOrder() == Optionality.FORBIDDEN;\r\n break;\r\n default:\r\n throw newValidationError(aggCall, RESOURCE.percentileFunctionsArgumentLimit());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public T serialize(Class type, @Nullable Field field, LuaTable table){\r\n T object = null;\r\n if (type == List.class || type.isArray()) {\r\n try {\r\n Class listType = getListType(type, field);\r\n return (T) serializeList(listType, table);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n return null;\r\n }\r\n }\r\n try {\r\n if (!methodAccessCache.containsKey(type)) {\r\n cacheType(type);\r\n }\r\n var methodAccess = methodAccessCache.get(type);\r\n var fieldMetaMap = fieldMetaCache.get(type);\r\n object = (T) constructorCache.get(type).newInstance();\r\n if (table == null) {\r\n return object;\r\n }\r\n LuaValue[] keys = table.keys();\r\n for (LuaValue k : keys) {\r\n try {\r\n var keyName = k.checkjstring();\r\n if (!fieldMetaMap.containsKey(keyName)) {\r\n continue;\r\n }\r\n var fieldMeta = fieldMetaMap.get(keyName);\r\n LuaValue keyValue = table.get(k);\r\n if (keyValue.istable()) {\r\n methodAccess.invoke(object, fieldMeta.index, serialize(fieldMeta.getType(), fieldMeta.getField(), keyValue.checktable()));\r\n } else if (fieldMeta.getType().equals(float.class)) {\r\n methodAccess.invoke(object, fieldMeta.index, keyValue.tofloat());\r\n } else if (fieldMeta.getType().equals(int.class)) {\r\n methodAccess.invoke(object, fieldMeta.index, keyValue.toint());\r\n } else if (fieldMeta.getType().equals(String.class)) {\r\n methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());\r\n } else if (fieldMeta.getType().equals(boolean.class)) {\r\n methodAccess.invoke(object, fieldMeta.index, keyValue.toboolean());\r\n } else {\r\n methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());\r\n }\r\n } catch (Exception ex) {\r\n continue;\r\n }\r\n }\r\n } catch (Exception e) {\r\n Grasscutter.getLogger().info(ScriptUtils.toMap(table).toString());\r\n e.printStackTrace();\r\n }\r\n return object;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTextRange currentRange){\r\n if (state.currentGroup.isEmpty()) {\r\n return false;\r\n }\r\n Objects.requireNonNull(state.currentGroupCursor);\r\n Objects.requireNonNull(state.cursorBetween);\r\n Objects.requireNonNull(state.prev);\r\n Objects.requireNonNull(state.prevRange);\r\n if (group.citationType != CitationType.AUTHORYEAR_PAR) {\r\n return false;\r\n }\r\n if (state.prev != null) {\r\n if (group.citationType != state.prev.citationType) {\r\n return false;\r\n }\r\n if (!UnoTextRange.comparables(state.prevRange, currentRange)) {\r\n return false;\r\n }\r\n int textOrder = UnoTextRange.compareStarts(state.prevRange, currentRange);\r\n if (textOrder != -1) {\r\n String msg = String.format(\"MergeCitationGroups:\" + \" \\\"%s\\\" supposed to be followed by \\\"%s\\\",\" + \" but %s\", state.prevRange.getString(), currentRange.getString(), ((textOrder == 0) ? \"they start at the same position\" : \"the start of the latter precedes the start of the first\"));\r\n LOGGER.warn(msg);\r\n return false;\r\n }\r\n }\r\n if (state.cursorBetween == null) {\r\n return false;\r\n }\r\n Objects.requireNonNull(state.cursorBetween);\r\n Objects.requireNonNull(state.currentGroupCursor);\r\n if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {\r\n LOGGER.warn(\"MergeCitationGroups: cursorBetween.end != currentGroupCursor.end\");\r\n throw new IllegalStateException(\"MergeCitationGroups failed\");\r\n }\r\n XTextRange rangeStart = currentRange.getStart();\r\n boolean couldExpand = true;\r\n XTextCursor thisCharCursor = currentRange.getText().createTextCursorByRange(state.cursorBetween.getEnd());\r\n while (couldExpand && (UnoTextRange.compareEnds(state.cursorBetween, rangeStart) < 0)) {\r\n couldExpand = thisCharCursor.goRight((short) 1, true);\r\n String thisChar = thisCharCursor.getString();\r\n thisCharCursor.collapseToEnd();\r\n if (thisChar.isEmpty() || \"\\n\".equals(thisChar) || !thisChar.trim().isEmpty()) {\r\n couldExpand = false;\r\n if (!thisChar.isEmpty()) {\r\n thisCharCursor.goLeft((short) 1, false);\r\n }\r\n break;\r\n }\r\n state.cursorBetween.goRight((short) 1, true);\r\n state.currentGroupCursor.goRight((short) 1, true);\r\n if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) {\r\n LOGGER.warn(\"MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)\");\r\n throw new IllegalStateException(\"MergeCitationGroups failed\");\r\n }\r\n }\r\n return couldExpand;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Parameter createQueryParameter(RequiredParameterNode queryParam){\r\n String queryParamName = unescapeIdentifier(queryParam.paramName().get().text());\r\n boolean isQuery = !queryParam.paramName().get().text().equals(Constants.PATH) && queryParam.annotations().isEmpty();\r\n if (queryParam.typeName() instanceof BuiltinSimpleNameReferenceNode && isQuery) {\r\n QueryParameter queryParameter = new QueryParameter();\r\n queryParameter.setName(unescapeIdentifier(queryParamName));\r\n Schema openApiSchema = ConverterCommonUtils.getOpenApiSchema(queryParam.typeName().toString().trim());\r\n queryParameter.setSchema(openApiSchema);\r\n queryParameter.setRequired(true);\r\n if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName.trim()));\r\n }\r\n return queryParameter;\r\n } else if (queryParam.typeName().kind() == OPTIONAL_TYPE_DESC && isQuery) {\r\n NodeList annotations = getAnnotationNodesFromServiceNode(queryParam);\r\n String isOptional = Constants.TRUE;\r\n if (!annotations.isEmpty()) {\r\n Optional values = ConverterCommonUtils.extractServiceAnnotationDetails(annotations, \"http:ServiceConfig\", \"treatNilableAsOptional\");\r\n if (values.isPresent()) {\r\n isOptional = values.get();\r\n }\r\n }\r\n return setOptionalQueryParameter(queryParamName, ((OptionalTypeDescriptorNode) queryParam.typeName()), isOptional);\r\n } else if (queryParam.typeName().kind() == SyntaxKind.ARRAY_TYPE_DESC && isQuery) {\r\n ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) queryParam.typeName();\r\n return handleArrayTypeQueryParameter(queryParamName, arrayNode);\r\n } else if (queryParam.typeName() instanceof SimpleNameReferenceNode && isQuery) {\r\n QueryParameter queryParameter = new QueryParameter();\r\n queryParameter.setName(unescapeIdentifier(queryParamName));\r\n SimpleNameReferenceNode queryNode = (SimpleNameReferenceNode) queryParam.typeName();\r\n OpenAPIComponentMapper componentMapper = new OpenAPIComponentMapper(components);\r\n TypeSymbol typeSymbol = (TypeSymbol) semanticModel.symbol(queryNode).orElseThrow();\r\n componentMapper.createComponentSchema(components.getSchemas(), typeSymbol);\r\n Schema schema = new Schema<>();\r\n schema.set$ref(unescapeIdentifier(queryNode.name().text().trim()));\r\n queryParameter.setSchema(schema);\r\n queryParameter.setRequired(true);\r\n if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName.trim()));\r\n }\r\n return queryParameter;\r\n } else if (queryParam.typeName().kind() == SIMPLE_NAME_REFERENCE) {\r\n QueryParameter queryParameter = new QueryParameter();\r\n Schema refSchema = handleReference(semanticModel, components, (SimpleNameReferenceNode) queryParam.typeName());\r\n queryParameter.setSchema(refSchema);\r\n queryParameter.setRequired(true);\r\n if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName));\r\n }\r\n return queryParameter;\r\n } else {\r\n QueryParameter queryParameter = createContentTypeForMapJson(queryParamName, false);\r\n if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) {\r\n queryParameter.setDescription(apidocs.get(queryParamName.trim()));\r\n }\r\n return queryParameter;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress) throws InterruptedException{\r\n if (!conf.isDisableServerSocketBind()) {\r\n ServerBootstrap bootstrap = new ServerBootstrap();\r\n bootstrap.option(ChannelOption.ALLOCATOR, allocator);\r\n bootstrap.childOption(ChannelOption.ALLOCATOR, allocator);\r\n bootstrap.group(eventLoopGroup, eventLoopGroup);\r\n bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());\r\n bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());\r\n bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));\r\n bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));\r\n if (eventLoopGroup instanceof EpollEventLoopGroup) {\r\n bootstrap.channel(EpollServerSocketChannel.class);\r\n } else {\r\n bootstrap.channel(NioServerSocketChannel.class);\r\n }\r\n bootstrap.childHandler(new ChannelInitializer() {\r\n\r\n @Override\r\n protected void initChannel(SocketChannel ch) throws Exception {\r\n synchronized (suspensionLock) {\r\n while (suspended) {\r\n suspensionLock.wait();\r\n }\r\n }\r\n BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();\r\n ChannelPipeline pipeline = ch.pipeline();\r\n pipeline.addLast(\"bytebufList\", ByteBufList.ENCODER_WITH_SIZE);\r\n pipeline.addLast(\"lengthbaseddecoder\", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));\r\n pipeline.addLast(\"lengthprepender\", new LengthFieldPrepender(4));\r\n pipeline.addLast(\"bookieProtoDecoder\", new BookieProtoEncoding.RequestDecoder(registry));\r\n pipeline.addLast(\"bookieProtoEncoder\", new BookieProtoEncoding.ResponseEncoder(registry));\r\n pipeline.addLast(\"bookieAuthHandler\", new AuthHandler.ServerSideHandler(contextHandler.getConnectionPeer(), authProviderFactory));\r\n ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler();\r\n pipeline.addLast(\"bookieRequestHandler\", requestHandler);\r\n pipeline.addLast(\"contextHandler\", contextHandler);\r\n }\r\n });\r\n LOG.info(\"Binding bookie-rpc endpoint to {}\", address);\r\n Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel();\r\n if (listen.localAddress() instanceof InetSocketAddress) {\r\n if (conf.getBookiePort() == 0) {\r\n conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort());\r\n }\r\n }\r\n }\r\n if (conf.isEnableLocalTransport()) {\r\n ServerBootstrap jvmBootstrap = new ServerBootstrap();\r\n jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));\r\n jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup);\r\n jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());\r\n jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive());\r\n jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());\r\n jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));\r\n jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark()));\r\n if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) {\r\n jvmBootstrap.channel(LocalServerChannel.class);\r\n } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) {\r\n jvmBootstrap.channel(EpollServerSocketChannel.class);\r\n } else {\r\n jvmBootstrap.channel(NioServerSocketChannel.class);\r\n }\r\n jvmBootstrap.childHandler(new ChannelInitializer() {\r\n\r\n @Override\r\n protected void initChannel(LocalChannel ch) throws Exception {\r\n synchronized (suspensionLock) {\r\n while (suspended) {\r\n suspensionLock.wait();\r\n }\r\n }\r\n BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();\r\n ChannelPipeline pipeline = ch.pipeline();\r\n pipeline.addLast(\"lengthbaseddecoder\", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));\r\n pipeline.addLast(\"lengthprepender\", new LengthFieldPrepender(4));\r\n pipeline.addLast(\"bookieProtoDecoder\", new BookieProtoEncoding.RequestDecoder(registry));\r\n pipeline.addLast(\"bookieProtoEncoder\", new BookieProtoEncoding.ResponseEncoder(registry));\r\n pipeline.addLast(\"bookieAuthHandler\", new AuthHandler.ServerSideHandler(contextHandler.getConnectionPeer(), authProviderFactory));\r\n ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler();\r\n pipeline.addLast(\"bookieRequestHandler\", requestHandler);\r\n pipeline.addLast(\"contextHandler\", contextHandler);\r\n }\r\n });\r\n LOG.info(\"Binding jvm bookie-rpc endpoint to {}\", bookieId.toString());\r\n jvmBootstrap.bind(new LocalAddress(bookieId.toString())).sync();\r\n LocalBookiesRegistry.registerLocalBookieAddress(bookieId);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public IcTuple[] getRelevantIcTuples(final String className, final ClassConstantPool cp){\r\n final Set relevantTuplesContains = new HashSet<>();\r\n final List relevantTuples = new ArrayList<>();\r\n final List relevantCandidates = outerClassToTuples.get(className);\r\n if (relevantCandidates != null) {\r\n for (int index = 0; index < relevantCandidates.size(); ++index) {\r\n final IcTuple tuple = relevantCandidates.get(index);\r\n relevantTuplesContains.add(tuple);\r\n relevantTuples.add(tuple);\r\n }\r\n }\r\n final List entries = cp.entries();\r\n for (int eIndex = 0; eIndex < entries.size(); ++eIndex) {\r\n final ConstantPoolEntry entry = (ConstantPoolEntry) entries.get(eIndex);\r\n if (entry instanceof CPClass) {\r\n final CPClass clazz = (CPClass) entry;\r\n final IcTuple relevant = thisClassToTuple.get(clazz.name);\r\n if (relevant != null && relevantTuplesContains.add(relevant)) {\r\n relevantTuples.add(relevant);\r\n }\r\n }\r\n }\r\n final List tuplesToScan = new ArrayList<>(relevantTuples);\r\n final List tuplesToAdd = new ArrayList<>();\r\n while (tuplesToScan.size() > 0) {\r\n tuplesToAdd.clear();\r\n for (int index = 0; index < tuplesToScan.size(); ++index) {\r\n final IcTuple aRelevantTuple = tuplesToScan.get(index);\r\n final IcTuple relevant = thisClassToTuple.get(aRelevantTuple.outerClassString());\r\n if (relevant != null && !aRelevantTuple.outerIsAnonymous()) {\r\n tuplesToAdd.add(relevant);\r\n }\r\n }\r\n tuplesToScan.clear();\r\n for (int index = 0; index < tuplesToAdd.size(); ++index) {\r\n final IcTuple tuple = tuplesToAdd.get(index);\r\n if (relevantTuplesContains.add(tuple)) {\r\n relevantTuples.add(tuple);\r\n tuplesToScan.add(tuple);\r\n }\r\n }\r\n }\r\n relevantTuples.sort((arg0, arg1) -> {\r\n final Integer index1 = Integer.valueOf(arg0.getTupleIndex());\r\n final Integer index2 = Integer.valueOf(arg1.getTupleIndex());\r\n return index1.compareTo(index2);\r\n });\r\n return relevantTuples.toArray(IcTuple.EMPTY_ARRAY);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected JobTO getJobTO(final JobKey jobKey, final boolean includeCustom) throws SchedulerException{\r\n JobTO jobTO = null;\r\n if (scheduler.getScheduler().checkExists(jobKey)) {\r\n Triple reference = getReference(jobKey);\r\n if (reference != null) {\r\n jobTO = new JobTO();\r\n jobTO.setType(reference.getLeft());\r\n jobTO.setRefKey(reference.getMiddle());\r\n jobTO.setRefDesc(reference.getRight());\r\n } else if (includeCustom) {\r\n JobDetail jobDetail = scheduler.getScheduler().getJobDetail(jobKey);\r\n if (!TaskJob.class.isAssignableFrom(jobDetail.getJobClass()) && !ReportJob.class.isAssignableFrom(jobDetail.getJobClass()) && !SystemLoadReporterJob.class.isAssignableFrom(jobDetail.getJobClass()) && !NotificationJob.class.isAssignableFrom(jobDetail.getJobClass())) {\r\n jobTO = new JobTO();\r\n jobTO.setType(JobType.CUSTOM);\r\n jobTO.setRefKey(jobKey.getName());\r\n jobTO.setRefDesc(jobDetail.getJobClass().getName());\r\n }\r\n }\r\n if (jobTO != null) {\r\n List jobTriggers = scheduler.getScheduler().getTriggersOfJob(jobKey);\r\n if (jobTriggers.isEmpty()) {\r\n jobTO.setScheduled(false);\r\n } else {\r\n jobTO.setScheduled(true);\r\n jobTO.setStart(jobTriggers.get(0).getStartTime().toInstant().atOffset(FormatUtils.DEFAULT_OFFSET));\r\n }\r\n jobTO.setRunning(jobManager.isRunning(jobKey));\r\n jobTO.setStatus(\"UNKNOWN\");\r\n if (jobTO.isRunning()) {\r\n try {\r\n Object job = ApplicationContextProvider.getBeanFactory().getBean(jobKey.getName());\r\n if (job instanceof AbstractInterruptableJob && ((AbstractInterruptableJob) job).getDelegate() != null) {\r\n jobTO.setStatus(((AbstractInterruptableJob) job).getDelegate().currentStatus());\r\n }\r\n } catch (NoSuchBeanDefinitionException e) {\r\n LOG.warn(\"Could not find job {} implementation\", jobKey, e);\r\n }\r\n }\r\n }\r\n }\r\n return jobTO;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic void visit(ProjectExpression op) throws FrontendException{\r\n String fullAlias = op.getFieldSchema().alias;\r\n if (fullAlias != null) {\r\n RexNode inputRef;\r\n try {\r\n inputRef = builder.field(inputCount, inputOrdinal, fullAlias);\r\n } catch (IllegalArgumentException e) {\r\n final List fieldNames = builder.peek(inputCount, inputOrdinal).getRowType().getFieldNames();\r\n int index = -1;\r\n for (int i = 0; i < fieldNames.size(); i++) {\r\n if (fullAlias.endsWith(fieldNames.get(i))) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n if (index < 0) {\r\n String shortAlias = fullAlias;\r\n if (fullAlias.contains(\"::\")) {\r\n String[] tokens = fullAlias.split(\"::\");\r\n shortAlias = tokens[tokens.length - 1];\r\n }\r\n for (int i = 0; i < fieldNames.size(); i++) {\r\n if (fieldNames.get(i).equals(shortAlias)) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n if (index < 0) {\r\n throw new IllegalArgumentException(\"field [\" + fullAlias + \"] not found; input fields are: \" + fieldNames);\r\n }\r\n }\r\n inputRef = builder.field(inputCount, inputOrdinal, index);\r\n }\r\n stack.push(inputRef);\r\n } else {\r\n assert op.getInputNum() >= 0;\r\n final Operator pigRelOp = op.getAttachedRelationalOp();\r\n final LogicalRelationalOperator childOp = (LogicalRelationalOperator) pigRelOp.getPlan().getPredecessors(pigRelOp).get(op.getInputNum());\r\n if (builder.checkMap(childOp)) {\r\n builder.push(builder.getRel(childOp));\r\n final List fields = builder.getFields(inputCount, inputOrdinal, op.getColNum());\r\n for (int i = fields.size() - 1; i >= 0; i--) {\r\n stack.push(fields.get(i));\r\n }\r\n builder.build();\r\n } else {\r\n assert childOp instanceof LOInnerLoad;\r\n visit(((LOInnerLoad) childOp).getProjection());\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " void annotation(AnnotatedDescrBuilder adb){\r\n AnnotationDescrBuilder annotation = null;\r\n try {\r\n if (speculateFullAnnotation()) {\r\n boolean buildState = exprParser.isBuildDescr();\r\n exprParser.setBuildDescr(true);\r\n exprParser.fullAnnotation(adb);\r\n exprParser.setBuildDescr(buildState);\r\n } else {\r\n Token at = match(input, DRL6Lexer.AT, null, null, DroolsEditorType.SYMBOL);\r\n if (state.failed)\r\n return;\r\n String fqn = qualifiedIdentifier();\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0) {\r\n annotation = adb.newAnnotation(fqn);\r\n helper.setStart(annotation, at);\r\n }\r\n try {\r\n if (input.LA(1) == DRL6Lexer.LEFT_PAREN) {\r\n String value = chunk(DRL6Lexer.LEFT_PAREN, DRL6Lexer.RIGHT_PAREN, -1).trim();\r\n if (state.failed)\r\n return;\r\n if (state.backtracking == 0) {\r\n if (annotation != null) {\r\n annotation.value(value);\r\n } else {\r\n throw new RecognitionException();\r\n }\r\n }\r\n }\r\n } finally {\r\n if (state.backtracking == 0) {\r\n helper.setEnd(annotation);\r\n }\r\n }\r\n }\r\n } catch (RecognitionException re) {\r\n reportError(re);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public CompletableFuture asyncGetFirstLogRecord(){\r\n final CompletableFuture promise = new CompletableFuture();\r\n streamMetadataStore.logExists(logMetadata.getUri(), logMetadata.getLogName()).whenComplete(new FutureEventListener() {\r\n\r\n @Override\r\n public void onSuccess(Void value) {\r\n readLogSegmentsFromStore(LogSegmentMetadata.COMPARATOR, LogSegmentFilter.DEFAULT_FILTER, null).whenComplete(new FutureEventListener>>() {\r\n\r\n @Override\r\n public void onSuccess(Versioned> ledgerList) {\r\n if (ledgerList.getValue().isEmpty()) {\r\n promise.completeExceptionally(new LogEmptyException(\"Log \" + getFullyQualifiedName() + \" has no records\"));\r\n return;\r\n }\r\n CompletableFuture firstRecord = null;\r\n for (LogSegmentMetadata ledger : ledgerList.getValue()) {\r\n if (!ledger.isTruncated() && (ledger.getRecordCount() > 0 || ledger.isInProgress())) {\r\n firstRecord = asyncReadFirstUserRecord(ledger, DLSN.InitialDLSN);\r\n break;\r\n }\r\n }\r\n if (null != firstRecord) {\r\n FutureUtils.proxyTo(firstRecord, promise);\r\n } else {\r\n promise.completeExceptionally(new LogEmptyException(\"Log \" + getFullyQualifiedName() + \" has no records\"));\r\n }\r\n }\r\n\r\n @Override\r\n public void onFailure(Throwable cause) {\r\n promise.completeExceptionally(cause);\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public void onFailure(Throwable cause) {\r\n promise.completeExceptionally(cause);\r\n }\r\n });\r\n return promise;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void buildFormatTree(TrieTreeNode tree, char[] prefix, char[] suffix, AggregationMessageFormat format){\r\n if (prefix.length == 0 && suffix.length == 0) {\r\n tree.addFormat(\"\", format);\r\n return;\r\n }\r\n boolean isPrefix = true;\r\n int sIndex = 0, eIndex = 0;\r\n TrieTreeNode sCurrent = tree, eCurrent = tree;\r\n if (prefix.length != 0) {\r\n for (int i = 0; i < prefix.length; i++) {\r\n TrieTreeNode node = sCurrent.getChildNode(prefix[i], true);\r\n if (node == null) {\r\n node = new TrieTreeNode();\r\n sCurrent.addTreeNode(prefix[i], true, node);\r\n sIndex++;\r\n }\r\n sCurrent = node;\r\n }\r\n }\r\n if (suffix.length != 0) {\r\n for (int i = suffix.length - 1; i >= 0; i--) {\r\n TrieTreeNode node = eCurrent.getChildNode(suffix[i], false);\r\n if (node == null) {\r\n node = new TrieTreeNode();\r\n eCurrent.addTreeNode(suffix[i], false, node);\r\n eIndex++;\r\n }\r\n eCurrent = node;\r\n }\r\n }\r\n if (sIndex > eIndex) {\r\n isPrefix = true;\r\n } else if (sIndex < eIndex) {\r\n isPrefix = false;\r\n } else {\r\n isPrefix = sCurrent.getFormatMap().size() >= eCurrent.getFormatMap().size() ? false : true;\r\n }\r\n if (isPrefix) {\r\n sCurrent.addFormat(String.copyValueOf(suffix), format);\r\n } else {\r\n eCurrent.addFormat(String.copyValueOf(prefix), format);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String formatTimeDifference(final Date date1, final Date date2){\r\n final long millisecondsDiff = timeDifference(date1, date2);\r\n final long secondsDiff = millisecondsDiff / SECONDS.toMillis(1);\r\n final long minutesDiff = millisecondsDiff / MINUTES.toMillis(1);\r\n final long hoursDiff = millisecondsDiff / HOURS.toMillis(1);\r\n final long daysDiff = millisecondsDiff / DAYS.toMillis(1);\r\n final long hourFieldDiff = hoursDiff - DAYS.toHours(daysDiff);\r\n final long minuteFieldDiff = minutesDiff - HOURS.toMinutes(hoursDiff);\r\n final long secondFieldDiff = secondsDiff - MINUTES.toSeconds(minutesDiff);\r\n final long millisecondsFieldDiff = millisecondsDiff % SECONDS.toMillis(1);\r\n StringBuilder result = new StringBuilder();\r\n if (daysDiff > 0)\r\n result.append(format(\"%dd\", daysDiff));\r\n if (hourFieldDiff > 0) {\r\n if (daysDiff > 0 && minuteFieldDiff == 0 && secondFieldDiff == 0 && millisecondsFieldDiff == 0) {\r\n result.append(\" and \");\r\n } else if (daysDiff > 0) {\r\n result.append(\" \");\r\n }\r\n result.append(format(\"%dh\", hourFieldDiff));\r\n }\r\n if (minuteFieldDiff > 0) {\r\n final boolean notFirstDiff = daysDiff > 0 || hourFieldDiff > 0;\r\n if (notFirstDiff && secondFieldDiff == 0 && millisecondsFieldDiff == 0) {\r\n result.append(\" and \");\r\n } else if (notFirstDiff) {\r\n result.append(\" \");\r\n }\r\n result.append(format(\"%dm\", minuteFieldDiff));\r\n }\r\n if (secondFieldDiff > 0) {\r\n final boolean notFirstDiff = daysDiff > 0 || hourFieldDiff > 0 || minuteFieldDiff > 0;\r\n if (notFirstDiff && millisecondsFieldDiff == 0) {\r\n result.append(\" and \");\r\n } else if (notFirstDiff) {\r\n result.append(\" \");\r\n }\r\n result.append(format(\"%ds\", secondFieldDiff));\r\n }\r\n if (millisecondsFieldDiff > 0) {\r\n if (result.length() > 0)\r\n result.append(\" and \");\r\n result.append(format(\"%dms\", millisecondsFieldDiff));\r\n }\r\n return result.toString();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": " static void dumpSets(VolcanoPlanner planner, PrintWriter pw){\r\n Ordering ordering = Ordering.from(Comparator.comparingInt(o -> o.id));\r\n for (RelSet set : ordering.immutableSortedCopy(planner.allSets)) {\r\n pw.println(\"Set#\" + set.id + \", type: \" + set.subsets.get(0).getRowType());\r\n int j = -1;\r\n for (RelSubset subset : set.subsets) {\r\n ++j;\r\n pw.println(\"\\t\" + subset + \", best=\" + ((subset.best == null) ? \"null\" : (\"rel#\" + subset.best.getId())));\r\n assert subset.set == set;\r\n for (int k = 0; k < j; k++) {\r\n assert !set.subsets.get(k).getTraitSet().equals(subset.getTraitSet());\r\n }\r\n for (RelNode rel : subset.getRels()) {\r\n pw.print(\"\\t\\t\" + rel);\r\n for (RelNode input : rel.getInputs()) {\r\n RelSubset inputSubset = planner.getSubset(input, input.getTraitSet());\r\n if (inputSubset == null) {\r\n pw.append(\"no subset found for input \").print(input.getId());\r\n continue;\r\n }\r\n RelSet inputSet = inputSubset.set;\r\n if (input instanceof RelSubset) {\r\n final Iterator rels = inputSubset.getRels().iterator();\r\n if (rels.hasNext()) {\r\n input = rels.next();\r\n assert input.getTraitSet().satisfies(inputSubset.getTraitSet());\r\n assert inputSet.rels.contains(input);\r\n assert inputSet.subsets.contains(inputSubset);\r\n }\r\n }\r\n }\r\n if (planner.prunedNodes.contains(rel)) {\r\n pw.print(\", pruned\");\r\n }\r\n RelMetadataQuery mq = rel.getCluster().getMetadataQuery();\r\n pw.print(\", rowcount=\" + mq.getRowCount(rel));\r\n pw.println(\", cumulative cost=\" + planner.getCost(rel, mq));\r\n }\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void produce(Context context) throws Exception{\r\n ExportableData collection = (ExportableData) context.get(EXPORTABLE_DATA);\r\n JobData jobData = (JobData) context.get(JOB_DATA);\r\n String rootDirectory = jobData.getPathName();\r\n NeptuneExportParameters parameters = (NeptuneExportParameters) context.get(CONFIGURATION);\r\n boolean addExtension = parameters.isAddExtension();\r\n String projectionType = parameters.getProjectionType();\r\n if (projectionType != null && !projectionType.isEmpty()) {\r\n if (!projectionType.toUpperCase().startsWith(\"EPSG:\"))\r\n projectionType = \"EPSG:\" + projectionType;\r\n }\r\n Metadata metadata = (Metadata) context.get(METADATA);\r\n ChouettePTNetworkType rootObject = AbstractJaxbNeptuneProducer.tridentFactory.createChouettePTNetworkType();\r\n if (collection.getLine().getNetwork() != null)\r\n rootObject.setPTNetwork(networkProducer.produce(collection.getLine().getNetwork(), addExtension));\r\n for (GroupOfLine group : collection.getGroupOfLines()) {\r\n GroupOfLineType jaxbObj = groupOfLineProducer.produce(group, addExtension);\r\n jaxbObj.getLineId().add(collection.getLine().getObjectId());\r\n rootObject.getGroupOfLine().add(jaxbObj);\r\n }\r\n for (Company company : collection.getCompanies()) {\r\n CompanyType jaxbObj = companyProducer.produce(company, addExtension);\r\n rootObject.getCompany().add(jaxbObj);\r\n }\r\n ChouetteArea chouetteArea = new ChouetteArea();\r\n for (StopArea stopArea : collection.getStopAreas()) {\r\n stopArea.toProjection(projectionType);\r\n ChouetteArea.StopArea jaxbStopArea = stopAreaProducer.produce(stopArea, addExtension);\r\n if (stopArea.getAreaType().equals(ChouetteAreaEnum.ITL)) {\r\n for (StopArea child : stopArea.getRoutingConstraintAreas()) {\r\n if (collection.getStopAreas().contains(child)) {\r\n jaxbStopArea.getContains().add(child.getObjectId());\r\n }\r\n }\r\n } else {\r\n for (StopArea child : stopArea.getContainedStopAreas()) {\r\n if (collection.getStopAreas().contains(child)) {\r\n jaxbStopArea.getContains().add(child.getObjectId());\r\n }\r\n }\r\n for (StopPoint child : stopArea.getContainedScheduledStopPoints().stream().map(ScheduledStopPoint::getStopPoints).flatMap(List::stream).collect(Collectors.toList())) {\r\n if (collection.getStopPoints().contains(child)) {\r\n jaxbStopArea.getContains().add(child.getObjectId());\r\n }\r\n }\r\n }\r\n if (metadata != null && stopArea.hasCoordinates())\r\n metadata.getSpatialCoverage().update(stopArea.getLongitude().doubleValue(), stopArea.getLatitude().doubleValue());\r\n if (stopArea.hasAddress() || stopArea.hasCoordinates() || stopArea.hasProjection()) {\r\n ChouetteArea.AreaCentroid centroid = areaCentroidProducer.produce(stopArea, addExtension);\r\n chouetteArea.getAreaCentroid().add(centroid);\r\n jaxbStopArea.setCentroidOfArea(centroid.getObjectId());\r\n }\r\n chouetteArea.getStopArea().add(jaxbStopArea);\r\n }\r\n rootObject.setChouetteArea(chouetteArea);\r\n for (ConnectionLink connectionLink : collection.getConnectionLinks()) {\r\n rootObject.getConnectionLink().add(connectionLinkProducer.produce(connectionLink, addExtension));\r\n }\r\n for (Timetable timetable : collection.getTimetables()) {\r\n timetable.computeLimitOfPeriods();\r\n TimetableType jaxbObj = timetableProducer.produce(timetable, addExtension);\r\n rootObject.getTimetable().add(jaxbObj);\r\n for (VehicleJourney vehicleJourney : collection.getVehicleJourneys()) {\r\n if (vehicleJourney.getTimetables().contains(timetable)) {\r\n jaxbObj.getVehicleJourneyId().add(vehicleJourney.getObjectId());\r\n }\r\n }\r\n if (metadata != null)\r\n metadata.getTemporalCoverage().update(timetable.getStartOfPeriod(), timetable.getEndOfPeriod());\r\n }\r\n ChouetteLineDescription chouetteLineDescription = new ChouetteLineDescription();\r\n ChouetteLineDescription.Line jaxbLine = lineProducer.produce(collection.getLine(), collection.getRoutes(), addExtension);\r\n chouetteLineDescription.setLine(jaxbLine);\r\n rootObject.setChouetteLineDescription(chouetteLineDescription);\r\n if (collection.getLine().getRoutingConstraints() != null) {\r\n for (StopArea routingConstraint : collection.getLine().getRoutingConstraints()) {\r\n ITLType jaxbITL = routingConstraintProducer.produceITL(collection.getLine(), routingConstraint, addExtension);\r\n chouetteLineDescription.getITL().add(jaxbITL);\r\n }\r\n }\r\n for (Route route : collection.getRoutes()) {\r\n ChouetteRoute jaxbObj = routeProducer.produce(route, collection.getRoutes(), addExtension);\r\n jaxbObj.getJourneyPatternId().clear();\r\n for (JourneyPattern jp : route.getJourneyPatterns()) {\r\n if (collection.getJourneyPatterns().contains(jp)) {\r\n jaxbObj.getJourneyPatternId().add(jp.getObjectId());\r\n }\r\n }\r\n List ptLinks = NeptuneObjectUtil.getPtLinks(route);\r\n jaxbObj.getPtLinkId().addAll(NeptuneObjectUtil.extractObjectIds(ptLinks));\r\n for (PTLink ptLink : ptLinks) {\r\n PTLinkType jaxbLink = ptLinkProducer.produce(ptLink, addExtension);\r\n chouetteLineDescription.getPtLink().add(jaxbLink);\r\n }\r\n chouetteLineDescription.getChouetteRoute().add(jaxbObj);\r\n }\r\n for (JourneyPattern journeyPattern : collection.getJourneyPatterns()) {\r\n JourneyPatternType jaxbObj = journeyPatternProducer.produce(journeyPattern, addExtension);\r\n chouetteLineDescription.getJourneyPattern().add(jaxbObj);\r\n }\r\n for (StopPoint stopPoint : collection.getStopPoints()) {\r\n org.trident.schema.trident.ChouettePTNetworkType.ChouetteLineDescription.StopPoint jaxbObj = stopPointProducer.produce(stopPoint, addExtension);\r\n chouetteLineDescription.getStopPoint().add(jaxbObj);\r\n }\r\n for (VehicleJourney vehicleJourney : collection.getVehicleJourneys()) {\r\n List journeyFrequencies = vehicleJourney.getJourneyFrequencies();\r\n if (journeyFrequencies != null && !journeyFrequencies.isEmpty()) {\r\n int count = 0;\r\n for (JourneyFrequency journeyFrequency : journeyFrequencies) {\r\n Timeband timeband = journeyFrequency.getTimeband();\r\n TimeSlot timeSlot = new TimeSlot();\r\n if (timeband != null) {\r\n timeSlot.setBeginningSlotTime(timeband.getStartTime());\r\n timeSlot.setEndSlotTime(timeband.getEndTime());\r\n timeSlot.setObjectVersion(timeband.getObjectVersion());\r\n timeSlot.setCreationTime(timeband.getCreationTime());\r\n timeSlot.setCreatorId(timeband.getCreatorId());\r\n } else {\r\n timeSlot.setBeginningSlotTime(journeyFrequency.getFirstDepartureTime());\r\n timeSlot.setEndSlotTime(journeyFrequency.getLastDepartureTime());\r\n }\r\n timeSlot.setFirstDepartureTimeInSlot(journeyFrequency.getFirstDepartureTime());\r\n timeSlot.setLastDepartureTimeInSlot(journeyFrequency.getLastDepartureTime());\r\n VehicleJourneyType jaxbObj = vehicleJourneyProducer.produce(vehicleJourney, addExtension, count);\r\n timeSlot.setObjectId(jaxbObj.getObjectId().replaceAll(\"VehicleJourney\", \"TimeSlot\"));\r\n jaxbObj.setTimeSlotId(timeSlot.getObjectId());\r\n chouetteLineDescription.getVehicleJourney().add(jaxbObj);\r\n TimeSlotType jaxbTSObj = timeSlotProducer.produce(timeSlot, addExtension);\r\n rootObject.getTimeSlot().add(jaxbTSObj);\r\n count++;\r\n }\r\n } else {\r\n VehicleJourneyType jaxbObj = vehicleJourneyProducer.produce(vehicleJourney, addExtension);\r\n chouetteLineDescription.getVehicleJourney().add(jaxbObj);\r\n }\r\n }\r\n for (AccessLink accessLink : collection.getAccessLinks()) {\r\n if (collection.getStopAreas().contains(accessLink.getStopArea()) && collection.getAccessPoints().contains(accessLink.getAccessPoint())) {\r\n rootObject.getAccessLink().add(accessLinkProducer.produce(accessLink, addExtension));\r\n }\r\n }\r\n for (AccessPoint accessPoint : collection.getAccessPoints()) {\r\n rootObject.getAccessPoint().add(accessPointProducer.produce(accessPoint, addExtension));\r\n }\r\n JaxbNeptuneFileConverter writer = JaxbNeptuneFileConverter.getInstance();\r\n Path dir = Paths.get(rootDirectory, OUTPUT);\r\n String fileName = collection.getLine().getObjectId().replaceAll(\":\", \"-\") + \".xml\";\r\n File file = new File(dir.toFile(), fileName);\r\n writer.write(AbstractJaxbNeptuneProducer.tridentFactory.createChouettePTNetwork(rootObject), file);\r\n ActionReporter reporter = ActionReporter.Factory.getInstance();\r\n reporter.addFileReport(context, fileName, IO_TYPE.OUTPUT);\r\n if (metadata != null)\r\n metadata.getResources().add(new Metadata.Resource(fileName, NeptuneObjectPresenter.getName(collection.getLine().getNetwork()), NeptuneObjectPresenter.getName(collection.getLine())));\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public static String findPublicationDeliveryVersion(File f){\r\n String versionAttribute = null;\r\n try {\r\n XMLInputFactory inputFactory = getSecureXmlInputFactory();\r\n InputStream in = new FileInputStream(f);\r\n XMLEventReader eventReader = inputFactory.createXMLEventReader(new BufferedInputStream(in));\r\n while (versionAttribute == null && eventReader.hasNext()) {\r\n XMLEvent event = eventReader.nextEvent();\r\n if (event.isStartElement()) {\r\n StartElement startElement = event.asStartElement();\r\n if (startElement.getName().getLocalPart().equals(\"PublicationDelivery\")) {\r\n @SuppressWarnings(\"unchecked\")\r\n Iterator attributes = event.asStartElement().getAttributes();\r\n while (attributes.hasNext()) {\r\n Attribute attribute = attributes.next();\r\n if (attribute.getName().toString().equals(\"version\")) {\r\n versionAttribute = attribute.getValue();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n eventReader.close();\r\n in.close();\r\n } catch (FileNotFoundException e) {\r\n log.error(\"Could not find file \" + f.getAbsolutePath());\r\n } catch (XMLStreamException e) {\r\n log.error(\"Malformed xml\", e);\r\n } catch (IOException e) {\r\n log.error(\"Error closing file\", e);\r\n }\r\n return versionAttribute;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private synchronized void updateClientContext() throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException{\r\n final SslContextBuilder sslContextBuilder;\r\n final ClientConfiguration clientConf;\r\n final SslProvider provider;\r\n final boolean clientAuthentication;\r\n if (!(config instanceof ClientConfiguration)) {\r\n throw new SecurityException(\"Client configruation not provided\");\r\n }\r\n clientConf = (ClientConfiguration) config;\r\n provider = getTLSProvider(clientConf.getTLSProvider());\r\n clientAuthentication = clientConf.getTLSClientAuthentication();\r\n switch(KeyStoreType.valueOf(clientConf.getTLSTrustStoreType())) {\r\n case PEM:\r\n if (Strings.isNullOrEmpty(clientConf.getTLSTrustStore())) {\r\n throw new SecurityException(\"CA Certificate required\");\r\n }\r\n sslContextBuilder = SslContextBuilder.forClient().trustManager(new File(clientConf.getTLSTrustStore())).ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).clientAuth(ClientAuth.REQUIRE);\r\n break;\r\n case JKS:\r\n case PKCS12:\r\n TrustManagerFactory tmf = initTrustManagerFactory(clientConf.getTLSTrustStoreType(), clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath());\r\n sslContextBuilder = SslContextBuilder.forClient().trustManager(tmf).ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).clientAuth(ClientAuth.REQUIRE);\r\n break;\r\n default:\r\n throw new SecurityException(\"Invalid Truststore type: \" + clientConf.getTLSTrustStoreType());\r\n }\r\n if (clientAuthentication) {\r\n switch(KeyStoreType.valueOf(clientConf.getTLSKeyStoreType())) {\r\n case PEM:\r\n final String keyPassword;\r\n if (Strings.isNullOrEmpty(clientConf.getTLSCertificatePath())) {\r\n throw new SecurityException(\"Valid Certificate is missing\");\r\n }\r\n if (Strings.isNullOrEmpty(clientConf.getTLSKeyStore())) {\r\n throw new SecurityException(\"Valid Key is missing\");\r\n }\r\n if (!Strings.isNullOrEmpty(clientConf.getTLSKeyStorePasswordPath())) {\r\n keyPassword = getPasswordFromFile(clientConf.getTLSKeyStorePasswordPath());\r\n } else {\r\n keyPassword = null;\r\n }\r\n sslContextBuilder.keyManager(new File(clientConf.getTLSCertificatePath()), new File(clientConf.getTLSKeyStore()), keyPassword);\r\n break;\r\n case JKS:\r\n case PKCS12:\r\n KeyManagerFactory kmf = initKeyManagerFactory(clientConf.getTLSKeyStoreType(), clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath());\r\n sslContextBuilder.keyManager(kmf);\r\n break;\r\n default:\r\n throw new SecurityException(\"Invalid Keyfile type\" + clientConf.getTLSKeyStoreType());\r\n }\r\n }\r\n sslContext = sslContextBuilder.build();\r\n certLastRefreshTime = System.currentTimeMillis();\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void collectLedgersFromAllocator(final URI uri, final Namespace namespace, final List allocationPaths, final Set ledgers) throws IOException{\r\n final LinkedBlockingQueue poolQueue = new LinkedBlockingQueue();\r\n for (String allocationPath : allocationPaths) {\r\n String rootPath = uri.getPath() + \"/\" + allocationPath;\r\n try {\r\n List pools = getZooKeeperClient(namespace).get().getChildren(rootPath, false);\r\n for (String pool : pools) {\r\n poolQueue.add(rootPath + \"/\" + pool);\r\n }\r\n } catch (KeeperException e) {\r\n throw new ZKException(\"Failed to get list of pools from \" + rootPath, e);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n throw new DLInterruptedException(\"Interrupted on getting list of pools from \" + rootPath, e);\r\n }\r\n }\r\n logger.info(\"Collecting ledgers from allocators for {} : {}\", uri, poolQueue);\r\n executeAction(poolQueue, 10, new Action() {\r\n\r\n @Override\r\n public void execute(String poolPath) throws IOException {\r\n try {\r\n collectLedgersFromPool(poolPath);\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n throw new DLInterruptedException(\"Interrupted on collecting\" + \" ledgers from allocation pool \" + poolPath, e);\r\n } catch (KeeperException e) {\r\n throw new ZKException(\"Failed to collect ledgers from allocation pool \" + poolPath, e.code());\r\n }\r\n }\r\n\r\n private void collectLedgersFromPool(String poolPath) throws InterruptedException, ZooKeeperClient.ZooKeeperConnectionException, KeeperException {\r\n List allocators = getZooKeeperClient(namespace).get().getChildren(poolPath, false);\r\n for (String allocator : allocators) {\r\n String allocatorPath = poolPath + \"/\" + allocator;\r\n byte[] data = getZooKeeperClient(namespace).get().getData(allocatorPath, false, new Stat());\r\n if (null != data && data.length > 0) {\r\n try {\r\n long ledgerId = DLUtils.bytes2LogSegmentId(data);\r\n synchronized (ledgers) {\r\n ledgers.add(ledgerId);\r\n }\r\n } catch (NumberFormatException nfe) {\r\n logger.warn(\"Invalid ledger found in allocator path {} : \", allocatorPath, nfe);\r\n }\r\n }\r\n }\r\n }\r\n });\r\n logger.info(\"Collected ledgers from allocators for {}.\", uri);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public Query simplify(@Nullable String hintToken){\r\n TokenType clause = TokenType.SELECT;\r\n TokenType foundInClause = null;\r\n Query foundInSubQuery = null;\r\n TokenType majorClause = null;\r\n if (hintToken != null) {\r\n for (Token token : tokenList) {\r\n switch(token.type) {\r\n case ID:\r\n if (hintToken.equals(token.s)) {\r\n foundInClause = clause;\r\n }\r\n break;\r\n case SELECT:\r\n case FROM:\r\n case WHERE:\r\n case GROUP:\r\n case HAVING:\r\n case ORDER:\r\n majorClause = token.type;\r\n case JOIN:\r\n case USING:\r\n case ON:\r\n clause = token.type;\r\n break;\r\n case COMMA:\r\n if (majorClause == TokenType.FROM) {\r\n clause = TokenType.FROM;\r\n }\r\n break;\r\n case QUERY:\r\n if (((Query) token).contains(hintToken)) {\r\n foundInClause = clause;\r\n foundInSubQuery = (Query) token;\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n } else {\r\n foundInClause = TokenType.QUERY;\r\n }\r\n if (foundInClause != null) {\r\n switch(foundInClause) {\r\n case SELECT:\r\n purgeSelectListExcept(hintToken);\r\n purgeWhere();\r\n purgeOrderBy();\r\n break;\r\n case FROM:\r\n case JOIN:\r\n purgeSelect();\r\n purgeFromExcept(hintToken);\r\n purgeWhere();\r\n purgeGroupByHaving();\r\n purgeOrderBy();\r\n break;\r\n case ON:\r\n case USING:\r\n purgeSelect();\r\n purgeWhere();\r\n purgeOrderBy();\r\n break;\r\n case WHERE:\r\n purgeSelect();\r\n purgeGroupByHaving();\r\n purgeOrderBy();\r\n break;\r\n case GROUP:\r\n case HAVING:\r\n purgeSelect();\r\n purgeWhere();\r\n purgeOrderBy();\r\n break;\r\n case ORDER:\r\n purgeWhere();\r\n break;\r\n case QUERY:\r\n purgeWhere();\r\n purgeGroupByHaving();\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n for (Token token : tokenList) {\r\n switch(token.type) {\r\n case QUERY:\r\n {\r\n Query query = (Query) token;\r\n query.simplify((query == foundInSubQuery) ? hintToken : null);\r\n break;\r\n }\r\n default:\r\n break;\r\n }\r\n }\r\n return this;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private String getValueAsString(final AttrSchemaType type, final PlainSchema schema){\r\n if (getValue(type) == null) {\r\n LOG.warn(\"Could not find expected value for type {} in {}, reverting to getValue().toString()\", type, this);\r\n Object value = getValue();\r\n return Optional.ofNullable(value).map(Object::toString).orElse(null);\r\n }\r\n String result;\r\n switch(type) {\r\n case Boolean:\r\n result = getBooleanValue().toString();\r\n break;\r\n case Long:\r\n result = schema == null || schema.getConversionPattern() == null ? getLongValue().toString() : FormatUtils.format(getLongValue(), schema.getConversionPattern());\r\n break;\r\n case Double:\r\n result = schema == null || schema.getConversionPattern() == null ? getDoubleValue().toString() : FormatUtils.format(getDoubleValue(), schema.getConversionPattern());\r\n break;\r\n case Date:\r\n result = schema == null || schema.getConversionPattern() == null ? FormatUtils.format(getDateValue()) : FormatUtils.format(getDateValue(), schema.getConversionPattern());\r\n break;\r\n case Binary:\r\n result = Base64.getEncoder().encodeToString(getBinaryValue());\r\n break;\r\n case Encrypted:\r\n if (schema == null || !SyncopeConstants.ENCRYPTED_DECODE_CONVERSION_PATTERN.equals(schema.getConversionPattern()) || !schema.getCipherAlgorithm().isInvertible()) {\r\n result = getStringValue();\r\n } else {\r\n try {\r\n result = Encryptor.getInstance(getSecretKey(schema)).decode(getStringValue(), schema.getCipherAlgorithm());\r\n } catch (Exception e) {\r\n LOG.error(\"Could not decode encrypted value {} for schema {}\", getStringValue(), schema, e);\r\n result = getStringValue();\r\n }\r\n }\r\n break;\r\n case String:\r\n case Enum:\r\n default:\r\n result = getStringValue();\r\n }\r\n return result;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private static void addNewPaths(InternalWorkingMemory wm, Set smemsToNotify, List pmems){\r\n Set visited = new HashSet<>();\r\n for (PathMemory pmem : pmems) {\r\n LeftTupleSink tipNode = pmem.getPathEndNode();\r\n LeftTupleNode child = tipNode;\r\n LeftTupleNode parent = tipNode.getLeftTupleSource();\r\n while (true) {\r\n if (visited.add(child)) {\r\n if (parent != null && parent.getAssociatedTerminalsSize() != 1 && child.getAssociatedTerminalsSize() == 1) {\r\n Memory mem = wm.getNodeMemories().peekNodeMemory(parent);\r\n if (mem != null && mem.getSegmentMemory() != null) {\r\n SegmentMemory sm = mem.getSegmentMemory();\r\n if (sm.getFirst() != null && sm.size() < parent.getSinkPropagator().size()) {\r\n LeftTupleSink[] sinks = parent.getSinkPropagator().getSinks();\r\n for (int i = sm.size(); i < sinks.length; i++) {\r\n SegmentMemory childSmem = createChildSegment(wm, sinks[i]);\r\n sm.add(childSmem);\r\n pmem.setSegmentMemory(childSmem.getPos(), childSmem);\r\n smemsToNotify.add(childSmem);\r\n }\r\n }\r\n correctMemoryOnSplitsChanged(parent, null, wm);\r\n }\r\n } else {\r\n Memory mem = wm.getNodeMemories().peekNodeMemory(child);\r\n if (mem != null) {\r\n SegmentMemory sm = mem.getSegmentMemory();\r\n if (sm != null && !sm.getPathMemories().contains(pmem)) {\r\n RuntimeSegmentUtilities.addSegmentToPathMemory(pmem, sm);\r\n sm.notifyRuleLinkSegment(wm, pmem);\r\n }\r\n }\r\n }\r\n } else {\r\n Memory mem = wm.getNodeMemories().peekNodeMemory(child);\r\n if (mem != null) {\r\n mem.getSegmentMemory().notifyRuleLinkSegment(wm, pmem);\r\n }\r\n }\r\n if (parent == null) {\r\n break;\r\n }\r\n child = parent;\r\n parent = parent.getLeftTupleSource();\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void distinctify(Blackboard bb, boolean checkForDupExprs){\r\n RelNode rel = bb.root;\r\n if (checkForDupExprs && (rel instanceof LogicalProject)) {\r\n LogicalProject project = (LogicalProject) rel;\r\n final List projectExprs = project.getProjects();\r\n final List origins = new ArrayList<>();\r\n int dupCount = 0;\r\n for (int i = 0; i < projectExprs.size(); i++) {\r\n int x = projectExprs.indexOf(projectExprs.get(i));\r\n if (x >= 0 && x < i) {\r\n origins.add(x);\r\n ++dupCount;\r\n } else {\r\n origins.add(i);\r\n }\r\n }\r\n if (dupCount == 0) {\r\n distinctify(bb, false);\r\n return;\r\n }\r\n final Map squished = new HashMap<>();\r\n final List fields = rel.getRowType().getFieldList();\r\n final PairList newProjects = PairList.of();\r\n for (int i = 0; i < fields.size(); i++) {\r\n if (origins.get(i) == i) {\r\n squished.put(i, newProjects.size());\r\n RexInputRef.add2(newProjects, i, fields);\r\n }\r\n }\r\n rel = LogicalProject.create(rel, ImmutableList.of(), newProjects.leftList(), newProjects.rightList(), project.getVariablesSet());\r\n bb.root = rel;\r\n distinctify(bb, false);\r\n rel = bb.root();\r\n final PairList undoProjects = PairList.of();\r\n for (int i = 0; i < fields.size(); i++) {\r\n final int origin = origins.get(i);\r\n RelDataTypeField field = fields.get(i);\r\n undoProjects.add(new RexInputRef(castNonNull(squished.get(origin)), field.getType()), field.getName());\r\n }\r\n rel = LogicalProject.create(rel, ImmutableList.of(), undoProjects.leftList(), undoProjects.rightList(), ImmutableSet.of());\r\n bb.setRoot(rel, false);\r\n return;\r\n }\r\n assert rel != null : \"rel must not be null, root = \" + bb.root;\r\n final ImmutableBitSet groupSet = ImmutableBitSet.range(rel.getRowType().getFieldCount());\r\n rel = createAggregate(bb, groupSet, ImmutableList.of(groupSet), ImmutableList.of());\r\n bb.setRoot(rel, false);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "@Override\npublic Table create(SchemaPlus schema, String name, Map operand, @Nullable RelDataType rowType){\r\n final DruidSchema druidSchema = schema.unwrap(DruidSchema.class);\r\n final String dataSource = (String) operand.get(\"dataSource\");\r\n final Set metricNameBuilder = new LinkedHashSet<>();\r\n final Map fieldBuilder = new LinkedHashMap<>();\r\n final Map> complexMetrics = new HashMap<>();\r\n final String timestampColumnName;\r\n final SqlTypeName timestampColumnType;\r\n final Object timestampInfo = operand.get(\"timestampColumn\");\r\n if (timestampInfo != null) {\r\n if (timestampInfo instanceof Map) {\r\n Map map = (Map) timestampInfo;\r\n if (!(map.get(\"name\") instanceof String)) {\r\n throw new IllegalArgumentException(\"timestampColumn array must have name\");\r\n }\r\n timestampColumnName = (String) map.get(\"name\");\r\n if (!(map.get(\"type\") instanceof String) || map.get(\"type\").equals(\"timestamp with local time zone\")) {\r\n timestampColumnType = SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE;\r\n } else if (map.get(\"type\").equals(\"timestamp\")) {\r\n timestampColumnType = SqlTypeName.TIMESTAMP;\r\n } else {\r\n throw new IllegalArgumentException(\"unexpected type for timestampColumn array\");\r\n }\r\n } else {\r\n timestampColumnName = (String) timestampInfo;\r\n timestampColumnType = SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE;\r\n }\r\n } else {\r\n timestampColumnName = DruidTable.DEFAULT_TIMESTAMP_COLUMN;\r\n timestampColumnType = SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE;\r\n }\r\n fieldBuilder.put(timestampColumnName, timestampColumnType);\r\n final Object dimensionsRaw = operand.get(\"dimensions\");\r\n if (dimensionsRaw instanceof List) {\r\n final List dimensions = (List) dimensionsRaw;\r\n for (String dimension : dimensions) {\r\n fieldBuilder.put(dimension, SqlTypeName.VARCHAR);\r\n }\r\n }\r\n final Object complexMetricsRaw = operand.get(\"complexMetrics\");\r\n if (complexMetricsRaw instanceof List) {\r\n final List complexMetricList = (List) complexMetricsRaw;\r\n for (String metric : complexMetricList) {\r\n complexMetrics.put(metric, new ArrayList<>());\r\n }\r\n }\r\n final Object metricsRaw = operand.get(\"metrics\");\r\n if (metricsRaw instanceof List) {\r\n final List metrics = (List) metricsRaw;\r\n for (Object metric : metrics) {\r\n DruidType druidType = DruidType.LONG;\r\n final String metricName;\r\n String fieldName = null;\r\n if (metric instanceof Map) {\r\n Map map2 = (Map) metric;\r\n if (!(map2.get(\"name\") instanceof String)) {\r\n throw new IllegalArgumentException(\"metric must have name\");\r\n }\r\n metricName = (String) map2.get(\"name\");\r\n final String type = (String) map2.get(\"type\");\r\n fieldName = (String) map2.get(\"fieldName\");\r\n druidType = DruidType.getTypeFromMetric(type);\r\n } else {\r\n metricName = (String) metric;\r\n }\r\n if (!druidType.isComplex()) {\r\n fieldBuilder.put(metricName, druidType.sqlType);\r\n metricNameBuilder.add(metricName);\r\n } else {\r\n assert fieldName != null;\r\n if (complexMetrics.containsKey(fieldName)) {\r\n SqlTypeName type = fieldBuilder.get(fieldName);\r\n if (type != SqlTypeName.VARCHAR) {\r\n fieldBuilder.put(fieldName, SqlTypeName.VARBINARY);\r\n }\r\n complexMetrics.get(fieldName).add(new ComplexMetric(metricName, druidType));\r\n }\r\n }\r\n }\r\n }\r\n final Object interval = operand.get(\"interval\");\r\n final List intervals;\r\n if (interval instanceof String) {\r\n intervals = ImmutableList.of(new Interval(interval, ISOChronology.getInstanceUTC()));\r\n } else {\r\n intervals = null;\r\n }\r\n final String dataSourceName = Util.first(dataSource, name);\r\n if (dimensionsRaw == null || metricsRaw == null) {\r\n DruidConnectionImpl connection = new DruidConnectionImpl(druidSchema.url, druidSchema.url.replace(\":8082\", \":8081\"));\r\n return DruidTable.create(druidSchema, dataSourceName, intervals, fieldBuilder, metricNameBuilder, timestampColumnName, connection, complexMetrics);\r\n } else {\r\n return DruidTable.create(druidSchema, dataSourceName, intervals, fieldBuilder, metricNameBuilder, timestampColumnName, complexMetrics);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected static void fill(final RealmMember realmMember, final RealmMember template){\r\n MapContext jexlContext = new MapContext();\r\n JexlUtils.addFieldsToContext(realmMember, jexlContext);\r\n JexlUtils.addAttrsToContext(realmMember.getPlainAttrs(), jexlContext);\r\n JexlUtils.addAttrsToContext(realmMember.getDerAttrs(), jexlContext);\r\n JexlUtils.addAttrsToContext(realmMember.getVirAttrs(), jexlContext);\r\n if (template.getRealm() != null) {\r\n String evaluated = JexlUtils.evaluate(template.getRealm(), jexlContext);\r\n if (StringUtils.isNotBlank(evaluated)) {\r\n realmMember.setRealm(evaluated);\r\n }\r\n }\r\n Map currentAttrMap = EntityTOUtils.buildAttrMap(realmMember.getPlainAttrs());\r\n for (Attr templatePlainAttr : template.getPlainAttrs()) {\r\n if (!templatePlainAttr.getValues().isEmpty() && (!currentAttrMap.containsKey(templatePlainAttr.getSchema()) || currentAttrMap.get(templatePlainAttr.getSchema()).getValues().isEmpty())) {\r\n Attr evaluated = evaluateAttr(templatePlainAttr, jexlContext);\r\n if (!evaluated.getValues().isEmpty()) {\r\n realmMember.getPlainAttrs().add(evaluated);\r\n jexlContext.set(evaluated.getSchema(), evaluated.getValues().get(0));\r\n }\r\n }\r\n }\r\n currentAttrMap = EntityTOUtils.buildAttrMap(realmMember.getDerAttrs());\r\n for (Attr templateDerAttr : template.getDerAttrs()) {\r\n if (!currentAttrMap.containsKey(templateDerAttr.getSchema())) {\r\n realmMember.getDerAttrs().add(templateDerAttr);\r\n }\r\n }\r\n currentAttrMap = EntityTOUtils.buildAttrMap(realmMember.getVirAttrs());\r\n for (Attr templateVirAttr : template.getVirAttrs()) {\r\n if (!templateVirAttr.getValues().isEmpty() && (!currentAttrMap.containsKey(templateVirAttr.getSchema()) || currentAttrMap.get(templateVirAttr.getSchema()).getValues().isEmpty())) {\r\n Attr evaluated = evaluateAttr(templateVirAttr, jexlContext);\r\n if (!evaluated.getValues().isEmpty()) {\r\n realmMember.getVirAttrs().add(evaluated);\r\n jexlContext.set(evaluated.getSchema(), evaluated.getValues().get(0));\r\n }\r\n }\r\n }\r\n realmMember.getResources().addAll(template.getResources());\r\n realmMember.getAuxClasses().addAll(template.getAuxClasses());\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private Token getToken(){\r\n tokenStart = tokenEnd;\r\n while (tokenStart < original.length()) {\r\n char c = original.charAt(tokenStart);\r\n if (!((c == '~') || (c == '-') || Character.isWhitespace(c))) {\r\n break;\r\n }\r\n tokenStart++;\r\n }\r\n tokenEnd = tokenStart;\r\n if (tokenStart >= original.length()) {\r\n return Token.EOF;\r\n }\r\n if (original.charAt(tokenStart) == ',') {\r\n tokenEnd++;\r\n return Token.COMMA;\r\n }\r\n if (original.charAt(tokenStart) == ';') {\r\n tokenEnd++;\r\n return Token.AND;\r\n }\r\n tokenAbbrEnd = -1;\r\n tokenTerm = ' ';\r\n tokenCase = true;\r\n int bracesLevel = 0;\r\n int currentBackslash = -1;\r\n boolean firstLetterIsFound = false;\r\n while (tokenEnd < original.length()) {\r\n char c = original.charAt(tokenEnd);\r\n if (c == '{') {\r\n bracesLevel++;\r\n }\r\n if (firstLetterIsFound && (tokenAbbrEnd < 0) && ((bracesLevel == 0) || (c == '{'))) {\r\n tokenAbbrEnd = tokenEnd;\r\n }\r\n if ((c == '}') && (bracesLevel > 0)) {\r\n bracesLevel--;\r\n }\r\n if (!firstLetterIsFound && (currentBackslash < 0) && Character.isLetter(c)) {\r\n if (bracesLevel == 0) {\r\n tokenCase = Character.isUpperCase(c) || (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN);\r\n } else {\r\n tokenCase = true;\r\n }\r\n firstLetterIsFound = true;\r\n }\r\n if ((currentBackslash >= 0) && !Character.isLetter(c)) {\r\n if (!firstLetterIsFound) {\r\n String texCmdName = original.substring(currentBackslash + 1, tokenEnd);\r\n if (TEX_NAMES.contains(texCmdName)) {\r\n tokenCase = Character.isUpperCase(texCmdName.charAt(0));\r\n firstLetterIsFound = true;\r\n }\r\n }\r\n currentBackslash = -1;\r\n }\r\n if (c == '\\\\') {\r\n currentBackslash = tokenEnd;\r\n }\r\n if ((bracesLevel == 0) && ((\",;-\".indexOf(c) != -1) || Character.isWhitespace(c))) {\r\n break;\r\n }\r\n tokenEnd++;\r\n }\r\n if (tokenAbbrEnd < 0) {\r\n tokenAbbrEnd = tokenEnd;\r\n }\r\n if ((tokenEnd < original.length()) && (original.charAt(tokenEnd) == '-')) {\r\n tokenTerm = '-';\r\n }\r\n if (\"and\".equalsIgnoreCase(original.substring(tokenStart, tokenEnd))) {\r\n return Token.AND;\r\n } else {\r\n return Token.WORD;\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "protected void processHeaders(HeadersMessage m) throws ProtocolException{\r\n boolean downloadBlockBodies;\r\n long fastCatchupTimeSecs;\r\n lock.lock();\r\n try {\r\n if (blockChain == null) {\r\n log.warn(\"Received headers when Peer is not configured with a chain.\");\r\n return;\r\n }\r\n fastCatchupTimeSecs = this.fastCatchupTimeSecs;\r\n downloadBlockBodies = this.downloadBlockBodies;\r\n } finally {\r\n lock.unlock();\r\n }\r\n try {\r\n checkState(!downloadBlockBodies, toString());\r\n for (int i = 0; i < m.getBlockHeaders().size(); i++) {\r\n Block header = m.getBlockHeaders().get(i);\r\n boolean passedTime = header.getTime() >= fastCatchupTimeSecs;\r\n boolean reachedTop = blockChain.getBestChainHeight() >= vPeerVersionMessage.bestHeight;\r\n if (!passedTime && !reachedTop) {\r\n if (!vDownloadData) {\r\n log.info(\"Lost download peer status, throwing away downloaded headers.\");\r\n return;\r\n }\r\n if (blockChain.add(header)) {\r\n invokeOnBlocksDownloaded(header, null);\r\n } else {\r\n throw new ProtocolException(\"Got unconnected header from peer: \" + header.getHashAsString());\r\n }\r\n } else {\r\n lock.lock();\r\n try {\r\n log.info(\"Passed the fast catchup time ({}) at height {}, discarding {} headers and requesting full blocks\", Utils.dateTimeFormat(fastCatchupTimeSecs * 1000), blockChain.getBestChainHeight() + 1, m.getBlockHeaders().size() - i);\r\n this.downloadBlockBodies = true;\r\n this.lastGetBlocksBegin = Sha256Hash.ZERO_HASH;\r\n blockChainDownloadLocked(Sha256Hash.ZERO_HASH);\r\n } finally {\r\n lock.unlock();\r\n }\r\n return;\r\n }\r\n }\r\n if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS) {\r\n lock.lock();\r\n try {\r\n blockChainDownloadLocked(Sha256Hash.ZERO_HASH);\r\n } finally {\r\n lock.unlock();\r\n }\r\n }\r\n } catch (VerificationException e) {\r\n log.warn(\"Block header verification failed\", e);\r\n } catch (PrunedException e) {\r\n throw new RuntimeException(e);\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void saveData(Context context){\r\n Metadata metadata = (Metadata) context.get(METADATA);\r\n GtfsExporter exporter = (GtfsExporter) context.get(GTFS_EXPORTER);\r\n GtfsStopProducer stopProducer = new GtfsStopProducer(exporter);\r\n GtfsTransferProducer transferProducer = new GtfsTransferProducer(exporter);\r\n GtfsAgencyProducer agencyProducer = null;\r\n GtfsServiceProducer calendarProducer = null;\r\n GtfsExportParameters configuration = (GtfsExportParameters) context.get(CONFIGURATION);\r\n TimeZone timezone = TimeZone.getTimeZone(configuration.getTimeZone());\r\n String prefix = configuration.getObjectIdPrefix();\r\n String sharedPrefix = prefix;\r\n ExportableData collection = (ExportableData) context.get(EXPORTABLE_DATA);\r\n Map> timetables = collection.getTimetableMap();\r\n List datedServiceJourneys = collection.getDatedServiceJourneys();\r\n Set commercialStops = collection.getCommercialStops();\r\n Set physicalStops = collection.getPhysicalStops();\r\n Set connectionLinks = collection.getConnectionLinks();\r\n Set companies = collection.getAgencyCompanies();\r\n Set interchanges = collection.getInterchanges();\r\n if (!companies.isEmpty()) {\r\n agencyProducer = new GtfsAgencyProducer(exporter);\r\n }\r\n if (!timetables.isEmpty() || !datedServiceJourneys.isEmpty()) {\r\n calendarProducer = new GtfsServiceProducer(exporter);\r\n }\r\n for (Iterator iterator = commercialStops.iterator(); iterator.hasNext(); ) {\r\n StopArea stop = iterator.next();\r\n if (!stopProducer.save(stop, sharedPrefix, null, configuration.isKeepOriginalId(), configuration.isUseTpegHvt())) {\r\n iterator.remove();\r\n } else {\r\n if (metadata != null && stop.hasCoordinates())\r\n metadata.getSpatialCoverage().update(stop.getLongitude().doubleValue(), stop.getLatitude().doubleValue());\r\n }\r\n }\r\n for (StopArea stop : physicalStops) {\r\n stopProducer.save(stop, sharedPrefix, commercialStops, configuration.isKeepOriginalId(), configuration.isUseTpegHvt());\r\n if (metadata != null && stop.hasCoordinates())\r\n metadata.getSpatialCoverage().update(stop.getLongitude().doubleValue(), stop.getLatitude().doubleValue());\r\n }\r\n for (ConnectionLink link : connectionLinks) {\r\n if (!physicalStops.contains(link.getStartOfLink()) && !commercialStops.contains(link.getStartOfLink())) {\r\n continue;\r\n } else if (!physicalStops.contains(link.getEndOfLink()) && !commercialStops.contains(link.getEndOfLink())) {\r\n continue;\r\n }\r\n transferProducer.save(link, sharedPrefix, configuration.isKeepOriginalId());\r\n }\r\n for (Interchange interchange : interchanges) {\r\n if (isInterchangeValid(interchange)) {\r\n transferProducer.save(interchange, sharedPrefix, configuration.isKeepOriginalId());\r\n }\r\n }\r\n for (Company company : companies) {\r\n agencyProducer.save(company, prefix, timezone, configuration.isKeepOriginalId());\r\n }\r\n for (List tms : timetables.values()) {\r\n calendarProducer.save(tms, sharedPrefix, configuration.isKeepOriginalId());\r\n if (metadata != null) {\r\n for (Timetable tm : tms) {\r\n metadata.getTemporalCoverage().update(tm.getStartOfPeriod(), tm.getEndOfPeriod());\r\n }\r\n }\r\n }\r\n for (DatedServiceJourney datedServiceJourney : datedServiceJourneys) {\r\n if (datedServiceJourney.isNeitherCancelledNorReplaced()) {\r\n CalendarDay calendarDay = new CalendarDay();\r\n calendarDay.setDate(datedServiceJourney.getOperatingDay());\r\n calendarDay.setIncluded(true);\r\n calendarProducer.saveDay(datedServiceJourney.getVehicleJourney().getObjectId(), calendarDay);\r\n }\r\n }\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "private void readBlock(final boolean decompress) throws IOException{\r\n if (in == null) {\r\n throw new IOException(\"Input buffer is closed\");\r\n }\r\n if (!isCompressed || (currBlkIdx == -1)) {\r\n readFully(blockBuffer, 0, blockSize);\r\n bytesRead += blockSize;\r\n } else {\r\n readFully(blockBuffer, 0, 4);\r\n bytesRead += 4;\r\n final int h = DumpArchiveUtil.convert32(blockBuffer, 0);\r\n final boolean compressed = (h & 0x01) == 0x01;\r\n if (!compressed) {\r\n readFully(blockBuffer, 0, blockSize);\r\n bytesRead += blockSize;\r\n } else {\r\n final int flags = (h >> 1) & 0x07;\r\n int length = (h >> 4) & 0x0FFFFFFF;\r\n final byte[] compBuffer = readRange(length);\r\n bytesRead += length;\r\n if (!decompress) {\r\n Arrays.fill(blockBuffer, (byte) 0);\r\n } else {\r\n switch(DumpArchiveConstants.COMPRESSION_TYPE.find(flags & 0x03)) {\r\n case ZLIB:\r\n final Inflater inflator = new Inflater();\r\n try {\r\n inflator.setInput(compBuffer, 0, compBuffer.length);\r\n length = inflator.inflate(blockBuffer);\r\n if (length != blockSize) {\r\n throw new ShortFileException();\r\n }\r\n } catch (final DataFormatException e) {\r\n throw new DumpArchiveException(\"Bad data\", e);\r\n } finally {\r\n inflator.end();\r\n }\r\n break;\r\n case BZLIB:\r\n throw new UnsupportedCompressionAlgorithmException(\"BZLIB2\");\r\n case LZO:\r\n throw new UnsupportedCompressionAlgorithmException(\"LZO\");\r\n default:\r\n throw new UnsupportedCompressionAlgorithmException();\r\n }\r\n }\r\n }\r\n }\r\n currBlkIdx++;\r\n readOffset = 0;\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public void doRightUpdates(NotNode notNode, LeftTupleSink sink, BetaMemory bm, ReteEvaluator reteEvaluator, TupleSets srcRightTuples, TupleSets trgLeftTuples, TupleSets stagedLeftTuples){\r\n TupleMemory ltm = bm.getLeftTupleMemory();\r\n TupleMemory rtm = bm.getRightTupleMemory();\r\n ContextEntry[] contextEntry = bm.getContext();\r\n BetaConstraints constraints = notNode.getRawConstraints();\r\n boolean iterateFromStart = notNode.isIndexedUnificationJoin() || rtm.getIndexType().isComparison();\r\n for (RightTuple rightTuple = srcRightTuples.getUpdateFirst(); rightTuple != null; ) {\r\n RightTuple next = rightTuple.getStagedNext();\r\n if (ltm != null && ltm.size() > 0) {\r\n constraints.updateFromFactHandle(contextEntry, reteEvaluator, rightTuple.getFactHandleForEvaluation());\r\n FastIterator leftIt = notNode.getLeftIterator(ltm);\r\n LeftTuple firstLeftTuple = notNode.getFirstLeftTuple(rightTuple, ltm, leftIt);\r\n for (LeftTuple leftTuple = firstLeftTuple; leftTuple != null; ) {\r\n LeftTuple temp = (LeftTuple) leftIt.next(leftTuple);\r\n if (leftTuple.getStagedType() == LeftTuple.UPDATE) {\r\n leftTuple = temp;\r\n continue;\r\n }\r\n if (constraints.isAllowedCachedRight(contextEntry, leftTuple)) {\r\n leftTuple.setBlocker(rightTuple);\r\n rightTuple.addBlocked(leftTuple);\r\n ltm.remove(leftTuple);\r\n LeftTuple childLeftTuple = leftTuple.getFirstChild();\r\n if (childLeftTuple != null) {\r\n childLeftTuple.setPropagationContext(rightTuple.getPropagationContext());\r\n RuleNetworkEvaluator.unlinkAndDeleteChildLeftTuple(childLeftTuple, trgLeftTuples, stagedLeftTuples);\r\n }\r\n }\r\n leftTuple = temp;\r\n }\r\n }\r\n iterateFromStart = updateBlockersAndPropagate(notNode, rightTuple, reteEvaluator, rtm, contextEntry, constraints, iterateFromStart, sink, trgLeftTuples, ltm);\r\n rightTuple.clearStaged();\r\n rightTuple = next;\r\n }\r\n constraints.resetFactHandle(contextEntry);\r\n constraints.resetTuple(contextEntry);\r\n}", "smellKey": "S3776", "smellId": null, "repo": NaN, "language": "java"} {"function": "public function creating(Campaign $campaign): void\n {\n if (is_null($campaign->user_id) && ! is_null(auth()->user())) {\n $campaign->user_id = auth()->user()->id;\n }\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(ContentService $contentService, Filter $filter, ?array $languages = null)\n {\n $this->contentService = $contentService;\n $this->filter = $filter;\n $this->languages = $languages;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('reports', function (Blueprint $table) {\n $table->uuid('id')->primary();\n\n $table->string('name');\n $table->text('description')->nullable();\n $table->json('filters')->nullable();\n $table->json('columns');\n $table->string('model');\n\n $table->foreignUuid('user_id')->constrained('users');\n\n $table->timestamps();\n $table->softDeletes();\n });\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(\n URLAliasServiceInterface $innerService,\n EventDispatcherInterface $eventDispatcher\n ) {\n parent::__construct($innerService);\n\n $this->eventDispatcher = $eventDispatcher;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function products()\n {\n return $this->belongsToMany(Product::class, 'product_attributes')\n ->withPivot('value');\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function __construct(Brand $brand, $domainId)\n {\n $this->brand = $brand;\n $this->domainId = $domainId;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(\n ContentTypeService $contentTypeService,\n UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,\n ContentTypeIconResolver $contentTypeIconResolver,\n UrlGeneratorInterface $urlGenerator,\n EventDispatcherInterface $eventDispatcher\n ) {\n $this->contentTypeService = $contentTypeService;\n $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;\n $this->contentTypeIconResolver = $contentTypeIconResolver;\n $this->urlGenerator = $urlGenerator;\n $this->eventDispatcher = $eventDispatcher;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function getDataForQueryResource(mixed $data, Concrete $object = null, array $params = []): mixed;", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function supportsNormalization($data, string $format = null)\n {\n return $data instanceof Host;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testCreateSuiviInstance(): void\n {\n $suiviFactory = new SuiviFactory();\n $signalement = $this->createMock(Signalement::class);\n\n $suivi = $suiviFactory->createInstanceFrom($this->security->getUser(), $signalement, []);\n\n $this->assertInstanceOf(Suivi::class, $suivi);\n $this->assertEquals('', $suivi->getDescription());\n $this->assertFalse($suivi->getIsPublic());\n $this->assertInstanceOf(UserInterface::class, $suivi->getCreatedBy());\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function toEmail(object $notifiable): MailMessage\n {\n return MailMessage::make()\n ->settings($this->resolveNotificationSetting($notifiable))\n ->subject('The following engagement failed to be delivered.')\n ->line(\"The engagement with the following contents was unable to be delivered to {$this->engagement->recipient->display_name}.\")\n ->line('Subject: ' . ($this->engagement->subject ?? 'n/a'))\n ->line('Body: ' . $this->engagement->getBody());\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __toString(): string\n {\n return $this->bailleur->getName().'-'.$this->getTerritory()->getName();\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function getUrl()\n {\n return $this->url;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(private readonly ResponseRenderer $response)\n {\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function account(): BelongsTo\n {\n return $this->belongsTo(Account::class);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function __construct(\n URLWildcard $urlWildcard\n ) {\n $this->urlWildcard = $urlWildcard;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function viewAny(Authenticatable $authenticatable): Response\n {\n return $authenticatable->canOrElse(\n abilities: 'prompt.view-any',\n denyResponse: 'You do not have permission to view prompts.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function updateFieldsTo(?string $initialLanguageCode, array $fields): self\n {\n $languageCodes = array_map(\n static function (Field $field) {\n return $field->languageCode;\n },\n $fields\n );\n\n $this->targetVersionProperties['forUpdateInitialLanguageCode'] = $initialLanguageCode;\n $this->targetVersionProperties['forUpdateLanguageCodesList'] = array_values(\n array_unique($languageCodes)\n );\n\n return $this;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setAanmeldenVanaf(DateTimeImmutable $aanmeldenVanaf): void;", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function handle(\n OrderProcessingData $orderProcessingData,\n OrderProcessingStack $orderProcessingStack,\n ): OrderProcessingData {\n $orderData = $orderProcessingData->orderData;\n\n $payment = $orderData->payment;\n $currency = $this->currencyFacade->getDomainDefaultCurrencyByDomainId($orderProcessingData->getDomainId());\n\n if (!$payment?->isCzkRounding() || $currency->getCode() !== Currency::CODE_CZK) {\n return $orderProcessingStack->processNext($orderProcessingData);\n }\n\n $priceWithVat = $orderData->totalPrice->getPriceWithVat();\n $roundedPriceWithVat = $priceWithVat->round(0);\n\n $roundingPriceAmount = $this->rounding->roundPriceWithVatByCurrency(\n $roundedPriceWithVat->subtract($priceWithVat),\n $currency,\n );\n\n $roundingPrice = new Price($roundingPriceAmount, $roundingPriceAmount);\n\n if (!$roundingPrice->isZero()) {\n $orderData->addItem($this->createRoundingItemData($roundingPrice, $orderProcessingData->getDomainConfig()));\n $orderData->addTotalPrice($roundingPrice, OrderItemTypeEnum::TYPE_ROUNDING);\n }\n\n return $orderProcessingStack->processNext($orderProcessingData);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testEscalations_checkScenario4() {\n\t\t$this->clearLog(self::COMPONENT_SERVER);\n\t\t$response = $this->call('action.update', [\n\t\t\t'actionid' => self::$trigger_actionid,\n\t\t\t'operations' => [\n\t\t\t\t[\n\t\t\t\t\t'esc_period' => '1m',\n\t\t\t\t\t'esc_step_from' => 1,\n\t\t\t\t\t'esc_step_to' => 1,\n\t\t\t\t\t'evaltype' => 0,\n\t\t\t\t\t'operationtype' => OPERATION_TYPE_MESSAGE,\n\t\t\t\t\t'opmessage' => [\n\t\t\t\t\t\t'default_msg' => 0,\n\t\t\t\t\t\t'mediatypeid' => 1,\n\t\t\t\t\t\t'message' => 'Problem',\n\t\t\t\t\t\t'subject' => 'Problem'\n\t\t\t\t\t],\n\t\t\t\t\t'opmessage_grp' => [['usrgrpid' => 7]]\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t'esc_period' => '1m',\n\t\t\t\t\t'esc_step_from' => 2,\n\t\t\t\t\t'esc_step_to' => 2,\n\t\t\t\t\t'evaltype' => 0,\n\t\t\t\t\t'operationtype' => OPERATION_TYPE_MESSAGE,\n\t\t\t\t\t'opmessage' => [\n\t\t\t\t\t\t'default_msg' => 0,\n\t\t\t\t\t\t'mediatypeid' => 1,\n\t\t\t\t\t\t'message' => 'Problem',\n\t\t\t\t\t\t'subject' => 'Problem'\n\t\t\t\t\t],\n\t\t\t\t\t'opmessage_grp' => [['usrgrpid' => 7]]\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\n\t\t$this->assertArrayHasKey('actionids', $response['result']);\n\t\t$this->assertArrayHasKey(0, $response['result']['actionids']);\n\t\t$response = $this->call('user.update', [\n\t\t\t'userid' => 1,\n\t\t\t'medias' => [\n\t\t\t\t[\n\t\t\t\t\t'mediatypeid' => 1,\n\t\t\t\t\t'sendto' => 'test@local.local'\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\t\t$this->assertArrayHasKey('userids', $response['result']);\n\t\t$this->assertArrayHasKey(0, $response['result']['userids']);\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 6);\n\n\t\t$response = $this->call('trigger.update', [\n\t\t\t'triggerid' => self::$triggerid,\n\t\t\t'status' => 1\n\t\t]);\n\t\t$this->assertArrayHasKey('triggerids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['triggerids']));\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->waitForLogLineToBePresent(self::COMPONENT_SERVER, 'End of escalation_cancel()', true, 120);\n\n\t\t$response = $this->callUntilDataIsPresent('alert.get', [\n\t\t\t'actionids' => [self::$trigger_actionid],\n\t\t\t'sortfield' => 'alertid'\n\t\t], 5, 2);\n\t\t$esc_msg = 'NOTE: Escalation canceled';\n\t\t$this->assertArrayHasKey(1, $response['result']);\n\t\t$this->assertEquals(0, strncmp($esc_msg, $response['result'][1]['message'], strlen($esc_msg)));\n\n\t\t// trigger value is not updated during configuration cache sync (only initialized)\n\t\t// therefore need to restore it manually by sending OK value\n\t\t$response = $this->call('trigger.update', [\n\t\t\t'triggerid' => self::$triggerid,\n\t\t\t'status' => 0\n\t\t]);\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 0);\n\n\t\t// test ability to disable notifications about cancelled escalations\n\t\t$response = $this->call('action.update', [\n\t\t\t'actionid' => self::$trigger_actionid,\n\t\t\t'notify_if_canceled' => 0\n\t\t]);\n\t\t$this->assertArrayHasKey('actionids', $response['result']);\n\t\t$this->assertArrayHasKey(0, $response['result']['actionids']);\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 10);\n\n\t\t$response = $this->call('trigger.update', [\n\t\t\t'triggerid' => self::$triggerid,\n\t\t\t'status' => 1\n\t\t]);\n\n\t\t$this->assertArrayHasKey('triggerids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['triggerids']));\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->waitForLogLineToBePresent(self::COMPONENT_SERVER, 'End of escalation_cancel()', true, 120);\n\n\t\t$response = $this->callUntilDataIsPresent('alert.get', [\n\t\t\t'actionids' => [self::$trigger_actionid],\n\t\t\t'sortfield' => 'alertid',\n\t\t\t'sortorder' => 'DESC'\n\t\t], 5, 2);\n\t\t$this->assertArrayHasKey(0, $response['result']);\n\t\t$this->assertNotEquals(0, strncmp($esc_msg, $response['result'][0]['message'], strlen($esc_msg)));\n\n\t\t// revert to defaults, restore trigger status and value\n\t\t$response = $this->call('action.update', [\n\t\t\t'actionid' => self::$trigger_actionid,\n\t\t\t'notify_if_canceled' => 1\n\t\t]);\n\t\t$this->assertArrayHasKey('actionids', $response['result']);\n\t\t$this->assertArrayHasKey(0, $response['result']['actionids']);\n\n\t\t$response = $this->call('trigger.update', [\n\t\t\t'triggerid' => self::$triggerid,\n\t\t\t'status' => 0\n\t\t]);\n\t\t$this->assertArrayHasKey('triggerids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['triggerids']));\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 0);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function __construct(public DatabaseName $database, public TableName $designerSettings)\n {\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function (ProductVideoData $productVideoData) {\n return (bool)$productVideoData->id;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function supportsClassProvider(): array\n {\n return [\n [SymfonyUserInterface::class, false],\n [MVCUser::class, true],\n [get_class($this->createMock(MVCUser::class)), true],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function createInstance(RemoteWebElement $element, $options = []) {\n\t\t$instance = parent::createInstance($element, $options);\n\n\t\tif ($instance->mode === null) {\n\t\t\t$instance->mode = self::$default_mode;\n\t\t}\n\n\t\treturn $instance;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function find(string $type): ?TransactionType\n {\n return TransactionType::whereType(ucfirst($type))->first();\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function (Blueprint $table) {\n $table->unsignedInteger('vlan')->nullable();\n $table->string('time_elapsed', 50)->nullable();\n $table->string('time_left', 50)->nullable()->change();\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "private function getProvider(string $identifier): VariableProvider\n {\n return new class($identifier) implements VariableProvider {\n private $identifier;\n\n public function __construct(string $identifier)\n {\n $this->identifier = $identifier;\n }\n\n public function getIdentifier(): string\n {\n return $this->identifier;\n }\n\n public function getTwigVariables(View $view, array $options = []): object\n {\n return (object)[\n $this->identifier . '_parameter' => $this->identifier . '_value',\n ];\n }\n };\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function getSubscribedEvents(): array\n {\n return [\n ConfigResolveEvent::NAME => ['onUdwConfigResolve'],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __toString(): string\n {\n return $this->name;\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function testCreateProxyCacheResolver()\n {\n $this->configResolver\n ->expects(self::at(0))\n ->method('hasParameter')\n ->with('image_host')\n ->willReturn(true);\n\n $host = 'http://ibexa.co';\n\n $this->configResolver\n ->expects(self::at(1))\n ->method('getParameter')\n ->with('image_host')\n ->willReturn($host);\n\n $expected = new ProxyResolver($this->resolver, [$host]);\n\n self::assertEquals($expected, $this->factory->createCacheResolver());\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct(array $map = [])\n {\n $this->map = $map;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function isSupportedOrientation(string $orientation): bool\n {\n return in_array($orientation, self::ALLOWED_ORIENTATIONS, true);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function down(): void\n {\n Schema::dropIfExists('page_translations');\n Schema::table('pages', function (Blueprint $table) {\n $table->string('visit_intro')->nullable();\n $table->string('visit_hour_header')->nullable();\n $table->string('visit_hour_subheader')->nullable();\n $table->string('visit_city_pass_title')->nullable();\n $table->text('visit_city_pass_text')->nullable();\n $table->string('visit_city_pass_button_label')->nullable();\n $table->text('visit_admission_description')->nullable();\n $table->string('visit_buy_tickets_label')->nullable();\n $table->string('visit_become_member_label')->nullable();\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function getBreadcrumbs()\n\t{\n\t\treturn 'Maaltijden / Beheer';\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function testDashboardPlainTextWidget_Cancel($data) {\n\t\t$old_hash = CDBHelper::getHash($this->sql);\n\t\t$new_name = 'Widget to be cancelled';\n\n\t\t$this->page->login()->open('zabbix.php?action=dashboard.view&dashboardid='.self::$dashboardid)->waitUntilReady();\n\t\t$dashboard = CDashboardElement::find()->one()->edit();\n\t\t$old_widget_count = $dashboard->getWidgets()->count();\n\n\t\t// Start updating or creating a widget.\n\t\tif (CTestArrayHelper::get($data, 'update', false)) {\n\t\t\t$form = $dashboard->getWidget(self::DEFAULT_WIDGET)->edit();\n\t\t}\n\t\telse {\n\t\t\t$form = $dashboard->addWidget()->asForm();\n\t\t\t$form->fill(['Type' => CFormElement::RELOADABLE_FILL('Plain text')]);\n\t\t}\n\t\t$form->fill([\n\t\t\t'Name' => $new_name,\n\t\t\t'Refresh interval' => '15 minutes',\n\t\t\t'Items' => 'Linux: Available memory'\n\t\t]);\n\n\t\t// Save or cancel widget.\n\t\tif (CTestArrayHelper::get($data, 'save_widget', false)) {\n\t\t\t$form->submit();\n\n\t\t\t// Check that changes took place on the unsaved dashboard.\n\t\t\t$this->assertTrue($dashboard->getWidget($new_name)->isVisible());\n\t\t}\n\t\telse {\n\t\t\t$dialog = COverlayDialogElement::find()->one();\n\t\t\t$dialog->query('button:Cancel')->one()->click();\n\t\t\t$dialog->ensureNotPresent();\n\n\t\t\tif (CTestArrayHelper::get($data, 'update', false)) {\n\t\t\t\tforeach ([self::DEFAULT_WIDGET => true, $new_name => false] as $name => $valid) {\n\t\t\t\t\t$dashboard->getWidget($name, false)->isValid($valid);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$this->assertEquals($old_widget_count, $dashboard->getWidgets()->count());\n\t\t}\n\n\t\t// Save or cancel dashboard update.\n\t\tif (CTestArrayHelper::get($data, 'save_dashboard', false)) {\n\t\t\t$dashboard->save();\n\t\t}\n\t\telse {\n\t\t\t$dashboard->cancelEditing();\n\t\t}\n\n\t\t// Check that no changes were made to the widget.\n\t\t$this->assertEquals($old_hash, CDBHelper::getHash($this->sql));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "#[Route(path: '/superadmin/css-documentation/')]\n public function cssDocumentationAction()\n {\n return $this->render('@ShopsysFramework/Admin/Content/Superadmin/cssDocumentation.html.twig');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('campaign_actions', function (Blueprint $table) {\n $table->uuid('id')->primary();\n $table->foreignUuid('campaign_id')->constrained('campaigns');\n $table->string('type');\n $table->json('data');\n $table->timestamp('execute_at');\n $table->timestamp('last_execution_attempt_at')->nullable();\n $table->text('last_execution_attempt_error')->nullable();\n $table->timestamp('successfully_executed_at')->nullable();\n $table->timestamps();\n $table->softDeletes();\n });\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "protected function getSchemaFileBasePath(string $resourceType, string $format): string\n {\n return dirname(__DIR__) . '/Resources/REST/Schemas/' . $resourceType;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n protected readonly ProductAdvancedSearchFormFactory $advancedSearchFormFactory,\n protected readonly AdvancedSearchQueryBuilderExtender $advancedSearchQueryBuilderExtender,\n protected readonly ProductListAdminFacade $productListAdminFacade,\n protected readonly RuleFormViewDataFactory $ruleFormViewDataFactory,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function updateFrameworkBundleVersion(string $content, Version $version): string\n {\n return Strings::replace(\n $content,\n self::FRAMEWORK_BUNDLE_VERSION_PATTERN,\n function ($match) use ($version) {\n return str_replace($match[1], $version->getVersionString(), $match[0]);\n },\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testVeeamVmBackupCompletedWarning(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:46024->[1.1.1.1]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 4:13:08:37.60\nSNMPv2-MIB::snmpTrapOID.0 VEEAM-MIB::onVmBackupCompleted\nVEEAM-MIB::backupJobName Linux taeglich low\nVEEAM-MIB::vmName vmname1\nVEEAM-MIB::sourceHostName hostname\nVEEAM-MIB::vmBackupComment comment\nVEEAM-MIB::vmBackupResult Warning\nTRAP,\n 'SNMP Trap: VM backup Warning - vmname1 Job: Linux taeglich low - comment',\n 'Could not handle VEEAM-MIB::traps backup completed warning',\n [Severity::Warning, 'backup'],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function evaluate(APILimitationValue $value, APIUserReference $currentUser, ValueObject $object, array $targets = null): bool\n {\n if (!$value instanceof APIBlockingLimitation) {\n throw new InvalidArgumentException('$value', 'Must be of type: BlockingLimitation');\n }\n\n return false;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setFillMode($mode) {\n\t\t$this->mode = $mode;\n\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function up(): void\n {\n DB::update(\"update mediables set mediable_type = 'blocks' where mediable_type = ?\", ['A17\\CmsToolkit\\Models\\Block']);\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n createDefaultRelationshipTableFields($table, 'selection', 'video');\n $table->integer('position')->unsigned()->index();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function iterate()\n {\n $batchResult = $this->productInputPriceFacade->replaceBatchVatAndRecalculateInputPrices();\n\n if ($batchResult) {\n $this->logger->debug('Batch is done');\n } else {\n $deletedVatsCount = $this->vatFacade->deleteAllReplacedVats();\n $this->logger->debug('All vats are replaced');\n $this->logger->info('Deleted ' . $deletedVatsCount . ' vats');\n }\n\n return $batchResult;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getImagesCountByEntityIndexedById(string $entityName, int $entityId, ?string $type = null): int\n {\n $queryBuilder = $this->em->createQueryBuilder()\n ->select('COUNT(i)')\n ->from(Image::class, 'i', 'i.id')\n ->andWhere('i.entityName = :entityName')->setParameter('entityName', $entityName)\n ->andWhere('i.entityId = :entityId')->setParameter('entityId', $entityId);\n\n if ($type === null) {\n $queryBuilder->andWhere('i.type IS NULL');\n } else {\n $queryBuilder->andWhere('i.type = :type')->setParameter('type', $type);\n }\n\n return $queryBuilder->getQuery()->getSingleScalarResult();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testProductQuantityIsChangedInExistingCart(): void\n {\n $initialProductQuantity = 2;\n $newlyCreatedCart = $this->addTestingProductToNewCart($initialProductQuantity);\n\n $desiredProductQuantity = 3;\n\n $response = $this->getResponseContentForGql(__DIR__ . '/../_graphql/mutation/AddToCartMutation.graphql', [\n 'cartUuid' => $newlyCreatedCart['uuid'],\n 'productUuid' => $this->testingProduct->getUuid(),\n 'quantity' => $desiredProductQuantity,\n 'isAbsoluteQuantity' => true,\n ]);\n\n self::assertEquals($newlyCreatedCart['uuid'], $response['data']['AddToCart']['cart']['uuid']);\n\n $cart = $this->cartFacade->findCartByCartIdentifier($newlyCreatedCart['uuid']);\n self::assertNotNull($cart);\n\n $cartItems = $cart->getItems();\n self::assertCount(1, $cartItems);\n self::assertEquals($desiredProductQuantity, $cartItems[0]->getQuantity());\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (): int {\n return LicenseType::ConversationalAi->getSeatsInUse();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function setPlacement($placement)\n {\n $this->placement = $placement;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testOnSiteAccessMatch(SiteAccess $siteAccess, $configuredSessionStorageOptions, array $expectedSessionStorageOptions): void\n {\n $request = new Request();\n $request->setSession(new Session(new MockArraySessionStorage()));\n\n $this->sessionStorage\n ->expects(self::once())\n ->method('setOptions')\n ->with($expectedSessionStorageOptions);\n $this->configResolver\n ->expects(self::once())\n ->method('getParameter')\n ->with('session')\n ->will(self::returnValue($configuredSessionStorageOptions));\n\n $listener = new SessionSetDynamicNameListener($this->configResolver, $this->sessionStorageFactory);\n $listener->onSiteAccessMatch(new PostSiteAccessMatchEvent($siteAccess, $request, HttpKernelInterface::MAIN_REQUEST));\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function load(ObjectManager $manager): void\n {\n $mainPageBlogCategory = $this->blogCategoryFacade->getById(BlogCategory::BLOG_MAIN_PAGE_CATEGORY_ID);\n $mainPageBlogCategoryData = $this->blogCategoryDataFactory->createFromBlogCategory($mainPageBlogCategory);\n $mainPageBlogCategoryData->uuid = Uuid::uuid5(self::UUID_NAMESPACE, 'Main blog page')->toString();\n\n foreach ($this->domainsForDataFixtureProvider->getAllowedDemoDataDomains() as $domainConfig) {\n $locale = $domainConfig->getLocale();\n $domainId = $domainConfig->getId();\n\n $mainPageBlogCategoryData->names[$locale] = t('Main blog page - %locale%', ['%locale%' => $locale], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $mainPageBlogCategoryData->descriptions[$locale] = t('description - Main blog page - %locale%', ['%locale%' => $locale], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $mainPageBlogCategoryData->seoH1s[$domainId] = t('Main blog page - %locale% - H1', ['%locale%' => $locale], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $mainPageBlogCategoryData->seoMetaDescriptions[$domainId] = t('Main blog page - %locale% - meta description', ['%locale%' => $locale], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $mainPageBlogCategoryData->seoTitles[$domainId] = t('Main blog page - %locale% - Title', ['%locale%' => $locale], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n }\n $this->blogCategoryFacade->edit($mainPageBlogCategory->getId(), $mainPageBlogCategoryData);\n\n $this->addReference(self::FIRST_DEMO_BLOG_CATEGORY, $mainPageBlogCategory);\n\n //only in main category\n for ($i = 0; $i < self::PAGES_IN_CATEGORY; $i++) {\n $blogArticleData = $this->createArticle([$mainPageBlogCategory]);\n $blogArticle = $this->blogArticleFacade->create($blogArticleData);\n\n if ($i === 0) {\n $this->addReference(self::FIRST_DEMO_BLOG_ARTICLE, $blogArticle);\n }\n }\n\n $firstSubcategoryData = $this->createSubcategory($mainPageBlogCategory, 1);\n $firstSubcategory = $this->blogCategoryFacade->create($firstSubcategoryData);\n $this->addReference(self::FIRST_DEMO_BLOG_SUBCATEGORY, $firstSubcategory);\n\n //in first subcategory\n for ($i = 0; $i < self::PAGES_IN_CATEGORY; $i++) {\n $blogArticleData = $this->createArticle([$mainPageBlogCategory, $firstSubcategory]);\n\n if ($i === self::PAGES_IN_CATEGORY - 1) {\n $blogArticleData->visibleOnHomepage = false;\n }\n $this->blogArticleFacade->create($blogArticleData);\n }\n\n $secondSubcategoryData = $this->createSubcategory($mainPageBlogCategory, 2);\n $secondSubcategory = $this->blogCategoryFacade->create($secondSubcategoryData);\n $this->addReference(self::SECOND_DEMO_BLOG_SUBCATEGORY, $secondSubcategory);\n\n //in second subcategory\n for ($i = 0; $i < self::PAGES_IN_CATEGORY; $i++) {\n $blogArticleData = $this->createArticle([$mainPageBlogCategory, $secondSubcategory]);\n\n if ($i === self::PAGES_IN_CATEGORY - 1) {\n $blogArticleData->visibleOnHomepage = false;\n }\n $this->blogArticleFacade->create($blogArticleData);\n }\n\n $this->createBlogArticleForSearchingTest();\n $this->createBlockArticleForProductsTest();\n $this->createBlockArticleWithGrapesJs();\n\n $this->blogVisibilityFacade->refreshBlogArticlesVisibility();\n $this->blogVisibilityFacade->refreshBlogCategoriesVisibility();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function setParentLocator(VisibleCSSLocator $locator): void\n {\n parent::setParentLocator($locator);\n $this->table = $this->tableBuilder\n ->newTable()\n ->withParentLocator($this->parentLocator)\n ->withRowLocator($this->getLocator('relationRow'))\n ->withColumnLocator($this->getLocator('columnHeader'))\n ->build();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function updateObjectState(\n ObjectState $objectState,\n ObjectStateUpdateStruct $objectStateUpdateStruct\n ): ObjectState {\n $eventData = [\n $objectState,\n $objectStateUpdateStruct,\n ];\n\n $beforeEvent = new BeforeUpdateObjectStateEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return $beforeEvent->getUpdatedObjectState();\n }\n\n $updatedObjectState = $beforeEvent->hasUpdatedObjectState()\n ? $beforeEvent->getUpdatedObjectState()\n : $this->innerService->updateObjectState($objectState, $objectStateUpdateStruct);\n\n $this->eventDispatcher->dispatch(\n new UpdateObjectStateEvent($updatedObjectState, ...$eventData)\n );\n\n return $updatedObjectState;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getTotalCount(): int\n {\n return count($this->loadList());\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct(\n private readonly FlagFacade $flagFacade,\n private readonly FlagDataFactory $flagDataFactory,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function getFormKitSchema(SubmissibleField $field): array\n {\n return [\n '$formkit' => 'email',\n 'label' => $field->label,\n 'name' => $field->getKey(),\n ...($field->is_required ? ['validation' => 'required'] : []),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n $this->sql('\n CREATE TABLE categories_top (\n category_id INT NOT NULL,\n domain_id INT NOT NULL,\n position INT NOT NULL,\n PRIMARY KEY(category_id, domain_id)\n )');\n $this->sql('CREATE INDEX IDX_20AA436212469DE2 ON categories_top (category_id)');\n $this->sql('\n ALTER TABLE\n categories_top\n ADD\n CONSTRAINT FK_20AA436212469DE2 FOREIGN KEY (category_id)\n REFERENCES categories (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function down(): void\n {\n Schema::table('hrSystem', function (Blueprint $table) {\n $table->integer('hrSystemNumUsers')->default(0)->change();\n $table->integer('hrSystemProcesses')->default(0)->change();\n $table->integer('hrSystemMaxProcesses')->default(0)->change();\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function __construct(StorageGateway $gateway)\n {\n $this->gateway = $gateway;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testIpsSignature(): void\n {\n $device = Device::factory()->create(); /** @var Device $device */\n $ipv4 = Ipv4Address::factory()->make(); /** @var Ipv4Address $ipv4 */\n $this->assertTrapLogsMessage(\"{{ hostname }}\nUDP: [{{ ip }}]:57602->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 302:12:56:24.81\nSNMPv2-MIB::snmpTrapOID.0 FORTINET-FORTIGATE-MIB::fgTrapIpsSignature\nFORTINET-CORE-MIB::fnSysSerial.0 $device->serial\nSNMPv2-MIB::sysName.0 $device->hostname\nFORTINET-FORTIGATE-MIB::fgIpsTrapSigId.0 47173\nFORTINET-FORTIGATE-MIB::fgIpsTrapSrcIp.0 $ipv4->ipv4_address\nFORTINET-FORTIGATE-MIB::fgIpsTrapSigMsg.0 UPnP.SSDP.M.Search.Anomaly\",\n \"IPS signature UPnP.SSDP.M.Search.Anomaly detected from $ipv4->ipv4_address with Fortiguard ID 47173\",\n 'Could not handle fgTrapIpsSignature trap',\n [Severity::Warning],\n $device,\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "#[Route(path: '/slider/item/edit/{id}', requirements: ['id' => '\\d+'])]\n public function editAction(Request $request, $id)\n {\n $sliderItem = $this->sliderItemFacade->getById($id);\n $sliderItemData = $this->sliderItemDataFactory->createFromSliderItem($sliderItem);\n\n $form = $this->createForm(SliderItemFormType::class, $sliderItemData, [\n 'scenario' => SliderItemFormType::SCENARIO_EDIT,\n 'slider_item' => $sliderItem,\n ]);\n $form->handleRequest($request);\n\n if ($form->isSubmitted() && $form->isValid()) {\n $this->sliderItemFacade->edit($id, $sliderItemData);\n\n $this->addSuccessFlashTwig(\n t('Slider page {{ name }} modified'),\n [\n 'name' => $sliderItem->getName(),\n 'url' => $this->generateUrl('admin_slider_edit', ['id' => $sliderItem->getId()]),\n ],\n );\n\n return $this->redirectToRoute('admin_slider_list');\n }\n\n if ($form->isSubmitted() && !$form->isValid()) {\n $this->addErrorFlash(t('Please check the correctness of all data filled.'));\n }\n\n $this->breadcrumbOverrider->overrideLastItem(\n t('Editing slider page - %name%', ['%name%' => $sliderItem->getName()]),\n );\n\n return $this->render('@ShopsysFramework/Admin/Content/Slider/edit.html.twig', [\n 'form' => $form->createView(),\n 'sliderItem' => $sliderItem,\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function load(): array\n {\n return $this->getThumbnails();\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct()\n {\n parent::__construct();\n\n $this->middleware(\n static function ($request, $next) {\n app('view')->share('title', (string)trans('firefly.administration'));\n app('view')->share('mainTitleIcon', 'fa-hand-spock-o');\n\n return $next($request);\n }\n );\n $this->middleware(IsDemoUser::class)->except(['index']);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function isEnabled($enabled = true) {\n\t\t$input = $this->query('xpath:.//input[not(@type=\"hidden\")]|textarea')->one(false);\n\t\tif (!$input->isEnabled($enabled)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$multiselect = $this->query('class:multiselect')->one(false);\n\t\tif ($multiselect->isValid() && ($multiselect->getAttribute('aria-disabled') === 'true') === $enabled) {\n\t\t\treturn false;\n\t\t}\n\n\t\tforeach ($this->getControls() as $control) {\n\t\t\tif ($control->isEnabled() !== $enabled) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function __construct(\n ?ContentType $contentType,\n ?ContentTypeGroup $contentTypeGroup\n ) {\n $this->contentType = $contentType;\n $this->contentTypeGroup = $contentTypeGroup;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "private function fillDatasets($data_sets) {\n\t\t$form = $this->query('id:widget-dialogue-form')->asForm()->one();\n\t\tif ($data_sets) {\n\t\t\tif (CTestArrayHelper::isAssociative($data_sets)) {\n\t\t\t\t$data_sets = [$data_sets];\n\t\t\t}\n\n\t\t\t$last = count($data_sets) - 1;\n\t\t\t// Amount of data sets on frontend.\n\t\t\t$count_sets = $form->query('xpath://li[contains(@class, \"list-accordion-item\")]')->all()->count();\n\n\t\t\tforeach ($data_sets as $i => $data_set) {\n\t\t\t\t$mapping = [\n\t\t\t\t\t'host' => 'xpath://div[@id=\"ds_'.$i.'_hosts_\"]/..',\n\t\t\t\t\t'item' => 'xpath://div[@id=\"ds_'.$i.'_items_\"]/..'\n\t\t\t\t];\n\t\t\t\t// If host or item of data set exist in data provider, add the xpath selector and value from data provider to them.\n\t\t\t\tforeach ($mapping as $field => $selector) {\n\t\t\t\t\tif (array_key_exists($field, $data_set)) {\n\t\t\t\t\t\t$data_set = [$selector => $data_set[$field]] + $data_set;\n\t\t\t\t\t\tunset($data_set[$field]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t$form->fill($data_set);\n\n\t\t\t\t// Open next dataset, if it exists on frontend.\n\t\t\t\tif ($i !== $last) {\n\t\t\t\t\tif ($i + 1 < $count_sets) {\n\t\t\t\t\t\t$i += 2;\n\t\t\t\t\t\t$form->query('xpath:(//li[contains(@class, \"list-accordion-item\")])['.$i.']//button')->one()->click();\n\t\t\t\t\t}\n\t\t\t\t\t// Press \"Add new data set\" button, except for last data set.\n\t\t\t\t\telse {\n\t\t\t\t\t\t$form->query('button:Add new data set')->one()->click();\n\t\t\t\t\t}\n\n\t\t\t\t\t$form->invalidate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function createGlobalUrlAlias(\n string $resource,\n string $path,\n string $languageCode,\n bool $forwarding = false,\n bool $alwaysAvailable = false\n ): URLAlias {\n $eventData = [\n $resource,\n $path,\n $languageCode,\n $forwarding,\n $alwaysAvailable,\n ];\n\n $beforeEvent = new BeforeCreateGlobalUrlAliasEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return $beforeEvent->getUrlAlias();\n }\n\n $urlAlias = $beforeEvent->hasUrlAlias()\n ? $beforeEvent->getUrlAlias()\n : $this->innerService->createGlobalUrlAlias($resource, $path, $languageCode, $forwarding, $alwaysAvailable);\n\n $this->eventDispatcher->dispatch(\n new CreateGlobalUrlAliasEvent($urlAlias, ...$eventData)\n );\n\n return $urlAlias;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function booleanWithDefaultTrueProvider(): iterable\n {\n yield 'null value' => [null, true];\n yield 'valid value' => [true, true];\n yield 'valid value 2' => [false, false];\n yield 'valid value with type coercion' => [0, false];\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function (Blueprint $table) {\n $table->string('locale', 7)->default($this->getCurrentLocale())->index();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function register()\n {\n Panel::configureUsing(fn (Panel $panel) => ($panel->getId() !== 'admin') || $panel->plugin(new IntegrationGoogleRecaptchaPlugin()));\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function discoverWirelessRsrp();", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function updateObjectStateGroup(\n ObjectStateGroup $objectStateGroup,\n ObjectStateGroupUpdateStruct $objectStateGroupUpdateStruct\n ): ObjectStateGroup {\n $eventData = [\n $objectStateGroup,\n $objectStateGroupUpdateStruct,\n ];\n\n $beforeEvent = new BeforeUpdateObjectStateGroupEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return $beforeEvent->getUpdatedObjectStateGroup();\n }\n\n $updatedObjectStateGroup = $beforeEvent->hasUpdatedObjectStateGroup()\n ? $beforeEvent->getUpdatedObjectStateGroup()\n : $this->innerService->updateObjectStateGroup($objectStateGroup, $objectStateGroupUpdateStruct);\n\n $this->eventDispatcher->dispatch(\n new UpdateObjectStateGroupEvent($updatedObjectStateGroup, ...$eventData)\n );\n\n return $updatedObjectStateGroup;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function applySelect(\n QueryBuilder $query,\n SortClause $sortClause,\n int $number\n ): array {\n $query\n ->addSelect(\n sprintf(\n 'c.id AS %s',\n $column = $this->getSortColumnName($number)\n )\n );\n\n return [$column];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getBailleur(): ?Bailleur\n {\n return $this->bailleur;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function getSeoMetaDescription()\n {\n return $this->seoMetaDescription;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(\n LanguageService $languageService,\n ConfigResolverInterface $configResolver,\n SiteAccessServiceInterface $siteAccessService,\n array $siteAccesses\n ) {\n $this->languageService = $languageService;\n $this->configResolver = $configResolver;\n $this->siteAccessService = $siteAccessService;\n $this->siteAccesses = $siteAccesses;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (Blueprint $table) {\n $table->dropColumn('google_2fa_enabled');\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "function (): int|string {\n $count = TrackedEventCount::where('type', TrackedEventType::AiThreadSaved)->first()?->count;\n\n return ! is_null($count) ? Number::abbreviate($count, maxPrecision: 2) : 'N/A';\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(protected readonly string $projectDir)\n {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function isTabSelected($name = null, $selected = true) {\n\t\t$tab = $this->getTab($name)->parents('tag:li')->one();\n\n\t\tif ($this->query('xpath:./nav')->one(false)->isValid()) {\n\t\t\treturn $tab->hasClass('selected') === $selected;\n\t\t}\n\n\t\treturn $tab->getAttribute('aria-selected') === json_encode($selected);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function testGetSubscribedEvents(): void\n {\n $listener = new SessionSetDynamicNameListener($this->configResolver, $this->sessionStorageFactory);\n\n self::assertSame(\n [\n MVCEvents::SITEACCESS => ['onSiteAccessMatch', 250],\n ],\n $listener->getSubscribedEvents()\n );\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getTimePeriodValidationUpdateData() {\n\t\t$data = [];\n\n\t\tforeach ($this->getTimePeriodValidationData() as $item) {\n\t\t\t$item[0]['Widget name'] = 'Test cases for update';\n\n\t\t\t$data[] = $item;\n\t\t}\n\n\t\treturn $data;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n createDefaultRelationshipTableFields($table, 'exhibition', 'video');\n $table->integer('position')->unsigned()->index();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function before(Authenticatable $authenticatable): ?Response\n {\n if (! is_null($response = $this->hasAnyLicense($authenticatable, [LicenseType::RetentionCrm, LicenseType::RecruitmentCrm]))) {\n return $response;\n }\n\n if (! is_null($response = $this->hasFeatures())) {\n return $response;\n }\n\n return null;\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function setValue(array $parameters): void\n {\n if (!$this->isRelationEmpty()) {\n $this->getHTMLPage()\n ->find($this->getLocator('buttonRemove'))\n ->execute(new MouseOverAndClick());\n }\n\n $buttonLocator = CSSLocatorBuilder::base($this->parentLocator)\n ->withDescendant($this->getLocator('selectContent'))\n ->build();\n\n $this->getHTMLPage()\n ->setTimeout(5)\n ->find($buttonLocator)\n ->execute(new MouseOverAndClick());\n\n $this->universalDiscoveryWidget->verifyIsLoaded();\n $this->universalDiscoveryWidget->selectContent($parameters['value']);\n $this->universalDiscoveryWidget->confirm();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function get($path, $urlParams = [])\n\t{\n\n\t\tif (empty($path)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!empty($urlParams)) {\n\t\t\t$urlParams = '?' . implode(\"&\", $urlParams);\n\t\t} else {\n\t\t\t$urlParams = \"\";\n\t\t}\n\n\t\t$this->requestUrl = $this->getFhirURL() . $path . $urlParams;\n\n\t\t$client = new Client();\n\t\t$headers = [\n\t\t\t'Content-Type' => $this->getContentType(),\n\t\t\t'Authorization' => $this->getBearerToken()\n\t\t];\n\n\t\t$request = new Request('GET', $this->requestUrl, $headers);\n\t\t$res = $client->sendAsync($request)->wait();\n\t\treturn $res->getBody()->getContents();\n\t}", "smellKey": "0", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "protected function createUserWithPolicies(\n string $login,\n array $policiesData,\n ?RoleLimitation $roleLimitation = null\n ): User {\n $ibexaTestCore = $this->getIbexaTestCore();\n $userService = $ibexaTestCore->getUserService();\n $roleService = $ibexaTestCore->getRoleService();\n\n $userCreateStruct = $userService->newUserCreateStruct(\n $login,\n \"$login@test.local\",\n $login,\n 'eng-GB'\n );\n $userCreateStruct->setField('first_name', $login);\n $userCreateStruct->setField('last_name', $login);\n $user = $userService->createUser($userCreateStruct, [$userService->loadUserGroup(4)]);\n\n $role = $this->createRoleWithPolicies(uniqid('role_for_' . $login . '_', true), $policiesData);\n $roleService->assignRoleToUser($role, $user, $roleLimitation);\n\n return $user;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "protected function getLanguagesMap(): array\n {\n $languagesMap = [];\n\n foreach ($this->languageService->loadLanguages() as $language) {\n $languagesMap[$language->languageCode] = [\n 'name' => $language->name,\n 'id' => $language->id,\n 'languageCode' => $language->languageCode,\n 'enabled' => $language->enabled,\n ];\n }\n\n return $languagesMap;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "private function getSiteAccessService(): SiteAccessService\n {\n $siteAccessService = new SiteAccessService($this->provider, $this->configResolver);\n $siteAccessService->setSiteAccess($this->siteAccess);\n\n return $siteAccessService;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function handle(DossierMessageSISH $dossierMessageSISH): void\n {\n $dossierMessageSISH->setAction($this->action);\n $this->response = $this->esaboraSISHService->pushAdresse($dossierMessageSISH);\n $dossierMessageSISH->setSasAdresse($this->response->getSasId());\n parent::handle($dossierMessageSISH);\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n createDefaultRelationshipTableFields($table, 'event', 'exhibition');\n $table->integer('position')->unsigned()->index();\n $table->timestamps();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function update(JobRunErrorLog $jobRunErrorLog): void\n {\n $this->pimcoreEntityManager->persist($jobRunErrorLog);\n $this->pimcoreEntityManager->flush();\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function down(): void\n {\n if (Schema::hasTable('mediables') && Schema::hasColumn('mediables', 'locale')) {\n Schema::table('mediables', function (Blueprint $table) {\n $table->dropIndex('mediables_locale_index');\n $table->dropColumn('locale');\n });\n }\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function getParameters();", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function provideInValidFieldSettings()\n {\n return [\n [\n [\n // isMultiple must be bool\n 'isMultiple' => 23,\n ],\n ],\n [\n [\n // options must be array\n 'options' => 23,\n ],\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getName(SPIValue $value, FieldDefinition $fieldDefinition, string $languageCode): string\n {\n return (string)$value;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function keyMatches($key)\n {\n return (self::REFERENCE_KEY == $key);\n }", "smellKey": "0", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function delete(Authenticatable $authenticatable, Prompt $prompt): Response\n {\n return $authenticatable->canOrElse(\n abilities: [\"prompt.{$prompt->id}.delete\"],\n denyResponse: 'You do not have permission to delete this prompt.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getProductVideo(): ProductVideo\n {\n return $this->productVideo;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(public readonly EntityManagerInterface $em)\n {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getFlags(array $data): array\n {\n return $this->flagFacade->getByIds($data['flags']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($match) use ($version) {\n return str_replace($match[1], $version->getVersionString(), $match[0]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function selectAll($context = null) {\n\t\t$overlay = $this->edit($context);\n\t\t$overlay->query('xpath:.//input[@name=\"all_records\"]')->one()->click();\n\t\t$overlay->getFooter()->query('button:Select')->one()->click();\n\n\t\t$overlay->waitUntilNotPresent();\n\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "protected function getValidators(): array\n {\n return ['IntegerValueValidator' => new Validator\\IntegerValueValidator()];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function doAction(): void {\n\t\tif ($this->getInput('filter_counters', 0) != 0) {\n\t\t\t$profile = (new CTabFilterProfile(static::FILTER_IDX, static::FILTER_FIELDS_DEFAULT))->read();\n\t\t\t$filters = $this->hasInput('counter_index')\n\t\t\t\t? [$profile->getTabFilter($this->getInput('counter_index'))]\n\t\t\t\t: $profile->getTabsWithDefaults();\n\n\t\t\t$filter_counters = [];\n\n\t\t\tforeach ($filters as $index => $tabfilter) {\n\t\t\t\tif (!$tabfilter['filter_show_counter']) {\n\t\t\t\t\t$filter_counters[$index] = 0;\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$prepared_data = $this->prepareData($tabfilter, $tabfilter['sort'], $tabfilter['sortorder']);\n\t\t\t\t$subfilters_fields = self::getSubfilterFields($tabfilter);\n\t\t\t\tself::getSubfilters($subfilters_fields, $prepared_data);\n\t\t\t\t$filter_counters[$index] = count(self::applySubfilters($prepared_data['items']));\n\t\t\t}\n\n\t\t\t$this->setResponse(\n\t\t\t\t(new CControllerResponseData([\n\t\t\t\t\t'main_block' => json_encode(['filter_counters' => $filter_counters])\n\t\t\t\t]))->disableView()\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\t$filter = static::FILTER_FIELDS_DEFAULT;\n\t\t\t$this->getInputs($filter, array_keys($filter));\n\t\t\t$filter = $this->cleanInput($filter);\n\n\t\t\t// make data\n\t\t\t$prepared_data = $this->prepareData($filter, $filter['sort'], $filter['sortorder']);\n\n\t\t\t// Prepare subfilter data.\n\t\t\t$subfilters_fields = self::getSubfilterFields($filter);\n\t\t\t$subfilters = self::getSubfilters($subfilters_fields, $prepared_data);\n\t\t\t$prepared_data['items'] = self::applySubfilters($prepared_data['items']);\n\n\t\t\t$page = $this->getInput('page', 1);\n\t\t\t$view_url = (new CUrl('zabbix.php'))->setArgument('action', 'latest.view');\n\t\t\t$paging_arguments = array_filter(array_intersect_key($filter, self::FILTER_FIELDS_DEFAULT));\n\t\t\tarray_map([$view_url, 'setArgument'], array_keys($paging_arguments), $paging_arguments);\n\t\t\t$paging = CPagerHelper::paginate($page, $prepared_data['items'], ZBX_SORT_UP, $view_url);\n\n\t\t\t$this->extendData($prepared_data);\n\n\t\t\t// make response\n\t\t\t$data = [\n\t\t\t\t'results' => [\n\t\t\t\t\t'filter' => $filter,\n\t\t\t\t\t'view_curl' => $view_url,\n\t\t\t\t\t'sort_field' => $filter['sort'],\n\t\t\t\t\t'sort_order' => $filter['sortorder'],\n\t\t\t\t\t'paging' => $paging,\n\t\t\t\t\t'config' => [\n\t\t\t\t\t\t'hk_trends' => CHousekeepingHelper::get(CHousekeepingHelper::HK_TRENDS),\n\t\t\t\t\t\t'hk_trends_global' => CHousekeepingHelper::get(CHousekeepingHelper::HK_TRENDS_GLOBAL),\n\t\t\t\t\t\t'hk_history' => CHousekeepingHelper::get(CHousekeepingHelper::HK_HISTORY),\n\t\t\t\t\t\t'hk_history_global' => CHousekeepingHelper::get(CHousekeepingHelper::HK_HISTORY_GLOBAL)\n\t\t\t\t\t],\n\t\t\t\t\t'tags' => makeTags($prepared_data['items'], true, 'itemid', (int) $filter['show_tags'],\n\t\t\t\t\t\t$filter['tags'], array_key_exists('tags', $subfilters_fields) ? $subfilters_fields['tags'] : [],\n\t\t\t\t\t\t(int) $filter['tag_name_format'], $filter['tag_priority']\n\t\t\t\t\t)\n\t\t\t\t] + $prepared_data,\n\t\t\t\t'subfilters' => $subfilters,\n\t\t\t\t'subfilters_expanded' => array_flip($this->getInput('subfilters_expanded', []))\n\t\t\t];\n\n\t\t\t$response = new CControllerResponseData($data);\n\t\t\t$this->setResponse($response);\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function () {\n return [\n 'recurring' => 1,\n ];\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "protected function checkValueStructure(BaseValue $value): void\n {\n if (!is_int($value->value)) {\n throw new InvalidArgumentType(\n '$value->value',\n 'integer',\n $value->value\n );\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function isHidden()\n {\n return $this->hidden;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function vote(TokenInterface $token, $object, array $attributes): int\n {\n foreach ($attributes as $attribute) {\n if ($this->supportsAttribute($attribute)) {\n $targets = isset($attribute->limitations['targets']) ? $attribute->limitations['targets'] : [];\n if (\n $this->permissionResolver->canUser(\n $attribute->module,\n $attribute->function,\n $attribute->limitations['valueObject'],\n $targets\n ) === false\n ) {\n return VoterInterface::ACCESS_DENIED;\n }\n\n return VoterInterface::ACCESS_GRANTED;\n }\n }\n\n return VoterInterface::ACCESS_ABSTAIN;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getPolicyDraft(): PolicyDraft\n {\n return $this->policyDraft;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function specifyLocators(): array\n {\n return [\n new VisibleCSSLocator('url', '#ezplatform_content_forms_content_edit_fieldsData_ezurl_value_link'),\n new VisibleCSSLocator('text', '#ezplatform_content_forms_content_edit_fieldsData_ezurl_value_text'),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __invoke(Table $table): Table\n {\n return $table\n ->query(fn () => Prospect::query())\n ->columns([\n TextColumn::make(Prospect::displayNameKey())\n ->label('Name')\n ->sortable(),\n TextColumn::make('email')\n ->label('Email')\n ->sortable(),\n TextColumn::make('mobile')\n ->label('Mobile')\n ->sortable(),\n TextColumn::make('status')\n ->badge()\n ->state(function (Prospect $record) {\n return $record->status->name;\n })\n ->color(function (Prospect $record) {\n return $record->status->color->value;\n })\n ->sortable(query: function (Builder $query, string $direction): Builder {\n return $query\n ->join('prospect_statuses', 'prospects.status_id', '=', 'prospect_statuses.id')\n ->orderBy('prospect_statuses.name', $direction);\n }),\n TextColumn::make('source.name')\n ->label('Source')\n ->sortable(),\n TextColumn::make('created_at')\n ->label('Created')\n ->dateTime('g:ia - M j, Y ')\n ->sortable(),\n ])\n ->filters([\n QueryBuilder::make()\n ->constraints([\n TextConstraint::make('first_name')\n ->icon('heroicon-m-user'),\n TextConstraint::make('last_name')\n ->icon('heroicon-m-user'),\n TextConstraint::make('full_name')\n ->icon('heroicon-m-user'),\n TextConstraint::make('preferred')\n ->label('Preferred Name')\n ->icon('heroicon-m-user'),\n QueryBuilder\\Constraints\\DateConstraint::make('created_at')\n ->icon('heroicon-m-calendar'),\n TextConstraint::make('email')\n ->label('Email Address')\n ->icon('heroicon-m-envelope'),\n TextConstraint::make('email_2')\n ->label('Email Address 2')\n ->icon('heroicon-m-envelope'),\n TextConstraint::make('mobile')\n ->icon('heroicon-m-phone'),\n TextConstraint::make('phone')\n ->icon('heroicon-m-phone'),\n TextConstraint::make('address')\n ->icon('heroicon-m-map-pin'),\n TextConstraint::make('address_2')\n ->icon('heroicon-m-map-pin'),\n BooleanConstraint::make('sms_opt_out')\n ->label('SMS Opt Out')\n ->icon('heroicon-m-chat-bubble-bottom-center'),\n BooleanConstraint::make('email_bounce')\n ->icon('heroicon-m-arrow-uturn-left'),\n TextConstraint::make('hsgrad')\n ->label('HS Grad')\n ->icon('heroicon-m-academic-cap'),\n RelationshipConstraint::make('status')\n ->icon('heroicon-m-flag')\n ->selectable(\n IsRelatedToOperator::make()\n ->titleAttribute('name')\n ->multiple()\n ->preload(),\n ),\n RelationshipConstraint::make('source')\n ->icon('heroicon-m-arrow-left-on-rectangle')\n ->selectable(\n IsRelatedToOperator::make()\n ->titleAttribute('name')\n ->multiple()\n ->preload(),\n ),\n ])\n ->constraintPickerColumns([\n 'md' => 2,\n 'lg' => 3,\n 'xl' => 4,\n ])\n ->constraintPickerWidth('7xl'),\n ], layout: FiltersLayout::AboveContent)\n ->actions([\n ViewAction::make()\n ->authorize('view')\n ->url(fn (Prospect $record) => ProspectResource::getUrl('view', ['record' => $record])),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function create(): GoogleProductDomainData;", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testPageReportsActionLog_CheckLayout() {\n\t\t// dates can be in relative format, example: now-1y/y, now-1w, now\n\t\t$this->zbxTestLogin('auditacts.php?from=now-2y&to=now');\n\t\t$this->zbxTestCheckTitle('Action log');\n\t\t$this->zbxTestAssertElementPresentId('config');\n\t\t$this->zbxTestCheckHeader('Action log');\n\n\t\t$this->zbxTestTextPresent('Recipient');\n\t\t$this->zbxTestAssertElementPresentId('filter_userids__ms');\n\t\t$this->zbxTestAssertElementPresentXpath(\"//button[@name='filter_set']\");\n\t\t$this->zbxTestAssertElementPresentXpath(\"//button[contains(text(),'Reset')]\");\n\t\t$this->zbxTestTextPresent(['Time', 'Action','Type', 'Status', 'Recipient', 'Message', 'Status', 'Info']);\n\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function __construct(\n protected readonly BreadcrumbOverrider $breadcrumbOverrider,\n protected readonly AdminDomainTabsFacade $adminDomainTabsFacade,\n protected readonly BillingAddressDataFactory $billingAddressDataFactory,\n protected readonly BillingAddressFacade $billingAddressFacade,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(?ObjectState $objectState = null)\n {\n if ($objectState instanceof ObjectState) {\n $this->objectState = $objectState;\n $this->name = $objectState->getName();\n $this->identifier = $objectState->identifier;\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "protected function getImageRepository()\n {\n return $this->em->getRepository(Image::class);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function down(): void\n {\n $assistants = AiAssistant::query()\n ->where('model', AiModel::OpenAiGpt4o)\n ->get();\n\n foreach ($assistants as $assistant) {\n try {\n /** @var AiAssistant $assistant */\n\n /** @var OpenAiGpt4oService $service */\n $service = $assistant->model->getService();\n\n $service->disableAssistantFileUploads($assistant);\n } catch (Throwable $e) {\n report($e);\n\n continue;\n }\n }\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(Console $console, SubMenuSetupItem $parent)\n {\n parent::__construct($console);\n $this->parent = $parent;\n }", "smellKey": "0", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function testGetSiteAccessThrowsNotFoundException(): void\n {\n $staticSiteAccessProvider = new StaticSiteAccessProvider(\n [self::EXISTING_SA_NAME],\n [self::EXISTING_SA_NAME => [self::SA_GROUP]],\n );\n $service = new SiteAccessService(\n $staticSiteAccessProvider,\n $this->createMock(ConfigResolverInterface::class)\n );\n\n $this->expectException(NotFoundException::class);\n $service->get(self::UNDEFINED_SA_NAME);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function getCancelData() {\n\t\treturn [\n\t\t\t// Cancel creating widget with saving the dashboard.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'cancel_form' => true,\n\t\t\t\t\t'create_widget' => true,\n\t\t\t\t\t'save_dashboard' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Cancel updating widget with saving the dashboard.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'cancel_form' => true,\n\t\t\t\t\t'create_widget' => false,\n\t\t\t\t\t'save_dashboard' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Create widget without saving the dashboard.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'cancel_form' => false,\n\t\t\t\t\t'create_widget' => true,\n\t\t\t\t\t'save_dashboard' => false\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Update widget without saving the dashboard.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'cancel_form' => false,\n\t\t\t\t\t'create_widget' => false,\n\t\t\t\t\t'save_dashboard' => false\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function ($request, $next) {\n /** @var User $user */\n $user = auth()->user();\n $this->repository = app(ObjectGroupRepositoryInterface::class);\n $this->repository->setUser($user);\n\n return $next($request);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function (Get $get): array {\n return EmailTemplate::query()\n ->when(\n $get('onlyMyTemplates'),\n fn (Builder $query) => $query->whereBelongsTo(auth()->user())\n )\n ->orderBy('name')\n ->limit(50)\n ->pluck('name', 'id')\n ->toArray();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "protected function getSettingsSchemaExpectation()\n {\n return [\n 'isMultiple' => [\n 'type' => 'bool',\n 'default' => false,\n ],\n 'options' => [\n 'type' => 'hash',\n 'default' => [],\n ],\n 'multilingualOptions' => [\n 'type' => 'hash',\n 'default' => [],\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function createRuleForm($filterName, $index)\n {\n $rulesData = [\n $index => $this->ruleFormViewDataFactory->createDefault($filterName),\n ];\n\n return $this->advancedSearchFormFactory->createRulesForm(static::RULES_FORM_NAME, $rulesData);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "private function getRestrictedLanguagesCodes($hasAccess): array\n {\n if (!\\is_array($hasAccess)) {\n return [];\n }\n\n $restrictedLanguagesCodes = $this->permissionChecker->getRestrictions($hasAccess, LanguageLimitation::class);\n\n if (empty($restrictedLanguagesCodes)) {\n return [];\n }\n\n return $restrictedLanguagesCodes;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function testAnotherProductIsAddedToCart(): void\n {\n $productQuantity = 2;\n $newlyCreatedCart = $this->addTestingProductToNewCart($productQuantity);\n\n $secondProduct = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . 72, Product::class);\n $secondProductQuantity = 5;\n\n $response = $this->getResponseContentForGql(__DIR__ . '/../_graphql/mutation/AddToCartMutation.graphql', [\n 'cartUuid' => $newlyCreatedCart['uuid'],\n 'productUuid' => $secondProduct->getUuid(),\n 'quantity' => $secondProductQuantity,\n ]);\n\n self::assertEquals($newlyCreatedCart['uuid'], $response['data']['AddToCart']['cart']['uuid']);\n\n $cart = $this->cartFacade->findCartByCartIdentifier($newlyCreatedCart['uuid']);\n self::assertNotNull($cart);\n\n $cartItems = $cart->getItems();\n self::assertCount(2, $cartItems);\n\n self::assertEquals($productQuantity, $cartItems[0]->getQuantity());\n self::assertEquals($this->testingProduct->getUuid(), $cartItems[0]->getProduct()->getUuid());\n\n self::assertEquals($secondProductQuantity, $cartItems[1]->getQuantity());\n self::assertEquals($secondProduct->getUuid(), $cartItems[1]->getProduct()->getUuid());\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function load(ObjectManager $manager): void\n {\n $domainId = $this->domainsForDataFixtureProvider->getFirstAllowedDomainConfig()->getId();\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test';\n $promoCodeData->domainId = $domainId;\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n\n /** @var \\App\\Model\\Product\\Product $product */\n $product = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . 1);\n $this->promoCodeProductFactory->create($promoCode, $product);\n\n /** @var \\App\\Model\\Category\\Category $category */\n $category = $this->getReference(CategoryDataFixture::CATEGORY_FOOD);\n $this->promoCodeCategoryFactory->create($promoCode, $category);\n\n /** @var \\App\\Model\\Category\\Category $category */\n $category = $this->getReference(CategoryDataFixture::CATEGORY_BOOKS);\n $this->promoCodeCategoryFactory->create($promoCode, $category);\n\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::VALID_PROMO_CODE, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-product2';\n $promoCodeData->domainId = $domainId;\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n /** @var \\App\\Model\\Product\\Product $product */\n $product = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . 2);\n $this->promoCodeProductFactory->create($promoCode, $product);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::PROMO_CODE_FOR_PRODUCT_ID_2, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-not-yet-valid';\n $promoCodeData->domainId = $domainId;\n $promoCodeData->datetimeValidFrom = new DateTime('+1 year');\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::NOT_YET_VALID_PROMO_CODE, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-no-longer-valid';\n $promoCodeData->domainId = $domainId;\n $promoCodeData->datetimeValidTo = new DateTime('-1 year');\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::NO_LONGER_VALID_PROMO_CODE, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-for-registered-only';\n $promoCodeData->domainId = $domainId;\n $promoCodeData->registeredCustomerUserOnly = true;\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::PROMO_CODE_FOR_REGISTERED_ONLY, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-for-vip-pricing-group';\n $promoCodeData->domainId = $domainId;\n $vipPricingGroup = $this->getReferenceForDomain(PricingGroupDataFixture::PRICING_GROUP_VIP, $domainId, PricingGroup::class);\n $promoCodeData->limitedPricingGroups = [$vipPricingGroup];\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::PROMO_CODE_FOR_VIP_PRICING_GROUP, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test-for-new-product';\n $promoCodeData->domainId = $domainId;\n /** @var \\App\\Model\\Product\\Flag\\Flag $flag */\n $flag = $this->getReference(FlagDataFixture::FLAG_PRODUCT_NEW);\n $promoCodeData->flags = [$this->promoCodeFlagFactory->create($flag, PromoCodeFlag::TYPE_INCLUSIVE)];\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultLimit($promoCode);\n $this->addReferenceForDomain(self::PROMO_CODE_FOR_NEW_PRODUCT, $promoCode, $domainId);\n\n $promoCodeData = $this->promoCodeDataFactory->create();\n $promoCodeData->code = 'test100';\n $promoCodeData->discountType = PromoCode::DISCOUNT_TYPE_NOMINAL;\n $promoCodeData->domainId = $domainId;\n $promoCode = $this->promoCodeFacade->create($promoCodeData);\n $this->setDefaultNominalLimit($promoCode);\n\n $this->loadForOtherDomains();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($target) {\n\t\t\t\t\treturn $target->hasClass('expanded');\n\t\t\t\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function toHtml()\n\t{\n\t\treturn 'Verwijder velden: ' . implode(', ', $this->velden);\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "protected function getColumns(): int\n {\n return 3;\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function addPolicy(APIPolicyCreateStruct $policyCreateStruct): void\n {\n $this->policies[] = $policyCreateStruct;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getUploadedFile()\n {\n return $this->uploadedFile;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(AutosaveServiceInterface $autosaveService)\n {\n $this->autosaveService = $autosaveService;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct($message, $output, $code = 0, Throwable $previous = null)\n {\n parent::__construct($message, $code, $previous);\n $this->output = $output;\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "static function (string $groupName) {\n return new SiteAccessGroup($groupName);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getTriggerParameters(): array\n {\n return [\n 'start' => $this->getDate('start'),\n 'end' => $this->getDate('end'),\n 'accounts' => $this->getAccounts(),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function (Blueprint $table) {\n $table->text('author_display')->nullable();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($contentTypeGroupId, $prioritizedLanguages): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getContentTypeService()->loadContentTypeGroup(\n $contentTypeGroupId,\n $prioritizedLanguages\n );\n\n return true;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "#[DataProvider('booleanWithDefaultTrueProvider')]\n public function testEdit(mixed $actual, bool $expected): void\n {\n $sqlQueryBox = new SqlQueryBox(['Edit' => $actual]);\n $sqlQueryBoxArray = $sqlQueryBox->asArray();\n // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps\n self::assertSame($expected, $sqlQueryBox->Edit);\n self::assertSame($expected, $sqlQueryBoxArray['Edit']);\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function getLink(array $data): string\n {\n return $data['detail_url'];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (Blueprint $table) {\n $table->dropColumn('start_date');\n $table->dropColumn('end_date');\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function insertSetting(string $group, string $identifier, string $serializedValue): int\n {\n $query = $this->connection->createQueryBuilder();\n $query\n ->insert(self::SETTING_TABLE)\n ->values(\n [\n $this->connection->quoteIdentifier('group') => $query->createPositionalParameter($group),\n 'identifier' => $query->createPositionalParameter($identifier),\n 'value' => $query->createPositionalParameter($serializedValue),\n ]\n );\n\n $query->execute();\n\n return (int)$this->connection->lastInsertId(Gateway::SETTING_SEQ);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "abstract public function removeFileReferences(array $fieldIds, $versionNo);", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function down(): void\n {\n Schema::table('experiences', function (Blueprint $table) {\n $table->dropColumn('author_display');\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "#[DataProvider('getTestSellingDeniedDataProvider')]\n public function testSellingDenied(\n bool $hidden,\n bool $sellingDenied,\n bool $calculatedSellingDenied,\n ): void {\n $productData = $this->productDataFactory->create();\n $productData->hidden = $hidden;\n $productData->sellingDenied = $sellingDenied;\n $productData->unit = $this->getReference(UnitDataFixture::UNIT_PIECES, Unit::class);\n\n $stock = $this->getReference(StocksDataFixture::STOCK_PREFIX . 1, Stock::class);\n\n $productStockData = $this->productStockDataFactory->createFromStock($stock);\n $productStockData->productQuantity = 10;\n $productData->productStockData[$stock->getId()] = $productStockData;\n\n $productData->catnum = '123';\n\n $product = $this->productFacade->create($productData);\n\n $this->handleDispatchedRecalculationMessages();\n\n $this->em->clear();\n\n $productFromDb = $this->productFacade->getById($product->getId());\n\n $this->assertSame($calculatedSellingDenied, $productFromDb->getCalculatedSellingDenied(), 'Calculated selling denied:');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function setMatcherBuilder(MatcherBuilderInterface $matcherBuilder);", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getCopiedRole(): Role\n {\n if (!$this->hasCopiedRole()) {\n throw new UnexpectedValueException(sprintf('Return value is not set or not of type %s. Check hasCopiedRole() or set it using setCopiedRole() before you call the getter.', Role::class));\n }\n\n return $this->copiedRole;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setFieldNames($names) {\n\t\tif (!is_array($this->names)) {\n\t\t\t$this->names = [];\n\t\t}\n\n\t\tforeach ($names as $field => $name) {\n\t\t\t$this->names[$field] = $name;\n\t\t}\n\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function down(): void\n {\n Schema::drop('transport_group_transport');\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function getMainImagesByEntitiesIndexedByEntityId(array $entitiesOrEntityIds, $entityName)\n {\n $queryBuilder = $this->getImageRepository()\n ->createQueryBuilder('i')\n ->andWhere('i.entityName = :entityName')->setParameter('entityName', $entityName)\n ->andWhere('i.entityId IN (:entities)')->setParameter('entities', $entitiesOrEntityIds)\n ->addOrderBy('i.position', 'desc')\n ->addOrderBy('i.id', 'desc');\n\n $imagesByEntityId = [];\n\n /** @var \\Shopsys\\FrameworkBundle\\Component\\Image\\Image $image */\n foreach ($queryBuilder->getQuery()->execute() as $image) {\n $imagesByEntityId[$image->getEntityId()] = $image;\n }\n\n return $imagesByEntityId;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function hasContent(): bool\n {\n return $this->content instanceof Content;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function handle(Device $device, Trap $trap)\n {\n $srcIp = $trap->getOidData($trap->findOid('FORTINET-FORTIGATE-MIB::fgIpsTrapSrcIp'));\n $proto = $trap->getOidData($trap->findOid('FORTINET-FORTIGATE-MIB::fgIpsTrapSigMsg'));\n $trap->log(\"DDoS prevention triggered. Source: $srcIp Protocol: $proto\", Severity::Warning);\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function getAllStocks(): array\n {\n return $this->getStockRepository()->findBy([], ['position' => 'ASC']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getSpecifications(): array\n {\n return [\n new Specifications(\n Operator::EQ,\n Specifications::FORMAT_SINGLE,\n Specifications::TYPE_STRING\n ),\n new Specifications(\n Operator::IN,\n Specifications::FORMAT_ARRAY,\n Specifications::TYPE_STRING\n ),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function getFieldTypeIdentifier(Content $content, Field $field)\n {\n $contentType = $content->getContentType();\n $key = $contentType->id . ' ' . $field->fieldDefIdentifier;\n\n if (!isset($this->fieldTypeIdentifiers[$key])) {\n $this->fieldTypeIdentifiers[$key] = $contentType\n ->getFieldDefinition($field->fieldDefIdentifier)\n ->fieldTypeIdentifier;\n }\n\n return $this->fieldTypeIdentifiers[$key];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function testEscalations_disabledAction() {\n\t\t$this->clearLog(self::COMPONENT_SERVER);\n\t\t$response = $this->call('action.update', [\n\t\t\t'actionid' => self::$trigger_actionid,\n\t\t\t'status' => 1\n\t\t]);\n\n\t\t$this->assertArrayHasKey('actionids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['actionids']));\n\n\t\t$this->reloadConfigurationCache();\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 1);\n\n\t\t// Check if there are no alerts for this action\n\t\t$response = $this->call('alert.get', [\n\t\t\t'actionids' => [self::$trigger_actionid]\n\t\t]);\n\t\t$this->assertEmpty($response['result']);\n\n\t\t$this->sendSenderValue(self::HOST_NAME, self::TRAPPER_ITEM_NAME, 0);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "protected function setUp(): void\n {\n parent::setUp();\n\n $this->infolist($this->serviceRequestAssignmentInfolist());\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(Model $changer, Model $auditable, string $field, mixed $before, mixed $after)\n {\n $this->changer = $changer;\n $this->auditable = $auditable;\n $this->field = $field;\n $this->before = $before;\n $this->after = $after;\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function update($id, $name, $identifier)\n {\n $this->logger->logCall(__METHOD__, ['section' => $id, 'name' => $name, 'identifier' => $identifier]);\n $section = $this->persistenceHandler->sectionHandler()->update($id, $name, $identifier);\n\n $this->cache->invalidateTags([\n $this->cacheIdentifierGenerator->generateTag(self::SECTION_IDENTIFIER, [$id]),\n ]);\n\n return $section;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getLogsByJobRunId(\n int $jobRunId,\n int $step = null,\n array $orderBy = [],\n int $limit = 100,\n int $offset = 0\n ): array {\n $criteria = ['jobRunId' => $jobRunId];\n if ($step !== null && $step >= 0) {\n $criteria['step'] = $step;\n }\n\n return $this->getLogRepository()->findBy(\n $criteria,\n $orderBy,\n $limit,\n $offset\n );\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function testDashboardGraphWidget_Create($data) {\n\t\t$this->page->login()->open(self::DASHBOARD_URL);\n\t\t$form = $this->openGraphWidgetConfiguration();\n\n\t\t$this->fillForm($data, $form);\n\t\t$form->parents('class:overlay-dialogue-body')->one()->query('tag:output')->asMessage()->waitUntilNotVisible();\n\t\t$form->submit();\n\t\t$this->saveGraphWidget(CTestArrayHelper::get($data, 'main_fields.Name', 'Graph'));\n\n\t\t// Check values in created widget.\n\t\tif (CTestArrayHelper::get($data, 'check_form', false)) {\n\t\t\t$this->openGraphWidgetConfiguration(CTestArrayHelper::get($data, 'main_fields.Name', 'Graph'));\n\t\t\t$this->checkWidgetForm($data);\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getDocLinkByNameMysql(string $name): string|null;", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function testToFieldValueEmpty()\n {\n $storageFieldValue = new StorageFieldValue();\n $storageFieldValue->sortKeyString = '';\n $storageFieldValue->dataText = <<\n\n\nEOT;\n\n $expectedFieldValue = new FieldValue();\n $expectedFieldValue->data = ['destinationContentIds' => []];\n\n $actualFieldValue = new FieldValue();\n\n $this->converter->toFieldValue($storageFieldValue, $actualFieldValue);\n\n $this->assertEquals(\n $expectedFieldValue,\n $actualFieldValue\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getStocksEnabledOnDomain(int $domainId): array\n {\n return $this->getQueryBuilder()\n ->join(StockDomain::class, 'sd', Join::WITH, 's.id = sd.stock AND sd.isEnabled = TRUE AND sd.domainId = :domainId')\n ->setParameter('domainId', $domainId)\n ->getQuery()\n ->execute();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function loadChoicesForValues(array $values, $value = null)\n {\n // Optimize\n $values = array_filter($values);\n if (empty($values)) {\n return [];\n }\n\n return $this->loadChoiceList($value)->getChoicesForValues($values);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function setup(): void\n {\n $this->db = new NullDB();\n }", "smellKey": "0", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function createMetaFieldDefinitionCreateStruct(\n string $identifier,\n string $fieldGroup,\n Language $language,\n int $position\n ): FieldDefinitionCreateStruct {\n $fieldDefinitionCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct(\n uniqid('field_'),\n $identifier\n );\n\n $fieldDefinitionCreateStruct->fieldGroup = $fieldGroup;\n $label = $this->translator->trans(/** @Ignore */\n $identifier . '.name',\n [],\n 'ibexa_fieldtypes',\n $this->localeConverter->convertToPOSIX($language->languageCode)\n );\n\n $fieldDefinitionCreateStruct->names = [\n $language->languageCode => $label,\n ];\n\n $fieldDefinitionCreateStruct->position = $position;\n\n return $fieldDefinitionCreateStruct;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function setRequest(SimplifiedRequest $request);", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function down(): void\n {\n DB::update(\"update mediables set mediable_type = 'A17\\CmsToolkit\\Models\\Block' where mediable_type = ?\", ['blocks']);\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function getUserName(string $accessToken): string\n {\n $response = $this->getUser($accessToken);\n\n return $response['bot']['owner']['user']['name'] ?? '';\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function getRole(): ?Role\n {\n return $this->role;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(TicketedEventTypeRepository $repository)\n {\n $this->repository = $repository;\n parent::__construct();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "private function validate($orientation): void\n {\n if (\n is_string($orientation)\n && !$this->isSupportedOrientation($orientation)\n ) {\n $this->throwException($orientation);\n }\n\n if (is_array($orientation)) {\n $invalidOrientations = array_filter(\n $orientation,\n fn ($value): bool => !$this->isSupportedOrientation($value)\n );\n\n if (!empty($invalidOrientations)) {\n $this->throwException(implode(', ', $invalidOrientations));\n }\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getName(): string\n {\n return 'AttributeURL';\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function edit($context = null) {\n\t\t/* TODO: extend the function for composite elements with two buttons,\n\t\t * Example of such multiselect: [ Input field ] ( Select item ) ( Select prototype )\n\t\t */\n\t\t$this->getControls()->first()->click();\n\n\t\treturn COverlayDialogElement::find()->waitUntilPresent()\n\t\t\t\t->all()->last()->waitUntilReady()->setDataContext($context, $this->mode);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getAllowedDemoDataLocales(): array\n {\n $allowedLocales = array_map(\n static fn (DomainConfig $domainConfig) => $domainConfig->getLocale(),\n $this->getAllowedDemoDataDomains(),\n );\n\n return array_unique($allowedLocales);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getName()\n {\n return $this->name;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getTerritory(): ?Territory\n {\n return $this->territory;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "private function createSiteAcccess(string $name, array $groupNames = []): SiteAccess\n {\n $undefinedSiteAccess = new SiteAccess(\n $name,\n SiteAccess::DEFAULT_MATCHING_TYPE,\n null,\n StaticSiteAccessProvider::class\n );\n $undefinedSiteAccess->groups = array_map(\n static function (string $groupName) {\n return new SiteAccessGroup($groupName);\n },\n $groupNames\n );\n\n return $undefinedSiteAccess;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function validate($data, $tab) {\n\t\t$old_hash = CDBHelper::getHash(self::SQL);\n\n\t\t$this->page->login()->open(self::DASHBOARD_URL);\n\t\t$form = $this->openGraphWidgetConfiguration(CTestArrayHelper::get($data, 'Widget name'));\n\n\t\t$this->fillDatasets(CTestArrayHelper::get($data, 'Data set'));\n\n\t\tswitch ($tab) {\n\t\t\tcase 'Data set':\n\t\t\t\t// Remove data set.\n\t\t\t\tif (CTestArrayHelper::get($data, 'remove_data_set', false)) {\n\t\t\t\t\t$form->query('xpath://button[@class=\"btn-remove\"]')->one()->click();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'Overrides':\n\t\t\t\t$form->selectTab($tab);\n\t\t\t\t$this->fillOverrides(CTestArrayHelper::get($data, 'Overrides'));\n\n\t\t\t\t// Remove all override options.\n\t\t\t\tif (CTestArrayHelper::get($data, 'remove_override_options', false)) {\n\t\t\t\t\t$form->query('xpath://button[@class=\"subfilter-disable-btn\"]')->all()->click();\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t$form->selectTab($tab);\n\t\t\t\t$form->fill($data[$tab]);\n\t\t}\n\n\t\tsleep(2);\n\t\t$form->submit();\n\t\tCOverlayDialogElement::find()->one()->waitUntilReady()->query('xpath:div[@class=\"overlay-dialogue-footer\"]'.\n\t\t\t\t'//button[@class=\"dialogue-widget-save\"]')->waitUntilClickable()->one();\n\n\t\tif (array_key_exists('error', $data)) {\n\t\t\t$this->assertMessage(TEST_BAD, null, $data['error']);\n\t\t}\n\n\t\t$this->assertEquals($old_hash, CDBHelper::getHash(self::SQL));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getAllStocksQueryBuilder(): QueryBuilder\n {\n return $this->getQueryBuilder()\n ->orderBy('s.position', 'ASC');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function getCreateData() {\n\t\treturn [\n\t\t\t// Mandatory fields only.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t'host' => '*',\n\t\t\t\t\t\t'item' => '*'\n\t\t\t\t\t],\n\t\t\t\t\t'check_form' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Press button \"Add new override\", but left override fields empty.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t'host' => 'Add override',\n\t\t\t\t\t\t'item' => 'Override empty fields'\n\t\t\t\t\t],\n\t\t\t\t\t'Overrides' => []\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Comma in host and item name.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Comma in host/item names'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'Zabbix,Server',\n\t\t\t\t\t\t\t'item' => 'Agent, Ping',\n\t\t\t\t\t\t\t'Aggregation function' => 'min',\n\t\t\t\t\t\t\t'Aggregate' => 'Data set'\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => ',Zabbix Server',\n\t\t\t\t\t\t\t'item' => ',Agentp ping',\n\t\t\t\t\t\t\t'Draw' => 'Bar',\n\t\t\t\t\t\t\t'Aggregation function' => 'max'\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => ',Zabbix, Server,',\n\t\t\t\t\t\t\t'item' => 'Zabbix configuration cache, % used',\n\t\t\t\t\t\t\t'Aggregation function' => 'count',\n\t\t\t\t\t\t\t'Aggregation interval' => '24h'\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'Overrides' => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'Zabbix,Server',\n\t\t\t\t\t\t\t'item' => 'Agent,Ping',\n\t\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t\t['Draw', 'Bar'],\n\t\t\t\t\t\t\t\t['Missing data', 'Treat as 0']\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => ',Zabbix Server',\n\t\t\t\t\t\t\t'item' => ', Agent ping',\n\t\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t\t['Draw', 'Bar'],\n\t\t\t\t\t\t\t\t['Missing data', 'Connected']\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => ',,Zabbix Server,,',\n\t\t\t\t\t\t\t'item' => ', Agent, ping,',\n\t\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t\t['Draw', 'Bar']\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'check_form' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t/* Add Width, Fill and Missing data fields in overrides, which are disabled in data set tab.\n\t\t\t * Fill enabled right Y-axis fields.\n\t\t\t */\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Test graph widget',\n\t\t\t\t\t\t'Refresh interval' => '10 seconds'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t'host' => ['Zabbix*', 'one', 'two'],\n\t\t\t\t\t\t'item' => ['Agent*', 'one', 'two'],\n\t\t\t\t\t\t'Draw' => 'Bar',\n\t\t\t\t\t\t'Y-axis' => 'Right'\n\t\t\t\t\t],\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => 'now-1w',\n\t\t\t\t\t\t'To' => 'now'\n\t\t\t\t\t],\n\t\t\t\t\t'Axes' => [\n\t\t\t\t\t\t'id:righty_min' => '-15',\n\t\t\t\t\t\t'id:righty_max' => '155.5',\n\t\t\t\t\t\t'id:righty_units' => 'Static',\n\t\t\t\t\t\t'id:righty_static_units' => 'MB'\n\t\t\t\t\t],\n\t\t\t\t\t'Overrides' => [\n\t\t\t\t\t\t'host' => 'One host',\n\t\t\t\t\t\t'item' => 'One item',\n\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t['Width', '2'],\n\t\t\t\t\t\t\t['Fill', '2'],\n\t\t\t\t\t\t\t['Missing data', 'None']\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'check_form' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t/* Boundary values.\n\t\t\t * Creation with disabled axes and legend. Enabled Problems, but empty fields in problems tab.\n\t\t\t */\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Test boundary values',\n\t\t\t\t\t\t'Refresh interval' => '10 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => '*',\n\t\t\t\t\t\t\t'item' => '*',\n\t\t\t\t\t\t\t'Width' => '0',\n\t\t\t\t\t\t\t'Transparency' => '0',\n\t\t\t\t\t\t\t'Fill' => '0',\n\t\t\t\t\t\t\t'Missing data' => 'Treat as 0',\n\t\t\t\t\t\t\t'Time shift' => '-788400000'\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'Two host',\n\t\t\t\t\t\t\t'item' => 'Two item',\n\t\t\t\t\t\t\t'Y-axis' => 'Right',\n\t\t\t\t\t\t\t'Width' => '10',\n\t\t\t\t\t\t\t'Transparency' => '10',\n\t\t\t\t\t\t\t'Fill' => '10',\n\t\t\t\t\t\t\t'Missing data' => 'Connected',\n\t\t\t\t\t\t\t'Time shift' => '788400000',\n\t\t\t\t\t\t\t'Aggregation function' => 'sum',\n\t\t\t\t\t\t\t'Aggregation interval' => '788400000'\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'Displaying options' => [\n\t\t\t\t\t\t'History data selection' => 'Trends'\n\t\t\t\t\t],\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => 'now-59s',\n\t\t\t\t\t\t'To' => 'now'\n\t\t\t\t\t],\n\t\t\t\t\t'Axes' => [\n\t\t\t\t\t\t'Left Y' => false,\n\t\t\t\t\t\t'Right Y' => false,\n\t\t\t\t\t\t'X-Axis' => false\n\t\t\t\t\t],\n\t\t\t\t\t'Legend' => [\n\t\t\t\t\t\t'Show legend' => false\n\t\t\t\t\t],\n\t\t\t\t\t'Problems' => [\n\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t'Show problems' => true\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'Overrides' => [\n\t\t\t\t\t\t'host' => 'One host',\n\t\t\t\t\t\t'item' => 'One item',\n\t\t\t\t\t\t'time_shift' => '788400000',\n\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t'Time shift',\n\t\t\t\t\t\t\t['Draw', 'Staircase'],\n\t\t\t\t\t\t\t['Missing data', 'Treat as 0']\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'check_form' => true\n\t\t\t\t]\n\t\t\t],\n\t\t\t// All possible fields.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Graph widget with all filled fields',\n\t\t\t\t\t\t'Refresh interval' => 'No refresh'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'One host',\n\t\t\t\t\t\t\t'item' => 'One item',\n\t\t\t\t\t\t\t'Draw' => 'Staircase',\n\t\t\t\t\t\t\t'Width' => '10',\n\t\t\t\t\t\t\t'Transparency' => '10',\n\t\t\t\t\t\t\t'Fill' => '10',\n\t\t\t\t\t\t\t'Missing data' => 'Connected',\n\t\t\t\t\t\t\t'Time shift' => '0',\n\t\t\t\t\t\t\t'Aggregation function' => 'last',\n\t\t\t\t\t\t\t'Aggregation interval' => '1',\n\t\t\t\t\t\t\t'Aggregate' => 'Data set',\n\t\t\t\t\t\t\t'xpath://button[@id=\"lbl_ds_0_color\"]/..' => '009688'\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'Two host',\n\t\t\t\t\t\t\t'item' => 'Two item',\n\t\t\t\t\t\t\t'Y-axis' => 'Right',\n\t\t\t\t\t\t\t'Draw' => 'Points',\n\t\t\t\t\t\t\t'Point size' => '1',\n\t\t\t\t\t\t\t'Transparency' => '0',\n\t\t\t\t\t\t\t'Time shift' => '-1s',\n\t\t\t\t\t\t\t'xpath://button[@id=\"lbl_ds_1_color\"]/..' => '000000'\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'Displaying options' => [\n\t\t\t\t\t\t'History data selection' => 'History'\n\t\t\t\t\t],\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2018-11-15',\n\t\t\t\t\t\t'To' => '2018-11-15 14:20:00'\n\t\t\t\t\t],\n\t\t\t\t\t'Axes' => [\n\t\t\t\t\t\t'id:lefty_min' => '5',\n\t\t\t\t\t\t'id:lefty_max' => '15.5',\n\t\t\t\t\t\t'id:righty_min' => '-15',\n\t\t\t\t\t\t'id:righty_max' => '-5',\n\t\t\t\t\t\t'id:lefty_units' => 'Static',\n\t\t\t\t\t\t'id:lefty_static_units' => 'MB',\n\t\t\t\t\t\t'id:righty_units' => 'Static'\n\t\t\t\t\t],\n\t\t\t\t\t'Legend' => [\n\t\t\t\t\t\t'Number of rows' => '5'\n\t\t\t\t\t],\n\t\t\t\t\t'Problems' => [\n\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t'Show problems' => true,\n\t\t\t\t\t\t\t'Selected items only' => false,\n\t\t\t\t\t\t\t'Problem hosts' => ['Simple form test host'],\n\t\t\t\t\t\t\t'Severity' => ['Information', 'Average'],\n\t\t\t\t\t\t\t'Problem' => '2_trigger_*',\n\t\t\t\t\t\t\t'Tags' => 'Or'\n\t\t\t\t\t\t],\n\t\t\t\t\t\t'tags' => [\n\t\t\t\t\t\t\t['name' => 'server', 'value' => 'selenium', 'operator' => 'Equals'],\n\t\t\t\t\t\t\t['name' => 'Street', 'value' => 'dzelzavas']\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'Overrides' => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'One host',\n\t\t\t\t\t\t\t'item' => 'One item',\n\t\t\t\t\t\t\t'time_shift' => '-5s',\n\t\t\t\t\t\t\t'color' => '000000',\n\t\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t\t'Base color',\n\t\t\t\t\t\t\t\t['Width', '0'],\n\t\t\t\t\t\t\t\t['Draw', 'Line'],\n\t\t\t\t\t\t\t\t['Transparency', '0'],\n\t\t\t\t\t\t\t\t['Fill', '0'],\n\t\t\t\t\t\t\t\t['Point size', '1'],\n\t\t\t\t\t\t\t\t['Missing data', 'None'],\n\t\t\t\t\t\t\t\t['Y-axis', 'Right'],\n\t\t\t\t\t\t\t\t'Time shift'\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'host' => 'Two host',\n\t\t\t\t\t\t\t'item' => 'Two item',\n\t\t\t\t\t\t\t'time_shift' => '5s',\n\t\t\t\t\t\t\t'color' => 'FFFFFF',\n\t\t\t\t\t\t\t'options' => [\n\t\t\t\t\t\t\t\t'Base color',\n\t\t\t\t\t\t\t\t['Width', '1'],\n\t\t\t\t\t\t\t\t['Draw', 'Points'],\n\t\t\t\t\t\t\t\t['Transparency', '2'],\n\t\t\t\t\t\t\t\t['Fill', '3'],\n\t\t\t\t\t\t\t\t['Point size', '4'],\n\t\t\t\t\t\t\t\t['Missing data', 'Connected'],\n\t\t\t\t\t\t\t\t['Y-axis', 'Left'],\n\t\t\t\t\t\t\t\t'Time shift'\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t],\n\t\t\t\t\t'check_form' => true\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->index(['hostname', 'sysName', 'display']);\n $table->dropIndex('devices_hostname_index');\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "protected function getEmptyValueExpectation()\n {\n return new SelectionValue();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setPosition($position)\n {\n $this->position = $position;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function index()\n {\n $subTitle = (string)trans('firefly.instance_configuration');\n $subTitleIcon = 'fa-wrench';\n\n Log::channel('audit')->info('User visits admin config index.');\n\n // all available configuration and their default value in case\n // they don't exist yet.\n $singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;\n $isDemoSite = app('fireflyconfig')->get('is_demo_site', config('firefly.configuration.is_demo_site'))->data;\n $siteOwner = config('firefly.site_owner');\n\n return view(\n 'admin.configuration.index',\n compact('subTitle', 'subTitleIcon', 'singleUserMode', 'isDemoSite', 'siteOwner')\n );\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function __construct(\n PermissionResolver $permissionResolver,\n PermissionCheckerInterface $permissionChecker,\n ContentTypeService $contentTypeService\n ) {\n $this->contentTypeService = $contentTypeService;\n $this->permissionChecker = $permissionChecker;\n\n $hasAccess = $permissionResolver->hasAccess('content', 'create');\n $this->restrictedContentTypesIdentifiers = $this->getRestrictedContentTypesIdentifiers($hasAccess);\n $this->restrictedLanguagesCodes = $this->getRestrictedLanguagesCodes($hasAccess);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function validate($values, Constraint $constraint)\n {\n if (!$constraint instanceof UniqueProductParameters) {\n throw new UnexpectedTypeException($constraint, UniqueCollection::class);\n }\n\n $uniqueValues = [];\n $violations = [];\n\n /** @var \\Shopsys\\FrameworkBundle\\Model\\Product\\Parameter\\ProductParameterValueData $value */\n foreach ($values as $value) {\n $parameterId = $value->parameter->getId();\n $uniqueKey = $parameterId . '-' . $value->parameterValueData->locale;\n\n if (array_key_exists($uniqueKey, $uniqueValues)) {\n $violations[$parameterId] = $value->parameter->getName();\n }\n\n $uniqueValues[$uniqueKey] = $parameterId;\n }\n\n foreach ($violations as $violation) {\n $this->context->addViolation(\n $constraint->message,\n [\n '{{ parameterName }}' => $violation,\n ],\n );\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function getAllowedProperties(): array\n {\n return ['siteAccessesConfiguration'];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function onUdwConfigResolve(ConfigResolveEvent $event): void\n {\n if ($event->getConfigName() !== 'create') {\n return;\n }\n\n $config = $event->getConfig();\n\n if ($this->hasContentTypeRestrictions()) {\n $config['allowed_content_types'] = $this->restrictedContentTypesIdentifiers;\n $event->setConfig($config);\n }\n\n if ($this->hasLanguagesRestrictions()) {\n $config['content_on_the_fly']['allowed_languages'] = $this->restrictedLanguagesCodes;\n $event->setConfig($config);\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(Groep $groep)\n\t{\n\t\tparent::__construct($groep, null, $groep->naam . ' logboek', true);\n\n\t\t$fields = [];\n\t\t$fields[] = new GroepLogboekTable($groep);\n\n\t\t$this->addFields($fields);\n\n\t\t$this->formKnoppen = new ModalCloseButtons();\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function __invoke(PlacedOrderMessage $placedOrderMessage): void\n {\n try {\n $orderSent = $this->orderFacade->sendHeurekaOrderInfo($placedOrderMessage->orderId);\n\n if ($orderSent === true) {\n $this->logger->info('Order successfully sent to Heureka', [\n 'orderId' => $placedOrderMessage->orderId,\n ]);\n }\n } catch (Exception $exception) {\n $this->logger->error('Sending order to Heureka failed', [\n 'orderId' => $placedOrderMessage->orderId,\n 'exception' => $exception,\n ]);\n\n throw $exception;\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getRange(int|float $step = 1): array\n {\n return range($this->getMinimum(), $this->getMaximum(), $step);\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function work(\n Version $version,\n string $initialBranchName = AbstractShopsysReleaseWorker::MAIN_BRANCH_NAME,\n ): void {\n $this->processRunner->run('php ./utils/license-acknowledgements-generator/generate-acknowledgements.php');\n\n $this->processRunner->run('php phing markdown-fix');\n\n $this->commit('regenerated open source license acknowledgements');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function createUrlAlias(\n Location $location,\n string $path,\n string $languageCode,\n bool $forwarding = false,\n bool $alwaysAvailable = false\n ): URLAlias {\n $eventData = [\n $location,\n $path,\n $languageCode,\n $forwarding,\n $alwaysAvailable,\n ];\n\n $beforeEvent = new BeforeCreateUrlAliasEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return $beforeEvent->getUrlAlias();\n }\n\n $urlAlias = $beforeEvent->hasUrlAlias()\n ? $beforeEvent->getUrlAlias()\n : $this->innerService->createUrlAlias($location, $path, $languageCode, $forwarding, $alwaysAvailable);\n\n $this->eventDispatcher->dispatch(\n new CreateUrlAliasEvent($urlAlias, ...$eventData)\n );\n\n return $urlAlias;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function providerForTestGenerateTagThrowsInvalidArgumentException(): array\n {\n return [\n [['test', [], false], 'c'],\n [['some_invalid_pattern', [1, 2], true], 'ibx-c-1-v-2'],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "#[DataProvider('getAdministratorData')]\n public function testAdministratorDataIsAdded(?Administrator $expectedAdministrator): void\n {\n $orderProcessingData = $this->createOrderProcessingData();\n\n $loginAsUserFacade = $this->createMock(LoginAsUserFacade::class);\n $loginAsUserFacade->method('getCurrentAdministratorLoggedAsCustomer')->willReturn($expectedAdministrator);\n\n $setOrderDataAsAdministratorMiddleware = new SetOrderDataAsAdministratorMiddleware($loginAsUserFacade);\n\n $result = $setOrderDataAsAdministratorMiddleware->handle($orderProcessingData, $this->createOrderProcessingStack());\n $actualOrderData = $result->orderData;\n\n $this->assertSame($expectedAdministrator, $actualOrderData->createdAsAdministrator);\n $this->assertSame($expectedAdministrator?->getRealName(), $actualOrderData->createdAsAdministratorName);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function toDatabase(object $notifiable): array\n {\n $engagementType = match ($this->engagement->deliverable->channel) {\n EngagementDeliveryMethod::Email => 'Email',\n EngagementDeliveryMethod::Sms => 'SMS',\n default => ''\n };\n\n return FilamentNotification::make()\n ->danger()\n ->title('Engagement Delivery Failed')\n ->body(\"Your engagement {$engagementType} failed to be delivered to {$this->engagement->recipient->display_name}.\")\n ->getDatabaseMessage();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function user()\n {\n return $this->belongsTo(User::class);\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function __construct(\n protected readonly Domain $domain,\n protected readonly RequestStack $requestStack,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getTabDataCounter($name = null) {\n\t\treturn $this->getTab($name)->getAttribute('data-counter') ?? false;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getById(int $stockId): Stock\n {\n $stock = $this->getStockRepository()->find($stockId);\n\n if ($stock === null) {\n throw new StockNotFoundException();\n }\n\n return $stock;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function setUp(): void\n {\n parent::setUp();\n\n $this->groupsBySiteAccess = [\n self::EXISTING_SA_NAME => [self::SA_GROUP],\n 'first_sa' => [self::SA_GROUP],\n 'second_sa' => [self::SA_GROUP],\n ];\n $this->providers = [\n new StaticSiteAccessProvider([self::EXISTING_SA_NAME, 'first_sa'], $this->groupsBySiteAccess),\n new StaticSiteAccessProvider(['second_sa'], $this->groupsBySiteAccess),\n new StaticSiteAccessProvider([self::WITHOUT_GROUP_SA_NAME]),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function restore(Authenticatable $authenticatable, Prompt $prompt): Response\n {\n return $authenticatable->canOrElse(\n abilities: [\"prompt.{$prompt->id}.restore\"],\n denyResponse: 'You do not have permission to restore this prompt.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function testHandleGenerateListXlsxForRT()\n {\n self::bootKernel();\n $container = static::getContainer();\n $messageBus = $container->get(MessageBusInterface::class);\n $userEmail = 'admin-territoire-13-01@histologe.fr';\n $userRepository = static::getContainer()->get(UserRepository::class);\n /** @var User $user */\n $user = $userRepository->findOneBy(['email' => $userEmail]);\n $searchUser = new SearchUser($user);\n $message = new UserExportMessage($searchUser, 'xlsx');\n $messageBus->dispatch($message);\n $transport = $container->get('messenger.transport.async_priority_high');\n $envelopes = $transport->get();\n\n $this->assertCount(1, $envelopes);\n $handler = $container->get(UserExportMessageHandler::class);\n $handler($message);\n\n $this->assertEmailCount(1);\n /** @var NotificationEmail $email */\n $email = $this->getMailerMessage();\n\n $this->assertEmailHtmlBodyContains($email, 'export de la liste des utilisateurs');\n $this->assertEmailAddressContains($email, 'To', $userEmail);\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function getEmail(): string\n {\n return $this->email;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function down(): void\n {\n $twillUsersTable = config('twill.users_table', 'twill_users');\n\n if (Schema::hasTable($twillUsersTable) && Schema::hasColumn($twillUsersTable, 'google_2fa_secret')) {\n Schema::table($twillUsersTable, function (Blueprint $table) {\n $table->dropColumn('google_2fa_secret');\n });\n }\n\n if (Schema::hasTable($twillUsersTable) && Schema::hasColumn($twillUsersTable, 'google_2fa_enabled')) {\n Schema::table($twillUsersTable, function (Blueprint $table) {\n $table->dropColumn('google_2fa_enabled');\n });\n }\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "protected function getFieldName(): string\n {\n return 'number';\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function fetch(int $offset, int $limit): Iterator;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "#[Route(path: '/blog/article/list/', name: 'admin_blogarticle_list')]\n public function listAction(Request $request): Response\n {\n $domainFilterNamespace = 'blog-article';\n $selectedDomainId = $this->adminDomainFilterTabsFacade->getSelectedDomainId($domainFilterNamespace);\n\n $quickSearchData = new QuickSearchFormData();\n $quickSearchForm = $this->createForm(QuickSearchFormType::class, $quickSearchData);\n $quickSearchForm->handleRequest($request);\n\n $queryBuilder = $this->blogArticleFacade->getQueryBuilderForQuickSearch(\n $selectedDomainId,\n $quickSearchForm->getData(),\n );\n\n $grid = $this->blogArticleGridFactory->create($queryBuilder);\n\n return $this->render('@ShopsysFramework/Admin/Content/Blog/Article/list.html.twig', [\n 'quickSearchForm' => $quickSearchForm->createView(),\n 'gridView' => $grid->createView(),\n 'domainFilterNamespace' => $domainFilterNamespace,\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function up(): void\n {\n $assistants = AiAssistant::query()\n ->where('model', AiModel::OpenAiGpt4o)\n ->get();\n\n foreach ($assistants as $assistant) {\n try {\n /** @var AiAssistant $assistant */\n\n /** @var OpenAiGpt4oService $service */\n $service = $assistant->model->getService();\n\n $service->enableAssistantFileUploads($assistant);\n } catch (Throwable $e) {\n report($e);\n\n continue;\n }\n }\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function createLocationsFromRows(array $rows, $prefix = '', ?Location $location = null)\n {\n $locations = [];\n\n foreach ($rows as $row) {\n $id = $row[$prefix . 'node_id'];\n if (!isset($locations[$id])) {\n $locations[$id] = $this->createLocationFromRow($row, $prefix, $location);\n }\n }\n\n return array_values($locations);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getPlacement()\n {\n return $this->placement;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getTime(): ?float\n {\n return $this->searchResult->time;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testToFieldValue()\n {\n $storageFieldValue = new StorageFieldValue();\n $storageFieldValue->sortKeyString = '';\n $storageFieldValue->dataText = <<\n\n\nEOT;\n\n $expectedFieldValue = new FieldValue();\n $expectedFieldValue->data = ['destinationContentIds' => [3, 2, 1]];\n\n $actualFieldValue = new FieldValue();\n\n $this->converter->toFieldValue($storageFieldValue, $actualFieldValue);\n\n $this->assertEquals(\n $expectedFieldValue,\n $actualFieldValue\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function columns(): array\n {\n return [\n TextColumn::make('id', __('ID'))->searchable()->sortable(),\n ImageColumn::make('avatar', __('user_avatar')),\n TextColumn::make('name', __('user_name'))->searchable()->sortable()->description(function (User $user) {\n return new HtmlString(\"

{$user->phone}

{$user->email}

\");\n }),\n TextColumn::make('birthday')->dateTime(),\n TextColumn::make('status', __('user_status'))->badge(\n [\n 'active' => 'success',\n 'inactive' => 'danger',\n ],\n [\n 'active' => __('active'),\n 'inactive' => __('inactive'),\n ]\n ),\n TextColumn::make('gender', __('gender'))->badge([\n 'male' => 'primary',\n 'female' => 'danger',\n ], [\n 'male' => 'Nam',\n 'female' => 'N\u1eef',\n ]),\n TextColumn::make('created_at', __('Created At'))->dateTime()->sortable(),\n TextColumn::make('updated_at', __('Updated At'))->dateTime()->sortable(),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function getName()\n {\n return 'InfluxDB';\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "abstract public function loadUrlWildcardsData(int $offset = 0, int $limit = -1): array;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct(\n private readonly EsaboraSISHService $esaboraSISHService,\n ) {\n parent::__construct();\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function provideValidFieldSettings()\n {\n return [\n [\n [],\n ],\n [\n [\n 'isMultiple' => true,\n 'options' => ['foo', 'bar'],\n ],\n ],\n [\n [\n 'isMultiple' => false,\n 'options' => [23, 42],\n ],\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct(\n protected readonly EntityManagerInterface $em,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testCreateRelativeCacheResolver()\n {\n $this->configResolver\n ->expects(self::at(0))\n ->method('hasParameter')\n ->with('image_host')\n ->willReturn(true);\n\n $host = '/';\n\n $this->configResolver\n ->expects(self::at(1))\n ->method('getParameter')\n ->with('image_host')\n ->willReturn($host);\n\n $expected = new RelativeResolver($this->resolver);\n\n self::assertEquals($expected, $this->factory->createCacheResolver());\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function buildService(Repository $repository, $serviceName)\n {\n $methodName = 'get' . $serviceName . 'Service';\n if (!method_exists($repository, $methodName)) {\n throw new InvalidArgumentException($serviceName, 'No such service');\n }\n\n return $repository->$methodName();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(\n private readonly ProductVideoRepository $productVideoRepository,\n private readonly ProductVideoTranslationsRepository $productVideoTranslationsRepository,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testCreateCustomUrlAliasWithTheSamePathThrowsException(): void\n {\n $repository = $this->getRepository();\n $urlAliasService = $repository->getURLAliasService();\n $locationService = $repository->getLocationService();\n $language = 'ger-DE';\n\n $names = [\n 'eng-GB' => 'Contact',\n 'ger-DE' => 'Kontakt',\n 'eng-US' => 'Contact',\n ];\n $contactFolder = $this->createFolder(\n $names,\n 2,\n null,\n false // not always available, so the created content behaves the same as \"article\"\n );\n\n $this->expectException(InvalidArgumentException::class);\n $this->expectExceptionMessage(\n 'Argument \\'$path\\' is invalid: Path \\'Contact\\' already exists for the given context'\n );\n // attempt to create custom alias for German translation while a system one\n // for a different translation already exists\n $urlAliasService->createUrlAlias(\n $locationService->loadLocation(\n $contactFolder->contentInfo->mainLocationId\n ),\n 'Contact',\n $language,\n true, // forwarding\n true // always available\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function provideInputForToHash()\n {\n return [\n [\n new SelectionValue(),\n [],\n ],\n [\n new SelectionValue([23, 42]),\n [23, 42],\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (Blueprint $table) {\n $table->string('google_2fa_secret')->nullable();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function viewFooter()\n\t{\n\t\treturn '';\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function getStatus(): int\n {\n return $this->status;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function process(ContainerBuilder $container)\n {\n foreach ($container->findTaggedServiceIds('console.command') as $id => $attributes) {\n $definition = $container->getDefinition($id);\n\n $definition->addMethodCall('addOption', [\n 'siteaccess',\n null,\n InputOption::VALUE_OPTIONAL,\n 'SiteAccess to use for operations. If not provided, default siteaccess will be used',\n ]);\n }\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "abstract protected function getUserIdentifier(): string;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function testDashboardGraphWidget_ProblemsDisabledFields() {\n\t\t$this->page->login()->open(self::DASHBOARD_URL);\n\t\t$form = $this->openGraphWidgetConfiguration();\n\t\t$form->selectTab('Problems');\n\n\t\t$fields = ['Selected items only', 'Severity', 'Problem', 'Tags', 'Problem hosts'];\n\t\t$tag_elements = [\n\t\t\t'id:evaltype',\t\t\t\t// Tag type.\n\t\t\t'id:tags_0_tag',\t\t\t// Tag name.\n\t\t\t'id:tags_0_operator',\t\t// Tag operator.\n\t\t\t'id:tags_0_value',\t\t\t// Tag value\n\t\t\t'id:tags_0_remove',\t\t\t// Tag remove button.\n\t\t\t'id:tags_add'\t\t\t\t// Tagg add button.\n\t\t];\n\t\t$this->assertEnabledFields(array_merge($fields, $tag_elements), false);\n\n\t\t// Set \"Show problems\" and check that fields enabled now.\n\t\t$form->fill(['Show problems' => true]);\n\t\t$this->assertEnabledFields(array_merge($fields, $tag_elements), true);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function setLimit(int $limit): void;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public static function getName(): string\n {\n return 'upgrade';\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function setDate(Carbon $date): void;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function setId(int $id): void\n {\n $this->id = $id;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testCpUpsOverTemp(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:161->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 488:17:19:10.00\nSNMPv2-MIB::snmpTrapOID.0 CPS-MIB::upsOverTemp\nCPS-MIB::mtrapinfoString \"The UPS inner temperature is too high.\"\nSNMP-COMMUNITY-MIB::snmpTrapAddress.0 $device->ip\nSNMP-COMMUNITY-MIB::snmpTrapCommunity.0 \"comstring\"\nSNMPv2-MIB::snmpTrapEnterprise.0 CPS-MIB::cps\nTRAP,\n 'The UPS inner temperature is too high.',\n 'Could not handle CpUpsOverTemp trap',\n [Severity::Error],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function testGetExistingSiteAccess(string $siteAccessName, array $expectedGroups): void\n {\n $chainSiteAccessProvider = $this->getChainSiteAccessProvider();\n $expectedSiteAccess = new SiteAccess(\n $siteAccessName,\n SiteAccess::DEFAULT_MATCHING_TYPE,\n null,\n StaticSiteAccessProvider::class\n );\n $expectedSiteAccess->groups = $expectedGroups;\n\n $this->assertEquals(\n $expectedSiteAccess,\n $chainSiteAccessProvider->getSiteAccess($siteAccessName)\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(SettingCreateStruct $settingCreateStruct)\n {\n $this->settingCreateStruct = $settingCreateStruct;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function configureStore(Classificationstore\\StoreConfig $store): void\n {\n $group = Classificationstore\\GroupConfig::getByName('group1', $store->getId());\n if (!$group) {\n // create group\n $group = new Classificationstore\\GroupConfig();\n $group->setStoreId($store->getId());\n $group->setName('group1');\n $group->save();\n }\n\n $key1 = Classificationstore\\KeyConfig::getByName('field1', $store->getId());\n if (!$key1) {\n //create field1\n $key1 = new Classificationstore\\KeyConfig();\n $key1->setDefinition(json_encode(new ClassDefinition\\Data\\Input()));\n $key1->setStoreId($store->getId());\n $key1->setName('field1');\n $key1->setDescription('Input Field 1');\n $key1->setEnabled(true);\n $key1->setType('input');\n $key1->save();\n }\n\n $key2 = Classificationstore\\KeyConfig::getByName('field2', $store->getId());\n if (!$key2) {\n //create field2\n $key2 = new Classificationstore\\KeyConfig();\n $key2->setDefinition(json_encode(new ClassDefinition\\Data\\Input()));\n $key2->setStoreId($store->getId());\n $key2->setName('field2');\n $key2->setDescription('Input Field 2');\n $key2->setEnabled(true);\n $key2->setType('input');\n $key2->save();\n }\n\n $keygroup1 = Classificationstore\\KeyGroupRelation::getByGroupAndKeyId($group->getId(), $key1->getId());\n if (!$keygroup1) {\n //create key group relation\n $keygroup1 = new Classificationstore\\KeyGroupRelation();\n $keygroup1->setKeyId($key1->getId());\n $keygroup1->setGroupId($group->getId());\n $keygroup1->setSorter(1);\n $keygroup1->save();\n }\n\n $keygroup2 = Classificationstore\\KeyGroupRelation::getByGroupAndKeyId($group->getId(), $key2->getId());\n if (!$keygroup2) {\n $keygroup2 = new Classificationstore\\KeyGroupRelation();\n $keygroup2->setKeyId($key2->getId());\n $keygroup2->setGroupId($group->getId());\n $keygroup2->setSorter(2);\n $keygroup2->save();\n }\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getInvalidQuantityProvider(): array\n {\n return [\n [0],\n [-1],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function getStats(): array\n {\n return [\n Stat::make('Licensed Users', Number::abbreviate(\n Cache::tags([$this->cacheTag])->remember('licensed-ai-users-count', now()->addHours(24), function (): int {\n return LicenseType::ConversationalAi->getSeatsInUse();\n }),\n maxPrecision: 2,\n )),\n Stat::make('Available Licenses', Number::abbreviate(\n Cache::tags([$this->cacheTag])->remember('available-ai-licenses', now()->addHours(24), function (): int {\n return LicenseType::ConversationalAi->getAvailableSeats();\n }),\n maxPrecision: 2,\n )),\n Stat::make('Number of Assistants', Number::abbreviate(\n Cache::tags([$this->cacheTag])->remember('ai-assistants-count', now()->addHours(24), function (): int {\n return AiAssistant::count();\n }),\n maxPrecision: 2,\n )),\n Stat::make('Exchanges', Cache::tags([$this->cacheTag])->remember('ai-exchanges', now()->addHours(24), function (): int|string {\n $count = TrackedEventCount::where('type', TrackedEventType::AiExchange)->first()?->count;\n\n return ! is_null($count) ? Number::abbreviate($count, maxPrecision: 2) : 'N/A';\n })),\n Stat::make('New Exchanges', Cache::tags([$this->cacheTag])->remember('ai-new-exchanges', now()->addHours(24), function (): int|string {\n return Number::abbreviate(\n TrackedEvent::query()\n ->where('type', TrackedEventType::AiExchange)\n ->whereDate('occurred_at', '>=', now()->subDays(30))\n ->count(),\n maxPrecision: 2\n );\n })),\n Stat::make('Saved Conversations', Cache::tags([$this->cacheTag])->remember('ai-saved-conversations', now()->addHours(24), function (): int|string {\n $count = TrackedEventCount::where('type', TrackedEventType::AiThreadSaved)->first()?->count;\n\n return ! is_null($count) ? Number::abbreviate($count, maxPrecision: 2) : 'N/A';\n })),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function __construct(protected readonly ModuleFacade $moduleFacade)\n {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testGetTimezoneFrom(string $userEmail, string $timezone)\n {\n static::bootKernel();\n\n /** @var EntityManagerInterface $entityManager */\n $entityManager = static::getContainer()->get('doctrine.orm.default_entity_manager');\n\n $user = $entityManager->getRepository(User::class)->findOneBy([\n 'email' => $userEmail,\n ]);\n $securityMock = $this->createMock(Security::class);\n $securityMock->method('getUser')->willReturn($user);\n $timezoneProvider = new TimezoneProvider($securityMock);\n\n $this->assertEquals($timezone, $timezoneProvider->getTimezone());\n $this->assertEquals(new \\DateTimeZone($timezone), $timezoneProvider->getDateTimezone());\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "function (ProductVideoData $productVideoData) {\n return (bool)$productVideoData->id !== true;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n createDefaultRelationshipTableFields($table, 'generic_page', 'event');\n $table->integer('position')->unsigned()->index();\n $table->timestamps();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function createLocationProxy(\n int $locationId,\n array $prioritizedLanguages = Language::ALL\n ): Location {\n $initializer = function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($locationId, $prioritizedLanguages): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getLocationService()->loadLocation(\n $locationId,\n $prioritizedLanguages\n );\n\n return true;\n };\n\n return $this->proxyGenerator->createProxy(Location::class, $initializer);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getTagAttributes($node)\n\t{\n\t\treturn [\n\t\t\t'woonoord' => $node->attrs->id,\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "static function (ContentType $contentType): string {\n return $contentType->identifier;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function getVideoToken(): string\n {\n return $this->videoToken;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getTestBuildSharedGatewayData(): Traversable\n {\n $databasePlatformGatewayPairs = [\n [new Platforms\\SqlitePlatform(), SqliteGateway::class],\n [new Platforms\\MySQL80Platform(), FallbackGateway::class],\n [new Platforms\\MySqlPlatform(), FallbackGateway::class],\n [new Platforms\\PostgreSqlPlatform(), FallbackGateway::class],\n ];\n\n foreach ($databasePlatformGatewayPairs as $databasePlatformGatewayPair) {\n [$databasePlatform, $sharedGateway] = $databasePlatformGatewayPair;\n /** @var \\Doctrine\\DBAL\\Platforms\\AbstractPlatform $databasePlatform */\n $connectionMock = $this\n ->createMock(Connection::class);\n $connectionMock\n ->expects(self::any())\n ->method('getDatabasePlatform')\n ->willReturn($databasePlatform);\n\n yield [\n $connectionMock,\n $sharedGateway,\n ];\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setInNomeEscola(?string $inNomeEscola): self\n\t{\n\t\t$this->inNomeEscola = $inNomeEscola;\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "#[Route(path: '/mail/template/')]\n public function templateAction(): Response\n {\n $grid = $this->mailTemplateGridFactory->create();\n\n return $this->render('@ShopsysFramework/Admin/Content/Mail/list.html.twig', [\n 'gridView' => $grid->createView(),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function accepts(FilteringCriterion $criterion): bool\n {\n return $criterion instanceof ContentTypeIdentifier;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function toggleUpvote(): void\n {\n if ($this->isUpvoted()) {\n $this->cancelUpvote();\n\n return;\n }\n\n $this->upvote();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function testMatchLocation($matchingConfig, Location $location, $expectedResult)\n {\n $this->matcher->setMatchingConfig($matchingConfig);\n $this->assertSame($expectedResult, $this->matcher->matchLocation($location));\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getContentTypeDraft(): ContentTypeDraft\n {\n return $this->contentTypeDraft;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function loadIdList(): array\n {\n return $this->locationAwareConfigRepository->fetchAllKeys();\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getNoteText(int $journalId): ?string;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function create(CreateStruct $struct)\n {\n $language = $this->innerHandler->create($struct);\n $this->storeCache([$language]);\n\n return $language;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testCpUpsRebootStarted(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:161->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 488:17:19:10.00\nSNMPv2-MIB::snmpTrapOID.0 CPS-MIB::upsRebootStarted\nCPS-MIB::mtrapinfoString \"The UPS started reboot sequence.\"\nSNMP-COMMUNITY-MIB::snmpTrapAddress.0 $device->ip\nSNMP-COMMUNITY-MIB::snmpTrapCommunity.0 \"comstring\"\nSNMPv2-MIB::snmpTrapEnterprise.0 CPS-MIB::cps\nTRAP,\n 'The UPS started reboot sequence.',\n 'Could not handle CpUpsRebootStarted trap',\n [Severity::Warning],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function getFunctions()\n {\n $renderFieldCallable = function (Environment $environment, Content $content, $fieldIdentifier, array $params = []) {\n $this->fieldBlockRenderer->setTwig($environment);\n\n return $this->renderField($content, $fieldIdentifier, $params);\n };\n\n $renderFieldDefinitionSettingsCallable = function (Environment $environment, FieldDefinition $fieldDefinition, array $params = []) {\n $this->fieldBlockRenderer->setTwig($environment);\n\n return $this->renderFieldDefinitionSettings($fieldDefinition, $params);\n };\n\n return [\n new TwigFunction(\n 'ez_render_field',\n $renderFieldCallable,\n [\n 'is_safe' => ['html'],\n 'needs_environment' => true,\n 'deprecated' => '4.0',\n 'alternative' => 'ibexa_render_field',\n ]\n ),\n new TwigFunction(\n 'ibexa_render_field',\n $renderFieldCallable,\n ['is_safe' => ['html'], 'needs_environment' => true]\n ),\n new TwigFunction(\n 'ez_render_field_definition_settings',\n $renderFieldDefinitionSettingsCallable,\n [\n 'is_safe' => ['html'],\n 'needs_environment' => true,\n 'deprecated' => '4.0',\n 'alternative' => 'ibexa_render_field_definition_settings',\n ]\n ),\n new TwigFunction(\n 'ibexa_render_field_definition_settings',\n $renderFieldDefinitionSettingsCallable,\n ['is_safe' => ['html'], 'needs_environment' => true]\n ),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function detectFieldMapping($headers = null) {\n\t\t$rows = $this->getRows();\n\n\t\tif ($rows->count() === 0) {\n\t\t\tthrow new \\Exception('Failed to detect mapping for an empty multifield table.');\n\t\t}\n\n\t\tif ($headers === null) {\n\t\t\t$headers = $this->getHeadersText();\n\t\t}\n\n\t\t$result = [];\n\t\tforeach ($rows->first()->query($this->selectors['column'])->all() as $i => $column) {\n\t\t\t$label = CTestArrayHelper::get($headers, $i, $i);\n\t\t\t$element = CElementQuery::getInputElement($column, '.')->detect();\n\n\t\t\tif (!$element->isValid()) {\n\t\t\t\t$result[$label] = null;\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$value = $element->getAttribute('name');\n\t\t\tif ($value !== null) {\n\t\t\t\t$element->query('xpath', './/*[@name]')->one(false);\n\t\t\t\tif ($element->isValid()) {\n\t\t\t\t\t$value = $element->getAttribute('name');\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($value !== null) {\n\t\t\t\t$name = $value;\n\t\t\t\tif (substr($value, -1) === ']') {\n\t\t\t\t\t$pos = strrpos($value, '[');\n\t\t\t\t\tif ($pos !== false) {\n\t\t\t\t\t\t$name = substr($value, $pos + 1, -1);\n\t\t\t\t\t\tif (is_numeric($name)) {\n\t\t\t\t\t\t\t$value = substr($value, 0, $pos);\n\t\t\t\t\t\t\t$pos = strrpos($value, '[');\n\n\t\t\t\t\t\t\tif ($pos !== false) {\n\t\t\t\t\t\t\t\t$name = substr($value, $pos + 1, -1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!$name || is_numeric($name)) {\n\t\t\t\t\t\t$name = $label;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Element name cannot be detected, using label or index.\n\t\t\t\t$name = $label;\n\t\t\t}\n\n\t\t\t$aliases = [];\n\t\t\tif ($name !== $label) {\n\t\t\t\t$aliases[] = $label;\n\t\t\t}\n\t\t\t$aliases[] = $i;\n\n\t\t\tif (!empty($this->names) && array_key_exists($name, $this->names)) {\n\t\t\t\t$aliases[] = $name;\n\t\t\t\t$name = $this->names[$name];\n\t\t\t}\n\n\t\t\tforeach ($aliases as $alias) {\n\t\t\t\t$this->aliases[$alias] = $name;\n\t\t\t}\n\n\t\t\t$result[$label] = [\n\t\t\t\t'name' => $name,\n\t\t\t\t'class' => get_class($element),\n\t\t\t\t'selector' => CElementQuery::getLastSelector()\n\t\t\t];\n\t\t}\n\n\t\treturn $result;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function testCpUpsChargerFailure(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:161->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 488:17:19:10.00\nSNMPv2-MIB::snmpTrapOID.0 CPS-MIB::upsChargerFailure\nCPS-MIB::mtrapinfoString \"The battery charger is abnormal.\"\nSNMP-COMMUNITY-MIB::snmpTrapAddress.0 $device->ip\nSNMP-COMMUNITY-MIB::snmpTrapCommunity.0 \"comstring\"\nSNMPv2-MIB::snmpTrapEnterprise.0 CPS-MIB::cps\nTRAP,\n 'The battery charger is abnormal.',\n 'Could not handle CpUpsChargerFailure trap',\n [Severity::Warning],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "private function shouldExcludeFromAuthCheck(ServerRequestInterface $request): bool\n {\n $uri = $request->getUri()->getPath();\n if (\n CommonService::isCliRequest() ||\n CommonService::isAjaxRequest($request) !== false ||\n CommonService::isExcludedUri($uri, $this->excludedUris) === true\n ) {\n return true;\n }\n return false;\n }", "smellKey": "0", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function put($device, $measurement, $tags, $fields)\n {\n $stat = Measurement::start('write');\n $tmp_fields = [];\n $tmp_tags['hostname'] = $device['hostname'];\n foreach ($tags as $k => $v) {\n if (empty($v)) {\n $v = '_blank_';\n }\n $tmp_tags[$k] = $v;\n }\n foreach ($fields as $k => $v) {\n if ($k == 'time') {\n $k = 'rtime';\n }\n\n if (($value = $this->forceType($v)) !== null) {\n $tmp_fields[$k] = $value;\n }\n }\n\n if (empty($tmp_fields)) {\n Log::warning('All fields empty, skipping update', ['orig_fields' => $fields]);\n\n return;\n }\n\n Log::debug('InfluxDB data: ', [\n 'measurement' => $measurement,\n 'tags' => $tmp_tags,\n 'fields' => $tmp_fields,\n ]);\n\n try {\n $points = [\n new \\InfluxDB\\Point(\n $measurement,\n null, // the measurement value\n $tmp_tags,\n $tmp_fields // optional additional fields\n ),\n ];\n\n $this->connection->writePoints($points);\n $this->recordStatistic($stat->end());\n } catch (\\InfluxDB\\Exception $e) {\n Log::error('InfluxDB exception: ' . $e->getMessage());\n Log::debug($e->getTraceAsString());\n }\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function toStorageFieldDefinition(FieldDefinition $fieldDef, StorageFieldDefinition $storageDef): void\n {\n $validatorParameters = [];\n if (isset($fieldDef->fieldTypeConstraints->validators[self::PASSWORD_VALIDATOR_IDENTIFIER])) {\n $validatorParameters = $fieldDef->fieldTypeConstraints->validators[self::PASSWORD_VALIDATOR_IDENTIFIER];\n }\n\n $rules = [\n 'requireAtLeastOneUpperCaseCharacter' => self::REQUIRE_AT_LEAST_ONE_UPPER_CASE_CHAR,\n 'requireAtLeastOneLowerCaseCharacter' => self::REQUIRE_AT_LEAST_ONE_LOWER_CASE_CHAR,\n 'requireAtLeastOneNumericCharacter' => self::REQUIRE_AT_LEAST_ONE_NUMERIC_CHAR,\n 'requireAtLeastOneNonAlphanumericCharacter' => self::REQUIRE_AT_LEAST_ONE_NON_ALPHANUMERIC_CHAR,\n 'requireNewPassword' => self::REQUIRE_NEW_PASSWORD,\n ];\n\n $fieldSettings = $fieldDef->fieldTypeConstraints->fieldSettings;\n\n $storageDef->dataInt1 = 0;\n foreach ($rules as $rule => $flag) {\n if (isset($validatorParameters[$rule]) && $validatorParameters[$rule]) {\n $storageDef->dataInt1 |= $flag;\n }\n }\n\n $storageDef->dataInt1 |= $fieldSettings[UserType::REQUIRE_UNIQUE_EMAIL]\n ? self::REQUIRE_UNIQUE_EMAIL\n : 0;\n\n $storageDef->dataInt2 = null;\n if (isset($validatorParameters['minLength'])) {\n $storageDef->dataInt2 = $validatorParameters['minLength'];\n }\n\n $storageDef->dataInt3 = $fieldSettings[UserType::PASSWORD_TTL_SETTING] ?? null;\n $storageDef->dataInt4 = $fieldSettings[UserType::PASSWORD_TTL_WARNING_SETTING] ?? null;\n\n $storageDef->dataText2 = $fieldSettings[UserType::USERNAME_PATTERN];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "abstract public function removeFileReference($fieldId, $versionNo);", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function concerningProspect(Prospect $prospect = null): self\n {\n return $this->state([\n 'concern_id' => $prospect?->id ?? Prospect::factory(),\n 'concern_type' => (new Prospect())->getMorphClass(),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getIgnoredMultidomainEntitiesNames(): array;", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function loadByIdentifier($identifier)\n {\n $cacheItem = $this->cache->getItem(\n $this->cacheIdentifierGenerator->generateKey(\n self::SECTION_WITH_BY_ID_IDENTIFIER,\n [$this->cacheIdentifierSanitizer->escapeForCacheKey($identifier)],\n true\n )\n );\n\n if ($cacheItem->isHit()) {\n return $cacheItem->get();\n }\n\n $this->logger->logCall(__METHOD__, ['section' => $identifier]);\n $section = $this->persistenceHandler->sectionHandler()->loadByIdentifier($identifier);\n\n $cacheItem->set($section);\n $cacheItem->tag([\n $this->cacheIdentifierGenerator->generateTag(self::SECTION_IDENTIFIER, [$section->id]),\n ]);\n\n $this->cache->save($cacheItem);\n\n return $section;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "#[\\ReturnTypeWillChange]\n public function getIterator(): iterable\n {\n yield from parent::getIterator();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getFilterType() {\n\t\tif ($this->context === self::CONTEXT_LEFT) {\n\t\t\treturn [\n\t\t\t\t'selected_tab' => $this->query('xpath:./nav/ul/li/ul['.CXPathHelper::fromClass('ui-sortable-container').\n\t\t\t\t\t\t']/li['.CXPathHelper::fromClass('selected').']')->one(),\n\t\t\t\t'attribute' => 'data-target',\n\t\t\t\t'is_expanded' => function ($target) {\n\t\t\t\t\treturn $target->hasClass('expanded');\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\t\telse {\n\t\t\t// Time tab on the right side in multitab filter.\n\t\t\tif ($this->query('xpath:./nav')->one(false)->isValid()) {\n\t\t\t\treturn [\n\t\t\t\t\t'selected_tab' => $this->query('xpath:./nav/ul/li/ul[not(contains(@class,\"ui-sortable-container\"))]'.\n\t\t\t\t\t\t\t'/li['.CXPathHelper::fromClass('selected').']')->one(),\n\t\t\t\t\t'attribute' => 'data-target',\n\t\t\t\t\t'is_expanded' => function ($target) {\n\t\t\t\t\t\treturn $target->hasClass('expanded');\n\t\t\t\t\t}\n\t\t\t\t];\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t// Last selected tab. It can be closed or open.\n\t\t\t\t'selected_tab' => $this->query('xpath:./ul/li[@tabindex=\"0\"]')->one(),\n\t\t\t\t'attribute' => 'aria-controls',\n\t\t\t\t'is_expanded' => function ($target) {\n\t\t\t\t\treturn filter_var($target->getAttribute('aria-expanded'), FILTER_VALIDATE_BOOLEAN);\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function setSuggestionCollector(SuggestionCollectorInterface $suggestionCollector);", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getUser(): ?User\n {\n return $this->user;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function setBailleur(?Bailleur $bailleur): static\n {\n $this->bailleur = $bailleur;\n\n return $this;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function deleteObjectStateGroup(ObjectStateGroup $objectStateGroup): void\n {\n $eventData = [$objectStateGroup];\n\n $beforeEvent = new BeforeDeleteObjectStateGroupEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return;\n }\n\n $this->innerService->deleteObjectStateGroup($objectStateGroup);\n\n $this->eventDispatcher->dispatch(\n new DeleteObjectStateGroupEvent(...$eventData)\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function process(ContainerBuilder $container)\n {\n $pluginDataFixtureRegistryDefinition = $container->findDefinition(\n PluginDataFixtureRegistry::class,\n );\n $taggedServiceIds = $container->findTaggedServiceIds('shopsys.data_fixture');\n\n foreach (array_keys($taggedServiceIds) as $serviceId) {\n $this->registerDataFixture($pluginDataFixtureRegistryDefinition, $serviceId);\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function viewHeader()\n\t{\n\t\treturn '';\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function getUserGroup(): UserGroup\n {\n return $this->userGroup;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function model($className=__CLASS__)\n\t{\n\t\treturn parent::model($className);\n\t}", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "public function createLanguage(LanguageCreateStruct $languageCreateStruct): Language\n {\n $eventData = [$languageCreateStruct];\n\n $beforeEvent = new BeforeCreateLanguageEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return $beforeEvent->getLanguage();\n }\n\n $language = $beforeEvent->hasLanguage()\n ? $beforeEvent->getLanguage()\n : $this->innerService->createLanguage($languageCreateStruct);\n\n $this->eventDispatcher->dispatch(\n new CreateLanguageEvent($language, ...$eventData)\n );\n\n return $language;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function isEnabled()\n {\n return Config::get('influxdb.enable', false);\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function index(Request $request)\n {\n $items = Experience::webPublished()->notUnlisted()->ordered()->paginate();\n $title = 'Interactive Features';\n\n $this->seo->setTitle($title);\n\n $nav = [\n ['label' => 'Publications', 'href' => route('articles_publications'), 'links' => [\n [\n 'label' => 'Articles',\n 'href' => route('articles'),\n 'active' => false,\n ],\n [\n 'label' => 'Interactive Features',\n 'href' => route('interactiveFeatures'),\n 'active' => true,\n ],\n [\n 'label' => 'Digital Publications',\n 'href' => route('collection.publications.digital-publications'),\n 'active' => false,\n ],\n [\n 'label' => 'Print Publications',\n 'href' => route('collection.publications.printed-publications'),\n 'active' => false,\n ]\n ]],\n ];\n\n $crumbs = [\n ['label' => 'The Collection', 'href' => route('collection')],\n ['label' => 'Publications', 'href' => route('articles_publications')],\n ['label' => $title, 'href' => ''],\n ];\n\n $view_data = [\n 'title' => $title,\n 'nav' => $nav,\n 'breadcrumb' => $crumbs,\n 'wideBody' => true,\n 'filters' => null,\n 'listingCountText' => 'Showing ' . $items->total() . ' items',\n 'listingItems' => $items,\n 'type' => 'experience',\n ];\n\n return view('site.genericPage.index', $view_data);\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "function (Prospect $record) {\n return $record->status->name;\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getParameterName()\n {\n return collect($this->subtypeToParameter)->get($this->subtype);\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function setLoginToken($loginToken);", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function rules()\n {\n return [\n 'email' => 'required|email',\n 'password' => 'required|min:6',\n ];\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function getConfig()\n {\n $contentTypeGroups = [];\n\n $preferredLanguages = $this->userLanguagePreferenceProvider->getPreferredLanguages();\n $loadedContentTypeGroups = $this->contentTypeService->loadContentTypeGroups(\n $preferredLanguages\n );\n\n $eventContentTypeGroups = [];\n foreach ($loadedContentTypeGroups as $contentTypeGroup) {\n $eventContentTypeGroups[] = $contentTypeGroup;\n }\n\n /** @var \\Ibexa\\AdminUi\\Event\\AddContentTypeGroupToUIConfigEvent $event */\n $event = $this->eventDispatcher->dispatch(new AddContentTypeGroupToUIConfigEvent($eventContentTypeGroups));\n\n foreach ($event->getContentTypeGroups() as $contentTypeGroup) {\n $contentTypes = $this->contentTypeService->loadContentTypes(\n $contentTypeGroup,\n $preferredLanguages\n );\n\n usort($contentTypes, static function (ContentType $contentType1, ContentType $contentType2) {\n return strnatcasecmp($contentType1->getName(), $contentType2->getName());\n });\n\n foreach ($contentTypes as $contentType) {\n $contentTypeGroups[$contentTypeGroup->identifier][] = $this->getContentTypeData(\n $contentType,\n $contentTypeGroup->isSystem,\n );\n }\n }\n\n /** @var \\Ibexa\\AdminUi\\Event\\FilterContentTypesEvent $event */\n $event = $this->eventDispatcher->dispatch(new FilterContentTypesEvent($contentTypeGroups));\n\n return $event->getContentTypeGroups();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(string $extensionName, string $type, string $name, string $varName)\n {\n parent::__construct([], ['extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName]);\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function testCartIsMergedAfterLogin(): void\n {\n $anonymouslyAddedProduct = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . '5', Product::class);\n $anonymouslyAddedProductQuantity = 6;\n $this->addProductToCustomerCart($anonymouslyAddedProduct, $anonymouslyAddedProductQuantity);\n\n $anonymouslyAddedProduct2 = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . '1', Product::class);\n $anonymouslyAddedProductQuantity2 = 1;\n $this->addProductToCustomerCart($anonymouslyAddedProduct2, $anonymouslyAddedProductQuantity2);\n\n $testCartUuid = CartDataFixture::CART_UUID;\n\n $loginMutationWithCartUuid = 'mutation {\n Login(input: {\n email: \"no-reply@shopsys.com\"\n password: \"user123\"\n cartUuid: \"' . $testCartUuid . '\"\n }) {\n tokens {\n accessToken\n refreshToken\n }\n showCartMergeInfo\n }\n }\n ';\n\n $response = $this->getResponseDataForGraphQlType(\n $this->getResponseContentForQuery($loginMutationWithCartUuid),\n 'Login',\n );\n\n $cart = $this->findCartOfCurrentCustomer();\n\n self::assertNotNull($cart);\n\n self::assertTrue($response['showCartMergeInfo']);\n\n $cartItems = $cart->getItems();\n self::assertCount(3, $cartItems);\n\n self::assertEquals($anonymouslyAddedProduct->getFullname(), $cartItems[0]->getName(), 'First product name mismatch');\n self::assertEquals($anonymouslyAddedProductQuantity, $cartItems[0]->getQuantity(), 'First product quantity mismatch');\n\n self::assertEquals($anonymouslyAddedProduct2->getFullname(), $cartItems[1]->getName(), 'Second product name mismatch');\n self::assertEquals(3, $cartItems[1]->getQuantity(), 'Second product quantity mismatch');\n\n $thirdProduct = $this->getReference(ProductDataFixture::PRODUCT_PREFIX . '72', Product::class);\n self::assertEquals($thirdProduct->getFullname(), $cartItems[2]->getName(), 'Third product name mismatch');\n self::assertEquals(2, $cartItems[2]->getQuantity(), 'Third product quantity mismatch');\n\n $oldCart = $this->cartFacade->findCartByCartIdentifier($testCartUuid);\n self::assertNull($oldCart);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function unmarshal(mixed $value, array $params = []): mixed\n {\n if (is_array($value) && ($value['value'] !== null || $value['value2'] !== null)) {\n $minMaxValue = Serialize::unserialize($value['value'] ?? null);\n\n return [\n 'minimum' => $minMaxValue['minimum'] ?? null,\n 'maximum' => $minMaxValue['maximum'] ?? null,\n 'unitId' => $value['value2'],\n ];\n }\n\n return null;\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected function getBearerToken(): string\n\t{\n\t\treturn $this->bearerToken ?: \"\";\n\t}", "smellKey": "0", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function setContentTypeGroup(?ContentTypeGroup $contentTypeGroup): void\n {\n $this->contentTypeGroup = $contentTypeGroup;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function prepareDashboardData() {\n\t\t$response = CDataHelper::call('dashboard.create', [\n\t\t\t[\n\t\t\t\t'name' => 'Dashboard for Single Item Widget test',\n\t\t\t\t'private' => 0,\n\t\t\t\t'pages' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'name' => 'Page with widgets',\n\t\t\t\t\t\t'widgets' => [\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'item',\n\t\t\t\t\t\t\t\t'name' => self::$old_name,\n\t\t\t\t\t\t\t\t'x' => 0,\n\t\t\t\t\t\t\t\t'y' => 0,\n\t\t\t\t\t\t\t\t'width' => 12,\n\t\t\t\t\t\t\t\t'height' => 4,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 4,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemid',\n\t\t\t\t\t\t\t\t\t\t'value' => 42230\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'adv_conf',\n\t\t\t\t\t\t\t\t\t\t'value' => 1\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 1,\n\t\t\t\t\t\t\t\t\t\t'name' => 'description',\n\t\t\t\t\t\t\t\t\t\t'value' => 'Some description here. \u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435.'\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'desc_h_pos',\n\t\t\t\t\t\t\t\t\t\t'value' => 0\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'desc_v_pos',\n\t\t\t\t\t\t\t\t\t\t'value' => 0\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'time_h_pos',\n\t\t\t\t\t\t\t\t\t\t'value' => 2\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'time_v_pos',\n\t\t\t\t\t\t\t\t\t\t'value' => 2\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'desc_size',\n\t\t\t\t\t\t\t\t\t\t'value' => 17\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'decimal_size',\n\t\t\t\t\t\t\t\t\t\t'value' => 41\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'value_size',\n\t\t\t\t\t\t\t\t\t\t'value' => 56\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 0,\n\t\t\t\t\t\t\t\t\t\t'name' => 'time_size',\n\t\t\t\t\t\t\t\t\t\t'value' => 14\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'item',\n\t\t\t\t\t\t\t\t'name' => 'Widget to delete',\n\t\t\t\t\t\t\t\t'x' => 13,\n\t\t\t\t\t\t\t\t'y' => 0,\n\t\t\t\t\t\t\t\t'width' => 4,\n\t\t\t\t\t\t\t\t'height' => 4,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => 4,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemid',\n\t\t\t\t\t\t\t\t\t\t'value' => 42230\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\t\tself::$dashboardid = $response['dashboardids'][0];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n $table->integer('article_id')->unsigned();\n $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');\n $table->integer('related_article_id')->unsigned();\n $table->foreign('related_article_id')->references('id')->on('articles')->onDelete('cascade');\n $table->index(['related_article_id', 'article_id']);\n $table->integer('position')->unsigned()->index();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function listLocationAliases(\n Location $location,\n bool $custom = true,\n ?string $languageCode = null,\n ?bool $showAllTranslations = null,\n ?array $prioritizedLanguages = null\n ): iterable {\n return $this->service->listLocationAliases(\n $location,\n $custom,\n $languageCode,\n $this->languageResolver->getShowAllTranslations($showAllTranslations),\n $this->languageResolver->getPrioritizedLanguages($prioritizedLanguages)\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function toArray(): array\n {\n return [\n 'minimum' => $this->getMinimum(),\n 'maximum' => $this->getMaximum(),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function up(): void\n {\n Schema::table('component_statuslog', function (Blueprint $table) {\n $table->foreign('component_id', 'component_statuslog_ibfk_1')->references('id')->on('component')->onUpdate('CASCADE')->onDelete('CASCADE');\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "abstract public function find(\n Criterion $criterion,\n int $offset,\n int $limit,\n array $sortClauses = [],\n bool $doCount = true\n ): array;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function getChainSiteAccessProvider(): ChainSiteAccessProvider\n {\n return new ChainSiteAccessProvider($this->providers);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testNewIdCodePair(): void\n {\n $transform = new CountryDataModifierVersion20190121094400($this->data);\n\n $expected = ['SK' => 2, 'CZ' => 1, 'MA' => 5, 'UB' => 6];\n\n $this->assertEquals($expected, $transform->getNewIdCodePair());\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getContentInfo(): ContentInfo\n {\n return $this->contentInfo;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('families', function (Blueprint $table) {\n createDefaultTableFields($table);\n\n $table->string('title')->nullable();\n $table->text('text')->nullable();\n $table->string('link_label')->nullable();\n $table->string('external_link')->nullable();\n\n $table->integer('position')->unsigned()->nullable();\n\n $table->integer('page_id')->unsigned();\n $table->foreign('page_id')->references('id')->on('pages')->onDelete('CASCADE');\n });\n\n Schema::create('family_revisions', function (Blueprint $table) {\n createDefaultRevisionsTableFields($table, 'family');\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function testPageAdministrationGeneralImages_CheckLayoutIcons() {\n\n\t\t$this->zbxTestLogin('zabbix.php?action=image.list');\n\t\t$this->zbxTestAssertElementPresentXpath('//button[text()=\"Create icon\"]');\n\t\t$this->zbxTestCheckTitle('Configuration of images');\n\t\t$this->zbxTestCheckHeader('Images');\n\t\t$this->zbxTestTextPresent('Type');\n\t\t$this->zbxTestDropdownHasOptions('imagetype', ['Icon', 'Background']);\n\n\t\t$db_images = DBfetchArray(DBselect('SELECT name FROM images WHERE imagetype=1 LIMIT 5'));\n\t\tif (!$db_images) {\n\t\t\t$this->zbxTestTextPresent('No data found.');\n\t\t}\n\t\telse {\n\t\t\tforeach ($db_images as $db_image) {\n\t\t\t\t$this->zbxTestAssertElementPresentXpath(\"//div[@id='image']//a[text()='\".$db_image['name'].\"']\");\n\t\t\t}\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function testCpRtOverLoad(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:161->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 488:17:19:10.00\nSNMPv2-MIB::snmpTrapOID.0 CPS-MIB::returnFromOverLoad\nCPS-MIB::mtrapinfoString \"The UPS has returned from an overload condition.\"\nSNMP-COMMUNITY-MIB::snmpTrapAddress.0 $device->ip\nSNMP-COMMUNITY-MIB::snmpTrapCommunity.0 \"comstring\"\nSNMPv2-MIB::snmpTrapEnterprise.0 CPS-MIB::cps\nTRAP,\n 'The UPS has returned from an overload condition.',\n 'Could not handle CpRtOverLoad trap',\n [Severity::Ok],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public static function compareDataProvider(): Iterator\n {\n yield [\n 'orderedMigrationClassesFromLock' => ['Version1', 'Version2'],\n 'versionA' => new Version('Version1'),\n 'versionB' => new Version('Version2'),\n 'expectedResult' => self::EXPECTED_RESULT_LESS_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Version2', 'Version1'],\n 'versionA' => new Version('Version1'),\n 'versionB' => new Version('Version2'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => [],\n 'versionA' => new Version('Version1'),\n 'versionB' => new Version('Version2'),\n 'expectedResult' => self::EXPECTED_RESULT_LESS_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => [],\n 'versionA' => new Version('Version2'),\n 'versionB' => new Version('Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => [],\n 'versionA' => new Version('Namespace2\\Version1'),\n 'versionB' => new Version('Namespace1\\Version2'),\n 'expectedResult' => self::EXPECTED_RESULT_LESS_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => [],\n 'versionA' => new Version('Namespace2\\Version2'),\n 'versionB' => new Version('Namespace1\\Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Namespace2\\Version2', 'Namespace1\\Version1'],\n 'versionA' => new Version('Namespace2\\Version2'),\n 'versionB' => new Version('Namespace1\\Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_LESS_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Namespace1\\Version1', 'Namespace2\\Version2'],\n 'versionA' => new Version('Namespace2\\Version2'),\n 'versionB' => new Version('Namespace1\\Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Namespace2\\Version2', 'Namespace1\\Version1'],\n 'versionA' => new Version('Namespace1\\Version1'),\n 'versionB' => new Version('Namespace2\\Version2'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Namespace1\\Version1'],\n 'versionA' => new Version('Namespace2\\Version2'),\n 'versionB' => new Version('Namespace1\\Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_GREATER_THAN_ZERO,\n ];\n\n yield [\n 'orderedMigrationClassesFromLock' => ['Namespace2\\Version2'],\n 'versionA' => new Version('Namespace2\\Version2'),\n 'versionB' => new Version('Namespace1\\Version1'),\n 'expectedResult' => self::EXPECTED_RESULT_LESS_THAN_ZERO,\n ];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getValue(): array\n {\n $names = $this->table->getColumnValues(['Name']);\n\n return [$names[0]['Name']];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function getBbTagType()\n\t{\n\t\treturn BbParagraph::class;\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function verifyValueInItemView(array $values): void\n {\n $explodedValue = explode('/', $values['value']);\n $value = $explodedValue[count($explodedValue) - 1];\n\n $viewPatternRegex = '/Single relation[\\w\\/,: ]* %s [\\w \\/,:]*/';\n\n Assert::assertMatchesRegularExpression(\n sprintf($viewPatternRegex, $value),\n $this->getHTMLPage()->find($this->parentLocator)->getText(),\n 'Field has wrong value'\n );\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function down(): void\n {\n Schema::dropIfExists('permission_groups');\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getStockQuantity(array $data): ?int\n {\n return $data['stock_quantity'];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($offset, $limit) use ($argument, $category, $productFilterData, $search) {\n return $this->productFacade->getFilteredProductsByCategory(\n $category,\n $limit,\n $offset,\n $this->productOrderingModeProvider->getOrderingModeFromArgument($argument),\n $productFilterData,\n $search,\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getFieldTypeIdentifier(): string\n {\n return 'ezobjectrelation';\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (Blueprint $table) {\n $table->foreign('component_id', 'component_statuslog_ibfk_1')->references('id')->on('component')->onUpdate('CASCADE')->onDelete('CASCADE');\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function configure(): void\n {\n $params = func_get_arg(0);\n $this->settingsStoreScope = $params['settingsStoreScope'] ?? 'pimcore_config';\n\n if (!isset(self::$cache[$this->settingsStoreScope])) {\n // initialize runtime cache\n self::$cache[$this->settingsStoreScope] = [];\n }\n\n $this->locationAwareConfigRepository = new Config\\LocationAwareConfigRepository(\n $params['containerConfig'] ?? [],\n $this->settingsStoreScope,\n $params['storageConfig'] ?? null\n );\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getExistingSiteProvider(): array\n {\n return [\n 'existing_sa' => [self::EXISTING_SA_NAME, [self::SA_GROUP]],\n 'sa_without_group' => [self::WITHOUT_GROUP_SA_NAME, []],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testDisplayMessageError(): void\n {\n $kernel = self::bootKernel();\n $application = new Application($kernel);\n\n $command = $application->find('app:add-auto-affectation-rule');\n\n $commandTester = new CommandTester($command);\n\n $territory = 440;\n $partnerType = 'EPCI';\n $status = 'ACTIVE';\n $profileDeclarant = 'occupant';\n $inseeToInclude = 'partner_list';\n $inseeToExclude = '44850,44600';\n $partnerToExclude = '';\n $parc = 'public';\n $allocataire = 'caf';\n $commandTester->execute([\n 'territory' => $territory,\n 'partnerType' => $partnerType,\n 'status' => $status,\n 'profileDeclarant' => $profileDeclarant,\n 'inseeToInclude' => $inseeToInclude,\n 'inseeToExclude' => $inseeToExclude,\n 'partnerToExclude' => $partnerToExclude,\n 'parc' => $parc,\n 'allocataire' => $allocataire,\n ]);\n\n $output = $commandTester->getDisplay();\n $this->assertStringContainsString('Territory does not exists', $output);\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function __construct(\n public string $emailAddress,\n public string|Optional $action,\n public string|Optional $status,\n public string|Optional $diagnosticCode,\n ) {}", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "static function ($request, $next) {\n app('view')->share('title', (string)trans('firefly.administration'));\n app('view')->share('mainTitleIcon', 'fa-hand-spock-o');\n\n return $next($request);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "#[DataProvider('compareDataProvider')]\n public function testCompare(\n array $orderedMigrationClassesFromLock,\n Version $versionA,\n Version $versionB,\n string $expectedResult,\n ): void {\n $migrationsLockMock = $this->createMock(MigrationsLock::class);\n $migrationsLockMock->method('getOrderedInstalledMigrationClasses')->willReturn($orderedMigrationClassesFromLock);\n $migrationsLockComparator = new MigrationsLockComparator($migrationsLockMock);\n $actualResult = $migrationsLockComparator->compare($versionA, $versionB);\n\n if ($expectedResult === self::EXPECTED_RESULT_LESS_THAN_ZERO) {\n $this->assertLessThan(0, $actualResult);\n }\n\n if ($expectedResult === self::EXPECTED_RESULT_GREATER_THAN_ZERO) {\n $this->assertGreaterThan(0, $actualResult);\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function preRemove(LifecycleEventArgs $args): void\n {\n $entity = $args->getEntity();\n\n if ($this->customerUploadedFileConfig->hasUploadedFileEntityConfig($entity)) {\n $this->customerUploadedFileFacade->deleteAllUploadedFilesByEntity($entity);\n } elseif ($entity instanceof CustomerUploadedFile) {\n $this->customerUploadedFileFacade->deleteFileFromFilesystem($entity);\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testCpLowBattery(): void\n {\n $this->assertTrapLogsMessage(<<<'TRAP'\n{{ hostname }}\nUDP: [{{ ip }}]:161->[192.168.5.5]:162\nDISMAN-EVENT-MIB::sysUpTimeInstance 488:17:19:10.00\nSNMPv2-MIB::snmpTrapOID.0 CPS-MIB::lowBattery\nCPS-MIB::mtrapinfoString \"The UPS battery capacity is low than threshold, soon to be exhausted.\"\nSNMP-COMMUNITY-MIB::snmpTrapAddress.0 $device->ip\nSNMP-COMMUNITY-MIB::snmpTrapCommunity.0 \"comstring\"\nSNMPv2-MIB::snmpTrapEnterprise.0 CPS-MIB::cps\nTRAP,\n 'The UPS battery capacity is low than threshold, soon to be exhausted.',\n 'Could not handle CpLowBattery trap',\n [Severity::Warning],\n );\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "private function createBlockArticleForProductsTest(): void\n {\n $blogArticleData = $this->blogArticleDataFactory->create();\n $blogArticleData->publishDate = new DateTime('-2 days');\n $blogArticleData->uuid = Uuid::uuid5(self::UUID_NAMESPACE, 'Blog article for products testing')->toString();\n\n foreach ($this->domainsForDataFixtureProvider->getAllowedDemoDataLocales() as $locale) {\n $blogArticleData->names[$locale] = t('Blog article for products testing', [], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $blogArticleData->descriptions[$locale] = str_replace([' ', PHP_EOL], '', trim(<<

Produkty 1

\n
\n
\n
\n
\n
\n
\n
\n

Produkty 2

\n
\n
\n
\n
\n
\nEOT));\n\n $blogArticleData->perexes[$locale] = t('Blog article for products testing', [], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n }\n\n foreach ($this->domainsForDataFixtureProvider->getAllowedDemoDataDomains() as $domainConfig) {\n $locale = $domainConfig->getLocale();\n $domainId = $domainConfig->getId();\n\n $blogArticleData->blogCategoriesByDomainId[$domainId] = [$this->getReference(self::FIRST_DEMO_BLOG_CATEGORY, BlogCategory::class), $this->getReference(self::FIRST_DEMO_BLOG_SUBCATEGORY, BlogCategory::class)];\n $blogArticleData->seoTitles[$domainId] = t('Blog article for products testing', [], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n $blogArticleData->seoH1s[$domainId] = t('Blog article for products testing', [], Translator::DATA_FIXTURES_TRANSLATION_DOMAIN, $locale);\n }\n\n $blogArticle = $this->blogArticleFacade->create($blogArticleData);\n $this->addReference(self::DEMO_BLOG_ARTICLE_PREFIX . $blogArticle->getId(), $blogArticle);\n\n $this->articleCounter++;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testWithExpressionParam(): void\n {\n $view = $this->getContentViewMock();\n $event = new PreContentViewEvent($view);\n\n $randomNumber = rand(100, 200);\n\n $view->method('getParameters')\n ->willReturn([\n 'random_number' => $randomNumber,\n ]);\n\n $view->method('getConfigHash')\n ->willReturn([\n ContentViewTwigVariablesSubscriber::PARAMETERS_KEY => [\n 'plus_42' => '@=parameters[\"random_number\"] + 42',\n ],\n ]);\n\n $view\n ->expects(self::once())\n ->method('setParameters')\n ->with([\n 'random_number' => $randomNumber,\n 'plus_42' => $randomNumber + 42,\n ]);\n\n $subscriber = $this->getContentViewMockSubscriber();\n $subscriber->onPreContentView($event);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct(\n FieldBlockRendererInterface $fieldBlockRenderer,\n ParameterProviderRegistryInterface $parameterProviderRegistry,\n TranslationHelper $translationHelper\n ) {\n $this->fieldBlockRenderer = $fieldBlockRenderer;\n $this->parameterProviderRegistry = $parameterProviderRegistry;\n $this->translationHelper = $translationHelper;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function before(Authenticatable $authenticatable): ?Response\n {\n if (! is_null($response = $this->hasLicenses($authenticatable, LicenseType::ConversationalAi))) {\n return $response;\n }\n\n return null;\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "function (Blueprint $table) {\n $table->uuid('id')->primary();\n\n $table->string('name');\n $table->text('description')->nullable();\n $table->json('filters')->nullable();\n $table->json('columns');\n $table->string('model');\n\n $table->foreignUuid('user_id')->constrained('users');\n\n $table->timestamps();\n $table->softDeletes();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function setUp(): void\n {\n $this->repositoryConfigurationProvider = $this->getRepositoryConfigurationProvider();\n $this->entityManager = $this->getEntityManager();\n $this->serviceLocator = $this->getServiceLocator();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function transformMappingInternal()\n {\n return [];\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n $this->sql(\n 'CREATE TABLE cron_modules (module_id VARCHAR(255) NOT NULL, scheduled BOOLEAN NOT NULL, PRIMARY KEY(module_id));',\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function fill($labels, $context = null) {\n\t\tif (!in_array($this->mode, [self::MODE_SELECT, self::MODE_SELECT_MULTIPLE, self::MODE_TYPE])) {\n\t\t\tthrow new Exception('Unknown fill mode is set for multiselect element.');\n\t\t}\n\n\t\t$this->clear();\n\n\t\t// TODO: for loop and try/catch block should be removed after DEV-1535 is fixed.\n\t\tfor ($i = 0; $i < 2; $i++) {\n\t\t\ttry {\n\t\t\t\tif ($context === null && is_array($labels)) {\n\t\t\t\t\tif (array_key_exists('values', $labels)) {\n\t\t\t\t\t\tif (array_key_exists('context', $labels)) {\n\t\t\t\t\t\t\t$context = $labels['context'];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t$labels = $labels['values'];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tforeach ($labels as $label) {\n\t\t\t\t\t\t\tif (is_array($label) && array_key_exists('values', $label)) {\n\t\t\t\t\t\t\t\t$context = (array_key_exists('context', $label)) ? $label['context'] : null;\n\t\t\t\t\t\t\t\t$label = $label['values'];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ($this->mode === self::MODE_SELECT) {\n\t\t\t\t\t\t\t\tthrow new Exception('Cannot select multiple items in single select mode.');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telseif ($this->mode === self::MODE_SELECT_MULTIPLE) {\n\t\t\t\t\t\t\t\t$this->selectMultiple($label, $context);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t$this->type($label);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn $this;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ($this->mode === self::MODE_SELECT) {\n\t\t\t\t\treturn $this->select($labels, $context);\n\t\t\t\t}\n\t\t\t\telseif ($this->mode === self::MODE_SELECT_MULTIPLE) {\n\t\t\t\t\treturn $this->selectMultiple($labels, $context);\n\t\t\t\t}\n\n\t\t\t\treturn $this->type($labels);\n\t\t\t}\n\t\t\tcatch (StaleElementReferenceException $exception) {\n\t\t\t\tif ($i === 1) {\n\t\t\t\t\tthrow $exception;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function run(): void\n {\n EngagementResponse::factory()\n ->count(50)\n ->create();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function find(int $groupId): ?TransactionGroup;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function getOrderingPriority(array $data): int\n {\n return $data['ordering_priority'];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function addParameters(array $parameters);", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getKeyValuePairs()\n {\n $pairs = [];\n\n foreach (array_chunk($this->nodes, 2) as $pair) {\n $pairs[] = [\n 'key' => $pair[0],\n 'value' => $pair[1],\n ];\n }\n\n return $pairs;\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function __construct(iterable $handlers = [])\n {\n $this->handlers = $handlers;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(protected readonly EntityManagerInterface $em)\n {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function clear(string $environment, array $options = []): Process\n {\n $resolver = new OptionsResolver();\n $resolver->setDefaults([\n 'no-warmup' => false,\n 'no-optional-warmers' => false,\n 'env' => $environment,\n 'ansi' => false,\n 'no-ansi' => false,\n ]);\n\n foreach (['no-warmup', 'no-optional-warmers', 'ansi', 'no-ansi'] as $option) {\n $resolver->setAllowedTypes($option, 'bool');\n }\n\n return $this->runCommand('cache:clear', $resolver->resolve($options));\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function setUp(): void\n {\n parent::setUp();\n TestHelper::cleanUp();\n Pimcore::setAdminMode();\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function productsByProductListQuery(ProductList $productList): Promise\n {\n $productIds = $this->productListFacade->getProductIdsByProductList($productList);\n\n return $this->productsVisibleAndSortedByIdsBatchLoader->load($productIds);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($request, $next) {\n /** @var User $user */\n $user = auth()->user();\n $this->repository = app(CategoryRepositoryInterface::class);\n $this->repository->setUser($user);\n\n return $next($request);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "#[Route(path: '/slider/list/')]\n public function listAction()\n {\n $queryBuilder = $this->entityManager->createQueryBuilder()\n ->select('s')\n ->from(SliderItem::class, 's')\n ->where('s.domainId = :selectedDomainId')\n ->setParameter('selectedDomainId', $this->adminDomainTabsFacade->getSelectedDomainId())\n ->orderBy('s.position')\n ->addOrderBy('s.id');\n $dataSource = new QueryBuilderDataSource($queryBuilder, 's.id');\n\n $grid = $this->gridFactory->create('sliderItemList', $dataSource);\n $grid->enableDragAndDrop(SliderItem::class);\n\n $grid->addColumn('name', 's.name', t('Name'));\n $grid->addColumn('link', 's.link', t('Link'));\n $grid->addEditActionColumn('admin_slider_edit', ['id' => 's.id']);\n $grid->addDeleteActionColumn('admin_slider_delete', ['id' => 's.id'])\n ->setConfirmMessage(t('Do you really want to remove this page?'));\n\n $grid->setTheme('@ShopsysFramework/Admin/Content/Slider/listGrid.html.twig');\n\n return $this->render('@ShopsysFramework/Admin/Content/Slider/list.html.twig', [\n 'gridView' => $grid->createView(),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(PermissionResolver $permissionResolver)\n {\n $this->permissionResolver = $permissionResolver;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getVariants(array $data): array\n {\n return $this->productElasticsearchProvider->getSellableProductArrayByIds($data['variants']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function deleteObjectState(ObjectState $objectState): void\n {\n $eventData = [$objectState];\n\n $beforeEvent = new BeforeDeleteObjectStateEvent(...$eventData);\n\n $this->eventDispatcher->dispatch($beforeEvent);\n if ($beforeEvent->isPropagationStopped()) {\n return;\n }\n\n $this->innerService->deleteObjectState($objectState);\n\n $this->eventDispatcher->dispatch(\n new DeleteObjectStateEvent(...$eventData)\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function registerMediaConversions(Media $media = null): void\n {\n $this->addMediaConversion('avatar-height-250px')\n ->performOnCollections('avatar')\n ->height(250);\n\n $this->addMediaConversion('thumbnail')\n ->performOnCollections('avatar')\n ->width(32)\n ->height(32);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getAllowedDemoDataDomains(): array\n {\n return array_values($this->allowedDemoDataDomains);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (array $data) use ($component) {\n $template = EmailTemplate::find($data['emailTemplate']);\n\n if (! $template) {\n return;\n }\n\n $component->state(\n $component->generateImageUrls($template->content),\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "abstract protected function doEnrichFieldDefinition(Data $fieldDefinition, array $context = []): Data;", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function updateSetting(string $group, string $identifier, string $serializedValue): void\n {\n $query = $this->connection->createQueryBuilder();\n $query\n ->update(self::SETTING_TABLE)\n ->set('value', $query->createPositionalParameter($serializedValue))\n ->where(\n $query->expr()->eq(\n $this->connection->quoteIdentifier('group'),\n $query->createPositionalParameter($group, ParameterType::STRING)\n ),\n $query->expr()->eq(\n 'identifier',\n $query->createPositionalParameter($identifier, ParameterType::STRING)\n )\n );\n\n $query->execute();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getInCodTipoEnsino(): ?string\n\t{\n\t\treturn $this->inCodTipoEnsino;\n\t}", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "public static function allAuditActions() {\n\t\treturn CDBHelper::getDataProvider('SELECT * FROM alerts ORDER BY alertid LIMIT 7');\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "static function ($languageCode) use ($languagesMap) {\n // Get only Languages defined and enabled in Admin\n return isset($languagesMap[$languageCode]) && $languagesMap[$languageCode]['enabled'];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function update() {\n\t\treturn CDBHelper::getDataProvider(\n\t\t\t'SELECT DISTINCT t.triggerid,id.parent_itemid'.\n\t\t\t' FROM triggers t,functions f,item_discovery id'.\n\t\t\t' WHERE t.triggerid=f.triggerid'.\n\t\t\t\t' AND f.itemid=id.itemid'.\n\t\t\t\t' AND EXISTS ('.\n\t\t\t\t\t'SELECT NULL'.\n\t\t\t\t\t' FROM functions f,items i'.\n\t\t\t\t\t' WHERE t.triggerid=f.triggerid'.\n\t\t\t\t\t\t' AND f.itemid=i.itemid'.\n\t\t\t\t\t\t' AND i.hostid=15000'.\t//\t$this->templateid.\n\t\t\t\t\t\t' AND i.flags=2'.\n\t\t\t\t\t')'.\n\t\t\t\t' AND t.flags=2'\n\t\t);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function hasParameter(string $paramName, ?string $namespace = null, ?string $scope = null): bool;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n createDefaultRelationshipTableFields($table, 'generic_page', 'article');\n $table->integer('position')->unsigned()->index();\n $table->timestamps();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "abstract protected function getUserServiceMethod(): string;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function down(): void\n {\n if (\\LibreNMS\\DB\\Eloquent::getDriver() !== 'sqlite') {\n Schema::table('component_statuslog', function (Blueprint $table) {\n $table->dropForeign('component_statuslog_ibfk_1');\n });\n }\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function __construct()\n {\n parent::__construct();\n\n $this\n ->addRule('key', [\n 'type' => self::TYPE_STRING,\n 'description' => 'Attribute Key.',\n 'default' => '',\n 'example' => 'githubUrl',\n ])\n ->addRule('type', [\n 'type' => self::TYPE_STRING,\n 'description' => 'Attribute type.',\n 'default' => '',\n 'example' => 'string',\n ])\n ->addRule('format', [\n 'type' => self::TYPE_STRING,\n 'description' => 'String format.',\n 'default' => APP_DATABASE_ATTRIBUTE_URL,\n 'example' => APP_DATABASE_ATTRIBUTE_URL,\n ])\n ->addRule('default', [\n 'type' => self::TYPE_STRING,\n 'description' => 'Default value for attribute when not provided. Cannot be set when attribute is required.',\n 'default' => null,\n 'required' => false,\n 'example' => 'http://example.com',\n ])\n ;\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(string $enumClass, string $case)\n {\n parent::__construct(sprintf('Enum class \"%s\" does not contain \"%s\" case', $enumClass, $case));\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function allProxies() {\n\t\treturn CDBHelper::getDataProvider(\"select * from hosts where status in (\".HOST_STATUS_PROXY_ACTIVE.','.HOST_STATUS_PROXY_PASSIVE.\") order by hostid\");\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function index()\n {\n return $this->repository->listAll();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function handleContentTranslateForm(FilterViewBuilderParametersEvent $event): void\n {\n $controllerAction = $event->getParameters()->get('_controller');\n\n if (\n 'Ibexa\\Bundle\\AdminUi\\Controller\\ContentEditController::translateAction' !== $controllerAction\n ) {\n return;\n }\n\n $request = $event->getRequest();\n $languageCode = $request->attributes->get('toLanguageCode');\n $baseLanguageCode = $request->attributes->get('fromLanguageCode');\n $content = $this->contentService->loadContent(\n (int)$request->attributes->get('contentId'),\n null !== $baseLanguageCode ? [$baseLanguageCode] : null\n );\n $contentType = $this->contentTypeService->loadContentType(\n $content->getContentType()->id,\n $this->languagePreferenceProvider->getPreferredLanguages()\n );\n $toLanguage = $this->languageService->loadLanguage($languageCode);\n $fromLanguage = $baseLanguageCode ? $this->languageService->loadLanguage($baseLanguageCode) : null;\n\n $contentTranslateData = $this->resolveContentTranslationData(\n $content,\n $toLanguage,\n $fromLanguage,\n $contentType\n );\n $form = $this->resolveContentTranslateForm(\n $contentTranslateData,\n $toLanguage,\n $content\n );\n\n $event->getParameters()->add(['form' => $form->handleRequest($request)]);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function down(): void\n {\n Schema::table('devices', function (Blueprint $table) {\n $table->index('hostname');\n $table->dropIndex('devices_hostname_sysname_display_index');\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function productsByCatnumsQuery(array $catnums): Promise\n {\n $productIds = $this->productRepository->getProductIdsByCatnums($catnums);\n\n return $this->productsVisibleAndSortedByIdsBatchLoader->load($productIds);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function getTestSellingDeniedDataProvider(): array\n {\n return [\n [\n 'hidden' => true,\n 'sellingDenied' => true,\n 'calculatedSellingDenied' => true,\n ],\n [\n 'hidden' => false,\n 'sellingDenied' => false,\n 'calculatedSellingDenied' => false,\n ],\n [\n 'hidden' => true,\n 'sellingDenied' => false,\n 'calculatedSellingDenied' => false,\n ],\n [\n 'hidden' => false,\n 'sellingDenied' => true,\n 'calculatedSellingDenied' => true,\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function renderFieldDefinitionSettings(FieldDefinition $fieldDefinition, array $params = [])\n {\n return $this->fieldBlockRenderer->renderFieldDefinitionView($fieldDefinition, $params);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "#[Route(path: '/mail/edit/{id}', requirements: ['id' => '\\d+'])]\n public function editAction(Request $request, int $id): Response\n {\n $mailTemplate = $this->mailTemplateFacade->getById($id);\n $mailTemplateData = $this->mailTemplateDataFactory->createFromMailTemplate($mailTemplate);\n\n $mailTemplateVariables = $this->mailTemplateConfiguration->getMailTemplateVariablesBySlug(\n $mailTemplate->getName(),\n );\n\n $form = $this->createForm(\n MailTemplateFormType::class,\n $mailTemplateData,\n [\n 'allow_disable_sending' => in_array(\n $mailTemplateVariables->getType(),\n MailTemplateConfiguration::TYPES_WITH_SEND_MAIL_SETTING,\n true,\n ),\n 'entity' => $mailTemplate,\n 'required_subject_variables' => $mailTemplateVariables->getRequiredSubjectVariables(),\n 'required_body_variables' => $mailTemplateVariables->getRequiredBodyVariables(),\n ],\n );\n $form->handleRequest($request);\n\n if ($form->isSubmitted() && $form->isValid()) {\n $this->mailTemplateFacade->edit($id, $mailTemplateData);\n\n $this->addSuccessFlashTwig(\n t('Email template {{ name }} modified'),\n [\n 'name' => $mailTemplateVariables->getReadableName(),\n 'url' => $this->generateUrl('admin_mail_edit', ['id' => $mailTemplate->getId()]),\n ],\n );\n\n return $this->redirectToRoute('admin_mail_template');\n }\n\n if ($form->isSubmitted() && !$form->isValid()) {\n $this->addErrorFlash(t('Please check the correctness of all data filled.'));\n }\n\n $this->breadcrumbOverrider->overrideLastItem(\n t('Editing email template - %name%', ['%name%' => $mailTemplateVariables->getReadableName()]),\n );\n\n return $this->render('@ShopsysFramework/Admin/Content/Mail/edit.html.twig', [\n 'form' => $form->createView(),\n 'mailTemplateName' => $mailTemplateVariables->getReadableName(),\n 'bodyVariables' => $mailTemplateVariables->getBodyVariables(),\n 'subjectVariables' => $mailTemplateVariables->getSubjectVariables(),\n 'requiredBodyVariables' => $mailTemplateVariables->getRequiredBodyVariables(),\n 'requiredSubjectVariables' => $mailTemplateVariables->getRequiredSubjectVariables(),\n 'labeledVariables' => $mailTemplateVariables->getLabeledVariables(),\n 'entity' => $mailTemplate,\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function educatable(): MorphTo\n {\n return $this->morphTo();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "#[Route(path: '/superadmin/urls/')]\n public function urlsAction()\n {\n return $this->render('@ShopsysFramework/Admin/Content/Superadmin/urlsListGrid.html.twig');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function removeRow($index) {\n\t\t$row = $this->getRow($index);\n\t\t$row->query('button:Remove')->one()->click();\n\t\t$row->waitUntilNotPresent();\n\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function createUrlAlias(\n Location $location,\n string $path,\n string $languageCode,\n bool $forwarding = false,\n bool $alwaysAvailable = false\n ): URLAlias {\n return $this->service->createUrlAlias($location, $path, $languageCode, $forwarding, $alwaysAvailable);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function providerForCachedLoadMethodsMiss(): array\n {\n $object = new Setting(['group' => 'group_a1', 'identifier' => 'identifier_b2']);\n\n // string $method, array $arguments, string $key, array? $tagGeneratingArguments, array? $tagGeneratingResults, array? $keyGeneratingArguments, array? $keyGeneratingResults, mixed? $data, bool $multi\n return [\n [\n 'load',\n ['group_a1', 'identifier_b2'],\n 'ibx-set-group_a1-identifier_b2',\n [\n ['setting', ['group_a1', 'identifier_b2'], true],\n ['setting', ['group_a1', 'identifier_b2'], true],\n ],\n ['ibx-set-group_a1-identifier_b2', 'ibx-set-group_a1-identifier_b2'],\n null,\n null,\n $object,\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct($data, $templateid) {\n\t\tparent::__construct($data, $templateid, WIDGET_ACTION_LOG);\n\n\t\t$field_sort = (new CWidgetFieldSelect('sort_triggers', _('Sort entries by'), [\n\t\t\tSCREEN_SORT_TRIGGERS_TIME_DESC => _('Time').' ('._('descending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_TIME_ASC => _('Time').' ('._('ascending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_TYPE_DESC => _('Type').' ('._('descending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_TYPE_ASC => _('Type').' ('._('ascending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_STATUS_DESC => _('Status').' ('._('descending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_STATUS_ASC => _('Status').' ('._('ascending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_RECIPIENT_DESC => _('Recipient').' ('._('descending').')',\n\t\t\tSCREEN_SORT_TRIGGERS_RECIPIENT_ASC => _('Recipient').' ('._('ascending').')'\n\t\t]))\n\t\t\t->setDefault(SCREEN_SORT_TRIGGERS_TIME_DESC);\n\n\t\tif (array_key_exists('sort_triggers', $this->data)) {\n\t\t\t$field_sort->setValue($this->data['sort_triggers']);\n\t\t}\n\n\t\t$this->fields[$field_sort->getName()] = $field_sort;\n\n\t\t$field_lines = (new CWidgetFieldIntegerBox('show_lines', _('Show lines'), ZBX_MIN_WIDGET_LINES,\n\t\t\tZBX_MAX_WIDGET_LINES\n\t\t))\n\t\t\t->setFlags(CWidgetField::FLAG_LABEL_ASTERISK)\n\t\t\t->setDefault(25);\n\n\t\tif (array_key_exists('show_lines', $this->data)) {\n\t\t\t$field_lines->setValue($this->data['show_lines']);\n\t\t}\n\n\t\t$this->fields[$field_lines->getName()] = $field_lines;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n $this->sql(\n 'CREATE TABLE countries (\n id SERIAL NOT NULL,\n name VARCHAR(255) NOT NULL,\n domain_id INT NOT NULL,\n PRIMARY KEY(id))',\n );\n\n $this->sql('ALTER TABLE billing_addresses ADD COLUMN country_id INT DEFAULT NULL');\n $this->sql(\n 'ALTER TABLE billing_addresses ADD CONSTRAINT FK_DBD91748F92F3E70 FOREIGN KEY (country_id)\n REFERENCES countries (id) NOT DEFERRABLE INITIALLY IMMEDIATE',\n );\n $this->sql('CREATE INDEX IDX_DBD91748F92F3E70 ON billing_addresses (country_id)');\n $this->sql('ALTER TABLE delivery_addresses ADD country_id INT DEFAULT NULL');\n $this->sql(\n 'ALTER TABLE delivery_addresses ADD CONSTRAINT FK_2BAF3984E76AA954 FOREIGN KEY (country_id)\n REFERENCES countries (id) NOT DEFERRABLE INITIALLY IMMEDIATE',\n );\n $this->sql('CREATE INDEX IDX_2BAF3984F92F3E70 ON delivery_addresses (country_id)');\n\n $this->sql('ALTER TABLE orders ADD country_id INT');\n $this->sql(\n 'ALTER TABLE orders ADD CONSTRAINT FK_E52FFDEEF92F3E70 FOREIGN KEY (country_id)\n REFERENCES countries (id) NOT DEFERRABLE INITIALLY IMMEDIATE',\n );\n $this->sql('CREATE INDEX IDX_E52FFDEEF92F3E70 ON orders (country_id)');\n\n foreach ($this->getAllDomainIds() as $domainId) {\n $countOfOrdersOnDomain = $this->sql(\n 'SELECT COUNT(*) FROM orders WHERE domain_id = :domainId;',\n ['domainId' => $domainId],\n )->fetchOne();\n\n if ($countOfOrdersOnDomain === 0) {\n continue;\n }\n\n $this->sql(\n 'INSERT INTO countries (name, domain_id) VALUES (:countryName, :domainId)',\n [\n 'countryName' => '-',\n 'domainId' => $domainId,\n ],\n );\n $countryId = $this->connection->lastInsertId();\n $this->sql(\n 'UPDATE orders SET country_id = :countryId WHERE domain_id = :domainId',\n [\n 'countryId' => $countryId,\n 'domainId' => $domainId,\n ],\n );\n }\n $this->sql('ALTER TABLE orders ALTER country_id SET NOT NULL');\n\n $this->sql('ALTER TABLE orders ADD delivery_country_id INT DEFAULT NULL');\n $this->sql(\n 'ALTER TABLE orders ADD CONSTRAINT FK_E52FFDEEE76AA954 FOREIGN KEY (delivery_country_id)\n REFERENCES countries (id) NOT DEFERRABLE INITIALLY IMMEDIATE',\n );\n $this->sql('CREATE INDEX IDX_E52FFDEEE76AA954 ON orders (delivery_country_id)');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct()\n {\n parent::__construct();\n\n app('view')->share('showCategory', true);\n\n // translations:\n $this->middleware(\n function ($request, $next) {\n app('view')->share('mainTitleIcon', 'fa-credit-card');\n app('view')->share('title', (string)trans('firefly.accounts'));\n\n $this->repository = app(AccountRepositoryInterface::class);\n\n return $next($request);\n }\n );\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function createFromJobRun(\n JobRun $jobRun,\n ?int $elementId = null,\n ?string $message = null\n ): void {\n $jobRunErrorLog = new JobRunErrorLog(\n $jobRun->getId(),\n $jobRun->getCurrentStep(),\n $elementId,\n $message\n );\n\n $this->pimcoreEntityManager->persist($jobRunErrorLog);\n $this->pimcoreEntityManager->flush();\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function testGetDefaultVat()\n {\n $vatData = new VatData();\n $vatData->percent = '0';\n $vatData->name = 'vat name';\n\n $expected = new Vat($vatData, Domain::FIRST_DOMAIN_ID);\n $emMock = $this->createMock(EntityManager::class);\n\n $settingMock = $this->getMockBuilder(Setting::class)\n ->onlyMethods(['getForDomain', '__construct'])\n ->disableOriginalConstructor()\n ->getMock();\n $settingMock\n ->expects($this->once())\n ->method('getForDomain')\n ->with($this->equalTo(Vat::SETTING_DEFAULT_VAT))\n ->willReturn(1);\n\n $vatRepositoryMock = $this->getMockBuilder(VatRepository::class)\n ->onlyMethods(['findById', '__construct'])\n ->disableOriginalConstructor()\n ->getMock();\n $vatRepositoryMock\n ->expects($this->once())\n ->method('findById')\n ->with($this->equalTo(1))\n ->willReturn($expected);\n\n $domainMock = $this->getMockBuilder(Domain::class)\n ->onlyMethods(['__construct'])\n ->disableOriginalConstructor()\n ->getMock();\n\n $productRecalculationDispatcherMock = $this->createMock(ProductRecalculationDispatcher::class);\n\n $vatFacade = new VatFacade(\n $emMock,\n $vatRepositoryMock,\n $settingMock,\n new VatFactory(new EntityNameResolver([])),\n $domainMock,\n $productRecalculationDispatcherMock,\n );\n\n $defaultVat = $vatFacade->getDefaultVatForDomain(Domain::FIRST_DOMAIN_ID);\n\n $this->assertSame($expected, $defaultVat);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getHreflangLinks(array $data): array\n {\n return $data['hreflang_links'];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function setRole(Role $role): self\n {\n $this->role = $role;\n\n return $this;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function leaveNode(Node $node, Environment $env)\n {\n if ($node instanceof ModuleNode) {\n $this->inAModule = false;\n if ($this->hasMacroCalls) {\n $node->getNode('constructor_end')->setNode('_auto_macro_import', new ImportNode(new NameExpression('_self', 0), new AssignNameExpression('_self', 0), 0, 'import', true));\n }\n } elseif ($this->inAModule) {\n if (\n $node instanceof GetAttrExpression &&\n $node->getNode('node') instanceof NameExpression &&\n '_self' === $node->getNode('node')->getAttribute('name') &&\n $node->getNode('attribute') instanceof ConstantExpression\n ) {\n $this->hasMacroCalls = true;\n\n $name = $node->getNode('attribute')->getAttribute('value');\n $node = new MethodCallExpression($node->getNode('node'), 'macro_'.$name, $node->getNode('arguments'), $node->getTemplateLine());\n $node->setAttribute('safe', true);\n }\n }\n\n return $node;\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('form_field_submission', function (Blueprint $table) {\n $table->uuid('id')->primary();\n\n $table->longText('response');\n $table->foreignUuid('field_id')->constrained('form_fields')->cascadeOnDelete();\n $table->foreignUuid('submission_id')->constrained('form_submissions')->cascadeOnDelete();\n\n $table->timestamps();\n });\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getRowValue($index) {\n\t\t$value = [];\n\n\t\tforeach ($this->getRowControls($this->getRow($index)) as $name => $control) {\n\t\t\t$value[$name] = $control->getValue();\n\t\t}\n\n\t\treturn $value;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function down(): void\n {\n Schema::drop('syslog');\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function create(): HeurekaProductDomainData\n {\n return $this->createInstance();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function fillFromParameter(ParameterData $parameterData, Parameter $parameter)\n {\n /** @var \\Shopsys\\FrameworkBundle\\Model\\Product\\Parameter\\ParameterTranslation[] $translations */\n $translations = $parameter->getTranslations();\n $names = [];\n\n foreach ($translations as $translate) {\n $names[$translate->getLocale()] = $translate->getName();\n }\n\n $parameterData->name = $names;\n $parameterData->visible = $parameter->isVisible();\n $parameterData->uuid = $parameter->getUuid();\n $parameterData->parameterType = $parameter->getParameterType();\n $parameterData->unit = $parameter->getUnit();\n $parameterData->orderingPriority = $parameter->getOrderingPriority();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getCategories(array $data): array\n {\n return $this->categoryFacade->getByIds($data['categories']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "private function forceType($data)\n {\n /*\n * It is not trivial to detect if something is a float or an integer, and\n * therefore may cause breakages on inserts.\n * Just setting every number to a float gets around this, but may introduce\n * inefficiencies.\n */\n\n if (is_numeric($data)) {\n return floatval($data);\n }\n\n return $data === 'U' ? null : $data;\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "#[Override]\n public function shouldBeginTransaction(RequestEvent $event): bool\n {\n return $event->isMainRequest();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function findById(int $id): ?ProductVideoTranslations\n {\n return $this->getRepository()->find($id);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function jsonSerialize(): array\n\t{\n\t\treturn [\n\t\t\t'display' => $this->displayValue,\n\t\t\t'sort' => $this->sortValue,\n\t\t\t'export' => $this->exportValue,\n\t\t\t'filter' => $this->filterValue,\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function up(): void\n {\n Schema::table('custom_maps', function (Blueprint $table) {\n $table->smallInteger('node_align')->default(0)->after('height');\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function __construct(\n protected readonly CustomerUploadedFileConfig $customerUploadedFileConfig,\n protected readonly CustomerUploadedFileFacade $customerUploadedFileFacade,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function testRefreshUserNotSupported(): void\n {\n $user = $this->createMock(SymfonyUserInterface::class);\n\n $this->expectException(UnsupportedUserException::class);\n $this->userProvider->refreshUser($user);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('page_translations', function (Blueprint $table) {\n createDefaultTranslationsTableFields($table, 'page');\n $table->string('visit_intro')->nullable();\n $table->string('visit_hour_header')->nullable();\n $table->string('visit_hour_subheader')->nullable();\n $table->string('visit_city_pass_title')->nullable();\n $table->text('visit_city_pass_text')->nullable();\n $table->string('visit_city_pass_button_label')->nullable();\n $table->text('visit_admission_description')->nullable();\n $table->string('visit_buy_tickets_label')->nullable();\n $table->string('visit_become_member_label')->nullable();\n });\n\n Schema::table('pages', function (Blueprint $table) {\n $table->dropColumn(['visit_intro', 'visit_hour_header', 'visit_hour_subheader', 'visit_city_pass_title', 'visit_city_pass_text', 'visit_city_pass_button_label', 'visit_admission_description', 'visit_buy_tickets_label', 'visit_become_member_label']);\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function setPage(int $page): void;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public static function getPages(): array\n {\n return [\n 'index' => ListEngagementResponses::route('/'),\n 'view' => ViewEngagementResponse::route('/{record}'),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getTypeConstraints()\n {\n return new Content\\FieldTypeConstraints();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function publishTranslations(array $languageCodes): self\n {\n foreach ($languageCodes as $languageCode) {\n if (!is_string($languageCode) || empty($languageCode)) {\n throw new InvalidArgumentException('$languageCodes', 'All language codes should be non-empty strings');\n }\n }\n\n $this->targetVersionProperties['forPublishLanguageCodesList'] = $languageCodes;\n\n return $this;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getUpdatedRoleDraft(): RoleDraft\n {\n return $this->updatedRoleDraft;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function load(ObjectManager $manager): void\n {\n $this->createFlag(1, self::FLAG_PRODUCT_SALE);\n $this->createFlag(2, self::FLAG_PRODUCT_ACTION);\n $this->createFlag(3, self::FLAG_PRODUCT_NEW);\n $this->createFlag(4, self::FLAG_PRODUCT_MADEIN_CZ);\n $this->createFlag(5, self::FLAG_PRODUCT_MADEIN_SK);\n $this->createFlag(6, self::FLAG_PRODUCT_MADEIN_DE);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($model) {\n $model->delete();\n $this->dispatch('swalSuccess', ['message' => 'X\u00f3a th\u00e0nh c\u00f4ng']);\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('stp_id');\n $table->unsignedInteger('device_id')->index();\n $table->boolean('rootBridge');\n $table->string('bridgeAddress', 32);\n $table->string('protocolSpecification', 16);\n $table->mediumInteger('priority');\n $table->string('timeSinceTopologyChange', 32);\n $table->mediumInteger('topChanges');\n $table->string('designatedRoot', 32);\n $table->mediumInteger('rootCost');\n $table->integer('rootPort')->nullable();\n $table->mediumInteger('maxAge');\n $table->mediumInteger('helloTime');\n $table->mediumInteger('holdTime');\n $table->mediumInteger('forwardDelay');\n $table->smallInteger('bridgeMaxAge');\n $table->smallInteger('bridgeHelloTime');\n $table->smallInteger('bridgeForwardDelay');\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "#[DataProvider('booleanWithDefaultFalseProvider')]\n public function testSimple2fa(mixed $actual, bool $expected): void\n {\n $debug = new Debug(['simple2fa' => $actual]);\n $debugArray = $debug->asArray();\n self::assertSame($expected, $debug->simple2fa);\n self::assertSame($expected, $debugArray['simple2fa']);\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function setObjectState(ObjectState $objectState)\n {\n $this->objectState = $objectState;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function isAdvancedSearchFormSubmitted(Request $request)\n {\n $rulesData = $request->get(static::RULES_FORM_NAME);\n\n return $rulesData !== null;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function setUp(): void\n {\n parent::setUp();\n\n $this->insertDatabaseFixture(\n __DIR__ . '/../../_fixtures/roles.php'\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function widgets()\n {\n return [\n Stat::make(100,'demo')\n ];\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "protected function fillFromEntityAndType(ImageUploadData $imageUploadData, object $entity, ?string $type): void\n {\n $orderedImages = $this->imageFacade->getImagesByEntityIndexedById($entity, $type);\n $imageUploadData->orderedImages = $orderedImages;\n\n foreach ($orderedImages as $orderedImage) {\n $imageUploadData->namesIndexedByImageIdAndLocale[$orderedImage->getId()] = $orderedImage->getNames();\n }\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function setUp(): void {\n\t\t$user_macros = [\n\t\t\t30896 => [\n\t\t\t\t'hostids' => [10084],\n\t\t\t\t'macros' => [\n\t\t\t\t\t'{$TMG.PROXY.CHECK.URL1}' => 'http://zabbix.com',\n\t\t\t\t\t'{$CITY}' => 'Tokyo'\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\n\t\t// Such mocking approach allows to mock protected class methods, but still will not work with private methods.\n\t\t/** @var $stub CMacrosResolver */\n\t\t$this->stub = $this->getMockBuilder(CMacrosResolver::class)\n\t\t\t->setMethods(['getUserMacros'])\n\t\t\t->getMock();\n\n\t\t$this->stub->method('getUserMacros')\n\t\t\t->willReturn($user_macros);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n\n createDefaultRelationshipTableFields($table, 'page', 'printed_catalog');\n $table->integer('position')->unsigned()->index();\n\n $table->timestamps();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function __construct(\n\t\tprivate readonly MaaltijdenRepository $maaltijdenRepository,\n\t\tprivate readonly MaaltijdAanmeldingenRepository $maaltijdAanmeldingenRepository,\n\t\tprivate readonly ArchiefMaaltijdenRepository $archiefMaaltijdenRepository,\n\t\tprivate readonly CorveeTakenRepository $corveeTakenRepository\n\t) {\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function testDashboardGraphWidget_cancelWidgetEditing($data) {\n\t\t$old_hash = CDBHelper::getHash(self::SQL);\n\n\t\t$this->page->login()->open(self::DASHBOARD_URL);\n\t\t$form = $this->openGraphWidgetConfiguration(CTestArrayHelper::get($data, 'Existing widget', []));\n\t\t$form->fill($data['main_fields']);\n\t\t$this->fillDataSets($data['Data set']);\n\t\t$overlay = $this->query('xpath://div[contains(@class, \"overlay-dialogue\")][@data-dialogueid=\"widget_properties\"]')\n\t\t\t\t\t\t->asOverlayDialog()->one();\n\t\t$overlay->close();\n\n\t\t// Check canceled graph widget.\n\t\t$dashboard = CDashboardElement::find()->one();\n\t\t// If test fails and widget isn't canceled, need to wait until widget appears on the dashboard.\n\t\tsleep(2);\n\t\t$this->assertTrue(!$dashboard->query('xpath:.//div[contains(@class, \"dashboard-grid-widget-head\")]/h4[text()='.\n\t\t\t\tCXPathHelper::escapeQuotes($data['main_fields']['Name']).']')->one(false)->isValid());\n\t\t$dashboard->save();\n\n\t\t$this->assertEquals($old_hash, CDBHelper::getHash(self::SQL));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function testPageAdministrationGeneralImages_IconSimpleUpdate($image) {\n\t\t$sql_image = 'SELECT * FROM images WHERE imageid='.$image['imageid'];\n\t\t$old_image_hash = CDBHelper::getHash($sql_image);\n\n\t\t$this->zbxTestLogin('zabbix.php?action=image.list');\n\t\t$this->zbxTestAssertElementPresentXpath('//button[text()=\"Create icon\"]');\n\t\t$this->zbxTestDropdownSelectWait('imagetype', $image['imagetype'] == IMAGE_TYPE_ICON ? 'Icon' : 'Background');\n\t\t$this->zbxTestClickLinkTextWait($image['name']);\n\t\t$this->page->waitUntilReady();\n\t\t$this->zbxTestCheckHeader('Images');\n\t\t$this->zbxTestTextPresent(['Name', 'Upload', 'Image']);\n\t\t$this->zbxTestAssertElementPresentId('update');\n\t\t$this->zbxTestAssertElementPresentId('delete');\n\t\t$this->zbxTestAssertElementPresentId('cancel');\n\t\t$this->zbxTestClickWait('update');\n\t\t$this->zbxTestWaitUntilMessageTextPresent('msg-good', 'Image updated');\n\n\t\t$this->assertEquals($old_image_hash, CDBHelper::getHash($sql_image));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "private function resolveOptions(array $options = []): void\n {\n $resolver = new OptionsResolver();\n $resolver->setDefaults([\n 'processTimeout' => 300,\n ]);\n\n $resolver->setAllowedTypes('processTimeout', 'int');\n $resolver->setRequired('processTimeout');\n\n $options = $resolver->resolve($options);\n\n $this->processTimeout = $options['processTimeout'];\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "abstract protected function buildProvider(): BaseProvider;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function getServiceLocator(): ServiceLocator\n {\n return $this->createMock(ServiceLocator::class);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function clear() {\n\t\t$query = $this->query('xpath:.//span[@class=\"subfilter-disable-btn\"]');\n\t\t$query->all()->click();\n\t\t$query->waitUntilNotPresent();\n\n\t\treturn $this;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function setTerritory(?Territory $territory): static\n {\n $this->territory = $territory;\n\n return $this;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function __construct()\n {\n parent::__construct('installations', self::ALLOWED_ATTRIBUTES);\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function tableExists(DatabaseName $database, TableName $table): bool\n {\n // SHOW TABLES doesn't show temporary tables, so try select.\n return $this->dbi->tryQuery(sprintf(\n 'SELECT 1 FROM %s.%s LIMIT 1;',\n Util::backquote($database),\n Util::backquote($table),\n )) !== false;\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public static function getTimePeriodValidationData() {\n\t\treturn [\n\t\t\t// Empty From/To fields.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '',\n\t\t\t\t\t\t'To' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"From\": cannot be empty.',\n\t\t\t\t\t\t'Invalid parameter \"To\": cannot be empty.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-07-04 15:53:07',\n\t\t\t\t\t\t'To' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"To\": cannot be empty.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '',\n\t\t\t\t\t\t'To' => '2021-07-04 15:53:07'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"From\": cannot be empty.',\n\t\t\t\t\t\t'Minimum time period to display is 1 minute.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Date format validation (YYYY-MM-DD HH-MM-SS)\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '1',\n\t\t\t\t\t\t'To' => '2021-07-04 15:53:07'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"From\": a time is expected.',\n\t\t\t\t\t\t'Minimum time period to display is 1 minute.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-07-04 15:53:07',\n\t\t\t\t\t\t'To' => 'abc'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"To\": a time is expected.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '5:53:06 2021-07-31',\n\t\t\t\t\t\t'To' => '2021-07-04 15:53:07'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"From\": a time is expected.',\n\t\t\t\t\t\t'Minimum time period to display is 1 minute.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-02-30 00:00:00',\n\t\t\t\t\t\t'To' => '2021-07-04 15:53:07'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"From\": a time is expected.',\n\t\t\t\t\t\t'Minimum time period to display is 1 minute.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-05-02 00:00:00',\n\t\t\t\t\t\t'To' => '2021-25-09 00:00:00'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"To\": a time is expected.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-05-02 00:00:00',\n\t\t\t\t\t\t'To' => '2021.07.31 15:53:07'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"To\": a time is expected.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-07-04 12:53:00',\n\t\t\t\t\t\t'To' => 'now-s'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"To\": a time is expected.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Time range validation\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2021-07-04 12:53:00',\n\t\t\t\t\t\t'To' => '2021-07-04 12:52:59'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Minimum time period to display is 1 minute.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => '2027-07-04 12:53:00',\n\t\t\t\t\t\t'To' => 'now'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Minimum time period to display is 1 minute.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Time period' => [\n\t\t\t\t\t\t'Set custom time period' => true,\n\t\t\t\t\t\t'From' => 'now-58s',\n\t\t\t\t\t\t'To' => 'now'\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Minimum time period to display is 1 minute.'\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function hasParameterProvider($fieldTypeIdentifier);", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getRouteName(): string\n {\n return static::ROUTE_NAME;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function loadChoiceList($value = null)\n {\n $choices = $this->getChoiceList();\n\n return new ArrayChoiceList($choices, $value);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function supportsClass($class): bool\n {\n return true;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function provideValidInputForAcceptValue()\n {\n return [\n [\n [],\n new SelectionValue(),\n ],\n [\n [23],\n new SelectionValue([23]),\n ],\n [\n [23, 42],\n new SelectionValue([23, 42]),\n ],\n [\n new SelectionValue([23, 42]),\n new SelectionValue([23, 42]),\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function marshal(mixed $value, array $params = []): mixed\n {\n if (is_array($value)) {\n $minMaxValue = [\n 'minimum' => $value['minimum'] ?? null,\n 'maximum' => $value['maximum'] ?? null,\n ];\n\n return [\n 'value' => Serialize::serialize($minMaxValue),\n 'value2' => $value['unitId'] ?? null,\n ];\n }\n\n return null;\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getLoginURL(): string\n {\n return $this->endpoint . '/oauth/authorize?' . \\http_build_query([\n 'client_id' => $this->appID,\n 'redirect_uri' => $this->callback,\n 'response_type' => 'code',\n 'state' => \\json_encode($this->state),\n 'owner' => 'user'\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n private readonly ResponseRenderer $response,\n private readonly UserPreferences $userPreferences,\n private readonly Relation $relation,\n private readonly Config $config,\n private readonly ThemeManager $themeManager,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function (Blueprint $table) {\n $table->uuid('id')->primary();\n $table->foreignUuid('campaign_id')->constrained('campaigns');\n $table->string('type');\n $table->json('data');\n $table->timestamp('execute_at');\n $table->timestamp('last_execution_attempt_at')->nullable();\n $table->text('last_execution_attempt_error')->nullable();\n $table->timestamp('successfully_executed_at')->nullable();\n $table->timestamps();\n $table->softDeletes();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getAccessoriesPromise(array $data): Promise\n {\n return $this->productsSellableByIdsBatchLoader->load($data['accessories']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function getExtendedTypes(): iterable\n {\n yield OrderItemFormType::class;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function loadAll()\n {\n $this->logger->logCall(__METHOD__);\n\n return $this->persistenceHandler->sectionHandler()->loadAll();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function operator(Compiler $compiler)\n {\n return $compiler->raw('<=>');\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function isSearchable(): bool\n {\n return true;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function prepareDataStructureForYaml(string $id, mixed $data): mixed\n {\n return $data;\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function table(Table $table): Table\n {\n return $table\n ->heading('Latest KB Articles (5)')\n ->query(\n KnowledgeBaseArticle::latest()->limit(5)\n )\n ->columns([\n IdColumn::make(),\n TextColumn::make('title')\n ->label('Title')\n ->searchable()\n ->sortable()\n ->limit(),\n TextColumn::make('quality.name')\n ->label('Quality')\n ->sortable()\n ->toggleable(isToggledHiddenByDefault: true),\n TextColumn::make('status.name')\n ->label('Status')\n ->sortable()\n ->toggleable(isToggledHiddenByDefault: true),\n TextColumn::make('public')\n ->label('Public')\n ->sortable()\n ->formatStateUsing(fn (bool $state): string => $state ? 'Yes' : 'No')\n ->toggleable(isToggledHiddenByDefault: true),\n TextColumn::make('category.name')\n ->label('Category')\n ->sortable()\n ->toggleable(isToggledHiddenByDefault: true),\n ])\n ->actions([\n ViewAction::make()\n ->url(fn (KnowledgeBaseArticle $record): string => KnowledgeBaseArticleResource::getUrl(name: 'view', parameters: ['record' => $record])),\n ])\n ->recordUrl(\n fn (KnowledgeBaseArticle $record): string => KnowledgeBaseArticleResource::getUrl(name: 'view', parameters: ['record' => $record]),\n )\n ->paginated(false);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function assigned(User $user = null): self\n {\n return $this->state([\n 'assigned_to' => $user?->id ?? User::factory(),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function isVisible(array $data): bool\n {\n $currentCustomerPricingGroup = $this->currentCustomerUser->getPricingGroup();\n\n foreach ($data['visibility'] as $visibility) {\n if ($currentCustomerPricingGroup->getId() === $visibility['pricing_group_id']) {\n return $visibility['visible'];\n }\n }\n\n return false;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function createProxy(string $className, Closure $initializer, array $proxyOptions = []): VirtualProxyInterface;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function createValueFromInput($inputValue)\n {\n if (is_int($inputValue)) {\n $inputValue = new Value($inputValue);\n }\n\n return $inputValue;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function upvotes(): HasMany\n {\n return $this->hasMany(AiAssistantUpvote::class, 'assistant_id');\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function testRefreshUserNotFound(): void\n {\n $userId = 123;\n $apiUser = $this->buildUserValueObjectStub($userId);\n $user = $this->createMock(UserInterface::class);\n $user\n ->expects(self::once())\n ->method('getAPIUser')\n ->willReturn($apiUser);\n\n $this->userService\n ->expects(self::once())\n ->method('loadUser')\n ->with($userId)\n ->willThrowException(new NotFoundException('user', 'foo'));\n\n $this->expectException(UserNotFoundException::class);\n $this->userProvider->refreshUser($user);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct()\n {\n $this->sendRegistrationMail = false;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(string $identifier)\n {\n $this->identifier = $identifier;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function getWidgetCancelData() {\n\t\treturn [\n\t\t\t// Add new graph widget.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Cancel widget create'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t'host' => 'Cancel create',\n\t\t\t\t\t\t'item' => 'Cancel create'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Update existing graph widget.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'Existing widget' => 'Test cases for simple update and deletion',\n\t\t\t\t\t'main_fields' => [\n\t\t\t\t\t\t'Name' => 'Cancel widget update'\n\t\t\t\t\t],\n\t\t\t\t\t'Data set' => [\n\t\t\t\t\t\t'host' => 'Cancel update',\n\t\t\t\t\t\t'item' => 'Cancel update'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getIdentifier(): string\n {\n return $this->identifier;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function __construct(VersionInfo $versionInfo, array $translations)\n {\n $this->versionInfo = $versionInfo;\n $this->translations = $translations;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('transport_group_transport', function (Blueprint $table) {\n $table->id();\n $table->unsignedInteger('transport_group_id');\n $table->unsignedInteger('transport_id');\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function addRow($values) {\n\t\t$rows = $this->getRows()->count();\n\t\t$this->query('button:Add')->one()->click();\n\n\t\t// Wait until new table row appears.\n\t\t$this->query('xpath:.//'.CXPathHelper::fromSelector($this->selectors['row']).'['.($rows + 1).']')->waitUntilPresent();\n\t\treturn $this->updateRow($rows, $values);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function up(): void\n {\n Schema::table('3d_models', function (Blueprint $table) {\n $table->string('model_caption_title')->nullable();\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n $table->string('name')->default('')->unique();\n $table->string('desc')->default('');\n $table->text('pattern')->nullable();\n $table->text('params')->nullable();\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function testDashboardPlainTextWidget_Create($data) {\n\t\t$this->checkWidgetForm($data);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function behaviors()\n {\n return [\n 'CTimestampBehavior' => [\n 'class' => 'zii.behaviors.CTimestampBehavior',\n 'createAttribute' => 'created_at',\n 'updateAttribute' => 'updated_at',\n 'setUpdateOnCreate' => true,\n 'timestampExpression' => new CDbExpression('CONVERT_TZ(NOW(), \"+00:00\", \"-03:00\")'),\n ]\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "static function (PiggyBankEvent $event): void {\n $event->piggyBank = $event->piggyBank()->withTrashed()->first();\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function getMainVariant(array $data): array\n {\n return $this->productElasticsearchProvider->getVisibleProductArrayById($data['main_variant_id']);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (Blueprint $table) {\n $table->increments('id');\n $table->datetime('opening_time')->nullable();\n $table->datetime('closing_time')->nullable();\n $table->integer('type');\n $table->integer('day_of_week');\n $table->softDeletes();\n $table->timestamps();\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function providerForCachedLoadMethodsHit(): array\n {\n $object = new Setting(['group' => 'group_a1', 'identifier' => 'identifier_b2']);\n\n // string $method, array $arguments, string $key, array? $tagGeneratingArguments, array? $tagGeneratingResults, array? $keyGeneratingArguments, array? $keyGeneratingResults, mixed? $data, bool $multi\n return [\n [\n 'load',\n ['group_a1', 'identifier_b2'],\n 'ibx-set-group_a1-identifier_b2',\n [['setting', ['group_a1', 'identifier_b2'], true]],\n ['ibx-set-group_a1-identifier_b2'],\n null,\n null,\n $object,\n ],\n ];\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function transform(&$key, &$value, stdClass $obj, Configuration $config, $exceptionLogLevel)\n {\n $overwriteKey = '$overwrite';\n $overwriteDirectives = array();\n\n // Need to look into the rest of the object here, do we have access to it?\n\n if ( isset($obj->$overwriteKey) ) {\n $overwriteDirectives = $obj->$overwriteKey;\n // Remove the overwrite key from the object because the JsonReferenceTransformer will\n // not allow it.\n unset($obj->$overwriteKey);\n } else {\n // If the reference with overwrite was specified, it must contain the overwrite\n // directive!\n $this->logAndThrowException(\n sprintf(\"Expected '%s' directive not found\", $overwriteKey),\n array('log_level' => $exceptionLogLevel)\n );\n }\n\n $jsonRefUrl = $value;\n parent::transform($key, $value, $obj, $config, $exceptionLogLevel);\n\n if ( ! is_object($value) ) {\n $this->logger->warning(\n sprintf(\"JSON reference '%s' does not generate object, got %s. Skipping.\", $jsonRefUrl, gettype($value))\n );\n } else {\n foreach ( $overwriteDirectives as $overwriteKey => $overwriteValue ) {\n if ( ! isset($value->$overwriteKey) ) {\n $this->logger->debug(sprintf(\"Overwrite key '%s' not found in reference, adding.\", $overwriteKey));\n } else {\n $this->logger->debug(sprintf(\"Overwriting '%s' in reference.\", $overwriteKey));\n }\n $value->$overwriteKey = $overwriteValue;\n }\n }\n\n return true;\n }", "smellKey": "0", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function theQueryResultsAssignedToTheTwigVariableIsAObject($twigVariableName, $className)\n {\n $variableTypes = $this->getVariableTypesFromTemplate();\n\n Assert::assertArrayHasKey($twigVariableName, $variableTypes, \"The $twigVariableName twig variable was not set\");\n Assert::assertEquals($className, $variableTypes[$twigVariableName], \"The $twigVariableName twig variable does not have $className type\");\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(\n private Intervention $intervention,\n private User $user,\n private \\DateTimeImmutable $previousDate,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function setDescription($description): void\n {\n $this->description = $description;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function forceDelete(Authenticatable $authenticatable, Prompt $prompt): Response\n {\n return $authenticatable->canOrElse(\n abilities: [\"prompt.{$prompt->id}.force-delete\"],\n denyResponse: 'You do not have permission to permanently delete this prompt.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getLocationCreateStruct(array $data)\n {\n $struct = new CreateStruct();\n\n $struct->contentId = $data['contentobject_id'];\n $struct->contentVersion = $data['contentobject_version'];\n $struct->hidden = $data['is_hidden'];\n $struct->invisible = $data['is_invisible'];\n $struct->mainLocationId = $data['main_node_id'];\n $struct->parentId = $data['parent_node_id'];\n $struct->pathIdentificationString = $data['path_identification_string'];\n $struct->priority = $data['priority'];\n $struct->remoteId = md5(uniqid(static::class, true));\n $struct->sortField = $data['sort_field'];\n $struct->sortOrder = $data['sort_order'];\n\n return $struct;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function preGetData(mixed $container, array $params = []): mixed;", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function setLocale(string $locale): void\n {\n $this->locale = $locale;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('highlight_category', function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n\n createDefaultRelationshipTableFields($table, 'highlight', 'category');\n });\n\n Schema::create('experience_category', function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n\n createDefaultRelationshipTableFields($table, 'experience', 'category');\n });\n\n Schema::create('video_category', function (Blueprint $table) {\n $table->increments('id');\n $table->timestamps();\n\n createDefaultRelationshipTableFields($table, 'video', 'category');\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('form_authentications', function (Blueprint $table) {\n $table->uuid('id')->primary();\n\n $table->string('author_id')->nullable();\n $table->string('author_type')->nullable();\n $table->string('code')->nullable();\n $table->foreignUuid('form_id')->constrained('forms')->cascadeOnDelete();\n\n $table->timestamps();\n\n $table->index(['author_type', 'author_id']);\n });\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function search()\n\t{\n\n\t\t$criteria=new CDbCriteria;\n\n\t\t$criteria->compare('id',$this->id);\n\t\t$criteria->compare('name',$this->name,true);\n\t\t$criteria->compare('description',$this->description,true);\n\t\t$criteria->compare('measurement',$this->measurement,true);\n\t\t$criteria->compare('year_amount',$this->year_amount);\n\t\t$criteria->compare('food_id',$this->food_id);\n\n\t\treturn new CActiveDataProvider($this, array(\n\t\t\t'criteria'=>$criteria,\n\t\t));\n\t}", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "#[DataProvider('booleanWithDefaultFalseProvider')]\n public function testSql(mixed $actual, bool $expected): void\n {\n $debug = new Debug(['sql' => $actual]);\n $debugArray = $debug->asArray();\n self::assertSame($expected, $debug->sql);\n self::assertSame($expected, $debugArray['sql']);\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function __construct(Role $role, RoleCopyStruct $roleCopyStruct)\n {\n $this->role = $role;\n $this->roleCopyStruct = $roleCopyStruct;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function checkWidgetForm($data, $update = false) {\n\t\tif (CTestArrayHelper::get($data, 'expected', TEST_GOOD) === TEST_BAD) {\n\t\t\t$old_hash = CDBHelper::getHash($this->sql);\n\t\t}\n\n\t\t$data['fields']['Name'] = CTestArrayHelper::get($data, 'fields.Name', 'Plain text widget '.microtime());\n\t\t$this->page->login()->open('zabbix.php?action=dashboard.view&dashboardid='.self::$dashboard_create)->waitUntilReady();\n\t\t$dashboard = CDashboardElement::find()->one();\n\t\t$old_widget_count = $dashboard->getWidgets()->count();\n\n\t\t$form = ($update)\n\t\t\t? $dashboard->getWidget(self::$update_widget)->edit()->asForm()\n\t\t\t: $dashboard->edit()->addWidget()->asForm();\n\n\t\t$form->fill(['Type' => CFormElement::RELOADABLE_FILL('Plain text')]);\n\n\t\t// Prepare the data for filling in \"Items\" field of widget, get item names.\n\t\tif (array_key_exists('items', $data)) {\n\t\t\tforeach ($data['items'] as $array) {\n\t\t\t\t$data['fields']['Items'][] = implode(array_values($array));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t$data['fields']['Items'] = '';\n\t\t}\n\n\t\t$form->fill($data['fields']);\n\t\t$values = $form->getValues();\n\t\t$form->submit();\n\t\t$this->page->waitUntilReady();\n\n\t\t// Trim leading and trailing spaces from expected results if necessary.\n\t\tif (array_key_exists('trim', $data)) {\n\t\t\tforeach ($data['trim'] as $field) {\n\t\t\t\t$data['fields'][$field] = trim($data['fields'][$field]);\n\t\t\t}\n\t\t}\n\n\t\tif (CTestArrayHelper::get($data, 'expected', TEST_GOOD) === TEST_BAD) {\n\t\t\t$this->assertMessage($data['expected'], null, $data['error']);\n\t\t\t$this->assertEquals($old_hash, CDBHelper::getHash($this->sql));\n\t\t\tCOverlayDialogElement::find()->one()->close();\n\t\t\t$dashboard->save();\n\t\t\t$this->page->waitUntilReady();\n\t\t\t$this->assertFalse($dashboard->getWidget($data['fields']['Name'], false)->isValid());\n\t\t}\n\t\telse {\n\t\t\t$items_count = count($data['items']);\n\t\t\tif ($data['fields']['Name'] === '') {\n\t\t\t\tif ($items_count > 1) {\n\t\t\t\t\t$header = (array_key_exists('same_host', $data))\n\t\t\t\t\t\t? $data['same_host'].': '.$items_count.' items'\n\t\t\t\t\t\t: 'Plain text';\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// If name is empty string it is replaced by item name.\n\t\t\t\t\t$header = implode(array_keys($data['items'][0])).': '.implode($data['fields']['Items']);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$header = $data['fields']['Name'];\n\t\t\t}\n\n\t\t\tif ($update) {\n\t\t\t\tself::$update_widget = $header;\n\t\t\t}\n\n\t\t\tCOverlayDialogElement::ensureNotPresent();\n\t\t\t$widget = $dashboard->getWidget($header);\n\n\t\t\t// Save Dashboard to ensure that widget is correctly saved.\n\t\t\t$dashboard->save();\n\t\t\t$this->page->waitUntilReady();\n\t\t\t$this->assertMessage(TEST_GOOD, 'Dashboard updated');\n\n\t\t\t// Check widgets count.\n\t\t\t$this->assertEquals($old_widget_count + ($update ? 0 : 1), $dashboard->getWidgets()->count());\n\n\t\t\t// Check new widget form fields and values in frontend.\n\t\t\t$saved_form = $widget->edit();\n\t\t\t$this->assertEquals($values, $saved_form->getValues());\n\n\t\t\t// Prepare data to check widget \"Items\" field, should be in the format \"Host name: Item name\".\n\t\t\t$data['fields']['Items'] = [];\n\t\t\tforeach ($data['items'] as $host_item) {\n\t\t\t\tforeach ($host_item as $host => $item) {\n\t\t\t\t\t$data['fields']['Items'][] = $host.': '.$item;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$saved_form->checkValue($data['fields']);\n\t\t\t$saved_form->submit();\n\t\t\tCOverlayDialogElement::ensureNotPresent();\n\t\t\t$dashboard->save();\n\t\t\t$this->page->waitUntilReady();\n\t\t\t$this->assertMessage(TEST_GOOD, 'Dashboard updated');\n\n\t\t\t// Check new widget update interval.\n\t\t\t$refresh = (CTestArrayHelper::get($data['fields'], 'Refresh interval') === 'Default (1 minute)')\n\t\t\t\t? '1 minute'\n\t\t\t\t: (CTestArrayHelper::get($data['fields'], 'Refresh interval', '1 minute'));\n\t\t\t$this->assertEquals($refresh, $widget->getRefreshInterval());\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->boolean('google_2fa_enabled')->default(false);\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function testGetFullNameReturnsLastnameAndFirstnameForUser()\n {\n $customerUserData = TestCustomerProvider::getTestCustomerUserData(false);\n $customerUser = new CustomerUser($customerUserData);\n\n $this->assertSame('Lastname Firstname', $customerUser->getFullName());\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(\n ConfigResolverInterface $configResolver,\n ResolverInterface $resolver,\n $proxyResolverClass,\n $relativeResolverClass\n ) {\n $this->configResolver = $configResolver;\n $this->resolver = $resolver;\n $this->proxyResolverClass = $proxyResolverClass;\n $this->relativeResolverClass = $relativeResolverClass;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function testInheritanceTriggerPrototype_SimpleUpdate($data) {\n\t\t$sqlTriggers = 'SELECT * FROM triggers ORDER BY triggerid';\n\t\t$oldHashTriggers = CDBHelper::getHash($sqlTriggers);\n\n\t\t$this->zbxTestLogin('trigger_prototypes.php?form=update&context=host&triggerid='.$data['triggerid'].\n\t\t\t\t'&parent_discoveryid='.$data['parent_itemid']);\n\t\t$this->zbxTestClickWait('update');\n\t\t$this->zbxTestCheckTitle('Configuration of trigger prototypes');\n\t\t$this->zbxTestTextPresent('Trigger prototype updated');\n\n\t\t$this->assertEquals($oldHashTriggers, CDBHelper::getHash($sqlTriggers));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function setUser(User $user): void;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function getWordsAsString(): string;", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function testObjectDataRecycleAndRestore(): void\n {\n // create target object\n $inputText = TestHelper::generateRandomString();\n\n //create relation object\n $relationObject = TestHelper::createEmptyObject();\n\n // create source object\n $sourceObject = TestHelper::createEmptyObject();\n $sourceObject->setInput($inputText);\n $sourceObject->setObjects([$relationObject]); //set relation\n $sourceObject->setLobjects([$relationObject]); //set localized relation\n $sourceObject->save();\n\n $sourceObjectPath = $sourceObject->getFullPath();\n $sourceObjectId = $sourceObject->getId();\n\n //add to recyclebin\n Item::create($sourceObject, $this->user);\n $sourceObject->delete();\n\n //restore deleted items (parent + child)\n $recycledItems = new Item\\Listing();\n $recycledItems->setCondition('`path` = ?', $sourceObjectPath);\n $recycledItems->current()->restore();\n\n //load relation and check if relation loads correctly\n $restoredSourceObject = DataObject::getById($sourceObjectId);\n $restoredRelation = $restoredSourceObject->getLobjects();\n $restoredLocalizedRelation = $restoredSourceObject->getLobjects();\n\n $this->assertEquals($inputText, $restoredSourceObject->getInput(), 'Input data not restored properly');\n $this->assertEquals($relationObject->getId(), $restoredRelation[0]->getId(), 'Simple object relation not restored properly');\n $this->assertEquals($relationObject->getId(), $restoredLocalizedRelation[0]->getId(), 'Localized object relation not restored properly');\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getWidgetData() {\n\t\treturn [\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'error' => 'Invalid parameter \"Items\": cannot be empty.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"Show lines\": value must be one of 1-100.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => '0'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"Show lines\": value must be one of 1-100.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => '101'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"Show lines\": value must be one of 1-100.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => ' '\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t],\n\t\t\t\t\t'error' => 'Invalid parameter \"Show lines\": value must be one of 1-100.'\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_BAD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'error' => [\n\t\t\t\t\t\t'Invalid parameter \"Items\": cannot be empty.',\n\t\t\t\t\t\t'Invalid parameter \"Show lines\": value must be one of 1-100.'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Test case with items from the same host which name is used as widget header.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'same_host' => '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440',\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => ''\n\t\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory'],\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory in %']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Test case with items from two different hosts.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory in %'],\n\t\t\t\t\t\t['Simple host with item for plain text widget' => 'Test plain text']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Test case with items from the same host and with custom name.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => 'Test custom name'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory'],\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory in %']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Test case with items from two different hosts and with custom name.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => 'Test custom name2'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory'],\n\t\t\t\t\t\t['Simple host with item for plain text widget' => 'Test plain text']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t// Test case with one item which name is used as widget header.\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => ''\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => '',\n\t\t\t\t\t\t'Refresh interval' => 'Default (1 minute)'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['Simple host with item for plain text widget' => 'Test plain text']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => 'Header is hidden',\n\t\t\t\t\t\t'Show header' => false,\n\t\t\t\t\t\t'Refresh interval' => 'No refresh'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => 'Header appears',\n\t\t\t\t\t\t'Show header' => true,\n\t\t\t\t\t\t'Refresh interval' => '10 seconds'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Items location' => 'Top',\n\t\t\t\t\t\t'Refresh interval' => '30 seconds'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Items location' => 'Left',\n\t\t\t\t\t\t'Refresh interval' => '1 minute'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => '1',\n\t\t\t\t\t\t'Refresh interval' => '2 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show lines' => '100',\n\t\t\t\t\t\t'Refresh interval' => '10 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show text as HTML' => true,\n\t\t\t\t\t\t'Refresh interval' => '15 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show text as HTML' => false,\n\t\t\t\t\t\t'Refresh interval' => '10 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Dynamic items' => true,\n\t\t\t\t\t\t'Refresh interval' => '2 minutes'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Dynamic items' => false,\n\t\t\t\t\t\t'Refresh interval' => '1 minute'\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Name' => ' Widget with trimmed trailing and leading spaces ',\n\t\t\t\t\t\t'Refresh interval' => '30 seconds',\n\t\t\t\t\t\t'Show lines' => ' 5 '\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['Simple host with item for plain text widget' => 'Test plain text']\n\t\t\t\t\t],\n\t\t\t\t\t'trim' => ['Name', 'Show lines']\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'expected' => TEST_GOOD,\n\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t'Show header' => true,\n\t\t\t\t\t\t'Name' => 'Widget with updated fields',\n\t\t\t\t\t\t'Refresh interval' => '1 minute',\n\t\t\t\t\t\t'Items location' => 'Top',\n\t\t\t\t\t\t'Show lines' => '50',\n\t\t\t\t\t\t'Show text as HTML' => true,\n\t\t\t\t\t\t'Dynamic items' => true\n\t\t\t\t\t],\n\t\t\t\t\t'items' => [\n\t\t\t\t\t\t['\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440' => 'Linux: Available memory']\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function __construct(\n protected readonly AdminDomainTabsFacade $adminDomainTabsFacade,\n protected readonly MailTemplateFacade $mailTemplateFacade,\n protected readonly MailSettingFacade $mailSettingFacade,\n protected readonly BreadcrumbOverrider $breadcrumbOverrider,\n protected readonly MailTemplateGridFactory $mailTemplateGridFactory,\n protected readonly MailTemplateConfiguration $mailTemplateConfiguration,\n protected readonly MailTemplateDataFactory $mailTemplateDataFactory,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (AiMessage $response) use ($thread) {\n $response->save();\n\n dispatch(new RecordTrackedEvent(\n type: TrackedEventType::AiExchange,\n occurredAt: now(),\n ));\n\n $thread->touch();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "abstract public function getPolicies(): iterable;", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function getAllStages(): array\n {\n return [\n self::RELEASE_CANDIDATE,\n self::RELEASE,\n self::AFTER_RELEASE,\n ];\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getCriterion(APILimitationValue $value, APIUserReference $currentUser)\n {\n return new Criterion\\MatchNone();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function markAsExecuted(): void\n {\n app('fireflyconfig')->set(self::CONFIG_NAME, true);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function loadListByLanguageCodes(array $languageCodes): iterable\n {\n $missing = [];\n $languages = [];\n foreach ($languageCodes as $languageCode) {\n if ($language = $this->cache->get($this->cacheIdentifierGenerator->generateKey(self::LANGUAGE_CODE_IDENTIFIER, [$languageCode], true))) {\n $languages[$languageCode] = $language;\n } else {\n $missing[] = $languageCode;\n }\n }\n\n if (!empty($missing)) {\n $loaded = $this->innerHandler->loadListByLanguageCodes($missing);\n $this->storeCache($loaded);\n /** @noinspection AdditionOperationOnArraysInspection */\n $languages += $loaded;\n }\n\n return $languages;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function up(): void\n {\n $this->migrator->addEncrypted('ai.assistant_id');\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n // this up() migration is auto-generated, please modify it to your needs\n $this->addSql('ALTER TABLE accounts CHANGE blocked_reason blocked_reason LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE agenda CHANGE beschrijving beschrijving LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE biebbeschrijving CHANGE beschrijving beschrijving LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE biebexemplaar CHANGE opmerking opmerking LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE changelog CHANGE old_value old_value LONGTEXT DEFAULT NULL, CHANGE new_value new_value LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE civi_product CHANGE beschrijving beschrijving LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE civi_saldo CHANGE naam naam LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE civi_saldo_log CHANGE data data LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE courant CHANGE inhoud inhoud LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE courantbericht CHANGE bericht bericht LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE crv_functies CHANGE email_bericht email_bericht LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE crv_taken CHANGE wanneer_gemaild wanneer_gemaild LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE debug_log CHANGE call_trace call_trace LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE forum_delen CHANGE omschrijving omschrijving LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE forum_draden_reageren CHANGE concept concept LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE forum_posts CHANGE tekst tekst LONGTEXT NOT NULL, CHANGE bewerkt_tekst bewerkt_tekst LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE forumplaatjes CHANGE source_url source_url LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE instellingen CHANGE waarde waarde LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE lidinstellingen CHANGE waarde waarde LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE lidtoestemmingen CHANGE waarde waarde LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE mlt_archief CHANGE aanmeldingen aanmeldingen LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE mlt_maaltijden CHANGE omschrijving omschrijving LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE peiling CHANGE beschrijving beschrijving LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE peiling_optie CHANGE beschrijving beschrijving LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE profielen CHANGE kgb kgb LONGTEXT DEFAULT NULL, CHANGE novitiaat novitiaat LONGTEXT DEFAULT NULL, CHANGE vrienden vrienden LONGTEXT DEFAULT NULL, CHANGE medisch medisch LONGTEXT DEFAULT NULL, CHANGE novitiaatBijz novitiaatBijz LONGTEXT DEFAULT NULL');\n $this->addSql('ALTER TABLE savedquery CHANGE savedquery savedquery LONGTEXT NOT NULL');\n $this->addSql('ALTER TABLE voorkeur_opmerking CHANGE lidOpmerking lidOpmerking LONGTEXT DEFAULT NULL, CHANGE praesesOpmerking praesesOpmerking LONGTEXT DEFAULT NULL');\n }", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function load($id)\n {\n $language = $this->cache->get(\n $this->cacheIdentifierGenerator->generateKey(self::LANGUAGE_IDENTIFIER, [$id], true)\n );\n\n if ($language === null) {\n $language = $this->innerHandler->load($id);\n $this->storeCache([$language]);\n }\n\n return $language;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "#[Route(path: '/billing-address/edit/{id}', name: 'admin_billing_address_edit', requirements: ['id' => '\\d+'])]\n public function editAction(Request $request, int $id): Response\n {\n $billingAddress = $this->billingAddressFacade->getById($id);\n $billingAddressData = $this->billingAddressDataFactory->createFromBillingAddress($billingAddress);\n\n $form = $this->createForm(BillingAddressAndRelatedInfoFormType::class, $billingAddressData, [\n 'customer' => $billingAddress->getCustomer(),\n 'domain_id' => $this->adminDomainTabsFacade->getSelectedDomainId(),\n 'disableCompanyCustomerCheckbox' => true,\n ]);\n $form->handleRequest($request);\n\n if ($form->isSubmitted() && $form->isValid()) {\n $this->billingAddressFacade->edit($billingAddress->getId(), $billingAddressData);\n $this->addSuccessFlashTwig(\n t('Billing address {{ name }} modified'),\n [\n 'name' => $billingAddress->getCompanyName(),\n 'url' => $this->generateUrl('admin_billing_address_edit', ['id' => $billingAddress->getId()]),\n ],\n );\n\n return $this->redirectToRoute('admin_customer_list');\n }\n\n if ($form->isSubmitted() && !$form->isValid()) {\n $this->addErrorFlashTwig(t('Please check the correctness of all data filled.'));\n }\n\n $this->breadcrumbOverrider->overrideLastItem(\n t('Editing billing address - %name%', ['%name%' => $billingAddress->getCompanyName()]),\n );\n\n return $this->render('@ShopsysFramework/Admin/Content/Customer/BillingAddress/edit.html.twig', [\n 'form' => $form->createView(),\n 'billingAddress' => $billingAddress,\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function getEnrichedFieldDefinitions(array $context = []): array\n {\n $enrichedFieldDefinitions = [];\n if (is_array($this->fieldDefinitionsCache)) {\n foreach ($this->fieldDefinitionsCache as $key => $fieldDefinition) {\n $fieldDefinition = $this->doEnrichFieldDefinition($fieldDefinition, $context);\n $enrichedFieldDefinitions[$key] = $fieldDefinition;\n }\n }\n\n return $enrichedFieldDefinitions;\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getGuiData() {\n\t\treturn [\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'field' => [\n\t\t\t\t\t\t'Default language' => 'Russian (ru_RU)'\n\t\t\t\t\t],\n\t\t\t\t\t'message' => 'Configuration updated',\n\t\t\t\t\t'page_title' => '\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u0432\u0435\u0431-\u0438\u043d\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430',\n\t\t\t\t\t'html_lang' => 'ru',\n\t\t\t\t\t'defaultdb_lang' => 'ru_RU',\n\t\t\t\t\t'info' => self::INFO_RUS,\n\t\t\t\t\t'login_info' => [\n\t\t\t\t\t\t\t'name' => '\u0418\u043c\u044f \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f',\n\t\t\t\t\t\t\t'password' => '\u041f\u0430\u0440\u043e\u043b\u044c'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t[\n\t\t\t\t\t'field' => [\n\t\t\t\t\t\t'\u042f\u0437\u044b\u043a \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e' => '\u0410\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439 (en_US)'\n\t\t\t\t\t],\n\t\t\t\t\t'message' => '\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u044b',\n\t\t\t\t\t'page_title' => 'Configuration of GUI',\n\t\t\t\t\t'html_lang' => 'en',\n\t\t\t\t\t'defaultdb_lang' => 'en_US',\n\t\t\t\t\t'info' => self::INFO,\n\t\t\t\t\t'login_info' => [\n\t\t\t\t\t\t\t'name' => 'Username',\n\t\t\t\t\t\t\t'password' => 'Password'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function definition(): array\n {\n return [\n 'label' => $this->faker->word(),\n ];\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public static function isUnary(string $operator): bool\n {\n return in_array(\n $operator,\n [\n self::EQ,\n self::GT,\n self::GTE,\n self::LT,\n self::LTE,\n self::LIKE,\n self::CONTAINS,\n ],\n true\n );\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function message()\n {\n return $this->belongsTo(Message::class);\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "protected function setUp(): void\n {\n self::bootKernel();\n $this->entityManager = self::getContainer()->get('doctrine');\n $this->csrfTokenManager = self::getContainer()->get(CsrfTokenManagerInterface::class);\n $this->security = self::getContainer()->get(Security::class);\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public static function infolist(Infolist $infolist): Infolist\n {\n return $infolist\n ->schema([\n TextEntry::make('user.name'),\n TextEntry::make('sent_at')\n ->label('Sent')\n ->dateTime(),\n TextEntry::make('ai_assistant_name')\n ->label('Assistant')\n ->default('N/A'),\n TextEntry::make('feature')\n ->default('N/A'),\n TextEntry::make('message')\n ->prose()\n ->columnSpanFull(),\n CodeEntry::make('metadata')\n ->columnSpanFull(),\n CodeEntry::make('request')\n ->columnSpanFull(),\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function testGetNewIdForDomainAndCountryId(): void\n {\n $transform = new CountryDataModifierVersion20190121094400($this->data);\n\n $this->assertEquals(2, $transform->getNewId(4));\n $this->assertEquals(2, $transform->getNewId(2));\n $this->assertEquals(1, $transform->getNewId(3));\n $this->assertEquals(1, $transform->getNewId(1));\n $this->assertEquals(5, $transform->getNewId(5));\n $this->assertEquals(6, $transform->getNewId(6));\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function accept(Criterion $criterion);", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setValue(array $parameters): void\n {\n $this->setSpecificFieldValue('url', $parameters['url']);\n $this->setSpecificFieldValue('text', $parameters['text']);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function loadSettingById(int $id): ?array\n {\n $query = $this->connection->createQueryBuilder();\n $query\n ->select([\n $this->connection->quoteIdentifier('group'),\n 'identifier',\n 'value',\n ])\n ->from(self::SETTING_TABLE)\n ->where(\n $query->expr()->eq(\n 'id',\n $query->createPositionalParameter($id, ParameterType::INTEGER)\n )\n );\n\n $statement = $query->execute();\n $result = $statement->fetchAssociative();\n\n if (false === $result) {\n return null;\n }\n\n return $result;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function getName(): string\n {\n return 'Formatted';\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function testInvalidProductProvided(): void\n {\n $unknownUuid = '6c42d01c-b597-4afa-b58f-f792ff00b783';\n $response = $this->getResponseContentForGql(__DIR__ . '/../_graphql/mutation/AddToCartMutation.graphql', [\n 'productUuid' => $unknownUuid,\n 'quantity' => 10,\n ]);\n\n self::assertArrayHasKey('errors', $response);\n\n self::assertEquals(\n sprintf('Product with UUID \"%s\" is not available', $unknownUuid),\n $response['errors'][0]['message'],\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function isOptimizedAdminLoading(): bool;", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function view(Authenticatable $authenticatable, KnowledgeBaseCategory $knowledgeBaseCategory): Response\n {\n return $authenticatable->canOrElse(\n abilities: [\"knowledge_base_category.{$knowledgeBaseCategory->id}.view\"],\n denyResponse: 'You do not have permissions to view this knowledge base category.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getOrder(): int\n {\n return 4;\n }", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function blogCategoriesQuery(): array\n {\n return $this->blogCategoryFacade->getAllVisibleChildrenByBlogCategoryAndDomainId(\n $this->blogCategoryFacade->getRootBlogCategory(),\n $this->domain->getId(),\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(\n protected readonly ModuleList $moduleList,\n protected readonly ModuleFacade $moduleFacade,\n protected readonly PricingSetting $pricingSetting,\n protected readonly DelayedPricingSetting $delayedPricingSetting,\n protected readonly Localization $localization,\n protected readonly LocalizedRouterFactory $localizedRouterFactory,\n protected readonly MailSettingFacade $mailSettingFacade,\n protected readonly MailerSettingProvider $mailerSettingProvider,\n protected readonly AdminDomainTabsFacade $adminDomainTabsFacade,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('hours', function (Blueprint $table) {\n $table->increments('id');\n $table->datetime('opening_time')->nullable();\n $table->datetime('closing_time')->nullable();\n $table->integer('type');\n $table->integer('day_of_week');\n $table->softDeletes();\n $table->timestamps();\n });\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function createCacheResolver()\n {\n $imageHost = $this->configResolver->hasParameter('image_host') ?\n $this->configResolver->getParameter('image_host') :\n '';\n\n if ($imageHost === '') {\n return $this->resolver;\n }\n\n if ($imageHost === '/') {\n $this->resolverDecoratorClass = $this->relativeResolverClass;\n } else {\n $this->resolverDecoratorClass = $this->proxyResolverClass;\n }\n\n return new $this->resolverDecoratorClass($this->resolver, [$imageHost]);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function isExpanded($expanded = true) {\n\t\t$filter = $this->getFilterType();\n\n\t\treturn $this->query('id',\n\t\t\t\t$filter['selected_tab']->getAttribute($filter['attribute']))->one()->isDisplayed($expanded);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function overwrite($text) {\n\t\treturn $this->clear()->type($text);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function __construct(string $action, string $back_url) {\n\t\tparent::__construct([\n\t\t\t(new CSubmit('export', _('Export')))\n\t\t\t\t->removeAttribute('id')\n\t\t\t\t->removeAttribute('name')\n\t\t\t\t->removeAttribute('value')\n\t\t\t\t->addClass(ZBX_STYLE_BTN_ALT)\n\t\t\t\t->onClick('var $_form = jQuery(this).closest(\"form\");'.\n\t\t\t\t\t// Save the original form action.\n\t\t\t\t\t'if (!$_form.data(\"action\")) {'.\n\t\t\t\t\t\t'$_form.data(\"action\", $_form.attr(\"action\"));'.\n\t\t\t\t\t'}'.\n\t\t\t\t\t'$_form.attr(\"action\", '.json_encode(\n\t\t\t\t\t\t(new CUrl('zabbix.php'))\n\t\t\t\t\t\t\t->setArgument('action', $action)\n\t\t\t\t\t\t\t->setArgument('format', CExportWriterFactory::YAML)\n\t\t\t\t\t\t\t->setArgument('backurl', $back_url)\n\t\t\t\t\t\t\t->getUrl()\n\t\t\t\t\t).');'\n\t\t\t\t),\n\t\t\t(new CButton('export', ZWSPACE()))\n\t\t\t\t->addClass(ZBX_STYLE_BTN_ALT)\n\t\t\t\t->addClass(ZBX_STYLE_BTN_TOGGLE_CHEVRON)\n\t\t\t\t->setMenuPopup([\n\t\t\t\t\t'type' => 'dropdown',\n\t\t\t\t\t'data' => [\n\t\t\t\t\t\t'submit_form' => true,\n\t\t\t\t\t\t'items' => [\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'label' => _('YAML'),\n\t\t\t\t\t\t\t\t'url' => (new CUrl('zabbix.php'))\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('action', $action)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('format', CExportWriterFactory::YAML)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('backurl', $back_url)\n\t\t\t\t\t\t\t\t\t\t\t->getUrl()\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'label' => _('XML'),\n\t\t\t\t\t\t\t\t'url' => (new CUrl('zabbix.php'))\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('action', $action)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('format', CExportWriterFactory::XML)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('backurl', $back_url)\n\t\t\t\t\t\t\t\t\t\t\t->getUrl()\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'label' => _('JSON'),\n\t\t\t\t\t\t\t\t'url' => (new CUrl('zabbix.php'))\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('action', $action)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('format', CExportWriterFactory::JSON)\n\t\t\t\t\t\t\t\t\t\t\t->setArgument('backurl', $back_url)\n\t\t\t\t\t\t\t\t\t\t\t->getUrl()\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t])\n\t\t]);\n\n\t\t$this->addClass(ZBX_STYLE_BTN_SPLIT);\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public static function parse(string | self $value): self\n {\n if ($value instanceof self) {\n return $value;\n }\n\n return self::from($value);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function store(StoreRequest $request): JsonResponse\n {\n $data = $request->getAll();\n $bill = $this->repository->store($data);\n $manager = $this->getManager();\n\n /** @var BillTransformer $transformer */\n $transformer = app(BillTransformer::class);\n $transformer->setParameters($this->parameters);\n\n $resource = new Item($bill, $transformer, 'bills');\n\n return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "#[Route(path: '/blog/article/delete-confirm/{id}', name: 'admin_blogarticle_deleteconfirm', requirements: ['id' => '\\d+'])]\n public function deleteConfirmAction(int $id): Response\n {\n $message = t('Do you really want to remove this blog article?');\n\n return $this->confirmDeleteResponseFactory->createDeleteResponse($message, 'admin_blogarticle_delete', $id);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function restore(Authenticatable $authenticatable, KnowledgeBaseCategory $knowledgeBaseCategory): Response\n {\n return $authenticatable->canOrElse(\n abilities: [\"knowledge_base_category.{$knowledgeBaseCategory->id}.restore\"],\n denyResponse: 'You do not have permissions to restore this knowledge base category.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getIndexColumn(): bool\n {\n return false;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function create(): ParameterData\n {\n $parameterData = $this->createInstance();\n $this->fillNew($parameterData);\n\n return $parameterData;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function checkWidgetForm($data, $update = false) {\n\t\t$this->page->login()->open('zabbix.php?action=dashboard.view&dashboardid='.self::$dashboardid);\n\t\t$dashboard = CDashboardElement::find()->one();\n\t\t$old_widget_count = $dashboard->getWidgets()->count();\n\n\t\t$form = ($update)\n\t\t\t? $dashboard->getWidget(self::$old_name)->edit()->asForm()\n\t\t\t: $dashboard->edit()->addWidget()->asForm();\n\n\t\tCOverlayDialogElement::find()->one()->waitUntilReady();\n\t\t$form->fill($data['fields']);\n\n\t\tif ($update && !CTestArrayHelper::get($data['fields'], 'Name')) {\n\t\t\t$form->fill(['Name' => '']);\n\t\t}\n\n\t\t$values = $form->getFields()->asValues();\n\t\t$form->submit();\n\t\t$this->page->waitUntilReady();\n\n\t\tif (CTestArrayHelper::get($data, 'expected', TEST_GOOD) === TEST_BAD) {\n\t\t\t$old_hash = CDBHelper::getHash('SELECT * FROM widget ORDER BY widgetid');\n\t\t\t$this->assertMessage($data['expected'], null, $data['error']);\n\t\t\t$this->assertEquals($old_hash, CDBHelper::getHash('SELECT * FROM widget ORDER BY widgetid'));\n\t\t}\n\t\telse {\n\t\t\tCOverlayDialogElement::ensureNotPresent();\n\n\t\t\t$header = CTestArrayHelper::get($data['fields'], 'Name')\n\t\t\t\t\t? $data['fields']['Name']\n\t\t\t\t\t: $data['fields']['Item']['context']['values'].': '.$data['fields']['Item']['values'];\n\n\t\t\t$dashboard->getWidget($header)->waitUntilReady();\n\n\t\t\t// Save Dashboard to ensure that widget is correctly saved.\n\t\t\t$dashboard->save();\n\t\t\t$this->assertMessage(TEST_GOOD, 'Dashboard updated');\n\n\t\t\t// Check widget count.\n\t\t\t$this->assertEquals($old_widget_count + ($update ? 0 : 1), $dashboard->getWidgets()->count());\n\n\t\t\t// Check new widget form fields and values in frontend.\n\t\t\t$saved_form = $dashboard->getWidget($header)->edit();\n\t\t\t$this->assertEquals($values, $saved_form->getFields()->asValues());\n\n\t\t\t// As form is quite complex, show_header field should be checked separately.\n\t\t\tif (array_key_exists('show_header', $data['fields'])) {\n\t\t\t\t$saved_form->checkValue(['id:show_header' => $data['fields']['show_header']]);\n\t\t\t}\n\n\t\t\t// Check that widget is saved in DB for correct dashboard and correct dashboard page.\n\t\t\t$this->assertEquals(1,\n\t\t\t\t\tCDBHelper::getCount('SELECT * FROM widget w'.\n\t\t\t\t\t\t' WHERE EXISTS ('.\n\t\t\t\t\t\t\t'SELECT NULL'.\n\t\t\t\t\t\t\t' FROM dashboard_page dp'.\n\t\t\t\t\t\t\t' WHERE w.dashboard_pageid=dp.dashboard_pageid'.\n\t\t\t\t\t\t\t\t' AND dp.dashboardid='.self::$dashboardid.\n\t\t\t\t\t\t\t\t' AND w.name ='.zbx_dbstr(CTestArrayHelper::get($data['fields'], 'Name', '')).')'\n\t\t\t));\n\n\t\t\t// Check that original widget was not left in DB.\n\t\t\tif ($update) {\n\t\t\t\t$this->assertEquals(0, CDBHelper::getCount('SELECT NULL FROM widget WHERE name='.zbx_dbstr(self::$old_name)));\n\t\t\t}\n\n\t\t\t// Close widget popup and check update interval.\n\t\t\t$saved_form->submit();\n\t\t\tCOverlayDialogElement::ensureNotPresent();\n\t\t\t$dashboard->save();\n\t\t\t$this->assertMessage(TEST_GOOD, 'Dashboard updated');\n\n\t\t\t// Check new widget update interval.\n\t\t\t$refresh = (CTestArrayHelper::get($data['fields'], 'Refresh interval') === 'Default (1 minute)')\n\t\t\t\t? '15 minutes'\n\t\t\t\t: (CTestArrayHelper::get($data['fields'], 'Refresh interval', '1 minute'));\n\t\t\t$this->assertEquals($refresh, CDashboardElement::find()->one()->getWidget($header)->getRefreshInterval());\n\n\t\t\t// Write new name to update widget for update scenario.\n\t\t\tif ($update) {\n\t\t\t\tself::$old_name = $header;\n\t\t\t}\n\t\t}\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "function (Blueprint $table) {\n $table->dropUnique('related_unique');\n $table->unique(\n ['subject_id', 'subject_type', 'related_id', 'related_type'],\n 'related_unique'\n );\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function testGetEntityManagerWillUseDefaultConnection(): void\n {\n $serviceLocator = $this->getServiceLocator();\n $serviceLocator\n ->method('has')\n ->with(self::DEFAULT_ENTITY_MANAGER)\n ->willReturn(true);\n $serviceLocator\n ->method('get')\n ->with(self::DEFAULT_ENTITY_MANAGER)\n ->willReturn($this->entityManager);\n\n $this->repositoryConfigurationProvider\n ->method('getRepositoryConfig')\n ->willReturn([\n 'storage' => [],\n ]);\n\n $entityManagerFactory = new EntityManagerFactory(\n $this->repositoryConfigurationProvider,\n $serviceLocator,\n self::DEFAULT_CONNECTION,\n self::ENTITY_MANAGERS\n );\n\n self::assertEquals($this->entityManager, $entityManagerFactory->getEntityManager());\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function steps(): HasMany\n {\n return $this->hasMany(FormStep::class);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "private function findCartOfCurrentCustomer(): ?Cart\n {\n /** @var \\App\\Model\\Customer\\User\\CustomerUser $customerUser */\n $customerUser = $this->currentCustomerUser->findCurrentCustomerUser();\n\n $customerUserIdentifier = $this->customerUserIdentifierFactory->getByCustomerUser($customerUser);\n\n return $this->cartFacade->findCartByCustomerUserIdentifier($customerUserIdentifier);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function apply(Request $request, ParamConverter $configuration)\n {\n if (!$request->get(self::PARAMETER_CONTENT_TYPE_GROUP_ID)) {\n return false;\n }\n\n $id = (int)$request->get(self::PARAMETER_CONTENT_TYPE_GROUP_ID);\n\n try {\n $group = $this->contentTypeService->loadContentTypeGroup($id);\n } catch (NotFoundException $e) {\n throw new NotFoundHttpException(\"Content type group $id not found.\");\n }\n\n $request->attributes->set($configuration->getName(), $group);\n\n return true;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function form(Form $form): Form\n {\n return (resolve(CreateInteraction::class))->form($form);\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function recurring()\n {\n return $this->state(function () {\n return [\n 'recurring' => 1,\n ];\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function saveProductVideosToProduct(Product $product, array $productVideoDataList): void\n {\n /** @var \\App\\Model\\ProductVideo\\ProductVideo[] $productVideos */\n $productVideos = $this->productVideoRepository->findByProductId($product->getId());\n\n $videoDataListToUpdate = array_filter($productVideoDataList, function (ProductVideoData $productVideoData) {\n return (bool)$productVideoData->id;\n });\n\n $videoDataListToCreate = array_filter($productVideoDataList, function (ProductVideoData $productVideoData) {\n return (bool)$productVideoData->id !== true;\n });\n\n $productVideosToRemove = [];\n\n foreach ($productVideos as $productVideo) {\n if (array_key_exists($productVideo->getId(), $videoDataListToUpdate)) {\n $productVideo->setVideoToken(\n str_replace(self::YOUTUBE_LINKS_ARRAY, '', ($videoDataListToUpdate[$productVideo->getId()])->videoToken),\n );\n $this->cleanProductVideoTranslationsForProductVideo($productVideo);\n $this->persistVideoTranslations($videoDataListToUpdate[$productVideo->getId()], $productVideo);\n } else {\n $productVideosToRemove[] = $productVideo;\n }\n }\n\n foreach ($productVideosToRemove as $productVideoToRemove) {\n $this->cleanProductVideoTranslationsForProductVideo($productVideoToRemove);\n $this->productVideoRepository->em->remove($productVideoToRemove);\n }\n\n foreach ($videoDataListToCreate as $videoDataToCreate) {\n $productVideoEntity = new ProductVideo();\n $productVideoEntity->setProduct($product);\n $productVideoEntity->setVideoToken(str_replace(self::YOUTUBE_LINKS_ARRAY, '', $videoDataToCreate->videoToken));\n $this->productVideoRepository->em->persist($productVideoEntity);\n\n $this->persistVideoTranslations($videoDataToCreate, $productVideoEntity);\n }\n $this->productVideoRepository->em->flush();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct($points) {\n\t\tparent::__construct('polygon');\n\n\t\t$p = '';\n\n\t\tforeach ($points as $point) {\n\t\t\t$p .= ' '.$point[0].','.$point[1];\n\t\t}\n\n\t\t$this->setAttribute('points', ltrim($p));\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function validate($value, Constraint $constraint)\n {\n if (!$value instanceof URLUpdateData || $value->url === null) {\n return;\n }\n\n try {\n $url = $this->urlService->loadByUrl($value->url);\n\n if ($url->id === $value->id) {\n return;\n }\n\n $this->context->buildViolation($constraint->message)\n ->atPath('url')\n ->setParameter('%url%', $value->url)\n ->addViolation();\n } catch (NotFoundException $e) {\n // Do nothing\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function getPriority()\n {\n // we must be ran before auto-escaping\n return -10;\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function testRefreshUser(): void\n {\n $userId = 123;\n $apiUser = $this->buildUserValueObjectStub($userId);\n $user = $this->createUserWrapperMockFromAPIUser($apiUser, $userId);\n\n $this->permissionResolver\n ->expects(self::once())\n ->method('setCurrentUserReference')\n ->with(new UserReference($apiUser->getUserId()));\n\n self::assertSame($user, $this->userProvider->refreshUser($user));\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n $firstDomainTimeZone = $this->getDomain()->getDomainConfigById(Domain::FIRST_DOMAIN_ID)->getDateTimeZone();\n $utcTimeZone = new DateTimeZone('UTC');\n $dateTime = new DateTime('now', $utcTimeZone);\n $timeOffsetInHours = timezone_offset_get($firstDomainTimeZone, $dateTime) / 3600;\n\n $this->sql(\n sprintf('UPDATE blog_articles SET publish_date = publish_date - INTERVAL \\'%d hour\\';', $timeOffsetInHours),\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function hasElement(AbstractExpression $key)\n {\n foreach ($this->getKeyValuePairs() as $pair) {\n // we compare the string representation of the keys\n // to avoid comparing the line numbers which are not relevant here.\n if ((string) $key === (string) $pair['key']) {\n return true;\n }\n }\n\n return false;\n }", "smellKey": "0", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function validate(APILimitationValue $limitationValue)\n {\n $validationErrors = [];\n if (empty($limitationValue->limitationValues)) {\n $validationErrors[] = new ValidationError(\n \"\\$limitationValue->limitationValues => '%value%' can not be empty\",\n null,\n [\n 'value' => $limitationValue->limitationValues,\n ]\n );\n }\n\n return $validationErrors;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function lightboxEndDate()\n {\n if ($this->entity->lightbox_end_date) {\n return $this->entity->lightbox_end_date->format('M j, Y');\n }\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function setLocations(?array $locations): void\n {\n $this->locations = $locations;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(\n protected readonly ImageFacade $imageFacade,\n ) {\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getName(): ?string\n {\n return $this->name;\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function loadInternal(array $config, ContainerBuilder $container): void\n {\n $loader = new YamlFileLoader(\n $container,\n new FileLocator(__DIR__ . '/../../config')\n );\n\n $loader->load('services.yaml');\n $loader->load('maintenance.yaml');\n $loader->load('event_listeners.yaml');\n $loader->load('redirect_services.yaml');\n $loader->load('sitemap_services.yaml');\n $this->configureSitemaps($container, $config['sitemaps']);\n $container->setParameter('pimcore_seo.sitemaps', $config['sitemaps']);\n $container->setParameter('pimcore_seo.redirects', $config['redirects']);\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function configureOptions(OptionsResolver $resolver): void\n {\n /*\n * Data class is set to extended OrderItemData, so when a new item is created in collection form type, a proper data object will be created\n */\n $resolver->setDefault('data_class', OrderItemData::class);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function provideFieldTypeIdentifier(): string\n {\n return 'ezselection';\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function testOnSiteAccessMatchNoConfiguredSessionName(): void\n {\n $request = new Request();\n $request->setSession(new Session(new MockArraySessionStorage('some_default_name')));\n\n $configuredSessionStorageOptions = ['cookie_path' => '/bar'];\n $sessionName = 'some_default_name';\n $sessionOptions = $configuredSessionStorageOptions + ['name' => \"IBX_SESSION_ID_$sessionName\"];\n\n $this->sessionStorage\n ->expects(self::once())\n ->method('setOptions')\n ->with($sessionOptions);\n $this->configResolver\n ->expects(self::once())\n ->method('getParameter')\n ->with('session')\n ->will(self::returnValue($configuredSessionStorageOptions));\n\n $listener = new SessionSetDynamicNameListener($this->configResolver, $this->sessionStorageFactory);\n $listener->onSiteAccessMatch(new PostSiteAccessMatchEvent(new SiteAccess('test'), $request, HttpKernelInterface::MAIN_REQUEST));\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getFieldMapping() {\n\t\treturn is_array($this->mapping) ? $this->mapping : [];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function up(): void\n {\n Schema::create('device_groups', function (Blueprint $table) {\n $table->increments('id');\n $table->string('name')->default('')->unique();\n $table->string('desc')->default('');\n $table->text('pattern')->nullable();\n $table->text('params')->nullable();\n });\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "private function addProductToCustomerCart(Product $product, int $productQuantity): void\n {\n $this->getResponseContentForGql(__DIR__ . '/../_graphql/mutation/AddToCartMutation.graphql', [\n 'productUuid' => $product->getUuid(),\n 'quantity' => $productQuantity,\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function type(): string\n {\n return 'educatable_email';\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function getDefaultNamespace(): string;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function configureOptions(OptionsResolver $resolver): void\n {\n $resolver\n ->setDefaults([\n 'choice_loader' => $this->languageChoiceLoader,\n 'choice_label' => 'name',\n 'choice_name' => 'languageCode',\n 'choice_value' => 'languageCode',\n ]);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n URLServiceInterface $urlService,\n URLHandlerRegistryInterface $handlerRegistry\n ) {\n $this->urlService = $urlService;\n $this->handlerRegistry = $handlerRegistry;\n $this->logger = new NullLogger();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function isWriteable(): bool\n {\n return $this->locationAwareConfigRepository->isWriteable($this->id, $this->dataSource);\n }", "smellKey": "0", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function prepareData() {\n\t\t// Create host \"testhost\".\n\t\t$response = $this->call('host.create', [\n\t\t\t'host' => self::HOST_NAME,\n\t\t\t'interfaces' => [\n\t\t\t\t'type' => 1,\n\t\t\t\t'main' => 1,\n\t\t\t\t'useip' => 1,\n\t\t\t\t'ip' => '127.0.0.1',\n\t\t\t\t'dns' => '',\n\t\t\t\t'port' => $this->getConfigurationValue(self::COMPONENT_AGENT, 'ListenPort')\n\t\t\t],\n\t\t\t'groups' => ['groupid' => 4]\n\t\t]);\n\n\t\t$this->assertArrayHasKey('hostids', $response['result']);\n\t\t$this->assertArrayHasKey(0, $response['result']['hostids']);\n\t\tself::$hostid = $response['result']['hostids'][0];\n\n\t\t// Get host interface ids.\n\t\t$response = $this->call('host.get', [\n\t\t\t'output' => ['host'],\n\t\t\t'hostids' => [self::$hostid],\n\t\t\t'selectInterfaces' => ['interfaceid']\n\t\t]);\n\n\t\t$this->assertArrayHasKey(0, $response['result']);\n\t\t$this->assertArrayHasKey('interfaces', $response['result'][0]);\n\t\t$this->assertArrayHasKey(0, $response['result'][0]['interfaces']);\n\n\t\t// Create trapper item\n\t\t$response = $this->call('item.create', [\n\t\t\t'hostid' => self::$hostid,\n\t\t\t'name' => self::TRAPPER_ITEM_NAME,\n\t\t\t'key_' => self::TRAPPER_ITEM_NAME,\n\t\t\t'type' => ITEM_TYPE_TRAPPER,\n\t\t\t'value_type' => ITEM_VALUE_TYPE_UINT64\n\t\t]);\n\t\t$this->assertArrayHasKey('itemids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['itemids']));\n\n\t\t// Create trigger\n\t\t$response = $this->call('trigger.create', [\n\t\t\t'description' => 'Trapper received 1',\n\t\t\t'expression' => 'last(/'.self::HOST_NAME.'/'.self::TRAPPER_ITEM_NAME.')>0'\n\t\t]);\n\t\t$this->assertArrayHasKey('triggerids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['triggerids']));\n\t\tself::$triggerid = $response['result']['triggerids'][0];\n\n\t\t// Create trigger action\n\t\t$response = $this->call('action.create', [\n\t\t\t'esc_period' => '1h',\n\t\t\t'eventsource' => EVENT_SOURCE_TRIGGERS,\n\t\t\t'status' => 0,\n\t\t\t'filter' => [\n\t\t\t\t'conditions' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'conditiontype' => CONDITION_TYPE_TRIGGER,\n\t\t\t\t\t\t'operator' => CONDITION_OPERATOR_EQUAL,\n\t\t\t\t\t\t'value' => self::$triggerid\n\t\t\t\t\t]\n\t\t\t\t],\n\t\t\t\t'evaltype' => CONDITION_EVAL_TYPE_AND_OR\n\t\t\t],\n\t\t\t'name' => 'Trapper received 1 (problem) clone',\n\t\t\t'operations' => [\n\t\t\t\t[\n\t\t\t\t\t'esc_period' => 0,\n\t\t\t\t\t'esc_step_from' => 1,\n\t\t\t\t\t'esc_step_to' => 1,\n\t\t\t\t\t'operationtype' => OPERATION_TYPE_MESSAGE,\n\t\t\t\t\t'opmessage' => ['default_msg' => 1,\n\t\t\t\t\t\t\t\t\t'mediatypeid' => 0\n\t\t\t\t\t],\n\t\t\t\t\t'opmessage_grp' => [\n\t\t\t\t\t\t['usrgrpid' => 7]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t'pause_suppressed' => 0,\n\t\t\t'recovery_operations' => [\n\t\t\t\t[\n\t\t\t\t\t'operationtype' => OPERATION_TYPE_MESSAGE,\n\t\t\t\t\t'opmessage' => [\n\t\t\t\t\t\t'default_msg' => 1,\n\t\t\t\t\t\t'mediatypeid' => 0\n\t\t\t\t\t],\n\t\t\t\t\t'opmessage_grp' => [\n\t\t\t\t\t\t['usrgrpid' => 7]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\t\t$this->assertArrayHasKey('actionids', $response['result']);\n\t\t$this->assertEquals(1, count($response['result']['actionids']));\n\t\tself::$trigger_actionid = $response['result']['actionids'][0];\n\n\t\treturn true;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function scopeHasAccess($query, User $user)\n {\n if ($user->hasGlobalRead()) {\n return $query;\n }\n\n // maybe filtered in future\n return $query;\n }", "smellKey": "0", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "protected static function getFacadeAccessor(): string\n {\n return 'messages';\n }", "smellKey": "0", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "protected function fillNew(ParameterData $parameterData): void\n {\n foreach ($this->domain->getAllLocales() as $locale) {\n $parameterData->name[$locale] = null;\n }\n\n $parameterData->orderingPriority = 0;\n $parameterData->parameterType = Parameter::PARAMETER_TYPE_COMMON;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct(\n $repositoryClass,\n array $policyMap,\n LanguageResolver $languageResolver\n ) {\n $this->repositoryClass = $repositoryClass;\n $this->policyMap = $policyMap;\n $this->languageResolver = $languageResolver;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function addFieldTypeSemanticConfig(NodeBuilder $nodeBuilder): void\n {\n $nodeBuilder\n ->scalarNode('content_type_identifier')\n ->isRequired()\n ->cannotBeEmpty()\n ->end()\n ->scalarNode('content_field_identifier')\n ->isRequired()\n ->cannotBeEmpty()\n ->end()\n ->scalarNode('name_field_identifier')\n ->isRequired()\n ->cannotBeEmpty()\n ->end()\n ->scalarNode('parent_location_id')\n ->isRequired()\n ->cannotBeEmpty()\n ->end();\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function testDefault(): void\n {\n Current::$database = 'test_db';\n Current::$table = 'test_table';\n\n $dbiDummy = $this->createDbiDummy();\n $dbiDummy->addSelectDb('test_db');\n\n $dbi = $this->createDatabaseInterface($dbiDummy);\n DatabaseInterface::$instance = $dbi;\n $response = new ResponseRenderer();\n $template = new Template();\n $request = self::createStub(ServerRequest::class);\n $request->method('getParsedBodyParam')->willReturnMap([['tables', null, ['test_table']]]);\n\n $controller = new FirstStepController(\n $response,\n new Normalization($dbi, new Relation($dbi), new Transformations(), $template),\n );\n $controller($request);\n\n // phpcs:disable Generic.Files.LineLength.TooLong\n self::assertSame([\n 'legendText' => 'Step 3.1 Find transitive dependencies',\n 'headText' => 'Please answer the following question(s) carefully to obtain a correct normalization.',\n 'subText' => 'For each column below, please select the minimal set of columns among given set whose values combined together are sufficient to determine the value of the column.
Note: A column may have no transitive dependency, in that case you don\\'t have to select any.',\n 'extra' => '\\'name\\' depends on:
namedatetimefield


\\'datetimefield\\' depends on:
namedatetimefield


',\n ], $response->getJSONResult());\n // phpcs:enable\n }", "smellKey": "0", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function testOnSiteAccessMatchSubRequest(): void\n {\n $this->sessionStorage\n ->expects(self::never())\n ->method('setOptions');\n $listener = new SessionSetDynamicNameListener($this->configResolver, $this->sessionStorageFactory);\n $listener->onSiteAccessMatch(new PostSiteAccessMatchEvent(new SiteAccess('test'), new Request(), HttpKernelInterface::SUB_REQUEST));\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getControllerReference();", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function deleteLanguage(int $id): void\n {\n try {\n $this->innerGateway->deleteLanguage($id);\n } catch (DBALException | PDOException $e) {\n throw DatabaseException::wrap($e);\n }\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setMapping(int $locationId, int $contentId): void\n {\n $this->map[$locationId] = $contentId;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function getDate(string $field): ?Carbon\n {\n $value = $this->query($field);\n if (is_array($value)) {\n return null;\n }\n $value = (string)$value;\n\n return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function getFunctions()\n {\n $functions = parent::getFunctions();\n $functions[] = new TwigFunction(\n 'getOrderingNameByOrderingId',\n $this->getOrderingNameByOrderingId(...),\n );\n\n return $functions;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function visitCriteria(\n FilteringQueryBuilder $queryBuilder,\n FilteringCriterion $criterion\n ): string;", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function createGroupMemberships(): void\n {\n $users = User::get();\n\n /** @var User $user */\n foreach ($users as $user) {\n self::createGroupMembership($user);\n }\n }", "smellKey": "0", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function up(Schema $schema): void\n {\n $this->sql('\n CREATE INDEX IDX_5474CBC416EFC72D81257D5D8CDE5729 ON uploaded_files_relations (entity_name, entity_id, type)');\n $this->sql('\n CREATE INDEX IDX_5474CBC416EFC72D81257D5D8CDE5729276973A0 ON uploaded_files_relations (\n entity_name, entity_id, type, uploaded_file_id\n )');\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function create(Authenticatable $authenticatable): Response\n {\n return $authenticatable->canOrElse(\n abilities: 'prompt.create',\n denyResponse: 'You do not have permission to create prompts.'\n );\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function productsByCategoryQuery(Argument $argument, Category $category)\n {\n $search = $argument['search'] ?? '';\n\n $this->setDefaultFirstOffsetIfNecessary($argument);\n\n $productFilterData = $this->productFilterFacade->getValidatedProductFilterDataForCategory(\n $argument,\n $category,\n );\n\n return $this->productConnectionFactory->createConnectionForCategory(\n $category,\n function ($offset, $limit) use ($argument, $category, $productFilterData, $search) {\n return $this->productFacade->getFilteredProductsByCategory(\n $category,\n $limit,\n $offset,\n $this->productOrderingModeProvider->getOrderingModeFromArgument($argument),\n $productFilterData,\n $search,\n );\n },\n $this->productFacade->getFilteredProductsByCategoryCount($category, $productFilterData, $search),\n $argument,\n $productFilterData,\n );\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "protected function setUp(): void\n {\n parent::setUp();\n $this->matcher = new DepthMatcher();\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getSlice($offset, $length)\n {\n return $this->searchResult->searchHits;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function transformTitles()\n {\n return [];\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function files(): HasMany\n {\n return $this->hasMany(AiAssistantFile::class, 'assistant_id');\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "function (Blueprint $table) {\n $table->dropColumn('model_caption_title');\n }", "smellKey": "0", "smellId": null, "repo": "art-institute-of-chicago_artic", "language": "php"} {"function": "public function getDescription(): string\n\t{\n\t\treturn 'Maak de nieuwe groep en groep_lid tabellen.';\n\t}", "smellKey": "0", "smellId": null, "repo": "csrdelft_csrdelft", "language": "php"} {"function": "public function testOnSiteAccessMatchNonNativeSessionStorage(): void\n {\n $this->configResolver\n ->expects(self::never())\n ->method('getParameter');\n $listener = new SessionSetDynamicNameListener(\n $this->configResolver,\n $this->createMock(SessionStorageFactoryInterface::class)\n );\n $listener->onSiteAccessMatch(new PostSiteAccessMatchEvent(new SiteAccess('test'), new Request(), HttpKernelInterface::SUB_REQUEST));\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setName($name): void\n {\n $this->name = $name;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function getContentType(): string\n\t{\n\t\treturn $this->contentType ?: 'application/fhir+json';\n\t}", "smellKey": "0", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public static function prepareData() {\n\t\t// Create host for widget header and data tests.\n\t\tCDataHelper::createHosts([\n\t\t\t[\n\t\t\t\t'host' => 'Simple host with item for plain text widget',\n\t\t\t\t'interfaces' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'type' => INTERFACE_TYPE_AGENT,\n\t\t\t\t\t\t'main' => INTERFACE_PRIMARY,\n\t\t\t\t\t\t'useip' => INTERFACE_USE_IP,\n\t\t\t\t\t\t'ip' => '127.0.9.1',\n\t\t\t\t\t\t'dns' => '',\n\t\t\t\t\t\t'port' => '10077'\n\t\t\t\t\t]\n\t\t\t\t],\n\t\t\t\t'groups' => [\n\t\t\t\t\t'groupid' => '4'\n\t\t\t\t],\n\t\t\t\t'items' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'name' => 'Test plain text',\n\t\t\t\t\t\t'key_' => 'plain_text',\n\t\t\t\t\t\t'type' => ITEM_TYPE_ZABBIX,\n\t\t\t\t\t\t'value_type' => ITEM_VALUE_TYPE_FLOAT,\n\t\t\t\t\t\t'delay' => '30'\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\t\t$itemids = CDataHelper::getIds('name');\n\n\t\t$response = CDataHelper::call('dashboard.create', [\n\t\t\t[\n\t\t\t\t'name' => 'Dashboard for Plain Text Widget test',\n\t\t\t\t'pages' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'name' => 'Page with default widgets',\n\t\t\t\t\t\t'widgets' => [\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'plaintext',\n\t\t\t\t\t\t\t\t'name' => self::DEFAULT_WIDGET,\n\t\t\t\t\t\t\t\t'x' => 0,\n\t\t\t\t\t\t\t\t'y' => 0,\n\t\t\t\t\t\t\t\t'width' => 12,\n\t\t\t\t\t\t\t\t'height' => 5,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42227' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Host name of Zabbix agent running'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_INT32,\n\t\t\t\t\t\t\t\t\t\t'name' => 'dynamic',\n\t\t\t\t\t\t\t\t\t\t'value' => '1'\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'plaintext',\n\t\t\t\t\t\t\t\t'name' => self::DELETE_WIDGET,\n\t\t\t\t\t\t\t\t'x' => 0,\n\t\t\t\t\t\t\t\t'y' => 5,\n\t\t\t\t\t\t\t\t'width' => 12,\n\t\t\t\t\t\t\t\t'height' => 5,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42227' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Host name of Zabbix agent running'.\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name' => 'Dashboard for Plain text Widget create/update test',\n\t\t\t\t'pages' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'name' => 'Page with created/updated widgets',\n\t\t\t\t\t\t'widgets' => [\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'plaintext',\n\t\t\t\t\t\t\t\t'name' => self::$update_widget,\n\t\t\t\t\t\t\t\t'x' => 0,\n\t\t\t\t\t\t\t\t'y' => 0,\n\t\t\t\t\t\t\t\t'width' => 12,\n\t\t\t\t\t\t\t\t'height' => 5,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42243' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Available memory'.\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name' => 'Dashboard for checking data',\n\t\t\t\t'pages' => [\n\t\t\t\t\t[\n\t\t\t\t\t\t'name' => 'Page with Plain text widget',\n\t\t\t\t\t\t'widgets' => [\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'type' => 'plaintext',\n\t\t\t\t\t\t\t\t'name' => self::DATA_WIDET,\n\t\t\t\t\t\t\t\t'x' => 0,\n\t\t\t\t\t\t\t\t'y' => 0,\n\t\t\t\t\t\t\t\t'width' => 12,\n\t\t\t\t\t\t\t\t'height' => 6,\n\t\t\t\t\t\t\t\t'fields' => [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42227' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Host name of Zabbix agent running'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42243' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Available memory'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '42244' // item name in widget '\u0417\u0410\u0411\u0411\u0418\u041a\u0421 \u0421\u0435\u0440\u0432\u0435\u0440: Linux: Available memory in %'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => $itemids['Test plain text'] // item name in widget 'Simple host with item for plain text widget: Test plain text'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_ITEM,\n\t\t\t\t\t\t\t\t\t\t'name' => 'itemids',\n\t\t\t\t\t\t\t\t\t\t'value' => '99142' // item name in widget 'Test item host: Master item'.\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t'type' => ZBX_WIDGET_FIELD_TYPE_INT32,\n\t\t\t\t\t\t\t\t\t\t'name' => 'dynamic',\n\t\t\t\t\t\t\t\t\t\t'value' => '1'\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t]\n\t\t\t]\n\t\t]);\n\t\tself::$dashboardid = $response['dashboardids'][0];\n\t\tself::$dashboard_create = $response['dashboardids'][1];\n\t\tself::$dashboard_data = $response['dashboardids'][2];\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "abstract public function countAll(): int;", "smellKey": "0", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setSeoTitle($seoTitle)\n {\n $this->seoTitle = $seoTitle;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function isUpvoted(): bool\n {\n return $this->isUpvoted ??= $this->upvotes()->whereBelongsTo(auth()->user())->exists();\n }", "smellKey": "0", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function checkValue($expected, $raise_exception = true) {\n\t\t$rows = $this->getRows();\n\n\t\tif ($rows->count() !== count($expected)) {\n\t\t\tif ($raise_exception) {\n\t\t\t\tthrow new Exception('Row count \"'.$rows->count().'\" doesn\\'t match expected row count \"'.\n\t\t\t\t\t\tcount($expected).'\" of multifield element.'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\t$headers = $this->getHeadersText();\n\t\tforeach ($rows as $id => $row) {\n\t\t\tif (!array_key_exists($id, $expected)) {\n\t\t\t\tif ($raise_exception) {\n\t\t\t\t\tthrow new Exception('Row with index \"'.$id.'\" is not expected in multifield element.');\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t$controls = $this->getRowControls($row, $headers);\n\t\t\tforeach ($expected[$id] as $name => $value) {\n\t\t\t\t$field = (array_key_exists($name, $this->aliases)) ? $this->aliases[$name] : $name;\n\n\t\t\t\tif (!array_key_exists($field, $controls)) {\n\t\t\t\t\tif ($raise_exception) {\n\t\t\t\t\t\tthrow new Exception('Expected field \"'.$name.'\" is not present in multifield element row.');\n\t\t\t\t\t}\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tif (!$controls[$field]->checkValue($value, $raise_exception)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception $exception) {\n\t\t\t\t\tif ($raise_exception) {\n\t\t\t\t\t\tCExceptionHelper::setMessage($exception, 'Multifield element value for field \"'.$name.\n\t\t\t\t\t\t\t\t'['.$id.']\" is invalid: '.$exception->getMessage()\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow $exception;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function createContentTypeGroupProxyList(\n array $contentTypeGroupIds,\n array $prioritizedLanguages = Language::ALL\n ): array {\n $groups = [];\n foreach ($contentTypeGroupIds as $contentTypeGroupId) {\n $groups[] = $this->createContentTypeGroupProxy($contentTypeGroupId, $prioritizedLanguages);\n }\n\n return $groups;\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getOrderingNameByOrderingId(?string $orderingId): string\n {\n if ($orderingId === null) {\n return '';\n }\n\n $supportedOrderingModesNamesIndexedById = $this->productListOrderingModeForListFacade\n ->getProductListOrderingConfig()\n ->getSupportedOrderingModesNamesIndexedById();\n\n return $supportedOrderingModesNamesIndexedById[$orderingId] ?? t('Unsupported order') . ' ' . $orderingId;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function setSpecificFieldValue(string $fieldName, string $value): void\n {\n $fieldSelector = CSSLocatorBuilder::base($this->parentLocator)\n ->withDescendant($this->getLocator($fieldName))\n ->build();\n\n $this->getHTMLPage()->find($fieldSelector)->setValue($value);\n }", "smellKey": "0", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function testGetCodes(): void\n {\n $transform = new CountryDataModifierVersion20190121094400($this->data);\n\n $this->assertEquals(['SK', 'CZ', 'MA', 'UB'], $transform->getAllCodes());\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($option) {\n\t\t\t\t\t\treturn (is_array($option) && count($option) === 2);\n\t\t\t\t\t}", "smellKey": "0", "smellId": null, "repo": "CHERTS_zabbix_dbmon", "language": "php"} {"function": "public function getViewType();", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function getArgs(?ArrayObject $context): ArrayObject\n {\n if ($context === null) {\n return new ArrayObject();\n }\n\n return isset($context['args']) ? new ArrayObject($context['args']) : new ArrayObject();\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function fromJson(array $data): self\n\t{\n\t\treturn new self(\n\t\t\t$data['inNomeEscola'] ?? null,\n\t\t\t$data['inBairro'] ?? null,\n\t\t\t$data['inEndereco'] ?? null,\n\t\t\t$data['inMunicipio'] ?? null\n\t\t);\n\t}", "smellKey": "0", "smellId": null, "repo": "ipti_br", "language": "php"} {"function": "public function __construct($value)\n {\n parent::__construct(null, null, $value);\n }", "smellKey": "0", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getName(): string\n {\n return self::NAME;\n }", "smellKey": "0", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function listSuggestions($id_bibli=0, $statut='-1', $num_categ='-1', $mask, $debut=0, $nb_per_page=0, $aq=0, $order='',$location=0) {\n\n\t\tif ($statut == '-1') { \n\t\t\t$filtre1 = '1';\n\t\t} elseif ($statut == $mask) {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = '\".$mask.\"' \";\n\t\t} else {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = 0 and (statut & \".$statut.\") = '\".$statut.\"' \";\n\t\t}\n\t\t\t\n\t\tif ($num_categ == '-1') {\n\t\t\t$filtre2 = '1';\n\t\t} else {\n\t\t\t$filtre2 = \"num_categ = '\".$num_categ.\"' \";\n\t\t}\n\n\t\tif (!$id_bibli) $filtre3 = '1';\n\t\t\telse $filtre3.= \"num_entite = '\".$id_bibli.\"' \";\n\n\t\tif ($location == 0) {\n\t\t\t$filtre4 = '1';\n\t\t} else {\n\t\t\t$filtre4 = \"sugg_location = '\".$location.\"' \";\n\t\t}\t\t\n\t\tif(!$aq) {\n\t\t\t\n\t\t\t$q = \"select * from suggestions where 1 \";\n\t\t\t$q.= \"and \".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4 .\" \";\n\t\t\tif(!$order) $q.=\"order by statut, date_creation desc \";\n\t\t\t\telse $q.= \"order by\".$order.\" \";\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t$members=$aq->get_query_members(\"suggestions\",\"concat(titre,' ',editeur,' ',auteur,' ',commentaires)\",\"index_suggestion\",\"id_suggestion\", $filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4);\n\t\t\tif (!$order) {\n\t\t\t\t$q = \"select *, \".$members[\"select\"].\" as pert from suggestions where \".$members[\"where\"].\" and \".$members[\"restrict\"].\" order by pert desc \";\t\n\t\t\t} else {\n\t\t\t\t$q = \"select *, \".$members[\"select\"].\" as pert from suggestions where \".$members[\"where\"].\" and \".$members[\"restrict\"].\" order by \".$order.\", pert desc \";\n\t\t\t}\n\t\t} \n\t\t\n\t\tif (!$debut && $nb_per_page) $q.= \"limit \".$nb_per_page;\n\t\tif ($debut && $nb_per_page) $q.= \"limit \".$debut.\",\".$nb_per_page;\n\n\t\treturn $q;\t\t\t\t\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_7.5.8", "language": "php"} {"function": "public function buildBrowserData(\n $userAgent = '',\n $acceptHeader = '',\n $screenWidth = 0,\n $screenHeight = 0,\n $colorDepth = 0,\n $timeZoneOffset = 0,\n $language = '',\n $javaEnabled = false,\n $request = array()\n ) {\n if (!empty($userAgent)) {\n $request[self::BROWSER_INFO]['userAgent'] = $userAgent;\n }\n\n if (!empty($acceptHeader)) {\n $request[self::BROWSER_INFO]['acceptHeader'] = $acceptHeader;\n }\n\n if (!empty($screenWidth)) {\n $request[self::BROWSER_INFO]['screenWidth'] = $screenWidth;\n }\n\n if (!empty($screenHeight)) {\n $request[self::BROWSER_INFO]['screenHeight'] = $screenHeight;\n }\n\n if (!empty($colorDepth)) {\n $request[self::BROWSER_INFO]['colorDepth'] = $colorDepth;\n }\n\n if (!empty($timeZoneOffset)) {\n $request[self::BROWSER_INFO]['timeZoneOffset'] = $timeZoneOffset;\n }\n\n if (!empty($language)) {\n $request[self::BROWSER_INFO]['language'] = $language;\n }\n\n $request[self::BROWSER_INFO]['javaEnabled'] = $javaEnabled;\n\n return $request;\n }", "smellKey": "S107", "smellId": null, "repo": "Adyen_adyen-php-api-library", "language": "php"} {"function": "public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {\n\t\t$prev_cell_margin = $this->cell_margin;\n\t\t$prev_cell_padding = $this->cell_padding;\n\t\t$this->adjustCellPadding($border);\n\t\tif (!$ignore_min_height) {\n\t\t\t$min_cell_height = $this->getCellHeight($this->FontSize);\n\t\t\tif ($h < $min_cell_height) {\n\t\t\t\t$h = $min_cell_height;\n\t\t\t}\n\t\t}\n\t\t$this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);\n\t\t// apply text shadow if enabled\n\t\tif ($this->txtshadow['enabled']) {\n\t\t\t// save data\n\t\t\t$x = $this->x;\n\t\t\t$y = $this->y;\n\t\t\t$bc = $this->bgcolor;\n\t\t\t$fc = $this->fgcolor;\n\t\t\t$sc = $this->strokecolor;\n\t\t\t$alpha = $this->alpha;\n\t\t\t// print shadow\n\t\t\t$this->x += $this->txtshadow['depth_w'];\n\t\t\t$this->y += $this->txtshadow['depth_h'];\n\t\t\t$this->SetFillColorArray($this->txtshadow['color']);\n\t\t\t$this->SetTextColorArray($this->txtshadow['color']);\n\t\t\t$this->SetDrawColorArray($this->txtshadow['color']);\n\t\t\tif ($this->txtshadow['opacity'] != $alpha['CA']) {\n\t\t\t\t$this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);\n\t\t\t}\n\t\t\tif ($this->state == 2) {\n\t\t\t\t$this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));\n\t\t\t}\n\t\t\t//restore data\n\t\t\t$this->x = $x;\n\t\t\t$this->y = $y;\n\t\t\t$this->SetFillColorArray($bc);\n\t\t\t$this->SetTextColorArray($fc);\n\t\t\t$this->SetDrawColorArray($sc);\n\t\t\tif ($this->txtshadow['opacity'] != $alpha['CA']) {\n\t\t\t\t$this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);\n\t\t\t}\n\t\t}\n\t\tif ($this->state == 2) {\n\t\t\t$this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));\n\t\t}\n\t\t$this->cell_padding = $prev_cell_padding;\n\t\t$this->cell_margin = $prev_cell_margin;\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public static function listSuggestions($id_bibli=0, $statut='-1', $num_categ='-1', $mask=\"\", $debut=0, $nb_per_page=0, $aq=0, $order='',$location=0) {\n\n\t\tif ($statut == '-1') { \n\t\t\t$filtre1 = '1';\n\t\t} elseif ($statut == $mask) {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = '\".$mask.\"' \";\n\t\t} else {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = 0 and (statut & \".$statut.\") = '\".$statut.\"' \";\n\t\t}\n\t\t\t\n\t\tif ($num_categ == '-1') {\n\t\t\t$filtre2 = '1';\n\t\t} else {\n\t\t\t$filtre2 = \"num_categ = '\".$num_categ.\"' \";\n\t\t}\n\n\t\tif (!$id_bibli) $filtre3 = '1';\n\t\t\telse $filtre3.= \"num_entite = '\".$id_bibli.\"' \";\n\n\t\tif ($location == 0) {\n\t\t\t$filtre4 = '1';\n\t\t} else {\n\t\t\t$filtre4 = \"sugg_location = '\".$location.\"' \";\n\t\t}\t\t\n\t\tif(!$aq) {\n\t\t\t\n\t\t\t$q = \"select * from suggestions where 1 \";\n\t\t\t$q.= \"and \".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4 .\" \";\n\t\t\tif(!$order) $q.=\"order by statut, date_creation desc \";\n\t\t\t\telse $q.= \"order by\".$order.\" \";\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t$members=$aq->get_query_members(\"suggestions\",\"concat(titre,' ',editeur,' ',auteur,' ',commentaires)\",\"index_suggestion\",\"id_suggestion\", $filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4);\n\t\t\tif (!$order) {\n\t\t\t\t$q = \"select *, \".$members[\"select\"].\" as pert from suggestions where \".$members[\"where\"].\" and \".$members[\"restrict\"].\" order by pert desc \";\t\n\t\t\t} else {\n\t\t\t\t$q = \"select *, \".$members[\"select\"].\" as pert from suggestions where \".$members[\"where\"].\" and \".$members[\"restrict\"].\" order by \".$order.\", pert desc \";\n\t\t\t}\n\t\t} \n\t\t\n\t\tif (!$debut && $nb_per_page) $q.= \"limit \".$nb_per_page;\n\t\tif ($debut && $nb_per_page) $q.= \"limit \".$debut.\",\".$nb_per_page;\n\n\t\treturn $q;\t\t\t\t\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $name, ?array $permissions, bool $documentSecurity, bool $enabled, Response $response, Database $dbForProject, string $mode, Event $events) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collectionId = $collectionId == 'unique()' ? ID::unique() : $collectionId;\n\n // Map aggregate permissions into the multiple permissions they represent.\n $permissions = Permission::aggregate($permissions);\n\n try {\n $dbForProject->createDocument('database_' . $database->getInternalId(), new Document([\n '$id' => $collectionId,\n 'databaseInternalId' => $database->getInternalId(),\n 'databaseId' => $databaseId,\n '$permissions' => $permissions ?? [],\n 'documentSecurity' => $documentSecurity,\n 'enabled' => $enabled,\n 'name' => $name,\n 'search' => implode(' ', [$collectionId, $name]),\n ]));\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n $dbForProject->createCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), permissions: $permissions ?? [], documentSecurity: $documentSecurity);\n } catch (DuplicateException) {\n throw new Exception(Exception::COLLECTION_ALREADY_EXISTS);\n } catch (LimitException) {\n throw new Exception(Exception::COLLECTION_LIMIT_EXCEEDED);\n }\n\n $events\n ->setContext('database', $database)\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($collection, Response::MODEL_COLLECTION);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function get_query_members($table,$field_l,$field_i,$id_field,$restrict=\"\",$offset=0,$n=0,$is_fulltext=false) {\n\t\tglobal $pmb_search_full_text;\n\t\tif (($is_fulltext)&&($pmb_search_full_text)) $q=$this->get_query_full_text($table,$field_l,$field_i,$id_field); else {\n\t\t\t$select=\"\";\n\t\t\t$pcount=0;\n\t\t\t$q=$this->get_query_r($this->tree,$select,$pcount,$table,$field_l,$field_i,$id_field,0,1);\n\t\t}\n\t\tif ($restrict) $q[\"restrict\"]=$restrict;\n\t\treturn $q;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function send_mail($id_empr, $to_nom=\"\", $to_mail=\"\", $obj=\"\", $corps=\"\", $from_name=\"\", $from_mail=\"\", $headers=\"\", $copie_CC=\"\", $copie_BCC=\"\", $faire_nl2br=0, $pieces_jointes=array(), $reply_name=\"\", $reply_mail=\"\", $is_mailing=false, $type=\"\") {\n\t\t$campaign_recipients = $this->get_recipients();\n\t\t$recipient_instance = $campaign_recipients->add($id_empr, $to_mail, $corps);\n\t\t\n\t\t$corps = campaign_proxy::proxyfication($recipient_instance, $corps);\n\t\n\t\treturn mailpmb($to_nom, $to_mail, $obj, $corps, $from_name, $from_mail, $headers, $copie_CC, $copie_BCC, $faire_nl2br, $pieces_jointes, $reply_name, $reply_mail, $is_mailing, $type, $this->get_id());\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public static function add_post($thread_id, $section, $author_aid, $author_guid, $post_text, $post_topic, $smile, $html)\n\t{\n\t\tglobal $db;\n\t\t$db->insert(FORUM_TABLE_PREFIX . 'forum', array(\n\t\t\t'first_post' => $thread_id,\n\t\t\t'section' => $section,\n\t\t\t'author_aid' => $author_aid,\n\t\t\t'author_guid' => $author_guid,\n\t\t\t'post_text' => $post_text,\n\t\t\t'post_topic' => $post_topic,\n\t\t\t'post_smile' => $smile,\n\t\t\t'post_html' => $html,\n\t\t\t'post_date' => time(),\n\t\t\t'post_ip' => $_SERVER['REMOTE_ADDR']\n\t\t));\n\t}", "smellKey": "S107", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function __construct(\n ContentService $contentService,\n LocationService $locationService,\n HttpKernelInterface $kernel,\n ContentPreviewHelper $previewHelper,\n AuthorizationCheckerInterface $authorizationChecker,\n PreviewLocationProvider $locationProvider,\n CustomLocationControllerChecker $controllerChecker,\n bool $debugMode = false,\n ?LoggerInterface $logger = null\n ) {\n $this->contentService = $contentService;\n $this->locationService = $locationService;\n $this->kernel = $kernel;\n $this->previewHelper = $previewHelper;\n $this->authorizationChecker = $authorizationChecker;\n $this->locationProvider = $locationProvider;\n $this->controllerChecker = $controllerChecker;\n $this->debugMode = $debugMode;\n $this->logger = $logger ?? new NullLogger();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function _rows( $taxonomy, $terms, &$children, $start, $per_page, &$count, $parent_term = 0, $level = 0 ) {\n\n\t\t$end = $start + $per_page;\n\n\t\tforeach ( $terms as $key => $term ) {\n\n\t\t\tif ( $count >= $end ) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif ( $term->parent !== $parent_term && empty( $_REQUEST['s'] ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// If the page starts in a subtree, print the parents.\n\t\t\tif ( $count === $start && $term->parent > 0 && empty( $_REQUEST['s'] ) ) {\n\t\t\t\t$my_parents = array();\n\t\t\t\t$parent_ids = array();\n\t\t\t\t$p = $term->parent;\n\n\t\t\t\twhile ( $p ) {\n\t\t\t\t\t$my_parent = get_term( $p, $taxonomy );\n\t\t\t\t\t$my_parents[] = $my_parent;\n\t\t\t\t\t$p = $my_parent->parent;\n\n\t\t\t\t\tif ( in_array( $p, $parent_ids, true ) ) { // Prevent parent loops.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t$parent_ids[] = $p;\n\t\t\t\t}\n\n\t\t\t\tunset( $parent_ids );\n\n\t\t\t\t$num_parents = count( $my_parents );\n\n\t\t\t\twhile ( $my_parent = array_pop( $my_parents ) ) {\n\t\t\t\t\techo \"\\t\";\n\t\t\t\t\t$this->single_row( $my_parent, $level - $num_parents );\n\t\t\t\t\t$num_parents--;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( $count >= $start ) {\n\t\t\t\techo \"\\t\";\n\t\t\t\t$this->single_row( $term, $level );\n\t\t\t}\n\n\t\t\t++$count;\n\n\t\t\tunset( $terms[ $key ] );\n\n\t\t\tif ( isset( $children[ $term->term_id ] ) && empty( $_REQUEST['s'] ) ) {\n\t\t\t\t$this->_rows( $taxonomy, $terms, $children, $start, $per_page, $count, $term->term_id, $level + 1 );\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "function ps_add_pdflink($psdoc, float $llx, float $lly, float $urx, float $ury, string $filename, int $page, string $dest): void\n{\n error_clear_last();\n $result = \\ps_add_pdflink($psdoc, $llx, $lly, $urx, $ury, $filename, $page, $dest);\n if ($result === false) {\n throw PsException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function CalcPlot3Dlink($funcs, $linktext=\"View Graph\", $xmin=-2, $xmax=2, $ymin=-2, $ymax=2, $zmin=-2, $zmax=2, $xscl=1, $yscl=1, $zscl=1, $zclipmin=null,$zclipmax=null,$showbox=true,$scaleaxes=false) {\n\t$querystring = CalcPlot3Dquerystring($funcs, $xmin, $xmax, $ymin, $ymax, $zmin, $zmax, $xscl, $yscl, $zscl, $zclipmin, $zclipmax,$showbox);\n\t//$querystring is sanitized as it's constructed\n\t$out = '';\n\t$out .= Sanitize::encodeStringForDisplay($linktext).'';\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function runGitAction(string $status, GitHub $github, string $providerCommitHash, string $owner, string $repositoryName, Document $project, Document $function, string $deploymentId, Database $dbForProject, Database $dbForConsole): void\n {\n if ($function->getAttribute('providerSilentMode', false) === true) {\n return;\n }\n\n $deployment = $dbForProject->getDocument('deployments', $deploymentId);\n $commentId = $deployment->getAttribute('providerCommentId', '');\n\n if (!empty($providerCommitHash)) {\n $message = match ($status) {\n 'ready' => 'Build succeeded.',\n 'failed' => 'Build failed.',\n 'processing' => 'Building...',\n default => $status\n };\n\n $state = match ($status) {\n 'ready' => 'success',\n 'failed' => 'failure',\n 'processing' => 'pending',\n default => $status\n };\n\n $functionName = $function->getAttribute('name');\n $projectName = $project->getAttribute('name');\n\n $name = \"{$functionName} ({$projectName})\";\n\n $protocol = App::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';\n $hostname = App::getEnv('_APP_DOMAIN');\n $functionId = $function->getId();\n $projectId = $project->getId();\n $providerTargetUrl = $protocol . '://' . $hostname . \"/console/project-$projectId/functions/function-$functionId\";\n\n $github->updateCommitStatus($repositoryName, $providerCommitHash, $owner, $state, $message, $providerTargetUrl, $name);\n }\n\n if (!empty($commentId)) {\n $retries = 0;\n\n while (true) {\n $retries++;\n\n try {\n $dbForConsole->createDocument('vcsCommentLocks', new Document([\n '$id' => $commentId\n ]));\n break;\n } catch (Exception $err) {\n if ($retries >= 9) {\n throw $err;\n }\n\n \\sleep(1);\n }\n }\n\n // Wrap in try/finally to ensure lock file gets deleted\n try {\n $comment = new Comment();\n $comment->parseComment($github->getComment($owner, $repositoryName, $commentId));\n $comment->addBuild($project, $function, $status, $deployment->getId(), ['type' => 'logs']);\n $github->updateComment($owner, $repositoryName, $commentId, $comment->generateComment());\n } finally {\n $dbForConsole->deleteDocument('vcsCommentLocks', $commentId);\n }\n }\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function arPostAdjustment($patient_id, $encounter_id, $session_id, $amount, $code, $payer_type, $reason, $debug, $time = '', $codetype = '')\n {\n $codeonly = $code;\n $modifier = '';\n $tmp = strpos($code, ':');\n if ($tmp) {\n $codeonly = substr($code, 0, $tmp);\n $modifier = substr($code, $tmp + 1);\n }\n\n if (empty($time)) {\n $time = date('Y-m-d H:i:s');\n }\n\n sqlBeginTrans();\n $sequence_no = sqlQuery(\"SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?\", array($patient_id, $encounter_id));\n $query = \"INSERT INTO ar_activity ( \" .\n \"pid, encounter, sequence_no, code_type, code, modifier, payer_type, post_user, post_time, \" .\n \"session_id, memo, adj_amount \" .\n \") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n sqlStatement($query, array($patient_id, $encounter_id, $sequence_no['increment'], $codetype, $codeonly, $modifier, $payer_type, $_SESSION['authUserID'], $time, $session_id, $reason, $amount));\n sqlCommitTrans();\n return;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function dropdown_cats($optionall = 1, $all = 'All', $orderby = 'ID', $order = 'asc',\n\t\t$show_last_update = 0, $show_count = 0, $hide_empty = 1, $optionnone = false,\n\t\t$selected = 0, $exclude = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'wp_dropdown_categories()' );\n\n\t$show_option_all = '';\n\tif ( $optionall )\n\t\t$show_option_all = $all;\n\n\t$show_option_none = '';\n\tif ( $optionnone )\n\t\t$show_option_none = __('None');\n\n\t$vars = compact('show_option_all', 'show_option_none', 'orderby', 'order',\n\t\t\t\t\t'show_last_update', 'show_count', 'hide_empty', 'selected', 'exclude');\n\t$query = add_query_arg($vars, '');\n\treturn wp_dropdown_categories($query);\n}", "smellKey": "S107", "smellId": null, "repo": "jpbarraca_sqli-wordpress", "language": "php"} {"function": "function writeOptionLine($option_id, $title, $seq, $default, $value, $mapping = '', $notes = '', $codes = '', $tog1 = '', $tog2 = '', $active = '1', $subtype = '')\n{\n global $opt_line_no, $list_id;\n ++$opt_line_no;\n $bgcolor = \"#\" . (($opt_line_no & 1) ? \"ddddff\" : \"ffdddd\");\n $checked = $default ? \" checked\" : \"\";\n $checked_tog1 = $tog1 ? \" checked\" : \"\";\n $checked_tog2 = $tog2 ? \" checked\" : \"\";\n $checked_active = $active ? \" checked\" : \"\";\n\n echo \" \\n\";\n\n echo \" \";\n //New line for hidden input, for update items\n echo \"\";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n // if not english and translating lists then show the translation\n if ($GLOBALS['translate_lists'] && $_SESSION['language_choice'] > 1) {\n echo \" \" . xlt($title) . \"\\n\";\n }\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n if (preg_match('/Eye_QP_/', $list_id)) {\n echo \" \";\n echo \"\";\n echo \"\";\n } else {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n }\n // Tax rates, contraceptive methods and LBF names have an additional attribute.\n //\n if ($list_id == 'taxrate' || $list_id == 'contrameth' || $list_id == 'lbfnames' || $list_id == 'transactions') {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n } elseif ($list_id == 'adjreason') {\n // Adjustment reasons use option_value as a reason category. This is\n // needed to distinguish between adjustments that change the invoice\n // balance and those that just shift responsibility of payment or\n // are used as comments.\n echo \" \";\n echo \"\";\n echo \"\\n\";\n } elseif ($list_id == 'warehouse') {\n echo \" \\n\";\n // Build a drop-down list of facilities.\n $query = \"SELECT id, name FROM facility ORDER BY name\";\n $fres = sqlStatement($query);\n echo \"\\n\";\n echo \" \\n\";\n } elseif ($list_id == 'abook_type') { // Address book categories use option_value to flag category as a\n // person-centric vs company-centric vs indifferent.\n echo \" \";\n echo \"\";\n echo \"\\n\";\n } elseif ($list_id == 'immunizations') { // Immunization categories use option_value to map list items to CVX codes.\n echo \" \";\n echo \"\";\n echo \"\\n\";\n } elseif ($list_id == 'ptlistcols') {\n echo \" \";\n echo generate_select_list(\"opt[$opt_line_no][toggle_setting_1]\", 'Sort_Direction', $tog1, 'Sort Direction', null, 'option');\n echo \"\\n\";\n }\n\n if ($list_id == 'apptstat' || $list_id == 'groupstat') {\n list($apptstat_color, $apptstat_timealert) = explode(\"|\", $notes);\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n } else {\n // IPPF includes the ability to map each list item to a \"master\" identifier.\n // Sports teams use this for some extra info for fitness levels.\n if ($GLOBALS['ippf_specific'] || $list_id == 'fitness') {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n }\n echo \" \";\n echo \"\";\n echo \"\\n\";\n }\n\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n if (preg_match('/_issue_list$/', $list_id)) {\n echo \" \";\n echo generate_select_list(\"opt[$opt_line_no][subtype]\", 'issue_subtypes', $subtype, 'Subtype', ' ', 'optin');\n echo \"\\n\";\n }\n if (preg_match('/Eye_QP_/', $list_id)) {\n echo \"\";\n echo \"\";\n }\n echo \" \\n\";\n}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function addApiTracking($transactionId, $user, $numberOfRecords, $requestType, $testType, $url = null, $requestData = null, $responseData = null, $format = null)\n {\n $db = Zend_Db_Table_Abstract::getDefaultAdapter();\n try {\n\n $requestData = Pt_Commons_JsonUtility::encodeUtf8Json($requestData ?? '{}');\n $responseData = Pt_Commons_JsonUtility::encodeUtf8Json($responseData ?? '{}');\n\n $folderPath = realpath(UPLOAD_PATH) . DIRECTORY_SEPARATOR . 'track-api';\n if (!empty($requestData) && $requestData != '[]') {\n $this->common->makeDirectory($folderPath . DIRECTORY_SEPARATOR . 'requests');\n $this->common->dataToZippedFile($requestData, \"$folderPath/requests/$transactionId.json\");\n }\n if (!empty($responseData) && $responseData != '[]') {\n $this->common->makeDirectory($folderPath . DIRECTORY_SEPARATOR . 'responses');\n $this->common->dataToZippedFile($responseData, \"$folderPath/responses/$transactionId.json\");\n }\n\n $data = [\n 'transaction_id' => $transactionId ?? null,\n 'requested_by' => $user ?? 'system',\n 'requested_on' => Pt_Commons_General::getDateTime(),\n 'number_of_records' => $numberOfRecords ?? 0,\n 'request_type' => $requestType ?? null,\n 'test_type' => $testType ?? null,\n 'api_url' => $url ?? null,\n 'data_format' => $format ?? null\n ];\n return $db->insert(\"track_api_requests\", $data);\n } catch (Throwable $exc) {\n Pt_Commons_LoggerUtility::log('error', $exc->getFile() . \":\" . $exc->getLine() . \" - \" . $exc->getMessage());\n return 0;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public function __construct(\n\t\t?string $outCodEscola,\n\t\t?string $outDescNomeEscola,\n\t\t?string $outCodDiretoria,\n\t\t?string $outDescNomeDiretoria,\n\t\t?string $outTipoLogradouro,\n\t\t?string $outDescEndereco,\n\t\t?string $outNumero,\n\t\t?string $outDescBairro,\n\t\t?string $outDescComplemento,\n\t\t?string $outCodMunicipio,\n\t\t?string $outDescMunicipio,\n\t\t?string $outLatitude,\n\t\t?string $outLongitude,\n\t\t?string $outCodRedeEnsino,\n\t\t?string $outNomeRedeEnsino,\n\t\t?string $outCodDistrito,\n\t\t?string $outCEP,\n\t\t?string $outNomeDistrito,\n\t\t?array $outUnidades\n\t) {\n\t\t$this->outCodEscola = $outCodEscola;\n\t\t$this->outDescNomeEscola = $outDescNomeEscola;\n\t\t$this->outCodDiretoria = $outCodDiretoria;\n\t\t$this->outDescNomeDiretoria = $outDescNomeDiretoria;\n\t\t$this->outTipoLogradouro = $outTipoLogradouro;\n\t\t$this->outDescEndereco = $outDescEndereco;\n\t\t$this->outNumero = $outNumero;\n\t\t$this->outDescBairro = $outDescBairro;\n\t\t$this->outDescComplemento = $outDescComplemento;\n\t\t$this->outCodMunicipio = $outCodMunicipio;\n\t\t$this->outDescMunicipio = $outDescMunicipio;\n\t\t$this->outLatitude = $outLatitude;\n\t\t$this->outLongitude = $outLongitude;\n\t\t$this->outCodRedeEnsino = $outCodRedeEnsino;\n\t\t$this->outNomeRedeEnsino = $outNomeRedeEnsino;\n\t\t$this->outCodDistrito = $outCodDistrito;\n\t\t$this->outCEP = $outCEP;\n\t\t$this->outNomeDistrito = $outNomeDistrito;\n\t\t$this->outUnidades = $outUnidades;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(\n ?array $communes,\n ?string $statut,\n array $etiquettes,\n ?string $type,\n ?\\DateTime $dateStart,\n ?\\DateTime $dateEnd,\n bool $countRefused,\n bool $countArchived,\n ?Territory $territory,\n ?ArrayCollection $partners,\n ) {\n $this->communes = $communes;\n $this->statut = $statut;\n $this->etiquettes = $etiquettes;\n $this->type = $type;\n $this->dateStart = $dateStart;\n $this->dateEnd = $dateEnd;\n $this->countRefused = $countRefused;\n $this->countArchived = $countArchived;\n $this->territory = $territory;\n $this->partners = $partners;\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL)\n\t{\n\t\tif (is_array($name))\n\t\t{\n\t\t\t// always leave 'name' in last place, as the loop will break otherwise, due to $$item\n\t\t\tforeach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item)\n\t\t\t{\n\t\t\t\tif (isset($name[$item]))\n\t\t\t\t{\n\t\t\t\t\t$$item = $name[$item];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ($prefix === '' && config_item('cookie_prefix') !== '')\n\t\t{\n\t\t\t$prefix = config_item('cookie_prefix');\n\t\t}\n\n\t\tif ($domain == '' && config_item('cookie_domain') != '')\n\t\t{\n\t\t\t$domain = config_item('cookie_domain');\n\t\t}\n\n\t\tif ($path === '/' && config_item('cookie_path') !== '/')\n\t\t{\n\t\t\t$path = config_item('cookie_path');\n\t\t}\n\n\t\t$secure = ($secure === NULL && config_item('cookie_secure') !== NULL)\n\t\t\t? (bool) config_item('cookie_secure')\n\t\t\t: (bool) $secure;\n\n\t\t$httponly = ($httponly === NULL && config_item('cookie_httponly') !== NULL)\n\t\t\t? (bool) config_item('cookie_httponly')\n\t\t\t: (bool) $httponly;\n\n\t\tif ( ! is_numeric($expire))\n\t\t{\n\t\t\t$expire = time() - 86500;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$expire = ($expire > 0) ? time() + $expire : 0;\n\t\t}\n\n\t\tsetcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly);\n\t}", "smellKey": "S107", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function update($companyID, $name, $address, $city, $state,\n $zip, $phone1, $phone2, $faxNumber, $url,\n $keyTechnologies, $isHot, $notes, $owner,\n $billingContact, $email, $emailAddress)\n {\n $sql = sprintf(\n \"UPDATE\n company\n SET\n name = %s,\n address = %s,\n city = %s,\n state = %s,\n zip = %s,\n phone1 = %s,\n phone2 = %s,\n fax_number = %s,\n url = %s,\n key_technologies = %s,\n is_hot = %s,\n notes = %s,\n billing_contact = %s,\n owner = %s,\n date_modified = NOW()\n WHERE\n company_id = %s\n AND\n site_id = %s\",\n $this->_db->makeQueryString($name),\n $this->_db->makeQueryString($address),\n $this->_db->makeQueryString($city),\n $this->_db->makeQueryString($state),\n $this->_db->makeQueryString($zip),\n $this->_db->makeQueryString($phone1),\n $this->_db->makeQueryString($phone2),\n $this->_db->makeQueryString($faxNumber),\n $this->_db->makeQueryString($url),\n $this->_db->makeQueryString($keyTechnologies),\n ($isHot ? '1' : '0'),\n $this->_db->makeQueryString($notes),\n $this->_db->makeQueryInteger($billingContact),\n $this->_db->makeQueryInteger($owner),\n $this->_db->makeQueryInteger($companyID),\n $this->_siteID\n );\n\n $preHistory = $this->get($companyID);\n $queryResult = $this->_db->query($sql);\n $postHistory = $this->get($companyID);\n\n if (!$queryResult)\n {\n return false;\n }\n\n $history = new History($this->_siteID);\n $history->storeHistoryChanges(DATA_ITEM_COMPANY, $companyID, $preHistory, $postHistory);\n\n if (!empty($emailAddress))\n {\n /* Send e-mail notification. */\n //FIXME: Make subject configurable.\n $mailer = new Mailer($this->_siteID);\n $mailerStatus = $mailer->sendToOne(\n array($emailAddress, ''),\n 'CATS Notification: Company Ownership Change',\n $email,\n true\n );\n }\n\n return true;\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function creerDossierIB3($client, $ref_dos, $mca_b_ref, $road_manif, $date_preal, $t1, \n\t\t\t\t\t\t\t\t\t\t$poids, $ref_fact, $supplier, $fob, $fret, \n\t\t\t\t\t\t\t\t\t\t$assurance, $autre_frais, $po_ref, \n\t\t\t\t\t\t\t\t\t\t$commodity, $horse, $trailer_1, $trailer_2, $num_lic, $num_exo,\n\t\t\t\t\t\t\t\t\t\t$arrival_date, $crossing_date, $wiski_arriv, $wiski_dep, $amicongo_arriv,\n\t\t\t\t\t\t\t\t\t\t$insp_report, $ir, $ref_crf, $date_crf, $ref_decl, $dgda_in, $ref_liq, \n\t\t\t\t\t\t\t\t\t\t$date_liq, $ref_quit, $date_quit, $dgda_out, $custom_deliv, $dispatch_deliv,\n\t\t\t\t\t\t\t\t\t\t$remarque, $statut, $bl, $id_mod_trac, $id_util, $id_mod_trans, $credit_enlev_by, $bond_warehouse){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;$entree['mca_b_ref'] = $mca_b_ref;\n\t\t\t$entree['date_preal'] = $date_preal;$entree['t1'] = $t1;\n\t\t\t$entree['poids'] = $poids;$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['fob'] = $fob;$entree['fret'] = $fret;$entree['assurance'] = $assurance;\n\t\t\t$entree['autre_frais'] = $autre_frais;$entree['po_ref'] = $po_ref;\n\t\t\t$entree['commodity'] = $commodity;$entree['horse'] = $horse;$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;$entree['road_manif'] = $road_manif;\n\t\t\t$entree['num_lic'] = $num_lic;$entree['num_exo'] = $num_exo;$entree['arrival_date'] = $arrival_date;\n\t\t\t$entree['crossing_date'] = $crossing_date;$entree['wiski_arriv'] = $wiski_arriv;$entree['wiski_dep'] = $wiski_dep;\n\t\t\t$entree['amicongo_arriv'] = $amicongo_arriv;$entree['insp_report'] = $insp_report;$entree['ir'] = $ir;\n\t\t\t$entree['ref_crf'] = $ref_crf;$entree['date_crf'] = $date_crf;$entree['ref_decl'] = $ref_decl;\n\t\t\t$entree['dgda_in'] = $dgda_in;$entree['ref_liq'] = $ref_liq;$entree['date_liq'] = $date_liq;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['date_quit'] = $date_quit;$entree['dgda_out'] = $dgda_out;\n\t\t\t$entree['custom_deliv'] = $custom_deliv;$entree['dispatch_deliv'] = $dispatch_deliv;$entree['remarque'] = $remarque;\n\t\t\t$entree['statut'] = $statut;$entree['id_mod_trac'] = $id_mod_trac;$entree['id_util'] = $id_util;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['bl'] = $bl;\n\t\t\t$entree['supplier'] = $supplier;\n\t\t\t$entree['credit_enlev_by'] = $credit_enlev_by;\n\t\t\t$entree['bond_warehouse'] = $bond_warehouse;\n\n\t\t\tif($entree['date_quit'] == '' || (strlen($entree['date_quit']) != 10) ){\n\t\t\t\t$entree['date_quit'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_liq'] == '' || (strlen($entree['date_liq']) != 10) ){\n\t\t\t\t$entree['date_liq'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['poids'] == ''){\n\t\t\t\t$entree['poids'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fob'] == ''){\n\t\t\t\t$entree['fob'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fret'] == ''){\n\t\t\t\t$entree['fret'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['assurance'] == ''){\n\t\t\t\t$entree['assurance'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['autre_frais'] == '' ){\n\t\t\t\t$entree['autre_frais'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['ir'] == '' ){\n\t\t\t\t$entree['ir'] = 'NO';\n\t\t\t}\n\n\t\t\tif($entree['date_preal'] == '' || (strlen($entree['date_preal']) != 10) ){\n\t\t\t\t$entree['date_preal'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['arrival_date'] == '' || (strlen($entree['arrival_date']) != 10) ){\n\t\t\t\t$entree['arrival_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['crossing_date'] == '' || (strlen($entree['crossing_date']) != 10) ){\n\t\t\t\t$entree['crossing_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_arriv'] == '' || (strlen($entree['wiski_arriv']) != 10) ){\n\t\t\t\t$entree['wiski_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_dep'] == '' || (strlen($entree['wiski_dep']) != 10) ){\n\t\t\t\t$entree['wiski_dep'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['amicongo_arriv'] == '' || (strlen($entree['amicongo_arriv']) != 10) ){\n\t\t\t\t$entree['amicongo_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['insp_report'] == '' || (strlen($entree['insp_report']) != 10) ){\n\t\t\t\t$entree['insp_report'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_crf'] == '' || (strlen($entree['date_crf']) != 10) ){\n\t\t\t\t$entree['date_crf'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['dgda_in'] == '' || (strlen($entree['dgda_in']) != 10) ){\n\t\t\t\t$entree['dgda_in'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['dgda_out'] == '' || (strlen($entree['dgda_out']) != 10) ){\n\t\t\t\t$entree['dgda_out'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['custom_deliv'] == '' || (strlen($entree['custom_deliv']) != 10) ){\n\t\t\t\t$entree['custom_deliv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['dispatch_deliv'] == '' || (strlen($entree['dispatch_deliv']) != 10) ){\n\t\t\t\t$entree['dispatch_deliv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['bl'] == '' || (strlen($entree['bl']) != 10) ){\n\t\t\t\t$entree['bl'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(id_cli, ref_dos, mca_b_ref, date_preal, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_util, id_mod_trans, num_lic, t1, poids, ref_fact, fob, fret, assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tautre_frais, po_ref, commodity, horse, trailer_1, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_2, road_manif, num_exo, arrival_date, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcrossing_date, wiski_arriv, wiski_dep, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamicongo_arriv, insp_receiv, ir, ref_crf, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate_crf, ref_decl, dgda_in, ref_liq, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate_liq, ref_quit, date_quit, dgda_out, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcustom_deliv, dispatch_deliv, remarque, statut, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbl, supplier, credit_enlev_by, bond_warehouse) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['mca_b_ref'], \n\t\t\t\t\t\t\t\t\t$entree['date_preal'], $entree['id_mod_trac'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_trans'], $entree['num_lic'], $entree['t1'], \n\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['ref_fact'], $entree['fob'], \n\t\t\t\t\t\t\t\t\t$entree['fret'], $entree['assurance'], $entree['autre_frais'], \n\t\t\t\t\t\t\t\t\t$entree['po_ref'], $entree['commodity'], $entree['horse'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_1'], $entree['trailer_2'], $entree['road_manif'], \n\t\t\t\t\t\t\t\t\t$entree['num_exo'], $entree['arrival_date'], $entree['crossing_date'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_arriv'], $entree['wiski_dep'], $entree['amicongo_arriv'], \n\t\t\t\t\t\t\t\t\t$entree['insp_report'], $entree['ir'], $entree['ref_crf'], \n\t\t\t\t\t\t\t\t\t$entree['date_crf'], $entree['ref_decl'], $entree['dgda_in'], \n\t\t\t\t\t\t\t\t\t$entree['ref_liq'], $entree['date_liq'], $entree['ref_quit'], \n\t\t\t\t\t\t\t\t\t$entree['date_quit'], $entree['dgda_out'], $entree['custom_deliv'], \n\t\t\t\t\t\t\t\t\t$entree['dispatch_deliv'], $entree['remarque'], $entree['statut'], \n\t\t\t\t\t\t\t\t\t$entree['bl'], $entree['supplier'], $entree['credit_enlev_by'], \n\t\t\t\t\t\t\t\t\t$entree['bond_warehouse']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "protected function populateProductsWorksheet( &$worksheet, &$languages, $default_language_id, &$price_format, &$box_format, &$weight_format, &$text_format, $offset=null, $rows=null, &$min_id=null, &$max_id=null) {\n\t\t// get list of the field names, some are only available for certain OpenCart versions\n\t\t$query = $this->db->query( \"DESCRIBE `\".DB_PREFIX.\"product`\" );\n\t\t$product_fields = array();\n\t\tforeach ($query->rows as $row) {\n\t\t\t$product_fields[] = $row['Field'];\n\t\t}\n\n\t\t// Opencart versions from 2.0 onwards also have product_description.meta_title\n\t\t$sql = \"SHOW COLUMNS FROM `\".DB_PREFIX.\"product_description` LIKE 'meta_title'\";\n\t\t$query = $this->db->query( $sql );\n\t\t$exist_meta_title = ($query->num_rows > 0) ? true : false;\n\n\t\t// Opencart versions from 3.0 onwards use the seo_url DB table\n\t\t$exist_seo_url_table = $this->use_table_seo_url;\n\n\t\t// Set the column widths\n\t\t$j = 0;\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('product_id'),4)+1);\n\t\tforeach ($languages as $language) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('name')+4,30)+1);\n\t\t}\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('categories'),12)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('sku'),10)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('upc'),12)+1);\n\t\tif (in_array('ean',$product_fields)) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('ean'),14)+1);\n\t\t}\n\t\tif (in_array('jan',$product_fields)) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('jan'),13)+1);\n\t\t}\n\t\tif (in_array('isbn',$product_fields)) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('isbn'),13)+1);\n\t\t}\n\t\tif (in_array('mpn',$product_fields)) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('mpn'),15)+1);\n\t\t}\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('location'),10)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('quantity'),4)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('model'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('manufacturer'),10)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('product_type_id'),3)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('image_name'),12)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('shipping'),5)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('price'),10)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('points'),5)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('date_added'),19)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('date_modified'),19)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('date_available'),10)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('weight'),6)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('weight_unit'),3)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('length'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('width'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('height'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('length_unit'),3)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('status'),5)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('tax_class_id'),2)+1);\n\t\tif (!$exist_seo_url_table) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('seo_keyword'),16)+1);\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('description')+4,32)+1);\n\t\t}\n\t\tif ($exist_meta_title) {\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('meta_title')+4,20)+1);\n\t\t\t}\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('meta_description')+4,32)+1);\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('meta_keywords')+4,32)+1);\n\t\t}\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('stock_status_id'),3)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('store_ids'),16)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('layout'),16)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('related_ids'),16)+1);\n\t\tforeach ($languages as $language) {\n\t\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('tags')+4,32)+1);\n\t\t}\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('sort_order'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('subtract'),5)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('minimum'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('delivery_days'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('multistone'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('side_stone'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('rrp'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('product_markup'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('carat_from'),8)+1);\n\t\t$worksheet->getColumnDimensionByColumn($j++)->setWidth(max(strlen('carat_to'),8)+1);\n\n\t\t// The product headings row and column styles\n\t\t$styles = array();\n\t\t$data = array();\n\t\t$i = 1;\n\t\t$j = 0;\n\t\t$data[$j++] = 'product_id';\n\t\tforeach ($languages as $language) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'name('.$language['code'].')';\n\t\t}\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'categories';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'sku';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'upc';\n\t\tif (in_array('ean',$product_fields)) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'ean';\n\t\t}\n\t\tif (in_array('jan',$product_fields)) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'jan';\n\t\t}\n\t\tif (in_array('isbn',$product_fields)) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'isbn';\n\t\t}\n\t\tif (in_array('mpn',$product_fields)) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'mpn';\n\t\t}\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'location';\n\t\t$data[$j++] = 'quantity';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'model';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'manufacturer';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'product_type_id';\n\t\t$data[$j++] = 'image_name';\n\t\t$data[$j++] = 'shipping';\n\t\t$styles[$j] = &$price_format;\n\t\t$data[$j++] = 'price';\n\t\t$data[$j++] = 'points';\n\t\t$data[$j++] = 'date_added';\n\t\t$data[$j++] = 'date_modified';\n\t\t$data[$j++] = 'date_available';\n\t\t$styles[$j] = &$weight_format;\n\t\t$data[$j++] = 'weight';\n\t\t$data[$j++] = 'weight_unit';\n\t\t$data[$j++] = 'length';\n\t\t$data[$j++] = 'width';\n\t\t$data[$j++] = 'height';\n\t\t$data[$j++] = 'length_unit';\n\t\t$data[$j++] = 'status';\n\t\t$data[$j++] = 'tax_class_id';\n\t\tif (!$exist_seo_url_table) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'seo_keyword';\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'description('.$language['code'].')';\n\t\t}\n\t\tif ($exist_meta_title) {\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$styles[$j] = &$text_format;\n\t\t\t\t$data[$j++] = 'meta_title('.$language['code'].')';\n\t\t\t}\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'meta_description('.$language['code'].')';\n\t\t}\n\t\tforeach ($languages as $language) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'meta_keywords('.$language['code'].')';\n\t\t}\n\t\t$data[$j++] = 'stock_status_id';\n\t\t$data[$j++] = 'store_ids';\n\t\t$styles[$j] = &$text_format;\n\t\t$data[$j++] = 'layout';\n\t\t$data[$j++] = 'related_ids';\n\t\tforeach ($languages as $language) {\n\t\t\t$styles[$j] = &$text_format;\n\t\t\t$data[$j++] = 'tags('.$language['code'].')';\n\t\t}\n\t\t$data[$j++] = 'sort_order';\n\t\t$data[$j++] = 'subtract';\n\t\t$data[$j++] = 'minimum';\n\t\t$data[$j++] = 'delivery_days';\n\t\t$data[$j++] = 'multistone';\n\t\t$data[$j++] = 'side_stone';\n\t\t$data[$j++] = 'rrp';\n\t\t$data[$j++] = 'product_markup';\n\t\t$data[$j++] = 'carat_from';\n\t\t$data[$j++] = 'carat_to';\n\t\t$worksheet->getRowDimension($i)->setRowHeight(30);\n\t\t$this->setCellRow( $worksheet, $i, $data, $box_format );\n\n\t\t// The actual products data\n\t\t$i += 1;\n\t\t$j = 0;\n\t\t$store_ids = $this->getStoreIdsForProducts();\n\t\t$layouts = $this->getLayoutsForProducts();\n\t\t$products = $this->getProducts( $languages, $default_language_id, $product_fields, $exist_meta_title, $exist_seo_url_table, $offset, $rows, $min_id, $max_id );\n\t\t$len = count($products);\n\t\t$min_id = ($len>0) ? $products[0]['product_id'] : 0;\n\t\t$max_id = ($len>0) ? $products[$len-1]['product_id'] : 0;\n\t\tforeach ($products as $row) {\n\t\t\t$data = array();\n\t\t\t$worksheet->getRowDimension($i)->setRowHeight(26);\n\t\t\t$product_id = $row['product_id'];\n\t\t\t$data[$j++] = $product_id;\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$data[$j++] = html_entity_decode($row['name'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t}\n\t\t\t$data[$j++] = $row['categories'];\n\t\t\t$data[$j++] = $row['sku'];\n\t\t\t$data[$j++] = $row['upc'];\n\t\t\tif (in_array('ean',$product_fields)) {\n\t\t\t\t$data[$j++] = $row['ean'];\n\t\t\t}\n\t\t\tif (in_array('jan',$product_fields)) {\n\t\t\t\t$data[$j++] = $row['jan'];\n\t\t\t}\n\t\t\tif (in_array('isbn',$product_fields)) {\n\t\t\t\t$data[$j++] = $row['isbn'];\n\t\t\t}\n\t\t\tif (in_array('mpn',$product_fields)) {\n\t\t\t\t$data[$j++] = $row['mpn'];\n\t\t\t}\n\t\t\t$data[$j++] = $row['location'];\n\t\t\t$data[$j++] = $row['quantity'];\n\t\t\t$data[$j++] = $row['model'];\n\t\t\t$data[$j++] = $row['manufacturer'];\n\t\t\t$data[$j++] = $row['product_type_id'];\n\t\t\t$data[$j++] = $row['image_name'];\n\t\t\t$data[$j++] = ($row['shipping']==0) ? 'no' : 'yes';\n\t\t\t$data[$j++] = $row['price'];\n\t\t\t$data[$j++] = $row['points'];\n\t\t\t$data[$j++] = $row['date_added'];\n\t\t\t$data[$j++] = $row['date_modified'];\n\t\t\t$data[$j++] = $row['date_available'];\n\t\t\t$data[$j++] = $row['weight'];\n\t\t\t$data[$j++] = $row['weight_unit'];\n\t\t\t$data[$j++] = $row['length'];\n\t\t\t$data[$j++] = $row['width'];\n\t\t\t$data[$j++] = $row['height'];\n\t\t\t$data[$j++] = $row['length_unit'];\n\t\t\t$data[$j++] = ($row['status']==0) ? 'false' : 'true';\n\t\t\t$data[$j++] = $row['tax_class_id'];\n\t\t\tif (!$exist_seo_url_table) {\n\t\t\t\t$data[$j++] = ($row['keyword']) ? $row['keyword'] : '';\n\t\t\t}\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$data[$j++] = html_entity_decode($row['description'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t}\n\t\t\tif ($exist_meta_title) {\n\t\t\t\tforeach ($languages as $language) {\n\t\t\t\t\t$data[$j++] = html_entity_decode($row['meta_title'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t\t}\n\t\t\t}\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$data[$j++] = html_entity_decode($row['meta_description'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t}\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$data[$j++] = html_entity_decode($row['meta_keyword'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t}\n\t\t\t$data[$j++] = $row['stock_status_id'];\n\t\t\t$store_id_list = '';\n\t\t\tif (isset($store_ids[$product_id])) {\n\t\t\t\tforeach ($store_ids[$product_id] as $store_id) {\n\t\t\t\t\t$store_id_list .= ($store_id_list=='') ? $store_id : ','.$store_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$data[$j++] = $store_id_list;\n\t\t\t$layout_list = '';\n\t\t\tif (isset($layouts[$product_id])) {\n\t\t\t\tforeach ($layouts[$product_id] as $store_id => $name) {\n\t\t\t\t\t$layout_list .= ($layout_list=='') ? $store_id.':'.$name : ','.$store_id.':'.$name;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$data[$j++] = $layout_list;\n\t\t\t$data[$j++] = $row['related'];\n\t\t\tforeach ($languages as $language) {\n\t\t\t\t$data[$j++] = html_entity_decode($row['tag'][$language['code']],ENT_QUOTES,'UTF-8');\n\t\t\t}\n\t\t\t$data[$j++] = $row['sort_order'];\n\t\t\t$data[$j++] = ($row['subtract']==0) ? 'false' : 'true';\n\t\t\t$data[$j++] = $row['minimum'];\n\t\t\t$data[$j++] = $row['delivery_days'];\n\t\t\t$data[$j++] = $row['multistone'];\n\t\t\t$data[$j++] = $row['side_stone'];\n\t\t\t$data[$j++] = $row['rrp'];\n\t\t\t$data[$j++] = $row['product_markup'];\n\t\t\t$data[$j++] = $row['carat_from'];\n\t\t\t$data[$j++] = $row['carat_to'];\n\t\t\t$this->setCellRow( $worksheet, $i, $data, $this->null_array, $styles );\n\t\t\t$i += 1;\n\t\t\t$j = 0;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode, Mail $mails, Stats $usage) use ($databaseListener) {\n\n $route = $utopia->getRoute();\n\n if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope\n throw new Exception(Exception::PROJECT_UNKNOWN);\n }\n\n /*\n * Abuse Check\n */\n $abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');\n $timeLimitArray = [];\n\n $abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;\n\n foreach ($abuseKeyLabel as $abuseKey) {\n $timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject);\n $timeLimit\n ->setParam('{userId}', $user->getId())\n ->setParam('{userAgent}', $request->getUserAgent(''))\n ->setParam('{ip}', $request->getIP())\n ->setParam('{url}', $request->getHostname() . $route->getPath())\n ->setParam('{method}', $request->getMethod());\n $timeLimitArray[] = $timeLimit;\n }\n\n $closestLimit = null;\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n\n foreach ($timeLimitArray as $timeLimit) {\n foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys\n if (!empty($value)) {\n $timeLimit->setParam('{param-' . $key . '}', (\\is_array($value)) ? \\json_encode($value) : $value);\n }\n }\n\n $abuse = new Abuse($timeLimit);\n $remaining = $timeLimit->remaining();\n $limit = $timeLimit->limit();\n $time = (new \\DateTime($timeLimit->time()))->getTimestamp() + $route->getLabel('abuse-time', 3600);\n\n if ($limit && ($remaining < $closestLimit || is_null($closestLimit))) {\n $closestLimit = $remaining;\n $response\n ->addHeader('X-RateLimit-Limit', $limit)\n ->addHeader('X-RateLimit-Remaining', $remaining)\n ->addHeader('X-RateLimit-Reset', $time)\n ;\n }\n\n $enabled = App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled';\n\n if (\n $enabled // Abuse is enabled\n && !$isAppUser // User is not API key\n && !$isPrivilegedUser // User is not an admin\n && $abuse->check() // Route is rate-limited\n ) {\n throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED);\n }\n }\n\n /*\n * Background Jobs\n */\n $events\n ->setEvent($route->getLabel('event', ''))\n ->setProject($project)\n ->setUser($user);\n\n $audits\n ->setMode($mode)\n ->setUserAgent($request->getUserAgent(''))\n ->setIP($request->getIP())\n ->setEvent($route->getLabel('audits.event', ''))\n ->setProject($project)\n ->setUser($user);\n\n $usage\n ->setParam('projectInternalId', $project->getInternalId())\n ->setParam('projectId', $project->getId())\n ->setParam('project.{scope}.network.requests', 1)\n ->setParam('httpMethod', $request->getMethod())\n ->setParam('project.{scope}.network.inbound', 0)\n ->setParam('project.{scope}.network.outbound', 0);\n\n $deletes->setProject($project);\n $database->setProject($project);\n\n $dbForProject->on(Database::EVENT_DOCUMENT_CREATE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));\n $dbForProject->on(Database::EVENT_DOCUMENT_DELETE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));\n\n $useCache = $route->getLabel('cache', false);\n\n if ($useCache) {\n $key = md5($request->getURI() . implode('*', $request->getParams()) . '*' . APP_CACHE_BUSTER);\n $cache = new Cache(\n new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())\n );\n $timestamp = 60 * 60 * 24 * 30;\n $data = $cache->load($key, $timestamp);\n\n if (!empty($data)) {\n $data = json_decode($data, true);\n $parts = explode('/', $data['resourceType']);\n $type = $parts[0] ?? null;\n\n if ($type === 'bucket') {\n $bucketId = $parts[1] ?? null;\n\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_READ);\n $valid = $validator->isValid($bucket->getRead());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n $parts = explode('/', $data['resource']);\n $fileId = $parts[1] ?? null;\n\n if ($fileSecurity && !$valid) {\n $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);\n } else {\n $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n }\n\n if ($file->isEmpty()) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);\n }\n }\n\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + $timestamp) . ' GMT')\n ->addHeader('X-Appwrite-Cache', 'hit')\n ->setContentType($data['contentType'])\n ->send(base64_decode($data['payload']))\n ;\n } else {\n $response->addHeader('X-Appwrite-Cache', 'miss');\n }\n }\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function creerDossierLogistique2($ref_dos, $point_load, $horse, $trailer_1, \n\t\t\t\t\t\t\t\t\t\t$nom_chauf, $lic_num, $tel_chauf, $remarque, $frontiere, \n\t\t\t\t\t\t\t\t\t\t$destination, $transit, $id_cli, \n\t\t\t\t\t\t\t\t\t\t$id_mod_trans, $id_trans, $id_util){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['ref_dos'] = $ref_dos;\n\t\t\t$entree['point_load'] = $point_load;\n\t\t\t$entree['horse'] = $horse;\n\t\t\t$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['nom_chauf'] = $nom_chauf;\n\t\t\t$entree['lic_num'] = $lic_num;\n\t\t\t$entree['tel_chauf'] = $tel_chauf;\n\t\t\t$entree['remarque'] = $remarque;\n\t\t\t$entree['frontiere'] = $frontiere;\n\t\t\t$entree['destination'] = $destination;\n\t\t\t$entree['transit'] = $transit;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_trans'] = $id_trans;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_logistique(ref_dos, point_load, horse, trailer_1, nom_chauf, lic_num, tel_chauf, remarque, frontiere, destination, transit, id_cli, id_mod_trans, id_trans, id_util, statut) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \\'IN TRANSIT\\')');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['point_load'], $entree['horse'], $entree['trailer_1'], $entree['nom_chauf'], $entree['lic_num'], $entree['tel_chauf'], $entree['remarque'], $entree['frontiere'], $entree['destination'], $entree['transit'], $entree['id_cli'], $entree['id_mod_trans'], $entree['id_trans'], $entree['id_util']));\n\t\t\t\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "private function getDataCellForGeometryColumns(\n string|null $column,\n string $class,\n FieldMetadata $meta,\n array $map,\n array $urlParams,\n bool $conditionField,\n TransformationsInterface|null $transformationPlugin,\n array $transformOptions,\n StatementInfo $statementInfo,\n ): string {\n if ($column === null) {\n return $this->buildNullDisplay($class, $conditionField, $meta);\n }\n\n if ($column === '') {\n return $this->buildEmptyDisplay($class, $conditionField, $meta);\n }\n\n // Display as [GEOMETRY - (size)]\n if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM) {\n $geometryText = $this->handleNonPrintableContents(\n 'GEOMETRY',\n $column,\n $transformationPlugin,\n $transformOptions,\n $meta,\n $urlParams,\n );\n\n return $this->buildValueDisplay($class, $conditionField, $geometryText);\n }\n\n if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_WKT) {\n // Prepare in Well Known Text(WKT) format.\n $whereComparison = ' = ' . $column;\n\n // Convert to WKT format\n $wktval = Gis::convertToWellKnownText($column);\n [\n $isFieldTruncated,\n $displayedColumn,\n // skip 3rd param\n ] = $this->getPartialText($wktval);\n\n return $this->getRowData(\n $class,\n $conditionField,\n $statementInfo,\n $meta,\n $map,\n $wktval,\n $displayedColumn,\n $transformationPlugin,\n '',\n $whereComparison,\n $transformOptions,\n $isFieldTruncated,\n );\n }\n\n // Prepare in Well Known Binary (WKB) format.\n\n if ($_SESSION['tmpval']['display_binary']) {\n $whereComparison = ' = ' . $column;\n\n $wkbval = substr(bin2hex($column), 8);\n [\n $isFieldTruncated,\n $displayedColumn,\n // skip 3rd param\n ] = $this->getPartialText($wkbval);\n\n return $this->getRowData(\n $class,\n $conditionField,\n $statementInfo,\n $meta,\n $map,\n $wkbval,\n $displayedColumn,\n $transformationPlugin,\n '',\n $whereComparison,\n $transformOptions,\n $isFieldTruncated,\n );\n }\n\n $wkbval = $this->handleNonPrintableContents(\n 'BINARY',\n $column,\n $transformationPlugin,\n $transformOptions,\n $meta,\n $urlParams,\n );\n\n return $this->buildValueDisplay($class, $conditionField, $wkbval);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "private function writePlotArea(PHPExcel_Chart_PlotArea $plotArea, PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, $objWriter, PHPExcel_Worksheet $pSheet, PHPExcel_Chart_Axis $xAxis, PHPExcel_Chart_Axis $yAxis, PHPExcel_Chart_GridLines $majorGridlines, PHPExcel_Chart_GridLines $minorGridlines)\n {\n if (is_null($plotArea)) {\n return;\n }\n\n $id1 = $id2 = 0;\n $this->_seriesIndex = 0;\n $objWriter->startElement('c:plotArea');\n\n $layout = $plotArea->getLayout();\n\n $this->writeLayout($layout, $objWriter);\n\n $chartTypes = self::getChartType($plotArea);\n $catIsMultiLevelSeries = $valIsMultiLevelSeries = false;\n $plotGroupingType = '';\n foreach ($chartTypes as $chartType) {\n $objWriter->startElement('c:' . $chartType);\n\n $groupCount = $plotArea->getPlotGroupCount();\n for ($i = 0; $i < $groupCount; ++$i) {\n $plotGroup = $plotArea->getPlotGroupByIndex($i);\n $groupType = $plotGroup->getPlotType();\n if ($groupType == $chartType) {\n $plotStyle = $plotGroup->getPlotStyle();\n if ($groupType === PHPExcel_Chart_DataSeries::TYPE_RADARCHART) {\n $objWriter->startElement('c:radarStyle');\n $objWriter->writeAttribute('val', $plotStyle);\n $objWriter->endElement();\n } elseif ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART) {\n $objWriter->startElement('c:scatterStyle');\n $objWriter->writeAttribute('val', $plotStyle);\n $objWriter->endElement();\n }\n\n $this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet);\n }\n }\n\n $this->writeDataLabels($objWriter, $layout);\n\n if ($chartType === PHPExcel_Chart_DataSeries::TYPE_LINECHART) {\n // Line only, Line3D can't be smoothed\n\n $objWriter->startElement('c:smooth');\n $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine());\n $objWriter->endElement();\n } elseif (($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) {\n $objWriter->startElement('c:gapWidth');\n $objWriter->writeAttribute('val', 150);\n $objWriter->endElement();\n\n if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') {\n $objWriter->startElement('c:overlap');\n $objWriter->writeAttribute('val', 100);\n $objWriter->endElement();\n }\n } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {\n $objWriter->startElement('c:bubbleScale');\n $objWriter->writeAttribute('val', 25);\n $objWriter->endElement();\n\n $objWriter->startElement('c:showNegBubbles');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {\n $objWriter->startElement('c:hiLowLines');\n $objWriter->endElement();\n\n $objWriter->startElement('c:upDownBars');\n\n $objWriter->startElement('c:gapWidth');\n $objWriter->writeAttribute('val', 300);\n $objWriter->endElement();\n\n $objWriter->startElement('c:upBars');\n $objWriter->endElement();\n\n $objWriter->startElement('c:downBars');\n $objWriter->endElement();\n\n $objWriter->endElement();\n }\n\n // Generate 2 unique numbers to use for axId values\n // $id1 = $id2 = rand(10000000,99999999);\n // do {\n // $id2 = rand(10000000,99999999);\n // } while ($id1 == $id2);\n $id1 = '75091328';\n $id2 = '75089408';\n\n if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {\n $objWriter->startElement('c:axId');\n $objWriter->writeAttribute('val', $id1);\n $objWriter->endElement();\n $objWriter->startElement('c:axId');\n $objWriter->writeAttribute('val', $id2);\n $objWriter->endElement();\n } else {\n $objWriter->startElement('c:firstSliceAng');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n\n if ($chartType === PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) {\n $objWriter->startElement('c:holeSize');\n $objWriter->writeAttribute('val', 50);\n $objWriter->endElement();\n }\n }\n\n $objWriter->endElement();\n }\n\n if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {\n if ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {\n $this->writeValueAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines);\n } else {\n $this->writeCategoryAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis);\n }\n\n $this->writeValueAxis($objWriter, $plotArea, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines);\n }\n\n $objWriter->endElement();\n }", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n\t\t?string $outAnoLetivo,\n\t\t?string $outCodEscola,\n\t\t?string $outDescNomeAbrevEscola,\n\t\t?string $outNumClasse,\n\t\t?string $outCodTipoEnsino,\n\t\t?string $outDescTipoEnsino,\n\t\t?string $outCodSerieAno,\n\t\t?string $outDescSerieAno,\n\t\t?string $outGrauNivel,\n\t\t?string $outSerieNivel,\n\t\t?string $outCodTurno,\n\t\t?string $outDescricaoTurno,\n\t\t?string $outNumAluno,\n\t\t?string $outCodHabilitacao,\n\t\t?string $outDescHabilitacao,\n\t\t?string $outTurma,\n\t\t?string $outDescTurma,\n\t\t?string $outDataInclusaoMatricula,\n\t\t?string $outDataFimMatricula,\n\t\t?string $outDataInicioMatricula,\n\t\t?string $outHoraFinal,\n\t\t?string $outHoraInicial,\n\t\t?string $outCodSitMatricula,\n\t\t?string $outDescSitMatricula,\n\t\t?string $outCodSitTranspEscolar,\n\t\t?string $outDescSitTranspEscolar \n\t) {\n\t\t$this->outAnoLetivo = $outAnoLetivo;\n\t\t$this->outCodEscola = $outCodEscola;\n\t\t$this->outDescNomeAbrevEscola = $outDescNomeAbrevEscola;\n\t\t$this->outNumClasse = $outNumClasse;\n\t\t$this->outCodTipoEnsino = $outCodTipoEnsino;\n\t\t$this->outDescTipoEnsino = $outDescTipoEnsino;\n\t\t$this->outCodSerieAno = $outCodSerieAno;\n\t\t$this->outDescSerieAno = $outDescSerieAno;\n\t\t$this->outGrauNivel = $outGrauNivel;\n\t\t$this->outSerieNivel = $outSerieNivel;\n\t\t$this->outCodTurno = $outCodTurno;\n\t\t$this->outDescricaoTurno = $outDescricaoTurno;\n\t\t$this->outNumAluno = $outNumAluno;\n\t\t$this->outCodHabilitacao = $outCodHabilitacao;\n\t\t$this->outDescHabilitacao = $outDescHabilitacao;\n\t\t$this->outTurma = $outTurma;\n\t\t$this->outDescTurma = $outDescTurma;\n\t\t$this->outDataInclusaoMatricula = $outDataInclusaoMatricula;\n\t\t$this->outDataFimMatricula = $outDataFimMatricula;\n\t\t$this->outDataInicioMatricula = $outDataInicioMatricula;\n\t\t$this->outHoraFinal = $outHoraFinal;\n\t\t$this->outHoraInicial = $outHoraInicial;\n\t\t$this->outCodSitMatricula = $outCodSitMatricula;\n\t\t$this->outDescSitMatricula = $outDescSitMatricula;\n\t\t$this->outCodSitTranspEscolar = $outCodSitTranspEscolar;\n\t\t$this->outDescSitTranspEscolar = $outDescSitTranspEscolar ;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function recordSearchRelatedIds($system, &$ids, $direction=0, $no_relationships=false,\n $depth=0, $max_depth=1, $limit=0, $new_level_ids=null, $temp_ids=null){\n\n if($depth>=$max_depth) {return;}\n\n if($new_level_ids==null) {$new_level_ids = $ids;}\n\n if(!($direction==1||$direction==-1)){\n $direction = 0;\n }\n\n $mysqli = $system->getMysqli();\n\n $res1 = null; $res2 = null;\n\n if($temp_ids==null && !$no_relationships){\n //find temp relationship records (rt#1)\n $relRT = ($system->defineConstant('RT_RELATION')?RT_RELATION:0);\n $query = 'SELECT rec_ID FROM Records '\n .' where rec_RecTypeID='.$relRT.' AND rec_FlagTemporary=1';\n $temp_ids = mysql__select_list2($mysqli, $query);\n }\n\n if($direction>=0){\n\n //find all target related records\n $query = 'SELECT rl_TargetID, rl_RelationID FROM recLinks, Records '\n .' where rl_SourceID in ('.implode(',',$new_level_ids).') '\n .' AND rl_TargetID=rec_ID AND rec_FlagTemporary=0';\n if($no_relationships){\n $query = $query . ' AND rl_RelationID IS NULL';\n }\n\n $res = $mysqli->query($query);\n if ($res){\n $res1 = array();\n\n while ($row = $res->fetch_row()){\n\n $id = intval($row[1]);\n if($id>0){\n if($temp_ids!=null && in_array($id, $temp_ids)){ //is temporary\n continue; //exclude temporary\n }elseif(!in_array($id, $ids)){\n array_push($res1, $id);//add relationship record\n }\n }\n\n $id = intval($row[0]);\n if(!in_array($id, $ids)) {array_push($res1, $id);}\n }\n $res->close();\n }\n }\n\n if($direction<=0){\n $query = 'SELECT rl_SourceID, rl_RelationID FROM recLinks, Records where rl_TargetID in ('\n .implode(',',$new_level_ids).') '\n .' AND rl_SourceID=rec_ID AND rec_FlagTemporary=0';\n if($no_relationships){\n $query = $query . ' AND rl_RelationID IS NULL';\n }\n\n $res = $mysqli->query($query);\n if ($res){\n $res2 = array();\n\n while ($row = $res->fetch_row()){\n\n $id = intval($row[1]);\n if($id>0){\n if($temp_ids!=null && in_array($id, $temp_ids)){ //is temporary\n continue;\n }elseif(!in_array($id, $ids)){\n array_push($res2, $id);\n }\n }\n\n $id = intval($row[0]);\n if(!in_array($id, $ids)) {array_push($res2, $id);}\n }\n $res->close();\n }\n }\n\n if(!isEmptyArray($res1) && is_array($res2)){\n $res = array_merge_unique($res1, $res2);\n }elseif(!isEmptyArray($res1)){\n $res = $res1;\n }else{\n $res = $res2;\n }\n\n //find new level\n if(!isEmptyArray($res)){\n $ids = array_merge_unique($ids, $res);\n\n if($limit>0 && count($ids)>=$limit){\n $ids = array_slice($ids,0,$limit);\n }else{\n recordSearchRelatedIds($system, $ids, $direction, $no_relationships, $depth+1, $max_depth, $limit, $res, $temp_ids);\n }\n\n }\n}", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function ajoutInscriptionEleve2($num,$annee,$etab,$classe,$prof_principal,$filiere,$lv1,$lv2,$date_inscription,$commentaires)\n\t{\n\t$req = \"INSERT INTO `inscrit`(`ID_ELEVE`, `ANNEE`, `ID`, `ID_FILIERES`, `ID_LV1`, `ID_LV2`, `ID_CLASSE`, `DATE_INSCRIPTION`, `NOM_DU_PROF_PRINCIPAL`, `COMMENTAIRESANNEE`) VALUES ('$num', '$annee', '$etab','$filiere','$lv1','$lv2','$classe','$date_inscription','$prof_principal','$commentaires') \";\n\t\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function plot3d($func,$umin=-2,$umax=2,$vmin=-2,$vmax=2,$disc=20,$width=300,$height=300,$axes=1) {\n\tglobal $imasroot, $staticroot;\n\tif ($GLOBALS['inquestiondisplay'] == false) {return '';}\n\n\t$alt = '3D Plot';\n\tif (func_num_args()>14) {\n\t\t$bounds = array_slice(func_get_args(),9,6);\n\t\tif (func_num_args()>15) {\n\t\t\t$alt = func_get_arg(15);\n\t\t}\n\t} else if (func_num_args()>9) {\n\t\t$alt = func_get_arg(9);\n\t}\n\n\tif (strpos($func,',')!==FALSE) {\n\t\t$isparam = true;\n\t\t$func = str_replace('[','',$func);\n\t\t$func = str_replace(']','',$func);\n\t\t$func = explode(',',$func);\n\t\tforeach ($func as $k=>$v) {\n\t\t\t$usefunc[$k] = makeMathFunction($v, \"u,v\");\n\t\t}\n\n\t} else {\n\t\t$isparam = false;\n\t\t$zfunc = makeMathFunction($func, \"x,y\");\n\t}\n\t$count = 0;\n\t$du = ($umax-$umin)/($disc-1);\n\t$dv = ($vmax-$vmin)/($disc-1);\n\t$urnd = max(floor(-log10($du)-1e-12)+3,2);\n\t$vrnd = max(floor(-log10($dv)-1e-12)+3,2);\n\t$zrnd = max($urnd,$vrnd);\n $verts = '';\n\tfor ($i=0; $i<$disc;$i++) {\n\t\t for ($j=0;$j<$disc;$j++) {\n\t\t\t if ($count > 0) { $verts .= '~';}\n\t\t\t $u = $umin+$du*$i;\n\t\t\t $v = $vmin+$dv*$j;\n\t\t\t if ($isparam) {\n\t\t\t\t $x = round($usefunc[0](['u'=>$u,'v'=>$v]),$urnd);\n\t\t\t\t $y = round($usefunc[1](['u'=>$u,'v'=>$v]),$vrnd);\n\t\t\t\t $z = round($usefunc[2](['u'=>$u,'v'=>$v]),$zrnd);\n\t\t\t\t $verts .= \"$x,$y,$z\";\n\t\t\t } else {\n\t\t\t\t $z = round($zfunc(['x'=>$u,'y'=>$v]),$zrnd);\n\t\t\t\t $u = round($u,$urnd);\n\t\t\t\t $v = round($v,$vrnd);\n\t\t\t\t $verts .= \"$u,$v,$z\";\n\t\t\t }\n\t\t\t $count++;\n\t\t }\n\t }\n\t $count = 0;\n $faces = '';\n\t for ($i=0; $i<$disc-1;$i++) {\n\t\t for ($j=0;$j<$disc-1;$j++) {\n\t\t\t if ($count > 0) { $faces .= '~';}\n\t\t\t $faces .= ($i*$disc+$j) . ',' ;\n\t\t\t $faces .= (($i+1)*$disc+$j) . ',';\n\t\t\t $faces .= (($i+1)*$disc+$j+1) . ',';\n\t\t\t $faces .= ($i*$disc+$j+1);\n\n\t\t\t $count++;\n\t\t }\n\t }\n\n\t $useragent = $_SERVER['HTTP_USER_AGENT'] ?? '';\n\t $oldschool = false;\n\t if (isset($_SESSION['useflash'])) {\n\t\t$oldschool = true;\n\t } else if (preg_match('/MSIE\\s*(\\d+)/i',$useragent,$matches)) {\n\t\tif ($matches[1]<9) {\n\t\t\t$oldschool =true;\n\t\t}\n\t }\n $html = '';\n\t if ($oldschool || isset($_SESSION['useflash'])) {\n\t \t$r = uniqid();\n\t\t $GLOBALS['3dplotcnt'] = $r;\n\t\t $html .= \"
\";\n\t\t $html .= '

\"Get

';\n\t\t $html .= '
';\n\t\t $html .= '';\n\t } else {\n\t \t$r = uniqid();\n\t\t\tif (!isset($GLOBALS['3dplotcnt']) || (isset($GLOBALS['assessUIver']) && $GLOBALS['assessUIver'] > 1)) {\n\t\t\t\t$html .= '';\n\t\t\t}\n\t \t $GLOBALS['3dplotcnt'] = $r;\n\t \t $html .= \"\";\n\t \t if (isset($bounds)) {\n\t\t\t $bndtxt = 'bounds:\"' . implode(',',$bounds) . '\",';\n\t\t } else {\n\t\t \t $bndtxt='';\n\t\t }\n\t \t $url = $GLOBALS['basesiteurl'] . substr($_SERVER['SCRIPT_NAME'],strlen($imasroot)) . (isset($_SERVER['QUERY_STRING'])?'?'.Sanitize::encodeStringForDisplay($_SERVER['QUERY_STRING']).'&useflash=true':'?useflash=true');\n\t\t $html .= \"\";\n\t \t $html .= \"\";\n\t\t\t\t$init = \"var plot3d$r = new Viewer3D({verts: '$verts', faces: '$faces', $bndtxt width: '$width', height:'$height', showaxes:$axes}, 'plot3d$r');\";\n\t\t\t\tif (isset($GLOBALS['assessUIver']) && $GLOBALS['assessUIver'] > 1) {\n\t\t\t\t\t$html .= \"\";\n\t\t\t\t} else {\n\t\t\t\t\t$html .= \"\";\n\t\t\t\t}\n\t }\n\t return $html;\n\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private static function step($func, &$A, $B, $C, $D, $M, $s, $t)\n {\n $A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff;\n $A = self::rotate($A, $s);\n $A = ($B + $A) & 0xffffffff;\n }", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function getNavbar($page, $nbr_lignes, $nb_per_page, $url, $nb_per_page_custom_url = \"&nb_per_page_custom=!!nb_per_page_custom!!\", $action = '', $customs = \"\", $from_cms = false){\n global $opac_items_pagination_custom, $cms_active, $opac_rgaa_active;\n // on fait suivre les variables d'environnement du portail\n if ($cms_active && strpos($url, 'javascript:') === false) {\n $query = \"select distinct var_name from cms_vars\";\n $result = pmb_mysql_query($query);\n if (pmb_mysql_num_rows($result)) {\n while ($row = pmb_mysql_fetch_object($result)) {\n $var_name = $row->var_name;\n global ${$var_name};\n if (! empty(${$var_name}) && strpos($url, $var_name.\"=\") === false) {\n $url .= \"&\" . $var_name . \"=\" . rawurlencode(${$var_name});\n }\n }\n }\n }\n $navbar = new NavbarView($page, $nbr_lignes, $nb_per_page, $url, $nb_per_page_custom_url, $action, $from_cms);\n if($customs) {\n $navbar->setCustoms($customs);\n } else if ($opac_items_pagination_custom) {\n $navbar->setCustoms($opac_items_pagination_custom);\n }\n\n if($opac_rgaa_active){\n $navbar->setDistance(NavBarView::DISTANCE_RGAA);\n }\n\n return $navbar;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct(\n PersistenceHandler $persistenceHandler,\n SearchHandler $searchHandler,\n BackgroundIndexer $backgroundIndexer,\n RelationProcessor $relationProcessor,\n FieldTypeRegistry $fieldTypeRegistry,\n PasswordHashService $passwordHashGenerator,\n ProxyDomainMapperFactoryInterface $proxyDomainMapperFactory,\n Mapper\\ContentDomainMapper $contentDomainMapper,\n Mapper\\ContentTypeDomainMapper $contentTypeDomainMapper,\n Mapper\\RoleDomainMapper $roleDomainMapper,\n Mapper\\ContentMapper $contentMapper,\n ContentValidator $contentValidator,\n LimitationService $limitationService,\n LanguageResolver $languageResolver,\n PermissionService $permissionService,\n ContentFilteringHandler $contentFilteringHandler,\n LocationFilteringHandler $locationFilteringHandler,\n PasswordValidatorInterface $passwordValidator,\n ConfigResolverInterface $configResolver,\n NameSchemaServiceInterface $nameSchemaService,\n TransactionHandler $transactionHandler,\n array $serviceSettings = [],\n ?LoggerInterface $logger = null\n ) {\n $this->persistenceHandler = $persistenceHandler;\n $this->searchHandler = $searchHandler;\n $this->backgroundIndexer = $backgroundIndexer;\n $this->relationProcessor = $relationProcessor;\n $this->fieldTypeRegistry = $fieldTypeRegistry;\n $this->passwordHashService = $passwordHashGenerator;\n $this->proxyDomainMapperFactory = $proxyDomainMapperFactory;\n $this->contentDomainMapper = $contentDomainMapper;\n $this->contentTypeDomainMapper = $contentTypeDomainMapper;\n $this->roleDomainMapper = $roleDomainMapper;\n $this->limitationService = $limitationService;\n $this->languageResolver = $languageResolver;\n $this->contentFilteringHandler = $contentFilteringHandler;\n $this->permissionService = $permissionService;\n $this->locationFilteringHandler = $locationFilteringHandler;\n\n $this->serviceSettings = $serviceSettings + [\n 'content' => [],\n 'contentType' => [],\n 'location' => [],\n 'section' => [],\n 'role' => [],\n 'user' => [\n 'anonymousUserID' => 10,\n ],\n 'language' => [],\n 'trash' => [],\n 'io' => [],\n 'objectState' => [],\n 'search' => [],\n 'urlAlias' => [],\n 'urlWildcard' => [],\n 'nameSchema' => [],\n 'languages' => [],\n 'proxy_factory' => [],\n ];\n\n if (!empty($this->serviceSettings['languages'])) {\n $this->serviceSettings['language']['languages'] = $this->serviceSettings['languages'];\n }\n\n $this->logger = $logger ?? new NullLogger();\n $this->contentMapper = $contentMapper;\n $this->contentValidator = $contentValidator;\n $this->passwordValidator = $passwordValidator;\n $this->configResolver = $configResolver;\n $this->nameSchemaService = $nameSchemaService;\n $this->transactionHandler = $transactionHandler;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {\n\t\t$query = $this->connection->prepare('\n\t\t\t\tINSERT INTO `*PREFIX*share_external`\n\t\t\t\t\t(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)\n\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\t\t');\n\t\t$query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function info_modifierUneInscription($id, $nom, $prenom, $adresse, $cp, $ville, $lat, $lon, $sexe, $ddn, $date, $tel1, $tel2, $email) {\n\t\t$req = \"UPDATE `info_inscriptions` SET `nom_inscription` = :nom, `prenom_inscription` = :prenom, `adresse_inscription` = :adresse, `cp_inscription` = :cp, `ville_inscription` = :ville, `lat_inscription` = :lat, `lon_inscription` = :lon, `sexe_inscription` = :sexe, `ddn_inscription` = :ddn, `date_inscription` = :date, `tel1_inscription` = :tel1, `tel2_inscription` = :tel2, `email_inscription` = :email WHERE `id_inscription` = :id\";\n\t\t$params = array(\n\t\t\t':nom' => strtoupper($nom),\n\t\t\t':prenom' => ucwords($prenom),\n\t\t\t':adresse' => $adresse,\n\t\t\t':cp' => $cp,\n\t\t\t':ville' => strtoupper($ville),\n\t\t\t':lat' => $lat,\n\t\t\t':lon' => $lon,\n\t\t\t':sexe' => $sexe,\n\t\t\t':ddn' => $ddn,\n\t\t\t':date' => $date,\n\t\t\t':tel1' => $tel1,\n\t\t\t':tel2' => $tel2,\n\t\t\t':email' => $email,\n\t\t\t':id' => $id\n\t\t);\n\t\t$rs = $this->ReadAll($req, $params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la lecture des donnees ..\", $req, PdoBD::$monPdo->errorInfo());}\n\t\treturn $rs;\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function signParameters($oldparms, $endpoint, $method, $key, $secret, $org_secret, $org_id, $org_desc)\n {\n global $last_base_string;\n $parms = $oldparms;\n $parms[\"lti_version\"] = \"LTI-1p0\";\n $parms[\"lti_message_type\"] = \"basic-lti-launch-request\";\n if ( $org_id ) $parms[\"tool_consumer_instance_guid\"] = $org_id;\n if ( $org_desc ) {\n\t $parms[\"tool_consumer_instance_description\"] = $org_desc;\n\t $parms[\"tool_consumer_instance_name\"] = $org_desc;\n }\n $parms[\"basiclti_submit\"] = \"Launch Tool\";\n $parms[\"oauth_callback\"] = \"about:blank\";\n\n if ( $org_secret ) {\n $oauth_consumer_secret = $org_secret;\n $oauth_consumer_key = $org_id;\n } else {\n $oauth_consumer_secret = $secret;\n $oauth_consumer_key = $key;\n }\n\n $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();\n $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);\n\n $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);\n $acc_req->sign_request($hmac_method, $test_consumer, $test_token);\n\n // Pass this back up \"out of band\" for debugging\n $last_base_string = $acc_req->get_signature_base_string();\n\n $newparms = $acc_req->get_parameters();\n\n return $newparms;\n }", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function updateField($profileID = false, $page, $columnName, $title = false,\n $xPosition = 0, $yPosition = 0, $columnSpan = 1, $rowSpan = 1)\n {\n if (!($profileID = ($profileID !== false ? $profileID : $this->_savedProfileID)))\n {\n return false;\n }\n\n if ($title !== false)\n {\n // Update all occurances of this column name title\n // No need to error check, false just means nothing was changed\n $this->updateTitle($profileID, $columnName, $title, false);\n }\n\n $sql = sprintf(\n \"UPDATE\n profile_page_field\n SET\n x_position = %s,\n y_position = %s,\n column_span = %s,\n row_span = %s\n WHERE\n profile_id = %s\n AND\n page = %s\n AND\n column_name = %s\n AND\n site_id = %d\",\n $this->_db->makeQueryInteger($xPosition),\n $this->_db->makeQueryInteger($yPosition),\n $this->_db->makeQueryInteger($columnSpan),\n $this->_db->makeQueryInteger($rowSpan),\n $this->_db->makeQueryInteger($profileID),\n $this->_db->makeQueryString($page),\n $this->_db->makeQueryString($columnName),\n $this->_siteID\n );\n\n return $this->_db->query($sql);\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function creerFacture($ref_fact, $date_fact, $date_fact_rec, \n\t\t\t\t\t\t\t\t\t\t$fournisseur, $date_val, $fichier_fact, \n\t\t\t\t\t\t\t\t\t\t$tmp_fact, $id_mod_lic, $id_cli, $commodity, \n\t\t\t\t\t\t\t\t\t\t$montant_fact, $id_mon, $fret_fact, \n\t\t\t\t\t\t\t\t\t\t$assurance_fact, $autre_frais_fact){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['date_fact'] = $date_fact;\n\t\t\t$entree['date_fact_rec'] = $date_fact_rec;\n\t\t\t$entree['fournisseur'] = $fournisseur;\n\t\t\t$entree['date_val'] = $date_val;\n\t\t\t$entree['fichier_fact'] = $fichier_fact;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['commodity'] = $commodity;\n\t\t\t$entree['montant_fact'] = $montant_fact;\n\t\t\t$entree['id_mon'] = $id_mon;\n\t\t\t$entree['fret_fact'] = $fret_fact;\n\t\t\t$entree['assurance_fact'] = $assurance_fact;\n\t\t\t$entree['autre_frais_fact'] = $autre_frais_fact;\n\n\t\t\t/*echo '
ref_fact = '.$ref_fact;\n\t\t\techo '
date_fact = '.$date_fact;\n\t\t\techo '
date_fact_rec = '.$date_fact_rec;\n\t\t\techo '
fournisseur= '.$fournisseur;\n\t\t\techo '
date_val = '.$date_val;\n\t\t\techo '
fichier_fact = '.$fichier_fact;\n\t\t\techo '
id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
id_cli = '.$id_cli;\n\t\t\techo '
id_march = '.$id_march;*/\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO facture_licence(ref_fact, date_fact, date_fact_rec, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfournisseur, date_val, fichier_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_cli, commodity, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmontant_fact, id_mon, fret_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tassurance_fact, autre_frais_fact)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_fact'], $entree['date_fact'], $entree['date_fact_rec'], \n\t\t\t\t\t\t\t\t\t$entree['fournisseur'], $entree['date_val'], $entree['fichier_fact'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['id_cli'], $entree['commodity'], \n\t\t\t\t\t\t\t\t\t$entree['montant_fact'], $entree['id_mon'], $entree['fret_fact'], \n\t\t\t\t\t\t\t\t\t$entree['assurance_fact'], $entree['autre_frais_fact']));\n\n\t\t\t$facture = '../factures/'.$ref_fact;\n\n\t\t\tif(!is_dir($facture)){\n\t\t\t\tmkdir(\"../factures/$ref_fact\", 0777);\n\t\t\t}\n\n\t\t\tmove_uploaded_file($tmp_fact, '../factures/'.$ref_fact.'/' . basename($fichier_fact));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n RepositoryInterface $repository,\n Handler $handler,\n ContentDomainMapper $contentDomainMapper,\n Helper\\RelationProcessor $relationProcessor,\n NameSchemaServiceInterface $nameSchemaService,\n FieldTypeRegistry $fieldTypeRegistry,\n PermissionService $permissionService,\n ContentMapper $contentMapper,\n ContentValidator $contentValidator,\n ContentFilteringHandler $contentFilteringHandler,\n array $settings = []\n ) {\n $this->repository = $repository;\n $this->persistenceHandler = $handler;\n $this->contentDomainMapper = $contentDomainMapper;\n $this->relationProcessor = $relationProcessor;\n $this->nameSchemaService = $nameSchemaService;\n $this->fieldTypeRegistry = $fieldTypeRegistry;\n // Union makes sure default settings are ignored if provided in argument\n $this->settings = $settings + [\n // Version archive limit (0-50), only enforced on publish, not on un-publish.\n 'default_version_archive_limit' => 5,\n 'remove_archived_versions_on_publish' => true,\n ];\n $this->contentFilteringHandler = $contentFilteringHandler;\n $this->permissionResolver = $permissionService;\n $this->contentMapper = $contentMapper;\n $this->contentValidator = $contentValidator;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function get_linksbyname($cat_name = \"noname\", $before = '', $after = '
', $between = \" \", $show_images = true, $orderby = 'id',\n\t\t\t\t\t\t$show_description = true, $show_rating = false,\n\t\t\t\t\t\t$limit = -1, $show_updated = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\t$cat_id = -1;\n\t$cat = get_term_by('name', $cat_name, 'link_category');\n\tif ( $cat )\n\t\t$cat_id = $cat->term_id;\n\n\tget_links($cat_id, $before, $after, $between, $show_images, $orderby, $show_description, $show_rating, $limit, $show_updated);\n}", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "function (array $resources, string $subdomain, string $region, string $adminSecret, string $database, string $username, string $password, int $port, Response $response, Database $dbForProject, Document $project, Document $user, Event $events) {\n $migration = $dbForProject->createDocument('migrations', new Document([\n '$id' => ID::unique(),\n 'status' => 'pending',\n 'stage' => 'init',\n 'source' => NHost::getName(),\n 'credentials' => [\n 'subdomain' => $subdomain,\n 'region' => $region,\n 'adminSecret' => $adminSecret,\n 'database' => $database,\n 'username' => $username,\n 'password' => $password,\n 'port' => $port,\n ],\n 'resources' => $resources,\n 'statusCounters' => '{}',\n 'resourceData' => '{}',\n 'errors' => [],\n ]));\n\n $events->setParam('migrationId', $migration->getId());\n\n // Trigger Transfer\n $event = new Migration();\n $event\n ->setMigration($migration)\n ->setProject($project)\n ->setUser($user)\n ->trigger();\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($migration, Response::MODEL_MIGRATION);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function ajoutIntervenant($annee, $nom, $prenom, $actif, $date_naissance, $lieu_naissance, $tel, $adresse, $statut, $cp, $ville, $email, $commentaires, $diplome, $numsecu, $nationalite, $password, $iban, $bic, $compte, $banque)\n\t{\n\t\t$req = \"INSERT INTO `intervenants` VALUES ('', :nom, :prenom, :actif, :statut, :email, :tel, :adresse, :cp, :ville, :diplome, :commentaires, :date_naissance, :lieu_naissance, :nationalite, :numsecu, 'AUCUNE.jpg', '', '', '', '', :password, 0, :iban, :bic, :compte, :banque, '');\";\n\t\t$params = array(\n\t\t\t'nom' => $nom,\n\t\t\t'prenom' => $prenom,\n\t\t\t'actif' => $actif,\n\t\t\t'date_naissance' => $date_naissance,\n\t\t\t'lieu_naissance' => $lieu_naissance,\n\t\t\t'tel' => $tel,\n\t\t\t'adresse' => $adresse,\n\t\t\t'statut' => $statut,\n\t\t\t'cp' => $cp,\n\t\t\t'ville' => $ville,\n\t\t\t'email' => $email,\n\t\t\t'commentaires' => $commentaires,\n\t\t\t'diplome' => $diplome,\n\t\t\t'numsecu' => $numsecu,\n\t\t\t'nationalite' => $nationalite,\n\t\t\t'password' => $password,\n\t\t\t'iban' => $iban,\n\t\t\t'bic' => $bic,\n\t\t\t'compte' => $compte,\n\t\t\t'banque' => $banque,\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'intervenant dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\n\t\t$req = \"INSERT INTO `inscrit_intervenants` (`ID_INTERVENANT`, `ANNEE`) VALUES ((SELECT MAX(ID_INTERVENANT) FROM intervenants), :annee)\";\n\t\t$params = array(':annee' => $annee);\n\t\t$rs = $this->NonQuery($req, $params);\n\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'intervenant dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\treturn $rs;\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function (string $installationId, string $repositoryId, string $providerPullRequestId, GitHub $github, Request $request, Response $response, Document $project, Database $dbForConsole, callable $getProjectDB) use ($createGitDeployments) {\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if ($installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n $repository = $dbForConsole->getDocument('repositories', $repositoryId, [\n Query::equal('projectInternalId', [$project->getInternalId()])\n ]);\n\n if ($repository->isEmpty()) {\n throw new Exception(Exception::REPOSITORY_NOT_FOUND);\n }\n\n if (\\in_array($providerPullRequestId, $repository->getAttribute('providerPullRequestIds', []))) {\n throw new Exception(Exception::PROVIDER_CONTRIBUTION_CONFLICT);\n }\n\n $providerPullRequestIds = \\array_unique(\\array_merge($repository->getAttribute('providerPullRequestIds', []), [$providerPullRequestId]));\n $repository = $repository->setAttribute('providerPullRequestIds', $providerPullRequestIds);\n\n // TODO: Delete from array when PR is closed\n\n $repository = $dbForConsole->updateDocument('repositories', $repository->getId(), $repository);\n\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n $providerInstallationId = $installation->getAttribute('providerInstallationId');\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n\n $repositories = [$repository];\n $providerRepositoryId = $repository->getAttribute('providerRepositoryId');\n\n $owner = $github->getOwnerName($providerInstallationId);\n $repositoryName = $github->getRepositoryName($providerRepositoryId);\n $pullRequestResponse = $github->getPullRequest($owner, $repositoryName, $providerPullRequestId);\n\n $providerBranch = \\explode(':', $pullRequestResponse['head']['label'])[1] ?? '';\n $providerCommitHash = $pullRequestResponse['head']['sha'] ?? '';\n\n $createGitDeployments($github, $providerInstallationId, $repositories, $providerBranch, $providerCommitHash, $providerPullRequestId, true, $dbForConsole, $getProjectDB, $request);\n\n $response->noContent();\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addAttachment($file,\n $c_type = 'application/octet-stream',\n $name = '',\n $isfile = true,\n $encoding = 'base64',\n $disposition = 'attachment',\n $charset = '',\n $language = '',\n $location = '',\n $n_encoding = null,\n $f_encoding = null,\n $description = '',\n $h_charset = null,\n $add_headers = array()\n ) {\n if ($file instanceof Mail_mimePart) {\n $this->parts[] = $file;\n return true;\n }\n\n $bodyfile = null;\n\n if ($isfile) {\n // Don't load file into memory\n if ($this->build_params['delay_file_io']) {\n $filedata = null;\n $bodyfile = $file;\n } else {\n if (self::isError($filedata = $this->file2str($file))) {\n return $filedata;\n }\n }\n // Force the name the user supplied, otherwise use $file\n $filename = ($name ? $name : $this->basename($file));\n } else {\n $filedata = $file;\n $filename = $name;\n }\n\n if (!strlen($filename)) {\n $msg = \"The supplied filename for the attachment can't be empty\";\n return self::raiseError($msg);\n }\n\n $this->parts[] = array(\n 'body' => $filedata,\n 'body_file' => $bodyfile,\n 'name' => $filename,\n 'c_type' => $c_type,\n 'charset' => $charset,\n 'encoding' => $encoding,\n 'language' => $language,\n 'location' => $location,\n 'disposition' => $disposition,\n 'description' => $description,\n 'add_headers' => $add_headers,\n 'name_encoding' => $n_encoding,\n 'filename_encoding' => $f_encoding,\n 'headers_charset' => $h_charset,\n );\n\n return true;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public static function percentageBar($width, $height, $percent, $left_text = '', $right_text = '', $warn = null, $shadow = null, $colors = null)\n {\n $percent = min($percent, 100);\n if ($colors === null) {\n $colors = Color::percentage($percent, $warn ?: null);\n }\n $default = Color::percentage(0);\n $left_text_color = $colors['left_text'] ?? 'ffffff';\n $right_text_color = $colors['right_text'] ?? 'ffffff';\n $left_color = $colors['left'] ?? $default['left'];\n $right_color = $colors['right'] ?? $default['right'];\n\n $output = '
\n
';\n\n if ($shadow !== null) {\n $shadow = min($shadow, 100);\n $middle_color = $colors['middle'] ?? $default['middle'];\n $output .= '
';\n }\n\n $output .= '
\n
\n ' . $left_text . '\n ' . $right_text . '\n
';\n\n return $output;\n }", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function writeTemplateLine($selector, $dosage, $period, $quantity, $refills, $prices, $taxrates, $pkgqty)\n{\n global $tmpl_line_no;\n ++$tmpl_line_no;\n\n echo \" \\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n generate_form_field(array(\n 'data_type' => 1,\n 'field_id' => 'tmpl[' . attr($tmpl_line_no) . '][period]',\n 'list_id' => 'drug_interval',\n 'empty_title' => 'SKIP'\n ), $period);\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n /******************************************************************\n echo \" \";\n echo \"\";\n echo \"\\n\";\n ******************************************************************/\n\n foreach ($prices as $pricelevel => $price) {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n }\n\n $pres = sqlStatement(\"SELECT option_id FROM list_options \" .\n \"WHERE list_id = 'taxrate' AND activity = 1 ORDER BY seq\");\n while ($prow = sqlFetchArray($pres)) {\n echo \" \";\n echo \"\\n\";\n }\n\n echo \" \\n\";\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function writeCategoryAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis)\n {\n $objWriter->startElement('c:catAx');\n\n if ($id1 > 0) {\n $objWriter->startElement('c:axId');\n $objWriter->writeAttribute('val', $id1);\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:scaling');\n $objWriter->startElement('c:orientation');\n $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation'));\n $objWriter->endElement();\n $objWriter->endElement();\n\n $objWriter->startElement('c:delete');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n\n $objWriter->startElement('c:axPos');\n $objWriter->writeAttribute('val', \"b\");\n $objWriter->endElement();\n\n if (!is_null($xAxisLabel)) {\n $objWriter->startElement('c:title');\n $objWriter->startElement('c:tx');\n $objWriter->startElement('c:rich');\n\n $objWriter->startElement('a:bodyPr');\n $objWriter->endElement();\n\n $objWriter->startElement('a:lstStyle');\n $objWriter->endElement();\n\n $objWriter->startElement('a:p');\n $objWriter->startElement('a:r');\n\n $caption = $xAxisLabel->getCaption();\n if (is_array($caption)) {\n $caption = $caption[0];\n }\n $objWriter->startElement('a:t');\n // $objWriter->writeAttribute('xml:space', 'preserve');\n $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption));\n $objWriter->endElement();\n\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n\n $layout = $xAxisLabel->getLayout();\n $this->writeLayout($layout, $objWriter);\n\n $objWriter->startElement('c:overlay');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:numFmt');\n $objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat());\n $objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked());\n $objWriter->endElement();\n\n $objWriter->startElement('c:majorTickMark');\n $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark'));\n $objWriter->endElement();\n\n $objWriter->startElement('c:minorTickMark');\n $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark'));\n $objWriter->endElement();\n\n $objWriter->startElement('c:tickLblPos');\n $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels'));\n $objWriter->endElement();\n\n if ($id2 > 0) {\n $objWriter->startElement('c:crossAx');\n $objWriter->writeAttribute('val', $id2);\n $objWriter->endElement();\n\n $objWriter->startElement('c:crosses');\n $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses'));\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:auto');\n $objWriter->writeAttribute('val', 1);\n $objWriter->endElement();\n\n $objWriter->startElement('c:lblAlgn');\n $objWriter->writeAttribute('val', \"ctr\");\n $objWriter->endElement();\n\n $objWriter->startElement('c:lblOffset');\n $objWriter->writeAttribute('val', 100);\n $objWriter->endElement();\n\n if ($isMultiLevelSeries) {\n $objWriter->startElement('c:noMultiLvlLbl');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n }\n $objWriter->endElement();\n }", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "public function GetBlockTileData($frame, $metricId, $metricVersionId, $levelId, $urbanity, $partition, $x, $y, $z)\n\t{\n\t\t$s = App::Settings()->Map()->TileDataBlockSize;\n\t\t$blocks = [];\n\t\tfor($ix = $x; $ix < $x + $s; $ix++)\n\t\t{\n\t\t\t$row = [];\n\t\t\tfor($iy = $y; $iy < $y + $s; $iy++)\n\t\t\t{\n\t \t\t\t\t$row[$iy] = $this->GetTileData($frame, $metricId, $metricVersionId, $levelId, $urbanity, $partition, $ix, $iy, $z);\n\t\t\t}\n\t\t\t$blocks[$ix] = $row;\n\t\t}\n\t\t$ret = new TileDataInfo();\n\t\t$ret->Data = $blocks;\n\t\t$ret->EllapsedMs = GlobalTimer::EllapsedMs();\n\t\treturn $ret;\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "protected function insert_content_into_entrepot($source_id, $ref, $date_import, $ufield, $usubfield, $field_order, $subfield_order, $value, $recid, $search_id = '') {\n\t\t$query = \"insert ignore into entrepot_source_\".$source_id.\" (connector_id,source_id,ref,date_import,ufield,usubfield,field_order,subfield_order,value,i_value,recid, search_id) values(\n\t\t\t'\".addslashes($this->get_id()).\"',\".$source_id.\",'\".addslashes($ref).\"','\".addslashes($date_import).\"',\n\t\t\t'\".addslashes($ufield).\"','\".addslashes($usubfield).\"',\".$field_order.\",\".$subfield_order.\",'\".addslashes($value).\"',\n\t\t\t' \".addslashes(strip_empty_words($value)).\" ',$recid, '$search_id')\";\n\t\tpmb_mysql_query($query);\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function __getDetailSection($system, $recTypeId, $dtID, $recursion_depth, $mode, $fieldtypes, $reverseRecTypeId, $pointer_fields){\n\n global $dbs_rtStructs, $dbs_lookups;\n\n $res = null;\n\n $rtNames = $dbs_rtStructs['names'];//???need\n $rst_fi = $dbs_rtStructs['typedefs']['dtFieldNamesToIndex'];\n\n $dtValue = $dbs_rtStructs['typedefs'][$recTypeId]['dtFields'][$dtID];\n\n $detailType = $dtValue[$rst_fi['dty_Type']];\n $dt_label = $dtValue[$rst_fi['rst_DisplayName']];\n $dt_title = $dtValue[$rst_fi['rst_DisplayName']];\n $dt_tooltip = $dtValue[$rst_fi['rst_DisplayHelpText']];//help text\n\n $pref = \"\";\n //$dt_maxvalues = $dtValue[$rst_fi['rst_MaxValues']];//repeatable\n //$issingle = (is_numeric($dt_maxvalues) && intval($dt_maxvalues)==1)?\"true\":\"false\";\n\n if (($mode==3) || in_array($detailType, $fieldtypes)) //$fieldtypes - allowed types\n {\n\n switch ($detailType) {\n /* @TODO\n case 'file':\n break;\n case 'geo':\n break;\n case 'calculated':\n break;\n case 'fieldsetmarker':\n break;\n case 'relationtype':\n */\n case 'separator':\n return null;\n case 'enum':\n\n $res = array();\n if($mode==3){\n $res['children'] = array(\n array(\"text\"=>\"internalid\"),\n array(\"text\"=>\"code\"),\n array(\"text\"=>\"term\"),\n array(\"text\"=>\"conceptid\"));\n }\n break;\n\n case 'resource': // link to another record type\n case 'relmarker':\n\n $max_depth = 2;\n if ($mode==6 || $mode==4){\n $max_depth = 3;\n }elseif($mode==5){ //make it 1 for lazy load\n $max_depth = 1;\n }\n\n if($recursion_depth<$max_depth){\n\n if($reverseRecTypeId!=null){\n $res = __getRecordTypeTree($system, $recTypeId, $recursion_depth+1, $mode, $fieldtypes, $pointer_fields);\n if($res){\n $res['rt_ids'] = \"\".$recTypeId; //list of rectype - constraint\n //$res['reverse'] = \"yes\";\n $pref = ($detailType==\"resource\")?\"lf\":\"rf\";\n //before 2017-06-20 $dt_title = \" \" . $rtNames[$recTypeId] .\" \". $dt_title . \"\";\n\n $dt_title = \"<< \" . $rtNames[$recTypeId] .\" . \". $dt_title.'';\n\n if($mode==5){\n $res['lazy'] = true;\n }\n }\n }else{\n\n $pref = ($detailType==\"resource\")?\"lt\":\"rt\";\n\n $pointerRecTypeId = @$dtValue[$rst_fi['rst_PtrFilteredIDs']];\n if($pointerRecTypeId==null) {$pointerRecTypeId = '';}\n $is_required = ($dtValue[$rst_fi['rst_RequirementType']]=='required');\n $rectype_ids = explode(\",\", $pointerRecTypeId);\n\n\n if($mode==4 || $mode==5){\n /*\n if($pointerRecTypeId==\"\" || empty($rectype_ids)){ //TEMP\n $dt_title .= ' unconst';\n }\n */\n\n $dt_title = \" \" . $dt_title . \"\";\n }\n\n\n if($pointerRecTypeId==\"\" || empty($rectype_ids)){ //unconstrainded\n\n $res = __getRecordTypeTree($system, null, $recursion_depth+1, $mode, $fieldtypes, $pointer_fields);\n //$res['constraint'] = 0;\n\n }else{ //constrained pointer\n\n $res = array();\n\n\n if(is_array($rectype_ids) && count($rectype_ids)>1){\n $res['rt_ids'] = $pointerRecTypeId; //list of rectype - constraint\n $res['constraint'] = count($rectype_ids);\n if($mode!=5) {$res['children'] = array();}\n }\n if($mode==5){\n $res['rt_ids'] = $pointerRecTypeId;\n $res['lazy'] = true;\n }else{\n\n foreach($rectype_ids as $rtID){\n $rt_res = __getRecordTypeTree($system, $rtID, $recursion_depth+1, $mode, $fieldtypes, $pointer_fields);\n if(is_array($rectype_ids) && count($rectype_ids)==1){//exact one rectype constraint\n //avoid redundant level in tree\n $res = $rt_res;\n $res['constraint'] = 1;\n $res['rt_ids'] = $pointerRecTypeId; //list of rectype - constraint\n }elseif($rt_res!=null){\n array_push($res['children'], $rt_res);\n $res['constraint'] = count($rt_res);\n }\n }\n\n }\n\n }\n $res['required'] = $is_required;\n\n }\n }\n\n break;\n\n default:\n $res = array();\n }//end switch\n }\n\n if(is_array($res)){\n\n if(!@$res['code']) {$res['code'] = (($reverseRecTypeId!=null)?$reverseRecTypeId:$recTypeId).\":\".$pref.$dtID;} //(($reverseRecTypeId!=null)?$reverseRecTypeId:$recTypeId)\n $res['key'] = \"f:\".$dtID;\n if($mode==4 || $mode==5){\n\n $stype = ($detailType=='resource' || $detailType=='relmarker')?\"\":$dbs_lookups[$detailType];\n if($reverseRecTypeId!=null){\n //before 2017-06-20 $stype = $stype.\"linked from\";\n $res['isreverse'] = 1;\n }\n if($stype!=''){\n $stype = \" (\" . $stype .\")\";\n }\n\n $res['title'] = $dt_title . $stype;\n //$res['code'] =\n }else{\n $res['title'] = $dt_title;\n }\n $res['type'] = $detailType;\n $res['name'] = $dt_label;\n\n\n\n }\n return $res;\n }", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct(\n\t\t?string $outNome,\n\t\t?string $outResponsabilidade,\n\t\t?string $outCodTipoResponsabilidade,\n\t\t?string $outLogin,\n\t\t?string $outCPF,\n\t\t?string $outRGRNM,\n\t\t?string $outTipoOrigem,\n\t\t?string $outNRRG,\n\t\t?string $outDigitoRG,\n\t\t?string $outUFRG,\n\t\t?string $outCodSexo,\n\t\t?string $outCodEstadoCivil,\n\t\t?string $outEmailResponsavel,\n\t\t?string $outDataNascimento,\n\t\t?string $outCidadeNascimento,\n\t\t?string $outUFNascimento,\n\t\t?string $outNomePaisNascimento,\n\t\t?OutEnderecoResidencial $outEnderecoResidencial,\n\t\t?array $outLstTelefone\n\t) {\n\t\t$this->outNome = $outNome;\n\t\t$this->outResponsabilidade = $outResponsabilidade;\n\t\t$this->outCodTipoResponsabilidade = $outCodTipoResponsabilidade;\n\t\t$this->outLogin = $outLogin;\n\t\t$this->outCPF = $outCPF;\n\t\t$this->outRGRNM = $outRGRNM;\n\t\t$this->outTipoOrigem = $outTipoOrigem;\n\t\t$this->outNRRG = $outNRRG;\n\t\t$this->outDigitoRG = $outDigitoRG;\n\t\t$this->outUFRG = $outUFRG;\n\t\t$this->outCodSexo = $outCodSexo;\n\t\t$this->outCodEstadoCivil = $outCodEstadoCivil;\n\t\t$this->outEmailResponsavel = $outEmailResponsavel;\n\t\t$this->outDataNascimento = $outDataNascimento;\n\t\t$this->outCidadeNascimento = $outCidadeNascimento;\n\t\t$this->outUFNascimento = $outUFNascimento;\n\t\t$this->outNomePaisNascimento = $outNomePaisNascimento;\n\t\t$this->outEnderecoResidencial = $outEnderecoResidencial;\n\t\t$this->outLstTelefone = $outLstTelefone;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(\n CategoryFacade $categoryFacade,\n FlagFacade $flagFacade,\n BrandFacade $brandFacade,\n ProductElasticsearchProvider $productElasticsearchProvider,\n ParameterWithValuesFactory $parameterWithValuesFactory,\n ProductFrontendLimitProvider $productFrontendLimitProvider,\n DataLoaderInterface $productsSellableByIdsBatchLoader,\n CurrentCustomerUser $currentCustomerUser,\n private DataLoaderInterface $categoriesBatchLoader,\n private DataLoaderInterface $flagsBatchLoader,\n private DataLoaderInterface $brandsBatchLoader,\n ) {\n parent::__construct(\n $categoryFacade,\n $flagFacade,\n $brandFacade,\n $productElasticsearchProvider,\n $parameterWithValuesFactory,\n $productFrontendLimitProvider,\n $productsSellableByIdsBatchLoader,\n $currentCustomerUser,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function addObjectWordLink(\n int $wordId,\n int $contentId,\n float $frequency,\n int $placement,\n int $nextWordId,\n int $prevWordId,\n int $contentTypeId,\n int $fieldTypeId,\n int $published,\n int $sectionId,\n string $identifier,\n int $integerValue,\n int $languageMask\n ): void {\n $query = $this->connection->createQueryBuilder();\n $query\n ->insert(self::SEARCH_OBJECT_WORD_LINK_TABLE)\n ->values(\n [\n 'word_id' => $query->createPositionalParameter($wordId, ParameterType::INTEGER),\n 'contentobject_id' => $query->createPositionalParameter(\n $contentId,\n ParameterType::INTEGER\n ),\n 'frequency' => $query->createPositionalParameter($frequency),\n 'placement' => $query->createPositionalParameter(\n $placement,\n ParameterType::INTEGER\n ),\n 'next_word_id' => $query->createPositionalParameter(\n $nextWordId,\n ParameterType::INTEGER\n ),\n 'prev_word_id' => $query->createPositionalParameter(\n $prevWordId,\n ParameterType::INTEGER\n ),\n 'contentclass_id' => $query->createPositionalParameter(\n $contentTypeId,\n ParameterType::INTEGER\n ),\n 'contentclass_attribute_id' => $query->createPositionalParameter(\n $fieldTypeId,\n ParameterType::INTEGER\n ),\n 'published' => $query->createPositionalParameter(\n $published,\n ParameterType::INTEGER\n ),\n 'section_id' => $query->createPositionalParameter(\n $sectionId,\n ParameterType::INTEGER\n ),\n 'identifier' => $query->createPositionalParameter(\n $identifier,\n ParameterType::STRING\n ),\n 'integer_value' => $query->createPositionalParameter(\n $integerValue,\n ParameterType::INTEGER\n ),\n 'language_mask' => $query->createPositionalParameter(\n $languageMask,\n ParameterType::INTEGER\n ),\n ]\n );\n\n $query->execute();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function getTitres(\n\t $issns = [],\n\t $mirabel_titre_ids = [],\n\t $mirabel_revue_ids = [],\n\t $sudoc_ppn_ids = [],\n\t $worldcat_ids = [],\n\t $titre = '',\n\t $actif = false,\n\t $offset = 0\n\t )\n\t{\n\t $this->resetErrors();\n\t $this->resetResult();\n\t $this->curl_params = [];\n\t \n\t //issn\n\t $tmp = [];\n\t if( is_array($issns) && !empty($issns) ) {\n\t foreach($issns as $v) {\n\t $v = trim($v);\n\t if ($v) {\n\t $tmp[] = $v;\n\t }\n\t }\n\t }\n\t if( !empty($tmp) ) {\n\t $this->curl_params['issn'] = implode(',', $tmp);\n\t }\n\t \n\t //id\n\t $tmp = [];\n\t if( is_array($mirabel_titre_ids) && !empty($mirabel_titre_ids) ) {\n\t foreach($mirabel_titre_ids as $v) {\n\t $v = intval($v);\n\t if ($v) {\n\t $tmp[] = $v;\n\t }\n\t }\n\t }\n\t if(!empty($tmp)) {\n\t $this->curl_params['id'] = implode(',', $tmp);\n\t }\n\t \n\t //revueid\n\t $tmp = [];\n\t if( is_array($mirabel_revue_ids) && !empty($mirabel_revue_ids) ) {\n\t foreach($mirabel_revue_ids as $v) {\n\t $v = intval($v);\n\t if ($v) {\n\t $tmp[] = $v;\n\t }\n\t }\n\t }\n\t if(!empty($tmp)) {\n\t $this->curl_params['revueid'] = implode(',', $tmp);\n\t }\n\t \n\t //sudoc\n\t $tmp = [];\n\t if( is_array($sudoc_ppn_ids) && !empty($sudoc_ppn_ids) ) {\n\t foreach($sudoc_ppn_ids as $v) {\n\t $v = intval($v);\n\t if ($v) {\n\t $tmp[] = $v;\n\t }\n\t }\n\t }\n\t if(!empty($tmp)) {\n\t $this->curl_params['sudoc'] = implode(',', $tmp);\n\t }\n\t \n\t //worldcat\n\t $tmp = [];\n\t if( is_array($worldcat_ids) && !empty($worldcat_ids) ) {\n\t foreach($worldcat_ids as $v) {\n\t $v = intval($v);\n\t if ($v) {\n\t $tmp[] = $v;\n\t }\n\t }\n\t }\n\t if(!empty($tmp)) {\n\t $this->curl_params['worldcat'] = implode(',', $tmp);\n\t }\n\t \n\t //titre\n\t $tmp = '';\n\t if( is_string($titre)) {\n\t $tmp = trim ($titre);\n\t }\n\t if( !empty($tmp) ) {\n\t $this->curl_params['titre'] = implode(',', $tmp);\n\t }\n\t \n\t //actif\n\t if($actif) {\n\t $this->curl_params['actif'] = 1;\n\t }\n\t \n\t $offset = intval($offset);\n\t if($offset) {\n\t $this->curl_params['offset'] = $offset;\n\t }\n\t \n\t $this->curl_url = $this->api_url.\"/titres\";\n\t $this->sendRequest();\n\t \n\t if($this->error) {\n\t return false;\n\t }\n\t \n\t $response_body = json_decode($this->curl_response->body, true);\n\t \n\t if(is_null($response_body)) {\n\t $this->error = true;\n\t $this->error_msg[] = 'search => json response error';\n\t return false;\n\t }\n\t if(empty($response_body)) {\n\t $this->error = true;\n\t $this->error_msg[] = 'search => no result provided';\n\t return false;\n\t }\n\t $this->result = $response_body;\n\t return true;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function ajoutReglement($nom, $date, $type, $transaction, $banque, $montant, $commentaire, $eleves, $dons, $adhesion_caf, $adhesion_tarif_plein, $soutien)\n\t{\n\t\t$req = \"INSERT INTO quetigny_info_reglements (SOUTIEN, ADESION_CAF, ADESION_TARIF_PLEIN, STAGE, SORTIE_STAGE, DONS)\n VALUES (:soutien, :adhesion_caf, :adhesion_tarif_plein, 0, 0, :dons);\n \n SET @info_reglement_id = LAST_INSERT_ID();\n \n INSERT INTO quetigny_reglements (ID_INFO_REGLEMENT, ID_APPARTIENT_RCAF, ID_APPARTIENT_RCHEQUE, ID_TYPEREGLEMENT, NUMTRANSACTION, BANQUE, TRANSFERERTRESORIER, DATE_REGLEMENT, MONTANT, COMMENTAIRES, NOMREGLEMENT)\n VALUES (@info_reglement_id, NULL, NULL, :type, :transaction, :banque, 0, :date, :montant, :commentaire, :nom);\n \n SET @reglement_id = LAST_INSERT_ID();\n \n INSERT INTO quetigny_reglements_eleves (ID_REGLEMENT, ID_ELEVE) VALUES \";\n\t\t$params = array(\n\t\t\t':soutien' => $soutien,\n\t\t\t':adhesion_caf' => $adhesion_caf,\n\t\t\t':adhesion_tarif_plein' => $adhesion_tarif_plein,\n\t\t\t':dons' => $dons,\n\t\t\t':type' => $type,\n\t\t\t':transaction' => $transaction,\n\t\t\t':banque' => $banque,\n\t\t\t':date' => $date,\n\t\t\t':montant' => $montant,\n\t\t\t':commentaire' => $commentaire,\n\t\t\t':nom' => $nom\n\t\t);\n\n\t\t$values = array();\n\t\tforeach ($eleves as $eleve) {\n\t\t\t$eleve = (int)$eleve;\n\t\t\t$values[] = \"(@reglement_id, :eleve$eleve)\";\n\t\t\t$params[\":eleve$eleve\"] = $eleve;\n\t\t}\n\t\t$req .= implode(\", \", $values) . \";\";\n\n\t\t$rs = $this->NonQuery($req, $params);\n\t\tif ($rs === false) {\n\t\t\tafficherErreurSQL(\"Probl\u00e8me lors de l'insertion des donn\u00e9es dans la base de donn\u00e9es.\", $req, PdoBD::$monPdo->errorInfo());\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function processRequestAndSaveJobEvent(\n Partner $partner,\n string $url,\n string $jobAction,\n string $jobMessage = '',\n ?int $signalementId = null,\n array $payload = [],\n string $requestMethod = 'POST',\n string $contentType = 'application/json',\n ): JobEvent {\n try {\n $token = $this->getToken($partner);\n $response = $this->request($url, $payload, $token, $requestMethod, $contentType);\n $statusCode = $response->getStatusCode();\n $status = Response::HTTP_OK === $statusCode ? JobEvent::STATUS_SUCCESS : JobEvent::STATUS_FAILED;\n $responseContent = $response->getContent(throw: false);\n } catch (\\Exception $e) {\n $responseContent = $e->getMessage();\n $status = JobEvent::STATUS_FAILED;\n $statusCode = 9999;\n }\n\n return $this->jobEventManager->createJobEvent(\n service: self::TYPE_SERVICE,\n action: $jobAction,\n message: $jobMessage,\n response: $responseContent,\n status: $status,\n codeStatus: $statusCode,\n signalementId: $signalementId,\n partnerId: $partner->getId(),\n partnerType: $partner->getType(),\n );\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function generateLabelOrderContent($batchInfo, $batchControlNames, $samplesResult, $samplesCount, $primaryKeyColumn, $patientIdColumn, $table, $testType)\n {\n $labelNewContent = '';\n $displayOrder = [];\n $alphaNumeric = $this->generateAlphaNumericRange();\n $jsonToArray = json_decode((string)$batchInfo['label_order'], true);\n $batchControlNames ??= [];\n $content = '';\n $controls = '';\n if (!empty($jsonToArray) && (count($jsonToArray) != ($samplesCount + count($batchControlNames)))) {\n foreach ($samplesResult as $sample) {\n $displayOrder[] = \"s_\" . $sample[$primaryKeyColumn];\n $label = $sample['sample_code'] . \" - \" . $sample[$patientIdColumn];\n $content .= '
  • ' . $label . '
  • ';\n }\n if (!empty($batchControlNames) && count($batchControlNames) > 0) {\n foreach ($batchControlNames as $key => $value) {\n $displayOrder[] = $value;\n $clabel = str_replace(\"in house\", \"In-House\", $value);\n $clabel = str_replace(\"no of \", \" \", $clabel);\n $existingValue = $batchControlNames[$key] ?? \"\";\n $liLabel = $existingValue ?: $clabel;\n $controls .= '
  • ' . $liLabel . '
  • ';\n $labelNewContent .= ' ' . $liLabel . ' : ';\n }\n } else {\n $labelControls = preg_grep(\"/^no_of_/i\", $jsonToArray);\n foreach ($labelControls as $value) {\n $displayOrder[] = $value;\n $clabel = $this->formatLabel($value);\n $controls .= '
  • ' . $clabel . '
  • ';\n $labelNewContent .= ' ' . $clabel . ' : ';\n }\n }\n } else {\n $controls = '';\n foreach ($jsonToArray as $j => $jsonValue) {\n $index = ($batchInfo['position_type'] == 'alpha-numeric') ? $alphaNumeric[$j] : $j;\n $displayOrder[] = $jsonValue;\n $xplodJsonToArray = explode(\"_\", (string)$jsonValue);\n\n if (count($xplodJsonToArray) > 1 && $xplodJsonToArray[0] == \"s\") {\n $sampleQuery = \"SELECT sample_code, $patientIdColumn FROM $table WHERE $primaryKeyColumn = ?\";\n $sampleResult = $this->db->rawQuery($sampleQuery, [$xplodJsonToArray[1]]);\n $label = $sampleResult[0]['sample_code'] . \" - \" . $sampleResult[0][$patientIdColumn];\n $content .= '
  • ' . $label . '
  • ';\n } else {\n $label = $this->formatLabel($jsonValue);\n $existingValue = $batchControlNames[$jsonValue] ?? \"\";\n $liLabel = $existingValue ?: $label;\n $labelNewContent .= ' ' . $jsonValue . ' : ';\n $controls .= '
  • ' . $liLabel . '
  • ';\n }\n }\n }\n\n $content = $controls . $content;\n return ['content' => $content, 'labelNewContent' => $labelNewContent, 'displayOrder' => $displayOrder];\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function editerDossierRisque($id, $ref_doc, $date_doc, $date_recept, $id_bur_douane, $id_etap, $id_sen, $date_proch_pres, $id_reg, $date_pres, $remarque, $id_cli){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['id']=$id;\n\t\t\t$entree['ref_doc']=$ref_doc;\n\t\t\t$entree['date_doc']=$date_doc;\n\t\t\t$entree['date_recept']=$date_recept;\n\t\t\t$entree['id_bur_douane']=$id_bur_douane;\n\t\t\t$entree['id_etap']=$id_etap;\n\t\t\t$entree['id_sen']=$id_sen;\n\t\t\t$entree['date_proch_pres']=$date_proch_pres;\n\t\t\t$entree['id_reg']=$id_reg;\n\t\t\t$entree['date_pres']=$date_pres;\n\t\t\t$entree['remarque']=$remarque;\n\t\t\t$entree['id_cli']=$id_cli;\n\n\t\t\tif ($entree['date_pres'] == '') {\n\t\t\t\t$entree['date_pres'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('UPDATE dossier_risque_douane\n\t\t\t\t\t\t\t\t\t\t\t\tSET ref_doc = ?, date_doc = ?, date_recept = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_bur_douane = ?, id_etap = ?, id_sen = ?, date_proch_pres = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_reg = ?, date_pres = ?, remarque = ?, id_cli = ?\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE id = ?');\n\t\t\t$requete-> execute(array($entree['ref_doc'], $entree['date_doc'], $entree['date_recept'], $entree['id_bur_douane'], $entree['id_etap'], $entree['id_sen'], $entree['date_proch_pres'], $entree['id_reg'], $entree['date_pres'], $entree['remarque'], $entree['id_cli'], $entree['id']));\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public static function transfer($currency_name, $chain_currency, $to_address, $transfer_qty, $from_address, $from_private_key, $type, $fee = 0, $verificationcode = '')\n {\n try {\n $currency = Currency::where('name', $currency_name)->first();\n $chain_currency = Currency::where('name', $chain_currency)->first();\n if (!$currency) {\n throw new \\Exception('\u8d27\u5e01\u4e0d\u5b58\u5728');\n }\n if (!in_array($currency->type, ['eth', 'erc20', 'usdt', 'btc'])) {\n throw new \\Exception('\u8d27\u5e01\u7c7b\u578b\u4e0d\u652f\u6301');\n }\n if (\n empty($to_address) \n || empty($transfer_qty)\n || bc_comp($transfer_qty, 0) <= 0\n || empty($from_address)\n || empty($from_private_key)\n ) {\n throw new \\Exception('\u53c2\u6570\u4e0d\u5b8c\u6574\u6216\u4e0d\u5408\u6cd5');\n }\n $origin_transfer_qty = $transfer_qty;\n $decimal_scale = $chain_currency->decimal_scale ?? 0; //\u8c03\u6574\u4e3a\u6309\u94fe\u4e0a\u901a\u9053\u7684\u5c0f\u6570\u4f4d\u6570\uff0c\u89e3\u51b3\u4ee3\u5e01\u548c\u4e3b\u94fe\u5c0f\u6570\u4f4d\u6570\u4e0d\u4e00\u81f4\u7684\u95ee\u9898\n $lessen = bc_pow(10, $decimal_scale);\n $transfer_qty = bc_mul($transfer_qty, $lessen, 0); //\u8f6c\u8d26\u6570\u91cf\u8f6c\u6362\u4e3a\u533a\u5757\u94fe\u4e0a\u7684\u5355\u4f4d\n $fee = bc_mul($currency->chain_fee, $lessen, 0); //\u624b\u7eed\u8d39\u8f6c\u6362\u4e3a\u533a\u57df\u94fe\u4e0a\u7684\u5355\u4f4d\n $http_client = app('LbxChainServer');\n $method = 'POST';\n $result = [];\n $params = [\n 'multipart' => [\n [\n 'name' => 'type',\n 'contents' => $type,\n ],\n [\n 'name' => 'fromaddress',\n 'contents' => $from_address,\n ],\n [\n 'name' => 'privkey',\n 'contents' => $from_private_key,\n ],\n [\n 'name' => 'toaddress',\n 'contents' => $to_address,\n ],\n [\n 'name' => 'amount',\n 'contents' => $transfer_qty,\n ],\n [\n 'name' => 'tokenaddress',\n 'contents' => $currency->contract_address ?? '',\n ],\n [\n 'name' => 'fee',\n 'contents' => $fee,\n ],\n [\n 'name' => 'verificationcode',\n 'contents' => $verificationcode,\n ],\n ]\n ];\n switch ($chain_currency->type) {\n case 'erc20':\n $uri = '/v3/wallet/eth/tokensendto';\n break;\n case 'eth':\n $uri = '/v3/wallet/eth/sendto';\n break;\n case 'btc':\n $uri = '/v3/wallet/btc/sendto';\n break; \n case 'usdt':\n $uri = '/v3/wallet/usdt/sendto';\n break;\n default:\n throw new \\Exception('\u6682\u4e0d\u652f\u6301' . $chain_currency->type . '\u5e01\u79cd');\n break;\n }\n\n $response = $http_client->request($method, $uri, $params);\n $result = json_decode($response->getBody()->getContents(), true); \n isset($result['txid']) || $result['txid'] = $result['data']['txHex'] ?? ($result['data']['txid'] ?? '');\n if (isset($result['code']) && $result['code'] == 0) {\n $chain_hash = [\n 'code' => strtoupper($currency->type),\n 'txid' => $result['txid'],\n 'amount' => $origin_transfer_qty,\n 'sender' => $from_address,\n 'recipient' => $to_address,\n ];\n ChainHash::unguarded(function () use ($chain_hash) {\n return ChainHash::create($chain_hash);\n });\n } else {\n throw new \\Exception($result['msg'] ?? var_export($result, true));\n }\n //dump($params);\n return $result;\n } catch (\\Exception $e) {\n throw $e;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public function process_actions($id_serialcirc,$expl_id,$subscription=0,$ask_transmission=0,$report_late=0,$trans_accepted=0,$trans_doc_accepted=0,$ret_accepted=0){\n\t\t$id_serialcirc = intval($id_serialcirc);\n\t\t$expl_id = intval($expl_id);\n\n\t\t$empr_circ = new serialcirc_empr_circ($this->empr_id,$id_serialcirc,$expl_id);\n\t\tif($subscription==1){\n\t\t\t$empr_circ->subscribe();\n\t\t}else if($ask_transmission==1){\n\t\t\t$empr_circ->ask_transmission();\n\t\t}else if ($report_late == 1){\n\t\t\t$empr_circ->report_late();\n\t\t}else if ($trans_accepted == 1){\n\t\t\t$empr_circ->accept_transmission();\n\t\t}else if ($trans_doc_accepted == 1){\n\t\t\t$empr_circ->accept_transmission_doc();\n\t\t}else if($ret_accepted == 1){\n\t\t\t$empr_circ->accept_ret();\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function afficherSearchFileKBP($debut, $fin, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_march=NULL, $statut=NULL, $num_lic=NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$cleared=NULL){\n\t\t\tinclude(\"connexion.php\");\n\t\t\t$entree['debut'] = $debut;\n\t\t\t$entree['fin'] = $fin;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t\n\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t$sqlClient = ' AND d.id_cli = \"'.$id_cli.'\"';\n\t\t\t}else{\n\t\t\t\t$sqlClient = '';\n\t\t\t}\n\n\t\t\t$compteur = 0;\n\t\t\t$ligne = '';\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.ref_dos AS ref_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPPER(cl.nom_cli) AS nom_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.ref_fact AS ref_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fob AS fob_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fret AS fret,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.assurance AS assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.autre_frais AS autre_frais,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.num_lic AS num_lic,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.montant_decl AS montant_decl,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.*,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.supplier AS fournisseur,\n\t\t\t\t\t\t\t\t\t\t\t\t\ts.nom_site AS nom_site,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_in AS dgda_in_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_out AS dgda_out_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.custom_deliv AS custom_deliv_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.arrival_date AS arrival_date_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcl.id_cli AS id_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcl.code_cli AS code_cli,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_lic='2' AND d.id_mod_trans='1',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING INSURANCE',\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_decl IS NULL AND d.ref_decl IS NULL, 'UNDER PREPARATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_liq IS NULL AND d.ref_liq IS NULL, 'AWAITING LIQUIDATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NULL AND d.ref_quit IS NULL, 'AWAITING QUITTANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NOT NULL AND d.ref_quit IS NOT NULL AND d.dgda_out IS NULL, 'AWAITING BAE/BS', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.dgda_out IS NOT NULL AND d.dispatch_deliv IS NOT NULL, 'CLEARING COMPLETED', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\td.statut) AS statut,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.klsa_arriv IS NOT NULL AND d.wiski_arriv IS NULL,'ARRIVED AT K\\'LSA', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.wiski_arriv IS NOT NULL AND d.dispatch_klsa IS NULL, 'AT WISKI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.dispatch_klsa IS NOT NULL, 'DISPATCHED FROM K\\'LSA', 'EXCEPTED TO ARRIVE')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t, '') AS klsa_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.bond_warehouse='LUBUMBASHI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL AND d.warehouse_dep IS NOT NULL, 'DISPATCHED FROM AMICONGO', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL, 'ARRIVED AT AMICONGO', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'') AS amicongo_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.bond_warehouse='KOLWEZI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL AND d.warehouse_dep IS NOT NULL, 'DISPATCHED FROM WAREHOUSE', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL, 'ARRIVED AT WAREHOUSE', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'') AS kzi_status,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.dgda_out, d.dgda_in) AS dgda_delay,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.custom_deliv, d.arrival_date) AS arrival_deliver_delay\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND (d.date_preal BETWEEN ? AND ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.klsa_arriv IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\tORDER BY d.date_creat_dos ASC\");\n\t\t\t$requete-> execute(array($entree['id_mod_lic'], $entree['debut'], $entree['fin'], $entree['id_mod_trans']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t$compteur++;\n\t\t\t\t$bg = \"\";\n\t\t\t\t$color='';\n\t\t\t\t$class = \"\";\n\n\t\t\t\tif ($reponse['cleared'] == '1') {\n\t\t\t\t\t$style = \"style='color: blue;'\";\n\t\t\t\t\t$color = \"color: blue;\";\n\t\t\t\t\t$class = \"bg-primary\";\n\t\t\t\t}else if ($reponse['cleared'] == '2') {\n\t\t\t\t\t$style = \"style='color: red;'\";\n\t\t\t\t\t$color = \"color: red;\";\n\t\t\t\t\t$class = \"bg-danger\";\n\t\t\t\t}else{\n\t\t\t\t\t$style = \"\";\n\t\t\t\t\t$color = \"\";\n\t\t\t\t\t$class = \"\";\n\t\t\t\t}\n\n\t\t\t\t$date_exp = $this-> getLastEpirationLicence($reponse['num_lic']);\n\t\t\t\t$supplier = $this-> getLicence($reponse['num_lic'])['fournisseur'];\n\n\t\t\t\tif (isset($supplier)) {\n\t\t\t\t\t$reponse['fournisseur'] = $supplier;\n\t\t\t\t}\n\n\t\t\t\t//include('modalDeleteDossier.php');\n\t\t\t\t\n\n\t\t\t?>\n\t\t\t\t\">\n\t\t\t\t\n\t\t\t\t\" value=\"\">\n\t\t\t\t\" >\n\t\t\t\t\t \" style=\" vertical-align: middle; text-align: left; padding: 0.6rem;\" >\n\t\t\t\t\t \" style=\" vertical-align: middle; text-align: left; padding: 0.6rem;\" >\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t afficherRowTableau($id_mod_lic, $reponse['id_cli'], $id_mod_trans, $reponse['id_dos'], $compteur, $reponse['statut'], $reponse['klsa_status'], $reponse['amicongo_status'], $reponse['kzi_status']);\n\t\t\t\t\t\t/*if ($id_mod_trans == '1') {\n\t\t\t\t\t\t\tinclude('importRouteRow.php');\n\t\t\t\t\t\t}else if ($id_mod_trans == '3') {\n\t\t\t\t\t\t\tinclude('importAirRow.php');\n\t\t\t\t\t\t}*/\n\t\t\t\t\t?>\n\t\t\t\t\n\t\t\t closeCursor();\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n ?int $outAnoLetivo,\n ?int $outCodEscola,\n ?string $outNomeEscola,\n ?int $outCodUnidade,\n ?int $outCodTipoClasse,\n ?int $outCodTurno,\n ?string $outDescricaoTurno,\n ?string $outTurma,\n ?string $outDescricaoTurma,\n ?int $outNrCapacidadeFisicaMaxima,\n ?int $outNrAlunosAtivos,\n ?string $outDataInicioAula,\n ?string $outDataFimAula,\n ?string $outHorarioInicioAula,\n ?string $outHorarioFimAula,\n ?int $outCodDuracao,\n ?int $outCodHabilitacao,\n ?array $outAtividadesComplementar,\n ?int $outCodTipoEnsino,\n ?string $outNomeTipoEnsino,\n ?string $outNumeroSala,\n ?int $outCodSerieAno,\n ?string $outDescricaoSerieAno,\n ?OutDiasSemana $outDiasSemana,\n ?int $outProcessoID\n )\n {\n $this->outAnoLetivo = $outAnoLetivo;\n $this->outCodEscola = $outCodEscola;\n $this->outNomeEscola = $outNomeEscola;\n $this->outCodUnidade = $outCodUnidade;\n $this->outCodTipoClasse = $outCodTipoClasse;\n $this->outCodTurno = $outCodTurno;\n $this->outDescricaoTurno = $outDescricaoTurno;\n $this->outTurma = $outTurma;\n $this->outDescricaoTurma = $outDescricaoTurma;\n $this->outNrCapacidadeFisicaMaxima = $outNrCapacidadeFisicaMaxima;\n $this->outNrAlunosAtivos = $outNrAlunosAtivos;\n $this->outDataInicioAula = $outDataInicioAula;\n $this->outDataFimAula = $outDataFimAula;\n $this->outHorarioInicioAula = $outHorarioInicioAula;\n $this->outHorarioFimAula = $outHorarioFimAula;\n $this->outCodDuracao = $outCodDuracao;\n $this->outCodHabilitacao = $outCodHabilitacao;\n $this->outAtividadesComplementar = $outAtividadesComplementar;\n $this->outCodTipoEnsino = $outCodTipoEnsino;\n $this->outNomeTipoEnsino = $outNomeTipoEnsino;\n $this->outNumeroSala = $outNumeroSala;\n $this->outCodSerieAno = $outCodSerieAno;\n $this->outDescricaoSerieAno = $outDescricaoSerieAno;\n $this->outDiasSemana = $outDiasSemana;\n $this->outProcessoID = $outProcessoID;\n }", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(\n MenuItemFactoryInterface $factory,\n EventDispatcherInterface $eventDispatcher,\n PermissionResolver $permissionResolver,\n ConfigResolver $udwConfigResolver,\n ConfigResolverInterface $configResolver,\n LocationService $locationService,\n UniversalDiscoveryExtension $udwExtension,\n SiteaccessResolverInterface $siteaccessResolver,\n LimitationResolverInterface $limitationResolver\n ) {\n parent::__construct($factory, $eventDispatcher);\n\n $this->permissionResolver = $permissionResolver;\n $this->configResolver = $configResolver;\n $this->udwConfigResolver = $udwConfigResolver;\n $this->locationService = $locationService;\n $this->udwExtension = $udwExtension;\n $this->siteaccessResolver = $siteaccessResolver;\n $this->limitationResolver = $limitationResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function doSync($id_connector, $id_source,$auto_import = false, $id_tache='', $callback_listen_command=NULL, $callback_deals_command=NULL, $auto_delete = false, $not_in_notices_externes=false, $date_start='',$date_end='') {\n\t\tglobal $base_path, $msg;\n\t\tglobal $pmb_notice_controle_doublons;\n\t\t\n\t\tif (!$this->has_user_rights(ADMINISTRATION_AUTH)) {\n\t\t return array();\n\t\t}\n\t\t$id_source = intval($id_source);\n\t\t$id_tache = intval($id_tache);\n\t\tif ((!$id_connector) || (!$id_source)) {\n\t\t\treturn array();\n\t\t}\n\t\t$this->clear_error();\n\t\t\n\t\t$this->callback_listen_command = $callback_listen_command;\n\t\t$this->callback_deals_command = $callback_deals_command;\n\t\t$result_dosync=array();\n\t\t$this->id_source = $id_source;\n\t\t$this->id_tache = $id_tache;\n\t\t\n\t\t$contrs=new connecteurs();\n\t\trequire_once($base_path.\"/admin/connecteurs/in/\".$contrs->catalog[$id_connector][\"PATH\"].\"/\".$contrs->catalog[$id_connector][\"NAME\"].\".class.php\");\n\t\teval(\"\\$conn=new \".$contrs->catalog[$id_connector][\"NAME\"].\"(\\\"\".$base_path.\"/admin/connecteurs/in/\".$contrs->catalog[$id_connector][\"PATH\"].\"\\\");\");\n\t\t\n\t\t//Vrification qu'il n'y a pas de synchronisation en cours...\n\t\t$is_already_sync=false;\n\t\t$recover_env=\"\";\n\t\t$recover=false;\n\t\t$requete=\"select * from source_sync where source_id=$id_source\";\n\t\t$resultat=pmb_mysql_query($requete);\n\t\tif (pmb_mysql_num_rows($resultat)) {\n\t\t\t$rs_s=pmb_mysql_fetch_object($resultat);\n\t\t\tif (!$rs_s->cancel) {\n\t\t\t\t$result_dosync[] = $msg[\"connecteurs_sync_currentexists\"];\n\t\t\t\t$is_already_sync=true;\n\t\t\t} else {\n\t\t\t\t$recover=true;\n\t\t\t\t$recover_env=$rs_s->env;\n\t\t\t\t$env = array();\n\t\t\t}\n\t\t} else {\n\t\t\tglobal $form_from;\n\t\t\tglobal $form_until;\n\t\t\tglobal $form_radio;\n\t\t\t$form_radio = 'all_notices';\n\t\t\t$form_from = '';\n\t\t\t$form_until = '';\n\t\t\t$sync_last_date = $this->get_sync_last_date($id_source);\n\t\t\tif(($date_start && $date_start == $sync_last_date) && !$date_end) {\n\t\t\t\t$form_radio = 'last_sync';\n\t\t\t} elseif($date_start || $date_end) {\n\t\t\t\t$form_radio = 'date_sync';\n\t\t\t\t$form_from = $date_start;\n\t\t\t\t$form_until = $date_end;\n\t\t\t}\n\t\t\t$env = $conn->get_maj_environnement($id_source);\n\t\t}\n\t\t\n\t\t//si l'import automatique est activ\n\t\t//on rcupre la liste des lments dj synchroniss pour l'import aprs synchro\n\t\tif($auto_import) {\n\t\t\t$recid_ids = $this->get_elements_already_sync($id_source);\n\t\t}\n\t\t\n\t\tif (!$is_already_sync) {\n\t\t\tif (!$recover) {\n\t\t\t\t$requete=\"insert into source_sync (source_id,nrecu,ntotal,date_sync) values($id_source,0,0,now())\";\n\t\t\t\t$r=pmb_mysql_query($requete);\n\t\t\t} \n\t\t\telse {\n\t\t\t\t$requete=\"update source_sync set cancel=0 where source_id=$id_source\";\n\t\t\t\t$r=pmb_mysql_query($requete);\n\t\t\t}\n\t\t\tif ($r) {\n\t\t\t\t$n_maj=$conn->maj_entrepot($id_source,array(&$this,\"callback_progress\"),$recover,$recover_env);\n\n\t\t\t\t$result_dosync[] = sprintf($msg[\"connecteurs_count_notices\"],$n_maj);\n\t\t\t\tif (!$conn->error) {\n\t\t\t\t\t$this->callback_progress(1);\n\t\t\t\t\t$percent = 1;\n\t\t\t\t\t$requete=\"update source_sync set percent=\".round($percent*100).\" where source_id=$id_source\";\n\t\t\t\t\t$r=pmb_mysql_query($requete);\n\t\t\n\t\t\t\t\t$requete=\"delete from source_sync where source_id=\".$id_source;\n\t\t\t\t\tpmb_mysql_query($requete);\n\t\t\t\t\t$requete=\"update connectors_sources set last_sync_date=now() where source_id=\".$id_source;\n\t\t\t\t\tpmb_mysql_query($requete);\n\t\t\t\t} else {\n\t\t\t\t\tif ($conn->break_maj($id_source)) {\n\t\t\t\t\t\t$requete=\"delete from source_sync where source_id=\".$id_source;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$requete=\"update source_sync set cancel=2 where source_id=\".$id_source;\n\t\t\t\t\t}\n\t\t\t\t\tpmb_mysql_query($requete);\n\t\t\t\t\t$result_dosync[] = $conn->error_message;\n\t\t\t\t\t//Recopie du message d'erreur sur la proprit de la classe\n\t\t\t\t\t$this->set_error($conn->error_message);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t $this->set_error(pmb_mysql_error());\n\t\t\t $result_dosync[] = $this->error_message;\n\t\t\t}\n\t\t} else {\n\t\t $result_dosync[] = $msg[\"connecteurs_sync_currentexists\"];\n\t\t}\n\t\n\t\t//si l'import automatique est activ\n\t\tif($auto_import/* && !$auto_import*/){\n\t\t\t//on va chercher les notices non intgres\n\t\t\t$query = \"select distinct entrepot_source_\".$id_source.\".recid from entrepot_source_\".$id_source.\" where concat(connector_id,' \".$id_source.\" ',ref) not in(select recid from notices_externes)\";\n\t\t\tif(count($recid_ids)) {\n\t\t\t\t$query .= \" AND entrepot_source_\".$id_source.\".recid not in (\".implode(',', $recid_ids).\")\";\n\t\t\t}\n\t\t\t$result = pmb_mysql_query($query);\n\t\t\tif(pmb_mysql_num_rows($result)){\n\t\t\t\twhile ($row = pmb_mysql_fetch_object($result)){\n\t\t\t\t\t$infos=entrepot_to_unimarc($row->recid);\n\t\t\t\t\t\n\t\t\t\t\tif($infos['notice']){\n\t\t\t\t\t\t$z=new z3950_notice(\"unimarc\",$infos['notice'],$infos['source_id']);\n\t\t\t\t\t\tif($pmb_notice_controle_doublons != 0){\n\t\t\t\t\t\t\t$sign = new notice_doublon(true,$infos['source_id']);\n\t\t\t\t\t\t\t$signature = $sign->gen_signature($row->recid);\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t$signature = \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$z->signature = $signature;\n\t\t\t\t\t\tif($infos['notice']) $z->notice = $infos['notice'];\n\t\t\t\t\t\tif($infos['source_id']) $z->source_id = $infos['source_id'];\n\t\t\t\t\t\t$z->var_to_post();\n\t\t\t\t\t\t$ret=$z->insert_in_database();\n\t\t\t\t\t\t$id_notice = $ret[1];\n\t\t\t\t\t\t$rqt = \"select recid from external_count where rid = '$row->recid'\";\n\t\t\t\t\t\t$res = pmb_mysql_query($rqt);\n\t\t\t\t\t\tif(!isset($recid)) $recid = '';\n\t\t\t\t\t\tif(pmb_mysql_num_rows($res)) $recid = pmb_mysql_result($res,0,0);\n\t\t\t\t\t\tif(!$not_in_notices_externes){\n\t\t\t\t\t\t\t$req= \"insert into notices_externes set num_notice = '\".$id_notice.\"', recid = '\".$recid.\"'\";\n\t\t\t\t\t\t\tpmb_mysql_query($req);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!$conn->error && $auto_delete) {\n\t\t\t\t// On gre la suppression des notices qui ne sont plus prsentes dans l'entrept\n\t\t\t\t$query = \"select distinct num_notice \n\t\t\t\t\t\tfrom notices_externes \n\t\t\t\t\t\tleft join external_count on notices_externes.recid = external_count.recid \n\t\t\t\t\t\twhere rid is null and notices_externes.recid like '% \".$id_source.\" %'\";\n\t\t\t\t$result = pmb_mysql_query($query);\n\t\t\t\tif ($result && pmb_mysql_num_rows($result)) {\n\t\t\t\t\twhile ($row = pmb_mysql_fetch_object($result)) {\n\t\t\t\t\t\t// suppression de la notice\n\t\t\t\t\t\tnotice::del_notice($row->num_notice);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $result_dosync;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {\n\t\t// 1. create addressbook\n\t\t$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);\n\t\t$addressBookId = $book['id'];\n\n\t\t// 2. query changes\n\t\ttry {\n\t\t\t$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);\n\t\t} catch (ClientExceptionInterface $ex) {\n\t\t\tif ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {\n\t\t\t\t// remote server revoked access to the address book, remove it\n\t\t\t\t$this->backend->deleteAddressBook($addressBookId);\n\t\t\t\t$this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);\n\t\t\t\tthrow $ex;\n\t\t\t}\n\t\t\t$this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);\n\t\t\tthrow $ex;\n\t\t}\n\n\t\t// 3. apply changes\n\t\t// TODO: use multi-get for download\n\t\tforeach ($response['response'] as $resource => $status) {\n\t\t\t$cardUri = basename($resource);\n\t\t\tif (isset($status[200])) {\n\t\t\t\t$vCard = $this->download($url, $userName, $sharedSecret, $resource);\n\t\t\t\t$this->atomic(function () use ($addressBookId, $cardUri, $vCard) {\n\t\t\t\t\t$existingCard = $this->backend->getCard($addressBookId, $cardUri);\n\t\t\t\t\tif ($existingCard === false) {\n\t\t\t\t\t\t$this->backend->createCard($addressBookId, $cardUri, $vCard);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->backend->updateCard($addressBookId, $cardUri, $vCard);\n\t\t\t\t\t}\n\t\t\t\t}, $this->dbConnection);\n\t\t\t} else {\n\t\t\t\t$this->backend->deleteCard($addressBookId, $cardUri);\n\t\t\t}\n\t\t}\n\n\t\treturn $response['token'];\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function generateContent($samplesResult, $batchInfo, $batchControlNames, $configControl, $samplesCount, $table, $primaryKeyColumn, $patientIdColumn, $testType, $orderBy, $id)\n {\n $content = '';\n $labelNewContent = '';\n $displayOrder = [];\n if (isset($batchInfo['label_order']) && trim((string)$batchInfo['label_order']) != '') {\n $contentData = $this->generateLabelOrderContent($batchInfo, $batchControlNames, $samplesResult, $samplesCount, $primaryKeyColumn, $patientIdColumn, $table, $testType);\n $content = $contentData['content'];\n $labelNewContent = $contentData['labelNewContent'];\n $displayOrder = $contentData['displayOrder'];\n } else {\n $contentData = $this->generateDefaultContent($configControl, $primaryKeyColumn, $patientIdColumn, $orderBy, $id, $table, $testType);\n $content = $contentData['content'];\n $labelNewContent = $contentData['labelNewContent'];\n $displayOrder = $contentData['displayOrder'];\n }\n return ['content' => $content, 'labelNewContent' => $labelNewContent, 'displayOrder' => $displayOrder];\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function __construct($word,$literal,$not,$start_with,$operator,$sub,$pound=1,$special_term='') {\n\t\t$this->word=$word;\n\t\t$this->operator=$operator;\n\t\t$this->sub=$sub;\n\t\t$this->not=$not;\n\t\t$this->literal=$literal;\n\t\t$this->start_with=$start_with;\n\t\t$this->pound=$pound;\n\t\t$this->special_term = $special_term;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function modifIntervenantAvecCode($num, $nom, $prenom, $actif, $date_naissance, $lieu_naissance,$tel, $adresse,$statut, $cp, $ville,$email,$commentaires,$diplome,$numsecu,$nationalite,$password,$photo,$iban,$bic,$compte,$banque,$serviceCivique)\n\t{\n\t\t$req = \"UPDATE `intervenants` SET `NOM`=:nom,`PRENOM`=:prenom,`ACTIF`=:actif,`STATUT`=:statut,`EMAIL`=:email,`TELEPHONE`=:tel,`ADRESSE_POSTALE`=:adresse,`CODE_POSTAL`=:cp,`VILLE`=:ville,`DIPLOME`=:diplome,`COMMENTAIRES`=:commentaires,`DATE_DE_NAISSANCE`=:date_naissance,`LIEU_DE_NAISSANCE`=:lieu_naissance,`NATIONALITE`=:nationalite,`SECURITE_SOCIALE`=:numsecu,`PHOTO`=:photo,`PASSWORD`=:password, IBAN=:iban, BIC=:bic, COMPTEBANCAIRE=:compte, BANQUE=:banque, SERVICECIVIQUE=:serviceCivique WHERE `ID_INTERVENANT`=:num\";\n\n\t\t$params = array(\n\t\t\t':num' => $nom,\n\t\t\t':nom' => $nom,\n\t\t\t':prenom' => $prenom,\n\t\t\t':actif' => $actif,\n\t\t\t':date_naissance' => $date_naissance,\n\t\t\t':lieu_naissance' => $lieu_naissance,\n\t\t\t':tel' => $tel,\n\t\t\t':adresse' => $adresse,\n\t\t\t':statut' => $statut,\n\t\t\t':cp' => $cp,\n\t\t\t':ville' => $ville,\n\t\t\t':email' => $email,\n\t\t\t':commentaires' => $commentaires,\n\t\t\t':diplome' => $diplome,\n\t\t\t':numsecu' => $numsecu,\n\t\t\t':nationalite' => $nationalite,\n\t\t\t':password' => $password,\n\t\t\t':photo' => $photo,\n\t\t\t':iban' => $iban,\n\t\t\t':bic' => $bic,\n\t\t\t':compte' => $compte,\n\t\t\t':banque' => $banque,\n\t\t\t':serviceCivique' => $serviceCivique\n\t\t);\n\n\t\t$rs = $this->NonQuery($req,$params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function modifInscriptionEleve($num,$annee,$etab,$classe,$prof_principal,$filiere,$lv1,$lv2,$date_inscription,$commentaires,$nouveau)\n\t{\n\n\t\t// Sinon, on l'ajoute\n\t\tif($nouveau) {\n\t\t\t$req = \"INSERT INTO `inscrit`(`ID_ELEVE`, `ANNEE`, `ID`, `ID_FILIERES`, `ID_LV1`, `ID_LV2`, `ID_CLASSE`, `DATE_INSCRIPTION`, `NOM_DU_PROF_PRINCIPAL`, `COMMENTAIRESANNEE`) VALUES ('$num', '$annee', '$etab','$filiere','$lv1','$lv2','$classe','$date_inscription','$prof_principal','$commentaires') \";\n\t\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'ajout de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t\t\n\t\t\t\t\t// Si elle existe, on la met \u00e0 jour\n\t\t\n\t\t} else {\n\t\t\t\n\t\t\t\n\t\t$req = \"UPDATE `inscrit` SET `ID`=$etab,`ID_FILIERES`=$filiere,`ID_LV1`=$lv1,`ID_LV2`=$lv2,`ID_CLASSE`=$classe,`DATE_INSCRIPTION`='$date_inscription',`NOM_DU_PROF_PRINCIPAL`='$prof_principal',`COMMENTAIRESANNEE`='$commentaires' WHERE`ID_ELEVE`=$num AND `ANNEE`='$annee' \";\n\t\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\n\t\t\t\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n PermissionResolver $permissionResolver,\n UserService $userService,\n ContentTypeService $contentTypeService,\n ContentService $contentService,\n SearchService $searchService,\n FilterManager $filterManager,\n IOServiceInterface $ioService,\n MimeTypesInterface $mimeTypes,\n ImagineInterface $imagine\n ) {\n $this->permissionResolver = $permissionResolver;\n $this->userService = $userService;\n $this->contentTypeService = $contentTypeService;\n $this->contentService = $contentService;\n $this->searchService = $searchService;\n $this->filterManager = $filterManager;\n $this->ioService = $ioService;\n $this->mimeTypes = $mimeTypes;\n $this->imagine = $imagine;\n\n parent::__construct();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function genererGraphique($id, $type, $hauteur, $largeur, $titre, $valeurs, $nom, $nb, $total)\n{\n $couleurs = array('red', 'blue', 'green', 'pink', 'orange', 'brown', 'gray', 'lime', 'maroon', 'olive', 'navy', 'teal', 'yellow', 'purple');\n echo \"\n \";\n}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function block_core_page_list_render_nested_page_list( $open_submenus_on_click, $show_submenu_icons, $is_navigation_child, $nested_pages, $is_nested, $active_page_ancestor_ids = array(), $colors = array(), $depth = 0 ) {\n\tif ( empty( $nested_pages ) ) {\n\t\treturn;\n\t}\n\t$front_page_id = (int) get_option( 'page_on_front' );\n\t$markup = '';\n\tforeach ( (array) $nested_pages as $page ) {\n\t\t$css_class = $page['is_active'] ? ' current-menu-item' : '';\n\t\t$aria_current = $page['is_active'] ? ' aria-current=\"page\"' : '';\n\t\t$style_attribute = '';\n\n\t\t$css_class .= in_array( $page['page_id'], $active_page_ancestor_ids, true ) ? ' current-menu-ancestor' : '';\n\t\tif ( isset( $page['children'] ) ) {\n\t\t\t$css_class .= ' has-child';\n\t\t}\n\n\t\tif ( $is_navigation_child ) {\n\t\t\t$css_class .= ' wp-block-navigation-item';\n\n\t\t\tif ( $open_submenus_on_click ) {\n\t\t\t\t$css_class .= ' open-on-click';\n\t\t\t} elseif ( $show_submenu_icons ) {\n\t\t\t\t$css_class .= ' open-on-hover-click';\n\t\t\t}\n\t\t}\n\n\t\t$navigation_child_content_class = $is_navigation_child ? ' wp-block-navigation-item__content' : '';\n\n\t\t// If this is the first level of submenus, include the overlay colors.\n\t\tif ( ( ( 0 < $depth && ! $is_nested ) || $is_nested ) && isset( $colors['overlay_css_classes'], $colors['overlay_inline_styles'] ) ) {\n\t\t\t$css_class .= ' ' . trim( implode( ' ', $colors['overlay_css_classes'] ) );\n\t\t\tif ( '' !== $colors['overlay_inline_styles'] ) {\n\t\t\t\t$style_attribute = sprintf( ' style=\"%s\"', esc_attr( $colors['overlay_inline_styles'] ) );\n\t\t\t}\n\t\t}\n\n\t\tif ( (int) $page['page_id'] === $front_page_id ) {\n\t\t\t$css_class .= ' menu-item-home';\n\t\t}\n\n\t\t$title = wp_kses_post( $page['title'] );\n\t\t$aria_label = sprintf(\n\t\t\t/* translators: Accessibility text. %s: Parent page title. */\n\t\t\t__( '%s submenu' ),\n\t\t\twp_strip_all_tags( $title )\n\t\t);\n\n\t\t$markup .= '
  • ';\n\n\t\tif ( isset( $page['children'] ) && $is_navigation_child && $open_submenus_on_click ) {\n\t\t\t$markup .= '';\n\t\t} else {\n\t\t\t$markup .= '' . $title . '';\n\t\t}\n\n\t\tif ( isset( $page['children'] ) ) {\n\t\t\tif ( $is_navigation_child && $show_submenu_icons && ! $open_submenus_on_click ) {\n\t\t\t\t$markup .= '';\n\t\t\t}\n\t\t\t$markup .= '
      ';\n\t\t\t$markup .= block_core_page_list_render_nested_page_list( $open_submenus_on_click, $show_submenu_icons, $is_navigation_child, $page['children'], $is_nested, $active_page_ancestor_ids, $colors, $depth + 1 );\n\t\t\t$markup .= '
    ';\n\t\t}\n\t\t$markup .= '
  • ';\n\t}\n\treturn $markup;\n}", "smellKey": "S107", "smellId": null, "repo": "zhritik_wordpress-v19.0.0-1733519032", "language": "php"} {"function": "function transmitCCD($pid, $ccd_out, $recipient, $requested_by, $xml_type = \"CCD\", $format_type = 'xml', $message = '', $filename = '', $verifyFinalDelivery = false): string\n{\n //get patient name in Last_First format (used for CCDA filename) and\n //First Last for the message text.\n $patientData = getPatientPID(array(\"pid\" => $pid));\n if (empty($patientData)) { // shouldn't ever happen but we need to check anyways\n return( xl(ErrorConstants::ERROR_MESSAGE_UNEXPECTED_RESPONSE));\n }\n $patientName2 = \"\";\n $att_filename = \"\";\n\n // TODO: do we want to throw an error if we can't get patient data? Probably.\n\n if (!empty($patientData[0]['lname'])) {\n $patientName2 = trim($patientData[0]['fname'] . \" \" . $patientData[0]['lname']);\n }\n\n if (!empty($filename)) {\n // if we have a filename from our database, we want to send that\n $att_filename = $filename;\n $extension = \"\"; // no extension needed\n } elseif (!empty($patientName2)) {\n //spaces are the argument delimiter for the phiMail API calls and must be removed\n // CCDA format requires patient name in last, first format\n $att_filename = str_replace(\" \", \"_\", $xml_type . \"_\" . $patientData[0]['lname']\n . \"_\" . $patientData[0]['fname']);\n $extension = \".\" . $format_type;\n }\n\n $config_err = xl(ErrorConstants::MESSAGING_DISABLED) . \" \" . ErrorConstants::ERROR_CODE_ABBREVIATION . \":\";\n if ($GLOBALS['phimail_enable'] == false) {\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_MESSAGING_DISABLED);\n }\n\n $fp = phimail_connect($err);\n if ($fp === false) {\n return(\"$config_err $err\");\n }\n\n $phimail_username = $GLOBALS['phimail_username'];\n $cryptoGen = new CryptoGen();\n $phimail_password = $cryptoGen->decryptStandard($GLOBALS['phimail_password']);\n $ret = phimail_write_expect_OK($fp, \"AUTH $phimail_username $phimail_password\\n\");\n if ($ret !== true) {\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_AUTH_FAILED);\n }\n\n $ret = phimail_write_expect_OK($fp, \"TO $recipient\\n\");\n if ($ret !== true) {\n return( xl(ErrorConstants::RECIPIENT_NOT_ALLOWED) . \" \" . $ret );\n }\n\n $ret = fgets($fp, 1024); //ignore extra server data\n\n // add whatever the clinican added as a message to be sent.\n if (is_string($message) && trim($message) != \"\") {\n $text_out = $message . \"\\n\";\n }\n\n if ($requested_by == \"patient\") {\n $text_out .= xl(\"Delivery of the attached clinical document was requested by the patient\") .\n ($patientName2 == \"\" ? \".\" : \", \" . $patientName2 . \".\");\n } else {\n $text_out .= xl(\"A clinical document is attached\") .\n ($patientName2 == \"\" ? \".\" : \" \" . xl(\"for patient\") . \" \" . $patientName2 . \".\");\n }\n\n\n $text_len = strlen($text_out);\n phimail_write($fp, \"TEXT $text_len\\n\");\n $ret = @fgets($fp, 256);\n if ($ret != \"BEGIN\\n\") {\n phimail_close($fp);\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_MESSAGE_BEGIN_FAILED);\n }\n\n $ret = phimail_write_expect_OK($fp, $text_out);\n if ($ret !== true) {\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_MESSAGE_BEGIN_OK_FAILED);\n }\n\n // MU2 CareCoordination added the need to send CCDAs formatted as html,pdf, or xml\n if ($format_type == 'html') {\n $add_type = \"TEXT\";\n } elseif ($format_type == 'pdf') {\n $add_type = \"RAW\";\n } elseif ($format_type == 'xml') {\n $add_type = $xml_type == \"CCR\" ? \"CCR\" : \"CDA\";\n } else {\n // unsupported format\n return (\"$config_err \" . ErrorConstants::ERROR_CODE_INVALID_FORMAT_TYPE);\n }\n\n $ccd_len = strlen($ccd_out);\n\n phimail_write($fp, \"ADD \" . $add_type . \" \" . $ccd_len . \" \" . $att_filename . $extension . \"\\n\");\n $ret = fgets($fp, 256);\n if ($ret != \"BEGIN\\n\") {\n phimail_close($fp);\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_ADD_FILE_FAILED);\n }\n\n $ret = phimail_write_expect_OK($fp, $ccd_out);\n if ($ret !== true) {\n return(\"$config_err \" . ErrorConstants::ERROR_CODE_ADD_FILE_CONFIRM_FAILED);\n }\n\n if ($verifyFinalDelivery) {\n $ret = phimail_write_expect_OK($fp, \"SET FINAL 1\\n\");\n if ($ret !== true) {\n return( xl(ErrorConstants::ERROR_MESSAGE_SET_DISPOSITION_NOTIFICATION_FAILED) . \" \" . $ret );\n }\n } else {\n $ret = phimail_write_expect_OK($fp, \"SET FINAL 0\\n\");\n if ($ret !== true) {\n return( xl(ErrorConstants::ERROR_MESSAGE_SET_DISPOSITION_NOTIFICATION_FAILED) . \" \" . $ret );\n }\n }\n\n phimail_write($fp, \"SEND\\n\");\n $ret = fgets($fp);\n phimail_write($fp, \"OK\\n\");\n phimail_close($fp);\n\n if ($requested_by == \"patient\") {\n $reqBy = \"portal-user\";\n $sql = \"SELECT id FROM users WHERE username='portal-user'\";\n if (\n ($r = sqlStatementNoLog($sql)) === false ||\n ($u = sqlFetchArray($r)) === false\n ) {\n $reqID = 1; //default if we don't have a service user\n } else {\n $reqID = $u['id'];\n }\n } else {\n $reqBy = $_SESSION['authUser'];\n $reqID = $_SESSION['authUserID'];\n }\n\n if (substr($ret, 5) == \"ERROR\") {\n //log the failure\n\n EventAuditLogger::instance()->newEvent(\"transmit-ccd\", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);\n return( xl(ErrorConstants::ERROR_MESSAGE_FILE_SEND_FAILED));\n }\n\n /**\n * If we get here, the message was successfully sent and the return\n * value $ret is of the form \"QUEUED recipient message-id\" which\n * is suitable for logging.\n */\n $msg_id = explode(\" \", trim($ret), 4);\n if ($msg_id[0] != \"QUEUED\" || !isset($msg_id[2])) { //unexpected response\n $ret = \"UNEXPECTED RESPONSE: \" . $ret;\n EventAuditLogger::instance()->newEvent(\"transmit-ccd\", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);\n return( xl(ErrorConstants::ERROR_MESSAGE_UNEXPECTED_RESPONSE));\n }\n\n EventAuditLogger::instance()->newEvent(\"transmit-\" . $xml_type, $reqBy, $_SESSION['authProvider'], 1, $ret, $pid);\n $adodb = $GLOBALS['adodb']['db'];\n $sql = \"INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,patient_id,user_id) \" .\n \"VALUES ('S', ?, ?, ?, 'S', NOW(), ?, ?)\";\n $res = @sqlStatementNoLog($sql, array($msg_id[2],$phimail_username,$recipient,$pid,$reqID));\n\n return(\"SUCCESS\");\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function updateItemOnInputTextEvent(\n $toobserve,\n $toupdate,\n $url,\n $parameters = [],\n $minsize = -1,\n $buffertime = -1,\n $forceloadfor = [],\n $display = true\n ) {\n\n if (count($forceloadfor) == 0) {\n $forceloadfor = ['*'];\n }\n // Need to define min size for text search\n if ($minsize < 0) {\n $minsize = 0;\n }\n if ($buffertime < 0) {\n $buffertime = 0;\n }\n return self::updateItemOnEvent(\n $toobserve,\n $toupdate,\n $url,\n $parameters,\n [\"dblclick\", \"keyup\"],\n $minsize,\n $buffertime,\n $forceloadfor,\n $display\n );\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function addLeftJoin(\n $itemtype,\n $ref_table,\n array &$already_link_tables,\n $new_table,\n $linkfield,\n $meta = false,\n $meta_type = '',\n $joinparams = [],\n $field = ''\n ) {\n /** @var \\DBmysql $DB */\n global $DB;\n $criteria = SQLProvider::getLeftJoinCriteria(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $new_table,\n $linkfield,\n (bool) $meta,\n (string) $meta_type,\n $joinparams,\n $field\n );\n $iterator = new DBmysqlIterator($DB);\n $iterator->buildQuery([\n 'FROM' => 'table',\n ] + $criteria);\n $sql = $iterator->getSql();\n // Remove FROM $table clause and everything before it\n $prefix = 'SELECT * FROM `table` ';\n $sql = substr($sql, strlen($prefix));\n return $sql . ' ';\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function creerDossierIBUpload2($client, $ref_dos, $mca_b_ref, $road_manif, $date_preal, $t1, \n\t\t\t\t\t\t\t\t\t\t$poids, $ref_fact, $fob, $fret, \n\t\t\t\t\t\t\t\t\t\t$assurance, $autre_frais, $fournisseur, $po, \n\t\t\t\t\t\t\t\t\t\t$commodity, $horse, $trailer_1, $trailer_2, $num_lic, $num_exo,\n\t\t\t\t\t\t\t\t\t\t$arrival_date, $crossing_date, $wiski_arriv, $wiski_dep, $amicongo_arriv,\n\t\t\t\t\t\t\t\t\t\t$insp_report, $ir, $ref_crf, $date_crf, $ref_decl, $dgda_in, $ref_liq, \n\t\t\t\t\t\t\t\t\t\t$date_liq, $ref_quit, $date_quit, $dgda_out, $custom_deliv, $dispatch_deliv,\n\t\t\t\t\t\t\t\t\t\t$remarque, $statut, $id_mod_trac, $id_util, $bl, $supplier, $credit_enlev_by, $bond_warehouse){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;$entree['mca_b_ref'] = $mca_b_ref;\n\t\t\t$entree['date_preal'] = $date_preal;$entree['t1'] = $t1;\n\t\t\t$entree['poids'] = $poids;$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['fob'] = $fob;$entree['fret'] = $fret;$entree['assurance'] = $assurance;\n\t\t\t$entree['autre_frais'] = $autre_frais;$entree['po'] = $po;\n\t\t\t$entree['commodity'] = $commodity;$entree['horse'] = $horse;$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;$entree['road_manif'] = $road_manif;$entree['fournisseur'] = $fournisseur;\n\t\t\t$entree['num_lic'] = $num_lic;$entree['num_exo'] = $num_exo;$entree['arrival_date'] = $arrival_date;\n\t\t\t$entree['crossing_date'] = $crossing_date;$entree['wiski_arriv'] = $wiski_arriv;$entree['wiski_dep'] = $wiski_dep;\n\t\t\t$entree['amicongo_arriv'] = $amicongo_arriv;$entree['insp_report'] = $insp_report;$entree['ir'] = $ir;\n\t\t\t$entree['ref_crf'] = $ref_crf;$entree['date_crf'] = $date_crf;$entree['ref_decl'] = $ref_decl;\n\t\t\t$entree['dgda_in'] = $dgda_in;$entree['ref_liq'] = $ref_liq;$entree['date_liq'] = $date_liq;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['date_quit'] = $date_quit;$entree['dgda_out'] = $dgda_out;\n\t\t\t$entree['custom_deliv'] = $custom_deliv;$entree['dispatch_deliv'] = $dispatch_deliv;$entree['remarque'] = $remarque;\n\t\t\t$entree['statut'] = $statut;$entree['id_mod_trac'] = $id_mod_trac;$entree['id_util'] = $id_util;\n\t\t\t$entree['bl'] = $bl; $entree['supplier'] = $supplier; $entree['credit_enlev_by'] = $credit_enlev_by;\n\t\t\t$entree['bond_warehouse'] = $bond_warehouse;\n\t\t\t/*echo $client.' - '.$ref_dos.' - '.$mca_b_ref.' - '.$road_manif.' - '.$date_preal.' - '.$t1.' - '.$poids.' - '.$fob.' - '.$fret.' - '.$assurance.' - '.$autre_frais.' - '.$ref_fact.' - '.$fournisseur.' - '.$po.' - '.$commodity.' - '.$horse.' - '.$trailer_1.' - '.$trailer_2.' - '.$num_lic.' - '.$num_exo.' - '.$crossing_date.' - '.$arrival_date.' - '.$wiski_arriv.' - '.$wiski_dep.' - '.$amicongo_arriv.' - '.$insp_report.' - '.$ir.' - '.$ref_crf.' - '.$date_crf.' - '.$ref_decl.' - '.$dgda_in.' - '.$ref_liq.' - '.$date_liq.' - '.$ref_quit.' - '.$date_quit.' - '.$dgda_out.' - '.$custom_deliv.' - '.$dispatch_deliv.' - '.$statut.' - '.$remarque.'


    ';*/\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload_tracking(client, ref_dos, mca_b_ref, date_preal, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tt1, poids, ref_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfob, fret, assurance, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tautre_frais, fournisseur, po, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommodity, horse, trailer_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_2, road_manif, num_lic, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnum_exo, arrival_date, crossing_date, wiski_arriv, wiski_dep, amicongo_arriv, insp_report, ir, ref_crf, date_crf, ref_decl, dgda_in, ref_liq, date_liq, ref_quit, date_quit, dgda_out, custom_deliv, dispatch_deliv, remarque, statut,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_util, bl, supplier, credit_enlev_by, bond_warehouse) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['mca_b_ref'], $entree['date_preal'], \n\t\t\t\t\t\t\t\t\t$entree['t1'], $entree['poids'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['fournisseur'], $entree['po'], \n\t\t\t\t\t\t\t\t\t$entree['commodity'], $entree['horse'], $entree['trailer_1'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_2'], $entree['road_manif'], $entree['num_lic'], \n\t\t\t\t\t\t\t\t\t$entree['num_exo'], $entree['arrival_date'], $entree['crossing_date'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_arriv'], $entree['wiski_dep'], $entree['amicongo_arriv'], \n\t\t\t\t\t\t\t\t\t$entree['insp_report'], $entree['ir'], $entree['ref_crf'], \n\t\t\t\t\t\t\t\t\t$entree['date_crf'], $entree['ref_decl'], $entree['dgda_in'], \n\t\t\t\t\t\t\t\t\t$entree['ref_liq'], $entree['date_liq'], $entree['dgda_out'], \n\t\t\t\t\t\t\t\t\t$entree['ref_quit'], $entree['date_quit'], $entree['custom_deliv'], \n\t\t\t\t\t\t\t\t\t$entree['dispatch_deliv'], $entree['remarque'], $entree['statut'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_trac'], $entree['id_util'], $entree['bl'], \n\t\t\t\t\t\t\t\t\t$entree['supplier'], $entree['credit_enlev_by'], $entree['bond_warehouse']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function buildRepository(\n PersistenceHandler $persistenceHandler,\n SearchHandler $searchHandler,\n BackgroundIndexer $backgroundIndexer,\n RelationProcessor $relationProcessor,\n FieldTypeRegistry $fieldTypeRegistry,\n PasswordHashService $passwordHashService,\n ProxyDomainMapperFactoryInterface $proxyDomainMapperFactory,\n Mapper\\ContentDomainMapper $contentDomainMapper,\n Mapper\\ContentTypeDomainMapper $contentTypeDomainMapper,\n Mapper\\RoleDomainMapper $roleDomainMapper,\n Mapper\\ContentMapper $contentMapper,\n ContentValidator $contentValidator,\n LimitationService $limitationService,\n PermissionService $permissionService,\n ContentFilteringHandler $contentFilteringHandler,\n LocationFilteringHandler $locationFilteringHandler,\n PasswordValidatorInterface $passwordValidator,\n ConfigResolverInterface $configResolver,\n NameSchemaServiceInterface $nameSchemaService,\n TransactionHandler $transactionHandler\n ): Repository {\n $config = $this->repositoryConfigurationProvider->getRepositoryConfig();\n\n return new CoreRepository(\n $persistenceHandler,\n $searchHandler,\n $backgroundIndexer,\n $relationProcessor,\n $fieldTypeRegistry,\n $passwordHashService,\n $proxyDomainMapperFactory,\n $contentDomainMapper,\n $contentTypeDomainMapper,\n $roleDomainMapper,\n $contentMapper,\n $contentValidator,\n $limitationService,\n $this->languageResolver,\n $permissionService,\n $contentFilteringHandler,\n $locationFilteringHandler,\n $passwordValidator,\n $configResolver,\n $nameSchemaService,\n $transactionHandler,\n [\n 'role' => [\n 'policyMap' => $this->policyMap,\n ],\n 'languages' => $this->configResolver->getParameter('languages'),\n 'content' => [\n 'default_version_archive_limit' => $config['options']['default_version_archive_limit'],\n 'remove_archived_versions_on_publish' => $config['options']['remove_archived_versions_on_publish'],\n ],\n ],\n $this->logger\n );\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function ActualizaUsuario(\n\t\t\t\t$rut, $dv, $nombre, $apaterno, $amaterno, $fecha_nacimiento, $genero, \n\t\t\t\t$email, $nacionalidad, $direccion_particular, $codigo_escolaridad, $codigo_nivel, \n\t\t\t\t$gerencia, $cargo, $unidad_negocio, $centro_costo, $empresa_holding, \n\t\t\t\t$fecha_antiguedad, $tipo_contrato, $tramo_sence, $perfil_evaluacion)\n{\n\tglobal $c_host,$c_user,$c_pass,$c_db;\n\t$database = new database($c_host,$c_user,$c_pass);\n\t$database->setDb($c_db);\n\t\n\t$sql = \"\n\t\n\tUPDATE tbl_usuario \n\t\tSET nombre= '$nombre', \n\t\tapaterno= '$apaterno', \n\t\tamaterno= '$amaterno', \n\t\tnombre_completo= '$nombre_completo', \n\t\tcargo= '$cargo', \n\t\tfecha_nacimiento= '$fecha_nacimiento', \n\t\tgenero= '$genero', \n\t\temail= '$email', \n\t\tnacionalidad= '$nacionalidad', \n\t\tdireccion_particular= '$direccion_particular', \n\t\tcodigo_escolaridad= '$codigo_escolaridad', \n\t\tcodigo_nivel= '$codigo_nivel', \n\t\tgerencia= '$gerencia', \n\t\tunidad_negocio= '$unidad_negocio', \n\t\tcentro_costo= '$centro_costo', \n\t\tempresa_holding= '$empresa_holding', \n\t\tfecha_antiguedad= '$fecha_antiguedad', \n\t\ttipo_contrato= '$tipo_contrato', \n\t\ttramo_sence= '$tramo_sence', \n\t\tperfil_evaluacion= '$perfil_evaluacion'\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\tWHERE rut = '$rut'\n\t\n\t\";\n\t\n\t\n\t$database->setquery($sql);\n\t$database->query();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function modifierReglementStage($num, $type, $transaction, $banque, $montant, $eleves, $stage, $stageSortie)\n\t{\n\t\t$req = \"DELETE FROM `inscriptions_fratries_stage` WHERE `ID_INSCRIPTIONS` = :num\";\n\t\t$params = array(\n\t\t\t':num' => $num\n\t\t);\n\t\t$this->NonQuery($req, $params);\n\t\t\n\t\tif (count($eleves) > 0) {\n $req = \"\";\n $i = 0;\n $params = array(\n ':num' => $num\n );\n foreach ($eleves as $eleve) {\n $placeholder = \":eleve\" . $i;\n $req .= \"INSERT INTO `inscriptions_fratries_stage`(`ID_INSCRIPTIONS`, `ID_INSCRIPTIONS2`) VALUES (:num, $placeholder);\";\n $params[$placeholder] = $eleve;\n $i++;\n }\n $rs = $this->NonQuery($req, $params);\n if ($rs === false) {afficherErreurSQL(\"Probleme lors de la fratries dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n }\n\n\t\t$req = \"UPDATE `INSCRIPTIONS_STAGE` SET `PAIEMENT_INSCRIPTIONS` = :type, `NUMTRANSACTION` = :transaction, `BANQUE_INSCRIPTION` = :banque, `MONTANT_INSCRIPTION` = :montant WHERE `ID_INSCRIPTIONS` = :num\";\n\t\t$params = array(\n\t\t\t':type' => $type,\n\t\t\t':transaction' => $transaction,\n\t\t\t':banque' => $banque,\n\t\t\t':montant' => $montant,\n\t\t\t':num' => $num\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la recherche des groupes dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n $req = \"SELECT ID_INFO_REGLEMENT FROM `INSCRIPTIONS_STAGE` WHERE `ID_INSCRIPTIONS` = :id;\";\n $params = array(\n ':id' => $num\n );\n\n $rs = $this->Read($req, $params);\n if (!is_null($rs)) {\n $req = \"UPDATE `\" . PdoBD::$villeExtranet . \"_info_reglements` SET `STAGE` = :stage, `SORTIE_STAGE` = :storiestage WHERE `ID_INFO_REGLEMENT` = :id;\";\n $params = array(\n ':stage' => $stage,\n ':storiestage' => $stageSortie,\n ':id' => $rs['ID_INFO_REGLEMENT']\n );\n $this->NonQuery($req, $params);\n }\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct($snapshotTable, $datasetType,\n\t\t$variableId, $hasTotals, $urbanity, $partition, $hasDescriptions,\n\t\t$size, $direction, $hiddenValueLabels)\n\t{\n\t\t$this->variableId = $variableId;\n\t\t$this->urbanity = $urbanity;\n\t\t$this->partition = $partition;\n\t\t$this->hiddenValueLabels = $hiddenValueLabels;\n\n\t\t$this->hasTotals = $hasTotals;\n\t\t$this->hasDescriptions = $hasDescriptions;\n\t\t$this->size = $size;\n\t\t$this->direction = $direction;\n\n\t\tparent::__construct($snapshotTable, 'sna', $datasetType);\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n TranslatorInterface $translator,\n URLAliasService $urlAliasService,\n FormFactory $formFactory,\n DatasetFactory $datasetFactory,\n LocationService $locationService,\n PermissionResolver $permissionResolver,\n EventDispatcherInterface $eventDispatcher,\n TranslationHelper $translationHelper\n ) {\n parent::__construct($twig, $translator, $eventDispatcher);\n\n $this->urlAliasService = $urlAliasService;\n $this->formFactory = $formFactory;\n $this->datasetFactory = $datasetFactory;\n $this->locationService = $locationService;\n $this->permissionResolver = $permissionResolver;\n $this->translationHelper = $translationHelper;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function getListNavigator(\n int $count,\n int $pos,\n array $urlParams,\n string $script,\n string $frame,\n int $maxCount,\n string $name = 'pos',\n array $classes = [],\n ): string {\n if ($maxCount <= 0) {\n $maxCount = 250;\n }\n\n $pageSelector = '';\n if ($maxCount < $count) {\n $classes[] = 'pageselector';\n\n $pageSelector = Util::pageselector(\n $name,\n $maxCount,\n Util::getPageFromPosition($pos, $maxCount),\n (int) ceil($count / $maxCount),\n );\n }\n\n return (new Template())->render('list_navigator', [\n 'count' => $count,\n 'max_count' => $maxCount,\n 'classes' => $classes,\n 'frame' => $frame,\n 'position' => $pos,\n 'script' => $script,\n 'url_params' => $urlParams,\n 'param_name' => $name,\n 'page_selector' => $pageSelector,\n ]);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function fetchEvents($from_date, $to_date, $where_param = null, $orderby_param = null, $tracker_board = false, $nextX = 0, $bind_param = null, $query_param = null)\n{\n\n $sqlBindArray = array();\n\n if ($query_param) {\n $query = $query_param;\n\n if ($bind_param) {\n $sqlBindArray = $bind_param;\n }\n } else {\n //////\n if ($nextX) {\n $where =\n \"((e.pc_endDate >= ? AND e.pc_recurrtype > '0') OR \" .\n \"(e.pc_eventDate >= ?))\";\n\n array_push($sqlBindArray, $from_date, $from_date);\n } else {\n //////\n $where =\n \"((e.pc_endDate >= ? AND e.pc_eventDate <= ? AND e.pc_recurrtype > '0') OR \" .\n \"(e.pc_eventDate >= ? AND e.pc_eventDate <= ?))\";\n\n array_push($sqlBindArray, $from_date, $to_date, $from_date, $to_date);\n }\n\n if ($where_param) {\n $where .= $where_param;\n }\n\n // Filter out appointments based on a custom module filter\n $apptFilterEvent = new AppointmentsFilterEvent(new BoundFilter());\n $apptFilterEvent = $GLOBALS[\"kernel\"]->getEventDispatcher()->dispatch($apptFilterEvent, AppointmentsFilterEvent::EVENT_HANDLE, 10);\n $boundFilter = $apptFilterEvent->getBoundFilter();\n $sqlBindArray = array_merge($sqlBindArray, $boundFilter->getBoundValues());\n $where .= \" AND \" . $boundFilter->getFilterClause();\n\n $order_by = \"e.pc_eventDate, e.pc_startTime\";\n if ($orderby_param) {\n $order_by = $orderby_param;\n }\n\n // Tracker Board specific stuff\n $tracker_fields = '';\n $tracker_joins = '';\n if ($tracker_board) {\n $tracker_fields = \"e.pc_room, e.pc_pid, t.id, t.date, t.apptdate, t.appttime, t.eid, t.pid, t.original_user, t.encounter, t.lastseq, t.random_drug_test, t.drug_screen_completed, \" .\n \"q.pt_tracker_id, q.start_datetime, q.room, q.status, q.seq, q.user, \" .\n \"s.toggle_setting_1, s.toggle_setting_2, s.option_id, \";\n $tracker_joins = \"LEFT OUTER JOIN patient_tracker AS t ON t.pid = e.pc_pid AND t.apptdate = e.pc_eventDate AND t.appttime = e.pc_starttime AND t.eid = e.pc_eid \" .\n \"LEFT OUTER JOIN patient_tracker_element AS q ON q.pt_tracker_id = t.id AND q.seq = t.lastseq \" .\n \"LEFT OUTER JOIN list_options AS s ON s.list_id = 'apptstat' AND s.option_id = q.status AND s.activity = 1 \" ;\n }\n\n $query = \"SELECT \" .\n \"e.pc_eventDate, e.pc_endDate, e.pc_startTime, e.pc_endTime, e.pc_duration, e.pc_recurrtype, e.pc_recurrspec, e.pc_recurrfreq, e.pc_catid, e.pc_eid, e.pc_gid, \" .\n \"e.pc_title, e.pc_hometext, e.pc_apptstatus, \" .\n \"p.fname, p.mname, p.lname, p.DOB, p.pid, p.pubpid, p.phone_home, p.phone_cell, \" .\n \"p.hipaa_allowsms, p.phone_home, p.phone_cell, p.hipaa_voice, p.hipaa_allowemail, p.email, \" .\n \"u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, \" .\n \"f.name, \" .\n \"$tracker_fields\" .\n \"c.pc_catname, c.pc_catid, e.pc_facility \" .\n \"FROM openemr_postcalendar_events AS e \" .\n \"$tracker_joins\" .\n \"LEFT OUTER JOIN facility AS f ON e.pc_facility = f.id \" .\n \"LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid \" .\n \"LEFT OUTER JOIN users AS u ON u.id = e.pc_aid \" .\n \"LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid \" .\n \"WHERE $where \" .\n \"ORDER BY $order_by\";\n\n if ($bind_param) {\n $sqlBindArray = array_merge($sqlBindArray, $bind_param);\n }\n }\n\n\n ///////////////////////////////////////////////////////////////////////\n // The following code is from the calculateEvents function in the //\n // PostCalendar Module modified and inserted here by epsdky //\n ///////////////////////////////////////////////////////////////////////\n\n $events2 = array();\n\n $res = sqlStatement($query, $sqlBindArray);\n\n ////////\n if ($nextX) {\n global $resNotNull;\n $resNotNull = (isset($res) && $res != null);\n }\n\n while ($event = sqlFetchArray($res)) {\n ///////\n if ($nextX) {\n $stopDate = $event['pc_endDate'];\n } else {\n $stopDate = ($event['pc_endDate'] <= $to_date) ? $event['pc_endDate'] : $to_date;\n }\n\n ///////\n $incX = 0;\n switch ($event['pc_recurrtype']) {\n case '0':\n $events2[] = $event;\n\n break;\n //////\n case '1':\n case '3':\n $event_recurrspec = @unserialize($event['pc_recurrspec'], ['allowed_classes' => false]);\n\n if (checkEvent($event['pc_recurrtype'], $event_recurrspec)) {\n break; }\n\n $rfreq = $event_recurrspec['event_repeat_freq'];\n $rtype = $event_recurrspec['event_repeat_freq_type'];\n $exdate = $event_recurrspec['exdate'];\n\n list($ny,$nm,$nd) = explode('-', $event['pc_eventDate']);\n // $occurance = Date_Calc::dateFormat($nd,$nm,$ny,'%Y-%m-%d');\n $occurance = $event['pc_eventDate'];\n\n while ($occurance < $from_date) {\n $occurance =& __increment($nd, $nm, $ny, $rfreq, $rtype);\n list($ny,$nm,$nd) = explode('-', $occurance);\n }\n\n while ($occurance <= $stopDate) {\n $excluded = false;\n if (isset($exdate)) {\n foreach (explode(\",\", $exdate) as $exception) {\n // occurrance format == yyyy-mm-dd\n // exception format == yyyymmdd\n if (preg_replace(\"/-/\", \"\", $occurance) == $exception) {\n $excluded = true;\n }\n }\n }\n\n if ($excluded == false) {\n $event['pc_eventDate'] = $occurance;\n $event['pc_endDate'] = '0000-00-00';\n $events2[] = $event;\n //////\n if ($nextX) {\n ++$incX;\n if ($incX == $nextX) {\n break;\n }\n }\n\n //////\n }\n\n $occurance =& __increment($nd, $nm, $ny, $rfreq, $rtype);\n list($ny,$nm,$nd) = explode('-', $occurance);\n }\n break;\n\n //////\n case '2':\n $event_recurrspec = @unserialize($event['pc_recurrspec'], ['allowed_classes' => false]);\n\n if (checkEvent($event['pc_recurrtype'], $event_recurrspec)) {\n break; }\n\n $rfreq = $event_recurrspec['event_repeat_on_freq'];\n $rnum = $event_recurrspec['event_repeat_on_num'];\n $rday = $event_recurrspec['event_repeat_on_day'];\n $exdate = $event_recurrspec['exdate'];\n\n list($ny,$nm,$nd) = explode('-', $event['pc_eventDate']);\n\n if (isset($event_recurrspec['rt2_pf_flag']) && $event_recurrspec['rt2_pf_flag']) {\n $nd = 1;\n }\n\n $occuranceYm = \"$ny-$nm\"; // YYYY-mm\n $from_dateYm = substr($from_date, 0, 7); // YYYY-mm\n $stopDateYm = substr($stopDate, 0, 7); // YYYY-mm\n\n // $nd will sometimes be 29, 30 or 31 and if used in the mktime functions below\n // a problem with overflow will occur so it is set to 1 to avoid this (for rt2\n // appointments set prior to fix $nd remains unchanged). This can be done since\n // $nd has no influence past the mktime functions.\n while ($occuranceYm < $from_dateYm) {\n $occuranceYmX = date('Y-m-d', mktime(0, 0, 0, $nm + $rfreq, $nd, $ny));\n list($ny,$nm,$nd) = explode('-', $occuranceYmX);\n $occuranceYm = \"$ny-$nm\";\n }\n\n while ($occuranceYm <= $stopDateYm) {\n // (YYYY-mm)-dd\n $dnum = $rnum;\n do {\n $occurance = Date_Calc::NWeekdayOfMonth($dnum--, $rday, $nm, $ny, $format = \"%Y-%m-%d\");\n } while ($occurance === -1);\n\n if ($occurance >= $from_date && $occurance <= $stopDate) {\n $excluded = false;\n if (isset($exdate)) {\n foreach (explode(\",\", $exdate) as $exception) {\n // occurrance format == yyyy-mm-dd\n // exception format == yyyymmdd\n if (preg_replace(\"/-/\", \"\", $occurance) == $exception) {\n $excluded = true;\n }\n }\n }\n\n if ($excluded == false) {\n $event['pc_eventDate'] = $occurance;\n $event['pc_endDate'] = '0000-00-00';\n $events2[] = $event;\n //////\n if ($nextX) {\n ++$incX;\n if ($incX == $nextX) {\n break;\n }\n }\n\n //////\n }\n }\n\n $occuranceYmX = date('Y-m-d', mktime(0, 0, 0, $nm + $rfreq, $nd, $ny));\n list($ny,$nm,$nd) = explode('-', $occuranceYmX);\n $occuranceYm = \"$ny-$nm\";\n }\n break;\n }\n }\n\n return $events2;\n////////////////////// End of code inserted by epsdky\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ss_data_update_helper($device, $app_id, $fields, $metrics, $name, $polling_type, $rrd_def, $gen_type)\n {\n $rrd_name = [$polling_type, $name, $app_id, $gen_type];\n $metrics[$gen_type] = $fields;\n $tags = [\n 'name' => $name,\n 'app_id' => $app_id,\n 'type' => $gen_type,\n 'rrd_def' => $rrd_def,\n 'rrd_name' => $rrd_name,\n ];\n data_update($device, $polling_type, $tags, $fields);\n\n return $metrics;\n }", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function addMessage( $id, $msg, $type = '', $hide = true, $fallback_message = false, $fallback_type = false, $group = false, $admin_notice = false ) {\n\t\t\t$args = array(\n\t\t\t\t'id' => $id,\n\t\t\t\t'msg' => $msg,\n\t\t\t\t'type' => $type,\n\t\t\t\t'hide' => $hide,\n\t\t\t\t'message_fallback' => $fallback_message,\n\t\t\t\t'fallback_type' => $fallback_type,\n\t\t\t\t'group' => $group,\n\t\t\t\t'admin_notice' => $admin_notice,\n\t\t\t);\n\n\t\t\tself::add_message( $args );\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function __construct(string $appName,\n\t\tIRequest $request,\n\t\tIProvider $tokenProvider,\n\t\tISession $session,\n\t\tISecureRandom $random,\n\t\t?string $userId,\n\t\tIUserSession $userSession,\n\t\tIManager $activityManager,\n\t\tRemoteWipe $remoteWipe,\n\t\tLoggerInterface $logger) {\n\t\tparent::__construct($appName, $request);\n\t\t$this->tokenProvider = $tokenProvider;\n\t\t$this->uid = $userId;\n\t\t$this->userSession = $userSession;\n\t\t$this->session = $session;\n\t\t$this->random = $random;\n\t\t$this->activityManager = $activityManager;\n\t\t$this->remoteWipe = $remoteWipe;\n\t\t$this->logger = $logger;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function sendPimcoreDocumentMail(array $recipients, string $subjectType, ElementInterface $subject, Workflow $workflow, string $action, string $language, string $mailPath, string $deeplink): void\n {\n $mail = new \\Pimcore\\Mail(['document' => $mailPath, 'params' => $this->getNotificationEmailParameters($subjectType, $subject, $workflow, $action, $deeplink, $language)]);\n\n foreach ($recipients as $user) {\n $mail->addTo($user->getEmail(), $user->getName());\n }\n\n $mail->send();\n }", "smellKey": "S107", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?int $min, ?int $max, ?int $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n // Ensure attribute default is within range\n $min = (is_null($min)) ? PHP_INT_MIN : \\intval($min);\n $max = (is_null($max)) ? PHP_INT_MAX : \\intval($max);\n\n if ($min > $max) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Minimum value must be lesser than maximum value');\n }\n\n $validator = new Range($min, $max, Database::VAR_INTEGER);\n\n if (!is_null($default) && !$validator->isValid($default)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription());\n }\n\n $size = $max > 2147483647 ? 8 : 4; // Automatically create BigInt depending on max value\n\n $attribute = createAttribute($databaseId, $collectionId, new Document([\n 'key' => $key,\n 'type' => Database::VAR_INTEGER,\n 'size' => $size,\n 'required' => $required,\n 'default' => $default,\n 'array' => $array,\n 'format' => APP_DATABASE_ATTRIBUTE_INT_RANGE,\n 'formatOptions' => [\n 'min' => $min,\n 'max' => $max,\n ],\n ]), $response, $dbForProject, $database, $events);\n\n $formatOptions = $attribute->getAttribute('formatOptions', []);\n\n if (!empty($formatOptions)) {\n $attribute->setAttribute('min', \\intval($formatOptions['min']));\n $attribute->setAttribute('max', \\intval($formatOptions['max']));\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_INTEGER);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function creerDossierIBUploadExport($ref_dos, $num_lic, $date_exp, $tonnage, $ship_num, $barge, $horse, $trailer_1, $trailer_2, $num_lot, $nbr_bags, $poids, $kapulo_load, $dispatch_pweto, $arrival_pweto, $barge_load, $barge_dispatch_date, $doc_receiv, $nbre_seal, $dgda_seal, $remarque, $transporter, $load_date, $pv_mine, $demande_attestation, $assay_date, $ceec_in, $ceec_out, $min_div_in, $min_div_out, $date_decl, $dgda_in, $date_liq, $date_quit, $dgda_out, $gov_in, $gov_out, $dispatch_date, $klsa_arriv, $end_form, $exit_drc, $cleared, $statut, $site_load, $destination, $ref_decl, $ref_liq, $ref_quit, $impala_sncc, $docs_sncc, $sncc_sakania, $sakania_date, $id_cli, $id_util, $id_mod_trans){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['ref_dos'] = $ref_dos;$entree['num_lic'] = $num_lic;\n\t\t\t$entree['date_exp'] = $date_exp;$entree['tonnage'] = $tonnage;\n\t\t\t$entree['ship_num'] = $ship_num;$entree['barge'] = $barge;\n\t\t\t$entree['horse'] = $horse;$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;$entree['num_lot'] = $num_lot;\n\t\t\t$entree['nbr_bags'] = $nbr_bags;$entree['poids'] = $poids;\n\t\t\t$entree['kapulo_load'] = $kapulo_load;$entree['dispatch_pweto'] = $dispatch_pweto;\n\t\t\t$entree['arrival_pweto'] = $arrival_pweto;$entree['barge_load'] = $barge_load;\n\t\t\t$entree['barge_dispatch_date'] = $barge_dispatch_date;$entree['doc_receiv'] = $doc_receiv;\n\t\t\t$entree['nbre_seal'] = $nbre_seal;$entree['dgda_seal'] = $dgda_seal;\n\t\t\t$entree['remarque'] = $remarque;$entree['transporter'] = $transporter;\n\t\t\t$entree['load_date'] = $load_date;$entree['pv_mine'] = $pv_mine;\n\t\t\t$entree['demande_attestation'] = $demande_attestation;$entree['assay_date'] = $assay_date;\n\t\t\t$entree['ceec_in'] = $ceec_in;$entree['ceec_out'] = $ceec_out;\n\t\t\t$entree['min_div_in'] = $min_div_in;$entree['min_div_out'] = $min_div_out;\n\t\t\t$entree['date_decl'] = $date_decl;$entree['dgda_in'] = $dgda_in;\n\t\t\t$entree['date_liq'] = $date_liq;$entree['date_quit'] = $date_quit;\n\t\t\t$entree['dgda_out'] = $dgda_out;$entree['gov_in'] = $gov_in;\n\t\t\t$entree['gov_out'] = $gov_out;$entree['dispatch_date'] = $dispatch_date;\n\t\t\t$entree['klsa_arriv'] = $klsa_arriv;$entree['end_form'] = $end_form;\n\t\t\t$entree['exit_drc'] = $exit_drc;$entree['cleared'] = $cleared;\n\t\t\t$entree['statut'] = $statut;$entree['site_load'] = $site_load;\n\t\t\t$entree['destination'] = $destination;$entree['ref_decl'] = $ref_decl;\n\t\t\t$entree['ref_liq'] = $ref_liq;$entree['impala_sncc'] = $impala_sncc;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['docs_sncc'] = $docs_sncc;\n\t\t\t$entree['sncc_sakania'] = $sncc_sakania;$entree['sakania_date'] = $sakania_date;\n\t\t\t$entree['id_cli'] = $id_cli; $entree['id_util'] = $id_util; $entree['id_mod_trans'] = $id_mod_trans;\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload_export(ref_dos, num_lic, date_exp, tonnage, ship_num, barge, horse, trailer_1, trailer_2, num_lot, nbr_bags, poids, kapulo_load, dispatch_pweto, arrival_pweto, barge_load, barge_dispatch_date, doc_receiv, nbre_seal, dgda_seal, remarque, transporter, load_date, pv_mine, demande_attestation, assay_date, ceec_in, ceec_out, min_div_in, min_div_out, date_decl, dgda_in, date_liq, date_quit, dgda_out, gov_in, gov_out, dispatch_date, klsa_arriv, end_form, exit_drc, cleared, statut, site_load, destination, ref_decl, ref_liq, ref_quit, impala_sncc, docs_sncc, sncc_sakania, sakania_date, id_cli, id_util, id_mod_trans) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['num_lic'], $entree['date_exp'], $entree['tonnage'], $entree['ship_num'], $entree['barge'], $entree['horse'], $entree['trailer_1'], $entree['trailer_2'], $entree['num_lot'], $entree['nbr_bags'], $entree['poids'], $entree['kapulo_load'], $entree['dispatch_pweto'], $entree['arrival_pweto'], $entree['barge_load'], $entree['barge_dispatch_date'], $entree['doc_receiv'], $entree['nbre_seal'], $entree['dgda_seal'], $entree['remarque'], $entree['transporter'], $entree['load_date'], $entree['pv_mine'], $entree['demande_attestation'], $entree['assay_date'], $entree['ceec_in'], $entree['ceec_out'], $entree['min_div_in'], $entree['min_div_out'], $entree['date_decl'], $entree['dgda_in'], $entree['date_liq'], $entree['date_quit'], $entree['dgda_out'], $entree['gov_in'], $entree['gov_out'], $entree['dispatch_date'], $entree['klsa_arriv'], $entree['end_form'], $entree['exit_drc'], $entree['cleared'], $entree['statut'], $entree['site_load'], $entree['destination'], $entree['ref_decl'], $entree['ref_liq'], $entree['ref_quit'], $entree['impala_sncc'], $entree['docs_sncc'], $entree['sncc_sakania'], $entree['sakania_date'], $entree['id_cli'], $entree['id_util'], $entree['id_mod_trans']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "private function getHtmlForInsertEditFormColumn(\n ColumnFull $tableColumn,\n int $columnNumber,\n array $commentsMap,\n int $columnLength,\n bool $insertMode,\n array $currentRow,\n int $columnsCnt,\n bool $isUpload,\n array $foreigners,\n string $table,\n string $db,\n int $rowId,\n string $defaultCharEditing,\n array $repopulate,\n array $columnMime,\n string $whereClause,\n ): string {\n $column = new InsertEditColumn(\n $tableColumn->field,\n $tableColumn->type,\n $tableColumn->isNull,\n $tableColumn->key,\n $tableColumn->default,\n $tableColumn->extra,\n $columnLength,\n $this->isColumn($tableColumn->type, ['binary', 'varbinary']),\n $this->isColumn($tableColumn->type, ['blob', 'tinyblob', 'mediumblob', 'longblob']),\n $this->isColumn($tableColumn->type, ['char', 'varchar']),\n $insertMode,\n );\n\n $asIs = false;\n $fieldHashMd5 = $column->md5;\n if ($repopulate !== [] && array_key_exists($fieldHashMd5, $currentRow)) {\n $currentRow[$column->field] = $repopulate[$fieldHashMd5];\n $asIs = true;\n }\n\n $extractedColumnspec = Util::extractColumnSpec($column->type);\n\n //Call validation when the form submitted...\n $onChangeClause = 'return verificationsAfterFieldChange('\n . json_encode($fieldHashMd5) . ', '\n . json_encode((string) $rowId) . ',' . json_encode($column->pmaType) . ')';\n\n $vkey = '[multi_edit][' . $rowId . ']';\n // Use an MD5 as an array index to avoid having special characters\n // in the name attribute (see bug #1746964 )\n $columnNameAppendix = $vkey . '[' . $fieldHashMd5 . ']';\n\n // Prepares the field value\n if ($currentRow !== []) {\n // (we are editing)\n [\n $realNullValue,\n $specialCharsEncoded,\n $specialChars,\n $data,\n $backupField,\n ] = $this->getSpecialCharsAndBackupFieldForExistingRow(\n $currentRow,\n $column,\n $extractedColumnspec,\n $columnNameAppendix,\n $asIs,\n );\n } else {\n // (we are inserting)\n // display default values\n $defaultValue = $repopulate[$fieldHashMd5] ?? $column->default ?? null;\n\n $realNullValue = $defaultValue === null;\n $data = (string) $defaultValue;\n $specialChars = $this->getSpecialCharsForInsertingMode($defaultValue, $column->trueType);\n $specialCharsEncoded = Util::duplicateFirstNewline($specialChars);\n $backupField = '';\n }\n\n $this->fieldIndex = ($this->rowOffset * $columnsCnt) + $columnNumber + 1;\n\n // The function column\n // -------------------\n $foreignData = $this->relation->getForeignData($foreigners, $column->field, false, '', '');\n $isColumnBinary = $this->isColumnBinary($column, $isUpload);\n $functionOptions = '';\n\n if ($this->config->settings['ShowFunctionFields']) {\n $defaultFunction = Generator::getDefaultFunctionForField(\n $column->trueType,\n $column->firstTimestamp,\n $column->default,\n $column->extra,\n $column->isNull,\n $column->key,\n $column->type,\n $insertMode,\n );\n $functionOptions = Generator::getFunctionsForField($defaultFunction, $foreignData->foreignField);\n }\n\n // nullify code is needed by the js nullify() function to be able to generate calls to nullify() in jQuery\n $nullifyCode = $this->getNullifyCodeForNullColumn($column, $foreigners, $foreignData->foreignLink);\n\n // The value column (depends on type)\n // ----------------\n // See bug #1667887 for the reason why we don't use the maxlength\n // HTML attribute\n\n //add data attributes \"no of decimals\" and \"data type\"\n $noDecimals = 0;\n $type = current(explode('(', $column->pmaType));\n if (preg_match('/\\(([^()]+)\\)/', $column->pmaType, $match) === 1) {\n $match[0] = trim($match[0], '()');\n $noDecimals = $match[0];\n }\n\n // Check input transformation of column\n $transformedHtml = '';\n if (! empty($columnMime['input_transformation'])) {\n $file = $columnMime['input_transformation'];\n $transformationPlugin = $this->transformations->getPluginInstance((string) $file);\n if ($transformationPlugin instanceof IOTransformationsPlugin) {\n $transformationOptions = $this->transformations->getOptions(\n $columnMime['input_transformation_options'],\n );\n $urlParams = [\n 'db' => $db,\n 'table' => $table,\n 'transform_key' => $column->field,\n 'where_clause_sign' => Core::signSqlQuery($whereClause),\n 'where_clause' => $whereClause,\n ];\n $transformationOptions['wrapper_link'] = Url::getCommon($urlParams);\n $transformationOptions['wrapper_params'] = $urlParams;\n\n $transformedHtml = $transformationPlugin->getInputHtml(\n $columnNameAppendix,\n $transformationOptions,\n $currentRow[$column->field] ?? '',\n $this->fieldIndex,\n );\n\n $GLOBALS['plugin_scripts'] = array_merge(\n $GLOBALS['plugin_scripts'],\n $transformationPlugin->getScripts(),\n );\n }\n }\n\n $columnValue = '';\n $foreignDropdown = '';\n $dataType = '';\n $textAreaRows = $this->config->settings['TextareaRows'];\n $textareaCols = $this->config->settings['TextareaCols'];\n $maxlength = '';\n $enumSelectedValue = '';\n $enumValues = [];\n $columnSetValues = [];\n $setSelectSize = 0;\n $isColumnProtectedBlob = false;\n $blobValue = '';\n $blobValueUnit = '';\n $maxUploadSize = 0;\n $selectOptionForUpload = '';\n $inputFieldHtml = '';\n if ($transformedHtml === '') {\n if ($foreignData->dispRow !== null) {\n $foreignDropdown = $this->relation->foreignDropdown(\n $foreignData->dispRow,\n $foreignData->foreignField,\n $foreignData->foreignDisplay,\n $data,\n $this->config->settings['ForeignKeyMaxLimit'],\n );\n }\n\n $dataType = $this->dbi->types->getTypeClass($column->trueType);\n\n if ($column->isChar) {\n $textAreaRows = max($this->config->settings['CharTextareaRows'], 7);\n $textareaCols = $this->config->settings['CharTextareaCols'];\n $maxlength = $extractedColumnspec['spec_in_brackets'];\n } elseif ($this->config->settings['LongtextDoubleTextarea'] && str_contains($column->pmaType, 'longtext')) {\n $textAreaRows = $this->config->settings['TextareaRows'] * 2;\n $textareaCols = $this->config->settings['TextareaCols'] * 2;\n }\n\n if ($column->pmaType === 'enum') {\n $enumValues = $extractedColumnspec['enum_set_values'];\n\n foreach ($enumValues as $enumValue) {\n if (\n $data == $enumValue || ($data == ''\n && (! isset($_POST['where_clause']) || ! $column->isNull)\n && isset($column->default) && $enumValue == $column->default)\n ) {\n $enumSelectedValue = $enumValue;\n break;\n }\n }\n } elseif ($column->pmaType === 'set') {\n $columnSetValues = $extractedColumnspec['enum_set_values'];\n $setSelectSize = min(4, count($extractedColumnspec['enum_set_values']));\n } elseif ($column->isBinary || $column->isBlob) {\n $isColumnProtectedBlob = ($this->config->settings['ProtectBinary'] === 'blob' && $column->isBlob)\n || ($this->config->settings['ProtectBinary'] === 'all')\n || ($this->config->settings['ProtectBinary'] === 'noblob' && ! $column->isBlob);\n if ($isColumnProtectedBlob) {\n [$blobValue, $blobValueUnit] = Util::formatByteDown(mb_strlen(stripslashes($data)), 3, 1);\n }\n\n if ($isUpload && $column->isBlob) {\n $maxUploadSize = $this->getMaxUploadSize($column->pmaType);\n }\n\n if (! empty($this->config->settings['UploadDir'])) {\n $selectOptionForUpload = $this->getSelectOptionForUpload($vkey, $fieldHashMd5);\n }\n\n if (\n ! $isColumnProtectedBlob\n && ! ($column->isBlob || ($column->length > $this->config->settings['LimitChars']))\n ) {\n $inputFieldHtml = $this->getHtmlInput(\n $column,\n $columnNameAppendix,\n $specialChars,\n min(max($column->length * 2, 4), $this->config->settings['LimitChars']),\n $onChangeClause,\n 'HEX',\n );\n }\n } else {\n $columnValue = $this->getValueColumnForOtherDatatypes(\n $column,\n $defaultCharEditing,\n $backupField,\n $columnNameAppendix,\n $onChangeClause,\n $specialChars,\n $specialCharsEncoded,\n $data,\n $extractedColumnspec,\n );\n }\n }\n\n return $this->template->render('table/insert/column_row', [\n 'db' => $db,\n 'table' => $table,\n 'column' => $column,\n 'row_id' => $rowId,\n 'show_field_types_in_data_edit_view' => $this->config->settings['ShowFieldTypesInDataEditView'],\n 'show_function_fields' => $this->config->settings['ShowFunctionFields'],\n 'is_column_binary' => $isColumnBinary,\n 'function_options' => $functionOptions,\n 'nullify_code' => $nullifyCode,\n 'real_null_value' => $realNullValue,\n 'id_index' => $this->fieldIndex,\n 'type' => $type,\n 'decimals' => $noDecimals,\n 'special_chars' => $specialChars,\n 'transformed_value' => $transformedHtml,\n 'value' => $columnValue,\n 'is_value_foreign_link' => $foreignData->foreignLink,\n 'backup_field' => $backupField,\n 'data' => $data,\n 'gis_data_types' => Gis::getDataTypes(),\n 'foreign_dropdown' => $foreignDropdown,\n 'data_type' => $dataType,\n 'textarea_cols' => $textareaCols,\n 'textarea_rows' => $textAreaRows,\n 'max_length' => $maxlength,\n 'longtext_double_textarea' => $this->config->settings['LongtextDoubleTextarea'],\n 'enum_selected_value' => $enumSelectedValue,\n 'enum_values' => $enumValues,\n 'set_values' => $columnSetValues,\n 'set_select_size' => $setSelectSize,\n 'is_column_protected_blob' => $isColumnProtectedBlob,\n 'blob_value' => $blobValue,\n 'blob_value_unit' => $blobValueUnit,\n 'is_upload' => $isUpload,\n 'max_upload_size' => $maxUploadSize,\n 'select_option_for_upload' => $selectOptionForUpload,\n 'limit_chars' => $this->config->settings['LimitChars'],\n 'input_field_html' => $inputFieldHtml,\n 'field_title' => $this->getColumnTitle($column->field, $commentsMap),\n ]);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function modifElevesSansCode($nom, $prenom, $sexe, $date_naissance, $tel_enfant, $email_enfant,$responsable_legal,$tel_parent,$tel_parent2,$tel_parent3, $profession_pere,$adresse,$profession_mere,$ville, $email_parent,$prevenir_parent,$commentaires,$cp,$assurance,$codebarre,$num,$numAllocataire,$nbTempsLibres,$contactParents,$photo)\n\t{\t\t\t\n\t\t$req = \"UPDATE `eleves` SET `NOM`='\".strtoupper($nom).\"',`PRENOM`='\".ucfirst($prenom).\"',`SEXE`='$sexe',`DATE_DE_NAISSANCE`='$date_naissance',`RESPONSABLE_LEGAL`='$responsable_legal',`PR\u00c9VENIR_EN_CAS_D_ABSENCE`='$prevenir_parent',`PROFESSION_DU_P\u00c8RE`='$profession_pere',`PROFESSION_DE_LA_M\u00c8RE`='$profession_mere',`ADRESSE_POSTALE`='$adresse',`CODE_POSTAL`='$cp',`VILLE`='\".strtoupper($ville).\"',`T\u00c9L\u00c9PHONE_DES_PARENTS`='$tel_parent',`T\u00c9L\u00c9PHONE_DES_PARENTS2`='$tel_parent2',`T\u00c9L\u00c9PHONE_DES_PARENTS3`='$tel_parent3',`T\u00c9L\u00c9PHONE_DE_L_ENFANT`='$tel_enfant',`EMAIL_DES_PARENTS`='$email_parent',`EMAIL_DE_L_ENFANT`='$email_enfant',`PHOTO`='$photo',`CONTACT_AVEC_LES_PARENTS`='$contactParents',`COMMENTAIRES`='$commentaires',`N\u00b0_ALLOCATAIRE`='$numAllocataire',`NOMBRE_TPS_LIBRE`='$nbTempsLibres',`ASSURANCE_P\u00c9RISCOLAIRE`='$assurance' WHERE `ID_ELEVE`=\" . $num . \";\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'\u00e9l\u00e8ve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n ContentService $contentService,\n LanguageService $languageService,\n LocationService $locationService,\n UserService $userService,\n ContentTypeService $contentTypeService,\n PermissionResolver $permissionResolver,\n UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,\n CreateUserOnTheFlyDispatcher $createUserActionDispatcher,\n EditUserOnTheFlyDispatcher $editUserActionDispatcher\n ) {\n $this->contentService = $contentService;\n $this->locationService = $locationService;\n $this->languageService = $languageService;\n $this->userService = $userService;\n $this->contentTypeService = $contentTypeService;\n $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;\n $this->createUserActionDispatcher = $createUserActionDispatcher;\n $this->editUserActionDispatcher = $editUserActionDispatcher;\n $this->permissionResolver = $permissionResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n ContentService $contentService,\n ContentTypeService $contentTypeService,\n LanguageService $languageService,\n LocationService $locationService,\n ObjectStateService $objectStateService,\n URLAliasService $urlAliasService,\n RoleService $roleService,\n UserService $userService,\n BookmarkService $bookmarkService,\n ValueFactory $valueFactory,\n ConfigResolverInterface $configResolver,\n ?LoggerInterface $logger = null\n ) {\n $this->contentService = $contentService;\n $this->contentTypeService = $contentTypeService;\n $this->languageService = $languageService;\n $this->locationService = $locationService;\n $this->objectStateService = $objectStateService;\n $this->urlAliasService = $urlAliasService;\n $this->roleService = $roleService;\n $this->userService = $userService;\n $this->bookmarkService = $bookmarkService;\n $this->valueFactory = $valueFactory;\n $this->configResolver = $configResolver;\n $this->logger = $logger ?? new NullLogger();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function pageselector(\n string $name,\n int $rows,\n int $pageNow = 1,\n int $nbTotalPage = 1,\n int $showAll = 200,\n int $sliceStart = 5,\n int $sliceEnd = 5,\n int $percent = 20,\n int $range = 10,\n string $prompt = '',\n ): string {\n $increment = floor($nbTotalPage / $percent);\n $pageNowMinusRange = $pageNow - $range;\n $pageNowPlusRange = $pageNow + $range;\n\n $gotoPage = $prompt . ' ';\n\n return $gotoPage;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function systemd_data_update_helper(\n $device,\n $app_id,\n $fields,\n $metrics,\n $name,\n $polling_type,\n $rrd_def,\n $state_type,\n $rrd_flattened_name\n ) {\n $rrd_flattened_name = is_null($rrd_flattened_name)\n ? $state_type\n : $rrd_flattened_name;\n $rrd_name = [$polling_type, $name, $app_id, $rrd_flattened_name];\n\n // This if block allows metric names to be kept consistent\n // regardless of whether the metric is stored in an shared\n // or individual RRD.\n if (isset($metrics[$state_type])) {\n $metrics[$state_type] = array_merge($metrics[$state_type], $fields);\n } else {\n $metrics[$state_type] = $fields;\n }\n\n $tags = [\n 'name' => $name,\n 'app_id' => $app_id,\n 'type' => $state_type,\n 'rrd_def' => $rrd_def,\n 'rrd_name' => $rrd_name,\n ];\n data_update($device, $polling_type, $tags, $fields);\n\n return $metrics;\n }", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function creerDossierIBUpload($client, $ref_dos, $num_lic, $cod, $fxi, $montant_av, \n\t\t\t\t\t\t\t\t\t\t$date_fact, $ref_fact, $fob, $fret, \n\t\t\t\t\t\t\t\t\t\t$assurance, $autre_frais, $ref_decl, $montant_decl, \n\t\t\t\t\t\t\t\t\t\t$ref_liq, $id_util, $ref_quit, $date_quit, $id_mod_lic){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;$entree['num_lic'] = $num_lic;\n\t\t\t$entree['fxi'] = $fxi;$entree['montant_av'] = $montant_av;\n\t\t\t$entree['date_fact'] = $date_fact;$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['fob'] = $fob;$entree['fret'] = $fret;$entree['assurance'] = $assurance;\n\t\t\t$entree['autre_frais'] = $autre_frais;$entree['montant_decl'] = $montant_decl;\n\t\t\t$entree['ref_liq'] = $ref_liq;$entree['id_util'] = $id_util;$entree['ref_quit'] = $ref_quit;\n\t\t\t$entree['date_quit'] = $date_quit;$entree['cod'] = $cod;$entree['ref_decl'] = $ref_decl;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload(client, ref_dos, num_lic, fxi, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmontant_av, date_fact, ref_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfob, fret, assurance, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tautre_frais, ref_decl, montant_decl, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_liq, id_util, ref_quit,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate_quit, cod, id_mod_lic) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['num_lic'], $entree['fxi'], \n\t\t\t\t\t\t\t\t\t$entree['montant_av'], $entree['date_fact'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['ref_decl'], $entree['montant_decl'], \n\t\t\t\t\t\t\t\t\t$entree['ref_liq'], $entree['id_util'], $entree['ref_quit'], \n\t\t\t\t\t\t\t\t\t$entree['date_quit'], $entree['cod'], $entree['id_mod_lic']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(string $publicKeyCredentialId, string $type, array $transports, string $attestationType, TrustPath $trustPath, UuidInterface $aaguid, string $credentialPublicKey, string $userHandle, int $counter, ?array $otherUI = null)\n {\n $this->publicKeyCredentialId = $publicKeyCredentialId;\n $this->type = $type;\n $this->transports = $transports;\n $this->aaguid = $aaguid;\n $this->credentialPublicKey = $credentialPublicKey;\n $this->userHandle = $userHandle;\n $this->counter = $counter;\n $this->attestationType = $attestationType;\n $this->trustPath = $trustPath;\n $this->otherUI = $otherUI;\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function getimage_cache($notice_id=0, $etagere_id=0, $authority_id=0, $vigurl=0, $noticecode=0, $url_image=0, $empr_pic=0, $cached_in_opac = 0){\n global $pmb_notice_img_folder_id, $pmb_authority_img_folder_id, $opac_url_base,$empr_pics_max_size;\n\n\tglobal $pmb_img_cache_folder, $opac_img_cache_folder;\n\n\tif(!$cached_in_opac){\n\t\t$img_cache_folder = $pmb_img_cache_folder;\n\t}else{\n\t\t$img_cache_folder = $opac_img_cache_folder;\n\t}\n\n\t$stop = false;\n\t$hash = $location = $hash_location = $hash_location_empty = \"\";\n\n\t$imgpmb_name=$imgpmb_test=\"\";\n\tif($notice_id){\n\t\t$imgpmb_name=\"img_\".$notice_id;\n\t\t$imgpmb_test=$pmb_notice_img_folder_id;\n\t}elseif($etagere_id){\n\t\t$imgpmb_name=\"img_etag_\".$etagere_id;\n\t\t$imgpmb_test=$pmb_notice_img_folder_id;\n\t}elseif($authority_id){\n\t\t$imgpmb_name=\"img_authority_\".$authority_id;\n\t\t$imgpmb_test=$pmb_authority_img_folder_id;\n\t}\n\n\tif(!$stop && $imgpmb_name && $imgpmb_test){\n\t\t$req = \"select repertoire_path from upload_repertoire where repertoire_id ='\".$imgpmb_test.\"'\";\n\t\t$res = pmb_mysql_query($req);\n\t\tif(pmb_mysql_num_rows($res)){\n\t\t\t$rep = pmb_mysql_fetch_array($res,PMB_MYSQL_NUM);\n\t\t\t$location = $rep[0].$imgpmb_name;\n\t\t\tif($img_cache_folder && file_exists($location)){\n\t\t\t\t$hash = md5($opac_url_base.$location);\n\t\t\t\t$hash_location = $img_cache_folder.$hash.\".png\";\n\t\t\t\tif(file_exists($hash_location)){\n\t\t\t\t\t$location = $hash_location;\n\t\t\t\t\t$hash_location = \"\";\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t//Gestion de l'existance du fichier non gr, comme c'tait le cas avant\n\t\t\t}\n\t\t\t$stop = true;\n\t\t}\n\t}\n\n\tif(!$stop && $img_cache_folder){\n\t\t$hash_image=\"\";\n\t\tif($vigurl){\n\t\t\t$hash_image.=$vigurl;\n\t\t}\n\t\tif($noticecode){\n\t\t\t$hash_image.=$noticecode;\n\t\t}\n\t\tif($url_image){\n\t\t\t$hash_image.=$url_image;\n\t\t}\n\t\tif($empr_pic && $empr_pics_max_size){\n\t\t\t$hash_image.=$empr_pics_max_size;\n\t\t}\n\t\tif($hash_image){\n\t\t\t$hash=md5($hash_image);\n\t\t\t$image_rep_cache=$img_cache_folder.$hash.\".png\";\n\t\t\t//Pour les images vides elles peuvent changer entre les PMB, la gestion et l'Opac\n\t\t\t$hash_img_empty=md5($hash_image.$opac_url_base.$cached_in_opac);\n\t\t\t$image_empty_rep_cache=$img_cache_folder.$hash_img_empty.\".png\";\n\t\t\tif(file_exists($image_empty_rep_cache)){\n\t\t\t\t$location = $image_empty_rep_cache;\n\t\t\t}elseif(file_exists($image_rep_cache) && !isimage_cache_white_pixel($image_rep_cache)){\n\t\t\t\t$location = $image_rep_cache;\n\t\t\t}else{\n\t\t\t\t//on teste l'existence de rpertoire de cache pour viter les erreurs et les liens casss\n\t\t\t\tif (file_exists($img_cache_folder)) {\n\t\t\t\t\t$hash_location = $image_rep_cache;\n\t\t\t\t\t$hash_location_empty = $image_empty_rep_cache;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t$tmp = array(\"hash\" => $hash, \"location\" => $location, \"hash_location\" => $hash_location, \"hash_location_empty\" => $hash_location_empty);\n\treturn $tmp;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_7.5.8", "language": "php"} {"function": "public function creerDossierLogistique($ref_dos, $ref_mca, $road_manif, $ref_fact, \n\t\t\t\t\t\t\t\t\t\t$ref_batch, $poids, $ref_po, $montant_po, $origine, \n\t\t\t\t\t\t\t\t\t\t$destination, $transit, $id_cli, \n\t\t\t\t\t\t\t\t\t\t$id_mod_trans, $id_trans, $id_util){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['ref_dos'] = $ref_dos;\n\t\t\t$entree['ref_mca'] = $ref_mca;\n\t\t\t$entree['road_manif'] = $road_manif;\n\t\t\t$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['ref_batch'] = $ref_batch;\n\t\t\t$entree['poids'] = $poids;\n\t\t\t$entree['ref_po'] = $ref_po;\n\t\t\t$entree['montant_po'] = $montant_po;\n\t\t\t$entree['origine'] = $origine;\n\t\t\t$entree['destination'] = $destination;\n\t\t\t$entree['transit'] = $transit;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_trans'] = $id_trans;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_logistique(ref_dos, ref_mca, road_manif, ref_fact, ref_batch, poids, ref_po, montant_po, origine, destination, transit, id_cli, id_mod_trans, id_trans, id_util, statut) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \\'IN TRANSIT\\')');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['ref_mca'], $entree['road_manif'], $entree['ref_fact'], $entree['ref_batch'], $entree['poids'], $entree['ref_po'], $entree['montant_po'], $entree['origine'], $entree['destination'], $entree['transit'], $entree['id_cli'], $entree['id_mod_trans'], $entree['id_trans'], $entree['id_util']));\n\t\t\t\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n CustomerRepository $customerRepository,\n AttributeRepository $attributeRepository,\n ProductRepository $productRepository,\n ProductAttributeValueRepository $attributeValueRepository,\n ProductInventoryRepository $productInventoryRepository,\n ProductImageRepository $productImageRepository,\n ProductVideoRepository $productVideoRepository,\n ProductCustomerGroupPriceRepository $productCustomerGroupPriceRepository,\n protected ProductBundleOptionRepository $productBundleOptionRepository,\n protected ProductBundleOptionProductRepository $productBundleOptionProductRepository,\n protected BundleOption $bundleOptionHelper\n ) {\n parent::__construct(\n $customerRepository,\n $attributeRepository,\n $productRepository,\n $attributeValueRepository,\n $productInventoryRepository,\n $productImageRepository,\n $productVideoRepository,\n $productCustomerGroupPriceRepository\n );\n }", "smellKey": "S107", "smellId": null, "repo": "ahmadabdoul_bagisto", "language": "php"} {"function": "public function modifIntervenantSansCode($num, $nom, $prenom, $actif, $date_naissance, $lieu_naissance,$tel, $adresse,$statut, $cp, $ville,$email,$commentaires,$diplome,$numsecu,$nationalite,$photo,$iban,$bic,$compte,$banque,$serviceCivique)\n\t{\n\t\t$req = \"UPDATE `intervenants` SET `NOM`='$nom',`PRENOM`='$prenom',`ACTIF`=$actif,`STATUT`='$statut',`EMAIL`='$email',`TELEPHONE`='$tel',`ADRESSE_POSTALE`='$adresse',`CODE_POSTAL`='$cp',`VILLE`='$ville',`DIPLOME`='$diplome',`COMMENTAIRES`='$commentaires',`DATE_DE_NAISSANCE`='$date_naissance',`LIEU_DE_NAISSANCE`='$lieu_naissance',`NATIONALITE`='$nationalite',`SECURITE_SOCIALE`='$numsecu',`PHOTO`='$photo', IBAN='$iban', BIC='$bic', COMPTEBANCAIRE='$compte', BANQUE='$banque', SERVICECIVIQUE='$serviceCivique' WHERE `ID_INTERVENANT`=$num\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null)\n{\n global $today;\n $encounter = todaysTherapyGroupEncounterIf($group_id);\n if ($encounter) {\n if ($return_existing) {\n return $encounter;\n } else {\n return 0;\n }\n }\n\n if (is_array($provider)) {\n $visit_provider = (int)$provider[0];\n $counselors = implode(',', $provider);\n } elseif ($provider) {\n $visit_provider = $counselors = (int)$provider;\n } else {\n $visit_provider = $counselors = null;\n }\n\n $dos = $enc_date ? $enc_date : $today;\n $visit_reason = $reason ? $reason : xl('Please indicate visit reason');\n $tmprow = sqlQuery(\"SELECT username, facility, facility_id FROM users WHERE id = ?\", array($_SESSION[\"authUserID\"]));\n $username = $tmprow['username'];\n $facility = $tmprow['facility'];\n $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];\n $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];\n $visit_cat = $cat ? $cat : '(NULL)';\n $conn = $GLOBALS['adodb']['db'];\n $encounter = $conn->GenID(\"sequences\");\n addForm(\n $encounter,\n \"New Therapy Group Encounter\",\n sqlInsert(\n \"INSERT INTO form_groups_encounter SET \" .\n \"date = ?, \" .\n \"reason = ?, \" .\n \"facility = ?, \" .\n \"facility_id = ?, \" .\n \"billing_facility = ?, \" .\n \"provider_id = ?, \" .\n \"group_id = ?, \" .\n \"encounter = ?,\" .\n \"pc_catid = ? ,\" .\n \"appt_id = ? ,\" .\n \"counselors = ? \",\n array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)\n ),\n \"newGroupEncounter\",\n null,\n \"1\",\n \"NOW()\",\n $username,\n \"\",\n $group_id\n );\n return $encounter;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function normalcurve($mu, $sigma, $a, $b, $axislabel='',$x=null, $dirx='left', $y=null, $diry='right', $color='blue', $w=400,$h=150) {\n if ($sigma<=0) { echo 'Invalid sigma'; return;}\n if ($y!==null && $y<$x) { echo 'Second value should be bigger than the first'; return; }\n if ($a>=$b) { echo 'xmin should be smaller than xmax'; return; }\n if ($y!==null && $dirx==$diry) { echo 'directions should not be equal'; return;}\n\n $za = ($a-$mu)/$sigma;\n $zb = ($b-$mu)/$sigma;\n if ($x!==null) {\n \t $zx = ($x-$mu)/$sigma;\n }\n if ($y!==null) {\n $zy = ($y-$mu)/$sigma;\n }\n $dz = ($zb-$za)/80;\n $zab=$za-$sigma;\n $zbb=$zb+$sigma;\n $plot = \"setBorder(10,30,10,5);initPicture($za,$zb,-.1,.45);line([$zab,0],[$zbb,0]);\";\n for ($i=ceil($za);$i<$zb+$dz;$i++) {\n\t$label = $mu + $i*$sigma;\n\t$plot .= \"line([$i,.02],[$i,-.02]);text([$i,-.01],\\\"$label\\\",\\\"below\\\");\";\n }\n\n $midx = $w/2;\n $plot .= \"textabs([$midx,0],'$axislabel','above');\";\n $pts = array();\n $xpts = array();\n $ypts = array();\n\n $coef = 1/sqrt(2*3.1415926);\n\n if ($x !== null && $dirx=='right') {\n $py = $coef*exp(-$zx*$zx/2);\n $xpts[] = \"[$zx,0]\";\n $xpts[] = \"[$zx,$py]\";\n }\n if ($y !== null && $diry=='right') {\n $py = $coef*exp(-$zy*$zy/2);\n $ypts[] = \"[$zy,$py]\";\n }\n\n\n for ($z=$za;$z<=$zb+.00001;$z+=$dz) {\n\t$py = $coef*exp(-$z*$z/2);\n $pts[] = \"[$z,$py]\";\n if ($x !== null && (($dirx == 'left' && $z<$zx) || ($dirx == 'right' && $z>$zx && ($y===null || $z<$zy )))) {\n $xpts[] = \"[$z,$py]\";\n }\n if ($y !== null && $diry=='right' && $z>$zy) {\n $ypts[] = \"[$z,$py]\";\n }\n }\n if ($x !== null && $dirx=='left') {\n $py = $coef*exp(-$zx*$zx/2.0);\n $xpts[] = \"[$zx,$py]\";\n $xpts[] = \"[$zx,0]\";\n $xpts[] = \"[$za,0]\";\n }\n if ($x !== null && $dirx=='right' && $y===null) {\n $xpts[] = \"[$zb,0]\";\n }\n if ($y !== null && $diry=='left') {\n $py = $coef*exp(-$zy*$zy/2.0);\n $xpts[] = \"[$zy,$py]\";\n $xpts[] = \"[$zy,0]\";\n $xpts[] = \"[$zx,0]\";\n }\n if ($y !== null && $diry=='right') {\n $ypts[] = \"[$zb,0]\";\n $ypts[] = \"[$zy,0]\";\n }\n\n $plot .= 'fill=\"none\";path([' . implode(',',$pts) . ']);';\n if ($x !== null) {\n $plot .= 'fill=\"'.$color.'\";path([' . implode(',',$xpts) . ']);';\n }\n if ($y !== null && $diry=='right') {\n $plot .= 'fill=\"'.$color.'\";path([' . implode(',',$ypts) . ']);';\n }\n\n return showasciisvg($plot,$w,$h);\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function makeTchartsfromjournal($j, $order, $sn, &$anstypes, &$answer, &$showanswer, &$displayformat, &$answerboxsize, $showtotal=true) {\n\t$out = '';\n\t$debits = array(); $credits = array();\n\tforeach ($j as $jd) {\n if (isset($jd['debits'])) {\n for ($i=0;$i$max) {\n\t\t\t$max = count($debits[$o]);\n\t\t}\n\t\tif (isset($credits[$o]) && count($credits[$o])>$max) {\n\t\t\t$max = count($credits[$o]);\n\t\t}\n\t}\n\tif (isset($j[0]['numrows'])) {\n\t\t$max = $j[0]['numrows'];\n\t}\n\t$showanswer .= '
    ';\n\tforeach ($order as $o) {\n\t\tif (!isset($debits[$o])) {$debits[$o] = array();}\n\t\tif (!isset($credits[$o])) {$credits[$o] = array();}\n\t\t$out .= makeTchart($o, $max, $debits[$o], $credits[$o], $sn, $anstypes, $answer, $showanswer, $displayformat, $answerboxsize,true, $showtotal);\n\t\t$sn += $max*2 + ($showtotal?2:0);\n\t}\n\t$out .= '
    ';\n\t$showanswer .= '

     

    ';\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function create_data($pid, $encounter, $sections, $components, $recipients, $params, $document_type, $referral_reason, int $send = null, $date_options = [])\n {\n global $assignedEntity;\n global $representedOrganization;\n\n $this->getEncounterccdadispatchTable()->setOptions($pid, $encounter, $date_options);\n\n if (!$send) {\n $send = 0;\n }\n\n $serviceStartDates = $this->getServiceStartDates($pid, $encounter, $document_type, $date_options);\n\n $sections_list = explode('|', $sections);\n $components_list = explode('|', $components);\n $this->createdtime = time();\n $this->data .= \"\";\n $this->data .= \"\" . $GLOBALS['webroot'] . \"\";\n $this->data .= \"\" . $GLOBALS['OE_SITE_DIR'] . \"\";\n $this->data .= \"\";\n $this->data .= \"\";\n $this->data .= \"MyHealth\";\n $this->data .= \"\" . xmlEscape($serviceStartDates['start']) . \"\";\n $this->data .= \"\" . xmlEscape($serviceStartDates['end']) . \"\";\n $this->data .= \"\";\n $this->data .= \"\" . date('YmdHis') . \"\";\n $this->data .= \"\" . date('YmdHisO') . \"\";\n $this->data .= \"\" . date('O') . \"\";\n $this->data .= \"\" . htmlspecialchars($send, ENT_QUOTES) . \"\";\n $this->data .= \"\" . $document_type . \"\";\n $this->data .= \"\n \" . htmlspecialchars($assignedEntity['streetAddressLine'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($assignedEntity['city'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($assignedEntity['state'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($assignedEntity['postalCode'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($assignedEntity['country'] ?? '', ENT_QUOTES) . \"\n \n \n \n \" . htmlspecialchars($representedOrganization['name'] ?? '', ENT_QUOTES) . \"\n \n \" . htmlspecialchars($representedOrganization['street'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($representedOrganization['city'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($representedOrganization['state'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($representedOrganization['postal_code'] ?? '', ENT_QUOTES) . \"\n \" . htmlspecialchars($representedOrganization['country'] ?? '', ENT_QUOTES) . \"\n \";\n $this->data .= \"\" . htmlspecialchars($referral_reason ?: '', ENT_QUOTES) . \"\";\n\n /***************CCDA Header Information***************/\n $this->data .= $this->getEncounterccdadispatchTable()->getPatientdata($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getProviderDetails($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getAuthor($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getDataEnterer($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getInformant($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getCustodian($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getInformationRecipient($pid, $encounter, $recipients, $params);\n $this->data .= $this->getEncounterccdadispatchTable()->getLegalAuthenticator($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getDocumentParticipants($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getAuthenticator($pid, $encounter);\n $this->data .= $this->getEncounterccdadispatchTable()->getPrimaryCareProvider($pid, $encounter);\n /***************CCDA Header Information***************/\n\n /***************CCDA Body Information***************/\n if (in_array('encounters', $components_list)) {\n $this->data .= $this->getEncounterccdadispatchTable()->getEncounterHistory($pid);\n }\n\n if (in_array('continuity_care_document', $sections_list)) {\n $this->data .= $this->getContinuityCareDocument($pid, $components_list, $encounter);\n }\n\n // we're sending everything anyway. document type will tell engine what to include in cda.\n $this->data .= $this->getEncounterccdadispatchTable()->getClinicalNotes($pid, $encounter);\n\n if (in_array('progress_note', $sections_list)) {\n $this->data .= $this->getEncounterccdadispatchTable()->getProgressNotes($pid, $encounter);\n }\n\n if (in_array('discharge_summary', $sections_list)) {\n $this->data .= $this->getDischargeSummary($pid, $encounter);\n }\n\n if (in_array('procedure_note', $sections_list)) {\n $this->data .= $this->getProcedureNotes($pid, $encounter);\n }\n\n if (in_array('operative_note', $sections_list)) {\n $this->data .= $this->getOperativeNotes($pid, $encounter);\n }\n\n if (in_array('consultation_note', $sections_list)) {\n $this->data .= $this->getConsultationNote($pid, $encounter);\n }\n\n if (in_array('history_physical_note', $sections_list)) {\n $this->data .= $this->getHistoryAndPhysicalNotes($pid, $encounter, $components_list);\n }\n\n if (in_array('unstructured_document', $sections_list)) {\n $this->data .= $this->getEncounterccdadispatchTable()->getUnstructuredDocuments($pid, $encounter);\n }\n\n if ($this->exportwithDocuments) {\n $this->data .= $this->getEncounterccdadispatchTable()->getDocumentsForExport($pid, $encounter);\n }\n\n /***************CCDA Body Information***************/\n\n $this->data .= \"\";\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function createOrUpdate(\n ?string $filename = null,\n ?string $title = null,\n ?string $type = null,\n ?Signalement $signalement = null,\n ?User $user = null,\n bool $flush = false,\n ?DocumentType $documentType = null,\n ?string $description = null\n ): File {\n /** @var FileRepository $fileRepository */\n $fileRepository = $this->getRepository();\n $file = $fileRepository->findOneBy(['filename' => $filename]);\n if (null === $file) {\n $file = $this->fileFactory->createInstanceFrom(\n filename: $filename,\n title: $title,\n type: $type,\n signalement: $signalement,\n user: $user,\n documentType: $documentType,\n description: $description\n );\n }\n\n $file\n ->setTitle($title)\n ->setFileType($type)\n ->setSignalement($signalement)\n ->setDocumentType($documentType ?? DocumentType::AUTRE)\n ->setDescription($description);\n\n $this->save($file, $flush);\n\n return $file;\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public static function listSuggestions($id_bibli=0, $statut='-1', $num_categ='-1', $mask='', $debut=0, $nb_per_page=0, $aq=0, $order='',$location=0, $user_input='',$source=0, $user_id=0, $user_statut = array(), $date_inf='', $date_sup='') {\n\t\t\n\t\tif($source) \n\t\t\t$filtre_src = \" sugg_source = '\".$source.\"' \";\n\t\telse $filtre_src=\" 1 \";\n\t\t\n\t\tif (!$statut) $statut='-1';\n\t\tif ($statut == '-1') { \n\t\t\t$filtre1 = '1';\n\t\t} elseif ($statut == $mask) {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = '\".$mask.\"' \";\n\t\t} else {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = 0 and (statut & \".$statut.\") = '\".$statut.\"' \";\n\t\t}\n\t\t\t\n\t\tif ($num_categ == '-1') {\n\t\t\t$filtre2 = '1';\n\t\t} else {\n\t\t\t$filtre2 = \"num_categ = '\".$num_categ.\"' \";\n\t\t}\n\n\t\tif (!$id_bibli) $filtre3 = '1';\n\t\t\telse $filtre3.= \"num_entite = '\".$id_bibli.\"' \";\n\n\t\tif ($location == 0) {\n\t\t\t$filtre4 = '1';\n\t\t} else {\n\t\t\t$filtre4 = \"sugg_location = '\".$location.\"' \";\n\t\t}\t\n\n\t\tif (!trim($date_inf) && !trim($date_sup)) {\n\t\t\t$filtre5 = '1';\n\t\t} else {\n\t\t\tif (trim($date_inf) && trim($date_sup)) {\n\t\t\t\t$filtre5 = \"(date_creation BETWEEN '\".$date_inf.\"' AND '\".$date_sup.\"')\";\n\t\t\t} elseif (trim($date_inf)) {\n\t\t\t\t$filtre5 = \"date_creation >= '\".$date_inf.\"'\";\n\t\t\t} else {\n\t\t\t\t$filtre5 = \"date_creation <= '\".$date_sup.\"'\";\n\t\t\t}\n\t\t}\n\t\t\n\t\t$filtre_empr='';\n\t\t$tab_empr=array();\n\t\t$filtre_user='';\n\t\t$tab_user=array();\n\t\t$filtre_visitor='';\n\t\t$tab_visitor=array();\n\t\tif (is_array($user_id) && count($user_id) && is_array($user_statut) && count($user_statut)) {\n\t\t\tforeach ($user_id as $k=>$id) {\n\t\t\t\tif ($user_statut[$k] == \"0\") {\n\t\t\t\t\t$tab_user[] = $id;\n\t\t\t\t}\n\t\t\t\tif ($user_statut[$k] == \"1\") {\n\t\t\t\t\t$tab_empr[] = $id;\n\t\t\t\t}\n\t\t\t\tif ($user_statut[$k] == \"2\") {\n\t\t\t\t\t$tab_visitor[] = $id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (is_array($tab_empr) && count($tab_empr)) {\n\t\t\t$filtre_empr = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_empr).\"') and type_origine='1' \";\n\t\t}\n\t\tif (is_array($tab_user) && count($tab_user)) {\n\t\t\t$filtre_user = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_user).\"') and type_origine='0' \";\n\t\t}\n\t\tif (is_array($tab_visitor) && count($tab_visitor)) {\n\t\t\t$filtre_visitor = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_visitor).\"') and type_origine='2' \";\n\t\t}\n\t\tif ($filtre_empr!=\"\" || $filtre_user!=\"\" || $filtre_visitor!=\"\") {\n\t\t\t$table_origine = \", suggestions_origine \";\n\t\t\t$join_origine = \" id_suggestion=num_suggestion \";\n\t\t\t\t\n\t\t\t$deja_filtre = false;\n\t\t\t$clause_origine = \" and (\";\n\t\t\tif ($filtre_empr) {\n\t\t\t\t$clause_origine.=\" (\".$filtre_empr.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\tif ($filtre_user) {\n\t\t\t\tif ($deja_filtre) {\n\t\t\t\t\t$clause_origine.=\" or \";\n\t\t\t\t}\n\t\t\t\t$clause_origine.=\" (\".$filtre_user.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\tif ($filtre_visitor) {\n\t\t\t\tif ($deja_filtre) {\n\t\t\t\t\t$clause_origine.=\" or \";\n\t\t\t\t}\n\t\t\t\t$clause_origine.=\" (\".$filtre_visitor.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\t$clause_origine.= \" ) and \";\n\t\t} else {\n\t\t\t$table_origine = \"\";\n\t\t\t$join_origine = \"\";\n\t\t\t$clause_origine = \"\";\n\t\t}\n\t\t\n\t\tif(!$aq) {\n\t\t\t\n\t\t\t$q = \"select * from suggestions $table_origine\";\n\t\t\t$q.= \"where $join_origine $clause_origine \".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4 .\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t\tif(!$order) $q.=\"order by statut, date_creation desc \";\n\t\t\t\telse $q.= \"order by\".$order.\" \";\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t$isbn = '';\n\t\t\t$t_codes = array();\n\t\t\t\n\t\t\tif ($user_input!=='') {\n\t\t\t\tif (isEAN($user_input)) {\n\t\t\t\t\t// la saisie est un EAN -> on tente de le formater en ISBN\n\t\t\t\t\t$isbn = EANtoISBN($user_input);\n\t\t\t\t\tif($isbn) {\n\t\t\t\t\t\t$t_codes[] = $isbn;\n\t\t\t\t\t\t$t_codes[] = formatISBN($isbn,10);\n\t\t\t\t\t}\n\t\t\t\t} elseif (isISBN($user_input)) {\n\t\t\t\t\t// si la saisie est un ISBN\n\t\t\t\t\t$isbn = formatISBN($user_input);\n\t\t\t\t\tif($isbn) { \n\t\t\t\t\t\t$t_codes[] = $isbn ;\n\t\t\t\t\t\t$t_codes[] = formatISBN($isbn,13);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (count($t_codes)) {\n\n\t\t\t\t$q = \"select * from suggestions $table_origine\";\n\t\t\t\t$q.= \"where $join_origine $clause_origine (\".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4.\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t\t\t$q.= \") \"; \n\t\t\t\t$q.= \"and ('0' \";\n\t\t\t\tforeach ($t_codes as $v) {\n\t\t\t\t\t$q.= \"or code like '%\".$v.\"%' \";\n\t\t\t\t}\n\t\t\t\t$q.=\") \";\n\t\t\t\tif(!$order) $q.=\"order by statut, date_creation desc \";\n\t\t\t\t\telse $q.= \"order by\".$order.\" \";\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\n\t\t\t\t$members=$aq->get_query_members(\"suggestions\",\"concat(titre,' ',editeur,' ',auteur,' ',commentaires)\",\"index_suggestion\",\"id_suggestion\");\n\t\t\t\t\n\t\t\t\t$q = $q = \"select *, \".$members[\"select\"].\" as pert from suggestions $table_origine \";\n\t\t\t\t$q.= \"where $join_origine $clause_origine (\".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4.\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t\t\t$q.= \") \"; \n\t\t\t\t$q.= \"and (\".$members[\"where\"].\" \";\n\t\t\t\tforeach ($t_codes as $v) {\n\t\t\t\t\t$q.= \"or index_suggestion like ('%\".$v.\"%') \";\n\t\t\t\t}\n\t\t\t\t$q.=\") \";\n\t\t\t\n\t\t\t\tif (!$order) {\n\t\t\t\t\t$q.= \"order by pert desc \";\t\n\t\t\t\t} else {\n\t\t\t\t\t$q.= \"order by \".$order.\", pert desc \";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!$debut && $nb_per_page) $q.= \"limit \".$nb_per_page;\n\t\tif ($debut && $nb_per_page) $q.= \"limit \".$debut.\",\".$nb_per_page;\n\t\treturn $q;\t\t\t\t\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct(IConfig $config,\n\t\tIMailer $mailer,\n\t\tLoggerInterface $logger,\n\t\tITimeFactory $timeFactory,\n\t\tDefaults $defaults,\n\t\tIUserManager $userManager,\n\t\t$userId,\n\t\tIMipService $imipService,\n\t\tEventComparisonService $eventComparisonService) {\n\t\tparent::__construct('');\n\t\t$this->userId = $userId;\n\t\t$this->config = $config;\n\t\t$this->mailer = $mailer;\n\t\t$this->logger = $logger;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->defaults = $defaults;\n\t\t$this->userManager = $userManager;\n\t\t$this->imipService = $imipService;\n\t\t$this->eventComparisonService = $eventComparisonService;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function Create($type, $datasetId, $clippingItemId, $clippingCircle, $urbanity, $partition, $model, $fromDraft)\n\t{\n\t\t$ret = new DownloadStateBag();\n\t\t$ret->Initialize();\n\t\t$folder = $ret->GetFolder();\n\t\tif ($fromDraft)\n\t\t\t$key = BackofficeDownloadCache::CreateKey($type);\n\t\telse\n\t\t\t$key = DownloadCache::CreateKey($type, $clippingItemId, $clippingCircle, $urbanity, $partition);\n\n\t\t$ret->SetArray(array(\n\t\t\t'type' => $type,\n\t\t\t'datasetId' => $datasetId,\n\t\t\t'clippingItemId' => $clippingItemId,\n\t\t\t'clippingCircle' => $clippingCircle,\n\t\t\t'urbanity' => $urbanity,\n\t\t\t'partition' => $partition,\n\t\t\t'cacheKey' => $key,\n\t\t\t'outFile' => $folder . '/outfile',\n\t\t\t'dFile' => $folder . '/intermediate_data.json',\n\t\t\t'fullQuery' => $model->fullQuery,\n\t\t\t'countQuery' => $model->countQuery,\n\t\t\t'fullParams' => $model->fullParams,\n\t\t\t'extraColumns' => null,\n\t\t\t'cols' => $model->fullCols,\n\t\t\t'fromDraft' => $fromDraft,\n\t\t\t'areSegments' => false,\n\t\t\t'wktIndex' => $model->wktIndex,\n\t\t\t'index' => 0,\n\t\t\t'start' => 0,\n\t\t\t'progressLabel' => 'Creando archivo'\n\t\t));\n\t\treturn $ret;\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "function matrixrowcombine3($m,$r1,$a,$r2,$b,$r3,$c,$s) {\n\tif (!isMatrix($m)) { if ($GLOBALS['myrights']>10) { echo 'error: input matrixrowcombine3 not a matrix'; } return '';}\n\tfor ($j=0; $jref_pv = '.$ref_pv;\n\t\t\t// echo '
    date_pv = '.$date_pv;\n\t\t\t// echo '
    date_reception = '.$date_reception;\n\t\t\t// echo '
    id_bur_douane = '.$id_bur_douane;\n\t\t\t// echo '
    annee = '.$annee;\n\t\t\t// echo '
    marchandise = '.$marchandise;\n\t\t\t// echo '
    id_cli = '.$id_cli;\n\t\t\t// echo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\t// echo '
    fichier_pv= '.$fichier_pv;\n\t\t\t// echo '
    id_util = '.$id_util;\n\n\t\t\t$requete = $connexion-> prepare('UPDATE pv_contencieux\n\t\t\t\t\t\t\t\t\t\t\t\tSET ref_pv = ?, date_pv = ?, date_reception = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\tid_bur_douane = ?, annee = ?, marchandise = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\tid_cli = ?, id_mod_lic = ?, id_etat = ?, remarque = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\tdate_deb_contrad = ?, date_next_pres = ?, delai_grief = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\tinfraction = ?, droit_cdf = ?, droit_usd = ?, amende_cdf = ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\tamende_usd = ?, risque_potentiel = ?\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE id_pv = ?');\n\t\t\t$requete-> execute(array($entree['ref_pv'], $entree['date_pv'], $entree['date_reception'], $entree['id_bur_douane'], $entree['annee'], $entree['marchandise'], $entree['id_cli'], $entree['id_mod_lic'], $entree['id_etat'], $entree['remarque'], $entree['date_deb_contrad'], $entree['date_next_pres'], $entree['delai_grief'], $entree['infraction'], $entree['droit_cdf'], $entree['droit_usd'], $entree['amende_cdf'], $entree['amende_usd'], $entree['risque_potentiel'], $entree['id_pv']));\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function makeaccttable($rowhead, $rows, $anshead, $ansarray, $sn, &$anstypes, &$answer, &$showanswer, &$displayformat, &$answerboxsize) {\n\tif (!is_array($rowhead)) {\n\t\t$rowhead = array($rowhead);\n\t\t$rows = array($rows);\n\t\t$anshead = array($anshead);\n\t\t$ansarray = array($ansarray);\n\t}\n\n\tif ($anstypes === null) { $anstypes = array();}\n\tif ($answer === null) { $answer = array();}\n\tif ($showanswer === null) { $showanswer = '';}\n\tif ($displayformat === null) { $displayformat = array();}\n\n\t$maxsize = array(); $hasdecimals = false;\n\tfor ($j=0;$j$maxsize[$j]) { $maxsize[$j] = $sl;}\n\t\t\tif (!$hasdecimals && strpos($ansarray[$j][$i],'.')!==false) { $hasdecimals = true;}\n\t\t}\n\t}\n $out = '';\n\n\t$hashead = false;\n\tfor ($j=0;$j';\n\t\t\t$hashead = true;\n\t\t}\n\t}\n\tfor ($j=0;$j';\n\t\t\t$hashead = true;\n\t\t}\n\t}\n\tif ($hashead) {\n\t\t$out = ''.$out.'';\n\t} else {\n\t\t$out = '
    ';\n\t}\n\t$out .= '';\n\t$sa = $out;\n\tfor ($i=0;$i';\n\t\t\t$sa .= '';\n\t\t}\n\t\tfor ($j=0;$j';\n\t\t\t$sa .= '';\n\t\t\t$answerboxsize[$sn] = $maxsize[$j];\n\t\t\t$displayformat[$sn] = 'alignright';\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$sn++;\n\t\t}\n\t\t$out .= '';\n\t\t$sa .= '';\n\t}\n\t$out .= '
    '.$rows[$j][$i].''.($ansarray[$j][$i][0]=='$'?'$':'');\n\t\t\t$ansarray[$j][$i] = str_replace(array('$',','),'',$ansarray[$j][$i]) * 1;\n\t\t\t$answer[$sn] = $ansarray[$j][$i];\n\t\t\tif ($hasdecimals) {\n\t\t\t\t$sa .= number_format($ansarray[$j][$i],2,'.',',');\n\t\t\t} else {\n\t\t\t\t$sa .= number_format($ansarray[$j][$i]);\n\t\t\t}\n\t\t\t$sa .= '
    ';\n\t$sa .= '';\n\t$showanswer .= $sa.'

     

    ';\n\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $plotDirection = null, $smoothLine = null, $plotStyle = null)\n {\n $this->plotType = $plotType;\n $this->plotGrouping = $plotGrouping;\n $this->plotOrder = $plotOrder;\n $keys = array_keys($plotValues);\n $this->plotValues = $plotValues;\n if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) {\n $plotLabel[$keys[0]] = new PHPExcel_Chart_DataSeriesValues();\n }\n\n $this->plotLabel = $plotLabel;\n if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) {\n $plotCategory[$keys[0]] = new PHPExcel_Chart_DataSeriesValues();\n }\n $this->plotCategory = $plotCategory;\n $this->smoothLine = $smoothLine;\n $this->plotStyle = $plotStyle;\n \n if (is_null($plotDirection)) {\n $plotDirection = self::DIRECTION_COL;\n }\n $this->plotDirection = $plotDirection;\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n FormFactoryInterface $formFactory,\n UserService $userService,\n InvitationService $invitationService,\n InvitationSender $sender,\n Environment $twig,\n TranslatableNotificationHandlerInterface $notificationHandler,\n SiteAccessServiceInterface $siteAccessService,\n UrlGeneratorInterface $urlGenerator\n ) {\n $this->formFactory = $formFactory;\n $this->invitationService = $invitationService;\n $this->sender = $sender;\n $this->twig = $twig;\n $this->userService = $userService;\n $this->notificationHandler = $notificationHandler;\n $this->siteAccessService = $siteAccessService;\n $this->urlGenerator = $urlGenerator;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n $type,\n $device_id,\n $oids,\n $subtype,\n $index,\n $description,\n $current = null,\n $multiplier = 1,\n $divisor = 1,\n $aggregator = 'sum',\n $high_limit = null,\n $low_limit = null,\n $high_warn = null,\n $low_warn = null,\n $entPhysicalIndex = null,\n $entPhysicalMeasured = null,\n $rrd_type = 'GAUGE'\n ) {\n $this->type = $type;\n $this->device_id = $device_id;\n $this->oids = (array) $oids;\n $this->subtype = $subtype;\n $this->index = $index;\n $this->description = $description;\n $this->current = $current;\n $this->multiplier = $multiplier;\n $this->divisor = $divisor;\n $this->aggregator = $aggregator;\n $this->entPhysicalIndex = $entPhysicalIndex;\n $this->entPhysicalMeasured = $entPhysicalMeasured;\n $this->high_limit = $high_limit;\n $this->low_limit = $low_limit;\n $this->high_warn = $high_warn;\n $this->low_warn = $low_warn;\n $this->rrd_type = $rrd_type;\n\n // ensure leading dots\n array_walk($this->oids, function (&$oid) {\n $oid = '.' . ltrim($oid, '.');\n });\n\n $sensor = $this->toArray();\n // validity not checked yet\n if (is_null($this->current)) {\n $sensor['sensor_oids'] = $this->oids;\n\n $prefetch = self::fetchSnmpData(device_by_id_cache($device_id), [$sensor]);\n $this->current = static::processSensorValue($prefetch, $this->aggregator, $this->divisor, $this->multiplier);\n $this->valid = is_numeric($this->current);\n }\n\n d_echo('Discovered ' . get_called_class() . ' ' . print_r($sensor, true));\n }", "smellKey": "S107", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function modifIntervenantAvecCode($num, $nom, $prenom, $actif, $date_naissance, $lieu_naissance,$tel, $adresse,$statut, $cp, $ville,$email,$commentaires,$diplome,$numsecu,$nationalite,$password,$photo,$iban,$bic,$compte,$banque,$serviceCivique)\n\t{\n\t\t$req = \"UPDATE `intervenants` SET `NOM`='$nom',`PRENOM`='$prenom',`ACTIF`=$actif,`STATUT`='$statut',`EMAIL`='$email',`TELEPHONE`='$tel',`ADRESSE_POSTALE`='$adresse',`CODE_POSTAL`='$cp',`VILLE`='$ville',`DIPLOME`='$diplome',`COMMENTAIRES`='$commentaires',`DATE_DE_NAISSANCE`='$date_naissance',`LIEU_DE_NAISSANCE`='$lieu_naissance',`NATIONALITE`='$nationalite',`SECURITE_SOCIALE`='$numsecu',`PHOTO`='$photo',`PASSWORD`='$password', IBAN='$iban', BIC='$bic', COMPTEBANCAIRE='$compte', BANQUE='$banque', SERVICECIVIQUE='$serviceCivique' WHERE `ID_INTERVENANT`=$num\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function buildNode(\n Location $location,\n array &$uninitializedContentInfoList,\n array &$containerLocations,\n ?LoadSubtreeRequestNode $loadSubtreeRequestNode = null,\n bool $loadChildren = false,\n int $depth = 0,\n ?string $sortClause = null,\n string $sortOrder = Query::SORT_ASC,\n array $bookmarkLocations = [],\n ?Criterion $requestFilter = null\n ): Node {\n $contentInfo = $location->getContentInfo();\n $contentId = $location->getContentId();\n if (!isset($uninitializedContentInfoList[$contentId])) {\n $uninitializedContentInfoList[$contentId] = $contentInfo;\n }\n\n // Top Level Location (id = 1) does not have a content type\n $contentType = $location->getDepth() > 0\n ? $contentInfo->getContentType()\n : null;\n\n if ($contentType !== null && $contentType->isContainer()) {\n $containerLocations[] = $location;\n }\n\n $content = $location->getContent();\n $versionInfo = $content->getVersionInfo();\n\n $limit = $this->resolveLoadLimit($loadSubtreeRequestNode);\n $offset = null !== $loadSubtreeRequestNode\n ? $loadSubtreeRequestNode->offset\n : 0;\n\n $totalChildrenCount = 0;\n $children = [];\n if ($loadChildren && $depth < $this->getSetting('tree_max_depth')) {\n $searchResult = $this->findSubitems($location, $limit, $offset, $sortClause, $sortOrder, $requestFilter);\n $totalChildrenCount = (int) $searchResult->totalCount;\n\n /** @var \\Ibexa\\Contracts\\Core\\Repository\\Values\\Content\\Location $childLocation */\n foreach (array_column($searchResult->searchHits, 'valueObject') as $childLocation) {\n $childLoadSubtreeRequestNode = null !== $loadSubtreeRequestNode\n ? $this->findChild($childLocation->getId(), $loadSubtreeRequestNode)\n : null;\n\n $children[] = $this->buildNode(\n $childLocation,\n $uninitializedContentInfoList,\n $containerLocations,\n $childLoadSubtreeRequestNode,\n null !== $childLoadSubtreeRequestNode,\n $depth + 1,\n null,\n Query::SORT_ASC,\n $bookmarkLocations,\n $requestFilter\n );\n }\n }\n\n $translations = $versionInfo->getLanguageCodes();\n $mainLanguageCode = $versionInfo->getContentInfo()->getMainLanguageCode();\n\n return new Node(\n $depth,\n $location->getId(),\n $location->getContentId(),\n $versionInfo->getVersionNo(),\n $translations,\n '', // node name will be provided later by `supplyTranslatedContentName` method\n null !== $contentType ? $contentType->getIdentifier() : '',\n null === $contentType || $contentType->isContainer(),\n $location->isInvisible() || $location->isHidden(),\n $limit,\n $totalChildrenCount,\n $this->getReverseRelationsCount($contentInfo),\n isset($bookmarkLocations[$location->getId()]),\n $mainLanguageCode,\n $children,\n $location->getPathString()\n );\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function unenrollstu($cid,$tounenroll,$delforum=false,$deloffline=false,$withwithdrawn=false,$delwikirev=false,$usereplaceby=false,$upgradeassess=false) {\n\tglobal $DBH, $userid;\n\t$cid = intval($cid);\n\n\t$forums = array();\n\t$threads = array();\n\t$stm2 = $DBH->prepare(\"SELECT threadid FROM imas_forum_posts WHERE forumid=:forumid\");\n\n\t$stm = $DBH->query(\"SELECT id FROM imas_forums WHERE courseid=$cid\"); //sanitized above\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$forums[] = $row[0];\n\t\t$stm2->execute(array(':forumid'=>$row[0]));\n\t\twhile ($rw2 = $stm2->fetch(PDO::FETCH_NUM)) {\n\t\t\t$threads[] = $rw2[0];\n\t\t}\n\t}\n\t$threadlist = implode(',',$threads);\n\t$forumlist = implode(',',$forums);\n\n\t$assesses = array();\n\t$groupassess = array();\n\t$stm = $DBH->query(\"SELECT id,isgroup FROM imas_assessments WHERE courseid=$cid\");\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$assesses[] = $row[0];\n\t\tif ($row[1]>0) {\n\t\t\t$groupassess[] = $row[0];\n\t\t}\n\t}\n\t$aidlist = implode(',',$assesses);\n\n\t$wikis = array();\n\t$grpwikis = array();\n\t$stm = $DBH->query(\"SELECT id,groupsetid FROM imas_wikis WHERE courseid=$cid\");\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$wikis[] = $row[0];\n\t\tif ($row[1]>0) {\n\t\t\t$grpwikis[] = $row[0];\n\t\t}\n\t}\n\t$wikilist = implode(',',$wikis);\n\t$grpwikilist = implode(',',$grpwikis);\n\n\t$drills = array();\n\t$stm = $DBH->query(\"SELECT id FROM imas_drillassess WHERE courseid=$cid\");\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$drills[] = $row[0];\n\t}\n\t$drilllist = implode(',',$drills);\n\n\t$exttools = array();\n\t$stm = $DBH->query(\"SELECT id FROM imas_linkedtext WHERE courseid=$cid AND points>0\");\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$exttools[] = $row[0];\n\t}\n\t$exttoolslist = implode(',',$exttools);\n\n\t$stugroups = array();\n\t$stm = $DBH->query(\"SELECT imas_stugroups.id FROM imas_stugroups JOIN imas_stugroupset ON imas_stugroups.groupsetid=imas_stugroupset.id WHERE imas_stugroupset.courseid=$cid\");\n\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t$stugroups[] = $row[0];\n\t}\n\t$curdir = rtrim(dirname(__FILE__), '/\\\\');\n\trequire_once \"$curdir/filehandler.php\";\n\tif ($withwithdrawn=='remove' || $usereplaceby) {\n\t\trequire_once \"$curdir/updateassess.php\";\n\t}\n\tif (!empty($tounenroll) && count($tounenroll)>0) {\n $stulist = implode(',', array_map('intval', $tounenroll));\n\n\t\t$gbitems = array();\n\t\t$stm = $DBH->query(\"SELECT id FROM imas_gbitems WHERE courseid=$cid\");\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\t$gbitems[] = $row[0];\n\t\t}\n\t\t$gblist = implode(',',$gbitems);\n\t\t//new\n\t\t$grades = array();\n\t\tif (count($assesses)>0) {\n\t\t\t$query = \"SELECT userid, assessmentid, bestscores FROM imas_assessment_sessions \"\n\t\t\t\t. \" WHERE assessmentid IN ($aidlist) AND userid IN ($stulist)\";\n\t\t\t$stm = $DBH->query($query);\n\t\t\twhile ($row = $stm->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t$sp = explode(';', $row['bestscores']);\n\t\t\t\t$as = str_replace(array('-1','-2','~'), array('0','0',','), $sp[0]);\n\t\t\t\t$total = array_sum(explode(',', $as));\n\t\t\t\t$grades[$row['userid']]['assessment'][$row[\"assessmentid\"]] = $total;\n\t\t\t}\n\t\t\t$query = \"SELECT userid, assessmentid, score FROM imas_assessment_records \"\n\t\t\t\t. \" WHERE assessmentid IN ($aidlist) AND userid IN ($stulist)\";\n\t\t\t$stm = $DBH->query($query);\n\t\t\twhile ($row = $stm->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t$grades[$row['userid']]['assessment'][$row[\"assessmentid\"]] =$row[\"score\"];\n\t\t\t}\n\t\t\tdeleteasidfilesbyquery2('userid',$tounenroll,$assesses);\n\t\t\tdeleteAssess2FilesOnUnenroll($tounenroll, $assesses, $groupassess);\n\t\t\t//deleteasidfilesbyquery(array('assessmentid'=>$assesses, 'userid'=>$tounenroll));\n\t\t\t$query = \"DELETE FROM imas_assessment_sessions WHERE assessmentid IN ($aidlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t\t$query = \"DELETE FROM imas_assessment_records WHERE assessmentid IN ($aidlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t\t$query = \"DELETE FROM imas_exceptions WHERE itemtype='A' AND assessmentid IN ($aidlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\t$where = array();\n\t\tif (count($exttools)>0) {\n\t\t\t$where[] = \"(gradetype = 'exttool' AND gradetypeid IN ($exttoolslist))\";\n\t\t}\n\t\tif (count($gbitems)>0) {\n\t\t\t$where[] = \"(gradetype = 'offline' AND gradetypeid IN ($gblist))\";\n\t\t}\n\t\tif (count($forums)>0) {\n\t\t\t$where[] = \"(gradetype = 'forum' AND gradetypeid IN ($forumlist))\";\n\t\t}\n\t\tif (!empty($where)) {\n\t\t\t$query = \"SELECT userid, gradetype, gradetypeid, score FROM imas_grades WHERE userid IN ($stulist) AND (\"\n\t\t\t. implode (\" OR \", $where) . \")\";\n\t\t\t$stm = $DBH->query($query);\n\t\t\twhile ($row = $stm->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t$grades[$row['userid']][$row[\"gradetype\"]][$row[\"gradetypeid\"]] = $row[\"score\"];\n\t\t\t}\n\t\t}\n\t\tif (count($drills)>0) {\n\t\t\t$query = \"DELETE FROM imas_drillassess_sessions WHERE drillassessid IN ($drilllist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\tif (count($exttools)>0) {\n\t\t\t$query = \"DELETE FROM imas_grades WHERE gradetype='exttool' AND gradetypeid IN ($exttoolslist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\tif (count($gbitems)>0) {\n\t\t\t$query = \"DELETE FROM imas_grades WHERE gradetype='offline' AND gradetypeid IN ($gblist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\tif (count($threads)>0) {\n\t\t\t$query = \"DELETE FROM imas_forum_views WHERE threadid IN ($threadlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\tif (count($wikis)>0) {\n\t\t\t$query = \"DELETE FROM imas_wiki_views WHERE wikiid IN ($wikilist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\t\tif (count($forums)>0) {\n\t\t\t$query = \"DELETE FROM imas_grades WHERE gradetype='forum' AND gradetypeid IN ($forumlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t\t$query = \"DELETE FROM imas_exceptions WHERE (itemtype='F' OR itemtype='P' OR itemtype='R') AND assessmentid IN ($forumlist) AND userid IN ($stulist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\n\t\tif (count($stugroups)>0) {\n\t\t\t$stugrouplist = implode(',',$stugroups);\n\t\t\t$query = \"DELETE FROM imas_stugroupmembers WHERE userid IN ($stulist) AND stugroupid IN ($stugrouplist)\";\n\t\t\t$DBH->query($query); //values already sanitized\n\t\t}\n\n\t\t// delete grade excusals\n\t\t$query = \"DELETE FROM imas_excused WHERE courseid=$cid AND userid IN ($stulist)\";\n\t\t$DBH->query($query); //values already sanitized\n\n\t}\n\tif ($delforum && count($forums)>0) {\n\t\t$query = \"DELETE imas_forum_threads FROM imas_forum_posts JOIN imas_forum_threads ON imas_forum_posts.threadid=imas_forum_threads.id AND imas_forum_posts.posttype=0 WHERE imas_forum_threads.forumid IN ($forumlist)\";\n\t\t$DBH->query($query); //values already sanitized\n\t\t$stm = $DBH->query(\"SELECT id FROM imas_forum_posts WHERE forumid IN ($forumlist) AND files<>''\");\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\tdeleteallpostfiles($row[0]);\n\t\t}\n\n\t\t$query = \"DELETE FROM imas_forum_posts WHERE forumid IN ($forumlist) AND posttype=0\";\n\t\t$DBH->query($query); //values already sanitized\n\n\t\t/* //old\n\t\tforeach ($forums as $fid) {\n\t\t\t$query = \"DELETE imas_forum_threads FROM imas_forum_posts JOIN imas_forum_threads ON imas_forum_posts.threadid=imas_forum_threads.id AND imas_forum_posts.posttype=0 WHERE imas_forum_threads.forumid='$fid'\";\n\t\t\tmysql_query($query) or die(\"Query failed : \" . mysql_error());\n\n\t\t\t$query = \"DELETE FROM imas_forum_posts WHERE forumid='$fid' AND posttype=0\";\n\t\t\tmysql_query($query) or die(\"Query failed : \" . mysql_error());\n\t\t}*/\n\t}\n\tif ($delwikirev===1 && count($wikis)>0) {\n\t\t$query = \"DELETE FROM imas_wiki_revisions WHERE wikiid IN ($wikilist)\";\n\t\t$DBH->query($query); //values already sanitized\n\t} else if ($delwikirev===2 && count($grpwikis)>0) {\n\t\t$query = \"DELETE FROM imas_wiki_revisions WHERE wikiid IN ($grpwikilist)\";\n\t\t$DBH->query($query); //values already sanitized\n\t}\n\tif ($deloffline) {\n\t\t$DBH->query(\"DELETE FROM imas_gbitems WHERE courseid=$cid\");\n\t}\n\tif ($withwithdrawn=='unwithdraw' && count($assesses)>0) {\n\t\t$query = \"UPDATE imas_questions SET withdrawn=0 WHERE assessmentid IN ($aidlist)\";\n\t\t$DBH->query($query); //values already sanitized\n\t\t/*foreach ($assesses as $aid) {\n\t\t\t$query = \"UPDATE imas_questions SET withdrawn=0 WHERE assessmentid='$aid'\";\n\t\t\tmysql_query($query) or die(\"Query failed : \" . mysql_error());\n\t\t}*/\n\t}\n\n\tif ($withwithdrawn=='remove' || $usereplaceby) {\n\t\t$msg = updateassess($cid, $withwithdrawn=='remove', $usereplaceby);\n\t}\n\n\tif ($upgradeassess) {\n\t\t$stm = $DBH->prepare(\"UPDATE imas_courses SET UIver=2 WHERE id=?\");\n\t\t$stm->execute(array($cid));\n\t\tif (count($assesses)>0) {\n\t\t\t$stm = $DBH->query(\"SELECT * FROM imas_assessments WHERE id IN ($aidlist)\");\n\t\t\t$stm2 = null;\n\t\t\t$stm3 = null;\n\t\t\twhile ($row = $stm->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\tif ($stm2 === null) {\n\t\t\t\t\t$sets = [];\n\t\t\t\t\tforeach ($row as $k=>$v) {\n\t\t\t\t\t\tif ($k !== 'id') {\n\t\t\t\t\t\t\t$sets[] = \"$k=:$k\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$stm2 = $DBH->prepare(\"UPDATE imas_assessments SET \".implode(',', $sets). \" WHERE id=:id\");\n\t\t\t\t}\n\t\t\t\t$row = migrateAssessSettings($row, 1, 2); // TODO: generalize\n\t\t\t\t$qarr = [];\n\t\t\t\tforeach ($row as $k=>$v) {\n\t\t\t\t\t$qarr[':'.$k] = $v;\n\t\t\t\t}\n\t\t\t\t$stm2->execute($qarr);\n\t\t\t\t// now the questions\n\t\t\t\t$qstm = $DBH->prepare(\"SELECT * FROM imas_questions WHERE assessmentid=?\");\n\t\t\t\t$qstm->execute(array($row['id']));\n\t\t\t\twhile ($qrow = $qstm->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t\tif ($stm3 === null) {\n\t\t\t\t\t\t$sets = [];\n\t\t\t\t\t\tforeach ($qrow as $k=>$v) {\n\t\t\t\t\t\t\tif ($k !== 'id') {\n\t\t\t\t\t\t\t\t$sets[] = \"$k=:$k\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$stm3 = $DBH->prepare(\"UPDATE imas_questions SET \".implode(',', $sets). \" WHERE id=:id\");\n\t\t\t\t\t}\n\t\t\t\t\t$qrow = migrateQuestionSettings($qrow, $row, 1, 2); // TODO: generalize\n\t\t\t\t\t$qarr = [];\n\t\t\t\t\tforeach ($qrow as $k=>$v) {\n\t\t\t\t\t\t$qarr[':'.$k] = $v;\n\t\t\t\t\t}\n\t\t\t\t\t$stm3->execute($qarr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (!empty($tounenroll) && count($tounenroll)>0) {\n\t\t$query = \"DELETE FROM imas_students WHERE userid IN ($stulist) AND courseid=$cid\";\n\t\t$DBH->query($query); //values already sanitized\n\n\t\t$query = \"DELETE FROM imas_login_log WHERE userid IN ($stulist) AND courseid=$cid\";\n\t\t$DBH->query($query); //values already sanitized\n\n\t\t$query = \"DELETE FROM imas_content_track WHERE userid IN ($stulist) AND courseid=$cid\";\n\t\t$DBH->query($query); //values already sanitized\n\n\t\t$result = TeacherAuditLog::addTracking(\n\t\t\t$cid,\n\t\t\t\"Unenroll\",\n\t\t\tnull,\n\t\t\tarray(\n\t\t\t\t\"unenrolled\"=>$stulist,\n\t\t\t\t\"grades\"=>$grades\n\t\t\t)\n\t\t);\n\t}\n\n\t/*\n\t$lognote = \"Unenroll in $cid run by $userid via script \".basename($_SERVER['PHP_SELF']);\n\t$lognote .= \". Unenrolled: $stulist\";\n\t$stm = $DBH->prepare(\"INSERT INTO imas_log (time,log) VALUES (?,?)\");\n\t$stm->execute(array(time(), $lognote));\n\t*/\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct(\n\t\t?string $outCertMatr01,\n\t\t?string $outCertMatr02,\n\t\t?string $outCertMatr03,\n\t\t?string $outCertMatr04,\n\t\t?string $outCertMatr05,\n\t\t?string $outCertMatr06,\n\t\t?string $outCertMatr07,\n\t\t?string $outCertMatr08,\n\t\t?string $outCertMatr09\n\t) {\n\t\t$this->outCertMatr01 = $outCertMatr01;\n\t\t$this->outCertMatr02 = $outCertMatr02;\n\t\t$this->outCertMatr03 = $outCertMatr03;\n\t\t$this->outCertMatr04 = $outCertMatr04;\n\t\t$this->outCertMatr05 = $outCertMatr05;\n\t\t$this->outCertMatr06 = $outCertMatr06;\n\t\t$this->outCertMatr07 = $outCertMatr07;\n\t\t$this->outCertMatr08 = $outCertMatr08;\n\t\t$this->outCertMatr09 = $outCertMatr09;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function insertPrescriptions($prescriptionData, $encounter, $providerId, $authUserId, $formOptionId, $routeOptionId, $unitsOptionId, $intervalOptionId)\n {\n return sqlInsert(\n 'INSERT INTO `prescriptions`\n\t\t\t\t(\n\t\t\t\t\t`datetime`,\n\t\t\t\t\t`erx_source`,\n\t\t\t\t\t`encounter`,\n\t\t\t\t\t`date_added`,\n\t\t\t\t\t`user`,\n\t\t\t\t\t`provider_id`,\n\t\t\t\t\t`form`,\n\t\t\t\t\t`unit`,\n\t\t\t\t\t`route`,\n\t\t\t\t\t`interval`,\n\t\t\t\t\t`drug`,\n\t\t\t\t\t`drug_id`,\n\t\t\t\t\t`drug_info_erx`,\n\t\t\t\t\t`dosage`,\n\t\t\t\t\t`size`,\n\t\t\t\t\t`refills`,\n\t\t\t\t\t`note`,\n\t\t\t\t\t`site`,\n\t\t\t\t\t`rxnorm_drugcode`,\n\t\t\t\t\t`prescriptionguid`,\n\t\t\t\t\t`patient_id`\n\t\t\t\t)\n\t\t\tVALUES\n\t\t\t\t(\n\t\t\t\t\tNOW(), \\'1\\', ?, ?, ?,\n\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?,\n\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?\n\t\t\t\t);',\n array(\n $encounter,\n substr($prescriptionData['PrescriptionDate'], 0, 10),\n $authUserId,\n $providerId,\n $formOptionId,\n $unitsOptionId,\n $routeOptionId,\n $intervalOptionId,\n $prescriptionData['DrugName'],\n $prescriptionData['DrugID'],\n $prescriptionData['DrugInfo'],\n $prescriptionData['DosageNumberDescription'],\n self::sanitizeNumber($prescriptionData['Strength']),\n $prescriptionData['Refills'],\n $prescriptionData['PrescriptionNotes'],\n $prescriptionData['SiteID'],\n $prescriptionData['rxcui'],\n $prescriptionData['PrescriptionGuid'],\n $prescriptionData['ExternalPatientID']\n )\n );\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function afficherRowDossierClientModeTransportModeLicenceStatusAuto($id_cli, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_march=NULL, $statut=NULL, $num_lic=NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$cleared=NULL){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$compteur = 0;\n\t\t\t$bg = '';\n\t\t\t$style = '';\n\n\t\t\t/*echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    num_lic = '.$num_lic;*/\n\t\t\t\t//echo '
    -------'.$sqlStatus;\n\n\t\t\t$sql1 = \"\";\n\t\t\t$sqlOrder = \"\";\n\t\t\t$sqlIdMarch = \"\";\n\t\t\t$sqlStatus = \"\";\n\t\t\t$sqlLicence = \"\";\n\t\t\t$sqlCleared = \"\";\n\t\t\t$statut = str_replace('_', '/', $statut);\n\n\t\t\tif (isset($commodity) && ($commodity != '')) {\n\t\t\t\t$sql1 = ' AND d.commodity = \"'.$commodity.'\"';\n\t\t\t}\n\t\t\tif ($id_mod_lic == '1') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2' && $id_cli == '857') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.ref_dos DESC';\n\t\t\t}\n\n\t\t\tif (isset($id_march) && ($id_march != '')) {\n\t\t\t\t$sqlIdMarch = ' AND d.id_march = '.$id_march;\n\t\t\t}\n\n\t\t\tif (isset($statut) && ($statut != '')) {\n\t\t\t\t$sqlStatus = ' AND REPLACE(d.statut,\"\\'\",\"\") = \"'.$statut.'\"';\n\t\t\t}\n\n\t\t\tif (isset($num_lic) && ($num_lic != '')) {\n\t\t\t\t$sqlLicence = ' AND d.num_lic = \"'.$num_lic.'\"';\n\t\t\t}\n\n\t\t\tif (isset($cleared) && ($cleared != '')) {\n\t\t\t\t$sqlCleared = ' AND d.cleared = \"'.$cleared.'\"';\n\t\t\t}\n\n if ($_GET['id_mod_lic'] == '1') {\n \n\t\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t\t$sqlClient = ' AND cl.id_cli = \"'.$id_cli.'\"';\n\t\t\t\t}else{\n\t\t\t\t\t$sqlClient = '';\n\t\t\t\t}\n\n }else if ($_GET['id_mod_lic'] == '2') {\n \n\t\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t\t$sqlClient = ' AND cl.id_cli = \"'.$id_cli.'\"';\n\t\t\t\t}else{\n\t\t\t\t\t$sqlClient = '';\n\t\t\t\t}\n\n }\n\n if ($id_mod_lic=='2' && $id_mod_trans=='1') {\n \t\n\n\t\t\t\tif ($statut == 'AWAITING CRF/AD/INSURANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_ad IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING CRF/AD') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_ad IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING CRF/INSURANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING CRF') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING AD/INSURANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.date_ad IS NULL\n\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING AD') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_ad IS NULL AND d.date_crf IS NOT NULL AND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}/*else if ($statut == 'AWAITING INSURANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NULL\n\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}*/else if ($statut == 'AWAITING INSURANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_assurance IS NULL AND d.date_ad IS NOT NULL AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'UNDER PREPARATION') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_decl IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_decl IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'UNDER PREPARATION-EXCPECTED TO ARRIVE') {\n\n\t\t\t\t\t\t// $requete = $connexion-> prepare(\"SELECT COUNT(ref_dos) AS nbre\n\t\t\t\t\t\t// \t\t\t\t\t\t\tFROM dossier\n\t\t\t\t\t\t// \t\t\t\t\t\t\tWHERE id_mod_lic = ?\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_crf IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_ad IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_assurance IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_decl IS NULL \n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_decl IS NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND cleared <> '2'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlModeTransport\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlCommodity\");\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_decl IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_decl IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.klsa_arriv IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t\t}else if ($statut == 'UNDER PREPARATION-DISPATCHED') {\n\n\t\t\t\t\t\t// $requete = $connexion-> prepare(\"SELECT COUNT(ref_dos) AS nbre\n\t\t\t\t\t\t// \t\t\t\t\t\t\tFROM dossier\n\t\t\t\t\t\t// \t\t\t\t\t\t\tWHERE id_mod_lic = ?\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_crf IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_ad IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_assurance IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND dispatch_klsa IS NOT NULL \n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND wiski_arriv IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_decl IS NULL \n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_decl IS NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND cleared <> '2'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlModeTransport\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlCommodity\");\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_decl IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_decl IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.dispatch_klsa IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.wiski_arriv IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t\t}else if ($statut == 'UNDER PREPARATION-AT WISKY') {\n\n\t\t\t\t\t\t// $requete = $connexion-> prepare(\"SELECT COUNT(ref_dos) AS nbre\n\t\t\t\t\t\t// \t\t\t\t\t\t\tFROM dossier\n\t\t\t\t\t\t// \t\t\t\t\t\t\tWHERE id_mod_lic = ?\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_crf IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_ad IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_assurance IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND dispatch_klsa IS NULL \n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND wiski_arriv IS NOT NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND date_decl IS NULL \n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_decl IS NULL\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\tAND cleared <> '2'\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlModeTransport\n\t\t\t\t\t\t// \t\t\t\t\t\t\t\t$sqlCommodity\");\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_crf IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_ad IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_assurance IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.dispatch_klsa IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.wiski_arriv IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_decl IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_decl IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t\t}else if ($statut == 'AWAITING LIQUIDATION') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_decl IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_decl IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_liq IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_liq IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING QUITTANCE') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_liq IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_liq IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.date_quit IS NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_quit IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos NOT LIKE '%20-%'\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'AWAITING BAE/BS') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.date_quit IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_quit IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND dgda_out IS NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}else if ($statut == 'CLEARING COMPLETED') {\n\n\t\t\t\t\t$sqlStatus = \" AND d.dgda_out IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.dispatch_deliv IS NOT NULL\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.cleared <> '2'\";\n\n\t\t\t\t}\n\n }else{\n \t$sqlStatus = \" AND d.statut = '$statut'\";\n }\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.ref_dos AS ref_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPPER(cl.nom_cli) AS nom_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.ref_fact AS ref_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fob AS fob_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fret AS fret,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.assurance AS assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.autre_frais AS autre_frais,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.num_lic AS num_lic,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.montant_decl AS montant_decl,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.*,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.supplier AS fournisseur,\n\t\t\t\t\t\t\t\t\t\t\t\t\ts.nom_site AS nom_site,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_in AS dgda_in_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_out AS dgda_out_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.custom_deliv AS custom_deliv_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.arrival_date AS arrival_date_1,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_lic='2' AND d.id_mod_trans='1',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING INSURANCE',\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_decl IS NULL AND d.ref_decl IS NULL, 'UNDER PREPARATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_liq IS NULL AND d.ref_liq IS NULL, 'AWAITING LIQUIDATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NULL AND d.ref_quit IS NULL, 'AWAITING QUITTANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NOT NULL AND d.ref_quit IS NOT NULL AND d.dgda_out IS NULL, 'AWAITING BAE/BS', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.dgda_out IS NOT NULL AND d.dispatch_deliv IS NOT NULL, 'CLEARING COMPLETED', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\td.statut) AS statut,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.dgda_out, d.dgda_in) AS dgda_delay,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.custom_deliv, d.arrival_date) AS arrival_deliver_delay\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlIdMarch\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlLicence\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlCleared\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sql1\n\t\t\t\t\t\t\t\t\t\t\t\t$sqlOrder\");\n\t\t\t$requete-> execute(array($entree['id_mod_trans'], $entree['id_mod_lic']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t$compteur++;\n\t\t\t\t$bg = \"\";\n\t\t\t\t$color='';\n\t\t\t\t$class = \"\";\n\n\t\t\t\tif ($reponse['cleared'] == '1') {\n\t\t\t\t\t$style = \"style='color: blue;'\";\n\t\t\t\t\t$color = \"color: blue;\";\n\t\t\t\t\t$class = \"bg-primary\";\n\t\t\t\t}else if ($reponse['cleared'] == '2') {\n\t\t\t\t\t$style = \"style='color: red;'\";\n\t\t\t\t\t$color = \"color: red;\";\n\t\t\t\t\t$class = \"bg-danger\";\n\t\t\t\t}else{\n\t\t\t\t\t$style = \"\";\n\t\t\t\t\t$color = \"color: black;\";\n\t\t\t\t\t$class = \"bg-dark\";\n\t\t\t\t}\n\n\t\t\t\t$date_exp = $this-> getLastEpirationLicence($reponse['num_lic']);\n\t\t\t\t$supplier = $this-> getLicence($reponse['num_lic'])['fournisseur'];\n\n\t\t\t\tif (isset($supplier)) {\n\t\t\t\t\t$reponse['fournisseur'] = $supplier;\n\t\t\t\t}\n\n\t\t\t\t//include('modalDeleteDossier.php');\n\t\t\t\t\n\n\t\t\t?>\n\t\t\t\t\" value=\"\">\n\t\t\t\t\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black;\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black; \">\n\t\t\t\t\t\n\t\t\t\t\t afficherRowTableau2($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur);\n\t\t\t\t\t$this-> afficherRowTableau3($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur, $reponse['statut']);\n\t\t\t\t\t\t/*if ($id_mod_trans == '1') {\n\t\t\t\t\t\t\tinclude('importRouteRow.php');\n\t\t\t\t\t\t}else if ($id_mod_trans == '3') {\n\t\t\t\t\t\t\tinclude('importAirRow.php');\n\t\t\t\t\t\t}*/\n\t\t\t\t\t?>\n\t\t\t\t\n\t\t\t closeCursor();\n\t\t\t?>\n\t\t\tgetAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $sessionId = ($sessionId === 'current')\n ? Auth::sessionVerify($user->getAttribute('sessions'), Auth::$secret, $authDuration)\n : $sessionId;\n\n $sessions = $user->getAttribute('sessions', []);\n\n foreach ($sessions as $key => $session) {/** @var Document $session */\n if ($sessionId == $session->getId()) {\n // Comment below would skip re-generation if token is still valid\n // We decided to not include this because developer can get expiration date from the session\n // I kept code in comment because it might become relevant in the future\n\n // $expireAt = (int) $session->getAttribute('providerAccessTokenExpiry');\n // if(\\time() < $expireAt - 5) { // 5 seconds time-sync and networking gap, to be safe\n // return $response->noContent();\n // }\n\n $provider = $session->getAttribute('provider');\n $refreshToken = $session->getAttribute('providerRefreshToken');\n\n $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? '';\n $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}';\n\n $className = 'Appwrite\\\\Auth\\\\OAuth2\\\\' . \\ucfirst($provider);\n\n if (!\\class_exists($className)) {\n throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);\n }\n\n $oauth2 = new $className($appId, $appSecret, '', [], []);\n\n $oauth2->refreshTokens($refreshToken);\n\n $session\n ->setAttribute('providerAccessToken', $oauth2->getAccessToken(''))\n ->setAttribute('providerRefreshToken', $oauth2->getRefreshToken(''))\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$oauth2->getAccessTokenExpiry('')));\n\n $dbForProject->updateDocument('sessions', $sessionId, $session);\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n\n $session->setAttribute('expire', DateTime::formatTz(DateTime::addSeconds(new \\DateTime($session->getCreatedAt()), $authDuration)));\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId())\n ->setPayload($response->output($session, Response::MODEL_SESSION))\n ;\n\n return $response->dynamic($session, Response::MODEL_SESSION);\n }\n }\n\n throw new Exception(Exception::USER_SESSION_NOT_FOUND);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $domain, string $resourceType, string $resourceId, Response $response, Document $project, Event $events, Database $dbForConsole, Database $dbForProject) {\n $mainDomain = App::getEnv('_APP_DOMAIN', '');\n if ($domain === $mainDomain) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'You cannot assign your main domain to specific resource. Please use subdomain or a different domain.');\n }\n if ($domain === 'localhost' || $domain === APP_HOSTNAME_INTERNAL) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'This domain name is not allowed. Please pick another one.');\n }\n\n $document = $dbForConsole->findOne('rules', [\n Query::equal('domain', [$domain]),\n ]);\n\n if ($document && !$document->isEmpty()) {\n if ($document->getAttribute('projectId') === $project->getId()) {\n $resourceType = $document->getAttribute('resourceType');\n $resourceId = $document->getAttribute('resourceId');\n $message = \"Domain already assigned to '{$resourceType}' service\";\n if (!empty($resourceId)) {\n $message .= \" with ID '{$resourceId}'\";\n }\n\n $message .= '.';\n } else {\n $message = 'Domain already assigned to different project.';\n }\n\n throw new Exception(Exception::RULE_ALREADY_EXISTS, $message);\n }\n\n $resourceInternalId = '';\n\n if ($resourceType == 'function') {\n if (empty($resourceId)) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $function = $dbForProject->getDocument('functions', $resourceId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::RULE_RESOURCE_NOT_FOUND);\n }\n\n $resourceInternalId = $function->getInternalId();\n }\n\n $domain = new Domain($domain);\n\n $ruleId = ID::unique();\n $rule = new Document([\n '$id' => $ruleId,\n 'projectId' => $project->getId(),\n 'projectInternalId' => $project->getInternalId(),\n 'domain' => $domain->get(),\n 'resourceType' => $resourceType,\n 'resourceId' => $resourceId,\n 'resourceInternalId' => $resourceInternalId,\n 'certificateId' => '',\n ]);\n\n $status = 'created';\n $functionsDomain = App::getEnv('_APP_DOMAIN_FUNCTIONS');\n if (!empty($functionsDomain) && \\str_ends_with($domain->get(), $functionsDomain)) {\n $status = 'verified';\n }\n\n if ($status === 'created') {\n $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));\n $validator = new CNAME($target->get()); // Verify Domain with DNS records\n\n if ($validator->isValid($domain->get())) {\n $status = 'verifying';\n\n $event = new Certificate();\n $event\n ->setDomain(new Document([\n 'domain' => $rule->getAttribute('domain')\n ]))\n ->trigger();\n }\n }\n\n $rule->setAttribute('status', $status);\n $rule = $dbForConsole->createDocument('rules', $rule);\n\n $events->setParam('ruleId', $rule->getId());\n\n $rule->setAttribute('logs', '');\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($rule, Response::MODEL_PROXY_RULE);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function resolve_plans_sql($type = '', $patient_id = '0', $configurableOnly = false)\n{\n\n if ($configurableOnly) {\n // Collect all default, configurable (per patient) plans into an array\n // (ie. ignore the cqm rules)\n $sql = sqlStatementCdrEngine(\"SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`\");\n } else {\n // Collect all default plans into an array\n $sql = sqlStatementCdrEngine(\"SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`\");\n }\n\n $returnArray = array();\n for ($iter = 0; $row = sqlFetchArray($sql); $iter++) {\n $returnArray[] = $row;\n }\n\n // Now collect the pertinent plans\n $newReturnArray = array();\n\n // Need to select rules (use custom if exist)\n foreach ($returnArray as $plan) {\n $customPlan = sqlQueryCdrEngine(\"SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?\", array($plan['id'],$patient_id));\n\n // Decide if use default vs custom plan (preference given to custom plan)\n if (!empty($customPlan)) {\n if ($type == \"cqm\") {\n // For CQM , do not use custom plans (these are to create standard clinic wide reports)\n $goPlan = $plan;\n } else {\n // merge the custom plan with the default plan\n $mergedPlan = array();\n foreach ($customPlan as $key => $value) {\n if ($value == null && preg_match(\"/_flag$/\", $key)) {\n // use default setting\n $mergedPlan[$key] = $plan[$key];\n } else {\n // use custom setting\n $mergedPlan[$key] = $value;\n }\n }\n\n $goPlan = $mergedPlan;\n }\n } else {\n $goPlan = $plan;\n }\n\n // Use the chosen plan if set\n if (!empty($type)) {\n if ($goPlan[\"{$type}_flag\"] == 1) {\n // active, so use the plan\n $newReturnArray[] = $goPlan;\n }\n } else {\n if (\n $goPlan['normal_flag'] == 1 ||\n $goPlan['cqm_flag'] == 1\n ) {\n // active, so use the plan\n $newReturnArray[] = $goPlan;\n }\n }\n }\n\n $returnArray = $newReturnArray;\n\n return $returnArray;\n}", "smellKey": "S107", "smellId": null, "repo": "hendrik-buchwald-sonarsource_openemr", "language": "php"} {"function": "public function __construct($orientation = 'P', $unit = 'mm', $format = 'A4', $unicode = true, $encoding = 'UTF-8', $diskCache = false, $pdfTemplatePath = null, $enableFooter = true)\n {\n parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskCache);\n $this->pdfTemplatePath = $pdfTemplatePath ?? null;\n $this->enableFooter = $enableFooter;\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function getPortalAudit($patientid, $action = 'review', $activity = 'profile', $status = 'waiting', $auditflg = 1, $rtn = 'last', $oelog = true, $error = true)\n {\n $return = false;\n $result = false;\n $audit = array (\n $patientid,\n $activity,\n $auditflg,\n $status,\n $action\n );\n try {\n $sql = \"Select * From onsite_portal_activity As pa Where pa.patient_id = ? And pa.activity = ? And pa.require_audit = ? \" .\n \"And pa.status = ? And pa.pending_action = ? ORDER BY pa.date ASC LIMIT 1\";\n $return = sqlStatementNoLog($sql, $audit);\n $result = true;\n } catch (Exception $e) {\n if ($error) {\n $this->errorHandler($e, $sql, $audit);\n }\n }\n\n if ($oelog) {\n EventAuditLogger::instance()->auditSQLEvent($sql, $result, $audit);\n }\n\n if ($rtn == 'last') {\n return sqlFetchArray($return);\n } else {\n return $return;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {\n\n\t/**\n\t * Filters the caption text.\n\t *\n\t * Note: If the caption text is empty, the caption shortcode will not be appended\n\t * to the image HTML when inserted into the editor.\n\t *\n\t * Passing an empty value also prevents the {@see 'image_add_caption_shortcode'}\n\t * Filters from being evaluated at the end of image_add_caption().\n\t *\n\t * @since 4.1.0\n\t *\n\t * @param string $caption The original caption text.\n\t * @param int $id The attachment ID.\n\t */\n\t$caption = apply_filters( 'image_add_caption_text', $caption, $id );\n\n\t/**\n\t * Filters whether to disable captions.\n\t *\n\t * Prevents image captions from being appended to image HTML when inserted into the editor.\n\t *\n\t * @since 2.6.0\n\t *\n\t * @param bool $bool Whether to disable appending captions. Returning true from the filter\n\t * will disable captions. Default empty string.\n\t */\n\tif ( empty( $caption ) || apply_filters( 'disable_captions', '' ) ) {\n\t\treturn $html;\n\t}\n\n\t$id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';\n\n\tif ( ! preg_match( '/width=[\"\\']([0-9]+)/', $html, $matches ) ) {\n\t\treturn $html;\n\t}\n\n\t$width = $matches[1];\n\n\t$caption = str_replace( array( \"\\r\\n\", \"\\r\" ), \"\\n\", $caption );\n\t$caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption );\n\n\t// Convert any remaining line breaks to
    .\n\t$caption = preg_replace( '/[ \\n\\t]*\\n[ \\t]*/', '
    ', $caption );\n\n\t$html = preg_replace( '/(class=[\"\\'][^\\'\"]*)align(none|left|right|center)\\s?/', '$1', $html );\n\tif ( empty( $align ) ) {\n\t\t$align = 'none';\n\t}\n\n\t$shcode = '[caption id=\"' . $id . '\" align=\"align' . $align . '\" width=\"' . $width . '\"]' . $html . ' ' . $caption . '[/caption]';\n\n\t/**\n\t * Filters the image HTML markup including the caption shortcode.\n\t *\n\t * @since 2.6.0\n\t *\n\t * @param string $shcode The image HTML markup with caption shortcode.\n\t * @param string $html The image HTML markup.\n\t */\n\treturn apply_filters( 'image_add_caption_shortcode', $shcode, $html );\n}", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "public function __construct(\n Session $session,\n Router $router,\n ContentActionsMenu $contentActionsMenu,\n SubItemsList $subItemList,\n ContentTypePicker $contentTypePicker,\n LanguagePicker $languagePicker,\n Dialog $dialog,\n TranslationDialog $translationDialog,\n Repository $repository,\n Breadcrumb $breadcrumb,\n ContentItemAdminPreview $contentItemAdminPreview,\n ArgumentParser $argumentParser,\n UniversalDiscoveryWidget $universalDiscoveryWidget,\n IbexaDropdown $ibexaDropdown,\n UpperMenu $upperMenu,\n DeleteContentDialog $deleteContentDialog\n ) {\n parent::__construct($session, $router);\n $this->contentActionsMenu = $contentActionsMenu;\n $this->subItemList = $subItemList;\n $this->contentTypePicker = $contentTypePicker;\n $this->languagePicker = $languagePicker;\n $this->dialog = $dialog;\n $this->translationDialog = $translationDialog;\n $this->breadcrumb = $breadcrumb;\n $this->contentItemAdminPreview = $contentItemAdminPreview;\n $this->repository = $repository;\n $this->argumentParser = $argumentParser;\n $this->universalDiscoveryWidget = $universalDiscoveryWidget;\n $this->ibexaDropdown = $ibexaDropdown;\n $this->upperMenu = $upperMenu;\n $this->deleteContentDialog = $deleteContentDialog;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "private function writeValueAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines)\n {\n $objWriter->startElement('c:valAx');\n\n if ($id2 > 0) {\n $objWriter->startElement('c:axId');\n $objWriter->writeAttribute('val', $id2);\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:scaling');\n\n if (!is_null($xAxis->getAxisOptionsProperty('maximum'))) {\n $objWriter->startElement('c:max');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('maximum'));\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getAxisOptionsProperty('minimum'))) {\n $objWriter->startElement('c:min');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minimum'));\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:orientation');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('orientation'));\n\n\n $objWriter->endElement();\n $objWriter->endElement();\n\n $objWriter->startElement('c:delete');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n\n $objWriter->startElement('c:axPos');\n $objWriter->writeAttribute('val', \"l\");\n $objWriter->endElement();\n\n $objWriter->startElement('c:majorGridlines');\n $objWriter->startElement('c:spPr');\n\n if (!is_null($majorGridlines->getLineColorProperty('value'))) {\n $objWriter->startElement('a:ln');\n $objWriter->writeAttribute('w', $majorGridlines->getLineStyleProperty('width'));\n $objWriter->startElement('a:solidFill');\n $objWriter->startElement(\"a:{$majorGridlines->getLineColorProperty('type')}\");\n $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('alpha'));\n $objWriter->endElement(); //end alpha\n $objWriter->endElement(); //end srgbClr\n $objWriter->endElement(); //end solidFill\n\n $objWriter->startElement('a:prstDash');\n $objWriter->writeAttribute('val', $majorGridlines->getLineStyleProperty('dash'));\n $objWriter->endElement();\n\n if ($majorGridlines->getLineStyleProperty('join') == 'miter') {\n $objWriter->startElement('a:miter');\n $objWriter->writeAttribute('lim', '800000');\n $objWriter->endElement();\n } else {\n $objWriter->startElement('a:bevel');\n $objWriter->endElement();\n }\n\n if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) {\n $objWriter->startElement('a:headEnd');\n $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')));\n $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('head', 'w'));\n $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('head', 'len'));\n $objWriter->endElement();\n }\n\n if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) {\n $objWriter->startElement('a:tailEnd');\n $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')));\n $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('end', 'w'));\n $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('end', 'len'));\n $objWriter->endElement();\n }\n $objWriter->endElement(); //end ln\n }\n $objWriter->startElement('a:effectLst');\n\n if (!is_null($majorGridlines->getGlowSize())) {\n $objWriter->startElement('a:glow');\n $objWriter->writeAttribute('rad', $majorGridlines->getGlowSize());\n $objWriter->startElement(\"a:{$majorGridlines->getGlowColor('type')}\");\n $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('alpha'));\n $objWriter->endElement(); //end alpha\n $objWriter->endElement(); //end schemeClr\n $objWriter->endElement(); //end glow\n }\n\n if (!is_null($majorGridlines->getShadowProperty('presets'))) {\n $objWriter->startElement(\"a:{$majorGridlines->getShadowProperty('effect')}\");\n if (!is_null($majorGridlines->getShadowProperty('blur'))) {\n $objWriter->writeAttribute('blurRad', $majorGridlines->getShadowProperty('blur'));\n }\n if (!is_null($majorGridlines->getShadowProperty('distance'))) {\n $objWriter->writeAttribute('dist', $majorGridlines->getShadowProperty('distance'));\n }\n if (!is_null($majorGridlines->getShadowProperty('direction'))) {\n $objWriter->writeAttribute('dir', $majorGridlines->getShadowProperty('direction'));\n }\n if (!is_null($majorGridlines->getShadowProperty('algn'))) {\n $objWriter->writeAttribute('algn', $majorGridlines->getShadowProperty('algn'));\n }\n if (!is_null($majorGridlines->getShadowProperty(array('size', 'sx')))) {\n $objWriter->writeAttribute('sx', $majorGridlines->getShadowProperty(array('size', 'sx')));\n }\n if (!is_null($majorGridlines->getShadowProperty(array('size', 'sy')))) {\n $objWriter->writeAttribute('sy', $majorGridlines->getShadowProperty(array('size', 'sy')));\n }\n if (!is_null($majorGridlines->getShadowProperty(array('size', 'kx')))) {\n $objWriter->writeAttribute('kx', $majorGridlines->getShadowProperty(array('size', 'kx')));\n }\n if (!is_null($majorGridlines->getShadowProperty('rotWithShape'))) {\n $objWriter->writeAttribute('rotWithShape', $majorGridlines->getShadowProperty('rotWithShape'));\n }\n $objWriter->startElement(\"a:{$majorGridlines->getShadowProperty(array('color', 'type'))}\");\n $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'value')));\n\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'alpha')));\n $objWriter->endElement(); //end alpha\n\n $objWriter->endElement(); //end color:type\n $objWriter->endElement(); //end shadow\n }\n\n if (!is_null($majorGridlines->getSoftEdgesSize())) {\n $objWriter->startElement('a:softEdge');\n $objWriter->writeAttribute('rad', $majorGridlines->getSoftEdgesSize());\n $objWriter->endElement(); //end softEdge\n }\n\n $objWriter->endElement(); //end effectLst\n $objWriter->endElement(); //end spPr\n $objWriter->endElement(); //end majorGridLines\n\n if ($minorGridlines->getObjectState()) {\n $objWriter->startElement('c:minorGridlines');\n $objWriter->startElement('c:spPr');\n\n if (!is_null($minorGridlines->getLineColorProperty('value'))) {\n $objWriter->startElement('a:ln');\n $objWriter->writeAttribute('w', $minorGridlines->getLineStyleProperty('width'));\n $objWriter->startElement('a:solidFill');\n $objWriter->startElement(\"a:{$minorGridlines->getLineColorProperty('type')}\");\n $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('alpha'));\n $objWriter->endElement(); //end alpha\n $objWriter->endElement(); //end srgbClr\n $objWriter->endElement(); //end solidFill\n\n $objWriter->startElement('a:prstDash');\n $objWriter->writeAttribute('val', $minorGridlines->getLineStyleProperty('dash'));\n $objWriter->endElement();\n\n if ($minorGridlines->getLineStyleProperty('join') == 'miter') {\n $objWriter->startElement('a:miter');\n $objWriter->writeAttribute('lim', '800000');\n $objWriter->endElement();\n } else {\n $objWriter->startElement('a:bevel');\n $objWriter->endElement();\n }\n\n if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) {\n $objWriter->startElement('a:headEnd');\n $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')));\n $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('head', 'w'));\n $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('head', 'len'));\n $objWriter->endElement();\n }\n\n if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) {\n $objWriter->startElement('a:tailEnd');\n $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')));\n $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('end', 'w'));\n $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('end', 'len'));\n $objWriter->endElement();\n }\n $objWriter->endElement(); //end ln\n }\n\n $objWriter->startElement('a:effectLst');\n\n if (!is_null($minorGridlines->getGlowSize())) {\n $objWriter->startElement('a:glow');\n $objWriter->writeAttribute('rad', $minorGridlines->getGlowSize());\n $objWriter->startElement(\"a:{$minorGridlines->getGlowColor('type')}\");\n $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('alpha'));\n $objWriter->endElement(); //end alpha\n $objWriter->endElement(); //end schemeClr\n $objWriter->endElement(); //end glow\n }\n\n if (!is_null($minorGridlines->getShadowProperty('presets'))) {\n $objWriter->startElement(\"a:{$minorGridlines->getShadowProperty('effect')}\");\n if (!is_null($minorGridlines->getShadowProperty('blur'))) {\n $objWriter->writeAttribute('blurRad', $minorGridlines->getShadowProperty('blur'));\n }\n if (!is_null($minorGridlines->getShadowProperty('distance'))) {\n $objWriter->writeAttribute('dist', $minorGridlines->getShadowProperty('distance'));\n }\n if (!is_null($minorGridlines->getShadowProperty('direction'))) {\n $objWriter->writeAttribute('dir', $minorGridlines->getShadowProperty('direction'));\n }\n if (!is_null($minorGridlines->getShadowProperty('algn'))) {\n $objWriter->writeAttribute('algn', $minorGridlines->getShadowProperty('algn'));\n }\n if (!is_null($minorGridlines->getShadowProperty(array('size', 'sx')))) {\n $objWriter->writeAttribute('sx', $minorGridlines->getShadowProperty(array('size', 'sx')));\n }\n if (!is_null($minorGridlines->getShadowProperty(array('size', 'sy')))) {\n $objWriter->writeAttribute('sy', $minorGridlines->getShadowProperty(array('size', 'sy')));\n }\n if (!is_null($minorGridlines->getShadowProperty(array('size', 'kx')))) {\n $objWriter->writeAttribute('kx', $minorGridlines->getShadowProperty(array('size', 'kx')));\n }\n if (!is_null($minorGridlines->getShadowProperty('rotWithShape'))) {\n $objWriter->writeAttribute('rotWithShape', $minorGridlines->getShadowProperty('rotWithShape'));\n }\n $objWriter->startElement(\"a:{$minorGridlines->getShadowProperty(array('color', 'type'))}\");\n $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'value')));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'alpha')));\n $objWriter->endElement(); //end alpha\n $objWriter->endElement(); //end color:type\n $objWriter->endElement(); //end shadow\n }\n\n if (!is_null($minorGridlines->getSoftEdgesSize())) {\n $objWriter->startElement('a:softEdge');\n $objWriter->writeAttribute('rad', $minorGridlines->getSoftEdgesSize());\n $objWriter->endElement(); //end softEdge\n }\n\n $objWriter->endElement(); //end effectLst\n $objWriter->endElement(); //end spPr\n $objWriter->endElement(); //end minorGridLines\n }\n\n if (!is_null($yAxisLabel)) {\n $objWriter->startElement('c:title');\n $objWriter->startElement('c:tx');\n $objWriter->startElement('c:rich');\n\n $objWriter->startElement('a:bodyPr');\n $objWriter->endElement();\n\n $objWriter->startElement('a:lstStyle');\n $objWriter->endElement();\n\n $objWriter->startElement('a:p');\n $objWriter->startElement('a:r');\n\n $caption = $yAxisLabel->getCaption();\n if (is_array($caption)) {\n $caption = $caption[0];\n }\n\n $objWriter->startElement('a:t');\n // $objWriter->writeAttribute('xml:space', 'preserve');\n $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption));\n $objWriter->endElement();\n\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n\n if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {\n $layout = $yAxisLabel->getLayout();\n $this->writeLayout($layout, $objWriter);\n }\n\n $objWriter->startElement('c:overlay');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:numFmt');\n $objWriter->writeAttribute('formatCode', $xAxis->getAxisNumberFormat());\n $objWriter->writeAttribute('sourceLinked', $xAxis->getAxisNumberSourceLinked());\n $objWriter->endElement();\n\n $objWriter->startElement('c:majorTickMark');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_tick_mark'));\n $objWriter->endElement();\n\n $objWriter->startElement('c:minorTickMark');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_tick_mark'));\n $objWriter->endElement();\n\n $objWriter->startElement('c:tickLblPos');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('axis_labels'));\n $objWriter->endElement();\n\n $objWriter->startElement('c:spPr');\n\n if (!is_null($xAxis->getFillProperty('value'))) {\n $objWriter->startElement('a:solidFill');\n $objWriter->startElement(\"a:\" . $xAxis->getFillProperty('type'));\n $objWriter->writeAttribute('val', $xAxis->getFillProperty('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $xAxis->getFillProperty('alpha'));\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n }\n\n $objWriter->startElement('a:ln');\n\n $objWriter->writeAttribute('w', $xAxis->getLineStyleProperty('width'));\n $objWriter->writeAttribute('cap', $xAxis->getLineStyleProperty('cap'));\n $objWriter->writeAttribute('cmpd', $xAxis->getLineStyleProperty('compound'));\n\n if (!is_null($xAxis->getLineProperty('value'))) {\n $objWriter->startElement('a:solidFill');\n $objWriter->startElement(\"a:\" . $xAxis->getLineProperty('type'));\n $objWriter->writeAttribute('val', $xAxis->getLineProperty('value'));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $xAxis->getLineProperty('alpha'));\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n }\n\n $objWriter->startElement('a:prstDash');\n $objWriter->writeAttribute('val', $xAxis->getLineStyleProperty('dash'));\n $objWriter->endElement();\n\n if ($xAxis->getLineStyleProperty('join') == 'miter') {\n $objWriter->startElement('a:miter');\n $objWriter->writeAttribute('lim', '800000');\n $objWriter->endElement();\n } else {\n $objWriter->startElement('a:bevel');\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'head', 'type')))) {\n $objWriter->startElement('a:headEnd');\n $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'head', 'type')));\n $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('head'));\n $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('head'));\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'end', 'type')))) {\n $objWriter->startElement('a:tailEnd');\n $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'end', 'type')));\n $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('end'));\n $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('end'));\n $objWriter->endElement();\n }\n\n $objWriter->endElement();\n\n $objWriter->startElement('a:effectLst');\n\n if (!is_null($xAxis->getGlowProperty('size'))) {\n $objWriter->startElement('a:glow');\n $objWriter->writeAttribute('rad', $xAxis->getGlowProperty('size'));\n $objWriter->startElement(\"a:{$xAxis->getGlowProperty(array('color','type'))}\");\n $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','value')));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','alpha')));\n $objWriter->endElement();\n $objWriter->endElement();\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getShadowProperty('presets'))) {\n $objWriter->startElement(\"a:{$xAxis->getShadowProperty('effect')}\");\n\n if (!is_null($xAxis->getShadowProperty('blur'))) {\n $objWriter->writeAttribute('blurRad', $xAxis->getShadowProperty('blur'));\n }\n if (!is_null($xAxis->getShadowProperty('distance'))) {\n $objWriter->writeAttribute('dist', $xAxis->getShadowProperty('distance'));\n }\n if (!is_null($xAxis->getShadowProperty('direction'))) {\n $objWriter->writeAttribute('dir', $xAxis->getShadowProperty('direction'));\n }\n if (!is_null($xAxis->getShadowProperty('algn'))) {\n $objWriter->writeAttribute('algn', $xAxis->getShadowProperty('algn'));\n }\n if (!is_null($xAxis->getShadowProperty(array('size','sx')))) {\n $objWriter->writeAttribute('sx', $xAxis->getShadowProperty(array('size','sx')));\n }\n if (!is_null($xAxis->getShadowProperty(array('size','sy')))) {\n $objWriter->writeAttribute('sy', $xAxis->getShadowProperty(array('size','sy')));\n }\n if (!is_null($xAxis->getShadowProperty(array('size','kx')))) {\n $objWriter->writeAttribute('kx', $xAxis->getShadowProperty(array('size','kx')));\n }\n if (!is_null($xAxis->getShadowProperty('rotWithShape'))) {\n $objWriter->writeAttribute('rotWithShape', $xAxis->getShadowProperty('rotWithShape'));\n }\n\n $objWriter->startElement(\"a:{$xAxis->getShadowProperty(array('color','type'))}\");\n $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','value')));\n $objWriter->startElement('a:alpha');\n $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','alpha')));\n $objWriter->endElement();\n $objWriter->endElement();\n\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getSoftEdgesSize())) {\n $objWriter->startElement('a:softEdge');\n $objWriter->writeAttribute('rad', $xAxis->getSoftEdgesSize());\n $objWriter->endElement();\n }\n\n $objWriter->endElement(); //effectList\n $objWriter->endElement(); //end spPr\n\n if ($id1 > 0) {\n $objWriter->startElement('c:crossAx');\n $objWriter->writeAttribute('val', $id2);\n $objWriter->endElement();\n\n if (!is_null($xAxis->getAxisOptionsProperty('horizontal_crosses_value'))) {\n $objWriter->startElement('c:crossesAt');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses_value'));\n $objWriter->endElement();\n } else {\n $objWriter->startElement('c:crosses');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses'));\n $objWriter->endElement();\n }\n\n $objWriter->startElement('c:crossBetween');\n $objWriter->writeAttribute('val', \"midCat\");\n $objWriter->endElement();\n\n if (!is_null($xAxis->getAxisOptionsProperty('major_unit'))) {\n $objWriter->startElement('c:majorUnit');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_unit'));\n $objWriter->endElement();\n }\n\n if (!is_null($xAxis->getAxisOptionsProperty('minor_unit'))) {\n $objWriter->startElement('c:minorUnit');\n $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_unit'));\n $objWriter->endElement();\n }\n }\n\n if ($isMultiLevelSeries) {\n if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) {\n $objWriter->startElement('c:noMultiLvlLbl');\n $objWriter->writeAttribute('val', 0);\n $objWriter->endElement();\n }\n }\n\n $objWriter->endElement();\n }", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n $object_type,\n $life_duration,\n $set_life_duration,\n $source_set_ids,\n $repository_identifier,\n $deleted_record_statut,\n $include_items,\n $xslt = \"\",\n $include_links = 0,\n $deletion_management = 0,\n $deletion_management_transient_duration = 0)\n {\n parent::__construct($object_type, $life_duration);\n $this->set_life_duration = (int) $set_life_duration;\n $this->source_set_ids = $source_set_ids;\n $this->repository_identifier = $repository_identifier;\n $this->deleted_record_statut = $deleted_record_statut;\n $this->include_items = $include_items;\n $this->xslt = $xslt;\n $this->include_links = $include_links;\n $this->deletion_management = $deletion_management;\n $this->deletion_management_transient_duration = $deletion_management_transient_duration;\n }", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function modifIntervenantPublicAvecCode($num, $nom, $prenom, $date_naissance, $lieu_naissance,$tel, $adresse, $cp, $ville,$email,$diplome,$numsecu,$nationalite,$password)\n\t{\n\t\t$req = \"UPDATE `intervenants` SET `NOM`=:nom,`PRENOM`=:prenom,`EMAIL`=:email,`TELEPHONE`=:tel,`ADRESSE_POSTALE`=:adresse,`CODE_POSTAL`=:cp,`VILLE`=:ville,`DIPLOME`=:diplome,`DATE_DE_NAISSANCE`=:date_naissance,`LIEU_DE_NAISSANCE`=:lieu_naissance,`NATIONALITE`=:nationalite,`SECURITE_SOCIALE`=:numsecu,`PASSWORD`=:password WHERE `ID_INTERVENANT`=:num\";\n\t\t\n\t\t$params = array(\n\t\t\t':num' => $num,\n\t\t\t':nom' => $nom,\n\t\t\t':prenom' => $prenom,\n\t\t\t':date_naissance' => $date_naissance,\n\t\t\t':lieu_naissance' => $lieu_naissance,\n\t\t\t':tel' => $tel,\n\t\t\t':adresse' => $adresse,\n\t\t\t':cp' => $cp,\n\t\t\t':ville' => $ville,\n\t\t\t':email' => $email,\n\t\t\t':diplome' => $diplome,\n\t\t\t':numsecu' => $numsecu,\n\t\t\t':nationalite' => $nationalite,\n\t\t\t':password' => $password\n\t\t);\n\t\t$rs = $this->NonQuery($req,$params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function thisLineItem(\n $product_id,\n $warehouse_id,\n $patient_id,\n $encounter_id,\n $rowprod,\n $rowwh,\n $transdate,\n $qtys,\n $irnumber = ''\n) {\n\n global $warehouse, $product, $secqtys, $priqtys, $grandqtys;\n global $whleft, $prodleft; // left 2 columns, blank where repeated\n global $last_warehouse_id, $last_product_id, $product_first;\n global $form_action;\n\n $invnumber = empty($irnumber) ? ($patient_id ? \"$patient_id.$encounter_id\" : \"\") : $irnumber;\n\n // Product name for this detail line item.\n if (empty($rowprod)) {\n $rowprod = 'Unnamed Product';\n }\n\n // Warehouse name for this line item.\n if (empty($rowwh)) {\n $rowwh = 'None';\n }\n\n // If new warehouse or product...\n if ($warehouse_id != $last_warehouse_id || $product_id != $last_product_id) {\n // If there was anything to total...\n if (($product_first && $last_warehouse_id != '~') || (!$product_first && $last_product_id)) {\n $secei = getEndInventory($last_product_id, $last_warehouse_id);\n\n // Print second-column totals.\n if ($form_action == 'export') {\n // Export:\n if (! $_POST['form_details']) {\n if ($product_first) {\n echo csvEscape($product);\n echo ',' . csvEscape($warehouse);\n } else {\n echo csvEscape($warehouse);\n echo ',' . csvEscape($product);\n }\n\n echo ',' . csvEscape($secei - $secqtys[0] - $secqtys[1] - $secqtys[2] - $secqtys[3] - $secqtys[4]); // start inventory\n echo ',' . csvEscape($secqtys[0]); // sales\n echo ',' . csvEscape($secqtys[1]); // distributions\n echo ',' . csvEscape($secqtys[2]); // purchases\n echo ',' . csvEscape($secqtys[3]); // transfers\n echo ',' . csvEscape($secqtys[4]); // adjustments\n echo ',' . csvEscape($secei); // end inventory\n echo \"\\n\";\n }\n } else {\n // Not export:\n ?>\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n  \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n  \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n  \n \n \n $dbForConsole->getDocument('users', $userId));\n\n if ($user->isEmpty() && empty($mock)) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n if (!$mock) {\n $name = $user->getAttribute('name', 'Anonymous');\n $email = $user->getAttribute('email', '');\n $createdAt = new \\DateTime($user->getCreatedAt());\n\n $gitHub = $getUserGitHub($user->getId(), $project, $dbForProject, $dbForConsole, $logger);\n $githubName = $gitHub['name'] ?? '';\n $githubId = $gitHub['id'] ?? '';\n\n $isHero = \\array_key_exists($email, $heroes);\n $isContributor = \\in_array($githubId, $contributors);\n $isEmployee = \\array_key_exists($email, $employees);\n $employeeNumber = $isEmployee ? $employees[$email]['spot'] : '';\n\n if ($isHero) {\n $createdAt = new \\DateTime($heroes[$email]['memberSince'] ?? '');\n } elseif ($isEmployee) {\n $createdAt = new \\DateTime($employees[$email]['memberSince'] ?? '');\n }\n\n if (!$isEmployee && !empty($githubName)) {\n $employeeGitHub = \\array_search(\\strtolower($githubName), \\array_map(fn ($employee) => \\strtolower($employee['gitHub']) ?? '', $employees));\n if (!empty($employeeGitHub)) {\n $isEmployee = true;\n $employeeNumber = $isEmployee ? $employees[$employeeGitHub]['spot'] : '';\n $createdAt = new \\DateTime($employees[$employeeGitHub]['memberSince'] ?? '');\n }\n }\n\n $isPlatinum = $user->getInternalId() % 100 === 0;\n } else {\n $name = $mock === 'normal-long' ? 'Sir First Walter O\\'Brian Junior' : 'Walter O\\'Brian';\n $createdAt = new \\DateTime('now');\n $githubName = $mock === 'normal-no-github' ? '' : ($mock === 'normal-long' ? 'sir-first-walterobrian-junior' : 'walterobrian');\n $isHero = $mock === 'hero';\n $isContributor = $mock === 'contributor';\n $isEmployee = \\str_starts_with($mock, 'employee');\n $employeeNumber = match ($mock) {\n 'employee' => '1',\n 'employee-2digit' => '18',\n default => ''\n };\n\n $isPlatinum = $mock === 'platinum';\n }\n\n if ($isEmployee) {\n $isContributor = false;\n $isHero = false;\n }\n\n if ($isHero) {\n $isContributor = false;\n $isEmployee = false;\n }\n\n if ($isContributor) {\n $isHero = false;\n $isEmployee = false;\n }\n\n $isGolden = $isEmployee || $isHero || $isContributor;\n $isPlatinum = $isGolden ? false : $isPlatinum;\n $memberSince = \\strtoupper('Member since ' . $createdAt->format('M') . ' ' . $createdAt->format('d') . ', ' . $createdAt->format('o'));\n\n $imagePath = $isGolden ? 'front-golden.png' : ($isPlatinum ? 'front-platinum.png' : 'front.png');\n\n $baseImage = new \\Imagick(__DIR__ . '/../../../public/images/cards/cloud/' . $imagePath);\n\n if ($isEmployee) {\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/employee.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 793, 35);\n\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_CENTER);\n $text->setFont(__DIR__ . '/../../../public/fonts/Inter-Bold.ttf');\n $text->setFillColor(new \\ImagickPixel('#FFFADF'));\n $text->setFontSize(\\strlen($employeeNumber) <= 2 ? 54 : 48);\n $text->setFontWeight(700);\n $metricsText = $baseImage->queryFontMetrics($text, $employeeNumber);\n\n $hashtag = new \\ImagickDraw();\n $hashtag->setTextAlignment(Imagick::ALIGN_CENTER);\n $hashtag->setFont(__DIR__ . '/../../../public/fonts/Inter-Bold.ttf');\n $hashtag->setFillColor(new \\ImagickPixel('#FFFADF'));\n $hashtag->setFontSize(28);\n $hashtag->setFontWeight(700);\n $metricsHashtag = $baseImage->queryFontMetrics($hashtag, '#');\n\n $startX = 898;\n $totalWidth = $metricsHashtag['textWidth'] + 12 + $metricsText['textWidth'];\n\n $hashtagX = ($metricsHashtag['textWidth'] / 2);\n $textX = $hashtagX + 12 + ($metricsText['textWidth'] / 2);\n\n $hashtagX -= $totalWidth / 2;\n $textX -= $totalWidth / 2;\n\n $hashtagX += $startX;\n $textX += $startX;\n\n $baseImage->annotateImage($hashtag, $hashtagX, 150, 0, '#');\n $baseImage->annotateImage($text, $textX, 150, 0, $employeeNumber);\n }\n\n if ($isContributor) {\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/contributor.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 793, 34);\n }\n\n if ($isHero) {\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/hero.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 793, 34);\n }\n\n setlocale(LC_ALL, \"en_US.utf8\");\n // $name = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $name);\n // $memberSince = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $memberSince);\n // $githubName = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $githubName);\n\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_CENTER);\n $text->setFont(__DIR__ . '/../../../public/fonts/Poppins-Bold.ttf');\n $text->setFillColor(new \\ImagickPixel('#FFFFFF'));\n\n if (\\strlen($name) > 32) {\n $name = \\substr($name, 0, 32);\n }\n\n if (\\strlen($name) <= 23) {\n $text->setFontSize(80);\n $scalingDown = false;\n } else {\n $text->setFontSize(54);\n $scalingDown = true;\n }\n $text->setFontWeight(700);\n $baseImage->annotateImage($text, 512, 477, 0, $name);\n\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_CENTER);\n $text->setFont(__DIR__ . '/../../../public/fonts/Inter-SemiBold.ttf');\n $text->setFillColor(new \\ImagickPixel($isGolden || $isPlatinum ? '#FFFFFF' : '#FFB9CC'));\n $text->setFontSize(27);\n $text->setFontWeight(600);\n $text->setTextKerning(1.08);\n $baseImage->annotateImage($text, 512, 541, 0, \\strtoupper($memberSince));\n\n if (!empty($githubName)) {\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_CENTER);\n $text->setFont(__DIR__ . '/../../../public/fonts/Inter-Regular.ttf');\n $text->setFillColor(new \\ImagickPixel('#FFFFFF'));\n $text->setFontSize($scalingDown ? 28 : 32);\n $text->setFontWeight(400);\n $metrics = $baseImage->queryFontMetrics($text, $githubName);\n\n $baseImage->annotateImage($text, 512 + 20 + 4, 373 + ($scalingDown ? 2 : 0), 0, $githubName);\n\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/github.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $precisionFix = 5;\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 512 - ($metrics['textWidth'] / 2) - 20 - 4, 373 - ($metrics['textHeight'] - $precisionFix));\n }\n\n if (!empty($width) || !empty($height)) {\n $baseImage->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);\n }\n\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache\n ->setContentType('image/png')\n ->file($baseImage->getImageBlob());\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function aff_notice($id, $nocart=0, $gen_header=1, $use_cache=0, $mode_aff_notice=\"\", $depliable=\"\", $nodocnum=0, $enrichment=1, $recherche_ajax_mode=0, $show_map=1, $template_directory = \"\") {\n\n\tglobal $liens_opac;\n\tglobal $opac_notices_format;\n\tglobal $opac_notices_depliable;\n\tglobal $opac_cart_allow;\n\tglobal $opac_cart_only_for_subscriber;\n\tglobal $opac_notice_affichage_class;\n\tglobal $opac_notice_enrichment;\n\tglobal $opac_recherche_ajax_mode;\n\tglobal $opac_notices_format_onglets;\n\tglobal $lvl,$search_type_asked;\n\tglobal $record_css_already_included; // Pour pas inclure la css 10 fois\n\t\n\t$retour_aff = '';\n\tif ((($opac_cart_allow)&&(!$opac_cart_only_for_subscriber))||(($opac_cart_allow)&&($_SESSION[\"user_code\"]))) {\n\t\t$cart=1; \n\t} else {\n\t\t$cart=0;\n\t}\n\tif ($nocart) $cart=0;\n\t$id = intval($id);\n\t//Recherche des fonctions d'affichage\n\t$entete='';\n\t$recordmodes = record_display_modes::get_instance();\n\tif($recordmodes && $id==-1){\n\t\t$entete.=$recordmodes->show_mode_selector();\n\t}\n\t\n\t$f=get_aff_function();\n\tif ($f) return $entete.$f($id,$cart,$gen_header,$use_cache,$mode_aff_notice,$depliable,$nodocnum,$enrichment,$recherche_ajax_mode,$show_map,$recordmodes);\n\t\n\tif ($id>0) {\n\t\tif ($mode_aff_notice !== \"\") $type_aff=$mode_aff_notice;\n\t\telse $type_aff=$opac_notices_format;\n\t\t\n\t\tif ($depliable === \"\") $depliable=$opac_notices_depliable;\n\n\t\tif ($type_aff != AFF_ETA_NOTICES_TEMPLATE_DJANGO) {\n\t\t\t$header_only=0;\n\t\t\tif($recherche_ajax_mode && $opac_recherche_ajax_mode){\n\t\t\t\t//Si ajax, on ne charge pas tout\n\t\t\t\t$header_only=1;\n\t\t\t}\n\t\t\t$class_affichage_to_call = $opac_notice_affichage_class;\n\t\t\tif (!$class_affichage_to_call) $class_affichage_to_call=\"notice_affichage\";\n\t\t\t$current = new $class_affichage_to_call($id,$liens_opac,$cart,0,$header_only,!$gen_header, $show_map);\n\t\t\tif($nodocnum) $current->docnum_allowed = 0;\n\t\t\t\n\t\t\tif ($gen_header) $current->do_header();\n\t\t\n\t\t\tif(!$current->visu_notice){\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\t\tif($opac_recherche_ajax_mode && $recherche_ajax_mode && $depliable && $type_aff!=AFF_ETA_NOTICES_REDUIT && $type_aff!=AFF_ETA_NOTICES_TEMPLATE_DJANGO){\n\t\t\t$current->genere_ajax($type_aff,0) ;\n\t\t\t$retour_aff .= $current->result ;\n\t\t}else{\n\t\t\t$flag_no_onglet_perso = 0;\n\t\t\tswitch ($type_aff) {\n\t\t\t\tcase AFF_ETA_NOTICES_REDUIT :\n\t\t\t\t\t$retour_aff .= $current->notice_header_with_link.\"
    \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_ISBD :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->genere_simple($depliable, 'ISBD') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_PUBLIC :\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_simple($depliable, 'PUBLIC') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_BOTH :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_double($depliable, 'PUBLIC') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase AFF_ETA_NOTICES_BOTH_ISBD_FIRST :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_double($depliable, 'ISBD') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase AFF_ETA_NOTICES_TEMPLATE_DJANGO :\n\t\t\t\t\tglobal $include_path;\n\t\t\t\t\tglobal $opac_notices_format_django_directory;\n\t\t\t\t\t\n\t\t\t\t\tif (!$opac_notices_format_django_directory) $opac_notices_format_django_directory = \"common\";\n\t\t\t\t\t\n\t\t\t\t\tif (!$record_css_already_included) {\n\t\t\t\t\t\tif (file_exists($include_path.\"/templates/record/\".$opac_notices_format_django_directory.\"/styles/style.css\")) {\n\t\t\t\t\t\t\t$retour_aff .= \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$record_css_already_included = true;\n\t\t\t\t\t}\n\t\t\t\t\t// Si on l'appelle par le tag {% etagere_see %}, on veut tout le temps le rduit...\n\t\t\t\t\t$trace = debug_backtrace();\n\t\t\t\t\t$count_trace = count($trace);\n\t\t\t\t\t$from_etagesee_tag = false;\n\t\t\t\t\t$from_recordsee_tag = false;\n\t\t\t\t\tfor ($i = 2; $i < $count_trace; $i++) {\n\t\t\t\t\t if (isset($trace[$i]['object']) && get_class($trace[$i]['object']) === \"Etageresee_Tag\") {\n\t\t\t\t\t $from_etagesee_tag=true;\n\t\t\t\t\t }\n\t\t\t\t\t if (isset($trace[$i]['object']) && get_class($trace[$i]['object']) === \"Recordsee_Tag\") {\n\t\t\t\t\t $from_recordsee_tag=true;\n\t\t\t\t\t }\n\t\t\t\t\t}\n\t\t\t\t\tif($from_etagesee_tag === true){\n\t\t\t\t\t $retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t}elseif($from_recordsee_tag === true){\n\t\t\t\t\t $retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t}else{\n \t\t\t\t\tswitch ($lvl) {\n \t\t\t\t\t\tcase 'notice_display' :\n \t\t\t\t\t\t $from_serial_analysis = false;\n \t\t\t\t\t\t if(!empty($_GET['id']) && $_GET['id'] != $id) {\n \t\t\t\t\t\t if(notice::get_niveau_biblio($_GET['id']) == 's' && notice::get_niveau_biblio($id) == 'a') {\n \t\t\t\t\t\t $from_serial_analysis = true;\n \t\t\t\t\t\t }\n \t\t\t\t\t\t }\n \t\t\t\t\t\t if($from_serial_analysis) {\n \t\t\t\t\t\t $retour_aff .= record_display::get_display_in_result($id, $template_directory);\n \t\t\t\t\t\t } else {\n \t\t\t\t\t\t $retour_aff .= record_display::get_display_extended($id, $template_directory);\n \t\t\t\t\t\t }\n \t\t\t\t\t\t \n \t\t\t\t\t\t break;\n \t\t\t\t\t\tcase 'bulletin_display' :\n \t\t\t\t\t\tcase 'resa' :\n \t\t\t\t\t\t\t$retour_aff .= record_display::get_display_extended($id, $template_directory);\n \t\t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase 'more_result' :\n \t\t\t\t\t\tdefault :\n \t\t\t\t\t\t\tif($search_type_asked=='perio_a2z'){\n \t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_extended($id, $template_directory);\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_in_result($id, $template_directory);\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\tbreak;\n \t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\t\t\t\t\t\n\t\t\t\t\t$current->genere_double($depliable, 'autre') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\t$flag_no_onglet_perso=1;\n\t\t\t\t\tbreak ;\n\t\t\t\t\t\n\t\t\t}\n\t\t\n\t/*\t\t\t\n\t\t\t$onglets_title=\"\";\n\t\t\t$onglets_content=\"\";\n\t\t\tif($opac_notices_format_onglets){\n\t\t\t\t$onglets=explode(\",\", $opac_notices_format_onglets);\n\t\t\t\tforeach($onglets as $id_tpl){\n\t\t\t\t\t$notice_onglet=new notice_onglet($id_tpl);\n\t\t\t\t\t$onglets_title.=\"\n\t\t\t\t\t
  • \n\t\t\t\t\t\tget_onglet_header().\"\\\" onclick=\\\"show_what('tpl_\".$id_tpl.\"_', '$id'); return false;\\\">\".$notice_onglet->get_onglet_header().\"\n\t\t\t\t\t
  • \";\n\t\t\n\t\t\t\t\t$onglets_content.=\"\n\t\t\t\t\t\";\n\t\t\t\t}\n\t\t\t}\t\n\t\t\t$retour_aff=str_replace('', $onglets_title, $retour_aff);\n\t\t\t$retour_aff=str_replace('', $onglets_content, $retour_aff);\n\t\t\t\t\n\t*/\t\t\t\n\t\t\tif(!$flag_no_onglet_perso){\n\t\t\t\t$onglet_perso=new notice_onglets();\n\t\t\t\t$retour_aff=$onglet_perso->insert_onglets($id,$retour_aff);\n\t\t\t}\n\t\t\tif(!$depliable && $opac_notice_enrichment && $enrichment==1){\n\t\t\t\t$retour_aff.=\"\";\n\t\t\t}\n\t\t}\n\t}\t\n\treturn $entete.$retour_aff;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_7.5.8", "language": "php"} {"function": "public function __construct(\n\t\t?string $outDataAlteracaoFicha,\n\t\t?string $outOperador,\n\t\t?OutDadosPessoais $outDadosPessoais,\n\t\t?array $outIrmaos,\n\t\t?OutDocumentos $outDocumentos,\n\t\t?string $outCodJustificativa,\n\t\t?string $outJustificativaDocumento,\n\t\t?OutCertidaoNova $outCertidaoNova,\n\t\t?OutCertidaoAntiga $outCertidaoAntiga,\n\t\t?OutEnderecoResidencial $outEnderecoResidencial,\n\t\t?OutEnderecoIndicativo $outEnderecoIndicativo,\n\t\t?array $outTelefones,\n\t\t?OutDeficiencia $outDeficiencia,\n\t\t?array $outListaNecessidadesEspeciais,\n\t\t?OutRecursoAvaliacao $outRecursoAvaliacao,\n\t\t?string $outSucesso,\n\t\t?string $outErro,\n\t\t?string $outProcessoID\n\t) {\n\t\t$this->outDataAlteracaoFicha = $outDataAlteracaoFicha;\n\t\t$this->outOperador = $outOperador;\n\t\t$this->outDadosPessoais = $outDadosPessoais;\n\t\t$this->outIrmaos = $outIrmaos;\n\t\t$this->outDocumentos = $outDocumentos;\n\t\t$this->outCodJustificativa = $outCodJustificativa;\n\t\t$this->outJustificativaDocumento = $outJustificativaDocumento;\n\t\t$this->outCertidaoNova = $outCertidaoNova;\n\t\t$this->outCertidaoAntiga = $outCertidaoAntiga;\n\t\t$this->outEnderecoResidencial = $outEnderecoResidencial;\n\t\t$this->outEnderecoIndicativo = $outEnderecoIndicativo;\n\t\t$this->outTelefones = $outTelefones;\n\t\t$this->outDeficiencia = $outDeficiencia;\n\t\t$this->outListaNecessidadesEspeciais = $outListaNecessidadesEspeciais;\n\t\t$this->outRecursoAvaliacao = $outRecursoAvaliacao;\n\t\t$this->outSucesso = $outSucesso;\n\t\t$this->outErro = $outErro;\n\t\t$this->outProcessoID = $outProcessoID;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(string $adaptor, string $hostname, string $username, string $password, string $database, string $port = '', string $ssl_key = '', string $ssl_cert = '', string $ssl_ca = '') {\n\t\t$class = 'Opencart\\System\\Library\\DB\\\\' . $adaptor;\n\n\t\tif (class_exists($class)) {\n\t\t\t$this->adaptor = new $class($hostname, $username, $password, $database, $port, $ssl_key, $ssl_cert, $ssl_ca);\n\t\t} else {\n\t\t\tthrow new \\Exception('Error: Could not load database adaptor ' . $adaptor . '!');\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "achibear_opencart", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, Response $response, Database $dbForProject, Event $events) {\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_DATETIME,\n default: $default,\n required: $required\n );\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_DATETIME);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private static function doInsertUpdateRecord($recordId, $import_table, $recordType, $csv_mvsep,\n $details, $id_field, $old_id_in_idfield, $mode_output,\n $ignore_errors, $record_count){\n\n //check permission beforehand\n if($recordId>0){\n\n $ownerid = null;\n $access = null;\n $rectypes = array();\n if(!recordCanChangeOwnerwhipAndAccess(self::$system, $recordId, $ownerid, $access, $rectypes)){\n // error message: $res;\n self::$rep_permission++;\n return null;\n }\n }elseif($recordId==null || $recordId==''){\n $recordId = 0; //add new record\n }\n\n $record = array();\n $record['ID'] = $recordId;\n $record['RecTypeID'] = $recordType;\n $record['AddedByImport'] = 1;\n $record['no_validation'] = $ignore_errors?'ignore_all':true; //if true - don't check resouces and enums\n if(@$details['URL']) {$record['URL'] = @$details['URL'];}\n if(@$details['ScratchPad']) {$record['ScratchPad'] = @$details['ScratchPad'];}\n $record['details'] = $details;\n\n $updating_record = $recordId != 0 && // Check that a record is actually being updated, for the final count\n (array_key_exists('URL', $record) && !empty($record['URL'])\n || array_key_exists('ScratchPad', $record) && !empty($record['ScratchPad'])\n || is_array($details) && !empty($details));\n\n $ignore_dtys = array();\n\n foreach(array_keys($record['details']) as $dty){\n if(preg_match(\"/^t:\\\\d+$/\", $dty) !== 1){\n continue;\n }\n\n $dty = substr($dty, 2);\n if($dty > 0){\n array_push($ignore_dtys, $dty);\n }\n }\n\n if($recordId == 0){ // New records only\n\n $cached_increments = array_key_exists($recordType, self::$increment_fields) ? self::$increment_fields[$recordType] : array();\n\n foreach($cached_increments as $dty => $value){\n\n if(in_array($dty, $ignore_dtys)){\n continue;\n }\n\n $matches = array();\n if (preg_match('/(\\d+)$/', $value, $matches)){\n $digits = $matches[1];\n $increment_digit = str_pad(intval($digits) + 1, strlen($digits), '0', STR_PAD_LEFT);\n\n $value = substr($value,0,-strlen($digits)).($increment_digit);\n }else{ // shouldn't happen here, but just in case\n $value = $value.'1';\n }\n\n $cached_increments[$dty] = $value; // update cache\n $record['details'][$dty] = $value;\n\n array_push($ignore_dtys, $dty);\n }\n\n // Get missing auto increment values\n $auto_increment_params = array(\n 'rtyID' => $recordType,\n 'ignore_dtys' => $ignore_dtys\n );\n\n $auto_increment = recordGetAllIncremenetedValues(self::$system, $auto_increment_params);\n\n if(count($auto_increment) > 0){\n $record['details'] = array_replace($details, $auto_increment);\n\n $cached_increments = array_replace($cached_increments, $auto_increment);\n }\n if(count($cached_increments) > 0){\n self::$increment_fields[$recordType] = $cached_increments;\n }\n }\n\n $increment_update = true;\n if($updating_record){\n $increment_update = self::_isRecordUpdating($recordId, $record);\n }\n\n $out = recordSave(self::$system, $record, false, false, 0, $record_count);//see recordModify.php\n\n $new_recordID = null;\n\n if ( @$out['status'] != HEURIST_OK ) {\n\n if ($mode_output!='json'){\n //array(\"status\"=>$status, \"message\"=>$message, \"sysmsg\"=>$sysmsg)\n\n //@todo special formatting\n //foreach($out[\"error\"] as $idx=>$value){\n $value = htmlspecialchars($out[\"message\"]);\n $value = str_replace(\". You may need to make fields optional. Missing data\",\"\",$value);\n $k = strpos($value, \"Missing data for Required field(s) in\");\n if($k!==false){\n $value = \"\".substr($value,0,$k+37).\"\".substr($value,$k+37);\n }else{\n $value = \"\".$value.\"\";\n }\n //$out[\"error\"][$idx] = $value;\n //for}\n\n foreach($details['imp_id'] as $imp_id){\n print \"
    Line: \".intval($imp_id).\". \".implode(\";\",$value);\n $res = self::getImportValue($imp_id, $import_table);\n if(is_array($res)){\n $s = htmlspecialchars(implode(\", \", $res));\n print \"
    \".$s.DIV_E;\n }\n print DIV_E;\n }\n }else{\n if(self::$rep_skipped<100){\n $line_id = @$details['imp_id'][0];\n\n self::$rep_skipped_details[] = ($recordId>0?('record#'.$recordId):'new record')\n .($line_id>0?('(line#'.$line_id.')'):'')\n .': '.$out[\"message\"];\n }\n }\n\n self::$rep_skipped++;\n }\n else{\n\n $new_recordID = intval($out['data']);\n\n if($recordId != $new_recordID){ //}==null){\n self::$rep_added++;\n self::$rep_unique_ids[] = $new_recordID;\n }else{\n //do not count updates if this record was already inserted before\n if($updating_record && !in_array($new_recordID, self::$rep_unique_ids)){\n self::$rep_unique_ids[] = $new_recordID;\n !$increment_update || self::$rep_updated++;\n }elseif(is_numeric($new_recordID) && $new_recordID > 0){\n self::$rep_added++;\n self::$rep_unique_ids[] = $new_recordID;\n }\n }\n\n //change record id in import table from negative temp to id form Huerist records (for insert)\n if($id_field){ // ($recordId==null || $recordId>0)){\n\n $imp_ids = prepareIds($details['imp_id']);//for snyk\n $imp_ids = implode(\",\", $imp_ids);\n\n if($old_id_in_idfield==null){\n\n if($new_recordID>0){\n\n $updquery = \"UPDATE `$import_table` SET `$id_field`=$new_recordID WHERE imp_id in ($imp_ids)\";\n\n if(!self::$mysqli->query($updquery) && $mode_output!='json'){\n print \"
    Cannot update import table (set record id \".$new_recordID.\") for lines: $imp_ids
    \";\n }\n }\n\n }else{\n\n $oldvals = mysql__select_all( self::$mysqli,\n \"SELECT `imp_id`, `$id_field` FROM `$import_table` WHERE `imp_id` in ($imp_ids)\");\n if(is_array($oldvals))\n {\n foreach($oldvals as $idx=>$row){\n $ids = explode($csv_mvsep, $row[1]);\n $new_ids = array();\n foreach($ids as $i=>$id){\n if($id==$old_id_in_idfield){\n $new_ids[] = intval($new_recordID);\n }else{\n $new_ids[] = intval($id);\n }\n }\n /*array_map(function ($v) use ($old_id_in_idfield, $new_id) {\n return $v == $old_id_in_idfield ? $new_id : $v;\n }, $ids);*/\n\n $new_ids = \"'\".implode($csv_mvsep, $new_ids).\"'\";\n\n $updquery = \"UPDATE `$import_table` SET `$id_field`=$new_ids WHERE imp_id=\".intval($row[0]);\n\n self::$mysqli->query($updquery);\n }//foreach\n }\n }\n\n }\n\n /*\n if (@$out['warning'] && $mode_output!='json') {\n print \"
    Warning: \".implode(\";\",$out[\"warning\"]).DIV_E;\n }\n */\n\n }\n\n return $new_recordID;\n}", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function creerDossierIB($ref_dos, $id_cli, $ref_fact, $fob, \n\t\t\t\t\t\t\t\t\t\t$fret, $assurance, $autre_frais, $num_lic, \n\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $id_march, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$ref_av, $cod, $id_util, $road_manif, $date_preal, \n\t\t\t\t\t\t\t\t\t\t$t1, $poids,$po_ref, \n\t\t\t\t\t\t\t\t\t\t$commodity, $horse, $trailer_1, $trailer_2, $ref_crf, \n\t\t\t\t\t\t\t\t\t\t$date_crf, $bond_warehouse='KOLWEZI', $supplier, $temporelle='0', $frontiere='KASUMBALESA', $regime='EX1'){\n\t\t\tinclude('connexion.php');\n\n\t\t\tif ($id_cli != '845' && $id_cli != '856' && $id_cli != '857' && $id_cli != '863' && $id_cli != '864' && $id_cli != '884' && $id_cli != '885' && $id_cli != '901') {\n\t\t\t\t$bond_warehouse = 'LUBUMBASHI';\n\t\t\t}else{\n\t\t\t\t//if (isset($bond_warehouse) && ($bond_warehouse!=null)) {\n\t\t\t\t\t$bond_warehouse = 'KOLWEZI';\n\t\t\t\t//}\n\t\t\t}\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['ref_fact'] = $ref_fact; \n\t\t\t$entree['fob'] = $fob; $entree['fret'] = $fret; $entree['assurance'] = $assurance; \n\t\t\t$entree['autre_frais'] = $autre_frais; $entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic; $entree['id_march'] = $id_march; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['ref_av'] = $ref_av;\n\t\t\t$entree['cod'] = $cod;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t$entree['road_manif'] = $road_manif;$entree['date_preal'] = $date_preal;\n\t\t\t$entree['t1'] = $t1;$entree['poids'] = $poids;\n\t\t\t$entree['fret'] = $fret;$entree['po_ref'] = $po_ref;\n\t\t\t$entree['commodity'] = $commodity;$entree['horse'] = $horse;\n\t\t\t$entree['trailer_1'] = $trailer_1;$entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['ref_crf'] = $ref_crf;$entree['date_crf'] = $date_crf;\n\t\t\t$entree['bond_warehouse'] = $bond_warehouse;\n\t\t\t$entree['supplier'] = $supplier;\n\t\t\t$entree['temporelle'] = $temporelle;\n\t\t\t$entree['frontiere'] = $frontiere;\n\t\t\t$entree['regime'] = $regime;\n\n\t\t\tif($entree['date_preal'] == '' || (!isset($entree['date_preal'])) ){\n\t\t\t\t$entree['date_preal'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fob'] == '' || (!isset($entree['fob'])) ){\n\t\t\t\t$entree['fob'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fret'] == '' || (!isset($entree['fret'])) ){\n\t\t\t\t$entree['fret'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['assurance'] == '' || (!isset($entree['assurance'])) ){\n\t\t\t\t$entree['assurance'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['autre_frais'] == '' || (!isset($entree['autre_frais'])) ){\n\t\t\t\t$entree['autre_frais'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['poids'] == '' || (!isset($entree['poids'])) ){\n\t\t\t\t$entree['poids'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_crf'] == '' || (!isset($entree['date_crf'])) ){\n\t\t\t\t$entree['date_crf'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['id_march'] == '' || (!isset($entree['id_march'])) ){\n\t\t\t\t$entree['id_march'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['ref_av'] == '' || (!isset($entree['ref_av'])) ){\n\t\t\t\t$entree['ref_av'] = NULL;\n\t\t\t}\n\n\t\t\t// echo '
    --------------------------------------ref_dos = '.$entree['ref_dos'];\n\t\t\t// echo '
    --------------------------------------id_cli = '.$entree['id_cli'];\n\t\t\t// echo '
    --------------------------------------ref_fact = '.$entree['ref_fact'];\n\t\t\t// echo '
    --------------------------------------fob = '.$entree['fob'];\n\t\t\t// echo '
    --------------------------------------fret = '.$entree['fret'];\n\t\t\t// echo '
    --------------------------------------assurance = '.$entree['assurance'];\n\t\t\t// echo '
    --------------------------------------autre_frais = '.$entree['autre_frais'];\n\t\t\t// echo '
    --------------------------------------num_lic = '.$entree['num_lic'];\n\t\t\t// echo '
    --------------------------------------id_mod_lic = '.$entree['id_mod_lic'];\n\t\t\t// echo '
    --------------------------------------id_march = '.$entree['id_march'];\n\t\t\t// echo '
    --------------------------------------id_mod_trans = '.$entree['id_mod_trans'];\n\t\t\t// echo '
    --------------------------------------ref_av = '.$entree['ref_av'];\n\t\t\t// echo '
    --------------------------------------COD = '.$entree['cod'];\n\t\t\t// echo '
    --------------------------------------id_util = '.$entree['id_util'];\n\t\t\t// echo '
    --------------------------------------road_manif = '.$entree['road_manif'];\n\t\t\t// echo '
    --------------------------------------date_preal = '.$entree['date_preal'];\n\t\t\t// echo '
    --------------------------------------t1 = '.$entree['t1'];\n\t\t\t// echo '
    --------------------------------------poids = '.$entree['poids'];\n\t\t\t// echo '
    --------------------------------------po_ref = '.$entree['po_ref'];\n\t\t\t// echo '
    --------------------------------------commodity = '.$entree['commodity'];\n\t\t\t// echo '
    --------------------------------------horse = '.$entree['horse'];\n\t\t\t// echo '
    --------------------------------------trailer_1 = '.$entree['trailer_1'];\n\t\t\t// echo '
    --------------------------------------trailer_2 = '.$entree['trailer_2'];\n\t\t\t// echo '
    --------------------------------------ref_crf = '.$entree['ref_crf'];\n\t\t\t// echo '
    --------------------------------------date_crf = '.$entree['date_crf'];\n\t\t\t// echo '
    --------------------------------------bond_warehouse = '.$entree['bond_warehouse'];\n\t\t\t// echo '
    --------------------------------------supplier = '.$entree['supplier'];\n\t\t\t// echo '
    --------------------------------------statut = '.$entree['statut'];\n\t\t\t// echo '
    --------------------------------------temporelle = '.$entree['temporelle'];\n\t\t\t// echo '
    --------------------------------------frontiere = '.$entree['frontiere'];\n\t\t\t// echo '
    --------------------------------------regime = '.$entree['regime'];\n\n\t\t\tif (($this-> getDossierRefDos($ref_dos)==NULL)) {\n\t\t\t\n\t\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, ref_fact, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfret, assurance, autre_frais, num_lic, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_march, id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_av,cod, id_util, road_manif, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate_preal, t1, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpo_ref, commodity, horse, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_1, trailer_2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_crf, date_crf, bond_warehouse, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsupplier, statut, temporelle, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrontiere, regime)\n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \"EXPECTED TO ARRIVE\", ?, ?, ?)');\n\t\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['num_lic'], $entree['id_mod_lic'], \n\t\t\t\t\t\t\t\t\t\t$entree['id_march'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t\t$entree['ref_av'], $entree['cod'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t\t$entree['road_manif'], $entree['date_preal'], $entree['t1'], \n\t\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['po_ref'], $entree['commodity'], \n\t\t\t\t\t\t\t\t\t\t$entree['horse'], $entree['trailer_1'], $entree['trailer_2'], \n\t\t\t\t\t\t\t\t\t\t$entree['ref_crf'], $entree['date_crf'], $entree['bond_warehouse'], \n\t\t\t\t\t\t\t\t\t\t$entree['supplier'], $entree['temporelle'], $entree['frontiere'], \n\t\t\t\t\t\t\t\t\t\t$entree['regime']));\n\n\t\t\t\t$id_dos = $this-> getDossierRefDos($ref_dos)['id_dos'];\n\n\t\t\t for ($i=1; $i <= $_POST['nbre_document']; $i++) { \n\t\t\t \n\t\t\t if(isset($_FILES['fichier_'.$i]['name']) && $_FILES['fichier_'.$i]['name'] != ''){\n\t\t\t $fichier=$_FILES['fichier_'.$i]['name'];\n\t\t\t $tmp=$_FILES['fichier_'.$i]['tmp_name'];\n\t\t\t //$num_dos = $maClasse-> getNumDossier($_POST['id_dos']);\n\n\t\t\t $this-> archiver($id_dos, $_POST['id_doc_'.$i], $fichier, $tmp, $_POST['ref_dos']);\n\t\t\t }\n\n\t\t\t }\n\t\t\t}\n\n\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function sellDrug(\n $drug_id,\n $quantity,\n $fee,\n $patient_id = 0,\n $encounter_id = 0,\n $prescription_id = 0,\n $sale_date = '',\n $user = '',\n $default_warehouse = '',\n $testonly = false,\n &$expiredlots = null,\n $pricelevel = '',\n $selector = ''\n) {\n\n if (empty($patient_id)) {\n $patient_id = $GLOBALS['pid'];\n }\n\n if (empty($sale_date)) {\n $sale_date = date('Y-m-d');\n }\n\n if (empty($user)) {\n $user = $_SESSION['authUser'];\n }\n\n // error_log(\"quantity = '$quantity'\"); // debugging\n\n // Sanity check.\n if (!$testonly) {\n $tmp = sqlQuery(\n \"SELECT count(*) AS count from form_encounter WHERE pid = ? AND encounter = ?\",\n array($patient_id, $encounter_id)\n );\n if (empty($tmp['count'])) {\n die(xlt('Internal error: the referenced encounter no longer exists.') . text(\" $patient_id $encounter_id\"));\n }\n }\n\n if (empty($default_warehouse)) {\n // Get the default warehouse, if any, for the user.\n $rowuser = sqlQuery(\"SELECT default_warehouse FROM users WHERE username = ?\", array($user));\n $default_warehouse = $rowuser['default_warehouse'];\n }\n\n // Get relevant options for this product.\n $rowdrug = sqlQuery(\"SELECT allow_combining, reorder_point, name, dispensable \" .\n \"FROM drugs WHERE drug_id = ?\", array($drug_id));\n $allow_combining = $rowdrug['allow_combining'];\n $dispensable = $rowdrug['dispensable'];\n\n if (!$dispensable) {\n // Non-dispensable is a much simpler case and does not touch inventory.\n if ($testonly) {\n return true;\n }\n\n $sale_id = sqlInsert(\n \"INSERT INTO drug_sales ( \" .\n \"drug_id, inventory_id, prescription_id, pid, encounter, user, \" .\n \"sale_date, quantity, fee ) VALUES ( \" .\n \"?, 0, ?, ?, ?, ?, ?, ?, ?)\",\n array($drug_id, $prescription_id, $patient_id, $encounter_id, $user, $sale_date, $quantity, $fee)\n );\n return $sale_id;\n }\n\n // Combining is never allowed for prescriptions and will not work with\n // dispense_drug.php.\n if ($prescription_id) {\n $allow_combining = 0;\n }\n\n $rows = array();\n // $firstrow = false;\n $qty_left = $quantity;\n $bad_lot_list = '';\n $total_on_hand = 0;\n $gotexpired = false;\n\n // If the user has a default warehouse, sort those lots first.\n $orderby = ($default_warehouse === '') ?\n \"\" : \"di.warehouse_id != '$default_warehouse', \";\n $orderby .= \"lo.seq, di.expiration, di.lot_number, di.inventory_id\";\n\n // Retrieve lots in order of expiration date within warehouse preference.\n $query = \"SELECT di.*, lo.option_id, lo.seq \" .\n \"FROM drug_inventory AS di \" .\n \"LEFT JOIN list_options AS lo ON lo.list_id = 'warehouse' AND \" .\n \"lo.option_id = di.warehouse_id AND lo.activity = 1 \" .\n \"WHERE \" .\n \"di.drug_id = ? AND di.destroy_date IS NULL AND di.on_hand != 0 \";\n $sqlarr = array($drug_id);\n if ($GLOBALS['SELL_FROM_ONE_WAREHOUSE'] && $default_warehouse) {\n $query .= \"AND di.warehouse_id = ? \";\n $sqlarr[] = $default_warehouse;\n }\n\n $query .= \"ORDER BY $orderby\";\n $res = sqlStatement($query, $sqlarr);\n\n // First pass. Pick out lots to be used in filling this order, figure out\n // if there is enough quantity on hand and check for lots to be destroyed.\n while ($row = sqlFetchArray($res)) {\n if ($row['warehouse_id'] != $default_warehouse) {\n // Warehouses with seq > 99 are not available.\n $seq = empty($row['seq']) ? 0 : $row['seq'] + 0;\n if ($seq > 99) {\n continue;\n }\n }\n\n $on_hand = $row['on_hand'];\n $expired = (!empty($row['expiration']) && $row['expiration'] <= $sale_date);\n if ($expired || $on_hand < $quantity) {\n $tmp = $row['lot_number'];\n if (! $tmp) {\n $tmp = '[missing lot number]';\n }\n\n if ($bad_lot_list) {\n $bad_lot_list .= ', ';\n }\n\n $bad_lot_list .= $tmp;\n }\n\n if ($expired) {\n $gotexpired = true;\n continue;\n }\n\n /*****************************************************************\n // Note the first row in case total quantity is insufficient and we are\n // allowed to go negative.\n if (!$firstrow) $firstrow = $row;\n *****************************************************************/\n\n $total_on_hand += $on_hand;\n\n if ($on_hand > 0 && $qty_left > 0 && ($allow_combining || $on_hand >= $qty_left)) {\n $rows[] = $row;\n $qty_left -= $on_hand;\n }\n }\n\n if ($expiredlots !== null) {\n $expiredlots = $gotexpired;\n }\n\n if ($testonly) {\n // Just testing inventory, so return true if OK, false if insufficient.\n // $qty_left, if positive, is the amount requested that could not be allocated.\n return $qty_left <= 0;\n }\n\n if ($bad_lot_list) {\n send_drug_email(\n \"Possible lot destruction needed\",\n \"The following lot(s) are expired or were too small to fill the \" .\n \"order for patient $patient_id: $bad_lot_list\\n\"\n );\n }\n\n /*******************************************************************\n if (empty($firstrow)) return 0; // no suitable lots exist\n // This can happen when combining is not allowed. We will use the\n // first row and take it negative.\n if (empty($rows)) {\n $rows[] = $firstrow;\n $qty_left -= $firstrow['on_hand'];\n }\n *******************************************************************/\n\n // The above was an experiment in permitting a negative lot quantity.\n // We decided that was a bad idea, so now we just error out if there\n // is not enough on hand.\n if ($qty_left > 0) {\n return 0;\n }\n\n $sale_id = 0;\n $qty_final = $quantity; // remaining unallocated quantity\n $fee_final = $fee; // remaining unallocated fee\n\n // Second pass. Update the database.\n foreach ($rows as $row) {\n $inventory_id = $row['inventory_id'];\n\n /*****************************************************************\n $thisqty = $row['on_hand'];\n if ($qty_left > 0) {\n $thisqty += $qty_left;\n $qty_left = 0;\n }\n else if ($thisqty > $qty_final) {\n $thisqty = $qty_final;\n }\n *****************************************************************/\n $thisqty = min($qty_final, $row['on_hand']);\n\n $qty_final -= $thisqty;\n\n // Compute the proportional fee for this line item. For the last line\n // item take the remaining unallocated fee to avoid round-off error.\n if ($qty_final) {\n $thisfee = sprintf('%0.2f', $fee * $thisqty / $quantity);\n } else {\n $thisfee = sprintf('%0.2f', $fee_final);\n }\n\n $fee_final -= $thisfee;\n\n // Update inventory and create the sale line item.\n sqlStatement(\"UPDATE drug_inventory SET \" .\n \"on_hand = on_hand - ? \" .\n \"WHERE inventory_id = ?\", array($thisqty,$inventory_id));\n $sale_id = sqlInsert(\n \"INSERT INTO drug_sales ( \" .\n \"drug_id, inventory_id, prescription_id, pid, encounter, user, sale_date, quantity, fee, pricelevel, selector ) \" .\n \"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n array($drug_id, $inventory_id, $prescription_id, $patient_id, $encounter_id, $user,\n $sale_date,\n $thisqty,\n $thisfee,\n $pricelevel,\n $selector)\n );\n\n // If this sale exhausted the lot then auto-destroy it if that is wanted.\n if ($row['on_hand'] == $thisqty && !empty($GLOBALS['gbl_auto_destroy_lots'])) {\n sqlStatement(\n \"UPDATE drug_inventory SET \" .\n \"destroy_date = ?, destroy_method = ?, destroy_witness = ?, destroy_notes = ? \" .\n \"WHERE drug_id = ? AND inventory_id = ?\",\n array($sale_date, xl('Automatic from sale'), $user, \"sale_id = $sale_id\",\n $drug_id,\n $inventory_id)\n );\n }\n }\n\n /*******************************************************************\n // If appropriate, generate email to notify that re-order is due.\n if (($total_on_hand - $quantity) <= $rowdrug['reorder_point']) {\n send_drug_email(\"Product re-order required\",\n \"Product '\" . $rowdrug['name'] . \"' has reached its reorder point.\\n\");\n }\n // TBD: If the above is un-commented, fix it to handle the case of\n // $GLOBALS['gbl_min_max_months'] being true.\n *******************************************************************/\n\n // If combining is allowed then $sale_id will be just the last inserted ID,\n // and it serves only to indicate that everything worked. Otherwise there\n // can be only one inserted row and this is its ID.\n return $sale_id;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function generate_list_payment_category($tag_name, $list_id, $currvalue, $title, $empty_name = ' ', $class = '', $onchange = '', $PaymentType = 'insurance', $screen = 'new_payment')\n{\n $s = '';\n $s .= \"\";\n $fontTitle = xl('Please choose a valid selection from the list.');\n $fontText = xl('Fix this');\n $s .= \" \" . text($fontText) . \"!\";\n } else {\n $s .= \"\";\n }\n return $s;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $userId, ?string $email, ?string $phone, ?string $password, string $name, Response $response, Document $project, Database $dbForProject, Event $events) {\n\n $user = createUser('plaintext', '{}', $userId, $email, $password, $phone, $name, $project, $dbForProject, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function inscriptionStageOre($num,$nom,$prenom,$jour_naissance,$mois_naissance,$annee_naissance,$date,$ip,$user_agent,$origine,$id_atelier,$classe)\n\t{\n\t\t$req = \"INSERT INTO `ELEVE_STAGE`(`NOM_ELEVE_STAGE`, `PRENOM_ELEVE_STAGE`,`DDN_ELEVE_STAGE`,`ASSOCIATION_ELEVE_STAGE`, `CLASSE_ELEVE_STAGE`) VALUES ('\".strtoupper(addslashes($nom)).\"','\".ucfirst(addslashes($prenom)).\"','$annee_naissance-$mois_naissance-$jour_naissance','ore','$classe');\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t\n\t\t\n\t\t$req = \"INSERT INTO `INSCRIPTIONS_STAGE`(`ID_STAGE`,`ID_ELEVE_STAGE`,`ID_ATELIERS`,`VALIDE`,`DATE_INSCRIPTIONS`,`IP_INSCRIPTIONS`,`USER_AGENT_INSCRIPTIONS`, `ORIGINE_INSCRIPTIONS`) VALUES ('$num',(SELECT MAX(`ID_ELEVE_STAGE`) AS max_id FROM `ELEVE_STAGE`),'$id_atelier',0,'$date','$ip','\".addslashes($user_agent).\"','\".addslashes($origine).\"'); \";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function gettwopointdata($str,$type,$xmin=null,$xmax=null,$ymin=null,$ymax=null,$w=null,$h=null) {\n if (trim($str)=='') { return []; }\n if (is_string($xmin) && strpos($xmin,',')!==false) {\n list($xmin,$xmax,$ymin,$ymax,$w,$h) = parsedrawgrid($xmin,$xmax);\n } else {\n if ($xmin === null) { $xmin = -5;}\n if ($xmax === null) { $xmax = 5;}\n if ($ymin === null) { $ymin = -5;}\n if ($ymax === null) { $ymax = 5;}\n if ($w === null) { $w = 300;}\n if ($h === null) { $h = 300;}\n }\n\tif ($type=='line') {\n\t\t$code = 5;\n\t} else if ($type=='lineseg') {\n\t\t$code = 5.3;\n\t} else if ($type=='ray') {\n\t\t$code = 5.2;\n\t} else if ($type=='parab') {\n\t\t$code = 6;\n\t} else if ($type=='horizparab') {\n\t\t$code = 6.1;\n\t} else if ($type=='cubic') {\n\t\t$code = 6.3;\n\t} else if ($type=='sqrt') {\n\t\t$code = 6.5;\n\t} else if ($type=='cuberoot') {\n\t\t$code = 6.6;\n\t} else if ($type=='abs') {\n\t\t$code = 8;\n\t} else if ($type=='rational') {\n\t\t$code = 8.2;\n\t} else if ($type=='exp') {\n\t\t$code = 8.3;\n\t} else if ($type=='log') {\n\t\t$code = 8.4;\n\t} else if ($type=='genexp') {\n $code = 8.5;\n } else if ($type=='genlog') {\n $code = 8.6;\n } else if ($type=='circle' || $type=='circlerad') {\n\t\t$code = 7;\n\t} else if ($type=='ellipse' || $type=='ellipserad') {\n $code = 7.2;\n } else if ($type=='sin') {\n\t\t$code = 9.1;\n\t} else if ($type=='cos') {\n\t\t$code = 9;\n\t} else if ($type=='vector') {\n\t\t$code = 5.4;\n\t} else {\n\t\t$code = -1;\n\t}\n\t$imgborder = 5;\n\t$pixelsperx = ($w - 2*$imgborder)/($xmax-$xmin);\n\t$pixelspery = ($h - 2*$imgborder)/($ymax -$ymin);\n\t$outpts = array();\n\tlist($lines,$dots,$odots,$tplines,$ineqlines) = explode(';;',$str);\n\tif ($tplines=='') {return array();}\n\t$tplines = explode('),(', substr($tplines,1,strlen($tplines)-2));\n\tforeach ($tplines as $k=>$val) {\n\t\t$pts = explode(',',$val);\n\t\tif ($pts[0]==$code) {\n\t\t\t$pts[1] = ($pts[1] - $imgborder)/$pixelsperx + $xmin;\n\t\t\t$pts[3] = ($pts[3] - $imgborder)/$pixelsperx + $xmin;\n\t\t\t$pts[2] = ($h - $pts[2] - $imgborder)/$pixelspery + $ymin;\n\t\t\t$pts[4] = ($h - $pts[4] - $imgborder)/$pixelspery + $ymin;\n $outpt = array($pts[1], $pts[2], $pts[3], $pts[4]);\n if ($type=='ellipserad') {\n $pts[3] = abs($pts[3]-$pts[1]);\n $pts[4] = abs($pts[4]-$pts[2]);\n $outpt = array($pts[1], $pts[2], $pts[3], $pts[4]);\n } else if ($type=='circlerad') {\n $pts[3] = sqrt(pow($pts[3]-$pts[1],2)+pow($pts[4]-$pts[2],2));\n $outpt = array($pts[1], $pts[2], $pts[3]);\n } else if ($type=='genexp' || $type=='genlog') {\n $pts[5] = ($pts[5] - $imgborder)/$pixelsperx + $xmin;\n $pts[6] = ($h - $pts[6] - $imgborder)/$pixelspery + $ymin;\n // Last value is the asymptote: y val for genexp, x val for genlog\n $outpt = ($type=='genexp') ? array($pts[3], $pts[4], $pts[5], $pts[6], $pts[2]) : array($pts[3], $pts[4], $pts[5], $pts[6], $pts[1]);\n }\n\t\t\t$outpts[] = $outpt;\n\t\t}\n\t}\n\treturn $outpts;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function addItem($reportId, $itemId, $ruleId, $tempBeginMeasurement, $endMeasurement, $pass, $pid, $object_to_count, \\AmcItemizedActionData $numeratorItemizedDetails, \\AmcItemizedActionData $denominatorItemizedDetails)\n {\n $this->items[] = ['reportId' => $reportId, 'itemId' => $itemId, 'ruleId' => $ruleId,\n 'begin' => $tempBeginMeasurement, 'end' => $endMeasurement, 'pass' => $pass, 'pid' => $pid\n , 'object_to_count' => $object_to_count];\n\n $combinedAmc = new \\AmcItemizedActionData();\n $combinedAmc->addActionObject($numeratorItemizedDetails);\n $combinedAmc->addActionObject($denominatorItemizedDetails);\n $detailsJson = json_encode($combinedAmc);\n\n insertItemReportTracker($reportId, $itemId, $pass, $pid, '', $ruleId, $detailsJson);\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function dropdown_facility(\n $selected = '',\n $name = 'form_facility',\n $allow_unspecified = true,\n $allow_allfacilities = true,\n $disabled = '',\n $onchange = '',\n $multiple = false,\n $class = ''\n) {\n global $facilityService;\n\n $have_selected = false;\n $fres = $facilityService->getAllFacility();\n $id = $name;\n\n if ($multiple) {\n $name = $name . \"[]\";\n }\n echo \" \\n\";\n}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n RepositoryInterface $repository,\n ContentService $contentService,\n ContentTypeService $contentTypeService,\n ObjectStateService $objectStateService,\n URLAliasService $urlAliasService,\n UserService $userService,\n SearchService $searchService,\n SectionService $sectionService,\n TrashService $trashService,\n LocationService $locationService,\n LanguageService $languageService,\n NotificationService $notificationService\n ) {\n $this->repository = $repository;\n $this->contentService = $contentService;\n $this->contentTypeService = $contentTypeService;\n $this->objectStateService = $objectStateService;\n $this->urlAliasService = $urlAliasService;\n $this->userService = $userService;\n $this->searchService = $searchService;\n $this->sectionService = $sectionService;\n $this->trashService = $trashService;\n $this->locationService = $locationService;\n $this->languageService = $languageService;\n $this->notificationService = $notificationService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function exist_custom_item($patient_id, $category, $item, $complete, $num_items_comp, $num_items_thres, string $intervalType = null, string $intervalValue = null, $dateFocus = null, $dateTarget = null)\n{\n\n // Set the table\n $table = 'rule_patient_data';\n\n // Collect the correct column label for patient id in the table\n $patient_id_label = collect_database_label('pid', $table);\n\n // Get the interval sql query string\n /*\n For filters, $intervalType and $intervalValue are empty strings\n For targets, they are defiend (something like 1 year)\n if $intervalType and $intervalValue are empty strings, sql_interval_string returns something like\n [date field] <= $dateTarget\n If $intervalType and $intervalValue are valued, sql_interval_string returns something like\n [date field] between $dateFocus - interval and $dateTarget\n */\n $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateFocus, $dateTarget);\n\n // search for number of specific items\n $sql = sqlStatementCdrEngine(\"SELECT `result` \" .\n \"FROM `\" . escape_table_name($table) . \"` \" .\n \"WHERE `category`=? \" .\n \"AND `item`=? \" .\n \"AND `complete`=? \" .\n \"AND `\" . add_escape_custom($patient_id_label) . \"`=? \" .\n $dateSql, array($category,$item,$complete,$patient_id));\n\n // See if number of returned items passes the comparison\n return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function InsertaUsuarioTemp(\n\t\t\t\t$rut, $dv, $nombre, $apaterno, $amaterno, $fecha_nacimiento, $genero, \n\t\t\t\t$email, $nacionalidad, $direccion_particular, $codigo_escolaridad, $codigo_nivel, \n\t\t\t\t$gerencia, $cargo, $unidad_negocio, $centro_costo, $empresa_holding, \n\t\t\t\t$fecha_antiguedad, $tipo_contrato, $tramo_sence, $perfil_evaluacion, $accion){\n\tglobal $c_host,$c_user,$c_pass,$c_db;\t\n\t$rut_completo=$rut.\"-\".$dv;\n\t$nombre_completo=$nombre.\" \".$apaterno.\" \".$amaterno;\n\t$database = new database($c_host,$c_user,$c_pass);\n\t$database->setDb($c_db);\n\t$sql = \"INSERT INTO tbl_usuario_temp\n\t\t\t\t\t\t\t(rut, dv, rut_completo, nombre, apaterno, amaterno, \n\t\t\t\t\t\t\tnombre_completo, cargo, fecha_nacimiento, genero, email, \n\t\t\t\t\t\t\tnacionalidad, direccion_particular, codigo_escolaridad, \n\t\t\t\t\t\t\tcodigo_nivel, gerencia, unidad_negocio, \n\t\t\t\t\t\t\tcentro_costo, empresa_holding, fecha_antiguedad, \n\t\t\t\t\t\t\ttipo_contrato, tramo_sence, perfil_evaluacion, id_empresa, accion) \".\n\t\t\t\n\t\"VALUES \t\t\t\t('$rut', '$dv', '$rut_completo', '$nombre', \n\t\t\t\t\t\t\t'$apaterno', '$amaterno', '$nombre_completo', \n\t\t\t\t\t\t\t'$cargo', '$fecha_nacimiento', '$genero', \n\t\t\t\t\t\t\t'$email', '$nacionalidad','$direccion_particular', \n\t\t\t\t\t\t\t'$codigo_escolaridad','$codigo_nivel', '$gerencia', \n\t\t\t\t\t\t\t '$unidad_negocio', '$centro_costo', '$empresa_holding', \n\t\t\t\t\t\t\t'$fecha_antiguedad', '$tipo_contrato', '$tramo_sence', '$perfil_evaluacion', '19', '$accion'\n\t\t\t\n\t\t\t);\";\n\t\t\t\n\t$database->setquery($sql);\n\t$database->query();\t\n\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function makejournal($j, $sn, $ops, &$anstypes, &$questions, &$answer, &$showanswer, &$displayformat, &$answerboxsize) {\n\t$debug = false;\n\tif (isset($j['date'])) {//not multiple date\n\t\t$new = array($j);\n\t\t$j = $new;\n\t}\n\n\tif ($anstypes === null) { $anstypes = array();}\n\tif ($questions === null) { $questions = array();}\n\tif ($answer === null) { $answer = array();}\n\tif ($showanswer === null) { $showanswer = '';}\n\tif ($displayformat === null) { $displayformat = array();}\n\n\tif (isset($ops[0]) && $ops[0] == 'pulldowns') {\n\t\tarray_shift($ops);\n\t\t$disptype = 'select';\n\t} else {\n\t\t$disptype = 'typeahead';\n\t}\n\n\t$maxsizedescr = 0; $maxsizeentry = 0; $hasdecimals = false; $maxsizepostref=0;\n\tforeach ($j as $ix=>$jd) {\n\t\t$usePostRefs = !empty($jd['haspostrefs']);\n\t\t$valinc = $usePostRefs?2:1;\n $colinc = $usePostRefs?3:2;\n if (isset($jd['debits'])) {\n for ($i=0;$i$maxsizedescr) { $maxsizedescr = $sl;}\n if ($usePostRefs) {\n $sl = strlen($jd['debits'][$i+1]);\n if ($sl>$maxsizepostref) { $maxsizepostref = $sl; }\n }\n $sl = strlen($jd['debits'][$i+$valinc]);\n if ($sl>$maxsizeentry) { $maxsizeentry = $sl;}\n if (!$hasdecimals && strpos($jd['debits'][$i+$valinc],'.')!==false) { $hasdecimals = true;}\n if ($debug && !in_array($jd['debits'][$i], $ops)) {\n echo \"Eek: \".$jd['debits'][$i].\" not in options array
    \";\n }\n\n }\n }\n if (isset($jd['credits'])) {\n for ($i=0;$i$maxsizedescr) { $maxsizedescr = $sl;}\n if ($usePostRefs) {\n $sl = strlen($jd['credits'][$i+1]);\n if ($sl>$maxsizepostref) { $maxsizepostref = $sl; }\n }\n $sl = strlen($jd['credits'][$i+$valinc]);\n if ($sl>$maxsizeentry) { $maxsizeentry = $sl;}\n if (!$hasdecimals && strpos($jd['credits'][$i+$valinc],'.')!==false) { $hasdecimals = true;}\n if ($debug && !in_array($jd['credits'][$i], $ops)) {\n echo \"Eek: \".$jd['credits'][$i].\" not in options array
    \";\n }\n }\n }\n\t}\n\tforeach ($ops as $op) {\n\t\t$sl = strlen($op);\n\t\tif ($sl>$maxsizedescr) { $maxsizedescr = $sl;}\n\t}\n\tnatsort($ops);\n\t$maxsizedescr += 6;\n\t$maxsizeentry += 3;\n\t$maxsizeentry = max($maxsizeentry,10);\n\t$out = '';\n\tif ($usePostRefs) {\n\t\t$out .= '';\n\t}\n\t$out .= '';\n\t$sa = $out;\n\tforeach ($j as $ix=>$jd) {\n\t\t$usePostRefs = !empty($jd['haspostrefs']);\n\t\t$colinc = $usePostRefs?3:2;\n\t\t$valinc = $usePostRefs?2:1;\n\t\t$colspan = $usePostRefs ? 5 : 4;\n\t\tif ($ix>0) {\n\t\t\t$out .= '';\n\t\t\t$sa .= '';\n\t\t}\n $dateset = false;\n if (isset($jd['debits'])) {\n for ($i=0;$i':'').($jd['date'] ?? '').($dateset?'':'').'';\n $sa .= '';\n $dateset = true;\n $out .= '';\n if ($usePostRefs) {\n $out .= '';\n }\n $out .= '';\n $anstypes[$sn] = 'string'; $displayformat[$sn] = $disptype; $questions[$sn] = $ops; $answer[$sn] = $jd['debits'][$i]; $answerboxsize[$sn] = $maxsizedescr;\n $sa .= '';\n if ($usePostRefs) {\n $anstypes[$sn+1] = 'string'; $answer[$sn+1] = $jd['debits'][$i+1]; $answerboxsize[$sn+1] = $maxsizepostref;\n $sa .= '';\n }\n\n if ($jd['debits'][$i+$valinc]=='') {\n $anstypes[$sn+$valinc] = 'number'; $displayformat[$sn+$valinc] = 'debit';\n $answer[$sn+$valinc] = ''; $answerboxsize[$sn+$valinc] = $maxsizeentry;\n $sa .= '';\n } else {\n $jd['debits'][$i+$valinc] = str_replace(array('$',',',' '),'',$jd['debits'][$i+$valinc])*1;\n $sa .= '';\n $anstypes[$sn+$valinc] = 'number'; $displayformat[$sn+$valinc] = 'debit';\n $answer[$sn+$valinc] = $jd['debits'][$i+$valinc]; $answerboxsize[$sn+$valinc] = $maxsizeentry;\n }\n $anstypes[$sn+$colinc] = 'number'; $displayformat[$sn+$colinc] = 'credit';\n $answer[$sn+$colinc] = ''; $answerboxsize[$sn+$colinc] = $maxsizeentry;\n\n $sn += $colinc+1;\n }\n }\n if (isset($jd['credits'])) {\n for ($i=0;$i':'').($jd['date'] ?? '').($dateset?'':'').'';\n $sa .= '';\n $dateset = true;\n\n $out .= '';\n $sa .= '';\n if ($usePostRefs) {\n $out .= '';\n $sa .= '';\n }\n $out .= '';\n $jd['credits'][$i+$valinc] = str_replace(array('$',',',' '),'',$jd['credits'][$i+$valinc])*1;\n $sa .= '';\n //$anstypes[$sn] = 'string'; $displayformat[$sn] = 'typeahead'; $questions[$sn] = $ops; $answer[$sn] = $jd['credits'][$i]; $answerboxsize[$sn] = $maxsizedescr;\n $anstypes[$sn] = 'string'; $displayformat[$sn] = $disptype; $questions[$sn] = $ops; $answer[$sn] =$jd['credits'][$i]; $answerboxsize[$sn] = $maxsizedescr;\n if ($usePostRefs) {\n $anstypes[$sn+1] = 'string'; $answer[$sn+1] = $jd['credits'][$i+1]; $answerboxsize[$sn+1] = $maxsizepostref;\n }\n $anstypes[$sn+$valinc] = 'number'; $displayformat[$sn+$valinc] = 'debit';\n $answer[$sn+$valinc] = ''; $answerboxsize[$sn+$valinc] = $maxsizeentry;\n $anstypes[$sn+$colinc] = 'number'; $displayformat[$sn+$colinc] = 'credit';\n $answer[$sn+$colinc] = $jd['credits'][$i+$valinc]; $answerboxsize[$sn+$colinc] = $maxsizeentry;\n\n $sn += $colinc+1;\n }\n }\n\t\tif (isset($jd['extrarows'])) {\n\t\t\tfor ($i=0;$i<$jd['extrarows'];$i++) {\n\t\t\t\t$out .= '';\n\t\t\t $dateset = true;\n\n\t\t\t\t$out .= '';\n\t\t\t\tif ($usePostRefs) {\n\t\t\t\t\t$out .= '';\n\t\t\t\t}\n\t\t\t\t$out .= '';\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $disptype; $questions[$sn] = $ops; $answer[$sn] = \"\"; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t\tif ($usePostRefs) {\n\t\t\t\t\t$anstypes[$sn+1] = 'string'; $answer[$sn+1] = ''; $answerboxsize[$sn+1] = $maxsizepostref;\n\t\t\t\t}\n\t\t\t\t$anstypes[$sn+$valinc] = 'string'; $displayformat[$sn+$valinc] = 'debit'; $answer[$sn+$valinc] = ''; $answerboxsize[$sn+$valinc] = $maxsizeentry;\n\t\t\t\t$anstypes[$sn+$colinc] = 'string'; $displayformat[$sn+$colinc] = 'credit'; $answer[$sn+$colinc] = ''; $answerboxsize[$sn+$colinc] = $maxsizeentry;\n\t\t\t\t$sn += $colinc+1;\n\t\t\t}\n\t\t}\n\t\tif (isset($jd['note'])) {\n\t\t\t$out .= '';\n\t\t\t$sa .= '';\n\t\t}\n\t\tif (isset($jd['explanation'])) {\n\t\t\t$sa .= '';\n\t\t}\n\t}\n\t$out .= '
    Journal
    DateDescriptionPost Ref.DebitCredit
    '.($dateset?'':'').($jd['date'] ?? '').($dateset?'':'').'[AB'.$sn.'][AB'.($sn+1).'][AB'.($sn+2).'][AB'.($sn+3).']
    '.$jd['debits'][$i].''.$jd['debits'][$i+1].''.$jd['debits'][$i].'
    '.($hasdecimals?number_format($jd['debits'][$i+$valinc],2,'.',','):number_format($jd['debits'][$i+$valinc])).'
    '.($dateset?'':'').($jd['date'] ?? '').($dateset?'':'').'[AB'.$sn.'][AB'.($sn+1).'][AB'.($sn+2).']   '.$jd['credits'][$i].'[AB'.($sn+3).']'.$jd['credits'][$i+1].'
    '.($hasdecimals?number_format($jd['credits'][$i+$valinc],2,'.',','):number_format($jd['credits'][$i+$valinc])).'
    '.($dateset?'':'').($jd['date'] ?? '').($dateset?'':'').'[AB'.$sn.'][AB'.($sn+1).'][AB'.($sn+2).'][AB'.($sn+3).']
    '.($jd['date'] ?? '').''.$jd['note'].'
    '.($jd['date'] ?? '').''.$jd['note'].'
    '.($jd['date'] ?? '').''.$jd['explanation'].'
    ';\n\t$sa .= '';\n\t$showanswer .= $sa.'

     

    ';\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function addField($id, $caption, $type, $required = false, $size = 16, $minlen = 0, $maxlen = 255,\n $defaultValue = '', $regex_test = '', $regex_fail = '', $helpBody = '',\n $helpRules = '')\n {\n switch ($type)\n {\n case WFT_CURRENCY:\n if ($regex_test == '') $regex_test = WTR_CURRENCY;\n if ($regex_fail == '') $regex_fail = WTRF_CURRENCY;\n $minlen = 0;\n $maxlen = 10;\n break;\n case WFT_PHONE:\n if ($regex_test == '') $regex_test = WTR_PHONE;\n if ($regex_fail == '') $regex_fail = WTRF_PHONE;\n $minlen = 10;\n $maxlen = 13;\n break;\n case WFT_EMAIL:\n if ($regex_test == '') $regex_test = WTR_EMAIL;\n if ($regex_fail == '') $regex_fail = WTRF_EMAIL;\n $minlen = 10;\n $maxlen = 255;\n break;\n case WFT_CC_NUMBER:\n if ($regex_test == '') $regex_test = WTR_CC_NUMBER;\n if ($regex_fail == '') $regex_fail = WTRF_CC_NUMBER;\n $size = 30;\n $minlen = 15;\n $maxlen = 19;\n break;\n case WFT_CC_CVV2:\n if ($regex_test == '') $regex_test = WTR_CC_NUMBER;\n if ($regex_fail == '') $regex_fail = WTRF_CC_NUMBER;\n $size = 5;\n $minlen = 3;\n $maxlen = 4;\n break;\n case WFT_DATE:\n if ($regex_test == '') $regex_test = WTR_DATE;\n if ($regex_fail == '') $regex_fail = WTRF_DATE;\n $minlen = 6;\n $maxlen = 10;\n break;\n case WFT_CC_TYPE:\n $defaultValue = array(\n array( 'id' => WF_CARD_NAME_VISA, 'caption' => WF_CARD_NAME_VISA, 'selected' => false ),\n array( 'id' => WF_CARD_NAME_MASTERCARD, 'caption' => WF_CARD_NAME_MASTERCARD, 'selected' => false ),\n array( 'id' => WF_CARD_NAME_AMERICANEXPRESS, 'caption' => WF_CARD_NAME_AMERICANEXPRESS, 'selected' => false ),\n array( 'id' => WF_CARD_NAME_DISCOVER, 'caption' => WF_CARD_NAME_DISCOVER, 'selected' => false )\n );\n break;\n case WFT_BOOLEAN:\n $defaultValue = array(\n array( 'id' => 'true', 'caption' => 'True', 'selected' => false ),\n array( 'id' => 'false', 'caption' => 'False', 'selected' => false )\n );\n $minlen = 0;\n $maxlen = 10;\n break;\n case WFT_CC_EXPIRATION:\n // expiration has two select boxes\n $this->_tabIndex++;\n break;\n case WFT_ANTI_SPAM_IMAGE:\n $minlen = 6;\n $maxlen = 6;\n break;\n }\n $this->_fields[] = array(\n 'id' => $id,\n 'caption' => $caption,\n 'size' => $size,\n 'type' => $type,\n 'required' => $required,\n 'defaultValue' => $defaultValue,\n 'validatedData' => '',\n 'regex_test' => $regex_test,\n 'regex_fail' => $regex_fail,\n 'length' => array( $minlen, $maxlen ),\n 'helpBody' => $helpBody,\n 'html' => array(),\n 'helpRules' => $helpRules,\n 'tabIndex' => $this->_tabIndex++\n );\n $this->_defaultLayout .= sprintf('[%s][NL]', $id);\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "function (array $resources, string $subdomain, string $region, string $adminSecret, string $database, string $username, string $password, int $port, Response $response) {\n try {\n $nhost = new NHost($subdomain, $region, $adminSecret, $database, $username, $password, $port);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic(new Document($nhost->report($resources)), Response::MODEL_MIGRATION_REPORT);\n } catch (\\Exception $e) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Source Error: ' . $e->getMessage());\n }\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $functionId, string $name, string $runtime, array $execute, array $events, string $schedule, int $timeout, bool $enabled, bool $logging, string $entrypoint, string $commands, string $installationId, string $providerRepositoryId, string $providerBranch, bool $providerSilentMode, string $providerRootDirectory, Request $request, Response $response, Database $dbForProject, Document $project, Event $eventsInstance, Database $dbForConsole, GitHub $github) use ($redeployVcs) {\n // TODO: If only branch changes, re-deploy\n\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if (!empty($installationId) && $installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n if (!empty($providerRepositoryId) && (empty($installationId) || empty($providerBranch))) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'When connecting to VCS (Version Control System), you need to provide \"installationId\" and \"providerBranch\".');\n }\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n if (empty($runtime)) {\n $runtime = $function->getAttribute('runtime');\n }\n\n $enabled ??= $function->getAttribute('enabled', true);\n\n $repositoryId = $function->getAttribute('repositoryId', '');\n $repositoryInternalId = $function->getAttribute('repositoryInternalId', '');\n\n if (empty($entrypoint)) {\n $entrypoint = $function->getAttribute('entrypoint', '');\n }\n\n $isConnected = !empty($function->getAttribute('providerRepositoryId', ''));\n\n // Git disconnect logic\n if ($isConnected && empty($providerRepositoryId)) {\n $repositories = $dbForConsole->find('repositories', [\n Query::equal('projectInternalId', [$project->getInternalId()]),\n Query::equal('resourceInternalId', [$function->getInternalId()]),\n Query::equal('resourceType', ['function']),\n Query::limit(100),\n ]);\n\n foreach ($repositories as $repository) {\n $dbForConsole->deleteDocument('repositories', $repository->getId());\n }\n\n $providerRepositoryId = '';\n $installationId = '';\n $providerBranch = '';\n $providerRootDirectory = '';\n $providerSilentMode = true;\n $repositoryId = '';\n $repositoryInternalId = '';\n }\n\n // Git connect logic\n if (!$isConnected && !empty($providerRepositoryId)) {\n $teamId = $project->getAttribute('teamId', '');\n\n $repository = $dbForConsole->createDocument('repositories', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::team(ID::custom($teamId))),\n Permission::update(Role::team(ID::custom($teamId), 'owner')),\n Permission::update(Role::team(ID::custom($teamId), 'developer')),\n Permission::delete(Role::team(ID::custom($teamId), 'owner')),\n Permission::delete(Role::team(ID::custom($teamId), 'developer')),\n ],\n 'installationId' => $installation->getId(),\n 'installationInternalId' => $installation->getInternalId(),\n 'projectId' => $project->getId(),\n 'projectInternalId' => $project->getInternalId(),\n 'providerRepositoryId' => $providerRepositoryId,\n 'resourceId' => $function->getId(),\n 'resourceInternalId' => $function->getInternalId(),\n 'resourceType' => 'function',\n 'providerPullRequestIds' => []\n ]));\n\n $repositoryId = $repository->getId();\n $repositoryInternalId = $repository->getInternalId();\n }\n\n $live = true;\n\n if (\n $function->getAttribute('name') !== $name ||\n $function->getAttribute('entrypoint') !== $entrypoint ||\n $function->getAttribute('commands') !== $commands ||\n $function->getAttribute('providerRootDirectory') !== $providerRootDirectory ||\n $function->getAttribute('runtime') !== $runtime\n ) {\n $live = false;\n }\n\n $function = $dbForProject->updateDocument('functions', $function->getId(), new Document(array_merge($function->getArrayCopy(), [\n 'execute' => $execute,\n 'name' => $name,\n 'runtime' => $runtime,\n 'events' => $events,\n 'schedule' => $schedule,\n 'timeout' => $timeout,\n 'enabled' => $enabled,\n 'live' => $live,\n 'logging' => $logging,\n 'entrypoint' => $entrypoint,\n 'commands' => $commands,\n 'installationId' => $installation->getId(),\n 'installationInternalId' => $installation->getInternalId(),\n 'providerRepositoryId' => $providerRepositoryId,\n 'repositoryId' => $repositoryId,\n 'repositoryInternalId' => $repositoryInternalId,\n 'providerBranch' => $providerBranch,\n 'providerRootDirectory' => $providerRootDirectory,\n 'providerSilentMode' => $providerSilentMode,\n 'search' => implode(' ', [$functionId, $name, $runtime]),\n ])));\n\n // Redeploy logic\n if (!$isConnected && !empty($providerRepositoryId)) {\n $redeployVcs($request, $function, $project, $installation, $dbForProject, new Document(), $github);\n }\n\n // Inform scheduler if function is still active\n $schedule = $dbForConsole->getDocument('schedules', $function->getAttribute('scheduleId'));\n $schedule\n ->setAttribute('resourceUpdatedAt', DateTime::now())\n ->setAttribute('schedule', $function->getAttribute('schedule'))\n ->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deployment')));\n Authorization::skip(fn () => $dbForConsole->updateDocument('schedules', $schedule->getId(), $schedule));\n\n $eventsInstance->setParam('functionId', $function->getId());\n\n $response->dynamic($function, Response::MODEL_FUNCTION);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function displayq($qnidx,$qidx,$seed,$doshowans,$showhints,$attemptn,$returnqtxt=false,$clearla=false,$seqinactive=false,$qcolors=array()) {\n\t//$starttime = microtime(true);\n\tglobal $DBH, $RND, $imasroot, $myrights, $showtips, $urlmode, $CFG;\n\n\tif (extension_loaded('newrelic')) { // Ensure PHP agent is available\n\t\t// Record custom data about this web transaction\n\t\tnewrelic_add_custom_parameter ('cur_qsid', $qidx);\n\t}\n\n\t$qnidx = Sanitize::onlyInt($qnidx);\n\t$qidx = Sanitize::onlyInt($qidx);\n\t$seed = Sanitize::onlyInt($seed);\n\n\tif (!isset($_SESSION['choicemap'])) { $_SESSION['choicemap'] = array(); }\n\n\t//clear out choicemap if needed\n\tunset($_SESSION['choicemap'][$qnidx]);\n\tfor ($iidx=0;isset($_SESSION['choicemap'][1000*($qnidx+1)+$iidx]);$iidx++) {\n\t\tunset($_SESSION['choicemap'][1000*($qnidx+1)+$iidx]);\n\t}\n\n\t$GLOBALS['inquestiondisplay'] = true;\n\n\t$RND->srand($seed);\n\n\tif (is_int($doshowans) && $doshowans==2) {\n\t\t$doshowans = true;\n\t\t$nosabutton = true;\n\t} else {\n\t\t$nosabutton = false;\n\t}\n\n\t/*if (func_num_args()>5 && func_get_arg(5)==true) {\n\t\t$returnqtxt = true;\n\t} else {\n\t\t$returnqtxt = false;\n\t}\n\tif (func_num_args()>6 && func_get_arg(6)==true) {\n\t\t$clearla = true;\n\t} else {\n\t\t$clearla = false;\n\t}\n\tif (func_num_args()>7 && func_get_arg(7)==true) {\n\t\t$seqinactive = true;\n\t} else {\n\t\t$seqinactive = false;\n\t}*/\n\tif (isset($GLOBALS['qdatafordisplayq'])) {\n\t\t$qdata = $GLOBALS['qdatafordisplayq'];\n\t} else if (isset($GLOBALS['qi']) && isset($GLOBALS['qi'][$GLOBALS['questions'][$qnidx]]['qtext'])) {\n\t\t$qdata = $GLOBALS['qi'][$GLOBALS['questions'][$qnidx]];\n\t} else {\n\t\t$stm = $DBH->prepare(\"SELECT qtype,control,qcontrol,qtext,answer,hasimg,extref,solution,solutionopts FROM imas_questionset WHERE id=:id\");\n\t\t$stm->execute(array(':id'=>$qidx));\n\t\t$qdata = $stm->fetch(PDO::FETCH_ASSOC);\n\t}\n\n\tif ($qdata['hasimg']>0) {\n\t\t$stm = $DBH->prepare(\"SELECT var,filename,alttext FROM imas_qimages WHERE qsetid=:qsetid\");\n\t\t$stm->execute(array(':qsetid'=>$qidx));\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\tif (substr($row[1],0,4)=='http') {\n\t\t\t\t${$row[0]} = \"\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\"\";\n\t\t\t} else if(isset($GLOBALS['CFG']['GEN']['AWSforcoursefiles']) && $GLOBALS['CFG']['GEN']['AWSforcoursefiles'] == true) {\n\t\t\t\t${$row[0]} = \"\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\"\";\n\t\t\t} else {\n\t\t\t\t${$row[0]} = \"\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\"\";\n\t\t\t}\n\t\t}\n\t}\n\tif (isset($GLOBALS['lastanswers'])) {\n\t\tforeach ($GLOBALS['lastanswers'] as $iidx=>$ar) {\n\t\t\t$arv = explode('##',$ar);\n\t\t\t$arv = $arv[count($arv)-1];\n\t\t\t$arv = explode('&',$arv);\n\t\t\tif (count($arv)==1) {\n\t\t\t\t$arv = $arv[0];\n\t\t\t}\n\t\t\tif (is_array($arv)) {\n\t\t\t\tforeach ($arv as $kidx=>$arvp) {\n\t\t\t\t\t//if (is_numeric($arvp)) {\n\t\t\t\t\tif ($arvp==='') {\n\t\t\t\t\t\t$stuanswers[$iidx+1][$kidx] = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (strpos($arvp,'$f$')!==false) {\n\t\t\t\t\t\t\t$tmp = explode('$f$',$arvp);\n\t\t\t\t\t\t\t$arvp = $tmp[0];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strpos($arvp,'$!$')!==false) {\n\t\t\t\t\t\t\t$arvp = explode('$!$',$arvp);\n\t\t\t\t\t\t\t$arvp = $arvp[1];\n\t\t\t\t\t\t\tif (is_numeric($arvp)) { $arvp = intval($arvp);}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strpos($arvp,'$#$')!==false) {\n\t\t\t\t\t\t\t$tmp = explode('$#$',$arvp);\n\t\t\t\t\t\t\t$arvp = $tmp[0];\n\t\t\t\t\t\t\t$stuanswersval[$iidx+1][$kidx] = $tmp[1];\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$stuanswers[$iidx+1][$kidx] = $arvp;\n\t\t\t\t\t}\n\t\t\t\t\t//} else {\n\t\t\t\t\t//\t$stuanswers[$iidx+1][$kidx] = preg_replace('/\\W+/','',$arvp);\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//if (is_numeric($arv)) {\n\t\t\t\tif ($arv==='' || $arv==='ReGen') {\n\t\t\t\t\t$stuanswers[$iidx+1] = null;\n\t\t\t\t} else {\n\t\t\t\t\tif (strpos($arv,'$f$')!==false) {\n\t\t\t\t\t\t$tmp = explode('$f$',$arv);\n\t\t\t\t\t\t$arv = $tmp[0];\n\t\t\t\t\t}\n\t\t\t\t\tif (strpos($arv,'$!$')!==false) {\n\t\t\t\t\t\t$arv = explode('$!$',$arv);\n\t\t\t\t\t\t$arv = $arv[1];\n\t\t\t\t\t\tif (is_numeric($arv)) { $arv = intval($arv);}\n\t\t\t\t\t}\n\t\t\t\t\tif (strpos($arv,'$#$')!==false) {\n\t\t\t\t\t\t$tmp = explode('$#$',$arv);\n\t\t\t\t\t\t$arv = $tmp[0];\n\t\t\t\t\t\t$stuanswersval[$iidx+1] = $tmp[1];\n\t\t\t\t\t}\n\t\t\t\t\t$stuanswers[$iidx+1] = $arv;\n\t\t\t\t}\n\t\t\t\t//} else {\n\t\t\t\t//\t$stuanswers[$iidx+1] = preg_replace('/\\W+/','',$arv);\n\t\t\t\t//}\n\t\t\t}\n\n\n\t\t}\n\t\t$thisq = $qnidx+1;\n\t}\n\n\tif ($qdata['qtype'] == \"multipart\" || $qdata['qtype'] == 'conditional') {\n\t\t// if multipart/condition only has one part, the stuanswers script will\n\t\t// un-array it\n\t\tif (isset($stuanswers[$thisq]) && !is_array($stuanswers[$thisq])) {\n\t\t\t$stuanswers[$thisq] = array($stuanswers[$thisq]);\n\t\t\tif (isset($stuanswersval[$thisq])) {\n\t\t\t\t$stuanswersval[$thisq] = array($stuanswersval[$thisq]);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isset($GLOBALS['scores'])) {\n\t\t$scorenonzero = getscorenonzero();\n\t}\n\tif (isset($GLOBALS['rawscores'])) {\n\t\t$scoreiscorrect = getiscorrect();\n\t}\n\t$a11yqs = 'a11y_graph='.Sanitize::onlyInt($_SESSION['userprefs']['graphdisp']);\n\t$a11yqs .= '&a11y_mouse='.Sanitize::onlyInt($_SESSION['userprefs']['drawentry']);\n\t$a11yqs .= '&a11y_math='.Sanitize::onlyInt($_SESSION['userprefs']['mathdisp']);\n\n\n\t$preevalerror = error_get_last();\n\n\ttry {\n\t\t$res1 = eval(interpret('control',$qdata['qtype'],$qdata['control']));\n\t\t$res2 = eval(interpret('qcontrol',$qdata['qtype'],$qdata['qcontrol']));\n\t} catch (Throwable $t) {\n\t\t$res1 = 'caught';\n\t\t$res2 = 'caught';\n\t\tif ($myrights>10) {\n\t\t\techo '

    Caught error in evaluating the code in this question: ';\n\t\t\techo Sanitize::encodeStringForDisplay($t->getMessage());\n\t\t\techo '

    ';\n\t\t}\n\t} \n\tif ($res1===false || $res2===false) {\n\t\tif ($myrights>10) {\n\t\t\t$error = error_get_last();\n\t\t\techo '

    Caught error in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t} else {\n\t\t\techo '

    Something went wrong with this question. Tell your teacher.

    ';\n\t\t}\n\t} else {\n\t\t$error = error_get_last();\n\t\tif ($error && $error!=$preevalerror && $myrights>10) {\n\t\t\tif ($error['type']==$_ERROR) {\n\t\t\t\techo '

    Caught error in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t\t} else if ($error['type']==E_WARNING) {\n\t\t\t\techo '

    Caught warning in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t\t}\n\t\t}\n\t}\n\t$toevalqtxt = interpret('qtext',$qdata['qtype'],$qdata['qtext']);\n\t$toevalqtxt = str_replace('\\\\','\\\\\\\\',$toevalqtxt);\n\t$toevalqtxt = str_replace(array('\\\\\\\\n','\\\\\\\\\"','\\\\\\\\$','\\\\\\\\{'),array('\\\\n','\\\\\"','\\\\$','\\\\{'),$toevalqtxt);\n\t$toevalsoln = interpret('qtext',$qdata['qtype'],$qdata['solution']);\n\t$toevalsoln = str_replace('\\\\','\\\\\\\\',$toevalsoln);\n\t$toevalsoln = str_replace(array('\\\\\\\\n','\\\\\\\\\"','\\\\\\\\$','\\\\\\\\{'),array('\\\\n','\\\\\"','\\\\$','\\\\{'),$toevalsoln);\n\n\t$toevalqtxt = preg_replace('~(]*>|)\\s*///+\\s*(]*>|)~', '', $toevalqtxt);\n\n\t//$toevalqtxt = str_replace('\"','\\\\\"',$toevalqtxt);\n\t//echo \"toeval: $toevalqtxt\";\n\tif ($doshowans) {\n\t\t$RND->srand($seed+1);\n\t\t$preevalerror = error_get_last();\n\t\ttry {\n\t\t\t$res1 = eval(interpret('answer',$qdata['qtype'],$qdata['answer']));\n\t\t} catch (Throwable $t) {\n\t\t\t$res1 = 'caught';\n\t\t\tif ($myrights>10) {\n\t\t\t\techo '

    Caught error in evaluating a function in this question: ';\n\t\t\t\techo Sanitize::encodeStringForDisplay($t->getMessage());\n\t\t\t\techo '

    ';\n\t\t\t}\n\t\t}\n\n\n\t\tif ($res1===false) {\n\t\t\tif ($myrights>10) {\n\t\t\t\t$error = error_get_last();\n\t\t\t\techo '

    Caught error in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t\t} else {\n\t\t\t\techo '

    Something went wrong with this question. Tell your teacher.

    ';\n\t\t\t}\n\t\t} else {\n\t\t\t$error = error_get_last();\n\t\t\tif ($error && $error!=$preevalerror && $myrights>10) {\n\t\t\t\tif ($error['type']==$_ERROR) {\n\t\t\t\t\techo '

    Caught error in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t\t\t} else if ($error['type']==E_WARNING) {\n\t\t\t\t\techo '

    Caught warning in the question code: ',$error['message'], ' on line ', $error['line'] ,'

    ';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t$RND->srand($seed+2);\n\t$laarr = explode('##',$GLOBALS['lastanswers'][$qnidx]);\n\t$la = $laarr[count($laarr)-1];\n\tif ($la==\"ReGen\") {$la = '';}\n\tif ($clearla) {$la = '';}\n\tif (isset($requestclearla) && !isset($GLOBALS['questionscoreref'])) { $la = ''; $qcolors = array();}\n\n\t//$la = $GLOBALS['lastanswers'][$qnidx];\n\n\tif (isset($choices) && !isset($questions)) {\n\t\t$questions =& $choices;\n\t}\n\tif (isset($variable) && !isset($variables)) {\n\t\t$variables =& $variable;\n\t}\n\n\tif (isset($formatfeedbackon)) {\n\t\tunset($GLOBALS['noformatfeedback']);\n\t}\n\tif (isset($anstypes)) {\n\t\tif (!is_array($anstypes)) {\n\t\t\t$anstypes = explode(\",\",$anstypes);\n\t\t}\n\t\t$anstypes = array_map('trim', $anstypes);\n\t}\n\t//pack options\n\n $optionsPack = [];\n\tif (isset($ansprompt)) {$optionsPack['ansprompt'] = $ansprompt;}\n\tif (isset($displayformat)) {$optionsPack['displayformat'] = $displayformat;}\n\tif (isset($answerformat)) {$answerformat = str_replace(' ','',$answerformat); $optionsPack['answerformat'] = $answerformat;}\n\tif (isset($questions)) {$optionsPack['questions'] = $questions;}\n\tif (isset($answers)) {$optionsPack['answers'] = $answers;}\n\tif (isset($answer)) {$optionsPack['answer'] = $answer;}\n\tif (isset($questiontitle)) {$optionsPack['questiontitle'] = $questiontitle;}\n\tif (isset($answertitle)) {$optionsPack['answertitle'] = $answertitle;}\n\tif (isset($answersize)) {$optionsPack['answersize'] = $answersize;}\n\tif (isset($variables)) {$optionsPack['variables'] = $variables;}\n\tif (isset($strflags)) {$optionsPack['strflags'] = $strflags;}\n\tif (isset($domain)) {$optionsPack['domain'] = $domain;}\n\tif (isset($answerboxsize)) {$optionsPack['answerboxsize'] = $answerboxsize;}\n\tif (isset($hidepreview)) {$optionsPack['hidepreview'] = $hidepreview;}\n\tif (isset($matchlist)) {$optionsPack['matchlist'] = $matchlist;}\n\tif (isset($noshuffle)) {$optionsPack['noshuffle'] = $noshuffle;}\n\tif (isset($reqdecimals)) {$optionsPack['reqdecimals'] = $reqdecimals;}\n\tif (isset($reqsigfigs)) {$optionsPack['reqsigfigs'] = $reqsigfigs;}\n\tif (isset($grid)) {$optionsPack['grid'] = $grid;}\n\tif (isset($snaptogrid)) {$optionsPack['snaptogrid'] = $snaptogrid;}\n\tif (isset($background)) {$optionsPack['background'] = $background;}\n\tif (isset($scoremethod)) {$optionsPack['scoremethod'] = $scoremethod;}\n\n\tif (isset($GLOBALS['nocolormark'])) { //no colors\n\t\t$qcolors = array();\n\t}\n\t$GLOBALS['lastansweights'] = array();\n\tif ($qdata['qtype']==\"multipart\" || $qdata['qtype']=='conditional') {\n\t\tif (!isset($anstypes) && $GLOBALS['myrights']>10) {\n\t\t\techo 'Error in question: missing $anstypes for multipart or conditional question';\n\t\t\t$anstypes = array(\"number\");\n\t\t}\n\t\tif ($qdata['qtype']==\"multipart\") {\n\t\t\tif (isset($answeights)) {\n\t\t\t\tif (!is_array($answeights)) {\n\t\t\t\t\t$answeights = explode(\",\",$answeights);\n\t\t\t\t}\n\t\t\t\t$answeights = array_map('trim', $answeights);\n\t\t\t\t$localsum = array_sum($answeights);\n\t\t\t\tif ($localsum==0) {$localsum = 1;}\n\t\t\t\tforeach ($answeights as $kidx=>$vval) {\n\t\t\t\t\t$answeights[$kidx] = $vval/$localsum;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (count($anstypes)>1) {\n\t\t\t\t\tif (empty($qnpointval)) {$qnpointval=1;}\n\t\t\t\t\t$answeights = array_fill(0,count($anstypes)-1,round($qnpointval/count($anstypes),3));\n\t\t\t\t\t$answeights[] = $qnpointval-array_sum($answeights);\n\t\t\t\t\tforeach ($answeights as $kidx=>$vval) {\n\t\t\t\t\t\t$answeights[$kidx] = $vval/$qnpointval;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$answeights = array(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$GLOBALS['lastansweights'] = $answeights;\n\t\t}\n\t\t$laparts = explode(\"&\",$la);\n\n\t\tforeach ($anstypes as $kidx=>$anstype) {\n\t\t\t$qcol = ($qdata['qtype']==\"multipart\" && isset($qcolors[$kidx]))?(is_numeric($qcolors[$kidx])?rawscoretocolor(Sanitize::encodeStringForDisplay($qcolors[$kidx]),$answeights[$kidx]):Sanitize::encodeStringForDisplay($qcolors[$kidx])):'';\n\t\t\tlist($answerbox[$kidx],$entryTips[$kidx],$shanspt[$kidx],$previewloc[$kidx]) = makeanswerbox($anstype,$kidx,$laparts[$kidx] ?? '',$optionsPack,$qnidx+1,$qcol);\n\t\t}\n\t} else {\n\t\t$qcol = isset($qcolors[0])?(is_numeric($qcolors[0])?rawscoretocolor(Sanitize::encodeStringForDisplay($qcolors[0]),1):Sanitize::encodeStringForDisplay($qcolors[0])):'';\n\t\tlist($answerbox,$entryTips[0],$shanspt[0],$previewloc) = makeanswerbox(Sanitize::simpleString($qdata['qtype']),$qnidx,$la,$optionsPack,0,$qcol);\n\t}\n\tif ($qdata['qtype']=='conditional') {\n\t\t$qcol = isset($qcolors[0])?(is_numeric($qcolors[0])?rawscoretocolor(Sanitize::encodeStringForDisplay($qcolors[0]),1):Sanitize::encodeStringForDisplay($qcolors[0])):'';\n\t\tif ($qcol!='') {\n\t\t\tif (strpos($toevalqtxt, ''.$toevalqtxt.str_replace('\"','\\\\\"',getcolormark($qcol)).'
    ';\n\t\t\t} else {\n\t\t\t$toevalqtxt = '
    '.$toevalqtxt.str_replace('\"','\\\\\"',getcolormark($qcol)).'
    ';\n\t\t}\n\t\t}\n\t\tif (!isset($showanswer)) {\n\t\t\t$showanswer = _('Answers may vary');\n\t\t}\n\t}\n\n\tif ($returnqtxt) {\n\t\t//$toevalqtxt = preg_replace('/\\$answerbox(\\[\\d+\\])?/','',$toevalqtxt);\n\t}\n\n\n\t//create hintbuttons\n\tif (isset($hints) && is_array($hints) && count($hints)>0 && $showhints) {\n\t\t//$hintkeys = array_keys($hints);\n\t\t//$lastkey = array_pop($hintkeys);\n\t\t$lastkey = max(array_keys($hints));\n\t\tif ($qdata['qtype']==\"multipart\" && is_array($hints[$lastkey])) { //individual part hints\n\t\t\tforeach ($hints as $iidx=>$hintpart) {\n\t\t\t\tif (isset($scoreiscorrect) && $scoreiscorrect[$thisq][$iidx]==1) {continue;}\n\t\t\t\t$lastkey = max(array_keys($hintpart));\n\t\t\t\tif ($attemptn>$lastkey) {\n\t\t\t\t\t$usenum = $lastkey;\n\t\t\t\t} else {\n\t\t\t\t\t$usenum = $attemptn;\n\t\t\t\t}\n\t\t\t\tif ($hintpart[$usenum]!='') {\n\t\t\t\t\tif (strpos($hintpart[$usenum],'
    ')!==false) {\n\t\t\t\t\t\t$hintloc[$iidx] = $hintpart[$usenum];\n\t\t\t\t\t} else if (strpos($hintpart[$usenum],'button\"')!==false) {\n\t\t\t\t\t\t$hintloc[$iidx] = \"

    {$hintpart[$usenum]}

    \\n\";\n\t\t\t\t\t} else if (isset($hintlabel)) {\n\t\t\t\t\t\t$hintloc[$iidx] = \"

    $hintlabel {$hintpart[$usenum]}

    \\n\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$hintloc[$iidx] = \"

    \" . _('Hint:') . \" {$hintpart[$usenum]}

    \\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t} else if (!isset($scoreiscorrect) || $scoreiscorrect[$thisq]!=1) { //one hint for question\n\t\t\t//$lastkey = end(array_keys($hints));\n\n\t\t\tif ($attemptn>$lastkey) {\n\t\t\t\t$usenum = $lastkey;\n\t\t\t} else {\n\t\t\t\t$usenum = $attemptn;\n\t\t\t}\n\t\t\tif ($hints[$usenum]!='') {\n\t\t\t\tif (strpos($hints[$usenum],'
    ')!==false) {\n\t\t\t\t\t$hintloc = $hints[$usenum];\n\t\t\t\t} else if (strpos($hints[$usenum],'button\"')!==false) {\n\t\t\t\t\t$hintloc = \"

    {$hints[$usenum]}

    \\n\";\n\t\t\t\t} else if (isset($hintlabel)) {\n\t\t\t\t\t$hintloc = \"

    $hintlabel {$hints[$usenum]}

    \\n\";\n\t\t\t\t} else {\n\t\t\t\t\t$hintloc = \"

    \" . _('Hint:') . \" {$hints[$usenum]}

    \\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\tif (is_array($answerbox)) {\n\t\tforeach($answerbox as $iidx=>$abox) {\n\t\t\tif ($seqinactive) {\n\t\t\t\t$answerbox[$iidx] = str_replace('', $previewloc[$iidx], $answerbox[$iidx]);\n\t\t\t\t} else {\n\t\t\t\t\t$answerbox[$iidx] .= $previewloc[$iidx];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isset($hideanswerboxes) && $hideanswerboxes==true) {\n\t\t\t\t$answerbox[$iidx] = '';\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif ($seqinactive) {\n\t\t\t$answerbox = str_replace('', $previewloc, $answerbox);\n\t\t\t} else {\n\t\t\t\t$answerbox .= $previewloc;\n\t\t\t}\n\t\t}\n\t\tif (isset($hideanswerboxes) && $hideanswerboxes==true) {\n\t\t\t$answerbox = '';\n\t\t}\n\t}\n\n\tif ($doshowans && isset($showanswer) && !is_array($showanswer)) { //single showanswer defined\n\t\t$showanswerloc = (isset($showanswerstyle) && $showanswerstyle=='inline')?'':'
    ';\n\t\tif ($nosabutton) {\n\t\t\t$showanswerloc .= filter(_('Answer:') . \" $showanswer\\n\");\n\t\t} else {\n\t\t\t$showanswerloc .= \"\";\n\t\t\t$showanswerloc .= filter(\" $showanswer \\n\");\n\t\t}\n\t\t$showanswerloc .= (isset($showanswerstyle) && $showanswerstyle=='inline')?'':'
    ';\n\t} else if ($doshowans) {\n\t\t$showanswerloc = array();\n\t\tforeach($entryTips as $iidx=>$entryTip) {\n\t\t\t$showanswerloc[$iidx] = (isset($showanswerstyle) && $showanswerstyle=='inline')?'':'
    ';\n\t\t\tif ($doshowans && (!isset($showanswer) || (is_array($showanswer) && !isset($showanswer[$iidx]))) && $shanspt[$iidx]!=='') {\n\t\t\t\tif (strpos($shanspt[$iidx],'[AB')!==false) {\n\t\t\t\t\tforeach($shanspt as $subiidx=>$sarep) {\n\t\t\t\t\t\tif (strpos($shanspt[$iidx],'[AB'.$subiidx.']')!==false) {\n\t\t\t\t\t\t\t$shanspt[$iidx] = str_replace('[AB'.$subiidx.']', $sarep, $shanspt[$iidx]);\n\t\t\t\t\t\t\t$shanspt[$subiidx]='';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($nosabutton) {\n\t\t\t\t\t$showanswerloc[$iidx] .= \"\".filter(_('Answer:') . \" {$shanspt[$iidx]}\\n\");\n\t\t\t\t} else {\n\t\t\t\t\t$showanswerloc[$iidx] .= \"\"; //AMprocessNode(document.getElementById(\\\"ans$qnidx-$iidx\\\"));'>\";\n\t\t\t\t\t// $shanspt can contain HTML.\n\t\t\t\t\t$showanswerloc[$iidx] .= filter(\" {$shanspt[$iidx]}\\n\");\n\t\t\t\t}\n\t\t\t} else if ($doshowans && isset($showanswer) && is_array($showanswer)) { //use part specific showanswer\n\t\t\t\tif (isset($showanswer[$iidx])) {\n\t\t\t\t\tif ($nosabutton) {\n\t\t\t\t\t\t$showanswerloc[$iidx] .= \"\".filter(_('Answer:') . \" {$showanswer[$iidx]}\\n\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$showanswerloc[$iidx] .= \"\";// AMprocessNode(document.getElementById(\\\"ans$qnidx-$iidx\\\"));'>\";\n\t\t\t\t\t\t$showanswerloc[$iidx] .= filter(\" {$showanswer[$iidx]}\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$showanswerloc[$iidx] .= (isset($showanswerstyle) && $showanswerstyle=='inline')?'':'
    ';\n\t\t}\n\t\tif (!is_array($answerbox) && count($showanswerloc)==1) { //not a multipart question\n\t\t\t$showanswerloc = str_replace($qnidx.'-0\"',$qnidx.'\"', $showanswerloc[0]);\n\t\t}\n\t}\n\n\t//echo $toevalqtext;\n\ttry {\n\t\teval(\"\\$evaledqtext = \\\"$toevalqtxt\\\";\");\n\t\teval(\"\\$evaledsoln = \\\"$toevalsoln\\\";\");\n\t} catch (Throwable $t) {\n\t\tif ($myrights>10) {\n\t\t\techo '

    Caught error in evaluating the question text or solution text in this question: ';\n\t\t\techo Sanitize::encodeStringForDisplay($t->getMessage());\n\t\t\techo '

    ';\n\t\t}\n\t}\n\n\t\n\n\tif (strpos($evaledqtext,'[AB')!==false) {\n\t\tif (is_array($answerbox)) {\n\t\t\tforeach($answerbox as $iidx=>$abox) {\n\t\t\t\tif (strpos($evaledqtext,'[AB'.$iidx.']')!==false) {\n\t\t\t\t\t$evaledqtext = str_replace('[AB'.$iidx.']', $abox, $evaledqtext);\n\t\t\t\t\t$toevalqtxt .= '$answerbox['.$iidx.']'; //to prevent autoadd\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$evaledqtext = str_replace('[AB]', $answerbox, $evaledqtext);\n\t\t\t$toevalqtxt .= '$answerbox';\n\t\t}\n\t}\n\tif (strpos($evaledqtext,'[SAB')!==false) {\n\t\tif (!isset($showanswerloc)) {\n\t\t\t$evaledqtext = preg_replace('/\\[SAB\\d*\\]/','',$evaledqtext);\n\t\t} else if (is_array($showanswerloc)) {\n\t\t\tforeach($showanswerloc as $iidx=>$saloc) {\n\t\t\t\tif (strpos($evaledqtext,'[SAB'.$iidx.']')!==false) {\n\t\t\t\t\t$evaledqtext = str_replace('[SAB'.$iidx.']', $saloc, $evaledqtext);\n\t\t\t\t\t$toevalqtxt .= '$showanswerloc['.$iidx.']'; //to prevent autoadd\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$evaledqtext = str_replace('[SAB]', $showanswerloc, $evaledqtext);\n\t\t\t$toevalqtxt .= '$showanswerloc';\n\t\t}\n\t}\n if ($returnqtxt===2) {\n\t\treturn '
    '.$evaledsoln.'
    ';\n\t} else if ($returnqtxt===3) {\n\t\treturn '
    '.$evaledqtext.'
    '.$evaledsoln.'
    ';\n\t}\n\tif (($qdata['solutionopts']&1)==0) {\n\t\t$evaledsoln = ''._('This solution is for a similar problem, not your specific version').'
    '.$evaledsoln;\n\t}\n\tif ($returnqtxt) {\n\t\t$returntxt = $evaledqtext;\n\t} else if ($seqinactive) {\n\t\techo \"
    \";\n\t\techo filter($evaledqtext);\n\t} else {\n\t\techo \"
    \\n\";\n\t\techo filter($evaledqtext);\n\t\techo \"
    \\n\";\n\t}\n\n\tif (strpos($toevalqtxt,'$answerbox')===false) {\n\t\tif (is_array($answerbox)) {\n\t\t\tforeach($answerbox as $iidx=>$abox) {\n\t\t\t\tif ($seqinactive) {\n\t\t\t\t\t$answerbox[$iidx] = str_replace('$abox

    \";\n\t\t\t\t} else {\n\t\t\t\t\techo filter(\"
    $abox
    \\n\");\n\t\t\t\t\techo \"
     
    \\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t} else { //one question only\n\t\t\tif ($seqinactive) {\n\t\t\t\t$answerbox = str_replace('$answerbox

    \";\n\t\t\t} else {\n\t\t\t\techo filter(\"
    $answerbox
    \\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif ($returnqtxt) {\n\t\treturn $returntxt;\n\t}\n\tif (isset($helptext) && $showhints) {\n\t\techo '

    '.filter($helptext).'

    ';\n\t}\n\tif ($showhints && ($qdata['extref']!='' || (($qdata['solutionopts']&2)==2 && $qdata['solution']!=''))) {\n\t\techo '

    ', _('Get help: ');\n\t\t$extrefwidth = isset($GLOBALS['CFG']['GEN']['extrefsize'])?$GLOBALS['CFG']['GEN']['extrefsize'][0]:700;\n\t\t$extrefheight = isset($GLOBALS['CFG']['GEN']['extrefsize'])?$GLOBALS['CFG']['GEN']['extrefsize'][1]:500;\n\t\t$vidextrefwidth = isset($GLOBALS['CFG']['GEN']['vidextrefsize'])?$GLOBALS['CFG']['GEN']['vidextrefsize'][0]:873;\n\t\t$vidextrefheight = isset($GLOBALS['CFG']['GEN']['vidextrefsize'])?$GLOBALS['CFG']['GEN']['vidextrefsize'][1]:500;\n\t\t$qref = '';\n if ($qdata['extref']!= '') {\n\t\t\t$extref = explode('~~',$qdata['extref']);\n\n\t\t\tif (isset($GLOBALS['questions']) && (!isset($_SESSION['isteacher']) || $_SESSION['isteacher']==false) && !isset($_SESSION['stuview'])) {\n\t\t\t\t$qref = $GLOBALS['questions'][$qnidx].'-'.($qnidx+1);\n\t\t\t} \n\t\t\tfor ($i=0;$i

    ';\n\t}\n\n\techo \"
    \";\n\tforeach($entryTips as $iidx=>$entryTip) {\n\t\tif ((!isset($hidetips) || (is_array($hidetips) && !isset($hidetips[$iidx])))&& !$seqinactive && $showtips>0) {\n\t\t\techo \"

    \", _('Box'), \" \".($iidx+1).\": \".filter($entryTip).\"

    \";\n\t\t}\n\t\tif ($doshowans && strpos($toevalqtxt,'$showanswerloc')===false && is_array($showanswerloc) && isset($showanswerloc[$iidx])) {\n\t\t\t// $showanswerloc contains HTML.\n\t\t\techo '
    '.$showanswerloc[$iidx].'
    ';\n\t\t}\n\t\t/*if ($doshowans && (!isset($showanswer) || (is_array($showanswer) && !isset($showanswer[$iidx]))) && $shanspt[$iidx]!=='') {\n\t\t\tif ($nosabutton) {\n\t\t\t\techo filter(\"
    \" . _('Answer:') . \" {$shanspt[$iidx]}
    \\n\");\n\t\t\t} else {\n\t\t\t\techo \"
    \"; //AMprocessNode(document.getElementById(\\\"ans$qnidx-$iidx\\\"));'>\";\n\t\t\t\techo filter(\" {$shanspt[$iidx]}
    \\n\");\n\t\t\t}\n\t\t} else if ($doshowans && isset($showanswer) && is_array($showanswer)) { //use part specific showanswer\n\t\t\tif (isset($showanswer[$iidx])) {\n\t\t\t\tif ($nosabutton) {\n\t\t\t\t\techo filter(\"
    \" . _('Answer:') . \" {$showanswer[$iidx]}
    \\n\");\n\t\t\t\t} else {\n\t\t\t\t\techo \"
    \";// AMprocessNode(document.getElementById(\\\"ans$qnidx-$iidx\\\"));'>\";\n\t\t\t\t\techo filter(\" {$showanswer[$iidx]}
    \\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\t}\n\techo \"
    \\n\";\n\n\tif ($doshowans && !is_array($showanswerloc) && strpos($toevalqtxt,'$showanswerloc')===false) { //single showanswer defined\n\t\t/*if ($nosabutton) {\n\t\t\techo filter(\"
    \" . _('Answer:') . \" $showanswer
    \\n\");\n\t\t} else {\n\t\t\techo \"
    \";\n\t\t\techo filter(\" $showanswer
    \\n\");\n\t\t}*/\n\t\techo '
    '.$showanswerloc.'
    ';\n\n\t}\n\tif ($doshowans && ($qdata['solutionopts']&4)==4 && $qdata['solution']!='') {\n\t\tif ($nosabutton) {\n\t\t\techo filter(\"

    \" . _('Detailed Solution').'

    '. $evaledsoln .'
    ');\n\t\t} else {\n\t\t\techo \"
    \";\n\t\t\techo filter(\"
    $evaledsoln
    \\n\");\n\t\t}\n\t}\n\n\techo \"
    \\n\";\n\t//echo 'time: '.(microtime(true) - $starttime);\n\tif ($qdata['qtype']==\"multipart\" ) {\n\t\treturn $anstypes;\n\t} else {\n\t\treturn array(Sanitize::simpleString($qdata['qtype']));\n\t}\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function addNewDocument(\n $name,\n $type,\n $tmp_name,\n $error,\n $size,\n $owner = '',\n $patient_id_or_simple_directory = \"00\",\n $category_id = '1',\n $higher_level_path = '',\n $path_depth = '1',\n $skip_acl_check = false\n) {\n\n if (empty($owner)) {\n $owner = $_SESSION['authUserID'];\n }\n\n // Build the $_FILES array\n $TEMP_FILES = array();\n $TEMP_FILES['file']['name'][0] = $name;\n $TEMP_FILES['file']['type'][0] = $type;\n $TEMP_FILES['file']['tmp_name'][0] = $tmp_name;\n $TEMP_FILES['file']['error'][0] = $error;\n $TEMP_FILES['file']['size'][0] = $size;\n $_FILES = $TEMP_FILES;\n\n // Build the parameters\n $_GET['higher_level_path'] = $higher_level_path;\n $_GET['patient_id'] = $patient_id_or_simple_directory;\n $_POST['destination'] = '';\n $_POST['submit'] = 'Upload';\n $_POST['path_depth'] = $path_depth;\n $_POST['patient_id'] = (is_numeric($patient_id_or_simple_directory) && $patient_id_or_simple_directory > 0) ? $patient_id_or_simple_directory : \"00\";\n $_POST['category_id'] = $category_id;\n $_POST['process'] = 'true';\n\n // Add the Document and return the newly added document id\n $cd = new C_Document();\n $cd->manual_set_owner = $owner;\n if ($skip_acl_check) {\n $cd->skipAclCheck();\n }\n $cd->upload_action_process();\n $v = $cd->getTemplateVars(\"file\");\n if (!isset($v) || !$v) {\n return false;\n }\n\n return array(\"doc_id\" => $v[0]->id, \"url\" => $v[0]->url, \"name\" => $v[0]->name);\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')\n{\n\t// Output a cell\n\t$k = $this->k;\n\tif($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak())\n\t{\n\t\t// Automatic page break\n\t\t$x = $this->x;\n\t\t$ws = $this->ws;\n\t\tif($ws>0)\n\t\t{\n\t\t\t$this->ws = 0;\n\t\t\t$this->_out('0 Tw');\n\t\t}\n\t\t$this->AddPage($this->CurOrientation,$this->CurPageSize,$this->CurRotation);\n\t\t$this->x = $x;\n\t\tif($ws>0)\n\t\t{\n\t\t\t$this->ws = $ws;\n\t\t\t$this->_out(sprintf('%.3F Tw',$ws*$k));\n\t\t}\n\t}\n\tif($w==0)\n\t\t$w = $this->w-$this->rMargin-$this->x;\n\t$s = '';\n\tif($fill || $border==1)\n\t{\n\t\tif($fill)\n\t\t\t$op = ($border==1) ? 'B' : 'f';\n\t\telse\n\t\t\t$op = 'S';\n\t\t$s = sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);\n\t}\n\tif(is_string($border))\n\t{\n\t\t$x = $this->x;\n\t\t$y = $this->y;\n\t\tif(strpos($border,'L')!==false)\n\t\t\t$s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);\n\t\tif(strpos($border,'T')!==false)\n\t\t\t$s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);\n\t\tif(strpos($border,'R')!==false)\n\t\t\t$s .= sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);\n\t\tif(strpos($border,'B')!==false)\n\t\t\t$s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);\n\t}\n\tif($txt!=='')\n\t{\n\t\tif(!isset($this->CurrentFont))\n\t\t\t$this->Error('No font has been set');\n\t\tif($align=='R')\n\t\t\t$dx = $w-$this->cMargin-$this->GetStringWidth($txt);\n\t\telseif($align=='C')\n\t\t\t$dx = ($w-$this->GetStringWidth($txt))/2;\n\t\telse\n\t\t\t$dx = $this->cMargin;\n\t\tif($this->ColorFlag)\n\t\t\t$s .= 'q '.$this->TextColor.' ';\n\t\t$s .= sprintf('BT %.2F %.2F Td (%s) Tj ET',($this->x+$dx)*$k,($this->h-($this->y+.5*$h+.3*$this->FontSize))*$k,$this->_escape($txt));\n\t\tif($this->underline)\n\t\t\t$s .= ' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);\n\t\tif($this->ColorFlag)\n\t\t\t$s .= ' Q';\n\t\tif($link)\n\t\t\t$this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$this->GetStringWidth($txt),$this->FontSize,$link);\n\t}\n\tif($s)\n\t\t$this->_out($s);\n\t$this->lasth = $h;\n\tif($ln>0)\n\t{\n\t\t// Go to next line\n\t\t$this->y += $h;\n\t\tif($ln==1)\n\t\t\t$this->x = $this->lMargin;\n\t}\n\telse\n\t\t$this->x += $w;\n}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function genX12837P(\n $pid,\n $encounter,\n $x12_partner,\n &$log,\n $encounter_claim = false,\n $SEFLAG = false,\n $HLcount = 0,\n &$edicount = 0,\n &$patSegmentCount = 0\n ) {\n $today = time();\n $out = '';\n $claim = new Claim($pid, $encounter, $x12_partner);\n\n $log .= $claim->patientFirstName() . ' ' .\n $claim->patientMiddleName() . ' ' .\n $claim->patientLastName() . ' on ' .\n date('Y-m-d H:i', $today) . \".\\n\";\n\n $out .= \"ISA\" .\n \"*\" . $claim->x12gsisa01() .\n \"*\" . $claim->x12gsisa02() .\n \"*\" . $claim->x12gsisa03() .\n \"*\" . $claim->x12gsisa04() .\n \"*\" . $claim->x12gsisa05() .\n \"*\" . $claim->x12_sender_id() .\n \"*\" . $claim->x12gsisa07() .\n \"*\" . $claim->x12gsreceiverid() .\n \"*\" . \"030911\" . // dummy data replace by billing_process.php\n \"*\" . \"1630\" . // ditto\n \"*\" . \"^\" .\n \"*\" . \"00501\" .\n \"*\" . \"000000001\" .\n \"*\" . $claim->x12gsisa14() .\n \"*\" . $claim->x12gsisa15() .\n \"*:\" .\n \"~\\n\";\n\n $out .= \"GS\" .\n \"*\" . \"HC\" .\n \"*\" . $claim->x12gsgs02() .\n \"*\" . trim($claim->x12gs03()) .\n \"*\" . date('Ymd', $today) .\n \"*\" . date('Hi', $today) .\n \"*\" . \"1\" . // TODO add a tracking number\n \"*\" . \"X\" .\n \"*\" . $claim->x12gsversionstring() .\n \"~\\n\";\n\n // one transaction set (ST) based on direct send to insurance companies global\n if (\n (\n $HLcount == 1 // HLcount passed in to function by GeneratorX12Direct class\n && !empty($GLOBALS['gen_x12_based_on_ins_co'])\n )\n || (\n empty($GLOBALS['gen_x12_based_on_ins_co'])\n )\n ) {\n ++$edicount;\n $out .= \"ST\" .\n \"*\" . \"837\" .\n \"*\" . \"0021\" .\n \"*\" . $claim->x12gsversionstring() .\n \"~\\n\";\n\n ++$edicount;\n $out .= \"BHT\" .\n \"*\" . \"0019\" . // 0019 is required here\n \"*\" . \"00\" . // 00 = original transmission\n \"*\" . \"0123\" . // reference identification\n \"*\" . date('Ymd', $today) . // transaction creation date\n \"*\" . date('Hi', $today) . // transaction creation time\n \"*\" . ($encounter_claim ? \"RP\" : \"CH\") . // RP = reporting, CH = chargeable\n \"~\\n\";\n\n ++$edicount;\n // check entity type for NM*102 1 == person, 2 == non-person entity\n // SY = ssn so is 1 or person but we also check for a 3rd party submitter\n if ($claim->federalIdType() == \"SY\") {\n $out .= \"NM1\" . // Loop 1000A Submitter\n \"*\" . \"41\" .\n \"*\";\n // check for 3rd party submitter name entered in practice settings x12 partner\n if ($claim->x12_submitter_name()) {\n // non-person entity\n $out .= \"2\" .\n \"*\" . $claim->x12_submitter_name() .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"46\" .\n \"*\" . $claim->x12_sender_id();\n // use provider name since using ssn as tax id\n // insurance companies may be deprecating use of ssn 7-10-21\n } else {\n $firstName = $claim->providerFirstName();\n $lastName = $claim->providerLastName();\n $middleName = $claim->providerMiddleName();\n $suffixName = $claim->providerSuffixName();\n $out .= \"1\" .\n \"*\" . $lastName .\n \"*\" . $firstName .\n \"*\" . $middleName .\n \"*\" . // Name Prefix not used\n \"*\" . $suffixName .\n \"*\" . \"46\" .\n \"*\" . $claim->billingFacilityETIN();\n }\n // non-person entity, use 2\n } else {\n $out .= \"NM1\" .\n \"*\" . \"41\" .\n \"*\" . \"2\" . \"*\" ;\n // check for 3rd party\n if ($claim->x12_submitter_name()) {\n $out .= $claim->x12_submitter_name() .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"46\" .\n \"*\" . $claim->billingIdCode();\n // else use provider's group name\n } else {\n $billingFacilityName = substr($claim->billingFacilityName(), 0, 60);\n if ($billingFacilityName == '') {\n $log .= \"*** billing facility name in 1000A loop is empty\\n\";\n }\n $out .= $billingFacilityName .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"46\" .\n \"*\" . $claim->billingFacilityETIN();\n }\n }\n // close the NM1 segment\n $out .= \"~\\n\";\n\n ++$edicount;\n\n $billing_contact_name = $claim->billingContactName();\n if (empty($billing_contact_name)) {\n $log .= \"*** billing contact name in 1000A loop is empty.\\n\";\n }\n $out .= \"PER\" . // Loop 1000A, Submitter EDI contact information\n \"*\" . \"IC\" .\n \"*\" . $claim->billingContactName();\n $out .= !empty($claim->billingContactPhone()) ?\n \"*\" . \"TE\" . \"*\" . $claim->billingContactPhone() : \"*\";\n $out .= !empty($claim->billingContactEmail()) ?\n \"*\" . \"EM\" . \"*\" . $claim->billingContactEmail() : \"*\";\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"NM1\" . // Loop 1000B Receiver\n \"*\" . \"40\" .\n \"*\" . \"2\" .\n \"*\" . $claim->clearingHouseName() .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"46\" .\n \"*\" . $claim->clearingHouseETIN() .\n \"~\\n\";\n\n ++$edicount;\n\n $out .= \"HL\" . // Loop 2000A Billing/Pay-To Provider HL Loop\n \"*\" . $HLcount .\n \"*\" .\n \"*\" . \"20\" .\n \"*\" . \"1\" . // 1 indicates there are child segments\n \"~\\n\";\n\n // Situational PRV segment for provider taxonomy.\n if ($claim->facilityTaxonomy()) {\n ++$edicount;\n $out .= \"PRV\" .\n \"*\" . \"BI\" .\n \"*\" . \"PXC\" .\n \"*\" . $claim->facilityTaxonomy() .\n \"~\\n\";\n }\n\n // Situational CUR segment (foreign currency information) omitted here.\n ++$edicount;\n if ($claim->federalIdType() == \"SY\") { // check for entity type like in 1000A\n $firstName = $claim->providerFirstName();\n $lastName = $claim->providerLastName();\n $middleName = $claim->providerMiddleName();\n $out .= \"NM1\" .\n \"*\" . \"85\" .\n \"*\" . \"1\" .\n \"*\" . $lastName .\n \"*\" . $firstName .\n \"*\" . $middleName .\n \"*\" . // Name Prefix not used\n \"*\";\n } else {\n $billingFacilityName = substr($claim->billingFacilityName(), 0, 60);\n if ($billingFacilityName == '') {\n $log .= \"*** billing facility name in 2010A loop is empty.\\n\";\n }\n $out .= \"NM1\" . // Loop 2010AA Billing Provider\n \"*\" . \"85\" .\n \"*\" . \"2\" .\n \"*\" . $billingFacilityName .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\";\n }\n if ($claim->billingFacilityNPI()) {\n $out .= \"*XX*\" . $claim->billingFacilityNPI();\n } else {\n $log .= \"*** Billing facility has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->billingFacilityStreet()) {\n $out .= $claim->billingFacilityStreet();\n } else {\n $log .= \"*** Billing facility has no street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->billingFacilityCity()) {\n $out .= $claim->billingFacilityCity();\n } else {\n $log .= \"*** Billing facility has no city.\\n\";\n }\n $out .= \"*\";\n if ($claim->billingFacilityState()) {\n $out .= $claim->billingFacilityState();\n } else {\n $log .= \"*** Billing facility has no state.\\n\";\n }\n $out .= \"*\";\n // X12 requires a 9 digit zip in loop 2010AA but we output it anyways\n if (strlen($claim->billingFacilityZip()) != 9) {\n $log .= \"*** Billing facility zip is not 9 digits.\\n\";\n }\n $out .= $claim->billingFacilityZip();\n $out .= \"~\\n\";\n\n if ($claim->billingFacilityNPI() && $claim->billingFacilityETIN()) {\n ++$edicount;\n $out .= \"REF\";\n if ($claim->federalIdType()) {\n $out .= \"*\" . $claim->federalIdType();\n } else {\n $out .= \"*EI\"; // For dealing with the situation before adding TaxId type In facility.\n }\n $out .= \"*\" . $claim->billingFacilityETIN() . \"~\\n\";\n } else {\n $log .= \"*** No billing facility NPI and/or ETIN.\\n\";\n }\n if ($claim->providerNumberType() && $claim->providerNumber() && !$claim->billingFacilityNPI()) {\n ++$edicount;\n $out .= \"REF\" .\n \"*\" . $claim->providerNumberType() .\n \"*\" . $claim->providerNumber() .\n \"~\\n\";\n } elseif ($claim->providerNumber() && !$claim->providerNumberType()) {\n $log .= \"*** Payer-specific provider insurance number is present but has no type assigned.\\n\";\n }\n\n // Situational PER*1C segment omitted.\n\n // Pay-To Address defaults to billing provider and is no longer required in 5010 but may be useful\n if ($claim->pay_to_provider != '') {\n ++$edicount;\n $billingFacilityName = substr($claim->billingFacilityName(), 0, 60);\n $out .= \"NM1\" . // Loop 2010AB Pay-To Provider\n \"*\" . \"87\" .\n \"*\" . \"2\" .\n \"*\" . $billingFacilityName .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\";\n if ($claim->billingFacilityNPI()) {\n $out .= \"*XX*\" . $claim->billingFacilityNPI();\n } else {\n $log .= \"*** Pay to provider has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->billingFacilityStreet()) {\n $out .= $claim->billingFacilityStreet();\n } else {\n $log .= \"*** Pay to provider has no street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->billingFacilityCity()) {\n $out .= $claim->billingFacilityCity();\n } else {\n $log .= \"*** Pay to provider has no city.\\n\";\n }\n $out .= \"*\";\n if ($claim->billingFacilityState()) {\n $out .= $claim->billingFacilityState();\n } else {\n $log .= \"*** Pay to provider has no state.\\n\";\n }\n $out .= \"*\";\n // X12 requires a 9 digit zip but we output it anyways\n if (strlen($claim->billingFacilityZip()) != 9) {\n $log .= \"*** Pay to provider zip is not 9 digits.\\n\";\n }\n $out .= $claim->billingFacilityZip();\n $out .= \"~\\n\";\n }\n\n // Loop 2010AC Pay-To Plan Name omitted. Includes:\n // NM1*PE, N3, N4, REF*2U, REF*EI\n }\n\n if (!empty($GLOBALS['gen_x12_based_on_ins_co'])) {\n $HLcount += $patSegmentCount;\n }\n\n $HLcount++;\n\n $PatientHL = $claim->isSelfOfInsured() ? 0 : 1;\n $HLSubscriber = $HLcount++;\n\n ++$edicount;\n\n // replaced $HLBillingPayToProvider with 1 until it's supported in the generators\n $out .= \"HL\" . // Loop 2000B Subscriber HL Loop\n \"*\" . $HLSubscriber .\n \"*\" . \"1\" .\n \"*\" . \"22\" .\n \"*\" . $PatientHL .\n \"~\\n\";\n\n if (!$claim->payerSequence()) {\n $log .= \"*** Error: Insurance information is missing!\\n\";\n }\n\n ++$edicount;\n $out .= \"SBR\" . // Subscriber Information\n \"*\" . $claim->payerSequence() .\n \"*\" . ($claim->isSelfOfInsured() ? '18' : '') .\n \"*\" . $claim->groupNumber() .\n \"*\" . ($claim->groupNumber() ? '' : $claim->groupName()) . // if groupNumber no groupName\n \"*\" . $claim->insuredTypeCode() . // applies for secondary medicare\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . $claim->claimType() .\n \"~\\n\";\n\n // Segment PAT omitted.\n\n ++$edicount;\n $out .= \"NM1\" . // Loop 2010BA Subscriber\n \"*\" . \"IL\" .\n \"*\" . \"1\"; // 1 = person, 2 = non-person\n if ($claim->insuredLastName()) {\n $out .= \"*\" .\n $claim->insuredLastName();\n } else {\n $log .= \"*** Missing insured last name.\\n\";\n }\n $out .= \"*\";\n if ($claim->insuredFirstName()) {\n $out .= $claim->insuredFirstName();\n } else {\n $log .= \"*** Missing insured first name.\\n\";\n }\n $out .= \"*\" .\n $claim->insuredMiddleName() .\n \"*\" .\n \"*\" . // Name Suffix not used\n \"*\" . \"MI\" .\n // \"MI\" = Member Identification Number\n // \"II\" = Standard Unique Health Identifier, \"Required if the\n // HIPAA Individual Patient Identifier is mandated use.\"\n // Here we presume that is not true yet.\n \"*\";\n if ($claim->policyNumber()) {\n $out .= $claim->policyNumber();\n } else {\n $log .= \"*** Missing policy number.\\n\";\n }\n $out .= \"~\\n\";\n\n // For 5010, further subscriber info is sent only if they are the patient.\n if ($claim->isSelfOfInsured()) {\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->insuredStreet()) {\n $out .= $claim->insuredStreet();\n } else {\n $log .= \"*** Missing insured street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->insuredCity()) {\n $out .= $claim->insuredCity();\n } else {\n $log .= \"*** Missing insured city.\\n\";\n }\n $out .= \"*\";\n if ($claim->insuredState()) {\n $out .= $claim->insuredState();\n } else {\n $log .= \"*** Missing insured state.\\n\";\n }\n $out .= \"*\";\n if (\n !(\n (strlen($claim->x12Zip($claim->insuredZip())) == 5)\n || (strlen($claim->x12Zip($claim->insuredZip())) == 9)\n )\n ) {\n $log .= \"*** Insured zip is not 5 or 9 digits.\\n\";\n }\n $out .= $claim->x12Zip($claim->insuredZip());\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"DMG\" .\n \"*\" .\n \"D8\" .\n \"*\";\n if ($claim->insuredDOB()) {\n $out .= $claim->insuredDOB();\n } else {\n $log .= \"*** Missing insured DOB.\\n\";\n }\n $out .= \"*\";\n if ($claim->insuredSex()) {\n $out .= $claim->insuredSex();\n } else {\n $log .= \"*** Missing insured sex.\\n\";\n }\n $out .= \"~\\n\";\n }\n\n // Segment REF*SY (Subscriber Secondary Identification) omitted.\n // Segment REF*Y4 (Property and Casualty Claim Number) omitted.\n // Segment PER*IC (Property and Casualty Subscriber Contact Information) omitted.\n\n ++$edicount;\n $payerName = substr($claim->payerName(), 0, 60);\n $out .= \"NM1\" . // Loop 2010BB Payer\n \"*\" . \"PR\" .\n \"*\" . \"2\" .\n \"*\";\n if ($payerName) {\n $out .= $payerName;\n } else {\n $log .= \"*** Missing payer name.\\n\";\n }\n $out .= \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"PI\" .\n \"*\" . ($encounter_claim ? $claim->payerAltID() : $claim->payerID());\n if (!$claim->payerID()) {\n $log .= \"*** Payer ID is missing for payer '\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->payerStreet()) {\n $out .= $claim->payerStreet();\n } else {\n $log .= \"*** Missing payer street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->payerCity()) {\n $out .= $claim->payerCity();\n } else {\n $log .= \"*** Missing payer city.\\n\";\n }\n $out .= \"*\";\n if ($claim->payerState()) {\n $out .= $claim->payerState();\n } else {\n $log .= \"*** Missing payer state.\\n\";\n }\n $out .= \"*\";\n if (\n !(\n (strlen($claim->payerZip()) == 5)\n || (strlen($claim->payerZip()) == 9)\n )\n ) {\n $log .= \"*** Payer zip is not 5 or 9 digits.\\n\";\n }\n\n $out .= $claim->x12Zip($claim->payerZip());\n $out .= \"~\\n\";\n\n // Segment REF (Payer Secondary Identification) omitted.\n // Segment REF (Billing Provider Secondary Identification) omitted.\n\n if (!$claim->isSelfOfInsured()) {\n ++$edicount;\n $out .= \"HL\" . // Loop 2000C Patient Information\n \"*\" . $HLcount .\n \"*\" . $HLSubscriber .\n \"*\" . \"23\" .\n \"*\" . \"0\" .\n \"~\\n\";\n\n $HLcount++;\n ++$edicount;\n $out .= \"PAT\" .\n \"*\" . $claim->insuredRelationship() .\n \"~\\n\";\n\n ++$edicount;\n $out .= \"NM1\" . // Loop 2010CA Patient\n \"*\" . \"QC\" .\n \"*\" . \"1\" .\n \"*\";\n if ($claim->patientLastName()) {\n $out .= $claim->patientLastName();\n } else {\n $log .= \"*** Missing patient last name.\\n\";\n }\n $out .= \"*\";\n if ($claim->patientFirstName()) {\n $out .= $claim->patientFirstName();\n } else {\n $log .= \"*** Missing patient first name.\\n\";\n }\n if ($claim->patientMiddleName() !== '') {\n $out .= \"*\" . $claim->patientMiddleName();\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->patientStreet()) {\n $out .= $claim->patientStreet();\n } else {\n $log .= \"*** Missing patient street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->patientCity()) {\n $out .= $claim->patientCity();\n } else {\n $log .= \"*** Missing patient city.\\n\";\n }\n $out .= \"*\";\n if ($claim->patientState()) {\n $out .= $claim->patientState();\n } else {\n $log .= \"*** Missing patient state.\\n\";\n }\n $out .= \"*\";\n if (\n (strlen($claim->patientZip()) == 5)\n || (strlen($claim->patientZip()) == 9)\n ) {\n $out .= $claim->patientZip();\n } else {\n $log .= \"*** Patient zip is not 5 or 9 digits.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"DMG\" .\n \"*\" . \"D8\" .\n \"*\";\n if ($claim->patientDOB()) {\n $out .= $claim->patientDOB();\n } else {\n $log .= \"*** Missing patient DOB.\\n\";\n }\n $out .= \"*\";\n if ($claim->patientSex()) {\n $out .= $claim->patientSex();\n } else {\n $log .= \"*** Missing patient sex.\\n\";\n }\n $out .= \"~\\n\";\n\n // Segment REF*Y4 (Property and Casualty Claim Number) omitted.\n // Segment REF (Property and Casualty Patient Identifier) omitted.\n // Segment PER (Property and Casualty Patient Contact Information) omitted.\n } // end of patient different from insured\n\n $proccount = $claim->procCount();\n $clm_total_charges = 0;\n for ($prockey = 0; $prockey < $proccount; ++$prockey) {\n $clm_total_charges += floatval($claim->cptCharges($prockey));\n }\n if (!$clm_total_charges) {\n $log .= \"*** This claim has no charges!\\n\";\n }\n\n ++$edicount;\n $out .= \"CLM\" . // Loop 2300 Claim\n \"*\" . $pid . \"-\" . $encounter .\n \"*\" . sprintf(\"%.2f\", $clm_total_charges) .\n \"*\" .\n \"*\" .\n \"*\" . sprintf('%02d', $claim->facilityPOS()) . \":\" . \"B\" . \":\" . $claim->frequencyTypeCode() .\n \"*\" . \"Y\" .\n \"*\" . ($claim->billingFacilityAssignment() ? 'A' : 'C') .\n \"*\" . ($claim->billingFacilityAssignment() ? 'Y' : 'N') .\n \"*\" . \"Y\" . \"*\" . \"P\"; // added patient signature source code CLM10\n if ($claim->isRelatedEmployment()) {\n $out .= \"*\" . \"EM\";\n }\n $out .= \"~\\n\";\n\n // above is for historical use of encounter onset date, now in misc_billing_options\n // Segment DTP*431 (Onset of Current Symptoms or Illness)\n // Segment DTP*484 (Last Menstrual Period Date)\n\n if (\n $claim->onsetDate()\n && $claim->onsetDate() !== $claim->serviceDate()\n && $claim->onsetDateValid()\n ) {\n ++$edicount;\n $out .= \"DTP\" . // Date of Onset\n \"*\" . \"431\" .\n \"*\" . \"D8\" .\n \"*\" . $claim->onsetDate() .\n \"~\\n\";\n } elseif (\n $claim->miscOnsetDate()\n && $claim->miscOnsetDate() !== $claim->serviceDate()\n && $claim->box14Qualifier()\n && $claim->miscOnsetDateValid()\n ) {\n ++$edicount;\n $out .= \"DTP\" .\n \"*\" . $claim->box14Qualifier() .\n \"*\" . \"D8\" .\n \"*\" . $claim->miscOnsetDate() .\n \"~\\n\";\n }\n\n // Segment DTP*304 (Last Seen Date)\n // Segment DTP*453 (Acute Manifestation Date)\n // Segment DTP*439 (Accident Date)\n // Segment DTP*455 (Last X-Ray Date)\n // Segment DTP*471 (Hearing and Vision Prescription Date)\n // Segment DTP*314 (Disability) omitted.\n // Segment DTP*360 (Initial Disability Period Start) omitted.\n // Segment DTP*361 (Initial Disability Period End) omitted.\n // Segment DTP*297 (Last Worked Date)\n // Segment DTP*296 (Authorized Return to Work Date)\n\n // Segment DTP*454 (Initial Treatment Date)\n\n if ($claim->dateInitialTreatment() && ($claim->box15Qualifier()) && ($claim->dateInitialTreatmentValid())) {\n ++$edicount;\n $out .= \"DTP\" . // Date Last Seen\n \"*\" . $claim->box15Qualifier() .\n \"*\" . \"D8\" .\n \"*\" . $claim->dateInitialTreatment() .\n \"~\\n\";\n }\n\n if (strcmp($claim->facilityPOS(), '21') == 0 && $claim->onsetDateValid()) {\n ++$edicount;\n $out .= \"DTP\" . // Date of Hospitalization\n \"*\" . \"435\" .\n \"*\" . \"D8\" .\n \"*\" . $claim->onsetDate() .\n \"~\\n\";\n }\n\n // above is for historical use of encounter onset date, now in misc_billing_options\n if (strcmp($claim->facilityPOS(), '21') == 0 && $claim->hospitalizedFromDateValid()) {\n ++$edicount;\n $out .= \"DTP\" . // Date of Admission\n \"*\" . \"435\" .\n \"*\" . \"D8\" .\n \"*\" . $claim->hospitalizedFrom() .\n \"~\\n\";\n }\n\n // Segment DTP*096 (Discharge Date)\n if (strcmp($claim->facilityPOS(), '21') == 0 && $claim->hospitalizedToDateValid()) {\n ++$edicount;\n $out .= \"DTP\" . // Date of Discharge\n \"*\" . \"96\" .\n \"*\" . \"D8\" .\n \"*\" . $claim->hospitalizedTo() .\n \"~\\n\";\n }\n\n // Segments DTP (Assumed and Relinquished Care Dates) omitted.\n // Segment DTP*444 (Property and Casualty Date of First Contact) omitted.\n // Segment DTP*050 (Repricer Received Date) omitted.\n // Segment CN1 (Contract Information) omitted.\n\n /* Segment PWK for medical attachments\n * TODO: implement medical attachments :)\n * Hardcode OZ, support data for claim, PWK01 report type code\n * Hardcode EL, electronic, PWK02 report transmission code\n * Hardcode AC, attachment control number\n * Billing claim batch control number 9 digits for PWK06\n */\n if ($claim->isRelatedEmployment()) {\n $out .= \"PWK\" .\n \"*\" . \"OZ\" .\n \"*\" . \"EL\" .\n \"*\" . \"*\" .\n \"*\" . \"AC\" .\n \"*\" . BillingClaimBatchControlNumber::getIsa13() .\n \"~\";\n }\n\n $patientpaid = $claim->patientPaidAmount();\n if ($patientpaid != 0) {\n ++$edicount;\n $out .= \"AMT\" . // Patient paid amount. Page 190/220.\n \"*\" . \"F5\" .\n \"*\" . $patientpaid .\n \"~\\n\";\n }\n\n // Segment REF*4N (Service Authorization Exception Code) omitted.\n // Segment REF*F5 (Mandatory Medicare Crossover Indicator) omitted.\n // Segment REF*EW (Mammography Certification Number) omitted.\n // Segment REF*9F (Referral Number) omitted.\n\n if ($claim->priorAuth()) {\n ++$edicount;\n $out .= \"REF\" . // Prior Authorization Number\n \"*\" . \"G1\" .\n \"*\" . $claim->priorAuth() .\n \"~\\n\";\n }\n\n // Segment REF*F8 Payer Claim Control Number for claim re-submission.icn_resubmission_number\n if (strlen(trim($claim->billing_options['icn_resubmission_number'] ?? '')) > 3) {\n ++$edicount;\n error_log(\"Method 1: \" . errorLogEscape($claim->billing_options['icn_resubmission_number']), 0);\n $out .= \"REF\" .\n \"*\" . \"F8\" .\n \"*\" . $claim->icnResubmissionNumber() .\n \"~\\n\";\n }\n\n if ($claim->cliaCode() && ($claim->claimType() === 'MB')) {\n // Required by Medicare when in-house labs are done.\n ++$edicount;\n $out .= \"REF\" . // Clinical Laboratory Improvement Amendment Number\n \"*\" . \"X4\" .\n \"*\" . $claim->cliaCode() .\n \"~\\n\";\n }\n\n // Segment REF*9A (Repriced Claim Number) omitted.\n // Segment REF*9C (Adjusted Repriced Claim Number) omitted.\n // Segment REF*LX (Investigational Device Exemption Number) omitted.\n // Segment REF*D9 (Claim Identifier for Transmission Intermediaries) omitted.\n // Segment REF*EA (Medical Record Number) omitted.\n // Segment REF*P4 (Demonstration Project Identifier) omitted.\n // Segment REF*1J (Care Plan Oversight) omitted.\n // Segment K3 (File Information) omitted.\n if ($claim->additionalNotes()) {\n // Claim note.\n ++$edicount;\n $out .= \"NTE\" . // comments box 19\n \"*\" . \"ADD\" .\n \"*\" . $claim->additionalNotes() .\n \"~\\n\";\n }\n\n // Segment CR1 (Ambulance Transport Information) omitted.\n // Segment CR2 (Spinal Manipulation Service Information) omitted.\n // Segment CRC (Ambulance Certification) omitted.\n // Segment CRC (Patient Condition Information: Vision) omitted.\n // Segment CRC (Homebound Indicator) omitted.\n // Segment CRC (EPSDT Referral).\n if ($claim->epsdtFlag()) {\n ++$edicount;\n $out .= \"CRC\" .\n \"*\" . \"ZZ\" .\n \"*\" . \"Y\" .\n \"*\" . $claim->medicaidReferralCode() .\n \"~\\n\";\n }\n\n // Diagnoses, up to $max_per_seg per HI segment.\n $max_per_seg = 12;\n $da = $claim->diagArray();\n if ($claim->diagtype == \"ICD9\") {\n $diag_type_code = 'BK';\n } else {\n $diag_type_code = 'ABK';\n }\n $tmp = 0;\n foreach ($da as $diag) {\n if ($tmp % $max_per_seg == 0) {\n if ($tmp) {\n $out .= \"~\\n\";\n }\n ++$edicount;\n $out .= \"HI\"; // Health Diagnosis Codes\n }\n $out .= \"*\" . $diag_type_code . \":\" . $diag;\n if ($claim->diagtype == \"ICD9\") {\n $diag_type_code = 'BF';\n } else {\n $diag_type_code = 'ABF';\n }\n ++$tmp;\n }\n\n if ($tmp) {\n $out .= \"~\\n\";\n }\n\n // Segment HI*BP (Anesthesia Related Procedure) omitted.\n // Segment HI*BG (Condition Information) omitted.\n // Segment HCP (Claim Pricing/Repricing Information) omitted.\n if ($claim->referrer ?? null) {\n // Medicare requires referring provider's name and NPI.\n ++$edicount;\n $out .= \"NM1\" . // Loop 2310A Referring Provider\n \"*\" . \"DN\" .\n \"*\" . \"1\" .\n \"*\";\n if ($claim->referrerLastName()) {\n $out .= $claim->referrerLastName();\n } else {\n $log .= \"*** Missing referrer last name.\\n\";\n }\n $out .= \"*\";\n if ($claim->referrerFirstName()) {\n $out .= $claim->referrerFirstName();\n } else {\n $log .= \"*** Missing referrer first name.\\n\";\n }\n $out .= \"*\" .\n $claim->referrerMiddleName() .\n \"*\" .\n \"*\";\n if ($claim->referrerNPI()) {\n $out .=\n \"*\" . \"XX\" .\n \"*\" . $claim->referrerNPI();\n } else {\n $log .= \"*** Referring provider has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n }\n\n // Per the implementation guide lines, only include this information if it is different\n // than the Loop 2010AA information\n if ($claim->providerNPIValid() && ($claim->billingFacilityNPI() !== $claim->providerNPI())) {\n ++$edicount;\n $out .= \"NM1\" . // Loop 2310B Rendering Provider\n \"*\" . \"82\" .\n \"*\" . \"1\" .\n \"*\";\n if ($claim->providerLastName()) {\n $out .= $claim->providerLastName();\n } else {\n $log .= \"*** Missing provider last name.\\n\";\n }\n $out .= \"*\";\n if ($claim->providerFirstName()) {\n $out .= $claim->providerFirstName();\n } else {\n $log .= \"*** Missing provider first name.\\n\";\n }\n $out .= \"*\" .\n $claim->providerMiddleName() .\n \"*\" .\n \"*\";\n if ($claim->providerNPI()) {\n $out .=\n \"*\" . \"XX\" .\n \"*\" . $claim->providerNPI();\n } else {\n $log .= \"*** Rendering provider has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n\n if ($claim->providerTaxonomy()) {\n ++$edicount;\n $out .= \"PRV\" .\n \"*\" . \"PE\" . // Performing provider\n \"*\" . \"PXC\" .\n \"*\" . $claim->providerTaxonomy() .\n \"~\\n\";\n } else {\n $log .= \"*** Performing provider has no taxonomy code.\\n\";\n }\n }\n\n if (!$claim->providerNPIValid()) {\n // If the loop was skipped because the provider NPI was invalid, generate a warning for the log.\n $log .= \"*** Skipping 2310B because \" . $claim->providerLastName() .\n \",\" . $claim->providerFirstName() . \" has invalid NPI.\\n\";\n }\n\n if (!$claim->providerNPI() && in_array($claim->providerNumberType(), array('0B', '1G', 'G2', 'LU'))) {\n if ($claim->providerNumber()) {\n ++$edicount;\n $out .= \"REF\" .\n \"*\" . $claim->providerNumberType() .\n \"*\" . $claim->providerNumber() .\n \"~\\n\";\n }\n }\n // End of Loop 2310B\n\n // Loop 2310C is omitted in the case of home visits (POS=12)\n // and when the service facility is the billing facility\n if ($claim->facilityPOS() != 12 && ($claim->billing_facility['id'] != $claim->facility['id'])) {\n ++$edicount;\n $out .= \"NM1\" . // Loop 2310C Service Location\n \"*\" . \"77\" .\n \"*\" . \"2\";\n $facilityName = substr($claim->facilityName(), 0, 60);\n if ($claim->facilityName() || $claim->facilityNPI() || $claim->facilityETIN()) {\n $out .=\n \"*\" . $facilityName;\n } else {\n $log .= \"*** Check for invalid facility name, NPI, and/or tax id.\\n\";\n }\n if ($claim->facilityNPI() || $claim->facilityETIN()) {\n $out .=\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\";\n if ($claim->facilityNPI()) {\n $out .=\n \"*\" . \"XX\" . \"*\" . $claim->facilityNPI();\n } else {\n $out .=\n \"*\" . \"24\" . \"*\" . $claim->facilityETIN();\n }\n if (!$claim->facilityNPI()) {\n $log .= \"*** Service location has no NPI.\\n\";\n }\n }\n\n $out .= \"~\\n\";\n if ($claim->facilityStreet()) {\n ++$edicount;\n $out .= \"N3\" .\n \"*\" . $claim->facilityStreet() .\n \"~\\n\";\n } else {\n $log .= \"*** Missing service facility street.\\n\";\n }\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->facilityCity()) {\n $out .= $claim->facilityCity();\n } else {\n $log .= \"*** Missing service facility city.\\n\";\n }\n $out .= \"*\";\n if ($claim->facilityState()) {\n $out .= $claim->facilityState();\n } else {\n $log .= \"*** Missing service facility state.\\n\";\n }\n $out .= \"*\";\n if (strlen($claim->facilityZip()) != 9) {\n $log .= \"*** Service facility zip is not 9 digits.\\n\";\n }\n $out .= $claim->facilityZip();\n $out .= \"~\\n\";\n }\n // Segment REF (Service Facility Location Secondary Identification) omitted.\n // Segment PER (Service Facility Contact Information) omitted.\n\n // Loop 2310D, Supervising Provider\n if (! empty($claim->supervisorLastName())) {\n ++$edicount;\n $out .= \"NM1\" .\n \"*\" . \"DQ\" . // Supervising Physician\n \"*\" . \"1\" . // Person\n \"*\" . $claim->supervisorLastName() .\n \"*\" . $claim->supervisorFirstName() .\n \"*\" . $claim->supervisorMiddleName() .\n \"*\" . // NM106 not used\n \"*\"; // Name Suffix not used\n if ($claim->supervisorNPI()) {\n $out .=\n \"*\" . \"XX\" .\n \"*\" . $claim->supervisorNPI();\n } else {\n $log .= \"*** Supervising Provider has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n\n if ($claim->supervisorNumber()) {\n ++$edicount;\n $out .= \"REF\" .\n \"*\" . $claim->supervisorNumberType() .\n \"*\" . $claim->supervisorNumber() .\n \"~\\n\";\n }\n }\n\n // Segments NM1*PW, N3, N4 (Ambulance Pick-Up Location) omitted.\n // Segments NM1*45, N3, N4 (Ambulance Drop-Off Location) omitted.\n\n // Loops 2320 and 2330, other subscriber/payer information.\n // Remember that insurance index 0 is always for the payer being billed\n // by this claim, and 1 and above are always for the \"other\" payers.\n\n for ($ins = 1; $ins < $claim->payerCount(); ++$ins) {\n $tmp1 = $claim->claimType($ins);\n\n // if the ins is unassigned don't include this SBR/OI loop\n if ($tmp1 === '09') {\n continue;\n }\n\n $tmp2 = 'C1'; // Here a kludge. See page 321.\n if ($tmp1 === 'CI') {\n $tmp2 = 'C1';\n }\n if ($tmp1 === 'AM') {\n $tmp2 = 'AP';\n }\n if ($tmp1 === 'HM') {\n $tmp2 = 'HM';\n }\n if ($tmp1 === 'MB') {\n $tmp2 = 'MB';\n }\n if ($tmp1 === 'MC') {\n $tmp2 = 'MC';\n }\n if ($tmp1 === '09') {\n $tmp2 = 'PP';\n }\n\n ++$edicount;\n $out .= \"SBR\" . // Loop 2320, Subscriber Information - page 297/318\n \"*\" . $claim->payerSequence($ins) .\n \"*\" . $claim->insuredRelationship($ins) .\n \"*\" . $claim->groupNumber($ins) .\n \"*\" . ($claim->groupNumber() ? '' : $claim->groupName()) .\n \"*\" . $claim->insuredTypeCode($ins) .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . $claim->claimType($ins) .\n \"~\\n\";\n\n // Things that apply only to previous payers, not future payers.\n if ($claim->payerSequence($ins) < $claim->payerSequence()) {\n // Generate claim-level adjustments.\n $aarr = $claim->payerAdjustments($ins);\n foreach ($aarr as $a) {\n ++$edicount;\n $out .= \"CAS\" . // Previous payer's claim-level adjustments. Page 301/323.\n \"*\" . $a[1] .\n \"*\" . $a[2] .\n \"*\" . $a[3] .\n \"~\\n\";\n }\n\n $payerpaid = $claim->payerTotals($ins);\n ++$edicount;\n $out .= \"AMT\" . // Previous payer's paid amount. Page 307/332.\n \"*\" . \"D\" .\n \"*\" . $payerpaid[1] .\n \"~\\n\";\n // Segment AMT*A8 (COB Total Non-Covered Amount) omitted.\n // Segment AMT*EAF (Remaining Patient Liability) omitted.\n } // End of things that apply only to previous payers.\n\n ++$edicount;\n $out .= \"OI\" . // Other Insurance Coverage Information. Page 310/344.\n \"*\" .\n \"*\" .\n \"*\" . ($claim->billingFacilityAssignment($ins) ? 'Y' : 'N') .\n // For this next item, the 5010 example in the spec does not match its\n // description. So this might be wrong.\n \"*\" .\n \"*\" .\n \"*\" .\n \"Y\" .\n \"~\\n\";\n\n // Segment MOA (Medicare Outpatient Adjudication) omitted.\n ++$edicount;\n $out .= \"NM1\" . // Loop 2330A Subscriber info for other insco. Page 315/350.\n \"*\" . \"IL\" .\n \"*\" . \"1\" .\n \"*\";\n if ($claim->insuredLastName($ins)) {\n $out .= $claim->insuredLastName($ins);\n } else {\n $log .= \"*** Missing other insco insured last name.\\n\";\n }\n $out .= \"*\";\n if ($claim->insuredFirstName($ins)) {\n $out .= $claim->insuredFirstName($ins);\n } else {\n $log .= \"*** Missing other insco insured first name.\\n\";\n }\n $out .= \"*\" .\n $claim->insuredMiddleName($ins) .\n \"*\" .\n \"*\" .\n \"*\" . \"MI\" .\n \"*\";\n if ($claim->policyNumber($ins)) {\n $out .= $claim->policyNumber($ins);\n } else {\n $log .= \"*** Missing other insco policy number.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->insuredStreet($ins)) {\n $out .= $claim->insuredStreet($ins);\n } else {\n $log .= \"*** Missing other insco insured street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->insuredCity($ins)) {\n $out .= $claim->insuredCity($ins);\n } else {\n $log .= \"*** Missing other insco insured city.\\n\";\n }\n $out .= \"*\";\n if ($claim->insuredState($ins)) {\n $out .= $claim->insuredState($ins);\n } else {\n $log .= \"*** Missing other insco insured state.\\n\";\n }\n $out .= \"*\";\n if (\n !(\n (strlen($claim->insuredZip($ins)) == 5)\n || (strlen($claim->insuredZip($ins)) == 9)\n )\n ) {\n $log .= \"*** Other insco insured zip is not 5 or 9 digits.\\n\";\n }\n\n $out .= $claim->x12Zip($claim->insuredZip($ins));\n $out .= \"~\\n\";\n\n // Segment REF (Other Subscriber Secondary Identification) omitted.\n ++$edicount;\n $payerName = substr($claim->payerName($ins), 0, 60);\n $out .= \"NM1\" . // Loop 2330B Payer info for other insco. Page 322/359.\n \"*\" . \"PR\" .\n \"*\" . \"2\" .\n \"*\";\n if ($payerName) {\n $out .= $payerName;\n } else {\n $log .= \"*** Missing other insco payer name.\\n\";\n }\n $out .= \"*\" .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"PI\" .\n \"*\";\n if ($claim->payerID($ins)) {\n $out .= $claim->payerID($ins);\n } else {\n $log .= \"*** Missing other insco payer id.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N3\" .\n \"*\";\n if ($claim->payerStreet($ins)) {\n $out .= $claim->payerStreet($ins);\n } else {\n $log .= \"*** Missing other insco street.\\n\";\n }\n $out .= \"~\\n\";\n\n ++$edicount;\n $out .= \"N4\" .\n \"*\";\n if ($claim->payerCity($ins)) {\n $out .= $claim->payerCity($ins);\n } else {\n $log .= \"*** Missing other insco city.\\n\";\n }\n $out .= \"*\";\n if ($claim->payerState($ins)) {\n $out .= $claim->payerState($ins);\n } else {\n $log .= \"*** Missing other payer state.\\n\";\n }\n $out .= \"*\";\n if (\n !(\n (strlen($claim->payerZip($ins)) == 5)\n || (strlen($claim->payerZip($ins)) == 9)\n )\n ) {\n $log .= \"*** Other payer zip is not 5 or 9 digits.\\n\";\n }\n\n $out .= $claim->x12Zip($claim->payerZip($ins));\n $out .= \"~\\n\";\n\n // Segment DTP*573 (Claim Check or Remittance Date) omitted.\n // Segment REF (Other Payer Secondary Identifier) omitted.\n // Segment REF*G1 (Other Payer Prior Authorization Number) omitted.\n // Segment REF*9F (Other Payer Referral Number) omitted.\n // Segment REF*T4 (Other Payer Claim Adjustment Indicator) omitted.\n // Segment REF*F8 (Other Payer Claim Control Number) omitted.\n // Segment NM1 (Other Payer Referring Provider) omitted.\n // Segment REF (Other Payer Referring Provider Secondary Identification) omitted.\n // Segment NM1 (Other Payer Rendering Provider) omitted.\n // Segment REF (Other Payer Rendering Provider Secondary Identification) omitted.\n // Segment NM1 (Other Payer Service Facility Location) omitted.\n // Segment REF (Other Payer Service Facility Location Secondary Identification) omitted.\n // Segment NM1 (Other Payer Supervising Provider) omitted.\n // Segment REF (Other Payer Supervising Provider Secondary Identification) omitted.\n // Segment NM1 (Other Payer Billing Provider) omitted.\n // Segment REF (Other Payer Billing Provider Secondary Identification) omitted.\n } // End loops 2320/2330*.\n\n $loopcount = 0;\n\n // Loop 2400 Procedure Loop.\n //\n\n for ($prockey = 0; $prockey < $proccount; ++$prockey) {\n ++$loopcount;\n ++$edicount;\n $out .= \"LX\" . // Segment LX, Service Line. Page 398.\n \"*\" . $loopcount .\n \"~\\n\";\n\n ++$edicount;\n $out .= \"SV1\" . // Segment SV1, Professional Service. Page 400.\n \"*\" . \"HC:\" . $claim->cptKey($prockey);\n\n // need description of service for NOC items\n if ($claim->cptNOC($prockey)) {\n $out .= \":::::\" . $claim->cptDescription($prockey);\n }\n\n $out .= \"*\" . sprintf('%.2f', $claim->cptCharges($prockey)) .\n \"*\" . \"UN\" .\n \"*\" . $claim->cptUnits($prockey) .\n \"*\" .\n \"*\" .\n \"*\";\n\n $dia = $claim->diagIndexArray($prockey);\n $i = 0;\n foreach ($dia as $dindex) {\n if ($i) {\n $out .= ':';\n }\n\n $out .= $dindex;\n if (++$i >= 4) {\n break;\n }\n }\n\n // needed for epstd\n if ($claim->epsdtFlag()) {\n $out .= \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"Y\" .\n \"~\\n\";\n } else {\n $out .= \"~\\n\";\n }\n\n if (!$claim->cptCharges($prockey)) {\n $log .= \"*** Procedure '\" . $claim->cptKey($prockey) . \"' has no charges!\\n\";\n }\n\n if (empty($dia)) {\n $log .= \"*** Procedure '\" . $claim->cptKey($prockey) . \"' is not justified!\\n\";\n }\n\n // Segment SV5 (Durable Medical Equipment Service) omitted.\n // Segment PWK01 (Line Supplemental Information) omitted.\n // Segment CR1 (Ambulance Transport Information) omitted.\n // Segment CR3 (Durable Medical Equipment Certification) omitted.\n // Segment CRC (Ambulance Certification) omitted.\n // Segment CRC (Hospice Employee Indicator) omitted.\n // Segment CRC (Condition Indicator / Durable Medical Equipment) omitted.\n\n ++$edicount;\n $out .= \"DTP\" . // Date of Service. Page 435.\n \"*\" . \"472\" .\n \"*\" . \"D8\" .\n \"*\" . $claim->serviceDate() .\n \"~\\n\";\n\n $testnote = rtrim($claim->cptNotecodes($prockey));\n if (!empty($testnote)) {\n ++$edicount;\n $out .= \"NTE\" . // Explain Unusual Circumstances.\n \"*\" . \"ADD\" .\n \"*\" . $claim->cptNotecodes($prockey) .\n \"~\\n\";\n }\n\n // Segment DTP*471 (Prescription Date) omitted.\n // Segment DTP*607 (Revision/Recertification Date) omitted.\n // Segment DTP*463 (Begin Therapy Date) omitted.\n // Segment DTP*461 (Last Certification Date) omitted.\n // Segment DTP*304 (Last Seen Date) omitted.\n // Segment DTP (Test Date) omitted.\n // Segment DTP*011 (Shipped Date) omitted.\n // Segment DTP*455 (Last X-Ray Date) omitted.\n // Segment DTP*454 (Initial Treatment Date) omitted.\n // Segment QTY (Ambulance Patient Count) omitted.\n // Segment QTY (Obstetric Anesthesia Additional Units) omitted.\n // Segment MEA (Test Result) omitted.\n // Segment CN1 (Contract Information) omitted.\n // Segment REF*9B (Repriced Line Item Reference Number) omitted.\n // Segment REF*9D (Adjusted Repriced Line Item Reference Number) omitted.\n // Segment REF*G1 (Prior Authorization) omitted.\n // Segment REF*6R (Line Item Control Number) omitted.\n // (Really oughta have this for robust 835 posting!)\n // Segment REF*EW (Mammography Certification Number) omitted.\n // Segment REF*X4 (CLIA Number) omitted.\n // Segment REF*F4 (Referring CLIA Facility Identification) omitted.\n // Segment REF*BT (Immunization Batch Number) omitted.\n // Segment REF*9F (Referral Number) omitted.\n // Segment AMT*T (Sales Tax Amount) omitted.\n // Segment AMT*F4 (Postage Claimed Amount) omitted.\n // Segment K3 (File Information) omitted.\n // Segment NTE (Line Note) omitted.\n // Segment NTE (Third Party Organization Notes) omitted.\n // Segment PS1 (Purchased Service Information) omitted.\n // Segment HCP (Line Pricing/Repricing Information) omitted.\n\n // Loop 2410, Drug Information. Medicaid insurers seem to want this\n // with HCPCS codes.\n //\n $ndc = $claim->cptNDCID($prockey);\n\n if ($ndc) {\n ++$edicount;\n $out .= \"LIN\" . // Drug Identification. Page 500+ (Addendum pg 71).\n \"*\" . // Per addendum, LIN01 is not used.\n \"*\" . \"N4\" .\n \"*\" . $ndc .\n \"~\\n\";\n\n if (!preg_match('/^\\d\\d\\d\\d\\d-\\d\\d\\d\\d-\\d\\d$/', $ndc, $tmp) && !preg_match('/^\\d{11}$/', $ndc)) {\n $log .= \"*** NDC code '$ndc' has invalid format!\\n\";\n }\n\n ++$edicount;\n $out .= \"CTP\" . // Drug Pricing. Page 500+ (Addendum pg 74).\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . $claim->cptNDCQuantity($prockey) .\n \"*\" . $claim->cptNDCUOM($prockey) .\n // Note: 5010 documents \"ME\" (Milligrams) as an additional unit of measure.\n \"~\\n\";\n\n // Segment REF (Prescription or Compound Drug Association Number) omitted.\n }\n\n\n // Loop 2420A, Rendering Provider (service-specific).\n // Used if the rendering provider for this service line is different\n // from that in loop 2310B.\n\n if ($claim->providerNPI() != $claim->providerNPI($prockey)) {\n ++$edicount;\n $out .= \"NM1\" . // Loop 2420A Rendering Provider\n \"*\" . \"82\" .\n \"*\" . \"1\" .\n \"*\" . $claim->providerLastName($prockey) .\n \"*\" . $claim->providerFirstName($prockey) .\n \"*\" . $claim->providerMiddleName($prockey) .\n \"*\" .\n \"*\";\n if ($claim->providerNPI($prockey)) {\n $out .=\n \"*\" . \"XX\" .\n \"*\" . $claim->providerNPI($prockey);\n } else {\n $log .= \"*** Rendering provider has no NPI.\\n\";\n }\n $out .= \"~\\n\";\n\n // Segment PRV*PE (Rendering Provider Specialty Information) .\n\n if ($claim->providerTaxonomy($prockey)) {\n ++$edicount;\n $out .= \"PRV\" .\n \"*\" . \"PE\" . // PErforming provider\n \"*\" . \"PXC\" .\n \"*\" . $claim->providerTaxonomy($prockey) .\n \"~\\n\";\n }\n\n // Segment REF (Rendering Provider Secondary Identification).\n // REF*1C is required here for the Medicare provider number if NPI was\n // specified in NM109. Not sure if other payers require anything here.\n\n if ($claim->providerNumberType($prockey) == \"G2\") {\n ++$edicount; $out .= \"REF\" . \"*\" . $claim->providerNumberType($prockey) .\n \"*\" . $claim->providerNumber($prockey) . \"~\\n\";\n }\n } // end provider exception\n\n // Segment NM1 (Loop 2420B Purchased Service Provider Name) omitted.\n // Segment REF (Loop 2420B Purchased Service Provider Secondary Identification) omitted.\n // Segment NM1,N3,N4 (Loop 2420C Service Facility Location) omitted.\n // Segment REF (Loop 2420C Service Facility Location Secondary Identification) omitted.\n // Segment NM1 (Loop 2420D Supervising Provider Name) omitted.\n // Segment REF (Loop 2420D Supervising Provider Secondary Identification) omitted.\n\n // Loop 2420E, Ordering Provider\n if ($claim->orderer ?? null) {\n ++$edicount;\n $out .= \"NM1\" .\n \"*\" . \"DK\" .\n \"*\" . \"1\" .\n \"*\" . $claim->ordererLastName() . '*' . $claim->ordererFirstName() .\n \"*\" .\n \"*\" .\n \"*\" .\n \"*\" . \"XX\" .\n \"*\" . $claim->ordererNPI() . \"~\\n\";\n $out .= \"N3\" . \"*\" . $claim->ordererStreet() . \"~\\n\";\n $out .= \"N4\" . \"*\" . $claim->ordererCity() . \"*\" .\n $claim->ordererState() . \"*\" . $claim->ordererZip() . \"~\\n\";\n }\n\n // Segment NM1 (Referring Provider Name) omitted.\n // Segment REF (Referring Provider Secondary Identification) omitted.\n // Segments NM1*PW, N3, N4 (Ambulance Pick-Up Location) omitted.\n // Segments NM1*45, N3, N4 (Ambulance Drop-Off Location) omitted.\n\n // Loop 2430, adjudication by previous payers.\n\n for ($ins = 1; $ins < $claim->payerCount(); ++$ins) {\n if ($claim->payerSequence($ins) > $claim->payerSequence()) {\n continue; // payer is future, not previous\n }\n\n $payerpaid = $claim->payerTotals($ins, $claim->cptKey($prockey));\n $aarr = $claim->payerAdjustments($ins, $claim->cptKey($prockey));\n\n if ($payerpaid[1] == 0 && !count($aarr)) {\n $log .= \"*** Procedure '\" . $claim->cptKey($prockey) .\n \"' has no payments or adjustments from previous payer!\\n\";\n continue;\n }\n\n ++$edicount;\n $out .= \"SVD\" . // Service line adjudication. Page 554.\n \"*\" . $claim->payerID($ins) .\n \"*\" . $payerpaid[1] .\n \"*\" . \"HC:\" . $claim->cptKey($prockey) .\n \"*\" .\n \"*\" . $claim->cptUnits($prockey) .\n \"~\\n\";\n\n $tmpdate = $payerpaid[0];\n $cas = $claim->getLineItemAdjustments($aarr);\n\n // $key is the group code or payer_paid_date\n foreach ($cas as $key => $value) {\n if ($key == 'payer_paid_date') {\n if (!$tmpdate) {\n $tmpdate = $value;\n }\n continue;\n }\n\n $out .= \"CAS\" .\n \"*\" .\n $key . \"*\";\n $size = count($value);\n $cntr = 0;\n // $k is the reason code\n // $v is the amount\n foreach ($value as $k => $v) {\n $cntr++;\n $out .= $k .\n \"*\" .\n $v;\n if ($cntr < $size) {\n $out .= \"*\" .\n \"*\";\n }\n }\n $out .= \"~\\n\";\n ++$edicount;\n }\n\n if ($tmpdate) {\n ++$edicount;\n $out .= \"DTP\" . // Previous payer's line adjustment date. Page 493/566.\n \"*\" . \"573\" .\n \"*\" . \"D8\" .\n \"*\" . $tmpdate .\n \"~\\n\";\n }\n\n // Segment AMT*EAF (Remaining Patient Liability) omitted.\n // Segment LQ (Form Identification Code) omitted.\n // Segment FRM (Supporting Documentation) omitted.\n } // end loop 2430\n } // end this procedure\n\n if (\n $SEFLAG == true\n || empty($GLOBALS['gen_x12_based_on_ins_co'])\n ) {\n ++$edicount; //todo: This might have to go into the SE flag spot //***MS Modify\n\n $out .= \"SE\" . // SE Trailer\n \"*\" . $edicount .\n \"*\" . \"0021\" .\n \"~\\n\";\n }\n\n $out .= \"GE\" . // GE Trailer\n \"*\" . \"1\" .\n \"*\" . \"1\" .\n \"~\\n\";\n\n $out .= \"IEA\" . // IEA Trailer\n \"*\" . \"1\" .\n \"*\" . \"000000001\" .\n \"~\\n\";\n\n // Remove any trailing empty fields (delimiters) from each segment.\n $out = preg_replace('/\\*+~/', '~', $out);\n\n $log .= \"\\n\";\n return $out;\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (string $projectId, string $name, string $description, string $logo, string $url, string $legalName, string $legalCountry, string $legalState, string $legalCity, string $legalAddress, string $legalTaxId, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $project = $dbForConsole->updateDocument('projects', $project->getId(), $project\n ->setAttribute('name', $name)\n ->setAttribute('description', $description)\n ->setAttribute('logo', $logo)\n ->setAttribute('url', $url)\n ->setAttribute('legalName', $legalName)\n ->setAttribute('legalCountry', $legalCountry)\n ->setAttribute('legalState', $legalState)\n ->setAttribute('legalCity', $legalCity)\n ->setAttribute('legalAddress', $legalAddress)\n ->setAttribute('legalTaxId', $legalTaxId)\n ->setAttribute('search', implode(' ', [$projectId, $name])));\n\n $response->dynamic($project, Response::MODEL_PROJECT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?float $min, ?float $max, ?float $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n // Ensure attribute default is within range\n $min = (is_null($min)) ? -PHP_FLOAT_MAX : \\floatval($min);\n $max = (is_null($max)) ? PHP_FLOAT_MAX : \\floatval($max);\n\n if ($min > $max) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Minimum value must be lesser than maximum value');\n }\n\n // Ensure default value is a float\n if (!is_null($default)) {\n $default = \\floatval($default);\n }\n\n $validator = new Range($min, $max, Database::VAR_FLOAT);\n\n if (!is_null($default) && !$validator->isValid($default)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription());\n }\n\n $attribute = createAttribute($databaseId, $collectionId, new Document([\n 'key' => $key,\n 'type' => Database::VAR_FLOAT,\n 'required' => $required,\n 'size' => 0,\n 'default' => $default,\n 'array' => $array,\n 'format' => APP_DATABASE_ATTRIBUTE_FLOAT_RANGE,\n 'formatOptions' => [\n 'min' => $min,\n 'max' => $max,\n ],\n ]), $response, $dbForProject, $database, $events);\n\n $formatOptions = $attribute->getAttribute('formatOptions', []);\n\n if (!empty($formatOptions)) {\n $attribute->setAttribute('min', \\floatval($formatOptions['min']));\n $attribute->setAttribute('max', \\floatval($formatOptions['max']));\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_FLOAT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function create(string $name, string $value = null, $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self\n {\n return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function modifElevesAvecCode($nom, $prenom, $sexe, $date_naissance, $tel_enfant, $email_enfant,$responsable_legal,$tel_parent,$tel_parent2,$tel_parent3, $profession_pere,$adresse,$profession_mere,$ville, $email_parent,$prevenir_parent,$commentaires,$cp,$assurance,$codebarre,$password,$num,$numAllocataire,$nbTempsLibres,$contactParents,$photo)\n\t{\t\t\t\n\t\t$req = \"UPDATE `eleves` SET `NOM`='\".strtoupper($nom).\"',`PRENOM`='\".ucfirst($prenom).\"',`SEXE`='$sexe',`DATE_DE_NAISSANCE`='$date_naissance',`RESPONSABLE_LEGAL`='$responsable_legal',`PR\u00c9VENIR_EN_CAS_D_ABSENCE`='$prevenir_parent',`PROFESSION_DU_P\u00c8RE`='$profession_pere',`PROFESSION_DE_LA_M\u00c8RE`='$profession_mere',`ADRESSE_POSTALE`='$adresse',`CODE_POSTAL`='$cp',`VILLE`='\".strtoupper($ville).\"',`T\u00c9L\u00c9PHONE_DES_PARENTS`='$tel_parent',`T\u00c9L\u00c9PHONE_DES_PARENTS2`='$tel_parent2',`T\u00c9L\u00c9PHONE_DES_PARENTS3`='$tel_parent3',`T\u00c9L\u00c9PHONE_DE_L_ENFANT`='$tel_enfant',`EMAIL_DES_PARENTS`='$email_parent',`EMAIL_DE_L_ENFANT`='$email_enfant',`PHOTO`='$photo',`CONTACT_AVEC_LES_PARENTS`='$contactParents',`COMMENTAIRES`='$commentaires',`N\u00b0_ALLOCATAIRE`='$numAllocataire',`NOMBRE_TPS_LIBRE`='$nbTempsLibres',`ASSURANCE_P\u00c9RISCOLAIRE`='$assurance', `PASSWORD`='$password' WHERE `ID_ELEVE`=\" . $num . \";\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'\u00e9l\u00e8ve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());} else { }\n\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n\t\tstring $appName,\n\t\tIRequest $request,\n\t\tIFactory $l10nFactory,\n\t\tDefaults $defaults,\n\t\tIAppManager $appManager,\n\t\tISession $session,\n\t\tIUserSession $userSession,\n\t\tIConfig $config,\n\t\tIGroupManager $groupManager,\n\t\tIniGetWrapper $iniWrapper,\n\t\tIURLGenerator $urlGenerator,\n\t\tCapabilitiesManager $capabilitiesManager,\n\t\tIInitialStateService $initialStateService,\n\t\tIProvider $tokenProvider,\n\t) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->helper = new JSConfigHelper(\n\t\t\t$l10nFactory->get('lib'),\n\t\t\t$defaults,\n\t\t\t$appManager,\n\t\t\t$session,\n\t\t\t$userSession->getUser(),\n\t\t\t$config,\n\t\t\t$groupManager,\n\t\t\t$iniWrapper,\n\t\t\t$urlGenerator,\n\t\t\t$capabilitiesManager,\n\t\t\t$initialStateService,\n\t\t\t$tokenProvider\n\t\t);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function search_acl($aco_section_value=NULL, $aco_value=NULL, $aro_section_value=NULL, $aro_value=NULL, $aro_group_name=NULL, $axo_section_value=NULL, $axo_value=NULL, $axo_group_name=NULL, $return_value=NULL) {\n\t\t$this->debug_text(\"search_acl(): aco_section_value: $aco_section_value aco_value: $aco_value, aro_section_value: $aro_section_value, aro_value: $aro_value, aro_group_name: $aro_group_name, axo_section_value: $axo_section_value, axo_value: $axo_value, axo_group_name: $axo_group_name, return_value: $return_value\");\n\n\t\t$query = '\n\t\t\t\tSELECT\t\ta.id\n\t\t\t\tFROM\t\t'. $this->_db_table_prefix .'acl a';\n\n\t\t$where_query = array();\n\n\t\t// ACO\n\t\tif ($aco_section_value !== FALSE AND $aco_value !== FALSE) {\n\t\t\t$query .= '\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aco_map ac ON a.id=ac.acl_id';\n\n\t\t\tif ($aco_section_value == NULL AND $aco_value == NULL) {\n\t\t\t\t$where_query[] = '(ac.section_value IS NULL AND ac.value IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(ac.section_value='. $this->db->quote($aco_section_value) .' AND ac.value='. $this->db->quote($aco_value) .')';\n\t\t\t}\n\t\t}\n\n\t\t// ARO\n\t\tif ($aro_section_value !== FALSE AND $aro_value !== FALSE) {\n\t\t\t$query .= '\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aro_map ar ON a.id=ar.acl_id';\n\n\t\t\tif ($aro_section_value == NULL AND $aro_value == NULL) {\n\t\t\t\t$where_query[] = '(ar.section_value IS NULL AND ar.value IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(ar.section_value='. $this->db->quote($aro_section_value) .' AND ar.value='. $this->db->quote($aro_value) .')';\n\t\t\t}\n\t\t}\n\n\t\t// AXO\n\t\tif ($axo_section_value !== FALSE AND $axo_value !== FALSE) {\n\t\t\t$query .= '\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_map ax ON a.id=ax.acl_id';\n\n\t\t\tif ($axo_section_value == NULL AND $axo_value == NULL) {\n\t\t\t\t$where_query[] = '(ax.section_value IS NULL AND ax.value IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(ax.section_value='. $this->db->quote($axo_section_value) .' AND ax.value='. $this->db->quote($axo_value) .')';\n\t\t\t}\n\t\t}\n\n\t\t// ARO Group\n\t\tif ($aro_group_name !== FALSE) {\n\t\t\t$query .= '\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aro_groups_map arg ON a.id=arg.acl_id\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aro_groups rg ON arg.group_id=rg.id';\n\n\t\t\tif ($aro_group_name == NULL) {\n\t\t\t\t$where_query[] = '(rg.name IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(rg.name='. $this->db->quote($aro_group_name) .')';\n\t\t\t}\n\t\t}\n\n\t\t// AXO Group\n\t\tif ($axo_group_name !== FALSE) {\n\t\t\t$query .= '\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_groups_map axg ON a.id=axg.acl_id\n\t\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_groups xg ON axg.group_id=xg.id';\n\n\t\t\tif ($axo_group_name == NULL) {\n\t\t\t\t$where_query[] = '(xg.name IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(xg.name='. $this->db->quote($axo_group_name) .')';\n\t\t\t}\n\t\t}\n\t\tif ($return_value != FALSE) {\n\t\t\tif ($return_value == NULL) {\n\t\t\t\t$where_query[] = '(a.return_value IS NULL)';\n\t\t\t} else {\n\t\t\t\t$where_query[] = '(a.return_value='. $this->db->quote($return_value) .')';\n\t\t\t}\n\t\t}\n\n\t\tif (count($where_query) > 0) {\n\t\t\t$query .= '\n\t\t\t\tWHERE\t\t'. implode (' AND ', $where_query);\n\t\t}\n\n\t\treturn $this->db->GetCol($query);\n\t}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function raise(\n $event,\n CommonGLPI $item,\n array $options,\n $label,\n array $data,\n NotificationTarget $notificationtarget,\n NotificationTemplate $template,\n $notify_me,\n $emitter = null,\n ?CommonDBTM $trigger = null\n );", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {\n\t\t$this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function fin_pPMT(array $per,float $IY,float $Nper, float $PV, int $PY, int $CY, float $FV=0, int $type=0){\n if (count($per)!=2) {echo 'array size must be 2: cannot compute'; return '';}\n if ($CY<=0 or $PY<=0) { echo 'error: CY and PY must be positive'; return '';}\n if ($type!=0 && $type!=1) { echo 'error: type gets either 1 for annuity due (beginning) or 0 for general annuity (end)'; return '';}\n if ($IY<0) { echo 'error: IY cannot be negative'; return '';}\n $pmt=round(fin_PMT($IY,$Nper,$PV,$PY,$CY,$FV=0,$type=0),3);\n $i=$IY/($CY*100);\n $i2=((1+$i)**($CY/$PY))-1;\n\n $ipmt=array();\n $ipmt[0]=0;\n $ppmt=array();\n $ppmt[0]=0;\n $bal=abs($PV);\n $upto=$per[1];\n $intsum=array();\n $intsum[0]=0;\n $prnsum=array();\n $prnsum[0]=0;\n for ($j=1;$j<=$upto;$j++){\n $ipmt[$j]=round($bal*$i2,3);\n $intsum[$j]= round($intsum[$j-1]+$ipmt[$j],3);\n $ppmt[$j]=abs($pmt)-$ipmt[$j];\n $prnsum[$j]= round($prnsum[$j-1]+$ppmt[$j],3);\n $bal=round($bal-$ppmt[$j],3);\n }\n $k1=$per[0]-1;\n $k2=$per[1];\n $intpaid=$intsum[$k2]-$intsum[$k1];\n $prnpaid=$prnsum[$k2]-$prnsum[$k1];\n\n return $prnpaid;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function __construct(\n\t\t$job_id,\n\t\t$job_type,\n\t\t$job_type_title,\n\t\t$title,\n\t\t$view_link,\n\t\t$source_lang,\n\t\t$target_lang,\n\t\t$translation_complete,\n\t\t$duplicate\n\t) {\n\n\t\t$this->job_id = $job_id;\n\t\t$this->job_type = $job_type;\n\t\t$this->job_type_title = $job_type_title;\n\t\t$this->title = $title;\n\t\t$this->view_link = $view_link;\n\t\t$this->source_lang = $source_lang;\n\t\t$this->target_lang = $target_lang;\n\t\t$this->translation_complete = $translation_complete;\n\t\t$this->duplicate = $duplicate;\n\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function creerFacture($ref_fact, $date_fact, $date_fact_rec, \n\t\t\t\t\t\t\t\t\t\t$fournisseur, $date_val, $fichier_fact, \n\t\t\t\t\t\t\t\t\t\t$tmp_fact, $id_mod_lic, $id_cli, $commodity, \n\t\t\t\t\t\t\t\t\t\t$montant_fact, $id_mon, $fret_fact, \n\t\t\t\t\t\t\t\t\t\t$assurance_fact, $autre_frais_fact, $fsi=NULL, $aur=NULL){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['date_fact'] = $date_fact;\n\t\t\t$entree['date_fact_rec'] = $date_fact_rec;\n\t\t\t$entree['fournisseur'] = $fournisseur;\n\t\t\t$entree['date_val'] = $date_val;\n\t\t\t$entree['fichier_fact'] = $fichier_fact;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['commodity'] = $commodity;\n\t\t\t$entree['montant_fact'] = $montant_fact;\n\t\t\t$entree['id_mon'] = $id_mon;\n\t\t\t$entree['fret_fact'] = $fret_fact;\n\t\t\t$entree['assurance_fact'] = $assurance_fact;\n\t\t\t$entree['autre_frais_fact'] = $autre_frais_fact;\n\t\t\t$entree['fsi'] = $fsi;\n\t\t\t$entree['aur'] = $aur;\n\n\t\t\t/*echo '
    ref_fact = '.$ref_fact;\n\t\t\techo '
    date_fact = '.$date_fact;\n\t\t\techo '
    date_fact_rec = '.$date_fact_rec;\n\t\t\techo '
    fournisseur= '.$fournisseur;\n\t\t\techo '
    date_val = '.$date_val;\n\t\t\techo '
    fichier_fact = '.$fichier_fact;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    id_cli = '.$id_cli;\n\t\t\techo '
    id_march = '.$id_march;*/\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO facture_licence(ref_fact, date_fact, date_fact_rec, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfournisseur, date_val, fichier_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_cli, commodity, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmontant_fact, id_mon, fret_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tassurance_fact, autre_frais_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfsi, aur)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_fact'], $entree['date_fact'], $entree['date_fact_rec'], \n\t\t\t\t\t\t\t\t\t$entree['fournisseur'], $entree['date_val'], $entree['fichier_fact'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['id_cli'], $entree['commodity'], \n\t\t\t\t\t\t\t\t\t$entree['montant_fact'], $entree['id_mon'], $entree['fret_fact'], \n\t\t\t\t\t\t\t\t\t$entree['assurance_fact'], $entree['autre_frais_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fsi'], $entree['aur']));\n\n\t\t\t$facture = '../factures/'.$ref_fact;\n\n\t\t\tif(!is_dir($facture)){\n\t\t\t\tmkdir(\"../factures/$ref_fact\", 0777);\n\t\t\t}\n\n\t\t\tmove_uploaded_file($tmp_fact, '../factures/'.$ref_fact.'/' . basename($fichier_fact));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function button_widget($view, $form, $label, $name, $id, $translation_domain,\n $formHelper, $translatorHelper, $label_format = null, $type = null)\n {\n ?>\n $name, '%id%' => $id))\n : $formHelper->humanize($name); } ?>\n \n\n types->getTypeClass($trueType);\n $config = Config::getInstance();\n if ($currentClass !== '' && isset($config->settings['DefaultFunctions']['FUNC_' . $currentClass])) {\n $defaultFunction = $config->settings['DefaultFunctions']['FUNC_' . $currentClass];\n // Change the configured default function to include the ST_ prefix with MySQL 5.6 and later.\n // It needs to match the function listed in the select html element.\n if (\n $currentClass === 'SPATIAL' &&\n $dbi->getVersion() >= 50600 &&\n stripos($defaultFunction, 'ST_') !== 0\n ) {\n $defaultFunction = 'ST_' . $defaultFunction;\n }\n }\n\n // what function defined as default?\n // for the first timestamp we don't set the default function\n // if there is a default value for the timestamp\n // (not including CURRENT_TIMESTAMP)\n // and the column does not have the\n // ON UPDATE DEFAULT TIMESTAMP attribute.\n if (\n $trueType === 'timestamp'\n && $firstTimestamp\n && ($defaultValue === null || $defaultValue === '')\n && $extra !== 'on update CURRENT_TIMESTAMP'\n && ! $isNull\n ) {\n $defaultFunction = $config->settings['DefaultFunctions']['first_timestamp'];\n }\n\n // For primary keys of type char(36) or varchar(36) UUID if the default\n // function\n // Only applies to insert mode, as it would silently trash data on updates.\n if (\n $insertMode\n && $key === 'PRI'\n && ($type === 'char(36)' || $type === 'varchar(36)')\n ) {\n return $config->settings['DefaultFunctions']['FUNC_UUID'];\n }\n\n return $defaultFunction;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function __construct(\n\t\tIDBConnection $connection,\n\t\tIUserManager $userManager,\n\t\tIGroupManager $groupManager,\n\t\tIRootFolder $rootFolder,\n\t\tIMailer $mailer,\n\t\tDefaults $defaults,\n\t\tIFactory $l10nFactory,\n\t\tIURLGenerator $urlGenerator,\n\t\tITimeFactory $timeFactory,\n\t\tprivate IManager $shareManager,\n\t) {\n\t\t$this->dbConn = $connection;\n\t\t$this->userManager = $userManager;\n\t\t$this->groupManager = $groupManager;\n\t\t$this->rootFolder = $rootFolder;\n\t\t$this->mailer = $mailer;\n\t\t$this->defaults = $defaults;\n\t\t$this->l10nFactory = $l10nFactory;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->timeFactory = $timeFactory;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n\t\t$AppName,\n\t\tIRequest $request,\n\t\tIL10N $l10n,\n\t\tUserGlobalStoragesService $userGlobalStoragesService,\n\t\tLoggerInterface $logger,\n\t\tIUserSession $userSession,\n\t\tIGroupManager $groupManager,\n\t\tIConfig $config\n\t) {\n\t\tparent::__construct(\n\t\t\t$AppName,\n\t\t\t$request,\n\t\t\t$l10n,\n\t\t\t$userGlobalStoragesService,\n\t\t\t$logger,\n\t\t\t$userSession,\n\t\t\t$groupManager,\n\t\t\t$config\n\t\t);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {\n\t\tif ($level < 0) {\n\t\t\t$level = 0;\n\t\t}\n\t\tif (isset($this->outlines[0])) {\n\t\t\t$lastoutline = end($this->outlines);\n\t\t\t$maxlevel = $lastoutline['l'] + 1;\n\t\t} else {\n\t\t\t$maxlevel = 0;\n\t\t}\n\t\tif ($level > $maxlevel) {\n\t\t\t$level = $maxlevel;\n\t\t}\n\t\tif ($y == -1) {\n\t\t\t$y = $this->GetY();\n\t\t} elseif ($y < 0) {\n\t\t\t$y = 0;\n\t\t} elseif ($y > $this->h) {\n\t\t\t$y = $this->h;\n\t\t}\n\t\tif ($x == -1) {\n\t\t\t$x = $this->GetX();\n\t\t} elseif ($x < 0) {\n\t\t\t$x = 0;\n\t\t} elseif ($x > $this->w) {\n\t\t\t$x = $this->w;\n\t\t}\n\t\t$fixed = false;\n\t\tif (!empty($page) AND ($page[0] == '*')) {\n\t\t\t$page = intval(substr($page, 1));\n\t\t\t// this page number will not be changed when moving/add/deleting pages\n\t\t\t$fixed = true;\n\t\t}\n\t\tif (empty($page)) {\n\t\t\t$page = $this->PageNo();\n\t\t\tif (empty($page)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t$this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public function __construct(\n\t\t?string $inAnoLetivo,\n\t\t?string $inCodEscola,\n\t\t?string $inCodUnidade,\n\t\t?string $inFase,\n ?string $inInteresseIntegral = null,\n ?string $inInteresseEspanhol = null,\n ?string $inNecesAtendNoturno = null,\n ?string $inInteresseNovoTec = null,\n ?string $inCodigoObservacaoOpcaoNoturno = null,\n ?string $inCodigoEixoNovotecOpcaoUm = null ,\n ?string $inCodigoEscolaNovotecOpcaoUm = null,\n ?string $inCodigoUnidadeNovotecOpcaoUm = null,\n ?string $inFl_InteresseCentroIdiomas = null,\n ?string $inFl_AceiteEscolaPEIDistante = null,\n ?string $inCodigoEixoCELOpcaoUm = null,\n ?string $inCodigoEscolaCELOpcaoUm = null,\n ?string $inCodigoUnidadeCELOpcaoUm = null,\n ?string $inCodigoEixoNovotecOpcaoDois = null,\n ?string $inCodigoEixoNovotecOpcaoTres = null\n\t) {\n\t\t$this->inAnoLetivo = $inAnoLetivo;\n\t\t$this->inCodEscola = $inCodEscola;\n\t\t$this->inCodUnidade = $inCodUnidade;\n\t\t$this->inFase = $inFase;\n\t\t$this->inInteresseIntegral = $inInteresseIntegral;\n\t\t$this->inInteresseEspanhol = $inInteresseEspanhol;\n\t\t$this->inNecesAtendNoturno = $inNecesAtendNoturno;\n\t\t$this->inInteresseNovoTec = $inInteresseNovoTec;\n\t\t$this->inCodigoObservacaoOpcaoNoturno = $inCodigoObservacaoOpcaoNoturno;\n\t\t$this->inCodigoEixoNovotecOpcaoUm = $inCodigoEixoNovotecOpcaoUm;\n\t\t$this-> inCodigoEscolaNovotecOpcaoUm = $inCodigoEscolaNovotecOpcaoUm ;\n\t\t$this-> inCodigoUnidadeNovotecOpcaoUm = $inCodigoUnidadeNovotecOpcaoUm ;\n\t\t$this-> inFl_InteresseCentroIdiomas = $inFl_InteresseCentroIdiomas ;\n\t\t$this-> inFl_AceiteEscolaPEIDistante = $inFl_AceiteEscolaPEIDistante ;\n\t\t$this-> inCodigoEixoCELOpcaoUm = $inCodigoEixoCELOpcaoUm ;\n\t\t$this-> inCodigoEscolaCELOpcaoUm = $inCodigoEscolaCELOpcaoUm ;\n\t\t$this-> inCodigoUnidadeCELOpcaoUm = $inCodigoUnidadeCELOpcaoUm ;\n\t\t$this->inCodigoEixoNovotecOpcaoDois = $inCodigoEixoNovotecOpcaoDois;\n\t\t$this->inCodigoEixoNovotecOpcaoTres = $inCodigoEixoNovotecOpcaoTres;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function test_rules_clinic_collate($provider = '', $type = '', $dateTarget = '', $mode = '', $patient_id = '', $plan = '', $organize_mode = 'default', $options = array(), $pat_prov_rel = 'primary', $start = null, $batchSize = null, $user = '')\n{\n $results = [];\n // If set the $provider to collate_outer (or collate_inner without plans organize mode),\n // then run through this function recursively and return results.\n if (($provider === \"collate_outer\") || ($provider === \"collate_inner\" && $organize_mode !== 'plans')) {\n // First, collect an array of all providers\n $query = \"SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname\";\n $ures = sqlStatementCdrEngine($query);\n // Second, run through each provider recursively\n while ($urow = sqlFetchArray($ures)) {\n $newResults = test_rules_clinic($urow['id'], $type, $dateTarget, $mode, $patient_id, $plan, $organize_mode, $options, $pat_prov_rel, $start, $batchSize, $user);\n if (!empty($newResults)) {\n $provider_item['is_provider'] = true;\n $provider_item['prov_lname'] = $urow['lname'];\n $provider_item['prov_fname'] = $urow['fname'];\n $provider_item['npi'] = $urow['npi'];\n $provider_item['federaltaxid'] = $urow['federaltaxid'];\n $results[] = $provider_item;\n $results = array_merge($results, $newResults);\n }\n }\n\n // done, so now can return results\n return $results;\n }\n\n // If set organize-mode to plans, then collects active plans and run through this\n // function recursively and return results.\n if ($organize_mode === \"plans\") {\n // First, collect active plans\n $plans_resolve = resolve_plans_sql($plan, $patient_id);\n // Second, run through function recursively\n foreach ($plans_resolve as $plan_item) {\n // (if collate_inner, then nest a collation of providers within each plan)\n if ($provider === \"collate_inner\") {\n // First, collect an array of all providers\n $query = \"SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname\";\n $ures = sqlStatementCdrEngine($query);\n // Second, run through each provider recursively\n $provider_results = array();\n while ($urow = sqlFetchArray($ures)) {\n $newResults = test_rules_clinic($urow['id'], $type, $dateTarget, $mode, $patient_id, $plan_item['id'], 'default', $options, $pat_prov_rel, $start, $batchSize, $user);\n if (!empty($newResults)) {\n $provider_item['is_provider'] = true;\n $provider_item['prov_lname'] = $urow['lname'];\n $provider_item['prov_fname'] = $urow['fname'];\n $provider_item['npi'] = $urow['npi'];\n $provider_item['federaltaxid'] = $urow['federaltaxid'];\n $provider_results[] = $provider_item;\n $provider_results = array_merge($provider_results, $newResults);\n }\n }\n\n if (!empty($provider_results)) {\n $plan_item['is_plan'] = true;\n $results[] = $plan_item;\n $results = array_merge($results, $provider_results);\n }\n } else {\n // (not collate_inner, so do not nest providers within each plan)\n $newResults = test_rules_clinic($provider, $type, $dateTarget, $mode, $patient_id, $plan_item['id'], 'default', $options, $pat_prov_rel, $start, $batchSize, $user);\n if (!empty($newResults)) {\n $plan_item['is_plan'] = true;\n $results[] = $plan_item;\n $results = array_merge($results, $newResults);\n }\n }\n }\n\n // done, so now can return results\n return $results;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function creerDetailFactureDossier3($ref_fact, $id_dos, $id_deb, $montant, $tva, $usd='1', $detail=NULL, $unite=NULL, $pourcentage_qte){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['id_dos'] = $id_dos;\n\t\t\t$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['id_deb'] = $id_deb;\n\t\t\t$entree['montant'] = $montant;\n\t\t\t$entree['tva'] = $tva;\n\t\t\t$entree['usd'] = $usd;\n\t\t\t$entree['detail'] = $detail;\n\t\t\t$entree['unite'] = $unite;\n\t\t\t$entree['pourcentage_qte'] = $pourcentage_qte;\n\t\t\t// $entree['montant_tva'] = $montant_tva;\n\n\t\t\t// echo '

    id_dos = '.$id_dos;\n\t\t\t// echo '
    ref_fact = '.$ref_fact;\n\t\t\t// echo '
    id_deb = '.$id_deb;\n\t\t\t// echo '
    montant = '.$montant;\n\t\t\t// echo '
    tva = '.$tva;\n\t\t\t// echo '
    usd = '.$usd;\n\t\t\t// echo '
    detail = '.$detail;\n\t\t\t// echo '
    unite = '.$unite;\n\t\t\t// echo '
    pourcentage_qte = '.$pourcentage_qte;\n\t\t\t// echo '
    ------------------
    ';\n\n\t\t\tif ($montant>0) {\n\t\t\t\t$requete = $connexion-> prepare(\"INSERT INTO detail_facture_dossier(ref_fact, id_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_deb, montant, tva, usd, detail, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunite, pourcentage_qte)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)\");\n\t\t\t\t$requete-> execute(array($entree['ref_fact'], $entree['id_dos'],\n\t\t\t\t\t\t\t\t\t$entree['id_deb'], $entree['montant'], \n\t\t\t\t\t\t\t\t\t$entree['tva'], $entree['usd'], $entree['detail'], \n\t\t\t\t\t\t\t\t\t$entree['unite'], $entree['pourcentage_qte']));\n\t\t\t}\n\n\t\t\t\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function imagefilledarc ($image, $cx, $cy, $width, $height, $start, $end, $color, $style) {}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function oc_db_create(string $db_driver, string $db_hostname, string $db_username, string $db_password, string $db_database, string $db_port, string $db_prefix, string $db_ssl_key, string $db_ssl_cert, string $db_ssl_ca): bool {\n\ttry {\n\t\t// Database\n\t\t$db = new \\Opencart\\System\\Library\\DB($db_driver, $db_hostname, $db_username, $db_password, $db_database, $db_port, $db_ssl_key, $db_ssl_cert, $db_ssl_ca);\n\t} catch (\\Exception $e) {\n\t\treturn false;\n\t}\n\n\t// Set up Database structure\n\t$tables = oc_db_schema();\n\n\tforeach ($tables as $table) {\n\t\t$table_query = $db->query(\"SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '\" . $db_database . \"' AND TABLE_NAME = '\" . $db_prefix . $table['name'] . \"'\");\n\n\t\tif ($table_query->num_rows) {\n\t\t\t$db->query(\"DROP TABLE `\" . $db_prefix . $table['name'] . \"`\");\n\t\t}\n\n\t\t$sql = \"CREATE TABLE `\" . $db_prefix . $table['name'] . \"` (\" . \"\\n\";\n\n\t\tforeach ($table['field'] as $field) {\n\t\t\t$sql .= \" `\" . $field['name'] . \"` \" . $field['type'] . (!empty($field['not_null']) ? \" NOT NULL\" : \"\") . (isset($field['default']) ? \" DEFAULT '\" . $db->escape($field['default']) . \"'\" : \"\") . (!empty($field['auto_increment']) ? \" AUTO_INCREMENT\" : \"\") . \",\\n\";\n\t\t}\n\n\t\tif (isset($table['primary'])) {\n\t\t\t$primary_data = [];\n\n\t\t\tforeach ($table['primary'] as $primary) {\n\t\t\t\t$primary_data[] = \"`\" . $primary . \"`\";\n\t\t\t}\n\n\t\t\t$sql .= \" PRIMARY KEY (\" . implode(\",\", $primary_data) . \"),\\n\";\n\t\t}\n\n\t\tif (isset($table['index'])) {\n\t\t\tforeach ($table['index'] as $index) {\n\t\t\t\t$index_data = [];\n\n\t\t\t\tforeach ($index['key'] as $key) {\n\t\t\t\t\t$index_data[] = \"`\" . $key . \"`\";\n\t\t\t\t}\n\n\t\t\t\t$sql .= \" KEY `\" . $index['name'] . \"` (\" . implode(\",\", $index_data) . \"),\\n\";\n\t\t\t}\n\t\t}\n\n\t\t$sql = rtrim($sql, \",\\n\") . \"\\n\";\n\t\t$sql .= \") ENGINE=\" . $table['engine'] . \" CHARSET=\" . $table['charset'] . \" COLLATE=\" . $table['collate'] . \";\\n\";\n\n\t\t$db->query($sql);\n\t}\n\n\treturn true;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_opencart", "language": "php"} {"function": "function getineqdata($str,$type='linear',$xmin=null,$xmax=null,$ymin=null,$ymax=null,$w=null,$h=null) {\n if (is_string($xmin) && strpos($xmin,',')!==false) {\n list($xmin,$xmax,$ymin,$ymax,$w,$h) = parsedrawgrid($xmin,$xmax);\n }\n if (trim($str)=='' || $xmax==$xmin || $ymax==$ymin) { return []; } // invalid\n\t$imgborder = 5;\n\t$pixelsperx = ($w - 2*$imgborder)/($xmax-$xmin);\n\t$pixelspery = ($h - 2*$imgborder)/($ymax -$ymin);\n\t$outpts = array();\n\tlist($lines,$dots,$odots,$tplines,$ineqlines) = explode(';;',$str);\n\tif ($ineqlines=='') {return array();}\n\t$ineqlines = explode('),(', substr($ineqlines,1,strlen($ineqlines)-2));\n\tforeach ($ineqlines as $k=>$val) {\n\t\tif ($type == 'linear' && $pts[0] > 10.2) { continue; }\n\t\telse if ($type == 'quadratic' && $pts[0] < 10.3) { continue; }\n\t\t$pts = explode(',',$val);\n\t\t$pts[1] = ($pts[1] - $imgborder)/$pixelsperx + $xmin;\n\t\t$pts[3] = ($pts[3] - $imgborder)/$pixelsperx + $xmin;\n\t\t$pts[5] = ($pts[5] - $imgborder)/$pixelsperx + $xmin;\n\t\t$pts[2] = ($h - $pts[2] - $imgborder)/$pixelspery + $ymin;\n\t\t$pts[4] = ($h - $pts[4] - $imgborder)/$pixelspery + $ymin;\n\t\t$pts[6] = ($h - $pts[6] - $imgborder)/$pixelspery + $ymin;\n\t\tif ($pts[0] == 10.2 || $pts[0] == 10.4) {\n\t\t\t$pts[0] = 'ne';\n\t\t} else {\n\t\t\t$pts[0] = 'eq';\n\t\t}\n\t\t$outpts[] = $pts;\n\t}\n\treturn $outpts;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?bool $default, Response $response, Database $dbForProject, Event $events) {\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_BOOLEAN,\n default: $default,\n required: $required\n );\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_BOOLEAN);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $userId, string $email, string $password, string $passwordSalt, int $passwordCpu, int $passwordMemory, int $passwordParallel, int $passwordLength, string $name, Response $response, Document $project, Database $dbForProject, Event $events) {\n $options = [\n 'salt' => $passwordSalt,\n 'costCpu' => $passwordCpu,\n 'costMemory' => $passwordMemory,\n 'costParallel' => $passwordParallel,\n 'length' => $passwordLength\n ];\n\n $user = createUser('scrypt', \\json_encode($options), $userId, $email, $password, null, $name, $project, $dbForProject, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n RepositoryInterface $repository,\n BookmarkServiceInterface $bookmarkService,\n ContentServiceInterface $contentService,\n ContentTypeServiceInterface $contentTypeService,\n FieldTypeServiceInterface $fieldTypeService,\n LanguageServiceInterface $languageService,\n LocationServiceInterface $locationService,\n NotificationServiceInterface $notificationService,\n ObjectStateServiceInterface $objectStateService,\n RoleServiceInterface $roleService,\n SearchServiceInterface $searchService,\n SectionServiceInterface $sectionService,\n TrashServiceInterface $trashService,\n URLAliasServiceInterface $urlAliasService,\n URLServiceInterface $urlService,\n URLWildcardServiceInterface $urlWildcardService,\n UserPreferenceServiceInterface $userPreferenceService,\n UserServiceInterface $userService\n ) {\n $this->repository = $repository;\n $this->bookmarkService = $bookmarkService;\n $this->contentService = $contentService;\n $this->contentTypeService = $contentTypeService;\n $this->fieldTypeService = $fieldTypeService;\n $this->languageService = $languageService;\n $this->locationService = $locationService;\n $this->notificationService = $notificationService;\n $this->objectStateService = $objectStateService;\n $this->roleService = $roleService;\n $this->searchService = $searchService;\n $this->sectionService = $sectionService;\n $this->trashService = $trashService;\n $this->urlAliasService = $urlAliasService;\n $this->urlService = $urlService;\n $this->urlWildcardService = $urlWildcardService;\n $this->userPreferenceService = $userPreferenceService;\n $this->userService = $userService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function creerDossierIB($ref_dos, $id_cli, $ref_fact, $fob, \n\t\t\t\t\t\t\t\t\t\t$fret, $assurance, $autre_frais, $num_lic, \n\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $id_march, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$ref_av, $cod, $id_util, $road_manif, $date_preal, \n\t\t\t\t\t\t\t\t\t\t$t1, $poids,$po_ref, \n\t\t\t\t\t\t\t\t\t\t$commodity, $horse, $trailer_1, $trailer_2, $ref_crf, $date_crf){\n\t\t\tinclude('connexion.php');\n\n\t\t\t/*echo '
    ref_dos = '.$ref_dos;echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    ref_fact = '.$ref_fact;echo '
    fob = '.$fob;\n\t\t\techo '
    fret = '.$fret;echo '
    assurance = '.$assurance;\n\t\t\techo '
    autre_frais = '.$autre_frais;echo '
    num_lic = '.$num_lic;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;*/\n\t\t\t//echo '
    id_mod_lic = '.$id_mod_lic;\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['ref_fact'] = $ref_fact; \n\t\t\t$entree['fob'] = $fob; $entree['fret'] = $fret; $entree['assurance'] = $assurance; \n\t\t\t$entree['autre_frais'] = $autre_frais; $entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic; $entree['id_march'] = $id_march; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['ref_av'] = $ref_av;\n\t\t\t$entree['cod'] = $cod;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t$entree['road_manif'] = $road_manif;$entree['date_preal'] = $date_preal;\n\t\t\t$entree['t1'] = $t1;$entree['poids'] = $poids;\n\t\t\t$entree['fret'] = $fret;$entree['po_ref'] = $po_ref;\n\t\t\t$entree['commodity'] = $commodity;$entree['horse'] = $horse;\n\t\t\t$entree['trailer_1'] = $trailer_1;$entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['ref_crf'] = $ref_crf;$entree['date_crf'] = $date_crf;\n\n\t\t\tif($entree['date_preal'] == '' || (!isset($entree['date_preal'])) ){\n\t\t\t\t$entree['date_preal'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fob'] == '' || (!isset($entree['fob'])) ){\n\t\t\t\t$entree['fob'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['fret'] == '' || (!isset($entree['fret'])) ){\n\t\t\t\t$entree['fret'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['assurance'] == '' || (!isset($entree['assurance'])) ){\n\t\t\t\t$entree['assurance'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['autre_frais'] == '' || (!isset($entree['autre_frais'])) ){\n\t\t\t\t$entree['autre_frais'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['poids'] == '' || (!isset($entree['poids'])) ){\n\t\t\t\t$entree['poids'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_crf'] == '' || (!isset($entree['date_crf'])) ){\n\t\t\t\t$entree['date_crf'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, ref_fact, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfret, assurance, autre_frais, num_lic, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_march, id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_av,cod, id_util, road_manif, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate_preal, t1, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpo_ref, commodity, horse, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_1, trailer_2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_crf, date_crf)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['num_lic'], $entree['id_mod_lic'], \n\t\t\t\t\t\t\t\t\t$entree['id_march'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['ref_av'], $entree['cod'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['road_manif'], $entree['date_preal'], $entree['t1'], \n\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['po_ref'], $entree['commodity'], \n\t\t\t\t\t\t\t\t\t$entree['horse'], $entree['trailer_1'], $entree['trailer_2'], \n\t\t\t\t\t\t\t\t\t$entree['ref_crf'], $entree['date_crf']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, Response $response, Database $dbForProject, Event $events) {\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_STRING,\n filter: APP_DATABASE_ATTRIBUTE_URL,\n default: $default,\n required: $required\n );\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_URL);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\tlist($x, $y) = $this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);\n\t\t\t$s = '';\n\t\t\tforeach ($values as $value) {\n\t\t\t\tif (is_array($value)) {\n\t\t\t\t\t$s .= ',[\\''.addslashes($value[1]).'\\',\\''.addslashes($value[0]).'\\']';\n\t\t\t\t} else {\n\t\t\t\t\t$s .= ',[\\''.addslashes($value).'\\',\\''.addslashes($value).'\\']';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'.\"\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t// get annotation data\n\t\t$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);\n\t\t// set additional default values\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t// build appearance stream\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';\n\t\t$text = '';\n\t\tforeach($values as $item) {\n\t\t\tif (is_array($item)) {\n\t\t\t\t$text .= $item[1].\"\\n\";\n\t\t\t} else {\n\t\t\t\t$text .= $item.\"\\n\";\n\t\t\t}\n\t\t}\n\t\t$tmpid = $this->startTemplate($w, $h, false);\n\t\t$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);\n\t\t$this->endTemplate();\n\t\t--$this->n;\n\t\t$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];\n\t\tunset($this->xobjects[$tmpid]);\n\t\t$popt['ap']['n'] .= 'Q EMC';\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Ch';\n\t\t$opt['t'] = $name;\n\t\t$opt['opt'] = $values;\n\t\tunset($opt['mk']['ca']);\n\t\tunset($opt['mk']['rc']);\n\t\tunset($opt['mk']['ac']);\n\t\tunset($opt['mk']['i']);\n\t\tunset($opt['mk']['ri']);\n\t\tunset($opt['mk']['ix']);\n\t\tunset($opt['mk']['if']);\n\t\tunset($opt['mk']['tp']);\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "private static function validateResourcePointers($mysqli, $query, $imp_session,\n $fields_checked, $dt_id, $field_idx, $recStruc, $recordType, $progress_session_id){\n\n $dt_def = $recStruc[$recordType]['dtFields'][$dt_id];\n $idx_pointer_types = $recStruc['dtFieldNamesToIndex']['rst_PtrFilteredIDs'];\n\n $res = $mysqli->query($query);\n\n if($res){\n\n $cnt = 0;\n $tot_count = $imp_session['reccount']>0?$imp_session['reccount']:1000;\n if($tot_count>4000){\n mysql__update_progress(null, $progress_session_id, false, '0,'.$tot_count.','.MSG_VALIDATION_2);\n }\n\n $wrong_records = array();\n while ($row = $res->fetch_row()){\n\n $is_error = false;\n $newvalue = array();\n $values = self::getMultiValues($row[$field_idx], $imp_session['csv_enclosure'], $imp_session['csv_mvsep']);\n foreach($values as $idx=>$r_value){\n $r_value2 = super_trim($r_value);\n if(!($r_value2=='' || $r_value2=='NULL' || $r_value2<0)){ // && $r_value2>0\n\n if (!VerifyValue::isValidPointer($dt_def[$idx_pointer_types], $r_value2, $dt_id ))\n {//not found\n $is_error = true;\n array_push($newvalue, \"$r_value\");\n }else{\n array_push($newvalue, $r_value);\n }\n }\n }\n\n if($is_error){\n $row[$field_idx] = implode($imp_session['csv_mvsep'], $newvalue);\n array_push($wrong_records, $row);\n }\n\n $cnt++;\n if($tot_count>4000 && $cnt%2000==0){\n mysql__update_progress(null, $progress_session_id, false, $cnt.','.$tot_count.','.MSG_VALIDATION_2);\n }\n }\n $res->close();\n $cnt_error = count($wrong_records);\n if($cnt_error>0){\n $error = array();\n $error[\"count_error\"] = $cnt_error;\n $error[\"recs_error\"] = array_slice($wrong_records,0,1000);\n $error[\"field_checked\"] = $fields_checked;\n $error[\"err_message\"] = \"Record pointer fields must reference an existing record of valid type in the database\";\n $error[\"short_message\"] = \"Invalid Pointers\";\n\n $imp_session['validation']['count_error'] = $imp_session['validation']['count_error']+$cnt_error;\n array_push($imp_session['validation']['error'], $error);\n\n return $imp_session;\n }\n\n }else{\n return ERR_VALIDATION_QUERY.$query;\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function PDF_add_pdflink($pdfdoc, float $bottom_left_x, float $bottom_left_y, float $up_right_x, float $up_right_y, string $filename, int $page, string $dest): void\n{\n error_clear_last();\n $result = \\PDF_add_pdflink($pdfdoc, $bottom_left_x, $bottom_left_y, $up_right_x, $up_right_y, $filename, $page, $dest);\n if ($result === false) {\n throw PdfException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function imagecopymergegray($dst_im, $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h, int $pct): void\n{\n error_clear_last();\n $result = \\imagecopymergegray($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct);\n if ($result === false) {\n throw ImageException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function ajouterUtilisateurCentreInfo($idUser, $nom, $prenom, $email, $telFixe, $telMobile, $adresse, $codePostal, $ville, $dateNaissance, $lieuNaissance, $sexe, $photo)\n\t{\n\t\ttry {\n\t\t\t$req = \"INSERT INTO utilisateur_centreinfo VALUES (:id, :nom, :prenom, :email, :telFixe, :telMobile, :adresse, :codePostal, :ville, :dateNaissance, :lieuNaissance, :sexe, :photo);\";\n\t\t\t$params = array(\n\t\t\t\t':id' => $idUser,\n\t\t\t\t':nom' => $nom,\n\t\t\t\t':prenom' => $prenom,\n\t\t\t\t':email' => $email,\n\t\t\t\t':telMobile' => $telMobile,\n\t\t\t\t':telFixe' => $telFixe,\n\t\t\t\t':dateNaissance' => $dateNaissance,\n\t\t\t\t':lieuNaissance' => $lieuNaissance,\n\t\t\t\t':adresse' => $adresse,\n\t\t\t\t':codePostal' => $codePostal,\n\t\t\t\t':ville' => $ville,\n\t\t\t\t':sexe' => $sexe,\n\t\t\t\t':photo' => $photo\n\t\t\t);\n\t\t\t$rs = $this->NonQuery($req, $params);\n\t\t\t\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'ajout de l'utilisateur dans la base de donnees.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t}\n\t\tcatch (Exception $e) {\n\t\t\techo 'Exception re\u00e7ue : ', $e->getMessage(), \"\\n\";\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function recordLogItem($success, $event, $user, $group, $comments, $patientId = null, $category = null, $logFrom = 'open-emr', $menuItemId = null, $ccdaDocId = null, $user_notes = '', $api = null)\n {\n if ($patientId == \"NULL\") {\n $patientId = null;\n }\n\n // Encrypt if applicable\n if (!isset($this->cryptoGen)) {\n $this->cryptoGen = new CryptoGen();\n }\n $encrypt = 'No';\n if (!empty($GLOBALS[\"enable_auditlog_encryption\"])) {\n // encrypt the comments field\n $comments = $this->cryptoGen->encryptStandard($comments);\n if (!empty($api)) {\n // api log\n $api['request_url'] = (!empty($api['request_url'])) ? $this->cryptoGen->encryptStandard($api['request_url']) : '';\n $api['request_body'] = (!empty($api['request_body'])) ? $this->cryptoGen->encryptStandard($api['request_body']) : '';\n $api['response'] = (!empty($api['response'])) ? $this->cryptoGen->encryptStandard($api['response']) : '';\n }\n $encrypt = 'Yes';\n } else {\n // Since storing binary elements (uuid), need to base64 to not jarble them and to ensure the auditing hashing works\n $comments = base64_encode($comments);\n }\n\n // Collect timestamp and if pertinent, collect client cert name\n $current_datetime = date(\"Y-m-d H:i:s\");\n $SSL_CLIENT_S_DN_CN = $_SERVER['SSL_CLIENT_S_DN_CN'] ?? '';\n\n // Note that no longer using checksum field in log table in OpenEMR 6.0 and onward since using the checksum in log_comment_encrypt table.\n // Need to keep to maintain backward compatibility since the checksum is used when calculating checksum stored in log_comment_encrypt table\n // in pre 6.0.\n // Note also need to use lower case for 'insert into' to prevent a endless loop\n // Steps:\n // 1. insert entry into log table\n // 2. insert associated entry into log_comment_encrypt\n // 3. if api log entry, then insert insert associated entry into api_log\n // 4. if atna server is on, then send entry to atna server\n //\n // 1. insert entry into log table\n $logEntry = [\n $current_datetime,\n $event,\n $category,\n $user,\n $group,\n $comments,\n $user_notes,\n $patientId,\n $success,\n $SSL_CLIENT_S_DN_CN,\n $logFrom,\n $menuItemId,\n $ccdaDocId\n ];\n sqlInsertClean_audit(\"insert into `log` (`date`, `event`, `category`, `user`, `groupname`, `comments`, `user_notes`, `patient_id`, `success`, `crt_user`, `log_from`, `menu_item_id`, `ccda_doc_id`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", $logEntry);\n // 2. insert associated entry (in addition to calculating and storing applicable checksums) into log_comment_encrypt\n $last_log_id = $GLOBALS['adodb']['db']->Insert_ID();\n $checksumGenerate = hash('sha3-512', implode($logEntry));\n if (!empty($api)) {\n // api log\n $ipAddress = collectIpAddresses()['ip_string'];\n $apiLogEntry = [\n $last_log_id,\n $api['user_id'],\n $api['patient_id'],\n $ipAddress,\n $api['method'],\n $api['request'],\n $api['request_url'],\n $api['request_body'],\n $api['response'],\n $current_datetime\n ];\n $checksumGenerateApi = hash('sha3-512', implode($apiLogEntry));\n } else {\n $checksumGenerateApi = '';\n }\n sqlInsertClean_audit(\n \"INSERT INTO `log_comment_encrypt` (`log_id`, `encrypt`, `checksum`, `checksum_api`, `version`) VALUES (?, ?, ?, ?, '4')\",\n [\n $last_log_id,\n $encrypt,\n $checksumGenerate,\n $checksumGenerateApi\n ]\n );\n // 3. if api log entry, then insert insert associated entry into api_log\n if (!empty($api)) {\n // api log\n sqlInsertClean_audit(\"INSERT INTO `api_log` (`log_id`, `user_id`, `patient_id`, `ip_address`, `method`, `request`, `request_url`, `request_body`, `response`, `created_time`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", $apiLogEntry);\n }\n // 4. if atna server is on, then send entry to atna server\n if ($patientId == null) {\n $patientId = 0;\n }\n $this->sendAtnaAuditMsg($user, $group, $event, $patientId, $success, $comments);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function register_string_recursive( $key, $value, $arr, $prefix, $suffix, $requires_upgrade, $type, $admin_text_context_old ) {\n\t\tif ( is_scalar( $value ) ) {\n\t\t\t/** @phpstan-ignore-next-line */\n\t\t\ticl_register_string( WPML_Admin_Texts::DOMAIN_NAME_PREFIX . $suffix, $prefix . $key, $value, true );\n\t\t\tif ( $requires_upgrade ) {\n\t\t\t\t$this->migrate_3_2( $type, $admin_text_context_old, $suffix, $prefix . $key );\n\t\t\t}\n\t\t} elseif ( ! is_null( $value ) ) {\n\t\t\tforeach ( $value as $sub_key => $sub_value ) {\n\t\t\t\tif ( isset( $arr[ $sub_key ] ) ) {\n\t\t\t\t\t$this->register_string_recursive( $sub_key,\n\t\t\t\t\t $sub_value,\n\t\t\t\t\t $arr[ $sub_key ],\n\t\t\t\t\t $prefix . '[' . $key . ']',\n\t\t\t\t\t $suffix,\n\t\t\t\t\t $requires_upgrade,\n\t\t\t\t\t $type,\n\t\t\t\t\t $admin_text_context_old );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public static function printf($string, $arg1, $arg2 = \"\", $arg3 = \"\", $arg4 = \"\", $arg5 = \"\", $arg6 = \"\", $arg7 = \"\", $arg8 = \"\", $arg9 = \"\")\n {\n return sprintf($string, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7, $arg8, $arg9);\n }", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function createDocument(\n $patient_id,\n $category_id,\n $filename,\n $mimetype,\n &$data,\n $higher_level_path = '',\n $path_depth = 1,\n $owner = 0,\n $tmpfile = null,\n $date_expires = null,\n $foreign_reference_id = null,\n $foreign_reference_table = null\n ) {\n if (\n !empty($foreign_reference_id) && empty($foreign_reference_table)\n || empty($foreign_reference_id) && !empty($foreign_reference_table)\n ) {\n return xl('Reference table and reference id must both be set');\n }\n $this->set_foreign_reference_id($foreign_reference_id);\n $this->set_foreign_reference_table($foreign_reference_table);\n // The original code used the encounter ID but never set it to anything.\n // That was probably a mistake, but we reference it here for documentation\n // and leave it empty. Logically, documents are not tied to encounters.\n\n // Create a crypto object that will be used for for encryption/decryption\n $cryptoGen = new CryptoGen();\n\n if ($GLOBALS['generate_doc_thumb']) {\n $thumb_size = ($GLOBALS['thumb_doc_max_size'] > 0) ? $GLOBALS['thumb_doc_max_size'] : null;\n $thumbnail_class = new Thumbnail($thumb_size);\n\n if (!is_null($tmpfile)) {\n $has_thumbnail = $thumbnail_class->file_support_thumbnail($tmpfile);\n } else {\n $has_thumbnail = false;\n }\n\n if ($has_thumbnail) {\n $thumbnail_resource = $thumbnail_class->create_thumbnail(null, $data);\n if ($thumbnail_resource) {\n $thumbnail_data = $thumbnail_class->get_string_file($thumbnail_resource);\n } else {\n $has_thumbnail = false;\n }\n }\n } else {\n $has_thumbnail = false;\n }\n\n $encounter_id = '';\n $this->storagemethod = $GLOBALS['document_storage_method'];\n $this->mimetype = $mimetype;\n if ($this->storagemethod == self::STORAGE_METHOD_COUCHDB) {\n // Store it using CouchDB.\n if ($GLOBALS['couchdb_encryption']) {\n $document = $cryptoGen->encryptStandard($data, null, 'database');\n } else {\n $document = base64_encode($data);\n }\n if ($has_thumbnail) {\n if ($GLOBALS['couchdb_encryption']) {\n $th_document = $cryptoGen->encryptStandard($thumbnail_data, null, 'database');\n } else {\n $th_document = base64_encode($thumbnail_data);\n }\n $this->thumb_url = $this->get_thumb_name($filename);\n } else {\n $th_document = false;\n }\n\n $couch = new CouchDB();\n $docid = $couch->createDocId('documents');\n if (!empty($th_document)) {\n $couchdata = ['_id' => $docid, 'data' => $document, 'th_data' => $th_document];\n } else {\n $couchdata = ['_id' => $docid, 'data' => $document];\n }\n $resp = $couch->save_doc($couchdata);\n if (!$resp->id || !$resp->rev) {\n return xl('CouchDB save failed');\n } else {\n $docid = $resp->id;\n $revid = $resp->rev;\n }\n\n $this->url = $filename;\n $this->couch_docid = $docid;\n $this->couch_revid = $revid;\n } else {\n // Store it remotely.\n $offSiteUpload = new PatientDocumentStoreOffsite($data);\n $offSiteUpload->setPatientId($patient_id) ?? '';\n $offSiteUpload->setRemoteFileName($filename) ?? '';\n $offSiteUpload->setRemoteMimeType($mimetype) ?? '';\n $offSiteUpload->setRemoteCategory($category_id) ?? '';\n /**\n * There must be a return to terminate processing.\n */\n $this->eventDispatcher->dispatch($offSiteUpload, PatientDocumentStoreOffsite::REMOTE_STORAGE_LOCATION);\n\n /**\n * If the response from the listener is true then the file was uploaded to another location.\n * Else resume the local file storage\n */\n\n if ($GLOBALS['documentStoredRemotely'] ?? '') {\n return xlt(\"Document was uploaded to remote storage\"); // terminate processing\n }\n\n // Storing document files locally.\n $repository = $GLOBALS['oer_config']['documents']['repository'];\n $higher_level_path = preg_replace(\"/[^A-Za-z0-9\\/]/\", \"_\", $higher_level_path);\n if ((!empty($higher_level_path)) && (is_numeric($patient_id) && $patient_id > 0)) {\n // Allow higher level directory structure in documents directory and a patient is mapped.\n $filepath = $repository . $higher_level_path . \"/\";\n } elseif (!empty($higher_level_path)) {\n // Allow higher level directory structure in documents directory and there is no patient mapping\n // (will create up to 10000 random directories and increment the path_depth by 1).\n $filepath = $repository . $higher_level_path . '/' . rand(1, 10000) . '/';\n ++$path_depth;\n } elseif (!(is_numeric($patient_id)) || !($patient_id > 0)) {\n // This is the default action except there is no patient mapping (when patient_id is 00 or direct)\n // (will create up to 10000 random directories and set the path_depth to 2).\n $filepath = $repository . $patient_id . '/' . rand(1, 10000) . '/';\n $path_depth = 2;\n $patient_id = 0;\n } else {\n // This is the default action where the patient is used as one level directory structure\n // in documents directory.\n $filepath = $repository . $patient_id . '/';\n $path_depth = 1;\n }\n\n if (!file_exists($filepath)) {\n if (!mkdir($filepath, 0700, true)) {\n return xl('Unable to create patient document subdirectory');\n }\n }\n\n // collect the drive storage filename\n $this->drive_uuid = (new UuidRegistry(['document_drive' => true]))->createUuid();\n $filenameUuid = UuidRegistry::uuidToString($this->drive_uuid);\n\n $this->url = \"file://\" . $filepath . $filenameUuid;\n if (is_numeric($path_depth)) {\n // this is for when directory structure is more than one level\n $this->path_depth = $path_depth;\n }\n\n // Store the file.\n if ($GLOBALS['drive_encryption']) {\n $storedData = $cryptoGen->encryptStandard($data, null, 'database');\n } else {\n $storedData = $data;\n }\n if (file_exists($filepath . $filenameUuid)) {\n // this should never happen with current uuid mechanism\n return xl('Failed since file already exists') . \" $filepath$filenameUuid\";\n }\n if (file_put_contents($filepath . $filenameUuid, $storedData) === false) {\n return xl('Failed to create') . \" $filepath$filenameUuid\";\n }\n\n if ($has_thumbnail) {\n // Store the thumbnail.\n $this->thumb_url = \"file://\" . $filepath . $this->get_thumb_name($filenameUuid);\n if ($GLOBALS['drive_encryption']) {\n $storedThumbnailData = $cryptoGen->encryptStandard($thumbnail_data, null, 'database');\n } else {\n $storedThumbnailData = $thumbnail_data;\n }\n if (file_exists($filepath . $this->get_thumb_name($filenameUuid))) {\n // this should never happend with current uuid mechanism\n return xl('Failed since file already exists') . $filepath . $this->get_thumb_name($filenameUuid);\n }\n if (\n file_put_contents(\n $filepath . $this->get_thumb_name($filenameUuid),\n $storedThumbnailData\n ) === false\n ) {\n return xl('Failed to create') . $filepath . $this->get_thumb_name($filenameUuid);\n }\n }\n }\n\n if (\n ($GLOBALS['drive_encryption'] && ($this->storagemethod != 1))\n || ($GLOBALS['couchdb_encryption'] && ($this->storagemethod == 1))\n ) {\n $this->set_encrypted(self::ENCRYPTED_ON);\n } else {\n $this->set_encrypted(self::ENCRYPTED_OFF);\n }\n // we need our external unique reference identifier that can be mapped back to our table.\n $docUUID = (new UuidRegistry(['table_name' => $this->_table]))->createUuid();\n $this->set_uuid($docUUID);\n $this->name = $filename;\n $this->size = strlen($data);\n $this->hash = hash('sha3-512', $data);\n $this->type = $this->type_array['file_url'];\n $this->owner = $owner ? $owner : ($_SESSION['authUserID'] ?? null);\n $this->date_expires = $date_expires;\n $this->set_foreign_id($patient_id);\n $this->persist();\n $this->populate();\n if (is_numeric($this->get_id()) && is_numeric($category_id)) {\n $sql = \"REPLACE INTO categories_to_documents SET category_id = ?, document_id = ?\";\n $this->_db->Execute($sql, array($category_id, $this->get_id()));\n }\n\n return '';\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function genererGraphique($id, $type, $hauteur, $largeur, $titre, $valeurs, $nom, $nb, $total)\n {\n $couleurs = array('red', 'blue', 'green', 'pink', 'orange', 'brown', 'gray', 'lime', 'maroon', 'olive', 'navy', 'teal', 'yellow', 'purple');\n echo \"\n \";\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {\n\t\tif (3 > $ns) {\n\t\t\t$ns = 3;\n\t\t}\n\t\tif ($draw_circle) {\n\t\t\t$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);\n\t\t}\n\t\t$p = array();\n\t\tfor ($i = 0; $i < $ns; ++$i) {\n\t\t\t$a = $angle + ($i * 360 / $ns);\n\t\t\t$a_rad = deg2rad((float) $a);\n\t\t\t$p[] = $x0 + ($r * sin($a_rad));\n\t\t\t$p[] = $y0 + ($r * cos($a_rad));\n\t\t}\n\t\t$this->Polygon($p, $style, $line_style, $fill_color);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function (string $bucketId, string $fileId, ?string $name, ?array $permissions, Response $response, Database $dbForProject, Document $user, string $mode, Event $events) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_UPDATE);\n $valid = $validator->isValid($bucket->getUpdate());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n // Read permission should not be required for update\n $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n\n if ($file->isEmpty()) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);\n }\n\n // Map aggregate permissions into the multiple permissions they represent.\n $permissions = Permission::aggregate($permissions, [\n Database::PERMISSION_READ,\n Database::PERMISSION_UPDATE,\n Database::PERMISSION_DELETE,\n ]);\n\n // Users can only manage their own roles, API keys and Admin users can manage any\n $roles = Authorization::getRoles();\n if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles) && !\\is_null($permissions)) {\n foreach (Database::PERMISSIONS as $type) {\n foreach ($permissions as $permission) {\n $permission = Permission::parse($permission);\n if ($permission->getPermission() != $type) {\n continue;\n }\n $role = (new Role(\n $permission->getRole(),\n $permission->getIdentifier(),\n $permission->getDimension()\n ))->toString();\n if (!Authorization::isRole($role)) {\n throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \\implode(', ', $roles) . ')');\n }\n }\n }\n }\n\n if (\\is_null($permissions)) {\n $permissions = $file->getPermissions() ?? [];\n }\n\n $file->setAttribute('$permissions', $permissions);\n\n if (!is_null($name)) {\n $file->setAttribute('name', $name);\n }\n\n if ($fileSecurity && !$valid) {\n try {\n $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file);\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n } else {\n $file = Authorization::skip(fn() => $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file));\n }\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ->setParam('fileId', $file->getId())\n ->setContext('bucket', $bucket)\n ;\n\n $response->dynamic($file, Response::MODEL_FILE);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function choice_widget_options($view, $form, $choices, $translation_domain, $is_selected, $value, $formHelper,\n $translatorHelper)\n {\n ?>\n $choice): ?>\n \n escape($translatorHelper->trans($index, array(), $translation_domain)) ?>\">\n block($form, 'choice_widget_options', array('choices' => $choice)) ?>\n \n \n \n \n \n merge\";\n\n\t $result = MERGE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1 && $isOpenY1 && $isOpenY2;\n\t $isOpenZ2 = $isOpenX2;\n\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1 && $isOpenY1;\n\t $isOpenZ2 = $isOpenX2 && $isOpenY2;\n\n\t break;\n\tcase LT:\n\t // echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT. \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenX1 && $isOpenY1;\n\t $isOpenZ2 = $isOpenY2;\n\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED. \" -> merge\";\n\n\t $result = MERGE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1 && $isOpenY1;\n\t $isOpenZ2 = $isOpenX2;\n\n\t break;\n\n\tdefault:\n\t // echo \"error\";\n }\n\n break;\n\n case EQUAL_RIGHT:\n // echo \"here \" . EQUAL_RIGHT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t // echo \" error \" . EQUAL_LEFT;\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenX2 && $isOpenY1 && $isOpenY2;\n\n\t break;\n\tcase LT:\n\t // echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT;\n\n\t if ($isOpenX2 && $isOpenY1) {\n\t // echo \" -> SKIP\";\n\n\t $result = SKIP;\n\t } else {\n\t // echo \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenY2;\n\t }\n\t break;\n\tcase INCLUDED:\n\t // echo \" error \" . INCLUDED;\n\t break;\n\n\tdefault:\n\t // echo \"error\";\n }\n\n break;\n\n case LT:\n // echo \"here \" . LT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t // echo \" + \" . EQUAL_LEFT;\n\n\t if ($isOpenX1 && $isOpenY2) {\n\t // echo \" -> insert\";\n\n\t $result = INSERT;\n\t } else {\n\t // echo \" -> merge\";\n\n\t $result = MERGE;\n\t $z1 = $y1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenX2;\n\t }\n\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $y1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenX2 && $isOpenY2;\n\t break;\n\tcase LT:\n\t // echo \" + \" . LT . \" -> insert\";\n\n\t $result = INSERT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $y1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenY2;\n\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED . \" -> merge\";\n\n\t $result = MERGE;\n\t $z1 = $y1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenX2;\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case GT:\n // echo \"here \" . GT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase GT:\n\t // echo \" + \" . GT . \" -> SKIP\";\n\t $result = SKIP;\n\t break;\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case INCLUDED:\n // echo \"here \" . INCLUDED;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t // echo \" error \" . EQUAL_LEFT;\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenX2 && $isOpenY2;\n\t break;\n\tcase LT:\n\t // echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT . \" -> expand_right\";\n\n\t $result = EXPAND_RIGHT;\n\t $z1 = $x1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenY2;\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED . \" -> merge\";\n\n\t $result = MERGE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenX2;\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n // fallthrough\n default:\n echo \"error\";\n }\n\n // echo \" \";\n\n if ($result == ERROR || $result == INSERT || $result == SKIP) {\n return array(\"result\" => $result);\n } else {\n return array(\"result\" => $result,\n \"left-border\" => $z1, \"right-border\" => $z2,\n \"is-open-left\" => $isOpenZ1, \"is-open-right\" => $isOpenZ2);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function updateItemOnEventJsCode(\n $toobserve,\n $toupdate,\n $url,\n $parameters = [],\n $events = [\"change\"],\n $minsize = -1,\n $buffertime = -1,\n $forceloadfor = [],\n $display = true\n ) {\n\n if (is_array($toobserve)) {\n $zones = $toobserve;\n } else {\n $zones = [$toobserve];\n }\n $output = '';\n foreach ($zones as $zone) {\n foreach ($events as $event) {\n if ($buffertime > 0) {\n $output .= \"var last$zone$event = 0;\";\n }\n $output .= Html::jsGetElementbyID(Html::cleanId($zone)) . \".on(\n '$event',\n function(event) {\";\n // TODO manage buffer time !!?\n // if ($buffertime > 0) {\n // $output.= \"var elapsed = new Date().getTime() - last$zone$event;\n // last$zone$event = new Date().getTime();\n // if (elapsed < $buffertime) {\n // return;\n // }\";\n // }\n\n $condition = '';\n if ($minsize >= 0) {\n $condition = Html::jsGetElementbyID(Html::cleanId($zone)) . \".val().length >= $minsize \";\n }\n if (count($forceloadfor)) {\n foreach ($forceloadfor as $value) {\n if (!empty($condition)) {\n $condition .= \" || \";\n }\n $condition .= Html::jsGetElementbyID(Html::cleanId($zone)) . \".val() == '$value'\";\n }\n }\n if (!empty($condition)) {\n $output .= \"if ($condition) {\";\n }\n $output .= self::updateItemJsCode($toupdate, $url, $parameters, $toobserve, false);\n if (!empty($condition)) {\n $output .= \"}\";\n }\n $output .= \"}\";\n $output .= \");\\n\";\n }\n }\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (string $password, string $oldPassword, ?\\DateTime $requestTimestamp, Response $response, Document $user, Document $project, Database $dbForProject, Event $events) {\n\n // Check old password only if its an existing user.\n if (!empty($user->getAttribute('passwordUpdate')) && !Auth::passwordVerify($oldPassword, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions'))) { // Double check user password\n throw new Exception(Exception::USER_INVALID_CREDENTIALS);\n }\n\n $newPassword = Auth::passwordHash($password, Auth::DEFAULT_ALGO, Auth::DEFAULT_ALGO_OPTIONS);\n $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;\n $history = $user->getAttribute('passwordHistory', []);\n if ($historyLimit > 0) {\n $validator = new PasswordHistory($history, $user->getAttribute('hash'), $user->getAttribute('hashOptions'));\n if (!$validator->isValid($password)) {\n throw new Exception(Exception::USER_PASSWORD_RECENTLY_USED);\n }\n\n $history[] = $newPassword;\n $history = array_slice($history, (count($history) - $historyLimit), $historyLimit);\n }\n\n if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) {\n $personalDataValidator = new PersonalData($user->getId(), $user->getAttribute('email'), $user->getAttribute('name'), $user->getAttribute('phone'));\n if (!$personalDataValidator->isValid($password)) {\n throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA);\n }\n }\n\n $user\n ->setAttribute('password', $newPassword)\n ->setAttribute('passwordHistory', $history)\n ->setAttribute('passwordUpdate', DateTime::now())\n ->setAttribute('hash', Auth::DEFAULT_ALGO)\n ->setAttribute('hashOptions', Auth::DEFAULT_ALGO_OPTIONS);\n\n $user = $dbForProject->withRequestTimestamp($requestTimestamp, fn () => $dbForProject->updateDocument('users', $user->getId(), $user));\n\n $events->setParam('userId', $user->getId());\n\n $response->dynamic($user, Response::MODEL_ACCOUNT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function ActualizaDatosCierreUsuarios($id_inscripcion, $rut, $porcentaje_asistencia, $caso_especial, $nota, $estado, $viatico_utilizado, $movilizacion_utilizado)\n{\n\tglobal $c_host,$c_user,$c_pass,$c_db;\n\t$database = new database($c_host,$c_user,$c_pass);\n\t$database->setDb($c_db);\n\t\n\t$sql = \"UPDATE tbl_inscripcion_cierre\n\t\t\tSET \n\t\t\tporcentaje_asistencia= '$porcentaje_asistencia', \n\t\t\tcaso_especial= '$caso_especial', \n\t\t\tnota= '$nota', \n\t\t\testado= '$estado', \n\t\t\tviatico_utilizado= '$viatico_utilizado', \n\t\t\tmovilizacion_utilizada= '$movilizacion_utilizado' \n\t\t\t\n\t\t\t\n\n\n\n\n\t\t\tWHERE id_inscripcion = '$id_inscripcion' and rut='$rut'\";\n\t$database->setquery($sql);\n\t$database->query();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function addPortalMailboxMail(\n $owner,\n $newtext,\n $authorized = '0',\n $activity = '1',\n $title = 'Unassigned',\n $assigned_to = '',\n $datetime = '',\n $message_status = \"New\",\n $master_note = '0',\n $sid = '',\n $sn = '',\n $rid = '',\n $rn = '',\n $replyid = 0\n): int {\n\n if (empty($datetime)) {\n $datetime = date('Y-m-d H:i:s');\n }\n\n $user = $_SESSION['portal_username'] ? $_SESSION['portal_username'] : $_SESSION['authUser'];\n // make inactive if set as Done\n if ($message_status == \"Done\") {\n $activity = 0;\n }\n\n $body = $newtext;\n if ($master_note == '0') {\n $n = sqlQueryNoLog(\"SELECT MAX(id) as newid from onsite_mail\");\n $master_note = $n['newid'] + 1;\n }\n\n if ($replyid) {\n if ($owner != $sid) {\n $hold = $master_note;\n $master_note = $replyid;\n $replyid = $hold;\n } else {\n $replyid = $master_note;\n }\n } elseif ($owner != $sid) {\n $replyid = $master_note - 1;\n } else {\n $replyid = $master_note;\n }\n\n return sqlInsert(\n \"INSERT INTO onsite_mail (date, body, owner, user, groupname, \" .\n \"authorized, activity, title, assigned_to, message_status, mail_chain, sender_id, sender_name, recipient_id, recipient_name, reply_mail_chain) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)\",\n array($datetime, $body, $owner, $user, 'Default', $authorized, $activity, $title, $assigned_to, $message_status,$master_note,$sid,$sn,$rid,$rn,$replyid)\n );\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function _renderMenu(Zend_Navigation_Container $container,\n $ulClass,\n $indent,\n $innerIndent,\n $minDepth,\n $maxDepth,\n $onlyActive,\n $expandSibs,\n $ulId,\n $addPageClassToLi,\n $activeClass,\n $parentClass,\n $renderParentClass)\n {\n $html = '';\n\n // find deepest active\n if ($found = $this->findActive($container, $minDepth, $maxDepth)) {\n $foundPage = $found['page'];\n $foundDepth = $found['depth'];\n } else {\n $foundPage = null;\n }\n\n // create iterator\n $iterator = new RecursiveIteratorIterator($container,\n RecursiveIteratorIterator::SELF_FIRST);\n if (is_int($maxDepth)) {\n $iterator->setMaxDepth($maxDepth);\n }\n\n // iterate container\n $prevDepth = -1;\n foreach ($iterator as $page) {\n $depth = $iterator->getDepth();\n $isActive = $page->isActive(true);\n if ($depth < $minDepth || !$this->accept($page)) {\n // page is below minDepth or not accepted by acl/visibilty\n continue;\n } else if ($expandSibs && $depth > $minDepth) {\n // page is not active itself, but might be in the active branch\n $accept = false;\n if ($foundPage) {\n if ($foundPage->hasPage($page)) {\n // accept if page is a direct child of the active page\n $accept = true;\n } else if ($page->getParent()->isActive(true)) {\n // page is a sibling of the active branch...\n $accept = true;\n }\n }\n if (!$isActive && !$accept) {\n continue;\n }\n } else if ($onlyActive && !$isActive) {\n // page is not active itself, but might be in the active branch\n $accept = false;\n if ($foundPage) {\n if ($foundPage->hasPage($page)) {\n // accept if page is a direct child of the active page\n $accept = true;\n } else if ($foundPage->getParent()->hasPage($page)) {\n // page is a sibling of the active page...\n if (!$foundPage->hasPages() ||\n is_int($maxDepth) && $foundDepth + 1 > $maxDepth) {\n // accept if active page has no children, or the\n // children are too deep to be rendered\n $accept = true;\n }\n }\n }\n\n if (!$accept) {\n continue;\n }\n }\n\n // make sure indentation is correct\n $depth -= $minDepth;\n $myIndent = $indent . str_repeat($innerIndent, $depth * 2);\n\n if ($depth > $prevDepth) {\n $attribs = array();\n\n // start new ul tag\n if (0 == $depth) {\n $attribs = array(\n 'class' => $ulClass,\n 'id' => $ulId,\n );\n }\n\n // We don't need a prefix for the menu ID (backup)\n $skipValue = $this->_skipPrefixForId;\n $this->skipPrefixForId();\n\n $html .= $myIndent . '_htmlAttribs($attribs)\n . '>'\n . $this->getEOL();\n\n // Reset prefix for IDs\n $this->_skipPrefixForId = $skipValue;\n } else if ($prevDepth > $depth) {\n // close li/ul tags until we're at current depth\n for ($i = $prevDepth; $i > $depth; $i--) {\n $ind = $indent . str_repeat($innerIndent, $i * 2);\n $html .= $ind . $innerIndent . '' . $this->getEOL();\n $html .= $ind . '' . $this->getEOL();\n }\n // close previous li tag\n $html .= $myIndent . $innerIndent . '' . $this->getEOL();\n } else {\n // close previous li tag\n $html .= $myIndent . $innerIndent . '' . $this->getEOL();\n }\n\n // render li tag and page\n $liClasses = array();\n // Is page active?\n if ($isActive) {\n $liClasses[] = $activeClass;\n }\n // Add CSS class from page to LI?\n if ($addPageClassToLi) {\n $liClasses[] = $page->getClass();\n }\n // Add CSS class for parents to LI?\n if ($renderParentClass && $page->hasChildren()) {\n // Check max depth\n if ((is_int($maxDepth) && ($depth + 1 < $maxDepth))\n || !is_int($maxDepth)\n ) {\n $liClasses[] = $parentClass;\n }\n }\n\n $html .= $myIndent . $innerIndent . '_htmlAttribs(array('class' => implode(' ', $liClasses)))\n . '>' . $this->getEOL()\n . $myIndent . str_repeat($innerIndent, 2)\n . $this->htmlify($page)\n . $this->getEOL();\n\n // store as previous depth for next iteration\n $prevDepth = $depth;\n }\n\n if ($html) {\n // done iterating container; close open ul/li tags\n for ($i = $prevDepth+1; $i > 0; $i--) {\n $myIndent = $indent . str_repeat($innerIndent . $innerIndent, $i - 1);\n $html .= $myIndent . $innerIndent . '' . $this->getEOL()\n . $myIndent . '' . $this->getEOL();\n }\n $html = rtrim($html, $this->getEOL());\n }\n\n return $html;\n }", "smellKey": "S107", "smellId": null, "repo": "Testtarosa_Bill-System", "language": "php"} {"function": "function test_rules_clinic_batch_method($provider = '', $type = '', $dateTarget = '', $mode = '', $plan = '', $organize_mode = 'default', $options = array(), $pat_prov_rel = 'primary', $batchSize = '', $report_id = null)\n{\n\n // Default to a batchsize, if empty\n if (empty($batchSize)) {\n $batchSize = 100;\n }\n\n // Collect total number of pertinent patients (to calculate batching parameters)\n // note for group_calculation we will have some inefficiencies here\n $totalNumPatients = (int)buildPatientArray('', $provider, $pat_prov_rel, null, null, true);\n\n // Cycle through the batches and collect/combine results\n if (($totalNumPatients % $batchSize) > 0) {\n // not perfectly divisible\n $totalNumberBatches = floor($totalNumPatients / $batchSize) + 1;\n } else {\n // perfectly divisible\n $totalNumberBatches = floor($totalNumPatients / $batchSize);\n }\n\n (new SystemLogger())->debug(\n \"test_rules_clinic_batch_method()\",\n ['totalNumPatients' => $totalNumPatients, 'totalNumberBatches' => $totalNumberBatches]\n );\n\n // Fix things in the $options array(). This now stores the number of labs to be used in the denominator in the AMC report.\n // The problem with this variable is that is is added in every batch. So need to fix it by dividing this number by the number\n // of planned batches(note the fixed array will go into the test_rules_clinic function, however the original will be used\n // in the report storing/tracking engine.\n $options_modified = $options;\n if (!empty($options_modified['labs_manual'])) {\n $options_modified['labs_manual'] = $options_modified['labs_manual'] / $totalNumberBatches;\n }\n\n // Prepare the database to track/store results\n $fields = array('provider' => $provider,'mode' => $mode,'plan' => $plan,'organize_mode' => $organize_mode,'pat_prov_rel' => $pat_prov_rel);\n if (is_array($dateTarget)) {\n $fields = array_merge($fields, array('date_target' => $dateTarget['dateTarget']));\n $fields = array_merge($fields, array('date_begin' => $dateTarget['dateBegin']));\n } else {\n if (empty($dateTarget)) {\n $fields = array_merge($fields, array('date_target' => date(\"Y-m-d H:i:s\")));\n } else {\n $fields = array_merge($fields, array('date_target' => $dateTarget));\n }\n }\n\n if (!empty($options)) {\n foreach ($options as $key => $value) {\n $fields = array_merge($fields, array($key => $value));\n }\n }\n\n $report_id = beginReportDatabase($type, $fields, $report_id);\n setTotalItemsReportDatabase($report_id, $totalNumPatients);\n\n // Set ability to itemize report if this feature is turned on\n if (\n ( ($type == \"active_alert\" || $type == \"passive_alert\") && ($GLOBALS['report_itemizing_standard']) ) ||\n ( ($type == \"cqm\" || $type == \"cqm_2011\" || $type == \"cqm_2014\") && ($GLOBALS['report_itemizing_cqm']) ) ||\n ( (CertificationReportTypes::isAMCReportType($type)) && ($GLOBALS['report_itemizing_amc']) )\n ) {\n $GLOBALS['report_itemizing_temp_flag_and_id'] = $report_id;\n } else {\n $GLOBALS['report_itemizing_temp_flag_and_id'] = 0;\n }\n\n for ($i = 0; $i < $totalNumberBatches; $i++) {\n // If itemization is turned on, then reset the rule id iterator\n if ($GLOBALS['report_itemizing_temp_flag_and_id']) {\n $GLOBALS['report_itemized_test_id_iterator'] = 1;\n }\n\n $dataSheet_batch = test_rules_clinic($provider, $type, $dateTarget, $mode, '', $plan, $organize_mode, $options_modified, $pat_prov_rel, (($batchSize * $i) + 1), $batchSize);\n $dataSheet = array();\n if ($i == 0) {\n // For first cycle, simply copy it to dataSheet\n $dataSheet = $dataSheet_batch;\n } else {\n //debug\n //error_log(\"CDR: \".print_r($dataSheet,TRUE),0);\n //error_log(\"CDR: \".($batchSize*$i).\" records\",0);\n\n // Integrate batch results into main dataSheet\n foreach ($dataSheet_batch as $key => $row) {\n if (!$row['is_sub']) {\n //skip this stuff for the sub entries (and use previous main entry in percentage calculation)\n $total_patients = $dataSheet[$key]['total_patients'] + $row['total_patients'];\n $dataSheet[$key]['total_patients'] = $total_patients;\n $excluded = $dataSheet[$key]['excluded'] + $row['excluded'];\n $dataSheet[$key]['excluded'] = $excluded;\n $pass_filter = $dataSheet[$key]['pass_filter'] + $row['pass_filter'];\n $dataSheet[$key]['pass_filter'] = $pass_filter;\n }\n\n $pass_target = $dataSheet[$key]['pass_target'] + $row['pass_target'];\n $dataSheet[$key]['pass_target'] = $pass_target;\n $dataSheet[$key]['percentage'] = calculate_percentage($pass_filter, $excluded, $pass_target);\n }\n }\n\n //Update database to track results\n updateReportDatabase($report_id, ($total_patients ?? null));\n }\n\n // Record results in database and send to screen, if applicable.\n if (!empty($dataSheet)) {\n finishReportDatabase($report_id, json_encode($dataSheet));\n return $dataSheet;\n } else {\n // make sure the report at least completes even if we have nothing here.\n finishReportDatabase($report_id, json_encode([]));\n return [];\n }\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n\t\t?string $inNumRG = null,\n\t\t?string $inDigitoRG = null,\n\t\t?string $inUFRG = null,\n\t\t?string $inCPF = null,\n\t\t?string $inNumNIS = null,\n\t\t?string $inNumINEP = null,\n\t\t?string $inNumCertidaoNova = null,\n\t\t?CertidaoNasc $CertidaoNasc = null\n\t) {\n\t\t$this->inNumRG = $inNumRG;\n\t\t$this->inDigitoRG = $inDigitoRG;\n\t\t$this->inUFRG = $inUFRG;\n\t\t$this->inCPF = $inCPF;\n\t\t$this->inNumNIS = $inNumNIS;\n\t\t$this->inNumINEP = $inNumINEP;\n\t\t$this->inNumCertidaoNova = $inNumCertidaoNova;\n\t\t$this->CertidaoNasc = $CertidaoNasc;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function saveDatosGeneralesFacturaData($factur_numdoc, $factur_tipdocid, $factur_proveeid, $factur_proveerut,\n $factur_servid, $factur_servotro, $factur_montoto, $factur_montonet, $factur_impuest,\n $factur_fecemision, $factur_ota, $factur_numota, $factur_cuentaid, $factur_cuenta,\n $factur_proyectid, $factur_proyecto, $factur_curso, $factur_otanombre, $factur_cui,\n $factur_respgast, $factur_observacion, $factur_mes, $factur_anual, $factur_status, $factura_proveenom,\n $rut_created,$factur_cuenta_nombre\n)\n{\n $connexion = new DatabasePDO();\n $factur_created = date(\"Y-m-d H:i:s\");\n $sql = \"INSERT INTO tbl_finanza_facturas (factur_numdoc, factur_tipdocid, factur_proveeid, factur_proveerut,\n factur_servid, factur_servotro, factur_montoto, factur_montonet, factur_impuest,\n factur_fecemision, factur_ota, factur_numota, factur_cuentaid, factur_cuenta,\n factur_proyectid, factur_proyecto, factur_curso, factur_otanombre, factur_cui,\n factur_respgast, factur_observacion, factur_mes, factur_anual,\n factur_created, factur_status,factur_proveenom, factur_rut_create,factur_cuenta_nombre)\nVALUES (:factur_numdoc, :factur_tipdocid, :factur_proveeid, :factur_proveerut,\n :factur_servid, :factur_servotro, :factur_montoto, :factur_montonet, :factur_impuest,\n :factur_fecemision, :factur_ota, :factur_numota, :factur_cuentaid, :factur_cuenta,\n :factur_proyectid, :factur_proyecto, :factur_curso, :factur_otanombre, :factur_cui,\n :factur_respgast, :factur_observacion, :factur_mes, :factur_anual,\n :factur_created, :factur_status, :factura_proveenom, :rut_created, :factur_cuenta_nombre)\";\n $connexion->query($sql);\n $connexion->bind(':factur_numdoc', $factur_numdoc);\n $connexion->bind(':factur_tipdocid', $factur_tipdocid);\n $connexion->bind(':factur_proveeid', $factur_proveeid);\n $connexion->bind(':factur_proveerut', $factur_proveerut);\n $connexion->bind(':factur_servid', $factur_servid);\n $connexion->bind(':factur_servotro', $factur_servotro);\n $connexion->bind(':factur_montoto', $factur_montoto);\n $connexion->bind(':factur_montonet', $factur_montonet);\n $connexion->bind(':factur_impuest', $factur_impuest);\n $connexion->bind(':factur_fecemision', $factur_fecemision);\n $connexion->bind(':factur_ota', $factur_ota);\n $connexion->bind(':factur_numota', $factur_numota);\n $connexion->bind(':factur_cuentaid', $factur_cuentaid);\n $connexion->bind(':factur_cuenta', $factur_cuenta);\n $connexion->bind(':factur_proyectid', $factur_proyectid);\n $connexion->bind(':factur_proyecto', $factur_proyecto);\n $connexion->bind(':factur_curso', $factur_curso);\n $connexion->bind(':factur_otanombre', $factur_otanombre);\n $connexion->bind(':factur_cui', $factur_cui);\n $connexion->bind(':factur_respgast', $factur_respgast);\n $connexion->bind(':factur_observacion', $factur_observacion);\n $connexion->bind(':factur_mes', $factur_mes);\n $connexion->bind(':factur_anual', $factur_anual);\n $connexion->bind(':factur_created', $factur_created);\n $connexion->bind(':factur_status', $factur_status);\n $connexion->bind(':factura_proveenom', $factura_proveenom);\n $connexion->bind(':rut_created', $rut_created);\n $connexion->bind(':factur_cuenta_nombre', $factur_cuenta_nombre);\n $connexion->execute();\n\n return $connexion->lastInsertId();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function handleControlRequest(\n bool $srTakeAction,\n bool $replicaChangePrimary,\n bool $srReplicaServerControl,\n string|null $srReplicaAction,\n bool $srReplicaSkipError,\n int $srSkipErrorsCount,\n string|null $srReplicaControlParam,\n string $username,\n string $pmaPassword,\n string $hostname,\n int $port,\n ): void {\n if (! $srTakeAction) {\n return;\n }\n\n $refresh = false;\n $result = false;\n $messageSuccess = '';\n $messageError = '';\n\n if ($replicaChangePrimary && ! Config::getInstance()->settings['AllowArbitraryServer']) {\n $_SESSION['replication']['sr_action_status'] = 'error';\n $_SESSION['replication']['sr_action_info'] = __(\n 'Connection to server is disabled, please enable'\n . ' $cfg[\\'AllowArbitraryServer\\'] in phpMyAdmin configuration.',\n );\n } elseif ($replicaChangePrimary) {\n $result = $this->handleRequestForReplicaChangePrimary($username, $pmaPassword, $hostname, $port);\n } elseif ($srReplicaServerControl) {\n $result = $this->handleRequestForReplicaServerControl($srReplicaAction, $srReplicaControlParam);\n $refresh = true;\n\n switch ($srReplicaAction) {\n case 'start':\n $messageSuccess = __('Replication started successfully.');\n $messageError = __('Error starting replication.');\n break;\n case 'stop':\n $messageSuccess = __('Replication stopped successfully.');\n $messageError = __('Error stopping replication.');\n break;\n case 'reset':\n $messageSuccess = __('Replication resetting successfully.');\n $messageError = __('Error resetting replication.');\n break;\n default:\n $messageSuccess = __('Success.');\n $messageError = __('Error.');\n break;\n }\n } elseif ($srReplicaSkipError) {\n $result = $this->handleRequestForReplicaSkipError($srSkipErrorsCount);\n }\n\n if ($refresh) {\n $response = ResponseRenderer::getInstance();\n if ($response->isAjax()) {\n $response->setRequestStatus($result);\n $response->addJSON(\n 'message',\n $result\n ? Message::success($messageSuccess)\n : Message::error($messageError),\n );\n } else {\n $response->redirect(\n './index.php?route=/server/replication' . Url::getCommonRaw($GLOBALS['urlParams'], '&'),\n );\n }\n }\n\n unset($refresh);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n TranslatorInterface $translator,\n DatasetFactory $datasetFactory,\n FormFactory $formFactory,\n UrlGeneratorInterface $urlGenerator,\n PermissionResolver $permissionResolver,\n UserService $userService,\n UserSettingService $userSettingService,\n EventDispatcherInterface $eventDispatcher\n ) {\n parent::__construct($twig, $translator, $eventDispatcher);\n\n $this->datasetFactory = $datasetFactory;\n $this->formFactory = $formFactory;\n $this->urlGenerator = $urlGenerator;\n $this->permissionResolver = $permissionResolver;\n $this->userService = $userService;\n $this->userSettingService = $userSettingService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function info_modifierUneInscription($num, $nom, $prenom, $adresse, $cp, $ville, $lat, $lon, $sexe, $ddn, $date, $tel1, $tel2, $email) {\n\n $req = \"UPDATE `info_inscriptions` SET `nom_inscription` = '\".strtoupper($nom).\"', `prenom_inscription` = '\".ucfirst($prenom).\"', `adresse_inscription` = '\".strtoupper($adresse).\"', `cp_inscription` = '$cp', `ville_inscription` = '\".strtoupper($ville).\"', `lat_inscription` = '$lat', `lon_inscription` = '$lon', `sexe_inscription` = '$sexe', `ddn_inscription` = '$ddn', `date_inscription` = '$date', `tel1_inscription` = '$tel1', `tel2_inscription` = '$tel2', `email_inscription` = '$email' WHERE `id_inscription` = $num\";\n\n\t\t$rs = PdoBD::$monPdo->query($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la lecture des donnees ..\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t$laLigne = $rs->fetchAll();\n\t\treturn $laLigne; \n \n echo $req;\n \n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function updateMultipleFilesPopUp($debut, $fin, $klsa_arriv, \n\t\t\t $crossing_date, $wiski_arriv, $wiski_dep, \n\t\t\t $amicong_arriv, $insp_receiv, $ir, \n\t\t\t $ref_crf, $date_crf, $dgda_in, $ref_decl,\n\t\t\t $ref_liq, $date_liq, $ref_quit, \n\t\t\t $date_quit, $dgda_out, $custom_deliv, $cleared, \n\t\t\t $dispatch_deliv, $statut, $remarque, \n\t\t\t $nbre, $id_cli, $id_mod_trans, $id_mod_lic, \n\t\t\t $commodity, $type){\n\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['debut'] = $debut;\n\t\t\t$entree['fin'] = $fin;\n\n\t\t\t/*echo '
    debut = '.$debut;\n\t\t\techo '
    fin = '.$fin;\n\t\t\techo '
    dgda_out = '.$dgda_out;\n\t\t\techo '
    type = '.$type;\n\t\t\techo '
    id_cli = '.$id_cli;\n\t\t\techo '
    date_val = '.$date_val;\n\t\t\techo '
    fournisseur = '.$fournisseur;\n\t\t\techo '
    commodity = '.$commodity;\n\t\t\techo '
    fob = '.$fob;*/\n\t\t\t/*$nbre = $this-> getNombreDossierClientModeTransportModeLicenceUpdate($id_cli, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity, $debut, $fin);\n\n\t\t\tfor ($i=1; $i <= $nbre ; $i++) { \n\t\t\t\t# code...\n\t\t\t}*/\n\t\t\t$sqlType = '';\n\t\t\t$sqlClient = '';\n\n\t\t\tif (isset($type) && ($type == 'TOTAL FILES')) {\n\t\t\t\t$sqlType = '';\n\t\t\t}\n\n\t\t\tif (isset($id_cli) && ($id_cli != '')) {\n\t\t\t\t$sqlClient = ' AND d.id_cli = '.$id_cli;\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'CLEARING COMPLETED')) {\n\t\t\t\t$sqlType = \" AND d.cleared = '1'\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'FILES IN PROCESS')) {\n\t\t\t\t$sqlType = \" AND d.cleared = '0'\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'CANCELLED')) {\n\t\t\t\t$sqlType = \" AND d.cleared = '2'\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'KASUMBALESA')) {\n\t\t\t\t$sqlType = \" AND DATE(d.arrival_date) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'WISKI ARRIVAL')) {\n\t\t\t\t$sqlType = \" AND DATE(d.wiski_arriv) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'UNDER PROCESS AT WISKI')) {\n\t\t\t\t$sqlType = \" AND (d.wiski_arriv IS NOT NULL AND d.wiski_arriv <> '')\n\t\t\t\t\t\t\t\t\t\t\t\tAND (d.wiski_dep IS NULL OR d.wiski_dep = '')\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'WISKI DEPARTURE')) {\n\t\t\t\t$sqlType = \" AND DATE(d.wiski_dep) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'AWAIT CRF')) {\n\t\t\t\t$sqlType = \" AND (d.wiski_dep IS NOT NULL AND d.wiski_dep <> '')\n\t\t\t\t\t\t\t\t\t\t\t\tAND ( (d.date_crf IS NULL OR d.date_crf = '') AND (d.ref_crf IS NULL OR d.ref_crf = '' ))\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'DGDA IN')) {\n\t\t\t\t$sqlType = \" AND DATE(dgda_in) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'UNDER PROCESS AT DGDA')) {\n\t\t\t\t$sqlType = \" AND (d.dgda_in IS NOT NULL AND d.dgda_in <> '')\n\t\t\t\t\t\t\t\t\t\t\t\tAND (d.dgda_out IS NULL OR d.dgda_out = '')\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'LIQUIDATED / AWAIT QUITTANCE')) {\n\t\t\t\t$sqlType = \" AND ( (d.date_liq IS NOT NULL OR d.date_liq <> '')\n\t\t\t\t\t\t\t\t\t\t\t\t\tOR (d.ref_liq IS NOT NULL OR d.ref_liq <> '') )\n\t\t\t\t\t\t\t\t\t\t\t\tAND ( (d.date_quit IS NULL AND d.date_quit = '') \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND (d.ref_quit IS NULL AND d.ref_quit = '') )\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'QUITTANCE')) {\n\t\t\t\t$sqlType = \" AND DATE(d.date_quit) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'DGDA OUT')) {\n\t\t\t\t$sqlType = \" AND DATE(d.dgda_out) = CURRENT_DATE()\";\n\t\t\t}\n\n\t\t\tif (isset($type) && ($type == 'FILES CLEARED WAITING INVOICE')) {\n\t\t\t\t$sqlType = \" AND d.cleared = '1'\n\t\t\t\t\t\t\t\t\t\t\t\tAND d.facture = '0'\";\n\t\t\t}\n\n\t\t\t$sql1 = \"\";\n\t\t\tif (isset($commodity) && ($commodity != '')) {\n\t\t\t\t$sql1 = ' AND d.commodity = \"'.$commodity.'\"';\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.id_dos AS id_dos, d.ref_dos AS ref_dos\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.ref_dos BETWEEN ? AND ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sql1\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlType\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t\t\t\t\t\t\tORDER BY d.ref_dos ASC\");\n\t\t\t$requete-> execute(array($entree['id_mod_trans'], $entree['id_mod_lic'], \n\t\t\t\t\t\t\t\t\t$entree['debut'], $entree['fin']));\n\t\t\t\n\t\t\twhile($reponse = $requete-> fetch()){\n\t\t\t\t//echo $reponse['id_dos'].'
    ';\n\t\t if (isset($ref_decl) && ($ref_decl != '')) {\n\t\t $this-> MAJ_ref_decl($reponse['id_dos'], $ref_decl);\n\t\t }\n\n\t\t if (isset($date_decl) && ($date_decl != '')) {\n\t\t $this-> MAJ_date_decl($reponse['id_dos'], $date_decl);\n\t\t }\n\n\t\t if (isset($ref_liq) && ($ref_liq != '')) {\n\t\t $this-> MAJ_ref_liq($reponse['id_dos'], $ref_liq);\n\t\t }\n\n\t\t if (isset($date_liq) && ($date_liq != '')) {\n\t\t $this-> MAJ_date_liq($reponse['id_dos'], $date_liq);\n\t\t }\n\n\t\t if (isset($ref_quit) && ($ref_quit != '')) {\n\t\t $this-> MAJ_ref_quit($reponse['id_dos'], $ref_quit);\n\t\t }\n\n\t\t if (isset($date_quit) && ($date_quit != '')) {\n\t\t $this-> MAJ_date_quit($reponse['id_dos'], $date_quit);\n\t\t }\n\n\t\t if (isset($montant_decl) && ($montant_decl != '')) {\n\t\t $this-> MAJ_montant_decl($reponse['id_dos'], $montant_decl);\n\t\t }\n\n\t\t if (isset($klsa_arriv) && ($klsa_arriv != '')) {\n\t\t $this-> MAJ_klsa_arriv($reponse['id_dos'], $klsa_arriv);\n\t\t }\n\t\t \n\t\t if (isset($crossing_date) && ($crossing_date != '')) {\n\t\t $this-> MAJ_crossing_date($reponse['id_dos'], $crossing_date);\n\t\t }\n\t\t \n\t\t if (isset($wiski_arriv) && ($wiski_arriv != '')) {\n\t\t $this-> MAJ_wiski_arriv($reponse['id_dos'], $wiski_arriv);\n\t\t }\n\t\t \n\t\t if (isset($wiski_dep) && ($wiski_dep != '')) {\n\t\t $this-> MAJ_wiski_dep($reponse['id_dos'], $wiski_dep);\n\t\t }\n\t\t \n\t\t if (isset($ref_crf) && ($ref_crf != '')) {\n\t\t $this-> MAJ_ref_crf($reponse['id_dos'], $ref_crf);\n\t\t }\n\t\t \n\t\t if (isset($date_crf) && ($date_crf != '')) {\n\t\t $this-> MAJ_date_crf($reponse['id_dos'], $date_crf);\n\t\t }\n\t\t \n\t\t if (isset($dgda_in) && ($dgda_in != '')) {\n\t\t $this-> MAJ_dgda_in($reponse['id_dos'], $dgda_in);\n\t\t }\n\t\t \n\t\t if (isset($dgda_out) && ($dgda_out != '')) {\n\t\t $this-> MAJ_dgda_out($reponse['id_dos'], $dgda_out);\n\t\t \t//echo \"
    $dgda_out\";\n\t\t }\n\n\t\t if (isset($date_preal) && ($date_preal != '')) {\n\t\t $this-> MAJ_date_preal($reponse['id_dos'], $date_preal);\n\t\t }\n\n\t\t if (isset($custom_deliv) && ($custom_deliv != '')) {\n\t\t $this-> MAJ_custom_deliv($reponse['id_dos'], $custom_deliv);\n\t\t }\n\t\t \n\t\t if (isset($dispatch_klsa) && ($dispatch_klsa != '')) {\n\t\t $this-> MAJ_dispatch_klsa($reponse['id_dos'], $dispatch_klsa);\n\t\t }\n\t\t \n\t\t if (isset($dispatch_deliv) && ($dispatch_deliv != '')) {\n\t\t $this-> MAJ_dispatch_deliv($reponse['id_dos'], $dispatch_deliv);\n\t\t }\n\t\t \n\t\t if (isset($cleared) && ($cleared != '')) {\n\t\t $this-> MAJ_cleared($reponse['id_dos'], $cleared);\n\t\t }\n\n\t\t if (isset($statut) && ($statut != '')) {\n\t\t $this-> MAJ_statut($reponse['id_dos'], $statut);\n\t\t }\n\n\t\t if (isset($remarque) && ($remarque != '')) {\n\t\t $this-> MAJ_remarque($reponse['id_dos'], $remarque);\n\t\t }\n\n\t\t if (isset($cleared) && ($cleared != '')) {\n\t\t $this-> MAJ_cleared($reponse['id_dos'], $cleared);\n\t\t }\n\n\t\t if (isset($amicongo_arriv) && ($amicongo_arriv != '')) {\n\t\t $this-> MAJ_amicongo_arriv($reponse['id_dos'], $amicongo_arriv);\n\t\t }\n\n\t\t if (isset($insp_receiv) && ($insp_receiv != '')) {\n\t\t $this-> MAJ_insp_receiv($reponse['id_dos'], $insp_receiv);\n\t\t }\n\n\t\t if (isset($ir) && ($ir != '')) {\n\t\t $this-> MAJ_ir($reponse['id_dos'], $ir);\n\t\t }\n\n\t\t if (isset($ref_decl) && ($ref_decl != '')) {\n\t\t \t//echo \"
    $ref_decl\";\n\t\t $this-> MAJ_ref_decl($reponse['id_dos'], $ref_decl);\n\t\t }\n\n\t\t if (isset($ref_decl) && ($ref_decl != '')) {\n\t\t $this-> MAJ_ref_decl($reponse['id_dos'], $ref_decl);\n\t\t }\n\n\t\t\t}$requete-> closeCursor();\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function addForm(\n $encounter,\n $form_name,\n $form_id,\n $formdir,\n $pid,\n $authorized = \"0\",\n $date = \"NOW()\",\n $user = \"\",\n $group = \"\",\n $therapy_group = 'not_given'\n) {\n\n global $attendant_type;\n if (!$user) {\n $user = $_SESSION['authUser'] ?? null;\n }\n\n if (!$group) {\n $group = $_SESSION['authProvider'] ?? null;\n }\n\n if ($therapy_group == 'not_given') {\n $therapy_group = $attendant_type == 'pid' ? null : $_SESSION['therapy_group'];\n }\n\n //print_r($_SESSION['therapy_group']);die;\n $arraySqlBind = array();\n $sql = \"insert into forms (date, encounter, form_name, form_id, pid, \" .\n \"user, groupname, authorized, formdir, therapy_group_id) values (\";\n if ($date == \"NOW()\") {\n $sql .= \"$date\";\n } else {\n $sql .= \"?\";\n array_push($arraySqlBind, $date);\n }\n\n $sql .= \", ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n array_push($arraySqlBind, $encounter, $form_name, $form_id, $pid, $user, $group, $authorized, $formdir, $therapy_group);\n return sqlInsert($sql, $arraySqlBind);\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function save_term_ajax( $sitepress, $lang, $taxonomy, $slug, $name, $trid, $description, $meta_data ) {\n\t\t$new_term_object = false;\n\n\t\tif ( $name !== \"\" && $taxonomy && $trid && $lang ) {\n\n\t\t\t$args = array(\n\t\t\t\t'taxonomy' => $taxonomy,\n\t\t\t\t'lang_code' => $lang,\n\t\t\t\t'term' => $name,\n\t\t\t\t'trid' => $trid,\n\t\t\t\t'overwrite' => true\n\t\t\t);\n\n\t\t\tif ( $slug ) {\n\t\t\t\t$args[ 'slug' ] = $slug;\n\t\t\t}\n\t\t\tif ( $description ) {\n\t\t\t\t$args[ 'description' ] = $description;\n\t\t\t}\n\n\t\t\t$switch_lang = new WPML_Temporary_Switch_Language( $sitepress, $lang );\n\t\t\t$is_new_term = ! term_exists( $name, $taxonomy );\n\t\t\t$res = WPML_Terms_Translations::create_new_term( $args );\n\t\t\t$switch_lang->restore_lang();\n\n\t\t\tif ( $res && isset( $res[ 'term_taxonomy_id' ] ) ) {\n\t\t\t\t/* res holds the term taxonomy id, we return the whole term objects to the ajax call */\n\t\t\t\t$switch_lang = new WPML_Temporary_Switch_Language( $sitepress, $lang );\n\t\t\t\t/**\n\t\t\t\t * @var \\WP_Term|\\stdClass $new_term_object A few lines below, we are adding properties that WP_Term does not have.\n\t\t\t\t * We should probably improve this code and use a specialized object instead.\n\t\t\t\t */\n\t\t\t\t$new_term_object = get_term_by( 'term_taxonomy_id', (int) $res['term_taxonomy_id'], $taxonomy );\n\t\t\t\t$switch_lang->restore_lang();\n\n\t\t\t\t$lang_details = $sitepress->get_element_language_details( $new_term_object->term_taxonomy_id, 'tax_' . $new_term_object->taxonomy );\n\t\t\t\t$new_term_object->trid = $lang_details->trid;\n\t\t\t\t$new_term_object->language_code = $lang_details->language_code;\n\t\t\t\tif ( self::add_term_metadata( $res, $meta_data, $is_new_term ) ) {\n\t\t\t\t\t$new_term_object->meta_data = get_term_meta( $res['term_id'] );\n\t\t\t\t}\n\n\t\t\t\tWPML_Terms_Translations::icl_save_term_translation_action( $taxonomy, $res );\n\t\t\t}\n\t\t}\n\n\t\treturn $new_term_object;\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "function manage_tracker_status($apptdate, $appttime, $eid, $pid, $user, $status = '', $room = '', $enc_id = '')\n{\n $patientTrackerService = new PatientTrackerService();\n return $patientTrackerService->manage_tracker_status($apptdate, $appttime, $eid, $pid, $user, $status, $room, $enc_id);\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function buildZipEntry( $filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr ) {\n\t\t$filePath = str_replace( '\\\\', '/', $filePath );\n\t\t$fileCommentLength = ( empty( $fileComment ) ? 0 : strlen( $fileComment ) );\n\t\t$timestamp = (int) $timestamp;\n\t\t$timestamp = ( $timestamp == 0 ? time() : $timestamp );\n\n\t\t$dosTime = $this->getDosTime( $timestamp );\n\t\t$tsPack = pack( 'V', $timestamp );\n\n\t\tif ( $gpFlags && strlen( $gpFlags ) !== 2 ) {\n\t\t\t$gpFlags = \"\\x00\\x00\";\n\t\t}\n\n\t\t$isFileUTF8 = mb_check_encoding( $filePath, 'UTF-8' ) && ! mb_check_encoding( $filePath, 'ASCII' );\n\t\t$isCommentUTF8 = ! empty( $fileComment ) && mb_check_encoding( $fileComment, 'UTF-8' ) && ! mb_check_encoding( $fileComment, 'ASCII' );\n\n\t\t$localExtraField = '';\n\t\t$centralExtraField = '';\n\n\t\tif ( $this->addExtraField ) {\n\t\t\t$localExtraField .= \"\\x55\\x54\\x09\\x00\\x03\" . $tsPack . $tsPack . self::EXTRA_FIELD_NEW_UNIX_GUID;\n\t\t\t$centralExtraField .= \"\\x55\\x54\\x05\\x00\\x03\" . $tsPack . self::EXTRA_FIELD_NEW_UNIX_GUID;\n\t\t}\n\n\t\tif ( $isFileUTF8 || $isCommentUTF8 ) {\n\t\t\t$flag = 0;\n\t\t\t$gpFlagsV = unpack( 'vflags', (string) $gpFlags );\n\t\t\tif ( isset( $gpFlagsV['flags'] ) ) {\n\t\t\t\t$flag = $gpFlagsV['flags'];\n\t\t\t}\n\t\t\t$gpFlags = pack( 'v', $flag | ( 1 << 11 ) );\n\n\t\t\tif ( $isFileUTF8 ) {\n\t\t\t\t$utfPathExtraField = \"\\x75\\x70\"\n\t\t\t\t\t. pack( 'v', ( 5 + strlen( $filePath ) ) )\n\t\t\t\t\t. \"\\x01\"\n\t\t\t\t\t. pack( 'V', crc32( $filePath ) )\n\t\t\t\t\t. $filePath;\n\n\t\t\t\t$localExtraField .= $utfPathExtraField;\n\t\t\t\t$centralExtraField .= $utfPathExtraField;\n\t\t\t}\n\t\t\tif ( $isCommentUTF8 ) {\n\t\t\t\t$centralExtraField .= \"\\x75\\x63\" // utf8 encoded file comment extra field\n\t\t\t\t\t. pack( 'v', ( 5 + strlen( $fileComment ) ) )\n\t\t\t\t\t. \"\\x01\"\n\t\t\t\t\t. pack( 'V', crc32( $fileComment ) )\n\t\t\t\t\t. $fileComment;\n\t\t\t}\n\t\t}\n\n\t\t$header = $gpFlags . $gzType . $dosTime . $fileCRC32\n\t\t\t. pack( 'VVv', $gzLength, $dataLength, strlen( $filePath ) ); // File name length\n\n\t\t$zipEntry = self::ZIP_LOCAL_FILE_HEADER\n\t\t\t. self::ATTR_VERSION_TO_EXTRACT\n\t\t\t. $header\n\t\t\t. pack( 'v', strlen( $localExtraField ) ) // Extra field length\n\t\t\t. $filePath // FileName\n\t\t\t. $localExtraField; // Extra fields\n\n\t\t$this->zipwrite( $zipEntry );\n\n\t\t$cdEntry = self::ZIP_CENTRAL_FILE_HEADER\n\t\t\t. self::ATTR_MADE_BY_VERSION\n\t\t\t. ( $dataLength === 0 ? \"\\x0A\\x00\" : self::ATTR_VERSION_TO_EXTRACT )\n\t\t\t. $header\n\t\t\t. pack( 'v', strlen( $centralExtraField ) ) // Extra field length\n\t\t\t. pack( 'v', $fileCommentLength ) // File comment length\n\t\t\t. \"\\x00\\x00\" // Disk number start\n\t\t\t. \"\\x00\\x00\" // internal file attributes\n\t\t\t. pack( 'V', $extFileAttr ) // External file attributes\n\t\t\t. pack( 'V', $this->offset ) // Relative offset of local header\n\t\t\t. $filePath // FileName\n\t\t\t. $centralExtraField; // Extra fields\n\n\t\tif ( ! empty( $fileComment ) ) {\n\t\t\t$cdEntry .= $fileComment; // Comment\n\t\t}\n\n\t\t$this->cdRec[] = $cdEntry;\n\t\t$this->offset += strlen( $zipEntry ) + $gzLength;\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "function acl_check($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value=NULL, $axo_value=NULL, $root_aro_group=NULL, $root_axo_group=NULL) {\n\t\t$acl_result = $this->acl_query($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value, $axo_value, $root_aro_group, $root_axo_group);\n\n\t\treturn $acl_result['allow'];\n\t}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($stage, $unities, $approvalMedia, $finalRecoverMedia, $calculationFinalMedia, $hasFinalRecovery, $ruleType,\n $hasPartialRecovery, $partialRecoveries)\n {\n $this->stage = $stage;\n $this->unities = $unities;\n $this->approvalMedia = $approvalMedia;\n $this->finalRecoverMedia = $finalRecoverMedia;\n $this->calculationFinalMedia = $calculationFinalMedia;\n $this->hasFinalRecovery = $hasFinalRecovery;\n $this->ruleType = $ruleType;\n $this->hasPartialRecovery = $hasPartialRecovery;\n $this->partialRecoveries = $partialRecoveries;\n }", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function imagecopy($dst_im, $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h): void\n{\n error_clear_last();\n $result = \\imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);\n if ($result === false) {\n throw ImageException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(string $baseUrl = '', string $method = 'GET', string $host = 'localhost', string $scheme = 'http', int $httpPort = 80, int $httpsPort = 443, string $path = '/', string $queryString = '')\n {\n $this->setBaseUrl($baseUrl);\n $this->setMethod($method);\n $this->setHost($host);\n $this->setScheme($scheme);\n $this->setHttpPort($httpPort);\n $this->setHttpsPort($httpsPort);\n $this->setPathInfo($path);\n $this->setQueryString($queryString);\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function imagearc($image, int $cx, int $cy, int $width, int $height, int $start, int $end, int $color): void\n{\n error_clear_last();\n $result = \\imagearc($image, $cx, $cy, $width, $height, $start, $end, $color);\n if ($result === false) {\n throw ImageException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function afficherRowTableauExcel($id_mod_lic, $id_cli, $id_mod_trans, $id_dos, $compteur, $statut=NULL, $klsa_status=NULL, $amicongo_status=NULL, $kzi_status=NULL){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$bg = '';\n\n\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t$sqlClient = ' AND cl.id_cli = \"'.$id_cli.'\"';\n\t\t\t}else{\n\t\t\t\t$sqlClient = '';\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT c.champ_col AS champ_col, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.type_col AS type_col, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.calcul AS calcul,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.id_col AS id_col \n\t\t\t\t\t\t\t\t\t\t\tFROM colonne c, client cl, affectation_colonne_client_modele_licence af\n\t\t\t\t\t\t\t\t\t\t\tWHERE c.id_col = af.id_col\n\t\t\t\t\t\t\t\t\t\t\t\tAND af.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t AND cl.id_cli = ?\n\t\t\t\t\t\t\t\t\t\t\t AND af.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t AND af.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\tORDER BY af.rang ASC\");\n\t\t\t$requete-> execute(array($entree['id_cli'], $entree['id_mod_trans'], $entree['id_mod_lic']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t//getDataRow($champ_col, $id_dos)\n\t\t\t\tif ($reponse['id_col'] == '40' && $id_mod_lic == '2') {\n\t\t\t\t\t$getDataRowCalculNetDays = $this-> getDataRowCalculNetDays($reponse['champ_col'], $id_dos);\n\t\t\t\t\tif ( ($getDataRowCalculNetDays >= 0) && ($getDataRowCalculNetDays <= 3) ) {\n\t\t\t\t\t\t$bg = \"background-color: green; color: white;\";\n\t\t\t\t\t}else if ( ($getDataRowCalculNetDays > 3) && ($getDataRowCalculNetDays <= 5) ) {\n\t\t\t\t\t\t$bg = \"background-color: orange; color: white;\";\n\t\t\t\t\t}else if ( ($getDataRowCalculNetDays > 5) ) {\n\t\t\t\t\t\t$bg = \"background-color: red; color: white;\";\n\t\t\t\t\t}\n\t\t\t\t?>\n\t\t\t\t\">\n\t\t\t\t\t getDataRowCalculNetDays($reponse['champ_col'], $id_dos);\n\t\t\t\t\t?>\n\t\t\t\t\t getDataRowCalcul($reponse['champ_col'], $id_dos)[$reponse['champ_col']];?>\n\t\t\t\t\n\t\t\t\t getDataRowCalculNetDays($reponse['champ_col'], $id_dos);\n\t\t\t\t\t\t\tif ( ($this-> getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos)) >= 0) && ($this-> getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos)) <= 2) ) {\n\t\t\t\t\t\t\t\t$bg = \"background-color: green; color: white;\";\n\t\t\t\t\t\t\t}else if ( ($this-> getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos)) > 2) && ($this-> getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos)) <= 5) ) {\n\t\t\t\t\t\t\t\t$bg = \"background-color: orange; color: white;\";\n\t\t\t\t\t\t\t}else if ( ($this-> getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos)) > 5) ) {\n\t\t\t\t\t\t\t$bg = \"background-color: red; color: white;\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t\">\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos)) - $this-> getWeekendsAndHolidays($this-> getDataRow('demande_attestation', $id_dos), $this-> getDataRow('dispatch_date', $id_dos));\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t getDataRow($reponse['champ_col'], $id_dos);\n\t\t\t\t\tif ( ($getDataRow == '0') ) {\n\t\t\t\t\t\t?>\n\t\t\t\t\t\tTRANSIT\n\t\t\t\t\t\t\n\t\t\t\t\t\tCLEARED\n\t\t\t\t\t\t\n\t\t\t\t\t\tCANCELLED\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDataRow($reponse['champ_col'], $id_dos);?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDateExpirationLicence($this-> getDossier($id_dos)['num_lic']);?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getLicence2($this-> getDossier($id_dos)['num_lic'])['poids'];?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getBalanceLicenceDossier($id_dos);?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDifferenceDate($this-> getDataRow('ceec_out', $id_dos), $this-> getDataRow('ceec_in', $id_dos));?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDifferenceDate($this-> getDataRow('min_div_out', $id_dos), $this-> getDataRow('min_div_in', $id_dos));?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDifferenceDate($this-> getDataRow('dgda_out', $id_dos), $this-> getDataRow('dgda_in', $id_dos));?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDifferenceDate($this-> getDataRow('gov_out', $id_dos), $this-> getDataRow('gov_in', $id_dos));?>\n\t\t\t\t\n\t\t\t\t getDossier($id_dos)['id_mod_trans'] == '4') {\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t\">\n\t\t\t\t\t\t\t getDifferenceDate($this-> getDataRow('docs_sncc', $id_dos), $this-> getDataRow('demande_attestation', $id_dos));?>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\">\n\t\t\t\t\t\t\t getDifferenceDate($this-> getDataRow('dispatch_date', $id_dos), $this-> getDataRow('demande_attestation', $id_dos));?>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\">\n\t\t\t\t\t getDataRowCalcul($reponse['champ_col'], $id_dos)[$reponse['champ_col']])) {\n\t\t\t\t\t\t\techo $this-> getDataRowCalcul($reponse['champ_col'], $id_dos)[$reponse['champ_col']];\n\t\t\t\t\t\t}\n\t\t\t\t\t?>\n\t\t\t\t\t getDataRowCalcul($reponse['champ_col'], $id_dos)[$reponse['champ_col']];?>\n\t\t\t\t\n\t\t\t\t getLicence($this-> getDossier($id_dos)['num_lic'])['fournisseur'])) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t\" style=\"border: 1px solid black; \">\n\t\t\t\t\t\t\t getDataRow('supplier', $id_dos);?>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\" style=\"border: 1px solid black; \">\n\t\t\t\t\t\t\t getLicence($this-> getDossier($id_dos)['num_lic'])['fournisseur'];?>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDataRow($reponse['champ_col'], $id_dos);?>\n\t\t\t\t\t getDifferenceDate($this-> getDataRow('gov_out', $id_dos), $this-> getDataRow('gov_in', $id_dos));?>\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black;\">\n\t\t\t\t\t getDataRow($reponse['champ_col'], $id_dos);?>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\" style=\"border: 1px solid black; text-align: center;\">\n\t\t\t\t\t getDataRow($reponse['champ_col'], $id_dos);?>\n\t\t\t\t\n\t\t\t\t closeCursor();\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n ContentTypeService $contentTypeService,\n LanguageService $languageService,\n PathService $pathService,\n FormFactory $formFactory,\n FormFactoryInterface $sfFormFactory,\n SubitemsContentViewParameterSupplier $subitemsContentViewParameterSupplier,\n UserService $userService,\n BookmarkService $bookmarkService,\n ContentService $contentService,\n LocationService $locationService,\n UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,\n ConfigResolverInterface $configResolver,\n Repository $repository,\n PermissionResolver $permissionResolver,\n LookupLimitationsTransformer $lookupLimitationsTransformer\n ) {\n $this->contentTypeService = $contentTypeService;\n $this->languageService = $languageService;\n $this->pathService = $pathService;\n $this->formFactory = $formFactory;\n $this->sfFormFactory = $sfFormFactory;\n $this->subitemsContentViewParameterSupplier = $subitemsContentViewParameterSupplier;\n $this->userService = $userService;\n $this->bookmarkService = $bookmarkService;\n $this->contentService = $contentService;\n $this->locationService = $locationService;\n $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;\n $this->configResolver = $configResolver;\n $this->permissionResolver = $permissionResolver;\n $this->lookupLimitationsTransformer = $lookupLimitationsTransformer;\n $this->repository = $repository;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (string $userId, string $email, string $password, string $passwordSalt, string $passwordSaltSeparator, string $passwordSignerKey, string $name, Response $response, Document $project, Database $dbForProject, Event $events) {\n $user = createUser('scryptMod', '{\"signerKey\":\"' . $passwordSignerKey . '\",\"saltSeparator\":\"' . $passwordSaltSeparator . '\",\"salt\":\"' . $passwordSalt . '\"}', $userId, $email, $password, null, $name, $project, $dbForProject, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n $newTables = [],\n $changedTables = [],\n $removedTables = [],\n ?Schema $fromSchema = null,\n $createdSchemas = [],\n $droppedSchemas = [],\n $createdSequences = [],\n $alteredSequences = [],\n $droppedSequences = []\n ) {\n $this->newTables = $newTables;\n\n $this->changedTables = array_filter($changedTables, static function (TableDiff $diff): bool {\n return ! $diff->isEmpty();\n });\n\n $this->removedTables = $removedTables;\n $this->fromSchema = $fromSchema;\n $this->newNamespaces = $createdSchemas;\n $this->removedNamespaces = $droppedSchemas;\n $this->newSequences = $createdSequences;\n $this->changedSequences = $alteredSequences;\n $this->removedSequences = $droppedSequences;\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $documentId, ?\\DateTime $requestTimestamp, Response $response, Database $dbForProject, Event $events, Delete $deletes, string $mode) {\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId));\n\n if ($collection->isEmpty() || (!$collection->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n // Read permission should not be required for delete\n $document = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId));\n\n if ($document->isEmpty()) {\n throw new Exception(Exception::DOCUMENT_NOT_FOUND);\n }\n\n $dbForProject->withRequestTimestamp($requestTimestamp, function () use ($dbForProject, $database, $collection, $documentId) {\n try {\n $dbForProject->deleteDocument(\n 'database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(),\n $documentId\n );\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (RestrictedException) {\n throw new Exception(Exception::DOCUMENT_DELETE_RESTRICTED);\n }\n });\n\n // Add $collectionId and $databaseId for all documents\n $processDocument = function (Document $collection, Document $document) use (&$processDocument, $dbForProject, $database) {\n $document->setAttribute('$databaseId', $database->getId());\n $document->setAttribute('$collectionId', $collection->getId());\n\n $relationships = \\array_filter(\n $collection->getAttribute('attributes', []),\n fn($attribute) => $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP\n );\n\n foreach ($relationships as $relationship) {\n $related = $document->getAttribute($relationship->getAttribute('key'));\n\n if (empty($related)) {\n continue;\n }\n if (!\\is_array($related)) {\n $related = [$related];\n }\n\n $relatedCollectionId = $relationship->getAttribute('relatedCollection');\n $relatedCollection = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $relatedCollectionId)\n );\n\n foreach ($related as $relation) {\n if ($relation instanceof Document) {\n $processDocument($relatedCollection, $relation);\n }\n }\n }\n };\n\n $processDocument($collection, $document);\n\n $deletes\n ->setType(DELETE_TYPE_AUDIT)\n ->setDocument($document);\n\n $events\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('documentId', $document->getId())\n ->setContext('collection', $collection)\n ->setContext('database', $database)\n ->setPayload($response->output($document, Response::MODEL_DOCUMENT));\n\n $response->noContent();\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n TranslatorInterface $translator,\n SectionService $sectionService,\n DatasetFactory $datasetFactory,\n FormFactoryInterface $formFactory,\n PermissionResolver $permissionResolver,\n UserSettingService $userSettingService,\n EventDispatcherInterface $eventDispatcher\n ) {\n parent::__construct($twig, $translator, $eventDispatcher);\n\n $this->sectionService = $sectionService;\n $this->datasetFactory = $datasetFactory;\n $this->formFactory = $formFactory;\n $this->permissionResolver = $permissionResolver;\n $this->userSettingService = $userSettingService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function formpopup($label,$content,$width=600,$height=400,$type='link',$scroll='null',$id='popup',$ref='') {\n\tglobal $urlmode;\n\t$labelSanitized = Sanitize::encodeStringForDisplay($label);\n if (!is_scalar($content)) { echo \"invalid content in formpopup\"; return ''; }\n if (!is_scalar($label)) { echo \"invalid label in formpopup\"; return ''; }\n if (is_array($width)) { echo \"width should not be array in formpopup\"; $width = 600; }\n\n\tif ($scroll != null) {\n\t\t$scroll = ','.$scroll;\n\t}\n\tif ($height=='fit') {\n\t\t$height = \"'fit'\";\n\t}\n\tif ($ref!='') {\n\t\tif (strpos($ref,'-')!==false) {\n\t\t\t$ref = explode('-',$ref);\n\t\t\t$contentadd = 'Q'.$ref[1].': ';\n\t\t\t$ref = $ref[0];\n\t\t} else {\n\t\t\t$contentadd = '';\n\t\t}\n\t\tif (strpos($content,'watchvid.php')!==false) {\n\t\t\t$cp = explode('?url=',$content);\n\t\t\t$rec = \"recclick('extref',$ref,'\".$contentadd.trim(htmlentities(urldecode($cp[1]))).\"');\";\n\t\t} else {\n\t\t\t$rec = \"recclick('extref',$ref,'\".$contentadd.trim(htmlentities($content)).\"');\";\n\t\t}\n\n\t} else {\n\t\t$rec = '';\n\t}\n\tif (strpos($label,''.$label.'';\n\t} else {\n\t\tif ($type=='link') {\n\t\t\treturn ''.$labelSanitized.'';\n\t\t} else if ($type=='button') {\n\t\t\tif (substr($content,0,31)=='http://www.youtube.com/watch?v=') {\n\t\t\t\t$content = $GLOBALS['basesiteurl'] . \"/assessment/watchvid.php?url=\".Sanitize::encodeUrlParam($content);\n\t\t\t\t$width = 660;\n\t\t\t\t$height = 525;\n\t\t\t}\n return '';\n\n\t\t}\n\t}\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function generateResponse($path, $start, $end, $expand, $componentType, $format, $properties, ResponseInterface $response)\n {\n $calDataProp = '{'.Plugin::NS_CALDAV.'}calendar-data';\n $calendarNode = $this->server->tree->getNodeForPath($path);\n\n $blobs = [];\n if ($start || $end || $componentType) {\n // If there was a start or end filter, we need to enlist\n // calendarQuery for speed.\n $queryResult = $calendarNode->calendarQuery([\n 'name' => 'VCALENDAR',\n 'comp-filters' => [\n [\n 'name' => $componentType,\n 'comp-filters' => [],\n 'prop-filters' => [],\n 'is-not-defined' => false,\n 'time-range' => [\n 'start' => $start,\n 'end' => $end,\n ],\n ],\n ],\n 'prop-filters' => [],\n 'is-not-defined' => false,\n 'time-range' => null,\n ]);\n\n // queryResult is just a list of base urls. We need to prefix the\n // calendar path.\n $queryResult = array_map(\n function ($item) use ($path) {\n return $path.'/'.$item;\n },\n $queryResult\n );\n $nodes = $this->server->getPropertiesForMultiplePaths($queryResult, [$calDataProp]);\n unset($queryResult);\n } else {\n $nodes = $this->server->getPropertiesForPath($path, [$calDataProp], 1);\n }\n\n // Flattening the arrays\n foreach ($nodes as $node) {\n if (isset($node[200][$calDataProp])) {\n $blobs[$node['href']] = $node[200][$calDataProp];\n }\n }\n unset($nodes);\n\n $mergedCalendar = $this->mergeObjects(\n $properties,\n $blobs\n );\n\n if ($expand) {\n $calendarTimeZone = null;\n // We're expanding, and for that we need to figure out the\n // calendar's timezone.\n $tzProp = '{'.Plugin::NS_CALDAV.'}calendar-timezone';\n $tzResult = $this->server->getProperties($path, [$tzProp]);\n if (isset($tzResult[$tzProp])) {\n // This property contains a VCALENDAR with a single\n // VTIMEZONE.\n $vtimezoneObj = VObject\\Reader::read($tzResult[$tzProp]);\n $calendarTimeZone = $vtimezoneObj->VTIMEZONE->getTimeZone();\n // Destroy circular references to PHP will GC the object.\n $vtimezoneObj->destroy();\n unset($vtimezoneObj);\n } else {\n // Defaulting to UTC.\n $calendarTimeZone = new DateTimeZone('UTC');\n }\n\n $mergedCalendar = $mergedCalendar->expand($start, $end, $calendarTimeZone);\n }\n\n $filenameExtension = '.ics';\n\n switch ($format) {\n case 'text/calendar':\n $mergedCalendar = $mergedCalendar->serialize();\n $filenameExtension = '.ics';\n break;\n case 'application/calendar+json':\n $mergedCalendar = json_encode($mergedCalendar->jsonSerialize());\n $filenameExtension = '.json';\n break;\n }\n\n $filename = preg_replace(\n '/[^a-zA-Z0-9-_ ]/um',\n '',\n $calendarNode->getName()\n );\n $filename .= '-'.date('Y-m-d').$filenameExtension;\n\n $response->setHeader('Content-Disposition', 'attachment; filename=\"'.$filename.'\"');\n $response->setHeader('Content-Type', $format);\n\n $response->setStatus(200);\n $response->setBody($mergedCalendar);\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n string $entityName,\n int $entityId,\n string $type,\n string $temporaryFilename,\n string $uploadedFilename,\n int $position,\n string $hash,\n ?CustomerUser $customerUser = null,\n ) {\n $this->entityName = $entityName;\n $this->entityId = $entityId;\n $this->type = $type;\n $this->setTemporaryFilename($temporaryFilename);\n $this->setNameAndSlug($uploadedFilename);\n $this->position = $position;\n $this->hash = $hash;\n $this->customerUser = $customerUser;\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {\n\t\t$this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public static function fpdf($res, $color, $x, $y, $angle, $type, $datas, $width = null, $height = null)\n {\n return self::_draw(__FUNCTION__, $res, $color, $x, $y, $angle, $type, $datas, $width, $height);\n }", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function GetRanking($frame, $metricId, $metricVersionId, $levelId, $compareLevelId, $variableId,\n\t\t\t\t\t\t\t$hasTotals, $urbanity, $partition, $size, $direction, $hiddenValueLabels)\n\t{\n\t\t$data = null;\n\t\t$this->CheckNotNullNumeric($metricId);\n\t\t$this->CheckNotNullNumeric($metricVersionId);\n\t\t$this->CheckNotNumericNullable($levelId);\n\n\t\tif ($frame->ClippingRegionIds == NULL\n\t\t\t&& $frame->ClippingCircle == NULL && $frame->Envelope == null)\n\t\t\tthrow new PublicException(\"Debe indicarse una delimitaci\u00f3n espacial (zona, c\u00edrculo o regi\u00f3n).\");\n\n\t\t$key = RankingCache::CreateKey($frame, $metricVersionId, $levelId, $compareLevelId, $size, $direction, $urbanity, $partition, $hasTotals, $hiddenValueLabels);\n\n\t\tif ($frame->HasClippingFactor() && $frame->ClippingCircle == null && RankingCache::Cache()->HasData($metricId, $key, $data))\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn $this->GotFromCache($data);\n\t\t\t}\n\t\t\tcatch(\\Exception $e)\n\t\t\t{\n\t\t\t\tLog::HandleSilentException($e);\n\t\t\t\tRankingCache::Cache()->Clear($metricId, $key);\n\t\t\t}\n\t\t}\n\n\t\tPerformance::CacheMissed();\n\t\t$data = $this->CalculateRanking($frame, $metricId, $metricVersionId, $levelId, $compareLevelId, $variableId, $hasTotals, $urbanity, $partition, $size, $direction, $hiddenValueLabels);\n\n\t\tif ($frame->HasClippingFactor() && $frame->ClippingCircle == null)\n\t\t\tRankingCache::Cache()->PutData($metricId, $key, $data);\n\n\t\t$data->EllapsedMs = GlobalTimer::EllapsedMs();\n\n\t\treturn $data;\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "function creer_demande_fond($id_dept, $id_site, $beneficiaire, $id_cli, $cash, $montant, $usd, $libelle, $id_util_visa_dept, $id_dep){\n\t\t\tinclude(\"connexion.php\");\n\n\t\t\t$entree['id_dept'] = $id_dept;\n\t\t\t$entree['id_site'] = $id_site;\n\t\t\t$entree['beneficiaire'] = $beneficiaire;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['cash'] = $cash;\n\t\t\t$entree['montant'] = $montant;\n\t\t\t$entree['usd'] = $usd;\n\t\t\t$entree['libelle'] = $libelle;\n\t\t\t$entree['id_util_visa_dept'] = $id_util_visa_dept;\n\t\t\t$entree['id_dep'] = $id_dep;\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO demande_fond(id_dept, id_site, beneficiaire, id_cli, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcash, montant, usd, libelle, id_util_visa_dept, id_util, id_dep)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['id_dept'], $entree['id_site'], $entree['beneficiaire'], $entree['id_cli'], $entree['cash'], $entree['montant'], $entree['usd'], $entree['libelle'], $entree['id_util_visa_dept'], $_SESSION['id_util'], $_POST['id_dep']));\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n string $imageUrlPrefix,\n EntityManagerInterface $em,\n ImageConfig $imageConfig,\n ImageRepository $imageRepository,\n FilesystemOperator $filesystem,\n FileUpload $fileUpload,\n ImageLocator $imageLocator,\n ImageFactory $imageFactory,\n MountManager $mountManager,\n LoggerInterface $logger,\n CdnFacade $cdnFacade,\n CacheInterface|AdapterInterface $cache,\n ) {\n parent::__construct(\n $imageUrlPrefix,\n $em,\n $imageConfig,\n $imageRepository,\n $filesystem,\n $fileUpload,\n $imageLocator,\n $imageFactory,\n $mountManager,\n $logger,\n $cdnFacade,\n $cache,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function addEvent($type, $date, $description, $allDay, $enteredBy,\n $dataItemID, $dataItemType, $jobOrderID, $title, $duration,\n $reminderEnabled, $reminderEmail, $reminderTime, $isPublic,\n $timeZoneOffset)\n {\n $sql = sprintf(\n \"INSERT INTO calendar_event (\n type,\n date,\n description,\n all_day,\n entered_by,\n data_item_id,\n data_item_type,\n joborder_id,\n site_id,\n date_created,\n date_modified,\n title,\n duration,\n reminder_enabled,\n reminder_email,\n reminder_time,\n public\n )\n VALUES (\n %s,\n DATE_SUB(%s, INTERVAL %s HOUR),\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n NOW(),\n NOW(),\n %s,\n %s,\n %s,\n %s,\n %s,\n %s\n )\",\n $this->_db->makeQueryInteger($type),\n $this->_db->makeQueryString($date),\n $this->_db->makeQueryInteger($timeZoneOffset),\n $this->_db->makeQueryString($description),\n ($allDay ? '1' : '0'),\n $this->_db->makeQueryInteger($enteredBy),\n $this->_db->makeQueryInteger($dataItemID),\n $this->_db->makeQueryInteger($dataItemType),\n $this->_db->makeQueryInteger($jobOrderID),\n $this->_siteID,\n $this->_db->makeQueryString($title),\n $this->_db->makeQueryInteger($duration),\n ($reminderEnabled ? '1' : '0'),\n $this->_db->makeQueryString($reminderEmail),\n $this->_db->makeQueryInteger($reminderTime),\n ($isPublic ? '1' : '0')\n );\n\n $queryResult = $this->_db->query($sql);\n if (!$queryResult)\n {\n return -1;\n }\n\n return $this->_db->getLastInsertID();\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function CreateCalendarEvent($calendar_id, $summary, $location, $description, $all_day, $event_time, $event_timezone, $access_token) {\n\t\t$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';\n\n\t\t$curlPost = array('summary' => $summary);\n\t\t$curlPost['location'] = $location;\n\t\t$curlPost['description'] = $description;\n\t\tif($all_day == 1) {\n\t\t\t$curlPost['start'] = array('date' => $event_time['event_date']);\n\t\t\t$curlPost['end'] = array('date' => $event_time['event_date']);\n\t\t}\n\t\telse {\n\t\t\t$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);\n\t\t\t$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);\n\t\t}\n\t\t$ch = curl_init();\n\t\tcurl_setopt($ch, CURLOPT_URL, $url_events);\n\t\tcurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n\t\tcurl_setopt($ch, CURLOPT_POST, 1);\n\t\tcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n\t\tcurl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));\n\t\tcurl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));\n\t\t$data = json_decode(curl_exec($ch), true);\n\t\t$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);\n\t\tif($http_code != 200)\n\t\t\tthrow new Exception('Error : Failed to create event');\n\n\t\treturn $data['id'];\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function createSlaveConnectionFile(\n string $host,\n string $user,\n string $password,\n string $dbname,\n bool $use_timezones = false,\n bool $log_deprecation_warnings = false,\n bool $use_utf8mb4 = false,\n bool $allow_myisam = true,\n bool $allow_datetime = true,\n bool $allow_signed_keys = true,\n string $config_dir = GLPI_CONFIG_DIR\n ): bool {\n\n // Explode host into array (multiple values separated by a space char)\n $host = trim($host);\n if (strpos($host, ' ')) {\n $host = explode(' ', $host);\n }\n\n $properties = [\n 'slave' => true,\n 'dbhost' => $host,\n 'dbuser' => $user,\n 'dbpassword' => rawurlencode($password),\n 'dbdefault' => $dbname,\n ];\n if ($use_timezones) {\n $properties[self::PROPERTY_USE_TIMEZONES] = true;\n }\n if ($log_deprecation_warnings) {\n $properties[self::PROPERTY_LOG_DEPRECATION_WARNINGS] = true;\n }\n if ($use_utf8mb4) {\n $properties[self::PROPERTY_USE_UTF8MB4] = true;\n }\n if (!$allow_myisam) {\n $properties[self::PROPERTY_ALLOW_MYISAM] = false;\n }\n if (!$allow_datetime) {\n $properties[self::PROPERTY_ALLOW_DATETIME] = false;\n }\n if (!$allow_signed_keys) {\n $properties[self::PROPERTY_ALLOW_SIGNED_KEYS] = false;\n }\n\n $config_str = ' $value) {\n $config_str .= sprintf(' public $%s = %s;', $name, var_export($value, true)) . \"\\n\";\n }\n $config_str .= '}' . \"\\n\";\n\n return Toolbox::writeConfig('config_db_slave.php', $config_str, $config_dir);\n }", "smellKey": "S107", "smellId": null, "repo": "flegastelois_glpi", "language": "php"} {"function": "public function __construct(\n ?int $limit = 10,\n ?int $page = 1,\n ?Section $section = null,\n ?ContentType $contentType = null,\n ?string $trashed = null,\n ?array $trashedInterval = [],\n ?User $creator = null,\n ?array $sort = ['field' => 'trashed', 'direction' => 0]\n ) {\n $this->limit = $limit;\n $this->page = $page;\n $this->section = $section;\n $this->contentType = $contentType;\n $this->trashed = $trashed;\n $this->trashedInterval = $trashedInterval;\n $this->creator = $creator;\n $this->sort = $sort;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n\t\t?InDadosPessoais $inDadosPessoais,\n\t\t?InDeficiencia $inDeficiencia,\n\t\t?InRecursoAvaliacao $inRecursoAvaliacao,\n\t\t?InDocumentos $inDocumentos,\n\t\t?InCertidaoAntiga $inCertidaoAntiga,\n\t\t?InCertidaoNova $inCertidaoNova,\n\t\t?InEnderecoResidencial $inEnderecoResidencial,\n\t\t?InRastreio $inRastreio\n\t) {\n\t\t$this->inDadosPessoais = $inDadosPessoais;\n\t\t$this->inDeficiencia = $inDeficiencia;\n\t\t$this->inRecursoAvaliacao = $inRecursoAvaliacao;\n\t\t$this->inDocumentos = $inDocumentos;\n\t\t$this->inCertidaoAntiga = $inCertidaoAntiga;\n\t\t$this->inCertidaoNova = $inCertidaoNova;\n\t\t$this->inEnderecoResidencial = $inEnderecoResidencial;\n\t\t$this->inRastreio = $inRastreio;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function gen_liste ($requete, $champ_code, $champ_info, $nom, $on_change, $selected, $liste_vide_code, $liste_vide_info,$option_premier_code,$option_premier_info,$multiple=0,$attr='',$champ_optgroup='') {\n\tglobal $charset;\n\n\t$result=pmb_mysql_query($requete) or die ($requete);\n\t$renvoi=\"\\n\";\n\treturn $renvoi;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_7.5.8", "language": "php"} {"function": "function get_links_withrating($category = -1, $before = '', $after = '
    ', $between = \" \", $show_images = true,\n\t\t\t\t\t\t\t$orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\tget_links($category, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated);\n}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "protected function _renderMenu(\n Container $container,\n array|string $ulClasses,\n string $indent,\n string $innerIndent,\n ?int $minDepth,\n ?int $maxDepth,\n bool $onlyActive,\n bool $expandSibs,\n ?string $ulId,\n bool $addPageClassToLi,\n ?string $activeClass,\n string $parentClass,\n bool $renderParentClass\n ): string {\n $html = '';\n\n // find deepest active\n if ($found = $this->findActive($container, $minDepth, $maxDepth)) {\n $foundPage = $found['page'];\n $foundDepth = $found['depth'];\n } else {\n $foundPage = null;\n $foundDepth = null;\n }\n\n // create iterator\n $iterator = new RecursiveIteratorIterator($container, RecursiveIteratorIterator::SELF_FIRST);\n\n if (is_int($maxDepth)) {\n $iterator->setMaxDepth($maxDepth);\n }\n\n // iterate container\n $prevDepth = -1;\n foreach ($iterator as $page) {\n $depth = $iterator->getDepth();\n $isActive = $page->isActive(true);\n\n // Set ulClass depth wise if array of classes is supplied.\n if (is_array($ulClasses)) {\n $ulClass = $ulClasses[$depth] ?? $ulClasses['default'];\n } else {\n $ulClass = (string) $ulClasses;\n }\n\n if ($depth < $minDepth || !$this->accept($page)) {\n // page is below minDepth or not accepted by visibilty\n continue;\n } elseif ($expandSibs && $depth > $minDepth) {\n // page is not active itself, but might be in the active branch\n $accept = false;\n if ($foundPage) {\n if ($foundPage->hasPage($page)) {\n // accept if page is a direct child of the active page\n $accept = true;\n } elseif ($page->getParent()->isActive(true)) {\n // page is a sibling of the active branch...\n $accept = true;\n }\n }\n if (!$isActive && !$accept) {\n continue;\n }\n } elseif ($onlyActive && !$isActive) {\n // page is not active itself, but might be in the active branch\n $accept = false;\n if ($foundPage) {\n if ($foundPage->hasPage($page)) {\n // accept if page is a direct child of the active page\n $accept = true;\n } elseif ($foundPage->getParent()->hasPage($page)) {\n // page is a sibling of the active page...\n if (!$foundPage->hasPages() ||\n is_int($maxDepth) && $foundDepth + 1 > $maxDepth) {\n // accept if active page has no children, or the\n // children are too deep to be rendered\n $accept = true;\n }\n }\n }\n\n if (!$accept) {\n continue;\n }\n }\n\n // make sure indentation is correct\n $depth -= $minDepth;\n $myIndent = $indent . str_repeat($innerIndent, $depth * 2);\n\n if ($depth > $prevDepth) {\n $attribs = [];\n\n // start new ul tag\n if ((is_string($ulClasses) && 0 == $depth) || is_array($ulClasses)) {\n $attribs = [\n 'class' => $ulClass,\n 'id' => $ulId,\n ];\n }\n\n // We don't need a prefix for the menu ID (backup)\n $skipValue = $this->_skipPrefixForId;\n $this->skipPrefixForId();\n\n $html .= $myIndent . '_htmlAttribs($attribs)\n . '>'\n . $this->getEOL();\n\n // Reset prefix for IDs\n $this->_skipPrefixForId = $skipValue;\n } elseif ($prevDepth > $depth) {\n // close li/ul tags until we're at current depth\n for ($i = $prevDepth; $i > $depth; $i--) {\n $ind = $indent . str_repeat($innerIndent, $i * 2);\n $html .= $ind . $innerIndent . '' . $this->getEOL();\n $html .= $ind . '' . $this->getEOL();\n }\n // close previous li tag\n $html .= $myIndent . $innerIndent . '' . $this->getEOL();\n } else {\n // close previous li tag\n $html .= $myIndent . $innerIndent . '' . $this->getEOL();\n }\n\n // render li tag and page\n $liClasses = [];\n // Is page active?\n if ($isActive) {\n $liClasses[] = $activeClass;\n }\n // Add CSS class from page to LI?\n if ($addPageClassToLi) {\n $liClasses[] = $page->getClass();\n }\n // Add CSS class for parents to LI?\n if ($renderParentClass && $page->hasVisiblePages()) {\n // Check max depth\n if ((is_int($maxDepth) && ($depth + 1 < $maxDepth))\n || !is_int($maxDepth)\n ) {\n $liClasses[] = $parentClass;\n }\n }\n\n $html .= $myIndent . $innerIndent . '_htmlAttribs(['class' => implode(' ', $liClasses)])\n . '>' . $this->getEOL()\n . $myIndent . str_repeat($innerIndent, 2)\n . $this->htmlify($page)\n . $this->getEOL();\n\n // store as previous depth for next iteration\n $prevDepth = $depth;\n }\n\n if ($html) {\n // done iterating container; close open ul/li tags\n for ($i = $prevDepth + 1; $i > 0; $i--) {\n $myIndent = $indent . str_repeat($innerIndent . $innerIndent, $i - 1);\n $html .= $myIndent . $innerIndent . '' . $this->getEOL()\n . $myIndent . '' . $this->getEOL();\n }\n $html = rtrim($html, $this->getEOL());\n }\n\n return $html;\n }", "smellKey": "S107", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function sequential_code_set_search($form_code_type, $search_term, $limit = null, $modes = null, $count = false, $active = true, $start = null, $number = null, $filter_elements = array(), $is_hit_mode = false)\n{\n // Set the default behavior that is described in above function comments\n if (empty($modes)) {\n $modes = array('code','description');\n }\n\n // Return the Search Results (loop through each mode in order)\n foreach ($modes as $mode) {\n $res = code_set_search($form_code_type, $search_term, $count, $active, false, $start, $number, $filter_elements, $limit, $mode);\n if (($count && $res > 0) || (!$count && sqlNumRows($res) > 0)) {\n if ($is_hit_mode) {\n // just return the mode\n return $mode;\n } else {\n // returns the count number if count is true or returns the data if count is false\n return $res;\n }\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function LMS_InsertaRegistroCierreCursoImparticion_2022($rut, $id_curso, $id_empresa, $nota, $estado, $avance, $id_inscripcion, $porcentaje_asistencia,$caso_especial)\n{\n\n $connexion = new DatabasePDO();\n\n if ($estado == \"Reprobado\" or $estado == \"REPROBADO\") {\n $id_estado = \"0\";\n $estado = \"REPROBADO\";\n } else if ($estado == \"Aprobado\" or $estado == \"APROBADO\") {\n $id_estado = \"1\";\n $estado = \"APROBADO\";\n }\n if ($avance == \"\") {\n $avance = 0;\n }\n\n $Imp = DatosCompletosImparticion_2021($id_inscripcion); //print_r($Imp);\n $Tipo_Imparticion = $Imp[0]->tipo_audiencia;\n $MinimoAsistencia = $Imp[0]->minimo_asistencia;\n $MinimoNota = $Imp[0]->minimo_nota_aprobacion;\n //echo \"
    --> Tipo_Imparticion $Tipo_Imparticion MinimoAsistencia $MinimoAsistencia MinimoNota $MinimoNota\";\n\n if ($Tipo_Imparticion == \"fecha_inicio_termino\") {\n // FECHA INICIO TERMINO\n\n if ($MinimoAsistencia > 0 and $MinimoNota > 0) {\n //echo \"
    - caso 1\";\n if ($avance >= $MinimoAsistencia) {\n if ($nota >= $MinimoNota) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n\n } elseif ($MinimoAsistencia > 0 and $MinimoNota == \"\") {\n //echo \"
    - caso 2\";\n if ($avance >= $MinimoAsistencia) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } elseif ($MinimoAsistencia == \"\" and $MinimoNota > 0) {\n //echo \"
    - caso 3\";\n if ($nota >= $MinimoNota) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } else {\n //echo \"
    - caso 4\";\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n }\n\n } else {\n // POR SESIONES\n\n // formula para calcular avance segun sesiones\n $Num_sesiones = ImparticionesNumSesiones_2021($id_inscripcion);\n $avance = CalculaAvanceSegunSesiones_2022($id_inscripcion, $Num_sesiones, $rut);\n $porcentaje_asistencia = $avance;\n\n if ($MinimoAsistencia > 0 and $MinimoNota > 0) {\n //echo \"
    - caso 5\";\n\n\n //echo \"--> rut $rut avance $avance, nota $nota\";\n if ($avance >= $MinimoAsistencia) {\n if ($nota >= $MinimoNota) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n\n } elseif ($MinimoAsistencia > 0 and $MinimoNota == \"\") {\n //\techo \"
    - caso 6\";\n if ($avance >= $MinimoAsistencia) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } elseif ($MinimoAsistencia == \"\" and $MinimoNota > 0) {\n //echo \"
    - caso 7\";\n if ($nota >= $MinimoNota) {\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n } else {\n $estado_descripcion = \"REPROBADO\";\n $estado = \"1\";\n }\n } else {\n //echo \"
    - caso 8\";\n $estado_descripcion = \"APROBADO\";\n $estado = \"1\";\n }\n\n\n }\n\n\n //echo \"
    --> estado_descripcion $estado_descripcion, estado $estado\";\n\n\n // AUTOMATIZA EL ESTADO\n\n $sql = \"INSERT INTO tbl_inscripcion_cierre (rut, nota, estado, estado_descripcion, id_curso, id_empresa, avance, id_inscripcion, porcentaje_asistencia, anulado, caso_especial) \" .\n \"VALUES ('$rut', '$nota','$estado', '$estado_descripcion', '$id_curso', '$id_empresa', '$avance', '$id_inscripcion', '$porcentaje_asistencia', 'AUTOMATIZADO', '$caso_especial');\";\n\n //echo \"

    \".$sql;exit;\n\n\n\t$connexion->query($sql);\n\t$connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct(\n Domain $domain,\n ProductCollectionFacade $productCollectionFacade,\n ProductAccessoryFacade $productAccessoryFacade,\n CurrentCustomerUser $currentCustomerUser,\n ParameterWithValuesFactory $parameterWithValuesFactory,\n ProductAvailabilityFacade $productAvailabilityFacade,\n HreflangLinksFacade $hreflangLinksFacade,\n ProductFrontendLimitProvider $productFrontendLimitProvider,\n DataLoaderInterface $productsSellableByIdsBatchLoader,\n ProductVisibilityFacade $productVisibilityFacade,\n DataLoaderInterface $productsSellableCountByIdsBatchLoader,\n protected readonly FriendlyUrlFacade $friendlyUrlFacade,\n protected readonly ProductRepository $productRepository,\n protected readonly PricingGroupSettingFacade $pricingGroupSettingFacade,\n protected readonly ParameterRepository $parameterRepository,\n protected readonly BreadcrumbFacade $breadcrumbFacade,\n protected readonly DataLoaderInterface $categoriesBatchLoader,\n protected readonly DataLoaderInterface $brandsBatchLoader,\n protected readonly ProductVideoTranslationsRepository $productVideoTranslationsRepository,\n ) {\n parent::__construct(\n $domain,\n $productCollectionFacade,\n $productAccessoryFacade,\n $currentCustomerUser,\n $parameterWithValuesFactory,\n $productAvailabilityFacade,\n $hreflangLinksFacade,\n $productFrontendLimitProvider,\n $productsSellableByIdsBatchLoader,\n $productVisibilityFacade,\n $productsSellableCountByIdsBatchLoader,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function updateShare(\n\t\tstring $id,\n\t\t?int $permissions = null,\n\t\t?string $password = null,\n\t\t?string $sendPasswordByTalk = null,\n\t\t?string $publicUpload = null,\n\t\t?string $expireDate = null,\n\t\t?string $note = null,\n\t\t?string $label = null,\n\t\t?string $hideDownload = null,\n\t\t?string $attributes = null\n\t): DataResponse {\n\t\ttry {\n\t\t\t$share = $this->getShareById($id);\n\t\t} catch (ShareNotFound $e) {\n\t\t\tthrow new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));\n\t\t}\n\n\t\t$this->lock($share->getNode());\n\n\t\tif (!$this->canAccessShare($share, false)) {\n\t\t\tthrow new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));\n\t\t}\n\n\t\tif (!$this->canEditShare($share)) {\n\t\t\tthrow new OCSForbiddenException('You are not allowed to edit incoming shares');\n\t\t}\n\n\t\tif (\n\t\t\t$permissions === null &&\n\t\t\t$password === null &&\n\t\t\t$sendPasswordByTalk === null &&\n\t\t\t$publicUpload === null &&\n\t\t\t$expireDate === null &&\n\t\t\t$note === null &&\n\t\t\t$label === null &&\n\t\t\t$hideDownload === null &&\n\t\t\t$attributes === null\n\t\t) {\n\t\t\tthrow new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));\n\t\t}\n\n\t\tif ($note !== null) {\n\t\t\t$share->setNote($note);\n\t\t}\n\n\t\tif ($attributes !== null) {\n\t\t\t$share = $this->setShareAttributes($share, $attributes);\n\t\t}\n\t\t$this->checkInheritedAttributes($share);\n\n\t\t/**\n\t\t * expirationdate, password and publicUpload only make sense for link shares\n\t\t */\n\t\tif ($share->getShareType() === IShare::TYPE_LINK\n\t\t\t|| $share->getShareType() === IShare::TYPE_EMAIL) {\n\n\t\t\t/**\n\t\t\t * We do not allow editing link shares that the current user\n\t\t\t * doesn't own. This is confusing and lead to errors when\n\t\t\t * someone else edit a password or expiration date without\n\t\t\t * the share owner knowing about it.\n\t\t\t * We only allow deletion\n\t\t\t */\n\n\t\t\tif ($share->getSharedBy() !== $this->currentUser) {\n\t\t\t\tthrow new OCSForbiddenException('You are not allowed to edit link shares that you don\\'t own');\n\t\t\t}\n\n\t\t\t// Update hide download state\n\t\t\tif ($hideDownload === 'true') {\n\t\t\t\t$share->setHideDownload(true);\n\t\t\t} elseif ($hideDownload === 'false') {\n\t\t\t\t$share->setHideDownload(false);\n\t\t\t}\n\n\t\t\t$newPermissions = null;\n\t\t\tif ($publicUpload === 'true') {\n\t\t\t\t$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;\n\t\t\t} elseif ($publicUpload === 'false') {\n\t\t\t\t$newPermissions = Constants::PERMISSION_READ;\n\t\t\t}\n\n\t\t\tif ($permissions !== null) {\n\t\t\t\t$newPermissions = $permissions;\n\t\t\t\t$newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;\n\t\t\t}\n\n\t\t\tif ($newPermissions !== null) {\n\t\t\t\tif (!$this->hasPermission($newPermissions, Constants::PERMISSION_READ) && !$this->hasPermission($newPermissions, Constants::PERMISSION_CREATE)) {\n\t\t\t\t\tthrow new OCSBadRequestException($this->l->t('Share must at least have READ or CREATE permissions'));\n\t\t\t\t}\n\n\t\t\t\tif (!$this->hasPermission($newPermissions, Constants::PERMISSION_READ) && (\n\t\t\t\t\t$this->hasPermission($newPermissions, Constants::PERMISSION_UPDATE) || $this->hasPermission($newPermissions, Constants::PERMISSION_DELETE)\n\t\t\t\t)) {\n\t\t\t\t\tthrow new OCSBadRequestException($this->l->t('Share must have READ permission if UPDATE or DELETE permission is set'));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t// legacy\n\t\t\t\t$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||\n\t\t\t\t// correct\n\t\t\t\t$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)\n\t\t\t) {\n\t\t\t\tif (!$this->shareManager->shareApiLinkAllowPublicUpload()) {\n\t\t\t\t\tthrow new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));\n\t\t\t\t}\n\n\t\t\t\tif (!($share->getNode() instanceof \\OCP\\Files\\Folder)) {\n\t\t\t\t\tthrow new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));\n\t\t\t\t}\n\n\t\t\t\t// normalize to correct public upload permissions\n\t\t\t\tif ($publicUpload === 'true') {\n\t\t\t\t\t$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($newPermissions !== null) {\n\t\t\t\t// TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones\n\t\t\t\tif (($newPermissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {\n\t\t\t\t\t$newPermissions |= Constants::PERMISSION_SHARE;\n\t\t\t\t}\n\n\t\t\t\t$share->setPermissions($newPermissions);\n\t\t\t\t$permissions = $newPermissions;\n\t\t\t}\n\n\t\t\tif ($password === '') {\n\t\t\t\t$share->setPassword(null);\n\t\t\t} elseif ($password !== null) {\n\t\t\t\t$share->setPassword($password);\n\t\t\t}\n\n\t\t\tif ($label !== null) {\n\t\t\t\tif (strlen($label) > 255) {\n\t\t\t\t\tthrow new OCSBadRequestException(\"Maximum label length is 255\");\n\t\t\t\t}\n\t\t\t\t$share->setLabel($label);\n\t\t\t}\n\n\t\t\tif ($sendPasswordByTalk === 'true') {\n\t\t\t\tif (!$this->appManager->isEnabledForUser('spreed')) {\n\t\t\t\t\tthrow new OCSForbiddenException($this->l->t('\"Sending the password by Nextcloud Talk\" for sharing a file or folder failed because Nextcloud Talk is not enabled.'));\n\t\t\t\t}\n\n\t\t\t\t$share->setSendPasswordByTalk(true);\n\t\t\t} elseif ($sendPasswordByTalk !== null) {\n\t\t\t\t$share->setSendPasswordByTalk(false);\n\t\t\t}\n\t\t}\n\n\t\t// NOT A LINK SHARE\n\t\telse {\n\t\t\tif ($permissions !== null) {\n\t\t\t\t$share->setPermissions($permissions);\n\t\t\t}\n\t\t}\n\n\t\tif ($expireDate === '') {\n\t\t\t$share->setExpirationDate(null);\n\t\t} elseif ($expireDate !== null) {\n\t\t\ttry {\n\t\t\t\t$expireDate = $this->parseDate($expireDate);\n\t\t\t} catch (\\Exception $e) {\n\t\t\t\tthrow new OCSBadRequestException($e->getMessage(), $e);\n\t\t\t}\n\t\t\t$share->setExpirationDate($expireDate);\n\t\t}\n\n\t\ttry {\n\t\t\t$share = $this->shareManager->updateShare($share);\n\t\t} catch (GenericShareException $e) {\n\t\t\t$code = $e->getCode() === 0 ? 403 : $e->getCode();\n\t\t\tthrow new OCSException($e->getHint(), (int)$code);\n\t\t} catch (\\Exception $e) {\n\t\t\tthrow new OCSBadRequestException($e->getMessage(), $e);\n\t\t}\n\n\t\treturn new DataResponse($this->formatShare($share));\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function genererGraphique($id, $type, $hauteur, $largeur, $titre, $valeurs, $nom, $nb, $total)\n {\n $couleurs = array('red', 'blue', 'green', 'pink', 'orange', 'brown', 'gray', 'lime', 'maroon', 'olive', 'navy', 'teal', 'yellow', 'purple');\n echo \"\n \";\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function InsertaTablaCierreRutCursoImparticionAsistenciaEmpresa_2021($rut, $id_curso, $id_imparticion, $asistencia, $id_empresa, $nota, $nota_diagnostico, $estado, $estado_descripcion)\n{\n $connexion = new DatabasePDO();\n\n $sql = \"INSERT INTO tbl_inscripcion_cierre (rut, porcentaje_asistencia, avance, estado, id_curso, id_empresa, id_inscripcion, nota, caso_especial, estado_descripcion) \" .\n \"VALUES (:rut, :asistencia, :asistencia, :estado, :id_curso, :id_empresa, :id_imparticion, :nota, :nota_diagnostico, :estado_descripcion)\";\n $connexion->query($sql);\n $connexion->bind(':rut', $rut);\n $connexion->bind(':asistencia', $asistencia);\n $connexion->bind(':estado', $estado);\n $connexion->bind(':id_curso', $id_curso);\n $connexion->bind(':id_empresa', $id_empresa);\n $connexion->bind(':id_imparticion', $id_imparticion);\n $connexion->bind(':nota', $nota);\n $connexion->bind(':nota_diagnostico', $nota_diagnostico);\n $connexion->bind(':estado_descripcion', $estado_descripcion);\n $connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct($AppName,\n\t\tIRequest $request,\n\t\tIL10N $l10n,\n\t\tIUserManager $userManager,\n\t\tIUserSession $userSession,\n\t\tKeyManager $keyManager,\n\t\tCrypt $crypt,\n\t\tSession $session,\n\t\tISession $ocSession,\n\t\tUtil $util\n\t) {\n\t\tparent::__construct($AppName, $request);\n\t\t$this->l = $l10n;\n\t\t$this->userSession = $userSession;\n\t\t$this->userManager = $userManager;\n\t\t$this->keyManager = $keyManager;\n\t\t$this->crypt = $crypt;\n\t\t$this->session = $session;\n\t\t$this->ocSession = $ocSession;\n\t\t$this->util = $util;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($stage, $approvalMedia, $finalRecoverMedia, $calcFinalMedia, $hasFinalRecovery, $ruleType,\n $hasPartialRecovery, $partialRecoveries)\n {\n $this->stage = $stage;\n $this->approvalMedia = $approvalMedia;\n $this->finalRecoverMedia = $finalRecoverMedia;\n $this->calcFinalMedia = $calcFinalMedia;\n $this->hasFinalRecovery = $hasFinalRecovery;\n $this->ruleType = $ruleType;\n $this->hasPartialRecovery = $hasPartialRecovery;\n $this->partialRecoveries = $partialRecoveries;\n }", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null)\n {\n (!is_null($line_width)) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null;\n (!is_null($compound_type)) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null;\n (!is_null($dash_type)) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null;\n (!is_null($cap_type)) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null;\n (!is_null($join_type)) ? $this->lineStyleProperties['join'] = (string) $join_type : null;\n (!is_null($head_arrow_type)) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null;\n (!is_null($head_arrow_size)) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null;\n (!is_null($end_arrow_type)) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null;\n (!is_null($end_arrow_size)) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null;\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n\t\t$id,\n\t\t$content_id,\n\t\t$timestamp,\n\t\t$type,\n\t\t$format,\n\t\t$is_translatable,\n\t\t$data,\n\t\t$data_translated,\n\t\t$finished\n\t) {\n\t\t$this->id = (int) $id;\n\t\t$this->content_id = (int) $content_id;\n\t\t$this->timestamp = (int) $timestamp;\n\t\t$this->type = (string) $type;\n\t\t$this->format = (string) $format;\n\t\t$this->translatable = (bool) $is_translatable;\n\t\t$this->data = (string) $data;\n\t\t$this->data_translated = (bool) $data_translated;\n\t\t$this->finished = (bool) $finished;\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function createExecution(\n string $projectId,\n string $deploymentId,\n ?string $body,\n array $variables,\n int $timeout,\n string $image,\n string $source,\n string $entrypoint,\n string $version,\n string $path,\n string $method,\n array $headers,\n string $runtimeEntrypoint = null,\n ) {\n if (empty($headers['host'])) {\n $headers['host'] = App::getEnv('_APP_DOMAIN', '');\n }\n\n $runtimeId = \"$projectId-$deploymentId\";\n $route = '/runtimes/' . $runtimeId . '/execution';\n $params = [\n 'runtimeId' => $runtimeId,\n 'variables' => $variables,\n 'body' => $body,\n 'timeout' => $timeout,\n 'path' => $path,\n 'method' => $method,\n 'headers' => $headers,\n\n 'image' => $image,\n 'source' => $source,\n 'entrypoint' => $entrypoint,\n 'cpus' => $this->cpus,\n 'memory' => $this->memory,\n 'version' => $version,\n 'runtimeEntrypoint' => $runtimeEntrypoint,\n ];\n\n $timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);\n\n $response = $this->call(self::METHOD_POST, $route, [ 'x-opr-runtime-id' => $runtimeId ], $params, true, $timeout);\n\n $status = $response['headers']['status-code'];\n if ($status >= 400) {\n $message = \\is_string($response['body']) ? $response['body'] : $response['body']['message'];\n throw new \\Exception($message, $status);\n }\n\n return $response['body'];\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n\t\tIConfig $config,\n\t\tIUserManager $userManager,\n\t\tIGroupManager $groupManager,\n\t\tIAccountManager $accountManager,\n\t\tProfileManager $profileManager,\n\t\tIAppManager $appManager,\n\t\tIFactory $l10nFactory,\n\t\tIL10N $l,\n\t\tIInitialState $initialStateService,\n\t\tIManager $manager\n\t) {\n\t\t$this->config = $config;\n\t\t$this->userManager = $userManager;\n\t\t$this->accountManager = $accountManager;\n\t\t$this->profileManager = $profileManager;\n\t\t$this->groupManager = $groupManager;\n\t\t$this->appManager = $appManager;\n\t\t$this->l10nFactory = $l10nFactory;\n\t\t$this->l = $l;\n\t\t$this->initialStateService = $initialStateService;\n\t\t$this->manager = $manager;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {\n\t\t// convert old settings for the new write1DBarcode() function.\n\t\t$xres = 1 / $xres;\n\t\t$newstyle = array(\n\t\t\t'position' => '',\n\t\t\t'align' => '',\n\t\t\t'stretch' => false,\n\t\t\t'fitwidth' => false,\n\t\t\t'cellfitalign' => '',\n\t\t\t'border' => false,\n\t\t\t'padding' => 0,\n\t\t\t'fgcolor' => array(0,0,0),\n\t\t\t'bgcolor' => false,\n\t\t\t'text' => true,\n\t\t\t'font' => $font,\n\t\t\t'fontsize' => 8,\n\t\t\t'stretchtext' => 4\n\t\t);\n\t\tif ($style & 1) {\n\t\t\t$newstyle['border'] = true;\n\t\t}\n\t\tif ($style & 2) {\n\t\t\t$newstyle['bgcolor'] = false;\n\t\t}\n\t\tif ($style & 4) {\n\t\t\t$newstyle['position'] = 'C';\n\t\t} elseif ($style & 8) {\n\t\t\t$newstyle['position'] = 'L';\n\t\t} elseif ($style & 16) {\n\t\t\t$newstyle['position'] = 'R';\n\t\t}\n\t\tif ($style & 128) {\n\t\t\t$newstyle['text'] = true;\n\t\t}\n\t\tif ($style & 256) {\n\t\t\t$newstyle['stretchtext'] = 4;\n\t\t}\n\t\t$this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function actualizaTablaCierreRut_2021($rut, $id_curso, $id_imparticion, $asistencia, $id_empresa, $nota, $nota_diagnostico, $estado, $estado_descripcion)\n{\n $connexion = new DatabasePDO();\n \n $sql = \"UPDATE tbl_inscripcion_cierre\n SET porcentaje_asistencia = '$asistencia',\n avance = '$asistencia',\n nota = '$nota',\n caso_especial = '$nota_diagnostico',\n estado = '$estado',\n estado_descripcion = '$estado_descripcion'\n WHERE rut = '$rut'\n AND id_curso = '$id_curso'\n AND id_empresa = '$id_empresa'\n AND id_inscripcion = '$id_imparticion'\";\n // echo $sql;\n $connexion->query($sql);\n $connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function afficherRowDossierClientModeTransportModeLicence3($id_cli, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_march=NULL, $statut=NULL, $num_lic=NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$cleared=NULL){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$compteur = 0;\n\t\t\t$bg = '';\n\t\t\t$style = '';\n\n\t\t\t/*echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    num_lic = '.$num_lic;*/\n\t\t\t\t//echo '
    -------'.$sqlStatus;\n\n\t\t\t$sql1 = \"\";\n\t\t\t$sqlOrder = \"\";\n\t\t\t$sqlIdMarch = \"\";\n\t\t\t$sqlStatus = \"\";\n\t\t\t$sqlLicence = \"\";\n\t\t\t$sqlCleared = \"\";\n\n\t\t\tif (isset($commodity) && ($commodity != '')) {\n\t\t\t\t$sql1 = ' AND d.commodity = \"'.$commodity.'\"';\n\t\t\t}\n\t\t\tif ($id_mod_lic == '1') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2' && $id_cli == '857') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.ref_dos DESC';\n\t\t\t}\n\n\t\t\tif (isset($id_march) && ($id_march != '')) {\n\t\t\t\t$sqlIdMarch = ' AND d.id_march = '.$id_march;\n\t\t\t}\n\n\t\t\tif (isset($statut) && ($statut != '')) {\n\t\t\t\t$sqlStatus = ' AND REPLACE(d.statut,\"\\'\",\"\") = \"'.$statut.'\"';\n\t\t\t}\n\n\t\t\tif (isset($num_lic) && ($num_lic != '')) {\n\t\t\t\t$sqlLicence = ' AND d.num_lic = \"'.$num_lic.'\"';\n\t\t\t}\n\n\t\t\tif (isset($cleared) && ($cleared != '')) {\n\t\t\t\t$sqlCleared = ' AND d.cleared = \"'.$cleared.'\"';\n\t\t\t}\n\n if ($_GET['id_mod_lic'] == '1') {\n \n\t\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t\t$sqlClient = ' AND cl.id_cli = \"'.$id_cli.'\"';\n\t\t\t\t}else{\n\t\t\t\t\t$sqlClient = '';\n\t\t\t\t}\n\n }else if ($_GET['id_mod_lic'] == '2') {\n \n\t\t\t\tif (isset($id_cli) && ($id_cli!='')) {\n\t\t\t\t\t$sqlClient = ' AND cl.id_cli = \"'.$id_cli.'\"';\n\t\t\t\t}else{\n\t\t\t\t\t$sqlClient = '';\n\t\t\t\t}\n\n }\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.ref_dos AS ref_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPPER(cl.nom_cli) AS nom_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.ref_fact AS ref_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fob AS fob_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fret AS fret,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.assurance AS assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.autre_frais AS autre_frais,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.num_lic AS num_lic,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.montant_decl AS montant_decl,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.*,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.supplier AS fournisseur,\n\t\t\t\t\t\t\t\t\t\t\t\t\ts.nom_site AS nom_site,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_in AS dgda_in_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_out AS dgda_out_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.custom_deliv AS custom_deliv_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.arrival_date AS arrival_date_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.dgda_out, d.dgda_in) AS dgda_delay,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.custom_deliv, d.arrival_date) AS arrival_deliver_delay\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlClient\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlIdMarch\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlLicence\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlCleared\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sql1\n\t\t\t\t\t\t\t\t\t\t\t\t$sqlOrder\");\n\t\t\t$requete-> execute(array($entree['id_mod_trans'], $entree['id_mod_lic']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t$compteur++;\n\t\t\t\t$bg = \"\";\n\t\t\t\t$color='';\n\t\t\t\t$class = \"\";\n\n\t\t\t\tif ($reponse['cleared'] == '1') {\n\t\t\t\t\t$style = \"style='color: blue;'\";\n\t\t\t\t\t$color = \"color: blue;\";\n\t\t\t\t\t$class = \"bg-primary\";\n\t\t\t\t}else if ($reponse['cleared'] == '2') {\n\t\t\t\t\t$style = \"style='color: red;'\";\n\t\t\t\t\t$color = \"color: red;\";\n\t\t\t\t\t$class = \"bg-danger\";\n\t\t\t\t}else{\n\t\t\t\t\t$style = \"\";\n\t\t\t\t\t$color = \"color: black;\";\n\t\t\t\t\t$class = \"bg-dark\";\n\t\t\t\t}\n\n\t\t\t\t$date_exp = $this-> getLastEpirationLicence($reponse['num_lic']);\n\t\t\t\t$supplier = $this-> getLicence($reponse['num_lic'])['fournisseur'];\n\n\t\t\t\tif (isset($supplier)) {\n\t\t\t\t\t$reponse['fournisseur'] = $supplier;\n\t\t\t\t}\n\n\t\t\t\t//include('modalDeleteDossier.php');\n\t\t\t\t\n\n\t\t\t?>\n\t\t\t\t\" value=\"\">\n\t\t\t\t\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black;\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black; \">\n\t\t\t\t\t\n\t\t\t\t\t afficherRowTableau2($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur);\n\t\t\t\t\t$this-> afficherRowTableau3($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur);\n\t\t\t\t\t\t/*if ($id_mod_trans == '1') {\n\t\t\t\t\t\t\tinclude('importRouteRow.php');\n\t\t\t\t\t\t}else if ($id_mod_trans == '3') {\n\t\t\t\t\t\t\tinclude('importAirRow.php');\n\t\t\t\t\t\t}*/\n\t\t\t\t\t?>\n\t\t\t\t\n\t\t\t closeCursor();\n\t\t\t?>\n\t\t\t_xValues as $xKey => $xValue) {\n\t\t\t$bestFitY = $this->_yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);\n\n\t\t\t$SSres += ($this->_yValues[$xKey] - $bestFitY) * ($this->_yValues[$xKey] - $bestFitY);\n\t\t\tif ($const) {\n\t\t\t\t$SStot += ($this->_yValues[$xKey] - $meanY) * ($this->_yValues[$xKey] - $meanY);\n\t\t\t} else {\n\t\t\t\t$SStot += $this->_yValues[$xKey] * $this->_yValues[$xKey];\n\t\t\t}\n\t\t\t$SScov += ($this->_xValues[$xKey] - $meanX) * ($this->_yValues[$xKey] - $meanY);\n\t\t\tif ($const) {\n\t\t\t\t$SSsex += ($this->_xValues[$xKey] - $meanX) * ($this->_xValues[$xKey] - $meanX);\n\t\t\t} else {\n\t\t\t\t$SSsex += $this->_xValues[$xKey] * $this->_xValues[$xKey];\n\t\t\t}\n\t\t}\n\n\t\t$this->_SSResiduals = $SSres;\n\t\t$this->_DFResiduals = $this->_valueCount - 1 - $const;\n\n\t\tif ($this->_DFResiduals == 0.0) {\n\t\t\t$this->_stdevOfResiduals = 0.0;\n\t\t} else {\n\t\t\t$this->_stdevOfResiduals = sqrt($SSres / $this->_DFResiduals);\n\t\t}\n\t\tif (($SStot == 0.0) || ($SSres == $SStot)) {\n\t\t\t$this->_goodnessOfFit = 1;\n\t\t} else {\n\t\t\t$this->_goodnessOfFit = 1 - ($SSres / $SStot);\n\t\t}\n\n\t\t$this->_SSRegression = $this->_goodnessOfFit * $SStot;\n\t\t$this->_covariance = $SScov / $this->_valueCount;\n\t\t$this->_correlation = ($this->_valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->_valueCount * $sumX2 - pow($sumX,2)) * ($this->_valueCount * $sumY2 - pow($sumY,2)));\n\t\t$this->_slopeSE = $this->_stdevOfResiduals / sqrt($SSsex);\n\t\t$this->_intersectSE = $this->_stdevOfResiduals * sqrt(1 / ($this->_valueCount - ($sumX * $sumX) / $sumX2));\n\t\tif ($this->_SSResiduals != 0.0) {\n\t\t\tif ($this->_DFResiduals == 0.0) {\n\t\t\t\t$this->_F = 0.0;\n\t\t\t} else {\n\t\t\t\t$this->_F = $this->_SSRegression / ($this->_SSResiduals / $this->_DFResiduals);\n\t\t\t}\n\t\t} else {\n\t\t\tif ($this->_DFResiduals == 0.0) {\n\t\t\t\t$this->_F = 0.0;\n\t\t\t} else {\n\t\t\t\t$this->_F = $this->_SSRegression / $this->_DFResiduals;\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct(\n\t\tstring $appName,\n\t\tIRequest $request,\n\t\tIRootFolder $rootFolder,\n\t\tITrashManager $trashManager,\n\t\tIUserSession $userSession,\n\t\tIMimeTypeDetector $mimeTypeDetector,\n\t\tIPreview $previewManager,\n\t\tITimeFactory $time\n\t) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->trashManager = $trashManager;\n\t\t$this->rootFolder = $rootFolder;\n\t\t$this->userSession = $userSession;\n\t\t$this->mimeTypeDetector = $mimeTypeDetector;\n\t\t$this->previewManager = $previewManager;\n\t\t$this->time = $time;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n string $type = '',\n array $vars = [],\n $from = '-1d',\n $to = null,\n string $legend = 'no',\n string $aspect = 'normal',\n ?int $width = null,\n ?int $height = null,\n int $absolute_size = 0,\n $link = true,\n $popup = false,\n $popupTitle = '',\n $device = null,\n $port = null\n ) {\n $this->type = $type;\n $this->vars = $vars;\n $this->from = $from;\n $this->to = $to;\n $this->legend = $legend;\n $this->absolute_size = $absolute_size;\n $this->width = $width ?: ($aspect == 'wide' ? self::DEFAULT_WIDE_WIDTH : self::DEFAULT_NORMAL_WIDTH);\n $this->height = $height ?: ($aspect == 'wide' ? self::DEFAULT_WIDE_HEIGHT : self::DEFAULT_NORMAL_HEIGHT);\n $this->popupTitle = $popupTitle;\n $this->popup = filter_var($popup, FILTER_VALIDATE_BOOLEAN);\n $this->link = $link;\n\n // handle device and port ids/models for convenience could be set in $vars\n if ($device instanceof Device) {\n $this->vars['device'] = $device->device_id;\n } elseif (is_numeric($device)) {\n $this->vars['device'] = $device;\n } elseif ($port instanceof Port) {\n $this->vars['id'] = $port->port_id;\n } elseif (is_numeric($port)) {\n $this->vars['id'] = $port;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function afficherRowDossierClientModeTransportModeLicence2($id_cli, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$premiere_entree, $nombre_dossier_par_page, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_march=NULL, $statut=NULL, $num_lic=NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$cleared=NULL){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$compteur = $premiere_entree;\n\t\t\t$bg = '';\n\t\t\t$style = '';\n\n\t\t\t/*echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    num_lic = '.$num_lic;*/\n\t\t\t\t//echo '
    -------'.$sqlStatus;\n\n\t\t\t$sql1 = \"\";\n\t\t\t$sqlOrder = \"\";\n\t\t\t$sqlIdMarch = \"\";\n\t\t\t$sqlStatus = \"\";\n\t\t\t$sqlLicence = \"\";\n\t\t\t$sqlCleared = \"\";\n\t\t\t$index = 0;\n\n\t\t\tif (isset($commodity) && ($commodity != '')) {\n\t\t\t\t$sql1 = ' AND d.commodity = \"'.$commodity.'\"';\n\t\t\t}\n\t\t\tif ($id_mod_lic == '1') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2' && $id_cli == '857') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2' && $id_cli == '850') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.ref_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}\n\n\t\t\tif (isset($id_march) && ($id_march != '')) {\n\t\t\t\t$sqlIdMarch = ' AND d.id_march = '.$id_march;\n\t\t\t}\n\n\t\t\tif (isset($statut) && ($statut != '')) {\n\t\t\t\t$sqlStatus = ' AND REPLACE(d.statut,\"\\'\", \" \") = \"'.$statut.'\"';\n\t\t\t}\n\n\t\t\tif (isset($num_lic) && ($num_lic != '')) {\n\t\t\t\t$sqlLicence = ' AND d.num_lic = \"'.$num_lic.'\"';\n\t\t\t}else if ($id_mod_lic == '2' && $id_cli == '857') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}\n\t\t\telse if ($id_mod_lic == '2' && $id_cli == '850') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}\n\n\t\t\tif (isset($cleared) && ($cleared != '')) {\n\t\t\t\t$sqlCleared = ' AND d.cleared = \"'.$cleared.'\"';\n\t\t\t}\n\n\n\t\t\t\t if (isset($_GET['page'])) {\n\t\t\t\t $page = '&page='.$_GET['page'];\n\t\t\t\t }else{\n\t\t\t\t $page = '&page=1';\n\t\t\t\t }\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.ref_dos AS ref_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPPER(cl.nom_cli) AS nom_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.ref_fact AS ref_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fob AS fob_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fret AS fret,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.assurance AS assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.autre_frais AS autre_frais,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.num_lic AS num_lic,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.montant_decl AS montant_decl,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.*,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.supplier AS fournisseur,\n\t\t\t\t\t\t\t\t\t\t\t\t\ts.nom_site AS nom_site,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_in AS dgda_in_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_out AS dgda_out_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.custom_deliv AS custom_deliv_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.arrival_date AS arrival_date_1,\n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_lic='2' AND d.id_mod_trans='1' AND d.cleared<>'2',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING CRF', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD/INSURANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NULL AND d.date_assurance IS NOT NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING AD',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_crf IS NOT NULL AND d.date_ad IS NOT NULL AND d.date_assurance IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'AWAITING INSURANCE',\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_decl IS NULL AND d.ref_decl IS NULL, 'UNDER PREPARATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_liq IS NULL AND d.ref_liq IS NULL, 'AWAITING LIQUIDATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NULL AND d.ref_quit IS NULL, 'AWAITING QUITTANCE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.date_quit IS NOT NULL AND d.ref_quit IS NOT NULL AND d.dgda_out IS NULL, 'AWAITING BAE/BS', \n\t\t\t\t\t\t\t\t\t\t\t\t\t IF(d.dgda_out IS NOT NULL AND d.dispatch_deliv IS NOT NULL, 'CLEARING COMPLETED', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_lic='1' AND d.cleared<>'2', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.load_date IS NOT NULL AND d.ceec_in IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'LOADED',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.ceec_in IS NOT NULL AND d.ceec_out IS NULL, 'AT CEEC',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.ceec_out IS NOT NULL AND d.min_div_in IS NULL, 'CEEC OUT',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.min_div_in IS NOT NULL AND d.min_div_out IS NULL, 'AT MINE DIVISION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.min_div_out IS NOT NULL AND d.ref_decl IS NULL, 'MINE DIVISION OUT',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.ref_decl IS NOT NULL AND d.ref_liq IS NULL, 'DECLARATION',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.ref_liq IS NOT NULL AND d.ref_quit IS NULL, 'LIQUIDATED',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.ref_quit IS NOT NULL AND d.gov_in IS NULL, 'DGDA OUT',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.gov_in IS NOT NULL AND d.gov_out IS NULL, 'AT GOVERNOR\\'S OFFICE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.gov_out IS NOT NULL AND d.dispatch_date IS NULL, 'GOVERNOR\\'S OFFICE OUT',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.dispatch_date IS NOT NULL AND d.klsa_arriv IS NULL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'DISPATCHED', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.klsa_arriv IS NOT NULL AND d.end_form IS NULL, 'AT BORDER',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.end_form IS NOT NULL AND d.exit_drc IS NULL, 'UNDER FORMALITIES',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.exit_drc IS NOT NULL, 'EXIT DRC', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, d.statut )\n\t\t\t\t\t\t\t\t\t\t\t\t\t) AS statut,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2' AND d.cleared<>2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.klsa_arriv IS NOT NULL AND d.wiski_arriv IS NULL,'ARRIVED AT K\\'LSA', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.wiski_arriv IS NOT NULL AND d.dispatch_klsa IS NULL, 'AT WISKI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.dispatch_klsa IS NOT NULL, 'DISPATCHED FROM K\\'LSA', 'EXCEPTED TO ARRIVE')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t, '') AS klsa_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2' AND d.cleared<>2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.bond_warehouse='LUBUMBASHI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL AND d.warehouse_dep IS NOT NULL, 'DISPATCHED FROM AMICONGO', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL, 'ARRIVED AT AMICONGO', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'') AS amicongo_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.id_mod_trans='1' AND d.id_mod_lic='2' AND d.cleared<>2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.bond_warehouse='KOLWEZI',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL AND d.warehouse_dep IS NOT NULL, 'DISPATCHED FROM WAREHOUSE', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIF(d.warehouse_arriv IS NOT NULL, 'ARRIVED AT WAREHOUSE', '')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t,'') AS kzi_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.dgda_out, d.dgda_in) AS dgda_delay,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.custom_deliv, d.arrival_date) AS arrival_deliver_delay\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND cl.id_cli = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlIdMarch\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlLicence\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlCleared\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sql1\n\t\t\t\t\t\t\t\t\t\t\t\t$sqlOrder\n\t\t\t\t\t\t\t\t\t\t\t\tLIMIT $premiere_entree, $nombre_dossier_par_page\");\n\t\t\t$requete-> execute(array($entree['id_cli'], $entree['id_mod_trans'], $entree['id_mod_lic']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t$compteur++;\n\t\t\t\t$index++;\n\t\t\t\t$bg = \"\";\n\t\t\t\t$color='';\n\t\t\t\t$class = \"\";\n\n\t\t\t\tif ($reponse['cleared'] == '1') {\n\t\t\t\t\t$style = \"style='color: blue;'\";\n\t\t\t\t\t$color = \"color: blue;\";\n\t\t\t\t\t$class = \"bg-primary\";\n\t\t\t\t}else if ($reponse['cleared'] == '2') {\n\t\t\t\t\t$style = \"style='color: red;'\";\n\t\t\t\t\t$color = \"color: red;\";\n\t\t\t\t\t$class = \"bg-danger\";\n\t\t\t\t}else{\n\t\t\t\t\t$style = \"\";\n\t\t\t\t\t$color = \"\";\n\t\t\t\t\t$class = \"\";\n\t\t\t\t}\n\n\t\t\t\tif (($this-> verifierErreurDateKlsa($reponse['id_dos']) == true) || ($this-> verifierDelaiDateKlsa($reponse['id_dos']) == true)) {\n\t\t\t\t\t$clignoteDos = ' clignoteb';\n\t\t\t\t\t$couleurDos = ' color: rgb(255,69,0);';\n\t\t\t\t}else{\n\t\t\t\t\t$clignoteDos = '';\n\t\t\t\t\t$couleurDos = '';\n\t\t\t\t}\n\n\t\t\t\tif (empty($this-> getSouscriptionLicence($reponse['num_lic'])) && ($this-> verifierSouscriptionLicence($id_cli, $id_mod_lic) == true) && ($reponse['num_lic'] != 'UNDER VALUE')) {\n\t\t\t\t\t$clignoteDos = ' clignoteb';\n\t\t\t\t\t$couleurDos = ' color: rgb(0,0,0);';\n\t\t\t\t}else{\n\t\t\t\t\t$clignoteDos = '';\n\t\t\t\t\t$couleurDos = '';\n\t\t\t\t}\n\n\t\t\t\t$date_exp = $this-> getLastEpirationLicence($reponse['num_lic']);\n\t\t\t\t$supplier = $this-> getLicence($reponse['num_lic'])['fournisseur'];\n\n\t\t\t\tif (isset($supplier)) {\n\t\t\t\t\t$reponse['fournisseur'] = $supplier;\n\t\t\t\t}\n\n\t\t\t\t//include('modalDeleteDossier.php');\n\t\t\t\t\n\t\t\t?>\n\t\t\t\t\" value=\"\">\n\t\t\t\t\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black;\" >\n\t\t\t\t\t \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black; \">\" style=\"\">\n\t\t\t\t\t getDataUtilisateur($_SESSION['id_util'])['tracking_enab'])){\n\t\t\t\t\t \tif($this-> getDossierFacture2($reponse['id_dos'])==false){\n\t\t\t\t\t ?>\n\t\t\t\t\t\t&id_mod_trans=&id_mod_trac=&commodity=&statut=&id_march=&page=&id_dos=','pop1','width=80,height=80');\">   \n\n\t\t\t\t\t\t getDataUtilisateur($_SESSION['id_util'])['tracking_delete'] == '1' && ($index == '1' && $premiere_entree == '0')) {\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t&id_mod_trans=&id_mod_trac=&commodity=&statut=&id_march=&id_dos=','pop1','width=80,height=80');\">\n\t\t\t \n\t\t\t \n\t\t\t getDataUtilisateur($_SESSION['id_util'])['tracking_log'] == '1') {\n\t\t\t\t\t\t?>\n\t\t\t\t\t \t','pop1','width=900,height=950');\">\n\t\t\t\t\t \t\t\n\t \t\n\t\t \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n getNombreDocumentDossier($reponse['id_dos']);?>\n Toggle Dropdown\n
    \n \t&id_cli=&id_mod_trans=&id_mod_trac=&id_march=&commodity=&page=','pop1','width=80,height=80');\">\n\t\t\t\t\t\t\t\t Ajouter\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
    \n getListeDocumentForDossier($reponse['id_dos'], $reponse['id_mod_lic']);\n ?>\n
    \n
    \n\t\t\t\t\t\n\t\t\t\t\t afficherRowTableau($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur, $reponse['statut'], $reponse['klsa_status'], $reponse['amicongo_status'], $reponse['kzi_status']);\n\t\t\t\t\t\t/*if ($id_mod_trans == '1') {\n\t\t\t\t\t\t\tinclude('importRouteRow.php');\n\t\t\t\t\t\t}else if ($id_mod_trans == '3') {\n\t\t\t\t\t\t\tinclude('importAirRow.php');\n\t\t\t\t\t\t}*/\n\t\t\t\t\t?>\n\t\t\t\t\n\t\t\t closeCursor();\n\t\t\t?>\n\t\t\t
    \n\t
    \n\t\t\".htmlentities($msg[\n\t\t\n\t\t\t$titre\n\t\t\n\t
    \n\t\n\t\";\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {\n\t\t$prev_cell_margin = $this->cell_margin;\n\t\t$prev_cell_padding = $this->cell_padding;\n\t\t$txt = $this->removeSHY($txt);\n\t\t$rs = ''; //string to be returned\n\t\t$this->adjustCellPadding($border);\n\t\tif (!$ignore_min_height) {\n\t\t\t$min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];\n\t\t\tif ($h < $min_cell_height) {\n\t\t\t\t$h = $min_cell_height;\n\t\t\t}\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h);\n\t\t$k = $this->k;\n\t\tif ($this->rtl) {\n\t\t\t$x = $this->x - $this->cell_margin['R'];\n\t\t} else {\n\t\t\t$x = $this->x + $this->cell_margin['L'];\n\t\t}\n\t\t$y = $this->y + $this->cell_margin['T'];\n\t\t$prev_font_stretching = $this->font_stretching;\n\t\t$prev_font_spacing = $this->font_spacing;\n\t\t// cell vertical alignment\n\t\tswitch ($calign) {\n\t\t\tcase 'A': {\n\t\t\t\t// font top\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= $this->cell_padding['T'];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h - $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'L': {\n\t\t\t\t// font baseline\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= ($this->cell_padding['T'] + $this->FontAscent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B'] - $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h + $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'D': {\n\t\t\t\t// font bottom\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B']);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h + $this->FontAscent + $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B': {\n\t\t\t\t// cell bottom\n\t\t\t\t$y -= $h;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\tcase 'M': {\n\t\t\t\t// cell center\n\t\t\t\t$y -= ($h / 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'T': {\n\t\t\t\t// cell top\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// text vertical alignment\n\t\tswitch ($valign) {\n\t\t\tcase 'T': {\n\t\t\t\t// top\n\t\t\t\t$yt = $y + $this->cell_padding['T'];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B': {\n\t\t\t\t// bottom\n\t\t\t\t$yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'C':\n\t\t\tcase 'M': {\n\t\t\t\t// center\n\t\t\t\t$yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$basefonty = $yt + $this->FontAscent;\n\t\tif ($this->empty_string($w) OR ($w <= 0)) {\n\t\t\tif ($this->rtl) {\n\t\t\t\t$w = $x - $this->lMargin;\n\t\t\t} else {\n\t\t\t\t$w = $this->w - $this->rMargin - $x;\n\t\t\t}\n\t\t}\n\t\t$s = '';\n\t\t// fill and borders\n\t\tif (is_string($border) AND (strlen($border) == 4)) {\n\t\t\t// full border\n\t\t\t$border = 1;\n\t\t}\n\t\tif ($fill OR ($border == 1)) {\n\t\t\tif ($fill) {\n\t\t\t\t$op = ($border == 1) ? 'B' : 'f';\n\t\t\t} else {\n\t\t\t\t$op = 'S';\n\t\t\t}\n\t\t\tif ($this->rtl) {\n\t\t\t\t$xk = (($x - $w) * $k);\n\t\t\t} else {\n\t\t\t\t$xk = ($x * $k);\n\t\t\t}\n\t\t\t$s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);\n\t\t}\n\t\t// draw borders\n\t\t$s .= $this->getCellBorder($x, $y, $w, $h, $border);\n\t\tif ($txt != '') {\n\t\t\t$txt2 = $txt;\n\t\t\tif ($this->isunicode) {\n\t\t\t\tif (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {\n\t\t\t\t\t$txt2 = $this->UTF8ToLatin1($txt2);\n\t\t\t\t} else {\n\t\t\t\t\t$unicode = $this->UTF8StringToArray($txt); // array of UTF-8 unicode values\n\t\t\t\t\t$unicode = $this->utf8Bidi($unicode, '', $this->tmprtl);\n\t\t\t\t\tif (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {\n\t\t\t\t\t\t// ---- Fix for bug #2977340 \"Incorrect Thai characters position arrangement\" ----\n\t\t\t\t\t\t// NOTE: this doesn't work with HTML justification\n\t\t\t\t\t\t// Symbols that could overlap on the font top (only works in LTR)\n\t\t\t\t\t\t$topchar = array(3611, 3613, 3615, 3650, 3651, 3652); // chars that extends on top\n\t\t\t\t\t\t$topsym = array(3633, 3636, 3637, 3638, 3639, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662); // symbols with top position\n\t\t\t\t\t\t$numchars = count($unicode); // number of chars\n\t\t\t\t\t\t$unik = 0;\n\t\t\t\t\t\t$uniblock = array();\n\t\t\t\t\t\t$uniblock[$unik] = array();\n\t\t\t\t\t\t$uniblock[$unik][] = $unicode[0];\n\t\t\t\t\t\t// resolve overlapping conflicts by splitting the string in several parts\n\t\t\t\t\t\tfor ($i = 1; $i < $numchars; ++$i) {\n\t\t\t\t\t\t\t// check if symbols overlaps at top\n\t\t\t\t\t\t\tif (in_array($unicode[$i], $topsym) AND (in_array($unicode[($i - 1)], $topsym) OR in_array($unicode[($i - 1)], $topchar))) {\n\t\t\t\t\t\t\t\t// move symbols to another array\n\t\t\t\t\t\t\t\t++$unik;\n\t\t\t\t\t\t\t\t$uniblock[$unik] = array();\n\t\t\t\t\t\t\t\t$uniblock[$unik][] = $unicode[$i];\n\t\t\t\t\t\t\t\t++$unik;\n\t\t\t\t\t\t\t\t$uniblock[$unik] = array();\n\t\t\t\t\t\t\t\t$unicode[$i] = 0x200b; // Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$uniblock[$unik][] = $unicode[$i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// ---- END OF Fix for bug #2977340\n\t\t\t\t\t}\n\t\t\t\t\t$txt2 = $this->arrUTF8ToUTF16BE($unicode, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$txt2 = $this->_escape($txt2);\n\t\t\t// get current text width (considering general font stretching and spacing)\n\t\t\t$txwidth = $this->GetStringWidth($txt);\n\t\t\t$width = $txwidth;\n\t\t\t// check for stretch mode\n\t\t\tif ($stretch > 0) {\n\t\t\t\t// calculate ratio between cell width and text width\n\t\t\t\tif ($width <= 0) {\n\t\t\t\t\t$ratio = 1;\n\t\t\t\t} else {\n\t\t\t\t\t$ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);\n\t\t\t\t}\n\t\t\t\t// check if stretching is required\n\t\t\t\tif (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {\n\t\t\t\t\t// the text will be stretched to fit cell width\n\t\t\t\t\tif ($stretch > 2) {\n\t\t\t\t\t\t// set new character spacing\n\t\t\t\t\t\t$this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// set new horizontal stretching\n\t\t\t\t\t\t$this->font_stretching *= $ratio;\n\t\t\t\t\t}\n\t\t\t\t\t// recalculate text width (the text fills the entire cell)\n\t\t\t\t\t$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];\n\t\t\t\t\t// reset alignment\n\t\t\t\t\t$align = '';\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t// apply font stretching\n\t\t\t\t$rs .= sprintf('BT %.2F Tz ET ', $this->font_stretching);\n\t\t\t}\n\t\t\tif ($this->font_spacing != 0) {\n\t\t\t\t// increase/decrease font spacing\n\t\t\t\t$rs .= sprintf('BT %.2F Tc ET ', ($this->font_spacing * $this->k));\n\t\t\t}\n\t\t\tif ($this->ColorFlag) {\n\t\t\t\t$s .= 'q '.$this->TextColor.' ';\n\t\t\t}\n\t\t\t// rendering mode\n\t\t\t$s .= sprintf('BT %d Tr %.2F w ET ', $this->textrendermode, $this->textstrokewidth);\n\t\t\t// count number of spaces\n\t\t\t$ns = substr_count($txt, chr(32));\n\t\t\t// Justification\n\t\t\t$spacewidth = 0;\n\t\t\tif (($align == 'J') AND ($ns > 0)) {\n\t\t\t\tif ($this->isUnicodeFont()) {\n\t\t\t\t\t// get string width without spaces\n\t\t\t\t\t$width = $this->GetStringWidth(str_replace(' ', '', $txt));\n\t\t\t\t\t// calculate average space width\n\t\t\t\t\t$spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / $this->FontSize;\n\t\t\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t\t\t// word spacing is affected by stretching\n\t\t\t\t\t\t$spacewidth /= ($this->font_stretching / 100);\n\t\t\t\t\t}\n\t\t\t\t\t// set word position to be used with TJ operator\n\t\t\t\t\t$txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%.3F', $spacewidth).' (', $txt2);\n\t\t\t\t\t$unicode_justification = true;\n\t\t\t\t} else {\n\t\t\t\t\t// get string width\n\t\t\t\t\t$width = $txwidth;\n\t\t\t\t\t// new space width\n\t\t\t\t\t$spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;\n\t\t\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t\t\t// word spacing (Tw) is affected by stretching\n\t\t\t\t\t\t$spacewidth /= ($this->font_stretching / 100);\n\t\t\t\t\t}\n\t\t\t\t\t// set word spacing\n\t\t\t\t\t$rs .= sprintf('BT %.3F Tw ET ', $spacewidth);\n\t\t\t\t}\n\t\t\t\t$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];\n\t\t\t}\n\t\t\t// replace carriage return characters\n\t\t\t$txt2 = str_replace(\"\\r\", ' ', $txt2);\n\t\t\tswitch ($align) {\n\t\t\t\tcase 'C': {\n\t\t\t\t\t$dx = ($w - $width) / 2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'R': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $this->cell_padding['R'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $w - $width - $this->cell_padding['R'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'L': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $w - $width - $this->cell_padding['L'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $this->cell_padding['L'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'J':\n\t\t\t\tdefault: {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $this->cell_padding['R'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $this->cell_padding['L'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->rtl) {\n\t\t\t\t$xdx = $x - $dx - $width;\n\t\t\t} else {\n\t\t\t\t$xdx = $x + $dx;\n\t\t\t}\n\t\t\t$xdk = $xdx * $k;\n\t\t\t// print text\n\t\t\t$s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);\n\t\t\tif (isset($uniblock)) {\n\t\t\t\t// print overlapping characters as separate string\n\t\t\t\t$xshift = 0; // horizontal shift\n\t\t\t\t$ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);\n\t\t\t\t$spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));\n\t\t\t\tforeach ($uniblock as $uk => $uniarr) {\n\t\t\t\t\tif (($uk % 2) == 0) {\n\t\t\t\t\t\t// x space to skip\n\t\t\t\t\t\tif ($spacewidth != 0) {\n\t\t\t\t\t\t\t// justification shift\n\t\t\t\t\t\t\t$xshift += (count(array_keys($uniarr, 32)) * $spw);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$xshift += $this->GetArrStringWidth($uniarr); // + shift justification\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// character to print\n\t\t\t\t\t\t$topchr = $this->arrUTF8ToUTF16BE($uniarr, false);\n\t\t\t\t\t\t$topchr = $this->_escape($topchr);\n\t\t\t\t\t\t$s .= sprintf(' BT %.2F %.2F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->underline) {\n\t\t\t\t$s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->linethrough) {\n\t\t\t\t$s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->overline) {\n\t\t\t\t$s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->ColorFlag) {\n\t\t\t\t$s .= ' Q';\n\t\t\t}\n\t\t\tif ($link) {\n\t\t\t\t$this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);\n\t\t\t}\n\t\t}\n\t\t// output cell\n\t\tif ($s) {\n\t\t\t// output cell\n\t\t\t$rs .= $s;\n\t\t\tif ($this->font_spacing != 0) {\n\t\t\t\t// reset font spacing mode\n\t\t\t\t$rs .= ' BT 0 Tc ET';\n\t\t\t}\n\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t// reset font stretching mode\n\t\t\t\t$rs .= ' BT 100 Tz ET';\n\t\t\t}\n\t\t}\n\t\t// reset word spacing\n\t\tif (!$this->isUnicodeFont() AND ($align == 'J')) {\n\t\t\t$rs .= ' BT 0 Tw ET';\n\t\t}\n\t\t// reset stretching and spacing\n\t\t$this->font_stretching = $prev_font_stretching;\n\t\t$this->font_spacing = $prev_font_spacing;\n\t\t$this->lasth = $h;\n\t\tif ($ln > 0) {\n\t\t\t//Go to the beginning of the next line\n\t\t\t$this->y = $y + $h + $this->cell_margin['B'];\n\t\t\tif ($ln == 1) {\n\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t$this->x = $this->w - $this->rMargin;\n\t\t\t\t} else {\n\t\t\t\t\t$this->x = $this->lMargin;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// go left or right by case\n\t\t\tif ($this->rtl) {\n\t\t\t\t$this->x = $x - $w - $this->cell_margin['L'];\n\t\t\t} else {\n\t\t\t\t$this->x = $x + $w + $this->cell_margin['R'];\n\t\t\t}\n\t\t}\n\t\t$gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.\"\\n\";\n\t\t$rs = $gstyles.$rs;\n\t\t$this->cell_padding = $prev_cell_padding;\n\t\t$this->cell_margin = $prev_cell_margin;\n\t\treturn $rs;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public static function getLeftJoinCriteria(\n string $itemtype,\n string $ref_table,\n array &$already_link_tables,\n string $new_table,\n string $linkfield,\n bool $meta = false,\n string $meta_type = '',\n array $joinparams = [],\n string $field = ''\n ): array {\n /** @var \\DBmysql $DB */\n global $DB;\n // Rename table for meta left join\n $AS = \"\";\n $nt = $new_table;\n $cleannt = $nt;\n\n // Virtual field no link\n if (\\Search::isVirtualField($linkfield)) {\n return [];\n }\n\n $complexjoin = \\Search::computeComplexJoinID($joinparams);\n\n $is_fkey_composite_on_self = getTableNameForForeignKeyField($linkfield) === $ref_table\n && $linkfield !== getForeignKeyFieldForTable($ref_table);\n\n // Auto link\n if ($ref_table === $new_table && empty($complexjoin) && !$is_fkey_composite_on_self) {\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n return self::getDropdownTranslationJoinCriteria(\n $transAS,\n $nt,\n $transitemtype,\n $field\n );\n }\n return [];\n }\n\n // Multiple link possibilies case\n if (!empty($linkfield) && ($linkfield !== getForeignKeyFieldForTable($new_table))) {\n $nt .= \"_\" . $linkfield;\n $AS = \" AS `$nt`\";\n }\n\n if (!empty($complexjoin)) {\n $nt .= \"_\" . $complexjoin;\n $AS = \" AS `$nt`\";\n }\n\n $addmetanum = \"\";\n $rt = $ref_table;\n $cleanrt = $rt;\n if ($meta) {\n $addmetanum = self::getMetaTableUniqueSuffix($new_table, $meta_type);\n $AS = \" AS `$nt$addmetanum`\";\n $nt = $nt . $addmetanum;\n }\n\n // Do not take into account standard linkfield\n $tocheck = $nt . \".\" . $linkfield;\n if ($linkfield === getForeignKeyFieldForTable($new_table)) {\n $tocheck = $nt;\n }\n\n if (in_array($tocheck, $already_link_tables, true)) {\n return [];\n }\n $already_link_tables[] = $tocheck;\n\n // Handle mixed group case for AllAssets and ReservationItem\n if ($tocheck === 'glpi_groups' && ($itemtype === \\AllAssets::class || $itemtype === \\ReservationItem::class)) {\n $already_link_tables[] = 'glpi_groups_items';\n return [\n 'LEFT JOIN' => [\n 'glpi_groups_items' => [\n 'ON' => [\n 'glpi_groups_items' => 'items_id',\n $rt => 'id', [\n 'AND' => [\n 'glpi_groups_items.itemtype' => $rt . '_TYPE', // Placeholder to be replaced at the end of the SQL construction during union case handling\n 'glpi_groups_items.type' => Group_Item::GROUP_TYPE_NORMAL,\n ]\n ]\n ]\n ],\n 'glpi_groups' => [\n 'ON' => [\n 'glpi_groups' => 'id',\n 'glpi_groups_items' => 'groups_id'\n ]\n ]\n ]\n ];\n }\n\n $specific_leftjoin_criteria = [];\n\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $plugin_name = $plug['plugin'];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = static function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables);\n }\n return [];\n };\n $specific_leftjoin_criteria = \\Plugin::doOneHook($plugin_name, $hook_closure);\n $specific_leftjoin_criteria = $specific_leftjoin_criteria ?? []; // convert null into an empty array\n if (!is_array($specific_leftjoin_criteria)) {\n // Toolbox::deprecated('Plugin hook ' . $hook_function . ' should return an array of join criteria');\n $specific_leftjoin_criteria = self::parseJoinString($specific_leftjoin_criteria);\n }\n }\n\n // Link with plugin tables : need to know left join structure\n if (\n empty($specific_leftjoin_criteria)\n && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $new_table, $matches)\n ) {\n if (count($matches) == 2) {\n $plugin_name = $matches[1];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = static function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return self::parseJoinString($hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables) ?? '');\n }\n return '';\n };\n $specific_leftjoin_criteria = self::parseJoinString(\\Plugin::doOneHook($plugin_name, $hook_closure) ?? '');\n }\n }\n if (!empty($linkfield)) {\n $before_criteria = [];\n\n if (isset($joinparams['beforejoin']) && is_array($joinparams['beforejoin'])) {\n if (isset($joinparams['beforejoin']['table'])) {\n $joinparams['beforejoin'] = [$joinparams['beforejoin']];\n }\n\n foreach ($joinparams['beforejoin'] as $tab) {\n if (isset($tab['table'])) {\n $intertable = $tab['table'];\n $interlinkfield = $tab['linkfield'] ?? getForeignKeyFieldForTable($intertable);\n\n $interjoinparams = $tab['joinparams'] ?? [];\n /** @noinspection SlowArrayOperationsInLoopInspection */\n $before_criteria = array_merge_recursive($before_criteria, self::getLeftJoinCriteria(\n $itemtype,\n $rt,\n $already_link_tables,\n $intertable,\n $interlinkfield,\n (bool) $meta,\n $meta_type,\n $interjoinparams\n ));\n\n // No direct link with the previous joins\n if (!isset($tab['joinparams']['nolink']) || !$tab['joinparams']['nolink']) {\n $cleanrt = $intertable;\n $complexjoin = self::computeComplexJoinID($interjoinparams);\n if (!empty($interlinkfield) && ($interlinkfield !== getForeignKeyFieldForTable($intertable))) {\n $intertable .= \"_\" . $interlinkfield;\n }\n if (!empty($complexjoin)) {\n $intertable .= \"_\" . $complexjoin;\n }\n if ($meta) {\n $intertable .= self::getMetaTableUniqueSuffix($cleanrt, $meta_type);\n }\n $rt = $intertable;\n }\n }\n }\n }\n\n $addcondition = '';\n $add_criteria = $joinparams['condition'] ?? [];\n if (!is_array($add_criteria)) {\n if (empty($add_criteria)) {\n $add_criteria = [];\n } else {\n $add_criteria = [new QueryExpression($add_criteria)];\n }\n }\n $append_join_criteria = static function (&$join_fkey, $additional_criteria) {\n if (empty($additional_criteria)) {\n return;\n }\n $add_link = 'AND';\n if (is_array($additional_criteria)) {\n $first_criteria = reset($additional_criteria) ?? '';\n if (is_string($first_criteria) || is_a($first_criteria, QueryExpression::class)) {\n $first_criteria = trim($first_criteria);\n // If the first criteria starts with AND or OR, use it as a link operator\n if (preg_match('/^(AND|OR)\\s+/', $first_criteria, $matches)) {\n $add_link = $matches[1];\n $first_criteria = trim(substr($first_criteria, strlen($add_link)));\n array_shift($additional_criteria);\n array_unshift($additional_criteria, $first_criteria);\n }\n }\n }\n if (count(array_keys($join_fkey)) === 2) {\n $join_fkey[] = [$add_link => $additional_criteria];\n } else {\n // Find last key\n $last_key = array_keys($join_fkey);\n $last_key = array_pop($last_key);\n // Append new criteria to the last key\n $join_fkey[$last_key]['AND'][] = [$add_link => $additional_criteria];\n }\n };\n $placeholders = [\n '`REFTABLE`' => \"`$rt`\",\n 'REFTABLE' => \"`$rt`\",\n '`NEWTABLE`' => \"`$nt`\",\n 'NEWTABLE' => \"`$nt`\",\n ];\n // Recursively walk through add_criteria array and make the placeholder replacements in the keys and values\n $replace_placeholders = static function ($add_criteria) use (&$replace_placeholders, $placeholders) {\n $new_criteria = [];\n foreach ($add_criteria as $key => $value) {\n $new_key = strtr($key, $placeholders);\n $replaced_key = (string) $new_key !== (string) $key;\n if (is_array($value)) {\n $new_criteria[$new_key] = $replace_placeholders($value);\n } else if (is_a($value, QueryExpression::class)) {\n $value_string = $value->getValue();\n $new_value = strtr($value_string, $placeholders);\n $new_criteria[$new_key] = new QueryExpression($new_value);\n } else if ($value !== null) {\n $new_criteria[$new_key] = strtr($value, $placeholders);\n } else {\n $new_criteria[$new_key] = $value;\n }\n if ($replaced_key) {\n unset($new_criteria[$key]);\n }\n }\n return $new_criteria;\n };\n $add_criteria = $replace_placeholders($add_criteria);\n\n if (!isset($joinparams['jointype'])) {\n $joinparams['jointype'] = 'standard';\n }\n\n if (empty($specific_leftjoin_criteria)) {\n switch ($joinparams['jointype']) {\n case 'child':\n $linkfield = $joinparams['linkfield'] ?? getForeignKeyFieldForTable($cleanrt);\n\n // Child join\n $child_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $rt => 'id',\n $nt => $linkfield\n ]\n ]\n ]\n ];\n $append_join_criteria($child_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $child_join);\n break;\n\n case 'item_item':\n // Item_Item join\n $item_item_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $rt => 'id',\n $nt => getForeignKeyFieldForTable($cleanrt) . '_1',\n [\n 'OR' => [\n new QueryExpression($DB::quoteName(\"$rt.id\") . ' = ' . $DB::quoteName(\"$nt.\" . getForeignKeyFieldForTable($cleanrt) . '_2'))\n ]\n ]\n ]\n ]\n ]\n ];\n $append_join_criteria($item_item_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $item_item_join);\n break;\n\n case 'item_item_revert':\n // Item_Item join reverting previous item_item\n $item_item_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $nt => 'id',\n $rt => getForeignKeyFieldForTable($cleannt) . '_1',\n [\n 'OR' => [\n new QueryExpression($DB::quoteName(\"$nt.id\") . ' = ' . $DB::quoteName(\"$rt.\" . getForeignKeyFieldForTable($cleannt) . '_2'))\n ]\n ]\n ]\n ]\n ]\n ];\n $append_join_criteria($item_item_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $item_item_join);\n break;\n\n case \"mainitemtype_mainitem\":\n $addmain = 'main';\n //addmain defined to be used in itemtype_item case\n\n case \"itemtype_item\":\n if (!isset($addmain)) {\n $addmain = '';\n }\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n\n $items_id_column = 'items_id';\n if (\n isset($joinparams['specific_items_id_column'])\n && !empty($joinparams['specific_items_id_column'])\n ) {\n $items_id_column = $joinparams['specific_items_id_column'];\n }\n\n $itemtype_column = 'itemtype';\n if (\n isset($joinparams['specific_itemtype_column'])\n && !empty($joinparams['specific_itemtype_column'])\n ) {\n $itemtype_column = $joinparams['specific_itemtype_column'];\n }\n\n // Itemtype join\n $itemtype_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $rt => 'id',\n $nt => \"{$addmain}{$items_id_column}\",\n [\n 'AND' => [\n \"$nt.{$addmain}{$itemtype_column}\" => $used_itemtype\n ]\n ]\n ]\n ]\n ]\n ];\n $append_join_criteria($itemtype_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $itemtype_join);\n break;\n\n case \"itemtype_item_revert\":\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $itemtype_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $nt => 'id',\n $rt => 'items_id',\n [\n 'AND' => [\n \"$rt.itemtype\" => $used_itemtype\n ]\n ]\n ]\n ]\n ]\n ];\n $append_join_criteria($itemtype_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $itemtype_join);\n break;\n\n case \"itemtypeonly\":\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $itemtype_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $nt => 'itemtype',\n new QueryExpression(\"'$used_itemtype'\"),\n ]\n ]\n ]\n ];\n $append_join_criteria($itemtype_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $itemtype_join);\n break;\n\n case \"custom_condition_only\":\n $specific_leftjoin_criteria = ['LEFT JOIN' => [\"$new_table$AS\" => $add_criteria]];\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, self::getDropdownTranslationJoinCriteria(\n $transAS,\n $nt,\n $transitemtype,\n $field\n ));\n }\n break;\n\n default:\n // Standard join\n $standard_join = [\n 'LEFT JOIN' => [\n \"$new_table$AS\" => [\n 'ON' => [\n $rt => $linkfield,\n $nt => 'id'\n ]\n ]\n ]\n ];\n $append_join_criteria($standard_join['LEFT JOIN'][\"$new_table$AS\"]['ON'], $add_criteria);\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, $standard_join);\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n $specific_leftjoin_criteria = array_merge_recursive($specific_leftjoin_criteria, self::getDropdownTranslationJoinCriteria(\n $transAS,\n $nt,\n $transitemtype,\n $field\n ));\n }\n break;\n }\n }\n return array_merge_recursive($before_criteria, $specific_leftjoin_criteria);\n }\n\n return [];\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function calculateIntersection($x1, $x2, $isOpenX1, $isOpenX2, $y1, $y2, $isOpenY1, $isOpenY2) {\n\n// return values\n $result = ERROR;\n $z1 = 0;\n $z2 = 0;\n $isOpenZ1 = false;\n $isOpenZ2 = false;\n switch ( testPointVsInterval($y1,$x1,$x2)) { \n case EQUAL_LEFT:\n // echo \"here: \" . EQUAL_LEFT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) { \n\tcase EQUAL_LEFT:\n\t if ($isOpenX1 || $isOpenY1 || $isOpenY2) {\n\t // echo \" + \" . EQUAL_LEFT . \" -> doNotIntersectStop\";\n\n\t $result = DONOTINTERSECT_STOP;\n\t } else {\n\t // echo \" + \" . EQUAL_LEFT . \" -> doIntersectStop\";\n\n\t $result = DOINTERSECT_STOP;\n\t $z1 = $x1;\n\t $z2 = $x1;\n\t $isOpenZ1 = false;\n\t $isOpenZ2 = false;\n\t }\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1 || $isOpenY1;\n\t $isOpenZ2 = $isOpenX2 || $isOpenY2;\n\n\t break;\n\tcase LT:\n\t echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT. \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1 || $isOpenY1;\n\t $isOpenZ2 = $isOpenX2;\n\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED. \" -> doIntersectStop\";\n\n\t $result = DOINTERSECT_STOP;\n\t $z1 = $x1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenX1 || $isOpenY1;\n\t $isOpenZ2 = $isOpenY2;\n\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case EQUAL_RIGHT:\n // echo \"here \" . EQUAL_RIGHT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t // echo \" error \" . EQUAL_LEFT;\n\t break;\n\tcase EQUAL_RIGHT:\n\t if ($isOpenX2 || $isOpenY1 || $isOpenY2) {\n\t // echo \" + \" . EQUAL_LEFT . \" -> doNotIntersectStop\";\n\n\t $result = DONOTINTERSECT_CONTINIUE;\n\t } else {\n\t // echo \" + \" . EQUAL_LEFT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x2;\n\t $z2 = $x2;\n\t $isOpenZ1 = false;\n\t $isOpenZ2 = false;\n\t }\n\t break;\n\tcase LT:\n\t echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT;\n\n\t if ($isOpenX2 || $isOpenY1) {\n\t // echo \" -> doNotIntersectContiniue\";\n\n\t $result = DONOTINTERSECT_CONTINIUE;\n\t } else {\n\t // echo \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x2;\n\t $z2 = $x2;\n\t $isOpenZ1 = false;\n\t $isOpenZ2 = false;\n\t }\n\t break;\n\tcase INCLUDED:\n\t echo \" error \" . INCLUDED;\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case LT:\n // echo \"here \" . LT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t // echo \" + \" . EQUAL_LEFT;\n\n\t if ($isOpenX1 || $isOpenY2) {\n\t // echo \" -> doNotIntersectStop\";\n\n\t $result = DONOTINTERSECT_STOP;\n\t } else {\n\t // echo \" -> doIntersectStop\";\n\n\t $result = DOINTERSECT_STOP;\n\t $z1 = $x1;\n\t $z2 = $x1;\n\t $isOpenZ1 = false;\n\t $isOpenZ2 = false;\n\t }\n\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenX2 || $isOpenY2;\n\t break;\n\tcase LT:\n\t // echo \" + \" . LT . \" -> doNotIntersectStop\";\n\n\t $result = DONOTINTERSECT_STOP;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $x1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenX2;\n\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED . \" -> doIntersectStop\";\n\n\t $result = DOINTERSECT_STOP;\n\t $z1 = $x1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenX1;\n\t $isOpenZ2 = $isOpenY2;\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case GT:\n // echo \"here \" . GT;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase GT:\n\t // echo \" + \" . GT . \" -> doNotIntersectContiniue\";\n\t $result = DONOTINTERSECT_CONTINIUE;\n\t break;\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n case INCLUDED:\n // echo \"here \" . INCLUDED;\n\n switch ( testPointVsInterval($y2,$x1,$x2)) {\n\tcase EQUAL_LEFT:\n\t echo \" error \" . EQUAL_LEFT;\n\t break;\n\tcase EQUAL_RIGHT:\n\t // echo \" + \" . EQUAL_RIGHT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $y1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenX2 || $isOpenY2;\n\t break;\n\tcase LT:\n\t echo \" error \" . LT;\n\t break;\n\tcase GT:\n\t // echo \" + \" . GT . \" -> doIntersectContiniue\";\n\n\t $result = DOINTERSECT_CONTINIUE;\n\t $z1 = $y1;\n\t $z2 = $x2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenX2;\n\t break;\n\tcase INCLUDED:\n\t // echo \" + \" . INCLUDED . \" -> doIntersectStop\";\n\n\t $result = DOINTERSECT_STOP;\n\t $z1 = $y1;\n\t $z2 = $y2;\n\t $isOpenZ1 = $isOpenY1;\n\t $isOpenZ2 = $isOpenY2;\n\t break;\n\n\tdefault:\n\t echo \"error\";\n }\n\n break;\n\n // fallthrough\n default:\n echo \"error\";\n }\n\n // echo \" \";\n\n if ($result == ERROR || $result == DONOTINTERSECT_STOP || $result == DONOTINTERSECT_CONTINIUE) {\n return array(\"result\" => $result);\n } else if ($z1==$z2 && ($isOpenZ1 || $isOpenZ2)) { // check for (1,1] or similar\n return array(\"result\" => DONOTINTERSECT_STOP);\n } else {\n return array(\"result\" => $result,\n \"left-border\" => $z1, \"right-border\" => $z2,\n \"is-open-left\" => $isOpenZ1, \"is-open-right\" => $isOpenZ2);\n }\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function sendFax($number, $file, $pages, $localId = null, $callerId = null, $tag = null, $isDocument = null, $fileName = null): FaxStatus\n {\n // create fax status\n $status = new FaxStatus();\n if (is_file($file) && !$isDocument) {\n $data = file_get_contents($file);\n if (empty($data)) {\n $status->Result = FaxResult::InvalidOrMissingFile;\n return $status;\n }\n unlink($file);\n } else {\n // is content of document\n $data = $file;\n }\n //use server timezone\n if (empty($tz)) {\n $now = new DateTime();\n $tz = (string)($now->getOffset() / 3600);\n }\n // set default page count\n if (is_null($pages)) {\n $pages = 1;\n }\n // create post array/items\n $post = array(\n 'DialNumber' => $number,\n 'FaxImage' => base64_encode($data),\n 'TotalPages' => $pages,\n 'TimeZoneOffset' => $tz\n );\n // add optional items\n if (!is_null($localId)) {\n $post['LocalId'] = $localId;\n }\n if (!is_null($callerId)) {\n $post['CallerId'] = $callerId;\n }\n if (!is_null($tag)) {\n $post['Tag'] = $tag;\n }\n $DocumentParams = new \\stdClass();\n $DocumentParams->Name = $fileName ?? 'Unknown';\n $post['DocumentParams'] = $DocumentParams;\n\n $post['HeaderString'] = \" {date:d-MMM-yyyy} {time} FROM: {csid} TO: {number} P. {page}\";\n // set error default\n $status->Result = FaxResult::Error;\n // send fax\n $response = $this->clientHttpPost('/outbox', $post);\n if ($response && $this->isOK()) {\n $status->set(json_decode($response));\n } else {\n // This will have an error 'Message' in response.\n $status->set(json_decode($response));\n }\n\n return $status;\n }", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n $oai_out_get_records_object,\n &$msg,\n $repositoryName,\n $adminEmail,\n $sets,\n $repositoryIdentifier,\n $nb_results,\n $token_life_expectancy,\n $compression,\n $deletion_support,\n $additional_metadataformats,\n $base_url,\n $deletion_transient_duration = 0)\n {\n $this->msg = $msg;\n $this->oai_out_get_records_object = $oai_out_get_records_object;\n $this->repositoryName = $repositoryName;\n $this->adminEmail = $adminEmail;\n $this->sets = $sets;\n $this->repositoryIdentifier = $repositoryIdentifier;\n $this->nb_results = $nb_results;\n $this->token_life_expectancy = $token_life_expectancy;\n $this->compression = $compression;\n $this->deletion_support = $deletion_support;\n $this->known_metadata_formats = array_merge($this->known_metadata_formats, $additional_metadataformats);\n $this->base_url = $base_url;\n }", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?array $elements, ?bool $required, ?string $default, Response $response, Database $dbForProject, Event $events) {\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_STRING,\n filter: APP_DATABASE_ATTRIBUTE_ENUM,\n default: $default,\n required: $required,\n elements: $elements\n );\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_ENUM);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {\n\t\t$preview = $maxPreview;\n\t\tif (!$preview->valid()) {\n\t\t\tthrow new \\InvalidArgumentException('Failed to generate preview, failed to load image');\n\t\t}\n\n\t\t$previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');\n\t\t$sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);\n\t\ttry {\n\t\t\tif ($crop) {\n\t\t\t\tif ($height !== $preview->height() && $width !== $preview->width()) {\n\t\t\t\t\t//Resize\n\t\t\t\t\t$widthR = $preview->width() / $width;\n\t\t\t\t\t$heightR = $preview->height() / $height;\n\n\t\t\t\t\tif ($widthR > $heightR) {\n\t\t\t\t\t\t$scaleH = $height;\n\t\t\t\t\t\t$scaleW = $maxWidth / $heightR;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$scaleH = $maxHeight / $widthR;\n\t\t\t\t\t\t$scaleW = $width;\n\t\t\t\t\t}\n\t\t\t\t\t$preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));\n\t\t\t\t}\n\t\t\t\t$cropX = (int)floor(abs($width - $preview->width()) * 0.5);\n\t\t\t\t$cropY = (int)floor(abs($height - $preview->height()) * 0.5);\n\t\t\t\t$preview = $preview->cropCopy($cropX, $cropY, $width, $height);\n\t\t\t} else {\n\t\t\t\t$preview = $maxPreview->resizeCopy(max($width, $height));\n\t\t\t}\n\t\t} finally {\n\t\t\tself::unguardWithSemaphore($sem);\n\t\t}\n\n\n\t\t$path = $this->generatePath($width, $height, $crop, false, $preview->dataMimeType(), $prefix);\n\t\ttry {\n\t\t\t$file = $previewFolder->newFile($path);\n\t\t\t$file->putContent($preview->data());\n\t\t} catch (NotPermittedException $e) {\n\t\t\tthrow new NotFoundException();\n\t\t}\n\n\t\treturn $file;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function finderiv_fra($borrowlend, $principal, $date1, $date2, \n\t\t$strike, $basis, $today, $rate1, $rate2, $fmt=\"F j, Y\") {\n\tif (strcasecmp($borrowlend,\"borrow\")!=0 && strcasecmp($borrowlend,\"lend\")) {\n\t\techo \"finderiv_fra::borrowlend must be either borrow or lend.\";\n\t\treturn false;\n\t}\n\tif (!is_numeric($principal)) {\n\t\techo \"finderiv_fra::principal must be a number.\";\n\t\treturn false;\n\t}\n\tif ($principal<0) {\n\t\techo \"finderiv_fra::principal must be positive.\";\n\t\treturn false;\n\t}\n\t$startdate = date_create_from_format($fmt,$date1);\n\tif ($startdate==false) {\n\t\techo \"finderiv_fra::could not create first date from string.\";\n\t\techo \"The date is \" . $date1. \" and the format is \" . $fmt . \".\";\n\t\treturn false;\n\t}\n\t$enddate = date_create_from_format($fmt,$date2);\n\tif ($enddate==false) {\n\t\techo \"finderiv_fra::could not create second date from string.\";\n\t\techo \"The date is \" . $date2. \" and the format is \" . $fmt . \".\";\n\t\treturn false;\n\t}\n\tif ($startdate>=$enddate) {\n\t\techo \"finderiv_fra:: startdate must be before enddate.\";\n\t\treturn false;\n\t}\n\tif (!is_numeric($strike) ) {\n\t\techo \"finderiv_fra:: invalid strike\";\n\t\treturn false;\n\t}\n\tif ($basis!=360 && $basis!=365) {\n\t\techo \"finderiv_fra:: The basis must be 360 or 365.\";\n\t\treturn false;\t\n\t}\n\n\t$todaydate = date_create_from_format($fmt,$today);\n\tif ($todaydate==false) {\n\t\techo \"finderiv_fra::could not create today's date from string.\";\n\t\techo \"The date is \" . $today. \" and the format is \" . $fmt . \".\";\n\t\treturn false;\n\t}\n\tif ($todaydate>$startdate) {\n\t\techo \"finderiv_fra:: FRA starts in the past. Start date is less than today.\";\n\t\treturn false;\n\t}\n\tif (!is_numeric($rate1) ) {\n\t\techo \"finderiv_fra:: invalid first interest rate\";\n\t\treturn false;\n\t}\n\tif (!is_numeric($rate2) ) {\n\t\techo \"finderiv_fra:: invalid second interest rate\";\n\t\treturn false;\n\t}\n\t$days1 = ($todaydate->diff($startdate))->format(\"%r%a\");\n\t$days2 = ($todaydate->diff($enddate))->format(\"%r%a\");\n\n\t$fairrate = (exp($rate2*$days2/365-$rate1*$days1/365)-1)*$basis/($days2-$days1);\n\t\n\tswitch (strtoupper($borrowlend)) {\n\t\tcase \"LEND\":\n\t\t\t$PV = $principal*($strike-$fairrate)*($days2-$days1)/$basis*exp(-$rate2*$days2/365);\n\t\t\tbreak;\n\t\tcase \"BORROW\":\n\t\t\t$PV = $principal*($fairrate-$strike)*($days2-$days1)/$basis*exp(-$rate2*$days2/365);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\techo \"finderiv_fra::Should not be possible to get here.\";\n\t\t\treturn false;\n\t}\n\t\n\treturn $PV;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct(\n RepositoryInterface $repository,\n Handler $handler,\n ContentDomainMapper $contentDomainMapper,\n Helper\\NameSchemaService $nameSchemaService,\n PermissionCriterionResolver $permissionCriterionResolver,\n PermissionResolver $permissionResolver,\n LocationFilteringHandler $locationFilteringHandler,\n ContentTypeService $contentTypeService,\n array $settings = [],\n LoggerInterface $logger = null\n ) {\n $this->repository = $repository;\n $this->persistenceHandler = $handler;\n $this->contentDomainMapper = $contentDomainMapper;\n $this->nameSchemaService = $nameSchemaService;\n $this->permissionResolver = $permissionResolver;\n $this->locationFilteringHandler = $locationFilteringHandler;\n // Union makes sure default settings are ignored if provided in argument\n $this->settings = $settings + [\n //'defaultSetting' => array(),\n ];\n $this->permissionCriterionResolver = $permissionCriterionResolver;\n $this->contentTypeService = $contentTypeService;\n $this->logger = null !== $logger ? $logger : new NullLogger();\n }", "smellKey": "S107", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getMock($originalClassName, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false, $callOriginalMethods = false, $proxyTarget = null)\n {\n return parent::getMock(\n $originalClassName,\n $methods,\n $arguments,\n $mockClassName,\n $callOriginalConstructor,\n $callOriginalClone,\n $callAutoload,\n $cloneArguments,\n $callOriginalMethods,\n $proxyTarget\n );\n }", "smellKey": "S107", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function makestatement($s, $sn, $ops, &$anstypes, &$questions, &$answer, &$showanswer, &$displayformat, &$answerformat, &$answerboxsize) {\n\t$debug = false;\n\tif ($anstypes === null) { $anstypes = array();}\n\tif ($questions === null) { $questions = array();}\n\tif ($answer === null) { $answer = array();}\n\tif ($showanswer === null) { $showanswer = '';}\n\tif ($displayformat === null) { $displayformat = array();}\n\tif ($answerformat === null) { $answerformat = array();}\n if ($ops === null) { $ops = array(); }\n \n\tif (isset($ops[0]) && $ops[0] == 'pulldowns') {\n\t\tarray_shift($ops);\n\t\t$disptype = 'select';\n\t} else {\n\t\t$disptype = 'typeahead';\n\t}\n\tnatsort($ops);\n\t$maxind = 0;\n\n\n\t$maxsizedescr = 0; $maxsizeentry = 0; $hasdecimals = false; $hasexp = false; $expspan = 0; $blankexp = '';\n\tforeach ($s as $ix=>$jd) {\n\t\tif (!isset($jd['elements'])) {continue;}\n\t\tfor ($i=0;$i\";\n\t\t\t}\n\t\t\t$sl = strlen($jd['elements'][$i]);\n\t\t\tif ($sl>$maxsizedescr) { $maxsizedescr = $sl;}\n\t\t\t$sl = strlen($jd['elements'][$i+1]);\n\t\t\tif ($sl>$maxsizeentry) { $maxsizeentry = $sl;}\n\t\t\tif (!$hasdecimals && strpos($jd['elements'][$i+1],'.')!==false) { $hasdecimals = true;}\n\t\t}\n\t\tif (isset($jd['indent']) && $jd['indent']>$maxind) {\n\t\t\t$maxind = $jd['indent'];\n\t\t}\n\t\tif (isset($jd['totalindent']) && $jd['totalindent']>$maxind) {\n\t\t\t$maxind = $jd['totalindent'];\n\t\t}\n\t\tif (isset($jd['explanation'])) {\n\t\t\t$hasexp = true; $expspan = 1; $blankexp = '';\n\t\t}\n\t}\n\tforeach ($ops as $op) {\n\t\t$sl = strlen($op);\n\t\tif ($sl>$maxsizedescr) { $maxsizedescr = $sl;}\n\t}\n\t$pre = array(\"\"); $post = array(\"\");\n\tif ($maxind>0) {\n\t\tfor ($i=0;$i<=$maxind;$i++) {\n\t\t\t$pre[$i] = ''; $post[$i] = '';\n\t\t\tfor ($j=$i;$j<$maxind;$j++) {\n\t\t\t\t$pre[$i] .= '';\n\t\t\t}\n\t\t\tfor ($j=0;$j<$i;$j++) {\n\t\t\t\tif ($j==0) {\n\t\t\t\t\t$post[$i] .= '';\n\t\t\t\t} else {\n\t\t\t\t\t$post[$i] .= '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t$maxsizedescr += 6;\n\t$maxsizeentry += 3;\n\tif (isset($s[0]['bigtitle'])) {\n\t\t$out = '';\n\t\t$sa = '
    '.$s[0]['bigtitle'].'
    ';\n\t} else {\n\t\t$out = '
    '.$s[0]['bigtitle'].'
    ';\n\t\t$sa = '
    ';\n }\n $out .= ''; \n $sa .= '';\n if ($maxind > 0) {\n $out .= '';\n $sa .= '';\n }\n for ($i=1;$i<$maxind;$i++) {\n $out .= '';\n $sa .= '';\n }\n $sa .= '';\n $out .= '';\n $out .= '';\n $sa .= '';\n\t$grouptots = array(); $addspacer = false;\n\tforeach ($s as $ix=>$sg) {\n\t\tif (isset($sg['indent']) && $sg['indent']>0) {\n\t\t\t$ind = $sg['indent'];\n\t\t\t$hdrindent = $sg['indent'] - 1;\n\t\t\tif (isset($sg['totindent'])) {\n\t\t\t\t$totindent = $sg['totindent'];\n\t\t\t} else {\n\t\t\t\t$totindent = $sg['indent'] - 1;\n\t\t\t}\n\t\t} else {\n\t\t\t$hdrindent = 0; $totindent = 0; $ind =0;\n\t\t}\n\t\tif ($addspacer && !isset($sg['nospacer'])) {\n\t\t\t$out .= '';\n\t\t\t$sa .= '';\n\t\t}\n\t\tif (isset($sg['header'])) {\n\t\t\t$addspacer = false;\n\t\t\tif (is_array($sg['header'])) {\n\t\t\t\t$out .= ''.$pre[$hdrindent].''.$post[$hdrindent].'';\n\t\t\t\t$sa .= ''.$pre[$hdrindent].''.$post[$hdrindent].$blankexp.'';\n\t\t\t} else {\n\t\t\t\tif (isset($sg['headerops'])) {\n\t\t\t\t\tif ($sg['headerops'][0] == 'pulldowns') {\n\t\t\t\t\t\tarray_shift($sg['headerops']);\n\t\t\t\t\t\t$tdisptype = 'select';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$tdisptype = 'typeahead';\n\t\t\t\t\t}\n\t\t\t\t\tnatsort($sg['headerops']);\n\t\t\t\t\tif ($debug && !in_array($sg['header'], $sg['headerops'])) {\n\t\t\t\t\t\techo \"Eek: \".$sg['header'].\" not in header options array
    \";\n\t\t\t\t\t}\n\t\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $tdisptype; $questions[$sn] = $sg['headerops']; $answer[$sn] = $sg['header']; $answerboxsize[$sn] = 40;\n\t\t\t\t\t$out .= '';\n\t\t\t\t\t$sa .= '';\n\t\t\t\t\t$sn++;\n\t\t\t\t} else {\n\t\t\t\t\t$out .= '';\n\t\t\t\t\t$sa .= '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (isset($sg['elements'])) {\n\t\t\t$addspacer = true;\n\t\t\t$tot = 0;\n\t\t\tfor ($i=0;$i'.$sg['elements'][$i].'';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$out .= '';\n\t\t\t\t\t}\n\t\t\t\t\t$sn--;\n\t\t\t\t} else {\n\t\t\t\t\t$out .= '';\n\t\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $disptype; $questions[$sn] = $ops; $answer[$sn] = $sg['elements'][$i]; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t\t}\n\t\t\t\t$out .= $pre[$ind].''.$post[$ind].'';\n\t\t\t\t$sg['elements'][$i+1] = str_replace(array('$',',',' '),'',$sg['elements'][$i+1])*1;\n\t\t\t\t$sa .= ''.$pre[$ind].''.$post[$ind];\n\t\t\t\tif (isset($sg['explanation'])) {\n\t\t\t\t\t$sa .= '';\n\t\t\t\t} else {\n\t\t\t\t\t$sa .= $blankexp.'';\n\t\t\t\t}\n\t\t\t\t$anstypes[$sn+1] = 'number'; $displayformat[$sn+1] = 'alignright'; $answerformat[$sn+1] = 'parenneg'; $answer[$sn+1] = $sg['elements'][$i+1]; $answerboxsize[$sn+1] = $maxsizeentry;\n\t\t\t\t$tot += $sg['elements'][$i+1]*(isset($sg['totsigns'])?$sg['totsigns'][$i/2]:1);\n\t\t\t\t$sn += 2;\n\t\t\t}\n\t\t\tif (isset($sg['totneg'])) {\n\t\t\t\t$tot *= -1;\n\t\t\t}\n\n\t\t\t$grouptots[$ix] = $tot;\n\t\t\tif (isset($sg['totrows'])) {\n\t\t\t\t//echo \"count: \".count($sg['elements'])/2.\" totr: \".$sg['totrows'].'
    ';\n\t\t\t\tfor($i=count($sg['elements'])/2;$i<$sg['totrows'];$i++) {\n\t\t\t\t\t$out .= ''.$pre[$ind].''.$post[$ind].'';\n\t\t\t\t\t//$sa .= '';\n\t\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $disptype; $questions[$sn] = $ops; $answer[$sn] = \"\"; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t\t\t$anstypes[$sn+1] = 'string'; $displayformat[$sn+1] = 'alignright'; $answer[$sn+1] = ''; $answerboxsize[$sn+1] = $maxsizeentry;\n\t\t\t\t\t$sn += 2;\n\t\t\t\t}\n }\n $didextraline = false;\n\t\t\tif (isset($sg['tottitle']) || isset($sg['tottitleline'])) {\n\t\t\t\t$p = strrpos($out,'');\n $out = substr($out,0,$p).''.substr($out,$p+19);\n $p = strrpos($sa,'');\n $sa = substr($sa,0,$p).''.substr($sa,$p+19);\n $didextraline = true;\n }\n\n\t\t\t\tif (isset($sg['tottitleline']) && $sg['tottitleline']<0) {\n\t\t\t\t\t$p = strrpos($out,' class=\"f\"><');\n\t\t\t\t\t$out = substr($out,0,$p).' class=\"r\">[AB'.$sn.']'.substr($out,$p+11);\n\t\t\t\t\t$p = strrpos($sa,' class=\"f\"><');\n\t\t\t\t\t$sa = substr($sa,0,$p).' class=\"r\">'.($hasdecimals?number_format($tot,2,'.',','):number_format($tot)).substr($sa,$p+11);\n\t\t\t\t} else {\n\t\t\t\t\tif (isset($sg['tottitleops'])) {\n\t\t\t\t\t\tif ($sg['tottitleops'][0] == 'pulldowns') {\n\t\t\t\t\t\t\tarray_shift($sg['tottitleops']);\n\t\t\t\t\t\t\t$tdisptype = 'select';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$tdisptype = 'typeahead';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ($debug && !in_array($sg['tottitle'], $sg['tottitleops'])) {\n\t\t\t\t\t\t\techo \"Eek: \".$sg['tottitle'].\" not in total options array
    \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnatsort($sg['tottitleops']);\n\t\t\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $tdisptype; $questions[$sn] = $sg['tottitleops']; $answer[$sn] = $sg['tottitle']; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t\t\t\t$out .= '';\n\t\t\t\t\t\t$sa .= '';\n\t\t\t\t\t\t$sn++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$out .= '';\n\t\t\t\t\t\t$sa .= '';\n\t\t\t\t\t}\n\t\t\t\t\t$out .= $pre[$totindent].''.$post[$totindent].'';\n\t\t\t\t\t$sa .= $pre[$totindent].''.$post[$hdrindent].$blankexp.'';\n\n\t\t\t\t}\n\t\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answerformat[$sn] = 'parenneg'; $answer[$sn] = $tot; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t\t$sn++;\n\t\t\t}\n\t\t}\n\t\tif (isset($sg['totaltotal'])) {\n\t\t\t$addspacer = true;\n\t\t\t$p = strrpos($out,'');\n $out = substr($out,0,$p).''.substr($out,$p+19);\n $p = strrpos($sa,'');\n $sa = substr($sa,0,$p).''.substr($sa,$p+19);\n }\n\t\t\tfor ($i=1;$i\";\n\t\t\t\t}\n\t\t\t\tnatsort($sg['totaltotalops']);\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = $tdisptype; $questions[$sn] = $sg['totaltotalops']; $answer[$sn] = $sg['totaltotal'][0]; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t\t$sn++;\n\t\t\t} else {\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t}\n\t\t\tif (isset($sg['dblunder'])) {\n $under = ' style=\"border-bottom: 3px double #000\"';\n $underlabel = 'Double line';\n\t\t\t} else {\n $under = '';\n $underlabel = '';\n\t\t\t}\n\t\t\t$out .= $pre[$totind].''.$post[$totind].'';\n\t\t\t$sa .= $pre[$totind].''.$post[$totind].$blankexp.'';\n\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answerformat[$sn] = 'parenneg'; $answer[$sn] = $tottot; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t$sn++;\n\t\t}\n\t}\n\n\t$out .= '
    DescriptionAmount
    DescriptionAmountTotalTotalGroup TotalGroup Total
    Subcategory,'.$sg['header'][0].''.$sg['header'][1].'
    Subcategory,'.$sg['header'][0].''.$sg['header'][1].'
    Subcategory,[AB'.$sn.']
    Subcategory,'.$sg['header'].'
    Subcategory,'.$sg['header'].'
    Subcategory,'.$sg['header'].'
    '.$sg['elements'][$i].'
    [AB'.$sn.'][AB'.($sn+1).']
    '.$sg['elements'][$i].''.($hasdecimals?number_format($sg['elements'][$i+1],2,'.',','):number_format($sg['elements'][$i+1])).''.$sg['explanation'][$i/2].'
    [AB'.$sn.'][AB'.($sn+1).']
      
    ');\n $out = substr($out,0,$p).'',$p);\n $out = substr($out,0,$p).'Single line'.substr($out,$p+5);\n\t\t\t\t$p = strrpos($sa,'');\n $sa = substr($sa,0,$p).'',$p);\n $sa = substr($sa,0,$p).'Single line'.substr($sa,$p+5);\n\n if ($totindent < $ind) {\n $p = strrpos($out,'Single lineSingle line
    [AB'.$sn.']
    '.$sg['tottitle'].'
    '.$sg['tottitle'].'
    '.$sg['tottitle'].'Single line[AB'.$sn.']
    Single line'.($hasdecimals?number_format($tot,2,'.',','):number_format($tot)).'
    ');\n $out = substr($out,0,$p).'',$p);\n $out = substr($out,0,$p).'Single line'.substr($out,$p+5);\n\n\t\t\t$p = strrpos($sa,'');\n $sa = substr($sa,0,$p).'',$p);\n $sa = substr($sa,0,$p).'Single line'.substr($sa,$p+5);\n\n\t\t\t$tottot = 0;\n\t\t\tif (isset($sg['totalindent'])) {\n $totind = $sg['totalindent'];\n\t\t\t} else {\n $totind = 0;\n }\n if ($totind < $ind && !$didextraline) {\n $p = strrpos($out,'Single lineSingle line
    [AB'.$sn.']
    '.$sg['totaltotal'][0].'
    '.$sg['totaltotal'][0].'
    '.$sg['totaltotal'][0].'Single line[AB'.$sn.']'.$underlabel.'
    Single line'.($hasdecimals?number_format($tottot,2,'.',','):number_format($tottot)).$underlabel.'
    ';\n\t$sa .= '';\n\t$showanswer .= $sa.'

     

    ';\n\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function addBilling(\n $encounter_id,\n $code_type,\n $code,\n $code_text,\n $pid,\n string $authorized = null,\n $provider,\n $modifier = \"\",\n $units = \"\",\n $fee = \"0.00\",\n $ndc_info = '',\n $justify = '',\n $billed = 0,\n $notecodes = '',\n $pricelevel = '',\n $revenue_code = \"\",\n $payer_id = \"\"\n ) {\n if (!$authorized) {\n $authorized = \"0\";\n }\n\n // Sanity check.\n $tmp = sqlQuery(\n \"SELECT count(*) AS count from form_encounter WHERE pid = ? AND encounter = ?\",\n array($pid, $encounter_id)\n );\n if (empty($tmp['count'])) {\n die(xlt('Internal error: the referenced encounter no longer exists.'));\n }\n\n $sql = \"INSERT INTO billing (date, encounter, code_type, code, code_text, \" .\n \"pid, authorized, user, groupname, activity, billed, provider_id, \" .\n \"modifier, units, fee, ndc_info, justify, notecodes, pricelevel, revenue_code, payer_id) VALUES (\" .\n \"NOW(), ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n\n return sqlInsert($sql, array($encounter_id, $code_type, $code, $code_text, $pid, $authorized,\n $_SESSION['authUserID'], $_SESSION['authProvider'], $billed, $provider, $modifier, $units, $fee,\n $ndc_info, $justify, $notecodes, $pricelevel, $revenue_code, $payer_id));\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct(\n\t\t?string $outGuiaInterprete,\n\t\t?string $outInterpreteLibras,\n\t\t?string $outLeituraLabial,\n\t\t?string $outNenhum,\n\t\t?string $outProvaAmpliada,\n\t\t?string $outTamanhoFonte,\n\t\t?string $outProvaBraile,\n\t\t?string $outAuxilioTranscricao,\n\t\t?string $outAuxilioLeitor,\n\t\t?string $outProvaVideoLibras,\n\t\t?string $outCdAudioDefVisual,\n\t\t?string $outProvaLinguaPortuguesa\n\t) {\n\t\t$this->outGuiaInterprete = $outGuiaInterprete;\n\t\t$this->outInterpreteLibras = $outInterpreteLibras;\n\t\t$this->outLeituraLabial = $outLeituraLabial;\n\t\t$this->outNenhum = $outNenhum;\n\t\t$this->outProvaAmpliada = $outProvaAmpliada;\n\t\t$this->outTamanhoFonte = $outTamanhoFonte;\n\t\t$this->outProvaBraile = $outProvaBraile;\n\t\t$this->outAuxilioTranscricao = $outAuxilioTranscricao;\n\t\t$this->outAuxilioLeitor = $outAuxilioLeitor;\n\t\t$this->outProvaVideoLibras = $outProvaVideoLibras;\n\t\t$this->outCdAudioDefVisual = $outCdAudioDefVisual;\n\t\t$this->outProvaLinguaPortuguesa = $outProvaLinguaPortuguesa;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, Response $response, Database $dbForProject, Event $events) {\n\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_STRING,\n default: $default,\n required: $required\n );\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_STRING);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct($cb,$expl_id=0, $level=1, $action='', $expl=1, $expl_link='', $lien_suppr_cart=\"\", $explnum_link='', $show_resa=0, $print=0, $show_explnum=1, $no_link=true,$ajax_mode=0 ) {\n\t \t// $id = id de la notice afficher\n\t \t// $action\t = URL associe au header\n\t\t// $level :\n\t\t//\t\t0 : juste le header (titre / auteur principal avec le lien si applicable) \n\t\t// \t\t\tsuppression des niveaux entre 1 et 6, seul reste level\n\t\t//\t\t1 : ISBD seul, pas de note, bouton modif, expl, explnum et rsas\n\t\t// \t\t6 : cas gnral dtaill avec notes, categ, langues, indexation... + boutons\n\t\t// $expl -> affiche ou non les exemplaires associs\n\t\t// $expl_link -> lien associ l'exemplaire avec !!expl_id!!, !!notice_id!! et !!expl_cb!! mettre jour\n\t \t// $lien_suppr_cart -> lien de suppression de la notice d'un caddie\n\t \t//\n\t \t// $show_resa = affichage des resa ou pas\n\t\tglobal $explr_visible_mod,$pmb_droits_explr_localises;\n\t\t\n\t\t$expl_id = intval($expl_id);\n\t\tif(!$expl_id && $cb) {\n\t\t\t$query = \" select expl_id from exemplaires where expl_cb='\".$cb.\"'\";\n\t\t\t$result = pmb_mysql_query($query);\n\t\t\tif(pmb_mysql_num_rows($result)) {\n\t\t\t\t$expl = pmb_mysql_fetch_object($result);\n\t\t\t\t$expl_id = $expl->expl_id;\t\t\n\t\t\t}\t\n\t\t}\n\t\t\n\t \t$this->expl_data = $this->get_expl_info($cb,$expl_id);\n\t \t$this->notice_id = $this->expl_data->expl_notice;\n\t\t$this->id_bulletin = $this->expl_data->expl_bulletin;\n\t\t\n\t\tif($this->id_bulletin) {\n\t\t\t$req=\"select num_notice from bulletins where bulletin_id=\".$this->id_bulletin;\n\t\t\t$result = pmb_mysql_query($req);\n\t\t\tif(pmb_mysql_num_rows($result)) {\n\t\t\t\t$res = pmb_mysql_fetch_object($result);\n\t\t\t\t$this->num_notice = $res->num_notice;\n\t\t\t}\t\n\t\t}\n\t\t$this->header=$this->expl_titre_diplay().\" / \";\t\t\t\n\t\t$this->isbd=$this->expl_info_display();\n\t\t// notice de monographie\n\t\tif($this->notice_id) {\n\t\t\t$display = new mono_display($this->notice_id,$level, \"\", $expl, $expl_link, '', $explnum_link,1, 0, 1, 0, \"\", 1 , $no_link,true,0);\n\t\t\t$link_notice = str_replace(\"!!id!!\", $this->notice_id, $action );\n\t\t}\n\t\t// notice de bulletin\n\t\tif($this->num_notice) {\n\t\t\t$display = new mono_display($this->num_notice, $level, \"\", $expl, $expl_link, '', $explnum_link,1, 0, 1, 0, \"\", 1 , $no_link,true,0);\n\t\t\t$link_notice = str_replace(\"!!id!!\", $this->id_bulletin, $action );\t\t\t\n\t\t}\t\n\t\t// bulletin sans notice\n\t\tif(!$this->num_notice && $this->id_bulletin) {\n\t\t\t$display = new bulletinage_display($this->id_bulletin);\n\t\t\t$link_notice = str_replace(\"!!id!!\", $this->id_bulletin, $action );\t\n\t\t}\n\t\t\t\n\t\t$this->header.= $display->header;\n\t\t$this->isbd.= \"\".$display->header.\"\";\n//\t\t$this->isbd.= $display->isbd;\n\t\n\t\t//visibilit des exemplaires\n\t\tif ($pmb_droits_explr_localises) {\n\t\t\t$explr_tab_modif=explode(\",\",$explr_visible_mod);\n\t\t\t$as_modif = array_search($this->expl_data->idlocation,$explr_tab_modif);\n\t\t} else {\n\t\t\t$as_modif = true;\n\t\t}\n\t\tif (($expl_link) && ($as_modif!== FALSE && $as_modif!== NULL) ) {\n\t\t\t$expl_link = str_replace(\"!!notice_id!!\", $this->notice_id, $expl_link );\n\t\t\t$expl_link = str_replace(\"!!expl_cb!!\", $cb, $expl_link );\n\t\t\t$expl_link = str_replace(\"!!expl_id!!\", $expl_id, $expl_link );\n\t\t\t$expl_link = str_replace(\"!!bulletin_id!!\", $this->id_bulletin, $expl_link );\n\t\t\t\n\t\t\t$this->header= \"\".$this->header.\"\";\n\t\t}\n\t\t\n\t\tswitch($level) {\n\t\tcase 0:\n\t\t\t// l, c'est le niveau 0 : juste le header\n\t\t\t$this->result = $this->header;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t// niveau 1 et plus : header + isbd gnrer\n\t\t\t$this->init_javascript();\n\t\t\t$this->finalize();\n\t\t\tbreak;\n\t\t}\t\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function (string $projectId, string $name, string $teamId, string $region, string $description, string $logo, string $url, string $legalName, string $legalCountry, string $legalState, string $legalCity, string $legalAddress, string $legalTaxId, Response $response, Database $dbForConsole, Cache $cache, Group $pools) {\n\n\n $team = $dbForConsole->getDocument('teams', $teamId);\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n $auth = Config::getParam('auth', []);\n $auths = ['limit' => 0, 'maxSessions' => APP_LIMIT_USER_SESSIONS_DEFAULT, 'passwordHistory' => 0, 'passwordDictionary' => false, 'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false];\n foreach ($auth as $index => $method) {\n $auths[$method['key'] ?? ''] = true;\n }\n\n $projectId = ($projectId == 'unique()') ? ID::unique() : $projectId;\n\n $backups['database_db_fra1_02'] = ['from' => '7:30', 'to' => '8:15'];\n $backups['database_db_fra1_03'] = ['from' => '10:30', 'to' => '11:15'];\n $backups['database_db_fra1_04'] = ['from' => '13:30', 'to' => '14:15'];\n $backups['database_db_fra1_05'] = ['from' => '4:30', 'to' => '5:15'];\n $backups['database_db_fra1_06'] = ['from' => '16:30', 'to' => '17:15'];\n\n $databases = Config::getParam('pools-database', []);\n\n /**\n * Extract db from list while backing\n */\n if (count($databases) > 1) {\n $now = new \\DateTime();\n\n foreach ($databases as $index => $database) {\n if (empty($backups[$database])) {\n continue;\n }\n $backup = $backups[$database];\n $from = \\DateTime::createFromFormat('H:i', $backup['from']);\n $to = \\DateTime::createFromFormat('H:i', $backup['to']);\n if ($now >= $from && $now <= $to) {\n unset($databases[$index]);\n break;\n }\n }\n }\n\n if ($index = array_search('database_db_fra1_06', $databases)) {\n $database = $databases[$index];\n } else {\n $database = $databases[array_rand($databases)];\n }\n\n if ($projectId === 'console') {\n throw new Exception(Exception::PROJECT_RESERVED_PROJECT, \"'console' is a reserved project.\");\n }\n\n try {\n $project = $dbForConsole->createDocument('projects', new Document([\n '$id' => $projectId,\n '$permissions' => [\n Permission::read(Role::team(ID::custom($teamId))),\n Permission::update(Role::team(ID::custom($teamId), 'owner')),\n Permission::update(Role::team(ID::custom($teamId), 'developer')),\n Permission::delete(Role::team(ID::custom($teamId), 'owner')),\n Permission::delete(Role::team(ID::custom($teamId), 'developer')),\n ],\n 'name' => $name,\n 'teamInternalId' => $team->getInternalId(),\n 'teamId' => $team->getId(),\n 'region' => $region,\n 'description' => $description,\n 'logo' => $logo,\n 'url' => $url,\n 'version' => APP_VERSION_STABLE,\n 'legalName' => $legalName,\n 'legalCountry' => $legalCountry,\n 'legalState' => $legalState,\n 'legalCity' => $legalCity,\n 'legalAddress' => $legalAddress,\n 'legalTaxId' => ID::custom($legalTaxId),\n 'services' => new stdClass(),\n 'platforms' => null,\n 'authProviders' => [],\n 'webhooks' => null,\n 'keys' => null,\n 'auths' => $auths,\n 'search' => implode(' ', [$projectId, $name]),\n 'database' => $database\n ]));\n } catch (Duplicate $th) {\n throw new Exception(Exception::PROJECT_ALREADY_EXISTS);\n }\n\n $dbForProject = new Database($pools->get($database)->pop()->getResource(), $cache);\n $dbForProject->setNamespace(\"_{$project->getInternalId()}\");\n $dbForProject->create();\n\n $audit = new Audit($dbForProject);\n $audit->setup();\n\n $adapter = new TimeLimit('', 0, 1, $dbForProject);\n $adapter->setup();\n\n /** @var array $collections */\n $collections = Config::getParam('collections', [])['projects'] ?? [];\n\n foreach ($collections as $key => $collection) {\n if (($collection['$collection'] ?? '') !== Database::METADATA) {\n continue;\n }\n\n $attributes = [];\n $indexes = [];\n\n foreach ($collection['attributes'] as $attribute) {\n $attributes[] = new Document([\n '$id' => $attribute['$id'],\n 'type' => $attribute['type'],\n 'size' => $attribute['size'],\n 'required' => $attribute['required'],\n 'signed' => $attribute['signed'],\n 'array' => $attribute['array'],\n 'filters' => $attribute['filters'],\n 'default' => $attribute['default'] ?? null,\n 'format' => $attribute['format'] ?? ''\n ]);\n }\n\n foreach ($collection['indexes'] as $index) {\n $indexes[] = new Document([\n '$id' => $index['$id'],\n 'type' => $index['type'],\n 'attributes' => $index['attributes'],\n 'lengths' => $index['lengths'],\n 'orders' => $index['orders'],\n ]);\n }\n $dbForProject->createCollection($key, $attributes, $indexes);\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($project, Response::MODEL_PROJECT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n\t\t?string $inAnoLetivo,\n\t\t?string $inCodEscola,\n\t\t?string $inCodUnidade,\n\t\t?string $inCodTipoEnsino,\n\t\t?string $inCodSerieAno,\n\t\t?string $inCodTipoClasse,\n\t\t?string $inCodTurno,\n\t\t?string $inCodDuracao,\n\t\t?string $inTurma,\n\t\t?string $inNumeroSala,\n\t\t?string $inNrCapacidadeFisicaMaxima,\n\t\t?string $inDataInicioAula,\n\t\t?string $inDataFimAula,\n\t\t?string $inHorarioInicioAula,\n\t\t?string $inHorarioFimAula,\n\t\t?string $inCodHabilitacao,\n\t\t?array $inCodigoAtividadeComplementar,\n\t\t?InDiasDaSemana $inDiasDaSemana\n\t) {\n\t\t$this->inAnoLetivo = $inAnoLetivo;\n\t\t$this->inCodEscola = $inCodEscola;\n\t\t$this->inCodUnidade = $inCodUnidade;\n\t\t$this->inCodTipoEnsino = $inCodTipoEnsino;\n\t\t$this->inCodSerieAno = $inCodSerieAno;\n\t\t$this->inCodTipoClasse = $inCodTipoClasse;\n\t\t$this->inCodTurno = $inCodTurno;\n\t\t$this->inCodDuracao = $inCodDuracao;\n\t\t$this->inTurma = $inTurma;\n\t\t$this->inNumeroSala = $inNumeroSala;\n\t\t$this->inNrCapacidadeFisicaMaxima = $inNrCapacidadeFisicaMaxima;\n\t\t$this->inDataInicioAula = $inDataInicioAula;\n\t\t$this->inDataFimAula = $inDataFimAula;\n\t\t$this->inHorarioInicioAula = $inHorarioInicioAula;\n\t\t$this->inHorarioFimAula = $inHorarioFimAula;\n\t\t$this->inCodHabilitacao = $inCodHabilitacao;\n\t\t$this->inCodigoAtividadeComplementar = $inCodigoAtividadeComplementar;\n\t\t$this->inDiasDaSemana = $inDiasDaSemana;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\tlist($x, $y) = $this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);\n\t\t\t$s = '';\n\t\t\tforeach ($values as $value) {\n\t\t\t\tif (is_array($value)) {\n\t\t\t\t\t$s .= ',[\\''.addslashes($value[1]).'\\',\\''.addslashes($value[0]).'\\']';\n\t\t\t\t} else {\n\t\t\t\t\t$s .= ',[\\''.addslashes($value).'\\',\\''.addslashes($value).'\\']';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'.\"\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t$prop['Combo'] = true;\n\t\t// get annotation data\n\t\t$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);\n\t\t// set additional default options\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t// build appearance stream\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';\n\t\t$text = '';\n\t\tforeach($values as $item) {\n\t\t\tif (is_array($item)) {\n\t\t\t\t$text .= $item[1].\"\\n\";\n\t\t\t} else {\n\t\t\t\t$text .= $item.\"\\n\";\n\t\t\t}\n\t\t}\n\t\t$tmpid = $this->startTemplate($w, $h, false);\n\t\t$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);\n\t\t$this->endTemplate();\n\t\t--$this->n;\n\t\t$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];\n\t\tunset($this->xobjects[$tmpid]);\n\t\t$popt['ap']['n'] .= 'Q EMC';\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Ch';\n\t\t$opt['t'] = $name;\n\t\t$opt['opt'] = $values;\n\t\tunset($opt['mk']['ca']);\n\t\tunset($opt['mk']['rc']);\n\t\tunset($opt['mk']['ac']);\n\t\tunset($opt['mk']['i']);\n\t\tunset($opt['mk']['ri']);\n\t\tunset($opt['mk']['ix']);\n\t\tunset($opt['mk']['if']);\n\t\tunset($opt['mk']['tp']);\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public function form_label($view, $label, $required, $compound, $id, $name, $translation_domain, $label_attr,\n $formHelper, $translatorHelper, $label_format = null)\n {\n ?>\n \n \n \n $name, '%id%' => $id))\n : $formHelper->humanize($name); } ?>\n \n \n $maxsize[$j]) { $maxsize[$j] = $sl;}\n\t\t\tif (!$hasdecimals && strpos($cols[$j][$i],'.')!==false) { $hasdecimals = true;}\n\t\t}\n\t\t$maxsize[$j] += floor(($maxsize[$j]-0.5)/3); //add size to account for commas\n\t}\n\tif (count($headers)!=0) {\n\t\tif (!is_array($headers[0])) {\n\t\t\t$headers = array($headers);\n\t\t}\n $out = '';\n if (is_numeric($headers[0][1]) && abs($headers[0][1]) == count($cols)) {\n $out .= '';\n array_shift($headers);\n }\n $out .= '';\n\t\tforeach ($headers as $hdr) {\n\t\t\t$out .= '';\n\t\t\tif (isset($hdr[1]) && is_numeric($hdr[1])) {\n\t\t\t\tfor ($i=0;$i1) {\n\t\t\t\t\t\t$out .= ' colspan=\"'.$hdr[$i+1].'\"';\n\t\t\t\t\t}\n\t\t\t\t\t$out .= '>'.$hdr[$i].'';\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor ($i=0;$i';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out .= '';\n\t\t}\n\t\t$out .= '';\n\t} else {\n\t\t$out = '
    '.$headers[0][0].'
    ';\n\t}\n\t$out .= '';\n\t$sa = $out;\n\tforeach ($fixedrows as $fr) {\n\t\t$out .= ''; $sa .= '';\n\t\tforeach ($fr as $j=>$el) {\n if ($j==0 && $coltypes[0]==false) {\n $out .= ''; \n $sa .= '';\n } else {\n $out .= ''; \n $sa .= '';\n }\n\t\t}\n\t\t$out .= ''; $sa .= '';\n\t}\n\tfor ($i=0;$i\".$beforetxt.$cols[$j][$i].$aftertxt.'';\n $sa .= \"\".$beforetxt.$cols[$j][$i].$aftertxt.'';\n } else {\n\t\t\t\t $out .= \"\".$beforetxt.$cols[$j][$i].$aftertxt.'';\n $sa .= \"\".$beforetxt.$cols[$j][$i].$aftertxt.'';\n }\n\n\t\t\t} else {\n\t\t\t\tif ($i==$totrow && !isset($cols[$j][$i])) {\n\t\t\t\t\t$thistot = 0;\n\t\t\t\t\tfor ($k=0;$k<$totrow;$k++) {\n\t\t\t\t\t\t$thistot += $cols[$j][$k];\n\t\t\t\t\t}\n\t\t\t\t\t$cols[$j][$i] = $thistot;\n\t\t\t\t}\n\t\t\t\tif ($cols[$j][$i]==='nobox') {$out .= \"\"; $sa.= \"\"; continue;}\n\n\t\t\t\tif (substr($cols[$j][$i],0,6)=='fixed:') {$f = substr($cols[$j][$i],6); $out .= \"$beforetxt $f $aftertxt\"; $sa.= \"$beforetxt $f $aftertxt\"; continue;}\n\n\t\t\t\t$out .= ''.$beforetxt.((substr($cols[$j][$i],0,1)=='$'||$coltypes[$j]===2)?'$':'').'[AB'.$sn.']'.$aftertxt.'';\n\t\t\t\t$sa .= ''.$beforetxt.((substr($cols[$j][$i],0,1)=='$'||$coltypes[$j]===2)?'$':'');\n\n\t\t\t\t$cols[$j][$i] = str_replace('$','',$cols[$j][$i]);\n\t\t\t\t$answer[$sn] = $cols[$j][$i];\n\n\t\t\t\tif (is_numeric($cols[$j][$i])) {\n\t\t\t\t\t$cols[$j][$i] = str_replace(array('$',','),'',$cols[$j][$i]) * 1;\n\t\t\t\t\tif ($hasdecimals) {\n\t\t\t\t\t\t$sa .= number_format($cols[$j][$i],2,'.',',');\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$sa .= number_format($cols[$j][$i]);\n\t\t\t\t\t}\n\t\t\t\t\t$displayformat[$sn] = 'alignright';\n\t\t\t\t\t$answerformat[$sn] = 'parenneg';\n\t\t\t\t\t$anstypes[$sn] = 'number';\n\t\t\t\t} else {\n\t\t\t\t\t$sa .= $cols[$j][$i];\n\t\t\t\t\t$anstypes[$sn] = 'string';\n\t\t\t\t\tif ($strdisptype != '') {\n\t\t\t\t\t\t$displayformat[$sn] = $strdisptype;\n\t\t\t\t\t\t$questions[$sn] = $opts['ops'];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$answerboxsize[$sn] = $maxsize[$j];\n\t\t\t\t$sa .= $aftertxt.'';\n\t\t\t\t$sn++;\n\t\t\t}\n\t\t}\n\n\t\t$out .= '';\n\t\t$sa .= '';\n\t}\n\t$out .= '
    '.$el.''.$el.''.$el.''.$el.'
    ';\n\t$sa .= '';\n\t$showanswer .= $sa.'

     

    ';\n\n\treturn $out;\n\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($w, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);\n\t\t\treturn;\n\t\t}\n\t\tif ($this->empty_string($onvalue)) {\n\t\t\t$onvalue = 'On';\n\t\t}\n\t\tif ($checked) {\n\t\t\t$defval = $onvalue;\n\t\t} else {\n\t\t\t$defval = 'Off';\n\t\t}\n\t\t// set data for parent group\n\t\tif (!isset($this->radiobutton_groups[$this->page])) {\n\t\t\t$this->radiobutton_groups[$this->page] = array();\n\t\t}\n\t\tif (!isset($this->radiobutton_groups[$this->page][$name])) {\n\t\t\t$this->radiobutton_groups[$this->page][$name] = array();\n\t\t\t++$this->n;\n\t\t\t$this->radiobutton_groups[$this->page][$name]['n'] = $this->n;\n\t\t\t$this->radio_groups[] = $this->n;\n\t\t\t$kid = ($this->n + 2);\n\t\t} else {\n\t\t\t$kid = ($this->n + 1);\n\t\t}\n\t\t// save object ID to be added on Kids entry on parent object\n\t\t$this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t$prop['NoToggleToOff'] = 'true';\n\t\t$prop['Radio'] = 'true';\n\t\t$prop['borderStyle'] = 'inset';\n\t\t// get annotation data\n\t\t$popt = $this->getAnnotOptFromJSProp($prop);\n\t\t// set additional default values\n\t\t$font = 'zapfdingbats';\n\t\t$this->AddFont($font);\n\t\t$tmpfont = $this->getFontBuffer($font);\n\t\t$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];\n\t\t$fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = array();\n\t\t$popt['ap']['n'][$onvalue] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';\n\t\t$popt['ap']['n']['Off'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';\n\t\tif (!isset($popt['mk'])) {\n\t\t\t$popt['mk'] = array();\n\t\t}\n\t\t$popt['mk']['ca'] = '(l)';\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Btn';\n\t\tif ($checked) {\n\t\t\t$opt['v'] = array('/'.$onvalue);\n\t\t\t$opt['as'] = $onvalue;\n\t\t} else {\n\t\t\t$opt['as'] = 'Off';\n\t\t}\n\t\t$this->Annotation($x, $y, $w, $w, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct(\n TranslatableNotificationHandlerInterface $notificationHandler,\n TrashService $trashService,\n ContentTypeService $contentTypeService,\n UiPathService $uiPathService,\n TrashFormFactory $formFactory,\n SubmitHandler $submitHandler,\n UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,\n ConfigResolverInterface $configResolver,\n TrashSearchQueryType $trashSearchQueryType,\n UserService $userService\n ) {\n $this->notificationHandler = $notificationHandler;\n $this->trashService = $trashService;\n $this->contentTypeService = $contentTypeService;\n $this->uiPathService = $uiPathService;\n $this->formFactory = $formFactory;\n $this->submitHandler = $submitHandler;\n $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;\n $this->configResolver = $configResolver;\n $this->trashSearchQueryType = $trashSearchQueryType;\n $this->userService = $userService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n Domain $domain,\n ProductCollectionFacade $productCollectionFacade,\n ProductAccessoryFacade $productAccessoryFacade,\n CurrentCustomerUser $currentCustomerUser,\n ParameterWithValuesFactory $parameterWithValuesFactory,\n ProductAvailabilityFacade $productAvailabilityFacade,\n HreflangLinksFacade $hreflangLinksFacade,\n ProductFrontendLimitProvider $productFrontendLimitProvider,\n DataLoaderInterface $productsSellableByIdsBatchLoader,\n ProductVisibilityFacade $productVisibilityFacade,\n protected readonly FriendlyUrlFacade $friendlyUrlFacade,\n protected readonly ProductRepository $productRepository,\n protected readonly PricingGroupSettingFacade $pricingGroupSettingFacade,\n protected readonly ParameterRepository $parameterRepository,\n protected readonly BreadcrumbFacade $breadcrumbFacade,\n protected readonly DataLoaderInterface $categoriesBatchLoader,\n protected readonly DataLoaderInterface $brandsBatchLoader,\n protected readonly ProductVideoTranslationsRepository $productVideoTranslationsRepository,\n ) {\n parent::__construct(\n $domain,\n $productCollectionFacade,\n $productAccessoryFacade,\n $currentCustomerUser,\n $parameterWithValuesFactory,\n $productAvailabilityFacade,\n $hreflangLinksFacade,\n $productFrontendLimitProvider,\n $productsSellableByIdsBatchLoader,\n $productVisibilityFacade,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function addMailboxPnote(\n $pid,\n $newtext,\n $authorized = '0',\n $activity = '1',\n $title = 'Unassigned',\n $assigned_to = '',\n $datetime = '',\n $message_status = \"New\"\n) {\n\n if (empty($datetime)) {\n $datetime = date('Y-m-d H:i:s');\n }\n\n // make inactive if set as Done\n if ($message_status == \"Done\") {\n $activity = 0;\n }\n\n $body = date('Y-m-d H:i') . ' (' . $pid;\n if ($assigned_to) {\n $body .= \" to $assigned_to\";\n }\n\n $body = $body . ') ' . $newtext;\n\n return sqlInsert(\n \"INSERT INTO pnotes (date, body, pid, user, groupname, \" .\n \"authorized, activity, title, assigned_to, message_status, update_by, update_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())\",\n array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status, $_SESSION['authUserID'])\n );\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style='', $align='') {\n\t\tif ($this->empty_string(trim($code))) {\n\t\t\treturn;\n\t\t}\n\t\trequire_once(dirname(__FILE__).'/barcodes.php');\n\t\t// save current graphic settings\n\t\t$gvars = $this->getGraphicVars();\n\t\t// create new barcode object\n\t\t$barcodeobj = new TCPDFBarcode($code, $type);\n\t\t$arrcode = $barcodeobj->getBarcodeArray();\n\t\tif ($arrcode === false) {\n\t\t\t$this->Error('Error in 1D barcode string');\n\t\t}\n\t\t// set default values\n\t\tif (!isset($style['position'])) {\n\t\t\t$style['position'] = '';\n\t\t} elseif ($style['position'] == 'S') {\n\t\t\t// keep this for backward compatibility\n\t\t\t$style['position'] = '';\n\t\t\t$style['stretch'] = true;\n\t\t}\n\t\tif (!isset($style['fitwidth'])) {\n\t\t\tif (!isset($style['stretch'])) {\n\t\t\t\t$style['fitwidth'] = true;\n\t\t\t} else {\n\t\t\t\t$style['fitwidth'] = false;\n\t\t\t}\n\t\t}\n\t\tif ($style['fitwidth']) {\n\t\t\t// disable stretch\n\t\t\t$style['stretch'] = false;\n\t\t}\n\t\tif (!isset($style['stretch'])) {\n\t\t\tif (($w === '') OR ($w <= 0)) {\n\t\t\t\t$style['stretch'] = false;\n\t\t\t} else {\n\t\t\t\t$style['stretch'] = true;\n\t\t\t}\n\t\t}\n\t\tif (!isset($style['fgcolor'])) {\n\t\t\t$style['fgcolor'] = array(0,0,0); // default black\n\t\t}\n\t\tif (!isset($style['bgcolor'])) {\n\t\t\t$style['bgcolor'] = false; // default transparent\n\t\t}\n\t\tif (!isset($style['border'])) {\n\t\t\t$style['border'] = false;\n\t\t}\n\t\t$fontsize = 0;\n\t\tif (!isset($style['text'])) {\n\t\t\t$style['text'] = false;\n\t\t}\n\t\tif ($style['text'] AND isset($style['font'])) {\n\t\t\tif (isset($style['fontsize'])) {\n\t\t\t\t$fontsize = $style['fontsize'];\n\t\t\t}\n\t\t\t$this->SetFont($style['font'], '', $fontsize);\n\t\t}\n\t\tif (!isset($style['stretchtext'])) {\n\t\t\t$style['stretchtext'] = 4;\n\t\t}\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\tif (($w === '') OR ($w <= 0)) {\n\t\t\tif ($this->rtl) {\n\t\t\t\t$w = $x - $this->lMargin;\n\t\t\t} else {\n\t\t\t\t$w = $this->w - $this->rMargin - $x;\n\t\t\t}\n\t\t}\n\t\t// padding\n\t\tif (!isset($style['padding'])) {\n\t\t\t$padding = 0;\n\t\t} elseif ($style['padding'] === 'auto') {\n\t\t\t$padding = 10 * ($w / ($arrcode['maxw'] + 20));\n\t\t} else {\n\t\t\t$padding = floatval($style['padding']);\n\t\t}\n\t\t// horizontal padding\n\t\tif (!isset($style['hpadding'])) {\n\t\t\t$hpadding = $padding;\n\t\t} elseif ($style['hpadding'] === 'auto') {\n\t\t\t$hpadding = 10 * ($w / ($arrcode['maxw'] + 20));\n\t\t} else {\n\t\t\t$hpadding = floatval($style['hpadding']);\n\t\t}\n\t\t// vertical padding\n\t\tif (!isset($style['vpadding'])) {\n\t\t\t$vpadding = $padding;\n\t\t} elseif ($style['vpadding'] === 'auto') {\n\t\t\t$vpadding = ($hpadding / 2);\n\t\t} else {\n\t\t\t$vpadding = floatval($style['vpadding']);\n\t\t}\n\t\t// calculate xres (single bar width)\n\t\t$max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];\n\t\tif ($style['stretch']) {\n\t\t\t$xres = $max_xres;\n\t\t} else {\n\t\t\tif ($this->empty_string($xres)) {\n\t\t\t\t$xres = (0.141 * $this->k); // default bar width = 0.4 mm\n\t\t\t}\n\t\t\tif ($xres > $max_xres) {\n\t\t\t\t// correct xres to fit on $w\n\t\t\t\t$xres = $max_xres;\n\t\t\t}\n\t\t\tif ((isset($style['padding']) AND ($style['padding'] === 'auto'))\n\t\t\t\tOR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {\n\t\t\t\t$hpadding = 10 * $xres;\n\t\t\t\tif (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {\n\t\t\t\t\t$vpadding = ($hpadding / 2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ($style['fitwidth']) {\n\t\t\t$wold = $w;\n\t\t\t$w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));\n\t\t\tif (isset($style['cellfitalign'])) {\n\t\t\t\tswitch ($style['cellfitalign']) {\n\t\t\t\t\tcase 'L': {\n\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t$x -= ($wold - $w);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'R': {\n\t\t\t\t\t\tif (!$this->rtl) {\n\t\t\t\t\t\t\t$x += ($wold - $w);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'C': {\n\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t$x -= (($wold - $w) / 2);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$x += (($wold - $w) / 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault : {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$text_height = ($this->cell_height_ratio * $fontsize / $this->k);\n\t\t// height\n\t\tif (($h === '') OR ($h <= 0)) {\n\t\t\t// set default height\n\t\t\t$h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;\n\t\t}\n\t\t$barh = $h - $text_height - (2 * $vpadding);\n\t\tif ($barh <=0) {\n\t\t\t// try to reduce font or padding to fit barcode on available height\n\t\t\tif ($text_height > $h) {\n\t\t\t\t$fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));\n\t\t\t\t$text_height = ($this->cell_height_ratio * $fontsize / $this->k);\n\t\t\t\t$this->SetFont($style['font'], '', $fontsize);\n\t\t\t}\n\t\t\tif ($vpadding > 0) {\n\t\t\t\t$vpadding = (($h - $text_height) / 4);\n\t\t\t}\n\t\t\t$barh = $h - $text_height - (2 * $vpadding);\n\t\t}\n\t\t// fit the barcode on available space\n\t\t$this->fitBlock($w, $h, $x, $y, false);\n\t\t// set alignment\n\t\t$this->img_rb_y = $y + $h;\n\t\t// set alignment\n\t\tif ($this->rtl) {\n\t\t\tif ($style['position'] == 'L') {\n\t\t\t\t$xpos = $this->lMargin;\n\t\t\t} elseif ($style['position'] == 'C') {\n\t\t\t\t$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($style['position'] == 'R') {\n\t\t\t\t$xpos = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xpos = $x - $w;\n\t\t\t}\n\t\t\t$this->img_rb_x = $xpos;\n\t\t} else {\n\t\t\tif ($style['position'] == 'L') {\n\t\t\t\t$xpos = $this->lMargin;\n\t\t\t} elseif ($style['position'] == 'C') {\n\t\t\t\t$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($style['position'] == 'R') {\n\t\t\t\t$xpos = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xpos = $x;\n\t\t\t}\n\t\t\t$this->img_rb_x = $xpos + $w;\n\t\t}\n\t\t$xpos_rect = $xpos;\n\t\tif (!isset($style['align'])) {\n\t\t\t$style['align'] = 'C';\n\t\t}\n\t\tswitch ($style['align']) {\n\t\t\tcase 'L': {\n\t\t\t\t$xpos = $xpos_rect + $hpadding;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'R': {\n\t\t\t\t$xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\tdefault : {\n\t\t\t\t$xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$xpos_text = $xpos;\n\t\t// barcode is always printed in LTR direction\n\t\t$tempRTL = $this->rtl;\n\t\t$this->rtl = false;\n\t\t// print background color\n\t\tif ($style['bgcolor']) {\n\t\t\t$this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);\n\t\t} elseif ($style['border']) {\n\t\t\t$this->Rect($xpos_rect, $y, $w, $h, 'D');\n\t\t}\n\t\t// set foreground color\n\t\t$this->SetDrawColorArray($style['fgcolor']);\n\t\t$this->SetTextColorArray($style['fgcolor']);\n\t\t// print bars\n\t\tforeach ($arrcode['bcode'] as $k => $v) {\n\t\t\t$bw = ($v['w'] * $xres);\n\t\t\tif ($v['t']) {\n\t\t\t\t// draw a vertical bar\n\t\t\t\t$ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);\n\t\t\t\t$this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);\n\t\t\t}\n\t\t\t$xpos += $bw;\n\t\t}\n\t\t// print text\n\t\tif ($style['text']) {\n\t\t\tif (isset($style['label']) AND !$this->empty_string($style['label'])) {\n\t\t\t\t$label = $style['label'];\n\t\t\t} else {\n\t\t\t\t$label = $code;\n\t\t\t}\n\t\t\t$txtwidth = ($arrcode['maxw'] * $xres);\n\t\t\tif ($this->GetStringWidth($label) > $txtwidth) {\n\t\t\t\t$style['stretchtext'] = 2;\n\t\t\t}\n\t\t\t// print text\n\t\t\t$this->x = $xpos_text;\n\t\t\t$this->y = $y + $vpadding + $barh;\n\t\t\t$cellpadding = $this->cell_padding;\n\t\t\t$this->SetCellPadding(0);\n\t\t\t$this->Cell($txtwidth, '', $label, 0, 0, 'C', 0, '', $style['stretchtext'], false, 'T', 'T');\n\t\t\t$this->cell_padding = $cellpadding;\n\t\t}\n\t\t// restore original direction\n\t\t$this->rtl = $tempRTL;\n\t\t// restore previous settings\n\t\t$this->setGraphicVars($gvars);\n\t\t// set pointer to align the next text/objects\n\t\tswitch($align) {\n\t\t\tcase 'T':{\n\t\t\t\t$this->y = $y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'M':{\n\t\t\t\t$this->y = $y + round($h / 2);\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B':{\n\t\t\t\t$this->y = $this->img_rb_y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'N':{\n\t\t\t\t$this->SetY($this->img_rb_y);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$this->endlinex = $this->img_rb_x;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function creerDossierIBAcid($ref_dos, $id_cli, $ref_fact, $t1, $poids, \n\t\t\t\t\t\t\t\t\t\t\t$num_lic, $id_mod_lic, $id_march, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t$id_util, $horse, $trailer_1, $trailer_2, $klsa_arriv, \n\t\t\t\t\t\t\t\t\t\t\t$crossing_date, $wiski_arriv, $wiski_dep, $ref_crf, $date_crf){\n\t\t\tinclude('connexion.php');\n\n\t\t\t/*echo '
    ref_dos = '.$ref_dos;echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    ref_fact = '.$ref_fact;echo '
    t1 = '.$t1;\n\t\t\techo '
    poids = '.$poids;echo '
    num_lic = '.$num_lic;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;echo '
    id_march = '.$id_march;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;echo '
    id_util = '.$id_util;\n\t\t\techo '
    horse = '.$horse;echo '
    trailer_1 = '.$trailer_1;\n\t\t\techo '
    trailer_2 = '.$trailer_2;echo '
    klsa_arriv = '.$klsa_arriv;\n\t\t\techo '
    crossing_date = '.$crossing_date;echo '
    wiski_arriv = '.$wiski_arriv;\n\t\t\techo '
    wiski_dep = '.$wiski_dep;*/\n\t\t\t//echo '
    id_mod_lic = '.$id_mod_lic;\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['ref_fact'] = $ref_fact; \n\t\t\t$entree['t1'] = $t1; $entree['poids'] = $poids; $entree['num_lic'] = $num_lic; \n\t\t\t$entree['id_mod_lic'] = $id_mod_lic; $entree['id_march'] = $id_march; $entree['id_mod_trans'] = $id_mod_trans; \n\t\t\t$entree['id_util'] = $id_util; $entree['horse'] = $horse; $entree['trailer_1'] = $trailer_1; \n\t\t\t$entree['trailer_2'] = $trailer_2; $entree['klsa_arriv'] = $klsa_arriv; $entree['crossing_date'] = $crossing_date; \n\t\t\t$entree['wiski_arriv'] = $wiski_arriv; $entree['wiski_dep'] = $wiski_dep; \n\t\t\t$entree['ref_crf'] = $ref_crf; $entree['date_crf'] = $date_crf; \n\n\t\t\tif($entree['klsa_arriv'] == '' || (!isset($entree['klsa_arriv'])) ){\n\t\t\t\t$entree['klsa_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['crossing_date'] == '' || (!isset($entree['crossing_date'])) ){\n\t\t\t\t$entree['crossing_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_arriv'] == '' || (!isset($entree['wiski_arriv'])) ){\n\t\t\t\t$entree['wiski_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_dep'] == '' || (!isset($entree['wiski_dep'])) ){\n\t\t\t\t$entree['wiski_dep'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['poids'] == '' || (!isset($entree['poids'])) ){\n\t\t\t\t$entree['poids'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_crf'] == '' || (!isset($entree['date_crf'])) ){\n\t\t\t\t$entree['date_crf'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, ref_fact, t1, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnum_lic, id_mod_lic, id_march, id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_util, horse, trailer_1, trailer_2, klsa_arriv, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcrossing_date, wiski_arriv, wiski_dep, ref_crf, date_crf)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['t1'], $entree['poids'], $entree['num_lic'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['id_march'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['id_util'], $entree['horse'], $entree['trailer_1'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_2'], $entree['klsa_arriv'], $entree['crossing_date'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_arriv'], $entree['wiski_dep'], \n\t\t\t\t\t\t\t\t\t$entree['ref_crf'], $entree['date_crf']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public static function saveAudit(string $service, int $pid, int $success, array $auditData, ?string $ticket = null, ?string $transactionId = null, ?string $actionName = null, ?string $amount = null): void\n {\n $uuid = (new UuidRegistry(['table_name' => 'payment_processing_audit']))->createUuid();\n $auditData = json_encode($auditData);\n $auditData = (new CryptoGen())->encryptStandard($auditData);\n sqlStatement(\n \"INSERT INTO `payment_processing_audit` (`uuid`, `service`, `pid`, `success`, `action_name`, `amount`, `ticket`, `transaction_id`, `audit_data`, `date`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())\",\n [\n $uuid,\n $service,\n $pid,\n $success,\n $actionName,\n $amount,\n $ticket,\n $transactionId,\n $auditData\n ]\n );\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($link = null, $type = null, $length = null, $javascript = null, $bitrate = null, $captions = null, $categories = null, $channels = null, $copyright = null, $credits = null, $description = null, $duration = null, $expression = null, $framerate = null, $hashes = null, $height = null, $keywords = null, $lang = null, $medium = null, $player = null, $ratings = null, $restrictions = null, $samplingrate = null, $thumbnails = null, $title = null, $width = null)\n\t{\n\t\t$this->bitrate = $bitrate;\n\t\t$this->captions = $captions;\n\t\t$this->categories = $categories;\n\t\t$this->channels = $channels;\n\t\t$this->copyright = $copyright;\n\t\t$this->credits = $credits;\n\t\t$this->description = $description;\n\t\t$this->duration = $duration;\n\t\t$this->expression = $expression;\n\t\t$this->framerate = $framerate;\n\t\t$this->hashes = $hashes;\n\t\t$this->height = $height;\n\t\t$this->keywords = $keywords;\n\t\t$this->lang = $lang;\n\t\t$this->length = $length;\n\t\t$this->link = $link;\n\t\t$this->medium = $medium;\n\t\t$this->player = $player;\n\t\t$this->ratings = $ratings;\n\t\t$this->restrictions = $restrictions;\n\t\t$this->samplingrate = $samplingrate;\n\t\t$this->thumbnails = $thumbnails;\n\t\t$this->title = $title;\n\t\t$this->type = $type;\n\t\t$this->width = $width;\n\n\t\tif (class_exists('idna_convert'))\n\t\t{\n\t\t\t$idn = new idna_convert();\n\t\t\t$parsed = SimplePie_Misc::parse_url($link);\n\t\t\t$this->link = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);\n\t\t}\n\t\t$this->handler = $this->get_handler(); // Needs to load last\n\t}", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "function define_external_table(&$results, $index, $table_name, $col_code, $col_description, $col_description_brief, $filter_clauses = array(), $version_order = \"\", $joins = array(), $display_desc = \"\")\n{\n $results[$index] = array(EXT_TABLE_NAME => $table_name,\n EXT_COL_CODE => $col_code,\n EXT_COL_DESCRIPTION => $col_description,\n EXT_COL_DESCRIPTION_BRIEF => $col_description_brief,\n EXT_FILTER_CLAUSES => $filter_clauses,\n EXT_JOINS => $joins,\n EXT_VERSION_ORDER => $version_order,\n DISPLAY_DESCRIPTION => $display_desc\n );\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function resizePicture(\n $source_path,\n $dest_path,\n $new_width = 71,\n $new_height = 71,\n $img_y = 0,\n $img_x = 0,\n $img_width = 0,\n $img_height = 0,\n $max_size = 500\n ) {\n\n //get img information (dimensions and extension)\n $img_infos = getimagesize($source_path);\n if (empty($img_width)) {\n $img_width = $img_infos[0];\n }\n if (empty($img_height)) {\n $img_height = $img_infos[1];\n }\n\n if (\n empty($max_size)\n && (\n !empty($new_width)\n || !empty($new_height)\n )\n ) {\n $max_size = ($new_width > $new_height ? $new_width : $new_height);\n }\n\n $source_aspect_ratio = $img_width / $img_height;\n if ($source_aspect_ratio < 1) {\n $new_width = ceil($max_size * $source_aspect_ratio);\n $new_height = $max_size;\n } else {\n $new_width = $max_size;\n $new_height = ceil($max_size / $source_aspect_ratio);\n }\n\n $img_type = $img_infos[2];\n\n switch ($img_type) {\n case IMAGETYPE_BMP:\n $source_res = imagecreatefrombmp($source_path);\n break;\n\n case IMAGETYPE_GIF:\n $source_res = imagecreatefromgif($source_path);\n break;\n\n case IMAGETYPE_JPEG:\n $source_res = imagecreatefromjpeg($source_path);\n break;\n\n case IMAGETYPE_PNG:\n $source_res = imagecreatefrompng($source_path);\n break;\n\n case IMAGETYPE_WEBP:\n $source_res = imagecreatefromwebp($source_path);\n break;\n\n default:\n return false;\n }\n\n //create new img resource for store thumbnail\n $source_dest = imagecreatetruecolor($new_width, $new_height);\n\n // set transparent background for PNG/GIF/WebP\n if ($img_type === IMAGETYPE_GIF || $img_type === IMAGETYPE_PNG || $img_type === IMAGETYPE_WEBP) {\n imagecolortransparent($source_dest, imagecolorallocatealpha($source_dest, 0, 0, 0, 127));\n imagealphablending($source_dest, false);\n imagesavealpha($source_dest, true);\n }\n\n //resize image\n imagecopyresampled(\n $source_dest,\n $source_res,\n 0,\n 0,\n $img_x,\n $img_y,\n $new_width,\n $new_height,\n $img_width,\n $img_height\n );\n\n //output img\n $result = null;\n switch ($img_type) {\n case IMAGETYPE_GIF:\n case IMAGETYPE_PNG:\n $result = imagepng($source_dest, $dest_path);\n break;\n\n case IMAGETYPE_WEBP:\n $result = imagewebp($source_dest, $dest_path);\n break;\n\n case IMAGETYPE_JPEG:\n default:\n $result = imagejpeg($source_dest, $dest_path, 90);\n break;\n }\n return $result;\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function portalNewEvent($event, $user, $groupname, $success, $comments = \"\", $patient_id = null, $log_from = '', $user_notes = \"\", $ccda_doc_id = 0)\n {\n EventAuditLogger::instance()->recordLogItem($success, $event, $user, $groupname, $comments, $patient_id, null, $log_from, null, $ccda_doc_id, $user_notes);\n }", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function modifInscriptionEleve($num,$annee,$etab,$classe,$prof_principal,$filiere,$lv1,$lv2,$date_inscription,$commentaires,$nouveau)\n\t{\n\t\tif($nouveau) {\n\t\t\t$req = \"INSERT INTO `\".PdoBD::$villeExtranet.\"_inscrit`(`ID_ELEVE`, `ANNEE`, `ID`, `ID_FILIERES`, `ID_LV1`, `ID_LV2`, `ID_CLASSE`, `DATE_INSCRIPTION`, `NOM_DU_PROF_PRINCIPAL`, `COMMENTAIRESANNEE`) VALUES (:num, :annee, :etab, :filiere, :lv1, :lv2, :classe, :date_inscription, :prof_principal, :commentaires)\";\n\t\t\t$params = array(\n\t\t\t\t'num' => $num,\n\t\t\t\t'annee' => $annee,\n\t\t\t\t'etab' => $etab,\n\t\t\t\t'filiere' => $filiere,\n\t\t\t\t'lv1' => $lv1,\n\t\t\t\t'lv2' => $lv2,\n\t\t\t\t'classe' => $classe,\n\t\t\t\t'date_inscription' => $date_inscription,\n\t\t\t\t'prof_principal' => $prof_principal,\n\t\t\t\t'commentaires' => $commentaires\n\t\t\t);\n\t\t\t$rs = $this->NonQuery($req, $params);\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'ajout de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t} else {\n\t\t\t$req = \"UPDATE `\".PdoBD::$villeExtranet.\"_inscrit` SET `ID`=:etab,`ID_FILIERES`=:filiere,`ID_LV1`=:lv1,`ID_LV2`=:lv2,`ID_CLASSE`=:classe,`DATE_INSCRIPTION`=:date_inscription,`NOM_DU_PROF_PRINCIPAL`=:prof_principal,`COMMENTAIRESANNEE`=:commentaires WHERE `ID_ELEVE`=:num AND `ANNEE`=:annee\";\n\t\t\t$params = array(\n\t\t\t\t'etab' => $etab,\n\t\t\t\t'filiere' => $filiere,\n\t\t\t\t'lv1' => $lv1,\n\t\t\t\t'lv2' => $lv2,\n\t\t\t\t'classe' => $classe,\n\t\t\t\t'date_inscription' => $date_inscription,\n\t\t\t\t'prof_principal' => $prof_principal,\n\t\t\t\t'commentaires' => $commentaires,\n\t\t\t\t'num' => $num,\n\t\t\t\t'annee' => $annee\n\t\t\t);\n\t\t\t$rs = $this->NonQuery($req, $params);\n\t\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function G($r, $i, $a, $b, $c, $d, SplFixedArray $v, SplFixedArray $m)\n {\n $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][$i << 1]]);\n $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 32);\n $v[$c] = self::add64($v[$c], $v[$d]);\n $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 24);\n $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][($i << 1) + 1]]);\n $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 16);\n $v[$c] = self::add64($v[$c], $v[$d]);\n $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 63);\n return $v;\n }", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "public function creerDossierIB2($ref_dos, $id_cli, $ref_fact, $fob, \n\t\t\t\t\t\t\t\t\t\t$fret, $assurance, $autre_frais, $num_lic, \n\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $id_march, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$ref_av, $cod, $fxi, $montant_av, $date_fact, $ref_decl,\n\t\t\t\t\t\t\t\t\t\t$montant_decl, $ref_liq, $id_util, $ref_quit, $date_quit){\n\t\t\tinclude('connexion.php');\n\n\t\t\t/*echo '
    ref_dos = '.$ref_dos;echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    ref_fact = '.$ref_fact;echo '
    fob = '.$fob;\n\t\t\techo '
    fret = '.$fret;echo '
    assurance = '.$assurance;\n\t\t\techo '
    autre_frais = '.$autre_frais;echo '
    num_lic = '.$num_lic;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;*/\n\t\t\t//echo '
    id_mod_lic = '.$id_mod_lic;\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['ref_fact'] = $ref_fact; \n\t\t\t$entree['fob'] = $fob; $entree['fret'] = $fret; $entree['assurance'] = $assurance; \n\t\t\t$entree['autre_frais'] = $autre_frais; $entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic; $entree['id_march'] = $id_march; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['ref_av'] = $ref_av;\n\t\t\t$entree['cod'] = $cod;$entree['fxi'] = $fxi;\n\t\t\t$entree['montant_av'] = $montant_av;$entree['date_fact'] = $date_fact;\n\t\t\t$entree['ref_decl'] = $ref_decl;$entree['montant_decl'] = $montant_decl;\n\t\t\t$entree['ref_liq'] = $ref_liq;$entree['id_util'] = $id_util;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['date_quit'] = $date_quit;\n\n\t\t\tif($entree['date_fact'] == '' || (strlen($entree['date_fact']) != 10) ){\n\t\t\t\t$entree['date_fact'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_quit'] == '' || (strlen($entree['date_quit']) != 10) ){\n\t\t\t\t$entree['date_quit'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, ref_fact, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfret, assurance, autre_frais, num_lic, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_march, id_mod_trans, ref_av,cod, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfxi, montant_av, date_fact, ref_decl, montant_decl, ref_liq, id_util, ref_quit, date_quit)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['num_lic'], $entree['id_mod_lic'], \n\t\t\t\t\t\t\t\t\t$entree['id_march'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['ref_av'], $entree['cod'], $entree['fxi'], \n\t\t\t\t\t\t\t\t\t$entree['montant_av'], $entree['date_fact'], $entree['ref_decl'], \n\t\t\t\t\t\t\t\t\t$entree['montant_decl'], $entree['ref_liq'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['ref_quit'], $entree['date_quit']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "protected function addLineToNonCreditSubscriber($counters, $row, $pricingData, $vatable, &$sraw, $zone, $plan_key, $category_key, $zone_key) {\n\t\tif (!empty($counters)) {\n\t\t\tif (!(isset($pricingData['over_plan']) && $pricingData['over_plan'] < current($counters))) { // volume is partially priced (in & over plan)\n\t\t\t\t$volume_priced = current($counters);\n\t\t\t} else {\n\t\t\t\t$volume_priced = $pricingData['over_plan'];\n\t\t\t\t$planZone = &$sraw['breakdown']['in_plan'][$category_key][$zone_key];\n\t\t\t\t$planZone['totals'][key($counters)]['usagev'] = $this->getFieldVal($planZone['totals'][key($counters)]['usagev'], 0) + current($counters) - $volume_priced; // add partial usage to flat\n\t\t\t\t$planZone['totals'][key($counters)]['cost'] = $this->getFieldVal($planZone['totals'][key($counters)]['cost'], 0);\n\t\t\t\t$planZone['totals'][key($counters)]['count'] = $this->getFieldVal($planZone['totals'][key($counters)]['count'], 0) + 1;\n\t\t\t\t$planZone['vat'] = ($vatable ? floatval($this->vat) : 0); //@TODO we assume here that all the lines would be vatable or all vat-free\n\t\t\t}\n\n\t\t\t$zone['totals'][key($counters)]['usagev'] = $this->getFieldVal($zone['totals'][key($counters)]['usagev'], 0) + $volume_priced;\n\t\t\t$zone['totals'][key($counters)]['cost'] = $this->getFieldVal($zone['totals'][key($counters)]['cost'], 0) + $pricingData['aprice'];\n\t\t\t$zone['totals'][key($counters)]['count'] = $this->getFieldVal($zone['totals'][key($counters)]['count'], 0) + 1;\n\t\t\tif ($row['type'] == 'ggsn') {\n\t\t\t\t// TODO: What is this magic number 06? There should just be a ggsn row class\n\t\t\t\tif (isset($row['rat_type']) && $row['rat_type'] == '06') {\n\t\t\t\t\t$data_generation = 'usage_4g';\n\t\t\t\t} else {\n\t\t\t\t\t$data_generation = 'usage_3g';\n\t\t\t\t}\n\t\t\t\t$zone['totals'][key($counters)][$data_generation]['usagev'] = $this->getFieldVal($zone['totals'][key($counters)]['usagev_' . $data_generation], 0) + $volume_priced;\n\t\t\t\t$zone['totals'][key($counters)][$data_generation]['cost'] = $this->getFieldVal($zone['totals'][key($counters)]['cost_' . $data_generation], 0) + $pricingData['aprice'];\n\t\t\t\t$zone['totals'][key($counters)][$data_generation]['count'] = $this->getFieldVal($zone['totals'][key($counters)]['count_' . $data_generation], 0) + 1;\n\t\t\t}\n\t\t}\n\t\tif ($plan_key != 'in_plan' || $zone_key == 'service') {\n\t\t\t$zone['cost'] = $this->getFieldVal($zone['cost'], 0) + $pricingData['aprice'];\n\t\t}\n\t\t$zone['vat'] = ($vatable ? floatval($this->vat) : 0); //@TODO we assume here that all the lines would be vatable or all vat-free\n\t}", "smellKey": "S107", "smellId": null, "repo": "Testtarosa_Bill-System", "language": "php"} {"function": "function lr_betak($x, $y, $k1, $e1, $e2, $emult, $ydiff, $ymult, $y1, $y2) {\n $e1k = pow($e1, $k1);\n $e2k = pow($e2, $k1);\n $efrac = pow($emult / exp($x), $k1);\n $fval = $ymult * ($e1k - $e2k) / ($y2 * $e1k - $y1 * $e2k + $ydiff * $efrac);\n return $y - $fval;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function info_ajouterUneInscription($nom, $prenom, $adresse, $cp, $ville, $lat, $lon, $sexe, $ddn, $date, $tel1, $tel2, $email,$annee) {\n\n $req = \"INSERT INTO `info_inscriptions` VALUES('','\".strtoupper($nom).\"','\".ucfirst($prenom).\"','','','\".strtoupper($adresse).\"','$cp','\".strtoupper($ville).\"','$lat','$lon','$sexe','$ddn','$date','$tel1','$tel2','$email');\n INSERT INTO `info_annees` VALUES($annee,(SELECT MAX(`id_inscription`) FROM `info_inscriptions`));\";\n\n\t\t$rs = PdoBD::$monPdo->query($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la lecture des donnees ..\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t$laLigne = $rs->fetchAll();\n\t\treturn $laLigne; \n \n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function send_update(string $token, string $score_url, float $score,\n string $ltiuserid, string $activityProgress='Submitted',\n string $gradingProgress='FullyGraded', $isstu = 1, string $comment = ''\n ) {\n $pos = strpos($score_url, '?');\n $score_url = $pos === false ? $score_url . '/scores' : substr_replace($score_url, '/scores', $pos, 0);\n\n $content = $this->get_update_body($token, $score, $ltiuserid, $isstu, null,\n $activityProgress, $gradingProgress, $comment);\n $this->debuglog('Sending update: '.$content['body']);\n // try to spawn a curl and don't wait for response\n /*\n $disabled = explode(', ', ini_get('disable_functions'));\n if (function_exists('exec') && !in_array('exec', $disabled)) {\n \t try {\n \t\t$cmd = \"curl -X POST\";\n \t\tforeach ($content['header'] as $hdr) {\n \t\t\tif (strlen($hdr)<2) {continue;}\n \t\t\t//$cmd .= \" -H '\".str_replace(\"'\",\"\\\\'\",$hdr).\"'\";\n \t\t\t$cmd .= \" -H \" . escapeshellarg($hdr);\n \t\t}\n \t\t$cmd .= \" -d \" . escapeshellarg($content['body']) . ' ' . escapeshellarg($score_url);\n \t\t$cmd .= \" > /dev/null 2>&1 &\";\n \t\t@exec($cmd, $output, $exit);\n \t\treturn ($exit == 0);\n \t } catch (Exception $e) {\n \t\t//continue below\n \t }\n }\n */\n // do it the usual way, waiting for a response\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $score_url);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_HEADER, 1);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);\n curl_setopt($ch, CURLOPT_POST, 1);\n curl_setopt($ch, CURLOPT_POSTFIELDS, strval($content['body']));\n curl_setopt($ch, CURLOPT_HTTPHEADER, $content['header']);\n\n if (!empty($GLOBALS['CFG']['LTI']['skipsslverify'])) {\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);\n curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);\n }\n\n $response = curl_exec($ch);\n $request_info = curl_getinfo($ch);\n if (curl_errno($ch) || round(intval($request_info['http_code'])/100) != 2) {\n $this->debuglog('Grade update Error:' . curl_error($ch));\n return false;\n }\n $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);\n curl_close ($ch);\n\n $resp_headers = substr($response, 0, $header_size);\n $resp_body = substr($response, $header_size);\n $this->debuglog('Grade update success:' . $resp_body);\n return [\n 'headers' => array_filter(explode(\"\\r\\n\", $resp_headers)),\n 'body' => json_decode($resp_body, true),\n ];\n }", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function InsertaInscritosPorInsc($rut, $movilizacion, $viatico, $id_inscripcion, $tramo, $empresa, $gerencia, $centro_costo, $cargo){\n\tglobal $c_host,$c_user,$c_pass,$c_db;\t\n\t$rut_completo=$rut.\"-\".$dv;\n\t$nombre_completo=$nombre.\" \".$apaterno.\" \".$amaterno;\n\t$database = new database($c_host,$c_user,$c_pass);\n\t$database->setDb($c_db);\n\t$sql = \"INSERT INTO tbl_inscripcion_usuarios\n\t\t\t\t\t\t\t(id_inscripcion, rut, movilizacion, viatico, tramo_sence, empresa, gerencia, centro_costo, cargo) \".\n\t\t\t\n\t\"VALUES \t\t\t\t( '$id_inscripcion', '$rut', '$movilizacion', '$viatico', '$tramo', '$empresa', '$gerencia', '$centro_costo', '$cargo');\";\n\t\t\t\n\t$database->setquery($sql);\n\t$database->query();\t\n\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "protected function get_file_name($file_path, $name, $subfolder, $size, $type, $error,\n $index, $content_range) {\n\n $name = $this->trim_file_name($file_path, $name, $size, $type, $error,\n $index, $content_range);\n\n return $this->get_unique_filename(\n $file_path,\n $this->fix_file_extension($file_path, $name, $size, $type, $error,\n $index, $content_range),\n $subfolder,\n $size,\n $type,\n $error,\n $index,\n $content_range\n );\n }", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "protected function getCustomers( $exist_custom_field, $exist_salt, $exist_safe, $exist_token, $exist_code, $offset=null, $rows=null, $min_id=null, $max_id=null ) {\n\t\t// Newer OC versions use the 'customer_group_description' instead of 'customer_group' table for the 'name' field\n\t\t$exist_table_customer_group_description = false;\n\t\t$query = $this->db->query( \"SHOW TABLES LIKE '\".DB_PREFIX.\"customer_group_description'\" );\n\t\t$exist_table_customer_group_description = ($query->num_rows > 0);\n\n\t\t$language_id = $this->getDefaultLanguageId();\n\n\t\tif ($exist_table_customer_group_description) {\n\t\t\t$sql = \"SELECT c.*, cgd.name AS customer_group FROM `\".DB_PREFIX.\"customer` c \";\n\t\t\t$sql .= \"INNER JOIN `\".DB_PREFIX.\"customer_group_description` cgd ON cgd.customer_group_id=c.customer_group_id AND cgd.language_id='\".(int)$language_id.\"' \";\n\t\t} else {\n\t\t\t$sql = \"SELECT c.*, cg.name AS customer_group FROM `\".DB_PREFIX.\"customer` c \";\n\t\t\t$sql .= \"INNER JOIN `\".DB_PREFIX.\"customer_group` cg ON cg.customer_group_id=c.customer_group_id \";\n\t\t}\n\t\tif (isset($min_id) && isset($max_id)) {\n\t\t\t$sql .= \"WHERE c.customer_id BETWEEN $min_id AND $max_id \";\n\t\t}\n\t\t$sql .= \"GROUP BY c.`customer_id` \";\n\t\t$sql .= \"ORDER BY c.`customer_id` ASC \";\n\t\tif (isset($offset) && isset($rows)) {\n\t\t\t$sql .= \"LIMIT $offset,$rows; \";\n\t\t} else {\n\t\t\t$sql .= \"; \";\n\t\t}\n\t\t$results = $this->db->query( $sql );\n\t\treturn $results->rows;\n\t}", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "public function __construct(\n OrderNumberFilter $orderNumberFilter,\n OrderCreateDateFilter $orderCreateDateFilter,\n OrderPriceFilterWithVatFilter $orderPriceFilterWithVatFilter,\n OrderStatusFilter $orderStatusFilter,\n OrderProductFilter $orderProductFilter,\n OrderPhoneNumberFilter $orderPhoneNumberFilter,\n OrderStreetFilter $orderStreetFilter,\n OrderNameFilter $orderNameFilter,\n OrderLastNameFilter $orderLastNameFilter,\n OrderEmailFilter $orderEmailFilter,\n OrderCityFilter $orderCityFilter,\n OrderCustomerIdFilter $orderCustomerIdFilter,\n ) {\n parent::__construct();\n\n $this->registerFilter($orderPriceFilterWithVatFilter);\n $this->registerFilter($orderNumberFilter);\n $this->registerFilter($orderCreateDateFilter);\n $this->registerFilter($orderStatusFilter);\n $this->registerFilter($orderProductFilter);\n $this->registerFilter($orderNameFilter);\n $this->registerFilter($orderLastNameFilter);\n $this->registerFilter($orderEmailFilter);\n $this->registerFilter($orderPhoneNumberFilter);\n $this->registerFilter($orderStreetFilter);\n $this->registerFilter($orderCityFilter);\n $this->registerFilter($orderCustomerIdFilter);\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function CreateColumnFromFields($dataset, $field, $variable, $caption, $label, $columnWidth, $fieldWidth,\n\t\t$decimals, $format, $measure, $alignment, $useInSummary, $useInExport, $position = null, $after = '')\n\t{\n\t\t$newColumn = new entities\\DraftDatasetColumn();\n\t\t$newColumn->setDataset($dataset);\n\t\t$newColumn->setField($field);\n\t\t$newColumn->setVariable($variable);\n\t\t$newColumn->setCaption($caption);\n\t\t$newColumn->setLabel($label);\n\n\t\t$newColumn->setColumnWidth($columnWidth);\n\t\t$newColumn->setFieldWidth($fieldWidth);\n\t\t$newColumn->setDecimals($decimals);\n\t\t$newColumn->setFormat($format);\n\t\t$newColumn->setMeasure($measure);\n\t\t$newColumn->setAlignment($alignment);\n\n\t\t$newColumn->setUseInSummary($useInSummary);\n\t\t$newColumn->setUseInExport($useInExport);\n\n\t\treturn $this->CreateColumn($dataset, $newColumn, $position, $after);\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "public function creerPVContentieux($ref_pv, $date_pv, $date_reception, $id_bur_douane, $annee, $marchandise, $id_cli, $id_mod_lic, $fichier_pv, $id_util){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['ref_pv']=$ref_pv;\n\t\t\t$entree['date_pv']=$date_pv;\n\t\t\t$entree['date_reception']=$date_reception;\n\t\t\t$entree['id_bur_douane']=$id_bur_douane;\n\t\t\t$entree['annee']=$annee;\n\t\t\t$entree['marchandise']=$marchandise;\n\t\t\t$entree['id_cli']=$id_cli;\n\t\t\t$entree['id_mod_lic']=$id_mod_lic;\n\t\t\t$entree['fichier_pv']=$fichier_pv;\n\t\t\t$entree['id_util']=$id_util;\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO pv_contencieux(ref_pv, date_pv, date_reception, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_bur_douane, annee, marchandise, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_cli, id_mod_lic, fichier_pv, id_util) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_pv'], $entree['date_pv'], $entree['date_reception'], $entree['id_bur_douane'], $entree['annee'], $entree['marchandise'], $entree['id_cli'], $entree['id_mod_lic'], $entree['fichier_pv'], $entree['id_util']));\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\n TranslatableNotificationHandlerInterface $notificationHandler,\n TranslatorInterface $translator,\n ContentTypeService $contentTypeService,\n ActionDispatcherInterface $contentTypeActionDispatcher,\n FormFactory $formFactory,\n SubmitHandler $submitHandler,\n UserService $userService,\n LanguageService $languageService,\n ContentTypeFormFactory $contentTypeFormFactory,\n ContentTypeDraftMapper $contentTypeDraftMapper,\n ConfigResolverInterface $configResolver,\n FieldTypeToolbarFactory $fieldTypeToolbarFactory,\n MetaFieldDefinitionServiceInterface $metaFieldDefinitionService\n ) {\n $this->notificationHandler = $notificationHandler;\n $this->translator = $translator;\n $this->contentTypeService = $contentTypeService;\n $this->contentTypeActionDispatcher = $contentTypeActionDispatcher;\n $this->formFactory = $formFactory;\n $this->submitHandler = $submitHandler;\n $this->userService = $userService;\n $this->languageService = $languageService;\n $this->contentTypeFormFactory = $contentTypeFormFactory;\n $this->contentTypeDraftMapper = $contentTypeDraftMapper;\n $this->configResolver = $configResolver;\n $this->fieldTypeToolbarFactory = $fieldTypeToolbarFactory;\n $this->metaFieldDefinitionService = $metaFieldDefinitionService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function createInstanceFrom(\n Affectation $affectation,\n InterventionType $type,\n \\DateTimeImmutable $scheduledAt,\n \\DateTimeImmutable $registeredAt,\n string $status,\n ?string $providerName = null,\n ?int $providerId = null,\n ?string $doneBy = null,\n ?string $details = null,\n ?array $additionalInformation = null,\n ): Intervention {\n return (new Intervention())\n ->setPartner($affectation->getPartner())\n ->setSignalement($affectation->getSignalement())\n ->setType($type)\n ->setScheduledAt($scheduledAt)\n ->setRegisteredAt($registeredAt)\n ->setStatus($status)\n ->setProviderName($providerName)\n ->setProviderId($providerId)\n ->setDoneBy($doneBy)\n ->setDetails($details)\n ->setAdditionalInformation($additionalInformation)\n ;\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function __construct(\n ?array $communes,\n ?string $statut,\n array $etiquettes,\n ?string $type,\n ?\\DateTime $dateStart,\n ?\\DateTime $dateEnd,\n bool $countRefused,\n bool $countArchived,\n ?Territory $territory,\n ?Partner $partner,\n ) {\n $this->communes = $communes;\n $this->statut = $statut;\n $this->etiquettes = $etiquettes;\n $this->type = $type;\n $this->dateStart = $dateStart;\n $this->dateEnd = $dateEnd;\n $this->countRefused = $countRefused;\n $this->countArchived = $countArchived;\n $this->territory = $territory;\n $this->partner = $partner;\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "protected function get_unique_filename($file_path, $name, $subfolder, $size, $type, $error,\n $index, $content_range) {\n\n if($this->options['unique_filename']){ //Artem Osmakov assign uniqie name to uploaded file\n\n while(is_dir($this->get_upload_path($name, $subfolder))) {\n $name = $this->upcount_name($name);//unique name for subfolder\n }\n // Keep an existing filename if this is part of a chunked upload:\n $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]);\n while(is_file($this->get_upload_path($name, $subfolder))) { //till: is file and exists\n if ($uploaded_bytes === $this->get_file_size(\n $this->get_upload_path($name, $subfolder))) {\n break;\n }\n $name = $this->upcount_name($name);//get name with counter\n }\n\n }\n\n return $name;\n }", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function PDF_add_note($pdfdoc, float $llx, float $lly, float $urx, float $ury, string $contents, string $title, string $icon, int $open): void\n{\n error_clear_last();\n $result = \\PDF_add_note($pdfdoc, $llx, $lly, $urx, $ury, $contents, $title, $icon, $open);\n if ($result === false) {\n throw PdfException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private static function validateResourcePointers($mysqli, $query, $imp_session,\n $fields_checked, $dt_id, $field_idx, $recStruc, $recordType, $progress_session_id){\n\n $dt_def = $recStruc[$recordType]['dtFields'][$dt_id];\n $idx_pointer_types = $recStruc['dtFieldNamesToIndex']['rst_PtrFilteredIDs'];\n\n $res = $mysqli->query($query);\n\n if($res){\n\n $cnt = 0;\n $tot_count = $imp_session['reccount']>0?$imp_session['reccount']:1000;\n if($tot_count>4000){\n mysql__update_progress(null, $progress_session_id, false, '0,'.$tot_count.','.MSG_VALIDATION_2);\n }\n\n $wrong_records = array();\n while ($row = $res->fetch_row()){\n\n $is_error = false;\n $newvalue = array();\n $values = self::getMultiValues($row[$field_idx], $imp_session['csv_enclosure'], $imp_session['csv_mvsep']);\n foreach($values as $idx=>$r_value){\n $r_value2 = super_trim($r_value);\n if(!($r_value2=='' || $r_value2=='NULL' || $r_value2<0)){ // && $r_value2>0\n\n if (!VerifyValue::isValidPointer($dt_def[$idx_pointer_types], $r_value2 ))\n {//not found\n $is_error = true;\n array_push($newvalue, \"$r_value\");\n }else{\n array_push($newvalue, $r_value);\n }\n }\n }\n\n if($is_error){\n $row[$field_idx] = implode($imp_session['csv_mvsep'], $newvalue);\n array_push($wrong_records, $row);\n }\n\n $cnt++;\n if($tot_count>4000 && $cnt%2000==0){\n mysql__update_progress(null, $progress_session_id, false, $cnt.','.$tot_count.','.MSG_VALIDATION_2);\n }\n }\n $res->close();\n $cnt_error = count($wrong_records);\n if($cnt_error>0){\n $error = array();\n $error[\"count_error\"] = $cnt_error;\n $error[\"recs_error\"] = array_slice($wrong_records,0,1000);\n $error[\"field_checked\"] = $fields_checked;\n $error[\"err_message\"] = \"Record pointer fields must reference an existing record of valid type in the database\";\n $error[\"short_message\"] = \"Invalid Pointers\";\n\n $imp_session['validation']['count_error'] = $imp_session['validation']['count_error']+$cnt_error;\n array_push($imp_session['validation']['error'], $error);\n\n return $imp_session;\n }\n\n }else{\n return ERR_VALIDATION_QUERY.$query;\n }\n return null;\n}", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function multiple_code_set_search(array $form_code_types = null, $search_term, $limit = null, $modes = null, $count = false, $active = true, $start = null, $number = null, $filter_elements = array())\n{\n\n if (empty($form_code_types)) {\n // Collect the active code types\n $form_code_types = collect_codetypes(\"active\", \"array\");\n }\n\n if ($count) {\n //start the counter\n $counter = 0;\n } else {\n // Figure out the appropriate limit clause\n $limit_query = limit_query_string($limit, $start, $number);\n\n // Prepare the sql bind array\n $sql_bind_array = array();\n\n // Start the query string\n $query = \"SELECT * FROM ((\";\n }\n\n // Loop through each code type\n $flag_first = true;\n $flag_hit = false; //ensure there is a hit to avoid trying an empty query\n foreach ($form_code_types as $form_code_type) {\n // see if there is a hit\n $mode_hit = null;\n // only use the count method here, since it's much more efficient than doing the actual query\n $mode_hit = sequential_code_set_search($form_code_type, $search_term, null, $modes, true, $active, null, null, $filter_elements, true);\n if ($mode_hit) {\n if ($count) {\n // count the hits\n $count_hits = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit);\n // increment the counter\n $counter += $count_hits;\n } else {\n $flag_hit = true;\n // build the query\n $return_query = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit, true);\n if (!empty($sql_bind_array)) {\n $sql_bind_array = array_merge($sql_bind_array, $return_query['binds']);\n } else {\n $sql_bind_array = $return_query['binds'];\n }\n\n if (!$flag_first) {\n $query .= \") UNION ALL (\";\n }\n\n $query .= $return_query['query'];\n }\n\n $flag_first = false;\n }\n }\n\n if ($count) {\n //return the count\n return $counter;\n } else {\n // Finish the query string\n $query .= \")) as atari $limit_query\";\n\n // Process and return the query (if there was a hit)\n if ($flag_hit) {\n return sqlStatement($query, $sql_bind_array);\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function get_query_r($tree,&$select,&$pcount,$table,$field_l,$field_i,$id_field,$neg_parent=0,$main=1) {\n\n\t\t// Variable permettant de choisir si l'on utilise ou non la troncature droite du terme recherch\n\t\t$empty_word = get_empty_words();\n\t\t$troncat = \"\";\n\t\tif ($this->allow_term_troncat_search) {\n\t\t\t $troncat = \"%\";\n\t\t}\n\n\t\t$where=\"\";\n\t\tfor ($i=0; $ioperator)&&($tree[$i]->literal!=2)) $where.=$tree[$i]->operator.\" \";\n\t\t\tif ($tree[$i]->sub==null) {\n\t\t\t\tif ($tree[$i]->literal) $clause=\"trim(\".$field_l.\") \"; else $clause=$field_i.\" \";\n\t\t\t\tif ($tree[$i]->not) $clause.=\"not \";\n\t\t\t\t$clause.=\"like '\";\n\t\t\t\tif (!$tree[$i]->start_with) $clause.=\"%\";\n\t\t\t\tif (!$tree[$i]->literal) $clause.=\" \";\n\n\t\t\t\t// Condition permettant de dtecter si on a dj une toile dans le terme\n\t\t\t\t// Si la recherche avec troncature droite est activee dans l'administration\n\t\t\t\t// et qu'il n'y a pas d'toiles ajout du '%' droite du terme\n\t\t\t\tif(strpos($tree[$i]->word,\"*\") === false) {\n\t\t\t\t\t//Si c'est un mot vide, on ne troncature pas\n\t\t\t\t\tif (in_array($tree[$i]->word,$empty_word)===false) {\n\t\t\t\t\t\t$clause.=addslashes($tree[$i]->word.$troncat);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$clause.=addslashes($tree[$i]->word);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$clause.=addslashes(str_replace(\"*\",\"%\",$tree[$i]->word));\n\t\t\t\t}\n\n\t\t\t\tif (!$tree[$i]->literal) $clause.=\" \";\n\t\t\t\t$clause.=\"%'\";\n\t\t\t\tif($tree[$i]->literal!=2) $where.=$clause.\" \";\n\t\t\t\t//if ((!$tree[$i]->not)&&(!$neg_parent)) {\n\t\t\t\t\tif ($select) $select.=\"+\";\n\t\t\t\t\t$select.=\"(\".$clause.\")\";\n\t\t\t\t\tif ($tree[$i]->pound && ($tree[$i]->pound!=1)) $select.=\"*\".$tree[$i]->pound;\n\t\t\t\t\t$pcount++;\n\t\t\t\t//}\n\t\t\t} else {\n\t\t\t\tif ($tree[$i]->not) $where.=\"not \";\n\t\t\t\t//$tree[$i]->not\n\t\t\t\t$where.=\"( \".$this->get_query_r($tree[$i]->sub,$select,$pcount,$table,$field_l,$field_i,$id_field,$tree[$i]->not,0).\") \";\n\t\t\t}\n\t\t}\n\t\tif ($main) {\n\t\t\tif ($select==\"\") $select=\"1\";\n\t\t\tif ($where==\"\") $where=\"0\";\n\t\t\t$q=array();\n\t\t\t$q[\"select\"]=\"(\".$select.\")\";\n\t\t\t$q[\"where\"]=\"(\".$where.\")\";\n\t\t\t$q[\"post\"]=\" group by \".$id_field.\" order by pert desc,\".$field_i.\" asc\";\n\t\t\treturn $q;\n\t\t}\n\t\telse\n\t\t\treturn $where;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function choice_widget_collapsed($view, $form, $required, $placeholder, $placeholder_in_choices, $multiple,\n $value, $preferred_choices, $choices, $separator, $translation_domain,\n $formHelper, $translatorHelper)\n {\n ?>\n \n block($form, 'widget_attributes', array(\n 'required' => $required\n )) ?>\n multiple=\"multiple\"\n >\n \n 0): ?>\n block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?>\n 0 && null !== $separator): ?>\n \n \n \n block($form, 'choice_widget_options', array('choices' => $choices)) ?>\n \n query($sql);\n $connexion->bind(':reembo_tipdocid', $reembo_tipdocid);\n $connexion->bind(':reembo_tipdocOtro', $reembo_tipdocOtro);\n $connexion->bind(':reembo_proveeid', $reembo_proveeid);\n $connexion->bind(':reembo_proveerut', $reembo_proveerut);\n $connexion->bind(':reemboa_proveenom', $reemboa_proveenom);\n $connexion->bind(':reembo_servid', $reembo_servid);\n $connexion->bind(':reembo_servotro', $reembo_servotro);\n $connexion->bind(':reembo_montoto', $reembo_montoto);\n $connexion->bind(':reembo_montonet', $reembo_montonet);\n $connexion->bind(':reembo_impuest', $reembo_impuest);\n $connexion->bind(':reembo_fecemision', $reembo_fecemision);\n $connexion->bind(':reembo_ota', $reembo_ota);\n $connexion->bind(':reembo_numota', $reembo_numota);\n $connexion->bind(':reembo_cuentaid', $reembo_cuentaid);\n $connexion->bind(':reembo_cuenta', $reembo_cuenta);\n $connexion->bind(':reembo_proyectid', $reembo_proyectid);\n $connexion->bind(':reembo_proyecto', $reembo_proyecto);\n $connexion->bind(':reembo_curso', $reembo_curso);\n $connexion->bind(':reembo_otanombre', $reembo_otanombre);\n $connexion->bind(':reembo_cui', $reembo_cui);\n $connexion->bind(':reembo_respgast', $reembo_respgast);\n $connexion->bind(':reembo_observacion', $reembo_observacion);\n $connexion->bind(':reembo_mes', $reembo_mes);\n $connexion->bind(':reembo_anual', $reembo_anual);\n $connexion->bind(':reembo_status', $reembo_status);\n $connexion->bind(':hoy', $hoy);\n $connexion->bind(':reembo_cuenta_nombre', $reembo_cuenta_nombre);\n $connexion->bind(':id', $id);\n $connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function getHtmlForDataManipulationStatements(\n TrackedData $trackedData,\n array $filterUsers,\n array $urlParams,\n int $ddlogCount,\n string $dropImageOrText,\n string $version,\n DateTimeImmutable $dateFrom,\n DateTimeImmutable $dateTo,\n ): string {\n // no need for the second returned parameter\n [$html] = $this->getHtmlForDataStatements(\n $trackedData->dmlog,\n $filterUsers,\n $urlParams,\n $dropImageOrText,\n TrackedDataType::DML,\n $ddlogCount,\n $version,\n $dateFrom,\n $dateTo,\n );\n\n return $html;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function __construct(\n int $depth,\n int $locationId,\n int $contentId,\n int $versionNo,\n string $name,\n string $contentTypeIdentifier,\n bool $isContainer,\n bool $isInvisible,\n int $displayLimit,\n int $totalChildrenCount,\n int $reverseRelationsCount,\n bool $isBookmarked,\n string $mainLanguageCode,\n array $children = [],\n string $pathString = ''\n ) {\n $this->depth = $depth;\n $this->locationId = $locationId;\n $this->contentId = $contentId;\n $this->versionNo = $versionNo;\n $this->name = $name;\n $this->isInvisible = $isInvisible;\n $this->contentTypeIdentifier = $contentTypeIdentifier;\n $this->isContainer = $isContainer;\n $this->totalChildrenCount = $totalChildrenCount;\n $this->displayLimit = $displayLimit;\n $this->reverseRelationsCount = $reverseRelationsCount;\n $this->isBookmarked = $isBookmarked;\n $this->children = $children;\n $this->pathString = $pathString;\n $this->mainLanguageCode = $mainLanguageCode;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n\t\t?string $inNomeAluno = null,\n\t\t?string $inNomeMae = null,\n\t\t?string $inNomePai = null,\n\t\t?string $inNomeSocial = null,\n\t\t?string $inNomeAfetivo = null,\n\t\t?string $inDataNascimento = null,\n\t\t?string $inCorRaca = null,\n\t\t?string $inSexo = null,\n\t\t?string $inBolsaFamilia = null,\n\t\t?string $inQuilombola = null,\n\t\t?string $inPossuiInternet = null,\n\t\t?string $inPossuiNotebookSmartphoneTablet = null,\n\t\t?string $inTipoSanguineo = null,\n\t\t?string $inDoadorOrgaos = null,\n\t\t?string $inNumeroCNS = null,\n\t\t?string $inEmail = null,\n\t\t?string $inNacionalidade = null,\n\t\t?string $inNomeMunNascto = null,\n\t\t?string $inUFMunNascto = null,\n\t\t?string $inCodMunNasctoDNE = null,\n\t\t?string $inDataEntradaPais = null,\n\t\t?string $inCodPaisOrigem = null,\n\t\t?string $inPaisOrigem = null\n\t) {\n\t\t$this->inNomeAluno = $inNomeAluno;\n\t\t$this->inNomeMae = $inNomeMae;\n\t\t$this->inNomePai = $inNomePai;\n\t\t$this->inNomeSocial = $inNomeSocial;\n\t\t$this->inNomeAfetivo = $inNomeAfetivo;\n\t\t$this->inDataNascimento = $inDataNascimento;\n\t\t$this->inCorRaca = $inCorRaca;\n\t\t$this->inSexo = $inSexo;\n\t\t$this->inBolsaFamilia = $inBolsaFamilia;\n\t\t$this->inQuilombola = $inQuilombola;\n\t\t$this->inPossuiInternet = $inPossuiInternet;\n\t\t$this->inPossuiNotebookSmartphoneTablet = $inPossuiNotebookSmartphoneTablet;\n\t\t$this->inTipoSanguineo = $inTipoSanguineo;\n\t\t$this->inDoadorOrgaos = $inDoadorOrgaos;\n\t\t$this->inNumeroCNS = $inNumeroCNS;\n\t\t$this->inEmail = $inEmail;\n\t\t$this->inNacionalidade = $inNacionalidade;\n\t\t$this->inNomeMunNascto = $inNomeMunNascto;\n\t\t$this->inUFMunNascto = $inUFMunNascto;\n\t\t$this->inCodMunNasctoDNE = $inCodMunNasctoDNE;\n\t\t$this->inDataEntradaPais = $inDataEntradaPais;\n\t\t$this->inCodPaisOrigem = $inCodPaisOrigem;\n\t\t$this->inPaisOrigem = $inPaisOrigem;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function (array $resources, string $projectId, Response $response, Database $dbForProject, Database $dbForConsole, Document $project, Document $user, Event $events, Request $request) {\n $firebase = new OAuth2Firebase(\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),\n $request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'\n );\n\n $identity = $dbForConsole->findOne('identities', [\n Query::equal('provider', ['firebase']),\n Query::equal('userInternalId', [$user->getInternalId()]),\n ]);\n if ($identity === false || $identity->isEmpty()) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $accessToken = $identity->getAttribute('providerAccessToken');\n $refreshToken = $identity->getAttribute('providerRefreshToken');\n $accessTokenExpiry = $identity->getAttribute('providerAccessTokenExpiry');\n\n $isExpired = new \\DateTime($accessTokenExpiry) < new \\DateTime('now');\n if ($isExpired) {\n $firebase->refreshTokens($refreshToken);\n\n $accessToken = $firebase->getAccessToken('');\n $refreshToken = $firebase->getRefreshToken('');\n\n $verificationId = $firebase->getUserID($accessToken);\n\n if (empty($verificationId)) {\n throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED, 'Another request is currently refreshing OAuth token. Please try again.');\n }\n\n $identity = $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$firebase->getAccessTokenExpiry('')));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n }\n\n if ($identity->getAttribute('secrets')) {\n $serviceAccount = $identity->getAttribute('secrets');\n } else {\n $firebase->cleanupServiceAccounts($accessToken, $projectId);\n $serviceAccount = $firebase->createServiceAccount($accessToken, $projectId);\n $identity = $identity\n ->setAttribute('secrets', json_encode($serviceAccount));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n }\n\n $migration = $dbForProject->createDocument('migrations', new Document([\n '$id' => ID::unique(),\n 'status' => 'pending',\n 'stage' => 'init',\n 'source' => Firebase::getName(),\n 'credentials' => [\n 'serviceAccount' => json_encode($serviceAccount),\n ],\n 'resources' => $resources,\n 'statusCounters' => '{}',\n 'resourceData' => '{}',\n 'errors' => []\n ]));\n\n $events->setParam('migrationId', $migration->getId());\n\n // Trigger Transfer\n $event = new Migration();\n $event\n ->setMigration($migration)\n ->setProject($project)\n ->setUser($user)\n ->trigger();\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($migration, Response::MODEL_MIGRATION);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function addGeogebraJava($url,$width=400,$height=200,$commands=array(),$params=array(),$callback=null,$qn=null,$part=null) {\n\tif (!isset($GLOBALS['geogebracount'])) {\n\t\t$GLOBALS['geogebracount'] = 0;\n\t}\n\tif (!isset($params['framePossible'])) {\n\t\t$params['framePossible'] = 'false';\n\t}\n\t$params['ggbOnInitParam'] = $GLOBALS['geogebracount'];\n\t$out = ' ';\n\tif ($url != '') {\n\t\t$out .= '';\n\t}\n\tforeach ($params as $k=>$v) {\n\t\t$out .= \"\";\n\t}\n\t$out .= 'Please install Java 1.4.2 (or later) to use this page.';\n\t$out .= '';\n\n\tif (count($commands)>0) {\n\t\t$out .= '';\n\t}\n\tif ($callback!=null & $qn != null) {\n\t\tif ($part !== null) {$qn = 1000*($qn)+$part;} else {$qn--;}\n\n\t\t$out .= '';\n\t}\n\t$GLOBALS['geogebracount']++;\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function documents_search(\n\t\t\t$query,\n\t\t\t$documentBase = europresse_client::DOCUMENTBASE_DEFAULT,\n\t\t\t$domainId = europresse_client::DOMAINID_DEFAULT,\n\t\t\t$includes = europresse_client::INCLUDES_DEFAULT,\n\t\t\t$excludes = europresse_client::EXCLUDES_DEFAULT,\n\t\t\t$maxCount = europresse_client::MAXCOUNT_DEFAULT,\n\t\t\t$docUrl = europresse_client::DOCURL_DEFAULT,\n\t\t\t$dateRange = europresse_client::DATERANGE_DEFAULT,\n\t\t\t$startDate = europresse_client::STARTDATE_DEFAULT,\n\t\t\t$endDate = europresse_client::ENDDATE_DEFAULT,\n\t\t\t$fields = europresse_client::FIELDS_DEFAULT,\n\t\t\t$sort = europresse_client::SORT_DEFAULT, \n\t\t\t$CsLanguage = europresse_client::CSLANGUAGE_DEFAULT\n\t\t\t) {\n\t\t\t\t\n\t\t\t$this->reset_errors();\n\t\t\t$this->reset_result();\n\t\t\t\n\t\t\tif($this->access_token == '') {\n\t\t\t\t$this->auth_login();\n\t\t\t}\n\t\t\tif($this->error) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tif(!in_array($CsLanguage, europresse_client::CSLANGUAGE_AVAILABLE_VALUES)) {\n\t\t\t\t$CsLanguage = europresse_client::CSLANGUAGE_DEFAULT;\n\t\t\t}\n\t\t\t\n\t\t\t$this->curl_method = 'get';\n\t\t\t$this->curl_url = $this->ws_url.europresse_client::DOCUMENTS_SEARCH_PATH;\n\t\t\t$this->curl_headers = europresse_client::DEFAULT_HEADERS;\n\t\t\t$this->curl_headers[europresse_client::DEFAULT_AUTHORIZATION_HEADER_KEY] = europresse_client::DEFAULT_AUTHORIZATION_HEADER_PREFIX.$this->access_token;\n\t\t\t$this->curl_headers[europresse_client::CSLANGUAGE_HEADER] = $CsLanguage;\n\t\t\t$this->curl_params = [\n\t\t\t\t\t'query' \t\t=> $query,\n\t\t\t\t\t'documentBase'\t=> $documentBase,\n\t\t\t\t\t'domainId'\t\t=> $domainId,\n\t\t\t\t\t'includes'\t\t=> $includes,\n\t\t\t\t\t'excludes'\t\t=> $excludes,\n\t\t\t\t\t'maxCount'\t\t=> $maxCount,\n\t\t\t\t\t'docUrl'\t\t=> $docUrl,\n\t\t\t\t\t'dateRange'\t\t=> $dateRange,\n\t\t\t\t\t'startDate'\t\t=> $startDate,\n\t\t\t\t\t'endDate'\t\t=> $endDate,\n\t\t\t\t\t'fields'\t\t=> $fields,\n\t\t\t\t\t'sort'\t\t\t=> $sort,\n\t\t\t];\n\t\t\t\n\t\t\t$this->send_request();\n\t\t\t\n\t\t\tif($this->error) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t$response_body = json_decode($this->curl_response->body, true);\n\t\t\t$this->auth_logout();\n\t\t\tif( is_null($response_body) || empty($response_body) ) {\n\t\t\t\t$this->error = true;\n\t\t\t\t$this->error_msg[] = 'search => json response error';\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t$this->result = $response_body;\n\t\t\treturn true;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct(\n Pdf $diagram,\n string $db,\n string $tableName,\n int|null $fontSize,\n int $pageNumber,\n bool $showKeys = false,\n bool $tableDimension = false,\n bool $offline = false,\n ) {\n parent::__construct($diagram, $db, $pageNumber, $tableName, $showKeys, $tableDimension, $offline);\n\n $this->heightCell = 6;\n $this->setHeight();\n // setWidth must be after setHeight, because title can include table height which changes table width\n $this->setWidth($fontSize);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "private static function getValueForObject(Concrete $object, string $key, string $brickType = null, string $brickKey = null, ClassDefinition\\Data $fieldDefinition = null, array $context = [], array $brickDescriptor = null, string $requestedLanguage = null): \\stdClass\n {\n $getter = 'get' . ucfirst($key);\n $value = null;\n\n try {\n $value = $object->$getter($requestedLanguage ?? AdminTool::getCurrentUser()?->getLanguage());\n } catch (\\Throwable) {\n }\n\n if (empty($value)) {\n $value = $object->$getter();\n }\n if (!empty($value) && !empty($brickType)) {\n $getBrickType = 'get' . ucfirst($brickType);\n $value = $value->$getBrickType();\n if (!empty($value) && !empty($brickKey)) {\n if ($brickDescriptor) {\n $innerContainer = $brickDescriptor['innerContainer'] ?? 'localizedfields';\n $localizedFields = $value->{'get' . ucfirst($innerContainer)}();\n $brickDefinition = Model\\DataObject\\Objectbrick\\Definition::getByKey($brickType);\n /** @var Model\\DataObject\\ClassDefinition\\Data\\Localizedfields $fieldDefinitionLocalizedFields */\n $fieldDefinitionLocalizedFields = $brickDefinition->getFieldDefinition('localizedfields');\n $fieldDefinition = $fieldDefinitionLocalizedFields->getFieldDefinition($brickKey);\n $value = $localizedFields->getLocalizedValue($brickDescriptor['brickfield']);\n } else {\n $brickFieldGetter = 'get' . ucfirst($brickKey);\n $value = $value->$brickFieldGetter();\n }\n }\n }\n\n if (!$fieldDefinition) {\n $fieldDefinition = $object->getClass()->getFieldDefinition($key, $context);\n }\n\n if (!empty($brickType) && !empty($brickKey) && !$brickDescriptor) {\n $brickClass = Objectbrick\\Definition::getByKey($brickType);\n $context = ['object' => $object, 'outerFieldname' => $key];\n $fieldDefinition = $brickClass->getFieldDefinition($brickKey, $context);\n }\n\n if ($fieldDefinition->isEmpty($value) && $fieldDefinition->supportsInheritance()) {\n $parent = Service::hasInheritableParentObject($object);\n if (!empty($parent)) {\n return self::getValueForObject($parent, $key, $brickType, $brickKey, $fieldDefinition, $context, $brickDescriptor);\n }\n }\n\n $result = new \\stdClass();\n $result->value = $value;\n $result->objectid = $object->getId();\n\n return $result;\n }", "smellKey": "S107", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function creerDossierIBTrackingKlsa($ref_dos, $id_cli, $t1, $poids, \n\t\t\t\t\t\t\t\t\t\t$ref_fact, $horse, $trailer_1, $trailer_2, \n\t\t\t\t\t\t\t\t\t\t$transporteur, $destination, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$arrival_date, $crossing_date, $wiski_arriv, \n\t\t\t\t\t\t\t\t\t\t$wiski_dep, $remarque, $id_util, $id_mod_lic, \n\t\t\t\t\t\t\t\t\t\t$num_lic){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['t1'] = $t1; \n\t\t\t$entree['poids'] = $poids; $entree['ref_fact'] = $ref_fact; $entree['horse'] = $horse; \n\t\t\t$entree['trailer_1'] = $trailer_1; $entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['transporteur'] = $transporteur; $entree['destination'] = $destination; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['arrival_date'] = $arrival_date;\n\t\t\t$entree['crossing_date'] = $crossing_date;$entree['wiski_arriv'] = $wiski_arriv;\n\t\t\t$entree['wiski_dep'] = $wiski_dep;$entree['remarque'] = $remarque;\n\t\t\t$entree['id_util'] = $id_util; $entree['id_mod_lic'] = $id_mod_lic; \n\t\t\t$entree['num_lic'] = $num_lic;\n\n\t\t\tif($entree['arrival_date'] == '' || (strlen($entree['arrival_date']) != 10) ){\n\t\t\t\t$entree['arrival_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['crossing_date'] == '' || (strlen($entree['crossing_date']) != 10) ){\n\t\t\t\t$entree['crossing_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_arriv'] == '' || (strlen($entree['wiski_arriv']) != 10) ){\n\t\t\t\t$entree['wiski_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_dep'] == '' || (strlen($entree['wiski_dep']) != 10) ){\n\t\t\t\t$entree['wiski_dep'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, t1, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_fact, horse, trailer_1, trailer_2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransporteur, destination, id_mod_trans, arrival_date,crossing_date, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twiski_arriv, wiski_dep, remarque, id_util, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, num_lic)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['t1'], \n\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['ref_fact'], $entree['horse'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_1'], $entree['trailer_2'], $entree['transporteur'], \n\t\t\t\t\t\t\t\t\t$entree['destination'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['arrival_date'], $entree['crossing_date'], $entree['wiski_arriv'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_dep'], $entree['remarque'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['num_lic']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public static function forever($name, $value, $path = null, $domain = null, $secure = false, $httpOnly = true, $raw = false, $sameSite = null)\n {\n return \\Illuminate\\Cookie\\CookieJar::forever($name, $value, $path, $domain, $secure, $httpOnly, $raw, $sameSite);\n }", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function (string $functionId, ?string $entrypoint, ?string $commands, mixed $code, mixed $activate, Request $request, Response $response, Database $dbForProject, Event $events, Document $project, Device $deviceFunctions, Device $deviceLocal) {\n $activate = filter_var($activate, FILTER_VALIDATE_BOOLEAN);\n\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n if ($entrypoint === null) {\n $entrypoint = $function->getAttribute('entrypoint', '');\n }\n\n if ($commands === null) {\n $commands = $function->getAttribute('commands', '');\n }\n\n if (empty($entrypoint)) {\n throw new Exception(Exception::FUNCTION_ENTRYPOINT_MISSING);\n }\n\n $file = $request->getFiles('code');\n\n // GraphQL multipart spec adds files with index keys\n if (empty($file)) {\n $file = $request->getFiles(0);\n }\n\n if (empty($file)) {\n throw new Exception(Exception::STORAGE_FILE_EMPTY, 'No file sent');\n }\n\n $fileExt = new FileExt([FileExt::TYPE_GZIP]);\n $fileSizeValidator = new FileSize(App::getEnv('_APP_FUNCTIONS_SIZE_LIMIT', 0));\n $upload = new Upload();\n\n // Make sure we handle a single file and multiple files the same way\n $fileName = (\\is_array($file['name']) && isset($file['name'][0])) ? $file['name'][0] : $file['name'];\n $fileTmpName = (\\is_array($file['tmp_name']) && isset($file['tmp_name'][0])) ? $file['tmp_name'][0] : $file['tmp_name'];\n $fileSize = (\\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size'];\n\n if (!$fileExt->isValid($file['name'])) { // Check if file type is allowed\n throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED);\n }\n\n $contentRange = $request->getHeader('content-range');\n $deploymentId = ID::unique();\n $chunk = 1;\n $chunks = 1;\n\n if (!empty($contentRange)) {\n $start = $request->getContentRangeStart();\n $end = $request->getContentRangeEnd();\n $fileSize = $request->getContentRangeSize();\n $deploymentId = $request->getHeader('x-appwrite-id', $deploymentId);\n // TODO make `end >= $fileSize` in next breaking version\n if (is_null($start) || is_null($end) || is_null($fileSize) || $end > $fileSize) {\n throw new Exception(Exception::STORAGE_INVALID_CONTENT_RANGE);\n }\n\n // TODO remove the condition that checks `$end === $fileSize` in next breaking version\n if ($end === $fileSize - 1 || $end === $fileSize) {\n //if it's a last chunks the chunk size might differ, so we set the $chunks and $chunk to notify it's last chunk\n $chunks = $chunk = -1;\n } else {\n // Calculate total number of chunks based on the chunk size i.e ($rangeEnd - $rangeStart)\n $chunks = (int) ceil($fileSize / ($end + 1 - $start));\n $chunk = (int) ($start / ($end + 1 - $start)) + 1;\n }\n }\n\n if (!$fileSizeValidator->isValid($fileSize)) { // Check if file size is exceeding allowed limit\n throw new Exception(Exception::STORAGE_INVALID_FILE_SIZE);\n }\n\n if (!$upload->isValid($fileTmpName)) {\n throw new Exception(Exception::STORAGE_INVALID_FILE);\n }\n\n // Save to storage\n $fileSize ??= $deviceLocal->getFileSize($fileTmpName);\n $path = $deviceFunctions->getPath($deploymentId . '.' . \\pathinfo($fileName, PATHINFO_EXTENSION));\n $deployment = $dbForProject->getDocument('deployments', $deploymentId);\n\n $metadata = ['content_type' => $deviceLocal->getFileMimeType($fileTmpName)];\n if (!$deployment->isEmpty()) {\n $chunks = $deployment->getAttribute('chunksTotal', 1);\n $metadata = $deployment->getAttribute('metadata', []);\n if ($chunk === -1) {\n $chunk = $chunks;\n }\n }\n\n $chunksUploaded = $deviceFunctions->upload($fileTmpName, $path, $chunk, $chunks, $metadata);\n\n if (empty($chunksUploaded)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed moving file');\n }\n\n $activate = (bool) filter_var($activate, FILTER_VALIDATE_BOOLEAN);\n\n if ($chunksUploaded === $chunks) {\n if ($activate) {\n // Remove deploy for all other deployments.\n $activeDeployments = $dbForProject->find('deployments', [\n Query::equal('activate', [true]),\n Query::equal('resourceId', [$functionId]),\n Query::equal('resourceType', ['functions'])\n ]);\n\n foreach ($activeDeployments as $activeDeployment) {\n $activeDeployment->setAttribute('activate', false);\n $dbForProject->updateDocument('deployments', $activeDeployment->getId(), $activeDeployment);\n }\n }\n\n $fileSize = $deviceFunctions->getFileSize($path);\n\n if ($deployment->isEmpty()) {\n $deployment = $dbForProject->createDocument('deployments', new Document([\n '$id' => $deploymentId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'resourceInternalId' => $function->getInternalId(),\n 'resourceId' => $function->getId(),\n 'resourceType' => 'functions',\n 'buildInternalId' => '',\n 'entrypoint' => $entrypoint,\n 'commands' => $commands,\n 'path' => $path,\n 'size' => $fileSize,\n 'search' => implode(' ', [$deploymentId, $entrypoint]),\n 'activate' => $activate,\n 'metadata' => $metadata,\n 'type' => 'manual'\n ]));\n } else {\n $deployment = $dbForProject->updateDocument('deployments', $deploymentId, $deployment->setAttribute('size', $fileSize)->setAttribute('metadata', $metadata));\n }\n\n // Start the build\n $buildEvent = new Build();\n $buildEvent\n ->setType(BUILD_TYPE_DEPLOYMENT)\n ->setResource($function)\n ->setDeployment($deployment)\n ->setProject($project)\n ->trigger();\n } else {\n if ($deployment->isEmpty()) {\n $deployment = $dbForProject->createDocument('deployments', new Document([\n '$id' => $deploymentId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'resourceInternalId' => $function->getInternalId(),\n 'resourceId' => $function->getId(),\n 'resourceType' => 'functions',\n 'buildInternalId' => '',\n 'entrypoint' => $entrypoint,\n 'commands' => $commands,\n 'path' => $path,\n 'size' => $fileSize,\n 'chunksTotal' => $chunks,\n 'chunksUploaded' => $chunksUploaded,\n 'search' => implode(' ', [$deploymentId, $entrypoint]),\n 'activate' => $activate,\n 'metadata' => $metadata,\n 'type' => 'manual'\n ]));\n } else {\n $deployment = $dbForProject->updateDocument('deployments', $deploymentId, $deployment->setAttribute('chunksUploaded', $chunksUploaded)->setAttribute('metadata', $metadata));\n }\n }\n\n $metadata = null;\n\n $events\n ->setParam('functionId', $function->getId())\n ->setParam('deploymentId', $deployment->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($deployment, Response::MODEL_DEPLOYMENT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = '', $list = true, $optiondates = 0,\n\t\t\t\t $optioncount = 0, $hide_empty = 1, $use_desc_for_title = 1, $children=false, $child_of=0, $categories=0,\n\t\t\t\t $recurse=0, $feed = '', $feed_image = '', $exclude = '', $hierarchical=false) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'wp_list_categories()' );\n\n\t$query = compact('optionall', 'all', 'sort_column', 'sort_order', 'file', 'list', 'optiondates', 'optioncount', 'hide_empty', 'use_desc_for_title', 'children',\n\t\t'child_of', 'categories', 'recurse', 'feed', 'feed_image', 'exclude', 'hierarchical');\n\treturn wp_list_cats($query);\n}", "smellKey": "S107", "smellId": null, "repo": "jpbarraca_sqli-wordpress", "language": "php"} {"function": "public static function getUser(\n $username,\n $password,\n $firstName,\n $middleName,\n $lastName,\n array $acls = null,\n $primaryRole = null,\n $email = null,\n $organizationId = null,\n $personId = null\n ) {\n $acls = isset($acls) ? $acls : array(ROLE_ID_USER);\n $primaryRole = isset($primaryRole) ? $primaryRole : ROLE_ID_USER;\n $emailAddress = isset($email) ? $email : \"$username\" . self::DEFAULT_EMAIL_ADDRESS_SUFFIX;\n\n return new XDUser($username, $password, $emailAddress, $firstName, $middleName, $lastName, $acls, $primaryRole, $organizationId, $personId);\n }", "smellKey": "S107", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected function update_content_into_entrepot($source_id, $ref, $ufield, $usubfield, $field_order, $subfield_order, $search_id = '', $value = '') {\n\t\t$query = \"update ignore entrepot_source_\".$source_id.\" \";\n\t\t$query.= \"set value = '\".addslashes($value).\"', i_value = '\".addslashes(strip_empty_words($value)).\"' \";\n\t\t$query.= \"where source_id = {$source_id} \";\n\t\t$query.= \"and ref ='\".addslashes($ref).\"' \";\n\t\t$query.= \"and ufield = '\".addslashes($ufield).\"' \";\n\t\t$query.= \"and usubfield = '\".addslashes($usubfield).\"' \";\n\t\t$query.= \"and field_order = {$field_order} \";\n\t\t$query.= \"and subfield_order = {$subfield_order} \";\n\t\t$query.= \"and search_id = '{$search_id}' \";\n\t\t$query.= \"limit 1\";\n\t\tpmb_mysql_query($query);\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function thisLineItem(\n $patient_id,\n $encounter_id,\n $memo,\n $transdate,\n $rowmethod,\n $rowpayamount,\n $rowadjamount,\n $payer_type = 0,\n $irnumber = ''\n) {\n\n global $form_report_by, $insarray, $grandpaytotal, $grandadjtotal;\n\n if ($form_report_by != '1') { // reporting by method or check number\n showLineItem(\n $patient_id,\n $encounter_id,\n $memo,\n $transdate,\n $rowmethod,\n $rowpayamount,\n $rowadjamount,\n $payer_type,\n $irnumber\n );\n return;\n }\n\n // Reporting by payer.\n //\n if (!empty($_POST['form_details'])) { // details are wanted\n // Save everything for later sorting.\n $insarray[] = array(\n $patient_id,\n $encounter_id,\n $memo,\n $transdate,\n $rowmethod,\n $rowpayamount,\n $rowadjamount,\n $payer_type,\n $irnumber\n );\n } else { // details not wanted\n if (empty($insarray[$rowmethod])) {\n $insarray[$rowmethod] = array(0, 0);\n }\n\n $insarray[$rowmethod][0] += $rowpayamount;\n $insarray[$rowmethod][1] += $rowadjamount;\n $grandpaytotal += $rowpayamount;\n $grandadjtotal += $rowadjamount;\n }\n}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (string $userId, string $email, string $password, string $name, Response $response, Document $project, Database $dbForProject, Event $events) {\n $user = createUser('md5', '{}', $userId, $email, $password, null, $name, $project, $dbForProject, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct($notice,$create_link=0,$create_link_spec=0,$force_update=0,$id_thesaurus=0,$rejected=true,$associated=true,$parallel=false){\n\t\t$this->notice = $notice;\n\t\t$this->create_link = $create_link;\n\t\t$this->create_link_spec = $create_link_spec;\n\t\t$this->force_update = $force_update;\n\t\t$this->use_rejected = $rejected;\n\t\t$this->use_associated = $associated;\n\t\t$this->use_parallel = $parallel;\n\t\t$this->id_thesaurus = $id_thesaurus;\n\t\t$this->splitted = false;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct(\n ContentHandler $contentHandler,\n ContentTypeHandler $contentTypeHandler,\n LanguageHandler $languageHandler,\n LocationHandler $locationHandler,\n ObjectStateHandler $objectStateHandler,\n SectionHandler $sectionHandler,\n SPITransactionHandler $transactionHandler,\n TrashHandler $trashHandler,\n UrlAliasHandler $urlAliasHandler,\n UrlWildcardHandler $urlWildcardHandler,\n UserHandler $userHandler,\n UrlHandler $urlHandler,\n BookmarkHandler $bookmarkHandler,\n NotificationHandler $notificationHandler,\n UserPreferenceHandler $userPreferenceHandler,\n SettingHandler $settingHandler\n ) {\n $this->contentHandler = $contentHandler;\n $this->contentTypeHandler = $contentTypeHandler;\n $this->languageHandler = $languageHandler;\n $this->locationHandler = $locationHandler;\n $this->objectStateHandler = $objectStateHandler;\n $this->sectionHandler = $sectionHandler;\n $this->transactionHandler = $transactionHandler;\n $this->trashHandler = $trashHandler;\n $this->urlAliasHandler = $urlAliasHandler;\n $this->urlWildcardHandler = $urlWildcardHandler;\n $this->userHandler = $userHandler;\n $this->urlHandler = $urlHandler;\n $this->bookmarkHandler = $bookmarkHandler;\n $this->notificationHandler = $notificationHandler;\n $this->userPreferenceHandler = $userPreferenceHandler;\n $this->settingHandler = $settingHandler;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function ajoutEleve($nom, $prenom, $sexe, $date_naissance, $tel_enfant, $email_enfant,$responsable_legal,$tel_parent,$tel_parent2,$tel_parent3, $profession_pere,$adresse,$profession_mere,$ville, $email_parent,$prevenir_parent,$commentaires,$cp,$codebarre)\n\t{\t\t\t\n\t\t$req = \"INSERT INTO `eleves` VALUES ('', '\".strtoupper($nom).\"', '\".ucfirst($prenom).\"', '$sexe', '$date_naissance', '$responsable_legal', $prevenir_parent, '$profession_pere', '$profession_mere', '\".strtoupper($adresse).\"', '\".strtoupper($cp).\"', '\".strtoupper($ville).\"', '$tel_parent', '$tel_parent2', '$tel_parent3', '$tel_enfant', '$email_parent', '$email_enfant', NULL, NULL, '$commentaires', '', '', '', '$codebarre', 1, 1);\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'\u00e9l\u00e8ve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function DatosImparticiones_SumaHoras($id_curso, $id_inscripcion, $tipo_horario, $fecha_inicio, $fecha_termino, $hora_inicio, $hora_termino, $modalidad, $numero_horas)\n\t{\n\t\t$suma_tiempo = 0;\n\t\tif ($tipo_horario == \"fecha_sesiones\") {\n\t\t\t$InscripcionCursoSesiones = DatosImparticiones_Sesiones_data_2021($id_inscripcion);\n\t\t\tforeach ($InscripcionCursoSesiones as $ses) {\n\t\t\t\t$tiempo = TiempoTranscurrido_Full_2021($ses->hora_desde, $ses->hora_hasta);\n\t\t\t\tif ($tiempo > 0) {\n\t\t\t\t\t$suma_tiempo = $suma_tiempo + $tiempo;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$numero_horas_imparticiones = $suma_tiempo;\n\t\t\t$numero_horas_minutos = round(60 * $numero_horas);\n\t\t}\n\t\telse {\n\t\t\tif ($fecha_inicio == $fecha_termino) {\n\t\t\t\t$tiempo = TiempoTranscurrido_Full_2021($hora_inicio, $hora_termino);\n\t\t\t\tif ($tiempo > 0) {\n\t\t\t\t\t$suma_tiempo = $suma_tiempo + $tiempo;\n\t\t\t\t}\n\t\t\t\t$numero_horas_imparticiones = $suma_tiempo;\n\t\t\t\t$numero_horas_minutos = round(60 * $numero_horas);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$numero_horas_imparticiones = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ($numero_horas > 0) {\n\t\t\tif ($modalidad == \"2\") {\n\t\t\t\tif ($numero_horas_minutos > $numero_horas_imparticiones and $numero_horas_imparticiones > 0) {\n\t\t\t\t\t$diferencia_minutos = $numero_horas_minutos - $numero_horas_imparticiones;\n\t\t\t\t\t$alerta_curso .= \"
    Horas de Curso: $numero_horas hora(s). Faltan $diferencia_minutos minutos en las sesiones creadas.

    \";\n\t\t\t\t}\n\t\t\t\telseif ($numero_horas_minutos < $numero_horas_imparticiones and $numero_horas_imparticiones > 0) {\n\t\t\t\t\t$diferencia_minutos = $numero_horas_imparticiones - $numero_horas_minutos;\n\t\t\t\t\t$alerta_curso .= \"
    Horas de Curso: $numero_horas hora(s). Sobran $diferencia_minutos minutos en las sesiones creadas.

    \";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$alerta_curso .= \"
    Horas de Curso: $numero_horas hora(s)

    \";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$alerta_curso .= \"
    Horas de Curso: $numero_horas hora(s)

    \";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// no muestra horas del curso\n\t\t\t$alerta_curso .= \"
    El curso no tiene definida horas

    \";\n\t\t}\n\t\t\n\t\treturn $alerta_curso;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function (string $projectId, string $type, string $name, string $key, string $store, string $hostname, Response $response, Database $dbForConsole) {\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $platform = new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'projectInternalId' => $project->getInternalId(),\n 'projectId' => $project->getId(),\n 'type' => $type,\n 'name' => $name,\n 'key' => $key,\n 'store' => $store,\n 'hostname' => $hostname\n ]);\n\n $platform = $dbForConsole->createDocument('platforms', $platform);\n\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($platform, Response::MODEL_PLATFORM);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function fin_iPMT(array $per,float $IY,float $Nper, float $PV, int $PY, int $CY, float $FV=0, int $type=0){\n if (count($per)!=2) {echo 'array size must be 2: cannot compute'; return '';}\n if ($CY<=0 or $PY<=0) { echo 'error: CY and PY must be positive'; return '';}\n if ($type!=0 && $type!=1) { echo 'error: type gets either 1 for annuity due (beginning) or 0 for general annuity (end)'; return '';}\n if ($IY<0) { echo 'error: IY cannot be negative'; return '';}\n $pmt=round(fin_PMT($IY,$Nper,$PV,$PY,$CY,$FV=0,$type=0),3);\n $i=$IY/($CY*100);\n $i2=((1+$i)**($CY/$PY))-1;\n\n $ipmt=array();\n $ipmt[0]=0;\n $ppmt=array();\n $ppmt[0]=0;\n $bal=abs($PV);\n $upto=$per[1];\n $intsum=array();\n $intsum[0]=0;\n $prnsum=array();\n $prnsum[0]=0;\n for ($j=1;$j<=$upto;$j++){\n $ipmt[$j]=round($bal*$i2,3);\n $intsum[$j]= round($intsum[$j-1]+$ipmt[$j],3);\n $ppmt[$j]=abs($pmt)-$ipmt[$j];\n $prnsum[$j]= round($prnsum[$j-1]+$ppmt[$j],3);\n $bal=round($bal-$ppmt[$j],3);\n }\n $k1=$per[0]-1;\n $k2=$per[1];\n $intpaid=$intsum[$k2]-$intsum[$k1];\n $prnpaid=$prnsum[$k2]-$prnsum[$k1];\n\n return $intpaid;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($name, PHPExcel_Chart_Title $title = null, PHPExcel_Chart_Legend $legend = null, PHPExcel_Chart_PlotArea $plotArea = null, $plotVisibleOnly = true, $displayBlanksAs = '0', PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, PHPExcel_Chart_Axis $xAxis = null, PHPExcel_Chart_Axis $yAxis = null, PHPExcel_Chart_GridLines $majorGridlines = null, PHPExcel_Chart_GridLines $minorGridlines = null)\n {\n $this->name = $name;\n $this->title = $title;\n $this->legend = $legend;\n $this->xAxisLabel = $xAxisLabel;\n $this->yAxisLabel = $yAxisLabel;\n $this->plotArea = $plotArea;\n $this->plotVisibleOnly = $plotVisibleOnly;\n $this->displayBlanksAs = $displayBlanksAs;\n $this->xAxis = $xAxis;\n $this->yAxis = $yAxis;\n $this->majorGridlines = $majorGridlines;\n $this->minorGridlines = $minorGridlines;\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function FormSelectMultiple($fieldname, $data, $multiple = 0, $size = 1, $selected = '', $accesskey = '', $disable = false, $readonly = false)\n {\n if (empty($fieldname)) {\n return;\n }\n\n $disable_text = \"\";\n if ($disable) {\n $disable_text = \" disabled \";\n }\n\n if ($readonly) {\n $disable_text = \" disabled \";\n }\n\n $this->tabindex++;\n\n // Set up selected if required\n if (!empty($selected)) {\n for ($i = 0; !empty($data[$i]); $i++) {\n if ($data[$i]['id'] == $selected) {\n $data[$i]['selected'] = 1;\n }\n }\n }\n\n $c = count($data);\n if ($c < $size) {\n $size = $c;\n }\n\n $output = '';\n if ($this->GetOutputMode() == _PNH_RETURNOUTPUT) {\n return $output;\n } else {\n $this->output .= $output;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function getBasicDD($i, $typeid, $parent, $itemid, $typename, $statsletter, $showstats, $name)\n{\n global $cid, $staticroot;\n $out = '
    ';\n $out .= '';\n $out .= ' \"'';\n $out .= '';\n $out .= '';\n $out .= '
    ';\n return $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?float $min, ?float $max, ?float $default, Response $response, Database $dbForProject, Event $events) {\n $attribute = updateAttribute(\n databaseId: $databaseId,\n collectionId: $collectionId,\n key: $key,\n dbForProject: $dbForProject,\n events: $events,\n type: Database::VAR_FLOAT,\n default: $default,\n required: $required,\n min: $min,\n max: $max\n );\n\n $formatOptions = $attribute->getAttribute('formatOptions', []);\n\n if (!empty($formatOptions)) {\n $attribute->setAttribute('min', \\floatval($formatOptions['min']));\n $attribute->setAttribute('max', \\floatval($formatOptions['max']));\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_FLOAT);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function transferIncomingShares(string $sourceUid,\n\t\tstring $destinationUid,\n\t\tarray $sourceShares,\n\t\tarray $destinationShares,\n\t\tOutputInterface $output,\n\t\tstring $path,\n\t\tstring $finalTarget,\n\t\tbool $move): void {\n\t\t$output->writeln(\"Restoring incoming shares ...\");\n\t\t$progress = new ProgressBar($output, count($sourceShares));\n\t\t$prefix = \"$destinationUid/files\";\n\t\t$finalShareTarget = '';\n\t\tif (str_starts_with($finalTarget, $prefix)) {\n\t\t\t$finalShareTarget = substr($finalTarget, strlen($prefix));\n\t\t}\n\t\tforeach ($sourceShares as $share) {\n\t\t\ttry {\n\t\t\t\t// Only restore if share is in given path.\n\t\t\t\t$pathToCheck = '/';\n\t\t\t\tif (trim($path, '/') !== '') {\n\t\t\t\t\t$pathToCheck = '/' . trim($path) . '/';\n\t\t\t\t}\n\t\t\t\tif (!str_starts_with($share->getTarget(), $pathToCheck)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t$shareTarget = $share->getTarget();\n\t\t\t\t$shareTarget = $finalShareTarget . $shareTarget;\n\t\t\t\tif ($share->getShareType() === IShare::TYPE_USER &&\n\t\t\t\t\t$share->getSharedBy() === $destinationUid) {\n\t\t\t\t\t$this->shareManager->deleteShare($share);\n\t\t\t\t} elseif (isset($destinationShares[$share->getNodeId()])) {\n\t\t\t\t\t$destinationShare = $destinationShares[$share->getNodeId()];\n\t\t\t\t\t// Keep the share which has the most permissions and discard the other one.\n\t\t\t\t\tif ($destinationShare->getPermissions() < $share->getPermissions()) {\n\t\t\t\t\t\t$this->shareManager->deleteShare($destinationShare);\n\t\t\t\t\t\t$share->setSharedWith($destinationUid);\n\t\t\t\t\t\t// trigger refetching of the node so that the new owner and mountpoint are taken into account\n\t\t\t\t\t\t// otherwise the checks on the share update will fail due to the original node not being available in the new user scope\n\t\t\t\t\t\t$this->userMountCache->clear();\n\t\t\t\t\t\t$share->setNodeId($share->getNode()->getId());\n\t\t\t\t\t\t$this->shareManager->updateShare($share);\n\t\t\t\t\t\t// The share is already transferred.\n\t\t\t\t\t\t$progress->advance();\n\t\t\t\t\t\tif ($move) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$share->setTarget($shareTarget);\n\t\t\t\t\t\t$this->shareManager->moveShare($share, $destinationUid);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t$this->shareManager->deleteShare($share);\n\t\t\t\t} elseif ($share->getShareOwner() === $destinationUid) {\n\t\t\t\t\t$this->shareManager->deleteShare($share);\n\t\t\t\t} else {\n\t\t\t\t\t$share->setSharedWith($destinationUid);\n\t\t\t\t\t$share->setNodeId($share->getNode()->getId());\n\t\t\t\t\t$this->shareManager->updateShare($share);\n\t\t\t\t\t// trigger refetching of the node so that the new owner and mountpoint are taken into account\n\t\t\t\t\t// otherwise the checks on the share update will fail due to the original node not being available in the new user scope\n\t\t\t\t\t$this->userMountCache->clear();\n\t\t\t\t\t// The share is already transferred.\n\t\t\t\t\t$progress->advance();\n\t\t\t\t\tif ($move) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t$share->setTarget($shareTarget);\n\t\t\t\t\t$this->shareManager->moveShare($share, $destinationUid);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch (\\OCP\\Files\\NotFoundException $e) {\n\t\t\t\t$output->writeln('Share with id ' . $share->getId() . ' points at deleted file, skipping');\n\t\t\t} catch (\\Throwable $e) {\n\t\t\t\t$output->writeln('Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '');\n\t\t\t}\n\t\t\t$progress->advance();\n\t\t}\n\t\t$progress->finish();\n\t\t$output->writeln('');\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n EntityManagerInterface $em,\n ParameterRepository $parameterRepository,\n ProductFacade $productFacade,\n FriendlyUrlRepository $friendlyUrlRepository,\n ProductVisibilityFacade $productVisibilityFacade,\n FriendlyUrlFacade $friendlyUrlFacade,\n CategoryFacade $categoryFacade,\n ProductAccessoryFacade $productAccessoryFacade,\n BrandCachedFacade $brandCachedFacade,\n ProductAvailabilityFacade $productAvailabilityFacade,\n HreflangLinksFacade $hreflangLinksFacade,\n BaseProductExportFieldProvider $productExportFieldProvider,\n PricingGroupSettingFacade $pricingGroupSettingFacade,\n ProductRepository $productRepository,\n InMemoryCache $inMemoryCache,\n private readonly ProductPriceCalculation $productPriceCalculation,\n private readonly BreadcrumbFacade $breadcrumbFacade,\n private readonly ProductVideoTranslationsRepository $productVideoTranslationsRepository,\n ) {\n parent::__construct(\n $em,\n $parameterRepository,\n $productFacade,\n $friendlyUrlRepository,\n $productVisibilityFacade,\n $friendlyUrlFacade,\n $categoryFacade,\n $productAccessoryFacade,\n $brandCachedFacade,\n $productAvailabilityFacade,\n $hreflangLinksFacade,\n $productExportFieldProvider,\n $pricingGroupSettingFacade,\n $productRepository,\n $inMemoryCache,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function get_linksbyname($cat_name = \"noname\", $before = '', $after = '
    ', $between = \" \", $show_images = true, $orderby = 'id',\n\t\t\t\t\t\t $show_description = true, $show_rating = false,\n\t\t\t\t\t\t $limit = -1, $show_updated = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\t$cat_id = -1;\n\t$cat = get_term_by('name', $cat_name, 'link_category');\n\tif ( $cat )\n\t\t$cat_id = $cat->term_id;\n\n\tget_links($cat_id, $before, $after, $between, $show_images, $orderby, $show_description, $show_rating, $limit, $show_updated);\n}", "smellKey": "S107", "smellId": null, "repo": "jpbarraca_sqli-wordpress", "language": "php"} {"function": "public function get_query_mot($field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict=array(),$neg_restrict=false,$all_fields=false) {\n\t\tif(count($this->tree)){\n\t\t\t//return $this->get_query_r_mot($this->tree,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict);\n\t\t\treturn $this->get_query_r_mot_with_table_tempo_all($this->tree,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict,$all_fields);\n\t\t}else{\n\t\t\treturn \"select $field_id from $table_mot where $field_id = 0\";\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct(\n ContentHandler $contentHandler,\n LocationHandler $locationHandler,\n TypeHandler $contentTypeHandler,\n ContentTypeDomainMapper $contentTypeDomainMapper,\n LanguageHandler $contentLanguageHandler,\n FieldTypeRegistry $fieldTypeRegistry,\n ThumbnailStrategy $thumbnailStrategy,\n ?LoggerInterface $logger = null,\n ?ProxyDomainMapperInterface $proxyFactory = null\n ) {\n $this->contentHandler = $contentHandler;\n $this->locationHandler = $locationHandler;\n $this->contentTypeHandler = $contentTypeHandler;\n $this->contentTypeDomainMapper = $contentTypeDomainMapper;\n $this->contentLanguageHandler = $contentLanguageHandler;\n $this->fieldTypeRegistry = $fieldTypeRegistry;\n $this->thumbnailStrategy = $thumbnailStrategy;\n $this->logger = $logger ?? new NullLogger();\n parent::__construct($proxyFactory);\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function checkFormOutput(\n \\Ticket $ticket,\n $name = true,\n $textarea = true,\n $priority = true,\n $save = true,\n $assign = true,\n $openDate = true,\n $timeOwnResolve = true,\n $type = true,\n $status = true,\n $urgency = true,\n $impact = true,\n $category = true,\n $requestSource = true,\n $location = true\n ) {\n ob_start();\n $ticket->showForm($ticket->getID());\n $output = ob_get_contents();\n ob_end_clean();\n $crawler = new Crawler($output);\n\n $backtrace = debug_backtrace(0, 1);\n $caller = \"File: {$backtrace[0]['file']} Function: {$backtrace[0]['function']}:{$backtrace[0]['line']}\";\n // Opening date, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data input[name=date]:not([disabled])\"));\n $this->assertCount(($openDate === true ? 1 : 0), $matches, \"RW Opening date $caller\");\n\n // Time to own, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data input[name=time_to_own]:not([disabled])\"));\n $this->assertCount(($timeOwnResolve === true ? 1 : 0), $matches, \"Time to own editable $caller\");\n\n // Internal time to own, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data input[name=internal_time_to_own]:not([disabled])\"));\n $this->assertCount(($timeOwnResolve === true ? 1 : 0), $matches, \"Internal time to own editable $caller\");\n\n // Time to resolve, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data input[name=time_to_resolve]:not([disabled])\"));\n $this->assertCount(($timeOwnResolve === true ? 1 : 0), $matches, \"Time to resolve $caller\");\n\n // Internal time to resolve, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data input[name=internal_time_to_resolve]:not([disabled])\"));\n $this->assertCount(($timeOwnResolve === true ? 1 : 0), $matches, \"Internal time to resolve $caller\");\n\n //Type\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=type]:not([disabled])\"));\n $this->assertCount(($type === true ? 1 : 0), $matches, \"Type $caller\");\n\n //Status\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=status]:not([disabled])\"));\n $this->assertCount(($status === true ? 1 : 0), $matches, \"Status $caller\");\n\n //Urgency\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=urgency]:not([disabled])\"));\n $this->assertCount(($urgency === true ? 1 : 0), $matches, \"Urgency $caller\");\n\n //Impact\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=impact]:not([disabled])\"));\n $this->assertCount(($impact === true ? 1 : 0), $matches, \"Impact $caller\");\n\n //Category\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=itilcategories_id]:not([disabled])\"));\n $this->assertCount(($category === true ? 1 : 0), $matches, \"Category $caller\");\n\n //Request source file_put_contents('/tmp/out.html', $output)\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=requesttypes_id]:not([disabled])\"));\n $this->assertCount(($requestSource === true ? 1 : 0), $matches, \"Request source $caller\");\n\n //Location\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=locations_id]:not([disabled])\"));\n $this->assertCount(($location === true ? 1 : 0), $matches, \"Location $caller\");\n\n //Priority, editable\n $matches = iterator_to_array($crawler->filter(\"#itil-data select[name=priority]:not([disabled])\"));\n $this->assertCount(($priority === true ? 1 : 0), $matches, \"RW priority $caller\");\n\n //Save button\n $matches = iterator_to_array($crawler->filter(\"#itil-footer button[type=submit][name=update]:not([disabled])\"));\n $this->assertCount(($save === true ? 1 : 0), $matches, ($save === true ? 'Save button missing' : 'Save button present') . ' ' . $caller);\n\n //Assign to\n /*preg_match(\n '|.*' . $output;\n if ($labels) $_output .= '';\n $_output .= $separator;\n\n return $_output;\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null)\n {\n $this->axisOptions['axis_labels'] = (string) $axis_labels;\n ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null;\n ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null;\n ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null;\n ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null;\n ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null;\n ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null;\n ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null;\n ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null;\n ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null;\n ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null;\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function AgregaSesionesImparticion($sesion, $id_inscripcion, $fecha, $hora_desde, $hora_hasta, $observacion, $id_linea, $relator, $sesion_new)\n{\n $connexion = new DatabasePDO();\n $rut_creador = $_SESSION[\"user_\"];\n $fecha_creacion = date(\"Y-m-d\");\n\n $sqlMax = \"select max(sesion) as maxsesion from tbl_inscripcion_curso_sesiones_horarios where id_inscripcion='$id_inscripcion'\";\n $connexion->query($sqlMax);\n $codMax = $connexion->resultset();\n\n $nueva_ses = $codMax[0]->maxsesion;\n if ($sesion_new == \"1\") {\n $sesion_ins = $nueva_ses + 1;\n } else {\n $sesion_ins = $sesion;\n }\n\n\n $observacion = ($observacion);\n\n $sql = \"select h.* from tbl_inscripcion_curso_sesiones_horarios h where h.id='$id_linea'\";\n\n $connexion->query($sql);\n $cod = $connexion->resultset();\n\n\n if ($cod[0]->id > 0) {\n if ($relator <> \"\") {\n $updateRelator = \" ,\trelator='$relator' \";\n } else {\n $updateRelator = \" \";\n }\n $sql = \"update tbl_inscripcion_curso_sesiones_horarios \nset \nid_inscripcion='$id_inscripcion',\nfecha='$fecha',\nhora_desde='$hora_desde',\nhora_hasta='$hora_hasta',\nobservaciones='$observacion',\nrut_creador='$rut_creador',\nfecha_creacion='$fecha_creacion',\nsesion='$sesion'\n\" . $updateRelator . \"\nwhere id='\" . $id_linea . \"'\";\n if ($fecha <> \"\" and $id_inscripcion <> \"\") {\n $connexion->query($sql);\n $connexion->execute();\n }\n } else {\n $sql = \" INSERT INTO tbl_inscripcion_curso_sesiones_horarios (id_inscripcion,fecha,hora_desde,hora_hasta,observaciones,rut_creador,fecha_creacion,sesion, relator)\n VALUES ('$id_inscripcion','$fecha','$hora_desde','$hora_hasta','$observacion','$rut_creador','$fecha_creacion','$sesion_ins', '$relator')\";\n\n if ($fecha <> \"\" and $id_inscripcion <> \"\") {\n $connexion->query($sql);\n $connexion->execute();\n }\n }\n return $cod;\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function get_input_date_time_inter($name, $id = '', $date_begin = '', $time_begin = '', $date_end = '', $time_end = '', $required = false, $onchange='') {\n global $msg;\n\n if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {\n $version = get_browser_version($_SERVER['HTTP_USER_AGENT']);\n if (!$version || ((int) $version < 57)) {\n if ($required) {\n $required = 'true';\n } else {\n $required = 'false';\n }\n $fields_date = \"\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n \t\t \n \";\n return $fields_date;\n }\n }\n if ($required) {\n $required = 'required';\n } else {\n $required = '';\n }\n $time_begin = str_replace('T', '', $time_begin);\n $time_end = str_replace('T', '', $time_end);\n $fields_date = \"\n\t\t\n \n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t \";\n return $fields_date;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_7.5.8", "language": "php"} {"function": "public function __construct(IConfig $config,\n\t\tIL10N $l,\n\t\tIUserSession $userSession,\n\t\tIURLGenerator $urlGenerator,\n\t\tICacheFactory $cacheFactory,\n\t\tUtil $util,\n\t\tImageManager $imageManager,\n\t\tIAppManager $appManager,\n\t\tINavigationManager $navigationManager\n\t) {\n\t\tparent::__construct();\n\t\t$this->config = $config;\n\t\t$this->l = $l;\n\t\t$this->imageManager = $imageManager;\n\t\t$this->userSession = $userSession;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->cacheFactory = $cacheFactory;\n\t\t$this->util = $util;\n\t\t$this->appManager = $appManager;\n\t\t$this->navigationManager = $navigationManager;\n\n\t\t$this->name = parent::getName();\n\t\t$this->title = parent::getTitle();\n\t\t$this->entity = parent::getEntity();\n\t\t$this->productName = parent::getProductName();\n\t\t$this->url = parent::getBaseUrl();\n\t\t$this->color = parent::getColorPrimary();\n\t\t$this->iTunesAppId = parent::getiTunesAppId();\n\t\t$this->iOSClientUrl = parent::getiOSClientUrl();\n\t\t$this->AndroidClientUrl = parent::getAndroidClientUrl();\n\t\t$this->FDroidClientUrl = parent::getFDroidClientUrl();\n\t\t$this->docBaseUrl = parent::getDocBaseUrl();\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function copyResampled(\n ImageWrapper $sourceImage,\n int $destinationX,\n int $destinationY,\n int $sourceX,\n int $sourceY,\n int $destinationWidth,\n int $destinationHeight,\n int $sourceWidth,\n int $sourceHeight,\n ): bool {\n return imagecopyresampled(\n $this->image,\n $sourceImage->getImage(),\n $destinationX,\n $destinationY,\n $sourceX,\n $sourceY,\n $destinationWidth,\n $destinationHeight,\n $sourceWidth,\n $sourceHeight,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function newInsuranceData(\n $pid,\n $type = \"\",\n $provider = \"\",\n $policy_number = \"\",\n $group_number = \"\",\n $plan_name = \"\",\n $subscriber_lname = \"\",\n $subscriber_mname = \"\",\n $subscriber_fname = \"\",\n $subscriber_relationship = \"\",\n $subscriber_ss = \"\",\n $subscriber_DOB = null,\n $subscriber_street = \"\",\n $subscriber_postal_code = \"\",\n $subscriber_city = \"\",\n $subscriber_state = \"\",\n $subscriber_country = \"\",\n $subscriber_phone = \"\",\n $subscriber_employer = \"\",\n $subscriber_employer_street = \"\",\n $subscriber_employer_city = \"\",\n $subscriber_employer_postal_code = \"\",\n $subscriber_employer_state = \"\",\n $subscriber_employer_country = \"\",\n $copay = \"\",\n $subscriber_sex = \"\",\n $effective_date = null,\n $accept_assignment = \"TRUE\",\n $policy_type = \"\",\n $effective_date_end = null\n) {\n\n if (strlen($type) <= 0) {\n return false;\n }\n\n if (is_null($accept_assignment)) {\n $accept_assignment = \"TRUE\";\n }\n if (is_null($policy_type)) {\n $policy_type = \"\";\n }\n\n // If empty dates were passed, then null.\n if (empty($effective_date)) {\n $effective_date = null;\n }\n if (empty($subscriber_DOB)) {\n $subscriber_DOB = null;\n }\n if (empty($effective_date_end)) {\n $effective_date_end = null;\n }\n\n return sqlInsert(\n \"INSERT INTO `insurance_data` SET `type` = ?,\n `provider` = ?,\n `policy_number` = ?,\n `group_number` = ?,\n `plan_name` = ?,\n `subscriber_lname` = ?,\n `subscriber_mname` = ?,\n `subscriber_fname` = ?,\n `subscriber_relationship` = ?,\n `subscriber_ss` = ?,\n `subscriber_DOB` = ?,\n `subscriber_street` = ?,\n `subscriber_postal_code` = ?,\n `subscriber_city` = ?,\n `subscriber_state` = ?,\n `subscriber_country` = ?,\n `subscriber_phone` = ?,\n `subscriber_employer` = ?,\n `subscriber_employer_city` = ?,\n `subscriber_employer_street` = ?,\n `subscriber_employer_postal_code` = ?,\n `subscriber_employer_state` = ?,\n `subscriber_employer_country` = ?,\n `copay` = ?,\n `subscriber_sex` = ?,\n `pid` = ?,\n `date` = ?,\n `accept_assignment` = ?,\n `policy_type` = ?,\n `date_end` = ?\",\n [\n $type,\n $provider,\n $policy_number,\n $group_number,\n $plan_name,\n $subscriber_lname,\n $subscriber_mname,\n $subscriber_fname,\n $subscriber_relationship,\n $subscriber_ss,\n $subscriber_DOB,\n $subscriber_street,\n $subscriber_postal_code,\n $subscriber_city,\n $subscriber_state,\n $subscriber_country,\n $subscriber_phone,\n $subscriber_employer,\n $subscriber_employer_city,\n $subscriber_employer_street,\n $subscriber_employer_postal_code,\n $subscriber_employer_state,\n $subscriber_employer_country,\n $copay,\n $subscriber_sex,\n $pid,\n $effective_date,\n $accept_assignment,\n $policy_type,\n $effective_date_end\n ]\n );\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function AjouterReglementStage($num, $type, $transaction, $banque, $montant, $stage, $stageSortie, $eleves)\n\t{\n\t\t$params = array(\n\t\t\t':stage' => $stage,\n\t\t\t':stageSortie' => $stageSortie,\n\t\t\t':type' => $type,\n\t\t\t':transaction' => $transaction,\n\t\t\t':banque' => $banque,\n\t\t\t':montant' => $montant,\n\t\t\t':num' => $num\n\t\t);\n\t\t$req = \"INSERT INTO quetigny_info_reglements (SOUTIEN, ADESION_CAF, ADESION_TARIF_PLEIN, STAGE, SORTIE_STAGE, DONS)\n VALUES (0, 0, 0, :stage, :stageSortie, 0);\n \n SET @info_reglement_id = LAST_INSERT_ID();\n\n\t\tUPDATE `INSCRIPTIONS_STAGE` SET `ID_INFO_REGLEMENT` = @info_reglement_id, `PAIEMENT_INSCRIPTIONS` = :type, `NUMTRANSACTION` = :transaction, `BANQUE_INSCRIPTION` = :banque, `MONTANT_INSCRIPTION` = :montant WHERE `ID_INSCRIPTIONS` = :num\";\n\t\t$i = 0;\n\t\tforeach ($eleves as $idEleve) {\n $req .= \"INSERT INTO inscriptions_fratries_stage(ID_INSCRIPTIONS, ID_INSCRIPTIONS2) VALUES (:num, :idEleve$i);\";\n\t\t\t$param[':idEleve$i'] = $idEleve;\n\t\t\t$i++;\n }\n\t\t\n\t\t$rs = $this->NonQuery($req, $params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de lajout de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n Gateway $contentGateway,\n LocationGateway $locationGateway,\n Mapper $mapper,\n FieldHandler $fieldHandler,\n SlugConverter $slugConverter,\n UrlAliasGateway $urlAliasGateway,\n ContentTypeHandler $contentTypeHandler,\n TreeHandler $treeHandler,\n LanguageHandler $languageHandler,\n LoggerInterface $logger = null\n ) {\n $this->contentGateway = $contentGateway;\n $this->locationGateway = $locationGateway;\n $this->mapper = $mapper;\n $this->fieldHandler = $fieldHandler;\n $this->slugConverter = $slugConverter;\n $this->urlAliasGateway = $urlAliasGateway;\n $this->contentTypeHandler = $contentTypeHandler;\n $this->treeHandler = $treeHandler;\n $this->languageHandler = $languageHandler;\n $this->logger = null !== $logger ? $logger : new NullLogger();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function __construct(\n ?string $scheme,\n ?string $user,\n ?string $pass,\n ?string $host,\n ?int $port,\n string $path,\n ?string $query,\n ?string $fragment\n ) {\n $this->scheme = $this->formatScheme($scheme);\n $this->user_info = $this->formatUserInfo($user, $pass);\n $this->host = $this->formatHost($host);\n $this->port = $this->formatPort($port);\n $this->authority = $this->setAuthority();\n $this->path = $this->formatPath($path);\n $this->query = $this->formatQueryAndFragment($query);\n $this->fragment = $this->formatQueryAndFragment($fragment);\n $this->assertValidState();\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n PersistenceHandlerInterface $persistenceHandler,\n CacheSectionHandler $sectionHandler,\n CacheLocationHandler $locationHandler,\n CacheContentHandler $contentHandler,\n CacheContentLanguageHandler $contentLanguageHandler,\n CacheContentTypeHandler $contentTypeHandler,\n CacheUserHandler $userHandler,\n CacheTransactionHandler $transactionHandler,\n CacheTrashHandler $trashHandler,\n CacheUrlAliasHandler $urlAliasHandler,\n CacheObjectStateHandler $objectStateHandler,\n CacheUrlHandler $urlHandler,\n CacheBookmarkHandler $bookmarkHandler,\n CacheNotificationHandler $notificationHandler,\n CacheUserPreferenceHandler $userPreferenceHandler,\n CacheUrlWildcardHandler $urlWildcardHandler,\n SettingHandler $settingHandler,\n PersistenceLogger $logger\n ) {\n $this->persistenceHandler = $persistenceHandler;\n $this->sectionHandler = $sectionHandler;\n $this->locationHandler = $locationHandler;\n $this->contentHandler = $contentHandler;\n $this->contentLanguageHandler = $contentLanguageHandler;\n $this->contentTypeHandler = $contentTypeHandler;\n $this->userHandler = $userHandler;\n $this->transactionHandler = $transactionHandler;\n $this->trashHandler = $trashHandler;\n $this->urlAliasHandler = $urlAliasHandler;\n $this->objectStateHandler = $objectStateHandler;\n $this->urlHandler = $urlHandler;\n $this->bookmarkHandler = $bookmarkHandler;\n $this->notificationHandler = $notificationHandler;\n $this->userPreferenceHandler = $userPreferenceHandler;\n $this->urlWildcardHandler = $urlWildcardHandler;\n $this->settingHandler = $settingHandler;\n $this->logger = $logger;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function getHtmlForDataStatements(\n array $logData,\n array $filterUsers,\n array $urlParams,\n string $dropImageOrText,\n TrackedDataType $trackedDataType,\n int $lineNumber,\n string $version,\n DateTimeImmutable $dateFrom,\n DateTimeImmutable $dateTo,\n ): array {\n $offset = $lineNumber;\n $entries = [];\n foreach ($logData as $entry) {\n if (\n $this->isDateBetweenInclusive(new DateTimeImmutable($entry['date']), $dateFrom, $dateTo)\n && (in_array('*', $filterUsers, true)\n || in_array($entry['username'], $filterUsers, true))\n ) {\n $entry['formated_statement'] = Generator::formatSql($entry['statement'], true);\n $deleteParam = 'delete_' . $trackedDataType->getLogName();\n $entry['url_params'] = Url::getCommon($urlParams + [\n 'report' => 'true',\n 'version' => $version,\n $deleteParam => $lineNumber - $offset,\n ], '');\n $entry['line_number'] = $lineNumber;\n $entries[] = $entry;\n }\n\n $lineNumber++;\n }\n\n $html = $this->template->render('table/tracking/report_table', [\n 'table_id' => $trackedDataType->getTableId(),\n 'header_message' => $trackedDataType->getHeaderMessage(),\n 'entries' => $entries,\n 'drop_image_or_text' => $dropImageOrText,\n ]);\n\n return [$html, $lineNumber];\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "function edit_acl($acl_id, $aco_array, $aro_array, $aro_group_ids=NULL, $axo_array=NULL, $axo_group_ids=NULL, $allow=1, $enabled=1, $return_value=NULL, $note=NULL, $section_value=NULL) {\n\n\t\t$this->debug_text(\"edit_acl():\");\n\n\t\tif (empty($acl_id) ) {\n\t\t\t$this->debug_text(\"edit_acl(): Must specify a single ACL_ID to edit\");\n\t\t\treturn false;\n\t\t}\n\t\tif (count($aco_array) == 0) {\n\t\t\t$this->debug_text(\"edit_acl(): Must select at least one Access Control Object\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (count($aro_array) == 0 AND count($aro_group_ids) == 0) {\n\t\t\t$this->debug_text(\"edit_acl(): Must select at least one Access Request Object or Group\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (empty($allow)) {\n\t\t\t$allow=0;\n\t\t}\n\n\t\tif (empty($enabled)) {\n\t\t\t$enabled=0;\n\t\t}\n\n\t\t//if ($this->add_acl($aco_array, $aro_array, $group_ids, $allow, $enabled, $acl_id)) {\n\t\tif ($this->add_acl($aco_array, $aro_array, $aro_group_ids, $axo_array, $axo_group_ids, $allow, $enabled, $return_value, $note, $section_value, $acl_id)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\t$this->debug_text(\"edit_acl(): error in add_acl()\");\n\t\t\treturn false;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\tlist($x, $y) = $this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);\n\t\t\t$this->javascript .= 'f'.$name.\".buttonSetCaption('\".addslashes($caption).\"');\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".setAction('MouseUp','\".addslashes($action).\"');\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".highlight='push';\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".print=false;\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t$prop['Pushbutton'] = 'true';\n\t\t$prop['highlight'] = 'push';\n\t\t$prop['display'] = 'display.noPrint';\n\t\t// get annotation data\n\t\t$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t// build appearance stream\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';\n\t\t$tmpid = $this->startTemplate($w, $h, false);\n\t\t$bw = (2 / $this->k); // border width\n\t\t$border = array(\n\t\t\t'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),\n\t\t\t'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),\n\t\t\t'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),\n\t\t\t'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));\n\t\t$this->SetFillColor(204);\n\t\t$this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');\n\t\t$this->endTemplate();\n\t\t--$this->n;\n\t\t$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];\n\t\tunset($this->xobjects[$tmpid]);\n\t\t$popt['ap']['n'] .= 'Q EMC';\n\t\t// set additional default options\n\t\tif (!isset($popt['mk'])) {\n\t\t\t$popt['mk'] = array();\n\t\t}\n\t\t$ann_obj_id = ($this->n + 1);\n\t\tif (!empty($action) AND !is_array($action)) {\n\t\t\t$ann_obj_id = ($this->n + 2);\n\t\t}\n\t\t$popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);\n\t\t$popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);\n\t\t$popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Btn';\n\t\t$opt['t'] = $caption;\n\t\t$opt['v'] = $name;\n\t\tif (!empty($action)) {\n\t\t\tif (is_array($action)) {\n\t\t\t\t// form action options as on section 12.7.5 of PDF32000_2008.\n\t\t\t\t$opt['aa'] = '/D <<';\n\t\t\t\t$bmode = array('SubmitForm', 'ResetForm', 'ImportData');\n\t\t\t\tforeach ($action AS $key => $val) {\n\t\t\t\t\tif (($key == 'S') AND in_array($val, $bmode)) {\n\t\t\t\t\t\t$opt['aa'] .= ' /S /'.$val;\n\t\t\t\t\t} elseif (($key == 'F') AND (!empty($val))) {\n\t\t\t\t\t\t$opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);\n\t\t\t\t\t} elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {\n\t\t\t\t\t\t$opt['aa'] .= ' /Fields [';\n\t\t\t\t\t\tforeach ($val AS $field) {\n\t\t\t\t\t\t\t$opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$opt['aa'] .= ']';\n\t\t\t\t\t} elseif (($key == 'Flags')) {\n\t\t\t\t\t\t$ff = 0;\n\t\t\t\t\t\tif (is_array($val)) {\n\t\t\t\t\t\t\tforeach ($val AS $flag) {\n\t\t\t\t\t\t\t\tswitch ($flag) {\n\t\t\t\t\t\t\t\t\tcase 'Include/Exclude': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeNoValueFields': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 1;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExportFormat': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 2;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'GetMethod': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 3;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'SubmitCoordinates': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 4;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'XFDF': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 5;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeAppendSaves': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 6;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeAnnotations': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 7;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'SubmitPDF': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 8;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'CanonicalFormat': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 9;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExclNonUserAnnots': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 10;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExclFKey': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 11;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'EmbedForm': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 13;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$ff = intval($val);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$opt['aa'] .= ' /Flags '.$ff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$opt['aa'] .= ' >>';\n\t\t\t} else {\n\t\t\t\t// Javascript action or raw action command\n\t\t\t\t$js_obj_id = $this->addJavascriptObject($action);\n\t\t\t\t$opt['aa'] = '/D '.$js_obj_id.' 0 R';\n\t\t\t}\n\t\t}\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {\n\t\tif (!isset($this->xobjects[$id])) {\n\t\t\t$this->Error('The XObject Template \\''.$id.'\\' doesn\\'t exist!');\n\t\t}\n\t\tif ($this->inxobj) {\n\t\t\tif ($id == $this->xobjid) {\n\t\t\t\t// close current template\n\t\t\t\t$this->endTemplate();\n\t\t\t} else {\n\t\t\t\t// use the template as resource for the template currently opened\n\t\t\t\t$this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];\n\t\t\t}\n\t\t}\n\t\t// set default values\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\t$ow = $this->xobjects[$id]['w'];\n\t\t$oh = $this->xobjects[$id]['h'];\n\t\t// calculate template width and height on document\n\t\tif (($w <= 0) AND ($h <= 0)) {\n\t\t\t$w = $ow;\n\t\t\t$h = $oh;\n\t\t} elseif ($w <= 0) {\n\t\t\t$w = $h * $ow / $oh;\n\t\t} elseif ($h <= 0) {\n\t\t\t$h = $w * $oh / $ow;\n\t\t}\n\t\t// fit the template on available space\n\t\t$this->fitBlock($w, $h, $x, $y, $fitonpage);\n\t\t// set page alignment\n\t\t$rb_y = $y + $h;\n\t\t// set alignment\n\t\tif ($this->rtl) {\n\t\t\tif ($palign == 'L') {\n\t\t\t\t$xt = $this->lMargin;\n\t\t\t} elseif ($palign == 'C') {\n\t\t\t\t$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($palign == 'R') {\n\t\t\t\t$xt = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xt = $x - $w;\n\t\t\t}\n\t\t\t$rb_x = $xt;\n\t\t} else {\n\t\t\tif ($palign == 'L') {\n\t\t\t\t$xt = $this->lMargin;\n\t\t\t} elseif ($palign == 'C') {\n\t\t\t\t$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($palign == 'R') {\n\t\t\t\t$xt = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xt = $x;\n\t\t\t}\n\t\t\t$rb_x = $xt + $w;\n\t\t}\n\t\t// print XObject Template + Transformation matrix\n\t\t$this->StartTransform();\n\t\t// translate and scale\n\t\t$sx = ($w / $this->xobjects[$id]['w']);\n\t\t$sy = ($h / $this->xobjects[$id]['h']);\n\t\t$tm = array();\n\t\t$tm[0] = $sx;\n\t\t$tm[1] = 0;\n\t\t$tm[2] = 0;\n\t\t$tm[3] = $sy;\n\t\t$tm[4] = $xt * $this->k;\n\t\t$tm[5] = ($this->h - $h - $y) * $this->k;\n\t\t$this->Transform($tm);\n\t\t// set object\n\t\t$this->_out('/'.$id.' Do');\n\t\t$this->StopTransform();\n\t\t// add annotations\n\t\tif (!empty($this->xobjects[$id]['annotations'])) {\n\t\t\tforeach ($this->xobjects[$id]['annotations'] as $annot) {\n\t\t\t\t// transform original coordinates\n\t\t\t\t$coordlt = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));\n\t\t\t\t$ax = ($coordlt[4] / $this->k);\n\t\t\t\t$ay = ($this->h - $h - ($coordlt[5] / $this->k));\n\t\t\t\t$coordrb = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));\n\t\t\t\t$aw = ($coordrb[4] / $this->k) - $ax;\n\t\t\t\t$ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;\n\t\t\t\t$this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);\n\t\t\t}\n\t\t}\n\t\t// set pointer to align the next text/objects\n\t\tswitch($align) {\n\t\t\tcase 'T': {\n\t\t\t\t$this->y = $y;\n\t\t\t\t$this->x = $rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'M': {\n\t\t\t\t$this->y = $y + round($h/2);\n\t\t\t\t$this->x = $rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B': {\n\t\t\t\t$this->y = $rb_y;\n\t\t\t\t$this->x = $rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'N': {\n\t\t\t\t$this->SetY($rb_y);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function (string $userId, string $secret, Request $request, Response $response, Document $user, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) {\n\n /** @var Utopia\\Database\\Document $user */\n\n $userFromRequest = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId));\n\n if ($userFromRequest->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $token = Auth::tokenVerify($userFromRequest->getAttribute('tokens', []), Auth::TOKEN_TYPE_MAGIC_URL, $secret);\n\n if (!$token) {\n throw new Exception(Exception::USER_INVALID_TOKEN);\n }\n\n $user->setAttributes($userFromRequest->getArrayCopy());\n\n $duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $secret = Auth::tokenGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), $duration));\n\n $session = new Document(array_merge(\n [\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => Auth::SESSION_PROVIDER_MAGIC_URL,\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ],\n $detector->getOS(),\n $detector->getClient(),\n $detector->getDevice()\n ));\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $session = $dbForProject->createDocument('sessions', $session\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $tokens = $user->getAttribute('tokens', []);\n\n /**\n * We act like we're updating and validating\n * the recovery token but actually we don't need it anymore.\n */\n $dbForProject->deleteDocument('tokens', $token);\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $user->setAttribute('emailVerification', true);\n\n try {\n $dbForProject->updateDocument('users', $user->getId(), $user);\n } catch (\\Throwable $th) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed saving user to DB');\n }\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId());\n\n if (!Config::getParam('domainVerification')) {\n $response->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]));\n }\n\n $protocol = $request->getProtocol();\n\n $response\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ->setStatusCode(Response::STATUS_CODE_CREATED);\n\n $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'));\n\n $session\n ->setAttribute('current', true)\n ->setAttribute('countryName', $countryName)\n ->setAttribute('expire', $expire);\n\n $response->dynamic($session, Response::MODEL_SESSION);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function acl_return_value($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value=NULL, $axo_value=NULL, $root_aro_group=NULL, $root_axo_group=NULL) {\n\t\t$acl_result = $this->acl_query($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value, $axo_value, $root_aro_group, $root_axo_group);\n\n\t\treturn $acl_result['return_value'];\n\t}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL)\n\t{\n\t\t// Set the config file options\n\t\tget_instance()->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httponly);\n\t}", "smellKey": "S107", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function executeQueryAndGetQueryResponse(\n StatementInfo $statementInfo,\n bool $isGotoFile,\n string $db,\n string|null $table,\n string|null $sqlQueryForBookmark,\n string|null $messageToShow,\n array|null $sqlData,\n string $goto,\n string|null $dispQuery,\n Message|string|null $dispMessage,\n string $sqlQuery,\n string|null $completeQuery,\n ): string {\n // Handle remembered sorting order, only for single table query.\n // Handling is not required when it's a union query\n // (the parser never sets the 'union' key to 0).\n // Handling is also not required if we came from the \"Sort by key\"\n // drop-down.\n if (\n $this->isRememberSortingOrder($statementInfo)\n && ! $statementInfo->flags->union\n && ! isset($_POST['sort_by_key'])\n ) {\n if (! isset($_SESSION['sql_from_query_box'])) {\n $statementInfo = $this->handleSortOrder($db, $table, $statementInfo, $sqlQuery);\n } else {\n unset($_SESSION['sql_from_query_box']);\n }\n }\n\n $displayResultsObject = new DisplayResults(\n $this->dbi,\n $this->config,\n Current::$database,\n Current::$table,\n Current::$server,\n $goto,\n $sqlQuery,\n );\n $displayResultsObject->setConfigParamsForDisplayTable($statementInfo);\n\n // assign default full_sql_query\n $fullSqlQuery = $sqlQuery;\n\n // Do append a \"LIMIT\" clause?\n if ($this->isAppendLimitClause($statementInfo)) {\n $fullSqlQuery = $this->getSqlWithLimitClause($statementInfo);\n }\n\n $GLOBALS['reload'] = $this->hasCurrentDbChanged($db);\n $this->dbi->selectDb($db);\n\n if (isset($GLOBALS['show_as_php'])) {\n // Only if we ask to see the php code\n // The following was copied from getQueryResponseForNoResultsReturned()\n // Delete if it's not needed in this context\n if ($this->isDeleteTransformationInfo($statementInfo)) {\n $this->deleteTransformationInfo($db, $table ?? '', $statementInfo);\n }\n\n $message = $this->getMessageForNoRowsReturned($messageToShow, $statementInfo, 0);\n\n return Generator::getMessage($message, $GLOBALS['sql_query'], MessageType::Success);\n }\n\n // Handle disable/enable foreign key checks\n $defaultFkCheck = ForeignKey::handleDisableCheckInit();\n\n [$result, $numRows, $unlimNumRows, $profilingResults, $errorMessage] = $this->executeTheQuery(\n $statementInfo,\n $fullSqlQuery,\n $isGotoFile,\n $db,\n $table,\n $sqlQueryForBookmark,\n );\n\n $warningMessages = $this->dbi->getWarnings();\n\n // No rows returned -> move back to the calling page\n if (($numRows == 0 && $unlimNumRows == 0) || $statementInfo->flags->isAffected || $result === false) {\n $htmlOutput = $this->getQueryResponseForNoResultsReturned(\n $statementInfo,\n $db,\n $table,\n $messageToShow,\n $numRows,\n $displayResultsObject,\n $errorMessage,\n $profilingResults,\n $result,\n $sqlQuery,\n $completeQuery,\n );\n } else {\n // At least one row is returned -> displays a table with results\n $htmlOutput = $this->getQueryResponseForResultsReturned(\n $result,\n $statementInfo,\n $db,\n $table,\n $sqlData,\n $displayResultsObject,\n $unlimNumRows,\n $numRows,\n $dispQuery,\n $dispMessage,\n $profilingResults,\n $sqlQuery,\n $completeQuery,\n );\n }\n\n // Handle disable/enable foreign key checks\n ForeignKey::handleDisableCheckCleanup($defaultFkCheck);\n\n foreach ($warningMessages as $warning) {\n $message = Message::notice(htmlspecialchars((string) $warning));\n $htmlOutput .= $message->getDisplay();\n }\n\n return $htmlOutput;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "private function tableHasRow4D($tblname, $colname, $value, $colname2, $value2, $colname3, $value3, $colname4, $value4)\n {\n $row = sqlQuery(\"SELECT COUNT(*) AS count FROM $tblname WHERE \" .\n \"$colname LIKE '$value' AND $colname2 LIKE '$value2' AND $colname3 LIKE '$value3' AND $colname4 LIKE '$value4'\");\n return $row['count'] ? true : false;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct(?string $aaid, ?string $aaguid, array $attestationCertificateKeyIdentifiers, ?string $hash, ?string $url, string $timeOfLastStatusChange, ?string $rogueListURL, ?string $rogueListHash)\n {\n if (null !== $aaid && null !== $aaguid) {\n throw new LogicException('Authenticators cannot support both AAID and AAGUID');\n }\n if (null === $aaid && null === $aaguid && 0 === count($attestationCertificateKeyIdentifiers)) {\n throw new LogicException('If neither AAID nor AAGUID are set, the attestation certificate identifier list shall not be empty');\n }\n foreach ($attestationCertificateKeyIdentifiers as $attestationCertificateKeyIdentifier) {\n Assertion::string($attestationCertificateKeyIdentifier, Utils::logicException('Invalid attestation certificate identifier. Shall be a list of strings'));\n Assertion::notEmpty($attestationCertificateKeyIdentifier, Utils::logicException('Invalid attestation certificate identifier. Shall be a list of strings'));\n Assertion::regex($attestationCertificateKeyIdentifier, '/^[0-9a-f]+$/', Utils::logicException('Invalid attestation certificate identifier. Shall be a list of strings'));\n }\n $this->aaid = $aaid;\n $this->aaguid = $aaguid;\n $this->attestationCertificateKeyIdentifiers = $attestationCertificateKeyIdentifiers;\n $this->hash = Base64Url::decode($hash);\n $this->url = $url;\n $this->timeOfLastStatusChange = $timeOfLastStatusChange;\n $this->rogueListURL = $rogueListURL;\n $this->rogueListHash = $rogueListHash;\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)\n {\n if (!empty($this->action_function) && is_callable($this->action_function)) {\n call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);\n }\n }", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "function profile_install_addField($name, $title, $description, $category, $type, $valuetype, $weight, $canedit, $options, $step_id, $length, $visible = true)\n{\n global $module_id;\n\n $profilefield_handler = xoops_getModuleHandler('field', 'profile');\n $obj = $profilefield_handler->create();\n $obj->setVar('field_name', $name, true);\n $obj->setVar('field_moduleid', $module_id, true);\n $obj->setVar('field_show', 1);\n $obj->setVar('field_edit', $canedit ? 1 : 0);\n $obj->setVar('field_config', 0);\n $obj->setVar('field_title', strip_tags($title), true);\n $obj->setVar('field_description', strip_tags($description), true);\n $obj->setVar('field_type', $type, true);\n $obj->setVar('field_valuetype', $valuetype, true);\n $obj->setVar('field_options', $options, true);\n if ($canedit) {\n $obj->setVar('field_maxlength', $length, true);\n }\n\n $obj->setVar('field_weight', $weight, true);\n $obj->setVar('cat_id', $category, true);\n $obj->setVar('step_id', $step_id, true);\n $profilefield_handler->insert($obj);\n\n profile_install_setPermissions($obj->getVar('field_id'), $module_id, $canedit, $visible);\n\n return true;\n /*\n //$GLOBALS['xoopsDB']->query(\"INSERT INTO \".$GLOBALS['xoopsDB']->prefix(\"profile_field\").\" VALUES (0, {$category}, '{$type}', {$valuetype}, '{$name}', \" . $GLOBALS['xoopsDB']->quote($title) . \", \" . $GLOBALS['xoopsDB']->quote($description) . \", 0, {$length}, {$weight}, '', 1, {$canedit}, 1, 0, '\" . serialize($options) . \"', {$step_id})\");\n $gperm_itemid = $obj->getVar('field_id');\n unset($obj);\n $gperm_modid = $module_id;\n $sql = \"INSERT INTO \" . $GLOBALS['xoopsDB']->prefix(\"group_permission\") .\n \" (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) \" .\n \" VALUES \" .\n ($canedit ?\n \" (\" . XOOPS_GROUP_ADMIN . \", {$gperm_itemid}, {$gperm_modid}, 'profile_edit'), \"\n : \"\" ) .\n ($canedit == 1 ?\n \" (\" . XOOPS_GROUP_USERS . \", {$gperm_itemid}, {$gperm_modid}, 'profile_edit'), \"\n : \"\" ) .\n \" (\" . XOOPS_GROUP_ADMIN . \", {$gperm_itemid}, {$gperm_modid}, 'profile_search'), \" .\n \" (\" . XOOPS_GROUP_USERS . \", {$gperm_itemid}, {$gperm_modid}, 'profile_search') \" .\n \" \";\n $GLOBALS['xoopsDB']->query($sql);\n\n if ($visible) {\n $sql = \"INSERT INTO \" . $GLOBALS['xoopsDB']->prefix(\"profile_visibility\") .\n \" (field_id, user_group, profile_group) \" .\n \" VALUES \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_ADMIN . \", \" . XOOPS_GROUP_ADMIN . \"), \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_ADMIN . \", \" . XOOPS_GROUP_USERS . \"), \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_USERS . \", \" . XOOPS_GROUP_ADMIN . \"), \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_USERS . \", \" . XOOPS_GROUP_USERS . \"), \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_ANONYMOUS . \", \" . XOOPS_GROUP_ADMIN . \"), \" .\n \" ({$gperm_itemid}, \" . XOOPS_GROUP_ANONYMOUS . \", \" . XOOPS_GROUP_USERS . \")\" .\n \" \";\n $GLOBALS['xoopsDB']->query($sql);\n }\n */\n}", "smellKey": "S107", "smellId": null, "repo": "mambax7_XoopsCore25", "language": "php"} {"function": "public function inscriptionStageOre($num,$nom,$prenom,$datedenaissance,$date,$ip,$user_agent,$origine,$id_atelier,$classe,$tel_parent,$tel_enfant)\n\t{\n\t\t$req = \"INSERT INTO `ELEVE_STAGE`(`NOM_ELEVE_STAGE`, `PRENOM_ELEVE_STAGE`,`DDN_ELEVE_STAGE`,`ASSOCIATION_ELEVE_STAGE`, `CLASSE_ELEVE_STAGE`) VALUES (:nom, :prenom, :datedenaissance, 'ore', :classe);\";\n\t\t$params = array(\n\t\t\t':nom' => strtoupper(addslashes($nom)),\n\t\t\t':prenom' => ucfirst(addslashes($prenom)),\n\t\t\t':datedenaissance' => $datedenaissance,\n\t\t\t':classe' => $classe\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription de l'\u00e9l\u00e8ve au stage.\", $req, PdoBD::$monPdo->errorInfo());}\n\n\t\t$req2 = \"INSERT INTO `INSCRIPTIONS_STAGE`(`ID_STAGE`,`ID_ELEVE_STAGE`,`ID_ATELIERS`,`VALIDE`,`DATE_INSCRIPTIONS`,`IP_INSCRIPTIONS`,`USER_AGENT_INSCRIPTIONS`, `ORIGINE_INSCRIPTIONS`) VALUES (:num, (SELECT MAX(`ID_ELEVE_STAGE`) AS max_id FROM `ELEVE_STAGE`), :id_atelier, 0, :date, :ip, :user_agent, :origine);\";\n\t\t$params2 = array(\n\t\t\t':num' => $num,\n\t\t\t':id_atelier' => $id_atelier,\n\t\t\t':date' => $date,\n\t\t\t':ip' => $ip,\n\t\t\t':user_agent' => addslashes($user_agent),\n\t\t\t':origine' => addslashes($origine)\n\t\t);\n\t\t$rs2 = $this->NonQuery($req2, $params2);\n\t\tif ($rs2 === false) {afficherErreurSQL(\"Probleme lors de l'inscription de l'\u00e9l\u00e8ve au stage.\", $req2, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function get_query_r_mot_with_table_tempo_all($tree,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict=false,$all_fields=false) {\n\t\t// Variable permettant de choisir si l'on utilise ou non la troncature droite du terme recherch\n\t\t$empty_word = get_empty_words();\n\n\t\t$temporary_table = $last_table = \"\";\n\t\t$troncat = \"\";\n\t\tif ($this->allow_term_troncat_search) {\n\t\t\t$troncat = \"%\";\n\t\t}\n\t\t$lang_restrict = $field_restrict = array();\n\t\tfor($i=0 ; $isub){\n\t\t\t\t$elem_query = $this->get_query_r_mot_with_table_tempo_all($tree[$i]->sub,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict,$all_fields);\n\t\t\t}else{\n\t\t\t\tif($tree[$i]->word !== \"*\") {\n\t\t\t\t if($tree[$i]->literal == 0){\n\t\t\t\t\t\t// on commence...\n\t\t\t\t\t\t$qw = \"select distinct id_word from words where \".(count($lang_restrict)>0 ? $this->get_field_restrict($lang_restrict,$neg_restrict).\" and \": \"\");\n\n\t\t\t\t\t\t$table= $table_mot;\n\t\t\t\t\t\t//on ajoute le terme\n\t\t\t\t\t\t$qw.= \" words.\".$field_mot.\" \";\n\t\t\t\t\t\tif(strpos($tree[$i]->word, \"*\") !== false || ($this->allow_term_troncat_search && (strlen($tree[$i]->word)>2))){\n\t\t\t\t\t\t\t$qw.=\"like '\";\n\t\t\t\t\t\t\tif (strpos($tree[$i]->word,\"*\") === false) {\n\t\t\t\t\t\t\t\t//Si c'est un mot vide, on ne troncature pas\n\t\t\t\t\t\t\t\tif (in_array($tree[$i]->word,$empty_word)===false) {\n\t\t\t\t\t\t\t\t\t$qw.=addslashes($tree[$i]->word.$troncat);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$qw.=addslashes($tree[$i]->word);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$qw.=addslashes(str_replace(\"*\",\"%\",$tree[$i]->word));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$qw.=\"'\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$qw.=\"='\".addslashes($tree[$i]->word).\"'\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$tw = array();\n\t\t\t\t\t\t$rw = pmb_mysql_query($qw);\n\t\t\t\t\t\tif(pmb_mysql_num_rows($rw)) {\n\t\t\t\t\t\t\twhile($o = pmb_mysql_fetch_object($rw) ) {\n\t\t\t\t\t\t\t\t$tw[]=$o->id_word;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_mot \".gen_where_in($table_mot.'.num_word', $tw).\" and pond>0 \";\n\t\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t\t$elem_query.= ' and '.$this->get_field_restrict($restrict,$neg_restrict);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif($tree[$i]->start_with){\n\t\t\t\t\t\t\t$elem_query.=\" and field_position ='1'\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if ($tree[$i]->literal == 1){\n\t\t\t\t\t\t// on commence...\n\t\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_term where pond>0 and \";\n\t\t\t\t\t\t//on applique la restriction si besoin\n\t\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t\t$elem_query.= $this->get_field_restrict($restrict,$neg_restrict).\" and \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$table= $table_term;\n\t\t\t\t\t\t//on ajoute le terme\n\t\t\t\t\t\t$elem_query.= \" \".$table.\".\".$field_term.\" \";\n\t\t\t\t\t\t$elem_query.= \"like '\";\n\t\t\t\t\t\tif(!$tree[$i]->start_with){\n\t\t\t\t\t\t\t$elem_query.=\"%\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strpos($tree[$i]->word,\"*\") === false) {\n\t\t\t\t\t\t\t//Si c'est un mot vide, on ne troncature pas\n\t\t\t\t\t\t\tif (in_array($tree[$i]->word,$empty_word)===false) {\n\t\t\t\t\t\t\t\t$elem_query.=addslashes($tree[$i]->word.$troncat);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$elem_query.=addslashes($tree[$i]->word);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$elem_query.=addslashes(str_replace(\"*\",\"%\",$tree[$i]->word));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$elem_query.=\"%'\";\n\t\t\t\t\t}\n\t\t\t\t\tif($table_mot == \"notices_mots_global_index\" && $all_fields && $this->exclude_fields!=\"\"){\n\t\t\t\t\t\t$elem_query.= \" and code_champ not in (\".$this->exclude_fields.\")\";\n\t\t\t\t\t}\n\t\t\t\t}else if(count($tree)==1){\n\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_mot where 1\";\n\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t$elem_query.= \" and \".$this->get_field_restrict($restrict,$neg_restrict).\" \";\n\t\t\t\t\t}\n\t\t\t\t\tif($table_mot == \"notices_mots_global_index\" && $all_fields && $this->exclude_fields!=\"\"){\n\t\t\t\t\t\t$elem_query.= \" and code_champ not in (\".$this->exclude_fields.\")\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($tree[$i]->literal!=2 && $elem_query!= \"\"){\n\t\t\t\t$last_table = $temporary_table;\n\t\t\t\t$temporary_table = $this->tmp_prefix.md5(microtime(true).\"#\".$this->keep_empty.$i);\n\t\t\t\tswitch($tree[$i]->operator){\n\t\t\t\t\tcase \"and\" :\n\t\t\t\t\t\t//on cr la table tempo avec les rsultats du critre...\n\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"delete from \".$last_table.\" where \".$field_id.\" in (select \".$field_id.\" from \".$temporary_table.\")\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$temporary_table);\n\t\t\t\t\t\t\t$temporary_table = $last_table;\n\t\t\t\t\t\t\t$last_table = \"\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$new_temporary_table =$this->tmp_prefix.md5(microtime(true).\"new_temporary_table\".$this->keep_empty.$i);\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$new_temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory select $last_table.$field_id from $last_table join $temporary_table on $last_table.$field_id = $temporary_table.$field_id\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$temporary_table);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$last_table);\n\t\t\t\t\t\t\t$temporary_table=$new_temporary_table;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"or\" :\n\t\t\t\t\t\t$temporary_table = $last_table;\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"create temporary table tmp_\".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\t$rqt = \"insert ignore into \".$temporary_table.\" select distinct $field_id from $table_term where \".$field_id.\" not in(select \".$field_id.\" from tmp_\".$temporary_table.\") and code_champ = 1\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists tmp_\".$temporary_table);\n\t\t\t\t\t\t\t$last_table= \"\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$rqt = \"insert ignore into \".$temporary_table.\" \".$elem_query;\n\t\t\t\t\t\t\t$last_table= \"\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault :\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"create temporary table tmp_\".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory select distinct $field_id from $table_term where \".$field_id.\" not in(select \".$field_id.\" from tmp_\".$temporary_table.\") and code_champ = 1\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists tmp_\".$temporary_table);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t$query = \"select distinct $field_id from \".$temporary_table;\n\t\t\t\tif($last_table != \"\"){\n\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$last_table);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $query;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function __construct($shareWith = '',\n\t\t$name = '',\n\t\t$description = '',\n\t\t$providerId = '',\n\t\t$owner = '',\n\t\t$ownerDisplayName = '',\n\t\t$sharedBy = '',\n\t\t$sharedByDisplayName = '',\n\t\t$shareType = '',\n\t\t$resourceType = '',\n\t\t$sharedSecret = ''\n\t) {\n\t\t$this->setShareWith($shareWith);\n\t\t$this->setResourceName($name);\n\t\t$this->setDescription($description);\n\t\t$this->setProviderId($providerId);\n\t\t$this->setOwner($owner);\n\t\t$this->setOwnerDisplayName($ownerDisplayName);\n\t\t$this->setSharedBy($sharedBy);\n\t\t$this->setSharedByDisplayName($sharedByDisplayName);\n\t\t$this->setProtocol([\n\t\t\t'name' => 'webdav',\n\t\t\t'options' => [\n\t\t\t\t'sharedSecret' => $sharedSecret,\n\t\t\t\t'permissions' => '{http://open-cloud-mesh.org/ns}share-permissions'\n\t\t\t]\n\t\t]);\n\t\t$this->setShareType($shareType);\n\t\t$this->setResourceType($resourceType);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function updateAttribute(\n string $databaseId,\n string $collectionId,\n string $key,\n Database $dbForProject,\n Event $events,\n string $type,\n string $filter = null,\n string|bool|int|float $default = null,\n bool $required = null,\n int|float $min = null,\n int|float $max = null,\n array $elements = null,\n array $options = []\n): Document {\n $db = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId));\n\n if ($db->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $attribute = $dbForProject->getDocument('attributes', $db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key);\n\n if ($attribute->isEmpty()) {\n throw new Exception(Exception::ATTRIBUTE_NOT_FOUND);\n }\n\n if ($attribute->getAttribute('status') !== 'available') {\n throw new Exception(Exception::ATTRIBUTE_NOT_AVAILABLE);\n }\n\n if ($attribute->getAttribute(('type') !== $type)) {\n throw new Exception(Exception::ATTRIBUTE_TYPE_INVALID);\n }\n\n if ($attribute->getAttribute('type') === Database::VAR_STRING && $attribute->getAttribute(('filter') !== $filter)) {\n throw new Exception(Exception::ATTRIBUTE_TYPE_INVALID);\n }\n\n if ($required && isset($default)) {\n throw new Exception(Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED, 'Cannot set default value for required attribute');\n }\n\n if ($attribute->getAttribute('array', false) && isset($default)) {\n throw new Exception(Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED, 'Cannot set default value for array attributes');\n }\n\n $collectionId = 'database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId();\n\n $attribute\n ->setAttribute('default', $default)\n ->setAttribute('required', $required);\n\n $formatOptions = $attribute->getAttribute('formatOptions');\n\n switch ($attribute->getAttribute('format')) {\n case APP_DATABASE_ATTRIBUTE_INT_RANGE:\n case APP_DATABASE_ATTRIBUTE_FLOAT_RANGE:\n if ($min === $formatOptions['min'] && $max === $formatOptions['max']) {\n break;\n }\n\n if ($min > $max) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Minimum value must be lesser than maximum value');\n }\n\n if ($attribute->getAttribute('format') === APP_DATABASE_ATTRIBUTE_INT_RANGE) {\n $validator = new Range($min, $max, Database::VAR_INTEGER);\n } else {\n $validator = new Range($min, $max, Database::VAR_FLOAT);\n\n if (!is_null($default)) {\n $default = \\floatval($default);\n }\n }\n\n if (!is_null($default) && !$validator->isValid($default)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription());\n }\n\n $options = [\n 'min' => $min,\n 'max' => $max\n ];\n $attribute->setAttribute('formatOptions', $options);\n\n break;\n case APP_DATABASE_ATTRIBUTE_ENUM:\n if (empty($elements)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Enum elements must not be empty');\n }\n\n foreach ($elements as $element) {\n if (\\strlen($element) === 0) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Each enum element must not be empty');\n }\n }\n\n if (!is_null($default) && !in_array($default, $elements)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Default value not found in elements');\n }\n\n $options = [\n 'elements' => $elements\n ];\n\n $attribute->setAttribute('formatOptions', $options);\n\n break;\n }\n\n if ($type === Database::VAR_RELATIONSHIP) {\n $primaryDocumentOptions = \\array_merge($attribute->getAttribute('options', []), $options);\n $attribute->setAttribute('options', $primaryDocumentOptions);\n\n $dbForProject->updateRelationship(\n collection: $collectionId,\n id: $key,\n onDelete: $primaryDocumentOptions['onDelete'],\n );\n\n if ($primaryDocumentOptions['twoWay']) {\n $relatedCollection = $dbForProject->getDocument('database_' . $db->getInternalId(), $primaryDocumentOptions['relatedCollection']);\n\n $relatedAttribute = $dbForProject->getDocument('attributes', $db->getInternalId() . '_' . $relatedCollection->getInternalId() . '_' . $primaryDocumentOptions['twoWayKey']);\n $relatedOptions = \\array_merge($relatedAttribute->getAttribute('options'), $options);\n $relatedAttribute->setAttribute('options', $relatedOptions);\n $dbForProject->updateDocument('attributes', $db->getInternalId() . '_' . $relatedCollection->getInternalId() . '_' . $primaryDocumentOptions['twoWayKey'], $relatedAttribute);\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $relatedCollection->getId());\n }\n } else {\n $dbForProject->updateAttribute(\n collection: $collectionId,\n id: $key,\n required: $required,\n default: $default,\n formatOptions: $options ?? null\n );\n }\n\n $attribute = $dbForProject->updateDocument('attributes', $db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key, $attribute);\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collection->getId());\n\n $events\n ->setContext('collection', $collection)\n ->setContext('database', $db)\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('attributeId', $attribute->getId());\n\n return $attribute;\n}", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function drawGrid(\n\t\tawDrawer $drawer, awColor $color,\n\t\t$nx, $ny, $x1, $y1, $x2, $y2,\n\t\t$type, $space, $hInterval, $vInterval\n\t) {\n\n\t\tlist($left, $right, $top, $bottom) = $space;\n\n\t\t$width = $x2 - $x1 - $left - $right;\n\t\t$height = $y2 - $y1 - $top - $bottom;\n\n\t\tforeach($nx as $key => $n) {\n\n\t\t\tif(($key % $vInterval) === 0) {\n\n\t\t\t\t$pos = (int)round($x1 + $left + $n * $width);\n\t\t\t\t$drawer->line(\n\t\t\t\t\t$color,\n\t\t\t\t\tnew awLine(\n\t\t\t\t\t\tnew awPoint($pos, $y1),\n\t\t\t\t\t\tnew awPoint($pos, $y2),\n\t\t\t\t\t\t$type\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t\tforeach($ny as $key => $n) {\n\n\t\t\tif(($key % $hInterval) === 0) {\n\n\t\t\t\t$pos = (int)round($y1 + $top + $n * $height);\n\t\t\t\t$drawer->line(\n\t\t\t\t\t$color,\n\t\t\t\t\tnew awLine(\n\t\t\t\t\t\tnew awPoint($x1, $pos),\n\t\t\t\t\t\tnew awPoint($x2, $pos),\n\t\t\t\t\t\t$type\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t}", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function __construct(\n\t\t?string $outNumRA,\n\t\t?string $outDigitoRA,\n\t\t?string $outSiglaUFRA,\n\t\t?string $outNomeAluno,\n\t\t?string $outNomeMae,\n\t\t?string $outNomePai,\n\t\t?string $outNomeSocial,\n\t\t?string $outDataNascimento\n\t) {\n\t\t$this->outNumRA = $outNumRA;\n\t\t$this->outDigitoRA = $outDigitoRA;\n\t\t$this->outSiglaUFRA = $outSiglaUFRA;\n\t\t$this->outNomeAluno = $outNomeAluno;\n\t\t$this->outNomeMae = $outNomeMae;\n\t\t$this->outNomePai = $outNomePai;\n\t\t$this->outNomeSocial = $outNomeSocial;\n\t\t$this->outDataNascimento = $outDataNascimento;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(\n EntityManagerInterface $em,\n CategoryRepository $categoryRepository,\n Domain $domain,\n CategoryVisibilityRecalculationScheduler $categoryVisibilityRecalculationScheduler,\n FriendlyUrlFacade $friendlyUrlFacade,\n ImageFacade $imageFacade,\n PluginCrudExtensionFacade $pluginCrudExtensionFacade,\n CategoryWithPreloadedChildrenFactory $categoryWithPreloadedChildrenFactory,\n CategoryWithLazyLoadedVisibleChildrenFactory $categoryWithLazyLoadedVisibleChildrenFactory,\n CategoryFactoryInterface $categoryFactory,\n ProductRecalculationDispatcher $productRecalculationDispatcher,\n EventDispatcherInterface $eventDispatcher,\n CategoryParameterFacade $categoryParameterFacade,\n ProductOnCurrentDomainElasticFacade $productOnCurrentDomainElasticFacade,\n private readonly LinkedCategoryFacade $linkedCategoryFacade,\n ) {\n parent::__construct(\n $em,\n $categoryRepository,\n $domain,\n $categoryVisibilityRecalculationScheduler,\n $friendlyUrlFacade,\n $imageFacade,\n $pluginCrudExtensionFacade,\n $categoryWithPreloadedChildrenFactory,\n $categoryWithLazyLoadedVisibleChildrenFactory,\n $categoryFactory,\n $productRecalculationDispatcher,\n $eventDispatcher,\n $categoryParameterFacade,\n $productOnCurrentDomainElasticFacade,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function expand_collapse_widget($title, $label, $buttonLabel, $buttonLink, $buttonClass, $linkMethod, $bodyClass, $auth, $fixedWidth, $forceExpandAlways = false)\n{\n if ($fixedWidth) {\n echo \"
    \";\n } else {\n echo \"
    \";\n }\n\n echo \"\";\n if ($auth) {\n // show button, since authorized\n // first prepare class string\n if ($buttonClass) {\n $class_string = \"btn btn-primary btn-sm \" . $buttonClass;\n } else {\n $class_string = \"btn btn-primary btn-sm\";\n }\n\n // next, create the link\n if ($linkMethod == \"javascript\") {\n echo \"\";\n }\n\n if ($forceExpandAlways) {\n // Special case to force the widget to always be expanded\n echo \"\";\n echo \"
    \" .\n text($buttonLabel) . \"\" . text($title) . \"\";\n $indicatorTag = \"style='display: none'\";\n }\n\n $indicatorTag = isset($indicatorTag) ? $indicatorTag : \"\";\n echo \"\";\n echo text($title) . \"\";\n\n if (isset($_SESSION['patient_portal_onsite_two'])) {\n // collapse all entries in the patient portal\n $text = xl('expand');\n } elseif (getUserSetting($label . \"_ps_expand\")) {\n $text = xl('collapse');\n } else {\n $text = xl('expand');\n }\n\n echo \" (\" . text($text) .\n \")
    \";\n echo \"
    \";\n if ($forceExpandAlways) {\n // Special case to force the widget to always be expanded\n $styling = \"\";\n } elseif (isset($_SESSION['patient_portal_onsite_two'])) {\n // collapse all entries in the patient portal\n $styling = \"style='display: none'\";\n } elseif (getUserSetting($label . \"_ps_expand\")) {\n $styling = \"\";\n } else {\n $styling = \"style='display: none'\";\n }\n\n if ($bodyClass) {\n $styling .= \" class='\" . attr($bodyClass) . \"'\";\n }\n\n //next, create the first div tag to hold the information\n // note the code that calls this function will then place the ending div tag after the data\n echo \"
    \";\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($username, $dn, Access $access,\n\t\tIConfig $config, FilesystemHelper $fs, Image $image,\n\t\tLoggerInterface $logger, IAvatarManager $avatarManager, IUserManager $userManager,\n\t\tINotificationManager $notificationManager) {\n\t\tif ($username === null) {\n\t\t\t$logger->error(\"uid for '$dn' must not be null!\", ['app' => 'user_ldap']);\n\t\t\tthrow new \\InvalidArgumentException('uid must not be null!');\n\t\t} elseif ($username === '') {\n\t\t\t$logger->error(\"uid for '$dn' must not be an empty string\", ['app' => 'user_ldap']);\n\t\t\tthrow new \\InvalidArgumentException('uid must not be an empty string!');\n\t\t}\n\n\t\t$this->access = $access;\n\t\t$this->connection = $access->getConnection();\n\t\t$this->config = $config;\n\t\t$this->fs = $fs;\n\t\t$this->dn = $dn;\n\t\t$this->uid = $username;\n\t\t$this->image = $image;\n\t\t$this->logger = $logger;\n\t\t$this->avatarManager = $avatarManager;\n\t\t$this->userManager = $userManager;\n\t\t$this->notificationManager = $notificationManager;\n\n\t\t\\OCP\\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function createMainConfig(\n string $host,\n string $user,\n string $password,\n string $dbname,\n bool $use_timezones = false,\n bool $log_deprecation_warnings = false,\n bool $use_utf8mb4 = false,\n bool $allow_datetime = true,\n bool $allow_signed_keys = true,\n string $config_dir = GLPI_CONFIG_DIR\n ): bool {\n\n $properties = [\n 'dbhost' => $host,\n 'dbuser' => $user,\n 'dbpassword' => rawurlencode($password),\n 'dbdefault' => $dbname,\n ];\n if ($use_timezones) {\n $properties[self::PROPERTY_USE_TIMEZONES] = true;\n }\n if ($log_deprecation_warnings) {\n $properties[self::PROPERTY_LOG_DEPRECATION_WARNINGS] = true;\n }\n if ($use_utf8mb4) {\n $properties[self::PROPERTY_USE_UTF8MB4] = true;\n }\n if (!$allow_datetime) {\n $properties[self::PROPERTY_ALLOW_DATETIME] = false;\n }\n if (!$allow_signed_keys) {\n $properties[self::PROPERTY_ALLOW_SIGNED_KEYS] = false;\n }\n\n $config_str = ' $value) {\n $config_str .= sprintf(' public $%s = %s;', $name, var_export($value, true)) . \"\\n\";\n }\n $config_str .= '}' . \"\\n\";\n\n return Toolbox::writeConfig('config_db.php', $config_str, $config_dir);\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function ajoutdocseleves($nom, $commentaires, $fichier, $corrige, $date, $classe, $photo, $type, $categorie, $valide) {\n\n\t\t$req = \"INSERT INTO `docsEleves` (`id`, `nom`, `Commentaires`, `urlfichier`, `urlcorrige`, `dateMiseEnLigne`, `Classe`, `urlphoto`, `Type`, `NBDOWNLOAD`, `ID_CATEGDOC`, `valide`) VALUES (NULL, :nom, :commentaires, :fichier, :corrige, :date, :classe, :photo, :type, '0', :categorie, :valide)\";\n\n\t\t$params = array(\n\t\t\t':nom' => $nom,\n\t\t\t':commentaires' => $commentaires,\n\t\t\t':fichier' => $fichier,\n\t\t\t':corrige' => $corrige,\n\t\t\t':date' => $date,\n\t\t\t':classe' => $classe,\n\t\t\t':photo' => $photo,\n\t\t\t':type' => $type,\n\t\t\t':categorie' => $categorie,\n\t\t\t':valide' => $valide\n\t\t);\n\t\t$rs = $this->NonQuery($req,$params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'ajout des polycopi\u00e9s ..\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function afficherRowDossierClientModeTransportModeLicence2($id_cli, $id_mod_trans, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $commodity,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$premiere_entree, $nombre_dossier_par_page, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$id_march=NULL, $statut=NULL, $num_lic=NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t$cleared=NULL){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$compteur = $premiere_entree;\n\t\t\t$bg = '';\n\t\t\t$style = '';\n\n\t\t\t/*echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    num_lic = '.$num_lic;*/\n\t\t\t\t//echo '
    -------'.$sqlStatus;\n\n\t\t\t$sql1 = \"\";\n\t\t\t$sqlOrder = \"\";\n\t\t\t$sqlIdMarch = \"\";\n\t\t\t$sqlStatus = \"\";\n\t\t\t$sqlLicence = \"\";\n\t\t\t$sqlCleared = \"\";\n\n\t\t\tif (isset($commodity) && ($commodity != '')) {\n\t\t\t\t$sql1 = ' AND d.commodity = \"'.$commodity.'\"';\n\t\t\t}\n\t\t\tif ($id_mod_lic == '1') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.id_dos DESC';\n\t\t\t}else if ($id_mod_lic == '2') {\n\t\t\t\t$sqlOrder = ' ORDER BY d.ref_dos DESC';\n\t\t\t}\n\n\t\t\tif (isset($id_march) && ($id_march != '')) {\n\t\t\t\t$sqlIdMarch = ' AND d.id_march = '.$id_march;\n\t\t\t}\n\n\t\t\tif (isset($statut) && ($statut != '')) {\n\t\t\t\t$sqlStatus = ' AND d.statut = \"'.$statut.'\"';\n\t\t\t}\n\n\t\t\tif (isset($num_lic) && ($num_lic != '')) {\n\t\t\t\t$sqlLicence = ' AND d.num_lic = \"'.$num_lic.'\"';\n\t\t\t}\n\n\t\t\tif (isset($cleared) && ($cleared != '')) {\n\t\t\t\t$sqlCleared = ' AND d.cleared = \"'.$cleared.'\"';\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare(\"SELECT d.ref_dos AS ref_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPPER(cl.nom_cli) AS nom_cli,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.ref_fact AS ref_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fob AS fob_dos,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.fret AS fret,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.assurance AS assurance,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.autre_frais AS autre_frais,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.num_lic AS num_lic,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.montant_decl AS montant_decl,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.*,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.supplier AS fournisseur,\n\t\t\t\t\t\t\t\t\t\t\t\t\ts.nom_site AS nom_site,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_in AS dgda_in_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.dgda_out AS dgda_out_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.custom_deliv AS custom_deliv_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\td.arrival_date AS arrival_date_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.dgda_out, d.dgda_in) AS dgda_delay,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDATEDIFF(d.custom_deliv, d.arrival_date) AS arrival_deliver_delay\n\t\t\t\t\t\t\t\t\t\t\t\tFROM dossier d, client cl, site s, mode_transport mt\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE d.id_cli = cl.id_cli\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND cl.id_cli = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_site = s.id_site\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_trans = mt.id_mod_trans\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND mt.id_mod_trans = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND d.id_mod_lic = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlIdMarch\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlLicence\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sqlCleared\n\t\t\t\t\t\t\t\t\t\t\t\t\t$sql1\n\t\t\t\t\t\t\t\t\t\t\t\t$sqlOrder\n\t\t\t\t\t\t\t\t\t\t\t\tLIMIT $premiere_entree, $nombre_dossier_par_page\");\n\t\t\t$requete-> execute(array($entree['id_cli'], $entree['id_mod_trans'], $entree['id_mod_lic']));\n\t\t\twhile ($reponse = $requete-> fetch()) {\n\t\t\t\t$compteur++;\n\t\t\t\t$bg = \"\";\n\t\t\t\t$color='';\n\t\t\t\t$class = \"\";\n\n\t\t\t\tif ($reponse['cleared'] == '1') {\n\t\t\t\t\t$style = \"style='color: blue;'\";\n\t\t\t\t\t$color = \"color: blue;\";\n\t\t\t\t\t$class = \"bg-primary\";\n\t\t\t\t}else if ($reponse['cleared'] == '2') {\n\t\t\t\t\t$style = \"style='color: red;'\";\n\t\t\t\t\t$color = \"color: red;\";\n\t\t\t\t\t$class = \"bg-danger\";\n\t\t\t\t}else{\n\t\t\t\t\t$style = \"\";\n\t\t\t\t\t$color = \"color: black;\";\n\t\t\t\t\t$class = \"bg-light\";\n\t\t\t\t}\n\n\t\t\t\t$date_exp = $this-> getLastEpirationLicence($reponse['num_lic']);\n\t\t\t\t$supplier = $this-> getLicence($reponse['num_lic'])['fournisseur'];\n\n\t\t\t\tif (isset($supplier)) {\n\t\t\t\t\t$reponse['fournisseur'] = $supplier;\n\t\t\t\t}\n\n\t\t\t\t\n\t\t\t\t/*$ref_dos, $id_cli, $ref_fact, $fob, \n\t\t\t\t$fret, $assurance, $autre_frais, $num_lic, \n\t\t\t\t$id_mod_lic, $id_march*/\n\n\t\t\t?>\n\t\t\t\t\" value=\"\">\n\t\t\t\t\" >\n\t\t\t\t\t col_1 \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black;\" >\n\t\t\t\t\t col_6 \" style=\" border-right: 1px solid black; vertical-align: middle; text-align: left; padding: 0.6rem; border-top: 1px solid black; \">\n\t\t\t\t\t afficherRowTableau($id_mod_lic, $id_cli, $id_mod_trans, $reponse['id_dos'], $compteur);\n\t\t\t\t\t\t/*if ($id_mod_trans == '1') {\n\t\t\t\t\t\t\tinclude('importRouteRow.php');\n\t\t\t\t\t\t}else if ($id_mod_trans == '3') {\n\t\t\t\t\t\t\tinclude('importAirRow.php');\n\t\t\t\t\t\t}*/\n\t\t\t\t\t?>\n\t\t\t\t\n\t\t\t closeCursor();\n\t\t\t?>\n\t\t\t\n\t\t\t\t\">\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\tgetPayload();\n\n if (!empty($events->getEvent())) {\n if (empty($events->getPayload())) {\n $events->setPayload($responsePayload);\n }\n\n /**\n * Trigger functions.\n */\n $queueForFunctions\n ->from($events)\n ->trigger();\n\n /**\n * Trigger webhooks.\n */\n $events\n ->setClass(Event::WEBHOOK_CLASS_NAME)\n ->setQueue(Event::WEBHOOK_QUEUE_NAME)\n ->trigger();\n\n /**\n * Trigger realtime.\n */\n if ($project->getId() !== 'console') {\n $allEvents = Event::generateEvents($events->getEvent(), $events->getParams());\n $payload = new Document($events->getPayload());\n\n $db = $events->getContext('database');\n $collection = $events->getContext('collection');\n $bucket = $events->getContext('bucket');\n\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $payload,\n project: $project,\n database: $db,\n collection: $collection,\n bucket: $bucket,\n );\n\n Realtime::send(\n projectId: $target['projectId'] ?? $project->getId(),\n payload: $events->getPayload(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles'],\n options: [\n 'permissionsChanged' => $target['permissionsChanged'],\n 'userId' => $events->getParam('userId')\n ]\n );\n }\n }\n\n $route = $utopia->getRoute();\n $requestParams = $route->getParamsValues();\n\n /**\n * Audit labels\n */\n $pattern = $route->getLabel('audits.resource', null);\n if (!empty($pattern)) {\n $resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);\n if (!empty($resource) && $resource !== $pattern) {\n $audits->setResource($resource);\n }\n }\n\n if (!$user->isEmpty()) {\n $audits->setUser($user);\n }\n\n if (!empty($audits->getResource()) && !empty($audits->getUser()->getId())) {\n /**\n * audits.payload is switched to default true\n * in order to auto audit payload for all endpoints\n */\n $pattern = $route->getLabel('audits.payload', true);\n if (!empty($pattern)) {\n $audits->setPayload($responsePayload);\n }\n\n foreach ($events->getParams() as $key => $value) {\n $audits->setParam($key, $value);\n }\n $audits->trigger();\n }\n\n if (!empty($deletes->getType())) {\n $deletes->trigger();\n }\n\n if (!empty($database->getType())) {\n $database->trigger();\n }\n\n /**\n * Cache label\n */\n $useCache = $route->getLabel('cache', false);\n if ($useCache) {\n $resource = $resourceType = null;\n $data = $response->getPayload();\n\n if (!empty($data['payload'])) {\n $pattern = $route->getLabel('cache.resource', null);\n if (!empty($pattern)) {\n $resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);\n }\n\n $pattern = $route->getLabel('cache.resourceType', null);\n if (!empty($pattern)) {\n $resourceType = $parseLabel($pattern, $responsePayload, $requestParams, $user);\n }\n\n $key = md5($request->getURI() . implode('*', $request->getParams()) . '*' . APP_CACHE_BUSTER);\n $data = json_encode([\n 'resourceType' => $resourceType,\n 'resource' => $resource,\n 'contentType' => $response->getContentType(),\n 'payload' => base64_encode($data['payload']),\n ]) ;\n\n $signature = md5($data);\n $cacheLog = Authorization::skip(fn () => $dbForProject->getDocument('cache', $key));\n $accessedAt = $cacheLog->getAttribute('accessedAt', '');\n $now = DateTime::now();\n if ($cacheLog->isEmpty()) {\n Authorization::skip(fn () => $dbForProject->createDocument('cache', new Document([\n '$id' => $key,\n 'resource' => $resource,\n 'accessedAt' => $now,\n 'signature' => $signature,\n ])));\n } elseif (DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) {\n $cacheLog->setAttribute('accessedAt', $now);\n Authorization::skip(fn () => $dbForProject->updateDocument('cache', $cacheLog->getId(), $cacheLog));\n }\n\n if ($signature !== $cacheLog->getAttribute('signature')) {\n $cache = new Cache(\n new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())\n );\n $cache->save($key, $data);\n }\n }\n }\n\n if (\n App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled'\n && $project->getId()\n && !empty($route->getLabel('sdk.namespace', null))\n ) { // Don't calculate console usage on admin mode\n $metric = $route->getLabel('usage.metric', '');\n $usageParams = $route->getLabel('usage.params', []);\n\n if (!empty($metric)) {\n $usage->setParam($metric, 1);\n foreach ($usageParams as $param) {\n $param = $parseLabel($param, $responsePayload, $requestParams, $user);\n $parts = explode(':', $param);\n if (count($parts) != 2) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Usage params not properly set');\n }\n $usage->setParam($parts[0], $parts[1]);\n }\n }\n\n $fileSize = 0;\n $file = $request->getFiles('file');\n if (!empty($file)) {\n $fileSize = (\\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size'];\n }\n\n $usage\n ->setParam('project.{scope}.network.inbound', $request->getSize() + $fileSize)\n ->setParam('project.{scope}.network.outbound', $response->getSize())\n ->submit();\n }\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function updateEligibilityRecord($id, $status, $request_json, $response_json, $updateLastChecked, $responseMessage, $raw271, $eligibility_json, $individual_json)\n {\n $sql = \"UPDATE mod_claimrev_eligibility SET status = ? \";\n\n $sqlarr = array($status);\n if ($updateLastChecked) {\n $sql = $sql . \",last_checked = NOW() \";\n }\n if ($response_json != null) {\n $sql = $sql . \" ,response_json = ?\";\n array_push($sqlarr, $response_json);\n }\n if ($request_json != null) {\n $sql = $sql . \" ,request_json = ?\";\n array_push($sqlarr, $request_json);\n }\n if ($responseMessage != null) {\n $sql = $sql . \" ,response_message = ?\";\n array_push($sqlarr, $responseMessage);\n }\n if ($raw271 != null) {\n $sql = $sql . \" ,raw271 = ? \";\n array_push($sqlarr, $raw271);\n }\n if ($eligibility_json != null) {\n $sql = $sql . \" ,eligibility_json = ?\";\n array_push($sqlarr, $eligibility_json);\n }\n if ($individual_json != null) {\n $sql = $sql . \" ,individual_json = ?\";\n array_push($sqlarr, $individual_json);\n }\n\n $sql = $sql . \" WHERE id = ?\";\n array_push($sqlarr, $id);\n sqlStatement($sql, $sqlarr);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function get_linksbyname_withrating($cat_name = \"noname\", $before = '', $after = '
    ', $between = \" \",\n\t\t\t\t\t\t\t\t\t$show_images = true, $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\tget_linksbyname($cat_name, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated);\n}", "smellKey": "S107", "smellId": null, "repo": "jpbarraca_sqli-wordpress", "language": "php"} {"function": "public function __construct(Route $router, RuleGroup $parent, $name, $rule, $route, $method = '*', $option = [], $pattern = [])\n {\n $this->router = $router;\n $this->parent = $parent;\n $this->name = $name;\n $this->route = $route;\n $this->method = $method;\n $this->option = $option;\n $this->pattern = $pattern;\n\n $this->setRule($rule);\n\n if (!empty($option['cross_domain'])) {\n $this->router->setCrossDomainRule($this, $method);\n }\n }", "smellKey": "S107", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public static function updateItemOnEvent(\n $toobserve,\n $toupdate,\n $url,\n $parameters = [],\n $events = [\"change\"],\n $minsize = -1,\n $buffertime = -1,\n $forceloadfor = [],\n $display = true\n ) {\n\n $output = \"\";\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(\n\t\t?string $outCodEscola,\n\t\t?string $outDescNomeAbrevEscola,\n\t\t?string $outCodTipoEnsino,\n\t\t?string $outDescTipoEnsino,\n\t\t?string $outAnoLetivo,\n\t\t?string $outNumClasse,\n\t\t?string $outCodSerieAno,\n\t\t?string $outTurma,\n\t\t?string $outCodTurno,\n\t\t?string $outDescricaoTurno,\n\t\t?string $outCodHabilitacao,\n\t\t?string $outCodTipoClasse,\n\t\t?string $outNumSala,\n\t\t?string $outHorarioInicio,\n\t\t?string $outHorarioFim,\n\t\t?string $outQtdAtual,\n\t\t?string $outQtdDigitados,\n\t\t?string $outQtdEvadidos,\n\t\t?string $outQtdNCom,\n\t\t?string $outQtdOutros,\n\t\t?string $outQtdTransferidos,\n\t\t?string $outQtdRemanejados,\n\t\t?string $outQtdCessados,\n\t\t?string $outQtdReclassificados,\n\t\t?string $outCapacidadeFisicaMax,\n\t\t?string $outDataInicioAula,\n\t\t?string $outDataFimAula,\n\t\t?array $outAlunos,\n\t\t?string $outErro,\n\t\t?string $outProcessoID\n\t) {\n\t\t$this->outCodEscola = $outCodEscola;\n\t\t$this->outDescNomeAbrevEscola = $outDescNomeAbrevEscola;\n\t\t$this->outCodTipoEnsino = $outCodTipoEnsino;\n\t\t$this->outDescTipoEnsino = $outDescTipoEnsino;\n\t\t$this->outAnoLetivo = $outAnoLetivo;\n\t\t$this->outNumClasse = $outNumClasse;\n\t\t$this->outCodSerieAno = $outCodSerieAno;\n\t\t$this->outTurma = $outTurma;\n\t\t$this->outCodTurno = $outCodTurno;\n\t\t$this->outDescricaoTurno = $outDescricaoTurno;\n\t\t$this->outCodHabilitacao = $outCodHabilitacao;\n\t\t$this->outCodTipoClasse = $outCodTipoClasse;\n\t\t$this->outNumSala = $outNumSala;\n\t\t$this->outHorarioInicio = $outHorarioInicio;\n\t\t$this->outHorarioFim = $outHorarioFim;\n\t\t$this->outQtdAtual = $outQtdAtual;\n\t\t$this->outQtdDigitados = $outQtdDigitados;\n\t\t$this->outQtdEvadidos = $outQtdEvadidos;\n\t\t$this->outQtdNCom = $outQtdNCom;\n\t\t$this->outQtdOutros = $outQtdOutros;\n\t\t$this->outQtdTransferidos = $outQtdTransferidos;\n\t\t$this->outQtdRemanejados = $outQtdRemanejados;\n\t\t$this->outQtdCessados = $outQtdCessados;\n\t\t$this->outQtdReclassificados = $outQtdReclassificados;\n\t\t$this->outCapacidadeFisicaMax = $outCapacidadeFisicaMax;\n\t\t$this->outDataInicioAula = $outDataInicioAula;\n\t\t$this->outDataFimAula = $outDataFimAula;\n\t\t$this->outAlunos = $outAlunos;\n\t\t$this->outErro = $outErro;\n\t\t$this->outProcessoID = $outProcessoID;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct(\n\t\t$parameters,\n\t\t?IManager $encryptionManager = null,\n\t\t?Util $util = null,\n\t\t?LoggerInterface $logger = null,\n\t\t?IFile $fileHelper = null,\n\t\t$uid = null,\n\t\t?IStorage $keyStorage = null,\n\t\t?Update $update = null,\n\t\t?Manager $mountManager = null,\n\t\t?ArrayCache $arrayCache = null\n\t) {\n\t\t$this->mountPoint = $parameters['mountPoint'];\n\t\t$this->mount = $parameters['mount'];\n\t\t$this->encryptionManager = $encryptionManager;\n\t\t$this->util = $util;\n\t\t$this->logger = $logger;\n\t\t$this->uid = $uid;\n\t\t$this->fileHelper = $fileHelper;\n\t\t$this->keyStorage = $keyStorage;\n\t\t$this->unencryptedSize = [];\n\t\t$this->update = $update;\n\t\t$this->mountManager = $mountManager;\n\t\t$this->arrayCache = $arrayCache;\n\t\t$this->encryptedPaths = new CappedMemoryCache();\n\t\tparent::__construct($parameters);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function generate_select_list(\n $tag_name,\n $list_id,\n $currvalue,\n $title,\n $empty_name = ' ',\n $class = '',\n $onchange = '',\n $tag_id = '',\n $custom_attributes = null,\n $multiple = false, // new #10\n $backup_list = '', // new #11\n $ignore_default = false,\n $include_inactive = false,\n $tabIndex = false\n) {\n $attributes = [];\n $_options = [];\n $_metadata = [];\n\n $tag_name_esc = attr($tag_name);\n\n $attributes['name'] = ($multiple) ? $tag_name_esc . \"[]\" : $tag_name_esc;\n\n if ($tabIndex !== false) {\n $attributes['tabindex'] = attr($tabIndex);\n }\n\n if ($multiple) {\n $attributes['multiple'] = \"multiple\";\n }\n\n $attributes['id'] = attr($tag_name);\n $attributes['class'] = (!empty($class)) ? \"form-control \" . attr($class) : \"form-control\";\n\n if ($onchange) {\n $attributes['onchange'] = $onchange;\n }\n\n if ($custom_attributes != null && is_array($custom_attributes)) {\n foreach ($custom_attributes as $attr => $val) {\n if (isset($custom_attributes [$attr])) {\n $attributes[attr($attr)] = attr($val);\n }\n }\n }\n\n $attributes['title'] = attr($title);\n\n $selectEmptyName = xlt($empty_name);\n if ($empty_name) {\n preg_match_all('/select2/m', ($class ?? ''), $matches, PREG_SET_ORDER, 0);\n if (array_key_exists('placeholder', $attributes) && count($matches) > 0) {\n // We have a placeholder attribute as well as a select2 class indicating there\n // should be provided a truly empty option.\n $_options[] = [];\n } else {\n if ($multiple && !empty($currvalue)) {\n $_options[] = [\n 'label' => $selectEmptyName,\n 'value' => '',\n 'isSelected' => false,\n ];\n } else {\n $_options[] = [\n 'label' => $selectEmptyName,\n 'value' => '',\n 'isSelected' => true,\n ];\n }\n }\n }\n\n $got_selected = false;\n\n for ($active = 1; $active == 1 || ($active == 0 && $include_inactive); --$active) {\n $_optgroup = ($include_inactive) ? true : false;\n\n // List order depends on language translation options.\n // (Note we do not need to worry about the list order in the algorithm\n // after the below code block since that is where searches for exceptions\n // are done which include inactive items or items from a backup\n // list; note these will always be shown at the bottom of the list no matter the\n // chosen order.)\n // This block should be migrated to the ListService but the service currently does not translate or offer a sort option.\n $lang_id = empty($_SESSION['language_choice']) ? '1' : $_SESSION['language_choice'];\n // sort by title\n $order_by_sql = ($GLOBALS['gb_how_sort_list'] == '0') ? \"seq, title\" : \"title, seq\";\n if (!$GLOBALS['translate_lists']) {\n // do not translate\n $lres = sqlStatement(\"SELECT * FROM list_options WHERE list_id = ? AND activity = ? ORDER BY $order_by_sql\", [$list_id, $active]);\n } else {\n // do translate\n $order_by_sql = str_replace(\"seq\", \"lo.seq\", $order_by_sql);\n $sql = \"SELECT lo.option_id, lo.is_default,\n COALESCE((SELECT ld.definition FROM lang_constants AS lc, lang_definitions AS ld\n WHERE lc.constant_name = lo.title AND ld.cons_id = lc.cons_id AND ld.lang_id = ? AND ld.definition IS NOT NULL\n AND ld.definition != ''\n LIMIT 1), lo.title) AS title\n FROM list_options AS lo\n WHERE lo.list_id = ? AND lo.activity = ?\n ORDER BY {$order_by_sql}\";\n $lres = sqlStatement($sql, [$lang_id, $list_id, $active]);\n }\n\n // Populate the options array with pertinent values\n\n while ($lrow = sqlFetchArray($lres)) {\n $selectedValues = explode(\"|\", $currvalue ?? '');\n $isSelected = false;\n\n $optionValue = attr($lrow ['option_id']);\n\n if (\n (strlen($currvalue ?? '') == 0 && $lrow['is_default'] && !$ignore_default) ||\n (strlen($currvalue ?? '') > 0 && in_array($lrow['option_id'], $selectedValues))\n ) {\n $got_selected = true;\n $isSelected = true;\n }\n\n // Already has been translated above (if applicable), so do not need to use\n // the xl_list_label() function here\n $optionLabel = text($lrow ['title']);\n\n $_tmp = [\n 'label' => $optionLabel,\n 'value' => $optionValue,\n 'isSelected' => $isSelected,\n 'isActive' => $include_inactive,\n ];\n\n if ($_optgroup) {\n $_tmp['optGroupOptions'] = $_tmp;\n $_tmp['optgroupLabel'] = ($active) ? xla('Active') : xla('Inactive');\n }\n\n $_options[] = $_tmp;\n }\n } // end $active loop\n\n /*\n To show the inactive item in the list if the value is saved to database\n */\n if (!$got_selected && strlen($currvalue ?? '') > 0) {\n $_sql = \"SELECT * FROM list_options WHERE list_id = ? AND activity = 0 AND option_id = ? ORDER BY seq, title\";\n $lres_inactive = sqlStatement($_sql, [$list_id, $currvalue]);\n $lrow_inactive = sqlFetchArray($lres_inactive);\n if (!empty($lrow_inactive['option_id'])) {\n $optionValue = htmlspecialchars($lrow_inactive['option_id'], ENT_QUOTES);\n $_options[] = [\n 'label' => htmlspecialchars(xl_list_label($lrow_inactive['title']), ENT_NOQUOTES),\n 'value' => $optionValue,\n 'isSelected' => true,\n 'isActive' => false,\n ];\n $got_selected = true;\n }\n }\n\n if (!$got_selected && strlen($currvalue ?? '') > 0 && !$multiple) {\n $list_id = $backup_list;\n $lrow = sqlQuery(\"SELECT title FROM list_options WHERE list_id = ? AND option_id = ?\", [$list_id, $currvalue]);\n\n $_options[] = [\n 'value' => attr($currvalue),\n 'selected' => true,\n 'label' => ($lrow > 0 && !empty($backup_list)) ? text(xl_list_label($lrow['title'])) : text($currvalue),\n ];\n if (empty($lrow) && empty($backup_list)) {\n $metadata['error'] = [\n 'title' => xlt('Please choose a valid selection from the list.'),\n 'text' => xlt('Fix this'),\n ];\n }\n } elseif (!$got_selected && strlen($currvalue ?? '') > 0 && $multiple) {\n //if not found in main list, display all selected values that exist in backup list\n $list_id = $backup_list;\n\n $got_selected_backup = false;\n if (!empty($backup_list)) {\n $lres_backup = sqlStatement(\"SELECT * FROM list_options WHERE list_id = ? AND activity = 1 ORDER BY seq, title\", array($list_id));\n while ($lrow_backup = sqlFetchArray($lres_backup)) {\n $selectedValues = explode(\"|\", $currvalue);\n $optionValue = attr($lrow_backup['option_id']);\n\n if (in_array($lrow_backup ['option_id'], $selectedValues)) {\n $_options[] = [\n 'label' => text(xl_list_label($lrow_backup['title'])),\n 'value' => $optionValue,\n 'isSelected' => true,\n ];\n $got_selected_backup = true;\n }\n }\n }\n\n if (!$got_selected_backup) {\n $selectedValues = explode(\"|\", $currvalue);\n foreach ($selectedValues as $selectedValue) {\n $_options[] = [\n 'label' => text($selectedValue),\n 'value' => attr($selectedValue),\n 'isSelected' => true,\n ];\n }\n\n $_metadata['error'] = [\n 'title' => xlt('Please choose a valid selection from the list.'),\n 'text' => xlt('Fix this'),\n ];\n }\n }\n\n $_parsedOptions = [];\n $_og = false;\n foreach ($_options as $o) {\n $_isOG = (array_key_exists('optGroupOptions', $o) && count($o['optGroupOptions']) > 0) ? true : false;\n $_currOG = $o['optgroupLabel'] ?? false;\n\n // Render only if the current optgroup label is not triple equal to the previous label\n if ($_og !== $_currOG) {\n $_parsedOptions[] = \"\";\n }\n\n // Must have an opt group and it must be different than the previous\n if ($_isOG && $_og !== $_currOG) {\n $_parsedOptions[] = sprintf('', $_currOG);\n }\n\n $_parsedOptions[] = _create_option_element($o);\n\n $_og = $_currOG;\n }\n $optionString = implode(\"\\n\", $_parsedOptions);\n\n $_parsedAttributes = [];\n foreach ($attributes as $attr => $val) {\n $_parsedAttributes[] = sprintf('%s=\"%s\"', $attr, $val);\n }\n $attributeString = implode(\"\\n\", $_parsedAttributes);\n\n $_selectString = sprintf(\"\", $attributeString, $optionString);\n $output[] = $_selectString;\n\n if (array_key_exists('error', $_metadata)) {\n $_errorString = sprintf(\"%s\", $_metadata['error']['title'], $metadata['error']['text']);\n $output[] = $_errorString;\n }\n\n return implode(\"\", $output);\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n TranslatorInterface $translator,\n DatasetFactory $datasetFactory,\n UrlGeneratorInterface $urlGenerator,\n EventDispatcherInterface $eventDispatcher,\n FormFactoryInterface $formFactory,\n PermissionResolver $permissionResolver,\n LanguageService $languageService\n ) {\n parent::__construct($twig, $translator, $eventDispatcher);\n\n $this->datasetFactory = $datasetFactory;\n $this->formFactory = $formFactory;\n $this->urlGenerator = $urlGenerator;\n $this->permissionResolver = $permissionResolver;\n $this->languageService = $languageService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function makeSelectElement(\n $name,\n $fieldName,\n $prefix = '-',\n $selected = '',\n $addEmptyOption = false,\n $key = 0,\n $extra = '',\n $caption = ''\n ) {\n xoops_load('xoopsformselect');\n $element = new XoopsFormSelect($caption, $name, $selected);\n $element->setExtra($extra);\n\n if (false !== (bool)$addEmptyOption) {\n $element->addOption('0', ' ');\n }\n $this->addSelectOptions($element, $fieldName, $key, $prefix);\n\n return $element;\n }", "smellKey": "S107", "smellId": null, "repo": "mambax7_XoopsCore25", "language": "php"} {"function": "public function createRuntime(\n string $deploymentId,\n string $projectId,\n string $source,\n string $image,\n string $version,\n bool $remove = false,\n string $entrypoint = '',\n string $destination = '',\n array $variables = [],\n string $command = null,\n ) {\n $runtimeId = \"$projectId-$deploymentId\";\n $route = \"/runtimes\";\n $params = [\n 'runtimeId' => $runtimeId,\n 'source' => $source,\n 'destination' => $destination,\n 'image' => $image,\n 'entrypoint' => $entrypoint,\n 'variables' => $variables,\n 'remove' => $remove,\n 'command' => $command,\n 'cpus' => $this->cpus,\n 'memory' => $this->memory,\n 'version' => $version,\n ];\n\n $timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);\n\n $response = $this->call(self::METHOD_POST, $route, [ 'x-opr-runtime-id' => $runtimeId ], $params, true, $timeout);\n\n $status = $response['headers']['status-code'];\n if ($status >= 400) {\n $message = \\is_string($response['body']) ? $response['body'] : $response['body']['message'];\n throw new \\Exception($message, $status);\n }\n\n return $response['body'];\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function modifIntervenantPublicSansCode($num, $nom, $prenom, $date_naissance, $lieu_naissance,$tel, $adresse, $cp, $ville,$email,$diplome,$numsecu,$nationalite)\n\t{\n\t\t$req = \"UPDATE `intervenants` SET `NOM`='$nom',`PRENOM`='$prenom',`EMAIL`='$email',`TELEPHONE`='$tel',`ADRESSE_POSTALE`='$adresse',`CODE_POSTAL`='$cp',`VILLE`='$ville',`DIPLOME`='$diplome',`DATE_DE_NAISSANCE`='$date_naissance',`LIEU_DE_NAISSANCE`='$lieu_naissance',`NATIONALITE`='$nationalite',`SECURITE_SOCIALE`='$numsecu' WHERE `ID_INTERVENANT`=$num\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'agent dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);\n\t\t\t$s = '';\n\t\t\tforeach ($values as $value) {\n\t\t\t\t$s .= \"'\".addslashes($value).\"',\";\n\t\t\t}\n\t\t\t$this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1).\"]);\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t// get annotation data\n\t\t$popt = $this->getAnnotOptFromJSProp($prop);\n\t\t// set additional default values\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Ch';\n\t\t$opt['t'] = $name;\n\t\t$opt['opt'] = $values;\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function makeledgerfromjournal($j, $start, $order, $types, $sn, &$anstypes, &$answer, &$questions, &$showanswer, &$displayformat, &$answerboxsize) {\n\t$out = ''; $sa = '';\n\t$acts = array();\n\t$dates = array();\n\t$hasdecimals = false;\n\t$maxsizeentry = 1;\n\tforeach ($j as $jd) {\n if (isset($jd['date'])) {\n\t\t $dates[] = $jd['date'];\n }\n if (!isset($jd['debits'])) { $jd['debits'] = []; }\n if (!isset($jd['credits'])) { $jd['credits'] = []; }\n\t\tfor ($i=0;$i$maxsizeentry) { $maxsizeentry = $sl;}\n\t\t}\n\t\tfor ($i=0;$i$maxsizeentry) { $maxsizeentry = $sl;}\n\t\t}\n\t}\n\t$curbal = $start;\n\tforeach ($order as $idx=>$o) {\n\t\t$out .= '';\n\t\t$sa .= '
    '.$o.'
    DateDebitsCreditsBalance
    ';\n\t\t$out .= '';\n\t\t$sa .= '';\n\t\tforeach ($acts[$o] as $a) {\n\t\t\t$out .= '';\n\t\t\t$sa .= '';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'select'; $questions[$sn] = $dates; $answer[$sn] = $a[0];\n\t\t\t$sn++;\n\t\t\tif ($a[1]=='d') {\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = $a[2]; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t\t$sn++;\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t\t$sn++;\n\t\t\t\tif ($types[$idx]==1) {\n\t\t\t\t\t$curbal[$idx] += $a[2];\n\t\t\t\t} else {\n\t\t\t\t\t$curbal[$idx] -= $a[2];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t\t$sn++;\n\t\t\t\t$out .= '';\n\t\t\t\t$sa .= '';\n\t\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright';$answer[$sn] = $a[2]; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t\t$sn++;\n\t\t\t\tif ($types[$idx]==1) {\n\t\t\t\t\t$curbal[$idx] -= $a[2];\n\t\t\t\t} else {\n\t\t\t\t\t$curbal[$idx] += $a[2];\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out .= '';\n\t\t\t$sa .= '';\n\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = $curbal[$idx]; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t$sn++;\n\t\t}\n\t\tfor ($j=count($acts[$o]);$j';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'select'; $questions[$sn] = $dates; $answer[$sn] = '';\n\t\t\t$sn++;\n\t\t\t$out .= '';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t$sn++;\n\t\t\t$out .= '';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t$sn++;\n\t\t\t$out .= '';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizeentry;\n\t\t\t$sn++;\n\t\t}\n\t\t$out .= '
    '.$o.'
    DateDebitsCreditsBalance
    Beg. Bal.'.($hasdecimals?number_format($start[$idx],2,'.',','):number_format($start[$idx])).'
    Beg. Bal.'.($hasdecimals?number_format($start[$idx],2,'.',','):number_format($start[$idx])).'
    [AB'.$sn.']
    '.$a[0].'[AB'.$sn.']'.($hasdecimals?number_format($a[2],2,'.',','):number_format($a[2])).'[AB'.$sn.'][AB'.$sn.'][AB'.$sn.']'.($hasdecimals?number_format($a[2],2,'.',','):number_format($a[2])).'[AB'.$sn.']
    '.($hasdecimals?number_format($curbal[$idx],2,'.',','):number_format($curbal[$idx])).'
    [AB'.$sn.'][AB'.$sn.'][AB'.$sn.']

    ';\n\t\t$sa .= '
    ';\n\t}\n\t$showanswer .= $sa.'

     

    ';\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function CalcPlot3Dquerystring($funcs, $xmin, $xmax, $ymin, $ymax, $zmin, $zmax, $xscl, $yscl, $zscl, $zclipmin, $zclipmax, $showbox, $scaleaxes=false) {\n if ($zclipmin===null) {\n\t\t$zclipmin = $zmin - .5*($zmax-$zmin);\n\t}\n\tif ($zclipmax===null) {\n\t\t$zclipmax = $zmax + .5*($zmax-$zmin);\n\t}\n\t$out = array();\n\tif (!is_array($funcs)) {\n\t\t$funcs = array($funcs);\n\t}\n\tforeach ($funcs as $func) {\n\t\t$out[] = CalcPlot3DprepFunc($func, $xmin, $xmax, $ymin, $ymax, $zmin, $zmax);\n\t}\n\t$win = \"type=window;xmin=$xmin;xmax=$xmax;ymin=$ymin;ymax=$ymax;zmin=$zmin;zmax=$zmax;\";\n\t$win .= \"xscale=$xscl;yscale=$yscl;zscale=$zscl;zcmin=$zclipmin;zcmax=$zclipmax\";\n $win .= \";showbox=\" . ($showbox ? 'true' : 'false').';';\n $xd = $xmax-$xmin;\n $yd = $ymax-$ymin;\n $zd = $zmax-$zmin;\n $maxwidth = max($xd, $yd, $zd);\n if ($scaleaxes) {\n $xf = $maxwidth/$xd;\n $yf = $maxwidth/$yd;\n $zf = $maxwidth/$zd;\n $win .= \"xscalefactor=$xf;yscalefactor=$yf;zscalefactor=$zf;\";\n }\n $zoom = 0.0000055/atan(0.00000198669*$maxwidth);\n $win .= ';zoom='.$zoom;\n\t$out[] = $win;\n\treturn implode('&', array_map('Sanitize::encodeUrlParam', $out));\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function addBilling2($encounter, $code_type, $code, $code_text, string $modifier = null, string $units = null, string $fee = null, $justify)\n{\n if (!$fee) {\n $fee = \"0.00\";\n }\n $justify_string = '';\n if ($justify) {\n //trim eahc entry\n foreach ($justify as $temp_justify) {\n $justify_trimmed[] = trim($temp_justify);\n }\n\n //format it\n $justify_string = implode(\":\", $justify_trimmed) . \":\";\n }\n\n // set to authorize billing codes as default - bm\n // could place logic here via acls to control who\n // can authorize as a feature in the future\n $authorized = 1;\n\n $sql = \"insert into billing (date, encounter, code_type, code, code_text, pid, authorized, user, groupname,activity,billed,provider_id,modifier,units,fee,justify) values (NOW(), ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?, ?, ?, ?)\";\n\n return sqlInsert($sql, array($_SESSION['encounter'], $code_type, $code, $code_text, $_SESSION['pid'], $authorized, $_SESSION['authUserID'], $_SESSION['authProvider'], $_SESSION['authUserID'], $modifier, $units, $fee, $justify_string));\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private static function result($xi, $yi, $columns, $lines, $mw, $mh, $cos, $sin)\n {\n self::_rotate(0, 0, $cos, $sin, $x1, $y1);\n self::_rotate($columns * $mw, 0, $cos, $sin, $x2, $y2);\n self::_rotate($columns * $mw, $lines * $mh, $cos, $sin, $x3, $y3);\n self::_rotate(0, $lines * $mh, $cos, $sin, $x4, $y4);\n\n return array(\n 'width' => $columns * $mw,\n 'height' => $lines * $mh,\n 'p1' => array(\n 'x' => $xi + $x1,\n 'y' => $yi + $y1\n ),\n 'p2' => array(\n 'x' => $xi + $x2,\n 'y' => $yi + $y2\n ),\n 'p3' => array(\n 'x' => $xi + $x3,\n 'y' => $yi + $y3\n ),\n 'p4' => array(\n 'x' => $xi + $x4,\n 'y' => $yi + $y4\n )\n );\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n $data = [],\n $path = null,\n string $name = null,\n array $requirements = [],\n array $options = [],\n array $defaults = [],\n string $host = null,\n $methods = [],\n $schemes = [],\n string $condition = null,\n int $priority = null,\n string $locale = null,\n string $format = null,\n bool $utf8 = null,\n bool $stateless = null,\n string $env = null\n ) {\n if (\\is_string($data)) {\n $data = ['path' => $data];\n } elseif (!\\is_array($data)) {\n throw new \\TypeError(sprintf('\"%s\": Argument $data is expected to be a string or array, got \"%s\".', __METHOD__, get_debug_type($data)));\n } elseif ([] !== $data) {\n $deprecation = false;\n foreach ($data as $key => $val) {\n if (\\in_array($key, ['path', 'name', 'requirements', 'options', 'defaults', 'host', 'methods', 'schemes', 'condition', 'priority', 'locale', 'format', 'utf8', 'stateless', 'env', 'value'])) {\n $deprecation = true;\n }\n }\n\n if ($deprecation) {\n trigger_deprecation('symfony/routing', '5.3', 'Passing an array as first argument to \"%s\" is deprecated. Use named arguments instead.', __METHOD__);\n } else {\n $localizedPaths = $data;\n $data = ['path' => $localizedPaths];\n }\n }\n if (null !== $path && !\\is_string($path) && !\\is_array($path)) {\n throw new \\TypeError(sprintf('\"%s\": Argument $path is expected to be a string, array or null, got \"%s\".', __METHOD__, get_debug_type($path)));\n }\n\n $data['path'] = $data['path'] ?? $path;\n $data['name'] = $data['name'] ?? $name;\n $data['requirements'] = $data['requirements'] ?? $requirements;\n $data['options'] = $data['options'] ?? $options;\n $data['defaults'] = $data['defaults'] ?? $defaults;\n $data['host'] = $data['host'] ?? $host;\n $data['methods'] = $data['methods'] ?? $methods;\n $data['schemes'] = $data['schemes'] ?? $schemes;\n $data['condition'] = $data['condition'] ?? $condition;\n $data['priority'] = $data['priority'] ?? $priority;\n $data['locale'] = $data['locale'] ?? $locale;\n $data['format'] = $data['format'] ?? $format;\n $data['utf8'] = $data['utf8'] ?? $utf8;\n $data['stateless'] = $data['stateless'] ?? $stateless;\n $data['env'] = $data['env'] ?? $env;\n\n $data = array_filter($data, static function ($value): bool {\n return null !== $value;\n });\n\n if (isset($data['localized_paths'])) {\n throw new \\BadMethodCallException(sprintf('Unknown property \"localized_paths\" on annotation \"%s\".', static::class));\n }\n\n if (isset($data['value'])) {\n $data[\\is_array($data['value']) ? 'localized_paths' : 'path'] = $data['value'];\n unset($data['value']);\n }\n\n if (isset($data['path']) && \\is_array($data['path'])) {\n $data['localized_paths'] = $data['path'];\n unset($data['path']);\n }\n\n if (isset($data['locale'])) {\n $data['defaults']['_locale'] = $data['locale'];\n unset($data['locale']);\n }\n\n if (isset($data['format'])) {\n $data['defaults']['_format'] = $data['format'];\n unset($data['format']);\n }\n\n if (isset($data['utf8'])) {\n $data['options']['utf8'] = filter_var($data['utf8'], \\FILTER_VALIDATE_BOOLEAN) ?: false;\n unset($data['utf8']);\n }\n\n if (isset($data['stateless'])) {\n $data['defaults']['_stateless'] = filter_var($data['stateless'], \\FILTER_VALIDATE_BOOLEAN) ?: false;\n unset($data['stateless']);\n }\n\n foreach ($data as $key => $value) {\n $method = 'set'.str_replace('_', '', $key);\n if (!method_exists($this, $method)) {\n throw new \\BadMethodCallException(sprintf('Unknown property \"%s\" on annotation \"%s\".', $key, static::class));\n }\n $this->$method($value);\n }\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n\t\tstring $appName,\n\t\tIRequest $request,\n\t\tIVerificationToken $verificationToken,\n\t\tIUserManager $userManager,\n\t\tIL10N $l10n,\n\t\tIUserSession $userSession,\n\t\tIAccountManager $accountManager,\n\t\tCrypto $crypto\n\t) {\n\t\tparent::__construct($appName, $request);\n\t\t$this->verificationToken = $verificationToken;\n\t\t$this->userManager = $userManager;\n\t\t$this->l10n = $l10n;\n\t\t$this->userSession = $userSession;\n\t\t$this->accountManager = $accountManager;\n\t\t$this->crypto = $crypto;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function creerDossierIBUploadTrackingKlsa($client, $ref_dos, $num_lic, $t1, $poids, $ref_fact, \n\t\t\t\t\t\t\t\t\t\t$horse, $trailer_1, $trailer_2, $transporteur, \n\t\t\t\t\t\t\t\t\t\t$destination, $arrival_date, $crossing_date, $wiski_arriv, \n\t\t\t\t\t\t\t\t\t\t$wiski_dep, $remarque, $id_util, $id_mod_lic, $id_mod_trans){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;$entree['num_lic'] = $num_lic;\n\t\t\t$entree['poids'] = $poids;$entree['ref_fact'] = $ref_fact;\n\t\t\t$entree['horse'] = $horse;$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;$entree['transporteur'] = $transporteur;$entree['destination'] = $destination;\n\t\t\t$entree['arrival_date'] = $arrival_date;$entree['wiski_arriv'] = $wiski_arriv;\n\t\t\t$entree['wiski_dep'] = $wiski_dep;$entree['remarque'] = $remarque;\n\t\t\t$entree['id_util'] = $id_util;$entree['t1'] = $t1;$entree['crossing_date'] = $crossing_date;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t/*echo $client.' = client
    ';echo $ref_dos.' = ref_dos
    ';echo $num_lic.' = num_lic
    ';\n\t\t\techo $poids.' = poids
    ';echo $ref_fact.' = ref_fact
    ';echo $horse.' = horse
    ';\n\t\t\techo $trailer_1.' = trailer_1
    ';echo $trailer_2.' = trailer_2
    ';echo $transporteur.' = transporteur
    ';\n\t\t\techo $destination.' = destination
    ';echo $arrival_date.' = arrival_date
    ';echo $crossing_date.' = crossing_date
    ';\n\t\t\techo $wiski_arriv.' = wiski_arriv
    ';echo $wiski_dep.' = wiski_dep
    ';echo $remarque.' = remarque
    ';\n\t\t\techo $id_util.' = id_util
    ';echo $t1.' = t1
    ';echo $id_mod_lic.' = id_mod_lic
    ';\n\t\t\techo $id_mod_trans.' = id_mod_trans

    ------------';*/\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload_tracking(client, ref_dos, num_lic, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_fact, horse, trailer_1, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_2, transporteur, destination, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarrival_date, crossing_date, wiski_arriv, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twiski_dep, remarque,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_util, t1, id_mod_lic, id_mod_trans) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['num_lic'], $entree['poids'], \n\t\t\t\t\t\t\t\t\t$entree['ref_fact'], $entree['horse'], $entree['trailer_1'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_2'], $entree['transporteur'], $entree['destination'], \n\t\t\t\t\t\t\t\t\t$entree['arrival_date'], $entree['crossing_date'], $entree['wiski_arriv'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_dep'], $entree['remarque'], \n\t\t\t\t\t\t\t\t\t$entree['id_util'], $entree['t1'], $entree['id_mod_lic'], $entree['id_mod_trans']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function calculateTbSamplePassStatus(\n $referenceMTBDetected,\n $resMtbDetected,\n $referenceRIFResistance,\n $resRifResistance,\n $probe1,\n $probe2,\n $probe3,\n $probe4\n ) {\n $calculatedScore = \"fail\";\n if (!isset($resMtbDetected) || $resMtbDetected == \"\") {\n $calculatedScore = \"fail\";\n } else if ($resMtbDetected == \"noResult\" || $resMtbDetected == \"error\" || $resMtbDetected == \"invalid\") {\n $calculatedScore = \"noresult\";\n } else if ($this->resMtbDetectedEqualsRefMtbDetected($resMtbDetected, $referenceMTBDetected)) {\n if ($this->resRifResistanceEqualsRefRifResistance($resMtbDetected, $resRifResistance, $referenceRIFResistance)) {\n $calculatedScore = \"pass\";\n $ctValues = array(\n floatval($probe1),\n floatval($probe2),\n floatval($probe3),\n floatval($probe4)\n );\n if (max($ctValues) > self::CONCERN_CT_MAX_VALUE) {\n $calculatedScore = \"concern\";\n }\n } else if ($resRifResistance == \"indeterminate\") {\n $calculatedScore = \"partial\";\n }\n }\n return $calculatedScore;\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public function modifElevesAvecCode($nom, $prenom, $sexe, $date_naissance, $tel_enfant, $email_enfant, $responsable_legal, $tel_parent, $tel_parent2, $tel_parent3, $profession_pere, $adresse, $profession_mere, $ville, $email_parent, $prevenir_parent, $commentaires, $cp, $assurance, $codebarre, $password, $num, $numAllocataire, $nbTempsLibres, $contactParents, $photo)\n\t{\n\t\t$req = \"UPDATE `\".PdoBD::$villeExtranet.\"_eleves` SET `NOM` = :nom, `PRENOM` = :prenom, `SEXE` = :sexe, `DATE_DE_NAISSANCE` = :date_naissance, `RESPONSABLE_LEGAL` = :responsable, `PR\u00c9VENIR_EN_CAS_D_ABSENCE` = :prevenir, `PROFESSION_DU_P\u00c8RE` = :profession_pere, `PROFESSION_DE_LA_M\u00c8RE` = :profession_mere, `ADRESSE_POSTALE` = :adresse, `CODE_POSTAL` = :cp, `VILLE` = :ville, `T\u00c9L\u00c9PHONE_DES_PARENTS` = :tel_parent, `T\u00c9L\u00c9PHONE_DES_PARENTS2` = :tel_parent2, `T\u00c9L\u00c9PHONE_DES_PARENTS3` = :tel_parent3, `T\u00c9L\u00c9PHONE_DE_L_ENFANT` = :tel_enfant, `EMAIL_DES_PARENTS` = :email_parent, `EMAIL_DE_L_ENFANT` = :email_enfant, `PHOTO` = :photo, `CONTACT_AVEC_LES_PARENTS` = :contact_parents, `COMMENTAIRES` = :commentaires, `N\u00b0_ALLOCATAIRE` = :allocataire, `NOMBRE_TPS_LIBRE` = :temps_libres, `ASSURANCE_P\u00c9RISCOLAIRE` = :assurance, `PASSWORD` = :password WHERE `ID_ELEVE` = :eleve;\";\n\t\t$params = array(\n\t\t\t':nom' => strtoupper($nom),\n\t\t\t':prenom' => ucwords($prenom),\n\t\t\t':sexe' => $sexe,\n\t\t\t':date_naissance' => $date_naissance,\n\t\t\t':responsable' => $responsable_legal,\n\t\t\t':prevenir' => $prevenir_parent,\n\t\t\t':profession_pere' => $profession_pere,\n\t\t\t':profession_mere' => $profession_mere,\n\t\t\t':adresse' => $adresse,\n\t\t\t':cp' => $cp,\n\t\t\t':ville' => strtoupper($ville),\n\t\t\t':tel_parent' => $tel_parent,\n\t\t\t':tel_parent2' => $tel_parent2,\n\t\t\t':tel_parent3' => $tel_parent3,\n\t\t\t':tel_enfant' => $tel_enfant,\n\t\t\t':email_parent' => $email_parent,\n\t\t\t':email_enfant' => $email_enfant,\n\t\t\t':photo' => $photo,\n\t\t\t':contact_parents' => $contactParents,\n\t\t\t':commentaires' => $commentaires,\n\t\t\t':allocataire' => $numAllocataire,\n\t\t\t':temps_libres' => $nbTempsLibres,\n\t\t\t':assurance' => $assurance,\n\t\t\t':password' => $password,\n\t\t\t':eleve' => $num\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'\u00e9l\u00e8ve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(IDBConnection $dbConnection,\n\t\tIUserSession $userSession,\n\t\tIGroupManager $groupManager,\n\t\tLoggerInterface $logger,\n\t\tProxyMapper $proxyMapper,\n\t\tstring $principalPrefix,\n\t\tstring $dbPrefix,\n\t\tstring $cuType) {\n\t\t$this->db = $dbConnection;\n\t\t$this->userSession = $userSession;\n\t\t$this->groupManager = $groupManager;\n\t\t$this->logger = $logger;\n\t\t$this->proxyMapper = $proxyMapper;\n\t\t$this->principalPrefix = $principalPrefix;\n\t\t$this->dbTableName = 'calendar_' . $dbPrefix . 's';\n\t\t$this->dbMetaDataTableName = $this->dbTableName . '_md';\n\t\t$this->dbForeignKeyName = $dbPrefix . '_id';\n\t\t$this->cuType = $cuType;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function beginFile($filePath, $isDir, $fileComment, $timestamp, $gpFlags, $gzMethod,\n $dataLength = 0, $gzLength = 0, $dataCRC32 = 0) {\n\n $isFileUTF8 = mb_check_encoding($filePath, 'UTF-8') && !mb_check_encoding($filePath, 'ASCII');\n $isCommentUTF8 = !empty($fileComment) && mb_check_encoding($fileComment, 'UTF-8')\n && !mb_check_encoding($fileComment, 'ASCII');\n\n if ($isFileUTF8 || $isCommentUTF8) {\n $gpFlags |= GPFLAGS::EFS;\n }\n\n $localFileHeader = $this->buildLocalFileHeader($filePath, $timestamp, $gpFlags, $gzMethod, $dataLength,\n $gzLength, $isDir, $dataCRC32);\n\n $this->write($localFileHeader);\n\n return array($gpFlags, strlen($localFileHeader));\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getOrderLinkAndSortedHeaderHtml(\n FieldMetadata $fieldsMeta,\n array $sortExpression,\n array $sortExpressionNoDirection,\n StatementInfo $statementInfo,\n int $sessionMaxRows,\n string $comments,\n array $sortDirection,\n bool|array $colVisib,\n int|string|null $colVisibElement,\n ): array {\n // Checks if the table name is required; it's the case\n // for a query with a \"JOIN\" statement and if the column\n // isn't aliased, or in queries like\n // SELECT `1`.`master_field` , `2`.`master_field`\n // FROM `PMA_relation` AS `1` , `PMA_relation` AS `2`\n\n $sortTable = $fieldsMeta->table !== ''\n && $fieldsMeta->orgname === $fieldsMeta->name\n ? Util::backquote($fieldsMeta->table) . '.'\n : '';\n\n // Generates the orderby clause part of the query which is part\n // of URL\n [$singleSortOrder, $multiSortOrder, $orderImg] = $this->getSingleAndMultiSortUrls(\n $sortExpression,\n $sortExpressionNoDirection,\n $sortTable,\n $fieldsMeta->name,\n $sortDirection,\n $fieldsMeta,\n );\n\n $singleSortedSqlQuery = Query::replaceClause(\n $statementInfo->statement,\n $statementInfo->parser->list,\n $singleSortOrder,\n );\n $multiSortedSqlQuery = Query::replaceClause(\n $statementInfo->statement,\n $statementInfo->parser->list,\n $multiSortOrder,\n );\n\n $singleUrlParams = [\n 'db' => $this->db,\n 'table' => $this->table,\n 'sql_query' => $singleSortedSqlQuery,\n 'sql_signature' => Core::signSqlQuery($singleSortedSqlQuery),\n 'session_max_rows' => $sessionMaxRows,\n 'is_browse_distinct' => $this->isBrowseDistinct,\n ];\n\n $multiUrlParams = [\n 'db' => $this->db,\n 'table' => $this->table,\n 'sql_query' => $multiSortedSqlQuery,\n 'sql_signature' => Core::signSqlQuery($multiSortedSqlQuery),\n 'session_max_rows' => $sessionMaxRows,\n 'is_browse_distinct' => $this->isBrowseDistinct,\n ];\n\n // Displays the sorting URL\n // enable sort order swapping for image\n $orderLink = $this->getSortOrderLink($orderImg, $fieldsMeta, $singleUrlParams, $multiUrlParams);\n\n $orderLink .= $this->getSortOrderHiddenInputs($multiUrlParams, $fieldsMeta->name);\n\n return [\n 'column_name' => $fieldsMeta->name,\n 'order_link' => $orderLink,\n 'comments' => $comments,\n 'is_browse_pointer_enabled' => $this->config->settings['BrowsePointerEnable'] === true,\n 'is_browse_marker_enabled' => $this->config->settings['BrowseMarkerEnable'] === true,\n 'is_column_hidden' => $colVisib && ! $colVisibElement,\n 'is_column_numeric' => $this->isColumnNumeric($fieldsMeta),\n ];\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function __construct(\n ArtworkRepository $artworks,\n ArtistRepository $artists,\n SearchRepository $search,\n ExhibitionRepository $exhibitions,\n ArticleRepository $articles,\n PublicationsRepository $publications,\n EventRepository $events,\n GenericPageRepository $pages,\n EducatorResourceRepository $educatorResources,\n PressReleaseRepository $press,\n InteractiveFeatureRepository $interactiveFeature,\n HighlightRepository $highlight\n ) {\n $this->artworksRepository = $artworks;\n $this->artistsRepository = $artists;\n $this->searchRepository = $search;\n $this->exhibitionsRepository = $exhibitions;\n $this->articlesRepository = $articles;\n $this->eventsRepository = $events;\n $this->publicationsRepository = $publications;\n $this->pagesRepository = $pages;\n $this->educatorResourceRepository = $educatorResources;\n $this->pressRepository = $press;\n $this->interactiveFeatureRepository = $interactiveFeature;\n $this->highlightRepository = $highlight;\n\n parent::__construct();\n }", "smellKey": "S107", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function get_query_r_mot_with_table_tempo_all($tree,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict=false,$all_fields=false) {\n\t\t// Variable permettant de choisir si l'on utilise ou non la troncature droite du terme recherch\n\t\t$empty_word = get_empty_words();\n\n\t\t$temporary_table = $last_table = \"\";\n\t\t$troncat = \"\";\n\t\tif ($this->allow_term_troncat_search) {\n\t\t\t$troncat = \"%\";\n\t\t}\n\t\t$lang_restrict = $field_restrict = array();\n\t\tfor($i=0 ; $isub){\n\t\t\t\t$elem_query = $this->get_query_r_mot_with_table_tempo_all($tree[$i]->sub,$field_id,$table_mot,$field_mot,$table_term,$field_term,$restrict,$neg_restrict,$all_fields);\n\t\t\t}else{\n\t\t\t\tif($tree[$i]->word !== \"*\") {\n\t\t\t\t\tif($tree[$i]->literal == 0){\n\t\t\t\t\t\t// on commence...\n\t\t\t\t\t\t$qw = \"select distinct id_word from words where \".(count($lang_restrict)>0 ? $this->get_field_restrict($lang_restrict,$neg_restrict).\" and \": \"\");\n\n\t\t\t\t\t\t$table= $table_mot;\n\t\t\t\t\t\t//on ajoute le terme\n\t\t\t\t\t\t$qw.= \" words.\".$field_mot.\" \";\n\t\t\t\t\t\tif(strpos($tree[$i]->word, \"*\") !== false || ($this->allow_term_troncat_search && (strlen($tree[$i]->word)>2))){\n\t\t\t\t\t\t\t$qw.=\"like '\";\n\t\t\t\t\t\t\tif (strpos($tree[$i]->word,\"*\") === false) {\n\t\t\t\t\t\t\t\t//Si c'est un mot vide, on ne troncature pas\n\t\t\t\t\t\t\t\tif (in_array($tree[$i]->word,$empty_word)===false) {\n\t\t\t\t\t\t\t\t\t$qw.=addslashes($tree[$i]->word.$troncat);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$qw.=addslashes($tree[$i]->word);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$qw.=addslashes(str_replace(\"*\",\"%\",$tree[$i]->word));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$qw.=\"'\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$qw.=\"='\".addslashes($tree[$i]->word).\"'\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$tw = array();\n\t\t\t\t\t\t$rw = pmb_mysql_query($qw);\n\t\t\t\t\t\tif(pmb_mysql_num_rows($rw)) {\n\t\t\t\t\t\t\twhile($o = pmb_mysql_fetch_object($rw) ) {\n\t\t\t\t\t\t\t\t$tw[]=$o->id_word;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_mot \".gen_where_in($table_mot.'.num_word', $tw).\" and pond>0 \";\n\t\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t\t$elem_query.= ' and '.$this->get_field_restrict($restrict,$neg_restrict);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif($tree[$i]->start_with){\n\t\t\t\t\t\t $elem_query.=\" and field_position ='1'\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if ($tree[$i]->literal == 1){\n\t\t\t\t\t\t// on commence...\n\t\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_term where pond>0 and \";\n\t\t\t\t\t\t//on applique la restriction si besoin\n\t\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t\t$elem_query.= $this->get_field_restrict($restrict,$neg_restrict).\" and \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$table= $table_term;\n\t\t\t\t\t\t//on ajoute le terme\n\t\t\t\t\t\t$elem_query.= \" \".$table.\".\".$field_term.\" \";\n\t\t\t\t\t\t$elem_query.= \"like '\";\n\t\t\t\t\t\tif(!$tree[$i]->start_with){\n\t\t\t\t\t\t\t$elem_query.=\"%\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strpos($tree[$i]->word,\"*\") === false) {\n\t\t\t\t\t\t\t//Si c'est un mot vide, on ne troncature pas\n\t\t\t\t\t\t\tif (in_array($tree[$i]->word,$empty_word)===false) {\n\t\t\t\t\t\t\t\t$elem_query.=addslashes($tree[$i]->word.$troncat);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$elem_query.=addslashes($tree[$i]->word);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$elem_query.=addslashes(str_replace(\"*\",\"%\",$tree[$i]->word));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$elem_query.=\"%'\";\n\t\t\t\t\t}\n\t\t\t\t\tif($table_mot == \"notices_mots_global_index\" && $all_fields && $this->exclude_fields!=\"\"){\n\t\t\t\t\t\t$elem_query.= \" and code_champ not in (\".$this->exclude_fields.\")\";\n\t\t\t\t\t}\n\t\t\t\t}else if(count($tree)==1){\n\t\t\t\t\t$elem_query = \"select distinct $field_id from $table_mot where 1\";\n\t\t\t\t\tif($restrict){\n\t\t\t\t\t\t$elem_query.= \" and \".$this->get_field_restrict($restrict,$neg_restrict).\" \";\n\t\t\t\t\t}\n\t\t\t\t\tif($table_mot == \"notices_mots_global_index\" && $all_fields && $this->exclude_fields!=\"\"){\n\t\t\t\t\t\t$elem_query.= \" and code_champ not in (\".$this->exclude_fields.\")\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($tree[$i]->literal!=2 && $elem_query!= \"\"){\n\t\t\t\t$last_table = $temporary_table;\n\t\t\t\t$temporary_table = $this->tmp_prefix.md5(microtime(true).\"#\".$this->keep_empty.$i);\n\t\t\t\tswitch($tree[$i]->operator){\n\t\t\t\t\tcase \"and\" :\n\t\t\t\t\t\t//on cr la table tempo avec les rsultats du critre...\n\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"delete from \".$last_table.\" where \".$field_id.\" in (select \".$field_id.\" from \".$temporary_table.\")\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$temporary_table);\n\t\t\t\t\t\t\t$temporary_table = $last_table;\n\t\t\t\t\t\t\t$last_table = \"\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$new_temporary_table =$this->tmp_prefix.md5(microtime(true).\"new_temporary_table\".$this->keep_empty.$i);\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$new_temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory select $last_table.$field_id from $last_table join $temporary_table on $last_table.$field_id = $temporary_table.$field_id\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$temporary_table);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$last_table);\n\t\t\t\t\t\t\t$temporary_table=$new_temporary_table;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"or\" :\n\t\t\t\t\t\t$temporary_table = $last_table;\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"create temporary table tmp_\".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\t$rqt = \"insert ignore into \".$temporary_table.\" select distinct $field_id from $table_term where \".$field_id.\" not in(select \".$field_id.\" from tmp_\".$temporary_table.\") and code_champ = 1\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists tmp_\".$temporary_table);\n\t\t\t\t\t\t\t$last_table= \"\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$rqt = \"insert ignore into \".$temporary_table.\" \".$elem_query;\n\t\t\t\t\t\t\t$last_table= \"\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault :\n\t\t\t\t\t\tif($tree[$i]->not){\n\t\t\t\t\t\t\t$rqt = \"create temporary table tmp_\".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory select distinct $field_id from $table_term where \".$field_id.\" not in(select \".$field_id.\" from tmp_\".$temporary_table.\") and code_champ = 1\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t\tpmb_mysql_query(\"drop table if exists tmp_\".$temporary_table);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$rqt = \"create temporary table \".$temporary_table.\" ($field_id int, index using btree($field_id)) engine=memory $elem_query\";\n\t\t\t\t\t\t\tpmb_mysql_query($rqt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t$query = \"select distinct $field_id from \".$temporary_table;\n\t\t\t\tif($last_table != \"\"){\n\t\t\t\t\tpmb_mysql_query(\"drop table if exists \".$last_table);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $query;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "private function getRowValues(\n array $row,\n int $rowNumber,\n array|false $colOrder,\n array $map,\n string $gridEditConfig,\n bool|array|string $colVisib,\n string $urlSqlQuery,\n StatementInfo $statementInfo,\n ): string {\n $rowValuesHtml = '';\n\n $rowInfo = $this->getRowInfoForSpecialLinks($row);\n\n // Load SpecialSchemaLinks for all rows\n $specialSchemaLinks = SpecialSchemaLinks::get();\n $relationParameters = $this->relation->getRelationParameters();\n\n $columnCount = count($this->fieldsMeta);\n for ($currentColumn = 0; $currentColumn < $columnCount; ++$currentColumn) {\n // assign $i with appropriate column order\n $i = is_array($colOrder) ? $colOrder[$currentColumn] : $currentColumn;\n\n $meta = $this->fieldsMeta[$i];\n $orgFullColName = $this->db . '.' . $meta->orgtable . '.' . $meta->orgname;\n\n $notNullClass = $meta->isNotNull() ? 'not_null' : '';\n $relationClass = isset($map[$meta->name]) ? 'relation' : '';\n $hideClass = is_array($colVisib) && isset($colVisib[$currentColumn]) && ! $colVisib[$currentColumn]\n ? 'hide'\n : '';\n\n $gridEdit = '';\n if ($meta->orgtable != '' && $gridEditConfig !== 'disabled') {\n $gridEdit = $gridEditConfig === 'click' ? 'grid_edit click1' : 'grid_edit click2';\n }\n\n // handle datetime-related class, for grid editing\n $fieldTypeClass = $this->getClassForDateTimeRelatedFields($meta);\n\n // combine all the classes applicable to this column's value\n $class = implode(' ', array_filter([\n 'data',\n $gridEdit,\n $notNullClass,\n $relationClass,\n $hideClass,\n $fieldTypeClass,\n ]));\n\n // See if this column should get highlight because it's used in the\n // where-query.\n $conditionField = isset($this->highlightColumns[$meta->name])\n || isset($this->highlightColumns[Util::backquote($meta->name)]);\n\n $transformationPlugin = null;\n $transformOptions = [];\n\n if (\n $relationParameters->browserTransformationFeature !== null\n && $this->config->settings['BrowseMIME']\n && isset($this->mediaTypeMap[$orgFullColName]['mimetype'])\n && ! empty($this->mediaTypeMap[$orgFullColName]['transformation'])\n ) {\n $file = $this->mediaTypeMap[$orgFullColName]['transformation'];\n $plugin = $this->transformations->getPluginInstance($file);\n if ($plugin instanceof TransformationsInterface) {\n $transformationPlugin = $plugin;\n $transformOptions = $this->transformations->getOptions(\n $this->mediaTypeMap[$orgFullColName]['transformation_options'] ?? '',\n );\n\n $meta->internalMediaType = $this->mediaTypeMap[$orgFullColName]['mimetype'];\n }\n }\n\n // Check whether the field needs to display with syntax highlighting\n\n $dbLower = mb_strtolower($this->db);\n $tblLower = mb_strtolower($meta->orgtable);\n $nameLower = mb_strtolower($meta->orgname);\n if (\n isset($this->transformationInfo[$dbLower][$tblLower][$nameLower])\n && isset($row[$i])\n && trim($row[$i]) !== ''\n && ! $_SESSION['tmpval']['hide_transformation']\n ) {\n $transformationPlugin = new $this->transformationInfo[$dbLower][$tblLower][$nameLower]();\n $transformOptions = $this->transformations->getOptions(\n $this->mediaTypeMap[$orgFullColName]['transformation_options'] ?? '',\n );\n\n $orgTable = mb_strtolower($meta->orgtable);\n $orgName = mb_strtolower($meta->orgname);\n\n $meta->internalMediaType = $this->transformationInfo[$dbLower][$orgTable][$orgName]::getMIMEType()\n . '_' . $this->transformationInfo[$dbLower][$orgTable][$orgName]::getMIMESubtype();\n }\n\n // Check for the predefined fields need to show as link in schemas\n if (isset($specialSchemaLinks[$dbLower][$tblLower][$nameLower])) {\n $linkingUrl = $this->getSpecialLinkUrl(\n $specialSchemaLinks[$dbLower][$tblLower][$nameLower],\n $row[$i],\n $rowInfo,\n );\n $transformationPlugin = new Text_Plain_Link();\n\n $transformOptions = [0 => $linkingUrl, 2 => true];\n\n $meta->internalMediaType = 'Text_Plain';\n }\n\n $expressions = [];\n\n if ($statementInfo->statement instanceof SelectStatement) {\n $expressions = $statementInfo->statement->expr;\n }\n\n /**\n * The result set can have columns from more than one table,\n * this is why we have to check for the unique conditions\n * related to this table; however getting UniqueCondition is\n * costly and does not need to be called if we already know\n * the conditions for the current table.\n */\n if (! isset($this->whereClauseMap[$rowNumber][$meta->orgtable])) {\n $this->whereClauseMap[$rowNumber][$meta->orgtable] = (new UniqueCondition(\n $this->fieldsMeta,\n $row,\n false,\n $meta->orgtable,\n $expressions,\n ))->getWhereClause();\n }\n\n $urlParams = [\n 'db' => $this->db,\n 'table' => $meta->orgtable,\n 'where_clause_sign' => Core::signSqlQuery($this->whereClauseMap[$rowNumber][$meta->orgtable]),\n 'where_clause' => $this->whereClauseMap[$rowNumber][$meta->orgtable],\n 'transform_key' => $meta->orgname,\n ];\n\n if ($this->sqlQuery !== '') {\n $urlParams['sql_query'] = $urlSqlQuery;\n }\n\n $transformOptions['wrapper_link'] = Url::getCommon($urlParams);\n $transformOptions['wrapper_params'] = $urlParams;\n\n if ($meta->isNumeric) {\n $rowValuesHtml .= $this->getDataCellForNumericColumns(\n $row[$i],\n 'text-end ' . $class,\n $conditionField,\n $meta,\n $map,\n $statementInfo,\n $transformationPlugin,\n $transformOptions,\n );\n } elseif ($meta->isMappedTypeGeometry) {\n // Remove 'grid_edit' from $class as we do not allow to\n // inline-edit geometry data.\n $class = str_replace('grid_edit', '', $class);\n\n $rowValuesHtml .= $this->getDataCellForGeometryColumns(\n $row[$i],\n $class,\n $meta,\n $map,\n $urlParams,\n $conditionField,\n $transformationPlugin,\n $transformOptions,\n $statementInfo,\n );\n } else {\n $rowValuesHtml .= $this->getDataCellForNonNumericColumns(\n $row[$i],\n $class,\n $meta,\n $map,\n $urlParams,\n $conditionField,\n $transformationPlugin,\n $transformOptions,\n $statementInfo,\n );\n }\n }\n\n return $rowValuesHtml;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function add($lastName, $firstName, $email, $username, $password,\n $accessLevel, $eeoIsVisible = false, $userSiteID = -1)\n {\n\n $md5pwd = $password == LDAPUSER_PASSWORD ? $password : md5($password);\n $userSiteID = $userSiteID < 0 ? $this->_siteID : $userSiteID;\n $sql = sprintf(\n \"INSERT INTO user (\n user_name,\n password,\n access_level,\n can_change_password,\n is_test_user,\n email,\n first_name,\n last_name,\n site_id,\n can_see_eeo_info\n )\n VALUES (\n %s,\n %s,\n %s,\n 1,\n 0,\n %s,\n %s,\n %s,\n %s,\n %s\n )\",\n $this->_db->makeQueryString($username),\n $this->_db->makeQueryString($md5pwd),\n $this->_db->makeQueryInteger($accessLevel),\n $this->_db->makeQueryString($email),\n $this->_db->makeQueryString($firstName),\n $this->_db->makeQueryString($lastName),\n $userSiteID,\n ($eeoIsVisible ? 1 : 0)\n );\n\n $queryResult = $this->_db->query($sql);\n if (!$queryResult)\n {\n return -1;\n }\n\n return $this->_db->getLastInsertID();\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function __construct(AssignNameExpression $keyTarget, AssignNameExpression $valueTarget, AbstractExpression $seq, ?AbstractExpression $ifexpr, Node $body, ?Node $else, int $lineno, string $tag = null)\n {\n $body = new Node([$body, $this->loop = new ForLoopNode($lineno, $tag)]);\n\n if (null !== $ifexpr) {\n $body = new IfNode(new Node([$ifexpr, $body]), null, $lineno, $tag);\n }\n\n $nodes = ['key_target' => $keyTarget, 'value_target' => $valueTarget, 'seq' => $seq, 'body' => $body];\n if (null !== $else) {\n $nodes['else'] = $else;\n }\n\n parent::__construct($nodes, ['with_loop' => true, 'ifexpr' => null !== $ifexpr], $lineno, $tag);\n }", "smellKey": "S107", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {\n\t\t$this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function InsertaCurso($nombre_curso, $descripcion_curso, $modalidad, $tipo_curso, $prerequisito_curso,\n $archivo, $objetivo_curso, $sence, $numero_horas, $cantidad_maxima_participantes, $rut_otec,\n $clasificacion_curso, $cbc, $cod_identificador, $valor_hora, $valor_hora_sence, $codigo_curso,\n $id_empresa, $contenidos_cursos, $nombre_curso_sence, $foco, $programa_bbdd, $codigo_sence,\n $programa_bbdd_global, $programa_bbdd_elearning,$var,$var2,$var3,$var4,$var5, $var6, $bajada)\n{\n\n //$bajada=$programa_bbdd_elearning;\n // echo \"
    InsertaCurso.$programa_bbdd_elearning,$var,$var2,$var3,$var4,$var5, $var6, $var7, $bajada.\"; exit();\n $connexion = new DatabasePDO();\n\n if ($sence == \"si\" && $cbc == \"si\") {\n $valor_hora_sence = $valor_hora_sence + (($valor_hora_sence * 20) / 100);\n }\n\n $sql = \"INSERT INTO tbl_lms_curso \n (nombre, descripcion, modalidad, tipo, prerequisito, imagen, objetivo_curso, sence, numero_horas, \n cantidad_maxima_participantes, rut_otec, clasificacion, cbc, numero_identificador, valor_hora, \n valor_hora_sence, id, id_empresa, contenidos_cursos, nombre_curso_sence, id_foco, id_empresa_programa, \n id_programa_global, codigosence, bajada) \n VALUES \n (:nombre_curso, :descripcion_curso, :modalidad, :tipo_curso, :prerequisito_curso, :archivo, :objetivo_curso, \n :sence, :numero_horas, :cantidad_maxima_participantes, :rut_otec, :clasificacion_curso, :cbc, :cod_identificador, \n :valor_hora, :valor_hora_sence, :codigo_curso, :id_empresa, :contenidos_cursos, :nombre_curso_sence, :foco, \n :programa_bbdd_elearning, :programa_bbdd_global, :codigo_sence, :bajada)\";\n\n $connexion->query($sql);\n $connexion->bind(':nombre_curso', $nombre_curso);\n $connexion->bind(':descripcion_curso', $descripcion_curso);\n $connexion->bind(':modalidad', $modalidad);\n $connexion->bind(':tipo_curso', $tipo_curso);\n $connexion->bind(':prerequisito_curso', $prerequisito_curso);\n $connexion->bind(':archivo', $archivo);\n $connexion->bind(':objetivo_curso', $objetivo_curso);\n $connexion->bind(':sence', $sence);\n $connexion->bind(':numero_horas', $numero_horas);\n $connexion->bind(':cantidad_maxima_participantes', $cantidad_maxima_participantes);\n $connexion->bind(':rut_otec', $rut_otec);\n $connexion->bind(':clasificacion_curso', $clasificacion_curso);\n $connexion->bind(':cbc', $cbc);\n $connexion->bind(':cod_identificador', $cod_identificador);\n $connexion->bind(':valor_hora', $valor_hora);\n $connexion->bind(':valor_hora_sence', $valor_hora_sence);\n $connexion->bind(':codigo_curso', $codigo_curso);\n $connexion->bind(':id_empresa', $id_empresa);\n $connexion->bind(':contenidos_cursos', $contenidos_cursos);\n $connexion->bind(':nombre_curso_sence', $nombre_curso_sence);\n $connexion->bind(':foco', $foco);\n $connexion->bind(':programa_bbdd_elearning', $programa_bbdd_elearning);\n $connexion->bind(':programa_bbdd_global', $programa_bbdd_global);\n $connexion->bind(':codigo_sence', $codigo_sence);\n $connexion->bind(':bajada', $bajada);\n\n $connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function getfeedbacktxtnumfunc($stu, $partial, $fbtxt, $deffb='Incorrect', $vars='x', $requiretimes = '', $tol='.001',$domain='-10,10') {\n\tglobal $imasroot,$staticroot;\n\tif (isset($GLOBALS['testsettings']['testtype']) && ($GLOBALS['testsettings']['testtype']=='NoScores' || $GLOBALS['testsettings']['testtype']=='EndScore')) {\n\t\treturn '';\n\t}\n\tif ($stu===null || trim($stu)==='') {\n\t\treturn \" \";\n\t} else {\n\t\tif (strval($tol)[0]=='|') {\n\t\t\t$abstol = true;\n\t\t\t$tol = substr($tol,1);\n\t\t} else {\n\t\t\t$abstol =false;\n\t\t}\n\t\t$type = \"expression\";\n\t\tif (strpos($stu, '=')!==false) {\n\t\t\t$type = \"equation\";\n\t\t}\n\t\t$stuorig = $stu;\n\t\t$stu = str_replace(array('[',']'),array('(',')'), $stu);\n\t\tif ($type=='equation') {\n\t\t\t$stu = preg_replace('/(.*)=(.*)/','$1-($2)',$stu);\n\t\t}\n\n list($variables, $tps, $flist) = numfuncGenerateTestpoints($vars, $domain);\n $numpts = count($tps);\n\t\t$vlist = implode(\",\",$variables);\n $stu = numfuncPrepForEval($stu, $variables);\n\n\t\t$origstu = $stu;\n\t\t$stufunc = makeMathFunction(makepretty($stu), $vlist, [], $flist, true);\n\t\tif ($stufunc===false) {\n\t\t\treturn '
    \"Incorrect\"/ '.$deffb.'
    ';\n\t\t}\n\n\t\t$stupts = array();\n\t\t$cntnana = 0;\n\t\t$correct = true;\n\t\tfor ($i = 0; $i < $numpts; $i++) {\n\t\t\t$varvals = array();\n\t\t\tfor($j=0; $j < count($variables); $j++) {\n\t\t\t\t$varvals[$variables[$j]] = $tps[$i][$j];\n\t\t\t}\n\t\t\t$stupts[$i] = $stufunc($varvals);\n\t\t\tif (isNaN($stupts[$i])) {$cntnana++;}\n\t\t\tif ($stupts[$i]===false) {$correct = false; break;}\n\t\t}\n\t\tif ($cntnana==$numpts || !$correct) { //evald to NAN at all points\n\t\t\treturn '
    \"Incorrect\"/ '.$deffb.'
    ';\n\t\t}\n\n\t\t$match = -1;\n\t\tif (!is_array($partial)) { $partial = listtoarray($partial);}\n\t\tfor ($k=0;$k.000001 && is_numeric($ansb)) {\n\t\t\t\t\t\t$ratios[] = $ansb/$stupts[$i];\n\t\t\t\t\t\tif (abs($ansb)<=.00000001 && $stupts[$i]!=0) {\n\t\t\t\t\t\t\t$cntzero++;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (abs($stupts[$i])<=.000001 && is_numeric($ansb) && abs($ansb)<=.00000001) {\n\t\t\t\t\t\t$cntbothzero++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ($abstol) {\n\t\t\t\t\t\tif (abs($stupts[$i]-$ansb) > $tol-1E-12) {$correct = false; break;}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif ((abs($stupts[$i]-$ansb)/(abs($stupts[$i])+.0001) > $tol-1E-12)) {$correct = false; break;}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//echo \"$i, $ansa, $ansb, $cntnana, $cntnanb\";\n\t\t\tif ($cntnanb==20) {\n\t\t\t\tcontinue;\n\t\t\t} else if ($i<20) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ($diffnan>1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ($type==\"equation\") {\n\t\t\t\tif ($cntbothzero>$numpts-2) {\n\t\t\t\t\t$match = $k; break;\n\t\t\t\t} else if (count($ratios)>0) {\n\t\t\t\t\tif (count($ratios)==$cntzero) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$meanratio = array_sum($ratios)/count($ratios);\n\t\t\t\t\t\tfor ($i=0; $i $tol-1E-12) {continue 2;}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif ((abs($ratios[$i]-$meanratio)/(abs($meanratio)+.0001) > $tol-1E-12)) {continue 2;}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($correct) {\n\t\t\t\tif (is_array($requiretimes)) {\n\t\t\t\t\tif ($requiretimes[$k/2]!='') {\n\t\t\t\t\t\tif (checkreqtimes(str_replace(',','',$stuorig),$requiretimes[$k/2])==0) {\n\t\t\t\t\t\t\t$rightanswrongformat = $k;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if ($requiretimes!='') {\n\t\t\t\t\tif (checkreqtimes(str_replace(',','',$stuorig),$requiretimes)==0) {\n\t\t\t\t\t\t$rightanswrongformat = $k;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$match = $k; break;\n\t\t\t} else {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t}\n\t\t//WHAT to do with right answer, wrong format??\n\t\tif ($match>-1) {\n\t\t\tif ($partial[$match+1]<1) {\n\t\t\t\treturn '
    \"Incorrect\"/ '.$fbtxt[$match/2].'
    ';\n\t\t\t} else {\n\t\t\t\treturn '
    \"Correct\"/ '.$fbtxt[$match/2].'
    ';\n\t\t\t}\n\t\t} else {\n\t\t\treturn '
    \"Incorrect\"/ '.$deffb.'
    ';\n\t\t}\n\t}\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $smoothLine = null, $plotStyle = null)\n\t{\n\t\t$this->_plotType = $plotType;\n\t\t$this->_plotGrouping = $plotGrouping;\n\t\t$this->_plotOrder = $plotOrder;\n\t\t$keys = array_keys($plotValues);\n\t\t$this->_plotValues = $plotValues;\n\t\tif ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) {\n\t\t\t$plotLabel[$keys[0]] = new PHPExcel_Chart_DataSeriesValues();\n\t\t}\n\n\t\t$this->_plotLabel = $plotLabel;\n\t\tif ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) {\n\t\t\t$plotCategory[$keys[0]] = new PHPExcel_Chart_DataSeriesValues();\n\t\t}\n\t\t$this->_plotCategory = $plotCategory;\n\t\t$this->_smoothLine = $smoothLine;\n\t\t$this->_plotStyle = $plotStyle;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function saveDatosGeneralesFactura($factur_numdoc, $factur_tipdocid, $factur_proveerut, $factur_servid, $factur_servotro, $factur_montoto, $factur_montonet, $factur_impuest, $factur_fecemision, $factur_ota, $factur_numota, $factur_cuenta, $factur_proyecto, $factur_curso, $factur_otanombre, $factur_cui, $factur_respgast, $factur_observacion, $factur_mes, $factur_anual, $factur_status, $factura_proveenom, $rut_created, $factur_cuenta_nombre)\n\t{\n\t\t$result = array(\"code\" => 1, \"mensage\" => \"Actualizado\");\n\t\t//Se validan los datos recibidos antes de ser guardados\n\t\t\n\t\t//Se verifica el numero de documento proporcionado no se repita\n\t\t$consulNumDocFac = facturaFinanzaByNumdoc($factur_numdoc);\n\t\tif (count($consulNumDocFac) == 0) {\n\t\t\t//Se ubica el id del proveedor segun el rut suministrado\n\t\t\t$consulOtec = DatosOtecDadoRut($factur_proveerut);\n\t\t\t$factur_proveeid = $consulOtec[0]->id;\n\t\t\t\n\t\t\t//Se ubica el id de la cuenta segun el numero suministrado\n\t\t\t$factur_cuentaid = 0;\n\t\t\t\n\t\t\t//Se ubica el id del proyecto segun el nombre suministrado\n\t\t\t$consulProyecto = DatosProgramaByNombre($factur_proyecto);\n\t\t\t$factur_proyectid = $consulProyecto[0]->id;\n\t\t\t\n\t\t\t$factur_tipdocid = Decodear3($factur_tipdocid);\n\t\t\t$factur_servid = Decodear3($factur_servid);\n\t\t\t$factur_cui = Decodear3($factur_cui);\n\t\t\t$factur_respgast = Decodear3($factur_respgast);\n\t\t\tif ($factur_ota != \"on\") {\n\t\t\t\t$factur_ota = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$factur_ota = 1;\n\t\t\t}\n\t\t\treturn saveDatosGeneralesFacturaData($factur_numdoc, $factur_tipdocid, $factur_proveeid, $factur_proveerut, $factur_servid, $factur_servotro, $factur_montoto, $factur_montonet, $factur_impuest, $factur_fecemision, $factur_ota, $factur_numota, $factur_cuentaid, $factur_cuenta, $factur_proyectid, $factur_proyecto, $factur_curso, $factur_otanombre, $factur_cui, $factur_respgast, $factur_observacion, $factur_mes, $factur_anual, $factur_status, $factura_proveenom, $rut_created, $factur_cuenta_nombre);\n\t\t}\n\t\telse {\n\t\t\t$result = array(\"code\" => 0, \"mensage\" => \"N\u00famero de documento ya existe\");\n\t\t}\n\t\treturn $result;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {\n\t\tif (3 > $ns) {\n\t\t\t$ns = 3;\n\t\t}\n\t\tif ($draw_circle) {\n\t\t\t$this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);\n\t\t}\n\t\t$p = array();\n\t\tfor ($i = 0; $i < $ns; ++$i) {\n\t\t\t$a = $angle + ($i * 360 / $ns);\n\t\t\t$a_rad = deg2rad((float) $a);\n\t\t\t$p[] = $x0 + ($r * sin($a_rad));\n\t\t\t$p[] = $y0 + ($r * cos($a_rad));\n\t\t}\n\t\t$this->Polygon($p, $style, $line_style, $fill_color);\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct(Http $protocol,\n\t\tMiddlewareDispatcher $middlewareDispatcher,\n\t\tControllerMethodReflector $reflector,\n\t\tIRequest $request,\n\t\tIConfig $config,\n\t\tConnectionAdapter $connection,\n\t\tLoggerInterface $logger,\n\t\tIEventLogger $eventLogger,\n\t\tContainerInterface $appContainer) {\n\t\t$this->protocol = $protocol;\n\t\t$this->middlewareDispatcher = $middlewareDispatcher;\n\t\t$this->reflector = $reflector;\n\t\t$this->request = $request;\n\t\t$this->config = $config;\n\t\t$this->connection = $connection;\n\t\t$this->logger = $logger;\n\t\t$this->eventLogger = $eventLogger;\n\t\t$this->appContainer = $appContainer;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($AppName,\n\t\tIRequest $request,\n\t\tIConfig $config,\n\t\tIURLGenerator $urlGenerator,\n\t\tIL10N $l10n,\n\t\tChecker $checker,\n\t\tLoggerInterface $logger,\n\t\tISetupCheckManager $setupCheckManager,\n\t) {\n\t\tparent::__construct($AppName, $request);\n\t\t$this->config = $config;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->l10n = $l10n;\n\t\t$this->checker = $checker;\n\t\t$this->logger = $logger;\n\t\t$this->setupCheckManager = $setupCheckManager;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function normalcurve3($mu, $sigma, $a, $b, $axislabel='',$x=null, $dirx='left', $y=null, $diry='right', $color='blue', $q=null, $dirq='left', $r=null, $dirr='right', $color2='red', $w=400,$h=150) {\n if ($sigma<=0) { echo 'Invalid sigma'; return;}\n if ($y!==null && $y<$x) { echo 'Second value should be bigger than the first'; return; }\n if ($a>=$b) { echo 'xmin should be smaller than xmax'; return; }\n if ($y!==null && $dirx==$diry) { echo 'directions should not be equal'; return;}\n\n $za = ($a-$mu)/$sigma;\n $zb = ($b-$mu)/$sigma;\n if ($x!==null) {\n \t $zx = ($x-$mu)/$sigma;\n }\n if ($y!==null) {\n $zy = ($y-$mu)/$sigma;\n }\n if ($q!==null) {\n \t $zq = ($q-$mu)/$sigma;\n }\n if ($r!==null) {\n $zr = ($r-$mu)/$sigma;\n }\n $dz = ($zb-$za)/80;\n $zab=$za-$sigma;\n $zbb=$zb+$sigma;\n $plot = \"setBorder(10,30,10,5);initPicture($za,$zb,-.1,.45);line([$zab,0],[$zbb,0]);\";\n for ($i=ceil($za);$i<$zb+$dz;$i++) {\n\t$label = $mu + $i*$sigma;\n\t$plot .= \"line([$i,.02],[$i,-.02]);text([$i,-.01],\\\"$label\\\",\\\"below\\\");\";\n }\n\n $midx = $w/2;\n $plot .= \"textabs([$midx,0],'$axislabel','above');\";\n $pts = array();\n $xpts = array();\n $ypts = array();\n $qpts = array();\n $rpts = array();\n\n $coef = 1/sqrt(2*3.1415926);\n\n if ($x !== null && $dirx=='right') {\n $py = $coef*exp(-$zx*$zx/2);\n $xpts[] = \"[$zx,0]\";\n $xpts[] = \"[$zx,$py]\";\n }\n if ($y !== null && $diry=='right') {\n $py = $coef*exp(-$zy*$zy/2);\n $ypts[] = \"[$zy,$py]\";\n }\n if ($q !== null && $dirq=='right') {\n $pr = $coef*exp(-$zq*$zq/2);\n $qpts[] = \"[$zq,0]\";\n $qpts[] = \"[$zq,$pr]\";\n }\n if ($r !== null && $dirr=='right') {\n $pr = $coef*exp(-$zr*$zr/2);\n $rpts[] = \"[$zr,$pr]\";\n }\n\n for ($z=$za;$z<=$zb+.00001;$z+=$dz) {\n\t$py = $coef*exp(-$z*$z/2);\n $pts[] = \"[$z,$py]\";\n if ($x !== null && (($dirx == 'left' && $z<$zx) || ($dirx == 'right' && $z>$zx && ($y===null || $z<$zy )))) {\n $xpts[] = \"[$z,$py]\";\n }\n if ($y !== null && $diry=='right' && $z>$zy) {\n $ypts[] = \"[$z,$py]\";\n }\n if ($q !== null && (($dirq == 'left' && $z<$zq) || ($dirq == 'right' && $z>$zq && ($r===null || $z<$zr )))) {\n $qpts[] = \"[$z,$py]\";\n }\n if ($r !== null && $dirr=='right' && $z>$zr) {\n $rpts[] = \"[$z,$py]\";\n }\n }\n if ($x !== null && $dirx=='left') {\n $py = $coef*exp(-$zx*$zx/2.0);\n $xpts[] = \"[$zx,$py]\";\n $xpts[] = \"[$zx,0]\";\n $xpts[] = \"[$za,0]\";\n }\n if ($x !== null && $dirx=='right' && $y===null) {\n $xpts[] = \"[$zb,0]\";\n }\n if ($y !== null && $diry=='left') {\n $py = $coef*exp(-$zy*$zy/2.0);\n $xpts[] = \"[$zy,$py]\";\n $xpts[] = \"[$zy,0]\";\n $xpts[] = \"[$zx,0]\";\n }\n if ($y !== null && $diry=='right') {\n $ypts[] = \"[$zb,0]\";\n $ypts[] = \"[$zy,0]\";\n }\n\n if ($q !== null && $dirq=='left') {\n $py = $coef*exp(-$zq*$zq/2.0);\n $qpts[] = \"[$zq,$py]\";\n $qpts[] = \"[$zq,0]\";\n $qpts[] = \"[$zq,0]\";\n }\n if ($q !== null && $dirq=='right' && $r===null) {\n $qpts[] = \"[$zb,0]\";\n }\n if ($r !== null && $dirr=='left') {\n $py = $coef*exp(-$zr*$zr/2.0);\n $qpts[] = \"[$zr,$py]\";\n $qpts[] = \"[$zy,0]\";\n $qpts[] = \"[$zx,0]\";\n }\n if ($r !== null && $dirr=='right') {\n $rpts[] = \"[$zb,0]\";\n $rpts[] = \"[$zr,0]\";\n }\n\n $plot .= 'fill=\"none\";path([' . implode(',',$pts) . ']);';\n if ($x !== null) {\n $plot .= 'fill=\"'.$color.'\";path([' . implode(',',$xpts) . ']);';\n }\n if ($y !== null && $diry=='right') {\n $plot .= 'fill=\"'.$color.'\";path([' . implode(',',$ypts) . ']);';\n }\n if ($q !== null) {\n $plot .= 'fill=\"'.$color2.'\";path([' . implode(',',$qpts) . ']);';\n }\n if ($r !== null && $dirr=='right') {\n $plot .= 'fill=\"'.$color2.'\";path([' . implode(',',$rpts) . ']);';\n }\n return showasciisvg($plot,$w,$h);\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB)\n\t{\n\t\t$record\t = 0x005d; // Record identifier\n\t\t$length\t = 0x003c; // Bytes to follow\n\n\t\t$cObj\t\t= 0x0001; // Count of objects in file (set to 1)\n\t\t$OT\t\t = 0x0008; // Object type. 8 = Picture\n\t\t$id\t\t = 0x0001; // Object ID\n\t\t$grbit\t = 0x0614; // Option flags\n\n\t\t$cbMacro\t = 0x0000; // Length of FMLA structure\n\t\t$Reserved1 = 0x0000; // Reserved\n\t\t$Reserved2 = 0x0000; // Reserved\n\n\t\t$icvBack\t = 0x09;\t // Background colour\n\t\t$icvFore\t = 0x09;\t // Foreground colour\n\t\t$fls\t\t = 0x00;\t // Fill pattern\n\t\t$fAuto\t = 0x00;\t // Automatic fill\n\t\t$icv\t\t = 0x08;\t // Line colour\n\t\t$lns\t\t = 0xff;\t // Line style\n\t\t$lnw\t\t = 0x01;\t // Line weight\n\t\t$fAutoB\t = 0x00;\t // Automatic border\n\t\t$frs\t\t = 0x0000; // Frame style\n\t\t$cf\t\t = 0x0009; // Image format, 9 = bitmap\n\t\t$Reserved3 = 0x0000; // Reserved\n\t\t$cbPictFmla = 0x0000; // Length of FMLA structure\n\t\t$Reserved4 = 0x0000; // Reserved\n\t\t$grbit2\t = 0x0001; // Option flags\n\t\t$Reserved5 = 0x0000; // Reserved\n\n\n\t\t$header\t = pack(\"vv\", $record, $length);\n\t\t$data\t\t= pack(\"V\", $cObj);\n\t\t$data\t .= pack(\"v\", $OT);\n\t\t$data\t .= pack(\"v\", $id);\n\t\t$data\t .= pack(\"v\", $grbit);\n\t\t$data\t .= pack(\"v\", $colL);\n\t\t$data\t .= pack(\"v\", $dxL);\n\t\t$data\t .= pack(\"v\", $rwT);\n\t\t$data\t .= pack(\"v\", $dyT);\n\t\t$data\t .= pack(\"v\", $colR);\n\t\t$data\t .= pack(\"v\", $dxR);\n\t\t$data\t .= pack(\"v\", $rwB);\n\t\t$data\t .= pack(\"v\", $dyB);\n\t\t$data\t .= pack(\"v\", $cbMacro);\n\t\t$data\t .= pack(\"V\", $Reserved1);\n\t\t$data\t .= pack(\"v\", $Reserved2);\n\t\t$data\t .= pack(\"C\", $icvBack);\n\t\t$data\t .= pack(\"C\", $icvFore);\n\t\t$data\t .= pack(\"C\", $fls);\n\t\t$data\t .= pack(\"C\", $fAuto);\n\t\t$data\t .= pack(\"C\", $icv);\n\t\t$data\t .= pack(\"C\", $lns);\n\t\t$data\t .= pack(\"C\", $lnw);\n\t\t$data\t .= pack(\"C\", $fAutoB);\n\t\t$data\t .= pack(\"v\", $frs);\n\t\t$data\t .= pack(\"V\", $cf);\n\t\t$data\t .= pack(\"v\", $Reserved3);\n\t\t$data\t .= pack(\"v\", $cbPictFmla);\n\t\t$data\t .= pack(\"v\", $Reserved4);\n\t\t$data\t .= pack(\"v\", $grbit2);\n\t\t$data\t .= pack(\"V\", $Reserved5);\n\n\t\t$this->_append($header . $data);\n\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(Backend $backend,\n\t\tNotificationProviderManager $notificationProviderManager,\n\t\tIUserManager $userManager,\n\t\tIGroupManager $groupManager,\n\t\tCalDavBackend $caldavBackend,\n\t\tITimeFactory $timeFactory,\n\t\tIConfig $config,\n\t\tLoggerInterface $logger,\n\t\tPrincipal $principalConnector) {\n\t\t$this->backend = $backend;\n\t\t$this->notificationProviderManager = $notificationProviderManager;\n\t\t$this->userManager = $userManager;\n\t\t$this->groupManager = $groupManager;\n\t\t$this->caldavBackend = $caldavBackend;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->config = $config;\n\t\t$this->logger = $logger;\n\t\t$this->principalConnector = $principalConnector;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function getSentPnotesByDate(\n $date,\n $activity = \"1\",\n $cols = \"*\",\n $pid = \"%\",\n $limit = \"all\",\n $start = 0,\n $username = '',\n $docid = 0,\n $status = \"\",\n $orderid = 0\n) {\n\n $sqlParameterArray = array();\n if ($docid) {\n $sql = \"SELECT \" . escape_sql_column_name(process_cols_escape($cols), array('pnotes', 'gprelations')) . \" FROM pnotes AS p, gprelations AS r \" .\n \"WHERE p.date LIKE ? AND r.type1 = 1 AND \" .\n \"r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user\";\n array_push($sqlParameterArray, '%' . $date . '%', $docid);\n } elseif ($orderid) {\n $sql = \"SELECT \" . escape_sql_column_name(process_cols_escape($cols), array('pnotes','gprelations')) . \" FROM pnotes AS p, gprelations AS r \" .\n \"WHERE p.date LIKE ? AND r.type1 = 2 AND \" .\n \"r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user\";\n array_push($sqlParameterArray, '%' . $date . '%', $orderid);\n } else {\n $sql = \"SELECT \" . escape_sql_column_name(process_cols_escape($cols), array('pnotes')) . \" FROM pnotes AS p \" .\n \"WHERE date LIKE ? AND pid LIKE ? AND p.pid = p.user\";\n array_push($sqlParameterArray, '%' . $date . '%', $pid);\n }\n\n $sql .= \" AND deleted != 1\"; // exclude ALL deleted notes\n if ($activity != \"all\") {\n if ($activity == '0') {\n // only return inactive\n $sql .= \" AND (activity = '0' OR message_status = 'Done') \";\n } else { // $activity == '1'\n // only return active\n $sql .= \" AND activity = '1' AND message_status != 'Done' \";\n }\n }\n\n if ($username) {\n $sql .= \" AND assigned_to LIKE ?\";\n array_push($sqlParameterArray, $username);\n }\n\n if ($status) {\n $sql .= \" AND message_status IN ('\" . str_replace(\",\", \"','\", add_escape_custom($status)) . \"')\";\n }\n\n $sql .= \" ORDER BY date DESC\";\n if ($limit != \"all\") {\n $sql .= \" LIMIT \" . escape_limit($start) . \", \" . escape_limit($limit);\n }\n\n $res = sqlStatement($sql, $sqlParameterArray);\n\n $all = array();\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $all[$iter] = $row;\n }\n\n return $all;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $bucketId, string $fileId, mixed $file, ?array $permissions, Request $request, Response $response, Database $dbForProject, Document $user, Event $events, string $mode, Device $deviceFiles, Device $deviceLocal) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $validator = new Authorization(Database::PERMISSION_CREATE);\n if (!$validator->isValid($bucket->getCreate())) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n $allowedPermissions = [\n Database::PERMISSION_READ,\n Database::PERMISSION_UPDATE,\n Database::PERMISSION_DELETE,\n ];\n\n // Map aggregate permissions to into the set of individual permissions they represent.\n $permissions = Permission::aggregate($permissions, $allowedPermissions);\n\n // Add permissions for current the user if none were provided.\n if (\\is_null($permissions)) {\n $permissions = [];\n if (!empty($user->getId())) {\n foreach ($allowedPermissions as $permission) {\n $permissions[] = (new Permission($permission, 'user', $user->getId()))->toString();\n }\n }\n }\n\n // Users can only manage their own roles, API keys and Admin users can manage any\n $roles = Authorization::getRoles();\n if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles)) {\n foreach (Database::PERMISSIONS as $type) {\n foreach ($permissions as $permission) {\n $permission = Permission::parse($permission);\n if ($permission->getPermission() != $type) {\n continue;\n }\n $role = (new Role(\n $permission->getRole(),\n $permission->getIdentifier(),\n $permission->getDimension()\n ))->toString();\n if (!Authorization::isRole($role)) {\n throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \\implode(', ', $roles) . ')');\n }\n }\n }\n }\n\n $maximumFileSize = $bucket->getAttribute('maximumFileSize', 0);\n if ($maximumFileSize > (int) App::getEnv('_APP_STORAGE_LIMIT', 0)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Maximum bucket file size is larger than _APP_STORAGE_LIMIT');\n }\n\n\n $file = $request->getFiles('file');\n\n // GraphQL multipart spec adds files with index keys\n if (empty($file)) {\n $file = $request->getFiles(0);\n }\n\n if (empty($file)) {\n throw new Exception(Exception::STORAGE_FILE_EMPTY);\n }\n\n // Make sure we handle a single file and multiple files the same way\n $fileName = (\\is_array($file['name']) && isset($file['name'][0])) ? $file['name'][0] : $file['name'];\n $fileTmpName = (\\is_array($file['tmp_name']) && isset($file['tmp_name'][0])) ? $file['tmp_name'][0] : $file['tmp_name'];\n $fileSize = (\\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size'];\n\n $contentRange = $request->getHeader('content-range');\n $fileId = $fileId === 'unique()' ? ID::unique() : $fileId;\n $chunk = 1;\n $chunks = 1;\n\n if (!empty($contentRange)) {\n $start = $request->getContentRangeStart();\n $end = $request->getContentRangeEnd();\n $fileSize = $request->getContentRangeSize();\n $fileId = $request->getHeader('x-appwrite-id', $fileId);\n // TODO make `end >= $fileSize` in next breaking version\n if (is_null($start) || is_null($end) || is_null($fileSize) || $end > $fileSize) {\n throw new Exception(Exception::STORAGE_INVALID_CONTENT_RANGE);\n }\n\n $idValidator = new UID();\n if (!$idValidator->isValid($request->getHeader('x-appwrite-id'))) {\n throw new Exception(Exception::STORAGE_INVALID_APPWRITE_ID);\n }\n\n // TODO remove the condition that checks `$end === $fileSize` in next breaking version\n if ($end === $fileSize - 1 || $end === $fileSize) {\n //if it's a last chunks the chunk size might differ, so we set the $chunks and $chunk to -1 notify it's last chunk\n $chunks = $chunk = -1;\n } else {\n // Calculate total number of chunks based on the chunk size i.e ($rangeEnd - $rangeStart)\n $chunks = (int) ceil($fileSize / ($end + 1 - $start));\n $chunk = (int) ($start / ($end + 1 - $start)) + 1;\n }\n }\n\n /**\n * Validators\n */\n // Check if file type is allowed\n $allowedFileExtensions = $bucket->getAttribute('allowedFileExtensions', []);\n $fileExt = new FileExt($allowedFileExtensions);\n if (!empty($allowedFileExtensions) && !$fileExt->isValid($fileName)) {\n throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED, 'File extension not allowed');\n }\n\n // Check if file size is exceeding allowed limit\n $fileSizeValidator = new FileSize($maximumFileSize);\n if (!$fileSizeValidator->isValid($fileSize)) {\n throw new Exception(Exception::STORAGE_INVALID_FILE_SIZE, 'File size not allowed');\n }\n\n $upload = new Upload();\n if (!$upload->isValid($fileTmpName)) {\n throw new Exception(Exception::STORAGE_INVALID_FILE);\n }\n\n // Save to storage\n $fileSize ??= $deviceLocal->getFileSize($fileTmpName);\n $path = $deviceFiles->getPath($fileId . '.' . \\pathinfo($fileName, PATHINFO_EXTENSION));\n $path = str_ireplace($deviceFiles->getRoot(), $deviceFiles->getRoot() . DIRECTORY_SEPARATOR . $bucket->getId(), $path); // Add bucket id to path after root\n\n $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);\n\n $metadata = ['content_type' => $deviceLocal->getFileMimeType($fileTmpName)];\n if (!$file->isEmpty()) {\n $chunks = $file->getAttribute('chunksTotal', 1);\n $uploaded = $file->getAttribute('chunksUploaded', 0);\n $metadata = $file->getAttribute('metadata', []);\n\n if ($chunk === -1) {\n $chunk = $chunks;\n }\n\n if ($uploaded === $chunks) {\n throw new Exception(Exception::STORAGE_FILE_ALREADY_EXISTS);\n }\n }\n\n $chunksUploaded = $deviceFiles->upload($fileTmpName, $path, $chunk, $chunks, $metadata);\n\n if (empty($chunksUploaded)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed uploading file');\n }\n\n if ($chunksUploaded === $chunks) {\n if (App::getEnv('_APP_STORAGE_ANTIVIRUS') === 'enabled' && $bucket->getAttribute('antivirus', true) && $fileSize <= APP_LIMIT_ANTIVIRUS && $deviceFiles->getType() === Storage::DEVICE_LOCAL) {\n $antivirus = new Network(\n App::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),\n (int) App::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)\n );\n\n if (!$antivirus->fileScan($path)) {\n $deviceFiles->delete($path);\n throw new Exception(Exception::STORAGE_INVALID_FILE);\n }\n }\n\n $mimeType = $deviceFiles->getFileMimeType($path); // Get mime-type before compression and encryption\n $fileHash = $deviceFiles->getFileHash($path); // Get file hash before compression and encryption\n $data = '';\n // Compression\n $algorithm = $bucket->getAttribute('compression', COMPRESSION_TYPE_NONE);\n if ($fileSize <= APP_STORAGE_READ_BUFFER && $algorithm != COMPRESSION_TYPE_NONE) {\n $data = $deviceFiles->read($path);\n switch ($algorithm) {\n case COMPRESSION_TYPE_ZSTD:\n $compressor = new Zstd();\n break;\n case COMPRESSION_TYPE_GZIP:\n default:\n $compressor = new GZIP();\n break;\n }\n $data = $compressor->compress($data);\n }\n\n if ($bucket->getAttribute('encryption', true) && $fileSize <= APP_STORAGE_READ_BUFFER) {\n if (empty($data)) {\n $data = $deviceFiles->read($path);\n }\n $key = App::getEnv('_APP_OPENSSL_KEY_V1');\n $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM));\n $data = OpenSSL::encrypt($data, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag);\n }\n\n if (!empty($data)) {\n if (!$deviceFiles->write($path, $data, $mimeType)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to save file');\n }\n }\n\n $sizeActual = $deviceFiles->getFileSize($path);\n\n $openSSLVersion = null;\n $openSSLCipher = null;\n $openSSLTag = null;\n $openSSLIV = null;\n\n if ($bucket->getAttribute('encryption', true) && $fileSize <= APP_STORAGE_READ_BUFFER) {\n $openSSLVersion = '1';\n $openSSLCipher = OpenSSL::CIPHER_AES_128_GCM;\n $openSSLTag = \\bin2hex($tag);\n $openSSLIV = \\bin2hex($iv);\n }\n\n try {\n if ($file->isEmpty()) {\n $doc = new Document([\n '$id' => $fileId,\n '$permissions' => $permissions,\n 'bucketId' => $bucket->getId(),\n 'bucketInternalId' => $bucket->getInternalId(),\n 'name' => $fileName,\n 'path' => $path,\n 'signature' => $fileHash,\n 'mimeType' => $mimeType,\n 'sizeOriginal' => $fileSize,\n 'sizeActual' => $sizeActual,\n 'algorithm' => $algorithm,\n 'comment' => '',\n 'chunksTotal' => $chunks,\n 'chunksUploaded' => $chunksUploaded,\n 'openSSLVersion' => $openSSLVersion,\n 'openSSLCipher' => $openSSLCipher,\n 'openSSLTag' => $openSSLTag,\n 'openSSLIV' => $openSSLIV,\n 'search' => implode(' ', [$fileId, $fileName]),\n 'metadata' => $metadata,\n ]);\n\n $file = $dbForProject->createDocument('bucket_' . $bucket->getInternalId(), $doc);\n } else {\n $file = $file\n ->setAttribute('$permissions', $permissions)\n ->setAttribute('signature', $fileHash)\n ->setAttribute('mimeType', $mimeType)\n ->setAttribute('sizeActual', $sizeActual)\n ->setAttribute('algorithm', $algorithm)\n ->setAttribute('openSSLVersion', $openSSLVersion)\n ->setAttribute('openSSLCipher', $openSSLCipher)\n ->setAttribute('openSSLTag', $openSSLTag)\n ->setAttribute('openSSLIV', $openSSLIV)\n ->setAttribute('metadata', $metadata)\n ->setAttribute('chunksUploaded', $chunksUploaded);\n\n $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file);\n }\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (StructureException $exception) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, $exception->getMessage());\n } catch (DuplicateException) {\n throw new Exception(Exception::DOCUMENT_ALREADY_EXISTS);\n }\n } else {\n try {\n if ($file->isEmpty()) {\n $doc = new Document([\n '$id' => ID::custom($fileId),\n '$permissions' => $permissions,\n 'bucketId' => $bucket->getId(),\n 'bucketInternalId' => $bucket->getInternalId(),\n 'name' => $fileName,\n 'path' => $path,\n 'signature' => '',\n 'mimeType' => '',\n 'sizeOriginal' => $fileSize,\n 'sizeActual' => 0,\n 'algorithm' => '',\n 'comment' => '',\n 'chunksTotal' => $chunks,\n 'chunksUploaded' => $chunksUploaded,\n 'search' => implode(' ', [$fileId, $fileName]),\n 'metadata' => $metadata,\n ]);\n\n $file = $dbForProject->createDocument('bucket_' . $bucket->getInternalId(), $doc);\n } else {\n $file = $file\n ->setAttribute('chunksUploaded', $chunksUploaded)\n ->setAttribute('metadata', $metadata);\n\n $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file);\n }\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (StructureException $exception) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, $exception->getMessage());\n } catch (DuplicateException) {\n throw new Exception(Exception::DOCUMENT_ALREADY_EXISTS);\n }\n }\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ->setParam('fileId', $file->getId())\n ->setContext('bucket', $bucket)\n ;\n\n $metadata = null; // was causing leaks as it was passed by reference\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($file, Response::MODEL_FILE);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function capturePayment($account, $amount, $currency, $order_id, $order_ref, $card_number, $expire, $name, $type, $cvv, $issue, $eci_ref, $eci = '', $cavv = '', $xid = '') {\n\t\t$this->load->model('checkout/order');\n\n\t\t$timestamp = strftime(\"%Y%m%d%H%M%S\");\n\t\t$merchant_id = $this->config->get('payment_realex_remote_merchant_id');\n\t\t$secret = $this->config->get('payment_realex_remote_secret');\n\n\t\t$tmp = $timestamp . '.' . $merchant_id . '.' . $order_ref . '.' . $amount . '.' . $currency . '.' . $card_number;\n\t\t$hash = sha1($tmp);\n\t\t$tmp = $hash . '.' . $secret;\n\t\t$hash = sha1($tmp);\n\n\t\t$order_info = $this->model_checkout_order->getOrder($order_id);\n\n\t\t$xml = '';\n\t\t$xml .= '';\n\t\t\t$xml .= '' . $merchant_id . '';\n\t\t\t$xml .= '' . $account . '';\n\t\t\t$xml .= '' . $order_ref . '';\n\t\t\t$xml .= '' . $amount . '';\n\t\t\t$xml .= '';\n\t\t\t\t$xml .= 'OpenCart';\n\t\t\t$xml .= '';\n\t\t\t$xml .= '';\n\t\t\t\t$xml .= '' . $card_number . '';\n\t\t\t\t$xml .= '' . $expire . '';\n\t\t\t\t$xml .= '' . $type . '';\n\t\t\t\t$xml .= '' . $name . '';\n\t\t\t\t$xml .= '';\n\t\t\t\t\t$xml .= '' . (int)$cvv . '';\n\t\t\t\t\t$xml .= '2';\n\t\t\t\t$xml .= '';\n\t\t\t\tif (!empty($issue)) {\n\t\t\t\t\t$xml .= '' . (int)$issue . '';\n\t\t\t\t}\n\t\t\t$xml .= '';\n\n\t\t\tif ($this->config->get('payment_realex_remote_auto_settle') == 0) {\n\t\t\t\t$xml .= '';\n\t\t\t} elseif ($this->config->get('payment_realex_remote_auto_settle') == 1) {\n\t\t\t\t$xml .= '';\n\t\t\t} elseif ($this->config->get('payment_realex_remote_auto_settle') == 2) {\n\t\t\t\t$xml .= '';\n\t\t\t}\n\n\t\t\tif ($eci != '' || $cavv != '' || $xid != '') {\n\t\t\t\t$xml .= '';\n\t\t\t\t\tif ($eci != '') {\n\t\t\t\t\t\t$xml .= '' . (string)$eci . '';\n\t\t\t\t\t}\n\t\t\t\t\tif ($cavv != '') {\n\t\t\t\t\t\t$xml .= '' . (string)$cavv . '';\n\t\t\t\t\t}\n\t\t\t\t\tif ($xid != '') {\n\t\t\t\t\t\t$xml .= '' . (string)$xid . '';\n\t\t\t\t\t}\n\t\t\t\t$xml .= '';\n\t\t\t}\n\n\t\t\t$xml .= '' . $hash . '';\n\n\t\t\tif ($this->config->get('payment_realex_remote_tss_check') == 1) {\n\t\t\t\t$xml .= '';\n\t\t\t\t\t$xml .= '' . $order_info['ip'] . '';\n\n\t\t\t\t\tif ($this->customer->getId() > 0) {\n\t\t\t\t\t\t$xml .= '' . (int)$this->customer->getId() . '';\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((isset($order_info['payment_iso_code_2']) && !empty($order_info['payment_iso_code_2'])) || (isset($order_info['payment_postcode']) && !empty($order_info['payment_postcode']))) {\n\t\t\t\t\t\t$xml .= '
    ';\n\t\t\t\t\t\tif ((isset($order_info['payment_postcode']) && !empty($order_info['payment_postcode']))) {\n\t\t\t\t\t\t\t$xml .= '' . filter_var($order_info['payment_postcode'], FILTER_SANITIZE_NUMBER_INT) . '|' . filter_var($order_info['payment_address_1'], FILTER_SANITIZE_NUMBER_INT) . '';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((isset($order_info['payment_iso_code_2']) && !empty($order_info['payment_iso_code_2']))) {\n\t\t\t\t\t\t\t$xml .= '' . $order_info['payment_iso_code_2'] . '';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$xml .= '
    ';\n\t\t\t\t\t}\n\t\t\t\t\tif ((isset($order_info['shipping_iso_code_2']) && !empty($order_info['shipping_iso_code_2'])) || (isset($order_info['shipping_postcode']) && !empty($order_info['shipping_postcode']))) {\n\t\t\t\t\t\t$xml .= '
    ';\n\t\t\t\t\t\tif ((isset($order_info['shipping_postcode']) && !empty($order_info['shipping_postcode']))) {\n\t\t\t\t\t\t\t$xml .= '' . filter_var($order_info['shipping_postcode'], FILTER_SANITIZE_NUMBER_INT) . '|' . filter_var($order_info['shipping_address_1'], FILTER_SANITIZE_NUMBER_INT) . '';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((isset($order_info['shipping_iso_code_2']) && !empty($order_info['shipping_iso_code_2']))) {\n\t\t\t\t\t\t\t$xml .= '' . $order_info['shipping_iso_code_2'] . '';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$xml .= '
    ';\n\t\t\t\t\t}\n\t\t\t\t$xml .= '
    ';\n\t\t\t}\n\n\t\t$xml .= '
    ';\n\n\t\t$this->logger('capturePayment call');\n\t\t$this->logger(simplexml_load_string($xml));\n\t\t$this->logger($xml);\n\n\t\t$ch = curl_init();\n\t\tcurl_setopt($ch, CURLOPT_URL, \"https://epage.payandshop.com/epage-remote.cgi\");\n\t\tcurl_setopt($ch, CURLOPT_POST, 1);\n\t\tcurl_setopt($ch, CURLOPT_USERAGENT, \"OpenCart \" . VERSION);\n\t\tcurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n\t\tcurl_setopt($ch, CURLOPT_POSTFIELDS, $xml);\n\t\tcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\n\t\t$response = curl_exec ($ch);\n\t\tcurl_close ($ch);\n\n\t\t$this->logger('capturePayment xml response');\n\t\t$this->logger($response);\n\n\t\t$response = simplexml_load_string($response);\n\n\t\t$this->load->language('extension/payment/realex_remote');\n\n\t\t$message = '' . $this->language->get('text_result') . ': ' . (int)$response->result;\n\t\t$message .= '
    ' . $this->language->get('text_message') . ': ' . (string)$response->message;\n\t\t$message .= '
    ' . $this->language->get('text_order_ref') . ': ' . (string)$order_ref;\n\n\t\tif (isset($response->cvnresult) && !empty($response->cvnresult)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_cvn_result') . ': ' . (string)$response->cvnresult;\n\t\t}\n\n\t\tif (isset($response->avspostcoderesponse) && !empty($response->avspostcoderesponse)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_avs_postcode') . ': ' . (string)$response->avspostcoderesponse;\n\t\t}\n\n\t\tif (isset($response->avsaddressresponse) && !empty($response->avsaddressresponse)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_avs_address') . ': ' . (string)$response->avsaddressresponse;\n\t\t}\n\n\t\tif (isset($response->authcode) && !empty($response->authcode)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_auth_code') . ': ' . (string)$response->authcode;\n\t\t}\n\n\t\tif (!empty($eci_ref)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_eci') . ': (' . (int)$eci . ') ' . $this->language->get('text_3d_s' . (int)$eci_ref);\n\t\t}\n\n\t\tif (isset($response->tss->result) && !empty($response->tss->result)) {\n\t\t\t$message .= '
    ' . $this->language->get('text_tss') . ': ' . (int)$response->tss->result;\n\t\t}\n\n\t\t$message .= '
    ' . $this->language->get('text_timestamp') . ': ' . (string)$timestamp;\n\n\t\tif ($this->config->get('payment_realex_remote_card_data_status') == 1) {\n\t\t\t$message .= '
    ' . $this->language->get('entry_cc_type') . ': ' . (string)$type;\n\t\t\t$message .= '
    ' . $this->language->get('text_last_digits') . ': ' . (string)substr($card_number, -4);\n\t\t\t$message .= '
    ' . $this->language->get('entry_cc_expire_date') . ': ' . (string)$expire;\n\t\t\t$message .= '
    ' . $this->language->get('entry_cc_name') . ': ' . (string)$name;\n\n\t\t\tif (isset($response->cardissuer->bank) && !empty($response->cardissuer->bank)) {\n\t\t\t\t$message .= '
    ' . $this->language->get('text_card_bank') . ': ' . (string)$response->cardissuer->bank;\n\t\t\t}\n\n\t\t\tif (isset($response->cardissuer->country) && !empty($response->cardissuer->country)) {\n\t\t\t\t$message .= '
    ' . $this->language->get('text_card_country') . ': ' . (string)$response->cardissuer->country;\n\t\t\t}\n\n\t\t\tif (isset($response->cardissuer->region) && !empty($response->cardissuer->region)) {\n\t\t\t\t$message .= '
    ' . $this->language->get('text_card_region') . ': ' . (string)$response->cardissuer->region;\n\t\t\t}\n\t\t}\n\n\t\tif ($response->result == '00') {\n\t\t\t$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('config_order_status_id'));\n\n\t\t\t$realex_order_id = $this->addOrder($order_info, $response, $account, $order_ref);\n\n\t\t\tif ($this->config->get('payment_realex_remote_auto_settle') == 1) {\n\t\t\t\t$this->addTransaction($realex_order_id, 'payment', $order_info);\n\t\t\t\t$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('payment_realex_remote_order_status_success_settled_id'), $message);\n\t\t\t} else {\n\t\t\t\t$this->addTransaction($realex_order_id, 'auth', 0);\n\t\t\t\t$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('payment_realex_remote_order_status_success_unsettled_id'), $message);\n\t\t\t}\n\t\t} elseif ($response->result == \"101\") {\n\t\t\t// Decline\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_id'), $message);\n\t\t} elseif ($response->result == \"102\") {\n\t\t\t// Referal B\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_pending_id'), $message);\n\t\t} elseif ($response->result == \"103\") {\n\t\t\t// Referal A\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_stolen_id'), $message);\n\t\t} elseif ($response->result == \"200\") {\n\t\t\t// Error Connecting to Bank\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_bank_id'), $message);\n\t\t} elseif ($response->result == \"204\") {\n\t\t\t// Error Connecting to Bank\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_bank_id'), $message);\n\t\t} elseif ($response->result == \"205\") {\n\t\t\t// Comms Error\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_bank_id'), $message);\n\t\t} else {\n\t\t\t// Other\n\t\t\t$this->addHistory($order_id, $this->config->get('payment_realex_remote_order_status_decline_id'), $message);\n\t\t}\n\n\t\treturn $response;\n\t}", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "public function __construct(string $appName,\n\t\tIRequest $request,\n\t\tIURLGenerator $urlGenerator,\n\t\tIL10N $l10n,\n\t\tIConfig $config,\n\t\tIEventDispatcher $eventDispatcher,\n\t\tIUserSession $userSession,\n\t\tIAppManager $appManager,\n\t\tIRootFolder $rootFolder,\n\t\tHelper $activityHelper,\n\t\tIInitialState $initialState,\n\t\tITemplateManager $templateManager,\n\t\tIManager $shareManager,\n\t\tUserConfig $userConfig,\n\t\tViewConfig $viewConfig\n\t) {\n\t\tparent::__construct($appName, $request);\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->l10n = $l10n;\n\t\t$this->config = $config;\n\t\t$this->eventDispatcher = $eventDispatcher;\n\t\t$this->userSession = $userSession;\n\t\t$this->appManager = $appManager;\n\t\t$this->rootFolder = $rootFolder;\n\t\t$this->activityHelper = $activityHelper;\n\t\t$this->initialState = $initialState;\n\t\t$this->templateManager = $templateManager;\n\t\t$this->shareManager = $shareManager;\n\t\t$this->userConfig = $userConfig;\n\t\t$this->viewConfig = $viewConfig;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function creerDossierIBTrackingKlsa($ref_dos, $id_cli, $t1, $poids, \n\t\t\t\t\t\t\t\t\t\t$ref_fact, $horse, $trailer_1, $trailer_2, \n\t\t\t\t\t\t\t\t\t\t$transporteur, $destination, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$arrival_date, $crossing_date, $wiski_arriv, \n\t\t\t\t\t\t\t\t\t\t$wiski_dep, $remarque, $id_util, $id_mod_lic, \n\t\t\t\t\t\t\t\t\t\t$num_lic){\n\t\t\tinclude('connexion.php');\n\n\t\t\t/*echo '
    ref_dos = '.$ref_dos;echo '
    id_cli = '.$id_cli;\n\t\t\techo '
    t1 = '.$t1;echo '
    poids = '.$poids;\n\t\t\techo '
    ref_fact = '.$ref_fact;echo '
    horse = '.$horse;\n\t\t\techo '
    trailer_1 = '.$trailer_1;echo '
    trailer_2 = '.$trailer_2;\n\t\t\techo '
    transporteur = '.$transporteur;echo '
    destination = '.$destination;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;echo '
    arrival_date = '.$arrival_date;\n\t\t\techo '
    crossing_date = '.$crossing_date;echo '
    wiski_arriv = '.$wiski_arriv;\n\t\t\techo '
    wiski_dep = '.$wiski_dep;echo '
    remarque = '.$remarque;\n\t\t\techo '
    id_util = '.$id_util;echo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '

    ------------';*/\n\t\t\t//echo '
    transporteur = '.$transporteur;\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['t1'] = $t1; \n\t\t\t$entree['poids'] = $poids; $entree['ref_fact'] = $ref_fact; $entree['horse'] = $horse; \n\t\t\t$entree['trailer_1'] = $trailer_1; $entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['transporteur'] = $transporteur; $entree['destination'] = $destination; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['arrival_date'] = $arrival_date;\n\t\t\t$entree['crossing_date'] = $crossing_date;$entree['wiski_arriv'] = $wiski_arriv;\n\t\t\t$entree['wiski_dep'] = $wiski_dep;$entree['remarque'] = $remarque;\n\t\t\t$entree['id_util'] = $id_util; $entree['id_mod_lic'] = $id_mod_lic; \n\t\t\t$entree['num_lic'] = $num_lic;\n\n\t\t\tif($entree['arrival_date'] == '' || (strlen($entree['arrival_date']) != 10) ){\n\t\t\t\t$entree['arrival_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['crossing_date'] == '' || (strlen($entree['crossing_date']) != 10) ){\n\t\t\t\t$entree['crossing_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_arriv'] == '' || (strlen($entree['wiski_arriv']) != 10) ){\n\t\t\t\t$entree['wiski_arriv'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['wiski_dep'] == '' || (strlen($entree['wiski_dep']) != 10) ){\n\t\t\t\t$entree['wiski_dep'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, t1, poids, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_fact, horse, trailer_1, trailer_2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransporteur, destination, id_mod_trans, arrival_date,crossing_date, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twiski_arriv, wiski_dep, remarque, id_util, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, num_lic)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['t1'], \n\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['ref_fact'], $entree['horse'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_1'], $entree['trailer_2'], $entree['transporteur'], \n\t\t\t\t\t\t\t\t\t$entree['destination'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['arrival_date'], $entree['crossing_date'], $entree['wiski_arriv'], \n\t\t\t\t\t\t\t\t\t$entree['wiski_dep'], $entree['remarque'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['num_lic']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function Lista_curso_Crea_IMPARTICION_CreaImparticion($id_empresa, $codigo_imparticion, $id_curso, $fecha_inicio, $fecha_termino, $direccion, $ciudad, $cupos, $id_malla, $tipo_audiencia, $arreglo_post, $sesiones, $ejecutivo, $comentarios, $observacion, $hora_inicio, $hora_termino, $nombre, $relator, $streaming, $minimo_asistencia, $minimo_nota_aprobacion, $ejecutivo_externo)\n{\n $connexion = new DatabasePDO();\n //$comentarios1=($comentarios);\n //$comentarios2=($comentarios);\n $comentarios3=utf8_encode($comentarios);\n $nombre=utf8_encode($nombre);\n $sql = \"select id from tbl_inscripcion_curso where codigo_inscripcion='$codigo_imparticion' limit 1\";\n $connexion->query($sql);\n $cod = $connexion->resultset();\n\t$malla_bch=$_POST[\"malla_bch\"];\n\t$categoria_bch=$_POST[\"categoria_bch\"];\n if ($streaming <> \"\") {\n $direccion = $streaming;\n $comuna = \"STREAMING\";\n } else {\n $direccion = $direccion;\n $comuna = \"\";\n\n }\n\n $id = $cod[0]->id;\n //echo \"id $id\";\n if ($id > 0) {\n\n if($relator<>\"\"){\n $qrelator=\" id_audiencia='$relator', \";\n } else {\n $qrelator=\"\";\n }\n\n $sql = \"\nupdate tbl_inscripcion_curso\nset \ncodigo_inscripcion='\" . $codigo_imparticion . \"',\nfecha_inicio='$fecha_inicio', \nfecha_termino='$fecha_termino', \ndireccion='$direccion', \ncomuna='$comuna', \nciudad='$ciudad', \nid_curso='$id_curso', \nid_empresa='$id_empresa', \ncupos='$cupos', \nid_malla='$id_malla', \ntipo_audiencia='$tipo_audiencia', \nejecutivo='$ejecutivo', \ncomentarios='$comentarios3',\nobservacion='$observacion', \nhora_inicio='$hora_inicio', \nhora_termino='$hora_termino', \nnombre='\" . $nombre . \"',\n$qrelator\narchivo='\" . $ejecutivo_externo . \"',\nminimo_asistencia='$minimo_asistencia',\nminimo_nota_aprobacion='$minimo_nota_aprobacion',\nabierto_cerrado='$malla_bch', \npago='$categoria_bch'\n\nwhere id='\" . $id . \"'\";\n\n } else {\n $sql = \"\nINSERT INTO tbl_inscripcion_curso\n(codigo_inscripcion, fecha_inicio, fecha_termino, direccion, comuna, ciudad, id_curso, id_empresa, cupos, id_malla, tipo_audiencia, ejecutivo, comentarios,observacion, hora_inicio, hora_termino, nombre,id_audiencia,minimo_asistencia,minimo_nota_aprobacion, abierto_cerrado, pago) \" .\n \"VALUES ('$codigo_imparticion', '$fecha_inicio', '$fecha_termino', '$direccion', '$comuna', '$ciudad', '$id_curso', '$id_empresa', '$cupos', '$id_malla', '$tipo_audiencia','$ejecutivo','$comentarios','$observacion', '$hora_inicio', '$hora_termino', '$nombre', '$relator', '$minimo_asistencia', '$minimo_nota_aprobacion', '$malla_bch', '$categoria_bch');\";\n }\n\n\n\t $connexion->query($sql);\n $connexion->execute();\n // echo $sql; exit();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept, $encounter = 0, $copay = 0, $patcopay = 0)\n{\n global $sum_charges, $sum_ptpaid, $sum_inspaid, $sum_duept, $sum_copay, $sum_patcopay, $sum_balance;\n global $var_index;\n $var_index++;\n $balance = FormatMoney::getBucks($charges - $ptpaid - $inspaid);\n $balance = (round($duept, 2) != 0) ? 0 : $balance; // if balance is due from patient, then insurance balance is displayed as zero\n $encounter = $encounter ? $encounter : '';\n echo \" \\n\";\n echo \" \" . text(oeFormatShortDate($date)) . \"\\n\";\n echo \" \" . text($encounter) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($charges)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($inspaid * -1)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($ptpaid * -1)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($patcopay)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($copay)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($balance)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks(round($duept, 2) * 1)) . \"\\n\";\n echo \" \\n\";\n echo \" \\n\";\n\n $sum_charges += (float)$charges * 1;\n $sum_ptpaid += (float)$ptpaid * -1;\n $sum_inspaid += (float)$inspaid * -1;\n $sum_duept += (float)$duept * 1;\n $sum_patcopay += (float)$patcopay * 1;\n $sum_copay += (float)$copay * 1;\n $sum_balance += (float)$balance * 1;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ibase_pconnect(string $database = null, string $username = null, string $password = null, string $charset = null, int $buffers = null, int $dialect = null, string $role = null, int $sync = null)\n{\n error_clear_last();\n if ($sync !== null) {\n $result = \\ibase_pconnect($database, $username, $password, $charset, $buffers, $dialect, $role, $sync);\n } elseif ($role !== null) {\n $result = \\ibase_pconnect($database, $username, $password, $charset, $buffers, $dialect, $role);\n } elseif ($dialect !== null) {\n $result = \\ibase_pconnect($database, $username, $password, $charset, $buffers, $dialect);\n } elseif ($buffers !== null) {\n $result = \\ibase_pconnect($database, $username, $password, $charset, $buffers);\n } elseif ($charset !== null) {\n $result = \\ibase_pconnect($database, $username, $password, $charset);\n } elseif ($password !== null) {\n $result = \\ibase_pconnect($database, $username, $password);\n } elseif ($username !== null) {\n $result = \\ibase_pconnect($database, $username);\n } elseif ($database !== null) {\n $result = \\ibase_pconnect($database);\n } else {\n $result = \\ibase_pconnect();\n }\n if ($result === false) {\n throw IbaseException::createFromPhpError();\n }\n return $result;\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function fetchAppointments($from_date, $to_date, $patient_id = null, $provider_id = null, $facility_id = null, $pc_appstatus = null, $with_out_provider = null, $with_out_facility = null, $pc_catid = null, $tracker_board = false, $nextX = 0, $group_id = null, $patient_name = null)\n{\n $sqlBindArray = array();\n\n $where = \"\";\n\n if ($provider_id) {\n $where .= \" AND e.pc_aid = ?\";\n array_push($sqlBindArray, $provider_id);\n }\n\n if ($patient_id) {\n $where .= \" AND e.pc_pid = ?\";\n array_push($sqlBindArray, $patient_id);\n } elseif ($group_id) {\n //if $group_id this means we want only the group events\n $where .= \" AND e.pc_gid = ? AND e.pc_pid = ''\";\n array_push($sqlBindArray, $group_id);\n } else {\n $where .= \" AND e.pc_pid != ''\";\n }\n\n if ($facility_id) {\n $where .= \" AND e.pc_facility = ?\";\n array_push($sqlBindArray, $facility_id);\n }\n\n //Appointment Status Checking\n if ($pc_appstatus != '') {\n $where .= \" AND e.pc_apptstatus = ?\";\n array_push($sqlBindArray, $pc_appstatus);\n }\n\n if ($pc_catid != null) {\n $where .= \" AND e.pc_catid = ?\";\n array_push($sqlBindArray, $pc_catid);\n }\n\n if ($patient_name != null) {\n $where .= \" AND (p.fname LIKE CONCAT('%',?,'%') OR p.lname LIKE CONCAT('%',?,'%'))\";\n array_push($sqlBindArray, $patient_name, $patient_name);\n }\n\n //Without Provider checking\n if ($with_out_provider != '') {\n $where .= \" AND e.pc_aid = ''\";\n }\n\n //Without Facility checking\n if ($with_out_facility != '') {\n $where .= \" AND e.pc_facility = 0\";\n }\n\n $appointments = fetchEvents($from_date, $to_date, $where, '', $tracker_board, $nextX, $sqlBindArray);\n return $appointments;\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {\n\t\tif ($this->state != 2) {\n\t\t\t return;\n\t\t}\n\t\tif ($this->rtl) {\n\t\t\t$xc = ($this->w - $xc);\n\t\t}\n\t\t$op = TCPDF_STATIC::getPathPaintOperator($style);\n\t\tif ($op == 'f') {\n\t\t\t$line_style = array();\n\t\t}\n\t\tif ($cw) {\n\t\t\t$d = $b;\n\t\t\t$b = (360 - $a + $o);\n\t\t\t$a = (360 - $d + $o);\n\t\t} else {\n\t\t\t$b += $o;\n\t\t\t$a += $o;\n\t\t}\n\t\t$this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);\n\t\t$this->_out($op);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function (string $bucketId, string $fileId, Response $response, Database $dbForProject, Event $events, string $mode, Device $deviceFiles, Delete $deletes) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_DELETE);\n $valid = $validator->isValid($bucket->getDelete());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n // Read permission should not be required for delete\n $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n\n if ($file->isEmpty()) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);\n }\n\n // Make sure we don't delete the file before the document permission check occurs\n if ($fileSecurity && !$valid && !$validator->isValid($file->getDelete())) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n $deviceDeleted = false;\n if ($file->getAttribute('chunksTotal') !== $file->getAttribute('chunksUploaded')) {\n $deviceDeleted = $deviceFiles->abort(\n $file->getAttribute('path'),\n ($file->getAttribute('metadata', [])['uploadId'] ?? '')\n );\n } else {\n $deviceDeleted = $deviceFiles->delete($file->getAttribute('path'));\n }\n\n if ($deviceDeleted) {\n $deletes\n ->setType(DELETE_TYPE_CACHE_BY_RESOURCE)\n ->setResource('file/' . $fileId)\n ;\n\n if ($fileSecurity && !$valid) {\n try {\n $deleted = $dbForProject->deleteDocument('bucket_' . $bucket->getInternalId(), $fileId);\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n } else {\n $deleted = Authorization::skip(fn() => $dbForProject->deleteDocument('bucket_' . $bucket->getInternalId(), $fileId));\n }\n\n if (!$deleted) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove file from DB');\n }\n } else {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to delete file from device');\n }\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ->setParam('fileId', $file->getId())\n ->setContext('bucket', $bucket)\n ->setPayload($response->output($file, Response::MODEL_FILE))\n ;\n\n $response->noContent();\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function getSQLToCreateForeignKey(\n string $table,\n array $field,\n string $foreignDb,\n string $foreignTable,\n array $foreignField,\n string|null $name = null,\n string|null $onDelete = null,\n string|null $onUpdate = null,\n ): string {\n $sqlQuery = 'ALTER TABLE ' . Util::backquote($table) . ' ADD ';\n // if user entered a constraint name\n if ($name !== null && $name !== '') {\n $sqlQuery .= ' CONSTRAINT ' . Util::backquote($name);\n }\n\n foreach ($field as $key => $oneField) {\n $field[$key] = Util::backquote($oneField);\n }\n\n foreach ($foreignField as $key => $oneField) {\n $foreignField[$key] = Util::backquote($oneField);\n }\n\n $sqlQuery .= ' FOREIGN KEY (' . implode(', ', $field) . ') REFERENCES '\n . ($this->dbName !== $foreignDb\n ? Util::backquote($foreignDb) . '.' : '')\n . Util::backquote($foreignTable)\n . '(' . implode(', ', $foreignField) . ')';\n\n if ($onDelete !== null && $onDelete !== '') {\n $sqlQuery .= ' ON DELETE ' . $onDelete;\n }\n\n if ($onUpdate !== null && $onUpdate !== '') {\n $sqlQuery .= ' ON UPDATE ' . $onUpdate;\n }\n\n $sqlQuery .= ';';\n\n return $sqlQuery;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null)\n {\n $this->activateObject();\n (!is_null($line_width))\n ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width)\n : null;\n (!is_null($compound_type))\n ? $this->lineProperties['style']['compound'] = (string) $compound_type\n : null;\n (!is_null($dash_type))\n ? $this->lineProperties['style']['dash'] = (string) $dash_type\n : null;\n (!is_null($cap_type))\n ? $this->lineProperties['style']['cap'] = (string) $cap_type\n : null;\n (!is_null($join_type))\n ? $this->lineProperties['style']['join'] = (string) $join_type\n : null;\n (!is_null($head_arrow_type))\n ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type\n : null;\n (!is_null($head_arrow_size))\n ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size\n : null;\n (!is_null($end_arrow_type))\n ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type\n : null;\n (!is_null($end_arrow_size))\n ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size\n : null;\n }", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "public function __construct(\t$id,\t\t\t\t\t\t\t// $id = id de la notice afficher\n\t\t\t\t\t\t$level=1, \t\t\t\t\t\t// $level :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\t0 : juste le header (titre / auteur principal avec le lien si applicable)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\t1 : ISBD seul, pas de note, bouton modif, expl, explnum et rsas\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// \t6 : cas gnral dtaill avec notes, categ, langues, indexation... + boutons\n\t\t\t\t\t\t$action='', \t\t\t\t\t// $action\t = URL associe au header\n\t\t\t\t\t\t$expl=1, \t\t\t\t\t\t// $expl -> affiche ou non les exemplaires associs\n\t\t\t\t\t\t$expl_link='', \t\t\t\t\t// $expl_link -> lien associ l'exemplaire avec !!expl_id!!, !!notice_id!! et !!expl_cb!! mettre jour\n\t\t\t\t\t\t$lien_suppr_cart=\"\", \t\t\t// $lien_suppr_cart -> lien de suppression de la notice d'un caddie\n\t\t\t\t\t\t$explnum_link='',\n\t\t\t\t\t\t$show_resa=0, \t\t\t\t// $show_resa = affichage des resa ou pas\n\t\t\t\t\t\t$print=0, \t\t\t\t\t\t// $print = 0 affichage normal\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\t\t\t1 affichage impression sans liens\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\t\t\t2 affichage impression avec liens sur documents numeriques\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\t\t\t4 affichage email : sans lien sauf url associe\n\t\t\t\t\t\t$show_explnum=1,\n\t\t\t\t\t\t$show_statut=0,\n\t\t\t\t\t\t$anti_loop = array(),\n\t\t\t\t\t\t$draggable=0,\n\t\t\t\t\t\t$no_link=false,\n\t\t\t\t\t\t$show_opac_hidden_fields=true,\n\t\t\t\t\t\t$ajax_mode=0,\n\t\t\t\t\t\t$show_planning=0, \t\t\t\t// $show_planning = affichage des prvisions ou pas\n\t\t\t\t\t\t$show_map=1, // $show_map = affichage de la map\n\t\t\t\t\t\t$context_dsi_id_bannette=0, // $context_dsi_id_bannette = dans le contexte de la dsi\n\t\t\t\t\t\t$context_parameters = array()\t// Elements de contexte (ex : in_search, in_selector)\n\t\t\t\t\t\t) {\n\n\t \tglobal $pmb_recherche_ajax_mode;\n\t \tglobal $categ;\n\t \tglobal $id_empr;\n\t\t\n\t \tif (!is_array($anti_loop)) {\n\t \t\t$anti_loop = array();\n\t \t}\n\t \t$this->show_map=$show_map;\n\t\t$this->context_dsi_id_bannette=$context_dsi_id_bannette;\n\t\t$this->context_parameters = $context_parameters;\n\t\n\t \tif($pmb_recherche_ajax_mode){\n\t\t\t$this->ajax_mode=$ajax_mode;\n\t\t \tif($this->ajax_mode) {\n\t\t \t\t$param=array();\n\t\t\t\tif (is_object($id)){\n\t\t\t\t\t$param['id']=$id->notice_id;\n\t\t\t\t} else {\n\t\t\t\t\t$param['id']=$id;\n\t\t\t\t}\n\t\t\t\t$param['function_to_call']=\"mono_display\";\n\t\t\t \t//if($level)$param['level']=$level;\t// 6\n\t\t \t\tif($action)$param['action']=$action;\n\t\t \t\tif($expl)$param['expl']=$expl;\n\t\t \t\tif($expl_link)$param['expl_link']=$expl_link;\n\t//\t\t \tif($lien_suppr_cart)$param['lien_suppr_cart']=$lien_suppr_cart;\n\t\t\t \tif($explnum_link)$param['explnum_link']=$explnum_link;\n\t\t\t\t//if($show_resa)$param['show_resa']=$show_resa;\n\t\t\t \tif($print)$param['print']=$print;\n\t\t\t \t//if($show_explnum)$param['show_explnum']=$show_explnum;\n\t\t\t \t//if($show_statut)$param['show_statut']=$show_statut;\n\t\t\t \t//if($anti_loop)$param['anti_loop']=$anti_loop;\n\t\t\t \t//if($draggable)$param['draggable']=$draggable;\n\t\t\t \tif($no_link)$param['no_link']=$no_link;\n\t\t\t \tif($categ)$param['categ']=$categ;\n\t\t\t \tif($id_empr)$param['id_empr']=$id_empr;\n\t\t\t \t//if($show_opac_hidden_fields)$param['show_opac_hidden_fields']=$show_opac_hidden_fields;\n\t\t\t \t$this->mono_display_cmd=serialize($param);\n\t\t \t}\n\t \t}\n\n\t \tif(!$id)\n\t \t\treturn;\n\t\telse {\n\t\t\tif (is_object($id)){\n\t\t\t\t$this->notice_id = $id->notice_id;\n\t\t\t\t$this->notice = $id;\n\t\t\t\t$this->langues\t= get_notice_langues($this->notice_id, 0) ;\t// langues de la publication\n\t\t\t\t$this->languesorg\t= get_notice_langues($this->notice_id, 1) ; // langues originales\n\t\t\t\t$this->isbn = $id->code ;\n\t\t\t\t//Rcupration titre de srie\n\t\t\t\tif($id->tparent_id) {\n\t\t\t\t\t$parent = new serie($id->tparent_id);\n\t\t\t\t\t$this->tit_serie = $parent->name;\n\t\t\t\t\t$this->tit_serie_lien_gestion = $parent->isbd_entry_lien_gestion;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$this->notice_id = $id;\n\t\t\t\t$this->fetch_data();\n\t\t\t}\n\t\t\t$this->notice_relations = notice_relations_collection::get_object_instance($this->notice_id);\n\t\t\tif(!$this->ajax_mode || !$level) {\n\t\t\t\t$this->childs = $this->notice_relations->get_childs();\n\t\t\t}\n\t \t}\n\t \tglobal $memo_p_perso_notice;\n\t\tif(!$this->ajax_mode || !$level) {\n\t\t\tif(!$memo_p_perso_notice) {\n\t\t\t\t$memo_p_perso_notice=new parametres_perso(\"notices\");\n\t\t\t}\n\t\t\t$this->p_perso=$memo_p_perso_notice;\n\t\t}\n\t\t$this->level = $level;\n\t\t$this->expl = $expl;\n\t\t$this->show_resa = $show_resa;\n\t\n\t\t$this->link_expl = $expl_link;\n\t\t$this->link_explnum = $explnum_link;\n\t\t$this->lien_suppr_cart = $lien_suppr_cart;\n\t\t// mise jour des liens\n\t\t$this->action = $action;\n\t\t$this->drag=$draggable;\n\t\n\t\t$this->print_mode=$print;\n\t\t$this->show_explnum=$show_explnum;\n\t\t$this->show_statut=$show_statut;\n\t\t$this->no_link=$no_link;\n\t\n\t\t$this->anti_loop=$anti_loop;\n\t\n\t\t//affichage ou pas des champs persos OPAC masqus\n\t\t$this->show_opac_hidden_fields=$show_opac_hidden_fields;\n\t\n\t\t$this->action = str_replace('!!id!!', $this->notice_id, $this->action);\n\t\n\t\t$this->responsabilites = get_notice_authors($this->notice_id) ;\n\t\n\t\t// mise jour des catgories\n\t\tif(!$this->ajax_mode || !$level) $this->categories = get_notice_categories($this->notice_id) ;\n\t\n\t\t$this->show_planning = $show_planning;\n\t\t$this->do_header();\n\t\tswitch($level) {\n\t\t\tcase 0:\n\t\t\t\t// l, c'est le niveau 0 : juste le header\n\t\t\t\t$this->result = $this->header;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tglobal $pmb_map_activate;\n\t\t\t\t$this->map=new stdClass();\n\t\t\t\t$this->map_info=new stdClass();\n\t\t\t\tif($pmb_map_activate){\n\t\t\t\t\t$ids=array();\n\t\t\t\t\t$ids[]=$this->notice_id;\n\t\t\t\t\t$this->map=new map_objects_controler(TYPE_RECORD,$ids);\n\t\t\t\t\t$this->map_info=new map_info($this->notice_id);\n\t\t\t\t}\n\t\t\t\t// niveau 1 et plus : header + isbd gnrer\n\t\t\t\t$this->init_javascript();\n\t\t\t\tif(!$this->ajax_mode) $this->do_isbd();\n\t\t\t\t$this->finalize();\n\t\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function imagecopyresampled($dst_image, $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h): void\n{\n error_clear_last();\n $result = \\imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);\n if ($result === false) {\n throw ImageException::createFromPhpError();\n }\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function get_links($category = -1, $before = '', $after = '
    ', $between = ' ', $show_images = true, $orderby = 'name',\n\t\t\t$show_description = true, $show_rating = false, $limit = -1, $show_updated = 1, $display = true) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\t$order = 'ASC';\n\tif ( str_starts_with($orderby, '_') ) {\n\t\t$order = 'DESC';\n\t\t$orderby = substr($orderby, 1);\n\t}\n\n\tif ( $category == -1 ) // get_bookmarks() uses '' to signify all categories.\n\t\t$category = '';\n\n\t$results = get_bookmarks(array('category' => $category, 'orderby' => $orderby, 'order' => $order, 'show_updated' => $show_updated, 'limit' => $limit));\n\n\tif ( !$results )\n\t\treturn;\n\n\t$output = '';\n\n\tforeach ( (array) $results as $row ) {\n\t\tif ( !isset($row->recently_updated) )\n\t\t\t$row->recently_updated = false;\n\t\t$output .= $before;\n\t\tif ( $show_updated && $row->recently_updated )\n\t\t\t$output .= get_option('links_recently_updated_prepend');\n\t\t$the_link = '#';\n\t\tif ( !empty($row->link_url) )\n\t\t\t$the_link = esc_url($row->link_url);\n\t\t$rel = $row->link_rel;\n\t\tif ( '' != $rel )\n\t\t\t$rel = ' rel=\"' . $rel . '\"';\n\n\t\t$desc = esc_attr(sanitize_bookmark_field('link_description', $row->link_description, $row->link_id, 'display'));\n\t\t$name = esc_attr(sanitize_bookmark_field('link_name', $row->link_name, $row->link_id, 'display'));\n\t\t$title = $desc;\n\n\t\tif ( $show_updated )\n\t\t\tif ( !str_starts_with($row->link_updated_f, '00') )\n\t\t\t\t$title .= ' ('.__('Last updated') . ' ' . gmdate(get_option('links_updated_date_format'), $row->link_updated_f + (get_option('gmt_offset') * HOUR_IN_SECONDS)) . ')';\n\n\t\tif ( '' != $title )\n\t\t\t$title = ' title=\"' . $title . '\"';\n\n\t\t$alt = ' alt=\"' . $name . '\"';\n\n\t\t$target = $row->link_target;\n\t\tif ( '' != $target )\n\t\t\t$target = ' target=\"' . $target . '\"';\n\n\t\t$output .= '';\n\n\t\tif ( $row->link_image != null && $show_images ) {\n\t\t\tif ( str_contains( $row->link_image, 'http' ) )\n\t\t\t\t$output .= \"link_image\\\" $alt $title />\";\n\t\t\telse // If it's a relative path.\n\t\t\t\t$output .= \"link_image\\\" $alt $title />\";\n\t\t} else {\n\t\t\t$output .= $name;\n\t\t}\n\n\t\t$output .= '';\n\n\t\tif ( $show_updated && $row->recently_updated )\n\t\t\t$output .= get_option('links_recently_updated_append');\n\n\t\tif ( $show_description && '' != $desc )\n\t\t\t$output .= $between . $desc;\n\n\t\tif ($show_rating) {\n\t\t\t$output .= $between . get_linkrating($row);\n\t\t}\n\n\t\t$output .= \"$after\\n\";\n\t} // End while.\n\n\tif ( !$display )\n\t\treturn $output;\n\techo $output;\n}", "smellKey": "S107", "smellId": null, "repo": "ShashikantSingh09_web", "language": "php"} {"function": "public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children)\n\t{\n\t\t$this->No = $No;\n\t\t$this->Name = $name;\n\t\t$this->Type = $type;\n\t\t$this->PrevPps = $prev;\n\t\t$this->NextPps = $next;\n\t\t$this->DirPps = $dir;\n\t\t$this->Time1st = $time_1st;\n\t\t$this->Time2nd = $time_2nd;\n\t\t$this->_data = $data;\n\t\t$this->children = $children;\n\t\tif ($data != '') {\n\t\t\t$this->Size = strlen($data);\n\t\t} else {\n\t\t\t$this->Size = 0;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function configure(\n &$data_series,\n &$x_axis,\n &$y_axis,\n &$legend,\n &$show_filters,\n &$global_filters,\n $font_size,\n $limit = null,\n // default 10 from Metric Explorer\n $offset = null,\n $summarizeDataseries = false\n ) { // JMS: clearly we do not have enough parameters.\n // support min/max/average 'truncation' of dataset\n\n $this->limit = $limit;\n $this->show_filters = $show_filters;\n $this->setMultiCategory($data_series);\n\n // Instantiate the ComplexDataset to plot\n $this->_dataset = new \\DataWarehouse\\Data\\ComplexDataset();\n\n list(\n $dimensions,\n $metrics,\n //$yAxisArray,\n $globalFilterDescriptions,\n $dataSources\n ) = $this->_dataset->init(\n $this->_startDate,\n $this->_endDate,\n $this->_aggregationUnit,\n $data_series,\n $global_filters,\n $this->_queryType,\n $this->user\n );\n\n $this->_chart['metrics'] = $metrics;\n $this->_chart['dimensions'] = $dimensions;\n $this->setDataSource(array_keys($dataSources));\n\n if($this->show_filters)\n {\n $subtitle_separator = \" -- \";\n $subtitle = implode($subtitle_separator, array_unique($globalFilterDescriptions));\n $this->setSubtitle($subtitle, $font_size);\n }\n\n // ----------- set up xAxis and yAxis, assign to chart -----------\n\n $yAxisArray = $this->setAxes($summarizeDataseries, $offset, $x_axis, $font_size);\n $yAxisCount = count($yAxisArray);\n $legendRank = 1;\n\n // ------------ prepare to plot ------------\n\n // --- If ME, Does any dataset specify a pie chart? If so, set to truncate/summarize -- //\n // This corrects the 'pie charts are wrong' bug...\n if ( !$summarizeDataseries )\n {\n foreach($yAxisArray as $yAxisIndex => $yAxisObject)\n {\n foreach ($yAxisObject->series as $data_object)\n {\n if ( $data_object['data_description']->display_type=='pie' )\n {\n // set to summarize, then break both loops.\n $summarizeDataseries = true;\n break 2;\n }\n }\n }\n\n // if we have just reset summarizeDatasets, recompute limit, xAxis, and yAxis\n // with the new limit in place. Reset dataset _total to 1 to disable paging.\n if ($summarizeDataseries)\n {\n $yAxisArray = $this->setAxes($summarizeDataseries, $offset, $x_axis, $font_size);\n $yAxisCount = count($yAxisArray);\n\n // disable ME paging by setting dataset size to 1\n $this->_total = 1;\n }\n } // !$summarizeDatasets\n\n // OK, now let's plot something...\n // Each of the yAxisObjects returned from getYAxis()\n foreach($yAxisArray as $yAxisIndex => $yAxisObject)\n {\n if(count($yAxisObject->series) < 1)\n {\n continue;\n }\n\n $first_data_description = $yAxisObject->series[0]['data_description'];\n\n list($yAxisColor, $yAxisLineColor) = $this->getColorFromDataDescription($first_data_description);\n\n // set axis labels\n $defaultYAxisLabel = 'yAxis'.$yAxisIndex;\n $yAxisLabel = $yAxisObject->title;\n if($this->_shareYAxis)\n {\n $yAxisLabel = $defaultYAxisLabel;\n }\n $originalYAxisLabel = $yAxisLabel;\n\n $yAxisMin = $first_data_description->log_scale?null:0;\n $yAxisMax = null;\n $yAxisType = 'linear';\n $yIndex = $yAxisIndex + 1;\n $swapXYDone = false;\n $yAxisName = $yAxisIndex == 0 ? 'yaxis' : \"yaxis{$yIndex}\";\n $xAxisName = substr_replace($yAxisName, 'xaxis', 0, 5);\n $config = $this->getAxisOverrides($y_axis, $yAxisLabel, $yAxisIndex);\n if($config !== null)\n {\n if(isset($config->title))\n {\n $yAxisLabel = $config->title;\n }\n if(isset($config->min))\n {\n $yAxisMin = $first_data_description->log_scale && $config->min <= 0?null:$config->min;\n }\n if(isset($config->max))\n {\n $yAxisMax = $config->max;\n }\n if(isset($config->chartType))\n {\n $yAxisType = $config->chartType;\n }\n }\n if($yAxisLabel == $defaultYAxisLabel)\n {\n $yAxisLabel = '';\n }\n\n // populate the yAxis:\n $yAxis = array(\n 'automargin' => true,\n 'autorangeoptions' => array(\n 'minallowed' => $yAxisMin,\n 'maxallowed' => $yAxisMax\n ),\n 'cliponaxis' => false,\n 'layer' => 'below traces',\n 'title' => array(\n 'text' => '' . $yAxisLabel . '',\n 'standoff' => 5,\n 'font' => array(\n 'size' => ($font_size + 12),\n 'color' => $yAxisColor,\n 'family' => 'Lucida Grande, Lucida Sans Unicode, Arial, Helvetica, sans-serif',\n )\n ),\n 'otitle' => $originalYAxisLabel,\n 'dtitle' => $defaultYAxisLabel,\n 'exponentformat' => 'SI',\n 'tickfont' => array(\n 'size' => ($font_size + 11),\n 'color' => '#606060',\n ),\n 'ticksuffix' => ' ',\n 'tickmode' => 'auto',\n 'nticks' => 10,\n 'index' => $yAxisIndex,\n 'type' => ($yAxisObject->log_scale || $yAxisType == 'log') ? 'log' : 'linear',\n 'rangemode' => 'tozero',\n 'range' => [$yAxisMin, $yAxisMax],\n 'gridwidth' => $yAxisCount > 1 ? 0 : 1 + ($font_size / 8),\n 'gridcolor' => '#c0c0c0',\n 'linewidth' => 2 + $font_size / 4,\n 'linecolor' => '#c0d0e0',\n 'separatethousands' => true,\n 'side' => 'left',\n 'anchor' => 'x',\n 'overlaying' => $yAxisIndex == 0 ? null : 'y',\n );\n\n if ($yAxisIndex > 0) {\n $side = 'left';\n $anchor = 'free';\n if ($yAxisIndex % 2 == 1) {\n $side = 'right';\n }\n if ($yAxisIndex == 1) {\n $anchor = 'x';\n }\n $yAxis = array_merge($yAxis, array(\n 'side' => $side,\n 'anchor' => $anchor,\n 'autoshift' => true,\n ));\n }\n\n $this->_chart['layout'][\"{$yAxisName}\"] = $yAxis;\n\n // for each of the dataseries on this yAxisObject:\n foreach($yAxisObject->series as $data_description_index => $yAxisDataObjectAndDescription)\n {\n $legendRank += 2;\n $yAxisDataObject = $yAxisDataObjectAndDescription['yAxisDataObject']; // SimpleData object\n $data_description = $yAxisDataObjectAndDescription['data_description'];\n $decimals = $yAxisDataObjectAndDescription['decimals'];\n $semDecimals = $yAxisDataObjectAndDescription['semDecimals'];\n $filterParametersTitle = $yAxisDataObjectAndDescription['filterParametersTitle'];\n\n // ============= truncate (e.g. take average, min, max, sum of remaining values) ==========\n\n // Usage tab charts and ME pie charts will have their datasets summarized as follows:\n $dataSeriesSummarized = false;\n if ( $summarizeDataseries )\n {\n $valuesCount = $yAxisDataObject->getCount(true);\n\n if($valuesCount - $this->limit >= 1)\n {\n // only compute average (2nd parameter) if not drawing pie chart\n $yAxisDataObject->truncate($this->limit, $data_description->display_type!=='pie');\n\n // now merge the x labels, if needed, from multiple datasets:\n $mergedlabels = $yAxisDataObject->getXValues();\n foreach( $mergedlabels as $idx => $label) {\n if ($label === null) {\n $tmp = $this->_xAxisDataObject->getValues();\n $mergedlabels[$idx] = $tmp[$idx];\n }\n }\n $this->_xAxisDataObject->setValues($mergedlabels);\n $this->_xAxisDataObject->getCount(true);\n $this->setXAxis($x_axis, $font_size);\n $dataSeriesSummarized = true;\n }\n } // summarizeDataseries\n\n // ================ set color ================\n\n // If the first data set in the series, pick up the yAxisColorValue.\n if($data_description_index == 0) {\n $color = $yAxisColor;\n $lineColor = $yAxisLineColor;\n } else {\n list($color, $lineColor) = $this->getColorFromDataDescription($data_description);\n }\n\n $std_err_labels_enabled = property_exists($data_description, 'std_err_labels') && $data_description->std_err_labels;\n $isThumbnail = $this->_width <= \\DataWarehouse\\Visualization::$thumbnail_width;\n $this->_chart['layout']['stdErr'] = $data_description->std_err;\n $trace = array();\n $drilldown = array();\n $xValues = array();\n $yValues = array();\n $drillable = array();\n $text = array();\n $colors = array();\n\n // to display as pie chart:\n if($data_description->display_type == 'pie')\n {\n foreach( $yAxisDataObject->getValues() as $index => $value)\n {\n // If the first value, give it the yAxisColor so we don't skip\n // that color in the dataset. Otherwise, pick the next color.\n $yValues[] = $value;\n $xValues[] = $yAxisDataObject->getXValue($index);\n $colors[] = ($index == 0) ? $yAxisColor\n : '#'.str_pad(dechex($this->_colorGenerator->getColor() ), 6, '0', STR_PAD_LEFT);\n $drillable[] = true;\n // N.B.: These are drilldown labels.\n // X axis labels will be the same, but are plotted\n // from the x axis object instance variable.\n // See setXAxis() and _xAxisDataObject.\n $drilldown[] = array(\n 'id' => $yAxisDataObject->getXId($index),\n 'label' => $yAxisDataObject->getXValue($index)\n );\n\n $trace = array(\n 'labels' => $xValues,\n 'values' => $yValues,\n );\n\n }\n // Dont add data labels for all pie slices. Plotly will render all labels otherwise,\n // which causes the margin on pie charts with many slices to break\n $labelLimit = 12;\n $labelsAllocated = 0;\n $pieSum = array_sum($yValues);\n for ($i = 0; $i < count($xValues); $i++) {\n if ($isThumbnail || (($labelsAllocated < $labelLimit) && (($yValues[$i] / $pieSum) * 100) >= 2.0)) {\n $text[] = '' . $xValues[$i] . '
    ' . number_format($yValues[$i], $decimals, '.', ',');\n $labelsAllocated++;\n }\n else {\n $text[] = '';\n }\n\n }\n\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'closest';\n }\n else\n {\n if($this->_swapXY)\n {\n $trace['textangle'] = 90;\n $this->_chart['layout']['xaxis']['tickangle'] = 0;\n }\n\n // set the label for each value:\n foreach( $yAxisDataObject->getValues() as $index => $value)\n {\n $yValues[] = $value;\n $xValues[] = $yAxisDataObject->getXValue($index);\n $drillable[] = true;\n // N.B.: The following are drilldown labels.\n // Labels on the x axis come from the x axis object\n // (Though they are the same labels...)\n $drilldown[] = array(\n 'id' => $yAxisDataObject->getXId($index),\n 'label' => $yAxisDataObject->getXValue($index)\n );\n }\n }\n\n $values_count = count($yValues);\n if ($dataSeriesSummarized && $values_count > 0) {\n $drillable[$values_count - 1] = false;\n }\n\n $zIndex = isset($data_description->z_index) ? $data_description->z_index : $data_description_index;\n\n $dataSeriesName = $yAxisDataObject->getName();\n if ($data_description->restrictedByRoles && $this->_showWarnings) {\n $dataSeriesName .= $this->roleRestrictionsStringBuilder->registerRoleRestrictions($data_description->roleRestrictionsParameters);\n }\n if($this->_multiCategory) {\n $dataSeriesName = (\n $data_description->category\n . ': '\n . $dataSeriesName\n );\n }\n\n $formattedDataSeriesName = str_replace('style=\"\"', 'style=\"color:'.$yAxisColor.'\"', $dataSeriesName);\n $formattedDataSeriesName = str_replace('y_axis_title', $yAxisLabel, $formattedDataSeriesName);\n $formattedDataSeriesName.= $filterParametersTitle;\n\n $lookupDataSeriesName = $formattedDataSeriesName;\n if(isset($legend->{$formattedDataSeriesName}))\n {\n $config = $legend->{$formattedDataSeriesName};\n if(isset($config->title))\n {\n $lookupDataSeriesName = $config->title;\n }\n }\n $visible = true;\n if(isset($data_description->visibility) && isset($data_description->visibility->{$formattedDataSeriesName}))\n {\n $visible = $data_description->visibility->{$formattedDataSeriesName};\n }\n\n if (in_array($data_description->display_type, array('h_bar', 'bar', 'pie')))\n {\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'closest';\n }\n\n // Set tooltip format\n if ($data_description->display_type == 'pie')\n {\n $tooltip = '%{label}' . '
    ' . $lookupDataSeriesName\n . \": %{value:,.{$decimals}f} (%{percent}) \";\n }\n else\n {\n $tooltip = '%{hovertext}
    ' . \" \u25cf \"\n . $lookupDataSeriesName . \": %{y:,.{$decimals}f} \";\n }\n\n if ($yAxisCount > 1 || $data_description->std_err == 1) {\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'x unified';\n $tooltip = $lookupDataSeriesName . \": %{y:,.{$decimals}f} \";\n $this->_chart['layout'][\"{$yAxisName}\"]['showgrid'] = false;\n }\n else {\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'closest';\n }\n\n $this->_chart['layout']['hoverlabel']['bordercolor'] = $yAxisColor;\n // Hide markers for 32 points or greater, except when there are multiple traces then hide markers starting at 21 points.\n // Need check for chart types that this applies to otherwise bar, scatter, and pie charts will be hidden.\n $hideMarker = in_array($data_description->display_type, array('line', 'spline', 'area', 'areaspline'))\n && ($values_count >= 32 || (count($yAxisObject->series) > 1 && $values_count >= 21));\n\n $trace = array_merge($trace, array(\n 'automargin'=> $data_description->display_type == 'pie' ? true : null,\n 'name' => $lookupDataSeriesName,\n 'customdata' => $lookupDataSeriesName,\n 'zIndex' => $zIndex,\n 'cliponaxis' => false,\n 'otitle' => $formattedDataSeriesName,\n 'datasetId' => $data_description->id,\n 'drilldown' => $drilldown,\n 'marker' => array(\n 'size' => ($font_size/4 + 5) * 2,\n 'color' => $color,\n 'colors' => $data_description->display_type == 'pie' ? $colors : null,\n 'line' => array(\n 'width' => 1,\n 'color' => $lineColor,\n ),\n 'symbol' => $this->_symbolStyles[$data_description_index % 5],\n 'opacity' => $hideMarker ? 0.0 : 1.0\n ),\n 'line' => array(\n 'color' => $data_description->display_type == 'pie' ?\n null : $color,\n 'dash' => $data_description->line_type,\n 'width' => $data_description->display_type !== 'scatter' ? $data_description->line_width + $font_size / 4 : 0,\n 'shape' => $data_description->display_type == 'spline' || $data_description->display_type == 'areaspline' ? 'spline' : 'linear',\n ),\n 'type' => $data_description->display_type == 'h_bar' || $data_description->display_type == 'column' ? 'bar' : $data_description->display_type,\n 'mode' => $data_description->display_type == 'scatter' ? 'markers' : 'lines+markers',\n 'hovertext' => $xValues,\n 'hoveron'=> $data_description->display_type == 'area' || $data_description->display_type == 'areaspline' ? 'points+fills' : 'points',\n 'hovertemplate' => $tooltip,\n 'showlegend' => true,\n 'text' => $data_description->display_type == 'pie' && $data_description->value_labels ? $text : array(),\n 'textposition' => 'outside',\n 'textfont' => array(\n 'color' => $data_description->display_type == 'pie' ? '#000000' : $color,\n 'size' => ($font_size + 8),\n 'family' => 'Lucida Grande, Lucida Sans Unicode, Arial, Helvetica, sans-serif'\n ),\n 'textangle' => $data_description->display_type == 'h_bar' ? 0 : 90,\n 'textinfo' => $data_description->display_type == 'pie' ? 'text' : null,\n 'x' => $this->_swapXY ? $yValues : $xValues,\n 'y' => $this->_swapXY ? $xValues : $yValues,\n 'drillable' => $drillable,\n 'yaxis' => \"y{$yIndex}\",\n 'offsetgroup' => $yIndex > 1 ? \"group{$yIndex}\" : \"group{$legendRank}\",\n 'legendgroup' => $data_description_index,\n 'legendrank' => $legendRank - 1,\n 'traceorder' => $legendRank,\n 'cursor' => 'pointer',\n 'visible' => $visible,\n 'sort' => false,\n 'direction' => 'clockwise',\n 'isRestrictedByRoles' => $data_description->restrictedByRoles,\n ));\n\n if ($data_description->display_type == 'areaspline') {\n $trace['type'] = 'area';\n }\n\n // Set stack and configure area plots further\n if($data_description->display_type!=='line')\n {\n if ($trace['type']=='area' && $data_description_index == 0) {\n $hidden_trace = array(\n 'name' => 'area fix',\n 'x' => $this->_swapXY ? array_fill(0, count($xValues), 0) : $xValues,\n 'y' => $this->_swapXY ? $xValues : array_fill(0, count($xValues), 0),\n 'showlegend' => false,\n 'zIndex' => 0,\n 'mode' => 'lines+markers',\n 'marker' => array(\n 'color' => '#ffffff',\n 'size' => 0.1\n ),\n 'line' => array(\n 'color' => '#ffffff'\n ),\n 'legendrank' => -1000,\n 'traceorder' => -1000,\n 'hoverinfo' => 'skip',\n 'yaxis' => \"y{$yIndex}\",\n 'type' => 'scatter',\n );\n\n if ($this->_swapXY) {\n $hidden_trace['xaxis'] = \"x{$yIndex}\";\n unset($hidden_trace['yaxis']);\n }\n\n $this->_chart['data'][] = $hidden_trace;\n }\n\n if ($trace['type'] == 'bar' || $trace['type'] == 'pie') {\n $trace['line']['width'] = 0;\n $trace['marker']['line']['width'] = 0;\n }\n\n if ($trace['type'] == 'bar' && $data_description->display_type != 'h_bar') {\n $trace['textposition'] = 'outside';\n $trace['textangle'] = -90;\n }\n\n if ($data_description->combine_type=='side' && $trace['type']=='area'){\n if ($this->_swapXY) {\n $trace['fill'] = 'tozerox';\n }\n else {\n $trace['fill'] = 'tozeroy';\n }\n }\n elseif($data_description->combine_type=='stack')\n {\n $trace['stackgroup'] = 'one';\n $this->_chart['layout']['barmode'] = 'stack';\n }\n elseif($data_description->combine_type=='percent' && !$data_description->log_scale)\n {\n $trace['stackgroup'] = 'one';\n $trace['groupnorm'] = 'percent';\n if ($trace['type'] == 'bar') {\n $this->_chart['layout']['barmode'] = 'stack';\n $this->_chart['layout']['barnorm'] = 'percent';\n }\n }\n }\n\n // Set swap axis\n if ($this->_swapXY && $data_description->display_type!='pie') {\n if ($trace['type'] == 'bar') {\n $trace = array_merge($trace, array('orientation' => 'h'));\n $trace['textangle'] = 0;\n }\n if ($this->_chart['layout']['hovermode'] != 'closest') {\n $this->_chart['layout']['hovermode'] = 'y unified';\n $trace['hovertemplate'] = $lookupDataSeriesName . \": %{x:,.{$decimals}f} \";\n }\n else {\n $trace['hovertemplate'] = '%{hovertext}
    ' . \" \u25cf \"\n . $lookupDataSeriesName . \": %{x:,.{$decimals}f} \";\n }\n unset($trace['yaxis']);\n $trace['xaxis'] = \"x{$yIndex}\";\n\n if (!$swapXYDone) {\n $xtmp = $this->_chart['layout']['xaxis'];\n $ytmp = $this->_chart['layout'][\"{$yAxisName}\"];\n $this->_chart['layout']['yaxis'] = $xtmp;\n $this->_chart['layout'][\"{$xAxisName}\"] = $ytmp;\n\n $this->_chart['layout'][\"{$xAxisName}\"]['side'] = ($yAxisIndex % 2 != 0) ? 'top' : 'bottom';\n if ($this->_chart['layout'][\"{$xAxisName}\"]['side'] == 'top') {\n $this->_chart['layout'][\"{$xAxisName}\"]['title']['standoff'] = 0;\n }\n $this->_chart['layout'][\"{$xAxisName}\"]['anchor'] = 'free';\n if (isset($this->_chart['layout'][\"{$xAxisName}\"]['overlaying'])) {\n $this->_chart['layout'][\"{$xAxisName}\"]['overlaying'] = 'x';\n }\n\n $xAxisStep = 0.115;\n $xAxisBottomBoundStart = 0 + ($xAxisStep * ceil($yAxisCount/2));\n $xAxisTopBoundStart = 1 - ($xAxisStep * floor($yAxisCount/2));\n $topShift = floor($yAxisCount/2) - floor($yAxisIndex/2);\n $bottomShift = ceil($yAxisCount/2) - ceil($yAxisIndex/2);\n\n $this->_chart['layout'][\"{$xAxisName}\"]['position'] = $this->_chart['layout'][\"{$xAxisName}\"]['side'] == 'top' ? min(1 - ($xAxisStep * $topShift), 1) :\n max(0 + ($xAxisStep * $bottomShift), 0);\n\n $this->_chart['layout'][\"{$xAxisName}\"]['domain'] = array(0,1);\n $this->_chart['layout'][\"{$xAxisName}\"]['title']['standoff'] = 0;\n $this->_chart['layout'][\"{$xAxisName}\"]['type'] = $yAxisObject->log_scale ? 'log' : '-';\n $this->_chart['layout'][\"{$xAxisName}\"]['showgrid'] =$yAxisCount > 1 ? false : true;\n\n $this->_chart['layout']['yaxis']['linewidth'] = 2 + $font_size / 4;\n $this->_chart['layout']['yaxis']['linecolor'] = '#c0d0e0';\n $this->_chart['layout']['yaxis']['domain'] = array($xAxisBottomBoundStart, $xAxisTopBoundStart);\n $this->_chart['layout']['yaxis']['autorange'] = 'reversed';\n $this->_chart['layout']['yaxis']['showgrid'] = false;\n unset($this->_chart['layout']['yaxis']['position']);\n $swapXYDone = true;\n\n }\n\n if ($yIndex > 1) {\n unset($this->_chart['layout'][\"{$yAxisName}\"]);\n }\n\n }\n\n // Set null connectors\n if (in_array(null, $yValues) && $data_description->display_type == 'line') {\n $null_trace = array(\n 'name' => 'gap connector',\n 'zIndex' => $zIndex,\n 'x' => $this->_swapXY ? $yValues : $xValues,\n 'y' => $this->_swapXY ? $xValues : $yValues,\n 'showlegend' => false,\n 'mode' => 'lines',\n 'line' => array(\n 'color' => $color,\n 'dash' => 'dash'\n ),\n 'connectgaps' => true,\n 'hoverinfo' => 'skip',\n 'legendgroup' => $data_description_index,\n 'legendrank' => -1000,\n 'traceorder' => -1000,\n 'type' => 'scatter',\n 'visible' => $visible,\n 'yaxis' => \"y{$yIndex}\",\n 'isRestrictedByRoles' => $data_description->restrictedByRoles,\n );\n\n if ($this->_swapXY) {\n $null_trace['xaxis'] = \"x{$yIndex}\";\n unset($null_trace['yaxis']);\n }\n\n $this->_chart['data'][] = $null_trace;\n\n }\n\n // Adjust axis tick labels based on label length\n if(!($data_description->display_type == 'pie')) {\n $categoryLabels = array();\n $longLabel = false;\n for ($i = 0; $i < count($xValues); $i++) {\n if (count($xValues) > 20) {\n if ($i % 2 == 0) {\n $categoryLabels[] = mb_substr($xValues[$i], 0, 25) . '...';\n }\n else {\n $categoryLabels[] = '';\n }\n }\n elseif (strlen($xValues[$i]) > 70 || $longLabel) {\n $categoryLabels[] = mb_substr($xValues[$i], 0, 25) . '...';\n if (count($xValues) > 10 && !$longLabel) {\n $longLabel = true;\n }\n }\n elseif ($data_description->display_type == 'h_bar') {\n $categoryLabels[] = wordwrap($xValues[$i], 40, '
    ');\n } else {\n $categoryLabels[] = wordwrap($xValues[$i], 25, '
    ');\n }\n }\n if ($this->_swapXY) {\n $this->_chart['layout']['yaxis']['tickmode'] = 'array';\n $this->_chart['layout']['yaxis']['tickvals'] = $xValues;\n $this->_chart['layout']['yaxis']['ticktext'] = $categoryLabels;\n } else {\n $this->_chart['layout']['xaxis']['tickmode'] = 'array';\n $this->_chart['layout']['xaxis']['tickvals'] = $xValues;\n $this->_chart['layout']['xaxis']['ticktext'] = $categoryLabels;\n }\n }\n\n $this->_chart['data'][] = $trace;\n\n $error_info = $this->buildErrorDataSeries(\n $trace,\n $data_description,\n $legend,\n $lineColor,\n $yAxisDataObject,\n $formattedDataSeriesName,\n $yAxisIndex,\n $semDecimals,\n $decimals,\n $zIndex\n );\n\n $this->configureDataLabels(\n $data_description,\n $error_info,\n $xValues,\n $yValues,\n $std_err_labels_enabled,\n $font_size,\n $color,\n $isThumbnail,\n $decimals\n );\n } // end closure for each $yAxisObject\n } // end closure for each $yAxisArray\n\n // Add restricted data warning\n if ($this->_showWarnings) {\n $this->addRestrictedDataWarning();\n }\n\n // set title and subtitle for chart\n $this->setChartTitleSubtitle($font_size);\n\n }", "smellKey": "S107", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function addAnswer(\n $questionnaireID, // ID for the questionnaire\n $questionID, // ID for the parent question\n $text, // Textual description of the answer\n $actionSource, // Append to candidate source\n $actionNotes, // Appent to candidate notes\n $actionIsHot, // Set candidate is_hot\n $actionIsActive, // Set candidate is_active\n $actionCanRelocate, // Set candidate can_relocate\n $actionKeySkills, // Append to candidate skills\n $position // Position in the question (1,2,3,4, etc.)\n )\n {\n $sql = sprintf(\n \"INSERT INTO\n career_portal_questionnaire_answer (\n career_portal_questionnaire_id,\n career_portal_questionnaire_question_id,\n text,\n action_source,\n action_notes,\n action_is_hot,\n action_is_active,\n action_can_relocate,\n action_key_skills,\n position,\n site_id\n )\n VALUES (\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n )\",\n $this->_db->makeQueryInteger($questionnaireID),\n $this->_db->makeQueryInteger($questionID),\n $this->_db->makeQueryString($text),\n $this->_db->makeQueryString($actionSource),\n $this->_db->makeQueryString($actionNotes),\n $this->_db->makeQueryInteger($actionIsHot),\n $this->_db->makeQueryInteger($actionIsActive),\n $this->_db->makeQueryInteger($actionCanRelocate),\n $this->_db->makeQueryString($actionKeySkills),\n $this->_db->makeQueryInteger($position),\n $this->_siteID\n );\n\n if ($this->_db->query($sql))\n {\n return $this->_db->getLastInsertID();\n }\n else\n {\n return false;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function __construct(\n ?string $inAnoLetivo,\n ?string $inNumClasse,\n ?string $inCodTipoClasse,\n ?string $inCodTurno,\n ?string $inTurma,\n ?string $inNrCapacidadeFisicaMaxima,\n ?string $inDataInicioAula,\n ?string $inDataFimAula,\n ?string $inHorarioInicioAula,\n ?string $inHorarioFimAula,\n ?string $inCodDuracao,\n ?string $inCodHabilitacao,\n ?array $inCodigoAtividadeComplementar,\n ?string $inNumeroSala,\n ?InDiasDaSemana $inDiasDaSemana\n ) {\n $this->inAnoLetivo = $inAnoLetivo;\n $this->inNumClasse = $inNumClasse;\n $this->inCodTipoClasse = $inCodTipoClasse;\n $this->inCodTurno = $inCodTurno;\n $this->inTurma = $inTurma;\n $this->inNrCapacidadeFisicaMaxima = $inNrCapacidadeFisicaMaxima;\n $this->inDataInicioAula = $inDataInicioAula;\n $this->inDataFimAula = $inDataFimAula;\n $this->inHorarioInicioAula = $inHorarioInicioAula;\n $this->inHorarioFimAula = $inHorarioFimAula;\n $this->inCodDuracao = $inCodDuracao;\n $this->inCodHabilitacao = $inCodHabilitacao;\n $this->inCodigoAtividadeComplementar = $inCodigoAtividadeComplementar;\n $this->inNumeroSala = $inNumeroSala;\n $this->inDiasDaSemana = $inDiasDaSemana;\n }", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function gen_tpl_abt_modele($id,$titre,$num,$vol,$tome,$delais,$delais_critique,$change_statut_id){\n\t\tglobal $msg;\n\t\t\n\t\t$requete=\"select * from abts_modeles where modele_id='$id'\";\n\t\t$resultat=pmb_mysql_query($requete);\n\t\tif ($r_a=pmb_mysql_fetch_object($resultat)) {\n\t\t\t$tom_actif=$r_a->tom_actif;\t\n\t\t\t$vol_actif=$r_a->vol_actif;\t\n\t\t\t$num_depart=$r_a->num_depart;\n\t\t\t$vol_depart=$r_a->vol_depart;\n\t\t\t$tom_depart=$r_a->tom_depart;\t\n\t\t}\t\n\t\tif(!$num)\t$num=$num_depart;\n\t\tif(!$vol)\t$vol=$vol_depart;\n\t\tif(!$tome)\t$tome=$tom_depart;\t\t\t\n\t\t$contenu= \"\n\t\t
    \n\t\t\t\n\t\t
    \t\n\t\t
    \n\t\t\t\t\t\n\t\t
    \n\t\t\";\n\t\tif($vol_actif)$contenu.= \"\t\t\n\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \t\n\t\t\t
    \n\t\t\t\t\t\n\t\t\t
    \n\t\t
    \n\t\t\";\n\t\tif($tom_actif)$contenu.= \"\n\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t
    \n\t\t\";\t\t\n\t\t$contenu.= \"\n\t\t
    \n\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \t\n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t
    \n\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t
    \n\t\t
    \n\t\t\";\n\t\t\n\t\t// select !!change_statut!!\t\n\t\t$statut_form=str_replace('!!statut_check!!',\n\t\t\t\t\"\",\n\t\t\t$msg['catalog_change_statut_form']);\n\n\t\t$statut_form=str_replace('!!statut_list!!',\n\t\t\tdo_selector('docs_statut', \"change_statut[\".$id.\"]\", $change_statut_id),\n\t\t\t$statut_form);\n\t\t\t\t\n\t\t$contenu.= \"\n\t\t
     
    \n\t\t
    \n\t\t\t$statut_form\n\t\t
    \n\t\t\";\t\t\t\t\t\t\n\n\t\treturn gen_plus_form($id,$titre,$contenu);\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function updateForAdministration($userID, $firstName, $lastName, $email,\n $title, $phone_work, $phone_cell, $phone_other, $notes, $aspSiteRule)\n {\n $sql = sprintf(\n \"UPDATE\n user\n SET\n last_name = %s,\n first_name = %s,\n email = %s,\n title = %s,\n phone_work = %s,\n phone_cell = %s,\n phone_other = %s,\n notes = %s\n WHERE\n user_id = %s\n AND\n %s\",\n $this->_db->makeQueryString($lastName),\n $this->_db->makeQueryString($firstName),\n $this->_db->makeQueryString($email),\n $this->_db->makeQueryString($title),\n $this->_db->makeQueryString($phone_work),\n $this->_db->makeQueryString($phone_cell),\n $this->_db->makeQueryString($phone_other),\n $this->_db->makeQueryString($notes),\n $this->_db->makeQueryInteger($userID),\n $this->_siteID,\n $aspSiteRule\n );\n\n return (boolean) $this->_db->query($sql);\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "static public function add($title, $body, $type, $category, $player_id, $comments, $article_text, $article_image, &$errors)\n\t{\n\t\tglobal $db;\n\t\tif(!self::verify($title, $body, $article_text, $article_image, $errors))\n\t\t\treturn false;\n\n\t\t$db->insert(TABLE_PREFIX . 'news', array('title' => $title, 'body' => $body, 'type' => $type, 'date' => time(), 'category' => $category, 'player_id' => isset($player_id) ? $player_id : 0, 'comments' => $comments, 'article_text' => ($type == 3 ? $article_text : ''), 'article_image' => ($type == 3 ? $article_image : '')));\n\t\tself::clearCache();\n\t\treturn true;\n\t}", "smellKey": "S107", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function newPatientData(\n $db_id = \"\",\n $title = \"\",\n $fname = \"\",\n $lname = \"\",\n $mname = \"\",\n $sex = \"\",\n $DOB = \"\",\n $street = \"\",\n $postal_code = \"\",\n $city = \"\",\n $state = \"\",\n $country_code = \"\",\n $ss = \"\",\n $occupation = \"\",\n $phone_home = \"\",\n $phone_biz = \"\",\n $phone_contact = \"\",\n $status = \"\",\n $contact_relationship = \"\",\n $referrer = \"\",\n $referrerID = \"\",\n $email = \"\",\n $language = \"\",\n $ethnoracial = \"\",\n $interpretter = \"\",\n $migrantseasonal = \"\",\n $family_size = \"\",\n $monthly_income = \"\",\n $homeless = \"\",\n $financial_review = \"\",\n $pubpid = \"\",\n $pid = \"MAX(pid)+1\",\n $providerID = \"\",\n $genericname1 = \"\",\n $genericval1 = \"\",\n $genericname2 = \"\",\n $genericval2 = \"\",\n $billing_note = \"\",\n $phone_cell = \"\",\n $hipaa_mail = \"\",\n $hipaa_voice = \"\",\n $squad = 0,\n $pharmacy_id = 0,\n $drivers_license = \"\",\n $hipaa_notice = \"\",\n $hipaa_message = \"\",\n $regdate = \"\"\n) {\n\n $fitness = 0;\n $referral_source = '';\n if ($pid) {\n $rez = sqlQuery(\"select id, fitness, referral_source from patient_data where pid = ?\", array($pid));\n // Check for brain damage:\n if ($db_id != $rez['id']) {\n $errmsg = \"Internal error: Attempt to change patient_data.id from '\" .\n text($rez['id']) . \"' to '\" . text($db_id) . \"' for pid '\" . text($pid) . \"'\";\n die($errmsg);\n }\n\n $fitness = $rez['fitness'];\n $referral_source = $rez['referral_source'];\n }\n\n // Get the default price level.\n $lrow = sqlQuery(\"SELECT option_id FROM list_options WHERE \" .\n \"list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1\");\n $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];\n\n $query = (\"replace into patient_data set\n id='\" . add_escape_custom($db_id) . \"',\n title='\" . add_escape_custom($title) . \"',\n fname='\" . add_escape_custom($fname) . \"',\n lname='\" . add_escape_custom($lname) . \"',\n mname='\" . add_escape_custom($mname) . \"',\n sex='\" . add_escape_custom($sex) . \"',\n DOB='\" . add_escape_custom($DOB) . \"',\n street='\" . add_escape_custom($street) . \"',\n postal_code='\" . add_escape_custom($postal_code) . \"',\n city='\" . add_escape_custom($city) . \"',\n state='\" . add_escape_custom($state) . \"',\n country_code='\" . add_escape_custom($country_code) . \"',\n drivers_license='\" . add_escape_custom($drivers_license) . \"',\n ss='\" . add_escape_custom($ss) . \"',\n occupation='\" . add_escape_custom($occupation) . \"',\n phone_home='\" . add_escape_custom($phone_home) . \"',\n phone_biz='\" . add_escape_custom($phone_biz) . \"',\n phone_contact='\" . add_escape_custom($phone_contact) . \"',\n status='\" . add_escape_custom($status) . \"',\n contact_relationship='\" . add_escape_custom($contact_relationship) . \"',\n referrer='\" . add_escape_custom($referrer) . \"',\n referrerID='\" . add_escape_custom($referrerID) . \"',\n email='\" . add_escape_custom($email) . \"',\n language='\" . add_escape_custom($language) . \"',\n ethnoracial='\" . add_escape_custom($ethnoracial) . \"',\n interpretter='\" . add_escape_custom($interpretter) . \"',\n migrantseasonal='\" . add_escape_custom($migrantseasonal) . \"',\n family_size='\" . add_escape_custom($family_size) . \"',\n monthly_income='\" . add_escape_custom($monthly_income) . \"',\n homeless='\" . add_escape_custom($homeless) . \"',\n financial_review='\" . add_escape_custom($financial_review) . \"',\n pubpid='\" . add_escape_custom($pubpid) . \"',\n pid= '\" . add_escape_custom($pid) . \"',\n providerID = '\" . add_escape_custom($providerID) . \"',\n genericname1 = '\" . add_escape_custom($genericname1) . \"',\n genericval1 = '\" . add_escape_custom($genericval1) . \"',\n genericname2 = '\" . add_escape_custom($genericname2) . \"',\n genericval2 = '\" . add_escape_custom($genericval2) . \"',\n billing_note= '\" . add_escape_custom($billing_note) . \"',\n phone_cell = '\" . add_escape_custom($phone_cell) . \"',\n pharmacy_id = '\" . add_escape_custom($pharmacy_id) . \"',\n hipaa_mail = '\" . add_escape_custom($hipaa_mail) . \"',\n hipaa_voice = '\" . add_escape_custom($hipaa_voice) . \"',\n hipaa_notice = '\" . add_escape_custom($hipaa_notice) . \"',\n hipaa_message = '\" . add_escape_custom($hipaa_message) . \"',\n squad = '\" . add_escape_custom($squad) . \"',\n fitness='\" . add_escape_custom($fitness) . \"',\n referral_source='\" . add_escape_custom($referral_source) . \"',\n regdate='\" . add_escape_custom($regdate) . \"',\n pricelevel='\" . add_escape_custom($pricelevel) . \"',\n date=NOW()\");\n\n $id = sqlInsert($query);\n\n if (!$db_id) {\n // find the last inserted id for new patient case\n $db_id = $id;\n }\n\n $foo = sqlQuery(\"select `pid`, `uuid` from `patient_data` where `id` = ? order by `date` limit 0,1\", array($id));\n\n // set uuid if not set yet (if this was an insert and not an update)\n if (empty($foo['uuid'])) {\n $uuid = (new UuidRegistry(['table_name' => 'patient_data']))->createUuid();\n sqlStatementNoLog(\"UPDATE `patient_data` SET `uuid` = ? WHERE `id` = ?\", [$uuid, $id]);\n }\n\n return $foo['pid'];\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct(\n TranslatableNotificationHandlerInterface $notificationHandler,\n TranslatorInterface $translator,\n SectionService $sectionService,\n SearchService $searchService,\n FormFactory $formFactory,\n SectionCreateMapper $sectionCreateMapper,\n SectionUpdateMapper $sectionUpdateMapper,\n SubmitHandler $submitHandler,\n LocationService $locationService,\n PathService $pathService,\n PermissionResolver $permissionResolver,\n PermissionCheckerInterface $permissionChecker,\n ConfigResolverInterface $configResolver\n ) {\n $this->notificationHandler = $notificationHandler;\n $this->translator = $translator;\n $this->sectionService = $sectionService;\n $this->searchService = $searchService;\n $this->formFactory = $formFactory;\n $this->sectionCreateMapper = $sectionCreateMapper;\n $this->sectionUpdateMapper = $sectionUpdateMapper;\n $this->submitHandler = $submitHandler;\n $this->locationService = $locationService;\n $this->pathService = $pathService;\n $this->permissionResolver = $permissionResolver;\n $this->permissionChecker = $permissionChecker;\n $this->configResolver = $configResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function frontPayment($patient_id, $encounter, $method, $source, $amount1, $amount2, $timestamp, $auth = \"\")\n{\n\n if (empty($auth)) {\n $auth = $_SESSION['authUser'];\n }\n\n $tmprow = sqlQuery(\n \"SELECT date FROM form_encounter WHERE \" .\n \"encounter=? and pid=?\",\n array($encounter,$patient_id)\n );\n //the manipulation is done to insert the amount paid into payments table in correct order to show in front receipts report,\n //if the payment is for today's encounter it will be shown in the report under today field and otherwise shown as previous\n $tmprowArray = explode(' ', $tmprow['date']);\n if (date('Y-m-d') == $tmprowArray[0]) {\n if ($amount1 == 0) {\n $amount1 = $amount2;\n $amount2 = 0;\n }\n } else {\n if ($amount2 == 0) {\n $amount2 = $amount1;\n $amount1 = 0;\n }\n }\n\n $payid = sqlInsert(\"INSERT INTO payments ( \" .\n \"pid, encounter, dtime, user, method, source, amount1, amount2 \" .\n \") VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)\", array($patient_id,$encounter,$timestamp,$auth,$method,$source,$amount1,$amount2));\n return $payid;\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function add_acl($aco_array, $aro_array, $aro_group_ids=NULL, $axo_array=NULL, $axo_group_ids=NULL, $allow=1, $enabled=1, $return_value=NULL, $note=NULL, $section_value=NULL, $acl_id=FALSE ) {\n\n\t\t$this->debug_text(\"add_acl():\");\n\n\t\tif (empty($aco_array) || count($aco_array) == 0) {\n\t\t\t$this->debug_text(\"Must select at least one Access Control Object\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif ((empty($aro_array) || count($aro_array) == 0) AND (empty($aro_group_ids) || count($aro_group_ids) == 0)) {\n\t\t\t$this->debug_text(\"Must select at least one Access Request Object or Group\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (empty($allow)) {\n\t\t\t$allow=0;\n\t\t}\n\n\t\tif (empty($enabled)) {\n\t\t\t$enabled=0;\n\t\t}\n\n\t\tif (!empty($section_value)\n\t\t\tAND !$this->get_object_section_section_id(NULL, $section_value, 'ACL')) {\n\t\t\t$this->debug_text(\"add_acl(): Section Value: $section_value DOES NOT exist in the database.\");\n\t\t\treturn false;\n\t\t}\n\n\t\t//Unique the group arrays. Later one we unique ACO/ARO/AXO arrays.\n\t\tif (is_array($aro_group_ids)) {\n\t\t\t$aro_group_ids = array_unique($aro_group_ids);\n\t\t}\n\t\tif (is_array($axo_group_ids)) {\n\t\t\t$axo_group_ids = array_unique($axo_group_ids);\n\t\t}\n\n\t\t//Check for conflicting ACLs.\n\t\tif ($this->is_conflicting_acl($aco_array,$aro_array,$aro_group_ids,$axo_array,$axo_group_ids,array($acl_id))) {\n\t\t\t$this->debug_text(\"add_acl(): Detected possible ACL conflict, not adding ACL!\");\n\t\t\treturn false;\n\t\t}\n\n\t\t//Edit ACL if acl_id is set. This is simply if we're being called by edit_acl().\n\t\tif ($this->get_acl($acl_id) == FALSE) {\n\t\t\tif ( empty($section_value) ) {\n\t\t\t\t$section_value='system';\n\t\t\t\tif( !$this->get_object_section_section_id(NULL, $section_value, 'ACL') ) {\n\t\t\t\t\t// Use the acl section with the lowest order value.\n\t\t\t\t\t$acl_sections_table = $this->_db_table_prefix .'acl_sections';\n\t\t\t\t\t$acl_section_order_value = $this->db->GetOne(\"SELECT min(order_value) from $acl_sections_table\");\n\n\t\t\t\t\t$query = \"\n\t\t\t\t\t\tSELECT value\n\t\t\t\t\t\tFROM $acl_sections_table\n\t\t\t\t\t\tWHERE order_value = \" . $this->db->quote($acl_section_order_value);\n\t\t\t\t\t$section_value = $this->db->GetOne($query);\n\n\t\t\t\t\tif ( empty($section_value) ) {\n\t\t\t\t\t\t$this->debug_text(\"add_acl(): No valid acl section found.\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->debug_text(\"add_acl(): Using default section value: $section_value.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//ACL not specified, so create acl_id\n\t\t\tif (empty($acl_id)) {\n\t\t\t\t//Create ACL row first, so we have the acl_id\n\t\t\t\t$acl_id = $this->db->GenID($this->_db_table_prefix.'acl_seq',10);\n\n\t\t\t\t//Double check the ACL ID was generated.\n\t\t\t\tif (empty($acl_id)) {\n\t\t\t\t\t$this->debug_text(\"add_acl(): ACL_ID generation failed!\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//Begin transaction _after_ GenID. Because on the first run, if GenID has to create the sequence,\n\t\t\t//the transaction will fail.\n\t\t\t$this->db->BeginTrans();\n\n\t\t\t$query = 'INSERT INTO '.$this->_db_table_prefix.'acl (id,section_value,allow,enabled,return_value,note,updated_date) VALUES('. $this->db->quote($acl_id) .','. $this->db->quote($section_value) .','. $this->db->quote($allow) .','. $this->db->quote($enabled) .','. $this->db->quote($return_value) .', '. $this->db->quote($note) .','. time() .')';\n\t\t\t$result = $this->db->Execute($query);\n\t\t} else {\n\t\t\t$section_sql = '';\n\t\t\tif ( !empty($section_value) ) {\n\t\t\t\t$section_sql = 'section_value='. $this->db->quote ($section_value) .',';\n\t\t\t}\n\n\t\t\t$this->db->BeginTrans();\n\n\t\t\t//Update ACL row, and remove all mappings so they can be re-inserted.\n\t\t\t$query = '\n\t\t\t\tUPDATE\t'. $this->_db_table_prefix .'acl\n\t\t\t\tSET ' . $section_sql . '\n\t\t\t\t\t\tallow='. $this->db->quote($allow) .',\n\t\t\t\t\t\tenabled='. $this->db->quote($enabled) .',\n\t\t\t\t\t\treturn_value='. $this->db->quote($return_value) .',\n\t\t\t\t\t\tnote='. $this->db->quote($note) .',\n\t\t\t\t\t\tupdated_date='. time() .'\n\t\t\t\tWHERE\tid='. $this->db->quote($acl_id);\n\t\t\t$result = $this->db->Execute($query);\n\n\t\t\tif ($result) {\n\t\t\t\t$this->debug_text(\"Update completed without error, delete mappings...\");\n\t\t\t\t//Delete all mappings so they can be re-inserted.\n\t\t\t\tforeach (array('aco_map', 'aro_map', 'axo_map', 'aro_groups_map', 'axo_groups_map') as $map) {\n\t\t\t\t\t$query = 'DELETE FROM '. $this->_db_table_prefix . $map .' WHERE acl_id='. $this->db->quote($acl_id);\n\t\t\t\t\t$rs = $this->db->Execute($query);\n\n\t\t\t\t\tif (!is_object($rs))\n\t\t\t\t\t{\n\t\t\t\t\t\t$this->debug_db('add_acl');\n\t\t\t\t\t\t$this->db->RollBackTrans();\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!is_object($result)) {\n\t\t\t$this->debug_db('add_acl');\n\t\t\t$this->db->RollBackTrans();\n\t\t\treturn false;\n\t\t}\n\n\t\t$this->debug_text(\"Insert or Update completed without error, insert new mappings.\");\n\t\t// Insert ACO/ARO/AXO mappings\n\t\tforeach (array('aco', 'aro', 'axo') as $map) {\n\t\t\t$map_array = ${$map .'_array'};\n\n\t\t\tif (!is_array ($map_array)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tforeach ($map_array as $section_value => $value_array) {\n\t\t\t\t$this->debug_text ('Insert: '. strtoupper($map) . ' Section Value: $section_value' . strtoupper($map) . ' VALUE: $value_array');\n\t\t\t\t// $this->showarray ($aco_value_array);\n\n\t\t\t\tif (!is_array($value_array)) {\n\t\t\t\t\t$this->debug_text ('add_acl (): Invalid Format for '. strtoupper ($map) .' Array item. Skipping...');\n\t\t\t\t\tcontinue;\n\t\t\t\t\t// return true;\n\t\t\t\t}\n\n\t\t\t\t$value_array = array_unique($value_array);\n\n\t\t\t\tforeach ($value_array as $value) {\n\t\t\t\t\t$get_object_id = $this->get_object_id($section_value, $value, $map);\n\t\t\t\t\t$object_id = &$get_object_id;\n\n\t\t\t\t\tif (empty($object_id))\n\t\t\t\t\t{\n\t\t\t\t\t\t$this->debug_text('add_acl(): '. strtoupper($map) . \" Object Section Value: $section_value Value: $value DOES NOT exist in the database. Skipping...\");\n\t\t\t\t\t\t$this->db->RollBackTrans();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\t$query = 'INSERT INTO '. $this->_db_table_prefix . $map .'_map (acl_id,section_value,value) VALUES ('. $this->db->quote($acl_id) .', '. $this->db->quote($section_value) .', '. $this->db->quote($value) .')';\n\t\t\t\t\t$rs = $this->db->Execute($query);\n\n\t\t\t\t\tif (!is_object($rs))\n\t\t\t\t\t{\n\t\t\t\t\t\t$this->debug_db('add_acl');\n\t\t\t\t\t\t$this->db->RollBackTrans();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Insert ARO/AXO GROUP mappings\n\t\tforeach (array('aro', 'axo') as $map) {\n\t\t\t$map_group_ids = ${$map .'_group_ids'};\n\n\t\t\tif (!is_array($map_group_ids)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tforeach ($map_group_ids as $group_id) {\n\t\t\t\t$this->debug_text ('Insert: '. strtoupper($map) .' GROUP ID: '. $group_id);\n $get_group_data = $this->get_group_data($group_id, $map);\n $group_data = &$get_group_data;\n\n\t\t\t\tif (empty($group_data)) {\n\t\t\t\t\t$this->debug_text('add_acl(): '. strtoupper($map) . \" Group: $group_id DOES NOT exist in the database. Skipping...\");\n\t\t\t\t\t$this->db->RollBackTrans();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t$query = 'INSERT INTO '. $this->_db_table_prefix . $map .'_groups_map (acl_id,group_id) VALUES ('. $this->db->quote($acl_id) .', '. $this->db->quote($group_id) .')';\n\t\t\t\t$rs = $this->db->Execute($query);\n\n\t\t\t\tif (!is_object($rs)) {\n\t\t\t\t\t$this->debug_db('add_acl');\n\t\t\t\t\t$this->db->RollBackTrans();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t$this->db->CommitTrans();\n\n\t\tif ($this->_caching == TRUE AND $this->_force_cache_expire == TRUE) {\n\t\t\t//Expire all cache.\n\t\t\t$this->Cache_Lite->clean('default');\n\t\t}\n\n\t\t//Return only the ID in the first row.\n\t\treturn $acl_id;\n\t}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $projectId, string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response) {\n\n $domain = $request->getHostname();\n $protocol = $request->getProtocol();\n\n $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?'\n . \\http_build_query([\n 'project' => $projectId,\n 'code' => $code,\n 'state' => $state,\n 'error' => $error,\n 'error_description' => $error_description\n ]));\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function receiptArrayDetailLine(\n &$aReceipt,\n $code_type,\n $code,\n $description,\n $quantity,\n $charge,\n $billtime = '',\n $tax = 0,\n $chargecat = ''\n) {\n $adjust = 0;\n $adjreason = '';\n\n // This supports Suriname insurers.\n // It is set to true when the Customer is set and its notes include \"=Ins\".\n $insurer = false;\n if ($chargecat) {\n $tmprow = sqlQuery(\n \"SELECT notes FROM list_options WHERE list_id = 'chargecats' AND \" .\n \"option_id = ? AND activity = 1 AND notes LIKE '%=Ins%' LIMIT 1\",\n array($chargecat)\n );\n if (!empty($tmprow['notes'])) {\n $insurer = true;\n }\n }\n\n // If an invoice level adjustment, get it into the right column.\n if ($code_type === '') {\n $adjust = 0 - $charge;\n $charge = 0;\n } else {\n // Otherwise pull out any adjustments matching this line item.\n if (!empty($GLOBALS['gbl_checkout_line_adjustments'])) {\n // Total and clear matching adjustments in $aReceipt['_adjusts'].\n for ($i = 0; $i < count($aReceipt['_adjusts']); ++$i) {\n if (\n $aReceipt['_adjusts'][$i]['code_type'] == $code_type &&\n $aReceipt['_adjusts'][$i]['code'] == $code &&\n $aReceipt['_adjusts'][$i]['post_time'] == $billtime\n ) {\n $adjust += $aReceipt['_adjusts'][$i]['adj_amount'];\n if ($aReceipt['_adjusts'][$i]['memo']) {\n $adjreason = getAdjustTitle($aReceipt['_adjusts'][$i]['memo']);\n }\n $aReceipt['_adjusts'][$i]['adj_amount'] = 0;\n }\n }\n }\n }\n\n $charge = sprintf('%01.2f', $charge);\n $total = sprintf('%01.2f', $charge - $adjust);\n if (empty($quantity)) {\n $quantity = 1;\n }\n $price = sprintf('%01.4f', $charge / $quantity);\n $tmp = sprintf('%01.2f', $price);\n if ($price == $tmp) {\n $price = $tmp; // converts xx.xx00 to xx.xx.\n }\n\n $aReceipt['items'][] = array(\n 'code_type' => $code_type,\n 'code' => $code,\n 'description' => $description,\n 'price' => $price,\n 'quantity' => $quantity,\n 'charge' => $charge,\n 'adjustment' => sprintf('%01.2f', $adjust),\n 'adjreason' => $adjreason,\n 'total' => $total,\n 'insurer' => $insurer,\n 'tax' => $tax,\n );\n\n $aReceipt['total_price'] = sprintf('%01.2f', $aReceipt['total_price' ] + $price);\n $aReceipt['total_quantity'] = sprintf('%01.2f', $aReceipt['total_quantity' ] + $quantity);\n $aReceipt['total_charges'] = sprintf('%01.2f', $aReceipt['total_charge' ] + $charge);\n $aReceipt['total_adjustments'] = sprintf('%01.2f', $aReceipt['total_adjustments'] + $adjust);\n $aReceipt['total_totals'] = sprintf('%01.2f', $aReceipt['total_totals' ] + $total);\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct(\n CategoryFacade $categoryFacade,\n FlagFacade $flagFacade,\n BrandFacade $brandFacade,\n ProductElasticsearchProvider $productElasticsearchProvider,\n ParameterWithValuesFactory $parameterWithValuesFactory,\n ProductFrontendLimitProvider $productFrontendLimitProvider,\n DataLoaderInterface $productsSellableByIdsBatchLoader,\n CurrentCustomerUser $currentCustomerUser,\n DataLoaderInterface $productsSellableCountByIdsBatchLoader,\n private DataLoaderInterface $categoriesBatchLoader,\n private DataLoaderInterface $flagsBatchLoader,\n private DataLoaderInterface $brandsBatchLoader,\n ) {\n parent::__construct(\n $categoryFacade,\n $flagFacade,\n $brandFacade,\n $productElasticsearchProvider,\n $parameterWithValuesFactory,\n $productFrontendLimitProvider,\n $productsSellableByIdsBatchLoader,\n $currentCustomerUser,\n $productsSellableCountByIdsBatchLoader,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function __construct($ontology_filepath, $onto_store, $onto_store_config, $data_store_type, $data_store_config, $tab_namespaces, $default_display_label, $params){\n\t\t$this->params=$params;\n\t\t\n\t\t$this->handler = new onto_handler($ontology_filepath, $onto_store, $onto_store_config, $data_store_type, $data_store_config, $tab_namespaces, $default_display_label);\n\t\t$this->handler->get_ontology();\n\t\t\n\t\tif(!isset($params->sub) || !$params->sub){\n\t\t\t$params->sub=$this->handler->get_first_ontology_class_name();\n\t\t}\n\t\t$controler_class_name=self::resolve_controler_class_name($this->handler->get_onto_name());\n\t\t$this->controler=new $controler_class_name($this->handler,$this->params);\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function print_percentage_bar($width, $height, $percent, $left_text, $left_colour, $left_background, $right_text, $right_colour, $right_background)\n{\n return \\LibreNMS\\Util\\Html::percentageBar($width, $height, $percent, $left_text, $right_text, null, null, [\n 'left' => $left_background,\n 'left_text' => $left_colour,\n 'right' => $right_background,\n 'right_text' => $right_colour,\n ]);\n}", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function __construct($orientation = 'P', $unit = 'mm', $format = 'A4', $unicode = true, $encoding = 'UTF-8', $diskCache = false, $pdfTemplatePath = null, $enableFooter = true)\n {\n parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskCache);\n $this->pdfTemplatePath = $pdfTemplatePath ?? null;\n $this->enableFooter = $enableFooter;\n $this->commonService = ContainerRegistry::get(CommonService::class);\n }", "smellKey": "S107", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "function thisLineItem($patient_id, $encounter_id, $rowcat, $description, $transdate, $qty, $amount, $irnumber = '')\n{\n global $product, $category, $producttotal, $productqty, $cattotal, $catqty, $grandtotal, $grandqty;\n global $productleft, $catleft;\n\n $invnumber = $irnumber ? $irnumber : \"$patient_id.$encounter_id\";\n $rowamount = sprintf('%01.2f', $amount);\n\n $patdata = sqlQuery(\"SELECT \" .\n \"p.fname, p.mname, p.lname, p.pubpid, p.DOB, \" .\n \"p.street, p.city, p.state, p.postal_code, \" .\n \"p.ss, p.sex, p.status, p.phone_home, \" .\n \"p.phone_biz, p.phone_cell, p.hipaa_notice \" .\n \"FROM patient_data AS p \" .\n \"WHERE p.pid = ? LIMIT 1\", array($patient_id));\n\n $pat_name = $patdata['fname'] . ' ' . $patdata['mname'] . ' ' . $patdata['lname'];\n\n if (empty($rowcat)) {\n $rowcat = xl('None{{Sales}}');\n }\n\n $rowproduct = $description;\n if (! $rowproduct) {\n $rowproduct = xl('Unknown');\n }\n\n if ($product != $rowproduct || $category != $rowcat) {\n if ($product) {\n // Print product total.\n if ($_POST['form_csvexport']) {\n if (! $_POST['form_details']) {\n echo csvEscape(display_desc($category)) . ',';\n echo csvEscape(display_desc($product)) . ',';\n echo csvEscape($productqty) . ',';\n echo csvEscape(FormatMoney::getBucks($producttotal));\n echo \"\\n\";\n }\n } else {\n ?>\n \n \n \n \n \n \n \n \n \n  \n \n \n \n  \n \n \n \n \n \n \n \n \n \n\n \n \n  \n \n \n \n \n \n \n  \n \n \n \n  \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n  \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n  \n \n \n \n \n \n \n \n \n \n x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);\n\t\t\t$this->javascript .= 'f'.$name.\".buttonSetCaption('\".addslashes($caption).\"');\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".setAction('MouseUp','\".addslashes($action).\"');\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".highlight='push';\\n\";\n\t\t\t$this->javascript .= 'f'.$name.\".print=false;\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t$prop['Pushbutton'] = 'true';\n\t\t$prop['highlight'] = 'push';\n\t\t$prop['display'] = 'display.noPrint';\n\t\t// get annotation data\n\t\t$popt = $this->getAnnotOptFromJSProp($prop);\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';\n\t\t// set additional default options\n\t\tif (!isset($popt['mk'])) {\n\t\t\t$popt['mk'] = array();\n\t\t}\n\t\t$ann_obj_id = ($this->n + 1);\n\t\tif (!empty($action) AND !is_array($action)) {\n\t\t\t$ann_obj_id = ($this->n + 2);\n\t\t}\n\t\t$popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);\n\t\t$popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);\n\t\t$popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Btn';\n\t\t$opt['t'] = $caption;\n\t\t$opt['v'] = $name;\n\t\tif (!empty($action)) {\n\t\t\tif (is_array($action)) {\n\t\t\t\t// form action options as on section 12.7.5 of PDF32000_2008.\n\t\t\t\t$opt['aa'] = '/D <<';\n\t\t\t\t$bmode = array('SubmitForm', 'ResetForm', 'ImportData');\n\t\t\t\tforeach ($action AS $key => $val) {\n\t\t\t\t\tif (($key == 'S') AND in_array($val, $bmode)) {\n\t\t\t\t\t\t$opt['aa'] .= ' /S /'.$val;\n\t\t\t\t\t} elseif (($key == 'F') AND (!empty($val))) {\n\t\t\t\t\t\t$opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);\n\t\t\t\t\t} elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {\n\t\t\t\t\t\t$opt['aa'] .= ' /Fields [';\n\t\t\t\t\t\tforeach ($val AS $field) {\n\t\t\t\t\t\t\t$opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$opt['aa'] .= ']';\n\t\t\t\t\t} elseif (($key == 'Flags')) {\n\t\t\t\t\t\t$ff = 0;\n\t\t\t\t\t\tif (is_array($val)) {\n\t\t\t\t\t\t\tforeach ($val AS $flag) {\n\t\t\t\t\t\t\t\tswitch ($flag) {\n\t\t\t\t\t\t\t\t\tcase 'Include/Exclude': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeNoValueFields': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 1;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExportFormat': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 2;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'GetMethod': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 3;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'SubmitCoordinates': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 4;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'XFDF': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 5;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeAppendSaves': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 6;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'IncludeAnnotations': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 7;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'SubmitPDF': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 8;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'CanonicalFormat': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 9;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExclNonUserAnnots': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 10;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'ExclFKey': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 11;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase 'EmbedForm': {\n\t\t\t\t\t\t\t\t\t\t$ff += 1 << 13;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$ff = intval($val);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$opt['aa'] .= ' /Flags '.$ff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$opt['aa'] .= ' >>';\n\t\t\t} else {\n\t\t\t\t// Javascript action or raw action command\n\t\t\t\t$js_obj_id = $this->addJavascriptObject($action);\n\t\t\t\t$opt['aa'] = '/D '.$js_obj_id.' 0 R';\n\t\t\t}\n\t\t}\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function generate(\n $patient_id,\n $encounter_id,\n $sent_by,\n $send,\n $view,\n $emr_transfer,\n $components,\n $sections,\n $recipients,\n $params,\n $document_type,\n $referral_reason,\n $date_options = []\n ): GeneratedCcdaResult {\n\n // we need to make sure we don't accidently stuff in the debug logs any PHI so we'll only report on the presence of certain variables\n (new SystemLogger())->debug(\"CcdaGenerator->generate() called \", ['patient_id' => $patient_id\n , 'encounter_id' => $encounter_id, 'sent_by' => (!empty($sent_by) ? \"sent_by not empty\" : \"sent_by is empty\")\n , 'send' => $send, 'view' => $view, 'emr_transfer' => $emr_transfer, 'components' => $components\n , 'sections' => $sections, 'recipients' => !empty($recipients) ? \"Recipients count \" . (is_array($recipients) ? count($recipients) : \"1\") : \"No recipients\"\n , 'params' => $params, 'document_type' => $document_type\n , 'referral_reason' => (empty($referral_reason) ? \"No referral reason\" : \"Has referral reason\")\n , 'date_options' => $date_options]);\n if ($sent_by != '') {\n $_SESSION['authUserID'] = $sent_by;\n }\n\n if (!$sections) {\n $components0 = $this->getEncounterccdadispatchTable()->getCCDAComponents(0);\n foreach ($components0 as $key => $value) {\n if ($str ?? '') {\n $str .= '|';\n } else {\n $str = $key;\n continue;\n }\n $str .= $key;\n }\n $sections = $str;\n }\n\n if (!$components) {\n $components1 = $this->getEncounterccdadispatchTable()->getCCDAComponents(1);\n foreach ($components1 as $key => $value) {\n if ($str1 ?? '') {\n $str1 .= '|';\n } else {\n $str1 = $key;\n continue;\n }\n $str1 .= $key;\n }\n $components = $str1;\n }\n $data = $this->create_data(\n $patient_id,\n $encounter_id,\n $sections,\n $components,\n $recipients,\n $params,\n $document_type,\n $referral_reason,\n $send,\n $date_options\n );\n $content = $this->socket_get($data);\n $content = trim($content);\n // split content if unstructured is included from service.\n // service will send back a CDA and an auto created unstructured document\n // if CCM sends the documents(patient_files object) with data array.\n $unstructured = \"\";\n if (substr_count($content, '') == 2) {\n $d = explode('', $content);\n $content = $d[0] . '';\n $unstructured = $d[1] . '';\n }\n // save if generated by service. Filo!\n if (!empty($unstructured)) {\n $generatedResultUnstructered = $this->getEncounterccdadispatchTable()->logCCDA(\n $patient_id,\n $encounter_id,\n base64_encode($unstructured),\n $this->createdtime,\n 0,\n $_SESSION['authUserID'],\n 'unstructured',\n $view,\n $send,\n $emr_transfer\n );\n }\n $generatedResult = $this->getEncounterccdadispatchTable()->logCCDA(\n $patient_id,\n $encounter_id,\n base64_encode($content),\n $this->createdtime,\n 0,\n $_SESSION['authUserID'],\n $document_type,\n $view,\n $send,\n $emr_transfer\n );\n\n return $generatedResult;\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n Indexer $searchIndexer,\n Handler $locationHandler,\n IndexerGateway $gateway,\n LoggerInterface $logger,\n string $siteaccess,\n string $env,\n bool $isDebug,\n string $projectDir,\n ContentIdListGeneratorStrategyInterface $contentIdListGeneratorStrategy,\n string $phpPath = null\n ) {\n $this->gateway = $gateway;\n $this->searchIndexer = $searchIndexer;\n $this->locationHandler = $locationHandler;\n $this->phpPath = $phpPath;\n $this->logger = $logger;\n $this->siteaccess = $siteaccess;\n $this->env = $env;\n $this->isDebug = $isDebug;\n $this->projectDir = $projectDir;\n $this->contentIdListGeneratorStrategy = $contentIdListGeneratorStrategy;\n\n parent::__construct();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function write_form_line(\n $code_type,\n $code,\n $id,\n $date,\n $description,\n $amount,\n $units,\n $taxrates\n ) {\n global $lino;\n $amount = sprintf(\"%01.2f\", $amount);\n if (empty($units)) {\n $units = 1;\n }\n $price = $amount / $units; // should be even cents, but ok here if not\n if ($code_type == 'COPAY' && !$description) {\n $description = xl('Payment');\n }\n echo \" \\n\";\n echo \" \" . text(oeFormatShortDate($date));\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n echo \" \" . text($description) . \"\";\n echo \" \" . text($units) . \"\";\n echo \" \\n\";\n echo \" \\n\";\n ++$lino;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function updateItemOnEventJsCode(\n $toobserve,\n $toupdate,\n $url,\n $parameters = [],\n $events = [\"change\"],\n $minsize = -1,\n $buffertime = -1,\n $forceloadfor = [],\n $display = true\n ) {\n\n if (is_array($toobserve)) {\n $zones = $toobserve;\n } else {\n $zones = [$toobserve];\n }\n $output = '';\n foreach ($zones as $zone) {\n foreach ($events as $event) {\n $event = htmlescape($event);\n $zone_id = htmlescape(Html::cleanId($zone));\n\n if ($buffertime > 0) {\n $output .= \"var last$zone$event = 0;\";\n }\n\n $output .= \"$('#$zone_id').on('$event', function(event) {\";\n $condition = '';\n if ($minsize >= 0) {\n $condition = \"$('#$zone_id').val().length >= $minsize \";\n }\n if (count($forceloadfor)) {\n foreach ($forceloadfor as $value) {\n if (!empty($condition)) {\n $condition .= \" || \";\n }\n $condition .= \"$('#$zone_id').val() == '$value'\";\n }\n }\n if (!empty($condition)) {\n $output .= \"if ($condition) {\";\n }\n $output .= self::updateItemJsCode($toupdate, $url, $parameters, $toobserve, false);\n if (!empty($condition)) {\n $output .= \"}\";\n }\n $output .= \"}\";\n $output .= \");\";\n }\n }\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "smellKey": "S107", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(\n $type,\n $device_id,\n $oids,\n $subtype,\n $index,\n $description,\n $current = null,\n $multiplier = 1,\n $divisor = 1,\n $aggregator = 'sum',\n $access_point_id = null,\n $high_limit = null,\n $low_limit = null,\n $high_warn = null,\n $low_warn = null,\n $entPhysicalIndex = null,\n $entPhysicalMeasured = null\n ) {\n $this->access_point_ip = $access_point_id;\n parent::__construct(\n $type,\n $device_id,\n $oids,\n $subtype,\n $index,\n $description,\n $current,\n $multiplier,\n $divisor,\n $aggregator,\n $high_limit,\n $low_limit,\n $high_warn,\n $low_warn,\n $entPhysicalIndex,\n $entPhysicalMeasured\n );\n }", "smellKey": "S107", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "public function __construct(\n\t\t?bool $outFlagSegunda,\n\t\t?string $outHoraIniAulaSegunda,\n\t\t?string $outHoraFimAulaSegunda,\n\t\t?bool $outFlagTerca,\n\t\t?string $outHoraIniAulaTerca,\n\t\t?string $outHoraFimAulaTerca,\n\t\t?bool $outFlagQuarta,\n\t\t?string $outHoraIniAulaQuarta,\n\t\t?string $outHoraFimAulaQuarta,\n\t\t?bool $outFlagQuinta,\n\t\t?string $outHoraIniAulaQuinta,\n\t\t?string $outHoraFimAulaQuinta,\n\t\t?bool $outFlagSexta,\n\t\t?string $outHoraIniAulaSexta,\n\t\t?string $outHoraFimAulaSexta,\n\t\t?bool $outFlagSabado\n\t) {\n\t\t$this->outFlagSegunda = $outFlagSegunda;\n\t\t$this->outHoraIniAulaSegunda = $outHoraIniAulaSegunda;\n\t\t$this->outHoraFimAulaSegunda = $outHoraFimAulaSegunda;\n\t\t$this->outFlagTerca = $outFlagTerca;\n\t\t$this->outHoraIniAulaTerca = $outHoraIniAulaTerca;\n\t\t$this->outHoraFimAulaTerca = $outHoraFimAulaTerca;\n\t\t$this->outFlagQuarta = $outFlagQuarta;\n\t\t$this->outHoraIniAulaQuarta = $outHoraIniAulaQuarta;\n\t\t$this->outHoraFimAulaQuarta = $outHoraFimAulaQuarta;\n\t\t$this->outFlagQuinta = $outFlagQuinta;\n\t\t$this->outHoraIniAulaQuinta = $outHoraIniAulaQuinta;\n\t\t$this->outHoraFimAulaQuinta = $outHoraFimAulaQuinta;\n\t\t$this->outFlagSexta = $outFlagSexta;\n\t\t$this->outHoraIniAulaSexta = $outHoraIniAulaSexta;\n\t\t$this->outHoraFimAulaSexta = $outHoraFimAulaSexta;\n\t\t$this->outFlagSabado = $outFlagSabado;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function __construct($xLabels, $xValues, $colorArray, $width, $height, $legend1, $legend2, $legend3, $view, $noData)\n {\n $this->xLabels = $xLabels;\n $this->xValues = $xValues;\n $this->colorArray = $colorArray;\n $this->width = $width;\n $this->height = $height;\n $this->legend1 = $legend1;\n $this->legend2 = $legend2;\n $this->legend3 = $legend3;\n $this->view = $view;\n $this->noData = $noData;\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function creerDossierEB($ref_dos, $id_cli, $num_lic, $id_march, $id_mod_lic, \n\t\t\t\t\t\t\t\t\t\t$id_mod_trans, $id_util, $num_lot, $horse, $trailer_1, \n\t\t\t\t\t\t\t\t\t\t$trailer_2, $site_load, $destination, $transporter, \n\t\t\t\t\t\t\t\t\t\t$nbr_bags, $poids, $load_date, $dgda_seal){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['ref_dos'] = $ref_dos;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_march'] = $id_march;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t$entree['num_lot'] = $num_lot;\n\t\t\t$entree['horse'] = $horse;\n\t\t\t$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['site_load'] = $site_load;\n\t\t\t$entree['destination'] = $destination;\n\t\t\t$entree['transporter'] = $transporter;\n\t\t\t$entree['nbr_bags'] = $nbr_bags;\n\t\t\t$entree['poids'] = $poids;\n\t\t\t$entree['load_date'] = $load_date;\n\t\t\t$entree['dgda_seal'] = $dgda_seal;\n\n\t\t\t/*echo '
    ref_dos = '.$ref_dos;\n\t\t\techo '
    id_cli = '.$id_cli;\n\t\t\techo '
    num_lic = '.$num_lic;\n\t\t\techo '
    id_march = '.$id_march;\n\t\t\techo '
    id_mod_lic = '.$id_mod_lic;\n\t\t\techo '
    id_mod_trans = '.$id_mod_trans;\n\t\t\techo '
    id_util = '.$id_util;\n\t\t\techo '
    num_lot = '.$num_lot;\n\t\t\techo '
    horse = '.$horse;\n\t\t\techo '
    trailer_1 = '.$trailer_1;\n\t\t\techo '
    trailer_2 = '.$trailer_2;\n\t\t\techo '
    site_load = '.$site_load;\n\t\t\techo '
    destination = '.$destination;\n\t\t\techo '
    transporter = '.$transporter;\n\t\t\techo '
    nbr_bags = '.$nbr_bags;\n\t\t\techo '
    poids = '.$poids;\n\t\t\techo '
    load_date = '.$load_date;\n\t\t\techo '---------------
    ';*/\n\n\t\t\tif($entree['load_date'] == '' || (!isset($entree['load_date'])) ){\n\t\t\t\t$entree['load_date'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['poids'] == '' || (!isset($entree['poids'])) ){\n\t\t\t\t$entree['poids'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['nbr_bags'] == '' || (!isset($entree['nbr_bags'])) ){\n\t\t\t\t$entree['nbr_bags'] = NULL;\n\t\t\t}\n\n\t\t\tif (($this-> getDossierRefDos($ref_dos)==NULL)) {\n\t\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, num_lic, id_march, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_mod_trans, id_util, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnum_lot, horse, trailer_1, trailer_2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsite_load, destination, transporter, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnbr_bags, poids, load_date, dgda_seal)\n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['num_lic'], \n\t\t\t\t\t\t\t\t\t\t$entree['id_march'], $entree['id_mod_lic'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t\t$entree['id_util'], $entree['num_lot'], $entree['horse'], \n\t\t\t\t\t\t\t\t\t\t$entree['trailer_1'], $entree['trailer_2'], $entree['site_load'], \n\t\t\t\t\t\t\t\t\t\t$entree['destination'], $entree['transporter'], $entree['nbr_bags'], \n\t\t\t\t\t\t\t\t\t\t$entree['poids'], $entree['load_date'], $entree['dgda_seal']));\n\t\t\t}\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function (string $userId, string $secret, string $password, string $passwordAgain, Response $response, Document $user, Database $dbForProject, Document $project, Event $events) {\n if ($password !== $passwordAgain) {\n throw new Exception(Exception::USER_PASSWORD_MISMATCH);\n }\n\n $profile = $dbForProject->getDocument('users', $userId);\n\n if ($profile->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $tokens = $profile->getAttribute('tokens', []);\n $recovery = Auth::tokenVerify($tokens, Auth::TOKEN_TYPE_RECOVERY, $secret);\n\n if (!$recovery) {\n throw new Exception(Exception::USER_INVALID_TOKEN);\n }\n\n Authorization::setRole(Role::user($profile->getId())->toString());\n\n $newPassword = Auth::passwordHash($password, Auth::DEFAULT_ALGO, Auth::DEFAULT_ALGO_OPTIONS);\n\n $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;\n $history = $profile->getAttribute('passwordHistory', []);\n if ($historyLimit > 0) {\n $validator = new PasswordHistory($history, $profile->getAttribute('hash'), $profile->getAttribute('hashOptions'));\n if (!$validator->isValid($password)) {\n throw new Exception(Exception::USER_PASSWORD_RECENTLY_USED);\n }\n\n $history[] = $newPassword;\n $history = array_slice($history, (count($history) - $historyLimit), $historyLimit);\n }\n\n $profile = $dbForProject->updateDocument('users', $profile->getId(), $profile\n ->setAttribute('password', $newPassword)\n ->setAttribute('passwordHistory', $history)\n ->setAttribute('passwordUpdate', DateTime::now())\n ->setAttribute('hash', Auth::DEFAULT_ALGO)\n ->setAttribute('hashOptions', Auth::DEFAULT_ALGO_OPTIONS)\n ->setAttribute('emailVerification', true));\n\n $user->setAttributes($profile->getArrayCopy());\n\n $recoveryDocument = $dbForProject->getDocument('tokens', $recovery);\n\n /**\n * We act like we're updating and validating\n * the recovery token but actually we don't need it anymore.\n */\n $dbForProject->deleteDocument('tokens', $recovery);\n $dbForProject->deleteCachedDocument('users', $profile->getId());\n\n $events\n ->setParam('userId', $profile->getId())\n ->setParam('tokenId', $recoveryDocument->getId())\n ;\n\n $response->dynamic($recoveryDocument, Response::MODEL_TOKEN);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function creerAV($cod, $date_av, $montant_av, \n\t\t\t\t\t\t\t\t$fxi, $num_lic, $fichier_av, \n\t\t\t\t\t\t\t\t$tmp_av, $id_util, $id_mon){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['cod'] = $cod;\n\t\t\t$entree['date_av'] = $date_av;\n\t\t\t$entree['montant_av'] = $montant_av;\n\t\t\t$entree['fxi'] = $fxi;\n\t\t\t$entree['num_lic'] = $num_lic;\n\t\t\t$entree['fichier_av'] = $fichier_av;\n\t\t\t$entree['id_util'] = $id_util;\n\t\t\t$entree['id_mon'] = $id_mon;\n\n\t\t\t/*echo '
    cod = '.$cod;\n\t\t\techo '
    date_av = '.$date_av;\n\t\t\techo '
    montant_av = '.$montant_av;\n\t\t\techo '
    fxi= '.$fxi;\n\t\t\techo '
    num_lic = '.$num_lic;\n\t\t\techo '
    fichier_av = '.$fichier_av;\n\t\t\techo '
    id_util = '.$id_util;\n\t\t\techo '
    id_mon = '.$id_mon;\n\t\t\techo '
    id_march = '.$id_march;*/\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO av(cod, date_av, montant_av, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfxi, num_lic, fichier_av, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_util, id_mon)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['cod'], $entree['date_av'], $entree['montant_av'], \n\t\t\t\t\t\t\t\t\t$entree['fxi'], $entree['num_lic'], $entree['fichier_av'], \n\t\t\t\t\t\t\t\t\t$entree['id_util'], $entree['id_mon']));\n\n\t\t\t/*$av = '../av/'.$fichier_av;\n\n\t\t\tif(!is_dir($av)){\n\t\t\t\tmkdir(\"../av/$fichier_av\", 0777);\n\t\t\t}*/\n\n\t\t\tmove_uploaded_file($tmp_av, '../av/' . basename($fichier_av));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function creerDossierTrackingIBUpload($client, $ref_dos, $mca_b_ref, $road_manif, $date_preal, $t1, \n\t\t\t\t\t\t\t\t\t\t$poids, $fob, $fret, $assurance, \n\t\t\t\t\t\t\t\t\t\t$autre_frais, $ref_fact, $fournisseur, $po, \n\t\t\t\t\t\t\t\t\t\t$commodity, $horse, $trailer_1, $trailer_2, $id_mod_lic){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;$entree['mca_b_ref'] = $mca_b_ref;\n\t\t\t$entree['date_preal'] = $date_preal;$entree['t1'] = $t1;\n\t\t\t$entree['poids'] = $poids;$entree['fob'] = $fob;\n\t\t\t$entree['fret'] = $fret;$entree['assurance'] = $assurance;$entree['autre_frais'] = $autre_frais;\n\t\t\t$entree['ref_fact'] = $ref_fact;$entree['po'] = $po;\n\t\t\t$entree['commodity'] = $commodity;$entree['horse'] = $horse;$entree['trailer_1'] = $trailer_1;\n\t\t\t$entree['trailer_2'] = $trailer_2;$entree['road_manif'] = $road_manif;$entree['fournisseur'] = $fournisseur;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload(client, ref_dos, mca_b_ref, date_preal, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tt1, poids, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfret, assurance, autre_frais, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tref_fact, fournisseur, po, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommodity, horse, trailer_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrailer_2, road_manif, id_mod_lic) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['mca_b_ref'], $entree['date_preal'], \n\t\t\t\t\t\t\t\t\t$entree['t1'], $entree['poids'], $entree['fob'], \n\t\t\t\t\t\t\t\t\t$entree['fret'], $entree['assurance'], $entree['autre_frais'], \n\t\t\t\t\t\t\t\t\t$entree['ref_fact'], $entree['fournisseur'], $entree['po'], \n\t\t\t\t\t\t\t\t\t$entree['commodity'], $entree['horse'], $entree['trailer_1'], \n\t\t\t\t\t\t\t\t\t$entree['trailer_2'], $entree['road_manif'], $entree['id_mod_lic']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function __construct(\\WPML\\Core\\Twig\\Node\\Expression\\AssignNameExpression $keyTarget, \\WPML\\Core\\Twig\\Node\\Expression\\AssignNameExpression $valueTarget, \\WPML\\Core\\Twig\\Node\\Expression\\AbstractExpression $seq, \\WPML\\Core\\Twig\\Node\\Expression\\AbstractExpression $ifexpr = null, \\WPML\\Core\\Twig_NodeInterface $body, \\WPML\\Core\\Twig_NodeInterface $else = null, $lineno, $tag = null)\n {\n $body = new \\WPML\\Core\\Twig\\Node\\Node([$body, $this->loop = new \\WPML\\Core\\Twig\\Node\\ForLoopNode($lineno, $tag)]);\n if (null !== $ifexpr) {\n $body = new \\WPML\\Core\\Twig\\Node\\IfNode(new \\WPML\\Core\\Twig\\Node\\Node([$ifexpr, $body]), null, $lineno, $tag);\n }\n $nodes = ['key_target' => $keyTarget, 'value_target' => $valueTarget, 'seq' => $seq, 'body' => $body];\n if (null !== $else) {\n $nodes['else'] = $else;\n }\n parent::__construct($nodes, ['with_loop' => \\true, 'ifexpr' => null !== $ifexpr], $lineno, $tag);\n }", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n LoggerInterface $logger,\n TeleHealthVideoRegistrationController $registrationController,\n TeleHealthParticipantInvitationMailerService $mailerService,\n TeleHealthFrontendSettingsController $settingsController,\n TelehealthGlobalConfig $config,\n TeleHealthProvisioningService $provisioningService,\n ParticipantListService $participantListService,\n $assetPath,\n $isPatient = false\n ) {\n $this->assetPath = $assetPath;\n $this->twig = $twig;\n $this->logger = $logger;\n $this->isPatient = $isPatient;\n $this->appointmentService = new AppointmentService();\n $this->encounterService = new EncounterService();\n $this->sessionRepository = new TeleHealthSessionRepository();\n $this->telehealthRegistrationController = $registrationController;\n $this->telehealthUserRepo = new TeleHealthUserRepository();\n $this->mailerService = $mailerService;\n $this->settingsController = $settingsController;\n $this->config = $config;\n $this->provisioningService = $provisioningService;\n $this->participantListService = $participantListService;\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function CreateColumn($metric, $variable, $source, $output, $dataset, $datasetName,\n\t\t\t$calculatedField, $caption, $decimals = 2, $colWidth = 11, $fieldWidth = 11, $format = Format::F)\n\t{\n\t\t$datasetColumn = new DatasetColumnService();\n\t\t$name = $this->GetColumnName($datasetName, $calculatedField);\n\t\t$label = $this->GetColumnCaption($metric, $variable, $source, $output, $caption, $dataset, $datasetName);\n\n\t\t$col = $datasetColumn->GetColumnByVariable($dataset->getId(), $name);\n\t\tif($col == null)\n\t\t{\n\t\t\t$showCaption = ($label === null || trim($label) === \"\" ? $name : $label);\n\t\t\t$field = $datasetColumn->resolveStandardFieldName($dataset->getId());\n\t\t\t$col = $datasetColumn->CreateColumnFromFields($dataset, $field, $name,\n\t\t\t\t$showCaption, $label, $colWidth, $fieldWidth, $decimals, $format,\n\t\t\t\tMeasurement::Nominal, Alignment::Left, true, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif($col->getLabel() != $label)\n\t\t\t\t$datasetColumn->UpdateLabel($col, $label);\n\t\t\t// vac\u00eda los valores\n\t\t\t$datasetColumn->ResetColumnValues($dataset, $col);\n\t\t}\n\t\treturn $col;\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "function test_rules_clinic($provider = '', $type = '', $dateTarget = '', $mode = '', $patient_id = '', $plan = '', $organize_mode = 'default', $options = array(), $pat_prov_rel = 'primary', $start = null, $batchSize = null, $user = '')\n{\n\n // If dateTarget is an array, then organize them.\n if (is_array($dateTarget)) {\n $dateArray = $dateTarget;\n $dateTarget = $dateTarget['dateTarget'];\n } else {\n $dateArray = [];\n }\n\n // Set date to current if not set\n $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');\n\n // Prepare the results array\n $results = array();\n\n // we have a special mechanism for collation or plans organize method\n if ($provider === \"collate_outer\" || $organize_mode === 'plans') {\n return test_rules_clinic_collate($provider, $type, $dateTarget, $mode, $patient_id, $plan, $organize_mode, $options, $pat_prov_rel, $start, $batchSize, $user);\n }\n\n if ($provider === \"group_calculation\") {\n return test_rules_clinic_group_calculation($type, $dateArray, $mode, $patient_id, $plan, $organize_mode, $options, $pat_prov_rel, $start, $batchSize, $user);\n }\n\n // Collect applicable patient pids\n $patientData = buildPatientArray($patient_id, $provider, $pat_prov_rel, $start, $batchSize, false, $options['billing_facility_id'] ?? null);\n\n // Go through each patient(s)\n //\n // If in report mode, then tabulate for each rule:\n // Total Patients\n // Patients that pass the filter\n // Patients that pass the target\n // If in reminders mode, then create reminders for each rule:\n // Reminder that action is due soon\n // Reminder that action is due\n // Reminder that action is post-due\n\n //Collect applicable rules\n // Note that due to a limitation in the this function, the patient_id is explicitly\n // for grouping items when not being done in real-time or for official reporting.\n // So for cases such as patient reminders on a clinic scale, the calling function\n // will actually need rather than pass in a explicit patient_id for each patient in\n // a separate call to this function.\n $rules = resolve_rules_sql($type, $patient_id, false, $plan, $user);\n\n foreach ($rules as $rowRule) {\n // If using cqm or amc type, then use the hard-coded rules set.\n // Note these rules are only used in report mode.\n if ($rowRule['cqm_flag'] || $rowRule['amc_flag']) {\n $tempResults = test_rules_clinic_cqm_amc_rule($rowRule, $patientData, $dateArray, $dateTarget, $options, $provider, $pat_prov_rel);\n $results = array_merge($results, $tempResults);\n // Go on to the next rule\n continue;\n }\n\n // ALL OF THE BELOW RULES ARE FOR active_alert, passive_alert,patient_reminder\n // If in reminder mode then need to collect the measurement dates\n // from rule_reminder table\n $target_dates = array();\n if ($mode != \"report\") {\n // Calculate the dates to check for\n if ($type == \"patient_reminder\") {\n $reminder_interval_type = \"patient_reminder\";\n } else { // $type == \"passive_alert\" or $type == \"active_alert\"\n $reminder_interval_type = \"clinical_reminder\";\n }\n\n $target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);\n } else { // $mode == \"report\"\n // Only use the target date in the report\n $target_dates[0] = $dateTarget;\n }\n\n //Reset the counters\n $total_patients = 0;\n $pass_filter = 0;\n $exclude_filter = 0;\n $pass_target = 0;\n\n // Find the number of target groups\n $targetGroups = returnTargetGroups($rowRule['id']);\n\n if ((count($targetGroups) == 1) || ($mode == \"report\")) {\n // If report itemization is turned on, then iterate the rule id iterator\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $GLOBALS['report_itemized_test_id_iterator']++;\n }\n\n //skip this section if not report and more than one target group\n foreach ($patientData as $rowPatient) {\n // First, deal with deceased patients\n // (for now will simply skip the patient)\n // If want to support rules for deceased patients then will need to migrate this below\n // in target_dates foreach(guessing won't ever need to do this, though).\n // Note using the dateTarget rather than dateFocus\n if (is_patient_deceased($rowPatient['pid'], $dateTarget)) {\n continue;\n }\n\n // Count the total patients\n $total_patients++;\n\n $dateCounter = 1; // for reminder mode to keep track of which date checking\n // If report itemization is turned on, reset flag.\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $temp_track_pass = 1;\n }\n\n // Check if pass filter\n /*\n HR: moved the test_filter() check to this location, outside\n foreach ($target_dates as $dateFocus)\n\n Filters do not need to be tested against each $dateFocus value (see below) and filters were inappropriately failing to evaluate to true when\n filters were evaluated against $dateFoucs rather than $dateTarget.\n\n test_filter() looks for patient data entered prior to $dateTarget timepoint\n\n test_filter() was previously returning:\n --false if an inclusion filter does not succeed\n --\"EXCLUDED\" if an exclusion filter succeeds\n --otherwise true\n\n Changed so it now returns:\n -- if any required inclusions fail, return false\n -- if there are no required inclusions, and some optional inclusions exist, and any optional inclusions succeed,\n and either exclusions don't exist or exclusions don't succeed, return true\n -- if all inclusions are optional, and none succeed, return false\n -- if there are no inclusions, and there are exclusions, and exclusions do not succeed, return true\n -- if exclusions succeed (checked only if there are no inclusions, or if inclusions succeed), return 'EXCLUDED'\n -- if no inclusions or exclusions, return true (needed per Brady Miller). Rule will be applicable to all patients\n\n -- when processing inclusions, if filters exist in multiple categories (e.g. age, gender and lifestyle), need to process all categories.\n -- If required filters in one category succeed, need to check for required filters in other categories\n -- Similarly, if all filters in one category are optional and do not succeed, need to see if optional filters exist in a different category\n -- that might succeed\n\n -- Mixing optional and required filters makes no sense, but is tollerated. If one filter is required, any optional filters have no relevence\n\n -- Same ideas have been applied to analysis of targets\n */\n $passFilter = test_filter($rowPatient['pid'], $rowRule['id'], $dateTarget);\n if ($passFilter === \"EXCLUDED\") {\n // increment EXCLUDED and pass_filter counters\n // and set as FALSE for reminder functionality.\n $pass_filter++;\n $exclude_filter++;\n $passFilter = false;\n }\n\n if ($passFilter) {\n // increment pass filter counter\n $pass_filter++;\n // If report itemization is turned on, trigger flag.\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $temp_track_pass = 0;\n }\n\n foreach ($target_dates as $dateFocus) {\n //Skip if date is set to SKIP\n if ($dateFocus == \"SKIP\") {\n $dateCounter++;\n continue;\n }\n\n //Set date counter and reminder token (applicable for reminders only)\n // HR: $reminder_due is the status the reminder will have if the current value of $dateFocus passes the target\n // If target does not pass on last (3rd) pass, the status of 'past_due' will be used\n if ($dateCounter == 1) {\n $reminder_due = \"not_due\";\n } elseif ($dateCounter == 2) {\n $reminder_due = \"soon_due\";\n } else { // $dateCounter == 3\n $reminder_due = \"due\";\n }\n\n // Check if pass target\n /*\n HR: rules UI defines targets as lifestyle, custom table or custom.\n All of these are evaluated by \"database\" lookup (unlike filters, which can also look at age, gender, lists, and procedures)\n test_targets can look at procedures or appointments as well, but not defined in rule UI\n I reworked test_targets similar to how I reworked test_filters to properly handle required vs inclusion targets, and multiple target categories\n Previously, if had a single target, which was optional and evaluated to false, test_targets would return true.\n test_targets now returns false if have only optional targets and none evaluate to true\n\n test_targets considers all targets as \"inclusion\" even if target is defined as \"exclusion\"\n\n I added $dateTarget param to call to test_targets, to allow right boundary of examined intervals to be $dateTarget regardless of $dateFocus value\n */\n $passTarget = test_targets($rowPatient['pid'], $rowRule['id'], '', $dateFocus, $dateTarget);\n if ($passTarget) {\n // increment pass target counter (used for reporting)\n $pass_target++;\n // If report itemization is turned on, then record the \"passed\" item and set the flag\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);\n $temp_track_pass = 1;\n }\n\n if (\n ($mode != \"report\") &&\n (($mode == \"reminders-all\") || (($mode != \"reminders-all\") && ($reminder_due != \"not_due\")))\n ) {\n // Place the actions into the reminder return array.\n // There are 2 reminder modes, reminders-due and reminders-all. The not_due reminders are not\n // shown in reminders-due mode but are shown in reminders-all mode. So this block is skipped\n // if due_status is 'not_due' and mode is not 'reminders-all'.\n $actionArray = resolve_action_sql($rowRule['id'], '1');\n foreach ($actionArray as $action) {\n $action_plus = $action;\n $action_plus['due_status'] = $reminder_due;\n $action_plus['pid'] = $rowPatient['pid'];\n $action_plus['rule_id'] = $rowRule['id'];\n $results = reminder_results_integrate($results, $action_plus, $mode);\n }\n }\n\n break;\n } else {\n if (($mode != \"report\") && ($dateCounter == 3)) {\n // Did not pass any of the target dates, so place the past_due actions into the reminder\n // return array when runnning in one of the reminders mode (either reminders-due mode\n // or reminders-all mode).\n $actionArray = resolve_action_sql($rowRule['id'], '1');\n foreach ($actionArray as $action) {\n $action_plus = $action;\n $action_plus['due_status'] = 'past_due';\n $action_plus['pid'] = $rowPatient['pid'];\n $action_plus['rule_id'] = $rowRule['id'];\n $results = reminder_results_integrate($results, $action_plus, $mode);\n }\n }\n }\n\n $dateCounter++;\n }\n }\n\n // If report itemization is turned on, then record the \"failed\" item if it did not pass\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id']) && !($temp_track_pass)) {\n insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);\n }\n }\n }\n\n if ($mode == \"report\") {\n // Calculate and save the data for the rule (only pertinent for report mode)\n $percentage = calculate_percentage($pass_filter, $exclude_filter, $pass_target);\n $newRow = array('is_main' => true,'total_patients' => $total_patients,'excluded' => $exclude_filter,'pass_filter' => $pass_filter,'pass_target' => $pass_target,'percentage' => $percentage);\n $newRow = array_merge($newRow, $rowRule);\n\n // If itemization is turned on, then record the itemized_test_id\n if ($GLOBALS['report_itemizing_temp_flag_and_id']) {\n $newRow = array_merge($newRow, array('itemized_test_id' => $GLOBALS['report_itemized_test_id_iterator']));\n }\n\n $results[] = $newRow;\n }\n\n // Now run through the target groups if more than one\n if (count($targetGroups) > 1) {\n foreach ($targetGroups as $i) {\n // If report itemization is turned on, then iterate the rule id iterator\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $GLOBALS['report_itemized_test_id_iterator']++;\n }\n\n //Reset the target counter\n $pass_target = 0;\n\n foreach ($patientData as $rowPatient) {\n // First, deal with deceased patients\n // (for now will simply skip the patient)\n // If want to support rules for deceased patients then will need to migrate this below\n // in target_dates foreach(guessing won't ever need to do this, though).\n // Note using the dateTarget rather than dateFocus\n if (is_patient_deceased($rowPatient['pid'], $dateTarget)) {\n continue;\n }\n\n $dateCounter = 1; // for reminder mode to keep track of which date checking\n // If report itemization is turned on, reset flag.\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $temp_track_pass = 1;\n }\n\n // Check if pass filter\n /*\n HR: moved the test_filter() check to this location, outside\n foreach ($target_dates as $dateFocus)\n Filters do not need to be tested against each $dateFocus value (see below) and filters were inappropriately failing to evaluate to true when\n filters were evaluated against $dateFoucs rather than $dateTarget.\n */\n $passFilter = test_filter($rowPatient['pid'], $rowRule['id'], $dateTarget);\n if ($passFilter === \"EXCLUDED\") {\n $passFilter = false;\n }\n\n if ($passFilter) {\n // If report itemization is turned on, trigger flag.\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {\n $temp_track_pass = 0;\n }\n\n foreach ($target_dates as $dateFocus) {\n //Skip if date is set to SKIP\n if ($dateFocus == \"SKIP\") {\n $dateCounter++;\n continue;\n }\n\n //Set date counter and reminder token (applicable for reminders only)\n if ($dateCounter == 1) {\n $reminder_due = \"not_due\";\n } elseif ($dateCounter == 2) {\n $reminder_due = \"soon_due\";\n } else { // $dateCounter == 3\n $reminder_due = \"due\";\n }\n\n //Check if pass target\n // HR: I added $dateTarget param to test_targets to allow right boundary to be $dateTarget regardless of $dateFocus value\n $passTarget = test_targets($rowPatient['pid'], $rowRule['id'], $i, $dateFocus, $dateTarget);\n if ($passTarget) {\n // increment pass target counter (used for reporting)\n $pass_target++;\n // If report itemization is turned on, then record the \"passed\" item and set the flag\n if ($GLOBALS['report_itemizing_temp_flag_and_id'] ?? null) {\n insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);\n $temp_track_pass = 1;\n }\n\n if (\n ($mode != \"report\") &&\n (($mode == \"reminders-all\") || (($mode != \"reminders-all\") && ($reminder_due != \"not_due\")))\n ) {\n // Place the actions into the reminder return array.\n // There are 2 reminder modes, reminders-due and reminders-all. The not_due reminders are not\n // shown in reminders-due mode but are shown in reminders-all mode. So this block is skipped\n // if due_status is 'not_due' and mode is not 'reminders-all'.\n $actionArray = resolve_action_sql($rowRule['id'], $i);\n foreach ($actionArray as $action) {\n $action_plus = $action;\n $action_plus['due_status'] = $reminder_due;\n $action_plus['pid'] = $rowPatient['pid'];\n $action_plus['rule_id'] = $rowRule['id'];\n $results = reminder_results_integrate($results, $action_plus, $mode);\n }\n }\n\n break;\n } else {\n if (($mode != \"report\") && ($dateCounter == 3)) {\n // Did not pass any of the target dates, so place the past_due actions into the reminder\n // return array when runnning in one of the reminders mode (either reminders-due mode\n // or reminders-all mode).\n $actionArray = resolve_action_sql($rowRule['id'], $i);\n foreach ($actionArray as $action) {\n $action_plus = $action;\n $action_plus['due_status'] = 'past_due';\n $action_plus['pid'] = $rowPatient['pid'];\n $action_plus['rule_id'] = $rowRule['id'];\n $results = reminder_results_integrate($results, $action_plus, $mode);\n }\n }\n }\n\n $dateCounter++;\n }\n }\n\n // If report itemization is turned on, then record the \"failed\" item if it did not pass\n if (!empty($GLOBALS['report_itemizing_temp_flag_and_id']) && !($temp_track_pass)) {\n insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);\n }\n }\n\n if ($mode == \"report\") {\n // Calculate percentage for the rule (only pertinent for report mode)\n $percentage = calculate_percentage($pass_filter, $exclude_filter, $pass_target);\n }\n\n // Collect action for title (just use the first one, if more than one)\n $actionArray = resolve_action_sql($rowRule['id'], $i);\n // HR: Need to ensure $actionArray is valued before trying to use $actionArray[0]\n if ($actionArray) {\n $action = $actionArray[0];\n if ($mode == \"report\") {\n $newRow = array('is_sub' => true, 'action_category' => $action['category'], 'action_item' => $action['item'], 'total_patients' => '', 'excluded' => '', 'pass_filter' => '', 'pass_target' => $pass_target, 'percentage' => $percentage);\n\n // If itemization is turned on, then record the itemized_test_id\n if ($GLOBALS['report_itemizing_temp_flag_and_id']) {\n $newRow = array_merge($newRow, array('itemized_test_id' => $GLOBALS['report_itemized_test_id_iterator']));\n }\n\n $results[] = $newRow;\n }\n }\n }\n }\n }\n\n // Return the data\n return $results;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function exist_database_item($patient_id, $table, string $column = null, $data_comp = '', string $data = null, $num_items_comp = null, $num_items_thres = null, $intervalType = '', $intervalValue = '', $dateFocus = '', $dateTarget = '')\n{\n // HR: used for filters and targets\n\n // Set date to current if not set\n $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');\n\n // Collect the correct column label for patient id in the table\n $patient_id_label = collect_database_label('pid', $table);\n\n // Get the interval sql query string\n // HR: left boundary is $dateFocus - interval. right boundary is $dateTarget\n $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateFocus, $dateTarget);\n\n // If just checking for existence (ie. data is empty),\n // then simply set the comparison operator to ne.\n if (empty($data)) {\n $data_comp = \"ne\";\n }\n\n // get the appropriate sql comparison operator\n $compSql = convertCompSql($data_comp);\n\n // custom issues per table can be placed here\n $customSQL = '';\n if ($table == 'immunizations') {\n $customSQL = \" AND `added_erroneously` = '0' \";\n }\n\n //adding table list for where condition\n $whereTables = '';\n if ($table == 'procedure_result') {\n $whereTables = \", procedure_order_code, \" .\n \"procedure_order, \" .\n \"procedure_report \" ;\n $customSQL = \" AND procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND \" .\n \"procedure_report.procedure_order_id = procedure_order.procedure_order_id AND \" .\n \"procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND \" .\n \"procedure_result.procedure_report_id = procedure_report.procedure_report_id \";\n }\n\n // check for items\n if (empty($column)) {\n // simple search for any table entries\n $sql = sqlStatementCdrEngine(\"SELECT * \" .\n \"FROM `\" . escape_table_name($table) . \"` \" .\n \" \" . $whereTables . \" \" .\n \"WHERE \" . add_escape_custom($patient_id_label) . \"=? \" . $customSQL, array($patient_id));\n } else {\n // mdsupport : Allow trailing '**' in the strings to perform LIKE searches\n if ((substr($data, -2) == '**') && (($compSql == \"=\") || ($compSql == \"!=\"))) {\n $compSql = ($compSql == \"!=\" ? \" NOT\" : \"\") . \" LIKE CONCAT('%',?,'%') \";\n $data = substr_replace($data, '', -2);\n } else {\n $compSql = $compSql . \"? \";\n }\n\n if ($whereTables == \"\" && strpos($table, 'form_') !== false) {\n //To handle standard forms starting with form_\n //In this case, we are assuming the date field is \"date\"\n $sql = sqlStatementCdrEngine(\n \"SELECT b.`\" . escape_sql_column_name($column, [$table]) . \"` \" .\n \"FROM forms a \" .\n \"LEFT JOIN `\" . escape_table_name($table) . \"` \" . \" b \" .\n \"ON (a.form_id=b.id AND a.formdir LIKE '\" . add_escape_custom(substr($table, 5)) . \"') \" .\n \"WHERE a.deleted != '1' \" .\n \"AND b.`\" . escape_sql_column_name($column, [$table]) . \"`\" . $compSql .\n \"AND b.\" . add_escape_custom($patient_id_label) . \"=? \" . $customSQL\n . str_replace(\"`date`\", \"b.`date`\", $dateSql),\n array($data, $patient_id)\n );\n } else {\n // This allows to enter the wild card #CURDATE# in the CDR Demographics filter criteria at the value field\n // #CURDATE# is replace by the Current date allowing a dynamic date filtering\n if ($data == '#CURDATE#') {\n $data = date(\"Y-m-d\");\n }\n\n // search for number of specific items\n $sql = sqlStatementCdrEngine(\"SELECT `\" . escape_sql_column_name($column, [$table]) . \"` \" .\n \"FROM `\" . escape_table_name($table) . \"` \" .\n \" \" . $whereTables . \" \" .\n \"WHERE `\" . escape_sql_column_name($column, [$table]) . \"`\" . $compSql .\n \"AND \" . add_escape_custom($patient_id_label) . \"=? \" . $customSQL .\n $dateSql, array($data, $patient_id));\n }\n }\n\n // See if number of returned items passes the comparison\n return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function gd($res, $color, $x, $y, $angle, $type, $datas, $width = null, $height = null)\n {\n return self::_draw(__FUNCTION__, $res, $color, $x, $y, $angle, $type, $datas, $width, $height);\n }", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function addLog($date,$ip,$ip_localisation,$email,$mdp,$connexion,$user_agent,$forward)\n\t{\n\t\t$req = \"INSERT INTO `logs_extranet`(`id`, `date`, `ip`, `ip_localisation`, `email`, `mdp`, `connexion`, `user_agent`, `forward`) VALUES ('','$date','$ip','\".addslashes($ip_localisation).\"','\".addslashes($email).\"','\".addslashes($mdp).\"','$connexion','\".addslashes($user_agent).\"','\".addslashes($forward).\"')\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription.\", $req, PdoBD::$monPdo->errorInfo());}\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct($pixie, $route, $method = \"GET\", $post = [], $get = [], $param = [], $server = [], $cookie = [], $headers = [])\n {\n parent::__construct($pixie, $route, $method, $post, $get, $param, $server, $cookie);\n $this->_headers = $headers;\n }", "smellKey": "S107", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "private static function display_message( $id, $message, $type = '', $classes = array(), $hide = true, $dismiss = false, $admin_notice = false, $echo = false ) {\n\t\t\t$result = '';\n\t\t\t$temp_classes = array();\n\t\t\tif ( strpos( $type, 'icl-admin-message' ) ) {\n\t\t\t\t$type = str_replace( 'icl-admin-message-', '', $type );\n\t\t\t}\n\t\t\tif ( $admin_notice ) {\n\t\t\t\t$temp_classes[] = 'icl-admin-message';\n\t\t\t}\n\t\t\t$temp_types = explode( ' ', $type );\n\t\t\t$temp_types = array_unique( $temp_types );\n\t\t\tforeach ( $temp_types as $temp_type ) {\n\t\t\t\tif ( $admin_notice ) {\n\t\t\t\t\t$temp_classes[] = 'icl-admin-message-' . $temp_type;\n\t\t\t\t}\n\t\t\t\t$temp_classes[] = $temp_type;\n\t\t\t}\n\n\t\t\tif ( $classes ) {\n\t\t\t\tif ( ! is_array( $classes ) ) {\n\t\t\t\t\t$classes = explode( ' ', $classes );\n\t\t\t\t}\n\t\t\t\tforeach ( $classes as $class ) {\n\t\t\t\t\t$temp_classes[] = $class;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( $hide or $dismiss ) {\n\t\t\t\t$temp_classes[] = 'otgs-is-dismissible';\n\t\t\t}\n\n\t\t\t$temp_classes = array_unique( $temp_classes );\n\n\t\t\t$class = implode( ' ', $temp_classes );\n\n\t\t\t$result .= '
    ';\n\t\t\tif ( $hide ) {\n\t\t\t\t$result .= ' ' . __( 'Hide this notice.', 'sitepress' ) . '';\n\t\t\t}\n\n\t\t\tif ( $dismiss ) {\n\t\t\t\t$result .= ' ';\n\t\t\t\t$result .= '';\n\t\t\t\t$result .= __( 'Dismiss this notice.', 'sitepress' );\n\t\t\t\t$result .= '';\n\t\t\t}\n\n\t\t\t$result .= '
    ';\n\n\t\t\tif ( ! $echo ) {\n\t\t\t\techo $result;\n\t\t\t}\n\n\t\t\treturn $result;\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = '', $list = true, $optiondates = 0,\n\t\t\t\t$optioncount = 0, $hide_empty = 1, $use_desc_for_title = 1, $children=false, $child_of=0, $categories=0,\n\t\t\t\t$recurse=0, $feed = '', $feed_image = '', $exclude = '', $hierarchical=false) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'wp_list_categories()' );\n\n\t$query = compact('optionall', 'all', 'sort_column', 'sort_order', 'file', 'list', 'optiondates', 'optioncount', 'hide_empty', 'use_desc_for_title', 'children',\n\t\t'child_of', 'categories', 'recurse', 'feed', 'feed_image', 'exclude', 'hierarchical');\n\treturn wp_list_cats($query);\n}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "function ActualizaNoticiaConImagen($id_noticia, $titulo, $contenido, $tag, $categoria, $perfil, $estado, $portada)\n{\n\tglobal $c_host,$c_user,$c_pass,$c_db;\n\t$database = new database($c_host,$c_user,$c_pass);\n\t$database->setDb($c_db);\n\t\n\t$sql = \"UPDATE tbl_noticias SET titulo= '$titulo', contenido='$contenido', tag='$tag', categoria='$categoria', perfil='$perfil', estado='$estado'\n\t, portada='$portada' WHERE id = '$id_noticia'\";\n\t$database->setquery($sql);\n\t$database->query();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function IMPARTICION_CreaImparticion($id_empresa, $codigo_imparticion, $id_curso, $fecha_inicio, $fecha_termino, $direccion, $ciudad, $cupos, $id_audiencia, $tipo_audiencia, $arreglo_post, $sesiones, $ejecutivo, $comentarios)\n{\n $connexion = new DatabasePDO();\n $sql = \"INSERT INTO tbl_inscripcion_curso (codigo_inscripcion, fecha_inicio, fecha_termino, direccion, comuna, ciudad, id_curso, id_empresa, cupos, id_audiencia, tipo_audiencia,\n lunes_d_am, lunes_h_am, lunes_d_pm, lunes_h_pm,\n martes_d_am, martes_h_am, martes_d_pm, martes_h_pm,\n miercoles_d_am, miercoles_h_am, miercoles_d_pm, miercoles_h_pm,\n jueves_d_am, jueves_h_am, jueves_d_pm, jueves_h_pm,\n viernes_d_am, viernes_h_am, viernes_d_pm, viernes_h_pm, sesiones, ejecutivo, comentarios)\n VALUES (:codigo_inscripcion, :fecha_inicio, :fecha_termino, :direccion, :comuna, :ciudad, :id_curso, :id_empresa, :cupos, :id_audiencia, :tipo_audiencia,\n :lunes_d_am, :lunes_h_am, :lunes_d_pm, :lunes_h_pm,\n :martes_d_am, :martes_h_am, :martes_d_pm, :martes_h_pm,\n :miercoles_d_am, :miercoles_h_am, :miercoles_d_pm, :miercoles_h_pm,\n :jueves_d_am, :jueves_h_am, :jueves_d_pm, :jueves_h_pm,\n :viernes_d_am, :viernes_h_am, :viernes_d_pm, :viernes_h_pm, :sesiones, :ejecutivo, :comentarios)\";\n\t$ciudadu =\"\";\n $connexion->query($sql);\n $connexion->bind(':codigo_inscripcion', $codigo_imparticion);\n $connexion->bind(':fecha_inicio', $fecha_inicio);\n $connexion->bind(':fecha_termino', $fecha_termino);\n $connexion->bind(':direccion', $direccion);\n $connexion->bind(':comuna', $ciudadu);\n $connexion->bind(':ciudad', $ciudad);\n $connexion->bind(':id_curso', $id_curso);\n $connexion->bind(':id_empresa', $id_empresa);\n $connexion->bind(':cupos', $cupos);\n $connexion->bind(':id_audiencia', $id_audiencia);\n $connexion->bind(':tipo_audiencia', $tipo_audiencia);\n $connexion->bind(':lunes_d_am', $arreglo_post[\"lunes_d_am\"]);\n $connexion->bind(':lunes_h_am', $arreglo_post[\"lunes_h_am\"]);\n $connexion->bind(':lunes_d_pm', $arreglo_post[\"lunes_d_pm\"]);\n $connexion->bind(':lunes_h_pm', $arreglo_post[\"lunes_h_pm\"]);\n $connexion->bind(':martes_d_am', $arreglo_post[\"martes_d_am\"]);\n $connexion->bind(':martes_h_am', $arreglo_post[\"martes_h_am\"]);\n $connexion->bind(':martes_d_pm', $arreglo_post[\"martes_d_pm\"]);\n $connexion->bind(':martes_h_pm', $arreglo_post[\"martes_h_pm\"]);\n $connexion->bind(':miercoles_d_am', $arreglo_post[\"miercoles_d_am\"]);\n $connexion->bind(':miercoles_h_am', $arreglo_post[\"miercoles_h_am\"]);\n $connexion->bind(':miercoles_d_pm', $arreglo_post[\"miercoles_d_pm\"]);\n $connexion->bind(':miercoles_h_pm', $arreglo_post[\"miercoles_h_pm\"]);\n $connexion->bind(':jueves_d_am', $arreglo_post[\"jueves_d_am\"]);\n $connexion->bind(':jueves_h_am', $arreglo_post[\"jueves_h_am\"]);\n $connexion->bind(':jueves_d_pm', $arreglo_post[\"jueves_d_pm\"]);\n $connexion->bind(':jueves_h_pm', $arreglo_post[\"jueves_h_pm\"]);\n $connexion->bind(':viernes_d_am', $arreglo_post[\"viernes_d_am\"]);\n $connexion->bind(':viernes_h_am', $arreglo_post[\"viernes_h_am\"]);\n $connexion->bind(':viernes_d_pm', $arreglo_post[\"viernes_d_pm\"]);\n $connexion->bind(':viernes_h_pm', $arreglo_post[\"viernes_h_pm\"]);\n $connexion->bind(':sesiones', $sesiones);\n $connexion->bind(':ejecutivo', $ejecutivo);\n $connexion->bind(':comentarios', $comentarios);\n $connexion->execute();\n}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "private function CalculateRanking($frame, $metricId, $metricVersionId, $levelId, $compareLevelId, $variableId, $hasTotals, $urbanity, $partition, $size, $direction, $hiddenValueLabels)\n\t{\n\t\t$selectedService = new SelectedMetricService();\n\t\t$metric = $selectedService->GetSelectedMetric($metricId);\n\t\t$version = $metric->GetVersion($metricVersionId);\n\t\t$level = $version->GetLevel($levelId);\n\t\t$hasDescriptions = $level->HasDescriptions;\n\n\t\t$snapshotTable = SnapshotByDatasetModel::SnapshotTable($level->Dataset->Table);\n\t\tif ($compareLevelId)\n\t\t{\n\t\t\t$levelCompare = $metric->GetLevel($compareLevelId);\n\t\t\t$mergeTable = MergeSnapshotsByDatasetModel::TableName($snapshotTable, $levelCompare->Dataset->Id);\n\t\t\t$compareVariable = MergeSnapshotsByDatasetModel::GetRequiredVariableForLevelPairObjects($level, $levelCompare, $variableId);\n\t\t\t$variableCompareId = $compareVariable->attributes['mvv_id'];\n\t\t\t$table = new SnapshotByDatasetCompareRanking(\n\t\t\t\t$mergeTable, $level->Dataset->Type,\n\t\t\t\t$variableId,\n\t\t\t\t$variableCompareId,\n\t\t\t\t$hasTotals,\n\t\t\t\t$urbanity,\n\t\t\t\t$partition,\n\t\t\t\t$hasDescriptions,\n\t\t\t\t$size,\n\t\t\t\t$direction,\n\t\t\t\t$hiddenValueLabels\n\t\t\t);\n\t\t\t$table->CheckTableExists($level->Dataset->Id, $levelCompare->Dataset->Id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$table = new SnapshotByDatasetRanking($snapshotTable, $level->Dataset->Type,\n\t\t\t\t$variableId, $hasTotals, $urbanity, $partition, $hasDescriptions, $size, $direction, $hiddenValueLabels);\n\t\t}\n\n\t\t$rows = $table->GetRows($frame);\n\n\t\t$data = $this->CreateRankingInfo($rows);\n\t\treturn $data;\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "public static function setCookie(string $name,\n\t\tstring $value = '',\n\t\tint $maxAge = 0,\n\t\tstring $path = '',\n\t\tstring $domain = '',\n\t\tbool $secure = false,\n\t\tbool $httponly = false,\n\t\tint $samesite = self::SAMESITE_NONE) {\n\t\t$header = sprintf(\n\t\t\t'Set-Cookie: %s=%s',\n\t\t\t$name,\n\t\t\trawurlencode($value)\n\t\t);\n\n\t\tif ($path !== '') {\n\t\t\t$header .= sprintf('; Path=%s', $path);\n\t\t}\n\n\t\tif ($domain !== '') {\n\t\t\t$header .= sprintf('; Domain=%s', $domain);\n\t\t}\n\n\t\tif ($maxAge > 0) {\n\t\t\t$header .= sprintf('; Max-Age=%d', $maxAge);\n\t\t}\n\n\t\tif ($secure) {\n\t\t\t$header .= '; Secure';\n\t\t}\n\n\t\tif ($httponly) {\n\t\t\t$header .= '; HttpOnly';\n\t\t}\n\n\t\tif ($samesite === self::SAMESITE_LAX) {\n\t\t\t$header .= '; SameSite=Lax';\n\t\t} elseif ($samesite === self::SAMESITE_STRICT) {\n\t\t\t$header .= '; SameSite=Strict';\n\t\t}\n\n\t\theader($header, false);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function get_links_withrating($category = -1, $before = '', $after = '
    ', $between = \" \", $show_images = true,\n\t\t\t\t\t\t\t $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) {\n\t_deprecated_function( __FUNCTION__, '2.1.0', 'get_bookmarks()' );\n\n\tget_links($category, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated);\n}", "smellKey": "S107", "smellId": null, "repo": "jpbarraca_sqli-wordpress", "language": "php"} {"function": "public function __construct(\n RepositoryInterface $repository,\n PermissionResolver $permissionResolver,\n Handler $userHandler,\n LocationHandler $locationHandler,\n PasswordHashService $passwordHashGenerator,\n PasswordValidatorInterface $passwordValidator,\n ConfigResolverInterface $configResolver,\n array $settings = []\n ) {\n $this->repository = $repository;\n $this->permissionResolver = $permissionResolver;\n $this->userHandler = $userHandler;\n $this->locationHandler = $locationHandler;\n // Union makes sure default settings are ignored if provided in argument\n $this->settings = $settings + [\n 'defaultUserPlacement' => 12,\n 'userClassID' => 4, // @deprecated, use `user_content_type_identifier` configuration instead\n 'userGroupClassID' => 3,\n 'hashType' => $passwordHashGenerator->getDefaultHashType(),\n 'siteName' => 'ibexa.co',\n ];\n $this->passwordHashService = $passwordHashGenerator;\n $this->passwordValidator = $passwordValidator;\n $this->configResolver = $configResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function makeTchart($title,$numrows,$leftentries,$rightentries, $sn, &$anstypes, &$answer, &$showanswer, &$displayformat, &$answerboxsize, $dofloat = false, $showtotal=true) {\n\t$out = '';\n\t$sa = '
    '.$title.'
    DebitCredit
    ';\n\t$maxsize = 0;\n $hasdecimals = false;\n\tfor ($i=0;$i$maxsize) {\n\t\t\t$maxsize = strlen($leftentries[$i]);\n\t\t}\n\t\tif (strpos($leftentries[$i],'.')!==false) { $hasdecimals = true;}\n\t\t$leftentries[$i] = str_replace(array('$',','),'',$leftentries[$i]) * 1;\n\t}\n\tfor ($i=0;$i$maxsize) {\n\t\t\t$maxsize = strlen($rightentries[$i]);\n\t\t}\n\t\tif (strpos($rightentries[$i],'.')!==false) { $hasdecimals = true;}\n\t\t$rightentries[$i] = str_replace(array('$',','),'',$rightentries[$i]) * 1;\n\t}\n\t$tot = 0;\n\tfor ($i=0;$i<$numrows;$i++) {\n\t\t$out .= '';\n\t\tif (isset($leftentries[$i])) {\n\t\t\t$sa .= '';\n\t\t} else {\n\t\t\t$sa .='';\n\t\t}\n\n\t\t$answerboxsize[$sn] = $maxsize;\n\t\t$displayformat[$sn] = 'alignright';\n\t\tif (isset($leftentries[$i])) {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = $leftentries[$i];\n\t\t\t$tot += $answer[$sn];\n\t\t} else {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = '';\n\t\t}\n\t\t$sn++;\n\t\t$out .= '';\n\t\tif (isset($rightentries[$i])) {\n\t\t\t$sa .='';\n\t\t} else {\n\t\t\t$sa .='';\n\t\t}\n\t\t$answerboxsize[$sn] = $maxsize;\n\t\t$displayformat[$sn] = 'alignright';\n\t\tif (isset($rightentries[$i])) {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = $rightentries[$i];\n\t\t\t$tot -= $answer[$sn];\n\t\t} else {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = '';\n\t\t}\n\t\t$sn++;\n } \n $out .= '';\n $sa .= '';\n\tif ($showtotal !== false) {\n $out .= '';\n $sa .= '';\n\t\t$out .= '';\n\t\t$answerboxsize[$sn] = $maxsize;\n\t\t$displayformat[$sn] = 'alignright';\n\t\tif ($tot>0 || ($tot==0 && $showtotal==='zeroleft')) {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = $tot;\n\t\t\t$sa .= '';\n\t\t} else {\n\t\t\t$sa .= '';\n\t\t\t$anstypes[$sn] = 'string';\n\t\t\t$answer[$sn] = '';\n\t\t}\n\t\t$sn++;\n\n\t\t$out .= '';\n\t\t$answerboxsize[$sn] = $maxsize;\n\t\t$displayformat[$sn] = 'alignright';\n\t\tif ($tot<0 || ($tot==0 && $showtotal!=='zeroleft')) {\n\t\t\t$anstypes[$sn] = 'number';\n\t\t\t$answer[$sn] = -$tot;\n\t\t\t$sa .= '';\n\t\t} else {\n\t\t\t$sa .= '';\n\t\t\t$anstypes[$sn] = 'string';\n\t\t\t$answer[$sn] = '';\n }\n $out .= '';\n $sa .= '';\n\t\t$sn++;\n\t}\n\n\t$out .= '
    '.$title.'
    DebitCredit
    [AB'.$sn.']
    ';\n\t\t\tif ($hasdecimals) {\n\t\t\t\t$sa .= number_format($leftentries[$i],2,'.',',');\n\t\t\t} else {\n\t\t\t\t$sa .= number_format($leftentries[$i]);\n\t\t\t}\n\t\t\t$sa .= '
     [AB'.$sn.']
    ';\n\t\t\tif ($hasdecimals) {\n\t\t\t\t$sa .= number_format($rightentries[$i],2,'.',',');\n\t\t\t} else {\n\t\t\t\t$sa .= number_format($rightentries[$i]);\n\t\t\t}\n\t\t\t$sa .= '
    Double line[AB'.$sn.']
    Double line';\n\t\t\tif ($hasdecimals) {\n\t\t\t\t$sa .= number_format($tot,2,'.',',');\n\t\t\t} else {\n\t\t\t\t$sa .= number_format($tot);\n\t\t\t}\n\t\t\t$sa .= '
    Double line Double line[AB'.$sn.']
    Double line';\n\t\t\tif ($hasdecimals) {\n\t\t\t\t$sa .= number_format(-$tot,2,'.',',');\n\t\t\t} else {\n\t\t\t\t$sa .= number_format(-$tot);\n\t\t\t}\n\t\t\t$sa .= '
    Double line 
    ';\n\t$sa .= '';\n\tif ($dofloat) {\n\t\t$showanswer .= $sa . '
    ';\n\t} else {\n\t\t$showanswer .= $sa.'

     

    ';\n\t}\n\treturn $out;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct(\n UserService $userService,\n LanguageService $languageService,\n LocationService $locationService,\n ContentTypeService $contentTypeService,\n SearchService $searchService,\n ObjectStateService $objectStateService,\n PermissionResolver $permissionResolver,\n PathService $pathService,\n DatasetFactory $datasetFactory,\n UserLanguagePreferenceProviderInterface $userLanguagePreferenceProvider,\n LocationResolver $locationResolver\n ) {\n $this->userService = $userService;\n $this->languageService = $languageService;\n $this->locationService = $locationService;\n $this->contentTypeService = $contentTypeService;\n $this->searchService = $searchService;\n $this->objectStateService = $objectStateService;\n $this->permissionResolver = $permissionResolver;\n $this->pathService = $pathService;\n $this->datasetFactory = $datasetFactory;\n $this->userLanguagePreferenceProvider = $userLanguagePreferenceProvider;\n $this->locationResolver = $locationResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function imagettftext($image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text): array\n{\n error_clear_last();\n $result = \\imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);\n if ($result === false) {\n throw ImageException::createFromPhpError();\n }\n return $result;\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function ajouterStage($nom,$annee,$datedeb,$datefin,$prix,$couleur,$description,$lieu,$image,$affiche,$planning,$datefininscrit)\n\t{\n\t\t$req = \"INSERT INTO `STAGE_REVISION`(`ID_STAGE`, `ANNEE_STAGE`, `NOM_STAGE`, `DATEDEB_STAGE`, `DATEFIN_STAGE`, `DESCRIPTION_STAGE`, `IMAGE_STAGE`, `PRIX_STAGE`, `FOND_STAGE`, `AFFICHE_STAGE`, `PLANNING_STAGE`, `ID_LIEU`, `DATE_FIN_INSCRIT_STAGE`) \n\t\tVALUES ('','$annee','$nom','$datedeb','$datefin','$description','$image','$prix','$couleur','$affiche','$planning','$lieu','$datefininscrit')\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour du stage dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(\n TransactionAwareAdapterInterface $cache,\n PersistenceLogger $logger,\n InMemoryCache $inMemory,\n PersistenceHandler $persistenceHandler,\n CacheIdentifierGeneratorInterface $cacheIdentifierGenerator,\n CacheIdentifierSanitizer $cacheIdentifierSanitizer,\n LocationPathConverter $locationPathConverter,\n ?CacheIndicesValidatorInterface $cacheIndicesValidator = null\n ) {\n parent::__construct($cache, $logger, $inMemory, $cacheIndicesValidator);\n\n $this->persistenceHandler = $persistenceHandler;\n $this->cacheIdentifierGenerator = $cacheIdentifierGenerator;\n $this->cacheIdentifierSanitizer = $cacheIdentifierSanitizer;\n $this->locationPathConverter = $locationPathConverter;\n\n $this->init();\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function send_to_translation_batch_mode(\n\t\t$file,\n\t\t$title,\n\t\t$cms_id,\n\t\t$url,\n\t\t$source_language,\n\t\t$target_language,\n\t\t$word_count,\n\t\t$translator_id = 0,\n\t\t$note = '',\n\t\t$uuid = null\n\t) {\n\n\t\t$batch_id = $this->get_batch_job_id();\n\n\t\tif ( ! $batch_id ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$job_data = array(\n\t\t\t'file' => $file,\n\t\t\t'word_count' => $word_count,\n\t\t\t'title' => $title,\n\t\t\t'cms_id' => $cms_id,\n\t\t\t'udid' => $uuid,\n\t\t\t'url' => $url,\n\t\t\t'translator_id' => $translator_id,\n\t\t\t'note' => $note,\n\t\t\t'source_language' => $source_language,\n\t\t\t'target_language' => $target_language,\n\t\t);\n\n\t\t$tp_job = $this->tp_client->batches()->add_job( $batch_id, $job_data );\n\n\t\treturn $tp_job ? $tp_job->get_id() : false;\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function __construct(\n TranslatableNotificationHandlerInterface $notificationHandler,\n TranslatorInterface $translator,\n LocationService $locationService,\n ContentTypeService $contentTypeService,\n ContentService $contentService,\n TrashService $trashService,\n SectionService $sectionService,\n FormFactory $formFactory,\n SubmitHandler $submitHandler,\n PermissionResolver $permissionResolver,\n Repository $repository,\n TranslationHelper $translationHelper\n ) {\n $this->notificationHandler = $notificationHandler;\n $this->translator = $translator;\n $this->locationService = $locationService;\n $this->contentService = $contentService;\n $this->contentTypeService = $contentTypeService;\n $this->trashService = $trashService;\n $this->sectionService = $sectionService;\n $this->formFactory = $formFactory;\n $this->submitHandler = $submitHandler;\n $this->permissionResolver = $permissionResolver;\n $this->repository = $repository;\n $this->translationHelper = $translationHelper;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, $meanX, $meanY, $const)\n {\n $SSres = $SScov = $SScor = $SStot = $SSsex = 0.0;\n foreach ($this->xValues as $xKey => $xValue) {\n $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);\n\n $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY);\n if ($const) {\n $SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY);\n } else {\n $SStot += $this->yValues[$xKey] * $this->yValues[$xKey];\n }\n $SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY);\n if ($const) {\n $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX);\n } else {\n $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey];\n }\n }\n\n $this->SSResiduals = $SSres;\n $this->DFResiduals = $this->valueCount - 1 - $const;\n\n if ($this->DFResiduals == 0.0) {\n $this->stdevOfResiduals = 0.0;\n } else {\n $this->stdevOfResiduals = sqrt($SSres / $this->DFResiduals);\n }\n if (($SStot == 0.0) || ($SSres == $SStot)) {\n $this->goodnessOfFit = 1;\n } else {\n $this->goodnessOfFit = 1 - ($SSres / $SStot);\n }\n\n $this->SSRegression = $this->goodnessOfFit * $SStot;\n $this->covariance = $SScov / $this->valueCount;\n $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - pow($sumX, 2)) * ($this->valueCount * $sumY2 - pow($sumY, 2)));\n $this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex);\n $this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2));\n if ($this->SSResiduals != 0.0) {\n if ($this->DFResiduals == 0.0) {\n $this->f = 0.0;\n } else {\n $this->f = $this->SSRegression / ($this->SSResiduals / $this->DFResiduals);\n }\n } else {\n if ($this->DFResiduals == 0.0) {\n $this->f = 0.0;\n } else {\n $this->f = $this->SSRegression / $this->DFResiduals;\n }\n }\n }", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function imagepstext ($image, $text, $font_index, $size, $foreground, $background, $x, $y, $space = null, $tightness = null, $angle = null, $antialias_steps = null) {}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function add_service($device, $type, $desc, $ip = '', $param = '', $ignore = 0, $disabled = 0, $template_id = '', $name = '')\n{\n if (! is_array($device)) {\n $device = device_by_id_cache($device);\n }\n\n if (empty($ip)) {\n $ip = Device::pollerTarget($device['hostname']);\n }\n\n $insert = ['device_id' => $device['device_id'], 'service_ip' => $ip, 'service_type' => $type, 'service_changed' => ['UNIX_TIMESTAMP(NOW())'], 'service_desc' => $desc, 'service_param' => $param, 'service_ignore' => $ignore, 'service_status' => 3, 'service_message' => 'Service not yet checked', 'service_ds' => '{}', 'service_disabled' => $disabled, 'service_template_id' => $template_id, 'service_name' => $name];\n\n return dbInsert($insert, 'services');\n}", "smellKey": "S107", "smellId": null, "repo": "Jellyfrog_librenms", "language": "php"} {"function": "function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept, $encounter = 0, $copay = 0, $patcopay = 0)\n{\n global $var_index;\n $var_index++;\n $balance = $charges - $ptpaid - $inspaid;\n $balance = (round($duept, 2) != 0) ? 0 : $balance;//if balance is due from patient, then insurance balance is displayed as zero\n $encounter = $encounter ? $encounter : '';\n echo \" \\n\";\n echo \" \" . text(oeFormatShortDate($date)) . \"\\n\";\n echo \" \" . text($encounter) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($charges)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($inspaid * -1)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($ptpaid * -1)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($patcopay)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($copay)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks($balance)) . \"\\n\";\n echo \" \" . text(FormatMoney::getBucks(round($duept, 2) * 1)) . \"\\n\";\n echo \" \\n\";\n echo \" \\n\";\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function flattenitems($items,&$addto,&$folderholder,&$hiddenholder,&$greyitems,$folder,$avail=true,$ishidden=false,$curblockgrey=0) {\n global $studentinfo;\n $now = time();\n\tforeach ($items as $k=>$item) {\n\t\tif (is_array($item)) {\n\t\t\tif (!isset($item['avail'])) { //backwards compat\n\t\t\t\t$item['avail'] = 1;\n\t\t\t}\n\t\t\t$thisavail = ($avail && ($item['avail']==2 || ($item['avail']==1 && ($item['SH'][0]=='S' || ($item['startdate']<$now && $item['enddate']>$now)))));\n\t\t\t$thisblockgrey = 0;\n\t\t\tif (strlen($item['SH'])>2) {\n\t\t\t\t$thisblockgrey = intval($item['SH'][2]);\n\t\t\t} else {\n\t\t\t\t$thisblockgrey = 0;\n\t\t\t}\n\t\t\t//set as hidden if explicitly hidden or opens in future. We won't count past folders that aren't showing as hidden\n\t\t\t// to allow students with latepasses to access old assignments even if the folder is gone.\n $thisishidden = ($ishidden || \n $item['avail']==0 || \n ($item['avail']==1 && $item['SH'][0]=='H' && $item['startdate']>$now) ||\n (!empty($item['grouplimit']) && isset($studentinfo['section']) &&\n substr($item['grouplimit'][0],2) != $studentinfo['section'])\n );\n if (!empty($item['items'])) {\n\t\t\t flattenitems($item['items'],$addto,$folderholder,$hiddenholder,$greyitems,$folder.'-'.($k+1),$thisavail,$thisishidden,$thisblockgrey);\n }\n\t\t} else {\n\t\t\t$addto[] = $item;\n\t\t\t$folderholder[$item] = $folder;\n\t\t\tif ($ishidden) {\n\t\t\t\t$hiddenholder[$item] = true;\n $greyitems[$item] = 0;\n\t\t\t} else {\n\t\t\t\t$greyitems[$item] = $curblockgrey;\n\t\t\t}\n\t\t}\n\t}\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct(\n Environment $twig,\n TranslatorInterface $translator,\n URLService $urlService,\n FormFactory $formFactory,\n SubmitHandler $submitHandler,\n TranslatableNotificationHandlerInterface $notificationHandler,\n RequestStack $request,\n PermissionResolver $permissionResolver\n ) {\n parent::__construct($twig, $translator);\n\n $this->urlService = $urlService;\n $this->formFactory = $formFactory;\n $this->submitHandler = $submitHandler;\n $this->notificationHandler = $notificationHandler;\n $this->requestStack = $request;\n $this->permissionResolver = $permissionResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\tif ($js) {\n\t\t\t$this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);\n\t\t\t$s = '';\n\t\t\tforeach ($values as $value) {\n\t\t\t\t$s .= \"'\".addslashes($value).\"',\";\n\t\t\t}\n\t\t\t$this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1).\"]);\\n\";\n\t\t\treturn;\n\t\t}\n\t\t// get default style\n\t\t$prop = array_merge($this->getFormDefaultProp(), $prop);\n\t\t$prop['Combo'] = true;\n\t\t// get annotation data\n\t\t$popt = $this->getAnnotOptFromJSProp($prop);\n\t\t// set additional default options\n\t\t$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];\n\t\t$fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);\n\t\t$popt['da'] = $fontstyle;\n\t\t$popt['ap'] = array();\n\t\t$popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';\n\t\t// merge options\n\t\t$opt = array_merge($popt, $opt);\n\t\t// set remaining annotation data\n\t\t$opt['Subtype'] = 'Widget';\n\t\t$opt['ft'] = 'Ch';\n\t\t$opt['t'] = $name;\n\t\t$opt['opt'] = $values;\n\t\t$this->Annotation($x, $y, $w, $h, $name, $opt, 0);\n\t\tif ($this->rtl) {\n\t\t\t$this->x -= $w;\n\t\t} else {\n\t\t\t$this->x += $w;\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function inscriptionStageNouvelle($num,$nom,$prenom,$jour_naissance,$mois_naissance,$annee_naissance,$date,$ip,$user_agent,$origine,$id_atelier,$sexe,$etab,$classe,$filiere,$tel_enfant,$email_enfant,$tel_parent,$email_parent,$adresse,$cp,$ville,$association)\n\t{\n\t\t$req = \"INSERT INTO `ELEVE_STAGE`(`NOM_ELEVE_STAGE`, `PRENOM_ELEVE_STAGE`, `SEXE_ELEVE_STAGE`, `ETABLISSEMENT_ELEVE_STAGE`, `CLASSE_ELEVE_STAGE`, `ASSOCIATION_ELEVE_STAGE`, `TELEPHONE_PARENTS_ELEVE_STAGE`, `TELEPHONE_ELEVE_ELEVE_STAGE`, `EMAIL_PARENTS_ELEVE_STAGE`, `EMAIL_ENFANT_ELEVE_STAGE`, `ADRESSE_ELEVE_STAGE`, `CP_ELEVE_STAGE`, `VILLE_ELEVE_STAGE`, `DDN_ELEVE_STAGE`, `FILIERE_ELEVE_STAGE`) VALUES ('\".addslashes($nom).\"','\".addslashes($prenom).\"','$sexe','$etab','$classe','\".addslashes($association).\"','$tel_parent','$tel_enfant','\".addslashes($email_parent).\"','\".addslashes($email_enfant).\"','\".addslashes($adresse).\"','$cp','\".addslashes($ville).\"','$annee_naissance-$mois_naissance-$jour_naissance','$filiere');\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription.\", $req, PdoBD::$monPdo->errorInfo());}\n\t\t\n\t\t\n\t\t$req = \"INSERT INTO `INSCRIPTIONS_STAGE`(`ID_STAGE`,`ID_ELEVE_STAGE`,`ID_ATELIERS`,`VALIDE`,`DATE_INSCRIPTIONS`,`IP_INSCRIPTIONS`,`USER_AGENT_INSCRIPTIONS`, `ORIGINE_INSCRIPTIONS`) VALUES ('$num',(SELECT MAX(`ID_ELEVE_STAGE`) AS max_id FROM `ELEVE_STAGE`),'$id_atelier',0,'$date','$ip','\".addslashes($user_agent).\"','\".addslashes($origine).\"'); \";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'inscription.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function generateProviderPreview(ISimpleFolder $previewFolder, File $file, int $width, int $height, bool $crop, bool $max, string $mimeType, string $prefix) {\n\t\t$previewProviders = $this->previewManager->getProviders();\n\t\tforeach ($previewProviders as $supportedMimeType => $providers) {\n\t\t\t// Filter out providers that does not support this mime\n\t\t\tif (!preg_match($supportedMimeType, $mimeType)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tforeach ($providers as $providerClosure) {\n\t\t\t\t$provider = $this->helper->getProvider($providerClosure);\n\t\t\t\tif (!($provider instanceof IProviderV2)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!$provider->isAvailable($file)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');\n\t\t\t\t$sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);\n\t\t\t\ttry {\n\t\t\t\t\t$preview = $this->helper->getThumbnail($provider, $file, $width, $height);\n\t\t\t\t} finally {\n\t\t\t\t\tself::unguardWithSemaphore($sem);\n\t\t\t\t}\n\n\t\t\t\tif (!($preview instanceof IImage)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$path = $this->generatePath($preview->width(), $preview->height(), $crop, $max, $preview->dataMimeType(), $prefix);\n\t\t\t\ttry {\n\t\t\t\t\t$file = $previewFolder->newFile($path);\n\t\t\t\t\tif ($preview instanceof IStreamImage) {\n\t\t\t\t\t\t$file->putContent($preview->resource());\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$file->putContent($preview->data());\n\t\t\t\t\t}\n\t\t\t\t} catch (NotPermittedException $e) {\n\t\t\t\t\tthrow new NotFoundException();\n\t\t\t\t}\n\n\t\t\t\treturn $file;\n\t\t\t}\n\t\t}\n\n\t\tthrow new NotFoundException('No provider successfully handled the preview generation');\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function CreateMultiRequestFile($type, $datasetId, $clippingItemId, $clippingCircle, $urbanity, $partition, $fromDraft = false, $extraColumns = array())\n\t{\n\t\tself::ValidateType($type);\n\t\tself::ValidateClippingItem($clippingItemId);\n\n\t\t// Si est\u00e1 cacheado, sale\n\t\tif(self::IsCached($type, $datasetId, $clippingItemId, $clippingCircle, $urbanity, $partition, $fromDraft))\n\t\t\treturn array('done' => true);\n\n\t\t// Crea la estructura para la creaci\u00f3n en varios pasos del archivo a descargar\n\t\t$this->PrepareNewModel($type, $datasetId, $clippingItemId, $clippingCircle, $urbanity, $partition, $fromDraft, $extraColumns);\n\t\t$this->PrepareNewState($type, $datasetId, $clippingItemId, $clippingCircle, $urbanity, $partition, $fromDraft, $extraColumns);\n\t\treturn $this->GenerateNextFilePart();\n\t}", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "public function inserer_aff_debours($id_deb, $id_cli, $id_mod_lic, $id_march, $id_mod_trans, $montant, $montant_under_value, $usd, $tva, $unite){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['id_deb'] = $id_deb;\n\t\t\t$entree['id_cli'] = $id_cli;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;\n\t\t\t$entree['id_march'] = $id_march;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;\n\t\t\t$entree['montant'] = $montant;\n\t\t\t$entree['montant_under_value'] = $montant_under_value;\n\t\t\t$entree['unite'] = $unite;\n\n\t\t\tif ($entree['montant'] == '') {\n\t\t\t\t$entree['montant'] = NULL;\n\t\t\t}\n\n\t\t\tif ($entree['unite'] == '') {\n\t\t\t\t$entree['unite'] = NULL;\n\t\t\t}\n\n\t\t\t$entree['usd'] = $usd;\n\t\t\t$entree['tva'] = $tva;\n\n\t\t\t$requete = $connexion-> prepare(\"INSERT INTO affectation_debours_client_modele_licence(id_deb, id_cli, id_mod_lic, id_march, id_mod_trans, montant, usd, tva, unite) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)\");\n\t\t\t$requete-> execute(array($entree['id_deb'], $entree['id_cli'], $entree['id_mod_lic'], $entree['id_march'], $entree['id_mod_trans'], $entree['montant'], $entree['usd'], $entree['tva'], $entree['unite']));\n\n\t\t\tif ($entree['montant_under_value']>0) {// Under value\n\n\t\t\t\t$requete = $connexion-> prepare(\"INSERT INTO debours_under_value(id_deb, id_cli, id_mod_lic, id_march, id_mod_trans, montant, usd, tva) VALUES(?, ?, ?, ?, ?, ?, ?, ?)\");\n\t\t\t\t$requete-> execute(array($entree['id_deb'], $entree['id_cli'], $entree['id_mod_lic'], $entree['id_march'], $entree['id_mod_trans'], $entree['montant_under_value'], $entree['usd'], $entree['tva']));\n\n\t\t\t}\n\n\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "public function modifReglement($num,$nom,$date,$type,$cheque,$banque,$montant,$commentaire)\n\t{\t\t\t\n\t\t$req = \"UPDATE `reglements` SET `ID_TYPEREGLEMENT`=$type,`NUMCHEQUE`='$cheque',`BANQUE`='$banque',`DATE_REGLEMENT`='$date',`MONTANT`='$montant',`COMMENTAIRES`='$commentaire',`NOMREGLEMENT`='$nom' WHERE `ID`=$num;\";\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\t\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion de l'\u00e9l\u00e8ve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(string $appName,\n\t\tIRequest $request,\n\t\tIRootFolder $rootFolder,\n\t\tstring $userId,\n\t\tDirectMapper $mapper,\n\t\tISecureRandom $random,\n\t\tITimeFactory $timeFactory,\n\t\tIURLGenerator $urlGenerator,\n\t\tIEventDispatcher $eventDispatcher) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->rootFolder = $rootFolder;\n\t\t$this->userId = $userId;\n\t\t$this->mapper = $mapper;\n\t\t$this->random = $random;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->eventDispatcher = $eventDispatcher;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB)\n {\n $record = 0x005d; // Record identifier\n $length = 0x003c; // Bytes to follow\n\n $cObj = 0x0001; // Count of objects in file (set to 1)\n $OT = 0x0008; // Object type. 8 = Picture\n $id = 0x0001; // Object ID\n $grbit = 0x0614; // Option flags\n\n $cbMacro = 0x0000; // Length of FMLA structure\n $Reserved1 = 0x0000; // Reserved\n $Reserved2 = 0x0000; // Reserved\n\n $icvBack = 0x09; // Background colour\n $icvFore = 0x09; // Foreground colour\n $fls = 0x00; // Fill pattern\n $fAuto = 0x00; // Automatic fill\n $icv = 0x08; // Line colour\n $lns = 0xff; // Line style\n $lnw = 0x01; // Line weight\n $fAutoB = 0x00; // Automatic border\n $frs = 0x0000; // Frame style\n $cf = 0x0009; // Image format, 9 = bitmap\n $Reserved3 = 0x0000; // Reserved\n $cbPictFmla = 0x0000; // Length of FMLA structure\n $Reserved4 = 0x0000; // Reserved\n $grbit2 = 0x0001; // Option flags\n $Reserved5 = 0x0000; // Reserved\n\n\n $header = pack(\"vv\", $record, $length);\n $data = pack(\"V\", $cObj);\n $data .= pack(\"v\", $OT);\n $data .= pack(\"v\", $id);\n $data .= pack(\"v\", $grbit);\n $data .= pack(\"v\", $colL);\n $data .= pack(\"v\", $dxL);\n $data .= pack(\"v\", $rwT);\n $data .= pack(\"v\", $dyT);\n $data .= pack(\"v\", $colR);\n $data .= pack(\"v\", $dxR);\n $data .= pack(\"v\", $rwB);\n $data .= pack(\"v\", $dyB);\n $data .= pack(\"v\", $cbMacro);\n $data .= pack(\"V\", $Reserved1);\n $data .= pack(\"v\", $Reserved2);\n $data .= pack(\"C\", $icvBack);\n $data .= pack(\"C\", $icvFore);\n $data .= pack(\"C\", $fls);\n $data .= pack(\"C\", $fAuto);\n $data .= pack(\"C\", $icv);\n $data .= pack(\"C\", $lns);\n $data .= pack(\"C\", $lnw);\n $data .= pack(\"C\", $fAutoB);\n $data .= pack(\"v\", $frs);\n $data .= pack(\"V\", $cf);\n $data .= pack(\"v\", $Reserved3);\n $data .= pack(\"v\", $cbPictFmla);\n $data .= pack(\"v\", $Reserved4);\n $data .= pack(\"v\", $grbit2);\n $data .= pack(\"V\", $Reserved5);\n\n $this->append($header . $data);\n }", "smellKey": "S107", "smellId": null, "repo": "sattusp786_diyush", "language": "php"} {"function": "function receiptDetailLine(\n $code_type,\n $code,\n $description,\n $quantity,\n $charge,\n &$aTotals = '',\n $lineid = '',\n $billtime = '',\n $postdate = '',\n $chargecat = ''\n) {\n global $details, $TAXES_AFTER_ADJUSTMENT;\n\n // Use $lineid to match up (and delete) entries in $aInvTaxes with the line.\n $aTaxes = array();\n $totlinetax = pull_tax($lineid, $aTaxes);\n // $aTaxes now contains the total of each tax type for this line item, and those matched\n // amounts are removed from $aInvTaxes.\n\n $adjust = 0;\n $memo = '';\n $isadjust = false;\n\n // If an adjustment, do appropriate interpretation.\n if ($code_type === '') {\n $isadjust = true;\n $adjust = 0 - $charge;\n $charge = 0;\n list($payer, $code_type, $code) = explode('|', $code);\n $memo = $description;\n $description = $GLOBALS['simplified_demographics'] ? '' : \"$payer \";\n $description .= $code ? xl('Item Adjustment') : xl('Invoice Adjustment');\n $quantity = '';\n } else {\n // Total and clear adjustments in $aAdjusts matching this line item.\n $adjust += pull_adjustment($code_type, $code, $billtime, $memo);\n }\n\n $charge = formatMoneyNumber($charge);\n $total = formatMoneyNumber($charge + $totlinetax - $adjust);\n if (empty($quantity)) {\n $quantity = 1;\n }\n $price = formatMoneyNumber($charge / $quantity, 2);\n $tmp = formatMoneyNumber($price);\n if ($price == $tmp) {\n $price = $tmp;\n }\n if (is_array($aTotals)) {\n $aTotals[0] += $quantity;\n $aTotals[1] += $price;\n $aTotals[2] += $charge;\n $aTotals[3] += $adjust;\n $aTotals[4] += $total;\n // Accumulate columns 5 and beyond for taxes.\n $i = 5;\n foreach ($aTaxes as $tax) {\n $aTotals[$i++] += $tax;\n }\n }\n\n if (!$details) {\n return;\n }\n if (empty($postdate) || substr($postdate, 0, 4) == '0000') {\n $postdate = $billtime;\n }\n echo \" \\n\";\n echo \" \" .\n text(oeFormatShortDate($postdate)) . \"\\n\";\n echo \" \" . text($code) . \"\\n\";\n echo \" \" . text($description) . \"\\n\";\n echo \" \" . ($isadjust ? '' : $quantity) . \"\\n\";\n echo \" \" . text(oeFormatMoney($price, false, true)) . \"\\n\";\n\n if (!empty($GLOBALS['gbl_checkout_charges'])) {\n echo \" \" . text(oeFormatMoney($charge, false, true)) . \"\\n\";\n }\n\n if (!$TAXES_AFTER_ADJUSTMENT) {\n // Write tax amounts.\n foreach ($aTaxes as $tax) {\n echo \" \" . text(oeFormatMoney($tax, false, true)) . \"\\n\";\n }\n }\n\n // Charge Category\n if (!empty($GLOBALS['gbl_charge_categories'])) {\n echo \" \" . text($chargecat) . \"\\n\";\n }\n\n // Adjustment and its description.\n if (!empty($GLOBALS['gbl_checkout_line_adjustments'])) {\n echo \" \" . text($memo) . \"\\n\";\n echo \" \" . text(oeFormatMoney($adjust, false, true)) . \"\\n\";\n }\n\n if ($TAXES_AFTER_ADJUSTMENT) {\n // Write tax amounts.\n foreach ($aTaxes as $tax) {\n echo \" \" . text(oeFormatMoney($tax, false, true)) . \"\\n\";\n }\n }\n\n echo \" \" . text(oeFormatMoney($total)) . \"\\n\";\n echo \" \\n\";\n}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function getJsonForChartingDataSwitch(\n string $type,\n string $pName,\n array $serverVars,\n array $statusVars,\n array $ret,\n mixed $sysinfo,\n mixed $cpuload,\n mixed $memory,\n ): array {\n /**\n * We only collect the status and server variables here to read them all in one query,\n * and only afterwards assign them. Also do some allow list filtering on the names\n */\n switch ($type) {\n case 'servervar':\n if (preg_match('/[^a-zA-Z_]+/', $pName) !== 1) {\n $serverVars[] = $pName;\n }\n\n break;\n\n case 'statusvar':\n if (preg_match('/[^a-zA-Z_]+/', $pName) !== 1) {\n $statusVars[] = $pName;\n }\n\n break;\n\n case 'proc':\n $result = $this->dbi->query('SHOW PROCESSLIST');\n $ret['value'] = $result->numRows();\n break;\n\n case 'cpu':\n if (! $sysinfo) {\n $sysinfo = SysInfo::get();\n }\n\n if (! $cpuload) {\n $cpuload = $sysinfo->loadavg();\n }\n\n if (SysInfo::getOs() === 'Linux') {\n $ret['idle'] = $cpuload['idle'];\n $ret['busy'] = $cpuload['busy'];\n } else {\n $ret['value'] = $cpuload['loadavg'];\n }\n\n break;\n\n case 'memory':\n if (! $sysinfo) {\n $sysinfo = SysInfo::get();\n }\n\n if (! $memory) {\n $memory = $sysinfo->memory();\n }\n\n $ret['value'] = $memory[$pName] ?? 0;\n break;\n }\n\n return [$serverVars, $statusVars, $ret];\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public static function getNbSuggestions($id_bibli=0, $statut='-1', $num_categ='-1', $mask='', $aq=0, $location=0, $user_input='',$source=0, $user_id=array(), $user_statut=array(), $date_inf='', $date_sup='') {\n\t\tif($source) \n\t\t\t$filtre_src = \" sugg_source = '\".$source.\"' \";\n\t\telse $filtre_src=\" 1 \";\n\t\t\n\t\tif (!$statut) $statut='-1';\n\t\tif ($statut == '-1') { \n\t\t\t$filtre1 = '1';\n\t\t} elseif ($statut == $mask) {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = '\".$mask.\"' \";\n\t\t} else {\n\t\t\t$filtre1 = \"(statut & '\".$mask.\"') = 0 and (statut & '\".$statut.\"') = '\".$statut.\"' \";\n\t\t}\n\t\t\n\t\tif ($num_categ == '-1') {\n\t\t\t$filtre2 = '1';\n\t\t} else {\n\t\t\t$filtre2 = \"num_categ = '\".$num_categ.\"' \";\n\t\t}\n\t\t\t\n\t\tif (!$id_bibli) $filtre3 = '1';\n\t\t\telse $filtre3.= \"num_entite = '\".$id_bibli.\"' \";\n\t\tif ($location == 0) {\n\t\t\t$filtre4 = '1';\n\t\t} else {\n\t\t\t$filtre4 = \"sugg_location = '\".$location.\"' \";\n\t\t}\n\t\t\n\t\tif (!trim($date_inf) && !trim($date_sup)) {\n\t\t\t$filtre5 = '1';\n\t\t} else {\n\t\t\tif (trim($date_inf) && trim($date_sup)) {\n\t\t\t\t$filtre5 = \"(date_creation BETWEEN '\".$date_inf.\"' AND '\".$date_sup.\"')\";\n\t\t\t} elseif (trim($date_inf)) {\n\t\t\t\t$filtre5 = \"date_creation >= '\".$date_inf.\"'\";\n\t\t\t} else {\n\t\t\t\t$filtre5 = \"date_creation <= '\".$date_sup.\"'\";\n\t\t\t}\n\t\t}\n\t\t\n\t\t$filtre_empr='';\n\t\t$tab_empr=array();\n\t\t$filtre_user='';\n\t\t$tab_user=array();\n\t\t$filtre_visitor='';\n\t\t$tab_visitor=array();\n\t\tif (is_array($user_id) && count($user_id) && is_array($user_statut) && count($user_statut)) {\n\t\t\tforeach ($user_id as $k=>$id) {\n\t\t\t\tif ($user_statut[$k] == \"0\") {\n\t\t\t\t\t$tab_user[] = $id;\n\t\t\t\t}\n\t\t\t\tif ($user_statut[$k] == \"1\") {\n\t\t\t\t\t$tab_empr[] = $id;\n\t\t\t\t}\n\t\t\t\tif ($user_statut[$k] == \"2\") {\n\t\t\t\t\t$tab_visitor[] = $id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (is_array($tab_empr) && count($tab_empr)) {\n\t\t\t$filtre_empr = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_empr).\"') and type_origine='1' \";\n\t\t}\n\t\tif (is_array($tab_user) && count($tab_user)) {\t\t\n\t\t\t$filtre_user = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_user).\"') and type_origine='0' \";\n\t\t}\n\t\tif (is_array($tab_visitor) && count($tab_visitor)) {\t\t\n\t\t\t$filtre_visitor = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_visitor).\"') and type_origine='2' \";\n\t\t}\n\t\tif ($filtre_empr!=\"\" || $filtre_user!=\"\" || $filtre_visitor!=\"\") {\n\t\t\t$table_origine = \", suggestions_origine \";\n\t\t\t$join_origine = \" id_suggestion=num_suggestion \";\n\t\t\t\n\t\t\t$deja_filtre = false;\n\t\t\t$clause_origine = \" and (\";\n\t\t\tif ($filtre_empr) {\n\t\t\t\t$clause_origine.=\" (\".$filtre_empr.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\tif ($filtre_user) {\n\t\t\t\tif ($deja_filtre) {\n\t\t\t\t\t$clause_origine.=\" or \";\n\t\t\t\t}\n\t\t\t\t$clause_origine.=\" (\".$filtre_user.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\tif ($filtre_visitor) {\n\t\t\t\tif ($deja_filtre) {\n\t\t\t\t\t$clause_origine.=\" or \";\n\t\t\t\t}\n\t\t\t\t$clause_origine.=\" (\".$filtre_visitor.\") \";\n\t\t\t\t$deja_filtre = true;\n\t\t\t}\n\t\t\t$clause_origine.= \" ) and \";\n\t\t} else {\n\t\t\t$table_origine = \"\";\n\t\t\t$join_origine = \"\";\n\t\t\t$clause_origine = \"\";\n\t\t}\n\t\t\n\t\tif (!$aq) {\n\t\t\t$q = \"select count(1) from suggestions $table_origine\";\n\t\t\t$q.= \"where $join_origine $clause_origine \".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4 .\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t} else {\n\t\t\t\n\t\t\t$isbn = '';\n\t\t\t$t_codes = array();\n\t\t\t\n\t\t\tif ($user_input!=='') {\n\t\t\t\tif (isEAN($user_input)) {\n\t\t\t\t\t// la saisie est un EAN -> on tente de le formater en ISBN\n\t\t\t\t\t$isbn = EANtoISBN($user_input);\n\t\t\t\t\tif($isbn) {\n\t\t\t\t\t\t$t_codes[] = $isbn;\n\t\t\t\t\t\t$t_codes[] = formatISBN($isbn,10);\n\t\t\t\t\t}\n\t\t\t\t} elseif (isISBN($user_input)) {\n\t\t\t\t\t// si la saisie est un ISBN\n\t\t\t\t\t$isbn = formatISBN($user_input);\n\t\t\t\t\tif($isbn) { \n\t\t\t\t\t\t$t_codes[] = $isbn ;\n\t\t\t\t\t\t$t_codes[] = formatISBN($isbn,13);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (count($t_codes)) {\n\t\t\t\t\n\t\t\t\t$q = \"select count(1) from suggestions $table_origine\";\n\t\t\t\t$q.= \"where $join_origine $clause_origine (\".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4.\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t\t\t$q.= \") \"; \n\t\t\t\t$q.= \"and ('0' \";\n\t\t\t\tforeach ($t_codes as $v) {\n\t\t\t\t\t$q.= \"or code like '%\".$v.\"%' \";\n\t\t\t\t}\n\t\t\t\t$q.=\") \";\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t$members = $aq->get_query_members(\"suggestions\",\"concat(titre,' ',editeur,' ',auteur,' ',commentaires)\",\"index_suggestion\", \"id_suggestion\");\n\t\t\t\t\t\t\t\t\n\t\t\t\t$q = $q = \"select count(1) from suggestions $table_origine \";\n\t\t\t\t$q.= \"where $join_origine $clause_origine (\".$filtre1.\" and \".$filtre2.\" and \".$filtre3.\" and \".$filtre4.\" and \".$filtre5 .\" and \".$filtre_src;\n\t\t\t\t$q.= \") \"; \n\t\t\t\t$q.= \"and (\".$members[\"where\"].\" )\";\n\t\t\t}\n\t\t}\n\n\t\t$r = pmb_mysql_query($q);\n\t\treturn pmb_mysql_result($r, 0, 0); \n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "public function buildOpenInvoiceLineItem(\n $description,\n $itemAmount,\n $itemVatAmount,\n $itemVatPercentage,\n $numberOfItems,\n $vatCategory,\n $itemId,\n $productUrl = null,\n $imageUrl = null,\n $amountIncludingTax = null,\n $itemCategory = null\n ): array {\n $lineItem = array();\n // item id is optional\n if (!empty($itemId)) {\n $lineItem['id'] = $itemId;\n }\n\n $lineItem['description'] = $description;\n $lineItem['amountExcludingTax'] = $itemAmount;\n $lineItem['taxAmount'] = $itemVatAmount;\n $lineItem['taxPercentage'] = $itemVatPercentage;\n $lineItem['quantity'] = $numberOfItems;\n\n if (isset($productUrl)) {\n $lineItem['productUrl'] = $productUrl;\n }\n\n if (isset($imageUrl)) {\n $lineItem['imageUrl'] = $imageUrl;\n }\n\n if (isset($amountIncludingTax)) {\n $lineItem['amountIncludingTax'] = $amountIncludingTax;\n }\n\n if (isset($itemCategory)) {\n $lineItem['itemCategory'] = $itemCategory;\n }\n\n return $lineItem;\n }", "smellKey": "S107", "smellId": null, "repo": "Adyen_adyen-php-api-library", "language": "php"} {"function": "public function __construct(\n\t\t?string $inFlagSegunda,\n\t\t?string $inHoraIniAulaSegunda,\n\t\t?string $inHoraFimAulaSegunda,\n\t\t?string $inFlagTerca,\n\t\t?string $inHoraIniAulaTerca,\n\t\t?string $inHoraFimAulaTerca,\n\t\t?string $inFlagQuarta,\n\t\t?string $inHoraIniAulaQuarta,\n\t\t?string $inHoraFimAulaQuarta,\n\t\t?string $inFlagQuinta,\n\t\t?string $inHoraIniAulaQuinta,\n\t\t?string $inHoraFimAulaQuinta,\n\t\t?string $inFlagSexta,\n\t\t?string $inHoraIniAulaSexta,\n\t\t?string $inHoraFimAulaSexta,\n\t\t?string $inFlagSabado,\n\t\t?string $inHoraIniAulaSabado,\n\t\t?string $inHoraFimAulaSabado\n\t) {\n\t\t$this->inFlagSegunda = $inFlagSegunda;\n\t\t$this->inHoraIniAulaSegunda = $inHoraIniAulaSegunda;\n\t\t$this->inHoraFimAulaSegunda = $inHoraFimAulaSegunda;\n\t\t$this->inFlagTerca = $inFlagTerca;\n\t\t$this->inHoraIniAulaTerca = $inHoraIniAulaTerca;\n\t\t$this->inHoraFimAulaTerca = $inHoraFimAulaTerca;\n\t\t$this->inFlagQuarta = $inFlagQuarta;\n\t\t$this->inHoraIniAulaQuarta = $inHoraIniAulaQuarta;\n\t\t$this->inHoraFimAulaQuarta = $inHoraFimAulaQuarta;\n\t\t$this->inFlagQuinta = $inFlagQuinta;\n\t\t$this->inHoraIniAulaQuinta = $inHoraIniAulaQuinta;\n\t\t$this->inHoraFimAulaQuinta = $inHoraFimAulaQuinta;\n\t\t$this->inFlagSexta = $inFlagSexta;\n\t\t$this->inHoraIniAulaSexta = $inHoraIniAulaSexta;\n\t\t$this->inHoraFimAulaSexta = $inHoraFimAulaSexta;\n\t\t$this->inFlagSabado = $inFlagSabado;\n\t\t$this->inHoraIniAulaSabado = $inHoraIniAulaSabado;\n\t\t$this->inHoraFimAulaSabado = $inHoraFimAulaSabado;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function modifInscriptionEleve2($num,$annee,$etab,$classe,$prof_principal,$filiere,$lv1,$lv2,$date_inscription,$commentaires)\n\t{\n\t\t$req = \"UPDATE `\".PdoBD::$villeExtranet.\"_inscrit` SET `ID`=:etab,`ID_FILIERES`=:filiere,`ID_LV1`=:lv1,`ID_LV2`=:lv2,`ID_CLASSE`=:classe,`DATE_INSCRIPTION`=:date_inscription,`NOM_DU_PROF_PRINCIPAL`=:prof_principal,`COMMENTAIRESANNEE`=:commentaires WHERE `ID_ELEVE`=:num AND `ANNEE`=:annee\";\n\t\t$params = array(\n\t\t\t'etab' => $etab,\n\t\t\t'filiere' => $filiere,\n\t\t\t'lv1' => $lv1,\n\t\t\t'lv2' => $lv2,\n\t\t\t'classe' => $classe,\n\t\t\t'date_inscription' => $date_inscription,\n\t\t\t'prof_principal' => $prof_principal,\n\t\t\t'commentaires' => $commentaires,\n\t\t\t'num' => $num,\n\t\t\t'annee' => $annee\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la mise \u00e0 jour de l'eleve dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function (string $bucketId, string $name, ?array $permissions, bool $fileSecurity, bool $enabled, ?int $maximumFileSize, array $allowedFileExtensions, string $compression, bool $encryption, bool $antivirus, Response $response, Database $dbForProject, Event $events) {\n $bucket = $dbForProject->getDocument('buckets', $bucketId);\n\n if ($bucket->isEmpty()) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $permissions ??= $bucket->getPermissions();\n $maximumFileSize ??= $bucket->getAttribute('maximumFileSize', (int) App::getEnv('_APP_STORAGE_LIMIT', 0));\n $allowedFileExtensions ??= $bucket->getAttribute('allowedFileExtensions', []);\n $enabled ??= $bucket->getAttribute('enabled', true);\n $encryption ??= $bucket->getAttribute('encryption', true);\n $antivirus ??= $bucket->getAttribute('antivirus', true);\n\n /**\n * Map aggregate permissions into the multiple permissions they represent,\n * accounting for the resource type given that some types not allowed specific permissions.\n */\n // Map aggregate permissions into the multiple permissions they represent.\n $permissions = Permission::aggregate($permissions);\n\n $bucket = $dbForProject->updateDocument('buckets', $bucket->getId(), $bucket\n ->setAttribute('name', $name)\n ->setAttribute('$permissions', $permissions)\n ->setAttribute('maximumFileSize', $maximumFileSize)\n ->setAttribute('allowedFileExtensions', $allowedFileExtensions)\n ->setAttribute('fileSecurity', $fileSecurity)\n ->setAttribute('enabled', $enabled)\n ->setAttribute('encryption', $encryption)\n ->setAttribute('compression', $compression)\n ->setAttribute('antivirus', $antivirus));\n $dbForProject->updateCollection('bucket_' . $bucket->getInternalId(), $permissions, $fileSecurity);\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ;\n\n $response->dynamic($bucket, Response::MODEL_BUCKET);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function createGeneric($dataItemType, $dataItemID, $isProfileImage,\n $extractText, $title, $originalFilename, $tempFilename,\n $contentType, $fileContents, $fileExists)\n {\n /* Make a 'safe' filename with only standard ASCII characters. */\n $storedFilename = FileUtility::makeSafeFilename($originalFilename);\n\n /* Create an attachment title. */\n $attachmentTitle = FileUtility::getFileWithoutExtension(\n $originalFilename\n );\n\n /* Make attachment searchable. */\n if (!$extractText)\n {\n $extractedText = '';\n }\n else\n {\n $documentToText = new DocumentToText();\n $documentType = $documentToText->getDocumentType(\n $storedFilename, $contentType\n );\n\n /* If we're creating a file from text contents, we can skip\n * extracting because we already know the text contents.\n */\n if ($fileContents !== false && $documentType == DOCUMENT_TYPE_TEXT)\n {\n $extractedText = $fileContents;\n }\n else if ($fileContents !== false)\n {\n /* If it's not text and we are creating a file from contents,\n * don't try to extract text.\n */\n $extractedText = '';\n }\n else if (!$fileExists)\n {\n /* Can't extract text from a file that doesn't exist. */\n $extractedText = '';\n }\n else\n {\n $documentToText->convert($tempFilename, $documentType);\n\n if ($documentToText->isError())\n {\n $this->_isTextExtractionError = true;\n $this->_textExtractionError = $documentToText->getError();\n $extractedText = '';\n }\n else\n {\n $extractedText = $documentToText->getString();\n }\n\n /* If we are adding a bulk resume, and parsing fails, consider it\n * a fatal error.\n */\n if ($dataItemType == DATA_ITEM_BULKRESUME &&\n $this->_isTextExtractionError)\n {\n $this->_isError = true;\n $this->_error = $this->_textExtractionError;\n return false;\n }\n }\n }\n\n $attachments = new Attachments($this->_siteID);\n\n /* We can only check for duplicates right now if the file actually\n * exists. We'll do it again later below.\n */\n if ($fileExists && !$fileContents)\n {\n /* We store file size in KB, rounded to nearest KB. */\n $fileSize = round(@filesize($tempFilename) / 1024);\n\n /* The md5sum is stored for duplicate checking. */\n $md5sum = @md5_file($tempFilename);\n\n /* Check for duplicates. */\n $duplicates = $attachments->getMatching(\n $dataItemType, $dataItemID, $fileSize, $md5sum, $extractedText\n );\n\n /* Duplicate attachments are never added, but this is not a fatal\n * error. We will set a property to notify the caller that a\n * duplicate occurred.\n */\n if (!empty($duplicates))\n {\n $this->_duplicatesOccurred = true;\n\n if (file_exists($tempFilename))\n {\n unlink($tempFilename);\n }\n\n return false;\n }\n }\n else\n {\n $fileSize = 0;\n $md5sum = '';\n }\n\n /* Add the attachment record. At this point, there is no actual\n * associated directory / full file path.\n */\n $attachmentID = $attachments->add(\n $dataItemType, $dataItemID, $attachmentTitle, $originalFilename,\n $storedFilename, $contentType, $extractText, $extractedText,\n $isProfileImage, '', $fileSize, $md5sum\n );\n\n /* Were we successful? */\n if (!$attachmentID)\n {\n $this->_isError = true;\n $this->_error = 'Error adding attachment to the database.';\n @unlink($tempFilename);\n return false;\n }\n\n /* Store the extracted text and attachment ID in properties for later\n * access.\n */\n $this->_extractedText = $extractedText;\n $this->_attachmentID = $attachmentID;\n\n /* Create the attachment directory. */\n $uniqueDirectory = $this->_createDirectory(\n $attachmentID, $storedFilename\n );\n if (!$uniqueDirectory)\n {\n $attachments->delete($attachmentID, false);\n return false;\n }\n\n /* Create the full path name to the file. */\n $newFileFullPath = $uniqueDirectory . $storedFilename;\n\n /* Are we creating a new file from file contents, or are we moving a\n * temporary file?\n */\n if ($fileContents !== false)\n {\n $status = @file_put_contents($newFileFullPath, $fileContents);\n if (!$status)\n {\n $this->_isError = true;\n $this->_error = sprintf(\n 'Cannot create file %s.', $newFileFullPath\n );\n $attachments->delete($attachmentID, false);\n @unlink($uniqueDirectory);\n return false;\n }\n\n /* We store file size in KB, rounded to nearest KB. */\n $fileSize = round(@filesize($newFileFullPath) / 1024);\n\n /* The md5sum is stored for duplicate checking. */\n $md5sum = @md5_file($newFileFullPath);\n\n /* Check for duplicates. */\n $duplicates = $attachments->getMatching(\n $dataItemType, $dataItemID, $fileSize, $md5sum, $extractedText\n );\n\n /* Duplicate attachments are never added, but this is not a fatal\n * error. We will set a property to notify the caller that a\n * duplicate occurred.\n */\n if (!empty($duplicates))\n {\n $this->_duplicatesOccurred = true;\n $attachments->delete($attachmentID, false);\n @unlink($newFileFullPath);\n @unlink($uniqueDirectory);\n return false;\n }\n }\n else if ($fileExists)\n {\n /* Copy the temp file to the new path. */\n if (!@copy($tempFilename, $newFileFullPath))\n {\n $this->_isError = true;\n $this->_error = sprintf(\n 'Cannot copy temporary file %s to %s.',\n $tempFilename,\n $newFileFullPath\n );\n $attachments->delete($attachmentID, false);\n @unlink($newFileFullPath);\n @unlink($uniqueDirectory);\n return false;\n }\n\n /* Try to remove the temp file; if it fails it doesn't matter. */\n @unlink($tempFilename);\n }\n\n /* Store path to the file (inside the attachments directory) in this\n * object.\n */\n $this->_newFilePath = $newFileFullPath;\n $this->_containingDirectory = $uniqueDirectory;\n\n /* Update the database with the new directory name. */\n $attachments->setDirectoryName(\n $attachmentID,\n str_replace('./attachments/', '', $uniqueDirectory)\n );\n\n if (!eval(Hooks::get('CREATE_ATTACHMENT_FINISHED'))) return;\n\n return true;\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "function write_form_line(\n $code_type,\n $code,\n $id,\n $date,\n $description,\n $amount,\n $units,\n $taxrates,\n $billtime = '',\n $chargecat = ''\n) {\n global $lino, $totalchg, $aAdjusts, $taxes, $encounter_date, $TAXES_AFTER_ADJUSTMENT;\n\n // Write heading rows if that is not already done.\n write_form_headers();\n $amount = formatMoneyNumber($amount);\n if (empty($units)) {\n $units = 1;\n }\n $price = formatMoneyNumber($amount / $units, 2); // should be even cents, but...\n if (substr($price, -2) === '00') {\n $price = formatMoneyNumber($price);\n }\n\n // Total and clear adjustments in aAdjusts matching this line item. Should only\n // happen for billed items, and matching includes the billing timestamp in order\n // to handle the case of multiple checkouts.\n $memo = '';\n $adjust = pull_adjustment($code_type, $code, $billtime, $memo);\n $total = formatMoneyNumber($amount - $adjust);\n if (empty($GLOBALS['discount_by_money'])) {\n // Convert $adjust to a percentage of the amount, up to 4 decimal places.\n $adjust = round(100 * $adjust / $amount, 4);\n }\n\n // Compute the string of numeric tax rates to store with the charge line.\n $taxnumrates = '';\n $arates = explode(':', $taxrates);\n foreach ($taxes as $taxid => $taxarr) {\n $rate = $taxarr[1];\n if (empty($arates) || !in_array($taxid, $arates)) {\n $rate = 0;\n }\n $taxnumrates .= $rate . ':';\n }\n\n echo \" \\n\";\n echo \" \" . text(oeFormatShortDate($encounter_date));\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n // String of numeric tax rates is written here as a form field only for JavaScript tax computations.\n echo \"\";\n echo \"\";\n // Indicator of whether and when this line item was previously billed:\n echo \"\";\n echo \"\\n\";\n echo \" \" . text($description) . \"\";\n echo \" \" . text($units) . \"\";\n\n if (empty($GLOBALS['gbl_checkout_charges'])) {\n // We show only total charges here.\n echo \" \";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n } else {\n // In this case show price and extended charge amount.\n echo \" \";\n echo \"\";\n echo \"\\n\";\n echo \" \";\n echo \"\";\n echo \"\\n\";\n }\n\n // Match up (and delete) entries in $aInvTaxes with the line.\n $lineid = $code_type == 'PROD' ? \"P:$id\" : \"S:$id\";\n $aTaxes = array();\n pull_tax($lineid, $aTaxes); // fills in $aTaxes\n\n if (!$TAXES_AFTER_ADJUSTMENT) {\n // A tax column for each tax. JavaScript will compute the amounts and\n // account for how the discount affects them.\n $i = 0;\n foreach ($taxes as $taxid => $dummy) {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n ++$i;\n }\n }\n\n // Optional Charge Category.\n if (!empty($GLOBALS['gbl_charge_categories'])) {\n echo \" \";\n echo generate_select_list(\n \"line[$lino][chargecat]\",\n 'chargecats',\n $chargecat,\n '',\n ' ',\n '',\n '',\n '',\n $billtime ? array('disabled' => 'disabled') : null\n );\n echo \"\\n\";\n }\n\n if (!empty($GLOBALS['gbl_checkout_line_adjustments'])) {\n echo \" \";\n echo generate_select_list(\n \"line[$lino][memo]\",\n 'adjreason',\n $memo,\n '',\n ' ',\n '',\n 'billingChanged()',\n '',\n $billtime ? array('disabled' => 'disabled') : null\n );\n echo \"\\n\";\n echo \" \";\n echo empty($GLOBALS['discount_by_money']) ? '' : text($GLOBALS['gbl_currency_symbol']);\n echo \" \";\n echo empty($GLOBALS['discount_by_money']) ? '%' : '';\n echo \"\\n\";\n }\n\n if ($TAXES_AFTER_ADJUSTMENT) {\n // A tax column for each tax. JavaScript will compute the amounts and\n // account for how the discount affects them.\n $i = 0;\n foreach ($taxes as $taxid => $dummy) {\n echo \" \";\n echo \"\";\n echo \"\\n\";\n ++$i;\n }\n }\n\n // Extended amount after adjustments and taxes.\n echo \" \";\n echo \"\";\n echo \"\\n\";\n\n echo \" \\n\";\n ++$lino;\n $totalchg += $amount;\n}", "smellKey": "S107", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function exist_procedure_item($patient_id, $proc_title, $proc_code, $result_comp, string $result_data = null, $num_items_comp = null, $num_items_thres = null, $intervalType = '', $intervalValue = '', $dateFocus = '', $dateTarget = '')\n{\n\n // Set date to current if not set\n $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');\n\n // Set the table exception (for looking up pertinent date and pid sql columns)\n $table = \"PROCEDURE-EXCEPTION\";\n\n // Collect the correct column label for patient id in the table\n $patient_id_label = collect_database_label('pid', $table);\n\n // Get the interval sql query string\n // HR: interval will be $dateFocus - interval -> $dateTarget\n $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateFocus, $dateTarget);\n\n // If just checking for existence (ie result_data is empty),\n // then simply set the comparison operator to ne.\n if (empty($result_data)) {\n $result_comp = \"ne\";\n }\n\n // get the appropriate sql comparison operator\n $compSql = convertCompSql($result_comp);\n\n // explode the code array\n $codes = array();\n if (!empty($proc_code)) {\n $codes = explode(\"||\", $proc_code);\n } else {\n $codes[0] = '';\n }\n\n // ensure proc_title is at least blank\n if (empty($proc_title)) {\n $proc_title = '';\n }\n\n // collect specific items (use both title and/or codes) that fulfill request\n $sqlBindArray = array();\n $sql_query = \"SELECT procedure_result.result FROM \" .\n \"procedure_order_code, \" .\n \"procedure_order, \" .\n \"procedure_type, \" .\n \"procedure_report, \" .\n \"procedure_result \" .\n \"WHERE \" .\n \"procedure_order_code.procedure_code = procedure_type.procedure_code AND \" .\n \"procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND \" .\n \"procedure_order.lab_id = procedure_type.lab_id AND \" .\n \"procedure_report.procedure_order_id = procedure_order.procedure_order_id AND \" .\n \"procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND \" .\n \"procedure_result.procedure_report_id = procedure_report.procedure_report_id AND \" .\n \"procedure_type.procedure_type = 'ord' AND \";\n foreach ($codes as $tem) {\n $sql_query .= \"( ( (procedure_type.standard_code = ? AND procedure_type.standard_code != '') \" .\n \"OR (procedure_type.procedure_code = ? AND procedure_type.procedure_code != '') ) OR \";\n array_push($sqlBindArray, $tem, $tem);\n }\n\n // mdsupport : Allow trailing '**' in the strings to perform LIKE searches\n if ((substr($result_data, -2) == '**') && (($compSql == \"=\") || ($compSql == \"!=\"))) {\n $compSql = ($compSql == \"!=\" ? \" NOT\" : \"\") . \" LIKE CONCAT('%',?,'%') \";\n $result_data = substr_replace($result_data, '', -2);\n } else {\n $compSql = $compSql . \"? \";\n }\n\n $sql_query .= \"(procedure_type.name = ? AND procedure_type.name != '') ) \" .\n \"AND procedure_result.result \" . $compSql .\n \"AND \" . add_escape_custom($patient_id_label) . \" = ? \" . $dateSql;\n array_push($sqlBindArray, $proc_title, $result_data, $patient_id);\n\n $sql = sqlStatementCdrEngine($sql_query, $sqlBindArray);\n\n // See if number of returned items passes the comparison\n return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));\n}", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private static function _draw($call, $res, $color, $x, $y, $angle, $type, $datas, $width, $height)\n {\n $digit = '';\n $hri = '';\n $code = '';\n $crc = true;\n $rect = false;\n $b2d = false;\n\n if (is_array($datas)) {\n foreach (array('code' => '', 'crc' => true, 'rect' => false) as $v => $def) {\n $$v = isset($datas[$v]) ? $datas[$v] : $def;\n }\n\n $code = $code;\n } else {\n $code = $datas;\n }\n\n if ($code == '') {\n return false;\n }\n\n $code = (string) $code;\n\n $type = strtolower($type);\n\n switch ($type) {\n case 'std25':\n case 'int25':\n $digit = BarcodeI25::getDigit($code, $crc, $type);\n $hri = BarcodeI25::compute($code, $crc, $type);\n break;\n case 'ean8':\n case 'ean13':\n $digit = BarcodeEAN::getDigit($code, $type);\n $hri = BarcodeEAN::compute($code, $type);\n break;\n case 'upc':\n $digit = BarcodeUPC::getDigit($code);\n $hri = BarcodeUPC::compute($code);\n break;\n case 'code11':\n $digit = Barcode11::getDigit($code);\n $hri = $code;\n break;\n case 'code39':\n $digit = Barcode39::getDigit($code);\n $hri = $code;\n break;\n case 'code93':\n $digit = Barcode93::getDigit($code, $crc);\n $hri = $code;\n break;\n case 'code128':\n $digit = Barcode128::getDigit($code);\n $hri = $code;\n break;\n case 'codabar':\n $digit = BarcodeCodabar::getDigit($code);\n $hri = $code;\n break;\n case 'msi':\n $digit = BarcodeMSI::getDigit($code, $crc);\n $hri = BarcodeMSI::compute($code, $crc);\n break;\n case 'datamatrix':\n $digit = BarcodeDatamatrix::getDigit($code, $rect);\n $hri = $code;\n $b2d = true;\n break;\n }\n\n if ($digit == '') {\n return false;\n }\n\n if ($b2d) {\n $width = is_null($width) ? 5 : $width;\n $height = $width;\n } else {\n $width = is_null($width) ? 1 : $width;\n $height = is_null($height) ? 50 : $height;\n $digit = self::bitStringTo2DArray($digit);\n }\n\n if ($call == 'gd') {\n $result = self::digitToGDRenderer($res, $color, $x, $y, $angle, $width, $height, $digit);\n } elseif ($call == 'fpdf') {\n $result = self::digitToFPDFRenderer($res, $color, $x, $y, $angle, $width, $height, $digit);\n }\n\n $result['hri'] = $hri;\n return $result;\n }", "smellKey": "S107", "smellId": null, "repo": "Lord-Tiger_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function createStorage(\n\t\t$mountPoint,\n\t\t$backend,\n\t\t$authMechanism,\n\t\t$backendOptions,\n\t\t$mountOptions = null,\n\t\t$applicableUsers = null,\n\t\t$applicableGroups = null,\n\t\t$priority = null\n\t) {\n\t\t$canCreateNewLocalStorage = $this->config->getSystemValue('files_external_allow_create_new_local', true);\n\t\tif (!$canCreateNewLocalStorage && $backend === 'local') {\n\t\t\treturn new DataResponse(\n\t\t\t\t[\n\t\t\t\t\t'message' => $this->l10n->t('Forbidden to manage local mounts')\n\t\t\t\t],\n\t\t\t\tHttp::STATUS_FORBIDDEN\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\treturn $this->service->createStorage(\n\t\t\t\t$mountPoint,\n\t\t\t\t$backend,\n\t\t\t\t$authMechanism,\n\t\t\t\t$backendOptions,\n\t\t\t\t$mountOptions,\n\t\t\t\t$applicableUsers,\n\t\t\t\t$applicableGroups,\n\t\t\t\t$priority\n\t\t\t);\n\t\t} catch (\\InvalidArgumentException $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new DataResponse(\n\t\t\t\t[\n\t\t\t\t\t'message' => $this->l10n->t('Invalid backend or authentication mechanism class')\n\t\t\t\t],\n\t\t\t\tHttp::STATUS_UNPROCESSABLE_ENTITY\n\t\t\t);\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function creerDossierIB2($ref_dos, $id_cli, $ref_fact, $fob, \n\t\t\t\t\t\t\t\t\t\t$fret, $assurance, $autre_frais, $num_lic, \n\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $id_march, $id_mod_trans,\n\t\t\t\t\t\t\t\t\t\t$ref_av, $cod, $fxi, $montant_av, $date_fact, $ref_decl,\n\t\t\t\t\t\t\t\t\t\t$montant_decl, $ref_liq, $id_util, $ref_quit, $date_quit){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['ref_dos'] = $ref_dos; $entree['id_cli'] = $id_cli; $entree['ref_fact'] = $ref_fact; \n\t\t\t$entree['fob'] = $fob; $entree['fret'] = $fret; $entree['assurance'] = $assurance; \n\t\t\t$entree['autre_frais'] = $autre_frais; $entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic; $entree['id_march'] = $id_march; \n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['ref_av'] = $ref_av;\n\t\t\t$entree['cod'] = $cod;$entree['fxi'] = $fxi;\n\t\t\t$entree['montant_av'] = $montant_av;$entree['date_fact'] = $date_fact;\n\t\t\t$entree['ref_decl'] = $ref_decl;$entree['montant_decl'] = $montant_decl;\n\t\t\t$entree['ref_liq'] = $ref_liq;$entree['id_util'] = $id_util;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['date_quit'] = $date_quit;\n\n\t\t\tif($entree['date_fact'] == '' || (strlen($entree['date_fact']) != 10) ){\n\t\t\t\t$entree['date_fact'] = NULL;\n\t\t\t}\n\n\t\t\tif($entree['date_quit'] == '' || (strlen($entree['date_quit']) != 10) ){\n\t\t\t\t$entree['date_quit'] = NULL;\n\t\t\t}\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier(ref_dos, id_cli, ref_fact, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfret, assurance, autre_frais, num_lic, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_march, id_mod_trans, ref_av,cod, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfxi, montant_av, date_fact, ref_decl, montant_decl, ref_liq, id_util, ref_quit, date_quit)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['ref_dos'], $entree['id_cli'], $entree['ref_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fob'], $entree['fret'], $entree['assurance'], \n\t\t\t\t\t\t\t\t\t$entree['autre_frais'], $entree['num_lic'], $entree['id_mod_lic'], \n\t\t\t\t\t\t\t\t\t$entree['id_march'], $entree['id_mod_trans'], \n\t\t\t\t\t\t\t\t\t$entree['ref_av'], $entree['cod'], $entree['fxi'], \n\t\t\t\t\t\t\t\t\t$entree['montant_av'], $entree['date_fact'], $entree['ref_decl'], \n\t\t\t\t\t\t\t\t\t$entree['montant_decl'], $entree['ref_liq'], $entree['id_util'], \n\t\t\t\t\t\t\t\t\t$entree['ref_quit'], $entree['date_quit']));\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "private function get_regex_replacement(\n\t\t$def_url,\n\t\t$type,\n\t\t$type_id,\n\t\t$lang_negotiation,\n\t\t$lang,\n\t\t$dir_path,\n\t\t$home_url,\n\t\t$url_parts,\n\t\t$req_uri_params,\n\t\t$anchor_output\n\t) {\n\n\t\t$type_id = $this->maybeStripParentTerm( $type_id );\n\n\t\tif ( 1 === $lang_negotiation && $lang ) {\n\t\t\t$langprefix = '/' . $lang;\n\t\t} else {\n\t\t\t$langprefix = '';\n\t\t}\n\t\t$perm_url = '(' . rtrim( $home_url, '/' ) . ')?' . $langprefix . '/' . str_replace( '?', '\\?', $dir_path );\n\t\t$regk = '@href=[\\'\"](' . self::escapePlusSign( $perm_url ) . ')[\\'\"]@i';\n\t\t$regv = 'href=\"/' . ltrim( $url_parts['path'], '/' ) . '?' . $type . '=' . $type_id;\n\t\tif ( '' !== $req_uri_params ) {\n\t\t\t$regv .= '&' . $req_uri_params;\n\t\t}\n\t\t$regv .= $anchor_output . '\"';\n\n\t\t$def_url[ $regk ] = $regv;\n\n\t\treturn $def_url;\n\t}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function __construct(string $appName,\n\t\tIRequest $request,\n\t\tstring $userId,\n\t\tNotificationManager $notificationManager,\n\t\tITimeFactory $timeFactory,\n\t\tIJobList $jobList,\n\t\tTransferOwnershipMapper $mapper,\n\t\tIUserManager $userManager,\n\t\tIRootFolder $rootFolder) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->userId = $userId;\n\t\t$this->notificationManager = $notificationManager;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->jobList = $jobList;\n\t\t$this->mapper = $mapper;\n\t\t$this->userManager = $userManager;\n\t\t$this->rootFolder = $rootFolder;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function saveCharttoReport(\n $report_id,\n $chart_id,\n $chart_title,\n $chart_drill_details,\n $chart_date_description,\n $position_in_report,\n $timeframe_type,\n $entry_type,\n &$map = array()\n ) {\n $this->_pdo->execute(\n \"\n INSERT INTO ReportCharts (\n chart_id,\n report_id,\n user_id,\n chart_title,\n chart_drill_details,\n chart_type,\n chart_date_description,\n ordering,\n timeframe_type,\n image_data,\n type,\n selected\n ) VALUES (\n :chart_id,\n :report_id,\n :user_id,\n :chart_title,\n :chart_drill_details,\n :chart_type,\n :chart_date_description,\n :ordering,\n :timeframe_type,\n :image_data,\n :type,\n :selected\n )\n \",\n array(\n 'chart_id' => $chart_id,\n 'report_id' => $report_id,\n 'user_id' => $this->_user_id,\n 'chart_title' => $chart_title,\n 'chart_drill_details' => $chart_drill_details,\n 'chart_type' => '',\n 'chart_date_description' => $chart_date_description,\n 'ordering' => $position_in_report,\n 'timeframe_type' => $timeframe_type,\n 'image_data' => $this->resolveBlobFromChartId($map, $chart_id),\n 'type' => $entry_type,\n 'selected' => 0,\n )\n );\n }", "smellKey": "S107", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function discover(\n $type,\n $device_id,\n $oid,\n $index,\n $description = 'Processor',\n $precision = 1,\n $current_usage = null,\n $warn_percent = 75,\n $entPhysicalIndex = null,\n $hrDeviceIndex = null\n ) {\n $proc = new static();\n $proc->processor_type = $type;\n $proc->device_id = $device_id;\n $proc->processor_index = (string) $index;\n $proc->processor_descr = $description;\n $proc->processor_precision = $precision;\n $proc->processor_usage = $current_usage;\n $proc->entPhysicalIndex = $entPhysicalIndex;\n $proc->hrDeviceIndex = $hrDeviceIndex;\n\n // handle string indexes\n if (Str::contains($oid, '\"')) {\n $oid = preg_replace_callback('/\"([^\"]+)\"/', function ($matches) {\n return Oid::encodeString($matches[1])->oid;\n }, $oid);\n }\n $proc->processor_oid = '.' . ltrim($oid, '.');\n\n if (! is_null($warn_percent)) {\n $proc->processor_perc_warn = $warn_percent;\n }\n\n // validity not checked yet\n if (is_null($proc->processor_usage)) {\n $data = snmp_get(device_by_id_cache($proc->device_id), $proc->processor_oid, '-Ovq');\n $proc->valid = ($data !== false);\n if (! $proc->valid) {\n return $proc;\n }\n $proc->processor_usage = static::processData($data, $proc->processor_precision);\n }\n\n d_echo('Discovered ' . get_called_class() . ' ' . print_r($proc->toArray(), true));\n\n return $proc;\n }", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function __construct(\n UnitFacade $unitFacade,\n Domain $domain,\n ParameterRepository $parameterRepository,\n FriendlyUrlFacade $friendlyUrlFacade,\n ProductAccessoryRepository $productAccessoryRepository,\n PluginCrudExtensionFacade $pluginDataFormExtensionFacade,\n ProductParameterValueDataFactoryInterface $productParameterValueDataFactory,\n ImageUploadDataFactory $imageUploadDataFactory,\n ProductStockFacade $productStockFacade,\n StockFacade $stockFacade,\n ProductStockDataFactory $productStockDataFactory,\n ProductInputPriceDataFactory $productInputPriceDataFactory,\n UploadedFileDataFactory $uploadedFileDataFactory,\n private readonly ProductVideoDataFactory $productVideoDataFactory,\n private readonly ProductVideoRepository $productVideoRepository,\n ) {\n parent::__construct(\n $unitFacade,\n $domain,\n $parameterRepository,\n $friendlyUrlFacade,\n $productAccessoryRepository,\n $pluginDataFormExtensionFacade,\n $productParameterValueDataFactory,\n $imageUploadDataFactory,\n $productStockFacade,\n $stockFacade,\n $productStockDataFactory,\n $productInputPriceDataFactory,\n $uploadedFileDataFactory,\n );\n }", "smellKey": "S107", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function createMainConfig(\n string $host,\n string $user,\n string $password,\n string $dbname,\n bool $use_timezones = false,\n bool $log_deprecation_warnings = false,\n bool $use_utf8mb4 = false,\n bool $allow_myisam = true,\n bool $allow_datetime = true,\n bool $allow_signed_keys = true,\n string $config_dir = GLPI_CONFIG_DIR\n ): bool {\n\n $properties = [\n 'dbhost' => $host,\n 'dbuser' => $user,\n 'dbpassword' => rawurlencode($password),\n 'dbdefault' => $dbname,\n ];\n if ($use_timezones) {\n $properties[self::PROPERTY_USE_TIMEZONES] = true;\n }\n if ($log_deprecation_warnings) {\n $properties[self::PROPERTY_LOG_DEPRECATION_WARNINGS] = true;\n }\n if ($use_utf8mb4) {\n $properties[self::PROPERTY_USE_UTF8MB4] = true;\n }\n if (!$allow_myisam) {\n $properties[self::PROPERTY_ALLOW_MYISAM] = false;\n }\n if (!$allow_datetime) {\n $properties[self::PROPERTY_ALLOW_DATETIME] = false;\n }\n if (!$allow_signed_keys) {\n $properties[self::PROPERTY_ALLOW_SIGNED_KEYS] = false;\n }\n\n $config_str = ' $value) {\n $config_str .= sprintf(' public $%s = %s;', $name, var_export($value, true)) . \"\\n\";\n }\n $config_str .= '}' . \"\\n\";\n\n return Toolbox::writeConfig('config_db.php', $config_str, $config_dir);\n }", "smellKey": "S107", "smellId": null, "repo": "flegastelois_glpi", "language": "php"} {"function": "function discover_sensor($unused, $class, $device, $oid, $index, $type, $descr, $divisor = 1, $multiplier = 1, $low_limit = null, $low_warn_limit = null, $warn_limit = null, $high_limit = null, $current = null, $poller_type = 'snmp', $entPhysicalIndex = null, $entPhysicalIndex_measured = null, $user_func = null, $group = null, $rrd_type = 'GAUGE'): bool\n{\n $low_limit = set_null($low_limit);\n $low_warn_limit = set_null($low_warn_limit);\n $warn_limit = set_null($warn_limit);\n $high_limit = set_null($high_limit);\n $current = cast_number($current);\n\n if (! is_numeric($divisor)) {\n $divisor = 1;\n }\n\n app('sensor-discovery')->discover(new \\App\\Models\\Sensor([\n 'poller_type' => $poller_type,\n 'sensor_class' => $class,\n 'device_id' => $device['device_id'],\n 'sensor_oid' => $oid,\n 'sensor_index' => $index,\n 'sensor_type' => $type,\n 'sensor_descr' => $descr,\n 'sensor_divisor' => $divisor,\n 'sensor_multiplier' => $multiplier,\n 'sensor_limit' => $high_limit,\n 'sensor_limit_warn' => $warn_limit,\n 'sensor_limit_low' => $low_limit,\n 'sensor_limit_low_warn' => $low_warn_limit,\n 'sensor_current' => $current,\n 'entPhysicalIndex' => $entPhysicalIndex,\n 'entPhysicalIndex_measured' => $entPhysicalIndex_measured,\n 'user_func' => $user_func,\n 'group' => $group,\n 'rrd_type' => $rrd_type,\n ]));\n\n return true;\n}", "smellKey": "S107", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "private function addShareToDB($shareType, $sharedWith, $sharedBy, $shareOwner,\n\t\t$itemType, $fileSource, $fileTarget, $permissions, $token, $expiration,\n\t\t$parent) {\n\t\t$qb = $this->dbConn->getQueryBuilder();\n\t\t$qb->insert('share');\n\n\t\tif ($shareType) {\n\t\t\t$qb->setValue('share_type', $qb->expr()->literal($shareType));\n\t\t}\n\t\tif ($sharedWith) {\n\t\t\t$qb->setValue('share_with', $qb->expr()->literal($sharedWith));\n\t\t}\n\t\tif ($sharedBy) {\n\t\t\t$qb->setValue('uid_initiator', $qb->expr()->literal($sharedBy));\n\t\t}\n\t\tif ($shareOwner) {\n\t\t\t$qb->setValue('uid_owner', $qb->expr()->literal($shareOwner));\n\t\t}\n\t\tif ($itemType) {\n\t\t\t$qb->setValue('item_type', $qb->expr()->literal($itemType));\n\t\t}\n\t\tif ($fileSource) {\n\t\t\t$qb->setValue('file_source', $qb->expr()->literal($fileSource));\n\t\t}\n\t\tif ($fileTarget) {\n\t\t\t$qb->setValue('file_target', $qb->expr()->literal($fileTarget));\n\t\t}\n\t\tif ($permissions) {\n\t\t\t$qb->setValue('permissions', $qb->expr()->literal($permissions));\n\t\t}\n\t\tif ($token) {\n\t\t\t$qb->setValue('token', $qb->expr()->literal($token));\n\t\t}\n\t\tif ($expiration) {\n\t\t\t$qb->setValue('expiration', $qb->createNamedParameter($expiration, IQueryBuilder::PARAM_DATE));\n\t\t}\n\t\tif ($parent) {\n\t\t\t$qb->setValue('parent', $qb->expr()->literal($parent));\n\t\t}\n\n\t\t$this->assertEquals(1, $qb->execute());\n\t\treturn $qb->getLastInsertId();\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function __formatDate($timestamp, $format, $fromDb, $dayType, $timeType,\n $strftimeFallback, $timezone, $user=false) {\n global $cfg;\n static $cache;\n\n if ($timestamp && $fromDb)\n $timestamp = Misc::db2gmtime($timestamp);\n\n // Make sure timestamp is valid for realz.\n if (!$timestamp || !($datetime = DateTime::createFromFormat('U', $timestamp)))\n return '';\n\n // Normalize timezone\n if ($timezone)\n $timezone = Format::timezone($timezone);\n\n // Set the desired timezone (caching since it will be mostly same\n // for most date formatting.\n $timezone = Format::timezone($timezone, $cfg->getTimezone());\n if (isset($cache[$timezone]))\n $tz = $cache[$timezone];\n else\n $cache[$timezone] = $tz = new DateTimeZone($timezone);\n\n $datetime->setTimezone($tz);\n\n // Formmating options\n $options = array(\n 'timezone' => $tz->getName(),\n 'locale' => Internationalization::getCurrentLocale($user),\n 'daytype' => $dayType,\n 'timetype' => $timeType,\n 'strftime' => $strftimeFallback,\n );\n\n return self::IntDateFormat($datetime, $format, $options);\n\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function fdhistogram($freq,$label,$start,$cw,$labelstart=false,$upper=false,$width=300,$height=200,$showgrid=true,$fill='blue',$stroke='black') {\n\tif (!is_array($freq)) {echo \"freqarray must be an array\"; return 0;}\n\tif ($cw<0) { $cw *= -1;} else if ($cw==0) { echo \"Error - classwidth cannot be 0\"; return 0;}\n\t$x = $start;\n $vertlabel = 'Frequency';\n if (is_array($labelstart)) {\n $opts = $labelstart;\n $labelstart = false;\n foreach (['labelstart','upper','width','height','showgrid','fill','stroke','vertlabel'] as $v) {\n if (isset($opts[$v])) {\n ${$v} = $opts[$v];\n }\n }\n }\n\t$alt = \"Histogram for $label \\n\\n\";\n\t$maxfreq = 0;\n \n\tif ($upper===false) {\n\t\t$dx = $cw;\n\t\t$dxdiff = 0;\n\t} else {\n\t\t$dx = $upper - $start;\n\t\t$dxdiff = $cw-$dx;\n\t}\n $st = '';\n\tfor ($curr=0; $curr\";\n\t\t$st .= \"rect([$x,0],\";\n\t\t$x += $dx;\n\t\t$st .= \"[$x,{$freq[$curr]}]);\";\n\t\tif ($freq[$curr]>$maxfreq) { $maxfreq = $freq[$curr];}\n\t\t$x += $dxdiff;\n\t}\n\t$alt .= \"
    Label on left of box$vertlabel
    $x{$freq[$curr]}
    \\n\";\n\tif ($_SESSION['graphdisp']==0) {\n\t\treturn $alt;\n\t}\n\t$outst = \"setBorder(\".(40+7*strlen($maxfreq)).\",40,20,5); initPicture(\".($start>0?(max($start-.9*$cw,0)):$start).\",$x,0,$maxfreq);\";\n\t//$outst = \"setBorder(10); initPicture(\". ($start-.1*($x-$start)) .\",$x,\". (-.1*$maxfreq) .\",$maxfreq);\";\n\t$power = floor(log10($maxfreq))-1;\n\t$base = $maxfreq/pow(10,$power);\n\tif ($base>75) {$step = 20*pow(10,$power);} else if ($base>40) { $step = 10*pow(10,$power);} else if ($base>20) {$step = 5*pow(10,$power);} else if ($base>9) {$step = 2*pow(10,$power);} else {$step = pow(10,$power);}\n\t//if ($maxfreq>100) {$step = 20;} else if ($maxfreq > 50) { $step = 10; } else if ($maxfreq > 20) { $step = 5;} else if ($maxfreq>9) {$step = 2;} else {$step=1;}\n\t\n\tif ($showgrid===true) {\n\t\t$gdy = $step;\n\t} else {\n\t\t$gdy = 0;\n\t}\n\t\n\t\n\tif ($labelstart===false) {\n\t\t//$outst .= \"axes($cw,$step,1,1000,$step); fill=\\\"blue\\\"; textabs([\". ($width/2+15) .\",0],\\\"$label\\\",\\\"above\\\");\";\n\t\t$labelstart = $start;\n\t} //else {\n\t\t$outst .= \"axes(1000,$step,1,1000,$gdy); fill=\\\"$fill\\\"; stroke=\\\"$stroke\\\";\";\n\t\t$x = $labelstart;\n\t\t$tm = -.02*$maxfreq;\n\t\t$tx = .02*$maxfreq;\n\t\tfor ($curr=0; $currstate != 2) {\n\t\t\treturn;\n\t\t}\n\t\tif (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {\n\t\t\t$ry = $rx;\n\t\t}\n\t\tif (!(false === strpos($style, 'F')) AND isset($fill_color)) {\n\t\t\t$this->SetFillColorArray($fill_color);\n\t\t}\n\t\t$op = TCPDF_STATIC::getPathPaintOperator($style);\n\t\tif ($op == 'f') {\n\t\t\t$line_style = array();\n\t\t}\n\t\tif ($line_style) {\n\t\t\t$this->SetLineStyle($line_style);\n\t\t}\n\t\t$this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);\n\t\t$this->_out($op);\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public function exportTable(\n string $db,\n string $table,\n string $whatStrucOrData,\n ExportPlugin $exportPlugin,\n string $errorUrl,\n string $exportType,\n bool $doRelation,\n bool $doComments,\n bool $doMime,\n bool $doDates,\n string|null $allrows,\n string $limitTo,\n string $limitFrom,\n string $sqlQuery,\n array $aliases,\n ): void {\n $dbAlias = ! empty($aliases[$db]['alias'])\n ? $aliases[$db]['alias'] : '';\n if (! $exportPlugin->exportDBHeader($db, $dbAlias)) {\n return;\n }\n\n if ($allrows === '0' && $limitTo > 0 && $limitFrom >= 0) {\n $addQuery = ' LIMIT '\n . ($limitFrom > 0 ? $limitFrom . ', ' : '')\n . $limitTo;\n } else {\n $addQuery = '';\n }\n\n $tableObject = new Table($table, $db, $this->dbi);\n $isView = $tableObject->isView();\n if ($whatStrucOrData === 'structure' || $whatStrucOrData === 'structure_and_data') {\n if ($isView) {\n if (isset($GLOBALS['sql_create_view'])) {\n if (\n ! $exportPlugin->exportStructure(\n $db,\n $table,\n 'create_view',\n $exportType,\n $doRelation,\n $doComments,\n $doMime,\n $doDates,\n $aliases,\n )\n ) {\n return;\n }\n }\n } elseif (isset($GLOBALS['sql_create_table'])) {\n if (\n ! $exportPlugin->exportStructure(\n $db,\n $table,\n 'create_table',\n $exportType,\n $doRelation,\n $doComments,\n $doMime,\n $doDates,\n $aliases,\n )\n ) {\n return;\n }\n }\n }\n\n // If this is an export of a single view, we have to export data;\n // for example, a PDF report\n // if it is a merge table, no data is exported\n if ($whatStrucOrData === 'data' || $whatStrucOrData === 'structure_and_data') {\n if ($sqlQuery !== '') {\n // only preg_replace if needed\n if ($addQuery !== '') {\n // remove trailing semicolon before adding a LIMIT\n $sqlQuery = preg_replace('%;\\s*$%', '', $sqlQuery);\n }\n\n $localQuery = $sqlQuery . $addQuery;\n $this->dbi->selectDb($db);\n } else {\n // Data is exported only for Non-generated columns\n $tableObj = new Table($table, $db, $this->dbi);\n $nonGeneratedCols = $tableObj->getNonGeneratedColumns();\n\n $localQuery = 'SELECT ' . implode(', ', $nonGeneratedCols)\n . ' FROM ' . Util::backquote($db)\n . '.' . Util::backquote($table) . $addQuery;\n }\n\n if (! $exportPlugin->exportData($db, $table, $errorUrl, $localQuery, $aliases)) {\n return;\n }\n }\n\n // now export the triggers (needs to be done after the data because\n // triggers can modify already imported tables)\n if (\n isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData === 'structure'\n || $whatStrucOrData === 'structure_and_data')\n ) {\n if (\n ! $exportPlugin->exportStructure(\n $db,\n $table,\n 'triggers',\n $exportType,\n $doRelation,\n $doComments,\n $doMime,\n $doDates,\n $aliases,\n )\n ) {\n return;\n }\n }\n\n if (! $exportPlugin->exportDBFooter($db)) {\n return;\n }\n\n if (! isset($GLOBALS['sql_metadata'])) {\n return;\n }\n\n // Types of metadata to export.\n // In the future these can be allowed to be selected by the user\n $metadataTypes = $this->getMetadataTypes();\n $exportPlugin->exportMetadata($db, $table, $metadataTypes);\n }", "smellKey": "S107", "smellId": null, "repo": "achibear_phpmyadmin", "language": "php"} {"function": "public function creerLicenceIB2($id_banq, $num_lic, $id_cli, $id_post, \n\t\t\t\t\t\t\t\t\t\t$id_mon, $fob, $assurance, $fret, \n\t\t\t\t\t\t\t\t\t\t$autre_frais, $fsi, $aur, \n\t\t\t\t\t\t\t\t\t\t$id_mod_trans, $ref_fact, $date_fact, $fournisseur, \n\t\t\t\t\t\t\t\t\t\t$date_val, $date_exp, $id_march, $id_mod_lic, \n\t\t\t\t\t\t\t\t\t\t$id_util, $fichier_lic, $tmp, $fichier_fact, $tmp_fact, \n\t\t\t\t\t\t\t\t\t\t$id_type_lic, $id_mod_paie, $id_sous_type_paie,\n\t\t\t\t\t\t\t\t\t\t$provenance, $commodity, $tonnage, $poids, $unit_mes, $cod, $consommable){\n\t\t\tinclude('connexion.php');\n\t\t\t$entree['id_banq'] = $id_banq;$entree['num_lic'] = $num_lic;\n\t\t\t$entree['id_cli'] = $id_cli;$entree['id_post'] = $id_post;\n\t\t\t$entree['id_mon'] = $id_mon;$entree['fob'] = $fob;\n\t\t\t$entree['assurance'] = $assurance;$entree['fret'] = $fret;$entree['autre_frais'] = $autre_frais;\n\t\t\t$entree['fsi'] = $fsi;$entree['aur'] = $aur;\n\t\t\t$entree['id_mod_trans'] = $id_mod_trans;$entree['ref_fact'] = $ref_fact;$entree['date_fact'] = $date_fact;\n\t\t\t$entree['fournisseur'] = $fournisseur;$entree['date_val'] = $date_val;$entree['date_exp'] = $date_exp;\n\t\t\t$entree['id_march'] = $id_march;$entree['id_mod_lic'] = $id_mod_lic;$entree['id_util'] = $id_util;\n\t\t\t$entree['fichier_lic'] = $fichier_lic;$entree['fichier_fact'] = $fichier_fact;\n\t\t\t$entree['id_type_lic'] = $id_type_lic;$entree['id_mod_paie'] = $id_mod_paie;\n\t\t\t$entree['id_sous_type_paie'] = $id_sous_type_paie; $entree['provenance'] = $provenance;\n\t\t\t$entree['commodity'] = $commodity;\n\t\t\t$entree['tonnage'] = $tonnage; $entree['poids'] = $poids;\n\t\t\t$entree['unit_mes'] = $unit_mes;\n\t\t\t$entree['cod'] = $cod;\n\t\t\t$entree['consommable'] = $consommable;\n\n\t\t\tif ($entree['date_fact'] == '') {\n\t\t\t\t$entree['date_fact'] = NULL;\n\t\t\t}\n\n\t\t\tif ($entree['date_val'] == '') {\n\t\t\t\t$entree['date_val'] = NULL;\n\t\t\t}\n\n\t\t\tif ($entree['date_exp'] == '') {\n\t\t\t\t$entree['date_exp'] = NULL;\n\t\t\t}\n\n\t\t\tif ($entree['fob'] == '') {\n\t\t\t\t$entree['fob'] = NULL;\n\t\t\t}\n\t\t\tif ($entree['fret'] == '') {\n\t\t\t\t$entree['fret'] = NULL;\n\t\t\t}\n\t\t\tif ($entree['assurance'] == '') {\n\t\t\t\t$entree['assurance'] = NULL;\n\t\t\t}\n\t\t\tif ($entree['autre_frais'] == '') {\n\t\t\t\t$entree['autre_frais'] = NULL;\n\t\t\t}\n\t\t\t/*\n\t\t\tif ($entree[''] == '') {\n\t\t\t\t$entree[''] = NULL;\n\t\t\t}\n\n\t\t\tif ($entree[''] == '') {\n\t\t\t\t$entree[''] = NULL;\n\t\t\t}*/\n\n\t\t\t/*echo \"
    id_banq = $id_banq\";echo \"
    num_lic = $num_lic\";echo \"
    id_cli = $id_cli\";\n\t\t\techo \"
    id_post = $id_post\";echo \"
    id_mon = $id_mon\";echo \"
    fob = $fob\";\n\t\t\techo \"
    assurance = $assurance\";echo \"
    fret = $fret\";echo \"
    autre_frais = $autre_frais\";\n\t\t\techo \"
    fsi = $fsi\";echo \"
    aur = $aur\";echo \"
    id_mod_trans = $id_mod_trans\";\n\t\t\techo \"
    ref_fact = $ref_fact\";echo \"
    date_fact = $date_fact\";echo \"
    fournisseur = $fournisseur\";\n\t\t\techo \"
    date_val = $date_val\";echo \"
    date_exp = $date_exp\";echo \"
    id_march = $id_march\";\n\t\t\techo \"
    id_mod_lic = $id_mod_lic\";echo \"
    id_util = $id_util\";echo \"
    fichier_lic = $fichier_lic\";\n\t\t\techo \"
    fichier_fact = $fichier_fact\";echo \"
    id_type_lic = $id_type_lic\";echo \"
    id_mod_paie = $id_mod_paie\";\n\t\t\techo \"
    id_sous_type_paie = $id_sous_type_paie\";echo \"
    provenance = $provenance\";echo \"
    commodity = $commodity\";\n\t\t\techo \"
    --------------------------------\";*/\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO licence(id_banq, num_lic, id_cli, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_post, id_mon, fob, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tassurance, fret, autre_frais, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfsi, aur, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_trans, ref_fact, date_fact, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfournisseur, date_val, id_march, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_mod_lic, id_util, fichier_lic, fichier_fact,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid_type_lic, id_mod_paie, id_sous_type_paie, provenance, commodity, tonnage, poids, unit_mes, cod, consommable) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?,\n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?,\n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['id_banq'], $entree['num_lic'], $entree['id_cli'], \n\t\t\t\t\t\t\t\t\t$entree['id_post'], $entree['id_mon'], $entree['fob'], \n\t\t\t\t\t\t\t\t\t$entree['assurance'], $entree['fret'], $entree['autre_frais'], \n\t\t\t\t\t\t\t\t\t$entree['fsi'], $entree['aur'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_trans'], $entree['ref_fact'], $entree['date_fact'], \n\t\t\t\t\t\t\t\t\t$entree['fournisseur'], $entree['date_val'], $entree['id_march'], \n\t\t\t\t\t\t\t\t\t$entree['id_mod_lic'], $entree['id_util'], $entree['fichier_lic'], \n\t\t\t\t\t\t\t\t\t$entree['fichier_fact'], $entree['id_type_lic'], $entree['id_mod_paie'], \n\t\t\t\t\t\t\t\t\t$entree['id_sous_type_paie'], $entree['provenance'], $entree['commodity'], \n\t\t\t\t\t\t\t\t\t$entree['tonnage'], $entree['poids'], $entree['unit_mes'], $entree['cod'], \n\t\t\t\t\t\t\t\t\t$entree['consommable']));\n\t\t\tif ($date_exp != null) {\n\t\t\t\t$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t\t}\n\t\t\t\n\t\t\tif ($tmp != null) {\n\t\t\t\t$dossier = '../dossiers/'.$num_lic;\n\n\t\t\t\tif(!is_dir($dossier)){\n\t\t\t\t\tmkdir(\"../dossiers/$num_lic\", 0777);\n\t\t\t\t}\n\n\t\t\t\tmove_uploaded_file($tmp, '../dossiers/'.$num_lic.'/' . basename($fichier_lic));\n\t\t\t\tmove_uploaded_file($tmp_fact, '../dossiers/'.$num_lic.'/' . basename($fichier_fact));\n\t\t\t\t}\n\t\t\t\t//move_uploaded_file($tmp, '../dossiers/');\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "static public function update($id, $title, $body, $type, $category, $player_id, $comments, $article_text, $article_image, &$errors)\n\t{\n\t\tglobal $db;\n\t\tif(!self::verify($title, $body, $article_text, $article_image, $errors))\n\t\t\treturn false;\n\n\t\t$db->update(TABLE_PREFIX . 'news', array('title' => $title, 'body' => $body, 'type' => $type, 'category' => $category, 'last_modified_by' => isset($player_id) ? $player_id : 0, 'last_modified_date' => time(), 'comments' => $comments, 'article_text' => $article_text, 'article_image' => $article_image), array('id' => $id));\n\t\tself::clearCache();\n\t\treturn true;\n\t}", "smellKey": "S107", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function (string $userId, string $phone, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Event $events, EventPhone $messaging, Locale $locale) {\n\n if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {\n throw new Exception(Exception::GENERAL_PHONE_DISABLED, 'Phone provider not configured');\n }\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n\n $result = $dbForProject->findOne('users', [Query::equal('phone', [$phone])]);\n if ($result !== false && !$result->isEmpty()) {\n $user->setAttributes($result->getArrayCopy());\n } else {\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0) {\n $total = $dbForProject->count('users', max: APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n throw new Exception(Exception::USER_COUNT_EXCEEDED);\n }\n }\n\n $userId = $userId == 'unique()' ? ID::unique() : $userId;\n $user->setAttributes([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => null,\n 'phone' => $phone,\n 'emailVerification' => false,\n 'phoneVerification' => false,\n 'status' => true,\n 'password' => null,\n 'passwordUpdate' => null,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => implode(' ', [$userId, $phone]),\n 'accessedAt' => DateTime::now(),\n ]);\n\n $user->removeAttribute('$internalId');\n Authorization::skip(fn () => $dbForProject->createDocument('users', $user));\n }\n\n $secret = Auth::codeGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), Auth::TOKEN_EXPIRATION_PHONE));\n\n $token = new Document([\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'type' => Auth::TOKEN_TYPE_PHONE,\n 'secret' => Auth::hash($secret),\n 'expire' => $expire,\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n ]);\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $token = $dbForProject->createDocument('tokens', $token\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');\n\n $customTemplate = $project->getAttribute('templates', [])['sms.login-' . $locale->default] ?? [];\n if (!empty($customTemplate)) {\n $message = $customTemplate['message'] ?? $message;\n }\n\n $message = $message->setParam('{{token}}', $secret);\n $message = $message->render();\n\n $messaging\n ->setRecipient($phone)\n ->setMessage($message)\n ->trigger();\n\n $events->setPayload(\n $response->output(\n $token->setAttribute('secret', $secret),\n Response::MODEL_TOKEN\n )\n );\n\n // Hide secret for clients\n $token->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $secret : '');\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($token, Response::MODEL_TOKEN)\n ;\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function doGenerate(array $variables, array $defaults, array $requirements, array $tokens, array $parameters, string $name, int $referenceType, array $hostTokens, array $requiredSchemes = [])\n {\n $variables = array_flip($variables);\n $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);\n\n // all params must be given\n if ($diff = array_diff_key($variables, $mergedParams)) {\n throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing (\"%s\") to generate a URL for route \"%s\".', implode('\", \"', array_keys($diff)), $name));\n }\n\n $url = '';\n $optional = true;\n $message = 'Parameter \"{parameter}\" for route \"{route}\" must match \"{expected}\" (\"{given}\" given) to generate a corresponding URL.';\n foreach ($tokens as $token) {\n if ('variable' === $token[0]) {\n $varName = $token[3];\n // variable is not important by default\n $important = $token[5] ?? false;\n\n if (!$optional || $important || !\\array_key_exists($varName, $defaults) || (null !== $mergedParams[$varName] && (string) $mergedParams[$varName] !== (string) $defaults[$varName])) {\n // check requirement (while ignoring look-around patterns)\n if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\\(\\?(?:=|<=|!|strictRequirements) {\n throw new InvalidParameterException(strtr($message, ['{parameter}' => $varName, '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$varName]]));\n }\n\n if ($this->logger) {\n $this->logger->error($message, ['parameter' => $varName, 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$varName]]);\n }\n\n return '';\n }\n\n $url = $token[1].$mergedParams[$varName].$url;\n $optional = false;\n }\n } else {\n // static text\n $url = $token[1].$url;\n $optional = false;\n }\n }\n\n if ('' === $url) {\n $url = '/';\n }\n\n // the contexts base URL is already encoded (see Symfony\\Component\\HttpFoundation\\Request)\n $url = strtr(rawurlencode($url), $this->decodedChars);\n\n // the path segments \".\" and \"..\" are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3\n // so we need to encode them as they are not used for this purpose here\n // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route\n $url = strtr($url, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);\n if (str_ends_with($url, '/..')) {\n $url = substr($url, 0, -2).'%2E%2E';\n } elseif (str_ends_with($url, '/.')) {\n $url = substr($url, 0, -1).'%2E';\n }\n\n $schemeAuthority = '';\n $host = $this->context->getHost();\n $scheme = $this->context->getScheme();\n\n if ($requiredSchemes) {\n if (!\\in_array($scheme, $requiredSchemes, true)) {\n $referenceType = self::ABSOLUTE_URL;\n $scheme = current($requiredSchemes);\n }\n }\n\n if ($hostTokens) {\n $routeHost = '';\n foreach ($hostTokens as $token) {\n if ('variable' === $token[0]) {\n // check requirement (while ignoring look-around patterns)\n if (null !== $this->strictRequirements && !preg_match('#^'.preg_replace('/\\(\\?(?:=|<=|!|strictRequirements) {\n throw new InvalidParameterException(strtr($message, ['{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]]]));\n }\n\n if ($this->logger) {\n $this->logger->error($message, ['parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]]);\n }\n\n return '';\n }\n\n $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;\n } else {\n $routeHost = $token[1].$routeHost;\n }\n }\n\n if ($routeHost !== $host) {\n $host = $routeHost;\n if (self::ABSOLUTE_URL !== $referenceType) {\n $referenceType = self::NETWORK_PATH;\n }\n }\n }\n\n if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {\n if ('' !== $host || ('' !== $scheme && 'http' !== $scheme && 'https' !== $scheme)) {\n $port = '';\n if ('http' === $scheme && 80 !== $this->context->getHttpPort()) {\n $port = ':'.$this->context->getHttpPort();\n } elseif ('https' === $scheme && 443 !== $this->context->getHttpsPort()) {\n $port = ':'.$this->context->getHttpsPort();\n }\n\n $schemeAuthority = self::NETWORK_PATH === $referenceType || '' === $scheme ? '//' : \"$scheme://\";\n $schemeAuthority .= $host.$port;\n }\n }\n\n if (self::RELATIVE_PATH === $referenceType) {\n $url = self::getRelativePath($this->context->getPathInfo(), $url);\n } else {\n $url = $schemeAuthority.$this->context->getBaseUrl().$url;\n }\n\n // add a query string if needed\n $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {\n return $a == $b ? 0 : 1;\n });\n\n array_walk_recursive($extra, $caster = static function (&$v) use (&$caster) {\n if (\\is_object($v)) {\n if ($vars = get_object_vars($v)) {\n array_walk_recursive($vars, $caster);\n $v = $vars;\n } elseif (method_exists($v, '__toString')) {\n $v = (string) $v;\n }\n }\n });\n\n // extract fragment\n $fragment = $defaults['_fragment'] ?? '';\n\n if (isset($extra['_fragment'])) {\n $fragment = $extra['_fragment'];\n unset($extra['_fragment']);\n }\n\n if ($extra && $query = http_build_query($extra, '', '&', \\PHP_QUERY_RFC3986)) {\n $url .= '?'.strtr($query, self::QUERY_FRAGMENT_DECODED);\n }\n\n if ('' !== $fragment) {\n $url .= '#'.strtr(rawurlencode($fragment), self::QUERY_FRAGMENT_DECODED);\n }\n\n return $url;\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function add($title, $companyId, $contactId, $description, $notes,\n $duration, $maxRate, $type, $isHot, $public, $openings, $companyJobId,\n $salary, $city, $state, $startDate, $enteredBy, $recruiter, $owner,\n $department, $questionnaire = false)\n {\n /* Get the department ID of the selected department. */\n // FIXME: Move this up to the UserInterface level. I don't like this\n // tight coupling, and calling Contacts methods as static is\n // bad.\n $departmentId = (new Contacts($this->_siteID))->getDepartmentIDByName(\n $department, $companyId, $this->_db\n );\n $jobOrder = JobOrder::create(\n $this->_siteID,\n $title,\n $companyId,\n $contactId,\n $description,\n $notes,\n $duration,\n $maxRate,\n $type,\n $isHot,\n $public,\n $openings,\n $companyJobId,\n $salary,\n $city,\n $state,\n $startDate,\n $enteredBy,\n $recruiter,\n $owner,\n $departmentId,\n $questionnaire\n );\n $JobOrderRepository = new JobOrderRepository($this->_db);\n try {\n $jobOrderId = $JobOrderRepository->persist($jobOrder, new History($this->_siteID));\n } catch (JobOrderRepositoryException $e) {\n return -1;\n }\n return $jobOrderId;\n }", "smellKey": "S107", "smellId": null, "repo": "alifarhan2532_opencats-test", "language": "php"} {"function": "public function createInstanceFrom(\n Territory $territory,\n ?string $status = null,\n ?PartnerType $partnerType = null,\n ?string $profileDeclarant = null,\n ?string $inseeToInclude = null,\n ?string $inseeToExclude = null,\n ?string $partnerToExclude = null,\n ?string $parc = null,\n ?string $allocataire = null,\n ): AutoAffectationRule {\n $autoAffectationRule = (new AutoAffectationRule())\n ->setTerritory($territory)\n ->setStatus($status)\n ->setPartnerType($partnerType)\n ->setProfileDeclarant($profileDeclarant)\n ->setInseeToInclude($inseeToInclude)\n ->setParc($parc)\n ->setAllocataire($allocataire);\n\n if (!empty($inseeToExclude)) {\n $autoAffectationRule->setInseeToExclude(array_map('trim', explode(',', $inseeToExclude)));\n }\n if (!empty($partnerToExclude)) {\n $autoAffectationRule->setPartnerToExclude(array_map('trim', explode(',', $partnerToExclude)));\n }\n\n return $autoAffectationRule;\n }", "smellKey": "S107", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "private function handleInvalidEndpoint(\n $cacheKey,\n $cmd,\n $identifiers,\n $isRequired,\n $originalUri,\n $request,\n $value,\n &$endpoint,\n &$g\n ) {\n $nextHandler = $this->nextHandler;\n $endpointList = self::$cache->get($cacheKey);\n if ($endpointList instanceof EndpointList) {\n\n // Remove invalid endpoint from cached list\n $endpointList->remove($endpoint);\n\n // If possible, get another cached endpoint\n $newEndpoint = $endpointList->getEndpoint();\n }\n if (empty($newEndpoint)) {\n\n // If no more cached endpoints, make discovery call\n // if none made within cooldown for given key\n if (time() - $this->discoveryTimes[$cacheKey]\n < self::$discoveryCooldown\n ) {\n\n // If no more cached endpoints and it's required,\n // fail with original exception\n if ($isRequired) {\n return $value;\n }\n\n // Use original endpoint if not required\n return $this->useOriginalUri(\n $originalUri,\n $cmd,\n $request\n );\n }\n\n $newEndpoint = $this->discoverEndpoint(\n $cacheKey,\n $cmd,\n $identifiers\n );\n }\n $endpoint = $newEndpoint;\n $request = $this->modifyRequest($request, $endpoint);\n return $nextHandler($cmd, $request)->otherwise($g);\n }", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) {\n\t\tif ($this->empty_string(trim($code))) {\n\t\t\treturn;\n\t\t}\n\t\trequire_once(dirname(__FILE__).'/2dbarcodes.php');\n\t\t// save current graphic settings\n\t\t$gvars = $this->getGraphicVars();\n\t\t// create new barcode object\n\t\t$barcodeobj = new TCPDF2DBarcode($code, $type);\n\t\t$arrcode = $barcodeobj->getBarcodeArray();\n\t\tif (($arrcode === false) OR empty($arrcode)) {\n\t\t\t$this->Error('Error in 2D barcode string');\n\t\t}\n\t\t// set default values\n\t\tif (!isset($style['position'])) {\n\t\t\t$style['position'] = '';\n\t\t}\n\t\tif (!isset($style['fgcolor'])) {\n\t\t\t$style['fgcolor'] = array(0,0,0); // default black\n\t\t}\n\t\tif (!isset($style['bgcolor'])) {\n\t\t\t$style['bgcolor'] = false; // default transparent\n\t\t}\n\t\tif (!isset($style['border'])) {\n\t\t\t$style['border'] = false;\n\t\t}\n\t\t// padding\n\t\tif (!isset($style['padding'])) {\n\t\t\t$style['padding'] = 0;\n\t\t} elseif ($style['padding'] === 'auto') {\n\t\t\t$style['padding'] = 4;\n\t\t}\n\t\tif (!isset($style['hpadding'])) {\n\t\t\t$style['hpadding'] = $style['padding'];\n\t\t} elseif ($style['hpadding'] === 'auto') {\n\t\t\t$style['hpadding'] = 4;\n\t\t}\n\t\tif (!isset($style['vpadding'])) {\n\t\t\t$style['vpadding'] = $style['padding'];\n\t\t} elseif ($style['vpadding'] === 'auto') {\n\t\t\t$style['vpadding'] = 4;\n\t\t}\n\t\t// cell (module) dimension\n\t\tif (!isset($style['module_width'])) {\n\t\t\t$style['module_width'] = 1; // width of a single module in points\n\t\t}\n\t\tif (!isset($style['module_height'])) {\n\t\t\t$style['module_height'] = 1; // height of a single module in points\n\t\t}\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($h, $x, $y);\n\t\t// number of barcode columns and rows\n\t\t$rows = $arrcode['num_rows'];\n\t\t$cols = $arrcode['num_cols'];\n\t\t// module width and height\n\t\t$mw = $style['module_width'];\n\t\t$mh = $style['module_height'];\n\t\t// get max dimensions\n\t\tif ($this->rtl) {\n\t\t\t$maxw = $x - $this->lMargin;\n\t\t} else {\n\t\t\t$maxw = $this->w - $this->rMargin - $x;\n\t\t}\n\t\t$maxh = ($this->h - $this->tMargin - $this->bMargin);\n\t\t$ratioHW = ($rows * $mh) / ($cols * $mw);\n\t\t$ratioWH = ($cols * $mw) / ($rows * $mh);\n\t\tif (!$distort) {\n\t\t\tif (($maxw * $ratioHW) > $maxh) {\n\t\t\t\t$maxw = $maxh * $ratioWH;\n\t\t\t}\n\t\t\tif (($maxh * $ratioWH) > $maxw) {\n\t\t\t\t$maxh = $maxw * $ratioHW;\n\t\t\t}\n\t\t}\n\t\t// set maximum dimesions\n\t\tif ($w > $maxw) {\n\t\t\t$w = $maxw;\n\t\t}\n\t\tif ($h > $maxh) {\n\t\t\t$h = $maxh;\n\t\t}\n\t\t$hpad = (2 * $style['hpadding']);\n\t\t$vpad = (2 * $style['vpadding']);\n\t\t// set dimensions\n\t\tif ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {\n\t\t\t$w = ($cols + $hpad) * ($mw / $this->k);\n\t\t\t$h = ($rows + $vpad) * ($mh / $this->k);\n\t\t} elseif (($w === '') OR ($w <= 0)) {\n\t\t\t$w = $h * $ratioWH;\n\t\t} elseif (($h === '') OR ($h <= 0)) {\n\t\t\t$h = $w * $ratioHW;\n\t\t}\n\t\t// barcode size (excluding padding)\n\t\t$bw = ($w * $cols) / ($cols + $hpad);\n\t\t$bh = ($h * $rows) / ($rows + $vpad);\n\t\t// dimension of single barcode cell unit\n\t\t$cw = $bw / $cols;\n\t\t$ch = $bh / $rows;\n\t\tif (!$distort) {\n\t\t\tif (($cw / $ch) > ($mw / $mh)) {\n\t\t\t\t// correct horizontal distortion\n\t\t\t\t$cw = $ch * $mw / $mh;\n\t\t\t\t$bw = $cw * $cols;\n\t\t\t\t$style['hpadding'] = ($w - $bw) / (2 * $cw);\n\t\t\t} else {\n\t\t\t\t// correct vertical distortion\n\t\t\t\t$ch = $cw * $mh / $mw;\n\t\t\t\t$bh = $ch * $rows;\n\t\t\t\t$style['vpadding'] = ($h - $bh) / (2 * $ch);\n\t\t\t}\n\t\t}\n\t\t// fit the barcode on available space\n\t\t$this->fitBlock($w, $h, $x, $y, false);\n\t\t// set alignment\n\t\t$this->img_rb_y = $y + $h;\n\t\t// set alignment\n\t\tif ($this->rtl) {\n\t\t\tif ($style['position'] == 'L') {\n\t\t\t\t$xpos = $this->lMargin;\n\t\t\t} elseif ($style['position'] == 'C') {\n\t\t\t\t$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($style['position'] == 'R') {\n\t\t\t\t$xpos = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xpos = $x - $w;\n\t\t\t}\n\t\t\t$this->img_rb_x = $xpos;\n\t\t} else {\n\t\t\tif ($style['position'] == 'L') {\n\t\t\t\t$xpos = $this->lMargin;\n\t\t\t} elseif ($style['position'] == 'C') {\n\t\t\t\t$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($style['position'] == 'R') {\n\t\t\t\t$xpos = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$xpos = $x;\n\t\t\t}\n\t\t\t$this->img_rb_x = $xpos + $w;\n\t\t}\n\t\t$xstart = $xpos + ($style['hpadding'] * $cw);\n\t\t$ystart = $y + ($style['vpadding'] * $ch);\n\t\t// barcode is always printed in LTR direction\n\t\t$tempRTL = $this->rtl;\n\t\t$this->rtl = false;\n\t\t// print background color\n\t\tif ($style['bgcolor']) {\n\t\t\t$this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);\n\t\t} elseif ($style['border']) {\n\t\t\t$this->Rect($xpos, $y, $w, $h, 'D');\n\t\t}\n\t\t// set foreground color\n\t\t$this->SetDrawColorArray($style['fgcolor']);\n\t\t// print barcode cells\n\t\t// for each row\n\t\tfor ($r = 0; $r < $rows; ++$r) {\n\t\t\t$xr = $xstart;\n\t\t\t// for each column\n\t\t\tfor ($c = 0; $c < $cols; ++$c) {\n\t\t\t\tif ($arrcode['bcode'][$r][$c] == 1) {\n\t\t\t\t\t// draw a single barcode cell\n\t\t\t\t\t$this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);\n\t\t\t\t}\n\t\t\t\t$xr += $cw;\n\t\t\t}\n\t\t\t$ystart += $ch;\n\t\t}\n\t\t// restore original direction\n\t\t$this->rtl = $tempRTL;\n\t\t// restore previous settings\n\t\t$this->setGraphicVars($gvars);\n\t\t// set pointer to align the next text/objects\n\t\tswitch($align) {\n\t\t\tcase 'T':{\n\t\t\t\t$this->y = $y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'M':{\n\t\t\t\t$this->y = $y + round($h/2);\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B':{\n\t\t\t\t$this->y = $this->img_rb_y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'N':{\n\t\t\t\t$this->SetY($this->img_rb_y);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$this->endlinex = $this->img_rb_x;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function __construct(\n $username = null,\n $password = null,\n $email_address = NO_EMAIL_ADDRESS_SET,\n $first_name = null,\n $middle_name = null,\n $last_name = null,\n $role_set = array(ROLE_ID_USER),\n $primary_role = ROLE_ID_USER,\n $organization_id = null,\n $person_id = null,\n array $ssoAttrs = array(),\n $sticky = false\n ) {\n\n $this->_pdo = DB::factory('database');\n\n $userCheck = $this->_pdo->query(\"SELECT id FROM Users WHERE username=:username\", array(\n ':username' => $username,\n ));\n\n if (count($userCheck) > 0 && $username != NULL) {\n\n $username = preg_replace('/^(.+);(.+)$/', '$1 ($2)', $username);\n\n throw new Exception(\"User $username already exists\");\n\n }\n\n $this->_id = NULL;\n\n $this->_account_is_active = true;\n\n $this->_username = $username;\n $this->_password = $password;\n\n if (self::userExistsWithEmailAddress($email_address) != INVALID) {\n throw new Exception(\"An XDMoD user with e-mail address $email_address exists\");\n }\n\n $this->_email = $email_address;\n\n $this->_firstName = $first_name;\n $this->_middleName = $middle_name;\n $this->_lastName = $last_name;\n\n $this->setRoles($role_set);\n\n // Role Checking ====================\n\n if (count($this->_roles) == 0) {\n throw new Exception(\"At least one role must be associated with this user\");\n }\n\n foreach ($this->_roles as $role) {\n\n if (self::_getFormalRoleName($role) == NULL) {\n throw new Exception(\"Unrecognized role $role\");\n }\n\n }\n\n // =================================\n\n $this->_timeCreated = date('Y-m-d H:i:s');\n $this->_timeUpdated = NULL;\n $this->_timePasswordUpdated = NULL;\n\n $this->_organizationID = $organization_id;\n\n // A person id of 0 is not allowed\n $this->_personID = $person_id == 0 ? NULL : $person_id; //This user MUST have a person_id mapping\n\n $this->_update_token = true;\n $this->_token = NULL;\n\n $this->sticky = $sticky;\n\n parent::__construct(\n Log::factory(\n 'xduser.sql',\n array(\n 'db' => false,\n 'mail' => false,\n 'console' => false,\n 'file'=> LOG_DIR . \"/\" . xd_utilities\\getConfiguration('general', 'exceptions_logfile')\n )\n )\n );\n\n $this->setSSOAttrs($ssoAttrs);\n }", "smellKey": "S107", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {\n\t\t$objstyle = '';\n\t\tif(!isset($svgstyle['opacity'])) {\n\t\t\treturn $objstyle;\n\t\t}\n\t\t// clip-path\n\t\t$regs = array();\n\t\tif (preg_match('/url\\([\\s]*\\#([^\\)]*)\\)/si', $svgstyle['clip-path'], $regs)) {\n\t\t\t$clip_path = $this->svgclippaths[$regs[1]];\n\t\t\tforeach ($clip_path as $cp) {\n\t\t\t\t$this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);\n\t\t\t}\n\t\t}\n\t\t// opacity\n\t\tif ($svgstyle['opacity'] != 1) {\n\t\t\t$this->SetAlpha($svgstyle['opacity']);\n\t\t}\n\t\t// color\n\t\t$fill_color = $this->convertHTMLColorToDec($svgstyle['color']);\n\t\t$this->SetFillColorArray($fill_color);\n\t\t// text color\n\t\t$text_color = $this->convertHTMLColorToDec($svgstyle['text-color']);\n\t\t$this->SetTextColorArray($text_color);\n\t\t// clip\n\t\tif (preg_match('/rect\\(([a-z0-9\\-\\.]*)[\\s]*([a-z0-9\\-\\.]*)[\\s]*([a-z0-9\\-\\.]*)[\\s]*([a-z0-9\\-\\.]*)\\)/si', $svgstyle['clip'], $regs)) {\n\t\t\t$top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);\n\t\t\t$right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);\n\t\t\t$bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);\n\t\t\t$left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);\n\t\t\t$cx = $x + $left;\n\t\t\t$cy = $y + $top;\n\t\t\t$cw = $w - $left - $right;\n\t\t\t$ch = $h - $top - $bottom;\n\t\t\tif ($svgstyle['clip-rule'] == 'evenodd') {\n\t\t\t\t$clip_rule = 'CNZ';\n\t\t\t} else {\n\t\t\t\t$clip_rule = 'CEO';\n\t\t\t}\n\t\t\t$this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());\n\t\t}\n\t\t// fill\n\t\t$regs = array();\n\t\tif (preg_match('/url\\([\\s]*\\#([^\\)]*)\\)/si', $svgstyle['fill'], $regs)) {\n\t\t\t// gradient\n\t\t\t$gradient = $this->svggradients[$regs[1]];\n\t\t\tif (isset($gradient['xref'])) {\n\t\t\t\t// reference to another gradient definition\n\t\t\t\t$newgradient = $this->svggradients[$gradient['xref']];\n\t\t\t\t$newgradient['coords'] = $gradient['coords'];\n\t\t\t\t$newgradient['mode'] = $gradient['mode'];\n\t\t\t\t$newgradient['gradientUnits'] = $gradient['gradientUnits'];\n\t\t\t\tif (isset($gradient['gradientTransform'])) {\n\t\t\t\t\t$newgradient['gradientTransform'] = $gradient['gradientTransform'];\n\t\t\t\t}\n\t\t\t\t$gradient = $newgradient;\n\t\t\t}\n\t\t\t//save current Graphic State\n\t\t\t$this->_out('q');\n\t\t\t//set clipping area\n\t\t\tif (!empty($clip_function) AND method_exists($this, $clip_function)) {\n\t\t\t\t$bbox = call_user_func_array(array($this, $clip_function), $clip_params);\n\t\t\t\tif (is_array($bbox) AND (count($bbox) == 4)) {\n\t\t\t\t\tlist($x, $y, $w, $h) = $bbox;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($gradient['mode'] == 'measure') {\n\t\t\t\tif (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {\n\t\t\t\t\t$gtm = $gradient['gradientTransform'];\n\t\t\t\t\t// apply transformation matrix\n\t\t\t\t\t$xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];\n\t\t\t\t\t$ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];\n\t\t\t\t\t$xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];\n\t\t\t\t\t$yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];\n\t\t\t\t\tif (isset($gradient['coords'][4])) {\n\t\t\t\t\t\t$gradient['coords'][4] = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));\n\t\t\t\t\t}\n\t\t\t\t\t$gradient['coords'][0] = $xa;\n\t\t\t\t\t$gradient['coords'][1] = $ya;\n\t\t\t\t\t$gradient['coords'][2] = $xb;\n\t\t\t\t\t$gradient['coords'][3] = $yb;\n\n\t\t\t\t}\n\t\t\t\t// convert SVG coordinates to user units\n\t\t\t\t$gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);\n\t\t\t\t$gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);\n\t\t\t\t$gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);\n\t\t\t\t$gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);\n\t\t\t\tif (isset($gradient['coords'][4])) {\n\t\t\t\t\t$gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);\n\t\t\t\t}\n\t\t\t\t// shift units\n\t\t\t\tif ($gradient['gradientUnits'] == 'objectBoundingBox') {\n\t\t\t\t\t// convert to SVG coordinate system\n\t\t\t\t\t$gradient['coords'][0] += $x;\n\t\t\t\t\t$gradient['coords'][1] += $y;\n\t\t\t\t\t$gradient['coords'][2] += $x;\n\t\t\t\t\t$gradient['coords'][3] += $y;\n\t\t\t\t}\n\t\t\t\t// calculate percentages\n\t\t\t\t$gradient['coords'][0] = ($gradient['coords'][0] - $x) / $w;\n\t\t\t\t$gradient['coords'][1] = ($gradient['coords'][1] - $y) / $h;\n\t\t\t\t$gradient['coords'][2] = ($gradient['coords'][2] - $x) / $w;\n\t\t\t\t$gradient['coords'][3] = ($gradient['coords'][3] - $y) / $h;\n\t\t\t\tif (isset($gradient['coords'][4])) {\n\t\t\t\t\t$gradient['coords'][4] /= $w;\n\t\t\t\t}\n\t\t\t\t// fix values\n\t\t\t\tforeach($gradient['coords'] as $key => $val) {\n\t\t\t\t\tif ($val < 0) {\n\t\t\t\t\t\t$gradient['coords'][$key] = 0;\n\t\t\t\t\t} elseif ($val > 1) {\n\t\t\t\t\t\t$gradient['coords'][$key] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {\n\t\t\t\t\t// single color (no shading)\n\t\t\t\t\t$gradient['coords'][0] = 1;\n\t\t\t\t\t$gradient['coords'][1] = 0;\n\t\t\t\t\t$gradient['coords'][2] = 0.999;\n\t\t\t\t\t$gradient['coords'][3] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// swap Y coordinates\n\t\t\t$tmp = $gradient['coords'][1];\n\t\t\t$gradient['coords'][1] = $gradient['coords'][3];\n\t\t\t$gradient['coords'][3] = $tmp;\n\t\t\t// set transformation map for gradient\n\t\t\tif (($gradient['type'] == 3) AND ($gradient['mode'] == 'measure')) {\n\t\t\t\t// gradient is always circular\n\t\t\t\t$cy = $this->h - $y - ($gradient['coords'][1] * ($w + $h));\n\t\t\t\t$this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $w*$this->k, $x*$this->k, $cy*$this->k));\n\t\t\t} else {\n\t\t\t\t$this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k));\n\t\t\t}\n\t\t\tif (count($gradient['stops']) > 1) {\n\t\t\t\t$this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);\n\t\t\t}\n\t\t} elseif ($svgstyle['fill'] != 'none') {\n\t\t\t$fill_color = $this->convertHTMLColorToDec($svgstyle['fill']);\n\t\t\tif ($svgstyle['fill-opacity'] != 1) {\n\t\t\t\t$this->SetAlpha($svgstyle['fill-opacity']);\n\t\t\t}\n\t\t\t$this->SetFillColorArray($fill_color);\n\t\t\tif ($svgstyle['fill-rule'] == 'evenodd') {\n\t\t\t\t$objstyle .= 'F*';\n\t\t\t} else {\n\t\t\t\t$objstyle .= 'F';\n\t\t\t}\n\t\t}\n\t\t// stroke\n\t\tif ($svgstyle['stroke'] != 'none') {\n\t\t\t$stroke_style = array(\n\t\t\t\t'color' => $this->convertHTMLColorToDec($svgstyle['stroke']),\n\t\t\t\t'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),\n\t\t\t\t'cap' => $svgstyle['stroke-linecap'],\n\t\t\t\t'join' => $svgstyle['stroke-linejoin']\n\t\t\t\t);\n\t\t\tif (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {\n\t\t\t\t$stroke_style['dash'] = $svgstyle['stroke-dasharray'];\n\t\t\t}\n\t\t\t$this->SetLineStyle($stroke_style);\n\t\t\t$objstyle .= 'D';\n\t\t}\n\t\t// font\n\t\t$regs = array();\n\t\tif (!empty($svgstyle['font'])) {\n\t\t\tif (preg_match('/font-family[\\s]*:[\\s]*([^\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_family = $this->getFontFamilyName($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_family = $svgstyle['font-family'];\n\t\t\t}\n\t\t\tif (preg_match('/font-size[\\s]*:[\\s]*([^\\s\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_size = trim($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_size = $svgstyle['font-size'];\n\t\t\t}\n\t\t\tif (preg_match('/font-style[\\s]*:[\\s]*([^\\s\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_style = trim($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_style = $svgstyle['font-style'];\n\t\t\t}\n\t\t\tif (preg_match('/font-weight[\\s]*:[\\s]*([^\\s\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_weight = trim($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_weight = $svgstyle['font-weight'];\n\t\t\t}\n\t\t\tif (preg_match('/font-stretch[\\s]*:[\\s]*([^\\s\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_stretch = trim($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_stretch = $svgstyle['font-stretch'];\n\t\t\t}\n\t\t\tif (preg_match('/letter-spacing[\\s]*:[\\s]*([^\\s\\;\\\"]*)/si', $svgstyle['font'], $regs)) {\n\t\t\t\t$font_spacing = trim($regs[1]);\n\t\t\t} else {\n\t\t\t\t$font_spacing = $svgstyle['letter-spacing'];\n\t\t\t}\n\t\t} else {\n\t\t\t$font_family = $this->getFontFamilyName($svgstyle['font-family']);\n\t\t\t$font_size = $svgstyle['font-size'];\n\t\t\t$font_style = $svgstyle['font-style'];\n\t\t\t$font_weight = $svgstyle['font-weight'];\n\t\t\t$font_stretch = $svgstyle['font-stretch'];\n\t\t\t$font_spacing = $svgstyle['letter-spacing'];\n\t\t}\n\t\t$font_size = $this->getHTMLUnitToUnits($font_size, $prevsvgstyle['font-size'], $this->svgunit, false) * $this->k;\n\t\t$font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);\n\t\t$font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);\n\t\tswitch ($font_style) {\n\t\t\tcase 'italic': {\n\t\t\t\t$font_style = 'I';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'oblique': {\n\t\t\t\t$font_style = 'I';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'normal': {\n\t\t\t\t$font_style = '';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tswitch ($font_weight) {\n\t\t\tcase 'bold':\n\t\t\tcase 'bolder': {\n\t\t\t\t$font_style .= 'B';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tswitch ($svgstyle['text-decoration']) {\n\t\t\tcase 'underline': {\n\t\t\t\t$font_style .= 'U';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'overline': {\n\t\t\t\t$font_style .= 'O';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'line-through': {\n\t\t\t\t$font_style .= 'D';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'none': {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$this->SetFont($font_family, $font_style, $font_size);\n\t\t$this->setFontStretching($font_stretch);\n\t\t$this->setFontSpacing($font_spacing);\n\t\treturn $objstyle;\n\t}", "smellKey": "S107", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct(Tree $tree,\n\t\tView $view,\n\t\tISystemTagManager $tagManager,\n\t\tISystemTagObjectMapper $tagMapper,\n\t\tITagManager $fileTagger,\n\t\tIUserSession $userSession,\n\t\tIGroupManager $groupManager,\n\t\tFolder $userFolder,\n\t\tIAppManager $appManager\n\t) {\n\t\t$this->tree = $tree;\n\t\t$this->fileView = $view;\n\t\t$this->tagManager = $tagManager;\n\t\t$this->tagMapper = $tagMapper;\n\t\t$this->fileTagger = $fileTagger;\n\t\t$this->userSession = $userSession;\n\t\t$this->groupManager = $groupManager;\n\t\t$this->userFolder = $userFolder;\n\t\t$this->appManager = $appManager;\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function __construct($c, $ct, $desc, $fee, $justify, $modifiers, $units, $mod_size, $selected = true)\n {\n parent::__construct($c, $ct, $desc, $selected);\n $this->fee = $fee;\n $this->justify = $justify;\n $this->modifiers = $modifiers;\n $this->units = $units;\n $this->mod_size = $mod_size;\n }", "smellKey": "S107", "smellId": null, "repo": "hendrik-buchwald-sonarsource_openemr", "language": "php"} {"function": "function __construct(\n $dest_db,\n $source_db,\n $pre_ingest_update_statements,\n $source_query,\n $insert_table,\n $insert_fields = array(),\n $post_ingest_update_statements = array(),\n $delete_statement = null,\n $count_statement = null\n ) {\n $this->_destination_db = $dest_db;\n $this->_source_db = $source_db;\n $this->_source_query = $source_query;\n $this->_insert_fields = $insert_fields;\n $this->_insert_table = $insert_table;\n $this->_pre_ingest_update_statements = $pre_ingest_update_statements;\n $this->_post_ingest_update_statements = $post_ingest_update_statements;\n $this->_delete_statement = $delete_statement;\n $this->_count_statement = $count_statement;\n $this->_logger = Log::singleton('null');\n\n if ($this->_destination_db->_db_engine == 'mysql') {\n $this->_dest_helper = MySQLHelper::factory($this->_destination_db);\n }\n }", "smellKey": "S107", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, string $type, array $attributes, array $orders, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n $db = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($db->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $count = $dbForProject->count('indexes', [\n Query::equal('collectionInternalId', [$collection->getInternalId()]),\n Query::equal('databaseInternalId', [$db->getInternalId()])\n ], 61);\n\n $limit = $dbForProject->getLimitForIndexes();\n\n if ($count >= $limit) {\n throw new Exception(Exception::INDEX_LIMIT_EXCEEDED, 'Index limit exceeded');\n }\n\n // Convert Document[] to array of attribute metadata\n $oldAttributes = \\array_map(fn($a) => $a->getArrayCopy(), $collection->getAttribute('attributes'));\n\n $oldAttributes[] = [\n 'key' => '$id',\n 'type' => Database::VAR_STRING,\n 'status' => 'available',\n 'required' => true,\n 'array' => false,\n 'default' => null,\n 'size' => 36\n ];\n\n $oldAttributes[] = [\n 'key' => '$createdAt',\n 'type' => Database::VAR_DATETIME,\n 'status' => 'available',\n 'signed' => false,\n 'required' => false,\n 'array' => false,\n 'default' => null,\n 'size' => 0\n ];\n\n $oldAttributes[] = [\n 'key' => '$updatedAt',\n 'type' => Database::VAR_DATETIME,\n 'status' => 'available',\n 'signed' => false,\n 'required' => false,\n 'array' => false,\n 'default' => null,\n 'size' => 0\n ];\n\n // lengths hidden by default\n $lengths = [];\n\n foreach ($attributes as $i => $attribute) {\n // find attribute metadata in collection document\n $attributeIndex = \\array_search($attribute, array_column($oldAttributes, 'key'));\n\n if ($attributeIndex === false) {\n throw new Exception(Exception::ATTRIBUTE_UNKNOWN, 'Unknown attribute: ' . $attribute);\n }\n\n $attributeStatus = $oldAttributes[$attributeIndex]['status'];\n $attributeType = $oldAttributes[$attributeIndex]['type'];\n $attributeSize = $oldAttributes[$attributeIndex]['size'];\n\n if ($attributeType === Database::VAR_RELATIONSHIP) {\n throw new Exception(Exception::ATTRIBUTE_TYPE_INVALID, 'Cannot create an index for a relationship attribute: ' . $oldAttributes[$attributeIndex]['key']);\n }\n\n // ensure attribute is available\n if ($attributeStatus !== 'available') {\n throw new Exception(Exception::ATTRIBUTE_NOT_AVAILABLE, 'Attribute not available: ' . $oldAttributes[$attributeIndex]['key']);\n }\n\n // set attribute size as index length only for strings\n $lengths[$i] = ($attributeType === Database::VAR_STRING) ? $attributeSize : null;\n }\n\n $index = new Document([\n '$id' => ID::custom($db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key),\n 'key' => $key,\n 'status' => 'processing', // processing, available, failed, deleting, stuck\n 'databaseInternalId' => $db->getInternalId(),\n 'databaseId' => $databaseId,\n 'collectionInternalId' => $collection->getInternalId(),\n 'collectionId' => $collectionId,\n 'type' => $type,\n 'attributes' => $attributes,\n 'lengths' => $lengths,\n 'orders' => $orders,\n ]);\n\n $validator = new IndexValidator($dbForProject->getAdapter()->getMaxIndexLength());\n if (!$validator->isValid($collection->setAttribute('indexes', $index, Document::SET_TYPE_APPEND))) {\n throw new Exception(Exception::INDEX_INVALID, $validator->getDescription());\n }\n\n try {\n $index = $dbForProject->createDocument('indexes', $index);\n } catch (DuplicateException) {\n throw new Exception(Exception::INDEX_ALREADY_EXISTS);\n }\n\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId);\n\n $database\n ->setType(DATABASE_TYPE_CREATE_INDEX)\n ->setDatabase($db)\n ->setCollection($collection)\n ->setDocument($index);\n\n $events\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('indexId', $index->getId())\n ->setContext('collection', $collection)\n ->setContext('database', $db);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($index, Response::MODEL_INDEX);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n TranslatableNotificationHandlerInterface $notificationHandler,\n RoleService $roleService,\n RoleCreateMapper $roleCreateMapper,\n RoleCopyMapper $roleCopyMapper,\n RoleUpdateMapper $roleUpdateMapper,\n FormFactory $formFactory,\n SubmitHandler $submitHandler,\n ConfigResolverInterface $configResolver\n ) {\n $this->notificationHandler = $notificationHandler;\n $this->roleService = $roleService;\n $this->roleCreateMapper = $roleCreateMapper;\n $this->roleCopyMapper = $roleCopyMapper;\n $this->roleUpdateMapper = $roleUpdateMapper;\n $this->formFactory = $formFactory;\n $this->submitHandler = $submitHandler;\n $this->configResolver = $configResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct(\n Visitor $outputVisitor,\n JsonOutputGenerator $outputGenerator,\n ContentTypeInfoListValueObjectVisitor $contentTypeInfoListValueObjectVisitor,\n SubitemsListValueObjectVisitor $subitemsListValueObjectVisitor,\n LocationService $locationService,\n ContentService $contentService,\n ContentTypeService $contentTypeService,\n PermissionResolver $permissionResolver,\n ContentTypeMappings $contentTypeMappings,\n UserSettingService $userSettingService,\n QueryFactoryInterface $queryFactory,\n SearchService $searchService\n ) {\n $this->outputVisitor = $outputVisitor;\n $this->outputGenerator = $outputGenerator;\n $this->contentTypeInfoListValueObjectVisitor = $contentTypeInfoListValueObjectVisitor;\n $this->subitemsListValueObjectVisitor = $subitemsListValueObjectVisitor;\n $this->locationService = $locationService;\n $this->contentService = $contentService;\n $this->contentTypeService = $contentTypeService;\n $this->permissionResolver = $permissionResolver;\n $this->contentTypeMappings = $contentTypeMappings;\n $this->userSettingService = $userSettingService;\n $this->queryFactory = $queryFactory;\n $this->searchService = $searchService;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function __construct($pn, $tn, $cn, $pk = false, $ft = FM_TYPE_UNKNOWN, $fs = 0, $dv = null, $iai = null)\n {\n $this->PropertyName = $pn;\n $this->TableName = $tn;\n $this->ColumnName = $cn;\n $this->IsPrimaryKey = $pk;\n $this->FieldType = $ft;\n $this->FieldSize = $fs;\n $this->DefaultValue = $dv;\n $this->IsAutoInsert = $iai;\n }", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function relevanssi_process_tax_query_row(\n\tarray $row,\n\tbool $is_sub_row,\n\tstring $global_relation,\n\tstring $query_restrictions,\n\tstring $tax_query_relation,\n\tarray $term_tax_ids,\n\tarray $not_term_tax_ids,\n\tarray $and_term_tax_ids,\n\tarray $exist_queries\n): array {\n\tglobal $wpdb;\n\n\t$local_term_tax_ids = array();\n\t$local_not_term_tax_ids = array();\n\t$local_and_term_tax_ids = array();\n\t$term_tax_id = array();\n\n\t$exists_query = false;\n\tif ( isset( $row['operator'] ) && ( 'exists' === strtolower( $row['operator'] ) || 'not exists' === strtolower( $row['operator'] ) ) ) {\n\t\t$exists_query = true;\n\t}\n\n\tif ( $exists_query ) {\n\t\t$row['field'] = 'exists';\n\t}\n\tif ( ! isset( $row['field'] ) ) {\n\t\t$row['field'] = 'term_id'; // In case 'field' is not set, go with the WP default of 'term_id'.\n\t}\n\t$row['field'] = strtolower( $row['field'] ); // In some cases, you can get 'ID' instead of 'id'.\n\n\tif ( in_array( $row['field'], array( 'slug', 'name', 'id', 'term_id' ), true ) ) {\n\t\t$term_tax_id = relevanssi_term_tax_id_from_row( $row );\n\t}\n\n\tif ( 'term_taxonomy_id' === $row['field'] ) {\n\t\tif ( ! is_array( $row['terms'] ) ) {\n\t\t\t$row['terms'] = array( $row['terms'] );\n\t\t}\n\t\t$term_tax_id = array_filter( $row['terms'], 'is_numeric' );\n\t}\n\n\tif ( ! $exists_query && ( ! isset( $row['include_children'] ) || true === $row['include_children'] ) ) {\n\t\tforeach ( $term_tax_id as $t_id ) {\n\t\t\t$t_term = get_term_by( 'term_taxonomy_id', $t_id, $row['taxonomy'] );\n\t\t\t$t_id = $t_term->term_id;\n\t\t\t$kids = get_term_children( $t_id, $row['taxonomy'] );\n\t\t\tforeach ( $kids as $kid ) {\n\t\t\t\t$kid_term_tax_id = relevanssi_get_term_tax_id( $kid, $row['taxonomy'] );\n\t\t\t\tif ( $kid_term_tax_id ) {\n\t\t\t\t\t// In some weird cases, this may be null. See: https://wordpress.org/support/topic/childrens-of-chosen-product_cat-not-showing-up/.\n\t\t\t\t\t$term_tax_id[] = $kid_term_tax_id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t$term_tax_id = array_unique( $term_tax_id );\n\tif ( ! empty( $term_tax_id ) ) {\n\t\t$n = count( $term_tax_id );\n\t\t$term_tax_id = implode( ',', $term_tax_id );\n\n\t\t$tq_operator = 'IN'; // Assuming the default operator \"IN\", unless something else is provided.\n\t\tif ( isset( $row['operator'] ) ) {\n\t\t\t$tq_operator = strtoupper( $row['operator'] );\n\t\t}\n\t\tif ( ! in_array( $tq_operator, array( 'IN', 'NOT IN', 'AND' ), true ) ) {\n\t\t\t$tq_operator = 'IN';\n\t\t}\n\t\tif ( 'and' === $tax_query_relation ) {\n\t\t\tif ( 'AND' === $tq_operator ) {\n\t\t\t\t$query_restrictions .= \" AND relevanssi.doc IN (\n\t\t\t\t\tSELECT ID FROM $wpdb->posts WHERE 1=1\n\t\t\t\t\tAND (\n\t\t\t\t\t\tSELECT COUNT(1)\n\t\t\t\t\t\tFROM $wpdb->term_relationships AS tr\n\t\t\t\t\t\tWHERE tr.term_taxonomy_id IN ($term_tax_id)\n\t\t\t\t\t\tAND tr.object_id = $wpdb->posts.ID ) = $n\n\t\t\t\t\t)\";\n\t\t\t\t// Clean: $term_tax_id and $n are Relevanssi-generated.\n\t\t\t} elseif ( 'or' === $global_relation ) {\n\t\t\t\t$local_and_term_tax_ids[] = $term_tax_id;\n\t\t\t} else {\n\t\t\t\t$query_restrictions .= \" AND relevanssi.doc $tq_operator (\n\t\t\t\t\tSELECT DISTINCT(tr.object_id)\n\t\t\t\t\t\tFROM $wpdb->term_relationships AS tr\n\t\t\t\t\t\tWHERE tr.term_taxonomy_id IN ($term_tax_id))\";\n\t\t\t\t// Clean: all variables are Relevanssi-generated.\n\t\t\t}\n\t\t} else {\n\t\t\tif ( 'IN' === $tq_operator ) {\n\t\t\t\t$local_term_tax_ids[] = $term_tax_id;\n\t\t\t}\n\t\t\tif ( 'NOT IN' === $tq_operator ) {\n\t\t\t\t$local_not_term_tax_ids[] = $term_tax_id;\n\t\t\t}\n\t\t\tif ( 'AND' === $tq_operator ) {\n\t\t\t\t$local_and_term_tax_ids[] = $term_tax_id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tglobal $wp_query;\n\t\t$wp_query->is_category = false;\n\t}\n\n\t$copy_term_tax_ids = false;\n\tif ( ! $is_sub_row ) {\n\t\t$copy_term_tax_ids = true;\n\t}\n\tif ( $is_sub_row && ( 'or' === $global_relation || 'or' === $tax_query_relation ) ) {\n\t\t$copy_term_tax_ids = true;\n\t}\n\n\tif ( $copy_term_tax_ids ) {\n\t\t$term_tax_ids = array_merge( $term_tax_ids, $local_term_tax_ids );\n\t\t$not_term_tax_ids = array_merge( $not_term_tax_ids, $local_not_term_tax_ids );\n\t\t$and_term_tax_ids = array_merge( $and_term_tax_ids, $local_and_term_tax_ids );\n\t}\n\n\tif ( $exists_query ) {\n\t\t$taxonomy = $row['taxonomy'];\n\t\t$operator = 'IN';\n\t\tif ( 'not exists' === strtolower( $row['operator'] ) ) {\n\t\t\t$operator = 'NOT IN';\n\t\t}\n\t\t$exist_query_sql = \" relevanssi.doc $operator (\n\t\t\t\tSELECT DISTINCT(tr.object_id)\n\t\t\t\tFROM $wpdb->term_relationships AS tr, $wpdb->term_taxonomy AS tt\n\t\t\t\tWHERE tr.term_taxonomy_id = tt.term_taxonomy_id\n\t\t\t\tAND tt.taxonomy = '$taxonomy' )\";\n\t\t$exist_queries[] = $exist_query_sql;\n\t\tif ( 'and' === $tax_query_relation ) {\n\t\t\t$query_restrictions .= ' AND ' . $exist_query_sql;\n\t\t}\n\t}\n\n\treturn array(\n\t\t$query_restrictions,\n\t\t$term_tax_ids,\n\t\t$not_term_tax_ids,\n\t\t$and_term_tax_ids,\n\t\t$exist_queries,\n\t);\n}", "smellKey": "S107", "smellId": null, "repo": "Roland-s-Demo-Org_ACCESS-NYC", "language": "php"} {"function": "public function creerDossierMMG($client, $ref_dos, $t1, $poids, \n\t\t\t\t\t\t\t\t\t\t$ref_fact, $horse, $trailer_1, $trailer_2, \n\t\t\t\t\t\t\t\t\t\t$num_lic, $num_exo, $klsa_arriv, $crossing_date, \n\t\t\t\t\t\t\t\t\t\t$wiski_arriv, $wiski_dep, $insp_report, $ir, \n\t\t\t\t\t\t\t\t\t\t$ref_crf, $date_crf, $ref_decl, $dgda_in, \n\t\t\t\t\t\t\t\t\t\t$ref_liq, $date_liq, $ref_quit, $date_quit, \n\t\t\t\t\t\t\t\t\t\t$dgda_out, $regul_ir, $cleared, $statut, $remarque, \n\t\t\t\t\t\t\t\t\t\t$id_mod_lic, $id_util){\n\t\t\tinclude('connexion.php');\n\n\t\t\t$entree['client'] = $client;$entree['ref_dos'] = $ref_dos;\n\t\t\t$entree['t1'] = $t1;$entree['poids'] = $poids;\n\t\t\t$entree['ref_fact'] = $ref_fact;$entree['horse'] = $horse;\n\t\t\t$entree['trailer_1'] = $trailer_1;$entree['trailer_2'] = $trailer_2;\n\t\t\t$entree['num_lic'] = $num_lic;$entree['num_exo'] = $num_exo;\n\t\t\t$entree['klsa_arriv'] = $klsa_arriv;$entree['crossing_date'] = $crossing_date;\n\t\t\t$entree['wiski_arriv'] = $wiski_arriv;$entree['wiski_dep'] = $wiski_dep;\n\t\t\t$entree['insp_report'] = $insp_report;$entree['ir'] = $ir;\n\t\t\t$entree['ref_crf'] = $ref_crf;$entree['date_crf'] = $date_crf;\n\t\t\t$entree['ref_decl'] = $ref_decl;$entree['dgda_in'] = $dgda_in;\n\t\t\t$entree['ref_liq'] = $ref_liq;$entree['date_liq'] = $date_liq;\n\t\t\t$entree['ref_quit'] = $ref_quit;$entree['date_quit'] = $date_quit;\n\t\t\t$entree['dgda_out'] = $dgda_out;$entree['regul_ir'] = $regul_ir;\n\t\t\t$entree['cleared'] = $cleared;$entree['statut'] = $statut;$entree['remarque'] = $remarque;\n\t\t\t$entree['id_mod_lic'] = $id_mod_lic;$entree['id_util'] = $id_util;\n\n\t\t\t/*echo '
    ----
    client = '.$client;\n\t\t\techo '
    ref_dos = '.$ref_dos;\n\t\t\techo '
    t1 = '.$t1;\n\t\t\techo '
    poids = '.$poids;\n\t\t\techo '
    ref_fact = '.$ref_fact;\n\t\t\techo '
    horse = '.$horse;\n\t\t\techo '
    trailer_1 = '.$trailer_1;\n\t\t\techo '
    trailer_2 = '.$trailer_2;\n\t\t\techo '
    num_lic = '.$num_lic;\n\t\t\techo '
    num_exo = '.$num_exo;\n\t\t\techo '
    klsa_arriv = '.$klsa_arriv;\n\t\t\techo '
    crossing_date = '.$crossing_date;\n\t\t\techo '
    wiski_arriv = '.$wiski_arriv;\n\t\t\techo '
    wiski_dep = '.$wiski_dep;\n\t\t\techo '
    insp_report = '.$insp_report;\n\t\t\techo '
    ir = '.$ir;\n\t\t\techo '
    ref_crf = '.$ref_crf;\n\t\t\techo '
    date_crf = '.$date_crf;\n\t\t\techo '
    ref_decl = '.$ref_decl;\n\t\t\techo '
    dgda_in = '.$dgda_in;\n\t\t\techo '
    ref_liq = '.$ref_liq;\n\t\t\techo '
    date_liq = '.$date_liq;\n\t\t\techo '
    ref_quit = '.$ref_quit;\n\t\t\techo '
    date_quit = '.$date_quit;\n\t\t\techo '
    dgda_out = '.$dgda_out;\n\t\t\techo '
    regul_ir = '.$regul_ir;\n\t\t\techo '
    cleared = '.$cleared;\n\t\t\techo '
    statut = '.$statut;\n\t\t\techo '
    remarque = '.$remarque;*/\n\n\t\t\t$requete = $connexion-> prepare('INSERT INTO dossier_upload_tracking(client, ref_dos, t1, poids, ref_fact, horse, trailer_1, trailer_2, num_lic, num_exo, klsa_arriv, crossing_date, wiski_arriv, wiski_dep, insp_report, ir, ref_crf, date_crf, ref_decl, dgda_in, ref_liq, date_liq, ref_quit, date_quit, dgda_out, regul_ir, cleared, statut, remarque, id_mod_lic, id_util) \n\t\t\t\t\t\t\t\t\t\t\t\tVALUES(?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?, ?, \n\t\t\t\t\t\t\t\t\t\t\t\t\t?, ?, ?)');\n\t\t\t$requete-> execute(array($entree['client'], $entree['ref_dos'], $entree['t1'], $entree['poids'], $entree['ref_fact'], $entree['horse'], $entree['trailer_1'], $entree['trailer_2'], $entree['num_lic'], $entree['num_exo'], $entree['klsa_arriv'], $entree['crossing_date'], $entree['wiski_arriv'], $entree['wiski_dep'], $entree['insp_report'], $entree['ir'], $entree['ref_crf'], $entree['date_crf'], $entree['ref_decl'], $entree['dgda_in'], $entree['ref_liq'], $entree['date_liq'], $entree['ref_quit'], $entree['date_quit'], $entree['dgda_out'], $entree['regul_ir'], $entree['cleared'], $entree['statut'], $entree['remarque'], $entree['id_mod_lic'], $entree['id_util']));\n\t\t\t\n\t\t\t//$this-> creerDateExpirationLicence($num_lic, $date_exp);\n\t\t}", "smellKey": "S107", "smellId": null, "repo": "otace1_malabar-erp", "language": "php"} {"function": "function aff_notice($id, $nocart=0, $gen_header=1, $use_cache=0, $mode_aff_notice=\"\", $depliable=\"\", $nodocnum=0, $enrichment=1, $recherche_ajax_mode=0, $show_map=1, $template_directory = \"\") {\n\n\tglobal $liens_opac;\n\tglobal $opac_notices_format;\n\tglobal $opac_notices_depliable;\n\tglobal $opac_cart_allow;\n\tglobal $opac_cart_only_for_subscriber;\n\tglobal $opac_notice_affichage_class;\n\tglobal $opac_notice_enrichment;\n\tglobal $opac_recherche_ajax_mode;\n\tglobal $opac_notices_format_onglets;\n\tglobal $lvl,$search_type_asked;\n\tglobal $record_css_already_included; // Pour pas inclure la css 10 fois\n\tglobal $opac_rgaa_active;\n\t\n\t$retour_aff = \"\";\n\tif ((($opac_cart_allow)&&(!$opac_cart_only_for_subscriber))||(($opac_cart_allow)&&($_SESSION[\"user_code\"]))) {\n\t\t$cart=1; \n\t} else {\n\t\t$cart=0;\n\t}\n\tif ($nocart) $cart=0;\n\t$id = intval($id);\n\t//Recherche des fonctions d'affichage\n\t$entete='';\n\t$recordmodes = record_display_modes::get_instance();\n\tif($recordmodes && $id==-1){\n\t\t$entete.=$recordmodes->show_mode_selector();\n\t}\n\t\n\t$f=get_aff_function();\n\tif ($f) return $entete.$f($id,$cart,$gen_header,$use_cache,$mode_aff_notice,$depliable,$nodocnum,$enrichment,$recherche_ajax_mode,$show_map,$recordmodes);\n\t\n\tif ($id>0) {\n\t\tif ($mode_aff_notice !== \"\") $type_aff=$mode_aff_notice;\n\t\telse $type_aff=$opac_notices_format;\n\t\t\n\t\tif ($depliable === \"\") $depliable=$opac_notices_depliable;\n\n\t\tif ($type_aff != AFF_ETA_NOTICES_TEMPLATE_DJANGO) {\n\t\t\t$header_only=0;\n\t\t\tif($recherche_ajax_mode && $opac_recherche_ajax_mode){\n\t\t\t\t//Si ajax, on ne charge pas tout\n\t\t\t\t$header_only=1;\n\t\t\t}\n\t\t\t$class_affichage_to_call = $opac_notice_affichage_class;\n\t\t\tif (!$class_affichage_to_call) $class_affichage_to_call=\"notice_affichage\";\n\t\t\t$current = new $class_affichage_to_call($id,$liens_opac,$cart,0,$header_only,!$gen_header, $show_map);\n\t\t\tif($nodocnum) $current->docnum_allowed = 0;\n\t\t\t\n\t\t\tif ($gen_header) $current->do_header();\n\t\t\n\t\t\tif(!$current->visu_notice){\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\t\tif($opac_recherche_ajax_mode && $recherche_ajax_mode && $depliable && $type_aff!=AFF_ETA_NOTICES_REDUIT && $type_aff!=AFF_ETA_NOTICES_TEMPLATE_DJANGO){\n\t\t\t$current->genere_ajax($type_aff,0) ;\n\t\t\t$retour_aff .= $current->result ;\n\t\t}else{\n\t\t\t$flag_no_onglet_perso = 0;\n\t\t\tswitch ($type_aff) {\n\t\t\t\tcase AFF_ETA_NOTICES_REDUIT :\n\t\t\t\t\t$retour_aff .= $current->notice_header_with_link.\"
    \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_ISBD :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->genere_simple($depliable, 'ISBD') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_PUBLIC :\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_simple($depliable, 'PUBLIC') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak;\n\t\t\t\tcase AFF_ETA_NOTICES_BOTH :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_double($depliable, 'PUBLIC') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase AFF_ETA_NOTICES_BOTH_ISBD_FIRST :\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\n\t\t\t\t\t$current->genere_double($depliable, 'ISBD') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase AFF_ETA_NOTICES_TEMPLATE_DJANGO :\n\t\t\t\t\tglobal $include_path;\n\t\t\t\t\tglobal $opac_notices_format_django_directory;\n\t\t\t\t\t\n\t\t\t\t\tif (!$opac_notices_format_django_directory) $opac_notices_format_django_directory = \"common\";\n\t\t\t\t\t\n\t\t\t\t\tif (!$record_css_already_included) {\n\t\t\t\t\t\tif (file_exists($include_path.\"/templates/record/\".$opac_notices_format_django_directory.\"/styles/style.css\")) {\n\t\t\t\t\t\t\t$retour_aff .= \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$record_css_already_included = true;\n\t\t\t\t\t}\n\t\t\t\t\t// Si on l'appelle par le tag {% etagere_see %}, on veut tout le temps le rduit...\n\t\t\t\t\t$trace = debug_backtrace();\n\t\t\t\t\t$count_trace = count($trace);\n\t\t\t\t\t$from_etagesee_tag = false;\n\t\t\t\t\t$from_recordsee_tag = false;\n\t\t\t\t\t\n\t\t\t\t\tfor ($i = 2; $i < $count_trace; $i++) {\n\t\t\t\t\t\tif (isset($trace[$i]['object']) && get_class($trace[$i]['object']) === \"Etageresee_Tag\") {\n\t\t\t\t\t\t\t$from_etagesee_tag=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isset($trace[$i]['object']) && get_class($trace[$i]['object']) === \"Recordsee_Tag\") {\n\t\t\t\t\t\t\t$from_recordsee_tag=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif($from_etagesee_tag === true){\n\t\t\t\t\t\t$retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t}elseif($from_recordsee_tag === true){\n\t\t\t\t\t\t$retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tswitch ($lvl) {\n\t\t\t\t\t\t\tcase 'notice_display' :\n\t\t\t\t\t\t\t\t$from_serial_analysis = false;\n\t\t\t\t\t\t\t\tif(!empty($_GET['id']) && $_GET['id'] != $id) {\n\t\t\t\t\t\t\t\t\tif(notice::get_niveau_biblio($_GET['id']) == 's' && notice::get_niveau_biblio($id) == 'a') {\n\t\t\t\t\t\t\t\t\t\t$from_serial_analysis = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif($from_serial_analysis) {\n\t\t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_extended($id, $template_directory);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'bulletin_display' :\n\t\t\t\t\t\t\tcase 'resa' :\n\t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_extended($id, $template_directory);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'more_result' :\n\t\t\t\t\t\t\tdefault :\n\t\t\t\t\t\t\t\tif($search_type_asked=='perio_a2z'){\n\t\t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_extended($id, $template_directory);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$retour_aff .= record_display::get_display_in_result($id, $template_directory);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t$current->do_isbd();\n\t\t\t\t\t$current->do_public();\t\t\t\t\t\n\t\t\t\t\t$current->genere_double($depliable, 'autre') ;\n\t\t\t\t\t$retour_aff .= $current->result ;\n\t\t\t\t\t$flag_no_onglet_perso=1;\n\t\t\t\t\tbreak ;\n\t\t\t\t\t\n\t\t\t}\n\t\t\n\t/*\t\t\t\n\t\t\t$onglets_title=\"\";\n\t\t\t$onglets_content=\"\";\n\t\t\tif($opac_notices_format_onglets){\n\t\t\t\t$onglets=explode(\",\", $opac_notices_format_onglets);\n\t\t\t\tforeach($onglets as $id_tpl){\n\t\t\t\t\t$notice_onglet=new notice_onglet($id_tpl);\n\t\t\t\t\t$onglets_title.=\"\n\t\t\t\t\t
  • \n\t\t\t\t\t\tget_onglet_header().\"\\\" onclick=\\\"show_what('tpl_\".$id_tpl.\"_', '$id'); return false;\\\">\".$notice_onglet->get_onglet_header().\"\n\t\t\t\t\t
  • \";\n\t\t\n\t\t\t\t\t$onglets_content.=\"\n\t\t\t\t\t\";\n\t\t\t\t}\n\t\t\t}\t\n\t\t\t$retour_aff=str_replace('', $onglets_title, $retour_aff);\n\t\t\t$retour_aff=str_replace('', $onglets_content, $retour_aff);\n\t\t\t\t\n\t*/\t\t\t\n\t\t\tif(!$flag_no_onglet_perso){\n\t\t\t\t$onglet_perso=new notice_onglets();\n\t\t\t\t$retour_aff=$onglet_perso->insert_onglets($id,$retour_aff);\n\t\t\t}\n\t\t\tif(!$depliable && $opac_notice_enrichment && $enrichment==1){\n\t\t\t\t$retour_aff.=\"\";\n\t\t\t}\n\t\t}\n\t\tif($opac_rgaa_active){\n\t\t\tif(strpos($retour_aff, '
    ') === false){\n\t\t\t\t$retour_aff =\"
    \". $retour_aff.\"
    \";\n\t\t\t}\n\t\t}\n\t}\t\n\treturn $entete.$retour_aff;\n}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function (string $projectId, string $platformId, string $name, string $key, string $store, string $hostname, Response $response, Database $dbForConsole) {\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $platform = $dbForConsole->findOne('platforms', [\n Query::equal('$id', [$platformId]),\n Query::equal('projectInternalId', [$project->getInternalId()]),\n ]);\n\n if ($platform === false || $platform->isEmpty()) {\n throw new Exception(Exception::PLATFORM_NOT_FOUND);\n }\n\n $platform\n ->setAttribute('name', $name)\n ->setAttribute('key', $key)\n ->setAttribute('store', $store)\n ->setAttribute('hostname', $hostname);\n\n $dbForConsole->updateDocument('platforms', $platform->getId(), $platform);\n\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response->dynamic($platform, Response::MODEL_PLATFORM);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "static public function add($name, $title, $body, $player_id, $php, $enable_tinymce, $access, &$errors)\n\t{\n\t\tglobal $db;\n\t\tif (isset($name[0]) && isset($title[0]) && isset($body[0]) && $player_id != 0) {\n\t\t\t$query = $db->select(TABLE_PREFIX . 'pages', array('name' => $name));\n\t\t\tif ($query === false)\n\t\t\t\t$db->insert(TABLE_PREFIX . 'pages',\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'name' => $name,\n\t\t\t\t\t\t'title' => $title,\n\t\t\t\t\t\t'body' => $body,\n\t\t\t\t\t\t'player_id' => $player_id,\n\t\t\t\t\t\t'php' => $php ? '1' : '0',\n\t\t\t\t\t\t'enable_tinymce' => $enable_tinymce ? '1' : '0',\n\t\t\t\t\t\t'access' => $access\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\telse\n\t\t\t\t$errors[] = 'Page with this link already exists.';\n\t\t} else\n\t\t\t$errors[] = 'Please fill all inputs.';\n\n\t\treturn !count($errors);\n\t}", "smellKey": "S107", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function __construct(\n Repository $repository,\n UserService $userService,\n LocationService $locationService,\n UserProfileConfigurationInterface $configuration,\n PermissionResolver $permissionResolver,\n LanguageService $languageService,\n ActionDispatcherInterface $userActionDispatcher,\n GroupedContentFormFieldsProviderInterface $groupedContentFormFieldsProvider\n ) {\n $this->repository = $repository;\n $this->userService = $userService;\n $this->locationService = $locationService;\n $this->configuration = $configuration;\n $this->permissionResolver = $permissionResolver;\n $this->languageService = $languageService;\n $this->userActionDispatcher = $userActionDispatcher;\n $this->groupedContentFormFieldsProvider = $groupedContentFormFieldsProvider;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function ajoutRdv($num, $intervenant, $date, $commentaire, $matiere, $duree, $bsb, $idgoogle)\n\t{\n\t\t$req = \"INSERT INTO `\".PdoBD::$villeExtranet.\"_rdvparents` VALUES ('', :num, :intervenant, :date, :commentaire, :matiere, :duree, :bsb, :idgoogle);\";\n\t\t$params = array(\n\t\t\t':num' => $num,\n\t\t\t':intervenant' => $intervenant,\n\t\t\t':date' => $date,\n\t\t\t':commentaire' => addslashes($commentaire),\n\t\t\t':matiere' => $matiere,\n\t\t\t':duree' => $duree,\n\t\t\t':bsb' => $bsb,\n\t\t\t':idgoogle' => $idgoogle\n\t\t);\n\t\t$rs = $this->NonQuery($req, $params);\n\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de l'insertion du rdv dans la base de données.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S107", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "protected function handle_file_upload($uploaded_file, $name, $original_name, $subfolder, $size, $type, $error,\n $index = null, $content_range = null) {\n\n $file = new \\stdClass();\n $file->name = $this->get_file_name($uploaded_file, $name, $subfolder, $size, $type, $error,\n $index, $content_range);\n $file->size = $this->fix_integer_overflow((int)$size);\n $file->size_total = $file->size;\n $file->type = $type;\n $file->original_name = $original_name;\n $file->subfolder = $subfolder;\n\n //check max allowed file name - 255 bytes\n if(strlen($file->name)>255){\n $file->error = $this->get_error_message('file_name_too_big');\n return $file;\n }\n\n if(!$this->options['unique_filename']){\n // Keep an existing filename if this is part of a chunked upload:\n $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]);\n\n $new_file_path = $this->get_upload_path($name, $subfolder);\n\n if(is_file($new_file_path) && $uploaded_bytes !== $this->get_file_size($new_file_path))\n { //file with the same name exists\n\n // 3 - ignore if already file with such name already exist\n if($this->options['replace_edited_file']==3){\n\n $file->error = $this->get_error_message('skip_same_name2');\n return $file;\n\n }else{\n $old_md5 = 0;\n $new_md5 = 0;\n\n $old_md5 = md5_file($uploaded_file);\n $new_md5 = md5_file($new_file_path);\n if($old_md5==$new_md5){\n //skip - this file is quite the same\n $file->error = $this->get_error_message('skip_same_name');\n return $file;\n }\n // 2 - create unique file if modified\n if($this->options['replace_edited_file']==2){\n\n $this->options['unique_filename'] = true;\n\n $file->name = $this->get_file_name($uploaded_file, $name, $subfolder, $size, $type, $error,\n $index, $content_range);\n\n $this->options['unique_filename'] = false;\n }\n // 1 - overwrtie if modified (with same name and different checksum)\n }\n }\n }\n\n\n\n\n if ($this->validate($uploaded_file, $file, $error, $index)) {\n $this->handle_form_data($file, $index);\n $upload_dir = $this->get_upload_path('', $file->subfolder);\n if (!is_dir($upload_dir)) {\n mkdir($upload_dir, $this->options['mkdir_mode'], true);\n }\n $file_path = $this->get_upload_path($file->name, $file->subfolder);\n $append_file = $content_range && is_file($file_path) &&\n $file->size > $this->get_file_size($file_path);\n if ($uploaded_file && is_uploaded_file($uploaded_file) && file_exists($uploaded_file)) {\n // multipart/formdata uploads (POST method uploads)\n if ($append_file) {\n file_put_contents(\n $file_path,\n fopen($uploaded_file, 'r'),\n FILE_APPEND\n );\n } else {\n $res = move_uploaded_file($uploaded_file, $file_path);\n }\n } else {\n // Non-multipart uploads (PUT method support)\n /*\n Artem Osmakov 2024-06-23 HEURIST DOES NOT USE THIS MODE\n file_put_contents(\n $file_path,\n fopen($this->options['input_stream'], 'r'),\n $append_file ? FILE_APPEND : 0\n );\n */\n }\n\n //file does not exist\n if(!is_file($file_path)){\n $file->error = 'File is not uploaded';//$this->get_error_message('skip_same_name');\n return $file;\n }\n\n\n $file_size = $this->get_file_size($file_path, $append_file);\n if ($file_size === $file->size) {\n $file->url = $this->get_download_url($file->name, $file->subfolder);\n if ($this->is_valid_image_file($file_path)) {\n $this->handle_image_file($file_path, $file);\n }\n } else {\n $file->size = $file_size;\n if (!$content_range && $this->options['discard_aborted_uploads']) {\n if(file_exists($file_path)){\n unlink($file_path);\n }\n $file->error = $this->get_error_message('abort');\n }\n }\n $this->set_additional_file_properties($file);\n }\n return $file;\n }", "smellKey": "S107", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function generateSequenceID()\n {\n return generate_id();\n }", "smellKey": "S107", "smellId": null, "repo": "hendrik-buchwald-sonarsource_openemr", "language": "php"} {"function": "function finderiv_bsm($type, $strike, $mat, $today, $spot, $rf, $vol, $ans , $fmt=\"F j, Y\" ) {\n\tif (!is_numeric($vol) || $vol<=0) {\n\t\techo 'finderiv_bsm: vol must be greater than 0';\n\t\treturn false;\n\t}\n\tif (!is_numeric($spot) || $spot<=0) {\n\t\techo 'finderiv_bsm: spot must be greater than 0';\n\t\treturn false;\n\t}\n\tif (!is_numeric($strike) || $strike<=0) {\n\t\techo 'finderiv_bsm: strike must be greater than 0.';\n\t\treturn false;\n\t}\n\tif (!is_numeric($rf) || $rf<0) {\n\t\techo 'finderiv_bsm: rf must be greater than or equal to zero';\n\t\treturn false;\n\t}\n\tif (strcasecmp($type,\"call\")!=0 && strcasecmp($type,\"put\")!=0) {\n\t\techo 'finderiv_bsm: option type must be call or put.';\n\t\treturn false;\n\t}\n\t$todaydate = date_create_from_format($fmt,$today);\n\tif ($todaydate==false) {\n\t\techo \"finderiv_bsm::could not create today's date from string.\";\n\t\techo \"The date is \" . $today. \" and the format is \" . $fmt . \".\";\n\t\treturn false;\n\t}\n\n\t$matdate = date_create_from_format($fmt,$mat);\n\tif ($matdate==false) {\n\t\techo \"finderiv_bsm::could not create maturity date from string.\";\n\t\techo \"The date is \" . $mat . \" and the format is \" . $fmt . \".\";\n\t\treturn false;\n\t}\n\n\tif ($todaydate>$matdate) {\n\t\techo \"finderiv_bsm:: Option maturity is in the past. Maturity date is less than today.\";\n\t\treturn false;\n\t}\n\t$matdays = ($todaydate->diff($matdate))->format(\"%r%a\");\n\n\t$mat = $matdays/365;\n\t$d1 = (log($spot/$strike)+($rf+pow($vol,2)/2)*$mat)/($vol*sqrt($mat));\n\t$d2 = $d1-$vol*sqrt($mat);\n\trequire_once \"stats.php\";\n\tswitch (strtoupper($ans)) {\n\t\tcase \"VALUE\":\n\t\t\tif (strcasecmp($type,\"call\")==0) {\n\t\t\t\t$answer = $spot*normalcdf($d1,16)-$strike*exp(-$rf*$mat)*normalcdf($d2,16);\n\t\t\t} elseif(strcasecmp($type,\"put\")==0) {\n\t\t\t\t$answer =\t$strike*exp(-$rf*$mat)*normalcdf(-$d2,16)-$spot*normalcdf(-$d1,16);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"DELTA\":\n\t\t\tif (strcasecmp($type,\"call\")==0) {\n\t\t\t\t$answer = normalcdf($d1,16);\n\t\t\t} elseif(strcasecmp($type,\"put\")==0) {\n\t\t\t\t$answer = normalcdf($d1,16)-1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"GAMMA\":\n\t\t\t$answer = 1/sqrt(2*M_PI)*exp(-.5*pow($d1,2))/($spot*$vol*sqrt($mat));\n\t\t\tbreak;\n\t\tcase \"VEGA\":\n\t\t\t$answer = 1/sqrt(2*M_PI)*exp(-.5*pow($d1,2))*$spot*sqrt($mat)/100;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\techo \"finderiv_bsm:: the answer type must be value, delta, gamma or vega.\";\n\t\t\treturn false;\n\t}\t\n\treturn $answer;\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {\n\t\t// check if all required parameters are set\n\t\tif ($shareWith === null ||\n\t\t\t$name === null ||\n\t\t\t$providerId === null ||\n\t\t\t$owner === null ||\n\t\t\t$resourceType === null ||\n\t\t\t$shareType === null ||\n\t\t\t!is_array($protocol) ||\n\t\t\t!isset($protocol['name']) ||\n\t\t\t!isset($protocol['options']) ||\n\t\t\t!is_array($protocol['options']) ||\n\t\t\t!isset($protocol['options']['sharedSecret'])\n\t\t) {\n\t\t\treturn new JSONResponse(\n\t\t\t\t[\n\t\t\t\t\t'message' => 'Missing arguments',\n\t\t\t\t\t'validationErrors' => [],\n\t\t\t\t],\n\t\t\t\tHttp::STATUS_BAD_REQUEST\n\t\t\t);\n\t\t}\n\n\t\t$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);\n\t\tif (!in_array($shareType, $supportedShareTypes)) {\n\t\t\treturn new JSONResponse(\n\t\t\t\t['message' => 'Share type \"' . $shareType . '\" not implemented'],\n\t\t\t\tHttp::STATUS_NOT_IMPLEMENTED\n\t\t\t);\n\t\t}\n\n\t\t$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);\n\t\t$shareWith = $cloudId->getUser();\n\n\t\tif ($shareType === 'user') {\n\t\t\t$shareWith = $this->mapUid($shareWith);\n\n\t\t\tif (!$this->userManager->userExists($shareWith)) {\n\t\t\t\t$response = new JSONResponse(\n\t\t\t\t\t[\n\t\t\t\t\t\t'message' => 'User \"' . $shareWith . '\" does not exists at ' . $this->urlGenerator->getBaseUrl(),\n\t\t\t\t\t\t'validationErrors' => [],\n\t\t\t\t\t],\n\t\t\t\t\tHttp::STATUS_BAD_REQUEST\n\t\t\t\t);\n\t\t\t\t$response->throttle();\n\t\t\t\treturn $response;\n\t\t\t}\n\t\t}\n\n\t\tif ($shareType === 'group') {\n\t\t\tif (!$this->groupManager->groupExists($shareWith)) {\n\t\t\t\t$response = new JSONResponse(\n\t\t\t\t\t[\n\t\t\t\t\t\t'message' => 'Group \"' . $shareWith . '\" does not exists at ' . $this->urlGenerator->getBaseUrl(),\n\t\t\t\t\t\t'validationErrors' => [],\n\t\t\t\t\t],\n\t\t\t\t\tHttp::STATUS_BAD_REQUEST\n\t\t\t\t);\n\t\t\t\t$response->throttle();\n\t\t\t\treturn $response;\n\t\t\t}\n\t\t}\n\n\t\t// if no explicit display name is given, we use the uid as display name\n\t\t$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;\n\t\t$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;\n\n\t\t// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner\n\t\tif ($sharedBy === null) {\n\t\t\t$sharedBy = $owner;\n\t\t\t$sharedByDisplayName = $ownerDisplayName;\n\t\t}\n\n\t\ttry {\n\t\t\t$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);\n\t\t\t$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);\n\t\t\t$share->setProtocol($protocol);\n\t\t\t$provider->shareReceived($share);\n\t\t} catch (ProviderDoesNotExistsException|ProviderCouldNotAddShareException $e) {\n\t\t\treturn new JSONResponse(\n\t\t\t\t['message' => $e->getMessage()],\n\t\t\t\tHttp::STATUS_NOT_IMPLEMENTED\n\t\t\t);\n\t\t} catch (\\Exception $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new JSONResponse(\n\t\t\t\t[\n\t\t\t\t\t'message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl(),\n\t\t\t\t\t'validationErrors' => [],\n\t\t\t\t],\n\t\t\t\tHttp::STATUS_BAD_REQUEST\n\t\t\t);\n\t\t}\n\n\t\t$user = $this->userManager->get($shareWith);\n\t\t$recipientDisplayName = '';\n\t\tif ($user) {\n\t\t\t$recipientDisplayName = $user->getDisplayName();\n\t\t}\n\n\t\treturn new JSONResponse(\n\t\t\t['recipientDisplayName' => $recipientDisplayName],\n\t\t\tHttp::STATUS_CREATED);\n\t}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function conversionUnits2ScreenReader2($number1,$units1,$dimensions1,$number2,$units2,$dimensions2,$sign=\"=\",$tick=\"y\",$html=\"n\"){\n\n $tick = verifyTickMarks($tick);\n $exponentWord = _(\"exponent\");\n $retval1 = conversionUnit2ScreenReaderModification($units1,$tick);\n $retval2 = conversionUnit2ScreenReaderModification($units2,$tick);\n\n $unit1 = _($retval1[0]);\n $unitSR1 = $retval1[1]; // does this need a gettext option for foreign language screen readers\n\n $unit2 = _($retval2[0]);\n $unitSR2 = $retval2[1]; // does this need a gettext option for foreign language screen readers\n\n if($dimensions1==1) {\n if($dimensions2==1) {\n return htmlwarning($html).\"\n \n $number1 $unitSR1 $sign $number2 $unitSR2 \";\n } else {\n return htmlwarning($html).\"\n \n $number1 $unitSR1 $sign $number2 $unitSR2 $exponentWord $dimensions2\";\n }\n } else {\n if($dimensions2==1) {\n return htmlwarning($html).\"\n \n $number1 $unitSR1 $exponentWord $dimensions1 $sign $number2 $unitSR2\";\n }\n else {\n return htmlwarning($html).\"\n \n $number1 $unitSR1 $exponentWord $dimensions1 $sign $number2 $unitSR2 $exponentWord $dimensions2\";\n }\n }\n}", "smellKey": "S107", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {\n\t\t// replace 'NO-BREAK SPACE' (U+00A0) character with a simple space\n\t\t$txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);\n\t\t$prev_cell_margin = $this->cell_margin;\n\t\t$prev_cell_padding = $this->cell_padding;\n\t\t$txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);\n\t\t$rs = ''; //string to be returned\n\t\t$this->adjustCellPadding($border);\n\t\tif (!$ignore_min_height) {\n\t\t\t$min_cell_height = $this->getCellHeight($this->FontSize);\n\t\t\tif ($h < $min_cell_height) {\n\t\t\t\t$h = $min_cell_height;\n\t\t\t}\n\t\t}\n\t\t$k = $this->k;\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\tlist($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);\n\t\tif ($this->rtl) {\n\t\t\t$x = $this->x - $this->cell_margin['R'];\n\t\t} else {\n\t\t\t$x = $this->x + $this->cell_margin['L'];\n\t\t}\n\t\t$y = $this->y + $this->cell_margin['T'];\n\t\t$prev_font_stretching = $this->font_stretching;\n\t\t$prev_font_spacing = $this->font_spacing;\n\t\t// cell vertical alignment\n\t\tswitch ($calign) {\n\t\t\tcase 'A': {\n\t\t\t\t// font top\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= $this->cell_padding['T'];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h - $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'L': {\n\t\t\t\t// font baseline\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= ($this->cell_padding['T'] + $this->FontAscent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B'] - $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h + $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'D': {\n\t\t\t\t// font bottom\n\t\t\t\tswitch ($valign) {\n\t\t\t\t\tcase 'T': {\n\t\t\t\t\t\t// top\n\t\t\t\t\t\t$y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'B': {\n\t\t\t\t\t\t// bottom\n\t\t\t\t\t\t$y -= ($h - $this->cell_padding['B']);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\tcase 'C':\n\t\t\t\t\tcase 'M': {\n\t\t\t\t\t\t// center\n\t\t\t\t\t\t$y -= (($h + $this->FontAscent + $this->FontDescent) / 2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B': {\n\t\t\t\t// cell bottom\n\t\t\t\t$y -= $h;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\tcase 'M': {\n\t\t\t\t// cell center\n\t\t\t\t$y -= ($h / 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'T': {\n\t\t\t\t// cell top\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// text vertical alignment\n\t\tswitch ($valign) {\n\t\t\tcase 'T': {\n\t\t\t\t// top\n\t\t\t\t$yt = $y + $this->cell_padding['T'];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B': {\n\t\t\t\t// bottom\n\t\t\t\t$yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase 'C':\n\t\t\tcase 'M': {\n\t\t\t\t// center\n\t\t\t\t$yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$basefonty = $yt + $this->FontAscent;\n\t\tif (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {\n\t\t\tif ($this->rtl) {\n\t\t\t\t$w = $x - $this->lMargin;\n\t\t\t} else {\n\t\t\t\t$w = $this->w - $this->rMargin - $x;\n\t\t\t}\n\t\t}\n\t\t$s = '';\n\t\t// fill and borders\n\t\tif (is_string($border) AND (strlen($border) == 4)) {\n\t\t\t// full border\n\t\t\t$border = 1;\n\t\t}\n\t\tif ($fill OR ($border == 1)) {\n\t\t\tif ($fill) {\n\t\t\t\t$op = ($border == 1) ? 'B' : 'f';\n\t\t\t} else {\n\t\t\t\t$op = 'S';\n\t\t\t}\n\t\t\tif ($this->rtl) {\n\t\t\t\t$xk = (($x - $w) * $k);\n\t\t\t} else {\n\t\t\t\t$xk = ($x * $k);\n\t\t\t}\n\t\t\t$s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);\n\t\t}\n\t\t// draw borders\n\t\t$s .= $this->getCellBorder($x, $y, $w, $h, $border);\n\t\tif ($txt != '') {\n\t\t\t$txt2 = $txt;\n\t\t\tif ($this->isunicode) {\n\t\t\t\tif (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {\n\t\t\t\t\t$txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);\n\t\t\t\t} else {\n\t\t\t\t\t$unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values\n\t\t\t\t\t$unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t\t// replace thai chars (if any)\n\t\t\t\t\tif (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {\n\t\t\t\t\t\t// number of chars\n\t\t\t\t\t\t$numchars = count($unicode);\n\t\t\t\t\t\t// po pla, for far, for fan\n\t\t\t\t\t\t$longtail = array(0x0e1b, 0x0e1d, 0x0e1f);\n\t\t\t\t\t\t// do chada, to patak\n\t\t\t\t\t\t$lowtail = array(0x0e0e, 0x0e0f);\n\t\t\t\t\t\t// mai hun arkad, sara i, sara ii, sara ue, sara uee\n\t\t\t\t\t\t$upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);\n\t\t\t\t\t\t// mai ek, mai tho, mai tri, mai chattawa, karan\n\t\t\t\t\t\t$tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);\n\t\t\t\t\t\t// sara u, sara uu, pinthu\n\t\t\t\t\t\t$lowvowel = array(0x0e38, 0x0e39, 0x0e3a);\n\t\t\t\t\t\t$output = array();\n\t\t\t\t\t\tfor ($i = 0; $i < $numchars; $i++) {\n\t\t\t\t\t\t\tif (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {\n\t\t\t\t\t\t\t\t$ch0 = $unicode[$i];\n\t\t\t\t\t\t\t\t$ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;\n\t\t\t\t\t\t\t\t$ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;\n\t\t\t\t\t\t\t\t$chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;\n\t\t\t\t\t\t\t\tif (in_array($ch0, $tonemark)) {\n\t\t\t\t\t\t\t\t\tif ($chn == 0x0e33) {\n\t\t\t\t\t\t\t\t\t\t// sara um\n\t\t\t\t\t\t\t\t\t\tif (in_array($ch1, $longtail)) {\n\t\t\t\t\t\t\t\t\t\t\t// tonemark at upper left\n\t\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t// tonemark at upper right (normal position)\n\t\t\t\t\t\t\t\t\t\t\t$output[] = $ch0;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {\n\t\t\t\t\t\t\t\t\t\t// tonemark at lower left\n\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));\n\t\t\t\t\t\t\t\t\t} elseif (in_array($ch1, $upvowel)) {\n\t\t\t\t\t\t\t\t\t\tif (in_array($ch2, $longtail)) {\n\t\t\t\t\t\t\t\t\t\t\t// tonemark at upper left\n\t\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t// tonemark at upper right (normal position)\n\t\t\t\t\t\t\t\t\t\t\t$output[] = $ch0;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// tonemark at lower right\n\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {\n\t\t\t\t\t\t\t\t\t// add lower left nikhahit and sara aa\n\t\t\t\t\t\t\t\t\tif ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {\n\t\t\t\t\t\t\t\t\t\t$output[] = 0xf711;\n\t\t\t\t\t\t\t\t\t\t$this->CurrentFont['subsetchars'][0xf711] = true;\n\t\t\t\t\t\t\t\t\t\t$output[] = 0x0e32;\n\t\t\t\t\t\t\t\t\t\t$this->CurrentFont['subsetchars'][0x0e32] = true;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t$output[] = $ch0;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} elseif (in_array($ch1, $longtail)) {\n\t\t\t\t\t\t\t\t\tif ($ch0 == 0x0e31) {\n\t\t\t\t\t\t\t\t\t\t// lower left mai hun arkad\n\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, 0xf710);\n\t\t\t\t\t\t\t\t\t} elseif (in_array($ch0, $upvowel)) {\n\t\t\t\t\t\t\t\t\t\t// lower left\n\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));\n\t\t\t\t\t\t\t\t\t} elseif ($ch0 == 0x0e47) {\n\t\t\t\t\t\t\t\t\t\t// lower left mai tai koo\n\t\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, 0xf712);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// normal character\n\t\t\t\t\t\t\t\t\t\t$output[] = $ch0;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {\n\t\t\t\t\t\t\t\t\t// lower vowel\n\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));\n\t\t\t\t\t\t\t\t} elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {\n\t\t\t\t\t\t\t\t\t// yo ying without lower part\n\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, 0xf70f);\n\t\t\t\t\t\t\t\t} elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {\n\t\t\t\t\t\t\t\t\t// tho santan without lower part\n\t\t\t\t\t\t\t\t\t$output[] = $this->replaceChar($ch0, 0xf700);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$output[] = $ch0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// non-thai character\n\t\t\t\t\t\t\t\t$output[] = $unicode[$i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$unicode = $output;\n\t\t\t\t\t\t// update font subsetchars\n\t\t\t\t\t\t$this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);\n\t\t\t\t\t} // end of K_THAI_TOPCHARS\n\t\t\t\t\t$txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$txt2 = TCPDF_STATIC::_escape($txt2);\n\t\t\t// get current text width (considering general font stretching and spacing)\n\t\t\t$txwidth = $this->GetStringWidth($txt);\n\t\t\t$width = $txwidth;\n\t\t\t// check for stretch mode\n\t\t\tif ($stretch > 0) {\n\t\t\t\t// calculate ratio between cell width and text width\n\t\t\t\tif ($width <= 0) {\n\t\t\t\t\t$ratio = 1;\n\t\t\t\t} else {\n\t\t\t\t\t$ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);\n\t\t\t\t}\n\t\t\t\t// check if stretching is required\n\t\t\t\tif (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {\n\t\t\t\t\t// the text will be stretched to fit cell width\n\t\t\t\t\tif ($stretch > 2) {\n\t\t\t\t\t\t// set new character spacing\n\t\t\t\t\t\t$this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// set new horizontal stretching\n\t\t\t\t\t\t$this->font_stretching *= $ratio;\n\t\t\t\t\t}\n\t\t\t\t\t// recalculate text width (the text fills the entire cell)\n\t\t\t\t\t$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];\n\t\t\t\t\t// reset alignment\n\t\t\t\t\t$align = '';\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t// apply font stretching\n\t\t\t\t$rs .= sprintf('BT %F Tz ET ', $this->font_stretching);\n\t\t\t}\n\t\t\tif ($this->font_spacing != 0) {\n\t\t\t\t// increase/decrease font spacing\n\t\t\t\t$rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));\n\t\t\t}\n\t\t\tif ($this->ColorFlag AND ($this->textrendermode < 4)) {\n\t\t\t\t$s .= 'q '.$this->TextColor.' ';\n\t\t\t}\n\t\t\t// rendering mode\n\t\t\t$s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));\n\t\t\t// count number of spaces\n\t\t\t$ns = substr_count($txt, chr(32));\n\t\t\t// Justification\n\t\t\t$spacewidth = 0;\n\t\t\tif (($align == 'J') AND ($ns > 0)) {\n\t\t\t\tif ($this->isUnicodeFont()) {\n\t\t\t\t\t// get string width without spaces\n\t\t\t\t\t$width = $this->GetStringWidth(str_replace(' ', '', $txt));\n\t\t\t\t\t// calculate average space width\n\t\t\t\t\t$spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);\n\t\t\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t\t\t// word spacing is affected by stretching\n\t\t\t\t\t\t$spacewidth /= ($this->font_stretching / 100);\n\t\t\t\t\t}\n\t\t\t\t\t// set word position to be used with TJ operator\n\t\t\t\t\t$txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);\n\t\t\t\t\t$unicode_justification = true;\n\t\t\t\t} else {\n\t\t\t\t\t// get string width\n\t\t\t\t\t$width = $txwidth;\n\t\t\t\t\t// new space width\n\t\t\t\t\t$spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;\n\t\t\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t\t\t// word spacing (Tw) is affected by stretching\n\t\t\t\t\t\t$spacewidth /= ($this->font_stretching / 100);\n\t\t\t\t\t}\n\t\t\t\t\t// set word spacing\n\t\t\t\t\t$rs .= sprintf('BT %F Tw ET ', $spacewidth);\n\t\t\t\t}\n\t\t\t\t$width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];\n\t\t\t}\n\t\t\t// replace carriage return characters\n\t\t\t$txt2 = str_replace(\"\\r\", ' ', $txt2);\n\t\t\tswitch ($align) {\n\t\t\t\tcase 'C': {\n\t\t\t\t\t$dx = ($w - $width) / 2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'R': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $this->cell_padding['R'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $w - $width - $this->cell_padding['R'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'L': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $w - $width - $this->cell_padding['L'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $this->cell_padding['L'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'J':\n\t\t\t\tdefault: {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$dx = $this->cell_padding['R'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$dx = $this->cell_padding['L'];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->rtl) {\n\t\t\t\t$xdx = $x - $dx - $width;\n\t\t\t} else {\n\t\t\t\t$xdx = $x + $dx;\n\t\t\t}\n\t\t\t$xdk = $xdx * $k;\n\t\t\t// print text\n\t\t\t$s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);\n\t\t\tif (isset($uniblock)) {\n\t\t\t\t// print overlapping characters as separate string\n\t\t\t\t$xshift = 0; // horizontal shift\n\t\t\t\t$ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);\n\t\t\t\t$spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));\n\t\t\t\tforeach ($uniblock as $uk => $uniarr) {\n\t\t\t\t\tif (($uk % 2) == 0) {\n\t\t\t\t\t\t// x space to skip\n\t\t\t\t\t\tif ($spacewidth != 0) {\n\t\t\t\t\t\t\t// justification shift\n\t\t\t\t\t\t\t$xshift += (count(array_keys($uniarr, 32)) * $spw);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$xshift += $this->GetArrStringWidth($uniarr); // + shift justification\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// character to print\n\t\t\t\t\t\t$topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);\n\t\t\t\t\t\t$topchr = TCPDF_STATIC::_escape($topchr);\n\t\t\t\t\t\t$s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($this->underline) {\n\t\t\t\t$s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->linethrough) {\n\t\t\t\t$s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->overline) {\n\t\t\t\t$s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);\n\t\t\t}\n\t\t\tif ($this->ColorFlag AND ($this->textrendermode < 4)) {\n\t\t\t\t$s .= ' Q';\n\t\t\t}\n\t\t\tif ($link) {\n\t\t\t\t$this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);\n\t\t\t}\n\t\t}\n\t\t// output cell\n\t\tif ($s) {\n\t\t\t// output cell\n\t\t\t$rs .= $s;\n\t\t\tif ($this->font_spacing != 0) {\n\t\t\t\t// reset font spacing mode\n\t\t\t\t$rs .= ' BT 0 Tc ET';\n\t\t\t}\n\t\t\tif ($this->font_stretching != 100) {\n\t\t\t\t// reset font stretching mode\n\t\t\t\t$rs .= ' BT 100 Tz ET';\n\t\t\t}\n\t\t}\n\t\t// reset word spacing\n\t\tif (!$this->isUnicodeFont() AND ($align == 'J')) {\n\t\t\t$rs .= ' BT 0 Tw ET';\n\t\t}\n\t\t// reset stretching and spacing\n\t\t$this->font_stretching = $prev_font_stretching;\n\t\t$this->font_spacing = $prev_font_spacing;\n\t\t$this->lasth = $h;\n\t\tif ($ln > 0) {\n\t\t\t//Go to the beginning of the next line\n\t\t\t$this->y = $y + $h + $this->cell_margin['B'];\n\t\t\tif ($ln == 1) {\n\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t$this->x = $this->w - $this->rMargin;\n\t\t\t\t} else {\n\t\t\t\t\t$this->x = $this->lMargin;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// go left or right by case\n\t\t\tif ($this->rtl) {\n\t\t\t\t$this->x = $x - $w - $this->cell_margin['L'];\n\t\t\t} else {\n\t\t\t\t$this->x = $x + $w + $this->cell_margin['R'];\n\t\t\t}\n\t\t}\n\t\t$gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.\"\\n\";\n\t\t$rs = $gstyles.$rs;\n\t\t$this->cell_padding = $prev_cell_padding;\n\t\t$this->cell_margin = $prev_cell_margin;\n\t\treturn $rs;\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "public function __construct(\n\t\t?string $outNumClasse,\n\t\t?string $outCodTipoEnsino,\n\t\t?string $outDescTipoEnsino,\n\t\t?string $outCodSerieAno,\n\t\t?string $outTurma,\n\t\t?string $outCodTurno,\n\t\t?string $outDescricaoTurno,\n\t\t?string $outCodHabilitacao,\n\t\t?string $outNumSala,\n\t\t?string $outHorarioInicio,\n\t\t?string $outHorarioFim,\n\t\t?string $outCodTipoClasse,\n\t\t?string $outDescTipoClasse,\n\t\t?string $outSemestre,\n\t\t?string $outQtdAtual,\n\t\t?string $outQtdDigitados,\n\t\t?string $outQtdEvadidos,\n\t\t?string $outQtdNCom,\n\t\t?string $outQtdOutros,\n\t\t?string $outQtdTransferidos,\n\t\t?string $outQtdRemanejados,\n\t\t?string $outQtdCessados,\n\t\t?string $outQtdReclassificados,\n\t\t?string $outCapacidadeFisicaMax\n\t) {\n\t\t$this->outNumClasse = $outNumClasse;\n\t\t$this->outCodTipoEnsino = $outCodTipoEnsino;\n\t\t$this->outDescTipoEnsino = $outDescTipoEnsino;\n\t\t$this->outCodSerieAno = $outCodSerieAno;\n\t\t$this->outTurma = $outTurma;\n\t\t$this->outCodTurno = $outCodTurno;\n\t\t$this->outDescricaoTurno = $outDescricaoTurno;\n\t\t$this->outCodHabilitacao = $outCodHabilitacao;\n\t\t$this->outNumSala = $outNumSala;\n\t\t$this->outHorarioInicio = $outHorarioInicio;\n\t\t$this->outHorarioFim = $outHorarioFim;\n\t\t$this->outCodTipoClasse = $outCodTipoClasse;\n\t\t$this->outDescTipoClasse = $outDescTipoClasse;\n\t\t$this->outSemestre = $outSemestre;\n\t\t$this->outQtdAtual = $outQtdAtual;\n\t\t$this->outQtdDigitados = $outQtdDigitados;\n\t\t$this->outQtdEvadidos = $outQtdEvadidos;\n\t\t$this->outQtdNCom = $outQtdNCom;\n\t\t$this->outQtdOutros = $outQtdOutros;\n\t\t$this->outQtdTransferidos = $outQtdTransferidos;\n\t\t$this->outQtdRemanejados = $outQtdRemanejados;\n\t\t$this->outQtdCessados = $outQtdCessados;\n\t\t$this->outQtdReclassificados = $outQtdReclassificados;\n\t\t$this->outCapacidadeFisicaMax = $outCapacidadeFisicaMax;\n\t}", "smellKey": "S107", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function (string $userId, string $mock, int $width, int $height, Document $user, Document $project, Database $dbForProject, Database $dbForConsole, Response $response, array $heroes, array $contributors, array $employees, ?Logger $logger) use ($getUserGitHub) {\n $user = Authorization::skip(fn () => $dbForConsole->getDocument('users', $userId));\n\n if ($user->isEmpty() && empty($mock)) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n if (!$mock) {\n $internalId = $user->getInternalId();\n $bgVariation = $internalId % 3 === 0 ? '1' : ($internalId % 3 === 1 ? '2' : '3');\n $cardVariation = $internalId % 3 === 0 ? '1' : ($internalId % 3 === 1 ? '2' : '3');\n\n $name = $user->getAttribute('name', 'Anonymous');\n $email = $user->getAttribute('email', '');\n $createdAt = new \\DateTime($user->getCreatedAt());\n\n $gitHub = $getUserGitHub($user->getId(), $project, $dbForProject, $dbForConsole, $logger);\n $githubName = $gitHub['name'] ?? '';\n $githubId = $gitHub['id'] ?? '';\n\n $isHero = \\array_key_exists($email, $heroes);\n $isContributor = \\in_array($githubId, $contributors);\n $isEmployee = \\array_key_exists($email, $employees);\n $employeeNumber = $isEmployee ? $employees[$email]['spot'] : '';\n\n if ($isHero) {\n $createdAt = new \\DateTime($heroes[$email]['memberSince'] ?? '');\n } elseif ($isEmployee) {\n $createdAt = new \\DateTime($employees[$email]['memberSince'] ?? '');\n }\n\n if (!$isEmployee && !empty($githubName)) {\n $employeeGitHub = \\array_search(\\strtolower($githubName), \\array_map(fn ($employee) => \\strtolower($employee['gitHub']) ?? '', $employees));\n if (!empty($employeeGitHub)) {\n $isEmployee = true;\n $employeeNumber = $isEmployee ? $employees[$employeeGitHub]['spot'] : '';\n $createdAt = new \\DateTime($employees[$employeeGitHub]['memberSince'] ?? '');\n }\n }\n\n $isPlatinum = $user->getInternalId() % 100 === 0;\n } else {\n $bgVariation = \\str_ends_with($mock, '-bg2') ? '2' : (\\str_ends_with($mock, '-bg3') ? '3' : '1');\n $cardVariation = \\str_ends_with($mock, '-right') ? '2' : (\\str_ends_with($mock, '-middle') ? '3' : '1');\n $name = \\str_starts_with($mock, 'normal-long') ? 'Sir First Walter O\\'Brian Junior' : 'Walter O\\'Brian';\n $createdAt = new \\DateTime('now');\n $githubName = $mock === 'normal-no-github' ? '' : (\\str_starts_with($mock, 'normal-long') ? 'sir-first-walterobrian-junior' : 'walterobrian');\n $isHero = \\str_starts_with($mock, 'hero');\n $isContributor = \\str_starts_with($mock, 'contributor');\n $isEmployee = \\str_starts_with($mock, 'employee');\n $employeeNumber = match ($mock) {\n 'employee' => '1',\n 'employee-right' => '1',\n 'employee-middle' => '1',\n 'employee-2digit' => '18',\n 'employee-2digit-right' => '18',\n 'employee-2digit-middle' => '18',\n default => ''\n };\n\n $isPlatinum = \\str_starts_with($mock, 'platinum');\n }\n\n if ($isEmployee) {\n $isContributor = false;\n $isHero = false;\n }\n\n if ($isHero) {\n $isContributor = false;\n $isEmployee = false;\n }\n\n if ($isContributor) {\n $isHero = false;\n $isEmployee = false;\n }\n\n $isGolden = $isEmployee || $isHero || $isContributor;\n $isPlatinum = $isGolden ? false : $isPlatinum;\n $memberSince = \\strtoupper('Member since ' . $createdAt->format('M') . ' ' . $createdAt->format('d') . ', ' . $createdAt->format('o'));\n\n $baseImage = new \\Imagick(__DIR__ . \"/../../../public/images/cards/cloud/og-background{$bgVariation}.png\");\n\n $cardType = $isGolden ? '-golden' : ($isPlatinum ? '-platinum' : '');\n\n $image = new Imagick(__DIR__ . \"/../../../public/images/cards/cloud/og-card{$cardType}{$cardVariation}.png\");\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 1008 / 2 - $image->getImageWidth() / 2, 1008 / 2 - $image->getImageHeight() / 2);\n\n $imageLogo = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/og-background-logo.png');\n $imageShadow = new Imagick(__DIR__ . \"/../../../public/images/cards/cloud/og-shadow{$cardType}.png\");\n if ($cardVariation === '1') {\n $baseImage->compositeImage($imageLogo, Imagick::COMPOSITE_OVER, 32, 1008 - $imageLogo->getImageHeight() - 32);\n $baseImage->compositeImage($imageShadow, Imagick::COMPOSITE_OVER, -450, 700);\n } elseif ($cardVariation === '2') {\n $baseImage->compositeImage($imageLogo, Imagick::COMPOSITE_OVER, 1008 - $imageLogo->getImageWidth() - 32, 1008 - $imageLogo->getImageHeight() - 32);\n $baseImage->compositeImage($imageShadow, Imagick::COMPOSITE_OVER, -20, 710);\n } else {\n $baseImage->compositeImage($imageLogo, Imagick::COMPOSITE_OVER, 1008 - $imageLogo->getImageWidth() - 32, 1008 - $imageLogo->getImageHeight() - 32);\n $baseImage->compositeImage($imageShadow, Imagick::COMPOSITE_OVER, -135, 710);\n }\n\n if ($isEmployee) {\n $file = $cardVariation === '3' ? 'employee-skew.png' : 'employee.png';\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/' . $file);\n $image->setGravity(Imagick::GRAVITY_CENTER);\n\n $hashtag = new \\ImagickDraw();\n $hashtag->setTextAlignment(Imagick::ALIGN_LEFT);\n $hashtag->setFont(__DIR__ . '/../../../public/fonts/Inter-Bold.ttf');\n $hashtag->setFillColor(new \\ImagickPixel('#FFFADF'));\n $hashtag->setFontSize(20);\n $hashtag->setFontWeight(700);\n\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_LEFT);\n $text->setFont(__DIR__ . '/../../../public/fonts/Inter-Bold.ttf');\n $text->setFillColor(new \\ImagickPixel('#FFFADF'));\n $text->setFontSize(\\strlen($employeeNumber) <= 1 ? 36 : 28);\n $text->setFontWeight(700);\n\n if ($cardVariation === '3') {\n $hashtag->setFontSize(16);\n $text->setFontSize(\\strlen($employeeNumber) <= 1 ? 30 : 26);\n\n $hashtag->skewY(20);\n $hashtag->skewX(20);\n $text->skewY(20);\n $text->skewX(20);\n }\n\n $metricsHashtag = $baseImage->queryFontMetrics($hashtag, '#');\n $metricsText = $baseImage->queryFontMetrics($text, $employeeNumber);\n\n $group = new Imagick();\n $groupWidth = $metricsHashtag['textWidth'] + 6 + $metricsText['textWidth'];\n\n if ($cardVariation === '1') {\n $group->newImage($groupWidth, $metricsText['textHeight'], '#00000000');\n $group->annotateImage($hashtag, 0, $metricsText['textHeight'], 0, '#');\n $group->annotateImage($text, $metricsHashtag['textWidth'] + 6, $metricsText['textHeight'], 0, $employeeNumber);\n\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), -20);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 612, 203);\n\n $group->rotateImage(new ImagickPixel('#00000000'), -22);\n\n if (\\strlen($employeeNumber) <= 1) {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 660, 245);\n } else {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 655, 247);\n }\n } elseif ($cardVariation === '2') {\n $group->newImage($groupWidth, $metricsText['textHeight'], '#00000000');\n $group->annotateImage($hashtag, 0, $metricsText['textHeight'], 0, '#');\n $group->annotateImage($text, $metricsHashtag['textWidth'] + 6, $metricsText['textHeight'], 0, $employeeNumber);\n\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), 30);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 715, 425);\n\n $group->rotateImage(new ImagickPixel('#00000000'), 32);\n\n if (\\strlen($employeeNumber) <= 1) {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 775, 465);\n } else {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 767, 470);\n }\n } else {\n $group->newImage(300, 300, '#00000000');\n\n $hashtag->annotation(0, $metricsText['textHeight'], '#');\n $text->annotation($metricsHashtag['textWidth'] + 2, $metricsText['textHeight'], $employeeNumber);\n\n $group->drawImage($hashtag);\n $group->drawImage($text);\n\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 640, 293);\n\n if (\\strlen($employeeNumber) <= 1) {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 670, 317);\n } else {\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, 663, 322);\n }\n }\n }\n\n if ($isContributor) {\n $file = $cardVariation === '3' ? 'contributor-skew.png' : 'contributor.png';\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/' . $file);\n $image->setGravity(Imagick::GRAVITY_CENTER);\n\n if ($cardVariation === '1') {\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), -20);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 612, 203);\n } elseif ($cardVariation === '2') {\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), 30);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 715, 425);\n } else {\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 640, 293);\n }\n }\n\n if ($isHero) {\n $file = $cardVariation === '3' ? 'hero-skew.png' : 'hero.png';\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/' . $file);\n $image->setGravity(Imagick::GRAVITY_CENTER);\n\n if ($cardVariation === '1') {\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), -20);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 612, 203);\n } elseif ($cardVariation === '2') {\n $image->resizeImage(120, 120, Imagick::FILTER_LANCZOS, 1);\n $image->rotateImage(new ImagickPixel('#00000000'), 30);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 715, 425);\n } else {\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 640, 293);\n }\n }\n\n setlocale(LC_ALL, \"en_US.utf8\");\n // $name = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $name);\n // $memberSince = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $memberSince);\n // $githubName = \\iconv(\"utf-8\", \"ascii//TRANSLIT\", $githubName);\n\n $textName = new \\ImagickDraw();\n $textName->setTextAlignment(Imagick::ALIGN_CENTER);\n $textName->setFont(__DIR__ . '/../../../public/fonts/Poppins-Bold.ttf');\n $textName->setFillColor(new \\ImagickPixel('#FFFFFF'));\n\n if (\\strlen($name) > 32) {\n $name = \\substr($name, 0, 32);\n }\n\n if ($cardVariation === '1') {\n if (\\strlen($name) <= 23) {\n $scalingDown = false;\n $textName->setFontSize(54);\n } else {\n $scalingDown = true;\n $textName->setFontSize(36);\n }\n } elseif ($cardVariation === '2') {\n if (\\strlen($name) <= 23) {\n $scalingDown = false;\n $textName->setFontSize(50);\n } else {\n $scalingDown = true;\n $textName->setFontSize(34);\n }\n } else {\n if (\\strlen($name) <= 23) {\n $scalingDown = false;\n $textName->setFontSize(44);\n } else {\n $scalingDown = true;\n $textName->setFontSize(32);\n }\n }\n\n $textName->setFontWeight(700);\n\n $textMember = new \\ImagickDraw();\n $textMember->setTextAlignment(Imagick::ALIGN_CENTER);\n $textMember->setFont(__DIR__ . '/../../../public/fonts/Inter-Medium.ttf');\n $textMember->setFillColor(new \\ImagickPixel($isGolden || $isPlatinum ? '#FFFFFF' : '#FFB9CC'));\n $textMember->setFontWeight(500);\n $textMember->setTextKerning(1.12);\n\n if ($cardVariation === '1') {\n $textMember->setFontSize(21);\n\n $baseImage->annotateImage($textName, 550, 600, -22, $name);\n $baseImage->annotateImage($textMember, 585, 635, -22, $memberSince);\n } elseif ($cardVariation === '2') {\n $textMember->setFontSize(20);\n\n $baseImage->annotateImage($textName, 435, 590, 31.37, $name);\n $baseImage->annotateImage($textMember, 412, 628, 31.37, $memberSince);\n } else {\n $textMember->setFontSize(16);\n\n $textName->skewY(20);\n $textName->skewX(20);\n $textName->annotation(320, 700, $name);\n\n $textMember->skewY(20);\n $textMember->skewX(20);\n $textMember->annotation(330, 735, $memberSince);\n\n $baseImage->drawImage($textName);\n $baseImage->drawImage($textMember);\n }\n\n if (!empty($githubName)) {\n $text = new \\ImagickDraw();\n $text->setTextAlignment(Imagick::ALIGN_LEFT);\n $text->setFont(__DIR__ . '/../../../public/fonts/Inter-Regular.ttf');\n $text->setFillColor(new \\ImagickPixel('#FFFFFF'));\n $text->setFontSize($scalingDown ? 16 : 20);\n $text->setFontWeight(400);\n\n if ($cardVariation === '1') {\n $metrics = $baseImage->queryFontMetrics($text, $githubName);\n\n $group = new Imagick();\n $groupWidth = $metrics['textWidth'] + 32 + 4;\n $group->newImage($groupWidth, $metrics['textHeight'] + 10, '#00000000');\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/github.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $image->resizeImage(32, 32, Imagick::FILTER_LANCZOS, 1);\n $precisionFix = -1;\n\n $group->compositeImage($image, Imagick::COMPOSITE_OVER, 0, 0);\n $group->annotateImage($text, 32 + 4, $metrics['textHeight'] - $precisionFix, 0, $githubName);\n\n $group->rotateImage(new ImagickPixel('#00000000'), -22);\n $x = 510 - $group->getImageWidth() / 2;\n $y = 530 - $group->getImageHeight() / 2;\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, $x, $y);\n } elseif ($cardVariation === '2') {\n $metrics = $baseImage->queryFontMetrics($text, $githubName);\n\n $group = new Imagick();\n $groupWidth = $metrics['textWidth'] + 32 + 4;\n $group->newImage($groupWidth, $metrics['textHeight'] + 10, '#00000000');\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/github.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $image->resizeImage(32, 32, Imagick::FILTER_LANCZOS, 1);\n $precisionFix = -1;\n\n $group->compositeImage($image, Imagick::COMPOSITE_OVER, 0, 0);\n $group->annotateImage($text, 32 + 4, $metrics['textHeight'] - $precisionFix, 0, $githubName);\n\n $group->rotateImage(new ImagickPixel('#00000000'), 31.11);\n $x = 485 - $group->getImageWidth() / 2;\n $y = 530 - $group->getImageHeight() / 2;\n $baseImage->compositeImage($group, Imagick::COMPOSITE_OVER, $x, $y);\n } else {\n $text->skewY(20);\n $text->skewX(20);\n $text->setTextAlignment(\\Imagick::ALIGN_CENTER);\n\n $text->annotation(320 + 15 + 2, 640, $githubName);\n $metrics = $baseImage->queryFontMetrics($text, $githubName);\n\n $image = new Imagick(__DIR__ . '/../../../public/images/cards/cloud/github-skew.png');\n $image->setGravity(Imagick::GRAVITY_CENTER);\n $baseImage->compositeImage($image, Imagick::COMPOSITE_OVER, 512 - ($metrics['textWidth'] / 2), 518 + \\strlen($githubName) * 1.3);\n\n $baseImage->drawImage($text);\n }\n }\n\n if (!empty($width) || !empty($height)) {\n $baseImage->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);\n }\n\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache\n ->setContentType('image/png')\n ->file($baseImage->getImageBlob());\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function sendWorkflowEmailNotification(array $users, array $roles, Workflow $workflow, string $subjectType, ElementInterface $subject, string $action, string $mailType, string $mailPath): void\n {\n try {\n $recipients = $this->getNotificationUsersByName($users, $roles);\n if (!count($recipients)) {\n return;\n }\n\n $deeplink = '';\n $hostUrl = Tool::getHostUrl();\n if ($hostUrl !== '') {\n // Decide what kind of link to create\n $objectType = $type = 'object';\n if ($subject instanceof \\Pimcore\\Model\\Document) {\n $objectType = 'document';\n $type = $subject->getType();\n }\n if ($subject instanceof \\Pimcore\\Model\\Asset) {\n $objectType = 'asset';\n $type = $subject->getType();\n }\n\n $deeplink = $hostUrl . $this->router->generate('pimcore_admin_login_deeplink') . '?'.$objectType.'_' . $subject->getId() . '_'. $type;\n }\n\n foreach ($recipients as $language => $recipientsPerLanguage) {\n $localizedMailPath = str_replace(self::MAIL_PATH_LANGUAGE_PLACEHOLDER, $language, $mailPath);\n\n switch ($mailType) {\n case NotificationSubscriber::MAIL_TYPE_TEMPLATE:\n\n $this->sendTemplateMail(\n $recipientsPerLanguage,\n $subjectType,\n $subject,\n $workflow,\n $action,\n $language,\n $localizedMailPath,\n $deeplink\n );\n\n break;\n\n case NotificationSubscriber::MAIL_TYPE_DOCUMENT:\n\n $this->sendPimcoreDocumentMail(\n $recipientsPerLanguage,\n $subjectType,\n $subject,\n $workflow,\n $action,\n $language,\n $localizedMailPath,\n $deeplink\n );\n\n break;\n }\n }\n } catch (Exception $e) {\n \\Pimcore\\Logger::error('Error sending Workflow change notification email.');\n }\n }", "smellKey": "S107", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function setFiltres($tab_fou=array(),$tab_empr=array(),$tab_user=array(), $tab_rub=array(), $chk_dev='0',$cde_query='', $lgstat_filter=array(), $date_inf='', $date_sup='') {\n\t\t$this->filtre_actes=\"actes.num_entite='\".$this->id_bibli.\"' and actes.num_exercice='\".$this->id_exer.\"' and (actes.statut & \".STA_ACT_ENC.\" = \".STA_ACT_ENC.\") \";\n\t\t\n\t\t$type_acte=TYP_ACT_CDE;\n\t\tif ($chk_dev) {\n\t\t\t$type_acte=TYP_ACT_DEV;\n\t\t\t$this->type_acte = $type_acte;\n\t\t}\n\t\t\n\t\t$this->filtre_actes.= \"and actes.type_acte = '\".$type_acte.\"' \";\n\t\t\n\t\tif ($cde_query) {\n\t\t\t$cde_query = trim($cde_query);\n\t\t\t$this->filtre_actes.= \"and actes.numero like '%\".$cde_query.\"%' \";\n\t\t}\n\n\t\tif (is_array($tab_fou) && count($tab_fou)) {\t\t\n\t\t\t$this->filtre_actes.= \"and actes.num_fournisseur in ('\".implode(\"','\",$tab_fou).\"') \";\n\t\t}\n\t\t\n\t\tif ($date_inf) {\n\t\t\t$this->filtre_actes.= \"and actes.date_acte >= '\".$date_inf.\"' \";\n\t\t} \n\t\tif ($date_sup) {\n\t\t\t$this->filtre_actes.= \"and actes.date_acte <= '\".$date_sup.\"' \";\n\t\t}\t\t\n\t\t\n\t\t$this->filtre_lignes = \"and lignes_actes.type_ligne != '3' \";\t//pas de non recevable\n\t\t\n\t\tif (is_array($tab_rub) && count($tab_rub)) {\t\t\n\t\t\t$this->filtre_lignes.= \"and lignes_actes.num_rubrique in ('\".implode(\"','\",$tab_rub).\"') \";\n\t\t}\n\t\t\n\t\tif (is_array($lgstat_filter) && count($lgstat_filter) && $lgstat_filter[0]) {\n\t\t\t$this->filtre_lignes.= \"and lignes_actes.statut in ('\".implode(\"','\",$lgstat_filter).\"') \";\n\t\t}\n\t\t\n\t\t$filtre_empr='';\n\t\t$filtre_user='';\n\t\tif (is_array($tab_empr) && count($tab_empr)) {\n\t\t\t$filtre_empr = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_empr).\"') and type_origine='1' \";\n\t\t}\n\t\tif (is_array($tab_user) && count($tab_user)) {\t\t\n\t\t\t$filtre_user = \"suggestions_origine.origine in ('\".implode(\"','\",$tab_user).\"') and type_origine='0' \";\n\t\t}\n\t\tif ($filtre_empr && $filtre_user) {\n\t\t\t$this->filtre_origines= \"and ( (\".$filtre_empr.\") or (\".$filtre_user.\") ) \";\n\t\t} elseif($filtre_empr) {\n\t\t\t$this->filtre_origines= \"and (\".$filtre_empr.\") \";\n\t\t} elseif ($filtre_user){\n\t\t\t$this->filtre_origines= \"and (\".$filtre_user.\") \";\n\t\t}\n\t}", "smellKey": "S107", "smellId": null, "repo": "inovatio-france_pmb_nightlybuild", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?int $size, ?bool $required, ?string $default, bool $array, bool $encrypt, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n // Ensure attribute default is within required size\n $validator = new Text($size, 0);\n if (!is_null($default) && !$validator->isValid($default)) {\n throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription());\n }\n\n $filters = [];\n\n if ($encrypt) {\n $filters[] = 'encrypt';\n }\n\n $attribute = createAttribute($databaseId, $collectionId, new Document([\n 'key' => $key,\n 'type' => Database::VAR_STRING,\n 'size' => $size,\n 'required' => $required,\n 'default' => $default,\n 'array' => $array,\n 'filters' => $filters,\n ]), $response, $dbForProject, $database, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_STRING);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function test_rules_clinic_group_calculation($type = '', array $dateArray = array(), $mode = '', $patient_id = '', $plan = '', $organize_mode = 'default', $options = array(), $pat_prov_rel = 'primary', $start = null, $batchSize = null, $user = '')\n{\n (new SystemLogger())->debug(\n \"test_rules_clinic_group_calculation()\",\n array_combine(\n ['type', 'dateArray', 'mode', 'patient_id', 'plan', 'organize_mode'\n ,\n 'options',\n 'pat_prov_rel',\n 'start',\n 'batchSize',\n 'user'],\n func_get_args()\n )\n );\n\n $results = [];\n $facilityService = new FacilityService();\n $billingLocations = $facilityService->getAllBillingLocations();\n if (!empty($billingLocations)) {\n //Collect applicable rules\n // Note that due to a limitation in the this function, the patient_id is explicitly\n // for grouping items when not being done in real-time or for official reporting.\n // So for cases such as patient reminders on a clinic scale, the calling function\n // will actually need rather than pass in a explicit patient_id for each patient in\n // a separate call to this function.\n $rules = resolve_rules_sql($type, $patient_id, false, $plan, $user);\n $filteredRules = array_filter($rules, function ($rule) {\n return $rule['amc_flag'] || $rule['cqm_flag'];\n });\n\n // TODO: @adunsulag I'd prefer to use a service here, but in order to be consistent with everything else in this file we will use sqlStatementCdrEngine\n $sql = \"SELECT id, name, federal_ein, facility_npi, tax_id_type FROM facility WHERE facility.billing_location = 1 \"\n . \" AND id IN (SELECT DISTINCT billing_facility FROM form_encounter) \"\n . \" ORDER BY facility.id ASC\";\n $frez = sqlStatementCdrEngine($sql);\n while ($frow = sqlFetchArray($frez)) {\n // we run with the encounter_billing_facility\n\n $options['billing_facility_id'] = $frow['id'];\n $patientData = buildPatientArray($patient_id, 'group_calculation', $pat_prov_rel, $start, $batchSize, false, $frow['id']);\n\n (new SystemLogger())->debug(\n \"test_rules_clinic_group_calculation() patientIds retrieved for facility\",\n ['facilityId' => $frow['id'], 'patientData' => $patientData]\n );\n\n if (!empty($patientData)) {\n $group_item = [];\n $group_item['is_provider_group'] = true;\n $group_item['name'] = $frow['name'];\n $group_item['npi'] = $frow['facility_npi'];\n $group_item['federaltaxid'] = $frow['federal_ein'];\n $results[] = $group_item;\n\n foreach ($filteredRules as $rowRule) {\n $tempResults = test_rules_clinic_cqm_amc_rule($rowRule, $patientData, $dateArray, $dateArray, $options, null, $pat_prov_rel);\n if (!empty($tempResults)) {\n $results = array_merge($results, $tempResults);\n }\n (new SystemLogger())->debug(\n \"test_rules_clinic_group_calculation() results returned for facility\",\n ['facilityId' => $frow['id'], 'results' => $tempResults]\n );\n }\n\n // now we are going to do our providers\n $providers = rules_clinic_get_providers($frow['id'], $pat_prov_rel);\n if (!empty($providers)) { // should always be populated here\n $facility_pat_prov_rel = $pat_prov_rel . \"_billing_facility\";\n foreach ($providers as $prov) {\n $newResults = test_rules_clinic($prov['provider_id'], $type, $dateArray, $mode, $patient_id, $plan, $organize_mode, $options, $facility_pat_prov_rel, $start, $batchSize, $user);\n if (!empty($newResults)) {\n $provider_item['is_provider'] = true;\n $provider_item['is_provider_in_group'] = true;\n $provider_item['group'] = [\n 'name' => $frow['name']\n ,'npi' => $frow['facility_npi']\n ,'federaltaxid' => $frow['federal_ein']\n ];\n $provider_item['prov_lname'] = $prov['lname'];\n $provider_item['prov_fname'] = $prov['fname'];\n $provider_item['npi'] = $prov['npi'];\n $provider_item['federaltaxid'] = $prov['federaltaxid'];\n $results[] = $provider_item;\n $results = array_merge($results, $newResults);\n }\n }\n }\n }\n }\n }\n return $results;\n}", "smellKey": "S107", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\tlist($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);\n\t\tif (strlen($txt) == 0) {\n\t\t\t// fix empty text\n\t\t\t$txt = ' ';\n\t\t}\n\t\tif ($margin === '') {\n\t\t\t// set default margins\n\t\t\t$margin = $this->cell_margin;\n\t\t}\n\t\t// remove carriage returns\n\t\t$s = str_replace(\"\\r\", '', $txt);\n\t\t// check if string contains arabic text\n\t\tif (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {\n\t\t\t$arabic = true;\n\t\t} else {\n\t\t\t$arabic = false;\n\t\t}\n\t\t// check if string contains RTL text\n\t\tif ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {\n\t\t\t$rtlmode = true;\n\t\t} else {\n\t\t\t$rtlmode = false;\n\t\t}\n\t\t// get a char width\n\t\t$chrwidth = $this->GetCharWidth(46); // dot character\n\t\t// get array of unicode values\n\t\t$chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);\n\t\t// calculate maximum width for a single character on string\n\t\t$chrw = $this->GetArrStringWidth($chars, '', '', 0, true);\n\t\tarray_walk($chrw, array($this, 'getRawCharWidth'));\n\t\t$maxchwidth = max($chrw);\n\t\t// get array of chars\n\t\t$uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);\n\t\t// get the number of characters\n\t\t$nb = count($chars);\n\t\t// replacement for SHY character (minus symbol)\n\t\t$shy_replacement = 45;\n\t\t$shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);\n\t\t// widht for SHY replacement\n\t\t$shy_replacement_width = $this->GetCharWidth($shy_replacement);\n\t\t// page width\n\t\t$pw = $w = $this->w - $this->lMargin - $this->rMargin;\n\t\t// calculate remaining line width ($w)\n\t\tif ($this->rtl) {\n\t\t\t$w = $this->x - $this->lMargin;\n\t\t} else {\n\t\t\t$w = $this->w - $this->rMargin - $this->x;\n\t\t}\n\t\t// max column width\n\t\t$wmax = ($w - $wadj);\n\t\tif (!$firstline) {\n\t\t\t$wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);\n\t\t}\n\t\tif ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {\n\t\t\t// the maximum width character do not fit on column\n\t\t\treturn '';\n\t\t}\n\t\t// minimum row height\n\t\t$row_height = max($h, $this->getCellHeight($this->FontSize));\n\t\t// max Y\n\t\t$maxy = $this->y + $maxh - max($row_height, $h);\n\t\t$start_page = $this->page;\n\t\t$i = 0; // character position\n\t\t$j = 0; // current starting position\n\t\t$sep = -1; // position of the last blank space\n\t\t$prevsep = $sep; // previous separator\n\t\t$shy = false; // true if the last blank is a soft hypen (SHY)\n\t\t$prevshy = $shy; // previous shy mode\n\t\t$l = 0; // current string length\n\t\t$nl = 0; //number of lines\n\t\t$linebreak = false;\n\t\t$pc = 0; // previous character\n\t\t// for each character\n\t\twhile ($i < $nb) {\n\t\t\tif (($maxh > 0) AND ($this->y > $maxy) ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//Get the current character\n\t\t\t$c = $chars[$i];\n\t\t\tif ($c == 10) { // 10 = \"\\n\" = new line\n\t\t\t\t//Explicit line break\n\t\t\t\tif ($align == 'J') {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$talign = 'R';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$talign = 'L';\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$talign = $align;\n\t\t\t\t}\n\t\t\t\t$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);\n\t\t\t\tif ($firstline) {\n\t\t\t\t\t$startx = $this->x;\n\t\t\t\t\t$tmparr = array_slice($chars, $j, ($i - $j));\n\t\t\t\t\tif ($rtlmode) {\n\t\t\t\t\t\t$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t\t}\n\t\t\t\t\t$linew = $this->GetArrStringWidth($tmparr);\n\t\t\t\t\tunset($tmparr);\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$this->endlinex = $startx - $linew;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->endlinex = $startx + $linew;\n\t\t\t\t\t}\n\t\t\t\t\t$w = $linew;\n\t\t\t\t\t$tmpcellpadding = $this->cell_padding;\n\t\t\t\t\tif ($maxh == 0) {\n\t\t\t\t\t\t$this->SetCellPadding(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($firstblock AND $this->isRTLTextDir()) {\n\t\t\t\t\t$tmpstr = $this->stringRightTrim($tmpstr);\n\t\t\t\t}\n\t\t\t\t// Skip newlines at the beginning of a page or column\n\t\t\t\tif (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {\n\t\t\t\t\t$this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);\n\t\t\t\t}\n\t\t\t\tunset($tmpstr);\n\t\t\t\tif ($firstline) {\n\t\t\t\t\t$this->cell_padding = $tmpcellpadding;\n\t\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, $i));\n\t\t\t\t}\n\t\t\t\t++$nl;\n\t\t\t\t$j = $i + 1;\n\t\t\t\t$l = 0;\n\t\t\t\t$sep = -1;\n\t\t\t\t$prevsep = $sep;\n\t\t\t\t$shy = false;\n\t\t\t\t// account for margin changes\n\t\t\t\tif ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {\n\t\t\t\t\t$this->AcceptPageBreak();\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$this->x -= $margin['R'];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->x += $margin['L'];\n\t\t\t\t\t}\n\t\t\t\t\t$this->lMargin += $margin['L'];\n\t\t\t\t\t$this->rMargin += $margin['R'];\n\t\t\t\t}\n\t\t\t\t$w = $this->getRemainingWidth();\n\t\t\t\t$wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);\n\t\t\t} else {\n\t\t\t\t// 160 is the non-breaking space.\n\t\t\t\t// 173 is SHY (Soft Hypen).\n\t\t\t\t// \\p{Z} or \\p{Separator}: any kind of Unicode whitespace or invisible separator.\n\t\t\t\t// \\p{Lo} or \\p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.\n\t\t\t\t// \\p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.\n\t\t\t\tif (($c != 160)\n\t\t\t\t\tAND (($c == 173)\n\t\t\t\t\t\tOR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))\n\t\t\t\t\t\tOR (($c == 45)\n\t\t\t\t\t\t\tAND ($i < ($nb - 1))\n\t\t\t\t\t\t\tAND @preg_match('/[\\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))\n\t\t\t\t\t\t\tAND @preg_match('/[\\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\t// update last blank space position\n\t\t\t\t\t$prevsep = $sep;\n\t\t\t\t\t$sep = $i;\n\t\t\t\t\t// check if is a SHY\n\t\t\t\t\tif (($c == 173) OR ($c == 45)) {\n\t\t\t\t\t\t$prevshy = $shy;\n\t\t\t\t\t\t$shy = true;\n\t\t\t\t\t\tif ($pc == 45) {\n\t\t\t\t\t\t\t$tmp_shy_replacement_width = 0;\n\t\t\t\t\t\t\t$tmp_shy_replacement_char = '';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$tmp_shy_replacement_width = $shy_replacement_width;\n\t\t\t\t\t\t\t$tmp_shy_replacement_char = $shy_replacement_char;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$shy = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// update string length\n\t\t\t\tif ($this->isUnicodeFont() AND ($arabic)) {\n\t\t\t\t\t// with bidirectional algorithm some chars may be changed affecting the line length\n\t\t\t\t\t// *** very slow ***\n\t\t\t\t\t$l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));\n\t\t\t\t} else {\n\t\t\t\t\t$l += $this->GetCharWidth($c);\n\t\t\t\t}\n\t\t\t\tif (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {\n\t\t\t\t\tif (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {\n\t\t\t\t\t\t$sep = $prevsep;\n\t\t\t\t\t\t$shy = $prevshy;\n\t\t\t\t\t}\n\t\t\t\t\t// we have reached the end of column\n\t\t\t\t\tif ($sep == -1) {\n\t\t\t\t\t\t// check if the line was already started\n\t\t\t\t\t\tif (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))\n\t\t\t\t\t\t\tOR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {\n\t\t\t\t\t\t\t// print a void cell and go to next line\n\t\t\t\t\t\t\t$this->Cell($w, $h, '', 0, 1);\n\t\t\t\t\t\t\t$linebreak = true;\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, $j));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// truncate the word because do not fit on column\n\t\t\t\t\t\t\t$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\t$startx = $this->x;\n\t\t\t\t\t\t\t\t$tmparr = array_slice($chars, $j, ($i - $j));\n\t\t\t\t\t\t\t\tif ($rtlmode) {\n\t\t\t\t\t\t\t\t\t$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$linew = $this->GetArrStringWidth($tmparr);\n\t\t\t\t\t\t\t\tunset($tmparr);\n\t\t\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t\t\t$this->endlinex = $startx - $linew;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$this->endlinex = $startx + $linew;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$w = $linew;\n\t\t\t\t\t\t\t\t$tmpcellpadding = $this->cell_padding;\n\t\t\t\t\t\t\t\tif ($maxh == 0) {\n\t\t\t\t\t\t\t\t\t$this->SetCellPadding(0);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ($firstblock AND $this->isRTLTextDir()) {\n\t\t\t\t\t\t\t\t$tmpstr = $this->stringRightTrim($tmpstr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);\n\t\t\t\t\t\t\tunset($tmpstr);\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\t$this->cell_padding = $tmpcellpadding;\n\t\t\t\t\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, $i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$j = $i;\n\t\t\t\t\t\t\t--$i;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// word wrapping\n\t\t\t\t\t\tif ($this->rtl AND (!$firstblock) AND ($sep < $i)) {\n\t\t\t\t\t\t\t$endspace = 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$endspace = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// check the length of the next string\n\t\t\t\t\t\t$strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));\n\t\t\t\t\t\t$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));\n\t\t\t\t\t\tif (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {\n\t\t\t\t\t\t\t// truncate the word because do not fit on a full page width\n\t\t\t\t\t\t\t$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\t$startx = $this->x;\n\t\t\t\t\t\t\t\t$tmparr = array_slice($chars, $j, ($i - $j));\n\t\t\t\t\t\t\t\tif ($rtlmode) {\n\t\t\t\t\t\t\t\t\t$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$linew = $this->GetArrStringWidth($tmparr);\n\t\t\t\t\t\t\t\tunset($tmparr);\n\t\t\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t\t\t$this->endlinex = ($startx - $linew);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$this->endlinex = ($startx + $linew);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$w = $linew;\n\t\t\t\t\t\t\t\t$tmpcellpadding = $this->cell_padding;\n\t\t\t\t\t\t\t\tif ($maxh == 0) {\n\t\t\t\t\t\t\t\t\t$this->SetCellPadding(0);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ($firstblock AND $this->isRTLTextDir()) {\n\t\t\t\t\t\t\t\t$tmpstr = $this->stringRightTrim($tmpstr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);\n\t\t\t\t\t\t\tunset($tmpstr);\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\t$this->cell_padding = $tmpcellpadding;\n\t\t\t\t\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, $i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$j = $i;\n\t\t\t\t\t\t\t--$i;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// word wrapping\n\t\t\t\t\t\t\tif ($shy) {\n\t\t\t\t\t\t\t\t// add hypen (minus symbol) at the end of the line\n\t\t\t\t\t\t\t\t$shy_width = $tmp_shy_replacement_width;\n\t\t\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t\t\t$shy_char_left = $tmp_shy_replacement_char;\n\t\t\t\t\t\t\t\t\t$shy_char_right = '';\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$shy_char_left = '';\n\t\t\t\t\t\t\t\t\t$shy_char_right = $tmp_shy_replacement_char;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$shy_width = 0;\n\t\t\t\t\t\t\t\t$shy_char_left = '';\n\t\t\t\t\t\t\t\t$shy_char_right = '';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\t$startx = $this->x;\n\t\t\t\t\t\t\t\t$tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));\n\t\t\t\t\t\t\t\tif ($rtlmode) {\n\t\t\t\t\t\t\t\t\t$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$linew = $this->GetArrStringWidth($tmparr);\n\t\t\t\t\t\t\t\tunset($tmparr);\n\t\t\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t\t\t$this->endlinex = $startx - $linew - $shy_width;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$this->endlinex = $startx + $linew + $shy_width;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t$w = $linew;\n\t\t\t\t\t\t\t\t$tmpcellpadding = $this->cell_padding;\n\t\t\t\t\t\t\t\tif ($maxh == 0) {\n\t\t\t\t\t\t\t\t\t$this->SetCellPadding(0);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// print the line\n\t\t\t\t\t\t\tif ($firstblock AND $this->isRTLTextDir()) {\n\t\t\t\t\t\t\t\t$tmpstr = $this->stringRightTrim($tmpstr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);\n\t\t\t\t\t\t\tunset($tmpstr);\n\t\t\t\t\t\t\tif ($firstline) {\n\t\t\t\t\t\t\t\tif ($chars[$sep] == 45) {\n\t\t\t\t\t\t\t\t\t$endspace += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// return the remaining text\n\t\t\t\t\t\t\t\t$this->cell_padding = $tmpcellpadding;\n\t\t\t\t\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$i = $sep;\n\t\t\t\t\t\t\t$sep = -1;\n\t\t\t\t\t\t\t$shy = false;\n\t\t\t\t\t\t\t$j = ($i + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// account for margin changes\n\t\t\t\t\tif ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {\n\t\t\t\t\t\t$this->AcceptPageBreak();\n\t\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t\t$this->x -= $margin['R'];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$this->x += $margin['L'];\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$this->lMargin += $margin['L'];\n\t\t\t\t\t\t$this->rMargin += $margin['R'];\n\t\t\t\t\t}\n\t\t\t\t\t$w = $this->getRemainingWidth();\n\t\t\t\t\t$wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];\n\t\t\t\t\tif ($linebreak) {\n\t\t\t\t\t\t$linebreak = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t++$nl;\n\t\t\t\t\t\t$l = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// save last character\n\t\t\t$pc = $c;\n\t\t\t++$i;\n\t\t} // end while i < nb\n\t\t// print last substring (if any)\n\t\tif ($l > 0) {\n\t\t\tswitch ($align) {\n\t\t\t\tcase 'J':\n\t\t\t\tcase 'C': {\n\t\t\t\t\t$w = $w;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'L': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$w = $w;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$w = $l;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'R': {\n\t\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t\t$w = $l;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$w = $w;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\t$w = $l;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);\n\t\t\tif ($firstline) {\n\t\t\t\t$startx = $this->x;\n\t\t\t\t$tmparr = array_slice($chars, $j, ($nb - $j));\n\t\t\t\tif ($rtlmode) {\n\t\t\t\t\t$tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);\n\t\t\t\t}\n\t\t\t\t$linew = $this->GetArrStringWidth($tmparr);\n\t\t\t\tunset($tmparr);\n\t\t\t\tif ($this->rtl) {\n\t\t\t\t\t$this->endlinex = $startx - $linew;\n\t\t\t\t} else {\n\t\t\t\t\t$this->endlinex = $startx + $linew;\n\t\t\t\t}\n\t\t\t\t$w = $linew;\n\t\t\t\t$tmpcellpadding = $this->cell_padding;\n\t\t\t\tif ($maxh == 0) {\n\t\t\t\t\t$this->SetCellPadding(0);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($firstblock AND $this->isRTLTextDir()) {\n\t\t\t\t$tmpstr = $this->stringRightTrim($tmpstr);\n\t\t\t}\n\t\t\t$this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);\n\t\t\tunset($tmpstr);\n\t\t\tif ($firstline) {\n\t\t\t\t$this->cell_padding = $tmpcellpadding;\n\t\t\t\treturn (TCPDF_FONTS::UniArrSubString($uchars, $nb));\n\t\t\t}\n\t\t\t++$nl;\n\t\t}\n\t\tif ($firstline) {\n\t\t\treturn '';\n\t\t}\n\t\treturn $nl;\n\t}", "smellKey": "S107", "smellId": null, "repo": "GTNTGit_Ex-Site", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n $attribute = createAttribute($databaseId, $collectionId, new Document([\n 'key' => $key,\n 'type' => Database::VAR_STRING,\n 'size' => 39,\n 'required' => $required,\n 'default' => $default,\n 'array' => $array,\n 'format' => APP_DATABASE_ATTRIBUTE_IP,\n ]), $response, $dbForProject, $database, $events);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($attribute, Response::MODEL_ATTRIBUTE_IP);\n }", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n LocationService $locationService,\n ContentTypeService $contentTypeService,\n SearchService $searchService,\n BookmarkService $bookmarkService,\n ContentService $contentService,\n LookupLimitationsTransformer $lookupLimitationsTransformer,\n LocationPathQueryType $locationPathQueryType,\n LimitationResolverInterface $limitationResolver\n ) {\n $this->locationService = $locationService;\n $this->contentTypeService = $contentTypeService;\n $this->searchService = $searchService;\n $this->bookmarkService = $bookmarkService;\n $this->contentService = $contentService;\n $this->lookupLimitationsTransformer = $lookupLimitationsTransformer;\n $this->locationPathQueryType = $locationPathQueryType;\n $this->limitationResolver = $limitationResolver;\n }", "smellKey": "S107", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function ldap_list($link_identifier, string $base_dn, string $filter, array $attributes = null, int $attrsonly = 0, int $sizelimit = -1, int $timelimit = -1, int $deref = LDAP_DEREF_NEVER, array $serverctrls = null)\n{\n error_clear_last();\n if ($serverctrls !== null) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref, $serverctrls);\n } elseif ($deref !== LDAP_DEREF_NEVER) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);\n } elseif ($timelimit !== -1) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit);\n } elseif ($sizelimit !== -1) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit);\n } elseif ($attrsonly !== 0) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly);\n } elseif ($attributes !== null) {\n $result = \\ldap_list($link_identifier, $base_dn, $filter, $attributes);\n } else {\n $result = \\ldap_list($link_identifier, $base_dn, $filter);\n }\n if ($result === false) {\n throw LdapException::createFromPhpError();\n }\n return $result;\n}", "smellKey": "S107", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function __construct($variable, $field, $sqlType, $spssType = null, $fieldWidth = null, $columnWidth = null, $label = null, $measureLevels = null, $alignment = null, $decimals = null) {\n $this->variable = $variable;\n\t $this->field = $field;\n\t $this->spssType = $spssType;\n\t $this->sqlType = $sqlType;\n\t $this->columnWidth = $columnWidth;\n\t $this->fieldWidth = $fieldWidth;\n\t $this->label = $label;\n\t $this->measureLevels = $measureLevels;\n\t $this->alignment = $alignment;\n\t $this->decimals = $decimals;\n\t $this->labels = [];\n }", "smellKey": "S107", "smellId": null, "repo": "poblaciones_poblaciones", "language": "php"} {"function": "private function executeSlurmHelper($outputType, $exitStatus)\n {\n $process = proc_open(\n 'xdmod-slurm-helper -q -r frearson',\n array(\n 0 => array('file', '/dev/null', 'r'),\n 1 => array('pipe', 'w'),\n 2 => array('pipe', 'w'),\n ),\n $pipes,\n null,\n array(\n 'PATH' => realpath(__DIR__ . '/../scripts') . ':' . getenv('PATH'),\n 'XDMOD_SACCT_OUTPUT_TYPE' => $outputType,\n 'XDMOD_SACCT_EXIT_STATUS' => $exitStatus,\n )\n );\n\n if (!is_resource($process)) {\n throw new Exception('Failed to create xdmod-slurm-helper subprocess');\n }\n\n $stdout = stream_get_contents($pipes[1]);\n\n if ($stdout === false) {\n throw new Exception('Failed to get subprocess STDOUT');\n }\n\n $stderr = stream_get_contents($pipes[2]);\n\n if ($stderr === false) {\n throw new Exception('Failed to get subprocess STDERR');\n }\n\n $exitStatus = proc_close($process);\n\n return array(\n 'exit_status' => $exitStatus,\n 'stdout' => $stdout,\n 'stderr' => $stderr,\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "#[Route('/csv', name: 'back_signalement_list_export_old_csv')]\n public function exportCsv(\n Request $request,\n SignalementExportLoader $signalementExportLoader\n ): RedirectResponse|StreamedResponse {\n /** @var User $user */\n $user = $this->getUser();\n $filters = $request->getSession()->get('filters');\n try {\n $response = new StreamedResponse();\n $response->setCallback(function () use ($signalementExportLoader, $filters, $user) {\n $spreadsheet = $signalementExportLoader->load($user, $filters);\n $writer = new Csv($spreadsheet);\n $writer->save('php://output');\n });\n\n $disposition = HeaderUtils::makeDisposition(\n HeaderUtils::DISPOSITION_ATTACHMENT,\n 'export-histologe-'.date('dmY').'.csv'\n );\n $response->headers->set('Content-Type', 'text/csv');\n $response->headers->set('Content-Disposition', $disposition);\n\n return $response;\n } catch (\\ErrorException $e) {\n $this->addFlash('error', 'Probl\u00e8me d\\'identification de votre demande. Merci de r\u00e9essayer.');\n throw new \\Exception('Erreur lors de l\\'export du fichier par l\\'user \"'.$user->getId().'\" : '.$e->getMessage().' - '.print_r($filters, true));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "private function checkExportDirectory($dir)\n {\n // Desired attributes.\n $desiredPerms = 0570;\n $desiredUser = 'apache';\n $desiredGroup = 'xdmod';\n\n $this->console->displayMessage(<<<\"MSG\"\nIf the export directory does not exist, it must be created and assigned the\ncorrect permissions and ownership. It must be readable by the web server and\nboth readable and writable by the user that is used to generate the export\nfiles. By default, the web server user is expected to be {$desiredUser} and\nthe group is expected to be {$desiredGroup}. If your system uses a different\nuser and group then the automatic process will fail and you must set the\npermissions manually.\nMSG\n );\n $this->console->displayBlankLine();\n\n if (!is_dir($dir)) {\n $response = $this->console->prompt(\n 'Export directory does not exist. Create and set permissions?',\n 'yes',\n ['yes', 'no']\n );\n if ($response !== 'yes') {\n return;\n }\n if (!mkdir($dir, $desiredPerms, true)) {\n throw new Exception(sprintf(\n 'Failed to create directory \"%s\"',\n $dir\n ));\n }\n if (!chmod($dir, $desiredPerms)) {\n throw new Exception(sprintf(\n 'Failed to change permissions of \"%s\"',\n $dir\n ));\n }\n if (!chown($dir, $desiredUser)) {\n throw new Exception(sprintf(\n 'Failed to change owner of \"%s\"',\n $dir\n ));\n }\n if (!chgrp($dir, $desiredGroup)) {\n throw new Exception(sprintf(\n 'Failed to change group of \"%s\"',\n $dir\n ));\n }\n }\n\n $perms = fileperms($dir) & 0777;\n if ($perms != $desiredPerms) {\n $this->console->displayMessage(sprintf(\n 'Directory permissions are \"%o\", expected \"%o\".',\n $perms,\n $desiredPerms\n ));\n $response = $this->console->prompt(\n 'Update permissions?',\n 'yes',\n ['yes', 'no']\n );\n if ($response != 'no') {\n if (!chmod($dir, $desiredPerms)) {\n throw new Exception(sprintf(\n 'Failed to change permissions of \"%s\"',\n $dir\n ));\n }\n }\n }\n\n $user = posix_getpwuid(fileowner($dir))['name'];\n if ($user != $desiredUser) {\n $this->console->displayMessage(sprintf(\n 'Directory owner is \"%s\", expected \"%s\".',\n $user,\n $desiredUser\n ));\n $response = $this->console->prompt(\n 'Update owner?',\n 'yes',\n ['yes', 'no']\n );\n if ($response != 'no') {\n if (!chown($dir, $desiredUser)) {\n throw new Exception(sprintf(\n 'Failed to change owner of \"%s\"',\n $dir\n ));\n }\n }\n }\n\n $group = posix_getgrgid(filegroup($dir))['name'];\n if ($group != $desiredGroup) {\n $this->console->displayMessage(sprintf(\n 'Directory group is \"%s\", expected \"%s\".',\n $group,\n $desiredGroup\n ));\n $response = $this->console->prompt(\n 'Update group?',\n 'yes',\n ['yes', 'no']\n );\n if ($response != 'no') {\n if (!chgrp($dir, $desiredGroup)) {\n throw new Exception(sprintf(\n 'Failed to change group of \"%s\"',\n $dir\n ));\n }\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setZoomScaleNormal($pValue = 100) {\n\t\tif (($pValue >= 1) || is_null($pValue)) {\n\t\t\t$this->_zoomScaleNormal = $pValue;\n\t\t} else {\n\t\t\tthrow new Exception(\"Scale must be greater than or equal to 1.\");\n\t\t}\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function canRead($pFilename)\n\t{\n\t\t// Check if file exists\n\t\tif (!file_exists($pFilename)) {\n\t\t\tthrow new Exception(\"Could not open \" . $pFilename . \" for reading! File does not exist.\");\n\t\t}\n\n\t\ttry {\n\t\t\t// Use ParseXL for the hard work.\n\t\t\t$ole = new PHPExcel_Shared_OLERead();\n\n\t\t\t// get excel data\n\t\t\t$res = $ole->read($pFilename);\n\t\t\treturn true;\n\n\t\t} catch (Exception $e) {\n\t\t\treturn false;\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function downloadQrdaIAsZip($pids, $measures = '', $type = 'xml', $options = []): void\n {\n $bypid = false;\n if (empty($measures)) {\n $measures = $this->reportMeasures;\n } elseif (!is_array($measures) && $measures === 'all') {\n $measures = '';\n $bypid = true;\n }\n\n $zip_directory = sys_get_temp_dir() . ($bypid ? '/ep_measures_' : \"/qrda_export_\") . time();\n\n if (!is_dir($zip_directory)) {\n if (!mkdir($zip_directory, true, true) && !is_dir($zip_directory)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $zip_directory));\n }\n chmod($zip_directory, 0777);\n }\n // local xml save directory\n $directory = $GLOBALS['OE_SITE_DIR'] . '/documents/' . 'cat1_reports';\n $directory .= ($bypid ? '/all_measures' : \"/measures\");\n if (!is_dir($directory)) {\n if (!mkdir($directory, 0755, true) && !is_dir($directory)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $directory));\n }\n }\n\n $pids = is_array($pids) ? $pids : [$pids];\n if (!$bypid) {\n foreach ($measures as $measure) {\n if (is_array($measure)) {\n $dir_measure = $measure['measure_id'];\n } else {\n $dir_measure = $measure;\n }\n $measure_directory = $zip_directory . \"/\" . $dir_measure;\n $local_directory = $directory . \"/\" . $dir_measure;\n if (!is_dir($measure_directory)) {\n if (!mkdir($measure_directory, true, true) && !is_dir($measure_directory)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $measure_directory));\n }\n chmod($measure_directory, 0777);\n }\n if (!is_dir($local_directory)) {\n if (!mkdir($local_directory, true, true) && !is_dir($local_directory)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $local_directory));\n }\n chmod($local_directory, 0777);\n }\n\n // delete existing to make reporting easier with last exported reports, current.\n $glob = glob(\"$local_directory/*.*\");\n array_map('unlink', $glob);\n // create reports\n foreach ($pids as $pid) {\n $meta = sqlQuery(\"Select `fname`, `lname`, `pid` From `patient_data` Where `pid` = ?\", [$pid]);\n $file = $measure_directory . \"/{$meta['pid']}_{$meta['fname']}_{$meta['lname']}.\" . $type;\n $file_local = $local_directory . \"/{$meta['pid']}_{$meta['fname']}_{$meta['lname']}.\" . $type;\n $content = $this->getCategoryIReport($pid, $measure, $type, $options);\n if (empty($content)) {\n continue;\n }\n file_put_contents($file, $content);\n file_put_contents($file_local, $content);\n // in order to deal with our zip files we are going to force our garbage collector to run\n // json_decode stores a LOT of memory with our measures so we need to collect it. Otherwise\n // we end up exceeding our memory usage. ~60 patients exceeds over 256MB of memory...\n // we end up trading CPU cycles to make sure we don't blow up smaller OpenEMR installations.\n unset($content);\n gc_mem_caches();\n gc_collect_cycles(); // attempt to force memory collection here.\n if ($type === 'xml') {\n copy(\n __DIR__ . '/../../../interface/modules/zend_modules/public/xsl/qrda.xsl',\n $measure_directory . \"/qrda.xsl\"\n );\n }\n }\n }\n $zip_measure = 'measures';\n if (count($measures ?? []) === 1) {\n $zip_measure = $measures[0];\n }\n $zip_name = \"QRDA1_\" . $zip_measure . \"_\" . time() . \".zip\";\n } elseif ($bypid) {\n foreach ($pids as $pid) {\n $meta = sqlQuery(\"Select `fname`, `lname`, `pid` From `patient_data` Where `pid` = ?\", [$pid]);\n $file = $zip_directory . \"/{$meta['pid']}_{$meta['fname']}_{$meta['lname']}.\" . $type;\n $file_local = $directory . \"/{$meta['pid']}_{$meta['fname']}_{$meta['lname']}.\" . $type;\n $content = $this->getCategoryIReport($pid, '', $type, $options);\n if (empty($content)) {\n continue;\n }\n file_put_contents($file, $content);\n file_put_contents($file_local, $content);\n unset($content);\n unset($file);\n }\n $zip_name = \"ep_measures_\" . time() . \".zip\";\n }\n\n $save_path = sys_get_temp_dir() . \"/\" . $zip_name;\n $zip = new \\ZipArchive();\n $ret = $zip->open($save_path, \\ZipArchive::CREATE | \\ZipArchive::OVERWRITE);\n if ($ret !== true) {\n throw new \\RuntimeException(sprintf('Zip file \"%s\" was not created due to \"%s\"', $save_path, $ret));\n } else {\n $dir = opendir($zip_directory);\n while ($filename = readdir($dir)) {\n $filename_path = $zip_directory . \"/\" . $filename;\n if (is_file($filename_path)) {\n $zip->addFile($filename_path, $filename);\n }\n if (\n is_dir($filename_path) &&\n (\n !($filename == \".\" || $filename == \"..\")\n )\n ) {\n $dir_in_dir = opendir($filename_path);\n while ($filename_in_dir = readdir($dir_in_dir)) {\n if (!($filename_in_dir == \".\" || $filename_in_dir == \"..\")) {\n $zip->addFile($filename_path . \"/\" . $filename_in_dir, $filename_in_dir);\n }\n }\n }\n }\n $zip->close();\n }\n\n ob_clean();\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n header(\"Cache-Control: private\", false);\n header('Content-type: application/zip');\n header(\"Content-Disposition: attachment; filename=\\\"\" . $zip_name . \"\\\";\");\n header(\"Content-Transfer-Encoding: binary\");\n header(\"Content-Length: \" . filesize($save_path));\n flush();\n readfile($save_path);\n flush();\n exit;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function GetUserCalendarTimezone($access_token) {\n\t\t$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';\n\n\t\t$ch = curl_init();\n\t\tcurl_setopt($ch, CURLOPT_URL, $url_settings);\n\t\tcurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n\t\tcurl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));\n\t\tcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n\t\t$data = json_decode(curl_exec($ch), true); //echo '
    ';print_r($data);echo '
    ';\n\t\t$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);\n\t\tif($http_code != 200)\n\t\t\tthrow new Exception('Error : Failed to get timezone');\n\n\t\treturn $data['value'];\n\t}", "smellKey": "S112", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function render($options=array()) {\n\n switch(strtolower($options['template'])) {\n case 'simple':\n $inc = STAFFINC_DIR . 'templates/dynamic-form-simple.tmpl.php';\n break;\n default:\n throw new Exception(sprintf(__('%s: Unknown template style %s'),\n get_class(), $options['template']));\n }\n\n $form = $this;\n include $inc;\n\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function (string $userId, Response $response, Database $dbForProject, Event $events) {\n\n $user = $dbForProject->getDocument('users', $userId);\n\n if ($user->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $sessions = $user->getAttribute('sessions', []);\n\n foreach ($sessions as $key => $session) {\n /** @var Document $session */\n $dbForProject->deleteDocument('sessions', $session->getId());\n //TODO: fix this\n }\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $events\n ->setParam('userId', $user->getId())\n ->setPayload($response->output($user, Response::MODEL_USER));\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function getClasses($namespace)\n {\n $namespace = $this->rootNamespace.'\\\\'.$namespace;\n $classes = [$namespace.'\\\\Api', $namespace.'\\\\Service'];\n\n foreach ($classes as $class) {\n if (!class_exists($class)) {\n throw new \\RuntimeException(sprintf('%s does not exist', $class));\n }\n }\n\n return $classes;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function prepareDefinitionInput(array $input): array\n {\n $definition_fkey = static::getDefinition()::getForeignKeyField();\n $definition_id = static::getDefinition()->getID();\n\n if (\n array_key_exists($definition_fkey, $input)\n && (int)$input[$definition_fkey] !== $definition_id\n ) {\n throw new \\RuntimeException('Definition does not match the current concrete class.');\n }\n\n if (\n !$this->isNewItem()\n && (int)$this->fields[$definition_fkey] !== $definition_id\n ) {\n throw new \\RuntimeException('Definition cannot be changed.');\n }\n\n $input[$definition_fkey] = $definition_id;\n\n return $input;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function getPhpPath()\n {\n if ($this->phpPath) {\n return $this->phpPath;\n }\n\n $phpFinder = new PhpExecutableFinder();\n $this->phpPath = $phpFinder->find();\n if (!$this->phpPath) {\n throw new RuntimeException(\n 'The php executable could not be found. It is needed for executing parallel subprocesses, so add it to your PATH environment variable and try again'\n );\n }\n\n return $this->phpPath;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function post_updateItem($history = true)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n // Handle rich-text images\n $this->input = $this->addFiles(\n $this->input,\n [\n 'force_update' => true,\n 'name' => 'content',\n 'content_field' => 'content',\n ]\n );\n\n if (in_array('plan_start_date', $this->updates, true) || in_array('plan_end_date', $this->updates, true)) {\n // dates have changed, check for planning conflicts on attached team\n $team = ProjectTaskTeam::getTeamFor($this->fields['id']);\n $users = [];\n foreach ($team as $type => $actors) {\n switch ($type) {\n case User::getType():\n foreach ($actors as $actor) {\n $users[$actor['items_id']] = $actor['items_id'];\n }\n break;\n case Group::getType():\n foreach ($actors as $actor) {\n $group_iterator = $DB->request([\n 'SELECT' => 'users_id',\n 'FROM' => Group_User::getTable(),\n 'WHERE' => ['groups_id' => $actor['items_id']]\n ]);\n foreach ($group_iterator as $row) {\n $users[$row['users_id']] = $row['users_id'];\n }\n }\n break;\n case Supplier::getType():\n case Contact::getType():\n //only Users can be checked for planning conflicts\n break;\n default:\n if (count($actors)) {\n throw new \\RuntimeException($type . \" is not (yet?) handled.\");\n }\n }\n }\n\n foreach ($users as $user) {\n Planning::checkAlreadyPlanned(\n $user,\n $this->fields['plan_start_date'],\n $this->fields['plan_end_date']\n );\n }\n }\n if (in_array('auto_percent_done', $this->updates, true) && (int) $this->input['auto_percent_done'] === 1) {\n // Auto-calculate was toggled. Force recalculation of this and parents\n self::recalculatePercentDone($this->getID());\n } else {\n // Update parent percent_done\n if ($this->fields['projecttasks_id'] > 0) {\n self::recalculatePercentDone($this->fields['projecttasks_id']);\n }\n if ($this->fields['projects_id'] > 0) {\n Project::recalculatePercentDone($this->fields['projects_id']);\n }\n }\n\n if (isset($this->input['_old_projects_id'])) {\n // Recalculate previous parent project percent done\n Project::recalculatePercentDone($this->input['_old_projects_id']);\n }\n if (isset($this->input['_old_projecttasks_id'])) {\n // Recalculate previous parent task percent done\n self::recalculatePercentDone($this->input['_old_projecttasks_id']);\n }\n\n if (!isset($this->input['_disablenotif']) && $CFG_GLPI[\"use_notifications\"]) {\n // Read again project to be sure that all data are up to date\n $this->getFromDB($this->fields['id']);\n NotificationEvent::raiseEvent(\"update\", $this);\n }\n\n // If task has changed of project, update all sub-tasks\n if (in_array('projects_id', $this->updates, true)) {\n foreach (self::getAllForProjectTask($this->getID()) as $task) {\n $task['projects_id'] = $this->fields['projects_id'];\n self::getById($task['id'])->update($task);\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function actionSaveGrades()\n {\n $students = Yii::app()->request->getPost(\"students\");\n $disciplineId = Yii::app()->request->getPost(\"discipline\");\n $classroomId = Yii::app()->request->getPost(\"classroom\");\n $isConcept = Yii::app()->request->getPost(\"isConcept\");\n\n $transaction = Yii::app()->db->beginTransaction();\n try {\n foreach ($students as $student) {\n foreach ($student[\"grades\"] as $grade) {\n\n $gradeObject = Grade::model()->findByPk($grade[\"id\"]);\n\n if ($gradeObject == null) {\n $gradeObject = new Grade();\n $gradeObject->enrollment_fk = $student[\"enrollmentId\"];\n $gradeObject->discipline_fk = $disciplineId;\n $gradeObject->grade_unity_modality_fk = $grade[\"modalityId\"];\n }\n if (!$isConcept) {\n TLog::info(\"Modo Grades notas selecionado.\", array(\"IsConcept\" => $isConcept));\n $gradeObject->grade = isset($grade[\"value\"]) && $grade[\"value\"] !== \"\" ? $grade[\"value\"] : 0;\n } else {\n TLog::info(\"Modo Grades conceito selecionado.\", array(\"IsConcept\" => $isConcept));\n $gradeObject->grade_concept_fk = $grade[\"concept\"];\n }\n if ($gradeObject->save()) {\n TLog::info(\"GradeObject salva com sucesso.\", array(\n \"GradeObject\" => $gradeObject->id\n ));\n }\n\n }\n foreach ($student[\"partialRecoveriesGrades\"] as $gradePartialRecovery) {\n $gradeObject = Grade::model()->findByPk($gradePartialRecovery[\"id\"]);\n\n if ($gradeObject == null) {\n $gradeObject = new Grade();\n $gradeObject->enrollment_fk = $student[\"enrollmentId\"];\n $gradeObject->discipline_fk = $disciplineId;\n }\n $gradeObject->grade = isset($gradePartialRecovery[\"value\"]) && $gradePartialRecovery[\"value\"] !== \"\" ? $gradePartialRecovery[\"value\"] : null;\n if ($gradeObject->save()) {\n TLog::info(\"GradeObject de PartialRecovery salva com sucesso.\", array(\n \"GradeObject\" => $gradeObject->id\n ));\n }\n }\n }\n self::saveGradeResults($classroomId, $disciplineId);\n $transaction->commit();\n header('HTTP/1.1 200 OK');\n echo json_encode([\"valid\" => true]);\n } catch (Exception $e) {\n TLog::error(\"Ocorreu algum erro durante a transa\u00e7\u00e3o de SaveGrades\", [\"ExceptionMessage\" => $e->getMessage()]);\n $transaction->rollback();\n throw new Exception($e->getMessage(), 500, $e);\n }\n\n\n }", "smellKey": "S112", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function read(int $length): string\n {\n if (0 === $length) {\n return '';\n }\n $data = fread($this->resource, $length);\n if (false === $data) {\n throw new RuntimeException('Unable to read the memory');\n }\n if (mb_strlen($data, '8bit') !== $length) {\n throw new InvalidArgumentException(sprintf('Out of range. Expected: %d, read: %d.', $length, mb_strlen($data, '8bit')));\n }\n\n return $data;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function _writeDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1)\n\t{\n\t\tif ($pRelationId >= 0) {\n\t\t\t// xdr:oneCellAnchor\n\t\t\t$objWriter->startElement('xdr:oneCellAnchor');\n\t\t\t\t// Image location\n\t\t\t\t$aCoordinates \t\t= PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates());\n\t\t\t\t$aCoordinates[0] \t= PHPExcel_Cell::columnIndexFromString($aCoordinates[0]);\n\n\t\t\t\t// xdr:from\n\t\t\t\t$objWriter->startElement('xdr:from');\n\t\t\t\t\t$objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);\n\t\t\t\t\t$objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));\n\t\t\t\t\t$objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);\n\t\t\t\t\t$objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));\n\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t// xdr:ext\n\t\t\t\t$objWriter->startElement('xdr:ext');\n\t\t\t\t\t$objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));\n\t\t\t\t\t$objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));\n\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t// xdr:pic\n\t\t\t\t$objWriter->startElement('xdr:pic');\n\n\t\t\t\t\t// xdr:nvPicPr\n\t\t\t\t\t$objWriter->startElement('xdr:nvPicPr');\n\n\t\t\t\t\t\t// xdr:cNvPr\n\t\t\t\t\t\t$objWriter->startElement('xdr:cNvPr');\n\t\t\t\t\t\t$objWriter->writeAttribute('id', $pRelationId);\n\t\t\t\t\t\t$objWriter->writeAttribute('name', $pDrawing->getName());\n\t\t\t\t\t\t$objWriter->writeAttribute('descr', $pDrawing->getDescription());\n\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t// xdr:cNvPicPr\n\t\t\t\t\t\t$objWriter->startElement('xdr:cNvPicPr');\n\n\t\t\t\t\t\t\t// a:picLocks\n\t\t\t\t\t\t\t$objWriter->startElement('a:picLocks');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('noChangeAspect', '1');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t// xdr:blipFill\n\t\t\t\t\t$objWriter->startElement('xdr:blipFill');\n\n\t\t\t\t\t\t// a:blip\n\t\t\t\t\t\t$objWriter->startElement('a:blip');\n\t\t\t\t\t\t$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');\n\t\t\t\t\t\t$objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);\n\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t// a:stretch\n\t\t\t\t\t\t$objWriter->startElement('a:stretch');\n\t\t\t\t\t\t\t$objWriter->writeElement('a:fillRect', null);\n\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t// xdr:spPr\n\t\t\t\t\t$objWriter->startElement('xdr:spPr');\n\n\t\t\t\t\t\t// a:xfrm\n\t\t\t\t\t\t$objWriter->startElement('a:xfrm');\n\t\t\t\t\t\t$objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation()));\n\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t// a:prstGeom\n\t\t\t\t\t\t$objWriter->startElement('a:prstGeom');\n\t\t\t\t\t\t$objWriter->writeAttribute('prst', 'rect');\n\n\t\t\t\t\t\t\t// a:avLst\n\t\t\t\t\t\t\t$objWriter->writeElement('a:avLst', null);\n\n\t\t\t\t\t\t$objWriter->endElement();\n\n//\t\t\t\t\t\t// a:solidFill\n//\t\t\t\t\t\t$objWriter->startElement('a:solidFill');\n\n//\t\t\t\t\t\t\t// a:srgbClr\n//\t\t\t\t\t\t\t$objWriter->startElement('a:srgbClr');\n//\t\t\t\t\t\t\t$objWriter->writeAttribute('val', 'FFFFFF');\n\n///* SHADE\n//\t\t\t\t\t\t\t\t// a:shade\n//\t\t\t\t\t\t\t\t$objWriter->startElement('a:shade');\n//\t\t\t\t\t\t\t\t$objWriter->writeAttribute('val', '85000');\n//\t\t\t\t\t\t\t\t$objWriter->endElement();\n//*/\n\n//\t\t\t\t\t\t\t$objWriter->endElement();\n\n//\t\t\t\t\t\t$objWriter->endElement();\n/*\n\t\t\t\t\t\t// a:ln\n\t\t\t\t\t\t$objWriter->startElement('a:ln');\n\t\t\t\t\t\t$objWriter->writeAttribute('w', '88900');\n\t\t\t\t\t\t$objWriter->writeAttribute('cap', 'sq');\n\n\t\t\t\t\t\t\t// a:solidFill\n\t\t\t\t\t\t\t$objWriter->startElement('a:solidFill');\n\n\t\t\t\t\t\t\t\t// a:srgbClr\n\t\t\t\t\t\t\t\t$objWriter->startElement('a:srgbClr');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('val', 'FFFFFF');\n\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t// a:miter\n\t\t\t\t\t\t\t$objWriter->startElement('a:miter');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('lim', '800000');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t$objWriter->endElement();\n*/\n\n\t\t\t\t\t\tif ($pDrawing->getShadow()->getVisible()) {\n\t\t\t\t\t\t\t// a:effectLst\n\t\t\t\t\t\t\t$objWriter->startElement('a:effectLst');\n\n\t\t\t\t\t\t\t\t// a:outerShdw\n\t\t\t\t\t\t\t\t$objWriter->startElement('a:outerShdw');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('blurRad', \t\tPHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('dist',\t\t\tPHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('dir',\t\t\tPHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('algn',\t\t\t$pDrawing->getShadow()->getAlignment());\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('rotWithShape', \t'0');\n\n\t\t\t\t\t\t\t\t\t// a:srgbClr\n\t\t\t\t\t\t\t\t\t$objWriter->startElement('a:srgbClr');\n\t\t\t\t\t\t\t\t\t$objWriter->writeAttribute('val',\t\t$pDrawing->getShadow()->getColor()->getRGB());\n\n\t\t\t\t\t\t\t\t\t\t// a:alpha\n\t\t\t\t\t\t\t\t\t\t$objWriter->startElement('a:alpha');\n\t\t\t\t\t\t\t\t\t\t$objWriter->writeAttribute('val', \t$pDrawing->getShadow()->getAlpha() * 1000);\n\t\t\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->endElement();\n\t\t\t\t\t\t}\n/*\n\n\t\t\t\t\t\t// a:scene3d\n\t\t\t\t\t\t$objWriter->startElement('a:scene3d');\n\n\t\t\t\t\t\t\t// a:camera\n\t\t\t\t\t\t\t$objWriter->startElement('a:camera');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('prst', 'orthographicFront');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t// a:lightRig\n\t\t\t\t\t\t\t$objWriter->startElement('a:lightRig');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('rig', 'twoPt');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('dir', 't');\n\n\t\t\t\t\t\t\t\t// a:rot\n\t\t\t\t\t\t\t\t$objWriter->startElement('a:rot');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('lat', '0');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('lon', '0');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('rev', '0');\n\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t$objWriter->endElement();\n*/\n/*\n\t\t\t\t\t\t// a:sp3d\n\t\t\t\t\t\t$objWriter->startElement('a:sp3d');\n\n\t\t\t\t\t\t\t// a:bevelT\n\t\t\t\t\t\t\t$objWriter->startElement('a:bevelT');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('w', '25400');\n\t\t\t\t\t\t\t$objWriter->writeAttribute('h', '19050');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t// a:contourClr\n\t\t\t\t\t\t\t$objWriter->startElement('a:contourClr');\n\n\t\t\t\t\t\t\t\t// a:srgbClr\n\t\t\t\t\t\t\t\t$objWriter->startElement('a:srgbClr');\n\t\t\t\t\t\t\t\t$objWriter->writeAttribute('val', 'FFFFFF');\n\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t$objWriter->endElement();\n*/\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t// xdr:clientData\n\t\t\t\t$objWriter->writeElement('xdr:clientData', null);\n\n\t\t\t$objWriter->endElement();\n\t\t} else {\n\t\t\tthrow new Exception(\"Invalid parameters passed.\");\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function (string $teamId, array $queries, string $search, Response $response, Database $dbForProject) {\n\n $team = $dbForProject->getDocument('teams', $teamId);\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n // Set internal queries\n $queries[] = Query::equal('teamId', [$teamId]);\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $membershipId = $cursor->getValue();\n $cursorDocument = $dbForProject->getDocument('memberships', $membershipId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Membership '{$membershipId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $memberships = $dbForProject->find(\n collection: 'memberships',\n queries: $queries,\n );\n\n $total = $dbForProject->count(\n collection: 'memberships',\n queries: $filterQueries,\n max: APP_LIMIT_COUNT\n );\n\n $memberships = array_filter($memberships, fn(Document $membership) => !empty($membership->getAttribute('userId')));\n\n $memberships = array_map(function ($membership) use ($dbForProject, $team) {\n $user = $dbForProject->getDocument('users', $membership->getAttribute('userId'));\n\n $membership\n ->setAttribute('teamName', $team->getAttribute('name'))\n ->setAttribute('userName', $user->getAttribute('name'))\n ->setAttribute('userEmail', $user->getAttribute('email'))\n ;\n\n return $membership;\n }, $memberships);\n\n $response->dynamic(new Document([\n 'memberships' => $memberships,\n 'total' => $total,\n ]), Response::MODEL_MEMBERSHIP_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function thumbnailUpdateAction(Request $request): JsonResponse\n {\n $this->checkPermission('thumbnails');\n\n $pipe = Asset\\Image\\Thumbnail\\Config::getByName($request->get('name'));\n\n if (!$pipe->isWriteable()) {\n throw new ConfigWriteException();\n }\n\n $settingsData = $this->decodeJson($request->get('settings'));\n $mediaData = $this->decodeJson($request->get('medias'));\n $mediaOrder = $this->decodeJson($request->get('mediaOrder'));\n\n foreach ($settingsData as $key => $value) {\n $setter = 'set' . ucfirst($key);\n if (method_exists($pipe, $setter)) {\n $pipe->$setter($value);\n }\n }\n\n $pipe->resetItems();\n\n uksort($mediaData, function ($a, $b) use ($mediaOrder) {\n if ($a === 'default') {\n return -1;\n }\n\n return ($mediaOrder[$a] < $mediaOrder[$b]) ? -1 : 1;\n });\n\n foreach ($mediaData as $mediaName => $items) {\n if (preg_match('/[\"<>]/', $mediaName)) {\n throw new \\Exception('Invalid media query name');\n }\n\n foreach ($items as $item) {\n $type = $item['type'];\n unset($item['type']);\n\n $pipe->addItem($type, $item, $mediaName);\n }\n }\n\n $pipe->save();\n\n return $this->adminJson(['success' => true]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function setDisplayName($uid, $displayName) {\n\t\t$plugin = $this->which[Backend::SET_DISPLAYNAME];\n\n\t\tif ($plugin) {\n\t\t\treturn $plugin->setDisplayName($uid, $displayName);\n\t\t}\n\t\tthrow new \\Exception('No plugin implements setDisplayName in this LDAP Backend.');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function request($url) {\n $ch = curl_init();\n curl_setopt_array($ch, array(\n CURLOPT_CONNECTTIMEOUT => 10,\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_TIMEOUT => 60,\n CURLOPT_HTTPHEADER => array('Expect:'),\n CURLOPT_SSL_VERIFYPEER => false,\n CURLOPT_SSL_VERIFYHOST => false,\n CURLOPT_URL => $url\n ));\n $response = curl_exec($ch);\n if($response === false)\n throw new \\Exception(\"URL request failed:\".curl_error($ch));\n\n return $response;\n }", "smellKey": "S112", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "function clearAll()\n {\n throw new Exception('clearAll not implemented for SavantRenderEngine');\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function create(string $permission): self|static\n {\n if (!$permission) {\n throw new Exception('No permisson defined.');\n }\n $permissionDefinition = static::getByKey($permission);\n if ($permissionDefinition instanceof self) {\n Logger::info(\"Permission $permission allready exists. Skipping creation.\");\n\n return $permissionDefinition;\n } else {\n $permissionDefinition = new static();\n $permissionDefinition->setKey($permission);\n $permissionDefinition->save();\n\n return $permissionDefinition;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function writeWorksheet($pSheet = null, $pStringTable = null)\n\t{\n\t\tif (!is_null($pSheet)) {\n\t\t\t// Create XML writer\n\t\t\t$objWriter = null;\n\t\t\tif ($this->getParentWriter()->getUseDiskCaching()) {\n\t\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());\n\t\t\t} else {\n\t\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);\n\t\t\t}\n\n\t\t\t// XML header\n\t\t\t$objWriter->startDocument('1.0','UTF-8','yes');\n\n\t\t\t// Worksheet\n\t\t\t$objWriter->startElement('worksheet');\n\t\t\t$objWriter->writeAttribute('xml:space', 'preserve');\n\t\t\t$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');\n\t\t\t$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');\n\n\t\t\t\t// sheetPr\n\t\t\t\t$this->_writeSheetPr($objWriter, $pSheet);\n\n\t\t\t\t// Dimension\n\t\t\t\t$this->_writeDimension($objWriter, $pSheet);\n\n\t\t\t\t// sheetViews\n\t\t\t\t$this->_writeSheetViews($objWriter, $pSheet);\n\n\t\t\t\t// sheetFormatPr\n\t\t\t\t$this->_writeSheetFormatPr($objWriter, $pSheet);\n\n\t\t\t\t// cols\n\t\t\t\t$this->_writeCols($objWriter, $pSheet);\n\n\t\t\t\t// sheetData\n\t\t\t\t$this->_writeSheetData($objWriter, $pSheet, $pStringTable);\n\n\t\t\t\t// sheetProtection\n\t\t\t\t$this->_writeSheetProtection($objWriter, $pSheet);\n\n\t\t\t\t// protectedRanges\n\t\t\t\t$this->_writeProtectedRanges($objWriter, $pSheet);\n\n\t\t\t\t// autoFilter\n\t\t\t\t$this->_writeAutoFilter($objWriter, $pSheet);\n\n\t\t\t\t// mergeCells\n\t\t\t\t$this->_writeMergeCells($objWriter, $pSheet);\n\n\t\t\t\t// conditionalFormatting\n\t\t\t\t$this->_writeConditionalFormatting($objWriter, $pSheet);\n\n\t\t\t\t// dataValidations\n\t\t\t\t$this->_writeDataValidations($objWriter, $pSheet);\n\n\t\t\t\t// hyperlinks\n\t\t\t\t$this->_writeHyperlinks($objWriter, $pSheet);\n\n\t\t\t\t// Print options\n\t\t\t\t$this->_writePrintOptions($objWriter, $pSheet);\n\n\t\t\t\t// Page margins\n\t\t\t\t$this->_writePageMargins($objWriter, $pSheet);\n\n\t\t\t\t// Page setup\n\t\t\t\t$this->_writePageSetup($objWriter, $pSheet);\n\n\t\t\t\t// Header / footer\n\t\t\t\t$this->_writeHeaderFooter($objWriter, $pSheet);\n\n\t\t\t\t// Breaks\n\t\t\t\t$this->_writeBreaks($objWriter, $pSheet);\n\n\t\t\t\t// Drawings\n\t\t\t\t$this->_writeDrawings($objWriter, $pSheet);\n\n\t\t\t\t// LegacyDrawing\n\t\t\t\t$this->_writeLegacyDrawing($objWriter, $pSheet);\n\n\t\t\t\t// LegacyDrawingHF\n\t\t\t\t$this->_writeLegacyDrawingHF($objWriter, $pSheet);\n\n\t\t\t$objWriter->endElement();\n\n\t\t\t// Return\n\t\t\treturn $objWriter->getData();\n\t\t} else {\n\t\t\tthrow new Exception(\"Invalid PHPExcel_Worksheet object passed.\");\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public static function getMostPrivilegedAcl(XDUser $user, $moduleName = DEFAULT_MODULE_NAME, $aclHierarchyName = 'acl_hierarchy')\n {\n if (null === $user->getUserID()) {\n throw new Exception('A valid user id must be supplied.');\n }\n\n $query = <<query($query, array(\n ':acl_hierarchy_name' => $aclHierarchyName,\n ':user_id' => $user->getUserID()\n ));\n\n if (count($rows) > 0) {\n return new Acl($rows[0]);\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function useWordBreaksFromEnvironment()\n {\n $breaks = getenv('CMDLINE_WORDBREAKS');\n\n if (!$breaks) {\n throw new \\RuntimeException('Failed to read word breaks from environment; Environment var CMDLINE_WORDBREAKS not set');\n }\n\n $this->wordBreaks = $breaks;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function render($minify = true): string\n {\n if ($this->rendered) { // Don't render any template\n return '';\n }\n\n if (\\is_readable($this->path)) {\n $template = \\file_get_contents($this->path); // Include template file\n } elseif (!empty($this->content)) {\n $template = $this->print($this->content, self::FILTER_NL2P);\n } else {\n throw new Exception('\"' . $this->path . '\" template is not readable or not found');\n }\n\n // First replace the variables inside the params. Then replace the variables in the template\n $this->params = array_merge($this->params, \\str_replace(\\array_keys($this->params), \\array_values($this->params), $this->params));\n $template = \\str_replace(\\array_keys($this->params), \\array_values($this->params), $template);\n\n return $template;\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function prepareFilterForUsersInPrimaryGroup(string $groupDN, string $search = ''): string {\n\t\t$groupID = $this->getGroupPrimaryGroupID($groupDN);\n\t\tif ($groupID === false) {\n\t\t\tthrow new Exception('Not a valid group');\n\t\t}\n\n\t\t$filterParts = [];\n\t\t$filterParts[] = $this->access->getFilterForUserCount();\n\t\tif ($search !== '') {\n\t\t\t$filterParts[] = $this->access->getFilterPartForUserSearch($search);\n\t\t}\n\t\t$filterParts[] = 'primaryGroupID=' . $groupID;\n\n\t\treturn $this->access->combineFilterWithAnd($filterParts);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getToken($pId = 0) {\n \tif (isset($this->_tokens[$pId])) {\n \t\treturn $this->_tokens[$pId];\n \t} else {\n \t\tthrow new Exception(\"Token with id $pId does not exist.\");\n \t}\n }", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function (string $teamId, array $prefs, Response $response, Database $dbForProject, Event $events) {\n\n $team = $dbForProject->getDocument('teams', $teamId);\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n $team = $dbForProject->updateDocument('teams', $team->getId(), $team->setAttribute('prefs', $prefs));\n\n $events->setParam('teamId', $team->getId());\n\n $response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function createAttribute(string $databaseId, string $collectionId, Document $attribute, Response $response, Database $dbForProject, EventDatabase $database, Event $events): Document\n{\n $key = $attribute->getAttribute('key');\n $type = $attribute->getAttribute('type', '');\n $size = $attribute->getAttribute('size', 0);\n $required = $attribute->getAttribute('required', true);\n $signed = $attribute->getAttribute('signed', true); // integers are signed by default\n $array = $attribute->getAttribute('array', false);\n $format = $attribute->getAttribute('format', '');\n $formatOptions = $attribute->getAttribute('formatOptions', []);\n $filters = $attribute->getAttribute('filters', []); // filters are hidden from the endpoint\n $default = $attribute->getAttribute('default');\n $options = $attribute->getAttribute('options', []);\n\n $db = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId));\n\n if ($db->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n if (!empty($format)) {\n if (!Structure::hasFormat($format, $type)) {\n throw new Exception(Exception::ATTRIBUTE_FORMAT_UNSUPPORTED, \"Format {$format} not available for {$type} attributes.\");\n }\n }\n\n // Must throw here since dbForProject->createAttribute is performed by db worker\n if ($required && isset($default)) {\n throw new Exception(Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED, 'Cannot set default value for required attribute');\n }\n\n if ($array && isset($default)) {\n throw new Exception(Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED, 'Cannot set default value for array attributes');\n }\n\n if ($type === Database::VAR_RELATIONSHIP) {\n $options['side'] = Database::RELATION_SIDE_PARENT;\n $relatedCollection = $dbForProject->getDocument('database_' . $db->getInternalId(), $options['relatedCollection'] ?? '');\n if ($relatedCollection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND, 'The related collection was not found.');\n }\n }\n\n try {\n $attribute = new Document([\n '$id' => ID::custom($db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key),\n 'key' => $key,\n 'databaseInternalId' => $db->getInternalId(),\n 'databaseId' => $db->getId(),\n 'collectionInternalId' => $collection->getInternalId(),\n 'collectionId' => $collectionId,\n 'type' => $type,\n 'status' => 'processing', // processing, available, failed, deleting, stuck\n 'size' => $size,\n 'required' => $required,\n 'signed' => $signed,\n 'default' => $default,\n 'array' => $array,\n 'format' => $format,\n 'formatOptions' => $formatOptions,\n 'filters' => $filters,\n 'options' => $options,\n ]);\n\n $dbForProject->checkAttribute($collection, $attribute);\n $attribute = $dbForProject->createDocument('attributes', $attribute);\n } catch (DuplicateException) {\n throw new Exception(Exception::ATTRIBUTE_ALREADY_EXISTS);\n } catch (LimitException) {\n throw new Exception(Exception::ATTRIBUTE_LIMIT_EXCEEDED, 'Attribute limit exceeded');\n } catch (\\Exception $e) {\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId);\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId());\n throw $e;\n }\n\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId);\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId());\n\n if ($type === Database::VAR_RELATIONSHIP && $options['twoWay']) {\n $twoWayKey = $options['twoWayKey'];\n $options['relatedCollection'] = $collection->getId();\n $options['twoWayKey'] = $key;\n $options['side'] = Database::RELATION_SIDE_CHILD;\n\n try {\n $twoWayAttribute = new Document([\n '$id' => ID::custom($db->getInternalId() . '_' . $relatedCollection->getInternalId() . '_' . $twoWayKey),\n 'key' => $twoWayKey,\n 'databaseInternalId' => $db->getInternalId(),\n 'databaseId' => $db->getId(),\n 'collectionInternalId' => $relatedCollection->getInternalId(),\n 'collectionId' => $relatedCollection->getId(),\n 'type' => $type,\n 'status' => 'processing', // processing, available, failed, deleting, stuck\n 'size' => $size,\n 'required' => $required,\n 'signed' => $signed,\n 'default' => $default,\n 'array' => $array,\n 'format' => $format,\n 'formatOptions' => $formatOptions,\n 'filters' => $filters,\n 'options' => $options,\n ]);\n\n $dbForProject->checkAttribute($relatedCollection, $twoWayAttribute);\n $dbForProject->createDocument('attributes', $twoWayAttribute);\n } catch (DuplicateException) {\n $dbForProject->deleteDocument('attributes', $attribute->getId());\n throw new Exception(Exception::ATTRIBUTE_ALREADY_EXISTS);\n } catch (LimitException) {\n $dbForProject->deleteDocument('attributes', $attribute->getId());\n throw new Exception(Exception::ATTRIBUTE_LIMIT_EXCEEDED, 'Attribute limit exceeded');\n } catch (\\Exception $e) {\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $relatedCollection->getId());\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $relatedCollection->getInternalId());\n throw $e;\n }\n\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $relatedCollection->getId());\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $relatedCollection->getInternalId());\n }\n\n $database\n ->setType(DATABASE_TYPE_CREATE_ATTRIBUTE)\n ->setDatabase($db)\n ->setCollection($collection)\n ->setDocument($attribute);\n\n $events\n ->setContext('collection', $collection)\n ->setContext('database', $db)\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('attributeId', $attribute->getId());\n\n $response->setStatusCode(Response::STATUS_CODE_CREATED);\n\n return $attribute;\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function displayLdapFilter($target, $users = true)\n {\n $config_ldap = new self();\n if (!isset($_SESSION['ldap_server'])) {\n throw new \\RuntimeException('LDAP server must be set!');\n }\n $config_ldap->getFromDB($_SESSION['ldap_server']);\n\n $filter_name1 = null;\n $filter_name2 = null;\n if ($users) {\n $filter_name1 = \"condition\";\n $filter_var = \"ldap_filter\";\n } else {\n $filter_var = \"ldap_group_filter\";\n switch ($config_ldap->fields[\"group_search_type\"]) {\n case self::GROUP_SEARCH_USER:\n $filter_name1 = \"condition\";\n break;\n case self::GROUP_SEARCH_GROUP:\n $filter_name1 = \"group_condition\";\n break;\n case self::GROUP_SEARCH_BOTH:\n $filter_name1 = \"group_condition\";\n $filter_name2 = \"condition\";\n break;\n }\n }\n\n if ($filter_name1 !== null && empty($_SESSION[$filter_var])) {\n $_SESSION[$filter_var] = $config_ldap->fields[$filter_name1];\n }\n\n // Only display when looking for groups in users AND groups\n if (\n !$users\n && ($config_ldap->fields[\"group_search_type\"] === self::GROUP_SEARCH_BOTH)\n ) {\n if ($filter_name2 !== null && empty($_SESSION[\"ldap_group_filter2\"])) {\n $_SESSION[\"ldap_group_filter2\"] = $config_ldap->fields[$filter_name2];\n }\n }\n\n TemplateRenderer::getInstance()->display('pages/setup/ldap/filter.html.twig', [\n 'target' => $target,\n 'users' => $users,\n 'filter_name1' => $filter_name1,\n 'filter_name2' => $filter_name2,\n 'filter_var' => $filter_var,\n 'config_ldap' => $config_ldap,\n ]);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function sendProfileWithGroups($profiles): int\n {\n $result = 0;\n sqlStatementNoLog('SET autocommit=0');\n sqlStatementNoLog('START TRANSACTION');\n $results = [];\n try {\n foreach ($profiles as $profile) {\n $sql = 'Select pd.pid, ptd.profile, ptd.member_of, tpl.* From `patient_data` pd ' .\n \"Join `document_template_profiles` as ptd On pd.patient_groups LIKE CONCAT('%',ptd.member_of, '%') And ptd.profile = ? \" .\n 'Join (Select * From `document_template_profiles`) tplId On tplId.profile = ptd.profile ' .\n 'Join (Select `id`, `category`, `template_name`, `location`, `template_content`, `mime` From `document_templates`) as tpl On tpl.id = tplId.template_id';\n $query_result = sqlStatement($sql, array($profile));\n while ($row = sqlFetchArray($query_result)) {\n if (is_array($row)) {\n $tid = $row['template_name'];\n $result = $this->insertTemplate(\n $row['pid'],\n $row['category'],\n $row['template_name'],\n $row['template_content'],\n $row['mime'],\n $profile\n );\n //$results[$row['pid']][$row['profile']][$tid] = $row;\n }\n }\n }\n } catch (Exception $e) {\n throw new RuntimeException($e->getMessage(), $e->getCode(), $e);\n }\n sqlStatementNoLog('COMMIT');\n sqlStatementNoLog('SET autocommit=1');\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct()\n {\n if (empty($GLOBALS['oefax_enable_fax'] ?? null)) {\n throw new \\Exception(xlt(\"Access denied! Module not enabled\"));\n }\n\n $this->crypto = new CryptoGen();\n $this->baseDir = $GLOBALS['temporary_files_dir'];\n $this->uriDir = $GLOBALS['OE_SITE_WEBROOT'];\n $this->credentials = $this->getCredentials();\n $this->client = new EtherFaxClient();\n $this->client->setCredentials(\n $this->credentials['account'] ?? '',\n $this->credentials['username'] ?? '',\n $this->credentials['password'] ?? '',\n $this->credentials['appKey'] ?? ''\n );\n $this->portalUrl = \"https://clients.connect.etherfax.net/Account/Login\";\n parent::__construct();\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function handle()\n {\n $setting = $this->argument('setting');\n\n if ($this->option('dump')) {\n $this->line($setting ? json_encode(Config::get($setting)) : Config::toJson());\n\n return 0;\n }\n\n if (! $setting) {\n throw new \\RuntimeException('Not enough arguments (missing: \"setting\").');\n }\n\n if (Config::has($setting)) {\n $output = Config::get($setting);\n if (! is_string($output)) {\n $output = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);\n }\n\n $this->line($output);\n\n return 0;\n }\n\n return 1;\n }", "smellKey": "S112", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "protected function matchTypeAndDestination($action)\n {\n if (preg_match('#^([a-zA-Z0-9_]+):(.+)?$#', $action, $matches)) {\n $actionType = $matches[1];\n $actionValue = isset($matches[2]) ? $matches[2] : false;\n\n switch ($actionType) {\n case 'eznode':\n $type = UrlAlias::LOCATION;\n $destination = (int)$actionValue;\n break;\n\n case 'module':\n $type = UrlAlias::RESOURCE;\n $destination = $actionValue;\n break;\n\n case 'nop':\n $type = UrlAlias::VIRTUAL;\n $destination = null;\n break;\n\n default:\n // @todo log message\n throw new \\RuntimeException(\"Action type '{$actionType}' is unknown\");\n }\n } else {\n // @todo log message\n throw new \\RuntimeException(\"Action '{$action}' is not valid\");\n }\n\n return [$type, $destination];\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function createFromConfigFile($file)\n {\n $config = Json::loadFile($file);\n\n if (!isset($config['name'])) {\n throw new Exception(\"No module name specified in '$file'\");\n }\n\n if (!isset($config['version'])) {\n throw new Exception(\"No version specified in '$file'\");\n }\n\n if (!isset($config['release'])) {\n $config['release'] = 1;\n }\n\n if (!array_key_exists('prerelease', $config)) {\n $config['prerelease'] = false;\n }\n\n if (!isset($config['files'])) {\n throw new Exception(\"No files specified in '$file'\");\n }\n\n $fileIncludePaths\n = isset($config['files']['include_paths'])\n ? $config['files']['include_paths']\n : array();\n\n $fileIncludePatterns\n = isset($config['files']['include_patterns'])\n ? $config['files']['include_patterns']\n : array();\n\n $fileExcludePaths\n = isset($config['files']['exclude_paths'])\n ? $config['files']['exclude_paths']\n : array();\n\n $fileExcludePatterns\n = isset($config['files']['exclude_patterns'])\n ? $config['files']['exclude_patterns']\n : array();\n\n $fileMaps\n = isset($config['file_maps'])\n ? static::normalizeFileMaps($config['file_maps'])\n : array();\n\n $commandsPreBuild\n = isset($config['commands']['pre_build'])\n ? $config['commands']['pre_build']\n : array();\n\n return new static(array(\n 'name' => $config['name'],\n 'version' => $config['version'],\n 'release' => $config['release'],\n 'prerelease' => $config['prerelease'],\n 'file_include_paths' => $fileIncludePaths,\n 'file_include_patterns' => $fileIncludePatterns,\n 'file_exclude_paths' => $fileExcludePaths,\n 'file_exclude_patterns' => $fileExcludePatterns,\n 'file_maps' => $fileMaps,\n 'commands_pre_build' => $commandsPreBuild\n ));\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function GetRoute($uri = \"\")\n {\n if ($uri == \"\") {\n $action = RequestUtil::Get('action');\n if (! $action) {\n $action = $this->_defaultRoute;\n }\n\n $uri = $action ? $action : RequestUtil::GetCurrentURL();\n }\n\n // get the action requested\n $params = explode(\".\", str_replace(\"/\", \".\", $uri));\n $controller_param = isset($params [0]) && $params [0] ? $params [0] : \"\";\n $controller_param = str_replace(array (\n \".\",\n \"/\",\n \"\\\\\"\n ), array (\n \"\",\n \"\",\n \"\"\n ), $controller_param);\n\n if (! $controller_param) {\n throw new Exception(\"Invalid or missing Controller parameter\");\n }\n\n $method_param = isset($params [1]) && $params [1] ? $params [1] : \"\";\n if (! $method_param) {\n $method_param = \"DefaultAction\";\n }\n\n return array (\n $controller_param,\n $method_param\n );\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function check(ElementInterface $element, array $users): array\n {\n $protectedColumns = ['cid', 'cpath', 'userId', 'lEdit', 'lView', 'layouts'];\n\n if ($element instanceof DataObject\\AbstractObject) {\n $type = 'object';\n } else {\n if ($element instanceof Asset) {\n $type = 'asset';\n } else {\n if ($element instanceof Document) {\n $type = 'document';\n } else {\n throw new Exception('type not supported');\n }\n }\n }\n $db = Db::get();\n $tableName = 'users_workspaces_'.$type;\n $tableDesc = $db->fetchAllAssociative('describe '.$tableName);\n\n $result = [\n 'columns' => [],\n ];\n\n foreach ($tableDesc as $column) {\n $columnName = $column['Field'];\n if (in_array($columnName, $protectedColumns)) {\n continue;\n }\n\n $result['columns'][] = $columnName;\n }\n\n $permissions = [];\n $details = [];\n\n foreach ($users as $user) {\n if (!$user instanceof User) {\n continue;\n }\n\n $userPermission = [];\n $userPermission['userId'] = $user->getId();\n $userPermission['userName'] = $user->getName();\n\n foreach ($result['columns'] as $columnName) {\n $parentIds = self::collectParentIds($element);\n\n $userIds = $user->getRoles();\n\n $userIds[] = $user->getId();\n\n if ($user->isAdmin()) {\n $userPermission[$columnName] = true;\n\n continue;\n }\n\n $userPermission[$columnName] = false;\n\n try {\n $permissionsParent = $db->fetchAssociative(\n 'SELECT * FROM users_workspaces_'.$type.' , users u WHERE userId = u.id AND cid IN ('.implode(\n ',',\n $parentIds\n ).') AND userId IN ('.implode(\n ',',\n $userIds\n ).') ORDER BY LENGTH(cpath) DESC, FIELD(userId,'.$user->getId().') DESC, `' . $columnName . '` DESC LIMIT 1'\n );\n\n if ($permissionsParent) {\n $userPermission[$columnName] = $permissionsParent[$columnName] ? true : false;\n\n $details[] = self::createDetail($user, $columnName, $userPermission[$columnName], $permissionsParent['type'], $permissionsParent['name'], $permissionsParent['cpath']);\n\n continue;\n }\n\n // exception for list permission\n if (false === $permissionsParent && $columnName === 'list') {\n // check for children with permissions\n $path = $element->getRealFullPath().'/';\n if ($element->getId() == 1) {\n $path = '/';\n }\n\n $permissionsChildren = $db->fetchAssociative(\n 'SELECT list FROM users_workspaces_'.$type.', users u WHERE userId = u.id AND cpath LIKE ? AND userId IN ('.implode(\n ',',\n $userIds\n ).') AND list = 1 LIMIT 1',\n [Helper::escapeLike($path) .'%']\n );\n if ($permissionsChildren) {\n $result[$columnName] = $permissionsChildren[$columnName] ? true : false;\n $details[] = self::createDetail($user, $columnName, $result[$columnName], $permissionsChildren['type'], $permissionsChildren['name'], $permissionsChildren['cpath']);\n\n continue;\n }\n }\n } catch (Exception $e) {\n Logger::warn('Unable to get permission '.$type.' for object '.$element->getId());\n }\n }\n self::getUserPermissions($user, $details);\n self::getLanguagePermissions($user, $element, $details);\n $permissions[] = $userPermission;\n }\n\n $result['permissions'] = $permissions;\n\n $result['details'] = $details;\n\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function _output(?string $filePath = null, ?string $mimeType = null): bool {\n\t\tif ($filePath) {\n\t\t\tif (!file_exists(dirname($filePath))) {\n\t\t\t\tmkdir(dirname($filePath), 0777, true);\n\t\t\t}\n\t\t\t$isWritable = is_writable(dirname($filePath));\n\t\t\tif (!$isWritable) {\n\t\t\t\t$this->logger->error(__METHOD__ . '(): Directory \\'' . dirname($filePath) . '\\' is not writable.', ['app' => 'core']);\n\t\t\t\treturn false;\n\t\t\t} elseif (file_exists($filePath) && !is_writable($filePath)) {\n\t\t\t\t$this->logger->error(__METHOD__ . '(): File \\'' . $filePath . '\\' is not writable.', ['app' => 'core']);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!$this->valid()) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$imageType = $this->imageType;\n\t\tif ($mimeType !== null) {\n\t\t\tswitch ($mimeType) {\n\t\t\t\tcase 'image/gif':\n\t\t\t\t\t$imageType = IMAGETYPE_GIF;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/jpeg':\n\t\t\t\t\t$imageType = IMAGETYPE_JPEG;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/png':\n\t\t\t\t\t$imageType = IMAGETYPE_PNG;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/x-xbitmap':\n\t\t\t\t\t$imageType = IMAGETYPE_XBM;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/bmp':\n\t\t\t\tcase 'image/x-ms-bmp':\n\t\t\t\t\t$imageType = IMAGETYPE_BMP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/webp':\n\t\t\t\t\t$imageType = IMAGETYPE_WEBP;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception('\\OC_Image::_output(): \"' . $mimeType . '\" is not supported when forcing a specific output format');\n\t\t\t}\n\t\t}\n\n\t\tswitch ($imageType) {\n\t\t\tcase IMAGETYPE_GIF:\n\t\t\t\t$retVal = imagegif($this->resource, $filePath);\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_JPEG:\n\t\t\t\t/** @psalm-suppress InvalidScalarArgument */\n\t\t\t\timageinterlace($this->resource, (PHP_VERSION_ID >= 80000 ? true : 1));\n\t\t\t\t$retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_PNG:\n\t\t\t\t$retVal = imagepng($this->resource, $filePath);\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_XBM:\n\t\t\t\tif (function_exists('imagexbm')) {\n\t\t\t\t\t$retVal = imagexbm($this->resource, $filePath);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Exception('\\OC_Image::_output(): imagexbm() is not supported.');\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_WBMP:\n\t\t\t\t$retVal = imagewbmp($this->resource, $filePath);\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_BMP:\n\t\t\t\t$retVal = imagebmp($this->resource, $filePath);\n\t\t\t\tbreak;\n\t\t\tcase IMAGETYPE_WEBP:\n\t\t\t\t$retVal = imagewebp($this->resource, null, $this->getWebpQuality());\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$retVal = imagepng($this->resource, $filePath);\n\t\t}\n\t\treturn $retVal;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function getResultContentIdList(SearchResult $searchResult)\n {\n $contentIdList = [];\n\n foreach ($searchResult->searchHits as $searchHit) {\n $valueObject = $searchHit->valueObject;\n\n switch (true) {\n case $valueObject instanceof Content:\n $contentIdList[] = $valueObject->id;\n break;\n\n case $valueObject instanceof Location:\n $contentIdList[] = $valueObject->contentId;\n break;\n\n default:\n throw new \\RuntimeException(\n 'Unknown search result hit type: ' . get_class($searchHit->valueObject)\n );\n }\n }\n\n return $contentIdList;\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (array $resources, string $endpoint, string $projectID, string $key, Response $response) {\n try {\n $appwrite = new Appwrite($projectID, $endpoint, $key);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic(new Document($appwrite->report($resources)), Response::MODEL_MIGRATION_REPORT);\n } catch (\\Throwable $e) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Source Error: ' . $e->getMessage());\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function translationAddAction(Request $request): JsonResponse\n {\n $sourceDocument = Document::getById((int) $request->get('sourceId'));\n $targetDocument = Document::getByPath($request->get('targetPath'));\n\n if ($sourceDocument && $targetDocument) {\n if (empty($sourceDocument->getProperty('language'))) {\n throw new Exception(sprintf('Source Document(ID:%s) Language(Properties) missing', $sourceDocument->getId()));\n }\n\n if (empty($targetDocument->getProperty('language'))) {\n throw new Exception(sprintf('Target Document(ID:%s) Language(Properties) missing', $sourceDocument->getId()));\n }\n\n $service = new Document\\Service;\n if ($service->getTranslationSourceId($targetDocument) != $targetDocument->getId()) {\n throw new Exception('Target Document already linked to Source Document ID('.$service->getTranslationSourceId($targetDocument).'). Please unlink existing relation first.');\n }\n $service->addTranslation($sourceDocument, $targetDocument);\n }\n\n return $this->adminJson([\n 'success' => true,\n ]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "private function hydrate(): void\n {\n $is_hydrated = $this->route !== null && $this->controller !== null && $this->method !== null;\n if (!$is_hydrated) {\n [$controller, $method] = explode('::', $this->key);\n try {\n $this->controller = new ReflectionClass($controller);\n $this->method = $this->controller->getMethod($method);\n if (!$this->method->isPublic()) {\n throw new \\Exception('Method is not public');\n }\n $route_attributes = $this->method->getAttributes(Route::class);\n if (count($route_attributes) === 0) {\n throw new \\Exception(\"RoutePath has no Route attribute\");\n }\n $this->route = $route_attributes[0]->newInstance();\n } catch (\\Throwable $e) {\n throw new \\RuntimeException(\n \"Unable to hydrate RoutePath {$this->key}: {$e->getMessage()}\",\n 0,\n $e\n );\n }\n $this->mergeControllerRouteData();\n $this->compilePath();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function getSvgViaChromiumHelper($html, $width, $height){\n\n // Chromium requires the file to have a .html extension\n // cant use datauri as it will not execute embdeeded javascript\n $tmpFile = tempnam(sys_get_temp_dir(), 'xdmod-chromiumHtml-');\n $tmpHtmlFile = $tmpFile . '.html';\n if ($tmpFile === false || rename($tmpFile, $tmpHtmlFile) === false) {\n @unlink($tmpFile);\n throw \\Exception('Error creating temporary html file for chromium');\n }\n file_put_contents($tmpHtmlFile, $html);\n\n $chromiumPath = \\xd_utilities\\getConfiguration('reporting', 'chromium_path');\n\n $command = LIB_DIR . '/chrome-helper/chrome-helper.js' .\n ' --window-size=' . $width . ',' . $height .\n ' --path-to-chrome=' . $chromiumPath .\n ' --input-file=' . $tmpHtmlFile;\n\n $pipes = array();\n $descriptor_spec = array(\n 1 => array('pipe', 'w'),\n 2 => array('pipe', 'w'),\n );\n $process = proc_open($command, $descriptor_spec, $pipes);\n if (!is_resource($process)) {\n @unlink($tmpHtmlFile);\n throw new \\Exception('Unable execute command: \"'. $command . '\". Details: ' . print_r(error_get_last(), true));\n }\n\n $out = stream_get_contents($pipes[1]);\n $err = stream_get_contents($pipes[2]);\n fclose($pipes[1]);\n fclose($pipes[2]);\n $return_value = proc_close($process);\n\n @unlink($tmpHtmlFile);\n\n $chartSvg = json_decode($out);\n\n if ($chartSvg === null) {\n throw new \\Exception('Error executing command: \"'. $command . '\". Details: ' . $return_value . \" \" . $out . ' Errors: ' . $err);\n }\n\n return $chartSvg;\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function group_by($prop, $in, $del = true)\n\t{\n\t\t$del &= is_array($in);\n\t\t$out = [];\n\t\tforeach ($in as $i => $obj) {\n\t\t\tif (property_exists($obj, $prop)) {\n\t\t\t\t$key = $obj->$prop;\n\t\t\t} elseif (method_exists($obj, $prop)) {\n\t\t\t\t$key = $obj->$prop();\n\t\t\t} else {\n\t\t\t\tthrow new Exception('Veld bestaat niet');\n\t\t\t}\n\n\t\t\t$out[$key][] = $obj; // add to array\n\t\t\tif ($del) {\n\t\t\t\tunset($in[$i]);\n\t\t\t}\n\t\t}\n\t\treturn $out;\n\t}", "smellKey": "S112", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function getOptions(array $context, Data $fieldDefinition): array\n {\n $workflowName = null;\n if ($fieldDefinition instanceof Select || $fieldDefinition instanceof Multiselect) {\n $workflowName = $fieldDefinition->getOptionsProviderData();\n }\n if (!$workflowName) {\n throw new Exception('setup workflow name as options provider data');\n }\n\n $options = [];\n\n $workflow = $this->workflowManager->getWorkflowByName($workflowName);\n\n $mappedPlaces = null;\n $markingStore = $workflow->getMarkingStore();\n\n if ($markingStore instanceof DataObjectSplittedStateMarkingStore) {\n $mappedPlaces = $markingStore->getMappedPlaces($fieldDefinition->getName());\n }\n\n foreach ($this->workflowManager->getPlaceConfigsByWorkflowName($workflowName) as $placeConfig) {\n if (!is_array($mappedPlaces) || in_array($placeConfig->getPlace(), $mappedPlaces)) {\n $options[] = [\n 'key' => $this->generatePlaceLabel($placeConfig),\n 'value' => $placeConfig->getPlace(),\n ];\n }\n }\n\n return $options;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function deleteUser($uid) {\n\t\t$plugin = $this->which['deleteUser'];\n\t\tif ($plugin) {\n\t\t\tif ($this->suppressDeletion) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn $plugin->deleteUser($uid);\n\t\t}\n\t\tthrow new \\Exception('No plugin implements deleteUser in this LDAP Backend.');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function unitProxyAction(Request $request): JsonResponse\n {\n $this->checkPermission('quantityValueUnits');\n\n if ($request->get('data')) {\n if ($request->get('xaction') == 'destroy') {\n $data = json_decode($request->get('data'), true);\n $id = $data['id'];\n $unit = \\Pimcore\\Model\\DataObject\\QuantityValue\\Unit::getById($id);\n if (!empty($unit)) {\n $unit->delete();\n\n return $this->adminJson(['data' => [], 'success' => true]);\n } else {\n throw new \\Exception('Unit with id ' . $id . ' not found.');\n }\n } elseif ($request->get('xaction') == 'update') {\n $data = json_decode($request->get('data'), true);\n $unit = Unit::getById($data['id']);\n if (!empty($unit)) {\n if (($data['baseunit'] ?? null) == -1) {\n $data['baseunit'] = null;\n }\n $unit->setValues($data);\n $unit->save();\n\n return $this->adminJson(['data' => $unit->getObjectVars(), 'success' => true]);\n } else {\n throw new \\Exception('Unit with id ' . $data['id'] . ' not found.');\n }\n } elseif ($request->get('xaction') == 'create') {\n $data = json_decode($request->get('data'), true);\n if (isset($data['baseunit']) && $data['baseunit'] === -1) {\n $data['baseunit'] = null;\n }\n\n $id = $data['id'];\n if (Unit::getById($id)) {\n throw new \\Exception('unit with ID [' . $id . '] already exists');\n }\n\n if (mb_strlen($id) > 50) {\n throw new \\Exception('The maximal character length for the unit ID is 50 characters, the provided ID has ' . mb_strlen($id) . ' characters.');\n }\n\n $unit = new Unit();\n $unit->setValues($data);\n $unit->save();\n\n return $this->adminJson(['data' => $unit->getObjectVars(), 'success' => true]);\n }\n }\n\n return $this->adminJson(['success' => false]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $bucketId, string $range, Response $response, Database $dbForProject) {\n\n $bucket = $dbForProject->getDocument('buckets', $bucketId);\n\n if ($bucket->isEmpty()) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $usage = [];\n if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {\n $periods = [\n '24h' => [\n 'period' => '1h',\n 'limit' => 24,\n ],\n '7d' => [\n 'period' => '1d',\n 'limit' => 7,\n ],\n '30d' => [\n 'period' => '1d',\n 'limit' => 30,\n ],\n '90d' => [\n 'period' => '1d',\n 'limit' => 90,\n ],\n ];\n\n $metrics = [\n \"files.{$bucketId}.count.total\",\n \"files.{$bucketId}.storage.size\",\n \"files.{$bucketId}.requests.create\",\n \"files.{$bucketId}.requests.read\",\n \"files.{$bucketId}.requests.update\",\n \"files.{$bucketId}.requests.delete\",\n ];\n\n $stats = [];\n\n Authorization::skip(function () use ($dbForProject, $periods, $range, $metrics, &$stats) {\n foreach ($metrics as $metric) {\n $limit = $periods[$range]['limit'];\n $period = $periods[$range]['period'];\n\n $requestDocs = $dbForProject->find('stats', [\n Query::equal('period', [$period]),\n Query::equal('metric', [$metric]),\n Query::limit($limit),\n Query::orderDesc('time'),\n ]);\n\n $stats[$metric] = [];\n foreach ($requestDocs as $requestDoc) {\n $stats[$metric][] = [\n 'value' => $requestDoc->getAttribute('value'),\n 'date' => $requestDoc->getAttribute('time'),\n ];\n }\n\n // backfill metrics with empty values for graphs\n $backfill = $limit - \\count($requestDocs);\n while ($backfill > 0) {\n $last = $limit - $backfill - 1; // array index of last added metric\n $diff = match ($period) { // convert period to seconds for unix timestamp math\n '1h' => 3600,\n '1d' => 86400,\n };\n $stats[$metric][] = [\n 'value' => 0,\n 'date' => DateTime::formatTz(DateTime::addSeconds(new \\DateTime($stats[$metric][$last]['date'] ?? null), -1 * $diff)),\n ];\n $backfill--;\n }\n $stats[$metric] = array_reverse($stats[$metric]);\n }\n });\n\n $usage = new Document([\n 'range' => $range,\n 'filesCount' => $stats[$metrics[0]],\n 'filesStorage' => $stats[$metrics[1]],\n 'filesCreate' => $stats[$metrics[2]],\n 'filesRead' => $stats[$metrics[3]],\n 'filesUpdate' => $stats[$metrics[4]],\n 'filesDelete' => $stats[$metrics[5]],\n ]);\n }\n\n $response->dynamic($usage, Response::MODEL_USAGE_BUCKETS);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function factory($shortName, LoggerInterface $logger = null, \\stdClass $options = null)\n {\n if ( ! is_string($shortName) ) {\n $e = new \\Exception(\"Realm 'shortname' must be a string\", true);\n throw new \\Exception($e->getTraceAsString());\n }\n\n self::initialize($logger, $options);\n $configObj = self::$dataWarehouseConfig->getSectionData($shortName);\n\n if ( false === $configObj ) {\n $msg = sprintf(\"Request for unknown Realm: %s\", $shortName);\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new \\Exception($msg);\n }\n return new static($shortName, $configObj, $logger);\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function _storeData() {\n\t\t$this->_currentObject->detach();\n\n\t\tif (!apc_store($this->_cachePrefix.$this->_currentObjectID.'.cache',serialize($this->_currentObject),$this->_cacheTime)) {\n\t\t\t$this->__destruct();\n\t\t\tthrow new Exception('Failed to store cell '.$cellID.' in APC');\n\t\t}\n\t\t$this->_currentObjectID = $this->_currentObject = null;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "protected function exportImage($returnData, $width, $height, $scale, $format, $filename, $fileMeta = null)\n {\n if (isset($this->request['render_thumbnail']))\n {\n\n \\xd_charting\\processForThumbnail($returnData);\n\n $result = array(\n \"headers\" => array( \"Content-Type\" => \"image/png\"),\n \"results\" => \\xd_charting\\exportChart($returnData, '148', '69', 2, 'png')\n );\n\n return $result;\n }\n\n if (isset($this->request['render_for_report']))\n {\n\n \\xd_charting\\processForReport($returnData);\n\n $result = array( \n \"headers\" => array( \"Content-Type\" => \"image/png\"),\n \"results\" => \\xd_charting\\exportChart($returnData, $width, $height, $scale, 'png')\n );\n\n return $result;\n }\n\n if ($format === 'png' || $format === 'svg' || $format === 'pdf')\n {\n if (is_null($fileMeta))\n {\n $fileMeta = array(\n 'title' => $filename\n );\n }\n\n $result = array(\n \"headers\" => \\DataWarehouse\\ExportBuilder::getHeader( $format, false, $filename),\n \"results\" => \\xd_charting\\exportChart($returnData['data'][0], $width, $height, $scale, $format, null, $fileMeta)\n );\n\n return $result;\n }\n elseif($format === 'png_inline')\n {\n $result = array(\n \"headers\" => \\DataWarehouse\\ExportBuilder::getHeader( $format, false, $filename),\n \"results\" => 'data:image/png;base64,'.base64_encode(\\xd_charting\\exportChart($returnData['data'][0], $width, $height, $scale, 'png'))\n );\n return $result;\n\n }\n elseif($format === 'svg_inline')\n {\n $result = array(\n \"headers\" => \\DataWarehouse\\ExportBuilder::getHeader( $format, false, $filename),\n \"results\" => 'data:image/svg+xml;base64,' . base64_encode(\n \\xd_charting\\exportChart( $returnData['data'][0], $width, $height, $scale, 'svg'))\n );\n\n return $result;\n }\n elseif ($format === 'hc_jsonstore' ) {\n\n $result = array(\n \"headers\" => \\DataWarehouse\\ExportBuilder::getHeader( $format ),\n \"results\" => json_encode($returnData)\n );\n\n return $result;\n }\n elseif ($format === '_internal') {\n $result = array(\n 'headers' => \\DataWarehouse\\ExportBuilder::getHeader( 'hc_jsonstore' ),\n 'results' => $returnData,\n );\n return $result;\n }\n\n throw new \\Exception(\"Internal Error: unsupported image format $format\");\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function testLoginName(string $loginName) {\n\t\t$reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];\n\t\tif (!$this->configuration->usesLdapi()) {\n\t\t\t$reqs[] = 'ldapPort';\n\t\t}\n\t\tif (!$this->checkRequirements($reqs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$cr = $this->access->connection->getConnectionResource();\n\t\tif (!$this->ldap->isResource($cr)) {\n\t\t\tthrow new \\Exception('connection error');\n\t\t}\n\t\t/** @var resource|\\LDAP\\Connection $cr */\n\n\t\tif (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')\n\t\t\t=== false) {\n\t\t\tthrow new \\Exception('missing placeholder');\n\t\t}\n\n\t\t$users = $this->access->countUsersByLoginName($loginName);\n\t\tif ($this->ldap->errno($cr) !== 0) {\n\t\t\tthrow new \\Exception($this->ldap->error($cr));\n\t\t}\n\t\t$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);\n\t\t$this->result->addChange('ldap_test_loginname', $users);\n\t\t$this->result->addChange('ldap_test_effective_filter', $filter);\n\t\treturn $this->result;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function rewind()\n\t{\n\t\tif ($this->_position > 0)\n\t\t{\n\t\t\tthrow new \\Exception('PDO statement cannot be rewound for unbuffered queries');\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "public static function zipFolder($sourcefolder, $zipfilename, $removeFromLocalName) {\n// instantate an iterator (before creating the zip archive, just\n// in case the zip file is created inside the source folder)\n// and traverse the directory to get the file list.\n $dirlist = new RecursiveDirectoryIterator($sourcefolder);\n $filelist = new RecursiveIteratorIterator($dirlist);\n\n// instantate object\n $zip = new ZipArchive();\n\n $removeFromLocalName = preg_replace('|[\\\\/]|', DIRECTORY_SEPARATOR, $removeFromLocalName);\n $zipfilename = preg_replace('|[\\\\/]|', DIRECTORY_SEPARATOR, $zipfilename);\n\n// create and open the archive\n if (($res = $zip->open(\"$zipfilename\", ZipArchive::CREATE)) !== TRUE) {\n throw new Exception(\"Could not open archive\");\n }\n\n// add each file in the file list to the archive\n /** @var SplFileInfo $value */\n foreach ($filelist as $key => $value) {\n if($value->getBasename() == '.'){\n continue;\n }\n if($value->getBasename() == '..'){\n continue;\n }\n $localName = str_replace($removeFromLocalName, '', preg_replace('|[\\\\/]|', DIRECTORY_SEPARATOR, $value->getPathname()));\n if(!$zip->addFile($value->getPathname(), $localName)){\n throw new Exception(\"ERROR: Could not add file: $key\");\n }\n }\n\n// close the archive\n $zip->close();\n\n }", "smellKey": "S112", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "private function createClass(string $className): object {\n\t\ttry {\n\t\t\treturn $this->container->get($className);\n\t\t} catch (QueryException $e) {\n\t\t\tif (class_exists($className)) {\n\t\t\t\treturn new $className();\n\t\t\t}\n\t\t}\n\n\t\tthrow new \\Exception('Could not load ' . $className, 0, $e);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setWorksheet(PHPExcel_Worksheet $pValue = null, $pOverrideOld = false) {\n \tif (is_null($this->_worksheet)) {\n \t\t// Add drawing to PHPExcel_Worksheet\n\t \t$this->_worksheet = $pValue;\n\t \t$this->_worksheet->getCell($this->_coordinates);\n\t \t$this->_worksheet->getDrawingCollection()->append($this);\n \t} else {\n \t\tif ($pOverrideOld) {\n \t\t\t// Remove drawing from old PHPExcel_Worksheet\n \t\t\t$iterator = $this->_worksheet->getDrawingCollection()->getIterator();\n\n \t\t\twhile ($iterator->valid()) {\n \t\t\t\tif ($iterator->current()->getHashCode() == $this->getHashCode()) {\n \t\t\t\t\t$this->_worksheet->getDrawingCollection()->offsetUnset( $iterator->key() );\n \t\t\t\t\t$this->_worksheet = null;\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n\n \t\t\t// Set new PHPExcel_Worksheet\n \t\t\t$this->setWorksheet($pValue);\n \t\t} else {\n \t\t\tthrow new Exception(\"A PHPExcel_Worksheet has already been assigned. Drawings can only exist on one PHPExcel_Worksheet.\");\n \t\t}\n \t}\n \treturn $this;\n }", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function open(string $filePath, ?string $editorId = null, ?int $fileId = null): string {\n\t\t$userFolder = $this->rootFolder->getUserFolder($this->userId);\n\t\t$file = $userFolder->get($filePath);\n\t\tif ($fileId !== null && $file instanceof Folder) {\n\t\t\t$files = $file->getById($fileId);\n\n\t\t\t// Workaround to always open files with edit permissions if multiple occurences of\n\t\t\t// the same file id are in the user home, ideally we should also track the path of the file when opening\n\t\t\tusort($files, function (Node $a, Node $b) {\n\t\t\t\treturn ($b->getPermissions() & Constants::PERMISSION_UPDATE) <=> ($a->getPermissions() & Constants::PERMISSION_UPDATE);\n\t\t\t});\n\t\t\t$file = array_shift($files);\n\t\t}\n\n\t\tif (!$file instanceof File) {\n\t\t\tthrow new NotFoundException();\n\t\t}\n\n\t\t$filePath = $userFolder->getRelativePath($file->getPath());\n\n\t\tif ($editorId === null) {\n\t\t\t$editorId = $this->findEditorForFile($file);\n\t\t}\n\t\tif (!array_key_exists($editorId, $this->editors)) {\n\t\t\tthrow new \\RuntimeException(\"Editor $editorId is unknown\");\n\t\t}\n\n\t\treturn $this->createToken($editorId, $file, $filePath);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function deleteAction(Request $request): JsonResponse\n {\n $type = $request->get('type');\n\n if ($type === 'children') {\n $parentDocument = Document::getById((int) $request->get('id'));\n\n $list = new Document\\Listing();\n $list->setCondition('`path` LIKE ?', [$list->escapeLike($parentDocument->getRealFullPath()) . '/%']);\n $list->setLimit((int)$request->get('amount'));\n $list->setOrderKey('LENGTH(`path`)', false);\n $list->setOrder('DESC');\n\n $documents = $list->load();\n\n $deletedItems = [];\n foreach ($documents as $document) {\n $deletedItems[$document->getId()] = $document->getRealFullPath();\n if ($document->isAllowed('delete') && !$document->isLocked()) {\n $document->delete();\n }\n }\n\n return $this->adminJson(['success' => true, 'deleted' => $deletedItems]);\n }\n if ($id = $request->get('id')) {\n $document = Document::getById((int) $id);\n if ($document && $document->isAllowed('delete')) {\n try {\n if ($document->isLocked()) {\n throw new Exception('prevented deleting document, because it is locked: ID: ' . $document->getId());\n }\n $document->delete();\n\n return $this->adminJson(['success' => true]);\n } catch (Exception $e) {\n Logger::err((string) $e);\n\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }\n }\n\n throw $this->createAccessDeniedHttpException();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "private function reconnect(int $start): bool {\n\t\t$this->needReconnect = false;\n\t\t$range = $start . '-';\n\t\tif ($this->hasOpenStream()) {\n\t\t\tfclose($this->current);\n\t\t}\n\n\t\t$stream = ($this->openCallback)($range);\n\n\t\tif ($stream === false) {\n\t\t\t$this->current = null;\n\t\t\treturn false;\n\t\t}\n\t\t$this->current = $stream;\n\n\t\t$responseHead = stream_get_meta_data($this->current)['wrapper_data'];\n\n\t\twhile ($responseHead instanceof Wrapper) {\n\t\t\t$wrapperOptions = stream_context_get_options($responseHead->context);\n\t\t\tforeach ($wrapperOptions as $options) {\n\t\t\t\tif (isset($options['source']) && is_resource($options['source'])) {\n\t\t\t\t\t$responseHead = stream_get_meta_data($options['source'])['wrapper_data'];\n\t\t\t\t\tcontinue 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new \\Exception(\"Failed to get source stream from stream wrapper of \" . get_class($responseHead));\n\t\t}\n\n\t\t$rangeHeaders = array_values(array_filter($responseHead, function ($v) {\n\t\t\treturn preg_match('#^content-range:#i', $v) === 1;\n\t\t}));\n\t\tif (!$rangeHeaders) {\n\t\t\t$this->current = null;\n\t\t\treturn false;\n\t\t}\n\t\t$contentRange = $rangeHeaders[0];\n\n\t\t$content = trim(explode(':', $contentRange)[1]);\n\t\t$range = trim(explode(' ', $content)[1]);\n\t\t$begin = intval(explode('-', $range)[0]);\n\t\t$length = intval(explode('/', $range)[1]);\n\n\t\tif ($begin !== $start) {\n\t\t\t$this->current = null;\n\t\t\treturn false;\n\t\t}\n\n\t\t$this->offset = $begin;\n\t\t$this->length = $length;\n\t\tif ($start === 0) {\n\t\t\t$this->totalSize = $length;\n\t\t}\n\n\t\treturn true;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $userId, string $secret, Response $response, Document $user, Database $dbForProject, Event $events) {\n\n $profile = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId));\n\n if ($profile->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $tokens = $profile->getAttribute('tokens', []);\n $verification = Auth::tokenVerify($tokens, Auth::TOKEN_TYPE_VERIFICATION, $secret);\n\n if (!$verification) {\n throw new Exception(Exception::USER_INVALID_TOKEN);\n }\n\n Authorization::setRole(Role::user($profile->getId())->toString());\n\n $profile = $dbForProject->updateDocument('users', $profile->getId(), $profile->setAttribute('emailVerification', true));\n\n $user->setAttributes($profile->getArrayCopy());\n\n $verificationDocument = $dbForProject->getDocument('tokens', $verification);\n\n /**\n * We act like we're updating and validating\n * the verification token but actually we don't need it anymore.\n */\n $dbForProject->deleteDocument('tokens', $verification);\n $dbForProject->deleteCachedDocument('users', $profile->getId());\n\n $events\n ->setParam('userId', $userId)\n ->setParam('tokenId', $verificationDocument->getId())\n ;\n\n $response->dynamic($verificationDocument, Response::MODEL_TOKEN);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function run(): void\n {\n if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {\n Console::info('Skipped sms processing. No Phone provider has been set.');\n return;\n }\n\n if (empty($this->from)) {\n Console::info('Skipped sms processing. No phone number has been set.');\n return;\n }\n\n $message = new SMS(\n to: [$this->args['recipient']],\n content: $this->args['message'],\n from: $this->from,\n );\n\n try {\n $this->sms->send($message);\n } catch (\\Exception $error) {\n throw new Exception('Error sending message: ' . $error->getMessage(), 500);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (Request $request, Response $response, Locale $locale, Document $user, Document $project, Database $dbForProject, Reader $geodb, Event $events) {\n\n $protocol = $request->getProtocol();\n\n if ('console' === $project->getId()) {\n throw new Exception(Exception::USER_ANONYMOUS_CONSOLE_PROHIBITED, 'Failed to create anonymous user');\n }\n\n if (!$user->isEmpty()) {\n throw new Exception(Exception::USER_SESSION_ALREADY_EXISTS, 'Cannot create an anonymous user when logged in');\n }\n\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0) {\n $total = $dbForProject->count('users', max: APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n throw new Exception(Exception::USER_COUNT_EXCEEDED);\n }\n }\n\n $userId = ID::unique();\n $user->setAttributes([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => null,\n 'emailVerification' => false,\n 'status' => true,\n 'password' => null,\n 'hash' => Auth::DEFAULT_ALGO,\n 'hashOptions' => Auth::DEFAULT_ALGO_OPTIONS,\n 'passwordUpdate' => null,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'name' => null,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => $userId,\n 'accessedAt' => DateTime::now(),\n ]);\n $user->removeAttribute('$internalId');\n Authorization::skip(fn() => $dbForProject->createDocument('users', $user));\n\n // Create session token\n $duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $secret = Auth::tokenGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), $duration));\n\n $session = new Document(array_merge(\n [\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => Auth::SESSION_PROVIDER_ANONYMOUS,\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ],\n $detector->getOS(),\n $detector->getClient(),\n $detector->getDevice()\n ));\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $session = $dbForProject->createDocument('sessions', $session-> setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId())\n ;\n\n if (!Config::getParam('domainVerification')) {\n $response->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]));\n }\n\n $response\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ;\n\n $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'));\n\n $session\n ->setAttribute('current', true)\n ->setAttribute('countryName', $countryName)\n ->setAttribute('expire', $expire)\n ;\n\n $response->dynamic($session, Response::MODEL_SESSION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function correctPath(): void\n {\n // set path\n if ($this->getId() != 1) { // not for the root node\n if (!Element\\Service::isValidKey($this->getKey(), 'object')) {\n throw new Exception('invalid key for object with id [ '.$this->getId().' ] key is: [' . $this->getKey() . ']');\n }\n\n if (!$this->getParentId()) {\n throw new Exception('ParentID is mandatory and can\u00b4t be null. If you want to add the element as a child to the tree\u00b4s root node, consider setting ParentID to 1.');\n }\n\n if ($this->getParentId() == $this->getId()) {\n throw new Exception(\"ParentID and ID are identical, an element can't be the parent of itself in the tree.\");\n }\n\n $parent = DataObject::getById($this->getParentId());\n if (!$parent) {\n throw new Exception('ParentID not found.');\n }\n\n // use the parent's path from the database here (getCurrentFullPath), to ensure the path really exists and does not rely on the path\n // that is currently in the parent object (in memory), because this might have changed but wasn't not saved\n $this->setPath(str_replace('//', '/', $parent->getCurrentFullPath().'/'));\n\n if (strlen($this->getKey()) < 1) {\n throw new Exception('DataObject requires key');\n }\n } elseif ($this->getId() == 1) {\n // some data in root node should always be the same\n $this->setParentId(0);\n $this->setPath('/');\n $this->setKey('');\n $this->setType(DataObject::OBJECT_TYPE_FOLDER);\n }\n\n if (Service::pathExists($this->getRealFullPath())) {\n $duplicate = DataObject::getByPath($this->getRealFullPath());\n if ($duplicate instanceof self && $duplicate->getId() != $this->getId()) {\n $duplicateFullPathException = new DuplicateFullPathException('Duplicate full path [ '.$this->getRealFullPath().' ] - cannot save object');\n $duplicateFullPathException->setDuplicateElement($duplicate);\n $duplicateFullPathException->setCauseElement($this);\n\n throw $duplicateFullPathException;\n }\n }\n\n $this->validatePathLength();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function url($params = array(), $absolute = false, $protocol = 'http', $filterParams = true)\n {\n if (is_callable($this->rule))\n throw new \\Exception(\"The rule for '{$this->name}' route is a function and cannot be reversed\");\n\n $url = $this->basepath;\n if (substr($url, -1) === '/')\n $url = substr($url, 0, -1);\n $url.= is_array($this->rule) ? $this->rule[0] : $this->rule;\n\n $replace = array();\n $params = array_merge($this->defaults, $params);\n foreach ($params as $key => $value)\n $replace[\"<{$key}>\"] = $value;\n $url = str_replace(array_keys($replace), array_values($replace), $url);\n\n $count = 1;\n $chars = '[^\\(\\)]*?';\n while ($count > 0)\n $url = preg_replace(\"#\\\\({$chars}<{$chars}>{$chars}\\\\)#\", '', $url, -1, $count);\n\n $url = str_replace(array('(', ')'), '', $url);\n\n if ($absolute)\n $url = $protocol.'://'.$_SERVER['HTTP_HOST'].$url;\n\n return $url;\n }", "smellKey": "S112", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "public function createStoreAction(Request $request): JsonResponse\n {\n $this->checkPermission('classificationstore');\n\n $name = SecurityHelper::convertHtmlSpecialChars($request->get('name'));\n\n $config = Classificationstore\\StoreConfig::getByName($name);\n\n if (!$config) {\n $config = new Classificationstore\\StoreConfig();\n $config->setName($name);\n $config->save();\n } else {\n throw new \\Exception('Store with the given name exists');\n }\n\n return $this->adminJson(['success' => true, 'storeId' => $config->getId()]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function commit(): void\n {\n try {\n $this->persistenceHandler->commit();\n } catch (Exception $e) {\n throw new RuntimeException($e->getMessage(), 0, $e);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function removeUser()\n {\n\n if ($this->isPublicUser()) {\n throw new Exception('Cannot remove public user');\n }\n\n // Clean up any report-based data generated by the user\n $this->_pdo->execute(\"DELETE FROM ChartPool WHERE user_id=:user_id\", array(\n ':user_id' => $this->_id,\n ));\n $this->_pdo->execute(\"DELETE FROM Reports WHERE user_id=:user_id\", array(\n ':user_id' => $this->_id,\n ));\n $this->_pdo->execute(\"DELETE FROM ReportCharts WHERE user_id=:user_id\", array(\n ':user_id' => $this->_id,\n ));\n\n $this->_pdo->execute(\"DELETE FROM user_acl_group_by_parameters WHERE user_id=:user_id\", array(\n ':user_id' => $this->_id\n ));\n\n // Make sure to remove the acl relations\n $this->_pdo->execute(\"DELETE FROM user_acls WHERE user_id = :user_id\", array(\n ':user_id' => $this->_id\n ));\n\n $this->_pdo->execute(\"DELETE FROM Users WHERE id=:id\", array(\n ':id' => $this->_id,\n ));\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function parseJobArrayIndexes($arrayList)\n {\n if (preg_match('/^\\d+$/', $arrayList)) {\n return array($arrayList);\n }\n\n $containsBrackets\n = strpos($arrayList, '[') === 0\n && strrpos($arrayList, ']') === strlen($arrayList) - 1;\n\n if ($containsBrackets) {\n\n // Remove brackets and split on comma.\n $arrayParts = explode(\n ',',\n substr($arrayList, 1, strlen($arrayList) - 2)\n );\n\n $arrayIds = array();\n\n foreach ($arrayParts as $arrayPart) {\n if (strpos($arrayPart, '-') !== false) {\n list($min, $max) = explode('-', $arrayPart, 2);\n $arrayIds = array_merge($arrayIds, range($min, $max));\n } else {\n $arrayIds[] = $arrayPart;\n }\n }\n\n return $arrayIds;\n } else {\n $msg = \"Failed to parse job array indexes '$arrayList'\";\n throw new Exception($msg);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (Database $dbForConsole, Document $document) {\n try {\n $statsPerOrganization = [];\n\n /** Organization name */\n $statsPerOrganization['name'] = $document->getAttribute('name');\n\n /** Get Email and of the organization owner */\n $membership = $dbForConsole->findOne('memberships', [\n Query::equal('teamInternalId', [$document->getInternalId()]),\n ]);\n\n if (!$membership || $membership->isEmpty()) {\n throw new Exception('Membership not found. Skipping organization : ' . $document->getId());\n }\n\n $userInternalId = $membership->getAttribute('userInternalId', null);\n if ($userInternalId) {\n $user = $dbForConsole->findOne('users', [\n Query::equal('_id', [$userInternalId]),\n ]);\n\n $statsPerOrganization['email'] = $user->getAttribute('email', null);\n }\n\n /** Organization Creation Date */\n $statsPerOrganization['created'] = $document->getAttribute('$createdAt');\n\n /** Number of team members */\n $statsPerOrganization['members'] = $document->getAttribute('total');\n\n /** Number of projects in this organization */\n $statsPerOrganization['projects'] = $dbForConsole->count('projects', [\n Query::equal('teamId', [$document->getId()]),\n Query::limit(APP_LIMIT_COUNT)\n ]);\n\n if (!isset($statsPerOrganization['email'])) {\n throw new Exception('Email not found. Skipping organization : ' . $document->getId());\n }\n\n $event = new Event();\n $event\n ->setName('Organization Daily Usage')\n ->setProps($statsPerOrganization);\n $res = $this->mixpanel->createEvent($event);\n if (!$res) {\n throw new Exception('Failed to create event for organization : ' . $document->getId());\n }\n } catch (Exception $e) {\n Console::error($e->getMessage());\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function getByIdIgnoreCase(string $id): ClassDefinition|null\n {\n try {\n $class = new self();\n $name = $class->getDao()->getNameByIdIgnoreCase($id);\n if ($name === null) {\n throw new Exception('Class definition with ID ' . $id . ' does not exist');\n }\n $definitionFile = $class->getDefinitionFile($name);\n $class = @include $definitionFile;\n\n if (!$class instanceof self) {\n throw new Exception('Class definition with name ' . $name . ' or ID ' . $id . ' does not exist');\n }\n\n $class->setId($id);\n } catch (Exception $e) {\n Logger::info($e->getMessage());\n\n return null;\n }\n\n return $class;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function handle(\n CriteriaConverter $converter,\n QueryBuilder $queryBuilder,\n Criterion $criterion,\n array $languageSettings\n ) {\n $value = (array)$criterion->value;\n switch ($criterion->target) {\n case Criterion\\UserMetadata::MODIFIER:\n return $queryBuilder->expr()->in(\n 'v.creator_id',\n $queryBuilder->createNamedParameter($value, Connection::PARAM_INT_ARRAY)\n );\n\n case Criterion\\UserMetadata::GROUP:\n $subSelect = $this->connection->createQueryBuilder();\n $subSelect\n ->select(\n 't1.contentobject_id'\n )->from(\n LocationGateway::CONTENT_TREE_TABLE,\n 't1'\n )->innerJoin(\n 't1',\n LocationGateway::CONTENT_TREE_TABLE,\n 't2',\n $queryBuilder->expr()->like(\n 't1.path_string',\n $this->dbPlatform->getConcatExpression(\n 't2.path_string',\n $queryBuilder->createNamedParameter('%', ParameterType::STRING)\n )\n )\n )->where(\n $queryBuilder->expr()->in(\n 't2.contentobject_id',\n $queryBuilder->createNamedParameter($value, Connection::PARAM_INT_ARRAY)\n )\n );\n\n return $queryBuilder->expr()->in(\n 'c.owner_id',\n $subSelect->getSQL()\n );\n\n case Criterion\\UserMetadata::OWNER:\n return $queryBuilder->expr()->in(\n 'c.owner_id',\n $queryBuilder->createNamedParameter($value, Connection::PARAM_INT_ARRAY)\n );\n default:\n break;\n }\n\n throw new RuntimeException(\"Invalid target Criterion: '\" . $criterion->target . \"'\");\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function applyCertificateFiles(string $folder, string $domain, array $letsEncryptData): void\n {\n // Prepare folder in storage for domain\n $path = APP_STORAGE_CERTIFICATES . '/' . $domain;\n if (!\\is_readable($path)) {\n if (!\\mkdir($path, 0755, true)) {\n throw new Exception('Failed to create path for certificate.');\n }\n }\n\n // Move generated files\n if (!@\\rename('/etc/letsencrypt/live/' . $folder . '/cert.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/cert.pem')) {\n throw new Exception('Failed to rename certificate cert.pem. Let\\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']);\n }\n\n if (!@\\rename('/etc/letsencrypt/live/' . $folder . '/chain.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/chain.pem')) {\n throw new Exception('Failed to rename certificate chain.pem. Let\\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']);\n }\n\n if (!@\\rename('/etc/letsencrypt/live/' . $folder . '/fullchain.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/fullchain.pem')) {\n throw new Exception('Failed to rename certificate fullchain.pem. Let\\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']);\n }\n\n if (!@\\rename('/etc/letsencrypt/live/' . $folder . '/privkey.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/privkey.pem')) {\n throw new Exception('Failed to rename certificate privkey.pem. Let\\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']);\n }\n\n $config = \\implode(PHP_EOL, [\n \"tls:\",\n \" certificates:\",\n \" - certFile: /storage/certificates/{$domain}/fullchain.pem\",\n \" keyFile: /storage/certificates/{$domain}/privkey.pem\"\n ]);\n\n // Save configuration into Traefik using our new cert files\n if (!\\file_put_contents(APP_STORAGE_CONFIG . '/' . $domain . '.yml', $config)) {\n throw new Exception('Failed to save Traefik configuration.');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function runCompletion()\n {\n if (!$this->context) {\n throw new \\RuntimeException('A CompletionContext must be set before requesting completion.');\n }\n\n // Set the command to query options and arugments from\n $this->command = $this->detectCommand();\n\n $process = array(\n 'completeForOptionValues',\n 'completeForOptionShortcuts',\n 'completeForOptionShortcutValues',\n 'completeForOptions',\n 'completeForCommandName',\n 'completeForCommandArguments'\n );\n\n foreach ($process as $methodName) {\n $result = $this->{$methodName}();\n\n if (false !== $result) {\n // Return the result of the first completion mode that matches\n return $this->filterResults((array) $result);\n }\n }\n\n return array();\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getBaselineManifest(): ?array\n {\n $version = VersionParser::getNormalizedVersion(GLPI_VERSION, false);\n $manifest = file_get_contents($this->getCheckRootDir() . '/version/' . $version);\n try {\n $content = json_decode($manifest, true, 512, JSON_THROW_ON_ERROR);\n } catch (\\Throwable $e) {\n throw new \\RuntimeException('The source code file manifest is invalid.', previous: $e);\n }\n if (!isset($content['algorithm'], $content['files']) || !is_string($content['algorithm']) || !is_array($content['files'])) {\n throw new \\RuntimeException('The source code file manifest is invalid.');\n }\n return $content;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function getConfiguration($section, $option, $useCachedOptions = true)\n{\n $sectionData = getConfigurationSection($section, $useCachedOptions);\n\n if (empty($option)) {\n $msg = \"Configuration option not specified\";\n throw new Exception($msg);\n }\n\n if (!array_key_exists($option, $sectionData)) {\n $msg = \"Option '$option' does not exist in section '$section'\";\n throw new Exception($msg);\n }\n\n return $sectionData[$option];\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function convertSvg($svgData, $format, $width, $height, $docmeta){\n $author = isset($docmeta['author']) ? addcslashes($docmeta['author'], \"()\\n\\\\\") : 'XDMoD';\n $subject = isset($docmeta['subject']) ? addcslashes($docmeta['subject'], \"()\\n\\\\\") : 'XDMoD chart';\n $title = isset($docmeta['title']) ? addcslashes($docmeta['title'], \"()\\n\\\\\") :'XDMoD PDF chart export';\n $creator = addcslashes('XDMoD ' . OPEN_XDMOD_VERSION, \"()\\n\\\\\");\n\n switch($format){\n case 'png':\n $exifArgs = \"-Title='$title' -Author='$author' -Description='$subject' -Source='$creator'\";\n break;\n case 'pdf':\n $exifArgs = \"-Title='$title' -Author='$author' -Subject='$subject' -Creator='$creator'\";\n break;\n default:\n return $svgData;\n }\n\n $rsvgCommand = 'rsvg-convert -w ' .$width. ' -h '.$height.' -f ' . $format;\n if ($format == 'png'){\n $rsvgCommand = 'rsvg-convert -b \"#FFFFFF\" -w ' .$width. ' -h '.$height.' -f ' . $format;\n }\n $exifCommand = 'exiftool ' . $exifArgs . ' -o - -';\n\n $command = $rsvgCommand . ' | ' . $exifCommand;\n $pipes = array();\n $descriptor_spec = array(\n 0 => array('pipe', 'r'),\n 1 => array('pipe', 'w'),\n 2 => array('pipe', 'w'),\n );\n $process = proc_open($command, $descriptor_spec, $pipes);\n if (!is_resource($process)) {\n throw new \\Exception('Unable execute command: \"'. $command . '\". Details: ' . print_r(error_get_last(), true));\n }\n fwrite($pipes[0], $svgData);\n fclose($pipes[0]);\n $out = stream_get_contents($pipes[1]);\n $err = stream_get_contents($pipes[2]);\n\n fclose($pipes[1]);\n fclose($pipes[2]);\n\n $return_value = proc_close($process);\n\n if ($return_value != 0) {\n throw new \\Exception(\"$command returned $return_value, stdout: $out stderr: $err\");\n }\n return $out;\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function getPlaceholder(ImageValue $value, array $options = []): string\n {\n $options = $this->resolveOptions($options);\n\n $path = $this->getTemporaryPath();\n $placeholderUrl = $this->getPlaceholderUrl($options['url_pattern'], $value);\n\n try {\n $handler = curl_init();\n\n curl_setopt_array($handler, [\n CURLOPT_URL => $placeholderUrl,\n CURLOPT_FILE => fopen($path, 'wb'),\n CURLOPT_TIMEOUT => $options['timeout'],\n CURLOPT_FAILONERROR => true,\n ]);\n\n if (curl_exec($handler) === false) {\n throw new RuntimeException(\"Unable to download placeholder for {$value->id} ($placeholderUrl): \" . curl_error($handler));\n }\n } finally {\n curl_close($handler);\n }\n\n return $path;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getImporter(string $type): ImporterInterface\n {\n if (isset($this->importers[$type])) {\n return $this->importers[$type];\n }\n\n throw new Exception(sprintf('no importer for type \"%s\" registered', $type));\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function enableOutput()\n {\n if ($this->isRunning()) {\n throw new \\RuntimeException('Enabling output while the process is running is not possible.');\n }\n\n $this->outputDisabled = false;\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int {\n\t\tif (!$input->isInteractive()) {\n\t\t\t$output->writeln('Invalid TTY.');\n\t\t\t$output->writeln('If you are trying to execute the command in a Docker ');\n\t\t\t$output->writeln(\"container, do not forget to execute 'docker exec' with\");\n\t\t\t$output->writeln(\"the '-i' and '-t' options.\");\n\t\t\t$output->writeln('');\n\t\t\treturn 1;\n\t\t}\n\n\t\tif ($this->encryptionManager->isEnabled() === false) {\n\t\t\tthrow new \\Exception('Server side encryption is not enabled');\n\t\t}\n\n\t\t$output->writeln(\"\\n\");\n\t\t$output->writeln('You are about to encrypt all files stored in your Nextcloud installation.');\n\t\t$output->writeln('Depending on the number of available files, and their size, this may take quite some time.');\n\t\t$output->writeln('Please ensure that no user accesses their files during this time!');\n\t\t$output->writeln('Note: The encryption module you use determines which files get encrypted.');\n\t\t$output->writeln('');\n\t\t$question = new ConfirmationQuestion('Do you really want to continue? (y/n) ', false);\n\t\tif ($this->questionHelper->ask($input, $output, $question)) {\n\t\t\t$this->forceMaintenanceAndTrashbin();\n\n\t\t\ttry {\n\t\t\t\t$defaultModule = $this->encryptionManager->getEncryptionModule();\n\t\t\t\t$defaultModule->encryptAll($input, $output);\n\t\t\t} catch (\\Exception $ex) {\n\t\t\t\t$this->resetMaintenanceAndTrashbin();\n\t\t\t\tthrow $ex;\n\t\t\t}\n\n\t\t\t$this->resetMaintenanceAndTrashbin();\n\t\t\treturn 0;\n\t\t}\n\t\t$output->writeln('aborted');\n\t\treturn 1;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function GetColumnLetter($columnNumber)\n {\n // work with 1-based number\n $colNum = $columnNumber + 1;\n $code = \"\";\n\n if ($colNum > 26) {\n // greater than 26 means the column will be AA, AB, AC, etc.\n $left = floor($columnNumber / 26);\n $right = 1 + ($columnNumber % 26);\n\n if ($left > 26) {\n throw new Exception(\"Columns exceed supported amount\");\n }\n\n $code = chr($left + 64) . chr($right + 64);\n } else {\n $code = chr($colNum + 64);\n }\n\n return $code;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function generateLayoutTreeFromArray(array $array, bool $throwException = false, bool $insideLocalizedField = false): Data\\EncryptedField|bool|Data|Layout\n {\n if ($array) {\n if ($title = $array['title'] ?? false) {\n if (preg_match('/<.+?>/', $title)) {\n throw new Exception('not a valid title:' . htmlentities($title));\n }\n }\n if ($name = $array['name'] ?? false) {\n if (preg_match('/<.+?>/', $name)) {\n throw new Exception('not a valid name:' . htmlentities($name));\n }\n }\n\n /** @var LoaderInterface $loader */\n $loader = Pimcore::getContainer()->get('pimcore.implementation_loader.object.' . $array['datatype']);\n\n if ($loader->supports($array['fieldtype'])) {\n /** @var Data|Layout $item */\n $item = $loader->build($array['fieldtype']);\n\n $insideLocalizedField = $insideLocalizedField || $item instanceof DataObject\\ClassDefinition\\Data\\Localizedfields;\n\n if (method_exists($item, 'addChild')) { // allows children\n //TODO remove childs in Pimcore 12\n $item->setValues($array, ['children', 'childs']);\n $children = $array['children'] ?? [];\n\n if (!empty($children['datatype'])) {\n $childO = self::generateLayoutTreeFromArray($children, $throwException, $insideLocalizedField);\n $item->addChild($childO);\n } elseif (is_array($children) && count($children) > 0) {\n foreach ($children as $child) {\n $childO = self::generateLayoutTreeFromArray($child, $throwException, $insideLocalizedField);\n if ($childO !== false) {\n $item->addChild($childO);\n } else {\n if ($throwException) {\n throw new Exception('Could not add child ' . var_export($child, true));\n }\n\n Logger::err('Could not add child ' . var_export($child, true));\n\n return false;\n }\n }\n }\n } else {\n //for BC reasons\n $blockedVars = [];\n if ($item instanceof VarExporterInterface) {\n $blockedVars = $item->resolveBlockedVars();\n }\n self::removeDynamicOptionsFromArray($array, $blockedVars);\n $item->setValues($array);\n\n if ($item instanceof DataObject\\ClassDefinition\\Data\\EncryptedField) {\n $item->setupDelegate($array);\n }\n }\n\n return $item;\n }\n }\n if ($throwException) {\n throw new Exception('Could not add child ' . var_export($array, true));\n }\n\n return false;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function preGetData(mixed $container, array $params = []): mixed\n {\n if (!$container instanceof DataObject\\Concrete) {\n throw new Exception('Classification store fields are only valid in Objects');\n }\n\n if (!$container->getObjectVar($this->getName()) instanceof DataObject\\Classificationstore) {\n $store = new DataObject\\Classificationstore();\n $store->setObject($container);\n $store->setFieldname($this->getName());\n\n $container->{'set' . $this->getName()}($store);\n }\n\n return $container->getObjectVar($this->getName());\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $teamId, string $membershipId, string $userId, string $secret, Request $request, Response $response, Document $user, Database $dbForProject, Document $project, Reader $geodb, Event $events) {\n $protocol = $request->getProtocol();\n\n $membership = $dbForProject->getDocument('memberships', $membershipId);\n\n if ($membership->isEmpty()) {\n throw new Exception(Exception::MEMBERSHIP_NOT_FOUND);\n }\n\n if ($membership->getAttribute('teamId') !== $teamId) {\n throw new Exception(Exception::TEAM_MEMBERSHIP_MISMATCH);\n }\n\n $team = Authorization::skip(fn() => $dbForProject->getDocument('teams', $teamId));\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n if (Auth::hash($secret) !== $membership->getAttribute('secret')) {\n throw new Exception(Exception::TEAM_INVALID_SECRET);\n }\n\n if ($userId !== $membership->getAttribute('userId')) {\n throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')');\n }\n\n if ($user->isEmpty()) {\n $user->setAttributes($dbForProject->getDocument('users', $userId)->getArrayCopy()); // Get user\n }\n\n if ($membership->getAttribute('userId') !== $user->getId()) {\n throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')');\n }\n\n if ($membership->getAttribute('confirm') === true) {\n throw new Exception(Exception::MEMBERSHIP_ALREADY_CONFIRMED);\n }\n\n $membership // Attach user to team\n ->setAttribute('joined', DateTime::now())\n ->setAttribute('confirm', true)\n ;\n\n Authorization::skip(fn() => $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('emailVerification', true)));\n\n // Log user in\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $expire = DateTime::addSeconds(new \\DateTime(), $authDuration);\n $secret = Auth::tokenGenerator();\n $session = new Document(array_merge([\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => Auth::SESSION_PROVIDER_EMAIL,\n 'providerUid' => $user->getAttribute('email'),\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ], $detector->getOS(), $detector->getClient(), $detector->getDevice()));\n\n $session = $dbForProject->createDocument('sessions', $session\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n Authorization::setRole(Role::user($userId)->toString());\n\n $membership = $dbForProject->updateDocument('memberships', $membership->getId(), $membership);\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $team = Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team->setAttribute('total', $team->getAttribute('total', 0) + 1)));\n\n $events\n ->setParam('teamId', $team->getId())\n ->setParam('membershipId', $membership->getId())\n ;\n\n if (!Config::getParam('domainVerification')) {\n $response\n ->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]))\n ;\n }\n\n $response\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ;\n\n $response->dynamic(\n $membership\n ->setAttribute('teamName', $team->getAttribute('name'))\n ->setAttribute('userName', $user->getAttribute('name'))\n ->setAttribute('userEmail', $user->getAttribute('email')),\n Response::MODEL_MEMBERSHIP\n );\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $userId, Response $response, Database $dbForProject, Locale $locale) {\n\n $user = $dbForProject->getDocument('users', $userId);\n\n if ($user->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $sessions = $user->getAttribute('sessions', []);\n\n foreach ($sessions as $key => $session) {\n /** @var Document $session */\n\n $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'));\n $session->setAttribute('countryName', $countryName);\n $session->setAttribute('current', false);\n\n $sessions[$key] = $session;\n }\n\n $response->dynamic(new Document([\n 'sessions' => $sessions,\n 'total' => count($sessions),\n ]), Response::MODEL_SESSION_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $userId, Document $project, Database $dbForProject, Database $dbForConsole, ?Logger $logger) {\n try {\n $user = Authorization::skip(fn () => $dbForConsole->getDocument('users', $userId));\n\n $sessions = $user->getAttribute('sessions', []);\n\n $gitHubSession = null;\n foreach ($sessions as $session) {\n if ($session->getAttribute('provider', '') === 'github') {\n $gitHubSession = $session;\n break;\n }\n }\n\n if (empty($gitHubSession)) {\n throw new Exception(Exception::GENERAL_UNKNOWN, 'GitHub session not found.');\n }\n\n $provider = $gitHubSession->getAttribute('provider', '');\n $accessToken = $gitHubSession->getAttribute('providerAccessToken');\n $accessTokenExpiry = $gitHubSession->getAttribute('providerAccessTokenExpiry');\n $refreshToken = $gitHubSession->getAttribute('providerRefreshToken');\n\n $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? '';\n $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}';\n\n $className = 'Appwrite\\\\Auth\\\\OAuth2\\\\' . \\ucfirst($provider);\n\n if (!\\class_exists($className)) {\n throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);\n }\n\n $oauth2 = new $className($appId, $appSecret, '', [], []);\n\n $isExpired = new \\DateTime($accessTokenExpiry) < new \\DateTime('now');\n if ($isExpired) {\n try {\n $oauth2->refreshTokens($refreshToken);\n\n $accessToken = $oauth2->getAccessToken('');\n $refreshToken = $oauth2->getRefreshToken('');\n\n $verificationId = $oauth2->getUserID($accessToken);\n\n if (empty($verificationId)) {\n throw new \\Exception(\"Locked tokens.\"); // Race codition, handeled in catch\n }\n\n $gitHubSession\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$oauth2->getAccessTokenExpiry('')));\n\n Authorization::skip(fn () => $dbForProject->updateDocument('sessions', $gitHubSession->getId(), $gitHubSession));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n } catch (Throwable $err) {\n $index = 0;\n do {\n $previousAccessToken = $gitHubSession->getAttribute('providerAccessToken');\n\n $user = Authorization::skip(fn () => $dbForConsole->getDocument('users', $userId));\n $sessions = $user->getAttribute('sessions', []);\n\n $gitHubSession = new Document();\n foreach ($sessions as $session) {\n if ($session->getAttribute('provider', '') === 'github') {\n $gitHubSession = $session;\n break;\n }\n }\n\n $accessToken = $gitHubSession->getAttribute('providerAccessToken');\n\n if ($accessToken !== $previousAccessToken) {\n break;\n }\n\n $index++;\n \\usleep(500000);\n } while ($index < 10);\n }\n }\n\n $oauth2 = new $className($appId, $appSecret, '', [], []);\n $githubUser = $oauth2->getUserSlug($accessToken);\n $githubId = $oauth2->getUserID($accessToken);\n\n return [\n 'name' => $githubUser,\n 'id' => $githubId\n ];\n } catch (Exception $error) {\n if ($logger) {\n $version = App::getEnv('_APP_VERSION', 'UNKNOWN');\n\n $log = new Log();\n $log->setNamespace('console');\n $log->setServer(\\gethostname());\n $log->setVersion($version);\n $log->setType(Log::TYPE_ERROR);\n $log->setMessage($error->getMessage());\n\n $log->addTag('code', $error->getCode());\n $log->addTag('verboseType', get_class($error));\n\n $log->addExtra('file', $error->getFile());\n $log->addExtra('line', $error->getLine());\n $log->addExtra('trace', $error->getTraceAsString());\n $log->addExtra('detailedTrace', $error->getTrace());\n\n $log->setAction('avatarsGetGitHub');\n\n $isProduction = App::getEnv('_APP_ENV', 'development') === 'production';\n $log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);\n\n $responseCode = $logger->addLog($log);\n Console::info('GitHub error log pushed with status code: ' . $responseCode);\n }\n\n Console::warning(\"Failed: {$error->getMessage()}\");\n Console::warning($error->getTraceAsString());\n\n return [];\n }\n\n return [];\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $bucketId, string $name, ?array $permissions, bool $fileSecurity, bool $enabled, int $maximumFileSize, array $allowedFileExtensions, string $compression, bool $encryption, bool $antivirus, Response $response, Database $dbForProject, Event $events) {\n\n $bucketId = $bucketId === 'unique()' ? ID::unique() : $bucketId;\n\n // Map aggregate permissions into the multiple permissions they represent.\n $permissions = Permission::aggregate($permissions);\n\n try {\n $files = (Config::getParam('collections', [])['buckets'] ?? [])['files'] ?? [];\n if (empty($files)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Files collection is not configured.');\n }\n\n $attributes = [];\n $indexes = [];\n\n foreach ($files['attributes'] as $attribute) {\n $attributes[] = new Document([\n '$id' => $attribute['$id'],\n 'type' => $attribute['type'],\n 'size' => $attribute['size'],\n 'required' => $attribute['required'],\n 'signed' => $attribute['signed'],\n 'array' => $attribute['array'],\n 'filters' => $attribute['filters'],\n 'default' => $attribute['default'] ?? null,\n 'format' => $attribute['format'] ?? ''\n ]);\n }\n\n foreach ($files['indexes'] as $index) {\n $indexes[] = new Document([\n '$id' => $index['$id'],\n 'type' => $index['type'],\n 'attributes' => $index['attributes'],\n 'lengths' => $index['lengths'],\n 'orders' => $index['orders'],\n ]);\n }\n\n $dbForProject->createDocument('buckets', new Document([\n '$id' => $bucketId,\n '$collection' => 'buckets',\n '$permissions' => $permissions,\n 'name' => $name,\n 'maximumFileSize' => $maximumFileSize,\n 'allowedFileExtensions' => $allowedFileExtensions,\n 'fileSecurity' => $fileSecurity,\n 'enabled' => $enabled,\n 'compression' => $compression,\n 'encryption' => $encryption,\n 'antivirus' => $antivirus,\n 'search' => implode(' ', [$bucketId, $name]),\n ]));\n\n $bucket = $dbForProject->getDocument('buckets', $bucketId);\n\n $dbForProject->createCollection('bucket_' . $bucket->getInternalId(), $attributes, $indexes, permissions: $permissions ?? [], documentSecurity: $fileSecurity);\n } catch (Duplicate) {\n throw new Exception(Exception::STORAGE_BUCKET_ALREADY_EXISTS);\n }\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ;\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($bucket, Response::MODEL_BUCKET);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function startValidationService($port = '6662'): bool\n {\n $system = new System();\n $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\n if ($socket === false) {\n throw new Exception(\"Socket Creation Failed\");\n }\n $serverActive = @socket_connect($socket, \"localhost\", $port);\n\n if ($serverActive === false) {\n $path = $GLOBALS['fileroot'] . \"/ccdaservice/node_modules/oe-schematron-service\";\n if (IS_WINDOWS) {\n $redirect_errors = \" > \";\n $redirect_errors .= $system->escapeshellcmd($GLOBALS['temporary_files_dir'] . \"/schematron_server.log\") . \" 2>&1\";\n $cmd = $system->escapeshellcmd(\"node \" . $path . \"/app.js\") . $redirect_errors;\n $pipeHandle = popen(\"start /B \" . $cmd, \"r\");\n if ($pipeHandle === false) {\n throw new Exception(\"Failed to start local schematron service\");\n }\n if (pclose($pipeHandle) === -1) {\n error_log(\"Failed to close pipehandle for schematron service\");\n }\n } else {\n $command = 'nodejs';\n if (!$system->command_exists($command)) {\n if ($system->command_exists('node')) {\n $command = 'node';\n } else {\n error_log(\"Node is not installed on the system. Connection failed\");\n throw new Exception('Connection Failed.');\n }\n }\n $cmd = $system->escapeshellcmd(\"$command \" . $path . \"/app.js\");\n exec($cmd . \" > /dev/null &\");\n }\n sleep(2); // give cpu a rest\n $serverActive = socket_connect($socket, \"localhost\", $port);\n if ($serverActive === false) {\n error_log(\"Failed to start and connect to local schematron service server on port 6662\");\n throw new Exception(\"Connection Failed\");\n }\n }\n socket_close($socket);\n\n return $serverActive;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getParentIds(): array\n {\n // collect properties via parent - ids\n $parentIds = [1];\n $obj = $this->model->getParent();\n\n if ($obj) {\n while ($obj) {\n if ($obj->getId() == 1) {\n break;\n }\n if (in_array($obj->getId(), $parentIds)) {\n throw new Exception('detected infinite loop while resolving all parents from ' . $this->model->getId() . ' on ' . $obj->getId());\n }\n\n $parentIds[] = $obj->getId();\n $obj = $obj->getParent();\n }\n }\n\n return $parentIds;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function readComposerFile(string $path): ?array\n {\n if (is_file($path) && is_readable($path)) {\n try {\n return json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);\n } catch (JsonException $e) {\n throw new RuntimeException(sprintf('Failed to parse composer file %s', $path), previous: $e);\n }\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function request($method, $uri = '', array $options = [])\n {\n // WEB-2259, WEB-2345: Allow 4xx and 5xx responses\n $options = array_merge($options, ['http_errors' => false]);\n\n $response = $this->client->request($method, $uri, $options);\n $contents = $response->getBody()->getContents();\n $body = json_decode($contents);\n\n if (json_last_error() !== JSON_ERROR_NONE) {\n throw new \\Exception('Invalid JSON: ' . $contents);\n }\n\n if (is_object($body) && isset($body->error) && $body->status !== 404) {\n throw new \\Exception('API error: ' . $contents);\n }\n\n if (!in_array($response->getStatusCode(), [200, 404])) {\n throw new \\Exception('API invalid response: ' . $contents);\n }\n\n return (object) [\n 'body' => $body,\n 'status' => $response->getStatusCode()\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function onKernelController(ControllerEvent $event): void\n {\n $strategy = null;\n\n /** @var SecurityStrategy[] $attributes */\n $attributes = $event->getAttributes(SecurityStrategy::class);\n $number_of_attributes = \\count($attributes);\n if ($number_of_attributes > 1) {\n throw new \\RuntimeException(\\sprintf(\n 'You can apply only one security strategy per HTTP request. You actually used the \"%s\" attribute %d times.',\n SecurityStrategy::class,\n $number_of_attributes,\n ));\n } elseif ($number_of_attributes === 1) {\n $strategy = current($attributes)->strategy;\n } elseif ($event->isMainRequest()) {\n $strategy = $this->firewall->computeFallbackStrategy($event->getRequest()->getPathInfo());\n }\n\n if ($strategy !== null) {\n $this->firewall->applyStrategy($strategy);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($rounds = 12)\n {\n if (CRYPT_BLOWFISH != 1) {\n throw new Exception(\"bcrypt not supported in this installation. See http://php.net/crypt\");\n }\n\n $this->rounds = $rounds;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function processWenoPharmacyCsv($filePath, bool $isInsertOnly = true): false|int\n {\n $wenoLog = new WenoLogService();\n\n if (date(\"l\") == \"Monday\" && $isInsertOnly) {\n $sql = \"TRUNCATE TABLE weno_pharmacy\";\n sqlStatement($sql);\n }\n // Use existing connection.\n // Compared to creating a new connection, this method is slower by 3 seconds.\n // Using the sqlStatement() method is even slower by 10 seconds. That's 13 seconds slower overall.\n $connect = $GLOBALS['dbh'];\n if ($connect->connect_error) {\n $wenoLog->insertWenoLog(\"Pharmacy Directory\", \"Connection Failed.\");\n error_log(\"Connection failed: \" . $connect->connect_error);\n return false;\n }\n // Check if file exists and is readable\n if (!file_exists($filePath) || !is_readable($filePath)) {\n $wenoLog->insertWenoLog(\"Pharmacy Directory\", \"Download file not found or not readable\");\n error_log(\"Download file not found or not readable: \" . $filePath);\n return false;\n }\n // Begin transaction\n $connect->begin_transaction();\n try {\n $csv = Reader::createFromPath($filePath, 'r');\n $csv->setEscape('\\\\'); // Set the escape character to handle backslashes\n $csv->setHeaderOffset(0);\n $stmt = (new Statement())->offset(0);\n $records = $stmt->process($csv);\n\n $headers = $records->getHeader();\n $rowNumber = stripos($headers[3] ?? '', 'NCPDP_safe') !== false ? 1 : 2;\n\n if ($rowNumber === 2) {\n $csv->setHeaderOffset(1);\n $records = $stmt->process($csv);\n $headers = $records->getHeader();\n }\n if ($headers === false) {\n throw new Exception(\"Error reading header from file: $filePath\");\n }\n\n $columns = implode(\", \", array_map(fn($col) => \"`$col`\", $headers));\n $placeholders = implode(\", \", array_fill(0, count($headers), '?'));\n\n if ($isInsertOnly) {\n $sql = \"INSERT INTO weno_pharmacy ($columns) VALUES ($placeholders)\";\n } else {\n $updates = implode(\", \", array_map(fn($col) => \"`$col`=VALUES(`$col`)\", $headers));\n $sql = \"INSERT INTO weno_pharmacy ($columns) VALUES ($placeholders) ON DUPLICATE KEY UPDATE $updates\";\n }\n\n $stmt = $connect->prepare($sql);\n if (!$stmt) {\n throw new Exception(\"Prepare failed: (\" . $connect->errno . \") \" . $connect->error);\n }\n\n $types = str_repeat('s', count($headers));\n $recordSizeInBytes = 0;\n $batchSize = 30000;\n $batchRecords = [];\n foreach ($records as $record) {\n if (stripos($record['Created'], 'Confidential WENO Exchange') !== false) {\n continue;\n }\n $rowNumber++;\n\n $record = array_map(fn($item) => str_replace(['[', ']'], '', trim($item ?? '')), $record);\n $dateTime = \\DateTime::createFromFormat('m/d/Y h:i:s A', $record['Created']);\n $record['Created'] = $dateTime ? $dateTime->format('Y-m-d H:i:s') : null;\n $dateTime = \\DateTime::createFromFormat('m/d/Y h:i:s A', $record['Modified']);\n $record['Modified'] = $dateTime ? $dateTime->format('Y-m-d H:i:s') : null;\n $dateTime = \\DateTime::createFromFormat('m/d/Y h:i:s A', $record['Deleted']);\n $record['Deleted'] = $dateTime ? $dateTime->format('Y-m-d H:i:s') : null;\n\n $record['Business_Name'] = ucwords(strtolower($record['Business_Name']));\n $record['Address_Line_1'] = ucwords(strtolower($record['Address_Line_1']));\n $record['City'] = ucwords(strtolower($record['City']));\n\n if (count($record) !== count($headers)) {\n error_log(text(\"Column count mismatch at row $rowNumber in file: $filePath\"));\n continue;\n }\n // Batch records in groups of batch size.\n $batchRecords[] = $record;\n\n if (count($batchRecords) === $batchSize) {\n $recordSizeInBytes += strlen(serialize($batchRecords));\n foreach ($batchRecords as $record) {\n $stmt->bind_param($types, ...array_values($record));\n $stmt->execute();\n }\n $batchRecords = [];\n }\n }\n // Finish processing any remaining records.\n if (!empty($batchRecords)) {\n $recordSizeInBytes += strlen(serialize($batchRecords));\n foreach ($batchRecords as $record) {\n $stmt->bind_param($types, ...array_values($record));\n $stmt->execute();\n }\n }\n\n $connect->commit();\n // $connect->close();\n } catch (Exception $e) {\n $connect->rollback();\n error_log(text($e->getMessage()));\n return false;\n }\n\n return $rowNumber - 2;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getAdapter(?stdClass $configuration, Config $fullConfig = null): Adapter\\CustomReportAdapterInterface\n {\n if ($configuration === null) {\n $configuration = new stdClass();\n }\n\n $type = $configuration->type ?? 'sql';\n $serviceLocator = Pimcore::getContainer()->get('pimcore.custom_report.adapter.factories');\n\n if (!$serviceLocator->has($type)) {\n throw new RuntimeException(sprintf('Could not find Custom Report Adapter with type %s', $type));\n }\n\n /** @var \\Pimcore\\Bundle\\CustomReportsBundle\\Tool\\Adapter\\CustomReportAdapterFactoryInterface $factory */\n $factory = $serviceLocator->get($type);\n\n return $factory->create($configuration, $fullConfig);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function read($file)\n\t{\n\t\t$fh = fopen($file, \"r\");\n\t\tif (!$fh) {\n\t\t\tthrow new Exception(\"Can't open file $file\");\n\t\t}\n\t\t$this->_file_handle = $fh;\n\n\t\t$signature = fread($fh, 8);\n\t\tif (\"\\xD0\\xCF\\x11\\xE0\\xA1\\xB1\\x1A\\xE1\" != $signature) {\n\t\t\tthrow new Exception(\"File doesn't seem to be an OLE container.\");\n\t\t}\n\t\tfseek($fh, 28);\n\t\tif (fread($fh, 2) != \"\\xFE\\xFF\") {\n\t\t\t// This shouldn't be a problem in practice\n\t\t\tthrow new Exception(\"Only Little-Endian encoding is supported.\");\n\t\t}\n\t\t// Size of blocks and short blocks in bytes\n\t\t$this->bigBlockSize = pow(2, self::_readInt2($fh));\n\t\t$this->smallBlockSize = pow(2, self::_readInt2($fh));\n\n\t\t// Skip UID, revision number and version number\n\t\tfseek($fh, 44);\n\t\t// Number of blocks in Big Block Allocation Table\n\t\t$bbatBlockCount = self::_readInt4($fh);\n\n\t\t// Root chain 1st block\n\t\t$directoryFirstBlockId = self::_readInt4($fh);\n\n\t\t// Skip unused bytes\n\t\tfseek($fh, 56);\n\t\t// Streams shorter than this are stored using small blocks\n\t\t$this->bigBlockThreshold = self::_readInt4($fh);\n\t\t// Block id of first sector in Short Block Allocation Table\n\t\t$sbatFirstBlockId = self::_readInt4($fh);\n\t\t// Number of blocks in Short Block Allocation Table\n\t\t$sbbatBlockCount = self::_readInt4($fh);\n\t\t// Block id of first sector in Master Block Allocation Table\n\t\t$mbatFirstBlockId = self::_readInt4($fh);\n\t\t// Number of blocks in Master Block Allocation Table\n\t\t$mbbatBlockCount = self::_readInt4($fh);\n\t\t$this->bbat = array();\n\n\t\t// Remaining 4 * 109 bytes of current block is beginning of Master\n\t\t// Block Allocation Table\n\t\t$mbatBlocks = array();\n\t\tfor ($i = 0; $i < 109; ++$i) {\n\t\t\t$mbatBlocks[] = self::_readInt4($fh);\n\t\t}\n\n\t\t// Read rest of Master Block Allocation Table (if any is left)\n\t\t$pos = $this->_getBlockOffset($mbatFirstBlockId);\n\t\tfor ($i = 0; $i < $mbbatBlockCount; ++$i) {\n\t\t\tfseek($fh, $pos);\n\t\t\tfor ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {\n\t\t\t\t$mbatBlocks[] = self::_readInt4($fh);\n\t\t\t}\n\t\t\t// Last block id in each block points to next block\n\t\t\t$pos = $this->_getBlockOffset(self::_readInt4($fh));\n\t\t}\n\n\t\t// Read Big Block Allocation Table according to chain specified by\n\t\t// $mbatBlocks\n\t\tfor ($i = 0; $i < $bbatBlockCount; ++$i) {\n\t\t\t$pos = $this->_getBlockOffset($mbatBlocks[$i]);\n\t\t\tfseek($fh, $pos);\n\t\t\tfor ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) {\n\t\t\t\t$this->bbat[] = self::_readInt4($fh);\n\t\t\t}\n\t\t}\n\n\t\t// Read short block allocation table (SBAT)\n\t\t$this->sbat = array();\n\t\t$shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;\n\t\t$sbatFh = $this->getStream($sbatFirstBlockId);\n\t\tfor ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {\n\t\t\t$this->sbat[$blockId] = self::_readInt4($sbatFh);\n\t\t}\n\t\tfclose($sbatFh);\n\n\t\t$this->_readPpsWks($directoryFirstBlockId);\n\n\t\treturn true;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function installPhpParser(string $version, string $phpParserDir) {\n $lockFile = __DIR__ . \"/PHP-Parser-install-lock\";\n $lockFd = fopen($lockFile, 'w+');\n if (!flock($lockFd, LOCK_EX)) {\n throw new Exception(\"Failed to acquire installation lock\");\n }\n\n try {\n // Check whether a parallel process has already installed PHP-Parser.\n if (is_dir($phpParserDir)) {\n return;\n }\n\n $cwd = getcwd();\n chdir(__DIR__);\n\n $tarName = \"v$version.tar.gz\";\n passthru(\"wget https://github.com/nikic/PHP-Parser/archive/$tarName\", $exit);\n if ($exit !== 0) {\n passthru(\"curl -LO https://github.com/nikic/PHP-Parser/archive/$tarName\", $exit);\n }\n if ($exit !== 0) {\n throw new Exception(\"Failed to download PHP-Parser tarball\");\n }\n if (!mkdir($phpParserDir)) {\n throw new Exception(\"Failed to create directory $phpParserDir\");\n }\n passthru(\"tar xvzf $tarName -C PHP-Parser-$version --strip-components 1\", $exit);\n if ($exit !== 0) {\n throw new Exception(\"Failed to extract PHP-Parser tarball\");\n }\n unlink(__DIR__ . \"/$tarName\");\n chdir($cwd);\n } finally {\n flock($lockFd, LOCK_UN);\n @unlink($lockFile);\n }\n}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function init(): void {\n\t\t// prevent any XML processing from loading external entities\n\t\tlibxml_set_external_entity_loader(static function () {\n\t\t\treturn null;\n\t\t});\n\n\t\t// calculate the root directories\n\t\tOC::$SERVERROOT = str_replace(\"\\\\\", '/', substr(__DIR__, 0, -4));\n\n\t\t// register autoloader\n\t\t$loaderStart = microtime(true);\n\t\trequire_once __DIR__ . '/autoloader.php';\n\t\tself::$loader = new \\OC\\Autoloader([\n\t\t\tOC::$SERVERROOT . '/lib/private/legacy',\n\t\t]);\n\t\tif (defined('PHPUNIT_RUN')) {\n\t\t\tself::$loader->addValidRoot(OC::$SERVERROOT . '/tests');\n\t\t}\n\t\tspl_autoload_register([self::$loader, 'load']);\n\t\t$loaderEnd = microtime(true);\n\n\t\tself::$CLI = (php_sapi_name() == 'cli');\n\n\t\t// Add default composer PSR-4 autoloader, ensure apcu to be disabled\n\t\tself::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';\n\t\tself::$composerAutoloader->setApcuPrefix(null);\n\n\t\ttry {\n\t\t\tself::initPaths();\n\t\t\t// setup 3rdparty autoloader\n\t\t\t$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';\n\t\t\tif (!file_exists($vendorAutoLoad)) {\n\t\t\t\tthrow new \\RuntimeException('Composer autoloader not found, unable to continue. Check the folder \"3rdparty\". Running \"git submodule update --init\" will initialize the git submodule that handles the subfolder \"3rdparty\".');\n\t\t\t}\n\t\t\trequire_once $vendorAutoLoad;\n\t\t} catch (\\RuntimeException $e) {\n\t\t\tif (!self::$CLI) {\n\t\t\t\thttp_response_code(503);\n\t\t\t}\n\t\t\t// we can't use the template error page here, because this needs the\n\t\t\t// DI container which isn't available yet\n\t\t\tprint($e->getMessage());\n\t\t\texit();\n\t\t}\n\n\t\t// setup the basic server\n\t\tself::$server = new \\OC\\Server(\\OC::$WEBROOT, self::$config);\n\t\tself::$server->boot();\n\n\t\t$eventLogger = Server::get(\\OCP\\Diagnostics\\IEventLogger::class);\n\t\t$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);\n\t\t$eventLogger->start('boot', 'Initialize');\n\n\t\t// Override php.ini and log everything if we're troubleshooting\n\t\tif (self::$config->getValue('loglevel') === ILogger::DEBUG) {\n\t\t\terror_reporting(E_ALL);\n\t\t}\n\n\t\t// Don't display errors and log them\n\t\t@ini_set('display_errors', '0');\n\t\t@ini_set('log_errors', '1');\n\n\t\tif (!date_default_timezone_set('UTC')) {\n\t\t\tthrow new \\RuntimeException('Could not set timezone to UTC');\n\t\t}\n\n\n\t\t//try to configure php to enable big file uploads.\n\t\t//this doesn\u00b4t work always depending on the webserver and php configuration.\n\t\t//Let\u00b4s try to overwrite some defaults if they are smaller than 1 hour\n\n\t\tif (intval(@ini_get('max_execution_time') ?: 0) < 3600) {\n\t\t\t@ini_set('max_execution_time', strval(3600));\n\t\t}\n\n\t\tif (intval(@ini_get('max_input_time') ?: 0) < 3600) {\n\t\t\t@ini_set('max_input_time', strval(3600));\n\t\t}\n\n\t\t//try to set the maximum execution time to the largest time limit we have\n\t\tif (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {\n\t\t\t@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));\n\t\t}\n\n\t\tself::setRequiredIniValues();\n\t\tself::handleAuthHeaders();\n\t\t$systemConfig = Server::get(\\OC\\SystemConfig::class);\n\t\tself::registerAutoloaderCache($systemConfig);\n\n\t\t// initialize intl fallback if necessary\n\t\tOC_Util::isSetLocaleWorking();\n\n\t\t$config = Server::get(\\OCP\\IConfig::class);\n\t\tif (!defined('PHPUNIT_RUN')) {\n\t\t\t$errorHandler = new OC\\Log\\ErrorHandler(\n\t\t\t\t\\OCP\\Server::get(\\Psr\\Log\\LoggerInterface::class),\n\t\t\t);\n\t\t\t$exceptionHandler = [$errorHandler, 'onException'];\n\t\t\tif ($config->getSystemValueBool('debug', false)) {\n\t\t\t\tset_error_handler([$errorHandler, 'onAll'], E_ALL);\n\t\t\t\tif (\\OC::$CLI) {\n\t\t\t\t\t$exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tset_error_handler([$errorHandler, 'onError']);\n\t\t\t}\n\t\t\tregister_shutdown_function([$errorHandler, 'onShutdown']);\n\t\t\tset_exception_handler($exceptionHandler);\n\t\t}\n\n\t\t/** @var \\OC\\AppFramework\\Bootstrap\\Coordinator $bootstrapCoordinator */\n\t\t$bootstrapCoordinator = Server::get(\\OC\\AppFramework\\Bootstrap\\Coordinator::class);\n\t\t$bootstrapCoordinator->runInitialRegistration();\n\n\t\t$eventLogger->start('init_session', 'Initialize session');\n\t\tOC_App::loadApps(['session']);\n\t\tif (!self::$CLI) {\n\t\t\tself::initSession();\n\t\t}\n\t\t$eventLogger->end('init_session');\n\t\tself::checkConfig();\n\t\tself::checkInstalled($systemConfig);\n\n\t\tOC_Response::addSecurityHeaders();\n\n\t\tself::performSameSiteCookieProtection($config);\n\n\t\tif (!defined('OC_CONSOLE')) {\n\t\t\t$errors = OC_Util::checkServer($systemConfig);\n\t\t\tif (count($errors) > 0) {\n\t\t\t\tif (!self::$CLI) {\n\t\t\t\t\thttp_response_code(503);\n\t\t\t\t\tOC_Util::addStyle('guest');\n\t\t\t\t\ttry {\n\t\t\t\t\t\tOC_Template::printGuestPage('', 'error', ['errors' => $errors]);\n\t\t\t\t\t\texit;\n\t\t\t\t\t} catch (\\Exception $e) {\n\t\t\t\t\t\t// In case any error happens when showing the error page, we simply fall back to posting the text.\n\t\t\t\t\t\t// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Convert l10n string into regular string for usage in database\n\t\t\t\t$staticErrors = [];\n\t\t\t\tforeach ($errors as $error) {\n\t\t\t\t\techo $error['error'] . \"\\n\";\n\t\t\t\t\techo $error['hint'] . \"\\n\\n\";\n\t\t\t\t\t$staticErrors[] = [\n\t\t\t\t\t\t'error' => (string)$error['error'],\n\t\t\t\t\t\t'hint' => (string)$error['hint'],\n\t\t\t\t\t];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\t$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));\n\t\t\t\t} catch (\\Exception $e) {\n\t\t\t\t\techo('Writing to database failed');\n\t\t\t\t}\n\t\t\t\texit(1);\n\t\t\t} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {\n\t\t\t\t$config->deleteAppValue('core', 'cronErrors');\n\t\t\t}\n\t\t}\n\n\t\t// User and Groups\n\t\tif (!$systemConfig->getValue(\"installed\", false)) {\n\t\t\tself::$server->getSession()->set('user_id', '');\n\t\t}\n\n\t\tOC_User::useBackend(new \\OC\\User\\Database());\n\t\tServer::get(\\OCP\\IGroupManager::class)->addBackend(new \\OC\\Group\\Database());\n\n\t\t// Subscribe to the hook\n\t\t\\OCP\\Util::connectHook(\n\t\t\t'\\OCA\\Files_Sharing\\API\\Server2Server',\n\t\t\t'preLoginNameUsedAsUserName',\n\t\t\t'\\OC\\User\\Database',\n\t\t\t'preLoginNameUsedAsUserName'\n\t\t);\n\n\t\t//setup extra user backends\n\t\tif (!\\OCP\\Util::needUpgrade()) {\n\t\t\tOC_User::setupBackends();\n\t\t} else {\n\t\t\t// Run upgrades in incognito mode\n\t\t\tOC_User::setIncognitoMode(true);\n\t\t}\n\n\t\tself::registerCleanupHooks($systemConfig);\n\t\tself::registerShareHooks($systemConfig);\n\t\tself::registerEncryptionWrapperAndHooks();\n\t\tself::registerAccountHooks();\n\t\tself::registerResourceCollectionHooks();\n\t\tself::registerFileReferenceEventListener();\n\t\tself::registerRenderReferenceEventListener();\n\t\tself::registerAppRestrictionsHooks();\n\n\t\t// Make sure that the application class is not loaded before the database is setup\n\t\tif ($systemConfig->getValue(\"installed\", false)) {\n\t\t\tOC_App::loadApp('settings');\n\t\t\t/* Build core application to make sure that listeners are registered */\n\t\t\tServer::get(\\OC\\Core\\Application::class);\n\t\t}\n\n\t\t//make sure temporary files are cleaned up\n\t\t$tmpManager = Server::get(\\OCP\\ITempManager::class);\n\t\tregister_shutdown_function([$tmpManager, 'clean']);\n\t\t$lockProvider = Server::get(\\OCP\\Lock\\ILockingProvider::class);\n\t\tregister_shutdown_function([$lockProvider, 'releaseAll']);\n\n\t\t// Check whether the sample configuration has been copied\n\t\tif ($systemConfig->getValue('copied_sample_config', false)) {\n\t\t\t$l = Server::get(\\OCP\\L10N\\IFactory::class)->get('lib');\n\t\t\tOC_Template::printErrorPage(\n\t\t\t\t$l->t('Sample configuration detected'),\n\t\t\t\t$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),\n\t\t\t\t503\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t$request = Server::get(IRequest::class);\n\t\t$host = $request->getInsecureServerHost();\n\t\t/**\n\t\t * if the host passed in headers isn't trusted\n\t\t * FIXME: Should not be in here at all :see_no_evil:\n\t\t */\n\t\tif (!OC::$CLI\n\t\t\t&& !Server::get(\\OC\\Security\\TrustedDomainHelper::class)->isTrustedDomain($host)\n\t\t\t&& $config->getSystemValueBool('installed', false)\n\t\t) {\n\t\t\t// Allow access to CSS resources\n\t\t\t$isScssRequest = false;\n\t\t\tif (strpos($request->getPathInfo() ?: '', '/css/') === 0) {\n\t\t\t\t$isScssRequest = true;\n\t\t\t}\n\n\t\t\tif (substr($request->getRequestUri(), -11) === '/status.php') {\n\t\t\t\thttp_response_code(400);\n\t\t\t\theader('Content-Type: application/json');\n\t\t\t\techo '{\"error\": \"Trusted domain error.\", \"code\": 15}';\n\t\t\t\texit();\n\t\t\t}\n\n\t\t\tif (!$isScssRequest) {\n\t\t\t\thttp_response_code(400);\n\t\t\t\tServer::get(LoggerInterface::class)->info(\n\t\t\t\t\t'Trusted domain error. \"{remoteAddress}\" tried to access using \"{host}\" as host.',\n\t\t\t\t\t[\n\t\t\t\t\t\t'app' => 'core',\n\t\t\t\t\t\t'remoteAddress' => $request->getRemoteAddress(),\n\t\t\t\t\t\t'host' => $host,\n\t\t\t\t\t]\n\t\t\t\t);\n\n\t\t\t\t$tmpl = new OCP\\Template('core', 'untrustedDomain', 'guest');\n\t\t\t\t$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));\n\t\t\t\t$tmpl->printPage();\n\n\t\t\t\texit();\n\t\t\t}\n\t\t}\n\t\t$eventLogger->end('boot');\n\t\t$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));\n\t\t$eventLogger->start('runtime', 'Runtime');\n\t\t$eventLogger->start('request', 'Full request after boot');\n\t\tregister_shutdown_function(function () use ($eventLogger) {\n\t\t\t$eventLogger->end('request');\n\t\t});\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getServerById(int $id): array {\n\t\t$query = $this->connection->getQueryBuilder();\n\t\t$query->select('*')->from($this->dbTable)\n\t\t\t->where($query->expr()->eq('id', $query->createParameter('id')))\n\t\t\t->setParameter('id', $id, IQueryBuilder::PARAM_INT);\n\n\t\t$qResult = $query->executeQuery();\n\t\t$result = $qResult->fetchAll();\n\t\t$qResult->closeCursor();\n\n\t\tif (empty($result)) {\n\t\t\tthrow new \\Exception('No Server found with ID: ' . $id);\n\t\t}\n\n\t\treturn $result[0];\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $url, int $width, int $height, Response $response) {\n\n $quality = 80;\n $output = 'png';\n $type = 'png';\n\n if (!\\extension_loaded('imagick')) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing');\n }\n\n $domain = new Domain(\\parse_url($url, PHP_URL_HOST));\n\n if (!$domain->isKnown()) {\n throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED);\n }\n\n $fetch = @\\file_get_contents($url);\n\n if (!$fetch) {\n throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND);\n }\n\n try {\n $image = new Image($fetch);\n } catch (\\Exception $exception) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unable to parse image');\n }\n\n $image->crop((int) $width, (int) $height);\n $output = (empty($output)) ? $type : $output;\n $data = $image->output($output, $quality);\n\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + 60 * 60 * 24 * 30) . ' GMT')\n ->setContentType('image/png')\n ->file($data);\n unset($image);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function preGetData(mixed $container, array $params = []): mixed\n {\n if (\n !$container instanceof DataObject\\Concrete &&\n !$container instanceof DataObject\\Fieldcollection\\Data\\AbstractData &&\n !$container instanceof DataObject\\Objectbrick\\Data\\AbstractData\n ) {\n throw new Exception('Localized Fields are only valid in Objects, Fieldcollections and Objectbricks');\n }\n\n $lf = $container->getObjectVar('localizedfields');\n if (!$lf instanceof Localizedfield) {\n $lf = new Localizedfield();\n\n $object = $container;\n if ($container instanceof DataObject\\Objectbrick\\Data\\AbstractData) {\n $object = $container->getObject();\n\n $context = [\n 'containerType' => 'objectbrick',\n 'containerKey' => $container->getType(),\n 'fieldname' => $container->getFieldname(),\n ];\n $lf->setContext($context);\n } elseif ($container instanceof DataObject\\Fieldcollection\\Data\\AbstractData) {\n $object = $container->getObject();\n\n $context = [\n 'containerType' => 'fieldcollection',\n 'containerKey' => $container->getType(),\n 'fieldname' => $container->getFieldname(),\n ];\n $lf->setContext($context);\n } elseif ($container instanceof DataObject\\Concrete) {\n $context = ['object' => $container];\n $lf->setContext($context);\n }\n $lf->setObject($object);\n\n $container->setObjectVar('localizedfields', $lf);\n }\n\n return $container->getObjectVar('localizedfields');\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getPreRelease()\n {\n if ($this->prerelease === false) {\n throw new Exception('This is not a pre-release build');\n }\n\n return $this->prerelease;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $projectId, bool $enabled, string $senderName, string $senderEmail, string $replyTo, string $host, int $port, string $username, string $password, string $secure, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n // Ensure required params for when enabling SMTP\n if ($enabled) {\n if (empty($senderName)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Sender name is required when enabling SMTP.');\n } elseif (empty($senderEmail)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Sender email is required when enabling SMTP.');\n } elseif (empty($host)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Host is required when enabling SMTP.');\n } elseif (empty($port)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Port is required when enabling SMTP.');\n }\n }\n\n // validate SMTP settings\n if ($enabled) {\n $mail = new PHPMailer(true);\n $mail->isSMTP();\n $mail->Username = $username;\n $mail->Password = $password;\n $mail->Host = $host;\n $mail->Port = $port;\n $mail->SMTPSecure = $secure;\n $mail->SMTPAutoTLS = false;\n $mail->Timeout = 5;\n\n try {\n $valid = $mail->SmtpConnect();\n\n if (!$valid) {\n throw new Exception('Connection is not valid.');\n }\n } catch (Throwable $error) {\n throw new Exception(Exception::PROJECT_SMTP_CONFIG_INVALID, 'Could not connect to SMTP server: ' . $error->getMessage());\n }\n }\n\n // Save SMTP settings\n if ($enabled) {\n $smtp = [\n 'enabled' => $enabled,\n 'senderName' => $senderName,\n 'senderEmail' => $senderEmail,\n 'replyTo' => $replyTo,\n 'host' => $host,\n 'port' => $port,\n 'username' => $username,\n 'password' => $password,\n 'secure' => $secure,\n ];\n } else {\n $smtp = [\n 'enabled' => false\n ];\n }\n\n $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('smtp', $smtp));\n\n $response->dynamic($project, Response::MODEL_PROJECT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function setXAxis(&$x_axis, $font_size)\n {\n if (!isset($this->_xAxisDataObject) ) {\n throw new \\Exception(get_class($this).\" _xAxisDataObject not set \");\n }\n\n $defaultXAxisLabel = 'xAxis';\n $xAxisLabel = $this->_xAxisDataObject->getName() == ORGANIZATION_NAME ? '' :\n $this->_xAxisDataObject->getName();\n\n if($xAxisLabel == '')\n {\n $xAxisLabel = $defaultXAxisLabel;\n }\n $originalXAxisLabel = $xAxisLabel;\n\n if(isset($x_axis->{$xAxisLabel}))\n {\n $config = $x_axis->{$xAxisLabel};\n if(isset($config->title))\n {\n $xAxisLabel = $config->title;\n }\n }\n if($xAxisLabel == $defaultXAxisLabel)\n {\n $xAxisLabel = '';\n }\n\n // --- set xAxis in _chart object ---\n $this->_chart['layout']['xaxis'] = array(\n 'automargin' => true,\n 'cliponaxis' => false,\n 'layer' => 'below traces',\n 'title' => array(\n 'text' => '' . $xAxisLabel . '',\n 'standoff' => 5,\n 'font' => array(\n 'size' => ($font_size + 12),\n 'color' => '#000000',\n 'family' => 'Lucida Grande, Lucida Sans Unicode, Arial, Helvetica, sans-serif'\n ),\n ),\n 'otitle' => $originalXAxisLabel,\n 'dtitle' => $defaultXAxisLabel,\n 'tickfont' => array(\n 'size' => ($font_size + 11),\n 'color' => '#606060',\n ),\n 'ticktext' => array(),\n 'type' => 'category',\n 'linewidth' => 2 + $font_size / 4,\n 'linecolor' => '#c0d0e0',\n 'rangemode' => 'tozero',\n 'showgrid' => false,\n 'gridcolor' => '#c0c0c0',\n 'spikedash' => 'solid',\n 'spikethickness' => 1,\n 'spikecolor' => '#c0c0c0',\n 'standoff' => 25,\n 'timeseries' => false,\n 'categoryarray' => $this->_xAxisDataObject->getValues()\n );\n\n if (isset($this->_chart['layout']['xaxis']['categoryarray']))\n {\n $this->_chart['layout']['xaxis']['categoryorder'] = 'array';\n }\n\n $count = $this->_xAxisDataObject->getCount();\n $this->_chart['layout']['xaxis']['dtick'] = $count < 20 ? 0 : round($count / 20);\n if (!$this->_swapXY)\n {\n $this->_chart['layout']['xaxis']['tickangle'] = -90;\n $this->_chart['layout']['xaxis']['ticklabelposition'] = 'outside left';\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $databaseId, string $collectionId, Response $response, Database $dbForProject, string $mode, Event $events, Delete $deletes) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n if (!$dbForProject->deleteDocument('database_' . $database->getInternalId(), $collectionId)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove collection from DB');\n }\n\n $dbForProject->deleteCachedCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId());\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($collection);\n\n $events\n ->setContext('database', $database)\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setPayload($response->output($collection, Response::MODEL_COLLECTION));\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $this->permissionResolver->setCurrentUserReference(\n $this->userService->loadUserByLogin($input->getOption('user'))\n );\n\n $limit = $input->getOption('iteration-count');\n if (!ctype_digit($limit) || (int)$limit < 1) {\n throw new RuntimeException(\"'--iteration-count' should be > 0, you passed '{$limit}'\");\n }\n\n $limit = (int)$limit;\n\n $query = new URLQuery();\n $query->filter = new Criterion\\VisibleOnly();\n $query->sortClauses = [\n new SortClause\\URL(),\n ];\n $query->offset = 0;\n $query->limit = $limit;\n\n $totalCount = $this->getTotalCount();\n\n $progress = new ProgressBar($output, $totalCount);\n $progress->start();\n while ($query->offset < $totalCount) {\n $this->urlChecker->check($query);\n\n $progress->advance(min($limit, $totalCount - $query->offset));\n $query->offset += $limit;\n }\n $progress->finish();\n\n return self::SUCCESS;\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function Create()\n {\n try {\n $json = json_decode(RequestUtil::GetBody());\n if (empty($json)) {\n throw new Exception('The request body does not contain valid JSON');\n }\n if ($_SESSION['pid'] !== true && $_SESSION['register'] !== true) {\n throw new Exception('Unauthorized');\n }\n\n if (empty($_SESSION['fnameRegistration']) || empty($_SESSION['lnameRegistration']) || empty($_SESSION['dobRegistration']) || empty($_SESSION['emailRegistration']) || empty($_SESSION['token_id_holder'])) {\n throw new Exception('Something went wrong');\n }\n\n // get new pid\n $result = sqlQueryNoLog(\"select max(`pid`)+1 as `pid` from `patient_data`\");\n if (empty($result['pid'])) {\n $pidRegistration = 1;\n } else {\n $pidRegistration = $result['pid'];\n }\n // store the pid so can use for other registration elements inserted later (such as insurance)\n sqlStatementNoLog(\"UPDATE `verify_email` SET `pid_holder` = ? WHERE `id` = ?\", [$pidRegistration , $_SESSION['token_id_holder']]);\n\n $patient = new Patient($this->Phreezer);\n $patient->Title = $this->SafeGetVal($json, 'title', $patient->Title);\n $patient->Language = $this->SafeGetVal($json, 'language', $patient->Language);\n $patient->Financial = $this->SafeGetVal($json, 'financial', $patient->Financial);\n //$patient->Fname = $this->SafeGetVal($json, 'fname', $patient->Fname);\n $patient->Fname = $_SESSION['fnameRegistration'];\n //$patient->Lname = $this->SafeGetVal($json, 'lname', $patient->Lname);\n $patient->Lname = $_SESSION['lnameRegistration'];\n //$patient->Mname = $this->SafeGetVal($json, 'mname', $patient->Mname);\n $patient->Mname = $_SESSION['mnameRegistration'];\n //$patient->Dob = date('Y-m-d', strtotime($this->SafeGetVal($json, 'dob', $patient->Dob)));\n $patient->Dob = $_SESSION['dobRegistration'];\n $patient->Street = $this->SafeGetVal($json, 'street', $patient->Street);\n $patient->PostalCode = $this->SafeGetVal($json, 'postalCode', $patient->PostalCode);\n $patient->City = $this->SafeGetVal($json, 'city', $patient->City);\n $patient->State = $this->SafeGetVal($json, 'state', $patient->State);\n $patient->CountryCode = $this->SafeGetVal($json, 'countryCode', $patient->CountryCode);\n $patient->DriversLicense = $this->SafeGetVal($json, 'driversLicense', $patient->DriversLicense);\n $patient->Ss = $this->SafeGetVal($json, 'ss', $patient->Ss);\n $patient->Occupation = $this->SafeGetVal($json, 'occupation', $patient->Occupation);\n $patient->PhoneHome = $this->SafeGetVal($json, 'phoneHome', $patient->PhoneHome);\n $patient->PhoneBiz = $this->SafeGetVal($json, 'phoneBiz', $patient->PhoneBiz);\n $patient->PhoneContact = $this->SafeGetVal($json, 'phoneContact', $patient->PhoneContact);\n $patient->PhoneCell = $this->SafeGetVal($json, 'phoneCell', $patient->PhoneCell);\n $patient->PharmacyId = $this->SafeGetVal($json, 'pharmacyId', $patient->PharmacyId);\n $patient->Status = $this->SafeGetVal($json, 'status', $patient->Status);\n $patient->ContactRelationship = $this->SafeGetVal($json, 'contactRelationship', $patient->ContactRelationship);\n $patient->Date = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'date', $patient->Date)));\n $patient->Sex = $this->SafeGetVal($json, 'sex', $patient->Sex);\n $patient->Referrer = $this->SafeGetVal($json, 'referrer', $patient->Referrer);\n $patient->Referrerid = $this->SafeGetVal($json, 'referrerid', $patient->Referrerid);\n $patient->Providerid = $this->SafeGetVal($json, 'providerid', $patient->Providerid);\n $patient->RefProviderid = $this->SafeGetVal($json, 'refProviderid', $patient->RefProviderid);\n //$patient->Email = $this->SafeGetVal($json, 'email', $patient->Email);\n $patient->Email = $_SESSION['emailRegistration'];\n //$patient->EmailDirect = $this->SafeGetVal($json, 'emailDirect', $patient->EmailDirect);\n $patient->Ethnoracial = $this->SafeGetVal($json, 'ethnoracial', $patient->Ethnoracial);\n $patient->Race = $this->SafeGetVal($json, 'race', $patient->Race);\n $patient->Ethnicity = $this->SafeGetVal($json, 'ethnicity', $patient->Ethnicity);\n $patient->Religion = $this->SafeGetVal($json, 'religion', $patient->Religion);\n //$patient->Interpretter = $this->SafeGetVal($json, 'interpretter', $patient->Interpretter);\n //$patient->Migrantseasonal = $this->SafeGetVal($json, 'migrantseasonal', $patient->Migrantseasonal);\n $patient->FamilySize = $this->SafeGetVal($json, 'familySize', $patient->FamilySize);\n //$patient->MonthlyIncome = $this->SafeGetVal($json, 'monthlyIncome', $patient->MonthlyIncome);\n //$patient->BillingNote = $this->SafeGetVal($json, 'billingNote', $patient->BillingNote);\n //$patient->Homeless = $this->SafeGetVal($json, 'homeless', $patient->Homeless);\n //$patient->FinancialReview = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'financialReview', $patient->FinancialReview)));\n //$patient->Pubpid = $this->SafeGetVal($json, 'pubpid', $patient->Pubpid);\n $patient->Pubpid = $pidRegistration;\n //$patient->Pid = $this->SafeGetVal($json, 'pid', $patient->Pid);\n $patient->Pid = $pidRegistration;\n //$patient->Genericname1 = $this->SafeGetVal($json, 'genericname1', $patient->Genericname1);\n //$patient->Genericval1 = $this->SafeGetVal($json, 'genericval1', $patient->Genericval1);\n //$patient->Genericname2 = $this->SafeGetVal($json, 'genericname2', $patient->Genericname2);\n //$patient->Genericval2 = $this->SafeGetVal($json, 'genericval2', $patient->Genericval2);\n $patient->HipaaMail = $this->SafeGetVal($json, 'hipaaMail', $patient->HipaaMail);\n $patient->HipaaVoice = $this->SafeGetVal($json, 'hipaaVoice', $patient->HipaaVoice);\n $patient->HipaaNotice = $this->SafeGetVal($json, 'hipaaNotice', $patient->HipaaNotice);\n $patient->HipaaMessage = $this->SafeGetVal($json, 'hipaaMessage', $patient->HipaaMessage);\n $patient->HipaaAllowsms = $this->SafeGetVal($json, 'hipaaAllowsms', $patient->HipaaAllowsms);\n $patient->HipaaAllowemail = $this->SafeGetVal($json, 'hipaaAllowemail', $patient->HipaaAllowemail);\n //$patient->Squad = $this->SafeGetVal($json, 'squad', $patient->Squad);\n //$patient->Fitness = $this->SafeGetVal($json, 'fitness', $patient->Fitness);\n //$patient->ReferralSource = $this->SafeGetVal($json, 'referralSource', $patient->ReferralSource);\n //$patient->Pricelevel = $this->SafeGetVal($json, 'pricelevel', $patient->Pricelevel);\n $patient->Regdate = date('Y-m-d', strtotime($this->SafeGetVal($json, 'regdate', $patient->Regdate)));\n //$patient->Contrastart = date('Y-m-d', strtotime($this->SafeGetVal($json, 'contrastart', $patient->Contrastart)));\n //$patient->CompletedAd = $this->SafeGetVal($json, 'completedAd', $patient->CompletedAd);\n //$patient->AdReviewed = date('Y-m-d', strtotime($this->SafeGetVal($json, 'adReviewed', $patient->AdReviewed)));\n //$patient->Vfc = $this->SafeGetVal($json, 'vfc', $patient->Vfc);\n $patient->Mothersname = $this->SafeGetVal($json, 'mothersname', $patient->Mothersname);\n $patient->Guardiansname = $this->SafeGetVal($json, 'guardiansname', $patient->Guardiansname);\n $patient->AllowImmRegUse = $this->SafeGetVal($json, 'allowImmRegUse', $patient->AllowImmRegUse);\n $patient->AllowImmInfoShare = $this->SafeGetVal($json, 'allowImmInfoShare', $patient->AllowImmInfoShare);\n $patient->AllowHealthInfoEx = $this->SafeGetVal($json, 'allowHealthInfoEx', $patient->AllowHealthInfoEx);\n $patient->AllowPatientPortal = $this->SafeGetVal($json, 'allowPatientPortal', $patient->AllowPatientPortal);\n //$patient->DeceasedDate = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'deceasedDate', $patient->DeceasedDate)));\n //$patient->DeceasedReason = $this->SafeGetVal($json, 'deceasedReason', $patient->DeceasedReason);\n //$patient->SoapImportStatus = $this->SafeGetVal($json, 'soapImportStatus', $patient->SoapImportStatus);\n //$patient->CmsportalLogin = $this->SafeGetVal($json, 'cmsportalLogin', $patient->CmsportalLogin);\n $patient->CareTeam = $this->SafeGetVal($json, 'careTeam', $patient->CareTeam);\n $patient->County = $this->SafeGetVal($json, 'county', $patient->County);\n //$patient->Industry = $this->SafeGetVal($json, 'industry', $patient->Industry);\n $patient->Validate();\n $errors = $patient->GetValidationErrors();\n if (count($errors) > 0) {\n $this->RenderErrorJSON('Please check the form for errors' . $errors, $errors);\n } else {\n $patient->Save(true);\n $this->RenderJSON($patient, $this->JSONPCallback(), true, $this->SimpleObjectParams());\n }\n } catch (Exception $ex) {\n $this->RenderExceptionJSON($ex);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function _cellToPackedRowcol($cell)\n\t{\n\t\t$cell = strtoupper($cell);\n\t\tlist($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell);\n\t\tif ($col >= 256) {\n\t\t\tthrow new Exception(\"Column in: $cell greater than 255\");\n\t\t}\n\t\t// FIXME: change for BIFF8\n\t\tif ($row >= 16384) {\n\t\t\tthrow new Exception(\"Row in: $cell greater than 16384 \");\n\t\t}\n\n\t\t// Set the high bits to indicate if row or col are relative.\n\t\tif ($this->_BIFF_version == 0x0500) {\n\t\t\t$row |= $col_rel << 14;\n\t\t\t$row |= $row_rel << 15;\n\t\t\t$col = pack('C', $col);\n\t\t} elseif ($this->_BIFF_version == 0x0600) {\n\t\t\t$col |= $col_rel << 14;\n\t\t\t$col |= $row_rel << 15;\n\t\t\t$col = pack('v', $col);\n\t\t}\n\t\t$row = pack('v', $row);\n\n\t\treturn array($row, $col);\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function read($length): string\n {\n if (!isset($this->stream)) {\n throw new \\RuntimeException('Stream is detached');\n }\n if (!$this->readable) {\n throw new \\RuntimeException('Cannot read from non-readable stream');\n }\n if ($length < 0) {\n throw new \\RuntimeException('Length parameter cannot be negative');\n }\n\n if (0 === $length) {\n return '';\n }\n\n try {\n $string = fread($this->stream, $length);\n } catch (\\Exception $e) {\n throw new \\RuntimeException('Unable to read from stream', 0, $e);\n }\n\n if (false === $string) {\n throw new \\RuntimeException('Unable to read from stream');\n }\n\n return $string;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getOAuth2AuthCredentials($provider, $refresh=false) {\n if (!($c=$this->getConfig()))\n return false;\n\n $creds=$c->toArray();\n // Decrypt Access Token\n if ($creds['access_token']) {\n $creds['access_token'] = Crypto::decrypt(\n $creds['access_token'],\n SECRET_SALT,\n md5($creds['resource_owner_email'].$this->getNamespace())\n );\n }\n\n // Decrypt Referesh Token\n if ($creds['refresh_token']) {\n $creds['refresh_token'] = Crypto::decrypt(\n $creds['refresh_token'],\n SECRET_SALT,\n md5($creds['resource_owner_email'].$this->getNamespace())\n );\n }\n\n try {\n // Init credentials and see of we need to\n // refresh the token\n $errors = [];\n $auth = sprintf('oauth2:%s', $provider);\n $class = 'osTicket\\Mail\\OAuth2AuthCredentials';\n if (($cred=$class::init($creds))\n && ($token=$cred->getToken())\n && ($refresh && $token->isExpired())\n && ($bk=$this->getOAuth2Backend())\n && ($info=$bk->refreshAccessToken( #nolint\n $token->getRefreshToken(),\n $this->getBkId(), $errors))\n && isset($info['access_token'])\n && $this->updateCredentials($auth,\n // Merge new access token with\n // already decrypted creds\n array_merge($creds, $info), $errors\n )) {\n return $this->getCredentials($auth, $refresh);\n } elseif ($errors) {\n // Throw an exception with the error\n throw new Exception($errors['refresh_token']\n ?? __('Referesh Token Expired'));\n }\n } catch (Exception $ex) {\n // rethrow the exception including above.\n throw $ex;\n }\n return $cred;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public static function GetFileUpload($fieldname, $ignore_empty = false, $max_kb = 0, $ok_types = null)\n {\n // make sure there is actually a file upload\n if (! isset($_FILES [$fieldname])) {\n // this means the form field wasn't present which is generally an error\n // however if ignore is specified, then return empty string\n if ($ignore_empty) {\n return null;\n }\n\n throw new Exception(\"\\$_FILES['\" . $fieldname . \"'] is empty. Did you forget to add enctype='multipart/form-data' to your form code?\");\n }\n\n // make sure a file was actually uploaded, otherwise return null\n if ($_FILES [$fieldname] ['error'] == 4) {\n return;\n }\n\n // get the upload ref\n $upload = $_FILES [$fieldname];\n\n // make sure there were no errors during upload, but ignore case where\n if ($upload ['error']) {\n $error_codes [0] = \"The file uploaded with success.\";\n $error_codes [1] = \"The uploaded file exceeds the upload_max_filesize directive in php.ini.\";\n $error_codes [2] = \"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.\";\n $error_codes [3] = \"The uploaded file was only partially uploaded.\";\n $error_codes [4] = \"No file was uploaded.\";\n throw new Exception(\"Error uploading file: \" . $error_codes [$upload ['error']]);\n }\n\n // backwards compatibility\n if (self::$TestMode) {\n self::$VALIDATE_FILE_UPLOAD = false;\n }\n\n // make sure this is a legit file request\n if (self::$VALIDATE_FILE_UPLOAD && is_uploaded_file($upload ['tmp_name']) == false) {\n throw new Exception(\"Unable to access this upload: \" . $fieldname);\n }\n\n // get the filename and Extension\n $tmp_path = $upload ['tmp_name'];\n $info = pathinfo($upload ['name']);\n\n require_once(\"FileUpload.php\");\n $fupload = new FileUpload();\n $fupload->Name = $info ['basename'];\n $fupload->Size = $upload ['size'];\n $fupload->Type = $upload ['type'];\n $fupload->Extension = strtolower($info ['extension']);\n\n if ($ok_types && ! in_array($fupload->Extension, $ok_types)) {\n throw new Exception(\"The file '\" . htmlentities($fupload->Name) . \"' is not a type that is allowed. Allowed file types are: \" . (implode(\", \", $ok_types)) . \".\");\n }\n\n if ($max_kb && ($fupload->Size / 1024) > $max_kb) {\n throw new Exception(\"The file '\" . htmlentities($fupload->Name) . \"' is to large. Maximum allowed size is \" . number_format($max_kb / 1024, 2) . \"Mb\");\n }\n\n // open the file and read the entire contents\n $fh = fopen($tmp_path, \"r\");\n $fupload->Data = fread($fh, filesize($tmp_path));\n fclose($fh);\n\n return $fupload;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function getFieldtypeIdentifier(VisibleCSSLocator $fieldLocator, string $fieldName): string\n {\n $isEditable = !$this->getHTMLPage()\n ->find($fieldLocator)\n ->hasClass($this->getLocator('noneditableFieldClass')->getSelector());\n\n if (!$isEditable) {\n return strtolower($fieldName);\n }\n\n $fieldClass = $this->getHTMLPage()->find($fieldLocator)->getAttribute('class');\n $pattern = '/ibexa-field-edit--[ez|ibexa][a-z_]*/';\n\n preg_match($pattern, $fieldClass, $matches);\n\n if (empty($matches)) {\n throw new RuntimeException(sprintf(\n 'Cannot match results for pattern: \"%s\" and subject: \"%s\".',\n $pattern,\n $fieldClass\n ));\n }\n\n $matchedResults = explode('--', $matches[0]);\n\n return $matchedResults[1];\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public function saveUser()\n {\n /* BEGIN: VALIDATION */\n if ($this->isPublicUser()) {\n throw new Exception('The public role user cannot be saved.');\n }\n\n if ($this->_user_type == 0) {\n throw new Exception('The user must have a valid user type.');\n }\n\n if (count($this->_roles) === 0) {\n throw new Exception('A user must have at least one role.');\n }\n\n if (count($this->_acls) === 0) {\n throw new Exception('A user must have at least one acl.');\n }\n\n $match = preg_match(RESTRICTION_USERNAME, $this->_username);\n if ($match === false || $match === 0) {\n throw new Exception('A user must have a valid username.');\n }\n\n // Retrieve the userId (if any) for the email associated with this User\n // object.\n $id_of_user_holding_email_address = self::userExistsWithEmailAddress($this->_email);\n\n // A common e-mail address CAN be shared among multiple XSEDE accounts...\n // Each XDMoD (local) account must have a distinct e-mail address (unless that e-mail address is present in moddb.ExceptionEmailAddresses)\n\n // The second condition is in place to account for the case where a new Single Sign On user is being created (and is not currently in the XDMoD DB)\n if (($id_of_user_holding_email_address != INVALID) && ($this->getUserType() != SSO_USER_TYPE)) {\n\n if (!isset($this->_id)) {\n // This user has no record in the database (never saved). If $id_of_user_holding_email_address\n // holds a valid id, then an already saved user has the e-mail address.\n\n throw new Exception(\"An XDMoD user with e-mail address {$this->_email} exists\");\n } else {\n\n // This user has been saved, so we make sure the $id_of_user_holding_email_address is in fact this user's\n // id... otherwise throw the exception\n\n if ($id_of_user_holding_email_address != $this->_id) {\n throw new Exception(\"An XDMoD user with e-mail address {$this->_email} exists\");\n }\n }\n }//if ($id_of_user_holding_email_address != INVALID)\n\n /* END: VALIDATION */\n\n $handle = $this->_pdo->handle();\n $update_data = array();\n\n // Determine whether or not we're inserting or updating.\n $forUpdate = isset($this->_id);\n\n /* BEGIN: Query Data Population */\n if ($forUpdate) {\n $update_data['id'] = $this->_id;\n }\n\n $update_data['username'] = $this->_username;\n $includePassword = strlen($this->_password) <= CHARLIM_PASSWORD;\n if ($includePassword) {\n if ($this->_password == \"\" || is_null($this->_password)) {\n $update_data['password'] = NULL;\n } else {\n $this->_password = password_hash($this->_password, PASSWORD_DEFAULT);\n $update_data['password'] = $this->_password;\n }\n $update_data['password_last_updated'] = 'NOW()';\n }\n $update_data['email_address'] = ($this->_email);\n $update_data['first_name'] = ($this->_firstName);\n $update_data['middle_name'] = ($this->_middleName);\n $update_data['last_name'] = ($this->_lastName);\n $update_data['account_is_active'] = ($this->_account_is_active) ? '1' : '0';\n $update_data['person_id'] = $this->_personID == null\n ? 'NULL'\n : ($this->_personID);\n $update_data['organization_id'] = $this->_organizationID == null\n ? 'NULL'\n : ($this->_organizationID);\n $update_data['field_of_science'] = ($this->_field_of_science);\n if ($this->_update_token) {\n $update_data['token'] = ($this->_generateToken());\n $this->_token = $update_data['token'];\n }\n $update_data['user_type'] = $this->_user_type;\n $update_data['sticky'] = $this->sticky ? 1 : 0;\n\n /* END: Query Data Population */\n try {\n /* BEGIN: Construct the parameterized query */\n $query = $forUpdate\n ? $this->getUpdateQuery($this->_update_token, $includePassword)\n : $this->getInsertQuery($this->_update_token, $includePassword);\n /* END: Construct the parameterized query */\n\n /* BEGIN: Execute the query */\n if ($forUpdate) {\n /* $rowCount = */\n $this->_pdo->execute($query, $update_data);\n } else {\n // NOTE: There may be a better way to do this (atomicity issue) ?\n $new_user_id = $this->_pdo->insert($query, $update_data);\n // New User Creation -- assign the new user id to the associated roles\n $this->_id = $new_user_id;\n }\n } catch (Exception $e) {\n throw new Exception(\"Exception occured while inserting / updating. UpdateToken: [{$this->_update_token}] Query: [$query] data: [{$this->arrayToString($update_data)}]\", null, $e);\n }\n /* END: Execute the query */\n\n /* BEGIN: Update Token Information */\n if ($this->_update_token) {\n // Set token to expire in 30 days from now...\n $this->_pdo->execute(\n 'UPDATE Users SET token_expiration=DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE id=:id',\n array('id' => $this->_id)\n );\n $this->_update_token = false;\n }\n /* END: Update Token Information */\n\n /* BEGIN: ACL data processing */\n\n // REMOVE: existing user -> acl relations\n $this->_pdo->execute(\n 'DELETE FROM user_acls WHERE user_id = :user_id',\n array('user_id' => $this->_id)\n );\n\n // REMOVE: existing user_acl_group_by_parameter records for this user.\n $this->_pdo->execute(\n 'DELETE FROM moddb.user_acl_group_by_parameters WHERE user_id = :user_id',\n array('user_id' => $this->_id)\n );\n\n // ADD: current user -> acl relations\n foreach ($this->_acls as $acl) {\n if (null !== $acl->getAclId()) {\n $params = array(\n ':user_id' => $this->_id,\n ':acl_id' => $acl->getAclId()\n );\n\n // Add the appropriate user_acl record.\n $this->_pdo->execute(\n 'INSERT INTO user_acls(user_id, acl_id) VALUES(:user_id, :acl_id)',\n $params\n );\n\n // Add the appropriate user_acl_group_by_parameters record.\n $this->_pdo->execute(\n self::UAGBP_INSERT_QUERY,\n $params\n );\n\n }\n }\n /* END: ACL data processing */\n\n // Retrieve this users most privileged acl as it will be used to set the\n // the _active_role property.\n $mostPrivilegedAcl = Acls::getMostPrivilegedAcl($this);\n\n if (!isset($mostPrivilegedAcl)) {\n throw new Exception('Unable to determine this users most privileged acl. There may be a problem with the state of the database.');\n }\n\n $timestampData = $this->_pdo->query(\n \"SELECT time_created, time_last_updated, password_last_updated\n FROM Users\n WHERE id=:id\",\n array('id' => $this->_id)\n );\n\n $this->_timeCreated = $timestampData[0]['time_created'];\n $this->_timeUpdated = $timestampData[0]['time_last_updated'];\n $this->_timePasswordUpdated = $timestampData[0]['password_last_updated'];\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function GetKeyMaps($objectclass)\n {\n // TODO: if a php memory error occurs within this method, uncomment this block to debug\n /*\n * if (Phreezer::$cnt++ > 500)\n * {\n * throw new Exception(\"A sanity limit was exceeded when recursing KeyMaps for `$objectclass`. Please check your Map for circular joins.\");\n * }\n * //\n */\n\n // this is a temporary ram cache\n $kms = $this->_mapCache->Get($objectclass . \"KeyMaps\");\n if ($kms) {\n return $kms;\n }\n\n $this->IncludeModel($objectclass);\n if (! class_exists($objectclass . \"Map\")) {\n throw new Exception(\"Class '\" . $objectclass . \"Map' is not defined.\");\n }\n\n $kms = call_user_func(array (\n $objectclass . \"Map\",\n \"GetKeyMaps\"\n ));\n $this->_mapCache->Set($objectclass . \"KeyMaps\", $kms);\n return $kms;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function gridSaveColumnConfigAction(Request $request): JsonResponse\n {\n $asset = Asset::getById((int) $request->get('id'));\n\n if (!$asset) {\n throw $this->createNotFoundException();\n }\n\n if ($asset->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');\n\n $searchType = $request->get('searchType');\n $type = $request->get('type');\n\n // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();\n $gridConfigData['context'] = $context;\n unset($gridConfigData['settings']['isShared']);\n\n $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);\n\n $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = null;\n if ($gridConfigId) {\n $gridConfig = GridConfig::getById($gridConfigId);\n }\n\n if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess around with somebody else's configuration\");\n }\n\n $this->updateGridConfigShares($gridConfig, $metadata);\n\n if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata);\n }\n\n if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);\n $gridConfig->setType($type);\n\n $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }\n\n if ($metadata) {\n $gridConfig->setName($metadata['gridConfigName']);\n $gridConfig->setDescription($metadata['gridConfigDescription']);\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n }\n\n $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();\n\n $userId = $this->getAdminUser()->getId();\n\n $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);\n\n $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = $gridConfig->getName();\n $settings['gridConfigDescription'] = $gridConfig->getDescription();\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId();\n\n return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }\n\n throw $this->createAccessDeniedHttpException();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "private function decryptWithoutSecret(string $authenticatedCiphertext, string $password = ''): string {\n\t\t$hmacKey = $encryptionKey = $password;\n\n\t\t$parts = explode('|', $authenticatedCiphertext);\n\t\t$partCount = \\count($parts);\n\t\tif ($partCount < 3 || $partCount > 4) {\n\t\t\tthrow new Exception('Authenticated ciphertext could not be decoded.');\n\t\t}\n\n\t\t$ciphertext = $this->hex2bin($parts[0]);\n\t\t$iv = $parts[1];\n\t\t$hmac = $this->hex2bin($parts[2]);\n\n\t\tif ($partCount === 4) {\n\t\t\t$version = $parts[3];\n\t\t\tif ($version >= '2') {\n\t\t\t\t$iv = $this->hex2bin($iv);\n\t\t\t}\n\n\t\t\tif ($version === '3') {\n\t\t\t\t$keyMaterial = hash_hkdf('sha512', $password);\n\t\t\t\t$encryptionKey = substr($keyMaterial, 0, 32);\n\t\t\t\t$hmacKey = substr($keyMaterial, 32);\n\t\t\t}\n\t\t}\n\t\t$this->cipher->setPassword($encryptionKey);\n\t\t$this->cipher->setIV($iv);\n\n\t\tif (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {\n\t\t\tthrow new Exception('HMAC does not match.');\n\t\t}\n\n\t\t$result = $this->cipher->decrypt($ciphertext);\n\t\tif ($result === false) {\n\t\t\tthrow new Exception('Decryption failed');\n\t\t}\n\n\t\treturn $result;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $projectId, string $platformId, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $platform = $dbForConsole->findOne('platforms', [\n Query::equal('$id', [$platformId]),\n Query::equal('projectInternalId', [$project->getInternalId()]),\n ]);\n\n if ($platform === false || $platform->isEmpty()) {\n throw new Exception(Exception::PLATFORM_NOT_FOUND);\n }\n\n $response->dynamic($platform, Response::MODEL_PLATFORM);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function save(bool $saveDefinitionFile = true): void\n {\n if (!$this->getKey()) {\n throw new Exception('A object-brick needs a key to be saved!');\n }\n\n if ($this->isForbiddenName()) {\n throw new Exception(sprintf('Invalid key for object-brick: %s', $this->getKey()));\n }\n\n if ($this->getParentClass() && !preg_match('/^[a-zA-Z_\\x7f-\\xff\\\\\\][a-zA-Z0-9_\\x7f-\\xff\\\\\\]*$/', $this->getParentClass())) {\n throw new Exception(sprintf('Invalid parentClass value for class definition: %s',\n $this->getParentClass()));\n }\n\n $this->checkTablenames();\n $this->checkContainerRestrictions();\n\n $isUpdate = file_exists($this->getDefinitionFile());\n\n if (!$isUpdate) {\n $this->dispatchEvent(new ObjectbrickDefinitionEvent($this), ObjectbrickDefinitionEvents::PRE_ADD);\n } else {\n $this->dispatchEvent(new ObjectbrickDefinitionEvent($this), ObjectbrickDefinitionEvents::PRE_UPDATE);\n }\n\n $fieldDefinitions = $this->getFieldDefinitions();\n foreach ($fieldDefinitions as $fd) {\n if ($fd->isForbiddenName()) {\n throw new Exception(sprintf('Forbidden name used for field definition: %s', $fd->getName()));\n }\n\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\DataContainerAwareInterface) {\n $fd->preSave($this);\n }\n }\n\n $newClassDefinitions = [];\n $classDefinitionsToDelete = [];\n\n foreach ($this->classDefinitions as $cl) {\n if (!isset($cl['deleted']) || !$cl['deleted']) {\n $newClassDefinitions[] = $cl;\n } else {\n $classDefinitionsToDelete[] = $cl;\n }\n }\n\n $this->classDefinitions = $newClassDefinitions;\n\n $this->generateClassFiles($saveDefinitionFile);\n\n $cacheKey = 'objectbrick_' . $this->getKey();\n // for localized fields getting a fresh copy\n RuntimeCache::set($cacheKey, $this);\n\n $this->createContainerClasses();\n $this->updateDatabase();\n\n foreach ($fieldDefinitions as $fd) {\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\DataContainerAwareInterface) {\n $fd->postSave($this);\n }\n }\n\n if (!$isUpdate) {\n $this->dispatchEvent(new ObjectbrickDefinitionEvent($this), ObjectbrickDefinitionEvents::POST_ADD);\n } else {\n $this->dispatchEvent(new ObjectbrickDefinitionEvent($this), ObjectbrickDefinitionEvents::POST_UPDATE);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function generateChartBlob(\n $type,\n $insertion_rank,\n $start_date,\n $end_date\n ) {\n $pdo = DB::factory('database');\n\n switch ($type) {\n case 'volatile':\n $temp_file = $this->generateCachedFilename(\n $insertion_rank,\n true,\n true\n );\n $temp_file = str_replace('.png', '.xrc', $temp_file);\n\n $iq = array();\n\n if (file_exists($temp_file) == true) {\n $chart_id_config = file($temp_file);\n $iq[] = array('chart_id' => $chart_id_config[0]);\n }\n else {\n return $this->generateChartBlob(\n 'chart_pool',\n $insertion_rank['rank'],\n $start_date,\n $end_date\n );\n }\n break;\n\n case 'chart_pool':\n $iq = $pdo->query(\n \"\n SELECT chart_id\n FROM ChartPool\n WHERE user_id = :user_id\n AND insertion_rank = :insertion_rank\n \",\n array(\n 'user_id' => $this->_user_id,\n 'insertion_rank' => $insertion_rank,\n )\n );\n break;\n\n case 'cached':\n case 'report':\n $iq = $pdo->query(\n \"\n SELECT chart_id\n FROM ReportCharts\n WHERE report_id = :report_id\n AND ordering = :ordering\n \",\n array(\n 'report_id' => $insertion_rank['report_id'],\n 'ordering' => $insertion_rank['ordering'],\n )\n );\n break;\n }\n\n if (count($iq) == 0) {\n throw new \\Exception(\"Unable to target chart entry\");\n }\n\n $chart_id = $iq[0]['chart_id'];\n\n $chartoverrides = array(\n \"render_for_report\" => \"y\",\n \"start_date\" => \"$start_date\",\n \"end_date\" => \"$end_date\",\n \"format\" => 'png_inline',\n \"scale\" => 1,\n \"width\" => 800,\n \"height\" => 600,\n \"show_title\" => 'n',\n \"title\" => '',\n \"subtitle\" => '',\n \"show_filters\" => false,\n \"font_size\" => 3,\n \"show_guide_lines\" => 'y',\n \"show_gradient\" => 'n',\n \"format\" => 'png_inline'\n );\n\n $raw_png_data = $this->getChartData($chart_id, $chartoverrides);\n\n switch ($type) {\n case 'chart_pool':\n $pdo->execute(\n \"\n UPDATE moddb.ChartPool\n SET image_data = :image_data\n WHERE user_id = :user_id\n AND insertion_rank = :insertion_rank\n \",\n array(\n 'user_id' => $this->_user_id,\n 'insertion_rank' => $insertion_rank,\n 'image_data' => \"$start_date,$end_date;\"\n . $raw_png_data\n )\n );\n break;\n\n case 'volatile':\n case 'cached':\n return $raw_png_data;\n break;\n\n case 'report':\n $pdo->execute(\n \"\n UPDATE moddb.ReportCharts\n SET image_data = :image_data\n WHERE report_id = :report_id\n AND ordering = :ordering\n \",\n array(\n 'report_id' => $insertion_rank['report_id'],\n 'ordering' => $insertion_rank['ordering'],\n 'image_data' => \"$start_date,$end_date;\"\n . $raw_png_data\n )\n );\n break;\n }\n\n return $raw_png_data;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function run($args, $options) {\n Bootstrap::connect();\n osTicket::start();\n\n switch ($args['action']) {\n case 'backends':\n // List configured backends\n foreach (FileStorageBackend::allRegistered(true) as $char=>$bk) {\n print \"$char -- {$bk::$desc} ($bk)\\n\";\n }\n break;\n\n case 'list':\n // List files matching criteria\n // ORM would be nice!\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n foreach ($files as $f) {\n printf(\"% 5d %s % 8d %s % 16s %s\\n\", $f->id, $f->bk,\n $f->size, $f->created, $f->type, $f->name);\n if ($f->attrs) {\n printf(\" %s\\n\", $f->attrs);\n }\n }\n break;\n\n case 'dump':\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n try {\n $f = $files->one();\n }\n catch (DoesNotExist $e) {\n $this->fail('No file matches the given criteria');\n }\n catch (ObjectNotUnique $e) {\n $this->fail('Criteria must select exactly 1 file');\n }\n\n if ($bk = $f->open())\n $bk->passthru();\n break;\n\n case 'load':\n // Load file content from STDIN\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n try {\n $f = $files->one();\n }\n catch (DoesNotExist $e) {\n $this->fail('No file matches the given criteria');\n }\n catch (ObjectNotUnique $e) {\n $this->fail('Criteria must select exactly 1 file');\n }\n\n try {\n if ($bk = $f->open())\n $bk->unlink();\n }\n catch (Exception $e) {}\n\n if ($options['to'])\n $bk = FileStorageBackend::lookup($options['to'], $f);\n else\n // Use the system default\n $bk = AttachmentFile::getBackendForFile($f);\n\n $type = false;\n $signature = '';\n $finfo = new finfo(FILEINFO_MIME_TYPE);\n if ($options['file'] && $options['file'] != '-') {\n if (!file_exists($options['file']))\n $this->fail($options['file'].': Cannot open file');\n if (!$bk->upload($options['file']))\n $this->fail('Unable to upload file contents to backend');\n $type = $finfo->file($options['file']);\n list(, $signature) = AttachmentFile::_getKeyAndHash($options['file'], true);\n }\n else {\n $stream = fopen('php://stdin', 'rb');\n // reading from the stream will likely return an amount of\n // data different from the backend requested block size. Loop\n // until $read_size bytes are recieved.\n while (true) {\n $contents = '';\n $read_size = $bk->getBlockSize();\n while ($read_size > 0 && ($block = fread($stream, $read_size))) {\n $contents .= $block;\n $read_size -= strlen($block);\n }\n if (!$contents)\n break;\n if (!$bk->write($contents))\n $this->fail('Unable to send file contents to backend');\n if (!$type)\n $type = $finfo->buffer($contents);\n }\n if (!$bk->flush())\n $this->fail('Unable to commit file contents to backend');\n }\n\n // TODO: Update file metadata\n $f->bk = $bk->getBkChar();\n $f->created = SqlFunction::NOW();\n $f->type = $type;\n $f->signature = $signature;\n\n if (!$f->save())\n $this->fail('Unable to update file metadata');\n\n $this->stdout->write(\"Successfully saved contents\\n\");\n break;\n\n case 'migrate':\n if (!$options['to'])\n $this->fail('Please specify a target backend for migration');\n\n if (!FileStorageBackend::isRegistered($options['to']))\n $this->fail('Target backend is not installed. See `backends` action');\n\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n\n $count = 0;\n foreach ($files as $f) {\n if ($f->getBackend() == $options['to'])\n continue;\n if ($options['verbose'])\n $this->stdout->write('Migrating '.$f->name.\"\\n\");\n try {\n if (!$f->migrate($options['to']))\n $this->stderr->write('Unable to migrate '.$f->name.\"\\n\");\n else\n $count++;\n }\n catch (IOException $e) {\n $this->stderr->write('IOError: '.$e->getMessage());\n }\n }\n $this->stdout->write(\"Migrated $count files\\n\");\n break;\n\n /**\n * export\n *\n * Export file contents to a stream file. The format of the stream\n * will be a continuous stream of file information in the following\n * format:\n *\n * AFILEOF\\x1c\n *\n * Where\n * A is the version code of the export\n * \"FIL\" is the literal text 'FIL'\n * meta-length is 'V' packed header length (bytes)\n * data-length is 'V' packed data length (bytes)\n * meta is the %file record, php serialized\n * data is the raw content of the file\n * \"EOF\" is the literal text 'EOF'\n * \\x1c is an ASCII 0x1c byte (file separator)\n *\n * Options:\n * --file File to which to direct the stream output, default\n * is stdout\n */\n case 'export':\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n\n if (!$options['file'] || $options['file'] == '-')\n $options['file'] = 'php://stdout';\n\n if (!($stream = fopen($options['file'], 'wb')))\n $this->fail($options['file'].': Unable to open file for export stream');\n\n foreach ($files as $f) {\n if ($options['verbose'])\n $this->stderr->write($f->name.\"\\n\");\n\n // TODO: Log %attachment and %ticket_attachment entries\n $info = array('file' => $f->getInfo());\n $header = serialize($info);\n fwrite($stream, 'AFIL'.pack('VV', strlen($header), $f->getSize()));\n fwrite($stream, $header);\n $FS = $f->open();\n while ($block = $FS->read())\n fwrite($stream, $block);\n fwrite($stream, \"EOF\\x1c\");\n }\n fclose($stream);\n break;\n\n /**\n * import\n *\n * Import a collection of file contents exported by the `export`.\n * See the export function above for details about the stream\n * format.\n *\n * Options:\n * --file File from which to read the export stream, default\n * is stdin\n * --to Backend to receive the contents (@see `backends`)\n * --verbose Show file names while importing\n */\n case 'import':\n if (!$options['file'] || $options['file'] == '-')\n $options['file'] = 'php://stdin';\n\n if (!($stream = fopen($options['file'], 'rb')))\n $this->fail($options['file'].': Unable to open import stream');\n\n while (true) {\n // Read the file header\n // struct file_data_header {\n // char[4] marker; // Four chars, 'AFIL'\n // int lenMeta;\n // int lenData;\n // };\n if (!($header = fread($stream, 12)))\n break; // EOF\n\n list(, $mark, $hlen, $dlen) = unpack('V3', $header);\n\n // AFIL written as little-endian 4-byte int is 0x4c4946xx (LIFA),\n // where 'A' is the version code of the export\n $version = $mark & 0xff;\n if (($mark >> 8) != 0x4c4946)\n $this->fail('Bad file record');\n\n // Read the header\n $header = fread($stream, $hlen);\n if (strlen($header) != $hlen)\n $this->fail('Short read getting header info');\n\n $header = unserialize($header);\n if (!$header)\n $this->fail('Unable to decipher file header');\n\n // Find or create the file record\n $finfo = $header['file'];\n // TODO: Consider the $version code, drop columns which do\n // not exist in this database schema\n $f = AttachmentFile::lookup($finfo['id']);\n if ($f) {\n // Verify file information\n if ($f->getSize() != $finfo['size']\n || $f->getSignature() != $finfo['signature']\n ) {\n $this->fail(sprintf(\n '%s: File data does not match existing file record',\n $finfo['name']\n ));\n }\n // Drop existing file contents, if any\n try {\n if ($bk = $f->open())\n $bk->unlink();\n }\n catch (Exception $e) {}\n }\n // Create a new file\n else {\n // Bypass the AttachmentFile::create() because we do not\n // have the data to send yet.\n $f = new AttachmentFile($finfo);\n if (!$f->save(true)) {\n $this->fail(sprintf(\n '%s: Unable to create new file record',\n $finfo['name']));\n }\n }\n\n // Determine the backend to recieve the file contents\n if ($options['to']) {\n $bk = FileStorageBackend::lookup($options['to'], $f);\n }\n // Use the system default\n else {\n $bk = AttachmentFile::getBackendForFile($f);\n }\n\n if ($options['verbose'])\n $this->stdout->write('Importing '.$f->getName().\"\\n\");\n\n // Write file contents to the backend\n $md5 = hash_init('md5');\n $sha1 = hash_init('sha1');\n $written = 0;\n\n // Handle exceptions by dropping imported file contents and\n // then returning the error to the error output stream.\n try {\n while ($dlen > 0) {\n $read_size = min($dlen, $bk->getBlockSize());\n $contents = '';\n // reading from the stream will likely return an amount of\n // data different from the backend requested block size. Loop\n // until $read_size bytes are recieved.\n while ($read_size > 0 && ($block = fread($stream, $read_size))) {\n $contents .= $block;\n $read_size -= strlen($block);\n }\n if ($read_size != 0) {\n // short read\n throw new Exception(sprintf(\n '%s: Some contents are missing from the stream',\n $f->getName()\n ));\n }\n // Calculate MD5 and SHA1 hashes of the file to verify\n // contents after successfully written to backend\n if (!$bk->write($contents))\n throw new Exception(\n 'Unable to send file contents to backend');\n hash_update($md5, $contents);\n hash_update($sha1, $contents);\n $dlen -= strlen($contents);\n $written += strlen($contents);\n }\n // Some backends cannot handle flush() without a\n // corresponding write() call.\n if ($written && !$bk->flush())\n throw new Exception(\n 'Unable to commit file contents to backend');\n\n // Check the signature hash\n if ($finfo['signature']) {\n $md5 = base64_encode(hash_final($md5, true));\n $sha1 = base64_encode(hash_final($sha1, true));\n $sig = str_replace(\n array('=','+','/'),\n array('','-','_'),\n substr($sha1, 0, 16) . substr($md5, 0, 16));\n if ($sig != $finfo['signature']) {\n throw new Exception(sprintf(\n '%s: Signature verification failed',\n $f->getName()\n ));\n }\n }\n\n // Update file to record current backend\n $f->bk = $bk->getBkChar();\n if (!$f->save())\n return false;\n\n } // end try\n catch (Exception $ex) {\n if ($bk) $bk->unlink();\n $this->fail($ex->getMessage());\n }\n\n // Read file record footer\n $footer = fread($stream, 4);\n if (strlen($footer) != 4)\n $this->fail('Unable to read file EOF marker');\n list(, $footer) = unpack('N', $footer);\n // Footer should be EOF\\x1c as an int\n if ($footer != 0x454f461c)\n $this->fail('Incorrect file EOF marker');\n }\n break;\n\n case 'zip':\n // Create a temporary ZIP file\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n if (!$options['file'])\n $this->fail('Please specify zip file with `-f`');\n\n $zip = new ZipArchive();\n if (true !== ($reason = $zip->open($options['file'],\n ZipArchive::CREATE)))\n $this->fail($reason.': Unable to create zip file');\n\n foreach ($files as $f) {\n if ($options['verbose'])\n $this->stderr->write($f->name.\"\\n\");\n $info = pathinfo($f->getName());\n $name = Charset::transcode(\n sprintf('%s-%d.%s',\n $info['filename'], $f->getId(), $info['extension']),\n 'utf-8', 'cp437');\n $zip->addFromString($name, $f->getData());\n }\n $zip->close();\n break;\n\n case 'expunge':\n $files = AttachmentFile::objects();\n $this->_applyCriteria($options, $files);\n\n foreach ($files as $f) {\n // Drop associated attachment links\n $f->attachments->expunge();\n\n // Drop file contents\n if ($bk = $f->open())\n $bk->unlink();\n\n // Drop file record\n $f->delete();\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function find(string $path): IMountPoint {\n\t\t$this->setupManager->setupForPath($path);\n\t\t$path = Filesystem::normalizePath($path);\n\n\t\tif (isset($this->pathCache[$path])) {\n\t\t\treturn $this->pathCache[$path];\n\t\t}\n\n\n\n\t\tif (count($this->mounts) === 0) {\n\t\t\t$this->setupManager->setupRoot();\n\t\t\tif (count($this->mounts) === 0) {\n\t\t\t\tthrow new \\Exception(\"No mounts even after explicitly setting up the root mounts\");\n\t\t\t}\n\t\t}\n\n\t\t$current = $path;\n\t\twhile (true) {\n\t\t\t$mountPoint = $current . '/';\n\t\t\tif (isset($this->mounts[$mountPoint])) {\n\t\t\t\t$this->pathCache[$path] = $this->mounts[$mountPoint];\n\t\t\t\treturn $this->mounts[$mountPoint];\n\t\t\t} elseif ($current === '') {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t$current = dirname($current);\n\t\t\tif ($current === '.' || $current === '/') {\n\t\t\t\t$current = '';\n\t\t\t}\n\t\t}\n\n\t\tthrow new NotFoundException(\"No mount for path \" . $path . \" existing mounts (\" . count($this->mounts) .\"): \" . implode(\",\", array_keys($this->mounts)));\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getType(): string {\n $value = $this->getValue();\n\n $matches = [];\n\n if ($this->name === \"param\") {\n preg_match('/^\\s*([\\w\\|\\\\\\\\\\[\\]]+)\\s*\\$\\w+.*$/', $value, $matches);\n } elseif ($this->name === \"return\") {\n preg_match('/^\\s*([\\w\\|\\\\\\\\\\[\\]]+)\\s*$/', $value, $matches);\n }\n\n if (isset($matches[1]) === false) {\n throw new Exception(\"@$this->name doesn't contain a type or has an invalid format \\\"$value\\\"\");\n }\n\n return $matches[1];\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __call(string $method, array $args)\n {\n if (str_starts_with($method, 'get')) {\n $key = substr($method, 3, strlen($method) - 3);\n\n $idx = array_searchi($key, $this->columns);\n if ($idx !== false) {\n $correctedKey = $this->columns[$idx];\n\n return isset($this->data[$correctedKey]) ? $this->data[$correctedKey] : null;\n }\n\n throw new Exception(\"Requested data $key not available\");\n }\n\n if (str_starts_with($method, 'set')) {\n $key = substr($method, 3, strlen($method) - 3);\n $idx = array_searchi($key, $this->columns);\n\n if ($idx !== false) {\n $correctedKey = $this->columns[$idx];\n $this->data[$correctedKey] = $args[0];\n $this->markMeDirty();\n } else {\n throw new Exception(\"Requested data $key not available\");\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct()\n {\n // Enabled by default since 5.3. Still checking if someone disabled\n // manually.\n if (!extension_loaded('fileinfo')) {\n throw new \\RuntimeException('The extension \"ext/fileinfo\" must be loaded in order for this class to work.');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function objectbrickUpdateAction(Request $request, EventDispatcherInterface $eventDispatcher): JsonResponse\n {\n try {\n $key = $request->get('key');\n $title = $request->get('title');\n $group = $request->get('group');\n\n if ($request->get('task') == 'add') {\n // check for existing brick with same name with different lower/upper cases\n $list = new DataObject\\Objectbrick\\Definition\\Listing();\n $list = $list->loadNames();\n\n foreach ($list as $brickName) {\n if (strtolower($key) === strtolower($brickName)) {\n throw new \\Exception('Brick with the same name already exists (lower/upper cases may be different)');\n }\n }\n }\n\n // now we create a new definition\n $brickDef = new DataObject\\Objectbrick\\Definition();\n $brickDef->setKey($key);\n $brickDef->setTitle($title);\n $brickDef->setGroup($group);\n\n if ($request->get('values')) {\n $values = $this->decodeJson($request->get('values'));\n\n $brickDef->setParentClass($values['parentClass']);\n $brickDef->setImplementsInterfaces($values['implementsInterfaces']);\n $brickDef->setClassDefinitions($values['classDefinitions']);\n }\n\n if ($request->get('configuration')) {\n $configuration = $this->decodeJson($request->get('configuration'));\n\n $configuration['datatype'] = 'layout';\n $configuration['fieldtype'] = 'panel';\n\n $layout = DataObject\\ClassDefinition\\Service::generateLayoutTreeFromArray($configuration, true);\n $brickDef->setLayoutDefinitions($layout);\n }\n\n $event = new GenericEvent($this, [\n 'brickDefinition' => $brickDef,\n ]);\n $eventDispatcher->dispatch($event, AdminEvents::CLASS_OBJECTBRICK_UPDATE_DEFINITION);\n $brickDef = $event->getArgument('brickDefinition');\n\n $brickDef->save();\n\n return $this->adminJson(['success' => true, 'id' => $brickDef->getKey()]);\n } catch (\\Exception $e) {\n Logger::error($e->getMessage());\n\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "#[Override]\n public function prepareEndUserAnswer(Question $question, mixed $answer): mixed\n {\n if (!is_array($answer)) {\n $answer = [$answer];\n }\n\n $actors = [];\n if (is_array($answer)) {\n foreach ($answer as $actor) {\n // The \"0\" value can occur when the empty label is selected.\n if ($actor == \"0\") {\n continue;\n }\n\n $actor_parts = explode('-', $actor);\n $itemtype = getItemtypeForForeignKeyField($actor_parts[0]);\n $item_id = $actor_parts[1];\n\n // Check if the itemtype is allowed\n if (!in_array($itemtype, $this->getAllowedActorTypes())) {\n throw new Exception(\"Invalid actor type: $itemtype\");\n }\n\n // Check if the item exists\n if ($itemtype::getById($item_id) === false) {\n throw new Exception(\"Invalid actor ID: $item_id\");\n }\n\n $actors[] = [\n 'itemtype' => $itemtype,\n 'items_id' => $item_id\n ];\n }\n }\n\n if (!$this->isMultipleActors($question) && count($actors) > 1) {\n throw new Exception(\"Multiple actors are not allowed\");\n }\n\n return $actors;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getToken(string $action, string $transid, string $confirmPinInput, string $uuidTx): string\n {\n if (($action != 'void') && ($action != 'credit')) {\n $this->logger->error(\"SphereRevert getToken action needs to be void or credit. Exiting.\");\n exit;\n }\n\n // Note added the sphere_credit_void_confirm_pin in OpenEMR so can not initiate a credit\n // or void in OpenEMR without knowing this value (ie. the user will enter it in when\n // request the credit/void, which is then compared to the value (an encrypted hash) set\n // in globals).\n if (!$this->authGlobalPin->globalVerify($confirmPinInput)) {\n throw new Exception(xl('Incorrect confirmation PIN'));\n }\n\n // Note that the returnurl needs to match the returnUrl that is created in processSphereRevert() js function, so\n // if modify this, also need to modify there\n $response = $this->client->request('POST', 'token.php', [\n 'form_params' => [\n 'aggregators' => 1,\n 'aggregator1' => Sphere::AGGREGATOR_ID,\n 'custid' => $this->custid,\n 'password' => $this->custpass,\n 'returnurl' => $this->returnUrl . \"?action=\" . urlencode($action) . \"&front=\" . urlencode($this->front) . \"&uuid_tx=\" . urlencode($uuidTx) . \"&revert=1&csrf_token=\" . urlencode(CsrfUtils::collectCsrfToken(\"sphere_revert\")),\n 'action' => $action,\n 'transid' => $transid\n ]\n ]);\n $token = $response->getBody();\n\n // for testing of token, need to trim off the = at end if it exists\n $trimmedToken = trim($token, '=');\n if ((strlen($trimmedToken) == 43) && (ctype_alnum($trimmedToken))) {\n // success, so return token\n return $token;\n } else {\n // not successful, so return error message\n throw new Exception($token);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (string $bucketId, string $fileId, Response $response, Database $dbForProject, string $mode) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_READ);\n $valid = $validator->isValid($bucket->getRead());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n if ($fileSecurity && !$valid) {\n $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);\n } else {\n $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n }\n\n if ($file->isEmpty()) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);\n }\n\n $response->dynamic($file, Response::MODEL_FILE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct($params) {\n\t\tif (isset($params['host']) && isset($params['user']) && isset($params['password'])) {\n\t\t\t$this->host = $params['host'];\n\t\t\t$this->username = $params['user'];\n\t\t\t$this->password = $params['password'];\n\t\t\tif (isset($params['secure'])) {\n\t\t\t\tif (is_string($params['secure'])) {\n\t\t\t\t\t$this->secure = ($params['secure'] === 'true');\n\t\t\t\t} else {\n\t\t\t\t\t$this->secure = (bool)$params['secure'];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$this->secure = false;\n\t\t\t}\n\t\t\t$this->root = isset($params['root']) ? '/' . ltrim($params['root']) : '/';\n\t\t\t$this->port = $params['port'] ?? 21;\n\t\t\t$this->utf8Mode = isset($params['utf8']) && $params['utf8'];\n\t\t} else {\n\t\t\tthrow new \\Exception('Creating ' . self::class . ' storage failed, required parameters not set');\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function buildDelete($table, $where, array $joins = [])\n {\n\n if (!count($where)) {\n throw new \\RuntimeException('Cannot run an DELETE query without WHERE clause!');\n }\n\n $query = \"DELETE \" . self::quoteName($table) . \" FROM \" . self::quoteName($table);\n\n $this->iterator = new DBmysqlIterator($this);\n $query .= $this->iterator->analyseJoins($joins);\n $query .= \" WHERE \" . $this->iterator->analyseCrit($where);\n\n return $query;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(array $parameters)\n {\n parent::__construct('ResourceSpecifications', 'modw_aggregates', 'resourcespecsfact_by_day', array());\n\n $config = RawStatisticsConfiguration::factory();\n\n $dataTable = $this->getDataTable();\n\n // The data table is always aliased to \"agg\".\n $tables = ['agg' => $dataTable];\n\n foreach ($config->getQueryTableDefinitions('ResourceSpecifications') as $tableDef) {\n $alias = $tableDef['alias'];\n $table = new Table(new Schema($tableDef['schema']), $tableDef['name'], $alias);\n $tables[$alias] = $table;\n $this->addTable($table);\n\n $join = $tableDef['join'];\n $this->addWhereCondition(new WhereCondition(new TableField($table, $join['primaryKey']), '=', new TableField($tables[$join['foreignTableAlias']], $join['foreignKey'])));\n }\n\n $factTable = $tables['rs'];\n\n $this->setDistinct(true);\n\n if (isset($parameters['start_date']) && isset($parameters['end_date'])) {\n $startDate = date_parse_from_format('Y-m-d', $parameters['start_date']);\n $startDateTimestamp = mktime(0, 0, 0, $startDate['month'], $startDate['day'], $startDate['year']);\n\n $endDate = date_parse_from_format('Y-m-d', $parameters['end_date']);\n $endDateTimestamp = mktime(23, 59, 59, $endDate['month'], $endDate['day'], $endDate['year']);\n\n if ($startDateTimestamp === false) {\n throw new Exception('invalid \"start_date\" query parameter.');\n }\n\n if ($endDateTimestamp === false) {\n throw new Exception('invalid \"end_date\" query parameter.');\n }\n\n $startDayId = (date('Y', $startDateTimestamp) * 100000 + date('z', $startDateTimestamp) + 1);\n $endDayId = (date('Y', $endDateTimestamp) * 100000 + date('z', $endDateTimestamp) + 1);\n\n $factEndIdField = new TableField($factTable, 'end_day_id');\n $factStartIdField = new TableField($factTable, 'start_day_id');\n\n $this->addWhereCondition(new WhereCondition($factEndIdField, '>=', $startDayId));\n $this->addWhereCondition(new WhereCondition($factStartIdField, '<=', $endDayId));\n\n } else {\n throw new Exception('invalid query parameters');\n }\n\n foreach ($config->getQueryFieldDefinitions('ResourceSpecifications') as $field) {\n $alias = $field['name'];\n if (isset($field['tableAlias']) && isset($field['column'])) {\n $this->addField(new TableField($tables[$field['tableAlias']], $field['column'], $alias));\n } elseif (isset($field['formula'])) {\n $this->addField(new FormulaField($field['formula'], $alias));\n } else {\n throw new Exception(sprintf(\n 'Missing tableAlias and column or formula for \"%s\", definition: %s',\n $alias,\n json_encode($field)\n ));\n }\n $this->documentation[$alias] = $field;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function __get($name)\n {\n if ('children' === $name) {\n throw new \\RuntimeException('Starting sabre/vobject 4.0 the children property is now protected. You should use the children() method instead');\n }\n\n $matches = $this->select($name);\n if (0 === count($matches)) {\n return;\n } else {\n $firstMatch = current($matches);\n /* @var $firstMatch Property */\n $firstMatch->setIterator(new ElementList(array_values($matches)));\n\n return $firstMatch;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function create(CreateStruct $struct)\n {\n throw new \\RuntimeException('Not implemented yet.');\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function delete($id)\n {\n throw new \\RuntimeException('Not implemented yet.');\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function curl_request($url, $options = [])\n\t{\n\t\t$curl = curl_init($url);\n\t\tcurl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n\t\tcurl_setopt_array($curl, $options);\n\t\t$resp = curl_exec($curl);\n\n\t\tif ($resp == false) {\n\t\t\tthrow new Exception(curl_error($curl));\n\t\t}\n\n\t\treturn $resp;\n\t}", "smellKey": "S112", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function __set($key, $val)\n {\n if (! Phreezer::$COMPAT_VERSION_2) {\n throw new Exception(\"Unknown property: $key\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (Document $collection, Document $document, string $permission) use (&$checkPermissions, $dbForProject, $database) {\n $documentSecurity = $collection->getAttribute('documentSecurity', false);\n $validator = new Authorization($permission);\n\n $valid = $validator->isValid($collection->getPermissionsByType($permission));\n if (($permission === Database::PERMISSION_UPDATE && !$documentSecurity) || !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n if ($permission === Database::PERMISSION_UPDATE) {\n $valid = $valid || $validator->isValid($document->getUpdate());\n if ($documentSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n }\n\n $relationships = \\array_filter(\n $collection->getAttribute('attributes', []),\n fn($attribute) => $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP\n );\n\n foreach ($relationships as $relationship) {\n $related = $document->getAttribute($relationship->getAttribute('key'));\n\n if (empty($related)) {\n continue;\n }\n\n $isList = \\is_array($related) && \\array_values($related) === $related;\n\n if ($isList) {\n $relations = $related;\n } else {\n $relations = [$related];\n }\n\n $relatedCollectionId = $relationship->getAttribute('relatedCollection');\n $relatedCollection = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $relatedCollectionId)\n );\n\n foreach ($relations as &$relation) {\n if (\n \\is_array($relation)\n && \\array_values($relation) !== $relation\n && !isset($relation['$id'])\n ) {\n $relation['$id'] = ID::unique();\n $relation = new Document($relation);\n }\n if ($relation instanceof Document) {\n $current = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $relatedCollection->getInternalId(), $relation->getId())\n );\n\n if ($current->isEmpty()) {\n $type = Database::PERMISSION_CREATE;\n\n if (isset($relation['$id']) && $relation['$id'] === 'unique()') {\n $relation['$id'] = ID::unique();\n }\n } else {\n $relation->removeAttribute('$collectionId');\n $relation->removeAttribute('$databaseId');\n $relation->setAttribute('$collection', $relatedCollection->getId());\n $type = Database::PERMISSION_UPDATE;\n }\n\n $checkPermissions($relatedCollection, $relation, $type);\n }\n }\n\n if ($isList) {\n $document->setAttribute($relationship->getAttribute('key'), \\array_values($relations));\n } else {\n $document->setAttribute($relationship->getAttribute('key'), \\reset($relations));\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');\n if (!$path) {\n $path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';\n }\n $path_override = $this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path;\n\n if (!file_exists($path_override)) {\n return false;\n } else {\n file_put_contents($path_override, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($path_override)));\n }\n\n $pattern_escape_com = '#(^\\s*?\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism';\n // Check if there is already an override file, if not, we just need to copy the file\n if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n // Check if override file is writable\n $override_path = _PS_ROOT_DIR_ . '/' . $file;\n\n if ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path))) {\n throw new Exception(Context::getContext()->getTranslator()->trans('file (%s) not writable', [$override_path], 'Admin.Notifications.Error'));\n }\n\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname . 'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n $override_file = array_diff($override_file, [\"\\n\"]);\n eval(preg_replace(['#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'], [' ', 'class ' . $classname . 'OverrideOriginal' . $uniq], implode('', $override_file)));\n $override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq);\n\n $module_file = file($path_override);\n $module_file = array_diff($module_file, [\"\\n\"]);\n eval(preg_replace(['#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'], [' ', 'class ' . $classname . 'Override' . $uniq], implode('', $module_file)));\n $module_class = new ReflectionClass($classname . 'Override' . $uniq);\n\n // Check if none of the methods already exists in the override class\n foreach ($module_class->getMethods() as $method) {\n if ($override_class->hasMethod($method->getName())) {\n $method_override = $override_class->getMethod($method->getName());\n if (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.', [$method->getName(), $classname, $name[1], $version[1], $date[1]], 'Admin.Modules.Notification'));\n }\n\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden.', [$method->getName(), $classname], 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', [$method->getName(), $classname], 'Admin.Modules.Notification'));\n }\n }\n\n // Check if none of the properties already exists in the override class\n foreach ($module_class->getProperties() as $property) {\n if ($override_class->hasProperty($property->getName())) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The property %1$s in the class %2$s is already defined.', [$property->getName(), $classname], 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b' . $property->getName() . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', [$property->getName(), $classname], 'Admin.Modules.Notification'));\n }\n }\n\n foreach ($module_class->getConstants() as $constant => $value) {\n if ($override_class->hasConstant($constant)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The constant %1$s in the class %2$s is already defined.', [$constant, $classname], 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/(const\\s)\\s*(\\b' . $constant . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', [$constant, $classname], 'Admin.Modules.Notification'));\n }\n }\n\n // Insert the methods from module override in override\n $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);\n array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);\n $code = implode('', $override_file);\n\n file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));\n } else {\n $override_src = $path_override;\n\n $override_dest = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . $path;\n $dir_name = dirname($override_dest);\n\n if (!$orig_path && !is_dir($dir_name)) {\n @mkdir($dir_name, FileSystem::DEFAULT_MODE_FOLDER);\n }\n\n if (!is_writable($dir_name)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('directory (%s) not writable', [$dir_name], 'Admin.Notifications.Error'));\n }\n $module_file = file($override_src);\n $module_file = array_diff($module_file, [\"\\n\"]);\n\n if ($orig_path) {\n do {\n $uniq = uniqid();\n } while (class_exists($classname . 'OverrideOriginal_remove', false));\n eval(preg_replace(['#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'], [' ', 'class ' . $classname . 'Override' . $uniq], implode('', $module_file)));\n $module_class = new ReflectionClass($classname . 'Override' . $uniq);\n\n // For each method found in the override, prepend a comment with the module name and version\n foreach ($module_class->getMethods() as $method) {\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', [$method->getName(), $classname], 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for properties\n foreach ($module_class->getProperties() as $property) {\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b' . $property->getName() . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', [$property->getName(), $classname], 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for constants\n foreach ($module_class->getConstants() as $constant => $value) {\n $module_file = preg_replace('/(const\\s)\\s*(\\b' . $constant . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', [$constant, $classname], 'Admin.Modules.Notification'));\n }\n }\n }\n\n file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));\n\n // Re-generate the class index\n Tools::generateIndex();\n }\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct(\\stdClass $config, array $context = [])\n {\n if (!Admin::getCurrentUser()->isAdmin()) {\n throw new \\Exception('AnyGetter only allowed for admin users');\n }\n\n parent::__construct($config, $context);\n\n $this->attribute = $config->attribute ?? '';\n $this->param1 = $config->param1 ?? '';\n $this->isArrayType = $config->isArrayType ?? false;\n\n $this->forwardAttribute = $config->forwardAttribute ?? '';\n $this->forwardParam1 = $config->forwardParam1 ?? '';\n\n $this->returnLastResult = $config->returnLastResult ?? false;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public static function GetServerRootUrl()\n {\n $url = self::GetCurrentURL(false);\n $parts = explode('/', $url);\n if (count($parts) < 2) {\n throw new Exception('RequestUtil is unable to determine the server root');\n }\n\n return $parts [0] . '//' . $parts [2] . '/';\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function determineFeature(array $objectclasses, string $attr, string $dbkey, string $confkey, bool $po = false): array {\n\t\t$cr = $this->getConnection();\n\t\tif (!$cr) {\n\t\t\tthrow new \\Exception('Could not connect to LDAP');\n\t\t}\n\t\t$p = 'objectclass=';\n\t\tforeach ($objectclasses as $key => $value) {\n\t\t\t$objectclasses[$key] = $p.$value;\n\t\t}\n\t\t$maxEntryObjC = '';\n\n\t\t//how deep to dig?\n\t\t//When looking for objectclasses, testing few entries is sufficient,\n\t\t$dig = 3;\n\n\t\t$availableFeatures =\n\t\t\t$this->cumulativeSearchOnAttribute($objectclasses, $attr,\n\t\t\t\t$dig, $maxEntryObjC);\n\t\tif (is_array($availableFeatures)\n\t\t && count($availableFeatures) > 0) {\n\t\t\tnatcasesort($availableFeatures);\n\t\t\t//natcasesort keeps indices, but we must get rid of them for proper\n\t\t\t//sorting in the web UI. Therefore: array_values\n\t\t\t$this->result->addOptions($dbkey, array_values($availableFeatures));\n\t\t} else {\n\t\t\tthrow new \\Exception(self::$l->t('Could not find the desired feature'));\n\t\t}\n\n\t\t$setFeatures = $this->configuration->$confkey;\n\t\tif (is_array($setFeatures) && !empty($setFeatures)) {\n\t\t\t//something is already configured? pre-select it.\n\t\t\t$this->result->addChange($dbkey, $setFeatures);\n\t\t} elseif ($po && $maxEntryObjC !== '') {\n\t\t\t//pre-select objectclass with most result entries\n\t\t\t$maxEntryObjC = str_replace($p, '', $maxEntryObjC);\n\t\t\t$this->applyFind($dbkey, $maxEntryObjC);\n\t\t\t$this->result->addChange($dbkey, $maxEntryObjC);\n\t\t}\n\n\t\treturn $availableFeatures;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $projectId, string $type, string $locale, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $templates = $project->getAttribute('templates', []);\n $template = $templates['email.' . $type . '-' . $locale] ?? null;\n\n if (is_null($template)) {\n throw new Exception(Exception::PROJECT_TEMPLATE_DEFAULT_DELETION);\n }\n\n unset($templates['email.' . $type . '-' . $locale]);\n\n $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('templates', $templates));\n\n $response->dynamic(new Document([\n 'type' => $type,\n 'locale' => $locale,\n 'senderName' => $template['senderName'],\n 'senderEmail' => $template['senderEmail'],\n 'subject' => $template['subject'],\n 'replyTo' => $template['replyTo'],\n 'message' => $template['message']\n ]), Response::MODEL_EMAIL_TEMPLATE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "static function ($answer) {\n $version = new Version($answer);\n\n if (!str_starts_with($version->getOriginalString(), 'v')) {\n throw new RuntimeException(\n 'Development version name must start with \\'v\\'',\n );\n }\n\n if (!$version->hasPreReleaseSuffix()) {\n throw new RuntimeException(\n 'Development version must be suffixed (with \\'-dev\\', \\'-alpha1\\', ...)',\n );\n }\n\n return $version;\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (array $resources, string $projectId, Response $response, Request $request, Document $user, Database $dbForConsole) {\n $firebase = new OAuth2Firebase(\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),\n $request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'\n );\n\n $identity = $dbForConsole->findOne('identities', [\n Query::equal('provider', ['firebase']),\n Query::equal('userInternalId', [$user->getInternalId()]),\n ]);\n\n if ($identity === false || $identity->isEmpty()) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $accessToken = $identity->getAttribute('providerAccessToken');\n $refreshToken = $identity->getAttribute('providerRefreshToken');\n $accessTokenExpiry = $identity->getAttribute('providerAccessTokenExpiry');\n\n if (empty($accessToken) || empty($refreshToken) || empty($accessTokenExpiry)) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n if (App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $isExpired = new \\DateTime($accessTokenExpiry) < new \\DateTime('now');\n if ($isExpired) {\n $firebase->refreshTokens($refreshToken);\n\n $accessToken = $firebase->getAccessToken('');\n $refreshToken = $firebase->getRefreshToken('');\n\n $verificationId = $firebase->getUserID($accessToken);\n\n if (empty($verificationId)) {\n throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED, 'Another request is currently refreshing OAuth token. Please try again.');\n }\n\n $identity = $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$firebase->getAccessTokenExpiry('')));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n }\n\n // Get Service Account\n if ($identity->getAttribute('secrets')) {\n $serviceAccount = $identity->getAttribute('secrets');\n } else {\n $firebase->cleanupServiceAccounts($accessToken, $projectId);\n $serviceAccount = $firebase->createServiceAccount($accessToken, $projectId);\n $identity = $identity\n ->setAttribute('secrets', json_encode($serviceAccount));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n }\n\n $firebase = new Firebase($serviceAccount);\n\n try {\n $report = $firebase->report($resources);\n } catch (\\Exception $e) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Source Error: ' . $e->getMessage());\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_OK)\n ->dynamic(new Document($report), Response::MODEL_MIGRATION_REPORT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function create(IShare $share): IShare {\n\t\t$shareWith = $share->getSharedWith();\n\t\t/*\n\t\t * Check if file is not already shared with the remote user\n\t\t */\n\t\t$alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_EMAIL, $share->getNode(), 1, 0);\n\t\tif (!empty($alreadyShared)) {\n\t\t\t$message = 'Sharing %1$s failed, because this item is already shared with the account %2$s';\n\t\t\t$message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with the account %2$s', [$share->getNode()->getName(), $shareWith]);\n\t\t\t$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);\n\t\t\tthrow new \\Exception($message_t);\n\t\t}\n\n\t\t// if the admin enforces a password for all mail shares we create a\n\t\t// random password and send it to the recipient\n\t\t$password = $share->getPassword() ?: '';\n\t\t$passwordEnforced = $this->shareManager->shareApiLinkEnforcePassword();\n\t\tif ($passwordEnforced && empty($password)) {\n\t\t\t$password = $this->autoGeneratePassword($share);\n\t\t}\n\n\t\tif (!empty($password)) {\n\t\t\t$share->setPassword($this->hasher->hash($password));\n\t\t}\n\n\t\t$shareId = $this->createMailShare($share);\n\n\t\t// Sends share password to receiver when it's a permanent one (otherwise she will have to request it via the showShare UI)\n\t\t// or to owner when the password shall be given during a Talk session\n\t\tif ($this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false) === false || $share->getSendPasswordByTalk()) {\n\t\t\t$send = $this->sendPassword($share, $password);\n\t\t\tif ($passwordEnforced && $send === false) {\n\t\t\t\t$this->sendPasswordToOwner($share, $password);\n\t\t\t}\n\t\t}\n\n\t\t$this->createShareActivity($share);\n\t\t$data = $this->getRawShare($shareId);\n\n\t\treturn $this->createShareObject($data);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private static function _registerAutoloader()\n {\n $autoloaderClass = __NAMESPACE__ . '\\PHPFHIRAutoloader';\n $autoloaderClassFile = __DIR__ . '/PHPFHIRAutoloader.php';\n\n if (!class_exists($autoloaderClass, false)) {\n if (!file_exists($autoloaderClassFile)) {\n throw new \\RuntimeException(sprintf(\n 'PHPFHIRAutoloader class is not defined and was not found at expected location \"%s\".',\n $autoloaderClassFile\n ));\n }\n\n require $autoloaderClassFile;\n }\n\n $autoloaderClass::register();\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function imagePath(string $appName, string $file): string {\n\t\t$cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');\n\t\t$cacheKey = $appName.'-'.$file;\n\t\tif ($key = $cache->get($cacheKey)) {\n\t\t\treturn $key;\n\t\t}\n\n\t\t// Read the selected theme from the config file\n\t\t$theme = \\OC_Util::getTheme();\n\n\t\t//if a theme has a png but not an svg always use the png\n\t\t$basename = substr(basename($file), 0, -4);\n\n\t\ttry {\n\t\t\t$appPath = $this->getAppManager()->getAppPath($appName);\n\t\t} catch (AppPathNotFoundException $e) {\n\t\t\tif ($appName === 'core' || $appName === '') {\n\t\t\t\t$appName = 'core';\n\t\t\t\t$appPath = false;\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException('image not found: image: ' . $file . ' webroot: ' . \\OC::$WEBROOT . ' serverroot: ' . \\OC::$SERVERROOT);\n\t\t\t}\n\t\t}\n\n\t\t// Check if the app is in the app folder\n\t\t$path = '';\n\t\t$themingEnabled = $this->config->getSystemValueBool('installed', false) && $this->getAppManager()->isEnabledForUser('theming');\n\t\t$themingImagePath = false;\n\t\tif ($themingEnabled) {\n\t\t\t$themingDefaults = \\OC::$server->get('ThemingDefaults');\n\t\t\tif ($themingDefaults instanceof ThemingDefaults) {\n\t\t\t\t$themingImagePath = $themingDefaults->replaceImagePath($appName, $file);\n\t\t\t}\n\t\t}\n\n\t\tif (file_exists(\\OC::$SERVERROOT . \"/themes/$theme/apps/$appName/img/$file\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/apps/$appName/img/$file\";\n\t\t} elseif (!file_exists(\\OC::$SERVERROOT . \"/themes/$theme/apps/$appName/img/$basename.svg\")\n\t\t\t&& file_exists(\\OC::$SERVERROOT . \"/themes/$theme/apps/$appName/img/$basename.png\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/apps/$appName/img/$basename.png\";\n\t\t} elseif (!empty($appName) and file_exists(\\OC::$SERVERROOT . \"/themes/$theme/$appName/img/$file\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/$appName/img/$file\";\n\t\t} elseif (!empty($appName) and (!file_exists(\\OC::$SERVERROOT . \"/themes/$theme/$appName/img/$basename.svg\")\n\t\t\t&& file_exists(\\OC::$SERVERROOT . \"/themes/$theme/$appName/img/$basename.png\"))) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/$appName/img/$basename.png\";\n\t\t} elseif (file_exists(\\OC::$SERVERROOT . \"/themes/$theme/core/img/$file\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/core/img/$file\";\n\t\t} elseif (!file_exists(\\OC::$SERVERROOT . \"/themes/$theme/core/img/$basename.svg\")\n\t\t\t&& file_exists(\\OC::$SERVERROOT . \"/themes/$theme/core/img/$basename.png\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/core/img/$basename.png\";\n\t\t} elseif ($themingEnabled && $themingImagePath) {\n\t\t\t$path = $themingImagePath;\n\t\t} elseif ($appPath && file_exists($appPath . \"/img/$file\")) {\n\t\t\t$path = $this->getAppManager()->getAppWebPath($appName) . \"/img/$file\";\n\t\t} elseif ($appPath && !file_exists($appPath . \"/img/$basename.svg\")\n\t\t\t&& file_exists($appPath . \"/img/$basename.png\")) {\n\t\t\t$path = $this->getAppManager()->getAppWebPath($appName) . \"/img/$basename.png\";\n\t\t} elseif (!empty($appName) and file_exists(\\OC::$SERVERROOT . \"/$appName/img/$file\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/$appName/img/$file\";\n\t\t} elseif (!empty($appName) and (!file_exists(\\OC::$SERVERROOT . \"/$appName/img/$basename.svg\")\n\t\t\t\t&& file_exists(\\OC::$SERVERROOT . \"/$appName/img/$basename.png\"))) {\n\t\t\t$path = \\OC::$WEBROOT . \"/$appName/img/$basename.png\";\n\t\t} elseif (file_exists(\\OC::$SERVERROOT . \"/core/img/$file\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/core/img/$file\";\n\t\t} elseif (!file_exists(\\OC::$SERVERROOT . \"/core/img/$basename.svg\")\n\t\t\t&& file_exists(\\OC::$SERVERROOT . \"/core/img/$basename.png\")) {\n\t\t\t$path = \\OC::$WEBROOT . \"/themes/$theme/core/img/$basename.png\";\n\t\t}\n\n\t\tif ($path !== '') {\n\t\t\t$cache->set($cacheKey, $path);\n\t\t\treturn $path;\n\t\t}\n\n\t\tthrow new RuntimeException('image not found: image:' . $file . ' webroot:' . \\OC::$WEBROOT . ' serverroot:' . \\OC::$SERVERROOT);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(array $properties = [])\n {\n foreach ($properties as $property => $value) {\n if ($this->propertyExists($property)) {\n $this->{$property} = $value;\n } else {\n throw new Exception(\"Property ${$property} does not exist on \" . get_class($this));\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function stopMessengerWorkers(): void\n {\n $app = new Application(Pimcore::getKernel());\n $app->setAutoExit(false);\n\n $input = new ArrayInput([\n 'command' => 'messenger:stop-workers',\n '--no-ansi' => null,\n '--no-interaction' => null,\n '--ignore-maintenance-mode' => null,\n ]);\n\n $output = new BufferedOutput();\n $return = $app->run($input, $output);\n\n if (0 !== $return) {\n // return the output, don't use if you used NullOutput()\n $content = $output->fetch();\n\n throw new Exception('Running messenger:stop-workers failed, output was: ' . $content);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function setUp(): void\n {\n $data = @file_get_contents(__DIR__ . '/../../resources/docker/docker-compose.yml');\n\n if ($data === false) {\n throw new Exception('Failed to read compose file');\n }\n\n $this->object = new Compose($data);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function theCaldavResponseShouldContainAPropertyWithHrefValue(\n\t\tstring $key,\n\t\tstring $value,\n\t): void {\n\t\t/** @var \\Sabre\\DAV\\Xml\\Response\\MultiStatus $multiStatus */\n\t\t$multiStatus = $this->responseXml['value'];\n\t\t$responses = $multiStatus->getResponses()[0]->getResponseProperties();\n\t\tif (!isset($responses[200])) {\n\t\t\tthrow new \\Exception(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Expected code 200 got [%s]',\n\t\t\t\t\timplode(',', array_keys($responses)),\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\t$props = $responses[200];\n\t\tif (!array_key_exists($key, $props)) {\n\t\t\tthrow new \\Exception(\"Cannot find property \\\"$key\\\"\");\n\t\t}\n\n\t\t$actualValue = $props[$key]->getHref();\n\t\tif ($actualValue !== $value) {\n\t\t\tthrow new \\Exception(\"Property \\\"$key\\\" found with value \\\"$actualValue\\\", expected \\\"$value\\\"\");\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function Create()\n {\n try {\n $json = json_decode(RequestUtil::GetBody());\n\n if (!$json) {\n throw new Exception('The request body does not contain valid JSON');\n }\n\n $onsiteportalactivity = new OnsitePortalActivity($this->Phreezer);\n\n // TODO: any fields that should not be inserted by the user should be commented out\n\n // this is an auto-increment. uncomment if updating is allowed\n // $onsiteportalactivity->Id = $this->SafeGetVal($json, 'id');\n\n $onsiteportalactivity->Date = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'date')));\n\n // only allow patient to create onsiteportalactivity about themself\n if (!empty($GLOBALS['bootstrap_pid'])) {\n $onsiteportalactivity->PatientId = $GLOBALS['bootstrap_pid'];\n } else {\n $onsiteportalactivity->PatientId = $this->SafeGetVal($json, 'patientId');\n }\n\n $onsiteportalactivity->Activity = $this->SafeGetVal($json, 'activity');\n $onsiteportalactivity->RequireAudit = $this->SafeGetVal($json, 'requireAudit');\n $onsiteportalactivity->PendingAction = $this->SafeGetVal($json, 'pendingAction');\n $onsiteportalactivity->ActionTaken = $this->SafeGetVal($json, 'actionTaken');\n $onsiteportalactivity->Status = $this->SafeGetVal($json, 'status');\n $onsiteportalactivity->Narrative = $this->SafeGetVal($json, 'narrative');\n $onsiteportalactivity->TableAction = $this->SafeGetVal($json, 'tableAction');\n $onsiteportalactivity->TableArgs = $this->SafeGetVal($json, 'tableArgs');\n $onsiteportalactivity->ActionUser = $this->SafeGetVal($json, 'actionUser');\n $onsiteportalactivity->ActionTakenTime = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'actionTakenTime')));\n $onsiteportalactivity->Checksum = $this->SafeGetVal($json, 'checksum');\n\n $onsiteportalactivity->Validate();\n $errors = $onsiteportalactivity->GetValidationErrors();\n\n if (count($errors) > 0) {\n $this->RenderErrorJSON('Please check the form for errors', $errors);\n } else {\n $onsiteportalactivity->Save();\n $this->RenderJSON($onsiteportalactivity, $this->JSONPCallback(), true, $this->SimpleObjectParams());\n }\n } catch (Exception $ex) {\n $this->RenderExceptionJSON($ex);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $userId, string $email, string $url, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Locale $locale, Event $events, Mail $mails) {\n\n if (empty(App::getEnv('_APP_SMTP_HOST'))) {\n throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP disabled');\n }\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n\n $result = $dbForProject->findOne('users', [Query::equal('email', [$email])]);\n if ($result !== false && !$result->isEmpty()) {\n $user->setAttributes($result->getArrayCopy());\n } else {\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0) {\n $total = $dbForProject->count('users', max: APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n throw new Exception(Exception::USER_COUNT_EXCEEDED);\n }\n }\n\n // Makes sure this email is not already used in another identity\n $identityWithMatchingEmail = $dbForProject->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n if ($identityWithMatchingEmail !== false && !$identityWithMatchingEmail->isEmpty()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n $userId = $userId === 'unique()' ? ID::unique() : $userId;\n\n $user->setAttributes([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => $email,\n 'emailVerification' => false,\n 'status' => true,\n 'password' => null,\n 'hash' => Auth::DEFAULT_ALGO,\n 'hashOptions' => Auth::DEFAULT_ALGO_OPTIONS,\n 'passwordUpdate' => null,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => implode(' ', [$userId, $email]),\n 'accessedAt' => DateTime::now(),\n ]);\n\n $user->removeAttribute('$internalId');\n Authorization::skip(fn () => $dbForProject->createDocument('users', $user));\n }\n\n $loginSecret = Auth::tokenGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), Auth::TOKEN_EXPIRATION_CONFIRM));\n\n $token = new Document([\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'type' => Auth::TOKEN_TYPE_MAGIC_URL,\n 'secret' => Auth::hash($loginSecret), // One way hash encryption to protect DB leak\n 'expire' => $expire,\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n ]);\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $token = $dbForProject->createDocument('tokens', $token\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n if (empty($url)) {\n $url = $request->getProtocol() . '://' . $request->getHostname() . '/auth/magic-url';\n }\n\n $url = Template::parseURL($url);\n $url['query'] = Template::mergeQuery(((isset($url['query'])) ? $url['query'] : ''), ['userId' => $user->getId(), 'secret' => $loginSecret, 'expire' => $expire, 'project' => $project->getId()]);\n $url = Template::unParseURL($url);\n\n $body = $locale->getText(\"emails.magicSession.body\");\n $subject = $locale->getText(\"emails.magicSession.subject\");\n $customTemplate = $project->getAttribute('templates', [])['email.magicSession-' . $locale->default] ?? [];\n\n $message = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-inner-base.tpl');\n $message->setParam('{{body}}', $body);\n $body = $message->render();\n\n $smtp = $project->getAttribute('smtp', []);\n $smtpEnabled = $smtp['enabled'] ?? false;\n\n $senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);\n $senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');\n $replyTo = \"\";\n\n if ($smtpEnabled) {\n if (!empty($smtp['senderEmail'])) {\n $senderEmail = $smtp['senderEmail'];\n }\n if (!empty($smtp['senderName'])) {\n $senderName = $smtp['senderName'];\n }\n if (!empty($smtp['replyTo'])) {\n $replyTo = $smtp['replyTo'];\n }\n\n $mails\n ->setSmtpHost($smtp['host'] ?? '')\n ->setSmtpPort($smtp['port'] ?? '')\n ->setSmtpUsername($smtp['username'] ?? '')\n ->setSmtpPassword($smtp['password'] ?? '')\n ->setSmtpSecure($smtp['secure'] ?? '');\n\n if (!empty($customTemplate)) {\n if (!empty($customTemplate['senderEmail'])) {\n $senderEmail = $customTemplate['senderEmail'];\n }\n if (!empty($customTemplate['senderName'])) {\n $senderName = $customTemplate['senderName'];\n }\n if (!empty($customTemplate['replyTo'])) {\n $replyTo = $customTemplate['replyTo'];\n }\n\n $body = $customTemplate['message'] ?? '';\n $subject = $customTemplate['subject'] ?? $subject;\n }\n\n $mails\n ->setSmtpReplyTo($replyTo)\n ->setSmtpSenderEmail($senderEmail)\n ->setSmtpSenderName($senderName);\n }\n\n $emailVariables = [\n 'subject' => $subject,\n 'hello' => $locale->getText(\"emails.magicSession.hello\"),\n 'body' => $body,\n 'footer' => $locale->getText(\"emails.magicSession.footer\"),\n 'thanks' => $locale->getText(\"emails.magicSession.thanks\"),\n 'signature' => $locale->getText(\"emails.magicSession.signature\"),\n 'direction' => $locale->getText('settings.direction'),\n 'bg-body' => '#f7f7f7',\n 'bg-content' => '#ffffff',\n 'text-content' => '#000000',\n /* {{user}} ,{{team}}, {{project}} and {{redirect}} are required in the templates */\n 'user' => '',\n 'team' => '',\n 'project' => $project->getAttribute('name'),\n 'redirect' => $url\n ];\n\n $mails\n ->setSubject($subject)\n ->setBody($body)\n ->setVariables($emailVariables)\n ->setRecipient($email)\n ->trigger();\n\n $events->setPayload(\n $response->output(\n $token->setAttribute('secret', $loginSecret),\n Response::MODEL_TOKEN\n )\n );\n\n // Hide secret for clients\n $token->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $loginSecret : '');\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($token, Response::MODEL_TOKEN)\n ;\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "#[Route('/show/{uuid}', name: 'show_file')]\n public function showFile(\n File $file,\n Request $request,\n LoggerInterface $logger,\n FilesystemOperator $fileStorage,\n ): BinaryFileResponse {\n try {\n $variant = $request->query->get('variant');\n $filename = $file->getFilename();\n $documentType = $file->getDocumentType();\n $variantNames = ImageManipulationHandler::getVariantNames($filename);\n\n if ('thumb' == $variant && $fileStorage->fileExists($variantNames[ImageManipulationHandler::SUFFIX_THUMB])) {\n $filename = $variantNames[ImageManipulationHandler::SUFFIX_THUMB];\n } elseif ($fileStorage->fileExists($variantNames[ImageManipulationHandler::SUFFIX_RESIZE])) {\n $filename = $variantNames[ImageManipulationHandler::SUFFIX_RESIZE];\n }\n if (!$fileStorage->fileExists($filename)) {\n throw new \\Exception('File \"'.$filename.'\" not found');\n }\n $tmpFilepath = $this->getParameter('uploads_tmp_dir').$filename;\n $bucketFilepath = $this->getParameter('url_bucket').'/'.$filename;\n $content = file_get_contents($bucketFilepath);\n file_put_contents($tmpFilepath, $content);\n $file = new SymfonyFile($tmpFilepath);\n\n if (DocumentType::EXPORT === $documentType) {\n return (new BinaryFileResponse($file))->setContentDisposition(\n ResponseHeaderBag::DISPOSITION_INLINE,\n $file->getFilename()\n );\n }\n\n return new BinaryFileResponse($file);\n } catch (\\Throwable $exception) {\n $logger->error($exception->getMessage());\n }\n\n return new BinaryFileResponse(\n new SymfonyFile($this->getParameter('images_dir').'image-404.png'),\n );\n }", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "private function checkCurlResult($ch, $result) {\n\t\tif ($result === false) {\n\t\t\t$error = curl_error($ch);\n\t\t\tcurl_close($ch);\n\t\t\tthrow new \\Exception($error);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function unzip($zipFile)\n {\n $zip = new ZipArchive();\n\n if ($zip->open($zipFile) === true) {\n $zip->extractTo(storage_path('app') . '/tempDir');\n $zipFolderName = trim($zip->getNameIndex(0), '/');\n $zip->close();\n\n if (strpos($zipFolderName, '.')) {\n return '';\n }\n\n return $zipFolderName;\n }\n\n throw new Exception('Cannot read the zip file');\n }", "smellKey": "S112", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public static function formatClinicalRules(array $results)\n {\n $formattedResults = array();\n foreach ($results as $result) {\n if ($result instanceof RsResultIF) {\n $formattedResults [] = $result->format();\n } else {\n throw new Exception(\"Result must be an instance of RsResultIF\");\n }\n }\n\n return $formattedResults;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct() {\n\t\t$pow_2_53 = (float)self::POW_2_53_MINUS_1 + 1.0;\n\t\tif ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {\n\t\t\tthrow new \\RuntimeException(\n\t\t\t\t'This class assumes floats to be double precision or \"better\".'\n\t\t\t);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function addOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');\n if (!$path) {\n $path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';\n }\n $path_override = $this->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path;\n\n if (!file_exists($path_override)) {\n return false;\n } else {\n file_put_contents($path_override, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($path_override)));\n }\n\n $pattern_escape_com = '#(^\\s*?\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism';\n // Check if there is already an override file, if not, we just need to copy the file\n if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n // Check if override file is writable\n $override_path = _PS_ROOT_DIR_ . '/' . $file;\n\n if ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path))) {\n throw new Exception(Context::getContext()->getTranslator()->trans('file (%s) not writable', array($override_path), 'Admin.Notifications.Error'));\n }\n\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname . 'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n $override_file = array_diff($override_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class ' . $classname . 'OverrideOriginal' . $uniq), implode('', $override_file)));\n $override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq);\n\n $module_file = file($path_override);\n $module_file = array_diff($module_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname . 'Override' . $uniq);\n\n // Check if none of the methods already exists in the override class\n foreach ($module_class->getMethods() as $method) {\n if ($override_class->hasMethod($method->getName())) {\n $method_override = $override_class->getMethod($method->getName());\n if (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.', array($method->getName(), $classname, $name[1], $version[1], $date[1]), 'Admin.Modules.Notification'));\n }\n\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Check if none of the properties already exists in the override class\n foreach ($module_class->getProperties() as $property) {\n if ($override_class->hasProperty($property->getName())) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The property %1$s in the class %2$s is already defined.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b' . $property->getName() . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n foreach ($module_class->getConstants() as $constant => $value) {\n if ($override_class->hasConstant($constant)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The constant %1$s in the class %2$s is already defined.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/(const\\s)\\s*(\\b' . $constant . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Insert the methods from module override in override\n $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);\n array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);\n $code = implode('', $override_file);\n\n file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));\n } else {\n $override_src = $path_override;\n\n $override_dest = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . $path;\n $dir_name = dirname($override_dest);\n\n if (!$orig_path && !is_dir($dir_name)) {\n @mkdir($dir_name, FileSystem::DEFAULT_MODE_FOLDER);\n }\n\n if (!is_writable($dir_name)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('directory (%s) not writable', array($dir_name), 'Admin.Notifications.Error'));\n }\n $module_file = file($override_src);\n $module_file = array_diff($module_file, array(\"\\n\"));\n\n if ($orig_path) {\n do {\n $uniq = uniqid();\n } while (class_exists($classname . 'OverrideOriginal_remove', false));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override' . $uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname . 'Override' . $uniq);\n\n // For each method found in the override, prepend a comment with the module name and version\n foreach ($module_class->getMethods() as $method) {\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b' . $method->getName() . '\\b))/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for properties\n foreach ($module_class->getProperties() as $property) {\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b' . $property->getName() . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for constants\n foreach ($module_class->getConstants() as $constant => $value) {\n $module_file = preg_replace('/(const\\s)\\s*(\\b' . $constant . '\\b)/ism', \"/*\\n * module: \" . $this->name . \"\\n * date: \" . date('Y-m-d H:i:s') . \"\\n * version: \" . $this->version . \"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n }\n }\n\n file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));\n\n // Re-generate the class index\n Tools::generateIndex();\n }\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function (string $functionId, string $body, bool $async, string $path, string $method, array $headers, Response $response, Document $project, Database $dbForProject, Document $user, Event $events, Stats $usage, string $mode, Func $queueForFunctions, Reader $geodb) {\n\n $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($function->isEmpty() || (!$function->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $version = $function->getAttribute('version', 'v2');\n $runtimes = Config::getParam($version === 'v2' ? 'runtimes-v2' : 'runtimes', []);\n\n $runtime = (isset($runtimes[$function->getAttribute('runtime', '')])) ? $runtimes[$function->getAttribute('runtime', '')] : null;\n\n if (\\is_null($runtime)) {\n throw new Exception(Exception::FUNCTION_RUNTIME_UNSUPPORTED, 'Runtime \"' . $function->getAttribute('runtime', '') . '\" is not supported');\n }\n\n $deployment = Authorization::skip(fn () => $dbForProject->getDocument('deployments', $function->getAttribute('deployment', '')));\n\n if ($deployment->getAttribute('resourceId') !== $function->getId()) {\n throw new Exception(Exception::DEPLOYMENT_NOT_FOUND, 'Deployment not found. Create a deployment before trying to execute a function');\n }\n\n if ($deployment->isEmpty()) {\n throw new Exception(Exception::DEPLOYMENT_NOT_FOUND, 'Deployment not found. Create a deployment before trying to execute a function');\n }\n\n /** Check if build has completed */\n $build = Authorization::skip(fn () => $dbForProject->getDocument('builds', $deployment->getAttribute('buildId', '')));\n if ($build->isEmpty()) {\n throw new Exception(Exception::BUILD_NOT_FOUND);\n }\n\n if ($build->getAttribute('status') !== 'ready') {\n throw new Exception(Exception::BUILD_NOT_READY);\n }\n\n $validator = new Authorization('execute');\n\n if (!$validator->isValid($function->getAttribute('execute'))) { // Check if user has write access to execute function\n throw new Exception(Exception::USER_UNAUTHORIZED, $validator->getDescription());\n }\n\n $jwt = ''; // initialize\n if (!$user->isEmpty()) { // If userId exists, generate a JWT for function\n $sessions = $user->getAttribute('sessions', []);\n $current = new Document();\n\n foreach ($sessions as $session) {\n /** @var Utopia\\Database\\Document $session */\n if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too\n $current = $session;\n }\n }\n\n if (!$current->isEmpty()) {\n $jwtObj = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.\n $jwt = $jwtObj->encode([\n 'userId' => $user->getId(),\n 'sessionId' => $current->getId(),\n ]);\n }\n }\n\n $headers['x-appwrite-trigger'] = 'http';\n $headers['x-appwrite-user-id'] = $user->getId() ?? '';\n $headers['x-appwrite-user-jwt'] = $jwt ?? '';\n $headers['x-appwrite-country-code'] = '';\n $headers['x-appwrite-continent-code'] = '';\n $headers['x-appwrite-continent-eu'] = 'false';\n\n $ip = $headers['x-real-ip'] ?? '';\n if (!empty($ip)) {\n $record = $geodb->get($ip);\n\n if ($record) {\n $eu = Config::getParam('locale-eu');\n\n $headers['x-appwrite-country-code'] = $record['country']['iso_code'] ?? '';\n $headers['x-appwrite-continent-code'] = $record['continent']['code'] ?? '';\n $headers['x-appwrite-continent-eu'] = (\\in_array($record['country']['iso_code'], $eu)) ? 'true' : 'false';\n }\n }\n\n $headersFiltered = [];\n foreach ($headers as $key => $value) {\n if (\\in_array(\\strtolower($key), FUNCTION_ALLOWLIST_HEADERS_REQUEST)) {\n $headersFiltered[] = ['name' => $key, 'value' => $value];\n }\n }\n\n $executionId = ID::unique();\n\n $execution = new Document([\n '$id' => $executionId,\n '$permissions' => !$user->isEmpty() ? [Permission::read(Role::user($user->getId()))] : [],\n 'functionInternalId' => $function->getInternalId(),\n 'functionId' => $function->getId(),\n 'deploymentInternalId' => $deployment->getInternalId(),\n 'deploymentId' => $deployment->getId(),\n 'trigger' => 'http', // http / schedule / event\n 'status' => $async ? 'waiting' : 'processing', // waiting / processing / completed / failed\n 'responseStatusCode' => 0,\n 'responseHeaders' => [],\n 'requestPath' => $path,\n 'requestMethod' => $method,\n 'requestHeaders' => $headersFiltered,\n 'errors' => '',\n 'logs' => '',\n 'duration' => 0.0,\n 'search' => implode(' ', [$functionId, $executionId]),\n ]);\n\n $events\n ->setParam('functionId', $function->getId())\n ->setParam('executionId', $execution->getId())\n ->setContext('function', $function);\n\n if ($async) {\n if ($function->getAttribute('logging')) {\n /** @var Document $execution */\n $execution = Authorization::skip(fn () => $dbForProject->createDocument('executions', $execution));\n }\n\n $queueForFunctions\n ->setType('http')\n ->setExecution($execution)\n ->setFunction($function)\n ->setBody($body)\n ->setHeaders($headers)\n ->setPath($path)\n ->setMethod($method)\n ->setJWT($jwt)\n ->setProject($project)\n ->setUser($user)\n ->trigger();\n\n return $response\n ->setStatusCode(Response::STATUS_CODE_ACCEPTED)\n ->dynamic($execution, Response::MODEL_EXECUTION);\n }\n\n $durationStart = \\microtime(true);\n\n $vars = [];\n\n // V2 vars\n if ($version === 'v2') {\n $vars = \\array_merge($vars, [\n 'APPWRITE_FUNCTION_TRIGGER' => $headers['x-appwrite-trigger'] ?? '',\n 'APPWRITE_FUNCTION_DATA' => $body ?? '',\n 'APPWRITE_FUNCTION_USER_ID' => $headers['x-appwrite-user-id'] ?? '',\n 'APPWRITE_FUNCTION_JWT' => $headers['x-appwrite-user-jwt'] ?? ''\n ]);\n }\n\n // Shared vars\n foreach ($function->getAttribute('varsProject', []) as $var) {\n $vars[$var->getAttribute('key')] = $var->getAttribute('value', '');\n }\n\n // Function vars\n foreach ($function->getAttribute('vars', []) as $var) {\n $vars[$var->getAttribute('key')] = $var->getAttribute('value', '');\n }\n\n // Appwrite vars\n $vars = \\array_merge($vars, [\n 'APPWRITE_FUNCTION_ID' => $functionId,\n 'APPWRITE_FUNCTION_NAME' => $function->getAttribute('name'),\n 'APPWRITE_FUNCTION_DEPLOYMENT' => $deployment->getId(),\n 'APPWRITE_FUNCTION_PROJECT_ID' => $project->getId(),\n 'APPWRITE_FUNCTION_RUNTIME_NAME' => $runtime['name'] ?? '',\n 'APPWRITE_FUNCTION_RUNTIME_VERSION' => $runtime['version'] ?? '',\n ]);\n\n /** Execute function */\n $executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST'));\n try {\n $version = $function->getAttribute('version', 'v2');\n $command = $runtime['startCommand'];\n $command = $version === 'v2' ? '' : 'cp /tmp/code.tar.gz /mnt/code/code.tar.gz && nohup helpers/start.sh \"' . $command . '\"';\n $executionResponse = $executor->createExecution(\n projectId: $project->getId(),\n deploymentId: $deployment->getId(),\n body: \\strlen($body) > 0 ? $body : null,\n variables: $vars,\n timeout: $function->getAttribute('timeout', 0),\n image: $runtime['image'],\n source: $build->getAttribute('path', ''),\n entrypoint: $deployment->getAttribute('entrypoint', ''),\n version: $version,\n path: $path,\n method: $method,\n headers: $headers,\n runtimeEntrypoint: $command\n );\n\n $headersFiltered = [];\n foreach ($executionResponse['headers'] as $key => $value) {\n if (\\in_array(\\strtolower($key), FUNCTION_ALLOWLIST_HEADERS_RESPONSE)) {\n $headersFiltered[] = ['name' => $key, 'value' => $value];\n }\n }\n\n /** Update execution status */\n $status = $executionResponse['statusCode'] >= 400 ? 'failed' : 'completed';\n $execution->setAttribute('status', $status);\n $execution->setAttribute('responseStatusCode', $executionResponse['statusCode']);\n $execution->setAttribute('responseHeaders', $headersFiltered);\n $execution->setAttribute('logs', $executionResponse['logs']);\n $execution->setAttribute('errors', $executionResponse['errors']);\n $execution->setAttribute('duration', $executionResponse['duration']);\n } catch (\\Throwable $th) {\n $durationEnd = \\microtime(true);\n\n $execution\n ->setAttribute('duration', $durationEnd - $durationStart)\n ->setAttribute('status', 'failed')\n ->setAttribute('responseStatusCode', 500)\n ->setAttribute('errors', $th->getMessage() . '\\nError Code: ' . $th->getCode());\n Console::error($th->getMessage());\n }\n\n if ($function->getAttribute('logging')) {\n /** @var Document $execution */\n $execution = Authorization::skip(fn () => $dbForProject->createDocument('executions', $execution));\n }\n\n // TODO revise this later using route label\n $usage\n ->setParam('functionId', $function->getId())\n ->setParam('executions.{scope}.compute', 1)\n ->setParam('executionStatus', $execution->getAttribute('status', ''))\n ->setParam('executionTime', $execution->getAttribute('duration')); // ms\n\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n\n if (!$isPrivilegedUser && !$isAppUser) {\n $execution->setAttribute('logs', '');\n $execution->setAttribute('errors', '');\n }\n\n $headers = [];\n foreach (($executionResponse['headers'] ?? []) as $key => $value) {\n $headers[] = ['name' => $key, 'value' => $value];\n }\n\n $execution->setAttribute('responseBody', $executionResponse['body'] ?? '');\n $execution->setAttribute('responseHeaders', $headers);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($execution, Response::MODEL_EXECUTION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function handleInventoryFile()\n {\n if (isset($this->mainasset)) {\n $ext = (Request::XML_MODE === $this->inventory_format ? 'xml' : 'json');\n $items = $this->getItems();\n\n foreach ($items as $item) {\n $itemtype = $item->getType();\n if (!isset($item->fields['id']) || empty($item->fields['id'])) {\n throw new \\RuntimeException('Item ID is missing :(');\n }\n $id = $item->fields['id'];\n\n $filename = GLPI_INVENTORY_DIR . '/' . $this->conf->buildInventoryFileName($itemtype, $id, $ext);\n $subdir = dirname($filename);\n if (!is_dir($subdir)) {\n mkdir($subdir, 0755, true);\n }\n if ($this->inventory_tmpfile !== false) {\n copy($this->inventory_tmpfile, $filename);\n } elseif (isset($this->inventory_content)) {\n file_put_contents($filename, $this->inventory_content);\n }\n }\n }\n\n if ($this->inventory_tmpfile !== false && file_exists($this->inventory_tmpfile)) {\n unlink($this->inventory_tmpfile);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (string $teamId, string $membershipId, Response $response, Database $dbForProject, Event $events) {\n\n $membership = $dbForProject->getDocument('memberships', $membershipId);\n\n if ($membership->isEmpty()) {\n throw new Exception(Exception::TEAM_INVITE_NOT_FOUND);\n }\n\n if ($membership->getAttribute('teamId') !== $teamId) {\n throw new Exception(Exception::TEAM_MEMBERSHIP_MISMATCH);\n }\n\n $user = $dbForProject->getDocument('users', $membership->getAttribute('userId'));\n\n if ($user->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $team = $dbForProject->getDocument('teams', $teamId);\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n try {\n $dbForProject->deleteDocument('memberships', $membership->getId());\n } catch (AuthorizationException $exception) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (\\Exception $exception) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove membership from DB');\n }\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n if ($membership->getAttribute('confirm')) { // Count only confirmed members\n $team->setAttribute('total', \\max($team->getAttribute('total', 0) - 1, 0));\n Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team));\n }\n\n $events\n ->setParam('teamId', $team->getId())\n ->setParam('membershipId', $membership->getId())\n ->setPayload($response->output($membership, Response::MODEL_MEMBERSHIP))\n ;\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function validateDomain(Domain $domain, bool $isMainDomain): void\n {\n if (empty($domain->get())) {\n throw new Exception('Missing certificate domain.');\n }\n\n if (!$domain->isKnown() || $domain->isTest()) {\n throw new Exception('Unknown public suffix for domain.');\n }\n\n if (!$isMainDomain) {\n // TODO: Would be awesome to also support A/AAAA records here. Maybe dry run?\n\n // Validate if domain target is properly configured\n $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));\n\n if (!$target->isKnown() || $target->isTest()) {\n throw new Exception('Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.');\n }\n\n // Verify domain with DNS records\n $validator = new CNAME($target->get());\n if (!$validator->isValid($domain->get())) {\n throw new Exception('Failed to verify domain DNS records.');\n }\n } else {\n // Main domain validation\n // TODO: Would be awesome to check A/AAAA record here. Maybe dry run?\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function unzipFlat($zipfile, $destination){\n\n if(file_exists($zipfile) && filesize($zipfile)>0 && file_exists($destination)){\n\n $res = array();\n $zip = new \\ZipArchive;\n if ( $zip->open( $zipfile ) === true)\n {\n for ( $i=0; $i < $zip->numFiles; $i++ )\n {\n $entry = $zip->getNameIndex($i);\n if ( substr( $entry, -1 ) == '/' ) {continue;} // skip directories\n\n $fp = $zip->getStream( $entry );\n if (!$fp ) {\n throw new \\Exception('Unable to extract the file.');\n }else{\n $filename = $destination.USanitize::sanitizeFileName(basename($entry));//snyk SSRF\n $ofp = fopen($filename, 'w' );\n while ( ! feof( $fp ) ) {\n fwrite( $ofp, fread($fp, 8192) );\n }\n\n fclose($fp);\n fclose($ofp);\n\n $res[] = $filename;\n }\n }\n\n $zip->close();\n return $res;\n }\n else {\n return false;\n }\n }else{\n return false;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) {\n\t\tif (strpos($value,'!') !== false) {\n\t\t\tthrow new Exception('Cell coordinate must not specify a worksheet.');\n\t\t} elseif (strpos($value,':') === false) {\n\t\t\tthrow new Exception('Cell coordinate must be a range of cells.');\n\t\t} elseif (strpos($value,'$') !== false) {\n\t\t\tthrow new Exception('Cell coordinate must not be absolute.');\n\t\t}\n\t\t$value = strtoupper($value);\n\n\t\tif ($method == self::SETPRINTRANGE_OVERWRITE) {\n\t\t\tif ($index == 0) {\n\t\t\t\t$this->_printArea = $value;\n\t\t\t} else {\n\t\t\t\t$printAreas = explode(',',$this->_printArea);\n\t\t\t\tif($index < 0) {\n\t\t\t\t\t$index = count($printAreas) - abs($index) + 1;\n\t\t\t\t}\n\t\t\t\tif (($index <= 0) || ($index > count($printAreas))) {\n\t\t \t\tthrow new Exception('Invalid index for setting print range.');\n\t\t\t\t}\n\t\t\t\t$printAreas[$index-1] = $value;\n\t\t\t\t$this->_printArea = implode(',',$printAreas);\n\t\t\t}\n\t\t} elseif($method == self::SETPRINTRANGE_INSERT) {\n\t\t\tif ($index == 0) {\n\t\t\t\t$this->_printArea .= ($this->_printArea == '') ? $value : ','.$value;\n\t\t\t} else {\n\t\t\t\t$printAreas = explode(',',$this->_printArea);\n\t\t\t\tif($index < 0) {\n\t\t\t\t\t$index = abs($index) - 1;\n\t\t\t\t}\n\t\t\t\tif ($index > count($printAreas)) {\n\t\t \t\tthrow new Exception('Invalid index for setting print range.');\n\t\t\t\t}\n\t\t\t\t$printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index));\n\t\t\t\t$this->_printArea = implode(',',$printAreas);\n\t\t\t}\n\t\t} else {\n \t\tthrow new Exception('Invalid method for setting print range.');\n\t\t}\n\n \treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function (array $queries, string $search, Response $response, Database $dbForConsole) {\n\n $queries = Query::parseQueries($queries);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $projectId = $cursor->getValue();\n $cursorDocument = $dbForConsole->getDocument('projects', $projectId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Project '{$projectId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $response->dynamic(new Document([\n 'projects' => $dbForConsole->find('projects', $queries),\n 'total' => $dbForConsole->count('projects', $filterQueries, APP_LIMIT_COUNT),\n ]), Response::MODEL_PROJECT_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function Login($username, $password)\n {\n // for backwards compatibility with Phreeze 2x, look in multiple places for the AccountCriteria class\n if (! class_exists(\"AccountCriteria\")) {\n @include_once(\"Model/AccountCriteria.php\");\n }\n\n if (! class_exists(\"AccountCriteria\")) {\n @include_once(\"Model/DAO/AccountCriteria.php\");\n }\n\n if (! class_exists(\"AccountCriteria\")) {\n throw new Exception(\"Unable to locate AccountCriteria class.\");\n }\n\n if ($username == \"\" || $password == \"\") {\n return false;\n }\n\n $this->_phreezer->Observe(\"AuthAccount.Login Searching For Matching Account...\");\n\n $criteria = new AccountCriteria();\n // set both the name and the _Equals properties for backwards compatibility\n if (property_exists($criteria, 'Username')) {\n $criteria->Username = $username;\n }\n\n $criteria->Username_Equals = $username;\n if (property_exists($criteria, 'Password')) {\n $criteria->Password = base64_encode(crypt($password, $username));\n }\n\n $criteria->Password_Equals = base64_encode(crypt($password, $username));\n\n $ds = $this->_phreezer->Query(\"Account\", $criteria);\n\n // we have to clear the cache, this resolves an issue where logging in repeatedly\n // will retain the same cached child objects\n $this->ClearCache();\n\n if ($account = $ds->Next()) {\n // we can't do $this = $account, so instead just clone all the properties:\n $this->LoadFromObject($account);\n $this->GetRole(); // this triggers the role to load so it will be cached\n\n // we need to update the login date and count\n // $this->LastLogin = date('Y-m-d H:i:s');\n // $this->LoginCount++;\n // $this->Save();\n\n return true;\n } else {\n return false;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $io = new SymfonyStyle($input, $output);\n $io->newLine();\n\n $src = $input->getArgument('src');\n $dest = $input->getArgument('dest');\n\n if (!$src) {\n $src = 'dev/pimcore/admin-ui-classic-bundle/public/extjs/js/pimcore-ext-all.json';\n }\n\n if (!$dest) {\n $dest = 'dev/pimcore/admin-ui-classic-bundle/public/extjs/js/ext-all';\n }\n\n $absoluteManifest = getcwd() . '/' . $src;\n\n $bootstrapFile = getcwd() . '/dev/pimcore/admin-ui-classic-bundle/public/extjs/js/bootstrap-ext-all.js';\n $bootstrap = file_get_contents($bootstrapFile);\n if (!$bootstrap) {\n throw new \\Exception('bootstrap file not found');\n }\n\n $scriptContents = $bootstrap . \"\\n\\n\";\n $scriptContentsMinified = $bootstrap . \"\\n\\n\";\n\n if (is_file($absoluteManifest)) {\n $manifestContents = file_get_contents($absoluteManifest);\n $manifestContents = json_decode($manifestContents, true);\n\n $loadOrder = $manifestContents['loadOrder'];\n\n $count = 0;\n\n // build dependencies\n $main = $loadOrder[count($loadOrder) - 1];\n $list = [\n $main['idx'] => $main,\n ];\n\n $this->populate($loadOrder, $list, $main);\n ksort($list);\n\n // replace this with loadOrder if we want to load the entire list\n foreach ($loadOrder as $loadOrderIdx => $loadOrderItem) {\n $count++;\n $relativePath = $loadOrderItem['path'];\n\n $fullPath = PIMCORE_WEB_ROOT . $relativePath;\n\n if (is_file($fullPath)) {\n $includeContents = file_get_contents($fullPath);\n\n $minify = new JS($includeContents);\n $includeContentsMinfified = $minify->minify();\n $includeContentsMinfified .= \"\\r\\n;\\r\\n\";\n $scriptContentsMinified .= $includeContentsMinfified;\n\n $includeContents .= \"\\r\\n;\\r\\n\";\n $scriptContents .= $includeContents;\n } else {\n throw new \\Exception('file does not exist: ' . $fullPath);\n }\n }\n } else {\n throw new \\Exception('manifest does not exist: ' . $absoluteManifest);\n }\n\n $scriptPath = getcwd() . '/' . $dest;\n file_put_contents($scriptPath . '.js', $scriptContentsMinified);\n file_put_contents($scriptPath . '-debug.js', $scriptContents);\n\n $io->writeln('writing to ' . $scriptPath);\n\n $io->success('Done');\n\n return 0;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function action_set_default() {\n $this->prepare();\n if ($this->request->method != 'POST') {\n throw new \\Exception();\n }\n\n if (!$this->user) {\n throw new ForbiddenException();\n }\n\n $id = $this->request->postWrap('id');\n\n if (!$id) {\n throw new NotFoundException(\"Missing wishlist id.\");\n }\n $wishList = $this->getWishList($id);\n\n if ($wishList->owner->id() != $this->user->id()) {\n throw new NotFoundException(\"Missing wishlist\");\n }\n\n $wishList->setAsUserDefaultWishList($this->user);\n\n if ($this->request->is_ajax()) {\n $this->jsonResponse(['success' => 1]);\n return;\n }\n\n $this->redirect($this->generateUrl('default', array(\n 'controller' => 'wishlist',\n 'action' => 'view',\n 'id' => $wishList->id()\n )));\n }", "smellKey": "S112", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "protected function evaluateTpl(Storage $template, array $parameters = array())\n {\n\n $this->evalTemplateX = $template;\n $this->evalParametersX = $parameters;\n unset($template, $parameters);\n\n if (isset($this->evalParametersX['this'])) {\n throw new \\InvalidArgumentException('Invalid parameter (this)');\n }\n if (isset($this->evalParametersX['view'])) {\n throw new \\InvalidArgumentException('Invalid parameter (view)');\n }\n\n if ($this->evalTemplateX instanceof FileStorage) {\n extract($this->evalParametersX, EXTR_SKIP);\n $this->evalParametersX = null;\n\n ob_start();\n require $this->evalTemplateX;\n\n $this->evalTemplateX = null;\n\n return ob_get_clean();\n } elseif ($this->evalTemplateX instanceof StringStorage) {\n extract($this->evalParametersX, EXTR_SKIP);\n $this->evalParametersX = null;\n\n ob_start();\n eval('; ?>'.$this->evalTemplateX.'evalTemplateX = null;\n\n return ob_get_clean();\n\n } else if ($this->evalTemplateX instanceof ClassStorage) {\n $callable = $this->evalTemplateX->getContent();\n\n if (!is_callable($callable)) {\n throw new \\Exception(\"Template must be a valid callable\");\n }\n\n $this->evalParametersX['view'] = $this;\n if ($this->has('form')) {\n $this->evalParametersX['formHelper'] = $this->get('form');\n }\n if ($this->has('translator')) {\n $this->evalParametersX['translatorHelper'] = $this['translator'];\n }\n\n $func = new \\ReflectionMethod($callable[0], $callable[1]);\n $funcParams = $func->getParameters();\n $tplParams = [];\n foreach ($funcParams as $k => $param) {\n if (array_key_exists($param->getName(), $this->evalParametersX)) {\n $tplParams[$k] = $this->evalParametersX[$param->getName()];\n } else {\n $tplParams[$k] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;\n }\n }\n\n $this->evalParametersX = null;\n\n ob_start();\n call_user_func_array($callable, $tplParams);\n\n $this->evalTemplateX = null;\n\n return ob_get_clean();\n }\n\n return false;\n }", "smellKey": "S112", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "public function convert(AbstractQuantityValue $quantityValue, Unit $toUnit): AbstractQuantityValue\n {\n if (!$quantityValue instanceof QuantityValue) {\n throw new UnsupportedException('Only QuantityValue is supported.');\n }\n $fromUnit = $quantityValue->getUnit();\n if (!$fromUnit instanceof Unit) {\n throw new Exception('Quantity value has no unit');\n }\n\n $fromBaseUnit = $fromUnit->getBaseunit();\n if ($fromBaseUnit === null) {\n $fromUnit = clone $fromUnit;\n $fromBaseUnit = $fromUnit;\n }\n\n if ($fromUnit->getFactor() === null) {\n $fromUnit->setFactor(1);\n }\n\n if ($fromUnit->getConversionOffset() === null) {\n $fromUnit->setConversionOffset(0);\n }\n\n $toBaseUnit = $toUnit->getBaseunit();\n if ($toBaseUnit === null) {\n $toUnit = clone $toUnit;\n $toBaseUnit = $toUnit;\n }\n\n if ($toUnit->getFactor() === null) {\n $toUnit->setFactor(1);\n }\n\n if ($toUnit->getConversionOffset() === null) {\n $toUnit->setConversionOffset(0);\n }\n\n if ($fromBaseUnit->getId() !== $toBaseUnit->getId()) {\n throw new Exception($fromUnit.' must have same base unit as '.$toUnit.' to be able to convert values');\n }\n\n $convertedValue = ($quantityValue->getValue() * $fromUnit->getFactor() - $fromUnit->getConversionOffset()) / $toUnit->getFactor() + $toUnit->getConversionOffset();\n\n return new QuantityValue($convertedValue, $toUnit->getId());\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function loadCommands(\n\t\tInputInterface $input,\n\t\tConsoleOutputInterface $output\n\t) {\n\t\t// $application is required to be defined in the register_command scripts\n\t\t$application = $this->application;\n\t\t$inputDefinition = $application->getDefinition();\n\t\t$inputDefinition->addOption(\n\t\t\tnew InputOption(\n\t\t\t\t'no-warnings',\n\t\t\t\tnull,\n\t\t\t\tInputOption::VALUE_NONE,\n\t\t\t\t'Skip global warnings, show command output only',\n\t\t\t\tnull\n\t\t\t)\n\t\t);\n\t\ttry {\n\t\t\t$input->bind($inputDefinition);\n\t\t} catch (\\RuntimeException $e) {\n\t\t\t//expected if there are extra options\n\t\t}\n\t\tif ($input->getOption('no-warnings')) {\n\t\t\t$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);\n\t\t}\n\n\t\tif ($this->memoryInfo->isMemoryLimitSufficient() === false) {\n\t\t\t$output->getErrorOutput()->writeln(\n\t\t\t\t'The current PHP memory limit ' .\n\t\t\t\t'is below the recommended value of 512MB.'\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\trequire_once __DIR__ . '/../../../core/register_command.php';\n\t\t\tif ($this->config->getSystemValueBool('installed', false)) {\n\t\t\t\tif (\\OCP\\Util::needUpgrade()) {\n\t\t\t\t\tthrow new NeedsUpdateException();\n\t\t\t\t} elseif ($this->config->getSystemValueBool('maintenance')) {\n\t\t\t\t\t$this->writeMaintenanceModeInfo($input, $output);\n\t\t\t\t} else {\n\t\t\t\t\tOC_App::loadApps();\n\t\t\t\t\t$appManager = \\OCP\\Server::get(IAppManager::class);\n\t\t\t\t\tforeach ($appManager->getInstalledApps() as $app) {\n\t\t\t\t\t\t$appPath = \\OC_App::getAppPath($app);\n\t\t\t\t\t\tif ($appPath === false) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// load commands using info.xml\n\t\t\t\t\t\t$info = $appManager->getAppInfo($app);\n\t\t\t\t\t\tif (isset($info['commands'])) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t$this->loadCommandsFromInfoXml($info['commands']);\n\t\t\t\t\t\t\t} catch (\\Throwable $e) {\n\t\t\t\t\t\t\t\t$output->writeln(\"\" . $e->getMessage() . \"\");\n\t\t\t\t\t\t\t\t$this->logger->error($e->getMessage(), [\n\t\t\t\t\t\t\t\t\t'exception' => $e,\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// load from register_command.php\n\t\t\t\t\t\t\\OC_App::registerAutoloading($app, $appPath);\n\t\t\t\t\t\t$file = $appPath . '/appinfo/register_command.php';\n\t\t\t\t\t\tif (file_exists($file)) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\trequire $file;\n\t\t\t\t\t\t\t} catch (\\Exception $e) {\n\t\t\t\t\t\t\t\t$this->logger->error($e->getMessage(), [\n\t\t\t\t\t\t\t\t\t'exception' => $e,\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} elseif ($input->getArgument('command') !== '_completion' && $input->getArgument('command') !== 'maintenance:install') {\n\t\t\t\t$errorOutput = $output->getErrorOutput();\n\t\t\t\t$errorOutput->writeln(\"Nextcloud is not installed - only a limited number of commands are available\");\n\t\t\t}\n\t\t} catch (NeedsUpdateException $e) {\n\t\t\tif ($input->getArgument('command') !== '_completion') {\n\t\t\t\t$errorOutput = $output->getErrorOutput();\n\t\t\t\t$errorOutput->writeln(\"Nextcloud or one of the apps require upgrade - only a limited number of commands are available\");\n\t\t\t\t$errorOutput->writeln(\"You may use your browser or the occ upgrade command to do the upgrade\");\n\t\t\t}\n\t\t}\n\n\t\tif ($input->getFirstArgument() !== 'check') {\n\t\t\t$errors = \\OC_Util::checkServer(\\OC::$server->getSystemConfig());\n\t\t\tif (!empty($errors)) {\n\t\t\t\tforeach ($errors as $error) {\n\t\t\t\t\t$output->writeln((string)$error['error']);\n\t\t\t\t\t$output->writeln((string)$error['hint']);\n\t\t\t\t\t$output->writeln('');\n\t\t\t\t}\n\t\t\t\tthrow new \\Exception(\"Environment not properly prepared.\");\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function assertJsonConfigIsWritable($name)\n {\n $file = implode(\n DIRECTORY_SEPARATOR,\n array(\n CONFIG_DIR,\n \"$name.json\"\n )\n );\n\n if (!is_writable($file)) {\n throw new Exception(\"Cannot write to file '$file'\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function renderParams(string $string, string $context): string\n {\n $templatingEngine = Pimcore::getContainer()->get('pimcore.templating.engine.delegating');\n\n try {\n $twig = $templatingEngine->getTwigEnvironment(true);\n $template = $twig->createTemplate($string);\n\n return $template->render($this->getParams());\n } catch (SecurityError $e) {\n Logger::err((string) $e);\n\n throw new Exception(sprintf('Failed rendering the %s: %s. Please check your twig sandbox security policy or contact the administrator.',\n $context, substr($e->getMessage(), 0, strpos($e->getMessage(), ' in \"__string'))));\n } finally {\n $templatingEngine->disableSandboxExtensionFromTwigEnvironment();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function sendTestEmailAction(Request $request): JsonResponse\n {\n if (!$this->getAdminUser()->isAllowed('emails')) {\n throw new \\Exception(\"Permission denied, user needs 'emails' permission.\");\n }\n\n // Simulate a frontend request to prefix assets\n $request->attributes->set(RequestHelper::ATTRIBUTE_FRONTEND_REQUEST, true);\n\n $mail = new Mail();\n\n if ($request->get('emailType') == 'text') {\n $mail->text($request->get('content'));\n } elseif ($request->get('emailType') == 'html') {\n $mail->html($request->get('content'));\n } elseif ($request->get('emailType') == 'document') {\n $doc = \\Pimcore\\Model\\Document::getByPath($request->get('documentPath'));\n\n if ($doc instanceof \\Pimcore\\Model\\Document\\Email) {\n $mail->setDocument($doc);\n\n if ($request->get('mailParamaters')) {\n if ($mailParamsArray = json_decode($request->get('mailParamaters'), true)) {\n foreach ($mailParamsArray as $mailParam) {\n if ($mailParam['key']) {\n $mail->setParam($mailParam['key'], $mailParam['value']);\n }\n }\n }\n }\n } else {\n throw new \\Exception('Email document not found!');\n }\n }\n\n if ($from = $request->get('from')) {\n $addressArray = \\Pimcore\\Helper\\Mail::parseEmailAddressField($from);\n if ($addressArray) {\n //use the first address only\n [$cleanedFromAddress] = $addressArray;\n $mail->from(new Address($cleanedFromAddress['email'], $cleanedFromAddress['name']));\n }\n }\n\n $toAddresses = \\Pimcore\\Helper\\Mail::parseEmailAddressField($request->get('to'));\n foreach ($toAddresses as $cleanedToAddress) {\n $mail->addTo($cleanedToAddress['email'], $cleanedToAddress['name']);\n }\n\n $mail->subject($request->get('subject'));\n $mail->setIgnoreDebugMode(true);\n\n $mail->send();\n\n return $this->adminJson([\n 'success' => true,\n ]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $databaseId, string $name, bool $enabled, Response $response, Database $dbForProject, Event $events) {\n\n $database = $dbForProject->getDocument('databases', $databaseId);\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n try {\n $database = $dbForProject->updateDocument('databases', $databaseId, $database\n ->setAttribute('name', $name)\n ->setAttribute('enabled', $enabled)\n ->setAttribute('search', implode(' ', [$databaseId, $name])));\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (StructureException $exception) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. ' . $exception->getMessage());\n }\n\n $events->setParam('databaseId', $database->getId());\n\n $response->dynamic($database, Response::MODEL_DATABASE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (Validator $context) {\n if (!$context instanceof OpenEMRParticleValidator) {\n throw new \\RuntimeException(\"CoverageValidator requires an instance of OpenEMRParticleValidator\");\n }\n $context->required('pid')->numeric();\n $context->required('type')->inArray(array('primary', 'secondary', 'tertiary'))\n ->callback(function ($value) {\n if ($GLOBALS['insurance_only_one']) {\n if ($value !== 'primary') {\n throw new InvalidValueException(\"only primary insurance allowed with insurance_only_one global setting enabled\", \"INSURANCE_ONLY_ONE::INVALID_INSURANCE_TYPE\");\n }\n }\n return true;\n });\n $context->required('provider')->numeric();\n $context->optional('plan_name')->lengthBetween(2, 255);\n $context->required('policy_number')->lengthBetween(2, 255);\n $context->optional('group_number')->lengthBetween(2, 255);\n $context->required('subscriber_lname')->lengthBetween(2, 255);\n $context->optional('subscriber_mname')->lengthBetween(1, 255);\n $context->required('subscriber_fname')->lengthBetween(1, 255);\n $context->required('subscriber_relationship')->listOption('sub_relation')\n ->callback(function ($value, $values) {\n if (\n !empty($values['pid'])\n && !empty($values['subscriber_lname']) && !empty($values['subscriber_fname'])\n && !empty($values['subscriber_ss'])\n ) {\n // check name and previous names to make sure a mistake hasn't been made.\n $pidSearch = new TokenSearchField('pid', new TokenSearchValue($values['pid']));\n $prevFirstNameSearch = new StringSearchField('previous_name_first', $values['subscriber_fname'], SearchModifier::EXACT);\n $prevLastNameSearch = new StringSearchField('previous_name_last', $values['subscriber_lname'], SearchModifier::EXACT);\n $previousNameSearch = new CompositeSearchField('patient-previous-name', []);\n $previousNameSearch->setChildren([$pidSearch, $prevFirstNameSearch, $prevLastNameSearch]);\n\n $firstNameSearch = new StringSearchField('fname', $values['subscriber_fname'], SearchModifier::EXACT);\n $lastNameSearch = new StringSearchField('lname', $values['subscriber_lname'], SearchModifier::EXACT);\n $currentNameSearch = new CompositeSearchField('patient-current-name', []);\n $currentNameSearch->setChildren([$pidSearch, $firstNameSearch, $lastNameSearch]);\n\n $ssnSearch = new StringSearchField('ss', $values['subscriber_ss'], SearchModifier::EXACT);\n $ssnPidSearch = new CompositeSearchField('patient-ssn', []);\n $ssnPidSearch->setChildren([$pidSearch, $ssnSearch]);\n $patientService = new PatientService();\n $isAnd = false;\n $results = $patientService->search([$previousNameSearch, $currentNameSearch, $ssnPidSearch], $isAnd);\n\n if ($value === 'self') {\n if (!$results->hasData()) {\n throw new InvalidValueException(\"Subscriber name must match patient name for self relationship\", \"Record::INVALID_SELF_SUBSCRIBER_NAME\");\n }\n $patient = $results->getData()[0];\n // need to check the social security number as well\n if ($patient['ss'] !== $values['subscriber_ss']) {\n throw new InvalidValueException(\"Subscriber social security number must match patient social security number for self relationship\", \"Record::INVALID_SELF_SUBSCRIBER_SSN\");\n }\n // if the first and last name do not match exactly we need to search previous names to see if we have a match here.\n // we do this because the results return SSN OR name matches so we have to manually check the name matches\n if ($patient['lname'] != $values['subscriber_lname'] || $patient['fname'] != $values['subscriber_fname']) {\n // need to search previous names, if no matches here then throw exception\n $previousNames = $patient['previous_names'];\n $found = false;\n foreach ($previousNames as $previousName) {\n // do a strict equality and then we can do multibyte comparison for localizations\n // note if we want to handle more comprehensive multibytes\n // we need to do some normalizations as per this stackoverflow post: https://stackoverflow.com/a/38855868\n if (\n mb_is_string_equal_ci($previousName['previous_name_first'], $values['subscriber_fname'])\n && mb_is_string_equal_ci($previousName['previous_name_last'], $values['subscriber_lname'])\n ) {\n $found = true;\n break;\n }\n }\n if (!$found) {\n throw new InvalidValueException(\"Subscriber name must match patient name for self relationship\", \"Record::INVALID_SELF_SUBSCRIBER_NAME\");\n }\n }\n } else {\n if ($results->hasData()) {\n // need to check to see if its because the ssn matched\n // or because we have a name match\n if ($results->getData()[0]['ss'] === $values['subscriber_ss']) {\n throw new InvalidValueException(\"Subscriber social security number must not match patient social security number for non-self relationship\", \"Record::INVALID_SUBSCRIBER_SSN\");\n } else {\n // Note: we do not throw an exception on the name match here as there can be a subscriber name ie John Smith who is covered by someone who is NOT themselves also named John Smith\n // for example a father and son with the same name. This is a rare case but it does happen.\n }\n }\n }\n }\n return true;\n });\n $context->required('subscriber_DOB')->datetime('Y-m-d');\n $context->required('subscriber_street')->lengthBetween(2, 255);\n $context->required('subscriber_postal_code')->lengthBetween(2, 255);\n $context->required('subscriber_city')->lengthBetween(2, 255);\n $context->required('subscriber_state')->listOption($GLOBALS['state_list']);\n $context->optional('subscriber_country')->listOption($GLOBALS['country_list']);\n $context->optional('subscriber_phone')->lengthBetween(2, 255);\n $context->required('subscriber_sex')->listOption('sex');\n $context->required('accept_assignment')->inArray(['TRUE', 'FALSE']);\n // policy type has a Not Applicable(NA) option which is an empty string so we allow empty here\n $context->optional('policy_type')->allowEmpty(true)->inArray(InsurancePolicyTypes::POLICY_TYPES);\n $context->optional('subscriber_employer')->lengthBetween(2, 255);\n $context->optional('subscriber_employer_street')->lengthBetween(2, 255);\n $context->optional('subscriber_employer_postal_code')->lengthBetween(2, 255);\n $context->optional('subscriber_employer_state')->listOption($GLOBALS['state_list']);\n $context->optional('subscriber_employer_country')->listOption($GLOBALS['country_list']);\n $context->optional('subscriber_employer_city')->lengthBetween(2, 255);\n $context->optional('copay')->lengthBetween(2, 255);\n $context->required('date')->datetime('Y-m-d')\n ->callback(function ($value, $values) {\n // need to check\n // TODO: @adunsulag need to move all these queries into the InsuranceService...\n if (!empty($values['pid']) && !empty($values['type']) && !empty($value)) {\n $sqlCheck = \"SELECT COUNT(*) AS cnt FROM insurance_data WHERE pid = ? AND type = ? AND date = ?\";\n $binds = [$values['pid'], $values['type'], $value];\n if (!empty($values['uuid'])) {\n $sqlCheck .= \" AND uuid != ?\";\n $binds[] = UuidRegistry::uuidToBytes($values['uuid']);\n }\n $duplicatePolicyCount = QueryUtils::fetchSingleValue($sqlCheck, 'cnt', $binds);\n if ($duplicatePolicyCount != null && $duplicatePolicyCount > 0) {\n throw new InvalidValueException(\"A policy for this type with the same effective date already exists for this patient\", \"Record::DUPLICATE_RECORD\");\n }\n }\n\n // can't figure out how to make the current policy check work with a nullable date_end\n // so we will do it on the date column\n if (!empty($values['pid']) && !empty($values['type'])) {\n if (empty($value)) {\n $sqlCheck = \"SELECT COUNT(*) AS cnt FROM insurance_data WHERE pid = ? AND type = ? AND date_end IS NULL\";\n $binds = [$values['pid'], $values['type']];\n if (!empty($values['uuid'])) {\n $sqlCheck .= \" AND uuid != ?\";\n $binds[] = UuidRegistry::uuidToBytes($values['uuid']);\n }\n // check to make sure there are no other policies for this type with an empty end date as we can\n // only have one current policy for a given type\n $currentPolicyCount = QueryUtils::fetchSingleValue($sqlCheck, 'cnt', $binds);\n if ($currentPolicyCount != null && $currentPolicyCount > 0) {\n throw new InvalidValueException(\"A current policy (no end date) already exists for this patient and type.\", \"Record::DUPLICATE_CURRENT_POLICY\");\n }\n }\n if (!empty($values['date_end']) && strtotime($values['date']) > strtotime($values['date_end'])) {\n throw new InvalidValueException(\"Start date cannot be after end date\", \"DateTime::INVALID_START_DATE\");\n }\n }\n return true;\n });\n $context->optional('date_end')\n ->required(function ($values) {\n if (!empty($values['date'])) {\n if (!empty($values['pid']) && !empty($values['type'])) {\n return true;\n }\n }\n return false;\n }, null, true)\n ->datetime('Y-m-d')\n ->callback(function ($value, $values) {\n\n\n return true;\n });\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getEventDispatcher()\n {\n if ($this->container) {\n /** @var EventDispatcher $dispatcher */\n return $this->container->get('event_dispatcher');\n } else {\n throw new \\Exception('Container does not exist');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function runReport($rowRule, $patients, $dateTarget, $options = array())\n {\n $ruleId = $rowRule['id'];\n $patientData = array();\n foreach ($patients as $patient) {\n $patientData [] = $patient['pid'];\n }\n\n $reportFactory = null;\n if (ReportTypes::getType($ruleId) == ReportTypes::CQM) {\n $reportFactory = new CqmReportFactory();\n } elseif (ReportTypes::getType($ruleId) == ReportTypes::AMC) {\n $reportFactory = new AmcReportFactory();\n } else {\n throw new Exception(\"Unknown rule: \" . $ruleId);\n }\n\n $report = null;\n if ($reportFactory instanceof RsReportFactoryAbstract) {\n $report = $reportFactory->createReport(ReportTypes::getClassName($ruleId), $rowRule, $patientData, $dateTarget, $options);\n }\n\n $results = array();\n if (\n $report instanceof RsReportIF &&\n !$report instanceof RsUnimplementedIF\n ) {\n $report->execute();\n $results = $report->getResults();\n } else {\n (new SystemLogger())->errorLogCaller(\"Rule class does not implement valid interfaces\", ['ruleId' => $ruleId, 'class' => ReportTypes::getClassName($ruleId)]);\n }\n\n return RsHelper::formatClinicalRules($results);\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function save(array $params = []): void\n {\n $context = $this->model->getContext();\n\n // if inside a field collection a delete is not necessary as the fieldcollection deletes all entries anyway\n // see Pimcore\\Model\\DataObject\\Fieldcollection\\Dao::delete\n\n $forceUpdate = false;\n if ((isset($params['newParent']) && $params['newParent']) || DataObject::isDirtyDetectionDisabled() || $this->model->hasDirtyLanguages(\n ) || $context['containerType'] == 'fieldcollection') {\n $forceUpdate = $this->delete(false, true);\n }\n\n $object = $this->model->getObject();\n $validLanguages = Tool::getValidLanguages();\n\n if (isset($context['containerType']) && $context['containerType'] === 'fieldcollection') {\n $containerKey = $context['containerKey'];\n $container = DataObject\\Fieldcollection\\Definition::getByKey($containerKey);\n } elseif (isset($context['containerType']) && $context['containerType'] === 'objectbrick') {\n $containerKey = $context['containerKey'];\n $container = DataObject\\Objectbrick\\Definition::getByKey($containerKey);\n } else {\n $container = $this->model->getClass();\n }\n\n if (!isset($params['owner'])) {\n throw new Exception('need owner from container implementation');\n }\n\n $this->model->_setOwner($params['owner']);\n $this->model->_setOwnerFieldname('localizedfields');\n $this->model->_setOwnerLanguage(null);\n\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $localizedfields */\n $localizedfields = $container->getFieldDefinition('localizedfields');\n $fieldDefinitions = $localizedfields->getFieldDefinitions(\n ['suppressEnrichment' => true]\n );\n\n /**\n * We temporary enable the runtime cache so we don't have to calculate the tree for each language\n * which is a great performance gain if you have a lot of languages\n */\n DataObject\\Concrete\\Dao\\InheritanceHelper::setUseRuntimeCache(true);\n\n $ignoreLocalizedQueryFallback = \\Pimcore\\Config::getSystemConfiguration('objects')['ignore_localized_query_fallback'];\n if (!$ignoreLocalizedQueryFallback) {\n $this->model->markLanguageAsDirtyByFallback();\n }\n\n $flag = DataObject\\Localizedfield::getGetFallbackValues();\n\n if (!$ignoreLocalizedQueryFallback) {\n DataObject\\Localizedfield::setGetFallbackValues(true);\n }\n\n foreach ($validLanguages as $language) {\n if (empty($params['newParent'])\n && !empty($params['isUpdate'])\n && !$this->model->isLanguageDirty($language)\n && !$forceUpdate\n ) {\n continue;\n }\n\n $inheritedValues = DataObject::doGetInheritedValues();\n DataObject::setGetInheritedValues(false);\n\n $insertData = [\n 'ooo_id' => $this->model->getObject()->getId(),\n 'language' => $language,\n ];\n\n if ($container instanceof DataObject\\Objectbrick\\Definition || $container instanceof DataObject\\Fieldcollection\\Definition) {\n $insertData['fieldname'] = $context['fieldname'];\n $insertData['index'] = $context['index'] ?? 0;\n }\n\n foreach ($fieldDefinitions as $fieldName => $fd) {\n if ($fd instanceof CustomResourcePersistingInterface) {\n // for fieldtypes which have their own save algorithm eg. relational data types, ...\n $context = $this->model->getContext() ? $this->model->getContext() : [];\n if (isset($context['containerType']) && ($context['containerType'] === 'fieldcollection' || $context['containerType'] === 'objectbrick')) {\n $context['subContainerType'] = 'localizedfield';\n }\n\n $isUpdate = isset($params['isUpdate']) && $params['isUpdate'];\n $childParams = $this->getFieldDefinitionParams($fieldName, $language, ['isUpdate' => $isUpdate, 'context' => $context]);\n\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\Relations\\AbstractRelations) {\n $saveLocalizedRelations = $forceUpdate || ($params['saveRelationalData']['saveLocalizedRelations'] ?? false);\n if (($saveLocalizedRelations && $container instanceof DataObject\\Fieldcollection\\Definition)\n || (((!$container instanceof DataObject\\Fieldcollection\\Definition || $container instanceof DataObject\\Objectbrick\\Definition)\n && $this->model->isLanguageDirty($language))\n || $saveLocalizedRelations)) {\n if ($saveLocalizedRelations) {\n $childParams['forceSave'] = true;\n }\n $fd->save($this->model, $childParams);\n }\n } else {\n $fd->save($this->model, $childParams);\n }\n }\n if ($fd instanceof ResourcePersistenceAwareInterface\n && $fd instanceof DataObject\\ClassDefinition\\Data) {\n if (is_array($fd->getColumnType())) {\n $fieldDefinitionParams = $this->getFieldDefinitionParams($fieldName, $language, ['isUpdate' => ($params['isUpdate'] ?? false)]);\n $insertDataArray = $fd->getDataForResource(\n $this->model->getLocalizedValue($fieldName, $language, true),\n $object,\n $fieldDefinitionParams\n );\n $insertData = array_merge($insertData, $insertDataArray);\n $this->model->setLocalizedValue($fieldName, $fd->getDataFromResource($insertDataArray, $object, $fieldDefinitionParams), $language, false);\n } else {\n $fieldDefinitionParams = $this->getFieldDefinitionParams($fieldName, $language, ['isUpdate' => ($params['isUpdate'] ?? false)]);\n $insertData[$fd->getName()] = $fd->getDataForResource(\n $this->model->getLocalizedValue($fieldName, $language, true),\n $object,\n $fieldDefinitionParams\n );\n $this->model->setLocalizedValue($fieldName, $fd->getDataFromResource($insertData[$fd->getName()], $object, $fieldDefinitionParams), $language, false);\n }\n }\n }\n\n $storeTable = $this->getTableName();\n $queryTable = $this->getQueryTableName().'_'.$language;\n\n try {\n if ((isset($params['newParent']) && $params['newParent']) || !isset($params['isUpdate']) || !$params['isUpdate'] || $this->model->isLanguageDirty(\n $language\n )) {\n Helper::upsert($this->db, $storeTable, $insertData, $this->getPrimaryKey($storeTable));\n }\n } catch (TableNotFoundException $e) {\n // if the table doesn't exist -> create it! deferred creation for object bricks ...\n try {\n $this->db->rollBack();\n } catch (Exception $er) {\n // PDO adapter throws exceptions if rollback fails\n Logger::info((string) $er);\n }\n\n $this->createUpdateTable();\n\n // throw exception which gets caught in AbstractObject::save() -> retry saving\n throw new LanguageTableDoesNotExistException('missing table created, start next run ... ;-)');\n }\n\n if ($container instanceof DataObject\\ClassDefinition || $container instanceof DataObject\\Objectbrick\\Definition) {\n // query table\n $data = [];\n $data['ooo_id'] = $this->model->getObject()->getId();\n $data['language'] = $language;\n\n $this->inheritanceHelper = new DataObject\\Concrete\\Dao\\InheritanceHelper(\n $object->getClassId(),\n 'ooo_id',\n $storeTable,\n $queryTable\n );\n $this->inheritanceHelper->resetFieldsToCheck();\n $sql = 'SELECT * FROM '.$queryTable.' WHERE ooo_id = '.$object->getId(\n ).\" AND language = '\".$language.\"'\";\n\n $oldData = [];\n\n try {\n $oldData = $this->db->fetchAssociative($sql);\n } catch (TableNotFoundException $e) {\n // if the table doesn't exist -> create it!\n\n // the following is to ensure consistent data and atomic transactions, while having the flexibility\n // to add new languages on the fly without saving all classes having localized fields\n\n // first we need to roll back all modifications, because otherwise they would be implicitly committed\n // by the following DDL\n try {\n $this->db->rollBack();\n } catch (Exception $er) {\n // PDO adapter throws exceptions if rollback fails\n Logger::info((string) $er);\n }\n\n // this creates the missing table\n $this->createUpdateTable();\n\n // at this point we throw an exception so that the transaction gets repeated in DataObject::save()\n throw new LanguageTableDoesNotExistException('missing table created, start next run ... ;-)');\n }\n\n // get fields which shouldn't be updated\n $untouchable = [];\n\n // @TODO: currently we do not support lazyloading in localized fields\n\n $inheritanceEnabled = $object->getClass()->getAllowInherit();\n $parentData = null;\n if ($inheritanceEnabled) {\n // get the next suitable parent for inheritance\n $parentForInheritance = $object->getNextParentForInheritance();\n if ($parentForInheritance) {\n // we don't use the getter (built in functionality to get inherited values) because we need to avoid race conditions\n // we cannot DataObject\\AbstractObject::setGetInheritedValues(true); and then $this->model->getLocalizedValue($key, $language)\n // so we select the data from the parent object using FOR UPDATE, which causes a lock on this row\n // so the data of the parent cannot be changed while this transaction is on progress\n $parentData = $this->db->fetchAssociative(\n 'SELECT * FROM '.$queryTable.' WHERE ooo_id = ? AND language = ? FOR UPDATE',\n [$parentForInheritance->getId(), $language]\n );\n }\n }\n\n foreach ($fieldDefinitions as $fd) {\n if ($fd instanceof QueryResourcePersistenceAwareInterface\n && $fd instanceof DataObject\\ClassDefinition\\Data) {\n $key = $fd->getName();\n\n // exclude untouchables if value is not an array - this means data has not been loaded\n if (!in_array($key, $untouchable)) {\n $localizedValue = $this->model->getLocalizedValue($key, $language, $ignoreLocalizedQueryFallback);\n $insertData = $fd->getDataForQueryResource(\n $localizedValue,\n $object,\n $this->getFieldDefinitionParams($key, $language)\n );\n $isEmpty = $fd->isEmpty($localizedValue);\n\n if (is_array($insertData)) {\n $columnNames = array_keys($insertData);\n $data = array_merge($data, $insertData);\n } else {\n $columnNames = [$key];\n $data[$key] = $insertData;\n }\n\n // if the current value is empty and we have data from the parent, we just use it\n if ($isEmpty && $parentData) {\n foreach ($columnNames as $columnName) {\n if (array_key_exists($columnName, $parentData)) {\n $data[$columnName] = $parentData[$columnName];\n if (is_array($insertData)) {\n $insertData[$columnName] = $parentData[$columnName];\n } else {\n $insertData = $parentData[$columnName];\n }\n }\n }\n }\n\n if ($inheritanceEnabled && $fd->getFieldType() != 'calculatedValue') {\n //get changed fields for inheritance\n if ($fd->isRelationType()) {\n if (is_array($insertData)) {\n $doInsert = false;\n foreach ($insertData as $insertDataKey => $insertDataValue) {\n $oldDataValue = $oldData[$insertDataKey] ?? null;\n $parentDataValue = $parentData[$insertDataKey] ?? null;\n if ($isEmpty && $oldDataValue == $parentDataValue) {\n // do nothing, ... value is still empty and parent data is equal to current data in query table\n } elseif ($oldDataValue != $insertDataValue) {\n $doInsert = true;\n\n break;\n }\n }\n\n if ($doInsert) {\n $this->inheritanceHelper->addRelationToCheck(\n $key,\n $fd,\n array_keys($insertData)\n );\n }\n } else {\n $oldDataValue = $oldData[$key] ?? null;\n $parentDataValue = $parentData[$key] ?? null;\n if ($isEmpty && $oldDataValue == $parentDataValue) {\n // do nothing, ... value is still empty and parent data is equal to current data in query table\n } elseif ($oldDataValue != $insertData) {\n $this->inheritanceHelper->addRelationToCheck($key, $fd);\n }\n }\n } else {\n if (is_array($insertData)) {\n foreach ($insertData as $insertDataKey => $insertDataValue) {\n $oldDataValue = $oldData[$insertDataKey] ?? null;\n $parentDataValue = $parentData[$insertDataKey] ?? null;\n if ($isEmpty && $oldDataValue == $parentDataValue) {\n // do nothing, ... value is still empty and parent data is equal to current data in query table\n } elseif ($oldDataValue != $insertDataValue) {\n $this->inheritanceHelper->addFieldToCheck($insertDataKey, $fd);\n }\n }\n } else {\n $oldDataValue = $oldData[$key] ?? null;\n $parentDataValue = $parentData[$key] ?? null;\n if ($isEmpty && $oldDataValue == $parentDataValue) {\n // do nothing, ... value is still empty and parent data is equal to current data in query table\n } elseif ($oldDataValue != $insertData) {\n // data changed, do check and update\n $this->inheritanceHelper->addFieldToCheck($key, $fd);\n }\n }\n }\n }\n } else {\n Logger::debug(\n 'Excluding untouchable query value for object [ '.$this->model->getObjectId() .\" ] key [ $key ] because it has not been loaded\"\n );\n }\n }\n }\n\n $queryTable = $this->getQueryTableName().'_'.$language;\n Helper::upsert($this->db, $queryTable, $data, $this->getPrimaryKey($queryTable));\n if ($inheritanceEnabled) {\n $context = isset($params['context']) ? $params['context'] : [];\n if ($context['containerType'] === 'objectbrick') {\n $inheritanceRelationContext = [\n 'ownertype' => 'localizedfield',\n 'ownername' => '/objectbrick~' . $context['fieldname'] . '/' . $context['containerKey'] . '/localizedfield~localizedfield',\n ];\n } else {\n $inheritanceRelationContext = [\n 'ownertype' => 'localizedfield',\n 'ownername' => 'localizedfield',\n ];\n }\n $this->inheritanceHelper->doUpdate($object->getId(), true, [\n 'language' => $language,\n 'inheritanceRelationContext' => $inheritanceRelationContext,\n ]);\n }\n $this->inheritanceHelper->resetFieldsToCheck();\n }\n\n DataObject::setGetInheritedValues($inheritedValues);\n } // foreach language\n\n if (!$ignoreLocalizedQueryFallback) {\n DataObject\\Localizedfield::setGetFallbackValues($flag);\n }\n DataObject\\Concrete\\Dao\\InheritanceHelper::setUseRuntimeCache(false);\n DataObject\\Concrete\\Dao\\InheritanceHelper::clearRuntimeCache();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function applySelect(QueryBuilder $query, array $sortClauses): void\n {\n foreach ($sortClauses as $nr => $sortClause) {\n foreach ($this->handlers as $handler) {\n if ($handler->accept($sortClause)) {\n foreach ($handler->applySelect($query, $sortClause, $nr) as $column) {\n if (strrpos($column, '_null', -6) === false) {\n $direction = $sortClause->direction;\n } else {\n // Always sort null last\n $direction = 'ASC';\n }\n\n $this->sortColumns[$column] = $direction;\n }\n continue 2;\n }\n }\n\n throw new RuntimeException('No handler available for Sort Clause: ' . get_class($sortClause));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function addCustomLayoutAction(Request $request): JsonResponse\n {\n $layoutId = $request->get('layoutIdentifier');\n $existingLayout = DataObject\\ClassDefinition\\CustomLayout::getById($layoutId);\n if ($existingLayout) {\n throw new \\Exception('Custom Layout identifier already exists');\n }\n\n $customLayout = DataObject\\ClassDefinition\\CustomLayout::create(\n [\n 'name' => $request->get('layoutName'),\n 'userOwner' => $this->getAdminUser()->getId(),\n 'classId' => $request->get('classId'),\n ]\n );\n\n $customLayout->setId($layoutId);\n if (!$customLayout->isWriteable()) {\n throw new ConfigWriteException();\n }\n $customLayout->save();\n\n $isWriteable = $customLayout->isWriteable();\n $data = $customLayout->getObjectVars();\n $data['isWriteable'] = $isWriteable;\n\n return $this->adminJson(['success' => true, 'id' => $customLayout->getId(), 'name' => $customLayout->getName(),\n 'data' => $data, ]);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function __construct(string $savePath = null)\n {\n if (null === $savePath) {\n $savePath = \\ini_get('session.save_path');\n }\n\n $baseDir = $savePath;\n\n if ($count = substr_count($savePath, ';')) {\n if ($count > 2) {\n throw new \\InvalidArgumentException(sprintf('Invalid argument $savePath \\'%s\\'.', $savePath));\n }\n\n // characters after last ';' are the path\n $baseDir = ltrim(strrchr($savePath, ';'), ';');\n }\n\n if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {\n throw new \\RuntimeException(sprintf('Session Storage was not able to create directory \"%s\".', $baseDir));\n }\n\n if ($savePath !== \\ini_get('session.save_path')) {\n ini_set('session.save_path', $savePath);\n }\n if ('files' !== \\ini_get('session.save_handler')) {\n ini_set('session.save_handler', 'files');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function createRequestRecord(\n $userId,\n $realm,\n $startDate,\n $endDate,\n $format\n ) {\n try {\n $this->dbh->beginTransaction();\n\n // Check for duplicate submitted or available requests for the user.\n $duplicates = array_filter(\n $this->listUserRequestsByState($userId),\n function ($request) use ($realm, $startDate, $endDate, $format) {\n return ($request['state'] == 'Submitted' || $request['state'] == 'Available')\n && $realm == $request['realm']\n && $startDate == $request['start_date']\n && $endDate == $request['end_date']\n && $format == $request['export_file_format'];\n }\n );\n if (count($duplicates) > 0) {\n throw new Exception('Cannot create duplicate request');\n }\n\n $sql = \"INSERT INTO batch_export_requests\n (requested_datetime, user_id, realm, start_date, end_date, export_file_format)\n VALUES\n (NOW(), :user_id, :realm, :start_date, :end_date, :export_file_format)\";\n\n $params = array(\n 'user_id' => $userId,\n 'realm' => $realm,\n 'start_date' => $startDate,\n 'end_date' => $endDate,\n 'export_file_format' => $format\n );\n\n $this->logger->info([\n 'module' => self::LOG_MODULE,\n 'message' => 'Creating data warehouse export record',\n 'event' => 'INSERT',\n 'table' => 'moddb.batch_export_requests',\n 'user_id' => $userId,\n 'realm' => $realm,\n 'start_date' => $startDate,\n 'end_date' => $endDate,\n 'format' => $format\n ]);\n\n $id = $this->dbh->insert($sql, $params);\n $this->dbh->commit();\n return $id;\n } catch (Exception $e) {\n $this->dbh->rollBack();\n $this->logger->err([\n 'module' => self::LOG_MODULE,\n 'message' => 'Record creation failed: ' . $e->getMessage(),\n 'stacktrace' => $e->getTraceAsString()\n ]);\n throw $e;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function work(\n Version $version,\n string $initialBranchName = AbstractShopsysReleaseWorker::MAIN_BRANCH_NAME,\n ): void {\n if (!str_starts_with($version->getOriginalString(), 'v')) {\n throw new RuntimeException(\n 'Name of released version must start with \\'v\\'',\n );\n }\n\n if ($version->getOriginalString() !== 'v' . $version->getVersionString()) {\n throw new RuntimeException(\n 'Version string needs to follow SemVer format (e.g. v11.0.0)',\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function Error($msg)\n\t{\n\t\tthrow new Exception($msg);\n\t}", "smellKey": "S112", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function getConverter($typeName)\n {\n if (!isset($this->converterMap[$typeName])) {\n throw new NotFound($typeName);\n } elseif (!$this->converterMap[$typeName] instanceof Converter) {\n if (!is_callable($this->converterMap[$typeName])) {\n throw new \\RuntimeException(\"Converter '$typeName' is neither callable nor an instance\");\n }\n\n $factory = $this->converterMap[$typeName];\n $this->converterMap[$typeName] = call_user_func($factory);\n\n if (!$this->converterMap[$typeName] instanceof Converter) {\n throw new \\RuntimeException(\n \"Converter '{$typeName}' callable returned \" . gettype($this->converterMap[$typeName]) . ' instead of a converter'\n );\n }\n }\n\n return $this->converterMap[$typeName];\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public static function unzip($system, $zipfile, $destination){\n\n if(!(file_exists($zipfile) && filesize($zipfile)>0 && file_exists($destination))){\n throw new \\Exception('Archive file not found');\n }\n\n $root_folder = $system->getFileStoreRootFolder();\n chdir($root_folder);\n $root_folder = realpath($root_folder);\n\n if (strpos($root_folder, '\\\\')!==false){\n $root_folder = str_replace('\\\\','/',$root_folder);\n }\n\n //set current folder\n chdir($destination);// relatively db root or HEURIST_FILES_DIR??\n $destination_dir = realpath($destination);\n\n if ($destination_dir !== false) {\n if (strpos($destination_dir, '\\\\')!==false){\n $destination_dir = str_replace('\\\\','/',$destination_dir);\n }\n if( substr($destination_dir, -1, 1) != '/' ){\n $destination_dir = $destination_dir.'/';\n }\n if (strpos($destination_dir, $root_folder) !== 0) {\n //HEURIST_SCRATCH_DIR\n //HEURIST_TILESTACKS_DIR\n throw new \\Exception('Destination folder must within database storage folder ');//$destination_dir.' '.$root_folder\n }\n }\n\n $fileCount = 0;\n $totalSize = 0;\n\n $zip = new \\ZipArchive();\n if ($zip->open($zipfile) === true) {\n for ($i = 0; $i < $zip->numFiles; $i++) {\n $filename = $zip->getNameIndex($i);\n $stats = $zip->statIndex($i);\n\n if (strpos($filename, '../') !== false || substr($filename, 0, 1) === '/') {\n throw new \\Exception('Archive contains unsecure entry '.$filename);\n }\n\n if (substr($filename, -1) !== '/') {\n $fileCount++;\n if ($fileCount > MAX_FILES) {\n // Reached max. number of files\n throw new \\Exception('Archive contains more than '.MAX_FILES.' entries');\n }\n\n $destination_file = $destination_dir.$filename;\n\n $fp = $zip->getStream($filename);// Compliant\n $currentSize = 0;\n while (!feof($fp)) {\n $currentSize += READ_LENGTH;\n $totalSize += READ_LENGTH;\n\n if ($totalSize > MAX_SIZE) {\n // Reached max. size\n throw new \\Exception('Maximum allowed extraction size achieved ('.MAX_SIZE.')');\n }\n\n // Additional protection: check compression ratio\n if ($stats['comp_size'] > 0 && $stats['comp_size']>READ_LENGTH) {\n $ratio = floor($currentSize / $stats['comp_size']);\n if ($ratio > MAX_RATIO) {\n // Reached max. compression ratio\n throw new \\Exception('Maximum allowed compression ration detected ('.$ratio.' > '.MAX_RATIO.')');\n }\n }\n\n file_put_contents($destination_file, fread($fp, READ_LENGTH), FILE_APPEND);\n }\n\n fclose($fp);\n } else {\n if (!file_exists($destination_dir.$filename) && !mkdir($destination_dir.$filename, 0777, true)) {\n throw new \\Exception('Cannot create subfolder on unzip');\n }\n }\n }\n $zip->close();\n }\n\n return $fileCount;\n\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function (string $projectId, int $limit, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $auths = $project->getAttribute('auths', []);\n $auths['maxSessions'] = $limit;\n\n $dbForConsole->updateDocument('projects', $project->getId(), $project\n ->setAttribute('auths', $auths));\n\n $response->dynamic($project, Response::MODEL_PROJECT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (Document $user, Response $response, Document $project, Database $dbForConsole, Request $request) {\n $firebase = new OAuth2Firebase(\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),\n $request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'\n );\n\n $identity = $dbForConsole->findOne('identities', [\n Query::equal('provider', ['firebase']),\n Query::equal('userInternalId', [$user->getInternalId()]),\n ]);\n\n if ($identity === false || $identity->isEmpty()) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $accessToken = $identity->getAttribute('providerAccessToken');\n $refreshToken = $identity->getAttribute('providerRefreshToken');\n $accessTokenExpiry = $identity->getAttribute('providerAccessTokenExpiry');\n\n if (empty($accessToken) || empty($refreshToken) || empty($accessTokenExpiry)) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n if (App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n try {\n $isExpired = new \\DateTime($accessTokenExpiry) < new \\DateTime('now');\n if ($isExpired) {\n try {\n $firebase->refreshTokens($refreshToken);\n } catch (\\Exception $e) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $accessToken = $firebase->getAccessToken('');\n $refreshToken = $firebase->getRefreshToken('');\n\n $verificationId = $firebase->getUserID($accessToken);\n\n if (empty($verificationId)) {\n throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED, 'Another request is currently refreshing OAuth token. Please try again.');\n }\n\n $identity = $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$firebase->getAccessTokenExpiry('')));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n }\n\n $projects = $firebase->getProjects($accessToken);\n\n $output = [];\n foreach ($projects as $project) {\n $output[] = [\n 'displayName' => $project['displayName'],\n 'projectId' => $project['projectId'],\n ];\n }\n } catch (\\Exception $e) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $response->dynamic(new Document([\n 'projects' => $output,\n 'total' => count($output),\n ]), Response::MODEL_MIGRATION_FIREBASE_PROJECT_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $projectId, string $method, bool $status, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n $auth = Config::getParam('auth')[$method] ?? [];\n $authKey = $auth['key'] ?? '';\n $status = ($status === '1' || $status === 'true' || $status === 1 || $status === true);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $auths = $project->getAttribute('auths', []);\n $auths[$authKey] = $status;\n\n $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('auths', $auths));\n\n $response->dynamic($project, Response::MODEL_PROJECT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function updateGridConfigFavourites(?GridConfig $gridConfig, array $metadata): void\n {\n $currentUser = $this->getAdminUser();\n\n if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }\n\n if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n\n $sharedUsers = [];\n\n if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];\n\n if ($sharedUserIds) {\n $sharedUsers = array_map('intval', explode(',', $sharedUserIds));\n }\n }\n\n if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());\n\n foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }\n\n foreach ($sharedUsers as $id) {\n // Check if the user has already a favourite\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );\n\n if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());\n\n if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ($favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }\n\n // Check if the user is the owner. If that is the case we do not update the favourite\n if ($favouriteGridConfig->getOwnerId() === $id) {\n continue;\n }\n }\n }\n\n $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId(0);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function __construct($account = null, $user = null, $password = null, $key = null)\n {\n // set credentials, default timeout\n $this->setCredentials($account, $user, $password, $key);\n $this->timeout = EtherFaxClient::DEFAULT_TIMEOUT;\n if (empty($GLOBALS['oefax_enable_fax'] ?? null)) {\n throw new \\RuntimeException(xlt(\"Access denied! Module not enabled\"));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (string $projectId, string $type, string $locale, Response $response, Database $dbForConsole) {\n\n throw new Exception(Exception::GENERAL_NOT_IMPLEMENTED);\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $templates = $project->getAttribute('templates', []);\n $template = $templates['sms.' . $type . '-' . $locale] ?? null;\n\n if (is_null($template)) {\n throw new Exception(Exception::PROJECT_TEMPLATE_DEFAULT_DELETION);\n }\n\n unset($template['sms.' . $type . '-' . $locale]);\n\n $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('templates', $templates));\n\n $response->dynamic(new Document([\n 'type' => $type,\n 'locale' => $locale,\n 'message' => $template['message']\n ]), Response::MODEL_SMS_TEMPLATE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function resolveController(mixed $controller): callable\n {\n if (\\is_object($controller) || \\is_callable($controller)) {\n // Nothing to do, already set.\n return $controller;\n }\n\n if (\\is_array($controller)) {\n [$class, $method] = $controller;\n } elseif (\\str_contains($controller, ':')) {\n [$class, $method] = \\preg_split('~:+~', $controller, 2);\n } else {\n $class = $controller;\n $method = null;\n }\n\n if (!$class || !\\is_string($class)) {\n throw new \\RuntimeException('Wrongly formed controller array');\n }\n\n if (!$this->plugin_container->has($class)) {\n throw new \\RuntimeException(\\sprintf(\n 'Expected controller class `%s` to be a public service, but did not find it in the service container.'\n . ' You should either implement the `%s` interface, or extend the `%s` abstract class.',\n $class,\n PublicService::class,\n AbstractController::class\n ));\n }\n\n try {\n // Try to instantiate without any parameters\n $object = new $class();\n } catch (\\Error) {\n // Try to load the service from the DI container\n $object = $this->plugin_container->get($class);\n }\n\n if (!\\is_callable($object)) {\n return \\sprintf(\n 'Controller class `%s` cannot be called without a method name. You need to implement the `__invoke()` method, or add your route parameters on a public method with the `Route` attribute.',\n $class\n );\n }\n\n return $method ? [$object, $method] : $object;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function sendTemplate($pids, $templates, $category = null): int\n {\n $result = 0;\n sqlStatementNoLog('SET autocommit=0');\n sqlStatementNoLog('START TRANSACTION');\n try {\n foreach ($templates as $id => $profile) {\n $template = $this->fetchTemplate($id);\n $destination_category = $template['category'];\n if ($destination_category === 'repository') {\n $destination_category = $category;\n }\n $content = $template['template_content'];\n $name = $template['template_name'];\n foreach ($pids as $pid) {\n $result = $this->insertTemplate($pid, $destination_category, $name, $content, $template['mime'], $profile);\n }\n }\n } catch (Exception $e) {\n throw new RuntimeException($e->getMessage(), $e->getCode(), $e);\n }\n sqlStatementNoLog('COMMIT');\n sqlStatementNoLog('SET autocommit=1');\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function doGetGridColumnConfig(Request $request, Config $config, bool $isDelete = false): array\n {\n $class = null;\n $fields = null;\n\n if ($request->get('id')) {\n $class = DataObject\\ClassDefinition::getById($request->get('id'));\n } elseif ($request->get('name')) {\n $class = DataObject\\ClassDefinition::getByName($request->get('name'));\n }\n\n $gridConfigId = null;\n $gridType = 'search';\n if ($request->get('gridtype')) {\n $gridType = $request->get('gridtype');\n }\n\n $objectId = (int) $request->get('objectId');\n\n if ($objectId) {\n $fields = DataObject\\Service::getCustomGridFieldDefinitions($class->getId(), $objectId);\n }\n\n $context = ['purpose' => 'gridconfig'];\n if ($class) {\n $context['class'] = $class;\n }\n\n if ($objectId) {\n $object = DataObject::getById($objectId);\n $context['object'] = $object;\n }\n\n if (!$fields && $class) {\n $fields = $class->getFieldDefinitions();\n }\n\n $types = [];\n if ($request->get('types')) {\n $types = explode(',', $request->get('types'));\n }\n\n $userId = $this->getAdminUser()->getId();\n\n $requestedGridConfigId = $isDelete ? null : $request->get('gridConfigId');\n\n // grid config\n $gridConfig = [];\n $searchType = $request->get('searchType');\n\n if (strlen($requestedGridConfigId ?? '') == 0 && $class) {\n // check if there is a favourite view\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), $objectId ?: 0, $searchType);\n if (!$favourite && $objectId) {\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), 0, $searchType);\n }\n\n if ($favourite) {\n $requestedGridConfigId = $favourite->getGridConfigId();\n }\n }\n\n if (is_numeric($requestedGridConfigId) && $requestedGridConfigId > 0) {\n $db = Db::get();\n $savedGridConfig = GridConfig::getById((int) $requestedGridConfigId);\n\n if ($savedGridConfig) {\n $shared = false;\n if (!$this->getAdminUser()->isAdmin()) {\n $userIds = [$this->getAdminUser()->getId()];\n $userIds = array_merge($userIds, $this->getAdminUser()->getRoles());\n $userIds = implode(',', $userIds);\n $shared = ($savedGridConfig->getOwnerId() != $userId && $savedGridConfig->isShareGlobally()) || $db->fetchOne('select 1 from gridconfig_shares where sharedWithUserId IN ('.$userIds.') and gridConfigId = '.$savedGridConfig->getId());\n // $shared = $savedGridConfig->isShareGlobally() || GridConfigShare::getByGridConfigAndSharedWithId($savedGridConfig->getId(), $this->getUser()->getId());\n\n if (!$shared && $savedGridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception('You are neither the owner of this config nor it is shared with you');\n }\n }\n\n $gridConfigId = $savedGridConfig->getId();\n $gridConfig = $savedGridConfig->getConfig();\n $gridConfig = json_decode($gridConfig, true);\n $gridConfigName = SecurityHelper::convertHtmlSpecialChars($savedGridConfig->getName());\n $owner = $savedGridConfig->getOwnerId();\n $ownerObject = User::getById($owner);\n if ($ownerObject instanceof User) {\n $owner = $ownerObject->getName();\n }\n $modificationDate = $savedGridConfig->getModificationDate();\n $gridConfigDescription = SecurityHelper::convertHtmlSpecialChars($savedGridConfig->getDescription());\n $sharedGlobally = $savedGridConfig->isShareGlobally();\n $setAsFavourite = $savedGridConfig->isSetAsFavourite();\n $saveFilters = $savedGridConfig->isSaveFilters();\n\n foreach ($gridConfig['columns'] as &$column) {\n if (array_key_exists('isOperator', $column) && $column['isOperator']) {\n $colAttributes = &$column['fieldConfig']['attributes'];\n SecurityHelper::convertHtmlSpecialCharsArrayKeys($colAttributes, ['label', 'attribute', 'param1']);\n }\n }\n }\n }\n\n $localizedFields = [];\n $objectbrickFields = [];\n if (is_array($fields)) {\n foreach ($fields as $key => $field) {\n if ($field instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedFields[] = $field;\n } elseif ($field instanceof DataObject\\ClassDefinition\\Data\\Objectbricks) {\n $objectbrickFields[] = $field;\n }\n }\n }\n\n $availableFields = [];\n\n if (empty($gridConfig)) {\n $availableFields = $this->getDefaultGridFields(\n $request->query->getBoolean('no_system_columns'),\n $class,\n $gridType,\n $request->query->getBoolean('no_brick_columns'),\n $fields,\n $context,\n $objectId,\n $types\n );\n } else {\n $savedColumns = $gridConfig['columns'];\n foreach ($savedColumns as $key => $sc) {\n if (!$sc['hidden']) {\n if (in_array($key, self::SYSTEM_COLUMNS)) {\n $colConfig = [\n 'key' => $key,\n 'type' => 'system',\n 'label' => $key,\n 'position' => $sc['position'],\n ];\n $this->injectCustomLayoutValues($colConfig, $sc);\n $availableFields[] = $colConfig;\n } else {\n $keyParts = explode('~', $key);\n\n if (substr($key, 0, 1) == '~') {\n // not needed for now\n $type = $keyParts[1];\n // $field = $keyParts[2];\n $groupAndKeyId = explode('-', $keyParts[3]);\n $keyId = (int) $groupAndKeyId[1];\n\n if ($type == 'classificationstore') {\n $keyDef = DataObject\\Classificationstore\\KeyConfig::getById($keyId);\n if ($keyDef) {\n $keyFieldDef = json_decode($keyDef->getDefinition(), true);\n if ($keyFieldDef) {\n $keyFieldDef = \\Pimcore\\Model\\DataObject\\Classificationstore\\Service::getFieldDefinitionFromJson($keyFieldDef, $keyDef->getType());\n $fieldConfig = $this->getFieldGridConfig($keyFieldDef, $gridType, (string)$sc['position'], true, null, $class, $objectId);\n if ($fieldConfig) {\n $fieldConfig['key'] = $key;\n $fieldConfig['label'] = '#' . $keyFieldDef->getTitle();\n $fieldConfig = $this->injectCustomLayoutValues($fieldConfig, $sc);\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n } elseif (count($keyParts) > 1) {\n $brick = $keyParts[0];\n $brickDescriptor = null;\n\n if (strpos($brick, '?') !== false) {\n $brickDescriptor = substr($brick, 1);\n $brickDescriptor = json_decode($brickDescriptor, true);\n $keyPrefix = $brick . '~';\n $brick = $brickDescriptor['containerKey'];\n } else {\n $keyPrefix = $brick . '~';\n }\n\n $fieldname = $keyParts[1];\n\n $brickClass = DataObject\\Objectbrick\\Definition::getByKey($brick);\n\n $fd = null;\n if ($brickClass instanceof DataObject\\Objectbrick\\Definition) {\n if ($brickDescriptor) {\n $innerContainer = $brickDescriptor['innerContainer'] ?? 'localizedfields';\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $localizedFields */\n $localizedFields = $brickClass->getFieldDefinition($innerContainer);\n $fd = $localizedFields->getFieldDefinition($brickDescriptor['brickfield']);\n } else {\n $fd = $brickClass->getFieldDefinition($fieldname);\n }\n }\n\n if ($fd !== null) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, (string)$sc['position'], true, $keyPrefix, $class, $objectId);\n if (!empty($fieldConfig)) {\n $fieldConfig = $this->injectCustomLayoutValues($fieldConfig, $sc);\n $availableFields[] = $fieldConfig;\n }\n }\n } else {\n if (DataObject\\Service::isHelperGridColumnConfig($key)) {\n $calculatedColumnConfig = $this->getCalculatedColumnConfig($request, $savedColumns[$key]);\n if ($calculatedColumnConfig) {\n $availableFields[] = $calculatedColumnConfig;\n }\n } else {\n $fd = $class->getFieldDefinition($key);\n //if not found, look for localized fields\n if (empty($fd)) {\n foreach ($localizedFields as $lf) {\n $fd = $lf->getFieldDefinition($key);\n if (!empty($fd)) {\n break;\n }\n }\n }\n\n if (!empty($fd)) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, (string)$sc['position'], true, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $fieldConfig = $this->injectCustomLayoutValues($fieldConfig, $sc);\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n }\n }\n }\n }\n usort($availableFields, function ($a, $b) {\n if ($a['position'] == $b['position']) {\n return 0;\n }\n\n return ($a['position'] < $b['position']) ? -1 : 1;\n });\n\n $frontendLanguages = Tool\\Admin::reorderWebsiteLanguages(\\Pimcore\\Tool\\Admin::getCurrentUser(), $config['general']['valid_languages']);\n if ($frontendLanguages) {\n $language = $frontendLanguages[0];\n } else {\n $language = $request->getLocale();\n }\n\n if (!Tool::isValidLanguage($language)) {\n $validLanguages = Tool::getValidLanguages();\n $language = $validLanguages[0];\n }\n\n if (!empty($gridConfig) && !empty($gridConfig['language'])) {\n $language = $gridConfig['language'];\n }\n\n $availableConfigs = $class ? $this->getMyOwnGridColumnConfigs($userId, $class->getId(), $searchType) : [];\n $sharedConfigs = $class ? $this->getSharedGridColumnConfigs($this->getAdminUser(), $class->getId(), $searchType) : [];\n $settings = $this->getShareSettings((int)$gridConfigId);\n $settings['gridConfigId'] = (int)$gridConfigId;\n $settings['gridConfigName'] = $gridConfigName ?? null;\n $settings['gridConfigDescription'] = $gridConfigDescription ?? null;\n $settings['owner'] = $owner ?? null;\n $settings['modificationDate'] = $modificationDate ?? null;\n $settings['shareGlobally'] = $sharedGlobally ?? null;\n $settings['setAsFavourite'] = $setAsFavourite ?? null;\n $settings['saveFilters'] = $saveFilters ?? null;\n $settings['isShared'] = !$gridConfigId || ($shared ?? null);\n $settings['allowVariants'] = $class && $class->getAllowVariants();\n\n $context = $gridConfig['context'] ?? null;\n if ($context) {\n $context = json_decode($context, true);\n }\n\n return [\n 'sortinfo' => $gridConfig['sortinfo'] ?? false,\n 'language' => $language,\n 'availableFields' => $availableFields,\n 'settings' => $settings,\n 'onlyDirectChildren' => $gridConfig['onlyDirectChildren'] ?? false,\n 'pageSize' => $gridConfig['pageSize'] ?? false,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n 'context' => $context,\n 'searchFilter' => $gridConfig['searchFilter'] ?? '',\n 'filter' => $gridConfig['filter'] ?? [],\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function __construct($params) {\n\t\tif (!isset($params['host'])) {\n\t\t\tthrow new \\Exception('Invalid configuration, no host provided');\n\t\t}\n\n\t\tif (isset($params['auth'])) {\n\t\t\t$auth = $params['auth'];\n\t\t} elseif (isset($params['user']) && isset($params['password']) && isset($params['share'])) {\n\t\t\t[$workgroup, $user] = $this->splitUser($params['user']);\n\t\t\t$auth = new BasicAuth($user, $workgroup, $params['password']);\n\t\t} else {\n\t\t\tthrow new \\Exception('Invalid configuration, no credentials provided');\n\t\t}\n\n\t\tif (isset($params['logger'])) {\n\t\t\tif (!$params['logger'] instanceof LoggerInterface) {\n\t\t\t\tthrow new \\Exception(\n\t\t\t\t\t'Invalid logger. Got '\n\t\t\t\t\t. get_class($params['logger'])\n\t\t\t\t\t. ' Expected ' . LoggerInterface::class\n\t\t\t\t);\n\t\t\t}\n\t\t\t$this->logger = $params['logger'];\n\t\t} else {\n\t\t\t$this->logger = \\OC::$server->get(LoggerInterface::class);\n\t\t}\n\n\t\t$options = new Options();\n\t\tif (isset($params['timeout'])) {\n\t\t\t$timeout = (int)$params['timeout'];\n\t\t\tif ($timeout > 0) {\n\t\t\t\t$options->setTimeout($timeout);\n\t\t\t}\n\t\t}\n\t\t$serverFactory = new ServerFactory($options);\n\t\t$this->server = $serverFactory->createServer($params['host'], $auth);\n\t\t$this->share = $this->server->getShare(trim($params['share'], '/'));\n\n\t\t$this->root = $params['root'] ?? '/';\n\t\t$this->root = '/' . ltrim($this->root, '/');\n\t\t$this->root = rtrim($this->root, '/') . '/';\n\n\t\t$this->showHidden = isset($params['show_hidden']) && $params['show_hidden'];\n\t\t$this->caseSensitive = (bool) ($params['case_sensitive'] ?? true);\n\t\t$this->checkAcl = isset($params['check_acl']) && $params['check_acl'];\n\n\t\t$this->statCache = new CappedMemoryCache();\n\t\tparent::__construct($params);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function updateGridConfigShares(?GridConfig $gridConfig, array $metadata): void\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }\n\n if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];\n\n if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }\n\n if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }\n\n $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);\n\n foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $migrationId, Response $response, Database $dbForProject) {\n $migration = $dbForProject->getDocument('migrations', $migrationId);\n\n if ($migration->isEmpty()) {\n throw new Exception(Exception::MIGRATION_NOT_FOUND);\n }\n\n $response->dynamic($migration, Response::MODEL_MIGRATION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function dataGetAppIcon(): array {\n\t\t$nothing = function ($appId) {\n\t\t\t$this->assertEquals('test', $appId);\n\t\t\tthrow new \\RuntimeException();\n\t\t};\n\n\t\t$createCallback = function ($workingIcons) {\n\t\t\treturn function ($appId, $icon) use ($workingIcons) {\n\t\t\t\t$this->assertEquals('test', $appId);\n\t\t\t\tif (in_array($icon, $workingIcons)) {\n\t\t\t\t\treturn '/path/' . $icon;\n\t\t\t\t}\n\t\t\t\tthrow new \\RuntimeException();\n\t\t\t};\n\t\t};\n\n\t\treturn [\n\t\t\t'does not find anything' => [\n\t\t\t\t$nothing,\n\t\t\t\tfalse,\n\t\t\t\tnull,\n\t\t\t],\n\t\t\t'nothing if request dark but only bright available' => [\n\t\t\t\t$createCallback(['app.svg']),\n\t\t\t\ttrue,\n\t\t\t\tnull,\n\t\t\t],\n\t\t\t'nothing if request bright but only dark available' => [\n\t\t\t\t$createCallback(['app-dark.svg']),\n\t\t\t\tfalse,\n\t\t\t\tnull,\n\t\t\t],\n\t\t\t'bright and only app.svg' => [\n\t\t\t\t$createCallback(['app.svg']),\n\t\t\t\tfalse,\n\t\t\t\t'/path/app.svg',\n\t\t\t],\n\t\t\t'dark and only app-dark.svg' => [\n\t\t\t\t$createCallback(['app-dark.svg']),\n\t\t\t\ttrue,\n\t\t\t\t'/path/app-dark.svg',\n\t\t\t],\n\t\t\t'dark only appname -dark.svg' => [\n\t\t\t\t$createCallback(['test-dark.svg']),\n\t\t\t\ttrue,\n\t\t\t\t'/path/test-dark.svg',\n\t\t\t],\n\t\t\t'bright and only appname.svg' => [\n\t\t\t\t$createCallback(['test.svg']),\n\t\t\t\tfalse,\n\t\t\t\t'/path/test.svg',\n\t\t\t],\n\t\t\t'priotize custom over default' => [\n\t\t\t\t$createCallback(['app.svg', 'test.svg']),\n\t\t\t\tfalse,\n\t\t\t\t'/path/test.svg',\n\t\t\t],\n\t\t\t'defaults to bright' => [\n\t\t\t\t$createCallback(['test-dark.svg', 'test.svg']),\n\t\t\t\tnull,\n\t\t\t\t'/path/test.svg',\n\t\t\t],\n\t\t\t'no dark icon on default' => [\n\t\t\t\t$createCallback(['test-dark.svg', 'test.svg', 'app-dark.svg', 'app.svg']),\n\t\t\t\tfalse,\n\t\t\t\t'/path/test.svg',\n\t\t\t],\n\t\t\t'no bright icon on dark' => [\n\t\t\t\t$createCallback(['test-dark.svg', 'test.svg', 'app-dark.svg', 'app.svg']),\n\t\t\t\ttrue,\n\t\t\t\t'/path/test-dark.svg',\n\t\t\t],\n\t\t];\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function checkFallbackLanguageLoop(string $source, array $definitions, array $fallbacks = []): void\n {\n if (isset($definitions[$source])) {\n $targets = explode(',', $definitions[$source]);\n foreach ($targets as $l) {\n $target = trim($l);\n if ($target) {\n if (in_array($target, $fallbacks)) {\n throw new Exception(\"Language `$source` | `$target` causes an infinte loop.\");\n }\n $fallbacks[] = $target;\n\n $this->checkFallbackLanguageLoop($target, $definitions, $fallbacks);\n }\n }\n } else {\n throw new Exception(\"Language `$source` doesn't exist\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getVersion($versionSpec) {\n\t\t// * indicates that the version is compatible with all versions\n\t\tif ($versionSpec === '*') {\n\t\t\treturn new Version('', '');\n\t\t}\n\n\t\t// Count the amount of =, if it is one then it's either maximum or minimum\n\t\t// version. If it is two then it is maximum and minimum.\n\t\t$versionElements = explode(' ', $versionSpec);\n\t\t$firstVersion = $versionElements[0] ?? '';\n\t\t$firstVersionNumber = substr($firstVersion, 2);\n\t\t$secondVersion = $versionElements[1] ?? '';\n\t\t$secondVersionNumber = substr($secondVersion, 2);\n\n\t\tswitch (count($versionElements)) {\n\t\t\tcase 1:\n\t\t\t\tif (!$this->isValidVersionString($firstVersionNumber)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (str_starts_with($firstVersion, '>')) {\n\t\t\t\t\treturn new Version($firstVersionNumber, '');\n\t\t\t\t}\n\t\t\t\treturn new Version('', $firstVersionNumber);\n\t\t\tcase 2:\n\t\t\t\tif (!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn new Version($firstVersionNumber, $secondVersionNumber);\n\t\t}\n\n\t\tthrow new \\Exception(\n\t\t\tsprintf(\n\t\t\t\t'Version cannot be parsed: %s',\n\t\t\t\t$versionSpec\n\t\t\t)\n\t\t);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function create(\\OCP\\Share\\IShare $share) {\n\t\t$qb = $this->dbConn->getQueryBuilder();\n\n\t\t$qb->insert('share');\n\t\t$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));\n\n\t\t$expirationDate = $share->getExpirationDate();\n\t\tif ($expirationDate !== null) {\n\t\t\t$expirationDate = clone $expirationDate;\n\t\t\t$expirationDate->setTimezone(new \\DateTimeZone(date_default_timezone_get()));\n\t\t}\n\n\t\tif ($share->getShareType() === IShare::TYPE_USER) {\n\t\t\t//Set the UID of the user we share with\n\t\t\t$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));\n\t\t\t$qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));\n\n\t\t\t//If an expiration date is set store it\n\t\t\tif ($expirationDate !== null) {\n\t\t\t\t$qb->setValue('expiration', $qb->createNamedParameter($expirationDate, 'datetime'));\n\t\t\t}\n\t\t} elseif ($share->getShareType() === IShare::TYPE_GROUP) {\n\t\t\t//Set the GID of the group we share with\n\t\t\t$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));\n\n\t\t\t//If an expiration date is set store it\n\t\t\tif ($expirationDate !== null) {\n\t\t\t\t$qb->setValue('expiration', $qb->createNamedParameter($expirationDate, 'datetime'));\n\t\t\t}\n\t\t} elseif ($share->getShareType() === IShare::TYPE_LINK) {\n\t\t\t//set label for public link\n\t\t\t$qb->setValue('label', $qb->createNamedParameter($share->getLabel()));\n\t\t\t//Set the token of the share\n\t\t\t$qb->setValue('token', $qb->createNamedParameter($share->getToken()));\n\n\t\t\t//If a password is set store it\n\t\t\tif ($share->getPassword() !== null) {\n\t\t\t\t$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));\n\t\t\t}\n\n\t\t\t$qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));\n\n\t\t\t//If an expiration date is set store it\n\t\t\tif ($expirationDate !== null) {\n\t\t\t\t$qb->setValue('expiration', $qb->createNamedParameter($expirationDate, 'datetime'));\n\t\t\t}\n\n\t\t\tif (method_exists($share, 'getParent')) {\n\t\t\t\t$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));\n\t\t\t}\n\n\t\t\t$qb->setValue('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0, IQueryBuilder::PARAM_INT));\n\t\t} else {\n\t\t\tthrow new \\Exception('invalid share type!');\n\t\t}\n\n\t\t// Set what is shares\n\t\t$qb->setValue('item_type', $qb->createParameter('itemType'));\n\t\tif ($share->getNode() instanceof \\OCP\\Files\\File) {\n\t\t\t$qb->setParameter('itemType', 'file');\n\t\t} else {\n\t\t\t$qb->setParameter('itemType', 'folder');\n\t\t}\n\n\t\t// Set the file id\n\t\t$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));\n\t\t$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));\n\n\t\t// set the permissions\n\t\t$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));\n\n\t\t// set share attributes\n\t\t$shareAttributes = $this->formatShareAttributes(\n\t\t\t$share->getAttributes()\n\t\t);\n\t\t$qb->setValue('attributes', $qb->createNamedParameter($shareAttributes));\n\n\t\t// Set who created this share\n\t\t$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));\n\n\t\t// Set who is the owner of this file/folder (and this the owner of the share)\n\t\t$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));\n\n\t\t// Set the file target\n\t\t$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));\n\n\t\tif ($share->getNote() !== '') {\n\t\t\t$qb->setValue('note', $qb->createNamedParameter($share->getNote()));\n\t\t}\n\n\t\t// Set the time this share was created\n\t\t$shareTime = $this->timeFactory->now();\n\t\t$qb->setValue('stime', $qb->createNamedParameter($shareTime->getTimestamp()));\n\n\t\t// insert the data and fetch the id of the share\n\t\t$qb->executeStatement();\n\n\t\t// Update mandatory data\n\t\t$id = $qb->getLastInsertId();\n\t\t$share->setId((string)$id);\n\t\t$share->setProviderId($this->identifier());\n\n\t\t$share->setShareTime(\\DateTime::createFromImmutable($shareTime));\n\n\t\t$mailSendValue = $share->getMailSend();\n\t\t$share->setMailSend(($mailSendValue === null) ? true : $mailSendValue);\n\n\t\treturn $share;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function readMpegFrame($fp) {\n $header_seek_pos = ftell($fp) + self::$headerSeekLimit;\n do {\n $pos = ftell($fp);\n $first_header_byte = $this->readBytes($fp, 1);\n if ($first_header_byte[0] === 0xFF) {\n $second_header_byte = $this->readBytes($fp, 1);\n if ((($second_header_byte[0] >> 5) & 0b111) == 0b111) {\n fseek($fp, $pos);\n $header_bytes = $this->readBytes($fp, 4);\n break;\n }\n }\n fseek($fp, 1, SEEK_CUR);\n } while (ftell($fp) <= $header_seek_pos);\n\n if (!isset($header_bytes) || $header_bytes[0] !== 0xFF || (($header_bytes[1] >> 5) & 0b111) != 0b111) {\n throw new \\Exception('At '.$pos\n .'(0x'.dechex($pos).') should be a frame header!');\n }\n\n switch ($header_bytes[1] >> 3 & 0b11) {\n case 0b00: $this->codecVersion = self::MPEG_25; break;\n case 0b10: $this->codecVersion = self::MPEG_2; break;\n case 0b11: $this->codecVersion = self::MPEG_1; break;\n }\n\n switch ($header_bytes[1] >> 1 & 0b11) {\n case 0b01: $this->layerVersion = self::LAYER_3; break;\n case 0b10: $this->layerVersion = self::LAYER_2; break;\n case 0b11: $this->layerVersion = self::LAYER_1; break;\n }\n\n if (!isset($this->codecVersion) || !isset($this->layerVersion) || !isset($header_bytes[2])) {\n throw new \\Exception('Unrecognized codecVersion or layerVersion headers!');\n }\n $this->bitRate = self::$_bitRateTable[$this->codecVersion][$this->layerVersion][$header_bytes[2] >> 4];\n $this->sampleRate = self::$_sampleRateTable[$this->codecVersion][($header_bytes[2] >> 2) & 0b11];\n\n switch ($header_bytes[3] >> 6) {\n case 0b00: $this->channel = self::STEREO; break;\n case 0b01: $this->channel = self::JOINT_STEREO; break;\n case 0b10: $this->channel = self::DUAL_MONO; break;\n case 0b11: $this->channel = self::MONO; break;\n }\n\n if (!isset($this->channel)) {\n throw new \\Exception('Unrecognized channel header!');\n }\n $vbr_offset = self::$_vbrOffsets[$this->codecVersion][$this->channel == self::MONO ? 0 : 1];\n\n // check for VBR\n fseek($fp, $pos + $vbr_offset);\n if (fread($fp, 4) == self::VBR_SYNC) {\n $this->isVbr = true;\n $flagsBytes = $this->readBytes($fp, 4);\n\n // VBR frames count presence\n if (($flagsBytes[3] & 2)) {\n $this->vbrProperties['frames'] = implode(unpack('N', fread($fp, 4)));\n }\n // VBR stream size presence\n if ($flagsBytes[3] & 4) {\n $this->vbrProperties['bytes'] = implode(unpack('N', fread($fp, 4)));\n }\n // VBR TOC presence\n if ($flagsBytes[3] & 1) {\n fseek($fp, 100, SEEK_CUR);\n }\n // VBR quality\n if ($flagsBytes[3] & 8) {\n $this->vbrProperties['quality'] = implode(unpack('N', fread($fp, 4)));\n }\n }\n\n // go to the end of frame\n if ($this->layerVersion == self::LAYER_1) {\n $this->_cbrFrameSize = floor((12 * $this->bitRate / $this->sampleRate + ($header_bytes[2] >> 1 & 0b1)) * 4);\n } else {\n $this->_cbrFrameSize = floor(144 * $this->bitRate / $this->sampleRate + ($header_bytes[2] >> 1 & 0b1));\n }\n\n fseek($fp, $pos + $this->_cbrFrameSize);\n\n return isset($this->vbrProperties['frames']) ? $this->vbrProperties['frames'] : null;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function uploadCustomLogoAction(Request $request): JsonResponse\n {\n $logoFile = $request->files->get('Filedata');\n\n if (!$logoFile instanceof UploadedFile\n || !in_array($logoFile->guessExtension(), ['svg', 'png', 'jpg'])\n ) {\n throw new \\Exception('Unsupported file format.');\n }\n\n $storage = Tool\\Storage::get('admin');\n $storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($logoFile->getPathname(), 'rb'));\n\n // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n\n $response = $this->adminJson(['success' => true]);\n $response->headers->set('Content-Type', 'text/html');\n\n return $response;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $projectId, string $webhookId, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $webhook = $dbForConsole->findOne('webhooks', [\n Query::equal('$id', [$webhookId]),\n Query::equal('projectInternalId', [$project->getInternalId()]),\n ]);\n\n if ($webhook === false || $webhook->isEmpty()) {\n throw new Exception(Exception::WEBHOOK_NOT_FOUND);\n }\n\n $response->dynamic($webhook, Response::MODEL_WEBHOOK);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function theCaldavResponseShouldContainAProperty(string $key): void {\n\t\t/** @var \\Sabre\\DAV\\Xml\\Response\\MultiStatus $multiStatus */\n\t\t$multiStatus = $this->responseXml['value'];\n\t\t$responses = $multiStatus->getResponses()[0]->getResponseProperties();\n\t\tif (!isset($responses[200])) {\n\t\t\tthrow new \\Exception(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Expected code 200 got [%s]',\n\t\t\t\t\timplode(',', array_keys($responses)),\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\t$props = $responses[200];\n\t\tif (!array_key_exists($key, $props)) {\n\t\t\tthrow new \\Exception(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Expected property %s in %s',\n\t\t\t\t\t$key,\n\t\t\t\t\tjson_encode($props, JSON_PRETTY_PRINT),\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getId($idx)\n {\n if (isset( $this->_ids[$idx] ) || array_key_exists($idx, $this->_ids) ) {\n return $this->_ids[$idx];\n }\n\n throw new \\Exception(\n get_class($this) . \":getId( idx = $idx ) not found\"\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function getStrippedCiphertextStream(\n StreamInterface $cipherText,\n $tagLength\n ) {\n $cipherTextSize = $cipherText->getSize();\n if ($cipherTextSize == null || $cipherTextSize <= 0) {\n throw new \\RuntimeException('Cannot decrypt a stream of unknown'\n . ' size.');\n }\n return new LimitStream(\n $cipherText,\n $cipherTextSize - $tagLength,\n 0\n );\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function renderContent(Content $content, $viewType = ViewManagerInterface::VIEW_TYPE_FULL, $parameters = [])\n {\n $view = new ContentView(null, $parameters, $viewType);\n $view->setContent($content);\n if (isset($parameters['location'])) {\n $view->setLocation($parameters['location']);\n }\n\n $this->viewConfigurator->configure($view);\n\n if ($view->getTemplateIdentifier() === null) {\n throw new RuntimeException('Unable to find a template for #' . $content->contentInfo->id);\n }\n\n return $this->renderContentView($view, $parameters);\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function savePatientGroupsByProfile($profile_groups): bool\n {\n sqlStatementNoLog('SET autocommit=0');\n sqlStatementNoLog('START TRANSACTION');\n\n try {\n sqlQuery('DELETE From `document_template_profiles` WHERE `template_id` = 0');\n $sql = 'INSERT INTO `document_template_profiles` (`id`, `template_id`, `profile`, `template_name`, `category`, `provider`, `modified_date`, `member_of`, `active`) VALUES (NULL, 0, ?, \"\", \"Group\", ?, current_timestamp(), ?, ?)';\n\n foreach ($profile_groups as $profile => $groups) {\n foreach ($groups as $group) {\n $rtn = sqlInsert($sql, array($profile, $_SESSION['authUserID'] ?? null, $group['group'] ?? '', $group['active']));\n }\n }\n } catch (Exception $e) {\n throw new RuntimeException($e->getMessage(), $e->getCode(), $e);\n }\n sqlStatementNoLog('COMMIT');\n sqlStatementNoLog('SET autocommit=1');\n\n return $rtn ?? 0;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function getImageFieldIdentifier(string $contentTypeIdentifier): string\n {\n $imageFieldIdentifier = $this->imageMappings[$contentTypeIdentifier]['imageFieldIdentifier'];\n if (null === $imageFieldIdentifier) {\n throw new RuntimeException(\n sprintf(\n 'Missing key imageFieldIdentifier for content type mapping \"%s\".',\n $contentTypeIdentifier\n )\n );\n }\n\n return $imageFieldIdentifier;\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "protected function GetCurrentUser()\n {\n if (! $this->_cu) {\n require_once(\"verysimple/Authentication/Authenticator.php\");\n\n $this->Phreezer->Observe(\"Loading CurrentUser from Session\");\n $this->_cu = Authenticator::GetCurrentUser($this->GUID);\n\n if ($this->_cu) {\n if (get_class($this->_cu) == \"__PHP_Incomplete_Class\") {\n // this happens if the class used for authentication was not included before the session was started\n $tmp = print_r($this->_cu, 1);\n $parts1 = explode(\"__PHP_Incomplete_Class_Name] => \", $tmp);\n $parts2 = explode(\"[\", $parts1 [1]);\n $name = trim($parts2 [0]);\n\n Authenticator::ClearAuthentication($this->GUID);\n throw new Exception(\"The class definition used for authentication '$name' must be defined (included) before the session is started, for example in _app_config.php.\");\n } else {\n // refresh the current user if the object supports it\n if (method_exists($this->_cu, 'Refresh')) {\n $this->_cu->Refresh($this->Phreezer);\n }\n }\n }\n } else {\n $this->Phreezer->Observe(\"Using previously loaded CurrentUser\");\n }\n\n return $this->_cu;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function createPortalOneTime(array $p, bool $encrypt_redirect = false): array|bool\n {\n $redirect_token = null;\n $passed_in_pid = $p['pid'] ?? 0;\n $valid = PatientPortalService::isValidPortalPatient($passed_in_pid);\n if (empty($valid['valid'] ?? null) || empty($passed_in_pid)) {\n throw new RuntimeException(xlt(\"Invalid Pid or patient not found!\"));\n }\n $email = ($valid['email'] ?? '') ?: ($p['email'] ?? '');\n $date_base = ($p['enabled_datetime'] ?? null) ?: 'NOW';\n $expiry = new DateTime($date_base);\n $expiry->add(new DateInterval($p['expiry_interval'] ?? 'PT15M'));\n $token_raw = RandomGenUtils::createUniqueToken(16);\n $token_encrypt = $this->cryptoGen->encryptStandard($token_raw);\n $pin = substr(str_shuffle(str_shuffle(\"0123456789\")), 0, 6);\n if (empty($p['pid']) || empty($token_raw)) {\n $err = xlt(\"Onetime failed with missing PID or the token creation failed\");\n $this->systemLogger->error($err);\n throw new RuntimeException($err);\n }\n\n $redirect_raw = trim($p['redirect_link'] ?? null);\n if (!empty($redirect_raw) && $encrypt_redirect) {\n $redirect_plus = js_escape(['pid' => $passed_in_pid, 'to' => $redirect_raw]);\n $redirect_token = $this->cryptoGen->encryptStandard($redirect_plus);\n if (empty($redirect_token)) {\n // since redirect should be in database we can continue.\n $this->systemLogger->error(xlt(\"Onetime redirect failed encryption.\"));\n }\n }\n if (!empty($p['target_link'] ?? null)) {\n $site_addr = trim($p['target_link']);\n } elseif ($this->context == 'portal') {\n $site_addr = trim($GLOBALS['portal_onsite_two_address']);\n } else {\n $err = xlt(\"Onetime creation failed. Missing site address!\");\n $this->systemLogger->error($err);\n throw new RuntimeException($err);\n }\n\n $rtn['encoded_link'] = $this->encodeLink($site_addr, $token_encrypt, $redirect_token);\n $rtn['onetime_token'] = $token_encrypt;\n $rtn['redirect_token'] = $redirect_token;\n $rtn['pin'] = $pin;\n $rtn['email'] = $email;\n\n $save = $this->insertOnetime($passed_in_pid, $pin, $token_raw, $redirect_raw, $expiry->format('U'));\n if (empty($save)) {\n $err = xlt(\"Onetime save failed!\");\n $this->systemLogger->error($err);\n throw new RuntimeException($err);\n }\n\n $this->systemLogger->debug(xlt(\"New standard onetime token created and saved successfully.\"));\n\n return $rtn;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function handle(\n CriteriaConverter $converter,\n QueryBuilder $queryBuilder,\n Criterion $criterion,\n array $languageSettings\n ) {\n $column = 't.is_invisible';\n\n switch ($criterion->value[0]) {\n case Criterion\\Visibility::VISIBLE:\n return $queryBuilder->expr()->eq(\n $column,\n $queryBuilder->createNamedParameter(0, ParameterType::INTEGER)\n );\n\n case Criterion\\Visibility::HIDDEN:\n return $queryBuilder->expr()->eq(\n $column,\n $queryBuilder->createNamedParameter(1, ParameterType::INTEGER)\n );\n\n default:\n throw new RuntimeException(\n \"Unknown value '{$criterion->value[0]}' for Visibility Criterion handler.\"\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "#[\\ReturnTypeWillChange]\n public function offsetSet($offset, $value)\n {\n throw new RuntimeException('Configuration is readonly');\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "protected function processKeyTransformers(stdClass $obj)\n {\n // Bail if there are no transformers to process\n\n if ( 0 == count($this->keyTransformers) ) {\n return $obj;\n }\n\n // Examine each key in the configuration object. If there is a transformer that\n // matches the key, transform the key and value.\n\n $replaceObjWithValue = false;\n foreach ( $obj as $key => &$value ) {\n\n // Examine all transformers\n\n foreach ( $this->keyTransformers as $transformer ) {\n\n $transformKey = $key;\n\n if ( ! $transformer->keyMatches($transformKey) ) {\n continue;\n }\n\n try {\n $stop = ( ! $transformer->transform($transformKey, $value, $obj, $this, Log::ERR) );\n } catch ( Exception $e ) {\n throw new Exception(sprintf(\"%s: %s\", $this->filename, $e->getMessage()));\n }\n\n if ( null === $transformKey && null === $value ) {\n\n // If the returned key and value are both null, remove the key/value\n // pair from the JSON.\n\n unset($obj->$key);\n\n } elseif ( null === $transformKey ) {\n\n // If the key is null but the value is set, replace the ENTIRE OBJECT\n // with the value.\n $replaceObjWithValue = true;\n\n } else {\n\n // If the key and value are both set replace them both (either may be\n // modified).\n\n if ( $transformKey != $key ) {\n unset($obj->$key);\n }\n $obj->$transformKey = $value;\n\n }\n\n if ( $stop ) {\n break;\n }\n\n }\n\n // A value can be an object, array, or salcar. The (possibly transformed)\n // value should now be examined for an objects that may need to be transformed\n // and recursively process any objects.\n\n if ( is_object($value) ) {\n $value = $this->processKeyTransformers($value);\n } elseif ( is_array($value) ) {\n\n // Arrays may contain objects or scalars. We are not handling the case\n // where an object may be deeply nested in an array.\n\n foreach ( $value as $index => &$element ) {\n if ( is_object($element) ) {\n $element = $this->processKeyTransformers($element);\n }\n }\n }\n\n if ($replaceObjWithValue) {\n return $value;\n }\n\n }\n\n return $obj;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function addHeader(\n $name,\n $content,\n ?HTMLTableSuperHeader $super = null,\n ?HTMLTableHeader $father = null\n ) {\n\n $this->tryAddHeader();\n if (is_null($super)) {\n if (!$this->super) {\n throw new \\Exception('A sub header requires a super header');\n }\n return $this->appendHeader(new HTMLTableSuperHeader(\n $this,\n $name,\n $content,\n $father\n ));\n }\n if ($this->super) {\n throw new \\Exception('Cannot attach a super header to another header');\n }\n return $this->appendHeader(new HTMLTableSubHeader($super, $name, $content, $father));\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getColumns(?stdClass $configuration): array\n {\n $sql = '';\n if ($configuration) {\n $sql = $this->buildQueryString($configuration);\n }\n\n if (!preg_match('/(ALTER|CREATE|DROP|RENAME|TRUNCATE|UPDATE|DELETE) /i', $sql, $matches)) {\n $sql .= ' LIMIT 0,1';\n $db = Db::get();\n $res = $db->fetchAssociative($sql);\n if ($res) {\n return array_keys($res);\n }\n\n return [];\n }\n\n throw new Exception(\"Only 'SELECT' statements are allowed! You've used '\" . $matches[0] . \"'\");\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject, EventDatabase $database, Event $events) {\n\n $db = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($db->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $attribute = $dbForProject->getDocument('attributes', $db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key);\n\n if ($attribute->isEmpty()) {\n throw new Exception(Exception::ATTRIBUTE_NOT_FOUND);\n }\n\n // Only update status if removing available attribute\n if ($attribute->getAttribute('status') === 'available') {\n $attribute = $dbForProject->updateDocument('attributes', $attribute->getId(), $attribute->setAttribute('status', 'deleting'));\n }\n\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId);\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId());\n\n if ($attribute->getAttribute('type') === Database::VAR_RELATIONSHIP) {\n $options = $attribute->getAttribute('options');\n if ($options['twoWay']) {\n $relatedCollection = $dbForProject->getDocument('database_' . $db->getInternalId(), $options['relatedCollection']);\n\n if ($relatedCollection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $relatedAttribute = $dbForProject->getDocument('attributes', $db->getInternalId() . '_' . $relatedCollection->getInternalId() . '_' . $options['twoWayKey']);\n\n if ($relatedAttribute->isEmpty()) {\n throw new Exception(Exception::ATTRIBUTE_NOT_FOUND);\n }\n\n if ($relatedAttribute->getAttribute('status') === 'available') {\n $dbForProject->updateDocument('attributes', $relatedAttribute->getId(), $relatedAttribute->setAttribute('status', 'deleting'));\n }\n\n $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $options['relatedCollection']);\n $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $relatedCollection->getInternalId());\n }\n }\n\n $database\n ->setType(DATABASE_TYPE_DELETE_ATTRIBUTE)\n ->setCollection($collection)\n ->setDatabase($db)\n ->setDocument($attribute);\n\n // Select response model based on type and format\n $type = $attribute->getAttribute('type');\n $format = $attribute->getAttribute('format');\n\n $model = match ($type) {\n Database::VAR_BOOLEAN => Response::MODEL_ATTRIBUTE_BOOLEAN,\n Database::VAR_INTEGER => Response::MODEL_ATTRIBUTE_INTEGER,\n Database::VAR_FLOAT => Response::MODEL_ATTRIBUTE_FLOAT,\n Database::VAR_DATETIME => Response::MODEL_ATTRIBUTE_DATETIME,\n Database::VAR_RELATIONSHIP => Response::MODEL_ATTRIBUTE_RELATIONSHIP,\n Database::VAR_STRING => match ($format) {\n APP_DATABASE_ATTRIBUTE_EMAIL => Response::MODEL_ATTRIBUTE_EMAIL,\n APP_DATABASE_ATTRIBUTE_ENUM => Response::MODEL_ATTRIBUTE_ENUM,\n APP_DATABASE_ATTRIBUTE_IP => Response::MODEL_ATTRIBUTE_IP,\n APP_DATABASE_ATTRIBUTE_URL => Response::MODEL_ATTRIBUTE_URL,\n default => Response::MODEL_ATTRIBUTE_STRING,\n },\n default => Response::MODEL_ATTRIBUTE,\n };\n\n $events\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('attributeId', $attribute->getId())\n ->setContext('collection', $collection)\n ->setContext('database', $db)\n ->setPayload($response->output($attribute, $model));\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function resolveParameters(ViewEvent $event, array $vars): array\n {\n $controllerArguments = $event->controllerArgumentsEvent?->getNamedArguments() ?? [];\n $controllerResults = is_array($event->getControllerResult()) ? $event->getControllerResult() : [];\n\n $mergedArray = array_merge(array_keys($controllerArguments), array_keys($controllerResults), array_keys($vars));\n $duplicateKeys = array_unique(array_diff_assoc($mergedArray, array_unique($mergedArray)));\n\n if ($duplicateKeys) {\n throw new Exception('Duplicate keys found: '.implode(', ', array_values($duplicateKeys)).'. Please use unique names for your controller arguments, controller results and template variables.');\n }\n\n return array_merge($controllerArguments, $controllerResults, $vars);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected static function removeUser($userId, $username)\n {\n $helper = new XdmodTestHelper();\n\n $helper->authenticateDashboard('mgr');\n $data = array(\n 'operation' => 'delete_user',\n 'uid' => $userId\n );\n\n $response = $helper->post('controllers/user_admin.php', null, $data);\n\n $expectedHttpCode = 200;\n $expectedContentType = 'application/json';\n\n $actualContentType = $response[1]['content_type'];\n $actualHttpCode = $response[1]['http_code'];\n if (strpos($actualContentType, $expectedContentType) === false) {\n throw new Exception(\"Expected content-type: $expectedContentType. Received: $actualContentType\");\n }\n if ($expectedHttpCode !== $actualHttpCode) {\n throw new Exception(\"Expected http code: $expectedHttpCode. Received: $actualHttpCode\");\n }\n\n $actualSuccess = (bool) $response[0]['success'];\n $actualMessage = $response[0]['message'];\n\n $actualSuccessMessage = $actualMessage ? 'true' : 'false';\n\n // Begin determining if the response was as expected.\n if (strpos($actualMessage, 'user_does_not_exist') === false) {\n // If the user does exist...\n\n // then we expect the 'success' property to be true. If not,\n // throw an exception.\n if ($actualSuccess !== true) {\n throw new Exception(\n sprintf(\n \"Remove User ['success'] Expected: true, Received: %s | %s\",\n $actualSuccessMessage,\n $actualMessage\n )\n );\n }\n\n // then we expect that the users name will be in the returned\n // message. If it's not then throw an exception.\n if (strpos($actualMessage, $username) === false) {\n throw new Exception(\n sprintf(\n \"Remove User ['message'] did not contain username: %s. Received: %s\",\n $username,\n $actualMessage\n )\n );\n }\n } else {\n // If the user is not found\n\n // And the 'success' property is not false ( as expected ) then throw\n // an exception.\n if ($actualSuccess !== false) {\n throw new Exception(\n sprintf(\n \"Remove User ['success'] Expected: false, Received: %s | %s\",\n $actualSuccessMessage,\n $actualMessage\n )\n );\n }\n }\n\n $helper->logoutDashboard();\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected static function rscandir(string $base = '', array &$data = []): array\n {\n if (substr($base, -1, 1) != DIRECTORY_SEPARATOR) { //add trailing slash if it doesn't exists\n $base .= DIRECTORY_SEPARATOR;\n }\n\n if (count($data) > 2000) {\n throw new Exception('limit of 2000 files reached');\n }\n\n $array = array_diff(scandir($base), ['.', '..', '.svn']);\n foreach ($array as $value) {\n if (is_dir($base . $value)) {\n $data[] = $base . $value . DIRECTORY_SEPARATOR;\n $data = self::rscandir($base . $value . DIRECTORY_SEPARATOR, $data);\n } elseif (is_file($base . $value)) {\n $data[] = $base . $value;\n }\n }\n\n return $data;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getExecutable(string $name, bool $throwException = false, bool $checkExternal = true): string|false\n {\n if (isset(self::$executableCache[$name])) {\n if (!self::$executableCache[$name] && $throwException) {\n throw new Exception(\"No '$name' executable found, please install the application or add it to the PATH (in system settings or to your PATH environment variable\");\n }\n\n return self::$executableCache[$name];\n }\n\n // allow custom setup routines for certain programs\n $customSetupMethod = 'setup' . ucfirst($name);\n if (method_exists(__CLASS__, $customSetupMethod)) {\n self::$customSetupMethod();\n }\n\n // get executable from pimcore_executable_* param\n if ($checkExternal && $externalExecutable = self::getExternalExecutable($name, $throwException)) {\n self::$executableCache[$name] = $externalExecutable;\n\n return $externalExecutable;\n }\n\n $paths = [];\n\n try {\n $systemConfig = Config::getSystemConfiguration('general');\n if (!empty($systemConfig['path_variable'])) {\n $paths = explode(PATH_SEPARATOR, $systemConfig['path_variable']);\n }\n } catch (Exception $e) {\n Logger::warning((string) $e);\n }\n\n array_push($paths, '');\n\n // allow custom check routines for certain programs\n $customCheckMethod = 'check' . ucfirst($name);\n if (!method_exists(__CLASS__, $customCheckMethod)) {\n $customCheckMethod = null;\n }\n\n foreach ($paths as $path) {\n try {\n $path = rtrim($path, '/\\\\ ');\n if ($path) {\n $executablePath = $path . DIRECTORY_SEPARATOR . $name;\n } else {\n $executablePath = $name;\n }\n\n $executableFinder = new ExecutableFinder();\n $fullQualifiedPath = $executableFinder->find($executablePath);\n if ($fullQualifiedPath) {\n if (!$customCheckMethod || self::$customCheckMethod($executablePath)) {\n self::$executableCache[$name] = $fullQualifiedPath;\n\n return $fullQualifiedPath;\n }\n }\n } catch (Exception $e) {\n // nothing to do ...\n }\n }\n\n self::$executableCache[$name] = false;\n\n if ($throwException) {\n throw new Exception(\"No '$name' executable found, please install the application or add it to the PATH (in system settings or to your PATH environment variable\");\n }\n\n return false;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getMultiplePredefinedValues()\n {\n\n $itil_class = static::$itiltype;\n $itil_object = new $itil_class();\n\n $itemstable = null;\n switch ($itil_class) {\n case 'Change':\n $itemstable = 'glpi_changes_items';\n break;\n case 'Problem':\n $itemstable = 'glpi_items_problems';\n break;\n case 'Ticket':\n $itemstable = 'glpi_items_tickets';\n break;\n default:\n throw new \\RuntimeException('Unknown ITIL type ' . $itil_class);\n }\n\n $fields = [\n $itil_object->getSearchOptionIDByField('field', 'name', 'glpi_documents'),\n $itil_object->getSearchOptionIDByField('field', 'items_id', $itemstable),\n $itil_object->getSearchOptionIDByField('field', 'name', 'glpi_tasktemplates')\n ];\n\n return $fields;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (string $userId, string $secret, Request $request, Response $response, Document $user, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) {\n\n $userFromRequest = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId));\n\n if ($userFromRequest->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $token = Auth::phoneTokenVerify($userFromRequest->getAttribute('tokens', []), $secret);\n\n if (!$token) {\n throw new Exception(Exception::USER_INVALID_TOKEN);\n }\n\n $user->setAttributes($userFromRequest->getArrayCopy());\n\n $duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $secret = Auth::tokenGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), $duration));\n\n $session = new Document(array_merge(\n [\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => Auth::SESSION_PROVIDER_PHONE,\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ],\n $detector->getOS(),\n $detector->getClient(),\n $detector->getDevice()\n ));\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $session = $dbForProject->createDocument('sessions', $session\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n /**\n * We act like we're updating and validating\n * the recovery token but actually we don't need it anymore.\n */\n $dbForProject->deleteDocument('tokens', $token);\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $user->setAttribute('phoneVerification', true);\n\n $dbForProject->updateDocument('users', $user->getId(), $user);\n\n if (false === $user) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed saving user to DB');\n }\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId())\n ;\n\n if (!Config::getParam('domainVerification')) {\n $response->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]));\n }\n\n $protocol = $request->getProtocol();\n\n $response\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ;\n\n $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'));\n\n $session\n ->setAttribute('current', true)\n ->setAttribute('countryName', $countryName)\n ->setAttribute('expire', $expire)\n ;\n\n $response->dynamic($session, Response::MODEL_SESSION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function create($class, $isConstructed, $tagNumber)\n {\n if (!is_numeric($class) || $class < self::CLASS_UNIVERSAL || $class > self::CLASS_PRIVATE) {\n throw new Exception(sprintf('Invalid class %d given', $class));\n }\n\n if (!is_bool($isConstructed)) {\n throw new Exception(\"\\$isConstructed must be a boolean value ($isConstructed given)\");\n }\n\n $tagNumber = self::makeNumeric($tagNumber);\n if ($tagNumber < 0) {\n throw new Exception(sprintf('Invalid $tagNumber %d given. You can only use positive integers.', $tagNumber));\n }\n\n if ($tagNumber < self::LONG_FORM) {\n return ($class << 6) | ($isConstructed << 5) | $tagNumber;\n }\n\n $firstOctet = ($class << 6) | ($isConstructed << 5) | self::LONG_FORM;\n\n // Tag numbers formatted in long form are base-128 encoded. See X.609#8.1.2.4\n return chr($firstOctet).Base128::encode($tagNumber);\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function execute($query, $params = array()) {\n //return $this->pixie->db->result_driver('PDOV', $this->conn->query($query));\n\n $vulnFields = null;\n if (array_key_exists('vuln_fields', $params)) {\n $vulnFields = $params['vuln_fields'];\n unset($params['vuln_fields']);\n }\n\n $this->startBlindness($vulnFields);\n\n $stmt = $this->conn->prepare($query);\n try {\n if (!$stmt->execute($params)) {\n $error = $stmt->errorInfo();\n throw new \\Exception(\"Database error:\\n\" . $error[2] . \" \\n in query:\\n{$query}\");\n }\n $result = $this->pixie->db->result_driver('PDOV', $stmt);\n\n } catch (\\Exception $e) {\n $isVulnerable = $this->vulnerable;\n $isBlind = $this->isBlinded;\n $this->stopBlindness($vulnFields);\n $error = $stmt->errorInfo();\n throw new SQLException(\"Database error:\\n\" . $error[2] . \" \\n in query:\\n{$query}\", 0, $e, $isVulnerable, $isBlind);\n }\n\n $this->stopBlindness($vulnFields);\n\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "Tmlrb2xhb3M_hackazon", "language": "php"} {"function": "public function getUserTask(int $id, ?string $userId): OCPTask {\n\t\ttry {\n\t\t\t$taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);\n\t\t\treturn $taskEntity->toPublicTask();\n\t\t} catch (DoesNotExistException $e) {\n\t\t\tthrow new NotFoundException('Could not find task with the provided id and user id');\n\t\t} catch (MultipleObjectsReturnedException $e) {\n\t\t\tthrow new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);\n\t\t} catch (Exception $e) {\n\t\t\tthrow new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getTask(int $id): OCPTask {\n\t\ttry {\n\t\t\t$taskEntity = $this->taskMapper->find($id);\n\t\t\treturn $taskEntity->toPublicTask();\n\t\t} catch (DoesNotExistException $e) {\n\t\t\tthrow new NotFoundException('Could not find task with the provided id');\n\t\t} catch (MultipleObjectsReturnedException $e) {\n\t\t\tthrow new RuntimeException('Could not uniquely identify task with given id', 0, $e);\n\t\t} catch (Exception $e) {\n\t\t\tthrow new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function loadConfiguration()\n{\n $iniFile = CONFIG_PORTAL_SETTINGS;\n $iniDir = preg_replace('/\\\\.ini$/', '.d', $iniFile);\n\n if (!is_readable($iniFile)) {\n $msg = \"Could not read settings file: \" . $iniFile;\n throw new Exception($msg);\n }\n\n // Parse the main config file.\n $iniData = parse_ini_file($iniFile, true);\n\n if ($iniData === false) {\n $msg = \"Failed to parse settings file: \" . $iniFile;\n throw new Exception($msg);\n }\n\n // Merge partial config files.\n $filePaths = glob(\"$iniDir/*.ini\");\n sort($filePaths);\n\n foreach ($filePaths as $partialFile) {\n if (!is_readable($partialFile)) {\n $msg = \"Could not read settings file: \" . $partialFile;\n throw new Exception($msg);\n }\n\n $partialData = parse_ini_file($partialFile, true);\n\n if ($partialData === false) {\n $msg = \"Failed to parse settings file: \" . $partialFile;\n throw new Exception($msg);\n }\n\n foreach ($partialData as $sectionName => $sectionData) {\n foreach ($sectionData as $key => $value) {\n $iniData[$sectionName][$key] = $value;\n }\n }\n }\n\n return $iniData;\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected function prepareLimitationAndContent(User $user, UserGroup $userGroup)\n {\n $repository = $this->getRepository();\n\n $contentService = $repository->getContentService();\n $permissionResolver = $repository->getPermissionResolver();\n\n /* BEGIN: Inline */\n $roleService = $repository->getRoleService();\n\n $role = $roleService->loadRoleByIdentifier('Editor');\n $roleDraft = $roleService->createRoleDraft($role);\n // Search for the new policy instance\n /** @var \\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyDraft $policy */\n $editPolicy = null;\n foreach ($roleDraft->getPolicies() as $policy) {\n if ('content' != $policy->module || 'edit' != $policy->function) {\n continue;\n }\n $editPolicy = $policy;\n break;\n }\n\n if (null === $editPolicy) {\n throw new \\ErrorException(\n 'Cannot find mandatory policy test fixture content::edit.'\n );\n }\n\n // Give read access for the user section\n $policyUpdate = $roleService->newPolicyUpdateStruct();\n $policyUpdate->addLimitation(\n new UserGroupLimitation(\n [\n 'limitationValues' => [true],\n ]\n )\n );\n $roleService->updatePolicyByRoleDraft(\n $roleDraft,\n $editPolicy,\n $policyUpdate\n );\n $roleService->publishRoleDraft($roleDraft);\n\n $roleService->assignRoleToUserGroup($role, $userGroup);\n\n $content = $this->createWikiPage();\n $contentId = $content->id;\n\n $permissionResolver->setCurrentUserReference($user);\n\n $draft = $contentService->createContentDraft(\n $contentService->loadContentInfo($contentId)\n );\n /* END: Inline */\n\n return $draft;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(string $directory = GLPI_LOG_DIR)\n {\n if (!is_dir($directory)) {\n throw new \\RuntimeException(sprintf('Invalid directory \"%s\".', $directory));\n }\n\n $this->directory = $directory;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function getInvertedColor($hexcolor = \"\", $bw = true, $sbw = true)\n {\n if (str_contains($hexcolor, '#')) {\n $hexcolor = trim($hexcolor, '#');\n }\n // convert 3-digit hex to 6-digits.\n if (strlen($hexcolor) === 3) {\n $hexcolor = $hexcolor[0] . $hexcolor[0]\n . $hexcolor[1] . $hexcolor[1]\n . $hexcolor[2] . $hexcolor[2];\n }\n if (strlen($hexcolor) != 6) {\n throw new \\Exception('Invalid HEX color.');\n }\n\n $r = hexdec(substr($hexcolor, 0, 2));\n $g = hexdec(substr($hexcolor, 2, 2));\n $b = hexdec(substr($hexcolor, 4, 2));\n\n if ($bw) {\n return ($r * 0.299 + $g * 0.587 + $b * 0.114) > 100\n ? ($sbw\n ? '#303030'\n : '#000000')\n : ($sbw\n ? '#DFDFDF'\n : '#FFFFFF');\n }\n // invert color components\n $r = 255 - $r;\n $g = 255 - $g;\n $b = 255 - $b;\n\n // pad each with zeros and return\n return \"#\"\n . str_pad($r, 2, '0', STR_PAD_LEFT)\n . str_pad($g, 2, '0', STR_PAD_LEFT)\n . str_pad($b, 2, '0', STR_PAD_LEFT);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function LoadKeys()\n {\n\n // get the keys and constraints\n $sql = \"show create table `\" . $this->Name . \"`\";\n\n $create_table = \"\";\n\n $rs = $this->Schema->Server->Connection->Select($sql);\n\n if ($row = $this->Schema->Server->Connection->Next($rs)) {\n if (isset($row [\"Create Table\"])) {\n $create_table = $row [\"Create Table\"];\n } elseif (isset($row [\"Create View\"])) {\n $this->IsView = true;\n $create_table = $row [\"Create View\"];\n\n // treat the 1st column in a view as the primary key\n $this->Columns [$this->GetColumnNameByIndex(0, false)]->Key = 'PRI';\n } else {\n throw new Exception(\"Unknown Table Type\");\n }\n }\n\n $this->Schema->Server->Connection->Release($rs);\n\n $lines = explode(\"\\n\", $create_table);\n\n foreach ($lines as $line) {\n $line = trim($line);\n if (substr($line, 0, 11) == \"PRIMARY KEY\") {\n preg_match_all(\"/`(\\w+)`/\", $line, $matches, PREG_PATTERN_ORDER);\n // print \"
    \"; print_r($matches); die(); // DEBUG\n                $this->PrimaryKeys [$matches [1] [0]] = new DBKey($this, \"PRIMARY KEY\", $matches [0] [0]);\n            } elseif (substr($line, 0, 3) == \"KEY\") {\n                preg_match_all(\"/`(\\w+)`/\", $line, $matches, PREG_PATTERN_ORDER);\n                // print \"
    \"; print_r($matches); die(); // DEBUG\n                $this->ForeignKeys [$matches [1] [0]] = new DBKey($this, $matches [1] [0], $matches [1] [1]);\n\n                // Add keys to the column for convenience\n                $this->Columns [$matches [1] [1]]->Keys [] = $matches [1] [0];\n            } elseif (substr($line, 0, 10) == \"CONSTRAINT\") {\n                preg_match_all(\"/`(\\w+)`/\", $line, $matches, PREG_PATTERN_ORDER);\n                // print \"
    \"; print_r($matches); die(); // DEBUG\n                $this->Constraints [$matches [1] [0]] = new DBConstraint($this, $matches [1]);\n\n                // the set is basically the reverse of the constraint, but we want to add it to the\n                // constraining table so we don't have to do reverse-lookup looking for child relationships\n                $this->Schema->Tables [$matches [1] [2]]->Sets [$matches [1] [0]] = new DBSet($this, $matches [1]);\n\n                // print \"
    ##########################\\r\\n\" . print_r($matches,1) . \"\\r\\n##########################\\r\\n\";\n\n                // Add constraints to the column for convenience\n                $this->Columns [$matches [1] [1]]->Constraints [] = $matches [1] [0];\n            } elseif (strstr($line, \"COMMENT \")) {\n                // TODO: this is pretty fragile... ?\n                // table comments and column comments are seemingly differentiated by \"COMMENT=\" vs \"COMMENT \"\n                $parts = explode(\"`\", $line);\n                $column = $parts [1];\n                $comment = strstr($line, \"COMMENT \");\n                $comment = substr($comment, 9, strlen($comment) - 11);\n                $comment = str_replace(\"''\", \"'\", $comment);\n                $this->Columns [$column]->Comment = $comment;\n\n                if ($this->Columns [$column]->Default == \"\" && substr($comment, 0, 8) == \"default=\") {\n                    $this->Columns [$column]->Default = substr($comment, 9, strlen($comment) - 10);\n                }\n\n                // print \"
    \" . $column . \"=\" . htmlspecialchars( $this->Columns[$column]->Default );\n            }\n\n            // TODO: look for COMMENT\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"}
    {"function": "function (Response $response) {\n\n        $checkStart = \\microtime(true);\n\n        foreach (\n            [\n            'Uploads' => APP_STORAGE_UPLOADS,\n            'Cache' => APP_STORAGE_CACHE,\n            'Config' => APP_STORAGE_CONFIG,\n            'Certs' => APP_STORAGE_CERTIFICATES\n            ] as $key => $volume\n        ) {\n            $device = new Local($volume);\n\n            if (!\\is_readable($device->getRoot())) {\n                throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not readable');\n            }\n\n            if (!\\is_writable($device->getRoot())) {\n                throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not writable');\n            }\n        }\n\n        $output = [\n            'status' => 'pass',\n            'ping' => \\round((\\microtime(true) - $checkStart) / 1000)\n        ];\n\n        $response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS);\n    }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"}
    {"function": "public function getConfig(): JsonFieldInterface\n    {\n        $config = json_decode($this->fields['config'], true);\n        $strategy = $this->getStrategy();\n        $config_class = $strategy->getConfigClass();\n\n        if (!is_a($config_class, JsonFieldInterface::class, true)) {\n            throw new \\RuntimeException(\"Invalid config class\");\n        }\n\n        return $config_class::jsonDeserialize($config);\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "protected function prepareMyCurrentRelations(\n        Localizedfield|\\Pimcore\\Model\\DataObject\\Fieldcollection\\Data\\AbstractData|\\Pimcore\\Model\\DataObject\\Objectbrick\\Data\\AbstractData|Concrete $object,\n        array $params\n    ): array {\n        if ($object instanceof Concrete) {\n            $relations = $object->retrieveRelationData(['fieldname' => $this->getName(), 'ownertype' => 'object']);\n        } elseif ($object instanceof AbstractData) {\n            $relations = $object->getObject()->retrieveRelationData(\n                [\n                    'fieldname' => $this->getName(),\n                    'ownertype' => 'fieldcollection',\n                    'ownername' => $object->getFieldname(),\n                    'position' => (string)$object->getIndex(), //Gets cast to string for checking a delta of the relations on removal or addition\n                ]\n            );\n        } elseif ($object instanceof Localizedfield) {\n            $context = $params['context'] ?? null;\n            if (isset($context['containerType']) &&\n                ($context['containerType'] === 'fieldcollection' || $context['containerType'] === 'objectbrick')) {\n                $fieldname = $context['fieldname'] ?? null;\n                if ($context['containerType'] === 'fieldcollection') {\n                    $index = $context['index'] ?? null;\n                    $filter = '/'.$context['containerType'].'~'.$fieldname.'/'.$index.'/%';\n                } else {\n                    $filter = '/'.$context['containerType'].'~'.$fieldname.'/%';\n                }\n                $relations = $object->getObject()->retrieveRelationData(\n                    [\n                        'fieldname' => $this->getName(),\n                        'ownertype' => 'localizedfield',\n                        'ownername' => $filter,\n                        'position' => $params['language'],\n                    ]\n                );\n            } else {\n                $relations = $object->getObject()->retrieveRelationData(\n                    [\n                        'fieldname' => $this->getName(),\n                        'ownertype' => 'localizedfield',\n                        'position' => $params['language'],\n                    ]\n                );\n            }\n        } elseif ($object instanceof \\Pimcore\\Model\\DataObject\\Objectbrick\\Data\\AbstractData) {\n            $relations = $object->getObject()->retrieveRelationData(\n                [\n                    'fieldname' => $this->getName(),\n                    'ownertype' => 'objectbrick',\n                    'ownername' => $object->getFieldname(),\n                    'position' => $object->getType(),\n                ]\n            );\n        } else {\n            throw new Exception('Invalid object type');\n        }\n\n        return $relations;\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "public function __construct(PHPExcel_Worksheet $parent, $arguments) {\n\t\t$memcacheServer\t= (isset($arguments['memcacheServer']))\t? $arguments['memcacheServer']\t: 'localhost';\n\t\t$memcachePort\t= (isset($arguments['memcachePort']))\t? $arguments['memcachePort']\t: 11211;\n\t\t$cacheTime\t\t= (isset($arguments['cacheTime']))\t\t? $arguments['cacheTime']\t\t: 600;\n\n\t\tif (is_null($this->_cachePrefix)) {\n\t\t\t$baseUnique = $this->_getUniqueID();\n\t\t\t$this->_cachePrefix = substr(md5($baseUnique),0,8).'.';\n\n\t\t\t//\tSet a new Memcache object and connect to the Memcache server\n\t\t\t$this->_memcache = new Memcache();\n\t\t\tif (!$this->_memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) {\n\t\t\t\tthrow new Exception('Could not connect to MemCache server at '.$memcacheServer.':'.$memcachePort);\n\t\t\t}\n\t\t\t$this->_cacheTime = $cacheTime;\n\n\t\t\tparent::__construct($parent);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "public function create(string $path, string $editorId, string $creatorId, $templateId = null): string {\n\t\t$userFolder = $this->rootFolder->getUserFolder($this->userId);\n\t\tif ($userFolder->nodeExists($path)) {\n\t\t\tthrow new \\RuntimeException('File already exists');\n\t\t} else {\n\t\t\tif (!$userFolder->nodeExists(dirname($path))) {\n\t\t\t\tthrow new \\RuntimeException('Invalid path');\n\t\t\t}\n\t\t\t/** @var Folder $folder */\n\t\t\t$folder = $userFolder->get(dirname($path));\n\t\t\t$file = $folder->newFile(basename($path));\n\t\t\t$editor = $this->getEditor($editorId);\n\t\t\t$creators = $editor->getCreators();\n\t\t\tforeach ($creators as $creator) {\n\t\t\t\tif ($creator->getId() === $creatorId) {\n\t\t\t\t\t$creator->create($file, $creatorId, $templateId);\n\t\t\t\t\treturn $this->createToken($editorId, $file, $path);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new \\RuntimeException('No creator found');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"}
    {"function": "public function getConfigs(): array {\n\t\tif ($this->user === null) {\n\t\t\tthrow new \\Exception('No user logged in');\n\t\t}\n\n\t\t$userId = $this->user->getUID();\n\t\t$userConfigs = array_map(function (string $key) use ($userId) {\n\t\t\t$value = $this->config->getUserValue($userId, Application::APP_ID, $key, $this->getDefaultConfigValue($key));\n\t\t\t// If the default is expected to be a boolean, we need to cast the value\n\t\t\tif (is_bool($this->getDefaultConfigValue($key)) && is_string($value)) {\n\t\t\t\treturn $value === '1';\n\t\t\t}\n\t\t\treturn $value;\n\t\t}, $this->getAllowedConfigKeys());\n\n\t\treturn array_combine($this->getAllowedConfigKeys(), $userConfigs);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"}
    {"function": "public function getDataValidation()\n\t{\n\t\tif (!isset($this->_parent)) {\n\t\t\tthrow new Exception('Cannot get data validation for cell that is not bound to a worksheet');\n\t\t}\n\n\t\treturn $this->_parent->getDataValidation($this->getCoordinate());\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "public function setDocument(int|Model\\Document|string|null $document): static\n    {\n        if (!empty($document)) {\n            if (is_numeric($document)) { //id of document passed\n                $document = Model\\Document\\Email::getById($document);\n            } elseif (is_string($document)) { //path of document passed\n                $document = Model\\Document\\Email::getByPath($document);\n            }\n        }\n\n        if ($document instanceof Model\\Document\\Email || $document === null) {\n            $this->document = $document;\n            $this->setDocumentId($document instanceof Model\\Document ? $document->getId() : null);\n            $this->setDocumentSettings();\n        } else {\n            throw new Exception(\"$document is not an instance of \" . Model\\Document\\Email::class);\n        }\n\n        return $this;\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "function (string $projectId, string $type, string $locale, string $message, Response $response, Database $dbForConsole) {\n\n        throw new Exception(Exception::GENERAL_NOT_IMPLEMENTED);\n\n        $project = $dbForConsole->getDocument('projects', $projectId);\n\n        if ($project->isEmpty()) {\n            throw new Exception(Exception::PROJECT_NOT_FOUND);\n        }\n\n        $templates = $project->getAttribute('templates', []);\n        $templates['sms.' . $type . '-' . $locale] = [\n            'message' => $message\n        ];\n\n        $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('templates', $templates));\n\n        $response->dynamic(new Document([\n            'message' => $message,\n            'type' => $type,\n            'locale' => $locale,\n        ]), Response::MODEL_SMS_TEMPLATE);\n    }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"}
    {"function": "public function init(\n        $startDate,\n        $endDate,\n        $aggregationUnit,\n        $data_series,\n        $global_filters,\n        $query_type,\n        $user\n    ) {\n        // JMS: please improve this when possible.\n        if ( !in_array($query_type, array('aggregate','timeseries') ) ) {\n            throw new \\Exception(\n                get_class($this).\" unsupported query_type found: \".$query_type\n            );\n        }\n\n        $globalFilterDescriptions = array();\n        //$yAxisArray  = array();\n        $metrics     = array();\n        $dimensions  = array();\n        $dataSources = array();\n\n        foreach ($data_series as $data_description_index => $data_description) {\n\n            $realm = \\Realm\\Realm::factory($data_description->realm);\n\n            try {\n                $stat = $realm->getStatisticObject($data_description->metric);\n                $statLabel = $stat->getName();\n                $metrics[$statLabel] = $stat->getHtmlDescription();\n            } catch (\\Exception $ex) {\n                continue;\n            }\n\n            if (!$stat->usesTimePeriodTablesForAggregate()) {\n                throw new Exception(\n                    \"Metric $statLabel cannot be used in aggregate form. Please switch to a timeseries chart or modify/delete the metric.\"\n                );\n            }\n\n            $query_classname = '\\\\DataWarehouse\\\\Query\\\\' .\n                ( $query_type == 'aggregate' ? 'AggregateQuery' : 'TimeseriesQuery');\n\n            $query = new $query_classname(\n                $data_description->realm,\n                $aggregationUnit,\n                $startDate,\n                $endDate\n            );\n\n            $dataSources[$query->getDataSource()] = 1;\n            $group_by = $query->addGroupBy($data_description->group_by);\n            $dimensions[$group_by->getName()] = $group_by->getHtmlDescription();\n            $query->addStat($data_description->metric);\n\n            if (\n                $data_description->std_err == 1\n                || (\n                    property_exists($data_description, 'std_err_labels')\n                    && $data_description->std_err_labels\n                )) {\n                $semStatId = \\Realm\\Realm::getStandardErrorStatisticFromStatistic(\n                    $data_description->metric\n                );\n                if ($query->getRealm()->statisticExists($semStatId)) {\n                    $query->addStat($semStatId);\n                }\n                else {\n                    $data_description->std_err = 0;\n                    $data_description->std_err_labels = false;\n                }\n            }\n\n            // set sort and order by for dataset\n            $query = $this->setOrderBy($data_description, $query);\n\n            // Role parameters: grouped with global filters.\n            //      User-added filters added to chart\n            //      implicit role-associated filters\n            $groupedRoleParameters = $this->determineRoleParameters(\n                $data_description,\n                $global_filters\n            );\n            $query->setRoleParameters($groupedRoleParameters);\n\n            $data_description->roleRestrictionsParameters = $query->setMultipleRoleParameters($data_description->authorizedRoles, $user);\n            $data_description->restrictedByRoles = $query->isLimitedByRoleRestrictions();\n\n            $globalFilterDescriptions = array_merge(\n                $globalFilterDescriptions,\n                $query->roleParameterDescriptions\n            );\n\n            $query->setFilters($data_description->filters);\n\n            // Create the Simple*Dataset; add to $this->_dataDescripters[]\n            $this->addDataset($data_description, $query);\n\n        } // foreach ($data_series as $data_description_index => $data_description)\n\n        return array(\n            $dimensions,\n            $metrics,\n            //$yAxisArray,\n            $globalFilterDescriptions,\n            $dataSources\n        );\n    }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"}
    {"function": "public function __construct()\n    {\n        if (empty($GLOBALS['oefax_enable_sms'] ?? null)) {\n            throw new \\RuntimeException(xlt(\"Access denied! Module not enabled\"));\n        }\n        parent::__construct();\n    }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"}
    {"function": "function (string $databaseId, string $name, bool $enabled, Response $response, Database $dbForProject, Event $events) {\n\n        $databaseId = $databaseId == 'unique()' ? ID::unique() : $databaseId;\n\n        try {\n            $dbForProject->createDocument('databases', new Document([\n                '$id' => $databaseId,\n                'name' => $name,\n                'enabled' => $enabled,\n                'search' => implode(' ', [$databaseId, $name]),\n            ]));\n            $database = $dbForProject->getDocument('databases', $databaseId);\n\n            $collections = (Config::getParam('collections', [])['databases'] ?? [])['collections'] ?? [];\n            if (empty($collections)) {\n                throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The \"collections\" collection is not configured.');\n            }\n\n            $attributes = [];\n            $indexes = [];\n\n            foreach ($collections['attributes'] as $attribute) {\n                $attributes[] = new Document([\n                    '$id' => $attribute['$id'],\n                    'type' => $attribute['type'],\n                    'size' => $attribute['size'],\n                    'required' => $attribute['required'],\n                    'signed' => $attribute['signed'],\n                    'array' => $attribute['array'],\n                    'filters' => $attribute['filters'],\n                    'default' => $attribute['default'] ?? null,\n                    'format' => $attribute['format'] ?? ''\n                ]);\n            }\n\n            foreach ($collections['indexes'] as $index) {\n                $indexes[] = new Document([\n                    '$id' => $index['$id'],\n                    'type' => $index['type'],\n                    'attributes' => $index['attributes'],\n                    'lengths' => $index['lengths'],\n                    'orders' => $index['orders'],\n                ]);\n            }\n            $dbForProject->createCollection('database_' . $database->getInternalId(), $attributes, $indexes);\n        } catch (DuplicateException) {\n            throw new Exception(Exception::DATABASE_ALREADY_EXISTS);\n        }\n\n        $events->setParam('databaseId', $database->getId());\n\n        $response\n            ->setStatusCode(Response::STATUS_CODE_CREATED)\n            ->dynamic($database, Response::MODEL_DATABASE);\n    }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"}
    {"function": "public function getTableName(): string\n    {\n        if (empty($this->tableName)) {\n            // default\n            $this->tableName = 'object_' . $this->model->getClassId();\n\n            if (!$this->model->getIgnoreLocalizedFields()) {\n                $language = null;\n                // check for a localized field and if they should be used for this list\n                if (property_exists('\\\\Pimcore\\\\Model\\\\DataObject\\\\' . ucfirst($this->model->getClassName()), 'localizedfields')) {\n                    if ($this->model->getLocale()) {\n                        if (Tool::isValidLanguage((string)$this->model->getLocale())) {\n                            $language = (string)$this->model->getLocale();\n                        }\n                        if (!$language && DataObject\\Localizedfield::isStrictMode()) {\n                            throw new Exception('could not resolve locale: ' . $this->model->getLocale());\n                        }\n                    }\n\n                    if (!$language) {\n                        $locale = Pimcore::getContainer()->get(LocaleServiceInterface::class)->findLocale();\n                        if (Tool::isValidLanguage((string)$locale)) {\n                            $language = (string)$locale;\n                        }\n                    }\n\n                    if (!$language) {\n                        $language = Tool::getDefaultLanguage();\n                    }\n\n                    if (!$language) {\n                        throw new Exception('No valid language/locale set. Use $list->setLocale() to add a language to the listing, or register a global locale');\n                    }\n                    $this->tableName = 'object_localized_' . $this->model->getClassId() . '_' . $language;\n                }\n            }\n        }\n\n        return $this->tableName;\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "public function buildUpdateOrInsert($table, $params, $where, $onlyone = true): string\n    {\n        $req = $this->request(array_merge(['FROM' => $table], $where));\n        $data = array_merge($where, $params);\n        if ($req->count() == 0) {\n            return $this->buildInsert($table, $data);\n        } elseif ($req->count() == 1 || !$onlyone) {\n            return $this->buildUpdate($table, $data, $where);\n        } else {\n            throw new RuntimeException('Update would change too many rows!');\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "public static function getList(array $config = []): Listing\n    {\n        $className = DataObject::class;\n        // get classname\n        if (!in_array(static::class, [__CLASS__, Concrete::class, Folder::class], true)) {\n            /** @var Concrete $tmpObject */\n            $tmpObject = new static();\n            if ($tmpObject instanceof Concrete) {\n                $className = 'Pimcore\\\\Model\\\\DataObject\\\\' . ucfirst($tmpObject->getClassName());\n            }\n        }\n\n        if (!empty($config['class'])) {\n            $className = ltrim($config['class'], '\\\\');\n        }\n\n        if ($className) {\n            $listClass = $className . '\\\\Listing';\n            /** @var DataObject\\Listing $list */\n            $list = self::getModelFactory()->build($listClass);\n            $list->setValues($config);\n\n            return $list;\n        }\n\n        throw new Exception('Unable to initiate list class - class not found or invalid configuration');\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "public function executeStatement(mysqli_stmt $stmt): void\n    {\n        if (!$stmt->execute()) {\n            throw new \\RuntimeException(\n                sprintf(\n                    'Error executing statement \"%s\": %s',\n                    $this->current_query,\n                    $stmt->error\n                )\n            );\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "public function listWorksheetNames($pFilename)\n\t{\n\t\t// Check if file exists\n\t\tif (!file_exists($pFilename)) {\n\t\t\tthrow new Exception(\"Could not open \" . $pFilename . \" for reading! File does not exist.\");\n\t\t}\n\n\t\t$worksheetNames = array();\n\n\t\t// Read the OLE file\n\t\t$this->_loadOLE($pFilename);\n\n\t\t// total byte size of Excel data (workbook global substream + sheet substreams)\n\t\t$this->_dataSize = strlen($this->_data);\n\n\t\t$this->_pos\t\t= 0;\n\t\t$this->_sheets\t= array();\n\n\t\t// Parse Workbook Global Substream\n\t\twhile ($this->_pos < $this->_dataSize) {\n\t\t\t$code = self::_GetInt2d($this->_data, $this->_pos);\n\n\t\t\tswitch ($code) {\n\t\t\t\tcase self::XLS_Type_BOF:\t$this->_readBof();\t\tbreak;\n\t\t\t\tcase self::XLS_Type_SHEET:\t$this->_readSheet();\tbreak;\n\t\t\t\tcase self::XLS_Type_EOF:\t$this->_readDefault();\tbreak 2;\n\t\t\t\tdefault:\t\t\t\t\t$this->_readDefault();\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tforeach ($this->_sheets as $sheet) {\n\t\t\tif ($sheet['sheetType'] != 0x00) {\n\t\t\t\t// 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$worksheetNames[] = $sheet['name'];\n\t\t}\n\n\t\treturn $worksheetNames;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "public function emailLogsAction(Request $request): JsonResponse\n    {\n        if (!$this->getAdminUser()->isAllowed('emails') && !$this->getAdminUser()->isAllowed('gdpr_data_extractor')) {\n            throw new \\Exception(\"Permission denied, user needs 'emails' permission.\");\n        }\n\n        $list = new Tool\\Email\\Log\\Listing();\n        if ($request->get('documentId')) {\n            $list->setCondition('documentId = ' . (int)$request->get('documentId'));\n        }\n        $list->setLimit((int)$request->get('limit', 50));\n        $list->setOffset((int)$request->get('start', 0));\n        $list->setOrderKey('sentDate');\n\n        if ($request->get('filter')) {\n            $filterTerm = $request->get('filter');\n            if ($filterTerm == '*') {\n                $filterTerm = '';\n            }\n\n            $filterTerm = str_replace('%', '*', $filterTerm);\n            $filterTerm = htmlspecialchars($filterTerm, ENT_QUOTES);\n\n            if (strpos($filterTerm, '@')) {\n                $parts = explode(' ', $filterTerm);\n                $parts = array_map(function ($part) {\n                    if (strpos($part, '@')) {\n                        $part = '\"' . $part . '\"';\n                    }\n\n                    return $part;\n                }, $parts);\n                $filterTerm = implode(' ', $parts);\n            }\n\n            if (str_starts_with($filterTerm, '@')) {\n                $filterTerm = str_replace('@', '', $filterTerm);\n            }\n\n            $condition = '( MATCH (`from`,`to`,`cc`,`bcc`,`subject`,`params`) AGAINST (' . $list->quote($filterTerm) . ' IN BOOLEAN MODE) )';\n\n            if ($request->get('documentId')) {\n                $condition .= 'AND documentId = ' . (int)$request->get('documentId');\n            }\n\n            $list->setCondition($condition);\n        }\n\n        $list->setOrder('DESC');\n\n        $data = $list->load();\n        $jsonData = [];\n\n        if (is_array($data)) {\n            foreach ($data as $entry) {\n                $tmp = $entry->getObjectVars();\n                unset($tmp['bodyHtml']);\n                unset($tmp['bodyText']);\n                $jsonData[] = $tmp;\n            }\n        }\n\n        return $this->adminJson([\n            'data' => $jsonData,\n            'success' => true,\n            'total' => $list->getTotalCount(),\n        ]);\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"}
    {"function": "public function setRequest(Request $request): void\n    {\n        if ($this->request) {\n            throw new \\RuntimeException('Cannot set request twice in config.');\n        }\n        $this->request = $request;\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "private function exportBreadthAlgorithm(EhiExportJobTask $jobTask): EhiExportJobTask\n    {\n        $patientPids = $jobTask->getPatientIds();\n        $xmlTableStructure = $this->getXmlNode($this->xmlConfigPath . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . 'openemr.openemr.xml');\n        $xmlMetaStructure = $this->getXmlNode($this->xmlConfigPath . DIRECTORY_SEPARATOR . 'schemaspy'\n            . DIRECTORY_SEPARATOR . 'schemas' . DIRECTORY_SEPARATOR . 'openemr.meta.xml');\n        $exportState = new Models\\ExportState($this->logger, $xmlTableStructure, $xmlMetaStructure, $jobTask);\n\n        $pidKey = new Models\\ExportKeyDefinition();\n        $pidKey->foreignKeyTable = \"patient_data\";\n        $pidKey->foreignKeyColumn = \"pid\";\n\n        $specialTables = [\n            'patient_data'\n            , ExportOnsiteMessagesTableDefinition::TABLE_NAME\n            , ExportOnsiteMailTableDefinition::TABLE_NAME\n            , ExportEsignatureTableDefinition::TABLE_NAME\n            , ExportClinicalNotesFormTableDefinition::TABLE_NAME\n            , ExportFormsGroupsEncounterTableDefinition::TABLE_NAME\n            , ExportTrackAnythingFormTableDefinition::TABLE_NAME\n        ];\n        foreach ($specialTables as $table) {\n            // some tables are not installed yet and must be skipped if they do not exist\n            // such as the ExportClinicalNotesFormTableDefinition::TABLE_NAME which must be specially handled\n            if (QueryUtils::existsTable($table)) {\n                $tableDefinition = $exportState->createTableDefinition($table);\n                $tableDefinition->addKeyValueList($pidKey, $patientPids);\n                $exportState->addTableDefinition($tableDefinition);\n            }\n        }\n\n        $maxCycleLimit = self::CYCLE_MAX_ITERATIONS_LIMIT;\n        $iterations = 0;\n\n        /**\n         * We go through a queue of the tables to do a breadth first traversal of the foreign key\n         * links of each table.  We do this so we can grab the largest amount of datasets and minimize\n         * rework as much as possible.\n         * We grab all of the key definitions for each table and loop primarily through parent relationships\n         * (IE where the table has a column with a foreign key that points to another table, ie its parent relationship)\n         * In limited cases (such as patient_data and a few others) we grab the child relationships (IE where another table has a column with a foreign key that points to the current table)\n         *\n         * We loop through each of the tables and we track the actual key values (both FK&PK) in order to avoid grabbing the same datasets\n         * at the same time.  Granted this could end up holding a ton of data in memory especially for keys with string values and we will need to bench mark this for performance\n         * We write out the data records to disk as a csv file and then record tabulated result data of the total records written.\n         * If a table has been processed previously but is reached again via a different key relationship it will be added to the queue\n         * to be processed again ONLY IF there is new key values that are added.\n         * This means that some tables will be written out to disk multiple times, which creates some redundancy.\n         * For simplicity we just grab the entire unioned data set from all of the keys for that table and then rewrite over the same file.\n         * Additional optimizations work could be done to make this more efficient but I chose in the interest of time for a working algorithm\n         * than a highly efficient algorithm that would take more time to implement.\n         *\n         * Once the data has been exported, the exporter will grab all of the documents and export them to the zip file\n         * as well.  If there are dependent assets for linked tables (such as images in the case of the pain map form)\n         * those also get exported.\n         *\n         * For safety purposes we limit our max cycles that we will iterate through the tables in order to avoid\n         * any kind of infinite loop routine.\n         */\n        while ($exportState->hasTableDefinitions() && $iterations++ <= $maxCycleLimit) {\n            $tableDefinition = $exportState->getNextTableDefinitionToProcess();\n            // otherwise if we have no records we skip as well.\n            $records = $tableDefinition->getRecords();\n            if (empty($records)) {\n                continue;\n            }\n\n            $keyDefinitions = $exportState->getKeyDataForTable($tableDefinition);\n            // write out the csv file\n            $this->writeCsvFile($jobTask, $records, $tableDefinition->table, $exportState->getTempSysDir(), $tableDefinition->getColumnNames());\n            $exportState->addExportResultTable($tableDefinition->table, count($records));\n            $jobTask->exportedResult = $exportState->getExportResult();\n            $this->taskService->update($jobTask); // for progress updates\n            $tableDefinition->setHasNewData(false);\n            if (!empty($keyDefinitions)) {\n                foreach ($keyDefinitions['keys'] as $keyDefinition) {\n                    if (!($keyDefinition instanceof ExportKeyDefinition)) {\n                        throw new \\RuntimeException(\"Invalid key definition\");\n                    }\n                    $foreignKeyTableDefinition = $keyDefinitions['tables'][$keyDefinition->foreignKeyTable];\n                    // we process ALL parent keys, or if it is a child key we only process a select few of these keys.\n                    if ($this->shouldProcessForeignKey($keyDefinition)) {\n                        foreach ($records as $record) {\n                            $keyColumnName = $keyDefinition->localColumn;\n                            // we have in some cases a need to override the local value such as with our list_options\n                            // table so we can handle some more dynamic values here.\n                            if (isset($keyDefinition->localValueOverride)) {\n                                $recordValue = $keyDefinition->localValueOverride;\n                            } else {\n                                $recordValue = $record[$keyColumnName] ?? null;\n                            }\n                            if (isset($recordValue)) {\n                                $foreignKeyTableDefinition->addKeyValue($keyDefinition, $recordValue);\n                            }\n                        }\n                        // we only add it to be processed if there is new data to do so.\n                        if ($foreignKeyTableDefinition->hasNewData()) {\n                            // if the table already is in the queue the operation is a noop\n                            $exportState->addTableDefinition($foreignKeyTableDefinition);\n                        }\n                    }\n                }\n            }\n        }\n        $this->exportCustomTables($jobTask, $exportState);\n        if ($iterations > $maxCycleLimit) {\n            throw new \\RuntimeException(\"Max iterations reached, check for cyclic dependencies\");\n        }\n        $exportedResult = $exportState->getExportResult();\n        $document = $this->generateZipfile($jobTask, $exportedResult, $exportState);\n        $documentService = new DocumentService();\n        $exportedResult->downloadLink = $documentService->getDownloadLink($document->get_id());\n        $jobTask->exportedResult = $exportedResult;\n        $jobTask->document = $document;\n        $jobTask->export_document_id = $document->get_id();\n        return $jobTask;\n    }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"}
    {"function": "public static function getLatestVersionNumber(array $args = array())\n    {\n        if (isset(static::$latestVersion)) {\n            return static::$latestVersion;\n        }\n\n        $scheme = 'https';\n        $host   = 'xdmod.ccr.buffalo.edu';\n        $port   = null;\n        $path   = '/rest/v0.1/versions/current';\n\n        $url = $scheme . '://' . $host;\n\n        if (isset($port) && is_numeric($port)) {\n            $url .= ':' . $port;\n        }\n\n        $url .= $path;\n\n        if (!isset($args['open-xdmod'])) {\n            $args['open-xdmod'] = true;\n        }\n\n        if (count($args) > 0) {\n            $url .= '?' . http_build_query($args);\n        }\n\n        $contextOpts = array(\n            'http' => array(\n                'timeout'    => static::$timeout,\n                'user_agent' => 'XDMoD',\n            ),\n        );\n\n        $context = stream_context_create($contextOpts);\n\n        // Perform the query.\n        $json = @file_get_contents($url, false, $context);\n\n        if ($json === false) {\n            throw new Exception('Failed to query server');\n        } elseif ($json === '') {\n            throw new Exception('No data returned from server');\n        }\n\n        $data = json_decode($json, true);\n\n        if ($data === null) {\n            $msg = \"Failed to decode JSON '$json': \"\n                . Json::getLastErrorMessage();\n            throw new Exception($msg);\n        }\n\n        if (!isset($data['success'])) {\n            throw new Exception(\"No success value found in JSON '$json'\");\n        }\n\n        if (isset($data['success']) && !$data['success']) {\n            $msg = 'Failed to retrieve version data';\n\n            if (isset($data['message'])) {\n                $msg .= ': ' . $data['message'];\n            }\n\n            throw new Exception($msg);\n        }\n\n        if (!isset($data['results'])) {\n            throw new Exception(\"No results value found in JSON '$json'\");\n        }\n\n        static::$latestVersion = $data['results'];\n\n        return static::$latestVersion;\n    }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"}
    {"function": "public static function sendMail($properties) {\n        $mail = MailWrapper::initPHPMailer($properties);\n        if(!$mail->send()){\n            throw new \\Exception($mail->ErrorInfo);\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"}
    {"function": "public function exec()\n    {\n        if(empty($this->grades)){\n            throw new Exception(\"N\u00e3o foram adicionadas notas antes de excutar o caso de uso\", 1);\n        }\n\n        $result = 0;\n        switch ($this->calculation->id) {\n            default:\n            case GradeCalculation::OP_SUM:\n                $result = array_reduce($this->grades, function ($acc, $grade) {\n                    /** @var Grade $grade */\n                    $acc += floatval($grade);\n                    return $acc;\n                });\n                break;\n            case GradeCalculation::OP_MAX:\n                $result = max($this->grades);\n                break;\n            case GradeCalculation::OP_MIN:\n                $result = min($this->grades);\n                break;\n            case GradeCalculation::OP_MEDIA:\n                $finalGrade = array_reduce($this->grades, function ($acc, $grade) {\n                    /** @var Grade $grade */\n                    $acc += floatval($grade);\n                    return $acc;\n                });\n                $result = $finalGrade / sizeof($this->grades);\n                break;\n            case GradeCalculation::OP_MEDIA_BY_WEIGTH:\n                $acc = [0, 0];\n                foreach ($this->grades as $key => $value) {\n                    $acc[0] += $value * $this->weights[$key];\n                    $acc[1] += $this->weights[$key];\n                }\n\n                $result = $acc[0] / $acc[1];\n                break;\n        }\n\n        return round($result, 1);\n    }", "smellKey": "S112", "smellId": null, "repo": "ipti_br.tag", "language": "php"}
    {"function": "private function determineGroups(string $dbKey, string $confKey, bool $testMemberOf = true) {\n\t\t$reqs = ['ldapHost', 'ldapBase'];\n\t\tif (!$this->configuration->usesLdapi()) {\n\t\t\t$reqs[] = 'ldapPort';\n\t\t}\n\t\tif (!$this->checkRequirements($reqs)) {\n\t\t\treturn  false;\n\t\t}\n\t\t$cr = $this->getConnection();\n\t\tif (!$cr) {\n\t\t\tthrow new \\Exception('Could not connect to LDAP');\n\t\t}\n\n\t\t$this->fetchGroups($dbKey, $confKey);\n\n\t\tif ($testMemberOf) {\n\t\t\t$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();\n\t\t\t$this->result->markChange();\n\t\t\tif (!$this->configuration->hasMemberOfFilterSupport) {\n\t\t\t\tthrow new \\Exception('memberOf is not supported by the server');\n\t\t\t}\n\t\t}\n\n\t\treturn $this->result;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"}
    {"function": "private function create() {\n\t\t$isCluster = in_array('redis.cluster', $this->config->getKeys(), true);\n\t\t$config = $isCluster\n\t\t\t? $this->config->getValue('redis.cluster', [])\n\t\t\t: $this->config->getValue('redis', []);\n\n\t\tif ($isCluster && !class_exists('RedisCluster')) {\n\t\t\tthrow new \\Exception('Redis Cluster support is not available');\n\t\t}\n\n\t\t$timeout = $config['timeout'] ?? 0.0;\n\t\t$readTimeout = $config['read_timeout'] ?? 0.0;\n\n\t\t$auth = null;\n\t\tif (isset($config['password']) && (string)$config['password'] !== '') {\n\t\t\tif (isset($config['user']) && (string)$config['user'] !== '') {\n\t\t\t\t$auth = [$config['user'], $config['password']];\n\t\t\t} else {\n\t\t\t\t$auth = $config['password'];\n\t\t\t}\n\t\t}\n\n\t\t// # TLS support\n\t\t// # https://github.com/phpredis/phpredis/issues/1600\n\t\t$connectionParameters = $this->getSslContext($config);\n\t\t$persistent = $this->config->getValue('redis.persistent', true);\n\n\t\t// cluster config\n\t\tif ($isCluster) {\n\t\t\tif (!isset($config['seeds'])) {\n\t\t\t\tthrow new \\Exception('Redis cluster config is missing the \"seeds\" attribute');\n\t\t\t}\n\n\t\t\t// Support for older phpredis versions not supporting connectionParameters\n\t\t\tif ($connectionParameters !== null) {\n\t\t\t\t$this->instance = new \\RedisCluster(null, $config['seeds'], $timeout, $readTimeout, $persistent, $auth, $connectionParameters);\n\t\t\t} else {\n\t\t\t\t$this->instance = new \\RedisCluster(null, $config['seeds'], $timeout, $readTimeout, $persistent, $auth);\n\t\t\t}\n\n\t\t\tif (isset($config['failover_mode'])) {\n\t\t\t\t$this->instance->setOption(\\RedisCluster::OPT_SLAVE_FAILOVER, $config['failover_mode']);\n\t\t\t}\n\t\t} else {\n\t\t\t$this->instance = new \\Redis();\n\n\t\t\t$host = $config['host'] ?? '127.0.0.1';\n\t\t\t$port = $config['port'] ?? ($host[0] !== '/' ? 6379 : null);\n\n\t\t\t$this->eventLogger->start('connect:redis', 'Connect to redis and send AUTH, SELECT');\n\t\t\t// Support for older phpredis versions not supporting connectionParameters\n\t\t\tif ($connectionParameters !== null) {\n\t\t\t\t// Non-clustered redis requires connection parameters to be wrapped inside `stream`\n\t\t\t\t$connectionParameters = [\n\t\t\t\t\t'stream' => $this->getSslContext($config)\n\t\t\t\t];\n\t\t\t\tif ($persistent) {\n\t\t\t\t\t/**\n\t\t\t\t\t * even though the stubs and documentation don't want you to know this,\n\t\t\t\t\t * pconnect does have the same $connectionParameters argument connect has\n\t\t\t\t\t *\n\t\t\t\t\t * https://github.com/phpredis/phpredis/blob/0264de1824b03fb2d0ad515b4d4ec019cd2dae70/redis.c#L710-L730\n\t\t\t\t\t *\n\t\t\t\t\t * @psalm-suppress TooManyArguments\n\t\t\t\t\t */\n\t\t\t\t\t$this->instance->pconnect($host, $port, $timeout, null, 0, $readTimeout, $connectionParameters);\n\t\t\t\t} else {\n\t\t\t\t\t$this->instance->connect($host, $port, $timeout, null, 0, $readTimeout, $connectionParameters);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ($persistent) {\n\t\t\t\t\t$this->instance->pconnect($host, $port, $timeout, null, 0, $readTimeout);\n\t\t\t\t} else {\n\t\t\t\t\t$this->instance->connect($host, $port, $timeout, null, 0, $readTimeout);\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t// Auth if configured\n\t\t\tif ($auth !== null) {\n\t\t\t\t$this->instance->auth($auth);\n\t\t\t}\n\n\t\t\tif (isset($config['dbindex'])) {\n\t\t\t\t$this->instance->select($config['dbindex']);\n\t\t\t}\n\t\t\t$this->eventLogger->end('connect:redis');\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"}
    {"function": "public function applyFromArray($pStyles = null) {\n\t\tif (is_array($pStyles)) {\n\t\t\tif ($this->_isSupervisor) {\n\t\t\t\t$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));\n\t\t\t} else {\n\t\t\t\tif (array_key_exists('name', $pStyles)) {\n\t\t\t\t\t$this->setName($pStyles['name']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('bold', $pStyles)) {\n\t\t\t\t\t$this->setBold($pStyles['bold']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('italic', $pStyles)) {\n\t\t\t\t\t$this->setItalic($pStyles['italic']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('superScript', $pStyles)) {\n\t\t\t\t\t$this->setSuperScript($pStyles['superScript']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('subScript', $pStyles)) {\n\t\t\t\t\t$this->setSubScript($pStyles['subScript']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('underline', $pStyles)) {\n\t\t\t\t\t$this->setUnderline($pStyles['underline']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('strike', $pStyles)) {\n\t\t\t\t\t$this->setStrikethrough($pStyles['strike']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('color', $pStyles)) {\n\t\t\t\t\t$this->getColor()->applyFromArray($pStyles['color']);\n\t\t\t\t}\n\t\t\t\tif (array_key_exists('size', $pStyles)) {\n\t\t\t\t\t$this->setSize($pStyles['size']);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Exception(\"Invalid style array passed.\");\n\t\t}\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "protected function getAndApplyPatch(RemoteFilesystem $downloader, $install_path, $patch_url, PackageInterface $package) {\n\n    // Local patch file.\n    if (file_exists($patch_url)) {\n      $filename = realpath($patch_url);\n    }\n    else {\n      // Generate random (but not cryptographically so) filename.\n      $filename = uniqid(sys_get_temp_dir().'/') . \".patch\";\n\n      // Download file from remote filesystem to this location.\n      $hostname = parse_url($patch_url, PHP_URL_HOST);\n\n      try {\n        $downloader->copy($hostname, $patch_url, $filename, false);\n      } catch (\\Exception $e) {\n        // In case of an exception, retry once as the download might\n        // have failed due to intermittent network issues.\n        $downloader->copy($hostname, $patch_url, $filename, false);\n      }\n    }\n\n    // The order here is intentional. p1 is most likely to apply with git apply.\n    // p0 is next likely. p2 is extremely unlikely, but for some special cases,\n    // it might be useful. p4 is useful for Magento 2 patches\n    $patch_levels = array('-p1', '-p0', '-p2', '-p4');\n\n    // Check for specified patch level for this package.\n    $extra = $this->composer->getPackage()->getExtra();\n    if (!empty($extra['patchLevel'][$package->getName()])){\n      $patch_levels = array($extra['patchLevel'][$package->getName()]);\n    }\n    // Attempt to apply with git apply.\n    $patched = $this->applyPatchWithGit($install_path, $patch_levels, $filename);\n\n    // In some rare cases, git will fail to apply a patch, fallback to using\n    // the 'patch' command.\n    if (!$patched) {\n      foreach ($patch_levels as $patch_level) {\n        // --no-backup-if-mismatch here is a hack that fixes some\n        // differences between how patch works on windows and unix.\n        if ($patched = $this->executeCommand(\"patch %s --no-backup-if-mismatch -d %s < %s\", $patch_level, $install_path, $filename)) {\n          break;\n        }\n      }\n    }\n\n    // Clean up the temporary patch file.\n    if (isset($hostname)) {\n      unlink($filename);\n    }\n    // If the patch *still* isn't applied, then give up and throw an Exception.\n    // Otherwise, let the user know it worked.\n    if (!$patched) {\n      throw new \\Exception(\"Cannot apply patch $patch_url\");\n    }\n  }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"}
    {"function": "public static function getDescriptorParamValue(XDUser $user, $aclName, $groupByName)\n    {\n        if (null == $user->getUserID()) {\n            throw new Exception('A valid user id must be supplied.');\n        }\n        if (null === $aclName) {\n            throw new Exception('A valid acl name is required.');\n        }\n        if (null === $groupByName) {\n            throw new Exception('A valid group by name is required.');\n        }\n        $db = DB::factory('database');\n        $query = <<query($query, array(\n            ':user_id' => $user->getUserID(),\n            ':acl_name' => $aclName,\n            ':group_by_name' => $groupByName\n        ));\n        if (count($rows) > 0) {\n            return $rows[0]['value'];\n        }\n        return null;\n    }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"}
    {"function": "public function cellExists($pCoordinate = 'A1')\n\t{\n\t\t// Worksheet reference?\n\t\tif (strpos($pCoordinate, '!') !== false) {\n\t\t\t$worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true);\n\t\t\treturn $this->getParent()->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]);\n\t\t}\n\n\t\t// Named range?\n\t\tif ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) &&\n\t\t\t(preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) {\n\t\t\t$namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this);\n\t\t\tif (!is_null($namedRange)) {\n\t\t\t\t$pCoordinate = $namedRange->getRange();\n\t\t\t\tif ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {\n\t\t\t\t\tif (!$namedRange->getLocalOnly()) {\n\t\t\t\t\t\treturn $namedRange->getWorksheet()->cellExists($pCoordinate);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Uppercase coordinate\n\t\t$pCoordinate = strtoupper($pCoordinate);\n\n\t\tif (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) {\n\t\t\tthrow new Exception('Cell coordinate can not be a range of cells.');\n\t\t} elseif (strpos($pCoordinate,'$') !== false) {\n\t\t\tthrow new Exception('Cell coordinate must not be absolute.');\n\t\t} else {\n\t\t\t// Coordinates\n\t\t\t$aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate);\n\n\t\t\t// Cell exists?\n\t\t\treturn $this->_cellCollection->isDataSet($pCoordinate);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "public function getHeaders($legacy = true): array\n    {\n       //parse class attributes and normalize key name\n        $reflect = new ReflectionClass($this);\n        $props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);\n\n        $headers = [];\n\n        foreach ($props as $prop) {\n            $propname = $prop->getName();\n            $headername = $this->getHeaderName($propname);\n            if (!empty($this->$propname)) {\n                $headers[$headername] = $this->$propname;\n            } else if (in_array($propname, $this->getRequireds()) && $legacy === false) {\n                throw new \\RuntimeException(\n                    sprintf(\n                        '%1$s HTTP header is mandatory!',\n                        $headername\n                    )\n                );\n            }\n        }\n\n        return $headers;\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "public static function getByKey(string $key): ?Definition\n    {\n        /** @var Definition $fc */\n        $fc = null;\n        $cacheKey = 'fieldcollection_' . $key;\n\n        try {\n            $fc = RuntimeCache::get($cacheKey);\n            if (!$fc) {\n                throw new Exception('FieldCollection in registry is not valid');\n            }\n        } catch (Exception $e) {\n            $def = new Definition();\n            $def->setKey($key);\n            $fieldFile = $def->getDefinitionFile();\n\n            if (is_file($fieldFile)) {\n                $fc = include $fieldFile;\n                RuntimeCache::set($cacheKey, $fc);\n            }\n        }\n\n        if ($fc) {\n            return $fc;\n        }\n\n        return null;\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "protected function getSetupFactory(): SetupFactory\n    {\n        if (null === $this->setupFactory) {\n            if (false === ($setupClass = getenv('setupFactory'))) {\n                $setupClass = LegacySetupFactory::class;\n                putenv(\"setupFactory=$setupClass\");\n            }\n\n            if (false === getenv('fixtureDir')) {\n                putenv('fixtureDir=Legacy');\n            }\n\n            if (false === class_exists($setupClass)) {\n                throw new ErrorException(\n                    sprintf(\n                        'Environment variable \"setupFactory\" does not reference an existing class: %s. Did you forget to install a package dependency?',\n                        $setupClass\n                    )\n                );\n            }\n\n            $this->setupFactory = new $setupClass();\n        }\n\n        return $this->setupFactory;\n    }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"}
    {"function": "public function getXMPData(?string $filePath = null): array\n    {\n        if (!$filePath) {\n            $filePath = $this->getLocalFile();\n        }\n\n        $data = [];\n\n        if (is_file($filePath)) {\n            $chunkSize = 1024;\n\n            if (($file_pointer = fopen($filePath, 'rb')) === false) {\n                throw new RuntimeException('Could not open file for reading');\n            }\n\n            $tag = 'rdf____RDF->rdf____Description) {\n                        foreach ($xml->rdf____RDF->rdf____Description as $description) {\n                            $data = array_merge($data, object2array($description));\n                        }\n                    }\n                }\n\n                if (isset($data['@attributes'])) {\n                    unset($data['@attributes']);\n                }\n            }\n\n            fclose($file_pointer);\n        }\n\n        // remove namespace prefixes if possible\n        $resultData = [];\n        array_walk($data, function ($value, $key) use (&$resultData) {\n            $parts = explode('____', $key);\n            $length = count($parts);\n            if ($length > 1) {\n                $name = $parts[$length - 1];\n                if (!isset($resultData[$name])) {\n                    $key = $name;\n                }\n            }\n\n            $resultData[$key] = $value;\n        });\n\n        return $resultData;\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "private function buildInstance(): OperatorInterface\n    {\n        $phpClass = $this->getPhpClass();\n\n        if ($phpClass && class_exists($phpClass)) {\n            $operatorInstance = new $phpClass($this->config, $this->context);\n\n            return $operatorInstance;\n        }\n\n        throw new \\Exception('PHPCode operator class does not exist: ' . $phpClass);\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"}
    {"function": "public static function factory($time_period, $start_date, $end_date, $aggregate_table_prefix)\n    {\n        self::registerAggregationUnits();\n\n        $time_period = self::deriveAggregationUnitName($time_period, $start_date, $end_date);\n\n        if (isset(self::$_unit_name_to_class_name[$time_period])) {\n            $class_name = self::$_unit_name_to_class_name[$time_period];\n\n            // we need the derived class to have the realm so we know which aggregate table to use\n            $class = new $class_name;\n            $class->setAggTablePrefix($aggregate_table_prefix);\n\n            return $class;\n        } else {\n            throw new \\Exception(\"TimeAggregationUnit: Time period {$time_period} is invalid.\");\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"}
    {"function": "public function setActiveSheetIndexByName($pValue = '')\n\t{\n\t\tif (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) {\n\t\t\t$this->setActiveSheetIndex($worksheet->getParent()->getIndex($worksheet));\n\t\t\treturn $worksheet;\n\t\t}\n\n\t\tthrow new Exception('Workbook does not contain sheet:' . $pValue);\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"}
    {"function": "function (string $client_id, string $client_secret, string $grantType, string $redirectURI, string $code, string $refreshToken, Response $response) {\n\n        if ($client_id != '1') {\n            throw new Exception(Exception::GENERAL_MOCK, 'Invalid client ID');\n        }\n\n        if ($client_secret != '123456') {\n            throw new Exception(Exception::GENERAL_MOCK, 'Invalid client secret');\n        }\n\n        $responseJson = [\n            'access_token' => '123456',\n            'refresh_token' => 'tuvwxyz',\n            'expires_in' => 14400\n        ];\n\n        if ($grantType === 'authorization_code') {\n            if ($code !== 'abcdef') {\n                throw new Exception(Exception::GENERAL_MOCK, 'Invalid token');\n            }\n\n            $response->json($responseJson);\n        } elseif ($grantType === 'refresh_token') {\n            if ($refreshToken !== 'tuvwxyz') {\n                throw new Exception(Exception::GENERAL_MOCK, 'Invalid refresh token');\n            }\n\n            $response->json($responseJson);\n        } else {\n            throw new Exception(Exception::GENERAL_MOCK, 'Invalid grant type');\n        }\n    }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"}
    {"function": "public function addFieldCollection(string $type, string $fieldname = null): void\n    {\n        $this->setData(null);\n\n        if (empty($type)) {\n            throw new Exception('No fieldcollectiontype given');\n        }\n\n        DataObject\\Fieldcollection\\Definition::getByKey($type);\n        $this->fieldCollectionConfigs[] = ['type' => $type, 'fieldname' => $fieldname];\n    }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"}
    {"function": "public function appendHeader(HTMLTableHeader $header_object, $allow_super_header = false)\n    {\n        $header_name    = '';\n        $subHeader_name = '';\n        $header_object->getHeaderAndSubHeaderName($header_name, $subHeader_name);\n        if (\n            $header_object->isSuperHeader()\n            && (!$this->super)\n            && (!$allow_super_header)\n        ) {\n            throw new \\Exception(sprintf(\n                'Implementation error: invalid super header name \"%s\"',\n                $header_name\n            ));\n        }\n        if (\n            !$header_object->isSuperHeader()\n            && $this->super\n        ) {\n            throw new \\Exception(sprintf(\n                'Implementation error: invalid super header name \"%s\"',\n                $header_name\n            ));\n        }\n\n        if (!isset($this->headers[$header_name])) {\n            $this->headers[$header_name]           = [];\n            $this->headers_order[]                 = $header_name;\n            $this->headers_sub_order[$header_name] = [];\n        }\n        if (!isset($this->headers[$header_name][$subHeader_name])) {\n            $this->headers_sub_order[$header_name][] = $subHeader_name;\n        }\n        $this->headers[$header_name][$subHeader_name] = $header_object;\n        return $header_object;\n    }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"}
    {"function": "protected function searchForBlocksAndApplyProcessing($code, $directive, $functionName) {\n        $markers = array('', '/*ACG_' . $directive . '*/');\n\n        $hasChanged = false;\n\n        foreach ($markers as $marker) {\n            $markerLength = strlen($marker);\n            $codeLength = strlen($code);\n            $callBack = array($this, $functionName);\n\n\n            $startPos = 0;\n            $stopPos = 0;\n            $seekStartPos = 0;\n\n\n            while (1) {\n                $startPos = strpos($code, $marker, $seekStartPos);\n                if ($startPos === false) {\n                    break;\n                }\n                //echo $startPos . '

    ';\n //startPos: before start Marker, stopPos: after stop Marker\n\n $stopPos = strpos($code, $marker, $startPos + 1) + $markerLength;\n if ($stopPos < $startPos) {\n throw new Exception(\"missing stop marker $marker. in file $this->fileBeingProcessed\");\n }\n //blockText: text within the Markers, excluding the Markers\n $blockText = substr($code, $startPos + $markerLength, $stopPos - $startPos - 2 * $markerLength);\n //$processedText = $this->processServiceListBlock($blockText);\n $processedText = call_user_func($callBack, $blockText);\n //up to, but exculding Marker\n $beforeBlock = substr($code, 0, $startPos);\n //after Marker\n $afterBlock = substr($code, $stopPos);\n $code = $beforeBlock . $processedText . $afterBlock;\n $hasChanged = true;\n $seekStartPos = strlen($beforeBlock . $processedText);\n }\n }\n if ($hasChanged) {\n return $code;\n } else {\n return false;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ChristosPapadopoulos23_hackazon", "language": "php"} {"function": "public function renderTemplate(Container $container, ?string $partial = null): string\n {\n if (null === $partial) {\n $partial = $this->getTemplate();\n }\n\n if (empty($partial)) {\n throw new Exception('Unable to render menu: No partial view script provided');\n }\n\n $pages = $this->getPages($container);\n\n return $this->templatingEngine->render($partial, compact('pages'));\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function __construct() {\n if (is_null(self::$impl)) {\n try {\n self::$impl = new Extension();\n } catch (RuntimeException $rex) {\n throw new RuntimeException(\"Unable to initialize AWS CRT via awscrt extension: \\n$rex\", -1);\n }\n }\n ++self::$refcount;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function tokenize($string)\n {\n $string = preg_replace('(\\\\r\\\\n|\\\\r)', \"\\n\", $string);\n $tokens = [];\n $line = 1;\n\n while (strlen($string)) {\n foreach ($this->tokenSpecifications as $token => $regexp) {\n if (!preg_match($regexp, $string, $matches)) {\n continue;\n }\n\n // Remove matched string\n $string = substr($string, strlen($matches[0]));\n $line += substr_count($matches[0], \"\\n\");\n\n // Append token to list\n $tokens[] = [\n 'type' => $token,\n 'data' => $this->filterValues($matches),\n ];\n\n // Continue with outer loop\n continue 2;\n }\n\n throw new RuntimeException(\"Parse error in line $line: \" . substr($string, 0, 100));\n }\n\n return $tokens;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getConnection() {\n\t\tif ($this->connection !== null) {\n\t\t\treturn $this->connection;\n\t\t}\n\n\t\t$scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';\n\t\t$base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';\n\n\t\t// Adding explicit credential provider to the beginning chain.\n\t\t// Including default credential provider (skipping AWS shared config files).\n\t\t$provider = CredentialProvider::memoize(\n\t\t\tCredentialProvider::chain(\n\t\t\t\t$this->paramCredentialProvider(),\n\t\t\t\tCredentialProvider::defaultProvider(['use_aws_shared_config_files' => false])\n\t\t\t)\n\t\t);\n\n\t\t$options = [\n\t\t\t'version' => $this->params['version'] ?? 'latest',\n\t\t\t'credentials' => $provider,\n\t\t\t'endpoint' => $base_url,\n\t\t\t'region' => $this->params['region'],\n\t\t\t'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,\n\t\t\t'signature_provider' => \\Aws\\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider()),\n\t\t\t'csm' => false,\n\t\t\t'use_arn_region' => false,\n\t\t\t'http' => [\n\t\t\t\t'verify' => $this->getCertificateBundlePath(),\n\t\t\t\t// Timeout for the connection to S3 server, not for the request.\n\t\t\t\t'connect_timeout' => 5\n\t\t\t],\n\t\t\t'use_aws_shared_config_files' => false,\n\t\t];\n\n\t\tif ($this->params['s3-accelerate']) {\n\t\t\t$options['use_accelerate_endpoint'] = true;\n\t\t} else {\n\t\t\t$options['endpoint'] = $base_url;\n\t\t}\n\n\t\tif ($this->getProxy()) {\n\t\t\t$options['http']['proxy'] = $this->getProxy();\n\t\t}\n\t\tif (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {\n\t\t\t$options['signature_version'] = 'v2';\n\t\t}\n\t\t$this->connection = new S3Client($options);\n\n\t\ttry {\n\t\t\t$logger = Server::get(LoggerInterface::class);\n\t\t\tif (!$this->connection::isBucketDnsCompatible($this->bucket)) {\n\t\t\t\t$logger->debug('Bucket \"' . $this->bucket . '\" This bucket name is not dns compatible, it may contain invalid characters.',\n\t\t\t\t\t['app' => 'objectstore']);\n\t\t\t}\n\t\n\t\t\tif ($this->params['verify_bucket_exists'] && !$this->connection->doesBucketExist($this->bucket)) {\n\t\t\t\ttry {\n\t\t\t\t\t$logger->info('Bucket \"' . $this->bucket . '\" does not exist - creating it.', ['app' => 'objectstore']);\n\t\t\t\t\tif (!$this->connection::isBucketDnsCompatible($this->bucket)) {\n\t\t\t\t\t\tthrow new \\Exception(\"The bucket will not be created because the name is not dns compatible, please correct it: \" . $this->bucket);\n\t\t\t\t\t}\n\t\t\t\t\t$this->connection->createBucket(['Bucket' => $this->bucket]);\n\t\t\t\t\t$this->testTimeout();\n\t\t\t\t} catch (S3Exception $e) {\n\t\t\t\t\t$logger->debug('Invalid remote storage.', [\n\t\t\t\t\t\t'exception' => $e,\n\t\t\t\t\t\t'app' => 'objectstore',\n\t\t\t\t\t]);\n\t\t\t\t\tif ($e->getAwsErrorCode() !== 'BucketAlreadyOwnedByYou') {\n\t\t\t\t\t\tthrow new \\Exception('Creation of bucket \"' . $this->bucket . '\" failed. ' . $e->getMessage());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\t// google cloud's s3 compatibility doesn't like the EncodingType parameter\n\t\t\tif (strpos($base_url, 'storage.googleapis.com')) {\n\t\t\t\t$this->connection->getHandlerList()->remove('s3.auto_encode');\n\t\t\t}\n\t\t} catch (S3Exception $e) {\n\t\t\tthrow new \\Exception('S3 service is unable to handle request: ' . $e->getMessage());\n\t\t}\n\n\t\treturn $this->connection;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function create(array $userOptions): Creatable\n {\n if (!isset($userOptions['imageId']) && !isset($userOptions['blockDeviceMapping'][0]['uuid'])) {\n throw new \\RuntimeException('imageId or blockDeviceMapping.uuid must be set.');\n }\n\n $response = $this->execute($this->api->postServer(), $userOptions);\n\n return $this->populateFromResponse($response);\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function parseFunctionLike(\n PrettyPrinterAbstract $prettyPrinter,\n FunctionOrMethodName $name,\n int $classFlags,\n int $flags,\n Node\\FunctionLike $func,\n ?string $cond\n): FuncInfo {\n $comment = $func->getDocComment();\n $paramMeta = [];\n $aliasType = null;\n $alias = null;\n $isDeprecated = false;\n $verify = true;\n $docReturnType = null;\n $docParamTypes = [];\n\n if ($comment) {\n $tags = parseDocComment($comment);\n foreach ($tags as $tag) {\n if ($tag->name === 'prefer-ref') {\n $varName = $tag->getVariableName();\n if (!isset($paramMeta[$varName])) {\n $paramMeta[$varName] = [];\n }\n $paramMeta[$varName]['preferRef'] = true;\n } else if ($tag->name === 'alias' || $tag->name === 'implementation-alias') {\n $aliasType = $tag->name;\n $aliasParts = explode(\"::\", $tag->getValue());\n if (count($aliasParts) === 1) {\n $alias = new FunctionName(new Name($aliasParts[0]));\n } else {\n $alias = new MethodName(new Name($aliasParts[0]), $aliasParts[1]);\n }\n } else if ($tag->name === 'deprecated') {\n $isDeprecated = true;\n } else if ($tag->name === 'no-verify') {\n $verify = false;\n } else if ($tag->name === 'return') {\n $docReturnType = $tag->getType();\n } else if ($tag->name === 'param') {\n $docParamTypes[$tag->getVariableName()] = $tag->getType();\n }\n }\n }\n\n $varNameSet = [];\n $args = [];\n $numRequiredArgs = 0;\n $foundVariadic = false;\n foreach ($func->getParams() as $i => $param) {\n $varName = $param->var->name;\n $preferRef = !empty($paramMeta[$varName]['preferRef']);\n unset($paramMeta[$varName]);\n\n if (isset($varNameSet[$varName])) {\n throw new Exception(\"Duplicate parameter name $varName for function $name\");\n }\n $varNameSet[$varName] = true;\n\n if ($preferRef) {\n $sendBy = ArgInfo::SEND_PREFER_REF;\n } else if ($param->byRef) {\n $sendBy = ArgInfo::SEND_BY_REF;\n } else {\n $sendBy = ArgInfo::SEND_BY_VAL;\n }\n\n if ($foundVariadic) {\n throw new Exception(\"Error in function $name: only the last parameter can be variadic\");\n }\n\n $type = $param->type ? Type::fromNode($param->type) : null;\n if ($type === null && !isset($docParamTypes[$varName])) {\n throw new Exception(\"Missing parameter type for function $name()\");\n }\n\n if ($param->default instanceof Expr\\ConstFetch &&\n $param->default->name->toLowerString() === \"null\" &&\n $type && !$type->isNullable()\n ) {\n $simpleType = $type->tryToSimpleType();\n if ($simpleType === null) {\n throw new Exception(\n \"Parameter $varName of function $name has null default, but is not nullable\");\n }\n }\n\n $foundVariadic = $param->variadic;\n\n $args[] = new ArgInfo(\n $varName,\n $sendBy,\n $param->variadic,\n $type,\n isset($docParamTypes[$varName]) ? Type::fromPhpDoc($docParamTypes[$varName]) : null,\n $param->default ? $prettyPrinter->prettyPrintExpr($param->default) : null\n );\n if (!$param->default && !$param->variadic) {\n $numRequiredArgs = $i + 1;\n }\n }\n\n foreach (array_keys($paramMeta) as $var) {\n throw new Exception(\"Found metadata for invalid param $var of function $name\");\n }\n\n $returnType = $func->getReturnType();\n if ($returnType === null && $docReturnType === null && !$name->isConstructor() && !$name->isDestructor()) {\n throw new Exception(\"Missing return type for function $name()\");\n }\n\n $return = new ReturnInfo(\n $func->returnsByRef(),\n $returnType ? Type::fromNode($returnType) : null,\n $docReturnType ? Type::fromPhpDoc($docReturnType) : null\n );\n\n return new FuncInfo(\n $name,\n $classFlags,\n $flags,\n $aliasType,\n $alias,\n $isDeprecated,\n $verify,\n $args,\n $return,\n $numRequiredArgs,\n $cond\n );\n}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (array $queries, Response $response, Document $user, Database $dbForProject) {\n\n $queries = Query::parseQueries($queries);\n\n $queries[] = Query::equal('userInternalId', [$user->getInternalId()]);\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $identityId = $cursor->getValue();\n $cursorDocument = $dbForProject->getDocument('identities', $identityId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Identity '{$identityId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $results = $dbForProject->find('identities', $queries);\n $total = $dbForProject->count('identities', $filterQueries, APP_LIMIT_COUNT);\n\n $response->dynamic(new Document([\n 'identities' => $results,\n 'total' => $total,\n ]), Response::MODEL_IDENTITY_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function setStat($stat)\n {\n $permitted_statistics = $this->realm->getStatisticIds();\n\n if ($stat == 'all') {\n $this->_main_stat_field = null;\n foreach ($permitted_statistics as $stat_name) {\n $this->addStatField($this->realm->getStatisticObject($stat_name));\n }\n } else {\n if (!in_array($stat, $permitted_statistics)) {\n throw new \\Exception(\n sprintf(\"Statistic %s is not available for Group By %s\", $stat, $this->_group_by !== null ? $this->_group_by->getId() : 'null')\n );\n }\n\n $this->logger->debug(\n sprintf(\"%s: Set primary statistic field: %s\", $this, $stat)\n );\n\n $this->_main_stat_field = $this->realm->getStatisticObject($stat);\n foreach ($permitted_statistics as $stat_name) {\n $this->addStatField($this->realm->getStatisticObject($stat_name));\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function __construct(\n array $parameters,\n $stat = \"all\"\n ) {\n parent::__construct('Gateways', 'modw_gateways', 'gatewayfact_by_day', array());\n\n // The same fact table row may correspond to multiple rows in the\n // aggregate table (e.g. a job that runs over two days).\n $this->setDistinct(true);\n\n $config = RawStatisticsConfiguration::factory();\n\n // The data table is always aliased to \"agg\".\n $tables = ['agg' => $this->getDataTable()];\n\n foreach ($config->getQueryTableDefinitions('Gateways') as $tableDef) {\n $alias = $tableDef['alias'];\n $table = new Table(\n new Schema($tableDef['schema']),\n $tableDef['name'],\n $alias\n );\n $tables[$alias] = $table;\n $this->addTable($table);\n\n $join = $tableDef['join'];\n $this->addWhereCondition(new WhereCondition(\n new TableField($table, $join['primaryKey']),\n '=',\n new TableField($tables[$join['foreignTableAlias']], $join['foreignKey'])\n ));\n }\n\n // This table is defined in the configuration file, but used in the section below.\n $factTable = $tables['jt'];\n\n if (isset($parameters['primary_key'])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'job_id'), \"=\", $parameters['primary_key']));\n } elseif (isset($parameters['job_identifier'])) {\n $matches = array();\n if (preg_match('/^(\\d+)(?:[\\[_](\\d+)\\]?)?$/', $parameters['job_identifier'], $matches)) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'resource_id'), '=', $parameters['resource_id']));\n if (isset($matches[2])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_jobid'), '=', $matches[1]));\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_job_array_index'), '=', $matches[2]));\n } else {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_job_id_raw'), '=', $matches[1]));\n }\n } else {\n throw new Exception('invalid \"job_identifier\" query parameter');\n }\n } elseif (isset($parameters['start_date']) && isset($parameters['end_date'])) {\n $startDate = date_parse_from_format('Y-m-d', $parameters['start_date']);\n $startDateTs = mktime(\n 0,\n 0,\n 0,\n $startDate['month'],\n $startDate['day'],\n $startDate['year']\n );\n if ($startDateTs === false) {\n throw new Exception('invalid \"start_date\" query parameter');\n }\n\n $endDate = date_parse_from_format('Y-m-d', $parameters['end_date']);\n $endDateTs = mktime(\n 23,\n 59,\n 59,\n $endDate['month'],\n $endDate['day'],\n $endDate['year']\n );\n if ($endDateTs === false) {\n throw new Exception('invalid \"end_date\" query parameter');\n }\n\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'end_time_ts'), \">=\", $startDateTs));\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'end_time_ts'), \"<=\", $endDateTs));\n } else {\n throw new Exception('invalid query parameters');\n }\n\n if ($stat == \"accounting\" || $stat == 'batch') {\n foreach ($config->getQueryFieldDefinitions('Gateways') as $field) {\n $alias = $field['name'];\n if (isset($field['tableAlias']) && isset($field['column'])) {\n $this->addField(new TableField(\n $tables[$field['tableAlias']],\n $field['column'],\n $alias\n ));\n } elseif (isset($field['formula'])) {\n $this->addField(new FormulaField($field['formula'], $alias));\n } else {\n throw new Exception(sprintf(\n 'Missing tableAlias and column or formula for \"%s\", definition: %s',\n $alias,\n json_encode($field)\n ));\n }\n $this->documentation[$alias] = $field;\n }\n } else {\n $this->addField(new TableField($factTable, \"job_id\", \"jobid\"));\n $this->addField(new TableField($factTable, \"local_jobid\", \"local_job_id\"));\n\n $rt = new Table(new Schema(\"modw\"), \"resourcefact\", \"rf\");\n $this->joinTo($rt, \"task_resource_id\", \"code\", \"resource\");\n\n // Instead of Person we use Gateway table, for Gateways realm\n $pt = new Table(new Schema('modw_gateways'), 'gateway', 'p');\n // here we are joining to the gatewayfact_by_day table on person_id\n $this->joinTo($pt, \"person_id\", \"long_name\", \"name\", \"proxy_person_id\");\n\n $st = new Table(new Schema('modw'), 'systemaccount', 'sa');\n $this->joinTo($st, \"systemaccount_id\", \"username\", \"username\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function correctPath(): void\n {\n // set path\n if ($this->getId() != 1) { // not for the root node\n if (!Element\\Service::isValidKey($this->getKey(), 'asset')) {\n throw new Exception(\"invalid filename '\" . $this->getKey() . \"' for asset with id [ \" . $this->getId() . ' ]');\n }\n\n if (!$this->getParentId()) {\n throw new Exception('ParentID is mandatory and can\u00b4t be null. If you want to add the element as a child to the tree\u00b4s root node, consider setting ParentID to 1.');\n }\n\n if ($this->getParentId() == $this->getId()) {\n throw new Exception(\"ParentID and ID are identical, an element can't be the parent of itself in the tree.\");\n }\n\n if ($this->getFilename() === '..' || $this->getFilename() === '.') {\n throw new Exception('Cannot create asset called \"..\" or \".\"');\n }\n\n $parent = Asset::getById($this->getParentId());\n if (!$parent) {\n throw new Exception('ParentID not found.');\n }\n\n // use the parent's path from the database here (getCurrentFullPath),\n //to ensure the path really exists and does not rely on the path\n // that is currently in the parent asset (in memory),\n //because this might have changed but wasn't not saved\n $this->setPath(str_replace('//', '/', $parent->getCurrentFullPath() . '/'));\n } elseif ($this->getId() == 1) {\n // some data in root node should always be the same\n $this->setParentId(0);\n $this->setPath('/');\n $this->setFilename('');\n $this->setType('folder');\n }\n\n // do not allow PHP and .htaccess files\n if (preg_match(\"@\\.ph(p[\\d+]?|t|tml|ps|ar)$@i\", $this->getFilename()) || $this->getFilename() == '.htaccess') {\n $this->setFilename($this->getFilename() . '.txt');\n }\n\n if (mb_strlen($this->getFilename()) > 255) {\n throw new Exception('Filenames longer than 255 characters are not allowed');\n }\n\n if (Asset\\Service::pathExists($this->getRealFullPath())) {\n $duplicate = Asset::getByPath($this->getRealFullPath());\n if ($duplicate instanceof Asset && $duplicate->getId() != $this->getId()) {\n $duplicateFullPathException = new DuplicateFullPathException('Duplicate full path [ ' . $this->getRealFullPath() . ' ] - cannot save asset');\n $duplicateFullPathException->setDuplicateElement($duplicate);\n $duplicateFullPathException->setCauseElement($this);\n\n throw $duplicateFullPathException;\n }\n }\n\n $this->validatePathLength();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $projectId, string $name, array $scopes, ?string $expire, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $key = new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'projectInternalId' => $project->getInternalId(),\n 'projectId' => $project->getId(),\n 'name' => $name,\n 'scopes' => $scopes,\n 'expire' => $expire,\n 'sdks' => [],\n 'accessedAt' => null,\n 'secret' => \\bin2hex(\\random_bytes(128)),\n ]);\n\n $key = $dbForConsole->createDocument('keys', $key);\n\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($key, Response::MODEL_KEY);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function cropImage($newWidth, $newHeight, $cropPos = 'm')\n\t\t# Author: Jarrod Oberto\n\t\t# Date: 08-09-11\n\t\t# Purpose: Crops the image\n\t\t# Param in: $newWidth: crop with\n\t\t# $newHeight: crop height\n\t\t# $cropPos: Can be any of the following:\n\t\t# tl, t, tr, l, m, r, bl, b, br, auto\n\t\t# Or:\n\t\t# a custom position such as '30x50'\n\t\t# Param out: n/a\n\t\t# Reference:\n\t\t# Notes:\n\t\t#\n\t{\n\n\t\t// *** Make sure the file passed in is valid\n\t\tif ( ! $this->image)\n\t\t{\n\t\t\tif ($this->debug)\n\t\t\t{\n\t\t\t\tthrow new Exception('file ' . $this->getFileName() . ' is missing or invalid');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow new Exception();\n\t\t\t}\n\t\t};\n\n\t\t$this->imageResized = $this->image;\n\t\t$this->crop($this->width, $this->height, $newWidth, $newHeight, $cropPos);\n\n\t}", "smellKey": "S112", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public function execute($force = false, bool $enable_partial_warnings = true)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n if (\n ($force === true)\n || (($this->fields['do_count'] == self::COUNT_YES)\n || ($this->fields['do_count'] == self::COUNT_AUTO)\n && ($this->getField('last_execution_time') != null)\n && ($this->fields['last_execution_time'] <= $CFG_GLPI['max_time_for_count']))\n ) {\n $search = new Search();\n //Do the same as self::getParameters() but getFromDB is useless\n $query_tab = [];\n parse_str($this->getField('query'), $query_tab);\n\n $params = null;\n if (class_exists($this->getField('itemtype'))) {\n $params = $this->prepareQueryToUse(\n $this->getField('type'),\n $query_tab,\n $enable_partial_warnings\n );\n }\n\n if (!$params) {\n throw new \\RuntimeException('Saved search #' . $this->getID() . ' seems to be broken!');\n } else {\n $data = $search->prepareDatasForSearch(\n $this->getField('itemtype'),\n $params\n );\n // force saved search ID to indicate to Search to save execution time\n $data['search']['savedsearches_id'] = $this->getID();\n $data['search']['sort'] = [];\n $search->constructSQL($data);\n $search->constructData($data, true);\n return $data;\n }\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function doQuery($query)\n {\n $debug_data = [\n 'query' => $query,\n 'time' => 0,\n 'rows' => 0,\n 'errors' => '',\n 'warnings' => '',\n ];\n\n $start_time = microtime(true);\n\n $this->checkForDeprecatedTableOptions($query);\n\n $res = $this->dbh->query($query);\n if (!$res) {\n throw new \\RuntimeException(\n sprintf(\n 'MySQL query error: %s (%d) in SQL query \"%s\".',\n $this->dbh->error,\n $this->dbh->errno,\n $query\n )\n );\n }\n\n $duration = (microtime(true) - $start_time) * 1000;\n\n $debug_data['time'] = $duration;\n $debug_data['rows'] = $this->affectedRows();\n\n // Ensure that we collect warning after affected rows\n $this->last_query_warnings = $this->fetchQueryWarnings();\n\n $warnings_string = implode(\n \"\\n\",\n array_map(\n static function ($warning) {\n return sprintf('%s: %s', $warning['Code'], $warning['Message']);\n },\n $this->last_query_warnings\n )\n );\n $debug_data['warnings'] = $warnings_string;\n\n // Output warnings in SQL log\n if (!empty($this->last_query_warnings)) {\n $message = sprintf(\n \" *** MySQL query warnings:\\n SQL: %s\\n Warnings: \\n%s\\n\",\n $query,\n $warnings_string\n );\n $message .= Toolbox::backtrace(false, 'DBmysql->doQuery()', ['Toolbox::backtrace()']);\n Toolbox::logSqlWarning($message);\n\n ErrorHandler::getInstance()->handleSqlWarnings($this->last_query_warnings, $query);\n }\n\n if (isset($_SESSION['glpi_use_mode']) && ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE)) {\n \\Glpi\\Debug\\Profile::getCurrent()->addSQLQueryData(\n $debug_data['query'],\n $debug_data['time'],\n $debug_data['rows'],\n $debug_data['errors'],\n $debug_data['warnings']\n );\n }\n\n if ($this->execution_time === true) {\n $this->execution_time = $duration;\n }\n return $res;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function updateComments(): void\n {\n $comments = $this->input['_comments'] ?? [];\n\n // Keep track of comments found\n $found_comments = [];\n\n // Parse each submitted comment\n foreach ($comments as $comment_data) {\n $comment = new Comment();\n\n // Read uuids\n $uuid = $comment_data['uuid'] ?? '';\n if (empty($uuid)) {\n throw new RuntimeException(\n \"UUID is missing: \" . json_decode($comment_data)\n );\n }\n\n $section_uuid = $comment_data['forms_sections_uuid'] ?? '';\n if (empty($section_uuid)) {\n throw new RuntimeException(\n \"Parent section UUID is missing: \" . json_decode($comment_data)\n );\n }\n\n // Get parent id\n $section = Section::getByUuid($section_uuid);\n if ($section === null) {\n throw new RuntimeException(\"Parent section not found: $section_uuid\");\n }\n $comment_data['forms_sections_id'] = $section->getID();\n\n $comment = Comment::getByUuid($uuid);\n if ($comment === null) {\n // Add new question\n $comment = new Comment();\n $id = $comment->add($comment_data);\n\n if (!$id) {\n throw new RuntimeException(\"Failed to add comment\");\n }\n } else {\n // Update existing comment\n $comment_data['id'] = $comment->getID();\n\n $success = $comment->update($comment_data);\n if (!$success) {\n throw new RuntimeException(\"Failed to update comment\");\n }\n $id = $comment->getID();\n }\n // Keep track of its id\n $found_comments[] = $id;\n }\n\n // Deletion will be handled in a separate method\n $this->input['_found_comments'] = $found_comments;\n\n // Special input has been handled, it can be deleted\n unset($this->input['_comments']);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private static function validateType(string $type): bool\n {\n if (!in_array($type, self::ALLOWED_TYPES)) {\n throw new Exception(sprintf('Invalid type `%s`, allowed types are %s', $type, implode(',', self::ALLOWED_TYPES)));\n }\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function fromPayload(string $event, Document $payload, Document $project = null, Document $database = null, Document $collection = null, Document $bucket = null): array\n {\n $channels = [];\n $roles = [];\n $permissionsChanged = false;\n $projectId = null;\n // TODO: add method here to remove all the magic index accesses\n $parts = explode('.', $event);\n\n switch ($parts[0]) {\n case 'users':\n $channels[] = 'account';\n $channels[] = 'account.' . $parts[1];\n $roles = [Role::user(ID::custom($parts[1]))->toString()];\n break;\n case 'rules':\n $channels[] = 'console';\n $projectId = 'console';\n $roles = [Role::team($project->getAttribute('teamId'))->toString()];\n break;\n case 'teams':\n if ($parts[2] === 'memberships') {\n $permissionsChanged = $parts[4] ?? false;\n $channels[] = 'memberships';\n $channels[] = 'memberships.' . $parts[3];\n } else {\n $permissionsChanged = $parts[2] === 'create';\n $channels[] = 'teams';\n $channels[] = 'teams.' . $parts[1];\n }\n $roles = [Role::team(ID::custom($parts[1]))->toString()];\n break;\n case 'databases':\n if (in_array($parts[4] ?? [], ['attributes', 'indexes'])) {\n $channels[] = 'console';\n $projectId = 'console';\n $roles = [Role::team($project->getAttribute('teamId'))->toString()];\n } elseif (($parts[4] ?? '') === 'documents') {\n if ($database->isEmpty()) {\n throw new \\Exception('Database needs to be passed to Realtime for Document events in the Database.');\n }\n if ($collection->isEmpty()) {\n throw new \\Exception('Collection needs to be passed to Realtime for Document events in the Database.');\n }\n\n $channels[] = 'documents';\n $channels[] = 'databases.' . $database->getId() . '.collections.' . $payload->getAttribute('$collectionId') . '.documents';\n $channels[] = 'databases.' . $database->getId() . '.collections.' . $payload->getAttribute('$collectionId') . '.documents.' . $payload->getId();\n\n $roles = $collection->getAttribute('documentSecurity', false)\n ? \\array_merge($collection->getRead(), $payload->getRead())\n : $collection->getRead();\n }\n break;\n case 'buckets':\n if ($parts[2] === 'files') {\n if ($bucket->isEmpty()) {\n throw new \\Exception('Bucket needs to be passed to Realtime for File events in the Storage.');\n }\n $channels[] = 'files';\n $channels[] = 'buckets.' . $payload->getAttribute('bucketId') . '.files';\n $channels[] = 'buckets.' . $payload->getAttribute('bucketId') . '.files.' . $payload->getId();\n\n $roles = $bucket->getAttribute('fileSecurity', false)\n ? \\array_merge($bucket->getRead(), $payload->getRead())\n : $bucket->getRead();\n }\n\n break;\n\n case 'functions':\n if ($parts[2] === 'executions') {\n if (!empty($payload->getRead())) {\n $channels[] = 'console';\n $channels[] = 'executions';\n $channels[] = 'executions.' . $payload->getId();\n $channels[] = 'functions.' . $payload->getAttribute('functionId');\n $roles = $payload->getRead();\n }\n } elseif ($parts[2] === 'deployments') {\n $channels[] = 'console';\n $projectId = 'console';\n $roles = [Role::team($project->getAttribute('teamId'))->toString()];\n }\n\n break;\n case 'migrations':\n $channels[] = 'console';\n $projectId = 'console';\n $roles = [Role::team($project->getAttribute('teamId'))->toString()];\n break;\n }\n\n return [\n 'channels' => $channels,\n 'roles' => $roles,\n 'permissionsChanged' => $permissionsChanged,\n 'projectId' => $projectId\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function logCCDA($pid, $encounter, $content, $time, $status, $user_id, $document_type, $view = 0, $transfer = 0, $emr_transfer = 0)\n {\n $content = base64_decode($content);\n $document = new \\Document();\n $document_type = $document_type ?? '';\n\n // we need to populate the category id based upon the document_type\n // TOC -> CCDA folder\n // CCD -> TOC\n //\n $categoryId = QueryUtils::fetchSingleValue(\n 'Select `id` FROM categories WHERE name=?',\n 'id',\n [self::CCDA_DOCUMENT_FOLDER]\n );\n\n if ($categoryId === false) {\n throw new RuntimeException(\"document category id does not exist in system\");\n }\n\n // we want to grab the patient name here so we can provide a human readable document name\n $binaryUuid = (new UuidRegistry(['table_name' => 'ccda']))->createUuid();\n $patientService = new PatientService();\n $patient = $patientService->findByPid($pid);\n if (!empty($patient)) {\n // should always be populated...\n // we are only supporting xml for now\n $file_name = \"CCDA_\" . $patient['lname'] . '_' . $patient['fname'];\n if (!empty($document_type)) {\n $file_name .= '_' . $document_type;\n }\n $file_name .= '_' . date(\"Y-m-d\") . \".xml\";\n } else {\n $file_name = UuidRegistry::uuidToString($binaryUuid) . \".xml\";\n }\n\n $mimeType = \"text/xml\";\n\n try {\n \\sqlBeginTrans();\n\n // set the foreign key so we can track documents connected to a specific export\n $result = $document->createDocument(\n $pid,\n $categoryId,\n $file_name,\n $mimeType,\n $content\n );\n if (!empty($result)) {\n throw new \\RuntimeException(\"Failed to save document for ccda. Message: \" . $result);\n }\n\n $file_path = $document->get_url();\n $docid = $document->get_couch_docid();\n $revid = $document->get_couch_revid();\n $hash = $document->get_hash();\n $encrypted = $document->is_encrypted();\n $referralId = $this->getMostRecentPatientReferral($pid);\n\n $query = \"insert into ccda (`uuid`, `pid`, `encounter`, `ccda_data`, `time`, `status`, `user_id`, `couch_docid`, `couch_revid`, `hash`, `view`, `transfer`, `emr_transfer`, `encrypted`, `transaction_id`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n $appTable = new ApplicationTable();\n $result = $appTable->zQuery($query, array($binaryUuid, $pid, $encounter, $file_path, $time, $status, $user_id, $docid, $revid, $hash, $view, $transfer, $emr_transfer, $encrypted, $referralId));\n\n // now let's go ahead and log our amc actions for this behavior\n if (!empty($emr_transfer)) {\n $this->logAmc($pid, $referralId);\n }\n $moduleInsertId = $result->getGeneratedValue();\n\n // if we have an id, then let's update our document with the foreign key reference\n $document->set_foreign_reference_id($moduleInsertId);\n $document->set_foreign_reference_table('ccda');\n // if we have encounter information we are going to populate it.\n if (!empty($encounter)) {\n $document->set_encounter_check(0);\n $document->set_encounter_id($encounter);\n }\n $document->persist(); // save the updated references here.\n \\sqlCommitTrans();\n } catch (\\Exception $exception) {\n \\sqlRollbackTrans();\n // TODO: @adunsulag do we need to clean up the file if we fail to commit the transaction here?\n throw $exception;\n }\n return new GeneratedCcdaResult($moduleInsertId, UuidRegistry::uuidToString($binaryUuid), $file_name, $content);\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function clearGroupCache($gid) {\n\t\tif (!$this->groupBackend->groupExists($gid)) {\n\t\t\tthrow new \\Exception('Group id not found in LDAP');\n\t\t}\n\t\t$this->groupBackend->getLDAPAccess($gid)->getConnection()->clearCache();\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function testContentTypeLimitationForbid()\n {\n $this->expectException(UnauthorizedException::class);\n\n $repository = $this->getRepository();\n $permissionResolver = $repository->getPermissionResolver();\n\n $contentService = $repository->getContentService();\n\n $contentTypeId = $this->generateId('contentType', 33);\n /* BEGIN: Use Case */\n $user = $this->createUserVersion1();\n\n $roleService = $repository->getRoleService();\n\n $role = $roleService->loadRoleByIdentifier('Editor');\n $roleDraft = $roleService->createRoleDraft($role);\n $editPolicy = null;\n /** @var \\Ibexa\\Contracts\\Core\\Repository\\Values\\User\\PolicyDraft $policy */\n foreach ($roleDraft->getPolicies() as $policy) {\n if ('content' != $policy->module || 'edit' != $policy->function) {\n continue;\n }\n $editPolicy = $policy;\n break;\n }\n\n if (null === $editPolicy) {\n throw new \\ErrorException('No content:edit policy found.');\n }\n\n $policyUpdate = $roleService->newPolicyUpdateStruct();\n $policyUpdate->addLimitation(\n new ContentTypeLimitation(\n ['limitationValues' => [$contentTypeId]]\n )\n );\n\n $roleService->updatePolicyByRoleDraft(\n $roleDraft,\n $editPolicy,\n $policyUpdate\n );\n $roleService->publishRoleDraft($roleDraft);\n $roleService->assignRoleToUser($roleService->loadRole($role->id), $user);\n\n $content = $this->createWikiPage();\n\n $permissionResolver->setCurrentUserReference($user);\n\n // This call fails with an UnauthorizedException\n $contentService->createContentDraft($content->contentInfo);\n /* END: Use Case */\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function decrypt(?string $data, array $params = []): ?string\n {\n if ($data) {\n $object = $params['object'] ?? null;\n $fd = $params['fieldDefinition'];\n $delegateFd = $fd->getDelegate();\n\n try {\n $key = Pimcore::getContainer()->getParameter('pimcore.encryption.secret');\n\n try {\n $key = Key::loadFromAsciiSafeString($key);\n } catch (Exception $e) {\n throw new Exception('could not load key');\n }\n\n if (!(isset($params['skipDecryption']) && $params['skipDecryption'])) {\n $data = Crypto::decrypt($data, $key);\n }\n\n if ($delegateFd instanceof AfterDecryptionUnmarshallerInterface) {\n $data = $delegateFd->unmarshalAfterDecryption($data, $object, $params);\n }\n\n return $data;\n } catch (Exception $e) {\n Logger::error((string) $e);\n\n throw new Exception('encrypted field ' . $delegateFd->getName() . ' cannot be decoded');\n }\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __set(string $name, mixed $value): void\n {\n $requestAttributes = ['document', 'editmode'];\n if (in_array($name, $requestAttributes)) {\n throw new RuntimeException(sprintf(\n 'Property \"%s\" is a request attribute and can\\'t be set on the controller instance',\n $name\n ));\n }\n\n throw new RuntimeException(sprintf('Trying to set unknown property \"%s\"', $name));\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $email, string $password, Request $request, Response $response, Document $user, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) {\n\n $email = \\strtolower($email);\n $protocol = $request->getProtocol();\n\n $profile = $dbForProject->findOne('users', [\n Query::equal('email', [$email]),\n ]);\n\n if (!$profile || empty($profile->getAttribute('passwordUpdate')) || !Auth::passwordVerify($password, $profile->getAttribute('password'), $profile->getAttribute('hash'), $profile->getAttribute('hashOptions'))) {\n throw new Exception(Exception::USER_INVALID_CREDENTIALS);\n }\n\n if (false === $profile->getAttribute('status')) { // Account is blocked\n throw new Exception(Exception::USER_BLOCKED); // User is in status blocked\n }\n\n $user->setAttributes($profile->getArrayCopy());\n\n $duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), $duration));\n $secret = Auth::tokenGenerator();\n $session = new Document(array_merge(\n [\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => Auth::SESSION_PROVIDER_EMAIL,\n 'providerUid' => $email,\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ],\n $detector->getOS(),\n $detector->getClient(),\n $detector->getDevice()\n ));\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n // Re-hash if not using recommended algo\n if ($user->getAttribute('hash') !== Auth::DEFAULT_ALGO) {\n $user\n ->setAttribute('password', Auth::passwordHash($password, Auth::DEFAULT_ALGO, Auth::DEFAULT_ALGO_OPTIONS))\n ->setAttribute('hash', Auth::DEFAULT_ALGO)\n ->setAttribute('hashOptions', Auth::DEFAULT_ALGO_OPTIONS);\n $dbForProject->updateDocument('users', $user->getId(), $user);\n }\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $session = $dbForProject->createDocument('sessions', $session->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n\n if (!Config::getParam('domainVerification')) {\n $response\n ->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]))\n ;\n }\n\n $response\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ;\n\n $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'));\n\n $session\n ->setAttribute('current', true)\n ->setAttribute('countryName', $countryName)\n ->setAttribute('expire', $expire)\n ;\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId())\n ;\n\n $response->dynamic($session, Response::MODEL_SESSION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function preSave(mixed $containerDefinition, array $params = []): void\n {\n $optionsProvider = DataObject\\ClassDefinition\\Helper\\OptionsProviderResolver::resolveProvider(\n $this->getOptionsProviderClass(),\n DataObject\\ClassDefinition\\Helper\\OptionsProviderResolver::MODE_MULTISELECT\n );\n if (!$this->useConfiguredOptions() && $optionsProvider !== null) {\n $context = [];\n $context['fieldname'] = $this->getName();\n\n try {\n $options = $optionsProvider->getOptions($context, $this);\n } catch (Throwable $e) {\n // error from getOptions => no values => no comma => no problems\n $options = null;\n }\n } else {\n $options = $this->getOptions();\n }\n if (is_array($options) && array_reduce($options, static function ($containsComma, $option) {\n return $containsComma || str_contains((string)$option['value'], ',');\n }, false)) {\n throw new Exception(\"Field {$this->getName()}: Multiselect option values may not contain commas (,) for now, see issue #5010.\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $databaseId, Response $response, Database $dbForProject, Event $events, Delete $deletes) {\n\n $database = $dbForProject->getDocument('databases', $databaseId);\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n if (!$dbForProject->deleteDocument('databases', $databaseId)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove collection from DB');\n }\n\n $dbForProject->deleteCachedDocument('databases', $database->getId());\n $dbForProject->deleteCachedCollection('databases_' . $database->getInternalId());\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($database);\n\n $events\n ->setParam('databaseId', $database->getId())\n ->setPayload($response->output($database, Response::MODEL_DATABASE));\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function convertToHtmlEntities(string $htmlContent, string $charset = 'UTF-8'): string\n {\n set_error_handler(function () { throw new \\Exception(); });\n\n try {\n return mb_encode_numericentity($htmlContent, [0x80, 0x10FFFF, 0, 0x1FFFFF], $charset);\n } catch (\\Exception|\\ValueError $e) {\n try {\n $htmlContent = iconv($charset, 'UTF-8', $htmlContent);\n $htmlContent = mb_encode_numericentity($htmlContent, [0x80, 0x10FFFF, 0, 0x1FFFFF], 'UTF-8');\n } catch (\\Exception|\\ValueError $e) {\n }\n\n return $htmlContent;\n } finally {\n restore_error_handler();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(\n $cmd,\n $descriptorspec = [\n 0 => ['pipe', 'r'],\n 1 => ['pipe', 'w'],\n 2 => ['pipe', 'w'],\n ],\n $cwd = null,\n $env = null,\n $blocking = false\n ) {\n $this->_process = proc_open($cmd, $descriptorspec, $this->_pipes, $cwd, $env);\n if (! is_resource($this->_process)) {\n throw new Exception(\"Command failed: $cmd\");\n }\n stream_set_blocking($this->_pipes[1], $blocking);\n stream_set_blocking($this->_pipes[2], $blocking);\n $this->_synchronous = true;\n }", "smellKey": "S112", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function __construct(ResponseInterface $response)\n {\n $statusCode = $response->getStatusCode();\n if (Response::HTTP_OK !== $statusCode) {\n throw new \\Exception('status code : '.$statusCode);\n }\n $dataResponse = $response->toArray();\n if (!isset($dataResponse['rowList']) || !isset($dataResponse['rowList'][0]) || !isset($dataResponse['rowList'][0]['documentZipContent'])) {\n throw new \\Exception('Invalid response');\n }\n $this->documentZipContent = $dataResponse['rowList'][0]['documentZipContent'];\n }", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "public function getProviders(IUser $user): array {\n\t\t$appClasses = $this->getAppProviderClasses($user);\n\t\t$providerClasses = $this->getServerProviderClasses();\n\t\t$allClasses = array_merge($providerClasses, $appClasses);\n\t\t/** @var list $providers */\n\t\t$providers = [];\n\n\t\tforeach ($allClasses as $class) {\n\t\t\ttry {\n\t\t\t\t$provider = $this->serverContainer->get($class);\n\t\t\t\tif ($provider instanceof IProvider || $provider instanceof IBulkProvider) {\n\t\t\t\t\t$providers[] = $provider;\n\t\t\t\t} else {\n\t\t\t\t\t$this->logger->warning('Ignoring invalid contacts menu provider', [\n\t\t\t\t\t\t'class' => $class,\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t} catch (QueryException $ex) {\n\t\t\t\t$this->logger->error(\n\t\t\t\t\t'Could not load contacts menu action provider ' . $class,\n\t\t\t\t\t[\n\t\t\t\t\t\t'app' => 'core',\n\t\t\t\t\t\t'exception' => $ex,\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t\tthrow new Exception('Could not load contacts menu action provider');\n\t\t\t}\n\t\t}\n\n\t\treturn $providers;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected static function getTestServiceId(?string $id, string $className): string\n {\n $kernel = self::$kernel;\n if (!$kernel instanceof IbexaTestKernel) {\n throw new RuntimeException(sprintf(\n 'Expected %s to be an instance of %s.',\n get_class($kernel),\n IbexaTestKernel::class,\n ));\n }\n\n $id = $id ?? $className;\n\n return $kernel->getAliasServiceId($id);\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function (int $connection, SwooleRequest $request) use ($server, $register, $stats, &$realtime, $logError) {\n $app = new App('UTC');\n $request = new Request($request);\n $response = new Response(new SwooleResponse());\n\n Console::info(\"Connection open (user: {$connection})\");\n\n App::setResource('pools', fn() => $register->get('pools'));\n App::setResource('request', fn() => $request);\n App::setResource('response', fn() => $response);\n\n try {\n /** @var \\Utopia\\Database\\Document $project */\n $project = $app->getResource('project');\n\n /*\n * Project Check\n */\n if (empty($project->getId())) {\n throw new Exception('Missing or unknown project ID', 1008);\n }\n\n $dbForProject = getProjectDB($project);\n $console = $app->getResource('console'); /** @var \\Utopia\\Database\\Document $console */\n $user = $app->getResource('user'); /** @var \\Utopia\\Database\\Document $user */\n\n /*\n * Abuse Check\n *\n * Abuse limits are connecting 128 times per minute and ip address.\n */\n $timeLimit = new TimeLimit('url:{url},ip:{ip}', 128, 60, $dbForProject);\n $timeLimit\n ->setParam('{ip}', $request->getIP())\n ->setParam('{url}', $request->getURI());\n\n $abuse = new Abuse($timeLimit);\n\n if (App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled' && $abuse->check()) {\n throw new Exception('Too many requests', 1013);\n }\n\n /*\n * Validate Client Domain - Check to avoid CSRF attack.\n * Adding Appwrite API domains to allow XDOMAIN communication.\n * Skip this check for non-web platforms which are not required to send an origin header.\n */\n $origin = $request->getOrigin();\n $originValidator = new Origin(\\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', [])));\n\n if (!$originValidator->isValid($origin) && $project->getId() !== 'console') {\n throw new Exception($originValidator->getDescription(), 1008);\n }\n\n $roles = Auth::getRoles($user);\n\n $channels = Realtime::convertChannels($request->getQuery('channels', []), $user->getId());\n\n /**\n * Channels Check\n */\n if (empty($channels)) {\n throw new Exception('Missing channels', 1008);\n }\n\n $realtime->subscribe($project->getId(), $connection, $roles, $channels);\n\n $user = empty($user->getId()) ? null : $response->output($user, Response::MODEL_ACCOUNT);\n\n $server->send([$connection], json_encode([\n 'type' => 'connected',\n 'data' => [\n 'channels' => array_keys($channels),\n 'user' => $user\n ]\n ]));\n\n $stats->set($project->getId(), [\n 'projectId' => $project->getId(),\n 'teamId' => $project->getAttribute('teamId')\n ]);\n $stats->incr($project->getId(), 'connections');\n $stats->incr($project->getId(), 'connectionsTotal');\n } catch (\\Throwable $th) {\n call_user_func($logError, $th, \"initServer\");\n\n $response = [\n 'type' => 'error',\n 'data' => [\n 'code' => $th->getCode(),\n 'message' => $th->getMessage()\n ]\n ];\n\n $server->send([$connection], json_encode($response));\n $server->close($connection, $th->getCode());\n\n if (App::isDevelopment()) {\n Console::error('[Error] Connection Error');\n Console::error('[Error] Code: ' . $response['data']['code']);\n Console::error('[Error] Message: ' . $response['data']['message']);\n }\n } finally {\n $register->get('pools')->reclaim();\n }\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (Request $request, Response $response, Document $user, Database $dbForProject, Event $events, EventPhone $messaging, Document $project, Locale $locale) {\n\n if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {\n throw new Exception(Exception::GENERAL_PHONE_DISABLED);\n }\n\n if (empty($user->getAttribute('phone'))) {\n throw new Exception(Exception::USER_PHONE_NOT_FOUND);\n }\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n $secret = Auth::codeGenerator();\n $expire = DateTime::addSeconds(new \\DateTime(), Auth::TOKEN_EXPIRATION_CONFIRM);\n\n $verification = new Document([\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'type' => Auth::TOKEN_TYPE_PHONE,\n 'secret' => Auth::hash($secret),\n 'expire' => $expire,\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n ]);\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $verification = $dbForProject->createDocument('tokens', $verification\n ->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');\n\n $customTemplate = $project->getAttribute('templates', [])['sms.verification-' . $locale->default] ?? [];\n if (!empty($customTemplate)) {\n $message = $customTemplate['message'] ?? $message;\n }\n\n $message = $message->setParam('{{token}}', $secret);\n $message = $message->render();\n\n $messaging\n ->setRecipient($user->getAttribute('phone'))\n ->setMessage($message)\n ->trigger()\n ;\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('tokenId', $verification->getId())\n ->setPayload($response->output(\n $verification->setAttribute('secret', $secret),\n Response::MODEL_TOKEN\n ))\n ;\n\n // Hide secret for clients\n $verification->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $secret : '');\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($verification, Response::MODEL_TOKEN);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addToGroup($uid, $gid) {\n\t\t$plugin = $this->which[GroupInterface::ADD_TO_GROUP];\n\n\t\tif ($plugin) {\n\t\t\treturn $plugin->addToGroup($uid, $gid);\n\t\t}\n\t\tthrow new \\Exception('No plugin implements addToGroup in this LDAP Backend.');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function GetColumns()\n {\n if (! $this->ModelName) {\n throw new Exception(\"ModelName must be defined in \" . get_class($this) . \"::GetColumns\");\n }\n\n $counter = 0;\n $props = array ();\n foreach (get_class_vars($this->ModelName) as $var => $val) {\n $props [$counter++] = $var;\n }\n\n return $props;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function testOwnerLimitationForbid()\n {\n $this->expectException(UnauthorizedException::class);\n\n $repository = $this->getRepository();\n $permissionResolver = $repository->getPermissionResolver();\n\n $contentService = $repository->getContentService();\n\n /* BEGIN: Use Case */\n $user = $this->createUserVersion1();\n\n $roleService = $repository->getRoleService();\n\n $role = $roleService->loadRoleByIdentifier('Editor');\n $roleDraft = $roleService->createRoleDraft($role);\n // Search for the new policy instance\n /** @var \\Ibexa\\Contracts\\Core\\Repository\\Values\\User\\PolicyDraft $policy */\n $removePolicy = null;\n foreach ($roleDraft->getPolicies() as $policy) {\n if ('content' != $policy->module || 'remove' != $policy->function) {\n continue;\n }\n $removePolicy = $policy;\n break;\n }\n\n if (null === $removePolicy) {\n throw new \\ErrorException('No content:remove policy found.');\n }\n\n // Only allow remove for the user's own content\n $policyUpdate = $roleService->newPolicyUpdateStruct();\n $policyUpdate->addLimitation(\n new OwnerLimitation(\n ['limitationValues' => [1]]\n )\n );\n $roleService->updatePolicyByRoleDraft(\n $roleDraft,\n $removePolicy,\n $policyUpdate\n );\n $roleService->publishRoleDraft($roleDraft);\n\n $roleService->assignRoleToUser($role, $user);\n\n $content = $this->createWikiPage();\n\n $permissionResolver->setCurrentUserReference($user);\n\n // This call fails with an UnauthorizedException, because the current\n // user is not the content owner\n $contentService->deleteContent(\n $contentService->loadContentInfo($content->id)\n );\n /* END: Use Case */\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function loadProcessingConfig($configFilePath)\n {\n if (! is_file($configFilePath)) {\n throw new Exception(\"'$configFilePath' is missing. If no processing is needed, use an empty array.\");\n }\n\n $configFileContents = @file_get_contents($configFilePath);\n if ($configFileContents === false) {\n $error = error_get_last();\n throw new Exception(\"Error opening file '$configFilePath': \" . $error['message']);\n }\n\n $config = @json_decode($configFileContents);\n if ($config === null) {\n throw new Exception(\"Error decoding file '$configFilePath'.\");\n }\n\n if (! is_array($config)) {\n throw new Exception(\"'$configFilePath' must be an array of processing steps.\");\n }\n\n return $config;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function updateHtaccess(): bool {\n\t\t$config = Server::get(SystemConfig::class);\n\n\t\ttry {\n\t\t\t$webRoot = self::findWebRoot($config);\n\t\t} catch (InvalidArgumentException $e) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$setupHelper = Server::get(\\OC\\Setup::class);\n\n\t\tif (!is_writable($setupHelper->pathToHtaccess())) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());\n\t\t$content = \"#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\\n\";\n\t\t$htaccessContent = explode($content, $htaccessContent, 2)[0];\n\n\t\t//custom 403 error page\n\t\t$content .= \"\\nErrorDocument 403 \" . $webRoot . '/index.php/error/403';\n\n\t\t//custom 404 error page\n\t\t$content .= \"\\nErrorDocument 404 \" . $webRoot . '/index.php/error/404';\n\n\t\t// Add rewrite rules if the RewriteBase is configured\n\t\t$rewriteBase = $config->getValue('htaccess.RewriteBase', '');\n\t\tif ($rewriteBase !== '') {\n\t\t\t$content .= \"\\n\";\n\t\t\t$content .= \"\\n Options -MultiViews\";\n\t\t\t$content .= \"\\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]\";\n\t\t\t$content .= \"\\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !\\\\.(css|js|mjs|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\\\.php\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\\\.ico|manifest\\\\.json)$\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\\\.php\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\\\.php\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/robots\\\\.txt\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/(ocs-provider|updater)/\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_URI} !^/\\\\.well-known/(acme-challenge|pki-validation)/.*\";\n\t\t\t$content .= \"\\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$\";\n\t\t\t$content .= \"\\n RewriteRule . index.php [PT,E=PATH_INFO:$1]\";\n\t\t\t$content .= \"\\n RewriteBase \" . $rewriteBase;\n\t\t\t$content .= \"\\n \";\n\t\t\t$content .= \"\\n SetEnv front_controller_active true\";\n\t\t\t$content .= \"\\n \";\n\t\t\t$content .= \"\\n DirectorySlash off\";\n\t\t\t$content .= \"\\n \";\n\t\t\t$content .= \"\\n \";\n\t\t\t$content .= \"\\n\";\n\t\t}\n\n\t\t// Never write file back if disk space should be too low\n\t\tif (function_exists('disk_free_space')) {\n\t\t\t$df = disk_free_space(\\OC::$SERVERROOT);\n\t\t\t$size = strlen($content) + 10240;\n\t\t\tif ($df !== false && $df < (float)$size) {\n\t\t\t\tthrow new \\Exception(\\OC::$SERVERROOT . \" does not have enough space for writing the htaccess file! Not writing it back!\");\n\t\t\t}\n\t\t}\n\t\t//suppress errors in case we don't have permissions for it\n\t\treturn (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . \"\\n\");\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function handle(\n CriteriaConverter $converter,\n QueryBuilder $queryBuilder,\n Criterion $criterion,\n array $languageSettings\n ) {\n $column = $this->getColumnName($criterion);\n\n $value = (array)$criterion->value;\n switch ($criterion->operator) {\n case Criterion\\Operator::IN:\n return $queryBuilder->expr()->in(\n $column,\n $queryBuilder->createNamedParameter($value, Connection::PARAM_INT_ARRAY)\n );\n\n case Criterion\\Operator::BETWEEN:\n return $this->dbPlatform->getBetweenExpression(\n $column,\n $queryBuilder->createNamedParameter($value[0], ParameterType::INTEGER),\n $queryBuilder->createNamedParameter($value[1], ParameterType::INTEGER)\n );\n\n case Criterion\\Operator::EQ:\n case Criterion\\Operator::GT:\n case Criterion\\Operator::GTE:\n case Criterion\\Operator::LT:\n case Criterion\\Operator::LTE:\n $operatorFunction = $this->comparatorMap[$criterion->operator];\n\n return $queryBuilder->expr()->$operatorFunction(\n $column,\n $queryBuilder->createNamedParameter(reset($value), ParameterType::INTEGER)\n );\n\n default:\n throw new RuntimeException(\n \"Unknown operator '{$criterion->operator}' for DateMetadata Criterion handler.\"\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function updateJob(ExportJob $job)\n {\n $sql = \"UPDATE export_job SET `output`=?, `errors`=?, `status`=? WHERE uuid = ?\";\n $params = [$job->getOutput(), $job->getErrors(), $job->getStatus(), $job->getUuid()];\n $ret = sqlQueryNoLog($sql, $params);\n if (!empty($ret)) {\n // replace our UUID param so we don't spit out binary\n $params[2] = $job->getUuidString();\n $this->logger->error(\"Failed to save ExportJob\", ['sql' => $sql, 'params' => $params, 'sqlError' => getSqlLastError()]);\n throw new \\RuntimeException(\"Failed to save ExportJob with updated output,errors, & status\");\n }\n return $job;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function shredFile($line)\n {\n throw new Exception('Cloud resources do not support shredding by file. Please use the -d option and specify a directory');\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $functionId, Response $response, Database $dbForProject) {\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $response->dynamic(new Document([\n 'variables' => $function->getAttribute('vars', []),\n 'total' => \\count($function->getAttribute('vars', [])),\n ]), Response::MODEL_VARIABLE_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function updateFileTags($path, $tags) {\n\t\tif ($this->tagger === null) {\n\t\t\tthrow new \\RuntimeException('No tagger set');\n\t\t}\n\t\tif ($this->homeFolder === null) {\n\t\t\tthrow new \\RuntimeException('No homeFolder set');\n\t\t}\n\n\t\t$fileId = $this->homeFolder->get($path)->getId();\n\n\t\t$currentTags = $this->tagger->getTagsForObjects([$fileId]);\n\n\t\tif (!empty($currentTags)) {\n\t\t\t$currentTags = current($currentTags);\n\t\t}\n\n\t\t$newTags = array_diff($tags, $currentTags);\n\t\tforeach ($newTags as $tag) {\n\t\t\tif ($tag === ITags::TAG_FAVORITE) {\n\t\t\t\t$this->addActivity(true, $fileId, $path);\n\t\t\t}\n\t\t\t$this->tagger->tagAs($fileId, $tag);\n\t\t}\n\t\t$deletedTags = array_diff($currentTags, $tags);\n\t\tforeach ($deletedTags as $tag) {\n\t\t\tif ($tag === ITags::TAG_FAVORITE) {\n\t\t\t\t$this->addActivity(false, $fileId, $path);\n\t\t\t}\n\t\t\t$this->tagger->unTag($fileId, $tag);\n\t\t}\n\n\t\t// TODO: re-read from tagger to make sure the\n\t\t// list is up to date, in case of concurrent changes ?\n\t\treturn $tags;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function extractSchemaFromFile(string $schema_path): array\n {\n if (\n !is_file($schema_path)\n || !is_readable($schema_path)\n || ($schema_sql = file_get_contents($schema_path)) === false\n ) {\n throw new \\RuntimeException(sprintf(__('Unable to read installation file \"%s\".'), $schema_path));\n }\n\n $matches = [];\n preg_match_all('/(?CREATE TABLE[^`]*`(?\\w+)`.+?);$/ms', $schema_sql, $matches);\n $tables_names = $matches['table_name'];\n $create_table_sql_queries = $matches['sql_query'];\n\n $schema = [];\n foreach ($create_table_sql_queries as $index => $create_table_sql_query) {\n $schema[$tables_names[$index]] = $create_table_sql_query;\n }\n return $schema;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function isDataSet($pCoord) {\n\t\t//\tCheck if the requested entry is the current object, or exists in the cache\n\t\tif (parent::isDataSet($pCoord)) {\n\t\t\tif ($this->_currentObjectID == $pCoord) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t//\tCheck if the requested entry still exists in cache\n\t\t\t$success = wincache_ucache_exists($this->_cachePrefix.$pCoord.'.cache');\n\t\t\tif ($success === false) {\n\t\t\t\t//\tEntry no longer exists in Wincache, so clear it from the cache array\n\t\t\t\tparent::deleteCacheData($pCoord);\n\t\t\t\tthrow new Exception('Cell entry '.$cellID.' no longer exists in WinCache');\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function ($mode, $project, $console, $request, $response, $dbForProject, $dbForConsole) {\n /** @var Appwrite\\Utopia\\Request $request */\n /** @var Appwrite\\Utopia\\Response $response */\n /** @var Utopia\\Database\\Document $project */\n /** @var Utopia\\Database\\Database $dbForProject */\n /** @var Utopia\\Database\\Database $dbForConsole */\n /** @var string $mode */\n\n Authorization::setDefaultStatus(true);\n\n Auth::setCookieName('a_session_' . $project->getId());\n $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n\n if (APP_MODE_ADMIN === $mode) {\n Auth::setCookieName('a_session_' . $console->getId());\n $authDuration = Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n }\n\n $session = Auth::decodeSession(\n $request->getCookie(\n Auth::$cookieName, // Get sessions\n $request->getCookie(Auth::$cookieName . '_legacy', '')\n )\n );// Get fallback session from old clients (no SameSite support)\n\n // Get fallback session from clients who block 3rd-party cookies\n if ($response) {\n $response->addHeader('X-Debug-Fallback', 'false');\n }\n\n if (empty($session['id']) && empty($session['secret'])) {\n if ($response) {\n $response->addHeader('X-Debug-Fallback', 'true');\n }\n $fallback = $request->getHeader('x-fallback-cookies', '');\n $fallback = \\json_decode($fallback, true);\n $session = Auth::decodeSession(((isset($fallback[Auth::$cookieName])) ? $fallback[Auth::$cookieName] : ''));\n }\n\n Auth::$unique = $session['id'] ?? '';\n Auth::$secret = $session['secret'] ?? '';\n\n if (APP_MODE_ADMIN !== $mode) {\n if ($project->isEmpty()) {\n $user = new Document([]);\n } else {\n if ($project->getId() === 'console') {\n $user = $dbForConsole->getDocument('users', Auth::$unique);\n } else {\n $user = $dbForProject->getDocument('users', Auth::$unique);\n }\n }\n } else {\n $user = $dbForConsole->getDocument('users', Auth::$unique);\n }\n\n if (\n $user->isEmpty() // Check a document has been found in the DB\n || !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration)\n ) { // Validate user has valid login token\n $user = new Document([]);\n }\n\n if (APP_MODE_ADMIN === $mode) {\n if ($user->find('teamId', $project->getAttribute('teamId'), 'memberships')) {\n Authorization::setDefaultStatus(false); // Cancel security segmentation for admin users.\n } else {\n $user = new Document([]);\n }\n }\n\n $authJWT = $request->getHeader('x-appwrite-jwt', '');\n\n if (!empty($authJWT) && !$project->isEmpty()) { // JWT authentication\n $jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.\n\n try {\n $payload = $jwt->decode($authJWT);\n } catch (JWTException $error) {\n throw new Exception(Exception::USER_JWT_INVALID, 'Failed to verify JWT. ' . $error->getMessage());\n }\n\n $jwtUserId = $payload['userId'] ?? '';\n $jwtSessionId = $payload['sessionId'] ?? '';\n\n if ($jwtUserId && $jwtSessionId) {\n $user = $dbForProject->getDocument('users', $jwtUserId);\n }\n\n if (empty($user->find('$id', $jwtSessionId, 'sessions'))) { // Match JWT to active token\n $user = new Document([]);\n }\n }\n\n return $user;\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function saveThisReport()\n {\n if (!isset($this->_report_id)) {\n throw new \\Exception(\n \"configureSelectedReport() must be called first\"\n );\n }\n\n $this->_pdo->execute(\n \"\n UPDATE Reports SET\n name = :report_name,\n title = :report_title,\n header = :report_header,\n footer = :report_footer,\n charts_per_page = :charts_per_page,\n format = :format,\n schedule = :schedule,\n delivery = :delivery\n WHERE report_id = :report_id\n \",\n array(\n 'report_name' => $this->_report_name,\n 'report_title' => $this->_report_title,\n 'report_header' => $this->_report_header,\n 'report_footer' => $this->_report_footer,\n 'charts_per_page' => $this->_charts_per_page,\n 'format' => $this->_report_format,\n 'schedule' => $this->_report_schedule,\n 'delivery' => $this->_report_delivery,\n 'report_id' => $this->_report_id,\n )\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function readData() {\n\t\t// Default config should always get loaded\n\t\t$configFiles = [$this->configFilePath];\n\n\t\t// Add all files in the config dir ending with the same file name\n\t\t$extra = glob($this->configDir.'*.'.$this->configFileName);\n\t\tif (is_array($extra)) {\n\t\t\tnatsort($extra);\n\t\t\t$configFiles = array_merge($configFiles, $extra);\n\t\t}\n\n\t\t// Include file and merge config\n\t\tforeach ($configFiles as $file) {\n\t\t\tunset($CONFIG);\n\n\t\t\t// Invalidate opcache (only if the timestamp changed)\n\t\t\tif (function_exists('opcache_invalidate')) {\n\t\t\t\topcache_invalidate($file, false);\n\t\t\t}\n\n\t\t\t$filePointer = @fopen($file, 'r');\n\t\t\tif ($filePointer === false) {\n\t\t\t\t// e.g. wrong permissions are set\n\t\t\t\tif ($file === $this->configFilePath) {\n\t\t\t\t\t// opening the main config file might not be possible\n\t\t\t\t\t// (likely on a new installation)\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\thttp_response_code(500);\n\t\t\t\tdie(sprintf('FATAL: Could not open the config file %s', $file));\n\t\t\t}\n\n\t\t\t// Try to acquire a file lock\n\t\t\tif (!flock($filePointer, LOCK_SH)) {\n\t\t\t\tthrow new \\Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tinclude $file;\n\t\t\t} finally {\n\t\t\t\t// Close the file pointer and release the lock\n\t\t\t\tflock($filePointer, LOCK_UN);\n\t\t\t\tfclose($filePointer);\n\t\t\t}\n\n\t\t\tif (!defined('PHPUNIT_RUN') && headers_sent()) {\n\t\t\t\t// syntax issues in the config file like leading spaces causing PHP to send output\n\t\t\t\t$errorMessage = sprintf('Config file has leading content, please remove everything before \"cache = array_merge($this->cache, $CONFIG);\n\t\t\t}\n\t\t}\n\n\t\t$this->envCache = getenv();\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $userId, array $labels, Response $response, Database $dbForProject, Event $events) {\n\n $user = $dbForProject->getDocument('users', $userId);\n\n if ($user->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $user->setAttribute('labels', (array) \\array_values(\\array_unique($labels)));\n\n $user = $dbForProject->updateDocument('users', $user->getId(), $user);\n\n $events\n ->setParam('userId', $user->getId());\n\n $response->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function importVersionsForFile(IUser $user, Node $source, Node $target, array $versions): void {\n\t\t$userFolder = $this->rootFolder->getUserFolder($user->getUID());\n\t\t$relativePath = $userFolder->getRelativePath($target->getPath());\n\n\t\tif ($relativePath === null) {\n\t\t\tthrow new \\Exception('Target does not have a relative path' . $target->getPath());\n\t\t}\n\n\t\t$userView = new View('/' . $user->getUID());\n\t\t// create all parent folders\n\t\tStorage::createMissingDirectories($relativePath, $userView);\n\t\tStorage::scheduleExpire($user->getUID(), $relativePath);\n\n\t\tforeach ($versions as $version) {\n\t\t\t// 1. Import the file in its new location.\n\t\t\t// Nothing to do for the current version.\n\t\t\tif ($version->getTimestamp() !== $source->getMTime()) {\n\t\t\t\t$backend = $version->getBackend();\n\t\t\t\t$versionFile = $backend->getVersionFile($user, $source, $version->getRevisionId());\n\t\t\t\t$newVersionPath = 'files_versions/' . $relativePath . '.v' . $version->getTimestamp();\n\n\t\t\t\t$versionContent = $versionFile->fopen('r');\n\t\t\t\tif ($versionContent === false) {\n\t\t\t\t\t$this->logger->warning('Fail to open version file.', ['source' => $source, 'version' => $version, 'versionFile' => $versionFile]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$userView->file_put_contents($newVersionPath, $versionContent);\n\t\t\t\t// ensure the file is scanned\n\t\t\t\t$userView->getFileInfo($newVersionPath);\n\t\t\t}\n\n\t\t\t// 2. Create the entity in the database\n\t\t\t$versionEntity = new VersionEntity();\n\t\t\t$versionEntity->setFileId($target->getId());\n\t\t\t$versionEntity->setTimestamp($version->getTimestamp());\n\t\t\t$versionEntity->setSize($version->getSize());\n\t\t\t$versionEntity->setMimetype($this->mimeTypeLoader->getId($version->getMimetype()));\n\t\t\tif ($version instanceof IMetadataVersion) {\n\t\t\t\t$versionEntity->setMetadata($version->getMetadata());\n\t\t\t}\n\t\t\t$this->versionsMapper->insert($versionEntity);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function start()\n {\n if ($this->started) {\n return true;\n }\n\n if (\\PHP_SESSION_ACTIVE === session_status()) {\n throw new \\RuntimeException('Failed to start the session: already started by PHP.');\n }\n\n if (filter_var(\\ini_get('session.use_cookies'), \\FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) {\n throw new \\RuntimeException(sprintf('Failed to start the session because headers have already been sent by \"%s\" at line %d.', $file, $line));\n }\n\n $sessionId = $_COOKIE[session_name()] ?? null;\n /*\n * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`.\n *\n * ---------- Part 1\n *\n * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6.\n * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character.\n * Allowed values are integers such as:\n * - 4 for range `a-f0-9`\n * - 5 for range `a-v0-9`\n * - 6 for range `a-zA-Z0-9,-`\n *\n * ---------- Part 2\n *\n * The part `{22,250}` is related to the PHP ini directive `session.sid_length`.\n * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length.\n * Allowed values are integers between 22 and 256, but we use 250 for the max.\n *\n * Where does the 250 come from?\n * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255.\n * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250.\n *\n * ---------- Conclusion\n *\n * The parts 1 and 2 prevent the warning below:\n * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, \"-\", and \",\" characters are allowed.`\n *\n * The part 2 prevents the warning below:\n * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).`\n */\n if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) {\n // the session ID in the header is invalid, create a new one\n session_id(session_create_id());\n }\n\n // ok to try and start the session\n if (!session_start()) {\n throw new \\RuntimeException('Failed to start the session.');\n }\n\n if (null !== $this->emulateSameSite) {\n $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());\n if (null !== $originalCookie) {\n header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);\n }\n }\n\n $this->loadSession();\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function () {\n throw new Exception(Exception::GENERAL_MOCK, 'Mock 500 error', 500);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function GetEventbyId($calendar_id, $event,$access_token) {\n\t\t$url_parameters = array();\n\n\t\t$url_parameters['fields'] = 'items(id,summary,timeZone)';\n\t\t$url_parameters['minAccessRole'] = 'owner';\n\n\t\t$url_calendars = 'https://www.googleapis.com/calendar/v3/calendars/'.$calendar_id.'/events/'. $event;\n\n\t\t$ch = curl_init();\n\t\tcurl_setopt($ch, CURLOPT_URL, $url_calendars);\n\t\tcurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n\t\tcurl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));\n\t\tcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n\t\t$data = json_decode(curl_exec($ch), true); //echo '
    ';print_r($data);echo '
    ';\n\t\t$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);\n\t\tif($http_code != 200)\n\t\t\tthrow new Exception('Error : Failed to get event');\n\n\t\treturn $data;\n\n\n\t}", "smellKey": "S112", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function getPatientSettings($queryVars)\n {\n $pid = $queryVars['pid'];\n if (empty($pid)) {\n throw new InvalidArgumentException(\"patient pid is missing from queryVars\");\n }\n\n $apptId = $queryVars['eid'];\n if (empty($apptId)) {\n throw new InvalidArgumentException(\"appointment eid is missing from queryVars\");\n }\n\n $appt = $this->appointmentService->getAppointment($apptId);\n if (!empty($appt)) {\n // TODO: get the appointment service to return a single appointment so odd it returns a list.\n $appt = $appt[0];\n }\n\n if (empty($appt)) {\n throw new InvalidArgumentException(\"appointment could not be found for pc_eid\" . $apptId);\n }\n\n $session = $this->sessionRepository->getSessionByAppointmentId($apptId);\n if (empty($session)) {\n throw new InvalidArgumentException(\"telehealth session could not be found for encounter \" . $apptId);\n }\n\n $userService = new UserService();\n $user = $userService->getUser($appt['pc_aid']);\n\n if (empty($user)) {\n throw new RuntimeException(\"Could not find provider for appointment \" . $apptId . \" this is a data integrity issue as telehealth appts should have providers\");\n }\n\n $isPatientDenied = true;\n // grab our list of participants and make sure this patient pid is allowed to join the session\n if (!$this->isPatientPidAuthorizedForSession($pid, $session)) {\n // overly paranoid but we double check the pid\n $this->logger->debug(\"Invalid access! Pid was not in appointment participant list. This could be \"\n . \"a security violation!\", [\"pid\" => $pid, 'pc_eid' => $apptId]);\n throw new InvalidArgumentException(\"Invalid access!\");\n }\n $patientResult = $this->getPatientForPid($pid);\n\n $patientTelehealthSettings = $this->getOrCreateTelehealthPatient($patientResult);\n $providerTelehealthSettings = $this->getOrCreateTelehealthProvider($user);\n\n $data = [\n 'calleeName' => $user['fname'] . ' ' . $user['lname']\n , 'calleeUuid' => $providerTelehealthSettings->getUsername()\n , 'apiKey' => $this->getApiKeyForPassword($patientTelehealthSettings->getAuthToken())\n , 'assetPath' => $this->assetPath\n , 'callerName' => $patientResult['fname'] . ' ' . $patientResult['lname']\n , 'callerUuid' => $patientTelehealthSettings->getUsername()\n , 'isPatient' => $this->isPatient\n , 'provider' => $user\n , 'patient' => $patientResult\n , 'appointment' => [\n 'eid' => $appt['pc_eid'],\n 'apptstatus' => $appt['pc_apptstatus']\n ]\n , 'participantList' => $this->getParticipantListForAppointment($user, $session)\n , 'serviceUrl' => $GLOBALS[Bootstrap::COMLINK_VIDEO_TELEHEALTH_API]\n ];\n return $data;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function prepareDataForPersistence(mixed $data, Localizedfield|AbstractData|Model\\DataObject\\Objectbrick\\Data\\AbstractData|Concrete $object = null, array $params = []): ?array\n {\n $return = [];\n\n if ($object instanceof Model\\DataObject\\Localizedfield) {\n $object = $object->getObject();\n } elseif ($object instanceof Model\\DataObject\\Objectbrick\\Data\\AbstractData || $object instanceof Model\\DataObject\\Fieldcollection\\Data\\AbstractData) {\n $object = $object->getObject();\n }\n\n if ($data && !is_array($data)) {\n throw new Exception('Slug data not valid');\n }\n\n if (is_array($data) && count($data) > 0) {\n foreach ($data as $slugItem) {\n if ($slugItem instanceof Model\\DataObject\\Data\\UrlSlug) {\n $return[] = [\n 'objectId' => $object->getId(),\n 'classId' => $object->getClassId(),\n 'fieldname' => $this->getName(),\n 'slug' => $slugItem->getSlug(),\n 'siteId' => $slugItem->getSiteId() ?? 0,\n ];\n } else {\n throw new Exception('expected instance of UrlSlug');\n }\n }\n\n return $return;\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected function buildDeployment(GitHub $github, Document $project, Document $function, Document $deployment, Document $template)\n {\n global $register;\n\n $dbForProject = $this->getProjectDB($project);\n $dbForConsole = $this->getConsoleDB();\n\n $function = $dbForProject->getDocument('functions', $function->getId());\n if ($function->isEmpty()) {\n throw new Exception('Function not found', 404);\n }\n\n $deployment = $dbForProject->getDocument('deployments', $deployment->getId());\n if ($deployment->isEmpty()) {\n throw new Exception('Deployment not found', 404);\n }\n\n if (empty($deployment->getAttribute('entrypoint', ''))) {\n throw new Exception('Entrypoint for your Appwrite Function is missing. Please specify it when making deployment or update the entrypoint under your function\\'s \"Settings\" > \"Configuration\" > \"Entrypoint\".', 500);\n }\n\n $version = $function->getAttribute('version', 'v2');\n $runtimes = Config::getParam($version === 'v2' ? 'runtimes-v2' : 'runtimes', []);\n $key = $function->getAttribute('runtime');\n $runtime = isset($runtimes[$key]) ? $runtimes[$key] : null;\n if (\\is_null($runtime)) {\n throw new Exception('Runtime \"' . $function->getAttribute('runtime', '') . '\" is not supported');\n }\n\n // Realtime preparation\n $allEvents = Event::generateEvents('functions.[functionId].deployments.[deploymentId].update', [\n 'functionId' => $function->getId(),\n 'deploymentId' => $deployment->getId()\n ]);\n\n $startTime = DateTime::now();\n $durationStart = \\microtime(true);\n\n $buildId = $deployment->getAttribute('buildId', '');\n\n $isNewBuild = empty($buildId);\n\n if ($isNewBuild) {\n $buildId = ID::unique();\n $build = $dbForProject->createDocument('builds', new Document([\n '$id' => $buildId,\n '$permissions' => [],\n 'startTime' => $startTime,\n 'deploymentInternalId' => $deployment->getInternalId(),\n 'deploymentId' => $deployment->getId(),\n 'status' => 'processing',\n 'path' => '',\n 'runtime' => $function->getAttribute('runtime'),\n 'source' => $deployment->getAttribute('path', ''),\n 'sourceType' => strtolower(App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL)),\n 'logs' => '',\n 'endTime' => null,\n 'duration' => 0,\n 'size' => 0\n ]));\n\n $deployment->setAttribute('buildId', $build->getId());\n $deployment->setAttribute('buildInternalId', $build->getInternalId());\n $deployment = $dbForProject->updateDocument('deployments', $deployment->getId(), $deployment);\n } else {\n $build = $dbForProject->getDocument('builds', $buildId);\n }\n\n $source = $deployment->getAttribute('path', '');\n $installationId = $deployment->getAttribute('installationId', '');\n $providerRepositoryId = $deployment->getAttribute('providerRepositoryId', '');\n $providerCommitHash = $deployment->getAttribute('providerCommitHash', '');\n $isVcsEnabled = $providerRepositoryId ? true : false;\n $owner = '';\n $repositoryName = '';\n\n if ($isVcsEnabled) {\n $installation = $dbForConsole->getDocument('installations', $installationId);\n $providerInstallationId = $installation->getAttribute('providerInstallationId');\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n }\n\n try {\n if ($isNewBuild && $isVcsEnabled) {\n $tmpDirectory = '/tmp/builds/' . $buildId . '/code';\n $rootDirectory = $function->getAttribute('providerRootDirectory', '');\n $rootDirectory = \\rtrim($rootDirectory, '/');\n $rootDirectory = \\ltrim($rootDirectory, '.');\n $rootDirectory = \\ltrim($rootDirectory, '/');\n\n $owner = $github->getOwnerName($providerInstallationId);\n $repositoryName = $github->getRepositoryName($providerRepositoryId);\n\n $cloneOwner = $deployment->getAttribute('providerRepositoryOwner', $owner);\n $cloneRepository = $deployment->getAttribute('providerRepositoryName', $repositoryName);\n\n $branchName = $deployment->getAttribute('providerBranch');\n $commitHash = $deployment->getAttribute('providerCommitHash', '');\n $gitCloneCommand = $github->generateCloneCommand($cloneOwner, $cloneRepository, $branchName, $tmpDirectory, $rootDirectory, $commitHash);\n $stdout = '';\n $stderr = '';\n Console::execute('mkdir -p /tmp/builds/' . \\escapeshellcmd($buildId), '', $stdout, $stderr);\n $exit = Console::execute($gitCloneCommand, '', $stdout, $stderr);\n\n if ($exit !== 0) {\n throw new \\Exception('Unable to clone code repository: ' . $stderr);\n }\n\n // Build from template\n $templateRepositoryName = $template->getAttribute('repositoryName', '');\n $templateOwnerName = $template->getAttribute('ownerName', '');\n $templateBranch = $template->getAttribute('branch', '');\n\n $templateRootDirectory = $template->getAttribute('rootDirectory', '');\n $templateRootDirectory = \\rtrim($templateRootDirectory, '/');\n $templateRootDirectory = \\ltrim($templateRootDirectory, '.');\n $templateRootDirectory = \\ltrim($templateRootDirectory, '/');\n\n if (!empty($templateRepositoryName) && !empty($templateOwnerName) && !empty($templateBranch)) {\n // Clone template repo\n $tmpTemplateDirectory = '/tmp/builds/' . \\escapeshellcmd($buildId) . '/template';\n $gitCloneCommandForTemplate = $github->generateCloneCommand($templateOwnerName, $templateRepositoryName, $templateBranch, $tmpTemplateDirectory, $templateRootDirectory);\n $exit = Console::execute($gitCloneCommandForTemplate, '', $stdout, $stderr);\n\n if ($exit !== 0) {\n throw new \\Exception('Unable to clone code repository: ' . $stderr);\n }\n\n // Ensure directories\n Console::execute('mkdir -p ' . $tmpTemplateDirectory . '/' . $templateRootDirectory, '', $stdout, $stderr);\n Console::execute('mkdir -p ' . $tmpDirectory . '/' . $rootDirectory, '', $stdout, $stderr);\n\n // Merge template into user repo\n Console::execute('cp -rfn ' . $tmpTemplateDirectory . '/' . $templateRootDirectory . '/* ' . $tmpDirectory . '/' . $rootDirectory, '', $stdout, $stderr);\n\n // Commit and push\n $exit = Console::execute('git config --global user.email \"team@appwrite.io\" && git config --global user.name \"Appwrite\" && cd ' . $tmpDirectory . ' && git add . && git commit -m \"Create \\'' . \\escapeshellcmd($function->getAttribute('name', '')) . '\\' function\" && git push origin ' . \\escapeshellcmd($branchName), '', $stdout, $stderr);\n\n if ($exit !== 0) {\n throw new \\Exception('Unable to push code repository: ' . $stderr);\n }\n\n $exit = Console::execute('cd ' . $tmpDirectory . ' && git rev-parse HEAD', '', $stdout, $stderr);\n\n if ($exit !== 0) {\n throw new \\Exception('Unable to get vcs commit SHA: ' . $stderr);\n }\n\n $providerCommitHash = \\trim($stdout);\n $authorUrl = \"https://github.com/$cloneOwner\";\n\n $deployment->setAttribute('providerCommitHash', $providerCommitHash ?? '');\n $deployment->setAttribute('providerCommitAuthorUrl', $authorUrl);\n $deployment->setAttribute('providerCommitAuthor', 'Appwrite');\n $deployment->setAttribute('providerCommitMessage', \"Create '\" . $function->getAttribute('name', '') . \"' function\");\n $deployment->setAttribute('providerCommitUrl', \"https://github.com/$cloneOwner/$cloneRepository/commit/$providerCommitHash\");\n $deployment = $dbForProject->updateDocument('deployments', $deployment->getId(), $deployment);\n\n /**\n * Send realtime Event\n */\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $build,\n project: $project\n );\n Realtime::send(\n projectId: 'console',\n payload: $build->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n }\n\n $tmpPath = '/tmp/builds/' . \\escapeshellcmd($buildId);\n $tmpPathFile = $tmpPath . '/code.tar.gz';\n\n Console::execute('tar --exclude code.tar.gz -czf ' . $tmpPathFile . ' -C /tmp/builds/' . \\escapeshellcmd($buildId) . '/code' . (empty($rootDirectory) ? '' : '/' . $rootDirectory) . ' .', '', $stdout, $stderr);\n\n $deviceFunctions = $this->getFunctionsDevice($project->getId());\n\n $localDevice = new Local();\n $buffer = $localDevice->read($tmpPathFile);\n $mimeType = $localDevice->getFileMimeType($tmpPathFile);\n\n $path = $deviceFunctions->getPath($deployment->getId() . '.' . \\pathinfo('code.tar.gz', PATHINFO_EXTENSION));\n $result = $deviceFunctions->write($path, $buffer, $mimeType);\n\n if (!$result) {\n throw new \\Exception(\"Unable to move file\");\n }\n\n Console::execute('rm -rf ' . $tmpPath, '', $stdout, $stderr);\n\n $source = $path;\n\n $build = $dbForProject->updateDocument('builds', $build->getId(), $build->setAttribute('source', $source));\n\n $this->runGitAction('processing', $github, $providerCommitHash, $owner, $repositoryName, $project, $function, $deployment->getId(), $dbForProject, $dbForConsole);\n }\n\n /** Request the executor to build the code... */\n $build->setAttribute('status', 'building');\n $build = $dbForProject->updateDocument('builds', $buildId, $build);\n\n if ($isVcsEnabled) {\n $this->runGitAction('building', $github, $providerCommitHash, $owner, $repositoryName, $project, $function, $deployment->getId(), $dbForProject, $dbForConsole);\n }\n\n /** Trigger Webhook */\n $deploymentModel = new Deployment();\n\n $deploymentUpdate = new Event(Event::WEBHOOK_QUEUE_NAME, Event::WEBHOOK_CLASS_NAME);\n $deploymentUpdate\n ->setProject($project)\n ->setEvent('functions.[functionId].deployments.[deploymentId].update')\n ->setParam('functionId', $function->getId())\n ->setParam('deploymentId', $deployment->getId())\n ->setPayload($deployment->getArrayCopy(array_keys($deploymentModel->getRules())))\n ->trigger();\n\n /** Trigger Functions */\n $pools = $register->get('pools');\n $connection = $pools->get('queue')->pop();\n\n $functions = new Func($connection->getResource());\n $functions\n ->from($deploymentUpdate)\n ->trigger();\n\n $connection->reclaim();\n\n /** Trigger Realtime */\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $build,\n project: $project\n );\n\n Realtime::send(\n projectId: 'console',\n payload: $build->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n\n $vars = [];\n\n // Shared vars\n foreach ($function->getAttribute('varsProject', []) as $var) {\n $vars[$var->getAttribute('key')] = $var->getAttribute('value', '');\n }\n\n // Function vars\n foreach ($function->getAttribute('vars', []) as $var) {\n $vars[$var->getAttribute('key')] = $var->getAttribute('value', '');\n }\n\n // Appwrite vars\n $vars = \\array_merge($vars, [\n 'APPWRITE_FUNCTION_ID' => $function->getId(),\n 'APPWRITE_FUNCTION_NAME' => $function->getAttribute('name'),\n 'APPWRITE_FUNCTION_DEPLOYMENT' => $deployment->getId(),\n 'APPWRITE_FUNCTION_PROJECT_ID' => $project->getId(),\n 'APPWRITE_FUNCTION_RUNTIME_NAME' => $runtime['name'] ?? '',\n 'APPWRITE_FUNCTION_RUNTIME_VERSION' => $runtime['version'] ?? '',\n ]);\n\n $command = $deployment->getAttribute('commands', '');\n $command = \\str_replace('\"', '\\\\\"', $command);\n\n $response = null;\n\n $err = null;\n\n // TODO: Remove run() wrapper when switching to new utopia queue. That should be done on Swoole adapter in the libary\n Co\\run(function () use ($project, $deployment, &$response, $source, $function, $runtime, $vars, $command, &$build, $dbForProject, $allEvents, &$err) {\n Co::join([\n Co\\go(function () use (&$response, $project, $deployment, $source, $function, $runtime, $vars, $command, &$err) {\n try {\n $version = $function->getAttribute('version', 'v2');\n $command = $version === 'v2' ? 'tar -zxf /tmp/code.tar.gz -C /usr/code && cd /usr/local/src/ && ./build.sh' : 'tar -zxf /tmp/code.tar.gz -C /mnt/code && helpers/build.sh \"' . $command . '\"';\n\n $response = $this->executor->createRuntime(\n deploymentId: $deployment->getId(),\n projectId: $project->getId(),\n source: $source,\n image: $runtime['image'],\n version: $version,\n remove: true,\n entrypoint: $deployment->getAttribute('entrypoint'),\n destination: APP_STORAGE_BUILDS . \"/app-{$project->getId()}\",\n variables: $vars,\n command: $command\n );\n } catch (Exception $error) {\n $err = $error;\n }\n }),\n Co\\go(function () use ($project, $deployment, &$response, &$build, $dbForProject, $allEvents, &$err) {\n try {\n $this->executor->getLogs(\n deploymentId: $deployment->getId(),\n projectId: $project->getId(),\n callback: function ($logs) use (&$response, &$build, $dbForProject, $allEvents, $project) {\n if ($response === null) {\n $build = $dbForProject->getDocument('builds', $build->getId());\n\n if ($build->isEmpty()) {\n throw new Exception('Build not found', 404);\n }\n\n $build = $build->setAttribute('logs', $build->getAttribute('logs', '') . $logs);\n $build = $dbForProject->updateDocument('builds', $build->getId(), $build);\n\n /**\n * Send realtime Event\n */\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $build,\n project: $project\n );\n Realtime::send(\n projectId: 'console',\n payload: $build->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n }\n }\n );\n } catch (Exception $error) {\n if (empty($err)) {\n $err = $error;\n }\n }\n }),\n ]);\n });\n\n if ($err) {\n throw $err;\n }\n\n $endTime = DateTime::now();\n $durationEnd = \\microtime(true);\n\n /** Update the build document */\n $build->setAttribute('startTime', DateTime::format((new \\DateTime())->setTimestamp($response['startTime'])));\n $build->setAttribute('endTime', $endTime);\n $build->setAttribute('duration', \\intval(\\ceil($durationEnd - $durationStart)));\n $build->setAttribute('status', 'ready');\n $build->setAttribute('path', $response['path']);\n $build->setAttribute('size', $response['size']);\n $build->setAttribute('logs', $response['output']);\n\n if ($isVcsEnabled) {\n $this->runGitAction('ready', $github, $providerCommitHash, $owner, $repositoryName, $project, $function, $deployment->getId(), $dbForProject, $dbForConsole);\n }\n\n Console::success(\"Build id: $buildId created\");\n\n /** Set auto deploy */\n if ($deployment->getAttribute('activate') === true) {\n $function->setAttribute('deploymentInternalId', $deployment->getInternalId());\n $function->setAttribute('deployment', $deployment->getId());\n $function->setAttribute('live', true);\n $function = $dbForProject->updateDocument('functions', $function->getId(), $function);\n }\n\n /** Update function schedule */\n $dbForConsole = $this->getConsoleDB();\n // Inform scheduler if function is still active\n $schedule = $dbForConsole->getDocument('schedules', $function->getAttribute('scheduleId'));\n $schedule\n ->setAttribute('resourceUpdatedAt', DateTime::now())\n ->setAttribute('schedule', $function->getAttribute('schedule'))\n ->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deployment')));\n Authorization::skip(fn () => $dbForConsole->updateDocument('schedules', $schedule->getId(), $schedule));\n } catch (\\Throwable $th) {\n $endTime = DateTime::now();\n $durationEnd = \\microtime(true);\n $build->setAttribute('endTime', $endTime);\n $build->setAttribute('duration', \\intval(\\ceil($durationEnd - $durationStart)));\n $build->setAttribute('status', 'failed');\n $build->setAttribute('logs', $th->getMessage());\n Console::error($th->getMessage());\n Console::error($th->getFile() . ':' . $th->getLine());\n Console::error($th->getTraceAsString());\n\n if ($isVcsEnabled) {\n $this->runGitAction('failed', $github, $providerCommitHash, $owner, $repositoryName, $project, $function, $deployment->getId(), $dbForProject, $dbForConsole);\n }\n } finally {\n $build = $dbForProject->updateDocument('builds', $buildId, $build);\n\n /**\n * Send realtime Event\n */\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $build,\n project: $project\n );\n Realtime::send(\n projectId: 'console',\n payload: $build->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n\n /** Update usage stats */\n if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {\n $statsd = $register->get('statsd');\n $usage = new Stats($statsd);\n $usage\n ->setParam('projectInternalId', $project->getInternalId())\n ->setParam('projectId', $project->getId())\n ->setParam('functionId', $function->getId())\n ->setParam('builds.{scope}.compute', 1)\n ->setParam('buildStatus', $build->getAttribute('status', ''))\n ->setParam('buildTime', $build->getAttribute('duration'))\n ->setParam('networkRequestSize', 0)\n ->setParam('networkResponseSize', 0)\n ->submit();\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function factory(IngestorOptions $options, EtlConfiguration $etlConfig, LoggerInterface $logger = null)\n {\n $options->verify();\n\n $className = $options->class;\n\n // If the class name does not include a namespace designation, use the namespace from the\n // ingestor configuration or the default namespace if not specified.\n\n if ( false === strstr($className, '\\\\') ) {\n if ( $options->namespace ) {\n $className = $options->namespace .\n ( strpos($options->namespace, '\\\\') != strlen($options->namespace) - 1 ? \"\\\\\" : \"\" ) .\n $className;\n } else {\n $className = self::$defaultIngestorNs . $className;\n }\n }\n\n if ( class_exists($className) ) {\n $ingestor = new $className($options, $etlConfig, $logger);\n } else {\n $msg = __CLASS__ . \": Error creating ingestor '{$options->name}', class '$className' not found\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n if ( ! $ingestor instanceof iAction ) {\n $msg = __CLASS__ . \": $className does not implenment interface iAction\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n return $ingestor;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setConfig(string $view, string $key, $value): void {\n\t\tif ($this->user === null) {\n\t\t\tthrow new \\Exception('No user logged in');\n\t\t}\n\n\t\tif (!$view) {\n\t\t\tthrow new \\Exception('Unknown view');\n\t\t}\n\n\t\tif (!in_array($key, $this->getAllowedConfigKeys())) {\n\t\t\tthrow new \\InvalidArgumentException('Unknown config key');\n\t\t}\n\t\n\t\tif (!in_array($value, $this->getAllowedConfigValues($key))\n\t\t\t&& !empty($this->getAllowedConfigValues($key))) {\n\t\t\tthrow new \\InvalidArgumentException('Invalid config value');\n\t\t}\n\n\t\t// Cast boolean values\n\t\tif (is_bool($this->getDefaultConfigValue($key))) {\n\t\t\t$value = $value === '1';\n\t\t}\n\n\t\t$config = $this->getConfigs();\n\t\t$config[$view][$key] = $value;\n\n\t\t$this->config->setUserValue($this->user->getUID(), Application::APP_ID, self::CONFIG_KEY, json_encode($config));\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function createZipFile($dataFile, array $request)\n {\n $zipFile = $this->getExportDataFilePath($request['id']);\n\n $this->logger->info([\n 'module' => self::LOG_MODULE,\n 'message' => 'Creating zip file',\n 'batch_export_request.id' => $request['id'],\n 'data_file' => $dataFile,\n 'zip_file' => $zipFile\n ]);\n\n try {\n $zip = new ZipArchive();\n $zipOpenCode = $zip->open($zipFile, ZipArchive::CREATE);\n\n if ($zipOpenCode !== true) {\n throw new Exception(sprintf(\n 'Failed to open zip file \"%s\", error code \"%s\"',\n $zipFile,\n $zipOpenCode\n ));\n }\n\n // Override the name of the temporary data file with the proper\n // name that will be used in the archive file.\n $localName = $this->getDataFileName($request);\n\n if (!$zip->addFile($dataFile, $localName)) {\n throw new Exception(sprintf(\n 'Failed to add file \"%s\" to zip file \"%s\"',\n $dataFile,\n $zipFile\n ));\n }\n\n $readmeText = $this->getReadmeText($request['realm']);\n if (!$zip->addFromString('README.txt', $readmeText)) {\n throw new Exception(sprintf(\n 'Failed to add \"README.txt\" to zip file \"%s\"',\n $dataFile,\n $zipFile\n ));\n }\n\n if (!$zip->close()) {\n throw new Exception(sprintf(\n 'Failed to close zip file \"%s\"',\n $zipFile\n ));\n }\n\n return $zipFile;\n } catch (Exception $e) {\n $this->logger->err([\n 'module' => self::LOG_MODULE,\n 'message' => $e->getMessage(),\n 'stacktrace' => $e->getTraceAsString()\n ]);\n throw new Exception('Failed to create zip file', 0, $e);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function determineAttributes() {\n\t\t$reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];\n\t\tif (!$this->configuration->usesLdapi()) {\n\t\t\t$reqs[] = 'ldapPort';\n\t\t}\n\t\tif (!$this->checkRequirements($reqs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$attributes = $this->getUserAttributes();\n\n\t\tif (!is_array($attributes)) {\n\t\t\tthrow new \\Exception('Failed to determine user attributes');\n\t\t}\n\n\t\tnatcasesort($attributes);\n\t\t$attributes = array_values($attributes);\n\n\t\t$this->result->addOptions('ldap_loginfilter_attributes', $attributes);\n\n\t\t$selected = $this->configuration->ldapLoginFilterAttributes;\n\t\tif (is_array($selected) && !empty($selected)) {\n\t\t\t$this->result->addChange('ldap_loginfilter_attributes', $selected);\n\t\t}\n\n\t\treturn $this->result;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function prepareDefinitionInput(array $input): array\n {\n $definition_fkey = AssetDefinition::getForeignKeyField();\n $definition_id = static::getDefinition()->getID();\n\n if (\n array_key_exists($definition_fkey, $input)\n && (int)$input[$definition_fkey] !== $definition_id\n ) {\n throw new \\RuntimeException('Definition does not match the current concrete class.');\n }\n\n if (\n !$this->isNewItem()\n && (int)$this->fields[$definition_fkey] !== $definition_id\n ) {\n throw new \\RuntimeException('Definition cannot be changed.');\n }\n\n $input[$definition_fkey] = $definition_id;\n\n return $input;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function createPatientFromSessionInvitationData($data)\n {\n $patientService = new PatientService();\n $listService = new ListService();\n // wierd that it goes off the option title instead of the option id here\n $sexOption = $listService->getListOption('sex', 'UNK');\n $yesOption = $listService->getListOption('yesno', 'YES');\n // the validator will scream if we are sending the wrong data\n $insertData = [\n 'email' => $data['email'] ?? null\n , 'fname' => $data['fname'] ?? null\n , 'lname' => $data['lname'] ?? null\n , 'DOB' => $data['DOB'] ?? null\n , 'sex' => $sexOption['title'] // we set it to unknown. Patient can fill it in later, we do this to simplify the invitation\n // since we are explicitly sending them an invitation with their email, the provider has gotten verbal confirmation\n // that the patient wants to receive a message via email.\n , 'hipaa_allowemail' => $yesOption['title']\n , 'allow_patient_portal' => $yesOption['title']\n ];\n // do our more strict validation then pass on to the Patient Service Insert\n $patientValidator = new TelehealthPatientValidator();\n $result = $patientValidator->validate($insertData, TelehealthPatientValidator::TELEHEALTH_INSERT_CONTEXT);\n if (!$result->hasErrors()) {\n $result = $patientService->insert($insertData);\n }\n if ($result->hasErrors()) {\n // need to throw the exception\n $message = \"\";\n foreach ($result->getValidationMessages() as $key => $value) {\n $message .= \"Validation failed for key $key with messages \" . implode(\";\", $value) . \".\";\n }\n throw new TelehealthValidationException($result->getValidationMessages(), $message);\n } elseif ($result->hasInternalErrors()) {\n throw new \\RuntimeException(implode(\". \", $result->getInternalErrors()));\n }\n $patientResult = $result->getData() ?? [];\n if (empty($patientResult)) {\n throw new \\RuntimeException(\"Patient was not created\");\n }\n\n $pid = $patientResult[0]['pid'];\n $patientData = $patientService->findByPid($pid);\n\n // now we need to create the portal credentials here\n $patientAccessService = new PatientAccessOnsiteService();\n $pwd = $patientAccessService->getRandomPortalPassword();\n $uname = $patientData['fname'] . $patientData['id'];\n $login_uname = $patientAccessService->getUniqueTrustedUsernameForPid($pid);\n $login_uname = $login_uname ?? $uname;\n $result = $patientAccessService->saveCredentials($pid, $pwd, $uname, $login_uname);\n\n // TODO: @adunsulag we need to handle if the email credentials don't send, or if we want to bundle all of this\n // into a single email\n $patientAccessService->sendCredentialsEmail($pid, $pwd, $uname, $login_uname, $data['email']);\n\n return $pid;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function _readFormula()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; row index\n\t\t$row = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; col index\n\t\t$column = self::_GetInt2d($recordData, 2);\n\t\t$columnString = PHPExcel_Cell::stringFromColumnIndex($column);\n\n\t\t// offset: 20: size: variable; formula structure\n\t\t$formulaStructure = substr($recordData, 20);\n\n\t\t// offset: 14: size: 2; option flags, recalculate always, recalculate on open etc.\n\t\t$options = self::_GetInt2d($recordData, 14);\n\n\t\t// bit: 0; mask: 0x0001; 1 = recalculate always\n\t\t// bit: 1; mask: 0x0002; 1 = calculate on open\n\t\t// bit: 2; mask: 0x0008; 1 = part of a shared formula\n\t\t$isPartOfSharedFormula = (bool) (0x0008 & $options);\n\n\t\t// WARNING:\n\t\t// We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true\n\t\t// the formula data may be ordinary formula data, therefore we need to check\n\t\t// explicitly for the tExp token (0x01)\n\t\t$isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure{2}) == 0x01;\n\n\t\tif ($isPartOfSharedFormula) {\n\t\t\t// part of shared formula which means there will be a formula with a tExp token and nothing else\n\t\t\t// get the base cell, grab tExp token\n\t\t\t$baseRow = self::_GetInt2d($formulaStructure, 3);\n\t\t\t$baseCol = self::_GetInt2d($formulaStructure, 5);\n\t\t\t$this->_baseCell = PHPExcel_Cell::stringFromColumnIndex($baseCol). ($baseRow + 1);\n\t\t}\n\n\t\t// Read cell?\n\t\tif ( !is_null($this->getReadFilter()) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {\n\n\t\t\tif ($isPartOfSharedFormula) {\n\t\t\t\t// formula is added to this cell after the sheet has been read\n\t\t\t\t$this->_sharedFormulaParts[$columnString . ($row + 1)] = $this->_baseCell;\n\t\t\t}\n\n\t\t\t// offset: 16: size: 4; not used\n\n\t\t\t// offset: 4; size: 2; XF index\n\t\t\t$xfIndex = self::_GetInt2d($recordData, 4);\n\n\t\t\t// offset: 6; size: 8; result of the formula\n\t\t\tif ( (ord($recordData{6}) == 0)\n\t\t\t\t&& (ord($recordData{12}) == 255)\n\t\t\t\t&& (ord($recordData{13}) == 255) ) {\n\n\t\t\t\t// String formula. Result follows in appended STRING record\n\t\t\t\t$dataType = PHPExcel_Cell_DataType::TYPE_STRING;\n\n\t\t\t\t// read possible SHAREDFMLA record\n\t\t\t\t$code = self::_GetInt2d($this->_data, $this->_pos);\n\t\t\t\tif ($code == self::XLS_Type_SHAREDFMLA) {\n\t\t\t\t\t$this->_readSharedFmla();\n\t\t\t\t}\n\n\t\t\t\t// read STRING record\n\t\t\t\t$value = $this->_readString();\n\n\t\t\t} elseif ((ord($recordData{6}) == 1)\n\t\t\t\t&& (ord($recordData{12}) == 255)\n\t\t\t\t&& (ord($recordData{13}) == 255)) {\n\n\t\t\t\t// Boolean formula. Result is in +2; 0=false, 1=true\n\t\t\t\t$dataType = PHPExcel_Cell_DataType::TYPE_BOOL;\n\t\t\t\t$value = (bool) ord($recordData{8});\n\n\t\t\t} elseif ((ord($recordData{6}) == 2)\n\t\t\t\t&& (ord($recordData{12}) == 255)\n\t\t\t\t&& (ord($recordData{13}) == 255)) {\n\n\t\t\t\t// Error formula. Error code is in +2\n\t\t\t\t$dataType = PHPExcel_Cell_DataType::TYPE_ERROR;\n\t\t\t\t$value = self::_mapErrorCode(ord($recordData{8}));\n\n\t\t\t} elseif ((ord($recordData{6}) == 3)\n\t\t\t\t&& (ord($recordData{12}) == 255)\n\t\t\t\t&& (ord($recordData{13}) == 255)) {\n\n\t\t\t\t// Formula result is a null string\n\t\t\t\t$dataType = PHPExcel_Cell_DataType::TYPE_NULL;\n\t\t\t\t$value = '';\n\n\t\t\t} else {\n\n\t\t\t\t// forumla result is a number, first 14 bytes like _NUMBER record\n\t\t\t\t$dataType = PHPExcel_Cell_DataType::TYPE_NUMERIC;\n\t\t\t\t$value = self::_extractNumber(substr($recordData, 6, 8));\n\n\t\t\t}\n\n\t\t\t$cell = $this->_phpSheet->getCell($columnString . ($row + 1));\n\t\t\tif (!$this->_readDataOnly) {\n\t\t\t\t// add cell style\n\t\t\t\t$cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);\n\t\t\t}\n\n\t\t\t// store the formula\n\t\t\tif (!$isPartOfSharedFormula) {\n\t\t\t\t// not part of shared formula\n\t\t\t\t// add cell value. If we can read formula, populate with formula, otherwise just used cached value\n\t\t\t\ttry {\n\t\t\t\t\tif ($this->_version != self::XLS_BIFF8) {\n\t\t\t\t\t\tthrow new Exception('Not BIFF8. Can only read BIFF8 formulas');\n\t\t\t\t\t}\n\t\t\t\t\t$formula = $this->_getFormulaFromStructure($formulaStructure); // get formula in human language\n\t\t\t\t\t$cell->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA);\n\n\t\t\t\t} catch (Exception $e) {\n\t\t\t\t\t$cell->setValueExplicit($value, $dataType);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ($this->_version == self::XLS_BIFF8) {\n\t\t\t\t\t// do nothing at this point, formula id added later in the code\n\t\t\t\t} else {\n\t\t\t\t\t$cell->setValueExplicit($value, $dataType);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// store the cached calculated value\n\t\t\t$cell->setCalculatedValue($value);\n\t\t}\n\t}\n\n\t/**\n\t * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader,\n\t * which usually contains relative references.\n\t * These will be used to construct the formula in each shared formula part after the sheet is read.\n\t */\n\tprivate function _readSharedFmla()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything\n\t\t$cellRange = substr($recordData, 0, 6);\n\t\t$cellRange = $this->_readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax\n\n\t\t// offset: 6, size: 1; not used\n\n\t\t// offset: 7, size: 1; number of existing FORMULA records for this shared formula\n\t\t$no = ord($recordData{7});\n\n\t\t// offset: 8, size: var; Binary token array of the shared formula\n\t\t$formula = substr($recordData, 8);\n\n\t\t// at this point we only store the shared formula for later use\n\t\t$this->_sharedFormulas[$this->_baseCell] = $formula;\n\n\t}\n\n\t/**\n\t * Read a STRING record from current stream position and advance the stream pointer to next record\n\t * This record is used for storing result from FORMULA record when it is a string, and\n\t * it occurs directly after the FORMULA record\n\t *\n\t * @return string The string contents as UTF-8\n\t */\n\tprivate function _readString()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif ($this->_version == self::XLS_BIFF8) {\n\t\t\t$string = self::_readUnicodeStringLong($recordData);\n\t\t\t$value = $string['value'];\n\t\t} else {\n\t\t\t$string = $this->_readByteStringLong($recordData);\n\t\t\t$value = $string['value'];\n\t\t}\n\n\t\treturn $value;\n\t}\n\n\t/**\n\t * Read BOOLERR record\n\t * This record represents a Boolean value or error value\n\t * cell.\n\t *\n\t * --\t\"OpenOffice.org's Documentation of the Microsoft\n\t * \t\tExcel File Format\"\n\t */\n\tprivate function _readBoolErr()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; row index\n\t\t$row = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; column index\n\t\t$column = self::_GetInt2d($recordData, 2);\n\t\t$columnString = PHPExcel_Cell::stringFromColumnIndex($column);\n\n\t\t// Read cell?\n\t\tif ( !is_null($this->getReadFilter()) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {\n\t\t\t// offset: 4; size: 2; index to XF record\n\t\t\t$xfIndex = self::_GetInt2d($recordData, 4);\n\n\t\t\t// offset: 6; size: 1; the boolean value or error value\n\t\t\t$boolErr = ord($recordData{6});\n\n\t\t\t// offset: 7; size: 1; 0=boolean; 1=error\n\t\t\t$isError = ord($recordData{7});\n\n\t\t\t$cell = $this->_phpSheet->getCell($columnString . ($row + 1));\n\t\t\tswitch ($isError) {\n\t\t\t\tcase 0: // boolean\n\t\t\t\t\t$value = (bool) $boolErr;\n\n\t\t\t\t\t// add cell value\n\t\t\t\t\t$cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_BOOL);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 1: // error type\n\t\t\t\t\t$value = self::_mapErrorCode($boolErr);\n\n\t\t\t\t\t// add cell value\n\t\t\t\t\t$cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_ERROR);\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!$this->_readDataOnly) {\n\t\t\t\t// add cell style\n\t\t\t\t$cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read MULBLANK record\n\t * This record represents a cell range of empty cells. All\n\t * cells are located in the same row\n\t *\n\t * --\t\"OpenOffice.org's Documentation of the Microsoft\n\t * \t\tExcel File Format\"\n\t */\n\tprivate function _readMulBlank()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; index to row\n\t\t$row = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; index to first column\n\t\t$fc = self::_GetInt2d($recordData, 2);\n\n\t\t// offset: 4; size: 2 x nc; list of indexes to XF records\n\t\t// add style information\n\t\tif (!$this->_readDataOnly) {\n\t\t\tfor ($i = 0; $i < $length / 2 - 3; ++$i) {\n\t\t\t\t$columnString = PHPExcel_Cell::stringFromColumnIndex($fc + $i);\n\n\t\t\t\t// Read cell?\n\t\t\t\tif ( !is_null($this->getReadFilter()) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {\n\t\t\t\t\t$xfIndex = self::_GetInt2d($recordData, 4 + 2 * $i);\n\t\t\t\t\t$this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// offset: 6; size 2; index to last column (not needed)\n\t}\n\n\t/**\n\t * Read LABEL record\n\t * This record represents a cell that contains a string. In\n\t * BIFF8 it is usually replaced by the LABELSST record.\n\t * Excel still uses this record, if it copies unformatted\n\t * text cells to the clipboard.\n\t *\n\t * --\t\"OpenOffice.org's Documentation of the Microsoft\n\t * \t\tExcel File Format\"\n\t */\n\tprivate function _readLabel()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; index to row\n\t\t$row = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; index to column\n\t\t$column = self::_GetInt2d($recordData, 2);\n\t\t$columnString = PHPExcel_Cell::stringFromColumnIndex($column);\n\n\t\t// Read cell?\n\t\tif ( !is_null($this->getReadFilter()) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {\n\t\t\t// offset: 4; size: 2; XF index\n\t\t\t$xfIndex = self::_GetInt2d($recordData, 4);\n\n\t\t\t// add cell value\n\t\t\t// todo: what if string is very long? continue record\n\t\t\tif ($this->_version == self::XLS_BIFF8) {\n\t\t\t\t$string = self::_readUnicodeStringLong(substr($recordData, 6));\n\t\t\t\t$value = $string['value'];\n\t\t\t} else {\n\t\t\t\t$string = $this->_readByteStringLong(substr($recordData, 6));\n\t\t\t\t$value = $string['value'];\n\t\t\t}\n\t\t\t$cell = $this->_phpSheet->getCell($columnString . ($row + 1));\n\t\t\t$cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);\n\n\t\t\tif (!$this->_readDataOnly) {\n\t\t\t\t// add cell style\n\t\t\t\t$cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read BLANK record\n\t */\n\tprivate function _readBlank()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; row index\n\t\t$row = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; col index\n\t\t$col = self::_GetInt2d($recordData, 2);\n\t\t$columnString = PHPExcel_Cell::stringFromColumnIndex($col);\n\n\t\t// Read cell?\n\t\tif ( !is_null($this->getReadFilter()) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) {\n\t\t\t// offset: 4; size: 2; XF index\n\t\t\t$xfIndex = self::_GetInt2d($recordData, 4);\n\n\t\t\t// add style information\n\t\t\tif (!$this->_readDataOnly) {\n\t\t\t\t$this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Read MSODRAWING record\n\t */\n\tprivate function _readMsoDrawing()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\n\t\t// get spliced record data\n\t\t$splicedRecordData = $this->_getSplicedRecordData();\n\t\t$recordData = $splicedRecordData['recordData'];\n\n\t\t$this->_drawingData .= $recordData;\n\t}\n\n\t/**\n\t * Read OBJ record\n\t */\n\tprivate function _readObj()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif ($this->_readDataOnly || $this->_version != self::XLS_BIFF8) {\n\t\t\treturn;\n\t\t}\n\n\t\t// recordData consists of an array of subrecords looking like this:\n\t\t//\tft: 2 bytes; ftCmo type (0x15)\n\t\t//\tcb: 2 bytes; size in bytes of ftCmo data\n\t\t//\tot: 2 bytes; Object Type\n\t\t//\tid: 2 bytes; Object id number\n\t\t//\tgrbit: 2 bytes; Option Flags\n\t\t//\tdata: var; subrecord data\n\n\t\t// for now, we are just interested in the second subrecord containing the object type\n\t\t$ftCmoType\t= self::_GetInt2d($recordData, 0);\n\t\t$cbCmoSize\t= self::_GetInt2d($recordData, 2);\n\t\t$otObjType\t= self::_GetInt2d($recordData, 4);\n\t\t$idObjID\t= self::_GetInt2d($recordData, 6);\n\t\t$grbitOpts\t= self::_GetInt2d($recordData, 6);\n\n\t\t$this->_objs[] = array(\n\t\t\t'ftCmoType'\t=> $ftCmoType,\n\t\t\t'cbCmoSize'\t=> $cbCmoSize,\n\t\t\t'otObjType'\t=> $otObjType,\n\t\t\t'idObjID'\t=> $idObjID,\n\t\t\t'grbitOpts'\t=> $grbitOpts\n\t\t);\n\t\t$this->textObjRef = $idObjID;\n\n//\t\techo '_readObj()
    ';\n//\t\tvar_dump(end($this->_objs));\n//\t\techo '
    ';\n\t}\n\n\t/**\n\t * Read WINDOW2 record\n\t */\n\tprivate function _readWindow2()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; option flags\n\t\t$options = self::_GetInt2d($recordData, 0);\n\n\t\t// bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines\n\t\t$showGridlines = (bool) ((0x0002 & $options) >> 1);\n\t\t$this->_phpSheet->setShowGridlines($showGridlines);\n\n\t\t// bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers\n\t\t$showRowColHeaders = (bool) ((0x0004 & $options) >> 2);\n\t\t$this->_phpSheet->setShowRowColHeaders($showRowColHeaders);\n\n\t\t// bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen\n\t\t$this->_frozen = (bool) ((0x0008 & $options) >> 3);\n\n\t\t// bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left\n\t\t$this->_phpSheet->setRightToLeft((bool)((0x0040 & $options) >> 6));\n\n\t\t// bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active\n\t\t$isActive = (bool) ((0x0400 & $options) >> 10);\n\t\tif ($isActive) {\n\t\t\t$this->_phpExcel->setActiveSheetIndex($this->_phpExcel->getIndex($this->_phpSheet));\n\t\t}\n\t}\n\n\t/**\n\t * Read SCL record\n\t */\n\tprivate function _readScl()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// offset: 0; size: 2; numerator of the view magnification\n\t\t$numerator = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; numerator of the view magnification\n\t\t$denumerator = self::_GetInt2d($recordData, 2);\n\n\t\t// set the zoom scale (in percent)\n\t\t$this->_phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator);\n\t}\n\n\t/**\n\t * Read PANE record\n\t */\n\tprivate function _readPane()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif (!$this->_readDataOnly) {\n\t\t\t// offset: 0; size: 2; position of vertical split\n\t\t\t$px = self::_GetInt2d($recordData, 0);\n\n\t\t\t// offset: 2; size: 2; position of horizontal split\n\t\t\t$py = self::_GetInt2d($recordData, 2);\n\n\t\t\tif ($this->_frozen) {\n\t\t\t\t// frozen panes\n\t\t\t\t$this->_phpSheet->freezePane(PHPExcel_Cell::stringFromColumnIndex($px) . ($py + 1));\n\t\t\t} else {\n\t\t\t\t// unfrozen panes; split windows; not supported by PHPExcel core\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read SELECTION record. There is one such record for each pane in the sheet.\n\t */\n\tprivate function _readSelection()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif (!$this->_readDataOnly) {\n\t\t\t// offset: 0; size: 1; pane identifier\n\t\t\t$paneId = ord($recordData{0});\n\n\t\t\t// offset: 1; size: 2; index to row of the active cell\n\t\t\t$r = self::_GetInt2d($recordData, 1);\n\n\t\t\t// offset: 3; size: 2; index to column of the active cell\n\t\t\t$c = self::_GetInt2d($recordData, 3);\n\n\t\t\t// offset: 5; size: 2; index into the following cell range list to the\n\t\t\t// entry that contains the active cell\n\t\t\t$index = self::_GetInt2d($recordData, 5);\n\n\t\t\t// offset: 7; size: var; cell range address list containing all selected cell ranges\n\t\t\t$data = substr($recordData, 7);\n\t\t\t$cellRangeAddressList = $this->_readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax\n\n\t\t\t$selectedCells = $cellRangeAddressList['cellRangeAddresses'][0];\n\n\t\t\t// first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!)\n\t\t\tif (preg_match('/^([A-Z]+1\\:[A-Z]+)16384$/', $selectedCells)) {\n\t\t\t\t$selectedCells = preg_replace('/^([A-Z]+1\\:[A-Z]+)16384$/', '${1}1048576', $selectedCells);\n\t\t\t}\n\n\t\t\t// first row '1' + last row '65536' indicates that full column is selected\n\t\t\tif (preg_match('/^([A-Z]+1\\:[A-Z]+)65536$/', $selectedCells)) {\n\t\t\t\t$selectedCells = preg_replace('/^([A-Z]+1\\:[A-Z]+)65536$/', '${1}1048576', $selectedCells);\n\t\t\t}\n\n\t\t\t// first column 'A' + last column 'IV' indicates that full row is selected\n\t\t\tif (preg_match('/^(A[0-9]+\\:)IV([0-9]+)$/', $selectedCells)) {\n\t\t\t\t$selectedCells = preg_replace('/^(A[0-9]+\\:)IV([0-9]+)$/', '${1}XFD${2}', $selectedCells);\n\t\t\t}\n\n\t\t\t$this->_phpSheet->setSelectedCells($selectedCells);\n\t\t}\n\t}\n\n\tprivate function _includeCellRangeFiltered($cellRangeAddress)\n\t{\n\t\t$includeCellRange = true;\n\t\tif (!is_null($this->getReadFilter())) {\n\t\t\t$includeCellRange = false;\n\t\t\t$rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($cellRangeAddress);\n\t\t\t$rangeBoundaries[1][0]++;\n\t\t\tfor ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; $row++) {\n\t\t\t\tfor ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; $column++) {\n\t\t\t\t\tif ($this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle())) {\n\t\t\t\t\t\t$includeCellRange = true;\n\t\t\t\t\t\tbreak 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $includeCellRange;\n\t}\n\n\t/**\n\t * MERGEDCELLS\n\t *\n\t * This record contains the addresses of merged cell ranges\n\t * in the current sheet.\n\t *\n\t * --\t\"OpenOffice.org's Documentation of the Microsoft\n\t * \t\tExcel File Format\"\n\t */\n\tprivate function _readMergedCells()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) {\n\t\t\t$cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($recordData);\n\t\t\tforeach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) {\n\t\t\t\tif ($this->_includeCellRangeFiltered($cellRangeAddress)) {\n\t\t\t\t\t$this->_phpSheet->mergeCells($cellRangeAddress);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read HYPERLINK record\n\t */\n\tprivate function _readHyperLink()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer forward to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif (!$this->_readDataOnly) {\n\t\t\t// offset: 0; size: 8; cell range address of all cells containing this hyperlink\n\t\t\ttry {\n\t\t\t\t$cellRange = $this->_readBIFF8CellRangeAddressFixed($recordData, 0, 8);\n\t\t\t} catch (Exception $e) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// offset: 8, size: 16; GUID of StdLink\n\n\t\t\t// offset: 24, size: 4; unknown value\n\n\t\t\t// offset: 28, size: 4; option flags\n\n\t\t\t\t// bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL\n\t\t\t\t$isFileLinkOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 0;\n\n\t\t\t\t// bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL\n\t\t\t\t$isAbsPathOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 1;\n\n\t\t\t\t// bit: 2 (and 4); mask: 0x00000014; 0 = no description\n\t\t\t\t$hasDesc = (0x00000014 & self::_GetInt2d($recordData, 28)) >> 2;\n\n\t\t\t\t// bit: 3; mask: 0x00000008; 0 = no text, 1 = has text\n\t\t\t\t$hasText = (0x00000008 & self::_GetInt2d($recordData, 28)) >> 3;\n\n\t\t\t\t// bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame\n\t\t\t\t$hasFrame = (0x00000080 & self::_GetInt2d($recordData, 28)) >> 7;\n\n\t\t\t\t// bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name)\n\t\t\t\t$isUNC = (0x00000100 & self::_GetInt2d($recordData, 28)) >> 8;\n\n\t\t\t// offset within record data\n\t\t\t$offset = 32;\n\n\t\t\tif ($hasDesc) {\n\t\t\t\t// offset: 32; size: var; character count of description text\n\t\t\t\t$dl = self::_GetInt4d($recordData, 32);\n\t\t\t\t// offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated\n\t\t\t\t$desc = self::_encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false);\n\t\t\t\t$offset += 4 + 2 * $dl;\n\t\t\t}\n\t\t\tif ($hasFrame) {\n\t\t\t\t$fl = self::_GetInt4d($recordData, $offset);\n\t\t\t\t$offset += 4 + 2 * $fl;\n\t\t\t}\n\n\t\t\t// detect type of hyperlink (there are 4 types)\n\t\t\t$hyperlinkType = null;\n\n\t\t\tif ($isUNC) {\n\t\t\t\t$hyperlinkType = 'UNC';\n\t\t\t} else if (!$isFileLinkOrUrl) {\n\t\t\t\t$hyperlinkType = 'workbook';\n\t\t\t} else if (ord($recordData{$offset}) == 0x03) {\n\t\t\t\t$hyperlinkType = 'local';\n\t\t\t} else if (ord($recordData{$offset}) == 0xE0) {\n\t\t\t\t$hyperlinkType = 'URL';\n\t\t\t}\n\n\t\t\tswitch ($hyperlinkType) {\n\t\t\tcase 'URL':\n\t\t\t\t// section 5.58.2: Hyperlink containing a URL\n\t\t\t\t// e.g. http://example.org/index.php\n\n\t\t\t\t// offset: var; size: 16; GUID of URL Moniker\n\t\t\t\t$offset += 16;\n\t\t\t\t// offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word\n\t\t\t\t$us = self::_GetInt4d($recordData, $offset);\n\t\t\t\t$offset += 4;\n\t\t\t\t// offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated\n\t\t\t\t$url = self::_encodeUTF16(substr($recordData, $offset, $us - 2), false);\n\t\t\t\t$url .= $hasText ? '#' : '';\n\t\t\t\t$offset += $us;\n\t\t\t\tbreak;\n\n\t\t\tcase 'local':\n\t\t\t\t// section 5.58.3: Hyperlink to local file\n\t\t\t\t// examples:\n\t\t\t\t// mydoc.txt\n\t\t\t\t// ../../somedoc.xls#Sheet!A1\n\n\t\t\t\t// offset: var; size: 16; GUI of File Moniker\n\t\t\t\t$offset += 16;\n\n\t\t\t\t// offset: var; size: 2; directory up-level count.\n\t\t\t\t$upLevelCount = self::_GetInt2d($recordData, $offset);\n\t\t\t\t$offset += 2;\n\n\t\t\t\t// offset: var; size: 4; character count of the shortened file path and name, including trailing zero word\n\t\t\t\t$sl = self::_GetInt4d($recordData, $offset);\n\t\t\t\t$offset += 4;\n\n\t\t\t\t// offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string)\n\t\t\t\t$shortenedFilePath = substr($recordData, $offset, $sl);\n\t\t\t\t$shortenedFilePath = self::_encodeUTF16($shortenedFilePath, true);\n\t\t\t\t$shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero\n\n\t\t\t\t$offset += $sl;\n\n\t\t\t\t// offset: var; size: 24; unknown sequence\n\t\t\t\t$offset += 24;\n\n\t\t\t\t// extended file path\n\t\t\t\t// offset: var; size: 4; size of the following file link field including string lenth mark\n\t\t\t\t$sz = self::_GetInt4d($recordData, $offset);\n\t\t\t\t$offset += 4;\n\n\t\t\t\t// only present if $sz > 0\n\t\t\t\tif ($sz > 0) {\n\t\t\t\t\t// offset: var; size: 4; size of the character array of the extended file path and name\n\t\t\t\t\t$xl = self::_GetInt4d($recordData, $offset);\n\t\t\t\t\t$offset += 4;\n\n\t\t\t\t\t// offset: var; size 2; unknown\n\t\t\t\t\t$offset += 2;\n\n\t\t\t\t\t// offset: var; size $xl; character array of the extended file path and name.\n\t\t\t\t\t$extendedFilePath = substr($recordData, $offset, $xl);\n\t\t\t\t\t$extendedFilePath = self::_encodeUTF16($extendedFilePath, false);\n\t\t\t\t\t$offset += $xl;\n\t\t\t\t}\n\n\t\t\t\t// construct the path\n\t\t\t\t$url = str_repeat('..\\\\', $upLevelCount);\n\t\t\t\t$url .= ($sz > 0) ?\n\t\t\t\t\t$extendedFilePath : $shortenedFilePath; // use extended path if available\n\t\t\t\t$url .= $hasText ? '#' : '';\n\n\t\t\t\tbreak;\n\n\n\t\t\tcase 'UNC':\n\t\t\t\t// section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path\n\t\t\t\t// todo: implement\n\t\t\t\treturn;\n\n\t\t\tcase 'workbook':\n\t\t\t\t// section 5.58.5: Hyperlink to the Current Workbook\n\t\t\t\t// e.g. Sheet2!B1:C2, stored in text mark field\n\t\t\t\t$url = 'sheet://';\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tif ($hasText) {\n\t\t\t\t// offset: var; size: 4; character count of text mark including trailing zero word\n\t\t\t\t$tl = self::_GetInt4d($recordData, $offset);\n\t\t\t\t$offset += 4;\n\t\t\t\t// offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated\n\t\t\t\t$text = self::_encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false);\n\t\t\t\t$url .= $text;\n\t\t\t}\n\n\t\t\t// apply the hyperlink to all the relevant cells\n\t\t\tforeach (PHPExcel_Cell::extractAllCellReferencesInRange($cellRange) as $coordinate) {\n\t\t\t\t$this->_phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read DATAVALIDATIONS record\n\t */\n\tprivate function _readDataValidations()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer forward to next record\n\t\t$this->_pos += 4 + $length;\n\t}\n\n\t/**\n\t * Read DATAVALIDATION record\n\t */\n\tprivate function _readDataValidation()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer forward to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif ($this->_readDataOnly) {\n\t\t\treturn;\n\t\t}\n\n\t\t// offset: 0; size: 4; Options\n\t\t$options = self::_GetInt4d($recordData, 0);\n\n\t\t// bit: 0-3; mask: 0x0000000F; type\n\t\t$type = (0x0000000F & $options) >> 0;\n\t\tswitch ($type) {\n\t\t\tcase 0x00:\t$type = PHPExcel_Cell_DataValidation::TYPE_NONE;\t\tbreak;\n\t\t\tcase 0x01:\t$type = PHPExcel_Cell_DataValidation::TYPE_WHOLE;\t\tbreak;\n\t\t\tcase 0x02:\t$type = PHPExcel_Cell_DataValidation::TYPE_DECIMAL;\t\tbreak;\n\t\t\tcase 0x03:\t$type = PHPExcel_Cell_DataValidation::TYPE_LIST;\t\tbreak;\n\t\t\tcase 0x04:\t$type = PHPExcel_Cell_DataValidation::TYPE_DATE;\t\tbreak;\n\t\t\tcase 0x05:\t$type = PHPExcel_Cell_DataValidation::TYPE_TIME;\t\tbreak;\n\t\t\tcase 0x06:\t$type = PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH;\tbreak;\n\t\t\tcase 0x07:\t$type = PHPExcel_Cell_DataValidation::TYPE_CUSTOM;\t\tbreak;\n\t\t}\n\n\t\t// bit: 4-6; mask: 0x00000070; error type\n\t\t$errorStyle = (0x00000070 & $options) >> 4;\n\t\tswitch ($errorStyle) {\n\t\t\tcase 0x00:\t$errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP;\t\t\tbreak;\n\t\t\tcase 0x01:\t$errorStyle = PHPExcel_Cell_DataValidation::STYLE_WARNING;\t\tbreak;\n\t\t\tcase 0x02:\t$errorStyle = PHPExcel_Cell_DataValidation::STYLE_INFORMATION;\tbreak;\n\t\t}\n\n\t\t// bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list)\n\t\t// I have only seen cases where this is 1\n\t\t$explicitFormula = (0x00000080 & $options) >> 7;\n\n\t\t// bit: 8; mask: 0x00000100; 1= empty cells allowed\n\t\t$allowBlank = (0x00000100 & $options) >> 8;\n\n\t\t// bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity\n\t\t$suppressDropDown = (0x00000200 & $options) >> 9;\n\n\t\t// bit: 18; mask: 0x00040000; 1= show prompt box if cell selected\n\t\t$showInputMessage = (0x00040000 & $options) >> 18;\n\n\t\t// bit: 19; mask: 0x00080000; 1= show error box if invalid values entered\n\t\t$showErrorMessage = (0x00080000 & $options) >> 19;\n\n\t\t// bit: 20-23; mask: 0x00F00000; condition operator\n\t\t$operator = (0x00F00000 & $options) >> 20;\n\t\tswitch ($operator) {\n\t\t\tcase 0x00: $operator = PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN\t\t\t;\tbreak;\n\t\t\tcase 0x01: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN\t\t;\tbreak;\n\t\t\tcase 0x02: $operator = PHPExcel_Cell_DataValidation::OPERATOR_EQUAL\t\t\t\t;\tbreak;\n\t\t\tcase 0x03: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL\t\t\t;\tbreak;\n\t\t\tcase 0x04: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN\t\t;\tbreak;\n\t\t\tcase 0x05: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN\t\t\t;\tbreak;\n\t\t\tcase 0x06: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL;\tbreak;\n\t\t\tcase 0x07: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL\t;\tbreak;\n\t\t}\n\n\t\t// offset: 4; size: var; title of the prompt box\n\t\t$offset = 4;\n\t\t$string = self::_readUnicodeStringLong(substr($recordData, $offset));\n\t\t$promptTitle = $string['value'] !== chr(0) ?\n\t\t\t$string['value'] : '';\n\t\t$offset += $string['size'];\n\n\t\t// offset: var; size: var; title of the error box\n\t\t$string = self::_readUnicodeStringLong(substr($recordData, $offset));\n\t\t$errorTitle = $string['value'] !== chr(0) ?\n\t\t\t$string['value'] : '';\n\t\t$offset += $string['size'];\n\n\t\t// offset: var; size: var; text of the prompt box\n\t\t$string = self::_readUnicodeStringLong(substr($recordData, $offset));\n\t\t$prompt = $string['value'] !== chr(0) ?\n\t\t\t$string['value'] : '';\n\t\t$offset += $string['size'];\n\n\t\t// offset: var; size: var; text of the error box\n\t\t$string = self::_readUnicodeStringLong(substr($recordData, $offset));\n\t\t$error = $string['value'] !== chr(0) ?\n\t\t\t$string['value'] : '';\n\t\t$offset += $string['size'];\n\n\t\t// offset: var; size: 2; size of the formula data for the first condition\n\t\t$sz1 = self::_GetInt2d($recordData, $offset);\n\t\t$offset += 2;\n\n\t\t// offset: var; size: 2; not used\n\t\t$offset += 2;\n\n\t\t// offset: var; size: $sz1; formula data for first condition (without size field)\n\t\t$formula1 = substr($recordData, $offset, $sz1);\n\t\t$formula1 = pack('v', $sz1) . $formula1; // prepend the length\n\t\ttry {\n\t\t\t$formula1 = $this->_getFormulaFromStructure($formula1);\n\n\t\t\t// in list type validity, null characters are used as item separators\n\t\t\tif ($type == PHPExcel_Cell_DataValidation::TYPE_LIST) {\n\t\t\t\t$formula1 = str_replace(chr(0), ',', $formula1);\n\t\t\t}\n\t\t} catch (Exception $e) {\n\t\t\treturn;\n\t\t}\n\t\t$offset += $sz1;\n\n\t\t// offset: var; size: 2; size of the formula data for the first condition\n\t\t$sz2 = self::_GetInt2d($recordData, $offset);\n\t\t$offset += 2;\n\n\t\t// offset: var; size: 2; not used\n\t\t$offset += 2;\n\n\t\t// offset: var; size: $sz2; formula data for second condition (without size field)\n\t\t$formula2 = substr($recordData, $offset, $sz2);\n\t\t$formula2 = pack('v', $sz2) . $formula2; // prepend the length\n\t\ttry {\n\t\t\t$formula2 = $this->_getFormulaFromStructure($formula2);\n\t\t} catch (Exception $e) {\n\t\t\treturn;\n\t\t}\n\t\t$offset += $sz2;\n\n\t\t// offset: var; size: var; cell range address list with\n\t\t$cellRangeAddressList = $this->_readBIFF8CellRangeAddressList(substr($recordData, $offset));\n\t\t$cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses'];\n\n\t\tforeach ($cellRangeAddresses as $cellRange) {\n\t\t\t$stRange = $this->_phpSheet->shrinkRangeToFit($cellRange);\n\t\t\t$stRange = PHPExcel_Cell::extractAllCellReferencesInRange($stRange);\n\t\t\tforeach ($stRange as $coordinate) {\n\t\t\t\t$objValidation = $this->_phpSheet->getCell($coordinate)->getDataValidation();\n\t\t\t\t$objValidation->setType($type);\n\t\t\t\t$objValidation->setErrorStyle($errorStyle);\n\t\t\t\t$objValidation->setAllowBlank((bool)$allowBlank);\n\t\t\t\t$objValidation->setShowInputMessage((bool)$showInputMessage);\n\t\t\t\t$objValidation->setShowErrorMessage((bool)$showErrorMessage);\n\t\t\t\t$objValidation->setShowDropDown(!$suppressDropDown);\n\t\t\t\t$objValidation->setOperator($operator);\n\t\t\t\t$objValidation->setErrorTitle($errorTitle);\n\t\t\t\t$objValidation->setError($error);\n\t\t\t\t$objValidation->setPromptTitle($promptTitle);\n\t\t\t\t$objValidation->setPrompt($prompt);\n\t\t\t\t$objValidation->setFormula1($formula1);\n\t\t\t\t$objValidation->setFormula2($formula2);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Read SHEETLAYOUT record. Stores sheet tab color information.\n\t */\n\tprivate function _readSheetLayout()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// local pointer in record data\n\t\t$offset = 0;\n\n\t\tif (!$this->_readDataOnly) {\n\t\t\t// offset: 0; size: 2; repeated record identifier 0x0862\n\n\t\t\t// offset: 2; size: 10; not used\n\n\t\t\t// offset: 12; size: 4; size of record data\n\t\t\t// Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?)\n\t\t\t$sz = self::_GetInt4d($recordData, 12);\n\n\t\t\tswitch ($sz) {\n\t\t\t\tcase 0x14:\n\t\t\t\t\t// offset: 16; size: 2; color index for sheet tab\n\t\t\t\t\t$colorIndex = self::_GetInt2d($recordData, 16);\n\t\t\t\t\t$color = self::_readColor($colorIndex,$this->_palette,$this->_version);\n\t\t\t\t\t$this->_phpSheet->getTabColor()->setRGB($color['rgb']);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0x28:\n\t\t\t\t\t// TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007\n\t\t\t\t\treturn;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read SHEETPROTECTION record (FEATHEADR)\n\t */\n\tprivate function _readSheetProtection()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\tif ($this->_readDataOnly) {\n\t\t\treturn;\n\t\t}\n\n\t\t// offset: 0; size: 2; repeated record header\n\n\t\t// offset: 2; size: 2; FRT cell reference flag (=0 currently)\n\n\t\t// offset: 4; size: 8; Currently not used and set to 0\n\n\t\t// offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag)\n\t\t$isf = self::_GetInt2d($recordData, 12);\n\t\tif ($isf != 2) {\n\t\t\treturn;\n\t\t}\n\n\t\t// offset: 14; size: 1; =1 since this is a feat header\n\n\t\t// offset: 15; size: 4; size of rgbHdrSData\n\n\t\t// rgbHdrSData, assume \"Enhanced Protection\"\n\t\t// offset: 19; size: 2; option flags\n\t\t$options = self::_GetInt2d($recordData, 19);\n\n\t\t// bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects\n\t\t$bool = (0x0001 & $options) >> 0;\n\t\t$this->_phpSheet->getProtection()->setObjects(!$bool);\n\n\t\t// bit: 1; mask 0x0002; edit scenarios\n\t\t$bool = (0x0002 & $options) >> 1;\n\t\t$this->_phpSheet->getProtection()->setScenarios(!$bool);\n\n\t\t// bit: 2; mask 0x0004; format cells\n\t\t$bool = (0x0004 & $options) >> 2;\n\t\t$this->_phpSheet->getProtection()->setFormatCells(!$bool);\n\n\t\t// bit: 3; mask 0x0008; format columns\n\t\t$bool = (0x0008 & $options) >> 3;\n\t\t$this->_phpSheet->getProtection()->setFormatColumns(!$bool);\n\n\t\t// bit: 4; mask 0x0010; format rows\n\t\t$bool = (0x0010 & $options) >> 4;\n\t\t$this->_phpSheet->getProtection()->setFormatRows(!$bool);\n\n\t\t// bit: 5; mask 0x0020; insert columns\n\t\t$bool = (0x0020 & $options) >> 5;\n\t\t$this->_phpSheet->getProtection()->setInsertColumns(!$bool);\n\n\t\t// bit: 6; mask 0x0040; insert rows\n\t\t$bool = (0x0040 & $options) >> 6;\n\t\t$this->_phpSheet->getProtection()->setInsertRows(!$bool);\n\n\t\t// bit: 7; mask 0x0080; insert hyperlinks\n\t\t$bool = (0x0080 & $options) >> 7;\n\t\t$this->_phpSheet->getProtection()->setInsertHyperlinks(!$bool);\n\n\t\t// bit: 8; mask 0x0100; delete columns\n\t\t$bool = (0x0100 & $options) >> 8;\n\t\t$this->_phpSheet->getProtection()->setDeleteColumns(!$bool);\n\n\t\t// bit: 9; mask 0x0200; delete rows\n\t\t$bool = (0x0200 & $options) >> 9;\n\t\t$this->_phpSheet->getProtection()->setDeleteRows(!$bool);\n\n\t\t// bit: 10; mask 0x0400; select locked cells\n\t\t$bool = (0x0400 & $options) >> 10;\n\t\t$this->_phpSheet->getProtection()->setSelectLockedCells(!$bool);\n\n\t\t// bit: 11; mask 0x0800; sort cell range\n\t\t$bool = (0x0800 & $options) >> 11;\n\t\t$this->_phpSheet->getProtection()->setSort(!$bool);\n\n\t\t// bit: 12; mask 0x1000; auto filter\n\t\t$bool = (0x1000 & $options) >> 12;\n\t\t$this->_phpSheet->getProtection()->setAutoFilter(!$bool);\n\n\t\t// bit: 13; mask 0x2000; pivot tables\n\t\t$bool = (0x2000 & $options) >> 13;\n\t\t$this->_phpSheet->getProtection()->setPivotTables(!$bool);\n\n\t\t// bit: 14; mask 0x4000; select unlocked cells\n\t\t$bool = (0x4000 & $options) >> 14;\n\t\t$this->_phpSheet->getProtection()->setSelectUnlockedCells(!$bool);\n\n\t\t// offset: 21; size: 2; not used\n\t}\n\n\t/**\n\t * Read RANGEPROTECTION record\n\t * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification,\n\t * where it is referred to as FEAT record\n\t */\n\tprivate function _readRangeProtection()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t\t// local pointer in record data\n\t\t$offset = 0;\n\n\t\tif (!$this->_readDataOnly) {\n\t\t\t$offset += 12;\n\n\t\t\t// offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag\n\t\t\t$isf = self::_GetInt2d($recordData, 12);\n\t\t\tif ($isf != 2) {\n\t\t\t\t// we only read FEAT records of type 2\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t$offset += 2;\n\n\t\t\t$offset += 5;\n\n\t\t\t// offset: 19; size: 2; count of ref ranges this feature is on\n\t\t\t$cref = self::_GetInt2d($recordData, 19);\n\t\t\t$offset += 2;\n\n\t\t\t$offset += 6;\n\n\t\t\t// offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record)\n\t\t\t$cellRanges = array();\n\t\t\tfor ($i = 0; $i < $cref; ++$i) {\n\t\t\t\ttry {\n\t\t\t\t\t$cellRange = $this->_readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8));\n\t\t\t\t} catch (Exception $e) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t$cellRanges[] = $cellRange;\n\t\t\t\t$offset += 8;\n\t\t\t}\n\n\t\t\t// offset: var; size: var; variable length of feature specific data\n\t\t\t$rgbFeat = substr($recordData, $offset);\n\t\t\t$offset += 4;\n\n\t\t\t// offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit)\n\t\t\t$wPassword = self::_GetInt4d($recordData, $offset);\n\t\t\t$offset += 4;\n\n\t\t\t// Apply range protection to sheet\n\t\t\tif ($cellRanges) {\n\t\t\t\t$this->_phpSheet->protectCells(implode(' ', $cellRanges), strtoupper(dechex($wPassword)), true);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read IMDATA record\n\t */\n\tprivate function _readImData()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\n\t\t// get spliced record data\n\t\t$splicedRecordData = $this->_getSplicedRecordData();\n\t\t$recordData = $splicedRecordData['recordData'];\n\n\t\t// UNDER CONSTRUCTION\n\n\t\t// offset: 0; size: 2; image format\n\t\t$cf = self::_GetInt2d($recordData, 0);\n\n\t\t// offset: 2; size: 2; environment from which the file was written\n\t\t$env = self::_GetInt2d($recordData, 2);\n\n\t\t// offset: 4; size: 4; length of the image data\n\t\t$lcb = self::_GetInt4d($recordData, 4);\n\n\t\t// offset: 8; size: var; image data\n\t\t$iData = substr($recordData, 8);\n\n\t\tswitch ($cf) {\n\t\tcase 0x09: // Windows bitmap format\n\t\t\t// BITMAPCOREINFO\n\t\t\t// 1. BITMAPCOREHEADER\n\t\t\t// offset: 0; size: 4; bcSize, Specifies the number of bytes required by the structure\n\t\t\t$bcSize = self::_GetInt4d($iData, 0);\n//\t\t\tvar_dump($bcSize);\n\n\t\t\t// offset: 4; size: 2; bcWidth, specifies the width of the bitmap, in pixels\n\t\t\t$bcWidth = self::_GetInt2d($iData, 4);\n//\t\t\tvar_dump($bcWidth);\n\n\t\t\t// offset: 6; size: 2; bcHeight, specifies the height of the bitmap, in pixels.\n\t\t\t$bcHeight = self::_GetInt2d($iData, 6);\n//\t\t\tvar_dump($bcHeight);\n\t\t\t$ih = imagecreatetruecolor($bcWidth, $bcHeight);\n\n\t\t\t// offset: 8; size: 2; bcPlanes, specifies the number of planes for the target device. This value must be 1\n\n\t\t\t// offset: 10; size: 2; bcBitCount specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24\n\t\t\t$bcBitCount = self::_GetInt2d($iData, 10);\n//\t\t\tvar_dump($bcBitCount);\n\n\t\t\t$rgbString = substr($iData, 12);\n\t\t\t$rgbTriples = array();\n\t\t\twhile (strlen($rgbString) > 0) {\n\t\t\t\t$rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString);\n\t\t\t\t$rgbString = substr($rgbString, 3);\n\t\t\t}\n\t\t\t$x = 0;\n\t\t\t$y = 0;\n\t\t\tforeach ($rgbTriples as $i => $rgbTriple) {\n\t\t\t\t$color = imagecolorallocate($ih, $rgbTriple['r'], $rgbTriple['g'], $rgbTriple['b']);\n\t\t\t\timagesetpixel($ih, $x, $bcHeight - 1 - $y, $color);\n\t\t\t\t$x = ($x + 1) % $bcWidth;\n\t\t\t\t$y = $y + floor(($x + 1) / $bcWidth);\n\t\t\t}\n\t\t\t//imagepng($ih, 'image.png');\n\n\t\t\t$drawing = new PHPExcel_Worksheet_Drawing();\n\t\t\t$drawing->setPath($filename);\n\t\t\t$drawing->setWorksheet($this->_phpSheet);\n\n\t\t\tbreak;\n\n\t\tcase 0x02: // Windows metafile or Macintosh PICT format\n\t\tcase 0x0e: // native format\n\t\tdefault;\n\t\t\tbreak;\n\n\t\t}\n\n\t\t// _getSplicedRecordData() takes care of moving current position in data stream\n\t}\n\n\t/**\n\t * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record\n\t * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented.\n\t * In this case, we must treat the CONTINUE record as a MSODRAWING record\n\t */\n\tprivate function _readContinue()\n\t{\n\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t$recordData = substr($this->_data, $this->_pos + 4, $length);\n\n\t\t// check if we are reading drawing data\n\t\t// this is in case a free CONTINUE record occurs in other circumstances we are unaware of\n\t\tif ($this->_drawingData == '') {\n\t\t\t// move stream pointer to next record\n\t\t\t$this->_pos += 4 + $length;\n\n\t\t\treturn;\n\t\t}\n\n\t\t// check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data\n\t\tif ($length < 4) {\n\t\t\t// move stream pointer to next record\n\t\t\t$this->_pos += 4 + $length;\n\n\t\t\treturn;\n\t\t}\n\n\t\t// dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record\n\t\t// look inside CONTINUE record to see if it looks like a part of an Escher stream\n\t\t// we know that Escher stream may be split at least at\n\t\t//\t\t0xF003 MsofbtSpgrContainer\n\t\t//\t\t0xF004 MsofbtSpContainer\n\t\t//\t\t0xF00D MsofbtClientTextbox\n\t\t$validSplitPoints = array(0xF003, 0xF004, 0xF00D); // add identifiers if we find more\n\n\t\t$splitPoint = self::_GetInt2d($recordData, 2);\n\t\tif (in_array($splitPoint, $validSplitPoints)) {\n\t\t\t// get spliced record data (and move pointer to next record)\n\t\t\t$splicedRecordData = $this->_getSplicedRecordData();\n\t\t\t$this->_drawingData .= $splicedRecordData['recordData'];\n\n\t\t\treturn;\n\t\t}\n\n\t\t// move stream pointer to next record\n\t\t$this->_pos += 4 + $length;\n\n\t}\n\n\n\t/**\n\t * Reads a record from current position in data stream and continues reading data as long as CONTINUE\n\t * records are found. Splices the record data pieces and returns the combined string as if record data\n\t * is in one piece.\n\t * Moves to next current position in data stream to start of next record different from a CONtINUE record\n\t *\n\t * @return array\n\t */\n\tprivate function _getSplicedRecordData()\n\t{\n\t\t$data = '';\n\t\t$spliceOffsets = array();\n\n\t\t$i = 0;\n\t\t$spliceOffsets[0] = 0;\n\n\t\tdo {\n\t\t\t++$i;\n\n\t\t\t// offset: 0; size: 2; identifier\n\t\t\t$identifier = self::_GetInt2d($this->_data, $this->_pos);\n\t\t\t// offset: 2; size: 2; length\n\t\t\t$length = self::_GetInt2d($this->_data, $this->_pos + 2);\n\t\t\t$data .= substr($this->_data, $this->_pos + 4, $length);\n\n\t\t\t$spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length;\n\n\t\t\t$this->_pos += 4 + $length;\n\t\t\t$nextIdentifier = self::_GetInt2d($this->_data, $this->_pos);\n\t\t}\n\t\twhile ($nextIdentifier == self::XLS_Type_CONTINUE);\n\n\t\t$splicedData = array(\n\t\t\t'recordData' => $data,\n\t\t\t'spliceOffsets' => $spliceOffsets,\n\t\t);\n\n\t\treturn $splicedData;\n\n\t}\n\n\t/**\n\t * Convert formula structure into human readable Excel formula like 'A3+A5*5'\n\t *\n\t * @param string $formulaStructure The complete binary data for the formula\n\t * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas\n\t * @return string Human readable formula\n\t */\n\tprivate function _getFormulaFromStructure($formulaStructure, $baseCell = 'A1')\n\t{\n\t\t// offset: 0; size: 2; size of the following formula data\n\t\t$sz = self::_GetInt2d($formulaStructure, 0);\n\n\t\t// offset: 2; size: sz\n\t\t$formulaData = substr($formulaStructure, 2, $sz);\n\n\t\t// for debug: dump the formula data\n\t\t//echo '';\n\t\t//echo 'size: ' . $sz . \"\\n\";\n\t\t//echo 'the entire formula data: ';\n\t\t//Debug::dump($formulaData);\n\t\t//echo \"\\n----\\n\";\n\n\t\t// offset: 2 + sz; size: variable (optional)\n\t\tif (strlen($formulaStructure) > 2 + $sz) {\n\t\t\t$additionalData = substr($formulaStructure, 2 + $sz);\n\n\t\t\t// for debug: dump the additional data\n\t\t\t//echo 'the entire additional data: ';\n\t\t\t//Debug::dump($additionalData);\n\t\t\t//echo \"\\n----\\n\";\n\n\t\t} else {\n\t\t\t$additionalData = '';\n\t\t}\n\n\t\treturn $this->_getFormulaFromData($formulaData, $additionalData, $baseCell);\n\t}\n\n\t/**\n\t * Take formula data and additional data for formula and return human readable formula\n\t *\n\t * @param string $formulaData The binary data for the formula itself\n\t * @param string $additionalData Additional binary data going with the formula\n\t * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas\n\t * @return string Human readable formula\n\t */\n\tprivate function _getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1')\n\t{\n\t\t// start parsing the formula data\n\t\t$tokens = array();\n\n\t\twhile (strlen($formulaData) > 0 and $token = $this->_getNextToken($formulaData, $baseCell)) {\n\t\t\t$tokens[] = $token;\n\t\t\t$formulaData = substr($formulaData, $token['size']);\n\n\t\t\t// for debug: dump the token\n\t\t\t//var_dump($token);\n\t\t}\n\n\t\t$formulaString = $this->_createFormulaFromTokens($tokens, $additionalData);\n\n\t\treturn $formulaString;\n\t}\n\n\t/**\n\t * Take array of tokens together with additional data for formula and return human readable formula\n\t *\n\t * @param array $tokens\n\t * @param array $additionalData Additional binary data going with the formula\n\t * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas\n\t * @return string Human readable formula\n\t */\n\tprivate function _createFormulaFromTokens($tokens, $additionalData)\n\t{\n\t\t// empty formula?\n\t\tif (count($tokens) == 0) {\n\t\t\treturn '';\n\t\t}\n\n\t\t$formulaStrings = array();\n\t\tforeach ($tokens as $token) {\n\t\t\t// initialize spaces\n\t\t\t$space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen\n\t\t\t$space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen\n\t\t\t$space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis\n\t\t\t$space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis\n\t\t\t$space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis\n\t\t\t$space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis\n\n\t\t\tswitch ($token['name']) {\n\t\t\tcase 'tAdd': // addition\n\t\t\tcase 'tConcat': // addition\n\t\t\tcase 'tDiv': // division\n\t\t\tcase 'tEQ': // equality\n\t\t\tcase 'tGE': // greater than or equal\n\t\t\tcase 'tGT': // greater than\n\t\t\tcase 'tIsect': // intersection\n\t\t\tcase 'tLE': // less than or equal\n\t\t\tcase 'tList': // less than or equal\n\t\t\tcase 'tLT': // less than\n\t\t\tcase 'tMul': // multiplication\n\t\t\tcase 'tNE': // multiplication\n\t\t\tcase 'tPower': // power\n\t\t\tcase 'tRange': // range\n\t\t\tcase 'tSub': // subtraction\n\t\t\t\t$op2 = array_pop($formulaStrings);\n\t\t\t\t$op1 = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$op1$space1$space0{$token['data']}$op2\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tUplus': // unary plus\n\t\t\tcase 'tUminus': // unary minus\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}$op\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tPercent': // percent sign\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$op$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrVolatile': // indicates volatile function\n\t\t\tcase 'tAttrIf':\n\t\t\tcase 'tAttrSkip':\n\t\t\tcase 'tAttrChoose':\n\t\t\t\t// token is only important for Excel formula evaluator\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrSpace': // space / carriage return\n\t\t\t\t// space will be used when next token arrives, do not alter formulaString stack\n\t\t\t\tswitch ($token['data']['spacetype']) {\n\t\t\t\tcase 'type0':\n\t\t\t\t\t$space0 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type1':\n\t\t\t\t\t$space1 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type2':\n\t\t\t\t\t$space2 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type3':\n\t\t\t\t\t$space3 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type4':\n\t\t\t\t\t$space4 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type5':\n\t\t\t\t\t$space5 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrSum': // SUM function with one parameter\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"{$space1}{$space0}SUM($op)\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tFunc': // function with fixed number of arguments\n\t\t\tcase 'tFuncV': // function with variable number of arguments\n\t\t\t\tif ($token['data']['function'] != '') {\n\t\t\t\t\t// normal function\n\t\t\t\t\t$ops = array(); // array of operators\n\t\t\t\t\tfor ($i = 0; $i < $token['data']['args']; ++$i) {\n\t\t\t\t\t\t$ops[] = array_pop($formulaStrings);\n\t\t\t\t\t}\n\t\t\t\t\t$ops = array_reverse($ops);\n\t\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']['function']}(\" . implode(',', $ops) . \")\";\n\t\t\t\t\tunset($space0, $space1);\n\t\t\t\t} else {\n\t\t\t\t\t// add-in function\n\t\t\t\t\t$ops = array(); // array of operators\n\t\t\t\t\tfor ($i = 0; $i < $token['data']['args'] - 1; ++$i) {\n\t\t\t\t\t\t$ops[] = array_pop($formulaStrings);\n\t\t\t\t\t}\n\t\t\t\t\t$ops = array_reverse($ops);\n\t\t\t\t\t$function = array_pop($formulaStrings);\n\t\t\t\t\t$formulaStrings[] = \"$space1$space0$function(\" . implode(',', $ops) . \")\";\n\t\t\t\t\tunset($space0, $space1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'tParen': // parenthesis\n\t\t\t\t$expression = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$space3$space2($expression$space5$space4)\";\n\t\t\t\tunset($space2, $space3, $space4, $space5);\n\t\t\t\tbreak;\n\t\t\tcase 'tArray': // array constant\n\t\t\t\t$constantArray = self::_readBIFF8ConstantArray($additionalData);\n\t\t\t\t$formulaStrings[] = $space1 . $space0 . $constantArray['value'];\n\t\t\t\t$additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tMemArea':\n\t\t\t\t// bite off chunk of additional data\n\t\t\t\t$cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($additionalData);\n\t\t\t\t$additionalData = substr($additionalData, $cellRangeAddressList['size']);\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tArea': // cell range address\n\t\t\tcase 'tBool': // boolean\n\t\t\tcase 'tErr': // error code\n\t\t\tcase 'tInt': // integer\n\t\t\tcase 'tMemErr':\n\t\t\tcase 'tMemFunc':\n\t\t\tcase 'tMissArg':\n\t\t\tcase 'tName':\n\t\t\tcase 'tNameX':\n\t\t\tcase 'tNum': // number\n\t\t\tcase 'tRef': // single cell reference\n\t\t\tcase 'tRef3d': // 3d cell reference\n\t\t\tcase 'tArea3d': // 3d cell range reference\n\t\t\tcase 'tRefN':\n\t\t\tcase 'tAreaN':\n\t\t\tcase 'tStr': // string\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$formulaString = $formulaStrings[0];\n\n\t\t// for debug: dump the human readable formula\n\t\t//echo '----' . \"\\n\";\n\t\t//echo 'Formula: ' . $formulaString;\n\n\t\treturn $formulaString;\n\t}\n\n\t/**\n\t * Fetch next token from binary formula data\n\t *\n\t * @param string Formula data\n\t * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas\n\t * @return array\n\t * @throws Exception\n\t */\n\tprivate function _getNextToken($formulaData, $baseCell = 'A1')\n\t{\n\t\t// offset: 0; size: 1; token id\n\t\t$id = ord($formulaData[0]); // token id\n\t\t$name = false; // initialize token name\n\n\t\tswitch ($id) {\n\t\tcase 0x03: $name = 'tAdd';\t\t$size = 1;\t$data = '+';\tbreak;\n\t\tcase 0x04: $name = 'tSub';\t\t$size = 1;\t$data = '-';\tbreak;\n\t\tcase 0x05: $name = 'tMul';\t\t$size = 1;\t$data = '*';\tbreak;\n\t\tcase 0x06: $name = 'tDiv';\t\t$size = 1;\t$data = '/';\tbreak;\n\t\tcase 0x07: $name = 'tPower';\t$size = 1;\t$data = '^';\tbreak;\n\t\tcase 0x08: $name = 'tConcat';\t$size = 1;\t$data = '&';\tbreak;\n\t\tcase 0x09: $name = 'tLT';\t\t$size = 1;\t$data = '<';\tbreak;\n\t\tcase 0x0A: $name = 'tLE';\t\t$size = 1;\t$data = '<=';\tbreak;\n\t\tcase 0x0B: $name = 'tEQ';\t\t$size = 1;\t$data = '=';\tbreak;\n\t\tcase 0x0C: $name = 'tGE';\t\t$size = 1;\t$data = '>=';\tbreak;\n\t\tcase 0x0D: $name = 'tGT';\t\t$size = 1;\t$data = '>';\tbreak;\n\t\tcase 0x0E: $name = 'tNE';\t\t$size = 1;\t$data = '<>';\tbreak;\n\t\tcase 0x0F: $name = 'tIsect';\t$size = 1;\t$data = ' ';\tbreak;\n\t\tcase 0x10: $name = 'tList';\t\t$size = 1;\t$data = ',';\tbreak;\n\t\tcase 0x11: $name = 'tRange';\t$size = 1;\t$data = ':';\tbreak;\n\t\tcase 0x12: $name = 'tUplus';\t$size = 1;\t$data = '+';\tbreak;\n\t\tcase 0x13: $name = 'tUminus';\t$size = 1;\t$data = '-';\tbreak;\n\t\tcase 0x14: $name = 'tPercent';\t$size = 1;\t$data = '%';\tbreak;\n\t\tcase 0x15:\t//\tparenthesis\n\t\t\t$name = 'tParen';\n\t\t\t$size = 1;\n\t\t\t$data = null;\n\t\t\tbreak;\n\t\tcase 0x16:\t//\tmissing argument\n\t\t\t$name = 'tMissArg';\n\t\t\t$size = 1;\n\t\t\t$data = '';\n\t\t\tbreak;\n\t\tcase 0x17:\t//\tstring\n\t\t\t$name = 'tStr';\n\t\t\t// offset: 1; size: var; Unicode string, 8-bit string length\n\t\t\t$string = self::_readUnicodeStringShort(substr($formulaData, 1));\n\t\t\t$size = 1 + $string['size'];\n\t\t\t$data = self::_UTF8toExcelDoubleQuoted($string['value']);\n\t\t\tbreak;\n\t\tcase 0x19:\t//\tSpecial attribute\n\t\t\t// offset: 1; size: 1; attribute type flags:\n\t\t\tswitch (ord($formulaData[1])) {\n\t\t\tcase 0x01:\n\t\t\t\t$name = 'tAttrVolatile';\n\t\t\t\t$size = 4;\n\t\t\t\t$data = null;\n\t\t\t\tbreak;\n\t\t\tcase 0x02:\n\t\t\t\t$name = 'tAttrIf';\n\t\t\t\t$size = 4;\n\t\t\t\t$data = null;\n\t\t\t\tbreak;\n\t\t\tcase 0x04:\n\t\t\t\t$name = 'tAttrChoose';\n\t\t\t\t// offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1)\n\t\t\t\t$nc = self::_GetInt2d($formulaData, 2);\n\t\t\t\t// offset: 4; size: 2 * $nc\n\t\t\t\t// offset: 4 + 2 * $nc; size: 2\n\t\t\t\t$size = 2 * $nc + 6;\n\t\t\t\t$data = null;\n\t\t\t\tbreak;\n\t\t\tcase 0x08:\n\t\t\t\t$name = 'tAttrSkip';\n\t\t\t\t$size = 4;\n\t\t\t\t$data = null;\n\t\t\t\tbreak;\n\t\t\tcase 0x10:\n\t\t\t\t$name = 'tAttrSum';\n\t\t\t\t$size = 4;\n\t\t\t\t$data = null;\n\t\t\t\tbreak;\n\t\t\tcase 0x40:\n\t\t\tcase 0x41:\n\t\t\t\t$name = 'tAttrSpace';\n\t\t\t\t$size = 4;\n\t\t\t\t// offset: 2; size: 2; space type and position\n\t\t\t\tswitch (ord($formulaData[2])) {\n\t\t\t\tcase 0x00:\n\t\t\t\t\t$spacetype = 'type0';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x01:\n\t\t\t\t\t$spacetype = 'type1';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x02:\n\t\t\t\t\t$spacetype = 'type2';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x03:\n\t\t\t\t\t$spacetype = 'type3';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x04:\n\t\t\t\t\t$spacetype = 'type4';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x05:\n\t\t\t\t\t$spacetype = 'type5';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception('Unrecognized space type in tAttrSpace token');\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// offset: 3; size: 1; number of inserted spaces/carriage returns\n\t\t\t\t$spacecount = ord($formulaData[3]);\n\n\t\t\t\t$data = array('spacetype' => $spacetype, 'spacecount' => $spacecount);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception('Unrecognized attribute flag in tAttr token');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0x1C:\t//\terror code\n\t\t\t// offset: 1; size: 1; error code\n\t\t\t$name = 'tErr';\n\t\t\t$size = 2;\n\t\t\t$data = self::_mapErrorCode(ord($formulaData[1]));\n\t\t\tbreak;\n\t\tcase 0x1D:\t//\tboolean\n\t\t\t// offset: 1; size: 1; 0 = false, 1 = true;\n\t\t\t$name = 'tBool';\n\t\t\t$size = 2;\n\t\t\t$data = ord($formulaData[1]) ? 'TRUE' : 'FALSE';\n\t\t\tbreak;\n\t\tcase 0x1E:\t//\tinteger\n\t\t\t// offset: 1; size: 2; unsigned 16-bit integer\n\t\t\t$name = 'tInt';\n\t\t\t$size = 3;\n\t\t\t$data = self::_GetInt2d($formulaData, 1);\n\t\t\tbreak;\n\t\tcase 0x1F:\t//\tnumber\n\t\t\t// offset: 1; size: 8;\n\t\t\t$name = 'tNum';\n\t\t\t$size = 9;\n\t\t\t$data = self::_extractNumber(substr($formulaData, 1));\n\t\t\t$data = str_replace(',', '.', (string)$data); // in case non-English locale\n\t\t\tbreak;\n\t\tcase 0x20:\t//\tarray constant\n\t\tcase 0x40:\n\t\tcase 0x60:\n\t\t\t// offset: 1; size: 7; not used\n\t\t\t$name = 'tArray';\n\t\t\t$size = 8;\n\t\t\t$data = null;\n\t\t\tbreak;\n\t\tcase 0x21:\t//\tfunction with fixed number of arguments\n\t\tcase 0x41:\n\t\tcase 0x61:\n\t\t\t$name = 'tFunc';\n\t\t\t$size = 3;\n\t\t\t// offset: 1; size: 2; index to built-in sheet function\n\t\t\tswitch (self::_GetInt2d($formulaData, 1)) {\n\t\t\tcase 2: $function = 'ISNA'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 3: $function = 'ISERROR'; \t\t$args = 1; \tbreak;\n\t\t\tcase 10: $function = 'NA'; \t\t\t$args = 0; \tbreak;\n\t\t\tcase 15: $function = 'SIN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 16: $function = 'COS'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 17: $function = 'TAN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 18: $function = 'ATAN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 19: $function = 'PI'; \t\t\t$args = 0; \tbreak;\n\t\t\tcase 20: $function = 'SQRT'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 21: $function = 'EXP'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 22: $function = 'LN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 23: $function = 'LOG10'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 24: $function = 'ABS'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 25: $function = 'INT'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 26: $function = 'SIGN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 27: $function = 'ROUND'; \t\t\t$args = 2; \tbreak;\n\t\t\tcase 30: $function = 'REPT'; \t\t\t$args = 2; \tbreak;\n\t\t\tcase 31: $function = 'MID'; \t\t\t$args = 3; \tbreak;\n\t\t\tcase 32: $function = 'LEN'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 33: $function = 'VALUE'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 34: $function = 'TRUE'; \t\t\t$args = 0; \tbreak;\n\t\t\tcase 35: $function = 'FALSE'; \t\t\t$args = 0; \tbreak;\n\t\t\tcase 38: $function = 'NOT'; \t\t\t$args = 1; \tbreak;\n\t\t\tcase 39: $function = 'MOD'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 40: $function = 'DCOUNT'; \t\t$args = 3;\tbreak;\n\t\t\tcase 41: $function = 'DSUM'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 42: $function = 'DAVERAGE'; \t\t$args = 3;\tbreak;\n\t\t\tcase 43: $function = 'DMIN'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 44: $function = 'DMAX'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 45: $function = 'DSTDEV'; \t\t$args = 3;\tbreak;\n\t\t\tcase 48: $function = 'TEXT'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 61: $function = 'MIRR'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 63: $function = 'RAND'; \t\t\t$args = 0;\tbreak;\n\t\t\tcase 65: $function = 'DATE'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 66: $function = 'TIME'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 67: $function = 'DAY'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 68: $function = 'MONTH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 69: $function = 'YEAR'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 71: $function = 'HOUR'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 72: $function = 'MINUTE'; \t\t$args = 1;\tbreak;\n\t\t\tcase 73: $function = 'SECOND'; \t\t$args = 1;\tbreak;\n\t\t\tcase 74: $function = 'NOW'; \t\t\t$args = 0;\tbreak;\n\t\t\tcase 75: $function = 'AREAS'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 76: $function = 'ROWS'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 77: $function = 'COLUMNS'; \t\t$args = 1;\tbreak;\n\t\t\tcase 83: $function = 'TRANSPOSE'; \t\t$args = 1;\tbreak;\n\t\t\tcase 86: $function = 'TYPE'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 97: $function = 'ATAN2'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 98: $function = 'ASIN'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 99: $function = 'ACOS'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 105: $function = 'ISREF'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 111: $function = 'CHAR'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 112: $function = 'LOWER'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 113: $function = 'UPPER'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 114: $function = 'PROPER'; \t\t$args = 1;\tbreak;\n\t\t\tcase 117: $function = 'EXACT'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 118: $function = 'TRIM'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 119: $function = 'REPLACE'; \t\t$args = 4;\tbreak;\n\t\t\tcase 121: $function = 'CODE'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 126: $function = 'ISERR'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 127: $function = 'ISTEXT'; \t\t$args = 1;\tbreak;\n\t\t\tcase 128: $function = 'ISNUMBER'; \t\t$args = 1;\tbreak;\n\t\t\tcase 129: $function = 'ISBLANK'; \t\t$args = 1;\tbreak;\n\t\t\tcase 130: $function = 'T'; \t\t\t\t$args = 1;\tbreak;\n\t\t\tcase 131: $function = 'N'; \t\t\t\t$args = 1;\tbreak;\n\t\t\tcase 140: $function = 'DATEVALUE'; \t\t$args = 1;\tbreak;\n\t\t\tcase 141: $function = 'TIMEVALUE'; \t\t$args = 1;\tbreak;\n\t\t\tcase 142: $function = 'SLN'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 143: $function = 'SYD'; \t\t\t$args = 4;\tbreak;\n\t\t\tcase 162: $function = 'CLEAN'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 163: $function = 'MDETERM'; \t\t$args = 1;\tbreak;\n\t\t\tcase 164: $function = 'MINVERSE'; \t\t$args = 1;\tbreak;\n\t\t\tcase 165: $function = 'MMULT'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 184: $function = 'FACT'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 189: $function = 'DPRODUCT'; \t\t$args = 3;\tbreak;\n\t\t\tcase 190: $function = 'ISNONTEXT'; \t\t$args = 1;\tbreak;\n\t\t\tcase 195: $function = 'DSTDEVP'; \t\t$args = 3;\tbreak;\n\t\t\tcase 196: $function = 'DVARP'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 198: $function = 'ISLOGICAL'; \t\t$args = 1;\tbreak;\n\t\t\tcase 199: $function = 'DCOUNTA'; \t\t$args = 3;\tbreak;\n\t\t\tcase 207: $function = 'REPLACEB'; \t\t$args = 4;\tbreak;\n\t\t\tcase 210: $function = 'MIDB'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 211: $function = 'LENB'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 212: $function = 'ROUNDUP'; \t\t$args = 2;\tbreak;\n\t\t\tcase 213: $function = 'ROUNDDOWN'; \t\t$args = 2;\tbreak;\n\t\t\tcase 214: $function = 'ASC'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 215: $function = 'DBCS'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 221: $function = 'TODAY'; \t\t\t$args = 0;\tbreak;\n\t\t\tcase 229: $function = 'SINH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 230: $function = 'COSH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 231: $function = 'TANH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 232: $function = 'ASINH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 233: $function = 'ACOSH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 234: $function = 'ATANH'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 235: $function = 'DGET'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 244: $function = 'INFO'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 252: $function = 'FREQUENCY'; \t\t$args = 2;\tbreak;\n\t\t\tcase 261: $function = 'ERROR.TYPE'; \t$args = 1;\tbreak;\n\t\t\tcase 271: $function = 'GAMMALN'; \t\t$args = 1;\tbreak;\n\t\t\tcase 273: $function = 'BINOMDIST'; \t\t$args = 4;\tbreak;\n\t\t\tcase 274: $function = 'CHIDIST'; \t\t$args = 2;\tbreak;\n\t\t\tcase 275: $function = 'CHIINV'; \t\t$args = 2;\tbreak;\n\t\t\tcase 276: $function = 'COMBIN'; \t\t$args = 2;\tbreak;\n\t\t\tcase 277: $function = 'CONFIDENCE'; \t$args = 3;\tbreak;\n\t\t\tcase 278: $function = 'CRITBINOM'; \t\t$args = 3;\tbreak;\n\t\t\tcase 279: $function = 'EVEN'; \t\t\t$args = 1;\tbreak;\n\t\t\tcase 280: $function = 'EXPONDIST'; \t\t$args = 3;\tbreak;\n\t\t\tcase 281: $function = 'FDIST'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 282: $function = 'FINV'; \t\t\t$args = 3;\tbreak;\n\t\t\tcase 283: $function = 'FISHER'; \t\t$args = 1;\tbreak;\n\t\t\tcase 284: $function = 'FISHERINV'; \t\t$args = 1;\tbreak;\n\t\t\tcase 285: $function = 'FLOOR'; \t\t\t$args = 2;\tbreak;\n\t\t\tcase 286: $function = 'GAMMADIST'; \t\t$args = 4;\tbreak;\n\t\t\tcase 287: $function = 'GAMMAINV'; \t\t$args = 3;\tbreak;\n\t\t\tcase 288: $function = 'CEILING'; \t\t$args = 2;\tbreak;\n\t\t\tcase 289: $function = 'HYPGEOMDIST';\t$args = 4;\tbreak;\n\t\t\tcase 290: $function = 'LOGNORMDIST';\t$args = 3;\tbreak;\n\t\t\tcase 291: $function = 'LOGINV';\t\t\t$args = 3;\tbreak;\n\t\t\tcase 292: $function = 'NEGBINOMDIST';\t$args = 3;\tbreak;\n\t\t\tcase 293: $function = 'NORMDIST';\t\t$args = 4;\tbreak;\n\t\t\tcase 294: $function = 'NORMSDIST';\t\t$args = 1;\tbreak;\n\t\t\tcase 295: $function = 'NORMINV';\t\t$args = 3;\tbreak;\n\t\t\tcase 296: $function = 'NORMSINV';\t\t$args = 1;\tbreak;\n\t\t\tcase 297: $function = 'STANDARDIZE';\t$args = 3;\tbreak;\n\t\t\tcase 298: $function = 'ODD';\t\t\t$args = 1;\tbreak;\n\t\t\tcase 299: $function = 'PERMUT';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 300: $function = 'POISSON';\t\t$args = 3;\tbreak;\n\t\t\tcase 301: $function = 'TDIST';\t\t\t$args = 3;\tbreak;\n\t\t\tcase 302: $function = 'WEIBULL';\t\t$args = 4;\tbreak;\n\t\t\tcase 303: $function = 'SUMXMY2';\t\t$args = 2;\tbreak;\n\t\t\tcase 304: $function = 'SUMX2MY2';\t\t$args = 2;\tbreak;\n\t\t\tcase 305: $function = 'SUMX2PY2';\t\t$args = 2;\tbreak;\n\t\t\tcase 306: $function = 'CHITEST';\t\t$args = 2;\tbreak;\n\t\t\tcase 307: $function = 'CORREL';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 308: $function = 'COVAR';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 309: $function = 'FORECAST';\t\t$args = 3;\tbreak;\n\t\t\tcase 310: $function = 'FTEST';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 311: $function = 'INTERCEPT';\t\t$args = 2;\tbreak;\n\t\t\tcase 312: $function = 'PEARSON';\t\t$args = 2;\tbreak;\n\t\t\tcase 313: $function = 'RSQ';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 314: $function = 'STEYX';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 315: $function = 'SLOPE';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 316: $function = 'TTEST';\t\t\t$args = 4;\tbreak;\n\t\t\tcase 325: $function = 'LARGE';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 326: $function = 'SMALL';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 327: $function = 'QUARTILE';\t\t$args = 2;\tbreak;\n\t\t\tcase 328: $function = 'PERCENTILE';\t\t$args = 2;\tbreak;\n\t\t\tcase 331: $function = 'TRIMMEAN';\t\t$args = 2;\tbreak;\n\t\t\tcase 332: $function = 'TINV';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 337: $function = 'POWER';\t\t\t$args = 2;\tbreak;\n\t\t\tcase 342: $function = 'RADIANS';\t\t$args = 1;\tbreak;\n\t\t\tcase 343: $function = 'DEGREES';\t\t$args = 1;\tbreak;\n\t\t\tcase 346: $function = 'COUNTIF';\t\t$args = 2;\tbreak;\n\t\t\tcase 347: $function = 'COUNTBLANK';\t\t$args = 1;\tbreak;\n\t\t\tcase 350: $function = 'ISPMT';\t\t\t$args = 4;\tbreak;\n\t\t\tcase 351: $function = 'DATEDIF';\t\t$args = 3;\tbreak;\n\t\t\tcase 352: $function = 'DATESTRING';\t\t$args = 1;\tbreak;\n\t\t\tcase 353: $function = 'NUMBERSTRING';\t$args = 2;\tbreak;\n\t\t\tcase 360: $function = 'PHONETIC';\t\t$args = 1;\tbreak;\n\t\t\tcase 368: $function = 'BAHTTEXT';\t\t$args = 1;\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception('Unrecognized function in formula');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$data = array('function' => $function, 'args' => $args);\n\t\t\tbreak;\n\t\tcase 0x22:\t//\tfunction with variable number of arguments\n\t\tcase 0x42:\n\t\tcase 0x62:\n\t\t\t$name = 'tFuncV';\n\t\t\t$size = 4;\n\t\t\t// offset: 1; size: 1; number of arguments\n\t\t\t$args = ord($formulaData[1]);\n\t\t\t// offset: 2: size: 2; index to built-in sheet function\n\t\t\t$index = self::_GetInt2d($formulaData, 2);\n\t\t\tswitch ($index) {\n\t\t\tcase 0: $function = 'COUNT';\t\t\tbreak;\n\t\t\tcase 1: $function = 'IF';\t\t\t\tbreak;\n\t\t\tcase 4: $function = 'SUM';\t\t\tbreak;\n\t\t\tcase 5: $function = 'AVERAGE';\t\tbreak;\n\t\t\tcase 6: $function = 'MIN';\t\t\tbreak;\n\t\t\tcase 7: $function = 'MAX';\t\t\tbreak;\n\t\t\tcase 8: $function = 'ROW';\t\t\tbreak;\n\t\t\tcase 9: $function = 'COLUMN';\t\t\tbreak;\n\t\t\tcase 11: $function = 'NPV';\t\t\tbreak;\n\t\t\tcase 12: $function = 'STDEV';\t\t\tbreak;\n\t\t\tcase 13: $function = 'DOLLAR';\t\t\tbreak;\n\t\t\tcase 14: $function = 'FIXED';\t\t\tbreak;\n\t\t\tcase 28: $function = 'LOOKUP';\t\t\tbreak;\n\t\t\tcase 29: $function = 'INDEX';\t\t\tbreak;\n\t\t\tcase 36: $function = 'AND';\t\t\tbreak;\n\t\t\tcase 37: $function = 'OR';\t\t\t\tbreak;\n\t\t\tcase 46: $function = 'VAR';\t\t\tbreak;\n\t\t\tcase 49: $function = 'LINEST';\t\t\tbreak;\n\t\t\tcase 50: $function = 'TREND';\t\t\tbreak;\n\t\t\tcase 51: $function = 'LOGEST';\t\t\tbreak;\n\t\t\tcase 52: $function = 'GROWTH';\t\t\tbreak;\n\t\t\tcase 56: $function = 'PV';\t\t\t\tbreak;\n\t\t\tcase 57: $function = 'FV';\t\t\t\tbreak;\n\t\t\tcase 58: $function = 'NPER';\t\t\tbreak;\n\t\t\tcase 59: $function = 'PMT';\t\t\tbreak;\n\t\t\tcase 60: $function = 'RATE';\t\t\tbreak;\n\t\t\tcase 62: $function = 'IRR';\t\t\tbreak;\n\t\t\tcase 64: $function = 'MATCH';\t\t\tbreak;\n\t\t\tcase 70: $function = 'WEEKDAY';\t\tbreak;\n\t\t\tcase 78: $function = 'OFFSET';\t\t\tbreak;\n\t\t\tcase 82: $function = 'SEARCH';\t\t\tbreak;\n\t\t\tcase 100: $function = 'CHOOSE';\t\t\tbreak;\n\t\t\tcase 101: $function = 'HLOOKUP';\t\tbreak;\n\t\t\tcase 102: $function = 'VLOOKUP';\t\tbreak;\n\t\t\tcase 109: $function = 'LOG';\t\t\tbreak;\n\t\t\tcase 115: $function = 'LEFT';\t\t\tbreak;\n\t\t\tcase 116: $function = 'RIGHT';\t\t\tbreak;\n\t\t\tcase 120: $function = 'SUBSTITUTE';\t\tbreak;\n\t\t\tcase 124: $function = 'FIND';\t\t\tbreak;\n\t\t\tcase 125: $function = 'CELL';\t\t\tbreak;\n\t\t\tcase 144: $function = 'DDB';\t\t\tbreak;\n\t\t\tcase 148: $function = 'INDIRECT';\t\tbreak;\n\t\t\tcase 167: $function = 'IPMT';\t\t\tbreak;\n\t\t\tcase 168: $function = 'PPMT';\t\t\tbreak;\n\t\t\tcase 169: $function = 'COUNTA';\t\t\tbreak;\n\t\t\tcase 183: $function = 'PRODUCT';\t\tbreak;\n\t\t\tcase 193: $function = 'STDEVP';\t\t\tbreak;\n\t\t\tcase 194: $function = 'VARP';\t\t\tbreak;\n\t\t\tcase 197: $function = 'TRUNC';\t\t\tbreak;\n\t\t\tcase 204: $function = 'USDOLLAR';\t\tbreak;\n\t\t\tcase 205: $function = 'FINDB';\t\t\tbreak;\n\t\t\tcase 206: $function = 'SEARCHB';\t\tbreak;\n\t\t\tcase 208: $function = 'LEFTB';\t\t\tbreak;\n\t\t\tcase 209: $function = 'RIGHTB';\t\t\tbreak;\n\t\t\tcase 216: $function = 'RANK';\t\t\tbreak;\n\t\t\tcase 219: $function = 'ADDRESS';\t\tbreak;\n\t\t\tcase 220: $function = 'DAYS360';\t\tbreak;\n\t\t\tcase 222: $function = 'VDB';\t\t\tbreak;\n\t\t\tcase 227: $function = 'MEDIAN';\t\t\tbreak;\n\t\t\tcase 228: $function = 'SUMPRODUCT';\t\tbreak;\n\t\t\tcase 247: $function = 'DB';\t\t\t\tbreak;\n\t\t\tcase 255: $function = '';\t\t\t\tbreak;\n\t\t\tcase 269: $function = 'AVEDEV';\t\t\tbreak;\n\t\t\tcase 270: $function = 'BETADIST';\t\tbreak;\n\t\t\tcase 272: $function = 'BETAINV';\t\tbreak;\n\t\t\tcase 317: $function = 'PROB';\t\t\tbreak;\n\t\t\tcase 318: $function = 'DEVSQ';\t\t\tbreak;\n\t\t\tcase 319: $function = 'GEOMEAN';\t\tbreak;\n\t\t\tcase 320: $function = 'HARMEAN';\t\tbreak;\n\t\t\tcase 321: $function = 'SUMSQ';\t\t\tbreak;\n\t\t\tcase 322: $function = 'KURT';\t\t\tbreak;\n\t\t\tcase 323: $function = 'SKEW';\t\t\tbreak;\n\t\t\tcase 324: $function = 'ZTEST';\t\t\tbreak;\n\t\t\tcase 329: $function = 'PERCENTRANK';\tbreak;\n\t\t\tcase 330: $function = 'MODE';\t\t\tbreak;\n\t\t\tcase 336: $function = 'CONCATENATE';\tbreak;\n\t\t\tcase 344: $function = 'SUBTOTAL';\t\tbreak;\n\t\t\tcase 345: $function = 'SUMIF';\t\t\tbreak;\n\t\t\tcase 354: $function = 'ROMAN';\t\t\tbreak;\n\t\t\tcase 358: $function = 'GETPIVOTDATA';\tbreak;\n\t\t\tcase 359: $function = 'HYPERLINK';\t\tbreak;\n\t\t\tcase 361: $function = 'AVERAGEA';\t\tbreak;\n\t\t\tcase 362: $function = 'MAXA';\t\t\tbreak;\n\t\t\tcase 363: $function = 'MINA';\t\t\tbreak;\n\t\t\tcase 364: $function = 'STDEVPA';\t\tbreak;\n\t\t\tcase 365: $function = 'VARPA';\t\t\tbreak;\n\t\t\tcase 366: $function = 'STDEVA';\t\t\tbreak;\n\t\t\tcase 367: $function = 'VARA';\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception('Unrecognized function in formula');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$data = array('function' => $function, 'args' => $args);\n\t\t\tbreak;\n\t\tcase 0x23:\t//\tindex to defined name\n\t\tcase 0x43:\n\t\tcase 0x63:\n\t\t\t$name = 'tName';\n\t\t\t$size = 5;\n\t\t\t// offset: 1; size: 2; one-based index to definedname record\n\t\t\t$definedNameIndex = self::_GetInt2d($formulaData, 1) - 1;\n\t\t\t// offset: 2; size: 2; not used\n\t\t\t$data = $this->_definedname[$definedNameIndex]['name'];\n\t\t\tbreak;\n\t\tcase 0x24:\t//\tsingle cell reference e.g. A5\n\t\tcase 0x44:\n\t\tcase 0x64:\n\t\t\t$name = 'tRef';\n\t\t\t$size = 5;\n\t\t\t$data = $this->_readBIFF8CellAddress(substr($formulaData, 1, 4));\n\t\t\tbreak;\n\t\tcase 0x25:\t//\tcell range reference to cells in the same sheet (2d)\n\t\tcase 0x45:\n\t\tcase 0x65:\n\t\t\t$name = 'tArea';\n\t\t\t$size = 9;\n\t\t\t$data = $this->_readBIFF8CellRangeAddress(substr($formulaData, 1, 8));\n\t\t\tbreak;\n\t\tcase 0x26:\t//\tConstant reference sub-expression\n\t\tcase 0x46:\n\t\tcase 0x66:\n\t\t\t$name = 'tMemArea';\n\t\t\t// offset: 1; size: 4; not used\n\t\t\t// offset: 5; size: 2; size of the following subexpression\n\t\t\t$subSize = self::_GetInt2d($formulaData, 5);\n\t\t\t$size = 7 + $subSize;\n\t\t\t$data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize));\n\t\t\tbreak;\n\t\tcase 0x27:\t//\tDeleted constant reference sub-expression\n\t\tcase 0x47:\n\t\tcase 0x67:\n\t\t\t$name = 'tMemErr';\n\t\t\t// offset: 1; size: 4; not used\n\t\t\t// offset: 5; size: 2; size of the following subexpression\n\t\t\t$subSize = self::_GetInt2d($formulaData, 5);\n\t\t\t$size = 7 + $subSize;\n\t\t\t$data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize));\n\t\t\tbreak;\n\t\tcase 0x29:\t//\tVariable reference sub-expression\n\t\tcase 0x49:\n\t\tcase 0x69:\n\t\t\t$name = 'tMemFunc';\n\t\t\t// offset: 1; size: 2; size of the following sub-expression\n\t\t\t$subSize = self::_GetInt2d($formulaData, 1);\n\t\t\t$size = 3 + $subSize;\n\t\t\t$data = $this->_getFormulaFromData(substr($formulaData, 3, $subSize));\n\t\t\tbreak;\n\n\t\tcase 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places\n\t\tcase 0x4C:\n\t\tcase 0x6C:\n\t\t\t$name = 'tRefN';\n\t\t\t$size = 5;\n\t\t\t$data = $this->_readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell);\n\t\t\tbreak;\n\n\t\tcase 0x2D:\t//\tRelative 2d range reference\n\t\tcase 0x4D:\n\t\tcase 0x6D:\n\t\t\t$name = 'tAreaN';\n\t\t\t$size = 9;\n\t\t\t$data = $this->_readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell);\n\t\t\tbreak;\n\n\t\tcase 0x39:\t//\tExternal name\n\t\tcase 0x59:\n\t\tcase 0x79:\n\t\t\t$name = 'tNameX';\n\t\t\t$size = 7;\n\t\t\t// offset: 1; size: 2; index to REF entry in EXTERNSHEET record\n\t\t\t// offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record\n\t\t\t$index = self::_GetInt2d($formulaData, 3);\n\t\t\t// assume index is to EXTERNNAME record\n\t\t\t$data = $this->_externalNames[$index - 1]['name'];\n\t\t\t// offset: 5; size: 2; not used\n\t\t\tbreak;\n\n\t\tcase 0x3A:\t//\t3d reference to cell\n\t\tcase 0x5A:\n\t\tcase 0x7A:\n\t\t\t$name = 'tRef3d';\n\t\t\t$size = 7;\n\n\t\t\ttry {\n\t\t\t\t// offset: 1; size: 2; index to REF entry\n\t\t\t\t$sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1));\n\t\t\t\t// offset: 3; size: 4; cell address\n\t\t\t\t$cellAddress = $this->_readBIFF8CellAddress(substr($formulaData, 3, 4));\n\n\t\t\t\t$data = \"$sheetRange!$cellAddress\";\n\t\t\t} catch (Exception $e) {\n\t\t\t\t// deleted sheet reference\n\t\t\t\t$data = '#REF!';\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase 0x3B:\t//\t3d reference to cell range\n\t\tcase 0x5B:\n\t\tcase 0x7B:\n\t\t\t$name = 'tArea3d';\n\t\t\t$size = 11;\n\n\t\t\ttry {\n\t\t\t\t// offset: 1; size: 2; index to REF entry\n\t\t\t\t$sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1));\n\t\t\t\t// offset: 3; size: 8; cell address\n\t\t\t\t$cellRangeAddress = $this->_readBIFF8CellRangeAddress(substr($formulaData, 3, 8));\n\n\t\t\t\t$data = \"$sheetRange!$cellRangeAddress\";\n\t\t\t} catch (Exception $e) {\n\t\t\t\t// deleted sheet reference\n\t\t\t\t$data = '#REF!';\n\t\t\t}\n\n\t\t\tbreak;\n\t\t// Unknown cases\t// don't know how to deal with\n\t\tdefault:\n\t\t\tthrow new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula');\n\t\t\tbreak;\n\t\t}\n\n\t\treturn array(\n\t\t\t'id' => $id,\n\t\t\t'name' => $name,\n\t\t\t'size' => $size,\n\t\t\t'data' => $data,\n\t\t);\n\t}\n\n\t/**\n\t * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2'\n\t * section 3.3.4\n\t *\n\t * @param string $cellAddressStructure\n\t * @return string\n\t */\n\tprivate function _readBIFF8CellAddress($cellAddressStructure)\n\t{\n\t\t// offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))\n\t\t$row = self::_GetInt2d($cellAddressStructure, 0) + 1;\n\n\t\t// offset: 2; size: 2; index to column or column offset + relative flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$column = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($cellAddressStructure, 2));\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) {\n\t\t\t\t$column = '$' . $column;\n\t\t\t}\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) {\n\t\t\t\t$row = '$' . $row;\n\t\t\t}\n\n\t\treturn $column . $row;\n\t}\n\n\t/**\n\t * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column\n\t * to indicate offsets from a base cell\n\t * section 3.3.4\n\t *\n\t * @param string $cellAddressStructure\n\t * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas\n\t * @return string\n\t */\n\tprivate function _readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1')\n\t{\n\t\tlist($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell);\n\t\t$baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1;\n\n\t\t// offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))\n\t\t\t$rowIndex = self::_GetInt2d($cellAddressStructure, 0);\n\t\t\t$row = self::_GetInt2d($cellAddressStructure, 0) + 1;\n\n\t\t// offset: 2; size: 2; index to column or column offset + relative flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$colIndex = 0x00FF & self::_GetInt2d($cellAddressStructure, 2);\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) {\n\t\t\t\t$column = PHPExcel_Cell::stringFromColumnIndex($colIndex);\n\t\t\t\t$column = '$' . $column;\n\t\t\t} else {\n\t\t\t\t$colIndex = ($colIndex <= 127) ? $colIndex : $colIndex - 256;\n\t\t\t\t$column = PHPExcel_Cell::stringFromColumnIndex($baseCol + $colIndex);\n\t\t\t}\n\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) {\n\t\t\t\t$row = '$' . $row;\n\t\t\t} else {\n\t\t\t\t$rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536;\n\t\t\t\t$row = $baseRow + $rowIndex;\n\t\t\t}\n\n\t\treturn $column . $row;\n\t}\n\n\t/**\n\t * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1'\n\t * always fixed range\n\t * section 2.5.14\n\t *\n\t * @param string $subData\n\t * @return string\n\t * @throws Exception\n\t */\n\tprivate function _readBIFF5CellRangeAddressFixed($subData)\n\t{\n\t\t// offset: 0; size: 2; index to first row\n\t\t$fr = self::_GetInt2d($subData, 0) + 1;\n\n\t\t// offset: 2; size: 2; index to last row\n\t\t$lr = self::_GetInt2d($subData, 2) + 1;\n\n\t\t// offset: 4; size: 1; index to first column\n\t\t$fc = ord($subData{4});\n\n\t\t// offset: 5; size: 1; index to last column\n\t\t$lc = ord($subData{5});\n\n\t\t// check values\n\t\tif ($fr > $lr || $fc > $lc) {\n\t\t\tthrow new Exception('Not a cell range address');\n\t\t}\n\n\t\t// column index to letter\n\t\t$fc = PHPExcel_Cell::stringFromColumnIndex($fc);\n\t\t$lc = PHPExcel_Cell::stringFromColumnIndex($lc);\n\n\t\tif ($fr == $lr and $fc == $lc) {\n\t\t\treturn \"$fc$fr\";\n\t\t}\n\t\treturn \"$fc$fr:$lc$lr\";\n\t}\n\n\t/**\n\t * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1'\n\t * always fixed range\n\t * section 2.5.14\n\t *\n\t * @param string $subData\n\t * @return string\n\t * @throws Exception\n\t */\n\tprivate function _readBIFF8CellRangeAddressFixed($subData)\n\t{\n\t\t// offset: 0; size: 2; index to first row\n\t\t$fr = self::_GetInt2d($subData, 0) + 1;\n\n\t\t// offset: 2; size: 2; index to last row\n\t\t$lr = self::_GetInt2d($subData, 2) + 1;\n\n\t\t// offset: 4; size: 2; index to first column\n\t\t$fc = self::_GetInt2d($subData, 4);\n\n\t\t// offset: 6; size: 2; index to last column\n\t\t$lc = self::_GetInt2d($subData, 6);\n\n\t\t// check values\n\t\tif ($fr > $lr || $fc > $lc) {\n\t\t\tthrow new Exception('Not a cell range address');\n\t\t}\n\n\t\t// column index to letter\n\t\t$fc = PHPExcel_Cell::stringFromColumnIndex($fc);\n\t\t$lc = PHPExcel_Cell::stringFromColumnIndex($lc);\n\n\t\tif ($fr == $lr and $fc == $lc) {\n\t\t\treturn \"$fc$fr\";\n\t\t}\n\t\treturn \"$fc$fr:$lc$lr\";\n\t}\n\n\t/**\n\t * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6'\n\t * there are flags indicating whether column/row index is relative\n\t * section 3.3.4\n\t *\n\t * @param string $subData\n\t * @return string\n\t */\n\tprivate function _readBIFF8CellRangeAddress($subData)\n\t{\n\t\t// todo: if cell range is just a single cell, should this funciton\n\t\t// not just return e.g. 'A1' and not 'A1:A1' ?\n\n\t\t// offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767))\n\t\t\t$fr = self::_GetInt2d($subData, 0) + 1;\n\n\t\t// offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767))\n\t\t\t$lr = self::_GetInt2d($subData, 2) + 1;\n\n\t\t// offset: 4; size: 2; index to first column or column offset + relative flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$fc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 4));\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($subData, 4))) {\n\t\t\t\t$fc = '$' . $fc;\n\t\t\t}\n\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($subData, 4))) {\n\t\t\t\t$fr = '$' . $fr;\n\t\t\t}\n\n\t\t// offset: 6; size: 2; index to last column or column offset + relative flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$lc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 6));\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($subData, 6))) {\n\t\t\t\t$lc = '$' . $lc;\n\t\t\t}\n\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($subData, 6))) {\n\t\t\t\t$lr = '$' . $lr;\n\t\t\t}\n\n\t\treturn \"$fc$fr:$lc$lr\";\n\t}\n\n\t/**\n\t * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column\n\t * to indicate offsets from a base cell\n\t * section 3.3.4\n\t *\n\t * @param string $subData\n\t * @param string $baseCell Base cell\n\t * @return string Cell range address\n\t */\n\tprivate function _readBIFF8CellRangeAddressB($subData, $baseCell = 'A1')\n\t{\n\t\tlist($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell);\n\t\t$baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1;\n\n\t\t// TODO: if cell range is just a single cell, should this funciton\n\t\t// not just return e.g. 'A1' and not 'A1:A1' ?\n\n\t\t// offset: 0; size: 2; first row\n\t\t$frIndex = self::_GetInt2d($subData, 0); // adjust below\n\n\t\t// offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767)\n\t\t$lrIndex = self::_GetInt2d($subData, 2); // adjust below\n\n\t\t// offset: 4; size: 2; first column with relative/absolute flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$fcIndex = 0x00FF & self::_GetInt2d($subData, 4);\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($subData, 4))) {\n\t\t\t\t// absolute column index\n\t\t\t\t$fc = PHPExcel_Cell::stringFromColumnIndex($fcIndex);\n\t\t\t\t$fc = '$' . $fc;\n\t\t\t} else {\n\t\t\t\t// column offset\n\t\t\t\t$fcIndex = ($fcIndex <= 127) ? $fcIndex : $fcIndex - 256;\n\t\t\t\t$fc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $fcIndex);\n\t\t\t}\n\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($subData, 4))) {\n\t\t\t\t// absolute row index\n\t\t\t\t$fr = $frIndex + 1;\n\t\t\t\t$fr = '$' . $fr;\n\t\t\t} else {\n\t\t\t\t// row offset\n\t\t\t\t$frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536;\n\t\t\t\t$fr = $baseRow + $frIndex;\n\t\t\t}\n\n\t\t// offset: 6; size: 2; last column with relative/absolute flags\n\n\t\t\t// bit: 7-0; mask 0x00FF; column index\n\t\t\t$lcIndex = 0x00FF & self::_GetInt2d($subData, 6);\n\t\t\t$lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256;\n\t\t\t$lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex);\n\n\t\t\t// bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)\n\t\t\tif (!(0x4000 & self::_GetInt2d($subData, 6))) {\n\t\t\t\t// absolute column index\n\t\t\t\t$lc = PHPExcel_Cell::stringFromColumnIndex($lcIndex);\n\t\t\t\t$lc = '$' . $lc;\n\t\t\t} else {\n\t\t\t\t// column offset\n\t\t\t\t$lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256;\n\t\t\t\t$lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex);\n\t\t\t}\n\n\t\t\t// bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)\n\t\t\tif (!(0x8000 & self::_GetInt2d($subData, 6))) {\n\t\t\t\t// absolute row index\n\t\t\t\t$lr = $lrIndex + 1;\n\t\t\t\t$lr = '$' . $lr;\n\t\t\t} else {\n\t\t\t\t// row offset\n\t\t\t\t$lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536;\n\t\t\t\t$lr = $baseRow + $lrIndex;\n\t\t\t}\n\n\t\treturn \"$fc$fr:$lc$lr\";\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function getVariantsAction(\n Request $request,\n EventDispatcherInterface $eventDispatcher,\n GridHelperService $gridHelperService,\n LocaleServiceInterface $localeService,\n CsrfProtectionHandler $csrfProtection\n ): JsonResponse {\n $parentObject = DataObject\\Concrete::getById((int) $request->get('objectId'));\n if (empty($parentObject)) {\n throw new \\Exception('No Object found with id ' . $request->get('objectId'));\n }\n\n if (!$parentObject->isAllowed('view')) {\n throw new \\Exception('Permission denied');\n }\n\n $allParams = array_merge($request->request->all(), $request->query->all());\n $allParams['folderId'] = $parentObject->getId();\n $allParams['classId'] = $parentObject->getClassId();\n\n $csrfProtection->checkCsrfToken($request);\n\n $result = $this->gridProxy(\n $allParams,\n DataObject::OBJECT_TYPE_VARIANT,\n $request,\n $eventDispatcher,\n $gridHelperService,\n $localeService\n );\n\n return $this->adminJson($result);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $userId, string $email, string $password, string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Event $events) {\n $email = \\strtolower($email);\n if ('console' === $project->getId()) {\n $whitelistEmails = $project->getAttribute('authWhitelistEmails');\n $whitelistIPs = $project->getAttribute('authWhitelistIPs');\n\n if (!empty($whitelistEmails) && !\\in_array($email, $whitelistEmails) && !\\in_array(strtoupper($email), $whitelistEmails)) {\n throw new Exception(Exception::USER_EMAIL_NOT_WHITELISTED);\n }\n\n if (!empty($whitelistIPs) && !\\in_array($request->getIP(), $whitelistIPs)) {\n throw new Exception(Exception::USER_IP_NOT_WHITELISTED);\n }\n }\n\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0) {\n $total = $dbForProject->count('users', max: APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n throw new Exception(Exception::USER_COUNT_EXCEEDED);\n }\n }\n\n // Makes sure this email is not already used in another identity\n $identityWithMatchingEmail = $dbForProject->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n if ($identityWithMatchingEmail !== false && !$identityWithMatchingEmail->isEmpty()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) {\n $personalDataValidator = new PersonalData($userId, $email, $name, null);\n if (!$personalDataValidator->isValid($password)) {\n throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA);\n }\n }\n\n $passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;\n $password = Auth::passwordHash($password, Auth::DEFAULT_ALGO, Auth::DEFAULT_ALGO_OPTIONS);\n try {\n $userId = $userId == 'unique()' ? ID::unique() : $userId;\n $user->setAttributes([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => $email,\n 'emailVerification' => false,\n 'status' => true,\n 'password' => $password,\n 'passwordHistory' => $passwordHistory > 0 ? [$password] : [],\n 'passwordUpdate' => DateTime::now(),\n 'hash' => Auth::DEFAULT_ALGO,\n 'hashOptions' => Auth::DEFAULT_ALGO_OPTIONS,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'name' => $name,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => implode(' ', [$userId, $email, $name]),\n 'accessedAt' => DateTime::now(),\n ]);\n $user->removeAttribute('$internalId');\n Authorization::skip(fn() => $dbForProject->createDocument('users', $user));\n } catch (Duplicate) {\n throw new Exception(Exception::USER_ALREADY_EXISTS);\n }\n\n Authorization::unsetRole(Role::guests()->toString());\n Authorization::setRole(Role::user($user->getId())->toString());\n Authorization::setRole(Role::users()->toString());\n\n $events->setParam('userId', $user->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($user, Response::MODEL_ACCOUNT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function extract($filename)\n {\n if (!is_file($filename)) {\n throw new RuntimeException(sprintf('The file \"%s\" does not exist.', $filename));\n }\n $file = new SplFileInfo($filename);\n\n $extractor = $this->getExtractor();\n\n $catalogue = new MessageCatalogue();\n $extractor->visitFile($file, $catalogue);\n\n return $catalogue;\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function write(IProfile $profile): bool {\n\t\t$file = $this->getFilename($profile->getToken());\n\n\t\t$profileIndexed = is_file($file);\n\t\tif (!$profileIndexed) {\n\t\t\t// Create directory\n\t\t\t$dir = \\dirname($file);\n\t\t\tif (!is_dir($dir) && @mkdir($dir, 0777, true) === false && !is_dir($dir)) {\n\t\t\t\tthrow new \\RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));\n\t\t\t}\n\t\t}\n\n\t\t$profileToken = $profile->getToken();\n\t\t// when there are errors in sub-requests, the parent and/or children tokens\n\t\t// may equal the profile token, resulting in infinite loops\n\t\t$parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;\n\t\t$childrenToken = array_filter(array_map(function (IProfile $p) use ($profileToken) {\n\t\t\treturn $profileToken !== $p->getToken() ? $p->getToken() : null;\n\t\t}, $profile->getChildren()));\n\n\t\t// Store profile\n\t\t$data = [\n\t\t\t'token' => $profileToken,\n\t\t\t'parent' => $parentToken,\n\t\t\t'children' => $childrenToken,\n\t\t\t'data' => $profile->getCollectors(),\n\t\t\t'method' => $profile->getMethod(),\n\t\t\t'url' => $profile->getUrl(),\n\t\t\t'time' => $profile->getTime(),\n\t\t\t'status_code' => $profile->getStatusCode(),\n\t\t];\n\n\t\t$context = stream_context_create();\n\n\t\tif (\\function_exists('gzcompress')) {\n\t\t\t$file = 'compress.zlib://'.$file;\n\t\t\tstream_context_set_option($context, 'zlib', 'level', 3);\n\t\t}\n\n\t\tif (file_put_contents($file, serialize($data), 0, $context) === false) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!$profileIndexed) {\n\t\t\t// Add to index\n\t\t\tif (false === $file = fopen($this->getIndexFilename(), 'a')) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfputcsv($file, [\n\t\t\t\t$profile->getToken(),\n\t\t\t\t$profile->getMethod(),\n\t\t\t\t$profile->getUrl(),\n\t\t\t\t$profile->getTime(),\n\t\t\t\t$profile->getParentToken(),\n\t\t\t\t$profile->getStatusCode(),\n\t\t\t]);\n\t\t\tfclose($file);\n\t\t}\n\n\t\treturn true;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function preLoginNameUsedAsUserName($param) {\n\t\tif (!isset($param['uid'])) {\n\t\t\tthrow new \\Exception('key uid is expected to be set in $param');\n\t\t}\n\n\t\t$backends = \\OC::$server->getUserManager()->getBackends();\n\t\tforeach ($backends as $backend) {\n\t\t\tif ($backend instanceof Database) {\n\t\t\t\t/** @var \\OC\\User\\Database $backend */\n\t\t\t\t$uid = $backend->loginName2UserName($param['uid']);\n\t\t\t\tif ($uid !== false) {\n\t\t\t\t\t$param['uid'] = $uid;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function removeFromGroup($uid, $gid) {\n\t\t$plugin = $this->which[GroupInterface::REMOVE_FROM_GROUP];\n\n\t\tif ($plugin) {\n\t\t\treturn $plugin->removeFromGroup($uid, $gid);\n\t\t}\n\t\tthrow new \\Exception('No plugin implements removeFromGroup in this LDAP Backend.');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function downloadTemplate($template_file)\n {\n try {\n if ($template_file == null || $template_file == '') {\n $template_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'template.tpl';\n if (!file_exists($template_file)) {\n throw new \\Exception(\"Template example file not found\");\n }\n } else {\n $template_file = $this->checkTemplate($template_file);\n }\n\n header(CTYPE_HTML);\n $res = readfile($template_file);\n\n if (!$res) {\n throw new \\Exception(\"Cannot read template file \" . basename($template_file));\n }\n\n } catch (\\Exception $e) {\n print $e->getMessage();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function convertCriteria(\n string $fieldTypeIdentifier,\n QueryBuilder $outerQuery,\n QueryBuilder $subQuery,\n Criterion $criterion,\n string $column\n ) {\n if ($this->registry->has($fieldTypeIdentifier)) {\n return $this->registry->get($fieldTypeIdentifier)->handle(\n $outerQuery,\n $subQuery,\n $criterion,\n $column\n );\n }\n\n if ($this->defaultHandler === null) {\n throw new RuntimeException(\n \"No conversion for a Field Type '$fieldTypeIdentifier' found.\"\n );\n }\n\n return $this->defaultHandler->handle($outerQuery, $subQuery, $criterion, $column);\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function (string $databaseId, string $collectionId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n $collectionDocument = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n $collection = $dbForProject->getCollection('database_' . $database->getInternalId() . '_collection_' . $collectionDocument->getInternalId());\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n $grouped = Query::groupByType($queries);\n $limit = $grouped['limit'] ?? APP_LIMIT_COUNT;\n $offset = $grouped['offset'] ?? 0;\n\n $audit = new Audit($dbForProject);\n $resource = 'database/' . $databaseId . '/collection/' . $collectionId;\n $logs = $audit->getLogsByResource($resource, $limit, $offset);\n\n $output = [];\n\n foreach ($logs as $i => &$log) {\n $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN';\n\n $detector = new Detector($log['userAgent']);\n $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)\n\n $os = $detector->getOS();\n $client = $detector->getClient();\n $device = $detector->getDevice();\n\n $output[$i] = new Document([\n 'event' => $log['event'],\n 'userId' => $log['data']['userId'],\n 'userEmail' => $log['data']['userEmail'] ?? null,\n 'userName' => $log['data']['userName'] ?? null,\n 'mode' => $log['data']['mode'] ?? null,\n 'ip' => $log['ip'],\n 'time' => $log['time'],\n 'osCode' => $os['osCode'],\n 'osName' => $os['osName'],\n 'osVersion' => $os['osVersion'],\n 'clientType' => $client['clientType'],\n 'clientCode' => $client['clientCode'],\n 'clientName' => $client['clientName'],\n 'clientVersion' => $client['clientVersion'],\n 'clientEngine' => $client['clientEngine'],\n 'clientEngineVersion' => $client['clientEngineVersion'],\n 'deviceName' => $device['deviceName'],\n 'deviceBrand' => $device['deviceBrand'],\n 'deviceModel' => $device['deviceModel']\n ]);\n\n $record = $geodb->get($log['ip']);\n\n if ($record) {\n $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \\strtolower($record['country']['iso_code']) : '--';\n $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown'));\n } else {\n $output[$i]['countryCode'] = '--';\n $output[$i]['countryName'] = $locale->getText('locale.country.unknown');\n }\n }\n\n $response->dynamic(new Document([\n 'total' => $audit->countLogsByResource($resource),\n 'logs' => $output,\n ]), Response::MODEL_LOG_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function Load(&$row)\n {\n $fms = $this->_phreezer->GetFieldMaps(get_class($this));\n $this->_phreezer->Observe(\"Loading \" . get_class($this), OBSERVE_DEBUG);\n\n $this->IsLoaded(true); // assume true until fail occurs\n $this->IsPartiallyLoaded(false); // at least we tried\n\n // in order to prevent collisions on fields, QueryBuilder appends __tablename__rand to the\n // sql statement. We need to strip that out so we can match it up to the property names\n $rowlocal = array ();\n foreach ($row as $key => $val) {\n $info = explode(\"___\", $key);\n\n // we prefer to use tablename.colname if we have it, but if not\n // just use the colname\n $newkey = isset($info [1]) ? ($info [1] . \".\" . $info [0]) : $info [0];\n if (isset($rowlocal [$newkey])) {\n throw new Exception(\"The column `$newkey` was selected twice in the same query, causing a data collision\");\n }\n\n $rowlocal [$newkey] = $val;\n }\n\n foreach ($fms as $fm) {\n if (array_key_exists($fm->TableName . \".\" . $fm->ColumnName, $rowlocal)) {\n // first try to locate the field by tablename.colname\n $prop = $fm->PropertyName;\n $this->$prop = $rowlocal [$fm->TableName . \".\" . $fm->ColumnName];\n } elseif (array_key_exists($fm->ColumnName, $rowlocal)) {\n // if we can't locate the field by tablename.colname, then just look for colname\n $prop = $fm->PropertyName;\n $this->$prop = $rowlocal [$fm->ColumnName];\n } else {\n // there is a required column missing from this $row array - mark as partially loaded\n $this->_phreezer->Observe(\"Missing column '\" . $fm->ColumnName . \"' while loading \" . get_class($this), OBSERVE_WARN);\n $this->IsLoaded(false);\n $this->IsPartiallyLoaded(true);\n }\n }\n\n // now look for any eagerly loaded children - their fields should be available in this query\n $kms = $this->_phreezer->GetKeyMaps(get_class($this));\n\n foreach ($kms as $km) {\n if ($km->LoadType == KM_LOAD_EAGER || $km->LoadType == KM_LOAD_INNER) {\n // load the child object that was obtained eagerly and cache so we\n // won't ever grab the same object twice in one page load\n $this->_phreezer->IncludeModel($km->ForeignObject);\n $foclass = $km->ForeignObject;\n $fo = new $foclass($this->_phreezer, $row);\n\n $this->_phreezer->SetCache($foclass, $fo->GetPrimaryKeyValue(), $fo, $this->_phreezer->CacheQueryObjectLevel2);\n }\n }\n\n $this->_phreezer->Observe(\"Firing \" . get_class($this) . \"->OnLoad()\", OBSERVE_DEBUG);\n $this->OnLoad();\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function setDeviceType(string $type): void\n {\n $instance = self::$instance;\n if ($type == 'desktop') {\n $instance->isDesktop = true;\n $instance->isPhone = false;\n $instance->isTablet = false;\n } elseif ($type == 'tablet') {\n $instance->isTablet = true;\n $instance->isDesktop = false;\n $instance->isPhone = false;\n } elseif (in_array($type, ['mobile', 'phone'])) {\n $instance->isPhone = true;\n $instance->isDesktop = false;\n $instance->isTablet = false;\n } else {\n throw new Exception(sprintf('Unknown device \"%s\".', $type));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $functionId, string $executionId, Response $response, Database $dbForProject, string $mode) {\n $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($function->isEmpty() || (!$function->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $execution = $dbForProject->getDocument('executions', $executionId);\n\n if ($execution->getAttribute('functionId') !== $function->getId()) {\n throw new Exception(Exception::EXECUTION_NOT_FOUND);\n }\n\n if ($execution->isEmpty()) {\n throw new Exception(Exception::EXECUTION_NOT_FOUND);\n }\n\n $roles = Authorization::getRoles();\n $isPrivilegedUser = Auth::isPrivilegedUser($roles);\n $isAppUser = Auth::isAppUser($roles);\n if (!$isPrivilegedUser && !$isAppUser) {\n $execution->setAttribute('logs', '');\n $execution->setAttribute('errors', '');\n }\n\n $response->dynamic($execution, Response::MODEL_EXECUTION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function render($options=array()) {\n\n switch(strtolower($options['template'])) {\n case 'simple':\n $inc = STAFFINC_DIR . 'templates/dynamic-form-simple.tmpl.php';\n break;\n default:\n throw new Exception(sprintf(__('%s: Unknown template style %s'),\n 'FormUtils', $options['template']));\n }\n\n $form = $this;\n include $inc;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function updateVlResults($params)\n {\n $alertMsg = new Zend_Session_Namespace('alertSpace');\n if (!$this->isShipmentEditable($params['shipmentId'], $params['participantId']) && (!isset($params['reqAccessFrom']) || empty($params['reqAccessFrom']) || $params['reqAccessFrom'] != 'admin')) {\n $alertMsg->message = \"You are not allowed to update the response for this participant.\";\n return false;\n }\n\n $db = Zend_Db_Table_Abstract::getDefaultAdapter();\n\n $adminAuthNameSpace = new Zend_Session_Namespace('administrators');\n $authNameSpace = new Zend_Session_Namespace('datamanagers');\n $mandatoryFields = ['receiptDate', 'testDate', 'vlAssay'];\n\n $db->beginTransaction();\n try {\n\n $mandatoryCheckErrors = $this->mandatoryFieldsCheck($params, $mandatoryFields);\n if (!empty($mandatoryCheckErrors)) {\n\n $userAgent = $_SERVER['HTTP_USER_AGENT'];\n $commonService = new Application_Service_Common();\n\n // $ipAddress = $commonService->getIPAddress();\n // $operatingSystem = $commonService->getOperatingSystem($userAgent);\n // $browser = $commonService->getBrowser($userAgent);\n // //throw new Exception('Missed mandatory fields - ' . implode(\",\", $mandatoryCheckErrors));\n // error_log(date('Y-m-d H:i:s') . '|FORMERROR|Missed mandatory fields - ' . implode(\",\", $mandatoryCheckErrors) . '|' . $params['schemeCode'] . '|' . $params['participantId'] . '|' . $ipAddress . '|' . $operatingSystem . '|' . $browser . PHP_EOL, 3, DOWNLOADS_FOLDER . \" /../errors.log\");\n throw new Exception('Missed mandatory fields on the form');\n }\n $shipmentParticipantDb = new Application_Model_DbTable_ShipmentParticipantMap();\n if (isset($params['sampleRehydrationDate']) && trim($params['sampleRehydrationDate']) != \"\") {\n $params['sampleRehydrationDate'] = Pt_Commons_General::isoDateFormat($params['sampleRehydrationDate']);\n }\n if (isset($params['assayExpirationDate']) && trim($params['assayExpirationDate']) != \"\") {\n $params['assayExpirationDate'] = Pt_Commons_General::isoDateFormat($params['assayExpirationDate']);\n }\n\n $attributes = [\n \"sample_rehydration_date\" => (isset($params['sampleRehydrationDate']) && !empty($params['sampleRehydrationDate'])) ? $params['sampleRehydrationDate'] : '',\n \"vl_assay\" => (isset($params['vlAssay']) && !empty($params['vlAssay'])) ? (int) $params['vlAssay'] : '',\n \"assay_lot_number\" => (isset($params['assayLotNumber']) && !empty($params['assayLotNumber'])) ? $params['assayLotNumber'] : '',\n \"assay_expiration_date\" => (isset($params['assayExpirationDate']) && !empty($params['assayExpirationDate'])) ? $params['assayExpirationDate'] : '',\n \"specimen_volume\" => (isset($params['specimenVolume']) && !empty($params['specimenVolume'])) ? $params['specimenVolume'] : '',\n \"date_of_xpert_instrument_calibration\" => (isset($params['geneXpertInstrument']) && !empty($params['geneXpertInstrument'])) ? $params['geneXpertInstrument'] : \"\",\n \"instrument_sn\" => (isset($params['instrumentSn']) && !empty($params['instrumentSn'])) ? $params['instrumentSn'] : \"\",\n \"uploaded_file\" => (isset($params['uploadedFilePath']) && !empty($params['uploadedFilePath'])) ? $params['uploadedFilePath'] : ''\n ];\n\n if (isset($params['otherAssay']) && $params['otherAssay'] != \"\") {\n $attributes['other_assay'] = htmlentities($params['otherAssay']);\n }\n if (isset($params['extraction']) && $params['extraction'] != \"\" && $params['platformType'] == 'htp') {\n $attributes['extraction'] = $params['extraction'];\n } else {\n $attributes['extraction'] = null;\n }\n if (isset($params['amplification']) && $params['amplification'] != \"\" && $params['platformType'] == 'htp') {\n $attributes['amplification'] = $params['amplification'];\n } else {\n $attributes['amplification'] = null;\n }\n\n if (!isset($params['modeOfReceipt'])) {\n $params['modeOfReceipt'] = null;\n }\n $attributes = Zend_Json::encode($attributes);\n $responseStatus = \"responded\";\n // if ($params['isPtTestNotPerformed'] == \"yes\") {\n // $responseStatus = \"nottested\";\n // }\n $data = array(\n \"shipment_receipt_date\" => Pt_Commons_General::isoDateFormat($params['receiptDate']),\n \"shipment_test_date\" => Pt_Commons_General::isoDateFormat($params['testDate']),\n \"attributes\" => $attributes,\n \"supervisor_approval\" => $params['supervisorApproval'],\n \"participant_supervisor\" => $params['participantSupervisor'],\n \"user_comment\" => $params['userComments'],\n \"mode_id\" => $params['modeOfReceipt'],\n \"response_status\" => $responseStatus,\n );\n if (!empty($authNameSpace->dm_id)) {\n $data[\"updated_by_user\"] = $authNameSpace->dm_id ?? null;\n $data[\"updated_on_user\"] = new Zend_Db_Expr('now()');\n } elseif (!empty($adminAuthNameSpace->admin_id)) {\n $data[\"updated_by_admin\"] = $adminAuthNameSpace->admin_id ?? null;\n $data[\"updated_on_admin\"] = new Zend_Db_Expr('now()');\n }\n\n if (isset($params['testReceiptDate']) && trim($params['testReceiptDate']) != '' && $responseStatus == 'responded') {\n $data['shipment_test_report_date'] = Pt_Commons_General::isoDateFormat($params['testReceiptDate']);\n } else {\n $data['shipment_test_report_date'] = new Zend_Db_Expr('now()');\n }\n\n if (!empty($params['isPtTestNotPerformed']) && $params['isPtTestNotPerformed'] == 'yes') {\n $data['is_pt_test_not_performed'] = 'yes';\n // $data['shipment_test_date'] = null;\n $data['vl_not_tested_reason'] = $params['vlNotTestedReason'];\n $data['pt_test_not_performed_comments'] = $params['ptNotTestedComments'];\n $data['pt_support_comments'] = $params['ptSupportComments'];\n } else {\n $data['is_pt_test_not_performed'] = null;\n $data['vl_not_tested_reason'] = null;\n $data['pt_test_not_performed_comments'] = null;\n $data['pt_support_comments'] = null;\n }\n\n if (isset($authNameSpace->qc_access) && $authNameSpace->qc_access == 'yes') {\n $data['qc_done'] = $params['qcDone'] ?? 'no';\n if (isset($data['qc_done']) && trim($data['qc_done']) == \"yes\") {\n $data['qc_date'] = Pt_Commons_General::isoDateFormat($params['qcDate']);\n $data['qc_done_by'] = trim($params['qcDoneBy']);\n $data['qc_created_on'] = new Zend_Db_Expr('now()');\n } else {\n $data['qc_date'] = null;\n $data['qc_done_by'] = null;\n $data['qc_created_on'] = null;\n }\n }\n if (isset($params['labDirectorName']) && $params['labDirectorName'] != \"\") {\n $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();\n /* Shipment Participant table updation */\n $dbAdapter->update(\n 'shipment_participant_map',\n array(\n 'lab_director_name' => $params['labDirectorName'],\n 'lab_director_email' => $params['labDirectorEmail'],\n 'contact_person_name' => $params['contactPersonName'],\n 'contact_person_email' => $params['contactPersonEmail'],\n 'contact_person_telephone' => $params['contactPersonTelephone']\n ),\n 'map_id = ' . $params['smid']\n );\n /* Participant table updation */\n $dbAdapter->update(\n 'participant',\n array(\n 'lab_director_name' => $params['labDirectorName'],\n 'lab_director_email' => $params['labDirectorEmail'],\n 'contact_person_name' => $params['contactPersonName'],\n 'contact_person_email' => $params['contactPersonEmail'],\n 'contact_person_telephone' => $params['contactPersonTelephone']\n ),\n 'participant_id = ' . $params['participantId']\n );\n }\n $noOfRowsAffected = $shipmentParticipantDb->updateShipment($data, $params['smid'], $params['hdLastDate']);\n\n $vlResponseDb = new Application_Model_DbTable_ResponseVl();\n $vlResponseDb->updateResults($params);\n $this->saveAdminData($params);\n $db->commit();\n\n if (isset($params['reqAccessFrom']) && !empty($params['reqAccessFrom']) && $params['reqAccessFrom'] == 'admin') {\n $alertMsg->message = \"Updated Successfully\";\n } else {\n $alertMsg->message = \"Thank you for submitting your result. We have received it and the PT Results will be published on or after the due date\";\n }\n } catch (Exception $e) {\n // If any of the queries failed and threw an exception,\n // we want to roll back the whole transaction, reversing\n // changes made in the transaction, even those that succeeded.\n // Thus all changes are committed together, or none are.\n $db->rollBack();\n $alertMsg->message = \"Sorry we could not record your result. Please try again or contact the PT adminstrator\";\n error_log($e->getMessage());\n }\n }", "smellKey": "S112", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public function dumpPHPClasses(ClassDefinition $classDefinition): void\n {\n $classFilePath = $classDefinition->getPhpClassFile();\n $phpClass = $this->classBuilder->buildClass($classDefinition);\n\n $this->filesystem->dumpFile($classFilePath, $phpClass);\n if (!file_exists($classFilePath)) {\n throw new Exception(sprintf('Cannot write class file in %s please check the rights on this directory', $classFilePath));\n }\n\n $listingClassFilePath = $classDefinition->getPhpListingClassFile();\n $listingPhpClass = $this->listingClassBuilder->buildListingClass($classDefinition);\n\n $this->filesystem->dumpFile($listingClassFilePath, $listingPhpClass);\n if (!file_exists($listingClassFilePath)) {\n throw new Exception(\n sprintf('Cannot write class file in %s please check the rights on this directory', $listingClassFilePath)\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function fixSession() {\n if ($this->isEnabled()) {\n return;\n }\n\n $sessionName = session_name();\n $arrays = [&$_GET, &$_POST, &$_COOKIE];\n foreach ($arrays as $k => $arr) {\n if (isset($arrays[$k][$sessionName]) && strlen($arrays[$k][$sessionName]) > 32) {\n switch ($this->actionOnCorruptedId) {\n case self::ACTION_EXCEPTION:\n throw new \\Exception(\"Invalid session id\");\n\n case self::ACTION_HTTP_EXCEPTION:\n unset($arrays[$k][$sessionName]);\n throw new HttpException(\"Invalid session id. Recreated id.\", 400, null, \"Bad request\");\n\n default:\n unset($arrays[$k][$sessionName]);\n }\n }\n }\n\n if (PHP_SESSION_NONE === session_status()) {\n try {\n session_start();\n\n } catch (\\Exception $e) {\n switch ($this->actionOnCorruptedId) {\n case self::ACTION_EXCEPTION:\n throw new \\Exception(\"Invalid session id\");\n\n case self::ACTION_HTTP_EXCEPTION:\n throw new HttpException(\"Invalid session id. Recreated id.\", 400, null, \"Bad request\");\n\n default:\n session_start();\n }\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "dit21123_hackazon", "language": "php"} {"function": "public function write($string): int\n {\n if (!isset($this->stream)) {\n throw new \\RuntimeException('Stream is detached');\n }\n if (!$this->writable) {\n throw new \\RuntimeException('Cannot write to a non-writable stream');\n }\n\n // We can't know the size after writing anything\n $this->size = null;\n $result = fwrite($this->stream, $string);\n\n if ($result === false) {\n throw new \\RuntimeException('Unable to write to stream');\n }\n\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function gridMarkFavouriteColumnConfigAction(Request $request): JsonResponse\n {\n $objectId = (int)$request->get('objectId');\n $object = DataObject::getById($objectId);\n\n if ($object->isAllowed('list')) {\n $classId = $request->get('classId');\n $gridConfigId = $request->get('gridConfigId');\n $searchType = $request->get('searchType');\n $global = $request->get('global');\n $user = $this->getAdminUser();\n $type = $request->get('type');\n\n $favourite = new GridConfigFavourite();\n $favourite->setOwnerId($user->getId());\n $class = DataObject\\ClassDefinition::getById($classId);\n if (!$class) {\n throw new \\Exception('class ' . $classId . ' does not exist anymore');\n }\n $favourite->setClassId($classId);\n $favourite->setSearchType($searchType);\n $favourite->setType($type);\n $specializedConfigs = false;\n\n try {\n if ($gridConfigId != 0) {\n $gridConfig = GridConfig::getById((int)$gridConfigId);\n $favourite->setGridConfigId($gridConfig->getId());\n }\n $favourite->setObjectId($objectId);\n $favourite->save();\n\n if ($global) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n $db = Db::get();\n $count = $db->fetchOne('select * from gridconfig_favourites where '\n . 'ownerId = ' . $user->getId()\n . ' and classId = ' . $db->quote($classId).\n ' and searchType = ' . $db->quote($searchType)\n . ' and objectId != ' . $objectId . ' and objectId != 0'\n . ' and `type` != ' . $db->quote($type));\n $specializedConfigs = $count > 0;\n } catch (\\Exception $e) {\n $favourite->delete();\n }\n\n return $this->adminJson(['success' => true, 'spezializedConfigs' => $specializedConfigs]);\n }\n\n throw $this->createAccessDeniedHttpException();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "protected function processSource(string $source, array $credentials): Source\n {\n switch ($source) {\n case Firebase::getName():\n return new Firebase(\n json_decode($credentials['serviceAccount'], true),\n );\n break;\n case Supabase::getName():\n return new Supabase(\n $credentials['endpoint'],\n $credentials['apiKey'],\n $credentials['databaseHost'],\n 'postgres',\n $credentials['username'],\n $credentials['password'],\n $credentials['port'],\n );\n break;\n case NHost::getName():\n return new NHost(\n $credentials['subdomain'],\n $credentials['region'],\n $credentials['adminSecret'],\n $credentials['database'],\n $credentials['username'],\n $credentials['password'],\n $credentials['port'],\n );\n break;\n case Appwrite::getName():\n return new Appwrite($credentials['projectId'], str_starts_with($credentials['endpoint'], 'http://localhost/v1') ? 'http://appwrite/v1' : $credentials['endpoint'], $credentials['apiKey']);\n break;\n default:\n throw new \\Exception('Invalid source type');\n break;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function assertDownloadLimitNotExceeded(array $contentIdList): void\n {\n if (count($contentIdList) > $this->downloadLimit) {\n throw new RuntimeException(\n sprintf(\n 'Total download limit in one request is %d.',\n $this->downloadLimit\n )\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function ($password) use ($io) {\n if ($password === null) {\n throw new Exception('The password cannot be empty');\n }\n\n $repeatQuestion = new Question('Repeat the password');\n $repeatQuestion->setHidden(true);\n $repeatQuestion->setHiddenFallback(false);\n $repeatQuestion->setValidator(function ($repeatedPassword) use ($password) {\n if ($repeatedPassword !== $password) {\n throw new Exception('Passwords do not match');\n }\n\n return $repeatedPassword;\n });\n $repeatQuestion->setMaxAttempts(1);\n\n return $io->askQuestion($repeatQuestion);\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (string $bucketId, array $queries, string $search, Response $response, Database $dbForProject, string $mode) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_READ);\n $valid = $validator->isValid($bucket->getRead());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n $queries = Query::parseQueries($queries);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $fileId = $cursor->getValue();\n\n if ($fileSecurity && !$valid) {\n $cursorDocument = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);\n } else {\n $cursorDocument = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n }\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"File '{$fileId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n if ($fileSecurity && !$valid) {\n $files = $dbForProject->find('bucket_' . $bucket->getInternalId(), $queries);\n $total = $dbForProject->count('bucket_' . $bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT);\n } else {\n $files = Authorization::skip(fn () => $dbForProject->find('bucket_' . $bucket->getInternalId(), $queries));\n $total = Authorization::skip(fn () => $dbForProject->count('bucket_' . $bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT));\n }\n\n $response->dynamic(new Document([\n 'files' => $files,\n 'total' => $total,\n ]), Response::MODEL_FILE_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function _processBitmap($bitmap)\n\t{\n\t\t// Open file.\n\t\t$bmp_fd = @fopen($bitmap,\"rb\");\n\t\tif (!$bmp_fd) {\n\t\t\tthrow new Exception(\"Couldn't import $bitmap\");\n\t\t}\n\n\t\t// Slurp the file into a string.\n\t\t$data = fread($bmp_fd, filesize($bitmap));\n\n\t\t// Check that the file is big enough to be a bitmap.\n\t\tif (strlen($data) <= 0x36) {\n\t\t\tthrow new Exception(\"$bitmap doesn't contain enough data.\\n\");\n\t\t}\n\n\t\t// The first 2 bytes are used to identify the bitmap.\n\t\t$identity = unpack(\"A2ident\", $data);\n\t\tif ($identity['ident'] != \"BM\") {\n\t\t\tthrow new Exception(\"$bitmap doesn't appear to be a valid bitmap image.\\n\");\n\t\t}\n\n\t\t// Remove bitmap data: ID.\n\t\t$data = substr($data, 2);\n\n\t\t// Read and remove the bitmap size. This is more reliable than reading\n\t\t// the data size at offset 0x22.\n\t\t//\n\t\t$size_array = unpack(\"Vsa\", substr($data, 0, 4));\n\t\t$size = $size_array['sa'];\n\t\t$data = substr($data, 4);\n\t\t$size -= 0x36; // Subtract size of bitmap header.\n\t\t$size += 0x0C; // Add size of BIFF header.\n\n\t\t// Remove bitmap data: reserved, offset, header length.\n\t\t$data = substr($data, 12);\n\n\t\t// Read and remove the bitmap width and height. Verify the sizes.\n\t\t$width_and_height = unpack(\"V2\", substr($data, 0, 8));\n\t\t$width = $width_and_height[1];\n\t\t$height = $width_and_height[2];\n\t\t$data = substr($data, 8);\n\t\tif ($width > 0xFFFF) {\n\t\t\tthrow new Exception(\"$bitmap: largest image width supported is 65k.\\n\");\n\t\t}\n\t\tif ($height > 0xFFFF) {\n\t\t\tthrow new Exception(\"$bitmap: largest image height supported is 65k.\\n\");\n\t\t}\n\n\t\t// Read and remove the bitmap planes and bpp data. Verify them.\n\t\t$planes_and_bitcount = unpack(\"v2\", substr($data, 0, 4));\n\t\t$data = substr($data, 4);\n\t\tif ($planes_and_bitcount[2] != 24) { // Bitcount\n\t\t\tthrow new Exception(\"$bitmap isn't a 24bit true color bitmap.\\n\");\n\t\t}\n\t\tif ($planes_and_bitcount[1] != 1) {\n\t\t\tthrow new Exception(\"$bitmap: only 1 plane supported in bitmap image.\\n\");\n\t\t}\n\n\t\t// Read and remove the bitmap compression. Verify compression.\n\t\t$compression = unpack(\"Vcomp\", substr($data, 0, 4));\n\t\t$data = substr($data, 4);\n\n\t\t//$compression = 0;\n\t\tif ($compression['comp'] != 0) {\n\t\t\tthrow new Exception(\"$bitmap: compression not supported in bitmap image.\\n\");\n\t\t}\n\n\t\t// Remove bitmap data: data size, hres, vres, colours, imp. colours.\n\t\t$data = substr($data, 20);\n\n\t\t// Add the BITMAPCOREHEADER data\n\t\t$header = pack(\"Vvvvv\", 0x000c, $width, $height, 0x01, 0x18);\n\t\t$data\t= $header . $data;\n\n\t\treturn (array($width, $height, $size, $data));\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function action(string $version, string $mode, Registry $register): void\n {\n $appRoutes = App::getRoutes();\n $response = new Response(new HttpResponse());\n $mocks = ($mode === 'mocks');\n\n // Mock dependencies\n App::setResource('request', fn () => new Request());\n App::setResource('response', fn () => $response);\n App::setResource('dbForConsole', fn () => new Database(new MySQL(''), new Cache(new None())));\n App::setResource('dbForProject', fn () => new Database(new MySQL(''), new Cache(new None())));\n\n $platforms = [\n 'client' => APP_PLATFORM_CLIENT,\n 'server' => APP_PLATFORM_SERVER,\n 'console' => APP_PLATFORM_CONSOLE,\n ];\n\n $authCounts = [\n 'client' => 1,\n 'server' => 2,\n 'console' => 1,\n ];\n\n $keys = [\n APP_PLATFORM_CLIENT => [\n 'Project' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Project',\n 'description' => 'Your project ID',\n 'in' => 'header',\n ],\n 'JWT' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-JWT',\n 'description' => 'Your secret JSON Web Token',\n 'in' => 'header',\n ],\n 'Locale' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Locale',\n 'description' => '',\n 'in' => 'header',\n ],\n ],\n APP_PLATFORM_SERVER => [\n 'Project' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Project',\n 'description' => 'Your project ID',\n 'in' => 'header',\n ],\n 'Key' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Key',\n 'description' => 'Your secret API key',\n 'in' => 'header',\n ],\n 'JWT' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-JWT',\n 'description' => 'Your secret JSON Web Token',\n 'in' => 'header',\n ],\n 'Locale' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Locale',\n 'description' => '',\n 'in' => 'header',\n ],\n ],\n APP_PLATFORM_CONSOLE => [\n 'Project' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Project',\n 'description' => 'Your project ID',\n 'in' => 'header',\n ],\n 'Key' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Key',\n 'description' => 'Your secret API key',\n 'in' => 'header',\n ],\n 'JWT' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-JWT',\n 'description' => 'Your secret JSON Web Token',\n 'in' => 'header',\n ],\n 'Locale' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Locale',\n 'description' => '',\n 'in' => 'header',\n ],\n 'Mode' => [\n 'type' => 'apiKey',\n 'name' => 'X-Appwrite-Mode',\n 'description' => '',\n 'in' => 'header',\n ],\n ],\n ];\n\n foreach ($platforms as $platform) {\n $routes = [];\n $models = [];\n $services = [];\n\n foreach ($appRoutes as $key => $method) {\n foreach ($method as $route) {\n /** @var \\Utopia\\Route $route */\n $routeSecurity = $route->getLabel('sdk.auth', []);\n $sdkPlaforms = [];\n\n foreach ($routeSecurity as $value) {\n switch ($value) {\n case APP_AUTH_TYPE_SESSION:\n $sdkPlaforms[] = APP_PLATFORM_CLIENT;\n break;\n case APP_AUTH_TYPE_KEY:\n $sdkPlaforms[] = APP_PLATFORM_SERVER;\n break;\n case APP_AUTH_TYPE_JWT:\n $sdkPlaforms[] = APP_PLATFORM_SERVER;\n break;\n case APP_AUTH_TYPE_ADMIN:\n $sdkPlaforms[] = APP_PLATFORM_CONSOLE;\n break;\n }\n }\n\n if (empty($routeSecurity)) {\n $sdkPlaforms[] = APP_PLATFORM_CLIENT;\n }\n\n if (!$route->getLabel('docs', true)) {\n continue;\n }\n\n if ($route->getLabel('sdk.mock', false) && !$mocks) {\n continue;\n }\n\n if (!$route->getLabel('sdk.mock', false) && $mocks) {\n continue;\n }\n\n if (empty($route->getLabel('sdk.namespace', null))) {\n continue;\n }\n\n if ($platform !== APP_PLATFORM_CONSOLE && !\\in_array($platforms[$platform], $sdkPlaforms)) {\n continue;\n }\n\n $routes[] = $route;\n }\n }\n\n foreach (Config::getParam('services', []) as $service) {\n if (\n !isset($service['docs']) // Skip service if not part of the public API\n || !isset($service['sdk'])\n || !$service['docs']\n || !$service['sdk']\n ) {\n continue;\n }\n\n $services[] = [\n 'name' => $service['key'] ?? '',\n 'description' => $service['subtitle'] ?? '',\n 'x-globalAttributes' => $service['globalAttributes'] ?? [],\n ];\n }\n\n $models = $response->getModels();\n\n foreach ($models as $key => $value) {\n if ($platform !== APP_PLATFORM_CONSOLE && !$value->isPublic()) {\n unset($models[$key]);\n }\n }\n\n $arguments = [new App('UTC'), $services, $routes, $models, $keys[$platform], $authCounts[$platform] ?? 0];\n foreach (['swagger2', 'open-api3'] as $format) {\n $formatInstance = match ($format) {\n 'swagger2' => new Swagger2(...$arguments),\n 'open-api3' => new OpenAPI3(...$arguments),\n default => throw new Exception('Format not found: ' . $format)\n };\n\n $specs = new Specification($formatInstance);\n $endpoint = App::getEnv('_APP_HOME', '[HOSTNAME]');\n $email = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);\n\n $formatInstance\n ->setParam('name', APP_NAME)\n ->setParam('description', 'Appwrite backend as a service cuts up to 70% of the time and costs required for building a modern application. We abstract and simplify common development tasks behind a REST APIs, to help you develop your app in a fast and secure way. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)')\n ->setParam('endpoint', 'https://HOSTNAME/v1')\n ->setParam('version', APP_VERSION_STABLE)\n ->setParam('terms', $endpoint . '/policy/terms')\n ->setParam('support.email', $email)\n ->setParam('support.url', $endpoint . '/support')\n ->setParam('contact.name', APP_NAME . ' Team')\n ->setParam('contact.email', $email)\n ->setParam('contact.url', $endpoint . '/support')\n ->setParam('license.name', 'BSD-3-Clause')\n ->setParam('license.url', 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE')\n ->setParam('docs.description', 'Full API docs, specs and tutorials')\n ->setParam('docs.url', $endpoint . '/docs');\n\n if ($mocks) {\n $path = __DIR__ . '/../../../../app/config/specs/' . $format . '-mocks-' . $platform . '.json';\n\n if (!file_put_contents($path, json_encode($specs->parse()))) {\n throw new Exception('Failed to save mocks spec file: ' . $path);\n }\n\n Console::success('Saved mocks spec file: ' . realpath($path));\n\n continue;\n }\n\n $path = __DIR__ . '/../../../../app/config/specs/' . $format . '-' . $version . '-' . $platform . '.json';\n\n if (!file_put_contents($path, json_encode($specs->parse()))) {\n throw new Exception('Failed to save spec file: ' . $path);\n }\n\n Console::success('Saved spec file: ' . realpath($path));\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $bucketId, Response $response, Database $dbForProject, Delete $deletes, Event $events) {\n $bucket = $dbForProject->getDocument('buckets', $bucketId);\n\n if ($bucket->isEmpty()) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n if (!$dbForProject->deleteDocument('buckets', $bucketId)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove bucket from DB');\n }\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($bucket);\n\n $events\n ->setParam('bucketId', $bucket->getId())\n ->setPayload($response->output($bucket, Response::MODEL_BUCKET))\n ;\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function createTable($system, $table_name, $query, $recreate = false){\n\n $mysqli = $system->getMysqli();\n\n if($recreate || !hasTable($mysqli, $table_name)){\n\n $res = $mysqli->query('DROP TABLE IF EXISTS '.$table_name);\n\n $res = $mysqli->query($query);\n if(!$res){\n $msg = \"Cannot create $table_name\";\n $system->addError(HEURIST_DB_ERROR, $msg, $mysqli->error);\n throw new Exception($msg);\n }\n $res = array(true, \"$table_name created\");\n }else{\n $res = array(false, \"$table_name already exists\");\n }\n return $res;\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function alterTable($system, $table_name, $field_name, $query, $modify_if_exists = false){\n\n $mysqli = $system->getMysqli();\n\n $column_exists = hasColumn($mysqli, $table_name, $field_name);\n\n $rep1 = 'add';\n $rep2 = 'added';\n\n if($column_exists && $modify_if_exists){\n $query = str_replace('ADD COLUMN','MODIFY',$query);\n if(stripos($query,' AFTER `')>0){\n $query = stristr($query,' AFTER `',true);\n }\n $column_exists = false;\n $rep1 = 'alter';\n $rep2 = 'altered';\n }\n\n if(!$column_exists){ //column not defined\n $res = $mysqli->query($query);\n if(!$res){\n $msg = \"Can not $rep1 field $field_name to $table_name\";\n $system->addError(HEURIST_DB_ERROR, $msg, $mysqli->error);\n throw new Exception($msg);\n }\n $res = array(true, \"$table_name: $field_name $rep2\");\n }else{\n $res = array(false, \"$table_name: $field_name already exists\");\n }\n\n return $res;\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public static function bunzip2($in, $out)\n {\n if (!file_exists ($in) || !is_readable ($in)){\n throw new \\Exception('Archive file doesn\\'t exists');\n }\n\n if (!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ){\n throw new \\Exception('Destination folder or file is not writeable');\n }\n\n $in_file = bzopen ($in, \"r\");\n $out_file = fopen ($out, \"wb\");\n\n while ($buffer = bzread ($in_file, 4096)) {\n fwrite ($out_file, $buffer, 4096);\n }\n\n bzclose ($in_file);\n fclose ($out_file);\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function (string $installationId, string $providerRepositoryId, string $providerRootDirectory, GitHub $github, Response $response, Document $project, Database $dbForConsole) {\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if ($installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n $providerInstallationId = $installation->getAttribute('providerInstallationId');\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n\n $owner = $github->getOwnerName($providerInstallationId);\n $repositoryName = $github->getRepositoryName($providerRepositoryId);\n\n if (empty($repositoryName)) {\n throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);\n }\n\n $files = $github->listRepositoryContents($owner, $repositoryName, $providerRootDirectory);\n $languages = $github->listRepositoryLanguages($owner, $repositoryName);\n\n $detectorFactory = new Detector($files, $languages);\n\n $detectorFactory\n ->addDetector(new JavaScript())\n ->addDetector(new Bun())\n ->addDetector(new PHP())\n ->addDetector(new Python())\n ->addDetector(new Dart())\n ->addDetector(new Swift())\n ->addDetector(new Ruby())\n ->addDetector(new Java())\n ->addDetector(new CPP())\n ->addDetector(new Deno())\n ->addDetector(new Dotnet());\n\n $runtime = $detectorFactory->detect();\n\n $runtimes = Config::getParam('runtimes');\n $runtimeDetail = \\array_reverse(\\array_filter(\\array_keys($runtimes), function ($key) use ($runtime, $runtimes) {\n return $runtimes[$key]['key'] === $runtime;\n }))[0] ?? '';\n\n $detection = [];\n $detection['runtime'] = $runtimeDetail;\n\n $response->dynamic(new Document($detection), Response::MODEL_DETECTION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function getDataForQueryResource(mixed $data, DataObject\\Concrete $object = null, array $params = []): ?string\n {\n //return null when data is not set\n if (!$data) {\n return null;\n }\n\n $d = [];\n\n if (is_array($data)) {\n foreach ($data as $metaObject) {\n $element = $metaObject->getElement();\n if ($element instanceof Element\\ElementInterface) {\n $elementType = Element\\Service::getElementType($element);\n $d[] = $elementType . '|' . $element->getId();\n }\n }\n\n return ',' . implode(',', $d) . ',';\n }\n\n throw new Exception('invalid data passed to getDataForQueryResource - must be array');\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getCriterion(APILimitationValue $value, APIUserReference $currentUser)\n {\n if (empty($value->limitationValues)) {\n // A Policy should not have empty limitationValues stored\n throw new \\RuntimeException('$value->limitationValues is empty');\n }\n\n if (!isset($value->limitationValues[1])) {\n // 1 limitation value: EQ operation\n return new Criterion\\SectionId($value->limitationValues[0]);\n }\n\n // several limitation values: IN operation\n return new Criterion\\SectionId($value->limitationValues);\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function has_role($role) {\n if ($this->role_driver == null)\n throw new \\Exception(\"No role configuration is present.\");\n\n if ($this->user == null)\n return false;\n\n return $this->role_driver->has_role($this->user, $role);\n }", "smellKey": "S112", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "public function saveQuestionnaireResource($q, $name = null, $q_record_id = null, $q_id = null, $lform = null, $type = null)\n {\n $type = $type ?? 'Questionnaire';\n $id = 0;\n $fhir_ob = null;\n if (is_string($q)) {\n $q = json_decode($q, true);\n $is_json = json_last_error() === JSON_ERROR_NONE;\n if (!$is_json) {\n throw new Exception(xlt(\"Questionnaire json is invalid\"));\n }\n }\n $fhir_ob = new FHIRQuestionnaire($q);\n $q_ob = $this->fhirObjectToArray($fhir_ob);\n\n if (empty($q_id)) {\n if (!empty($q_ob['id'])) {\n $q_id = $q_ob['id'];\n }\n }\n\n $name = $name ?: ($q_ob['title'] ?? null);\n if (empty($name)) {\n $name = $q_ob['name'] ?? null;\n }\n $name = trim($name);\n if (empty($q_record_id)) {\n $id = $this->getQuestionnaireIdAndVersion($name, $q_id);\n } else {\n $id = $q_record_id;\n }\n if (empty($id)) {\n $q_uuid = (new UuidRegistry(['table_name' => 'questionnaire_repository']))->createUuid();\n $q_id = UuidRegistry::uuidToString($q_uuid);\n $serverConfig = new ServerConfig();\n $fhirUrl = $serverConfig->getFhirUrl();\n // make sure we always have a slash at the end for our url\n if (!empty($fhirUrl) && $fhirUrl[strlen($fhirUrl) - 1] != '/') {\n $fhirUrl .= '/';\n }\n $q_url = $fhirUrl . 'Questionnaire/' . $q_id;\n $fhir_ob->setId(new FHIRId($q_id));\n $fhir_ob->setUrl(new FHIRUri($q_url));\n $fhir_ob->setTitle(new FHIRString($name));\n $fhir_ob->setName(new FHIRString(strtolower(str_replace(' ', '', $name))));\n }\n\n $q_version = $q_ob['meta']['versionId'] ?? 1;\n $q_last_date = $q_ob['meta']['lastUpdated'] ?? null;\n $q_profile = $q_ob['meta']['profile'][0] ?? null;\n $q_status = $q_ob['status'] == 'draft' ? 'active' : $q_ob['status'];\n $q_code = $q_ob[\"code\"][0]['code'] ?? null;\n $q_display = $q_ob['code'][0]['display'] ?? null;\n\n $content = $this->jsonSerialize($fhir_ob);\n $bind = array(\n $q_uuid,\n $q_id,\n $_SESSION['authUserID'],\n $q_version,\n $q_last_date,\n $name,\n $type,\n $q_profile,\n $q_status,\n $q_url,\n $q_code,\n $q_display,\n $content,\n $lform\n );\n\n $sql_insert = \"INSERT INTO `questionnaire_repository` (`id`, `uuid`, `questionnaire_id`, `provider`, `version`, `created_date`, `modified_date`, `name`, `type`, `profile`, `active`, `status`, `source_url`, `code`, `code_display`, `questionnaire`, `lform`) VALUES (NULL, ?, ?, ?, ?, current_timestamp(), ?, ?, ?, ?, '1', ?, ?, ?, ?, ?, ?)\";\n $sql_update = \"UPDATE `questionnaire_repository` SET `provider` = ?,`version` = ?, `modified_date` = ?, `name` = ?, `type` = ?, `profile` = ?, `status` = ?, `code` = ?, `code_display` = ?, `questionnaire` = ?, `lform` = ? WHERE `questionnaire_repository`.`id` = ?\";\n\n if (!empty($id)) {\n $version_update = (int)$id['version'] + 1;\n $bind = array(\n $_SESSION['authUserID'],\n $version_update,\n date(\"Y-m-d H:i:s\"),\n $name,\n $type,\n $q_profile,\n $q_status,\n $q_code,\n $q_display,\n $content,\n $lform,\n $id['id']\n );\n sqlInsert($sql_update, $bind);\n $id = $id['id'];\n } else {\n $id = sqlInsert($sql_insert, $bind) ?: 0;\n }\n\n return $id;\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function shredLine($line)\n {\n $this->logger->debug(\"Shredding line '$line'\");\n\n $date = $node = $type = null;\n\n $job = array();\n\n if (preg_match(self::$linePattern, $line, $matches)) {\n $date = preg_replace(\n '#^(\\d{2})/(\\d{2})/(\\d{4})$#',\n '$3-$1-$2',\n $matches[1]\n );\n\n $type = $matches[3];\n $jobId = $matches[4];\n $params = $matches[5];\n } else {\n throw new Exception(\"Malformed PBS accounting line: '$line'\");\n }\n\n // Ignore all non-\"end\" events.\n if ($type != 'E') {\n $this->logger->debug(\"Ignoring event type '$type'\");\n return;\n }\n\n $jobIdData = $this->getJobId($jobId);\n $job['job_id'] = $jobIdData['job_id'];\n if ($jobIdData['job_array_index'] !== null) {\n $job['job_array_index'] = $jobIdData['job_array_index'];\n }\n\n $paramList = preg_split('/\\s+/', $params);\n\n foreach ($paramList as $param) {\n if (strpos($param, '=') === false) {\n continue;\n }\n\n list($key, $value) = explode('=', $param, 2);\n\n $key = strtolower(str_replace('.', '_', $key));\n\n if ($key == 'exec_host') {\n $data = $this->parseExecHost($value);\n\n // The first node in the host list is used for the host\n // filter feature.\n $node = $data['host_list'][0]['node'];\n\n // Build list of host names compatible with the\n // compressed host list format used by Slurm. This list\n // is currently not compressed, but that could be\n // implemented in the future to reduce database storage\n // requirements.\n $nodes = array();\n foreach ($data['host_list'] as $hostData) {\n $nodes[] = $hostData['node'];\n }\n $job['node_list'] = implode(',', array_unique($nodes));\n\n $job['resources_used_nodes'] = $data['node_count'];\n $job['resources_used_cpus'] = $data['cpu_count'];\n } elseif (isset(self::$columnFormats[$key])) {\n $format = self::$columnFormats[$key];\n $parseMethod = 'parse' . ucfirst($format);\n\n $parsedValue = null;\n\n try {\n $parsedValue = $this->$parseMethod($value);\n } catch (Exception $e) {\n $msg = \"Failed to parse '$key' value '$value': \"\n . $e->getMessage();\n $this->logger->err($msg);\n }\n\n $job[$key] = $parsedValue;\n } elseif ($key === 'group') {\n $job['groupname'] = $value;\n } else {\n $job[$key] = $value;\n }\n }\n\n if (array_key_exists('resource_list_nodes', $job)) {\n $nodesData = $this->resourceParser->parseResourceListNodes($job['resource_list_nodes']);\n $job['resources_used_gpus'] = $this->resourceParser->getGpuCountFromResourceListNodes($nodesData);\n }\n\n // Special cases for SDSC Comet and other versions of PBS.\n if (!array_key_exists('resources_used_gpus', $job) || $job['resources_used_gpus'] === 0) {\n if (array_key_exists('resource_list_gpus', $job)) {\n $job['resources_used_gpus'] = $job['resource_list_gpus'];\n } elseif (array_key_exists('resource_list_ngpus', $job)) {\n $job['resources_used_gpus'] = $job['resource_list_ngpus'];\n } elseif (array_key_exists('resource_list_nodect', $job)) {\n $nodesData = $this->resourceParser->parseResourceListNodes($job['resource_list_nodect']);\n $job['resources_used_gpus'] = $this->resourceParser->getGpuCountFromResourceListNodes($nodesData);\n }\n }\n\n $this->logger->debug('Parsed data: ' . json_encode($job));\n\n if (!$this->testHostFilter($node)) {\n $this->logger->debug('Skipping line due to host filter');\n return;\n }\n\n $job['host'] = $this->getResource();\n\n foreach (array_keys($job) as $key) {\n if (!in_array($key, self::$columnNames)) {\n $this->logger->debug(\"Ignoring unknown attribute '$key'\");\n unset($job[$key]);\n }\n }\n\n $this->checkJobData($line, $job);\n\n $this->insertRow($job);\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (App $utopia, Request $request, Document $project) {\n\n $route = $utopia->match($request);\n\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n $isAppUser = Auth::isAppUser(Authorization::getRoles());\n\n if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs\n return;\n }\n\n $auths = $project->getAttribute('auths', []);\n switch ($route->getLabel('auth.type', '')) {\n case 'emailPassword':\n if (($auths['emailPassword'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email / Password authentication is disabled for this project');\n }\n break;\n\n case 'magic-url':\n if ($project->getAttribute('usersAuthMagicURL', true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Magic URL authentication is disabled for this project');\n }\n break;\n\n case 'anonymous':\n if (($auths['anonymous'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Anonymous authentication is disabled for this project');\n }\n break;\n\n case 'invites':\n if (($auths['invites'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Invites authentication is disabled for this project');\n }\n break;\n\n case 'jwt':\n if (($auths['JWT'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'JWT authentication is disabled for this project');\n }\n break;\n\n default:\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');\n break;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function processRequest(array $data = [])\n {\n $this->isValid = false;\n\n $this->useExistingPassword = (boolean) $data['use_existing_password'];\n $this->host = $data['host'];\n $this->port = $data['port'];\n $this->user = $data['user'];\n $this->password = $this->useExistingPassword ? $this->defaultPassword : $data['password'];\n $this->db = $data['db'];\n $this->createIfNotExists = $data['create_if_not_exists'];\n\n if (!$data['host']) {\n $this->errors[] = 'Please enter the host name.';\n }\n\n if (!$data['port']) {\n $this->errors[] = 'Please enter the port.';\n }\n\n if (!$data['user']) {\n $this->errors[] = 'Please enter the username.';\n }\n\n if (!$data['db']) {\n $this->errors[] = 'Please enter the DB name.';\n }\n\n if (count($this->errors)) {\n return false;\n }\n\n try {\n $dsn = \"mysql:host={$this->host};port={$this->port}\";\n // Try to connect\n $conn = new \\PDO($dsn, $this->user, $this->password);\n\n $stmt = $conn->query('USE `'.$this->db.'`');\n\n if (!$stmt || $stmt->errorCode() > 0) {\n if ($this->createIfNotExists) {\n $stmt = $conn->query(\"CREATE DATABASE `\".$this->db.\"` COLLATE 'utf8_general_ci'\");\n\n if (!$stmt || $stmt->errorCode() > 0) {\n throw new \\Exception('Can\\'t create database ' . $this->db);\n }\n } else {\n throw new \\Exception('Can\\'t connect to database ' . $this->db);\n }\n }\n\n\n } catch (\\Exception $e) {\n $this->errors[] = \"Error \" . $e->getCode() . \": \" . $e->getMessage();\n return false;\n }\n\n $this->isValid = true;\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "public function getCacheData($pCoord) {\n\t\tif ($pCoord === $this->_currentObjectID) {\n\t\t\treturn $this->_currentObject;\n\t\t}\n\t\t$this->_storeData();\n\n\t\t//\tCheck if the entry that has been requested actually exists\n\t\t$obj = null;\n\t\tif (parent::isDataSet($pCoord)) {\n\t\t\t$success = false;\n\t\t\t$obj = wincache_ucache_get($this->_cachePrefix.$pCoord.'.cache', $success);\n\t\t\tif ($success === false) {\n\t\t\t\t//\tEntry no longer exists in WinCache, so clear it from the cache array\n\t\t\t\tparent::deleteCacheData($pCoord);\n\t\t\t\tthrow new Exception('Cell entry '.$cellID.' no longer exists in WinCache');\n\t\t\t}\n\t\t} else {\n\t\t\t//\tReturn null if requested entry doesn't exist in cache\n\t\t\treturn null;\n\t\t}\n\n\t\t//\tSet current entry to the requested entry\n\t\t$this->_currentObjectID = $pCoord;\n\t\t$this->_currentObject = unserialize($obj);\n\t\t//\tRe-attach the parent worksheet\n\t\t$this->_currentObject->attach($this->_parent);\n\n\t\t//\tReturn requested entry\n\t\treturn $this->_currentObject;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function handle(\n CriteriaConverter $converter,\n QueryBuilder $queryBuilder,\n Criterion $criterion,\n array $languageSettings\n ) {\n $column = 'priority';\n\n switch ($criterion->operator) {\n case Criterion\\Operator::BETWEEN:\n return $this->dbPlatform->getBetweenExpression(\n $column,\n $queryBuilder->createNamedParameter($criterion->value[0], ParameterType::STRING),\n $queryBuilder->createNamedParameter($criterion->value[1], ParameterType::STRING)\n );\n\n case Criterion\\Operator::GT:\n case Criterion\\Operator::GTE:\n case Criterion\\Operator::LT:\n case Criterion\\Operator::LTE:\n $operatorFunction = $this->comparatorMap[$criterion->operator];\n\n return $queryBuilder->expr()->$operatorFunction(\n $column,\n $queryBuilder->createNamedParameter(reset($criterion->value), ParameterType::STRING)\n );\n\n default:\n throw new RuntimeException(\n \"Unknown operator '{$criterion->operator}' for Priority Criterion handler.\"\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function addOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname.'Core');\n if (!$path) {\n $path = 'modules'.DIRECTORY_SEPARATOR.$classname.DIRECTORY_SEPARATOR.$classname.'.php';\n }\n $path_override = $this->getLocalPath().'override'.DIRECTORY_SEPARATOR.$path;\n\n if (!file_exists($path_override)) {\n return false;\n } else {\n file_put_contents($path_override, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($path_override)));\n }\n\n $pattern_escape_com = '#(^\\s*?\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism';\n // Check if there is already an override file, if not, we just need to copy the file\n if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n // Check if override file is writable\n $override_path = _PS_ROOT_DIR_.'/'.$file;\n\n if ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path))) {\n throw new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path));\n }\n\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname.'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n $override_file = array_diff($override_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class '.$classname.'OverrideOriginal'.$uniq), implode('', $override_file)));\n $override_class = new ReflectionClass($classname.'OverrideOriginal'.$uniq);\n\n $module_file = file($path_override);\n $module_file = array_diff($module_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n // Check if none of the methods already exists in the override class\n foreach ($module_class->getMethods() as $method) {\n if ($override_class->hasMethod($method->getName())) {\n $method_override = $override_class->getMethod($method->getName());\n if (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version)) {\n throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.'), $method->getName(), $classname, $name[1], $version[1], $date[1]));\n }\n throw new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden.'), $method->getName(), $classname));\n }\n\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override method %1$s in class %2$s.'), $method->getName(), $classname));\n }\n }\n\n // Check if none of the properties already exists in the override class\n foreach ($module_class->getProperties() as $property) {\n if ($override_class->hasProperty($property->getName())) {\n throw new Exception(sprintf(Tools::displayError('The property %1$s in the class %2$s is already defined.'), $property->getName(), $classname));\n }\n\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override property %1$s in class %2$s.'), $property->getName(), $classname));\n }\n }\n\n foreach ($module_class->getConstants() as $constant => $value) {\n if ($override_class->hasConstant($constant)) {\n throw new Exception(sprintf(Tools::displayError('The constant %1$s in the class %2$s is already defined.'), $constant, $classname));\n }\n\n $module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override constant %1$s in class %2$s.'), $constant, $classname));\n }\n }\n\n // Insert the methods from module override in override\n $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);\n array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);\n $code = implode('', $override_file);\n\n file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));\n } else {\n $override_src = $path_override;\n\n $override_dest = _PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'override'.DIRECTORY_SEPARATOR.$path;\n $dir_name = dirname($override_dest);\n\n if (!$orig_path && !is_dir($dir_name)) {\n $oldumask = umask(0000);\n @mkdir($dir_name, 0777);\n umask($oldumask);\n }\n\n if (!is_writable($dir_name)) {\n throw new Exception(sprintf(Tools::displayError('directory (%s) not writable'), $dir_name));\n }\n $module_file = file($override_src);\n $module_file = array_diff($module_file, array(\"\\n\"));\n\n if ($orig_path) {\n do {\n $uniq = uniqid();\n } while (class_exists($classname.'OverrideOriginal_remove', false));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n // For each method found in the override, prepend a comment with the module name and version\n foreach ($module_class->getMethods() as $method) {\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override method %1$s in class %2$s.'), $method->getName(), $classname));\n }\n }\n\n // Same loop for properties\n foreach ($module_class->getProperties() as $property) {\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override property %1$s in class %2$s.'), $property->getName(), $classname));\n }\n }\n\n // Same loop for constants\n foreach ($module_class->getConstants() as $constant => $value) {\n $module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(sprintf(Tools::displayError('Failed to override constant %1$s in class %2$s.'), $constant, $classname));\n }\n }\n }\n\n file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));\n\n // Re-generate the class index\n Tools::generateIndex();\n }\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function unmergeCells($pRange = 'A1:A1')\n\t{\n\t\t// Uppercase coordinate\n\t\t$pRange = strtoupper($pRange);\n\n\t\tif (strpos($pRange,':') !== false) {\n\t\t\tif (isset($this->_mergeCells[$pRange])) {\n\t\t\t\tunset($this->_mergeCells[$pRange]);\n\t\t\t} else {\n\t\t\t\tthrow new Exception('Cell range ' . $pRange . ' not known as merged.');\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Exception('Merge can only be removed from a range of cells.');\n\t\t}\n\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function Update()\n {\n $is_portal = GlobalConfig::$PORTAL;\n try {\n $json = json_decode(RequestUtil::GetBody());\n\n if (!$json) {\n throw new Exception('The request body does not contain valid JSON');\n }\n $pk = $this->GetRouter()->GetUrlParam('id');\n $onsitedocument = $this->Phreezer->Get('OnsiteDocument', $pk);\n\n $existing_template = $onsitedocument->FullDocument;\n\n $hasVersion = stripos($existing_template, 'portal_version') !== false;\n if ($this->SafeGetVal($json, 'type') == 'flattened') {\n $existing = $this->SafeGetVal($json, 'fullDocument');\n if (!empty($existing)) {\n $config = HTMLPurifier_Config::createDefault();\n $config->set('Core.Encoding', 'UTF-8');\n // purifier will only allow base64 data urls in img tag.\n // all other element will be removed. Flatten document have already been sanitized\n // by replacing all inputs, checks and radios tags to their answers.\n // Thus Enter Comment: <input name=\"element\" value=\"This is my comment I don't like purifier\" />\n // renders to Enter Comment: 'This is my comment I don't like purifier in document.'\n $config->set('URI.AllowedSchemes', array('data' => true));\n $purify = new HTMLPurifier($config);\n $existing_template = $purify->purify($existing);\n // since this is a flatten document won't need to track legacy or not.\n if (!$hasVersion) {\n $existing_template = $existing_template . \"<input id='portal_version' name='portal_version' type='hidden' value='New' />\";\n }\n }\n } elseif (!empty($this->SafeGetVal($json, 'fullDocument'))) { // test if an unexpected document is sent.\n // the only time a document is allow from interface is fo flattened documents\n // which should be flagged and even still if flagged HTMLPurifier will blow it up.\n error_log(xlt(\"Invalid save attempt. Suspected portal document attack!\"));\n throw new Exception(xlt(\"Invalid save attempt\"));\n }\n\n // only allow patient to update themselves (part 1)\n if (!empty($GLOBALS['bootstrap_pid'])) {\n if ($GLOBALS['bootstrap_pid'] != $onsitedocument->Pid) {\n $error = 'Unauthorized';\n throw new Exception($error);\n }\n }\n // only allow patient to update themselves (part 2)\n if (!empty($GLOBALS['bootstrap_pid'])) {\n $onsitedocument->Pid = $GLOBALS['bootstrap_pid'];\n } else {\n $onsitedocument->Pid = $this->SafeGetVal($json, 'pid', $onsitedocument->Pid);\n }\n // Set values from API interface.\n $onsitedocument->Facility = $this->SafeGetVal($json, 'facility', $onsitedocument->Facility);\n $onsitedocument->Provider = $this->SafeGetVal($json, 'provider', $onsitedocument->Provider);\n $onsitedocument->Encounter = $this->SafeGetVal($json, 'encounter', $onsitedocument->Encounter);\n $onsitedocument->CreateDate = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'createDate', $onsitedocument->CreateDate)));\n $onsitedocument->DocType = $this->SafeGetVal($json, 'docType', $onsitedocument->DocType);\n $onsitedocument->PatientSignedStatus = $this->SafeGetVal($json, 'patientSignedStatus', $onsitedocument->PatientSignedStatus);\n $onsitedocument->PatientSignedTime = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'patientSignedTime', $onsitedocument->PatientSignedTime)));\n $onsitedocument->AuthorizeSignedTime = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'authorizeSignedTime', $onsitedocument->AuthorizeSignedTime)));\n $onsitedocument->AcceptSignedStatus = $this->SafeGetVal($json, 'acceptSignedStatus', $onsitedocument->AcceptSignedStatus);\n $onsitedocument->AuthorizingSignator = $this->SafeGetVal($json, 'authorizingSignator', $onsitedocument->AuthorizingSignator);\n $onsitedocument->ReviewDate = date('Y-m-d H:i:s', strtotime($this->SafeGetVal($json, 'reviewDate', $onsitedocument->ReviewDate)));\n $onsitedocument->DenialReason = $this->SafeGetVal($json, 'denialReason', $onsitedocument->DenialReason);\n $onsitedocument->AuthorizedSignature = $this->SafeGetVal($json, 'authorizedSignature', $onsitedocument->AuthorizedSignature);\n $onsitedocument->PatientSignature = $this->SafeGetVal($json, 'patientSignature', $onsitedocument->PatientSignature);\n $onsitedocument->FullDocument = $existing_template; // retain original template that was populated during create save.\n $onsitedocument->FileName = $this->SafeGetVal($json, 'fileName', $onsitedocument->FileName);\n $onsitedocument->FilePath = $this->SafeGetVal($json, 'filePath', $onsitedocument->FilePath);\n $onsitedocument->TemplateData = $this->SafeGetVal($json, 'templateData', $onsitedocument->TemplateData);\n $version = $this->SafeGetVal($json, 'version');\n\n $onsitedocument->Validate();\n $errors = $onsitedocument->GetValidationErrors();\n if (count($errors) > 0) {\n $this->RenderErrorJSON('Please check the form for errors', $errors);\n } else {\n $onsitedocument->Save();\n $this->RenderJSON($onsitedocument, $this->JSONPCallback(), true, $this->SimpleObjectParams());\n }\n } catch (Exception $ex) {\n $this->RenderExceptionJSON($ex);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function __callStatic(string $method, array $arguments)\n {\n // check for custom static getters like DataObject::getByMyfield()\n $propertyName = lcfirst(preg_replace('/^getBy/i', '', $method));\n $classDefinition = ClassDefinition::getById(self::classId());\n\n // get real fieldname (case sensitive)\n $fieldnames = [];\n $defaultCondition = '';\n foreach ($classDefinition->getFieldDefinitions() as $fd) {\n $fieldnames[] = $fd->getName();\n }\n $realPropertyName = implode('', preg_grep('/^' . preg_quote($propertyName, '/') . '$/i', $fieldnames));\n\n if (!$classDefinition->getFieldDefinition($realPropertyName) instanceof Model\\DataObject\\ClassDefinition\\Data) {\n $localizedField = $classDefinition->getFieldDefinition('localizedfields');\n if ($localizedField instanceof Model\\DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $fieldnames = [];\n foreach ($localizedField->getFieldDefinitions() as $fd) {\n $fieldnames[] = $fd->getName();\n }\n $realPropertyName = implode('', preg_grep('/^' . preg_quote($propertyName, '/') . '$/i', $fieldnames));\n $localizedFieldDefinition = $localizedField->getFieldDefinition($realPropertyName);\n if ($localizedFieldDefinition instanceof Model\\DataObject\\ClassDefinition\\Data) {\n $realPropertyName = 'localizedfields';\n array_unshift($arguments, $localizedFieldDefinition->getName());\n }\n }\n }\n\n if ($classDefinition->getFieldDefinition($realPropertyName) instanceof Model\\DataObject\\ClassDefinition\\Data) {\n $field = $classDefinition->getFieldDefinition($realPropertyName);\n if (!$field->isFilterable()) {\n throw new Exception(\"Static getter '::getBy\".ucfirst($realPropertyName).\"' is not allowed for fieldtype '\" . $field->getFieldType() . \"'\");\n }\n\n $db = Db::get();\n\n if ($field instanceof Model\\DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedPropertyName = empty($arguments[0]) ? throw new InvalidArgumentException('Mandatory argument $field not set.') : $arguments[0];\n $value = array_key_exists(1, $arguments) ? $arguments[1] : throw new InvalidArgumentException('Mandatory argument $value not set.');\n $locale = $arguments[2] ?? null;\n $limit = $arguments[3] ?? null;\n $offset = $arguments[4] ?? 0;\n $objectTypes = $arguments[5] ?? null;\n\n $localizedField = $field->getFieldDefinition($localizedPropertyName);\n\n if (!$localizedField instanceof Model\\DataObject\\ClassDefinition\\Data) {\n Logger::error('Class: DataObject\\\\Concrete => call to undefined static method ' . $method);\n\n throw new Exception('Call to undefined static method ' . $method . ' in class DataObject\\\\Concrete');\n }\n\n if (!$localizedField->isFilterable()) {\n throw new Exception(\"Static getter '::getBy\".ucfirst($realPropertyName).\"' is not allowed for fieldtype '\" . $localizedField->getFieldType() . \"'\");\n }\n\n $defaultCondition = $db->quoteIdentifier($localizedPropertyName) . ' = ' . $db->quote($value) . ' ';\n $listConfig = [\n 'condition' => $defaultCondition,\n ];\n\n $listConfig['locale'] = $locale;\n } else {\n $value = array_key_exists(0, $arguments) ? $arguments[0] : throw new InvalidArgumentException('Mandatory argument $value not set.');\n $limit = $arguments[1] ?? null;\n $offset = $arguments[2] ?? 0;\n $objectTypes = $arguments[3] ?? null;\n\n if (!$field instanceof AbstractRelations) {\n $defaultCondition = $db->quoteIdentifier($realPropertyName) . ' = ' . $db->quote($value) . ' ';\n }\n $listConfig = [\n 'condition' => $defaultCondition,\n ];\n }\n\n if (!is_array($limit)) {\n $listConfig['limit'] = $limit;\n $listConfig['offset'] = $offset;\n } else {\n $listConfig = array_merge($listConfig, $limit);\n $limitCondition = $limit['condition'] ?? '';\n $listConfig['condition'] = $defaultCondition . $limitCondition;\n }\n\n $list = static::makeList($listConfig, $objectTypes);\n\n if ($field instanceof AbstractRelations) {\n $list = $field->addListingFilter($list, $value);\n }\n\n if (isset($listConfig['limit']) && $listConfig['limit'] == 1) {\n $elements = $list->getObjects();\n\n return isset($elements[0]) ? $elements[0] : null;\n }\n\n return $list;\n }\n\n try {\n return call_user_func_array([parent::class, $method], $arguments);\n } catch (Exception $e) {\n // there is no property for the called method, so throw an exception\n Logger::error('Class: DataObject\\\\Concrete => call to undefined static method '.$method);\n\n throw new Exception('Call to undefined static method '.$method.' in class DataObject\\\\Concrete');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected function hostForSite(Site $site): string\n {\n $host = $site->getMainDomain();\n if (!empty($host)) {\n return $host;\n }\n\n foreach ($site->getDomains() as $domain) {\n if (!empty($domain)) {\n $host = $domain;\n\n break;\n }\n }\n\n if (empty($host)) {\n throw new RuntimeException(sprintf('Failed to resolve host for site %d', $site->getId()));\n }\n\n return $host;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function load(DataObject\\Fieldcollection\\Data\\AbstractData|DataObject\\Objectbrick\\Data\\AbstractData|DataObject\\Concrete $object, array $params = []): void\n {\n $validLanguages = Tool::getValidLanguages();\n foreach ($validLanguages as &$language) {\n $language = $this->db->quote($language);\n }\n\n $context = $this->model->getContext();\n if (isset($context['containerType']) && $context['containerType'] === 'fieldcollection') {\n $containerKey = $context['containerKey'];\n $index = $context['index'];\n $fieldname = $context['fieldname'];\n\n $container = DataObject\\Fieldcollection\\Definition::getByKey($containerKey);\n\n $data = $this->db->fetchAllAssociative(\n 'SELECT * FROM '.$this->getTableName()\n .' WHERE ooo_id = ? AND language IN ('.implode(\n ',',\n $validLanguages\n ).') AND `fieldname` = ? AND `index` = ?',\n [\n $this->model->getObject()->getId(),\n $fieldname,\n $index,\n ]\n );\n } elseif (isset($context['containerType']) && $context['containerType'] === 'objectbrick') {\n $containerKey = $context['containerKey'];\n $container = DataObject\\Objectbrick\\Definition::getByKey($containerKey);\n $fieldname = $context['fieldname'];\n\n $data = $this->db->fetchAllAssociative(\n 'SELECT * FROM '.$this->getTableName()\n .' WHERE ooo_id = ? AND language IN ('.implode(',', $validLanguages).') AND `fieldname` = ?',\n [\n $this->model->getObject()->getId(),\n $fieldname,\n ]\n );\n } else {\n $object->__objectAwareFields['localizedfields'] = true;\n $container = $this->model->getClass();\n $data = $this->db->fetchAllAssociative(\n 'SELECT * FROM '.$this->getTableName().' WHERE ooo_id = ? AND language IN ('.implode(\n ',',\n $validLanguages\n ).')',\n [$this->model->getObject()->getId()]\n );\n }\n\n if (!isset($params['owner'])) {\n throw new Exception('need owner from container implementation');\n }\n\n $this->model->_setOwner($params['owner']);\n $this->model->_setOwnerFieldname('localizedfields');\n $this->model->_setOwnerLanguage(null);\n\n foreach ($data as $row) {\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $localizedfields */\n $localizedfields = $container->getFieldDefinition('localizedfields');\n foreach ($localizedfields->getFieldDefinitions(\n ['object' => $object, 'suppressEnrichment' => true]\n ) as $key => $fd) {\n if ($fd instanceof CustomResourcePersistingInterface) {\n // datafield has it's own loader\n $params['language'] = $row['language'];\n $params['object'] = $object;\n if (!isset($params['context'])) {\n $params['context'] = [];\n }\n $params['context']['object'] = $object;\n\n if ($fd instanceof LazyLoadingSupportInterface\n && $fd instanceof DataObject\\ClassDefinition\\Data\n && $fd->getLazyLoading()) {\n $lazyKey = $fd->getName() . DataObject\\LazyLoadedFieldsInterface::LAZY_KEY_SEPARATOR . $row['language'];\n } else {\n $value = $fd->load($this->model, $params);\n if ($value === 0 || !empty($value)) {\n $this->model->setLocalizedValue($key, $value, $row['language'], false);\n }\n }\n }\n if ($fd instanceof ResourcePersistenceAwareInterface) {\n if (is_array($fd->getColumnType())) {\n $multidata = [];\n foreach ($fd->getColumnType() as $fkey => $fvalue) {\n $multidata[$key.'__'.$fkey] = $row[$key.'__'.$fkey];\n }\n $value = $fd->getDataFromResource($multidata, null, $this->getFieldDefinitionParams($key, $row['language']));\n $this->model->setLocalizedValue($key, $value, $row['language'], false);\n } else {\n $value = $fd->getDataFromResource($row[$key], null, $this->getFieldDefinitionParams($key, $row['language']));\n $this->model->setLocalizedValue($key, $value, $row['language'], false);\n }\n }\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getChildrenIDs() {\n if (!$this->loaded())\n throw new \\Exception(\"The model is not loaded\");\n $result = [];\n $ids = $this->pixie->db->query('select')->table($this->table)\n ->fields($this->id_field)->where('lpos', '>', $this->lpos)\n ->where('rpos', '<', $this->rpos)->where('depth', '>', 0)->execute()->as_array();\n if (count($ids)) {\n array_walk($ids, function($item) use(&$result) {\n $result[] = $item->categoryID;\n });\n }\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "antonisLem_hackazon", "language": "php"} {"function": "public function theWebdavResponseShouldHaveAStatusCode($statusCode) {\n\t\tif ((int)$statusCode !== $this->response->getStatusCode()) {\n\t\t\tthrow new \\Exception(\"Expected $statusCode, got \".$this->response->getStatusCode());\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $userId, string $email, Response $response, Database $dbForProject, Event $events) {\n\n $user = $dbForProject->getDocument('users', $userId);\n\n if ($user->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $email = \\strtolower($email);\n\n // Makes sure this email is not already used in another identity\n $identityWithMatchingEmail = $dbForProject->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n Query::notEqual('userId', $user->getId()),\n ]);\n if ($identityWithMatchingEmail !== false && !$identityWithMatchingEmail->isEmpty()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n $user\n ->setAttribute('email', $email)\n ->setAttribute('emailVerification', false)\n ;\n\n\n try {\n $user = $dbForProject->updateDocument('users', $user->getId(), $user);\n } catch (Duplicate $th) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n $events->setParam('userId', $user->getId());\n\n $response->dynamic($user, Response::MODEL_USER);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function downloadallAction()\n {\n $pids = $this->params('pids');\n $document_type = $this->params('document_type') ?? '';\n if ($pids != '') {\n $zip = new Zip();\n $parent_dir = sys_get_temp_dir() . \"/CCDA_Patient_Documents_\" . time();\n if (!is_dir($parent_dir)) {\n if (!mkdir($parent_dir, true) && !is_dir($parent_dir)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $parent_dir));\n }\n chmod($parent_dir, 0777);\n }\n\n $dir = $parent_dir . \"/\";\n $arr = explode('|', $pids);\n foreach ($arr as $row) {\n $pid = $row;\n $ids = $this->getEncountermanagerTable()->getFileID($pid, 2);\n $doc_type = $document_type;\n foreach ($ids as $row_inner) {\n $id = $row_inner['id'];\n // xml version for parsing or transfer.\n $ccdaDocuments = \\Document::getDocumentsForForeignReferenceId('ccda', $id);\n $content = !empty($ccdaDocuments) ? $ccdaDocuments[0]->get_data() : \"\"; // nothing here to export\n // From header oid for an unstructured document.\n // used if the auto create patient document export is on in ccda service.\n // else document_type is correctly set if purposely sent as unstructured from CCM\n if (stripos($content, '2.16.840.1.113883.10.20.22.1.10') > 0) {\n $doc_type = 'unstructured';\n }\n /* let's not have a dir per patient for now! though we'll keep for awhile.\n * $dir = $parent_dir . \"/CCDA_{$row_inner['lname']}_{$row_inner['fname']}/\";*/\n $filename = \"CCDA_{$row_inner['lname']}_{$row_inner['fname']}\";\n if (!empty($doc_type) && in_array($doc_type, self::VALID_CCDA_DOCUMENT_TYPES)) {\n $filename .= \"_\" . $doc_type;\n }\n $filename .= \"_\" . date(\"Y_m_d_His\"); // ensure somewhat unique\n $filename_html = $filename . \".html\";\n $filename .= \".xml\";\n if (!is_dir($dir)) {\n if (!mkdir($dir, true) && !is_dir($dir)) {\n throw new \\RuntimeException(sprintf('Directory \"%s\" was not created', $dir));\n }\n chmod($dir, 0777);\n }\n $f2 = fopen($dir . $filename, \"w\");\n fwrite($f2, $content);\n fclose($f2);\n if ($doc_type != 'unstructured') {\n // html version for viewing\n $content = $this->buildCCDAHtml($content);\n $f2 = fopen($dir . $filename_html, \"w\");\n fwrite($f2, $content);\n fclose($f2);\n }\n }\n copy(__DIR__ . \"/../../../../../public/xsl/cda.xsl\", $dir . \"CDA.xsl\");\n }\n\n $zip_dir = sys_get_temp_dir() . \"/\";\n $zip_name = \"CCDA\";\n // since we are sending this out to the filesystem we need to whitelist these document types so that we don't\n // get any kind of filesystem injection attack here.\n if (!empty($document_type) && in_array($document_type, self::VALID_CCDA_DOCUMENT_TYPES)) {\n $zip_name .= \"_All\";\n }\n $zip_name .= \"_\" . date(\"Y_m_d_His\") . \".zip\";\n $zip->setArchive($zip_dir . $zip_name);\n $zip->compress($parent_dir);\n\n ob_clean();\n header(\"Cache-Control: public\");\n header(\"Content-Description: File Transfer\");\n header(\"Content-Disposition: attachment; filename=$zip_name\");\n header(\"Content-Type: application/download\");\n header(\"Content-Transfer-Encoding: binary\");\n readfile($zip_dir . $zip_name);\n\n // we need to unlink both the directory and the zip file once are done... as its a security hazard\n // to have these files just hanging around in a tmp folder\n unlink($zip_dir . $zip_name);\n\n $view = new ViewModel();\n $view->setTerminal(true);\n return $view;\n } else {\n // we return just empty Json, otherwise it triggers an error if we don't return some kind of HTTP response.\n $view = new JsonModel();\n $view->setTerminal(true);\n return $view;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getCurrentDraft()\n {\n if ($this->currentDraft === null) {\n throw new RuntimeException('No current draft has been set');\n }\n\n return $this->currentDraft;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function get($name)\n {\n if (!$this->instances[$name]) {\n $className = preg_replace('#(\\\\\\\\)[^\\\\\\\\]+$#', '$1', __CLASS__).ucfirst($name).'Provider';\n if (!class_exists($className)) {\n throw new \\Exception('Invalid authentication method for REST service.');\n }\n\n $this->instances[$name] = new $className($this->pixie);\n }\n\n return $this->instances[$name];\n }", "smellKey": "S112", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "public static function filterUnpublishedAdvancedElements(?array $data): array\n {\n if (DataObject::doHideUnpublished() && is_array($data)) {\n $publishedList = [];\n $mapping = [];\n foreach ($data as $advancedElement) {\n if (!$advancedElement instanceof DataObject\\Data\\ObjectMetadata\n && !$advancedElement instanceof DataObject\\Data\\ElementMetadata) {\n throw new Exception('only supported for advanced many-to-many (+object) relations');\n }\n\n $elementId = null;\n if ($advancedElement instanceof DataObject\\Data\\ObjectMetadata) {\n $elementId = $advancedElement->getObjectId();\n $elementType = 'object';\n } else {\n $elementId = $advancedElement->getElementId();\n $elementType = $advancedElement->getElementType();\n }\n\n if (!$elementId) {\n continue;\n }\n if ($elementType == 'asset') {\n // there is no published flag for assets\n continue;\n }\n $mapping[$elementType][$elementId] = true;\n }\n\n $db = Db::get();\n $publishedMapping = [];\n\n // now do the query;\n foreach ($mapping as $elementType => $idList) {\n $idList = array_keys($mapping[$elementType]);\n $query = 'SELECT id FROM ' . $elementType . 's WHERE published=1 AND id IN (' . implode(',', $idList) . ');';\n $publishedIds = $db->fetchFirstColumn($query);\n $publishedMapping[$elementType] = $publishedIds;\n }\n\n foreach ($data as $advancedElement) {\n $elementId = null;\n if ($advancedElement instanceof DataObject\\Data\\ObjectMetadata) {\n $elementId = $advancedElement->getObjectId();\n $elementType = 'object';\n } else {\n $elementId = $advancedElement->getElementId();\n $elementType = $advancedElement->getElementType();\n }\n\n if ($elementType == 'asset') {\n $publishedList[] = $advancedElement;\n }\n\n if (isset($publishedMapping[$elementType]) && in_array($elementId, $publishedMapping[$elementType])) {\n $publishedList[] = $advancedElement;\n }\n }\n\n return $publishedList;\n }\n\n return is_array($data) ? $data : [];\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected function VerifyCSRFToken($headerName = 'X-CSRFToken')\n {\n // check that a CSRF token is present in the request\n $headers = RequestUtil::GetHeaders();\n\n // make this case-insensitive (IE changes all headers to lower-case)\n $headers = array_change_key_case($headers, CASE_LOWER);\n $headerName = strtolower($headerName);\n\n if (array_key_exists($headerName, $headers)) {\n if ($this->GetCSRFToken() != $headers [$headerName]) {\n throw new Exception('Invalid CSRFToken');\n }\n } else {\n throw new Exception('Missing CSRFToken');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getByName(string $name): ?CustomLayout\n {\n $cacheKey = 'customlayout_' . $name;\n\n try {\n $customLayout = RuntimeCache::get($cacheKey);\n if (!$customLayout) {\n throw new Exception('Custom Layout in registry is null');\n }\n } catch (Exception $e) {\n try {\n $customLayout = new self();\n $customLayout->getDao()->getByName($name);\n RuntimeCache::set($cacheKey, $customLayout);\n } catch (Model\\Exception\\NotFoundException $e) {\n return null;\n }\n }\n\n return $customLayout;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function query() {\n\n $query = '';\n $params = array();\n if (!$this->parent) {\n $this->_aliases = [];\n }\n\n if ($this->_type == 'insert') {\n $query .= \"INSERT INTO {$this->escape_table($this->_table, $params)} \";\n if (empty($this->_data) && $this->_db_type == 'pgsql') {\n $query.= \"DEFAULT VALUES \";\n } else {\n if (isset($this->_data[0]) && is_array($this->_data[0])) { // Batch insert\n $first_row = true;\n $columns_array = array();\n\n foreach ($this->_data as $row) {\n $columns = '';\n $values = '';\n $first = true;\n if ($first_row) {\n foreach ($row as $key => $val) {\n if (!$first) {\n $values .= ', ';\n $columns .= ', ';\n } else {\n $first = false;\n }\n $columns .= $this->quote($key);\n $columns_array[] = $key;\n $values .= $this->escape_value($val, $params, $key);\n }\n $query .= \"({$columns}) VALUES({$values})\";\n } else {\n foreach ($columns_array as $col) {\n if (!$first) {\n $values .= ', ';\n } else {\n $first = false;\n }\n $values .= $this->escape_value($row[$col], $params, $col);\n }\n $query .= \", ({$values})\";\n }\n $first_row = false;\n }\n } else {\n $columns = '';\n $values = '';\n $first = true;\n foreach ($this->_data as $key => $val) {\n if (!$first) {\n $values .= ', ';\n $columns .= ', ';\n } else {\n $first = false;\n }\n $columns .= $this->quote($key);\n $values .= $this->escape_value($val, $params, $key);\n }\n $query .= \"({$columns}) VALUES({$values})\";\n }\n }\n } else {\n if ($this->_type == 'select') {\n $query .= \"SELECT \";\n if ($this->_fields == null) {\n $query .= \"* \";\n } else {\n $first = true;\n foreach ($this->_fields as $f) {\n if (!$first) {\n $query .= \", \";\n } else {\n $first = false;\n }\n if (is_array($f)) {\n $query .= \"{$this->escape_field($f[0])} AS {$f[1]} \";\n } else {\n $query .= \"{$this->escape_field($f)} \";\n }\n }\n }\n if (!empty($this->_table))\n $query .= \"FROM {$this->escape_table($this->_table, $params)} \";\n }\n if ($this->_type == 'count') {\n $query .= \"SELECT COUNT(*) as {$this->quote('count')} FROM {$this->escape_table($this->_table, $params)} \";\n }\n\n if ($this->_type == 'delete') {\n if ($this->_db_type != 'sqlite') {\n $query .= \"DELETE {$this->last_alias()}.* FROM {$this->escape_table($this->_table, $params)} \";\n } else {\n if (!empty($this->_joins)) {\n throw new \\Exception(\"SQLite doesn't support deleting a table with JOIN in the query\");\n }\n $query .= \"DELETE FROM {$this->escape_table($this->_table, $params)} \";\n }\n }\n if ($this->_type == 'update') {\n $query .= \"UPDATE {$this->escape_table($this->_table, $params)} \";\n }\n\n $joinedTables = [];\n foreach ($this->_joins as $join) {\n $table = $join[0];\n $table = $this->escape_table($table, $params);\n if (in_array($table, $joinedTables)) {\n continue;\n }\n $query .= strtoupper($join[1]) . \" JOIN {$table} \";\n if (!empty($join[2]))\n $query.=\"ON {$this->get_condition_query($join[2], $params, true, true)} \";\n $joinedTables[] = $table;\n }\n\n if ($this->_type == 'update') {\n\n $query.= \"SET \";\n\n $first = true;\n foreach ($this->_data as $key => $val) {\n\n if (!$first) {\n $query.=\", \";\n } else {\n $first = false;\n }\n\n $query .= \"{$this->quote($key)} = {$this->escape_value($val, $params, $key)}\";\n }\n $query .= \" \";\n }\n\n if (!empty($this->_conditions)) {\n $query .= \"WHERE {$this->get_condition_query($this->_conditions, $params, true)} \";\n }\n if (($this->_type == 'select' || $this->_type == 'count') && $this->_group_by != null) {\n $query .= \"GROUP BY {$this->escape_field($this->_group_by)} \";\n }\n if (($this->_type == 'select' || $this->_type == 'count') && !empty($this->_having)) {\n $query .= \"HAVING {$this->get_condition_query($this->_having, $params, true)} \";\n }\n\n if ($this->_type == 'select' && !empty($this->_order_by)) {\n $query .= \"ORDER BY \";\n $first = true;\n foreach ($this->_order_by as $order) {\n if (!$first) {\n $query .= ',';\n } else {\n $first = false;\n }\n $query .= $this->escape_field($order[0]) . \" \";\n if (isset($order[1])) {\n $dir = strtoupper($order[1]);\n $query .= $dir . \" \";\n }\n }\n }\n\n if (count($this->_union) > 0 && ($this->_type == 'select')) {\n $query = \"({$query}) \";\n foreach ($this->_union as $union) {\n $query .= $union[1] ? \"UNION ALL \" : \"UNION \";\n if ($union[0] instanceof DB\\Query) {\n $query .= $this->subquery($union[0], $params);\n } elseif ($union[0] instanceof DB\\Expression) {\n $query .= \"({$union[0]->value}) \";\n } else {\n throw new \\Exception(\"You can only use query builder instances or \\$pixie->db->expr() for unions\");\n }\n }\n }\n\n if ($this->_type != 'count') {\n if ($this->_limit != null) {\n $query .= \"LIMIT {$this->_limit} \";\n }\n if ($this->_offset != null) {\n $query .= \"OFFSET {$this->_offset} \";\n }\n }\n }\n\n return array($query, $params);\n }", "smellKey": "S112", "smellId": null, "repo": "Tmlrb2xhb3M_hackazon", "language": "php"} {"function": "private function getMilestoneNumberForMilestoneStatus($milestoneStatus, $milestoneName, $accessToken)\n {\n $url = http_build_query(['state' => $milestoneStatus, 'per_page' => 100]);\n $url = \"https://api.github.com/repos/openemr/openemr/milestones?\" . $url;\n\n $guzzle = new Client();\n try {\n if (!empty($accessToken)) {\n $headers = ['Authorization' => 'token ' . $accessToken];\n $response = $guzzle->request('GET', $url, ['headers' => $headers]);\n } else {\n $response = $guzzle->get($url);\n }\n // now we need to find the milestone number by comparing the milestone name to the name in the JSON response\n if ($response->getStatusCode() == 200) {\n $milestones = json_decode($response->getBody(), true);\n foreach ($milestones as $milestone) {\n if ($milestone['title'] == $milestoneName) {\n return $milestone['number'];\n }\n }\n // if we didn't find the milestone we should grab the next link from the header and find it here\n $headers = $response->getHeaders();\n $nextLink = $this->getNextLink($headers);\n $loopBreak = false;\n while ($nextLink && $loopBreak++ < self::MAX_API_FETCH_COUNT) {\n echo \"attempting to retrieve \" . $nextLink . \"\\n\";\n if (!empty($accessToken)) {\n $response = $guzzle->request('GET', $nextLink, ['headers' => ['Authorization' => 'token ' . $accessToken]]);\n } else {\n $response = $guzzle->get($nextLink);\n }\n if ($response->getStatusCode() == 200) {\n $headers = $response->getHeaders();\n $milestones = json_decode($response->getBody(), true);\n foreach ($milestones as $milestone) {\n if ($milestone['title'] == $milestoneName) {\n return $milestone['number'];\n }\n }\n $nextLink = $this->getNextLink($headers);\n } elseif ($response->getStatusCode() == 403) {\n $this->printRateLimitMessage($response);\n $nextLink = false;\n } else {\n $nextLink = false;\n }\n }\n if ($loopBreak >= self::MAX_API_FETCH_COUNT) {\n throw new \\RuntimeException(\"Error getting milestones from github. Too many API calls\\n\");\n }\n return false;\n } else if ($response->getStatusCode() === 403) {\n $this->printRateLimitMessage($response);\n throw new \\RuntimeException(\"Error getting milestones from github\\n\");\n } else {\n throw new \\RuntimeException(\"Error getting milestones from github\\n\");\n }\n } catch (GuzzleException $exception) {\n if ($exception->getCode() == 403) {\n $this->printRateLimitMessage($exception->getResponse());\n throw $exception;\n }\n echo \"Error getting milestones from github. Exception message was: \" . $exception->getMessage() . \"\\n\";\n throw $exception;\n } catch (\\Exception $e) {\n echo \"Error getting milestones from github. Exception message was: \" . $e->getMessage() . \"\\n\";\n throw $e;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function deleteAcl(Acl $acl)\n {\n if (null == $acl->getAclId()) {\n throw new Exception('Acl must have an id to be deleted.');\n }\n\n $db = DB::factory('database');\n\n $query = \"DELETE FROM acls WHERE acl_id = :acl_id\";\n $rows = $db->execute($query, array(\n ':acl_id' => $acl->getAclId()\n ));\n return $rows === 1;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function LoadDriver()\n {\n if ($this->_driver == null) {\n require_once(\"verysimple/IO/Includer.php\");\n\n // the driver was not explicitly provided so we will try to create one from\n // the connection setting based on the database types that we do know about\n switch ($this->ConnectionSetting->Type) {\n case \"mysql\":\n include_once(\"verysimple/DB/DataDriver/MySQL.php\");\n $this->_driver = new DataDriverMySQL();\n break;\n case \"mysqli\":\n include_once(\"verysimple/DB/DataDriver/MySQLi.php\");\n $this->_driver = new DataDriverMySQLi();\n break;\n case \"sqlite\":\n include_once(\"verysimple/DB/DataDriver/SQLite.php\");\n $this->_driver = new DataDriverSQLite();\n break;\n default:\n try {\n Includer::IncludeFile(\"verysimple/DB/DataDriver/\" . $this->ConnectionSetting->Type . \".php\");\n $classname = \"DataDriver\" . $this->ConnectionSetting->Type;\n $this->_driver = new $classname();\n } catch (IncludeException $ex) {\n throw new Exception('Unknown DataDriver \"' . $this->ConnectionSetting->Type . '\" specified in connection settings');\n }\n break;\n }\n\n DataAdapter::$DRIVER_INSTANCE = $this->_driver;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function verifyProperty($property, $value)\n {\n // Perform input verificaiton and possibly transformation\n\n switch ( $property ) {\n\n case 'buffered_query':\n case 'optimize_query':\n case 'disable_keys':\n case 'ignore_source':\n case 'force_load_data_infile_replace_into':\n case 'hide_sql_warnings':\n $origValue = $value;\n $value = \\xd_utilities\\filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);\n if ( null === $value ) {\n $msg = get_class($this) . \": '$property' must be a boolean (type = \" . gettype($origValue) . \")\";\n throw new Exception($msg);\n }\n break;\n\n case 'hide_sql_warning_codes':\n $value = ( is_array($value) ? $value : array($value) );\n foreach ( $value as &$v ) {\n $origValue = $v;\n $v = \\xd_utilities\\filter_var($v, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);\n if ( null === $v ) {\n $msg = get_class($this) . \": '$property' must be an integer or array of integers (type = \" . gettype($origValue) . \")\";\n throw new Exception($msg);\n }\n }\n unset($v);\n break;\n\n case 'include_only_resource_codes':\n case 'exclude_resource_codes':\n $value = ( is_array($value) ? $value : array($value) );\n foreach ( $value as $v ) {\n if ( ! is_string($v) ) {\n $msg = get_class($this) . \": '$property' must be a string or array of strings (type = \" . gettype($v) . \")\";\n throw new Exception($msg);\n }\n }\n break;\n\n case 'utility':\n case 'source':\n case 'destination':\n if ( ! is_string($value) ) {\n $msg = get_class($this) . \": '$property' must be a string (type = \" . gettype($value) . \")\";\n throw new Exception($msg);\n }\n break;\n\n default:\n $value = parent::verifyProperty($property, $value);\n break;\n }\n\n return $value;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function offsetSet($offset, $value): void\n {\n if ($value instanceof CqmPatient) {\n if ($offset == \"\") {\n $this->_patients[] = $value;\n } else {\n $this->_patients[$offset] = $value;\n }\n } else {\n throw new Exception(\"Value must be an instance of CqmPatient\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getDiffDataFromEditmode(array $data, Concrete $object = null, array $params = []): mixed\n {\n throw new Exception('not supported');\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function GetUrl($controller, $method, $params = '', $requestMethod = '')\n {\n throw new Exception('Not yet implemented');\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function smartyInit($smarty_templates_dir=null){\n\n\n if($smarty_templates_dir==null && defined('HEURIST_SMARTY_TEMPLATES_DIR')){\n $smarty_templates_dir = HEURIST_SMARTY_TEMPLATES_DIR;\n }\n\n if(!file_exists($smarty_templates_dir)){\n throw new \\Exception('Smarty templates folder does not exist');\n }\n //check folder existance and create new folders if they are missing\n if(!folderCreate($smarty_templates_dir, true)){\n throw new \\Exception('Failed to create folder for smarty templates');\n }\n if(!folderCreate($smarty_templates_dir.'configs/', true)){\n throw new \\Exception('Failed to create configs folder for smarty templates');\n }\n if(!folderCreate($smarty_templates_dir.'compiled/', true)){\n throw new \\Exception('Failed to create compiled folder for smarty templates');\n }\n if(!folderCreate($smarty_templates_dir.'cache/', true)){\n throw new \\Exception('Failed to create cache folder for smarty templates');\n }\n\n $smarty = new Smarty();\n\n\n $smarty->setTemplateDir($smarty_templates_dir);\n $smarty->setCompileDir($smarty_templates_dir.'compiled');\n $smarty->setCacheDir($smarty_templates_dir.'cache');\n $smarty->setConfigDir($smarty_templates_dir.'configs');\n\n // enable security\n \n $smarty->enableSecurity('HeuristSecurityPolicy');\n \n //allowed php functions\n $php_functions = array( 'count', //'constant', \n 'sizeof', 'in_array', 'is_array', 'intval', 'implode', 'explode',\n //'array_key_exists', 'array_column',\n 'array_count_values', 'array_keys', //'array_multisort',\n 'array_diff', 'array_merge', 'array_slice', 'array_unique',\n 'asort', 'ksort', //'sort', \n 'array_values', \n 'floatval', 'is_numeric', 'json_encode',\n 'nl2br',\n 'preg_match_all','print_r','printf', 'range', 'round',\n 'setlocale', 'strcmp', 'strpos', 'strstr', 'substr', 'strlen',\n 'time',\n 'utf8_encode');\n\n //register php functions\n foreach($php_functions as $fname){\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, $fname, $fname);\n }\n\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'array_key_exists', 'heuristModifierArrayKeyExists');\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'array_column', 'heuristModifierArrayColumn');\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'translate', 'heuristModifierTranslate');\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'arraysortby', 'heuristModifierArraySortByFields');\n\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'sort', 'heuristModifierArraySort');\n $smarty->registerPlugin(Smarty::PLUGIN_MODIFIER, 'array_multisort', 'heuristModifierArrayMultiSort');\n \n \n return $smarty;\n}", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function IncludeMap($objectclass)\n {\n try {\n Includer::RequireClass($objectclass, \"Model/DAO/\");\n } catch (IncludeException $ex) {\n throw new Exception($ex->getMessage() . '. If a map file does not exist then ' . get_class($this) . ' can implement GetFieldFromProp instead.');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function addAsset(Request $request, Config $config): array\n {\n $defaultUploadPath = $config['assets']['default_upload_path'] ?? '/';\n\n if (array_key_exists('Filedata', $_FILES)) {\n $filename = $_FILES['Filedata']['name'];\n $sourcePath = $_FILES['Filedata']['tmp_name'];\n } elseif ($request->get('type') == 'base64') {\n $filename = $request->get('filename');\n $sourcePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/upload-base64' . uniqid() . '.tmp';\n $data = preg_replace('@^data:[^,]+;base64,@', '', $request->get('data'));\n $filesystem = new Filesystem();\n $filesystem->dumpFile($sourcePath, base64_decode($data));\n } else {\n throw new \\Exception('The filename of the asset is empty');\n }\n\n $parentId = $request->query->getInt('parentId');\n $parentPath = $request->query->get('parentPath');\n\n if ($request->get('dir') && $request->get('parentId')) {\n // this is for uploading folders with Drag&Drop\n // param \"dir\" contains the relative path of the file\n $parent = Asset::getById((int) $request->get('parentId'));\n $dir = $request->get('dir');\n if (strpos($dir, '..') !== false) {\n throw new \\Exception('not allowed');\n }\n\n $newPath = $parent->getRealFullPath() . '/' . trim($dir, '/ ');\n\n $maxRetries = 5;\n $newParent = null;\n for ($retries = 0; $retries < $maxRetries; $retries++) {\n try {\n $newParent = Asset\\Service::createFolderByPath($newPath);\n\n break;\n } catch (\\Exception $e) {\n if ($retries < ($maxRetries - 1)) {\n $waitTime = rand(100000, 900000); // microseconds\n usleep($waitTime); // wait specified time until we restart the transaction\n } else {\n // if the transaction still fail after $maxRetries retries, we throw out the exception\n throw $e;\n }\n }\n }\n if ($newParent) {\n $parentId = $newParent->getId();\n }\n } elseif (!$request->get('parentId') && $parentPath) {\n $parent = Asset::getByPath($parentPath);\n if ($parent instanceof Asset\\Folder) {\n $parentId = $parent->getId();\n } else { //create defined parent folder, if doesn't exist.\n $parentId = Asset\\Service::createFolderByPath($parentPath)->getId();\n }\n }\n\n $filename = Element\\Service::getValidKey($filename, 'asset');\n if (empty($filename)) {\n throw new \\Exception('The filename of the asset is empty');\n }\n\n $context = $request->get('context');\n if ($context) {\n $context = json_decode($context, true);\n $context = $context ?: [];\n\n $this->validateManyToManyRelationAssetType($context, $filename, $sourcePath);\n\n $event = new ResolveUploadTargetEvent($parentId, $filename);\n $event->setArgument('context', $context);\n\n \\Pimcore::getEventDispatcher()->dispatch($event, AssetEvents::RESOLVE_UPLOAD_TARGET);\n $filename = Element\\Service::getValidKey($event->getFilename(), 'asset');\n $parentId = $event->getParentId();\n }\n\n if (!$parentId) {\n $parentId = Asset\\Service::createFolderByPath($defaultUploadPath)->getId();\n }\n\n $parentAsset = Asset::getById((int)$parentId);\n\n if (!$request->get('allowOverwrite')) {\n // check for duplicate filename\n $filename = $this->getSafeFilename($parentAsset->getRealFullPath(), $filename);\n }\n\n if (!$parentAsset->isAllowed('create')) {\n throw $this->createAccessDeniedHttpException(\n 'Missing the permission to create new assets in the folder: ' . $parentAsset->getRealFullPath()\n );\n }\n\n if (is_file($sourcePath) && filesize($sourcePath) < 1) {\n throw new \\Exception('File is empty!');\n } elseif (!is_file($sourcePath)) {\n throw new \\Exception('Something went wrong, please check upload_max_filesize and post_max_size in your php.ini as well as the write permissions of your temporary directories.');\n }\n\n // check if there is a requested type and if matches the asset type of the uploaded file\n $uploadAssetType = $request->get('uploadAssetType');\n if ($uploadAssetType) {\n $mimetype = MimeTypes::getDefault()->guessMimeType($sourcePath);\n $assetType = Asset::getTypeFromMimeMapping($mimetype, $filename);\n\n if ($uploadAssetType !== $assetType) {\n throw new \\Exception(\"Mime type $mimetype does not match with asset type: $uploadAssetType\");\n }\n }\n\n if ($request->get('allowOverwrite') && Asset\\Service::pathExists($parentAsset->getRealFullPath().'/'.$filename)) {\n $asset = Asset::getByPath($parentAsset->getRealFullPath().'/'.$filename);\n $asset->setStream(fopen($sourcePath, 'rb', false, File::getContext()));\n $asset->save();\n } else {\n $asset = Asset::create($parentId, [\n 'filename' => $filename,\n 'sourcePath' => $sourcePath,\n 'userOwner' => $this->getAdminUser()->getId(),\n 'userModification' => $this->getAdminUser()->getId(),\n ]);\n }\n\n @unlink($sourcePath);\n\n return [\n 'success' => true,\n 'asset' => $asset,\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public static function create($val)\n {\n if (self::$_prefer) {\n switch (self::$_prefer) {\n case 'gmp':\n $ret = new BigIntegerGmp();\n break;\n case 'bcmath':\n $ret = new BigIntegerBcmath();\n break;\n default:\n throw new \\UnexpectedValueException('Unknown number implementation: ' . self::$_prefer);\n }\n }\n else {\n // autodetect\n if (function_exists('gmp_add')) {\n $ret = new BigIntegerGmp();\n }\n elseif (function_exists('bcadd')) {\n $ret = new BigIntegerBcmath();\n } else {\n throw new \\RuntimeException('Requires GMP or bcmath extension.');\n }\n }\n\n if (is_int($val)) {\n $ret->_fromInteger($val);\n }\n else {\n // convert to string, if not already one\n $val = (string)$val;\n\n // validate string\n if (!preg_match('/^-?[0-9]+$/', $val)) {\n throw new \\InvalidArgumentException('Expects a string representation of an integer.');\n }\n $ret->_fromString($val);\n }\n\n return $ret;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function default_http_handler()\n{\n $version = guzzle_major_version();\n // If Guzzle 6 or 7 installed\n if ($version === 6 || $version === 7) {\n return new \\Aws\\Handler\\GuzzleV6\\GuzzleHandler();\n }\n\n // If Guzzle 5 installed\n if ($version === 5) {\n return new \\Aws\\Handler\\GuzzleV5\\GuzzleHandler();\n }\n\n throw new \\RuntimeException('Unknown Guzzle version: ' . $version);\n}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function before()\n {\n $className = $this->get_real_class($this);\n $controllerName = strtolower($className);\n\n // Create vulnerability service.\n if (!isset($this->pixie->vulnService)) {\n $this->vulninjection = $this->pixie->vulninjection->service($controllerName);\n $this->pixie->setVulnService($this->vulninjection);\n\n } else {\n $this->vulninjection = $this->pixie->vulnService;\n $this->pixie->vulnService->loadAndAddChildContext($controllerName);\n }\n\n $this->vulninjection->getConfig()->getCurrentContext()->setRequest($this->request);\n\n // Switch vulnerability config to the controller level\n $this->vulninjection->goDown($controllerName);\n\n if ($this->mustCheckSessionId()) {\n $actionContext = $this->vulninjection->getCurrentContext()->getOrCreateChildByName($this->request->param('action'));\n /** @var PHPSessionIdOverflow $sessVuln */\n $sessVuln = $actionContext->getVulnerability('PHPSessionIdOverflow');\n $sessVuln->fixSession();\n }\n\n if ($className == 'Install' && in_array($this->request->param('action'), ['index', 'login'])) {\n $this->installationProcess = true;\n }\n\n try {\n /** @var Connection $pdov */\n $this->pixie->db->get();\n \n } catch (\\Exception $e) {\n $this->pixie->session->set('isInstalled', false);\n if (!$this->installationProcess) {\n $this->redirect('/install');\n return;\n }\n }\n\n // Check Hackazon is installed\n if (!$this->installationProcess && !$this->pixie->session->get('isInstalled')) {\n try {\n /** @var Connection $pdov */\n $pdov = $this->pixie->db->get();\n /** @var \\PDO $conn */\n $conn = $pdov->conn;\n $res = $conn->query(\"SHOW TABLES\");\n $dbTables = $res->fetchAll();\n\n if (count($dbTables) < 20) {\n throw new \\Exception(\"Not all tables are existing\");\n }\n $this->pixie->session->set('isInstalled', true);\n\n } catch (\\Exception $e) {\n $this->pixie->session->set('isInstalled', false);\n $this->redirect('/install');\n return;\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "xatziandreoy_hackazon", "language": "php"} {"function": "public function rollback(): void\n {\n try {\n $this->persistenceHandler->rollback();\n } catch (Exception $e) {\n throw new RuntimeException($e->getMessage(), 0, $e);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function (string $databaseId, array $queries, string $search, Response $response, Database $dbForProject, string $mode) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $collectionId = $cursor->getValue();\n $cursorDocument = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Collection '{$collectionId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $response->dynamic(new Document([\n 'collections' => $dbForProject->find('database_' . $database->getInternalId(), $queries),\n 'total' => $dbForProject->count('database_' . $database->getInternalId(), $filterQueries, APP_LIMIT_COUNT),\n ]), Response::MODEL_COLLECTION_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function executeUpdateAction(DataObject $object, mixed $values): array\n {\n $data = ['success' => false];\n\n if ($object instanceof DataObject\\Concrete) {\n $object->setOmitMandatoryCheck(true);\n }\n\n // this prevents the user from renaming, relocating (actions in the tree) if the newest version isn't the published one\n // the reason is that otherwise the content of the newer not published version will be overwritten\n if ($object instanceof DataObject\\Concrete) {\n $latestVersion = $object->getLatestVersion();\n if ($latestVersion && $latestVersion->getData()->getModificationDate() != $object->getModificationDate()) {\n return ['success' => false, 'message' => \"You can't rename or relocate if there's a newer not published version\"];\n }\n }\n\n $key = $values['key'] ?? null;\n if ($key) {\n $key = Service::getValidKey($key, 'object');\n }\n\n if ($object->isAllowed('settings')) {\n if ($key) {\n if ($object->isAllowed('rename')) {\n $object->setKey($key);\n } elseif ($key !== $object->getKey()) {\n Logger::debug('prevented renaming object because of missing permissions ');\n }\n }\n\n if (!empty($values['parentId'])) {\n $parent = DataObject::getById($values['parentId']);\n\n //check if parent is changed\n if ($object->getParentId() != $parent->getId()) {\n if (!$parent->isAllowed('create')) {\n throw new \\Exception('Prevented moving object - no create permission on new parent ');\n }\n\n $objectWithSamePath = DataObject::getByPath($parent->getRealFullPath() . '/' . $object->getKey());\n\n if ($objectWithSamePath != null) {\n return ['success' => false, 'message' => 'prevented creating object because object with same path+key already exists'];\n }\n\n if ($object->isLocked()) {\n return ['success' => false, 'message' => 'prevented moving object, because it is locked: ID: ' . $object->getId()];\n }\n\n $object->setParentId($values['parentId']);\n }\n }\n\n if (array_key_exists('locked', $values)) {\n $object->setLocked($values['locked']);\n }\n\n $object->setModificationDate(time());\n $object->setUserModification($this->getAdminUser()->getId());\n\n try {\n $isIndexUpdate = isset($values['indices']);\n\n if ($isIndexUpdate) {\n // Ensure the update sort index is already available in the postUpdate eventListener\n $indexUpdate = is_int($values['indices']) ? $values['indices'] : $values['indices'][$object->getId()];\n $object->setIndex($indexUpdate);\n }\n\n $object->save();\n\n if ($isIndexUpdate) {\n $this->updateIndexesOfObjectSiblings($object, $indexUpdate);\n }\n\n $data = [\n 'success' => true,\n 'treeData' => $this->getTreeNodeConfig($object),\n ];\n } catch (\\Exception $e) {\n Logger::error((string) $e);\n\n return ['success' => false, 'message' => $e->getMessage()];\n }\n } elseif ($key && $object->isAllowed('rename')) {\n return $this->renameObject($object, $key);\n } else {\n Logger::debug('prevented update object because of missing permissions.');\n }\n\n return $data;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function save(string $path, string $format = null, int $quality = null): static\n {\n if (!$format) {\n $format = 'png32';\n }\n\n if ($format == 'original') {\n $format = $this->sourceImageFormat;\n }\n\n $format = strtolower($format);\n\n if ($format == 'png') {\n // we need to force imagick to create png32 images, otherwise this can cause some strange effects\n // when used with gray-scale images\n $format = 'png32';\n }\n\n $originalFilename = null;\n $i = $this->resource; // this is because of HHVM which has problems with $this->resource->writeImage();\n\n if (in_array($format, ['jpeg', 'pjpeg', 'jpg']) && $this->isAlphaPossible) {\n // set white background for transparent pixels\n $i->setImageBackgroundColor('#ffffff');\n\n if ($i->getImageAlphaChannel() !== 0) { // Note: returns (int) 0 if there's no AlphaChannel, PHP Docs are wrong. See: https://www.imagemagick.org/api/channel.php\n // Imagick version compatibility\n $alphaChannel = 11; // This works at least as far back as version 3.1.0~rc1-1\n if (defined('Imagick::ALPHACHANNEL_REMOVE')) {\n // Imagick::ALPHACHANNEL_REMOVE has been added in 3.2.0b2\n $alphaChannel = \\Imagick::ALPHACHANNEL_REMOVE;\n }\n $i->setImageAlphaChannel($alphaChannel);\n }\n\n $i->mergeImageLayers(\\Imagick::LAYERMETHOD_FLATTEN);\n }\n\n if (!$this->isPreserveMetaData()) {\n $i->stripImage();\n if ($format == 'png32') {\n // do not include any meta-data\n // this is due a bug in -strip, therefore we have to use this custom option\n // see also: https://github.com/ImageMagick/ImageMagick/issues/156\n $i->setOption('png:include-chunk', 'none');\n }\n }\n if (!$this->isPreserveColor()) {\n $i->profileImage('*', '');\n }\n\n if ($quality && !$this->isPreserveColor()) {\n $i->setCompressionQuality($quality);\n $i->setImageCompressionQuality($quality);\n }\n\n if ($format == 'tiff') {\n $i->setCompression(\\Imagick::COMPRESSION_LZW);\n }\n\n // force progressive JPEG if filesize >= 10k\n // normally jpeg images are bigger than 10k so we avoid the double compression (baseline => filesize check => if necessary progressive)\n // and check the dimensions here instead to faster generate the image\n // progressive JPEG - better compression, smaller filesize, especially for web optimization\n if ($format == 'jpeg' && !$this->isPreserveColor()) {\n if (($this->getWidth() * $this->getHeight()) > 35000) {\n $i->setInterlaceScheme(\\Imagick::INTERLACE_PLANE);\n }\n }\n\n // Imagick isn't able to work with custom stream wrappers, so we make a workaround\n $realTargetPath = null;\n if (!stream_is_local($path)) {\n $realTargetPath = $path;\n $path = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/imagick-tmp-' . uniqid() . '.' . pathinfo($path, PATHINFO_EXTENSION);\n }\n\n $filesystem = new Filesystem();\n if (!stream_is_local($path)) {\n $i->setImageFormat($format);\n $filesystem->dumpFile($path, $i->getImageBlob());\n $success = file_exists($path);\n } else {\n if ($this->checkPreserveAnimation($format, $i)) {\n $success = $i->writeImages('GIF:' . $path, true);\n } else {\n $success = $i->writeImage($format . ':' . $path);\n }\n }\n\n if (!$success) {\n throw new Exception('Unable to write image: ' . $path);\n }\n\n if ($realTargetPath) {\n $filesystem->rename($path, $realTargetPath, true);\n }\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function loadByLanguageCode($languageCode)\n {\n foreach ($this->languages as $language) {\n if ($language->languageCode == $languageCode) {\n return $language;\n }\n }\n throw new \\RuntimeException(\"Language $languageCode not found.\");\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $daysAgo = $input->getOption('older-than-days');\n\n if (!isset($daysAgo)) {\n throw new Exception('Missing option \"--older-than-days\"');\n } elseif (!is_numeric($daysAgo)) {\n throw new Exception('The \"--older-than-days\" option value should be numeric');\n }\n\n $date = new DateTime(\"-{$daysAgo} days\");\n $dateTimestamp = $date->getTimestamp();\n $recyclebinItems = new Recyclebin\\Item\\Listing();\n $recyclebinItems->setCondition(\"date < $dateTimestamp\");\n\n foreach ($recyclebinItems->load() as $recyclebinItem) {\n try {\n $recyclebinItem->delete();\n } catch (Exception $e) {\n $msg = \"Could not delete {$recyclebinItem->getPath()} ({$recyclebinItem->getId()}) because of: {$e->getMessage()}\";\n Logger::error($msg);\n $this->output->writeln($msg);\n }\n }\n\n $this->output->writeln('Recyclebin cleanup done!');\n\n return 0;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function import($path, $categoryLevels = 2)\n {\n $this->lastCategoryLevel = $categoryLevels - 1;\n\n if (!file_exists($path) || !is_dir($path) || !is_readable($path)) {\n throw new \\Exception('Product and category path is not accessible');\n }\n\n $this->result = [];\n $this->clearDatabase();\n $this->importCategory($this->getRoot(), $path);\n\n return $this->result;\n }", "smellKey": "S112", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "public function getTableRow(array $elementData): TableRow\n {\n if ($this->isEmpty()) {\n throw new \\Exception(\n sprintf(\n 'Table row with given data was not found! Keys: %s, Values: %s',\n implode(',', array_keys($elementData)),\n implode(',', array_values($elementData))\n )\n );\n }\n\n $searchedHeaders = array_keys($elementData);\n\n $allHeaders = $this->parentElement->findAll($this->getLocator('columnHeader'))\n ->mapBy(new ElementTextMapper());\n\n $foundHeaders = $this->getHeaderPositions($searchedHeaders, $allHeaders);\n $rowElement = $this->getMatchingTableRow($foundHeaders, $elementData);\n\n while (null === $rowElement && $this->pagination->isNextButtonActive()) {\n $this->pagination->clickNextButton();\n $rowElement = $this->getMatchingTableRow($foundHeaders, $elementData);\n }\n\n $cellLocators = [];\n foreach ($allHeaders as $headerPosition => $header) {\n $cellLocators[] = $this->getTableCellLocator($headerPosition, $header);\n }\n\n $filteredCellLocators = array_filter($cellLocators, static function (LocatorInterface $locator) {\n return '' !== $locator->getIdentifier();\n });\n\n if ($rowElement) {\n return $this->tableFactory->createRow($rowElement, new LocatorCollection($filteredCellLocators));\n }\n\n throw new \\Exception(\n sprintf(\n 'Table row with given data was not found! Keys: %s, Values: %s',\n implode(',', array_keys($elementData)),\n implode(',', array_values($elementData))\n )\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (App $utopia, Response $response, Request $request) {\n\n $result = [];\n $route = $utopia->getRoute();\n $path = APP_STORAGE_CACHE . '/tests.json';\n $tests = (\\file_exists($path)) ? \\json_decode(\\file_get_contents($path), true) : [];\n\n if (!\\is_array($tests)) {\n throw new Exception(Exception::GENERAL_MOCK, 'Failed to read results', 500);\n }\n\n $result[$route->getMethod() . ':' . $route->getPath()] = true;\n\n $tests = \\array_merge($tests, $result);\n\n if (!\\file_put_contents($path, \\json_encode($tests), LOCK_EX)) {\n throw new Exception(Exception::GENERAL_MOCK, 'Failed to save results', 500);\n }\n\n $response->dynamic(new Document(['result' => $route->getMethod() . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function getDatabaseProvider(): string {\n\t\t$platform = $this->inner->getDatabasePlatform();\n\t\tif ($platform instanceof MySQLPlatform) {\n\t\t\treturn IDBConnection::PLATFORM_MYSQL;\n\t\t} elseif ($platform instanceof OraclePlatform) {\n\t\t\treturn IDBConnection::PLATFORM_ORACLE;\n\t\t} elseif ($platform instanceof PostgreSQLPlatform) {\n\t\t\treturn IDBConnection::PLATFORM_POSTGRES;\n\t\t} elseif ($platform instanceof SqlitePlatform) {\n\t\t\treturn IDBConnection::PLATFORM_SQLITE;\n\t\t} else {\n\t\t\tthrow new \\Exception('Database ' . $platform::class . ' not supported');\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function messageMissingRequirement($type, $name)\n {\n switch ($type) {\n case 'ext':\n return sprintf(\n __('This plugin requires PHP extension %1$s'),\n $name\n );\n case 'plugin':\n return sprintf(\n __('This plugin requires %1$s plugin'),\n $name\n );\n case 'compil':\n return sprintf(\n __('This plugin requires PHP compiled along with \"%1$s\"'),\n $name\n );\n case 'param':\n return sprintf(\n __('This plugin requires PHP parameter %1$s'),\n $name\n );\n case 'glpiparam':\n return sprintf(\n __('This plugin requires GLPI parameter %1$s'),\n $name\n );\n default:\n throw new \\RuntimeException(\"messageMissing type $type is unknown!\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function getAppDataRootFolder(): Folder {\n\t\t$name = $this->getAppDataFolderName();\n\n\t\ttry {\n\t\t\t/** @var Folder $node */\n\t\t\t$node = $this->rootFolder->get($name);\n\t\t\treturn $node;\n\t\t} catch (NotFoundException $e) {\n\t\t\ttry {\n\t\t\t\treturn $this->rootFolder->newFolder($name);\n\t\t\t} catch (NotPermittedException $e) {\n\t\t\t\tthrow new \\RuntimeException('Could not get appdata folder');\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getStatistics(Request $request, Application $app)\n {\n $user = $this->getUserFromRequest($request);\n\n $aggregationUnit = $request->get('aggregation_unit', 'auto');\n\n $startDate = $this->getStringParam($request, 'start_date', true);\n $endDate = $this->getStringParam($request, 'end_date', true);\n\n $this->checkDateRange($startDate, $endDate);\n\n // This try/catch block is intended to replace the \"Base table or\n // view not found: 1146 Table 'modw_aggregates.jobfact_by_day'\n // doesn't exist\" error message with something more informative for\n // Open XDMoD users.\n try {\n $query = new \\DataWarehouse\\Query\\AggregateQuery(\n 'Jobs',\n $aggregationUnit,\n $startDate,\n $endDate,\n 'none',\n 'all'\n );\n\n $result = $query->execute();\n } catch (PDOException $e) {\n if ($e->getCode() === '42S02' && strpos($e->getMessage(), 'modw_aggregates.jobfact_by_') !== false) {\n $msg = 'Aggregate table not found, have you ingested your data?';\n throw new Exception($msg);\n } else {\n throw $e;\n }\n } catch (Exception $e) {\n throw new BadRequestHttpException($e->getMessage());\n }\n\n $rawRoles = XdmodConfiguration::assocArrayFactory('roles.json', CONFIG_DIR);\n\n $mostPrivileged = $user->getMostPrivilegedRole()->getName();\n $formats = $rawRoles['roles'][$mostPrivileged]['statistics_formats'];\n\n return $app->json(\n array(\n 'totalCount' => 1,\n 'success' => true,\n 'message' => '',\n 'formats' => $formats,\n 'data' => array($result)\n )\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function open($mode='a+') {\n if ($this->fp)\n return $this->fp;\n\n try {\n if (($file=$this->getFile())) {\n if (!($this->fp=fopen($file, $mode)))\n throw new Exception();\n } else {\n // We don't have a file create one in temp directory\n $prefix = Format::filename(Misc::randCode(6));\n if (!($temp=tempnam(sys_get_temp_dir(), $prefix))\n || !($this->fp=fopen($temp, $mode))\n || !($meta=stream_get_meta_data($this->fp))) {\n throw new Exception();\n }\n // get filename from mera\n $this->file = $meta['uri'];\n $this->init();\n }\n } catch(Exception $ex) {\n @fclose($this->fp);\n @unlink($temp);\n throw new Exception();\n }\n\n return $this->fp;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function createAttributeFromCollection(Database $database, string $collectionId, string $attributeId, string $from = null): void\n {\n $from ??= $collectionId;\n\n $collectionType = match ($this->project->getInternalId()) {\n 'console' => 'console',\n default => 'projects',\n };\n\n if ($from === 'files') {\n $collectionType = 'buckets';\n }\n\n $collection = $this->collections[$collectionType][$from] ?? null;\n\n if (is_null($collection)) {\n throw new Exception(\"Collection {$from} not found\");\n }\n\n $attributes = $collection['attributes'];\n\n $attributeKey = array_search($attributeId, array_column($attributes, '$id'));\n\n if ($attributeKey === false) {\n throw new Exception(\"Attribute {$attributeId} not found\");\n }\n\n $attribute = $attributes[$attributeKey];\n $filters = $attribute['filters'] ?? [];\n $default = $attribute['default'] ?? null;\n\n $database->createAttribute(\n collection: $collectionId,\n id: $attributeId,\n type: $attribute['type'],\n size: $attribute['size'],\n required: $attribute['required'] ?? false,\n default: in_array('json', $filters) ? json_encode($default) : $default,\n signed: $attribute['signed'] ?? false,\n array: $attribute['array'] ?? false,\n format: $attribute['format'] ?? '',\n formatOptions: $attribute['formatOptions'] ?? [],\n filters: $filters,\n );\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function actionSave($id = null)\n {\n $request = Yii::app()->request->getPost(\"CoursePlan\");\n $transaction = Yii::app()->db->beginTransaction();\n try {\n if ($id !== null) {\n $coursePlan = CoursePlan::model()->findByPk($id);\n $logSituation = \"U\";\n } else {\n $coursePlan = new CoursePlan;\n $coursePlan->school_inep_fk = Yii::app()->user->school;\n $coursePlan->users_fk = Yii::app()->user->loginInfos->id;\n $logSituation = \"C\";\n }\n $startTimestamp = $this->dataConverter($request[\"start_date\"], 0);\n $request[\"start_date\"] = $startTimestamp;\n $coursePlan->attributes = $request;\n $coursePlan->situation = 'PENDENTE';\n if ($coursePlan->save()) {\n TLog::info(\"Plano de aula salvo com sucesso\", ['CoursePlanId' => $coursePlan->id]);\n }\n $errors = $coursePlan->getErrors();\n $courseClassIds = [];\n $i = 1;\n foreach ($_POST[\"course-class\"] as $cc) {\n if ($cc[\"id\"] == \"\") {\n $courseClass = new CourseClass;\n $courseClass->course_plan_fk = $coursePlan->id;\n } else {\n $courseClass = CourseClass::model()->findByPk($cc[\"id\"]);\n }\n $courseClass->order = $i++;\n $courseClass->content = $cc['content'];\n $courseClass->methodology = $cc['methodology'];\n if ($courseClass->save()) {\n TLog::info(\"Aula salva com sucesso\", ['CourseClassId' => $courseClass->id, 'CoursePlanId' => $coursePlan->id]);\n }\n\n array_push($courseClassIds, $courseClass->id);\n\n CourseClassHasClassAbility::model()->deleteAll(\"course_class_fk = :course_class_fk and course_class_ability_fk not in ( '\" . implode(\"', '\", $cc['ability']) . \"' )\", [\":course_class_fk\" => $courseClass->id]);\n foreach ($cc[\"ability\"] as $abilityId) {\n $courseClassHasClassAbility = CourseClassHasClassAbility::model()->find(\"course_class_fk = :course_class_fk and course_class_ability_fk = :course_class_ability_fk\", [\"course_class_fk\" => $courseClass->id, \"course_class_ability_fk\" => $abilityId]);\n if ($courseClassHasClassAbility == null) {\n $courseClassHasClassAbility = new CourseClassHasClassAbility();\n $courseClassHasClassAbility->course_class_fk = $courseClass->id;\n $courseClassHasClassAbility->course_class_ability_fk = $abilityId;\n if ($courseClassHasClassAbility->save()) {\n TLog::info(\"CourseClassHasClassAbility salvo com sucesso\", ['CourseClassId' => $courseClass->id]);\n }\n $coursePlanVsAbility = new CoursePlanDisciplineVsAbilities();\n $coursePlanVsAbility->course_plan_fk = $coursePlan->id;\n $abilitieData = CourseClassAbilities::model()->findByPk($abilityId);\n $coursePlanVsAbility->discipline_fk = $abilitieData->edcenso_discipline_fk;\n $coursePlanVsAbility->course_class_fk = $courseClass->id;\n $coursePlanVsAbility->ability_fk = $abilityId;\n if ($coursePlanVsAbility->save()) {\n TLog::info(\"CoursePlanDisciplineVsAbilites salvo com sucesso\", ['CourseClassId' => $courseClass->id]);\n }\n }\n }\n\n if ($cc[\"resource\"] != null) {\n $idsArray = [];\n foreach ($cc[\"resource\"] as $r) {\n $courseClassHasClassResource = CourseClassHasClassResource::model()->find(\"id = :id\", [\"id\" => $r[\"id\"]]);\n if ($courseClassHasClassResource == null) {\n $courseClassHasClassResource = new CourseClassHasClassResource();\n $courseClassHasClassResource->course_class_fk = $courseClass->id;\n $courseClassHasClassResource->course_class_resource_fk = $r[\"value\"];\n }\n $courseClassHasClassResource->amount = $r[\"amount\"];\n if ($courseClassHasClassResource->save())\n TLog::info(\"CourseClassHasClassResource salvo com sucesso\", ['CourseClassId' => $courseClass->id]);\n array_push($idsArray, $courseClassHasClassResource->id);\n }\n CourseClassHasClassResource::model()->deleteAll(\"course_class_fk = :course_class_fk and id not in ( '\" . implode(\"', '\", $idsArray) . \"' )\", [\":course_class_fk\" => $courseClass->id]);\n TLog::info(\"Todos os recusos n\u00e3o relacionados a alguma habilidade foram deletados com sucesso\", $idsArray);\n } else {\n CourseClassHasClassResource::model()->deleteAll(\"course_class_fk = :course_class_fk\", [\":course_class_fk\" => $courseClass->id]);\n TLog::info(\"Todos os recursos foram deletados com sucesso\", ['CoursePlanId' => $coursePlan->id, 'CourseClassId' => $courseClass->id]);\n }\n }\n\n if (empty($courseClassIds)) {\n CourseClass::model()->deleteAll(\"course_plan_fk = :course_plan_fk\", [\":course_plan_fk\" => $coursePlan->id]);\n TLog::info(\"Todas as aulas foram deletadas com sucesso.\", ['coursePlanId' => $coursePlan->id, 'CourseClasses' => $courseClassIds]);\n } else {\n CourseClass::model()->deleteAll(\"course_plan_fk = :course_plan_fk and id not in ( '\" . implode(\"', '\", $courseClassIds) . \"' )\", [\":course_plan_fk\" => $coursePlan->id]);\n TLog::info(\"Todas as aulas n\u00e3o inclusas na atualiza\u00e7\u00e3o foram deletadas com sucesso.\", ['coursePlanId' => $coursePlan->id, 'CourseClassesIds' => $courseClassIds]);\n }\n $transaction->commit();\n header('HTTP/1.1 200 OK');\n Log::model()->saveAction(\"courseplan\", $id, $logSituation, $coursePlan->name);\n Yii::app()->user->setFlash('success', Yii::t('default', 'Plano de Curso salvo com sucesso!'));\n $this->redirect(array('index'));\n } catch (Exception $e) {\n TLog::error('Ocorreu um erro durante a transa\u00e7\u00e3o de salvar um plano de aula', $e);\n $transaction->rollback();\n throw new Exception($e->getMessage(), 500, $e);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function addChartToQueue($chartIdentifier, $chartTitle, $chartDrillDetails, $chartDateDesc) {\n\n if (empty($chartIdentifier)){\n throw new Exception(\"A chart identifier must be specified\");\n\t\t\t}\n\n if (empty($chartTitle)){\n throw new Exception(\"A chart title must be specified\");\n\t\t\t}\n\t\t\t\t\t\t\t\n // Since we are now letting the user have full control over the titles of charts (courtesy of the Metric Explorer),\n // we need to make sure the title is escaped properly such that the thumbnails in the Report Generator don't break.\n\t \n $chartIdentifier = str_replace(\"title=\".$chartTitle, \"title=\".urlencode($chartTitle), $chartIdentifier);\n\t \n if ($this->chartExistsInQueue($chartIdentifier)){\n throw new Exception(\"chart_exists_in_queue\");\n }\n\t\n $insertQuery = \"INSERT INTO {$this->_table_name} (user_id, chart_id, chart_title, chart_drill_details, chart_date_description, type) VALUES \" .\n \"(:user_id, :chart_id, :chart_title, :chart_drill_details, :chart_date_description, 'image')\";\n\t \n $this->_pdo->execute(\n $insertQuery, \n array(\n 'user_id' => $this->_user_id,\n 'chart_id' => $chartIdentifier,\n 'chart_title'=> $chartTitle, \n 'chart_date_description' => $chartDateDesc,\n 'chart_drill_details'=> $chartDrillDetails\n )\n );\n\t\t\n\t\t}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function save($filename)\n\t{\n\t\t// Initial Setting for saving\n\t\t$this->_BIG_BLOCK_SIZE = pow(2,\n\t\t\t\t\t ((isset($this->_BIG_BLOCK_SIZE))? self::_adjust2($this->_BIG_BLOCK_SIZE) : 9));\n\t\t$this->_SMALL_BLOCK_SIZE= pow(2,\n\t\t\t\t\t ((isset($this->_SMALL_BLOCK_SIZE))? self::_adjust2($this->_SMALL_BLOCK_SIZE): 6));\n\n\t\tif (is_resource($filename)) {\n\t\t $this->_FILEH_ = $filename;\n\t\t} else if ($filename == '-' || $filename == '') {\n\t\t\t$this->_tmp_filename = tempnam($this->_tmp_dir, \"OLE_PPS_Root\");\n\t\t\t$this->_FILEH_ = fopen($this->_tmp_filename,\"w+b\");\n\t\t\tif ($this->_FILEH_ == false) {\n\t\t\t\tthrow new Exception(\"Can't create temporary file.\");\n\t\t\t}\n\t\t} else {\n\t\t\t$this->_FILEH_ = fopen($filename, \"wb\");\n\t\t}\n\t\tif ($this->_FILEH_ == false) {\n\t\t\tthrow new Exception(\"Can't open $filename. It may be in use or protected.\");\n\t\t}\n\t\t// Make an array of PPS's (for Save)\n\t\t$aList = array();\n\t\t$this->_savePpsSetPnt($aList);\n\t\t// calculate values for header\n\t\tlist($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo);\n\t\t// Save Header\n\t\t$this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt);\n\n\t\t// Make Small Data string (write SBD)\n\t\t$this->_data = $this->_makeSmallData($aList);\n\n\t\t// Write BB\n\t\t$this->_saveBigData($iSBDcnt, $aList);\n\t\t// Write PPS\n\t\t$this->_savePps($aList);\n\t\t// Write Big Block Depot and BDList and Adding Header informations\n\t\t$this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt);\n\n\t\tif (!is_resource($filename)) {\n \t\t\tfclose($this->_FILEH_);\n \t\t}\n\n\t\treturn true;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function getLoggedInUser()\n{\n\n if (!isset($_SESSION['xdUser'])) {\n throw new \\SessionExpiredException();\n }\n\n $user = \\XDUser::getUserByID($_SESSION['xdUser']);\n\n if ($user == NULL) {\n throw new \\Exception('User does not exist');\n }\n\n return $user;\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private static function getExternalExecutable(string $name, bool $throwException = false): string|false\n {\n $executable = false;\n\n // use DI to provide the ability to customize / overwrite paths\n if (Pimcore::hasContainer() && Pimcore::getContainer()->hasParameter('pimcore_executable_' . $name)) {\n $executable = Pimcore::getContainer()->getParameter('pimcore_executable_' . $name);\n\n if ($executable === false && $throwException) {\n throw new Exception(\"'$name' executable was disabled manually in parameters.yml\");\n }\n }\n\n return $executable;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getCriterion(APILimitationValue $value, APIUserReference $currentUser)\n {\n if (empty($value->limitationValues)) {\n // A Policy should not have empty limitationValues stored\n throw new RuntimeException('$value->limitationValues is empty');\n }\n\n if (!isset($value->limitationValues[1])) {\n // 1 limitation value: EQ operation\n return new Criterion\\ObjectStateId($value->limitationValues[0]);\n }\n\n $groupedLimitationValues = $this->groupLimitationValues($value->limitationValues);\n\n if (count($groupedLimitationValues) === 1) {\n // one group, several limitation values: IN operation\n return new Criterion\\ObjectStateId($groupedLimitationValues[0]);\n }\n\n // limitations from different groups require logical AND between them\n $criterions = [];\n foreach ($groupedLimitationValues as $limitationGroup) {\n $criterions[] = new Criterion\\ObjectStateId($limitationGroup);\n }\n\n return new Criterion\\LogicalAnd($criterions);\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (string $ruleId, Response $response, Event $events, Document $project, Database $dbForConsole) {\n $rule = $dbForConsole->getDocument('rules', $ruleId);\n\n if ($rule->isEmpty() || $rule->getAttribute('projectInternalId') !== $project->getInternalId()) {\n throw new Exception(Exception::RULE_NOT_FOUND);\n }\n\n $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));\n\n if (!$target->isKnown() || $target->isTest()) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Domain target must be configured as environment variable.');\n }\n\n if ($rule->getAttribute('verification') === true) {\n return $response->dynamic($rule, Response::MODEL_PROXY_RULE);\n }\n\n $validator = new CNAME($target->get()); // Verify Domain with DNS records\n $domain = new Domain($rule->getAttribute('domain', ''));\n\n if (!$validator->isValid($domain->get())) {\n throw new Exception(Exception::RULE_VERIFICATION_FAILED);\n }\n\n $dbForConsole->updateDocument('rules', $rule->getId(), $rule->setAttribute('status', 'verifying'));\n\n // Issue a TLS certificate when domain is verified\n $event = new Certificate();\n $event\n ->setDomain(new Document([\n 'domain' => $rule->getAttribute('domain')\n ]))\n ->trigger();\n\n $events->setParam('ruleId', $rule->getId());\n\n $certificate = $dbForConsole->getDocument('certificates', $rule->getAttribute('certificateId', ''));\n $rule->setAttribute('logs', $certificate->getAttribute('logs', ''));\n\n $response->dynamic($rule, Response::MODEL_PROXY_RULE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $teamId, string $name, array $roles, Response $response, Document $user, Database $dbForProject, Event $events) {\n\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n $isAppUser = Auth::isAppUser(Authorization::getRoles());\n\n $teamId = $teamId == 'unique()' ? ID::unique() : $teamId;\n\n try {\n $team = Authorization::skip(fn() => $dbForProject->createDocument('teams', new Document([\n '$id' => $teamId,\n '$permissions' => [\n Permission::read(Role::team($teamId)),\n Permission::update(Role::team($teamId, 'owner')),\n Permission::delete(Role::team($teamId, 'owner')),\n ],\n 'name' => $name,\n 'total' => ($isPrivilegedUser || $isAppUser) ? 0 : 1,\n 'prefs' => new \\stdClass(),\n 'search' => implode(' ', [$teamId, $name]),\n ])));\n } catch (Duplicate $th) {\n throw new Exception(Exception::TEAM_ALREADY_EXISTS);\n }\n\n if (!$isPrivilegedUser && !$isAppUser) { // Don't add user on server mode\n if (!\\in_array('owner', $roles)) {\n $roles[] = 'owner';\n }\n\n $membershipId = ID::unique();\n $membership = new Document([\n '$id' => $membershipId,\n '$permissions' => [\n Permission::read(Role::user($user->getId())),\n Permission::read(Role::team($team->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::update(Role::team($team->getId(), 'owner')),\n Permission::delete(Role::user($user->getId())),\n Permission::delete(Role::team($team->getId(), 'owner')),\n ],\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'teamId' => $team->getId(),\n 'teamInternalId' => $team->getInternalId(),\n 'roles' => $roles,\n 'invited' => DateTime::now(),\n 'joined' => DateTime::now(),\n 'confirm' => true,\n 'secret' => '',\n 'search' => implode(' ', [$membershipId, $user->getId()])\n ]);\n\n $membership = $dbForProject->createDocument('memberships', $membership);\n $dbForProject->deleteCachedDocument('users', $user->getId());\n }\n\n $events->setParam('teamId', $team->getId());\n\n if (!empty($user->getId())) {\n $events->setParam('userId', $user->getId());\n }\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($team, Response::MODEL_TEAM);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $functionId, string $variableId, Response $response, Database $dbForProject) {\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $variable = $dbForProject->getDocument('variables', $variableId);\n if (\n $variable === false ||\n $variable->isEmpty() ||\n $variable->getAttribute('resourceInternalId') !== $function->getInternalId() ||\n $variable->getAttribute('resourceType') !== 'function'\n ) {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n if ($variable === false || $variable->isEmpty()) {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n $response->dynamic($variable, Response::MODEL_VARIABLE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function ($request) {\n //TODO: Move this to the Request class itself\n $timestampHeader = $request->getHeader('x-appwrite-timestamp');\n $requestTimestamp = null;\n if (!empty($timestampHeader)) {\n try {\n $requestTimestamp = new \\DateTime($timestampHeader);\n } catch (\\Throwable $e) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid X-Appwrite-Timestamp header value');\n }\n }\n return $requestTimestamp;\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function load(Asset\\Document $asset): static\n {\n // avoid timeouts\n $maxExecTime = (int) ini_get('max_execution_time');\n if ($maxExecTime > 1 && $maxExecTime < 250) {\n set_time_limit(250);\n }\n\n if (!$this->isFileTypeSupported($asset->getFilename())) {\n $message = \"Couldn't load document \" . $asset->getRealFullPath() . ' only Microsoft/Libre/Open-Office/PDF documents are currently supported';\n Logger::error($message);\n\n throw new Exception($message);\n }\n\n $this->asset = $asset;\n\n // first we have to create a pdf out of the document (if it isn't already one), so that we can pass it to ghostscript\n // unfortunately there isn't any other way at the moment\n if (!preg_match(\"/\\.?pdf$/i\", $asset->getFilename())) {\n if (!parent::isFileTypeSupported($asset->getFilename())) {\n $this->getPdf();\n }\n }\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function correctPath(): void\n {\n // set path\n if ($this->getId() != 1) { // not for the root node\n // check for a valid key, home has no key, so omit the check\n if (!Element\\Service::isValidKey($this->getKey(), 'document')) {\n throw new Exception('invalid key for document with id [ ' . $this->getId() . ' ] key is: [' . $this->getKey() . ']');\n }\n\n if (!$this->getParentId()) {\n throw new Exception('ParentID is mandatory and can\u00b4t be null. If you want to add the element as a child to the tree\u00b4s root node, consider setting ParentID to 1.');\n }\n\n if ($this->getParentId() == $this->getId()) {\n throw new Exception(\"ParentID and ID are identical, an element can't be the parent of itself in the tree.\");\n }\n\n $parent = Document::getById($this->getParentId());\n if (!$parent) {\n throw new Exception('ParentID not found.');\n }\n\n // use the parent's path from the database here (getCurrentFullPath), to ensure the path really exists and does not rely on the path\n // that is currently in the parent object (in memory), because this might have changed but wasn't not saved\n $this->setPath(str_replace('//', '/', $parent->getCurrentFullPath() . '/'));\n\n if (strlen($this->getKey()) < 1) {\n throw new Exception('Document requires key, generated key automatically');\n }\n } elseif ($this->getId() == 1) {\n // some data in root node should always be the same\n $this->setParentId(0);\n $this->setPath('/');\n $this->setKey('');\n $this->setType('page');\n }\n\n if (Document\\Service::pathExists($this->getRealFullPath())) {\n $duplicate = Document::getByPath($this->getRealFullPath());\n if ($duplicate instanceof Document && $duplicate->getId() != $this->getId()) {\n $duplicateFullPathException = new DuplicateFullPathException('Duplicate full path [ ' . $this->getRealFullPath() . ' ] - cannot save document');\n $duplicateFullPathException->setDuplicateElement($duplicate);\n $duplicateFullPathException->setCauseElement($this);\n\n throw $duplicateFullPathException;\n }\n }\n\n $this->validatePathLength();\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function tryAddHeader()\n {\n if ($this->ordered_headers !== null) {\n throw new \\Exception('Implementation error: must define all headers before any row');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function renderDialogBoxEditables(array|Document\\Editable $config, EditableRenderer $editableRenderer, string $dialogId, string &$html): array\n {\n if ($config instanceof BlockInterface || $config instanceof Area) {\n // Unsupported element was passed (e.g., Block, Areablock, ...)\n // or an Areas was passed, which is not supported to avoid too long editable names\n throw new Exception(sprintf('Using editables of type \"%s\" for the editable dialog \"%s\" is not supported.', get_debug_type($config), $dialogId));\n } elseif ($config instanceof Document\\Editable) {\n // Map editable to array config\n $config = [\n 'type' => $config->getType(),\n 'name' => $config->getName(),\n 'label' => $config->getLabel(),\n 'config' => $config->getConfig(),\n 'description' => $config->getDialogDescription(),\n ];\n }\n\n if (isset($config['items']) && is_array($config['items'])) {\n // layout component\n foreach ($config['items'] as $index => $child) {\n $config['items'][$index] = $this->renderDialogBoxEditables($child, $editableRenderer, $dialogId, $html);\n }\n } elseif (isset($config['name']) && isset($config['type'])) {\n $editable = $editableRenderer->getEditable($this->getDocument(), $config['type'], $config['name'], $config['config'] ?? []);\n if (!$editable instanceof Document\\Editable) {\n throw new Exception(sprintf('Invalid editable type \"%s\" configured for Dialog Box', $config['type']));\n }\n\n $editable->setInDialogBox($dialogId);\n $editable->addConfig('dialogBoxConfig', $config);\n $html .= $editable->render();\n } else {\n foreach ($config as $index => $item) {\n $config['items'][$index] = $this->renderDialogBoxEditables($item, $editableRenderer, $dialogId, $html);\n }\n }\n\n return $config;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function write(Profile $profile): bool\n {\n $file = $this->getFilename($profile->getToken());\n\n $profileIndexed = is_file($file);\n\n if (!$profileIndexed) {\n // Create directory\n $dir = dirname($file);\n\n if (!is_dir($dir) && @mkdir($dir, 0777, true) === false && !is_dir($dir)) {\n throw new RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));\n }\n }\n\n $data = $this->getDataByProfile($profile);\n\n if (file_put_contents($file, $data, LOCK_EX) === false) {\n return false;\n }\n\n if (!$profileIndexed) {\n $file = fopen($this->getIndexFilename(), 'a');\n\n // Add to index\n if ($file === false) {\n return false;\n }\n\n fputcsv($file, [\n $profile->getToken(),\n $profile->getIp(),\n $profile->getMethod(),\n $profile->getUrl(),\n $profile->getTime(),\n $profile->getParentToken(),\n $profile->getStatusCode(),\n ]);\n fclose($file);\n }\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function (string $functionId, string $variableId, Response $response, Database $dbForProject, Database $dbForConsole) {\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $variable = $dbForProject->getDocument('variables', $variableId);\n if ($variable === false || $variable->isEmpty() || $variable->getAttribute('resourceInternalId') !== $function->getInternalId() || $variable->getAttribute('resourceType') !== 'function') {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n if ($variable === false || $variable->isEmpty()) {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n $dbForProject->deleteDocument('variables', $variable->getId());\n\n $dbForProject->updateDocument('functions', $function->getId(), $function->setAttribute('live', false));\n\n // Inform scheduler to pull the latest changes\n $schedule = $dbForConsole->getDocument('schedules', $function->getAttribute('scheduleId'));\n $schedule\n ->setAttribute('resourceUpdatedAt', DateTime::now())\n ->setAttribute('schedule', $function->getAttribute('schedule'))\n ->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deployment')));\n Authorization::skip(fn () => $dbForConsole->updateDocument('schedules', $schedule->getId(), $schedule));\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function up(): void\n {\n $teams = config('permission.teams');\n $tableNames = config('permission.table_names');\n $columnNames = config('permission.column_names');\n $pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';\n $pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';\n\n if (empty($tableNames)) {\n throw new Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');\n }\n\n if ($teams && empty($columnNames['team_foreign_key'] ?? null)) {\n throw new Exception('Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');\n }\n\n Schema::create($tableNames['permissions'], function (Blueprint $table) {\n //$table->engine('InnoDB');\n $table->uuid('id')->primary(); // permission id\n $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)\n $table->string('guard_name'); // For MyISAM use string('guard_name', 25);\n $table->timestamps();\n\n $table->unique(['name', 'guard_name']);\n });\n\n Schema::create($tableNames['roles'], function (Blueprint $table) use ($teams, $columnNames) {\n //$table->engine('InnoDB');\n $table->uuid('id')->primary(); // role id\n\n if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing\n $table->uuid($columnNames['team_foreign_key'])->nullable();\n $table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');\n }\n $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)\n $table->string('guard_name'); // For MyISAM use string('guard_name', 25);\n $table->timestamps();\n\n if ($teams || config('permission.testing')) {\n $table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);\n } else {\n $table->unique(['name', 'guard_name']);\n }\n });\n\n Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {\n $table->uuid($pivotPermission);\n\n $table->string('model_type');\n $table->uuid($columnNames['model_morph_key']);\n $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');\n\n $table->foreign($pivotPermission)\n ->references('id') // permission id\n ->on($tableNames['permissions'])\n ->onDelete('cascade');\n\n if ($teams) {\n $table->uuid($columnNames['team_foreign_key']);\n $table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');\n\n $table->primary(\n [$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_permissions_permission_model_type_primary'\n );\n } else {\n $table->primary(\n [$pivotPermission, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_permissions_permission_model_type_primary'\n );\n }\n });\n\n Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {\n $table->uuid($pivotRole);\n\n $table->string('model_type');\n $table->uuid($columnNames['model_morph_key']);\n $table->string('via')->default('direct');\n $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');\n\n $table->foreign($pivotRole)\n ->references('id') // role id\n ->on($tableNames['roles'])\n ->onDelete('cascade');\n\n if ($teams) {\n $table->uuid($columnNames['team_foreign_key']);\n $table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');\n\n $table->primary(\n [$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_roles_role_model_type_primary'\n );\n } else {\n $table->primary(\n [$pivotRole, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_roles_role_model_type_primary'\n );\n }\n });\n\n Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {\n $table->uuid($pivotPermission);\n $table->uuid($pivotRole);\n\n $table->foreign($pivotPermission)\n ->references('id') // permission id\n ->on($tableNames['permissions'])\n ->onDelete('cascade');\n\n $table->foreign($pivotRole)\n ->references('id') // role id\n ->on($tableNames['roles'])\n ->onDelete('cascade');\n\n $table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');\n });\n\n app('cache')\n ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)\n ->forget(config('permission.cache.key'));\n }", "smellKey": "S112", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public static function tearDownAfterClass(): void\n {\n parent::tearDownAfterClass();\n\n foreach (static::$testConfigFiles as $file) {\n // The file may not exist because this function is run twice due to\n // the use of `@runInSeparateProcess`.\n if (file_exists($file) && !unlink($file)) {\n throw new Exception(\"Failed to remove file '$file'\");\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function getImageValue(Content $content): Value\n {\n $imageFieldIdentifier = $this->getImageFieldIdentifier($content->getContentType()->identifier);\n $value = $content->getFieldValue($imageFieldIdentifier);\n\n if (null === $value) {\n throw new RuntimeException(\n sprintf(\n 'Missing field with identifier: \"%s\"',\n $imageFieldIdentifier\n )\n );\n }\n\n if (!$value instanceof Value) {\n throw new RuntimeException(\n sprintf(\n 'Field value should be of type %s. \"%s\" given.',\n Value::class,\n get_debug_type($value)\n )\n );\n }\n\n return $value;\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (string $variableId, string $key, ?string $value, Document $project, Response $response, Database $dbForProject, Database $dbForConsole) {\n $variable = $dbForProject->getDocument('variables', $variableId);\n if ($variable === false || $variable->isEmpty() || $variable->getAttribute('resourceType') !== 'project') {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n $variable\n ->setAttribute('key', $key)\n ->setAttribute('value', $value ?? $variable->getAttribute('value'))\n ->setAttribute('search', implode(' ', [$variableId, $key, 'project']));\n\n try {\n $dbForProject->updateDocument('variables', $variable->getId(), $variable);\n } catch (DuplicateException $th) {\n throw new Exception(Exception::VARIABLE_ALREADY_EXISTS);\n }\n\n $functions = $dbForProject->find('functions', [\n Query::limit(APP_LIMIT_SUBQUERY)\n ]);\n\n foreach ($functions as $function) {\n $dbForProject->updateDocument('functions', $function->getId(), $function->setAttribute('live', false));\n }\n\n $response->dynamic($variable, Response::MODEL_VARIABLE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function writeStream(string $path, $stream, ?int $size = null): int {\n\t\tif ($size === null) {\n\t\t\t$stream = CountWrapper::wrap($stream, function (int $writtenSize) use (&$size) {\n\t\t\t\t$size = $writtenSize;\n\t\t\t});\n\t\t\tif (!$stream) {\n\t\t\t\tthrow new \\Exception(\"Failed to wrap stream\");\n\t\t\t}\n\t\t}\n\t\t/** @psalm-suppress InternalMethod */\n\t\t$result = $this->getConnection()->put($this->absPath($path), $stream);\n\t\tfclose($stream);\n\t\tif ($result) {\n\t\t\treturn $size;\n\t\t} else {\n\t\t\tthrow new \\Exception(\"Failed to write steam to sftp storage\");\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setZoomScale($pValue = 100) {\n\t\t// Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,\n\t\t// but it is apparently still able to handle any scale >= 1\n\t\tif (($pValue >= 1) || is_null($pValue)) {\n\t\t\t$this->_zoomScale = $pValue;\n\t\t} else {\n\t\t\tthrow new Exception(\"Scale must be greater than or equal to 1.\");\n\t\t}\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "protected function saveElement(Element\\ElementInterface $element): void\n {\n try {\n $element->save();\n } catch (Exception $e) {\n throw new Exception('Unable to save ' . Element\\Service::getElementType($element) . ' with id ' . $element->getId() . ' because of the following reason: ' . $e->getMessage());\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getCurrentProgress(string $key): SessionProgress\n {\n if (!$this->hasProgress($key)) {\n throw new \\RuntimeException(\\sprintf(\n \"Cannot find a progress bar for key \\\"%s\\\".\",\n $key,\n ));\n }\n\n Session::start();\n\n $progress = $_SESSION['progress'][$key];\n\n session_write_close();\n\n if (!$progress instanceof SessionProgress) {\n throw new \\RuntimeException(\\sprintf(\n \"Stored progress bar value with key \\\"%s\\\" is invalid.\",\n $key,\n ));\n }\n\n return $progress;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function RollbackTransaction($connection)\n {\n throw new Exception('Transaction support is not implemented for this DataDriver');\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function parseDate(array $item): array\n {\n $result = null;\n $property = $this->getDbProperty($item);\n $value = new Carbon($item[self::KEY_VALUE]);\n\n switch ($item[self::KEY_OPERATOR]) {\n case self::OPERATOR_EQ:\n $key = $property . '_eq';\n $result = [\n $key,\n \"{$property} BETWEEN :{$key}_start AND :{$key}_end\",\n [\n $key . '_start' => $value->toDateTimeString(),\n $key . '_end' => $value->addDay()->subSecond()->toDateTimeString(),\n ],\n ];\n\n break;\n case self::OPERATOR_GT:\n $key = $property . '_gt';\n $result = [\n $key,\n \"{$property} > :{$key}\",\n [$key => $value->toDateTimeString()],\n ];\n\n break;\n case self::OPERATOR_LT:\n $key = $property . '_lt';\n $result = [\n $key,\n \"{$property} < :{$key}\",\n [$key => $value->addDay()->subSecond()->toDateTimeString()],\n ];\n\n break;\n }\n\n if (is_null($result)) {\n throw new Exception();\n }\n\n return $result;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct(LoggerInterface $logger = null)\n {\n // Must set properties that are used in `setLogger` before calling the\n // parent constructor.\n $this->fileWriterFactory = new FileWriterFactory($logger);\n parent::__construct($logger);\n\n $this->rawStatsConfig = RawStatisticsConfiguration::factory();\n\n try {\n $this->exportDir = xd_utilities\\getConfiguration(\n 'data_warehouse_export',\n 'export_directory'\n );\n } catch (Exception $e) {\n $this->logger->err([\n 'module' => self::LOG_MODULE,\n 'message' => $e->getMessage(),\n 'stacktrace' => $e->getTraceAsString()\n ]);\n throw new Exception('Export directory is not configured', 0, $e);\n }\n\n if (!is_dir($this->exportDir)) {\n throw new Exception(sprintf(\n 'Export directory \"%s\" does not exist',\n $this->exportDir\n ));\n }\n\n if (!is_readable($this->exportDir)) {\n throw new Exception(sprintf(\n 'Export directory \"%s\" is not readable',\n $this->exportDir\n ));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function launchRequest(array $options)\n {\n // Check for mandatory parameters in the options.\n if (!array_key_exists('route', $options)) {\n throw new \\Exception('Must provide a route for an internal REST request.');\n }\n if (!array_key_exists('method', $options)) {\n throw new \\Exception('Must provide a request method to make an internal REST request.');\n }\n if (!array_key_exists('user', $options) || !($options['user'] instanceof \\XDUser)) {\n throw new \\Exception('Must provide a user to launch an internal REST request.');\n }\n\n // Get optional parameters from the options.\n $params = array_key_exists('params', $options) ? $options['params'] : array();\n $content = array_key_exists('content', $options) ? $options['content'] : null;\n $cookies = array_key_exists('cookies', $options) ? $options['cookies'] : $_COOKIE;\n $files = array_key_exists('files', $options) ? $options['files'] : $_FILES;\n $server = array_key_exists('server', $options) ? $options['server'] : $_SERVER;\n $catch = array_key_exists('catch', $options) ? $options['catch'] : false;\n $returnResponse = array_key_exists('returnResponse', $options) ? $options['returnResponse'] : false;\n $decodeResponse = array_key_exists('decodeResponse', $options) ? $options['decodeResponse'] : true;\n\n // Get the instance of the REST API application.\n $app = XdmodApplicationFactory::getInstance();\n\n // Create a request object using the given options.\n $route = $options['route'];\n if (!\\xd_utilities\\string_begins_with($route, '/')) {\n $route = \"/$route\";\n }\n $request = Request::create(\n $route,\n $options['method'],\n $params,\n $cookies,\n $files,\n $server,\n $content\n );\n $request->attributes->set(BaseControllerProvider::_USER, $options['user']);\n\n // Determine the type of request by checking if an existing request\n // is accessible. If it is, the type of request to launch is a sub-request.\n // Otherwise, a master request needs to be launched.\n $request_level = HttpKernelInterface::MASTER_REQUEST;\n try {\n $existing_request = $app['request'];\n $request_level = HttpKernelInterface::SUB_REQUEST;\n } catch (\\Exception $e) {\n\n }\n\n // Launch the request.\n $response = $app->handle($request, $request_level, $catch);\n\n // If the response object was requested, return it.\n if ($returnResponse) {\n return $response;\n }\n\n // Retrieve the encoded content from the response object.\n $encodedContent = $response->getContent();\n\n // If decoding was not requested, simply return the encoded contents.\n if (!$decodeResponse) {\n return $encodedContent;\n }\n\n // Get and return the decoded content of the response.\n // Use the encoded content as the return value, if all else fails.\n $decodedContent = $encodedContent;\n\n // If the original content is provided in the response, use that as\n // the decoded content to return. Otherwise, attempt to decode the\n // response contents.\n if (property_exists($response, 'originalContent')) {\n $decodedContent = $response->originalContent;\n } else {\n $contentType = $response->headers->get('Content-Type');\n if ($contentType === 'application/json') {\n $decodedContent = json_decode($encodedContent);\n }\n }\n\n return $decodedContent;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function getConfigInstance(string $file): array\n {\n $fileType = pathinfo($file, PATHINFO_EXTENSION);\n if (file_exists($file)) {\n if ($fileType == 'yaml') {\n $content = Yaml::parseFile($file);\n } else {\n $content = include($file);\n }\n\n if (is_array($content)) {\n return $content;\n }\n } else {\n throw new Exception($file . \" doesn't exist\");\n }\n\n throw new Exception($file . ' is invalid');\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function shredLine($line)\n {\n throw new Exception('Shredder subclass must implement shredLine');\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function start($callback = null)\n {\n if ($this->isRunning()) {\n throw new \\RuntimeException('Process is already running');\n }\n if ($this->outputDisabled && null !== $callback) {\n throw new \\LogicException('Output has been disabled, enable it to allow the use of a callback.');\n }\n\n $this->resetProcessData();\n $this->starttime = $this->lastOutputTime = microtime(true);\n $this->callback = $this->buildCallback($callback);\n $descriptors = $this->getDescriptors();\n\n $commandline = $this->commandline;\n\n if ('\\\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {\n $commandline = 'cmd /V:ON /E:ON /C \"(' . $commandline . ')';\n foreach ($this->processPipes->getFiles() as $offset => $filename) {\n $commandline .= ' ' . $offset . '>' . Utils::escapeArgument($filename);\n }\n $commandline .= '\"';\n\n if (!isset($this->options['bypass_shell'])) {\n $this->options['bypass_shell'] = true;\n }\n }\n\n $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);\n\n if (!is_resource($this->process)) {\n throw new \\RuntimeException('Unable to launch a new process.');\n }\n $this->status = self::STATUS_STARTED;\n\n if ($this->tty) {\n return;\n }\n\n $this->updateStatus(false);\n $this->checkTimeout();\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "private function getDataSet(array $request, XDUser $user)\n {\n $this->logger->info([\n 'module' => self::LOG_MODULE,\n 'message' => 'Querying data',\n 'Users.id' => $user->getUserID(),\n 'user_email' => $user->getEmailAddress(),\n 'user_first_name' => $user->getFirstName(),\n 'user_last_name' => $user->getLastName(),\n 'batch_export_request.id' => $request['id'],\n 'realm' => $request['realm'],\n 'start_date' => $request['start_date'],\n 'end_date' => $request['end_date']\n ]);\n\n try {\n $className = $this->realmManager->getRawDataQueryClass($request['realm']);\n $this->logger->debug([\n 'module' => self::LOG_MODULE,\n 'message' => sprintf('Instantiating query class \"%s\"', $className)\n ]);\n $query = new $className(\n [\n 'start_date' => $request['start_date'],\n 'end_date' => $request['end_date']\n ],\n 'batch'\n );\n $dataSet = new BatchDataset($query, $user, $this->logger);\n return $dataSet;\n } catch (Exception $e) {\n $this->logger->err([\n 'module' => self::LOG_MODULE,\n 'message' => $e->getMessage(),\n 'stacktrace' => $e->getTraceAsString()\n ]);\n throw new Exception('Failed to create batch export query', 0, $e);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setEndDate($date)\n {\n if ( null === $date ) {\n $this->endDate = null;\n } else {\n if ( false === ($ts = strtotime($date)) ) {\n $msg = get_class($this) . \": Could not parse end date '$date'\";\n throw new Exception($msg);\n }\n\n $this->endDate = date(\"Y-m-d H:i:s\", $ts);\n }\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $teamId, string $email, string $userId, string $phone, array $roles, string $url, string $name, Response $response, Document $project, Document $user, Database $dbForProject, Locale $locale, Mail $mails, EventPhone $messaging, Event $events) {\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if (empty($url)) {\n if (!$isAPIKey && !$isPrivilegedUser) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'URL is required');\n }\n }\n\n if (empty($userId) && empty($email) && empty($phone)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'At least one of userId, email, or phone is required');\n }\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n $isAppUser = Auth::isAppUser(Authorization::getRoles());\n\n if (!$isPrivilegedUser && !$isAppUser && empty(App::getEnv('_APP_SMTP_HOST'))) {\n throw new Exception(Exception::GENERAL_SMTP_DISABLED);\n }\n\n $email = \\strtolower($email);\n $name = (empty($name)) ? $email : $name;\n $team = $dbForProject->getDocument('teams', $teamId);\n\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n if (!empty($userId)) {\n $invitee = $dbForProject->getDocument('users', $userId);\n if ($invitee->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND, 'User with given userId doesn\\'t exist.', 404);\n }\n if (!empty($email) && $invitee->getAttribute('email', '') !== $email) {\n throw new Exception(Exception::USER_ALREADY_EXISTS, 'Given userId and email doesn\\'t match', 409);\n }\n if (!empty($phone) && $invitee->getAttribute('phone', '') !== $phone) {\n throw new Exception(Exception::USER_ALREADY_EXISTS, 'Given userId and phone doesn\\'t match', 409);\n }\n $email = $invitee->getAttribute('email', '');\n $phone = $invitee->getAttribute('phone', '');\n $name = empty($name) ? $invitee->getAttribute('name', '') : $name;\n } elseif (!empty($email)) {\n $invitee = $dbForProject->findOne('users', [Query::equal('email', [$email])]); // Get user by email address\n if (!empty($invitee) && !empty($phone) && $invitee->getAttribute('phone', '') !== $phone) {\n throw new Exception(Exception::USER_ALREADY_EXISTS, 'Given email and phone doesn\\'t match', 409);\n }\n } elseif (!empty($phone)) {\n $invitee = $dbForProject->findOne('users', [Query::equal('phone', [$phone])]);\n if (!empty($invitee) && !empty($email) && $invitee->getAttribute('email', '') !== $email) {\n throw new Exception(Exception::USER_ALREADY_EXISTS, 'Given phone and email doesn\\'t match', 409);\n }\n }\n\n if (empty($invitee)) { // Create new user if no user with same email found\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0 && $project->getId() !== 'console') { // check users limit, console invites are allways allowed.\n $total = $dbForProject->count('users', [], APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n throw new Exception(Exception::USER_COUNT_EXCEEDED, 'Project registration is restricted. Contact your administrator for more information.');\n }\n }\n\n // Makes sure this email is not already used in another identity\n $identityWithMatchingEmail = $dbForProject->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n if ($identityWithMatchingEmail !== false && !$identityWithMatchingEmail->isEmpty()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n try {\n $userId = ID::unique();\n $invitee = Authorization::skip(fn() => $dbForProject->createDocument('users', new Document([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::read(Role::user($userId)),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => empty($email) ? null : $email,\n 'phone' => empty($phone) ? null : $phone,\n 'emailVerification' => false,\n 'status' => true,\n 'password' => Auth::passwordHash(Auth::passwordGenerator(), Auth::DEFAULT_ALGO, Auth::DEFAULT_ALGO_OPTIONS),\n 'hash' => Auth::DEFAULT_ALGO,\n 'hashOptions' => Auth::DEFAULT_ALGO_OPTIONS,\n /**\n * Set the password update time to 0 for users created using\n * team invite and OAuth to allow password updates without an\n * old password\n */\n 'passwordUpdate' => null,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'name' => $name,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => implode(' ', [$userId, $email, $name]),\n ])));\n } catch (Duplicate $th) {\n throw new Exception(Exception::USER_ALREADY_EXISTS);\n }\n }\n\n $isOwner = Authorization::isRole('team:' . $team->getId() . '/owner');\n\n if (!$isOwner && !$isPrivilegedUser && !$isAppUser) { // Not owner, not admin, not app (server)\n throw new Exception(Exception::USER_UNAUTHORIZED, 'User is not allowed to send invitations for this team');\n }\n\n $secret = Auth::tokenGenerator();\n\n $membershipId = ID::unique();\n $membership = new Document([\n '$id' => $membershipId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($invitee->getId())),\n Permission::update(Role::team($team->getId(), 'owner')),\n Permission::delete(Role::user($invitee->getId())),\n Permission::delete(Role::team($team->getId(), 'owner')),\n ],\n 'userId' => $invitee->getId(),\n 'userInternalId' => $invitee->getInternalId(),\n 'teamId' => $team->getId(),\n 'teamInternalId' => $team->getInternalId(),\n 'roles' => $roles,\n 'invited' => DateTime::now(),\n 'joined' => ($isPrivilegedUser || $isAppUser) ? DateTime::now() : null,\n 'confirm' => ($isPrivilegedUser || $isAppUser),\n 'secret' => Auth::hash($secret),\n 'search' => implode(' ', [$membershipId, $invitee->getId()])\n ]);\n\n if ($isPrivilegedUser || $isAppUser) { // Allow admin to create membership\n try {\n $membership = Authorization::skip(fn() => $dbForProject->createDocument('memberships', $membership));\n } catch (Duplicate $th) {\n throw new Exception(Exception::TEAM_INVITE_ALREADY_EXISTS);\n }\n $team->setAttribute('total', $team->getAttribute('total', 0) + 1);\n $team = Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team));\n\n $dbForProject->deleteCachedDocument('users', $invitee->getId());\n } else {\n try {\n $membership = $dbForProject->createDocument('memberships', $membership);\n } catch (Duplicate $th) {\n throw new Exception(Exception::TEAM_INVITE_ALREADY_EXISTS);\n }\n\n $url = Template::parseURL($url);\n $url['query'] = Template::mergeQuery(((isset($url['query'])) ? $url['query'] : ''), ['membershipId' => $membership->getId(), 'userId' => $invitee->getId(), 'secret' => $secret, 'teamId' => $teamId]);\n $url = Template::unParseURL($url);\n if (!empty($email)) {\n $projectName = $project->isEmpty() ? 'Console' : $project->getAttribute('name', '[APP-NAME]');\n\n $body = $locale->getText(\"emails.invitation.body\");\n $subject = \\sprintf($locale->getText(\"emails.invitation.subject\"), $team->getAttribute('name'), $projectName);\n $customTemplate = $project->getAttribute('templates', [])['email.invitation-' . $locale->default] ?? [];\n\n $message = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-inner-base.tpl');\n $message->setParam('{{body}}', $body);\n $body = $message->render();\n\n $smtp = $project->getAttribute('smtp', []);\n $smtpEnabled = $smtp['enabled'] ?? false;\n\n $senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);\n $senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');\n $replyTo = \"\";\n\n if ($smtpEnabled) {\n if (!empty($smtp['senderEmail'])) {\n $senderEmail = $smtp['senderEmail'];\n }\n if (!empty($smtp['senderName'])) {\n $senderName = $smtp['senderName'];\n }\n if (!empty($smtp['replyTo'])) {\n $replyTo = $smtp['replyTo'];\n }\n\n $mails\n ->setSmtpHost($smtp['host'] ?? '')\n ->setSmtpPort($smtp['port'] ?? '')\n ->setSmtpUsername($smtp['username'] ?? '')\n ->setSmtpPassword($smtp['password'] ?? '')\n ->setSmtpSecure($smtp['secure'] ?? '');\n\n if (!empty($customTemplate)) {\n if (!empty($customTemplate['senderEmail'])) {\n $senderEmail = $customTemplate['senderEmail'];\n }\n if (!empty($customTemplate['senderName'])) {\n $senderName = $customTemplate['senderName'];\n }\n if (!empty($customTemplate['replyTo'])) {\n $replyTo = $customTemplate['replyTo'];\n }\n\n $body = $customTemplate['message'] ?? '';\n $subject = $customTemplate['subject'] ?? $subject;\n }\n\n $mails\n ->setSmtpReplyTo($replyTo)\n ->setSmtpSenderEmail($senderEmail)\n ->setSmtpSenderName($senderName);\n }\n\n $emailVariables = [\n 'owner' => $user->getAttribute('name'),\n 'subject' => $subject,\n 'hello' => $locale->getText(\"emails.invitation.hello\"),\n 'body' => $body,\n 'footer' => $locale->getText(\"emails.invitation.footer\"),\n 'thanks' => $locale->getText(\"emails.invitation.thanks\"),\n 'signature' => $locale->getText(\"emails.invitation.signature\"),\n 'direction' => $locale->getText('settings.direction'),\n 'bg-body' => '#f7f7f7',\n 'bg-content' => '#ffffff',\n 'text-content' => '#000000',\n /* {{user}} ,{{team}}, {{project}} and {{redirect}} are required in the templates */\n 'user' => $user->getAttribute('name'),\n 'team' => $team->getAttribute('name'),\n 'project' => $projectName,\n 'redirect' => $url\n ];\n\n $mails\n ->setSubject($subject)\n ->setBody($body)\n ->setRecipient($invitee->getAttribute('email'))\n ->setName($invitee->getAttribute('name'))\n ->setVariables($emailVariables)\n ->trigger()\n ;\n } elseif (!empty($phone)) {\n $message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');\n\n $customTemplate = $project->getAttribute('templates', [])['sms.invitation-' . $locale->default] ?? [];\n if (!empty($customTemplate)) {\n $message = $customTemplate['message'];\n }\n\n $message = $message->setParam('{{token}}', $url);\n $message = $message->render();\n\n $messaging\n ->setRecipient($phone)\n ->setMessage($message)\n ->trigger();\n }\n }\n\n $events\n ->setParam('teamId', $team->getId())\n ->setParam('membershipId', $membership->getId())\n ;\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic(\n $membership\n ->setAttribute('teamName', $team->getAttribute('name'))\n ->setAttribute('userName', $invitee->getAttribute('name'))\n ->setAttribute('userEmail', $invitee->getAttribute('email')),\n Response::MODEL_MEMBERSHIP\n );\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function createTemporaryDirectory(): string\n {\n $caDir = tempnam(sys_get_temp_dir(), 'webauthn-ca-');\n if (file_exists($caDir)) {\n unlink($caDir);\n }\n mkdir($caDir);\n if (!is_dir($caDir)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $caDir));\n }\n\n return $caDir;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function factory(MaintenanceOptions $options, EtlConfiguration $etlConfig, LoggerInterface $logger = null)\n {\n $options->verify();\n\n $className = $options->class;\n\n // If the class name does not include a namespace designation, use the namespace from the\n // ingestor configuration or the default namespace if not specified.\n\n if ( false === strstr($className, '\\\\') ) {\n if ( $options->namespace ) {\n $className = $options->namespace .\n ( strpos($options->namespace, '\\\\') != strlen($options->namespace) - 1 ? \"\\\\\" : \"\" ) .\n $className;\n } else {\n $className = self::$defaultIngestorNs . $className;\n }\n }\n\n if ( class_exists($className) ) {\n $action = new $className($options, $etlConfig, $logger);\n } else {\n $msg = __CLASS__ . \": Error creating action '{$options->name}', class '$className' not found\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n if ( ! $action instanceof iAction ) {\n $msg = __CLASS__ . \": $className does not implenment interface iAction\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n return $action;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function loginName2UserName($param): void {\n\t\tif (!isset($param['uid'])) {\n\t\t\tthrow new \\Exception('key uid is expected to be set in $param');\n\t\t}\n\n\t\t$userBackend = \\OC::$server->get(User_Proxy::class);\n\t\t$uid = $userBackend->loginName2UserName($param['uid']);\n\t\tif ($uid !== false) {\n\t\t\t$param['uid'] = $uid;\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function updateGridConfigFavourites(?GridConfig $gridConfig, array $metadata, int $objectId): void\n {\n $currentUser = $this->getAdminUser();\n\n if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }\n\n if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n\n $sharedUsers = [];\n\n if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];\n\n if ($sharedUserIds) {\n $sharedUsers = array_map('intval', explode(',', $sharedUserIds));\n }\n }\n\n if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());\n\n foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }\n\n foreach ($sharedUsers as $id) {\n $global = true;\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n $id,\n $gridConfig->getClassId(),\n $objectId,\n $gridConfig->getSearchType()\n );\n\n // If the user has already a favourite for that object we check the current favourite and decide if we update\n if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());\n\n if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ($favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }\n\n // Check if the user is the owner. If that is the case we do not update the favourite\n if ($favouriteGridConfig->getOwnerId() === $id) {\n continue;\n }\n }\n }\n\n // Check if the user has already a global favourite then we do not save the favourite as global\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );\n\n if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());\n\n if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ($favouriteGridConfig->isShareGlobally() === false) {\n $global = false;\n }\n\n // Check if the user is the owner. If that is the case we do not update the global favourite\n if ($favouriteGridConfig->getOwnerId() === $id) {\n $global = false;\n }\n }\n }\n\n $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId($objectId);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();\n\n if ($global === true) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (string $installationId, string $providerRepositoryId, GitHub $github, Response $response, Document $project, Database $dbForConsole) {\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if ($installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n $providerInstallationId = $installation->getAttribute('providerInstallationId');\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n\n $owner = $github->getOwnerName($providerInstallationId) ?? '';\n $repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';\n\n if (empty($repositoryName)) {\n throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);\n }\n\n $branches = $github->listBranches($owner, $repositoryName) ?? [];\n\n $response->dynamic(new Document([\n 'branches' => \\array_map(function ($branch) {\n return new Document(['name' => $branch]);\n }, $branches),\n 'total' => \\count($branches),\n ]), Response::MODEL_BRANCH_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $documentId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $document = $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId);\n\n if ($document->isEmpty()) {\n throw new Exception(Exception::DOCUMENT_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n $grouped = Query::groupByType($queries);\n $limit = $grouped['limit'] ?? APP_LIMIT_COUNT;\n $offset = $grouped['offset'] ?? 0;\n\n $audit = new Audit($dbForProject);\n $resource = 'database/' . $databaseId . '/collection/' . $collectionId . '/document/' . $document->getId();\n $logs = $audit->getLogsByResource($resource, $limit, $offset);\n\n $output = [];\n\n foreach ($logs as $i => &$log) {\n $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN';\n\n $detector = new Detector($log['userAgent']);\n $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)\n\n $os = $detector->getOS();\n $client = $detector->getClient();\n $device = $detector->getDevice();\n\n $output[$i] = new Document([\n 'event' => $log['event'],\n 'userId' => $log['data']['userId'],\n 'userEmail' => $log['data']['userEmail'] ?? null,\n 'userName' => $log['data']['userName'] ?? null,\n 'mode' => $log['data']['mode'] ?? null,\n 'ip' => $log['ip'],\n 'time' => $log['time'],\n 'osCode' => $os['osCode'],\n 'osName' => $os['osName'],\n 'osVersion' => $os['osVersion'],\n 'clientType' => $client['clientType'],\n 'clientCode' => $client['clientCode'],\n 'clientName' => $client['clientName'],\n 'clientVersion' => $client['clientVersion'],\n 'clientEngine' => $client['clientEngine'],\n 'clientEngineVersion' => $client['clientEngineVersion'],\n 'deviceName' => $device['deviceName'],\n 'deviceBrand' => $device['deviceBrand'],\n 'deviceModel' => $device['deviceModel']\n ]);\n\n $record = $geodb->get($log['ip']);\n\n if ($record) {\n $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \\strtolower($record['country']['iso_code']) : '--';\n $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown'));\n } else {\n $output[$i]['countryCode'] = '--';\n $output[$i]['countryName'] = $locale->getText('locale.country.unknown');\n }\n }\n $response->dynamic(new Document([\n 'total' => $audit->countLogsByResource($resource),\n 'logs' => $output,\n ]), Response::MODEL_LOG_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function initialize(InputInterface $input, OutputInterface $output)\n {\n parent::initialize($input, $output);\n if (!$this->searchIndexer instanceof Indexer) {\n throw new RuntimeException(\n sprintf(\n 'Found \"%s\" instead of Search Engine Indexer',\n get_parent_class($this->searchIndexer)\n )\n );\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "private function detectGroupMemberAssoc() {\n\t\t$possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber', 'zimbraMailForwardingAddress'];\n\t\t$filter = $this->configuration->ldapGroupFilter;\n\t\tif (empty($filter)) {\n\t\t\treturn false;\n\t\t}\n\t\t$cr = $this->getConnection();\n\t\tif (!$cr) {\n\t\t\tthrow new \\Exception('Could not connect to LDAP');\n\t\t}\n\t\t$base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];\n\t\t$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);\n\t\tif (!$this->ldap->isResource($rr)) {\n\t\t\treturn false;\n\t\t}\n\t\t/** @var resource|\\LDAP\\Result $rr */\n\t\t$er = $this->ldap->firstEntry($cr, $rr);\n\t\twhile ($this->ldap->isResource($er)) {\n\t\t\t$this->ldap->getDN($cr, $er);\n\t\t\t$attrs = $this->ldap->getAttributes($cr, $er);\n\t\t\t$result = [];\n\t\t\t$possibleAttrsCount = count($possibleAttrs);\n\t\t\tfor ($i = 0; $i < $possibleAttrsCount; $i++) {\n\t\t\t\tif (isset($attrs[$possibleAttrs[$i]])) {\n\t\t\t\t\t$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!empty($result)) {\n\t\t\t\tnatsort($result);\n\t\t\t\treturn key($result);\n\t\t\t}\n\n\t\t\t$er = $this->ldap->nextEntry($cr, $er);\n\t\t}\n\n\t\treturn false;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $bucketId, Response $response, Database $dbForProject) {\n\n $bucket = $dbForProject->getDocument('buckets', $bucketId);\n\n if ($bucket->isEmpty()) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $response->dynamic($bucket, Response::MODEL_BUCKET);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function createUser($username, $password) {\n\t\t$plugin = $this->which[Backend::CREATE_USER];\n\n\t\tif ($plugin) {\n\t\t\treturn $plugin->createUser($username, $password);\n\t\t}\n\t\tthrow new \\Exception('No plugin implements createUser in this LDAP Backend.');\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function createJobRequest(ExportJob $job)\n {\n // we will generate a UUID here, if we ever want the db to do that we would accomplish that here...\n $binaryUuid = (new UuidRegistry(['table_name' => 'export_job']))->createUuid();\n $job->setUuid($binaryUuid);\n\n $sql = \"INSERT INTO `export_job`(`uuid`, `start_time`, `resource_include_time`, `output_format`, `resources`, \"\n . \"`client_id`, `user_id`, `access_token_id`, `status`, `request_uri`) \"\n . \" VALUES (?,?,?,?,?,?,?,?,?,?)\";\n\n $startTime = $job->getStartTime()->format(self::DATETIME_FORMAT);\n if ($job->getResourceIncludeTime() instanceof \\DateTime) {\n $resourceIncludeTime = $job->getResourceIncludeTime()->format(self::DATETIME_FORMAT);\n } else {\n $resourceIncludeTime = null;\n }\n $params = [$job->getUuid(), $startTime, $resourceIncludeTime\n , $job->getOutputFormat(), $job->getResourcesString(), $job->getClientId(), $job->getUserId()\n , $job->getAccessTokenId(), $job->getStatus(), $job->getRequestURI()];\n\n sqlStatementThrowException($sql, $params);\n $id = sqlGetLastInsertId();\n if (!is_int($id)) {\n $params[0] = $job->getUuidString(); // so we don't spit out the binary value\n $this->logger->error(\"Failed to save ExportJob\", ['ret' => $id, 'sql' => $sql, 'params' => $params, 'sqlError' => getSqlLastError()]);\n throw new \\RuntimeException(\"Failed to save ExportJob\");\n } else {\n $job->setId($id);\n }\n return $job;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $url, Response $response) {\n\n $width = 56;\n $height = 56;\n $quality = 80;\n $output = 'png';\n $type = 'png';\n\n if (!\\extension_loaded('imagick')) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing');\n }\n\n $domain = new Domain(\\parse_url($url, PHP_URL_HOST));\n\n if (!$domain->isKnown()) {\n throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED);\n }\n\n $curl = \\curl_init();\n\n \\curl_setopt_array($curl, [\n CURLOPT_RETURNTRANSFER => 1,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_MAXREDIRS => 3,\n CURLOPT_URL => $url,\n CURLOPT_USERAGENT => \\sprintf(\n APP_USERAGENT,\n App::getEnv('_APP_VERSION', 'UNKNOWN'),\n App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)\n ),\n ]);\n\n $html = \\curl_exec($curl);\n\n \\curl_close($curl);\n\n if (!$html) {\n throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED);\n }\n\n $doc = new DOMDocument();\n $doc->strictErrorChecking = false;\n @$doc->loadHTML($html);\n\n $links = $doc->getElementsByTagName('link');\n $outputHref = '';\n $outputExt = '';\n $space = 0;\n\n foreach ($links as $link) { /* @var $link DOMElement */\n $href = $link->getAttribute('href');\n $rel = $link->getAttribute('rel');\n $sizes = $link->getAttribute('sizes');\n $absolute = URLParse::unparse(\\array_merge(\\parse_url($url), \\parse_url($href)));\n\n switch (\\strtolower($rel)) {\n case 'icon':\n case 'shortcut icon':\n //case 'apple-touch-icon':\n $ext = \\pathinfo(\\parse_url($absolute, PHP_URL_PATH), PATHINFO_EXTENSION);\n\n switch ($ext) {\n case 'ico':\n case 'png':\n case 'jpg':\n case 'jpeg':\n $size = \\explode('x', \\strtolower($sizes));\n\n $sizeWidth = (int) ($size[0] ?? 0);\n $sizeHeight = (int) ($size[1] ?? 0);\n\n if (($sizeWidth * $sizeHeight) >= $space) {\n $space = $sizeWidth * $sizeHeight;\n $outputHref = $absolute;\n $outputExt = $ext;\n }\n\n break;\n }\n\n break;\n }\n }\n\n if (empty($outputHref) || empty($outputExt)) {\n $default = \\parse_url($url);\n\n $outputHref = $default['scheme'] . '://' . $default['host'] . '/favicon.ico';\n $outputExt = 'ico';\n }\n\n $domain = new Domain(\\parse_url($outputHref, PHP_URL_HOST));\n\n if (!$domain->isKnown()) {\n throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED);\n }\n\n if ('ico' == $outputExt) { // Skip crop, Imagick isn\\'t supporting icon files\n $data = @\\file_get_contents($outputHref, false);\n\n if (empty($data) || (\\mb_substr($data, 0, 5) === '<html') || \\mb_substr($data, 0, 5) === '<!doc') {\n throw new Exception(Exception::AVATAR_ICON_NOT_FOUND, 'Favicon not found');\n }\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + 60 * 60 * 24 * 30) . ' GMT')\n ->setContentType('image/x-icon')\n ->file($data);\n }\n\n $fetch = @\\file_get_contents($outputHref, false);\n\n if (!$fetch) {\n throw new Exception(Exception::AVATAR_ICON_NOT_FOUND);\n }\n\n $image = new Image($fetch);\n $image->crop((int) $width, (int) $height);\n $output = (empty($output)) ? $type : $output;\n $data = $image->output($output, $quality);\n\n $response\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + 60 * 60 * 24 * 30) . ' GMT')\n ->setContentType('image/png')\n ->file($data);\n unset($image);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function verifyProperty($property, $value)\n {\n switch ( $property ) {\n\n case 'buffered_query':\n case 'optimize_query':\n case 'disable_keys':\n $origValue = $value;\n $value = \\xd_utilities\\filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);\n if ( null === $value ) {\n $msg = get_class($this) . \": '$property' must be a boolean (type = \" . gettype($origValue) . \")\";\n throw new Exception($msg);\n }\n break;\n\n case 'aggregation_units':\n case 'include_only_resource_codes':\n case 'exclude_resource_codes':\n $value = ( is_array($value) ? $value : array($value) );\n foreach ( $value as $v ) {\n if ( ! is_string($v) ) {\n $msg = get_class($this) . \": '$property' must be a string or array of strings (type = \" . gettype($v) . \")\";\n throw new Exception($msg);\n }\n }\n break;\n\n case 'utility':\n case 'source':\n case 'destination':\n if ( ! is_string($value) ) {\n $msg = get_class($this) . \": '$property' must be a string (type = \" . gettype($value) . \")\";\n throw new Exception($msg);\n }\n break;\n\n default:\n $value = parent::verifyProperty($property, $value);\n break;\n }\n\n return $value;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function getByKey(string $permission): ?Definition\n {\n if (!$permission) {\n throw new Exception('No permisson defined.');\n }\n $list = new Definition\\Listing();\n $list->setCondition('`key`=?', [$permission]);\n $list->setLimit(1);\n $permissionDefinition = $list->load();\n\n if (1 === count($permissionDefinition)) {\n return $permissionDefinition[0];\n }\n\n return null;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "protected static function getTemporaryFileFromStream(mixed $stream, bool $keep = false): string\n {\n if (is_string($stream)) {\n $src = fopen($stream, 'rb');\n $fileExtension = pathinfo($stream, PATHINFO_EXTENSION);\n } else {\n $src = $stream;\n $streamMeta = stream_get_meta_data($src);\n $fileExtension = pathinfo($streamMeta['uri'], PATHINFO_EXTENSION);\n }\n\n $tmpFilePath = File::getLocalTempFilePath($fileExtension, $keep);\n\n $dest = fopen($tmpFilePath, 'wb', false, File::getContext());\n if (!$dest) {\n throw new Exception(sprintf('Unable to create temporary file in %s', $tmpFilePath));\n }\n\n stream_copy_to_stream($src, $dest);\n fclose($dest);\n\n return $tmpFilePath;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getDefinition(): AssetDefinition\n {\n $definition = AssetDefinitionManager::getInstance()->getDefinition(static::$definition_system_name);\n if (!($definition instanceof AssetDefinition)) {\n throw new \\RuntimeException('Asset definition is expected to be defined in concrete class.');\n }\n\n return $definition;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setName(string $name): static\n {\n if ($name !== 'localizedfields') {\n throw new Exception('Localizedfields can only be named `localizedfields`, no other names are allowed');\n }\n\n $this->name = $name;\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function onKernelController(ControllerEvent $event): void\n {\n $strategy = null;\n\n /** @var SecurityStrategy[] $attributes */\n $attributes = $event->getAttributes(SecurityStrategy::class);\n $number_of_attributes = \\count($attributes);\n if ($number_of_attributes > 1) {\n throw new \\RuntimeException(\\sprintf(\n 'You can apply only one security strategy per HTTP request. You actually used the \"%s\" attribute %d times.',\n SecurityStrategy::class,\n $number_of_attributes,\n ));\n } elseif ($number_of_attributes === 1) {\n $strategy = current($attributes)->strategy;\n } elseif ($event->isMainRequest()) {\n $strategy = $this->firewall->computeFallbackStrategy($event->getRequest());\n }\n\n if ($strategy !== null) {\n $this->firewall->applyStrategy($strategy);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setVerbose($flag = true)\n {\n $origFlag = $flag;\n $flag = \\xd_utilities\\filter_var($flag, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);\n if ( null === $flag ) {\n $msg = get_class($this) . \": Verbose flag is not a boolean: '$origFlag'\";\n throw new Exception($msg);\n }\n $this->verbose = $flag;\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function cloneEvent(array $event = [])\n {\n $item = new $event['old_itemtype']();\n $item->getFromDB((int) $event['old_items_id']);\n\n $input = array_merge($item->fields, [\n 'plan' => [\n 'begin' => date(\"Y-m-d H:i:s\", strtotime($event['start'])),\n 'end' => date(\"Y-m-d H:i:s\", strtotime($event['end'])),\n ],\n ]);\n unset($input['id'], $input['uuid']);\n\n if (isset($item->fields['name'])) {\n $input['name'] = sprintf(__('Copy of %s'), $item->fields['name']);\n }\n\n // manage change of assigment for CommonITILTask\n if (isset($event['actor']['itemtype'], $event['actor']['items_id']) && $item instanceof CommonITILTask) {\n $key = match ($event['actor']['itemtype']) {\n \"group\" => \"groups_id_tech\",\n \"user\" => isset($item->fields['users_id_tech']) ? \"users_id_tech\" : \"users_id\",\n default => throw new \\RuntimeException(sprintf('Unexpected event actor itemtype `%s`.', $event['actor']['itemtype'])),\n };\n\n unset(\n $input['users_id_tech'],\n $input['users_id'],\n $input['groups_id_tech'],\n $input['groups_id']\n );\n\n $input[$key] = $event['actor']['items_id'];\n }\n\n $new_items_id = $item->add($input);\n\n // manage all assigments for ProjectTask\n if (isset($event['actor']['itemtype'], $event['actor']['items_id']) && $item instanceof ProjectTask) {\n $team = new ProjectTaskTeam();\n $team->add([\n 'projecttasks_id' => $new_items_id,\n 'itemtype' => ucfirst($event['actor']['itemtype']),\n 'items_id' => $event['actor']['items_id']\n ]);\n }\n\n return $new_items_id;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function merge(int $merge_target_id, array $ticket_ids, array &$status, array $params = [])\n {\n /** @var \\DBmysql $DB */\n global $DB;\n $p = [\n 'linktypes' => [],\n 'full_transaction' => true,\n 'link_type' => CommonITILObject_CommonITILObject::SON_OF,\n 'append_actors' => [CommonITILActor::REQUESTER, CommonITILActor::OBSERVER, CommonITILActor::ASSIGN]\n ];\n $p = array_replace($p, $params);\n $ticket = new Ticket();\n $merge_target = new Ticket();\n $merge_target->getFromDB($merge_target_id);\n $fup = new ITILFollowup();\n $document_item = new Document_Item();\n $task = new TicketTask();\n\n if (!$merge_target->canAddFollowups()) {\n foreach ($ticket_ids as $id) {\n Toolbox::logDebug(sprintf(__('Not enough rights to merge tickets %d and %d'), $merge_target_id, $id));\n // Set status = 2 : Rights issue\n $status[$id] = 2;\n }\n return false;\n }\n $in_transaction = $DB->inTransaction();\n\n if ($p['full_transaction'] && !$in_transaction) {\n $DB->beginTransaction();\n }\n foreach ($ticket_ids as $id) {\n try {\n if (!$p['full_transaction'] && !$in_transaction) {\n $DB->beginTransaction();\n }\n if ($merge_target->canUpdateItem() && $ticket->can($id, DELETE)) {\n if (!$ticket->getFromDB($id)) {\n //Cannot retrieve ticket. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to load ticket %d'), $id), 1);\n }\n //Build followup from the original ticket\n $input = [\n 'itemtype' => 'Ticket',\n 'items_id' => $merge_target_id,\n 'content' => $ticket->fields['name'] . \"<br /><br />\" . $ticket->fields['content'],\n 'users_id' => $ticket->fields['users_id_recipient'],\n 'date_creation' => $ticket->fields['date_creation'],\n 'date_mod' => $ticket->fields['date_mod'],\n 'date' => $ticket->fields['date_creation'],\n 'sourceitems_id' => $ticket->getID()\n ];\n if (!$fup->add($input)) {\n //Cannot add followup. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to add followup to ticket %d'), $merge_target_id), 1);\n }\n if (in_array('ITILFollowup', $p['linktypes'])) {\n // Copy any followups to the ticket\n $tomerge = $fup->find([\n 'items_id' => $id,\n 'itemtype' => 'Ticket'\n ]);\n foreach ($tomerge as $fup2) {\n $fup2['items_id'] = $merge_target_id;\n $fup2['sourceitems_id'] = $id;\n $fup2['content'] = $fup2['content'];\n unset($fup2['id']);\n if (!$fup->add($fup2)) {\n // Cannot add followup. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to add followup to ticket %d'), $merge_target_id), 1);\n }\n }\n }\n if (in_array('TicketTask', $p['linktypes'])) {\n $merge_tmp = ['tickets_id' => $merge_target_id];\n if (!$task->can(-1, CREATE, $merge_tmp)) {\n throw new \\RuntimeException(sprintf(__('Not enough rights to merge tickets %d and %d'), $merge_target_id, $id), 2);\n }\n // Copy any tasks to the ticket\n $tomerge = $task->find([\n 'tickets_id' => $id\n ]);\n foreach ($tomerge as $task2) {\n $task2['tickets_id'] = $merge_target_id;\n $task2['sourceitems_id'] = $id;\n $task2['content'] = $task2['content'];\n unset($task2['id']);\n unset($task2['uuid']);\n if (!$task->add($task2)) {\n //Cannot add followup. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to add task to ticket %d'), $merge_target_id), 1);\n }\n }\n }\n if (in_array('Document', $p['linktypes'])) {\n if (!$merge_target->canAddItem('Document')) {\n throw new \\RuntimeException(sprintf(__('Not enough rights to merge tickets %d and %d'), $merge_target_id, $id), 2);\n }\n $tomerge = $document_item->find([\n 'itemtype' => 'Ticket',\n 'items_id' => $id,\n 'NOT' => [\n 'documents_id' => new QuerySubQuery([\n 'SELECT' => 'documents_id',\n 'FROM' => $document_item->getTable(),\n 'WHERE' => [\n 'itemtype' => 'Ticket',\n 'items_id' => $merge_target_id\n ]\n ])\n ]\n ]);\n\n foreach ($tomerge as $document_item2) {\n $document_item2['items_id'] = $merge_target_id;\n unset($document_item2['id']);\n if (!$document_item->add($document_item2)) {\n //Cannot add document. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to add document to ticket %d'), $merge_target_id), 1);\n }\n }\n }\n if ($p['link_type'] > 0 && $p['link_type'] < 5) {\n //Add relation (this is parent of merge target)\n $tt = new Ticket_Ticket();\n $linkparams = [\n 'link' => $p['link_type'],\n 'tickets_id_1' => $id,\n 'tickets_id_2' => $merge_target_id\n ];\n $tt->deleteByCriteria([\n 'OR' => [\n [\n 'AND' => [\n 'tickets_id_1' => $merge_target_id,\n 'tickets_id_2' => $id\n ]\n ],\n [\n 'AND' => [\n 'tickets_id_2' => $merge_target_id,\n 'tickets_id_1' => $id\n ]\n ]\n ]\n ]);\n if (!$tt->add($linkparams)) {\n //Cannot link tickets. Abort/fail the merge\n throw new \\RuntimeException(sprintf(__('Failed to link tickets %d and %d'), $merge_target_id, $id), 1);\n }\n }\n if (isset($p['append_actors'])) {\n $tu = new Ticket_User();\n $existing_users = $tu->find(['tickets_id' => $merge_target_id]);\n $gt = new Group_Ticket();\n $existing_groups = $gt->find(['tickets_id' => $merge_target_id]);\n $st = new Supplier_Ticket();\n $existing_suppliers = $st->find(['tickets_id' => $merge_target_id]);\n\n foreach ($p['append_actors'] as $actor_type) {\n $users = $tu->find([\n 'tickets_id' => $id,\n 'type' => $actor_type\n ]);\n $groups = $gt->find([\n 'tickets_id' => $id,\n 'type' => $actor_type\n ]);\n $suppliers = $st->find([\n 'tickets_id' => $id,\n 'type' => $actor_type\n ]);\n $users = array_filter($users, function ($user) use ($existing_users) {\n foreach ($existing_users as $existing_user) {\n if (\n $existing_user['users_id'] > 0 && $user['users_id'] > 0 &&\n $existing_user['users_id'] === $user['users_id'] &&\n $existing_user['type'] === $user['type']\n ) {\n // Internal users\n return false;\n } else if (\n $existing_user['users_id'] == 0 && $user['users_id'] == 0 &&\n $existing_user['alternative_email'] === $user['alternative_email'] &&\n $existing_user['type'] === $user['type']\n ) {\n // External users\n return false;\n }\n }\n return true;\n });\n $groups = array_filter($groups, function ($group) use ($existing_groups) {\n foreach ($existing_groups as $existing_group) {\n if (\n $existing_group['groups_id'] === $group['groups_id'] &&\n $existing_group['type'] === $group['type']\n ) {\n return false;\n }\n }\n return true;\n });\n $suppliers = array_filter($suppliers, function ($supplier) use ($existing_suppliers) {\n foreach ($existing_suppliers as $existing_supplier) {\n if (\n $existing_supplier['suppliers_id'] > 0 && $supplier['suppliers_id'] > 0 &&\n $existing_supplier['suppliers_id'] === $supplier['suppliers_id'] &&\n $existing_supplier['type'] === $supplier['type']\n ) {\n // Internal suppliers\n return false;\n } else if (\n $existing_supplier['suppliers_id'] == 0 && $supplier['suppliers_id'] == 0 &&\n $existing_supplier['alternative_email'] === $supplier['alternative_email'] &&\n $existing_supplier['type'] === $supplier['type']\n ) {\n // External suppliers\n return false;\n }\n }\n return true;\n });\n foreach ($users as $user) {\n $user['tickets_id'] = $merge_target_id;\n unset($user['id']);\n $tu->add($user);\n }\n foreach ($groups as $group) {\n $group['tickets_id'] = $merge_target_id;\n unset($group['id']);\n $gt->add($group);\n }\n foreach ($suppliers as $supplier) {\n $supplier['tickets_id'] = $merge_target_id;\n unset($supplier['id']);\n $st->add($supplier);\n }\n }\n }\n //Delete this ticket\n if (!$ticket->delete(['id' => $id, '_disablenotif' => true])) {\n throw new \\RuntimeException(sprintf(__('Failed to delete ticket %d'), $id), 1);\n }\n if (!$p['full_transaction'] && !$in_transaction) {\n $DB->commit();\n }\n $status[$id] = 0;\n Event::log(\n $merge_target_id,\n 'ticket',\n 4,\n 'tracking',\n sprintf(\n __('%s merges ticket %s into %s'),\n $_SESSION['glpiname'],\n $id,\n $merge_target_id\n )\n );\n } else {\n throw new \\RuntimeException(sprintf(__('Not enough rights to merge tickets %d and %d'), $merge_target_id, $id), 2);\n }\n } catch (\\RuntimeException $e) {\n if ($e->getCode() < 1 || $e->getCode() > 2) {\n $status[$id] = 1;\n } else {\n $status[$id] = $e->getCode();\n }\n Toolbox::logDebug($e->getMessage());\n if (!$in_transaction) {\n $DB->rollBack();\n }\n if ($p['full_transaction']) {\n return false;\n }\n }\n }\n if ($p['full_transaction'] && !$in_transaction) {\n $DB->commit();\n }\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function match($pathinfo): array\n {\n throw new \\RuntimeException(\"The UrlWildcardRouter doesn't support the match() method. Use matchRequest() instead.\");\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function __construct(\n array $parameters,\n $stat = \"all\"\n ) {\n parent::__construct('Cloud', 'modw_cloud', 'cloudfact_by_day', array());\n\n $this->setDistinct(true);\n $config = RawStatisticsConfiguration::factory();\n\n // The data table is always aliased to \"agg\".\n $tables = ['agg' => $this->getDataTable()];\n\n foreach ($config->getQueryTableDefinitions('Cloud') as $tableDef) {\n $alias = $tableDef['alias'];\n $table = new Table(\n new Schema($tableDef['schema']),\n $tableDef['name'],\n $alias\n );\n $tables[$alias] = $table;\n $this->addTable($table);\n\n $join = $tableDef['join'];\n $this->addWhereCondition(new WhereCondition(\n new TableField($table, $join['primaryKey']),\n '=',\n new TableField($tables[$join['foreignTableAlias']], $join['foreignKey'])\n ));\n }\n\n // This table is defined in the configuration file, but used in the section below.\n $factTable = $tables['i'];\n $sessionTable = $tables['sr'];\n\n if (isset($parameters['primary_key'])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'instance_id'), \"=\", $parameters['primary_key']));\n } elseif (isset($parameters['job_identifier'])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'resource_id'), '=', $parameters['resource_id']));\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'provider_identifier'), '=', $parameters['job_identifier']));\n } elseif (isset($parameters['start_date']) && isset($parameters['end_date'])) {\n $startDate = date_parse_from_format('Y-m-d', $parameters['start_date']);\n $startDateTs = mktime(0, 0, 0, $startDate['month'], $startDate['day'], $startDate['year']);\n\n if ($startDateTs === false) {\n throw new Exception('invalid \"start_date\" query parameter');\n }\n\n $endDate = date_parse_from_format('Y-m-d', $parameters['end_date']);\n $endDateTs = mktime(23, 59, 59, $endDate['month'], $endDate['day'], $endDate['year']);\n\n if ($endDateTs === false) {\n throw new Exception('invalid \"end_date\" query parameter');\n }\n\n $this->addPdoWhereCondition(new WhereCondition(new TableField($sessionTable, 'end_time_ts'), \">=\", $startDateTs));\n $this->addPdoWhereCondition(new WhereCondition(new TableField($sessionTable, 'start_time_ts'), \"<=\", $endDateTs));\n } else {\n throw new Exception('invalid query parameters');\n }\n\n if ($stat == \"accounting\" || $stat == 'batch') {\n foreach ($config->getQueryFieldDefinitions('Cloud') as $field) {\n $alias = $field['name'];\n if (isset($field['tableAlias']) && isset($field['column'])) {\n $this->addField(new TableField(\n $tables[$field['tableAlias']],\n $field['column'],\n $alias\n ));\n } elseif (isset($field['formula'])) {\n $this->addField(new FormulaField($field['formula'], $alias));\n } else {\n throw new Exception(sprintf(\n 'Missing tableAlias and column or formula for \"%s\", definition: %s',\n $alias,\n json_encode($field)\n ));\n }\n $this->documentation[$alias] = $field;\n }\n }\n elseif ($stat == 'timeseries') {\n $this->setDistinct(false);\n\n $this->addField(new TableField($tables['agg'], 'start_time'));\n $this->addField(new TableField($tables['agg'], 'end_time'));\n $this->addField(new TableField($tables['agg'], 'start_event_type_id'));\n $this->addField(new TableField($tables['agg'], 'end_event_type_id'));\n\n $pt = new Table(new Schema('modw'), 'person', 'p');\n $this->joinTo($pt, \"person_id\", \"long_name\", \"name\");\n\n $st = new Table(new Schema('modw'), 'systemaccount', 'sa');\n $this->joinTo($st, \"systemaccount_id\", \"username\", \"username\");\n\n } else {\n $this->addField(new TableField($factTable, \"provider_identifier\", \"local_job_id\"));\n $this->addField(new TableField($factTable, \"instance_id\", \"jobid\"));\n\n $rt = new Table(new Schema(\"modw\"), \"resourcefact\", \"rf\");\n $this->joinTo($rt, \"host_resource_id\", \"code\", \"resource\");\n\n $pt = new Table(new Schema('modw'), 'person', 'p');\n $this->joinTo($pt, \"person_id\", \"long_name\", \"name\");\n\n $st = new Table(new Schema('modw'), 'systemaccount', 'sa');\n $this->joinTo($st, \"systemaccount_id\", \"username\", \"username\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setDryrun($flag = true)\n {\n $origFlag = $flag;\n $flag = \\xd_utilities\\filter_var($flag, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);\n if ( null === $flag ) {\n $msg = get_class($this) . \": Dryrun flag is not a boolean: '$origFlag'\";\n throw new Exception($msg);\n }\n $this->dryrun = $flag;\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $projectId, string $platformId, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $platform = $dbForConsole->findOne('platforms', [\n Query::equal('$id', [$platformId]),\n Query::equal('projectInternalId', [$project->getInternalId()]),\n ]);\n\n if ($platform === false || $platform->isEmpty()) {\n throw new Exception(Exception::PLATFORM_NOT_FOUND);\n }\n\n $dbForConsole->deleteDocument('platforms', $platformId);\n\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function getCriterion(APILimitationValue $value, APIUserReference $currentUser)\n {\n if (empty($value->limitationValues)) {\n // A Policy should not have empty limitationValues store\n throw new \\RuntimeException('$value->limitationValues is empty');\n }\n\n if (!isset($value->limitationValues[1])) {\n // 1 limitation value: EQ operation\n return new PermissionSubtree($value->limitationValues[0]);\n }\n\n // several limitation values: IN operation\n return new PermissionSubtree($value->limitationValues);\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "static function register($filter, $group) {\n if (!isset($filter::$id))\n throw new Exception('QueueColumnFilter must define $id');\n if (isset(static::$registry[$filter::$id]))\n throw new Exception($filter::$id\n . ': QueueColumnFilter already registered under that id');\n if (!is_subclass_of($filter, get_called_class()))\n throw new Exception('Filter must extend QueueColumnFilter');\n\n static::$registry[$filter::$id] = array($group, $filter);\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function create(IShare $share) {\n\t\t$shareWith = $share->getSharedWith();\n\t\t$itemSource = $share->getNodeId();\n\t\t$itemType = $share->getNodeType();\n\t\t$permissions = $share->getPermissions();\n\t\t$sharedBy = $share->getSharedBy();\n\t\t$shareType = $share->getShareType();\n\t\t$expirationDate = $share->getExpirationDate();\n\n\t\tif ($shareType === IShare::TYPE_REMOTE_GROUP &&\n\t\t\t!$this->isOutgoingServer2serverGroupShareEnabled()\n\t\t) {\n\t\t\t$message = 'It is not allowed to send federated group shares from this server.';\n\t\t\t$message_t = $this->l->t('It is not allowed to send federated group shares from this server.');\n\t\t\t$this->logger->debug($message, ['app' => 'Federated File Sharing']);\n\t\t\tthrow new \\Exception($message_t);\n\t\t}\n\n\t\t/*\n\t\t * Check if file is not already shared with the remote user\n\t\t */\n\t\t$alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE, $share->getNode(), 1, 0);\n\t\t$alreadySharedGroup = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE_GROUP, $share->getNode(), 1, 0);\n\t\tif (!empty($alreadyShared) || !empty($alreadySharedGroup)) {\n\t\t\t$message = 'Sharing %1$s failed, because this item is already shared with %2$s';\n\t\t\t$message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with the account %2$s', [$share->getNode()->getName(), $shareWith]);\n\t\t\t$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);\n\t\t\tthrow new \\Exception($message_t);\n\t\t}\n\n\n\t\t// don't allow federated shares if source and target server are the same\n\t\t$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);\n\t\t$currentServer = $this->addressHandler->generateRemoteURL();\n\t\t$currentUser = $sharedBy;\n\t\tif ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {\n\t\t\t$message = 'Not allowed to create a federated share to the same account.';\n\t\t\t$message_t = $this->l->t('Not allowed to create a federated share to the same account');\n\t\t\t$this->logger->debug($message, ['app' => 'Federated File Sharing']);\n\t\t\tthrow new \\Exception($message_t);\n\t\t}\n\n\t\t// Federated shares always have read permissions\n\t\tif (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {\n\t\t\t$message = 'Federated shares require read permissions';\n\t\t\t$message_t = $this->l->t('Federated shares require read permissions');\n\t\t\t$this->logger->debug($message, ['app' => 'Federated File Sharing']);\n\t\t\tthrow new \\Exception($message_t);\n\t\t}\n\n\t\t$share->setSharedWith($cloudId->getId());\n\n\t\ttry {\n\t\t\t$remoteShare = $this->getShareFromExternalShareTable($share);\n\t\t} catch (ShareNotFound $e) {\n\t\t\t$remoteShare = null;\n\t\t}\n\n\t\tif ($remoteShare) {\n\t\t\ttry {\n\t\t\t\t$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);\n\t\t\t\t$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time(), $shareType, $expirationDate);\n\t\t\t\t$share->setId($shareId);\n\t\t\t\t[$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId);\n\t\t\t\t// remote share was create successfully if we get a valid token as return\n\t\t\t\t$send = is_string($token) && $token !== '';\n\t\t\t} catch (\\Exception $e) {\n\t\t\t\t// fall back to old re-share behavior if the remote server\n\t\t\t\t// doesn't support flat re-shares (was introduced with Nextcloud 9.1)\n\t\t\t\t$this->removeShareFromTable($share);\n\t\t\t\t$shareId = $this->createFederatedShare($share);\n\t\t\t}\n\t\t\tif ($send) {\n\t\t\t\t$this->updateSuccessfulReshare($shareId, $token);\n\t\t\t\t$this->storeRemoteId($shareId, $remoteId);\n\t\t\t} else {\n\t\t\t\t$this->removeShareFromTable($share);\n\t\t\t\t$message_t = $this->l->t('File is already shared with %s', [$shareWith]);\n\t\t\t\tthrow new \\Exception($message_t);\n\t\t\t}\n\t\t} else {\n\t\t\t$shareId = $this->createFederatedShare($share);\n\t\t}\n\n\t\t$data = $this->getRawShare($shareId);\n\t\treturn $this->createShareObject($data);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function newToken(string $token,\n\t\tstring $uid,\n\t\tstring $loginName,\n\t\t$password,\n\t\tstring $name,\n\t\tint $type,\n\t\tint $remember): PublicKeyToken {\n\t\t$dbToken = new PublicKeyToken();\n\t\t$dbToken->setUid($uid);\n\t\t$dbToken->setLoginName($loginName);\n\n\t\t$config = array_merge([\n\t\t\t'digest_alg' => 'sha512',\n\t\t\t'private_key_bits' => $password !== null && strlen($password) > 250 ? 4096 : 2048,\n\t\t], $this->config->getSystemValue('openssl', []));\n\n\t\t// Generate new key\n\t\t$res = openssl_pkey_new($config);\n\t\tif ($res === false) {\n\t\t\t$this->logOpensslError();\n\t\t\tthrow new \\RuntimeException('OpenSSL reported a problem');\n\t\t}\n\n\t\tif (openssl_pkey_export($res, $privateKey, null, $config) === false) {\n\t\t\t$this->logOpensslError();\n\t\t\tthrow new \\RuntimeException('OpenSSL reported a problem');\n\t\t}\n\n\t\t// Extract the public key from $res to $pubKey\n\t\t$publicKey = openssl_pkey_get_details($res);\n\t\t$publicKey = $publicKey['key'];\n\n\t\t$dbToken->setPublicKey($publicKey);\n\t\t$dbToken->setPrivateKey($this->encrypt($privateKey, $token));\n\n\t\tif (!is_null($password) && $this->config->getSystemValueBool('auth.storeCryptedPassword', true)) {\n\t\t\tif (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {\n\t\t\t\tthrow new \\RuntimeException('Trying to save a password with more than 469 characters is not supported. If you want to use big passwords, disable the auth.storeCryptedPassword option in config.php');\n\t\t\t}\n\t\t\t$dbToken->setPassword($this->encryptPassword($password, $publicKey));\n\t\t\t$dbToken->setPasswordHash($this->hashPassword($password));\n\t\t}\n\n\t\t$dbToken->setName($name);\n\t\t$dbToken->setToken($this->hashToken($token));\n\t\t$dbToken->setType($type);\n\t\t$dbToken->setRemember($remember);\n\t\t$dbToken->setLastActivity($this->time->getTime());\n\t\t$dbToken->setLastCheck($this->time->getTime());\n\t\t$dbToken->setVersion(PublicKeyToken::VERSION);\n\n\t\treturn $dbToken;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function via(string $morphReference, string $key)\n {\n $className = Relation::getMorphedModel($morphReference);\n\n if (is_null($className)) {\n throw new Exception(\"Model not found for reference: {$morphReference}\");\n }\n\n return $className::whereKey($key)->firstOrFail();\n }", "smellKey": "S112", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public static function importTranslationsFromFile(string $file, string $domain = self::DOMAIN_DEFAULT, bool $replaceExistingTranslations = true, array $languages = null, stdClass $dialect = null): array\n {\n $delta = [];\n\n if (is_readable($file)) {\n if (!$languages) {\n $languages = static::getValidLanguages($domain);\n }\n\n //read import data\n $tmpData = file_get_contents($file);\n\n //replace magic excel bytes\n $tmpData = str_replace(\"\\xEF\\xBB\\xBF\", '', $tmpData);\n\n //convert to utf-8 if needed\n $tmpData = Tool\\Text::convertToUTF8($tmpData);\n\n //store data for further usage\n $filesystem = new Filesystem();\n $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_translations';\n $filesystem->dumpFile($importFile, $tmpData);\n\n $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_translations_original';\n $filesystem->dumpFile($importFileOriginal, $tmpData);\n\n // determine csv type if not set\n if (empty($dialect)) {\n $dialect = Tool\\Admin::determineCsvDialect(PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_translations_original');\n }\n\n //read data\n $data = [];\n if (($handle = fopen(PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_translations', 'r')) !== false) {\n while (($rowData = fgetcsv($handle, 0, $dialect->delimiter, $dialect->quotechar, $dialect->escapechar)) !== false) {\n $data[] = $rowData;\n }\n fclose($handle);\n }\n\n //process translations\n if (count($data) > 1) {\n $keys = $data[0];\n // remove wrong quotes in some export/import constellations\n $keys = array_map(function ($value) {\n return trim($value, '\ufeff\"\"');\n }, $keys);\n $data = array_slice($data, 1);\n foreach ($data as $row) {\n $keyValueArray = [];\n $row = Service::unEscapeCsvRecord($row);\n for ($counter = 0; $counter < count($row); $counter++) {\n $rd = str_replace('&quot;', '\"', $row[$counter]);\n $keyValueArray[$keys[$counter]] = $rd;\n }\n\n $textKey = $keyValueArray['key'] ?? null;\n if ($textKey) {\n $t = static::getByKey($textKey, $domain, true);\n $dirty = false;\n foreach ($keyValueArray as $key => $value) {\n if (in_array($key, $languages)) {\n $currentTranslation = $t->getTranslation($key);\n if ($replaceExistingTranslations) {\n $t->addTranslation($key, $value);\n if ($currentTranslation != $value) {\n $dirty = true;\n }\n } else {\n if (!$currentTranslation) {\n $t->addTranslation($key, $value);\n if ($currentTranslation != $value) {\n $dirty = true;\n }\n } elseif ($currentTranslation != $value && $value) {\n $delta[] =\n [\n 'lg' => $key,\n 'key' => $textKey,\n 'text' => $t->getTranslation($key),\n 'csv' => $value,\n ];\n }\n }\n }\n }\n\n if ($dirty) {\n if (array_key_exists('creationDate', $keyValueArray) && $keyValueArray['creationDate']) {\n $t->setCreationDate((int) $keyValueArray['creationDate']);\n }\n $t->setModificationDate(time()); //ignore modificationDate from file\n $t->save();\n }\n }\n\n // call the garbage collector if memory consumption is > 100MB\n if (memory_get_usage() > 100_000_000) {\n Pimcore::collectGarbage();\n }\n }\n static::clearDependentCache();\n } else {\n throw new Exception('less than 2 rows of data - nothing to import');\n }\n } else {\n throw new Exception(\"$file is not readable\");\n }\n\n return $delta;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function processFinite(Stream $stream, int $mt, int $ai, ?string $val): CBORObject\n {\n switch ($mt) {\n case 0b000: //0\n return UnsignedIntegerObject::createObjectForValue($ai, $val);\n case 0b001: //1\n return SignedIntegerObject::createObjectForValue($ai, $val);\n case 0b010: //2\n $length = null === $val ? $ai : Utils::binToInt($val);\n\n return new ByteStringObject($stream->read($length));\n case 0b011: //3\n $length = null === $val ? $ai : Utils::binToInt($val);\n\n return new TextStringObject($stream->read($length));\n case 0b100: //4\n $object = new ListObject();\n $nbItems = null === $val ? $ai : Utils::binToInt($val);\n for ($i = 0; $i < $nbItems; ++$i) {\n $object->add($this->process($stream));\n }\n\n return $object;\n case 0b101: //5\n $object = new MapObject();\n $nbItems = null === $val ? $ai : Utils::binToInt($val);\n for ($i = 0; $i < $nbItems; ++$i) {\n $object->add($this->process($stream), $this->process($stream));\n }\n\n return $object;\n case 0b110: //6\n return $this->tagObjectManager->createObjectForValue($ai, $val, $this->process($stream));\n case 0b111: //7\n return $this->otherTypeManager->createObjectForValue($ai, $val);\n default:\n throw new RuntimeException(sprintf('Unsupported major type \"%s\" (%d).', str_pad(decbin($mt), 5, '0', STR_PAD_LEFT), $mt)); // Should never append\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function addConfiguration(array $configuration)\n {\n $env = $this->getEnvironment();\n\n $yamlString = Yaml::dump($configuration, 5, 4);\n $destinationFileName = 'ezplatform_behat_' . sha1($yamlString) . '.yaml';\n $destinationFilePath = \"config/packages/{$env}/{$destinationFileName}\";\n\n $configurationDir = dirname($destinationFilePath);\n if (!is_dir($configurationDir)) {\n if (false === @mkdir($configurationDir)) {\n $error = error_get_last();\n throw new RuntimeException(sprintf(\n 'Unable to create the configuration directory \"%s\": %s',\n $configurationDir,\n $error['message']\n ));\n }\n }\n\n if (!file_exists($destinationFilePath)) {\n file_put_contents($destinationFilePath, $yamlString);\n }\n\n $this->addImportToPlatformYaml($destinationFileName, $env);\n $this->clearSymfonyCache();\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setInputFilter(InputFilterInterface $inputFilter)\n {\n throw new \\Exception(\"Not used\");\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function load(): void\n {\n if (!isset($_SESSION[$this->sessionKey])) {\n return;\n }\n $data = \\json_decode($_SESSION[$this->sessionKey], true);\n if (\\is_array($data)) {\n foreach ($data as $cookie) {\n $this->setCookie(new SetCookie($cookie));\n }\n } elseif (\\strlen($data)) {\n throw new \\RuntimeException('Invalid cookie data');\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "final public static function getItemField($itemtype): string\n {\n if (is_subclass_of($itemtype, 'Rule') && !is_subclass_of($itemtype, 'LevelAgreementLevel')) {\n $itemtype = 'Rule';\n }\n\n if (isset(static::$items_id) && getItemtypeForForeignKeyField(static::$items_id) == $itemtype) {\n return static::$items_id;\n }\n\n if (isset(static::$itemtype) && preg_match('/^itemtype/', static::$itemtype)) {\n return static::$items_id;\n }\n\n throw new \\RuntimeException('Cannot guess field for itemtype ' . $itemtype . ' on ' . static::class);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function prepareInputForAdd($input)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n if (!isset($input['itemtype'])) {\n Session::addMessageAfterRedirect(\n __s('An item type is mandatory'),\n false,\n ERROR\n );\n return false;\n }\n\n if (!isset($input['items_id'])) {\n Session::addMessageAfterRedirect(\n __s('An item ID is mandatory'),\n false,\n ERROR\n );\n return false;\n }\n\n if (!isset($input['projecttasks_id'])) {\n Session::addMessageAfterRedirect(\n __s('A project task is mandatory'),\n false,\n ERROR\n );\n return false;\n }\n\n $task = new ProjectTask();\n $task->getFromDB($input['projecttasks_id']);\n switch ($input['itemtype']) {\n case User::getType():\n Planning::checkAlreadyPlanned(\n $input['items_id'],\n $task->fields['plan_start_date'],\n $task->fields['plan_end_date']\n );\n break;\n case Group::getType():\n $group_iterator = $DB->request([\n 'SELECT' => 'users_id',\n 'FROM' => Group_User::getTable(),\n 'WHERE' => ['groups_id' => $input['items_id']]\n ]);\n foreach ($group_iterator as $row) {\n Planning::checkAlreadyPlanned(\n $row['users_id'],\n $task->fields['plan_start_date'],\n $task->fields['plan_end_date']\n );\n }\n break;\n case Supplier::getType():\n case Contact::getType():\n //only Users can be checked for planning conflicts\n break;\n default:\n throw new \\RuntimeException($input['itemtype'] . \" is not (yet?) handled.\");\n }\n\n return $input;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function testHostFilter($host)\n {\n if (!$this->hasHostFilter()) {\n return true;\n }\n\n $result = preg_match($this->getHostFilter(), $host);\n\n if ($result === false) {\n throw new Exception('Error applying host filter');\n } elseif ($result) {\n $this->logger->debug(\"Host filter allows '$host'\");\n return true;\n } else {\n $this->logger->debug(\"Host filter disallows '$host'\");\n return false;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function getXdmodAccount()\n {\n $samlAttrs = $this->_as->getAttributes();\n /*\n * SimpleSAMLphp uses its own session, this sets it back.\n */\n \\SimpleSAML_Session::getSessionFromRequest()->cleanup();\n if ($this->_as->isAuthenticated()) {\n $userName = $samlAttrs['username'][0];\n\n $xdmodUserId = \\XDUser::userExistsWithUsername($userName);\n\n if ($xdmodUserId !== INVALID) {\n $user = \\XDUser::getUserByID($xdmodUserId);\n $user->setSSOAttrs($samlAttrs);\n return $user;\n }\n\n // If we've gotten this far then we're creating a new user. Proceed with gathering the\n // information we'll need to do so.\n $emailAddress = isset($samlAttrs['email_address']) ? $samlAttrs['email_address'][0] : NO_EMAIL_ADDRESS_SET;\n $systemUserName = isset($samlAttrs['system_username']) ? $samlAttrs['system_username'][0] : $userName;\n $firstName = isset($samlAttrs['first_name']) ? $samlAttrs['first_name'][0] : 'UNKNOWN';\n $middleName = isset($samlAttrs['middle_name']) ? $samlAttrs['middle_name'][0] : null;\n $lastName = isset($samlAttrs['last_name']) ? $samlAttrs['last_name'][0] : null;\n $personId = \\DataWarehouse::getPersonIdFromPII($systemUserName, $samlAttrs['organization'][0]);\n\n // Attempt to identify which organization this user should be associated with. Prefer\n // using the personId if not unknown, then fall back to the saml attributes if the\n // 'organization' property is present, and finally defaulting to the Unknown organization\n // if none of the preceding conditions are met.\n $userOrganization = $this->getOrganizationId($samlAttrs, $personId);\n\n try {\n $newUser = new \\XDUser(\n $userName,\n null,\n $emailAddress,\n $firstName,\n $middleName,\n $lastName,\n array(ROLE_ID_USER),\n ROLE_ID_USER,\n $userOrganization,\n $personId,\n $samlAttrs\n );\n } catch (Exception $e) {\n throw new Exception('An account is currently configured with this information, please contact an administrator.');\n }\n\n $newUser->setUserType(SSO_USER_TYPE);\n\n try {\n $newUser->saveUser();\n } catch (Exception $e) {\n $this->logger->err('User creation failed: ' . $e->getMessage());\n throw $e;\n }\n\n $this->handleNotifications($newUser, $samlAttrs, ($personId != UNKNOWN_USER_TYPE));\n\n return $newUser;\n }\n throw new \\DataWarehouse\\Query\\Exceptions\\AccessDeniedException('Authentication failure.');\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $databaseId, string $collectionId, array $queries, Response $response, Database $dbForProject) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n\n \\array_push(\n $queries,\n Query::equal('collectionId', [$collectionId]),\n Query::equal('databaseId', [$databaseId])\n );\n\n // Get cursor document if there was a cursor query\n $cursor = \\array_filter($queries, function ($query) {\n return \\in_array($query->getMethod(), [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n });\n\n $cursor = \\reset($cursor);\n\n if ($cursor) {\n $attributeId = $cursor->getValue();\n $cursorDocument = Authorization::skip(fn() => $dbForProject->find('attributes', [\n Query::equal('collectionId', [$collectionId]),\n Query::equal('databaseId', [$databaseId]),\n Query::equal('key', [$attributeId]),\n Query::limit(1),\n ]));\n\n if (empty($cursorDocument) || $cursorDocument[0]->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Attribute '{$attributeId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument[0]);\n }\n\n $filters = Query::groupByType($queries)['filters'];\n\n $attributes = $dbForProject->find('attributes', $queries);\n $total = $dbForProject->count('attributes', $filters, APP_LIMIT_COUNT);\n\n $response->dynamic(new Document([\n 'attributes' => $attributes,\n 'total' => $total,\n ]), Response::MODEL_ATTRIBUTE_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function createLazyLoadingValueHolderFactory(): LazyLoadingValueHolderFactory\n {\n $config = new Configuration();\n\n // Proxy cache directory needs to be created before\n if (!is_dir($this->proxyCacheDir)) {\n if (false === @mkdir($this->proxyCacheDir, 0777, true)) {\n if (!is_dir($this->proxyCacheDir)) {\n $error = error_get_last();\n\n throw new RuntimeException(sprintf(\n 'Unable to create the Repository Proxy directory \"%s\": %s',\n $this->proxyCacheDir,\n $error['message']\n ));\n }\n }\n } elseif (!is_writable($this->proxyCacheDir)) {\n throw new RuntimeException(sprintf(\n 'The Repository Proxy directory \"%s\" is not writeable for the current system user.',\n $this->proxyCacheDir\n ));\n }\n\n $config->setGeneratorStrategy(new FileWriterGeneratorStrategy(new FileLocator($this->proxyCacheDir)));\n $config->setProxiesTargetDir($this->proxyCacheDir);\n\n spl_autoload_register($config->getProxyAutoloader());\n\n return new LazyLoadingValueHolderFactory($config);\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function addOverride($classname)\n\t{\n\t\t$orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname.'Core');\n\t\tif (!$path)\n\t\t\t$path = 'modules'.DIRECTORY_SEPARATOR.$classname.DIRECTORY_SEPARATOR.$classname.'.php';\n\t\t$path_override = $this->getLocalPath().'override'.DIRECTORY_SEPARATOR.$path;\n\n\t\tif (!file_exists($path_override))\n\t\t\treturn false;\n\t\telse\n\t\t\tfile_put_contents($path_override, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($path_override)));\n\n\t\t$pattern_escape_com = '#(^\\s*?\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism';\n\t\t// Check if there is already an override file, if not, we just need to copy the file\n\t\tif ($file = PrestaShopAutoload::getInstance()->getClassPath($classname))\n\t\t{\n\t\t\t// Check if override file is writable\n\t\t\t$override_path = _PS_ROOT_DIR_.'/'.$file;\n\n\t\t\tif ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path)))\n\t\t\t\tthrow new Exception(sprintf(Tools::displayError('file (%s) not writable'), $override_path));\n\n\t\t\t// Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n\t\t\tdo $uniq = uniqid();\n\t\t\twhile (class_exists($classname.'OverrideOriginal_remove', false));\n\n\t\t\t// Make a reflection of the override class and the module override class\n\t\t\t$override_file = file($override_path);\n\t\t\t$override_file = array_diff($override_file, array(\"\\n\"));\n\t\t\teval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class '.$classname.'OverrideOriginal'.$uniq), implode('', $override_file)));\n\t\t\t$override_class = new ReflectionClass($classname.'OverrideOriginal'.$uniq);\n\n\t\t\t$module_file = file($path_override);\n\t\t\t$module_file = array_diff($module_file, array(\"\\n\"));\n\t\t\teval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n\t\t\t$module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n\t\t\t// Check if none of the methods already exists in the override class\n\t\t\tforeach ($module_class->getMethods() as $method)\n\t\t\t{\n\t\t\t\tif ($override_class->hasMethod($method->getName()))\n\t\t\t\t{\n\t\t\t\t\t$method_override = $override_class->getMethod($method->getName());\n\t\t\t\t\tif (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version))\n\t\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.'), $method->getName(), $classname, $name[1], $version[1], $date[1]));\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('The method %1$s in the class %2$s is already overridden.'), $method->getName(), $classname));\n\t\t\t\t}\n\n\t\t\t\t$module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1\", $module_file);\n\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override method %1$s in class %2$s.'), $method->getName(), $classname));\n\t\t\t}\n\n\t\t\t// Check if none of the properties already exists in the override class\n\t\t\tforeach ($module_class->getProperties() as $property)\n\t\t\t{\n\t\t\t\tif ($override_class->hasProperty($property->getName()))\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('The property %1$s in the class %2$s is already defined.'), $property->getName(), $classname));\n\n\t\t\t\t$module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1$2$3\", $module_file);\n\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override property %1$s in class %2$s.'), $property->getName(), $classname));\n\t\t\t}\n\n\t\t\tforeach ($module_class->getConstants() as $constant => $value)\n\t\t\t{\n\t\t\t\tif ($override_class->hasConstant($constant))\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('The constant %1$s in the class %2$s is already defined.'), $constant, $classname));\n\n\t\t\t\t$module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1$2\", $module_file);\n\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override constant %1$s in class %2$s.'), $constant, $classname));\n\t\t\t}\n\n\t\t\t// Insert the methods from module override in override\n\t\t\t$copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);\n\t\t\tarray_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);\n\t\t\t$code = implode('', $override_file);\n\n\t\t\tfile_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$override_src = $path_override;\n\n\t\t\t$override_dest = _PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'override'.DIRECTORY_SEPARATOR.$path;\n\t\t\t$dir_name = dirname($override_dest);\n\n\t\t\tif (!$orig_path && !is_dir($dir_name))\n\t\t\t{\n\t\t\t\t$oldumask = umask(0000);\n\t\t\t\t@mkdir($dir_name, 0777);\n\t\t\t\tumask($oldumask);\n\t\t\t}\n\n\t\t\tif (!is_writable($dir_name))\n\t\t\t\tthrow new Exception(sprintf(Tools::displayError('directory (%s) not writable'), $dir_name));\n\t\t\t$module_file = file($override_src);\n\t\t\t$module_file = array_diff($module_file, array(\"\\n\"));\n\n\t\t\tif ($orig_path)\n\t\t\t{\n\t\t\t\tdo $uniq = uniqid();\n\t\t\t\twhile (class_exists($classname.'OverrideOriginal_remove', false));\n\t\t\t\teval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n\t\t\t\t$module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n\t\t\t\t// For each method found in the override, prepend a comment with the module name and version\n\t\t\t\tforeach ($module_class->getMethods() as $method)\n\t\t\t\t{\n\t\t\t\t\t$module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1\", $module_file);\n\t\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override method %1$s in class %2$s.'), $method->getName(), $classname));\n\t\t\t\t}\n\n\t\t\t\t// Same loop for properties\n\t\t\t\tforeach ($module_class->getProperties() as $property)\n\t\t\t\t{\n\t\t\t\t\t$module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1$2$3\", $module_file);\n\t\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override property %1$s in class %2$s.'), $property->getName(), $classname));\n\t\t\t\t}\n\n\t\t\t\t// Same loop for constants\n\t\t\t\tforeach ($module_class->getConstants() as $constant => $value)\n\t\t\t\t{\n\t\t\t\t\t$module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n\\t* module: \".$this->name.\"\\n\\t* date: \".date('Y-m-d H:i:s').\"\\n\\t* version: \".$this->version.\"\\n\\t*/\\n\\t$1$2\", $module_file);\n\t\t\t\t\tif ($module_file === NULL)\n\t\t\t\t\t\tthrow new Exception(sprintf(Tools::displayError('Failed to override constant %1$s in class %2$s.'), $constant, $classname));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfile_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));\n\n\t\t\t// Re-generate the class index\n\t\t\tTools::generateIndex();\n\t\t}\n\t\treturn true;\n\t}", "smellKey": "S112", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function getPersonIdByLongName($longName)\n {\n $sql = 'SELECT id FROM person WHERE long_name = :name';\n $people = $this->dbh->query($sql, array('name' => $longName));\n $isUnknown = strtolower($longName) === 'unknown';\n\n // We only care if there is more than one result if the $longName is not 'unknown'.\n if (count($people) !== 1 && $isUnknown === false) {\n throw new Exception(\n sprintf('Found %d people, expected 1 for %s', count($people), $longName)\n );\n }\n return $people[0]['id'];\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "static function HandleError($code, $string, $file, $line, $context = '')\n {\n // ignore supressed errors\n if (error_reporting() == 0) {\n return;\n }\n\n if (self::$IGNORE_DEPRECATED && strpos($string, \"deprecated\") === true) {\n return true;\n }\n\n throw new Exception($string . \" in \" . basename($file) . \" at line $line\", $code);\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getById(string $id): ?CustomLayout\n {\n $cacheKey = 'customlayout_' . $id;\n\n try {\n $customLayout = RuntimeCache::get($cacheKey);\n if (!$customLayout) {\n throw new Exception('Custom Layout in registry is null');\n }\n } catch (Exception $e) {\n try {\n $customLayout = new self();\n $customLayout->getDao()->getById($id);\n RuntimeCache::set($cacheKey, $customLayout);\n } catch (Model\\Exception\\NotFoundException $e) {\n return null;\n }\n }\n\n return $customLayout;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $provider, string $code, string $state, string $error, string $error_description, Request $request, Response $response, Document $project, Document $user, Database $dbForProject, Reader $geodb, Event $events) use ($oauthDefaultSuccess) {\n\n $protocol = $request->getProtocol();\n $callback = $protocol . '://' . $request->getHostname() . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project->getId();\n $defaultState = ['success' => $project->getAttribute('url', ''), 'failure' => ''];\n $validateURL = new URL();\n $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? '';\n $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}';\n $providerEnabled = $project->getAttribute('authProviders', [])[$provider . 'Enabled'] ?? false;\n\n $className = 'Appwrite\\\\Auth\\\\OAuth2\\\\' . \\ucfirst($provider);\n\n if (!\\class_exists($className)) {\n throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED);\n }\n\n $providers = Config::getParam('providers');\n $providerName = $providers[$provider]['name'] ?? '';\n\n /** @var Appwrite\\Auth\\OAuth2 $oauth2 */\n $oauth2 = new $className($appId, $appSecret, $callback);\n\n if (!empty($state)) {\n try {\n $state = \\array_merge($defaultState, $oauth2->parseState($state));\n } catch (\\Exception $exception) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to parse login state params as passed from OAuth2 provider');\n }\n } else {\n $state = $defaultState;\n }\n\n if (!$validateURL->isValid($state['success'])) {\n throw new Exception(Exception::PROJECT_INVALID_SUCCESS_URL);\n }\n\n if (!empty($state['failure']) && !$validateURL->isValid($state['failure'])) {\n throw new Exception(Exception::PROJECT_INVALID_FAILURE_URL);\n }\n $failure = [];\n if (!empty($state['failure'])) {\n $failure = URLParser::parse($state['failure']);\n }\n $failureRedirect = (function (string $type, ?string $message = null, ?int $code = null) use ($failure, $response) {\n $exception = new Exception($type, $message, $code);\n if (!empty($failure)) {\n $query = URLParser::parseQuery($failure['query']);\n $query['error'] = json_encode([\n 'message' => $exception->getMessage(),\n 'type' => $exception->getType(),\n 'code' => !\\is_null($code) ? $code : $exception->getCode(),\n ]);\n $failure['query'] = URLParser::unparseQuery($query);\n $response->redirect(URLParser::unparse($failure), 301);\n }\n\n throw $exception;\n });\n\n if (!$providerEnabled) {\n $failureRedirect(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please enable the provider from your ' . APP_NAME . ' console to continue.');\n }\n\n if (!empty($error)) {\n $message = 'The ' . $providerName . ' OAuth2 provider returned an error: ' . $error;\n if (!empty($error_description)) {\n $message .= ': ' . $error_description;\n }\n $failureRedirect(Exception::USER_OAUTH2_PROVIDER_ERROR, $message);\n }\n\n if (empty($code)) {\n $failureRedirect(Exception::USER_OAUTH2_PROVIDER_ERROR, 'Missing OAuth2 code. Please contact the Appwrite team for additional support.');\n }\n\n if (!empty($appSecret) && isset($appSecret['version'])) {\n $key = App::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']);\n $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \\hex2bin($appSecret['iv']), \\hex2bin($appSecret['tag']));\n }\n\n $accessToken = '';\n $refreshToken = '';\n $accessTokenExpiry = 0;\n\n try {\n $accessToken = $oauth2->getAccessToken($code);\n $refreshToken = $oauth2->getRefreshToken($code);\n $accessTokenExpiry = $oauth2->getAccessTokenExpiry($code);\n } catch (OAuth2Exception $ex) {\n $failureRedirect(\n $ex->getType(),\n 'Failed to obtain access token. The ' . $providerName . ' OAuth2 provider returned an error: ' . $ex->getMessage(),\n $ex->getCode(),\n );\n }\n\n $oauth2ID = $oauth2->getUserID($accessToken);\n if (empty($oauth2ID)) {\n $failureRedirect(Exception::USER_MISSING_ID);\n }\n\n $name = $oauth2->getUserName($accessToken);\n $email = $oauth2->getUserEmail($accessToken);\n\n // Check if this identity is connected to a different user\n if (!$user->isEmpty()) {\n $userId = $user->getId();\n\n $identitiesWithMatchingEmail = $dbForProject->find('identities', [\n Query::equal('providerEmail', [$email]),\n Query::notEqual('userId', $userId),\n ]);\n if (!empty($identitiesWithMatchingEmail)) {\n throw new Exception(Exception::USER_ALREADY_EXISTS);\n }\n }\n\n $sessions = $user->getAttribute('sessions', []);\n $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $current = Auth::sessionVerify($sessions, Auth::$secret, $authDuration);\n\n if ($current) { // Delete current session of new one.\n $currentDocument = $dbForProject->getDocument('sessions', $current);\n if (!$currentDocument->isEmpty()) {\n $dbForProject->deleteDocument('sessions', $currentDocument->getId());\n $dbForProject->deleteCachedDocument('users', $user->getId());\n }\n }\n\n if ($user->isEmpty()) {\n $session = $dbForProject->findOne('sessions', [ // Get user by provider id\n Query::equal('provider', [$provider]),\n Query::equal('providerUid', [$oauth2ID]),\n ]);\n if ($session !== false && !$session->isEmpty()) {\n $user->setAttributes($dbForProject->getDocument('users', $session->getAttribute('userId'))->getArrayCopy());\n }\n }\n\n if ($user === false || $user->isEmpty()) { // No user logged in or with OAuth2 provider ID, create new one or connect with account with same email\n if (empty($email)) {\n throw new Exception(Exception::USER_UNAUTHORIZED, 'OAuth provider failed to return email.');\n }\n\n /**\n * Is verified is not used yet, since we don't know after an accout is created anymore if it was verified or not.\n */\n $isVerified = $oauth2->isEmailVerified($accessToken);\n\n $userWithEmail = $dbForProject->findOne('users', [\n Query::equal('email', [$email]),\n ]);\n if ($userWithEmail !== false && !$userWithEmail->isEmpty()) {\n $user->setAttributes($userWithEmail->getArrayCopy());\n }\n\n // If user is not found, check if there is an identity with the same provider user ID\n if ($user === false || $user->isEmpty()) {\n $identity = $dbForProject->findOne('identities', [\n Query::equal('provider', [$provider]),\n Query::equal('providerUid', [$oauth2ID]),\n ]);\n\n if ($identity !== false && !$identity->isEmpty()) {\n $user = $dbForProject->getDocument('users', $identity->getAttribute('userId'));\n }\n }\n\n if ($user === false || $user->isEmpty()) { // Last option -> create the user\n $limit = $project->getAttribute('auths', [])['limit'] ?? 0;\n\n if ($limit !== 0) {\n $total = $dbForProject->count('users', max: APP_LIMIT_USERS);\n\n if ($total >= $limit) {\n $failureRedirect(Exception::USER_COUNT_EXCEEDED);\n }\n }\n\n // Makes sure this email is not already used in another identity\n $identityWithMatchingEmail = $dbForProject->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n if ($identityWithMatchingEmail !== false && !$identityWithMatchingEmail->isEmpty()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n try {\n $userId = ID::unique();\n $user->setAttributes([\n '$id' => $userId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'email' => $email,\n 'emailVerification' => true,\n 'status' => true, // Email should already be authenticated by OAuth2 provider\n 'password' => null,\n 'hash' => Auth::DEFAULT_ALGO,\n 'hashOptions' => Auth::DEFAULT_ALGO_OPTIONS,\n 'passwordUpdate' => null,\n 'registration' => DateTime::now(),\n 'reset' => false,\n 'name' => $name,\n 'prefs' => new \\stdClass(),\n 'sessions' => null,\n 'tokens' => null,\n 'memberships' => null,\n 'search' => implode(' ', [$userId, $email, $name]),\n 'accessedAt' => DateTime::now(),\n ]);\n $user->removeAttribute('$internalId');\n Authorization::skip(fn() => $dbForProject->createDocument('users', $user));\n } catch (Duplicate) {\n $failureRedirect(Exception::USER_ALREADY_EXISTS);\n }\n }\n }\n\n Authorization::setRole(Role::user($user->getId())->toString());\n Authorization::setRole(Role::users()->toString());\n\n if (false === $user->getAttribute('status')) { // Account is blocked\n $failureRedirect(Exception::USER_BLOCKED); // User is in status blocked\n }\n\n $identity = $dbForProject->findOne('identities', [\n Query::equal('userInternalId', [$user->getInternalId()]),\n Query::equal('provider', [$provider]),\n Query::equal('providerUid', [$oauth2ID]),\n ]);\n if ($identity === false || $identity->isEmpty()) {\n // Before creating the identity, check if the email is already associated with another user\n $userId = $user->getId();\n\n $identitiesWithMatchingEmail = $dbForProject->find('identities', [\n Query::equal('providerEmail', [$email]),\n Query::notEqual('userId', $user->getId()),\n ]);\n if (!empty($identitiesWithMatchingEmail)) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n\n $dbForProject->createDocument('identities', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($userId)),\n Permission::delete(Role::user($userId)),\n ],\n 'userInternalId' => $user->getInternalId(),\n 'userId' => $userId,\n 'provider' => $provider,\n 'providerUid' => $oauth2ID,\n 'providerEmail' => $email,\n 'providerAccessToken' => $accessToken,\n 'providerRefreshToken' => $refreshToken,\n 'providerAccessTokenExpiry' => DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry),\n ]));\n } else {\n $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry));\n $dbForProject->updateDocument('identities', $identity->getId(), $identity);\n }\n\n // Create session token, verify user account and update OAuth2 ID and Access Token\n $duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;\n $detector = new Detector($request->getUserAgent('UNKNOWN'));\n $record = $geodb->get($request->getIP());\n $secret = Auth::tokenGenerator();\n $expire = DateTime::formatTz(DateTime::addSeconds(new \\DateTime(), $duration));\n\n $session = new Document(array_merge([\n '$id' => ID::unique(),\n 'userId' => $user->getId(),\n 'userInternalId' => $user->getInternalId(),\n 'provider' => $provider,\n 'providerUid' => $oauth2ID,\n 'providerAccessToken' => $accessToken,\n 'providerRefreshToken' => $refreshToken,\n 'providerAccessTokenExpiry' => DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry),\n 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak\n 'userAgent' => $request->getUserAgent('UNKNOWN'),\n 'ip' => $request->getIP(),\n 'countryCode' => ($record) ? \\strtolower($record['country']['iso_code']) : '--',\n ], $detector->getOS(), $detector->getClient(), $detector->getDevice()));\n\n if (empty($user->getAttribute('email'))) {\n $user->setAttribute('email', $oauth2->getUserEmail($accessToken));\n }\n\n if (empty($user->getAttribute('name'))) {\n $user->setAttribute('name', $oauth2->getUserName($accessToken));\n }\n\n $user\n ->setAttribute('status', true)\n ;\n\n Authorization::setRole(Role::user($user->getId())->toString());\n\n $dbForProject->updateDocument('users', $user->getId(), $user);\n\n $session = $dbForProject->createDocument('sessions', $session->setAttribute('$permissions', [\n Permission::read(Role::user($user->getId())),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ]));\n\n $dbForProject->deleteCachedDocument('users', $user->getId());\n\n $session->setAttribute('expire', $expire);\n\n $events\n ->setParam('userId', $user->getId())\n ->setParam('sessionId', $session->getId())\n ->setPayload($response->output($session, Response::MODEL_SESSION))\n ;\n\n if (!Config::getParam('domainVerification')) {\n $response->addHeader('X-Fallback-Cookies', \\json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]));\n }\n\n // Add keys for non-web platforms - TODO - add verification phase to aviod session sniffing\n if (parse_url($state['success'], PHP_URL_PATH) === $oauthDefaultSuccess) {\n $state['success'] = URLParser::parse($state['success']);\n $query = URLParser::parseQuery($state['success']['query']);\n $query['project'] = $project->getId();\n $query['domain'] = Config::getParam('cookieDomain');\n $query['key'] = Auth::$cookieName;\n $query['secret'] = Auth::encodeSession($user->getId(), $secret);\n $state['success']['query'] = URLParser::unparseQuery($query);\n $state['success'] = URLParser::unparse($state['success']);\n }\n\n $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)\n ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \\DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))\n ->redirect($state['success'])\n ;\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function render($name, array $parameters = array())\n {\n $storage = $this->load($name);\n $key = hash('sha256', serialize($storage));\n $this->current = $key;\n $this->parents[$key] = null;\n\n // attach the global variables\n $parameters = array_replace($this->getGlobals(), $parameters);\n // render\n if (false === $content = $this->evaluateTpl($storage, $parameters)) {\n throw new \\RuntimeException(sprintf('The template \"%s\" cannot be rendered.', $this->parser->parse($name)));\n }\n\n // decorator\n if ($this->parents[$key]) {\n /** @var SlotsHelper $slots */\n $slots = $this->get('slots');\n $this->stack[] = $slots->get('_content');\n $slots->set('_content', $content);\n\n $content = $this->render($this->parents[$key], $parameters);\n\n $slots->set('_content', array_pop($this->stack));\n }\n\n return $content;\n }", "smellKey": "S112", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "function (string $databaseId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) {\n\n $database = $dbForProject->getDocument('databases', $databaseId);\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n $grouped = Query::groupByType($queries);\n $limit = $grouped['limit'] ?? APP_LIMIT_COUNT;\n $offset = $grouped['offset'] ?? 0;\n\n $audit = new Audit($dbForProject);\n $resource = 'database/' . $databaseId;\n $logs = $audit->getLogsByResource($resource, $limit, $offset);\n\n $output = [];\n\n foreach ($logs as $i => &$log) {\n $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN';\n\n $detector = new Detector($log['userAgent']);\n $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)\n\n $os = $detector->getOS();\n $client = $detector->getClient();\n $device = $detector->getDevice();\n\n $output[$i] = new Document([\n 'event' => $log['event'],\n 'userId' => ID::custom($log['data']['userId']),\n 'userEmail' => $log['data']['userEmail'] ?? null,\n 'userName' => $log['data']['userName'] ?? null,\n 'mode' => $log['data']['mode'] ?? null,\n 'ip' => $log['ip'],\n 'time' => $log['time'],\n 'osCode' => $os['osCode'],\n 'osName' => $os['osName'],\n 'osVersion' => $os['osVersion'],\n 'clientType' => $client['clientType'],\n 'clientCode' => $client['clientCode'],\n 'clientName' => $client['clientName'],\n 'clientVersion' => $client['clientVersion'],\n 'clientEngine' => $client['clientEngine'],\n 'clientEngineVersion' => $client['clientEngineVersion'],\n 'deviceName' => $device['deviceName'],\n 'deviceBrand' => $device['deviceBrand'],\n 'deviceModel' => $device['deviceModel']\n ]);\n\n $record = $geodb->get($log['ip']);\n\n if ($record) {\n $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \\strtolower($record['country']['iso_code']) : '--';\n $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown'));\n } else {\n $output[$i]['countryCode'] = '--';\n $output[$i]['countryName'] = $locale->getText('locale.country.unknown');\n }\n }\n\n $response->dynamic(new Document([\n 'total' => $audit->countLogsByResource($resource),\n 'logs' => $output,\n ]), Response::MODEL_LOG_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (array $queries, string $search, Response $response, Document $project, Database $dbForConsole) {\n $queries = Query::parseQueries($queries);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n $queries[] = Query::equal('projectInternalId', [$project->getInternalId()]);\n\n // Get cursor document if there was a cursor query\n $cursor = Query::getByType($queries, [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $ruleId = $cursor->getValue();\n $cursorDocument = $dbForConsole->getDocument('rules', $ruleId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Rule '{$ruleId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $rules = $dbForConsole->find('rules', $queries);\n foreach ($rules as $rule) {\n $certificate = $dbForConsole->getDocument('certificates', $rule->getAttribute('certificateId', ''));\n $rule->setAttribute('logs', $certificate->getAttribute('logs', ''));\n $rule->setAttribute('renewAt', $certificate->getAttribute('renewDate', ''));\n }\n\n $response->dynamic(new Document([\n 'rules' => $rules,\n 'total' => $dbForConsole->count('rules', $filterQueries, APP_LIMIT_COUNT),\n ]), Response::MODEL_PROXY_RULE_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $functionId, string $deploymentId, string $buildId, Request $request, Response $response, Database $dbForProject, Document $project, Event $events) use ($redeployVcs) {\n\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $deployment = $dbForProject->getDocument('deployments', $deploymentId);\n\n if ($deployment->isEmpty()) {\n throw new Exception(Exception::DEPLOYMENT_NOT_FOUND);\n }\n\n $build = Authorization::skip(fn () => $dbForProject->getDocument('builds', $buildId));\n\n if ($build->isEmpty()) {\n throw new Exception(Exception::BUILD_NOT_FOUND);\n }\n\n $deploymentId = ID::unique();\n\n $deployment->removeAttribute('$internalId');\n $deployment = $dbForProject->createDocument('deployments', $deployment->setAttributes([\n '$id' => $deploymentId,\n 'buildId' => '',\n 'buildInternalId' => '',\n 'entrypoint' => $function->getAttribute('entrypoint'),\n 'commands' => $function->getAttribute('commands', ''),\n 'search' => implode(' ', [$deploymentId, $function->getAttribute('entrypoint')]),\n ]));\n\n $buildEvent = new Build();\n\n $buildEvent\n ->setType(BUILD_TYPE_DEPLOYMENT)\n ->setResource($function)\n ->setDeployment($deployment)\n ->setProject($project)\n ->trigger();\n\n $events\n ->setParam('functionId', $function->getId())\n ->setParam('deploymentId', $deployment->getId());\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function getUserTask(int $id, ?string $userId): Task {\n\t\ttry {\n\t\t\t$taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);\n\t\t\treturn $taskEntity->toPublicTask();\n\t\t} catch (DoesNotExistException $e) {\n\t\t\tthrow new TaskNotFoundException('Could not find task with the provided id and user id');\n\t\t} catch (MultipleObjectsReturnedException $e) {\n\t\t\tthrow new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);\n\t\t} catch (Exception $e) {\n\t\t\tthrow new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function getConfigurationSection($section, $useCachedOptions = true)\n{\n global $iniData;\n\n if (empty($section)) {\n $msg = \"Configuration section not specified\";\n throw new Exception($msg);\n }\n\n if (null === $iniData || !$useCachedOptions) {\n $iniData = loadConfiguration();\n }\n\n // Verifying that the section exist.\n if (!array_key_exists($section, $iniData)) {\n $msg = \"Undefined configuration section: '$section'\";\n throw new Exception($msg);\n }\n\n return $iniData[$section];\n}", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $functionId, string $name, string $runtime, array $execute, array $events, string $schedule, int $timeout, bool $enabled, bool $logging, string $entrypoint, string $commands, string $installationId, string $providerRepositoryId, string $providerBranch, bool $providerSilentMode, string $providerRootDirectory, string $templateRepository, string $templateOwner, string $templateRootDirectory, string $templateBranch, Request $request, Response $response, Database $dbForProject, Document $project, Document $user, Event $eventsInstance, Database $dbForConsole, GitHub $github) use ($redeployVcs) {\n $functionId = ($functionId == 'unique()') ? ID::unique() : $functionId;\n\n // build from template\n $template = new Document([]);\n if (\n !empty($templateRepository)\n && !empty($templateOwner)\n && !empty($templateRootDirectory)\n && !empty($templateBranch)\n ) {\n $template->setAttribute('repositoryName', $templateRepository)\n ->setAttribute('ownerName', $templateOwner)\n ->setAttribute('rootDirectory', $templateRootDirectory)\n ->setAttribute('branch', $templateBranch);\n }\n\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if (!empty($installationId) && $installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n if (!empty($providerRepositoryId) && (empty($installationId) || empty($providerBranch))) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'When connecting to VCS (Version Control System), you need to provide \"installationId\" and \"providerBranch\".');\n }\n\n $function = $dbForProject->createDocument('functions', new Document([\n '$id' => $functionId,\n 'execute' => $execute,\n 'enabled' => $enabled,\n 'live' => true,\n 'logging' => $logging,\n 'name' => $name,\n 'runtime' => $runtime,\n 'deploymentInternalId' => '',\n 'deployment' => '',\n 'events' => $events,\n 'schedule' => $schedule,\n 'scheduleInternalId' => '',\n 'scheduleId' => '',\n 'timeout' => $timeout,\n 'entrypoint' => $entrypoint,\n 'commands' => $commands,\n 'search' => implode(' ', [$functionId, $name, $runtime]),\n 'version' => 'v3',\n 'installationId' => $installation->getId(),\n 'installationInternalId' => $installation->getInternalId(),\n 'providerRepositoryId' => $providerRepositoryId,\n 'repositoryId' => '',\n 'repositoryInternalId' => '',\n 'providerBranch' => $providerBranch,\n 'providerRootDirectory' => $providerRootDirectory,\n 'providerSilentMode' => $providerSilentMode,\n ]));\n\n $schedule = Authorization::skip(\n fn () => $dbForConsole->createDocument('schedules', new Document([\n 'region' => App::getEnv('_APP_REGION', 'default'), // Todo replace with projects region\n 'resourceType' => 'function',\n 'resourceId' => $function->getId(),\n 'resourceInternalId' => $function->getInternalId(),\n 'resourceUpdatedAt' => DateTime::now(),\n 'projectId' => $project->getId(),\n 'schedule' => $function->getAttribute('schedule'),\n 'active' => false,\n ]))\n );\n\n $function->setAttribute('scheduleId', $schedule->getId());\n $function->setAttribute('scheduleInternalId', $schedule->getInternalId());\n\n // Git connect logic\n if (!empty($providerRepositoryId)) {\n $repository = $dbForConsole->createDocument('repositories', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'installationId' => $installation->getId(),\n 'installationInternalId' => $installation->getInternalId(),\n 'projectId' => $project->getId(),\n 'projectInternalId' => $project->getInternalId(),\n 'providerRepositoryId' => $providerRepositoryId,\n 'resourceId' => $function->getId(),\n 'resourceInternalId' => $function->getInternalId(),\n 'resourceType' => 'function',\n 'providerPullRequestIds' => []\n ]));\n\n $function->setAttribute('repositoryId', $repository->getId());\n $function->setAttribute('repositoryInternalId', $repository->getInternalId());\n }\n\n $function = $dbForProject->updateDocument('functions', $function->getId(), $function);\n\n // Redeploy vcs logic\n if (!empty($providerRepositoryId)) {\n $redeployVcs($request, $function, $project, $installation, $dbForProject, $template, $github);\n }\n\n $functionsDomain = App::getEnv('_APP_DOMAIN_FUNCTIONS', '');\n if (!empty($functionsDomain)) {\n $ruleId = ID::unique();\n $routeSubdomain = ID::unique();\n $domain = \"{$routeSubdomain}.{$functionsDomain}\";\n\n $rule = Authorization::skip(\n fn () => $dbForConsole->createDocument('rules', new Document([\n '$id' => $ruleId,\n 'projectId' => $project->getId(),\n 'projectInternalId' => $project->getInternalId(),\n 'domain' => $domain,\n 'resourceType' => 'function',\n 'resourceId' => $function->getId(),\n 'resourceInternalId' => $function->getInternalId(),\n 'status' => 'verified',\n 'certificateId' => '',\n ]))\n );\n\n /** Trigger Webhook */\n $ruleModel = new Rule();\n $ruleCreate = new Event(Event::WEBHOOK_QUEUE_NAME, Event::WEBHOOK_CLASS_NAME);\n $ruleCreate\n ->setProject($project)\n ->setEvent('rules.[ruleId].create')\n ->setParam('ruleId', $rule->getId())\n ->setPayload($rule->getArrayCopy(array_keys($ruleModel->getRules())))\n ->trigger();\n\n /** Trigger Functions */\n $ruleCreate\n ->setClass(Event::FUNCTIONS_CLASS_NAME)\n ->setQueue(Event::FUNCTIONS_QUEUE_NAME)\n ->trigger();\n\n /** Trigger realtime event */\n $allEvents = Event::generateEvents('rules.[ruleId].create', [\n 'ruleId' => $rule->getId(),\n ]);\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $allEvents[0],\n payload: $rule,\n project: $project\n );\n Realtime::send(\n projectId: 'console',\n payload: $rule->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n Realtime::send(\n projectId: $project->getId(),\n payload: $rule->getArrayCopy(),\n events: $allEvents,\n channels: $target['channels'],\n roles: $target['roles']\n );\n }\n\n $eventsInstance->setParam('functionId', $function->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($function, Response::MODEL_FUNCTION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addAclOrganization($aclName, $organizationId)\n {\n if (empty($this->_id)) {\n throw new Exception(\"This user must be saved prior to calling \" . __FUNCTION__ . \".\");\n }\n\n // If they haven't provided an organizationId then we can't add an\n // acl relation to it.\n if (!isset($organizationId)) {\n return;\n }\n\n $acl = Acls::getAclByName($aclName);\n\n if ( null == $acl) {\n throw new Exception(\"Unable to retrieve acl for: $aclName\");\n }\n\n\n $cleanUserAclGroupByParameters = <<<SQL\nDELETE FROM user_acl_group_by_parameters\nWHERE user_id = :user_id AND\n acl_id = :acl_id\nSQL;\n\n $this->_pdo->execute($cleanUserAclGroupByParameters, array(\n ':user_id' => $this->_id,\n ':acl_id' => $acl->getAclId()\n ));\n\n $populateUserAclGroupByParameters = <<<SQL\nINSERT INTO user_acl_group_by_parameters (user_id, acl_id, group_by_id, value)\nSELECT inc.*\nFROM (\n SELECT\n :user_id AS user_id,\n :acl_id AS acl_id,\n gb.group_by_id AS group_by_id,\n :value AS value\n FROM group_bys gb\n WHERE gb.name = 'provider'\n) inc\nLEFT JOIN user_acl_group_by_parameters cur\n ON cur.user_id = inc.user_id\n AND cur.acl_id = inc.acl_id\n AND cur.group_by_id = inc.group_by_id\n AND cur.value = inc.value\nWHERE cur.user_acl_parameter_id IS NULL;\nSQL;\n\n $this->_pdo->execute($populateUserAclGroupByParameters, array(\n ':user_id' => $this->_id,\n ':acl_id' => $acl->getAclId(),\n ':value' => $organizationId\n ));\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $index = $collection->find('key', $key, 'indexes');\n if (empty($index)) {\n throw new Exception(Exception::INDEX_NOT_FOUND);\n }\n\n $response->dynamic($index, Response::MODEL_INDEX);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function deleteMissingSections(): void\n {\n // We can't run this code if we don't have the list of updated sections\n if (!isset($this->input['_found_sections'])) {\n return;\n }\n $found_sections = $this->input['_found_sections'];\n\n // Safety check to avoid deleting all sections if some code run an update\n // without the _sections keys.\n // Deletion is only done if the special \"_delete_missing_sections\" key\n // is present\n $delete_missing_sections = $this->input['_delete_missing_sections'] ?? false;\n if ($delete_missing_sections) {\n // Avoid empty IN clause\n if (empty($found_sections)) {\n $found_sections = [-1];\n }\n\n $missing_sections = (new Section())->find([\n // Is part of this form\n 'forms_forms_id' => $this->fields['id'],\n\n // Was not found in the submitted data\n 'id' => ['NOT IN', $found_sections],\n ]);\n\n foreach ($missing_sections as $row) {\n $section = new Section();\n $success = $section->delete($row);\n if (!$success) {\n throw new \\RuntimeException(\"Failed to delete section\");\n }\n }\n }\n\n unset($this->input['_found_sections']);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (string $projectId, string $name, array $events, string $url, bool $security, string $httpUser, string $httpPass, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $security = (bool) filter_var($security, FILTER_VALIDATE_BOOLEAN);\n\n $webhook = new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'projectInternalId' => $project->getInternalId(),\n 'projectId' => $project->getId(),\n 'name' => $name,\n 'events' => $events,\n 'url' => $url,\n 'security' => $security,\n 'httpUser' => $httpUser,\n 'httpPass' => $httpPass,\n 'signatureKey' => \\bin2hex(\\random_bytes(64)),\n ]);\n\n $webhook = $dbForConsole->createDocument('webhooks', $webhook);\n\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($webhook, Response::MODEL_WEBHOOK);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function decryptWithSystemKey(File $node, string $key): void {\n\t\t$storage = $node->getStorage();\n\t\t$name = $node->getName();\n\n\t\t$node->move($node->getPath() . '.bak');\n\t\t$systemKeyPath = $this->getSystemKeyPath($node);\n\t\t$this->rootView->copy($key, $systemKeyPath);\n\n\t\ttry {\n\t\t\tif (!$storage->instanceOfStorage(Encryption::class)) {\n\t\t\t\t$storage = $this->encryptionManager->forceWrapStorage($node->getMountPoint(), $storage);\n\t\t\t}\n\t\t\t/** @var false|resource $source */\n\t\t\t$source = $storage->fopen($node->getInternalPath(), 'r');\n\t\t\tif (!$source) {\n\t\t\t\tthrow new \\Exception(\"Failed to open \" . $node->getPath() . \" with \" . $key);\n\t\t\t}\n\t\t\t$decryptedNode = $node->getParent()->newFile($name);\n\n\t\t\t$target = $this->openWithoutDecryption($decryptedNode, 'w');\n\t\t\tstream_copy_to_stream($source, $target);\n\t\t\tfclose($target);\n\t\t\tfclose($source);\n\n\t\t\t$decryptedNode->getStorage()->getScanner()->scan($decryptedNode->getInternalPath());\n\t\t} catch (\\Exception $e) {\n\t\t\t$this->rootView->rmdir($systemKeyPath);\n\n\t\t\t// remove the .bak\n\t\t\t$node->move(substr($node->getPath(), 0, -4));\n\n\t\t\tthrow $e;\n\t\t}\n\n\t\tif ($this->isDataEncrypted($decryptedNode)) {\n\t\t\tthrow new \\Exception($node->getPath() . \" still encrypted after attempting to decrypt with \" . $key);\n\t\t}\n\n\t\t$this->markAsUnEncrypted($decryptedNode);\n\n\t\t$this->rootView->rmdir($systemKeyPath);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function manipulateStorageConfig(StorageConfig &$storage, ?IUser $user = null) {\n\t\t$auth = new RSACrypt();\n\t\t$auth->setPassword($this->config->getSystemValue('secret', ''));\n\t\tif (!$auth->loadKey($storage->getBackendOption('private_key'))) {\n\t\t\t// Add fallback routine for a time where secret was not enforced to be exists\n\t\t\t$auth->setPassword('');\n\t\t\tif (!$auth->loadKey($storage->getBackendOption('private_key'))) {\n\t\t\t\tthrow new \\RuntimeException('unable to load private key');\n\t\t\t}\n\t\t}\n\t\t$storage->setBackendOption('public_key_auth', $auth);\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function extractMetadata(): array\n {\n //check\n if ($this->inError()) {\n throw new \\RuntimeException(print_r($this->getErrors(), true));\n }\n\n $this->metadata = [\n 'deviceid' => $this->raw_data->deviceid,\n 'version' => $this->raw_data->version ?? $this->raw_data->content->versionclient ?? null,\n 'itemtype' => $this->raw_data->itemtype ?? 'Computer',\n 'port' => $this->raw_data->{'httpd-port'} ?? null,\n ];\n\n if (property_exists($this->raw_data, 'content') && property_exists($this->raw_data->content, 'versionprovider')) {\n $this->metadata['provider'] = [];\n foreach ($this->raw_data->content->versionprovider as $property => $content) {\n $this->metadata['provider'][$property] = $content;\n }\n }\n\n $expecteds = ['action', 'name', 'installed-tasks', 'enabled-tasks', 'tag'];\n foreach ($expecteds as $expected) {\n if (property_exists($this->raw_data, $expected)) {\n $this->metadata[$expected] = $this->raw_data->{$expected};\n }\n }\n\n return $this->metadata;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function CommitTransaction()\n {\n if ($this->ConnectionSetting->IsReadOnlySlave) {\n throw new Exception('Transactions are not allowed on a read-only slave');\n }\n\n $this->RequireConnection(true);\n $this->Observe(\"DataAdapter ($this->_label) (DataAdapter.CommitTransaction)\", OBSERVE_QUERY);\n $this->_transactionInProgress = false;\n return $this->_driver->CommitTransaction($this->_dbconn);\n }", "smellKey": "S112", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function deleteMissingQuestions(): void\n {\n // We can't run this code if we don't have the list of updated sections\n if (!isset($this->input['_found_questions'])) {\n return;\n }\n $found_questions = $this->input['_found_questions'];\n\n // Safety check to avoid deleting all questions if some code run an update\n // without the _questions keys.\n // Deletion is only done if the special \"_delete_missing_questions\" key\n // is present\n $delete_missing_questions = $this->input['_delete_missing_questions'] ?? false;\n if ($delete_missing_questions) {\n // Avoid empty IN clause\n if (empty($found_questions)) {\n $found_questions = [-1];\n }\n\n $missing_questions = (new Question())->find([\n // Is part of this form\n 'forms_sections_id' => new QuerySubQuery([\n 'SELECT' => 'id',\n 'FROM' => Section::getTable(),\n 'WHERE' => [\n 'forms_forms_id' => $this->fields['id'],\n ],\n ]),\n // Was not found in the submitted data\n 'id' => ['NOT IN', $found_questions],\n ]);\n\n foreach ($missing_questions as $row) {\n $question = new Question();\n $success = $question->delete($row);\n if (!$success) {\n throw new \\RuntimeException(\"Failed to delete question\");\n }\n }\n }\n\n unset($this->input['_found_questions']);\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function flattenPdf($inputFilePath, $outputFilePath, $deleteOriginal = true)\n {\n // Escape shell arguments to handle spaces and special characters\n $inputFilePath = escapeshellarg($inputFilePath);\n $outputFilePath = escapeshellarg($outputFilePath);\n\n // Construct the pdftk command\n $command = \"pdftk {$inputFilePath} output {$outputFilePath} flatten\";\n\n // Execute the command and capture the output and return code\n $output = shell_exec($command);\n $returnCode = shell_exec(\"echo $?\");\n\n // Check if the command was successful\n if (intval($returnCode) !== 0) {\n throw new RuntimeException(\"pdftk error: $output\");\n }\n if ($deleteOriginal && file_exists($inputFilePath)) {\n unlink($inputFilePath);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public function addOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname.'Core');\n if (!$path) {\n $path = 'modules'.DIRECTORY_SEPARATOR.$classname.DIRECTORY_SEPARATOR.$classname.'.php';\n }\n $path_override = $this->getLocalPath().'override'.DIRECTORY_SEPARATOR.$path;\n\n if (!file_exists($path_override)) {\n return false;\n } else {\n file_put_contents($path_override, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($path_override)));\n }\n\n $pattern_escape_com = '#(^\\s*?\\/\\/.*?\\n|\\/\\*(?!\\n\\s+\\* module:.*?\\* date:.*?\\* version:.*?\\*\\/).*?\\*\\/)#ism';\n // Check if there is already an override file, if not, we just need to copy the file\n if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n // Check if override file is writable\n $override_path = _PS_ROOT_DIR_.'/'.$file;\n\n if ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path))) {\n throw new Exception(Context::getContext()->getTranslator()->trans('file (%s) not writable', array($override_path), 'Admin.Notifications.Error'));\n }\n\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname.'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n $override_file = array_diff($override_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class '.$classname.'OverrideOriginal'.$uniq), implode('', $override_file)));\n $override_class = new ReflectionClass($classname.'OverrideOriginal'.$uniq);\n\n $module_file = file($path_override);\n $module_file = array_diff($module_file, array(\"\\n\"));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n // Check if none of the methods already exists in the override class\n foreach ($module_class->getMethods() as $method) {\n if ($override_class->hasMethod($method->getName())) {\n $method_override = $override_class->getMethod($method->getName());\n if (preg_match('/module: (.*)/ism', $override_file[$method_override->getStartLine() - 5], $name) && preg_match('/date: (.*)/ism', $override_file[$method_override->getStartLine() - 4], $date) && preg_match('/version: ([0-9.]+)/ism', $override_file[$method_override->getStartLine() - 3], $version)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden by the module %3$s version %4$s at %5$s.', array($method->getName(), $classname, $name[1], $version[1], $date[1]), 'Admin.Modules.Notification'));\n }\n throw new Exception(Context::getContext()->getTranslator()->trans('The method %1$s in the class %2$s is already overridden.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Check if none of the properties already exists in the override class\n foreach ($module_class->getProperties() as $property) {\n if ($override_class->hasProperty($property->getName())) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The property %1$s in the class %2$s is already defined.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n foreach ($module_class->getConstants() as $constant => $value) {\n if ($override_class->hasConstant($constant)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('The constant %1$s in the class %2$s is already defined.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n\n $module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Insert the methods from module override in override\n $copy_from = array_slice($module_file, $module_class->getStartLine() + 1, $module_class->getEndLine() - $module_class->getStartLine() - 2);\n array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);\n $code = implode('', $override_file);\n\n file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));\n } else {\n $override_src = $path_override;\n\n $override_dest = _PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'override'.DIRECTORY_SEPARATOR.$path;\n $dir_name = dirname($override_dest);\n\n if (!$orig_path && !is_dir($dir_name)) {\n $oldumask = umask(0000);\n @mkdir($dir_name, 0777);\n umask($oldumask);\n }\n\n if (!is_writable($dir_name)) {\n throw new Exception(Context::getContext()->getTranslator()->trans('directory (%s) not writable', array($dir_name), 'Admin.Notifications.Error'));\n }\n $module_file = file($override_src);\n $module_file = array_diff($module_file, array(\"\\n\"));\n\n if ($orig_path) {\n do {\n $uniq = uniqid();\n } while (class_exists($classname.'OverrideOriginal_remove', false));\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override'.$uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname.'Override'.$uniq);\n\n // For each method found in the override, prepend a comment with the module name and version\n foreach ($module_class->getMethods() as $method) {\n $module_file = preg_replace('/((:?public|private|protected)\\s+(static\\s+)?function\\s+(?:\\b'.$method->getName().'\\b))/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', array($method->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for properties\n foreach ($module_class->getProperties() as $property) {\n $module_file = preg_replace('/((?:public|private|protected)\\s)\\s*(static\\s)?\\s*(\\$\\b'.$property->getName().'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2$3\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override property %1$s in class %2$s.', array($property->getName(), $classname), 'Admin.Modules.Notification'));\n }\n }\n\n // Same loop for constants\n foreach ($module_class->getConstants() as $constant => $value) {\n $module_file = preg_replace('/(const\\s)\\s*(\\b'.$constant.'\\b)/ism', \"/*\\n * module: \".$this->name.\"\\n * date: \".date('Y-m-d H:i:s').\"\\n * version: \".$this->version.\"\\n */\\n $1$2\", $module_file);\n if ($module_file === null) {\n throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override constant %1$s in class %2$s.', array($constant, $classname), 'Admin.Modules.Notification'));\n }\n }\n }\n\n file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));\n\n // Re-generate the class index\n Tools::generateIndex();\n }\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function () use ($dbForProject, $database, $collection, $documentId) {\n try {\n $dbForProject->deleteDocument(\n 'database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(),\n $documentId\n );\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (RestrictedException) {\n throw new Exception(Exception::DOCUMENT_DELETE_RESTRICTED);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function generateCases(Config $config): string\n {\n $template = 'case %caseName% = \\'%optionValue%\\';';\n\n $cases = $caseNames = [];\n foreach ($config->getSelectOptions() as $selectOption) {\n $caseName = $this->generateCaseName($selectOption);\n if (isset($caseNames[$caseName])) {\n throw new Exception(\n sprintf(\n 'Case \\'%s\\' for value \\'%s\\' already exists for value \\'%s\\'. Configure a name or ensure the alphanumeric characters are unique.',\n $caseName,\n $selectOption->getValue(),\n $caseNames[$caseName]\n ),\n 1676890789419\n );\n }\n\n // Store value for unique check\n $value = $selectOption->getValue();\n $caseNames[$caseName] = $value;\n\n $cases[] = strtr(\n $template,\n [\n '%caseName%' => $caseName,\n '%optionValue%' => $this->escapeSingleQuote($value),\n ]\n );\n }\n\n return $this->implodeTemplateValues($cases);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function swap(int $locationId1, int $locationId2): bool\n {\n $queryBuilder = $this->connection->createQueryBuilder();\n $expr = $queryBuilder->expr();\n $queryBuilder\n ->select('node_id', 'main_node_id', 'contentobject_id', 'contentobject_version')\n ->from(self::CONTENT_TREE_TABLE)\n ->where(\n $expr->in(\n 'node_id',\n ':locationIds'\n )\n )\n ->setParameter('locationIds', [$locationId1, $locationId2], Connection::PARAM_INT_ARRAY)\n ;\n $statement = $queryBuilder->execute();\n $contentObjects = [];\n foreach ($statement->fetchAll(FetchMode::ASSOCIATIVE) as $row) {\n $row['is_main_node'] = (int)$row['main_node_id'] === (int)$row['node_id'];\n $contentObjects[$row['node_id']] = $row;\n }\n\n if (!isset($contentObjects[$locationId1], $contentObjects[$locationId2])) {\n throw new RuntimeException(\n sprintf(\n '%s: failed to fetch either Location %d or Location %d',\n __METHOD__,\n $locationId1,\n $locationId2\n )\n );\n }\n $content1data = $contentObjects[$locationId1];\n $content2data = $contentObjects[$locationId2];\n\n $queryBuilder = $this->connection->createQueryBuilder();\n $queryBuilder\n ->update(self::CONTENT_TREE_TABLE)\n ->set('contentobject_id', ':contentId')\n ->set('contentobject_version', ':versionNo')\n ->set('main_node_id', ':mainNodeId')\n ->where(\n $expr->eq('node_id', ':locationId')\n );\n\n $queryBuilder\n ->setParameter(':contentId', $content2data['contentobject_id'])\n ->setParameter(':versionNo', $content2data['contentobject_version'])\n ->setParameter(\n ':mainNodeId',\n // make main Location main again, preserve main Location id of non-main one\n $content2data['is_main_node']\n ? $content1data['node_id']\n : $content2data['main_node_id']\n )\n ->setParameter('locationId', $locationId1);\n\n // update Location 1 entry\n $queryBuilder->execute();\n\n $queryBuilder\n ->setParameter(':contentId', $content1data['contentobject_id'])\n ->setParameter(':versionNo', $content1data['contentobject_version'])\n ->setParameter(\n ':mainNodeId',\n $content1data['is_main_node']\n // make main Location main again, preserve main Location id of non-main one\n ? $content2data['node_id']\n : $content1data['main_node_id']\n )\n ->setParameter('locationId', $locationId2);\n\n // update Location 2 entry\n $queryBuilder->execute();\n\n return true;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getTemplates(string $editor, string $type): array {\n\t\tif (!array_key_exists($editor, $this->editors)) {\n\t\t\tthrow new \\RuntimeException('No matching editor found');\n\t\t}\n\t\t$templates = [];\n\t\tforeach ($this->editors[$editor]->getCreators() as $creator) {\n\t\t\tif ($creator->getId() === $type) {\n\t\t\t\t$templates = [\n\t\t\t\t\t'empty' => [\n\t\t\t\t\t\t'id' => 'empty',\n\t\t\t\t\t\t'title' => $this->l10n->t('Empty file'),\n\t\t\t\t\t\t'preview' => null\n\t\t\t\t\t]\n\t\t\t\t];\n\n\t\t\t\tif ($creator instanceof ACreateFromTemplate) {\n\t\t\t\t\t$templates = $creator->getTemplates();\n\t\t\t\t}\n\n\t\t\t\t$templates = array_map(function ($template) use ($creator) {\n\t\t\t\t\t$template['extension'] = $creator->getExtension();\n\t\t\t\t\t$template['mimetype'] = $creator->getMimetype();\n\t\t\t\t\treturn $template;\n\t\t\t\t}, $templates);\n\t\t\t}\n\t\t}\n\t\t$return = [];\n\t\t$return['templates'] = $templates;\n\t\treturn $return;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $name, ?array $permissions, bool $documentSecurity, bool $enabled, Response $response, Database $dbForProject, string $mode, Event $events) {\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n if ($database->isEmpty()) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId);\n\n if ($collection->isEmpty()) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $permissions ??= $collection->getPermissions() ?? [];\n\n // Map aggregate permissions into the multiple permissions they represent.\n $permissions = Permission::aggregate($permissions);\n\n $enabled ??= $collection->getAttribute('enabled', true);\n\n try {\n $collection = $dbForProject->updateDocument('database_' . $database->getInternalId(), $collectionId, $collection\n ->setAttribute('name', $name)\n ->setAttribute('$permissions', $permissions)\n ->setAttribute('documentSecurity', $documentSecurity)\n ->setAttribute('enabled', $enabled)\n ->setAttribute('search', implode(' ', [$collectionId, $name])));\n $dbForProject->updateCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $permissions, $documentSecurity);\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (StructureException $exception) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. ' . $exception->getMessage());\n }\n\n $events\n ->setContext('database', $database)\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId());\n\n $response->dynamic($collection, Response::MODEL_COLLECTION);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function Escape($val)\n {\n if (DataAdapter::$ADAPTER_INSTANCE) {\n DataAdapter::$ADAPTER_INSTANCE->LoadDriver();\n }\n\n // this is an unfortunate leftover from poor design of making this function static\n // we cannon use the driver's escape method without a static reference\n if (! DataAdapter::$DRIVER_INSTANCE) {\n throw new Exception(\"DataAdapter must be instantiated before Escape can be called\");\n }\n\n // $driver->RequireConnection(true);\n return DataAdapter::$DRIVER_INSTANCE->Escape($val);\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function executeStatement(): int {\n\t\tif ($this->getType() === \\Doctrine\\DBAL\\Query\\QueryBuilder::SELECT) {\n\t\t\tthrow new \\RuntimeException('Invalid query type, expected INSERT, DELETE or UPDATE statement');\n\t\t}\n\n\t\ttry {\n\t\t\t$result = $this->execute();\n\t\t} catch (\\Doctrine\\DBAL\\Exception $e) {\n\t\t\tthrow \\OC\\DB\\Exceptions\\DbalException::wrap($e);\n\t\t}\n\n\t\tif (!is_int($result)) {\n\t\t\tthrow new \\RuntimeException('Invalid return type for statement');\n\t\t}\n\n\t\treturn $result;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function move($path, $replace = true)\n {\n if (!$this->loaded) {\n throw new \\Exception('File \"' . $this->name . '\" is not loaded, so it cannot be moved.');\n }\n\n if ($this->moved) {\n throw new \\Exception('File \"' . $this->name . '\" is already moved');\n }\n\n if (file_exists($path)) {\n if ($replace) {\n unlink($path);\n } else {\n throw new \\Exception('File on path \"' . $this->name . '\" exists already.');\n }\n }\n\n move_uploaded_file($this->tmpName, $path);\n $this->moved = true;\n }", "smellKey": "S112", "smellId": null, "repo": "Tmlrb2xhb3M_hackazon", "language": "php"} {"function": "public function setLastModifiedStartDate($date)\n {\n if ( null === $date ) {\n $this->lastModifiedStartDate = null;\n } elseif ( false === ( $ts = strtotime($date)) ) {\n $msg = get_class($this) . \": Could not parse last modified start date '$date'\";\n throw new Exception($msg);\n } else {\n $this->lastModifiedStartDate = date(\"Y-m-d H:i:s\", $ts);\n }\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function generateStyles($generateSurroundingHTML = true) {\n\t\t// PHPExcel object known?\n\t\tif (is_null($this->_phpExcel)) {\n\t\t\tthrow new Exception('Internal PHPExcel object not set to an instance of an object.');\n\t\t}\n\n\t\t// Build CSS\n\t\t$css = $this->buildCSS($generateSurroundingHTML);\n\n\t\t// Construct HTML\n\t\t$html = '';\n\n\t\t// Start styles\n\t\tif ($generateSurroundingHTML) {\n\t\t\t$html .= '\t<style type=\"text/css\">' . PHP_EOL;\n\t\t\t$html .= '\t html { ' . $this->_assembleCSS($css['html']) . ' }' . PHP_EOL;\n\t\t}\n\n\t\t// Write all other styles\n\t\tforeach ($css as $styleName => $styleDefinition) {\n\t\t\tif ($styleName != 'html') {\n\t\t\t\t$html .= '\t ' . $styleName . ' { ' . $this->_assembleCSS($styleDefinition) . ' }' . PHP_EOL;\n\t\t\t}\n\t\t}\n\n\t\t// End styles\n\t\tif ($generateSurroundingHTML) {\n\t\t\t$html .= '\t</style>' . PHP_EOL;\n\t\t}\n\n\t\t// Return\n\t\treturn $html;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function addChild(Context $child)\n {\n if (!$child || $this->children->contains($child)) {\n return;\n }\n\n // Ensure we add only allowed sub-contexts\n if (!$this->canContainSubtree($child)) {\n throw new \\Exception('Invalid context hierarchy structure.');\n }\n\n if ($child->getParent()) {\n $child->getParent()->removeChild($child);\n }\n\n $this->children->append($child);\n $child->setParent($this);\n\n if ($this->technology != Context::TECH_GENERIC && $this->technology != $child->technology) {\n $child->setTechnology($this->technology);\n }\n }", "smellKey": "S112", "smellId": null, "repo": "dit21123_hackazon", "language": "php"} {"function": "public static function getDescriptorParamValues(XDUser $user, $aclName, $groupByName)\n {\n if (null == $user->getUserID()) {\n throw new Exception('A valid user id must be supplied.');\n }\n if (null === $aclName) {\n throw new Exception('A valid acl name is required.');\n }\n if (null === $groupByName) {\n throw new Exception('A valid group by name is required.');\n }\n\n $query = <<<SQL\nSELECT DISTINCT uagbp.value\nFROM user_acl_group_by_parameters uagbp\n JOIN group_bys gb ON gb.group_by_id = uagbp.group_by_id\n JOIN acls a ON a.acl_id = uagbp.acl_id\nWHERE uagbp.user_id = :user_id\n AND a.name = :acl_name\n AND gb.name = :group_by_name;\nSQL;\n $db = DB::factory('database');\n $rows = $db->query($query, array(\n ':user_id' => $user->getUserID(),\n ':acl_name' => $aclName,\n ':group_by_name' => $groupByName\n ));\n if (count($rows) > 0) {\n return array_reduce($rows, function ($carry, $item) {\n $carry [] = $item['value'];\n return $carry;\n }, array());\n }\n return array();\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function listWorksheetNames($pFilename)\n\t{\n\t\t// Check if file exists\n\t\tif (!file_exists($pFilename)) {\n\t\t\tthrow new Exception(\"Could not open \" . $pFilename . \" for reading! File does not exist.\");\n\t\t}\n\n\t\t$worksheetNames = array();\n\n\t\t$xml = simplexml_load_file($pFilename);\n\t\t$namespaces = $xml->getNamespaces(true);\n\n\t\t$xml_ss = $xml->children($namespaces['ss']);\n\t\tforeach($xml_ss->Worksheet as $worksheet) {\n\t\t\t$worksheet_ss = $worksheet->attributes($namespaces['ss']);\n\t\t\t$worksheetNames[] = $worksheet_ss['Name'];\n\t\t}\n\n\t\treturn $worksheetNames;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function logAndThrowException($message, array $options = null)\n {\n $logMessage = array();\n $message = \"{$this}: \" . ( is_string($message) ? $message : \"\" );\n $logLevel = Log::ERR;\n $exceptionProvided = false;\n $code = 0;\n\n if ( null !== $options ) {\n\n if ( array_key_exists('exception', $options) && $options['exception'] instanceof Exception ) {\n // Don't add the exception message if it is the same as the general message\n $exceptionMessage = $options['exception']->getMessage();\n if ( $message != $exceptionMessage ) {\n $message .= sprintf(\" Exception: '%s'\", $exceptionMessage);\n }\n\n // PDOException uses a string exception code (typically a five characters alphanumeric\n // identifier defined in the ANSI SQL standard) while Exception uses an int. Use the\n // driver specific error code instead so that we can propagate the error code with\n // the newly thrown Exception.\n // See: https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html\n\n if ( $options['exception'] instanceof PDOException ) {\n $code = $options['exception']->errorInfo[1];\n } else {\n $code = $options['exception']->getCode();\n }\n\n $exceptionProvided = true;\n }\n\n if ( array_key_exists('sql', $options) && is_string($options['sql']) ) {\n $logMessage['sql'] = $options['sql'];\n if ( $exceptionProvided ) {\n $logMessage['stacktrace'] = $options['exception']->getTraceAsString();\n }\n }\n\n if ( array_key_exists('endpoint', $options) && $options['endpoint'] instanceof iDataEndpoint ) {\n $message .= \" Using DataEndpoint: '\" . $options['endpoint'] . \"'\";\n }\n\n if ( array_key_exists('log_level', $options) && ! empty($options['log_level']) ) {\n $logLevel = $options['log_level'];\n }\n }\n\n $logMessage['message'] = $message;\n\n $this->logger->log($logLevel, $logMessage);\n throw new Exception($message, $code);\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected function getRelativePath($path) {\n\t\tif (!isset(self::$userFolderCache)) {\n\t\t\t$userSession = \\OC::$server->get(IUserSession::class);\n\t\t\t$userID = $userSession->getUser()->getUID();\n\t\t\tself::$userFolderCache = \\OC::$server->getUserFolder($userID);\n\t\t}\n\t\t$relativePath = self::$userFolderCache->getRelativePath($path);\n\t\tif ($relativePath === null) {\n\t\t\tthrow new \\Exception(\"Search result not in user folder\");\n\t\t}\n\t\treturn $relativePath;\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function renameTable($oldtable, $newtable)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n if (!$DB->tableExists(\"$newtable\") && $DB->tableExists(\"$oldtable\")) {\n $query = \"RENAME TABLE `$oldtable` TO `$newtable`\";\n $DB->doQueryOrDie($query, $this->version . \" rename $oldtable\");\n\n // Clear possibly forced value of table name.\n // Actually the only forced value in core is for config table.\n $itemtype = getItemTypeForTable($newtable);\n if (class_exists($itemtype)) {\n $itemtype::forceTable($newtable);\n }\n\n // Update target of \"buffered\" schema updates\n if (isset($this->change[$oldtable])) {\n $this->change[$newtable] = $this->change[$oldtable];\n unset($this->change[$oldtable]);\n }\n if (isset($this->fulltexts[$oldtable])) {\n $this->fulltexts[$newtable] = $this->fulltexts[$oldtable];\n unset($this->fulltexts[$oldtable]);\n }\n if (isset($this->uniques[$oldtable])) {\n $this->uniques[$newtable] = $this->uniques[$oldtable];\n unset($this->uniques[$oldtable]);\n }\n } else {\n if (\n str_starts_with($oldtable, 'glpi_plugin_')\n || str_starts_with($newtable, 'glpi_plugin_')\n ) {\n return;\n }\n $message = sprintf(\n __('Unable to rename table %1$s (%2$s) to %3$s (%4$s)!'),\n $oldtable,\n ($DB->tableExists($oldtable) ? __('ok') : __('nok')),\n $newtable,\n ($DB->tableExists($newtable) ? __('nok') : __('ok'))\n );\n if (isCommandLine()) {\n throw new \\RuntimeException($message);\n } else {\n echo htmlspecialchars($message) . \"\\n\";\n die(1);\n }\n }\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (string $code, Document $user, Document $project, Request $request, Response $response, Database $dbForConsole) {\n $state = $user['prefs']['migrationState'] ?? '{}';\n $prefs['migrationState'] = '';\n $user->setAttribute('prefs', $prefs);\n $dbForConsole->updateDocument('users', $user->getId(), $user);\n\n if (empty($state)) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Installation requests from organisation members for the Appwrite Google App are currently unsupported.');\n }\n\n $state = \\json_decode($state, true);\n $redirect = $state['redirect'] ?? '';\n $projectId = $state['projectId'] ?? '';\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if (empty($redirect)) {\n $redirect = $request->getProtocol() . '://' . $request->getHostname() . '/console/project-$projectId/settings/migrations';\n }\n\n if ($project->isEmpty()) {\n $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($redirect);\n\n return;\n }\n\n // OAuth Authroization\n if (!empty($code)) {\n $oauth2 = new OAuth2Firebase(\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),\n App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),\n $request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'\n );\n\n $accessToken = $oauth2->getAccessToken($code);\n $refreshToken = $oauth2->getRefreshToken($code);\n $accessTokenExpiry = $oauth2->getAccessTokenExpiry($code);\n $email = $oauth2->getUserEmail($accessToken);\n $oauth2ID = $oauth2->getUserID($accessToken);\n\n if (empty($accessToken)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to get access token.');\n }\n\n if (empty($refreshToken)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to get refresh token.');\n }\n\n if (empty($accessTokenExpiry)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to get access token expiry.');\n }\n\n // Makes sure this email is not already used in another identity\n $identity = $dbForConsole->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n\n if ($identity !== false && !$identity->isEmpty()) {\n if ($identity->getAttribute('userInternalId', '') !== $user->getInternalId()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n }\n\n if ($identity !== false && !$identity->isEmpty()) {\n $identity = $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n } else {\n $identity = $dbForConsole->createDocument('identities', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ],\n 'userInternalId' => $user->getInternalId(),\n 'userId' => $user->getId(),\n 'provider' => 'firebase',\n 'providerUid' => $oauth2ID,\n 'providerEmail' => $email,\n 'providerAccessToken' => $accessToken,\n 'providerRefreshToken' => $refreshToken,\n 'providerAccessTokenExpiry' => DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry),\n ]));\n }\n } else {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Missing OAuth2 code.');\n }\n\n $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($redirect);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function convertTemplate($template, $mode)\n {\n //1. get template content\n //2. find all texts within {}\n //3. find words within this text\n //4. split by .\n //5. find starting with \"f\"\n //6. get local DT ID - find Concept Code\n //7. replace\n\n //1. get template content\n if($template==null || $template==''){\n throw new \\Exception('Template is empty');\n }\n\n //2. find all texts within {} - expressions\n if (! preg_match_all('/\\{([^}]+)\\}/s', $template, $matches)){\n return $template; // nothing to do -- no substitutions\n }\n\n $not_found_details = array();\n $replacements_exp = array();\n\n $len = count($matches[1]);\n for ($i=0; $i < $len; ++$i) {\n\n $exp = $matches[1][$i];\n if(!trim($exp)) {continue;} //empty{}\n if(substr($exp,0,1)==\"*\" && substr($exp,-1)==\"*\") {continue;} //this is comment\n\n //3. find words within this text\n if (! preg_match_all('/(\\\\$([a-zA-Z_0-9.])+)/', $exp, $matches2) ){\n continue;\n }\n\n $replacements = array();\n\n foreach ($matches2[1] as $var) {\n\n //4. split by \".\"\n $parts = explode(\".\", $var);\n $parts2 = array();\n foreach ($parts as $part) {\n //5. find starting with \"f\"\n if(strpos($part, 'f')===0){\n $prefix = 'f';\n }elseif(strpos($part, '$f')===0){\n $prefix = '$f';\n }else{\n $prefix = null;\n }\n\n if($prefix){\n //6. get local DT ID - find Concept Code\n $code = substr($part, strlen($prefix));\n if(substr($part, -1)=='s'){\n $suffix = 's';\n $code = substr($code,0,strlen($code)-1);\n }elseif(ReportTemplateMgr::endsWith($part,'_originalvalue')){\n $suffix = '_originalvalue';\n $code = substr($code,0,strlen($code)-strlen($suffix));\n }else{\n $suffix = \"\";\n }\n\n if($mode==0){\n $localID = $code;\n if(strpos($localID,\"_\")===false){\n $conceptCode = ConceptCode::getDetailTypeConceptID($localID);\n $part = $prefix.str_replace(\"-\",\"_\",$conceptCode).$suffix;\n }\n }else{\n $conceptCode = $code;\n\n if(strpos($conceptCode,\"_\")!==false){\n $conceptCode = str_replace(\"_\",\"-\",$conceptCode);\n\n $localID = ConceptCode::getDetailTypeLocalID($conceptCode);\n if($localID==null){\n //local code not found - it means that this detail is not in this database\n array_push($not_found_details, $conceptCode);\n $part = $prefix.\"[[\".$conceptCode.\"]]\".$suffix;\n }else{\n $part = $prefix.$localID.$suffix;\n }\n }\n }\n }\n array_push($parts2, $part);\n }\n $new_var = implode(\".\", $parts2);\n\n if($var!=$new_var){\n $replacements[$var] = $new_var;\n }\n }//for vars\n\n if(!empty($replacements)){\n $new_exp = \"{\".$this->arrayStrReplace(array_keys($replacements), array_values($replacements), $exp).\"}\";\n if($matches[0][$i] != $new_exp){\n $replacements_exp[$matches[0][$i]] = $new_exp;\n }\n }\n }//for expressions\n\n\n if(!empty($replacements_exp)){\n $template = $this->arrayStrReplace(array_keys($replacements_exp), array_values($replacements_exp), $template);\n }\n\n return $mode == 1 ? [\"template\" => $template, \"details_not_found\" => $not_found_details] : $template;\n }", "smellKey": "S112", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function (string $providerInstallationId, string $setupAction, string $state, string $code, GitHub $github, Document $user, Document $project, Request $request, Response $response, Database $dbForConsole) {\n if (empty($state)) {\n $error = 'Installation requests from organisation members for the Appwrite GitHub App are currently unsupported. To proceed with the installation, login to the Appwrite Console and install the GitHub App.';\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, $error);\n }\n\n $state = \\json_decode($state, true);\n $projectId = $state['projectId'] ?? '';\n\n $defaultState = [\n 'success' => $request->getProtocol() . '://' . $request->getHostname() . \"/console/project-$projectId/settings/git-installations\",\n 'failure' => $request->getProtocol() . '://' . $request->getHostname() . \"/console/project-$projectId/settings/git-installations\",\n ];\n\n $state = \\array_merge($defaultState, $state ?? []);\n\n $redirectSuccess = $state['success'] ?? '';\n $redirectFailure = $state['failure'] ?? '';\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n $error = 'Project with the ID from state could not be found.';\n\n if (!empty($redirectFailure)) {\n $separator = \\str_contains($redirectFailure, '?') ? '&' : ':';\n return $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($redirectFailure . $separator . \\http_build_query(['error' => $error]));\n }\n\n throw new Exception(Exception::PROJECT_NOT_FOUND, $error);\n }\n\n $personalSlug = '';\n\n // OAuth Authroization\n if (!empty($code)) {\n $oauth2 = new OAuth2Github(App::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), App::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), \"\");\n $accessToken = $oauth2->getAccessToken($code) ?? '';\n $refreshToken = $oauth2->getRefreshToken($code) ?? '';\n $accessTokenExpiry = $oauth2->getAccessTokenExpiry($code) ?? '';\n $personalSlug = $oauth2->getUserSlug($accessToken) ?? '';\n $email = $oauth2->getUserEmail($accessToken);\n $oauth2ID = $oauth2->getUserID($accessToken);\n\n // Makes sure this email is not already used in another identity\n $identity = $dbForConsole->findOne('identities', [\n Query::equal('providerEmail', [$email]),\n ]);\n if ($identity !== false && !$identity->isEmpty()) {\n if ($identity->getAttribute('userInternalId', '') !== $user->getInternalId()) {\n throw new Exception(Exception::USER_EMAIL_ALREADY_EXISTS);\n }\n }\n\n if ($identity !== false && !$identity->isEmpty()) {\n $identity = $identity\n ->setAttribute('providerAccessToken', $accessToken)\n ->setAttribute('providerRefreshToken', $refreshToken)\n ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry));\n\n $dbForConsole->updateDocument('identities', $identity->getId(), $identity);\n } else {\n $identity = $dbForConsole->createDocument('identities', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::user($user->getId())),\n Permission::delete(Role::user($user->getId())),\n ],\n 'userInternalId' => $user->getInternalId(),\n 'userId' => $user->getId(),\n 'provider' => 'github',\n 'providerUid' => $oauth2ID,\n 'providerEmail' => $email,\n 'providerAccessToken' => $accessToken,\n 'providerRefreshToken' => $refreshToken,\n 'providerAccessTokenExpiry' => DateTime::addSeconds(new \\DateTime(), (int)$accessTokenExpiry),\n ]));\n }\n }\n\n // Create / Update installation\n if (!empty($providerInstallationId)) {\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n $owner = $github->getOwnerName($providerInstallationId) ?? '';\n\n $projectInternalId = $project->getInternalId();\n\n $installation = $dbForConsole->findOne('installations', [\n Query::equal('providerInstallationId', [$providerInstallationId]),\n Query::equal('projectInternalId', [$projectInternalId])\n ]);\n\n if ($installation === false || $installation->isEmpty()) {\n $teamId = $project->getAttribute('teamId', '');\n\n $installation = new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::team(ID::custom($teamId))),\n Permission::update(Role::team(ID::custom($teamId), 'owner')),\n Permission::update(Role::team(ID::custom($teamId), 'developer')),\n Permission::delete(Role::team(ID::custom($teamId), 'owner')),\n Permission::delete(Role::team(ID::custom($teamId), 'developer')),\n ],\n 'providerInstallationId' => $providerInstallationId,\n 'projectId' => $projectId,\n 'projectInternalId' => $projectInternalId,\n 'provider' => 'github',\n 'organization' => $owner,\n 'personal' => $personalSlug === $owner\n ]);\n\n $installation = $dbForConsole->createDocument('installations', $installation);\n } else {\n $installation = $installation\n ->setAttribute('organization', $owner)\n ->setAttribute('personal', $personalSlug === $owner);\n $installation = $dbForConsole->updateDocument('installations', $installation->getId(), $installation);\n }\n } else {\n $error = 'Installation of the Appwrite GitHub App on organization accounts is restricted to organization owners. As a member of the organization, you do not have the necessary permissions to install this GitHub App. Please contact the organization owner to create the installation from the Appwrite console.';\n\n if (!empty($redirectFailure)) {\n $separator = \\str_contains($redirectFailure, '?') ? '&' : ':';\n return $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($redirectFailure . $separator . \\http_build_query(['error' => $error]));\n }\n\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, $error);\n }\n\n $response\n ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n ->addHeader('Pragma', 'no-cache')\n ->redirect($redirectSuccess);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function poll_hl7_results(&$info, $labs = 0)\n{\n global $srcdir, $orphanLog, $lab_npi;\n $labs = (int)$labs + 0;\n // echo \"<!-- post: \"; print_r($_POST); echo \" -->\\n\"; // debugging\n // echo \"<!-- in: \"; print_r($info); echo \" -->\\n\"; // debugging\n\n $filecount = 0;\n $badcount = 0;\n $maxdl = $_REQUEST['form_max_results'] ?? 9999; // in case to prevent not running report.\n if (!isset($info['match'])) {\n $info['match'] = array(); // match requests\n }\n\n if (!isset($info['select'])) {\n $info['select'] = array(); // match request responses\n }\n\n $ppres = sqlStatement(\"SELECT * FROM procedure_providers ORDER BY name\");\n\n while ($pprow = sqlFetchArray($ppres)) {\n $ppid = (int)$pprow['ppid'];\n $protocol = $pprow['protocol'];\n $remote_host = $pprow['remote_host'];\n $send_account = $pprow['send_fac_id'];\n $recv_account = $pprow['recv_fac_id'];\n $lab_app = $pprow['recv_app_id'];\n $lab_name = $pprow['name'];\n $lab_npi = strtoupper(trim($pprow['npi']));\n $debug = trim($pprow['DorP']) === 'D';\n $hl7 = '';\n $orphanLog = '';\n $log = '';\n $logpath = $GLOBALS['OE_SITE_DIR'] . \"/documents/procedure_results/logs/$lab_npi\";\n\n if ($ppid !== $labs && $labs > 0) {\n continue;\n }\n $filecount = 0;\n // Support manual results when doing electronic orders\n // without an existing patient and/or procedure and/or order.\n //\n if (isset($info['orphaned_order'])) {\n $pprow['direction'] = $info['orphaned_order']; // manual results or order not found\n }\n\n if ($protocol == 'SFTP') {\n $remote_port = 22;\n // Hostname may have \":port\" appended to specify a nonstandard port number.\n if ($i = strrpos($remote_host, ':')) {\n $remote_port = (int)substr($remote_host, $i + 1);\n $remote_host = substr($remote_host, 0, $i);\n }\n\n // Compute the target path name.\n $pathname = '.';\n if ($pprow['results_path']) {\n $pathname = $pprow['results_path'] . '/' . $pathname;\n }\n\n // Connect to the server and enumerate files to process.\n $sftp = new SFTP($remote_host, $remote_port);\n if (!$sftp->login($pprow['login'], $pprow['password'])) {\n return xl('Login to remote host') . \" '$remote_host' \" . xl('failed');\n }\n\n $files = $sftp->nlist($pathname);\n foreach ($files as $file) {\n if (str_starts_with($file, '.')) {\n continue;\n }\n\n if (!isset($info[\"$lab_name/$ppid/$file\"])) {\n $info[\"$lab_name/$ppid/$file\"] = array();\n }\n\n // Ensure that archive directory exists.\n $prpath = $GLOBALS['OE_SITE_DIR'] . \"/documents/procedure_results\";\n if (!file_exists($prpath)) {\n if (!mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n }\n\n $prpath .= '/' . $pprow['ppid'] . '-' . $pprow['npi'];\n if (!file_exists($prpath)) {\n if (!mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n }\n\n // Get file contents.\n $hl7 = $sftp->get(\"$pathname/$file\");\n\n ++$filecount;\n $fh = fopen(\"$prpath/$file\", 'w');\n if ($fh) {\n // Store the file, encrypted when enabled\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n $log .= \"Retrieved and Saved File #$filecount: $file\\n\";\n } else {\n $log .= \"Retrieved but Couldn't Save File #$filecount: $file\\n\";\n //return xl('Cannot create file') . ' \"' . \"$prpath/$file\" . '\"';\n }\n\n // If user requested reject and delete, do that.\n if (!empty($info[\"$lab_name/$ppid/$file\"]['delete'])) {\n $fh = fopen(\"$prpath/$file.rejected\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n } else {\n $log .= \"Retrieved but Couldn't Save Rejected File #$filecount: $file\\n\";\n //return xl('Cannot create file') . ' \"' . \"$prpath/$file.rejected\" . '\"';\n }\n\n if (strtoupper($lab_npi) != 'LABCORP') { // this is nuts\n if (!$sftp->delete(\"$pathname/$file\")) {\n return xl('Cannot delete (from SFTP server) file') . ' \"' . \"$pathname/$file\" . '\"';\n }\n }\n continue;\n }\n\n if (!match_lab($hl7, $send_account, $recv_account, $lab_app, $lab_npi)) {\n $log .= \"No Lab Account Matched for File #$filecount: Account: $send_account\\n\";\n continue;\n }\n if ($filecount > $maxdl) {\n break;\n }\n // Do a dry run of its contents and check for errors and match requests.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']);\n $log .= \"Lab matched account $send_account. Results Dry Run Parse for Errors: \" .\n $tmp['mssgs'] ? print_r($tmp['mssgs'], true) : \"None\" . \"\\n\";\n\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n // $info[\"$lab_name/$ppid/$file\"]['match'] = $tmp['match'];\n if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) {\n // There are errors or matching requests so skip this file.\n continue;\n }\n $orphanLog = '';\n // Now the money shot - not a dry run.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']);\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n // $info[\"$lab_name/$ppid/$file\"]['match'] = $tmp['match'];\n if (empty($tmp['fatal']) && empty($tmp['needmatch'])) {\n // It worked, archive and delete the file.\n $fh = fopen(\"$prpath/$file\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n $log .= \"Success Saved Results #$filecount to: $file\\n\";\n } else {\n $log .= \"Success but Couldn't Save File #$filecount: $file\\n\";\n return xl('Cannot create file') . ' \"' . \"$prpath/$file\" . '\"';\n }\n if (strtoupper($lab_npi) != 'LABCORP') { // this is nuts\n if (!$sftp->delete(\"$pathname/$file\")) {\n return xl('Cannot delete (from SFTP server) file') . ' \"' . \"$pathname/$file\" . '\"';\n }\n }\n }\n } // end of this file\n if (!file_exists($logpath)) {\n if (!mkdir($logpath, 0755, true) && !is_dir($logpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $logpath));\n }\n }\n $logfile = \"batchrun_\" . date(\"m-d-y_His\") . \".log\";\n $fh = fopen(\"$logpath/$logfile\", 'w');\n if ($fh) {\n $logadd = print_r($info, true);\n $log .= \"Done Batch Run. Debug shows:\\n\" . $logadd . \"\\n\";\n fwrite($fh, $log);\n fclose($fh);\n }\n } elseif ($protocol == 'FS') {\n // Filesystem directory containing results files.\n $pathname = $pprow['results_path'];\n if (!($dh = opendir($pathname))) {\n return xl('Unable to access directory for lab npi:') . \" $lab_npi\";\n }\n\n // Sort by filename just because.\n $files = array();\n while (false !== ($file = readdir($dh))) {\n if (str_starts_with($file, '.')) {\n continue;\n }\n if (is_dir($file)) {\n continue;\n }\n $files[$file] = $file;\n }\n closedir($dh);\n ksort($files);\n // For each file...\n foreach ($files as $file) {\n if (!isset($info[\"$lab_name/$ppid/$file\"])) {\n $info[\"$lab_name/$ppid/$file\"] = array();\n }\n\n // Ensure that archive directory exists.\n $prpath = $GLOBALS['OE_SITE_DIR'] . \"/documents/procedure_results\";\n if (!file_exists($prpath) && !mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n\n $prpath .= '/' . $pprow['ppid'] . '-' . $pprow['npi'];\n if (!file_exists($prpath) && !mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n\n // Get file contents.\n $hl7 = file_get_contents(\"$pathname/$file\");\n\n ++$filecount;\n if (empty($hl7)) {\n $log .= \"Result file empty for some reason. #$filecount: $file\\n\";\n continue;\n }\n\n $fh = fopen(\"$prpath/$file\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n $log .= \"Retrieved and Saved File #$filecount: $file\\n\";\n }\n // If user requested reject and delete, do that.\n if (!empty($info[\"$lab_name/$ppid/$file\"]['delete'])) {\n $fh = fopen(\"$prpath/$file.rejected\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n } else {\n return xl('Cannot create file') . ' \"' . \"$prpath/$file.rejected\" . '\"';\n }\n\n if (!unlink(\"$pathname/$file\")) {\n return xl('Cannot delete file') . ' \"' . \"$pathname/$file\" . '\"';\n }\n\n continue;\n }\n\n if (!match_lab($hl7, $send_account, $recv_account, $lab_app, $lab_npi)) {\n $log .= \"No Lab Match File #$filecount: Account: $send_account\\n\";\n continue;\n }\n if ($filecount > $maxdl) {\n break;\n }\n\n // Do a dry run of its contents and check for errors and match requests.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']);\n if (!empty($tmp['mssgs'])) {\n $log .= \"Lab matched account $send_account. Results Dry Run Parse for Errors: \" .\n $tmp['mssgs'] ? print_r($tmp['mssgs'][0], true) : \"None\" . \"\\n\";\n }\n\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n // $info[\"$lab_name/$ppid/$file\"]['match'] = $tmp['match'];\n if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) {\n // There are errors or matching requests so skip this file.\n continue;\n }\n $orphanLog = '';\n // Now the money shot - not a dry run.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']);\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n // $info[\"$lab_name/$ppid/$file\"]['match'] = $tmp['match'];\n if (empty($tmp['fatal']) && empty($tmp['needmatch'])) {\n // It worked, archive and delete the file.\n $fh = fopen(\"$prpath/$file\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n $log .= \"Success Saved Results #$filecount to: $prpath/$file\\n\";\n } else {\n return xl('Cannot create file') . ' \"' . \"$prpath/$file\" . '\"';\n }\n\n if (!unlink(\"$pathname/$file\")) {\n return xl('Cannot delete file') . ' \"' . \"$pathname/$file\" . '\"';\n }\n }\n } // end of this file\n if (!file_exists($logpath)) {\n if (!mkdir($logpath, 0755, true) && !is_dir($logpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $logpath));\n }\n }\n $logfile = \"batchrun_\" . date(\"m-d-y_His\") . \".log\";\n $fh = fopen(\"$logpath/$logfile\", 'w');\n if ($fh) {\n $logadd = print_r($info, true);\n $log .= \"End of Run Debug Log is:\\n\" . $logadd . \"\\n\";\n fwrite($fh, $log);\n fclose($fh);\n }\n } elseif ($protocol == 'WS' && strtoupper($lab_npi) == 'QUEST') {\n if ($debug) {\n continue;\n }\n // Compute the target path name.\n $pathname = '.';\n if ($pprow['results_path']) {\n $pathname = $pprow['results_path'] . '/' . $pathname;\n }\n\n $client = new QuestResultClient($ppid);\n\n // Connect to the web service and enumerate files to process.\n\n $client->buildRequest(20);\n $order_results = $client->getResultsBatch(false);\n $request_id = $order_results->requestId;\n $results = $order_results->results;\n if (empty($results)) {\n return ''; // nothing to do\n }\n\n foreach ($results as $result) {\n $control_id = $result->HL7Message->controlId;\n $file = \"result_\" . $control_id . \".hl7\";\n\n ++$filecount;\n if (!isset($info[\"$lab_name/$ppid/$file\"])) {\n $info[\"$lab_name/$ppid/$file\"] = array();\n }\n\n // Ensure that archive directory exists.\n $prpath = $GLOBALS['OE_SITE_DIR'] . \"/documents/procedure_results\";\n if (!file_exists($prpath)) {\n if (!mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n }\n\n $prpath .= '/' . $pprow['ppid'] . '-' . $pprow['npi'];\n if (!file_exists($prpath)) {\n if (!mkdir($prpath, 0755, true) && !is_dir($prpath)) {\n throw new RuntimeException(sprintf('Directory \"%s\" was not created', $prpath));\n }\n }\n\n // Get result contents.\n $hl7 = $result->HL7Message->message;\n if (!$hl7) {\n break;\n }\n $segs = explode(\"\\r\", $result->HL7Message->message);\n $a = explode('|', $segs[0]);\n $client->SENDING_FACILITY = $a[5];\n $client->RECEIVING_APPLICATION = $a[2];\n $client->RECEIVING_FACILITY = $a[3];\n unset($segs);\n // If user requested reject and delete, do that.\n if (!empty($info[\"$lab_name/$ppid/$file\"]['delete'])) {\n $fh = fopen(\"$prpath/$file.rejected\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n } else {\n return xl('Cannot create file') . ' \"' . \"$prpath/$file.rejected\" . '\"';\n }\n\n $acks = $client->buildResultAck($control_id);\n $response = $client->sendResultAck($request_id, $acks, false);\n continue;\n }\n\n if (!match_lab($hl7, $send_account, $recv_account, $lab_app, $lab_npi)) {\n $log .= \"No Lab Match Account: $send_account\\n\";\n continue;\n }\n\n // Do a dry run of its contents and check for errors and match requests.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']);\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n // $info[\"$lab_name/$ppid/$file\"]['match'] = $tmp['match'];\n if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) {\n // There are errors or matching requests so skip this file.\n continue;\n }\n $orphanLog = '';\n // Now the money shot - not a dry run.\n $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']);\n $info[\"$lab_name/$ppid/$file\"]['mssgs'] = $tmp['mssgs'];\n if (empty($tmp['fatal']) && empty($tmp['needmatch'])) {\n // It worked, archive and delete the file.\n $fh = fopen(\"$prpath/$file\", 'w');\n if ($fh) {\n $hl7_crypt = hl7Crypt($hl7);\n fwrite($fh, $hl7_crypt);\n fclose($fh);\n } else {\n return xl('Cannot create file') . ' \"' . \"$prpath/$file\" . '\"';\n }\n // remove ie ack\n $acks = $client->buildResultAck($control_id);\n $response = $client->sendResultAck($request_id, $acks, false);\n }\n } // end of this file\n // remove from service.\n } // end quest\n // TBD: Insert \"else if ($protocol == '???') {...}\" to support other protocols.\n } // end procedure provider\n\n // echo \"<!-- out: \"; print_r($info); echo \" -->\\n\"; // debugging\n\n return '';\n}", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (string $ruleId, Response $response, Document $project, Database $dbForConsole, Delete $deletes, Event $events) {\n $rule = $dbForConsole->getDocument('rules', $ruleId);\n\n if ($rule->isEmpty() || $rule->getAttribute('projectInternalId') !== $project->getInternalId()) {\n throw new Exception(Exception::RULE_NOT_FOUND);\n }\n\n $dbForConsole->deleteDocument('rules', $rule->getId());\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($rule);\n\n $events->setParam('ruleId', $rule->getId());\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function factory(AggregatorOptions $options, EtlConfiguration $etlConfig, LoggerInterface $logger = null)\n {\n $options->verify();\n\n $className = $options->class;\n\n // If the class name does not include a namespace designation, use the namespace from the\n // aggregator configuration or the default namespace if not specified.\n\n if ( false === strstr($className, '\\\\') ) {\n if ( $options->namespace ) {\n $className = $options->namespace .\n ( strpos($options->namespace, '\\\\') != strlen($options->namespace) - 1 ? \"\\\\\" : \"\" ) .\n $className;\n } else {\n $className = self::$defaultAggregatorNs . $className;\n }\n }\n\n if ( class_exists($className) ) {\n $aggregator = new $className($options, $etlConfig, $logger);\n } else {\n $msg = __CLASS__ . \": Error creating aggregator '{$options->name}', class '$className' not found\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n if ( ! $aggregator instanceof iAction ) {\n $msg = __CLASS__ . \": $className does not implenment action interface iAction\";\n if ( null !== $logger ) {\n $logger->err($msg);\n }\n throw new Exception($msg);\n }\n\n return $aggregator;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function expandHostList($hostList)\n {\n $this->logger->debug(\"Expanding host list '$hostList'\");\n\n // Hosts that have been parsed.\n $hosts = array();\n // If the host list does not contain brackets it is sufficient\n // to split the host list string on commas.\n $hostListContainsBrackets\n = strpos($hostList, '[') !== false\n || strpos($hostList, ']') !== false;\n\n if (!$hostListContainsBrackets) {\n $hosts = explode(',', $hostList);\n }\n else {\n\n // Copy list string to use in error messages.\n $this->hostList = $hostList;\n\n // Append comma to simplify logic inside loop.\n $hostList .= ',';\n\n // Current bracket nesting level.\n $bracketLevel = 0;\n\n // Current part being parsed.\n $part = '';\n\n for ($i = 0; $i < strlen($hostList); ++$i) {\n $c = substr($hostList, $i, 1);\n\n if ($c === ',' && $bracketLevel === 0) {\n if ($part !== '') {\n $hosts = array_merge($hosts, $this->expandPart($part));\n }\n\n $part = '';\n } else {\n $part .= $c;\n }\n\n if ($c === '[') {\n $bracketLevel += 1;\n } elseif ($c === ']') {\n $bracketLevel -= 1;\n }\n\n if ($bracketLevel > 1) {\n $msg = \"Nested brackets in host list '$this->hostList'\";\n throw new Exception($msg);\n }\n\n if ($bracketLevel < 0) {\n $msg = \"Unbalanced brackets in host list '$this->hostList'\";\n throw new Exception($msg);\n }\n }\n\n if ($bracketLevel > 0) {\n $msg = \"Unbalanced brackets in host list '$this->hostList'\";\n throw new Exception($msg);\n }\n }\n\n // incase of an empty hostlist or a hostlist that has some spaces\n // around the name, trim them and filter out anything that is empty\n $hosts = array_map('trim', $hosts);\n return array_filter($hosts, function ($value) {\n return '' !== $value;\n });\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (string $functionId, Response $response, Database $dbForProject, Delete $deletes, Event $events, Database $dbForConsole) {\n\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n if (!$dbForProject->deleteDocument('functions', $function->getId())) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove function from DB');\n }\n\n // Inform scheduler to no longer run function\n $schedule = $dbForConsole->getDocument('schedules', $function->getAttribute('scheduleId'));\n $schedule\n ->setAttribute('resourceUpdatedAt', DateTime::now())\n ->setAttribute('active', false);\n Authorization::skip(fn () => $dbForConsole->updateDocument('schedules', $schedule->getId(), $schedule));\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($function);\n\n $events->setParam('functionId', $function->getId());\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) {\n\t\tif (!is_null($this->getSheetByName($pSheet->getTitle()))) {\n\t\t\tthrow new Exception(\"Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.\");\n\t\t}\n\n\t\t// count how many cellXfs there are in this workbook currently, we will need this below\n\t\t$countCellXfs = count($this->_cellXfCollection);\n\n\t\t// copy all the shared cellXfs from the external workbook and append them to the current\n\t\tforeach ($pSheet->getParent()->getCellXfCollection() as $cellXf) {\n\t\t\t$this->addCellXf(clone $cellXf);\n\t\t}\n\n\t\t// move sheet to this workbook\n\t\t$pSheet->rebindParent($this);\n\n\t\t// update the cellXfs\n\t\tforeach ($pSheet->getCellCollection(false) as $cellID) {\n\t\t\t$cell = $pSheet->getCell($cellID);\n\t\t\t$cell->setXfIndex( $cell->getXfIndex() + $countCellXfs );\n\t\t}\n\n\t\treturn $this->addSheet($pSheet, $iSheetIndex);\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "private function executeCommand(OutputInterface $output, $cmd, $timeout = 300)\n {\n $phpFinder = new PhpExecutableFinder();\n if (!$phpPath = $phpFinder->find(false)) {\n throw new \\RuntimeException('The php executable could not be found. Add it to your PATH environment variable and try again');\n }\n\n // We don't know which php arguments where used so we gather some to be on the safe side\n $arguments = $phpFinder->findArguments();\n if (false !== ($ini = php_ini_loaded_file())) {\n $arguments[] = '--php-ini=' . $ini;\n }\n\n // Pass memory_limit in case this was specified as php argument, if not it will most likely be same as $ini.\n if ($memoryLimit = ini_get('memory_limit')) {\n $arguments[] = '-d memory_limit=' . $memoryLimit;\n }\n\n $phpArgs = implode(' ', array_map('escapeshellarg', $arguments));\n $php = escapeshellarg($phpPath) . ($phpArgs ? ' ' . $phpArgs : '');\n\n // Make sure to pass along relevant global Symfony options to console command\n $console = escapeshellarg('bin/console');\n if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {\n $console .= ' -' . str_repeat('v', $output->getVerbosity() - 1);\n }\n\n if ($output->isDecorated()) {\n $console .= ' --ansi';\n }\n\n $console .= ' --env=' . escapeshellarg($this->environment);\n\n $process = Process::fromShellCommandline(\n implode(' ', [$php, $console, $cmd]),\n null,\n null,\n null,\n $timeout\n );\n\n $process->run(static function ($type, $buffer) use ($output) { $output->write($buffer, false); });\n if (!$process->getExitCode() === 1) {\n throw new \\RuntimeException(sprintf('An error occurred when executing the \"%s\" command.', escapeshellarg($cmd)));\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function offsetSet($offset, $value): void\n {\n throw new Exception(\"modifying the config isn't allowed\");\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function copyFile($srcFile, $destFile)\n {\n #$this->logger->debug(\"Copying '$srcFile' to '$destFile'\");\n\n if (!is_file($srcFile)) {\n throw new Exception(\"File '$srcFile' does not exist\");\n }\n\n if (!copy($srcFile, $destFile)) {\n throw new Exception(\"Failed to copy file '$srcFile' to '$destFile'\");\n }\n\n if (!chmod($destFile, fileperms($srcFile))) {\n throw new Exception(\"Failed change the mode of file '$destFile'\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function handle()\n {\n $iiifMedia = $this->item;\n\n $iiifMediaUuid = ImageHelpers::get_clean_media_uuid($iiifMedia);\n\n if (!Uuid::isValid($iiifMediaUuid)) {\n throw new Exception('Invalid UUID');\n }\n\n $s3 = Storage::disk(config('twill.media_library.disk'));\n $local = Storage::disk('local');\n $iiifS3 = Storage::disk('iiif_s3');\n\n $localFilename = $iiifMediaUuid;\n\n // Clean up first if this job failed\n $this->deleteSrc($local, $localFilename);\n $this->deleteOut($local, $localFilename);\n\n // No need to do all this work if the tiles have been generated..?\n if (!$this->forceRetile && $iiifS3->exists($localFilename)) {\n return true;\n }\n\n // https://stackoverflow.com/questions/47581934/copying-a-file-using-2-disks-with-laravel\n $local->writeStream('tiles/src/' . $localFilename, $s3->readStream($iiifMedia->uuid));\n\n exec(base_path() . '/bin/tile.sh ' . escapeshellarg($localFilename) . ' 2>&1', $output, $status);\n\n if ($status !== 0) {\n throw new \\Exception('TileMedia: ' . json_encode($output));\n }\n\n // This won't happen since we exited early, but if that check is removed, we need this\n if ($iiifS3->exists($localFilename)) {\n $iiifS3->deleteDirectory($localFilename);\n }\n\n // There's probably a quicker way to transfer an entire directory to S3, but this'll do for now\n // https://bakerstreetsystems.com/blog/post/recursively-transfer-entire-directory-amazon-s3-laravel-52\n // https://stackoverflow.com/questions/44900585/aws-s3-copy-and-replicate-folder-in-laravel\n // We are nesting a $localFilename directory inside a $localFilename directory and uploading the inner one\n // This is done to prevent uploading the same directory twice, if multiple uploads are happening in parallel\n $s3Client = $iiifS3->getDriver()->getAdapter()->getClient();\n $s3Client->uploadDirectory(storage_path() . '/app/tiles/out/' . $localFilename, config('filesystems.disks.iiif_s3.bucket'));\n\n // Clean up on success\n $this->deleteSrc($local, $localFilename);\n $this->deleteOut($local, $localFilename);\n }", "smellKey": "S112", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function build(QdmRequestInterface $request): array\n {\n // Create the patient service\n $patientService = new PatientService($request, new CodeTypesService());\n\n // Query all patients and build QDM models in a loop, storing the QDM patient model in an associative array,\n // so we can later look up by PID\n $qdm_patients_map = [];\n $patientResult = $patientService->executeQuery();\n while ($patient = sqlFetchArray($patientResult)) {\n $qdmRecord = new QdmRecord($patient, $patient['pid'], $patient['pid']);\n $qdmPatient = $patientService->makeQdmModel($qdmRecord);\n $qdm_patients_map[$patient['pid']] = $qdmPatient;\n }\n\n $entityCount = 10000;\n foreach ($this->services as $serviceClass) {\n // Create our service and make sure it implements required methods (inherits from AbstractQdmService).\n $service = new $serviceClass($request, new CodeTypesService());\n if ($service instanceof QdmServiceInterface) {\n // Using the services, query all records for ALL patients in our QdmRequest object, which means we\n // get all relevant models for all patients in one query for this particular service category.\n $result = $service->executeQuery();\n while ($record = sqlFetchArray($result)) {\n // Create a QDM record with the result. This makes sure we have required PID.\n if (\n !isset($record['pid'])\n ) {\n throw new \\Exception(\"The query result generated by QdmService::getSqlStatement() must contain a pid\");\n }\n $qdmRecord = new QdmRecord($record, $record['pid'], $entityCount);\n // Use the service to make a QDM model with the data from the query result\n try {\n $qdmModel = $service->makeQdmModel($qdmRecord);\n // If for some reason the the model doesn't need to return a value, or the date is invalid, makeQdmModel can return null\n if ($qdmModel !== null) {\n // Using the PID map, find the patient this model belongs to and add this data element\n // to the correct patient's QDM model\n $qdmPatient = $qdm_patients_map[$qdmRecord->getPid()];\n $qdmPatient->add_data_element($qdmModel);\n } else {\n error_log(\"QDM Builder Warning: NULL returned by makeQdmModel() on `$serviceClass` for PID = `{$qdmRecord->getPid()}`... Continuing execution.\");\n }\n } catch (\\Exception $e) {\n // There was an error creating the model, such as passing a parameter that is not a member of a QDM Object\n // TODO improve error handling\n error_log($e->getMessage());\n }\n\n $entityCount++;\n }\n } else {\n throw new \\Exception(\"Service does not implement required contract for making QDM models\");\n }\n }\n\n // Take just the map of models, re-index into simple array without PID as index\n $models = array_values($qdm_patients_map);\n return $models;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getSendByString(): string {\n switch ($this->sendBy) {\n case self::SEND_BY_VAL:\n return \"0\";\n case self::SEND_BY_REF:\n return \"1\";\n case self::SEND_PREFER_REF:\n return \"ZEND_SEND_PREFER_REF\";\n }\n throw new Exception(\"Invalid sendBy value\");\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setObjectVar(string $var, mixed $value, bool $silent = false): static\n {\n if (!property_exists($this, $var)) {\n if ($silent) {\n return $this;\n }\n\n throw new Exception('property ' . $var . ' does not exist');\n }\n $this->$var = $value;\n\n return $this;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function createToken(XDUser $user)\n {\n $query = <<<SQL\nINSERT INTO moddb.user_tokens (user_id, token, created_on, expires_on)\nVALUES(:user_id, :token, :created_on, :expires_on);\nSQL;\n $db = DB::factory('database');\n\n // We need to, when presented with a token know which user it is for. To allow for this the tokens stored in the\n // db will encode the Users.id value along with the hashed token value. This will mean that some pre-processing\n // will need to occur when attempting to validate the token, but it alleviates the problem of having to attempt\n // to match every token in the db to find which user it's meant to authenticate.\n $password = bin2hex(random_bytes(32));\n $hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => 12));\n\n $createdOn = date_create()->format('Y-m-d H:m:s');\n $expirationInterval = \\xd_utilities\\getConfiguration('api_token', 'expiration_interval');\n if (empty($expirationInterval)) {\n throw new \\Exception('Expiration Interval not provided.');\n }\n $dateInterval = date_interval_create_from_date_string($expirationInterval);\n $expirationDate = date_add(date_create(), $dateInterval)->format('Y-m-d H:m:s');\n\n $result = $db->execute(\n $query,\n array(\n ':user_id' => $user->getUserID(),\n ':token' => $hash,\n ':created_on' => $createdOn,\n ':expires_on' => $expirationDate\n )\n );\n\n if ($result != 1) {\n throw new \\Exception('Unable to create a new API token.');\n }\n\n return array(\n 'token' => sprintf('%s.%s', $user->getUserID(), $password),\n 'expiration_date' => $expirationDate,\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function escape_table($table, &$params) {\n $alias = null;\n if (is_array($table)) {\n $alias = $table[1];\n $table = $table[0];\n }\n\n $this->getRootQuery()->addUsedAlias($alias);\n\n if (is_string($table)) {\n $table = $this->quote($table);\n if ($alias != null)\n $table.= \" AS {$alias}\";\n return $table;\n }\n\n if ($alias == null) {\n $alias = $this->last_alias();\n $this->getRootQuery()->addUsedAlias($alias);\n }\n\n if ($table instanceof DB\\Query)\n return \"{$this->subquery($table, $params)} AS {$alias}\";\n\n if ($table instanceof DB\\Expression)\n return \"({$table->value}) AS {$alias}\";\n\n throw new \\Exception(\"Parameter type \" . get_class($table) . \" cannot be used as a table\");\n }", "smellKey": "S112", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "function __construct($fileName)\n\t\t# Author: Jarrod Oberto\n\t\t# Date: 27-02-08\n\t\t# Purpose: Constructor\n\t\t# Param in: $fileName: File name and path.\n\t\t# Param out: n/a\n\t\t# Reference:\n\t\t# Notes:\n\t\t#\n\t{\n\t\tif ( ! $this->testGDInstalled())\n\t\t{\n\t\t\tif ($this->debug)\n\t\t\t{\n\t\t\t\tthrow new Exception('The GD Library is not installed.');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow new Exception();\n\t\t\t}\n\t\t};\n\n\t\t$this->initialise();\n\n\t\t// *** Save the image file name. Only store this incase you want to display it\n\t\t$this->fileName = $fileName;\n\t\t$this->fileExtension = fix_strtolower(strrchr($fileName, '.'));\n\n\t\t// *** Open up the file\n\t\t$this->image = $this->openImage($fileName);\n\n\n\t\t// *** Assign here so we don't modify the original\n\t\t$this->imageResized = $this->image;\n\n\t\t// *** If file is an image\n\t\tif ($this->testIsImage($this->image))\n\t\t{\n\t\t\t// *** Get width and height\n\t\t\t$this->width = imagesx($this->image);\n\t\t\t$this->widthOriginal = imagesx($this->image);\n\t\t\t$this->height = imagesy($this->image);\n\t\t\t$this->heightOriginal = imagesy($this->image);\n\n\n\t\t\t/* Added 15-09-08\n * Get the filesize using this build in method.\n * Stores an array of size\n *\n * $this->imageSize[1] = width\n * $this->imageSize[2] = height\n * $this->imageSize[3] = width x height\n *\n */\n\t\t\t$this->imageSize = getimagesize($this->fileName);\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$this->errorArray[] = 'File is not an image';\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "function () {\n $group = new Group();\n\n $fallbackForDB = 'db_main=' . AppwriteURL::unparse([\n 'scheme' => 'mariadb',\n 'host' => App::getEnv('_APP_DB_HOST', 'mariadb'),\n 'port' => App::getEnv('_APP_DB_PORT', '3306'),\n 'user' => App::getEnv('_APP_DB_USER', ''),\n 'pass' => App::getEnv('_APP_DB_PASS', ''),\n 'path' => App::getEnv('_APP_DB_SCHEMA', ''),\n ]);\n $fallbackForRedis = 'redis_main=' . AppwriteURL::unparse([\n 'scheme' => 'redis',\n 'host' => App::getEnv('_APP_REDIS_HOST', 'redis'),\n 'port' => App::getEnv('_APP_REDIS_PORT', '6379'),\n 'user' => App::getEnv('_APP_REDIS_USER', ''),\n 'pass' => App::getEnv('_APP_REDIS_PASS', ''),\n ]);\n\n $connections = [\n 'console' => [\n 'type' => 'database',\n 'dsns' => App::getEnv('_APP_CONNECTIONS_DB_CONSOLE', $fallbackForDB),\n 'multiple' => false,\n 'schemes' => ['mariadb', 'mysql'],\n ],\n 'database' => [\n 'type' => 'database',\n 'dsns' => App::getEnv('_APP_CONNECTIONS_DB_PROJECT', $fallbackForDB),\n 'multiple' => true,\n 'schemes' => ['mariadb', 'mysql'],\n ],\n 'queue' => [\n 'type' => 'queue',\n 'dsns' => App::getEnv('_APP_CONNECTIONS_QUEUE', $fallbackForRedis),\n 'multiple' => false,\n 'schemes' => ['redis'],\n ],\n 'pubsub' => [\n 'type' => 'pubsub',\n 'dsns' => App::getEnv('_APP_CONNECTIONS_PUBSUB', $fallbackForRedis),\n 'multiple' => false,\n 'schemes' => ['redis'],\n ],\n 'cache' => [\n 'type' => 'cache',\n 'dsns' => App::getEnv('_APP_CONNECTIONS_CACHE', $fallbackForRedis),\n 'multiple' => true,\n 'schemes' => ['redis'],\n ],\n ];\n\n $maxConnections = App::getEnv('_APP_CONNECTIONS_MAX', 151);\n $instanceConnections = $maxConnections / App::getEnv('_APP_POOL_CLIENTS', 14);\n\n $multiprocessing = App::getEnv('_APP_SERVER_MULTIPROCESS', 'disabled') === 'enabled';\n\n if ($multiprocessing) {\n $workerCount = swoole_cpu_num() * intval(App::getEnv('_APP_WORKER_PER_CORE', 6));\n } else {\n $workerCount = 1;\n }\n\n if ($workerCount > $instanceConnections) {\n throw new \\Exception('Pool size is too small. Increase the number of allowed database connections or decrease the number of workers.', 500);\n }\n\n $poolSize = (int)($instanceConnections / $workerCount);\n\n foreach ($connections as $key => $connection) {\n $type = $connection['type'] ?? '';\n $dsns = $connection['dsns'] ?? '';\n $multipe = $connection['multiple'] ?? false;\n $schemes = $connection['schemes'] ?? [];\n $config = [];\n $dsns = explode(',', $connection['dsns'] ?? '');\n foreach ($dsns as &$dsn) {\n $dsn = explode('=', $dsn);\n $name = ($multipe) ? $key . '_' . $dsn[0] : $key;\n $dsn = $dsn[1] ?? '';\n $config[] = $name;\n if (empty($dsn)) {\n //throw new Exception(Exception::GENERAL_SERVER_ERROR, \"Missing value for DSN connection in {$key}\");\n continue;\n }\n\n $dsn = new DSN($dsn);\n $dsnHost = $dsn->getHost();\n $dsnPort = $dsn->getPort();\n $dsnUser = $dsn->getUser();\n $dsnPass = $dsn->getPassword();\n $dsnScheme = $dsn->getScheme();\n $dsnDatabase = $dsn->getPath();\n\n if (!in_array($dsnScheme, $schemes)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, \"Invalid console database scheme\");\n }\n\n /**\n * Get Resource\n *\n * Creation could be reused accross connection types like database, cache, queue, etc.\n *\n * Resource assignment to an adapter will happen below.\n */\n switch ($dsnScheme) {\n case 'mysql':\n case 'mariadb':\n $resource = function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {\n return new PDOProxy(function () use ($dsnHost, $dsnPort, $dsnUser, $dsnPass, $dsnDatabase) {\n return new PDO(\"mysql:host={$dsnHost};port={$dsnPort};dbname={$dsnDatabase};charset=utf8mb4\", $dsnUser, $dsnPass, array(\n PDO::ATTR_TIMEOUT => 3, // Seconds\n PDO::ATTR_PERSISTENT => true,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::ATTR_ERRMODE => App::isDevelopment() ? PDO::ERRMODE_WARNING : PDO::ERRMODE_SILENT, // If in production mode, warnings are not displayed\n PDO::ATTR_EMULATE_PREPARES => true,\n PDO::ATTR_STRINGIFY_FETCHES => true\n ));\n });\n };\n break;\n case 'redis':\n $resource = function () use ($dsnHost, $dsnPort, $dsnPass) {\n $redis = new Redis();\n @$redis->pconnect($dsnHost, (int)$dsnPort);\n if ($dsnPass) {\n $redis->auth($dsnPass);\n }\n $redis->setOption(Redis::OPT_READ_TIMEOUT, -1);\n\n return $redis;\n };\n break;\n\n default:\n throw new Exception(Exception::GENERAL_SERVER_ERROR, \"Invalid scheme\");\n break;\n }\n\n $pool = new Pool($name, $poolSize, function () use ($type, $resource, $dsn) {\n // Get Adapter\n $adapter = null;\n switch ($type) {\n case 'database':\n $adapter = match ($dsn->getScheme()) {\n 'mariadb' => new MariaDB($resource()),\n 'mysql' => new MySQL($resource()),\n default => null\n };\n\n $adapter->setDefaultDatabase($dsn->getPath());\n break;\n case 'pubsub':\n $adapter = $resource();\n break;\n case 'queue':\n $adapter = match ($dsn->getScheme()) {\n 'redis' => new Queue\\Connection\\Redis($dsn->getHost(), $dsn->getPort()),\n default => null\n };\n break;\n case 'cache':\n $adapter = match ($dsn->getScheme()) {\n 'redis' => new RedisCache($resource()),\n default => null\n };\n break;\n\n default:\n throw new Exception(Exception::GENERAL_SERVER_ERROR, \"Server error: Missing adapter implementation.\");\n break;\n }\n\n return $adapter;\n });\n\n $group->add($pool);\n }\n\n Config::setParam('pools-' . $key, $config);\n }\n\n return $group;\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function buildUpdate($table, $params, $clauses, array $joins = [])\n {\n //when no explicit \"WHERE\", we only have a WHERE clause.\n if (!isset($clauses['WHERE'])) {\n $clauses = ['WHERE' => $clauses];\n } else {\n $known_clauses = ['WHERE', 'ORDER', 'LIMIT', 'START'];\n foreach (array_keys($clauses) as $key) {\n if (!in_array($key, $known_clauses)) {\n throw new \\RuntimeException(\n str_replace(\n '%clause',\n $key,\n 'Trying to use an unknown clause (%clause) building update query!'\n )\n );\n }\n }\n }\n\n if (!count($clauses['WHERE'])) {\n throw new \\RuntimeException('Cannot run an UPDATE query without WHERE clause!');\n }\n if (!count($params)) {\n throw new \\RuntimeException('Cannot run an UPDATE query without parameters!');\n }\n\n $query = \"UPDATE \" . self::quoteName($table);\n\n //JOINS\n $this->iterator = new DBmysqlIterator($this);\n $query .= $this->iterator->analyseJoins($joins);\n\n $query .= \" SET \";\n foreach ($params as $field => $value) {\n if ($value instanceof QueryParam || $value instanceof QueryExpression) {\n //no quote for query parameters nor expressions\n $query .= self::quoteName($field) . \" = \" . $value->getValue() . \", \";\n } else if ($value === null || $value === 'NULL' || $value === 'null') {\n $query .= self::quoteName($field) . \" = NULL, \";\n } else if (is_bool($value)) {\n // transform boolean as int (prevent `false` to be transformed to empty string)\n $query .= self::quoteName($field) . \" = '\" . (int)$value . \"', \";\n } else {\n $query .= self::quoteName($field) . \" = \" . self::quoteValue($value) . \", \";\n }\n }\n $query = rtrim($query, ', ');\n\n $query .= \" WHERE \" . $this->iterator->analyseCrit($clauses['WHERE']);\n\n // ORDER BY\n if (isset($clauses['ORDER']) && !empty($clauses['ORDER'])) {\n $query .= $this->iterator->handleOrderClause($clauses['ORDER']);\n }\n\n if (isset($clauses['LIMIT']) && !empty($clauses['LIMIT'])) {\n $offset = (isset($clauses['START']) && !empty($clauses['START'])) ? $clauses['START'] : null;\n $query .= $this->iterator->handleLimits($clauses['LIMIT'], $offset);\n }\n\n return $query;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function getById(string $id): ?Config\n {\n $cacheKey = self::getCacheKey($id);\n\n try {\n $selectOptions = RuntimeCache::get($cacheKey);\n if (!$selectOptions instanceof self) {\n throw new RuntimeException('Select options in registry is invalid', 1678353750987);\n }\n } catch (Exception $e) {\n try {\n $selectOptions = new self();\n /** @var Config\\Dao $dao */\n $dao = $selectOptions->getDao();\n $dao->getById($id);\n RuntimeCache::set($cacheKey, $selectOptions);\n } catch (NotFoundException $e) {\n return null;\n }\n }\n\n return $selectOptions;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function getLast($func, $throw)\n {\n $source = $this->getWhereIteratorOrInnerIterator($func);\n\n $count = 0;\n $last = null;\n\n foreach ($source as $stored) {\n $count++;\n $last = $stored;\n }\n\n if ($count == 0 && $throw) {\n throw new \\RuntimeException(\"The input sequence contains no matching element.\");\n }\n\n return $last;\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function factory($sectionName, $autoConnect = true)\n {\n // If this section has been used before in creating a database instance (handle), then\n // it will have been cached. In this case, the cached handle will be returned.\n\n if ( array_key_exists($sectionName, self::$instancePool) ) {\n return self::$instancePool[$sectionName];\n }\n\n try {\n $iniSection = xd_utilities\\getConfigurationSection($sectionName, 'db_engine');\n } catch (Exception $e) {\n $msg = \"Unable to get database configuration options: \" . $e->getMessage();\n throw new Exception($msg);\n }\n\n // Not all engines are required to specify all configuration options (e.g., Oracle) so\n // allow NULL (empty) options. Specific engines may enforce additional requirements.\n\n $engine = ( array_key_exists('db_engine', $iniSection) ? $iniSection['db_engine'] : null);\n $database = ( array_key_exists('database', $iniSection) ? $iniSection['database'] : null);\n $user = ( array_key_exists('user', $iniSection) ? $iniSection['user'] : null );\n\n if ( null === $engine || null === $database || null === $user ) {\n $msg = \"Configuration section '$sectionName' missing required options (db_engine, database, user)\";\n throw new Exception($msg);\n }\n\n $password = ( array_key_exists('pass', $iniSection) ? $iniSection['pass'] : null );\n $host = ( array_key_exists('host', $iniSection) ? $iniSection['host'] : null );\n $port = ( array_key_exists('port', $iniSection) ? $iniSection['port'] : null );\n\n $engine = \"CCR\\\\DB\\\\$engine\";\n\n // Ensure that the class exists before we attempt to instantiate it\n\n if ( class_exists($engine) ) {\n $db = new $engine($host, $port, $database, $user, $password);\n } else {\n $msg = \"Error creating database defined in section '$sectionName', class '$engine' not found\";\n throw new Exception($msg);\n }\n\n // All database interfaces must implement iDatabase\n\n if ( ! $db instanceof iDatabase ) {\n throw new Exception(\"$engine does not implenment interface iDatabase\");\n }\n\n self::$instancePool[$sectionName] = $db;\n if ($autoConnect) {\n self::$instancePool[$sectionName]->connect();\n }\n\n return self::$instancePool[$sectionName];\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function open($save_path, $name)\n\t{\n\t\tif ( ! is_dir($save_path))\n\t\t{\n\t\t\tif ( ! mkdir($save_path, 0700, TRUE))\n\t\t\t{\n\t\t\t\tthrow new Exception(\"Session: Configured save path '\".$this->_config['save_path'].\"' is not a directory, doesn't exist or cannot be created.\");\n\t\t\t}\n\t\t}\n\t\telseif ( ! is_writable($save_path))\n\t\t{\n\t\t\tthrow new Exception(\"Session: Configured save path '\".$this->_config['save_path'].\"' is not writable by the PHP process.\");\n\t\t}\n\n\t\t$this->_config['save_path'] = $save_path;\n\t\t$this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR\n\t\t\t.$name // we'll use the session cookie name as a prefix to avoid collisions\n\t\t\t.($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : '');\n\n\t\t$this->php5_validate_id();\n\n\t\treturn $this->_success;\n\t}", "smellKey": "S112", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public static function fromFile(string $path): self\n {\n if (!\\is_readable($path)) {\n throw new Exception(\"$path view template is not readable.\");\n }\n\n $template = new Template();\n return $template->setPath($path);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $iterationCount = (int) $input->getOption('iteration-count');\n $this->dryRun = $input->getOption('dry-run');\n $this->mode = $input->getOption('mode');\n\n if (!array_key_exists($this->mode, self::MODES)) {\n $output->writeln(\n sprintf('The selected mode is not supported. Use one of the following modes: %s', implode(', ', array_keys(self::MODES)))\n );\n\n return self::SUCCESS;\n }\n\n $from = $input->getOption('from');\n $to = $input->getOption('to');\n\n if ($from && !$this->validateDateTimeString($from, $output)) {\n return self::SUCCESS;\n }\n if ($to && !$this->validateDateTimeString($to, $output)) {\n return self::SUCCESS;\n }\n if ($from) {\n $this->from = $this->dateStringToTimestamp($from);\n }\n if ($to) {\n $this->to = $this->dateStringToTimestamp($to);\n }\n\n $consoleScript = $_SERVER['argv'][0];\n\n if (getenv('INNER_CALL')) {\n $this->timezone = $input->getArgument('timezone');\n $this->processTimestamps((int) $input->getOption('offset'), $iterationCount, $output);\n $output->writeln($this->done);\n } else {\n $timezone = $input->getArgument('timezone');\n $this->timezone = $this->validateTimezone($timezone, $output);\n\n $output->writeln([\n sprintf('Converting timestamps for fields: %s', implode(', ', self::MODES[$this->mode])),\n 'Calculating number of Field values to update...',\n ]);\n $count = $this->countTimestampBasedFields();\n $output->writeln([\n sprintf('Found %d total Field values for update', $count),\n '',\n ]);\n\n if ($count == 0) {\n $output->writeln('Nothing to process, exiting.');\n\n return self::SUCCESS;\n }\n\n $helper = $this->getHelper('question');\n $question = new ConfirmationQuestion(\n '<question>Are you sure you want to proceed?</question> ',\n false\n );\n\n if (!$helper->ask($input, $output, $question)) {\n $output->writeln('');\n\n return self::SUCCESS;\n }\n\n $progressBar = $this->getProgressBar($count, $output);\n $progressBar->start();\n\n for ($offset = 0; $offset < $count; $offset += $iterationCount) {\n $processScriptFragments = [\n $this->getPhpPath(),\n $consoleScript,\n $this->getName(),\n $this->timezone,\n '--mode=' . $this->mode,\n '--offset=' . $offset,\n '--iteration-count=' . $iterationCount,\n ];\n\n if ($from) {\n $processScriptFragments[] = '--from=' . $from;\n }\n if ($to) {\n $processScriptFragments[] = '--to=' . $to;\n }\n if ($this->dryRun) {\n $processScriptFragments[] = '--dry-run';\n }\n\n $process = new Process($processScriptFragments);\n\n $process->setEnv(['INNER_CALL' => 1]);\n $process->run();\n\n if (!$process->isSuccessful()) {\n throw new RuntimeException($process->getErrorOutput());\n }\n\n $doneInProcess = (int) $process->getOutput();\n $this->done += $doneInProcess;\n\n $progressBar->advance($doneInProcess);\n }\n\n $progressBar->finish();\n $output->writeln([\n '',\n sprintf('Done: %d', $this->done),\n ]);\n }\n\n return self::SUCCESS;\n }", "smellKey": "S112", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $io = new SymfonyStyle($input, $output);\n\n $targetEnvironment = $input->getArgument(self::ARG_ENVIRONMENT);\n\n if ($targetEnvironment === null && $input->isInteractive()) {\n $targetEnvironment = $io->choice('What environment do you want to set?', EnvironmentType::ALL);\n }\n\n if ($targetEnvironment === null) {\n throw new Exception(\n 'The target environment cannot be empty. Please run this command in interactive mode or set it via an argument.',\n );\n }\n\n if (!in_array($targetEnvironment, EnvironmentType::ALL, true)) {\n throw new Exception(sprintf('Unknown environment \"%s\".', $targetEnvironment));\n }\n\n $this->environmentFileSetting->removeFilesForAllEnvironments();\n $this->environmentFileSetting->createFileForEnvironment($targetEnvironment);\n\n $output->writeln(sprintf('Application environment successfully changed to \"%s\".', $targetEnvironment));\n\n return Command::SUCCESS;\n }", "smellKey": "S112", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function asEditTheLastCreatedCommentAndSetTextToItShouldReturn($user, $text, $statusCode) {\n\t\t$client = new \\GuzzleHttp\\Client();\n\t\t$options = [];\n\t\t$options['auth'] = [$user, '123456'];\n\t\t$options['body'] = '<?xml version=\"1.0\"?>\n<d:propertyupdate xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\">\n <d:set>\n <d:prop>\n <oc:message>' . $text . '</oc:message>\n </d:prop>\n </d:set>\n</d:propertyupdate>';\n\t\ttry {\n\t\t\t$res = $client->request('PROPPATCH', $this->baseUrl . '/remote.php/dav/comments/files/' . $this->fileId . '/' . $this->commentId, $options);\n\t\t} catch (\\GuzzleHttp\\Exception\\ClientException $e) {\n\t\t\t$res = $e->getResponse();\n\t\t}\n\n\t\tif ($res->getStatusCode() !== (int)$statusCode) {\n\t\t\tthrow new \\Exception(\"Response status code was not $statusCode (\" . $res->getStatusCode() . \")\");\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $functionId, string $variableId, string $key, ?string $value, Response $response, Database $dbForProject, Database $dbForConsole) {\n\n $function = $dbForProject->getDocument('functions', $functionId);\n\n if ($function->isEmpty()) {\n throw new Exception(Exception::FUNCTION_NOT_FOUND);\n }\n\n $variable = $dbForProject->getDocument('variables', $variableId);\n if ($variable === false || $variable->isEmpty() || $variable->getAttribute('resourceInternalId') !== $function->getInternalId() || $variable->getAttribute('resourceType') !== 'function') {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n if ($variable === false || $variable->isEmpty()) {\n throw new Exception(Exception::VARIABLE_NOT_FOUND);\n }\n\n $variable\n ->setAttribute('key', $key)\n ->setAttribute('value', $value ?? $variable->getAttribute('value'))\n ->setAttribute('search', implode(' ', [$variableId, $function->getId(), $key, 'function']));\n\n try {\n $dbForProject->updateDocument('variables', $variable->getId(), $variable);\n } catch (DuplicateException $th) {\n throw new Exception(Exception::VARIABLE_ALREADY_EXISTS);\n }\n\n $dbForProject->updateDocument('functions', $function->getId(), $function->setAttribute('live', false));\n\n // Inform scheduler to pull the latest changes\n $schedule = $dbForConsole->getDocument('schedules', $function->getAttribute('scheduleId'));\n $schedule\n ->setAttribute('resourceUpdatedAt', DateTime::now())\n ->setAttribute('schedule', $function->getAttribute('schedule'))\n ->setAttribute('active', !empty($function->getAttribute('schedule')) && !empty($function->getAttribute('deployment')));\n Authorization::skip(fn () => $dbForConsole->updateDocument('schedules', $schedule->getId(), $schedule));\n\n $response->dynamic($variable, Response::MODEL_VARIABLE);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function theTagHasGroup($type, $tagName, $groups) {\n\t\t$foundTag = $this->findTag($type, $tagName, 'admin', true);\n\t\tif ($foundTag === null) {\n\t\t\tthrow new \\Exception('No matching tag found');\n\t\t}\n\n\t\tif ($foundTag['groups'] !== $groups) {\n\t\t\tthrow new \\Exception('Tag has groups \"' . $foundTag['group'] . '\" instead of the expected \"' . $groups . '\"');\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function updateGridConfigShares(?GridConfig $gridConfig, array $metadata): void\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }\n\n if ($gridConfig->getOwnerId() != $user->getId() && !$user->isAdmin()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];\n\n if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }\n\n if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }\n\n $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);\n\n foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function handle(Request $request, Closure $next): Response\n {\n $data = SnsMessage::fromRequest($request);\n\n app(StoreInboundWebhook::class)\n ->handle(\n InboundWebhookSource::AwsSns,\n in_array($data->type, ['SubscriptionConfirmation', 'UnsubscribeConfirmation', 'Notification']) ? $data->type : 'UnknownSnsType',\n $request->url(),\n $request->getContent()\n );\n\n if ($data->type === 'SubscriptionConfirmation') {\n if (app()->environment('testing')) {\n return response(status: 200);\n }\n\n file_get_contents($data->subscribeURL);\n\n return response(status: 200);\n }\n\n if ($data->type === 'UnsubscribeConfirmation') {\n return response(status: 200);\n }\n\n if ($data->type !== 'Notification') {\n throw new Exception('Unknown AWS SNS webhook type');\n }\n\n return $next($request);\n }", "smellKey": "S112", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function initialize(DAV\\Server $server)\n {\n if ($this->allowUnauthenticatedAccess) {\n $authPlugin = $server->getPlugin('auth');\n if (!$authPlugin) {\n throw new \\Exception('The Auth plugin must be loaded before the ACL plugin if you want to allow unauthenticated access.');\n }\n $authPlugin->autoRequireLogin = false;\n }\n\n $this->server = $server;\n $server->on('propFind', [$this, 'propFind'], 20);\n $server->on('beforeMethod:*', [$this, 'beforeMethod'], 20);\n $server->on('beforeBind', [$this, 'beforeBind'], 20);\n $server->on('beforeUnbind', [$this, 'beforeUnbind'], 20);\n $server->on('propPatch', [$this, 'propPatch']);\n $server->on('beforeUnlock', [$this, 'beforeUnlock'], 20);\n $server->on('report', [$this, 'report']);\n $server->on('method:ACL', [$this, 'httpAcl']);\n $server->on('onHTMLActionsPanel', [$this, 'htmlActionsPanel']);\n $server->on('getPrincipalByUri', function ($principal, &$uri) {\n $uri = $this->getPrincipalByUri($principal);\n\n // Break event chain\n if ($uri) {\n return false;\n }\n });\n\n array_push($server->protectedProperties,\n '{DAV:}alternate-URI-set',\n '{DAV:}principal-URL',\n '{DAV:}group-membership',\n '{DAV:}principal-collection-set',\n '{DAV:}current-user-principal',\n '{DAV:}supported-privilege-set',\n '{DAV:}current-user-privilege-set',\n '{DAV:}acl',\n '{DAV:}acl-restrictions',\n '{DAV:}inherited-acl-set',\n '{DAV:}owner',\n '{DAV:}group'\n );\n\n // Automatically mapping nodes implementing IPrincipal to the\n // {DAV:}principal resourcetype.\n $server->resourceTypeMapping['Sabre\\\\DAVACL\\\\IPrincipal'] = '{DAV:}principal';\n\n // Mapping the group-member-set property to the HrefList property\n // class.\n $server->xml->elementMap['{DAV:}group-member-set'] = 'Sabre\\\\DAV\\\\Xml\\\\Property\\\\Href';\n $server->xml->elementMap['{DAV:}acl'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Property\\\\Acl';\n $server->xml->elementMap['{DAV:}acl-principal-prop-set'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Request\\\\AclPrincipalPropSetReport';\n $server->xml->elementMap['{DAV:}expand-property'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Request\\\\ExpandPropertyReport';\n $server->xml->elementMap['{DAV:}principal-property-search'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Request\\\\PrincipalPropertySearchReport';\n $server->xml->elementMap['{DAV:}principal-search-property-set'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Request\\\\PrincipalSearchPropertySetReport';\n $server->xml->elementMap['{DAV:}principal-match'] = 'Sabre\\\\DAVACL\\\\Xml\\\\Request\\\\PrincipalMatchReport';\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $projectId, string $webhookId, Response $response, Database $dbForConsole) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $webhook = $dbForConsole->findOne('webhooks', [\n Query::equal('$id', [$webhookId]),\n Query::equal('projectInternalId', [$project->getInternalId()]),\n ]);\n\n if ($webhook === false || $webhook->isEmpty()) {\n throw new Exception(Exception::WEBHOOK_NOT_FOUND);\n }\n\n $webhook->setAttribute('signatureKey', \\bin2hex(\\random_bytes(64)));\n\n $dbForConsole->updateDocument('webhooks', $webhook->getId(), $webhook);\n $dbForConsole->deleteCachedDocument('projects', $project->getId());\n\n $response->dynamic($webhook, Response::MODEL_WEBHOOK);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(\n array $parameters,\n $stat = \"all\"\n ) {\n parent::__construct('Jobs', 'modw_aggregates', 'jobfact_by_day', array());\n\n // The same fact table row may correspond to multiple rows in the\n // aggregate table (e.g. a job that runs over two days).\n $this->setDistinct(true);\n\n $config = RawStatisticsConfiguration::factory();\n\n // The data table is always aliased to \"agg\".\n $tables = ['agg' => $this->getDataTable()];\n\n foreach ($config->getQueryTableDefinitions('Jobs') as $tableDef) {\n $alias = $tableDef['alias'];\n $table = new Table(\n new Schema($tableDef['schema']),\n $tableDef['name'],\n $alias\n );\n $tables[$alias] = $table;\n $this->addTable($table);\n\n $join = $tableDef['join'];\n $this->addWhereCondition(new WhereCondition(\n new TableField($table, $join['primaryKey']),\n '=',\n new TableField($tables[$join['foreignTableAlias']], $join['foreignKey'])\n ));\n }\n\n // This table is defined in the configuration file, but used in the section below.\n $factTable = $tables['jt'];\n\n if (isset($parameters['primary_key'])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'job_id'), \"=\", $parameters['primary_key']));\n } elseif (isset($parameters['job_identifier'])) {\n $matches = array();\n if (preg_match('/^(\\d+)(?:[\\[_](\\d+)\\]?)?$/', $parameters['job_identifier'], $matches)) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'resource_id'), '=', $parameters['resource_id']));\n if (isset($matches[2])) {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_jobid'), '=', $matches[1]));\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_job_array_index'), '=', $matches[2]));\n } else {\n $this->addPdoWhereCondition(new WhereCondition(new TableField($factTable, 'local_job_id_raw'), '=', $matches[1]));\n }\n } else {\n throw new Exception('invalid \"job_identifier\" query parameter');\n }\n } elseif (isset($parameters['start_date']) && isset($parameters['end_date'])) {\n $startDate = date_parse_from_format('Y-m-d', $parameters['start_date']);\n $startDateTs = mktime(\n 0,\n 0,\n 0,\n $startDate['month'],\n $startDate['day'],\n $startDate['year']\n );\n if ($startDateTs === false) {\n throw new Exception('invalid \"start_date\" query parameter');\n }\n\n $endDate = date_parse_from_format('Y-m-d', $parameters['end_date']);\n $endDateTs = mktime(\n 23,\n 59,\n 59,\n $endDate['month'],\n $endDate['day'],\n $endDate['year']\n );\n if ($endDateTs === false) {\n throw new Exception('invalid \"end_date\" query parameter');\n }\n\n $startDayId = (\n date('Y', $startDateTs) * 100000\n + date('z', $startDateTs) + 1\n );\n $endDayId = (\n date('Y', $endDateTs) * 100000\n + date('z', $endDateTs) + 1\n );\n $aggDayIdField = new TableField($tables['agg'], 'day_id');\n $this->addWhereCondition(\n new WhereCondition($aggDayIdField, '>=', $startDayId)\n );\n $this->addWhereCondition(\n new WhereCondition($aggDayIdField, '<=', $endDayId)\n );\n $factEndDayIdField = new TableField($factTable, 'end_day_id');\n $this->addWhereCondition(\n new WhereCondition($factEndDayIdField, '>=', $startDayId)\n );\n $this->addWhereCondition(\n new WhereCondition($factEndDayIdField, '<=', $endDayId)\n );\n if ($startDayId === $endDayId) {\n // In this case, only jobs that ended on a single specific day\n // are being requested, so there will not be any duplicate rows\n // from jobs spanning multiple days. Thus, remove the DISTINCT\n // constraint and thereby speed up the query.\n $this->setDistinct(false);\n }\n } else {\n throw new Exception('invalid query parameters');\n }\n\n if ($stat == \"accounting\" || $stat == 'batch') {\n foreach ($config->getQueryFieldDefinitions('Jobs') as $field) {\n $alias = $field['name'];\n if (isset($field['tableAlias']) && isset($field['column'])) {\n $this->addField(new TableField(\n $tables[$field['tableAlias']],\n $field['column'],\n $alias\n ));\n } elseif (isset($field['formula'])) {\n $this->addField(new FormulaField($field['formula'], $alias));\n } else {\n throw new Exception(sprintf(\n 'Missing tableAlias and column or formula for \"%s\", definition: %s',\n $alias,\n json_encode($field)\n ));\n }\n $this->documentation[$alias] = $field;\n }\n } else {\n $this->addField(new TableField($factTable, \"job_id\", \"jobid\"));\n $this->addField(new TableField($factTable, \"local_jobid\", \"local_job_id\"));\n\n $rt = new Table(new Schema(\"modw\"), \"resourcefact\", \"rf\");\n $this->joinTo($rt, \"task_resource_id\", \"code\", \"resource\");\n\n $pt = new Table(new Schema('modw'), 'person', 'p');\n $this->joinTo($pt, \"person_id\", \"long_name\", \"name\");\n\n $st = new Table(new Schema('modw'), 'systemaccount', 'sa');\n $this->joinTo($st, \"systemaccount_id\", \"username\", \"username\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function getUniqueKey(ElementInterface $element, int $nr = 0): string\n {\n $list = new Listing();\n $list->setUnpublished(true);\n $list->setObjectTypes(DataObject::$types);\n $key = Element\\Service::getValidKey($element->getKey(), 'object');\n if (!$key) {\n throw new Exception('No item key set.');\n }\n if ($nr) {\n $key .= '_'.$nr;\n }\n\n $parent = $element->getParent();\n if (!$parent) {\n throw new Exception('You have to set a parent Object to determine a unique Key');\n }\n\n if (!$element->getId()) {\n $list->setCondition('parentId = ? AND `key` = ? ', [$parent->getId(), $key]);\n } else {\n $list->setCondition('parentId = ? AND `key` = ? AND id != ? ', [$parent->getId(), $key, $element->getId()]);\n }\n $check = $list->loadIdList();\n if (!empty($check)) {\n $nr++;\n $key = self::getUniqueKey($element, $nr);\n }\n\n return $key;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function delete(): void\n {\n $this->dispatchEvent(new DocumentEvent($this), DocumentEvents::PRE_DELETE);\n\n $this->beginTransaction();\n\n try {\n if ($this->getId() == 1) {\n throw new Exception('root-node cannot be deleted');\n }\n\n $this->doDelete();\n $this->getDao()->delete();\n\n $this->commit();\n\n //clear parent data from registry\n $parentCacheKey = self::getCacheKey($this->getParentId());\n if (RuntimeCache::isRegistered($parentCacheKey)) {\n /** @var Document $parent */\n $parent = RuntimeCache::get($parentCacheKey);\n if ($parent instanceof self) {\n $parent->setChildren(null);\n }\n }\n } catch (Exception $e) {\n $this->rollBack();\n $failureEvent = new DocumentEvent($this);\n $failureEvent->setArgument('exception', $e);\n $this->dispatchEvent($failureEvent, DocumentEvents::POST_DELETE_FAILURE);\n Logger::error((string) $e);\n\n throw $e;\n }\n\n // clear cache\n $this->clearDependentCache();\n\n //clear document from registry\n RuntimeCache::set(self::getCacheKey($this->getId()), null);\n RuntimeCache::set(self::getPathCacheKey($this->getRealFullPath()), null);\n\n $this->dispatchEvent(new DocumentEvent($this), DocumentEvents::POST_DELETE);\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function getChartData($chart_id, $overrides)\n {\n $arg_set = explode(\"&\", $chart_id);\n $query_params = array();\n\n foreach ($arg_set as $a) {\n list($arg_name, $arg_value) = explode('=', $a, 2);\n $query_params[$arg_name] = $arg_value;\n }\n\n $callargs = array_merge($query_params, $overrides);\n\n $supportedControllers = array(\n 'metric_explorer' => array(\n 'class' => '\\DataWarehouse\\Access\\MetricExplorer',\n 'function' => 'get_data' ),\n 'usage_explorer' => array(\n 'class' => '\\DataWarehouse\\Access\\MetricExplorer',\n 'function' => 'get_data' ),\n 'data_explorer' => array(\n 'class' => '\\DataWarehouse\\Access\\DataExplorer',\n 'function' => 'get_ak_plot'),\n 'custom_query' => array(\n 'class' => '\\DataWarehouse\\Access\\CustomQuery',\n 'function' => 'get_data'\n )\n );\n\n if( isset($query_params['controller_module']) && isset($query_params['operation']) )\n {\n $module = $query_params['controller_module'];\n $operation = $query_params['operation'];\n\n if( isset($supportedControllers[$module]) && $supportedControllers[$module]['function'] == $operation ) {\n $c = new $supportedControllers[$module]['class']($callargs);\n $response = $c->$operation($this->_user);\n }\n else\n {\n $usageAdapter = new Usage($callargs);\n $response = $usageAdapter->getCharts($this->_user);\n }\n return $response['results'];\n }\n else\n {\n // No controller specified - this must be a chart generated with an ealier verson\n // of the XDMoD software. Use the presence of format=hc_jsonstore to determine which\n // controller processes the chart\n if( isset($query_params['format']) && $query_params['format'] == 'hc_jsonstore') {\n $c = new \\DataWarehouse\\Access\\MetricExplorer($callargs);\n $response = $c->get_data($this->_user);\n } else {\n $usageAdapter = new Usage($callargs);\n $response = $usageAdapter->getCharts($this->_user);\n }\n return $response['results'];\n }\n\n throw new \\Exception(\"Unsupported controller in report generator\");\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function testPortalSettingsVersionNumber()\n {\n $portalSettingsData = parse_ini_file($this->portalSettingIniPath, true);\n if ($portalSettingsData === false) {\n throw new Exception(\n sprintf('Failed to parse \"%s\"', $this->portalSettingIniPath)\n );\n }\n\n $buildData = Json::loadFile($this->buildJsonPath);\n\n $this->assertEquals(\n $buildData['version'],\n $portalSettingsData['general']['version'],\n sprintf(\n 'Version in \"%s\" matches version in \"%s\"',\n $this->portalSettingIniPath,\n $this->buildJsonPath\n )\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private static function getSearchResultsBySchema(array $schema, array $request_params): array\n {\n // Schema must be an object type\n if ($schema['type'] !== Doc\\Schema::TYPE_OBJECT) {\n throw new \\RuntimeException('Schema must be an object type');\n }\n // Initialize a new search\n $search = new self($schema, $request_params);\n $ids = $search->getMatchingRecords();\n $results = $search->hydrateRecords($ids);\n\n $mapped_props = array_filter($search->getFlattenedProperties(), static function ($prop) {\n return isset($prop['x-mapper']);\n });\n\n foreach ($results as &$result) {\n // Handle mapped fields\n foreach ($mapped_props as $mapped_prop_name => $mapped_prop) {\n if (ArrayPathAccessor::hasElementByArrayPath($result, $mapped_prop['x-mapped-from'])) {\n ArrayPathAccessor::setElementByArrayPath(\n array: $result,\n path: $mapped_prop_name,\n value: $mapped_prop['x-mapper'](ArrayPathAccessor::getElementByArrayPath($result, $mapped_prop['x-mapped-from']))\n );\n }\n }\n // Handle mapped objects\n $mapped_objs = [];\n foreach ($search->getFlattenedProperties() as $prop_name => $prop) {\n if (isset($prop['x-mapped-property'])) {\n $parent_obj_path = substr($prop_name, 0, strrpos($prop_name, '.'));\n if (isset($mapped_objs[$parent_obj_path])) {\n // Parent object already mapped\n continue;\n }\n $parent_obj = ArrayPathAccessor::getElementByArrayPath($schema['properties'], $parent_obj_path);\n if ($parent_obj === null) {\n continue;\n }\n $mapper = $parent_obj['items']['x-mapper'] ?? $parent_obj['x-mapper'];\n $mapped_from = $parent_obj['items']['x-mapped-from'] ?? $parent_obj['x-mapped-from'];\n $mapped_objs[$parent_obj_path] = $mapper(ArrayPathAccessor::getElementByArrayPath($result, $mapped_from));\n }\n }\n foreach ($mapped_objs as $path => $data) {\n $existing_data = ArrayPathAccessor::getElementByArrayPath($result, $path) ?? [];\n $data = array_merge($existing_data, $data);\n ArrayPathAccessor::setElementByArrayPath($result, $path, $data);\n }\n $result = Doc\\Schema::fromArray($schema)->castProperties($result);\n }\n unset($result);\n\n // Count the total number of results with the same criteria, but without the offset and limit\n $criteria = $search->getSearchCriteria();\n // We only need the total count, so we don't need to hydrate the records\n $all_records = $search->getMatchingRecords(true);\n $total_count = 0;\n foreach ($all_records as $schema_name => $records) {\n $total_count += count($records);\n }\n\n return [\n 'results' => array_values($results),\n 'start' => $criteria['START'] ?? 0,\n 'limit' => $criteria['LIMIT'] ?? count($results),\n 'total' => $total_count,\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getTempSysDir()\n {\n if (!isset($this->tempDir)) {\n $this->tempDir = tempnam(sys_get_temp_dir(), 'ehi-export-');\n if (file_exists($this->tempDir)) {\n unlink($this->tempDir);\n }\n mkdir($this->tempDir);\n if (!is_dir($this->tempDir)) {\n throw new \\RuntimeException(\"Failed to make temporary directory for export in temp directory\");\n }\n }\n return $this->tempDir;\n }", "smellKey": "S112", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (App $utopia, Request $request, Document $project) {\n\n $route = $utopia->getRoute();\n\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n $isAppUser = Auth::isAppUser(Authorization::getRoles());\n\n if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs\n return;\n }\n\n $auths = $project->getAttribute('auths', []);\n switch ($route->getLabel('auth.type', '')) {\n case 'emailPassword':\n if (($auths['emailPassword'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email / Password authentication is disabled for this project');\n }\n break;\n\n case 'magic-url':\n if ($project->getAttribute('usersAuthMagicURL', true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Magic URL authentication is disabled for this project');\n }\n break;\n\n case 'anonymous':\n if (($auths['anonymous'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Anonymous authentication is disabled for this project');\n }\n break;\n\n case 'invites':\n if (($auths['invites'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Invites authentication is disabled for this project');\n }\n break;\n\n case 'jwt':\n if (($auths['JWT'] ?? true) === false) {\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'JWT authentication is disabled for this project');\n }\n break;\n\n default:\n throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');\n break;\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function () use ($id) {\n\t\t\t$qb = $this->db->getQueryBuilder();\n\t\t\t$update = $qb->update('calendars')\n\t\t\t\t->set('deleted_at', $qb->createNamedParameter(null))\n\t\t\t\t->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));\n\t\t\t$update->executeStatement();\n\n\t\t\t$calendarData = $this->getCalendarById($id);\n\t\t\t$shares = $this->getShares($id);\n\t\t\tif ($calendarData === null) {\n\t\t\t\tthrow new RuntimeException('Calendar data that was just written can\\'t be read back. Check your database configuration.');\n\t\t\t}\n\t\t\t$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(\n\t\t\t\t$id,\n\t\t\t\t$calendarData,\n\t\t\t\t$shares\n\t\t\t));\n\t\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function quote($identifier)\n {\n // We can't quote non-strings so....\n if (!is_string($identifier)) {\n throw new \\Exception('Unable to quote non-string identifier.');\n }\n\n // Don't quote the identifier if it's already been quoted\n if (str_starts_with($identifier, $this->systemQuoteChar)\n && str_ends_with($identifier, $this->systemQuoteChar)) {\n return $identifier;\n } else {\n return $this->systemQuoteChar . $identifier . $this->systemQuoteChar;\n }\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected function encode64($input, $count)\n {\n if (!is_int($count) || $count < 1) {\n throw new \\Exception('Argument count must be a positive integer');\n }\n $output = '';\n $i = 0;\n do {\n $value = ord($input[$i++]);\n $output .= $this->itoa64[$value & 0x3f];\n if ($i < $count) {\n $value |= ord($input[$i]) << 8;\n }\n $output .= $this->itoa64[($value >> 6) & 0x3f];\n if ($i++ >= $count) {\n break;\n }\n if ($i < $count) {\n $value |= ord($input[$i]) << 16;\n }\n $output .= $this->itoa64[($value >> 12) & 0x3f];\n if ($i++ >= $count) {\n break;\n }\n $output .= $this->itoa64[($value >> 18) & 0x3f];\n } while ($i < $count);\n\n return $output;\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function theResponseShouldContainAShareTypesPropertyWith($table) {\n\t\t$keys = $this->response;\n\t\tif (!array_key_exists('{http://owncloud.org/ns}share-types', $keys)) {\n\t\t\tthrow new \\Exception(\"Cannot find property \\\"{http://owncloud.org/ns}share-types\\\"\");\n\t\t}\n\n\t\t$foundTypes = [];\n\t\t$data = $keys['{http://owncloud.org/ns}share-types'];\n\t\tforeach ($data as $item) {\n\t\t\tif ($item['name'] !== '{http://owncloud.org/ns}share-type') {\n\t\t\t\tthrow new \\Exception('Invalid property found: \"' . $item['name'] . '\"');\n\t\t\t}\n\n\t\t\t$foundTypes[] = $item['value'];\n\t\t}\n\n\t\tforeach ($table->getRows() as $row) {\n\t\t\t$key = array_search($row[0], $foundTypes);\n\t\t\tif ($key === false) {\n\t\t\t\tthrow new \\Exception('Expected type ' . $row[0] . ' not found');\n\t\t\t}\n\n\t\t\tunset($foundTypes[$key]);\n\t\t}\n\n\t\tif ($foundTypes !== []) {\n\t\t\tthrow new \\Exception('Found more share types then specified: ' . $foundTypes);\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $databaseId, string $documentId, string $collectionId, string|array $data, ?array $permissions, Response $response, Database $dbForProject, Document $user, Event $events, string $mode) {\n\n $data = (\\is_string($data)) ? \\json_decode($data, true) : $data; // Cast to JSON array\n\n if (empty($data)) {\n throw new Exception(Exception::DOCUMENT_MISSING_DATA);\n }\n\n if (isset($data['$id'])) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, '$id is not allowed for creating new documents, try update instead');\n }\n\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId));\n\n if ($collection->isEmpty() || (!$collection->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $allowedPermissions = [\n Database::PERMISSION_READ,\n Database::PERMISSION_UPDATE,\n Database::PERMISSION_DELETE,\n ];\n\n // Map aggregate permissions to into the set of individual permissions they represent.\n $permissions = Permission::aggregate($permissions, $allowedPermissions);\n\n // Add permissions for current the user if none were provided.\n if (\\is_null($permissions)) {\n $permissions = [];\n if (!empty($user->getId())) {\n foreach ($allowedPermissions as $permission) {\n $permissions[] = (new Permission($permission, 'user', $user->getId()))->toString();\n }\n }\n }\n\n // Users can only manage their own roles, API keys and Admin users can manage any\n if (!$isAPIKey && !$isPrivilegedUser) {\n foreach (Database::PERMISSIONS as $type) {\n foreach ($permissions as $permission) {\n $permission = Permission::parse($permission);\n if ($permission->getPermission() != $type) {\n continue;\n }\n $role = (new Role(\n $permission->getRole(),\n $permission->getIdentifier(),\n $permission->getDimension()\n ))->toString();\n if (!Authorization::isRole($role)) {\n throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \\implode(', ', Authorization::getRoles()) . ')');\n }\n }\n }\n }\n\n $data['$collection'] = $collection->getId(); // Adding this param to make API easier for developers\n $data['$id'] = $documentId == 'unique()' ? ID::unique() : $documentId;\n $data['$permissions'] = $permissions;\n $document = new Document($data);\n\n $checkPermissions = function (Document $collection, Document $document, string $permission) use (&$checkPermissions, $dbForProject, $database) {\n $documentSecurity = $collection->getAttribute('documentSecurity', false);\n $validator = new Authorization($permission);\n\n $valid = $validator->isValid($collection->getPermissionsByType($permission));\n if (($permission === Database::PERMISSION_UPDATE && !$documentSecurity) || !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n if ($permission === Database::PERMISSION_UPDATE) {\n $valid = $valid || $validator->isValid($document->getUpdate());\n if ($documentSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n }\n\n $relationships = \\array_filter(\n $collection->getAttribute('attributes', []),\n fn($attribute) => $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP\n );\n\n foreach ($relationships as $relationship) {\n $related = $document->getAttribute($relationship->getAttribute('key'));\n\n if (empty($related)) {\n continue;\n }\n\n $isList = \\is_array($related) && \\array_values($related) === $related;\n\n if ($isList) {\n $relations = $related;\n } else {\n $relations = [$related];\n }\n\n $relatedCollectionId = $relationship->getAttribute('relatedCollection');\n $relatedCollection = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $relatedCollectionId)\n );\n\n foreach ($relations as &$relation) {\n if (\n \\is_array($relation)\n && \\array_values($relation) !== $relation\n && !isset($relation['$id'])\n ) {\n $relation['$id'] = ID::unique();\n $relation = new Document($relation);\n }\n if ($relation instanceof Document) {\n $current = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $relatedCollection->getInternalId(), $relation->getId())\n );\n\n if ($current->isEmpty()) {\n $type = Database::PERMISSION_CREATE;\n\n if (isset($relation['$id']) && $relation['$id'] === 'unique()') {\n $relation['$id'] = ID::unique();\n }\n } else {\n $relation->removeAttribute('$collectionId');\n $relation->removeAttribute('$databaseId');\n $relation->setAttribute('$collection', $relatedCollection->getId());\n $type = Database::PERMISSION_UPDATE;\n }\n\n $checkPermissions($relatedCollection, $relation, $type);\n }\n }\n\n if ($isList) {\n $document->setAttribute($relationship->getAttribute('key'), \\array_values($relations));\n } else {\n $document->setAttribute($relationship->getAttribute('key'), \\reset($relations));\n }\n }\n };\n\n $checkPermissions($collection, $document, Database::PERMISSION_CREATE);\n\n try {\n $document = $dbForProject->createDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $document);\n } catch (StructureException $exception) {\n throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, $exception->getMessage());\n } catch (DuplicateException $exception) {\n throw new Exception(Exception::DOCUMENT_ALREADY_EXISTS);\n }\n\n // Add $collectionId and $databaseId for all documents\n $processDocument = function (Document $collection, Document $document) use (&$processDocument, $dbForProject, $database) {\n $document->setAttribute('$databaseId', $database->getId());\n $document->setAttribute('$collectionId', $collection->getId());\n\n $relationships = \\array_filter(\n $collection->getAttribute('attributes', []),\n fn($attribute) => $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP\n );\n\n foreach ($relationships as $relationship) {\n $related = $document->getAttribute($relationship->getAttribute('key'));\n\n if (empty($related)) {\n continue;\n }\n if (!\\is_array($related)) {\n $related = [$related];\n }\n\n $relatedCollectionId = $relationship->getAttribute('relatedCollection');\n $relatedCollection = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $relatedCollectionId)\n );\n\n foreach ($related as $relation) {\n if ($relation instanceof Document) {\n $processDocument($relatedCollection, $relation);\n }\n }\n }\n };\n\n $processDocument($collection, $document);\n\n $events\n ->setParam('databaseId', $databaseId)\n ->setParam('collectionId', $collection->getId())\n ->setParam('documentId', $document->getId())\n ->setContext('collection', $collection)\n ->setContext('database', $database);\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic($document, Response::MODEL_DOCUMENT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (GitHub $github, string $providerInstallationId, array $repositories, string $providerBranch, string $providerBranchUrl, string $providerRepositoryName, string $providerRepositoryUrl, string $providerRepositoryOwner, string $providerCommitHash, string $providerCommitAuthor, string $providerCommitAuthorUrl, string $providerCommitMessage, string $providerCommitUrl, string $providerPullRequestId, bool $external, Database $dbForConsole, callable $getProjectDB, Request $request) {\n foreach ($repositories as $resource) {\n $resourceType = $resource->getAttribute('resourceType');\n\n if ($resourceType === \"function\") {\n $projectId = $resource->getAttribute('projectId');\n $project = Authorization::skip(fn () => $dbForConsole->getDocument('projects', $projectId));\n $dbForProject = $getProjectDB($project);\n\n $functionId = $resource->getAttribute('resourceId');\n $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId));\n\n $deploymentId = ID::unique();\n $repositoryId = $resource->getId();\n $repositoryInternalId = $resource->getInternalId();\n $providerRepositoryId = $resource->getAttribute('providerRepositoryId');\n $installationId = $resource->getAttribute('installationId');\n $installationInternalId = $resource->getAttribute('installationInternalId');\n $productionBranch = $function->getAttribute('providerBranch');\n $activate = false;\n\n if ($providerBranch == $productionBranch && $external === false) {\n $activate = true;\n }\n\n $owner = $github->getOwnerName($providerInstallationId) ?? '';\n $repositoryName = $github->getRepositoryName($providerRepositoryId) ?? '';\n\n if (empty($repositoryName)) {\n throw new Exception(Exception::PROVIDER_REPOSITORY_NOT_FOUND);\n }\n\n $isAuthorized = !$external;\n\n if (!$isAuthorized && !empty($providerPullRequestId)) {\n if (\\in_array($providerPullRequestId, $resource->getAttribute('providerPullRequestIds', []))) {\n $isAuthorized = true;\n }\n }\n\n $commentStatus = $isAuthorized ? 'waiting' : 'failed';\n\n $authorizeUrl = $request->getProtocol() . '://' . $request->getHostname() . \"/git/authorize-contributor?projectId={$projectId}&installationId={$installationId}&repositoryId={$repositoryId}&providerPullRequestId={$providerPullRequestId}\";\n\n $action = $isAuthorized ? ['type' => 'logs'] : ['type' => 'authorize', 'url' => $authorizeUrl];\n\n $latestCommentId = '';\n\n if (!empty($providerPullRequestId)) {\n $latestComment = Authorization::skip(fn () => $dbForConsole->findOne('vcsComments', [\n Query::equal('providerRepositoryId', [$providerRepositoryId]),\n Query::equal('providerPullRequestId', [$providerPullRequestId]),\n Query::orderDesc('$createdAt'),\n ]));\n\n if ($latestComment !== false && !$latestComment->isEmpty()) {\n $latestCommentId = $latestComment->getAttribute('providerCommentId', '');\n $comment = new Comment();\n $comment->parseComment($github->getComment($owner, $repositoryName, $latestCommentId));\n $comment->addBuild($project, $function, $commentStatus, $deploymentId, $action);\n\n $latestCommentId = \\strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment()));\n } else {\n $comment = new Comment();\n $comment->addBuild($project, $function, $commentStatus, $deploymentId, $action);\n $latestCommentId = \\strval($github->createComment($owner, $repositoryName, $providerPullRequestId, $comment->generateComment()));\n\n if (!empty($latestCommentId)) {\n $teamId = $project->getAttribute('teamId', '');\n\n $latestComment = Authorization::skip(fn () => $dbForConsole->createDocument('vcsComments', new Document([\n '$id' => ID::unique(),\n '$permissions' => [\n Permission::read(Role::team(ID::custom($teamId))),\n Permission::update(Role::team(ID::custom($teamId), 'owner')),\n Permission::update(Role::team(ID::custom($teamId), 'developer')),\n Permission::delete(Role::team(ID::custom($teamId), 'owner')),\n Permission::delete(Role::team(ID::custom($teamId), 'developer')),\n ],\n 'installationInternalId' => $installationInternalId,\n 'installationId' => $installationId,\n 'projectInternalId' => $project->getInternalId(),\n 'projectId' => $project->getId(),\n 'providerRepositoryId' => $providerRepositoryId,\n 'providerBranch' => $providerBranch,\n 'providerPullRequestId' => $providerPullRequestId,\n 'providerCommentId' => $latestCommentId\n ])));\n }\n }\n } elseif (!empty($providerBranch)) {\n $latestComments = Authorization::skip(fn () => $dbForConsole->find('vcsComments', [\n Query::equal('providerRepositoryId', [$providerRepositoryId]),\n Query::equal('providerBranch', [$providerBranch]),\n Query::orderDesc('$createdAt'),\n ]));\n\n foreach ($latestComments as $comment) {\n $latestCommentId = $comment->getAttribute('providerCommentId', '');\n $comment = new Comment();\n $comment->parseComment($github->getComment($owner, $repositoryName, $latestCommentId));\n $comment->addBuild($project, $function, $commentStatus, $deploymentId, $action);\n\n $latestCommentId = \\strval($github->updateComment($owner, $repositoryName, $latestCommentId, $comment->generateComment()));\n }\n }\n\n if (!$isAuthorized) {\n $functionName = $function->getAttribute('name');\n $projectName = $project->getAttribute('name');\n $name = \"{$functionName} ({$projectName})\";\n $message = 'Authorization required for external contributor.';\n\n $providerRepositoryId = $resource->getAttribute('providerRepositoryId');\n $repositoryName = $github->getRepositoryName($providerRepositoryId);\n $owner = $github->getOwnerName($providerInstallationId);\n $github->updateCommitStatus($repositoryName, $providerCommitHash, $owner, 'failure', $message, $authorizeUrl, $name);\n continue;\n }\n\n if ($external) {\n $pullRequestResponse = $github->getPullRequest($owner, $repositoryName, $providerPullRequestId);\n $providerRepositoryName = $pullRequestResponse['head']['repo']['owner']['login'];\n $providerRepositoryOwner = $pullRequestResponse['head']['repo']['name'];\n }\n\n $deployment = $dbForProject->createDocument('deployments', new Document([\n '$id' => $deploymentId,\n '$permissions' => [\n Permission::read(Role::any()),\n Permission::update(Role::any()),\n Permission::delete(Role::any()),\n ],\n 'resourceId' => $functionId,\n 'resourceType' => 'functions',\n 'entrypoint' => $function->getAttribute('entrypoint'),\n 'commands' => $function->getAttribute('commands'),\n 'type' => 'vcs',\n 'installationId' => $installationId,\n 'installationInternalId' => $installationInternalId,\n 'providerRepositoryId' => $providerRepositoryId,\n 'repositoryId' => $repositoryId,\n 'repositoryInternalId' => $repositoryInternalId,\n 'providerBranchUrl' => $providerBranchUrl,\n 'providerRepositoryName' => $providerRepositoryName,\n 'providerRepositoryOwner' => $providerRepositoryOwner,\n 'providerRepositoryUrl' => $providerRepositoryUrl,\n 'providerCommitHash' => $providerCommitHash,\n 'providerCommitAuthorUrl' => $providerCommitAuthorUrl,\n 'providerCommitAuthor' => $providerCommitAuthor,\n 'providerCommitMessage' => $providerCommitMessage,\n 'providerCommitUrl' => $providerCommitUrl,\n 'providerCommentId' => \\strval($latestCommentId),\n 'providerBranch' => $providerBranch,\n 'search' => implode(' ', [$deploymentId, $function->getAttribute('entrypoint')]),\n 'activate' => $activate,\n ]));\n\n if (!empty($providerCommitHash) && $function->getAttribute('providerSilentMode', false) === false) {\n $functionName = $function->getAttribute('name');\n $projectName = $project->getAttribute('name');\n $name = \"{$functionName} ({$projectName})\";\n $message = 'Starting...';\n\n $providerRepositoryId = $resource->getAttribute('providerRepositoryId');\n $repositoryName = $github->getRepositoryName($providerRepositoryId);\n $owner = $github->getOwnerName($providerInstallationId);\n\n $providerTargetUrl = $request->getProtocol() . '://' . $request->getHostname() . \"/console/project-$projectId/functions/function-$functionId\";\n $github->updateCommitStatus($repositoryName, $providerCommitHash, $owner, 'pending', $message, $providerTargetUrl, $name);\n }\n\n $buildEvent = new Build();\n $buildEvent\n ->setType(BUILD_TYPE_DEPLOYMENT)\n ->setResource($function)\n ->setDeployment($deployment)\n ->setProject($project)\n ->trigger();\n\n //TODO: Add event?\n }\n }\n}", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function verifySections(\n EtlConfiguration $etlConfig,\n array $sectionNameList,\n array $sectionActionObjectList = array(),\n $verifyDisabled = false\n ) {\n if ( 0 == count($sectionNameList) ) {\n return $sectionActionObjectList;\n }\n\n $messages = array();\n\n foreach ( $sectionNameList as $sectionName ) {\n $actionNameList = $etlConfig->getSectionActionNames($sectionName);\n $actionObjectList = ( array_key_exists($sectionName, $sectionActionObjectList)\n ? $sectionActionObjectList[$sectionName]\n : array() );\n try {\n $sectionActionObjectList[$sectionName] = $this->verifyActions(\n $etlConfig,\n $actionNameList,\n $actionObjectList,\n $sectionName\n );\n } catch ( Exception $e ) {\n $messages[] = \"('$sectionName': \" . $e->getMessage() . \")\";\n }\n } // foreach ( $sectionNames as $sectionName )\n\n if ( 0 != count($messages) ) {\n $msg = \"Error verifying sections: \" . implode(\", \", $messages);\n throw new Exception($msg);\n }\n\n return $sectionActionObjectList;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function call(string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true, int $timeout = 15, callable $callback = null)\n {\n $headers = array_merge($this->headers, $headers);\n $ch = curl_init($this->endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : ''));\n $responseHeaders = [];\n $responseStatus = -1;\n $responseType = '';\n $responseBody = '';\n\n switch ($headers['content-type']) {\n case 'application/json':\n $query = json_encode($params);\n break;\n\n case 'multipart/form-data':\n $query = $this->flatten($params);\n break;\n\n default:\n $query = http_build_query($params);\n break;\n }\n\n foreach ($headers as $i => $header) {\n $headers[] = $i . ':' . $header;\n unset($headers[$i]);\n }\n\n if (isset($callback)) {\n $headers[] = 'accept: text/event-stream';\n\n $handleEvent = function ($ch, $data) use ($callback) {\n $callback($data);\n return \\strlen($data);\n };\n\n curl_setopt($ch, CURLOPT_WRITEFUNCTION, $handleEvent);\n } else {\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n }\n\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);\n curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);\n curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);\n curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);\n curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {\n $len = strlen($header);\n $header = explode(':', $header, 2);\n\n if (count($header) < 2) { // ignore invalid headers\n return $len;\n }\n\n $responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);\n\n return $len;\n });\n\n if ($method != self::METHOD_GET) {\n curl_setopt($ch, CURLOPT_POSTFIELDS, $query);\n }\n\n // Allow self signed certificates\n if ($this->selfSigned) {\n curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\n }\n\n $responseBody = curl_exec($ch);\n\n if (isset($callback)) {\n curl_close($ch);\n return [];\n }\n\n $responseType = $responseHeaders['content-type'] ?? '';\n $responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);\n\n if ($decode) {\n switch (substr($responseType, 0, strpos($responseType, ';'))) {\n case 'application/json':\n $json = json_decode($responseBody, true);\n\n if ($json === null) {\n throw new Exception('Failed to parse response: ' . $responseBody);\n }\n\n $responseBody = $json;\n $json = null;\n break;\n }\n }\n\n if ((curl_errno($ch)/* || 200 != $responseStatus*/)) {\n throw new Exception(curl_error($ch) . ' with status code ' . $responseStatus, $responseStatus);\n }\n\n curl_close($ch);\n\n $responseHeaders['status-code'] = $responseStatus;\n\n return [\n 'headers' => $responseHeaders,\n 'body' => $responseBody\n ];\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (string $databaseId, string $collectionId, string $documentId, array $queries, Response $response, Database $dbForProject, string $mode) {\n $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($database->isEmpty() || (!$database->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::DATABASE_NOT_FOUND);\n }\n\n $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId));\n\n if ($collection->isEmpty() || (!$collection->getAttribute('enabled', false) && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::COLLECTION_NOT_FOUND);\n }\n\n $queries = Query::parseQueries($queries);\n\n try {\n $document = $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId, $queries);\n } catch (AuthorizationException) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n } catch (QueryException $e) {\n throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, $e->getMessage());\n }\n\n if ($document->isEmpty()) {\n throw new Exception(Exception::DOCUMENT_NOT_FOUND);\n }\n\n // Add $collectionId and $databaseId for all documents\n $processDocument = function (Document $collection, Document $document) use (&$processDocument, $dbForProject, $database) {\n if ($document->isEmpty()) {\n return;\n }\n\n $document->setAttribute('$databaseId', $database->getId());\n $document->setAttribute('$collectionId', $collection->getId());\n\n $relationships = \\array_filter(\n $collection->getAttribute('attributes', []),\n fn($attribute) => $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP\n );\n\n foreach ($relationships as $relationship) {\n $related = $document->getAttribute($relationship->getAttribute('key'));\n\n if (empty($related)) {\n continue;\n }\n if (!\\is_array($related)) {\n $related = [$related];\n }\n\n $relatedCollectionId = $relationship->getAttribute('relatedCollection');\n $relatedCollection = Authorization::skip(\n fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $relatedCollectionId)\n );\n\n foreach ($related as $relation) {\n if ($relation instanceof Document) {\n $processDocument($relatedCollection, $relation);\n }\n }\n }\n };\n\n $processDocument($collection, $document);\n\n $response->dynamic($document, Response::MODEL_DOCUMENT);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function phash($type, $imageData)\n {\n $out = \"\";\n\n if ($type === 'png' || $type === 'svg') {\n $command = '/root/bin/imagehash';\n if ($type == 'svg') {\n $command = 'rsvg-convert -f png | /root/bin/imagehash';\n }\n $pipes = array();\n $descriptor_spec = array(\n 0 => array('pipe', 'r'),\n 1 => array('pipe', 'w'),\n 2 => array('pipe', 'w'),\n );\n $process = proc_open($command, $descriptor_spec, $pipes);\n if (!is_resource($process)) {\n throw new \\Exception('Unable execute command Details: ' . print_r(error_get_last(), true));\n }\n fwrite($pipes[0], $imageData);\n fclose($pipes[0]);\n\n $out = stream_get_contents($pipes[1]);\n $err = stream_get_contents($pipes[2]);\n fclose($pipes[1]);\n fclose($pipes[2]);\n $retval = proc_close($process);\n if (strlen($err) > 0 || $retval !== 0) {\n throw new \\UnexpectedValueException(\"imagehash returned $retval stderr='$err'\");\n }\n } else {\n $out = sha1($imageData);\n }\n\n return $out;\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setAutoFilter($pRange = '')\n\t{\n\t\t// Uppercase coordinate\n\t\t$pRange = strtoupper($pRange);\n\n\t\tif (strpos($pRange,':') !== false) {\n\t\t\t$this->_autoFilter = $pRange;\n\t\t\t$this->_dirty = true;\n\t\t} else {\n\t\t\tthrow new Exception('Autofilter must be set on a range of cells.');\n\t\t}\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "private function loadShippedJson(): void {\n\t\tif ($this->shippedApps === null) {\n\t\t\t$shippedJson = \\OC::$SERVERROOT . '/core/shipped.json';\n\t\t\tif (!file_exists($shippedJson)) {\n\t\t\t\tthrow new \\Exception(\"File not found: $shippedJson\");\n\t\t\t}\n\t\t\t$content = json_decode(file_get_contents($shippedJson), true);\n\t\t\t$this->shippedApps = $content['shippedApps'];\n\t\t\t$this->alwaysEnabled = $content['alwaysEnabled'];\n\t\t\t$this->defaultEnabled = $content['defaultEnabled'];\n\t\t}\n\t}", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function delete(bool $deleteQuery = true, bool $isUpdate = true): bool\n {\n if ($isUpdate && !DataObject::isDirtyDetectionDisabled() && !$this->model->hasDirtyFields()) {\n return false;\n }\n $object = $this->model->getObject();\n $context = $this->model->getContext();\n $container = null;\n\n try {\n if (isset($context['containerType']) && ($context['containerType'] === 'fieldcollection' || $context['containerType'] === 'objectbrick')) {\n $containerKey = $context['containerKey'];\n if ($context['containerType'] === 'fieldcollection') {\n $container = DataObject\\Fieldcollection\\Definition::getByKey($containerKey);\n } else {\n $container = DataObject\\Objectbrick\\Definition::getByKey($containerKey);\n }\n } else {\n $container = $object->getClass();\n }\n if ($deleteQuery) {\n $id = $object->getId();\n $tablename = $this->getTableName();\n if (isset($context['containerType']) && $context['containerType'] === 'objectbrick') {\n $this->db->delete($tablename, ['ooo_id' => $id, 'fieldname' => $context['fieldname']]);\n } else {\n $this->db->delete($tablename, ['ooo_id' => $id]);\n }\n\n if (!$container instanceof DataObject\\Fieldcollection\\Definition || $container instanceof DataObject\\Objectbrick\\Definition) {\n $validLanguages = Tool::getValidLanguages();\n foreach ($validLanguages as $language) {\n $queryTable = $this->getQueryTableName().'_'.$language;\n $this->db->delete($queryTable, ['ooo_id' => $id]);\n }\n }\n }\n\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $fieldDefinition */\n $fieldDefinition = $container->getFieldDefinition('localizedfields', ['suppressEnrichment' => true]);\n $childDefinitions = $fieldDefinition->getFieldDefinitions(['suppressEnrichment' => true]);\n\n foreach ($childDefinitions as $fd) {\n if ($fd instanceof CustomResourcePersistingInterface) {\n $params = [\n 'context' => $this->model->getContext() ? $this->model->getContext() : [],\n 'isUpdate' => $isUpdate,\n ];\n if (isset($params['context']['containerType']) && ($params['context']['containerType'] === 'fieldcollection' || $params['context']['containerType'] === 'objectbrick')) {\n $params['context']['subContainerType'] = 'localizedfield';\n }\n\n $fd->delete($object, $params);\n }\n }\n } catch (Exception $e) {\n Logger::error((string) $e);\n\n if ($isUpdate && $e instanceof TableNotFoundException) {\n try {\n $this->db->rollBack();\n } catch (Exception $er) {\n // PDO adapter throws exceptions if rollback fails\n Logger::info((string) $er);\n }\n\n $this->createUpdateTable();\n\n // throw exception which gets caught in AbstractObject::save() -> retry saving\n throw new LanguageTableDoesNotExistException('missing table created, start next run ... ;-)');\n }\n }\n\n // remove relations\n $ignoreLocalizedQueryFallback = \\Pimcore\\Config::getSystemConfiguration('objects')['ignore_localized_query_fallback'];\n if (!$ignoreLocalizedQueryFallback) {\n $this->model->markLanguageAsDirtyByFallback();\n }\n\n if (!DataObject::isDirtyDetectionDisabled()) {\n if (!$this->model->hasDirtyFields()) {\n return false;\n }\n }\n\n $db = Db::get();\n $dirtyLanguageCondition = null;\n\n if ($this->model->allLanguagesAreDirty() ||\n ($container instanceof DataObject\\Fieldcollection\\Definition)\n ) {\n $dirtyLanguageCondition = '';\n } elseif ($this->model->hasDirtyLanguages()) {\n $languageList = [];\n if (is_array($this->model->getDirtyLanguages())) {\n foreach ($this->model->getDirtyLanguages() as $language => $flag) {\n if ($flag) {\n $languageList[] = $db->quote($language);\n }\n }\n }\n\n $dirtyLanguageCondition = ' AND position IN('.implode(',', $languageList).')';\n }\n\n if ($container instanceof DataObject\\Fieldcollection\\Definition) {\n $objectId = $object->getId();\n $index = $context['index'] ?? $context['containerKey'] ?? null;\n $containerName = $context['fieldname'];\n if (!$context['containerType']) {\n throw new Exception('no container type set');\n }\n\n $sql = Helper::quoteInto($this->db, 'src_id = ?', $objectId).\" AND ownertype = 'localizedfield' AND \"\n .Helper::quoteInto($this->db,\n 'ownername LIKE ?',\n '/'.$context['containerType'].'~'.$containerName.'/'.$index.'/%'\n ).$dirtyLanguageCondition;\n\n if ($deleteQuery || $context['containerType'] === 'fieldcollection') {\n // Fieldcollection don't support delta updates, so we delete the relations and insert them later again\n $this->db->executeStatement('DELETE FROM object_relations_'.$object->getClassId().' WHERE '.$sql);\n }\n\n return true;\n }\n\n if ($deleteQuery || $context['containerType'] === 'fieldcollection') {\n // Fieldcollection don't support delta updates, so we delete the relations and insert them later again\n $sql = 'ownertype = \"localizedfield\" AND ownername = \"localizedfield\" and src_id = '.$this->model->getObject(\n )->getId().$dirtyLanguageCondition;\n $this->db->executeStatement(\n 'DELETE FROM object_relations_'.$this->model->getObject()->getClassId().' WHERE '.$sql\n );\n }\n\n return false;\n }", "smellKey": "S112", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function handleAgentResponse(Response $response, $request): array\n {\n $data = [];\n\n $raw_content = (string)$response->getBody();\n\n switch ($request) {\n case self::ACTION_STATUS:\n $data['answer'] = preg_replace('/status: /', '', $raw_content);\n break;\n case self::ACTION_INVENTORY:\n $now = new DateTime();\n $data['answer'] = sprintf(\n __('Requested at %s'),\n $now->format(__('Y-m-d H:i:s'))\n );\n break;\n default:\n throw new \\RuntimeException(sprintf('Unknown request type %s', $request));\n }\n\n return $data;\n }", "smellKey": "S112", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (Database $dbForConsole, Document $project) use ($pools, $cache) {\n /**\n * Skip user projects with id 'console'\n */\n if ($project->getId() === 'console') {\n Console::info(\"Skipping project console\");\n return;\n }\n\n Console::log(\"Getting stats for {$project->getId()}\");\n\n try {\n $db = $project->getAttribute('database');\n $adapter = $pools\n ->get($db)\n ->pop()\n ->getResource();\n\n $dbForProject = new Database($adapter, $cache);\n $dbForProject->setDefaultDatabase('appwrite');\n $dbForProject->setNamespace('_' . $project->getInternalId());\n\n $statsPerProject = [];\n\n $statsPerProject['time'] = microtime(true);\n\n /** Get Project ID */\n $statsPerProject['project_id'] = $project->getId();\n\n /** Get project created time */\n $statsPerProject['project_created'] = $project->getAttribute('$createdAt');\n\n /** Get Project Name */\n $statsPerProject['project_name'] = $project->getAttribute('name');\n\n /** Get Total Functions */\n $statsPerProject['custom_functions'] = $dbForProject->count('functions', [], APP_LIMIT_COUNT);\n\n foreach (\\array_keys(Config::getParam('runtimes')) as $runtime) {\n $statsPerProject['custom_functions_' . $runtime] = $dbForProject->count('functions', [\n Query::equal('runtime', [$runtime]),\n ], APP_LIMIT_COUNT);\n }\n\n /** Get Total Deployments */\n $statsPerProject['custom_deployments'] = $dbForProject->count('deployments', [], APP_LIMIT_COUNT);\n\n /** Get Total Teams */\n $statsPerProject['custom_teams'] = $dbForProject->count('teams', [], APP_LIMIT_COUNT);\n\n /** Get Total Members */\n $teamInternalId = $project->getAttribute('teamInternalId', null);\n if ($teamInternalId) {\n $statsPerProject['custom_organization_members'] = $dbForConsole->count('memberships', [\n Query::equal('teamInternalId', [$teamInternalId])\n ], APP_LIMIT_COUNT);\n } else {\n $statsPerProject['custom_organization_members'] = 0;\n }\n\n /** Get Email and Name of the project owner */\n if ($teamInternalId) {\n $membership = $dbForConsole->findOne('memberships', [\n Query::equal('teamInternalId', [$teamInternalId]),\n ]);\n\n if (!$membership || $membership->isEmpty()) {\n throw new Exception('Membership not found. Skipping project : ' . $project->getId());\n }\n\n $userInternalId = $membership->getAttribute('userInternalId', null);\n if ($userInternalId) {\n $user = $dbForConsole->findOne('users', [\n Query::equal('_id', [$userInternalId]),\n ]);\n\n $statsPerProject['email'] = $user->getAttribute('email', null);\n $statsPerProject['name'] = $user->getAttribute('name', null);\n }\n }\n\n /** Get Domains */\n $statsPerProject['custom_domains'] = $dbForConsole->count('domains', [\n Query::equal('projectInternalId', [$project->getInternalId()]),\n Query::limit(APP_LIMIT_COUNT)\n ]);\n\n /** Get Platforms */\n $platforms = $dbForConsole->find('platforms', [\n Query::equal('projectInternalId', [$project->getInternalId()]),\n Query::limit(APP_LIMIT_COUNT)\n ]);\n\n $statsPerProject['custom_platforms_web'] = sizeof(array_filter($platforms, function ($platform) {\n return $platform['type'] === 'web';\n }));\n\n $statsPerProject['custom_platforms_android'] = sizeof(array_filter($platforms, function ($platform) {\n return $platform['type'] === 'android';\n }));\n\n $statsPerProject['custom_platforms_apple'] = sizeof(array_filter($platforms, function ($platform) {\n return str_contains($platform['type'], 'apple');\n }));\n\n $statsPerProject['custom_platforms_flutter'] = sizeof(array_filter($platforms, function ($platform) {\n return str_contains($platform['type'], 'flutter');\n }));\n\n $flutterPlatforms = [Origin::CLIENT_TYPE_FLUTTER_ANDROID, Origin::CLIENT_TYPE_FLUTTER_IOS, Origin::CLIENT_TYPE_FLUTTER_MACOS, Origin::CLIENT_TYPE_FLUTTER_WINDOWS, Origin::CLIENT_TYPE_FLUTTER_LINUX];\n\n foreach ($flutterPlatforms as $flutterPlatform) {\n $statsPerProject['custom_platforms_' . $flutterPlatform] = sizeof(array_filter($platforms, function ($platform) use ($flutterPlatform) {\n return $platform['type'] === $flutterPlatform;\n }));\n }\n\n $statsPerProject['custom_platforms_api_keys'] = $dbForConsole->count('keys', [\n Query::equal('projectInternalId', [$project->getInternalId()]),\n Query::limit(APP_LIMIT_COUNT)\n ]);\n\n /** Get Usage $statsPerProject */\n $periods = [\n 'infinity' => [\n 'period' => '1d',\n 'limit' => 90,\n ],\n '24h' => [\n 'period' => '1h',\n 'limit' => 24,\n ],\n ];\n\n Authorization::skip(function () use ($dbForProject, $periods, &$statsPerProject) {\n foreach ($this->metrics as $key => $metric) {\n foreach ($periods as $periodKey => $periodValue) {\n $limit = $periodValue['limit'];\n $period = $periodValue['period'];\n\n $requestDocs = $dbForProject->find('stats', [\n Query::equal('period', [$period]),\n Query::equal('metric', [$metric]),\n Query::limit($limit),\n Query::orderDesc('time'),\n ]);\n\n $statsPerProject[$key . '_' . $periodKey] = [];\n foreach ($requestDocs as $requestDoc) {\n $statsPerProject[$key . '_' . $periodKey][] = [\n 'value' => $requestDoc->getAttribute('value'),\n 'date' => $requestDoc->getAttribute('time'),\n ];\n }\n\n $statsPerProject[$key . '_' . $periodKey] = array_reverse($statsPerProject[$key . '_' . $periodKey]);\n // Calculate aggregate of each metric\n $statsPerProject[$key . '_' . $periodKey] = array_sum(array_column($statsPerProject[$key . '_' . $periodKey], 'value'));\n }\n }\n });\n\n if (isset($statsPerProject['email'])) {\n /** Send data to mixpanel */\n $res = $this->mixpanel->createProfile($statsPerProject['email'], '', [\n 'name' => $statsPerProject['name'],\n 'email' => $statsPerProject['email']\n ]);\n\n if (!$res) {\n Console::error('Failed to create user profile for project: ' . $project->getId());\n }\n\n $event = new Event();\n $event\n ->setName('Project Daily Usage')\n ->setProps($statsPerProject);\n $res = $this->mixpanel->createEvent($event);\n if (!$res) {\n Console::error('Failed to create event for project: ' . $project->getId());\n }\n }\n } catch (Exception $e) {\n Console::error('Failed to send stats for project: ' . $project->getId());\n Console::error($e->getMessage());\n } finally {\n $pools\n ->get($db)\n ->reclaim();\n }\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function processMacro($string, stdClass $config)\n {\n if ( null === self::$etlConfig ) {\n $msg = __CLASS__ . \": ETL configuration object not set\";\n throw new Exception($msg);\n }\n\n $paths = self::$etlConfig->getPaths();\n\n if ( ! isset($paths->macro_dir) ) {\n $msg = __CLASS__ . \": ETL configuration paths.macro_dir is not set\";\n throw new Exception($msg);\n } elseif ( ! is_dir($paths->macro_dir) ) {\n $msg = __CLASS__ . \": ETL configuration paths.macro_dir '{$paths->macro_dir}' is not a directory\";\n throw new Exception($msg);\n }\n\n $requiredProperties = array(\"name\", \"file\");\n $missingProperties = array();\n\n // Verify requred options\n\n foreach ( $requiredProperties as $p ) {\n if ( ! isset($config->$p) || null === $config->$p || \"\" == $config->$p ) {\n $missingProperties[] = $p;\n }\n }\n\n if ( 0 != count($missingProperties) ) {\n $msg = __CLASS__ . \": Required properties not provided: \" . implode(\", \", $missingProperties);\n throw new Exception($msg);\n }\n\n // Read in a macro file, substitute keys for values, and return the macro\n\n $filename = $paths->macro_dir . \"/\" . $config->file;\n if ( ! is_file($filename) ) {\n $msg = __CLASS__ . \": Cannot load macro file '$filename'\";\n throw new Exception($msg);\n } elseif ( 0 == filesize($filename) ) {\n // No use processing an empty macro\n return;\n }\n\n if ( false === ($macro = @file_get_contents($filename)) ) {\n $msg = __CLASS__ . \": Error reading macro file '$filename'\";\n throw new Exception($msg);\n }\n\n // Strip comments from macro\n\n $stripped = array();\n\n foreach ( explode(\"\\n\", $macro) as $line ) {\n if ( 0 === strpos($line, \"--\") || 0 === strpos($line, \"#\") ) {\n continue;\n }\n $stripped[] = $line;\n }\n\n $macro = @implode(\"\\n\", $stripped);\n\n // Replace macro arguments\n\n $vs = new VariableStore();\n\n if ( isset($config->args) ) {\n $vs->add((array) $config->args);\n $macro = $vs->substitute($macro);\n\n }\n\n $vs->clear();\n $vs->add(array($config->name => $macro));\n $string = $vs->substitute($string);\n\n return $string;\n\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function setUseDiskCaching($pValue = false, $pDirectory = null) {\n\t\t$this->_useDiskCaching = $pValue;\n\n\t\tif ($pDirectory !== NULL) {\n \t\tif (is_dir($pDirectory)) {\n \t\t\t$this->_diskCachingDirectory = $pDirectory;\n \t\t} else {\n \t\t\tthrow new Exception(\"Directory does not exist: $pDirectory\");\n \t\t}\n\t\t}\n\t\treturn $this;\n\t}", "smellKey": "S112", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function getCharts(XDUser $user, $chartsKey = 'data') {\n\n if (isset($this->request['summary'])) {\n return $this->getSummaryCharts($user);\n }\n\n // Determine which realms are being requested.\n if (empty($this->request['realm'])) {\n throw new Exception('One or more realms must be specified.');\n }\n $requestedRealms = array_map('trim', explode(',', $this->request['realm']));\n\n // For each realm requested, get the requested charts.\n $usageCharts = array();\n foreach ($requestedRealms as $usageRealm) {\n // Set the realm on the request object for functions that look\n // at the request directly.\n $this->request['realm'] = $usageRealm;\n $realm = Realm::factory($usageRealm);\n\n // If present, move the dimension value into statistic.\n if (array_key_exists('dimension', $this->request)) {\n $this->request['group_by'] = $this->request['dimension'];\n unset($this->request['dimension']);\n }\n\n // Get the request's group by.\n $usageGroupBy = \\xd_utilities\\array_get($this->request, 'group_by', 'none');\n $usageGroupByObject = $realm->getGroupByObject($usageGroupBy);\n // Get whether or not the request is for a timeseries chart.\n $usageIsTimeseries = \\xd_utilities\\array_get($this->request, 'dataset_type') === 'timeseries';\n\n // Get the format to return the results in.\n $usageFormat = \\xd_utilities\\array_get($this->request, 'format', 'hc_jsonstore');\n $isJsonStoreExport = $usageFormat === 'jsonstore';\n $isCsvExport = $usageFormat === 'csv';\n $isXmlExport = $usageFormat === 'xml';\n $isTextExport =\n $isCsvExport\n || $isXmlExport\n || $usageFormat === 'json'\n || $isJsonStoreExport\n ;\n\n // If present, move the fact value into statistic.\n if (array_key_exists('fact', $this->request)) {\n $this->request['statistic'] = $this->request['fact'];\n unset($this->request['fact']);\n }\n\n // Get whether or not the request is for multiple metrics.\n $isSingleMetricQuery = array_key_exists('statistic', $this->request);\n\n // If this request is asking for timeseries data for multiple metrics\n // for a datasheet, return an error response.\n if (\n $usageIsTimeseries\n && !$isSingleMetricQuery\n && $isJsonStoreExport\n ) {\n return array(\n 'headers' => \\DataWarehouse\\ExportBuilder::getHeader($usageFormat),\n 'results' => json_encode(array(\n \"metaData\" => array(\n \"totalProperty\" => \"total\",\n \"root\" => \"records\",\n \"id\" => \"id\",\n \"fields\" => array(\n array(\n \"name\" => 'Message',\n \"type\" => 'string',\n ),\n ),\n ),\n \"success\" => true,\n \"message\" => 'Datasheet view is not available for timeseries. Turn off timeseries or use the Export button to get the data.',\n \"total\" => 1,\n \"records\" => array(\n array(\n 'Message' => 'Datasheet view is not available for timeseries. Turn off timeseries or use the Export button to get the data.',\n ),\n ),\n \"columns\" => array(\n array(\n \"header\" => 'Error Message',\n \"width\" => 600,\n \"dataIndex\" => 'Message',\n \"sortable\" => true,\n 'editable' => false,\n 'align' => 'left',\n 'renderer' => \"CCR.xdmod.ui.stringRenderer\",\n ),\n ),\n )),\n );\n }\n\n // Convert the request options to a set of Metric Explorer requests.\n //\n // If one statistic was requested, convert it into a single ME request.\n // Otherwise, create one ME request for each available statistic.\n //\n // If the request was for aggregate charts and any statistic can't\n // be provided in that form, quietly change its chart to timeseries.\n $meRequests = array();\n $userStatistics = Acls::getPermittedStatistics($user, $usageRealm, $usageGroupBy);\n if ($isSingleMetricQuery) {\n if (!$usageIsTimeseries) {\n $userStatisticObject = $realm->getStatisticObject($this->request['statistic']);\n if (!$userStatisticObject->usesTimePeriodTablesForAggregate()) {\n throw new BadRequestHttpException(\n json_encode(\n array(\n 'statistic' => $userStatisticObject->getName(),\n 'instructions' => 'Try again as timeseries',\n 'description' => 'Aggregate View not supported'\n )\n )\n );\n }\n }\n $meRequests[] = $this->convertChartRequest($this->request, $isTextExport);\n } else {\n foreach ($userStatistics as $userStatistic) {\n $userStatisticObject = $realm->getStatisticObject($userStatistic);\n\n if ( ! $userStatisticObject->showInMetricCatalog() ) {\n continue;\n }\n\n $statisticRequest = $this->request;\n $statisticRequest['statistic'] = $userStatistic;\n if (\n !$usageIsTimeseries &&\n !$userStatisticObject->usesTimePeriodTablesForAggregate()\n ) {\n // If a text-based export of aggregate data was requested\n // and not all statistics can be provided as aggregates,\n // return a failure response.\n if ($isTextExport) {\n return array(\n 'results' => json_encode(array(\n 'success' => false,\n 'message' => \"Aggregate data not available for all metrics. Change to timeseries and try again.\",\n 'totalCount' => 0,\n $chartsKey => array(),\n )),\n 'headers' => array(),\n );\n }\n\n $statisticRequest['dataset_type'] = 'timeseries';\n $statisticRequest['display_type'] = 'line';\n $statisticRequest['swap_xy'] = false;\n }\n $meRequests[] = $this->convertChartRequest($statisticRequest, $isTextExport);\n }\n }\n\n // If this is a special format, condense the list of requests to a\n // single request.\n if ($isTextExport && !empty($meRequests)) {\n $firstMeRequest = null;\n foreach ($meRequests as &$meRequest) {\n if ($firstMeRequest === null) {\n $firstMeRequest = $meRequest;\n continue;\n }\n\n $firstMeRequest['data_series_unencoded'][] = $meRequest['data_series_unencoded'][0];\n }\n $firstMeRequest['data_series'] = urlencode(json_encode($firstMeRequest['data_series_unencoded']));\n\n // Generate the title now, as we can't use the Metric Explorer\n // response's properties to easily generate the title.\n if ($isSingleMetricQuery) {\n $specialFormatChartTitle = $realm->getStatisticObject($this->request['statistic'])->getName();\n } else {\n $specialFormatChartTitle = $usageRealm;\n }\n if ($usageGroupBy !== 'none') {\n $specialFormatChartTitle .= ': by ' . $usageGroupByObject->getName();\n }\n $firstMeRequest['title'] = $specialFormatChartTitle;\n\n // Generate the filename based on how Usage previously did it.\n $firstMeRequest['filename'] = $this->generateFilename(\n $specialFormatChartTitle,\n $this->request['start_date'],\n $this->request['end_date'],\n $usageIsTimeseries\n );\n\n $meRequests = array($firstMeRequest);\n }\n\n // Run the Metric Explorer chart generator on each request.\n $meResponses = array();\n foreach ($meRequests as $meRequest) {\n $meGenerator = new MetricExplorer($meRequest);\n $meResponses[] = $meGenerator->get_data($user);\n }\n\n // If no charts were generated, return a failure response.\n if (empty($meResponses)) {\n return array(\n 'results' => json_encode(array(\n 'success' => false,\n 'message' => 'No charts could be generated using the given parameters.',\n 'totalCount' => 0,\n $chartsKey => array(),\n )),\n 'headers' => array(),\n );\n }\n\n // If this is a text export, perform special handling of the response.\n if ($isTextExport) {\n\n $meResponse = $meResponses[0];\n\n // If this is a JSON store export...\n if ($isJsonStoreExport) {\n\n // Combine multiple results into a single object to return.\n $meRequest = $meRequests[0];\n $meRequestIsTimeseries = $meRequest['timeseries'];\n $emptyResultFound = false;\n $combinedResult = null;\n $combinedResultColumns = null;\n $combinedResultFields = null;\n $combinedResultRecords = array();\n $combinedResultFirstColumn = null;\n $combinedResultRestricted = false;\n foreach ($meResponse['results'] as $meJsonResult) {\n $meResult = json_decode($meJsonResult, true);\n if ($combinedResultFirstColumn === null) {\n $combinedResultFirstColumn = $meResult['metaData']['fields'][0]['name'];\n }\n\n if ($meResult['records'] == array(array('Message' => 'Dataset is empty'))) {\n $emptyResultFound = true;\n continue;\n }\n\n if ($meRequestIsTimeseries) {\n $combinedResultRecords = $meResult['records'];\n } else {\n foreach ($meResult['records'] as $meResultRecord) {\n $meResultRecordFirstValue = $meResultRecord[$combinedResultFirstColumn];\n if (array_key_exists($meResultRecordFirstValue, $combinedResultRecords)) {\n $combinedResultRecords[$meResultRecordFirstValue] = array_merge(\n $combinedResultRecords[$meResultRecordFirstValue],\n $meResultRecord\n );\n } else {\n $combinedResultRecords[$meResultRecordFirstValue] = $meResultRecord;\n }\n }\n }\n\n if (\\xd_utilities\\array_get($meResult, 'restrictedByRoles', false)) {\n $combinedResultRestricted = true;\n }\n\n if ($combinedResult === null) {\n $combinedResult = $meResult;\n $combinedResultFields = $meResult['metaData']['fields'];\n $combinedResultColumns = $meResult['columns'];\n continue;\n }\n\n $combinedResultFields[] = $meResult['metaData']['fields'][1];\n $combinedResultColumns[] = $meResult['columns'][1];\n }\n\n // If no results were returned, return a failure response.\n // Otherwise, finish combining the results.\n if ($combinedResult === null) {\n if ($emptyResultFound) {\n $failureResults = reset($meResponse['results']);\n } else {\n $failureResults = json_encode(array(\n 'success' => false,\n ));\n }\n\n return array(\n 'headers' => $meResponse['headers'],\n 'results' => $failureResults,\n );\n }\n\n if ($meRequestIsTimeseries) {\n $timeseriesTemplateField = $combinedResultFields[2];\n $timeseriesTemplateColumn = $combinedResultColumns[2];\n\n $timeseriesGroupByColumnName = $combinedResultColumns[1]['dataIndex'];\n $valueColumnName = $timeseriesTemplateColumn['dataIndex'];\n\n $combinedResultFields = array_slice($combinedResultFields, 0, 1);\n $combinedResultColumns = array_slice($combinedResultColumns, 0, 1);\n\n $timeseriesFields = array();\n $nextFieldNameIndex = 0;\n $timeseriesColumns = array();\n $timeseriesRecords = array();\n foreach ($combinedResultRecords as $resultRecord) {\n $resultRecordDimension = $resultRecord[$timeseriesGroupByColumnName];\n\n if (!array_key_exists($resultRecordDimension, $timeseriesColumns)) {\n $timeseriesDimensionColumnName = \"dimension_column_$nextFieldNameIndex\";\n $nextFieldNameIndex++;\n\n $timeseriesColumn = $timeseriesTemplateColumn;\n $timeseriesColumn['header'] = \"[${resultRecordDimension}] \" . $timeseriesColumn['header'];\n $timeseriesColumn['dataIndex'] = $timeseriesDimensionColumnName;\n $timeseriesColumns[$resultRecordDimension] = $timeseriesColumn;\n\n $timeseriesField = $timeseriesTemplateField;\n $timeseriesField['name'] = $timeseriesDimensionColumnName;\n $timeseriesFields[$resultRecordDimension] = $timeseriesField;\n } else {\n $timeseriesDimensionColumnName = $timeseriesColumns[$resultRecordDimension]['dataIndex'];\n }\n\n $timeseriesRecordTime = $resultRecord[$combinedResultFirstColumn];\n $timeseriesRecord = array(\n $combinedResultFirstColumn => $timeseriesRecordTime,\n $timeseriesDimensionColumnName => $resultRecord[$valueColumnName],\n );\n\n if (array_key_exists($timeseriesRecordTime, $timeseriesRecords)) {\n $timeseriesRecords[$timeseriesRecordTime] = array_merge(\n $timeseriesRecords[$timeseriesRecordTime],\n $timeseriesRecord\n );\n } else {\n $timeseriesRecords[$timeseriesRecordTime] = $timeseriesRecord;\n }\n }\n\n $combinedResultFields = array_merge(\n $combinedResultFields,\n array_values($timeseriesFields)\n );\n $combinedResultColumns = array_merge(\n $combinedResultColumns,\n array_values($timeseriesColumns)\n );\n $combinedResultRecords = $timeseriesRecords;\n }\n\n // Sort the value columns by title.\n $combinedResultKeyColumns = array_slice($combinedResultColumns, 0, 1);\n $combinedResultValueColumns = array_slice($combinedResultColumns, 1);\n usort($combinedResultValueColumns, function ($a, $b) {\n return strcmp($a['header'], $b['header']);\n });\n $combinedResultColumns = array_merge(\n $combinedResultKeyColumns,\n $combinedResultValueColumns\n );\n\n // Store the combined results in the object to be returned.\n $combinedResult['metaData']['fields'] = $combinedResultFields;\n $combinedResult['columns'] = $combinedResultColumns;\n $combinedResult['records'] = array_values($combinedResultRecords);\n $combinedResult['restrictedByRoles'] = $combinedResultRestricted;\n\n // Get the dimension and metric descriptions.\n $jsonStoreMessage = '<ul>';\n $jsonStoreMessage .= '<li>' . $usageGroupByObject->getHtmlNameAndDescription() . '</li>';\n\n $jsonStoreMessageMetricDescriptions = array();\n foreach ($meRequest['data_series_unencoded'] as $meRequestDataSeries) {\n $jsonStoreMessageMetricDescriptions[] = sprintf(\n '<li>%s</li>',\n $realm->getStatisticObject($meRequestDataSeries['metric'])->getHtmlNameAndDescription()\n );\n }\n sort($jsonStoreMessageMetricDescriptions);\n $jsonStoreMessage .= implode('', $jsonStoreMessageMetricDescriptions);\n\n $jsonStoreMessage .= '</ul>';\n $combinedResult['message'] = $jsonStoreMessage;\n\n // Sort the datasheet appropriately.\n if ($meRequestIsTimeseries || !$isSingleMetricQuery) {\n $sortField = $combinedResultFirstColumn;\n $sortDirection = 'asc';\n } else {\n $meRequestSortType = $meRequest['data_series_unencoded'][0]['sort_type'];\n\n if (\\xd_utilities\\string_begins_with($meRequestSortType, 'value')) {\n $sortField = $combinedResult['metaData']['fields'][1]['name'];\n } else {\n $sortField = $combinedResultFirstColumn;\n }\n\n if (\\xd_utilities\\string_ends_with($meRequestSortType, 'desc')) {\n $sortDirection = 'desc';\n } else {\n $sortDirection = 'asc';\n }\n }\n\n $combinedResult['metaData']['sortInfo'] = array(\n 'field' => $sortField,\n 'direction' => $sortDirection,\n );\n\n // Set the results to the combined result.\n $meResponse['results'] = json_encode($combinedResult);\n }\n\n return $meResponse;\n }\n\n // Get attributes common to all charts that will be returned.\n $usageTitle = \\xd_utilities\\array_get($this->request, 'title');\n $usageSubtitle = \\xd_utilities\\array_get($this->request, 'subtitle');\n $usageOffset = intval(\\xd_utilities\\array_get($this->request, 'offset', 0));\n $usageWidth = intval(\\xd_utilities\\array_get($this->request, 'width', self::DEFAULT_WIDTH));\n $usageHeight = intval(\\xd_utilities\\array_get($this->request, 'height', self::DEFAULT_HEIGHT));\n $usageFontSize = intval(\\xd_utilities\\array_get($this->request, 'font_size', 3));\n $usageShowGradient = \\xd_utilities\\array_get($this->request, 'show_gradient', 'y');\n $usageShowGradient = $usageShowGradient === 'true' || $usageShowGradient === 'y';\n $thumbnailRequested = \\xd_utilities\\array_get($this->request, 'thumbnail', 'n') === 'y';\n $showTitle = \\xd_utilities\\array_get($this->request, 'show_title', 'y');\n\n // Generate the chart settings that will be returned with each chart.\n $usageChartSettings = array(\n 'dataset_type' => \\xd_utilities\\array_get($this->request, 'dataset_type', $usageGroupByObject->getDefaultDatasetType()),\n 'display_type' => \\xd_utilities\\array_get($this->request, 'display_type', $usageGroupByObject->getDefaultDisplayType($usageGroupByObject->getDefaultDatasetType())),\n 'combine_type' => \\xd_utilities\\array_get($this->request, 'combine_type', $usageGroupByObject->getDefaultCombineMethod()),\n 'show_legend' => \\xd_utilities\\array_get($this->request, 'show_legend', $usageGroupByObject->getDefaultShowLegend()),\n 'show_guide_lines' => \\xd_utilities\\array_get($this->request, 'show_guide_lines', $usageGroupByObject->getDefaultShowGuideLines()),\n 'log_scale' => \\xd_utilities\\array_get($this->request, 'log_scale', $usageGroupByObject->getDefaultLogScale()),\n 'limit' => \\xd_utilities\\array_get($this->request, 'limit', $usageGroupByObject->getDefaultLimit()),\n 'offset' => \\xd_utilities\\array_get($this->request, 'offset', $usageGroupByObject->getDefaultOffset()),\n 'show_trend_line' => \\xd_utilities\\array_get($this->request, 'show_trend_line', $usageGroupByObject->getDefaultShowTrendLine()),\n 'show_error_bars' => \\xd_utilities\\array_get($this->request, 'show_error_bars', $usageGroupByObject->getDefaultShowErrorBars()),\n 'show_aggregate_labels' => \\xd_utilities\\array_get($this->request, 'show_aggregate_labels', $usageGroupByObject->getDefaultShowAggregateLabels()),\n 'show_error_labels' => \\xd_utilities\\array_get($this->request, 'show_error_labels', $usageGroupByObject->getDefaultShowErrorLabels()),\n 'hide_tooltip' => \\xd_utilities\\array_get($this->request, 'hide_tooltip', false),\n 'enable_errors' => 'n',\n 'enable_trend_line' => \\xd_utilities\\array_get($this->request, 'enable_trend_line', $usageGroupByObject->getDefaultEnableTrendLine()),\n );\n\n $usageSubnotes = array();\n if ($usageGroupBy === 'resource' || array_key_exists('resource', $this->request)) {\n $usageSubnotes[] = '* Resources marked with asterisk do not provide processor'\n . ' counts per job when submitting to the '\n . ORGANIZATION_NAME . ' Central Database. This affects the'\n . ' accuracy of the following (and related) statistics: Job'\n . ' Size and CPU Consumption';\n }\n\n // Generate the title style that will be used for all charts.\n $usageTitleFontSizeInPixels = 16 + $usageFontSize;\n $usageTitleStyle = array(\n 'color' => '#000000',\n 'size' => \"${usageTitleFontSizeInPixels}\",\n );\n\n // Get the user's report generator chart pool.\n $chartPool = new XDChartPool($user);\n\n // Convert each Metric Explorer response into a Usage chart.\n foreach ($meResponses as $meResponseIndex => $meResponse) {\n // If the response indicates failure, skip this response.\n $meResponseContent = $meResponse['results'];\n if (!$meResponseContent['success']) {\n continue;\n }\n\n // Get the request for this chart.\n $meRequest = $meRequests[$meResponseIndex];\n $meRequestIsTimeseries = $meRequest['timeseries'];\n\n // Get the statistic object used by this chart request.\n $meRequestMetric = $realm->getStatisticObject($meRequest['data_series_unencoded'][0]['metric']);\n\n $errorstat = \\Realm\\Realm::getStandardErrorStatisticFromStatistic(\n $meRequest['data_series_unencoded'][0]['metric']\n );\n\n if (in_array($errorstat, $realm->getStatisticIds()) ) {\n $usageChartSettings['enable_errors'] = 'y';\n }\n\n // Get the chart object from the response.\n $meChart = &$meResponseContent['data'][0];\n\n // Extract the report generator options.\n $meReportGeneratorMeta = \\xd_utilities\\array_extract($meChart, 'reportGeneratorMeta', array());\n\n // Replace the in-chart descriptions with empty arrays.\n $meChart['dimensions'] = array();\n $meChart['metrics'] = array();\n\n // Grab the dimension and metric and generate a formatted group\n // and metric description.\n $usageChartDimensionDescription = $usageGroupByObject->getHtmlNameAndDescription();\n $usageChartMetricDescription = $meRequestMetric->getHtmlNameAndDescription();\n\n // If specified, use the given subtitle. Otherwise, get the\n // subtitle from the title of the resulting chart.\n //\n // Because the function doesn't receive a custom title, if any,\n // from this adapter, the chart's subtitle is placed in the title.\n $usageChartSubtitle = $usageSubtitle !== null ? $usageSubtitle : $meChart['layout']['annotations'][0]['text'];\n // Generate the title and short title of this chart.\n $usageChartShortTitle = $meRequestMetric->getName();\n if ($usageTitle !== null) {\n $usageChartTitle = $usageTitle;\n } else {\n $usageChartTitle = $usageChartShortTitle;\n if ($usageGroupBy !== 'none') {\n $usageChartTitle .= ': by ' . $usageGroupByObject->getName();\n }\n }\n\n // If a thumbnail was requested, do not use an in-chart title or subtitle.\n // Otherwise, use one.\n if ($thumbnailRequested) {\n $meChart['layout']['annotations'][0]['text'] = '';\n $meChart['layout']['annotations'][1]['text'] = '';\n $meChart['layout']['thumbnail'] = true;\n } else {\n // If a title was provided, display that. Otherwise, use the\n // generated title.\n $meChart['layout']['annotations'][0]['text'] = $usageChartTitle;\n $meChart['layout']['annotations'][1]['text'] = $usageChartSubtitle;\n }\n\n // Set the title style.\n $meChart['layout']['annotations'][0]['font'] = array_merge($meChart['layout']['annotations'][0]['font'], $usageTitleStyle);\n\n // If the \"Show Title\" checkbox on the Export Dialog has not been ticked,\n // do not show a chart title. However, the Metric Explorer promotes the\n // subtitle to the title if it exists and the title is not shown so mimic\n // this behavior for consistency. See AggregateChart::setChartTitleSubtitle()\n\n if ( 'n' == $showTitle ) {\n // The subtitle text is empty for thumbnails but above it is set to\n // the value of the 'subtitle' parameter or the chart title if the\n // parameter isn't present. Keep this check in here in case that\n // changes.\n\n if ( isset($meChart['layout']['annotations'][1]['text']) && '' != $meChart['layout']['annotations'][1]['text'] ) {\n $meChart['layout']['annotations'][0]['text'] = $meChart['layout']['annotations'][1]['text'];\n $meChart['layout']['annotations'][1]['text'] = '';\n } else {\n $meChart['layout']['annotations'][0]['text'] = '';\n }\n }\n\n // Generate the expected IDs for the chart.\n $usageMetric = $meRequest['data_series_unencoded'][0]['metric'];\n $usageChartId = \"statistic_${usageRealm}_${usageGroupBy}_${usageMetric}\";\n $usageChartMenuId = \"group_by_${usageRealm}_${usageGroupBy}\";\n\n // Remove extraneous x-axis properties.\n if ($meRequestIsTimeseries) {\n unset($meChart['layout']['xaxis']['title']);\n } elseif ($usageChartSettings['display_type'] != 'h_bar') {\n unset($meChart['layout']['xaxis']['title']['text']);\n }\n\n // If there is a y-axis...\n if (isset($meChart['layout']['yaxis'])) {\n // If a thumbnail was requested, remove the y-axis label.\n if ($thumbnailRequested) {\n $meChart['layout']['yaxis']['title'] = '';\n }\n\n // Fix the x-axis labels to be the same size as the y-axis labels.\n $meChart['layout']['xaxis']['tickfont']['size'] =\n $meChart['layout']['yaxis']['tickfont']['size'];\n // Set the y-axis grid line dash style and color.\n if ($meRequestIsTimeseries) {\n $meChart['layout']['yaxis']['gridcolor'] = '#c0c0c0';\n } else {\n unset($meChart['layout']['yaxis']['gridcolor']);\n }\n if ($usageChartSettings['show_guide_lines'] === 'n') {\n $axis = ($usageChartSettings['display_type'] == 'h_bar') ? 'x' : 'y';\n $meChart['layout'][$axis . 'axis']['showgrid'] = false;\n }\n }\n\n // If there are x-axis categories, they are sorted by value,\n // and this is a grouped chart, enumerate them with rank.\n $chartSortedByValue = \\xd_utilities\\string_begins_with(\n $meRequest['data_series_unencoded'][0]['sort_type'],\n 'value'\n );\n if (\n (isset($meChart['layout']['xaxis']['ticktext']) || isset($meChart['layout']['yaxis']['ticktext']))\n && $chartSortedByValue\n && $usageGroupBy !== 'none'\n ) {\n $meChartCategories = array();\n foreach (['x', 'y'] as $axis) {\n if (isset($meChart['layout'][$axis . 'axis']['ticktext'])) {\n $meChartCategories = $meChart['layout'][$axis . 'axis']['ticktext'];\n }\n }\n $usageChartCategories = array();\n $currentCategoryRank = $usageOffset + 1;\n foreach ($meChartCategories as $meChartCategory) {\n if (!empty($meChartCategory)) {\n $usageChartCategories[] = \"${currentCategoryRank}. ${meChartCategory}\";\n }\n else {\n $usageChartCategories[] = '';\n }\n $currentCategoryRank++;\n }\n if (isset($meChart['layout']['yaxis']['ticktext'])) {\n $meChart['layout']['yaxis']['ticktext'] = $usageChartCategories;\n }\n else {\n $meChart['layout']['xaxis']['ticktext'] = $usageChartCategories;\n }\n }\n\n // Generate the chart arguments string for the report generator.\n //\n // If the controller module was specified in the request, ensure\n // it is at the front of the arguments string. The rest of the\n // parameters should be sorted by key.\n $usageChartArgs = $this->request;\n unset($usageChartArgs['height']);\n unset($usageChartArgs['scale']);\n unset($usageChartArgs['show_title']);\n unset($usageChartArgs['width']);\n ksort($usageChartArgs);\n if (array_key_exists('controller_module', $usageChartArgs)) {\n $usageChartArgs = array(\n 'controller_module' => $usageChartArgs['controller_module'],\n ) + $usageChartArgs;\n }\n $usageChartArgsStr = urldecode(http_build_query($usageChartArgs));\n\n // Check if the user's chart pool contains this chart.\n $usageChartInPool = $chartPool->chartExistsInQueue($usageChartArgsStr);\n $queryDescripter = Acls::getQueryDescripters(\n $user,\n $usageRealm,\n $usageGroupBy,\n $meRequestMetric->getId()\n );\n $drillTargets = $queryDescripter->getDrillTargets($meRequestMetric->getHiddenGroupBys());\n $drillDowns = array_map(\n function ($drillTarget) {\n return explode('-', $drillTarget, 2);\n },\n $drillTargets\n );\n\n // For each data series...\n array_walk($meChart['data'], function (\n &$meDataSeries,\n $meDataSeriesIndex\n ) use (\n $usageRealm,\n $usageGroupBy,\n $drillDowns,\n $meRequestIsTimeseries,\n $thumbnailRequested,\n $meRequest,\n $meRequestMetric,\n $usageGroupByObject,\n $user,\n $chartSortedByValue\n ) {\n // Determine the type of this data series.\n $isTrendLineSeries = \\xd_utilities\\string_begins_with($meDataSeries['name'], 'Trend Line: ');\n $isStdErrSeries = \\xd_utilities\\string_begins_with($meDataSeries['name'], 'Std Err: ');\n $isNullSeries = $meDataSeries['name'] == 'gap connector';\n $isPrimaryDataSeries = !($isTrendLineSeries || $isStdErrSeries || $isNullSeries);\n\n // If this is a primary data series, increment the rank of the\n // current primary data series. Further, if this chart is\n // a timeseries chart, it is sorted by value, and it is a\n // grouped chart, add the rank to the series label.\n if ($isPrimaryDataSeries) {\n if (\n $meRequestIsTimeseries\n && $chartSortedByValue\n && $usageGroupBy !== 'none'\n ) {\n $rank = $meDataSeries['legendrank']+1;\n $meDataSeries['name'] = \"${rank}. \" . $meDataSeries['name'];\n }\n }\n\n // If this is the primary data series and the chart is not a\n // thumbnail, use line markers if and only if the number of\n // data points is less than or equal to 30,\n // or if there's a single y series data point.\n if ($isPrimaryDataSeries && !$thumbnailRequested) {\n // is there a single y data point?\n $y_values_count = 0;\n foreach ($meDataSeries['y'] as $value) {\n if ($value !== null ) {\n ++$y_values_count;\n }\n // we are only interested in the == 1 case\n if ($y_values_count > 1) {\n break;\n }\n }\n }\n\n // If this is a trend line data series...\n if ($isTrendLineSeries) {\n // Change the line style to a dotted line.\n $meDataSeries['line']['dash'] = 'dashdot';\n }\n\n if (!$isTrendLineSeries && !$thumbnailRequested) {\n $meDataSeries['drilldown']['drilldowns'] = $drillDowns;\n $meDataSeries['drilldown']['realm'] = $usageRealm;\n $meDataSeries['drilldown']['groupUnit'] = array($usageGroupBy, $usageGroupByObject->getName());\n }\n\n // Remove extraneous properties.\n unset($meDataSeries['otitle']);\n unset($meDataSeries['datasetId']);\n unset($meDataSeries['visible']);\n });\n\n if ('n' == $usageGroupByObject->getDefaultEnableErrors()) {\n $usageChartSettings['enable_errors'] = 'n';\n }\n\n // Create a Usage-style chart.\n $usageChart = array(\n 'hc_jsonstore' => $meChart,\n 'query_time' => '',\n 'query_string' => '',\n 'title' => $usageChartTitle,\n 'params_title' => html_entity_decode($usageChartSubtitle),\n 'comments' => 'comments',\n 'chart_args' => $usageChartArgsStr,\n 'reportGeneratorMeta' => array(\n 'included_in_report' => $usageChartInPool ? 'y' : 'n',\n ),\n 'short_title' => $usageChartShortTitle,\n 'random_id' => 'chart_' . mt_rand(), //TODO: Use a definitively-unique ID for inserting chart HTML tags.\n 'subnotes' => $usageSubnotes,\n 'group_description' => $usageChartDimensionDescription,\n 'description' => $usageChartMetricDescription,\n 'id' => $usageChartId,\n 'menu_id' => $usageChartMenuId,\n 'realm' => $usageRealm,\n 'start_date' => $this->request['start_date'],\n 'end_date' => $this->request['end_date'],\n 'chart_settings' => json_encode($usageChartSettings),\n 'show_gradient' => $usageShowGradient,\n 'final_width' => $usageWidth,\n 'final_height' => $usageHeight - 4,\n 'sort_type' => $meRequest['data_series_unencoded'][0]['sort_type'],\n );\n foreach ($meReportGeneratorMeta as $reportKey => $reportValue) {\n if (\n $reportKey === 'included_in_report'\n || array_key_exists($reportKey, $usageChart)\n ) {\n continue;\n }\n\n $usageChart[$reportKey] = $reportValue;\n }\n\n // Add the chart to the set of charts to return.\n $usageCharts[] = $usageChart;\n }\n }\n\n // Sort the results by short title.\n usort($usageCharts, function ($a, $b) {\n return strcmp($a['short_title'], $b['short_title']);\n });\n\n // Get the format to return the results in.\n if ($usageFormat === 'session_variable') {\n $usageFormat = 'hc_jsonstore';\n }\n\n // Get the file name to use for the results.\n $usageFileNameTitle = $usageCharts[0]['hc_jsonstore']['layout']['annotations'][0]['text'];\n if (empty($usageFileNameTitle)) {\n $usageFileNameTitle = 'untitled';\n }\n $usageFileName = $this->generateFilename(\n $usageFileNameTitle,\n $this->request['start_date'],\n $this->request['end_date'],\n $usageIsTimeseries\n );\n\n // Return the results in a response-like array.\n if ($usageFormat !== 'hc_jsonstore') {\n $chartsKey = 'data';\n $usageCharts = array_map(function ($usageChart) {\n return $usageChart['hc_jsonstore'];\n }, $usageCharts);\n }\n return $this->exportImage(\n array(\n 'success' => true,\n 'message' => 'success',\n 'totalCount' => count($usageCharts),\n $chartsKey => $usageCharts,\n ),\n $usageWidth,\n $usageHeight,\n \\xd_utilities\\array_get($this->request, 'scale', self::DEFAULT_SCALE),\n $usageFormat,\n $usageFileName,\n array(\n 'author' => $user->getFormalName(),\n 'subject' => ($usageIsTimeseries ? 'Timeseries' : 'Aggregate') . ' data for period ' . $this->request['start_date'] . ' -> ' . $this->request['end_date'],\n 'title' => $usageFileNameTitle\n )\n );\n }", "smellKey": "S112", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (array $queries, string $search, Response $response, Document $project, Database $dbForProject, Database $dbForConsole) {\n $queries = Query::parseQueries($queries);\n\n $queries[] = Query::equal('projectInternalId', [$project->getInternalId()]);\n\n if (!empty($search)) {\n $queries[] = Query::search('search', $search);\n }\n\n // Get cursor document if there was a cursor query\n $cursor = Query::getByType($queries, [Query::TYPE_CURSORAFTER, Query::TYPE_CURSORBEFORE]);\n $cursor = reset($cursor);\n if ($cursor) {\n /** @var Query $cursor */\n $installationId = $cursor->getValue();\n $cursorDocument = $dbForConsole->getDocument('installations', $installationId);\n\n if ($cursorDocument->isEmpty()) {\n throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, \"Installation '{$installationId}' for the 'cursor' value not found.\");\n }\n\n $cursor->setValue($cursorDocument);\n }\n\n $filterQueries = Query::groupByType($queries)['filters'];\n\n $results = $dbForConsole->find('installations', $queries);\n $total = $dbForConsole->count('installations', $filterQueries, APP_LIMIT_COUNT);\n\n $response->dynamic(new Document([\n 'installations' => $results,\n 'total' => $total,\n ]), Response::MODEL_INSTALLATION_LIST);\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function assertTypeId($expectedTypeId, ASNObject $object)\n {\n $actualType = $object->getType();\n if ($expectedTypeId != $actualType) {\n throw new Exception(\"Expected type ($expectedTypeId) does not match actual type ($actualType\");\n }\n }", "smellKey": "S112", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function toUnicodeCodepoint($char)\n {\n $charCode = false;\n // 7bits, 1 char\n if ((ord($char[0]) & 0x80) == 0x00) {\n $charCode = ord($char[0]);\n } elseif ((ord($char[0]) & 0xe0) == 0xc0) { // 11 bits, 2 chars\n if ((ord($char[1]) & 0xc0) != 0x80) {\n return $charCode;\n }\n\n $charCode = (\n ((ord($char[0]) & 0x1f) << 6) +\n ((ord($char[1]) & 0x3f))\n );\n\n if ($charCode < 128) {\n throw new RuntimeException('Illegal UTF-8 input character: ' . $char);\n }\n } elseif ((ord($char[0]) & 0xf0) == 0xe0) { // 16 bits, 3 chars\n if ((ord($char[1]) & 0xc0) != 0x80 ||\n (ord($char[2]) & 0xc0) != 0x80) {\n return $charCode;\n }\n $charCode = (\n ((ord($char[0]) & 0x0f) << 12) +\n ((ord($char[1]) & 0x3f) << 6) +\n ((ord($char[2]) & 0x3f))\n );\n\n if ($charCode < 2048) {\n throw new RuntimeException('Illegal UTF-8 input character: ' . $char);\n }\n } elseif ((ord($char[0]) & 0xf8) == 0xf0) { // 21 bits, 4 chars\n if ((ord($char[1]) & 0xc0) != 0x80 ||\n (ord($char[2]) & 0xc0) != 0x80 ||\n (ord($char[3]) & 0xc0) != 0x80) {\n return $charCode;\n }\n\n $charCode = (\n ((ord($char[0]) & 0x07) << 18) +\n ((ord($char[1]) & 0x3f) << 12) +\n ((ord($char[2]) & 0x3f) << 6) +\n ((ord($char[3]) & 0x3f))\n );\n\n if ($charCode < 65536) {\n throw new RuntimeException('Illegal UTF-8 input character: ' . $char);\n }\n } elseif ((ord($char[0]) & 0xfc) == 0xf8) { // 26 bits, 5 chars\n if ((ord($char[1]) & 0xc0) != 0x80 ||\n (ord($char[2]) & 0xc0) != 0x80 ||\n (ord($char[3]) & 0xc0) != 0x80 ||\n (ord($char[4]) & 0xc0) != 0x80) {\n return $charCode;\n }\n\n $charCode = (\n ((ord($char[0]) & 0x03) << 24) +\n ((ord($char[1]) & 0x3f) << 18) +\n ((ord($char[2]) & 0x3f) << 12) +\n ((ord($char[3]) & 0x3f) << 6) +\n ((ord($char[4]) & 0x3f))\n );\n\n if ($charCode < 2097152) {\n throw new RuntimeException('Illegal UTF-8 input character: ' . $char);\n }\n } elseif ((ord($char[0]) & 0xfe) == 0xfc) { // 31 bits, 6 chars\n if ((ord($char[1]) & 0xc0) != 0x80 ||\n (ord($char[2]) & 0xc0) != 0x80 ||\n (ord($char[3]) & 0xc0) != 0x80 ||\n (ord($char[4]) & 0xc0) != 0x80 ||\n (ord($char[5]) & 0xc0) != 0x80) {\n return $charCode;\n }\n\n $charCode = (\n ((ord($char[0]) & 0x01) << 30) +\n ((ord($char[1]) & 0x3f) << 24) +\n ((ord($char[2]) & 0x3f) << 18) +\n ((ord($char[3]) & 0x3f) << 12) +\n ((ord($char[4]) & 0x3f) << 6) +\n ((ord($char[5]) & 0x3f))\n );\n\n if ($charCode < 67108864) {\n throw new RuntimeException('Illegal UTF-8 input character: ' . $char);\n }\n }\n\n return $charCode;\n }", "smellKey": "S112", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function (string $migrationId, Response $response, Database $dbForProject, Document $project, Document $user, Event $eventInstance) {\n $migration = $dbForProject->getDocument('migrations', $migrationId);\n\n if ($migration->isEmpty()) {\n throw new Exception(Exception::MIGRATION_NOT_FOUND);\n }\n\n if ($migration->getAttribute('status') !== 'failed') {\n throw new Exception(Exception::MIGRATION_IN_PROGRESS, 'Migration not failed yet');\n }\n\n $migration\n ->setAttribute('status', 'pending')\n ->setAttribute('dateUpdated', \\time());\n\n // Trigger Migration\n $event = new Migration();\n $event\n ->setMigration($migration)\n ->setProject($project)\n ->setUser($user)\n ->trigger();\n\n $response->noContent();\n }", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __invoke(ContainerInterface $container, $requestedName)\n {\n $element = new Text;\n\n $element->setAttribute('class', 'form-control');\n $element->setLabelOption('class','col-sm-2 control-label');\n\n return $element;\n }", "smellKey": "S1172", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')\n {\n return $this->parent;\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "protected function _backup($params = array())\n\t{\n\t\t// Currently unsupported\n\t\treturn $this->db->display_error('db_unsupported_feature');\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function ($app) {\n return new EmbedConverterService();\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function getRequestSource(\n RequestSourceFieldConfig $config,\n AnswersSet $answers_set,\n ): ?int {\n return match ($this) {\n self::FROM_TEMPLATE => null, // Let the template apply its default value by itself.\n self::SPECIFIC_VALUE => $config->getSpecificRequestSource(),\n };\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function imagefilledellipse ($image, $cx, $cy, $width, $height, $color) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setStrokeDashArray (array $dashArray) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function transfer_summary_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_transfer_summary\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . xlt($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function getDocListByEncID($encounter, $raw_encounter_date, $pid)\n{\n global $ISSUE_TYPES, $auth_med;\n\n $documents = getDocumentsByEncounter($pid, $encounter);\n if (!empty($documents) && count($documents) > 0) {\n foreach ($documents as $documentrow) {\n if ($auth_med) {\n $irow = sqlQuery(\"SELECT type, title, begdate FROM lists WHERE id = ? LIMIT 1\", array($documentrow['list_id']));\n if ($irow) {\n $tcode = $irow['type'];\n if ($ISSUE_TYPES[$tcode]) {\n $tcode = $ISSUE_TYPES[$tcode][2];\n }\n echo text(\"$tcode: \" . $irow['title']);\n }\n } else {\n echo \"(\" . xlt('No access') . \")\";\n }\n\n // Get the notes for this document and display as title for the link.\n $queryString = \"SELECT date,note FROM notes WHERE foreign_id = ? ORDER BY date\";\n $noteResultSet = sqlStatement($queryString, array($documentrow['id']));\n $note = '';\n while ($row = sqlFetchArray($noteResultSet)) {\n $note .= oeFormatShortDate(date('Y-m-d', strtotime($row['date']))) . \" : \" . $row['note'] . \"\\n\";\n }\n $docTitle = ( $note ) ? $note : xl(\"View document\");\n\n $docHref = $GLOBALS['webroot'] . \"/controller.php?document&view&patient_id=\" . attr_url($pid) . \"&doc_id=\" . attr_url($documentrow['id']);\n echo \"<div class='text docrow' id='\" . attr($documentrow['id']) . \"'data-toggle='tooltip' data-placement='top' title='\" . attr($docTitle) . \"'>\\n\";\n echo \"<a href='$docHref' onclick='top.restoreSession()' >\" . xlt('Document') . \": \" . text($documentrow['document_name']) . '-' . $documentrow['id'] . ' (' . text(xl_document_category($documentrow['name'])) . ')' . \"</a>\";\n echo \"</div>\";\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function rightJoin($join, $condition = null, $bind = [])\n {\n return $this->join($join, $condition, 'RIGHT');\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function function1(int $value): int\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function aws_crt_credentials_provider_static_options_set_session_token(object $options, string $session_token): void {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function punSubscribe($channels, $callback) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {\n\t\t// check if server admin allows to mount public links from other servers\n\t\tif ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {\n\t\t\treturn new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);\n\t\t}\n\n\t\t$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());\n\n\t\t$httpClient = $this->clientService->newClient();\n\n\t\ttry {\n\t\t\t$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',\n\t\t\t\t[\n\t\t\t\t\t'body' =>\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'token' => $token,\n\t\t\t\t\t\t\t'shareWith' => rtrim($cloudId->getId(), '/'),\n\t\t\t\t\t\t\t'password' => $password\n\t\t\t\t\t\t],\n\t\t\t\t\t'connect_timeout' => 10,\n\t\t\t\t]\n\t\t\t);\n\t\t} catch (\\Exception $e) {\n\t\t\tif (empty($password)) {\n\t\t\t\t$message = $this->l->t(\"Couldn't establish a federated share.\");\n\t\t\t} else {\n\t\t\t\t$message = $this->l->t(\"Couldn't establish a federated share, maybe the password was wrong.\");\n\t\t\t}\n\t\t\treturn new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);\n\t\t}\n\n\t\t$body = $response->getBody();\n\t\t$result = json_decode($body, true);\n\n\t\tif (is_array($result) && isset($result['remoteUrl'])) {\n\t\t\treturn new JSONResponse(['message' => $this->l->t('Federated Share request sent, you will receive an invitation. Check your notifications.')]);\n\t\t}\n\n\t\t// if we doesn't get the expected response we assume that we try to add\n\t\t// a federated share from a Nextcloud <= 9 server\n\t\t$message = $this->l->t(\"Couldn't establish a federated share, it looks like the server to federate with is too old (Nextcloud <= 9).\");\n\t\treturn new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n $dbAdapter = $container->get(\\Laminas\\Db\\Adapter\\Adapter::class);\n $resultSetPrototype = new ResultSet();\n $resultSetPrototype->setArrayObjectPrototype(new Multipledb());\n $tableGateway = new TableGateway('multiple_db', $dbAdapter, null, $resultSetPrototype);\n $table = new MultipledbTable($tableGateway);\n return $table;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getBillsBetween(\n $code_type,\n $cols = \"id,date,pid,code_type,code,user,authorized,x12_partner_id\"\n ) {\n self::generateTheQueryPart();\n global $query_part, $billstring, $auth;\n // Selecting by the date in the billing table is wrong, because that is\n // just the data entry date; instead we want to go by the encounter date\n // which is the date in the form_encounter table.\n //\n $sql = \"SELECT distinct form_encounter.date AS enc_date, form_encounter.pid AS enc_pid, \" .\n \"form_encounter.encounter AS enc_encounter, form_encounter.provider_id AS enc_provider_id, billing.* \" .\n \"FROM form_encounter \" .\n \"LEFT OUTER JOIN billing ON \" .\n \"billing.encounter = form_encounter.encounter AND \" .\n \"billing.pid = form_encounter.pid AND \" .\n \"billing.code_type LIKE ? AND \" .\n \"billing.activity = 1 \" .\n \"LEFT OUTER JOIN patient_data on patient_data.pid = form_encounter.pid \" .\n \"LEFT OUTER JOIN claims on claims.patient_id = form_encounter.pid and claims.encounter_id = form_encounter.encounter \" .\n \"LEFT OUTER JOIN insurance_data on insurance_data.pid = form_encounter.pid and insurance_data.type = 'primary' \" .\n \"WHERE 1=1 $query_part \" . \" $auth \" . \" $billstring \" .\n \"ORDER BY form_encounter.provider_id, form_encounter.encounter, form_encounter.pid, billing.code_type, billing.code ASC\";\n //echo $sql;\n $res = sqlStatement($sql, array($code_type));\n $all = [];\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $all[$iter] = $row;\n }\n\n return $all;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function checkPheumococcal(CqmPatient $patient, $beginDate, $endDate)\n {\n $options = array( Medication::OPTION_COUNT => 4 );\n $dobPlus42Days = date('Y-m-d 00:00:00', strtotime('+42 day', strtotime($patient->dob)));\n $dobPlus2Years = date('Y-m-d 00:00:00', strtotime('+2 year', strtotime($patient->dob)));\n if (\n Helper::checkMed(Medication::PNEUMOCOCCAL_VAC, $patient, $dobPlus42Days, $dobPlus2Years, $options) &&\n !Helper::checkAllergy(Allergy::PNEUM_VAC, $patient)\n ) {\n return true;\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function validate_image_file($uploaded_file, $file, $error, $index)\n {\n if ($this->imagetype($uploaded_file) !== $this->get_file_type($file->name)) {\n $file->error = $this->get_error_message('invalid_file_type');\n return false;\n }\n $max_width = @$this->options['max_width'];\n $max_height = @$this->options['max_height'];\n $min_width = @$this->options['min_width'];\n $min_height = @$this->options['min_height'];\n if ($max_width || $max_height || $min_width || $min_height) {\n list($img_width, $img_height) = $this->get_image_size($uploaded_file);\n if (!empty($img_width) && !empty($img_height)) {\n if ($max_width && $img_width > $max_width) {\n $file->error = $this->get_error_message('max_width');\n return false;\n }\n if ($max_height && $img_height > $max_height) {\n $file->error = $this->get_error_message('max_height');\n return false;\n }\n if ($min_width && $img_width < $min_width) {\n $file->error = $this->get_error_message('min_width');\n return false;\n }\n if ($min_height && $img_height < $min_height) {\n $file->error = $this->get_error_message('min_height');\n return false;\n }\n }\n }\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __set($name, $value)\n\t{\n\t\tthrow new CsrException('Kan geen velden zetten op ProfielToestemmingProxy');\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "protected function showPort(array $port, $dprefs, $so, $canedit, $agg, $rand, $with_ma = true)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $css_class = 'netport';\n if ((int) $port['ifstatus'] === 1) {\n if ((int) $port['trunk'] === 1) {\n $css_class .= ' trunk'; // port_trunk.png\n } else if ($this->isHubConnected($port['id'])) {\n $css_class .= ' hub'; //multiple_mac_addresses.png\n } else {\n $css_class .= ' cotrunk'; //connected_trunk.png\n }\n }\n\n $port_number = $port['logical_number'] ?? \"\";\n $whole_output = \"<tr class='$css_class' id='port_number_{$port_number}'>\";\n if ($canedit && $with_ma) {\n $whole_output .= \"<td>\" . Html::getMassiveActionCheckBox(__CLASS__, $port['id']) . \"</td>\";\n }\n foreach ($dprefs as $dpref) {\n $output = '';\n $td_class = '';\n foreach ($so as $option) {\n if ((int) $option['id'] === (int) $dpref) {\n switch ($dpref) {\n case 6:\n $output .= Dropdown::getYesNo($port['is_deleted']);\n break;\n case 1:\n if ($agg === true) {\n $td_class = 'aggregated';\n }\n\n $name = $port['name'];\n $url = NetworkPort::getFormURLWithID($port['id']);\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($name)) {\n $name = sprintf(__('%1$s (%2$s)'), $name, $port['id']);\n }\n\n $output .= '<a href=\"' . htmlescape($url) . '\">' . htmlescape($name) . '</a>';\n break;\n case 31:\n $speed = $port[$option['field']];\n //TRANS: list of unit (bps for bytes per second)\n $bytes = [__('bps'), __('Kbps'), __('Mbps'), __('Gbps'), __('Tbps')];\n foreach ($bytes as $val) {\n if ($speed >= 1000) {\n $speed /= 1000;\n } else {\n break;\n }\n }\n //TRANS: %1$s is a number maybe float or string and %2$s the unit\n $output .= htmlescape(sprintf(__('%1$s %2$s'), round($speed, 2), $val));\n break;\n case 32:\n $state_class = '';\n $state_title = __('Unknown');\n switch ($port[$option['field']]) {\n case 1: //up\n $state_class = 'green';\n $state_title = __('Up');\n break;\n case 2: //down\n $state_class = 'red';\n $state_title = __('Down');\n break;\n case 3: //testing\n $state_class = 'orange';\n $state_title = __('Test');\n break;\n }\n $output .= sprintf(\n '<i class=\"fas fa-circle %s\" title=\"%s\"></i> <span class=\"sr-only\">%s</span>',\n htmlescape($state_class),\n htmlescape($state_title),\n htmlescape($state_title)\n );\n break;\n case 34:\n $in = $port[$option['field']];\n $out = $port['ifoutbytes'];\n\n if (empty($in) && empty($out)) {\n break;\n }\n\n if (!empty($in)) {\n $in = Toolbox::getSize($in);\n } else {\n $in = ' - ';\n }\n\n if (!empty($out)) {\n $out = Toolbox::getSize($out);\n } else {\n $out = ' - ';\n }\n\n $output .= sprintf('%s / %s', $in, $out);\n break;\n case 35:\n $in = $port[$option['field']];\n $out = $port['ifouterrors'];\n\n if ($in == 0 && $out == 0) {\n break;\n }\n\n if ($in > 0 || $out > 0) {\n $td_class = 'orange';\n }\n\n $output .= sprintf('%s / %s', $in, $out);\n break;\n case 36:\n switch ($port[$option['field']]) {\n case 2: //half\n $td_class = 'orange';\n $output .= __s('Half');\n break;\n case 3: //full\n $output .= __s('Full');\n break;\n }\n break;\n case 38:\n $vlans = $DB->request([\n 'SELECT' => [\n NetworkPort_Vlan::getTable() . '.id',\n Vlan::getTable() . '.name',\n NetworkPort_Vlan::getTable() . '.tagged',\n Vlan::getTable() . '.tag',\n ],\n 'FROM' => NetworkPort_Vlan::getTable(),\n 'INNER JOIN' => [\n Vlan::getTable() => [\n 'ON' => [\n NetworkPort_Vlan::getTable() => 'vlans_id',\n Vlan::getTable() => 'id'\n ]\n ]\n ],\n 'WHERE' => ['networkports_id' => $port['id']]\n ]);\n\n if (count($vlans) > 10) {\n $output .= sprintf(\n __('%s linked VLANs'),\n count($vlans)\n );\n } else {\n foreach ($vlans as $row) {\n $output .= $row['name'];\n if (!empty($row['tag'])) {\n $output .= ' [' . $row['tag'] . ']';\n }\n $output .= ($row['tagged'] == 1 ? 'T' : 'U');\n if ($canedit) {\n $output .= '<a title=\"' . __s('Delete') . '\" href=\"' . NetworkPort::getFormURLWithID($row['id']) . '&amp;unassign_vlan=unassigned\">'\n . '<i class=\"fas fa-trash\"></i>'\n . '<span class=\"sr-only\">' . __s('Delete') . '</span>'\n . '</a>';\n }\n $output .= '<br/>';\n }\n }\n break;\n case 39:\n $netport = new NetworkPort();\n $netport->getFromDB($port['id']);\n\n $device1 = $netport->getItem();\n\n if ($device1 === false || !$device1->can($device1->getID(), READ)) {\n break;\n }\n\n $relations_id = 0;\n $oppositePort = NetworkPort_NetworkPort::getOpposite($netport, $relations_id);\n\n if ($oppositePort === false) {\n break;\n }\n\n $device2 = $oppositePort->getItem();\n if ($device2 !== false) {\n $output .= $this->getUnmanagedLink($device2, $oppositePort);\n\n //equipments connected to hubs\n if ($device2::class === Unmanaged::class && $device2->fields['hub'] == 1) {\n $houtput = \"<div class='hub'>\";\n\n $hub_ports = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $device2::class,\n 'items_id' => $device2->getID()\n ]\n ]);\n\n $list_ports = [];\n foreach ($hub_ports as $hrow) {\n $npo = $this->getContact($hrow['id']);\n $list_ports[] = $npo;\n }\n\n $hub_equipments = $DB->request([\n 'SELECT' => ['unm.*', 'netp.mac'],\n 'FROM' => Unmanaged::getTable() . ' AS unm',\n 'INNER JOIN' => [\n self::getTable() . ' AS netp' => [\n 'ON' => [\n 'netp' => 'items_id',\n 'unm' => 'id', [\n 'AND' => [\n 'netp.itemtype' => $device2::class\n ]\n ]\n ]\n ]\n ],\n 'WHERE' => [\n 'netp.itemtype' => $device2::class,\n 'netp.id' => $list_ports\n ]\n ]);\n\n if (count($hub_equipments) > 10) {\n $houtput .= '<div>' . sprintf(\n __s('%s equipments connected to the hub'),\n count($hub_equipments)\n ) . '</div>';\n } else {\n foreach ($hub_equipments as $hrow) {\n $hub = new Unmanaged();\n $hub->getFromDB($hrow['id']);\n $hub->fields['mac'] = $hrow['mac'];\n $houtput .= '<div>' . $this->getUnmanagedLink($hub, $hub) . '</div>';\n }\n }\n\n $houtput .= \"</div>\";\n $output .= $houtput;\n }\n }\n break;\n case 40:\n $co_class = '';\n switch ($port['ifstatus']) {\n case 1: //up\n $co_class = 'fa-link netport green';\n $title = __('Connected');\n break;\n case 2: //down\n $co_class = 'fa-unlink netport red';\n $title = __('Not connected');\n break;\n case 3: //testing\n $co_class = 'fa-link netport orange';\n $title = __('Testing');\n break;\n case 5: //dormant\n $co_class = 'fa-link netport grey';\n $title = __('Dormant');\n break;\n case 4: //unknown\n default:\n $co_class = 'fa-question-circle';\n $title = __('Unknown');\n break;\n }\n $output .= sprintf(\n '<i class=\"fas %s\" title=\"%s\"></i> <span class=\"sr-only\">%s</span>',\n htmlescape($co_class),\n htmlescape($title),\n htmlescape($title)\n );\n break;\n case 41:\n if ($port['ifstatus'] == 1) {\n $output .= sprintf(\"<i class='fa fa-circle green' title='%s'></i>\", __s('Connected'));\n } else if (!empty($port['lastup'])) {\n $time = strtotime(date('Y-m-d H:i:s')) - strtotime($port['lastup']);\n $output .= Html::timestampToString($time, false);\n }\n break;\n case 126: //IP address\n $ips_iterator = $this->getIpsForPort('NetworkPort', $port['id']);\n foreach ($ips_iterator as $iprow) {\n $output .= '<br/>' . $iprow['name'];\n }\n break;\n case 127:\n $names_iterator = $DB->request([\n 'FROM' => 'glpi_networknames',\n 'WHERE' => [\n 'itemtype' => 'NetworkPort',\n 'items_id' => $port['id']\n ]\n ]);\n foreach ($names_iterator as $namerow) {\n $netname = new NetworkName();\n $netname->getFromDB($namerow['id']);\n $output .= '<br/>' . $netname->getLink();\n }\n break;\n default:\n if (\n isset($option[\"linkfield\"])\n && isset($option['joinparams'])\n ) {\n $netport_table = $this->getTable();\n $already_link_tables = [];\n $join = Search::addLeftJoin(\n __CLASS__,\n $netport_table,\n $already_link_tables,\n $option[\"table\"],\n $option[\"linkfield\"],\n 0,\n 0,\n $option[\"joinparams\"],\n $option[\"field\"]\n );\n $iterator = $DB->request([\n 'FROM' => $netport_table,\n 'JOIN' => [new QueryExpression($join)],\n 'WHERE' => [\n \"$netport_table.id\" => $port['id']\n ]\n ]);\n foreach ($iterator as $row) {\n $output .= $row[$option['field']];\n }\n } else {\n $output .= $port[$option['field']];\n }\n break;\n }\n }\n }\n $whole_output .= \"<td class='$td_class'>\" . $output . \"</td>\";\n }\n $whole_output .= '</tr>';\n return $whole_output;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function parse($value) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($request) use ($credentials, $endpoints) {\n $this->setAuthBase($endpoints['token_uri']); // required\n $this->setRedirect($endpoints['redirect_uri']); // required\n $this->setAuthOptions([\n 'authorize_uri' => $endpoints['authorize_uri'] ?? null,\n 'discovery_url' => $endpoints['discovery_url'] ?? null,\n ]);\n $this->token_config = array_merge($this->token_config, $credentials);\n $this->initOAuthClient();\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function help_requested($modId, $currentActionStatus): mixed\n {\n // must call a script that implements a dialog to show help.\n // I can't find a way to override the Lamina's UI except using a dialog.\n if (file_exists(__DIR__ . '/show_help.php')) {\n include __DIR__ . '/show_help.php';\n }\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (Response $response, Document $user, Database $dbForProject) {\n\n\n $sessions = $user->getAttribute('sessions', []);\n $current = new Document();\n\n foreach ($sessions as $session) { /** @var Utopia\\Database\\Document $session */\n if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too\n $current = $session;\n }\n }\n\n if ($current->isEmpty()) {\n throw new Exception(Exception::USER_SESSION_NOT_FOUND);\n }\n\n $jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.\n\n $response\n ->setStatusCode(Response::STATUS_CODE_CREATED)\n ->dynamic(new Document(['jwt' => $jwt->encode([\n // 'uid' => 1,\n // 'aud' => 'http://site.com',\n // 'scopes' => ['user'],\n // 'iss' => 'http://api.mysite.com',\n 'userId' => $user->getId(),\n 'sessionId' => $current->getId(),\n ])]), Response::MODEL_JWT);\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function extendQueryBuilder(QueryBuilder $queryBuilder, $rulesData)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function render($options=array()) {\n $config = $this->field->getConfiguration();\n // process textarea attributes\n $attrs = array();\n foreach ($config as $k => $v) {\n switch ($k) {\n case 'rows':\n case 'cols':\n case 'length':\n case 'maxlength':\n if ($v && is_numeric($v))\n $attrs[$k] = '\"'.$v.'\"';;\n break;\n case 'context':\n $attrs['data-root-context'] = '\"'.$v.'\"';\n break;\n case 'class':\n // This might conflict with html attr below\n $attrs[$k] = '\"'.$v.'\"';\n break;\n case 'html':\n if ($v) {\n $class = array('richtext', 'no-bar');\n $class[] = @$config['size'] ?: 'small';\n $attrs['class'] = '\"'.implode(' ', $class).'\"';\n $this->value = Format::viewableImages($this->value);\n }\n break;\n }\n }\n // placeholder\n $attrs['placeholder'] = sprintf('\"%s\"',\n Format::htmlchars($this->field->getLocal('placeholder',\n $config['placeholder'])));\n ?>\n <span style=\"display:inline-block;width:100%\">\n <textarea <?php echo Format::array_implode('=', ' ',\n array_filter($attrs)); ?>\n id=\"<?php echo $this->id; ?>\"\n name=\"<?php echo $this->name; ?>\"><?php\n echo Format::htmlchars($this->value, ($config['html']));\n ?></textarea>\n </span>\n <?php\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function post_updateItem($history = true)\n {\n if (\n !isset($this->input['_no_check_plan'])\n && isset($this->fields[\"users_id\"])\n && isset($this->fields[\"begin\"])\n && !empty($this->fields[\"begin\"])\n ) {\n Planning::checkAlreadyPlanned(\n $this->fields[\"users_id\"],\n $this->fields[\"begin\"],\n $this->fields[\"end\"],\n [\n $this->getType() => [$this->fields['id']]\n ]\n );\n }\n if (in_array(\"begin\", $this->updates)) {\n PlanningRecall::managePlanningUpdates(\n $this->getType(),\n $this->getID(),\n $this->fields[\"begin\"]\n );\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function validateBinaryOperand($cellID, &$operand, &$stack)\n {\n if (is_array($operand)) {\n if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {\n do {\n $operand = array_pop($operand);\n } while (is_array($operand));\n }\n }\n // Numbers, matrices and booleans can pass straight through, as they're already valid\n if (is_string($operand)) {\n // We only need special validations for the operand if it is a string\n // Start by stripping off the quotation marks we use to identify true excel string values internally\n if ($operand > '' && $operand{0} == '\"') {\n $operand = self::unwrapResult($operand);\n }\n // If the string is a numeric value, we treat it as a numeric, so no further testing\n if (!is_numeric($operand)) {\n // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations\n if ($operand > '' && $operand{0} == '#') {\n $stack->push('Value', $operand);\n $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand));\n return false;\n } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) {\n // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations\n $stack->push('Value', '#VALUE!');\n $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!'));\n return false;\n }\n }\n }\n\n // return a true if the value of the operand is one that we can use in normal binary operations\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "#[Deprecated(replacement: '%class%->pconnect(%parametersList%)')]\n public function popen(\n $host,\n $port = 6379,\n $timeout = 0.0,\n $persistentId = '',\n $retryInterval = 0,\n $readTimeout = 0.0\n ) {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function aws_crt_log_to_stream(object $stream): void {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function function1(int $value)\n{\n}", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "static function __create($ht, &$error=false) {\n global $ost;\n\n $ht['properties'] = JsonDataEncoder::encode($ht['properties']);\n if (($status = TicketStatus::create($ht)))\n $status->save(true);\n\n return $status;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function ($name, $value, $status) use (&$setProps): void {\n\t\t\t\t$setProps[$name] = $value;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function value_to_mega_value(&$value, $key) {\n\t $value = $value / 1000000.0;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function getZonePopover(bool $editor, array $zone): string\n {\n return '';\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function _remove_type_callback(&$mime, $ext_type, $type_info)\n {\n // temporarily we'll put match to false\n $matched = false;\n list ( $ext, $type ) = $ext_type;\n if ($type_info ['wildcard']) {\n if (substr($type, 0, strpos($type, '/')) == $type_info ['type']) {\n $matched = true;\n }\n } elseif ($type == $type_info ['type']) {\n $matched = true;\n }\n\n if ($matched) {\n $this->remove_extension($ext);\n $type_info ['last_match'] = true;\n } elseif ($type_info ['last_match']) {\n // we do not need to continue if the previous type matched, but this type didn't.\n // because all types are sorted in alphabetical order, we can be sure there will be\n // no further successful matches.\n return false;\n }\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getData(Model\\Asset $asset, array $fields = null, string $requestedLanguage = null, array $params = []): array\n {\n $data = self::gridElementData($asset);\n $loader = null;\n\n if (!empty($fields)) {\n $data = [\n 'id' => $asset->getId(),\n 'id~system' => $asset->getId(),\n 'type~system' => $asset->getType(),\n 'fullpath~system' => $asset->getRealFullPath(),\n 'filename~system' => $asset->getKey(),\n 'creationDate~system' => $asset->getCreationDate(),\n 'modificationDate~system' => $asset->getModificationDate(),\n 'idPath~system' => Service::getIdPath($asset),\n ];\n\n $requestedLanguage = str_replace('default', '', $requestedLanguage);\n\n foreach ($fields as $field) {\n $fieldDef = explode('~', $field);\n if (isset($fieldDef[1]) && $fieldDef[1] === 'system') {\n if ($fieldDef[0] === 'preview') {\n $data[$field] = self::getPreviewThumbnail($asset, ['treepreview' => true, 'width' => 108, 'height' => 70, 'frame' => true]);\n } elseif ($fieldDef[0] === 'size') {\n $size = $asset->getFileSize();\n $data[$field] = formatBytes($size);\n }\n } else {\n if (isset($fieldDef[1])) {\n $language = ($fieldDef[1] === 'none' ? '' : $fieldDef[1]);\n $rawMetaData = $asset->getMetadata($fieldDef[0], $language, true, true);\n } else {\n $rawMetaData = $asset->getMetadata($field, $requestedLanguage, true, true);\n }\n\n $metaData = $rawMetaData['data'] ?? null;\n\n if ($rawMetaData) {\n $type = $rawMetaData['type'];\n if (!$loader) {\n $loader = \\Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data');\n }\n\n $metaData = $rawMetaData['data'] ?? null;\n\n try {\n /** @var Data $instance */\n $instance = $loader->build($type);\n $metaData = $instance->getDataForListfolderGrid($rawMetaData['data'] ?? null, $rawMetaData);\n } catch (UnsupportedException $e) {\n }\n }\n\n $data[$field] = $metaData;\n }\n }\n }\n\n return $data;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function ($dn, $attr) {\n\t\t\t\tif ($attr === 'primaryGroupToken') {\n\t\t\t\t\treturn [1337];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function delete(User $user, Port $port): bool\n {\n return $user->hasGlobalAdmin();\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new \\Application\\Controller\\SendtoController($container->get(\\Application\\Model\\ApplicationTable::class), $container->get(\\Application\\Model\\SendtoTable::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function convertGotenberg(string $url, string $outputFile, ?string $sessionName = null, ?string $sessionId = null, string $windowSize = '1280,1024'): bool\n {\n try {\n /** @var GotenbergAPI|object $request */\n $request = GotenbergAPI::chromium(Config::getSystemConfiguration('gotenberg')['base_url']);\n if (method_exists($request, 'screenshot')) {\n $sizes = explode(',', $windowSize);\n $urlResponse = $request->screenshot()\n ->width((int) $sizes[0])\n ->height((int) $sizes[1])\n ->png()\n ->url($url);\n\n $file = GotenbergAPI::save($urlResponse, PIMCORE_SYSTEM_TEMP_DIRECTORY);\n\n return rename(PIMCORE_SYSTEM_TEMP_DIRECTORY . '/' . $file, $outputFile);\n }\n\n } catch (Exception $e) {\n // nothing to do\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function imprimerFichesPresencesScolaire($lesClasses,$lesEleves,$num)\n\t{\n\t\trequire('fpdf/fpdf.php');\n\t\t$pdf = new FPDF();\n\t\t$pdf->SetFillColor(192,192,192);\n\t\tforeach($lesClasses as $laClasse) {\n\n\t\t\t// Ne pas afficher BTS et FAC\n\t\t\tif($laClasse['ID'] < 57) {\n\n\n\t\t\t\t$pdf->AddPage();\n\t\t\t\t$pdf->SetFont('Arial', '', 18);\n\t\t\t\t//$pdf->Image('https://association-ore.fr/extranet/images/logo.png',0,5,50,0,'PNG');\n\t\t\t\t$pdf->Cell(0, 10, utf8_decode('Fiche de pr\u00e9sences'),0,1,'C');\n\t\t\t\t$pdf->Cell(0, 10, utf8_decode('soutien scolaire'),0,1,'C');\n\t\t\t\t$pdf->SetFont('Arial', 'B', 11);\n\t\t\t\t$pdf->Ln();\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode('Classe : '),0,0,'L');\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode($laClasse['NOM']),0,1,'L');\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode('Date : '),0,0,'L');\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode('________________________________'),0,1,'L');\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode('Intervenant : '),0,0,'L');\n\t\t\t\t$pdf->Cell(50, 10, utf8_decode('________________________________'),0,1,'L');\n\n\n\n\t\t\t\t$pdf->Cell(20, 8, utf8_decode('Pr\u00e9sent ?'),0,0,'C',true);\n\t\t\t\t$pdf->Cell(60, 8, utf8_decode('Nom'),0,0,'C',true);\n\t\t\t\t$pdf->Cell(22, 8, utf8_decode('Mail Parent'),0,0,'C',true);\n\t\t\t\t$pdf->Cell(23, 8, utf8_decode('R\u00e8glement'),0,0,'C',true);\n\t\t\t\t$pdf->Cell(24, 8, utf8_decode('Photo'),0,0,'C',true);\n\n\t\t\t\t$pdf->Ln();\n\n\t\t\t\t$pdf->SetFont('Arial', '', 11);\n\n\t\t\t\t/* liste des \u00e9l\u00e8ves */\n\n\t\t\t\tforeach($lesEleves as $lEleve) {\n\n\n\t\t\t\t\tif($lEleve['ID_CLASSE'] == $laClasse['ID']) {\n\n\t\t\t\t\t\t// case \u00e0 cocher pr\u00e9sent\n\t\t\t\t\t\t$pdf->Cell(20, 8, ' ',1,0,'L');\n\t\t\t\t\t\t// nom pr\u00e9nom\n\t\t\t\t\t\t$pdf->Cell(70, 8, utf8_decode($lEleve['NOM'] . ' ' . $lEleve['PRENOM']),0,0,'L');\n\n\n\t\t\t\t\t\tif( $lEleve['EMAIL_DES_PARENTS'] == null){\n\t\t\t\t\t\t\t$text = \"X\";\n\t\t\t\t\t\t$pdf->Cell(20, 8, utf8_decode($text) ,0,0,'L');\n\t\t\t\t\t\t}else if( $lEleve['EMAIL_DES_PARENTS'] != null){\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif( $Ligne == null){\n\t\t\t\t\t\t\t$text = \"X\";\n\t\t\t\t\t\t$pdf->Cell(20, 8, utf8_decode($text) ,0,0,'L');\n\t\t\t\t\t\t}else if( $Ligne != null){\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif( $lEleve['PHOTO'] == null){\n\t\t\t\t\t\t\t$text = \"X\";\n\t\t\t\t\t\t$pdf->Cell(20, 8, utf8_decode($text) ,0,0,'L');\n\t\t\t\t\t\t}else if( $lEleve['PHOTO'] != null){\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t\t\t$pdf->Ln();\n\n\t\t\t\t\t\t$i++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t// Lignes vides\n\t\t\t\tfor($x = 0; $x < 6; $x++) {\n\t\t\t\t\t// case \u00e0 cocher pr\u00e9sent\n\t\t\t\t\t$pdf->Cell(20, 8, ' ',1,0,'L');\n\t\t\t\t\t// nom pr\u00e9nom\n\t\t\t\t\t$pdf->Cell(70, 8, utf8_decode('__________________________'),0,0,'L');\n\t\t\t\t\t// espace pour observations\n\t\t\t\t\t$pdf->Cell(70, 8, '______________________',0,0,'L');\n\n\t\t\t\t\t$pdf->Ln();\n\t\t\t\t}\n\n\n\t\t\t\tif($i == 0) {\n\t\t\t\t\t$pdf->Cell(50, 10, utf8_decode('Aucun \u00e9l\u00e8ve inscrit dans cette classe.'),0,0,'L');\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t$pdf->Output();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function expire($key, $ttl) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getEvaluateReportsInPdf($shipmentId, $sLimit, $sOffset) {}", "smellKey": "S1172", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public static function createTimeZoneIDEnumeration($zoneType, $region = null, $rawOffset = 0) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function create($vars=false, &$errors=array()) {\n $event = new static($vars);\n return $event;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function save(DataObject\\Concrete $object, array $params = []): array\n {\n return $this->delete($object, true);\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype = null)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '146',\n 'table' => static::getTable(),\n 'field' => '_virtual',\n 'name' => self::getTypeName(Session::getPluralNumber()),\n 'datatype' => 'specific',\n 'additionalfields' => [\n 'id',\n 'name',\n 'url',\n 'open_window',\n 'icon',\n ],\n 'forcegroupby' => true,\n 'nosearch' => true,\n 'nosort' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n ],\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (\n\t\t\t\t\\Psr\\Http\\Message\\RequestInterface $request,\n\t\t\t\t\\Psr\\Http\\Message\\ResponseInterface $response,\n\t\t\t\t\\Psr\\Http\\Message\\UriInterface $uri\n\t\t\t) use ($options) {\n\t\t\t\t$this->preventLocalAddress($uri->__toString(), $options);\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function validateTokens(RequestInterface $request, &$conditions) {\n\t\tforeach ($conditions as &$fileCondition) {\n\t\t\tif (isset($fileCondition['tokens'])) {\n\t\t\t\tforeach ($fileCondition['tokens'] as &$token) {\n\t\t\t\t\tif (isset($token['token'])) {\n\t\t\t\t\t\tif (str_starts_with($token['token'], 'opaquelocktoken:')) {\n\t\t\t\t\t\t\t$token['validToken'] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function handleRequest(Request $request)\n\t{\n\t\tif ($this->isPosted()) {\n\t\t\tforeach ($this->fields as $field) {\n\t\t\t\tif ($field instanceof InputField) {\n\t\t\t\t\t$this->loadProperty($field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public static function showElig($res, $X12info, $segTer, $compEleSep)\n {\n\n $i = 0;\n echo \"\t<div id='report_results'>\n <table class='table table-striped table-hover'>\n <thead>\n <th>\" . text(xl('Facility Name')) . \"</th>\n <th>\" . text(xl('Facility NPI')) . \"</th>\n <th>\" . text(xl('Insurance Comp')) . \"</th>\n <th>\" . text(xl('Appt Date')) . \"</th>\n <th>\" . text(xl('Policy No')) . \"</th>\n <th>\" . text(xl('Patient Name')) . \"</th>\n <th>\" . text(xl('DOB')) . \"</th>\n <th>\" . text(xl('Gender')) . \"</th>\n <th>\" . text(xl('SSN')) . \"</th>\n <th>\t&nbsp;\t\t\t </th>\n </thead>\n <tbody>\";\n\n foreach ($res as $row) {\n $i = $i + 1;\n // what the heck is below for... looks abandoned.\n $elig = array();\n $elig[0] = $row['facility_name']; // Inquiring Provider Name calendadr\n $elig[1] = $row['facility_npi']; // Inquiring Provider NPI\n $elig[2] = $row['payer_name']; // Payer Name our insurance co name\n $elig[3] = $row['policy_number']; // Subscriber ID\n $elig[4] = $row['subscriber_lname']; // Subscriber Last Name\n $elig[5] = $row['subscriber_fname']; // Subscriber First Name\n $elig[6] = $row['subscriber_mname']; // Subscriber Middle Initial\n $elig[7] = $row['subscriber_dob']; // Subscriber Date of Birth\n $elig[8] = substr($row['subscriber_sex'], 0, 1); // Subscriber Sex\n $elig[9] = $row['subscriber_ss']; // Subscriber SSN\n $elig[10] = self::translateRelationship($row['subscriber_relationship']); // Pt Relationship to insured\n $elig[11] = $row['lname']; // Dependent Last Name\n $elig[12] = $row['fname']; // Dependent First Name\n $elig[13] = $row['mname']; // Dependent Middle Initial\n $elig[14] = $row['dob']; // Dependent Date of Birth\n $elig[15] = substr($row['sex'], 0, 1); // Dependent Sex\n $elig[16] = $row['pc_eventDate']; // Date of service\n $elig[17] = \"30\"; // Service Type\n $elig[18] = $row['pubpid']; // Patient Account Number pubpid\n\n echo \"\t<tr id='PR\" . $i . \"_\" . text($row['policy_number']) . \"'>\n\t\t\t\t<td class ='detail'>\" . text($row['facility_name']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['facility_npi']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['payer_name']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text(date(\"m/d/Y\", strtotime($row['pc_eventDate']))) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['policy_number']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['subscriber_lname'] . \" \" . $row['subscriber_fname']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['subscriber_dob']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['subscriber_sex']) . \"</td>\n\t\t\t\t<td class ='detail'>\" . text($row['subscriber_ss']) . \"</td>\n\t\t\t\t<td class ='detail'>\n\t\t\t\t<img src=\\\"\" . $GLOBALS['images_static_relative'] . \"/deleteBtn.png\\\" title=\" . text(xl('Delete Row')) . \" style='cursor:pointer;cursor:hand;' onclick='deletetherow(\\\"\" . $i . \"_\" . text($row['policy_number']) . \"\\\")'>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\";\n unset($elig); // see ..\n }\n\n if ($i == 0) {\n echo \"\t<tr>\n\t\t\t\t<td class='norecord' colspan=9>\n\t\t\t\t\t<div style='padding:5px;font-family:arial;font-size:13px;text-align:center;'>\" . text(xl('No records found')) . \"</div>\n\t\t\t\t</td>\n\t\t\t</tr>\t\";\n }\n echo \"\t</tbody>\n\t\t\t</table>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function processRequest(array $data = [])\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "Tmlrb2xhb3M_hackazon", "language": "php"} {"function": "public function setAttribute($attr, $value) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function checkSecurity(string $action, Request $request)\n {\n if ($this->shouldCheckCSRFTokenForRequest($action)) {\n $CSRFToken = $this->getCSRFToken();\n if (!CsrfUtils::verifyCsrfToken($CSRFToken, self::CSRF_TOKEN_NAME)) {\n throw new CsrfInvalidException(xlt('Authentication Error'));\n }\n }\n\n if (!AclMain::aclCheckCore('admin', 'super')) {\n throw new AccessDeniedException('admin', 'super');\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($value, $key) {\n return Str::contains($key, 'ef-');\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function vitals_report($pid, $encounter, $cols, $id, $print = true)\n{\n $count = 0;\n $data = formFetch(\"form_vitals\", $id);\n $patient_data = getPatientData($GLOBALS['pid']);\n $patient_age = getPatientAge($patient_data['DOB']);\n $is_pediatric_patient = ($patient_age <= 20 || (preg_match('/month/', $patient_age)));\n\n $vitals = \"\";\n if ($data) {\n $vitals .= \"<table><tr>\";\n\n foreach ($data as $key => $value) {\n if (\n $key == \"uuid\" ||\n $key == \"id\" || $key == \"pid\" ||\n $key == \"user\" || $key == \"groupname\" ||\n $key == \"authorized\" || $key == \"activity\" ||\n $key == \"date\" || $value == \"\" ||\n $value == \"0000-00-00 00:00:00\" || $value == \"0.0\"\n ) {\n // skip certain data\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n if ($key == 'inhaled_oxygen_concentration') {\n $value .= \" %\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n\n //modified by BM 06-2009 for required translation\n if ($key == \"Temp Method\" || $key == \"BMI Status\") {\n if ($key == \"BMI Status\") {\n if ($is_pediatric_patient) {\n $value = \"See Growth-Chart\";\n }\n }\n\n $vitals .= '<td><div class=\"bold\" style=\"display:inline-block\">' . xlt($key) . ': </div></td><td><div class=\"text\" style=\"display:inline-block\">' . xlt($value) . \"</div></td>\";\n } elseif ($key == \"Bps\") {\n $bps = $value;\n if (!empty($bpd)) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt('Blood Pressure') . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($bps) . \"/\" . text($bpd) . \"</div></td>\";\n } else {\n continue;\n }\n } elseif ($key == \"Bpd\") {\n $bpd = $value;\n if ($bps) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt('Blood Pressure') . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($bps) . \"/\" . text($bpd) . \"</div></td>\";\n } else {\n continue;\n }\n } elseif ($key == \"Weight\") {\n $value = floatval($value);\n $convValue = number_format($value * 0.45359237, 2);\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\";\n // show appropriate units\n $mode = $GLOBALS['us_weight_format'];\n if ($GLOBALS['units_of_measurement'] == 2) {\n $vitals .= text($convValue) . \" \" . xlt('kg') . \" (\" . text(US_weight($value, $mode)) . \")\";\n } elseif ($GLOBALS['units_of_measurement'] == 3) {\n $vitals .= text(US_weight($value, $mode));\n } elseif ($GLOBALS['units_of_measurement'] == 4) {\n $vitals .= text($convValue) . \" \" . xlt('kg');\n } else { // = 1 or not set\n $vitals .= text(US_weight($value, $mode)) . \" (\" . text($convValue) . \" \" . xlt('kg') . \")\";\n }\n\n $vitals .= \"</div></td>\";\n } elseif ($key == \"Height\" || $key == \"Waist Circ\" || $key == \"Head Circ\") {\n $value = floatval($value);\n $convValue = number_format(round($value * 2.54, 1), 2);\n // show appropriate units\n if ($GLOBALS['units_of_measurement'] == 2) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($convValue) . \" \" . xlt('cm') . \" (\" . text($value) . \" \" . xlt('in') . \")</div></td>\";\n } elseif ($GLOBALS['units_of_measurement'] == 3) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($value) . \" \" . xlt('in') . \"</div></td>\";\n } elseif ($GLOBALS['units_of_measurement'] == 4) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($convValue) . \" \" . xlt('cm') . \"</div></td>\";\n } else { // = 1 or not set\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($value) . \" \" . xlt('in') . \" (\" . text($convValue) . \" \" . xlt('cm') . \")</div></td>\";\n }\n } elseif ($key == \"Temperature\") {\n $value = floatval($value);\n $convValue = number_format((($value - 32) * 0.5556), 2);\n // show appropriate units\n if ($GLOBALS['units_of_measurement'] == 2) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($convValue) . \" \" . xlt('C') . \" (\" . text($value) . \" \" . xlt('F') . \")</div></td>\";\n } elseif ($GLOBALS['units_of_measurement'] == 3) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($value) . \" \" . xlt('F') . \"</div></td>\";\n } elseif ($GLOBALS['units_of_measurement'] == 4) {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($convValue) . \" \" . xlt('C') . \"</div></td>\";\n } else { // = 1 or not set\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($value) . \" \" . xlt('F') . \" (\" . text($convValue) . \" \" . xlt('C') . \")</div></td>\";\n }\n } elseif ($key == \"Pulse\" || $key == \"Respiration\" || $key == \"Oxygen Saturation\" || $key == \"BMI\" || $key == \"Oxygen Flow Rate\") {\n $value = floatval($value);\n $c_value = number_format($value, 0);\n if ($key == \"Oxygen Saturation\") {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('%') . \"</div></td>\";\n } elseif ($key == \"Oxygen Flow Rate\") {\n $c_value = number_format($value, 2);\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('l/min') . \"</div></td>\";\n } elseif ($key == \"BMI\") {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('kg/m^2') . \"</div></td>\";\n } else { //pulse and respirations\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('per min') . \"</div></td>\";\n }\n } elseif ($key == \"Ped Weight Height\" || $key == 'Ped Bmi' || $key == 'Ped Head Circ') {\n $value = floatval($value);\n if ($is_pediatric_patient) {\n $c_value = number_format($value, 0);\n if ($key == \"Ped Weight Height\") {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt(\"Pediatric Height Weight Percentile\") . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('%') . \"</div></td>\";\n } elseif ($key == \"Ped Bmi\") {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt(\"Pediatric BMI Percentile\") . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('%') . \"</div></td>\";\n } elseif ($key == \"Ped Head Circ\") {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt(\"Pediatric Head Circumference Percentile\") . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($c_value) . \" \" . xlt('%') . \"</div></td>\";\n }\n }\n } else {\n $vitals .= \"<td><div class='font-weight-bold d-inline-block'>\" . xlt($key) . \": </div></td><td><div class='text' style='display:inline-block'>\" . text($value) . \"</div></td>\";\n }\n\n $count++;\n\n if ($count == $cols) {\n $count = 0;\n $vitals .= \"</tr><tr>\\n\";\n }\n }\n\n $vitals .= \"</tr></table>\";\n }\n\n if ($print) {\n echo $vitals ;\n } else {\n return $vitals;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "static function ($k, $v) {\n return str_starts_with($v, '_');\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (Concrete $object, Data $fieldDefinition, $property, $currentValue) {\n if ($fieldDefinition instanceof Data\\CustomRecyclingMarshalInterface) {\n return $fieldDefinition->marshalRecycleData($object, $currentValue);\n }\n\n return $currentValue;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function save($id, $data, $ttl = 60, $raw = FALSE)\n\t{\n\t\treturn apc_store($id, $data, (int) $ttl);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function painmap_report($pid, $encounter, $cols, $id)\n{\n /* Create a form object. */\n $c = new C_FormPainMap();\n /* Render the form. */\n echo $c->report_action($id);\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getDataToSend(NotificationTarget $target, $tid, $to, array $user_infos, array $options)\n {\n\n $language = $user_infos['language'];\n $user_name = $user_infos['username'];\n\n $sender = $target->getSender();\n $replyto = $target->getReplyTo();\n\n $mailing_options['to'] = $to;\n $mailing_options['toname'] = $user_name;\n $mailing_options['from'] = $sender['email'];\n $mailing_options['fromname'] = $sender['name'];\n $mailing_options['replyto'] = $replyto['email'];\n $mailing_options['replytoname'] = $replyto['name'];\n $mailing_options['messageid'] = $target->getMessageID();\n\n $template_data = $this->templates_by_languages[$tid];\n $mailing_options['subject'] = $template_data['subject'];\n $mailing_options['content_html'] = $template_data['content_html'];\n $mailing_options['content_text'] = $template_data['content_text'];\n $mailing_options['items_id'] = method_exists($target->obj, \"getField\")\n ? $target->obj->getField('id')\n : 0;\n if (property_exists($target->obj, 'documents') && isset($target->obj->documents)) {\n $mailing_options['documents'] = $target->obj->documents;\n }\n\n return $mailing_options;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($x, $y, $z) {\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function ($tagId) {\n\t\t\t\tthrow new TagNotFoundException();\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function createTimeZone($zoneId) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($uuid, HttpRestRequest $request) {\n RestConfig::authorization_check(\"admin\", \"users\");\n $data = (array) (json_decode(file_get_contents(\"php://input\"), true));\n $return = (new FhirPractitionerRestController())->patch($uuid, $data);\n RestConfig::apiLog($return, $data);\n return $return;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "static function FilePost($url, $data = \"\", $verify_cert = false, $timeout = 30)\n {\n $qs = HttpRequest::ArrayToQueryString($data);\n $url = $url . ($qs ? \"?\" . $qs : \"\");\n\n $show_headers = false;\n $url = parse_url($url);\n\n if (! isset($url ['port'])) {\n if ($url ['scheme'] == 'http') {\n $url ['port'] = 80;\n } elseif ($url ['scheme'] == 'https') {\n $url ['port'] = 443;\n }\n }\n\n $url ['query'] = isset($url ['query']) ? $url ['query'] : '';\n\n $url ['protocol'] = $url ['scheme'] . '://';\n $eol = \"\\r\\n\";\n\n $headers = \"POST \" . $url ['protocol'] . $url ['host'] . $url ['path'] . \" HTTP/1.0\" . $eol . \"Host: \" . $url ['host'] . $eol . \"Referer: \" . $url ['protocol'] . $url ['host'] . $url ['path'] . $eol . \"Content-Type: application/x-www-form-urlencoded\" . $eol . \"Content-Length: \" . strlen($url ['query']) . $eol . $eol . $url ['query'];\n $fp = fsockopen($url ['host'], $url ['port'], $errno, $errstr, 30);\n if ($fp) {\n fputs($fp, $headers);\n $result = '';\n while (! feof($fp)) {\n $result .= fgets($fp, 128);\n }\n\n fclose($fp);\n if (! $show_headers) {\n // removes headers\n $match = preg_split(\"/\\r\\n\\r\\n/s\", $result, 2);\n $result = $match [1];\n }\n\n return $result;\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function eagerlyWhere(array $where, $key, $relation, $subRelation = '', $closure = null)\n {\n // \u9884\u8f7d\u5165\u5173\u8054\u67e5\u8be2 \u652f\u6301\u5d4c\u5957\u9884\u8f7d\u5165\n $throughList = $this->through->where($where)->select();\n $keys = $throughList->column($this->throughPk, $this->throughPk);\n\n if ($closure instanceof Closure) {\n $closure($this->query);\n }\n\n $list = $this->query->where($this->throughKey, 'in', $keys)->select();\n\n // \u7ec4\u88c5\u6a21\u578b\u6570\u636e\n $data = [];\n $keys = $throughList->column($this->foreignKey, $this->throughPk);\n\n foreach ($list as $set) {\n $data[$keys[$set->{$this->throughKey}]][] = $set;\n }\n\n return $data;\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public function check_defgroups($params=null){\n\n $resStatus = true;\n $resMsg = '';\n\n $mysqli = $this->mysqli;\n\n $div_valid = '<div><h3 class=\"res-valid\">';\n $div_found = '<div><h3 class=\"error\">Found ';\n\n // record types =========================\n $cnt = intval(mysql__select_value($mysqli, 'select count(rty_ID) from defRecTypes left join defRecTypeGroups on rty_RecTypeGroupID=rtg_ID WHERE rtg_ID is null'));\n if($cnt>0){\n\n $resStatus = false;\n $resMsg .= $div_found.$cnt.' record types that are not belong any group</h3></div>';\n\n //find trash group\n $trash_id = mysql__select_value($mysqli, 'select rtg_ID FROM defRecTypeGroups WHERE rtg_Name=\"Trash\"');\n if($trash_id>0){\n\n $mysqli->query('update defRecTypes left join defRecTypeGroups on rty_RecTypeGroupID=rtg_ID set rty_RecTypeGroupID='.intval($trash_id).' WHERE rtg_ID is null');\n\n $cnt2 = $mysqli->affected_rows;\n\n $resMsg .= $div_valid.$cnt2.' record types have been placed to \"Trash\" group</h3></div>';\n }else{\n $resMsg .= '<div><h3 class=\"error\">Cannot find record type \"Trash\" group. </h3></div>';\n }\n }else{\n $resMsg .= '<div><h3 class=\"res-valid\">OK: All Record Types belong to existing groups</h3></div>';\n }\n\n // fields types =========================\n $cnt = intval(mysql__select_value($mysqli, 'select count(dty_ID) from defDetailTypes left join defDetailTypeGroups on dty_DetailTypeGroupID=dtg_ID WHERE dtg_ID is null'));\n if($cnt>0){\n\n $resStatus = false;\n $resMsg .= $div_found.$cnt.' base field types that are not belong any group</h3></div>';\n\n //find trash group\n $trash_id = mysql__select_value($mysqli, 'select dtg_ID FROM defDetailTypeGroups WHERE dtg_Name=\"Trash\"');\n if($trash_id>0){\n\n $mysqli->query('update defDetailTypes left join defDetailTypeGroups on dty_DetailTypeGroupID=dtg_ID set dty_DetailTypeGroupID='.intval($trash_id).' WHERE dtg_ID is null');\n\n $cnt2 = $mysqli->affected_rows;\n\n $resMsg .= $div_valid.$cnt2.' field types have been placed to \"Trash\" group</h3></div>';\n }else{\n $resMsg .= '<div><h3 class=\"error\">Cannot find field type \"Trash\" group.</h3></div>';\n }\n }else{\n $resMsg .= '<div><h3 class=\"res-valid\">OK: All Base Field Types belong to existing groups</h3></div>';\n }\n\n // vocabularies =========================\n $cnt = intval(mysql__select_value($mysqli, 'select count(trm_ID) from defTerms left join defVocabularyGroups on trm_VocabularyGroupID=vcg_ID WHERE trm_ParentTermID is null and vcg_ID is null'));\n if($cnt>0){\n\n $resStatus = false;\n $resMsg .= $div_found.$cnt.' vocabularies that are not belong any group</h3></div>';\n\n //find trash group\n $trash_id = mysql__select_value($mysqli, 'select vcg_ID FROM defVocabularyGroups WHERE vcg_Name=\"Trash\"');\n if($trash_id>0){\n $mysqli->query('update defTerms left join defVocabularyGroups on trm_VocabularyGroupID=vcg_ID set trm_VocabularyGroupID='.intval($trash_id).' WHERE trm_ParentTermID is null and vcg_ID is null');\n\n $cnt2 = $mysqli->affected_rows;\n\n $resMsg .= $div_valid.$cnt2.' vocabularies have been placed to \"Trash\" group</h3></div>';\n }else{\n $resMsg .= '<div><h3 class=\"error\">Cannot vocabularies \"Trash\" group.</h3></div>';\n }\n }else{\n $resMsg .= '<div><h3 class=\"res-valid\">OK: All Vocabularies belong to existing groups</h3></div>';\n }\n\n return array('status'=>$resStatus, 'message'=>$resMsg);\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function intlcal_create_instance($timeZone = null, $locale = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ereqForm($pid, $encounter, $form_id, $reqStr = null, $doDoc = true)\n{\n\n $styleSheet = <<<STYLES\nimg{border:none;outline:none;}.h3{margin:0px;padding:0px;font-size:18px;}h4{font-size:15px;}.span{display:block;text-align:center;}.cor-edi-main-wrap{margin:50px auto;max-width:850px;}.cor-edi-main-wrap table{width:100%;border-spacing:0px;font-size:11.5px;font-family:sans-serif;}.cor-edi-main-wrap table td{padding:1px 2px;vertical-align:top;}.cor-edi-main-table{border:0px;border-left:1px solid #000;border-top:1px solid #000;font-size:11.5px;}table.dotted-table{border:0px;border-left:1px dotted #000;border-top:1px dotted #000;font-size:9.5px;}.cor-edi-main-table tbody tr td, .cor-edi-main-table tr td{border:0px;border-right:1px solid #000;border-bottom:1px solid #000;}table.dotted-table tbody tr td, table.dotted-table tr td{border:0px;border-right:1px dotted #000;border-bottom:1px dotted #000;}.cor-edi-main-table tbody tr td table tr td, .cor-edi-main-table tr td table.no-border tr td{border:0px;border-right:0px;border-bottom:0px;padding:1px;padding-top:0px;}table.with-border tbody tr td, .cor-edi-main-table tbody tr td table.with-border tr td, .cor-edi-main-table tr td{border:0px;border-right:1px solid #000;border-bottom:1px solid #000;}table.dotted-table tbody tr td, table.dotted-table tbody tr td table tr td, table.dotted-table tr td{font-size:9.5px;}.no-border{border:0px;}.cor-edi-main-table.no-border{border:0px;}.cor-edi-main-table tbody tr td.no-border{border:0px;}.cor-edi-main-table tbody tr td table.no-border tr td{border:0px;}div.sig-underline{padding-top:75px;border-bottom:1px solid #000;width:250px;}.width50{width:50%;}.width25{width:25%;}.width30{width:30%;}.width75{width:75%;}div.height75{height:75px;}.cor-edi-main-table tr td table tr td.imaging-label{width:175px;height:150px;border-top:1px dashed #000;border-left:1px dashed #000;border-right:1px dashed #000;border-bottom:1px dashed #000;padding:10px;color:#303030;text-align:center;font-weight:bold;}.cor-edi-main-table tbody tr td table tr td.text-r{text-align:right;}.cor-edi-main-table tr td table tr td.bar-code-label {border:0px;outline:none;width:4.0in;height:1.0in;}\nSTYLES;\n /* To use barcode you need to install TCPDF and comment appropriate lines\n $barcodeobj = new TCPDF2DBarcode($reqStr, 'PDF417,4,4');\n $lc_2d = $barcodeobj->getBarcodePngData(4, 4, array(0,0,0));\n $lc_2d = \"data:image/png;base64,\" . base64_encode($lc_2d);*/\n try {\n $mpdf = new mPDF();\n $pdfContent = '<!DOCTYPE html>';\n $pdfContent .= '<html lang=\"en\">';\n $pdfContent .= '<head></head>';\n $pdfContent .= '<body>';\n $pdfContent .= '<div class=\"cor-edi-main-wrap\">';\n $pdfContent .= '<table class=\"cor-edi-main-table no-border\" style=\"margin-top:0px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"border:0px;width:35%;padding-left:20px;\"><table style=\"width:190px;\"><tr><td class=\"imaging-label\">Imaging Label</td></tr></table></td>';\n $pdfContent .= '<td style=\"border:0px;text-align:center;width:25%;\"><h3 class=\"h3\"><div class=\"span\">LabCorp</div><div class=\"span\">EREQ</div><div class=\"span\">OpenEMR</div></h3></td>';\n $pdfContent .= \"<td style='border:0px;width:40%;margin:0px 0px;padding:0px 0px'><table><tr>\";\n $pdfContent .= \"<td class='bar-code-label'>Barcode Placeholder</td>\";\n //$pdfContent .= \"<td class='bar-code-label'><img style='width:3.75in;height:0.95in;border:0px;outline:none;' src='$lc_2d'></td>\";\n $pdfContent .= '</tr></table></td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '<table class=\"cor-edi-main-table no-border\" style=\"margin-top:10px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"border:0px;text-align:left;padding-left:20px;\"><h4>LabCorp\u00ae</h4></td>';\n $pdfContent .= '<td style=\"border:0px;text-align:center;\"><h4>OpenEMR</h4></td>';\n $pdfContent .= '<td style=\"border:0px;text-align:right;padding-right:20px;\"><b>Page 1 of 2</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $procedure = sqlQuery(\"SELECT * FROM procedure_order WHERE procedure_order_id=?\", [$form_id]);\n $account_facility = $procedure['account_facility'];\n $facility = sqlQuery(\"SELECT * FROM facility f WHERE f.id=?\", [$account_facility]);\n $location = sqlQueryNoLog(\"SELECT f.facility_code FROM users as u \" .\n \"INNER JOIN facility as f ON u.facility_id = f.id WHERE u.id = ?\", array($procedure['provider_id']));\n\n $account = $facility['facility_code'];\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:45%;border-right: 0px;\">';\n $pdfContent .= \"<h4>Account #: \" . text($account) . \"</h4><br/>\";\n $pdfContent .= '<h4>Req/Control #: ' . text($form_id) . '</h4>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td style=\"width:55%;\">';\n $pdfContent .= '<table>';\n\n if (!empty($procedure['date_collected'])) {\n $collection_date = date(\"m/d/Y\", strtotime($procedure['date_collected']));\n $collection_time = date(\"H:i\", strtotime($procedure['date_collected']));\n } else {\n $collection_date = '';\n $collection_time = '';\n }\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"text-align:right;width:35%;\">Collection Date:</td>';\n $pdfContent .= '<td style=\"width:65%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"text-align:right;\">Collection Time:</td>';\n $pdfContent .= '<td>' . text($collection_time) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"text-align:right;\">Courtesy Copy:</td>';\n $pdfContent .= '<td>Acct# &nbsp; Attn: &nbsp;<br/>Fax# &nbsp; Attn: &nbsp;<br/>Patient </td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n\n $pdfContent .= '<td class=\"width50\" style=\"padding-left:8px;\"><b>Client / Ordering Site Information:</b></td>';\n $pdfContent .= '<td class=\"width50\" style=\"padding-left:8px;\">Physician Information:</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Account Name:</td><td style=\"width:64%;padding-left:8px;\">' . text($facility['name']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Address 1:</td><td style=\"padding-left:8px;\">' . text($facility['street']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Address 2:</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">City, State Zip:</td><td style=\"padding-left:8px;\">' . text($facility['city']) . ', ' . text($facility['state']) . ' ' . text($facility['postal_code']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Phone:</td><td style=\"padding-left:8px;\">' . text($facility['phone']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $provider = sqlQuery(\"SELECT concat(lname,', ', fname) as name, npi, upin, id FROM users WHERE id=?\", [$procedure['provider_id']]);\n $pdfContent .= '<tr><td style=\"text-align:right;width:36%;\">Ordering Physician:</td><td style=\"width:64%;padding-left:8px;\">' . text($provider['name']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Physician Degree:</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">NPI:</td><td style=\"padding-left:8px;\">' . text($provider['npi']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">UPIN:</td><td style=\"padding-left:8px;\">' . text($provider['upin']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Physician ID:</td><td style=\"padding-left:8px;\">' . text($provider['id']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $patient = sqlQuery(\"SELECT * FROM patient_data WHERE pid=?\", [$pid]);\n $pdfContent .= '<td style=\"padding-left:8px;\" colspan=\"2\"><b>Patient Information:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $page = getPatientAgeYMD($patient['DOB']);\n $ageformat = explode(' ', $page['ageinYMD']);\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Patient Name:</td><td style=\"width:64%;padding-left:8px;\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Gender:</td><td style=\"padding-left:8px;\">' . text($patient['sex']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Date of Birth:</td><td style=\"padding-left:8px;\">' . date(\"m/d/Y\", strtotime($patient['DOB'])) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Age:</td><td style=\"padding-left:8px;\">' . str_replace('y', '', text($ageformat[0])) . '/' . text(str_replace('m', '', $ageformat[1])) . '/' . text(str_replace('d', '', $ageformat[2])) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Patient Address:</td><td style=\"padding-left:8px;\">' . text($patient['street']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">City, State Zip:</td><td style=\"padding-left:8px;\">' . text($patient['city']) . ', ' . text($patient['state']) . ' ' . text($patient['postal_code']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"text-align:right;width:36%;\">Patient SSN:</td><td style=\"width:64%;padding-left:8px;\">' . text($patient['ss']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Patient ID:</td><td style=\"padding-left:8px;\">' . text($patient['pubpid']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Phone:</td><td style=\"padding-left:8px;\">' . text($patient['phone_home']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">&nbsp;</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Alt Control #:</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Alt Patient ID:</td><td style=\"padding-left:8px;\">' . text($patient['pid']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $proc_sql = sqlStatement(\"SELECT procedure_code, procedure_name, diagnoses, procedure_order_seq FROM procedure_order_code WHERE procedure_order_id=?\", [$form_id]);\n $proc_order = sqlNumRows($proc_sql);\n $procedure_right = floor($proc_order / 2);\n $procedure_left = $proc_order - $procedure_right;\n $all_procedures = array();\n $all_diagnoses = array();\n\n if (!empty($procedure['order_diagnosis'])) {\n $all_diagnoses[] = $procedure['order_diagnosis'];\n }\n while ($row = sqlFetchArray($proc_sql)) {\n $all_procedures[] = $row;\n }\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width25\" style=\"width:17%;padding-left:8px;\"><b>ORDER CODE</b></td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:33%;padding-left:8px;\"><b>TESTS ORDERED (TOTAL: ' . text($proc_order) . ')</b></td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:17%;padding-left:8px;\"><b>ORDER CODE</b></td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:33%;padding-left:8px;\"><b>TESTS ORDERED</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:17%;padding-left:8px;height:100px;border-right:0px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n for ($i = 0; $i < $procedure_left; $i++) {\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">' . text($all_procedures[$i]['procedure_code']) . '</td>';\n $temp_diag = explode(\";\", $all_procedures[$i]['diagnoses']);\n foreach ($temp_diag as $sub_diag) {\n $all_diagnoses[] = $sub_diag;\n }\n $pdfContent .= '</tr>';\n }\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td style=\"width:17%;padding-left:8px;height:100px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n for ($i = 0; $i < $procedure_left; $i++) {\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">' . text($all_procedures[$i]['procedure_name']) . '</td>';\n $pdfContent .= '</tr>';\n }\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td style=\"width:17%;padding-left:8px;height:100px;border-right:0px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n for ($i = $procedure_left; $i < $proc_order; $i++) {\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">' . text($all_procedures[$i]['procedure_code']) . '</td>';\n $temp_diag = explode(\";\", $all_procedures[$i]['diagnoses']);\n foreach ($temp_diag as $sub_diag) {\n $all_diagnoses[] = $sub_diag;\n }\n $pdfContent .= '</tr>';\n }\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td style=\"width:17%;padding-left:8px;height:100px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n for ($i = $procedure_left; $i < $proc_order; $i++) {\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">' . text($all_procedures[$i]['procedure_name']) . '</td>';\n $pdfContent .= '</tr>';\n }\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $vitals = sqlQuery(\"SELECT height, weight FROM form_vitals v join forms f on f.form_id=v.id WHERE f.pid=? and f.encounter=? ORDER BY v.date DESC LIMIT 1\", [$pid, $encounter]);\n $i = 0;\n $aoe_pap = '';\n $allspecs = [];\n $allbltype = [];\n $allblpurpose = [];\n while ($all_procedures[$i]) {\n $aoe_list = sqlStatement(\n \"SELECT \" .\n \"a.question_code, a.answer, q.question_code , q.tips, q.question_text, q.procedure_code FROM procedure_answers AS a \" .\n \"LEFT JOIN procedure_questions AS q ON q.lab_id = ? \" .\n \"AND q.procedure_code = ? AND q.question_code = a.question_code \" .\n \"WHERE a.procedure_order_id = ? AND a.procedure_order_seq = ? \" .\n \"ORDER BY q.seq, a.answer_seq\",\n array($procedure['lab_id'], $all_procedures[$i]['procedure_code'], $form_id, $all_procedures[$i]['procedure_order_seq'])\n );\n foreach ($aoe_list as $aoe_data) {\n if ($aoe_data['question_code']) {\n if (stripos($all_procedures[$i]['procedure_name'], 'PAP') !== false) {\n if ($aoe_data['answer']) {\n $aoe_pap .= '<tr><td style=\"width:36%;text-align:right;\">' . text($aoe_data['question_text']) . ':</td><td style=\"width:64%;padding-left:8px;\">' . text($aoe_data['answer']) . '</td></tr>';\n $pap_proc = 'AOE Test: ' . $all_procedures[$i]['procedure_code'];\n }\n continue;\n }\n if ($aoe_data['question_code'] == \"SOURCE\" && !empty($aoe_data['answer'])) {\n $allspecs[] = $aoe_data['answer'];\n }\n if ($aoe_data['question_code'] == 'BLSRCE') {\n $ans = \"\";\n switch (trim($aoe_data['answer'])) {\n case 'V':\n $ans = \"Venous\";\n break;\n case 'F':\n $ans = \"FingerStick\";\n break;\n }\n if ($ans) {\n $allbltype[] = $ans;\n }\n }\n if ($aoe_data['question_code'] == 'BLPURP') {\n $ans = \"\";\n switch (trim($aoe_data['answer'])) {\n case 'I':\n $ans = \"Initial\";\n break;\n case 'R':\n $ans = \"Repeat\";\n break;\n case 'F':\n $ans = \"Followup\";\n break;\n }\n if ($ans) {\n $allblpurpose[] = $ans;\n }\n }\n if ($aoe_data['question_code'] == 'TOTVOL') {\n $vitals['urine_total_volume'] = $aoe_data['answer'];\n }\n }\n }\n $i++;\n }\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n if (!empty($pap_proc)) {\n $pdfContent .= \"<td class='width50' style='padding-left:8px;'><b>text($pap_proc)</b></td>\";\n } else {\n $pdfContent .= '<td class=\"width50\" style=\"padding-left:8px;\"><b>Clinical Information:</b></td>';\n }\n $pdfContent .= '<td class=\"width50\" style=\"padding-left:8px;\"><b>Additional Information:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"min-height:50px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n if ($pap_proc && $aoe_pap) {\n $pdfContent .= $aoe_pap;\n } else {\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">' . text($procedure['clinical_hx']) . '</td><td style=\"width:64%;padding-left:8px;\">&nbsp;</td></tr>';\n }\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td style=\"min-height:50px;\" class=\"width50\">';\n $pdfContent .= '<table>';\n\n $fasting = $procedure['specimen_fasting'] === 'YES' ? \"YES\" : \"NO\";\n $pdfContent .= '<tr><td style=\"text-align:right;width:36%;\">Fasting:</td><td style=\"width:64%;padding-left:8px;\">' . text($fasting) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Height (in):</td><td style=\"padding-left:8px;\">' . text($vitals['height']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Weight (lbs oz):</td><td style=\"padding-left:8px;\">' . text($vitals['weight']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Urine Total Volume (mls):</td><td style=\"padding-left:8px;\">' . text($vitals['urine_total_volume']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td colspan=\"2\"><b>Micro/Histo Information: </b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n if (!empty($allspecs)) {\n $specs = implode(',', $allspecs);\n }\n $pdfContent .= '<tr><td style=\"text-align:right;width:36%;\">Source:</td><td style=\"width:64%;padding-left:8px;\">' . text($specs) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"padding-left:8px;\"></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $race = array(\"declne_to_specfy\" => 9, \"amer_ind_or_alaska_native\" => 3, \"Asian\" => 4, \"black_or_afri_amer\" => 2, \"native_hawai_or_pac_island\" => 5, \"white\" => 1);\n $hispanic = empty($patient['ethnicity']) ? \"9\" : null;\n $hispanic = ($patient['ethnicity'] === \"hisp_or_latin\" && empty($hispanic)) ? 1 : 2;\n $pdfContent .= '<td style=\"padding-left:8px;\" colspan=\"2\"><b>Blood Lead Information: </b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Race:</td><td style=\"width:64%;padding-left:8px;\">' . text($race[$patient['race']]) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Hispanic:</td><td style=\"padding-left:8px;\">' . text($hispanic) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Blood Lead Type:</td><td style=\"padding-left:8px;\">' . text(implode(',', $allbltype)) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Blood Lead Purpose:</td><td style=\"width:64%;padding-left:8px;\">' . text(implode(',', $allblpurpose)) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Blood Lead County:</td><td style=\"padding-left:8px;\">' . text($patient['county']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:30px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;\" colspan=\"8\"><b>Diagnosis Codes:</b>List all applicable Diagnosis codes. Must be at Highest Level Specificity.</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n // need to remove the code system prefix\n $codesOnlyArray = [];\n foreach ($all_diagnoses as $diagnosis) {\n $splitCode = explode(\":\", $diagnosis);\n if (!empty($splitCode)) {\n if (!empty($splitCode[1])) {\n $codesOnlyArray[] = $splitCode[1];\n } else {\n $codesOnlyArray[] = $splitCode;\n }\n }\n }\n for ($i = 0; $i < 8; $i++) {\n $pdfContent .= '<td style=\"width:12.5%;\" >' . text($codesOnlyArray[$i] ?? '') . '</td>';\n }\n $pdfContent .= '</tr>';\n if (!empty($all_diagnoses[8])) {\n $pdfContent .= '<tr>';\n for ($i = 8; $i < 16; $i++) {\n $pdfContent .= '<td style=\"width:12.5%;\" >' . text($codesOnlyArray[$i] ?? '') . '</td>';\n }\n $pdfContent .= '</tr>';\n }\n\n $primary = sqlQuery(\"SELECT i.*,ic.name,ic.id FROM insurance_data i join insurance_companies ic ON i.provider=ic.id WHERE i.pid=? and i.type='primary' ORDER BY i.date DESC LIMIT 1\", [$pid]);\n $billtype = \"Unknown\";\n switch (trim($procedure['billing_type'])) {\n case 'T':\n $billtype = \"Third Party\";\n break;\n case 'P':\n $billtype = \"Patient\";\n break;\n case 'C':\n $billtype = \"Client\";\n break;\n }\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"border-right:0px;\"><b>Bill Type:</b></td>';\n $pdfContent .= '<td colspan=\"3\" style=\"padding-left:8px;\">' . text($billtype) . '</td>';\n $pdfContent .= '<td style=\"border-right:0px;\"><b>LCA Ins Code:</b></td>';\n $pdfContent .= '<td colspan=\"3\" style=\"padding-left:8px;\">&nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n\n $pdfContent .= '<table class=\"cor-edi-main-table dotted-table\" style=\"margin-bottom:10px;page-break-after:always;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width25\" style=\"width:25%;\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td colspan=\"2\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td></tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($patient['dob']) . '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>' . text($account) . '</td>';\n $pdfContent .= '<td>' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table no-border\" style=\"margin-bottom:30px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"text-align:right;padding-right:20px;\" class=\"no-border\"><b>Page 2 of 2</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table no-border\" style=\"margin-bottom:10px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\" class=\"no-border\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Account Number:</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($account) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Req/Control#</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($form_id) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Collection Date:</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($collection_date) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;\" class=\"no-border\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Patient Name:</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($patient['lname']) . ', ' . text($patient['fname']) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Patient ID:</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($patient['pubpid']) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"width:36%;text-align:right;\">Alt Pat ID:</td>';\n $pdfContent .= '<td style=\"width:64%;padding-left:8px;\">' . text($patient['pid']) . '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;\" ><b>Responsible Party / Guarantor Information:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td>';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:24%;text-align:right;\">RP Name:</td><td style=\"width:76%;padding-left:8px;\">' . text($primary['subscriber_lname']) . ', ' . text($primary['subscriber_fname']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">RP Address:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_street']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">RP City, State Zip:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_city']) . ', ' . text($primary['subscriber_state']) . ' ' . text($primary['subscriber_postal_code']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">RP Phone:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_phone']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">RP Relation to Pt:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_relationship']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;width:33%;\" ><b>ABN: &nbsp; </b> &nbsp;</td>';\n $pdfContent .= '<td style=\"padding-left:8px;width:33%;\" ><b>Worker\u2019s Comp: &nbsp; </b> &nbsp;</td>';\n $pdfContent .= '<td style=\"padding-left:8px;width:33%;\" ><b>Date of Injury: &nbsp; </b> &nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"cor-edi-main-table\" style=\"margin-bottom:6px;\">';\n $pdfContent .= '<tbody>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;\" colspan=\"2\"><b>Insurance Information:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;\"><b>Primary Insurance: </b></td>';\n $pdfContent .= '<td style=\"padding-left:8px;\"><b>Secondary Insurance:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">LCA Ins Code:</td><td style=\"width:64%;padding-left:8px;\">&nbsp;</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Co Name:</td><td style=\"padding-left:8px;\">' . text($primary['name']) . '</td></tr>';\n $paddress = sqlQuery(\"SELECT * FROM addresses WHERE foreign_id=?\", [$primary['id']]);\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Address 1:</td><td style=\"padding-left:8px;\">' . text($paddress['line1']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Address 2:</td><td style=\"padding-left:8px;\">' . text($paddress['line2']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins City, State Zip:</td><td style=\"padding-left:8px;\">' . text($paddress['city']) . ', ' . text($paddress['state']) . ' ' . text($paddress['zip']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Policy Number:</td><td style=\"padding-left:8px;\">' . text($primary['policy_number']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Group #:</td><td style=\"padding-left:8px;\">' . text($primary['group_number']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Emp/Group Name:</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n if (!empty($primary['name'])) {\n $pprovider_id = $provider['id'];\n }\n $pdfContent .= '<tr><td style=\"text-align:right;\">Provider #:</td><td style=\"padding-left:8px;\">' . text($pprovider_id) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $secondary = sqlQuery(\"SELECT i.*, ic.name, ic.id FROM insurance_data i join insurance_companies ic ON i.provider=ic.id WHERE i.pid=? and i.type='secondary' ORDER BY i.date DESC LIMIT 1\", [$pid]);\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">LCA Ins Code:</td><td style=\"width:64%;padding-left:8px;\">&nbsp;</td></tr>';\n $saddress = sqlQuery(\"SELECT * FROM addresses WHERE foreign_id=?\", [$secondary['id']]);\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Co Name:</td><td style=\"padding-left:8px;\">' . text($secondary['name']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Address 1:</td><td style=\"padding-left:8px;\">' . text($saddress['line1']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins Address 2:</td><td style=\"padding-left:8px;\">' . text($saddress['line2']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Ins City, State Zip:</td><td style=\"padding-left:8px;\">' . text($saddress['city']) . ', ' . text($saddress['state']) . ' ' . text($saddress['zip']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Policy Number:</td><td style=\"padding-left:8px;\">' . text($secondary['policy_number']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Group #:</td><td style=\"padding-left:8px;\">' . text($secondary['group_number']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Emp/Group Name:</td><td style=\"padding-left:8px;\">&nbsp;</td></tr>';\n if (!empty($secondary['name'])) {\n $sprovider_id = $provider['id'];\n }\n $pdfContent .= '<tr><td style=\"text-align:right;\">Provider #:</td><td style=\"padding-left:8px;\">' . text($sprovider_id) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td style=\"padding-left:8px;\"><b>Primary Policy Holder / Insured:</b></td>';\n $pdfContent .= '<td style=\"padding-left:8px;\"><b>Secondary Policy Holder / Insured:</b></td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Insured Name:</td><td style=\"width:64%;padding-left:8px;\">' . text($primary['subscriber_lname']) . ', ' . text($primary['subscriber_fname']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Insured Address:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_street']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">&nbsp;</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_city']) . ', ' . text($primary['subscriber_state']) . ' ' . text($primary['subscriber_postal_code']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Insured Relation to Pt:</td><td style=\"padding-left:8px;\">' . text($primary['subscriber_relationship']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr><td style=\"width:36%;text-align:right;\">Insured Name:</td><td style=\"width:64%;padding-left:8px;\">' . text($secondary['subscriber_lname']) . ', ' . text($secondary['subscriber_fname']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Insured Address:</td><td style=\"padding-left:8px;\">' . text($secondary['subscriber_street']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">&nbsp;</td><td style=\"padding-left:8px;\">' . text($secondary['subscriber_city']) . ', ' . text($secondary['subscriber_state']) . ' ' . text($secondary['subscriber_postal_code']) . '</td></tr>';\n $pdfContent .= '<tr><td style=\"text-align:right;\">Insured Relation to Pt:</td><td style=\"padding-left:8px;\">' . text($secondary['subscriber_relationship']) . '</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n\n $pdfContent .= '<table class=\"\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td colspan=\"2\" class=\"no-border\" style=\"padding-top:30px;\">';\n $pdfContent .= '<div>Authorization - Please sign and Date</div>';\n $pdfContent .= '<div>I hereby authorize the release of medical information related to the services described hereon and </div>';\n $pdfContent .= '<div>authorize payment directly to Laboratory Corporation of America. I agree to assume responsibility for</div>';\n $pdfContent .= '<div>payment of charges for laboratory services that are not covered by my healthcare insurer.</div>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td colspan=\"2\" class=\"no-border\">';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table style=\"width:250px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;height: 40px;padding-top:40px;border-bottom:1px solid #000;\">&nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr><td class=\"width50\" style=\"width:50%;\">Patient Signature</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table style=\"width:150px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;height: 40px;padding-top:40px;border-bottom:1px solid #000;\">&nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr><td class=\"width50\" style=\"width:50%;\">Date</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '<table>';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table style=\"width:250px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;height: 40px;padding-top:40px;border-bottom:1px solid #000;\">&nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr><td class=\"width50\" style=\"width:50%;\">Patient Signature</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '<td class=\"width50\">';\n $pdfContent .= '<table style=\"width:150px;\">';\n $pdfContent .= '<tr>';\n $pdfContent .= '<td class=\"width50\" style=\"width:50%;height: 40px;padding-top:40px;border-bottom:1px solid #000;\">&nbsp;</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '<tr><td class=\"width50\" style=\"width:50%;\">Date</td></tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</table>';\n $pdfContent .= '</td>';\n $pdfContent .= '</tr>';\n $pdfContent .= '</tbody>';\n $pdfContent .= '</table>';\n $pdfContent .= '</div>';\n $pdfContent .= '</body>';\n $pdfContent .= '</html>';\n $mpdf->WriteHTML($styleSheet, 1);\n $mpdf->WriteHTML($pdfContent, 2);\n\n $unique = date('y-m-d-His', time());\n $filename = \"ereq_\" . $unique . \"_order_\" . $form_id . \".pdf\";\n\n//-----------patch in exclude dodoc\n if ($_REQUEST['debug'] || !$doDoc) {\n $mpdf->Output($filename, \"I\");\n return;\n }\n $mpdfData = $mpdf->Output($filename, \"S\");\n\n// register the new document\n $category = sqlQuery(\"SELECT id FROM categories WHERE name LIKE ?\", array(\"LabCorp\"));\n if (!$category['id']) {\n $category = sqlQuery(\"SELECT id FROM categories WHERE name LIKE ?\", array('Lab Report'));\n }\n $DOCUMENT_CATEGORY = $category['id'];\n\n $d = new Document();\n $good = $d->createDocument($pid, $DOCUMENT_CATEGORY, $filename, \"application/pdf\", $mpdfData);\n if (!empty($good)) {\n echo $good;\n exit;\n }\n $unique = date('y-m-d-H:i:s', time());\n $documentationOf = \"$unique\";\n sqlStatement(\n \"UPDATE documents SET documentationOf = ?, list_id = ? WHERE id = ?\",\n array($documentationOf, $form_id, $d->id)\n );\n } catch (Exception $e) {\n echo \"Message: \" . $e->getMessage();\n echo \"\";\n echo \"getCode(): \" . $e->getCode();\n echo \"\";\n echo \"__toString(): \" . $e->__toString();\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ftp_raw(FTP\\Connection|resource $ftp, string $command): ?array {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function downloadViaProxy($filename, $mimeType, $url, $bypassProxy = true, $originalFileName=null){\n/*\n $rawdata = loadRemoteURLContent($url, $bypassProxy);//blocked\n\n if($rawdata!==false){\n\n fileSave($rawdata, $filename);\n\n if(file_exists($filename)){\n downloadFile($mimeType, $filename, $originalFileName);\n }\n\n }\n*/\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private function generateActionLinks($id, $uri): array\n {\n $patientLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"createPatient(event, \" . attr_js($id) . \", \" . attr_js($id) . \", \" . attr_js(json_encode([])) . \")\\\"> <i class='fa fa-chart-simple mr-2' title='\" . xla(\"Chart fax or Create patient and chart fax to documents.\") . \"'></i></a>\";\n $messageLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"notifyUser(event, \" . attr_js($id) . \", \" . attr_js($id) . \", \" . attr_js(0) . \")\\\"> <i class='fa fa-paper-plane mr-2' title='\" . xla(\"Notify a user and attach this fax to message.\") . \"'></i></a>\";\n $downloadLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"getDocument(event, null, \" . attr_js($id) . \", 'true')\\\"> <i class='fa fa-file-download mr-2' title='\" . xla(\"Download and delete fax\") . \"'></i></a>\";\n $viewLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"getDocument(event, null, \" . attr_js($id) . \", 'false')\\\"> <i class='fa fa-file-pdf mr-2' title='\" . xla(\"View fax document\") . \"'></i></a>\";\n $deleteLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"getDocument(event, null, \" . attr_js($id) . \", 'false', 'true')\\\"> <i class='text-danger fa fa-trash mr-2' title='\" . xla(\"Delete this fax document\") . \"'></i></a>\";\n $forwardLink = \"<a role='button' href='javascript:void(0)' onclick=\\\"forwardFax(event, \" . attr_js($id) . \")\\\"> <i class='fa fa-forward mr-2' title='\" . xla(\"Forward fax to new fax recipient or email attachment.\") . \"'></i></a>\";\n\n $vtoggle = \"<a href='javascript:' onclick=messageShow(\" . attr_js($id) . \")><span class='mx-1 fa fa-eye-slash fa-1x'></span></a>\";\n $vreply = \"<a href='javascript:' onclick=messageReply(\" . attr_js($id) . \")><span class='mx-1 fa fa-reply'></span></a>\";\n\n return [\n 'sms' => $vtoggle . $vreply,\n 'inbound' => $patientLink . $messageLink . $forwardLink . $viewLink . $downloadLink . $deleteLink,\n 'outbound' => $viewLink . $downloadLink . $deleteLink\n ];\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function register(Request $request){\n return view('auth.register');\n }", "smellKey": "S1172", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function xRevRange($stream, $end, $start, $count = null)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setnx($key, $value)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ped_GI_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_ped_GI\", $id);\n if ($data) :\n print \"<table span class=text><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n\n print \"</tr></table>\";\n endif;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function intlcal_set_lenient($calendar, $isLenient) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (Concrete $object, Data $fieldDefinition, $property, $currentValue) {\n if ($fieldDefinition instanceof Data\\CustomVersionMarshalInterface) {\n return $fieldDefinition->unmarshalVersion($object, $currentValue);\n }\n\n return $currentValue;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function restored(Service $service): void\n {\n //\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function setPattern($pattern) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function intltz_get_raw_offset($obj) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "#[Deprecated(replacement: '%class%->lLen(%parametersList%)')]\n public function lSize($key)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function install_sql($modId, $currentActionStatus): mixed\n {\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function imagesetthickness ($image, $thickness) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function hKeys($key)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function save(\n &$bill,\n &$prod,\n $main_provid = null,\n $main_supid = null,\n $default_warehouse = null,\n $mark_as_closed = false\n ) {\n global $code_types;\n\n if (isset($main_provid) && $main_supid == $main_provid) {\n $main_supid = 0;\n }\n\n $copay_update = false;\n $update_session_id = '';\n $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted\n $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted\n $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted\n\n if (is_array($bill)) {\n foreach ($bill as $iter) {\n // Skip disabled (billed) line items.\n if (!empty($iter['billed'])) {\n continue;\n }\n\n $id = $iter['id'] ?? null;\n $code_type = $iter['code_type'];\n $code = $iter['code'];\n $del = !empty($iter['del']);\n $units = empty($iter['units']) ? 1 : intval($iter['units']);\n $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];\n $revenue_code = empty($iter['revenue_code']) ? '' : trim($iter['revenue_code']);\n $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);\n $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);\n $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);\n $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);\n\n $price = 0;\n if (!empty($iter['price'])) {\n if ($code_type == 'COPAY' || $this->pricesAuthorized()) {\n $price = 0 + trim($iter['price'] ?? 0);\n } else {\n $price = $this->getPrice($pricelevel, $code_type, $code);\n }\n }\n\n $fee = sprintf('%01.2f', $price * $units);\n\n if (!$cod0 && ($code_types[$code_type]['fee'] ?? null) == 1) {\n $mod0 = $modifier;\n $cod0 = $code;\n $ct0 = $code_type;\n }\n\n if ($code_type == 'COPAY') {\n if ($fee < 0) {\n $fee = $fee * -1;\n }\n if ($id) {\n // editing copay in ar_session\n $session_id = $id;\n $res_amount = sqlQuery(\n \"SELECT pay_amount FROM ar_activity WHERE pid = ? AND encounter = ? AND session_id = ?\",\n array($this->pid, $this->encounter, $session_id)\n );\n if ($fee != $res_amount['pay_amount']) {\n sqlStatement(\n \"UPDATE ar_session SET user_id = ?, pay_total = ?, modified_time = now(), \" .\n \"post_to_date = now() WHERE session_id = ?\",\n array($_SESSION['authUserID'], $fee, $session_id)\n );\n }\n // deleting old copay\n sqlStatement(\n \"UPDATE ar_activity SET deleted = NOW() WHERE \" .\n \"deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?\",\n array($this->pid, $this->encounter, $id)\n );\n } else {\n // adding new copay from fee sheet into ar_session\n $session_id = sqlInsert(\n \"INSERT INTO ar_session \" .\n \"(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, \" .\n \"adjustment_code, post_to_date) \" .\n \"VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())\",\n array($_SESSION['authUserID'], $fee, $this->pid)\n );\n }\n // adding new or changed copay from fee sheet into ar_activity\n sqlBeginTrans();\n $sequence_no = sqlQuery(\"SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE \" .\n \"pid = ? AND encounter = ?\", array($this->pid, $this->encounter));\n SqlStatement(\n \"INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, \" .\n \"payer_type, post_time, post_user, session_id, pay_amount, account_code) \" .\n \"VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')\",\n array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,\n $_SESSION['authUserID'], $session_id, $fee)\n );\n sqlCommitTrans();\n\n if (!$cod0) {\n $copay_update = true;\n $update_session_id = $session_id;\n }\n\n continue;\n }\n\n # Code to create justification for all codes based on first justification\n if ($GLOBALS['replicate_justification'] == '1') {\n if ($justify != '') {\n $autojustify = $justify;\n }\n }\n\n if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {\n $justify = $autojustify;\n }\n\n if ($justify) {\n $justify = str_replace(',', ':', $justify) . ':';\n }\n\n $auth = \"1\";\n\n $ndc_info = '';\n if (!empty($iter['ndcnum'])) {\n $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .\n trim($iter['ndcqty']);\n }\n\n // If the item is already in the database...\n if ($id) {\n // Get existing values from database.\n $logarr = null;\n $tmp = sqlQuery(\n \"SELECT * FROM billing WHERE id = ? AND billed = 0 AND activity = 1\",\n array($id)\n );\n if (!empty($tmp)) {\n $logarr = array(\n $tmp['code_type'],\n $tmp['code'],\n '',\n $tmp['pricelevel'],\n $tmp['fee'],\n $tmp['units'],\n $tmp['provider_id'],\n ''\n );\n }\n //\n if ($del) {\n $this->logFSMessage(xl('Item deleted'), '', $logarr);\n BillingUtilities::deleteBilling($id);\n } else {\n if (!empty($tmp)) {\n $tmparr = array('code' => $code, 'authorized' => $auth);\n if (isset($iter['units' ])) {\n $tmparr['units' ] = $units;\n }\n\n if (isset($iter['price' ])) {\n $tmparr['fee' ] = $fee;\n }\n\n if (isset($iter['pricelevel'])) {\n $tmparr['pricelevel'] = $pricelevel;\n }\n\n if (isset($iter['mod' ])) {\n $tmparr['modifier' ] = $modifier;\n }\n\n if (isset($iter['provid' ])) {\n $tmparr['provider_id'] = $provid;\n }\n\n if (isset($iter['ndcnum' ])) {\n $tmparr['ndc_info' ] = $ndc_info;\n }\n\n if (isset($iter['justify' ])) {\n $tmparr['justify' ] = $justify;\n }\n\n if (isset($iter['notecodes'])) {\n $tmparr['notecodes' ] = $notecodes;\n }\n\n if (isset($iter['revenue_code'])) {\n $tmparr['revenue_code'] = $revenue_code;\n }\n\n foreach ($tmparr as $key => $value) {\n if ($tmp[$key] != $value) {\n if ('fee' == $key) {\n $this->logFSMessage(xl('Price changed'), $value, $logarr);\n }\n\n if ('units' == $key) {\n $this->logFSMessage(xl('Quantity changed'), $value, $logarr);\n }\n\n if ('provider_id' == $key) {\n $this->logFSMessage(xl('Service provider changed'), $value, $logarr);\n }\n\n sqlStatement(\"UPDATE billing SET `$key` = ? WHERE id = ?\", array($value, $id));\n }\n }\n }\n }\n } elseif (!$del) { // Otherwise it's a new item...\n $logarr = array($code_type, $code, '', $pricelevel, $fee, $units, $provid, '');\n $this->logFSMessage(xl('Item added'), '', $logarr);\n $code_text = lookup_code_descriptions($code_type . \":\" . $code . \":\" . $modifier);\n BillingUtilities::addBilling(\n $this->encounter,\n $code_type,\n $code,\n $code_text,\n $this->pid,\n $auth,\n $provid,\n $modifier,\n $units,\n $fee,\n $ndc_info,\n $justify,\n 0,\n $notecodes,\n $pricelevel,\n $revenue_code,\n $this->payer_id\n );\n }\n } // end for\n }\n\n // if modifier is not inserted during loop update the record using the first\n // non-empty modifier and code\n if ($copay_update == true && $update_session_id != '' && $mod0 != '') {\n sqlStatement(\n \"UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?\" .\n \" WHERE deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?\",\n array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)\n );\n }\n\n // Doing similarly to the above but for products.\n if (is_array($prod)) {\n foreach ($prod as $iter) {\n // Skip disabled (billed) line items.\n if (!empty($iter['billed'])) {\n continue;\n }\n\n $drug_id = $iter['drug_id'];\n $selector = empty($iter['selector']) ? '' : $iter['selector'];\n $sale_id = $iter['sale_id']; // present only if already saved\n $units = intval(trim($iter['units']));\n if (!$units) {\n $units = 1;\n }\n $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];\n $del = !empty($iter['del']);\n $rxid = 0;\n $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];\n $somechange = false;\n\n $price = 0;\n if (!empty($iter['price'])) {\n if ($iter['price'] != 'X') {\n // The price from the form is good.\n $price = 0 + trim($iter['price']);\n } else {\n // Otherwise get its price for the given price level and product.\n $price = $this->getPrice($pricelevel, 'PROD', $drug_id, $selector);\n }\n }\n\n $fee = sprintf('%01.2f', $price * $units);\n\n // $units is the user view, multipliers of Basic Units.\n // Need to compute inventory units for the save logic below.\n $inv_units = $units * $this->getBasicUnits($drug_id, $selector);\n\n // If the item is already in the database...\n if ($sale_id) {\n // Get existing values from database.\n $tmprow = sqlQuery(\n \"SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, \" .\n \"ds.sale_date, ds.drug_id, ds.selector, ds.pricelevel, di.warehouse_id \" .\n \"FROM drug_sales AS ds \" .\n \"LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id \" .\n \"WHERE ds.sale_id = ?\",\n array($sale_id)\n );\n $rxid = (int) $tmprow['prescription_id'];\n $logarr = null;\n if (!empty($tmprow)) {\n $logarr = array(\n 'PROD',\n $tmprow['drug_id'],\n $tmprow['selector'],\n $tmprow['pricelevel'],\n $tmprow['fee'],\n $tmprow['quantity'],\n '',\n $tmprow['warehouse_id']\n );\n }\n //\n if ($del) {\n if (!empty($tmprow)) {\n // Delete this sale and reverse its inventory update.\n $this->logFSMessage(xl('Item deleted'), '', $logarr);\n sqlStatement(\"DELETE FROM drug_sales WHERE sale_id = ?\", array($sale_id));\n if (!empty($tmprow['inventory_id'])) {\n sqlStatement(\n \"UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?\",\n array($tmprow['quantity'], $tmprow['inventory_id'])\n );\n }\n }\n\n if ($rxid) {\n sqlStatement(\"DELETE FROM prescriptions WHERE id = ?\", array($rxid));\n }\n } else {\n // Modify the sale and adjust inventory accordingly.\n if (!empty($tmprow)) {\n foreach (\n array(\n 'quantity' => $inv_units,\n 'fee' => $fee,\n 'pricelevel' => $pricelevel,\n 'selector' => $selector,\n 'sale_date' => $this->visit_date,\n ) as $key => $value\n ) {\n if ($tmprow[$key] != $value) {\n $somechange = true;\n if ('fee' == $key) {\n $this->logFSMessage(xl('Price changed'), $value, $logarr);\n }\n\n if ('pricelevel' == $key) {\n $this->logFSMessage(xl('Price level changed'), $value, $logarr);\n }\n\n if ('selector' == $key) {\n $this->logFSMessage(xl('Template selector changed'), $value, $logarr);\n }\n\n if ('quantity' == $key) {\n $this->logFSMessage(xl('Quantity changed'), $value, $logarr);\n }\n\n sqlStatement(\n \"UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?\",\n array($value, $sale_id)\n );\n if ($key == 'quantity' && $tmprow['inventory_id']) {\n sqlStatement(\n \"UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?\",\n array($inv_units - $tmprow['quantity'], $tmprow['inventory_id'])\n );\n }\n }\n }\n\n if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {\n // Changing warehouse. Requires deleting and re-adding the sale.\n // Not setting $somechange because this alone does not affect a prescription.\n $this->logFSMessage(xl('Warehouse changed'), $warehouse_id, $logarr);\n sqlStatement(\"DELETE FROM drug_sales WHERE sale_id = ?\", array($sale_id));\n sqlStatement(\n \"UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?\",\n array($inv_units, $tmprow['inventory_id'])\n );\n $tmpnull = null;\n $sale_id = sellDrug(\n $drug_id,\n $inv_units,\n $fee,\n $this->pid,\n $this->encounter,\n (empty($iter['rx']) ? 0 : $rxid),\n $this->visit_date,\n '',\n $warehouse_id,\n false,\n $tmpnull,\n $pricelevel,\n $selector\n );\n }\n }\n\n // Delete Rx if $rxid and flag not set.\n if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {\n sqlStatement(\"UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?\", array($sale_id));\n sqlStatement(\"DELETE FROM prescriptions WHERE id = ?\", array($rxid));\n }\n }\n } elseif (! $del) { // Otherwise it's a new item...\n $somechange = true;\n $logarr = array('PROD', $drug_id, $selector, $pricelevel, $fee, $units, '', $warehouse_id);\n $this->logFSMessage(xl('Item added'), '', $logarr);\n $tmpnull = null;\n $sale_id = sellDrug(\n $drug_id,\n $inv_units,\n $fee,\n $this->pid,\n $this->encounter,\n 0,\n $this->visit_date,\n '',\n $warehouse_id,\n false,\n $tmpnull,\n $pricelevel,\n $selector\n );\n if (!$sale_id) {\n die(xlt(\"Insufficient inventory for product ID\") . \" \\\"\" . text($drug_id) . \"\\\".\");\n }\n }\n\n // If a prescription applies, create or update it.\n if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {\n // If an active rx already exists for this drug and date we will\n // replace it, otherwise we'll make a new one.\n if (empty($rxid)) {\n $rxid = '';\n }\n\n // Get default drug attributes; prefer the template with the matching selector.\n $drow = sqlQuery(\n \"SELECT dt.*, \" .\n \"d.name, d.form, d.size, d.unit, d.route, d.substitute \" .\n \"FROM drugs AS d, drug_templates AS dt WHERE \" .\n \"d.drug_id = ? AND dt.drug_id = d.drug_id \" .\n \"ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1\",\n array($drug_id, $selector)\n );\n if (!empty($drow)) {\n $rxobj = new Prescription($rxid);\n $rxobj->set_patient_id($this->pid);\n $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);\n $rxobj->set_drug_id($drug_id);\n $rxobj->set_quantity($inv_units);\n $rxobj->set_per_refill($inv_units);\n $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));\n $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));\n $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));\n $rxobj->set_date_added($this->visit_date);\n // Remaining attributes are the drug and template defaults.\n $rxobj->set_drug($drow['name']);\n $rxobj->set_unit($drow['unit']);\n $rxobj->set_dosage($drow['dosage']);\n $rxobj->set_form($drow['form']);\n $rxobj->set_refills($drow['refills']);\n $rxobj->set_size($drow['size']);\n $rxobj->set_route($drow['route']);\n $rxobj->set_interval($drow['period']);\n $rxobj->set_substitute($drow['substitute']);\n //\n $rxobj->persist();\n // Set drug_sales.prescription_id to $rxobj->get_id().\n $oldrxid = $rxid;\n $rxid = (int) $rxobj->get_id();\n if ($rxid != $oldrxid) {\n sqlStatement(\n \"UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?\",\n array($rxid, $sale_id)\n );\n }\n }\n }\n } // end for\n }\n\n // Set default and/or supervising provider for the encounter.\n if (isset($main_provid) && $main_provid != $this->provider_id) {\n $this->logFSMessage(xl('Default provider changed'));\n sqlStatement(\n \"UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?\",\n array($main_provid, $this->pid, $this->encounter)\n );\n $this->provider_id = $main_provid;\n }\n\n if (isset($main_supid) && $main_supid != $this->supervisor_id) {\n sqlStatement(\n \"UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?\",\n array($main_supid, $this->pid, $this->encounter)\n );\n $this->supervisor_id = $main_supid;\n }\n\n // Save-and-Close is currently specific to Family Planning but might be more\n // generally useful. It provides the ability to mark an encounter as billed\n // directly from the Fee Sheet, if there are no charges.\n if ($mark_as_closed) {\n $this->closeVisit($this->pid, $this->encounter);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function trim_item(&$item, $key, $len){\n if($item!='' && $item!=null){\n $item = substr(trim($item),0,$len);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function hour_to_day(&$value, $key) {\n\t $value = $value / 24.0;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function locale_get_display_script($locale, $in_locale = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(IServerContainer $serverContainer) {\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function checkRotavirus(CqmPatient $patient, $beginDate, $endDate)\n {\n $options = array( Medication::OPTION_COUNT => 4 );\n $dobPlus42Days = date('Y-m-d 00:00:00', strtotime('+42 day', strtotime($patient->dob)));\n $dobPlus2Years = date('Y-m-d 00:00:00', strtotime('+2 year', strtotime($patient->dob)));\n if (\n Helper::checkMed(Medication::ROTAVIRUS_VAC, $patient, $dobPlus42Days, $dobPlus2Years, $options) &&\n !Helper::checkAllergy(Allergy::ROTAVIRUS_VAC, $patient, $patient->dob, $endDate)\n ) {\n return true;\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function outputDateDetail($attrs, $value) {\n makeTag('raw', null, $value);\n if (preg_match('/^\\\\s*-?(\\\\d+)\\\\s*$/', $value, $matches)) { // year only\n makeTag('year', null, $matches[1]);\n } else {\n $date = strtotime($value);\n if ($date) {\n makeTag('year', null, date('Y', $date));\n makeTag('month', null, date('n', $date));\n makeTag('day', null, date('j', $date));\n if (preg_match(\"![ T]!\", $value)) { // looks like there's a time\n makeTag('hour', null, date('H', $date));\n makeTag('minutes', null, date('i', $date));\n makeTag('seconds', null, date('s', $date));\n }\n } else {\n // cases that strtotime doesn't catch\n if (preg_match('/^([+-]?\\d\\d\\d\\d+)-(\\d\\d)$/', $value, $matches)) {\n // e.g. MMMM-DD\n makeTag('year', null, intval($matches[1]));\n makeTag('month', null, intval($matches[2]));\n } else {\n @list($date, $time) = preg_split(\"![ T]!\", $value);\n @list($y, $m, $d) = array_map(\"intval\", preg_split(REGEX_SPLIT_DATE, $date));\n if (!(1 <= $m && $m <= 12 && 1 <= $d && $d <= 31)) {\n @list($d, $m, $y) = array_map(\"intval\", preg_split(REGEX_SPLIT_DATE, $date));\n }\n if (!(1 <= $m && $m <= 12 && 1 <= $d && $d <= 31)) {\n @list($m, $d, $y) = array_map(\"intval\", preg_split(REGEX_SPLIT_DATE, $date));\n }\n if (1 <= $m && $m <= 12 && 1 <= $d && $d <= 31) {\n makeTag('year', null, $y);\n makeTag('month', null, $m);\n makeTag('day', null, $d);\n }\n @list($h, $m, $s) = array_map(\"intval\", preg_split(\"![-:]!\", $time));\n if (0 <= $h && $h <= 23) {\n makeTag('hour', null, $h);\n }\n if (0 <= $m && $m <= 59) {\n makeTag('minutes', null, $m);\n }\n if (0 <= $s && $s <= 59) {\n makeTag('seconds', null, $s);\n }\n }\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function asort(array &$arr, $sort_flag = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($key, $data) {\n return ['pimcore' => $data];\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function isgraph ($codepoint ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($uid, $keyID, $encryptionModuleId) {\n\t\t\t\tif ($keyID === 'publicKey') {\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\t\t\t\treturn 'key';\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function __construct($id = \"\", $_prefix = \"\")\n {\n parent::__construct();\n\n if (is_numeric($id)) {\n $this->id = $id;\n } else {\n $id = \"\";\n $this->date = date(\"Y-m-d H:i:s\");\n }\n\n $this->_table = \"form_leg_length\";\n $this->activity = 1;\n $this->pid = $GLOBALS['pid'];\n if ($id != \"\") {\n $this->populate();\n //$this->date = $this->get_date();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function configureCompletion(CompletionHandler $handler)\n {\n // Override this method to configure custom value completions\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($contentId): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getContentService()->loadContentInfo(\n $contentId\n );\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function emitJavascript($options=array()) {\n\n // Check if we need to emit javascript\n if (!($fid=$this->getFormId()))\n return;\n ?>\n <script type=\"text/javascript\">\n $(function() {\n <?php\n //XXX: We ONLY want to watch field on this form. We'll only\n // watch form inputs if form_id is specified. Current FORM API\n // doesn't generate the entire form (just fields)\n if ($fid) {\n ?>\n $(document).off('change.<?php echo $fid; ?>');\n $(document).on('change.<?php echo $fid; ?>',\n 'form#<?php echo $fid; ?> :input',\n function() {\n //Clear any current errors...\n var errors = $('#field'+$(this).attr('id')+'_error');\n if (errors.length)\n errors.slideUp('fast', function (){\n $(this).remove();\n });\n //TODO: Validation input inplace or via ajax call\n // and set any new errors AND visibilty changes\n }\n );\n <?php\n }\n ?>\n });\n </script>\n <?php\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "private function handleUrlChecker($config, ContainerBuilder $container, FileLoader $loader)\n {\n $loader->load('url_checker.yml');\n }", "smellKey": "S1172", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function ($uuid, HttpRestRequest $request) {\n RestConfig::authorization_check(\"patients\", \"demo\");\n $data = (array) (json_decode(file_get_contents(\"php://input\"), true));\n $return = (new FhirPatientRestController())->put($uuid, $data);\n RestConfig::apiLog($return, $data);\n return $return;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($uuid) {\n return \"?\";\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function testCreateUserSessionHashed(array $data): void\n {\n $userIds = ['md5', 'bcrypt', 'argon2', 'sha512', 'scrypt', 'phpass', 'scrypt-modified'];\n\n foreach ($userIds as $userId) {\n // Ensure sessions can be created with hashed passwords\n $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', array_merge([\n 'origin' => 'http://localhost',\n 'content-type' => 'application/json',\n 'x-appwrite-project' => $this->getProject()['$id'],\n ]), [\n 'email' => $userId . '@appwrite.io',\n 'password' => 'appwrite',\n ]);\n\n $this->assertEquals(201, $response['headers']['status-code']);\n $this->assertEquals($userId, $response['body']['userId']);\n }\n\n foreach ($userIds as $userId) {\n // Ensure all passwords were re-hashed\n $response = $this->client->call(Client::METHOD_GET, '/users/' . $userId, array_merge([\n 'content-type' => 'application/json',\n 'x-appwrite-project' => $this->getProject()['$id'],\n ], $this->getHeaders()), []);\n\n $this->assertEquals(200, $response['headers']['status-code']);\n $this->assertEquals($userId, $response['body']['$id']);\n $this->assertEquals($userId . '@appwrite.io', $response['body']['email']);\n $this->assertEquals('argon2', $response['body']['hash']);\n $this->assertStringStartsWith('$argon2', $response['body']['password']);\n }\n\n foreach ($userIds as $userId) {\n // Ensure sessions can be created after re-hashing of passwords\n $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', array_merge([\n 'origin' => 'http://localhost',\n 'content-type' => 'application/json',\n 'x-appwrite-project' => $this->getProject()['$id'],\n ]), [\n 'email' => $userId . '@appwrite.io',\n 'password' => 'appwrite',\n ]);\n\n $this->assertEquals(201, $response['headers']['status-code']);\n $this->assertEquals($userId, $response['body']['userId']);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function arPostPayment(\n $patient_id,\n $encounter_id,\n $session_id,\n $amount,\n $code,\n $payer_type,\n $memo,\n $debug,\n $time = '',\n $codetype = '',\n $date = null,\n $payer_claim_number = null\n ) {\n $codeonly = $code;\n $modifier = '';\n $tmp = strpos($code, ':');\n if ($tmp) {\n $codeonly = substr($code, 0, $tmp);\n $modifier = substr($code, $tmp + 1);\n }\n\n if (empty($time)) {\n $time = date('Y-m-d H:i:s');\n }\n\n sqlBeginTrans();\n $sequence_no = sqlQuery(\n \"SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?\",\n array($patient_id, $encounter_id)\n );\n $query = \"INSERT INTO ar_activity ( \" .\n \"pid, encounter, sequence_no, code_type, code, modifier, payer_type, post_time, post_date, post_user, \" .\n \"session_id, memo, pay_amount, payer_claim_number \" .\n \") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\";\n sqlStatement(\n $query,\n array(\n $patient_id,\n $encounter_id,\n $sequence_no['increment'],\n $codetype,\n $codeonly,\n $modifier,\n $payer_type,\n $time,\n $date,\n $_SESSION['authUserID'],\n $session_id,\n $memo,\n $amount,\n $payer_claim_number\n )\n );\n sqlCommitTrans();\n return;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function renderException(\\Exception $e)\n {\n // do nothing\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public function validateExAppRequestToNC(IRequest $request, bool $isDav = false): bool {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function transform(array $srcRecord, &$orderId)\n {\n foreach ( $srcRecord as $key => &$value ) {\n if ( null === $value ) {\n // Transform NULL values for MySQL LOAD FILE\n $value = '\\N';\n } elseif ( '' === $value ) {\n $value = $this->stringEnclosure . '' . $this->stringEnclosure;\n } elseif (strpos($value, $this->lineSeparator) !== false\n || strpos($value, $this->fieldSeparator) !== false\n || strpos($value, $this->stringEnclosure) !== false\n || strpos($value, $this->escapeChar) !== false) {\n // if the string contains any special characters it is enclosed in the stringEnclosure\n // occurences of the stringEnclosure and the escape character are escaped\n\n $search = array($this->escapeChar, $this->stringEnclosure);\n $replace = array($this->escapeChar . $this->escapeChar, $this->escapeChar . $this->stringEnclosure);\n\n $value = $this->stringEnclosure . str_replace($search, $replace, $value) . $this->stringEnclosure;\n }\n }\n\n return array($srcRecord);\n\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function isIDStart ($codepoint ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($value, $key) use (&$nb) {\n if ($key === 'field') {\n $nb++;\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function showLdapGroups(\n $target,\n $start,\n $sync = 0,\n $filter = '',\n $filter2 = '',\n $entity = 0\n ) {\n $limitexceeded = false;\n $ldap_groups = self::getAllGroups(\n $_REQUEST['authldaps_id'],\n $filter,\n $filter2,\n $entity,\n $limitexceeded\n );\n $total_results = count($ldap_groups);\n\n echo \"<div class='card p-3 mt-3'>\";\n self::displaySizeLimitWarning($limitexceeded);\n\n // delete end\n array_splice($ldap_groups, $start + $_SESSION['glpilist_limit']);\n // delete begin\n if ($start > 0) {\n array_splice($ldap_groups, 0, $start);\n }\n\n $dn_index = 1;\n $entries = [];\n foreach ($ldap_groups as $groupinfos) {\n $entry = [\n 'id' => $dn_index,\n 'itemtype' => self::class, // required for massive actions\n ];\n $group = $groupinfos[\"cn\"];\n $group_dn = $groupinfos[\"dn\"];\n $search_type = $groupinfos[\"search_type\"];\n $group_cell = '';\n $group_cell .= Html::hidden(\"dn[$dn_index]\", [\n 'value' => $group_dn,\n 'data-glpicore-ma-tags' => 'common'\n ]);\n $group_cell .= Html::hidden(\"ldap_import_type[$dn_index]\", [\n 'value' => $search_type,\n 'data-glpicore-ma-tags' => 'common'\n ]);\n if (Session::isMultiEntitiesMode()) {\n $group_cell .= Html::hidden(\"ldap_import_recursive[$dn_index]\", [\n 'value' => 0,\n 'data-glpicore-ma-tags' => 'common'\n ]);\n }\n $group_cell .= htmlescape($group);\n $entry['group'] = $group_cell;\n $entry['group_dn'] = $group_dn;\n if (Session::isMultiEntitiesMode()) {\n $entry['entity'] = Entity::dropdown([\n 'value' => $entity,\n 'name' => \"ldap_import_entities[$dn_index]\",\n 'specific_tags' => ['data-glpicore-ma-tags' => 'common'],\n 'display' => false,\n ]);\n $entry['child_entities'] = Html::getCheckbox([\n 'name' => \"ldap_import_recursive[$dn_index]\",\n 'massive_tags' => 'select_item_child_entities',\n 'specific_tags' => ['data-glpicore-ma-tags' => 'common'],\n ]);\n }\n $entries[] = $entry;\n $dn_index++;\n }\n\n $columns = [\n 'group' => Group::getTypeName(1),\n 'group_dn' => __('Group DN'),\n ];\n if (Session::isMultiEntitiesMode()) {\n $columns['entity'] = __('Destination entity');\n\n $chk_all_child_entities = Html::getCheckbox([\n 'criterion' => ['tag_for_massive' => 'select_item_child_entities']\n ]);\n $columns['child_entities'] = [\n 'label' => $chk_all_child_entities . __s('Child entities'),\n 'raw_header' => true\n ];\n }\n\n TemplateRenderer::getInstance()->display('components/datatable.html.twig', [\n 'is_tab' => false,\n 'nofilter' => true,\n 'nosort' => true,\n 'start' => $start,\n 'limit' => $_SESSION['glpilist_limit'],\n 'columns' => $columns,\n 'formatters' => [\n 'group' => 'raw_html', // Raw because there are some hidden inputs added here. The Group itself is pre-sanitized.\n 'entity' => 'raw_html', // Select HTML element\n 'child_entities' => 'raw_html' // Checkbox HTML element\n ],\n 'entries' => $entries,\n 'total_number' => $total_results,\n 'filtered_number' => $total_results,\n 'showmassiveactions' => true,\n 'massiveactionparams' => [\n 'num_displayed' => count($entries),\n 'container' => 'mass' . self::class . mt_rand(),\n 'specific_actions' => [\n __CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'import_group' => _sx('button', 'Import')\n ],\n 'extraparams' => [\n 'authldaps_id' => $_REQUEST['authldaps_id'],\n 'massive_action_fields' => [\n 'authldaps_id',\n 'dn',\n 'ldap_import_type',\n 'ldap_import_entities',\n 'ldap_import_recursive'\n ]\n ]\n ]\n ]);\n\n echo \"</div>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setOption($option, $value)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getRange($key, $start, $end) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function geoDist($key, $member1, $member2, $unit = 'm') { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function createBHT($row, $X12info, $segTer, $compEleSep)\n {\n $BHT = array();\n $BHT[0] = \"BHT\"; // Beginning of Hierarchical Transaction Segment ID\n $BHT[1] = \"0022\"; // Subscriber Structure Code\n $BHT[2] = \"13\"; // Purpose Code - This is a Request\n $BHT[3] = \"PROVTest600\"; // Submitter Transaction Identifier\n // This information is required by the information Receiver when using Real Time transactions.\n // For BATCH this can be used for optional information.\n $BHT[4] = str_pad(date('Ymd'), 8, \" \"); // Date Transaction Set Created\n $BHT[5] = str_pad(date('Hi'), 4, \" \"); // Time Transaction Set Created no space after and 1300 is plenty\n $BHT['Created'] = implode('*', $BHT); // Data Element Separator\n $BHT['Created'] = $BHT ['Created'] . $segTer;\n return trim($BHT['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($sectionId): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getSectionService()->loadSection($sectionId);\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function datefmt_get_timetype(MessageFormatter $mf) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')\n\t{\n\t\tthrow new RuntimeException('CI Error: '.$message);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function ltrimzero($v,$k) {\n\treturn ltrim($v, ' 0');\n}", "smellKey": "S1172", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function displayProgressBar($width, $percent, $options = [])\n {\n $param['title'] = __('Progress');\n $param['simple'] = false;\n $param['forcepadding'] = true;\n\n if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $param[$key] = $val;\n }\n }\n\n $title = $param['title'];\n $label = \"\";\n if ($param['simple']) {\n $label = \"$percent%\";\n $title = \"\";\n }\n\n $output = <<<HTML\n $title\n <div class=\"progress\" style=\"height: 15px; min-width: 50px;\">\n <div class=\"progress-bar bg-info\" role=\"progressbar\" style=\"width: {$percent}%;\"\n aria-valuenow=\"$percent\" aria-valuemin=\"0\" aria-valuemax=\"100\">$label</div>\n </div>\nHTML;\n\n if (!$param['forcepadding']) {\n echo $output;\n } else {\n echo Toolbox::str_pad($output, 4096);\n self::glpi_flush();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype, $main_joinparams)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '39',\n 'table' => 'glpi_devicepowersupplies',\n 'field' => 'designation',\n 'name' => static::getTypeName(1),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_items_devicepowersupplies',\n 'joinparams' => $main_joinparams\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($locationId, $prioritizedLanguages): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getLocationService()->loadLocation(\n $locationId,\n $prioritizedLanguages\n );\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function setHasNewData(bool $newData)\n {\n $this->hasNewData = false;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function _adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)\n\t{\n\t\t$aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);\n\t\tif (!empty($aRowDimensions)) {\n\t\t\tforeach ($aRowDimensions as $objRowDimension) {\n\t\t\t\t$newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);\n\t\t\t\tlist(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);\n\t\t\t\tif ($objRowDimension->getRowIndex() != $newReference) {\n\t\t\t\t\t$objRowDimension->setRowIndex($newReference);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$pSheet->refreshRowDimensions();\n\n\t\t\t$copyDimension = $pSheet->getRowDimension($beforeRow - 1);\n\t\t\tfor ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {\n\t\t\t\t$newDimension = $pSheet->getRowDimension($i);\n\t\t\t\t$newDimension->setRowHeight($copyDimension->getRowHeight());\n\t\t\t\t$newDimension->setVisible($copyDimension->getVisible());\n\t\t\t\t$newDimension->setOutlineLevel($copyDimension->getOutlineLevel());\n\t\t\t\t$newDimension->setCollapsed($copyDimension->getCollapsed());\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public static function loadValidatorMetadata(ClassMetadata $metadata)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "xatziandreoy_hackazon", "language": "php"} {"function": "public function __construct($key, $actionName, $type, stdClass $options = null, LoggerInterface $logger = null)\n {\n parent::__construct($logger);\n\n if ( empty($key) || ! is_string($key) ) {\n $msg = \"Key must be a valid non-empty string\";\n $this->logAndThrowException($msg);\n }\n\n if ( empty($actionName) || ! is_string($actionName) ) {\n $msg = \"Action name must be a valid non-empty string\";\n $this->logAndThrowException($msg);\n }\n\n $this->key = $key;\n\n $this->metadata = new stdClass;\n $this->metadata->type = $type;\n $this->metadata->creating_action = $actionName;\n $this->metadata->creation_time = date('Y-m-d H:i:s');\n $this->metadata->modifying_action = null;\n $this->metadata->modified_time = null;\n $this->metadata->state_size_bytes = 0;\n\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function create($record)\n {\n // TODO: not sure we need this anymore.\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "static function add($vars, &$errors) {\n if(!($faq = self::create($vars)))\n return false;\n\n return $faq;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function($errno, $errstr, $errfile, $errline=null, array $errcontext=null) {\n global $errline_prev, $filename, $file;\n\n //it may report error several times with different messages - send for the first one\n if($errline_prev!=$errline){\n\n $errline_prev=$errline;\n //database, record ID and name of bad image\n sendEmail(HEURIST_MAIL_TO_ADMIN, 'Cannot load image file. DB:'.HEURIST_DBNAME,\n 'File :'.$filename.' is corrupted. System message: '.$errstr);\n //ID#'.$file['ulf_ID'].'\n\n }\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function stream_cast($cast_as)\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(HttpRestRequest $request)\n {\n $this->mimeTypeHandlers = [];\n $this->defaultMimeTypeHandler = new BaseDocumentDownloader();\n $this->logger = new SystemLogger();\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ftp_systype(FTP\\Connection|resource $ftp): string|false {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function shouldSetDBConfig(InputInterface $input, OutputInterface $output)\n {\n\n return $input->getOption('reconfigure') || !file_exists(GLPI_CONFIG_DIR . '/config_db.php');\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function createST($row, $X12info, $segTer, $compEleSep)\n {\n $ST = array();\n $ST[0] = \"ST\"; // Transaction Set Header Segment ID\n $ST[1] = \"270\"; // Transaction Set Identifier Code (Inquiry Request)\n $ST[2] = \"000000003\"; // Transaction Set Control Number - Must match SE's\n $ST[3] = \"005010X279A1\"; // Standard 005010X279A1 in $ST[3]\n $ST['Created'] = implode('*', $ST); // Data Element Separator\n $ST['Created'] = $ST ['Created'] . $segTer;\n return trim($ST['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function genererGraphique($id, $type, $hauteur, $largeur, $titre, $valeurs, $nom, $nb, $total)\n {\n $couleurs = array('red', 'blue', 'green', 'pink', 'orange', 'brown', 'gray', 'lime', 'maroon', 'olive', 'navy', 'teal', 'yellow', 'purple');\n echo \"<canvas id='\" . $id . \"'></canvas>\n\t\t\t\t\t\t<script>\n\t\t\t\t\t\tvar ctx = document.getElementById('\" . $id . \"');\n\t\t\t\t\t\tctx.height = \" . $hauteur . \";\n\t\t\t\t\t\tctx.width = \" . $largeur . \";\n\t\t\t\t\t\tvar myChart = new Chart(ctx, {\n\t\t\t\t\t\t\ttype: 'doughnut',\n\t\t\t\t\t\t\tdata: { labels: [\";\n $i = 0;\n foreach ($valeurs as $uneStat) {\n if ($i > 0) {\n echo ',';\n }\n echo \"'\" . $uneStat[$nom] . \" : \" . $uneStat[$nb] . \" (\" . round(($uneStat[$nb] / $total) * 100) . \" %)'\";\n $i++;\n }\n echo \"],\n\t\t\t\t\t\t\t\tdatasets: [{ label: '',\n\t\t\t\t\t\t\t\t\tdata: [\";\n $i = 0;\n foreach ($valeurs as $uneStat) {\n if ($i > 0) {\n echo ',';\n }\n echo \"'\" . $uneStat[$nb] . \"'\";\n $i++;\n }\n echo \"], backgroundColor: [\";\n $i = 0;\n foreach ($valeurs as $uneStat) {\n if ($i > 0) {\n echo ',';\n }\n echo \"'\" . $couleurs[$i] . \"'\";\n $i++;\n }\n echo \"]\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toptions: { responsive: true,\n\t\t\t\t\t\t\t\tlegend: { position: 'top' },\n\t\t\t\t\t\t\t\ttitle: { display: false, text: '\" . $titre . \"' }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t</script>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function (mixed $value) {\n return null;\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function assessment_intake_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n print \"Assessment Intake Report\";\n $data = formFetch(\"form_assessment_intake\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function replaceRefPlaceholdersInParameters(array $parameters, array $placeholders, string $controller): array\n {\n $new_parameters = $parameters;\n foreach ($new_parameters as &$parameter) {\n $is_array = isset($parameter['schema']['items']['$ref']);\n if (!$is_array && !isset($parameter['schema']['$ref'])) {\n continue;\n }\n $original_ref = $is_array ? $parameter['schema']['items']['$ref'] : $parameter['schema']['$ref'];\n $new_ref = $original_ref;\n foreach ($placeholders as $placeholder_name => $placeholder_value) {\n if (str_contains($original_ref, '{' . $placeholder_name . '}')) {\n $new_ref = str_replace('{' . $placeholder_name . '}', $placeholder_value, $new_ref);\n }\n if ($is_array) {\n $parameter['schema']['items']['$ref'] = $new_ref;\n } else {\n $parameter['schema']['$ref'] = $new_ref;\n }\n }\n }\n unset($parameter);\n return $new_parameters;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function showInstantiationForm(NetworkPort $netport, $options, $recursiveItems)\n {\n echo \"<div class='alert alert-info'>\" . __s('No options available for this port type.') . \"</div>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function isMirrored ($codepoint ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($app, $parameters) {\n $asn = $parameters['asn'] ?? '?';\n $mock = \\Mockery::mock(\\LibreNMS\\Util\\AutonomousSystem::class);\n $mock->shouldReceive('name')->withAnyArgs()->zeroOrMoreTimes()->andReturnUsing(function () use ($asn) {\n return \"AS$asn-MOCK-TEXT\";\n });\n\n return $mock;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function parseMessage($locale, $pattern, $source) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, array $params = []): void\n {\n if (!$omitMandatoryCheck && $this->getMandatory() && $this->isEmpty($data)) {\n throw new Model\\Element\\ValidationException('Empty mandatory field [ ' . $this->getName() . ' ]');\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function delete(User $user, CustomMap $customMap): bool\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function (ContainerInterface $c): IRequestId {\n\t\t\treturn new RequestId(\n\t\t\t\t$_SERVER['UNIQUE_ID'] ?? '',\n\t\t\t\t$this->get(ISecureRandom::class)\n\t\t\t);\n\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function (Content $parentFolder): Filter {\n return (new Filter())\n ->withCriterion(\n new Criterion\\RemoteId(TestContentProvider::CONTENT_REMOTE_IDS['no-location'])\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "function (string $identityId, Response $response, Database $dbForProject, Event $events, Delete $deletes) {\n\n $identity = $dbForProject->getDocument('identities', $identityId);\n\n if ($identity->isEmpty()) {\n throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);\n }\n\n $dbForProject->deleteDocument('identities', $identityId);\n\n return $response->noContent();\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function match(string $regexp, int $flags = 0, int $offset = 0): array\n {\n $match = ((\\PREG_PATTERN_ORDER | \\PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match';\n\n if ($this->ignoreCase) {\n $regexp .= 'i';\n }\n\n set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });\n\n try {\n if (false === $match($regexp.'u', $this->string, $matches, $flags | \\PREG_UNMATCHED_AS_NULL, $offset)) {\n $lastError = preg_last_error();\n\n foreach (get_defined_constants(true)['pcre'] as $k => $v) {\n if ($lastError === $v && '_ERROR' === substr($k, -6)) {\n throw new RuntimeException('Matching failed with '.$k.'.');\n }\n }\n\n throw new RuntimeException('Matching failed with unknown error code.');\n }\n } finally {\n restore_error_handler();\n }\n\n return $matches;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function ($o) { return ['second']; }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (string $databaseId, string $collectionId, array $args) {\n return \"/v1/databases/$databaseId/collections/$collectionId/documents\";\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function write($data) {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "protected function destroy_image_object($file_path)\n {\n // nothing to do\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($search, $limit, $offset) {\n\t\t\t\tswitch ($offset) {\n\t\t\t\t\tcase 0: return ['user3' => $this->getTestUser('user3'),\n\t\t\t\t\t\t'user33' => $this->getTestUser('user33')];\n\t\t\t\t\tcase 2: return ['user333' => $this->getTestUser('user333')];\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "#[Route(path: '/User/Me/Emails/Default', methods: ['GET'], middlewares: [ResultFormatterMiddleware::class])]\n #[RouteVersion(introduced: '2.0')]\n #[Doc\\Route(\n description: 'Get the default email address for the current user',\n responses: [\n ['schema' => 'EmailAddress']\n ]\n )]\n public function getMyDefaultEmail(Request $request): Response\n {\n $emails = $this->getEmailDataForUser($this->getMyUserID());\n foreach ($emails as $email) {\n if ($email['is_default']) {\n return new JSONResponse($email);\n }\n }\n return self::getNotFoundErrorResponse();\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype, $main_joinparams)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '114',\n 'table' => 'glpi_deviceharddrives',\n 'field' => 'designation',\n 'name' => sprintf(__('%1$s: %2$s'), self::getTypeName(1), __('Name')),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_items_deviceharddrives',\n 'joinparams' => $main_joinparams\n ]\n ]\n ];\n\n $tab[] = [\n 'id' => '115',\n 'table' => 'glpi_items_deviceharddrives',\n 'field' => 'capacity',\n 'name' => sprintf(__('%1$s: %2$s'), self::getTypeName(1), __('Capacity by default')),\n 'unit' => 'auto',\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'number',\n 'width' => 1000,\n 'massiveaction' => false,\n 'joinparams' => $main_joinparams,\n 'computation' => '(' .\n QueryFunction::sum('TABLE.capacity') . ' / ' .\n QueryFunction::count('TABLE.id') . ') * ' .\n QueryFunction::count(expression: 'TABLE.id', distinct: true),\n 'nometa' => true, // cannot GROUP_CONCAT a SUM\n ];\n\n $tab[] = [\n 'id' => '116',\n 'table' => 'glpi_deviceharddrivetypes',\n 'field' => 'name',\n 'name' => sprintf(__('%1$s: %2$s'), self::getTypeName(1), _n('Type', 'Types', 1)),\n 'massiveaction' => false,\n 'datatype' => 'dropdown',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => self::getTable(),\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => Item_DeviceHardDrive::getTable(),\n 'joinparams' => ['jointype' => 'itemtype_item']\n ]\n ]\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($request) use ($options) {\n return $this->auth_options = array_merge_recursive($this->auth_options, $options);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function blPop(array $keys, $timeout) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function __construct($id = \"\", $prefix = \"\")\n {\n $this->id = $id;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function createSE($row, $segmentcount, $X12info, $segTer, $compEleSep)\n {\n $SE = array();\n $SE[0] = \"SE\"; // Transaction Set Trailer Segment ID\n $SE[1] = $segmentcount; // Segment Count\n $SE[2] = \"000000003\"; // Transaction Set Control Number - Must match ST's\n $SE['Created'] = implode('*', $SE); // Data Element Separator\n $SE['Created'] = $SE['Created'] . $segTer;\n return trim($SE['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (TerminateEvent $event) use (\n $cache, $eventDispatcher, $filesystem\n ) {\n // we need to clear the cache with a delay, because the cache is used by messenger:stop-workers\n // to send the stop signal to all worker processes\n sleep(2);\n $this->clearPimcoreCache($cache, $eventDispatcher, $filesystem);\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "protected function buildErrorDataSeries(\n $trace,\n &$data_description,\n &$legend,\n $error_color,\n &$yAxisDataObject,\n $formattedDataSeriesName,\n $yAxisIndex,\n $semDecimals,\n $decimals,\n $zIndex\n ) {\n\n $std_err_labels_enabled = property_exists($data_description, 'std_err_labels') && $data_description->std_err_labels;\n // build error data series and add it to chart\n if(($data_description->std_err == 1 || $std_err_labels_enabled) && $data_description->display_type != 'pie')\n {\n $stderr = array();\n $dataLabels = array();\n $errorLabels = array();\n $errorCount = $yAxisDataObject->getErrorCount();\n for($i = 0; $i < $errorCount; $i++)\n {\n // build the error bar and set for display\n $v = $yAxisDataObject->getValue($i);\n $e = $yAxisDataObject->getError($i);\n $stderr[] = $e;\n $errorLabels[] = isset($e) ? '+/- ' . number_format($e, $semDecimals, '.', ',') : '+/-' . number_format(0, $semDecimals, '.', ',');\n $dataLabels[] = isset($v) ? number_format($v, $decimals, '.', ',') . ' [' . $errorLabels[$i] . ']': (isset($e) ? $errorLabels[$i] : '');\n }\n\n // -- set error dataseries name and visibility --\n $dsn = 'Std Err: '.$formattedDataSeriesName;\n\n // update the name of the dataseries:\n $lookupDataSeriesName = $dsn;\n if(isset($legend->{$dsn}))\n {\n $config = $legend->{$dsn};\n if(isset($config->title))\n {\n $lookupDataSeriesName = $config->title;\n }\n }\n $visible = true;\n if(isset($data_description->visibility) && isset($data_description->visibility->{$dsn}))\n {\n $visible = $data_description->visibility->{$dsn};\n }\n\n // create the data series description:\n $error_trace = array_merge($trace, array(\n 'name' => $lookupDataSeriesName,\n 'otitle' => $dsn,\n 'datasetId' => $data_description->id,\n 'color'=> $error_color,\n 'marker' => array(\n 'color' => $error_color,\n 'line' => array(\n 'width' => 1,\n 'color' => $error_color,\n ),\n ),\n 'line' => array(\n 'color' => $error_color,\n ),\n 'hovertext' => $errorLabels,\n 'mode' => $data_description->display_type == 'scatter' ? 'markers' : 'lines',\n 'text' => array(),\n 'hovertemplate' => '<b> %{hovertext} </b>',\n 'visible' => $visible,\n 'showlegend' => true,\n 'legendgroup' => null,\n 'connectgaps' => false,\n 'legendrank' => $trace['legendrank'] + 1,\n 'traceorder' => $trace['legendrank'] - 1,\n 'isRestrictedByRoles' => $data_description->restrictedByRoles,\n ));\n\n $error_y = array(\n 'type' => 'data',\n 'array' => $stderr,\n 'arrayminus' => $stderr,\n 'symmetric' => false,\n 'color' => $error_color\n );\n\n if ($error_trace['type'] == 'area') {\n $error_trace['fill'] = $trace['fill'];\n // Referenced https://stackoverflow.com/questions/15202079/convert-hex-color-to-rgb-values-in-php\n // for idea\n list($r, $g, $b) = sscanf($trace['marker']['color'], '#%02x%02x%02x');\n $a = 0.4;\n $fillColor = 'rgba(' . $r . ',' . $g . ',' . $b . ',' . $a . ')';\n $error_trace['fillcolor'] = $fillColor;\n if ($data_description->combine_type=='stack') {\n $error_trace['stackgroup'] = 'two';\n $error_trace['stackgaps'] = 'interpolate';\n }\n }\n\n if ($trace['type'] == 'bar') {\n $this->_chart['layout']['barmode'] = 'overlay';\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'x unified';\n\n if ($this->_swapXY) {\n $this->_chart['layout']['hovermode'] = $this->_hideTooltip ? false : 'y unified';\n }\n\n if ($data_description->combine_type=='side') {\n $this->_chart['layout']['barmode'] = 'group';\n }\n if ($data_description->combine_type=='stack') {\n $error_trace['y'] = array_fill(0, count($error_trace['y']), 0);\n for ($i = 0; $i < count($errorLabels); $i++) {\n if (!isset($errorLabels[$i])) {\n $error_trace['y'][$i] = null;\n }\n }\n $this->_chart['layout']['barmode'] = 'stack';\n }\n }\n\n if (isset($trace['visible']) && $trace['visible'] != 1) {\n $error_trace['visible'] = 'legendonly';\n }\n\n if(!$data_description->log_scale && $data_description->std_err)\n {\n if ($visible == 1) {\n $idx = count($this->_chart['data']) - 1;\n if ($this->_swapXY) {\n $this->_chart['data'][$idx]['error_x'] = $error_y;\n } else {\n $this->_chart['data'][$idx]['error_y'] = $error_y;\n }\n }\n $this->_chart['data'][] = $error_trace;\n }\n\n return array('data_labels' => $dataLabels, 'error_labels' => $errorLabels);\n } // if not pie\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function ($type, $msg) {\n throw new TransportException(sprintf('Connection could not be established with host \"%s\": ', $this->url).$msg);\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE)\n\t{\n\t\t// Create XML writer\n\t\t$objWriter = null;\n\t\tif ($this->getParentWriter()->getUseDiskCaching()) {\n\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());\n\t\t} else {\n\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);\n\t\t}\n\n\t\t// XML header\n\t\t$objWriter->startDocument('1.0','UTF-8','yes');\n\n\t\t// xdr:wsDr\n\t\t$objWriter->startElement('xdr:wsDr');\n\t\t$objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');\n\t\t$objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');\n\n\t\t\t// Loop through images and write drawings\n\t\t\t$i = 1;\n\t\t\t$iterator = $pWorksheet->getDrawingCollection()->getIterator();\n\t\t\twhile ($iterator->valid()) {\n\t\t\t\t$this->_writeDrawing($objWriter, $iterator->current(), $i);\n\n\t\t\t\t$iterator->next();\n\t\t\t\t++$i;\n\t\t\t}\n\n\t\t\tif ($includeCharts) {\n\t\t\t\t$chartCount = $pWorksheet->getChartCount();\n\t\t\t\t// Loop through charts and write the chart position\n\t\t\t\tif ($chartCount > 0) {\n\t\t\t\t\tfor ($c = 0; $c < $chartCount; ++$c) {\n\t\t\t\t\t\t$this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t$objWriter->endElement();\n\n\t\t// Return\n\t\treturn $objWriter->getData();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "protected function updateExistingUser(IUser $user, array $data, array $oldData): void {\n\t\t$uid = $user->getUID();\n\t\t$jsonEncodedData = $this->prepareJson($data);\n\t\t$query = $this->connection->getQueryBuilder();\n\t\t$query->update($this->table)\n\t\t\t->set('data', $query->createNamedParameter($jsonEncodedData))\n\t\t\t->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))\n\t\t\t->executeStatement();\n\n\t\t$this->deleteUserData($user);\n\t\t$this->writeUserData($user, $data);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($server, $workerId) {\n Console::success('Starting reload...');\n}", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "static function is_phone($phone, &$error='') {\n /* We're not really validating the phone number but just making sure it doesn't contain illegal chars and of acceptable len */\n $stripped=preg_replace(\"(\\(|\\)|\\-|\\.|\\+|[ ]+)\",\"\",$phone);\n return (!is_numeric($stripped) || ((strlen($stripped)<7) || (strlen($stripped)>16)))?false:true;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function escape_ical(string $string, string $charset): string\n\t{\n\t\treturn TextUtil::escape_ical($string);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries)\n\t{\n\t\t$objWriter->startElement('c:catAx');\n\n\t\t\tif ($id1 > 0) {\n\t\t\t\t$objWriter->startElement('c:axId');\n\t\t\t\t\t$objWriter->writeAttribute('val', $id1);\n\t\t\t\t$objWriter->endElement();\n\t\t\t}\n\n\t\t\t$objWriter->startElement('c:scaling');\n\t\t\t\t$objWriter->startElement('c:orientation');\n\t\t\t\t\t$objWriter->writeAttribute('val', \"minMax\");\n\t\t\t\t$objWriter->endElement();\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:delete');\n\t\t\t\t$objWriter->writeAttribute('val', 0);\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:axPos');\n\t\t\t\t$objWriter->writeAttribute('val', \"b\");\n\t\t\t$objWriter->endElement();\n\n\t\t\tif (!is_null($xAxisLabel)) {\n\t\t\t\t$objWriter->startElement('c:title');\n\t\t\t\t\t$objWriter->startElement('c:tx');\n\t\t\t\t\t\t$objWriter->startElement('c:rich');\n\n\t\t\t\t\t\t\t$objWriter->startElement('a:bodyPr');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->startElement('a:lstStyle');\n\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t$objWriter->startElement('a:p');\n\t\t\t\t\t\t\t\t$objWriter->startElement('a:r');\n\n\t\t\t\t\t\t\t\t\t$caption = $xAxisLabel->getCaption();\n\t\t\t\t\t\t\t\t\tif (is_array($caption))\n\t\t\t\t\t\t\t\t\t\t$caption = $caption[0];\n\t\t\t\t\t\t\t\t\t$objWriter->startElement('a:t');\n//\t\t\t\t\t\t\t\t\t\t$objWriter->writeAttribute('xml:space', 'preserve');\n\t\t\t\t\t\t\t\t\t\t$objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $caption ));\n\t\t\t\t\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t\t\t\t$objWriter->endElement();\n\t\t\t\t\t\t\t$objWriter->endElement();\n\t\t\t\t\t\t$objWriter->endElement();\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t$layout = $xAxisLabel->getLayout();\n\t\t\t\t\t$this->_writeLayout($layout, $objWriter);\n\n\t\t\t\t\t$objWriter->startElement('c:overlay');\n\t\t\t\t\t\t$objWriter->writeAttribute('val', 0);\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t$objWriter->endElement();\n\n\t\t\t}\n\n\t\t\t$objWriter->startElement('c:numFmt');\n\t\t\t\t$objWriter->writeAttribute('formatCode', \"General\");\n\t\t\t\t$objWriter->writeAttribute('sourceLinked', 1);\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:majorTickMark');\n\t\t\t\t$objWriter->writeAttribute('val', \"out\");\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:minorTickMark');\n\t\t\t\t$objWriter->writeAttribute('val', \"none\");\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:tickLblPos');\n\t\t\t\t$objWriter->writeAttribute('val', \"nextTo\");\n\t\t\t$objWriter->endElement();\n\n\t\t\tif ($id2 > 0) {\n\t\t\t\t\t$objWriter->startElement('c:crossAx');\n\t\t\t\t\t\t$objWriter->writeAttribute('val', $id2);\n\t\t\t\t\t$objWriter->endElement();\n\n\t\t\t\t\t$objWriter->startElement('c:crosses');\n\t\t\t\t\t\t$objWriter->writeAttribute('val', \"autoZero\");\n\t\t\t\t\t$objWriter->endElement();\n\t\t\t}\n\n\t\t\t$objWriter->startElement('c:auto');\n\t\t\t\t$objWriter->writeAttribute('val', 1);\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:lblAlgn');\n\t\t\t\t$objWriter->writeAttribute('val', \"ctr\");\n\t\t\t$objWriter->endElement();\n\n\t\t\t$objWriter->startElement('c:lblOffset');\n\t\t\t\t$objWriter->writeAttribute('val', 100);\n\t\t\t$objWriter->endElement();\n\n\t\t\tif ($isMultiLevelSeries) {\n\t\t\t\t$objWriter->startElement('c:noMultiLvlLbl');\n\t\t\t\t\t$objWriter->writeAttribute('val', 0);\n\t\t\t\t$objWriter->endElement();\n\t\t\t}\n\t\t$objWriter->endElement();\n\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function getAdditionalLoginInfo(CustomerUser $customerUser): ?string\n {\n return null;\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function intlcal_get_greatest_minimum($calendar, $field) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function escape_xml(string $string, string $charset): string\n\t{\n\t\treturn htmlspecialchars($string, ENT_XML1, 'UTF-8');\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "function ($app, $params) use ($process) {\n return $process;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "private function preenable($modId, $currentActionStatus): mixed\n {\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function doExportBrick(Concrete $object, array &$result, Objectbrick $container, Data\\Objectbricks $brickFieldDef): void\n {\n $allowedBrickTypes = $container->getAllowedBrickTypes();\n $resultContainer = [];\n foreach ($allowedBrickTypes as $brickType) {\n $brickDef = Objectbrick\\Definition::getByKey($brickType);\n $brickGetter = 'get' . ucfirst($brickType);\n $brickValue = $container->$brickGetter();\n\n if ($brickValue instanceof Objectbrick\\Data\\AbstractData) {\n $resultContainer[$brickType] = [];\n $fDefs = $brickDef->getFieldDefinitions();\n foreach ($fDefs as $fd) {\n $getter = 'get' . ucfirst($fd->getName());\n $value = $brickValue->$getter();\n if ($fd instanceof NormalizerInterface\n && $fd instanceof DataObject\\ClassDefinition\\Data) {\n $marshalledValue = $fd->normalize($value);\n $resultContainer[$brickType][$fd->getName()] = $marshalledValue;\n }\n }\n }\n }\n $result[$container->getFieldname()] = $resultContainer;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function aws_crt_event_loop_group_release(object $event_loop_group): void {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function get(string $key, mixed $default = null): mixed\n {\n return null;\n }", "smellKey": "S1172", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function clinical_notes_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $clinicalNotesService = new ClinicalNotesService();\n $records = $clinicalNotesService->getClinicalNotesForPatientForm($id, $pid, $encounter) ?? [];\n $data = array_filter($records, function ($val) {\n return $val['activity'] == ClinicalNotesService::ACTIVITY_ACTIVE;\n });\n\n $viewArgs = [\n 'notes' => $data\n ];\n\n $twig = new TwigContainer(__DIR__, $GLOBALS['kernel']);\n $t = $twig->getTwig();\n echo $t->render('templates/report.html.twig', $viewArgs);\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function clone(array $override_input = [], bool $history = true, bool $clone_as_template = false)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n if ($DB->isSlave()) {\n return false;\n }\n $new_item = new static();\n $input = $this->fields;\n $input['profiles_id'] = $override_input['profiles_id'];\n unset($input['id']);\n\n $input = $new_item->prepareInputForClone($input);\n\n $result = $DB->updateOrInsert(static::getTable(), $input, [\n 'name' => $input['name'],\n 'profiles_id' => $input['profiles_id'],\n ]);\n if ($result !== false) {\n $new_item->getFromDBByCrit([\n 'name' => $input['name'],\n 'profiles_id' => $input['profiles_id'],\n ]);\n $new_item->post_clone($this, $history);\n }\n\n return $new_item->fields['id'];\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function color ($x, $y, $paintMethod) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (Request $request, $next) use ($instance) {\n // \u83b7\u53d6\u5f53\u524d\u64cd\u4f5c\u540d\n $action = $this->actionName . $this->rule->getConfig('action_suffix');\n\n if (is_callable([$instance, $action])) {\n // \u6267\u884c\u64cd\u4f5c\u65b9\u6cd5\n $call = [$instance, $action];\n\n // \u4e25\u683c\u83b7\u53d6\u5f53\u524d\u64cd\u4f5c\u65b9\u6cd5\u540d\n $reflect = new ReflectionMethod($instance, $action);\n $methodName = $reflect->getName();\n $suffix = $this->rule->getConfig('action_suffix');\n $actionName = $suffix ? substr($methodName, 0, -strlen($suffix)) : $methodName;\n $this->request->setAction($actionName);\n\n // \u81ea\u52a8\u83b7\u53d6\u8bf7\u6c42\u53d8\u91cf\n $vars = $this->rule->getConfig('url_param_type')\n ? $this->request->route()\n : $this->request->param();\n $vars = array_merge($vars, $this->param);\n } elseif (is_callable([$instance, '_empty'])) {\n // \u7a7a\u64cd\u4f5c\n $call = [$instance, '_empty'];\n $vars = [$this->actionName];\n $reflect = new ReflectionMethod($instance, '_empty');\n } else {\n // \u64cd\u4f5c\u4e0d\u5b58\u5728\n throw new HttpException(404, 'method not exists:' . get_class($instance) . '->' . $action . '()');\n }\n\n $this->app['hook']->listen('action_begin', $call);\n\n $data = $this->app->invokeReflectMethod($instance, $reflect, $vars);\n\n return $this->autoResponse($data);\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public function getAll($searchParams)\n {\n // the only resource we have right now is the Export operation\n $resources = [\n $this->getBulkDataStatusDefinition()\n ];\n\n $bundleSearchResult = $this->fhirService->createBundle('OperationDefinition', $resources, false);\n $response = $this->createResponseForCode(StatusCode::OK);\n $response->getBody()->write(json_encode($bundleSearchResult));\n return $response;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function PHPToExcel($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) {\n\t\t$saveTimeZone = date_default_timezone_get();\n\t\tdate_default_timezone_set('UTC');\n\t\t$retValue = FALSE;\n\t\tif ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {\n\t\t\t$retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'),\n\t\t\t\t\t\t\t\t\t\t\t\t $dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s')\n\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t} elseif (is_numeric($dateValue)) {\n\t\t\t$retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue),\n\t\t\t\t\t\t\t\t\t\t\t\t date('H',$dateValue), date('i',$dateValue), date('s',$dateValue)\n\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t}\n\t\tdate_default_timezone_set($saveTimeZone);\n\n\t\treturn $retValue;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function intlgregcal_is_leap_year($year) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool {\n $ex = new \\RuntimeException(sprintf(\n 'Unable to open \"%s\" using mode \"%s\": %s',\n $filename,\n $mode,\n $errstr\n ));\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($dateRange, $key) use ($item) {\n return isset($dateRange['date']) && $dateRange['date']->isSameDay($item->date);\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public static function createDTP($row, $qual, $X12info, $segTer, $compEleSep)\n {\n $DTP = array();\n $DTP[0] = \"DTP\"; // Date or Time or Period Segment ID\n $DTP[1] = $qual; // Qualifier - Date of Service\n $DTP[2] = \"D8\"; // Date Format Qualifier - (D8 means CCYYMMDD)\n if ($qual == '102') {\n $DTP[3] = $row['date']; // Ins effective Date\n } else {\n switch ($X12info['x12_dtp03']) {\n case 'A':\n $dtp_date = !empty($row['pc_eventDate']) && $row['pc_eventDate'] > '20010101' ? $row['pc_eventDate'] : date(\"Ymd\");\n break;\n case 'E':\n $dtp_date = !empty($row['date']) && $row['date'] > '20010101' ? $row['date'] : date(\"Ymd\");\n break;\n default:\n $dtp_date = date(\"Ymd\");\n }\n $DTP[3] = $dtp_date; // Date of Service\n }\n $DTP['Created'] = implode('*', $DTP); // Data Element Separator\n $DTP['Created'] = $DTP['Created'] . $segTer;\n return trim($DTP['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function day_to_year(&$value, $key) {\n\t $value = $value / 365.242199;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function ftp_nb_get(FTP\\Connection|resource $ftp, string $local_filename, string $remote_filename, int $mode = FTP_BINARY, int $offset = 0): int {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function onRejected(RequestInterface $request, array $options)\n {\n return function ($reason) {\n //do nothing\n return new RejectedPromise($reason);\n };\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function intl_is_failure($error_code) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function link_to_submission($launch, $localuserid, $localcourse, $db) {\n $role = standardize_role($launch->get_roles());\n $contextid = $launch->get_platform_context_id();\n $platform_id = $launch->get_platform_id();\n $resource_link = $launch->get_resource_link();\n $target = parse_target_link($launch->get_target_link(), $db);\n $targetltiuserid = $launch->get_submission_review_user_id();\n if (empty($targetltiuserid)) {\n echo _('No target user id provided');\n exit;\n }\n if (empty($target) && function_exists('lti_can_handle_launch')) {\n if (lti_can_handle_launch($launch->get_target_link())) {\n $target = ['type'=>'ext'];\n }\n }\n if (empty($target)) {\n echo \"Error parsing requested resource\";\n exit;\n }\n\n // look to see if we already know where this link should point\n $link = $db->get_link_assoc($resource_link['id'], $contextid, $platform_id);\n if ($link === null) {\n $lineitemstr = $launch->get_lineitem();\n if ($lineitemstr !== false) {\n $link = $db->get_link_assoc_by_lineitem($lineitemstr, $localcourse->get_id());\n }\n }\n if ($link === null) {\n echo _('Cannot do a submission launch before an initial regular launch');\n exit;\n } \n // OK, we have a link at this point, so now we'll redirect to it\n if ($link->get_placementtype() == 'assess') {\n $_SESSION['ltiitemtype'] = $link->get_typenum();\n $_SESSION['ltiitemid'] = $link->get_typeid();\n $_SESSION['ltiitemver'] = $localcourse->get_UIver();\n $_SESSION['ltirole'] = strtolower($role);\n\n $targetuserid = $db->get_local_userid($launch, $role);\n if ($targetuserid == false) {\n echo 'Cannot find target student';\n exit;\n }\n\n if (empty($localcourse->get_UIver())) {\n $localcourse->set_UIver($db->get_UIver($localcourse->get_courseid()));\n }\n if ($localcourse->get_UIver() == 1) {\n $targetasid = $db->get_old_asid($targetuserid, $link->get_typeid());\n if ($targetasid == false) {\n echo _('This student does not have an assessment record yet');\n }\n header(sprintf('Location: %s/course/gb-viewasid.php?cid=%d&aid=%d&uid=%d&asid=%d',\n $GLOBALS['basesiteurl'],\n $localcourse->get_courseid(),\n $link->get_typeid(),\n $targetuserid,\n $targetasid\n ));\n } else {\n header(sprintf('Location: %s/assess2/gbviewassess.php?cid=%d&aid=%d&uid=%d',\n $GLOBALS['basesiteurl'],\n $localcourse->get_courseid(),\n $link->get_typeid(),\n $targetuserid\n ));\n }\n } else if ($link->get_placementtype() == 'course') {\n \n } else if (function_exists('lti_redirect_submissionreview') && lti_is_reviewable($link->get_placementtype())) {\n $_SESSION['ltiitemtype'] = $link->get_typenum();\n $_SESSION['ltiitemid'] = $link->get_typeid();\n $_SESSION['ltiitemver'] = $localcourse->get_UIver();\n $_SESSION['ltirole'] = strtolower($role);\n\n lti_redirect_submissionreview($link);\n } else {\n echo 'Unsupported placementtype';\n print_r($link);\n exit;\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function rawCommand($command, $arguments)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function _renderDeepestMenu(\n Container $container,\n string $ulClass,\n string $indent,\n string $innerIndent,\n ?int $minDepth,\n ?int $maxDepth,\n ?string $ulId,\n bool $addPageClassToLi,\n ?string $activeClass,\n string $parentClass,\n bool $renderParentClass\n ): string {\n if (!$active = $this->findActive($container, $minDepth - 1, $maxDepth)) {\n return '';\n }\n\n // special case if active page is one below minDepth\n if ($active['depth'] < $minDepth) {\n if (!$active['page']->hasPages()) {\n return '';\n }\n } elseif (!$active['page']->hasPages()) {\n // found pages has no children; render siblings\n $active['page'] = $active['page']->getParent();\n } elseif (is_int($maxDepth) && $active['depth'] + 1 > $maxDepth) {\n // children are below max depth; render siblings\n $active['page'] = $active['page']->getParent();\n }\n\n $attribs = [\n 'class' => $ulClass,\n 'id' => $ulId,\n ];\n\n // We don't need a prefix for the menu ID (backup)\n $skipValue = $this->_skipPrefixForId;\n $this->skipPrefixForId();\n\n $html = $indent . '<ul'\n . $this->_htmlAttribs($attribs)\n . '>'\n . $this->getEOL();\n\n // Reset prefix for IDs\n $this->_skipPrefixForId = $skipValue;\n\n /** @var Page $subPage */\n foreach ($active['page'] as $subPage) {\n if (!$this->accept($subPage)) {\n continue;\n }\n\n $liClass = '';\n if ($subPage->isActive(true) && $addPageClassToLi) {\n $liClass = $this->_htmlAttribs(\n ['class' => $activeClass . ' ' . $subPage->getClass()]\n );\n } elseif ($subPage->isActive(true)) {\n $liClass = $this->_htmlAttribs(['class' => $activeClass]);\n } elseif ($addPageClassToLi) {\n $liClass = $this->_htmlAttribs(\n ['class' => $subPage->getClass()]\n );\n }\n $html .= $indent . $innerIndent . '<li' . $liClass . '>' . $this->getEOL();\n $html .= $indent . str_repeat($innerIndent, 2) . $this->htmlify($subPage)\n . $this->getEOL();\n $html .= $indent . $innerIndent . '</li>' . $this->getEOL();\n }\n\n $html .= $indent . '</ul>';\n\n return $html;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function individual_treatment_plan_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n print \"Individual Treatment Plan\";\n $data = formFetch(\"form_individual_treatment_plan\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function questionnaire_assessments_report($pid, $encounter, $cols, $id)\n{\n $form = formFetch(\"form_questionnaire_assessments\", $id);\n if (!$form) {\n echo xlt('Nothing to report.');\n return;\n }\n $responseService = new QuestionnaireResponseService();\n try {\n $qr = json_decode($form['questionnaire_response'], true);\n if (json_last_error() !== JSON_ERROR_NONE) {\n die(xlt('Nothing to report. Parse error.'));\n }\n $html = $responseService->buildQuestionnaireResponseHtml($qr);\n echo $html;\n } catch (Exception $e) {\n echo xlt(\"Error\") . \" \" . text($e->getMessage());\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function apcu_entry($key, callable $generator, $ttl = 0){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')\n {\n $table = $this->query->getTable();\n $model = basename(str_replace('\\\\', '/', get_class($this->parent)));\n $relation = basename(str_replace('\\\\', '/', $this->model));\n $localKey = $this->localKey;\n $foreignKey = $this->foreignKey;\n $softDelete = $this->query->getOptions('soft_delete');\n\n return $this->parent->db()\n ->alias($model)\n ->whereExists(function ($query) use ($table, $model, $relation, $localKey, $foreignKey) {\n $query->table([$table => $relation])\n ->field($relation . '.' . $localKey)\n ->whereExp($model . '.' . $foreignKey, '=' . $relation . '.' . $localKey)\n ->when($softDelete, function ($query) use ($softDelete, $relation) {\n $query->where($relation . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);\n });\n });\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public static function dropdownAllTypes(CommonDBTM $item, $name)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $onlyglobal = 0;\n $entity_restrict = -1;\n $checkright = true;\n\n return Dropdown::showSelectItemFromItemtypes([\n 'items_id_name' => $name,\n 'entity_restrict' => $entity_restrict,\n 'itemtypes' => $CFG_GLPI['kb_types'],\n 'onlyglobal' => $onlyglobal,\n 'checkright' => $checkright\n ]);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setTargetsString($ignored)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "function psychiatrisch_onderzoek_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_psychiatrisch_onderzoek\", $id);\n if ($data) {\n print \"<table>\";\n\n foreach ($data as $key => $value) {\n // here we check for current ???? what ? session ?\n if (\n $key == \"id\" || $key == \"pid\" || $key == \"user\" ||\n $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" ||\n $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\"\n ) {\n continue;\n }\n\n // larry :: ??? - is this for check box or select or what ?\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n // Datum onderzoek\n if ($key == \"datum_onderzoek\") {\n print \"<tr><td><span class=bold>\" . xlt('Examination Date') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Reden van aanmelding\n if ($key == \"reden_van_aanmelding\") {\n print \"<tr><td><span class=bold>\" . xlt('Reason for Visit') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Conclusie van intake\n if ($key == \"conclusie_van_intake\") {\n print \"<tr><td><span class=bold>\" . xlt('Intake Conclusion') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Medicatie\n if ($key == \"medicatie\") {\n print \"<tr><td><span class=bold>\" . xlt('Medications') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Anamnese\n if ($key == \"anamnese\") {\n print \"<tr><td><span class=bold>\" . xlt('History') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Psychiatrisch onderzoek i.e.z.\n if ($key == \"psychiatrisch_onderzoek\") {\n print \"<tr><td><span class=bold>\" . xlt('Psychiatric Examination') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Beschrijvende conclusie\n if ($key == \"beschrijvende_conclusie\") {\n print \"<tr><td><span class=bold>\" . xlt('Conclusions') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Behandelvoorstel\n if ($key == \"behandelvoorstel\") {\n print \"<tr><td><span class=bold>\" . xlt('Treatment Plan') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // increment records counter\n $count++;\n // check if not at the end close/open new row\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct(\n\t\tGoogleClientManager $authenticator,\n\t\tProfielRepository $profielRepository\n\t) {\n\t\t$this->groepNaam = trim(\n\t\t\tInstellingUtil::lid_instelling('googleContacts', 'groepnaam')\n\t\t);\n\t\tif (empty($this->groepNaam)) {\n\t\t\t$this->groepNaam = self::DEFAULT_GROEPNAAM;\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "function function1(int $value, int $value2): ?bool\n{\n}", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public function writeVBARelationships(PHPExcel $pPHPExcel = null)\n {\n // Create XML writer\n $objWriter = null;\n if ($this->getParentWriter()->getUseDiskCaching()) {\n $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());\n } else {\n $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);\n }\n\n // XML header\n $objWriter->startDocument('1.0', 'UTF-8', 'yes');\n\n // Relationships\n $objWriter->startElement('Relationships');\n $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');\n $objWriter->startElement('Relationship');\n $objWriter->writeAttribute('Id', 'rId1');\n $objWriter->writeAttribute('Type', 'http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature');\n $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin');\n $objWriter->endElement();\n $objWriter->endElement();\n\n return $objWriter->getData();\n\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function matchUseImports(Tokens $tokens, string $className): ?string\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "#[Deprecated(replacement: '%class%->evalSha(%parametersList%)')]\n public function evaluateSha($scriptSha, $args = array(), $numKeys = 0)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function supprimerElevesDuGroupe($num,$eleves)\n\t{\n\t\t$req = '';\n\t\tforeach($eleves as $eleve) {\n\t\t\t$req .= \"UPDATE `INSCRIPTIONS_STAGE` SET `ID_GROUPE`='0' WHERE `ID_INSCRIPTIONS` = $eleve;\";\n\t\t}\n\t\t$rs = PdoBD::$monPdo->exec($req);\n\t\tif ($rs === false) {afficherErreurSQL(\"Probleme lors de la suppression de l'agent dans la base de donn&eacute;es.\", $req, PdoBD::$monPdo->errorInfo());}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function update($vars, &$errors) {\n $this->isactive = $vars['isactive'];\n $this->notes = $vars['notes'];\n return $this->save(true);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "private function getJobExecutable(Application $app, \\XDUser $user, $realm, $jobId, $action, $actionName)\n {\n $QueryClass = \"\\\\DataWarehouse\\\\Query\\\\$realm\\\\JobMetadata\";\n $query = new $QueryClass();\n\n $execInfo = $query->getJobExecutableInfo($user, $jobId);\n\n if (count($execInfo) === 0) {\n throw new Exception(\n \"Executable information unavailable for $realm $jobId\",\n 500\n );\n }\n\n return $app->json(\n $this->arraytostore(json_decode(json_encode($execInfo), true)),\n 200\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected static function decodeWeekOfMonth($value, $count, $locale)\n {\n throw new Exception\\NotImplemented(__METHOD__);\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function smarty_function_xl($params, &$smarty)\n{\n if (empty($params['t'])) {\n trigger_error(\"xl: missing 't' parameter\", E_USER_WARNING);\n return;\n } else {\n $translate = $params['t'];\n }\n\n echo xl($translate);\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function intakeverslag_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_intakeverslag\", $id);\n if ($data) {\n print \"<table>\";\n\n foreach ($data as $key => $value) {\n // here we check for current ???? what ? session ?\n if (\n $key == \"id\" || $key == \"pid\" || $key == \"user\" ||\n $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" ||\n $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\"\n ) {\n continue;\n }\n\n // larry :: ??? - is this for check box or select or what ?\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n // Intakedatum\n if ($key == \"intakedatum\") {\n print \"<tr><td><span class=bold>\" . xlt('Intake Date') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Reden van aanmelding\n if ($key == \"reden_van_aanmelding\") {\n print \"<tr><td><span class=bold>\" . xlt('Reason for Visit') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Klachten/Probleemgebieden\n if ($key == \"klachten_probleemgebieden\") {\n print \"<tr><td><span class=bold>\" . xlt('Problem List') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Hulpverlening en/of onderzoek tot nu toe\n if ($key == \"hulpverlening_onderzoek\") {\n print \"<tr><td><span class=bold>\" . xlt('Psychiatric History') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Hulpvraag en doelen\n if ($key == \"hulpvraag_en_doelen\") {\n print \"<tr><td><span class=bold>\" . xlt('Treatment Goals') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Bijzonderheden systeem\n if ($key == \"bijzonderheden_systeem\") {\n print \"<tr><td><span class=bold>\" . xlt('Specialty Systems') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Werk/ opleiding/ vrije tijdsbesteding\n if ($key == \"werk_opleiding_vrije_tijdsbesteding\") {\n print \"<tr><td><span class=bold>\" . xlt('Work/ Education/ Hobbies') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Relatie(s)/ kinderen\n if ($key == \"relatie_kinderen\") {\n print \"<tr><td><span class=bold>\" . xlt('Relation(s) / Children') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Somatische context\n if ($key == \"somatische_context\") {\n print \"<tr><td><span class=bold>\" . xlt('Somatic Context') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n /////////////////////////////////////////////////////\n // - one line entry forms\n // alcohol\n if ($key == \"alcohol\") {\n print \"<tr><td><span class=bold>\" . xlt('Alcohol') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // drugs\n if ($key == \"drugs\") {\n print \"<tr><td><span class=bold>\" . xlt('Drugs') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // roken\n if ($key == \"roken\") {\n print \"<tr><td><span class=bold>\" . xlt('Tobacco') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n ////////////////////////////////////////////////////////\n\n // Medicatie\n if ($key == \"medicatie\") {\n print \"<tr><td><span class=bold>\" . xlt('Medications') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Familieanamnese\n if ($key == \"familieanamnese\") {\n print \"<tr><td><span class=bold>\" . xlt('Family History') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Indruk/observaties\n if ($key == \"indruk_observaties\") {\n print \"<tr><td><span class=bold>\" . xlt('Assessment') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Beschrijvende conclusie\n if ($key == \"beschrijvende_conclusie\") {\n print \"<tr><td><span class=bold>\" . xlt('Conclusions') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // Behandelvoorstel\n if ($key == \"behandelvoorstel\") {\n print \"<tr><td><span class=bold>\" . xlt('Treatment Plan') . \": </span><span class=text>\" .\n nl2br(text($value)) . \"</span></td></tr>\";\n }\n\n // increment records counter\n $count++;\n // check if not at the end close/open new row\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function completeArgument($name, $value, $previous)\n {\n if ($name == 'plugin') {\n return Plugin::where('plugin_name', 'like', $value . '%')\n ->pluck('plugin_name')\n ->toArray();\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function (string $projectId, string $range, Response $response, Database $dbForConsole, Database $dbForProject, Registry $register) {\n\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $usage = [];\n if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {\n $periods = [\n '24h' => [\n 'period' => '1h',\n 'limit' => 24,\n ],\n '7d' => [\n 'period' => '1d',\n 'limit' => 7,\n ],\n '30d' => [\n 'period' => '1d',\n 'limit' => 30,\n ],\n '90d' => [\n 'period' => '1d',\n 'limit' => 90,\n ],\n ];\n\n $dbForProject->setNamespace(\"_{$project->getInternalId()}\");\n\n $metrics = [\n 'project.$all.network.requests',\n 'project.$all.network.bandwidth',\n 'project.$all.storage.size',\n 'users.$all.count.total',\n 'databases.$all.count.total',\n 'documents.$all.count.total',\n 'executions.$all.compute.total',\n 'buckets.$all.count.total'\n ];\n\n $stats = [];\n\n Authorization::skip(function () use ($dbForProject, $periods, $range, $metrics, &$stats) {\n foreach ($metrics as $metric) {\n $limit = $periods[$range]['limit'];\n $period = $periods[$range]['period'];\n\n $requestDocs = $dbForProject->find('stats', [\n Query::equal('period', [$period]),\n Query::equal('metric', [$metric]),\n Query::limit($limit),\n Query::orderDesc('time'),\n ]);\n\n $stats[$metric] = [];\n foreach ($requestDocs as $requestDoc) {\n $stats[$metric][] = [\n 'value' => $requestDoc->getAttribute('value'),\n 'date' => $requestDoc->getAttribute('time'),\n ];\n }\n\n // backfill metrics with empty values for graphs\n $backfill = $limit - \\count($requestDocs);\n while ($backfill > 0) {\n $last = $limit - $backfill - 1; // array index of last added metric\n $diff = match ($period) { // convert period to seconds for unix timestamp math\n '1h' => 3600,\n '1d' => 86400,\n };\n $stats[$metric][] = [\n 'value' => 0,\n 'date' => DateTime::formatTz(DateTime::addSeconds(new \\DateTime($stats[$metric][$last]['date'] ?? null), -1 * $diff)),\n ];\n $backfill--;\n }\n $stats[$metric] = array_reverse($stats[$metric]);\n }\n });\n\n $usage = new Document([\n 'range' => $range,\n 'requests' => $stats[$metrics[0]] ?? [],\n 'network' => $stats[$metrics[1]] ?? [],\n 'storage' => $stats[$metrics[2]] ?? [],\n 'users' => $stats[$metrics[3]] ?? [],\n 'databases' => $stats[$metrics[4]] ?? [],\n 'documents' => $stats[$metrics[5]] ?? [],\n 'executions' => $stats[$metrics[6]] ?? [],\n 'buckets' => $stats[$metrics[7]] ?? [],\n ]);\n }\n\n $response->dynamic($usage, Response::MODEL_USAGE_PROJECT);\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function imagestringup ($image, $font, $x, $y, $string, $color) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function isValid($token, string $path, string $method): bool\n\t{\n\t\treturn $this->manager->isTokenValid($token);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "function smartyDieObject($params, &$smarty)\n{\n return Tools::d($params['var']);\n}", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function setFillAlpha ($opacity) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $client_id, string $redirectURI, string $scope, string $state, Response $response) {\n\n $response->redirect($redirectURI . '?' . \\http_build_query(['code' => 'abcdef', 'state' => $state]));\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function cache_info($type = NULL)\n\t{\n\t\treturn $this->_redis->info();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function ($type, $buffer) use ($logHandle) {\n fwrite($logHandle, $buffer);\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct($search = null, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (Request $request, Response $response, Application $app) {\n $origin = $request->headers->get('Origin');\n if ($origin !== null) {\n try {\n $corsDomains = \\xd_utilities\\getConfiguration('cors', 'domains');\n if (!empty($corsDomains)){\n $allowedCorsDomains = explode(',', $corsDomains);\n if (in_array($origin, $allowedCorsDomains)) {\n // If these headers change similar updates will need to be made to the `error` section below\n $response->headers->set('Access-Control-Allow-Origin', $origin);\n $response->headers->set('Access-Control-Allow-Headers', 'x-requested-with, content-type');\n $response->headers->set('Access-Control-Allow-Credentials', 'true');\n $response->headers->set('Vary', 'Origin');\n }\n }\n } catch (\\Exception $e) {\n // this catches if the section or config item does not exist\n // in that case we just carry on\n }\n }\n if (PDODB::debugging()) {\n $debugInfo = PDODB::debugInfo();\n\n $contentType = $response->headers->get('content-type', null);\n if ('application/json' === strtolower($contentType)) {\n $content = $response->getContent();\n $jsonContent = json_decode($content);\n\n if (is_array($jsonContent)) {\n foreach ($jsonContent as $entry) {\n if (is_object($entry)) {\n $entry->debug = $debugInfo;\n break;\n }\n }\n } elseif (is_object($jsonContent)) {\n $jsonContent->debug = $debugInfo;\n }\n\n\n $response->setContent(json_encode($jsonContent));\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (\n &$wrappedObject,\n LazyLoadingInterface $proxy,\n $method,\n array $parameters,\n &$initializer\n ) use ($contentTypeId, $prioritizedLanguages): bool {\n $initializer = null;\n $wrappedObject = $this->repository->getContentTypeService()->loadContentType(\n $contentTypeId,\n $prioritizedLanguages\n );\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function sMembers($key)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')\n {\n throw new Exception('relation not support: has');\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public function pfAdd($key, array $elements)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function InsertCarePlan($care_plan_array, $pid, CarecoordinationTable $carecoordinationTable, $revapprove = 1): void\n {\n if (empty($care_plan_array)) {\n return;\n }\n\n $newid = '';\n $encounter_for_forms = null;\n $forms_encounters = null;\n $appTable = new ApplicationTable();\n $res = $appTable->zQuery(\"SELECT MAX(id) as largestId FROM `form_care_plan`\");\n foreach ($res as $val) {\n if ($val['largestId']) {\n $newid = $val['largestId'] + 1;\n } else {\n $newid = 1;\n }\n }\n\n foreach ($care_plan_array as $key => $value) {\n $plan_date_value = $value['date'] ? date(\"Y-m-d\", $this->str_to_time($value['date'])) : null;\n $end_date = $value['end_date'] ? date(\"Y-m-d H:i:s\", $this->str_to_time($value['end_date'])) : null;\n $low_date = $value['reason_date_low'] ? date(\"Y-m-d H:i:s\", $this->str_to_time($value['reason_date_low'])) : null;\n $high_date = $value['reason_date_high'] ? date(\"Y-m-d H:i:s\", $this->str_to_time($value['reason_date_high'])) : null;\n\n $encounter_for_forms = $this->findClosestEncounterWithForm(trim($plan_date_value), $pid, 'form_care_plan');\n if (empty($encounter_for_forms)) {\n $query_sel_enc = \"SELECT encounter\n FROM form_encounter\n WHERE date=? AND pid=?\";\n $res_query_sel_enc = $appTable->zQuery($query_sel_enc, array(date('Y-m-d H:i:s'), $pid));\n if ($res_query_sel_enc->count() == 0 && empty($encounter_for_forms)) {\n $res_enc = $appTable->zQuery(\"SELECT encounter\n FROM form_encounter\n WHERE pid=?\n ORDER BY id DESC\n LIMIT 1\", array($pid));\n $res_enc_cur = $res_enc->current();\n $encounter_for_forms = $res_enc_cur['encounter'];\n } else {\n foreach ($res_query_sel_enc as $value2) {\n $encounter_for_forms = $value2['encounter'];\n }\n }\n }\n\n if (!empty($forms_encounters) && count($forms_encounters ?? []) > 0) {\n if (!isset($forms_encounters[$encounter_for_forms])) {\n $res = $appTable->zQuery(\"SELECT MAX(id) as largestId FROM `form_care_plan`\");\n foreach ($res as $val) {\n if ($val['largestId']) {\n $newid = $val['largestId'] + 1;\n } else {\n $newid = 1;\n }\n }\n } else {\n $newid = $forms_encounters[$encounter_for_forms]['form_id'];\n }\n }\n\n $query_insert = \"INSERT INTO `form_care_plan` (`id`,`pid`,`groupname`,`user`,`encounter`,`activity`,`code`,`codetext`,`description`,`date`,`care_plan_type`, `date_end`, `reason_code`, `reason_description`, `reason_date_low`, `reason_date_high`, `reason_status`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\";\n $res = $appTable->zQuery($query_insert, array($newid, $pid, $_SESSION[\"authProvider\"], $_SESSION[\"authUser\"], $encounter_for_forms, 1, $value['code'], $value['text'], $value['description'], $plan_date_value, $value['plan_type'], $end_date, $value['reason_code'], $value['reason_code_text'], $low_date, $high_date, $value['reason_status'] ?? null));\n\n $forms_encounters[$encounter_for_forms] = ['enc' => $encounter_for_forms, 'form_id' => $newid, 'date' => $plan_date_value];\n }\n\n if (count($forms_encounters ?? []) > 0) {\n foreach ($forms_encounters as $k => $form) {\n $query = \"INSERT INTO forms(date,encounter,form_name,form_id,pid,user,groupname,formdir) VALUES(?,?,?,?,?,?,?,?)\";\n $appTable->zQuery($query, array(date('Y-m-d'), $k, 'Care Plan Form', $form['form_id'], $pid, $_SESSION[\"authUser\"], $_SESSION[\"authProvider\"], 'care_plan'));\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function addBlocks(\n DataObject\\Concrete $object,\n AttributeSet $result,\n array $exportAttributes = null\n ): DataObjectDataExtractor {\n $locale = str_replace('-', '_', $result->getSourceLanguage());\n if (!Tool::isValidLanguage($locale)) {\n $locale = Locale::getPrimaryLanguage($locale);\n }\n\n $fieldDefinitions = $object->getClass()->getFieldDefinitions();\n foreach ($fieldDefinitions as $fd) {\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\Block) {\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields|null $blockLocalizedFieldDefinition */\n $blockLocalizedFieldDefinition = $fd->getFieldDefinition('localizedfields');\n if ($blockLocalizedFieldDefinition) {\n $blockLocalizedFieldsDefinitions = $blockLocalizedFieldDefinition->getFieldDefinitions();\n\n /** @var array $blocks */\n $blocks = $object->get($fd->getName());\n\n if ($blocks) {\n $blockIdx = -1;\n /** @var DataObject\\Data\\BlockElement[] $blockItems */\n foreach ($blocks as $blockItems) {\n $blockIdx++;\n if ($blockItems) {\n foreach ($blockItems as $blockItem) {\n if ($blockItem->getType() == 'localizedfields') {\n /** @var DataObject\\Localizedfield $blockItemData */\n $blockItemData = $blockItem->getData();\n\n foreach ($blockLocalizedFieldsDefinitions as $blockLocalizedFieldDefinition) {\n // check allowed datatypes\n if (!in_array(\n $blockLocalizedFieldDefinition->getFieldtype(),\n self::EXPORTABLE_TAGS\n )) {\n continue;\n }\n\n $content = $blockItemData->getLocalizedValue(\n $blockLocalizedFieldDefinition->getName(),\n $locale\n );\n\n $targetContent = [];\n foreach ($result->getTargetLanguages() as $targetLanguage) {\n if (Tool::isValidLanguage($targetLanguage)) {\n $targetContent[$targetLanguage] = $blockItemData->getLocalizedValue(\n $blockLocalizedFieldDefinition->getName(),\n $targetLanguage\n );\n }\n }\n\n if (!empty($content)) {\n $name =\n $fd->getName() .\n self::BLOCK_DELIMITER . $blockIdx .\n self::BLOCK_DELIMITER . 'localizedfield' .\n self::BLOCK_DELIMITER . $blockLocalizedFieldDefinition->getName();\n\n $result->addAttribute(\n Attribute::TYPE_BLOCK,\n $name,\n $content,\n false,\n $targetContent\n );\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n return $this;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function soccer_injury_report($pid, $encounter, $cols, $id)\n{\n global $si_report_cols;\n\n $arr_gameplay = array(\n '1' => '1st Quarter',\n '2' => '2nd Quarter',\n '3' => '3rd Quarter',\n '4' => '4th Quarter',\n '5' => 'Warm Up',\n '6' => 'Extra Time',\n '7' => 'Cool Down',\n '11' => 'Training Warm Up',\n '12' => 'Training Session',\n '13' => 'Training Cool Down',\n );\n\n $arr_activity = array(\n '1' => 'Tackling',\n '2' => 'Tackled',\n '3' => 'Collision',\n '4' => 'Kicked',\n '5' => 'Use of Elbow',\n '6' => 'Hit by Ball',\n '7' => 'Other:',\n '11' => 'Passing',\n '12' => 'Shooting',\n '13' => 'Running',\n '14' => 'Dribbling',\n '15' => 'Heading',\n '16' => 'Jumping',\n '17' => 'Landing',\n '18' => 'Fall',\n '19' => 'Stretching',\n '20' => 'Twist/Turning',\n '21' => 'Throwing',\n '22' => 'Diving',\n '23' => 'Other NC:',\n );\n\n $arr_surface = array(\n '1' => 'Pitch' ,\n '2' => 'Training' ,\n '3' => 'Artificial' ,\n '4' => 'All Weather',\n '5' => 'Indoor' ,\n '6' => 'Gym' ,\n '7' => 'Other' ,\n );\n\n $arr_position = array(\n '1' => 'Defender' ,\n '2' => 'Midfield Offense',\n '3' => 'Midfield Defense',\n '4' => 'Wing Back' ,\n '5' => 'Forward' ,\n '6' => 'Striker' ,\n '7' => 'Goal Keeper' ,\n '8' => 'Starting Lineup' ,\n '9' => 'Substitute' ,\n );\n\n $arr_footwear = array(\n '1' => 'Molded Cleat' ,\n '2' => 'Detachable Cleats',\n '3' => 'Indoor Shoes' ,\n '4' => 'Turf Shoes' ,\n );\n\n $arr_equip = array(\n '1' => 'Shin Pads' ,\n '2' => 'Gloves' ,\n '3' => 'Ankle Strapping',\n '4' => 'Knee Strapping' ,\n '5' => 'Bracing' ,\n '6' => 'Synthetic Cast' ,\n );\n\n $arr_side = array(\n '1' => 'Left' ,\n '2' => 'Right' ,\n '3' => 'Bilateral' ,\n '4' => 'Not Applicable',\n );\n\n $arr_removed = array(\n '1' => 'Immediately',\n '2' => 'Later' ,\n '3' => 'Not at All' ,\n );\n\n $arr_treat = array(\n '1' => 'Hospital A&amp;E Dept',\n '2' => 'General Practitioner' ,\n '3' => 'Physiotherapist' ,\n '4' => 'Nurse' ,\n '5' => 'Hospital Specialist' ,\n '6' => 'Osteopath' ,\n '7' => 'Chiropractor' ,\n '8' => 'Sports Massage Th' ,\n '9' => 'Sports Physician' ,\n );\n\n /****\n $row = sqlQuery (\"SELECT forms.date AS occdate, si.* \" .\n \"FROM forms, form_soccer_injury AS si WHERE \" .\n \"forms.formdir = 'soccer_injury' AND forms.form_id = '$id' AND \" .\n \"si.id = '$id' AND si.activity = '1'\");\n ****/\n\n $row = sqlQuery(\"SELECT form_encounter.onset_date AS occdate, si.* \" .\n \"FROM forms, form_encounter, form_soccer_injury AS si WHERE \" .\n \"forms.formdir = 'soccer_injury' AND \" .\n \"forms.form_id = ? AND \" .\n \"si.id = ? AND si.activity = '1' AND \" .\n \"form_encounter.encounter = forms.encounter AND \" .\n \"form_encounter.pid = forms.pid\", array($id));\n\n if (!$row) {\n return;\n }\n\n $si_report_cols = $cols;\n\n echo \"<table cellpadding='0' cellspacing='0'>\\n\";\n echo \" <tr>\\n\";\n\n si_report_item(\"Occurred\", substr($row['occdate'], 0, 10) . \" \" . substr($row['siinjtime'], 0, 5));\n si_report_item(\"During\", $arr_gameplay[$row['sigametime']]);\n si_report_item(\"Mechanism\", $arr_activity[$row['simechanism']] . ' ' . $row['simech_other']);\n si_report_item(\"Surface\", $arr_surface[$row['sisurface']]);\n si_report_item(\"Position\", $arr_position[$row['siposition']]);\n si_report_item(\"Footwear\", $arr_footwear[$row['sifootwear']]);\n foreach ($arr_equip as $key => $value) {\n if ($row[\"siequip_$key\"]) {\n si_report_item(\"Equipment\", $value);\n }\n }\n\n si_report_item(\"Side\", $arr_side[$row['siside']]);\n si_report_item(\"Removed\", $arr_removed[$row['siremoved']]);\n foreach ($arr_treat as $key => $value) {\n if ($row[\"sitreat_$key\"]) {\n si_report_item(\"Treatment\", $value);\n }\n }\n\n if ($row[\"sitreat_other\"]) {\n si_report_item(\"Treatment\", $row[\"sitreat_other\"]);\n }\n\n si_report_item(\"To Return\", $row['sinoreturn'] ? \"No\" : \"Yes\");\n\n echo \" </tr>\\n\";\n echo \"</table>\\n\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function setACL(array $acl)\n {\n throw new \\Sabre\\DAV\\Exception\\Forbidden('Setting ACL is not supported on this node');\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function reset_module($modId, $currentActionStatus): mixed\n {\n $rtn = true;\n $modService = new ModuleService();\n $logMessage = ''; // Initialize an empty string to store log messages\n\n if (!$modService::getModuleState($modId)) {\n $sql = \"DELETE FROM `user_settings` WHERE `setting_label` LIKE 'global:weno%'\";\n $rtn = sqlQuery($sql);\n $logMessage .= \"DELETE FROM `user_settings`: \" . (empty($rtn) ? \"Success\" : \"Failed\") . \"\\n\";\n\n $sql = \"DELETE FROM `globals` WHERE `gl_name` LIKE 'weno%'\";\n $rtn = sqlQuery($sql);\n $logMessage .= \"DELETE FROM `globals`: \" . (empty($rtn) ? \"Success\" : \"Failed\") . \"\\n\";\n\n $sql = \"DROP TABLE IF EXISTS `weno_pharmacy`\";\n $rtn = sqlQuery($sql);\n $logMessage .= \"DROP TABLE `weno_pharmacy`: \" . (empty($rtn) ? \"Success\" : \"Failed\") . \"\\n\";\n\n $sql = \"DROP TABLE IF EXISTS `weno_assigned_pharmacy`\";\n $rtn = sqlQuery($sql);\n $logMessage .= \"DROP TABLE `weno_assigned_pharmacy`: \" . (empty($rtn) ? \"Success\" : \"Failed\") . \"\\n\";\n\n $sql = \"DROP TABLE IF EXISTS `weno_download_log`\";\n $rtn = sqlQuery($sql);\n $logMessage .= \"DROP TABLE `weno_download_log`: \" . (empty($rtn) ? \"Success\" : \"Failed\") . \"\\n\";\n\n error_log(text($logMessage));\n }\n\n // return log messages to the MM to show user.\n return text($logMessage);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function whereIn($column, $values, $boolean = 'and', $not = false)\n {\n if ($column == 'id') {\n $this->ids($values);\n\n return $this;\n }\n\n throw new \\Exception('whereIn function has been defined only for IDS at the API Query Builder');\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "private function _listdevices($params)\n {\n $devices = Device::hasAccess($this->user['user'])->pluck('hostname');\n\n $msg = $devices->implode(', ');\n\n return $this->respond($msg ?: 'Nothing to show..?');\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function (string $databaseId, string $collectionId, array $args) {\n return [ 'queries' => $args['queries']];\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function imagepng ($image, $filename = null, $quality = null, $filters = null) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getTemplateID(\n TemplateFieldConfig $config,\n AnswersSet $answers_set,\n ): ?int {\n return match ($this) {\n self::DEFAULT_TEMPLATE => null, // Use default template\n self::SPECIFIC_TEMPLATE => $config->getSpecificTemplateID()\n };\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function check_boolean(Shape $shape, $value)\n {\n if (!is_bool($value)) {\n $this->addError('must be a boolean. Found '\n . Aws\\describe_type($value));\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setSourceEncoding($encoding) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($req, $res) {\n $res->json([\n 'v2Woks' => true\n ]);\n}", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function post_updateItem($history = true)\n {\n if (count($this->updates) > 0) {\n UserMention::handleUserMentions($this);\n }\n\n // Clear filter on itemtype change\n if (\n $this instanceof FilterableInterface\n && $this->getItemtypeField() !== null\n && in_array($this->getItemtypeField(), $this->updates)\n ) {\n $this->deleteFilter();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private static function initialize($fields_correspondence=null)\n{\n if (self::$initialized) {return;}\n\n global $system;\n self::$system = $system;\n self::$mysqli = $system->getMysqli();\n self::$initialized = true;\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function showConfig(User $user, ServiceTemplate $template): bool\n {\n return $user->isAdmin();\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function showItemtype($ID, $value = 0)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n //Criteria already added : only display the selected itemtype\n if ($ID > 0) {\n if ($item = getItemForItemtype($this->fields['itemtype'])) {\n echo $item::getTypeName();\n }\n echo \"<input type='hidden' name='itemtype' value='\" . htmlescape($this->fields['itemtype']) . \"'>\";\n } else {\n $options = [];\n //Add criteria : display dropdown\n foreach ($CFG_GLPI['unicity_types'] as $itemtype) {\n if ($item = getItemForItemtype($itemtype)) {\n if ($item::canCreate()) {\n $options[$itemtype] = $item::getTypeName(1);\n }\n }\n }\n asort($options);\n $rand = Dropdown::showFromArray('itemtype', $options, ['display_emptychoice' => true]);\n\n $params = ['itemtype' => '__VALUE__',\n 'id' => $ID\n ];\n Ajax::updateItemOnSelectEvent(\n \"dropdown_itemtype$rand\",\n \"span_fields\",\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownUnicityFields.php\",\n $params\n );\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (&$wrappedObject, LazyLoadingInterface $proxy, $method, array $parameters, &$initializer) {\n $initializer = null;\n $wrappedObject = new ConfigWrapper($this->aggregator->getConfig());\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "public static function getURLContent($url, &$msgerr = null, $rec = 0)\n {\n $curl_error = null;\n $content = self::callCurl($url, [], $msgerr, $curl_error, true);\n return $content;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function sMembers($key) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function touch ($key, $expiration = 0) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function numfmt_get_error_message(NumberFormatter $fmt, $nf) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function needEscaping(Environment $env)\n {\n if (\\count($this->statusStack)) {\n return $this->statusStack[\\count($this->statusStack) - 1];\n }\n\n return $this->defaultStrategy ? $this->defaultStrategy : false;\n }", "smellKey": "S1172", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "static function (Options $options, $value) {\n if ($value instanceof Field) {\n $value = $value->fieldDefIdentifier;\n }\n\n return $value;\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected static function getMailHandler($ident, array $conf)\n {\n $mailLogLevel\n = isset($conf['mailLogLevel'])\n ? $conf['mailLogLevel']\n : self::getDefaultLogLevel('mail');\n\n $from\n = isset($conf['emailFrom'])\n ? $conf['emailFrom']\n : self::getConfiguration('email_from');\n\n $to\n = isset($conf['emailTo'])\n ? $conf['emailTo']\n : self::getConfiguration('email_to');\n\n $subject\n = isset($conf['emailSubject'])\n ? $conf['emailSubject']\n : self::getConfiguration('email_subject');\n\n $maxColumnWidth = array_key_exists('maxColumnWidth', $conf) ? $conf['maxColumnWidth'] : 70;\n\n return new NativeMailerHandler($to, $subject, $from, self::convertToMonologLevel($mailLogLevel), true, $maxColumnWidth);\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function enable($modId, $currentActionStatus): mixed\n {\n if (empty($this->service)) {\n $this->service = new BootstrapService();\n }\n $globals = $this->service->fetchPersistedSetupSettings() ?? '';\n if (empty($globals)) {\n $globals = $this->service->getVendorGlobals();\n }\n $this->service->saveModuleListenerGlobals($globals);\n\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function CalcPlot3Dembed($funcs, $width=500, $height=500, $xmin=-2, $xmax=2, $ymin=-2, $ymax=2, $zmin=-2, $zmax=2, $xscl=1, $yscl=1, $zscl=1, $zclipmin=null,$zclipmax=null,$showbox=true,$scaleaxes=false) {\n\t$querystring = CalcPlot3Dquerystring($funcs, $xmin, $xmax, $ymin, $ymax, $zmin, $zmax, $xscl, $yscl, $zscl, $zclipmin, $zclipmax,$showbox);\n\t$out = '<div class=\"video-wrapper-wrapper\" style=\"max-width: '.Sanitize::onlyInt($width).'px\">';\n\t$aspectRatio = round(100*$height/$width,2);\n\t$out .= '<div class=\"fluid-width-video-wrapper\" style=\"padding-top:'.$aspectRatio.'%\">';\n\t$out .= '<iframe frameborder=0 scrolling=\"no\" ';\n\t//$querystring is sanitized as it's constructed\n\t$out .= 'src=\"https://c3d.libretexts.org/CalcPlot3D/dynamicFigure/index.html?'.$querystring.'\"></iframe>';\n\t$out .= '</div></div>';\n\treturn $out;\n}", "smellKey": "S1172", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n $dbAdapter = $container->get(\\Laminas\\Db\\Adapter\\Adapter::class);\n $resultSetPrototype = new ResultSet();\n $resultSetPrototype->setArrayObjectPrototype(new Syndromicsurveillance());\n $tableGateway = new TableGateway('module_menu', $dbAdapter, null, $resultSetPrototype);\n $table = new SyndromicsurveillanceTable($tableGateway);\n return $table;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function write($html_file, $save_to, $options)\n {\n $pdfwk = new Pdf($this->binaryPath);\n $pdfwk->generateFromHtml(file_get_contents($html_file), $save_to);\n\n return $pdfFilePath;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function _buildQuery(\n array $constraints = array(),\n $order = true,\n $limit = true\n ) {\n $sql = 'SELECT id, logtime, priority, message FROM log_table';\n\n $clauses = array();\n $params = array();\n\n if ($this->ident !== null) {\n $clauses[] = 'ident = ?';\n $params[] = $this->ident;\n }\n\n foreach ($constraints as $constraint) {\n list($column, $op, $value) = $constraint;\n $clauses[] = \"$column $op ?\";\n $params[] = $value;\n }\n\n if (count($clauses) > 0) {\n $sql .= ' WHERE ' . implode(' AND ', $clauses);\n }\n\n if ($limit) {\n $sql .= ' ORDER BY id DESC';\n }\n\n if ($limit) {\n $sql .= ' LIMIT 1';\n }\n\n return array($sql, $params);\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function ($a, $b, $in) {\n\t\t\t\treturn $in;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setSubstChars($chars) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function charFromName($characterName, $nameChoice = IntlChar::UNICODE_CHAR_NAME) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function function2(int $value, int $value2, int $value3, int $value4, int $value5): ?bool\n{\n}", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function edih_sort_upload($files_array, $html_out = true, $err_only = true)\n{\n //\n $prc_htm = '';\n $rmk_htm = '';\n $dirpath = csv_edih_basedir();\n //\n if (is_array($files_array) && count($files_array)) {\n // we have some files\n $p_ar = csv_parameters($type = \"ALL\");\n //\n $prc_htm .= \"<p><em>Received Files</em></p>\" . PHP_EOL;\n foreach ($files_array as $key => $val) {\n //\n $prc_htm .= \"<ul class='fupl'>\" . PHP_EOL;\n if (isset($p_ar[$key])) {\n $tp_dir = $p_ar[$key]['directory'];\n $tp_base = basename($tp_dir);\n $idx = 0;\n $prc_htm .= \"<li>type \" . text($key) . \"</li>\" . PHP_EOL;\n if (!is_array($val) || !count($val)) {\n $prc_htm .= \"<li>no new files</li>\" . PHP_EOL;\n continue;\n }\n\n foreach ($val as $idx => $nf) {\n // check if the file has already been stored\n // a matching file name will not be replaced\n $nfb = basename($nf);\n $testname = $tp_dir . DS . $nfb;\n $prc_htm .= \"<li>\" . text($nfb) . \"</li>\" . PHP_EOL;\n if (is_file($testname)) {\n $prc_htm .= \"<li> -- file exists</li>\" . PHP_EOL;\n } elseif (rename($nf, $testname)) {\n $iscm = chmod($testname, 0400);\n if (!$iscm) {\n // if we could write, we should be able to set permissions\n $prc_htm .= \"<li> -- file save error</li>\" . PHP_EOL;\n unlink($testname);\n }\n } else {\n $prc_htm .= \"<li> -- file save error</li>\" . PHP_EOL;\n }\n }\n } elseif ($key == 'reject') {\n $prc_htm .= \"<li><bd>Reject:</bd></li>\" . PHP_EOL;\n foreach ($val as $idx => $nf) {\n $prc_htm .= \"<li>\" . text($nf['name']) . \"</li>\" . PHP_EOL;\n $prc_htm .= \"<li> --\" . text($nf['comment']) . \"</li>\" . PHP_EOL;\n }\n } elseif ($key == 'remark') {\n $rmk_htm .= \"<p><bd>Remarks:</bd><br />\" . PHP_EOL;\n foreach ($val as $idx => $r) {\n $rmk_htm .= text($r) . \"<br />\" . PHP_EOL;\n }\n\n $rmk_htm .= \"</p>\" . PHP_EOL;\n } else {\n $prc_htm .= \"<li>\" . text($key) . \" type not stored</li>\" . PHP_EOL;\n foreach ($val as $idx => $nf) {\n $prc_htm .= \"<li>\" . text(basename($nf)) . \"</li>\" . PHP_EOL;\n }\n }\n\n $prc_htm .= \"</ul>\" . PHP_EOL;\n $prc_htm .= $rmk_htm . PHP_EOL;\n }\n } else {\n // should not happen since this function should not be called unless there are new files\n $prc_htm .= \"<ul><li>No files submitted</li></ul>\" . PHP_EOL;\n }\n\n //\n return $prc_htm;\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getPropertyEnum ($alias ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function hOneIsUnique(AcceptanceTester $I, Training $page)\n {\n $I->seeNumberOfElements('h1', 1);\n }", "smellKey": "S1172", "smellId": null, "repo": "nevercodealone_cms-symfony-sulu", "language": "php"} {"function": "public static function displayPlanningItem(array $val, $who, $type = \"\", $complete = 0)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $html = \"\";\n $rand = mt_rand();\n $users_id = \"\"; // show users_id project task\n $img = \"rdv_private.png\"; // default icon for project task\n\n if ((int) $val[\"users_id\"] !== Session::getLoginUserID()) {\n $users_id = \"<br>\" . sprintf(__('%1$s: %2$s'), __('By'), getUserName($val[\"users_id\"]));\n $img = \"rdv_public.png\";\n }\n\n $html .= \"<img src='\" . $CFG_GLPI[\"root_doc\"] . \"/pics/\" . $img . \"' alt='' title=\\\"\" .\n self::getTypeName(1) . \"\\\">&nbsp;\";\n $html .= \"<a id='project_task_\" . $val[\"id\"] . $rand . \"' href='\" .\n self::getFormURLWithID($val[\"id\"]) . \"'>\";\n\n switch ($type) {\n case \"in\":\n //TRANS: %1$s is the start time of a planned item, %2$s is the end\n $beginend = sprintf(\n __('From %1$s to %2$s'),\n date(\"H:i\", strtotime($val[\"begin\"])),\n date(\"H:i\", strtotime($val[\"end\"]))\n );\n $html .= sprintf(__('%1$s: %2$s'), $beginend, Html::resume_text($val[\"name\"], 80));\n break;\n\n case \"through\":\n $html .= Html::resume_text($val[\"name\"], 80);\n break;\n\n case \"begin\":\n $start = sprintf(__('Start at %s'), date(\"H:i\", strtotime($val[\"begin\"])));\n $html .= sprintf(__('%1$s: %2$s'), $start, Html::resume_text($val[\"name\"], 80));\n break;\n\n case \"end\":\n $end = sprintf(__('End at %s'), date(\"H:i\", strtotime($val[\"end\"])));\n $html .= sprintf(__('%1$s: %2$s'), $end, Html::resume_text($val[\"name\"], 80));\n break;\n }\n\n $html .= $users_id;\n $html .= \"</a>\";\n\n $html .= \"<div class='b'>\";\n $html .= sprintf(__('%1$s: %2$s'), __('Percent done'), $val[\"status\"] . \"%\");\n $html .= \"</div>\";\n\n // $val['content'] has already been sanitized and decoded by self::populatePlanning()\n $content = $val['content'];\n $html .= \"<div class='event-description rich_text_container'>\" . $content . \"</div>\";\n\n $parent = getItemForItemtype($val['itemtype']);\n $parent->getFromDB($val[$parent::getForeignKeyField()]);\n $html .= $parent->getLink(['icon' => true, 'forceid' => true]) . \"<br>\";\n $html .= \"<span>\" . Entity::badgeCompletenameById($parent->getEntityID()) . \"</span><br>\";\n return $html;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function __responseHeaderCallback($curl, $data) {\n\t\tif (($strlen = strlen($data)) <= 2) return $strlen;\n\t\tif (substr($data, 0, 4) == 'HTTP')\n\t\t\t$this->response->code = (int)substr($data, 9, 3);\n\t\telse {\n\t\t\tlist($header, $value) = explode(': ', trim($data), 2);\n\t\t\tif ($header == 'Last-Modified')\n\t\t\t\t$this->response->headers['time'] = strtotime($value);\n\t\t\telseif ($header == 'Content-Length')\n\t\t\t\t$this->response->headers['size'] = (int)$value;\n\t\t\telseif ($header == 'Content-Type')\n\t\t\t\t$this->response->headers['type'] = $value;\n\t\t\telseif ($header == 'ETag')\n\t\t\t\t$this->response->headers['hash'] = substr($value, 1, -1);\n\t\t\telseif (preg_match('/^x-amz-meta-.*$/', $header))\n\t\t\t\t$this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;\n\t\t}\n\t\treturn $strlen;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function ($name) {\n\t\t\t\treturn null;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function apcu_exists($keys){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function brPop(array $keys, $timeout)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function buildPrintView($frow, $currvalue, $value_allowed = true)\n {\n $tmp = '';\n if ($currvalue) {\n $urow = $this->getProviderFromId($currvalue);\n $tmp = ucwords($urow['fname'] . \" \" . $urow['lname']);\n if (empty($tmp)) {\n $tmp = \"($currvalue)\";\n }\n }\n if ($tmp === '') {\n $tmp = '&nbsp;';\n } else {\n $tmp = htmlspecialchars($tmp, ENT_QUOTES);\n }\n\n echo $tmp;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ($self, $value) {\n $wrapped = \"/\".$value.\"/iu\";\n if (false === @preg_match($value, ' ')\n && false !== @preg_match($wrapped, ' ')) {\n $value = $wrapped;\n }\n if ($value == '//iu')\n return '';\n\n return $value;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function (string $installationId, string $search, GitHub $github, Response $response, Document $project, Database $dbForConsole) {\n if (empty($search)) {\n $search = \"\";\n }\n\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if ($installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n $providerInstallationId = $installation->getAttribute('providerInstallationId');\n $privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');\n $githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');\n $github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);\n\n $page = 1;\n $perPage = 4;\n\n $owner = $github->getOwnerName($providerInstallationId);\n $repos = $github->searchRepositories($owner, $page, $perPage, $search);\n\n $repos = \\array_map(function ($repo) use ($installation) {\n $repo['id'] = \\strval($repo['id'] ?? '');\n $repo['pushedAt'] = $repo['pushed_at'] ?? null;\n $repo['provider'] = $installation->getAttribute('provider', '') ?? '';\n $repo['organization'] = $installation->getAttribute('organization', '') ?? '';\n return $repo;\n }, $repos);\n\n $repos = batch(\\array_map(function ($repo) use ($github) {\n return function () use ($repo, $github) {\n try {\n $files = $github->listRepositoryContents($repo['organization'], $repo['name'], '');\n $languages = $github->listRepositoryLanguages($repo['organization'], $repo['name']);\n\n $detectorFactory = new Detector($files, $languages);\n\n $detectorFactory\n ->addDetector(new JavaScript())\n ->addDetector(new Bun())\n ->addDetector(new PHP())\n ->addDetector(new Python())\n ->addDetector(new Dart())\n ->addDetector(new Swift())\n ->addDetector(new Ruby())\n ->addDetector(new Java())\n ->addDetector(new CPP())\n ->addDetector(new Deno())\n ->addDetector(new Dotnet());\n\n $runtime = $detectorFactory->detect();\n\n $runtimes = Config::getParam('runtimes');\n $runtimeDetail = \\array_reverse(\\array_filter(\\array_keys($runtimes), function ($key) use ($runtime, $runtimes) {\n return $runtimes[$key]['key'] === $runtime;\n }))[0] ?? '';\n\n $repo['runtime'] = $runtimeDetail;\n } catch (Throwable $error) {\n $repo['runtime'] = \"\";\n Console::warning(\"Runtime not detected for \" . $repo['organization'] . \"/\" . $repo['name']);\n }\n return $repo;\n };\n }, $repos));\n\n $repos = \\array_map(function ($repo) {\n return new Document($repo);\n }, $repos);\n\n $response->dynamic(new Document([\n 'providerRepositories' => $repos,\n 'total' => \\count($repos),\n ]), Response::MODEL_PROVIDER_REPOSITORY_LIST);\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function addPrinter($name, $manufacturer, $entity, $comment = '')\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $manufacturer_id = 0;\n if ($manufacturer != '') {\n $manufacturer_id = Dropdown::importExternal('Manufacturer', $manufacturer);\n }\n\n //If there's a printer in a parent entity with the same name and manufacturer\n $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'manufacturers_id' => $manufacturer_id,\n 'name' => $name,\n ] + getEntitiesRestrictCriteria(self::getTable(), 'entities_id', $entity, true)\n ]);\n\n if ($printer = $iterator->current()) {\n $id = $printer[\"id\"];\n } else {\n $input[\"name\"] = $name;\n $input[\"manufacturers_id\"] = $manufacturer_id;\n $input[\"entities_id\"] = $entity;\n\n $id = $this->add($input);\n }\n return $id;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function save(DataObject\\Concrete $object, string $ownertype, string $ownername, string $position, int $index, string $type = 'object'): void\n {\n throw new Exception('Needs to be implemented by child class');\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function checkIpv(CqmPatient $patient, $beginDate, $endDate)\n {\n $dobPlus42Days = date('Y-m-d 00:00:00', strtotime('+42 day', strtotime($patient->dob)));\n $dobPlus2Years = date('Y-m-d 00:00:00', strtotime('+2 year', strtotime($patient->dob)));\n $threeCount = array( Medication::OPTION_COUNT => 3 );\n if (\n Helper::checkMed(Medication::IPV, $patient, $dobPlus42Days, $dobPlus2Years, $threeCount) &&\n !( Helper::checkAllergy(Allergy::IPV, $patient, $patient->dob, $endDate) ||\n Helper::checkAllergy(Allergy::NEOMYCIN, $patient, $patient->dob, $endDate) ||\n Helper::checkAllergy(Allergy::STREPTOMYCIN, $patient, $patient->dob, $endDate) )\n ) {\n return true;\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected static function decodeWeekOfYear($value, $count, $locale)\n {\n switch ($count) {\n case 1:\n return (string) ((int) ($value->format('W')));\n case 2:\n return $value->format('W');\n default:\n throw new Exception\\ValueNotInList($count, array(1, 2));\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getAllowedTerms($defs, $defs_nonsel, $dtyID){\n\n self::initialize();\n\n $allowed_terms = null;\n\n if($dtyID==null || !@self::$dtyIDDefs[$dtyID]){ //detail type ID is not defined or terms are already found\n\n //self::$system->defineConstant('DT_RELATION_TYPE');\n\n if ( $dtyID == self::$system->getConstant('DT_RELATION_TYPE')) {\n $parent_id = 'relation';\n }elseif(is_array($defs) && count($defs)==1){\n $parent_id = $defs[0];\n }else{\n $parent_id = $defs;\n }\n if($parent_id==null || $parent_id==''){\n $allowed_terms = 'all';\n }else{\n self::getTerms();\n $allowed_terms = self::$dbs_terms->treeData($parent_id, 3);\n }\n\n self::$dtyIDDefs[$dtyID] = $allowed_terms;\n\n/*\n if ( $dtyID == DT_RELATION_TYPE) {\n //get all root terms (vocabs)\n $allowed_terms = getTermListAll(self::$mysqli, 'relation');//see dbsData.php\n self::$dtyIDDefs[$dtyID] = $allowed_terms;\n\n } else {\n\n $terms = getTermsFromFormat($defs);//see dbsData.php\n\n if (($cntTrm = count($terms)) > 0) {\n\n if ($cntTrm == 1) { //vocabulary\n $vocabId = $terms[0];\n $terms = getTermOffspringList(self::$mysqli, $vocabId);//see dbsData.php\n array_push($terms, $vocabId);\n\n }else{\n $nonTerms = getTermsFromFormat($defs_nonsel);//see dbsData.php\n if (count($nonTerms) > 0) {\n $terms = array_diff($terms, $nonTerms);\n }\n }\n if (count($terms)<1) {\n $allowed_terms = \"all\";\n }else{\n $allowed_terms = $terms;\n }\n\n if($dtyID!=null){ //keep for future use\n self::$dtyIDDefs[$dtyID] = $allowed_terms;\n }\n\n }\n }\n*/\n }else{\n //take from store\n $allowed_terms = self::$dtyIDDefs[$dtyID];\n }\n return $allowed_terms;\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function ftp_nlist(FTP\\Connection|resource $ftp, string $directory): array|false {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function day_to_millenium(&$value, $key) {\n\t $value = $value / 365242.199;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function isSuspicious($text, &$error = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getItems(DomainConfig $domainConfig, ?int $lastSeekId, int $maxResults): iterable\n {\n $brands = $this->brandRepository->getAll();\n\n foreach ($brands as $brand) {\n yield $this->luigisBoxBrandFeedItemFactory->create($brand, $domainConfig);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function _get_categories_array($patient_id, $user = '')\n {\n $categories = array();\n $sqlArray = array();\n $sql = \"SELECT c.id, c.name, c.aco_spec, d.id AS document_id, d.name AS document_name, d.type, d.url, d.docdate\"\n . \" FROM categories AS c, documents AS d, categories_to_documents AS c2d\"\n . \" WHERE c.id = c2d.category_id\"\n . \" AND c2d.document_id = d.id AND d.deleted = 0\";\n\n if (is_numeric($patient_id)) {\n if ($patient_id == \"00\") {\n // Collect documents that are not assigned to a patient\n $sql .= \" AND (d.foreign_id = 0 OR d.foreign_id IS NULL) \";\n } else {\n // Collect documents for a specific patient\n $sql .= \" AND d.foreign_id = ? \";\n array_push($sqlArray, $patient_id);\n }\n }\n\n $sql .= \" ORDER BY c.id ASC, d.docdate DESC, d.url ASC\";\n\n //echo $sql;\n $result = $this->_db->Execute($sql, $sqlArray);\n\n while ($result && !$result->EOF) {\n $categories[$result->fields['id']][$result->fields['document_id']] = $result->fields;\n $result->MoveNext();\n }\n\n return $categories;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function increment($id, $offset = 1)\n\t{\n\t\treturn TRUE;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function collator_create($locale) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $projectId, Response $response, Document $user, Database $dbForConsole, Delete $deletes) {\n $project = $dbForConsole->getDocument('projects', $projectId);\n\n if ($project->isEmpty()) {\n throw new Exception(Exception::PROJECT_NOT_FOUND);\n }\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($project);\n\n if (!$dbForConsole->deleteDocument('projects', $projectId)) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove project from DB');\n }\n\n $response->noContent();\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function update(User $user, Port $port): bool\n {\n return $user->hasGlobalAdmin();\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "private function renderContourChart($groupCount, $dimensions)\n {\n require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_contour.php');\n\n $this->renderCartesianPlotArea('intint');\n\n for ($i = 0; $i < $groupCount; ++$i) {\n $this->renderPlotContour($i);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function getHTMLTableHeader(\n $itemtype,\n HTMLTableBase $base,\n ?HTMLTableSuperHeader $super = null,\n ?HTMLTableHeader $father = null,\n array $options = []\n ) {\n\n $column_name = __CLASS__;\n\n if (isset($options['dont_display'][$column_name])) {\n return;\n }\n\n $base->addHeader($column_name, Manufacturer::getTypeName(1), $super, $father);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function buildDisplayView($frow, $currvalue): string\n {\n $urow = $this->getProviderFromId($currvalue);\n $s = text(ucwords(($urow['fname'] ?? '') . \" \" . ($urow['lname'] ?? '')));\n return $s;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function method($value, $rule)\n {\n $method = Container::get('request')->method();\n return strtoupper($rule) == $method;\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function smarty_outputfilter_trimwhitespace($source, &$smarty)\n{\n // Pull out the script blocks\n preg_match_all(\"!<script[^>]*?>.*?</script>!is\", $source, $match);\n $_script_blocks = $match[0];\n $source = preg_replace(\"!<script[^>]*?>.*?</script>!is\",\n '@@@SMARTY:TRIM:SCRIPT@@@', $source);\n\n // Pull out the pre blocks\n preg_match_all(\"!<pre[^>]*?>.*?</pre>!is\", $source, $match);\n $_pre_blocks = $match[0];\n $source = preg_replace(\"!<pre[^>]*?>.*?</pre>!is\",\n '@@@SMARTY:TRIM:PRE@@@', $source);\n \n // Pull out the textarea blocks\n preg_match_all(\"!<textarea[^>]*?>.*?</textarea>!is\", $source, $match);\n $_textarea_blocks = $match[0];\n $source = preg_replace(\"!<textarea[^>]*?>.*?</textarea>!is\",\n '@@@SMARTY:TRIM:TEXTAREA@@@', $source);\n\n // remove all leading spaces, tabs and carriage returns NOT\n // preceeded by a php close tag.\n $source = trim(preg_replace('/((?<!\\?>)\\n)[\\s]+/m', '\\1', $source));\n\n // replace textarea blocks\n smarty_outputfilter_trimwhitespace_replace(\"@@@SMARTY:TRIM:TEXTAREA@@@\",$_textarea_blocks, $source);\n\n // replace pre blocks\n smarty_outputfilter_trimwhitespace_replace(\"@@@SMARTY:TRIM:PRE@@@\",$_pre_blocks, $source);\n\n // replace script blocks\n smarty_outputfilter_trimwhitespace_replace(\"@@@SMARTY:TRIM:SCRIPT@@@\",$_script_blocks, $source);\n\n return $source;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function findWithGlobalCriteria($input)\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function checkUserHasAccessToPatient($userId, $patientUuid)\n {\n // TODO: the session should never be populated with the pid from the access token unless the user had access to\n // it. However, if we wanted an additional check or if we wanted to fire off any kind of event that does\n // patient filtering by provider / clinic we would handle that here.\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function save($id, $data, $ttl = 60, $raw = FALSE)\n\t{\n\t\treturn TRUE;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "function smartyDump($params, &$smarty)\n{\n return Tools::dump($params['var']);\n}", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function isValidTerm($defs, $defs_nonsel, $id, $dtyID){\n\n $allowed_terms = self::getAllowedTerms($defs, $dtyID);\n\n return $allowed_terms && ($allowed_terms === \"all\" || in_array($id, $allowed_terms));\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "static function agentActions($agent, $options=array()) {\n if (!$agent)\n return;\n\n require STAFFINC_DIR.'templates/tickets-actions.tmpl.php';\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function __construct(\n $realmId,\n $aggregationUnitName,\n $startDate,\n $endDate,\n $groupById = null,\n $statisticId = null,\n array $parameters = array(),\n LoggerInterface $logger = null\n ) {\n $realmId = 'Cloud';\n $schema = 'modw_cloud';\n $dataTablePrefix = 'cloudfact_by_';\n\n parent::__construct(\n $realmId,\n $aggregationUnitName,\n $startDate,\n $endDate,\n $groupById,\n null,\n $parameters\n );\n\n // The same fact table row may correspond to multiple rows in the\n // aggregate table (e.g. a job that runs over two days).\n $this->setDistinct(true);\n\n // Override values set in Query::__construct() to use the fact table rather than the\n // aggregation table prefix from the Realm configuration.\n\n $this->setDataTable($schema, sprintf(\"%s%s\", $dataTablePrefix, $aggregationUnitName));\n $this->_aggregation_unit = \\DataWarehouse\\Query\\TimeAggregationUnit::factory(\n $aggregationUnitName,\n $startDate,\n $endDate,\n sprintf(\"%s.%s\", $schema, $dataTablePrefix)\n );\n\n $dataTable = $this->getDataTable();\n $sessionlistTable = new Table($dataTable->getSchema(), $dataTable->getName() . \"_sessionlist\", \"sl\");\n\n $factTable = new Table(new Schema('modw_cloud'), \"instance\", \"i\");\n $sessionTable = new Table(new Schema('modw_cloud'), \"session_records\", \"sr\");\n\n $resourcefactTable = new Table(new Schema('modw'), 'resourcefact', 'rf');\n $this->addTable($resourcefactTable);\n\n $this->addWhereCondition(new WhereCondition(\n new TableField($dataTable, \"host_resource_id\"),\n '=',\n new TableField($resourcefactTable, \"id\")\n ));\n\n $personTable = new Table(new Schema('modw'), 'person', 'p');\n\n $this->addTable($personTable);\n $this->addWhereCondition(new WhereCondition(\n new TableField($dataTable, \"person_id\"),\n '=',\n new TableField($personTable, \"id\")\n ));\n\n $this->addField(new TableField($resourcefactTable, \"code\", 'resource'));\n $this->addField(new TableField($personTable, \"long_name\", \"name\"));\n\n $this->addField(new TableField($factTable, \"provider_identifier\", \"local_job_id\"));\n $this->addField(new TableField($factTable, \"instance_id\", \"jobid\"));\n\n $this->addTable($factTable);\n $this->addTable($sessionlistTable);\n $this->addTable($sessionTable);\n\n $this->addWhereCondition(new WhereCondition(\n new TableField($sessionlistTable, \"agg_id\"),\n \"=\",\n new TableField($dataTable, \"id\")\n ));\n $this->addWhereCondition(new WhereCondition(\n new TableField($sessionlistTable, \"session_id\"),\n \"=\",\n new TableField($sessionTable, \"session_id\")\n ));\n\n $this->addWhereCondition(new WhereCondition(\n new TableField($factTable, \"instance_id\"),\n \"=\",\n new TableField($sessionTable, \"instance_id\")\n ));\n\n $this->prependOrder(\n new \\DataWarehouse\\Query\\Model\\OrderBy(\n new TableField($factTable, 'provider_identifier'),\n 'DESC',\n 'end_time_ts'\n )\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function isMassiveActionAllowed(int $items_id): bool\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function showSummary(NotificationTemplate $template, $options = [])\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $nID = $template->getField('id');\n $canedit = Config::canUpdate();\n\n if ($canedit) {\n $twig_params = [\n 'id' => $nID,\n 'add_msg' => __('Add a new translation'),\n ];\n // language=Twig\n echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG\n <div class=\"text-center mb-3\">\n <a class=\"btn btn-primary\" href=\"{{ 'NotificationTemplateTranslation'|itemtype_form_path }}?notificationtemplates_id={{ id }}\">{{ add_msg }}</a>\n </div>\nTWIG, $twig_params);\n }\n\n $entries = [];\n foreach (\n $DB->request([\n 'FROM' => 'glpi_notificationtemplatetranslations',\n 'WHERE' => ['notificationtemplates_id' => $nID]\n ]) as $data\n ) {\n if ($this->getFromDB($data['id'])) {\n $href = self::getFormURL() . \"?id=\" . $data['id'] . \"&notificationtemplates_id=\" . $nID;\n $lang = $data['language'] !== '' ? $CFG_GLPI['languages'][$data['language']][0] : __('Default translation');\n\n $entries[] = [\n 'itemtype' => self::class,\n 'id' => $data['id'],\n 'language' => '<a href=\"' . htmlescape($href) . '\">' . htmlescape($lang) . '</a>',\n ];\n }\n }\n\n TemplateRenderer::getInstance()->display('components/datatable.html.twig', [\n 'is_tab' => true,\n 'nopager' => true,\n 'nofilter' => true,\n 'nosort' => true,\n 'columns' => [\n 'language' => __('Language'),\n ],\n 'formatters' => [\n 'language' => 'raw_html'\n ],\n 'entries' => $entries,\n 'total_number' => count($entries),\n 'filtered_number' => count($entries),\n 'showmassiveactions' => $canedit,\n 'massiveactionparams' => [\n 'num_displayed' => count($entries),\n 'container' => 'mass' . static::class . mt_rand(),\n ]\n ]);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function execute(Input $input, Output $output)\n {\n throw new \\LogicException('You must override the execute() method in the concrete command class.');\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function evaluation_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_evaluation\", $id);\n $sql = \"SELECT name from form_evaluation_checks WHERE foreign_id = ?\";\n $results = sqlQ($sql, array($id));\n $data2 = array();\n while ($row = sqlFetchArray($results)) {\n $data2[] = $row['name'];\n }\n\n $data = array_merge($data, $data2);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n if (is_numeric($key)) {\n $key = \"check\";\n }\n\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function populateRouteOptions($dataRecord, FHIRDosage $dosage)\n {\n // the route information isn't populated via the e-perscribe option or medication list anywhere as far\n // as I can tell and the FHIR code was using drug route options from the National Cancer Institute which\n // FHIR US-Core suggests we use SNOMED-CT values found here: http://hl7.org/fhir/R4/valueset-route-codes.html\n // if we end up needing these for certification / testing I've left the SQL that would need to be populated\n // here as well as the FHIR code\n /**\n * UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38288\" WHERE list_id='drug_route' AND option_id=1;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38288\" WHERE list_id='drug_route' AND option_id=6;\n\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C3829\" WHERE list_id='drug_route' AND option_id=2;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38675\" WHERE list_id='drug_route' AND option_id=3;\n\n -- it looks like 4,7,17,and 21 are empty... not sure why\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38300\" WHERE list_id='drug_route' AND option_id=5;\n -- again 7 is empty, not sure why\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38287\" WHERE list_id='drug_route' AND option_id=8;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38299\" WHERE list_id='drug_route' AND option_id=9;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C28161\" WHERE list_id='drug_route' AND option_id=10;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38276\" WHERE list_id='drug_route' AND option_id=11;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38284\" WHERE list_id='drug_route' AND option_id=12;\n -- Not sure why 13,14,15 are duplicates\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38192\" WHERE list_id='drug_route' AND option_id=13;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38192\" WHERE list_id='drug_route' AND option_id=14;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38192\" WHERE list_id='drug_route' AND option_id=15;\n\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38238\" WHERE list_id='drug_route' AND option_id=16;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38290\" WHERE list_id='drug_route' AND option_id=18;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C38305\" WHERE list_id='drug_route' AND option_id=19;\n UPDATE `list_options` SET codes=\"NCI-CONCEPT-ID:C28161\" WHERE list_id='drug_route' AND option_id=20;\n */\n// if (!empty($dataRecord['route'])) {\n//\n// list($routeValue, $routeCode) = [\n// '0' => ['', ''],\n// '1' => ['ORAL', 'C38288'],\n// '2' => ['RECTAL', 'C38295'],\n// '3' => ['CUTANEOUS', 'C38675'],\n// '4' => ['To Affected Area', ''],\n// '5' => ['SUBLINGUAL', 'C38300'],\n// '6' => ['ORAL', 'C38288'],\n// '7' => ['OD', ''],\n// '8' => ['OPHTHALMIC', 'C38287'],\n// '9' => ['SUBCUTANEOUS', 'C38299'],\n// '10' => ['INTRAMUSCULAR', 'C28161'],\n// '11' => ['INTRAVENOUS', 'C38276'],\n// '12' => ['NASAL', 'C38284'],\n// '13' => ['AURICULAR (OTIC)', 'C38192'],\n// '14' => ['AURICULAR (OTIC)', 'C38192'],\n// '15' => ['AURICULAR (OTIC)', 'C38192'],\n// '16' => ['INTRADERMAL', 'C38238'],\n// '18' => ['OTHER', 'C38290'],\n// '19' => ['TRANSDERMAL', 'C38305'],\n// '20' => ['INTRAMUSCULAR', 'C28161'],\n// ][$dataRecord['route']] ?? ['', ''];\n// $route = new FHIRCodeableConcept();\n// $routeCoding = new FHIRCoding();\n// $routeCoding->setSystem(FhirCodeSystemConstants::NCIMETA_NCI_NIH);\n// $routeCoding->setCode($routeCode);\n// $routeCoding->setDisplay($routeValue);\n// $route->addCoding($routeCoding);\n// $dosage->setRoute($route);\n// }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($curl, $header) use (&$responseHeaders) {\n $len = strlen($header);\n $header = explode(':', $header, 2);\n\n if (count($header) < 2) { // ignore invalid headers\n return $len;\n }\n\n $responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);\n\n return $len;\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct(string $globalPrefix, LoggerInterface $logger, IProfiler $profiler,\n\t\t?string $localCacheClass = null, ?string $distributedCacheClass = null, ?string $lockingCacheClass = null, string $logFile = '') {\n\t\t$this->logFile = $logFile;\n\t\t$this->globalPrefix = $globalPrefix;\n\n\t\tif (!$localCacheClass) {\n\t\t\t$localCacheClass = self::NULL_CACHE;\n\t\t}\n\t\t$localCacheClass = ltrim($localCacheClass, '\\\\');\n\t\tif (!$distributedCacheClass) {\n\t\t\t$distributedCacheClass = $localCacheClass;\n\t\t}\n\t\t$distributedCacheClass = ltrim($distributedCacheClass, '\\\\');\n\n\t\t$missingCacheMessage = 'Memcache {class} not available for {use} cache';\n\t\t$missingCacheHint = 'Is the matching PHP module installed and enabled?';\n\t\tif (!class_exists($localCacheClass) || !$localCacheClass::isAvailable()) {\n\t\t\tthrow new \\OCP\\HintException(strtr($missingCacheMessage, [\n\t\t\t\t'{class}' => $localCacheClass, '{use}' => 'local'\n\t\t\t]), $missingCacheHint);\n\t\t}\n\t\tif (!class_exists($distributedCacheClass) || !$distributedCacheClass::isAvailable()) {\n\t\t\tthrow new \\OCP\\HintException(strtr($missingCacheMessage, [\n\t\t\t\t'{class}' => $distributedCacheClass, '{use}' => 'distributed'\n\t\t\t]), $missingCacheHint);\n\t\t}\n\t\tif (!($lockingCacheClass && class_exists($lockingCacheClass) && $lockingCacheClass::isAvailable())) {\n\t\t\t// don't fall back since the fallback might not be suitable for storing lock\n\t\t\t$lockingCacheClass = self::NULL_CACHE;\n\t\t}\n\t\t$lockingCacheClass = ltrim($lockingCacheClass, '\\\\');\n\n\t\t$this->localCacheClass = $localCacheClass;\n\t\t$this->distributedCacheClass = $distributedCacheClass;\n\t\t$this->lockingCacheClass = $lockingCacheClass;\n\t\t$this->profiler = $profiler;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function createOperationOutcomeSuccess(string $resourceType, int|string $id)\n {\n $operation = self::createOperationOutcomeResource('success', 'success');\n // TODO: if we wanted to put the resource path we would do that here\n return $operation;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function testLDAPURI(?Connection &$connection): array\n {\n if (@ldap_connect($this->fields['host'], $this->fields['port'])) {\n return [\n 'success' => true,\n 'message' => __('LDAP URI check succeeded')\n ];\n } else {\n return [\n 'success' => false,\n 'message' => sprintf(__('LDAP URI was not parseable (%s:%s)'), $this->fields['host'], $this->fields['port'])\n ];\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function physical_exam_report($pid, $encounter, $cols, $id)\n{\n global $pelines;\n\n $rows = array();\n $res = sqlStatement(\"SELECT * FROM form_physical_exam WHERE forms_id = ?\", array($id));\n while ($row = sqlFetchArray($res)) {\n $rows[$row['line_id']] = $row;\n }\n\n echo \"<table cellpadding='0' cellspacing='0'>\\n\";\n\n foreach ($pelines as $sysname => $sysarray) {\n $sysnamedisp = xl($sysname);\n foreach ($sysarray as $line_id => $description) {\n $linedbrow = $rows[$line_id];\n if (\n !($linedbrow['wnl'] || $linedbrow['abn'] || $linedbrow['diagnosis'] ||\n $linedbrow['comments'])\n ) {\n continue;\n }\n\n if ($sysname != '*') { // observation line\n echo \" <tr>\\n\";\n echo \" <td class='text' align='center'>\" . ($linedbrow['wnl'] ? \"WNL\" : \"\") . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' align='center'>\" . ($linedbrow['abn'] ? \"ABNL\" : \"\") . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' nowrap>\" . text($sysnamedisp) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' nowrap>\" . text($description) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text($linedbrow['diagnosis']) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text($linedbrow['comments']) . \"</td>\\n\";\n echo \" </tr>\\n\";\n } else { // treatment line\n echo \" <tr>\\n\";\n echo \" <td class='text' align='center'>\" . ($linedbrow['wnl'] ? \"Y\" : \"\") . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' align='center'>&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' colspan='2' nowrap>\" . text($description) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text' colspan='2'>\" . text($linedbrow['comments']) . \"</td>\\n\";\n echo \" </tr>\\n\";\n }\n\n $sysnamedisp = '';\n } // end of line\n } // end of system name\n\n echo \"</table>\\n\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function isJavaIDPart ($codepoint ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function handleHelpers(array $config, ContainerBuilder $container, FileLoader $loader)\n {\n $loader->load('helpers.yml');\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "protected function runAfterBatch(InputInterface $input, OutputInterface $output, array $items): void\n {\n if ($this->input->hasOption('processes') && (int)$this->input->getOption('processes') <= 1) {\n if ($output->isVeryVerbose()) {\n $output->writeln('Collect garbage.');\n }\n Pimcore::collectGarbage();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function build(\n App $utopia,\n callable $complexity,\n callable $attributes,\n array $urls,\n array $params,\n ): GQLSchema {\n App::setResource('utopia:graphql', static function () use ($utopia) {\n return $utopia;\n });\n\n if (!empty(self::$schema)) {\n return self::$schema;\n }\n\n $api = static::api(\n $utopia,\n $complexity\n );\n //$collections = static::collections(\n // $utopia,\n // $complexity,\n // $attributes,\n // $urls,\n // $params,\n //);\n\n $queries = \\array_merge_recursive(\n $api['query'],\n //$collections['query']\n );\n $mutations = \\array_merge_recursive(\n $api['mutation'],\n //$collections['mutation']\n );\n\n \\ksort($queries);\n \\ksort($mutations);\n\n return static::$schema = new GQLSchema([\n 'query' => new ObjectType([\n 'name' => 'Query',\n 'fields' => $queries\n ]),\n 'mutation' => new ObjectType([\n 'name' => 'Mutation',\n 'fields' => $mutations\n ])\n ]);\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function (Blueprint $table) {\n if (Schema::hasColumn('printed_catalog_slugs', 'printed_publication_id')) {\n Schema::table('printed_catalog_slugs', function (Blueprint $table) {\n $table->renameColumn('printed_publication_id', 'printed_catalog_id');\n });\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function _stop_element_handler($parser, $name)\n {\n if (isset($this->current)) {\n $this->current = new BigInteger(base64_decode($this->current), 256);\n unset($this->current);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function return_code_info_test($type, $string, $limit = 20, $modes = null, $count = false)\n{\n echo \"<ol>\";\n $res = return_code_information($type, $string);\n while ($code = sqlFetchArray($res)) {\n echo \"<li>\" . $code['code_type_name'] . \":\" . $code['code'] . \":\" . $code['code_text'] . \":\" . $code['code_text_short'] . \"</li>\";\n }\n echo \"</ol>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($appid, $key, $default) {\n\t\t\t\tif ($key === 'newUser.generateUserID') {\n\t\t\t\t\treturn 'yes';\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function trans(?string $id, array $parameters = [], string $domain = null, string $locale = null): string\n {\n if (null === $id || '' === $id) {\n return '';\n }\n\n if (!isset($parameters['%count%']) || !is_numeric($parameters['%count%'])) {\n return strtr($id, $parameters);\n }\n\n $number = (float) $parameters['%count%'];\n $locale = $locale ?: $this->getLocale();\n\n $parts = [];\n if (preg_match('/^\\|++$/', $id)) {\n $parts = explode('|', $id);\n } elseif (preg_match_all('/(?:\\|\\||[^\\|])++/', $id, $matches)) {\n $parts = $matches[0];\n }\n\n $intervalRegexp = <<<'EOF'\n/^(?P<interval>\n ({\\s*\n (\\-?\\d+(\\.\\d+)?[\\s*,\\s*\\-?\\d+(\\.\\d+)?]*)\n \\s*})\n\n |\n\n (?P<left_delimiter>[\\[\\]])\n \\s*\n (?P<left>-Inf|\\-?\\d+(\\.\\d+)?)\n \\s*,\\s*\n (?P<right>\\+?Inf|\\-?\\d+(\\.\\d+)?)\n \\s*\n (?P<right_delimiter>[\\[\\]])\n)\\s*(?P<message>.*?)$/xs\nEOF;\n\n $standardRules = [];\n foreach ($parts as $part) {\n $part = trim(str_replace('||', '|', $part));\n\n // try to match an explicit rule, then fallback to the standard ones\n if (preg_match($intervalRegexp, $part, $matches)) {\n if ($matches[2]) {\n foreach (explode(',', $matches[3]) as $n) {\n if ($number == $n) {\n return strtr($matches['message'], $parameters);\n }\n }\n } else {\n $leftNumber = '-Inf' === $matches['left'] ? -\\INF : (float) $matches['left'];\n $rightNumber = is_numeric($matches['right']) ? (float) $matches['right'] : \\INF;\n\n if (('[' === $matches['left_delimiter'] ? $number >= $leftNumber : $number > $leftNumber)\n && (']' === $matches['right_delimiter'] ? $number <= $rightNumber : $number < $rightNumber)\n ) {\n return strtr($matches['message'], $parameters);\n }\n }\n } elseif (preg_match('/^\\w+\\:\\s*(.*?)$/', $part, $matches)) {\n $standardRules[] = $matches[1];\n } else {\n $standardRules[] = $part;\n }\n }\n\n $position = $this->getPluralizationRule($number, $locale);\n\n if (!isset($standardRules[$position])) {\n // when there's exactly one rule given, and that rule is a standard\n // rule, use this rule\n if (1 === \\count($parts) && isset($standardRules[0])) {\n return strtr($standardRules[0], $parameters);\n }\n\n $message = sprintf('Unable to choose a translation for \"%s\" with locale \"%s\" for value \"%d\". Double check that this translation has the correct plural options (e.g. \"There is one apple|There are %%count%% apples\").', $id, $locale, $number);\n\n if (class_exists(InvalidArgumentException::class)) {\n throw new InvalidArgumentException($message);\n }\n\n throw new \\InvalidArgumentException($message);\n }\n\n return strtr($standardRules[$position], $parameters);\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new ModuleconfigForm($container->get(\\Laminas\\Db\\Adapter\\Adapter::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getAllVariants($locale) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype, $main_joinparams)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '13',\n 'table' => 'glpi_devicegraphiccards',\n 'field' => 'designation',\n 'name' => static::getTypeName(1),\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_items_devicegraphiccards',\n 'joinparams' => $main_joinparams\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function datefmt_get_calendar(MessageFormatter $mf) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function compileSearchResources($query, $resources)\n {\n return empty($resources) ? [] : ['resources' => join(',', $resources)];\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "private function getCallbacks($bk) {\n return [\n // see onClose routine for details\n 'close' => [$this, 'onClose']\n ];\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype = null)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => 'monitor',\n 'name' => self::getTypeName(Session::getPluralNumber())\n ];\n\n $tab[] = [\n 'id' => '1429',\n 'table' => Asset_PeripheralAsset::getTable(),\n 'field' => 'id',\n 'name' => _x('quantity', 'Number of monitors'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'specific_items_id_column' => 'items_id_asset',\n 'specific_itemtype_column' => 'itemtype_asset',\n 'condition' => ['NEWTABLE.' . 'itemtype_peripheral' => 'Monitor']\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setSave($save = 1)\n {\n $this->data['save'] = true;\n }", "smellKey": "S1172", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function ($model, $key) use ($ids) {\n return CollectionHelpers::collectApi($ids)->search(function ($id, $key) use ($model) {\n return $id == $model->id;\n });\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function (string $required, string $nullable, ?string $optional) {\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function must($value, $rule = null)\n {\n return !empty($value) || '0' == $value;\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public function backToStock(array $input, $history = true)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $result = $DB->update(\n static::getTable(),\n [\n 'date_out' => 'NULL',\n 'date_use' => 'NULL',\n 'printers_id' => 0\n ],\n [\n 'id' => $input['id']\n ]\n );\n return $result && ($DB->affectedRows() > 0);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($value, $key) use (&$compound) {\n $compound .= $value;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function smartyMaxWords($params, &$smarty)\n{\n Tools::displayAsDeprecated();\n $params['s'] = str_replace('...', ' ...', html_entity_decode($params['s'], ENT_QUOTES, 'UTF-8'));\n $words = explode(' ', $params['s']);\n\n foreach ($words as &$word) {\n if (Tools::strlen($word) > $params['n']) {\n $word = Tools::substr(trim(chunk_split($word, $params['n']-1, '- ')), 0, -1);\n }\n }\n\n return implode(' ', Tools::htmlentitiesUTF8($words));\n}", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function smartyTruncate($params, &$smarty)\n{\n Tools::displayAsDeprecated();\n $text = isset($params['strip']) ? strip_tags($params['text']) : $params['text'];\n $length = $params['length'];\n $sep = isset($params['sep']) ? $params['sep'] : '...';\n\n if (Tools::strlen($text) > $length + Tools::strlen($sep)) {\n $text = Tools::substr($text, 0, $length).$sep;\n }\n\n return (isset($params['encode']) ? Tools::htmlentitiesUTF8($text, ENT_NOQUOTES) : $text);\n}", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private static function _readDataFile($filename, $type=null, $validate=true){\n\n $data=null;\n try{\n // TODO: This special-casing based on a specific file name, which could be changed in an entirely\n // different part of the code, is a pretty horrible way of setting a file path. Should be passed directly\n // and setting default path should only occur where no file path is specified.\n if(strpos($filename,'websiteStarterRecords')===0 || strpos($filename,'webpageStarterRecords')===0){\n $filename = HEURIST_DIR.'hclient/widgets/cms/'.$filename;\n }elseif (!file_exists($filename)) {\n $filename = HEURIST_SCRATCH_DIR.basename($filename);\n }\n\n if(!file_exists($filename)){\n\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Import file doesn\\'t exist');\n }elseif(!is_readable($filename))\n {\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Import file is not readable. Check permissions');\n }else\n {\n\n if(isXMLfile($filename)){\n $data = self::hmlToJson($filename);\n }else{\n $content = file_get_contents($filename);\n $data = json_decode($content, true);\n }\n\n\n if($validate){\n $imp_rectypes = @$data['heurist']['database']['rectypes'];\n if($data==null || !$imp_rectypes)\n {\n if(!(count(self::$system->getError())>0)){\n self::$system->addError(HEURIST_ACTION_BLOCKED,\n 'The data file contains data which does not correspond with expectations.<br> \"Record type\" section not found. You might be trying to load a data template file.');\n }\n }\n\n\n\n\n }\n\n }\n } catch (Exception $e){\n $data = null;\n }\n\n return $data;\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($id = \"\", $prefix = \"\", InsuranceCompanyService $insuranceCompanyService = null)\n {\n $this->id = $id;\n $this->name = \"\";\n $this->_table = \"insurance_companies\";\n $phone = new PhoneNumber();\n $phone->set_type(TYPE_WORK);\n $fax = new PhoneNumber();\n $fax->set_type(TYPE_FAX);\n $this->address = new Address();\n $this->phone_numbers = array($phone, $fax);\n if ($insuranceCompanyService === null) {\n $this->InsuranceCompany = new InsuranceCompanyService();\n } else {\n $this->InsuranceCompany = $insuranceCompanyService;\n }\n $this->ins_type_code_array = $this->InsuranceCompany->getInsuranceTypesCached();\n $this->ins_claim_type_array = $this->InsuranceCompany->getInsuranceClaimTypes();\n if ($id != \"\") {\n $this->populate();\n }\n\n $this->X12Partner = new X12Partner();\n $this->cqm_sop_array = $this->InsuranceCompany->getInsuranceCqmSopCached();\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function jsonFormatProtect(&$val, $key, $type = 'encode')\n {\n if (!empty($val) && true !== $val) {\n $val = 'decode' == $type ? urldecode($val) : urlencode($val);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function intlcal_roll($calendar, $field, $amountOrUpOrDown) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(Naming $naming)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "Function GetCredentials(&$credentials,$defaults,&$interactions)\n\t{\n\t\tReset($credentials);\n\t\t$end=(GetType($key=Key($credentials))!=\"string\");\n\t\tfor(;!$end;)\n\t\t{\n\t\t\tif(!IsSet($this->credentials[$key]))\n\t\t\t{\n\t\t\t\tif(IsSet($defaults[$key]))\n\t\t\t\t\t$credentials[$key]=$defaults[$key];\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"the requested credential \".$key.\" is not defined\";\n\t\t\t\t\treturn(SASL_NOMECH);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\t$credentials[$key]=$this->credentials[$key];\n\t\t\tNext($credentials);\n\t\t\t$end=(GetType($key=Key($credentials))!=\"string\");\n\t\t}\n\t\treturn(SASL_CONTINUE);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new \\Application\\Controller\\SoapController($container->get(\\Carecoordination\\Controller\\EncounterccdadispatchController::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function setFillOpacity ($fillOpacity) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n $dbAdapter = $container->get(\\Laminas\\Db\\Adapter\\Adapter::class);\n $table = new DocumentsTable($dbAdapter);\n return $table;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function evalSha($scriptSha, $args = array(), $numKeys = 0)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function _renderPiePlotArea($doughnut = False) {\n\t\t$this->_graph = new PieGraph(self::$_width,self::$_height);\n\n\t\t$this->_renderTitle();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function view(User $user, DeviceGroup $deviceGroup): bool\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype = null)\n {\n\n $tab = [];\n\n $tab[] = [\n 'id' => 'followup',\n 'name' => _n('Followup', 'Followups', Session::getPluralNumber())\n ];\n\n $followup_condition = '';\n if (!Session::haveRight('followup', self::SEEPRIVATE)) {\n $followup_condition = [\n 'OR' => [\n 'NEWTABLE.is_private' => 0,\n 'NEWTABLE.users_id' => Session::getLoginUserID()\n ]\n ];\n }\n\n $tab[] = [\n 'id' => '25',\n 'table' => static::getTable(),\n 'field' => 'content',\n 'name' => __('Description'),\n 'forcegroupby' => true,\n 'splititems' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ],\n 'datatype' => 'text',\n 'htmltext' => true\n ];\n\n $tab[] = [\n 'id' => '36',\n 'table' => static::getTable(),\n 'field' => 'date',\n 'name' => _n('Date', 'Dates', 1),\n 'datatype' => 'datetime',\n 'massiveaction' => false,\n 'forcegroupby' => true,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '27',\n 'table' => static::getTable(),\n 'field' => 'id',\n 'name' => _x('quantity', 'Number of followups'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '29',\n 'table' => 'glpi_requesttypes',\n 'field' => 'name',\n 'name' => RequestType::getTypeName(1),\n 'datatype' => 'dropdown',\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => static::getTable(),\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ]\n ]\n ];\n\n $tab[] = [\n 'id' => '91',\n 'table' => static::getTable(),\n 'field' => 'is_private',\n 'name' => __('Private followup'),\n 'datatype' => 'bool',\n 'forcegroupby' => true,\n 'splititems' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '93',\n 'table' => 'glpi_users',\n 'field' => 'name',\n 'name' => __('Writer'),\n 'datatype' => 'itemlink',\n 'right' => 'all',\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => static::getTable(),\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($string, $args) {\n\t\t\t\t/** \\DateTime $args */\n\t\t\t\treturn $args->format(\\DateTime::ATOM);\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function update(User $user, ServiceTemplate $template): bool\n {\n return $user->isAdmin();\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function (string $mockType) {\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function hIncrBy($key, $hashKey, $value) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function _insert_batch($table, $keys, $values)\n\t{\n\t\treturn ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function getLocale($localeType) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($value, $values) {\n if (empty($values['uuid']) && empty($values['pid'])) {\n return true; // nothing to do here if we don't have a uuid or pid, so don't run the check and let other failures happen\n }\n // if src date is null\n // if most recent target date is null\n // this is ok.\n // if most recent target date is not null\n // we need to check to make sure target type can receive src date\n\n // if src date is not null\n // if most recent target date is null || target date is the same as src date\n // this is ok as it means there are no other dates and we can easily swap\n // if most recent target date is not null\n // we need to check to make sure target type does NOT have a date that is the same as src date\n\n // hit the database to grab the most recent policy for this type\n // grab the uuid we are checking\n $uuidBytes = UuidRegistry::uuidToBytes($values['uuid']);\n $srcData = QueryUtils::fetchRecords(\"SELECT `date`,`type` FROM insurance_data WHERE uuid = ?\", [$uuidBytes]);\n if (empty($srcData)) {\n throw new InvalidValueException(\"Invalid coverage uuid\", \"Record::INVALID_RECORD_UUID\");\n }\n $srcDate = $srcData[0]['date'];\n $targetDate = QueryUtils::fetchSingleValue(\n \"SELECT `date` FROM insurance_data WHERE pid = ? AND type = ? ORDER BY date DESC LIMIT 1\",\n 'date',\n [$values['pid'], $values['type']]\n );\n if (empty($srcDate)) {\n if (!empty($targetDate)) {\n $srcTypeCanReceiveTarget = QueryUtils::fetchSingleValue(\n \"SELECT COUNT(*) AS cnt FROM insurance_data WHERE pid = ? AND type = ? AND date IS NOT NULL AND date = ?\",\n 'cnt',\n [$values['pid'], $srcData['type'], $targetDate]\n );\n if ($srcTypeCanReceiveTarget > 0) {\n throw new InvalidValueException(\"Source coverage type already has a policy with an effective date that conflicts with the target policy effective date\", \"Record::INVALID_SOURCE_POLICY_DATE\");\n }\n }\n } else {\n if (!(empty($targetDate) || $targetDate == $srcDate)) {\n $targetTypeCanReceiveSrc = QueryUtils::fetchSingleValue(\n \"SELECT COUNT(*) AS cnt FROM insurance_data WHERE pid = ? AND type = ? AND date IS NOT NULL AND date = ?\",\n 'cnt',\n [$values['pid'], $values['type'], $srcDate]\n );\n if ($targetTypeCanReceiveSrc > 0) {\n throw new InvalidValueException(\"Target coverage type already has a policy with an effective date that conflicts with the source policy effective date\", \"Record::INVALID_TARGET_POLICY_DATE\");\n }\n }\n }\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new CCDAEventsSubscriber($container->get(CcdaGenerator::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function aws_crt_signing_config_aws_set_date(int $config, int $timestamp): void {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __call($name, $arguments)\n {\n // TODO: Implement __call() method.\n return Json::create(HttpTools::FaliJson(404),'',404);\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "protected function update(array $params = []): void\n {\n $disallowedKeysInFirstLevel = ['install', 'admin', 'plugin'];\n if ($this->getParentId() == 1 && in_array($this->getKey(), $disallowedKeysInFirstLevel)) {\n throw new Exception('Key: ' . $this->getKey() . ' is not allowed in first level (root-level)');\n }\n\n // set index if null\n if ($this->getIndex() === null) {\n $this->setIndex($this->getDao()->getNextIndex());\n }\n\n if ($this->isFieldDirty('properties')) {\n // save properties\n $properties = $this->getProperties();\n $this->getDao()->deleteAllProperties();\n foreach ($properties as $property) {\n if (!$property->getInherited()) {\n $property->setDao(null);\n $property->setCid($this->getId());\n $property->setCtype('document');\n $property->setCpath($this->getRealFullPath());\n $property->save();\n }\n }\n }\n\n $this->getDao()->update();\n\n //set document to registry\n RuntimeCache::set(self::getCacheKey($this->getId()), $this);\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getDigit($code, $crc)\n {\n if (preg_match('`[^0-9]`', $code)) {\n return '';\n }\n\n $index = 0;\n $result = '';\n\n $code = self::compute($code, false);\n\n // start\n $result = '110';\n\n // digits\n $len = strlen($code);\n for ($i = 0; $i < $len; $i++) {\n $result .= self::$encoding[ intval($code[$i]) ];\n }\n\n // stop\n $result .= '1001';\n\n return($result);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($key, $default) {\n\t\t\t\treturn $default;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function processMassiveActionsForOneItemtype(\n MassiveAction $ma,\n CommonDBTM $item,\n array $ids\n ) {\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setParameter ($namespace, $name, $value) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function applyJoins(DoctrineQueryBuilder $queryBuilder): static\n {\n return $this;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function post_clone($source, $history)\n {\n if (method_exists($this, 'updateGroupFields')) {\n // Toolbox::hasTrait doesn't work to tell PHPStan this method exists even when using generics and assert-if-true\n $this->updateGroupFields();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function propFind(PropFind $propFind, INode $node)\n {\n // There's a bunch of properties that must appear as a self-closing\n // xml-element. This event handler ensures that this will be the case.\n $props = [\n '{http://calendarserver.org/ns/}subscribed-strip-alarms',\n '{http://calendarserver.org/ns/}subscribed-strip-attachments',\n '{http://calendarserver.org/ns/}subscribed-strip-todos',\n ];\n\n foreach ($props as $prop) {\n if (200 === $propFind->getStatus($prop)) {\n $propFind->set($prop, '', 200);\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function throwException($errno, $errstr) {\n throw new RuntimeException($errstr);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function review_of_systems_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_review_of_systems\", $id);\n $sql = \"SELECT name from form_review_of_systems_checks where foreign_id = ?\";\n $results = sqlQ($sql, array($id));\n $data2 = array();\n while ($row = sqlFetchArray($results)) {\n $data2[] = $row['name'];\n }\n\n $data = array_merge($data, $data2);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n if (is_numeric($key)) {\n $key = \"check\";\n }\n\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ankleinjury_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_ankleinjury\", $id);\n if ($data) {\n print \"<table>\\n<tr>\\n\";\n foreach ($data as $key => $value) {\n if (\n $key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" ||\n $key == \"authorized\" || $key == \"activity\" || $key == \"date\" ||\n $value == \"\" || $value == \"0000-00-00 00:00:00\"\n ) {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n $key = str_replace(\"Ankle \", \"\", $key);\n $key = str_replace(\"Injuary\", \"Injury\", $key);\n print \"<td valign='top'><span class='bold'>\" . xlt($key) . \": </span><span class='text'>\" . text($value) . \"</span></td>\\n\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr>\\n<tr>\\n\";\n }\n }\n\n print \"</tr>\\n</table>\\n\";\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype, $main_joinparams)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '14',\n 'table' => 'glpi_devicemotherboards',\n 'field' => 'designation',\n 'name' => static::getTypeName(1),\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_items_devicemotherboards',\n 'joinparams' => $main_joinparams\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function unregister($modId, $currentActionStatus)\n {\n $logMessage = 'Claimrev Background tasks have been removed'; // Initialize an empty string to store log messages\n $sql = \"DELETE FROM `background_services` WHERE `name` = ? OR `name` = ? OR `name` = ?\";\n $status = sqlQuery($sql, array('ClaimRev_Send', 'ClaimRev_Receive', 'ClaimRev_Elig_Send_Receive'));\n error_log($logMessage . ' ' . text($status));\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function underscoredToCamelized($name)\n {\n $parts = preg_split();\n }", "smellKey": "S1172", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "function render($options=array()) {\n $config = $this->field->getConfiguration();\n list($phone, $ext) = explode(\"X\", $this->value);\n ?>\n <input id=\"<?php echo $this->id; ?>\" type=\"tel\" name=\"<?php echo $this->name; ?>\" value=\"<?php\n echo Format::htmlchars($phone); ?>\"/><?php\n // Allow display of extension field even if disabled if the phone\n // number being edited has an extension\n if ($ext || $config['ext']) { ?> <?php echo __('Ext'); ?>:\n <input type=\"text\" name=\"<?php\n echo $this->name; ?>-ext\" value=\"<?php echo Format::htmlchars($ext);\n ?>\" size=\"5\"/>\n <?php }\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "protected function addLocalizedFieldsInBricks(\n DataObject\\Concrete $object,\n AttributeSet $result,\n array $exportAttributes = null\n ): DataObjectDataExtractor {\n $locale = str_replace('-', '_', $result->getSourceLanguage());\n if (!Tool::isValidLanguage($locale)) {\n $locale = Locale::getPrimaryLanguage($locale);\n }\n\n if ($fieldDefinitions = $object->getClass()->getFieldDefinitions()) {\n foreach ($fieldDefinitions as $fieldDefinition) {\n if (!$fieldDefinition instanceof Data\\Objectbricks) {\n continue;\n }\n\n if (!$brickContainer = $object->get($fieldDefinition->getName())) {\n continue;\n }\n\n foreach ($fieldDefinition->getAllowedTypes() ?: [] as $brickType) {\n $brickGetter = 'get' . ucfirst($brickType);\n\n /** @var DataObject\\Objectbrick\\Data\\AbstractData $brick */\n if (!$brick = $brickContainer->$brickGetter()) {\n continue;\n }\n\n $brickDefinition = DataObject\\Objectbrick\\Definition::getByKey($brickType);\n\n $localizedFieldsDefinition = $brickDefinition->getFieldDefinition('localizedfields');\n if (!$localizedFieldsDefinition instanceof Localizedfields) {\n continue;\n }\n\n $localizedFields = $brick->get('localizedfields');\n\n if (!$localizedFields instanceof DataObject\\Localizedfield) {\n continue;\n }\n\n foreach ($localizedFieldsDefinition->getFieldDefinitions() ?: [] as $fd) {\n //relations are loaded from dependencies\n if ($fd instanceof Data\\Relations\\AbstractRelations) {\n continue;\n }\n\n // check allowed data-types\n if (!in_array($fd->getFieldtype(), self::EXPORTABLE_TAGS)) {\n continue;\n }\n\n $content = $localizedFields->getLocalizedValue($fd->getName(), $locale);\n\n $targetContent = [];\n foreach ($result->getTargetLanguages() as $targetLanguage) {\n if (Tool::isValidLanguage($targetLanguage)) {\n $targetContent[$targetLanguage] = $localizedFields->getLocalizedValue(\n $fd->getName(),\n $targetLanguage\n );\n }\n }\n\n if (!empty($content)) {\n $name =\n $fieldDefinition->getName() .\n self::BRICK_DELIMITER . $brickType .\n self::BRICK_DELIMITER . $fd->getName();\n\n $result->addAttribute(\n Attribute::TYPE_BRICK_LOCALIZED_FIELD,\n $name,\n $content,\n false,\n $targetContent\n );\n }\n }\n }\n }\n }\n\n return $this;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function imagesetclip ($im, $x1, $y1, $x2, $y2) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($str) {\n throw new SyntaxError('`constant` function not available');\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $routeName, array $parameters) use ($ignoreFrontController) {\n\t\t\t\tif ($routeName === 'ocs.core.OCS.getCapabilities') {\n\t\t\t\t\tif (!$ignoreFrontController) {\n\t\t\t\t\t\treturn '/nextcloud/index.php/ocsapp/cloud/capabilities';\n\t\t\t\t\t}\n\t\t\t\t\treturn '/nextcloud/ocsapp/cloud/capabilities';\n\t\t\t\t} elseif ($routeName === 'ocs.core.WhatsNew.dismiss') {\n\t\t\t\t\tif (!$ignoreFrontController) {\n\t\t\t\t\t\treturn '/nextcloud/index.php/ocsapp/core/whatsnew';\n\t\t\t\t\t}\n\t\t\t\t\treturn '/nextcloud/ocsapp/core/whatsnew';\n\t\t\t\t}\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function mb_http_input($type = '')\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function sDiffStore($dstKey, $key1, ...$otherKeys)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function hasWhere($where = [], $fields = null)\n {\n throw new Exception('relation not support: hasWhere');\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function ($u) {\n return '`uuid` = ?';\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function _memoryCacheAdd($id, $data)\n {\n $this->_memoryCachingArray[$this->_file] = $data;\n if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {\n foreach ($this->_memoryCachingArray as $key => $value) {\n unset($this->_memoryCachingArray[$key]);\n }\n } else {\n $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function newTransaction(\n $pid,\n $body,\n $title,\n $authorized = \"0\",\n $status = \"1\",\n $assigned_to = \"*\"\n) {\n\n $body = add_escape_custom($body);\n $id = sqlInsert(\"insert into transactions ( \" .\n \"date, title, pid, user, groupname, authorized \" .\n \") values ( \" .\n \"NOW(), '$title', '$pid', '\" . $_SESSION['authUser'] .\n \"', '\" . $_SESSION['authProvider'] . \"', '$authorized' \" .\n \")\");\n sqlStatement(\n \"INSERT INTO lbt_data (form_id, field_id, field_value) VALUES (?, ?, ?)\",\n array($id, 'body', $body)\n );\n return $id;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function zRangeByLex($key, $min, $max, $offset = null, $limit = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function smarty_function_pc_filter($args, &$smarty)\n{\n extract($args);\n unset($args);\n\n if (empty($type)) {\n trigger_error(\"pc_filter: missing 'type' parameter\", E_USER_WARNING);\n return;\n }\n\n $Date = postcalendar_getDate();\n if (!isset($y)) {\n $y = substr($Date, 0, 4);\n }\n\n if (!isset($m)) {\n $m = substr($Date, 4, 2);\n }\n\n if (!isset($d)) {\n $d = substr($Date, 6, 2);\n }\n\n $tplview = pnVarCleanFromInput('tplview');\n $viewtype = pnVarCleanFromInput('viewtype');\n $pc_username = pnVarCleanFromInput('pc_username');\n\n if (!isset($viewtype)) {\n $viewtype = _SETTING_DEFAULT_VIEW;\n }\n\n $types = explode(',', $type);\n $output = new pnHTML();\n $output->SetOutputMode(_PNH_RETURNOUTPUT);\n $modinfo = pnModGetInfo(pnModGetIDFromName(__POSTCALENDAR__));\n $mdir = pnVarPrepForOS($modinfo['directory']);\n unset($modinfo);\n $pcTemplate = pnVarPrepForOS(_SETTING_TEMPLATE);\n if (empty($pcTemplate)) {\n $pcTemplate = 'default';\n }\n\n list($dbconn) = pnDBGetConn();\n $pntable = pnDBGetTables();\n //================================================================\n // build the username filter pulldown\n //================================================================\n if (in_array('user', $types)) {\n @define('_PC_FORM_USERNAME', true);\n $sql = \"SELECT DISTINCT users.username, users.lname, users.fname\n\t \t\t\tFROM $pntable[postcalendar_events], users where users.id=pc_aid\n\t\t\t\tORDER BY pc_aid\";\n\n $result = $dbconn->Execute($sql);\n if ($result !== false) {\n $useroptions = \"<select multiple='multiple' size='3' name=\\\"pc_username[]\\\" class=\\\"$class\\\">\";\n $useroptions .= \"<option value=\\\"\\\" class=\\\"$class\\\">\" . _PC_FILTER_USERS . \"</option>\";\n $selected = $pc_username == '__PC_ALL__' ? 'selected=\"selected\"' : '';\n $useroptions .= \"<option value=\\\"__PC_ALL__\\\" class=\\\"$class\\\" $selected>\" . _PC_FILTER_USERS_ALL . \"</option>\";\n for (; !$result->EOF; $result->MoveNext()) {\n $sel = $pc_username == $result->fields[0] ? 'selected=\"selected\"' : '';\n $useroptions .= \"<option value=\\\"\" . $result->fields[0] . \"\\\" $sel class=\\\"$class\\\">\" . $result->fields[1] . \", \" . $result->fields[2] . \"</option>\";\n }\n\n $useroptions .= '</select>';\n $result->Close();\n }\n }\n\n //================================================================\n // build the category filter pulldown\n //================================================================\n if (in_array('category', $types)) {\n @define('_PC_FORM_CATEGORY', true);\n $category = pnVarCleanFromInput('pc_category');\n $categories = pnModAPIFunc(__POSTCALENDAR__, 'user', 'getCategories');\n $catoptions = \"<select name=\\\"pc_category\\\" class=\\\"$class\\\">\";\n $catoptions .= \"<option value=\\\"\\\" class=\\\"$class\\\">\" . _PC_FILTER_CATEGORY . \"</option>\";\n foreach ($categories as $c) {\n $sel = $category == $c['id'] ? 'selected=\"selected\"' : '';\n $catoptions .= \"<option value=\\\"$c[id]\\\" $sel class=\\\"$class\\\">\" . xl_appt_category($c[name]) . \"</option>\";\n }\n\n $catoptions .= '</select>';\n }\n\n //================================================================\n // build the topic filter pulldown\n //================================================================\n if (in_array('topic', $types) && _SETTING_DISPLAY_TOPICS) {\n @define('_PC_FORM_TOPIC', true);\n $topic = pnVarCleanFromInput('pc_topic');\n $topics = pnModAPIFunc(__POSTCALENDAR__, 'user', 'getTopics');\n $topoptions = \"<select name=\\\"pc_topic\\\" class=\\\"$class\\\">\";\n $topoptions .= \"<option value=\\\"\\\" class=\\\"$class\\\">\" . _PC_FILTER_TOPIC . \"</option>\";\n foreach ($topics as $t) {\n $sel = $topic == $t['id'] ? 'selected=\"selected\"' : '';\n $topoptions .= \"<option value=\\\"$t[id]\\\" $sel class=\\\"$class\\\">$t[text]</option>\";\n }\n\n $topoptions .= '</select>';\n } else {\n $topoptions = '';\n }\n\n //================================================================\n // build it in the correct order\n //================================================================\n if (!isset($label)) {\n $label = _PC_TPL_VIEW_SUBMIT;\n }\n\n $submit = \"<input type=\\\"submit\\\" valign=\\\"middle\\\" name=\\\"submit\\\" value=\\\"$label\\\" class=\\\"$class\\\" />\";\n $orderArray = array('user' => $useroptions, 'category' => $catoptions, 'topic' => $topoptions, 'jump' => $submit);\n\n if (isset($order)) {\n $newOrder = array();\n $order = explode(',', $order);\n foreach ($order as $tmp_order) {\n array_push($newOrder, $orderArray[$tmp_order]);\n }\n\n foreach ($orderArray as $key => $old_order) {\n if (!in_array($key, $newOrder)) {\n array_push($newOrder, $orderArray[$old_order]);\n }\n }\n\n $order = $newOrder;\n } else {\n $order = $orderArray;\n }\n\n foreach ($order as $element) {\n echo $element;\n }\n\n if (!in_array('user', $types)) {\n echo $output->FormHidden('pc_username', $pc_username);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function exportJsonStore(\n $limit = null,\n $offset = null\n ) {\n\n $returnData = array(\n 'totalCount' => $this->_total,\n 'success' => true,\n 'message' => 'success',\n 'data' => array(\n $this->_chart\n )\n );\n\n return $returnData;\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "static function ($matches) {\n return '';\n }", "smellKey": "S1172", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)\n {\n $aHyperlinkCollection = $pSheet->getHyperlinkCollection();\n ($pNumCols > 0 || $pNumRows > 0) ? uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellSort'));\n\n foreach ($aHyperlinkCollection as $key => $value) {\n $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);\n if ($key != $newReference) {\n $pSheet->setHyperlink($newReference, $value);\n $pSheet->setHyperlink($key, null);\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function rulepassed($items_id, $itemtype, $rules_id)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function hour_to_year(&$value, $key) {\n\t $value = $value / 8765.81277;\n\t}", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function locale_get_all_variants($locale) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function observation_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $sql = \"SELECT * FROM `form_observation` WHERE id=? AND pid = ? AND encounter = ?\";\n $res = sqlStatement($sql, array($id,$_SESSION[\"pid\"], $_SESSION[\"encounter\"]));\n\n\n\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $data[$iter] = $row;\n }\n\n if (!empty($data)) {\n print \"<table style='border-collapse:collapse;border-spacing:0;width: 100%;'>\n <tr>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Code') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Description') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Code Type') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Table Code') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Value') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Unit') . \"</span></td>\n <td align='center' style='border:1px solid #ccc;padding:4px;'><span class=bold>\" . xlt('Date') . \"</span></td>\n </tr>\";\n foreach ($data as $key => $value) {\n if ($value['code'] == 'SS003') {\n if ($value['ob_value'] == '261QE0002X') {\n $value['ob_value'] = 'Emergency Care';\n } elseif ($value['ob_value'] == '261QM2500X') {\n $value['ob_value'] = 'Medical Specialty';\n } elseif ($value['ob_value'] == '261QP2300X') {\n $value['ob_value'] = 'Primary Care';\n } elseif ($value['ob_value'] == '261QU0200X') {\n $value['ob_value'] = 'Urgent Care';\n }\n }\n\n if ($value['code'] == '21612-7') {\n if ($value['ob_unit'] == 'd') {\n $value['ob_unit'] = 'Day';\n } elseif ($value['ob_unit'] == 'mo') {\n $value['ob_unit'] = 'Month';\n } elseif ($value['ob_unit'] == 'UNK') {\n $value['ob_unit'] = 'Unknown';\n } elseif ($value['ob_unit'] == 'wk') {\n $value['ob_unit'] = 'Week';\n } elseif ($value['ob_unit'] == 'a') {\n $value['ob_unit'] = 'Year';\n }\n }\n\n print \"<tr>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['code']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['description']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['code_type']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['table_code']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['ob_value']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['ob_unit']) . \"</span></td>\n <td style='border:1px solid #ccc;padding:4px;'><span class=text>\" . text($value['date']) . \"</span></td>\n </tr>\";\n print \"\\n\";\n }\n\n print \"</table>\";\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function __construct($id = \"\", $_prefix = \"\")\n {\n parent::__construct();\n\n $this->_table = \"form_prior_auth\";\n\n if (is_numeric($id)) {\n $this->id = $id;\n } else {\n $id = \"\";\n }\n\n $this->pid = $GLOBALS['pid'];\n $this->activity = 1;\n $this->date = date(\"Y-m-d H:i:s\");\n $this->prior_auth_number = \"\";\n $this->date_from = date(\"Y-m-d\");\n $this->date_to = null;\n\n if ($id != \"\") {\n $this->populate();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function createGE($row, $X12info, $segTer, $compEleSep)\n {\n $GE = array();\n $GE[0] = \"GE\"; // Functional Group Trailer Segment ID\n $GE[1] = \"1\"; // Number of included Transaction Sets\n $GE[2] = \"2\"; // Group Control Number\n $GE['Created'] = implode('*', $GE); // Data Element Separator\n $GE['Created'] = $GE['Created'] . $segTer;\n return trim($GE['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function rPush($key, $value1, $value2 = null, $valueN = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getJobSummary(Application $app, \\XDUser $user, $realm, $jobId, $action, $actionName)\n {\n $queryclass = \"\\\\DataWarehouse\\\\Query\\\\$realm\\\\JobMetadata\";\n $query = new $queryclass();\n\n $jobsummary = $query->getJobSummary($user, $jobId);\n\n $result = array();\n\n // Really this should be a recursive function!\n foreach ($jobsummary as $key => $val) {\n $name = \"$key\";\n if (is_array($val)) {\n if (array_key_exists('avg', $val) && !is_array($val['avg'])) {\n $result[] = array_merge(array(\"name\" => $name, \"leaf\" => true), $this->encodeFloatArray($val));\n } else {\n $l1data = array(\"name\" => $name, \"avg\" => \"\", \"expanded\" => \"true\", \"children\" => array());\n foreach ($val as $subkey => $subval) {\n $subName = \"$subkey\";\n if (is_array($subval)) {\n if (array_key_exists('avg', $subval) && !is_array($subval['avg'])) {\n $l1data['children'][] = array_merge(array(\"name\" => $subName, \"leaf\" => true), $this->encodeFloatArray($subval));\n } else {\n $l2data = array(\"name\" => $subName, \"avg\" => \"\", \"expanded\" => \"true\", \"children\" => array());\n\n foreach ($subval as $subsubkey => $subsubval) {\n $subSubName = \"$subsubkey\";\n if (is_array($subsubval)) {\n if (array_key_exists('avg', $subsubval) && !is_array($subsubval['avg'])) {\n $l2data['children'][] = array_merge(array(\"name\" => $subSubName, \"leaf\" => true), $this->encodeFloatArray($subsubval));\n }\n }\n }\n\n if (count($l2data['children']) > 0) {\n $l1data['children'][] = $l2data;\n }\n }\n }\n }\n if (count($l1data['children']) > 0) {\n $result[] = $l1data;\n }\n }\n }\n }\n\n return $app->json(\n $result\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function procedure_order_report($pid, $encounter, $cols, $id)\n{\n generate_order_report($id);\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function polynomialRegression($order, $yValues, $xValues, $const)\n {\n // calculate sums\n $x_sum = array_sum($xValues);\n $y_sum = array_sum($yValues);\n $xx_sum = $xy_sum = 0;\n for ($i = 0; $i < $this->valueCount; ++$i) {\n $xy_sum += $xValues[$i] * $yValues[$i];\n $xx_sum += $xValues[$i] * $xValues[$i];\n $yy_sum += $yValues[$i] * $yValues[$i];\n }\n /*\n * This routine uses logic from the PHP port of polyfit version 0.1\n * written by Michael Bommarito and Paul Meagher\n *\n * The function fits a polynomial function of order $order through\n * a series of x-y data points using least squares.\n *\n */\n for ($i = 0; $i < $this->valueCount; ++$i) {\n for ($j = 0; $j <= $order; ++$j) {\n $A[$i][$j] = pow($xValues[$i], $j);\n }\n }\n for ($i=0; $i < $this->valueCount; ++$i) {\n $B[$i] = array($yValues[$i]);\n }\n $matrixA = new Matrix($A);\n $matrixB = new Matrix($B);\n $C = $matrixA->solve($matrixB);\n\n $coefficients = array();\n for ($i = 0; $i < $C->m; ++$i) {\n $r = $C->get($i, 0);\n if (abs($r) <= pow(10, -9)) {\n $r = 0;\n }\n $coefficients[] = $r;\n }\n\n $this->intersect = array_shift($coefficients);\n $this->_slope = $coefficients;\n\n $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum);\n foreach ($this->xValues as $xKey => $xValue) {\n $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct(TranslatorInterface $translator, array $policyMap)\n {\n $this->policyChoices = $this->buildPolicyChoicesFromMap($policyMap);\n }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_admin-ui", "language": "php"} {"function": "function (string $uid, int $shareType) use ($existingShareTypes, $shareMock) {\n\t\t\t\tif (in_array($shareType, $existingShareTypes)) {\n\t\t\t\t\treturn [$shareMock];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getPathSecuritySchema(RoutePath $route_path, string $route_method): array\n {\n return [\n [\n 'oauth' => []\n ]\n ];\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function displayAdditionalRuleCondition($condition, $criteria, $name, $value, $test = false)\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function copy_forward($zone, $copy_from, $copy_to, $pid)\n{\n global $form_id;\n\n $query = \"select *,form_encounter.date as encounter_date\n\n from forms,form_encounter,form_eye_base,\n form_eye_hpi,form_eye_ros,form_eye_vitals,\n form_eye_acuity,form_eye_refraction,form_eye_biometrics,\n form_eye_external,form_eye_antseg,form_eye_postseg,\n form_eye_neuro,form_eye_locking\n where\n forms.deleted != '1' and\n forms.formdir='eye_mag' and\n forms.encounter=form_encounter.encounter and\n forms.form_id=form_eye_base.id and\n forms.form_id=form_eye_hpi.id and\n forms.form_id=form_eye_ros.id and\n forms.form_id=form_eye_vitals.id and\n forms.form_id=form_eye_acuity.id and\n forms.form_id=form_eye_refraction.id and\n forms.form_id=form_eye_biometrics.id and\n forms.form_id=form_eye_external.id and\n forms.form_id=form_eye_antseg.id and\n forms.form_id=form_eye_postseg.id and\n forms.form_id=form_eye_neuro.id and\n forms.form_id=form_eye_locking.id and\n forms.pid =? and\n forms.form_id =? \";\n\n $objQuery = sqlQuery($query, array($pid,$copy_from));\n if ($zone == \"EXT\") {\n $result['RUL'] = $objQuery['RUL'];\n $result['LUL'] = $objQuery['LUL'];\n $result['RLL'] = $objQuery['RLL'];\n $result['LLL'] = $objQuery['LLL'];\n $result['RBROW'] = $objQuery['RBROW'];\n $result['LBROW'] = $objQuery['LBROW'];\n $result['RMCT'] = $objQuery['RMCT'];\n $result['LMCT'] = $objQuery['LMCT'];\n $result['RADNEXA'] = $objQuery['RADNEXA'];\n $result['LADNEXA'] = $objQuery['LADNEXA'];\n $result['RMRD'] = $objQuery['RMRD'];\n $result['LMRD'] = $objQuery['LMRD'];\n $result['RLF'] = $objQuery['RLF'];\n $result['LLF'] = $objQuery['LLF'];\n $result['RVFISSURE'] = $objQuery['RVFISSURE'];\n $result['LVFISSURE'] = $objQuery['LVFISSURE'];\n $result['RCAROTID'] = $objQuery['RCAROTID'];\n $result['LCAROTID'] = $objQuery['LCAROTID'];\n $result['RTEMPART'] = $objQuery['RTEMPART'];\n $result['LTEMPART'] = $objQuery['LTEMPART'];\n $result['RCNV'] = $objQuery['RCNV'];\n $result['LCNV'] = $objQuery['LCNV'];\n $result['RCNVII'] = $objQuery['RCNVII'];\n $result['LCNVII'] = $objQuery['LCNVII'];\n $result['ODSCHIRMER1'] = $objQuery['ODSCHIRMER1'];\n $result['OSSCHIRMER1'] = $objQuery['OSSCHIRMER1'];\n $result['ODSCHIRMER2'] = $objQuery['ODSCHIRMER2'];\n $result['OSSCHIRMER2'] = $objQuery['OSSCHIRMER2'];\n $result['ODTBUT'] = $objQuery['ODTBUT'];\n $result['OSTBUT'] = $objQuery['OSTBUT'];\n $result['OSHERTEL'] = $objQuery['OSHERTEL'];\n $result['HERTELBASE'] = $objQuery['HERTELBASE'];\n $result['ODPIC'] = $objQuery['ODPIC'];\n $result['OSPIC'] = $objQuery['OSPIC'];\n $result['EXT_COMMENTS'] = $objQuery['EXT_COMMENTS'];\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n } elseif ($zone == \"ANTSEG\") {\n $result['OSCONJ'] = $objQuery['OSCONJ'];\n $result['ODCONJ'] = $objQuery['ODCONJ'];\n $result['ODCORNEA'] = $objQuery['ODCORNEA'];\n $result['OSCORNEA'] = $objQuery['OSCORNEA'];\n $result['ODAC'] = $objQuery['ODAC'];\n $result['OSAC'] = $objQuery['OSAC'];\n $result['ODLENS'] = $objQuery['ODLENS'];\n $result['OSLENS'] = $objQuery['OSLENS'];\n $result['ODIRIS'] = $objQuery['ODIRIS'];\n $result['OSIRIS'] = $objQuery['OSIRIS'];\n $result['ODKTHICKNESS'] = $objQuery['ODKTHICKNESS'];\n $result['OSKTHICKNESS'] = $objQuery['OSKTHICKNESS'];\n $result['ODGONIO'] = $objQuery['ODGONIO'];\n $result['OSGONIO'] = $objQuery['OSGONIO'];\n $result['ODSHRIMER1'] = $objQuery['ODSHIRMER1'];\n $result['OSSHRIMER1'] = $objQuery['OSSHIRMER1'];\n $result['ODSHRIMER2'] = $objQuery['ODSHIRMER2'];\n $result['OSSHRIMER2'] = $objQuery['OSSHIRMER2'];\n $result['ODTBUT'] = $objQuery['ODTBUT'];\n $result['OSTBUT'] = $objQuery['OSTBUT'];\n $result['ANTSEG_COMMENTS'] = $objQuery['ANTSEG_COMMENTS'];\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n } elseif ($zone == \"RETINA\") {\n $result['ODDISC'] = $objQuery['ODDISC'];\n $result['OSDISC'] = $objQuery['OSDISC'];\n $result['ODCUP'] = $objQuery['ODCUP'];\n $result['OSCUP'] = $objQuery['OSCUP'];\n $result['ODMACULA'] = $objQuery['ODMACULA'];\n $result['OSMACULA'] = $objQuery['OSMACULA'];\n $result['ODVESSELS'] = $objQuery['ODVESSELS'];\n $result['OSVESSELS'] = $objQuery['OSVESSELS'];\n $result['ODVITREOUS'] = $objQuery['ODVITREOUS'];\n $result['OSVITREOUS'] = $objQuery['OSVITREOUS'];\n $result['ODPERIPH'] = $objQuery['ODPERIPH'];\n $result['OSPERIPH'] = $objQuery['OSPERIPH'];\n $result['ODDRAWING'] = $objQuery['ODDRAWING'];\n $result['OSDRAWING'] = $objQuery['OSDRAWING'];\n $result['ODCMT'] = $objQuery['ODCMT'];\n $result['OSCMT'] = $objQuery['OSCMT'];\n $result['RETINA_COMMENTS'] = $objQuery['RETINA_COMMENTS'];\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n } elseif ($zone == \"NEURO\") {\n $result['ACT'] = $objQuery['ACT'];\n $result['ACT5CCDIST'] = $objQuery['ACT5CCDIST'];\n $result['ACT1CCDIST'] = $objQuery['ACT1CCDIST'];\n $result['ACT2CCDIST'] = $objQuery['ACT2CCDIST'];\n $result['ACT3CCDIST'] = $objQuery['ACT3CCDIST'];\n $result['ACT4CCDIST'] = $objQuery['ACT4CCDIST'];\n $result['ACT6CCDIST'] = $objQuery['ACT6CCDIST'];\n $result['ACT7CCDIST'] = $objQuery['ACT7CCDIST'];\n $result['ACT8CCDIST'] = $objQuery['ACT8CCDIST'];\n $result['ACT9CCDIST'] = $objQuery['ACT9CCDIST'];\n $result['ACT10CCDIST'] = $objQuery['ACT10CCDIST'];\n $result['ACT11CCDIST'] = $objQuery['ACT11CCDIST'];\n $result['ACT1SCDIST'] = $objQuery['ACT1SCDIST'];\n $result['ACT2SCDIST'] = $objQuery['ACT2SCDIST'];\n $result['ACT3SCDIST'] = $objQuery['ACT3SCDIST'];\n $result['ACT4SCDIST'] = $objQuery['ACT4SCDIST'];\n $result['ACT5SCDIST'] = $objQuery['ACT5SCDIST'];\n $result['ACT6SCDIST'] = $objQuery['ACT6SCDIST'];\n $result['ACT7SCDIST'] = $objQuery['ACT7SCDIST'];\n $result['ACT8SCDIST'] = $objQuery['ACT8SCDIST'];\n $result['ACT9SCDIST'] = $objQuery['ACT9SCDIST'];\n $result['ACT10SCDIST'] = $objQuery['ACT10SCDIST'];\n $result['ACT11SCDIST'] = $objQuery['ACT11SCDIST'];\n $result['ACT1SCNEAR'] = $objQuery['ACT1SCNEAR'];\n $result['ACT2SCNEAR'] = $objQuery['ACT2SCNEAR'];\n $result['ACT3SCNEAR'] = $objQuery['ACT3SCNEAR'];\n $result['ACT4SCNEAR'] = $objQuery['ACT4SCNEAR'];\n $result['ACT5CCNEAR'] = $objQuery['ACT5CCNEAR'];\n $result['ACT6CCNEAR'] = $objQuery['ACT6CCNEAR'];\n $result['ACT7CCNEAR'] = $objQuery['ACT7CCNEAR'];\n $result['ACT8CCNEAR'] = $objQuery['ACT8CCNEAR'];\n $result['ACT9CCNEAR'] = $objQuery['ACT9CCNEAR'];\n $result['ACT10CCNEAR'] = $objQuery['ACT10CCNEAR'];\n $result['ACT11CCNEAR'] = $objQuery['ACT11CCNEAR'];\n $result['ACT5SCNEAR'] = $objQuery['ACT5SCNEAR'];\n $result['ACT6SCNEAR'] = $objQuery['ACT6SCNEAR'];\n $result['ACT7SCNEAR'] = $objQuery['ACT7SCNEAR'];\n $result['ACT8SCNEAR'] = $objQuery['ACT8SCNEAR'];\n $result['ACT9SCNEAR'] = $objQuery['ACT9SCNEAR'];\n $result['ACT10SCNEAR'] = $objQuery['ACT10SCNEAR'];\n $result['ACT11SCNEAR'] = $objQuery['ACT11SCNEAR'];\n $result['ACT1CCNEAR'] = $objQuery['ACT1CCNEAR'];\n $result['ACT2CCNEAR'] = $objQuery['ACT2CCNEAR'];\n $result['ACT3CCNEAR'] = $objQuery['ACT3CCNEAR'];\n $result['ACT4CCNEAR'] = $objQuery['ACT4CCNEAR'];\n $result['ODVF1'] = $objQuery['ODVF1'];\n $result['ODVF2'] = $objQuery['ODVF2'];\n $result['ODVF3'] = $objQuery['ODVF3'];\n $result['ODVF4'] = $objQuery['ODVF4'];\n $result['OSVF1'] = $objQuery['OSVF1'];\n $result['OSVF2'] = $objQuery['OSVF2'];\n $result['OSVF3'] = $objQuery['OSVF3'];\n $result['OSVF4'] = $objQuery['OSVF4'];\n $result['MOTILITY_RS'] = $objQuery['MOTILITY_RS'];\n $result['MOTILITY_RI'] = $objQuery['MOTILITY_RI'];\n $result['MOTILITY_RR'] = $objQuery['MOTILITY_RR'];\n $result['MOTILITY_RL'] = $objQuery['MOTILITY_RL'];\n $result['MOTILITY_LS'] = $objQuery['MOTILITY_LS'];\n $result['MOTILITY_LI'] = $objQuery['MOTILITY_LI'];\n $result['MOTILITY_LR'] = $objQuery['MOTILITY_LR'];\n $result['MOTILITY_LL'] = $objQuery['MOTILITY_LL'];\n $result['NEURO_COMMENTS'] = $objQuery['NEURO_COMMENTS'];\n $result['STEREOPSIS'] = $objQuery['STEREOPSIS'];\n $result['ODNPA'] = $objQuery['ODNPA'];\n $result['OSNPA'] = $objQuery['OSNPA'];\n $result['VERTFUSAMPS'] = $objQuery['VERTFUSAMPS'];\n $result['DIVERGENCEAMPS'] = $objQuery['DIVERGENCEAMPS'];\n $result['NPC'] = $objQuery['NPC'];\n $result['DACCDIST'] = $objQuery['DACCDIST'];\n $result['DACCNEAR'] = $objQuery['DACCNEAR'];\n $result['CACCDIST'] = $objQuery['CACCDIST'];\n $result['CACCNEAR'] = $objQuery['CACCNEAR'];\n $result['ODCOLOR'] = $objQuery['ODCOLOR'];\n $result['OSCOLOR'] = $objQuery['OSCOLOR'];\n $result['ODCOINS'] = $objQuery['ODCOINS'];\n $result['OSCOINS'] = $objQuery['OSCOINS'];\n $result['ODREDDESAT'] = $objQuery['ODREDDESAT'];\n $result['OSREDDESAT'] = $objQuery['OSREDDESAT'];\n $result['ODPUPILSIZE1'] = $objQuery['ODPUPILSIZE1'];\n $result['ODPUPILSIZE2'] = $objQuery['ODPUPILSIZE2'];\n $result['ODPUPILREACTIVITY'] = $objQuery['ODPUPILREACTIVITY'];\n $result['ODAPD'] = $objQuery['ODAPD'];\n $result['OSPUPILSIZE1'] = $objQuery['OSPUPILSIZE1'];\n $result['OSPUPILSIZE2'] = $objQuery['OSPUPILSIZE2'];\n $result['OSPUPILREACTIVITY'] = $objQuery['OSPUPILREACTIVITY'];\n $result['OSAPD'] = $objQuery['OSAPD'];\n $result['DIMODPUPILSIZE1'] = $objQuery['DIMODPUPILSIZE1'];\n $result['DIMODPUPILSIZE2'] = $objQuery['DIMODPUPILSIZE2'];\n $result['DIMODPUPILREACTIVITY'] = $objQuery['DIMODPUPILREACTIVITY'];\n $result['DIMOSPUPILSIZE1'] = $objQuery['DIMOSPUPILSIZE1'];\n $result['DIMOSPUPILSIZE2'] = $objQuery['DIMOSPUPILSIZE2'];\n $result['DIMOSPUPILREACTIVITY'] = $objQuery['DIMOSPUPILREACTIVITY'];\n $result['PUPIL_COMMENTS'] = $objQuery['PUPIL_COMMENTS'];\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n } elseif ($zone == \"IMPPLAN\") {\n $result['IMPPLAN'] = build_IMPPLAN_items($pid, $copy_from);\n echo json_encode($result);\n } elseif ($zone == \"ALL\") {\n $result['RUL'] = $objQuery['RUL'];\n $result['LUL'] = $objQuery['LUL'];\n $result['RLL'] = $objQuery['RLL'];\n $result['LLL'] = $objQuery['LLL'];\n $result['RBROW'] = $objQuery['RBROW'];\n $result['LBROW'] = $objQuery['LBROW'];\n $result['RMCT'] = $objQuery['RMCT'];\n $result['LMCT'] = $objQuery['LMCT'];\n $result['RADNEXA'] = $objQuery['RADNEXA'];\n $result['LADNEXA'] = $objQuery['LADNEXA'];\n $result['RMRD'] = $objQuery['RMRD'];\n $result['LMRD'] = $objQuery['LMRD'];\n $result['RLF'] = $objQuery['RLF'];\n $result['LLF'] = $objQuery['LLF'];\n $result['RVFISSURE'] = $objQuery['RVFISSURE'];\n $result['LVFISSURE'] = $objQuery['LVFISSURE'];\n $result['ODHERTEL'] = $objQuery['ODHERTEL'];\n $result['OSHERTEL'] = $objQuery['OSHERTEL'];\n $result['HERTELBASE'] = $objQuery['HERTELBASE'];\n $result['ODPIC'] = $objQuery['ODPIC'];\n $result['OSPIC'] = $objQuery['OSPIC'];\n $result['EXT_COMMENTS'] = $objQuery['EXT_COMMENTS'];\n\n $result['OSCONJ'] = $objQuery['OSCONJ'];\n $result['ODCONJ'] = $objQuery['ODCONJ'];\n $result['ODCORNEA'] = $objQuery['ODCORNEA'];\n $result['OSCORNEA'] = $objQuery['OSCORNEA'];\n $result['ODAC'] = $objQuery['ODAC'];\n $result['OSAC'] = $objQuery['OSAC'];\n $result['ODLENS'] = $objQuery['ODLENS'];\n $result['OSLENS'] = $objQuery['OSLENS'];\n $result['ODIRIS'] = $objQuery['ODIRIS'];\n $result['OSIRIS'] = $objQuery['OSIRIS'];\n $result['ODKTHICKNESS'] = $objQuery['ODKTHICKNESS'];\n $result['OSKTHICKNESS'] = $objQuery['OSKTHICKNESS'];\n $result['ODGONIO'] = $objQuery['ODGONIO'];\n $result['OSGONIO'] = $objQuery['OSGONIO'];\n $result['ANTSEG_COMMENTS'] = $objQuery['ANTSEG_COMMENTS'];\n\n $result['ODDISC'] = $objQuery['ODDISC'];\n $result['OSDISC'] = $objQuery['OSDISC'];\n $result['ODCUP'] = $objQuery['ODCUP'];\n $result['OSCUP'] = $objQuery['OSCUP'];\n $result['ODMACULA'] = $objQuery['ODMACULA'];\n $result['OSMACULA'] = $objQuery['OSMACULA'];\n $result['ODVESSELS'] = $objQuery['ODVESSELS'];\n $result['OSVESSELS'] = $objQuery['OSVESSELS'];\n $result['ODVITREOUS'] = $objQuery['ODVITREOUS'];\n $result['OSVITREOUS'] = $objQuery['OSVITREOUS'];\n $result['ODPERIPH'] = $objQuery['ODPERIPH'];\n $result['OSPERIPH'] = $objQuery['OSPERIPH'];\n $result['ODDRAWING'] = $objQuery['ODDRAWING'];\n $result['OSDRAWING'] = $objQuery['OSDRAWING'];\n $result['ODCMT'] = $objQuery['ODCMT'];\n $result['OSCMT'] = $objQuery['OSCMT'];\n $result['RETINA_COMMENTS'] = $objQuery['RETINA_COMMENTS'];\n\n $result['ACT'] = $objQuery['ACT'];\n $result['ACT5CCDIST'] = $objQuery['ACT5CCDIST'];\n $result['ACT1CCDIST'] = $objQuery['ACT1CCDIST'];\n $result['ACT2CCDIST'] = $objQuery['ACT2CCDIST'];\n $result['ACT3CCDIST'] = $objQuery['ACT3CCDIST'];\n $result['ACT4CCDIST'] = $objQuery['ACT4CCDIST'];\n $result['ACT6CCDIST'] = $objQuery['ACT6CCDIST'];\n $result['ACT7CCDIST'] = $objQuery['ACT7CCDIST'];\n $result['ACT8CCDIST'] = $objQuery['ACT8CCDIST'];\n $result['ACT9CCDIST'] = $objQuery['ACT9CCDIST'];\n $result['ACT10CCDIST'] = $objQuery['ACT10CCDIST'];\n $result['ACT11CCDIST'] = $objQuery['ACT11CCDIST'];\n $result['ACT1SCDIST'] = $objQuery['ACT1SCDIST'];\n $result['ACT2SCDIST'] = $objQuery['ACT2SCDIST'];\n $result['ACT3SCDIST'] = $objQuery['ACT3SCDIST'];\n $result['ACT4SCDIST'] = $objQuery['ACT4SCDIST'];\n $result['ACT5SCDIST'] = $objQuery['ACT5SCDIST'];\n $result['ACT6SCDIST'] = $objQuery['ACT6SCDIST'];\n $result['ACT7SCDIST'] = $objQuery['ACT7SCDIST'];\n $result['ACT8SCDIST'] = $objQuery['ACT8SCDIST'];\n $result['ACT9SCDIST'] = $objQuery['ACT9SCDIST'];\n $result['ACT10SCDIST'] = $objQuery['ACT10SCDIST'];\n $result['ACT11SCDIST'] = $objQuery['ACT11SCDIST'];\n $result['ACT1SCNEAR'] = $objQuery['ACT1SCNEAR'];\n $result['ACT2SCNEAR'] = $objQuery['ACT2SCNEAR'];\n $result['ACT3SCNEAR'] = $objQuery['ACT3SCNEAR'];\n $result['ACT4SCNEAR'] = $objQuery['ACT4SCNEAR'];\n $result['ACT5CCNEAR'] = $objQuery['ACT5CCNEAR'];\n $result['ACT6CCNEAR'] = $objQuery['ACT6CCNEAR'];\n $result['ACT7CCNEAR'] = $objQuery['ACT7CCNEAR'];\n $result['ACT8CCNEAR'] = $objQuery['ACT8CCNEAR'];\n $result['ACT9CCNEAR'] = $objQuery['ACT9CCNEAR'];\n $result['ACT10CCNEAR'] = $objQuery['ACT10CCNEAR'];\n $result['ACT11CCNEAR'] = $objQuery['ACT11CCNEAR'];\n $result['ACT5SCNEAR'] = $objQuery['ACT5SCNEAR'];\n $result['ACT6SCNEAR'] = $objQuery['ACT6SCNEAR'];\n $result['ACT7SCNEAR'] = $objQuery['ACT7SCNEAR'];\n $result['ACT8SCNEAR'] = $objQuery['ACT8SCNEAR'];\n $result['ACT9SCNEAR'] = $objQuery['ACT9SCNEAR'];\n $result['ACT10SCNEAR'] = $objQuery['ACT10SCNEAR'];\n $result['ACT11SCNEAR'] = $objQuery['ACT11SCNEAR'];\n $result['ACT1CCNEAR'] = $objQuery['ACT1CCNEAR'];\n $result['ACT2CCNEAR'] = $objQuery['ACT2CCNEAR'];\n $result['ACT3CCNEAR'] = $objQuery['ACT3CCNEAR'];\n $result['ACT4CCNEAR'] = $objQuery['ACT4CCNEAR'];\n $result['ODVF1'] = $objQuery['ODVF1'];\n $result['ODVF2'] = $objQuery['ODVF2'];\n $result['ODVF3'] = $objQuery['ODVF3'];\n $result['ODVF4'] = $objQuery['ODVF4'];\n $result['OSVF1'] = $objQuery['OSVF1'];\n $result['OSVF2'] = $objQuery['OSVF2'];\n $result['OSVF3'] = $objQuery['OSVF3'];\n $result['OSVF4'] = $objQuery['OSVF4'];\n $result['MOTILITY_RS'] = $objQuery['MOTILITY_RS'];\n $result['MOTILITY_RI'] = $objQuery['MOTILITY_RI'];\n $result['MOTILITY_RR'] = $objQuery['MOTILITY_RR'];\n $result['MOTILITY_RL'] = $objQuery['MOTILITY_RL'];\n $result['MOTILITY_LS'] = $objQuery['MOTILITY_LS'];\n $result['MOTILITY_LI'] = $objQuery['MOTILITY_LI'];\n $result['MOTILITY_LR'] = $objQuery['MOTILITY_LR'];\n $result['MOTILITY_LL'] = $objQuery['MOTILITY_LL'];\n $result['NEURO_COMMENTS'] = $objQuery['NEURO_COMMENTS'];\n $result['STEREOPSIS'] = $objQuery['STEREOPSIS'];\n $result['ODNPA'] = $objQuery['ODNPA'];\n $result['OSNPA'] = $objQuery['OSNPA'];\n $result['VERTFUSAMPS'] = $objQuery['VERTFUSAMPS'];\n $result['DIVERGENCEAMPS'] = $objQuery['DIVERGENCEAMPS'];\n $result['NPC'] = $objQuery['NPC'];\n $result['DACCDIST'] = $objQuery['DACCDIST'];\n $result['DACCNEAR'] = $objQuery['DACCNEAR'];\n $result['CACCDIST'] = $objQuery['CACCDIST'];\n $result['CACCNEAR'] = $objQuery['CACCNEAR'];\n $result['ODCOLOR'] = $objQuery['ODCOLOR'];\n $result['OSCOLOR'] = $objQuery['OSCOLOR'];\n $result['ODCOINS'] = $objQuery['ODCOINS'];\n $result['OSCOINS'] = $objQuery['OSCOINS'];\n $result['ODREDDESAT'] = $objQuery['ODREDDESAT'];\n $result['OSREDDESAT'] = $objQuery['OSREDDESAT'];\n $result['ODPUPILSIZE1'] = $objQuery['ODPUPILSIZE1'];\n $result['ODPUPILSIZE2'] = $objQuery['ODPUPILSIZE2'];\n $result['ODPUPILREACTIVITY'] = $objQuery['ODPUPILREACTIVITY'];\n $result['ODAPD'] = $objQuery['ODAPD'];\n $result['OSPUPILSIZE1'] = $objQuery['OSPUPILSIZE1'];\n $result['OSPUPILSIZE2'] = $objQuery['OSPUPILSIZE2'];\n $result['OSPUPILREACTIVITY'] = $objQuery['OSPUPILREACTIVITY'];\n $result['OSAPD'] = $objQuery['OSAPD'];\n $result['DIMODPUPILSIZE1'] = $objQuery['DIMODPUPILSIZE1'];\n $result['DIMODPUPILSIZE2'] = $objQuery['DIMODPUPILSIZE2'];\n $result['DIMODPUPILREACTIVITY'] = $objQuery['DIMODPUPILREACTIVITY'];\n $result['DIMOSPUPILSIZE1'] = $objQuery['DIMOSPUPILSIZE1'];\n $result['DIMOSPUPILSIZE2'] = $objQuery['DIMOSPUPILSIZE2'];\n $result['DIMOSPUPILREACTIVITY'] = $objQuery['DIMOSPUPILREACTIVITY'];\n $result['PUPIL_COMMENTS'] = $objQuery['PUPIL_COMMENTS'];\n $result['IMP'] = $objQuery['IMP'];\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n } elseif ($zone == \"READONLY\") {\n $result = $objQuery;\n $count_rx = '0';\n $query1 = \"select * from form_eye_mag_wearing where PID=? and ENCOUNTER=? and FORM_ID >'0' ORDER BY RX_NUMBER\";\n $wear = sqlStatement($query1, array($pid,$_SESSION['encounter']));\n while ($wearing = sqlFetchArray($wear)) {\n ${\"display_W_$count_rx\"} = '';\n ${\"ODSPH_$count_rx\"} = $wearing['ODSPH'];\n ${\"ODCYL_$count_rx\"} = $wearing['ODCYL'];\n ${\"ODAXIS_$count_rx\"} = $wearing['ODAXIS'];\n ${\"OSSPH_$count_rx\"} = $wearing['OSSPH'];\n ${\"OSCYL_$count_rx\"} = $wearing['OSCYL'];\n ${\"OSAXIS_$count_rx\"} = $wearing['OSAXIS'];\n ${\"ODMIDADD_$count_rx\"} = $wearing['ODMIDADD'];\n ${\"OSMIDADD_$count_rx\"} = $wearing['OSMIDADD'];\n ${\"ODADD_$count_rx\"} = $wearing['ODADD'];\n ${\"OSADD_$count_rx\"} = $wearing['OSADD'];\n ${\"ODVA_$count_rx\"} = $wearing['ODVA'];\n ${\"OSVA_$count_rx\"} = $wearing['OSVA'];\n ${\"ODNEARVA_$count_rx\"} = $wearing['ODNEARVA'];\n ${\"OSNEARVA_$count_rx\"} = $wearing['OSNEARVA'];\n ${\"ODPRISM_$count_rx\"} = $wearing['ODPRISM'] ?? '';\n ${\"OSPRISM_$count_rx\"} = $wearing['OSPRISM'] ?? '';\n ${\"W_$count_rx\"} = '1';\n ${\"RX_TYPE_$count_rx\"} = $wearing['RX_TYPE'];\n ${\"ODHPD_$count_rx\"} = $wearing['ODHPD'];\n ${\"ODHBASE_$count_rx\"} = $wearing['ODHBASE'];\n ${\"ODVPD_$count_rx\"} = $wearing['ODVPD'];\n ${\"ODVBASE_$count_rx\"} = $wearing['ODVBASE'];\n ${\"ODSLABOFF_$count_rx\"} = $wearing['ODSLABOFF'];\n ${\"ODVERTEXDIST_$count_rx\"} = $wearing['ODVERTEXDIST'];\n ${\"OSHPD_$count_rx\"} = $wearing['OSHPD'];\n ${\"OSHBASE_$count_rx\"} = $wearing['OSHBASE'];\n ${\"OSVPD_$count_rx\"} = $wearing['OSVPD'];\n ${\"OSVBASE_$count_rx\"} = $wearing['OSVBASE'];\n ${\"OSSLABOFF_$count_rx\"} = $wearing['OSSLABOFF'];\n ${\"OSVERTEXDIST_$count_rx\"} = $wearing['OSVERTEXDIST'];\n ${\"ODMPDD_$count_rx\"} = $wearing['ODMPDD'];\n ${\"ODMPDN_$count_rx\"} = $wearing['ODMPDN'];\n ${\"OSMPDD_$count_rx\"} = $wearing['OSMPDD'];\n ${\"OSMPDN_$count_rx\"} = $wearing['OSMPDN'];\n ${\"BPDD_$count_rx\"} = $wearing['BPDD'];\n ${\"BPDN_$count_rx\"} = $wearing['BPDN'];\n ${\"LENS_MATERIAL_$count_rx\"} = $wearing['LENS_MATERIAL'];\n ${\"LENS_TREATMENTS_$count_rx\"} = $wearing['LENS_TREATMENTS'];\n ${\"COMMENTS_$count_rx\"} = $wearing['COMMENTS'];\n }\n $result['IMPPLAN'] = build_IMPPLAN_items($pid, $copy_from);\n $result['query'] = $query;\n $result[\"json\"] = json_encode($result);\n echo json_encode($result);\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function mois_precedent($m, $mois, $a)\n {\n $m--;\n if ($m == 0) {\n $a--;\n $m = 12;\n }\n return \"<a href=index.php?choixTraitement=intervenant&action=recapPlanning&m=$m&a=$a> &laquo; </a>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function refer(ReferralForm $form, &$errors, $alert=true) {\n global $thisstaff;\n\n $evd = array();\n $audit = array();\n $referee = $form->getReferee();\n switch (true) {\n case $referee instanceof Staff:\n $dept = $this->getDept();\n if ($this->getStaffId() == $referee->getId()) {\n $errors['agent'] = sprintf(__('%s is assigned to %s'),\n __('Ticket'),\n __('the agent')\n );\n } elseif(!$referee->isAvailable()) {\n $errors['agent'] = sprintf(__('Agent is unavailable for %s'),\n __('referral'));\n } else {\n $evd['staff'] = array($referee->getId(), (string) $referee->getName()->getOriginal());\n $audit = array('staff' => $referee->getName()->name);\n }\n break;\n case $referee instanceof Team:\n if ($this->getTeamId() == $referee->getId()) {\n $errors['team'] = sprintf(__('%s is assigned to %s'),\n __('Ticket'),\n __('the team')\n );\n } else {\n //TODO::\n $evd = array('team' => $referee->getId());\n $audit = array('team' => $referee->getName());\n }\n break;\n case $referee instanceof Dept:\n if ($this->getDeptId() == $referee->getId()) {\n $errors['dept'] = sprintf(__('%s is already in %s'),\n __('Ticket'),\n __('the department')\n );\n } else {\n //TODO::\n $evd = array('dept' => $referee->getId());\n $audit = array('dept' => $referee->getName());\n }\n break;\n default:\n $errors['target'] = __('Unknown referral');\n }\n\n if (!$errors && !$this->getThread()->refer($referee))\n $errors['err'] = __('Unable to refer ticket');\n\n if ($errors)\n return false;\n\n $this->logEvent('referred', $evd);\n\n $type = array('type' => 'referred');\n $type += $audit;\n Signal::send('object.edited', $this, $type);\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "static function (RequestInterface $request, array $options) {\n\t\t\t\t// The handler should not be called\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function function2(?NamespacedType $value)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function imageftbbox ($size, $angle, $fontfile, $text, $extrainfo = null ) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function showForITILTemplate(ITILTemplate $tt, $withtemplate = 0)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $itilcategory = new self();\n $ID = $tt->fields['id'];\n\n if (\n !$tt->getFromDB($ID)\n || !$tt->can($ID, READ)\n ) {\n return false;\n }\n\n echo \"<div class='center'>\";\n\n $iterator = $DB->request([\n 'FROM' => 'glpi_itilcategories',\n 'WHERE' => [\n 'OR' => [\n 'tickettemplates_id_incident' => $ID,\n 'tickettemplates_id_demand' => $ID,\n 'changetemplates_id' => $ID,\n 'problemtemplates_id' => $ID\n ]\n ],\n 'ORDER' => 'name'\n ]);\n\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr><th colspan='5'>\";\n $itilcategory_type = $itilcategory->getType();\n echo \"<a href='\" . $itilcategory_type::getSearchURL() . \"'>\";\n echo self::getTypeName(count($iterator));\n echo \"</a>\";\n echo \"</th></tr>\";\n if (count($iterator)) {\n echo \"<th>\" . __s('Name') . \"</th>\";\n echo \"<th>\" . __s('Incident') . \"</th>\";\n echo \"<th>\" . __s('Request') . \"</th>\";\n echo \"<th>\" . htmlescape(Change::getTypeName(1)) . \"</th>\";\n echo \"<th>\" . htmlescape(Problem::getTypeName(1)) . \"</th>\";\n echo \"</tr>\";\n\n foreach ($iterator as $data) {\n echo \"<tr class='tab_bg_2'>\";\n $itilcategory->getFromDB($data['id']);\n echo \"<td>\" . $itilcategory->getLink(['comments' => true]) . \"</td>\";\n if ($data['tickettemplates_id_incident'] == $ID) {\n echo \"<td class='center'>\n <img src='\" . htmlescape($CFG_GLPI[\"root_doc\"]) . \"/pics/ok.png' alt=\\\"\" . __s('OK') .\n \"\\\" width='14' height='14'>\n </td>\";\n } else {\n echo \"<td>&nbsp;</td>\";\n }\n if ($data['tickettemplates_id_demand'] == $ID) {\n echo \"<td class='center'>\n <img src='\" . htmlescape($CFG_GLPI[\"root_doc\"]) . \"/pics/ok.png' alt=\\\"\" . __s('OK') .\n \"\\\" width='14' height='14'>\n </td>\";\n } else {\n echo \"<td>&nbsp;</td>\";\n }\n if ($data['changetemplates_id'] == $ID) {\n echo \"<td class='center'>\n <img src='\" . htmlescape($CFG_GLPI[\"root_doc\"]) . \"/pics/ok.png' alt=\\\"\" . __s('OK') .\n \"\\\" width='14' height='14'>\n </td>\";\n } else {\n echo \"<td>&nbsp;</td>\";\n }\n if ($data['problemtemplates_id'] == $ID) {\n echo \"<td class='center'>\n <img src='\" . htmlescape($CFG_GLPI[\"root_doc\"]) . \"/pics/ok.png' alt=\\\"\" . __s('OK') .\n \"\\\" width='14' height='14'>\n </td>\";\n } else {\n echo \"<td>&nbsp;</td>\";\n }\n }\n } else {\n echo \"<tr><th colspan='5'>\" . __s('No item found') . \"</th></tr>\";\n }\n\n echo \"</table></div>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function mois_precedent($m, $mois, $a)\n {\n $m--;\n if ($m == 0) {\n $a--;\n $m = 12;\n }\n return \"<a href=index.php?choixTraitement=intervenant&action=Planning&m=$m&a=$a> &laquo; </a>\";\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function imprimerFicheGroupesSortie($idStage,$idAtelier,$nb,$lesInscriptions,$lesClasses)\n\t{\n\t\t/* on cr\u00e9\u00e9 le PDF */\n\t\trequire('fpdf/fpdf.php');\n\t\t$pdf = new FPDF();\n\n\t\t$pdf->AddPage();\n\n\t\t/* Fonction Cell :\n\t\tpremier chiffre = largeur\n\t\t2\u00e8me chiffre = hauteur\n\t\ttexte\n\t\tbordure (0 ou 1)\n\t\tretour \u00e0 la ligne (0 pas de retour, 1 retour)\n\t\talignement (L, C ou R)\n\t\tcouleur de fond (true ou false)\n\t\tlien\n\t\t*/\n\n\t\t/* liste */\n\t\t$pdf->SetFont('Arial', '', 11);\n\n\t\t// On parcours les inscriptions\n\t\t$i = 0;\n\t\t$iGroupe = $nb;\n\t\t$numGroupe = 0;\n\t\t$classePrec = '';\n\t\tforeach($lesInscriptions as $lInscription) {\n\n\t\t\t$i++;\n\n\t\t\t// Si on atteint le nb max\n\t\t\tif($iGroupe == $nb) {\n\n\t\t\t\t// On saute une page\n\t\t\t\tif($numGroupe > 0) { $pdf->AddPage(); }\n\n\t\t\t\t// Compteur du nb d'\u00e9l\u00e8ves du groupe\n\t\t\t\t$iGroupe = 0;\n\n\t\t\t\t// Num\u00e9ro du groupe\n\t\t\t\t$numGroupe++;\n\n\t\t\t\t// Entete\n\t\t\t\t$pdf->SetFont('Arial', '', 18);\n\t\t\t\t$pdf->SetFillColor(192,192,192);\n\n\t\t\t\t// Nom du groupe\n\t\t\t\t$pdf->Cell(185, 8, utf8_decode('Groupe n\u00b0'.$numGroupe),1,1,'C',true);\n\n\t\t\t\t// Nouveau tableau\n\t\t\t\t$pdf->SetFont('Arial', '', 11);\n\n\t\t\t\t$pdf->Cell(5, 5, utf8_decode('N\u00b0'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(40, 5, utf8_decode('Photo'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(40, 5, utf8_decode('NOM'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(40, 5, utf8_decode('Pr\u00e9nom'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(20, 5, utf8_decode('Classe'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(40, 5, utf8_decode('T\u00e9l'),1,1,'C',true);\n\t\t\t\t//$pdf->Cell(50, 5, utf8_decode('Groupe'),1,1,'C',true);\n\t\t\t}\n\n\t\t\t// Nom de la classe\n\t\t\t$laClasse = '';\n\t\t\tforeach($lesClasses as $uneClasse) {\n\t\t\t\tif($uneClasse['ID'] == $lInscription['CLASSE_ELEVE_STAGE']) {\n\t\t\t\t\t$laClasse = $uneClasse['NOM'];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$pdf->SetFillColor(255,255,255);\n\n\t\t\t// Ligne de l'inscription\n\t\t\t$pdf->Cell(5, 30, utf8_decode(($iGroupe+1)),1,0,'C',true);\n\n\t\t\t$pdf->SetFillColor(0,0,0);\n\t\t\t$pdf->Cell(40, 30, '',1,0,'C',true);\n\n\t\t\t// Si la photo n'est pas vide\n\t\t\tif($lInscription['PHOTO_ELEVE_STAGE'] != '') {\n\t\t\t\t$url = 'photosEleves/'.$lInscription['PHOTO_ELEVE_STAGE'];\n\t\t\t\t$extension = pathinfo($url,PATHINFO_EXTENSION);\n\t\t\t\t$pdf->Image($url,15,(23+($iGroupe*30)),0,30,$extension);\n\t\t\t}\n\n\n\t\t\t$pdf->SetFillColor(255,255,255);\n\t\t\t$pdf->Cell(40, 30, utf8_decode(strtoupper(stripslashes($lInscription['NOM_ELEVE_STAGE']))),1,0,'L',true);\n\t\t\t$pdf->Cell(40, 30, utf8_decode(ucfirst(strtolower(stripslashes($lInscription['PRENOM_ELEVE_STAGE'])))),1,0,'L');\n\t\t\t$pdf->Cell(20, 30, utf8_decode($laClasse),1,0,'L');\n\t\t\t$pdf->Cell(40, 30, utf8_decode(stripslashes($lInscription['TELEPHONE_ELEVE_ELEVE_STAGE'])),1,1,'L');\n\n\t\t\t$i++;\n\t\t\t$iGroupe++;\n\t\t}\n\t\t$pdf->Output();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function ($item, $key) use ($model) {\n if (isset($this->getTypeMap()[$item->api_model])) {\n return $this->getTypeMap()[$item->api_model] == (string) get_class($model) && $item->id == $model->id;\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function getObject($moduleDirectory, $option = 'Controller', $adapter = '')\n {\n $obj = null;\n\n if ($option == 'Form' && $moduleDirectory != 'Installer') {\n error_log('getObject called with option of Form. This call signature is deprecated. Use getFormObject instead');\n } elseif ($option == 'Setup') {\n error_log('getObject called with option of Setup. This call signature is deprecated. Use getSetupObject instead');\n }\n\n $className = str_replace('[module_name]', $moduleDirectory, '[module_name]\\\\' . $option . '\\Moduleconfig' . $option . '');\n\n if ($this->container->has($className)) {\n $obj = $this->container->get($className);\n }\n\n return $obj;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (Blueprint $table) {\n //\n }", "smellKey": "S1172", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public static function checkRotavirus_2014(CqmPatient $patient, $beginDate, $endDate)\n {\n $options = array( Medication::OPTION_COUNT => 2 );\n $dobPlus42Days = date('Y-m-d 00:00:00', strtotime('+42 day', strtotime($patient->dob)));\n $dobPlus2Years = date('Y-m-d 00:00:00', strtotime('+2 year', strtotime($patient->dob)));\n if (\n Helper::checkMed(Medication::ROTAVIRUS_VAC, $patient, $dobPlus42Days, $dobPlus2Years, $options) &&\n !Helper::checkAllergy(Allergy::ROTAVIRUS_VAC, $patient, $patient->dob, $endDate)\n ) {\n return true;\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ($matches) use ($replacement) {\n return $replacement;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new EncountermanagerController($container->get(\\Carecoordination\\Model\\EncountermanagerTable::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($class, $main_joinparams)\n {\n $tab = [];\n\n $tab[] = [\n 'id' => '110',\n 'table' => 'glpi_devicememories',\n 'field' => 'designation',\n 'name' => DeviceMemoryType::getTypeName(1),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_items_devicememories',\n 'joinparams' => $main_joinparams\n ]\n ]\n ];\n\n $tab[] = [\n 'id' => '111',\n 'table' => 'glpi_items_devicememories',\n 'field' => 'size',\n 'unit' => 'auto',\n 'name' => _n('Memory', 'Memories', 1),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'mio',\n 'width' => 100,\n 'massiveaction' => false,\n 'joinparams' => $main_joinparams,\n 'computation' => '(' .\n QueryFunction::sum('TABLE.size') . '/' .\n QueryFunction::count('TABLE.id') . ') * ' .\n QueryFunction::count('TABLE.id', true),\n 'nometa' => true, // cannot GROUP_CONCAT a SUM\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function canViewSpecificicDashboard($key, $canViewAll = false): bool\n {\n self::loadAllDashboards();\n\n $dashboard = new Dashboard($key);\n $dashboard->load();\n // check global (admin) right\n if (Dashboard::canView() && !$dashboard->isPrivate()) {\n return true;\n }\n\n return isset(self::$all_dashboards[$key]);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getEquation($dp = 0)\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "protected function trim_file_name(\n $file_path,\n $name,\n $size,\n $type,\n $error,\n $index,\n $content_range\n ) {\n // Remove path information and dots around the filename, to prevent uploading\n // into different directories or replacing hidden system files.\n // Also remove control characters and spaces (\\x00..\\x20) around the filename:\n $name = trim($this->basename(stripslashes($name)), \".\\x00..\\x20\");\n // Replace dots in filenames to avoid security issues with servers\n // that interpret multiple file extensions, e.g. \"example.php.png\":\n $replacement = $this->options['replace_dots_in_filenames'];\n if (!empty($replacement)) {\n $parts = explode('.', $name);\n if (count($parts) > 2) {\n $ext = array_pop($parts);\n $name = implode($replacement, $parts) . '.' . $ext;\n }\n }\n // Use a timestamp for empty filenames:\n if (!$name) {\n $name = str_replace('.', '-', microtime(true));\n }\n return $name;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function aws_crt_test_verify_sigv4a_signing(int $signable, int $signing_config, string $expected_canonical_request, string $signature, string $ecc_key_pub_x, string $ecc_key_pub_y): bool {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function updateQueryTableOnDelete(int $oo_id, array $ids, string $fieldname): void\n {\n if (!empty($ids)) {\n $value = null;\n $this->db->executeStatement('UPDATE ' . $this->querytable .' SET ' . $this->db->quoteIdentifier($fieldname) . '=? WHERE ' . $this->db->quoteIdentifier($this->idField) . ' IN (' . implode(',', $ids) . ')', [$value]);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array\n {\n if (!$collection->all()) {\n return [[], [], ''];\n }\n $regexpList = [];\n $code = '';\n $state = (object) [\n 'regexMark' => 0,\n 'regex' => [],\n 'routes' => [],\n 'mark' => 0,\n 'markTail' => 0,\n 'hostVars' => [],\n 'vars' => [],\n ];\n $state->getVars = static function ($m) use ($state) {\n if ('_route' === $m[1]) {\n return '?:';\n }\n\n $state->vars[] = $m[1];\n\n return '';\n };\n\n $chunkSize = 0;\n $prev = null;\n $perModifiers = [];\n foreach ($collection->all() as $name => $route) {\n preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);\n if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {\n $chunkSize = 1;\n $routes = new RouteCollection();\n $perModifiers[] = [$rx[0], $routes];\n $prev = $rx[0];\n }\n $routes->add($name, $route);\n }\n\n foreach ($perModifiers as [$modifiers, $routes]) {\n $prev = false;\n $perHost = [];\n foreach ($routes->all() as $name => $route) {\n $regex = $route->compile()->getHostRegex();\n if ($prev !== $regex) {\n $routes = new RouteCollection();\n $perHost[] = [$regex, $routes];\n $prev = $regex;\n }\n $routes->add($name, $route);\n }\n $prev = false;\n $rx = '{^(?';\n $code .= \"\\n {$state->mark} => \".self::export($rx);\n $startingMark = $state->mark;\n $state->mark += \\strlen($rx);\n $state->regex = $rx;\n\n foreach ($perHost as [$hostRegex, $routes]) {\n if ($matchHost) {\n if ($hostRegex) {\n preg_match('#^.\\^(.*)\\$.[a-zA-Z]*$#', $hostRegex, $rx);\n $state->vars = [];\n $hostRegex = '(?i:'.preg_replace_callback('#\\?P<([^>]++)>#', $state->getVars, $rx[1]).')\\.';\n $state->hostVars = $state->vars;\n } else {\n $hostRegex = '(?:(?:[^./]*+\\.)++)';\n $state->hostVars = [];\n }\n $state->mark += \\strlen($rx = ($prev ? ')' : '').\"|{$hostRegex}(?\");\n $code .= \"\\n .\".self::export($rx);\n $state->regex .= $rx;\n $prev = true;\n }\n\n $tree = new StaticPrefixCollection();\n foreach ($routes->all() as $name => $route) {\n preg_match('#^.\\^(.*)\\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);\n\n $state->vars = [];\n $regex = preg_replace_callback('#\\?P<([^>]++)>#', $state->getVars, $rx[1]);\n if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {\n $regex = substr($regex, 0, -1);\n }\n $hasTrailingVar = (bool) preg_match('#\\{\\w+\\}/?$#', $route->getPath());\n\n $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]);\n }\n\n $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);\n }\n if ($matchHost) {\n $code .= \"\\n .')'\";\n $state->regex .= ')';\n }\n $rx = \")/?$}{$modifiers}\";\n $code .= \"\\n .'{$rx}',\";\n $state->regex .= $rx;\n $state->markTail = 0;\n\n // if the regex is too large, throw a signaling exception to recompute with smaller chunk size\n set_error_handler(function ($type, $message) { throw str_contains($message, $this->signalingException->getMessage()) ? $this->signalingException : new \\ErrorException($message); });\n try {\n preg_match($state->regex, '');\n } finally {\n restore_error_handler();\n }\n\n $regexpList[$startingMark] = $state->regex;\n }\n\n $state->routes[$state->mark][] = [null, null, null, null, false, false, 0];\n unset($state->getVars);\n\n return [$regexpList, $state->routes, $code];\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function imagecreatetruecolor ($width, $height) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function formatObject($object, $format = null, $locale = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(Util $util,\n\t\tIConfig $config,\n\t\tIUserManager $userManager,\n\t\tQuestionHelper $questionHelper) {\n\t\t$this->util = $util;\n\t\t$this->questionHelper = $questionHelper;\n\t\t$this->userManager = $userManager;\n\t\tparent::__construct();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "Function Initialize(&$client)\n\t{\n\t\treturn(1);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function printLabelValuePair($params, &$smarty)\n {\n if($params['var']){\n return '<div><div class=\"tlbl\">'.$params['lbl'].': </div><b>'.$params['var'].'</b></div>';\n }else{\n return '';\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "protected function canNotificationBeDisabled(string $event): bool\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function imagefilltoborder ($image, $x, $y, $border, $color) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function displayDebugInfos($with_session = true, $ajax = false, $rand = null)\n {\n Toolbox::deprecated('Html::displayDebugInfo is not used anymore. It was replaced by a unified debug bar.');\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function _validateEnum($fieldname, $data_type=null){\n\n $value = @$this->data[$fieldname];\n\n if($value==null){\n return true;\n }\n\n $enums = $this->fields[$fieldname]['rst_FieldConfig'];\n $values = is_array($value) ? $value : explode(',', $value);\n $isKeyBased = is_array($enums[0]);\n\n foreach($values as $value){\n // remove negation\n if(strpos($value, '-') === 0){ $value = substr($value, 1); }\n\n $isNotFound = true;\n if($isKeyBased){\n if(findInArray($enums, 'key', $value)!==null){\n $isNotFound = false;\n break;\n }\n }elseif(array_search($value, $enums, true)!==false){\n $isNotFound = false;\n }\n if($isNotFound){\n $this->system->addError(HEURIST_INVALID_REQUEST, \"Wrong parameter for field $fieldname: $value\");\n return false;\n }\n }//for\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function ($app, $key, $default) {\n\t\t\t\tswitch ($key) {\n\t\t\t\t\tcase 'maximumCalendarsSubscriptions':\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn $default;\n\t\t\t\t}\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (int $errno, string $errstr, string $errfile, int $errline): bool {\n //Logger::debug(implode(\" \", [$errno, $errstr, $errfile, $errline]));\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function isReservedMacroName($name)\n {\n @trigger_error(sprintf('The \"%s\" method is deprecated since Twig 2.7 and will be removed in 3.0.', __METHOD__), \\E_USER_DEPRECATED);\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype = null)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $tab = [];\n\n $tab[] = [\n 'id' => 'followup',\n 'name' => _n('Followup', 'Followups', Session::getPluralNumber())\n ];\n\n $followup_condition = '';\n if (!Session::haveRight('followup', self::SEEPRIVATE)) {\n $followup_condition = [\n 'OR' => [\n 'NEWTABLE.is_private' => 0,\n 'NEWTABLE.users_id' => Session::getLoginUserID()\n ]\n ];\n }\n\n $tab[] = [\n 'id' => '25',\n 'table' => static::getTable(),\n 'field' => 'content',\n 'name' => __('Description'),\n 'forcegroupby' => true,\n 'splititems' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ],\n 'datatype' => 'text',\n 'htmltext' => true\n ];\n\n $tab[] = [\n 'id' => '36',\n 'table' => static::getTable(),\n 'field' => 'date',\n 'name' => _n('Date', 'Dates', 1),\n 'datatype' => 'datetime',\n 'massiveaction' => false,\n 'forcegroupby' => true,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '72',\n 'table' => static::getTable(),\n 'field' => 'date',\n 'name' => _n('Latest date', 'Latest dates', 1),\n 'datatype' => 'datetime',\n 'massiveaction' => false,\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ],\n 'computation' => QueryFunction::max('TABLE.date'),\n 'nometa' => true // cannot GROUP_CONCAT a MAX\n ];\n\n\n $tab[] = [\n 'id' => '27',\n 'table' => static::getTable(),\n 'field' => 'id',\n 'name' => _x('quantity', 'Number of followups'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '29',\n 'table' => 'glpi_requesttypes',\n 'field' => 'name',\n 'name' => RequestType::getTypeName(1),\n 'datatype' => 'dropdown',\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => static::getTable(),\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ]\n ]\n ];\n\n $tab[] = [\n 'id' => '91',\n 'table' => static::getTable(),\n 'field' => 'is_private',\n 'name' => __('Private followup'),\n 'datatype' => 'bool',\n 'forcegroupby' => true,\n 'splititems' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ];\n\n $tab[] = [\n 'id' => '93',\n 'table' => 'glpi_users',\n 'field' => 'name',\n 'name' => __('Writer'),\n 'datatype' => 'itemlink',\n 'right' => 'all',\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => static::getTable(),\n 'joinparams' => [\n 'jointype' => 'itemtype_item',\n 'condition' => $followup_condition\n ]\n ]\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private static function softwareByCategory(\n $data,\n $itemtype,\n $items_id,\n $withtemplate,\n $canedit,\n $display\n ) {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $ID = $data[\"id\"];\n $verid = $data[\"verid\"];\n\n if ($display) {\n echo \"<tr class='tab_bg_1'>\";\n if ($canedit) {\n echo \"<td>\";\n Html::showMassiveActionCheckBox(__CLASS__, $ID);\n echo \"</td>\";\n }\n echo \"<td>\";\n echo \"<a href='\" . Software::getFormURLWithID($data['softwares_id']) . \"'>\";\n echo ($_SESSION[\"glpiis_ids_visible\"] ? sprintf(\n __('%1$s (%2$s)'),\n $data[\"softname\"],\n $data['softwares_id']\n )\n : $data[\"softname\"]);\n echo \"</a></td>\";\n echo \"<td>\" . htmlescape($data[\"state\"]) . \"</td>\";\n\n echo \"<td>\" . htmlescape($data[\"version\"]);\n echo \"</td><td>\";\n }\n\n $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_softwarelicenses.*',\n 'glpi_softwarelicensetypes.name AS type'\n ],\n 'FROM' => 'glpi_items_softwarelicenses',\n 'INNER JOIN' => [\n 'glpi_softwarelicenses' => [\n 'FKEY' => [\n 'glpi_items_softwarelicenses' => 'softwarelicenses_id',\n 'glpi_softwarelicenses' => 'id'\n ]\n ]\n ],\n 'LEFT JOIN' => [\n 'glpi_softwarelicensetypes' => [\n 'FKEY' => [\n 'glpi_softwarelicenses' => 'softwarelicensetypes_id',\n 'glpi_softwarelicensetypes' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n \"glpi_items_softwarelicenses.items_id\" => $items_id,\n 'glpi_items_softwarelicenses.itemtype' => $itemtype,\n 'OR' => [\n 'glpi_softwarelicenses.softwareversions_id_use' => $verid,\n [\n 'glpi_softwarelicenses.softwareversions_id_use' => 0,\n 'glpi_softwarelicenses.softwareversions_id_buy' => $verid\n ]\n ]\n ]\n ]);\n\n $licids = [];\n foreach ($iterator as $licdata) {\n $licids[] = $licdata['id'];\n $licserial = $licdata['serial'];\n\n if (!empty($licdata['type'])) {\n $licserial = sprintf(__('%1$s (%2$s)'), $licserial, $licdata['type']);\n }\n\n if ($display) {\n echo \"<span class='b'>\" . htmlescape($licdata['name']) . \"</span> - \" . htmlescape($licserial);\n\n $link_item = Toolbox::getItemTypeFormURL('SoftwareLicense');\n $link = $link_item . \"?id=\" . $licdata['id'];\n $comment = \"<table><tr><td>\" . __s('Name') . \"</td><td>\" . htmlescape($licdata['name']) . \"</td></tr>\" .\n \"<tr><td>\" . __s('Serial number') . \"</td><td>\" . htmlescape($licdata['serial']) . \"</td></tr>\" .\n \"<tr><td>\" . __s('Comments') . '</td><td>' . htmlescape($licdata['comment']) . \"</td></tr>\" .\n \"</table>\";\n\n Html::showToolTip($comment, ['link' => $link]);\n echo \"<br>\";\n }\n }\n\n if ($display) {\n if (!count($licids)) {\n echo \"&nbsp;\";\n }\n\n echo \"</td>\";\n\n echo \"<td>\" . Html::convDate($data['dateinstall']) . \"</td>\";\n echo \"<td>\" . $data['arch'] . \"</td>\";\n\n if (isset($data['is_dynamic'])) {\n echo \"<td>\" . Dropdown::getYesNo($data['is_dynamic']) . \"</td>\";\n }\n\n echo \"<td>\" . Dropdown::getDropdownName(\n \"glpi_softwarecategories\",\n $data['softwarecategories_id']\n );\n echo \"</td>\";\n echo \"<td>\" . Dropdown::getYesNo($data[\"softvalid\"]) . \"</td>\";\n echo \"<td></td>\"; // empty td for filter column\n echo \"</tr>\\n\";\n }\n\n return $licids;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getRights($interface = 'central')\n {\n $values[self::READMY] = __('See personnal planning');\n $values[self::READGROUP] = __('See schedule of people in my groups');\n $values[self::READALL] = __('See all plannings');\n\n return $values;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function setName($name)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "public function restore(Model\\User $user = null): void\n {\n $dummy = null;\n $raw = Storage::get('recycle_bin')->read($this->getStorageFile());\n $element = Serialize::unserialize($raw);\n\n // check for element with the same name\n if ($element instanceof Document) {\n $indentElement = Document::getByPath($element->getRealFullPath());\n if ($indentElement) {\n $element->setKey($element->getKey().'_restore');\n }\n } elseif ($element instanceof Asset) {\n $indentElement = Asset::getByPath($element->getRealFullPath());\n if ($indentElement) {\n $element->setFilename($element->getFilename().'_restore');\n }\n } elseif ($element instanceof DataObject\\AbstractObject) {\n $indentElement = DataObject::getByPath($element->getRealFullPath());\n if ($indentElement) {\n $element->setKey($element->getKey().'_restore');\n }\n\n // create an empty object first and clone it\n // see https://github.com/pimcore/pimcore/issues/4219\n Model\\Version::disable();\n $className = get_class($element);\n /** @var Document|Asset|AbstractObject $dummy */\n $dummy = Pimcore::getContainer()->get('pimcore.model.factory')->build($className);\n $dummy->setId($element->getId());\n $dummy->setParentId($element->getParentId() ?: 1);\n $dummy->setKey($element->getKey());\n if ($dummy instanceof DataObject\\Concrete) {\n $dummy->setOmitMandatoryCheck(true);\n }\n $dummy->save(['isRecycleBinRestore' => true]);\n Model\\Version::enable();\n }\n\n if (\\Pimcore\\Tool\\Admin::getCurrentUser()) {\n $parent = $element->getParent();\n if ($parent && !$parent->isAllowed('publish')) {\n throw new Exception('Not sufficient permissions');\n }\n }\n\n try {\n $isDirtyDetectionDisabled = DataObject::isDirtyDetectionDisabled();\n DataObject::disableDirtyDetection();\n\n $this->doRecursiveRestore($element);\n\n DataObject::setDisableDirtyDetection($isDirtyDetectionDisabled);\n } catch (Exception $e) {\n Logger::error((string) $e);\n if ($dummy) {\n $dummy->delete();\n }\n\n throw $e;\n }\n\n $this->delete();\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function postRootPackageInstall(Event $event)\n {\n if (! file_exists('.env')) {\n self::setPermissions();\n self::populateEnv();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function lLen($key)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function zIncrBy($key, $value, $member) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function send_patient_data_to_remote_system($patientData)\n{\n // This is just a stub for example only\n // For example, you could write data to a file and send to a remote SFTP server\n // or build a remote API call.\n return;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function InsertObservationPerformed($observation_preformed_array, $pid, CarecoordinationTable $carecoordinationTable, $revapprove = 1)\n {\n if (empty($observation_preformed_array)) {\n return;\n }\n $newid = '';\n $appTable = new ApplicationTable();\n $res = $appTable->zQuery('SELECT MAX(id) as largestId FROM `form_observation`');\n foreach ($res as $val) {\n if ($val['largestId']) {\n $newid = $val['largestId'] + 1;\n } else {\n $newid = 1;\n }\n }\n\n foreach ($observation_preformed_array as $key => $value) {\n $date_end = null;\n if (!empty($value['date'])) {\n $enc_date = date(\"Y-m-d\", $this->str_to_time($value['date']));\n $date = date(\"Y-m-d H:i:s\", $this->str_to_time($value['date']));\n $date_end = $value['date_end'] ? date(\"Y-m-d H:i:s\", $this->str_to_time($value['date_end'])) : null;\n } else {\n $date = date('Y-m-d');\n }\n\n $query_sel_enc = 'SELECT encounter\n FROM form_encounter\n WHERE date LIKE ? AND pid=?';\n $res_query_sel_enc = $appTable->zQuery($query_sel_enc, array('%' . $enc_date . '%', $pid));\n\n if ($res_query_sel_enc->count() == 0) {\n $res_enc = $appTable->zQuery('SELECT encounter\n FROM form_encounter\n WHERE pid=?\n ORDER BY id DESC\n LIMIT 1', array($pid));\n $res_enc_cur = $res_enc->current();\n $encounter_for_forms = $res_enc_cur['encounter'];\n } else {\n foreach ($res_query_sel_enc as $value2) {\n $encounter_for_forms = $value2['encounter'];\n }\n }\n\n $res = $appTable->zQuery(\n 'INSERT INTO form_observation(\n id,date,pid,groupname,user,encounter, activity,\n code,\n observation,\n ob_value,\n ob_unit,\n description,\n ob_status,\n ob_code,\n ob_type,\n ob_reason_status,\n ob_reason_code,\n ob_reason_text,\n date_end)\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n array(\n $newid, $date, $pid, $_SESSION['authProvider'], $_SESSION['authUser'], $encounter_for_forms, 1,\n $value['code'] ?: null,\n $value['observation'],\n $value['result_code_text'],\n $value['result_code_unit'] ?? '',\n $value['code_text'],\n $value['observation_status'],\n $value['result_code'],\n $value['observation_type'],\n $value['reason_status'],\n $value['reason_code'],\n $value['reason_code_text'],\n $date_end\n )\n );\n // insert form for observation\n if (($observation_preformed_array[$key - 1]['date'] ?? null) == $value['date']) {\n continue;\n }\n if (count($observation_preformed_array) > 0) {\n $query = 'INSERT INTO forms(date,encounter,form_name,form_id,pid,user,groupname,formdir) VALUES(?,?,?,?,?,?,?,?)';\n $appTable->zQuery($query, array($date, $encounter_for_forms, 'Observation Form', $newid, $pid, $_SESSION['authUser'], $_SESSION['authProvider'], 'observation'));\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($current, $key, $iterator) {\n return ( ! $iterator->isDot() );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function ftp_get(FTP\\Connection|resource $ftp, string $local_filename, string $remote_filename, int $mode = FTP_BINARY, int $offset = 0): bool {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function showInstances(CommonDBTM $item, $withtemplate)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $instances = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->fields['id']\n ]\n ]);\n\n $entries = [];\n $item = new self();\n foreach ($instances as $row) {\n $item->getFromDB($row['id']);\n $databases = $item->getDatabases();\n $databasetype = new DatabaseInstanceType();\n $databasetype_name = '';\n if ($item->fields['databaseinstancetypes_id'] > 0 && $databasetype->getFromDB($item->fields['databaseinstancetypes_id'])) {\n $databasetype_name = $databasetype->fields['name'];\n }\n $manufacturer = new Manufacturer();\n $manufacturer_name = '';\n if ($item->fields['manufacturers_id'] > 0 && $manufacturer->getFromDB($item->fields['manufacturers_id'])) {\n $manufacturer_name = $manufacturer->fields['name'];\n }\n\n $entries[] = [\n 'itemtype' => self::class,\n 'id' => $item->getID(),\n 'row_class' => $item->isDeleted() ? 'table-danger' : '',\n 'name' => $item->getLink(),\n 'database_count' => sprintf(_n('%1$d database', '%1$d databases', count($databases)), count($databases)),\n 'version' => $item->fields['version'],\n 'databaseinstancetypes_id' => $databasetype_name,\n 'manufacturers_id' => $manufacturer_name\n ];\n }\n\n TemplateRenderer::getInstance()->display('components/datatable.html.twig', [\n 'is_tab' => true,\n 'nofilter' => true,\n 'columns' => [\n 'name' => __('Name'),\n 'database_count' => Database::getTypeName(1),\n 'version' => _n('Version', 'Versions', 1),\n 'databaseinstancetypes_id' => DatabaseInstanceType::getTypeName(1),\n 'manufacturers_id' => Manufacturer::getTypeName(1),\n ],\n 'formatters' => [\n 'name' => 'raw_html'\n ],\n 'entries' => $entries,\n 'total_number' => count($entries),\n 'filtered_number' => count($entries),\n 'showmassiveactions' => false,\n ]);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($type, $buffer) use ($event, $writeBuffer) {\n if ($writeBuffer) {\n $event->getIO()->write($buffer, false);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function (string $bucketId, string $fileId, Response $response, Request $request, Database $dbForProject, string $mode, Device $deviceFiles) {\n $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));\n\n $isAPIKey = Auth::isAppUser(Authorization::getRoles());\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n\n if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {\n throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);\n }\n\n $fileSecurity = $bucket->getAttribute('fileSecurity', false);\n $validator = new Authorization(Database::PERMISSION_READ);\n $valid = $validator->isValid($bucket->getRead());\n if (!$fileSecurity && !$valid) {\n throw new Exception(Exception::USER_UNAUTHORIZED);\n }\n\n if ($fileSecurity && !$valid) {\n $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);\n } else {\n $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));\n }\n\n if ($file->isEmpty()) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);\n }\n\n $mimes = Config::getParam('storage-mimes');\n\n $path = $file->getAttribute('path', '');\n\n if (!$deviceFiles->exists($path)) {\n throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in ' . $path);\n }\n\n $contentType = 'text/plain';\n\n if (\\in_array($file->getAttribute('mimeType'), $mimes)) {\n $contentType = $file->getAttribute('mimeType');\n }\n\n $response\n ->setContentType($contentType)\n ->addHeader('Content-Security-Policy', 'script-src none;')\n ->addHeader('X-Content-Type-Options', 'nosniff')\n ->addHeader('Content-Disposition', 'inline; filename=\"' . $file->getAttribute('name', '') . '\"')\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache\n ->addHeader('X-Peak', \\memory_get_peak_usage())\n ;\n\n $size = $file->getAttribute('sizeOriginal', 0);\n\n $rangeHeader = $request->getHeader('range');\n if (!empty($rangeHeader)) {\n $start = $request->getRangeStart();\n $end = $request->getRangeEnd();\n $unit = $request->getRangeUnit();\n\n if ($end === null) {\n $end = min(($start + 2000000 - 1), ($size - 1));\n }\n\n if ($unit != 'bytes' || $start >= $end || $end >= $size) {\n throw new Exception(Exception::STORAGE_INVALID_RANGE);\n }\n\n $response\n ->addHeader('Accept-Ranges', 'bytes')\n ->addHeader('Content-Range', \"bytes $start-$end/$size\")\n ->addHeader('Content-Length', $end - $start + 1)\n ->setStatusCode(Response::STATUS_CODE_PARTIALCONTENT);\n }\n\n $source = '';\n if (!empty($file->getAttribute('openSSLCipher'))) { // Decrypt\n $source = $deviceFiles->read($path);\n $source = OpenSSL::decrypt(\n $source,\n $file->getAttribute('openSSLCipher'),\n App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),\n 0,\n \\hex2bin($file->getAttribute('openSSLIV')),\n \\hex2bin($file->getAttribute('openSSLTag'))\n );\n }\n\n switch ($file->getAttribute('algorithm', 'none')) {\n case 'zstd':\n if (empty($source)) {\n $source = $deviceFiles->read($path);\n }\n $compressor = new Zstd();\n $source = $compressor->decompress($source);\n break;\n case 'gzip':\n if (empty($source)) {\n $source = $deviceFiles->read($path);\n }\n $compressor = new GZIP();\n $source = $compressor->decompress($source);\n break;\n }\n\n if (!empty($source)) {\n if (!empty($rangeHeader)) {\n $response->send(substr($source, $start, ($end - $start + 1)));\n }\n $response->send($source);\n }\n\n if (!empty($rangeHeader)) {\n $response->send($deviceFiles->read($path, $start, ($end - $start + 1)));\n }\n\n $size = $deviceFiles->getFileSize($path);\n if ($size > APP_STORAGE_READ_BUFFER) {\n $response->addHeader('Content-Length', $deviceFiles->getFileSize($path));\n for ($i = 0; $i < ceil($size / MAX_OUTPUT_CHUNK_SIZE); $i++) {\n $response->chunk(\n $deviceFiles->read(\n $path,\n ($i * MAX_OUTPUT_CHUNK_SIZE),\n min(MAX_OUTPUT_CHUNK_SIZE, $size - ($i * MAX_OUTPUT_CHUNK_SIZE))\n ),\n (($i + 1) * MAX_OUTPUT_CHUNK_SIZE) >= $size\n );\n }\n } else {\n $response->send($deviceFiles->read($path));\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function function1(int $value, bool $value2)\n{\n}", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "public static function initEditorSystem(\n $id,\n $rand = '',\n $display = true,\n $readonly = false,\n $enable_images = true,\n int $editor_height = 150,\n array $add_body_classes = [],\n string $toolbar_location = 'top',\n bool $init = true,\n string $placeholder = '',\n bool $toolbar = true,\n bool $statusbar = true,\n string $content_style = ''\n ) {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n // load tinymce lib\n Html::requireJs('tinymce');\n\n $language = $_SESSION['glpilanguage'];\n if (!file_exists(GLPI_ROOT . \"/public/lib/tinymce-i18n/langs6/$language.js\")) {\n $language = $CFG_GLPI[\"languages\"][$_SESSION['glpilanguage']][2];\n if (!file_exists(GLPI_ROOT . \"/public/lib/tinymce-i18n/langs6/$language.js\")) {\n $language = \"en_GB\";\n }\n }\n $language_url = $CFG_GLPI['root_doc'] . '/public/lib/tinymce-i18n/langs6/' . $language . '.js';\n\n // Apply all GLPI styles to editor content\n $theme = ThemeManager::getInstance()->getCurrentTheme();\n $content_css_paths = [\n 'css/glpi.scss',\n 'css/core_palettes.scss',\n ];\n if ($theme->isCustomTheme()) {\n $content_css_paths[] = $theme->getPath();\n }\n $content_css = preg_replace('/^.*href=\"([^\"]+)\".*$/', '$1', self::css('public/lib/base.css', ['force_no_version' => true]));\n $content_css .= ',' . preg_replace('/^.*href=\"([^\"]+)\".*$/', '$1', self::css('public/lib/tabler.css', ['force_no_version' => true]));\n $content_css .= ',' . implode(',', array_map(static function ($path) {\n return preg_replace('/^.*href=\"([^\"]+)\".*$/', '$1', self::scss($path, ['force_no_version' => true]));\n }, $content_css_paths));\n $skin_url = preg_replace('/^.*href=\"([^\"]+)\".*$/', '$1', self::css('css/standalone/tinymce_empty_skin', ['force_no_version' => true]));\n\n // TODO: the recent changes to $skin_url above break tinyMCE's placeholders\n // Reverted to the previous version here, but this should be fixed properly\n $skin_url = $CFG_GLPI['root_doc'] . \"/public/lib/tinymce/skins/ui/oxide\";\n\n $cache_suffix = '?v=' . FrontEnd::getVersionCacheKey(GLPI_VERSION);\n $readonlyjs = $readonly ? 'true' : 'false';\n\n $invalid_elements = 'applet,canvas,embed,form,object';\n if (!$enable_images) {\n $invalid_elements .= ',img';\n }\n if (!GLPI_ALLOW_IFRAME_IN_RICH_TEXT) {\n $invalid_elements .= ',iframe';\n }\n\n $plugins = [\n 'autolink',\n 'autoresize',\n 'code',\n 'directionality',\n 'fullscreen',\n 'link',\n 'lists',\n 'quickbars',\n 'searchreplace',\n 'table',\n ];\n if ($enable_images) {\n $plugins[] = 'image';\n $plugins[] = 'glpi_upload_doc';\n }\n if ($DB->use_utf8mb4) {\n $plugins[] = 'emoticons';\n }\n $pluginsjs = json_encode($plugins);\n\n $language_opts = '';\n if ($language !== 'en_GB') {\n $language_opts = json_encode([\n 'language' => $language,\n 'language_url' => $language_url\n ]);\n }\n\n $mandatory_field_msg = json_encode(__('The %s field is mandatory'));\n\n // Add custom classes to tinymce body\n $body_class = \"rich_text_container\";\n foreach ($add_body_classes as $class) {\n $body_class .= \" $class\";\n }\n\n // Compute init option as \"string boolean\" so it can be inserted directly into the js output\n $init = $init ? 'true' : 'false';\n\n // Compute toolbar option as \"string boolean\" so it can be inserted directly into the js output\n $toolbar = $toolbar ? 'true' : 'false';\n\n // Compute statusbar option as \"string boolean\" so it can be inserted directly into the js output\n $statusbar = $statusbar ? 'true' : 'false';\n\n $js = <<<JS\n $(function() {\n const html_el = $('html');\n var richtext_layout = \"{$_SESSION['glpirichtext_layout']}\";\n\n // Store config in global var so the editor can be reinitialized from the client side if needed\n tinymce_editor_configs['{$id}'] = Object.assign({\n license_key: 'gpl',\n\n link_default_target: '_blank',\n branding: false,\n selector: '#' + $.escapeSelector('{$id}'),\n text_patterns: false,\n paste_webkit_styles: 'all',\n\n plugins: {$pluginsjs},\n\n // Appearance\n skin_url: '{$skin_url}', // Doesn't matter which skin is used. We include the proper skins in the core GLPI styles.\n body_class: '{$body_class}',\n content_css: '{$content_css}',\n content_style: '{$content_style}',\n highlight_on_focus: false,\n autoresize_bottom_margin: 1, // Avoid excessive bottom padding\n autoresize_overflow_padding: 0,\n\n min_height: $editor_height,\n height: $editor_height, // Must be used with min_height to prevent \"height jump\" when the page is loaded\n resize: true,\n\n // disable path indicator in bottom bar\n elementpath: false,\n\n placeholder: \"{$placeholder}\",\n\n // inline toolbar configuration\n menubar: false,\n toolbar_location: '{$toolbar_location}',\n toolbar: {$toolbar} && richtext_layout == 'classic'\n ? 'styles | bold italic | forecolor backcolor | bullist numlist outdent indent | emoticons table link image | code fullscreen'\n : false,\n quickbars_insert_toolbar: richtext_layout == 'inline'\n ? 'emoticons quicktable quickimage quicklink | bullist numlist | outdent indent '\n : false,\n quickbars_selection_toolbar: richtext_layout == 'inline'\n ? 'bold italic | styles | forecolor backcolor '\n : false,\n contextmenu: richtext_layout == 'classic'\n ? false\n : 'copy paste | emoticons table image link | undo redo | code fullscreen',\n\n // Status bar configuration\n statusbar: {$statusbar},\n\n // Content settings\n entity_encoding: 'raw',\n invalid_elements: '{$invalid_elements}',\n readonly: {$readonlyjs},\n relative_urls: false,\n remove_script_host: false,\n\n // Misc options\n browser_spellcheck: true,\n cache_suffix: '{$cache_suffix}',\n\n // Security options\n // Iframes are disabled by default. We assume that administrator that enable it are aware of the potential security issues.\n sandbox_iframes: false,\n\n init_instance_callback: (editor) => {\n const page_root_el = $(document.documentElement);\n const root_el = $(editor.dom.doc.documentElement);\n // Copy data-glpi-theme and data-glpi-theme-dark from page html element to editor root element\n const to_copy = ['data-glpi-theme', 'data-glpi-theme-dark'];\n for (const attr of to_copy) {\n if (page_root_el.attr(attr) !== undefined) {\n root_el.attr(attr, page_root_el.attr(attr));\n }\n }\n },\n setup: function(editor) {\n // \"required\" state handling\n if ($('#$id').attr('required') == 'required') {\n $('#$id').removeAttr('required'); // Necessary to bypass browser validation\n\n editor.on('submit', function (e) {\n if ($('#$id').val() == '') {\n const field = $('#$id').closest('.form-field').find('label').text().replace('*', '').trim();\n alert({$mandatory_field_msg}.replace('%s', field));\n e.preventDefault();\n\n // Prevent other events to run\n // Needed to not break single submit forms\n e.stopPropagation();\n }\n });\n editor.on('keyup', function (e) {\n editor.save();\n if ($('#$id').val() == '') {\n $(editor.container).addClass('required');\n } else {\n $(editor.container).removeClass('required');\n }\n });\n editor.on('init', function (e) {\n if (strip_tags($('#$id').val()) == '') {\n $(editor.container).addClass('required');\n }\n });\n editor.on('paste', function (e) {\n // Remove required on paste event\n // This is only needed when pasting with right click (context menu)\n // Pasting with Ctrl+V is already handled by keyup event above\n $(editor.container).removeClass('required');\n });\n }\n // Propagate click event to allow other components to\n // listen to it\n editor.on('click', function (e) {\n $(document).trigger('tinyMCEClick', [e]);\n });\n\n // Simulate focus on content-editable tinymce\n editor.on('click focus', function (e) {\n // Some focus events don't have the correct target and cant be handled\n if (!$(e.target.editorContainer).length) {\n return;\n }\n\n // Clear focus on other editors\n $('.simulate-focus').removeClass('simulate-focus');\n\n // Simulate input focus on our current editor\n $(e.target.editorContainer)\n .closest('.content-editable-tinymce')\n .addClass('simulate-focus');\n });\n\n editor.on('Change', function (e) {\n // Nothing fancy here. Since this is only used for tracking unsaved changes,\n // we want to keep the logic in common.js with the other form input events.\n onTinyMCEChange(e);\n\n // Propagate event to the document to allow other components to listen to it\n $(document).trigger('tinyMCEChange', [e]);\n });\n // ctrl + enter submit the parent form\n editor.addShortcut('ctrl+13', 'submit', function() {\n editor.save();\n submitparentForm($('#$id'));\n });\n }\n }, {$language_opts});\n\n // Init tinymce\n if ({$init}) {\n tinyMCE.init(tinymce_editor_configs['{$id}']);\n }\n });\nJS;\n\n if ($display) {\n echo Html::scriptBlock($js);\n } else {\n return Html::scriptBlock($js);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function checkSpecificValues($datatype, &$value)\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function createAgentTransmitterForResource(FHIRDomainResource $resource, FHIRReference $primaryBusinessEntity)\n {\n // agent:ProvenanceTransmitter - must support\n // agent:provenanceAuthor.type.coding.system=http://hl7.org/fhir/us/core/CodeSystem/us-core-provenance-participant-type - required\n // agent:provenanceAuthor.type.coding.code=transmitter - required\n\n $agent = new FHIRProvenanceAgent();\n $agentConcept = new FHIRCodeableConcept();\n $agentConceptCoding = new FHIRCoding();\n $agentConceptCoding->setSystem(\"http://hl7.org/fhir/us/core/CodeSystem/us-core-provenance-participant-type\");\n $agentConceptCoding->setCode(\"transmitter\");\n $agentConceptCoding->setDisplay(xlt(\"Transmitter\"));\n $agentConcept->addCoding($agentConceptCoding);\n $agent->setType($agentConcept);\n $agent->setWho($primaryBusinessEntity);\n $agent->setOnBehalfOf($primaryBusinessEntity);\n return $agent;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function __construct($message = 'unknown error', $code = null,\n $mode = null, $options = null, $userinfo = null)\n {\n\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "static function (int $errno, string $errstr) {\n throw new Exception($errstr);\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function read($amount=0, $offset=0) {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function imagecolorresolvealpha ($image, $red, $green, $blue, $alpha) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($app) {\n return new class () {\n private $output = [];\n\n public function log($class, $field, $mutator = false)\n {\n $class = $class . ($mutator ? ' as mutator' : '');\n\n if (!isset($this->output[$class])) {\n $this->output[$class] = [];\n }\n\n if (!in_array($field, $this->output[$class])) {\n $this->output[$class][] = $field;\n }\n }\n\n public function getOutput()\n {\n return $this->output;\n }\n };\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function aws_crt_signable_new_from_canonical_request(string $request): int {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getHTMLTableHeader(\n $itemtype,\n HTMLTableBase $base,\n ?HTMLTableSuperHeader $super = null,\n ?HTMLTableHeader $father = null,\n array $options = []\n ) {\n\n $column_name = __CLASS__;\n\n if (isset($options['dont_display'][$column_name])) {\n return;\n }\n\n $base->addHeader($column_name, __('Interface'), $super, $father);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (array $attributes) {\n return [\n 'published' => true,\n ];\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "private function writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, $dataType = 'str', PHPExcel_Worksheet $pSheet)\n {\n if (is_null($plotSeriesValues)) {\n return;\n }\n\n if ($plotSeriesValues->isMultiLevelSeries()) {\n $levelCount = $plotSeriesValues->multiLevelCount();\n\n $objWriter->startElement('c:multiLvlStrRef');\n\n $objWriter->startElement('c:f');\n $objWriter->writeRawData($plotSeriesValues->getDataSource());\n $objWriter->endElement();\n\n $objWriter->startElement('c:multiLvlStrCache');\n\n $objWriter->startElement('c:ptCount');\n $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount());\n $objWriter->endElement();\n\n for ($level = 0; $level < $levelCount; ++$level) {\n $objWriter->startElement('c:lvl');\n\n foreach ($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {\n if (isset($plotSeriesValue[$level])) {\n $objWriter->startElement('c:pt');\n $objWriter->writeAttribute('idx', $plotSeriesKey);\n\n $objWriter->startElement('c:v');\n $objWriter->writeRawData($plotSeriesValue[$level]);\n $objWriter->endElement();\n $objWriter->endElement();\n }\n }\n\n $objWriter->endElement();\n }\n\n $objWriter->endElement();\n\n $objWriter->endElement();\n } else {\n $objWriter->startElement('c:' . $dataType . 'Ref');\n\n $objWriter->startElement('c:f');\n $objWriter->writeRawData($plotSeriesValues->getDataSource());\n $objWriter->endElement();\n\n $objWriter->startElement('c:' . $dataType . 'Cache');\n\n if (($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {\n if (($plotSeriesValues->getFormatCode() !== null) && ($plotSeriesValues->getFormatCode() !== '')) {\n $objWriter->startElement('c:formatCode');\n $objWriter->writeRawData($plotSeriesValues->getFormatCode());\n $objWriter->endElement();\n }\n }\n\n $objWriter->startElement('c:ptCount');\n $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount());\n $objWriter->endElement();\n\n $dataValues = $plotSeriesValues->getDataValues();\n if (!empty($dataValues)) {\n if (is_array($dataValues)) {\n foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) {\n $objWriter->startElement('c:pt');\n $objWriter->writeAttribute('idx', $plotSeriesKey);\n\n $objWriter->startElement('c:v');\n $objWriter->writeRawData($plotSeriesValue);\n $objWriter->endElement();\n $objWriter->endElement();\n }\n }\n }\n\n $objWriter->endElement();\n\n $objWriter->endElement();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function forceDeleted(Service $service): void\n {\n //\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function createDMG($row, $X12info, $segTer, $compEleSep)\n {\n $DMG = array();\n $DMG[0] = \"DMG\"; // Date or Time or Period Segment ID\n $DMG[1] = \"D8\"; // Date Format Qualifier - (D8 means CCYYMMDD)\n $DMG[2] = $row['dob']; // Subscriber's Birth date\n $DMG[3] = strtoupper($row['sex'][0]);\n $DMG['Created'] = implode('*', $DMG); // Data Element Separator\n $DMG['Created'] = $DMG['Created'] . $segTer;\n return trim($DMG['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function sIsMember($key, $value)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function generateAccessPointHost(\n BaseAccessPointArn $arn,\n RequestInterface $req\n ) {\n if ($arn instanceof OutpostsAccessPointArn) {\n $accesspointName = $arn->getAccesspointName();\n } else {\n $accesspointName = $arn->getResourceId();\n }\n\n if ($arn instanceof MultiRegionAccessPointArn) {\n $partition = $this->partitionProvider->getPartitionByName(\n $arn->getPartition(),\n 's3'\n );\n $dnsSuffix = $partition->getDnsSuffix();\n return \"{$accesspointName}.accesspoint.s3-global.{$dnsSuffix}\";\n }\n\n $host = \"{$accesspointName}-\" . $arn->getAccountId();\n \n $useFips = $this->config['use_fips_endpoint']->isUseFipsEndpoint();\n $fipsString = $useFips ? \"-fips\" : \"\";\n\n if ($arn instanceof OutpostsAccessPointArn) {\n $host .= '.' . $arn->getOutpostId() . '.s3-outposts';\n } else if ($arn instanceof ObjectLambdaAccessPointArn) {\n if (!empty($this->config['endpoint'])) {\n return $host . '.' . $this->config['endpoint'];\n } else {\n $host .= \".s3-object-lambda{$fipsString}\";\n }\n } else {\n $host .= \".s3-accesspoint{$fipsString}\";\n if (!empty($this->config['dual_stack'])) {\n $host .= '.dualstack';\n }\n }\n\n if (!empty($this->config['use_arn_region']->isUseArnRegion())) {\n $region = $arn->getRegion();\n } else {\n $region = $this->region;\n }\n $region = \\Aws\\strip_fips_pseudo_regions($region);\n $host .= '.' . $region . '.' . $this->getPartitionSuffix($arn, $this->partitionProvider);\n return $host;\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function apc_bin_dumpfile($files, $user_vars, $filename, $flags = 0, $context = null){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function current_time(Mustache_Context $context)\n {\n return DateHelper::format_datetime(date('Y-m-d H:i'));\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function injectIntoDomSelector(string $html, string $code, string $selector, string $position, string $charset): string\n {\n $dom = new DomCrawler($html);\n $element = $dom->filter($selector)->eq(0);\n if ($element->count() && $node = $element->getNode(0)) {\n if (self::REPLACE === $position) {\n $node->textContent = $code;\n } elseif (self::POSITION_BEGINNING === $position) {\n $node->textContent = $code . $element->html();\n } elseif (self::POSITION_END === $position) {\n $node->textContent = $element->html() . $code;\n }\n }\n\n $html = html_entity_decode($dom->outerHtml());\n $dom->clear();\n unset($dom);\n\n return trim($html);\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function rom_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_rom\", $id);\n if ($data) {\n ?>\n\n <table border='1' bordercolor='#000000' cellpadding='7' cellspacing='0' class='text'>\n <col>\n <col>\n <col>\n <col>\n <tbody>\n\n <tr valign='top'>\n <td colspan='4'>\n <p align='left'><b>Neck</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>ACTIVE</b></p>\n </td>\n <td>\n <p align='center'><b>PASSIVE</b></p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-50\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_1_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_1_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Extension</p>\n </td>\n <td>\n <p align='center'><b>0-60\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_2_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_2_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Right Lateral Bending</p>\n </td>\n <td>\n <p align='center'><b>0-45\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_3_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_3_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Left Lateral Bending</p>\n </td>\n <td>\n <p align='center'><b>0-45\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_4_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_4_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Right Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-80\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_5_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_5_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Left Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-80\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_6_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_6_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='4'>\n <p align='left'><b>Back</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>ACTIVE</b></p>\n </td>\n <td>\n <p align='center'><b>PASSIVE</b></p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-90\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_7_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_7_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Extension</p>\n </td>\n <td>\n <p align='center'><b>0-25\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_8_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_8_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Right Lateral Bending</p>\n </td>\n <td>\n <p align='center'><b>0-25\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_9_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_9_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Left Lateral Bending</p>\n </td>\n <td>\n <p align='center'><b>0-25\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_10_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_10_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Right Lateral Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-30\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_11_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_11_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td>\n <p align='center'>Left Lateral Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-30\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_12_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r1_12_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n</tbody></table>\n</p>\n <table border='1' bordercolor='#000000' cellpadding='7' cellspacing='0' class='text'>\n <col>\n <col>\n <col>\n <col>\n <col>\n <col>\n<tr valign='top'>\n <td>\n <p align='center'>Straight Leg Raising (supine)</p>\n </td>\n <td>\n <p align='center'><b>0-90\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_1_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_1_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_1_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_1_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Straight Leg Raising (sitting)</p>\n </td>\n <td>\n <p align='center'><b>0-90\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_2_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_2_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_2_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_2_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Shoulder</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Abduction</p>\n </td>\n <td>\n <p align='center'><b>0-150\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_3_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_3_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_3_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_3_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Forward Elevation</p>\n </td>\n <td>\n <p align='center'><b>0-150\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_4_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_4_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_4_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_4_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Internal Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-80\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_5_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_5_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_5_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_5_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>External Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-90\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_6_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_6_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_6_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r2_6_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n</tbody></table>\n</p>\n <table border='1' bordercolor='#000000' cellpadding='7' cellspacing='0' class='text'>\n <col>\n <col>\n <col>\n <col>\n <col>\n <col>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Elbow and Forearm</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-150\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_1_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_1_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_1_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_1_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Extension</p>\n </td>\n <td>\n <p align='center'><b>0\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_2_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_2_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_2_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_2_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Supination</p>\n </td>\n <td>\n <p align='center'><b>0-80\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_3_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_3_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_3_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_3_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Pronation</p>\n </td>\n <td>\n <p align='center'><b>0-80\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_4_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_4_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_4_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_4_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Wrist</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Dorsiflexion</p>\n </td>\n <td>\n <p align='center'><b>0-60\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_5_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_5_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_5_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_5_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Palmar Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-60\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_6_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_6_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_6_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_6_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Radial Deviation</p>\n </td>\n <td>\n <p align='center'><b>0-20\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_7_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_7_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_7_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_7_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Ulnar Deviation</p>\n </td>\n <td>\n <p align='center'><b>0-30\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_8_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_8_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_8_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_8_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Hip</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Abduction</p>\n </td>\n <td>\n <p align='center'><b>0-40\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_9_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_9_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_9_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_9_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Adduction</p>\n </td>\n <td>\n <p align='center'><b>0-20\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_10_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_10_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_10_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_10_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-100\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_11_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_11_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_11_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_11_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Extension</p>\n </td>\n <td>\n <p align='center'><b>0-30\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_12_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_12_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_12_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_12_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Internal Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-40\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_13_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_13_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_13_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_13_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>External Rotation</p>\n </td>\n <td>\n <p align='center'><b>0-50\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_14_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_14_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_14_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_14_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Knee</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-150\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_15_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_15_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_15_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_15_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Extension</p>\n </td>\n <td>\n <p align='center'><b>0\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_16_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_16_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_16_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_16_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Ankle and Foot</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Dorsiflexion</p>\n </td>\n <td>\n <p align='center'><b>0-20\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_17_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_17_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_17_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_17_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Plantar Flexion</p>\n </td>\n <td>\n <p align='center'><b>0-40\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_18_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_18_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_18_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_18_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Inversion</p>\n </td>\n <td>\n <p align='center'><b>0-30\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_19_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_19_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_19_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_19_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>Eversion</p>\n </td>\n <td>\n <p align='center'><b>0-20\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_20_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_20_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_20_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r3_20_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n</tbody></table>\n</p>\n <table border='1' bordercolor='#000000' cellpadding='7' cellspacing='0' class='text'>\n <col>\n <col>\n <col>\n <col>\n <col>\n <col>\n\n <tr valign='top'>\n <td colspan='6'>\n <p align='left'><b>Hands and Fingers</b></p>\n </td>\n </tr>\n <tr valign='top'>\n <td>\n <p align='center'>&nbsp;</b></p>\n </td>\n <td>\n <p align='center'><b>NORMAL</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(R) Passive</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Active</b></p>\n </td>\n <td>\n <p align='center'><b>(L) Passive</b></p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>MCP Flexion thumb</p>\n </td>\n <td>\n <p align='center'><b>0-90\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_1_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_1_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_1_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_1_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>MCP flexion rest fingers</p>\n </td>\n <td>\n <p align='center'><b>0-90</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_2_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_2_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_2_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_2_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>MCP extension</p>\n </td>\n <td>\n <p align='center'><b>0\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_3_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_3_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_3_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_3_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>PIP Flexion all fingers</p>\n </td>\n <td>\n <p align='center'><b>0-100\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_4_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_4_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_4_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_4_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>PIP extension</p>\n </td>\n <td>\n <p align='center'><b>0\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_5_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_5_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_5_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_5_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>DIP flexion</p>\n </td>\n <td>\n <p align='center'><b>0-70\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_6_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_6_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_6_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_6_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n<tr valign='top'>\n <td>\n <p align='center'>DIP extension</p>\n </td>\n <td>\n <p align='center'><b>0\u00b0</b></p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_7_rt_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_7_rt_passive']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_7_lf_active']); ?>&nbsp;</p>\n </td>\n <td>\n <p align='center'><?php echo text($data['r4_7_lf_passive']); ?>&nbsp;</p>\n </td>\n </tr>\n</tbody></table>\n <?php if ($data['notes'] != '') {?>\n </p>\n <table border='0' cellpadding='0' cellspacing='0' class='text'>\n <tr class='text'>\n <td><b>NOTES</b></td>\n </tr>\n <tr class='text'>\n <td><p align='left'><?php echo text($data['notes']); ?>&nbsp;</p></td>\n </tr>\n </table>\n <?php } ?>\n\n <?php\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = [], $params = [])\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getTimespan($plain_array=false){\n $res = null;\n if($this->isValid()){\n //[start, latest-start, earliest-end, end, label, profile-start, profile-end, determination]\n\n $minmax = $this->calcMinMax();\n\n if(intval($minmax[0])<-250000){\n return null;\n }\n\n $res = array($minmax[0],'','',$minmax[1],$this->toReadableExt('',true), 0, 0, 0);\n\n $date = $this->tDate;\n\n if(@$date['timestamp']){\n\n $profile = 0;\n\n if($date['timestamp']['type']=='c'){ //radiometric/carbon\n\n if(@$date['timestamp']['deviation_negative'] && !@$date['timestamp']['deviation_positive']){\n $profile = 2; //slow start\n }elseif(!@$date['timestamp']['deviation_negative'] && @$date['timestamp']['deviation_positive']){\n $profile = 3; //slow finish\n }else{\n $profile = 1; //central\n }\n\n }elseif(@$date['timestamp']['circa']){\n $profile = 1; //central\n }elseif(@$date['timestamp']['before']){\n $profile = 2; //slow start\n }elseif(@$date['timestamp']['after']){\n $profile = 3; //slow finish\n }\n\n $res[5] = $profile;\n\n }else{\n $res[1] = Temporal::dateToISO($date['start']['latest'],2,false);\n $res[2] = Temporal::dateToISO($date['end']['earliest'],2,false);\n\n if(@$date['profile']){\n //simple range\n $res[5] = $date['profile'];\n }else{\n //fuzzy range\n if(@$date['start']['profile']>0) {$res[5] = $date['start']['profile'];}\n if(@$date['end']['profile']>0) {$res[6] = $date['end']['profile'];}\n }\n }\n\n //profile: Flat(0), Central(1) (circa), Slow Start(2) (before), Slow Finish(3) (after) - responsible for gradient\n //determination: Unknown(0), Conjecture(2), Measurment(3), Attested(1) - color depth\n if(@$date['determination']){\n $res[7] = $date['determination'];\n }\n }\n return $res;\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function show_404($page = '', $log_error = TRUE)\n\t{\n\t\tthrow new RuntimeException('CI Error: 404');\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function getBestellingLaatste(\n\t\t$persoon,\n\t\t\\DateTimeImmutable $begin = null,\n\t\t\\DateTimeImmutable $eind = null,\n\t\t$productIDs = []\n\t) {\n\t\tif ($begin == null) {\n\t\t\t$begin = date_create_immutable()->add(new \\DateInterval('P15H'));\n\t\t} else {\n\t\t\t$begin = $begin->setTime(0, 0, 0);\n\t\t}\n\t\tif ($eind == null) {\n\t\t\t$eind = date_create_immutable();\n\t\t} else {\n\t\t\t$eind = $eind->setTime(23, 59, 59);\n\t\t}\n\n\t\tif ($persoon == 'alles') {\n\t\t\treturn $this->civiBestellingRepository->findTussen($begin, $eind, [\n\t\t\t\t'soccie',\n\t\t\t\t'oweecie',\n\t\t\t]);\n\t\t} else {\n\t\t\treturn $this->civiBestellingRepository->findTussen(\n\t\t\t\t$begin,\n\t\t\t\t$eind,\n\t\t\t\t['soccie', 'oweecie'],\n\t\t\t\t$persoon\n\t\t\t);\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function incrementByKey ($server_key, $key, $offset = 1, $initial_value = 0, $expiry = 0) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($request) use ($params) {\n return $this->options = array_merge_recursive($this->options, [\n 'query' => $params,\n ]);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new CcdaGenerator($container->get(EncounterccdadispatchTable::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getImageHtmlTagForDocument($document_id, $width, $height, $addLink = true, $more_link = \"\")\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $document = new Document();\n if (!$document->getFromDB($document_id)) {\n return '';\n }\n\n $base_path = $CFG_GLPI['root_doc'];\n if (isCommandLine()) {\n $base_path = parse_url($CFG_GLPI['url_base'], PHP_URL_PATH);\n }\n\n // Add only image files : try to detect mime type\n $ok = false;\n $mime = '';\n if (isset($document->fields['filepath'])) {\n $fullpath = GLPI_DOC_DIR . \"/\" . $document->fields['filepath'];\n $mime = Toolbox::getMime($fullpath);\n $ok = Toolbox::getMime($fullpath, 'image');\n }\n\n if (!($ok || empty($mime))) {\n return '';\n }\n\n $out = '';\n if ($addLink) {\n $out .= '<a '\n . 'href=\"' . $base_path . '/front/document.send.php?docid=' . $document_id . $more_link . '\" '\n . 'target=\"_blank\" '\n . '>';\n }\n $out .= '<img ';\n if (isset($document->fields['tag'])) {\n $out .= 'alt=\"' . $document->fields['tag'] . '\" ';\n }\n $out .= 'width=\"' . $width . '\" '\n . 'src=\"' . $base_path . '/front/document.send.php?docid=' . $document_id . $more_link . '\" '\n . '/>';\n if ($addLink) {\n $out .= '</a>';\n }\n\n return $out;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function intlcal_get_maximum($calendar, $field) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new DocumentsController($container->get(DocumentsTable::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function upgrade_sql($modId, $currentActionStatus): mixed\n {\n return $currentActionStatus;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function cache_info($type = NULL)\n\t{\n\t\treturn get_dir_file_info($this->_cache_path);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function connect(\n $host,\n $port = 6379,\n $timeout = 0.0,\n $reserved = null,\n $retryInterval = 0,\n $readTimeout = 0.0,\n $connectionParameters = []\n ) {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function treatment_protocols_report($pid, $encounter, $cols, $id)\n{\n /****\n $cols = 1; // force always 1 column\n $count = 0;\n $data = sqlQuery(\"SELECT * \" .\n \"FROM form_treatment_protocols WHERE \" .\n \"id = '$id'\");\n if ($data) {\n print \"<table cellpadding='0' cellspacing='0'>\\n<tr>\\n\";\n foreach($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" ||\n $key == \"authorized\" || $key == \"activity\" || $key == \"date\" ||\n $value == \"\" || $value == \"0\" || $value == \"0.00\") {\n continue;\n }\n\n if ($key == 'followup_required') {\n switch ($value) {\n case '1': $value = 'Yes'; break;\n case '2': $value = 'Pending investigation'; break;\n }\n }\n\n $key=ucwords(str_replace(\"_\",\" \",$key));\n print \"<td valign='top'><span class='bold'>\" . text($key) . \": </span><span class='text'>\" . text($value) . \" &nbsp;</span></td>\\n\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr>\\n<tr>\\n\";\n }\n }\n print \"</tr>\\n</table>\\n\";\n }\n ****/\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function setChecks($checks) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function eagerlyManyToMany($where, $relation, $subRelation = '', $closure = null)\n {\n // \u9884\u8f7d\u5165\u5173\u8054\u67e5\u8be2 \u652f\u6301\u5d4c\u5957\u9884\u8f7d\u5165\n if ($closure instanceof Closure) {\n $closure($this->query);\n }\n\n $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where)\n ->with($subRelation)\n ->select();\n\n // \u7ec4\u88c5\u6a21\u578b\u6570\u636e\n $data = [];\n foreach ($list as $set) {\n $pivot = [];\n foreach ($set->getData() as $key => $val) {\n if (strpos($key, '__')) {\n list($name, $attr) = explode('__', $key, 2);\n if ('pivot' == $name) {\n $pivot[$attr] = $val;\n unset($set->$key);\n }\n }\n }\n\n $set->setRelation($this->pivotDataName, $this->newPivot($pivot, true));\n\n $data[$pivot[$this->localKey]][] = $set;\n }\n\n return $data;\n }", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function (HttpRestRequest $request) {\n RestConfig::authorization_check(\"patients\", \"demo\");\n $data = (array) (json_decode(file_get_contents(\"php://input\"), true));\n $return = (new FhirPatientRestController())->post($data);\n RestConfig::apiLog($return, $data);\n return $return;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function __construct(\n iDatabase $dest_db,\n array $source_data = array(),\n $insert_table,\n array $insert_fields = array(),\n array $post_ingest_update_statements = array(),\n $delete_statement = null,\n $count_statement = null\n ) {\n $this->_dest_db = $dest_db;\n\n $this->_source_data = $source_data;\n $this->_insert_table = $insert_table;\n $this->_insert_fields = $insert_fields;\n\n $this->_post_ingest_update_statements = $post_ingest_update_statements;\n $this->_delete_statement = $delete_statement;\n\n $this->_logger = Log::singleton('xdconsole');\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new CcdTable($container->get(\\Laminas\\Db\\Adapter\\Adapter::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function amcTrackingRequest($amc_id, $start = '', $end = '', $provider_id = '')\n{\n $where = '';\n\n # Collect the patient list first (from the provider)\n $patients = array();\n if (empty($provider)) {\n // Look at entire practice\n $rez = sqlStatement(\"SELECT `pid`, `fname`, `lname` FROM `patient_data`\");\n for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {\n $patients[$iter] = $row;\n }\n } else {\n // Look at one provider\n $rez = sqlStatement(\"SELECT `pid`, `fname`, `lname` FROM `patient_data` \" .\n \"WHERE providerID=?\", array($provider));\n for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {\n $patients[$iter] = $row;\n }\n }\n\n $results = array();\n foreach ($patients as $patient) {\n $tempResults = array();\n\n if ($amc_id == \"send_sum_amc\") {\n $sqlBindArray = array();\n array_push($sqlBindArray, $patient['pid']);\n if (!(empty($start))) {\n $where = \" AND `date`>=? \";\n array_push($sqlBindArray, $start);\n }\n\n if (!(empty($end))) {\n $where .= \" AND `date`<=? \";\n array_push($sqlBindArray, $end);\n }\n\n $rez = sqlStatement(\"SELECT `id`, `date` FROM `transactions` WHERE `title` = 'LBTref' AND `pid` = ? $where ORDER BY `date` DESC\", $sqlBindArray);\n while ($res = sqlFetchArray($rez)) {\n $amcCheck = amcCollect(\"send_sum_amc\", $patient['pid'], \"transactions\", $res['id']);\n if (empty($amcCheck)) {\n // Records have not been sent, so send this back\n array_push($tempResults, array(\"pid\" => $patient['pid'], \"fname\" => $patient['fname'], \"lname\" => $patient['lname'], \"date\" => $res['date'], \"id\" => $res['id']));\n }\n }\n } elseif ($amc_id == \"provide_rec_pat_amc\") {\n $sqlBindArray = array();\n array_push($sqlBindArray, $patient['pid']);\n if (!(empty($start))) {\n $where = \" AND `date_created`>=? \";\n array_push($sqlBindArray, $start);\n }\n\n if (!(empty($end))) {\n $where .= \" AND `date_created`<=? \";\n array_push($sqlBindArray, $end);\n }\n\n $rez = sqlStatement(\"SELECT * FROM `amc_misc_data` WHERE `amc_id`='provide_rec_pat_amc' AND `pid`=? AND \" .\n dateEmptySql('date_completed', true) .\n \"$where ORDER BY `date_created` DESC\", $sqlBindArray);\n while ($res = sqlFetchArray($rez)) {\n // Records have not been sent, so send this back\n array_push($tempResults, array(\"pid\" => $patient['pid'], \"fname\" => $patient['fname'], \"lname\" => $patient['lname'], \"date\" => $res['date_created']));\n }\n } elseif ($amc_id == \"provide_sum_pat_amc\") {\n $sqlBindArray = array();\n array_push($sqlBindArray, $patient['pid']);\n if (!(empty($start))) {\n $where = \" AND `date`>=? \";\n array_push($sqlBindArray, $start);\n }\n\n if (!(empty($end))) {\n $where .= \" AND `date`<=? \";\n array_push($sqlBindArray, $end);\n }\n\n $rez = sqlStatement(\"SELECT `encounter`, `date` FROM `form_encounter` WHERE `pid`=? $where ORDER BY `date` DESC\", $sqlBindArray);\n while ($res = sqlFetchArray($rez)) {\n $amcCheck = amcCollect(\"provide_sum_pat_amc\", $patient['pid'], \"form_encounter\", $res['encounter']);\n if (empty($amcCheck)) {\n // Records have not been given, so send this back\n array_push($tempResults, array(\"pid\" => $patient['pid'], \"fname\" => $patient['fname'], \"lname\" => $patient['lname'], \"date\" => $res['date'], \"id\" => $res['encounter']));\n }\n }\n } else {\n // report nothing\n return;\n }\n\n // process results\n $results = array_merge($results, $tempResults);\n }\n\n // send results\n return $results;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function doExportFieldcollection(Concrete $object, array &$result, Fieldcollection $container, Data\\Fieldcollections $containerDef): void\n {\n $resultContainer = [];\n\n $items = $container->getItems();\n foreach ($items as $item) {\n $type = $item->getType();\n\n $itemValues = [];\n\n $itemContainerDefinition = Fieldcollection\\Definition::getByKey($type);\n $fDefs = $itemContainerDefinition->getFieldDefinitions();\n\n foreach ($fDefs as $fd) {\n $getter = 'get' . ucfirst($fd->getName());\n $value = $item->$getter();\n\n if ($fd instanceof NormalizerInterface\n && $fd instanceof DataObject\\ClassDefinition\\Data) {\n $marshalledValue = $fd->normalize($value);\n $itemValues[$fd->getName()] = $marshalledValue;\n }\n }\n\n $resultContainer[] = [\n 'type' => $type,\n 'value' => $itemValues,\n ];\n }\n\n //TODO block\n\n $result[$container->getFieldname()] = $resultContainer;\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function (&$value, $key) {\n if ($value instanceof Element\\ElementInterface) {\n $value = $value->getId();\n } elseif (is_object($value) && method_exists($value, '__toString')) {\n $value = (string)$value;\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function prepareKanbanStateForUpdate($oldstate, $newstate, $users_id)\n {\n return $newstate;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function display_PMSFH($rows, $view = \"pending\", $min_height = \"min-height:344px;\")\n{\n global $PMSFH;\n global $pid;\n global $PMSFH_titles;\n if (!($PMFSH ?? '')) {\n $PMSFH = build_PMSFH($pid);\n }\n\n ob_start();\n // There are two rows in our PMH section, only one in the side panel.\n // If you want it across the bottom in a panel with 8 rows? Or other wise?\n // This should be able to handle that too.\n\n // We are building the PMSFH panel.\n // Let's put half in each of the 2 rows... or try to at least.\n // Find out the number of items present now and put half in each column.\n foreach ($PMSFH[0] as $key => $value) {\n if (!empty($total_PMSFH)) {\n $total_PMSFH += count($PMSFH[0][$key]);\n $total_PMSFH += 2; //add two for the title and a space\n } else {\n $total_PMSFH = count($PMSFH[0][$key]);\n $total_PMSFH = 2; //add two for the title and a space\n }\n $count[$key] = count($PMSFH[0][$key]) + 1;\n }\n\n //SOCH, FH and ROS are listed in $PMSFH even if negative, only count positives\n foreach ($PMSFH[0]['ROS'] as $key => $value) {\n if (empty($value['display'])) {\n if (!empty($total_PMSFH)) {\n $total_PMSFH--;\n }\n $count['ROS']--;\n }\n }\n\n foreach ($PMSFH[0]['FH'] as $key => $value) {\n if ($value['display'] == '') {\n if (!empty($total_PMSFH)) {\n $total_PMSFH--;\n } else {\n $total_PMSFH = 0;\n }\n $count['FH']--;\n }\n }\n\n foreach ($PMSFH[0]['SOCH'] as $key => $value) {\n if (($value['display'] == '') || (($item['display'] ?? '') == 'not_applicable')) {\n $total_PMSFH--;\n $count['SOCH']--;\n }\n }\n\n $counter = \"0\";\n $column_max = round(($total_PMSFH ?? null) / $rows) + 1;\n if ($column_max < \"25\") {\n $column_max = '20';\n }\n\n $open_table = \"<div style='float:left' class='table PMSFH_table'>\";\n $close_table = \"</div>\";\n // $div is used when $counter reaches $column_max and a new row is needed.\n // It is used only if $row_count <= $rows, ie. $rows -1 times.\n $div = '</div>\n <div id=\"PMSFH_block_2\" name=\"PMSFH_block_2\" class=\"QP_block_outer borderShadow text_clinical\" style=\"' . attr($min_height) . '\">';\n\n echo $header = '\n <div id=\"PMSFH_block_1\" name=\"PMSFH_block_1\" class=\"QP_block borderShadow text_clinical\" style=\"' . attr($min_height) . ';\">\n ';\n $row_count = 1;\n\n foreach ($PMSFH[0] as $key => $value) {\n if ($key == \"FH\" || $key == \"SOCH\" || $key == \"ROS\") {\n // We are going to build SocHx, FH and ROS separately below since they are different..\n continue;\n }\n\n $table = '';\n $header = '';\n $header .= ' <table class=\"PMSFH_header\">\n <tr>\n <td width=\"90%\">\n <span class=\"left\" style=\"font-weight:800;font-size:0.9em;\">' . xlt($key) . '</span>\n </td>\n <td>\n <span class=\"right btn-sm\" href=\"#PMH_anchor\" onclick=\"alter_issue2(\\'0\\',' . attr_js($key) . ',\\'0\\');\" style=\"text-align:right;font-size:8px;\">' . xlt(\"New\") . '</span>\n </td>\n </tr>\n </table>\n ';\n if (count($PMSFH[0][$key]) > '0') {\n $index = 0;\n foreach ($PMSFH[0][$key] as $item) {\n if (\n ( ($key == \"Medication\") || ($key == \"Eye Meds\") )\n &&\n ($item['status'] == \"Inactive\")\n ) {\n continue;\n }\n if (($key == \"Medication\") && ( !empty($item['row_subtype']))) {\n $subtype_Meds[$item['row_subtype']]['name'] = $item['row_subtype'];\n $subtype_Meds[$item['row_subtype']]['header'] = '\n <table class=\"PMSFH_header\">\n <tr>\n <td width=\"90%\">\n <span class=\"left\" style=\"font-weight:800;font-size:0.9em;\">' . xlt(ucwords($item['row_subtype'])) . ' Meds</span>\n </td>\n <td>\n <span class=\"right btn-sm\" href=\"#PMH_anchor\" onclick=\"alter_issue2(\\'0\\',\\'Eye Meds\\',\\'0\\');\" style=\"text-align:right;font-size:8px;\">' . xlt(\"New\") . '</span>\n </td>\n </tr>\n </table>\n ';\n $subtype_Meds[$item['row_subtype']]['table'] .= \"<span name='QP_PMH_\" . attr($item['rowid']) . \"' href='#PMH_anchor' id='QP_PMH_\" . attr($item['rowid']) . \"'\n onclick=\\\"alter_issue2(\" . attr_js($item['rowid']) . \",\\\"Eye Meds\\\",\" . attr_js($index) . \");\\\">\" . text($item['title']) . \"</span><br />\";\n $index++;\n continue;\n }\n\n if ($key == \"Allergy\") {\n if ($item['reaction']) {\n $reaction = \" (\" . text($item['reaction']) . \")\";\n } else {\n $reaction = \"\";\n }\n\n $red = \"style='color:red;'\";\n } else {\n $red = '';\n }\n\n $table .= \"<span $red name='QP_PMH_\" . $item['rowid'] . \"' href='#PMH_anchor' id='QP_PMH_\" . $item['rowid'] . \"'\n onclick=\\\"alter_issue2(\" . attr_js($item['rowid']) . \",\" . attr_js($key) . \",\" . attr_js($index) . \");\\\">\" . text($item['title'] . ($reaction ?? '')) . \"</span><br />\";\n $index++;\n }\n } else {\n if ($key == \"Allergy\") {\n $table .= xlt(\"NKDA{{No known drug allergies}}\");\n } else {\n $table .= xlt(\"None\");\n }\n\n $counter++;\n }\n\n $display_PMSFH[$key] = $header . $open_table . $table . $close_table;\n }\n\n echo $display_PMSFH['POH'];\n $count = $count['POH'] + $count['PMH'] + 4;\n if ($count >= $column_max) {\n echo $div . $header1;\n }\n\n echo $display_PMSFH['POS'];\n $count = $count + ($count['POS'] ?? null) + 4;\n if ($count >= $column_max) {\n echo $div . $header1;\n }\n\n echo $display_PMSFH['Eye Meds'];\n $count = $count + ($count['Surgery'] ?? null) + 4;\n if (($count >= $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n }\n\n echo $display_PMSFH['PMH'];\n $count = $count + ($count['Surgery'] ?? null) + 4;\n if (($count >= $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n }\n\n echo $display_PMSFH['Surgery'];\n\n $count = $count + ($count['Medication'] ?? null) + 4;\n if (($count >= $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n }\n\n echo $display_PMSFH['Medication'];\n\n $count = $count + ($count['Allergy'] ?? null) + 4;\n if (($count >= $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n }\n\n echo $display_PMSFH['Allergy'];\n\n $count = $count + ($count['FH'] ?? null) + 4;\n if (($count >= $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n } ?>\n <table class=\"PMSFH_header\">\n <tr>\n <td width=\"90%\">\n <span class=\"left\" style=\"font-weight:800;font-size:0.9em;\"><?php echo xlt(\"FH{{Family History}}\"); ?></span>\n </td>\n <td >\n <span class=\"right btn-sm\" href=\"#PMH_anchor\" onclick=\"alter_issue2('0','FH','');\" style=\"text-align:right;font-size:8px;\"><?php echo xlt(\"New\"); ?></span>\n </td>\n </tr>\n </table>\n <?php\n echo $open_table;\n $mention_FH = 0;\n if (count($PMSFH[0]['FH']) > 0) {\n foreach ($PMSFH[0]['FH'] as $item) {\n if (($counter > $column_max) && ($row_count < $rows)) {\n echo $close_table . $div . $open_table;\n $counter = \"0\";\n $row_count++;\n }\n\n if ($item['display'] > '') {\n $counter++;\n echo \"<span name='QP_PMH_\" . attr($item['rowid'] ?? '') . \"' href='#PMH_anchor' id='QP_PMH_\" . attr($item['rowid'] ?? '') . \"'\n onclick=\\\"alter_issue2('0','FH','');\\\">\" . xlt($item['short_title']) . \": \" . text($item['display']) . \"</span><br />\";\n $mention_FH++;\n }\n }\n }\n\n if (empty($mention_FH)) { ?>\n <span href=\"#PMH_anchor\" onclick=\"alter_issue2('0','FH','');\" style=\"text-align:right;\"><?php echo xlt(\"Negative\"); ?></span><br />\n <?php\n $counter = $counter + 3;\n }\n\n echo $close_table;\n $count = $count + ($count['SOCH'] ?? null) + 4;\n\n if (($count > $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n } ?>\n <table class=\"PMSFH_header\">\n <tr>\n <td width=\"90%\">\n <span class=\"left\" style=\"font-weight:800;font-size:0.9em;\"><?php echo xlt(\"Social\"); ?></span>\n </td>\n <td >\n <span class=\"right btn-sm\" href=\"#PMH_anchor\" onclick=\"alter_issue2('0','SOCH','');\" style=\"text-align:right;font-size:8px;\"><?php echo xlt(\"New\"); ?></span>\n </td>\n </tr>\n </table>\n <?php\n echo $open_table;\n $mention_SOCH = 0;\n foreach ($PMSFH[0]['SOCH'] as $item) {\n if (($counter > $column_max) && ($row_count < $rows)) {\n echo $close_table . $div . $open_table;\n $counter = \"0\";\n $row_count++;\n }\n\n if (($item['display'] > '') && ($item['display'] != 'not_applicable')) {\n echo \"<span name='QP_PMH_\" . ($item['rowid'] ?? '') . \"' href='#PMH_anchor' id='QP_PMH_\" . ($item['rowid'] ?? '') . \"'\n onclick=\\\"alter_issue2('0','SOCH','');\\\">\" . xlt($item['short_title']) . \": \" . text($item['display']) . \"</span><br />\";\n $counter++;\n $mention_SOCH++;\n }\n }\n\n if (empty($mention_SOCH)) {\n ?>\n <span href=\"#PMH_anchor\"\n onclick=\"alter_issue2('0','SOCH','');\" style=\"text-align:right;\"><?php echo xlt(\"Not documented\"); ?></span><br />\n <?php\n $counter = $counter + 2;\n }\n\n echo $close_table;\n $count = $count + ($count['ROS'] ?? null) + 4;\n\n if (($count > $column_max) && ($row_count < $rows)) {\n echo $div;\n $count = 0;\n $row_count = 2;\n } ?>\n <table class=\"PMSFH_header\">\n <tr>\n <td width=\"90%\">\n <span class=\"left\" style=\"font-weight:800;font-size:0.9em;\"><?php echo xlt(\"ROS{{Review of Systems}}\"); ?></span>\n </td>\n <td >\n <span class=\"right btn-sm\" href=\"#PMH_anchor\" onclick=\"alter_issue2('0','ROS','');\" style=\"text-align:right;font-size:8px;\"><?php echo xlt(\"New\"); ?></span>\n </td>\n </tr>\n </table>\n <?php\n echo $open_table;\n $mention = 0;\n\n foreach ($PMSFH[0]['ROS'] as $item) {\n if (($item['display'] ?? '') > '') {\n if (($counter > $column_max) && ($row_count < $rows)) {\n echo $close_table . $div . $open_table;\n $counter = \"0\";\n $row_count++;\n }\n\n //xlt($item['short_title']) - for a list of short_titles, see the predefined ROS categories\n echo \"<span name='QP_PMH_\" . attr($item['rowid'] ?? '') . \"' href='#PMH_anchor' id='QP_PMH_\" . attr($item['rowid'] ?? '') . \"'\n onclick=\\\"alter_issue2('0','ROS','');\\\">\" . xlt($item['short_title']) . \": \" . text($item['display']) . \"</span><br />\";\n $mention++;\n $counter++;\n }\n }\n\n if (empty($mention)) {\n echo xlt(\"Negative\") . \"<br />\";\n $counter = $counter++;\n }\n\n echo $close_table;\n ?>\n </div>\n <?php\n $PMH_panel = ob_get_contents();\n ob_end_clean();\n return $PMH_panel;\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($domSelector, $datetimepicker_timepicker = true, $datetimepicker_showseconds = true, $datetimepicker_formatInput = true) {\n ob_start();\n // In the event we need to pass the this objecto to the datetimepicker, we cannot use quotations because `this` would not be a string\n $selector = ($domSelector == \"this\") ? $domSelector : \"\\\"$domSelector\\\"\";\n echo \"$($selector).datetimepicker({\";\n require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php');\n echo \"})\";\n return ob_get_clean();\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ftp_rmdir(FTP\\Connection|resource $ftp, string $directory): bool {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function _include($filename, $once=false, $params=null)\n {\n if ($once) {\n return include_once($filename);\n } else {\n return include($filename);\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function generateManifest(string $algorithm, OutputInterface $output): void\n {\n $manifest_output = GLPI_ROOT . '/version/' . VersionParser::getNormalizedVersion(GLPI_VERSION, false);\n $checker = new SourceCodeIntegrityChecker();\n $manifest = $checker->generateManifest($algorithm);\n $manifest_json = json_encode($manifest, JSON_PRETTY_PRINT);\n $manifest_length = strlen($manifest_json);\n if (file_put_contents($manifest_output, $manifest_json) !== $manifest_length) {\n throw new \\RuntimeException(sprintf('Failed to write manifest to %s', $manifest_output));\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(\n\t\tGroep $groep,\n\t\t$action,\n\t\t$magWijzigen,\n\t\tprivate $isWijzigen,\n\t\t$nocancel = false\n\t) {\n\t\tparent::__construct(\n\t\t\t$groep,\n\t\t\t$action,\n\t\t\tReflectionUtil::classNameZonderNamespace($groep::class),\n\t\t\ttrue\n\t\t);\n\t\tif ($groep->id) {\n\t\t\t$this->titel .= ' wijzigen';\n\t\t} else {\n\t\t\t$this->titel .= ' aanmaken';\n\t\t}\n\t\t$fields = FormFieldFactory::generateFields($this->model);\n\n\t\t$fields['oudId']->hidden = true;\n\n\t\t$fields['familie'] = new RequiredAutocompleteField(\n\t\t\t'familie',\n\t\t\t$this->model->familie,\n\t\t\t$fields['familie']->description,\n\t\t\tfalse\n\t\t);\n\t\t$fields['familie']->title =\n\t\t\t'Vul hier een \\'achternaam\\' in zodat de juiste ketzers elkaar opvolgen';\n\t\t$fields['familie']->suggestions[] = $groep->getFamilieSuggesties();\n\t\t$fields['omschrijving']->description = 'Meer lezen';\n\n\t\tif ($groep instanceof HeeftMoment) {\n\t\t\t$fields['beginMoment']->to_datetime = $fields['eindMoment'];\n\t\t\t$fields['eindMoment']->from_datetime = $fields['beginMoment'];\n\t\t}\n\n\t\tif ($groep instanceof Activiteit) {\n\t\t\t$fields['eindMoment']->required = true;\n\t\t}\n\n\t\tif ($groep instanceof HeeftAanmeldMoment) {\n\t\t\t$fields['aanmeldenVanaf']->to_datetime = $fields['aanmeldenTot'];\n\t\t\t$fields['aanmeldenTot']->from_datetime = $fields['aanmeldenVanaf'];\n\n\t\t\tif ($groep instanceof HeeftMoment) {\n\t\t\t\t$fields['beginMoment']->title =\n\t\t\t\t\t'Dit is NIET het moment van openstellen voor aanmeldingen';\n\t\t\t\t$fields['eindMoment']->title =\n\t\t\t\t\t'Dit is NIET het moment van sluiten voor aanmeldingen';\n\t\t\t}\n\t\t}\n\n\t\tif ($groep instanceof Ketzer || $groep instanceof Activiteit) {\n\t\t\t$fields['bewerkenTot']->title =\n\t\t\t\t'Leden mogen hun eigen opmerking of keuze niet aanpassen als u dit veld leeg laat';\n\t\t\t$fields['afmeldenTot']->title =\n\t\t\t\t'Leden mogen zichzelf niet afmelden als u dit veld leeg laat';\n\t\t\t$fields['keuzelijst']->title =\n\t\t\t\t'Zet | tussen de opties en gebruik && voor meerdere keuzelijsten';\n\t\t}\n\t\tif ($groep instanceof Kring) {\n\t\t\tunset($fields['samenvatting']);\n\t\t}\n\n\t\t// GROEPEN_V2\n\t\tif (!LoginService::mag(P_ADMIN)) {\n\t\t\t$fields['versie']->hidden = true;\n\t\t\t$fields['keuzelijst2']->hidden = true;\n\t\t} else {\n\t\t\t$fields['versie']->title =\n\t\t\t\t'Versie 2 is een testversie, niet gebruiken als je niet weet wat je doet.';\n\t\t\t$fields['keuzelijst2']->title =\n\t\t\t\t'Formaat: naam:type:default:description:optie,optie,optie|naam:type:default:description:|...';\n\t\t}\n\n\t\t$fields['maker']->readonly = !LoginService::mag(P_ADMIN);\n\t\t$this->addFields($fields);\n\n\t\t$this->formKnoppen = new FormDefaultKnoppen($nocancel ? false : null);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "function hist_exam_plan_report($pid, $encounter, $cols, $id)\n{\n $cols = 1; // force always 1 column\n $count = 0;\n $data = sqlQuery(\"SELECT *\n FROM form_hist_exam_plan WHERE\n id = ? AND activity = '1'\", array($id));\n if ($data) {\n print \"<table cellpadding='0' cellspacing='0'>\\n<tr>\\n\";\n foreach ($data as $key => $value) {\n if (\n $key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" ||\n $key == \"authorized\" || $key == \"activity\" || $key == \"date\" ||\n $value == \"\" || $value == \"0\" || $value == \"0.00\"\n ) {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td valign='top'><span class='bold'>\" . text($key) . \": </span><span class='text'>\" . text($value) . \" &nbsp;</span></td>\\n\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr>\\n<tr>\\n\";\n }\n }\n\n print \"</tr>\\n</table>\\n\";\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function (array $attributes) {\n return [\n 'publish_end_date' => now()->addDay(),\n 'publish_start_date' => now()->subDay(),\n ];\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function getHTTPHeaders(Server $server)\n {\n return [];\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function smarty_core_get_include_path(&$params, &$smarty)\n{\n static $_path_array = null;\n\n if(!isset($_path_array)) {\n $_ini_include_path = ini_get('include_path');\n\n if(strstr($_ini_include_path,';')) {\n // windows pathnames\n $_path_array = explode(';',$_ini_include_path);\n } else {\n $_path_array = explode(':',$_ini_include_path);\n }\n }\n foreach ($_path_array as $_include_path) {\n if (@is_readable($_include_path . DIRECTORY_SEPARATOR . $params['file_path'])) {\n $params['new_file_path'] = $_include_path . DIRECTORY_SEPARATOR . $params['file_path'];\n return true;\n }\n }\n return false;\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function body_composition_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = sqlQuery(\"SELECT * \" .\n \"FROM form_body_composition WHERE \" .\n \"id = ? AND activity = '1'\", array($id));\n if ($data) {\n print \"<table cellpadding='0' cellspacing='0'>\\n<tr>\\n\";\n foreach ($data as $key => $value) {\n if (\n $key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" ||\n $key == \"authorized\" || $key == \"activity\" || $key == \"date\" ||\n $value == \"\" || $value == \"0\" || $value == \"0.00\"\n ) {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td valign='top'><span class='bold'>\" . text($key) . \": </span><span class='text'>\" . text($value) . \" &nbsp;</span></td>\\n\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr>\\n<tr>\\n\";\n }\n }\n\n print \"</tr>\\n</table>\\n\";\n }\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function displayNotFoundError(string $additional_info = '')\n {\n Toolbox::deprecated('Throw a `Symfony\\\\Component\\\\HttpKernel\\\\Exception\\\\NotFoundHttpException` exception instead.');\n\n throw new NotFoundHttpException();\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function addRemoteModels(&$sitemap)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function setOpacity($opacity) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private static function convertEncodingIfNeeded($upload_file_name, $original_filename, $params, $line)\n{\n $csv_encoding = $params['csv_encoding'] ?? null;\n\n if ($csv_encoding != 'UTF-8') {\n $content = file_get_contents($upload_file_name);\n\n if (!$csv_encoding) {\n $csv_encoding = mb_detect_encoding($content); // Automatically detect encoding\n }\n\n // Convert file content to UTF-8\n if ($csv_encoding && $csv_encoding != 'UTF-8') {\n $content = mb_convert_encoding($content, 'UTF-8', $csv_encoding);\n } else {\n $content = mb_convert_encoding($content, 'UTF-8');\n }\n\n if (!$content) {\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Your file can\\'t be converted to UTF-8. '\n . 'Please select the appropriate encoding or save it with UTF-8 encoding.');\n return false;\n }\n\n // Save the converted content to a temporary file\n $encoded_file_name = tempnam(HEURIST_SCRATCH_DIR, $original_filename);\n if (!file_put_contents($encoded_file_name, $content)) {\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Cannot save temporary file (with UTF-8 encoded CSV data) ' . $encoded_file_name);\n return false;\n }\n\n return $encoded_file_name;\n }\n\n return $upload_file_name; // No encoding change needed\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function supportsCode($code)\n {\n // we don't support searching by code\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function ($uuid, HttpRestRequest $request) {\n RestConfig::authorization_check(\"admin\", \"super\");\n $data = (array) (json_decode(file_get_contents(\"php://input\"), true));\n $return = (new FhirOrganizationRestController())->patch($uuid, $data);\n RestConfig::apiLog($return, $data);\n return $return;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "#[Route(path: '/swagger-oauth-redirect', methods: ['GET'], security_level: Route::SECURITY_NONE, tags: ['Session'])]\n #[RouteVersion(introduced: '2.0')]\n public function swaggerOAuthRedirect(Request $request): Response\n {\n $content = file_get_contents(GLPI_ROOT . '/public/lib/swagger-ui-dist/oauth2-redirect.html');\n return new Response(200, ['Content-Type' => 'text/html'], $content);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function beforeWriteContent($uri, INode $node, $data, $modified) {\n\t\tif (!$node instanceof Node) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn $this->checkQuota($node->getPath());\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "#[Route(path: '/User/Me/Picture', methods: ['GET'])]\n #[RouteVersion(introduced: '2.0')]\n #[Doc\\Route(\n description: 'Get the picture for the current user'\n )]\n public function getMyPicture(Request $request): Response\n {\n /** @var \\DBmysql $DB */\n global $DB;\n $it = $DB->request([\n 'SELECT' => ['name', 'picture'],\n 'FROM' => User::getTable(),\n 'WHERE' => [\n 'id' => $this->getMyUserID(),\n ],\n ]);\n $data = $it->current();\n return $this->getUserPictureResponse($data['name'], $data['picture']);\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function (callable $resolve, callable $reject) use ($value) {\n $reject($value);\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function zInterStore($output, $zSetKeys, array $weights = null, $aggregateFunction = 'SUM')\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function note_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_note\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if (\n $key == \"id\" ||\n $key == \"pid\" ||\n $key == \"user\" ||\n $key == \"groupname\" ||\n $key == \"authorized\" ||\n $key == \"activity\" ||\n $key == \"date\" ||\n $value == \"\" ||\n $value == \"0000-00-00 00:00:00\"\n ) {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print(\"<tr>\\n\");\n print(\"<tr>\\n\");\n if ($key == \"Note Type\") {\n print \"<td><span class=bold>\" . xlt($key) . \": </span><span class=text>\" . xlt($value) . \"</span></td>\";\n } elseif ($key == \"Date Of Signature\") {\n print \"<td><span class=bold>\" . xlt($key) . \": </span><span class=text>\" . oeFormatShortDate($value) . \"</span></td>\";\n } else {\n print \"<td><span class=bold>\" . xlt($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n }\n\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function cronInfo($name)\n {\n return ['description' => __('Alerts on reservations')];\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(\n $realmId,\n $aggregationUnitName,\n $startDate,\n $endDate,\n $groupById = null,\n $statisticId = null,\n array $parameters = array(),\n LoggerInterface $logger = null\n ) {\n $realmId = 'Gateways';\n $schema = 'modw_gateways';\n $dataTablePrefix = 'gatewayfact_by_';\n\n parent::__construct(\n $realmId,\n $aggregationUnitName,\n $startDate,\n $endDate,\n $groupById,\n null,\n $parameters\n );\n\n // The same fact table row may correspond to multiple rows in the\n // aggregate table (e.g. a job that runs over two days).\n $this->setDistinct(true);\n\n // Override values set in Query::__construct() to use the fact table rather than the\n // aggregation table prefix from the Realm configuration.\n\n $this->setDataTable($schema, sprintf(\"%s%s\", $dataTablePrefix, $aggregationUnitName));\n $this->_aggregation_unit = \\DataWarehouse\\Query\\TimeAggregationUnit::factory(\n $aggregationUnitName,\n $startDate,\n $endDate,\n sprintf(\"%s.%s\", $schema, $dataTablePrefix)\n );\n\n $dataTable = $this->getDataTable();\n $joblistTable = new Table($dataTable->getSchema(), $dataTable->getName() . \"_joblist\", \"jl\");\n $factTable = new Table(new Schema('modw'), \"job_tasks\", \"jt\");\n\n $resourcefactTable = new Table(new Schema('modw'), 'resourcefact', 'rf');\n $this->addTable($resourcefactTable);\n\n $this->addWhereCondition(new WhereCondition(\n new TableField($dataTable, \"task_resource_id\"),\n '=',\n new TableField($resourcefactTable, \"id\")\n ));\n\n // For Gateways realm the analog (with person_id) is the Gateway table:\n $personTable = new Table(new Schema('modw_gateways'), 'gateway', 'p');\n\n $this->addTable($personTable);\n $this->addWhereCondition(new WhereCondition(\n new TableField($dataTable, \"person_id\"),\n '=',\n new TableField($personTable, \"proxy_person_id\")\n ));\n\n $this->addField(new TableField($resourcefactTable, \"code\", 'resource'));\n $this->addField(new TableField($personTable, \"long_name\", \"name\"));\n\n $this->addField(new TableField($factTable, \"job_id\", \"jobid\"));\n $this->addField(new TableField($factTable, \"local_jobid\", \"local_job_id\"));\n $this->addField(new TableField($factTable, 'start_time_ts'));\n $this->addField(new TableField($factTable, 'end_time_ts'));\n $this->addField(new FormulaField('-1', 'cpu_user'));\n\n // This is used by Integrations and not currently shown on the XDMoD interface\n $this->addField(new TableField($factTable, 'name', 'job_name'));\n\n $this->addTable($joblistTable);\n $this->addTable($factTable);\n\n $this->addWhereCondition(new WhereCondition(\n new TableField($joblistTable, \"agg_id\"),\n \"=\",\n new TableField($dataTable, \"id\")\n ));\n $this->addWhereCondition(new WhereCondition(\n new TableField($joblistTable, \"jobid\"),\n \"=\",\n new TableField($factTable, \"job_id\")\n ));\n\n switch ($statisticId) {\n case \"job_count\":\n $this->addWhereCondition(new WhereCondition(\"jt.end_time_ts\", \"BETWEEN\", \"duration.day_start_ts AND duration.day_end_ts\"));\n break;\n case \"started_job_count\":\n $this->addWhereCondition(new WhereCondition(\"jt.start_time_ts\", \"BETWEEN\", \"duration.day_start_ts AND duration.day_end_ts\"));\n break;\n default:\n // All other metrics show running job count\n break;\n }\n\n $this->prependOrder(\n new \\DataWarehouse\\Query\\Model\\OrderBy(\n new TableField($factTable, 'end_time_ts'),\n 'DESC',\n 'end_time_ts'\n )\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function dap_report($pid, $encounter, $cols, $id)\n{\n $cols = 1; // force always 1 column\n $count = 0;\n $data = formFetch(\"form_dap\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n if ($value == \"on\") {\n $value = \"yes\";\n }\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . xlt($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function buildDisplayView($frow, $currvalue): string\n {\n $s = '';\n if (!empty($currvalue)) {\n $relcodes = explode(';', $currvalue);\n foreach ($relcodes as $codestring) {\n if ($codestring === '') {\n continue;\n }\n $tmp = lookup_code_descriptions($codestring);\n if ($s !== '') {\n $s .= '; ';\n }\n if (!empty($tmp)) {\n $s .= text($tmp);\n } else {\n $s .= text($codestring) . ' (' . xlt('not found') . ')';\n }\n }\n }\n return $s;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function createOperationOutcomeError($text, $type)\n {\n $issue = new FHIROperationOutcomeIssue();\n $issueType = new FHIRIssueType();\n $issueType->setValue(\"processing\");\n $issueSeverity = new FHIRIssueSeverity();\n $issueSeverity->setValue(\"error\");\n $issue->setSeverity($issueSeverity);\n $issue->setCode($issueType);\n $details = new FHIRCodeableConcept();\n $details->setText($text);\n $issue->setDetails($details);\n $operationOutcome = new FHIROperationOutcome();\n $operationOutcome->setId(Uuid::uuid4()); // not sure we care about storing these\n $operationOutcome->addIssue($issue);\n return $operationOutcome;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function redirect($url, $time=3) {\n //On v\u00e9rifie si aucun en-t\u00eate n'a d\u00e9j\u00e0 \u00e9t\u00e9 envoy\u00e9\n /*if (!headers_sent()) {\n header(\"refresh: $time;url=$url\");\n exit;\n }\n else {\n //echo '<meta https-equiv=\"refresh\" content=\"'.$time.';url='.$url.'\">';\n }*/\n echo '<SCRIPT LANGUAGE=\"JavaScript\">document.location.href=\"'.$url.'\";\n</SCRIPT>\n';\n}", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)\n {\n return '';\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($query) use ($dbversion) {\n return new \\ArrayIterator(\n [\n [\n 'context' => 'core',\n 'name' => 'dbversion',\n 'value' => $dbversion,\n ]\n ]\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function postPackageInstall(Event $event)\n {\n //self::convertVendorsToPhar($event);\n //var_dump($event);\n //$event->getComposer()->getInstallationManager()\n }", "smellKey": "S1172", "smellId": null, "repo": "Dhmhtrhs54_hackazon", "language": "php"} {"function": "public function view(User $user, AccountBalance $accountBalance): bool\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function oe_module_faxsms_patient_report_render_action_buttons(Event $event): void\n{\n ?>\n<button type=\"button\" class=\"genfax btn btn-success btn-sm btn-send-msg\" value=\"<?php echo xla('Send Fax'); ?>\"><?php echo xlt('Send Fax'); ?></button><span id=\"waitplace\"></span>\n<input type='hidden' name='fax' value='0'>\n<?php }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function function1(int $value): int\n{\n}", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function sdoh_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_sdoh\", $id);\n if (!empty($data)) {\n print \"<table><tr>\";\n\n $sdohData = [];\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n $sdohData[$key] = $value;\n }\n\n // note that including the bold inline styling so it works when create pdf (when storing as pdf document from portal)\n if (empty($sdohData['totalscore'])) {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"No Social Screening Risks\") . \"</span></td></tr>\";\n } else {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Social Screening Risks\") . \":\" . \"</span></td></tr>\";\n\n if (($sdohData['education'] ?? '') == 'lessthanhs') {\n echo \"<tr><td><span class=text>\" . xlt(\"Less than High School Education\") . \"</span></td></tr>\";\n }\n if (($sdohData['education'] ?? '') == 'highschool') {\n echo \"<tr><td><span class=text>\" . xlt(\"High School Diploma or GED\") . \"</span></td></tr>\";\n }\n if (($sdohData['education'] ?? '') == 'associate') {\n echo \"<tr><td><span class=text>\" . xlt(\"Some College\") . \"</span></td></tr>\";\n }\n if (($sdohData['disability'] ?? '') == 'disabilityyes') {\n echo \"<tr><td><span class=text>\" . xlt(\"Disability Self or Family\") . \"</span></td></tr>\";\n }\n if (($sdohData['housing'] ?? '') == 'housetemporary') {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability: Temporary(Shelter, Friends, Family)\") . \"</span></td></tr>\";\n }\n if (($sdohData['housing'] ?? '') == 'houseunsafe') {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability: Unsafe (Mold, Exposure)\") . \"</span></td></tr>\";\n }\n if (($sdohData['housing'] ?? '') == 'housecar') {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability: Car, van, mobile home\") . \"</span></td></tr>\";\n }\n if (($sdohData['housing'] ?? '') == 'houseunshelter') {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability: Unsheltered\") . \"</span></td></tr>\";\n }\n if (($sdohData['housing'] ?? '') == 'houseother') {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability\") . \": \" . text($sdohData['housingotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['worktemporary'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Employment Insecurity: Temporary\") . \"</span></td></tr>\";\n }\n if (($sdohData['workseasonal'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Employment Insecurity: Seasonal or Migrant\") . \"</span></td></tr>\";\n }\n if (($sdohData['worklooking'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Employment Insecurity: Looking for Work\") . \"</span></td></tr>\";\n }\n if (($sdohData['workretired'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Employment Insecurity: Retired\") . \"</span></td></tr>\";\n }\n if (($sdohData['workdisabled'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Employment Insecurity: Disabled\") . \"</span></td></tr>\";\n }\n if (($sdohData['workhours'] ?? 0) > 40) {\n echo \"<tr><td><span class=text>\" . xlt(\"Over 40 Work Hours\") . \": \" . text($sdohData['workhours']) . \"</span></td></tr>\";\n }\n if (!empty($sdohData['hhsize'])) {\n // this will prevent a division by zero php error if the hhsize is set to zero\n if ((($sdohData['hhincome'] ?? 0) / $sdohData['hhsize']) < 25000) {\n echo \"<tr><td><span class=text>\" . xlt(\"Potential Low Income. Household Size\") . \": \" . text($sdohData['hhsize']) . \" \" . xlt(\"Household Income\") . \": \" . text($sdohData['hhincome'] ?? 0) . \"</span></td></tr>\";\n }\n }\n if (($sdohData['careunder5'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Children Under 5\") . \"</span></td></tr>\";\n }\n if (($sdohData['care5to12'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Children 5 to 12\") . \"</span></td></tr>\";\n }\n if (($sdohData['careover12'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Children over 12\") . \"</span></td></tr>\";\n }\n if (($sdohData['carespecneeds'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Special Needs Child\") . \"</span></td></tr>\";\n }\n if (($sdohData['caredisabled'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Disabled or Ill Adult\") . \"</span></td></tr>\";\n }\n if (($sdohData['careelderly'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Elderly\") . \"</span></td></tr>\";\n }\n if (($sdohData['careother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver for Other\") . \": \" . text($sdohData['careotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['debtmedical'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Medical Bills\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtcreditcards'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Credit Cards\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtrent'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Rent or Mortgage\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtstudentloans'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Student Loans\") . \"</span></td></tr>\";\n }\n if (($sdohData['debttaxes'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Taxes\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtlegal'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Legal Issues\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtcar'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Car Loan or Tickets\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtutilities'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Utilities or Phone\") . \"</span></td></tr>\";\n }\n if (($sdohData['debtother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Debt for Other\") . \": \" . text($sdohData['debtotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['moneyfood'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Healthy Food\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneymedical'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Medicine or Medical Care\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneychildcare'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Childcare\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyutilities'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Utilities\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyphone'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Phone or Internet\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyrent'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Rent or Mortgage\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneytransportation'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Transportation\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyclothing'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Clothing\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyeducation'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Education\") . \"</span></td></tr>\";\n }\n if (($sdohData['moneyother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Struggle to pay for Other\") . \": \" . text($sdohData['moneyotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['transportmedical'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for Medical Care\") . \"</span></td></tr>\";\n }\n if (($sdohData['transportfood'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for Healthy Food\") . \"</span></td></tr>\";\n }\n if (($sdohData['transportwork'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for Work or Meetings\") . \"</span></td></tr>\";\n }\n if (($sdohData['transportschool'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for School or Childcare\") . \"</span></td></tr>\";\n }\n if (($sdohData['transportfamily'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for Visiting Family or Friends\") . \"</span></td></tr>\";\n }\n if (($sdohData['transportother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity for Other\") . \": \" . text($sdohData['transportotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['medicalnoinsurance'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to No Insurance\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalcopay'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to High Copay or Deductible\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalnotcovered'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to Specified Care Not Covered\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalwork'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to Inflexible Work Schedule\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalnoprovider'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to No Provider Available\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalunderstand'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to Not Understanding Care Plan\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicaltrust'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to Lack of Trust in Provider\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalchildcare'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to No Childcare\") . \"</span></td></tr>\";\n }\n if (($sdohData['medicalother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Delayed Medical Care due to Other\") . \": \" . text($sdohData['medicalotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['dentist'] ?? '') == 'dentistnoinsurance') {\n echo \"<tr><td><span class=text>\" . xlt(\"No Dental Insurance\") . \"</span></td></tr>\";\n }\n if (($sdohData['dentist'] ?? '') == 'dentistnoprovider') {\n echo \"<tr><td><span class=text>\" . xlt(\"No Dentist\") . \"</span></td></tr>\";\n }\n if (($sdohData['dentist'] ?? '') == 'dentistnowork') {\n echo \"<tr><td><span class=text>\" . xlt(\"No Dental Care due to Work Schedule\") . \"</span></td></tr>\";\n }\n if (($sdohData['dentist'] ?? '') == 'dentistnoother') {\n echo \"<tr><td><span class=text>\" . xlt(\"No Dental Care due to Other\") . \": \" . text($sdohData['dentistotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['social'] ?? '') == 'sociallessthan1') {\n echo \"<tr><td><span class=text>\" . xlt(\"Social Connection Less than Once a Week\") . \"</span></td></tr>\";\n }\n if (($sdohData['social'] ?? '') == 'social1') {\n echo \"<tr><td><span class=text>\" . xlt(\"Social Connection Only Once a Week\") . \"</span></td></tr>\";\n }\n if (($sdohData['social'] ?? '') == 'social2to3') {\n echo \"<tr><td><span class=text>\" . xlt(\"Social Connection Only 2 to 3 Times a Week\") . \"</span></td></tr>\";\n }\n if (($sdohData['stress'] ?? '') == 'stresslevelsomewhat') {\n echo \"<tr><td><span class=text>\" . xlt(\"Somewhat Stressed\") . \"</span></td></tr>\";\n }\n if (($sdohData['stress'] ?? '') == 'stresslevelalot') {\n echo \"<tr><td><span class=text>\" . xlt(\"Quite a Bit Stressed\") . \"</span></td></tr>\";\n }\n if (($sdohData['stress'] ?? '') == 'stresslevelverymuch') {\n echo \"<tr><td><span class=text>\" . xlt(\"Very Much Stressed\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressdeath'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Death of a Loved One\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressdivorce'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Divorce or Separation\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressjob'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Loss of Job\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressmoved'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Moved\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressillness'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Major Illness or Accident\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressvictim'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Victim of Crime\") . \"</span></td></tr>\";\n }\n if (($sdohData['stresswitness'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Witness of Crime or Accident\") . \"</span></td></tr>\";\n }\n if (($sdohData['stresslegal'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Legal Issues\") . \"</span></td></tr>\";\n }\n if (($sdohData['stresshomeless'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Loss of Housing\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressincarcerated'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Incarcerated\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressbankruptcy'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Bankruptcy\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressmarriage'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Marriage\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressbirth'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Birth of Child\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressadultchild'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: Child Moving Out\") . \"</span></td></tr>\";\n }\n if (($sdohData['stressother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Stress Event: (Other)\") . \" \" . text($sdohData['stressotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['safety'] ?? '') == 'safeday') {\n echo \"<tr><td><span class=text>\" . xlt(\"Unsafe Neighborhood at Night\") . \"</span></td></tr>\";\n }\n if (($sdohData['safety'] ?? '') == 'safeno') {\n echo \"<tr><td><span class=text>\" . xlt(\"Unsafe Neighborhood\") . \"</span></td></tr>\";\n }\n if (($sdohData['partnersafety'] ?? '') == 'partnerunsafe') {\n echo \"<tr><td><span class=text>\" . xlt(\"Intimate Partner Violence for Self or Family\") . \"</span></td></tr>\";\n }\n if (($sdohData['female'] ?? '') == 'femaleyes') {\n echo \"<tr><td><span class=text>\" . xlt(\"Female Headed Household\") . \"</span></td></tr>\";\n }\n if (($sdohData['addiction'] ?? '') == 'addictionyes') {\n echo \"<tr><td><span class=text>\" . xlt(\"Addiction with Self or Family\") . \"</span></td></tr>\";\n }\n if (($sdohData['armedservices'] ?? '') == 'armedservicesyes') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discharged from Armed Services\") . \"</span></td></tr>\";\n }\n if (($sdohData['refugee'] ?? '') == 'refugeeyes') {\n echo \"<tr><td><span class=text>\" . xlt(\"Refugee\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimrace'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Race and/or Ethnicity\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimgender'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Gender\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimsexpref'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Sexual Preference\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimgenexp'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Gender Expression\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimreligion'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Religion\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimdisability'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Disability\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimage'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Age\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimweight'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Weight\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimses'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Socioeconomic Status\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimedu'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Education Level\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimmarital'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Marital Status\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimcitizen'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Citenzenship Status\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimaccent'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Accent or Language\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimcriminalhist'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Criminal History\") . \"</span></td></tr>\";\n }\n if (($sdohData['discrimother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination for Other\") . \": \" . text($sdohData['discrimotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['displacework'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated at Work\") . \"</span></td></tr>\";\n }\n if (($sdohData['displacehousing'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Housing \") . \"</span></td></tr>\";\n }\n if (($sdohData['displacehealth'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Health Care\") . \"</span></td></tr>\";\n }\n if (($sdohData['displacelaw'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Law Enforcement\") . \"</span></td></tr>\";\n }\n if (($sdohData['displaceedu'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Education \") . \"</span></td></tr>\";\n }\n if (($sdohData['displacepublic'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Public(Shopping, Dining, Walking)\") . \"</span></td></tr>\";\n }\n if (($sdohData['displaceclubs'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Religious or Civic Clubs or Organizations\") . \"</span></td></tr>\";\n }\n if (($sdohData['displacegovt'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Government\") . \"</span></td></tr>\";\n }\n if (($sdohData['displacefinance'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Banking or Finance Services\") . \"</span></td></tr>\";\n }\n if (($sdohData['displaceother'] ?? '') == 'on') {\n echo \"<tr><td><span class=text>\" . xlt(\"Discriminated in Other\") . \": \" . text($sdohData['displaceotherinput'] ?? '') . \"</span></td></tr>\";\n }\n if (($sdohData['contact'] ?? '') == 'contactphone') {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Contact by Phone with Resources\") . \"</span></td></tr>\";\n }\n if (($sdohData['contact'] ?? '') == 'contactemail') {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Contact by Email with Resources\") . \"</span></td></tr>\";\n }\n if (($sdohData['contact'] ?? '') == 'contactportal') {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Contact through Patient Portal with Resources\") . \"</span></td></tr>\";\n }\n if (($sdohData['contact'] ?? '') == 'contactno') {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Do Not Contact With Resources\") . \"</span></td></tr>\";\n }\n if (($sdohData['contact'] ?? '') == 'contactother') {\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Contact with Resources via Other\") . \": \" . text($sdohData['contactotherinput'] ?? '') . \"</span></td></tr>\";\n }\n\n echo \"<tr><td><span class=text>\" . xlt(\"Patient Score\") . \" = \" . text($sdohData['totalscore'] ?? '') . \"</span></td></tr>\";\n\n echo \"<tr><td><span class=bold style='font-weight: bold;'>\" . xlt(\"Possible Diagnoses\") . \":\" . \"</span></td></tr>\";\n\n if (\n ($sdohData['debtmedical'] ?? '') == 'on'\n || ($sdohData['debtcreditcards'] ?? '') == 'on'\n || ($sdohData['debtrent'] ?? '') == 'on'\n || ($sdohData['debtstudentloans'] ?? '') == 'on'\n || ($sdohData['debttaxes'] ?? '') == 'on'\n || ($sdohData['debtlegal'] ?? '') == 'on'\n || ($sdohData['debtcar'] ?? '') == 'on'\n || ($sdohData['debtutilities'] ?? '') == 'on'\n || ($sdohData['debtother'] ?? '') == 'on'\n || ($sdohData['moneyfood'] ?? '') == 'on'\n || ($sdohData['moneymedical'] ?? '') == 'on'\n || ($sdohData['moneychildcare'] ?? '') == 'on'\n || ($sdohData['moneyutilities'] ?? '') == 'on'\n || ($sdohData['moneyphone'] ?? '') == 'on'\n || ($sdohData['moneyrent'] ?? '') == 'on'\n || ($sdohData['moneytransportation'] ?? '') == 'on'\n || ($sdohData['moneyclothing'] ?? '') == 'on'\n || ($sdohData['moneyeducation'] ?? '') == 'on'\n || ($sdohData['moneyother'] ?? '') == 'on'\n || ($sdohData['stressbankruptcy'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Financial Insecurity\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['moneyfood'] ?? '') == 'on'\n || ($sdohData['moneymedical'] ?? '') == 'on'\n || ($sdohData['moneychildcare'] ?? '') == 'on'\n || ($sdohData['moneyutilities'] ?? '') == 'on'\n || ($sdohData['moneyphone'] ?? '') == 'on'\n || ($sdohData['moneyrent'] ?? '') == 'on'\n || ($sdohData['moneytransportation'] ?? '') == 'on'\n || ($sdohData['moneyclothing'] ?? '') == 'on'\n || ($sdohData['moneyeducation'] ?? '') == 'on'\n || ($sdohData['moneyother'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Material Hardship\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['moneyfood'] ?? '') == 'on'\n || ($sdohData['transportfood'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Food Insecurity\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['housing'] ?? '') == 'housetemporary'\n || ($sdohData['housing'] ?? '') == 'houseunsafe'\n || ($sdohData['housing'] ?? '') == 'housecar'\n || ($sdohData['housing'] ?? '') == 'houseunshelter'\n || ($sdohData['housing'] ?? '') == 'houseother'\n || ($sdohData['debtrent'] ?? '') == 'on'\n || ($sdohData['moneyrent'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Housing Instability\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['transportmedical'] ?? '') == 'on'\n || ($sdohData['transportfood'] ?? '') == 'on'\n || ($sdohData['transportwork'] ?? '') == 'on'\n || ($sdohData['transportschool'] ?? '') == 'on'\n || ($sdohData['transportfamily'] ?? '') == 'on'\n || ($sdohData['transportother'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Transportation Insecurity\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['moneymedical'] ?? '') == 'on'\n || ($sdohData['medicalnoinsurance'] ?? '') == 'on'\n || ($sdohData['medicalcopay'] ?? '') == 'on'\n || ($sdohData['medicalnotcovered'] ?? '') == 'on'\n || ($sdohData['debtmedical'] ?? '') == 'on'\n || ($sdohData['dentist'] ?? '') == 'dentistnoinsurance'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Medical Cost Burden\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['education'] ?? '') == 'lessthanhs'\n || ($sdohData['education'] ?? '') == 'highschool'\n || ($sdohData['medicalunderstand'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Low Health Literacy\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['careunder5'] ?? '') == 'on'\n || ($sdohData['care5to12'] ?? '') == 'on'\n || ($sdohData['careover12'] ?? '') == 'on'\n || ($sdohData['moneychildcare'] ?? '') == 'on'\n || ($sdohData['transportschool'] ?? '') == 'on'\n || ($sdohData['medicalchildcare'] ?? '') == 'on'\n || ($sdohData['caredisabled'] ?? '') == 'on'\n || ($sdohData['careelderly'] ?? '') == 'on'\n || ($sdohData['careother'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Caregiver Burden\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['social'] ?? '') == 'sociallessthan1'\n || ($sdohData['social'] ?? '') == 'social1'\n || ($sdohData['social'] ?? '') == 'social2to3'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Social Isolation\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['stress'] ?? '') == 'stresslevelsomewhat'\n || ($sdohData['stress'] ?? '') == 'stresslevelalot'\n || ($sdohData['stress'] ?? '') == 'stresslevelverymuch'\n || ($sdohData['stressdeath'] ?? '') == 'on'\n || ($sdohData['stressdivorce'] ?? '') == 'on'\n || ($sdohData['stressjob'] ?? '') == 'on'\n || ($sdohData['stressmoved'] ?? '') == 'on'\n || ($sdohData['stressillness'] ?? '') == 'on'\n || ($sdohData['stressvictim'] ?? '') == 'on'\n || ($sdohData['stresswitness'] ?? '') == 'on'\n || ($sdohData['stresslegal'] ?? '') == 'on'\n || ($sdohData['stresshomeless'] ?? '') == 'on'\n || ($sdohData['stressincarcerated'] ?? '') == 'on'\n || ($sdohData['stressbankruptcy'] ?? '') == 'on'\n || ($sdohData['stressmarriage'] ?? '') == 'on'\n || ($sdohData['stressbirth'] ?? '') == 'on'\n || ($sdohData['stressadultchild'] ?? '') == 'on'\n || ($sdohData['stressother'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Elevated or Toxic Stress\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['partnersafety'] ?? '') == 'partnerunsafe'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Intimate Partner Violence\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['safety'] ?? '') == 'safeday'\n || ($sdohData['safety'] ?? '') == 'safeno'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Unsafe Neighborhood\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['discrimrace'] ?? '') == 'on'\n || ($sdohData['discrimgender'] ?? '') == 'on'\n || ($sdohData['discrimsexpref'] ?? '') == 'on'\n || ($sdohData['discrimgenexp'] ?? '') == 'on'\n || ($sdohData['discrimreligion'] ?? '') == 'on'\n || ($sdohData['discrimdisability'] ?? '') == 'on'\n || ($sdohData['discrimage'] ?? '') == 'on'\n || ($sdohData['discrimweight'] ?? '') == 'on'\n || ($sdohData['discrimses'] ?? '') == 'on'\n || ($sdohData['discrimedu'] ?? '') == 'on'\n || ($sdohData['discrimmarital'] ?? '') == 'on'\n || ($sdohData['discrimcitizen'] ?? '') == 'on'\n || ($sdohData['discrimaccent'] ?? '') == 'on'\n || ($sdohData['discrimcriminalhist'] ?? '') == 'on'\n || ($sdohData['discrimother'] ?? '') == 'on'\n || ($sdohData['displacework'] ?? '') == 'on'\n || ($sdohData['displacehousing'] ?? '') == 'on'\n || ($sdohData['displacehealth'] ?? '') == 'on'\n || ($sdohData['displacelaw'] ?? '') == 'on'\n || ($sdohData['displaceedu'] ?? '') == 'on'\n || ($sdohData['displacepublic'] ?? '') == 'on'\n || ($sdohData['displaceclubs'] ?? '') == 'on'\n || ($sdohData['displacegovt'] ?? '') == 'on'\n || ($sdohData['displacefinance'] ?? '') == 'on'\n || ($sdohData['displaceother'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Discrimination\") . \"</span></td></tr>\";\n }\n\n if (\n ($sdohData['medicalnoinsurance'] ?? '') == 'on'\n || ($sdohData['dentist'] ?? '') == 'dentistnoinsurance'\n || ($sdohData['medicalcopay'] ?? '') == 'on'\n || ($sdohData['medicalnotcovered'] ?? '') == 'on'\n ) {\n echo \"<tr><td><span class=text>\" . xlt(\"Uninsured or Underinsured\") . \"</span></td></tr>\";\n }\n }\n }\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function apc_compile_file($filename, $atomic = true){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getMultiByKey ($server_key, array $keys, $flags = 0) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function setSignatureMode($mode)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function ($o) { return ['eight']; }", "smellKey": "S1172", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "function (string $teamId, string $membershipId, array $roles, Request $request, Response $response, Document $user, Database $dbForProject, Event $events) {\n\n $team = $dbForProject->getDocument('teams', $teamId);\n if ($team->isEmpty()) {\n throw new Exception(Exception::TEAM_NOT_FOUND);\n }\n\n $membership = $dbForProject->getDocument('memberships', $membershipId);\n if ($membership->isEmpty()) {\n throw new Exception(Exception::MEMBERSHIP_NOT_FOUND);\n }\n\n $profile = $dbForProject->getDocument('users', $membership->getAttribute('userId'));\n if ($profile->isEmpty()) {\n throw new Exception(Exception::USER_NOT_FOUND);\n }\n\n $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());\n $isAppUser = Auth::isAppUser(Authorization::getRoles());\n $isOwner = Authorization::isRole('team:' . $team->getId() . '/owner');\n\n if (!$isOwner && !$isPrivilegedUser && !$isAppUser) { // Not owner, not admin, not app (server)\n throw new Exception(Exception::USER_UNAUTHORIZED, 'User is not allowed to modify roles');\n }\n\n /**\n * Update the roles\n */\n $membership->setAttribute('roles', $roles);\n $membership = $dbForProject->updateDocument('memberships', $membership->getId(), $membership);\n\n /**\n * Replace membership on profile\n */\n $dbForProject->deleteCachedDocument('users', $profile->getId());\n\n $events\n ->setParam('teamId', $team->getId())\n ->setParam('membershipId', $membership->getId());\n\n $response->dynamic(\n $membership\n ->setAttribute('teamName', $team->getAttribute('name'))\n ->setAttribute('userName', $profile->getAttribute('name'))\n ->setAttribute('userEmail', $profile->getAttribute('email')),\n Response::MODEL_MEMBERSHIP\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function incrBy($key, $value) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($provider, $file, $x, $y) use ($invalidProvider, $validProvider, $image) {\n\t\t\t\tif ($provider === $validProvider) {\n\t\t\t\t\treturn $image;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function _target($key)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function imagesettile ($image, $tile) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function initialize(InputInterface $input, OutputInterface $output)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function allowRestify(?User $user = null): bool\n {\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function geoRadius($key, $longitude, $latitude, $radius, $radiusUnit, array $options) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ftp_put(FTP\\Connection|resource $ftp, string $remote_filename, string $local_filename, int $mode = FTP_BINARY, int $offset = 0): bool {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function grapheme_extract($haystack, $size, $extract_type = null, $start = 0, &$next = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (ContainerInterface $container, $requestedName) {\n return new EncounterccdadispatchTable($container->get(\\Laminas\\Db\\Adapter\\Adapter::class));\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function addServer ($host, $port, $weight = 0) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function (APIFieldDefinition $fieldDefinition): bool {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function areConfusable($s1, $s2, &$error = null) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function prosthesis_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_prosthesis\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ($app, $lang) {\n\t\t\t\treturn $lang;\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function executeAddRule($input)\n {\n $this->check($_POST[\"affectentity\"], UPDATE);\n\n $collection = RuleCollection::getClassByType($_POST['sub_type']);\n $rule = $collection->getRuleClass();\n $ruleid = $rule->add($_POST);\n\n if ($ruleid) {\n //Add an action associated to the rule\n $ruleAction = new RuleAction();\n\n //Action is : affect computer to this entity\n $ruleAction->addActionByAttributes(\n \"assign\",\n $ruleid,\n \"entities_id\",\n $_POST[\"affectentity\"]\n );\n\n switch ($_POST['sub_type']) {\n case 'RuleRight':\n if ($_POST[\"profiles_id\"]) {\n $ruleAction->addActionByAttributes(\n \"assign\",\n $ruleid,\n \"profiles_id\",\n $_POST[\"profiles_id\"]\n );\n }\n $ruleAction->addActionByAttributes(\n \"assign\",\n $ruleid,\n \"is_recursive\",\n $_POST[\"is_recursive\"]\n );\n }\n }\n\n Event::log(\n $ruleid,\n \"rules\",\n 4,\n \"setup\",\n //TRANS: %s is the user login\n sprintf(__('%s adds the item'), $_SESSION[\"glpiname\"])\n );\n\n Html::back();\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct(\n\t\tManagerRegistry $registry,\n\t\tAccountRepository $accountRepository\n\t) {\n\t\tparent::__construct($registry, OneTimeToken::class);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "function ($attribute, $value): bool {\n if (! is_string($value)) {\n return false;\n }\n\n if (filter_var($value, FILTER_VALIDATE_URL) !== false) {\n return true;\n }\n\n libxml_use_internal_errors(true);\n $xml = simplexml_load_string($value);\n if ($xml !== false) {\n return true;\n }\n\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function exists(string $name): bool\n {\n return (bool) $this->getDataByName($this->model->getName());\n }", "smellKey": "S1172", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getPostData($data)\n {\n if (count($_POST)) {\n return $_POST;\n }\n\n if ($post_data = file_get_contents('php://input')) {\n if ($post_json = json_decode($post_data, true)) {\n return $post_json;\n }\n parse_str($post_data, $post_variables);\n if (count($post_variables)) {\n return $post_variables;\n }\n }\n\n return null;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function fix_file_extension(\n $file_path,\n $name,\n $size,\n $type,\n $error,\n $index,\n $content_range\n ) {\n // Add missing file extension for known image types:\n if (\n strpos($name, '.') === false &&\n preg_match('/^image\\/(gif|jpe?g|png)/', $type, $matches)\n ) {\n $name .= '.' . $matches[1];\n }\n if ($this->options['correct_image_extensions']) {\n $extensions = $this->get_valid_image_extensions($file_path);\n // Adjust incorrect image file extensions:\n if (!empty($extensions)) {\n $parts = explode('.', $name);\n $extIndex = count($parts) - 1;\n $ext = strtolower(@$parts[$extIndex]);\n if (!in_array($ext, $extensions)) {\n $parts[$extIndex] = $extensions[0];\n $name = implode('.', $parts);\n }\n }\n }\n return $name;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function hGet($key, $hashKey) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function post_clone($source, $history)\n {\n $this->updateDurationCache($this->getID());\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function datefmt_set_timezone_id(MessageFormatter $mf, $zone) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($filter, $base) {\n\t\t\t\tif ($base === $this->dn) {\n\t\t\t\t\treturn [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'pwdpolicysubentry' => ['cn=custom,ou=policies,dc=foo,dc=bar'],\n\t\t\t\t\t\t\t'pwdchangedtime' => [(new \\DateTime())->sub(new \\DateInterval('P28D'))->format('Ymdhis').'Z'],\n\t\t\t\t\t\t\t'pwdgraceusetime' => [],\n\t\t\t\t\t\t]\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\tif ($base === 'cn=custom,ou=policies,dc=foo,dc=bar') {\n\t\t\t\t\treturn [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'pwdmaxage' => ['2592000'],\n\t\t\t\t\t\t\t'pwdexpirewarning' => ['2591999'],\n\t\t\t\t\t\t]\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($attribute, $value, $parameters) {\n $values = array_map('trim', array_filter(explode(',', rtrim($this->test_emails, ','))));\n\n if (count($values) < 1) {\n return true;\n }\n\n foreach ($values as $email) {\n $validator = Validator::make([\n 'email' => $email\n ], [\n 'email' => 'required|email',\n ]);\n\n if ($validator->fails()) {\n return false;\n }\n }\n\n return true;\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function($m) {\n return ' [subquery] ';\n }", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function getActualMaximum($field) { }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ($message, $attribute, $rule, $parameters) use ($extra_keys) {\n return str_replace(\n [':extra', ':values'],\n [implode(',', $extra_keys), implode(',', $parameters)],\n $message);\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function getAccumActionConditions($frow, $condition_str, $action)\n {\n // For billing codes handle requirement to display its description.\n $tmp = explode('=', $action, 2);\n if (!empty($tmp[1])) {\n return \"valdesc:\" . js_escape(getCodeDescription($tmp[1])) . \", \";\n }\n return \"\";\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ($uuid, HttpRestRequest $request) {\n RestConfig::authorization_check(\"admin\", \"super\");\n $return = (new FhirValueSetRestController())->getOne($uuid);\n RestConfig::apiLog($return);\n return $return;\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function isdigit ($codepoint) {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function rawSearchOptionsToAdd($itemtype)\n {\n $tab = [];\n\n $name = self::getTypeName(Session::getPluralNumber());\n $tab[] = [\n 'id' => 'remote_management',\n 'name' => $name\n ];\n\n $tab[] = [\n 'id' => '1220',\n 'table' => self::getTable(),\n 'field' => 'remoteid',\n 'name' => __('ID'),\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'datatype' => 'dropdown',\n 'joinparams' => [\n 'jointype' => 'itemtype_item'\n ]\n ];\n\n $tab[] = [\n 'id' => '1221',\n 'table' => self::getTable(),\n 'field' => 'type',\n 'name' => _n('Type', 'Types', 1),\n 'forcegroupby' => true,\n 'width' => 1000,\n 'datatype' => 'dropdown',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'itemtype_item'\n ]\n ];\n\n return $tab;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows)\n {\n $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);\n if (!empty($aRowDimensions)) {\n foreach ($aRowDimensions as $objRowDimension) {\n $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);\n list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference);\n if ($objRowDimension->getRowIndex() != $newReference) {\n $objRowDimension->setRowIndex($newReference);\n }\n }\n $pSheet->refreshRowDimensions();\n\n $copyDimension = $pSheet->getRowDimension($beforeRow - 1);\n for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {\n $newDimension = $pSheet->getRowDimension($i);\n $newDimension->setRowHeight($copyDimension->getRowHeight());\n $newDimension->setVisible($copyDimension->getVisible());\n $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());\n $newDimension->setCollapsed($copyDimension->getCollapsed());\n }\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function createGS($row, $X12info, $segTer, $compEleSep)\n {\n $GS = array();\n $GS[0] = \"GS\"; // Functional Group Header Segment ID\n $GS[1] = \"HS\"; // Functional ID Code [ HS = Eligibility, Coverage or Benefit Inquiry (270) ]\n $GS[2] = $X12info['x12_sender_id']; // Application Sender's ID\n $GS[3] = $X12info['x12_receiver_id']; // Application Receiver's ID\n $GS[4] = date('Ymd'); // Date [CCYYMMDD]\n $GS[5] = date('His'); // Time [HHMM] Group Creation Time\n $GS[6] = BillingClaimBatchControlNumber::getGs06(); // Group Control Number No zeros for 5010\n $GS[7] = \"X\"; // Responsible Agency Code Accredited Standards Committee X12 ]\n $GS[8] = \"005010X279A1\"; // Version Release / Industry[ Identifier Code Query 005010X279A1\n $GS['Created'] = implode('*', $GS); // Data Element Separator\n $GS['Created'] = $GS ['Created'] . $segTer; // change the information in the tag or change the tag\n return trim($GS['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function createHL($row, $nHlCounter, $X12info, $segTer, $compEleSep)\n {\n $HL = array();\n $HL[0] = \"HL\"; // Hierarchical Level Segment ID\n $HL_LEN[0] = 2;\n $HL[1] = $nHlCounter; // Hierarchical ID No.\n if ($nHlCounter == 1) {\n $HL[2] = \"\";\n $HL[3] = 20; // Description: Identifies the payor, maintainer, or source of the information.\n $HL[4] = 1; // 1 Additional Subordinate HL Data Segment in This Hierarchical Structure.\n } elseif ($nHlCounter == 2) {\n $HL[2] = 1; // Hierarchical Parent ID Number\n $HL[3] = 21; // Hierarchical Level Code. '21' Information Receiver\n $HL[4] = 1; // 1 Additional Subordinate HL Data Segment in This Hierarchical Structure.\n } else {\n $HL[2] = 2;\n $HL[3] = 22; // Hierarchical Level Code.'22' Subscriber\n $HL[4] = 0; // 0 no Additional Subordinate in the Hierarchical Structure.\n }\n $HL['Created'] = implode('*', $HL); // Data Element Separator\n $HL['Created'] = $HL ['Created'] . $segTer;\n return trim($HL['Created']);\n }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function displayRightError(string $additional_info = '')\n {\n Toolbox::deprecated('Throw a `Symfony\\\\Component\\\\HttpKernel\\\\Exception\\\\AccessDeniedHttpException` exception instead.');\n\n throw new AccessDeniedHttpException();\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function lTrim($key, $start, $stop)\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function withCount($relations)\n {\n return $this;\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "function ListaDocsPorImparticiones_2021($PRINCIPAL, $id_imparticion, $id_empresa)\n\t{\n\t\treturn ($PRINCIPAL);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function vision_report($pid, $encounter, $cols, $id)\n{\n $count = 0;\n $data = formFetch(\"form_vision\", $id);\n if ($data) {\n print \"<table><tr>\";\n foreach ($data as $key => $value) {\n if ($key == \"id\" || $key == \"pid\" || $key == \"user\" || $key == \"groupname\" || $key == \"authorized\" || $key == \"activity\" || $key == \"date\" || $value == \"\" || $value == \"0000-00-00 00:00:00\") {\n continue;\n }\n\n if ($value == \"on\") {\n $value = \"yes\";\n }\n\n $key = ucwords(str_replace(\"_\", \" \", $key));\n print \"<td><span class=bold>\" . text($key) . \": </span><span class=text>\" . text($value) . \"</span></td>\";\n $count++;\n if ($count == $cols) {\n $count = 0;\n print \"</tr><tr>\\n\";\n }\n }\n }\n\n print \"</tr></table>\";\n}", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function calculateColumnWidths($calculateMergeCells = false)\n {\n // initialize $autoSizes array\n $autoSizes = array();\n foreach ($this->getColumnDimensions() as $colDimension) {\n if ($colDimension->getAutoSize()) {\n $autoSizes[$colDimension->getColumnIndex()] = -1;\n }\n }\n\n // There is only something to do if there are some auto-size columns\n if (!empty($autoSizes)) {\n // build list of cells references that participate in a merge\n $isMergeCell = array();\n foreach ($this->getMergeCells() as $cells) {\n foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {\n $isMergeCell[$cellReference] = true;\n }\n }\n\n // loop through all cells in the worksheet\n foreach ($this->getCellCollection(false) as $cellID) {\n $cell = $this->getCell($cellID, false);\n if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {\n // Determine width if cell does not participate in a merge\n if (!isset($isMergeCell[$this->cellCollection->getCurrentAddress()])) {\n // Calculated value\n // To formatted string\n $cellValue = PHPExcel_Style_NumberFormat::toFormattedString(\n $cell->getCalculatedValue(),\n $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()\n );\n\n $autoSizes[$this->cellCollection->getCurrentColumn()] = max(\n (float) $autoSizes[$this->cellCollection->getCurrentColumn()],\n (float)PHPExcel_Shared_Font::calculateColumnWidth(\n $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),\n $cellValue,\n $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),\n $this->getDefaultStyle()->getFont()\n )\n );\n }\n }\n }\n\n // adjust column widths\n foreach ($autoSizes as $columnIndex => $width) {\n if ($width == -1) {\n $width = $this->getDefaultColumnDimension()->getWidth();\n }\n $this->getColumnDimension($columnIndex)->setWidth($width);\n }\n }\n\n return $this;\n }", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function userMovesFile($user, $entry, $fileSource, $fileDestination) {\n\t\t$fullUrl = substr($this->baseUrl, 0, -4) . $this->getDavFilesPath($user);\n\t\t$headers['Destination'] = $fullUrl . $fileDestination;\n\t\ttry {\n\t\t\t$this->response = $this->makeDavRequest($user, \"MOVE\", $fileSource, $headers);\n\t\t} catch (\\GuzzleHttp\\Exception\\ClientException $e) {\n\t\t\t$this->response = $e->getResponse();\n\t\t}\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ftp_chmod(FTP\\Connection|resource $ftp, int $permissions, string $filename): int|false {}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function createRectypes($commonNames, $rt, $isAddDefaultSetOfFields, $convertTitleMask=true, $icon_filename=null, $newfields=null) {\n global $system, $mysqli, $rtyColumnNames;\n\n $ret = null;\n\n if (!isEmptyArray($commonNames)) {\n\n $colNames = join(\",\",$commonNames);\n\n $parameters = array(\"\");\n $titleMask = null;\n $rty_Name = null;\n $query = \"\";\n $querycols = \"\";\n\n foreach ($commonNames as $colName) {\n $val = array_shift($rt[0]['common']);\n\n if(@$rtyColumnNames[$colName]){\n //keep value of text title mask to create canonical one\n if($convertTitleMask && $colName == \"rty_TitleMask\"){\n $titleMask = $val;\n }elseif($colName == \"rty_Name\"){\n $rty_Name = $val;\n }elseif($colName == \"rty_NonOwnerVisibility\" && $val==''){\n $val = 'viewable';\n }\n\n if($query!=\"\") {\n $query = $query.\",\";\n $querycols = $querycols.\",\";\n }\n $querycols = $querycols.$colName;\n $query = $query.\"?\";\n $parameters = addParam($parameters, $rtyColumnNames[$colName], $val);\n\n }\n }\n\n $query_check = \"SELECT rty_ID FROM defRecTypes where rty_Name='\".$mysqli->real_escape_string($rty_Name).\"'\";\n $rty_ID = mysql__select_value($mysqli, $query_check);\n if($rty_ID>0){\n return \"Record type with specified name already exists in the database, please use the existing record type\\nThis type may be hidden - turn it on through Database > Manage structure\";\n }\n\n\n $query = \"insert into defRecTypes ($querycols) values ($query)\";\n\n $rows = mysql__exec_param_query($mysqli, $query, $parameters, true);\n\n if($rows === \"1062\"){\n $ret = \"Record type with specified name already exists in the database, please use the existing record type\\nThis type may be hidden - turn it on through Database > Manage structure\";\n }elseif($rows==0 || is_string($rows) ) {\n\n $ret = 'SQL error inserting data into table defRecTypes';\n handleError($ret, $query, $rows);\n\n } else {\n $rtyID = $mysqli->insert_id;\n\n $dbID = $system->settings->get('sys_dbRegisteredID');\n if(!($dbID>0)){ $dbID = 0;}\n\n $query= 'UPDATE defRecTypes SET rty_OriginatingDBID='.intval($dbID)\n .', rty_NameInOriginatingDB=rty_Name'\n .', rty_IDInOriginatingDB='.intval($rtyID)\n .' WHERE (NOT rty_OriginatingDBID>0 OR rty_OriginatingDBID IS NULL) AND rty_ID='.intval($rtyID);\n $mysqli->query($query);\n\n $ret = -$rtyID;\n if($isAddDefaultSetOfFields){\n //add default set of detail types\n addDefaultFieldForNewRecordType($rtyID, $newfields);\n }\n\n //create canonical title mask - convert names to ids\n if($titleMask){\n updateTitleMask($rtyID, $titleMask);\n }\n\n }\n }\n if ($ret == null) {\n $ret = \"no data supplied for inserting record type\";\n }\n\n return $ret;\n}", "smellKey": "S1172", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public static function showMassiveActionsSubForm(MassiveAction $ma)\n {\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function ($attribute, $value, $parameters, $validator) {\n $extra_keys = is_array($value) ? array_diff(array_keys($value), $parameters) : [];\n\n $validator->addReplacer('keys_in', function ($message, $attribute, $rule, $parameters) use ($extra_keys) {\n return str_replace(\n [':extra', ':values'],\n [implode(',', $extra_keys), implode(',', $parameters)],\n $message);\n });\n\n return is_array($value) && empty($extra_keys);\n }", "smellKey": "S1172", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "#[Deprecated(replacement: '%class%->zUnionStore(%parametersList%)')]\n public function zUnion($Output, $ZSetKeys, array $Weights = null, $aggregateFunction = 'SUM')\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getJobData(Application $app, XDUser $user, $realm, $jobId, $action, $actionName)\n {\n $dataSet = $this->getJobDataSet($user, $realm, $jobId, $action);\n\n return $app->json(\n array(\n 'data' => $dataSet->export(),\n 'success' => true\n ),\n 200\n );\n }", "smellKey": "S1172", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "function setState($state, $alerts=false) {\n switch (strtolower($state)) {\n case 'open':\n return $this->setStatus('open');\n case 'closed':\n return $this->setStatus('closed');\n case 'answered':\n return $this->setAnsweredState(1);\n case 'unanswered':\n return $this->setAnsweredState(0);\n case 'overdue':\n return $this->markOverdue();\n case 'notdue':\n return $this->clearOverdue();\n case 'unassined':\n return $this->unassign();\n }\n // FIXME: Throw and excception and add test cases\n return false;\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function showVerifyMail(string $token, string $userId, string $key): TemplateResponse {\n\t\tif ($this->userSession->getUser()->getUID() !== $userId) {\n\t\t\t// not a public page, hence getUser() must return an IUser\n\t\t\tthrow new InvalidArgumentException('Logged in account is not mail address owner');\n\t\t}\n\t\t$email = $this->crypto->decrypt($key);\n\n\t\treturn new TemplateResponse(\n\t\t\t'core', 'confirmation', [\n\t\t\t\t'title' => $this->l10n->t('Email confirmation'),\n\t\t\t\t'message' => $this->l10n->t('To enable the email address %s please click the button below.', [$email]),\n\t\t\t\t'action' => $this->l10n->t('Confirm'),\n\t\t\t], TemplateResponse::RENDER_AS_GUEST);\n\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function CdrActivationManager($id = \"\", $prefix = \"\")\n {\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "static function ($key, PromoCode $promoCode) use ($promoCodeCode) {\n return $promoCode->getCode() === $promoCodeCode;\n }", "smellKey": "S1172", "smellId": null, "repo": "shopsys_shopsys", "language": "php"} {"function": "function ($id, $key) use ($model) {\n return $id == $model->id;\n }", "smellKey": "S1172", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function prepareInputDataForProcess($input, $params)\n {\n return $input;\n }", "smellKey": "S1172", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function apcu_inc($key, $step = 1, &$success = null, $ttl = 0){}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (\n\t\t\t\t\t\\Psr\\Http\\Message\\RequestInterface $request,\n\t\t\t\t\t\\Psr\\Http\\Message\\ResponseInterface $response,\n\t\t\t\t\t\\Psr\\Http\\Message\\UriInterface $uri\n\t\t\t\t) {\n\t\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function (string $installationId, Response $response, Document $project, Database $dbForConsole, Delete $deletes) {\n $installation = $dbForConsole->getDocument('installations', $installationId);\n\n if ($installation->isEmpty()) {\n throw new Exception(Exception::INSTALLATION_NOT_FOUND);\n }\n\n if (!$dbForConsole->deleteDocument('installations', $installation->getId())) {\n throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove installation from DB');\n }\n\n $deletes\n ->setType(DELETE_TYPE_DOCUMENT)\n ->setDocument($installation);\n\n $response->noContent();\n }", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output)\n {\n throw new LogicException('You must override the execute() method in the concrete command class.');\n }", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function smartyShowObject($params, &$smarty)\n{\n return Tools::p($params['var']);\n}", "smellKey": "S1172", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function imprimerListeEleves($num,$lesInscriptions,$stageSelectionner,$lesGroupes)\n\t{\n\t\t/* on cr\u00e9\u00e9 le PDF */\n\t\trequire('fpdf/fpdf.php');\n\t\t$pdf = new FPDF();\n\n\t\t$pdf->AddPage();\n\n\t\t/* Fonction Cell :\n\t\tpremier chiffre = largeur\n\t\t2\u00e8me chiffre = hauteur\n\t\ttexte\n\t\tbordure (0 ou 1)\n\t\tretour \u00e0 la ligne (0 pas de retour, 1 retour)\n\t\talignement (L, C ou R)\n\t\tcouleur de fond (true ou false)\n\t\tlien\n\t\t*/\n\n\t\t/* titre */\n\t\t/*\n\t\t$pdf->SetFont('Arial', '', 18);\n\n\t\t$pdf->Image('https://association-ore.fr/extranet/images/logo.png',0,5,50,0,'PNG');\n\t\t$pdf->Cell(0, 10, utf8_decode('Liste des \u00e9l\u00e8ves inscrits \u00e0'),0,1,'C');\n\t\t$pdf->Cell(0, 10, utf8_decode($stageSelectionner['NOM_STAGE']),0,1,'C');\n\t\t$pdf->Ln();\n\t\t*/\n\n\t\t/* liste */\n\t\t$pdf->SetFont('Arial', '', 11);\n\t\t$pdf->SetFillColor(192,192,192);\n\n\t\t// On parcours les inscriptions\n\t\t$i = 0;\n\t\t$groupePrec = '';\n\t\t$classePrec = '';\n\t\tforeach($lesInscriptions as $lInscription) {\n\n\t\t\t$i++;\n\n\t\t\t//Si on passe aux lyc\u00e9ens\n\t\t\tif($lInscription['CLASSE_ELEVE_STAGE'] != $classePrec) {\n\n\t\t\t\tif($classePrec == 53) {\n\t\t\t\t\t// On saute une page\n\t\t\t\t\t//$pdf->AddPage();\n\t\t\t\t}\n\n\t\t\t\t$classePrec = $lInscription['CLASSE_ELEVE_STAGE'];\n\t\t\t}\n\n\t\t\t// Si on change de groupe\n\t\t\tif($lInscription['ID_GROUPE'] != $groupePrec) {\n\n\t\t\t\t// Entete\n\t\t\t\t$pdf->SetFont('Arial', '', 18);\n\n\t\t\t\t// Si aucun groupe\n\t\t\t\tif($lInscription['ID_GROUPE'] == 0) {\n\t\t\t\t\t$pdf->Cell(170, 8, utf8_decode('Aucun groupe'),1,1,'C',true);\n\t\t\t\t\t$groupePrec = 0;\n\t\t\t\t} else {\n\n\t\t\t\t\tforeach($lesGroupes as $leGroupe) {\n\n\t\t\t\t\t\tif($leGroupe['ID_GROUPE'] == $lInscription['ID_GROUPE']) {\n\n\t\t\t\t\t\t\t$pdf->Cell(170, 8, utf8_decode(stripslashes($leGroupe['NOM_GROUPE']) . ' (' . stripslashes($leGroupe['SALLES_GROUPE']).')'),1,1,'C',true);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$pdf->SetFont('Arial', '', 11);\n\n\t\t\t\t$pdf->Cell(10, 5, utf8_decode('N\u00b0'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(80, 5, utf8_decode('NOM'),1,0,'C',true);\n\t\t\t\t$pdf->Cell(80, 5, utf8_decode('Pr\u00e9nom'),1,1,'C',true);\n\t\t\t\t//$pdf->Cell(50, 5, utf8_decode('Groupe'),1,1,'C',true);\n\n\t\t\t\t$groupePrec = $lInscription['ID_GROUPE'];\n\t\t\t}\n\n\t\t\t// Ligne de l'inscription\n\t\t\t$pdf->Cell(10, 5, utf8_decode($i),1,0,'C');\n\t\t\t$pdf->Cell(80, 5, utf8_decode(strtoupper(stripslashes($lInscription['NOM_ELEVE_STAGE']))),1,0,'L');\n\t\t\t$pdf->Cell(80, 5, utf8_decode(ucfirst(strtolower(stripslashes($lInscription['PRENOM_ELEVE_STAGE'])))),1,1,'L');\n\n\t\t\t//$pdf->Cell(50, 5, utf8_decode($nom_groupe),1,1,'L');\n\t\t}\n\t\t$pdf->Output();\n\t}", "smellKey": "S1172", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function render($options=array()) {\n $config = $this->field->getConfiguration();\n $name = $this->field->getFormName();\n $id = substr(md5(spl_object_hash($this)), 10);\n $mimetypes = array_filter($config['__mimetypes'],\n function($t) { return strpos($t, '/') !== false; }\n );\n $maxfilesize = ($config['size'] ?: 1048576) / 1048576;\n $files = array();\n $new = $this->field->getClean(false);\n\n foreach ($this->field->getAttachments() as $att) {\n unset($new[$att->file_id]);\n $files[] = array(\n 'id' => $att->file->getId(),\n 'name' => $att->getFilename(),\n 'type' => $att->file->getType(),\n 'size' => $att->file->getSize(),\n 'download_url' => $att->file->getDownloadUrl(),\n );\n }\n\n // Add in newly added files not yet saved (if redisplaying after an\n // error)\n if ($new) {\n $F = AttachmentFile::objects()\n ->filter(array('id__in' => array_keys($new)))\n ->all();\n\n foreach ($F as $f) {\n $f->tmp_name = $new[$f->getId()];\n $files[] = array(\n 'id' => $f->getId(),\n 'name' => $f->getName(),\n 'type' => $f->getType(),\n 'size' => $f->getSize(),\n 'download_url' => $f->getDownloadUrl(),\n );\n }\n }\n\n //see if the attachment is saved in the session for this specific field\n if ($sessionAttachment = $_SESSION[':form-data'][$this->field->get('name')]) {\n $F = AttachmentFile::objects()\n ->filter(array('id__in' => array_keys($sessionAttachment)))\n ->all();\n\n foreach ($F as $f) {\n $f->tmp_name = $sessionAttachment[$f->getId()];\n $files[] = array(\n 'id' => $f->getId(),\n 'name' => $f->getName(),\n 'type' => $f->getType(),\n 'size' => $f->getSize(),\n 'download_url' => $f->getDownloadUrl(),\n );\n }\n }\n\n // Set default $field_id\n $field_id = $this->field->get('id');\n // Get Form Type\n $type = $this->field->getForm()->type;\n // Determine if for Ticket/Task/Custom\n if ($type && !is_numeric($field_id)) {\n if ($type == 'T')\n $field_id = 'ticket/attach';\n elseif ($type == 'A')\n $field_id = 'task/attach';\n }\n\n ?><div id=\"<?php echo $id;\n ?>\" class=\"filedrop\"><div class=\"files\"></div>\n <div class=\"dropzone\"><i class=\"icon-upload\"></i>\n <?php echo sprintf(\n __('Drop files here or %s choose them %s'),\n '<a href=\"#\" class=\"manual\">', '</a>'); ?>\n <input type=\"file\" multiple=\"multiple\"\n id=\"file-<?php echo $id; ?>\" style=\"display:none;\"\n accept=\"<?php echo implode(',', $config['__mimetypes']); ?>\"/>\n </div></div>\n <script type=\"text/javascript\">\n $(function(){$('#<?php echo $id; ?> .dropzone').filedropbox({\n url: 'ajax.php/form/upload/<?php echo $field_id; ?>',\n link: $('#<?php echo $id; ?>').find('a.manual'),\n paramname: 'upload[]',\n fallback_id: 'file-<?php echo $id; ?>',\n allowedfileextensions: <?php echo JsonDataEncoder::encode(\n $config['__extensions'] ?: array()); ?>,\n allowedfiletypes: <?php echo JsonDataEncoder::encode(\n $mimetypes); ?>,\n maxfiles: <?php echo $config['max'] ?: 20; ?>,\n maxfilesize: <?php echo str_replace(',', '.', $maxfilesize); ?>,\n name: '<?php echo $name; ?>[]',\n files: <?php echo JsonDataEncoder::encode($files); ?>\n });});\n </script>\n<?php\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function __construct($id = \"\", $_prefix = \"\")\n {\n parent::__construct();\n\n if (is_numeric($id)) {\n $this->id = $id;\n } else {\n $id = \"\";\n $this->date = date(\"Y-m-d H:i:s\");\n }\n\n $this->_table = \"form_ros2\";\n $this->activity = 1;\n $this->pid = $GLOBALS['pid'];\n if ($id != \"\") {\n $this->populate();\n //$this->date = $this->get_date();\n }\n }", "smellKey": "S1172", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ($uid, $searchProps, $options) {\n\t\t\t\treturn match ([$uid, $options['limit'] ?? null, $options['offset'] ?? null]) {\n\t\t\t\t\t['', 2, 0] => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'UID' => 'contact1',\n\t\t\t\t\t\t\t'URI' => 'contact1.vcf',\n\t\t\t\t\t\t],\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'UID' => 'contact2',\n\t\t\t\t\t\t\t'URI' => 'contact2.vcf',\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t\t['', 2, 3] => [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'UID' => 'contact3',\n\t\t\t\t\t\t\t'URI' => 'contact3.vcf',\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t\tdefault => [],\n\t\t\t\t};\n\t\t\t}", "smellKey": "S1172", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function oe_module_faxsms_document_render_javascript_fax_dialog(Event $event): void\n{\n ?>\nfunction doFax(e, filePath, mime='') {\n e.preventDefault();\n let btnClose = <?php echo xlj(\"Cancel\"); ?>;\n let title = <?php echo xlj(\"Send To Contact\"); ?>;\n let url = top.webroot_url + '/interface/modules/custom_modules/oe-module-faxsms/contact.php?isDocuments=1&type=fax&file=' +\n encodeURIComponent(filePath) + '&mime=' + encodeURIComponent(mime) + '&docid=' + encodeURIComponent(docid);\n dlgopen(url, 'faxto', 'modal-md', 'full', '', title, {\n buttons: [],\n sizeHeight: 'full',\n resolvePromiseOn: 'close'\n }).then(function () {\n top.restoreSession();\n });\n return false;\n}\n<?php }", "smellKey": "S1172", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getParameterOption($values, $default = false, bool $onlyParams = false)\n {\n $values = (array) $values;\n $tokens = $this->tokens;\n\n while (0 < \\count($tokens)) {\n $token = array_shift($tokens);\n if ($onlyParams && '--' === $token) {\n return $default;\n }\n\n foreach ($values as $value) {\n if ($token === $value) {\n return array_shift($tokens);\n }\n // Options with values:\n // For long options, test for '--option=' at beginning\n // For short options, test for '-o' at beginning\n $leading = str_starts_with($value, '--') ? $value.'=' : $value;\n if ('' !== $leading && str_starts_with($token, $leading)) {\n return substr($token, \\strlen($leading));\n }\n }\n }\n\n return $default;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function showForUser(string $user = \"\", bool $display = true)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n // Show events from $result in table form\n list($logItemtype, $logService) = self::logArray();\n\n // define default sorting\n $usersearch = \"\";\n if (!empty($user)) {\n $usersearch = $user . \" \";\n }\n\n // Query Database\n $iterator = $DB->request([\n 'FROM' => 'glpi_events',\n 'WHERE' => ['message' => ['LIKE', $usersearch . '%']],\n 'ORDER' => 'date DESC',\n 'LIMIT' => (int)$_SESSION['glpilist_limit']\n ]);\n\n // Number of results\n $number = count($iterator);\n\n // No Events in database\n if ($number < 1) {\n $twig_params = [\n 'class' => 'table table-hover table-bordered',\n 'header_rows' => [\n [__('No Event')]\n ],\n 'rows' => []\n ];\n $output = TemplateRenderer::getInstance()->render('components/table.html.twig', $twig_params);\n if ($display) {\n echo $output;\n return;\n } else {\n return $output;\n }\n }\n\n $twig_params = [\n 'class' => 'table table-hover table-striped table-bordered',\n 'header_rows' => [\n [\n [\n 'colspan' => 5,\n 'content' => \"<a href=\\\"\" . $CFG_GLPI[\"root_doc\"] . \"/front/event.php\\\">\" .\n sprintf(__('Last %d events'), $_SESSION['glpilist_limit']) . \"</a>\"\n ]\n ],\n [\n __('Source'),\n __('Id'),\n _n('Date', 'Dates', 1),\n [\n 'content' => __('Service'),\n 'style' => 'width: 10%'\n ],\n [\n 'content' => __('Message'),\n 'style' => 'width: 50%'\n ],\n ]\n ],\n 'rows' => []\n ];\n\n foreach ($iterator as $data) {\n $items_id = $data['items_id'];\n $type = $data['type'];\n $date = $data['date'];\n $service = $data['service'];\n $message = $data['message'];\n\n $itemtype = \"&nbsp;\";\n if (isset($logItemtype[$type])) {\n $itemtype = $logItemtype[$type];\n } else {\n if (!is_a($type, \\CommonDBTM::class, true)) {\n $type = getSingular($type);\n }\n if ($item = getItemForItemtype($type)) {\n $itemtype = $item->getTypeName(1);\n }\n }\n\n // Capture the 'echo' output of the function\n ob_start();\n self::displayItemLogID($type, $items_id);\n $item_log_id = ob_get_clean();\n\n $twig_params['rows'][] = [\n 'class' => 'tab_bg_2',\n 'values' => [\n $itemtype,\n $item_log_id,\n Html::convDateTime($date),\n $logService[$service] ?? '',\n $message\n ]\n ];\n }\n\n $output = TemplateRenderer::getInstance()->render('components/table.html.twig', $twig_params);\n if ($display) {\n echo $output;\n return;\n } else {\n return $output;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['daysOfWeek'])) {\n if (is_array($data['daysOfWeek'])) {\n foreach ($data['daysOfWeek'] as $d) {\n $this->addDaysOfWeek($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"daysOfWeek\" must be array of objects or null, ' . gettype($data['daysOfWeek']) . ' seen.');\n }\n }\n if (isset($data['allDay'])) {\n $this->setAllDay($data['allDay']);\n }\n if (isset($data['availableStartTime'])) {\n $this->setAvailableStartTime($data['availableStartTime']);\n }\n if (isset($data['availableEndTime'])) {\n $this->setAvailableEndTime($data['availableEndTime']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function up(): void\n {\n $teams = config('permission.teams');\n $tableNames = config('permission.table_names');\n $columnNames = config('permission.column_names');\n $pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';\n $pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';\n\n if (empty($tableNames)) {\n throw new \\Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');\n }\n if ($teams && empty($columnNames['team_foreign_key'] ?? null)) {\n throw new \\Exception('Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');\n }\n\n Schema::create($tableNames['permissions'], function (Blueprint $table) {\n //$table->engine('InnoDB');\n $table->bigIncrements('id'); // permission id\n $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)\n $table->string('guard_name'); // For MyISAM use string('guard_name', 25);\n $table->timestamps();\n\n $table->unique(['name', 'guard_name']);\n });\n\n Schema::create($tableNames['roles'], function (Blueprint $table) use ($teams, $columnNames) {\n //$table->engine('InnoDB');\n $table->bigIncrements('id'); // role id\n if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing\n $table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();\n $table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');\n }\n $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)\n $table->string('guard_name'); // For MyISAM use string('guard_name', 25);\n $table->timestamps();\n if ($teams || config('permission.testing')) {\n $table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);\n } else {\n $table->unique(['name', 'guard_name']);\n }\n });\n\n Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {\n $table->unsignedBigInteger($pivotPermission);\n\n $table->string('model_type');\n $table->unsignedBigInteger($columnNames['model_morph_key']);\n $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');\n\n $table->foreign($pivotPermission)\n ->references('id') // permission id\n ->on($tableNames['permissions'])\n ->onDelete('cascade');\n if ($teams) {\n $table->unsignedBigInteger($columnNames['team_foreign_key']);\n $table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');\n\n $table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_permissions_permission_model_type_primary');\n } else {\n $table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_permissions_permission_model_type_primary');\n }\n\n });\n\n Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {\n $table->unsignedBigInteger($pivotRole);\n\n $table->string('model_type');\n $table->unsignedBigInteger($columnNames['model_morph_key']);\n $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');\n\n $table->foreign($pivotRole)\n ->references('id') // role id\n ->on($tableNames['roles'])\n ->onDelete('cascade');\n if ($teams) {\n $table->unsignedBigInteger($columnNames['team_foreign_key']);\n $table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');\n\n $table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_roles_role_model_type_primary');\n } else {\n $table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],\n 'model_has_roles_role_model_type_primary');\n }\n });\n\n Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {\n $table->unsignedBigInteger($pivotPermission);\n $table->unsignedBigInteger($pivotRole);\n\n $table->foreign($pivotPermission)\n ->references('id') // permission id\n ->on($tableNames['permissions'])\n ->onDelete('cascade');\n\n $table->foreign($pivotRole)\n ->references('id') // role id\n ->on($tableNames['roles'])\n ->onDelete('cascade');\n\n $table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');\n });\n\n app('cache')\n ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)\n ->forget(config('permission.cache.key'));\n }", "smellKey": "S3776", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "function user_getRepositoryList($system, $ugr_ID, $writeOnly){\n\n $result = array();\n\n $ugr_ID = intval($ugr_ID);\n\n if($ugr_ID>=0){\n //1. search all workgroups\n $query = 'SELECT ugr_ID, ugr_Name, ugr_Preferences FROM sysUGrps '\n .' WHERE ugr_ID=0 OR ugr_ID='.$ugr_ID\n .' OR ugr_ID in (SELECT ugl_GroupID FROM sysUsrGrpLinks WHERE ugl_UserID='.$ugr_ID.')'\n .' ORDER BY ugr_Type DESC';\n\n\n $mysqli = $system->getMysqli();\n $res = $mysqli->query($query);//ugr_Type\n\n //2. loop and parse preferences\n if($res){\n while ($row = $res->fetch_row()) {\n //get preferences\n $prefs = $row[2];\n if($prefs!=null && $prefs!=''){\n $prefs = json_decode($prefs, true);\n if(!isEmptyArray($prefs) && array_key_exists('externalRepositories',$prefs)){\n $prefs = $prefs['externalRepositories'];\n if(is_array($prefs)){\n foreach($prefs as $service_id=>$service){\n if(!$writeOnly || @$service['params']['writeApiKey'] || @$service['params']['writeUser'])\n {\n //$service['service'].'_'.$usr_ID,\n $usr_ID = intval($row[0]);\n $result[] = array($service_id, $service['label'], $usr_ID, $row[1]);\n //$usr_ID, $row[1], $service['service'], $service['label']);\n }\n }\n }\n }\n }\n }\n $res->close();\n }\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function getMessage()\n {\n $authErrorMsg = $this->authenticate();\n if ($authErrorMsg !== 1) {\n return text(js_escape($authErrorMsg));\n // goes to alert\n }\n\n try {\n $messageStoreDir = $this->baseDir;\n if (!file_exists($messageStoreDir)) {\n mkdir($messageStoreDir, 0777, true);\n }\n\n $messageStoreList = $this->platform->get('/account/~/extension/~/message-store', [\n 'messageType' => \"\",\n 'dateFrom' => '2018-05-01'\n ])->json()->records;\n $timePerMessageStore = 6;\n $responseMsgs = \"\";\n foreach ($messageStoreList as $messageStore) {\n if (property_exists($messageStore, 'attachments')) {\n foreach ($messageStore->attachments as $attachment) {\n $id = $attachment->id;\n $uri = $attachment->uri;\n try {\n $apiResponse = $this->platform->get($uri);\n } catch (ApiException $e) {\n $responseMsgs .= \"<tr><td>Errors: \" . text($e->getMessage()) . $e->apiResponse()->request()->getUri()->__toString() . \"</td></tr>\";\n continue;\n }\n\n $ext = $this->getExtensionFromContentType($apiResponse->response()->getHeader('Content-Type')[0]);\n $type = $this->getTypeFromContentType($apiResponse->response()->getHeader('Content-Type')[0]);\n $start = microtime(true);\n file_put_contents(\"{$messageStoreDir}/{$type}_{$id}.{$ext}\", $apiResponse->raw());\n $responseMsgs .= \"<tr><td>\" . $messageStore->creationTime . \"</td><td>\" . $messageStore->type . \"</td><td>\" . $messageStore->from->name . \"</td><td>\" . $messageStore->to->name . \"</td><td>\" . $messageStore->availability . \"</td><td>\" . $messageStore->messageStatus . \"</td><td>\" . $messageStore->message->id . \"</td></tr>\";\n $end = microtime(true);\n $time = ($end - $start);\n if ($time < $timePerMessageStore) {\n sleep($timePerMessageStore - $time);\n }\n }\n } else {\n echo xlt(\"Does not have messages\") . PHP_EOL;\n }\n }\n } catch (ApiException $e) {\n echo \"<tr><td>Error: \" . text($e->getMessage() . $e->apiResponse()->request()->getUri()->__toString()) . \"</td></tr>\";\n }\n\n exit;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getComments()\n {\n $comment = \"\";\n $toadd = [];\n if ($this->isField('completename')) {\n $toadd[] = [\n 'name' => __s('Complete name'),\n 'value' => htmlescape((string) $this->getField('completename')),\n ];\n }\n\n if ($this->isField('serial')) {\n $toadd[] = [\n 'name' => __s('Serial number'),\n 'value' => htmlescape((string) $this->getField('serial')),\n ];\n }\n\n if ($this->isField('otherserial')) {\n $toadd[] = [\n 'name' => __s('Inventory number'),\n 'value' => htmlescape((string) $this->getField('otherserial')),\n ];\n }\n\n if ($this->isField('states_id') && $this->getType() != 'State') {\n $name = Dropdown::getDropdownName('glpi_states', $this->fields['states_id']);\n if (strlen($name) > 0) {\n $toadd[] = [\n 'name' => __s('Status'),\n 'value' => htmlescape($name),\n ];\n }\n }\n\n if ($this->isField('locations_id') && $this->getType() != 'Location') {\n $name = Dropdown::getDropdownName(\"glpi_locations\", $this->fields['locations_id']);\n if (strlen($name) > 0) {\n $toadd[] = [\n 'name' => htmlescape(Location::getTypeName(1)),\n 'value' => htmlescape($name),\n ];\n }\n }\n\n if ($this->isField('users_id')) {\n $name = getUserName($this->fields['users_id']);\n if (strlen($name) > 0) {\n $toadd[] = [\n 'name' => htmlescape(User::getTypeName(1)),\n 'value' => htmlescape($name),\n ];\n }\n }\n\n if ($this->isField('groups_id') && $this->getType() != 'Group') {\n $groups = $this->fields['groups_id'];\n if (!is_array($groups)) {\n $groups = [$groups];\n }\n foreach ($groups as $group) {\n $name = Dropdown::getDropdownName(\"glpi_groups\", $group);\n if (strlen($name) > 0) {\n $toadd[] = [\n 'name' => htmlescape(Group::getTypeName(1)),\n 'value' => htmlescape($name),\n ];\n }\n }\n }\n\n if ($this->isField('users_id_tech')) {\n $name = getUserName($this->fields['users_id_tech']);\n if (strlen($name) > 0) {\n $toadd[] = [\n 'name' => htmlescape(__('Technician in charge')),\n 'value' => htmlescape($name),\n ];\n }\n }\n\n if ($this->isField('contact')) {\n $toadd[] = [\n 'name' => __s('Alternate username'),\n 'value' => htmlescape((string) $this->getField('contact')),\n ];\n }\n\n if ($this->isField('contact_num')) {\n $toadd[] = [\n 'name' => __s('Alternate username number'),\n 'value' => htmlescape((string) $this->getField('contact_num')),\n ];\n }\n\n if (Infocom::canApplyOn($this)) {\n $infocom = new Infocom();\n if ($infocom->getFromDBforDevice($this->getType(), $this->fields['id'])) {\n $toadd[] = [\n 'name' => __s('Warranty expiration date'),\n 'value' => Infocom::getWarrantyExpir(\n $infocom->fields[\"warranty_date\"],\n $infocom->fields[\"warranty_duration\"],\n 0,\n true\n )\n ];\n }\n }\n\n if ($this instanceof CommonDropdown && $this->isField('comment')) {\n $toadd[] = [\n 'name' => __s('Comments'),\n 'value' => nl2br(htmlescape((string) $this->getField('comment'))),\n ];\n }\n\n if (count($toadd)) {\n foreach ($toadd as $data) {\n // Do not use SPAN here\n $comment .= sprintf(\n __s('%1$s: %2$s') . \"<br>\",\n \"<strong>\" . $data['name'],\n \"</strong>\" . $data['value']\n );\n }\n }\n\n if (!empty($comment)) {\n return Html::showToolTip($comment, ['display' => false]);\n }\n\n return $comment;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getEntitiesRestrictCriteria(\n $table = '',\n $field = '',\n $value = '',\n $is_recursive = false,\n $complete_request = false\n ) {\n\n // !='0' needed because consider as empty\n if (\n !$complete_request\n && ($value != '0')\n && empty($value)\n && isset($_SESSION['glpishowallentities'])\n && $_SESSION['glpishowallentities']\n ) {\n return [];\n }\n\n if (empty($field)) {\n if ($table == 'glpi_entities') {\n $field = \"id\";\n } else {\n $field = \"entities_id\";\n }\n }\n if (!empty($table)) {\n $field = \"$table.$field\";\n }\n\n if (!is_array($value) && strlen($value) == 0) {\n if (isset($_SESSION['glpiactiveentities'])) {\n $value = $_SESSION['glpiactiveentities'];\n } else if (isCommandLine() || Session::isCron()) {\n $value = '0'; // If value is not set, fallback to root entity in cron / command line\n }\n }\n\n $crit = [$field => $value];\n\n if ($is_recursive === 'auto' && !empty($table) && $table != 'glpi_entities') {\n $item = $this->getItemForItemtype($this->getItemTypeForTable($table));\n if ($item !== false) {\n $is_recursive = $item->maybeRecursive();\n }\n }\n\n if ($is_recursive) {\n $ancestors = [];\n if (is_array($value)) {\n $ancestors = $this->getAncestorsOf(\"glpi_entities\", $value);\n $ancestors = array_diff($ancestors, $value);\n } else if (strlen($value) == 0) {\n $ancestors = $_SESSION['glpiparententities'] ?? [];\n } else {\n $ancestors = $this->getAncestorsOf('glpi_entities', $value);\n }\n\n if (count($ancestors)) {\n if ($table == 'glpi_entities') {\n if (!is_array($value)) {\n $value = [$value => $value];\n }\n $crit = ['OR' => [$field => $value + $ancestors]];\n } else {\n $recur = (empty($table) ? 'is_recursive' : \"$table.is_recursive\");\n $crit = [\n 'OR' => [\n $field => $value,\n [$recur => 1, $field => $ancestors]\n ]\n ];\n }\n }\n }\n return $crit;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function isInTimeRange(DateTimeInterface $start, DateTimeInterface $end)\n {\n $dtstart = isset($this->DTSTART) ? $this->DTSTART->getDateTime() : null;\n $duration = isset($this->DURATION) ? VObject\\DateTimeParser::parseDuration($this->DURATION) : null;\n $due = isset($this->DUE) ? $this->DUE->getDateTime() : null;\n $completed = isset($this->COMPLETED) ? $this->COMPLETED->getDateTime() : null;\n $created = isset($this->CREATED) ? $this->CREATED->getDateTime() : null;\n\n if ($dtstart) {\n if ($duration) {\n $effectiveEnd = $dtstart->add($duration);\n\n return $start <= $effectiveEnd && $end > $dtstart;\n } elseif ($due) {\n return\n ($start < $due || $start <= $dtstart) &&\n ($end > $dtstart || $end >= $due);\n } else {\n return $start <= $dtstart && $end > $dtstart;\n }\n }\n if ($due) {\n return $start < $due && $end >= $due;\n }\n if ($completed && $created) {\n return\n ($start <= $created || $start <= $completed) &&\n ($end >= $created || $end >= $completed);\n }\n if ($completed) {\n return $start <= $completed && $end >= $completed;\n }\n if ($created) {\n return $end > $created;\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getGenericDateTimeSearchItems($options)\n {\n\n $params['with_time'] = false;\n $params['with_future'] = false;\n $params['with_days'] = true;\n $params['with_specific_date'] = true;\n\n if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }\n\n $dates = [];\n if ($params['with_time']) {\n $dates['NOW'] = __('Now');\n if ($params['with_days']) {\n $dates['TODAY'] = __('Today');\n }\n } else {\n $dates['NOW'] = __('Today');\n }\n\n if ($params['with_specific_date']) {\n $dates[0] = __('Specify a date');\n }\n\n if ($params['with_time']) {\n for ($i = 1; $i <= 24; $i++) {\n $dates['-' . $i . 'HOUR'] = sprintf(_n('- %d hour', '- %d hours', $i), $i);\n }\n\n for ($i = 1; $i <= 15; $i++) {\n $dates['-' . $i . 'MINUTE'] = sprintf(_n('- %d minute', '- %d minutes', $i), $i);\n }\n }\n\n for ($i = 1; $i <= 7; $i++) {\n $dates['-' . $i . 'DAY'] = sprintf(_n('- %d day', '- %d days', $i), $i);\n }\n\n if ($params['with_days']) {\n $dates['LASTSUNDAY'] = __('last Sunday');\n $dates['LASTMONDAY'] = __('last Monday');\n $dates['LASTTUESDAY'] = __('last Tuesday');\n $dates['LASTWEDNESDAY'] = __('last Wednesday');\n $dates['LASTTHURSDAY'] = __('last Thursday');\n $dates['LASTFRIDAY'] = __('last Friday');\n $dates['LASTSATURDAY'] = __('last Saturday');\n }\n\n for ($i = 1; $i <= 10; $i++) {\n $dates['-' . $i . 'WEEK'] = sprintf(_n('- %d week', '- %d weeks', $i), $i);\n }\n\n if ($params['with_days']) {\n $dates['BEGINMONTH'] = __('Beginning of the month');\n }\n\n for ($i = 1; $i <= 12; $i++) {\n $dates['-' . $i . 'MONTH'] = sprintf(_n('- %d month', '- %d months', $i), $i);\n }\n\n if ($params['with_days']) {\n $dates['BEGINYEAR'] = __('Beginning of the year');\n }\n\n for ($i = 1; $i <= 10; $i++) {\n $dates['-' . $i . 'YEAR'] = sprintf(_n('- %d year', '- %d years', $i), $i);\n }\n\n if ($params['with_future']) {\n if ($params['with_time']) {\n for ($i = 1; $i <= 24; $i++) {\n $dates[$i . 'HOUR'] = sprintf(_n('+ %d hour', '+ %d hours', $i), $i);\n }\n }\n\n for ($i = 1; $i <= 7; $i++) {\n $dates[$i . 'DAY'] = sprintf(_n('+ %d day', '+ %d days', $i), $i);\n }\n\n for ($i = 1; $i <= 10; $i++) {\n $dates[$i . 'WEEK'] = sprintf(_n('+ %d week', '+ %d weeks', $i), $i);\n }\n\n if ($params['with_days']) {\n $dates['ENDMONTH'] = __('End of the month');\n }\n\n for ($i = 1; $i <= 12; $i++) {\n $dates[$i . 'MONTH'] = sprintf(_n('+ %d month', '+ %d months', $i), $i);\n }\n\n if ($params['with_days']) {\n $dates['ENDYEAR'] = __('End of the year');\n }\n\n for ($i = 1; $i <= 10; $i++) {\n $dates[$i . 'YEAR'] = sprintf(_n('+ %d year', '+ %d years', $i), $i);\n }\n }\n return $dates;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function PERCENTILE()\n {\n $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());\n\n // Calculate\n $entry = array_pop($aArgs);\n\n if ((is_numeric($entry)) && (!is_string($entry))) {\n if (($entry < 0) || ($entry > 1)) {\n return PHPExcel_Calculation_Functions::NaN();\n }\n $mArgs = array();\n foreach ($aArgs as $arg) {\n // Is it a numeric value?\n if ((is_numeric($arg)) && (!is_string($arg))) {\n $mArgs[] = $arg;\n }\n }\n $mValueCount = count($mArgs);\n if ($mValueCount > 0) {\n sort($mArgs);\n $count = self::COUNT($mArgs);\n $index = $entry * ($count-1);\n $iBase = floor($index);\n if ($index == $iBase) {\n return $mArgs[$index];\n } else {\n $iNext = $iBase + 1;\n $iProportion = $index - $iBase;\n return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ;\n }\n }\n }\n return PHPExcel_Calculation_Functions::VALUE();\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['population'])) {\n if (is_array($data['population'])) {\n foreach ($data['population'] as $d) {\n $this->addPopulation($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"population\" must be array of objects or null, ' . gettype($data['population']) . ' seen.');\n }\n }\n if (isset($data['measureScore'])) {\n $this->setMeasureScore($data['measureScore']);\n }\n if (isset($data['stratifier'])) {\n if (is_array($data['stratifier'])) {\n foreach ($data['stratifier'] as $d) {\n $this->addStratifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"stratifier\" must be array of objects or null, ' . gettype($data['stratifier']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function createUrl($route_id, $id_lang = null, array $params = array(), $force_routes = false, $anchor = '', $id_shop = null)\n {\n if ($id_lang === null) {\n $id_lang = (int)Context::getContext()->language->id;\n }\n if ($id_shop === null) {\n $id_shop = (int)Context::getContext()->shop->id;\n }\n\n if (!isset($this->routes[$id_shop])) {\n $this->loadRoutes($id_shop);\n }\n\n if (!isset($this->routes[$id_shop][$id_lang][$route_id])) {\n $query = http_build_query($params, '', '&');\n $index_link = $this->use_routes ? '' : 'index.php';\n return ($route_id == 'index') ? $index_link.(($query) ? '?'.$query : '') : ((trim($route_id) == '') ? '' : 'index.php?controller='.$route_id).(($query) ? '&'.$query : '').$anchor;\n }\n $route = $this->routes[$id_shop][$id_lang][$route_id];\n // Check required fields\n $query_params = isset($route['params']) ? $route['params'] : array();\n foreach ($route['keywords'] as $key => $data) {\n if (!$data['required']) {\n continue;\n }\n\n if (!array_key_exists($key, $params)) {\n throw new PrestaShopException('Dispatcher::createUrl() miss required parameter \"'.$key.'\" for route \"'.$route_id.'\"');\n }\n if (isset($this->default_routes[$route_id])) {\n $query_params[$this->default_routes[$route_id]['keywords'][$key]['param']] = $params[$key];\n }\n }\n\n // Build an url which match a route\n if ($this->use_routes || $force_routes) {\n $url = $route['rule'];\n $add_param = array();\n\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key])) {\n if (!isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_param[$key] = $value;\n }\n } else {\n if ($params[$key]) {\n $replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];\n } else {\n $replace = '';\n }\n $url = preg_replace('#\\{([^{}]*:)?'.$key.'(:[^{}]*)?\\}#', $replace, $url);\n }\n }\n $url = preg_replace('#\\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\\}#', '', $url);\n if (count($add_param)) {\n $url .= '?'.http_build_query($add_param, '', '&');\n }\n }\n // Build a classic url index.php?controller=foo&...\n else {\n $add_params = array();\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key]) && !isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_params[$key] = $value;\n }\n }\n\n if (!empty($route['controller'])) {\n $query_params['controller'] = $route['controller'];\n }\n $query = http_build_query(array_merge($add_params, $query_params), '', '&');\n if ($this->multilang_activated) {\n $query .= (!empty($query) ? '&' : '').'id_lang='.(int)$id_lang;\n }\n $url = 'index.php?'.$query;\n }\n\n return $url.$anchor;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function registerHook($module_instance, $hook_name, $shop_list = null)\n {\n $return = true;\n if (is_array($hook_name)) {\n $hook_names = $hook_name;\n } else {\n $hook_names = array($hook_name);\n }\n\n foreach ($hook_names as $hook_name) {\n // Check hook name validation and if module is installed\n if (!Validate::isHookName($hook_name)) {\n throw new PrestaShopException('Invalid hook name');\n }\n if (!isset($module_instance->id) || !is_numeric($module_instance->id)) {\n return false;\n }\n\n // Retrocompatibility\n $hook_name_bak = $hook_name;\n if ($alias = Hook::getRetroHookName($hook_name)) {\n $hook_name = $alias;\n }\n\n Hook::exec('actionModuleRegisterHookBefore', array('object' => $module_instance, 'hook_name' => $hook_name));\n // Get hook id\n $id_hook = Hook::getIdByName($hook_name);\n\n // If hook does not exist, we create it\n if (!$id_hook) {\n $new_hook = new Hook();\n $new_hook->name = pSQL($hook_name);\n $new_hook->title = pSQL($hook_name);\n $new_hook->position = 1;\n $new_hook->add();\n $id_hook = $new_hook->id;\n if (!$id_hook) {\n return false;\n }\n }\n\n // If shop lists is null, we fill it with all shops\n if (is_null($shop_list)) {\n $shop_list = Shop::getCompleteListOfShopsID();\n }\n\n $shop_list_employee = Shop::getShops(true, null, true);\n\n foreach ($shop_list as $shop_id) {\n // Check if already register\n $sql = 'SELECT hm.`id_module`\n FROM `'._DB_PREFIX_.'hook_module` hm, `'._DB_PREFIX_.'hook` h\n WHERE hm.`id_module` = '.(int)$module_instance->id.' AND h.`id_hook` = '.$id_hook.'\n AND h.`id_hook` = hm.`id_hook` AND `id_shop` = '.(int)$shop_id;\n if (Db::getInstance()->getRow($sql)) {\n continue;\n }\n\n // Get module position in hook\n $sql = 'SELECT MAX(`position`) AS position\n FROM `'._DB_PREFIX_.'hook_module`\n WHERE `id_hook` = '.(int)$id_hook.' AND `id_shop` = '.(int)$shop_id;\n if (!$position = Db::getInstance()->getValue($sql)) {\n $position = 0;\n }\n\n // Register module in hook\n $return &= Db::getInstance()->insert('hook_module', array(\n 'id_module' => (int)$module_instance->id,\n 'id_hook' => (int)$id_hook,\n 'id_shop' => (int)$shop_id,\n 'position' => (int)($position + 1),\n ));\n\n if (!in_array($shop_id, $shop_list_employee)) {\n $where = '`id_module` = '.(int)$module_instance->id.' AND `id_shop` = '.(int)$shop_id;\n $return &= Db::getInstance()->delete('module_shop', $where);\n }\n }\n\n Hook::exec('actionModuleRegisterHookAfter', array('object' => $module_instance, 'hook_name' => $hook_name));\n }\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function onKernelRequestRedirect(RequestEvent $event)\n {\n if ($event->getRequestType() == HttpKernelInterface::MAIN_REQUEST) {\n $request = $event->getRequest();\n if ($request->attributes->get('needsRedirect') && $request->attributes->has('semanticPathinfo')) {\n $siteaccess = $request->attributes->get('siteaccess');\n $semanticPathinfo = $request->attributes->get('semanticPathinfo');\n $queryString = $request->getQueryString();\n if (\n $request->attributes->get('prependSiteaccessOnRedirect', true)\n && $siteaccess instanceof SiteAccess\n && $siteaccess->matcher instanceof URILexer\n ) {\n $semanticPathinfo = $siteaccess->matcher->analyseLink($semanticPathinfo);\n }\n\n $headers = [];\n if ($request->attributes->has('locationId')) {\n $headers['X-Location-Id'] = $request->attributes->get('locationId');\n }\n $event->setResponse(\n new RedirectResponse(\n $semanticPathinfo . ($queryString ? \"?$queryString\" : ''),\n Response::HTTP_MOVED_PERMANENTLY,\n $headers\n )\n );\n $event->stopPropagation();\n\n if (isset($this->logger)) {\n $this->logger->info(\n \"URLAlias made request to be redirected to $semanticPathinfo\",\n ['pathinfo' => $request->getPathInfo()]\n );\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "private function prepareInput($input, $add = false)\n {\n\n if ($add) {\n if (isset($input['date_creation']) && empty($input['date_creation'])) {\n $input['date_creation'] = 'NULL';\n }\n\n if (empty($input['ttl'])) {\n $input['ttl'] = self::DEFAULT_TTL;\n }\n }\n\n //search entity\n if ($add && !isset($input['entities_id'])) {\n $input['entities_id'] = $_SESSION['glpiactive_entity'] ?? 0;\n $input['is_recursive'] = $_SESSION['glpiactive_entity_recursive'] ?? 0;\n $domain = new Domain();\n if (isset($input['domains_id']) && $domain->getFromDB($input['domains_id'])) {\n $input['entities_id'] = $domain->fields['entities_id'];\n $input['is_recursive'] = $domain->fields['is_recursive'];\n }\n }\n\n if (!Session::isCron() && (isset($input['domainrecordtypes_id']) || isset($this->fields['domainrecordtypes_id']))) {\n if (!($_SESSION['glpiactiveprofile']['managed_domainrecordtypes'] === [-1])) {\n if (isset($input['domainrecordtypes_id']) && !(in_array($input['domainrecordtypes_id'], $_SESSION['glpiactiveprofile']['managed_domainrecordtypes'], true))) {\n //no right to use selected type\n Session::addMessageAfterRedirect(\n __s('You are not allowed to use this type of records'),\n true,\n ERROR\n );\n return false;\n }\n if ($add === false && !(in_array($this->fields['domainrecordtypes_id'], $_SESSION['glpiactiveprofile']['managed_domainrecordtypes'], true))) {\n //no right to change existing type\n Session::addMessageAfterRedirect(\n __s('You are not allowed to edit this type of records'),\n true,\n ERROR\n );\n return false;\n }\n }\n }\n\n return $input;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function parseOpenEMRRecord($dataRecord = array(), $encode = false)\n {\n $goal = new FHIRGoal();\n\n $fhirMeta = new FHIRMeta();\n $fhirMeta->setVersionId('1');\n if (!empty($dataRecord['creation_date'])) {\n $fhirMeta->setLastUpdated(UtilsService::getLocalDateAsUTC($dataRecord['creation_date']));\n } else {\n $fhirMeta->setLastUpdated(UtilsService::getDateFormattedAsUTC());\n }\n $goal->setMeta($fhirMeta);\n\n $fhirId = new FHIRId();\n $fhirId->setValue($dataRecord['uuid']);\n $goal->setId($fhirId);\n\n if (isset($dataRecord['puuid'])) {\n $goal->setSubject(UtilsService::createRelativeReference(\"Patient\", $dataRecord['puuid']));\n } else {\n $goal->setSubject(UtilsService::createDataMissingExtension());\n }\n\n $lifecycleStatus = new FHIRGoalLifecycleStatus();\n $lifecycleStatus->setValue(\"active\");\n $goal->setLifecycleStatus($lifecycleStatus);\n\n if (!empty($dataRecord['provider_uuid']) && !empty($dataRecord['provider_npi'])) {\n $goal->setExpressedBy(UtilsService::createRelativeReference(\"Practitioner\", $dataRecord['provider_uuid']));\n }\n\n\n // ONC only requires a descriptive text. Future FHIR implementors can grab these details and populate the\n // activity element if they so choose, for now we just return the combined description of the care plan.\n if (!empty($dataRecord['details'])) {\n $text = $this->getGoalTextFromDetails($dataRecord['details']);\n $codeableConcept = new FHIRCodeableConcept();\n $codeableConcept->setText($text['text']);\n $goal->setDescription($codeableConcept);\n\n $codeTypeService = new CodeTypesService();\n foreach ($dataRecord['details'] as $detail) {\n $fhirGoalTarget = new FHIRGoalTarget();\n if (!empty($detail['date'])) {\n $fhirDate = new FHIRDate();\n $parsedDateTime = \\DateTime::createFromFormat(\"Y-m-d H:i:s\", $detail['date'], new \\DateTimeZone(date('P')));\n $fhirDate->setValue($parsedDateTime->format(\"Y-m-d\"));\n $fhirGoalTarget->setDueDate($fhirDate);\n } else {\n $fhirGoalTarget->setDueDate(UtilsService::createDataMissingExtension());\n }\n $detailDescription = trim($detail['description'] ?? \"\");\n if (!empty($detailDescription)) {\n // if description is populated we also have to populate the measure with the correct code\n $fhirGoalTarget->setDetailString($detailDescription);\n\n if (!empty($detail['code'])) {\n $codeText = $codeTypeService->lookup_code_description($detail['code']);\n $codeSystem = $codeTypeService->getSystemForCode($detail['code']);\n\n $targetCodeableConcept = new FHIRCodeableConcept();\n $coding = new FhirCoding();\n $coding->setCode($detail['code']);\n if (empty($codeText)) {\n $coding->setDisplay(UtilsService::createDataMissingExtension());\n } else {\n $coding->setDisplay(xlt($codeText));\n }\n\n $coding->setSystem($codeSystem); // these should always be LOINC but we want this generic\n $targetCodeableConcept->addCoding($coding);\n $fhirGoalTarget->setMeasure($targetCodeableConcept);\n } else {\n $fhirGoalTarget->setMeasure(UtilsService::createDataMissingExtension());\n }\n }\n $goal->addTarget($fhirGoalTarget);\n }\n }\n\n if ($encode) {\n return json_encode($goal);\n } else {\n return $goal;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getBaseComponents($componentName = null)\n {\n $isBaseComponent = function ($component) {\n if (!$component instanceof VObject\\Component) {\n return false;\n }\n if ('VTIMEZONE' === $component->name) {\n return false;\n }\n if (isset($component->{'RECURRENCE-ID'})) {\n return false;\n }\n\n return true;\n };\n\n if ($componentName) {\n // Early exit\n return array_filter(\n $this->select($componentName),\n $isBaseComponent\n );\n }\n\n $components = [];\n foreach ($this->children as $childGroup) {\n foreach ($childGroup as $child) {\n if (!$child instanceof Component) {\n // If one child is not a component, they all are so we skip\n // the entire group.\n continue 2;\n }\n if ($isBaseComponent($child)) {\n $components[] = $child;\n }\n }\n }\n\n return $components;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function fax_prescription($p, $faxNum)\n {\n $err = \"Sent fax\";\n //strip - ,(, ), and ws\n $faxNum = preg_replace(\"/(-*)(\\(*)(\\)*)(\\s*)/\", \"\", $faxNum);\n //validate the number\n\n if (!empty($faxNum) && is_numeric($faxNum)) {\n //get the sendfax command and execute it\n $cmd = $this->pconfig['sendfax'];\n // prepend any prefix to the fax number\n $pref = $this->pconfig['prefix'];\n $faxNum = $pref . $faxNum;\n if (empty($cmd)) {\n $err .= \" Send fax not set in includes/config.php\";\n } else {\n //generate file to fax\n $faxFile = \"Failed\";\n $this->print_prescription($p, $faxFile);\n if (empty($faxFile)) {\n $err .= \" print_prescription returned empty file\";\n }\n\n $fileName = $GLOBALS['OE_SITE_DIR'] . \"/documents/\" . $p->get_id() .\n $p->get_patient_id() . \"_fax_.pdf\";\n //print \"filename is $fileName\";\n touch($fileName); // php bug\n $handle = fopen($fileName, \"w\");\n if (!$handle) {\n $err .= \" Failed to open file $fileName to write fax to\";\n }\n\n if (fwrite($handle, $faxFile) === false) {\n $err .= \" Failed to write data to $fileName\";\n }\n\n fclose($handle);\n $args = \" -n -d $faxNum $fileName\";\n //print \"command is $cmd $args<br />\";\n exec($cmd . $args);\n }\n } else {\n $err = \"bad fax number passed to function\";\n }\n\n if ($err) {\n $this->assign(\"process_result\", $err);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function reducequadraticform($a,$n,$rootnum,$d,$format=\"string\") {\n\tif ($rootnum<0) {\n\t\t$iscomplex = true;\n\t\t$rootnum = abs($rootnum);\n\t} else {\n\t\t$iscomplex = false;\n\t}\n\tif ($n == 0 || $rootnum == 0) {\n\t\t$n = 0;\n\t\t$rootnum = 0;\n\t}\n\t$root = 2;\n\t//reduce to (a+n sqrt(in))/d\n\tlist($rootA,$in) = reduceradical($rootnum,$root,\"parts\");\n\t$n *= $rootA;\n\tif ($in==1 && !$iscomplex) {\n\t\t$a += $n;\n\t\t$n = 0;\n\t} else if ($in == 0) {\n $n = 0;\n }\n\t$gr = gcd($n,$d);\n\t$gw = gcd($a,$d);\n\t$g = gcd($gr,$gw); //gcd of a,n, and d\n\t$a = $a/$g;\n\t$n = $n/$g;\n\t$d = $d/$g;\n\tif ($d<0) {\n\t\t$a = $a*-1;\n\t\t$n = $n*-1;\n\t\t$d = $d*-1;\n\t}\n\n\tif ($format=='parts') {\n\t\treturn array($a, $n, $in*($iscomplex?-1:1), $d);\n\t}\n\t$outstr = '';\n\tif ($format=='disp') {\n\t\t$outstr .= '`';\n\t}\n\tif ($d>1 && (($a != 0 && $n != 0) || ($n !=0 && abs($n) != 1))) {\n\t\t$outstr .= '(';\n\t}\n\tif ($a != 0 || $n == 0) {\n\t\t$outstr .= $a;\n\t\tif ($n>0) {\n\t\t\t$outstr .= '+';\n\t\t} else {\n\t\t//\t$outstr .= '-';\n\t\t}\n\t}\n\tif ((abs($n)!=1 || $in==1) && $n!=0) { // 3root(2) or 1root(1)\n\t\t$outstr .= $n;\n\t} else if ($n==-1) {\n\t\t$outstr .= '-';\n\t}\n\tif ($in>1 && $n!=0) {\n\t\t$outstr .= \"sqrt($in)\";\n\t}\n\tif ($iscomplex) {\n\t\t$outstr .= \"i\";\n\t}\n\tif ($d>1) {\n if (($a != 0 && $n != 0) || ($n != 0 && abs($n) != 1)) {\n $outstr .= ')';\n }\n\t\t$outstr .= \"/$d\";\n\t}\n\tif ($format=='disp') {\n\t\t$outstr .= '`';\n\t}\n\treturn $outstr;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function getValueFromData($name, $index, $discovery_data, $pre_cache, $default = null)\n {\n if (isset($discovery_data[$name])) {\n $name = $discovery_data[$name];\n }\n\n if (isset($discovery_data['oid']) && ! is_array($discovery_data['oid']) && isset($pre_cache[$discovery_data['oid']][$index]) && isset($pre_cache[$discovery_data['oid']][$index][$name])) {\n return $pre_cache[$discovery_data['oid']][$index][$name];\n }\n\n if (isset($pre_cache[$index][$name])) {\n return $pre_cache[$index][$name];\n }\n\n // parse sub_index options name with trailing colon and index\n if (preg_match('/^(.+):(\\d+)(?:-(\\d+))?$/', $name, $matches)) {\n // subindex found\n $name = $matches[1];\n\n //create the sub-index values in order to try to match them with precache\n $sub_indexes = explode('.', $index);\n\n // if subindex is a range, get them all, otherwise just get the first\n $index = isset($matches[3])\n ? implode('.', array_slice($sub_indexes, (int) $matches[2], (int) $matches[3]))\n : $sub_indexes[(int) $matches[2]];\n }\n\n // look for the data in pre_cache\n if (isset($pre_cache[$name]) && ! is_numeric($name)) {\n if (is_array($pre_cache[$name])) {\n if (isset($pre_cache[$name][$index][$name])) {\n return $pre_cache[$name][$index][$name];\n } elseif (isset($pre_cache[$name][$index])) {\n return $pre_cache[$name][$index];\n } elseif (count($pre_cache[$name]) === 1 && ! is_array(current($pre_cache[$name]))) {\n return current($pre_cache[$name]);\n }\n } else {\n return $pre_cache[$name];\n }\n }\n\n // search for name inside walked tables if oid is fully qualified\n if (str_contains($name, '::')) {\n foreach ($pre_cache as $table_name => $table) {\n if (is_array($table) && isset($table[$index][$name])) {\n return $table[$index][$name];\n }\n }\n }\n\n return $default;\n }", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<ExampleScenario xmlns=\"http://hl7.org/fhir\"></ExampleScenario>');\n }\n parent::xmlSerialize(true, $sxe);\n if (isset($this->url)) {\n $this->url->xmlSerialize(true, $sxe->addChild('url'));\n }\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->version)) {\n $this->version->xmlSerialize(true, $sxe->addChild('version'));\n }\n if (isset($this->name)) {\n $this->name->xmlSerialize(true, $sxe->addChild('name'));\n }\n if (isset($this->status)) {\n $this->status->xmlSerialize(true, $sxe->addChild('status'));\n }\n if (isset($this->experimental)) {\n $this->experimental->xmlSerialize(true, $sxe->addChild('experimental'));\n }\n if (isset($this->date)) {\n $this->date->xmlSerialize(true, $sxe->addChild('date'));\n }\n if (isset($this->publisher)) {\n $this->publisher->xmlSerialize(true, $sxe->addChild('publisher'));\n }\n if (0 < count($this->contact)) {\n foreach ($this->contact as $contact) {\n $contact->xmlSerialize(true, $sxe->addChild('contact'));\n }\n }\n if (0 < count($this->useContext)) {\n foreach ($this->useContext as $useContext) {\n $useContext->xmlSerialize(true, $sxe->addChild('useContext'));\n }\n }\n if (0 < count($this->jurisdiction)) {\n foreach ($this->jurisdiction as $jurisdiction) {\n $jurisdiction->xmlSerialize(true, $sxe->addChild('jurisdiction'));\n }\n }\n if (isset($this->copyright)) {\n $this->copyright->xmlSerialize(true, $sxe->addChild('copyright'));\n }\n if (isset($this->purpose)) {\n $this->purpose->xmlSerialize(true, $sxe->addChild('purpose'));\n }\n if (0 < count($this->actor)) {\n foreach ($this->actor as $actor) {\n $actor->xmlSerialize(true, $sxe->addChild('actor'));\n }\n }\n if (0 < count($this->instance)) {\n foreach ($this->instance as $instance) {\n $instance->xmlSerialize(true, $sxe->addChild('instance'));\n }\n }\n if (0 < count($this->process)) {\n foreach ($this->process as $process) {\n $process->xmlSerialize(true, $sxe->addChild('process'));\n }\n }\n if (0 < count($this->workflow)) {\n foreach ($this->workflow as $workflow) {\n $workflow->xmlSerialize(true, $sxe->addChild('workflow'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function printHTML($res, $res2, $data)\n{\n//print html css\n\n //convert end of line characters to html (escape for html output first)\n $patterns = array ('/\\n/');\n $replace = array ('<br />');\n $res['facility_address'] = text($res['facility_address']);\n $res['facility_address'] = preg_replace($patterns, $replace, $res['facility_address']);\n $res2['patient_address'] = text($res2['patient_address']);\n $res2['patient_address'] = preg_replace($patterns, $replace, $res2['patient_address']);\n\n //deal with bug (last array index is empty)\n //array_pop($data);\n\n ?>\n\n <html>\n <head>\n <style>\n body {\n font-family: sans-serif;\n font-weight: normal;\n font-size: 10pt;\n background: white;\n color: black;\n }\n div {\n padding: 0;\n margin: 0;\n }\n div.paddingdiv {\n width: 524pt;\n height: 668pt;\n page-break-after: always;\n }\n div.patientAddress {\n margin: 20pt 0 10pt 0;\n font-size: 10pt;\n }\n div.clinicAddress {\n text-align: center;\n width: 100%;\n font-size: 10pt;\n }\n div.sign {\n margin: 30pt 0 0 20pt;\n }\n div.tabletitle {\n font-size: 12pt;\n text-align: center;\n width: 100%;\n }\n table {\n margin: 0 20pt 0 20pt;\n border-collapse: collapse;\n border: 1pt solid black;\n }\n td {\n font-size: 10pt;\n padding: 2pt 3pt 2pt 3pt;\n border-right: 1pt solid black;\n border-left: 1pt solid black;\n }\n td.odd {\n background-color: #D8D8D8;\n }\n th {\n font-size: 10pt;\n border: 1pt solid black;\n padding: 2pt 3pt 2pt 3pt;\n }\n div.pageNumber {\n margin-top: 15pt;\n font-size: 8pt;\n text-align: center;\n width: 100%;\n }\n </style>\n <title><?php xl('Shot Record', 'e'); ?></title>\n </head>\n <body>\n\n <?php\n //plan 15 lines per page\n $linesPerPage = 15;\n $countTotalPages = (ceil((count($data)) / $linesPerPage));\n for ($i = 0; $i < $countTotalPages; $i++) {\n echo \"<div class='paddingdiv'>\\n\";\n\n //display facility information (Note it is already escaped)\n echo \"<div class='clinicAddress'>\" . $res['facility_address'] . \"</div>\\n\";\n\n //display patient information (Note patient address is already escaped)\n echo \"<div class='patientAddress'>\" . text($res2['patient_name']) . \"<br />\" .\n text(xl('Date of Birth') . \": \" . $res2['patient_DOB']) . \"<br />\" .\n $res2['patient_address'] . \"</div>\\n\";\n\n //display table title\n echo \"<div class='tabletitle'>\" . text($title) . \"</div>\\n\";\n\n echo \"<table cellspacing='0' cellpadding='0'>\\n\";\n\n //display header\n echo \"<tr>\\n\";\n foreach ($data[0] as $key => $value) {\n //convert end of line characters to space\n $patterns = array ('/\\n/');\n $replace = array (' ');\n $key = preg_replace($patterns, $replace, $key);\n echo \"<th>\" . text($key) . \"</th>\\n\";\n }\n\n echo \"</tr>\\n\";\n\n //display shot data\n for ($j = 0; $j < $linesPerPage; $j++) {\n if ($rowData = array_shift($data)) {\n echo \"<tr>\";\n foreach ($rowData as $key => $value) {\n //shading of cells\n if ($j == 0) {\n echo \"<td>\";\n } elseif ($j % 2) {\n echo \"<td class ='odd'>\";\n } else {\n echo \"<td>\";\n }\n\n // output data of cell\n echo ($value == \"\") ? \"&nbsp;\" : text($value);\n echo \"</td>\";\n }\n } else {\n //done displaying shot data, so leave loop\n break;\n }\n }\n\n echo \"</table>\\n\";\n\n //display signature line\n echo \"<div class='sign'>\" . xlt('Signature') .\n \":________________________________\" . \"</div>\\n\";\n\n if ($countTotalPages > 1) {\n //display page number if greater than one page\n echo \"<div class='pageNumber'>\" .\n text(xl('Page') . \" \" . ($i + 1) . \"/\" . $countTotalPages) .\n \"</div>\\n\";\n }\n\n echo \"</div>\\n\";\n }\n\n ?>\n\n <script>\n opener.top.printLogPrint(window);\n </script>\n </body>\n </html>\n <?php\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function getfeedbackbasic($correct,$wrong,$thisq,$partn=null) {\n\tglobal $rawscores,$imasroot,$staticroot;\n\tif (isset($GLOBALS['testsettings']['testtype']) && ($GLOBALS['testsettings']['testtype']=='NoScores' || $GLOBALS['testsettings']['testtype']=='EndScore')) {\n\t\treturn '';\n\t}\n\tif (isset($GLOBALS['assessUIver']) && $GLOBALS['assessUIver'] > 1) {\n\t\t$val = $GLOBALS['assess2-curq-iscorrect'] ?? -1;\n if (is_array($partn) && is_array($val)) {\n $res = 1;\n foreach ($partn as $i) {\n if (!isset($val[$i])) {\n $res = -1;\n break;\n } else if ($val[$i] < $res) {\n $res = $val[$i];\n }\n }\n } else if ($partn !== null && is_array($val)) {\n if (isset($val[$partn])) {\n\t\t\t $res = $val[$partn];\n } else {\n $res = -1;\n }\n\t\t} else {\n\t\t\t$res = $val;\n\t\t}\n\t\tif ($res > 0 && $res < 1) {\n\t\t\t$res = 0;\n\t\t}\n\t} else if (isset($rawscores[$thisq-1])) {\n\t\t$qn = $thisq-1;\n\t\tif (strpos($rawscores[$qn],'~')===false) {\n\t\t\t$res = ($rawscores[$qn]<0)?-1:(($rawscores[$qn]==1)?1:0);\n\t\t} else {\n\t\t\t$sp = explode('~',$rawscores[$qn]);\n\t\t\tif ($partn===null) {\n\t\t\t\t$res = 1;\n\t\t\t\tfor ($j=0;$j<count($sp);$j++) {\n\t\t\t\t\tif ($sp[$j]!=1) {\n\t\t\t\t\t\t$res=0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$res = ($sp[$partn]==1)?1:0;\n\t\t\t}\n\t\t}\n\t} else {\n return '';\n }\n\tif ($res==-1) {\n\t\treturn '';\n\t} else if ($res==1) {\n\t\treturn '<div class=\"feedbackwrap correct\"><img src=\"'.$staticroot.'/img/gchk.gif\" alt=\"Correct\"/> '.$correct.'</div>';\n\t} else if ($res==0) {\n\t\treturn '<div class=\"feedbackwrap incorrect\"><img src=\"'.$staticroot.'/img/redx.gif\" alt=\"Incorrect\"/> '.$wrong.'</div>';\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function force_download($filename = '', $data = '', $set_mime = FALSE)\n\t{\n\t\tif ($filename === '' OR $data === '')\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telseif ($data === NULL)\n\t\t{\n\t\t\tif ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t$filepath = $filename;\n\t\t\t$filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));\n\t\t\t$filename = end($filename);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$filesize = strlen($data);\n\t\t}\n\n\t\t// Set the default MIME type to send\n\t\t$mime = 'application/octet-stream';\n\n\t\t$x = explode('.', $filename);\n\t\t$extension = end($x);\n\n\t\tif ($set_mime === TRUE)\n\t\t{\n\t\t\tif (count($x) === 1 OR $extension === '')\n\t\t\t{\n\t\t\t\t/* If we're going to detect the MIME type,\n\t\t\t\t * we'll need a file extension.\n\t\t\t\t */\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Load the mime types\n\t\t\t$mimes =& get_mimes();\n\n\t\t\t// Only change the default MIME if we can find one\n\t\t\tif (isset($mimes[$extension]))\n\t\t\t{\n\t\t\t\t$mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension];\n\t\t\t}\n\t\t}\n\n\t\t/* It was reported that browsers on Android 2.1 (and possibly older as well)\n\t\t * need to have the filename extension upper-cased in order to be able to\n\t\t * download it.\n\t\t *\n\t\t * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/\n\t\t */\n\t\tif (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\\s(1|2\\.[01])/', $_SERVER['HTTP_USER_AGENT']))\n\t\t{\n\t\t\t$x[count($x) - 1] = strtoupper($extension);\n\t\t\t$filename = implode('.', $x);\n\t\t}\n\n\t\tif ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t// Clean output buffer\n\t\tif (ob_get_level() !== 0 && @ob_end_clean() === FALSE)\n\t\t{\n\t\t\t@ob_clean();\n\t\t}\n\n\t\t// Generate the server headers\n\t\theader('Content-Type: '.$mime);\n\t\theader('Content-Disposition: attachment; filename=\"'.$filename.'\"');\n\t\theader('Expires: 0');\n\t\theader('Content-Transfer-Encoding: binary');\n\t\theader('Content-Length: '.$filesize);\n\t\theader('Cache-Control: private, no-transform, no-store, must-revalidate');\n\n\t\t// If we have raw data - just dump it\n\t\tif ($data !== NULL)\n\t\t{\n\t\t\texit($data);\n\t\t}\n\n\t\t// Flush 1MB chunks of data\n\t\twhile ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE)\n\t\t{\n\t\t\techo $data;\n\t\t}\n\n\t\tfclose($fp);\n\t\texit;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function canRead($pFilename)\n\t{\n\t\t// Check if file exists\n\t\tif (!file_exists($pFilename)) {\n\t\t\tthrow new PHPExcel_Reader_Exception(\"Could not open \" . $pFilename . \" for reading! File does not exist.\");\n\t\t}\n\n\t\t// Check if zip class exists\n\t\tif (!class_exists('ZipArchive',FALSE)) {\n\t\t\tthrow new PHPExcel_Reader_Exception(\"ZipArchive library is not enabled\");\n\t\t}\n\n\t\t$xl = false;\n\t\t// Load file\n\t\t$zip = new ZipArchive;\n\t\tif ($zip->open($pFilename) === true) {\n\t\t\t// check if it is an OOXML archive\n\t\t\t$rels = simplexml_load_string($this->_getFromZipArchive($zip, \"_rels/.rels\"));\n\t\t\tif ($rels !== false) {\n\t\t\t\tforeach ($rels->Relationship as $rel) {\n\t\t\t\t\tswitch ($rel[\"Type\"]) {\n\t\t\t\t\t\tcase \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\":\n\t\t\t\t\t\t\tif (basename($rel[\"Target\"]) == 'workbook.xml') {\n\t\t\t\t\t\t\t\t$xl = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$zip->close();\n\t\t}\n\n\t\treturn $xl;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function showdataarray($a,$n=1,$opts=null) {\n\tif (!is_array($a)) {\n\t\treturn '';\n\t}\n $n = floor($n);\n $a = array_values($a);\n $format = 'table';\n $align = \"default\";\n\t$caption = \"\";\n $tablealign = '';\n if (is_array($opts)) {\n if (isset($opts['format'])) {\n $format = $opts['format'];\n }\n if (isset($opts['align'])) {\n $align = strtolower($opts['align']);\n }\n if (isset($opts['caption'])) {\n $caption = $opts['caption'];\n }\n if (isset($opts['tablealign'])) {\n $tablealign = $opts['tablealign'];\n }\n } else if (is_string($opts)) {\n if ($opts == 'pre') {\n $format = 'pre';\n } else {\n $align = strtolower($opts);\n }\n }\n\n\tif ($format == 'pre') {\n\t\t$maxwidth = 1; $cnt = 0;\n\t\tforeach ($a as $v) {\n\t\t\tif (strlen($v)>$maxwidth) {\n\t\t\t\t$maxwidth = strlen($v);\n\t\t\t}\n\t\t}\n\t\t$out = '<pre>';\n\t\twhile ($cnt<count($a)) {\n\t\t\tfor ($i=0;$i<$n;$i++) {\n\t\t\t\t$out .= sprintf(\"%{$maxwidth}s \",$a[$cnt]);\n\t\t\t\t$cnt++;\n\t\t\t}\n\t\t\t$out .= \"\\n\";\n\t\t}\n\t\t$out .= '</pre>';\n\t} else {\n $cellclass = '';\n if ($align=='c' || $align=='r' || $align=='l') {\n $cellclass = 'class='.$align;\n }\n\t\t$out = '<table class=stats';\n if ($tablealign == 'center') {\n $out .= ' style=\"margin:0 auto;\"';\n }\n $out .= '>';\n if ($caption != '') {\n $out .= '<caption>'.Sanitize::encodeStringForDisplay($caption).'</caption>';\n }\n $out .= '<tbody>';\n\t\t$cnt = 0;\n\t\twhile ($cnt<count($a)) {\n\t\t\t$out .= '<tr>';\n\t\t\tfor ($i=0;$i<$n;$i++) {\n\t\t\t\tif (isset($a[$cnt])) {\n\t\t\t\t\t$out .= '<td '.$cellclass.'>'.$a[$cnt].'</td>';\n\t\t\t\t} else {\n\t\t\t\t\t$out .= '<td></td>';\n\t\t\t\t}\n\t\t\t\t$cnt++;\n\t\t\t}\n\t\t\t$out .= '</tr>';\n\t\t}\n\t\t$out .= '</tbody></table>';\n\t}\n\treturn $out;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function edih_278_csv_data($obj278)\n{\n //\n // f278 file = array('Date', 'FileName', 'Control', 'TrnCount', 'Auth', 'Payer');\n // f278 claim = array('PtName', 'FileDate', 'Trace', 'Status' 'BHT03', 'FileName', 'Auth', 'Payer');\n //\n $ret_ar = array();\n //\n $de = $obj278->edih_delimiters()['e'];\n $ds = $obj278->edih_delimiters()['s'];\n $fn = $obj278->edih_filename();\n $seg_ar = $obj278->edih_segments();\n $env_ar = $obj278->edih_envelopes();\n $ft = csv_file_type($obj278->edih_type());\n //\n // $ft: 'HI'=>'278'\n if (!isset($env_ar['ST'])) {\n csv_edihist_log('edih_278_csv_data: envelope error ' . $fn);\n return false;\n }\n\n //\n if (!isset($env_ar['GS'])) {\n csv_edihist_log('edih_278_csv_data: envelope error ' . $fn);\n return $ret_ar;\n }\n\n //\n foreach ($env_ar['ISA'] as $icn => $isa) {\n // array('Date', 'FileName', 'Control', 'ta1ctrl', 'RejCt');\n $ret_ar[$icn]['type'] = $ft;\n $ret_ar[$icn]['claim'] = array();\n $ret_ar[$icn]['file'] = array();\n $rspdate = $isa['date'];\n //\n foreach ($env_ar['GS'] as $gs) {\n if ($gs['icn'] == $icn) {\n $rspdate = $gs['date'];\n break;\n }\n }\n\n foreach ($env_ar['ST'] as $st) {\n //\n if ($st['icn'] != $icn) {\n continue;\n }\n\n //\n $stsegs = array_slice($seg_ar, $st['start'], $st['count']);\n $loopid = '0';\n $hl = 0;\n //$isasender = $env_ar['ISA'][$st['icn']]['sender'];\n //$isadate = $env_ar['ISA'][$st['icn']]['date'];\n $isaicn = $st['icn'];\n $has_le = false;\n //\n // for \"claim\" array\n //\n foreach ($stsegs as $seg) {\n //\n if (strncmp($seg, 'BHT' . $de, 4) === 0) {\n // new transaction\n // bht01 0007 --> Src, Rcv, Sbr, Dep, Event, Services\n $rqst = '';\n $status = 'A';\n $cdx = count($ret_ar[$icn]['claim']);\n //\n $sar = explode($de, $seg);\n if (isset($sar[2])) {\n if ($sar[2] == '01') {\n $rqst = 'Cancel';\n }\n\n if ($sar[2] == '13') {\n $rqst = 'Req';\n }\n\n if ($sar[2] == '11') {\n $rqst = 'Rsp';\n }\n\n if ($sar[2] == '36') {\n $rqst = 'Reply';\n }\n }\n\n $loopid = 0;\n //\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = '';\n $ret_ar[$icn]['claim'][$cdx]['FileDate'] = $rspdate;\n $ret_ar[$icn]['claim'][$cdx]['Trace'] = '';\n $ret_ar[$icn]['claim'][$cdx]['Status'] = '';\n $ret_ar[$icn]['claim'][$cdx]['BHT03'] = $sar[3]; //bht03 = $sar[3];\n $ret_ar[$icn]['claim'][$cdx]['FileName'] = $fn;\n $ret_ar[$icn]['claim'][$cdx]['Auth'] = $rqst;\n $ret_ar[$icn]['claim'][$cdx]['Payer'] = '';\n //\n continue;\n }\n\n //\n if (strncmp($seg, 'HL' . $de, 3) === 0) {\n $sar = explode($de, $seg);\n $hl = $sar[1];\n $hlpc = $sar[2]; // parent code\n $hllc = $sar[3];\n $hlcc = (isset($sar[4])) ? $sar[4] : ''; // child code\n if ($sar[3] == '20') { // level code\n $loopid = '2000A'; // info source (payer)\n } elseif ($sar[3] == '21') {\n $loopid = '2000B'; // info receiver (clinic)\n } elseif ($sar[3] == '22') {\n $loopid = '2000C'; // subscriber\n } elseif ($sar[3] == '23') {\n $loopid = '2000D'; // dependent\n } elseif ($sar[3] == 'EV') {\n $loopid = '2000E'; // patient event\n } elseif ($sar[3] == 'SS') {\n $loopid = '2000F'; // service\n } else {\n //debug\n csv_edihist_log('HL has no level ' . $seg . ' in ' . $fn);\n }\n\n continue;\n }\n\n //\n if (strncmp($seg, 'NM1' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $nm101 = $sar[1];\n $nm103 = $sar[3];\n $nm103 = ($sar[4]) ? $nm103 . ', ' . $sar[4] : $nm103;\n $nm103 = ($sar[5]) ? $nm103 . ' ' . $sar[5] : $nm103;\n if ($loopid == '2000A') {\n $ret_ar[$icn]['claim'][$cdx]['Payer'] = $nm103; //\n $payer_name = $nm103;\n } elseif ($loopid == '2000C') {\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = $nm103; //$ptname = $nm1;\n $loopid = '2010C';\n } elseif ($loopid == '2000D') {\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = $nm103; //$ptname = $nm1;\n $loopid = '2010D';\n } elseif (strpos('|2000E', $loopid)) {\n $loopid = '2000E';\n $loopid = (strpos('|71|72|73|77|AAJ|DD|DK|DN|FA|G3|P3|QB|QV|SJ', $nm101) ) ? '2010EA' : $loopid;\n $loopid = (strpos('|45|FS|ND|PW|R3', $nm101) ) ? '2010EB' : $loopid;\n $loopid = ($nm101 == 'L5') ? '2010EC' : $loopid;\n } elseif ($loopid == '2000F') {\n $loopid = '2000F';\n $loopid = (strpos('|71|72|73|77|AAJ|DD|DK|DN|FA|G3|P3|QB|QV|SJ', $nm101) ) ? '2010FA' : $loopid;\n }\n\n continue;\n }\n\n // for 278 eligibility response (invalid data in 278 request)\n if (strncmp($seg, 'AAA' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $status = 'R';\n $rej_ct++;\n $aaa_code = $sar[3];\n $rsp_code = $sar[4];\n if ($loopid == '2000A') {\n $status .= ' Src ' . $aaa_code;\n } elseif ($loopid == '2000B') {\n $status .= ' Rcv ' . $aaa_code;\n } elseif ($loopid == '2000C') {\n $status .= ' Sbr ' . $aaa_code;\n } elseif ($loopid == '2000D') {\n $status .= ' Dep ' . $aaa_code;\n } elseif ($loopid == '2000E') {\n $status .= ' Pt ' . $aaa_code;\n } elseif ($loopid == '2000F') {\n $status .= ' Svc ' . $aaa_code;\n } elseif ($loopid == '2010FA') {\n $status .= ' Prv ' . $aaa_code;\n } elseif ($loopid == '2010EA') {\n $status .= ' Svc ' . $aaa_code;\n } elseif ($loopid == '2010EC') {\n $status .= ' Tpt ' . $aaa_code;\n }\n\n //\n $ret_ar[$icn]['claim'][$cdx]['Status'] = $status;\n //\n continue;\n }\n\n //\n // for 278 tracking\n // this assumes OpenEMR will include a TRN segment in requests\n if (strncmp($seg, 'TRN' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n if ($rqst == 'Req') {\n if (isset($sar[1]) && $sar[1] == '1') {\n $ret_ar[$icn]['claim'][$cdx]['Trace'] = (isset($sar[2])) ? $sar[2] : '';\n }\n } else {\n if (isset($sar[1]) && $sar[1] == '2') {\n $ret_ar[$icn]['claim'][$cdx]['Trace'] = (isset($sar[2])) ? $sar[2] : '';\n }\n }\n }\n } // end foreach($stsegs as $seg)\n //\n } // endforeach($env_ar['ST'] as $st\n $fdx = count($ret_ar[$icn]['file']);\n //\n $ret_ar[$icn]['file'][$fdx]['Date'] = $rspdate;\n $ret_ar[$icn]['file'][$fdx]['FileName'] = $fn;\n // could be GS06 for 278 request type\n $ret_ar[$icn]['file'][$fdx]['Control'] = $icn;\n $ret_ar[$icn]['file'][$fdx]['TrnCount'] = $cdx;\n $ret_ar[$icn]['file'][$fdx]['Auth'] = $rqst;\n $ret_ar[$icn]['file'][$fdx]['Payer'] = $payer_name;\n //\n } // endforeach($env_ar['ISA'] as $icn=>$isa)\n //\n return $ret_ar;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['instantiatesCanonical'])) {\n if (is_array($data['instantiatesCanonical'])) {\n foreach ($data['instantiatesCanonical'] as $d) {\n $this->addInstantiatesCanonical($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"instantiatesCanonical\" must be array of objects or null, ' . gettype($data['instantiatesCanonical']) . ' seen.');\n }\n }\n if (isset($data['instantiatesUri'])) {\n if (is_array($data['instantiatesUri'])) {\n foreach ($data['instantiatesUri'] as $d) {\n $this->addInstantiatesUri($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"instantiatesUri\" must be array of objects or null, ' . gettype($data['instantiatesUri']) . ' seen.');\n }\n }\n if (isset($data['basedOn'])) {\n if (is_array($data['basedOn'])) {\n foreach ($data['basedOn'] as $d) {\n $this->addBasedOn($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"basedOn\" must be array of objects or null, ' . gettype($data['basedOn']) . ' seen.');\n }\n }\n if (isset($data['priorRequest'])) {\n if (is_array($data['priorRequest'])) {\n foreach ($data['priorRequest'] as $d) {\n $this->addPriorRequest($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"priorRequest\" must be array of objects or null, ' . gettype($data['priorRequest']) . ' seen.');\n }\n }\n if (isset($data['groupIdentifier'])) {\n $this->setGroupIdentifier($data['groupIdentifier']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['intent'])) {\n $this->setIntent($data['intent']);\n }\n if (isset($data['priority'])) {\n $this->setPriority($data['priority']);\n }\n if (isset($data['codeReference'])) {\n $this->setCodeReference($data['codeReference']);\n }\n if (isset($data['codeCodeableConcept'])) {\n $this->setCodeCodeableConcept($data['codeCodeableConcept']);\n }\n if (isset($data['parameter'])) {\n if (is_array($data['parameter'])) {\n foreach ($data['parameter'] as $d) {\n $this->addParameter($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"parameter\" must be array of objects or null, ' . gettype($data['parameter']) . ' seen.');\n }\n }\n if (isset($data['subject'])) {\n $this->setSubject($data['subject']);\n }\n if (isset($data['encounter'])) {\n $this->setEncounter($data['encounter']);\n }\n if (isset($data['occurrenceDateTime'])) {\n $this->setOccurrenceDateTime($data['occurrenceDateTime']);\n }\n if (isset($data['occurrencePeriod'])) {\n $this->setOccurrencePeriod($data['occurrencePeriod']);\n }\n if (isset($data['occurrenceTiming'])) {\n $this->setOccurrenceTiming($data['occurrenceTiming']);\n }\n if (isset($data['authoredOn'])) {\n $this->setAuthoredOn($data['authoredOn']);\n }\n if (isset($data['requester'])) {\n $this->setRequester($data['requester']);\n }\n if (isset($data['performerType'])) {\n $this->setPerformerType($data['performerType']);\n }\n if (isset($data['performer'])) {\n $this->setPerformer($data['performer']);\n }\n if (isset($data['reasonCode'])) {\n if (is_array($data['reasonCode'])) {\n foreach ($data['reasonCode'] as $d) {\n $this->addReasonCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"reasonCode\" must be array of objects or null, ' . gettype($data['reasonCode']) . ' seen.');\n }\n }\n if (isset($data['reasonReference'])) {\n if (is_array($data['reasonReference'])) {\n foreach ($data['reasonReference'] as $d) {\n $this->addReasonReference($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"reasonReference\" must be array of objects or null, ' . gettype($data['reasonReference']) . ' seen.');\n }\n }\n if (isset($data['insurance'])) {\n if (is_array($data['insurance'])) {\n foreach ($data['insurance'] as $d) {\n $this->addInsurance($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"insurance\" must be array of objects or null, ' . gettype($data['insurance']) . ' seen.');\n }\n }\n if (isset($data['supportingInfo'])) {\n if (is_array($data['supportingInfo'])) {\n foreach ($data['supportingInfo'] as $d) {\n $this->addSupportingInfo($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"supportingInfo\" must be array of objects or null, ' . gettype($data['supportingInfo']) . ' seen.');\n }\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n if (isset($data['relevantHistory'])) {\n if (is_array($data['relevantHistory'])) {\n foreach ($data['relevantHistory'] as $d) {\n $this->addRelevantHistory($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"relevantHistory\" must be array of objects or null, ' . gettype($data['relevantHistory']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getSaveFormAction(): Action\n {\n return parent::getSaveFormAction()\n ->submit(null)\n ->requiresConfirmation()\n ->modalHeading('Sync all chats to this new service?')\n ->modalDescription('If you are moving to a new account, you will need to sync all the data to the new service to minimize disruption. Advising App can do this for you, but if you just want to save the settings and do it yourself, you can choose to do so.')\n ->modalWidth(MaxWidth::TwoExtraLarge)\n ->modalSubmitActionLabel('Save and sync all chats')\n ->modalHidden(function (AiIntegrationsSettings $originalSettings) {\n $newSettings = $this->form->getRawState();\n\n if ($originalSettings->open_ai_gpt_35_base_uri !== $newSettings['open_ai_gpt_35_base_uri']) {\n return false;\n }\n\n if ($originalSettings->open_ai_gpt_4_base_uri !== $newSettings['open_ai_gpt_4_base_uri']) {\n return false;\n }\n\n if ($originalSettings->open_ai_gpt_4o_base_uri !== $newSettings['open_ai_gpt_4o_base_uri']) {\n return false;\n }\n\n if ($originalSettings->open_ai_gpt_4o_mini_base_uri !== $newSettings['open_ai_gpt_4o_mini_base_uri']) {\n return false;\n }\n\n return true;\n })\n ->extraModalFooterActions([\n Action::make('justSave')\n ->label('Just save the settings')\n ->color('gray')\n ->action(fn () => $this->save())\n ->cancelParentActions(),\n ])\n ->action(function (AiIntegrationsSettings $originalSettings, ResetAiServiceIdsForModel $resetAiServiceIds) {\n $newSettings = $this->form->getState();\n\n $changedModels = [\n ...(($originalSettings->open_ai_gpt_35_base_uri !== $newSettings['open_ai_gpt_35_base_uri']) ? [AiModel::OpenAiGpt35] : []),\n ...(($originalSettings->open_ai_gpt_4_base_uri !== $newSettings['open_ai_gpt_4_base_uri']) ? [AiModel::OpenAiGpt4] : []),\n ...(($originalSettings->open_ai_gpt_4o_base_uri !== $newSettings['open_ai_gpt_4o_base_uri']) ? [AiModel::OpenAiGpt4o] : []),\n ...(($originalSettings->open_ai_gpt_4o_mini_base_uri !== $newSettings['open_ai_gpt_4o_mini_base_uri']) ? [AiModel::OpenAiGpt4o] : []),\n ];\n\n DB::transaction(function () use ($changedModels, $resetAiServiceIds) {\n foreach ($changedModels as $changedModel) {\n $resetAiServiceIds($changedModel);\n }\n });\n\n $this->save();\n\n foreach ($changedModels as $changedModel) {\n dispatch(app(ReInitializeAiModel::class, ['model' => $changedModel->value]));\n }\n });\n }", "smellKey": "S3776", "smellId": null, "repo": "canyongbs_advisingapp", "language": "php"} {"function": "public function check_dup_terms($params=null){\n global $TL;\n\n $resStatus = true;\n $resMsg = '';\n\n $mysqli = $this->mysqli;\n\n if(@$params['data']){\n $lists = json_decode($params['data'], true);\n }else{\n $lists = getTermsWithIssues($mysqli);\n }\n $trmWithWrongParents = prepareIds(@$lists[\"trm_missed_parents\"]);\n $trmWithWrongInverse = prepareIds(@$lists[\"trm_missed_inverse\"]);\n $trmDuplicates = @$lists[\"trm_dupes\"];\n\n $wasassigned1 = 0;\n $wasassigned2 = 0;\n if(@$params['fix']==\"1\")\n {\n mysql__safe_updatess($mysqli, false);\n\n if(!isEmptyArray($trmWithWrongParents)){\n\n $trash_group_id = mysql__select_value($mysqli, 'select vcg_ID from defVocabularyGroups where vcg_Name=\"Trash\"');\n\n if($trash_group_id>0){\n\n $query = 'UPDATE defTerms set trm_ParentTermID=NULL, trm_VocabularyGroupID='.intval($trash_group_id)\n .' WHERE trm_ID in ('.implode(',',$trmWithWrongParents).')';\n\n $wasassigned1 = mysql__exec_param_query($this->mysqli, $query, null, true );\n if(is_string($wasassigned1))\n {\n $resMsg = '<div class=\"error\">Cannot delete invalid pointers to parent terms. Error:'.$wasassigned1.DIV_E;\n $resStatus = false;\n }else{\n $trmWithWrongParents = array();//reset\n }\n\n }else{\n $resMsg = '<div class=\"error\">Cannot find \"Trash\" group to fix invalid pointers to parent terms.</div>';\n $resStatus = false;\n }\n }\n\n if(!isEmptyArray($trmWithWrongInverse)){\n $query = 'UPDATE defTerms set trm_InverseTermID=NULL '\n .' WHERE trm_ID in ('.implode(',',$trmWithWrongInverse).')';\n\n $wasassigned2 = mysql__exec_param_query($this->mysqli, $query, null, true );\n if(is_string($wasassigned2))\n {\n $resMsg = '<div class=\"error\">Cannot clear missing inverse terms ids. Error:'.$wasassigned2.DIV_E;\n $resStatus = false;\n }else{\n $trmWithWrongInverse = array();//reset\n }\n\n }\n\n mysql__safe_updatess($mysqli, true);\n }\n\n if(empty($trmWithWrongParents) && empty($trmWithWrongInverse)){\n $resMsg .= '<div><h3 class=\"res-valid\">OK: All terms have valid inverse and parent term references</h3></div>';\n\n if($wasassigned1>0){\n $resMsg .= \"<div>$wasassigned1 terms with wrong parent terms moved to 'Trash' group as vocabularies</div>\";\n }\n if($wasassigned2>0){\n $resMsg .= \"<div>$wasassigned2 wrong inverse term references are cleared</div>\";\n }\n }\n else\n {\n\n $resMsg .= DIV_S;\n if(!empty($trmWithWrongParents)){\n\n $resMsg .= '<h3>'.count($trmWithWrongParents).' terms have wrong parent term references</h3>';\n $cnt = 0;\n foreach ($trmWithWrongParents as $trm_ID) {\n $resMsg .= ('<br>'.$trm_ID.' '.$TL[$trm_ID]['trm_Label']);\n if($cnt>30){\n $resMsg .= ('<br>'.count($trmWithWrongParents)-$cnt.' more...');\n break;\n }\n $cnt++;\n }\n $resStatus = false;\n }\n if(!empty($trmWithWrongInverse)){\n\n $resMsg .= '<h3>'.count($trmWithWrongInverse).' terms have wrong inverse term references</h3>';\n $cnt = 0;\n foreach ($trmWithWrongInverse as $trm_ID) {\n $resMsg .= '<br>'.$trm_ID.' '.$TL[$trm_ID]['trm_Label'];\n if($cnt>30){\n $resMsg .= '<br>'.count($trmWithWrongInverse)-$cnt.' more...';\n break;\n }\n $cnt++;\n }\n $resStatus = false;\n }\n\n $resMsg .= '<br><br><button data-fix=\"dup_terms\">Correct wrong parent and inverse term references</button></div>';\n }\n\n if(!empty($trmDuplicates)){\n $resStatus = false;\n\n $resMsg .= '<h3>Terms are duplicated or ending in a number: these may be the result of automatic duplicate-avoidance. '\n .'If so, we suggest deleting the numbered term or using Design > Vocabularies to merge it with the un-numbered version.</h3>';\n foreach ($trmDuplicates as $parent_ID=>$dupes) {\n $resMsg .= '<div style=\"padding-top:10px;font-style:italic\">parent '.intval($parent_ID).' '\n .htmlspecialchars($TL[$parent_ID]['trm_Label']).DIV_E;\n foreach ($dupes as $trm_ID) {\n $resMsg .= '<div style=\"padding-left:60px\">'.intval($trm_ID).' '\n .htmlspecialchars($TL[$trm_ID]['trm_Label']).DIV_E;\n }\n }\n }\n\n return array('status'=>$resStatus,'message'=>$resMsg);\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public static function getModulesOnDisk($use_config = false, $logged_on_addons = false, $id_employee = false)\n {\n global $_MODULES;\n\n // Init var\n $module_list = array();\n $module_name_list = array();\n $modules_name_to_cursor = array();\n $errors = array();\n\n // Get modules directory list and memory limit\n $modules_dir = Module::getModulesDirOnDisk();\n\n $modules_installed = array();\n $result = Db::getInstance()->executeS('\n SELECT m.name, m.version, mp.interest, module_shop.enable_device\n FROM `'._DB_PREFIX_.'module` m\n '.Shop::addSqlAssociation('module', 'm', false).'\n LEFT JOIN `'._DB_PREFIX_.'module_preference` mp ON (mp.`module` = m.`name` AND mp.`id_employee` = '.(int)$id_employee.')');\n foreach ($result as $row) {\n $modules_installed[$row['name']] = $row;\n }\n\n foreach ($modules_dir as $module) {\n $module_errors = array();\n if (Module::useTooMuchMemory()) {\n $module_errors[] = Context::getContext()->getTranslator()->trans('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration', array(), 'Admin.Modules.Notification');\n break;\n }\n\n $iso = substr(Context::getContext()->language->iso_code, 0, 2);\n\n // Check if config.xml module file exists and if it's not outdated\n\n if ($iso == 'en') {\n $config_file = _PS_MODULE_DIR_.$module.'/config.xml';\n } else {\n $config_file = _PS_MODULE_DIR_.$module.'/config_'.$iso.'.xml';\n }\n\n $xml_exist = (file_exists($config_file));\n $need_new_config_file = $xml_exist ? (@filemtime($config_file) < @filemtime(_PS_MODULE_DIR_.$module.'/'.$module.'.php')) : true;\n\n // If config.xml exists and that the use config flag is at true\n if ($use_config && $xml_exist && !$need_new_config_file) {\n // Load config.xml\n libxml_use_internal_errors(true);\n $xml_module = @simplexml_load_file($config_file);\n if (!$xml_module) {\n $module_errors[] = Context::getContext()->getTranslator()->trans(\n '%s could not be loaded.',\n array($config_file),\n 'Admin.Modules.Notification'\n );\n break;\n }\n foreach (libxml_get_errors() as $error) {\n $module_errors[] = '['.$module.'] '.Context::getContext()->getTranslator()->trans('Error found in config file:', array(), 'Admin.Modules.Notification').' '.htmlentities($error->message);\n }\n libxml_clear_errors();\n\n // If no errors in Xml, no need instand and no need new config.xml file, we load only translations\n if (!count($module_errors) && (int)$xml_module->need_instance == 0) {\n $file = _PS_MODULE_DIR_.$module.'/'.Context::getContext()->language->iso_code.'.php';\n if (Tools::file_exists_cache($file) && include_once($file)) {\n if (isset($_MODULE) && is_array($_MODULE)) {\n $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;\n }\n }\n\n $item = new \\stdClass();\n $item->id = 0;\n $item->warning = '';\n\n foreach ($xml_module as $k => $v) {\n $item->$k = (string)$v;\n }\n\n $item->displayName = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string)$xml_module->name));\n $item->description = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->description), (string)$xml_module->name));\n $item->author = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->author), (string)$xml_module->name));\n $item->author_uri = (isset($xml_module->author_uri) && $xml_module->author_uri) ? stripslashes($xml_module->author_uri) : false;\n\n if (isset($xml_module->confirmUninstall)) {\n $item->confirmUninstall = Translate::getModuleTranslation((string)$xml_module->name, html_entity_decode(Module::configXmlStringFormat($xml_module->confirmUninstall)), (string)$xml_module->name);\n }\n\n $item->active = 0;\n $item->onclick_option = false;\n $item->trusted = Module::isModuleTrusted($item->name);\n\n $module_list[$item->name.'_disk'] = $item;\n\n $module_name_list[] = '\\''.pSQL($item->name).'\\'';\n $modules_name_to_cursor[Tools::strtolower(strval($item->name))] = $item;\n }\n }\n\n // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file\n if (!$use_config || !$xml_exist || (isset($xml_module->need_instance) && (int)$xml_module->need_instance == 1) || $need_new_config_file) {\n // If class does not exists, we include the file\n if (!class_exists($module, false)) {\n // Get content from php file\n $file_path = _PS_MODULE_DIR_.$module.'/'.$module.'.php';\n $file = trim(file_get_contents(_PS_MODULE_DIR_.$module.'/'.$module.'.php'));\n\n try {\n $parser = (new PhpParser\\ParserFactory)->create(PhpParser\\ParserFactory::PREFER_PHP7);\n $parser->parse($file);\n require_once($file_path);\n } catch (PhpParser\\Error $e) {\n $errors[] = Context::getContext()->getTranslator()->trans('%1$s (parse error in %2$s)', array($module, substr($file_path, strlen(_PS_ROOT_DIR_))), 'Admin.Modules.Notification');\n }\n\n preg_match('/\\n[\\s\\t]*?namespace\\s.*?;/', $file, $ns);\n if (!empty($ns)) {\n $ns = preg_replace('/\\n[\\s\\t]*?namespace\\s/', '', $ns[0]);\n $ns = rtrim($ns, ';');\n $module = $ns.'\\\\'.$module;\n }\n }\n\n // If class exists, we just instanciate it\n if (class_exists($module, false)) {\n try {\n $tmp_module = ServiceLocator::get($module);\n\n $item = new \\stdClass();\n\n $item->id = (int)$tmp_module->id;\n $item->warning = $tmp_module->warning;\n $item->name = $tmp_module->name;\n $item->version = $tmp_module->version;\n $item->tab = $tmp_module->tab;\n $item->displayName = $tmp_module->displayName;\n $item->description = stripslashes($tmp_module->description);\n $item->author = $tmp_module->author;\n $item->author_uri = (isset($tmp_module->author_uri) && $tmp_module->author_uri) ? $tmp_module->author_uri : false;\n $item->limited_countries = $tmp_module->limited_countries;\n $item->parent_class = get_parent_class($module);\n $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0;\n $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0;\n $item->active = $tmp_module->active;\n $item->trusted = Module::isModuleTrusted($tmp_module->name);\n $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null;\n $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null;\n $item->confirmUninstall = isset($tmp_module->confirmUninstall) ? html_entity_decode($tmp_module->confirmUninstall) : null;\n $item->description_full = stripslashes($tmp_module->description_full);\n $item->additional_description = isset($tmp_module->additional_description) ? stripslashes($tmp_module->additional_description) : null;\n $item->compatibility = isset($tmp_module->compatibility) ? (array)$tmp_module->compatibility : null;\n $item->nb_rates = isset($tmp_module->nb_rates) ? (array)$tmp_module->nb_rates : null;\n $item->avg_rate = isset($tmp_module->avg_rate) ? (array)$tmp_module->avg_rate : null;\n $item->badges = isset($tmp_module->badges) ? (array)$tmp_module->badges : null;\n $item->url = isset($tmp_module->url) ? $tmp_module->url : null;\n $item->onclick_option = method_exists($module, 'onclickOption') ? true : false;\n\n if ($item->onclick_option) {\n $href = Context::getContext()->link->getAdminLink('Module', true).'&module_name='.$tmp_module->name.'&tab_module='.$tmp_module->tab;\n $item->onclick_option_content = array();\n $option_tab = array('desactive', 'reset', 'configure', 'delete');\n\n foreach ($option_tab as $opt) {\n $item->onclick_option_content[$opt] = $tmp_module->onclickOption($opt, $href);\n }\n }\n\n $module_list[$item->name.'_disk'] = $item;\n\n if (!$xml_exist || $need_new_config_file) {\n self::$_generate_config_xml_mode = true;\n $tmp_module->_generateConfigXml();\n self::$_generate_config_xml_mode = false;\n }\n\n unset($tmp_module);\n } catch (Exception $e) {\n }\n } else {\n $module_errors[] = Context::getContext()->getTranslator()->trans('%1$s (class missing in %2$s)', array($module, substr($file_path, strlen(_PS_ROOT_DIR_))), 'Admin.Modules.Notification');\n }\n }\n $errors = array_merge($errors, $module_errors);\n }\n\n // Get modules information from database\n if (!empty($module_name_list)) {\n $list = Shop::getContextListShopID();\n $sql = 'SELECT m.id_module, m.name, (\n SELECT COUNT(*) FROM '._DB_PREFIX_.'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN ('.implode(',', $list).')\n ) as total\n FROM '._DB_PREFIX_.'module m\n WHERE LOWER(m.name) IN ('.Tools::strtolower(implode(',', $module_name_list)).')';\n $results = Db::getInstance()->executeS($sql);\n\n foreach ($results as $result) {\n if (isset($modules_name_to_cursor[Tools::strtolower($result['name'])])) {\n $module_cursor = $modules_name_to_cursor[Tools::strtolower($result['name'])];\n $module_cursor->id = (int)$result['id_module'];\n $module_cursor->active = ($result['total'] == count($list)) ? 1 : 0;\n }\n }\n }\n\n // Get Default Country Modules and customer module\n $files_list = array(\n array('type' => 'addonsNative', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0),\n array('type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0),\n array('type' => 'addonsBought', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1),\n );\n foreach ($files_list as $f) {\n if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $logged_on_addons)) {\n if (Module::useTooMuchMemory()) {\n $errors[] = Context::getContext()->getTranslator()->trans('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration', array(), 'Admin.Modules.Notification');\n break;\n }\n\n $file = $f['file'];\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $flag_found = 0;\n\n foreach ($module_list as $k => &$m) {\n if (Tools::strtolower($m->name) == Tools::strtolower($modaddons->name) && !isset($m->available_on_addons)) {\n $flag_found = 1;\n if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1) {\n $module_list[$k]->version_addons = $modaddons->version;\n }\n }\n }\n\n if ($flag_found == 0) {\n $item = new \\stdClass();\n $item->id = 0;\n $item->warning = '';\n $item->type = strip_tags((string)$f['type']);\n $item->name = strip_tags((string)$modaddons->name);\n $item->version = strip_tags((string)$modaddons->version);\n $item->tab = strip_tags((string)$modaddons->tab);\n $item->displayName = strip_tags((string)$modaddons->displayName);\n $item->description = stripslashes(strip_tags((string)$modaddons->description));\n $item->description_full = stripslashes(strip_tags((string)$modaddons->description_full));\n $item->author = strip_tags((string)$modaddons->author);\n $item->limited_countries = array();\n $item->parent_class = '';\n $item->onclick_option = false;\n $item->is_configurable = 0;\n $item->need_instance = 0;\n $item->not_on_disk = 1;\n $item->available_on_addons = 1;\n $item->trusted = Module::isModuleTrusted($item->name);\n $item->active = 0;\n $item->description_full = stripslashes($modaddons->description_full);\n $item->additional_description = isset($modaddons->additional_description) ? stripslashes($modaddons->additional_description) : null;\n $item->compatibility = isset($modaddons->compatibility) ? (array)$modaddons->compatibility : null;\n $item->nb_rates = isset($modaddons->nb_rates) ? (array)$modaddons->nb_rates : null;\n $item->avg_rate = isset($modaddons->avg_rate) ? (array)$modaddons->avg_rate : null;\n $item->badges = isset($modaddons->badges) ? (array)$modaddons->badges : null;\n $item->url = isset($modaddons->url) ? $modaddons->url : null;\n if (isset($item->description_full) && trim($item->description_full) != '') {\n $item->show_quick_view = true;\n }\n\n if (isset($modaddons->img)) {\n $item->image = Module::copyModAddonsImg($modaddons);\n }\n\n\n if ($item->type == 'addonsMustHave') {\n $item->addons_buy_url = strip_tags((string)$modaddons->url);\n $prices = (array)$modaddons->price;\n $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');\n\n foreach ($prices as $currency => $price) {\n if ($id_currency = Currency::getIdByIsoCode($currency)) {\n $item->price = (float)$price;\n $item->id_currency = (int)$id_currency;\n\n if ($id_default_currency == $id_currency) {\n break;\n }\n }\n }\n }\n\n $module_list[$item->name.'_feed'] = $item;\n }\n\n if (isset($module_list[$modaddons->name.'_disk'])) {\n $module_list[$modaddons->name.'_disk']->description_full = stripslashes(strip_tags((string)$modaddons->description_full));\n $module_list[$modaddons->name.'_disk']->additional_description = stripslashes(strip_tags((string)$modaddons->additional_description));\n $module_list[$modaddons->name.'_disk']->image = Module::copyModAddonsImg($modaddons);\n $module_list[$modaddons->name.'_disk']->show_quick_view = true;\n }\n }\n }\n }\n }\n\n foreach ($module_list as $key => &$module) {\n if (!isset($module->tab)) {\n $module->tab = 'others';\n }\n if (defined('_PS_HOST_MODE_') && in_array($module->name, self::$hosted_modules_blacklist)) {\n unset($module_list[$key]);\n } elseif (isset($modules_installed[$module->name])) {\n $module->installed = true;\n $module->database_version = $modules_installed[$module->name]['version'];\n $module->interest = $modules_installed[$module->name]['interest'];\n $module->enable_device = $modules_installed[$module->name]['enable_device'];\n } else {\n $module->installed = false;\n $module->database_version = 0;\n $module->interest = 0;\n }\n }\n\n usort($module_list, function ($a, $b) { return strnatcasecmp($a->displayName, $b->displayName); });\n if ($errors) {\n if (!isset(Context::getContext()->controller) && !Context::getContext()->controller->controller_name) {\n echo '<div class=\"alert error\"><h3>'.Context::getContext()->getTranslator()->trans('The following module(s) could not be loaded', array(), 'Admin.Modules.Notification').':</h3><ol>';\n foreach ($errors as $error) {\n echo '<li>'.$error.'</li>';\n }\n echo '</ol></div>';\n } else {\n foreach ($errors as $error) {\n Context::getContext()->controller->errors[] = $error;\n }\n }\n }\n\n return $module_list;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function draw_cylinder() {\n $size = 300;\n $input = func_get_args();\n $argsArray = [];\n $args = '';\n $hasFill = false;\n $hasDiameter = false;\n $hasRadius = false;\n $hasRadiusLab = false;\n $hasHeight = false;\n $hasHeightLab = false;\n $hasUserAltText = false;\n $altFill = \"\";\n $colorFill = 'lightblue';\n foreach ($input as $list) {\n if (!is_array($list)) {\n $list = listtoarray($list);\n }\n $list = array_map('trim', $list);\n $argsArray[]=$list;\n }\n foreach ($argsArray as $in) {\n if (array_key_exists(0,$in)) {\n if (empty($in[0])) {\n echo \"Eek! Cannot use an empty argument for draw_cylinder.\";\n return '';\n }\n if ($in[0] == \"alttext\") {\n if (isset($in[1])) {\n $hasUserAltText = true;\n $userAltText = $in[1];\n }\n }\n if ($in[0] == \"size\") {\n if (isset($in[1]) && is_numeric($in[1])) {\n $size = $in[1];\n }\n }\n if ($in[0] == \"fill\") {\n $hasFill = true;\n if (!isset($in[1]) || (!is_numeric($in[1]) && $in[1] == \"\")) {\n $fillPercent = $GLOBALS['RND']->rand(20,80);\n } elseif (is_numeric($in[1])) {\n if ($in[1]<0 || $in[1]>100) {\n echo 'Eek! Fill percent must be between 0 and 100.';\n $fillPercent = $GLOBALS['RND']->rand(20,80);\n } else {\n $fillPercent = $in[1];\n }\n $altFill = ($fillPercent > 0) ? true : false;\n }\n if (isset($in[2]) && $in[2] != \"\") {\n $colorFill = str_replace(\"trans\", \"\" ,$in[2]);\n }\n }\n } else {\n echo \"Eek! Cannot have empty arguments for draw_cylinder.\";\n return '';\n }\n }\n if (isset($argsArray[0]) && isset($argsArray[0][0]) && isset($argsArray[1]) && isset($argsArray[1][0])) {\n if ((is_numeric($argsArray[0][0]) && !is_numeric($argsArray[1][0])) || (!is_numeric($argsArray[0][0]) && is_numeric($argsArray[1][0]))) {\n echo 'Warning! Diameter and height must both be numeric.';\n return '';\n }\n if (is_numeric($argsArray[0][0]) && $argsArray[0][0]>0 && is_numeric($argsArray[1][0]) && $argsArray[1][0]>0) {\n $diameter = $argsArray[0][0];\n $height = $argsArray[1][0];\n }\n if (!is_numeric($argsArray[0][0])) {\n [$diameter,$height] = diffrands(3,6,2);\n }\n } else {\n [$diameter,$height] = diffrands(3,8,2);\n }\n \n \n //if ((is_numeric($argsArray[0][0]) && !is_numeric($argsArray[1][0])) || (!is_numeric($argsArray[0][0]) && is_numeric($argsArray[1][0]))) {\n //echo 'Warning! Gave diameter without height.';\n //}\n //if (is_numeric($argsArray[0][0]) && $argsArray[0][0]>0 && is_numeric($argsArray[1][0]) && $argsArray[1][0]>0) {\n //$diameter = $argsArray[0][0];\n //$height = $argsArray[1][0];\n //} else {\n //[$diameter,$height] = diffrands(3,8,2);\n //}\n // Set the window dimensions\n $af = 4;\n $dim = max(1.5*$diameter/2,1.5*($height/2+$diameter/$af));\n // Fill cylinder\n $fillColor = 'black';\n if ($hasFill === true) {\n $fillHeight = $fillPercent/100*$height;\n $fillColor = 'slategray';\n $args = $args . \"strokewidth=0; fill='$colorFill'; fillopacity=0.5; plot(['$diameter/2*cos(t)','$diameter/$af*sin(t)-$height/2'],0,2*pi); plot(['$diameter/2*cos(t)','$diameter/$af*sin(t)-$height/2+$fillHeight'],0,2*pi); rect([-$diameter/2,-$height/2],[$diameter/2,-$height/2+$fillHeight]); strokewidth=1; fill='none'; stroke='steelblue'; plot(['$diameter/2*cos(t)','$diameter/$af*sin(t)-$height/2+$fillHeight'],0,2*pi); stroke='black';\";\n }\n // Draw the cylinder\n $args = $args . \"strokewidth=2.5; strokedasharray='4 4'; stroke='$fillColor'; plot(['$diameter/2*cos(t)','$diameter/$af*sin(t)-$height/2'],0,pi); stroke='black'; strokedasharray='1 0'; fill='none'; ellipse([0,$height/2],$diameter/2,$diameter/$af); fill='none'; line([-$diameter/2,-$height/2],[-$diameter/2,$height/2]); line([$diameter/2,-$height/2],[$diameter/2,$height/2]); plot(['$diameter/2*cos(t)','$diameter/$af*sin(t)-$height/2'],pi,2*pi);\";\n // Draw and label the radius\n foreach ($argsArray as $in) {\n if ($in[0] == \"radius\") {\n $hasRadius = true;\n $args = $args . \"strokewidth=1; line([0,$height/2],[$diameter/2,$height/2]);\";\n if (isset($in[1])) {\n $hasRadiusLab = true;\n $radiusLab = $in[1];\n $args = $args . \"strokewidth=1; arc([$diameter/2,$height/2+1.5*$diameter/$af+$diameter/(10*$af)],[$diameter/4,$height/2+$diameter/(10*$af)],$diameter); text([$diameter/2,$height/2+1.5*$diameter/$af],'$in[1]',above);strokewidth=2;\";\n }\n }\n }\n // Draw and label the diameter\n foreach ($argsArray as $in) {\n if ($in[0] == \"diameter\") {\n $hasDiameter = true;\n $args = $args . \"strokewidth=1; line([-$diameter/2,$height/2],[$diameter/2,$height/2]);\";\n if (isset($in[1])) {\n $hasDiameterLab = true;\n $diameterLab = $in[1];\n $args = $args . \"strokewidth=1; arc([$diameter/2,$height/2+1.5*$diameter/$af+$diameter/(10*$af)],[$diameter/4,$height/2+$diameter/(10*$af)],$diameter); text([$diameter/2,$height/2+1.5*$diameter/$af],'$in[1]',above);strokewidth=2;\";\n }\n }\n }\n // Label the height\n foreach ($argsArray as $in) {\n if ($in[0] == \"height\") {\n if (isset($in[1])) {\n $heightLab = $in[1];\n $hasHeightLab = true;\n $args = $args . \"text([$diameter/2,0],'$in[1]',right);\";\n }\n }\n }\n // build the alt text\n if ($hasUserAltText !== true) {\n $alt = \"A circular cylinder\";\n if ($hasRadius === true) {\n $alt .= \" with the radius of its circular base drawn\";\n if ($hasRadiusLab === true) {\n $alt .= \" and labeled \".$radiusLab;\n }\n }\n if ($hasDiameter === true) {\n $alt .= ($hasRadius === true) ? \", \" : \"\";\n $alt .= \" with the diameter of its circular base drawn\";\n if ($hasDiameterLab === true) {\n $alt .= \" and labeled \".$diameterLab;\n }\n }\n if ($hasHeightLab === true) {\n $alt .= ($hasRadius === true || $hasDiameter === true) ? \", and\" : \"\";\n $alt .= \" with the height labeled \".$heightLab;\n }\n $alt .= \".\";\n if ($altFill === true) {\n $alt .= \" The cylinder is partially filled with colored material.\";\n }\n } else {\n $alt = $userAltText;\n }\n $gr = showasciisvg(\"setBorder(20);initPicture(-0.75*$dim,1.25*$dim,-$dim,$dim);$args\",$size,$size,$alt);\n return $gr;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function initContent()\n {\n if (!Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) {\n // You can uncomment these lines if you want to force https even from localhost and automatically redirect\n // header('HTTP/1.1 301 Moved Permanently');\n // header('Location: '.Tools::getShopDomainSsl(true).$_SERVER['REQUEST_URI']);\n // exit();\n $clientIsMaintenanceOrLocal = in_array(Tools::getRemoteAddr(), array_merge(array('127.0.0.1'), explode(',', Configuration::get('PS_MAINTENANCE_IP'))));\n // If ssl is enabled, https protocol is required. Exception for maintenance and local (127.0.0.1) IP\n if ($clientIsMaintenanceOrLocal) {\n $warningSslMessage = $this->trans('SSL is activated. However, your IP is allowed to enter unsecure mode for maintenance or local IP issues.', array(), 'Admin.Notifications.Error');\n } else {\n $url = 'https://'.Tools::safeOutput(Tools::getServerName()).Tools::safeOutput($_SERVER['REQUEST_URI']);\n $warningSslMessage = sprintf(\n Translate::ppTags(\n Tools::displayError('SSL is activated. Please connect using the following link to [1]log in to secure mode (https://)[/1]', false),\n array('<a href=\"%s\">')\n ),\n $url\n );\n }\n $this->context->smarty->assign('warningSslMessage', $warningSslMessage);\n }\n\n if (file_exists(_PS_ADMIN_DIR_.'/../install')) {\n $this->context->smarty->assign('wrong_install_name', true);\n }\n\n if (basename(_PS_ADMIN_DIR_) == 'admin' && file_exists(_PS_ADMIN_DIR_.'/../admin/')) {\n $rand = 'admin'.sprintf('%03d', rand(0, 999)).Tools::strtolower(Tools::passwdGen(6)).'/';\n if (@rename(_PS_ADMIN_DIR_.'/../admin/', _PS_ADMIN_DIR_.'/../'.$rand)) {\n Tools::redirectAdmin('../'.$rand);\n } else {\n $this->context->smarty->assign(array(\n 'wrong_folder_name' => true\n ));\n }\n } else {\n $rand = basename(_PS_ADMIN_DIR_).'/';\n }\n\n $this->context->smarty->assign(array(\n 'randomNb' => $rand,\n 'adminUrl' => Tools::getCurrentUrlProtocolPrefix().Tools::getShopDomain().__PS_BASE_URI__.$rand\n ));\n\n // Redirect to admin panel\n if (Tools::isSubmit('redirect') && Validate::isControllerName(Tools::getValue('redirect'))) {\n $this->context->smarty->assign('redirect', Tools::getValue('redirect'));\n } else {\n $tab = new Tab((int)$this->context->employee->default_tab);\n $this->context->smarty->assign('redirect', $this->context->link->getAdminLink($tab->class_name));\n }\n\n if ($nb_errors = count($this->errors)) {\n $this->context->smarty->assign(array(\n 'errors' => $this->errors,\n 'nbErrors' => $nb_errors,\n 'shop_name' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME')),\n 'disableDefaultErrorOutPut' => true,\n ));\n }\n\n if ($email = Tools::getValue('email')) {\n $this->context->smarty->assign('email', $email);\n }\n if ($password = Tools::getValue('password')) {\n $this->context->smarty->assign('password', $password);\n }\n\n // For reset password feature\n if ($reset_token = Tools::getValue('reset_token')) {\n $this->context->smarty->assign('reset_token', $reset_token);\n }\n if ($id_employee = Tools::getValue('id_employee')) {\n $this->context->smarty->assign('id_employee', $id_employee);\n $employee = new Employee($id_employee);\n if (Validate::isLoadedObject($employee)) {\n $this->context->smarty->assign('reset_email', $employee->email);\n }\n }\n\n $this->setMedia();\n $this->initHeader();\n parent::initContent();\n $this->initFooter();\n\n //force to disable modals\n $this->context->smarty->assign('modals', null);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function assign($tid, $target=null) {\n global $thisstaff;\n\n if (!($ticket=Ticket::lookup($tid)))\n Http::response(404, __('No such ticket'));\n\n if (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_ASSIGN)\n || !($form = $ticket->getAssignmentForm($_POST,\n array('target' => $target))))\n Http::response(403, __('Permission denied'));\n\n $errors = array();\n $info = array(\n ':title' => sprintf(__('Ticket #%s: %s'),\n $ticket->getNumber(),\n sprintf('%s %s',\n $ticket->isAssigned() ?\n __('Reassign') : __('Assign'),\n !strcasecmp($target, 'agents') ?\n __('to an Agent') : __('to a Team')\n )),\n ':action' => sprintf('#tickets/%d/assign%s',\n $ticket->getId(),\n ($target ? \"/$target\": '')),\n );\n\n if ($ticket->isAssigned()) {\n if ($ticket->getStaffId() == $thisstaff->getId())\n $assigned = __('you');\n else\n $assigned = $ticket->getAssigned();\n\n $info['notice'] = sprintf(__('%s is currently assigned to <b>%s</b>'),\n __('This ticket'),\n Format::htmlchars($assigned)\n );\n }\n\n if ($_POST && $form->isValid()) {\n if ($ticket->assign($form, $errors)) {\n $msg = sprintf(\n __('%s successfully'),\n sprintf(\n __('%s assigned to %s'),\n __('Ticket'),\n $form->getAssignee())\n );\n\n $assignee = $ticket->isAssigned() ? Format::htmlchars(implode('/', $ticket->getAssignees())) :\n '<span class=\"faded\">&mdash; '.__('Unassigned').' &mdash;';\n Http::response(201, $this->json_encode(['value' =>\n $assignee, 'id' => 'assign', 'msg' => $msg]));\n }\n\n $form->addErrors($errors);\n $info['error'] = $errors['err'] ?: __('Unable to assign ticket');\n }\n\n include STAFFINC_DIR . 'templates/assign.tmpl.php';\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function run($args, $options) {\n\n Bootstrap::connect();\n\n switch ($args['action']) {\n case 'import':\n if (!$options['file'] || $options['file'] == '-')\n $options['file'] = 'php://stdin';\n if (!($this->stream = fopen($options['file'], 'rb')))\n $this->fail(\"Unable to open input file [{$options['file']}]\");\n\n $extras = array();\n if ($options['org']) {\n if (!($org = Organization::lookup($options['org'])))\n $this->fail($options['org'].': Unknown organization ID');\n $extras['org_id'] = $options['org'];\n }\n $status = User::importCsv($this->stream, $extras);\n if (is_numeric($status))\n $this->stderr->write(\"Successfully imported $status clients\\n\");\n else\n $this->fail($status);\n break;\n\n case 'export':\n $stream = $options['file'] ?: 'php://stdout';\n if (!($this->stream = fopen($stream, 'c')))\n $this->fail(\"Unable to open output file [{$options['file']}]\");\n\n fputcsv($this->stream, array('Name', 'Email'));\n foreach (User::objects() as $user)\n fputcsv($this->stream,\n array((string) $user->getName(), $user->getEmail()));\n break;\n\n case 'activate':\n $users = $this->getQuerySet($options);\n foreach ($users as $U) {\n if ($options['verbose']) {\n $this->stderr->write(sprintf(\n \"Activating %s <%s>\\n\",\n $U->getName(), $U->getDefaultEmail()\n ));\n }\n if (!($account = $U->getAccount())) {\n $account = UserAccount::create(array('user' => $U));\n $U->account = $account;\n $U->save();\n }\n\n if ($options['send-mail']) {\n global $ost, $cfg;\n $ost = osTicket::start();\n $cfg = $ost->getConfig();\n\n if (($error = $account->sendConfirmEmail()) && $error !== true) {\n $this->warn(sprintf('%s: Unable to send email: %s',\n $U->getDefaultEmail(), $error->getMessage()\n ));\n }\n }\n }\n\n break;\n\n case 'lock':\n $users = $this->getQuerySet($options);\n $users->select_related('account');\n foreach ($users as $U) {\n if (!($account = $U->getAccount())) {\n $this->warn(sprintf(\n '%s: User does not have a client account',\n $U->getName()\n ));\n }\n $account->setFlag(UserAccountStatus::LOCKED);\n $account->save();\n }\n\n break;\n\n case 'list':\n $users = $this->getQuerySet($options);\n\n foreach ($users as $U) {\n $this->stdout->write(sprintf(\n \"%d %s <%s>%s\\n\",\n $U->id, $U->getName(), $U->getDefaultEmail(),\n ($O = $U->getOrganization()) ? \" ({$O->getName()})\" : ''\n ));\n }\n\n break;\n\n case 'set-password':\n $this->stderr->write('Enter new password: ');\n $ps1 = fgets(STDIN);\n if (!function_exists('posix_isatty') || !posix_isatty(STDIN)) {\n $this->stderr->write('Re-enter new password: ');\n $ps2 = fgets(STDIN);\n\n if ($ps1 != $ps2)\n $this->fail('Passwords do not match');\n }\n\n // Account is required\n $options['account'] = true;\n $users = $this->getQuerySet($options);\n\n $updated = 0;\n foreach ($users as $U) {\n $U->account->setPassword($ps1);\n if ($U->account->save())\n $updated++;\n }\n $this->stdout->write(sprintf('Updated %d users', $updated));\n break;\n\n default:\n $this->stderr->write('Unknown action!');\n }\n if (is_resource($this->stream))\n @fclose($this->stream);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function getsubinfo($items, $parent, $pre, $itemtypelimit = false, $spacer = '|&nbsp;&nbsp;')\n{\n global $ids, $types, $names, $sums, $parents, $gitypeids, $prespace, $CFG, $itemshowdata;\n if (!isset($gitypeids)) {\n $gitypeids = array();\n }\n\n foreach ($items as $k => $item) {\n if (is_array($item)) {\n $ids[] = $parent . '-' . ($k + 1);\n $types[] = \"Block\";\n $names[] = $item['name'];\n $prespace[] = $pre;\n $parents[] = $parent;\n $gitypeids[] = '';\n $sums[] = '';\n if (count($item['items']) > 0) {\n getsubinfo($item['items'], $parent . '-' . ($k + 1), $pre . $spacer, $itemtypelimit, $spacer);\n }\n } else {\n if ($item == null || $item == '') {\n continue;\n }\n if (!empty($itemshowdata)) {\n if (isset($itemshowdata[$item]['name'])) {\n $name = $itemshowdata[$item]['name'];\n } else if (isset($itemshowdata[$item]['title'])) {\n $name = $itemshowdata[$item]['title'];\n } else {\n continue;\n }\n if (isset($itemshowdata[$item]['summary'])) {\n $summary = $itemshowdata[$item]['summary'];\n } else if (isset($itemshowdata[$item]['text'])) {\n $summary = $itemshowdata[$item]['text'];\n } else {\n $summary = $itemshowdata[$item]['description'];\n }\n $arr = array($itemshowdata[$item]['itemtype'], $name, $summary, $itemshowdata[$item]['id']);\n } else {\n $arr = getiteminfo($item);\n }\n if ($arr[0] === false || ($itemtypelimit !== false && $arr[0] != $itemtypelimit)) {\n continue;\n }\n $ids[] = $item;\n $parents[] = $parent;\n $types[] = $arr[0];\n $names[] = $arr[1];\n $prespace[] = $pre;\n $gitypeids[] = $arr[3];\n $arr[2] = strip_tags($arr[2]);\n if (strlen($arr[2]) > 100) {\n $arr[2] = substr($arr[2], 0, 97) . '...';\n }\n $sums[] = $arr[2];\n }\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function quickview($items, $parent, $showdates = false, $showlinks = true)\n{\n global $DBH, $teacherid, $cid, $imasroot, $userid, $openblocks, $firstload, $exceptions, $latepasses, $CFG;\n global $itemtypes, $iteminfo, $addassess, $staticroot;\n if (!is_array($openblocks)) {$openblocks = array();}\n if ($parent == '0') {\n $itemtypes = array();\n $iteminfo = array();\n $stm = $DBH->prepare(\"SELECT id,itemtype,typeid FROM imas_items WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $itemtypes[$row[0]] = array($row[1], $row[2]);\n }\n $stm = $DBH->prepare(\"SELECT id,name,startdate,enddate,reviewdate,avail,ver FROM imas_assessments WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['Assessment'][$id] = $row;\n }\n $stm = $DBH->prepare(\"SELECT id,title,text,startdate,enddate,avail FROM imas_inlinetext WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['InlineText'][$id] = $row;\n }\n $stm = $DBH->prepare(\"SELECT id,title,startdate,enddate,avail FROM imas_linkedtext WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['LinkedText'][$id] = $row;\n }\n $stm = $DBH->prepare(\"SELECT id,name,startdate,enddate,avail FROM imas_forums WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['Forum'][$id] = $row;\n }\n $stm = $DBH->prepare(\"SELECT id,name,startdate,enddate,avail FROM imas_wikis WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['Wiki'][$id] = $row;\n }\n $stm = $DBH->prepare(\"SELECT id,name,startdate,enddate,avail FROM imas_drillassess WHERE courseid=:courseid\");\n $stm->execute(array(':courseid' => $cid));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $id = array_shift($row);\n $iteminfo['Drill'][$id] = $row;\n }\n }\n $now = time();\n for ($i = 0; $i < count($items); $i++) {\n if (is_array($items[$i])) { //is a block\n\n if ($items[$i]['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($items[$i]['startdate']);\n }\n if ($items[$i]['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($items[$i]['enddate']);\n }\n $bnum = $i + 1;\n if (strlen($items[$i]['SH']) == 1 || $items[$i]['SH'][1] == 'O') {\n $availbeh = _('Expanded');\n } else if ($items[$i]['SH'][1] == 'F') {\n $availbeh = _('as Folder');\n } else {\n $availbeh = _('Collapsed');\n }\n if ($items[$i]['avail'] == 2) {\n $show = sprintf(('Showing %s Always'), $availbeh);\n } else if ($items[$i]['avail'] == 0) {\n $show = _('Hidden');\n } else {\n $show = sprintf(_('Showing %1$s %2$s until %3$s'), $availbeh, $startdate, $enddate);\n }\n if ($items[$i]['avail'] == 2) {\n $color = '#0f0';\n } else if ($items[$i]['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($items[$i]['startdate'], $items[$i]['enddate'], $now);\n }\n if (in_array($items[$i]['id'], $openblocks)) {$isopen = true;} else { $isopen = false;}\n if ($isopen || count($items[$i]['items']) == 0) {\n $liclass = 'blockli';\n $qviewstyle = '';\n } else {\n $liclass = 'blockli nCollapse';\n $qviewstyle = 'style=\"display:none;\"';\n }\n if (!isset($CFG['CPS']['miniicons']['folder'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">B</span>';\n } else {\n $icon = '<img alt=\"folder\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['folder'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li class=\"' . $liclass . '\" id=\"' . \"$parent-$bnum\" . '\" obn=\"' . Sanitize::encodeStringForDisplay($items[$i]['id']) . '\">' . $icon;\n if ($items[$i]['avail'] == 2 || ($items[$i]['avail'] == 1 && $items[$i]['startdate'] < $now && $items[$i]['enddate'] > $now)) {\n echo '<b><span id=\"B' . $parent . '-' . $bnum . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($items[$i]['name']) . \"</span></b>\";\n //echo '<b>'.$items[$i]['name'].'</b>';\n } else {\n echo '<i><b><span id=\"B' . $parent . '-' . $bnum . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($items[$i]['name']) . \"</span></b></i>\";\n //echo '<i><b>'.$items[$i]['name'].'</b></i>';\n }\n if ($showdates) {\n echo \" $show\";\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n echo \" <a href=\\\"addblock.php?cid=$cid&id=$parent-$bnum\\\">\", _('Modify'), \"</a>\";\n echo \" | <a href=\\\"deleteblock.php?cid=$cid&id=$parent-$bnum&bid=\" . intval($items[$i]['id']) . \"&remove=ask\\\">\", _('Delete'), \"</a>\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=$parent-$bnum\\\">\", _('Copy'), \"</a>\";\n echo \" | <a href=\\\"course.php?cid=$cid&togglenewflag=$parent-$bnum\\\">\", _('NewFlag'), \"</a>\";\n echo '</span>';\n }\n if (count($items[$i]['items']) > 0) {\n echo '<ul class=qview ' . $qviewstyle . '>';\n quickview($items[$i]['items'], $parent . '-' . $bnum, $showdates, $showlinks);\n echo '</ul>';\n }\n echo '</li>';\n } else if ($itemtypes[$items[$i]][0] == 'Calendar') {\n if (!isset($CFG['CPS']['miniicons']['calendar'])) {\n $icon = '<span class=icon style=\"background-color:#0f0;\">C</span>';\n } else {\n $icon = '<img alt=\"calendar\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['calendar'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon . 'Calendar</li>';\n\n } else if ($itemtypes[$items[$i]][0] == 'Assessment') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['startdate'], $line['enddate'], $line['reviewdate'], $line['avail'], $line['ver']) = $iteminfo['Assessment'][$typeid];\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['reviewdate'] == 2000000000) {\n $reviewdate = _('Always');\n } else {\n $reviewdate = formatdate($line['reviewdate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['assess'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">?</span>';\n } else {\n $icon = '<img alt=\"assessment\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['assess'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now) {\n $show = sprintf(_('Available until %s'), $enddate);\n echo '<b><span id=\"A' . $typeid . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n //echo '<b>'.$line['name'].'</b> ';\n } else if ($line['avail'] == 1 && $line['startdate'] < $now && $line['reviewdate'] > $now) {\n if ($line['ver'] > 1) {\n $show = sprintf(_('Practice until %s'), $reviewdate);\n } else {\n $show = sprintf(_('Review until %s'), $reviewdate);\n }\n //echo '<b>'.$line['name'].'</b> ';\n echo '<b><span id=\"A' . $typeid . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n } else {\n $show = sprintf(_('Available %1$s to %2$s'), $startdate, $enddate);\n if ($line['reviewdate'] > 0 && $line['enddate'] != 2000000000) {\n if ($line['ver'] > 1) {\n $show .= sprintf(_(', practice until %s'), $reviewdate);\n } else {\n $show .= sprintf(_(', review until %s'), $reviewdate);\n }\n }\n //echo '<i><b>'.$line['name'].'</b></i> ';\n echo '<i><b><span id=\"A' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n }\n if ($showdates) {\n echo Sanitize::encodeStringForDisplay($show);\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n if ($line['ver'] > 1) {\n echo \" <a href=\\\"addquestions2.php?aid=\" . Sanitize::onlyInt($typeid) . \"&cid=$cid\\\">\", _('Questions'), \"</a> | \";\n echo \"<a href=\\\"addassessment2.php?id=\" . Sanitize::onlyInt($typeid) . \"&cid=$cid\\\">\", _('Settings'), \"</a> | \\n\";\n } else {\n echo \" <a href=\\\"addquestions.php?aid=\" . Sanitize::onlyInt($typeid) . \"&cid=$cid\\\">\", _('Questions'), \"</a> | \";\n echo \"<a href=\\\"addassessment.php?id=\" . Sanitize::onlyInt($typeid) . \"&cid=$cid\\\">\", _('Settings'), \"</a> | \\n\";\n }\n echo \"<a href=\\\"deleteassessment.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n if ($line['ver'] > 1) {\n echo \" | <a href=\\\"gb-itemanalysis2.php?cid=$cid&aid=\" . Sanitize::onlyInt($typeid) . \"\\\">\", _('Grades'), \"</a>\";\n } else {\n echo \" | <a href=\\\"gb-itemanalysis.php?cid=$cid&asid=average&aid=\" . Sanitize::onlyInt($typeid) . \"\\\">\", _('Grades'), \"</a>\";\n }\n echo '</span>';\n }\n echo \"</li>\";\n\n } else if ($itemtypes[$items[$i]][0] == 'InlineText') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['text'], $line['startdate'], $line['enddate'], $line['avail']) = $iteminfo['InlineText'][$typeid];\n if ($line['name'] == '##hidden##') {\n $line['name'] = strip_tags($line['text']);\n }\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['inline'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">!</span>';\n } else {\n $icon = '<img alt=\"text\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['inline'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 2 || ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now)) {\n echo '<b><span id=\"I' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n // echo '<b>'.$line['name']. \"</b>\";\n if ($showdates) {\n printf(_(' showing until %s'), Sanitize::encodeStringForDisplay($enddate));\n }\n } else {\n //echo '<i><b>'.$line['name']. \"</b></i>\";\n echo '<i><b><span id=\"I' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n if ($showdates) {\n printf(_(' showing %1$s until %2$s'), Sanitize::encodeStringForDisplay($startdate), Sanitize::encodeStringForDisplay($enddate));\n }\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n echo \" <a href=\\\"addinlinetext.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid\\\">\", _('Modify'), \"</a> | \\n\";\n echo \"<a href=\\\"deleteinlinetext.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n echo '</span>';\n }\n echo '</li>';\n } else if ($itemtypes[$items[$i]][0] == 'LinkedText') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['startdate'], $line['enddate'], $line['avail']) = $iteminfo['LinkedText'][$typeid];\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['linked'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">!</span>';\n } else {\n $icon = '<img alt=\"link\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['linked'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 2 || ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now)) {\n //echo '<b>'.$line['name']. \"</b>\";\n echo '<b><span id=\"L' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n if ($showdates) {\n printf(_(' showing until %s'), Sanitize::encodeStringForDisplay($enddate));\n }\n } else {\n //echo '<i><b>'.$line['name']. \"</b></i>\";\n echo '<i><b><span id=\"L' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n if ($showdates) {\n printf(_(' showing %1$s until %2$s'), Sanitize::encodeStringForDisplay($startdate), Sanitize::encodeStringForDisplay($enddate));\n }\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n echo \" <a href=\\\"addlinkedtext.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid\\\">\", _('Modify'), \"</a> | \\n\";\n echo \"<a href=\\\"deletelinkedtext.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n echo '</span>';\n }\n echo '</li>';\n } else if ($itemtypes[$items[$i]][0] == 'Forum') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['startdate'], $line['enddate'], $line['avail']) = $iteminfo['Forum'][$typeid];\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['forum'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">F</span>';\n } else {\n $icon = '<img alt=\"forum\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['forum'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 2 || ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now)) {\n //echo '<b>'.$line['name']. \"</b>\";\n echo '<b><span id=\"F' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n if ($showdates) {\n printf(_(' showing until %s'), Sanitize::encodeStringForDisplay($enddate));\n }\n } else {\n echo '<i><b><span id=\"F' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n //echo '<i><b>'.$line['name']. \"</b></i>\";\n if ($showdates) {\n printf(_(' showing %1$s until %2$s'), Sanitize::encodeStringForDisplay($startdate), Sanitize::encodeStringForDisplay($enddate));\n }\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n echo \" <a href=\\\"addforum.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid\\\">\", _('Modify'), \"</a> | \\n\";\n echo \"<a href=\\\"deleteforum.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n echo '</span>';\n }\n echo '</li>';\n } else if ($itemtypes[$items[$i]][0] == 'Wiki') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['startdate'], $line['enddate'], $line['avail']) = $iteminfo['Wiki'][$typeid];\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['wiki'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">W</span>';\n } else {\n $icon = '<img alt=\"wiki\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['wiki'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 2 || ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now)) {\n //echo '<b>'.$line['name']. \"</b>\";\n echo '<b><span id=\"W' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n if ($showdates) {\n printf(_(' showing until %s'), Sanitize::encodeStringForDisplay($enddate));\n }\n } else {\n echo '<i><b><span id=\"W' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n //echo '<i><b>'.$line['name']. \"</b></i>\";\n if ($showdates) {\n printf(_(' showing %1$s until %2$s'), Sanitize::encodeStringForDisplay($startdate), Sanitize::encodeStringForDisplay($enddate));\n }\n }\n if ($showlinks) {\n echo '<span class=\"links\">';\n echo \" <a href=\\\"addwiki.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid\\\">\", _('Modify'), \"</a> | \\n\";\n echo \"<a href=\\\"deletewiki.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n echo '</span>';\n }\n echo '</li>';\n } else if ($itemtypes[$items[$i]][0] == 'Drill') {\n $typeid = Sanitize::onlyInt($itemtypes[$items[$i]][1]);\n list($line['name'], $line['startdate'], $line['enddate'], $line['avail']) = $iteminfo['Drill'][$typeid];\n if ($line['startdate'] == 0) {\n $startdate = _('Always');\n } else {\n $startdate = formatdate($line['startdate']);\n }\n if ($line['enddate'] == 2000000000) {\n $enddate = _('Always');\n } else {\n $enddate = formatdate($line['enddate']);\n }\n if ($line['avail'] == 2) {\n $color = '#0f0';\n } else if ($line['avail'] == 0) {\n $color = '#ccc';\n } else {\n $color = makecolor2($line['startdate'], $line['enddate'], $now);\n }\n if (!isset($CFG['CPS']['miniicons']['drill'])) {\n $icon = '<span class=icon style=\"background-color:' . $color . '\">D</span>';\n } else {\n $icon = '<img alt=\"wiki\" src=\"' . $staticroot . '/img/' . $CFG['CPS']['miniicons']['drill'] . '\" class=\"mida icon\" /> ';\n }\n echo '<li id=\"' . Sanitize::encodeStringForDisplay($items[$i]) . '\">' . $icon;\n if ($line['avail'] == 2 || ($line['avail'] == 1 && $line['startdate'] < $now && $line['enddate'] > $now)) {\n //echo '<b>'.$line['name']. \"</b>\";\n echo '<b><span id=\"D' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b>\";\n if ($showdates) {\n printf(_(' showing until %s'), Sanitize::encodeStringForDisplay($enddate));\n }\n } else {\n echo '<i><b><span id=\"D' . Sanitize::encodeStringForDisplay($typeid) . '\" onclick=\"editinplace(this)\">' . Sanitize::encodeStringForDisplay($line['name']) . \"</span></b></i>\";\n //echo '<i><b>'.$line['name']. \"</b></i>\";\n if ($showdates) {\n printf(_(' showing %1$s until %2$s'), Sanitize::encodeStringForDisplay($startdate), Sanitize::encodeStringForDisplay($enddate));\n }\n }\n if ($showlinks) {\n echo ' <span class=\"links\">';\n echo \"<a href=\\\"adddrillassess.php?daid=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid\\\">\", _('Modify'), \"</a> | \\n\";\n echo \"<a href=\\\"deletedrillassess.php?id=\" . Sanitize::onlyInt($typeid) . \"&block=$parent&cid=$cid&remove=ask\\\">\", _('Delete'), \"</a>\\n\";\n echo \" | <a href=\\\"copyoneitem.php?cid=$cid&copyid=\" . Sanitize::encodeUrlParam($items[$i]) . \"\\\">\", _('Copy'), \"</a>\";\n echo \" | <a href=\\\"gb-viewdrill.php?cid=$cid&daid=\" . Sanitize::onlyInt($typeid) . \"\\\">\", _('Scores'), \"</a>\";\n echo '</span>';\n }\n echo '</li>';\n }\n\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function removeOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname.'Core');\n\n if ($orig_path && !$file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n return true;\n } elseif (!$orig_path && Module::getModuleIdByName($classname)) {\n $path = 'modules'.DIRECTORY_SEPARATOR.$classname.DIRECTORY_SEPARATOR.$classname.'.php';\n }\n\n // Check if override file is writable\n if ($orig_path) {\n $override_path = _PS_ROOT_DIR_.'/'.$file;\n } else {\n $override_path = _PS_OVERRIDE_DIR_.$path;\n }\n\n if (!is_file($override_path) || !is_writable($override_path)) {\n return false;\n }\n\n file_put_contents($override_path, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($override_path)));\n\n if ($orig_path) {\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname.'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class '.$classname.'OverrideOriginal_remove'.$uniq), implode('', $override_file)));\n $override_class = new ReflectionClass($classname.'OverrideOriginal_remove'.$uniq);\n\n $module_file = file($this->getLocalPath().'override/'.$path);\n eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+'.$classname.'(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class '.$classname.'Override_remove'.$uniq), implode('', $module_file)));\n $module_class = new ReflectionClass($classname.'Override_remove'.$uniq);\n\n // Remove methods from override file\n foreach ($module_class->getMethods() as $method) {\n if (!$override_class->hasMethod($method->getName())) {\n continue;\n }\n\n $method = $override_class->getMethod($method->getName());\n $length = $method->getEndLine() - $method->getStartLine() + 1;\n\n $module_method = $module_class->getMethod($method->getName());\n $module_length = $module_method->getEndLine() - $module_method->getStartLine() + 1;\n\n $override_file_orig = $override_file;\n\n $orig_content = preg_replace('/\\s/', '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));\n $module_content = preg_replace('/\\s/', '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));\n\n $replace = true;\n if (preg_match('/\\* module: ('.$this->name.')/ism', $override_file[$method->getStartLine() - 5])) {\n $override_file[$method->getStartLine() - 6] = $override_file[$method->getStartLine() - 5] = $override_file[$method->getStartLine() - 4] = $override_file[$method->getStartLine() - 3] = $override_file[$method->getStartLine() - 2] = '#--remove--#';\n $replace = false;\n }\n\n if (md5($module_content) != md5($orig_content) && $replace) {\n $override_file = $override_file_orig;\n }\n }\n\n // Remove properties from override file\n foreach ($module_class->getProperties() as $property) {\n if (!$override_class->hasProperty($property->getName())) {\n continue;\n }\n\n // Replace the declaration line by #--remove--#\n foreach ($override_file as $line_number => &$line_content) {\n if (preg_match('/(public|private|protected)\\s+(static\\s+)?(\\$)?'.$property->getName().'/i', $line_content)) {\n if (preg_match('/\\* module: ('.$this->name.')/ism', $override_file[$line_number - 4])) {\n $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = $override_file[$line_number - 1] = '#--remove--#';\n }\n $line_content = '#--remove--#';\n break;\n }\n }\n }\n\n // Remove properties from override file\n foreach ($module_class->getConstants() as $constant => $value) {\n if (!$override_class->hasConstant($constant)) {\n continue;\n }\n\n // Replace the declaration line by #--remove--#\n foreach ($override_file as $line_number => &$line_content) {\n if (preg_match('/(const)\\s+(static\\s+)?(\\$)?'.$constant.'/i', $line_content)) {\n if (preg_match('/\\* module: ('.$this->name.')/ism', $override_file[$line_number - 4])) {\n $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = $override_file[$line_number - 1] = '#--remove--#';\n }\n $line_content = '#--remove--#';\n break;\n }\n }\n }\n\n $count = count($override_file);\n for ($i = 0; $i < $count; ++$i) {\n if (preg_match('/(^\\s*\\/\\/.*)/i', $override_file[$i])) {\n $override_file[$i] = '#--remove--#';\n } elseif (preg_match('/(^\\s*\\/\\*)/i', $override_file[$i])) {\n if (!preg_match('/(^\\s*\\* module:)/i', $override_file[$i + 1])\n && !preg_match('/(^\\s*\\* date:)/i', $override_file[$i + 2])\n && !preg_match('/(^\\s*\\* version:)/i', $override_file[$i + 3])\n && !preg_match('/(^\\s*\\*\\/)/i', $override_file[$i + 4])) {\n for (; $override_file[$i] && !preg_match('/(.*?\\*\\/)/i', $override_file[$i]); ++$i) {\n $override_file[$i] = '#--remove--#';\n }\n $override_file[$i] = '#--remove--#';\n }\n }\n }\n\n // Rewrite nice code\n $code = '';\n foreach ($override_file as $line) {\n if ($line == '#--remove--#') {\n continue;\n }\n\n $code .= $line;\n }\n\n $to_delete = preg_match('/<\\?(?:php)?\\s+(?:abstract|interface)?\\s*?class\\s+'.$classname.'\\s+extends\\s+'.$classname.'Core\\s*?[{]\\s*?[}]/ism', $code);\n }\n\n if (!isset($to_delete) || $to_delete) {\n unlink($override_path);\n } else {\n file_put_contents($override_path, $code);\n }\n\n // Re-generate the class index\n Tools::generateIndex();\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function init()\n {\n /*\n * Globals are DEPRECATED as of version 1.5.0.1\n * Use the Context object to access objects instead.\n * Example: $this->context->cart\n */\n global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;\n\n if (self::$initialized) {\n return;\n }\n\n self::$initialized = true;\n\n parent::init();\n\n // enable Symfony error handler if debug mode enabled\n $this->initDebugguer();\n\n // If current URL use SSL, set it true (used a lot for module redirect)\n if (Tools::usingSecureMode()) {\n $useSSL = true;\n }\n\n // For compatibility with globals, DEPRECATED as of version 1.5.0.1\n $css_files = $this->css_files;\n $js_files = $this->js_files;\n\n $this->sslRedirection();\n\n if ($this->ajax) {\n $this->display_header = false;\n $this->display_footer = false;\n }\n\n // If account created with the 2 steps register process, remove 'account_created' from cookie\n if (isset($this->context->cookie->account_created)) {\n unset($this->context->cookie->account_created);\n }\n\n ob_start();\n\n // Init cookie language\n // @TODO This method must be moved into switchLanguage\n Tools::setCookieLanguage($this->context->cookie);\n\n $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://';\n $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false;\n $protocol_content = ($useSSL) ? 'https://' : 'http://';\n $link = new Link($protocol_link, $protocol_content);\n $this->context->link = $link;\n\n if ($id_cart = (int) $this->recoverCart()) {\n $this->context->cookie->id_cart = (int) $id_cart;\n }\n\n if ($this->auth && !$this->context->customer->isLogged()) {\n Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));\n }\n\n /* Theme is missing */\n if (!is_dir(_PS_THEME_DIR_)) {\n throw new PrestaShopException((sprintf(Tools::displayError('Current theme unavailable \"%s\". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\\\')))));\n }\n\n if (Configuration::get('PS_GEOLOCATION_ENABLED')) {\n if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {\n $this->context->country = $new_default;\n }\n } elseif (Configuration::get('PS_DETECT_COUNTRY')) {\n $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency;\n $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;\n $has_address_type = false;\n\n if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {\n $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};\n }\n\n if ((!$has_currency || $has_country) && !$has_address_type) {\n $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ?\n (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry();\n\n $country = new Country($id_country, (int) $this->context->cookie->id_lang);\n\n if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {\n $this->context->country = $country;\n $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id;\n $this->context->cookie->iso_code_country = strtoupper($country->iso_code);\n }\n }\n }\n\n $currency = Tools::setCurrency($this->context->cookie);\n\n if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) {\n $this->context->customer->logout();\n\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n } elseif (isset($_GET['mylogout'])) {\n $this->context->customer->mylogout();\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n }\n\n /* Cart already exists */\n if ((int) $this->context->cookie->id_cart) {\n if (!isset($cart)) {\n $cart = new Cart($this->context->cookie->id_cart);\n }\n\n if (Validate::isLoadedObject($cart) && $cart->OrderExists()) {\n PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);\n $this->context->cookie->check_cgv = false;\n } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED'))\n && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))\n && $cart->nbProducts()\n && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1\n && !FrontController::isInWhitelistForGeolocation()\n && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))\n ) {\n /* Delete product of cart, if user can't make an order from his country */\n PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart);\n } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {\n // update cart values\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n }\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $currency->id;\n $cart->update();\n }\n /* Select an address if not set */\n if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||\n !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {\n $to_update = false;\n if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {\n $to_update = true;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {\n $to_update = true;\n $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if ($to_update) {\n $cart->update();\n }\n }\n }\n\n if (!isset($cart) || !$cart->id) {\n $cart = new Cart();\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $this->context->cookie->id_currency;\n $cart->id_guest = (int) $this->context->cookie->id_guest;\n $cart->id_shop_group = (int) $this->context->shop->id_shop_group;\n $cart->id_shop = $this->context->shop->id;\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n $cart->id_address_invoice = (int) $cart->id_address_delivery;\n } else {\n $cart->id_address_delivery = 0;\n $cart->id_address_invoice = 0;\n }\n\n // Needed if the merchant want to give a free product to every visitors\n $this->context->cart = $cart;\n CartRule::autoAddToCart($this->context);\n } else {\n $this->context->cart = $cart;\n }\n\n $this->context->cart->checkAndUpdateAddresses();\n\n $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));\n\n // Automatically redirect to the canonical URL if needed\n if (!empty($this->php_self) && !Tools::getValue('ajax')) {\n $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));\n }\n\n Product::initPricesComputation();\n\n $display_tax_label = $this->context->country->display_tax_label;\n if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {\n $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});\n $country = new Country((int) $infos['id_country']);\n $this->context->country = $country;\n if (Validate::isLoadedObject($country)) {\n $display_tax_label = $country->display_tax_label;\n }\n }\n\n $languages = Language::getLanguages(true, $this->context->shop->id);\n $meta_language = array();\n foreach ($languages as $lang) {\n $meta_language[] = $lang['iso_code'];\n }\n\n /*\n * These shortcuts are DEPRECATED as of version 1.5.0.1\n * Use the Context to access objects instead.\n * Example: $this->context->cart\n */\n self::$cookie = $this->context->cookie;\n self::$cart = $cart;\n self::$smarty = $this->context->smarty;\n self::$link = $link;\n $defaultCountry = $this->context->country;\n\n $this->displayMaintenancePage();\n\n if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) {\n $this->displayRestrictedCountryPage();\n }\n\n $this->iso = $iso;\n $this->context->cart = $cart;\n $this->context->currency = $currency;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function listAutoSuggest($post, $limit)\n {\n $pages = 0;\n $limitEnd = \\Application\\Plugin\\CommonPlugin::escapeLimit($limit);\n\n if (isset($GLOBALS['set_autosuggest_options'])) {\n if ($GLOBALS['set_autosuggest_options'] == 1) {\n $leading = '%';\n } else {\n $leading = $post->leading;\n }\n\n if ($GLOBALS['set_autosuggest_options'] == 2) {\n $trailing = '%';\n } else {\n $trailing = $post->trailing;\n }\n\n if ($GLOBALS['set_autosuggest_options'] == 3) {\n $leading = '%';\n $trailing = '%';\n }\n } else {\n $leading = $post->leading;\n $trailing = $post->trailing;\n }\n\n $queryString = $post->queryString;\n\n\n $page = $post->page;\n $searchType = $post->searchType;\n $searchEleNo = $post->searchEleNo;\n\n if ($page == '') {\n $limitStart = 0;\n } else {\n $limitStart = \\Application\\Plugin\\CommonPlugin::escapeLimit($page);\n }\n\n $keyword = $leading . $queryString . $trailing;\n if (strtolower($searchType) == 'patient') {\n $sql = \"SELECT fname, mname, lname, pid, DOB FROM patient_data\n WHERE pid LIKE ?\n OR CONCAT(fname, ' ', lname) LIKE ?\n OR CONCAT(lname, ' ', fname) LIKE ?\n OR DATE_FORMAT(DOB,'%m-%d-%Y') LIKE ?\n OR DATE_FORMAT(DOB,'%d-%m-%Y') LIKE ?\n OR DATE_FORMAT(DOB,'%Y-%m-%d') LIKE ?\n ORDER BY fname \";\n $result = $this->zQuery($sql, array(\n $keyword,\n $keyword,\n $keyword,\n $keyword,\n $keyword,\n $keyword\n ));\n $rowCount = $result->count();\n $sql .= \"LIMIT $limitStart, $limitEnd\";\n $result = $this->zQuery($sql, array(\n $keyword,\n $keyword,\n $keyword,\n $keyword,\n $keyword,\n $keyword,\n\n ));\n } elseif (strtolower($searchType) == 'emrdirect') {\n $sql = \"SELECT fname, mname, lname,email_direct AS 'email',id FROM users\n WHERE (CONCAT(fname, ' ', lname) LIKE ?\n OR CONCAT(lname, ' ', fname) LIKE ?\n OR email_direct LIKE ?)\n AND abook_type = 'emr_direct'\n AND active = 1\n ORDER BY fname \";\n $result = $this->zQuery($sql, array(\n $keyword,\n $keyword,\n $keyword,\n ));\n $rowCount = $result->count();\n $sql .= \"LIMIT $limitStart, $limitEnd\";\n $result = $this->zQuery($sql, array(\n $keyword,\n $keyword,\n $keyword,\n ));\n }\n\n $arr = array();\n if ($result) {\n foreach ($result as $row) {\n $arr[] = $row;\n }\n\n $arr['rowCount'] = $rowCount;\n }\n\n return $arr;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function flattenArrayIndexed($array)\n {\n if (!is_array($array)) {\n return (array) $array;\n }\n\n $arrayValues = array();\n foreach ($array as $k1 => $value) {\n if (is_array($value)) {\n foreach ($value as $k2 => $val) {\n if (is_array($val)) {\n foreach ($val as $k3 => $v) {\n $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;\n }\n } else {\n $arrayValues[$k1.'.'.$k2] = $val;\n }\n }\n } else {\n $arrayValues[$k1] = $value;\n }\n }\n\n return $arrayValues;\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function processLogin()\n {\n /* Check fields validity */\n $passwd = trim(Tools::getValue('passwd'));\n $email = trim(Tools::getValue('email'));\n if (empty($email)) {\n $this->errors[] = Tools::displayError('Email is empty.');\n } elseif (!Validate::isEmail($email)) {\n $this->errors[] = Tools::displayError('Invalid email address.');\n }\n\n if (empty($passwd)) {\n $this->errors[] = Tools::displayError('The password field is blank.');\n } elseif (!Validate::isPasswd($passwd)) {\n $this->errors[] = Tools::displayError('Invalid password.');\n }\n\n if (!count($this->errors)) {\n // Find employee\n $this->context->employee = new Employee();\n $is_employee_loaded = $this->context->employee->getByEmail($email, $passwd);\n $employee_associated_shop = $this->context->employee->getAssociatedShops();\n if (!$is_employee_loaded) {\n $this->errors[] = Tools::displayError('The Employee does not exist, or the password provided is incorrect.');\n $this->context->employee->logout();\n } elseif (empty($employee_associated_shop) && !$this->context->employee->isSuperAdmin()) {\n $this->errors[] = Tools::displayError('This employee does not manage the shop anymore (Either the shop has been deleted or permissions have been revoked).');\n $this->context->employee->logout();\n } else {\n PrestaShopLogger::addLog(sprintf($this->l('Back Office connection from %s', 'AdminTab', false, false), Tools::getRemoteAddr()), 1, null, '', 0, true, (int)$this->context->employee->id);\n\n $this->context->employee->remote_addr = (int)ip2long(Tools::getRemoteAddr());\n // Update cookie\n $cookie = Context::getContext()->cookie;\n $cookie->id_employee = $this->context->employee->id;\n $cookie->email = $this->context->employee->email;\n $cookie->profile = $this->context->employee->id_profile;\n $cookie->passwd = $this->context->employee->passwd;\n $cookie->remote_addr = $this->context->employee->remote_addr;\n\n if (!Tools::getValue('stay_logged_in')) {\n $cookie->last_activity = time();\n }\n\n $cookie->write();\n\n // If there is a valid controller name submitted, redirect to it\n if (isset($_POST['redirect']) && Validate::isControllerName($_POST['redirect'])) {\n $url = $this->context->link->getAdminLink($_POST['redirect']);\n } else {\n $tab = new Tab((int)$this->context->employee->default_tab);\n $url = $this->context->link->getAdminLink($tab->class_name);\n }\n\n if (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(array('hasErrors' => false, 'redirect' => $url)));\n } else {\n $this->redirect_after = $url;\n }\n }\n }\n if (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function decodePortalOneTime($onetime_token, $redirect_token = null): array\n {\n $auth = false;\n $rtn = [];\n $rtn['pid'] = 0;\n $rtn['pin'] = null;\n $rtn['redirect'] = null;\n $rtn['error'] = null;\n $one_time = '';\n $t_info = [];\n\n if (strlen($onetime_token) >= 64) {\n if ($this->cryptoGen->cryptCheckStandard($onetime_token)) {\n $one_time = $this->cryptoGen->decryptStandard($onetime_token, null, 'drive', 6);\n if (!empty($one_time)) {\n $t_info = $this->getOnetime($one_time);\n if (!empty($t_info['pid'] ?? 0)) {\n $auth = sqlQueryNoLog(\"Select * From patient_access_onsite Where `pid` = ?\", array($t_info['pid']));\n }\n } else {\n $this->systemLogger->error(\"Onetime decrypt token failed. Empty!\");\n }\n }\n } else {\n $this->systemLogger->error(\"Onetime token invalid length.\");\n }\n if (!$auth) {\n $rtn['error'] = \"Onetime decode failed Onetime auth: \" . $onetime_token;\n $this->systemLogger->error($rtn['error']);\n throw new OneTimeAuthException($rtn['error']);\n }\n\n $validate = $t_info['expires'];\n if ($validate <= time()) {\n $rtn['error'] = xlt(\"Your one time credential reset link has expired. Reset and try again.\") . \"time:$validate time:\" . time();\n $this->systemLogger->error($rtn['error']);\n throw new OneTimeAuthExpiredException($rtn['error'], $auth['pid']);\n }\n // We'll rely on the stored redirect address as default.\n // However, leave the option of using embedded encrypted redirect.\n $redirect = $t_info['redirect_url'] ?? null;\n if (!empty($redirect_token)) {\n if ($this->cryptoGen->cryptCheckStandard($redirect_token)) {\n $redirect_decrypted = $this->cryptoGen->decryptStandard($redirect_token, null, 'drive', 6);\n $redirect_array = json_decode($redirect_decrypted, true);\n $redirect = $redirect_array['to'];\n if (($redirect_array['pid'] != $auth['pid'] && !empty($redirect_array['pid']))) {\n throw new OneTimeAuthException(xlt(\"Error! credentials pid to and from don't match!\"), $auth['pid']);\n }\n $this->systemLogger->debug(\"Redirect token decrypted: pid = \" . $redirect_array['pid'] . \" redirect = \" . $redirect);\n }\n }\n $rtn['pid'] = $auth['pid'];\n $rtn['pin'] = $t_info['onetime_pin'];\n $rtn['redirect'] = $redirect;\n $rtn['username'] = $auth['portal_username'];\n $rtn['login_username'] = $auth['portal_login_username'];\n $rtn['portal_pwd'] = $auth['portal_pwd'];\n $rtn['onetime_decrypted'] = $one_time;\n\n $this->updateOnetime($auth['pid'], $one_time);\n $this->systemLogger->debug(\"Onetime successfully decoded. $one_time\");\n\n return $rtn;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function recordTemplateByRecTypeID($system, $id){\n\n $record = array(\n 'rec_ID'=>'RECORD-IDENTIFIER',\n 'rec_RecTypeID'=>$id,\n 'rec_Title'=>'',\n 'rec_URL'=>'URL',\n 'rec_ScratchPad'=>'',\n 'rec_OwnerUGrpID'=>2,\n 'rec_NonOwnerVisibility'=>'public',\n 'rec_URLLastVerified'=>'',\n 'rec_URLErrorMessage'=>'',\n 'rec_AddedByUGrpID'=>2);\n\n $mysqli = $system->get_mysqli();\n $fields = mysql__select_assoc($mysqli, 'select dty_ID, dty_Type, dty_JsonTermIDTree, dty_PtrTargetRectypeIDs '\n .'from defRecStructure, defDetailTypes where dty_ID = rst_DetailTypeID '\n .'and rst_RecTypeID = '.$id);\n\n $details = array();\n $idx = 1;\n\n foreach ($fields as $dty_ID=>$fieldDetails){\n\n $dty_Type = $fieldDetails['dty_Type'];\n\n if($dty_Type=='separator') {continue;}\n\n\n if($dty_Type=='file'){\n $details[$dty_ID] = array($idx=>array('file'=>array('file'=>'TEXT', 'fileid'=>'TEXT')) );\n\n }elseif($dty_Type=='resource'){\n\n $extra_details = '';\n if(array_key_exists('dty_PtrTargetRectypeIDs', $fieldDetails)){ // retrieve list of rectype names\n\n $rty_names = mysql__select_list2($mysqli, 'SELECT rty_Name FROM defRecTypes WHERE rty_ID IN (' . $fieldDetails['dty_PtrTargetRectypeIDs'] .')');\n if(!empty($rty_names)){\n $extra_details = ' to ' . implode(' | ', $rty_names);\n }\n }\n\n $details[$dty_ID] = array($idx=>array('id'=>'RECORD_REFERENCE'.$extra_details, 'type'=>0, 'title'=>''));\n }elseif($dty_Type=='relmarker'){\n\n $extra_details = '';\n if(array_key_exists('dty_JsonTermIDTree', $fieldDetails)){ // retrieve list of vocab labels\n $trm_names = mysql__select_list2($mysqli, 'SELECT trm_Label FROM defTerms WHERE trm_ID IN ('. $fieldDetails['dty_JsonTermIDTree'] .')');\n if(!empty($trm_names)){\n $extra_details = ', ' . implode(' | ', $trm_names) . ' relation to ';\n }\n }\n if(array_key_exists('dty_PtrTargetRectypeIDs', $fieldDetails)){ // retrieve list of rectype names\n $rty_names = mysql__select_list2($mysqli, 'SELECT rty_Name FROM defRecTypes WHERE rty_ID IN ('. $fieldDetails['dty_PtrTargetRectypeIDs'] .')');\n if(!empty($rty_names)){\n if(empty($extra_details)){\n $extra_details = ', relation to ';\n }\n $extra_details .= implode(' | ', $rty_names);\n }\n }\n\n $details[$dty_ID] = array($idx=>'SEE NOTES AT START'.$extra_details);\n }elseif($dty_Type=='geo'){\n $details[$dty_ID] = array($idx=>array('geo'=>array('wkt'=>'WKT_VALUE')) );//'type'=>'TEXT',\n\n }elseif($dty_Type=='enum' || $dty_Type=='relationtype'){\n\n $extra_details = '';\n if(array_key_exists('dty_JsonTermIDTree', $fieldDetails)){ // retrieve list of vocab labels\n $trm_names = mysql__select_list2($mysqli, 'SELECT trm_Label FROM defTerms WHERE trm_ID IN ('. $fieldDetails['dty_JsonTermIDTree'] .')');\n if(!empty($trm_names)){\n $extra_details = ' from ' . implode(' | ', $trm_names);\n }\n }\n\n $details[$dty_ID] = array($idx=>'VALUE'.$extra_details);\n }elseif($dty_Type=='integer' || $dty_Type=='float' || $dty_Type=='year' ){\n $details[$dty_ID] = array($idx=>'NUMERIC');\n }elseif($dty_Type=='blocktext' ){\n $details[$dty_ID] = array($idx=>'MEMO_TEXT');\n }elseif($dty_Type=='date' ){\n $details[$dty_ID] = array($idx=>'DATE');\n }else{\n $details[$dty_ID] = array($idx=>'TEXT');\n }\n\n $idx++;\n }\n $record['details'] = $details;\n\n return $record;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function applyRightRules()\n {\n\n $return = false;\n\n if (\n $this->must_process_ruleright === true\n ) {\n $dynamic_profiles = Profile_User::getForUser($this->fields[\"id\"], true);\n\n if (\n isset($this->fields[\"id\"])\n && ($this->fields[\"id\"] > 0)\n && isset($this->input[\"_ldap_rules\"])\n && count($this->input[\"_ldap_rules\"])\n ) {\n //and add/update/delete only if it's necessary !\n if (isset($this->input[\"_ldap_rules\"][\"rules_entities_rights\"])) {\n $entities_rules = $this->input[\"_ldap_rules\"][\"rules_entities_rights\"];\n } else {\n $entities_rules = [];\n }\n\n if (isset($this->input[\"_ldap_rules\"][\"rules_entities\"])) {\n $entities = $this->input[\"_ldap_rules\"][\"rules_entities\"];\n } else {\n $entities = [];\n }\n\n if (isset($this->input[\"_ldap_rules\"][\"rules_rights\"])) {\n $rights = $this->input[\"_ldap_rules\"][\"rules_rights\"];\n } else {\n $rights = [];\n }\n\n $retrieved_dynamic_profiles = [];\n\n //For each affectation -> write it in DB\n foreach ($entities_rules as $entity) {\n //Multiple entities assignation\n if (is_array($entity[0])) {\n foreach ($entity[0] as $ent) {\n $unicity = $ent . \"-\" . $entity[1] . \"-\" . $entity[2];\n $retrieved_dynamic_profiles[$unicity] = [\n 'entities_id' => $ent,\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n } else {\n $unicity = $entity[0] . \"-\" . $entity[1] . \"-\" . $entity[2];\n $retrieved_dynamic_profiles[$unicity] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }\n\n if (\n (count($entities) > 0)\n && (count($rights) == 0)\n ) {\n if ($def_prof = Profile::getDefault()) {\n $rights[] = $def_prof;\n }\n }\n\n if (\n (count($rights) > 0)\n && (count($entities) > 0)\n ) {\n foreach ($rights as $right) {\n foreach ($entities as $entity) {\n $unicity = $entity[0] . \"-\" . $right . \"-\" . $entity[1];\n $retrieved_dynamic_profiles[$unicity] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $right,\n 'is_recursive' => $entity[1],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }\n }\n\n // Compare retrived profiles to existing ones : clean arrays to do purge and add\n if (count($retrieved_dynamic_profiles)) {\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n foreach ($dynamic_profiles as $keydb => $db_profile) {\n // Found existing profile : unset values in array\n if (\n ($db_profile['entities_id'] == $retr_profile['entities_id'])\n && ($db_profile['profiles_id'] == $retr_profile['profiles_id'])\n && ($db_profile['is_recursive'] == $retr_profile['is_recursive'])\n ) {\n unset($retrieved_dynamic_profiles[$keyretr]);\n unset($dynamic_profiles[$keydb]);\n }\n }\n }\n }\n\n // Add new dynamic profiles\n if (count($retrieved_dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n $right->add($retr_profile);\n }\n }\n\n //Unset all the temporary tables\n unset($this->input[\"_ldap_rules\"]);\n\n $return = true;\n } else if (count($dynamic_profiles) == 1) {\n $dynamic_profile = reset($dynamic_profiles);\n\n // If no rule applied and only one dynamic profile found, check if\n // it is the default profile\n if ($dynamic_profile['is_default_profile'] == true) {\n $default_profile = Profile::getDefault();\n\n // Remove from to be deleted list\n $dynamic_profiles = [];\n\n // Update profile if need to match the current default profile\n if ($dynamic_profile['profiles_id'] !== $default_profile) {\n $pu = new Profile_User();\n $dynamic_profile['profiles_id'] = $default_profile;\n $pu->add($dynamic_profile);\n $pu->delete([\n 'id' => $dynamic_profile['id']\n ]);\n }\n }\n }\n\n // Delete old dynamic profiles\n if (count($dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($dynamic_profiles as $keydb => $db_profile) {\n $right->delete($db_profile);\n }\n }\n $this->must_process_ruleright = false;\n }\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function getHintText(array $hints, string $hintlabel)\n {\n $qdata = $this->questionParams->getQuestionData();\n $attemptn = $this->questionParams->getStudentAttemptNumber();\n $scoreiscorrect = $this->questionParams->getScoreIsCorrect();\n\n $thisq = $this->questionParams->getQuestionNumber() + 1;\n\n $hintloc = '';\n\n $lastkey = max(array_keys($hints));\n\n if ($qdata['qtype'] == \"multipart\" && is_array($hints[$lastkey])) { //individual part hints\n $hintloc = array();\n $partattemptn = $this->questionParams->getStudentPartAttemptCount();\n\n foreach ($hints as $iidx => $hintpart) {\n if (!is_array($hintpart)) { continue; } // mixed formats\n $lastkey = max(array_keys($hintpart));\n $hintloc[$iidx] = '';\n if (is_array($hintpart[$lastkey])) { // has \"show for group of questions\"\n $usenum = 10000;\n $allcorrect = true;\n $maxatt = 0;\n $showfor = array_map('intval', $hintpart[$lastkey][1]);\n foreach ($showfor as $subpn) {\n if (!isset($partattemptn[$subpn])) {\n $partattemptn[$subpn] = 0;\n }\n if (isset($scoreiscorrect[$thisq][$subpn]) && $scoreiscorrect[$thisq][$subpn] == 1) {\n continue; // don't consider correct\n } else {\n $allcorrect = false;\n }\n if ($partattemptn[$subpn] > $lastkey && $lastkey < $usenum) {\n $usenum = $lastkey;\n } else if ($partattemptn[$subpn] < $usenum) {\n $usenum = $partattemptn[$subpn];\n }\n }\n if ($allcorrect) {\n $maxatt = min($partattemptn)-1;\n if ($maxatt > $lastkey) {\n $usenum = $lastkey;\n } else {\n $usenum = max($maxatt,0);\n }\n }\n if ($usenum == 10000) { \n continue;\n }\n if (!empty($hintpart[$usenum]) && is_array($hintpart[$usenum])) {\n $hintpart[$usenum] = $hintpart[$usenum][0];\n }\n } else {\n if (!isset($partattemptn[$iidx])) {\n $partattemptn[$iidx] = 0;\n }\n if ($partattemptn[$iidx] > $lastkey) {\n $usenum = $lastkey;\n } else {\n $usenum = $partattemptn[$iidx];\n if (!empty($scoreiscorrect[$thisq][$iidx]) && $scoreiscorrect[$thisq][$iidx]==1) {\n $usenum--;\n }\n }\n }\n if (!empty($hintpart[$usenum])) {\n if (strpos($hintpart[$usenum], '</div>') !== false) {\n $hintloc[$iidx] = $hintpart[$usenum];\n } else if (strpos($hintpart[$usenum], 'button\"') !== false) {\n $hintloc[$iidx] = \"<p>{$hintpart[$usenum]}</p>\\n\";\n } else if (!empty($hintlabel)) {\n $hintloc[$iidx] = \"<p>$hintlabel {$hintpart[$usenum]}</p>\\n\";\n } else {\n $hintloc[$iidx] = \"<p><i>\" . _('Hint:') . \"</i> {$hintpart[$usenum]}</p>\\n\";\n }\n }\n }\n } else { //one hint for question\n if ($attemptn > $lastkey) {\n $usenum = $lastkey;\n } else {\n $usenum = $attemptn;\n if (isset($scoreiscorrect) && ( \n (!is_array($scoreiscorrect[$thisq]) && $scoreiscorrect[$thisq] == 1) ||\n (is_array($scoreiscorrect[$thisq]) && min($scoreiscorrect[$thisq]) == 1)\n )) {\n $usenum--; // if correct, use prior hint\n }\n }\n \n if (!empty($hints[$usenum])) {\n if (!is_string($hints[$usenum])) { // shouldn't be, but a hack to get old bad code from throwing errors.\n $hintloc = $hints[$usenum]; \n } else if (strpos($hints[$usenum], '</div>') !== false) {\n $hintloc = $hints[$usenum];\n } else if (strpos($hints[$usenum], 'button\"') !== false) {\n $hintloc = \"<p>{$hints[$usenum]}</p>\\n\";\n } else if (!empty($hintlabel)) {\n $hintloc = \"<p>$hintlabel {$hints[$usenum]}</p>\\n\";\n } else {\n $hintloc = \"<p><i>\" . _('Hint:') . \"</i> {$hints[$usenum]}</p>\\n\";\n }\n }\n }\n return $hintloc;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function manageParams($itemtype, $params = [], $usesession = true, $forcebookmark = false): array\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $default_values = [];\n\n $default_values[\"start\"] = 0;\n $default_values[\"order\"] = \"ASC\";\n if (\n (\n empty($params['criteria'] ?? []) // No search criteria\n || $params['criteria'] == self::getDefaultCriteria($itemtype) // Default criteria\n )\n && ( // Is an asset\n in_array($itemtype, $CFG_GLPI['asset_types'])\n || $itemtype == AllAssets::getType()\n )\n ) {\n // Disable sort on assets default search request\n // This improve significantly performances on default search queries without much functional costs as users\n // often don't care about the default search results\n $default_values[\"sort\"] = 0;\n // Defining \"sort\" to 0 is no enough as the search engine will default to sorting on the `id` column.\n // Sorting by id still has a high performance cost on heavy requests, thus we must explicitly request\n // that no ORDER BY clause will be set\n $default_values[\"disable_order_by_fallback\"] = true;\n } else {\n // Search engine will automatically determine the best sorting column (ID or the first displayed column)\n $default_values[\"sort\"] = 0;\n }\n $default_values[\"is_deleted\"] = 0;\n $default_values[\"as_map\"] = 0;\n $default_values[\"browse\"] = $itemtype::$browse_default ?? 0;\n $default_values[\"unpublished\"] = 1;\n\n if (isset($params['start'])) {\n $params['start'] = (int)$params['start'];\n }\n\n $default_values[\"criteria\"] = self::getDefaultCriteria($itemtype);\n $default_values[\"metacriteria\"] = [];\n\n // Reorg search array\n // start\n // order\n // sort\n // is_deleted\n // itemtype\n // criteria : array (0 => array (link =>\n // field =>\n // searchtype =>\n // value => (contains)\n // metacriteria : array (0 => array (itemtype =>\n // link =>\n // field =>\n // searchtype =>\n // value => (contains)\n\n if ($itemtype != \\AllAssets::getType() && class_exists($itemtype)) {\n // retrieve default values for current itemtype\n $itemtype_default_values = [];\n if (method_exists($itemtype, 'getDefaultSearchRequest')) {\n $itemtype_default_values = call_user_func([$itemtype, 'getDefaultSearchRequest']);\n }\n\n // retrieve default values for the current user\n $user_default_values = \\SavedSearch_User::getDefault(\\Session::getLoginUserID(), $itemtype);\n if ($user_default_values === false) {\n $user_default_values = [];\n }\n\n // we construct default values in this order:\n // - general default\n // - itemtype default\n // - user default\n //\n // The last ones erase values or previous\n // So, we can combine each part (order from itemtype, criteria from user, etc)\n $default_values = array_merge(\n $default_values,\n $itemtype_default_values,\n $user_default_values\n );\n }\n\n // First view of the page or force bookmark : try to load a bookmark\n if (\n $forcebookmark\n || ($usesession\n && !isset($params[\"reset\"])\n && !isset($_SESSION['glpisearch'][$itemtype]))\n ) {\n $user_default_values = \\SavedSearch_User::getDefault(\\Session::getLoginUserID(), $itemtype);\n if ($user_default_values) {\n $_SESSION['glpisearch'][$itemtype] = [];\n // Only get data for bookmarks\n if ($forcebookmark) {\n $params = $user_default_values;\n } else {\n $bookmark = new \\SavedSearch();\n $bookmark->load($user_default_values['savedsearches_id']);\n }\n }\n }\n // Force reorder criterias\n if (\n isset($params[\"criteria\"])\n && is_array($params[\"criteria\"])\n && count($params[\"criteria\"])\n ) {\n $tmp = $params[\"criteria\"];\n $params[\"criteria\"] = [];\n foreach ($tmp as $val) {\n $params[\"criteria\"][] = $val;\n }\n }\n\n // transform legacy meta-criteria in criteria (with flag meta=true)\n // at the end of the array, as before there was only at the end of the query\n if (\n isset($params[\"metacriteria\"])\n && is_array($params[\"metacriteria\"])\n ) {\n // as we will append meta to criteria, check the key exists\n if (!isset($params[\"criteria\"])) {\n $params[\"criteria\"] = [];\n }\n foreach ($params[\"metacriteria\"] as $val) {\n $params[\"criteria\"][] = $val + ['meta' => 1];\n }\n $params[\"metacriteria\"] = [];\n }\n\n if (\n $usesession\n && isset($params[\"reset\"])\n ) {\n if (isset($_SESSION['glpisearch'][$itemtype])) {\n unset($_SESSION['glpisearch'][$itemtype]);\n }\n\n // if we ask for reset but without precising particular bookmark\n // then remove current active bookmark\n if (!isset($params['savedsearches_id'])) {\n unset($_SESSION['glpi_loaded_savedsearch']);\n }\n }\n\n if (\n is_array($params)\n && $usesession\n ) {\n foreach ($params as $key => $val) {\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }\n\n $saved_params = $params;\n foreach ($default_values as $key => $val) {\n if (!isset($params[$key])) {\n if (\n $usesession\n && ($key == 'is_deleted' || $key == 'as_map' || $key == 'browse' || $key === 'unpublished' || !isset($saved_params['criteria'])) // retrieve session only if not a new request\n && isset($_SESSION['glpisearch'][$itemtype][$key])\n ) {\n $params[$key] = $_SESSION['glpisearch'][$itemtype][$key];\n } else {\n $params[$key] = $val;\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }\n }\n\n if ($defaultfilter = \\DefaultFilter::getSearchCriteria($itemtype)) {\n $params['defaultfilter'] = $defaultfilter;\n $can_disablefilter = \\Session::haveRightsOr('search_config', [\\DisplayPreference::PERSONAL, \\DisplayPreference::GENERAL]);\n if (!isset($params['nodefault']) || !$can_disablefilter) {\n $defaultfilter['search_criteria']['_hidden'] = true;\n $params['criteria'][] = $defaultfilter['search_criteria'];\n }\n }\n return self::cleanParams($params);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function fetchThumbnailConfigs(InputInterface $input, string $thumbnailConfigName): array\n {\n /** @var Image\\Thumbnail\\Config $thumbnailConfig */\n $thumbnailConfig = Image\\Thumbnail\\Config::getByName($thumbnailConfigName);\n $thumbnailsToGenerate = [$thumbnailConfig];\n\n $medias = array_merge(['default' => 'defaultMedia'], $thumbnailConfig->getMedias() ?: []);\n foreach ($medias as $mediaName => $media) {\n $configMedia = clone $thumbnailConfig;\n if ($mediaName !== 'default') {\n $configMedia->selectMedia($mediaName);\n }\n\n if ($input->getOption('skip-medias') && $mediaName !== 'default') {\n continue;\n }\n\n $resolutions = [1, 2];\n if ($input->getOption('skip-high-res')) {\n $resolutions = [1];\n }\n\n foreach ($resolutions as $resolution) {\n $resConfig = clone $configMedia;\n $resConfig->setHighResolution($resolution);\n $thumbnailsToGenerate[] = $resConfig;\n\n if ($resConfig->getFormat() === 'SOURCE') {\n foreach ($resConfig->getAutoFormatThumbnailConfigs() as $autoFormat => $autoFormatThumbnailConfig) {\n if (!$input->getOption('skip-' . $autoFormat)) {\n $thumbnailsToGenerate[] = $autoFormatThumbnailConfig;\n }\n }\n }\n }\n }\n\n return $thumbnailsToGenerate;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function dropdownAllDevices(\n $myname,\n $itemtype,\n $items_id = 0,\n $admin = 0,\n $users_id = 0,\n $entity_restrict = -1,\n $options = []\n ) {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $params = [static::$items_id_1 => 0,\n 'used' => [],\n 'multiple' => 0,\n 'rand' => mt_rand()\n ];\n\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n\n $rand = $params['rand'];\n\n if ($_SESSION[\"glpiactiveprofile\"][\"helpdesk_hardware\"] == 0) {\n echo \"<input type='hidden' name='\" . htmlescape($myname) . \"' value=''>\";\n echo \"<input type='hidden' name='items_id' value='0'>\";\n } else {\n echo \"<div id='tracking_all_devices$rand' class='input-group mb-1'>\";\n // KEEP Ticket::HELPDESK_ALL_HARDWARE because it is only define on ticket level\n if (\n $_SESSION[\"glpiactiveprofile\"][\"helpdesk_hardware\"] & pow(\n 2,\n Ticket::HELPDESK_ALL_HARDWARE\n )\n ) {\n // Display a message if view my hardware\n if (\n $users_id\n && ($_SESSION[\"glpiactiveprofile\"][\"helpdesk_hardware\"] & pow(\n 2,\n Ticket::HELPDESK_MY_HARDWARE\n ))\n ) {\n echo \"<span class='input-group-text'>\" . __s('Or complete search') . \"</span>\";\n }\n\n $types = static::$itemtype_1::getAllTypesForHelpdesk();\n $types = array_filter($types, static fn ($k) => $k::canView(), ARRAY_FILTER_USE_KEY);\n $emptylabel = __('General');\n if ($params[static::$items_id_1] > 0) {\n $emptylabel = Dropdown::EMPTY_VALUE;\n }\n Dropdown::showItemTypes(\n $myname,\n array_keys($types),\n [\n 'emptylabel' => $emptylabel,\n 'value' => $itemtype,\n 'rand' => $rand,\n 'display_emptychoice' => true\n ]\n );\n $found_type = isset($types[$itemtype]);\n\n $p = [\n 'source_itemtype' => static::$itemtype_1,\n 'itemtype' => '__VALUE__',\n 'entity_restrict' => $entity_restrict,\n 'admin' => $admin,\n 'used' => $params['used'],\n 'multiple' => $params['multiple'],\n 'rand' => $rand,\n 'myname' => \"add_items_id\"\n ];\n\n if (isset($params['width'])) {\n $p['width'] = $params['width'];\n }\n\n Ajax::updateItemOnSelectEvent(\n Html::cleanId(\"dropdown_$myname$rand\"),\n Html::cleanId(\"results_$myname$rand\"),\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownTrackingDeviceType.php\",\n $p\n );\n echo \"<span id='\" . Html::cleanId(\"results_\" . htmlescape($myname) . \"$rand\") . \"'>\\n\";\n\n // Display default value if itemtype is displayed\n if (\n $found_type\n && $itemtype\n ) {\n if (\n ($item = getItemForItemtype($itemtype))\n && $items_id\n ) {\n if ($item->getFromDB($items_id)) {\n Dropdown::showFromArray(\n 'items_id',\n [$items_id => $item->getName()],\n ['value' => $items_id]\n );\n }\n } else {\n $p['source_itemtype'] = static::$itemtype_1;\n $p['itemtype'] = $itemtype;\n echo \"<script type='text/javascript' >\\n\";\n echo \"$(function() {\";\n Ajax::updateItemJsCode(\n \"results_\" . htmlescape($myname) . \"$rand\",\n $CFG_GLPI[\"root_doc\"] .\n \"/ajax/dropdownTrackingDeviceType.php\",\n $p\n );\n echo '});</script>';\n }\n }\n echo \"</span>\\n\";\n }\n echo \"</div>\";\n }\n return $rand;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function init()\n {\n /**\n * Globals are DEPRECATED as of version 1.5.0.1\n * Use the Context object to access objects instead.\n * Example: $this->context->cart\n */\n global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;\n\n if (self::$initialized) {\n return;\n }\n\n self::$initialized = true;\n\n parent::init();\n\n // If current URL use SSL, set it true (used a lot for module redirect)\n if (Tools::usingSecureMode()) {\n $useSSL = true;\n }\n\n // For compatibility with globals, DEPRECATED as of version 1.5.0.1\n $css_files = $this->css_files;\n $js_files = $this->js_files;\n\n $this->sslRedirection();\n\n if ($this->ajax) {\n $this->display_header = false;\n $this->display_footer = false;\n }\n\n // If account created with the 2 steps register process, remove 'account_created' from cookie\n if (isset($this->context->cookie->account_created)) {\n $this->context->smarty->assign('account_created', 1);\n unset($this->context->cookie->account_created);\n }\n\n ob_start();\n\n // Init cookie language\n // @TODO This method must be moved into switchLanguage\n Tools::setCookieLanguage($this->context->cookie);\n\n $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://';\n $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false;\n $protocol_content = ($useSSL) ? 'https://' : 'http://';\n $link = new Link($protocol_link, $protocol_content);\n $this->context->link = $link;\n\n if ($id_cart = (int)$this->recoverCart()) {\n $this->context->cookie->id_cart = (int)$id_cart;\n }\n\n if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) {\n Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));\n }\n\n /* Theme is missing */\n if (!is_dir(_PS_THEME_DIR_)) {\n throw new PrestaShopException((sprintf(Tools::displayError('Current theme unavailable \"%s\". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\\\')))));\n }\n\n if (Configuration::get('PS_GEOLOCATION_ENABLED')) {\n if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {\n $this->context->country = $new_default;\n }\n } elseif (Configuration::get('PS_DETECT_COUNTRY')) {\n $has_currency = isset($this->context->cookie->id_currency) && (int)$this->context->cookie->id_currency;\n $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;\n $has_address_type = false;\n\n if ((int)$this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {\n $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};\n }\n\n if ((!$has_currency || $has_country) && !$has_address_type) {\n $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ?\n (int)Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int)Tools::getCountry();\n\n $country = new Country($id_country, (int)$this->context->cookie->id_lang);\n\n if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {\n $this->context->country = $country;\n $this->context->cookie->id_currency = (int)Currency::getCurrencyInstance($country->id_currency ? (int)$country->id_currency : (int)Configuration::get('PS_CURRENCY_DEFAULT'))->id;\n $this->context->cookie->iso_code_country = strtoupper($country->iso_code);\n }\n }\n }\n\n $currency = Tools::setCurrency($this->context->cookie);\n\n if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) {\n $this->context->customer->logout();\n\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n } elseif (isset($_GET['mylogout'])) {\n $this->context->customer->mylogout();\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n }\n\n /* Cart already exists */\n if ((int)$this->context->cookie->id_cart) {\n if (!isset($cart)) {\n $cart = new Cart($this->context->cookie->id_cart);\n }\n\n if (Validate::isLoadedObject($cart) && $cart->OrderExists()) {\n PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int)$this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);\n $this->context->cookie->check_cgv = false;\n }\n /* Delete product of cart, if user can't make an order from his country */\n elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) &&\n !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) &&\n $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 &&\n !FrontController::isInWhitelistForGeolocation() &&\n !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {\n PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int)$this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart);\n }\n // update cart values\n elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int)$this->context->cookie->id_customer;\n }\n $cart->id_lang = (int)$this->context->cookie->id_lang;\n $cart->id_currency = (int)$currency->id;\n $cart->update();\n }\n /* Select an address if not set */\n if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||\n !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {\n $to_update = false;\n if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {\n $to_update = true;\n $cart->id_address_delivery = (int)Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {\n $to_update = true;\n $cart->id_address_invoice = (int)Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if ($to_update) {\n $cart->update();\n }\n }\n }\n\n if (!isset($cart) || !$cart->id) {\n $cart = new Cart();\n $cart->id_lang = (int)$this->context->cookie->id_lang;\n $cart->id_currency = (int)$this->context->cookie->id_currency;\n $cart->id_guest = (int)$this->context->cookie->id_guest;\n $cart->id_shop_group = (int)$this->context->shop->id_shop_group;\n $cart->id_shop = $this->context->shop->id;\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int)$this->context->cookie->id_customer;\n $cart->id_address_delivery = (int)Address::getFirstCustomerAddressId($cart->id_customer);\n $cart->id_address_invoice = (int)$cart->id_address_delivery;\n } else {\n $cart->id_address_delivery = 0;\n $cart->id_address_invoice = 0;\n }\n\n // Needed if the merchant want to give a free product to every visitors\n $this->context->cart = $cart;\n CartRule::autoAddToCart($this->context);\n } else {\n $this->context->cart = $cart;\n }\n\n /* get page name to display it in body id */\n\n // Are we in a payment module\n $module_name = '';\n if (Validate::isModuleName(Tools::getValue('module'))) {\n $module_name = Tools::getValue('module');\n }\n\n if (!empty($this->page_name)) {\n $page_name = $this->page_name;\n } elseif (!empty($this->php_self)) {\n $page_name = $this->php_self;\n } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && (Module::getInstanceByName($module_name) instanceof PaymentModule)) {\n $page_name = 'module-payment-submit';\n }\n // @retrocompatibility Are we in a module ?\n elseif (preg_match('#^'.preg_quote($this->context->shop->physical_uri, '#').'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {\n $page_name = 'module-'.$m[1].'-'.str_replace(array('.php', '/'), array('', '-'), $m[2]);\n } else {\n $page_name = Dispatcher::getInstance()->getController();\n $page_name = (preg_match('/^[0-9]/', $page_name) ? 'page_'.$page_name : $page_name);\n }\n\n $this->context->smarty->assign(Meta::getMetaTags($this->context->language->id, $page_name));\n $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));\n\n /* Breadcrumb */\n $navigation_pipe = (Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>');\n $this->context->smarty->assign('navigationPipe', $navigation_pipe);\n\n // Automatically redirect to the canonical URL if needed\n if (!empty($this->php_self) && !Tools::getValue('ajax')) {\n $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));\n }\n\n Product::initPricesComputation();\n\n $display_tax_label = $this->context->country->display_tax_label;\n if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {\n $infos = Address::getCountryAndState((int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});\n $country = new Country((int)$infos['id_country']);\n $this->context->country = $country;\n if (Validate::isLoadedObject($country)) {\n $display_tax_label = $country->display_tax_label;\n }\n }\n\n $languages = Language::getLanguages(true, $this->context->shop->id);\n $meta_language = array();\n foreach ($languages as $lang) {\n $meta_language[] = $lang['iso_code'];\n }\n\n $compared_products = array();\n if (Configuration::get('PS_COMPARATOR_MAX_ITEM') && isset($this->context->cookie->id_compare)) {\n $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);\n }\n\n $this->context->smarty->assign(array(\n // Useful for layout.tpl\n 'mobile_device' => $this->context->getMobileDevice(),\n 'link' => $link,\n 'cart' => $cart,\n 'currency' => $currency,\n 'currencyRate' => (float)$currency->getConversationRate(),\n 'cookie' => $this->context->cookie,\n 'page_name' => $page_name,\n 'hide_left_column' => !$this->display_column_left,\n 'hide_right_column' => !$this->display_column_right,\n 'base_dir' => _PS_BASE_URL_.__PS_BASE_URI__,\n 'base_dir_ssl' => $protocol_link.Tools::getShopDomainSsl().__PS_BASE_URI__,\n 'force_ssl' => Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE'),\n 'content_dir' => $protocol_content.Tools::getHttpHost().__PS_BASE_URI__,\n 'base_uri' => $protocol_content.Tools::getHttpHost().__PS_BASE_URI__.(!Configuration::get('PS_REWRITING_SETTINGS') ? 'index.php' : ''),\n 'tpl_dir' => _PS_THEME_DIR_,\n 'tpl_uri' => _THEME_DIR_,\n 'modules_dir' => _MODULE_DIR_,\n 'mail_dir' => _MAIL_DIR_,\n 'lang_iso' => $this->context->language->iso_code,\n 'lang_id' => (int)$this->context->language->id,\n 'language_code' => $this->context->language->language_code ? $this->context->language->language_code : $this->context->language->iso_code,\n 'come_from' => Tools::getHttpHost(true, true).Tools::htmlentitiesUTF8(str_replace(array('\\'', '\\\\'), '', urldecode($_SERVER['REQUEST_URI']))),\n 'cart_qties' => (int)$cart->nbProducts(),\n 'currencies' => Currency::getCurrencies(),\n 'languages' => $languages,\n 'meta_language' => implode(',', $meta_language),\n 'priceDisplay' => Product::getTaxCalculationMethod((int)$this->context->cookie->id_customer),\n 'is_logged' => (bool)$this->context->customer->isLogged(),\n 'is_guest' => (bool)$this->context->customer->isGuest(),\n 'add_prod_display' => (int)Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),\n 'shop_name' => Configuration::get('PS_SHOP_NAME'),\n 'roundMode' => (int)Configuration::get('PS_PRICE_ROUND_MODE'),\n 'use_taxes' => (int)Configuration::get('PS_TAX'),\n 'show_taxes' => (int)(Configuration::get('PS_TAX_DISPLAY') == 1 && (int)Configuration::get('PS_TAX')),\n 'display_tax_label' => (bool)$display_tax_label,\n 'vat_management' => (int)Configuration::get('VATNUMBER_MANAGEMENT'),\n 'opc' => (bool)Configuration::get('PS_ORDER_PROCESS_TYPE'),\n 'PS_CATALOG_MODE' => (bool)Configuration::get('PS_CATALOG_MODE') || (Group::isFeatureActive() && !(bool)Group::getCurrent()->show_prices),\n 'b2b_enable' => (bool)Configuration::get('PS_B2B_ENABLE'),\n 'request' => $link->getPaginationLink(false, false, false, true),\n 'PS_STOCK_MANAGEMENT' => Configuration::get('PS_STOCK_MANAGEMENT'),\n 'quick_view' => (bool)Configuration::get('PS_QUICK_VIEW'),\n 'shop_phone' => Configuration::get('PS_SHOP_PHONE'),\n 'compared_products' => is_array($compared_products) ? $compared_products : array(),\n 'comparator_max_item' => (int)Configuration::get('PS_COMPARATOR_MAX_ITEM'),\n 'currencySign' => $currency->sign, // backward compat, see global.tpl\n 'currencyFormat' => $currency->format, // backward compat\n 'currencyBlank' => $currency->blank, // backward compat\n ));\n\n // Add the tpl files directory for mobile\n if ($this->useMobileTheme()) {\n $this->context->smarty->assign(array(\n 'tpl_mobile_uri' => _PS_THEME_MOBILE_DIR_,\n ));\n }\n\n // Deprecated\n $this->context->smarty->assign(array(\n 'id_currency_cookie' => (int)$currency->id,\n 'logged' => $this->context->customer->isLogged(),\n 'customerName' => ($this->context->customer->logged ? $this->context->cookie->customer_firstname.' '.$this->context->cookie->customer_lastname : false)\n ));\n\n $assign_array = array(\n 'img_ps_dir' => _PS_IMG_,\n 'img_cat_dir' => _THEME_CAT_DIR_,\n 'img_lang_dir' => _THEME_LANG_DIR_,\n 'img_prod_dir' => _THEME_PROD_DIR_,\n 'img_manu_dir' => _THEME_MANU_DIR_,\n 'img_sup_dir' => _THEME_SUP_DIR_,\n 'img_ship_dir' => _THEME_SHIP_DIR_,\n 'img_store_dir' => _THEME_STORE_DIR_,\n 'img_col_dir' => _THEME_COL_DIR_,\n 'img_dir' => _THEME_IMG_DIR_,\n 'css_dir' => _THEME_CSS_DIR_,\n 'js_dir' => _THEME_JS_DIR_,\n 'pic_dir' => _THEME_PROD_PIC_DIR_\n );\n\n // Add the images directory for mobile\n if ($this->useMobileTheme()) {\n $assign_array['img_mobile_dir'] = _THEME_MOBILE_IMG_DIR_;\n }\n\n // Add the CSS directory for mobile\n if ($this->useMobileTheme()) {\n $assign_array['css_mobile_dir'] = _THEME_MOBILE_CSS_DIR_;\n }\n\n foreach ($assign_array as $assign_key => $assign_value) {\n if (substr($assign_value, 0, 1) == '/' || $protocol_content == 'https://') {\n $this->context->smarty->assign($assign_key, $protocol_content.Tools::getMediaServer($assign_value).$assign_value);\n } else {\n $this->context->smarty->assign($assign_key, $assign_value);\n }\n }\n\n /**\n * These shortcuts are DEPRECATED as of version 1.5.0.1\n * Use the Context to access objects instead.\n * Example: $this->context->cart\n */\n self::$cookie = $this->context->cookie;\n self::$cart = $cart;\n self::$smarty = $this->context->smarty;\n self::$link = $link;\n $defaultCountry = $this->context->country;\n\n $this->displayMaintenancePage();\n\n if ($this->restrictedCountry) {\n $this->displayRestrictedCountryPage();\n }\n\n if (Tools::isSubmit('live_edit') && !$this->checkLiveEditAccess()) {\n Tools::redirect('index.php?controller=404');\n }\n\n $this->iso = $iso;\n $this->context->cart = $cart;\n $this->context->currency = $currency;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, array $params = []): void\n {\n $activeGroups = $data->getActiveGroups();\n if (!$activeGroups) {\n return;\n }\n $items = $data->getItems();\n $validLanguages = $this->getValidLanguages();\n $subItems = [];\n $getInheritedValues = DataObject::doGetInheritedValues();\n\n if (!$omitMandatoryCheck) {\n if ($this->maxItems && count($activeGroups) > $this->maxItems) {\n throw new Model\\Element\\ValidationException(\n 'Groups in field [' . $this->getName() . '] is bigger than ' . $this->getMaxItems()\n );\n }\n\n foreach ($activeGroups as $activeGroupId => $enabled) {\n if ($enabled) {\n $groupDefinition = DataObject\\Classificationstore\\GroupConfig::getById($activeGroupId);\n if (!$groupDefinition) {\n continue;\n }\n\n $keyGroupRelations = $groupDefinition->getRelations();\n\n foreach ($keyGroupRelations as $keyGroupRelation) {\n foreach ($validLanguages as $validLanguage) {\n $keyId = $keyGroupRelation->getKeyId();\n\n $object = $data->getObject();\n if ($object->getClass()->getAllowInherit()) {\n DataObject::setGetInheritedValues(true);\n $value = $data->getLocalizedKeyValue($activeGroupId, $keyId, $validLanguage, true);\n DataObject::setGetInheritedValues($getInheritedValues);\n } else {\n $value = $items[$activeGroupId][$keyId][$validLanguage] ?? null;\n }\n\n $keyDef = DataObject\\Classificationstore\\Service::getFieldDefinitionFromJson(json_decode($keyGroupRelation->getDefinition(), true), $keyGroupRelation->getType());\n\n if ($keyGroupRelation->isMandatory()) {\n $keyDef->setMandatory(true);\n }\n\n try {\n $keyDef->checkValidity($value, false, $params);\n } catch (Exception $exception) {\n $subItems[] = new Model\\Element\\ValidationException(\n $exception->getMessage() . ' (' . $validLanguage . ')',\n $exception->getCode(),\n $exception->getPrevious()\n );\n }\n }\n }\n }\n }\n }\n\n if ($subItems) {\n $messages = array_map(function (Model\\Element\\ValidationException $validationException) {\n $validationException->addContext($this->getName());\n\n return $validationException->getMessage();\n }, $subItems);\n\n $validationException = new Model\\Element\\ValidationException(implode(', ', $messages));\n $validationException->setSubItems($subItems);\n\n throw $validationException;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getEncounters($pid)\n {\n\n $isfirst = 1;\n $res = sqlStatement(\"SELECT forms.encounter, forms.form_id, forms.form_name, \" .\n \"forms.formdir, forms.date AS fdate, form_encounter.date \" .\n \",form_encounter.reason \" .\n \"FROM forms, form_encounter WHERE \" .\n \"forms.pid = ? AND form_encounter.pid = ? AND \" .\n \"form_encounter.encounter = forms.encounter \" .\n \" AND forms.deleted=0 \" . // --JRM--\n \"ORDER BY form_encounter.date DESC, fdate ASC\", [$pid, $pid]);\n $res2 = sqlStatement(\"SELECT name FROM registry ORDER BY priority\");\n $encountersByDate = [];\n $encountersByEncounter = [];\n $html_strings = array();\n $registry_form_name = array();\n while ($result2 = sqlFetchArray($res2)) {\n array_push($registry_form_name, trim($result2['name']));\n }\n\n $encounter = null;\n while ($result = sqlFetchArray($res)) {\n $encounterId = $result['encounter'];\n if ($result[\"form_name\"] == \"New Patient Encounter\") {\n $encounter = [\n 'formdir' => $result[\"formdir\"]\n ,'form_id' => $result[\"form_id\"]\n ,'encounter' => $result[\"encounter\"]\n ,'display' => ''\n ,'forms' => []\n ];\n // show encounter reason, not just 'New Encounter'\n // trim to a reasonable length for display purposes --cfapress\n $maxReasonLength = 20;\n if (strlen($result[\"reason\"]) > $maxReasonLength) {\n $encounter['display'] = substr($result['reason'], 0, $maxReasonLength) . \" ... \";\n } else {\n $encounter['display'] = $result['reason'] ?? '';\n }\n $encounter['date'] = date(\"Y-m-d\", strtotime($result[\"date\"]));\n $encountersByDate[] = $encounterId;\n $encountersByEncounter[$encounterId] = $encounter;\n } else {\n $form_name = trim($result[\"form_name\"]);\n // TODO: @adunsulag we need to investigate why procedure order form saves\n // its name as this way.. so odd.\n if ($form_name === '-procedure') {\n $form_name = 'Procedure Order';\n }\n //if form name is not in registry, look for the closest match by\n // finding a registry name which is at the start of the form name.\n //this is to allow for forms to put additional helpful information\n //in the database in the same string as their form name after the name\n $form_name_found_flag = 0;\n foreach ($registry_form_name as $var) {\n if ($var == $form_name) {\n $form_name_found_flag = 1;\n }\n }\n\n // if the form does not match precisely with any names in the registry, now see if any front partial matches\n // and change $form_name appropriately so it will print above in $toprint = $html_strings[$var]\n if (!$form_name_found_flag) {\n foreach ($registry_form_name as $var) {\n if (strpos($form_name, $var) === 0) {\n $form_name = $var;\n }\n }\n }\n if (empty($encountersByEncounter[$encounterId]['forms'][$form_name])) {\n $encountersByEncounter[$encounterId]['forms'][$form_name] = [];\n }\n $encountersByEncounter[$encounterId]['forms'][$form_name][] = [\n 'formdir' => $result['formdir']\n , 'form_id' => $result['form_id']\n , 'encounter' => $result['encounter']\n , 'display' => xl_form_title($form_name)\n ];\n }\n }\n $encounters = array_map(function ($encounterId) use ($encountersByEncounter) {\n return $encountersByEncounter[$encounterId];\n }, $encountersByDate);\n return $encounters;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function Get($fieldname, $default = \"\", $escape = false, $ignorecase = false)\n {\n $val = null;\n\n if ($ignorecase) {\n $_REQUEST_LOWER = array_change_key_case($_REQUEST, CASE_LOWER);\n $val = (isset($_REQUEST_LOWER [strtolower($fieldname)]) && $_REQUEST_LOWER [strtolower($fieldname)] != \"\") ? $_REQUEST_LOWER [strtolower($fieldname)] : $default;\n } else {\n $val = (isset($_REQUEST [$fieldname]) && $_REQUEST [$fieldname] != \"\") ? $_REQUEST [$fieldname] : $default;\n }\n\n if ($escape) {\n $val = htmlspecialchars($val, ENT_COMPAT, null, false);\n }\n\n if (self::$ENCODE_NON_ASCII) {\n require_once(\"verysimple/String/VerySimpleStringUtil.php\");\n\n if (is_array($val)) {\n foreach ($val as $k => $v) {\n $val [$k] = VerySimpleStringUtil::EncodeToHTML($v);\n }\n } else {\n $val = VerySimpleStringUtil::EncodeToHTML($val);\n }\n }\n\n return $val;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getMetadata(?string $name = null, ?string $language = null, bool $strictMatchLanguage = false, bool $raw = false): mixed\n {\n $preEvent = new AssetEvent($this);\n $preEvent->setArgument('metadata', $this->metadata);\n $this->dispatchEvent($preEvent, AssetEvents::PRE_GET_METADATA);\n $this->metadata = $preEvent->getArgument('metadata');\n\n if ($name) {\n return $this->getMetadataByName($name, $language, $strictMatchLanguage, $raw);\n }\n\n $metaData = $this->getObjectVar('metadata');\n $result = [];\n $metaDataWithLanguage = [];\n if (is_array($metaData)) {\n foreach ($metaData as $md) {\n $md = (array)$md;\n\n if ((empty($md['language']) && !$strictMatchLanguage) || ($language == $md['language']) || !$language) {\n if (!$raw) {\n $md['data'] = $this->transformMetadata($md);\n }\n $result[] = $md;\n }\n\n if (!empty($md['language'])) {\n $metaDataWithLanguage[$md['language']][$md['name']] = $md;\n }\n }\n }\n\n if ($language && !$strictMatchLanguage) {\n foreach ($result as $key => &$item) {\n if (!$item['language'] && isset($metaDataWithLanguage[$language][$item['name']])) {\n $itemWithLanguage = $metaDataWithLanguage[$language][$item['name']];\n if (!in_array($itemWithLanguage, $result)) {\n $item = $itemWithLanguage;\n } else {\n unset($result[$key]);\n }\n }\n }\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function AMTremoveBrackets($node) {\n\tif ($node[0]=='{' && $node[strlen($node)-1]=='}') {\n\t\t\n\t\t$leftchop = 0;\n\t\t$st = substr($node,1,5);\n\t\tif ($st=='\\\\left') {\n\t\t\t$st = $node[6];\n\t\t\tif ($st=='(' || $st=='[' || $st=='{') {\n\t\t\t\t$leftchop = 7;\n\t\t\t} else {\n\t\t\t\t$st = substr($node,6,7);\n\t\t\t\tif ($st=='\\\\lbrace') {\n\t\t\t\t\t$leftchop = 13;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$st = $node[1];\n\t\t\tif ($st=='(' || $st=='[') {\n\t\t\t\t$leftchop = 2;\n\t\t\t}\n\t\t}\n\t\n\t\tif ($leftchop>0) {\n\t\t\t$st = substr($node,-8);\n\t\t\tif ($st=='\\\\right)}' || $st=='\\\\right]}' || $st=='\\\\right.}') {\n\t\t\t\t$node = '{'.substr($node,$leftchop);\n\t\t\t\t$node = substr($node,0,strlen($node)-8).'}';\n\t\t\t} else if ($st=='\\\\rbrace}') {\n\t\t\t\t$node = '{'.substr($node,$leftchop);\n\t\t\t\t$node = substr($node,0,strlen($node)-14).'}';\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\treturn $node;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<MedicinalProductContraindication xmlns=\"http://hl7.org/fhir\"></MedicinalProductContraindication>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->subject)) {\n foreach ($this->subject as $subject) {\n $subject->xmlSerialize(true, $sxe->addChild('subject'));\n }\n }\n if (isset($this->disease)) {\n $this->disease->xmlSerialize(true, $sxe->addChild('disease'));\n }\n if (isset($this->diseaseStatus)) {\n $this->diseaseStatus->xmlSerialize(true, $sxe->addChild('diseaseStatus'));\n }\n if (0 < count($this->comorbidity)) {\n foreach ($this->comorbidity as $comorbidity) {\n $comorbidity->xmlSerialize(true, $sxe->addChild('comorbidity'));\n }\n }\n if (0 < count($this->therapeuticIndication)) {\n foreach ($this->therapeuticIndication as $therapeuticIndication) {\n $therapeuticIndication->xmlSerialize(true, $sxe->addChild('therapeuticIndication'));\n }\n }\n if (0 < count($this->otherTherapy)) {\n foreach ($this->otherTherapy as $otherTherapy) {\n $otherTherapy->xmlSerialize(true, $sxe->addChild('otherTherapy'));\n }\n }\n if (0 < count($this->population)) {\n foreach ($this->population as $population) {\n $population->xmlSerialize(true, $sxe->addChild('population'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function updatePosition($id_hook, $way, $position = null)\n {\n foreach (Shop::getContextListShopID() as $shop_id) {\n $sql = 'SELECT hm.`id_module`, hm.`position`, hm.`id_hook`\n\t\t\t\t\tFROM `'._DB_PREFIX_.'hook_module` hm\n\t\t\t\t\tWHERE hm.`id_hook` = '.(int)$id_hook.' AND hm.`id_shop` = '.$shop_id.'\n\t\t\t\t\tORDER BY hm.`position` '.($way ? 'ASC' : 'DESC');\n if (!$res = Db::getInstance()->executeS($sql)) {\n continue;\n }\n\n foreach ($res as $key => $values) {\n if ((int)$values[$this->identifier] == (int)$this->id) {\n $k = $key;\n break;\n }\n }\n if (!isset($k) || !isset($res[$k]) || !isset($res[$k + 1])) {\n return false;\n }\n\n $from = $res[$k];\n $to = $res[$k + 1];\n\n if (isset($position) && !empty($position)) {\n $to['position'] = (int)$position;\n }\n\n $sql = 'UPDATE `'._DB_PREFIX_.'hook_module`\n\t\t\t\tSET `position`= position '.($way ? '-1' : '+1').'\n\t\t\t\tWHERE position between '.(int)(min(array($from['position'], $to['position']))).' AND '.max(array($from['position'], $to['position'])).'\n\t\t\t\tAND `id_hook` = '.(int)$from['id_hook'].' AND `id_shop` = '.$shop_id;\n if (!Db::getInstance()->execute($sql)) {\n return false;\n }\n\n $sql = 'UPDATE `'._DB_PREFIX_.'hook_module`\n\t\t\t\tSET `position`='.(int)$to['position'].'\n\t\t\t\tWHERE `'.pSQL($this->identifier).'` = '.(int)$from[$this->identifier].'\n\t\t\t\tAND `id_hook` = '.(int)$to['id_hook'].' AND `id_shop` = '.$shop_id;\n if (!Db::getInstance()->execute($sql)) {\n return false;\n }\n }\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['productCategory'])) {\n $this->setProductCategory($data['productCategory']);\n }\n if (isset($data['productCode'])) {\n $this->setProductCode($data['productCode']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['request'])) {\n if (is_array($data['request'])) {\n foreach ($data['request'] as $d) {\n $this->addRequest($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"request\" must be array of objects or null, ' . gettype($data['request']) . ' seen.');\n }\n }\n if (isset($data['quantity'])) {\n $this->setQuantity($data['quantity']);\n }\n if (isset($data['parent'])) {\n if (is_array($data['parent'])) {\n foreach ($data['parent'] as $d) {\n $this->addParent($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"parent\" must be array of objects or null, ' . gettype($data['parent']) . ' seen.');\n }\n }\n if (isset($data['collection'])) {\n $this->setCollection($data['collection']);\n }\n if (isset($data['processing'])) {\n if (is_array($data['processing'])) {\n foreach ($data['processing'] as $d) {\n $this->addProcessing($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"processing\" must be array of objects or null, ' . gettype($data['processing']) . ' seen.');\n }\n }\n if (isset($data['manipulation'])) {\n $this->setManipulation($data['manipulation']);\n }\n if (isset($data['storage'])) {\n if (is_array($data['storage'])) {\n foreach ($data['storage'] as $d) {\n $this->addStorage($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"storage\" must be array of objects or null, ' . gettype($data['storage']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function _groupMembers(string $dnGroup, array $seen = [], bool &$recursive = false): array {\n\t\tif (isset($seen[$dnGroup])) {\n\t\t\t$recursive = true;\n\t\t\treturn [];\n\t\t}\n\t\t$seen[$dnGroup] = true;\n\n\t\t// used extensively in cron job, caching makes sense for nested groups\n\t\t$cacheKey = '_groupMembers' . $dnGroup;\n\t\t$groupMembers = $this->access->connection->getFromCache($cacheKey);\n\t\tif ($groupMembers !== null) {\n\t\t\treturn $groupMembers;\n\t\t}\n\n\t\tif ($this->access->connection->ldapNestedGroups\n\t\t\t&& $this->access->connection->useMemberOfToDetectMembership\n\t\t\t&& $this->access->connection->hasMemberOfFilterSupport\n\t\t\t&& $this->access->connection->ldapMatchingRuleInChainState !== Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE\n\t\t) {\n\t\t\t$attemptedLdapMatchingRuleInChain = true;\n\t\t\t// Use matching rule 1.2.840.113556.1.4.1941 if available (LDAP_MATCHING_RULE_IN_CHAIN)\n\t\t\t$filter = $this->access->combineFilterWithAnd([\n\t\t\t\t$this->access->connection->ldapUserFilter,\n\t\t\t\t$this->access->connection->ldapUserDisplayName . '=*',\n\t\t\t\t'memberof:1.2.840.113556.1.4.1941:=' . $dnGroup\n\t\t\t]);\n\t\t\t$memberRecords = $this->access->fetchListOfUsers(\n\t\t\t\t$filter,\n\t\t\t\t$this->access->userManager->getAttributes(true)\n\t\t\t);\n\t\t\t$result = array_reduce($memberRecords, function ($carry, $record) {\n\t\t\t\t$carry[] = $record['dn'][0];\n\t\t\t\treturn $carry;\n\t\t\t}, []);\n\t\t\tif ($this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_AVAILABLE) {\n\t\t\t\t$this->access->connection->writeToCache($cacheKey, $result);\n\t\t\t\treturn $result;\n\t\t\t} elseif (!empty($memberRecords)) {\n\t\t\t\t$this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_AVAILABLE;\n\t\t\t\t$this->access->connection->saveConfiguration();\n\t\t\t\t$this->access->connection->writeToCache($cacheKey, $result);\n\t\t\t\treturn $result;\n\t\t\t}\n\t\t\t// when feature availability is unknown, and the result is empty, continue and test with original approach\n\t\t}\n\n\t\t$allMembers = [];\n\t\t$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);\n\t\tif (is_array($members)) {\n\t\t\tif ((int)$this->access->connection->ldapNestedGroups === 1) {\n\t\t\t\twhile ($recordDn = array_shift($members)) {\n\t\t\t\t\t$nestedMembers = $this->_groupMembers($recordDn, $seen, $recursive);\n\t\t\t\t\tif (!empty($nestedMembers)) {\n\t\t\t\t\t\t// Group, queue its members for processing\n\t\t\t\t\t\t$members = array_merge($members, $nestedMembers);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// User (or empty group, or previously seen group), add it to the member list\n\t\t\t\t\t\t$allMembers[] = $recordDn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$allMembers = $members;\n\t\t\t}\n\t\t}\n\n\t\t$allMembers += $this->getDynamicGroupMembers($dnGroup);\n\n\t\t$allMembers = array_unique($allMembers);\n\n\t\t// A group cannot be a member of itself\n\t\t$index = array_search($dnGroup, $allMembers, true);\n\t\tif ($index !== false) {\n\t\t\tunset($allMembers[$index]);\n\t\t}\n\n\t\tif (!$recursive) {\n\t\t\t$this->access->connection->writeToCache($cacheKey, $allMembers);\n\t\t}\n\n\t\tif (isset($attemptedLdapMatchingRuleInChain)\n\t\t\t&& $this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_UNKNOWN\n\t\t\t&& !empty($allMembers)\n\t\t) {\n\t\t\t$this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE;\n\t\t\t$this->access->connection->saveConfiguration();\n\t\t}\n\n\t\treturn $allMembers;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function updateassess($aidarr,$removewithdrawn,$doreplaceby) {\n\tglobal $DBH;\n\t//need to look up which assessments have withdrawn questions\n\t//and/or replaceable questions\n\t//for replaceable questions, look up replacement id\n\t//pull itemorders, remove withdrawn or replace ids, update itemorder\n\tif (!$removewithdrawn && !$doreplaceby) { return 'No changes reqested';}\n\n\tif (is_array($aidarr)) {\n\t\t$aidarr = array_map(\"intval\", $aidarr);\n\t} else {\n\t\t$aidarr = intval($aidarr);\n\t}\n\tif ($doreplaceby) {\n\t\t$query = \"UPDATE imas_questions AS iq JOIN imas_questionset AS iqs ON iq.questionsetid=iqs.id \";\n\t\tif (!is_array($aidarr)) {\n\t\t\t$query .= \"JOIN imas_assessments AS ia ON iq.assessmentid=ia.id \";\n\t\t}\n\t\t$query .= \"SET iq.questionsetid=iqs.replaceby WHERE iqs.replaceby>0 \";\n\t\tif (is_array($aidarr)) {\n\t\t\t$query .= \" AND iq.assessmentid IN (\".implode(',',$aidarr).\")\";\n\t\t} else {\n\t\t\t$query .= \" AND ia.courseid=$aidarr\";\n\t\t}\n\t\t$stm = $DBH->query($query); //pre-sanitized\n\t\t$replacedcnt = $stm->rowCount();\n\t}\n\n\tif ($removewithdrawn) {\n\t\t$query = \"SELECT iq.assessmentid,iq.id,iq.withdrawn FROM imas_questions AS iq \";\n\t\tif (!is_array($aidarr)) {\n\t\t\t$query .= \"JOIN imas_assessments AS ia ON iq.assessmentid=ia.id \";\n\t\t}\n\t\t$query .= \"WHERE iq.withdrawn>0\";\n\n\t\tif (is_array($aidarr)) {\n\t\t\t$query .= \" AND iq.assessmentid IN (\".implode(',',$aidarr).\")\";\n\t\t} else {\n\t\t\t$query .= \" AND ia.courseid=$aidarr\";\n\t\t}\n\t\t$todoaid = array();\n\t\t$withdrawn = array();\n\t\t$stm = $DBH->query($query); //pre-sanitized\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\t$todoaid[] = $row[0];\n\t\t\tif ($row[2]>0) {\n\t\t\t\t$withdrawn[$row[1]] = true;\n\t\t\t}\n\t\t}\n\t\tif (count($todoaid)==0) { return 'No changes to make';}\n\n\t\t$todoaid = array_unique($todoaid);\n\n\t\t$item_upd_stm = $DBH->prepare(\"UPDATE imas_assessments SET itemorder=:itemorder WHERE id=:id\");\n\n\t\t$query = \"SELECT id,itemorder,defpoints FROM imas_assessments WHERE id IN (\".implode(',',$todoaid).')';\n\t\t$stm = $DBH->query($query); //pre-sanitized\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\t$items = explode(',',$row[1]);\n\t\t\t$newitems = array();\n\t\t\tforeach ($items as $k=>$q) {\n\t\t\t\tif (strpos($q,'~')!==false) {\n\t\t\t\t\t$sub = explode('~',$q);\n\t\t\t\t\t$newsub = array();\n\t\t\t\t\t$front = 0;\n\t\t\t\t\tif (strpos($sub[0],'|')!==false) {\n\t\t\t\t\t\t$newsub[] = array_shift($sub);\n\t\t\t\t\t\t$front = 1;\n\t\t\t\t\t}\n\t\t\t\t\tforeach ($sub as $sq) {\n\t\t\t\t\t\tif (!isset($withdrawn[$sq])) {\n\t\t\t\t\t\t\t$newsub[] = $sq;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (count($newsub)==$front) {\n\n\t\t\t\t\t} else if (count($newsub)==$front+1) {\n\t\t\t\t\t\t$newitems[] = $newsub[$front];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$newitems[] = implode('~',$newsub);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!isset($withdrawn[$q])) {\n\t\t\t\t\t\t$newitems[] = $q;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$newitemlist = implode(',', $newitems);\n\t\t\t$item_upd_stm->execute(array(':itemorder'=>$newitemlist, ':id'=>$row[0]));\n\t\t\t\n\t\t\tupdatePointsPossible($row[0], $newitemlist, $row[2]);\n\t\t}\n\t}\n\n\t$msg = '';\n\tif ($removewithdrawn) {\n\t\tif (count($withdrawn)>0) {\n\t\t\t$msg .= 'Removed '.count($withdrawn).' withdrawn questions. ';\n\t\t} else {\n\t\t\t$msg .= 'No withdrawn questions to remove. ';\n\t\t}\n\t}\n\tif ($doreplaceby) {\n\t\tif ($replacedcnt>0) {\n\t\t\t$msg .= 'Updated '.$replacedcnt.' questions. ';\n\t\t} else {\n\t\t\t$msg .= 'No questions to update. ';\n\t\t}\n\t}\n\treturn $msg;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function initContent()\n {\n if (!Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) {\n // You can uncomment these lines if you want to force https even from localhost and automatically redirect\n // header('HTTP/1.1 301 Moved Permanently');\n // header('Location: '.Tools::getShopDomainSsl(true).$_SERVER['REQUEST_URI']);\n // exit();\n $clientIsMaintenanceOrLocal = in_array(Tools::getRemoteAddr(), array_merge(array('127.0.0.1'), explode(',', Configuration::get('PS_MAINTENANCE_IP'))));\n // If ssl is enabled, https protocol is required. Exception for maintenance and local (127.0.0.1) IP\n if ($clientIsMaintenanceOrLocal) {\n $warningSslMessage = $this->trans('SSL is activated. However, your IP is allowed to enter unsecure mode for maintenance or local IP issues.', array(), 'Admin.Login.Notification');\n } else {\n $url = 'https://' . Tools::safeOutput(Tools::getServerName()) . Tools::safeOutput($_SERVER['REQUEST_URI']);\n $warningSslMessage = $this->trans(\n 'SSL is activated. Please connect using the following link to [1]log in to secure mode (https://)[/1]',\n array('[1]' => '<a href=\"' . $url . '\">', '[/1]' => '</a>'),\n 'Admin.Login.Notification'\n );\n }\n $this->context->smarty->assign('warningSslMessage', $warningSslMessage);\n }\n\n if (file_exists(_PS_ADMIN_DIR_ . '/../install')) {\n $this->context->smarty->assign('wrong_install_name', true);\n }\n\n if (basename(_PS_ADMIN_DIR_) == 'admin' && file_exists(_PS_ADMIN_DIR_ . '/../admin/')) {\n $rand = 'admin' . sprintf('%03d', mt_rand(0, 999)) . Tools::strtolower(Tools::passwdGen(6)) . '/';\n if (@rename(_PS_ADMIN_DIR_ . '/../admin/', _PS_ADMIN_DIR_ . '/../' . $rand)) {\n Tools::redirectAdmin('../' . $rand);\n } else {\n $this->context->smarty->assign(array(\n 'wrong_folder_name' => true,\n ));\n }\n } else {\n $rand = basename(_PS_ADMIN_DIR_) . '/';\n }\n\n $this->context->smarty->assign(array(\n 'randomNb' => $rand,\n 'adminUrl' => Tools::getCurrentUrlProtocolPrefix() . Tools::getShopDomain() . __PS_BASE_URI__ . $rand,\n ));\n\n // Redirect to admin panel\n if (Tools::isSubmit('redirect') && Validate::isControllerName(Tools::getValue('redirect'))) {\n $this->context->smarty->assign('redirect', Tools::getValue('redirect'));\n } else {\n $tab = new Tab((int) $this->context->employee->default_tab);\n $this->context->smarty->assign('redirect', $this->context->link->getAdminLink($tab->class_name));\n }\n\n if ($nb_errors = count($this->errors)) {\n $this->context->smarty->assign(array(\n 'errors' => $this->errors,\n 'nbErrors' => $nb_errors,\n 'shop_name' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME')),\n 'disableDefaultErrorOutPut' => true,\n ));\n }\n\n if ($email = Tools::getValue('email')) {\n $this->context->smarty->assign('email', $email);\n }\n if ($password = Tools::getValue('password')) {\n $this->context->smarty->assign('password', $password);\n }\n\n // For reset password feature\n if ($reset_token = Tools::getValue('reset_token')) {\n $this->context->smarty->assign('reset_token', $reset_token);\n }\n if ($id_employee = Tools::getValue('id_employee')) {\n $this->context->smarty->assign('id_employee', $id_employee);\n $employee = new Employee($id_employee);\n if (Validate::isLoadedObject($employee)) {\n $this->context->smarty->assign('reset_email', $employee->email);\n }\n }\n\n $this->setMedia($isNewTheme = false);\n $this->initHeader();\n parent::initContent();\n $this->initFooter();\n\n //force to disable modals\n $this->context->smarty->assign('modals', null);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function create_HTML_statement($stmt)\n{\n if (! $stmt['pid']) {\n return \"\"; // get out if no data\n }\n\n#minimum_amount_due_to _print\n if ($stmt['amount'] <= ($GLOBALS['minimum_amount_to_print']) && $GLOBALS['use_statement_print_exclusion'] && ($_POST['form_category'] !== \"All\")) {\n return \"\";\n }\n\n// Facility (service location) modified by Daniel Pflieger at Growlingflea Software\n $service_query = sqlStatement(\"SELECT * FROM `form_encounter` fe join facility f on fe.facility_id = f.id where fe.id = ? \", array($stmt['fid']));\n $row = sqlFetchArray($service_query);\n $clinic_name = \"{$row['name']}\";\n $clinic_addr = \"{$row['street']}\";\n $clinic_csz = \"{$row['city']}, {$row['state']}, {$row['postal_code']}\";\n\n\n// Billing location modified by Daniel Pflieger at Growlingflea Software\n $service_query = sqlStatement(\"SELECT * FROM `form_encounter` fe join facility f on fe.billing_facility = f.id where fe.id = ?\", array($stmt['fid']));\n $row = sqlFetchArray($service_query);\n $remit_name = \"{$row['name']}\";\n $remit_addr = \"{$row['street']}\";\n $remit_csz = \"{$row['city']}, {$row['state']}, {$row['postal_code']}\";\n\n ob_start();\n ?><div style=\"padding-left:25px; page-break-after:always;\">\n <?php\n $find_provider = sqlQuery(\"SELECT * FROM form_encounter \" .\n \"WHERE pid = ? AND encounter = ? \" .\n \"ORDER BY id DESC LIMIT 1\", array($stmt['pid'],$stmt['encounter']));\n $providerID = $find_provider['provider_id'];\n echo report_header_2($stmt, $providerID);\n\n // dunning message setup\n\n // insurance has paid something\n // $stmt['age'] how old is the invoice\n // $stmt['dun_count'] number of statements run\n // $stmt['level_closed'] <= 3 insurance 4 = patient\n\n if ($GLOBALS['use_dunning_message']) {\n if ($stmt['ins_paid'] != 0 || $stmt['level_closed'] == 4) {\n // do collection messages\n switch ($stmt['age']) {\n case $stmt['age'] <= $GLOBALS['first_dun_msg_set']:\n $dun_message = $GLOBALS['first_dun_msg_text'];\n break;\n case $stmt['age'] <= $GLOBALS['second_dun_msg_set']:\n $dun_message = $GLOBALS['second_dun_msg_text'];\n break;\n case $stmt['age'] <= $GLOBALS['third_dun_msg_set']:\n $dun_message = $GLOBALS['third_dun_msg_text'];\n break;\n case $stmt['age'] <= $GLOBALS['fourth_dun_msg_set']:\n $dun_message = $GLOBALS['fourth_dun_msg_text'];\n break;\n case $stmt['age'] >= $GLOBALS['fifth_dun_msg_set']:\n $dun_message = $GLOBALS['fifth_dun_msg_text'];\n break;\n }\n }\n }\n\n // Text only labels\n\n $label_addressee = xl('ADDRESSED TO');\n $label_remitto = xl('REMIT TO');\n $label_chartnum = xl('Chart Number');\n $label_insinfo = xl('Insurance information on file');\n $label_totaldue = xl('Total amount due');\n $label_payby = xl('If paying by');\n $label_cards = xl('VISA/MC/Discovery/HSA');\n $label_cardnum = xl('Card');\n $label_expiry = xl('Exp');\n $label_cvv = xl('CVV');\n $label_sign = xl('Signature');\n $label_retpay = xl('Please return this bottom part with your payment');\n $label_pgbrk = xl('STATEMENT SUMMARY');\n $label_visit = xl('Visit Date');\n $label_desc = xl('Description');\n $label_amt = xl('Amount');\n\n // This is the text for the top part of the page, up to but not\n // including the detail lines. Some examples of variable fields are:\n // %s = string with no minimum width\n // %9s = right-justified string of 9 characters padded with spaces\n // %-25s = left-justified string of 25 characters padded with spaces\n // Note that \"\\n\" is a line feed (new line) character.\n // reformatted to handle i8n by tony\n\n $out = \"<div style='margin-left:60px;margin-top:20px;'><pre>\";\n $out .= \"\\n\";\n $out .= sprintf(\"_______________________ %s _______________________\\n\", $label_pgbrk);\n $out .= \"\\n\";\n $out .= sprintf(\"%-11s %-46s %s\\n\", $label_visit, $label_desc, $label_amt);\n\n // This must be set to the number of lines generated above.\n $count = 5;\n\n $num_ages = 4;\n $aging = array();\n for ($age_index = 0; $age_index < $num_ages; ++$age_index) {\n $aging[$age_index] = 0.00;\n }\n\n $todays_time = strtotime(date('Y-m-d'));\n\n // This generates the detail lines. Again, note that the values must be specified in the order used.\n foreach ($stmt['lines'] as $line) {\n if ($GLOBALS['use_custom_statement']) {\n $description = substr($line['desc'], 0, 30);\n } else {\n $description = $line['desc'];\n }\n\n $tmp = substr($description, 0, 14);\n if ($tmp == 'Procedure 9920' || $tmp == 'Procedure 9921' || $tmp == 'Procedure 9200' || $tmp == 'Procedure 9201') {\n $description = str_replace(\"Procedure\", xl('Office Visit') . \":\", $description);\n }\n\n //92002-14 are Eye Office Visit Codes\n\n $dos = $line['dos'];\n ksort($line['detail']);\n // suppressing individual adjustments = improved statement printing\n $adj_flag = false;\n $note_flag = false;\n $pt_paid_flag = false;\n $prev_ddate = '';\n $last_activity_date = $dos;\n foreach ($line['detail'] as $dkey => $ddata) {\n $ddate = substr($dkey, 0, 10);\n if (preg_match('/^(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)\\s*$/', $ddate, $matches)) {\n $ddate = $matches[1] . '-' . $matches[2] . '-' . $matches[3];\n }\n\n if ($ddate && $ddate > $last_activity_date) {\n $last_activity_date = $ddate;\n }\n\n $amount = '';\n\n if (!empty($ddata['pmt'])) {\n $amount = sprintf(\"%.2f\", 0 - $ddata['pmt']);\n $desc = xl('Paid') . ' ' . substr(oeFormatShortDate($ddate), 0, 6) .\n substr(oeFormatShortDate($ddate), 8, 2) .\n ': ' . $ddata['src'] . ' ' . $ddata['pmt_method'] . ' ' . $ddata['insurance_company'];\n // $ddata['plv'] is the 'payer_type' field in `ar_activity`, passed in via InvoiceSummary\n if ($ddata['src'] == 'Pt Paid' || $ddata['plv'] == '0') {\n $pt_paid_flag = true;\n $desc = xl('Pt paid') . ' ' . substr(oeFormatShortDate($ddate), 0, 6) .\n substr(oeFormatShortDate($ddate), 8, 2);\n }\n } elseif (!empty($ddata['rsn'])) {\n if ($ddata['chg']) {\n // this is where the adjustments used to be printed individually\n $adj_flag = true;\n } else {\n if ($ddate == $prev_ddate) {\n if ($note_flag) {\n // only 1 note per item or results in too much detail\n continue;\n } else {\n $desc = xl('Note') . ' ' . substr(oeFormatShortDate($ddate), 0, 6) .\n substr(oeFormatShortDate($ddate), 8, 2) .\n ': ' . ': ' . $ddata['rsn'] . ' ' . $ddata['pmt_method'] . ' ' . $ddata['insurance_company'];\n $note_flag = true;\n }\n } else {\n continue; // no need to print notes for 2nd insurances\n }\n }\n } elseif ($ddata['chg'] < 0) {\n $amount = sprintf(\"%.2f\", $ddata['chg']);\n $desc = xl('Patient Payment');\n } else {\n $amount = sprintf(\"%.2f\", $ddata['chg']);\n $desc = $description;\n }\n\n if (!$adj_flag) {\n $out .= sprintf(\"%-10s %-45s%8s\\n\", oeFormatShortDate($dos), $desc, $amount);\n ++$count;\n }\n\n $dos = '';\n $adj_flag = false;\n $note_flag = false;\n $prev_ddate = $ddate;\n }\n // print the adjustments summed after all other postings\n if ($line['adjust'] !== '0.00') {\n $out .= sprintf(\"%-10s %-45s%8s\\n\", oeFormatShortDate($dos), \"Insurance adjusted\", sprintf(\"%.2f\", 0 - $line['adjust']));\n ++$count;\n }\n\n // don't print a balance after a \"Paidpatient payment since it's on it's own line\n if (!$pt_paid_flag) {\n $out .= sprintf(\"%-10s %-45s%8s\\n\", oeFormatShortDate($dos), \"Item balance \", sprintf(\"%.2f\", ($line['amount'] - $line['paid'])));\n ++$count;\n }\n\n # Compute the aging bucket index and accumulate into that bucket.\n $last_activity_date = ($line['bill_date'] > $last_activity_date) ? $line['bill_date'] : $last_activity_date;\n // If first bill then make the amount due current and reset aging date\n if ($stmt['dun_count'] == '0') {\n $last_activity_date = date('Y-m-d');\n sqlStatement(\"UPDATE billing SET bill_date = ? WHERE pid = ? AND encounter = ?\", array(date('Y-m-d'), $row['pid'], $row['encounter']));\n }\n $age_in_days = (int) (($todays_time - strtotime($last_activity_date)) / (60 * 60 * 24));\n $age_index = (int) (($age_in_days - 1) / 30);\n $age_index = max(0, min($num_ages - 1, $age_index));\n $aging[$age_index] += $line['amount'] - $line['paid'];\n }\n\n // This generates blank lines until we are at line 20.\n // At line 20 we start middle third.\n\n while ($count++ < 16) {\n $out .= \"\\n\";\n }\n\n # Generate the string of aging text. This will look like:\n # Current xxx.xx / 31-60 x.xx / 61-90 x.xx / Over-90 xxx.xx\n # ....+....1....+....2....+....3....+....4....+....5....+....6....+\n #\n $ageline = xl('Current') . ': ' . sprintf(\"%.2f\", $aging[0]);\n for ($age_index = 1; $age_index < ($num_ages - 1); ++$age_index) {\n $ageline .= ' | ' . ($age_index * 30 + 1) . '-' . ($age_index * 30 + 30) . ':' .\n sprintf(\" %.2f\", $GLOBALS['gbl_currency_symbol'] . '' . $aging[$age_index]);\n }\n\n // Fixed text labels\n $label_ptname = xl('Name');\n $label_today = xl('Date');\n $label_due = xl('Due');\n $label_thanks = xl('Thank you for choosing');\n $label_call = xl('Please call if any of the above information is incorrect.');\n $label_prompt = xl('We appreciate prompt payment of balances due.');\n $label_dept = xl('Billing Department');\n $label_bill_phone = (!empty($GLOBALS['billing_phone_number']) ? $GLOBALS['billing_phone_number'] : $row['phone'] );\n $label_appointments = xl('Future Appointments') . ':';\n\n // This is the top portion of the page.\n $out .= \"\\n\\n\\n\";\n if (strlen($stmt['bill_note']) != 0 && $GLOBALS['statement_bill_note_print']) {\n $out .= sprintf(\"%-46s\\n\", $stmt['bill_note']);\n $count++;\n }\n\n if ($GLOBALS['use_dunning_message']) {\n $out .= sprintf(\"%-46s\\n\", $dun_message);\n $count++;\n }\n\n $out .= \"\\n\";\n $out .= sprintf(\n \"%-s: %-25s %-s: %-14s %-s: %8s\\n\",\n $label_ptname,\n $stmt['patient'],\n $label_today,\n oeFormatShortDate($stmt['today']),\n $label_due,\n $stmt['amount']\n );\n $out .= sprintf(\"__________________________________________________________________\\n\");\n $out .= \"\\n\";\n $out .= sprintf(\"%-s\\n\", $label_call);\n $out .= sprintf(\"%-s\\n\", $label_prompt);\n $out .= \"\\n\";\n // $out .= sprintf(\"%-s\\n\", $billing_contact);\n $out .= sprintf(\" %-s %-25s\\n\", $label_dept, $label_bill_phone);\n if ($GLOBALS['statement_message_to_patient']) {\n $out .= \"\\n\";\n $statement_message = $GLOBALS['statement_msg_text'];\n $out .= sprintf(\"%-40s\\n\", $statement_message);\n $count++;\n }\n\n if ($GLOBALS['show_aging_on_custom_statement']) {\n # code for ageing\n $ageline .= ' | ' . xl('Over') . ' ' . ($age_index * 30) . ':' .\n sprintf(\" %.2f\", $aging[$age_index]);\n $out .= \"\\n\" . $ageline . \"\\n\\n\";\n $count++;\n }\n\n if ($GLOBALS['number_appointments_on_statement'] != 0) {\n $out .= \"\\n\";\n $num_appts = $GLOBALS['number_appointments_on_statement'];\n $next_day = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y'));\n # add one day to date so it will not get todays appointment\n $current_date2 = date('Y-m-d', $next_day);\n $events = fetchNextXAppts($current_date2, $stmt['pid'], $num_appts);\n $j = 0;\n $out .= sprintf(\"%-s\\n\", $label_appointments);\n #loop to add the appointments\n for ($x = 1; $x <= $num_appts; $x++) {\n $next_appoint_date = oeFormatShortDate($events[$j]['pc_eventDate']);\n $next_appoint_time = substr($events[$j]['pc_startTime'], 0, 5);\n if (strlen(umname) != 0) {\n $next_appoint_provider = $events[$j]['ufname'] . ' ' . $events[$j]['umname'] . ' ' . $events[$j]['ulname'];\n } else {\n $next_appoint_provider = $events[$j]['ufname'] . ' ' . $events[$j]['ulname'];\n }\n\n if (strlen($next_appoint_time) != 0) {\n $label_plsnote[$j] = xlt('Date') . ': ' . text($next_appoint_date) . ' ' . xlt('Time') . ' ' . text($next_appoint_time) . ' ' . xlt('Provider') . ' ' . text($next_appoint_provider);\n $out .= sprintf(\"%-s\\n\", $label_plsnote[$j]);\n }\n\n $j++;\n $count++;\n }\n }\n\n while ($count++ < 29) {\n $out .= \"\\n\";\n }\n\n $out .= sprintf(\"%-10s %s\\n\", null, $label_retpay);\n $out .= '</pre></div>';\n $out .= '<div style=\"width:7.0in;border-top:1pt dotted black;font-size:12px;margin:0px;\"><br /><br />\n <table style=\"width:7in;margin-left:20px;\"><tr><td style=\"width:4.5in;\"><br />\n ';\n $out .= $label_payby . ' ' . $label_cards;\n $out .= \"<br /><br />\";\n $out .= $label_cardnum . ': __________________________________ ' . $label_expiry . ': ___ / ____ ' . $label_cvv . ':____<br /><br />';\n $out .= $label_sign . ' ______________________________________________<br />';\n $out .= \"</td><td style='width:2.0in;vertical-align:middle;'>\";\n $practice_cards = $GLOBALS['OE_SITE_DIR'] . \"/images/visa_mc_disc_credit_card_logos_176x35.gif\";\n if (file_exists($GLOBALS['OE_SITE_DIR'] . \"/images/visa_mc_disc_credit_card_logos_176x35.gif\")) {\n $out .= \"<img src='$practice_cards' style='width:90px;height:auto; margin:4px auto;'><br /><p>\\n<b>\" .\n $label_totaldue . \"</b>: \" . $stmt['amount'] . \"<br/>\" . xlt('Payment Tracking Id') . \": \" .\n text($stmt['pid']);\n $out .= \"<br />\" . xlt('Amount Paid') . \": _______ \" . xlt('Check') . \" #:</p>\";\n } else {\n $out .= \"<br /><p><b>\" . $label_totaldue . \"</b>: \" . $stmt['amount'] . \"<br/>\" .\n xlt('Payment Tracking Id') . \": \" . text($stmt['pid']) . \"</p>\";\n $out .= \"<br /><p>\" . xlt('Amount Paid') . \": _______ \" . xlt('Check') . \" #:</p>\";\n }\n\n $out .= \"</td></tr></table>\";\n\n $out .= '</div><br />\n <pre>';\n if (!empty($stmt['to'][3])) { //to avoid double blank lines the if condition is put.\n $out .= sprintf(\" %-32s\\n\", $stmt['to'][3]);\n }\n\n $out .= ' </pre>\n <div style=\"width:7.0in;border-top:1pt solid black;\"><br />';\n $out .= \" <table style='width:7.0in;margin:auto;'><tr>\";\n $out .= '<td style=\"margin:auto;\"></td><td style=\"width:3.0in;\"><b>'\n . $label_addressee . '</b><br />'\n . $stmt['to'][0] . '<br />'\n . $stmt['to'][1] . '<br />'\n . ($stmt['to'][2] ?? '') . '\n </td><td style=\"width:0.5in;\"></td>\n <td style=\"margin:auto;\"><b>' . $label_remitto . '</b><br />'\n . $remit_name . '<br />'\n . $remit_addr . '<br />'\n . $remit_csz . '\n </td>\n </tr></table>';\n\n $out .= \" </div></div>\";\n $out .= \"\\014\";\n echo $out;\n $output = ob_get_clean();\n return $output;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function canonicalRedirection($canonical_url = '')\n {\n if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET') {\n return;\n }\n\n $canonical_url = preg_replace('/#.*$/', '', $canonical_url);\n\n $match_url = rawurldecode(Tools::getCurrentUrlProtocolPrefix() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);\n if (!preg_match('/^' . Tools::pRegexp(rawurldecode($canonical_url), '/') . '([&?].*)?$/', $match_url)) {\n $params = [];\n $url_details = parse_url($canonical_url);\n\n if (!empty($url_details['query'])) {\n parse_str($url_details['query'], $query);\n foreach ($query as $key => $value) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n $excluded_key = ['isolang', 'id_lang', 'controller', 'fc', 'id_product', 'id_category', 'id_manufacturer', 'id_supplier', 'id_cms'];\n $excluded_key = array_merge($excluded_key, $this->redirectionExtraExcludedKeys);\n foreach ($_GET as $key => $value) {\n if (!in_array($key, $excluded_key) && Validate::isUrl($key) && Validate::isUrl($value)) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n\n $str_params = http_build_query($params, '', '&');\n if (!empty($str_params)) {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url) . '?' . $str_params;\n } else {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url);\n }\n\n // Don't send any cookie\n Context::getContext()->cookie->disallowWriting();\n if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $_SERVER['REQUEST_URI'] != __PS_BASE_URI__) {\n die('[Debug] This page has moved<br />Please use the following URL instead: <a href=\"' . $final_url . '\">' . $final_url . '</a>');\n }\n\n $redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';\n header('HTTP/1.0 ' . $redirect_type . ' Moved');\n header('Cache-Control: no-cache');\n Tools::redirectLink($final_url);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function _struct_to_array($values, &$i)\n {\n $child = array();\n if (isset($values[$i]['value'])) {\n array_push($child, $values[$i]['value']);\n }\n\n while ($i++ < count($values)) {\n if (isset($values[$i])) {\n switch ($values[$i]['type']) {\n case 'cdata':\n array_push($child, $values[$i]['value']);\n break;\n\n case 'complete':\n $name = $values[$i]['tag'];\n if (!empty($name)) {\n $child[$name] = (isset($values[$i]['value'])) ? ($values[$i]['value']) : '';\n if (isset($values[$i]['attributes'])) {\n $child[$name] = $values[$i]['attributes'];\n }\n }\n break;\n\n case 'open':\n $name = $values[$i]['tag'];\n $size = isset($child[$name]) ? sizeof($child[$name]) : 0;\n $child[$name][$size] = $this->_struct_to_array($values, $i);\n break;\n\n case 'close':\n return $child;\n break;\n }\n }\n }\n\n return $child;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function processReset()\n {\n if (_PS_MODE_DEMO_) {\n $this->errors[] = $this->trans('This functionality has been disabled.', array(), 'Admin.Notifications.Error');\n } elseif (!($reset_token_value = trim(Tools::getValue('reset_token')))) {\n // hidden fields\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($id_employee = trim(Tools::getValue('id_employee')))) {\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_email = trim(Tools::getValue('reset_email')))) {\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_password = trim(Tools::getValue('reset_passwd')))) {\n // password (twice)\n $this->errors[] = $this->trans('The password is missing: please enter your new password.', array(), 'Admin.Login.Notification');\n } elseif (!Validate::isPasswd($reset_password)) {\n $this->errors[] = $this->trans('The password is not in a valid format.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_confirm = trim(Tools::getValue('reset_confirm')))) {\n $this->errors[] = $this->trans('The confirmation is empty: please fill in the password confirmation as well.', array(), 'Admin.Login.Notification');\n } elseif ($reset_password !== $reset_confirm) {\n $this->errors[] = $this->trans('The password and its confirmation do not match. Please double check both passwords.', array(), 'Admin.Login.Notification');\n } else {\n $employee = new Employee();\n if (!$employee->getByEmail($reset_email) || !$employee || $employee->id != $id_employee) { // check matching employee id with its email\n $this->errors[] = $this->trans('This account does not exist.', array(), 'Admin.Login.Notification');\n } elseif ((strtotime($employee->last_passwd_gen.'+'.Configuration::get('PS_PASSWD_TIME_BACK').' minutes') - time()) > 0) {\n $this->errors[] = $this->trans('You can reset your password every %interval% minute(s) only. Please try again later.', array('%interval%' => Configuration::get('PS_PASSWD_TIME_BACK')), 'Admin.Login.Notification');\n } elseif ($employee->getValidResetPasswordToken() !== $reset_token_value) {\n // To update password, we must have the temporary reset token that matches.\n $this->errors[] = $this->trans('Your password reset request expired. Please start again.', array(), 'Admin.Login.Notification');\n }\n }\n\n if (!count($this->errors)) {\n $employee->passwd = $this->get('hashing')->hash($reset_password, _COOKIE_KEY_);\n $employee->last_passwd_gen = date('Y-m-d H:i:s', time());\n\n $params = array(\n '{email}' => $employee->email,\n '{lastname}' => $employee->lastname,\n '{firstname}' => $employee->firstname,\n );\n\n $employeeLanguage = new Language((int) $this->context->employee->id_lang);\n\n if (\n Mail::Send(\n $employee->id_lang,\n 'password',\n $this->trans(\n 'Your new password',\n array(),\n 'Emails.Subject',\n $employeeLanguage->locale\n ),\n $params,\n $employee->email,\n $employee->firstname.' '.$employee->lastname\n )\n ) {\n // Update employee only if the mail can be sent\n Shop::setContext(Shop::CONTEXT_SHOP, (int)min($employee->getAssociatedShops()));\n\n $result = $employee->update();\n if (!$result) {\n $this->errors[] = $this->trans('An error occurred while attempting to change your password.', array(), 'Admin.Login.Notification');\n } else {\n $employee->removeResetPasswordToken(); // Delete temporary reset token\n $employee->update();\n die(Tools::jsonEncode(array(\n 'hasErrors' => false,\n 'confirm' => $this->trans('The password has been changed successfully.', array(), 'Admin.Login.Notification')\n )));\n }\n } else {\n die(Tools::jsonEncode(array(\n 'hasErrors' => true,\n 'errors' => array($this->trans('An error occurred while attempting to change your password.', array(), 'Admin.Login.Notification'))\n )));\n }\n } elseif (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function detailsAdd(){\n\n if( !@$this->data['val'] && @$this->data['rVal']){\n $this->data['val'] = $this->data['rVal'];\n }\n\n if (!(@$this->data['val']!=null || @$this->data['geo']!=null || @$this->data['ulfID']!=null)){\n $this->system->addError(HEURIST_INVALID_REQUEST, \"Insufficent data passed. New field value not defined\");\n return false;\n }\n\n if(@$this->data['val']!=null){\n //attempt to pass server filters against malicious code\n if(@$this->data['details_encoded']==1 || @$this->data['details_encoded']==2){\n //$this->data['val'] = json_decode(str_replace( ' xxx_style=', ' style=',\n // str_replace( '^^/', '../', urldecode($this->data['val']))));\n //}elseif(@$this->data['details_encoded']==2){\n $this->data['val'] = urldecode( $this->data['val'] );\n }\n }\n\n if(!$this->_validateParamsAndCounts()){\n return false;\n }elseif (isEmptyArray($this->recIDs)){\n return $this->result_data;\n }\n\n $dtyID = $this->data['dtyID'];\n $dtyName = (@$this->data['dtyName'] ? \"'\".$this->data['dtyName'].\"'\" : \"id:\".$this->data['dtyID'].\"\");\n\n $mysqli = $this->system->getMysqli();\n\n //get array of max allowed values per record type\n $query = \"SELECT rst_RecTypeID,rst_MaxValues FROM defRecStructure WHERE rst_DetailTypeID = $dtyID and rst_RecTypeID in (\"\n .implode(',', $this->rtyIDs).')';\n $rtyLimits = mysql__select_assoc2($mysqli, $query);\n\n $basetype = null;\n if(@$this->data['geo']==null){\n $basetype = $this->getDetailType($dtyID);\n if($basetype=='geo'){\n $this->data['geo'] = $this->data['val'];\n }\n }\n\n $now = date(DATE_8601);\n $dtl = array('dtl_DetailTypeID' => $dtyID,\n 'dtl_Modified' => $now);\n $rec_update = array('rec_ID' => 'to-be-filled',\n 'rec_Modified' => $now);\n\n $baseTag = \"~add field $dtyName $now\";//name of tag assigned to modified records\n\n if(@$this->data['geo']!=null){\n\n list($geoType, $geoValue) = prepareGeoValue($mysqli, $this->data['geo']);\n if($geoType===false){\n $this->system->addError(HEURIST_INVALID_REQUEST, $geoValue);\n return false;\n }\n $dtl['dtl_Value'] = $geoType;\n $dtl['dtl_Geo'] = $geoValue;\n //$dtl['dtl_Geo'] = array(\"ST_GeomFromText(\\\"\" . $this->data['geo'] . \"\\\")\");\n }elseif($basetype=='date'){\n\n $useNewTemporalFormatInRecDetails = ($this->system->settings->get('sys_dbSubSubVersion')>=14);\n\n $dtl['dtl_Value'] = Temporal::getValueForRecDetails( $this->data['val'], $useNewTemporalFormatInRecDetails );\n\n\n }elseif(@$this->data['val']!=null){ //sanitize new value\n\n $this->_initPutifier();\n if(!in_array($dtyID, $this->not_purify)){\n\n //remove html script tags\n $dtl['dtl_Value'] = $this->_removeScriptTag($this->data['val']);\n\n //$s = $this->purifier->purify( $this->data['val']);\n //$dtl['dtl_Value'] = htmlspecialchars_decode( $this->data['val'] );\n }else{\n $dtl['dtl_Value'] = $this->data['val'];\n }\n\n }\n\n if(@$this->data['ulfID']>0){\n $dtl['dtl_UploadedFileID'] = $this->data['ulfID'];\n }\n\n $undefinedFieldsRecIDs = array();//limit not defined\n $processedRecIDs = array();//success\n $limitedRecIDs = array();//over limit - skip\n $sqlErrors = array();\n\n foreach ($this->recIDs as $recID) {\n $recID = intval($recID);//redundant for snyk\n //check field limit for this record\n $query = \"select rec_RecTypeID, tmp.cnt from Records \".\n \"left join (select dtl_RecID as recID, count(dtl_ID) as cnt \".\n \"from recDetails \".\n \"where dtl_RecID = $recID and dtl_DetailTypeID = $dtyID group by dtl_RecID) as tmp on rec_ID = tmp.recID \".\n \"where rec_ID = $recID\";\n\n $res = $mysqli->query($query);\n if(!$res){\n array_push($undefinedFieldsRecIDs, $recID);//cannot retrieve limit\n $sqlErrors[$recID] = $mysqli->error;\n continue;\n }\n\n $row = $res->fetch_row();\n\n $rectype_ID = $row[0];\n\n if (!array_key_exists($rectype_ID,$rtyLimits)) { //limit not defined\n array_push($undefinedFieldsRecIDs, $recID);\n continue;\n }elseif (intval($rtyLimits[$rectype_ID])>0 && $row[1]>0 && ($rtyLimits[$rectype_ID] - $row[1]) < 1){\n array_push($limitedRecIDs, $recID);//over limit - skip\n continue;\n }\n\n //limit ok so insert field\n $dtl['dtl_RecID'] = $recID;\n $ret = mysql__insertupdate($mysqli, 'recDetails', 'dtl', $dtl);\n\n if (!is_numeric($ret)) {\n $sqlErrors[$recID] = $ret;\n continue;\n }\n array_push($processedRecIDs, $recID);\n //update record edit date\n $rec_update['rec_ID'] = $recID;\n $ret = mysql__insertupdate($mysqli, 'Records', 'rec', $rec_update);\n if (!is_numeric($ret)) {\n $sqlErrors[$recID] = ERR_REC_MODDATE.$ret;\n }else{\n //update record title\n if(!recordUpdateTitle($this->system, $recID, $rectype_ID, null)){\n $sqlErrors[$recID] = ERR_REC_TITLE;\n }\n }\n }\n\n $this->_assignTagsAndReport('processed', $processedRecIDs, $baseTag);\n $this->_assignTagsAndReport('undefined', $undefinedFieldsRecIDs, $baseTag);\n $this->_assignTagsAndReport('limited', $limitedRecIDs, $baseTag);\n $this->_assignTagsAndReport('errors', $sqlErrors, $baseTag);\n\n\n\n return $this->result_data;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function sendWithoutRendering(MailerInterface $mailer = null): static\n {\n // filter email addresses\n\n // ... Remove headers that would otherwise be duplicated\n // $message->getHeaders()->remove('To');\n // $message->getHeaders()->remove('Subject'); ....\n\n $recipients = [];\n\n foreach (['To', 'Cc', 'Bcc', 'ReplyTo'] as $key) {\n $recipients[$key] = null;\n $getterName = 'get' . $key;\n $addresses = $this->$getterName();\n\n if ($addresses) {\n $addresses = $this->filterLogAddresses($addresses);\n /** @var MailboxListHeader|null $header */\n $header = $this->getHeaders()->get(strtolower($key));\n if ($header) {\n $header->setAddresses($addresses);\n }\n }\n\n $addresses = $this->$getterName();\n $recipients[$key] = $addresses;\n }\n\n $sendingFailedException = null;\n if ($mailer === null) {\n try {\n //if no mailer given, get default mailer from container\n $mailer = Pimcore::getContainer()->get(Mailer::class);\n } catch (Exception $e) {\n $sendingFailedException = $e;\n }\n }\n\n if (empty($this->getFrom()) && $hostname = Tool::getHostname()) {\n // set default \"from\" address\n $this->from('no-reply@' . $hostname);\n }\n\n $event = new MailEvent($this, [\n 'mailer' => $mailer,\n ]);\n\n Pimcore::getEventDispatcher()->dispatch($event, MailEvents::PRE_SEND);\n\n if ($event->hasArgument('mailer') && !$sendingFailedException) {\n $mailer = $event->getArgument('mailer');\n\n try {\n $mailer->send($this);\n } catch (Exception $e) {\n $sendingFailedException = new Exception($e->getMessage(), 0, $e);\n }\n }\n\n if ($this->loggingIsEnabled()) {\n if (Pimcore::inDebugMode() && !$this->ignoreDebugMode) {\n $recipients = $this->getDebugMailRecipients($recipients);\n }\n\n Pimcore::getEventDispatcher()->dispatch($event, MailEvents::PRE_LOG);\n\n try {\n $this->lastLogEntry = MailHelper::logEmail($this, $recipients, $sendingFailedException === null ? null : $sendingFailedException->getMessage());\n } catch (Exception $e) {\n Logger::emerg(\"Couldn't log Email\");\n }\n }\n\n if ($sendingFailedException instanceof Exception) {\n throw $sendingFailedException;\n }\n\n return $this;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['initialFill'])) {\n $this->setInitialFill($data['initialFill']);\n }\n if (isset($data['dispenseInterval'])) {\n $this->setDispenseInterval($data['dispenseInterval']);\n }\n if (isset($data['validityPeriod'])) {\n $this->setValidityPeriod($data['validityPeriod']);\n }\n if (isset($data['numberOfRepeatsAllowed'])) {\n $this->setNumberOfRepeatsAllowed($data['numberOfRepeatsAllowed']);\n }\n if (isset($data['quantity'])) {\n $this->setQuantity($data['quantity']);\n }\n if (isset($data['expectedSupplyDuration'])) {\n $this->setExpectedSupplyDuration($data['expectedSupplyDuration']);\n }\n if (isset($data['performer'])) {\n $this->setPerformer($data['performer']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function authenticateAction()\n {\n $request = $this->getRequest();\n $translator = $this->getServiceManager()->get('translator');\n $melisCoreAuth = $this->getServiceManager()->get('MelisCoreAuth');\n $melisMelisCoreConfig = $this->getServiceManager()->get('MelisCoreConfig');\n $userTable = $this->getServiceManager()->get('MelisCoreTableUser');\n $pathAppConfigForm = '/meliscore/forms/meliscore_login';\n\n // Creating the Laminas Form to validate datas\n $appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm);\n $factory = new \\Laminas\\Form\\Factory();\n $loginForm = $factory->createForm($appConfigForm);\n\n if ($request->isPost()) {\n $postValues = $request->getPost()->toArray();\n\n $loginForm->setData($postValues);\n\n // Validate datas\n if ($loginForm->isValid()) {\n //try using user email\n if(filter_var($postValues['usr_login'], FILTER_VALIDATE_EMAIL)){\n $userData = $userTable->getEntryByField('usr_email', $postValues['usr_login'])->current();\n /**\n * If user use his/her email to login, we update the adapter identity column to email\n */\n if(!empty($userData)) {\n $dbAdapter = $this->getServiceManager()->get(Adapter::class);\n $dbTableAuthAdapter = new DbTable($dbAdapter);\n $dbTableAuthAdapter->setTableName('melis_core_user')\n ->setIdentityColumn('usr_email')\n ->setCredentialColumn('usr_password');\n\n $melisCoreAuth->setAdapter($dbTableAuthAdapter);\n }\n }else {//try user login\n $userData = $userTable->getEntryByField('usr_login', $postValues['usr_login'])->current();\n }\n\n if (!empty($userData)) {\n\n /**\n * PASSWORD UPDATE - June 05, 2017\n * description: the following code below checks if the user's password is currently still on MD5,\n * if it's on MD5, it will still accept it, once correctly matched then it will update the user's password\n * encryption.\n */\n\n // @var $requiresPasswordReset - Flag for password update when successfully logged-in\n $requiresPasswordReset = false;\n // @var $password - user provided password\n $password = $postValues['usr_password'];\n // @var $newPassword - variable holder for new password encryption\n $newPassword = null;\n // @var $md5Regex - regular expression for checking if the password in the user table is on MD5\n $md5Regex = '/^[a-f0-9]{32}$/';\n // @var $needReset - Flag if user need's to use the forgot password link\n $needReset = false;\n // @var $isPassExpired - Flag if user need's to renew password\n $isPassExpired = false;\n\n // if the user password in the user table is on MD5\n if (preg_match($md5Regex, $userData->usr_password)) {\n // set $requiresPasswordReset flag to \"true\" to update to new password encryption\n $requiresPasswordReset = true;\n // encrypt the password to new encryption\n $newPassword = $melisCoreAuth->encryptPassword($password);\n // set the MD5 value of the user provided password, to match its' value to the user table password field\n $password = md5($postValues['usr_password']);\n } else {\n // check if the user password in user table is already in the new password encryption algorithm\n if (strlen($userData->usr_password) != 60) {\n // get the 'use_mcrypt' config\n $useMcrypt = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['use_mcrypt'];\n // encrypt the password to new encryption\n $newPassword = $melisCoreAuth->encryptPassword($password);\n\n /**\n * if 'use_mcrypt' is set to \"true\", then we'll use the mcrypt API for password checking,\n * however, this will still update the password to new password encryption.\n *\n * WARNING: mcrypt API is deprecated on PHP 7.1\n */\n if ($useMcrypt) {\n // salt config\n $salt = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['salt'];\n // hash_method config\n $hash = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['hash_method'];\n\n $enc = new \\Laminas\\Crypt\\BlockCipher(new \\Laminas\\Crypt\\Symmetric\\Mcrypt([\n 'algo' => 'aes',\n 'mode' => 'cfb',\n 'hash' => $hash,\n ]));\n $enc->setKey($salt);\n\n // get the encrypted password value from the user table\n $userEncPassword = $userData->usr_password;\n // get the decrypted password value from the user table\n $decryptedPassword = $enc->decrypt($userData->usr_password);\n\n // try to login using AES SHA256 by matching the decrypted user password to the user provided password\n if ($password == $decryptedPassword) {\n // set $requiresPasswordReset flag to \"true\" to update to new password encryption\n $requiresPasswordReset = true;\n // encrypt the password to new encryption\n $newPassword = $melisCoreAuth->encryptPassword($password);\n // set the MD5 value of the user provided password, to match its' value to the user table password field\n $password = $userEncPassword;\n }\n } else {\n // asked the password to reset their password (by using \"forgot password\" link)\n $needReset = true;\n }\n } else {\n $userPassword = $userData->usr_password;\n if ($melisCoreAuth->isPasswordCorrect($password, $userPassword)) {\n // this will be used in setCredential method\n $password = $userPassword;\n $passwordHistory = $this->getServiceManager()->get('MelisUpdatePasswordHistoryService');\n $userLastPasswordUpdatedDate = $passwordHistory->getLastPasswordUpdatedDate($userData->usr_id)[0]['uph_password_updated_date'];\n\n $file = $_SERVER['DOCUMENT_ROOT'] . '/../vendor/melisplatform/melis-core/config/app.login.php';\n\n if (file_exists($file)) {\n $config = $this->getServiceManager()->get('MelisCoreConfig')->getItem('meliscore/datas/login');\n\n if (!empty($config['password_validity_status']) && !empty($config['password_validity_lifetime'])) {\n $passwordValidityLifetime = $config['password_validity_lifetime'];\n $passwordExpiryDate = date('Y-m-d H:i:s', strtotime($userLastPasswordUpdatedDate . '+' . $passwordValidityLifetime . ' days'));\n $currentDate = date('Y-m-d H:i:s');\n \n if (strtotime($currentDate) > strtotime($passwordExpiryDate)) {\n $isPassExpired = true;\n }\n }\n }\n }\n }\n }\n\n if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/../vendor/melisplatform/melis-core/config/app.login.php')) {\n $config = $this->getServiceManager()->get('MelisCoreConfig')->getItem('meliscore/datas/login');\n\n // check first if login account lock option is true and if user account has been deactivated and also if lock type selected is timer\n // if it is the case, check if duration for the login lock has lapsed, if it has then user account gets reactivated\n if (isset($config['login_account_lock_status']) \n && !empty($config['login_account_lock_status']) \n && $config['login_account_type_of_lock'] == 'timer'\n && $userData->usr_status == self::USER_INACTIVE) {\n $melisCoreTableLogType = $this->getServiceManager()->get('MelisCoreTableLogType');\n $melisCoreTableLog = $this->getServiceManager()->get('MelisCoreTableLog');\n $logTypeId = current($melisCoreTableLogType->getEntryByField('logt_code', self::ACCOUNT_LOCKED)->toArray())['logt_id'];\n $dateAccountWasLocked = $melisCoreTableLog->getDateAccountWasLocked($logTypeId, $userData->usr_id);\n\n $days = (int) $config['login_account_duration_days']; \n $hours = (int) $config['login_account_duration_hours']; \n $minutes = (int) $config['login_account_duration_minutes'];\n $days += floor($hours / 24);\n $hours %= 24;\n\n // Calculate the total seconds\n $totalInSeconds = ($days * 24 * 60 * 60) + ($hours * 60 * 60) + ($minutes * 60);\n $interval = new DateInterval('PT' . $totalInSeconds . 'S');\n $accountWillUnlockDateTime = (new DateTime($dateAccountWasLocked))->add($interval)->format('Y-m-d H:i:s');\n $currentDateTime = (new DateTime('now'))->format('Y-m-d H:i:s');\n\n // if current date time is higher that means account is now unlocked \n if ($currentDateTime > $accountWillUnlockDateTime) {\n $melisUserTable = $this->getServiceManager()->get('MelisCore\\Model\\Tables\\MelisUserTable');\n // activate user's status\n $userData->usr_status = self::USER_ACTIVE;\n $melisUserTable->save(['usr_status' => $userData->usr_status], $userData->usr_id);\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_failed_too_many_failed_attempts')],\n 'textTitle' => 'Account unlocked',\n 'textMessage' => 'Account unlocked',\n 'datas' => [],\n ];\n $this->getEventManager()->trigger('meliscore_login_attempt_end', $this, array_merge($result, ['typeCode' => self::ACCOUNT_UNLOCKED, 'itemId' => $userData->usr_id]));\n }\n }\n }\n\n // If user is active\n if ($userData->usr_status == self::USER_ACTIVE) {\n if(!$isPassExpired) {\n if (!$needReset) {\n $melisCoreAuth->getAdapter()->setIdentity($postValues['usr_login'])\n ->setCredential($password);\n\n $result = $melisCoreAuth->authenticate();\n\n if ($result->isValid()) {\n $user = $melisCoreAuth->getAdapter()->getResultRowObject();\n\n // Update the rights of the user if it's not a custom role\n if ($user->usr_role_id != self::ROLE_ID_CUSTOM) {\n // Get rights from Role table\n $rightsXML = '';\n $tableUserRole = $this->getServiceManager()->get('MelisCoreTableUserRole');\n $datasRole = $tableUserRole->getEntryById($user->usr_role_id);\n if ($datasRole) {\n $datasRole = $datasRole->current();\n if (!empty($datasRole)) {\n $user->usr_rights = $datasRole->urole_rights;\n }\n }\n }\n\n // Write session\n $melisCoreAuth->getStorage()->write($user);\n\n // Update Melis BO locale\n $melisLangTable = $this->getServiceManager()->get('MelisCore\\Model\\Tables\\MelisLangTable');\n $datasLang = $melisLangTable->getEntryById($user->usr_lang_id);\n\n\n if (!empty($datasLang->current())) {\n $datasLang = $datasLang->current();\n $container = new Container('meliscore');\n $container['melis-lang-id'] = $user->usr_lang_id;\n $container['melis-lang-locale'] = $datasLang->lang_locale;\n }\n\n // update last login\n $loggedInDate = date('Y-m-d H:i:s');\n $this->getEventManager()->trigger('melis_core_auth_login_ok', $this, [\n 'login_date' => $loggedInDate,\n 'usr_id' => $user->usr_id,\n ]);\n\n // update user password if the password is on MD5\n if ($requiresPasswordReset) {\n $userTable->save([\n 'usr_password' => $newPassword,\n ], $userData->usr_id);\n \n $response = [];\n $response['success'] = true;\n $response['datas']['usr_id'] = $userData->usr_id;\n $response['datas']['usr_password'] = $newPassword;\n \n $this->getEventManager()->trigger('meliscore_update_password_history', $this, $response);\n }\n \n // Retrieving recent user logs on database\n $this->getEventManager()->trigger('meliscore_get_recent_user_logs', $this, []);\n \n // set same site cookie in built in php cookie\n // check if the user clicked remember me button\n $rememberMe = (int) $request->getPost('remember');\n if ($rememberMe == 1) {\n $this->rememberMe($postValues['usr_login'], $postValues['usr_password']);\n } else {\n $this->forgetMe($postValues['usr_login'], $postValues['usr_password']);\n }\n \n $result = [\n 'success' => true,\n 'errors' => [],\n ];\n } else { \n if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/../vendor/melisplatform/melis-core/config/app.login.php')) {\n $config = $this->getServiceManager()->get('MelisCoreConfig')->getItem('meliscore/datas/login');\n }\n \n // if login account lock is activated\n if (isset($config['login_account_lock_status']) && !empty($config['login_account_lock_status'])) {\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_failed_too_many_failed_attempts')],\n 'textTitle' => 'Wrong credentials on login',\n 'textMessage' => 'Wrong credentials on login',\n 'datas' => [],\n ];\n\n // log it everytime user has input wrong login credentials\n $this->getEventManager()->trigger('meliscore_login_attempt_end', $this, array_merge($result, ['typeCode' => self::WRONG_LOGIN_CREDENTIALS, 'itemId' => $userData->usr_id]));\n \n $melisCoreUserService = $this->getServiceManager()->get('MelisCoreUser');\n $userLastLoggedInDate = $melisCoreUserService->getUserLastLoggedInDate($userData->usr_id);\n $passwordHistory = $this->getServiceManager()->get('MelisUpdatePasswordHistoryService');\n $userLastPasswordUpdatedDate = $passwordHistory->getLastPasswordUpdatedDate($userData->usr_id)[0]['uph_password_updated_date'];\n $melisCoreTableLogType = $this->getServiceManager()->get('MelisCoreTableLogType');\n $melisCoreTableLog = $this->getServiceManager()->get('MelisCoreTableLog');\n \n if (empty($melisCoreTableLogType->getEntryByField('logt_code', self::ACCOUNT_UNLOCKED)->toArray())) {\n $dateAccountWasUnlocked = null;\n } else {\n $logTypeId = current($melisCoreTableLogType->getEntryByField('logt_code', self::ACCOUNT_UNLOCKED)->toArray())['logt_id'];\n $dateAccountWasUnlocked = $melisCoreTableLog->getDateAccountWasUnlocked($logTypeId, $userData->usr_id);\n }\n\n $logTypeId = current($melisCoreTableLogType->getEntryByField('logt_code', self::WRONG_LOGIN_CREDENTIALS)->toArray())['logt_id'];\n\n // check which is more recent, user logged in date, user password updated date or date account was unlocked\n // then use it as basis for checking the number of failed login attempts\n $date = max($userLastLoggedInDate, $userLastPasswordUpdatedDate, $dateAccountWasUnlocked);\n $numberOfFailedLoginAttempts = $melisCoreTableLog->getFailedLoginAttempts($logTypeId, $userData->usr_id, $date);\n\n if ($numberOfFailedLoginAttempts >= $config['login_account_lock_number_of_attempts']) {\n $melisUserTable = $this->getServiceManager()->get('MelisCore\\Model\\Tables\\MelisUserTable');\n \n // deactivate user's status\n $melisUserTable->save(['usr_status' => self::USER_INACTIVE], $userData->usr_id);\n $result['textTitle'] = 'Account locked';\n $result['textMessage'] = 'Account locked';\n $result['accountLocked'] = true;\n $result['accountLockType'] = $config['login_account_type_of_lock'];\n $result['accountLockAdminEmail'] = $config['login_account_admin_email'];\n $result['accountLockDurationInDays'] = $config['login_account_duration_days'];\n $result['accountLockDurationInHours'] = $config['login_account_duration_hours'];\n $result['accountLockDurationInMinutes'] = $config['login_account_duration_minutes'];\n\n // log it when user account has been locked\n $this->getEventManager()->trigger('meliscore_login_attempt_end', $this, array_merge($result, ['typeCode' => self::ACCOUNT_LOCKED, 'itemId' => $userData->usr_id]));\n }\n } else {\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],\n 'textTitle' => 'Wrong credentials on login',\n 'textMessage' => 'Wrong credentials on login',\n 'datas' => [],\n ];\n\n // log it everytime user has input wrong login credentials\n $this->getEventManager()->trigger('meliscore_login_attempt_end', $this, array_merge($result, ['typeCode' => self::WRONG_LOGIN_CREDENTIALS, 'itemId' => $userData->usr_id]));\n }\n }\n } else {\n $result = [\n 'success' => false,\n 'require_reset_password' => true,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_password_enc_update')],\n ];\n }\n } else {\n /** @var MelisCoreCreatePasswordService $melisCreatePwdSvc */\n $melisCreatePwdSvc = $this->getServiceManager()->get('MelisCoreCreatePassword');\n $url = $melisCreatePwdSvc->createExpiredPasswordRequest($userData->usr_login,$userData->usr_email);\n\n $result = [\n 'success' => false,\n 'password_expired' => true,\n 'renew_pass_url' => $url,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_password_enc_update')],\n ];\n }\n } else {\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],\n ];\n\n if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/../vendor/melisplatform/melis-core/config/app.login.php')) {\n $config = $this->getServiceManager()->get('MelisCoreConfig')->getItem('meliscore/datas/login');\n }\n\n // if login account lock is activated\n if (isset($config['login_account_lock_status']) && !empty($config['login_account_lock_status'])) {\n $melisCoreUserService = $this->getServiceManager()->get('MelisCoreUser');\n $userLastLoggedInDate = $melisCoreUserService->getUserLastLoggedInDate($userData->usr_id);\n $passwordHistory = $this->getServiceManager()->get('MelisUpdatePasswordHistoryService');\n $userLastPasswordUpdatedDate = $passwordHistory->getLastPasswordUpdatedDate($userData->usr_id)[0]['uph_password_updated_date'];\n $date = ($userLastLoggedInDate > $userLastPasswordUpdatedDate) ? $userLastLoggedInDate : $userLastPasswordUpdatedDate;\n $melisCoreTableLogType = $this->getServiceManager()->get('MelisCoreTableLogType');\n $melisCoreTableLog = $this->getServiceManager()->get('MelisCoreTableLog');\n $logTypeId = current($melisCoreTableLogType->getEntryByField('logt_code', self::WRONG_LOGIN_CREDENTIALS)->toArray())['logt_id'];\n $numberOfFailedLoginAttempts = $melisCoreTableLog->getFailedLoginAttempts($logTypeId, $userData->usr_id, $date);\n \n if ($numberOfFailedLoginAttempts >= $config['login_account_lock_number_of_attempts']) {\n $melisUserTable = $this->getServiceManager()->get('MelisCore\\Model\\Tables\\MelisUserTable');\n\n // deactivate user's status\n $melisUserTable->save(['usr_status' => self::USER_INACTIVE], $userData->usr_id);\n $result['accountLocked'] = true;\n $result['accountLockType'] = $config['login_account_type_of_lock'];\n $result['accountLockAdminEmail'] = $config['login_account_admin_email'];\n $result['accountLockDurationInDays'] = $config['login_account_duration_days'];\n $result['accountLockDurationInHours'] = $config['login_account_duration_hours'];\n $result['accountLockDurationInMinutes'] = $config['login_account_duration_minutes'];\n }\n }\n }\n } else {\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],\n ];\n }\n } else {\n $result = [\n 'success' => false,\n 'errors' => [$loginForm->getMessages()],\n ];\n }\n } else {\n $result = [\n 'success' => false,\n 'errors' => ['empty' => $translator->translate('tr_meliscore_login_errors_Empty datas')],\n ];\n }\n\n return new JsonModel($result);\n }", "smellKey": "S3776", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public function handle()\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $mainasset_entities_id = 0;\n // get entity of the parent asset\n if (isset($this->main_asset)) {\n $mainasset_entities_id = $this->main_asset->getEntityID();\n }\n\n // find configuration for main asset entity in which entity we must create the software\n $strategy = Entity::getUsedConfig(\n 'entities_strategy_software',\n $mainasset_entities_id\n );\n $entities_id_software = Entity::getUsedConfig(\n 'entities_strategy_software',\n $mainasset_entities_id,\n 'entities_id_software',\n 0\n );\n\n if ($strategy == Entity::CONFIG_NEVER) {\n // Configuration says that software can be created in the computer's entity\n $this->entities_id = $mainasset_entities_id;\n $this->is_recursive = 0;\n } else {\n // Software should be created in a different entity than main asset one\n $this->entities_id = $entities_id_software;\n $this->is_recursive = 1;\n }\n\n //Get operating system\n $operatingsystems_id = 0;\n\n if (isset($this->extra_data['\\Glpi\\Inventory\\Asset\\OperatingSystem'])) {\n if (is_array($this->extra_data['\\Glpi\\Inventory\\Asset\\OperatingSystem'])) {\n $os = $this->extra_data['\\Glpi\\Inventory\\Asset\\OperatingSystem'][0];\n } else {\n $os = $this->extra_data['\\Glpi\\Inventory\\Asset\\OperatingSystem'];\n }\n $operatingsystems_id = $os->getId();\n\n //add Operating System as Software\n $os_data = $os->getData()[0];\n $os_soft_data = new \\stdClass();\n $os_soft_data->name = $os_data->full_name ?? $os_data->name;\n $os_soft_data->arch = $os_data->arch ?? null;\n $os_soft_data->comment = null;\n $os_soft_data->manufacturers_id = 0;\n $os_soft_data->version = $os_data->version ?? '';\n\n $this->data[] = $os_soft_data;\n }\n\n $db_software = [];\n $db_software_wo_version = [];\n\n //Load existing software versions from db. Grab required fields\n //to build comparison key @see getFullCompareKey\n $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_items_softwareversions.id as item_soft_version_id',\n 'glpi_items_softwareversions.date_install as item_soft_version_date_install',\n 'glpi_softwares.id as softid',\n 'glpi_softwares.name',\n 'glpi_softwareversions.id AS versionid',\n 'glpi_softwareversions.name AS version',\n 'glpi_softwareversions.arch',\n 'glpi_softwares.entities_id',\n 'glpi_softwarecategories.name AS softwarecategories_id',\n 'glpi_softwares.is_recursive',\n 'glpi_softwareversions.operatingsystems_id',\n 'glpi_manufacturers.name AS manufacturers_id'\n ],\n 'FROM' => 'glpi_items_softwareversions',\n 'LEFT JOIN' => [\n 'glpi_softwareversions' => [\n 'ON' => [\n 'glpi_items_softwareversions' => 'softwareversions_id',\n 'glpi_softwareversions' => 'id'\n ]\n ],\n 'glpi_softwares' => [\n 'ON' => [\n 'glpi_softwareversions' => 'softwares_id',\n 'glpi_softwares' => 'id'\n ]\n ],\n 'glpi_softwarecategories' => [\n 'ON' => [\n 'glpi_softwares' => 'softwarecategories_id',\n 'glpi_softwarecategories' => 'id'\n ]\n ],\n 'glpi_manufacturers' => [\n 'ON' => [\n 'glpi_softwares' => 'manufacturers_id',\n 'glpi_manufacturers' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_items_softwareversions.items_id' => $this->item->fields['id'],\n 'glpi_items_softwareversions.itemtype' => $this->item->getType(),\n 'glpi_items_softwareversions.is_dynamic' => 1\n ]\n ]);\n\n foreach ($iterator as $data) {\n $item_soft_v_id = $data['item_soft_version_id'];\n $item_soft_v_date_install = $data['item_soft_version_date_install'];\n unset($data['item_soft_version_id']);\n if ($data['manufacturers_id'] == null) {\n $data['manufacturers_id'] = 0;\n }\n $key_w_version = $this->getFullCompareKey((object)$data);\n $key_wo_version = $this->getFullCompareKey((object)$data, false);\n $db_software[$key_w_version] = [\n 'id' => $item_soft_v_id,\n 'date_install' => $item_soft_v_date_install,\n ];\n $db_software_wo_version[$key_wo_version] = [\n 'versionid' => $data['versionid'],\n 'softid' => $data['softid'],\n 'version' => $data['version'],\n 'name' => $data['name'],\n ];\n $db_software_data[$key_wo_version] = [\n 'softid' => $data['softid'],\n 'softwarecategories' => $data['softwarecategories_id'],\n 'name' => $data['name'],\n 'manufacturer' => $data['manufacturers_id'],\n ];\n }\n\n //check for existing links\n $count_import = count($this->data);\n foreach ($this->data as $k => &$val) {\n //operating system id is not known before handle(); set it in value\n $val->operatingsystems_id = $operatingsystems_id;\n\n $val->entities_id = $this->entities_id;\n $val->is_recursive = $this->is_recursive;\n\n $key_w_version = $this->getFullCompareKey($val);\n $key_wo_version = $this->getFullCompareKey($val, false);\n\n $old_version = $db_software_wo_version[$key_wo_version]['version'] ?? \"\";\n $new_version = $val->version;\n\n $dedup_vkey = $key_w_version . $this->getVersionKey($val, 0);\n\n //update softwarecategories if needed\n //reconciles the software without the version (no needed here)\n $sckey = md5('softwarecategories_id' . ($val->softwarecategories_id ?? 0));\n if (\n isset($db_software_data[$key_wo_version])\n && $db_software_data[$key_wo_version]['softwarecategories'] != ($this->known_links[$sckey] ?? 0)\n ) {\n $software_to_update = new GSoftware();\n $software_to_update->update([\n \"id\" => $db_software_data[$key_wo_version]['softid'],\n \"softwarecategories_id\" => ($this->known_links[$sckey] ?? 0)\n ], 0);\n }\n\n //update date_install if needed\n //reconciles the software with the version (needed here)\n if (\n property_exists($val, 'date_install')\n && isset($db_software[$key_w_version])\n && $db_software[$key_w_version]['date_install'] != $val->date_install\n ) {\n $software_version = new Item_SoftwareVersion();\n $software_version->update([\n \"id\" => $db_software[$key_w_version]['id'],\n \"date_install\" => $val->date_install\n ], 0);\n }\n\n if (isset($db_software[$key_w_version])) {\n // software exist with the same version\n unset($this->data[$k]);\n unset($db_software[$key_w_version]);\n unset($db_software_wo_version[$key_wo_version]);\n $this->current_versions[$dedup_vkey] = true;\n } else {\n if ($old_version != \"\" && $old_version != $new_version) {\n // software exist but with different version\n $this->updated_versions[$key_wo_version] = [\n 'name' => $val->name,\n 'old' => $old_version,\n 'new' => $new_version,\n ];\n\n unset($db_software_wo_version[$key_wo_version]);\n } elseif (isset($this->current_versions[$dedup_vkey])) {\n // software addition already done (duplicate)\n unset($this->data[$k]);\n } else {\n // software addition\n $this->current_versions[$dedup_vkey] = true;\n $this->added_versions[$key_wo_version] = [\n 'name' => $val->name,\n 'version' => $new_version,\n ];\n }\n }\n }\n\n // track deleted versions (without those which version changed)\n $this->deleted_versions = array_values($db_software_wo_version);\n\n if (count($db_software) > 0 && (!$this->main_asset || !$this->main_asset->isPartial() || $this->main_asset->isPartial() && $count_import)) {\n //not found version means soft has been removed or updated, drop it\n $DB->delete(\n 'glpi_items_softwareversions',\n [\n 'id' => array_column($db_software, 'id')\n ]\n );\n }\n\n // store changes to logs\n $this->logSoftwares();\n\n if (!count($this->data)) {\n //nothing to do!\n return;\n }\n\n try {\n $this->populateSoftware();\n $this->storeSoftware();\n $this->populateVersions();\n $this->storeVersions();\n $this->storeAssetLink();\n } catch (\\Throwable $e) {\n throw $e;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function _process_fields($create_table = FALSE)\n\t{\n\t\t$fields = array();\n\n\t\tforeach ($this->fields as $key => $attributes)\n\t\t{\n\t\t\tif (is_int($key) && ! is_array($attributes))\n\t\t\t{\n\t\t\t\t$fields[] = array('_literal' => $attributes);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$attributes = array_change_key_case($attributes, CASE_UPPER);\n\n\t\t\tif ($create_table === TRUE && empty($attributes['TYPE']))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tisset($attributes['TYPE']) && $this->_attr_type($attributes);\n\n\t\t\t$field = array(\n\t\t\t\t'name'\t\t\t=> $key,\n\t\t\t\t'new_name'\t\t=> isset($attributes['NAME']) ? $attributes['NAME'] : NULL,\n\t\t\t\t'type'\t\t\t=> isset($attributes['TYPE']) ? $attributes['TYPE'] : NULL,\n\t\t\t\t'length'\t\t=> '',\n\t\t\t\t'unsigned'\t\t=> '',\n\t\t\t\t'null'\t\t\t=> '',\n\t\t\t\t'unique'\t\t=> '',\n\t\t\t\t'default'\t\t=> '',\n\t\t\t\t'auto_increment'\t=> '',\n\t\t\t\t'_literal'\t\t=> FALSE\n\t\t\t);\n\n\t\t\tisset($attributes['TYPE']) && $this->_attr_unsigned($attributes, $field);\n\n\t\t\tif ($create_table === FALSE)\n\t\t\t{\n\t\t\t\tif (isset($attributes['AFTER']))\n\t\t\t\t{\n\t\t\t\t\t$field['after'] = $attributes['AFTER'];\n\t\t\t\t}\n\t\t\t\telseif (isset($attributes['FIRST']))\n\t\t\t\t{\n\t\t\t\t\t$field['first'] = (bool) $attributes['FIRST'];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$this->_attr_default($attributes, $field);\n\n\t\t\tif (isset($attributes['NULL']))\n\t\t\t{\n\t\t\t\tif ($attributes['NULL'] === TRUE)\n\t\t\t\t{\n\t\t\t\t\t$field['null'] = empty($this->_null) ? '' : ' '.$this->_null;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$field['null'] = ' NOT NULL';\n\t\t\t\t}\n\t\t\t}\n\t\t\telseif ($create_table === TRUE)\n\t\t\t{\n\t\t\t\t$field['null'] = ' NOT NULL';\n\t\t\t}\n\n\t\t\t$this->_attr_auto_increment($attributes, $field);\n\t\t\t$this->_attr_unique($attributes, $field);\n\n\t\t\tif (isset($attributes['COMMENT']))\n\t\t\t{\n\t\t\t\t$field['comment'] = $this->db->escape($attributes['COMMENT']);\n\t\t\t}\n\n\t\t\tif (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT']))\n\t\t\t{\n\t\t\t\tswitch (strtoupper($attributes['TYPE']))\n\t\t\t\t{\n\t\t\t\t\tcase 'ENUM':\n\t\t\t\t\tcase 'SET':\n\t\t\t\t\t\t$attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']);\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t$field['length'] = is_array($attributes['CONSTRAINT'])\n\t\t\t\t\t\t\t? '('.implode(',', $attributes['CONSTRAINT']).')'\n\t\t\t\t\t\t\t: '('.$attributes['CONSTRAINT'].')';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$fields[] = $field;\n\t\t}\n\n\t\treturn $fields;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "Viko99_ventasci", "language": "php"} {"function": "public function forEachDocument(callable $callback): void\n {\n $internalProjectId = $this->project->getInternalId();\n\n $collections = match ($internalProjectId) {\n 'console' => $this->collections['console'],\n default => $this->collections['projects'],\n };\n\n foreach ($collections as $collection) {\n // Also skip cache collection because the we don't need to migrate\n // it and the $ids cause issues with the cursor pagination\n if ($collection['$collection'] !== Database::METADATA || $collection['$id'] === 'cache') {\n continue;\n }\n\n Console::log('Migrating Collection ' . $collection['$id'] . ':');\n\n \\Co\\run(function (array $collection, callable $callback) {\n foreach ($this->documentsIterator($collection['$id']) as $document) {\n go(function (Document $document, callable $callback) {\n if (empty($document->getId()) || empty($document->getCollection())) {\n return;\n }\n\n $old = $document->getArrayCopy();\n $new = call_user_func($callback, $document);\n\n if (is_null($new) || $new->getArrayCopy() == $old) {\n return;\n }\n\n try {\n $this->projectDB->updateDocument($document->getCollection(), $document->getId(), $document);\n } catch (\\Throwable $th) {\n Console::error('Failed to update document: ' . $th->getMessage());\n return;\n }\n }, $document, $callback);\n }\n }, $collection, $callback);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (isset($this->requestIdentifier)) {\n $json['requestIdentifier'] = $this->requestIdentifier;\n }\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->moduleUri)) {\n $json['moduleUri'] = $this->moduleUri;\n }\n if (isset($this->moduleCanonical)) {\n $json['moduleCanonical'] = $this->moduleCanonical;\n }\n if (isset($this->moduleCodeableConcept)) {\n $json['moduleCodeableConcept'] = $this->moduleCodeableConcept;\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->subject)) {\n $json['subject'] = $this->subject;\n }\n if (isset($this->encounter)) {\n $json['encounter'] = $this->encounter;\n }\n if (isset($this->occurrenceDateTime)) {\n $json['occurrenceDateTime'] = $this->occurrenceDateTime;\n }\n if (isset($this->performer)) {\n $json['performer'] = $this->performer;\n }\n if (0 < count($this->reasonCode)) {\n $json['reasonCode'] = [];\n foreach ($this->reasonCode as $reasonCode) {\n $json['reasonCode'][] = $reasonCode;\n }\n }\n if (0 < count($this->reasonReference)) {\n $json['reasonReference'] = [];\n foreach ($this->reasonReference as $reasonReference) {\n $json['reasonReference'][] = $reasonReference;\n }\n }\n if (0 < count($this->note)) {\n $json['note'] = [];\n foreach ($this->note as $note) {\n $json['note'][] = $note;\n }\n }\n if (0 < count($this->evaluationMessage)) {\n $json['evaluationMessage'] = [];\n foreach ($this->evaluationMessage as $evaluationMessage) {\n $json['evaluationMessage'][] = $evaluationMessage;\n }\n }\n if (isset($this->outputParameters)) {\n $json['outputParameters'] = $this->outputParameters;\n }\n if (isset($this->result)) {\n $json['result'] = $this->result;\n }\n if (0 < count($this->dataRequirement)) {\n $json['dataRequirement'] = [];\n foreach ($this->dataRequirement as $dataRequirement) {\n $json['dataRequirement'][] = $dataRequirement;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) {\n\t\t$file = new \\stdClass();\n\t\t$file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,\n\t\t\t$index, $content_range);\n\t\t$file->size = $this->fix_integer_overflow((int)$size);\n\t\t$file->type = $type;\n\t\tif ($this->validate($uploaded_file, $file, $error, $index)) {\n\t\t\t$this->handle_form_data($file, $index);\n\t\t\t$upload_dir = $this->get_upload_path();\n\t\t\tif (!$this->options['ftp'] && !is_dir($upload_dir)) {\n\t\t\t\tmkdir($upload_dir, $this->options['mkdir_mode'], true);\n\t\t\t}\n\t\t\t$file_path = $this->get_upload_path($file->name);\n\t\t\t$append_file = $content_range && is_file($file_path) &&\n\t\t\t\t$file->size > $this->get_file_size($file_path);\n\t\t\tif ($uploaded_file && is_uploaded_file($uploaded_file)) {\n\t\t\t\t// multipart/formdata uploads (POST method uploads)\n\t\t\t\tif ($append_file) {\n\t\t\t\t\tfile_put_contents(\n\t\t\t\t\t\t$file_path,\n\t\t\t\t\t\tfopen($uploaded_file, 'r'),\n\t\t\t\t\t\tFILE_APPEND\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tmove_uploaded_file($uploaded_file, $file_path);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif($this->get_file_size($uploaded_file) == $file->size){\n\t\t\t\t\tcopy($uploaded_file, $file_path);\n\t\t\t\t}else{\n\n\t\t\t\t\t// Non-multipart uploads (PUT method support)\n\t\t\t\t\tfile_put_contents(\n\t\t\t\t\t\t$file_path,\n\t\t\t\t\t\tfopen($this->options['input_stream'], 'r'),\n\t\t\t\t\t\t$append_file ? FILE_APPEND : 0\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$file_size = $this->get_file_size($file_path, $append_file);\n\t\t\t$file->path = $file_path;\n\t\t\tif ($file_size === $file->size) {\n\t\t\t\t$file->url = $this->get_download_url($file->name);\n\t\t\t\tif ($this->is_valid_image_file($file_path)) {\n\t\t\t\t\t$this->handle_image_file($file_path, $file);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$file->size = $file_size;\n\t\t\t\tif (!$content_range && $this->options['discard_aborted_uploads']) {\n\t\t\t\t\tunlink($file_path);\n\t\t\t\t\t$file->error = $this->get_error_message('abort');\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->set_additional_file_properties($file);\n\t\t}\n\t\treturn $file;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public function upload_action_process()\n {\n\n // Collect a manually set owner if this has been set\n // Used when want to manually assign the owning user/service such as the Direct mechanism\n $non_HTTP_owner = false;\n if ($this->manual_set_owner) {\n $non_HTTP_owner = $this->manual_set_owner;\n }\n\n $couchDB = false;\n $harddisk = false;\n if ($GLOBALS['document_storage_method'] == 0) {\n $harddisk = true;\n }\n if ($GLOBALS['document_storage_method'] == 1) {\n $couchDB = true;\n }\n\n if ($_POST['process'] != \"true\") {\n return;\n }\n\n $doDecryption = false;\n $encrypted = $_POST['encrypted'] ?? false;\n $passphrase = $_POST['passphrase'] ?? '';\n if (\n !$GLOBALS['hide_document_encryption'] &&\n $encrypted && $passphrase\n ) {\n $doDecryption = true;\n }\n\n if (is_numeric($_POST['category_id'])) {\n $category_id = $_POST['category_id'];\n } else {\n $category_id = 1;\n }\n\n $patient_id = 0;\n if (isset($_GET['patient_id']) && !$couchDB) {\n $patient_id = $_GET['patient_id'];\n } elseif (is_numeric($_POST['patient_id'])) {\n $patient_id = $_POST['patient_id'];\n }\n\n // ensure user has access to the category that is being uploaded to\n $skipUpload = false;\n if (!$this->isSkipAclCheck()) {\n $acoSpec = sqlQuery(\"SELECT `aco_spec` from `categories` WHERE `id` = ?\", [$category_id])['aco_spec'];\n if (AclMain::aclCheckAcoSpec($acoSpec) === false) {\n $error = xl(\"Not authorized to upload to the selected category.\\n\");\n $skipUpload = true;\n (new SystemLogger())->debug(\"An attempt was made to upload a document to an unauthorized category\", ['user-id' => $_SESSION['authUserID'], 'patient-id' => $patient_id, 'category-id' => $category_id]);\n }\n }\n\n if (!$skipUpload && !empty($_FILES['dicom_folder']['name'][0])) {\n // let's zip um up then pass along new zip\n $study_name = $_POST['destination'] ? (trim($_POST['destination']) . \".zip\") : 'DicomStudy.zip';\n $study_name = preg_replace('/\\s+/', '_', $study_name);\n $_POST['destination'] = \"\";\n $zipped = $this->zip_dicom_folder($study_name);\n if ($zipped) {\n $_FILES['file'] = $zipped;\n }\n // and off we go! just fall through and let routine\n // do its normal file processing..\n }\n\n $sentUploadStatus = array();\n if (!$skipUpload && count($_FILES['file']['name']) > 0) {\n $upl_inc = 0;\n\n foreach ($_FILES['file']['name'] as $key => $value) {\n $fname = $value;\n $error = \"\";\n if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {\n $fname = $value;\n if (empty($fname)) {\n $fname = htmlentities(\"<empty>\");\n }\n $error = xl(\"Error number\") . \": \" . $_FILES['file']['error'][$key] . \" \" . xl(\"occurred while uploading file named\") . \": \" . $fname . \"\\n\";\n if ($_FILES['file']['size'][$key] == 0) {\n $error .= xl(\"The system does not permit uploading files of with size 0.\") . \"\\n\";\n }\n } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {\n $error = xl(\"The system does not permit uploading files with MIME content type\") . \" - \" . mime_content_type($_FILES['file']['tmp_name'][$key]) . \".\\n\";\n } else {\n // Test for a zip of DICOM images\n if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {\n $za = new ZipArchive();\n $handler = $za->open($_FILES['file']['tmp_name'][$key]);\n if ($handler) {\n $mimetype = \"application/dicom+zip\";\n for ($i = 0; $i < $za->numFiles; $i++) {\n $stat = $za->statIndex($i);\n $fp = $za->getStream($stat['name']);\n if ($fp) {\n $head = fread($fp, 256);\n fclose($fp);\n if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.\n $mimetype = \"application/zip\";\n break;\n }\n unset($head);\n // if here -then a DICOM\n $parts = pathinfo($stat['name']);\n if ($parts['extension'] != \"dcm\" || empty($parts['extension'])) { // required extension for viewer\n $new_name = $parts['filename'] . \".dcm\";\n $za->renameIndex($i, $new_name);\n $za->renameName($parts['filename'], $new_name);\n }\n } else { // Rarely here\n $mimetype = \"application/zip\";\n break;\n }\n }\n $za->close();\n if ($mimetype == \"application/dicom+zip\") {\n sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!\n $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.\n }\n }\n }\n $tmpfile = fopen($_FILES['file']['tmp_name'][$key], \"r\");\n $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);\n fclose($tmpfile);\n if ($doDecryption) {\n $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);\n if ($filetext === false) {\n error_log(\"OpenEMR Error: Unable to decrypt a document since decryption failed.\");\n $filetext = \"\";\n }\n }\n if ($_POST['destination'] != '') {\n $fname = $_POST['destination'];\n }\n // test for single DICOM and assign extension if missing.\n if (strpos($filetext, 'DICM') !== false) {\n $mimetype = 'application/dicom';\n $parts = pathinfo($fname);\n if (!$parts['extension']) {\n $fname .= '.dcm';\n }\n }\n // set mimetype (if not already set above)\n if (empty($mimetype)) {\n $mimetype = mime_content_type($_FILES['file']['tmp_name'][$key]);\n }\n // if mimetype still empty, then do not upload the file\n if (empty($mimetype)) {\n $error = xl(\"Unable to discover mimetype, so did not upload \" . $_FILES['file']['tmp_name'][$key]) . \".\\n\";\n continue;\n }\n $d = new Document();\n $rc = $d->createDocument(\n $patient_id,\n $category_id,\n $fname,\n $mimetype,\n $filetext,\n empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],\n empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],\n $non_HTTP_owner,\n $_FILES['file']['tmp_name'][$key]\n );\n if ($rc) {\n $error .= $rc . \"\\n\";\n } else {\n $this->assign(\"upload_success\", \"true\");\n }\n $sentUploadStatus[] = $d;\n $this->assign(\"file\", $sentUploadStatus);\n }\n\n // Option to run a custom plugin for each file upload.\n // This was initially created to delete the original source file in a custom setting.\n $upload_plugin = $GLOBALS['OE_SITE_DIR'] . \"/documentUpload.plugin.php\";\n if (file_exists($upload_plugin)) {\n include_once($upload_plugin);\n }\n $upload_plugin_pp = 'documentUploadPostProcess';\n if (function_exists($upload_plugin_pp)) {\n $tmp = call_user_func($upload_plugin_pp, $value, $d);\n if ($tmp) {\n $error = $tmp;\n }\n }\n // Following is just an example of code in such a plugin file.\n /*****************************************************\n public function documentUploadPostProcess($filename, &$d) {\n $userid = $_SESSION['authUserID'];\n $row = sqlQuery(\"SELECT username FROM users WHERE id = ?\", array($userid));\n $owner = strtolower($row['username']);\n $dn = '1_' . ucfirst($owner);\n $filepath = \"/shared_network_directory/$dn/$filename\";\n if (@unlink($filepath)) return '';\n return \"Failed to delete '$filepath'.\";\n }\n *****************************************************/\n }\n }\n\n $this->assign(\"error\", $error);\n //$this->_state = false;\n $_POST['process'] = \"\";\n //return $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_upload.html\");\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function executeActions($output, $params, array $input = [])\n {\n if (count($this->actions)) {\n foreach ($this->actions as $action) {\n switch ($action->fields[\"action_type\"]) {\n case \"add_validation\":\n if (isset($output['_add_validation']) && !is_array($output['_add_validation'])) {\n $output['_add_validation'] = [$output['_add_validation']];\n }\n switch ($action->fields['field']) {\n case 'users_id_validate_requester_supervisor':\n $output['_add_validation'][] = 'requester_supervisor';\n break;\n\n case 'users_id_validate_assign_supervisor':\n $output['_add_validation'][] = 'assign_supervisor';\n break;\n\n case 'groups_id_validate':\n $output['_add_validation']['group'][] = $action->fields[\"value\"];\n break;\n\n case 'groups_id_validate_any':\n $output['_add_validation']['group_any'][] = $action->fields[\"value\"];\n break;\n\n case 'users_id_validate':\n $output['_add_validation'][] = $action->fields[\"value\"];\n break;\n\n case 'responsible_id_validate':\n $output['_add_validation'][] = 'requester_responsible';\n break;\n\n case 'validation_percent':\n $output[$action->fields[\"field\"]] = $action->fields[\"value\"];\n break;\n\n default:\n $output['_add_validation'][] = $action->fields[\"value\"];\n break;\n }\n break;\n\n case \"assign\":\n $output[$action->fields[\"field\"]] = $action->fields[\"value\"];\n\n // Special case of status\n if ($action->fields[\"field\"] === 'status') {\n // Add a flag to remember that status was forced by rule\n $output['_do_not_compute_status'] = true;\n }\n\n // Special case of users_id_requester\n if ($action->fields[\"field\"] === '_users_id_requester') {\n // Add groups of requester\n if (!isset($output['_groups_id_of_requester'])) {\n $output['_groups_id_of_requester'] = [];\n }\n foreach (Group_User::getUserGroups($action->fields[\"value\"]) as $g) {\n $output['_groups_id_of_requester'][$g['id']] = $g['id'];\n }\n }\n\n // Special case for _users_id_requester, _users_id_observer and _users_id_assign\n if (\n in_array(\n $action->fields[\"field\"],\n ['_users_id_requester', '_users_id_observer', '_users_id_assign']\n )\n ) {\n // must reset alternative_email field to prevent mix of user/email\n unset($output[$action->fields[\"field\"] . '_notif']);\n\n if ($action->fields[\"value\"] === 'requester_manager') {\n foreach ($input['_users_id_requester'] as $user_id) {\n $user = new User();\n $user->getFromDB($user_id);\n if (!empty($output[$action->fields[\"field\"]]) && !is_array($output[$action->fields[\"field\"]])) {\n $output[$action->fields[\"field\"]] = [$output[$action->fields[\"field\"]]];\n }\n if ($user->fields['users_id_supervisor'] > 0) {\n $output[$action->fields[\"field\"]][] = $user->fields['users_id_supervisor'];\n }\n }\n }\n }\n\n // special case of itil solution template\n if ($action->fields[\"field\"] == 'solution_template') {\n $output['_solutiontemplates_id'] = $action->fields[\"value\"];\n }\n\n // special case of appliance\n if ($action->fields[\"field\"] == \"assign_appliance\") {\n if (!array_key_exists(\"items_id\", $output) || $output['items_id'] == '0') {\n $output[\"items_id\"] = [];\n }\n $output[\"items_id\"][Appliance::getType()][] = $action->fields[\"value\"];\n }\n\n // Remove values that may have been added by any \"append\" rule action on same actor field.\n // Appended actors are stored on `_additional_*` keys.\n $actions = $this->getActions();\n $append_key = $actions[$action->fields[\"field\"]][\"appendto\"] ?? null;\n if (\n $append_key !== null\n && preg_match('/^_additional_/', $append_key) === 1\n && array_key_exists($append_key, $output)\n ) {\n unset($output[$append_key]);\n }\n\n break;\n\n case \"append\":\n $actions = $this->getActions();\n $value = $action->fields[\"value\"];\n if (\n isset($actions[$action->fields[\"field\"]][\"appendtoarray\"])\n && isset($actions[$action->fields[\"field\"]][\"appendtoarrayfield\"])\n ) {\n $value = $actions[$action->fields[\"field\"]][\"appendtoarray\"];\n $value[$actions[$action->fields[\"field\"]][\"appendtoarrayfield\"]]\n = $action->fields[\"value\"];\n }\n\n // special case of appliance\n if ($action->fields[\"field\"] === \"assign_appliance\") {\n if (!array_key_exists(\"items_id\", $output) || $output['items_id'] == '0') {\n $output[\"items_id\"] = [];\n }\n $output[\"items_id\"][Appliance::getType()][] = $value;\n } else {\n $output[$actions[$action->fields[\"field\"]][\"appendto\"]][] = $value;\n }\n\n // Special case of users_id_requester\n if ($action->fields[\"field\"] === '_users_id_requester') {\n // Add groups of requester\n if (!isset($output['_groups_id_of_requester'])) {\n $output['_groups_id_of_requester'] = [];\n }\n foreach (Group_User::getUserGroups($action->fields[\"value\"]) as $g) {\n $output['_groups_id_of_requester'][$g['id']] = $g['id'];\n }\n }\n\n if (\n in_array(\n $action->fields[\"field\"],\n ['_users_id_requester', '_users_id_observer', '_users_id_assign']\n )\n && $action->fields[\"value\"] === 'requester_manager'\n ) {\n foreach ($input['_users_id_requester'] as $user_id) {\n $user = new User();\n $user->getFromDB($user_id);\n if ($user->fields['users_id_supervisor'] > 0) {\n $output[$action->fields[\"field\"]][] = $user->fields['users_id_supervisor'];\n }\n }\n }\n break;\n\n case 'defaultfromuser':\n if (\n ( $action->fields['field'] == '_groups_id_requester')\n && isset($output['users_default_groups'])\n ) {\n $output['_groups_id_requester'] = $output['users_default_groups'];\n }\n if (\n ( $action->fields['field'] == '_groups_id_observer')\n && isset($output['users_default_groups'])\n ) {\n $output['_groups_id_observer'] = $output['users_default_groups'];\n }\n if (\n ( $action->fields['field'] == '_groups_id_assign')\n && isset($output['users_default_groups'])\n ) {\n $output['_groups_id_assign'] = $output['users_default_groups'];\n }\n break;\n\n case 'fromitem':\n if (\n $action->fields['field'] == '_groups_id_requester'\n && isset($output['_groups_id_of_item'])\n ) {\n $output['_groups_id_requester'] = $output['_groups_id_of_item'];\n }\n if (\n $action->fields['field'] == '_groups_id_observer'\n && isset($output['_groups_id_of_item'])\n ) {\n $output['_groups_id_observer'] = $output['_groups_id_of_item'];\n }\n if (\n $action->fields['field'] == '_groups_id_assign'\n && isset($output['_groups_id_of_item'])\n ) {\n $output['_groups_id_assign'] = $output['_groups_id_of_item'];\n }\n break;\n\n case 'compute':\n // Value could be not set (from test)\n $urgency = (isset($output['urgency']) ? $output['urgency'] : 3);\n $impact = (isset($output['impact']) ? $output['impact'] : 3);\n // Apply priority_matrix from config\n /** @var CommonITILObject $itemtype */\n $itemtype = static::getItemtype();\n $output['priority'] = $itemtype::computePriority($urgency, $impact);\n break;\n\n case 'do_not_compute':\n if (\n $action->fields['field'] == 'takeintoaccount_delay_stat'\n && $action->fields['value'] == 1\n ) {\n $output['_do_not_compute_takeintoaccount'] = true;\n }\n break;\n\n case \"affectbyip\":\n case \"affectbyfqdn\":\n case \"affectbymac\":\n if (!isset($output[\"entities_id\"])) {\n $output[\"entities_id\"] = $params[\"entities_id\"];\n }\n if (isset($this->regex_results[0])) {\n $regexvalue = RuleAction::getRegexResultById(\n $action->fields[\"value\"],\n $this->regex_results[0]\n );\n } else {\n $regexvalue = $action->fields[\"value\"];\n }\n\n switch ($action->fields[\"action_type\"]) {\n case \"affectbyip\":\n $result = IPAddress::getUniqueItemByIPAddress(\n $regexvalue,\n $output[\"entities_id\"]\n );\n break;\n\n case \"affectbyfqdn\":\n $result = FQDNLabel::getUniqueItemByFQDN(\n $regexvalue,\n $output[\"entities_id\"]\n );\n break;\n\n case \"affectbymac\":\n $result = NetworkPortInstantiation::getUniqueItemByMac(\n $regexvalue,\n $output[\"entities_id\"]\n );\n break;\n\n default:\n $result = [];\n }\n if (!empty($result)) {\n $output[\"items_id\"] = [];\n $output[\"items_id\"][$result[\"itemtype\"]][] = $result[\"id\"];\n }\n break;\n\n case 'regex_result':\n // Get each regex values\n $regex_values = array_map(\n fn ($regex_result) => RuleAction::getRegexResultById(\n $action->fields[\"value\"],\n $regex_result\n ),\n $this->regex_results\n );\n\n // Keep weird legacy default value that will not match anything\n if (empty($regex_values)) {\n $regex_values[] = $action->fields[\"value\"];\n }\n\n // Get field\n $field = $action->fields[\"field\"];\n\n // Handle each fields\n if ($field == \"_affect_itilcategory_by_code\") {\n $regex_value = $regex_values[0];\n\n if (!is_null($regex_value)) {\n $target_itilcategory = ITILCategory::getITILCategoryIDByCode($regex_value);\n if ($target_itilcategory != -1) {\n $output[\"itilcategories_id\"] = $target_itilcategory;\n }\n }\n } elseif ($field == \"_groups_id_requester\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"name\" => $regex_value,\n \"is_requester\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_requesters'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"_groups_id_requester_by_completename\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"completename\" => $regex_value,\n \"is_requester\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_requesters'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"_groups_id_assign\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"name\" => $regex_value,\n \"is_assign\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_assigns'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"_groups_id_assign_by_completename\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"completename\" => $regex_value,\n \"is_assign\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_assigns'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"_groups_id_observer\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"name\" => $regex_value,\n \"is_watcher\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_observers'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"_groups_id_observer_by_completename\") {\n foreach ($regex_values as $regex_value) {\n // Search group by name\n $group = new Group();\n $result = $group->getFromDBByCrit([\n \"completename\" => $regex_value,\n \"is_watcher\" => true\n ]);\n\n // Add groups found for each regex\n if ($result) {\n $output['_additional_groups_observers'][$group->getID()] = $group->getID();\n }\n }\n } elseif ($field == \"assign_appliance\") {\n $regex_value = $regex_values[0];\n\n if (!is_null($regex_value)) {\n $appliances = new Appliance();\n $target_appliances = $appliances->find([\n \"name\" => $regex_value,\n \"is_helpdesk_visible\" => true\n ]);\n\n if (\n (!array_key_exists(\"items_id\", $output) || $output['items_id'] == '0')\n && count($target_appliances) > 0\n ) {\n $output[\"items_id\"] = [];\n }\n\n foreach ($target_appliances as $value) {\n $output[\"items_id\"][Appliance::getType()][] = $value['id'];\n }\n }\n } elseif ($field == \"itilcategories_id\") {\n foreach ($regex_values as $regex_value) {\n // Search category by name\n $category = new ITILCategory();\n $result = $category->getFromDBByCrit([\n \"name\" => $regex_value,\n ]);\n\n // Stop at the first valid category found\n if ($result) {\n $output['itilcategories_id'] = $category->getID();\n break;\n }\n }\n } elseif ($field == \"_itilcategories_id_by_completename\") {\n foreach ($regex_values as $regex_value) {\n // Search category by name\n $category = new ITILCategory();\n $result = $category->getFromDBByCrit([\n \"completename\" => $regex_value,\n ]);\n\n // Stop at the first valid category found\n if ($result) {\n $output['itilcategories_id'] = $category->getID();\n break;\n }\n }\n }\n break;\n }\n }\n }\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function doGetDataForEditMode(DataObject\\Classificationstore $data, Concrete $object, array &$fieldData, array &$metaData, int $level = 1): array\n {\n $class = $object->getClass();\n $inheritanceAllowed = $class->getAllowInherit();\n $inherited = false;\n\n $items = $data->getItems();\n\n foreach ($items as $groupId => $keys) {\n if (!isset($data->getActiveGroups()[$groupId])) {\n continue;\n }\n foreach ($keys as $keyId => $languages) {\n $keyConfig = DataObject\\Classificationstore\\DefinitionCache::get($keyId);\n if ($keyConfig->getEnabled()) {\n $fd = DataObject\\Classificationstore\\Service::getFieldDefinitionFromKeyConfig($keyConfig);\n\n foreach ($languages as $language => $value) {\n $fdata = $value;\n if (!isset($fieldData[$language][$groupId][$keyId]) || $fd->isEmpty($fieldData[$language][$groupId][$keyId])) {\n // never override existing data\n $fieldData[$language][$groupId][$keyId] = $fdata;\n if (!$fd->isEmpty($fdata)) {\n $metaData[$language][$groupId][$keyId] = ['inherited' => $level > 1, 'objectid' => $object->getId()];\n }\n }\n }\n }\n }\n }\n\n // TODO\n if ($inheritanceAllowed) {\n // check if there is a parent with the same type\n $parent = DataObject\\Service::hasInheritableParentObject($object);\n if ($parent) {\n // same type, iterate over all language and all fields and check if there is something missing\n if ($this->localized) {\n $validLanguages = Tool::getValidLanguages();\n } else {\n $validLanguages = [];\n }\n array_unshift($validLanguages, 'default');\n\n $foundEmptyValue = false;\n\n $activeGroupIds = $this->recursiveGetActiveGroupsIds($object);\n\n foreach ($validLanguages as $language) {\n foreach ($activeGroupIds as $groupId => $enabled) {\n if (!$enabled) {\n continue;\n }\n\n $relation = new DataObject\\Classificationstore\\KeyGroupRelation\\Listing();\n $relation->setCondition('groupId = ' . $relation->quote($groupId));\n $relation = $relation->load();\n foreach ($relation as $key) {\n $keyId = $key->getKeyId();\n $fd = DataObject\\Classificationstore\\Service::getFieldDefinitionFromKeyConfig($key);\n\n if ($fd->isEmpty($fieldData[$language][$groupId][$keyId] ?? null)) {\n $foundEmptyValue = true;\n $inherited = true;\n $metaData[$language][$groupId][$keyId] = ['inherited' => true, 'objectid' => $parent->getId()];\n }\n }\n }\n }\n\n if ($foundEmptyValue) {\n // still some values are missing, ask the parent\n $getter = 'get' . ucfirst($this->getName());\n $parentData = $parent->$getter();\n $parentResult = $this->doGetDataForEditMode($parentData, $parent, $fieldData, $metaData, $level + 1);\n }\n }\n }\n\n $result = [\n 'data' => $fieldData,\n 'metaData' => $metaData,\n 'inherited' => $inherited,\n ];\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function getLabeledValue(array|ElementInterface $element): ResultContainer|\\stdClass|null\n {\n $result = new \\stdClass();\n $result->label = $this->label;\n\n $children = $this->getChildren();\n\n if (!$children) {\n return $result;\n } else {\n $isEqual = true;\n $valueArray = [];\n foreach ($children as $c) {\n $childResult = $c->getLabeledValue($element);\n $isArrayType = $childResult->isArrayType ?? false;\n $childValues = $childResult->value ?? null;\n if ($childValues && !$isArrayType) {\n $childValues = [$childValues];\n }\n\n if (is_array($childValues)) {\n foreach ($childValues as $value) {\n if (is_null($value) && $this->skipNull) {\n continue;\n }\n $valueArray[] = $value;\n }\n } else {\n if (!$this->skipNull) {\n $valueArray[] = null;\n }\n }\n }\n\n $firstValue = current($valueArray);\n foreach ($valueArray as $val) {\n if ($firstValue !== $val) {\n $isEqual = false;\n\n break;\n }\n }\n $result->value = $isEqual;\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function clearCache()\n{\n\trequire_once LIBS . 'news.php';\n\tNews::clearCache();\n\n\t$cache = Cache::getInstance();\n\n\tif($cache->enabled()) {\n\t\t$tmp = '';\n\n\t\tif ($cache->fetch('status', $tmp))\n\t\t\t$cache->delete('status');\n\n\t\tif ($cache->fetch('templates', $tmp))\n\t\t\t$cache->delete('templates');\n\n\t\tif ($cache->fetch('config_lua', $tmp))\n\t\t\t$cache->delete('config_lua');\n\n\t\tif ($cache->fetch('vocations', $tmp))\n\t\t\t$cache->delete('vocations');\n\n\t\tif ($cache->fetch('towns', $tmp))\n\t\t\t$cache->delete('towns');\n\n\t\tif ($cache->fetch('groups', $tmp))\n\t\t\t$cache->delete('groups');\n\n\t\tif ($cache->fetch('visitors', $tmp))\n\t\t\t$cache->delete('visitors');\n\n\t\tif ($cache->fetch('views_counter', $tmp))\n\t\t\t$cache->delete('views_counter');\n\n\t\tif ($cache->fetch('failed_logins', $tmp))\n\t\t\t$cache->delete('failed_logins');\n\n\t\tforeach (get_templates() as $template) {\n\t\t\tif ($cache->fetch('template_ini_' . $template, $tmp)) {\n\t\t\t\t$cache->delete('template_ini_' . $template);\n\t\t\t}\n\t\t}\n\n\t\tif ($cache->fetch('template_menus', $tmp)) {\n\t\t\t$cache->delete('template_menus');\n\t\t}\n\t\tif ($cache->fetch('database_tables', $tmp)) {\n\t\t\t$cache->delete('database_tables');\n\t\t}\n\t\tif ($cache->fetch('database_columns', $tmp)) {\n\t\t\t$cache->delete('database_columns');\n\t\t}\n\t\tif ($cache->fetch('database_checksum', $tmp)) {\n\t\t\t$cache->delete('database_checksum');\n\t\t}\n\t\tif ($cache->fetch('hooks', $tmp)) {\n\t\t\t$cache->delete('hooks');\n\t\t}\n\t\tif ($cache->fetch('last_kills', $tmp)) {\n\t\t\t$cache->delete('last_kills');\n\t\t}\n\t}\n\n\tdeleteDirectory(CACHE . 'signatures', ['index.html'], true);\n\tdeleteDirectory(CACHE . 'twig', ['index.html'], true);\n\tdeleteDirectory(CACHE . 'plugins', ['index.html'], true);\n\tdeleteDirectory(CACHE, ['signatures', 'twig', 'plugins', 'index.html'], true);\n\n\treturn true;\n}", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function maketrialbalance($data, $sn, $numrows, $ops, $bigtitle, &$anstypes, &$answer, &$questions, &$showanswer, &$displayformat, &$answerboxsize) {\n\t$out = '<table class=\"acctstatement noborder\"><caption>'.$bigtitle.'</caption><thead><tr><th>Accounts</th><th>Debits</th><th>Credits</th></tr></thead><tbody>';\n\t$sa = '<table class=\"acctstatement noborder\"><caption>'.$bigtitle.'</caption><thead><tr><th>Accounts</th><th>Debits</th><th>Credits</th></tr></thead><tbody>';\n\t$allaccts = array();\n\t$maxsizedescr = 4; $hasdecimals = false;\n\tforeach ($data as $t=>$dt) {\n\t\tfor ($i=0;$i<count($dt);$i+=2) {\n\t\t\tif (!in_array($dt[$i],$ops)) {\n\t\t\t\t$ops[] = $dt[$i];\n\t\t\t}\n\t\t\t$sl = strlen($dt[$i]);\n\t\t\tif ($sl>$maxsizedescr) { $maxsizedescr = $sl;}\n\t\t\tif (!$hasdecimals && strpos($dt[$i+1],'.')!==false) { $hasdecimals = true;}\n\t\t}\n\t}\n\t$c = 0; $totdeb = 0; $totcred = 0; $maxsizedescr += 6;\n\tforeach ($data as $t=>$dt) {\n\t\tfor($i=0;$i<count($dt);$i+=2) {\n\t\t\t$out .= '<tr><td>[AB'.$sn.']</td>';\n\t\t\t$sa .= '<tr><td>'.$dt[$i].'</td>';\n\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'typeahead'; $questions[$sn] = $ops; $answer[$sn] = $dt[$i]; $answerboxsize[$sn] = $maxsizedescr;\n\t\t\t$sn++;\n\t\t\tif ((($t=='assets' || $t=='expenses') && $dt[$i+1]>=0) || (!($t=='assets' || $t=='expenses') && $dt[$i+1]<0)) {\n\t\t\t\t$out .= '<td>[AB'.$sn.']</td>';\n\t\t\t\t$sa .= '<td class=\"r\">'.($hasdecimals?number_format(abs($dt[$i+1]),2,'.',','):number_format(abs($dt[$i+1]))).'</td>';\n\t\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = abs($dt[$i+1]); $answerboxsize[$sn] = 8;\n\t\t\t\t$sn++;\n\t\t\t\t$out .= '<td class=\"r\">[AB'.$sn.']</td>';\n\t\t\t\t$sa .= '<td class=\"r\"></td>';\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = 8;\n\t\t\t\t$sn++;\n\t\t\t\t$totdeb += abs($dt[$i+1]);\n\t\t\t} else {\n\t\t\t\t$out .= '<td class=\"r\">[AB'.$sn.']</td>';\n\t\t\t\t$sa .= '<td class=\"r\"></td>';\n\t\t\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = 8;\n\t\t\t\t$sn++;\n\t\t\t\t$out .= '<td>[AB'.$sn.']</td>';\n\t\t\t\t$sa .= '<td class=\"r\">'.($hasdecimals?number_format(abs($dt[$i+1]),2,'.',','):number_format(abs($dt[$i+1]))).'</td>';\n\t\t\t\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = abs($dt[$i+1]); $answerboxsize[$sn] = 8;\n\t\t\t\t$sn++;\n\t\t\t\t$totcred += abs($dt[$i+1]);\n\t\t\t}\n\t\t\t$c++;\n\t\t}\n\t}\n\tfor ($j=$c; $j<$numrows;$j++) {\n\t\t$out .= '<tr><td>[AB'.$sn.']</td>';\n\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'typeahead'; $questions[$sn] = $ops; $answer[$sn] = ''; $answerboxsize[$sn] = $maxsizedescr;\n\t\t$sn++;\n\t\t$out .= '<td class=\"r\">[AB'.$sn.']</td>';\n\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = 8;\n\t\t$sn++;\n\t\t$out .= '<td class=\"r\">[AB'.$sn.']</td>';\n\t\t$anstypes[$sn] = 'string'; $displayformat[$sn] = 'alignright'; $answer[$sn] = ''; $answerboxsize[$sn] = 8;\n\t\t$sn++;\n }\n $out .= '</tbody><tfoot>';\n $sa .= '</tbody><tfoot>';\n\t$out .= '<tr><td class=\"r\"><b>Total</b></td>';\n\t$sa .= '<tr><td class=\"r\"><b>Total</b></td>';\n\t$out .= '<td style=\"border-top:1px solid;border-bottom:3px double;\"><span class=\"sr-only\">Single line</span>[AB'.$sn.']<span class=\"sr-only\">Double line</span></td>';\n\t$sa .= '<td class=\"r\" style=\"border-top:1px solid;border-bottom:3px double;\"><span class=\"sr-only\">Single line</span>'.($hasdecimals?number_format($totdeb,2,'.',','):number_format($totdeb)).'<span class=\"sr-only\">Double line</span></td>';\n\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = $totdeb; $answerboxsize[$sn] = 8;\n\t$sn++;\n\t$out .= '<td style=\"border-top:1px solid;border-bottom:3px double;\"><span class=\"sr-only\">Single line</span>[AB'.$sn.']<span class=\"sr-only\">Double line</span></td>';\n\t$sa .= '<td class=\"r\" style=\"border-top:1px solid;border-bottom:3px double;\"><span class=\"sr-only\">Single line</span>'.($hasdecimals?number_format($totcred,2,'.',','):number_format($totcred)).'<span class=\"sr-only\">Double line</span></td>';\n\t$anstypes[$sn] = 'number'; $displayformat[$sn] = 'alignright'; $answer[$sn] = $totcred; $answerboxsize[$sn] = 8;\n\t$sn++;\n\t$out .= '</tfoot></table>';\n\t$sa .= '</tfoot></table>';\n\t$showanswer .= $sa.'<p>&nbsp;</p>';\n\treturn $out;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function showresults($q,$qtype) {\n\tglobal $qdata,$qsids,$qsdata;\n\t//eval(interpret('control',$qtype,$qsdata[$qsids[$q]][1]));\n\tlist($anstypes, $questions, $answer, $answers) = sandboxeval($qsdata[$qsids[$q]]['control'], $qtype);\n\n\tif ($qtype=='choices' || $qtype=='multans' || $qtype=='multipart') {\n\t\tif ($qtype=='multipart') {\n\t\t\tforeach ($anstypes as $i=>$type) {\n\t\t\t\tif ($type=='choices' || $type=='multans') {\n\t\t\t\t\tif (isset($questions[$i]) && is_array($questions[$i])) {\n\t\t\t\t\t\t$ql = $questions[$i];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$ql = $questions;\n\t\t\t\t\t}\n\t\t\t\t\tif ($type=='multans') {\n\t\t\t\t\t\tif (is_array($answers)) {\n\t\t\t\t\t\t\t$al = $answers[$i];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$al = $answers;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ($type=='choices') {\n\t\t\t\t\t\tif (is_array($answer)) {\n\t\t\t\t\t\t\t$al = $answer[$i];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$al = $answer;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdisp($q,$type,$i,$al,$ql);\n\t\t\t\t} else {\n\t\t\t\t\tif (is_array($answer)) {\n\t\t\t\t\t\t$al = $answer[$i];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$al = $answer;\n\t\t\t\t\t}\n\t\t\t\t\tdisp($q,$type,$i,$al);\n\t\t\t\t}\n\n\t\t\t}\n\t\t} else {\n\t\t\tif ($qtype=='multans') {\n\t\t\t\t$al = $answers;\n\t\t\t} else if ($qtype=='choices') {\n\t\t\t\t$al = $answer;\n\t\t\t}\n\t\t\tdisp($q,$qtype,-1,$al,$questions);\n\t\t}\n\t} else {\n\t\tdisp($q,$qtype,-1,$answer);\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function printq($qn,$qsetid,$seed,$pts) {\n\tglobal $DBH,$RND,$isfinal,$imasroot,$urlmode;\n\t$RND->srand($seed);\n\t$stm = $DBH->prepare(\"SELECT qtype,control,qcontrol,qtext,answer,hasimg FROM imas_questionset WHERE id=:id\");\n\t$stm->execute(array(':id'=>$qsetid));\n\t$qdata = $stm->fetch(PDO::FETCH_ASSOC);\n\n\tif ($qdata['hasimg']>0) {\n\t\t$stm = $DBH->prepare(\"SELECT var,filename,alttext FROM imas_qimages WHERE qsetid=:qsetid\");\n\t\t$stm->execute(array(':qsetid'=>$qsetid));\n\t\twhile ($row = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\tif (substr($row[1],0,4)=='http') {\n\t\t\t\t${$row[0]} = \"<img src=\\\"{$row[1]}\\\" alt=\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\" />\";\n\t\t\t} else if(isset($GLOBALS['CFG']['GEN']['AWSforcoursefiles']) && $GLOBALS['CFG']['GEN']['AWSforcoursefiles'] == true) {\n\t\t\t\t${$row[0]} = \"<img src=\\\"{$urlmode}s3.amazonaws.com/{$GLOBALS['AWSbucket']}/qimages/{$row[1]}\\\" alt=\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\" />\";\n\t\t\t} else {\n\t\t\t\t${$row[0]} = \"<img src=\\\"$imasroot/assessment/qimages/{$row[1]}\\\" alt=\\\"\".htmlentities($row[2],ENT_QUOTES).\"\\\" />\";\n\t\t\t}\n\t\t}\n\t}\n\ttry {\n\t\teval(interpret('control',$qdata['qtype'],$qdata['control']));\n\t\teval(interpret('qcontrol',$qdata['qtype'],$qdata['qcontrol']));\n\t\t$toevalqtxt = interpret('qtext',$qdata['qtype'],$qdata['qtext']);\n\t\t$toevalqtxt = str_replace('\\\\','\\\\\\\\',$toevalqtxt);\n\t\t$toevalqtxt = str_replace(array('\\\\\\\\n','\\\\\\\\\"','\\\\\\\\$','\\\\\\\\{'),array('\\\\n','\\\\\"','\\\\$','\\\\{'),$toevalqtxt);\n\t\t$RND->srand($seed+1);\n\t\teval(interpret('answer',$qdata['qtype'],$qdata['answer']));\n\t} catch (Throwable $thrownerror) {\n\t\tif ($GLOBALS['myrights']>10) {\n\t\t\techo '<p>Caught error in evaluating a function in a question: ';\n\t\t\techo Sanitize::encodeStringForDisplay($thrownerror->getMessage());\n\t\t\techo '</p>';\n\t\t}\n\t}\n\t$RND->srand($seed+2);\n\t$la = '';\n\n\tif (isset($choices) && !isset($questions)) {\n\t\t$questions =& $choices;\n\t}\n\tif (isset($variable) && !isset($variables)) {\n\t\t$variables =& $variable;\n\t}\n\tif ($displayformat==\"select\") {\n\t\tunset($displayformat);\n\t}\n\n\t//pack options\n\tif (isset($ansprompt)) {$options['ansprompt'] = $ansprompt;}\n\tif (isset($displayformat)) {$options['displayformat'] = $displayformat;}\n\tif (isset($answerformat)) {$options['answerformat'] = $answerformat;}\n\tif (isset($questions)) {$options['questions'] = $questions;}\n\tif (isset($answers)) {$options['answers'] = $answers;}\n\tif (isset($answer)) {$options['answer'] = $answer;}\n\tif (isset($questiontitle)) {$options['questiontitle'] = $questiontitle;}\n\tif (isset($answertitle)) {$options['answertitle'] = $answertitle;}\n\tif (isset($answersize)) {$options['answersize'] = $answersize;}\n\tif (isset($variables)) {$options['variables'] = $variables;}\n\tif (isset($domain)) {$options['domain'] = $domain;}\n\tif (isset($answerboxsize)) {$options['answerboxsize'] = $answerboxsize;}\n\tif (isset($hidepreview)) {$options['hidepreview'] = $hidepreview;}\n\tif (isset($matchlist)) {$options['matchlist'] = $matchlist;}\n\tif (isset($noshuffle)) {$options['noshuffle'] = $noshuffle;}\n\tif (isset($reqdecimals)) {$options['reqdecimals'] = $reqdecimals;}\n\tif (isset($grid)) {$options['grid'] = $grid;}\n\tif (isset($background)) {$options['background'] = $background;}\n\n\tif ($qdata['qtype']==\"multipart\") {\n\t\tif (!is_array($anstypes)) {\n\t\t\t$anstypes = explode(\",\",$anstypes);\n\t\t}\n\t\t$laparts = explode(\"&\",$la);\n\t\tforeach ($anstypes as $kidx=>$anstype) {\n\t\t\tlist($answerbox[$kidx],$tips[$kidx],$shans[$kidx]) = makeanswerbox($anstype,$kidx,$laparts[$kidx],$options,$qn+1);\n\t\t}\n\t} else {\n\t\tlist($answerbox,$tips[0],$shans[0]) = makeanswerbox($qdata['qtype'],$qn,$la,$options,0);\n\t}\n\n\techo \"<div class=q>\";\n\tif ($isfinal) {\n\t\techo \"<div class=\\\"trq$qn\\\">\\n\";\n\t} else {\n\t\techo \"<div class=m id=\\\"trq$qn\\\">\\n\";\n\t}\n\techo \"<div class=qnum>\".($qn+1).\") \";\n\tif (isset($_POST['points'])) {\n\t\techo '<br/>'.Sanitize::encodeStringForDisplay($pts).'pts';\n\t}\n\techo \"</div>\\n\";//end qnum div\n\techo \"<div class=floatl><div>\\n\";\n\t//echo $toevalqtext;\n\teval(\"\\$evaledqtext = \\\"$toevalqtxt\\\";\");\n\techo printfilter(filter($evaledqtext));\n\techo \"</div>\\n\"; //end question div\n\n\tif (strpos($toevalqtxt,'$answerbox')===false) {\n\t\tif (is_array($answerbox)) {\n\t\t\tforeach($answerbox as $iidx=>$abox) {\n\t\t\t\techo Sanitize::outgoingHtml(printfilter(filter(\"<div>$abox</div>\\n\")));\n\t\t\t\techo \"<div class=spacer>&nbsp;</div>\\n\";\n\t\t\t}\n\t\t} else { //one question only\n\t\t echo Sanitize::outgoingHtml(printfilter(filter(\"<div>$answerbox</div>\\n\")));\n\t\t}\n\n\n\t}\n\n\techo \"</div>\\n\"; //end floatl div\n\n\techo \"</div>\";//end m div\n\tif (!$isfinal) {\n\t\techo \"<div class=cbutn>\\n\";\n\t\techo \"<p><input type=button value=\\\"+1\\\" onclick=\\\"incspace($qn,1)\\\"><input type=button value=\\\"+.5\\\" onclick=\\\"incspace($qn,.5)\\\"><input type=button value=\\\"+.25\\\" onclick=\\\"incspace($qn,.25)\\\"><input type=button value=\\\"+.1\\\" onclick=\\\"incspace($qn,.1)\\\"><br/>\";\n\t\techo \"<input type=button value=\\\"-1\\\" onclick=\\\"incspace($qn,-1)\\\"><input type=button value=\\\"-.5\\\" onclick=\\\"incspace($qn,-.5)\\\"><input type=button value=\\\"-.25\\\" onclick=\\\"incspace($qn,-.25)\\\"><input type=button value=\\\"-.1\\\" onclick=\\\"incspace($qn,-.1)\\\"></p>\";\n\t\techo \"</div>\\n\"; //end cbutn div\n\t}\n\techo \"&nbsp;\";\n\techo \"</div>\\n\"; //end q div\n\tif (!isset($showanswer)) {\n\t\treturn $shans;\n\t} else {\n\t\treturn $showanswer;\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function findFileWithExtension($class, $ext)\n {\n // PSR-4 lookup\n $logicalPathPsr4 = strtr($class, '\\\\', DIRECTORY_SEPARATOR) . $ext;\n\n $first = $class[0];\n if (isset($this->prefixLengthsPsr4[$first])) {\n $subPath = $class;\n while (false !== $lastPos = strrpos($subPath, '\\\\')) {\n $subPath = substr($subPath, 0, $lastPos);\n $search = $subPath . '\\\\';\n if (isset($this->prefixDirsPsr4[$search])) {\n $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);\n foreach ($this->prefixDirsPsr4[$search] as $dir) {\n if (file_exists($file = $dir . $pathEnd)) {\n return $file;\n }\n }\n }\n }\n }\n\n // PSR-4 fallback dirs\n foreach ($this->fallbackDirsPsr4 as $dir) {\n if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {\n return $file;\n }\n }\n\n // PSR-0 lookup\n if (false !== $pos = strrpos($class, '\\\\')) {\n // namespaced class name\n $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)\n . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);\n } else {\n // PEAR-like class name\n $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;\n }\n\n if (isset($this->prefixesPsr0[$first])) {\n foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {\n if (0 === strpos($class, $prefix)) {\n foreach ($dirs as $dir) {\n if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {\n return $file;\n }\n }\n }\n }\n }\n\n // PSR-0 fallback dirs\n foreach ($this->fallbackDirsPsr0 as $dir) {\n if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {\n return $file;\n }\n }\n\n // PSR-0 include paths.\n if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {\n return $file;\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "static function Dispatch($phreezer, $renderEngine, $action = '', $context = null, $router = null)\n {\n if ($router == null) {\n require_once('GenericRouter.php');\n $router = new GenericRouter();\n }\n\n // get the route and normalize the controller name\n list ( $controller_param, $method_param ) = $router->GetRoute($action);\n $controller_class = $controller_param . \"Controller\";\n\n if (self::$FAST_LOOKUP) {\n if (! class_exists($controller_class)) {\n $controller_file = \"Controller/$controller_class.php\";\n include_once $controller_file;\n }\n\n $controller = new $controller_class($phreezer, $renderEngine, $context, $router);\n $controller->$method_param();\n\n return true;\n }\n\n // if the controller was in a sub-directory, get rid of the directory path\n $slashPos = strpos($controller_class, '/');\n while ($slashPos !== false) {\n $controller_class = substr($controller_class, $slashPos + 1);\n $slashPos = strpos($controller_class, '/');\n }\n\n if (! class_exists($controller_class)) {\n // attempt to locate the controller file\n $controller_file = \"Controller/\" . $controller_param . \"Controller.php\";\n $controller_filepath = null;\n\n // search for the controller file in the default locations, then the include path\n $paths = array_merge(array (\n './libs/',\n './'\n ), explode(PATH_SEPARATOR, get_include_path()));\n\n $found = false;\n foreach ($paths as $path) {\n $controller_filepath = self::ControllerFileExists($path . \"/\" . $controller_file);\n if ($controller_filepath) {\n $found = true;\n break;\n }\n }\n\n if (! $found) {\n throw new Exception(\"File ~/libs/\" . $controller_file . \" was not found in include path\");\n }\n\n // convert any php errors into an exception\n if (self::$IGNORE_DEPRECATED) {\n ExceptionThrower::Start();\n } else {\n ExceptionThrower::Start(E_ALL);\n ExceptionThrower::$IGNORE_DEPRECATED = false;\n }\n\n // we should be fairly certain the file exists at this point\n include_once($controller_filepath);\n\n // we found the file but the expected class doesn't appear to be defined\n if (! class_exists($controller_class)) {\n throw new Exception(\"Controller file was found, but class '\" . $controller_class . \"' is not defined\");\n }\n }\n\n // create an instance of the controller class\n $controller = new $controller_class($phreezer, $renderEngine, $context, $router);\n\n // we have a valid instance, just verify there is a matching method\n if (\n ! is_callable(array (\n $controller,\n $method_param\n ))\n ) {\n throw new Exception(\"'\" . $controller_class . \".\" . $method_param . \"' is not a valid action\");\n }\n\n // do not call the requested method/route if the controller request has been cancelled\n if (! $controller->IsTerminated()) {\n // file, class and method all are ok, go ahead and call it\n call_user_func(array (\n &$controller,\n $method_param\n ));\n }\n\n // reset error handling back to whatever it was\n // restore_exception_handler();\n ExceptionThrower::Stop();\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function manageRedirect($where)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n if (!empty($where)) {\n if (Session::getCurrentInterface()) {\n // redirect to URL : URL must be rawurlencoded\n $decoded_where = rawurldecode($where);\n $matches = [];\n\n // redirect to full url -> check if it's based on glpi url\n if (preg_match('@(([^:/].+:)?//[^/]+)(/.+)?@', $decoded_where, $matches)) {\n if ($matches[1] !== $CFG_GLPI['url_base']) {\n Session::addMessageAfterRedirect(__s('Redirection failed'));\n if (Session::getCurrentInterface() === \"helpdesk\") {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/helpdesk.public.php\");\n } else {\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/central.php\");\n }\n } else {\n Html::redirect($decoded_where);\n }\n }\n\n // Redirect to relative url\n if ($decoded_where[0] == '/') {\n // prevent exploit (//example.com) and force a redirect from glpi root\n $redirect_to = $CFG_GLPI[\"root_doc\"] . \"/\" . ltrim($decoded_where, '/');\n Html::redirect($redirect_to);\n }\n\n // explode with limit 3 to preserve the last part of the url\n // /index.php?redirect=ticket_2_Ticket$main#TicketValidation_1 (preserve anchor)\n $data = explode(\"_\", $where, 3);\n $forcetab = '';\n // forcetab for simple items\n if (isset($data[2])) {\n $forcetab = 'forcetab=' . $data[2];\n }\n\n switch (Session::getCurrentInterface()) {\n case \"helpdesk\":\n switch (strtolower($data[0])) {\n // Use for compatibility with old name\n case \"tracking\":\n case \"ticket\":\n $data[0] = 'Ticket';\n // redirect to item\n if (\n isset($data[1])\n && is_numeric($data[1])\n && ($data[1] > 0)\n ) {\n // Check entity\n if (\n ($item = getItemForItemtype($data[0]))\n && $item->isEntityAssign()\n ) {\n if ($item->getFromDB($data[1])) {\n if (!Session::haveAccessToEntity($item->getEntityID())) {\n Session::changeActiveEntities($item->getEntityID(), 1);\n }\n }\n }\n // force redirect to timeline when timeline is enabled and viewing\n // Tasks or Followups\n $forcetab = str_replace('TicketFollowup$1', 'Ticket$1', $forcetab);\n $forcetab = str_replace('TicketTask$1', 'Ticket$1', $forcetab);\n $forcetab = str_replace('ITILFollowup$1', 'Ticket$1', $forcetab);\n Html::redirect(Ticket::getFormURLWithID($data[1]) . \"&$forcetab\");\n } else if (!empty($data[0])) { // redirect to list\n if ($item = getItemForItemtype($data[0])) {\n $searchUrl = $item->getSearchURL();\n $searchUrl .= strpos($searchUrl, '?') === false ? '?' : '&';\n $searchUrl .= $forcetab;\n Html::redirect($searchUrl);\n }\n }\n\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/helpdesk.public.php\");\n // phpcs doesn't understand that the script will exit here so we need a comment to avoid the fallthrough warning\n\n case \"preference\":\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/preference.php?$forcetab\");\n // phpcs doesn't understand that the script will exit here so we need a comment to avoid the fallthrough warning\n\n case \"reservation\":\n Html::redirect(Reservation::getFormURLWithID($data[1]) . \"&$forcetab\");\n // phpcs doesn't understand that the script will exit here so we need a comment to avoid the fallthrough warning\n\n default:\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/helpdesk.public.php\");\n }\n // @phpstan-ignore deadCode.unreachable (defensive programming)\n break;\n\n case \"central\":\n switch (strtolower($data[0])) {\n case \"preference\":\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/preference.php?$forcetab\");\n\n // Use for compatibility with old name\n // no break\n case \"tracking\":\n $data[0] = \"Ticket\";\n //var defined, use default case\n\n default:\n // redirect to item\n if (\n !empty($data[0])\n && isset($data[1])\n && is_numeric($data[1])\n && ($data[1] > 0)\n ) {\n // Check entity\n if ($item = getItemForItemtype($data[0])) {\n if ($item->isEntityAssign()) {\n if ($item->getFromDB($data[1])) {\n if (!Session::haveAccessToEntity($item->getEntityID())) {\n Session::changeActiveEntities($item->getEntityID(), 1);\n }\n }\n }\n // force redirect to timeline when timeline is enabled\n $forcetab = str_replace('TicketFollowup$1', 'Ticket$1', $forcetab);\n $forcetab = str_replace('TicketTask$1', 'Ticket$1', $forcetab);\n $forcetab = str_replace('ITILFollowup$1', 'Ticket$1', $forcetab);\n Html::redirect($item->getFormURLWithID($data[1]) . \"&$forcetab\");\n }\n } else if (!empty($data[0])) { // redirect to list\n if ($item = getItemForItemtype($data[0])) {\n $searchUrl = $item->getSearchURL();\n $searchUrl .= strpos($searchUrl, '?') === false ? '?' : '&';\n $searchUrl .= $forcetab;\n Html::redirect($searchUrl);\n }\n }\n\n Html::redirect($CFG_GLPI[\"root_doc\"] . \"/front/central.php\");\n }\n // @phpstan-ignore deadCode.unreachable (defensive programming)\n break;\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function toArray($request)\n {\n switch ($this->modal_type) {\n case 'image':\n return [\n '__mediaType' => 'image',\n '__option_caption' => !empty($this->image_sequence_caption) || !empty($this->imageCaption('experience_image')),\n '__option_zoomable' => $this->zoomable,\n 'id' => (string) $this->id,\n 'src' => $this->modal_type === 'image' ? SlideMediaResource::collection($this->experienceImage)->toArray(request()) : [UrlHelpers::parseVideoUrl($this->video_url)],\n 'caption' => $this->image_sequence_caption ?? $this->imageCaption('experience_image'),\n ];\n\n break;\n case 'video':\n return [\n '__mediaType' => 'video',\n '__option_autoplay' => $this->video_play_settings && in_array('autoplay', $this->video_play_settings),\n '__option_controls' => $this->video_play_settings && in_array('control', $this->video_play_settings),\n '__option_inset' => $this->video_play_settings && in_array('inset', $this->video_play_settings),\n '__option_caption' => !empty($this->image_sequence_caption) || !empty($this->imageCaption('experience_image')),\n '__option_loop' => $this->video_play_settings && in_array('loop', $this->video_play_settings),\n '__option_zoomable' => $this->zoomable,\n 'id' => (string) $this->id,\n 'src' => $this->modal_type === 'image' ? SlideMediaResource::collection($this->experienceImage)->toArray(request()) : [UrlHelpers::parseVideoUrl($this->video_url)],\n 'caption' => $this->image_sequence_caption ?? $this->imageCaption('experience_image'),\n ];\n\n break;\n case 'image_sequence':\n return [\n '__mediaType' => 'image_sequence',\n '__option_reverse' => $this->image_sequence_playback && in_array('reverse', $this->image_sequence_playback),\n '__option_infinite' => $this->image_sequence_playback && in_array('infinite', $this->image_sequence_playback),\n '__option_caption' => !empty($this->image_sequence_caption) || !empty($this->imageCaption('experience_image')),\n 'id' => (string) $this->id,\n 'assetId' => $this->fileObject('image_sequence_file') ? $this->fileObject('image_sequence_file')->id : '0',\n 'caption' => $this->image_sequence_caption ?? $this->imageCaption('experience_image'),\n ];\n\n break;\n case '3d_model':\n $model3d = $this->model3d;\n\n if ($model3d) {\n return [\n 'id' => (string) $this->id,\n '__mediaType' => '3d_model',\n 'model_id' => $model3d->model_id,\n 'camera_position' => (array) $model3d->camera_position,\n 'camera_target' => $model3d->camera_target,\n 'annotation_list' => json_decode($model3d->annotation_list, true),\n 'caption' => $this->image_sequence_caption ?? ''\n ];\n }\n\n break;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "art-institute-of-chicago_artic.edu", "language": "php"} {"function": "public function setup(array $context)\n {\n // We have to prepare our batches here\n // Get all of our x-12 partners and make sure we have\n // directories to write to for them\n $result = sqlStatement(\"SELECT * from x12_partners\");\n while ($row = sqlFetchArray($result)) {\n $has_dir = true;\n if (!isset($row['x12_sftp_local_dir'])) {\n // Local Directory not set\n $has_dir = false;\n $this->printToScreen(xl(\"No directory for X12 partner \" . $row['name']));\n } elseif (\n isset($row['x12_sftp_local_dir']) &&\n !is_dir($row['x12_sftp_local_dir'])\n ) {\n // If the local directory doesn't exist, attempt to create it\n $has_dir = mkdir($row['x12_sftp_local_dir'], '644', true);\n if (false === $has_dir) {\n $this->printToScreen(xl(\"Could not create directory for X12 partner \" . $row['name']));\n }\n }\n\n $batch = new BillingClaimBatch('.txt', $context);\n $filename = $batch->getBatFilename();\n $filename = str_replace('batch', 'batch-p' . $row['id'], $filename);\n $batch->setBatFilename($filename);\n\n // Only set the batch file directory if we have a valid directory\n if ($has_dir) {\n $batch->setBatFiledir($row['x12_sftp_local_dir']);\n }\n\n // Store the x-12 partner's data in case we need to reference it (like need the Name or something)\n $this->x12_partners[$row['id']] = $row;\n\n // We need to track the edi count for each x-12 partner, initialize them to zero here\n $this->edi_counts[$row['id']] = 0;\n\n // We need to track the patient segment count for each x-12 partner, initialize them to zero here\n $this->pat_segment_counts[$row['id']] = 0;\n\n // Store the directory in an associative array with the partner ID as the index\n $this->x12_partner_batches[$row['id']] = $batch;\n\n // Look through the claims and set is_last on each one that\n // is the last for this x-12 partner\n $lastClaim = null;\n foreach ($context['claims'] as $claim) {\n if ($claim->getPartner() === $row['id']) {\n $lastClaim = $claim;\n }\n }\n if ($lastClaim !== null) {\n $lastClaim->setIsLast(true);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function edih_271_html($filename, $bht03 = '')\n{\n // create a display for an individual 277 response\n $html_str = '';\n //\n if ($filename) {\n $obj271 = csv_check_x12_obj($filename, 'f271');\n if ('edih_x12_file' == get_class($obj271)) {\n if ($bht03) {\n // particular transaction\n $html_str .= edih_271_transaction_html($obj271, $bht03);\n } else {\n // file contents\n $env_ar = $obj271->edih_envelopes();\n if (!isset($env_ar['ST'])) {\n $html_str .= \"<p>edih_271_html: file parse error, envelope error</p>\" . PHP_EOL;\n $html_str .= text($obj271->edih_message());\n return $html_str;\n } else {\n $html_str .= \"<div id='accordion'>\" . PHP_EOL;\n }\n\n foreach ($env_ar['ST'] as $st) {\n foreach ($env_ar['GS'] as $gs) {\n if ($gs['icn'] != $st['icn']) {\n continue;\n }\n\n if ($gs['gsn'] == $st['gsn']) {\n $gs_date = edih_format_date($gs['date']);\n $gs_sender = $gs['sender'];\n break;\n }\n }\n\n //\n // get each transaction\n foreach ($st['bht03'] as $bht) {\n $html_str .= \"<h3>\" . text($bht) . \" Benefit Eligibility</h3>\" . PHP_EOL;\n $html_str .= \"<div id='ac_\" . attr($bht) . \"'>\" . PHP_EOL;\n //\n $html_str .= edih_271_transaction_html($obj271, $bht);\n //\n $html_str .= \"</div>\" . PHP_EOL;\n }\n\n $html_str .= \"</div>\" . PHP_EOL;\n }\n }\n } else {\n $html_str .= \"<p>edih_271_html: file parse error</p>\" . PHP_EOL;\n }\n } else {\n csv_edihist_log(\"edih_271_html: error in file arguments\");\n $html_str .= \"Error: invalid file name<br />\" . PHP_EOL;\n return $html_str;\n }\n\n //\n return $html_str;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function updateDSIAttributes($dsiServiceId, $listId, $userId, $attributes)\n {\n $inTransaction = false;\n try {\n if (!$this->inNestedTransaction) {\n QueryUtils::startTransaction();\n } else {\n $inTransaction = true;\n }\n $currentAttributes = $this->getAttributes($listId, $dsiServiceId);\n $currentAttributesMap = [];\n foreach ($currentAttributes as $attribute) {\n $currentAttributesMap[$attribute['option_id']] = $attribute;\n }\n foreach ($attributes as $attribute) {\n $optionId = $attribute['name'];\n if (!array_key_exists($optionId, $currentAttributesMap)) {\n // doesn't exist so we will skip over this.\n continue;\n }\n $currentAttribute = $currentAttributesMap[$optionId];\n if (isset($currentAttribute['id'])) {\n if ($currentAttribute['value'] !== $attribute['value']) {\n $this->updateAttribute($currentAttribute['id'], $attribute['value'], $userId);\n }\n } else {\n $currentAttribute['source_value'] = $attribute['value'];\n $currentAttribute['client_id'] = $dsiServiceId;\n $this->insertAttribute($dsiServiceId, $currentAttribute, $userId);\n }\n unset($currentAttributesMap[$optionId]);\n }\n\n foreach ($currentAttributesMap as $currentAttribute) {\n $this->deleteAttribute($currentAttribute['id']);\n }\n if (!$this->inNestedTransaction) {\n QueryUtils::commitTransaction();\n }\n } catch (\\Exception $e) {\n if ($inTransaction && !$this->inNestedTransaction) {\n QueryUtils::rollbackTransaction();\n }\n throw $e;\n }\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function getFolderContents($path): iterable {\n\t\ttry {\n\t\t\t$path = ltrim($this->buildPath($path), '/');\n\t\t\ttry {\n\t\t\t\t$files = $this->share->dir($path);\n\t\t\t} catch (ForbiddenException $e) {\n\t\t\t\t$this->logger->critical($e->getMessage(), ['exception' => $e]);\n\t\t\t\tthrow new NotPermittedException();\n\t\t\t} catch (InvalidTypeException $e) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tforeach ($files as $file) {\n\t\t\t\t$this->statCache[$path . '/' . $file->getName()] = $file;\n\t\t\t}\n\n\t\t\tforeach ($files as $file) {\n\t\t\t\ttry {\n\t\t\t\t\t// the isHidden check is done before checking the config boolean to ensure that the metadata is always fetch\n\t\t\t\t\t// so we trigger the below exceptions where applicable\n\t\t\t\t\t$hide = $file->isHidden() && !$this->showHidden;\n\n\t\t\t\t\tif ($this->checkAcl && $acl = $this->getACL($file)) {\n\t\t\t\t\t\t// if there is no explicit deny, we assume it's allowed\n\t\t\t\t\t\t// this doesn't take inheritance fully into account but if read permissions is denied for a parent we wouldn't be in this folder\n\t\t\t\t\t\t// additionally, it's better to have false negatives here then false positives\n\t\t\t\t\t\tif ($acl->denies(ACL::MASK_READ) || $acl->denies(ACL::MASK_EXECUTE)) {\n\t\t\t\t\t\t\t$this->logger->debug('Hiding non readable entry ' . $file->getName());\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif ($hide) {\n\t\t\t\t\t\t$this->logger->debug('hiding hidden file ' . $file->getName());\n\t\t\t\t\t}\n\t\t\t\t\tif (!$hide) {\n\t\t\t\t\t\tyield $file;\n\t\t\t\t\t}\n\t\t\t\t} catch (ForbiddenException $e) {\n\t\t\t\t\t$this->logger->debug($e->getMessage(), ['exception' => $e]);\n\t\t\t\t} catch (NotFoundException $e) {\n\t\t\t\t\t$this->logger->debug('Hiding forbidden entry ' . $file->getName(), ['exception' => $e]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (ConnectException $e) {\n\t\t\t$this->logger->error('Error while getting folder content', ['exception' => $e]);\n\t\t\tthrow new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);\n\t\t} catch (NotFoundException $e) {\n\t\t\tthrow new \\OCP\\Files\\NotFoundException($e->getMessage(), 0, $e);\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getHookModuleExecList($hook_name = null)\n {\n $context = Context::getContext();\n $cache_id = 'hook_module_exec_list_'.(isset($context->shop->id) ? '_'.$context->shop->id : '').((isset($context->customer)) ? '_'.$context->customer->id : '');\n if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayPaymentEU' || $hook_name == 'displayBackOfficeHeader') {\n $frontend = true;\n $groups = array();\n $use_groups = Group::isFeatureActive();\n if (isset($context->employee)) {\n $frontend = false;\n } else {\n // Get groups list\n if ($use_groups) {\n if (isset($context->customer) && $context->customer->isLogged()) {\n $groups = $context->customer->getGroups();\n } elseif (isset($context->customer) && $context->customer->isLogged(true)) {\n $groups = array((int)Configuration::get('PS_GUEST_GROUP'));\n } else {\n $groups = array((int)Configuration::get('PS_UNIDENTIFIED_GROUP'));\n }\n }\n }\n\n // SQL Request\n $sql = new DbQuery();\n $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module, h.`live_edit`');\n $sql->from('module', 'm');\n if ($hook_name != 'displayBackOfficeHeader') {\n $sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & '.(int)Context::getContext()->getDevice()));\n $sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');\n }\n $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');\n $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');\n if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU') {\n $sql->where('h.`name` != \"displayPayment\" AND h.`name` != \"displayPaymentEU\"');\n }\n // For payment modules, we check that they are available in the contextual country\n elseif ($frontend) {\n if (Validate::isLoadedObject($context->country)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\") AND (SELECT `id_country` FROM `'._DB_PREFIX_.'module_country` mc WHERE mc.`id_module` = m.`id_module` AND `id_country` = '.(int)$context->country->id.' AND `id_shop` = '.(int)$context->shop->id.' LIMIT 1) = '.(int)$context->country->id.')');\n }\n if (Validate::isLoadedObject($context->currency)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\") AND (SELECT `id_currency` FROM `'._DB_PREFIX_.'module_currency` mcr WHERE mcr.`id_module` = m.`id_module` AND `id_currency` IN ('.(int)$context->currency->id.', -1, -2) LIMIT 1) IN ('.(int)$context->currency->id.', -1, -2))');\n }\n }\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('hm.`id_shop` = '.(int)$context->shop->id);\n }\n\n if ($frontend) {\n if ($use_groups) {\n $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('mg.`id_shop` = '.((int)$context->shop->id).(count($groups) ? ' AND mg.`id_group` IN ('.implode(', ', $groups).')' : ''));\n } elseif (count($groups)) {\n $sql->where('mg.`id_group` IN ('.implode(', ', $groups).')');\n }\n }\n }\n\n $sql->groupBy('hm.id_hook, hm.id_module');\n $sql->orderBy('hm.`position`');\n\n $list = array();\n if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {\n foreach ($result as $row) {\n $row['hook'] = strtolower($row['hook']);\n if (!isset($list[$row['hook']])) {\n $list[$row['hook']] = array();\n }\n\n $list[$row['hook']][] = array(\n 'id_hook' => $row['id_hook'],\n 'module' => $row['module'],\n 'id_module' => $row['id_module'],\n 'live_edit' => $row['live_edit'],\n );\n }\n }\n if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU' && $hook_name != 'displayBackOfficeHeader') {\n Cache::store($cache_id, $list);\n // @todo remove this in 1.6, we keep it in 1.5 for backward compatibility\n self::$_hook_modules_cache_exec = $list;\n }\n } else {\n $list = Cache::retrieve($cache_id);\n }\n\n // If hook_name is given, just get list of modules for this hook\n if ($hook_name) {\n $retro_hook_name = strtolower(Hook::getRetroHookName($hook_name));\n $hook_name = strtolower($hook_name);\n\n $return = array();\n $inserted_modules = array();\n if (isset($list[$hook_name])) {\n $return = $list[$hook_name];\n }\n foreach ($return as $module) {\n $inserted_modules[] = $module['id_module'];\n }\n if (isset($list[$retro_hook_name])) {\n foreach ($list[$retro_hook_name] as $retro_module_call) {\n if (!in_array($retro_module_call['id_module'], $inserted_modules)) {\n $return[] = $retro_module_call;\n }\n }\n }\n\n return (count($return) > 0 ? $return : false);\n } else {\n return $list;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function readfilePart($path, $from, $to) {\n\t\t$this->assertPathLength($path);\n\t\tif (ob_get_level()) {\n\t\t\tob_end_clean();\n\t\t}\n\t\t$handle = $this->fopen($path, 'rb');\n\t\tif ($handle) {\n\t\t\t$chunkSize = 524288; // 512 kiB chunks\n\t\t\t$startReading = true;\n\n\t\t\tif ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {\n\t\t\t\t// forward file handle via chunked fread because fseek seem to have failed\n\n\t\t\t\t$end = $from + 1;\n\t\t\t\twhile (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {\n\t\t\t\t\t$len = $from - ftell($handle);\n\t\t\t\t\tif ($len > $chunkSize) {\n\t\t\t\t\t\t$len = $chunkSize;\n\t\t\t\t\t}\n\t\t\t\t\t$result = fread($handle, $len);\n\n\t\t\t\t\tif ($result === false) {\n\t\t\t\t\t\t$startReading = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($startReading) {\n\t\t\t\t$end = $to + 1;\n\t\t\t\twhile (!feof($handle) && ftell($handle) < $end) {\n\t\t\t\t\t$len = $end - ftell($handle);\n\t\t\t\t\tif ($len > $chunkSize) {\n\t\t\t\t\t\t$len = $chunkSize;\n\t\t\t\t\t}\n\t\t\t\t\techo fread($handle, $len);\n\t\t\t\t\tflush();\n\t\t\t\t\t$this->checkConnectionStatus();\n\t\t\t\t}\n\t\t\t\treturn ftell($handle) - $from;\n\t\t\t}\n\n\t\t\tthrow new \\OCP\\Files\\UnseekableException('fseek error');\n\t\t}\n\t\treturn false;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function buildContextFromArray(array $config, $name = null, $storageRole = Context::STORAGE_ROLE_CHILD)\n {\n $type = in_array($config['type'], Context::getTypes()) ? $config['type'] : Context::TYPE_STANDARD;\n $technology = in_array($config['technology'], Context::getTechnologies()) ? $config['technology'] : Context::TECH_GENERIC;\n $context = new Context($name, null, $type, $storageRole);\n $context->setTechnology($technology);\n $context->setMappedTo($config['mapped_to'] ?: '');\n\n if (is_array($config['fields'])) {\n $fields = $config['fields'];\n\n // Iterate all fields and create a rule set\n foreach ($fields as $fieldData ) {\n $vulnElement = $this->buildVulnerabilityElementFromArray($fieldData['vulnerabilities']);\n\n $source = $fieldData['source'] ?: FieldDescriptor::SOURCE_ANY;\n\n if (!in_array($source, FieldDescriptor::getSources())) {\n throw new \\InvalidArgumentException(\"Invalid source for field '{$fieldData['name']}': \" . $source);\n }\n\n $field = new Field($fieldData['name'], $vulnElement, $source);\n $context->addField($field);\n }\n }\n\n if (is_array($config['children'])) {\n foreach ($config['children'] as $contextName => $contextData) {\n $child = $this->buildContextFromArray($contextData, $contextName);\n $context->addChild($child);\n }\n }\n\n\n if (is_array($config['vulnerabilities'])) {\n $vulnElement = $this->buildVulnerabilityElementFromArray($config['vulnerabilities']);\n $context->setVulnTree($vulnElement);\n }\n\n return $context;\n }", "smellKey": "S3776", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "function conversionFormulaGeometry() {\n\n $args = func_get_args();\n\n #region Argument verification\n\n\tif (count($args)==0) {\n\t\t$firstPart = \"C\"; // Circle is the default\n\t} else {\n $firstPart = strtoupper(substr((string)$args[0], 0, 1));\n }\n\n if ( count($args)>1 && !is_null($args[1]) ) {\n $tick = verifyTickMarks($args[1]);\n } else {\n $tick = \"\";\n }\n\n if ( count($args)>2 && !is_null($args[2]) ) {\n $PI = verifyPI($args[2]);\n } else {\n $PI = \" pi \";\n }\n\n\t#endregion\n\n $retval = array();\n\n if($firstPart==\"C\") {$type=\"Circle\";}\n if($firstPart==\"T\") {$type=\"Triangle\";}\n if($firstPart==\"R\") {$type=\"Rectangle\";}\n if($firstPart==\"S\") {$type=\"Square\";}\n if($firstPart==\"A\") {$type=\"SurfaceArea\";}\n if($firstPart==\"V\") {$type=\"Volume\";}\n\n if($type==\"Circle\") {\n $retval[0] = \"{$tick}C = {$PI}d{$tick}\";\n $retval[1] = \"{$tick}C = 2{$PI}r{$tick}\";\n $retval[2] = \"{$tick}A=$PI r^2{$tick}\";\n } elseif($type==\"Triangle\") {\n $retval[0] = \"P = \"._(\"add all sides\");\n $retval[1] = \"{$tick}A = 1/2bh{$tick}\";\n } elseif($type==\"Rectangle\") {\n $retval[0] = \"{$tick}P = 2W+2L{$tick}\";\n $retval[1] = \"{$tick}A = LW{$tick}\";\n } elseif($type==\"Square\") {\n $retval[0] = \"{$tick}P = 4s{$tick}\";\n $retval[1] = \"{$tick}A = s^2{$tick}\";\n } elseif($type==\"SurfaceArea\") {\n $retval[0] = \"{$tick}SA=2LW+2LH+2WH{$tick} \"._(\"(Surface Area of a Rectangular Solid)\");\n $retval[1] = \"{$tick}SA=6 s^2{$tick} \"._(\"(Surface Area of a Cube)\");\n $retval[2] = \"{$tick}SA=4{$PI}r^2{$tick} \"._(\"(Surface Area of a Sphere)\");\n $retval[3] = \"{$tick}SA=2{$PI}rh+2{$PI}r^2{$tick} \"._(\"(Surface Area of a Right Circular Cylinder)\");\n } elseif($type==\"Volume\") {\n $retval[0] = \"{$tick}V = LWH{$tick} \"._(\"(Volume of a Rectangular Solid)\");\n $retval[1] = \"{$tick}V = s^3{$tick} \"._(\"(Volume of a Cube)\");\n $retval[2] = \"{$tick}V = 4/3{$PI}r^3{$tick} \"._(\"(Volume of a Sphere)\");\n $retval[3] = \"{$tick}V = {$PI}hr^2{$tick} \"._(\"(Volume of a Right Circular Cylinder)\");\n } else {\n $retval[0] = \"'\".(string)$type.\"' \".isnotvalid();\n }\n\n return $retval;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function sliding_pager($params)\n\t{\n\t\t/*\n\t\t\t@param mixed $pagecount - number of pages to browse\n\t\t\t@param int $linknum - max. number of links to show on one page (default: 5)\n\t\t\t@param int $curpage - current page number\n\t\t\t@param string baseurl - baseurl to which the pagenumber will appended\n\t\t\t@param string urlAppend - text to append to url after pagenumber, e.g. \"html\" (default: \"\")\n\t\t\t@param string txtPre - laat zien voor de paginering\n\t\t\t@param string txtFirst - text for link to first page (default: \"<<\")\n\t\t\t@param string txtPrev - text for link to previous page (default: \"<\")\n\t\t\t@param string separator - text to print between page numbers (default: \" \")\n\t\t\t@param string txtNext - text for link to next page (default: \">\")\n\t\t\t@param string txtLast - text for link to last page (default: \">>\")\n\t\t\t@param string txtPost - laat zien na de paginering\n\t\t\t@param string txtSkip - text shown when page s are skipped (not shown) (default: \"\u2026\")\n\t\t\t@param string cssClass - css class for the pager (default: \"\")\n\t\t\t@param boolean linkCurrent - whether to link the current page (default: false)\n\t\t\t@param boolean showAlways - als er maar 1 pagina is, toch laten zien\n\t\t\t@param boolean showFirstLast - eerste/laatste links laten zien\n\t\t\t@param boolean showPrevNext - vorige/volgende links laten zien\n\t\t */\n\n\t\t/* Define all vars with default value */\n\t\t$pagecount = 0;\n\t\t$curpage = 0;\n\t\t$baseurl = '';\n\t\t$linknum = 3;\n\t\t$urlAppend = '';\n\t\t$txtPrev = '<';\n\t\t$separator = '';\n\t\t$txtNext = '>';\n\t\t$txtSkip = '\u2026';\n\t\t$cssClass = '';\n\t\t$showPrevNext = true;\n\n\t\t/* Import parameters */\n\t\textract($params);\n\n\t\t/* Convert page count if array */\n\t\tif (is_array($pagecount)) {\n\t\t\t$pagecount = sizeof($pagecount);\n\t\t}\n\n\t\t/* Define additional required vars */\n\t\tif ($linknum % 2 == 0) {\n\t\t\t$deltaL = $linknum / 2 - 1;\n\t\t\t$deltaR = $linknum / 2;\n\t\t} else {\n\t\t\t$deltaL = $deltaR = ($linknum - 1) / 2;\n\t\t}\n\n\t\t/* There is no 0th page: assume last page */\n\t\t$curpage = $curpage == 0 ? $pagecount : $curpage;\n\n\t\t/* Internally we need an \"array-compatible\" index */\n\t\t$intCurpage = $curpage - 1;\n\n\t\t/* Paging needed? */\n\t\tif ($pagecount <= 1) {\n\t\t\t// No paging needed for one page\n\t\t\treturn '';\n\t\t}\n\n\t\t/* Build all page links (we'll delete some later if required) */\n\t\t$links = [];\n\t\tfor ($i = 0; $i < $pagecount; $i++) {\n\t\t\t$links[$i] = $i + 1;\n\t\t}\n\n\t\t/* Sliding needed? */\n\t\tif ($pagecount > $linknum) {\n\t\t\t// Yes\n\t\t\tif ($intCurpage - $deltaL < 1) {\n\t\t\t\t// Delta_l needs adjustment, we are too far left\n\t\t\t\t$deltaL = $intCurpage - 1;\n\t\t\t\t$deltaR = $linknum - $deltaL - 1;\n\t\t\t}\n\t\t\tif ($intCurpage + $deltaR > $pagecount) {\n\t\t\t\t// Delta_r needs adjustment, we are too far right\n\t\t\t\t$deltaR = $pagecount - $intCurpage;\n\t\t\t\t$deltaL = $linknum - $deltaR - 1;\n\t\t\t}\n\t\t\tif ($intCurpage - $deltaL > 1) {\n\t\t\t\t// Let's do some cutting on the left side\n\t\t\t\tarray_splice($links, 0, $intCurpage - $deltaL);\n\t\t\t}\n\t\t\tif ($intCurpage + $deltaR < $pagecount) {\n\t\t\t\t// The right side will also need some treatment\n\t\t\t\tarray_splice($links, $intCurpage + $deltaR + 2 - $links[0]);\n\t\t\t}\n\t\t}\n\n\t\t/* Build link bar */\n\t\t$retval = '';\n\t\t$cssClass = $cssClass ? 'class=\"' . $cssClass . '\"' : '';\n\t\tif ($curpage > 1 && $showPrevNext) {\n\t\t\tif ($txtPrev != '<') {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t\t$baseurl .\n\t\t\t\t\t($curpage - 1) .\n\t\t\t\t\t$urlAppend .\n\t\t\t\t\t'\" ' .\n\t\t\t\t\t$cssClass .\n\t\t\t\t\t'>' .\n\t\t\t\t\t$txtPrev .\n\t\t\t\t\t'</a></li>';\n\t\t\t} else {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t\t$baseurl .\n\t\t\t\t\t($curpage - 1) .\n\t\t\t\t\t$urlAppend .\n\t\t\t\t\t'\" ' .\n\t\t\t\t\t$cssClass .\n\t\t\t\t\t' aria-label=\"Vorige\">' .\n\t\t\t\t\tIcon::getTag('chevron-left', null, 'Vorige', 'pagination') .\n\t\t\t\t\t'</a></li>';\n\t\t\t}\n\n\t\t\t$retval .= $separator;\n\t\t}\n\t\tif ($links[0] != 1) {\n\t\t\t$retval .=\n\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t$baseurl .\n\t\t\t\t'1' .\n\t\t\t\t$urlAppend .\n\t\t\t\t'\" ' .\n\t\t\t\t$cssClass .\n\t\t\t\t'>1</a></li>';\n\t\t\tif ($links[0] == 2) {\n\t\t\t\t$retval .= $separator;\n\t\t\t} else {\n\t\t\t\t$retval .=\n\t\t\t\t\t$separator .\n\t\t\t\t\t'<li class=\"page-item\"><span class=\"page-link\">' .\n\t\t\t\t\t$txtSkip .\n\t\t\t\t\t'</span></li>' .\n\t\t\t\t\t$separator;\n\t\t\t}\n\t\t}\n\t\tfor ($i = 0; $i < sizeof($links); $i++) {\n\t\t\tif ($links[$i] != $curpage) {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t\t$baseurl .\n\t\t\t\t\t$links[$i] .\n\t\t\t\t\t$urlAppend .\n\t\t\t\t\t'\" ' .\n\t\t\t\t\t$cssClass .\n\t\t\t\t\t'>' .\n\t\t\t\t\t$links[$i] .\n\t\t\t\t\t'</a></li>';\n\t\t\t} else {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item active\" aria-current=\"page\"><span class=\"page-link\">' .\n\t\t\t\t\t$links[$i] .\n\t\t\t\t\t'</span></li>';\n\t\t\t}\n\n\t\t\tif ($i < sizeof($links) - 1) {\n\t\t\t\t$retval .= $separator;\n\t\t\t}\n\t\t}\n\t\tif ($links[sizeof($links) - 1] != $pagecount) {\n\t\t\tif ($links[sizeof($links) - 2] != $pagecount - 1) {\n\t\t\t\t$retval .=\n\t\t\t\t\t$separator .\n\t\t\t\t\t'<li class=\"page-item\"><span class=\"page-link\">' .\n\t\t\t\t\t$txtSkip .\n\t\t\t\t\t'</span></li>' .\n\t\t\t\t\t$separator;\n\t\t\t} else {\n\t\t\t\t$retval .= $separator;\n\t\t\t}\n\t\t\t$retval .=\n\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t$baseurl .\n\t\t\t\t$pagecount .\n\t\t\t\t$urlAppend .\n\t\t\t\t'\" ' .\n\t\t\t\t$cssClass .\n\t\t\t\t'>' .\n\t\t\t\t$pagecount .\n\t\t\t\t'</a></li>';\n\t\t}\n\t\tif ($curpage != $pagecount && $showPrevNext) {\n\t\t\t$retval .= $separator;\n\n\t\t\tif ($txtNext != '>') {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t\t$baseurl .\n\t\t\t\t\t($curpage + 1) .\n\t\t\t\t\t$urlAppend .\n\t\t\t\t\t'\" ' .\n\t\t\t\t\t$cssClass .\n\t\t\t\t\t'>' .\n\t\t\t\t\t$txtNext .\n\t\t\t\t\t'</a></li>';\n\t\t\t} else {\n\t\t\t\t$retval .=\n\t\t\t\t\t'<li class=\"page-item\"><a class=\"page-link\" href=\"' .\n\t\t\t\t\t$baseurl .\n\t\t\t\t\t($curpage + 1) .\n\t\t\t\t\t$urlAppend .\n\t\t\t\t\t'\" ' .\n\t\t\t\t\t$cssClass .\n\t\t\t\t\t' aria-label=\"Volgende\">' .\n\t\t\t\t\tIcon::getTag('chevron-right', null, 'Volgende', 'pagination') .\n\t\t\t\t\t'</a></li>';\n\t\t\t}\n\t\t}\n\t\treturn $retval;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, array $params = []): void\n {\n if (!$omitMandatoryCheck && $this->getMandatory() && empty($data)) {\n throw new Element\\ValidationException('Empty mandatory field [ ' . $this->getName() . ' ]');\n }\n\n if (is_array($data)) {\n $this->performMultipleAssignmentCheck($data);\n foreach ($data as $elementMetadata) {\n if (!($elementMetadata instanceof DataObject\\Data\\ElementMetadata)) {\n throw new Element\\ValidationException('Expected DataObject\\\\Data\\\\ElementMetadata');\n }\n\n $d = $elementMetadata->getElement();\n\n if ($d instanceof Document) {\n $allow = $this->allowDocumentRelation($d);\n } elseif ($d instanceof Asset) {\n $allow = $this->allowAssetRelation($d);\n } elseif ($d instanceof DataObject\\AbstractObject) {\n $allow = $this->allowObjectRelation($d);\n } elseif (empty($d)) {\n $allow = true;\n } else {\n $allow = false;\n }\n if (!$allow) {\n throw new Element\\ValidationException(sprintf('Invalid relation in field `%s` [type: %s]', $this->getName(), $this->getFieldtype()));\n }\n }\n\n if ($this->getMaxItems() && count($data) > $this->getMaxItems()) {\n throw new Element\\ValidationException('Number of allowed relations in field `' . $this->getName() . '` exceeded (max. ' . $this->getMaxItems() . ')');\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function after()\n {\n $this->response->setHeader('Content-Type', $this->responseFormat . '; charset=utf-8');\n\n if ($this->request->method == 'HEAD') {\n $this->response->body = '';\n return;\n }\n\n if ($this->response->body instanceof Model) {\n /** @var Model $tmpData */\n $tmpData = $this->response->body;\n $tmpData = $tmpData->as_array();\n\n foreach ($tmpData as $key => $field) {\n if (!in_array($key, $this->exposedFields()) && $key != $this->model->id_field) {\n unset($tmpData[$key]);\n }\n }\n $this->response->body = $tmpData;\n }\n\n if ($this->isCollectionRequested) {\n $this->response->body = array_merge([\n 'data' => $this->response->body,\n ], $this->meta);\n }\n\n if ($this->responseFormat == self::FORMAT_XML) {\n $this->response->body = $this->asXML(is_array($this->response->body) ? $this->response->body : []);\n\n } else {\n $this->response->body = $this->response->body || is_array($this->response->body)\n ? json_encode($this->response->body) : '';\n }\n\n if (!is_string($this->response->body)) {\n $this->response->body = (string) $this->response->body;\n }\n\n //file_put_contents(__DIR__.'/../../../rest.log', date('Y-m-d H:i:s') . \"\\n\" . $this->response->body . \"\\n\\n\\n\", FILE_APPEND);\n\n if (!($this instanceof ErrorController)) {\n parent::after();\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "ChristosPapadopoulos23_hackazon", "language": "php"} {"function": "protected function RenderXML($page, $additionalProps = null, $supressProps = null, $noMap = false)\n {\n require_once(\"verysimple/String/VerySimpleStringUtil.php\");\n\n if (! is_array($supressProps)) {\n $supressProps = array ();\n }\n\n // never include these props\n $suppressProps [] = \"NoCache\";\n $suppressProps [] = \"CacheLevel\";\n $suppressProps [] = \"IsLoaded\";\n $suppressProps [] = \"IsPartiallyLoaded\";\n\n $xml = \"\";\n $xml .= \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\r\\n\";\n\n $xml .= \"<DataPage>\\r\\n\";\n $xml .= \"<ObjectName>\" . htmlspecialchars($page->ObjectName) . \"</ObjectName>\\r\\n\";\n $xml .= \"<ObjectKey>\" . htmlspecialchars($page->ObjectKey) . \"</ObjectKey>\\r\\n\";\n $xml .= \"<TotalRecords>\" . htmlspecialchars($page->TotalResults) . \"</TotalRecords>\\r\\n\";\n $xml .= \"<TotalPages>\" . htmlspecialchars($page->TotalPages) . \"</TotalPages>\\r\\n\";\n $xml .= \"<CurrentPage>\" . htmlspecialchars($page->CurrentPage) . \"</CurrentPage>\\r\\n\";\n $xml .= \"<PageSize>\" . htmlspecialchars($page->PageSize) . \"</PageSize>\\r\\n\";\n\n $xml .= \"<Records>\\r\\n\";\n\n // get the fieldmap for this object type unless not specified\n if ($noMap) {\n $fms = array ();\n } else {\n try {\n $fms = $this->Phreezer->GetFieldMaps($page->ObjectName);\n } catch (exception $ex) {\n throw new Exception(\"The objects contained in this DataPage do not have a FieldMap. Set noMap argument to true to supress this error: \" . $ex->getMessage());\n }\n }\n\n foreach ($page->Rows as $obj) {\n $xml .= \"<\" . htmlspecialchars($page->ObjectName) . \">\\r\\n\";\n foreach (get_object_vars($obj) as $var => $val) {\n if (! in_array($var, $supressProps)) {\n // depending on what type of field this is, do some special formatting\n $fm = isset($fms [$var]) ? $fms [$var]->FieldType : FM_TYPE_UNKNOWN;\n\n if ($fm == FM_TYPE_DATETIME) {\n $val = strtotime($val) ? date(\"m/d/Y h:i A\", strtotime($val)) : $val;\n } elseif ($fm == FM_TYPE_DATE) {\n $val = strtotime($val) ? date(\"m/d/Y\", strtotime($val)) : $val;\n }\n\n // if the developer has added a property that is not a simple type\n // we need to serialize it\n if (is_array($val) || is_object($val)) {\n $val = serialize($val);\n }\n\n $val = VerySimpleStringUtil::EncodeSpecialCharacters($val, true, true);\n\n $xml .= \"<\" . htmlspecialchars($var) . \">\" . $val . \"</\" . htmlspecialchars($var) . \">\\r\\n\";\n }\n }\n\n // Add any properties that we want from child objects\n if ($additionalProps) {\n foreach ($additionalProps as $meth => $propPair) {\n $props = explode(\",\", $propPair);\n foreach ($props as $prop) {\n $xml .= \"<\" . htmlspecialchars($meth . $prop) . \">\" . htmlspecialchars($obj->$meth()->$prop) . \"</\" . htmlspecialchars($meth . $prop) . \">\\r\\n\";\n }\n }\n }\n\n $xml .= \"</\" . htmlspecialchars($page->ObjectName) . \">\\r\\n\";\n }\n\n $xml .= \"</Records>\\r\\n\";\n\n $xml .= \"</DataPage>\\r\\n\";\n\n // capture output instead of rendering if specified\n if ($this->CaptureOutputMode) {\n $this->DebugOutput = $xml;\n } else {\n header('Content-type: text/xml');\n print $xml;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function save($refetch=false) {\n if ($this->__deleted__)\n throw new OrmException('Trying to update a deleted object');\n\n $pk = static::getMeta('pk');\n $wasnew = $this->__new__;\n\n // First, if any foreign properties of this object are connected to\n // another *new* object, then save those objects first and set the\n // local foreign key field values\n foreach (static::getMeta('joins') as $prop => $j) {\n if (isset($this->ht[$prop])\n && ($foreign = $this->ht[$prop])\n && $foreign instanceof VerySimpleModel\n && !in_array($j['local'], $pk)\n && null === $this->get($j['local'])\n ) {\n if ($foreign->__new__ && !$foreign->save())\n return false;\n $this->set($j['local'], $foreign->get($j['fkey'][1]));\n }\n }\n\n // If there's nothing in the model to be saved, then we're done\n if (count($this->dirty) === 0)\n return true;\n\n $ex = DbEngine::save($this);\n try {\n $ex->execute();\n if ($ex->affected_rows() != 1) {\n // This doesn't really signify an error. It just means that\n // the database believes that the row did not change. For\n // inserts though, it's a deal breaker\n if ($this->__new__)\n return false;\n else\n // No need to reload the record if requested \u2014 the\n // database didn't update anything\n $refetch = false;\n }\n }\n catch (OrmException $e) {\n return false;\n }\n\n if ($wasnew) {\n if (count($pk) == 1)\n // XXX: Ensure AUTO_INCREMENT is set for the field\n $this->ht[$pk[0]] = $ex->insert_id();\n $this->__new__ = false;\n Signal::send('model.created', $this);\n }\n else {\n $data = array('dirty' => $this->dirty);\n Signal::send('model.updated', $this, $data);\n foreach ($this->dirty as $key => $value) {\n if ($key != 'value' && $key != 'updated') {\n $type = array('type' => 'edited', 'key' => $key, 'orm_audit' => true);\n Signal::send('object.edited', $this, $type);\n }\n }\n }\n # Refetch row from database\n if ($refetch) {\n // Preserve non database information such as list relationships\n // across the refetch\n $this->refetch();\n }\n if ($wasnew) {\n // Attempt to update foreign, unsaved objects with the PK of\n // this newly created object\n foreach (static::getMeta('joins') as $prop => $j) {\n if (isset($this->ht[$prop])\n && ($foreign = $this->ht[$prop])\n && in_array($j['local'], $pk)\n ) {\n if ($foreign instanceof VerySimpleModel\n && null === $foreign->get($j['fkey'][1])\n ) {\n $foreign->set($j['fkey'][1], $this->get($j['local']));\n }\n elseif ($foreign instanceof InstrumentedList) {\n foreach ($foreign as $item) {\n if (null === $item->get($j['fkey'][1]))\n $item->set($j['fkey'][1], $this->get($j['local']));\n }\n }\n }\n }\n $this->__onload();\n }\n $this->dirty = array();\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function testClasses($app) {\n\t\t$appInfo = \\OCP\\Server::get(IAppManager::class)->getAppInfo($app);\n\t\t$appPath = \\OC_App::getAppPath($app);\n\t\t\\OC_App::registerAutoloading($app, $appPath);\n\n\t\t//Add the appcontainer\n\t\t$applicationClassName = \\OCP\\AppFramework\\App::buildAppNamespace($app) . '\\\\AppInfo\\\\Application';\n\t\tif (class_exists($applicationClassName)) {\n\t\t\t$application = new $applicationClassName();\n\t\t\t$this->addToAssertionCount(1);\n\t\t} else {\n\t\t\t$application = new \\OCP\\AppFramework\\App($app);\n\t\t\t$this->addToAssertionCount(1);\n\t\t}\n\n\t\tif (isset($appInfo['background-jobs'])) {\n\t\t\tforeach ($appInfo['background-jobs'] as $job) {\n\t\t\t\t$this->assertTrue(class_exists($job), 'Asserting background job \"' . $job . '\" exists');\n\t\t\t\t$this->assertInstanceOf($job, \\OC::$server->query($job));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['two-factor-providers'])) {\n\t\t\tforeach ($appInfo['two-factor-providers'] as $provider) {\n\t\t\t\t$this->assertTrue(class_exists($provider), 'Asserting two-factor providers \"' . $provider . '\" exists');\n\t\t\t\t$this->assertInstanceOf($provider, \\OC::$server->query($provider));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['commands'])) {\n\t\t\tforeach ($appInfo['commands'] as $command) {\n\t\t\t\t$this->assertTrue(class_exists($command), 'Asserting command \"' . $command . '\" exists');\n\t\t\t\t$this->assertInstanceOf($command, \\OC::$server->query($command));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['repair-steps']['pre-migration'])) {\n\t\t\tforeach ($appInfo['repair-steps']['pre-migration'] as $migration) {\n\t\t\t\t$this->assertTrue(class_exists($migration), 'Asserting pre-migration \"' . $migration . '\" exists');\n\t\t\t\t$this->assertInstanceOf($migration, \\OC::$server->query($migration));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['repair-steps']['post-migration'])) {\n\t\t\tforeach ($appInfo['repair-steps']['post-migration'] as $migration) {\n\t\t\t\t$this->assertTrue(class_exists($migration), 'Asserting post-migration \"' . $migration . '\" exists');\n\t\t\t\t$this->assertInstanceOf($migration, \\OC::$server->query($migration));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['repair-steps']['live-migration'])) {\n\t\t\tforeach ($appInfo['repair-steps']['live-migration'] as $migration) {\n\t\t\t\t$this->assertTrue(class_exists($migration), 'Asserting live-migration \"' . $migration . '\" exists');\n\t\t\t\t$this->assertInstanceOf($migration, \\OC::$server->query($migration));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['repair-steps']['install'])) {\n\t\t\tforeach ($appInfo['repair-steps']['install'] as $migration) {\n\t\t\t\t$this->assertTrue(class_exists($migration), 'Asserting install-migration \"' . $migration . '\" exists');\n\t\t\t\t$this->assertInstanceOf($migration, \\OC::$server->query($migration));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['repair-steps']['uninstall'])) {\n\t\t\tforeach ($appInfo['repair-steps']['uninstall'] as $migration) {\n\t\t\t\t$this->assertTrue(class_exists($migration), 'Asserting uninstall-migration \"' . $migration . '\" exists');\n\t\t\t\t$this->assertInstanceOf($migration, \\OC::$server->query($migration));\n\t\t\t}\n\t\t}\n\n\t\tif (isset($appInfo['commands'])) {\n\t\t\tforeach ($appInfo['commands'] as $command) {\n\t\t\t\t$this->assertTrue(class_exists($command), 'Asserting command \"'. $command . '\"exists');\n\t\t\t\t$this->assertInstanceOf($command, \\OC::$server->query($command));\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function post_updateItem($history = true)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n parent::post_updateItem($history);\n\n // Put same status on duplicated tickets when solving or closing (autoclose on solve)\n if (\n isset($this->input['status'])\n && in_array('status', $this->updates)\n && (in_array($this->input['status'], $this->getSolvedStatusArray())\n || in_array($this->input['status'], $this->getClosedStatusArray()))\n ) {\n CommonITILObject_CommonITILObject::manageLinksOnChange('Ticket', $this->getID(), [\n 'status' => $this->input['status'],\n ]);\n }\n\n $donotif = count($this->updates);\n\n if (isset($this->input['_forcenotif'])) {\n $donotif = true;\n }\n\n // Manage SLA / OLA Level : add actions\n foreach ([SLM::TTR, SLM::TTO] as $slmType) {\n list($dateField, $slaField) = SLA::getFieldNames($slmType);\n if (\n in_array($slaField, $this->updates)\n && ($this->fields[$slaField] > 0)\n ) {\n $this->manageSlaLevel($this->fields[$slaField]);\n }\n\n list($dateField, $olaField) = OLA::getFieldNames($slmType);\n if (\n in_array($olaField, $this->updates)\n && ($this->fields[$olaField] > 0)\n ) {\n $this->manageOlaLevel($this->fields[$olaField]);\n }\n }\n\n if (count($this->updates)) {\n // Update Ticket Tco\n if (\n in_array(\"actiontime\", $this->updates)\n || in_array(\"cost_time\", $this->updates)\n || in_array(\"cost_fixed\", $this->updates)\n || in_array(\"cost_material\", $this->updates)\n ) {\n if (!empty($this->input[\"items_id\"])) {\n foreach ($this->input[\"items_id\"] as $itemtype => $items) {\n foreach ($items as $items_id) {\n if ($itemtype && ($item = getItemForItemtype($itemtype))) {\n if ($item->getFromDB($items_id)) {\n $newinput = [];\n $newinput['id'] = $items_id;\n $newinput['ticket_tco'] = self::computeTco($item);\n $item->update($newinput);\n }\n }\n }\n }\n }\n }\n\n $donotif = true;\n }\n\n if (isset($this->input['_disablenotif'])) {\n $donotif = false;\n }\n\n if ($donotif && $CFG_GLPI[\"use_notifications\"]) {\n $mailtype = \"update\";\n\n if (\n isset($this->input[\"status\"])\n && $this->input[\"status\"]\n && in_array(\"status\", $this->updates)\n && in_array($this->input[\"status\"], $this->getSolvedStatusArray())\n ) {\n $mailtype = \"solved\";\n }\n\n if (\n isset($this->input[\"status\"])\n && $this->input[\"status\"]\n && in_array(\"status\", $this->updates)\n && in_array($this->input[\"status\"], $this->getClosedStatusArray())\n ) {\n $mailtype = \"closed\";\n }\n // to know if a solution is approved or not\n if (\n (isset($this->input['solvedate']) && ($this->input['solvedate'] == 'NULL')\n && isset($this->oldvalues['solvedate']) && $this->oldvalues['solvedate'])\n && (isset($this->input['status'])\n && ($this->input['status'] != $this->oldvalues['status'])\n && ($this->oldvalues['status'] == self::SOLVED))\n ) {\n $mailtype = \"rejectsolution\";\n }\n\n // Read again ticket to be sure that all data are up to date\n $this->getFromDB($this->fields['id']);\n NotificationEvent::raiseEvent($mailtype, $this);\n }\n\n $this->handleSatisfactionSurveyOnUpdate();\n\n // Add linked project\n $projects_ids = $this->input['_projects_id'] ?? [];\n foreach ($projects_ids as $projects_id) {\n if ($projects_id) {\n $item_project = new Item_Project();\n $item_project->add([\n 'projects_id' => $projects_id,\n 'itemtype' => Ticket::class,\n 'items_id' => $this->getID(),\n ]);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function Header()\n {\n // Logo\n //$image_file = K_PATH_IMAGES.'logo_example.jpg';\n if (trim($this->logo) != \"\") {\n if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo)) {\n $image_file = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo;\n if (in_array($this->schemeType, ['recency', 'dts', 'vl', 'eid', 'tb']) && $this->layout == 'zimbabwe') {\n $this->Image($image_file, 88, 15, 25, '', '', '', 'C', false, 300, '', false, false, 0, false, false, false);\n } elseif ($this->schemeType == 'dts' && $this->layout == 'jamaica') {\n $this->Image($image_file, 90, 13, 25, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);\n } elseif ($this->schemeType == 'dts' && $this->layout == 'myanmar') {\n $this->Image($image_file, 10, 2, 25, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);\n } elseif ($this->schemeType == 'vl' && $this->layout == 'myanmar') {\n $this->Image($image_file, 10, 05, 22, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);\n } else {\n $this->Image($image_file, 10, 8, 25, '', '', '', 'T', false, 300, '', false, false, 0, false, false, false);\n }\n }\n }\n $screening = \"\";\n if (isset($this->dtsPanelType) && !empty($this->dtsPanelType)) {\n $screening = \" - \" . ucwords($this->dtsPanelType);\n }\n // Set font\n $this->SetFont('helvetica', '', 10);\n //$this->header = nl2br(trim($this->header));\n //$this->header = preg_replace('/<br>$/', \"\", $this->header);\n\n if (isset($this->config->instituteAddress) && $this->config->instituteAddress != \"\") {\n $instituteAddress = nl2br(stripcslashes(trim($this->config->instituteAddress)));\n } else {\n $instituteAddress = null;\n }\n if (isset($this->config->additionalInstituteDetails) && $this->config->additionalInstituteDetails != \"\") {\n $additionalInstituteDetails = nl2br(stripcslashes(trim($this->config->additionalInstituteDetails)));\n } else {\n $additionalInstituteDetails = null;\n }\n if ($this->schemeType == 'vl' && $this->layout != 'zimbabwe') {\n if (isset($this->config) && $this->config != \"\") {\n $html = '<span style=\"font-weight: bold;text-align:center;font-size:18px;\">' . $this->config->instituteName . '</span>\n <br/><span style=\"font-weight: bold;text-align:center;font-size:11;\">' . nl2br(stripcslashes(trim($this->header))) . '</span>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n }\n $html .= '<br/><br/><span style=\"font-weight: bold;text-align:center;font-size:12;\">Proficiency Testing Program for HIV-1 Viral Load using Dried Tube Specimen</span>';\n //$htmlTitle = '<span style=\"font-weight: bold;text-align:center;font-size:12;\">Proficiency Testing Program for HIV Viral Load using ' . $this->scheme_name . '</span><br><span style=\"font-weight: bold; font-size:13;text-align:center;\">All Participants Summary Report</span>';\n } else {\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>Proficiency Testing Program for HIV Viral Load using ' . $this->scheme_name . '</span>';\n }\n } elseif ($this->schemeType == 'eid' && $this->layout != 'zimbabwe') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;font-size:11;\">' . $this->header . '</span><br/>';\n if (isset($this->config) && $this->config != \"\") {\n $html = '<span style=\"font-weight: bold;text-align:center;font-size:18px;\">' . $this->config->instituteName . '</span>\n <br/><span style=\"font-weight: bold;text-align:center;font-size:11;\">' . nl2br(stripcslashes(trim($this->header))) . '</span>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n }\n //$htmlTitle = '<span style=\"font-weight: bold;text-align:center;font-size:13;\">Proficiency Testing Program for HIV-1 Early Infant Diagnosis using ' . $this->scheme_name . '</span><br><span style=\"font-weight: bold; font-size:13;text-align:center;\">All Participants Summary Report</span>';\n } else {\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>Proficiency Testing Program for HIV-1 Early Infant Diagnosis using ' . $this->scheme_name . '</span><br><span style=\"font-weight: bold; font-size:11;text-align:center;\">Individual Participant Results Report</span>';\n }\n } elseif ($this->schemeType == 'tb' && $this->layout != 'zimbabwe') {\n $this->SetFont('helvetica', '', 10);\n $html = '<div style=\"font-weight: bold;text-align:center;background-color:black;color:white;height:100px;\"><span style=\"text-align:center;font-size:11;\">' . $this->header . ' | INDIVIDUAL FINAL REPORT</span></div>';\n } elseif (($this->schemeType == 'recency' || $this->schemeType == 'dts') && $this->layout != 'zimbabwe' && $this->layout != 'myanmar') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n }\n $html .= '<br>Proficiency Testing Report - ' . $this->scheme_name . '</span><br><span style=\"font-weight: bold; font-size:11;text-align:center;\">Individual Participant Results Report ' . $screening . '</span>';\n } elseif ($this->schemeType == 'dts' && $this->layout == 'myanmar') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>';\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n }\n $html .= '<br><br>Proficiency Testing Report - ' . $this->scheme_name . '</span>';\n } elseif ($this->schemeType == 'dts' && $this->layout == 'jamaica') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span></span>';\n /* if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n } */\n } elseif (in_array($this->schemeType, ['recency', 'dts', 'vl', 'eid', 'tb']) && $this->layout == 'zimbabwe') {\n if ($this->schemeType != 'tb') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span></span>';\n $this->writeHTMLCell(0, 0, 15, 05, $html, 0, 0, 0, true, 'J', true);\n $htmlInAdd = '<span style=\"font-weight: normal;text-align:right;\">' . $instituteAddress . '</span>';\n $this->writeHTMLCell(0, 0, 15, 20, $htmlInAdd, 0, 0, 0, true, 'J', true);\n $htmlInDetails = '<span style=\"font-weight: normal;text-align:left;\">' . $additionalInstituteDetails . '</span>';\n $this->writeHTMLCell(0, 0, 10, 20, $htmlInDetails, 0, 0, 0, true, 'J', true);\n }\n if ($this->schemeType == 'dts') {\n $this->writeHTMLCell(0, 0, 10, 40, '<span style=\"font-weight: bold;text-align:center;\">' . 'Proficiency Testing Report - Rapid HIV Serology Test</span>', 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'recency') {\n $this->writeHTMLCell(0, 0, 10, 40, '<span style=\"font-weight: bold;text-align:center;\">' . 'Proficiency Testing Report Rapid Test for Recent Infection (RTRI)</span>', 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'vl') {\n $this->writeHTMLCell(0, 0, 10, 39, '<span style=\"font-weight: bold;text-align:center;\">' . 'Proficiency Testing Program for HIV-1 Viral Load using Dried Tube Specimen</span>', 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'eid') {\n $this->writeHTMLCell(0, 0, 10, 39, '<span style=\"font-weight: bold;text-align:center;\">' . 'Proficiency Testing Program for HIV-1 Early Infant Diagnosis Using Dried Blood Spots</span>', 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'tb') {\n // $this->writeHTMLCell(0, 0, 10, 39, '<span style=\"font-weight: bold;text-align:center;\">' . 'Proficiency Testing Program for Tuberculosis</span>', 0, 0, 0, true, 'J', true);\n }\n if ($this->schemeType != 'tb') {\n $finalized = (!empty($this->resultStatus) && $this->resultStatus == 'finalized') ? 'FINAL ' : '';\n $finalizeReport = '<span style=\"font-weight: normal;text-align:center;\">' . $finalized . ' INDIVIDUAL REPORT ' . $screening . '</span>';\n $this->writeHTMLCell(0, 0, 10, 45, $finalizeReport, 0, 0, 0, true, 'J', true);\n }\n } elseif ($this->schemeType == 'covid19') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>Proficiency Testing Report - SARS-CoV-2</span>';\n } elseif ($this->schemeType == 'generic-test') {\n $this->SetFont('helvetica', '', 10);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>Proficiency Testing Report - ' . $this->scheme_name . '</span>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n }\n } else {\n $this->SetFont('helvetica', '', 11);\n $html = '<span style=\"font-weight: bold;text-align:center;\"><span style=\"text-align:center;\">' . $this->header . '</span><br>Proficiency Testing Report - ' . $this->scheme_name . '</span>';\n if ($this->instituteAddressPosition == \"header\" && isset($instituteAddress) && $instituteAddress != \"\") {\n $html .= '<br/><span style=\"font-weight: normal;text-align:center;font-size:11;\">' . $instituteAddress . '</span>';\n }\n }\n\n if ($this->schemeType == 'vl' && $this->layout != 'zimbabwe') {\n if ($this->layout == 'myanmar') {\n $this->writeHTMLCell(0, 0, 10, 05, $html, 0, 0, 0, true, 'J', true);\n } else {\n $this->writeHTMLCell(0, 0, 27, 10, $html, 0, 0, 0, true, 'J', true);\n }\n $html = '<hr/>';\n $mt = 30;\n if ($this->layout == 'myanmar') {\n $mt = 35;\n }\n $this->writeHTMLCell(0, 0, 10, $mt, $html, 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'dts' && $this->layout == 'jamaica') {\n $this->writeHTMLCell(0, 0, 15, 5, $html, 0, 0, 0, true, 'J', true);\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 40, $html, 0, 0, 0, true, 'J', true);\n } elseif (in_array($this->schemeType, ['recency', 'dts', 'vl', 'eid']) && $this->layout == 'zimbabwe') {\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 50, $html, 0, 0, 0, true, 'J', true);\n } else {\n if ($this->schemeType == 'tb' && $this->layout != 'zimbabwe') {\n $this->writeHTMLCell(0, 0, 15, 10, $html, 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType != 'tb' && ($this->schemeType != 'dts' && $this->layout != 'myanmar')) {\n $this->writeHTMLCell(0, 0, 27, 20, $html, 0, 0, 0, true, 'J', true);\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 40, $html, 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'dts' && $this->layout == 'myanmar') {\n $this->writeHTMLCell(0, 0, 27, 5, $html, 0, 0, 0, true, 'J', true);\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 28, $html, 0, 0, 0, true, 'J', true);\n } elseif ($this->schemeType == 'dts' && $this->layout == 'default') {\n $this->writeHTMLCell(0, 0, 27, 8, $html, 0, 0, 0, true, 'J', true);\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 38, $html, 0, 0, 0, true, 'J', true);\n } else {\n $this->writeHTMLCell(0, 0, 27, 8, $html, 0, 0, 0, true, 'J', true);\n $html = '<hr/>';\n $this->writeHTMLCell(0, 0, 10, 50, $html, 0, 0, 0, true, 'J', true);\n }\n }\n //Put the watermark\n $this->SetFont('', 'B', 120);\n $this->SetTextColor(230, 228, 198);\n $this->RotatedText(25, 190, $this->watermark, 45);\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "function ineqtointerval($str, $var) {\n\tif ($str === 'DNE') {\n\t\treturn $str;\n\t}\n\t$str = strtolower($str);\n $var = strtolower($var);\n $str = preg_replace('/(\\d)\\s*,\\s*(?=\\d{3}\\b)/',\"$1\", $str);\n\tif (preg_match('/all\\s*real/', $str)) {\n\t\treturn '(-oo,oo)';\n }\n $outpieces = [];\n $orpts = preg_split('/\\s*or\\s*/', $str);\n foreach ($orpts as $str) {\n if (count($orpts)==1 && strpos($str, '!=') !== false) {\n // special handling for != \n $pieces = explode('!=', $str);\n if (count($pieces) != 2 || trim($pieces[0]) != $var) {\n return false;\n }\n return '(-oo,' . $pieces[1] . ')U(' . $pieces[1] . ',oo)';\n }\n $pieces = preg_split('/(<=?|>=?)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);\n $cnt = count($pieces);\n $pieces = array_map('trim', $pieces);\n if ($cnt != 3 && $cnt != 5) {\n return false; //invalid\n } else if ($cnt == 5 && ($pieces[1][0] != $pieces[3][0] || $pieces[2] != $var)) {\n return false; // mixes > with <\n }\n if ($cnt==3 && $pieces[0]==$var && $pieces[1][0]=='>') {\n $outpieces[] = ($pieces[1]=='>'?'(':'[') . $pieces[2] . ',oo)';\n } else if ($cnt==3 && $pieces[0]==$var && $pieces[1][0]=='<') {\n $outpieces[] = '(-oo,' . $pieces[2] . ($pieces[1]=='<'?')':']');\n } else if ($cnt==3 && $pieces[2]==$var && $pieces[1][0]=='>') {\n $outpieces[] = '(-oo,' . $pieces[0] . ($pieces[1]=='>'?')':']');\n } else if ($cnt==3 && $pieces[2]==$var && $pieces[1][0]=='<') {\n $outpieces[] = ($pieces[1]=='<'?'(':'[') . $pieces[0] . ',oo)';\n } else if ($cnt==5 && $pieces[1][0]=='<') {\n $outpieces[] = ($pieces[1]=='<'?'(':'[') . $pieces[0] . ',' .\n $pieces[4] . ($pieces[3]=='<'?')':']');\n } else if ($cnt==5 && $pieces[1][0]=='>') {\n $outpieces[] = ($pieces[3]=='>'?'(':'[') . $pieces[4] . ',' .\n $pieces[0] . ($pieces[1]=='>'?')':']');\n }\n }\n if (count($outpieces) > 0) {\n return implode('U', $outpieces);\n }\n\treturn false;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function relationsActionGet(Request $request): JsonResponse\n {\n $mapping = ['keyName' => 'name', 'keyDescription' => 'description'];\n\n $start = 0;\n $limit = 15;\n $orderKey = 'name';\n $order = 'ASC';\n $relationIds = $request->get('relationIds');\n\n if ($relationIds) {\n $relationIds = json_decode($relationIds, true);\n }\n\n if ($request->get('dir')) {\n $order = $request->get('dir');\n }\n\n $allParams = array_merge($request->request->all(), $request->query->all());\n $sortingSettings = \\Pimcore\\Bundle\\AdminBundle\\Helper\\QueryParams::extractSortingSettings($allParams);\n\n if ($sortingSettings['orderKey'] && $sortingSettings['order']) {\n $orderKey = $sortingSettings['orderKey'];\n $order = $sortingSettings['order'];\n }\n\n if ($request->query->getBoolean('overrideSort')) {\n $orderKey = 'id';\n $order = 'DESC';\n }\n\n if ($request->get('limit')) {\n $limit = (int) $request->get('limit');\n } elseif (is_array($relationIds)) {\n $limit = count($relationIds);\n }\n\n if ($request->get('start')) {\n $start = (int) $request->get('start');\n }\n\n $list = new Classificationstore\\KeyGroupRelation\\Listing();\n\n if ($limit > 0) {\n $list->setLimit($limit);\n }\n\n $list->setOffset($start);\n $list->setOrder($order);\n $list->setOrderKey($orderKey);\n $conditionParts = [];\n\n if ($request->get('filter')) {\n $db = Db::get();\n $filterString = $request->get('filter');\n $filters = json_decode($filterString);\n /** @var \\stdClass $f */\n foreach ($filters as $f) {\n if (!isset($f->value)) {\n continue;\n }\n\n $fieldname = $mapping[$f->field];\n $conditionParts[] = $db->quoteIdentifier($fieldname) . ' LIKE ' . $db->quote('%' . $f->value . '%');\n }\n }\n\n if (!$request->get('relationIds')) {\n $groupId = $request->get('groupId');\n $conditionParts[] = ' groupId = ' . $list->quote($groupId);\n }\n\n if ($relationIds) {\n $relationParts = [];\n\n foreach ($relationIds as $relationId) {\n $keyId = $relationId['keyId'];\n $groupId = $relationId['groupId'];\n $relationParts[] = '(keyId = ' . $list->quote($keyId) . ' AND groupId = ' . $list->quote($groupId) . ')';\n }\n\n $conditionParts[] = '(' . implode(' OR ', $relationParts) . ')';\n }\n\n $condition = implode(' AND ', $conditionParts);\n\n $list->setCondition($condition);\n\n $listItems = $list->load();\n\n $rootElement = [];\n\n $data = [];\n foreach ($listItems as $config) {\n $type = $config->getType();\n $definition = json_decode($config->getDefinition(), true);\n $definition = \\Pimcore\\Model\\DataObject\\Classificationstore\\Service::getFieldDefinitionFromJson($definition, $type);\n DataObject\\Service::enrichLayoutDefinition($definition);\n\n $item = [\n 'keyId' => $config->getKeyId(),\n 'groupId' => $config->getGroupId(),\n 'keyName' => $config->getName(),\n 'keyDescription' => $config->getDescription(),\n 'id' => $config->getGroupId() . '-' . $config->getKeyId(),\n 'sorter' => $config->getSorter(),\n 'layout' => $definition,\n 'mandatory' => $config->isMandatory(),\n ];\n\n $data[] = $item;\n }\n $rootElement['data'] = $data;\n $rootElement['success'] = true;\n $rootElement['total'] = $list->getTotalCount();\n\n return $this->adminJson($rootElement);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "private function _writeSheetProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null)\n\t{\n\t\t// sheetProtection\n\t\t$objWriter->startElement('sheetProtection');\n\n\t\tif ($pSheet->getProtection()->getPassword() != '') {\n\t\t\t$objWriter->writeAttribute('password',\t\t\t\t$pSheet->getProtection()->getPassword());\n\t\t}\n\n\t\t$objWriter->writeAttribute('sheet',\t\t\t\t($pSheet->getProtection()->getSheet()\t\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('objects',\t\t\t\t($pSheet->getProtection()->getObjects()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('scenarios',\t\t\t($pSheet->getProtection()->getScenarios()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('formatCells',\t\t\t($pSheet->getProtection()->getFormatCells()\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('formatColumns',\t\t($pSheet->getProtection()->getFormatColumns()\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('formatRows',\t\t\t($pSheet->getProtection()->getFormatRows()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('insertColumns',\t\t($pSheet->getProtection()->getInsertColumns()\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('insertRows',\t\t\t($pSheet->getProtection()->getInsertRows()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('insertHyperlinks',\t\t($pSheet->getProtection()->getInsertHyperlinks()\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('deleteColumns',\t\t($pSheet->getProtection()->getDeleteColumns()\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('deleteRows',\t\t\t($pSheet->getProtection()->getDeleteRows()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('selectLockedCells',\t($pSheet->getProtection()->getSelectLockedCells()\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('sort',\t\t\t\t\t($pSheet->getProtection()->getSort()\t\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('autoFilter',\t\t\t($pSheet->getProtection()->getAutoFilter()\t\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('pivotTables',\t\t\t($pSheet->getProtection()->getPivotTables()\t\t? 'true' : 'false'));\n\t\t$objWriter->writeAttribute('selectUnlockedCells',\t($pSheet->getProtection()->getSelectUnlockedCells()\t? 'true' : 'false'));\n\t\t$objWriter->endElement();\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function find_aid_by_ancestor_walkback(int $sourceaid, int $aidsourcecid,\n int $copiedfrom, int $destcid\n ) {\n $stm = $this->dbh->prepare(\"SELECT ancestors FROM imas_courses WHERE id=?\");\n $stm->execute(array($destcid));\n $ancestors = explode(',', $stm->fetchColumn(0));\n $ciddepth = array_search($aidsourcecid, $ancestors); //so if we're looking for 23, \"20,24,23,26\" would give 2 here.\n if ($ciddepth !== false) {\n // first approach: look for aidsourcecid:sourcecid in ancestry of current course\n // then we'll walk back through the ancestors and make sure the course\n // history path matches.\n // This approach will work as long as there's a newer-format ancestry record\n $anregex = MYSQL_LEFT_WRDBND . $aidsourcecid . ':' . $sourceaid . MYSQL_RIGHT_WRDBND;\n $stm = $this->dbh->prepare(\"SELECT id,ancestors FROM imas_assessments WHERE ancestors REGEXP :ancestors AND courseid=:destcid\");\n $stm->execute(array(':ancestors' => $anregex, ':destcid' => $destcid));\n while ($res = $stm->fetch(PDO::FETCH_ASSOC)) {\n $aidanc = explode(',', $res['ancestors']);\n $isok = true;\n for ($i = 0; $i <= $ciddepth; $i++) {\n if (!isset($aidanc[$i])) {\n $isok = false;\n break;\n }\n $ancparts = explode(':', $aidanc[$i]);\n if ($ancparts[0] != $ancestors[$i]) {\n // course sequence doesn't match\n $isok = false;\n break; // not the same ancestry path\n }\n if ($i == $ciddepth) {\n // on last one - match sure assessment matches\n if ($sourceaid != $ancparts[1]) {\n $isok = false;\n break;\n }\n }\n }\n if ($isok) { // found it!\n return $res['id'];\n }\n }\n\n // last approach didn't work, so maybe it was an older-format ancestry.\n // We'll try a heavier-duty walkback that calls the database for each walkback\n array_unshift($ancestors, $destcid); //add current course to front\n $foundsubaid = true;\n $aidtolookfor = $sourceaid;\n for ($i = $ciddepth; $i >= 0; $i--) { //starts one course back from aidsourcecid because of the unshift\n $stm = $this->dbh->prepare(\"SELECT id FROM imas_assessments WHERE ancestors REGEXP :ancestors AND courseid=:cid\");\n $stm->execute(array(':ancestors' => '^([0-9]+:)?' . $aidtolookfor . MYSQL_RIGHT_WRDBND, ':cid' => $ancestors[$i]));\n if ($stm->rowCount() > 0) {\n $aidtolookfor = $stm->fetchColumn(0);\n } else {\n $foundsubaid = false;\n break;\n }\n }\n if ($foundsubaid) { // tracked it back all the way\n return $aidtolookfor;\n }\n\n // ok, still didn't work, so assessment wasn't copied through the whole\n // history. So let's see if we have a copy in our course with the assessment\n // anywhere in the ancestry.\n $anregex = MYSQL_LEFT_WRDBND . $sourceaid . MYSQL_RIGHT_WRDBND;\n $stm = $this->dbh->prepare(\"SELECT id,name,ancestors FROM imas_assessments WHERE ancestors REGEXP :ancestors AND courseid=:destcid\");\n $stm->execute(array(':ancestors' => $anregex, ':destcid' => $destcid));\n $res = $stm->fetchAll(PDO::FETCH_ASSOC);\n if (count($res) == 1) { //only one result - we found it\n return $res[0]['id'];\n }\n $stm = $this->dbh->prepare(\"SELECT name FROM imas_assessments WHERE id=?\");\n $stm->execute(array($sourceaid));\n $aidsourcename = $stm->fetchColumn(0);\n if (count($res) > 1) { //multiple results - look for the identical name\n foreach ($res as $k => $row) {\n $res[$k]['loc'] = strpos($row['ancestors'], (string) $aidtolookfor);\n if ($row['name'] == $aidsourcename) {\n return $row['id'];\n }\n }\n //no name match. pick the one with the assessment closest to the start\n usort($res, function ($a, $b) {return $a['loc'] - $b['loc'];});\n return $res[0]['id'];\n }\n\n // still haven't found it, so nothing in our current course has the\n // desired assessment as an ancestor. Try finding something just with\n // the right name maybe?\n $stm = $this->dbh->prepare(\"SELECT id FROM imas_assessments WHERE name=:name AND courseid=:courseid\");\n $stm->execute(array(':name' => $aidsourcename, ':courseid' => $destcid));\n if ($stm->rowCount() > 0) {\n return $stm->fetchColumn(0);\n }\n }\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function DOBandEncounter($pc_eid)\n{\n global $event_date,$info_msg;\n // Save new DOB if it's there.\n $patient_dob = trim($_POST['form_dob'] ?? '');\n $tmph = (int)$_POST['form_hour'];\n $tmpm = (int)$_POST['form_minute'];\n if (!empty($_POST['form_ampm']) && ($_POST['form_ampm'] == '2' && $tmph < 12)) {\n $tmph += 12;\n }\n\n $appttime = \"$tmph:$tmpm:00\";\n\n if ($patient_dob && $_POST['form_pid']) {\n sqlStatement(\"UPDATE patient_data SET DOB = ? WHERE \" .\n \"pid = ?\", array($patient_dob,$_POST['form_pid']));\n }\n\n // Manage tracker status.\n // And auto-create a new encounter if appropriate.\n if (!empty($_POST['form_pid'])) {\n $is_tracker = is_tracker_encounter_exist($event_date, $appttime, $_POST['form_pid'], $_GET['eid']);\n $is_checkin = is_checkin($_POST['form_apptstatus']);\n if (\n (int)$GLOBALS['auto_create_new_encounters']\n && $event_date == date('Y-m-d')\n && $is_checkin == '1'\n && !$is_tracker\n ) {\n $encounter = todaysEncounterCheck($_POST['form_pid'], $event_date, $_POST['form_comments'], $_POST['facility'], $_POST['billing_facility'], $_POST['form_provider'], $_POST['form_category'], false);\n if ($encounter) {\n $info_msg .= xl(\"New encounter created with id\");\n $info_msg .= \" $encounter\";\n }\n\n # Capture the appt status and room number for patient tracker. This will map the encounter to it also.\n if (isset($GLOBALS['temporary-eid-for-manage-tracker']) || !empty($_GET['eid'])) {\n // Note that the temporary-eid-for-manage-tracker is used to capture the eid for new appointments and when separate a recurring\n // appointment. It is set in the InsertEvent() function. Note that in the case of spearating a recurrent appointment, the get eid\n // parameter is actually erroneous(is eid of the recurrent appt and not the new separated appt), so need to use the\n // temporary-eid-for-manage-tracker global instead.\n $temp_eid = (isset($GLOBALS['temporary-eid-for-manage-tracker'])) ? $GLOBALS['temporary-eid-for-manage-tracker'] : $_GET['eid'];\n manage_tracker_status($event_date, $appttime, $temp_eid, $_POST['form_pid'], $_SESSION[\"authUser\"], $_POST['form_apptstatus'], $_POST['form_room'], $encounter);\n }\n } else {\n # Capture the appt status and room number for patient tracker.\n if (!empty($_GET['eid'])) {\n manage_tracker_status($event_date, $appttime, $_GET['eid'], $_POST['form_pid'], $_SESSION[\"authUser\"], $_POST['form_apptstatus'], $_POST['form_room'], $is_tracker);\n }\n }\n }\n\n // auto create encounter for therapy group\n if (!empty($_POST['form_gid'])) {\n // status Took Place is the check in of therapy group\n if ($GLOBALS['auto_create_new_encounters'] && $event_date == date('Y-m-d') && $_POST['form_apptstatus'] == '=') {\n $encounter = todaysTherapyGroupEncounterCheck($_POST['form_gid'], $event_date, $_POST['form_comments'], $_POST['facility'], $_POST['billing_facility'], $_POST['form_provider'], $_POST['form_category'], false, $pc_eid);\n if ($encounter) {\n $info_msg .= xl(\"New group encounter created with id\");\n $info_msg .= \" $encounter\";\n }\n }\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function parseConfigs(\\DOMElement $node, string $path): array\n {\n $defaults = [];\n $requirements = [];\n $options = [];\n $condition = null;\n $prefixes = [];\n $paths = [];\n $hosts = [];\n\n /** @var \\DOMElement $n */\n foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {\n if ($node !== $n->parentNode) {\n continue;\n }\n\n switch ($n->localName) {\n case 'path':\n $paths[$n->getAttribute('locale')] = trim($n->textContent);\n break;\n case 'host':\n $hosts[$n->getAttribute('locale')] = trim($n->textContent);\n break;\n case 'prefix':\n $prefixes[$n->getAttribute('locale')] = trim($n->textContent);\n break;\n case 'default':\n if ($this->isElementValueNull($n)) {\n $defaults[$n->getAttribute('key')] = null;\n } else {\n $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);\n }\n\n break;\n case 'requirement':\n $requirements[$n->getAttribute('key')] = trim($n->textContent);\n break;\n case 'option':\n $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));\n break;\n case 'condition':\n $condition = trim($n->textContent);\n break;\n default:\n throw new \\InvalidArgumentException(sprintf('Unknown tag \"%s\" used in file \"%s\". Expected \"default\", \"requirement\", \"option\" or \"condition\".', $n->localName, $path));\n }\n }\n\n if ($controller = $node->getAttribute('controller')) {\n if (isset($defaults['_controller'])) {\n $name = $node->hasAttribute('id') ? sprintf('\"%s\".', $node->getAttribute('id')) : sprintf('the \"%s\" tag.', $node->tagName);\n\n throw new \\InvalidArgumentException(sprintf('The routing file \"%s\" must not specify both the \"controller\" attribute and the defaults key \"_controller\" for ', $path).$name);\n }\n\n $defaults['_controller'] = $controller;\n }\n if ($node->hasAttribute('locale')) {\n $defaults['_locale'] = $node->getAttribute('locale');\n }\n if ($node->hasAttribute('format')) {\n $defaults['_format'] = $node->getAttribute('format');\n }\n if ($node->hasAttribute('utf8')) {\n $options['utf8'] = XmlUtils::phpize($node->getAttribute('utf8'));\n }\n if ($stateless = $node->getAttribute('stateless')) {\n if (isset($defaults['_stateless'])) {\n $name = $node->hasAttribute('id') ? sprintf('\"%s\".', $node->getAttribute('id')) : sprintf('the \"%s\" tag.', $node->tagName);\n\n throw new \\InvalidArgumentException(sprintf('The routing file \"%s\" must not specify both the \"stateless\" attribute and the defaults key \"_stateless\" for ', $path).$name);\n }\n\n $defaults['_stateless'] = XmlUtils::phpize($stateless);\n }\n\n if (!$hosts) {\n $hosts = $node->hasAttribute('host') ? $node->getAttribute('host') : null;\n }\n\n return [$defaults, $requirements, $options, $condition, $paths, $prefixes, $hosts];\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function fetchAudit(string $from, string $to, $pid = null, ?string $service = null, ?string $ticket = null, ?string $transactionId = null, ?string $actionName = null): array\n {\n $sqlBind = [];\n $sql = \"SELECT * FROM `payment_processing_audit` WHERE `date` > ? AND `date` < ?\";\n $sqlBind[] = $from;\n $sqlBind[] = $to;\n\n if (!empty($pid)) {\n $sql .= \" AND `pid` = ?\";\n $sqlBind[] = $pid;\n }\n\n if (!empty($service)) {\n $sql .= \" AND `service` = ?\";\n $sqlBind[] = $service;\n }\n\n if (!empty($ticket)) {\n $sql .= \" AND `ticket` = ?\";\n $sqlBind[] = $ticket;\n }\n\n if (!empty($transactionId)) {\n $sql .= \" AND `transaction_id` = ?\";\n $sqlBind[] = $transactionId;\n }\n\n if (!empty($actionName)) {\n $sql .= \" AND `action_name` = ?\";\n $sqlBind[] = $actionName;\n }\n\n $sql .= \" ORDER BY `date` DESC\";\n\n // Collect pertinent information from auditdata\n $cryptoGen = new CryptoGen();\n $return = [];\n $res = sqlStatement($sql, $sqlBind);\n while ($row = sqlFetchArray($res)) {\n $row['uuid'] = UuidRegistry::uuidToString($row['uuid']);\n\n // Set up the action label\n if (!empty($row['action_name'])) {\n if ($row['action_name'] == 'Sale') {\n $row['action_name_label'] = xl(\"Sale\");\n } elseif ($row['action_name'] == 'void') {\n $row['action_name_label'] = xl(\"Void\");\n } elseif ($row['action_name'] == 'credit') {\n $row['action_name_label'] = xl(\"Credit\");\n } else {\n $row['action_name_label'] = xl($row['action_name']);\n }\n }\n\n // decrypt the audit data\n $auditData = $cryptoGen->decryptStandard($row['audit_data']);\n $auditData = json_decode($auditData, true);\n\n // Collect the error message if not succcess\n if ($row['success'] != 1) {\n if (!empty($auditData['get']['cancel']) && $auditData['get']['cancel'] == 'cancel') {\n $row['error_message'] = xl(\"Cancelled\");\n } elseif (!empty($row['action_name']) && ($row['action_name'] == 'Sale')) {\n $row['error_message'] = $auditData['post']['status_name'] . \" - \" . $auditData['post']['description'];\n } elseif (!empty($row['action_name']) && ($row['action_name'] == 'void' || $row['action_name'] == 'credit')) {\n if (!empty($auditData['post']['status']) && (($auditData['post']['status'] == 'baddata') || ($auditData['post']['status'] == 'error'))) {\n $row['error_message'] = xl(\"Aborted since unable to submit transaction\") . \": \" . $auditData['post']['status'] . \" \" . $auditData['post']['error'] . \" \" . $auditData['post']['offenders'];\n } elseif (isset($auditData['check_querystring_hash']) && $auditData['check_querystring_hash'] === false) {\n $row['error_message'] = xl(\"querystring hash was invalid\");\n } elseif (!empty($auditData['token_request_error'])) {\n $row['error_message'] = xl(\"Aborted since unable to obtain token\") . \": \" . $auditData['token_request_error'];\n } elseif (!empty($auditData['error_custom'])) {\n $row['error_message'] = $auditData['error_custom'];\n } elseif ($auditData['complete_transaction']['status'] != 'accepted') {\n $completeRevertToString = \"\";\n foreach ($auditData['complete_transaction'] as $key => $value) {\n if (!empty($key) || !empty($value)) {\n $completeRevertToString .= $key . \":\" . $value . \"; \";\n }\n }\n $row['error_message'] = xl(\"Unable to complete transaction\") . \": \" . $completeRevertToString;\n }\n }\n }\n\n // Collect the front label\n $row['front'] = $auditData['get']['front'] ?? null;\n if ($row['front'] == 'patient') {\n $row['front_label'] = xl(\"Patient Portal\");\n } elseif ($row['front'] == 'clinic-phone') {\n $row['front_label'] = xl(\"Front Office by Phone\");\n } elseif ($row['front'] == 'clinic-retail') {\n $row['front_label'] = xl(\"Front Office in Person\");\n } elseif (!empty($row['front'])) {\n $row['front_label'] = xl($row['front']);\n }\n\n // See if offer void versus credit\n if (($row['reverted'] != 1) && ($row['action_name'] == \"Sale\") && ($auditData['post']['status_name'] == 'approved') && ($row['success'] == 1)) {\n if ((new \\DateTime($row['date']))->format('Y-m-d') == (new \\DateTime('NOW'))->format('Y-m-d')) {\n // still on same day as charge, so offer void and credit\n // TODO - appears void is not allowed (d/w Sphere) with current testing custids and also ask Sphere when should be offering void versus credit\n $row['offer_void'] = true;\n $row['offer_credit'] = true;\n } else {\n // no longer on same day as charge, so offer only credit\n $row['offer_credit'] = true;\n }\n }\n\n $return[] = $row;\n }\n\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function profielBewerken(Profiel $profiel, $alleenFormulier = false)\n\t{\n\t\tif (!$profiel->magBewerken()) {\n\t\t\tthrow $this->createAccessDeniedException();\n\t\t}\n\t\t$form = new ProfielForm($profiel, $alleenFormulier);\n\t\tif ($form->validate()) {\n\t\t\t$diff = $form->diff();\n\t\t\tif (empty($diff)) {\n\t\t\t\t$this->addFlash(FlashType::INFO, 'Geen wijzigingen');\n\t\t\t} else {\n\t\t\t\t$nieuw =\n\t\t\t\t\t$profiel->uid === null ||\n\t\t\t\t\t$this->profielRepository->find($profiel->uid) == null;\n\t\t\t\t$changeEntry = ProfielRepository::changelog($diff, $this->getUid());\n\t\t\t\tforeach ($diff as $change) {\n\t\t\t\t\tif ($change->property === 'status') {\n\t\t\t\t\t\tarray_push(\n\t\t\t\t\t\t\t$changeEntry->entries,\n\t\t\t\t\t\t\t...$this->lidStatusService->wijzig_lidstatus(\n\t\t\t\t\t\t\t\t$profiel,\n\t\t\t\t\t\t\t\t$change->old_value\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$profiel->changelog[] = $changeEntry;\n\t\t\t\tif ($nieuw) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t/** @var Connection $conn */\n\t\t\t\t\t\t$conn = $this->getDoctrine()->getConnection();\n\t\t\t\t\t\t$conn->setAutoCommit(false);\n\t\t\t\t\t\t$conn->connect();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t$this->profielRepository->create($profiel);\n\n\t\t\t\t\t\t\tif (filter_input(INPUT_POST, 'toestemming_geven') === 'true') {\n\t\t\t\t\t\t\t\t// Sla toesteming op.\n\t\t\t\t\t\t\t\t$toestemmingForm = new ToestemmingModalForm(\n\t\t\t\t\t\t\t\t\t$this->lidToestemmingRepository,\n\t\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif ($toestemmingForm->validate()) {\n\t\t\t\t\t\t\t\t\t$this->lidToestemmingRepository->saveForLid($profiel->uid);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tthrow new CsrException('Opslaan van toestemming mislukt');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$conn->commit();\n\t\t\t\t\t\t} catch (Exception $e) {\n\t\t\t\t\t\t\t$this->addFlash(FlashType::ERROR, $e->getMessage());\n\t\t\t\t\t\t\t$conn->rollBack();\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t$conn->setAutoCommit(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CsrException $ex) {\n\t\t\t\t\t\t$this->addFlash(FlashType::ERROR, $ex->getMessage());\n\t\t\t\t\t}\n\n\t\t\t\t\t$this->addFlash(\n\t\t\t\t\t\tFlashType::SUCCESS,\n\t\t\t\t\t\t'Profiel succesvol opgeslagen met lidnummer: ' . $profiel->uid\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t$this->profielRepository->update($profiel);\n\t\t\t\t\t$this->addFlash(\n\t\t\t\t\t\tFlashType::SUCCESS,\n\t\t\t\t\t\tcount($diff) . ' wijziging(en) succesvol opgeslagen'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn $this->redirectToRoute('csrdelft_profiel_profiel', [\n\t\t\t\t'uid' => $profiel->uid,\n\t\t\t]);\n\t\t}\n\t\tif ($alleenFormulier) {\n\t\t\treturn $this->render('plain.html.twig', [\n\t\t\t\t'titel' => 'Noviet toevoegen',\n\t\t\t\t'content' => $form,\n\t\t\t]);\n\t\t}\n\t\treturn $this->render('default.html.twig', ['content' => $form]);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "protected function prepareListFields()\n {\n $listFields = $this->getListFields();\n\n $result = [];\n foreach ($listFields as $field => &$data) {\n if (is_numeric($field) && is_string($data)) {\n $field = $data;\n $data = [];\n }\n\n $data['original_field_name'] = $field;\n\n if (!$data['type'] && $field != $this->model->id_field) {\n $data['type'] = 'text';\n }\n\n if (!array_key_exists('title', $data) || $data['title'] === null) {\n $data['title'] = ucwords(implode(' ', preg_split('/_+/', $field, -1, PREG_SPLIT_NO_EMPTY)));\n }\n\n $this->checkSubProp($field, $data);\n\n if ($data['type'] == 'link' || $data['is_link']) {\n $data['is_link'] = true;\n if (!$data['template']) {\n $data['template'] = '/admin/' . $this->alias . '/edit/%' . $this->model->id_field . '%';\n }\n }\n\n if ($data['type'] == 'image') {\n if (!$data['max_width']) {\n $data['max_width'] = 40;\n }\n\n if (!$data['max_height']) {\n $data['max_height'] = 30;\n }\n\n if (!$data['dir_path']) {\n $data['dir_path'] = '/images/';\n }\n\n if (!array_key_exists('orderable', $data)) {\n $data['orderable'] = false;\n }\n\n if (!array_key_exists('searching', $data)) {\n $data['searching'] = false;\n }\n }\n\n if ($data['extra']) {\n $data['orderable'] = false;\n $data['searching'] = false;\n }\n\n if (!array_key_exists('orderable', $data)) {\n $data['orderable'] = true;\n }\n\n if (!array_key_exists('searching', $data)) {\n $data['searching'] = true;\n }\n\n $field = $this->recursiveCreateRelativeFieldName($field, $data);\n\n $result[$field] = $data;\n }\n $listFields = $result;\n unset($data);\n if (array_key_exists($this->model->id_field, $listFields)) {\n if (!array_key_exists('type', $listFields[$this->model->id_field])) {\n $listFields[$this->model->id_field]['type'] = 'link';\n $listFields[$this->model->id_field]['template'] = '/admin/' . $this->alias . '/edit/%' . $this->model->id_field . '%';\n }\n $listFields[$this->model->id_field]['width'] = '60';\n }\n\n return $listFields;\n }", "smellKey": "S3776", "smellId": null, "repo": "antonisLem_hackazon", "language": "php"} {"function": "private function getMetaBalances(): void\n {\n $this->balances = Balance::getAccountBalances($this->collection, today());\n $balances = $this->balances;\n $default = $this->default;\n\n // get start and end, so the balance difference can be generated.\n $start = null;\n $end = null;\n if (null !== $this->start) {\n $start = Balance::getAccountBalances($this->collection, $this->start);\n }\n if (null !== $this->end) {\n $end = Balance::getAccountBalances($this->collection, $this->end);\n }\n\n $this->collection->transform(function (Account $account) use ($balances, $default, $start, $end) {\n $converter = new ExchangeRateConverter();\n $native = [\n 'currency_id' => $this->default->id,\n 'currency_name' => $this->default->name,\n 'currency_code' => $this->default->code,\n 'currency_symbol' => $this->default->symbol,\n 'currency_decimal_places' => $this->default->decimal_places,\n 'balance' => '0',\n 'period_start_balance' => null,\n 'period_end_balance' => null,\n 'balance_difference' => null,\n ];\n if (array_key_exists($account->id, $balances)) {\n $set = [];\n foreach ($balances[$account->id] as $currencyId => $entry) {\n $left = $start[$account->id][$currencyId]['balance'] ?? null;\n $right = $end[$account->id][$currencyId]['balance'] ?? null;\n $diff = null;\n if (null !== $left && null !== $right) {\n $diff = bcsub($right, $left);\n }\n\n $item = [\n 'currency_id' => $entry['currency']->id,\n 'currency_name' => $entry['currency']->name,\n 'currency_code' => $entry['currency']->code,\n 'currency_symbol' => $entry['currency']->symbol,\n 'currency_decimal_places' => $entry['currency']->decimal_places,\n 'balance' => $entry['balance'],\n 'period_start_balance' => $left,\n 'period_end_balance' => $right,\n 'balance_difference' => $diff,\n ];\n $set[] = $item;\n if ($converter->enabled()) {\n $native['balance'] = bcadd($native['balance'], $converter->convert($entry['currency'], $default, today(), $entry['balance']));\n if (null !== $diff) {\n $native['period_start_balance'] = $converter->convert($entry['currency'], $default, today(), $item['period_start_balance']);\n $native['period_end_balance'] = $converter->convert($entry['currency'], $default, today(), $item['period_end_balance']);\n $native['balance_difference'] = bcsub($native['period_end_balance'], $native['period_start_balance']);\n }\n }\n }\n $account->balance = $set;\n if ($converter->enabled()) {\n $account->native_balance = $native;\n }\n }\n\n return $account;\n });\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function simplexcreatelatexinequalities() {\n\t$simplexestring = array(); // return value\n\t// arguments list --------------------------------------------------\n\t// 0 = type (max,min)\n\t// 1 = objectivevariable\n\t// 2 = objective\n\t// 3 = constraints\n\t// 4 = header column names, default is not to show\n\t// 5 = showfractions\n\t// 6 = includeinequalities\n\n\t// process arguments -----------------------------------------------\n\t$args = func_get_args();\n\n\tif (count($args)<4) {\n\t\techo \"simplexcreatelatexinequalities requires at least 4 aurguments (type, objectivevariable, objective, and constraints).<br/>\\r\\n\";\n\t\treturn $simplexestring;\n\t}\n\n\t// type\n\tif(is_null($args[0])) {\n\t\techo \"In simplexcreatelatexinequalities - Supplied Type was null which is not valid. Valid values are <b>'min'</b> or <b>'max'</b>.<br/>\\r\\n\";\n\t\treturn $simplexestring;\n\t}\n\telse {\n\t\t$type = verifytype(\"simplexcreatelatexinequalities\",$args[0],null);\n\t\tif(is_null($type)) return $simplexestring;\n\t}\n\n // objectivevariable\n\tif(is_null($args[1])) {\n\t\t$objectivevariable = \"\";\n\t}\n\telse {\n\t\t$objectivevariable = $args[1];\n\t}\n\n\t// objective\n\tif(is_null($args[2])) {\n\t\techo \"In simplexcreatelatexinequalities - You must supply an objective function.<br/>\\r\\n\";\n\t\treturn $simplexestring;\n\t}\n\telse {\n\t\t$objective = $args[2];\n\t\tif (!is_array($objective)) { $objective = explode(',',$objective); }\n\t}\n\n\t//constraints\n\tif(is_null($args[3])) {\n\t\techo \"In simplexcreatelatexinequalities -You must supply constraint information.<br/>\\r\\n\";\n\t\treturn $simplexestring;\n\t}\n\telse {\n\t\t$constraints =verifyconstraints($type,$args[3]);\n\t}\n\n\t// OPTIONAL\n\t//header\n\n\tif((count($args)>4)&&(!is_null($args[4]))) {\n\t\t$headers = $args[4];\n\t\tif (!is_array($headers)) { $headers = explode(',',$headers); }\n\t}\n\telse {\n\t\t$headers=array();\n\t\tfor($j=0,$size = count($objective);$j<$size;$j++) {\n\t\t\t$count = $j+1;\n\t\t\tif($type==\"max\")\n\t\t\t{\n $headers[$j] = \"x_$count\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n $headers[$j] = \"y_$count\";\n\t\t\t}\n\t\t}\n\t}\n\n\t// showfractions\n\tif((count($args)>5)&&(!is_null($args[5]))) {\n\t\t$showfractions = verifyshowfraction(\"simplexcreatelatexinequalities\",$args[6],1);\n\t}\n\telse { $showfractions=1; }\n\n\t//includeinequalities in the output string flag\n\tif((count($args)>6)&&(!is_null($args[6]))) {\n\t\t$includeinequalities = $args[7];\n\t\tif(($includeinequalities!=0)&&($includeinequalities!=1)) {\n\t\t\techo \"In simplexcreatelatexinequalities the supplied inequalities flag value ($includeinequalities) is invalid. Valid values are 0 or 1.<br/>\\r\\n\";\n\t\t\t$includeinequalities=1;\n\t\t}\n\t}\n\telse {$includeinequalities = 1; }\n\n\t$tick = \"$\";\n\n\t// Done processing arguments ---------------------------------------\n\t$simplexestring = array();\n\tif($objectivevariable==\"\") {\n\t\t$simplexestring[0] = $tick;\n\t}\n\telse {\n\t\tif($type==\"max\") {\n $simplexestring[0] = \"Maximize \";\n\t\t}\n\t\telse {\n $simplexestring[0] = \"Minimize \";\n\t\t}\n\t\t$simplexestring[0] .= $tick.$objectivevariable.\" = \\\\displaystyle\";\n\t}\n\n\t// objective\n\t$isfirst = true;\n\tfor($j=0,$sizeobjective = count($objective);$j<$sizeobjective;$j++) {\n\t\tif($objective[$j]==0) {\n\t\t\t// do nothing\n\t\t}\n\t\telse {\n\n\t\t\t// do I need to add a + sign\n\t\t\tif($isfirst) {\n\t\t\t\t$isfirst = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif($objective[$j]>0) { $simplexestring[0] .= \"+\"; }\n\t\t\t}\n\n\t\t\t// take care of +1,-1 case\n\t\t\tif($objective[$j]==-1) {\n\t\t\t\t$simplexestring[0] .= \"-\";\n\t\t\t}\n\t\t\telseif ($objective[$j]==1) {\n\t\t\t\t// do nothing\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// add the number as a fraction display, or decimal value\n\t\t\t\t$frac = createsimplexelement($objective[$j]);\n\n\t\t\t\tif($showfractions==1) {\n\t\t\t\t\tif($frac[1]!=1) {\n $simplexestring[0] .= \"\\\\frac{\".$frac[0].\"}{\".$frac[1].\"}\";\n } else {\n $simplexestring[0] .= $frac[0];\n }\n\t\t\t\t}\n\t\t\t\telse {\n //$simplexestring[0] .= fractiontodecimal($frac);\n\t\t\t\t\t$simplexestring[0] .= $frac[0]/$frac[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t$simplexestring[0] .= $headers[$j];\n\t\t}\n\t}\n\t$simplexestring[0] .= $tick;\n if($objectivevariable!=\"\") {\n\t\t$simplexestring[0] .= \" subject to\";\n\t}\n\n\t// now create the inequalities from the constraints\n\tfor($r=0,$sizeconstraints = count($constraints);$r<$sizeconstraints;$r++) {\n\t\t// remember row 0 is the Maximize or minimize line\n\t\t$row = $r+1;\n\t\t$coeff = $constraints[$r][0];\n\t\t$isfirst = true;\n\t\t$simplexestring[$row] = $tick;\n\t\tfor($j=0,$sizeobjective = count($objective);$j<$sizeobjective;$j++) {\n\t\t\tif($coeff[$j]==0) {\n\t\t\t\t// do nothing\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// do I need to add a + sign\n\t\t\t\tif($isfirst) {\n\t\t\t\t\t$isfirst = false;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif($coeff[$j]>0) { $simplexestring[$row] .= \"+\"; }\n\t\t\t\t}\n\t\t\t\t// take care of +1,-1 case\n\t\t\t\tif($coeff[$j]==-1) {\n\t\t\t\t\t$simplexestring[$row] .= \"-\";\n\t\t\t\t}\n\t\t\t\telseif($coeff[$j]==1) {\n // do nothing\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// add the number as a fraction display, or decimal value\n\t\t\t\t\t$frac = createsimplexelement($coeff[$j]);\n\t\t\t\t\tif($showfractions==1) {\n\t\t\t\t\t\tif($frac[1]!=1) {\n $simplexestring[$row] .= \"\\\\frac{\".$frac[0].\"}{\".$frac[1].\"}\";\n } else {\n $simplexestring[$row] .= $frac[0];\n }\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t$simplexestring[$row] .= $frac[0]/$frac[1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$simplexestring[$row] .= $headers[$j];\n\t\t\t}\n\t\t}\n\t\t// does the user want the inequality symbol included in the output?\n\t\tif($includeinequalities==1) {$simplexestring[$row] .= $constraints[$r][1].\" \".$constraints[$r][2]; }\n\t\t$simplexestring[$row] .= $tick;\n\t}\n\n\treturn $simplexestring;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($filename)\n {\n if (!defined('IMAGETYPE_WEBP')) {\n define('IMAGETYPE_WEBP', 18);\n }\n\n if (!defined('IMAGETYPE_BMP')) {\n define('IMAGETYPE_BMP', 6);\n }\n\n if ($filename === null || empty($filename) || (!str_starts_with($filename, 'data:') && !is_file($filename))) {\n throw new SystemException('File does not exist');\n }\n\n $finfo = finfo_open(FILEINFO_MIME_TYPE);\n $checkWebp = false;\n if (!str_contains(finfo_file($finfo, $filename), 'image')) {\n if (version_compare(PHP_VERSION, '7.0.0', '<=') && str_contains(file_get_contents($filename), 'WEBPVP8')) {\n $checkWebp = true;\n $this->source_type = IMAGETYPE_WEBP;\n } else {\n throw new SystemException('Unsupported file type');\n }\n } elseif (str_contains(finfo_file($finfo, $filename), 'image/webp')) {\n $checkWebp = true;\n $this->source_type = IMAGETYPE_WEBP;\n }\n\n if (!$image_info = getimagesize($filename, $this->source_info)) {\n $image_info = getimagesize($filename);\n }\n\n if (!$checkWebp) {\n if (!$image_info) {\n if (str_contains(finfo_file($finfo, $filename), 'image')) {\n throw new SystemException('Unsupported image type');\n }\n\n throw new SystemException('Could not read file');\n }\n\n $this->original_w = $image_info[0];\n $this->original_h = $image_info[1];\n $this->source_type = $image_info[2];\n }\n\n switch ($this->source_type) {\n case IMAGETYPE_GIF:\n $this->source_image = imagecreatefromgif($filename);\n break;\n\n case IMAGETYPE_JPEG:\n $this->source_image = $this->imageCreateJpegfromExif($filename);\n\n // set new width and height for image, maybe it has changed\n $this->original_w = imagesx($this->source_image);\n $this->original_h = imagesy($this->source_image);\n\n break;\n\n case IMAGETYPE_PNG:\n $this->source_image = imagecreatefrompng($filename);\n break;\n\n case IMAGETYPE_WEBP:\n $this->source_image = imagecreatefromwebp($filename);\n $this->original_w = imagesx($this->source_image);\n $this->original_h = imagesy($this->source_image);\n\n break;\n\n case IMAGETYPE_BMP:\n if (version_compare(PHP_VERSION, '7.2.0', '<')) {\n throw new SystemException('For bmp support PHP >= 7.2.0 is required');\n }\n $this->source_image = imagecreatefrombmp($filename);\n break;\n\n default:\n throw new SystemException('Unsupported image type');\n }\n\n if (!$this->source_image) {\n throw new SystemException('Could not load image');\n }\n\n finfo_close($finfo);\n\n return $this->resize($this->getSourceWidth(), $this->getSourceHeight());\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "function deleteRecType($rtyID) {\n global $system, $mysqli;\n\n $ret = array();\n\n\n $query = 'SELECT dty_ID, dty_Name FROM defDetailTypes where FIND_IN_SET('.$rtyID.', dty_PtrTargetRectypeIDs)>0';\n $res = $mysqli->query($query);\n if ($mysqli->error) {\n return handleError(\"SQL error in deleteRecType retreiving field types which use rectype $rtyID\", $query, $mysqli->error);\n }else{\n $dtCount = $res->num_rows;\n if ($dtCount>0) { // there are fields that use this rectype, need to return error and the dty_IDs\n $errMsg = 'Record type '.$rtyID.' is referenced as a pointer target by the following base field definition(s). '\n .'To delete this record type you will need to remove this target record type from the base field definition(s). '\n .'Please edit the fields (click on links below) and set the <i>Target record types</i>'\n .' value to a different record type (or remove the constraint altogether).'\n .'<div style=\"text-align:left; padding-top:10px\"><ul>';\n /*\n \"Error: You cannot delete record type $rtyID. \"\n .\" It is referenced in $dtCount base field defintions \"\n .\"- please delete field definitions or remove rectype from pointer constraints to allow deletion of this record type.<div style='text-align:left'><ul>\";\n */\n $ret['dtyIDs'] = array();\n while ($row = $res->fetch_row()) {\n array_push($ret['dtyIDs'], $row[0]);\n $errMsg = $errMsg.('<li>'.$row[0]\n .'&nbsp;<a href=\"#\" onclick=\"{window.hWin.HEURIST4.ui.editBaseFieldDefinition('.$row[0].'); return false;}\">'.$row[1].'</li>');\n }\n $errMsg= $errMsg.\"</ul></div>\";\n\n $system->addError(HEURIST_ACTION_BLOCKED, $errMsg);\n return false;\n }\n }\n\n\n $query = 'SELECT sys_TreatAsPlaceRefForMapping FROM sysIdentification where 1';\n $res = $mysqli->query($query);\n if ($mysqli->error) {\n return handleError(\"SQL error in deleteRecType retreiving sys_TreatAsPlaceRefForMapping\", $query);\n }else{\n $places = $res->fetch_row();\n if(@$places[0] && $places[0]!=''){\n $places = explode(',', $places[0]);\n\n if (in_array($rtyID, $places)) {\n $system->addError(HEURIST_ACTION_BLOCKED, \"Error: You cannot delete record type $rtyID. \"\n .\" It is referenced as 'treat as places for mapping' in database properties\");\n return false;\n }\n }\n }\n\n\n $query = \"select rec_ID from Records where rec_RecTypeID=$rtyID and rec_FlagTemporary=0 limit 1\";\n $res = $mysqli->query($query);\n $error = $mysqli->error;\n if ($error) {\n $ret = handleError(\"SQL error finding records of type $rtyID in the Records table\", $query);\n } else {\n $recCount = $res->num_rows;\n if ($recCount) { // there are records existing of this rectype, need to return error and the recIDs\n $system->addError(HEURIST_ACTION_BLOCKED, \"You cannot delete record type $rtyID as it has existing data records\");\n /*$ret['recIDs'] = array();\n while ( $row = $res->fetch_row() ) {\n array_push($ret['recIDs'], $row[0]);\n }*/\n $ret = false;\n } else { // no records ok to delete this rectype. Not that this should cascade for all dependent definitions\n\n //delete temporary records\n $query = \"select rec_ID from Records where rec_RecTypeID=$rtyID and rec_FlagTemporary=1\";\n $recIds = mysql__select_list2($mysqli, $query);\n recordDelete($system, $recIds);\n\n /* @todo old h3 code to delete\n $res = $mysqli->query($query);\n while ($row = $res->fetch_row() ) {\n deleteRecord($row[0]);\n }*/\n\n $query = \"delete from defRecTypes where rty_ID = $rtyID\";\n $res = $mysqli->query($query);\n if ( $mysqli->error) {\n $ret = handleError(\"SQL error deleting record type $rtyID from defRecTypes table\", $query);\n } else {\n\n $ret['result'] = $rtyID;\n }\n }\n }\n return $ret;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['lifecycleStatus'])) {\n $this->setLifecycleStatus($data['lifecycleStatus']);\n }\n if (isset($data['achievementStatus'])) {\n $this->setAchievementStatus($data['achievementStatus']);\n }\n if (isset($data['category'])) {\n if (is_array($data['category'])) {\n foreach ($data['category'] as $d) {\n $this->addCategory($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"category\" must be array of objects or null, ' . gettype($data['category']) . ' seen.');\n }\n }\n if (isset($data['priority'])) {\n $this->setPriority($data['priority']);\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['subject'])) {\n $this->setSubject($data['subject']);\n }\n if (isset($data['startDate'])) {\n $this->setStartDate($data['startDate']);\n }\n if (isset($data['startCodeableConcept'])) {\n $this->setStartCodeableConcept($data['startCodeableConcept']);\n }\n if (isset($data['target'])) {\n if (is_array($data['target'])) {\n foreach ($data['target'] as $d) {\n $this->addTarget($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"target\" must be array of objects or null, ' . gettype($data['target']) . ' seen.');\n }\n }\n if (isset($data['statusDate'])) {\n $this->setStatusDate($data['statusDate']);\n }\n if (isset($data['statusReason'])) {\n $this->setStatusReason($data['statusReason']);\n }\n if (isset($data['expressedBy'])) {\n $this->setExpressedBy($data['expressedBy']);\n }\n if (isset($data['addresses'])) {\n if (is_array($data['addresses'])) {\n foreach ($data['addresses'] as $d) {\n $this->addAddresses($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"addresses\" must be array of objects or null, ' . gettype($data['addresses']) . ' seen.');\n }\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n if (isset($data['outcomeCode'])) {\n if (is_array($data['outcomeCode'])) {\n foreach ($data['outcomeCode'] as $d) {\n $this->addOutcomeCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"outcomeCode\" must be array of objects or null, ' . gettype($data['outcomeCode']) . ' seen.');\n }\n }\n if (isset($data['outcomeReference'])) {\n if (is_array($data['outcomeReference'])) {\n foreach ($data['outcomeReference'] as $d) {\n $this->addOutcomeReference($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"outcomeReference\" must be array of objects or null, ' . gettype($data['outcomeReference']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function ASinitPicture($arg=array()) {\n\n\t//$arg = explode(',',$arg);\n\tif (isset($arg[0]) && $arg[0]!='') { $this->xmin = $this->evalifneeded($arg[0]);}\n\tif (isset($arg[1])) { $this->xmax = $this->evalifneeded($arg[1]);}\n\tif (isset($arg[2])) { $this->ymin = $this->evalifneeded($arg[2]);}\n\tif (isset($arg[3])) { $this->ymax = $this->evalifneeded($arg[3]);}\n\n\tif ($this->xmin == $this->xmax) {\n\t\t$this->xmax = $this->xmin + .000001;\n\t}\n\tif (!is_array($this->border)) {\n\t\t$this->border = array($this->border,$this->border,$this->border,$this->border);\n\t} else if (count($this->border)<4) {\n\t\tfor ($i=count($this->border);$i<5;$i++) {\n\t\t\tif ($i==1) {\n\t\t\t\t$this->border[$i] = $this->border[0];\n\t\t\t} else {\n\t\t\t\t$this->border[$i] = $this->border[$i-2];\n\t\t\t}\n\t\t}\n\t}\n\t$this->xunitlength = ($this->width - $this->border[0] - $this->border[2])/($this->xmax - $this->xmin);\n\tif ($this->xunitlength<=0) {\n\t\t$this->xunitlength = 1;\n\t}\n\t$this->yunitlength = $this->xunitlength;\n\tif (!isset($arg[2])) { // no ymin\n\t\t$this->origin[0] = -$this->xmin*$this->xunitlength + $this->border[0];\n\t\t$this->origin[1] = $this->height / 2;\n\t\t$this->ymin = -($this->height - $this->border[1] - $this->border[3])/(2*$this->yunitlength);\n\t\t$this->ymax = -$this->ymin;\n\t} else {\n\t\tif (isset($arg[3])) { // do have ymax too\n\t\t\t$this->yunitlength = ($this->height - $this->border[1] - $this->border[3])/($this->ymax - $this->ymin);\n\t\t\tif ($this->yunitlength<=0) {\n\t\t\t\t$this->yunitlength = 1;\n\t\t\t}\n\t\t} else {\n\t\t\t$this->ymax = ($this->height - $this->border[1] - $this->border[3])/($this->yunitlength) + $this->ymin;\n\t\t}\n\t\t$this->origin[0] = -$this->xmin*$this->xunitlength + $this->border[0];\n\t\t$this->origin[1] = -$this->ymin*$this->yunitlength + $this->border[1];\n\t}\n\n\t$this->winxmin = max($this->border[0] - 5,0);\n\t$this->winxmax = min($this->width - $this->border[2] + 5, $this->width);\n\t$this->winymin = max($this->border[3] -5,0);\n\t$this->winymax = min($this->height - $this->border[1] + 5 , $this->height);\n\n\t$this->isinit = true;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function parseQRDAPatientDataSection($entryComponents): array\n {\n $this->is_qrda_import = true;\n $qrda_oids = array(\n '2.16.840.1.113883.10.20.24.3.147' => 'fetchAllergyIntoleranceObservation',\n '2.16.840.1.113883.10.20.24.3.41' => 'fetchMedicationData', // active medication @todo verify status all meds\n '2.16.840.1.113883.10.20.24.3.42' => 'fetchMedicationData', // Medication Administered Act @todo honor end dates\n '2.16.840.1.113883.10.20.24.3.139' => 'fetchMedicationData', // Medication Dispensed Act @todo set med type\n '2.16.840.1.113883.10.20.24.3.105' => 'fetchMedicationData', // Medication Discharge Act\n '2.16.840.1.113883.10.20.24.3.137' => 'fetchMedicalProblemData',// diagnosis\n '2.16.840.1.113883.10.20.24.3.138' => 'fetchMedicalProblemData',// concern symtom\n '2.16.840.1.113883.10.20.24.3.140' => 'fetchImmunizationData', // Immunization Administered (V3)\n '2.16.840.1.113883.10.20.22.4.14' => 'fetchProcedureActivityData', // procedure activity-performed 2.16.840.1.113883.10.20.24.3.64\n '2.16.840.1.113883.10.20.24.3.7' => 'fetchProcedureDeviceData', // procedure preformed Device Applied\n '2.16.840.1.113883.10.20.24.3.32' => 'fetchProcedurePreformedActivity',// procedure activity-intervention\n '2.16.840.1.113883.10.20.24.3.38' => 'fetchQrdaLabResultData', // lab test preformed\n '2.16.840.1.113883.10.20.24.3.133' => 'fetchEncounterPerformed',\n '2.16.840.1.113883.10.20.24.3.143' => 'fetchCarePlanData', // Immunization Order Substance Order @todo this is planned or goal MOVE\n '2.16.840.1.113883.10.20.24.3.47' => 'fetchCarePlanData', // Plan of Care Medication Substance Observation Activity Ordered\n '2.16.840.1.113883.10.20.24.3.130' => 'fetchCarePlanData', // Plan of Care Activity Supply CDA 2.16.840.1.113883.10.20.24.3.43\n '2.16.840.1.113883.10.20.24.3.31' => 'fetchCarePlanData', // Plan of Care Activity (act) Intervention Order\n '2.16.840.1.113883.10.20.24.3.37' => 'fetchCarePlanData', // Plan of Care Activity Observation Lab order\n '2.16.840.1.113883.10.20.24.3.17' => 'fetchCarePlanData', // Plan of Care Activity Observation Diagnostic Study, Order\n /**\n * CCDA 2.16.840.1.113883.10.20.22.4.13 - Procedure Activity Observation.\n * QRDA 2.16.840.1.113883.10.20.24.3.18 Diagnostic Study, Performed,\n * QRDA 2.16.840.1.113883.10.20.24.3.59 Physical Exam, Performed\n * QRDA '2.16.840.1.113883.10.20.24.3.54' Deceased Observation (V3) is handled in patient data parse.\n * */\n '2.16.840.1.113883.10.20.24.3.59' => 'fetchPhysicalExamPerformedData', // Physical Exam, Performed observation Vitals\n '2.16.840.1.113883.10.20.24.3.18' => 'fetchObservationPerformedData', //\n '2.16.840.1.113883.10.20.24.3.144' => 'fetchObservationPerformedData', // Assessment Performed\n '2.16.840.1.113883.10.20.24.3.54' => 'fetchDeceasedObservationData', // Deceased Observation (V3)\n '2.16.840.1.113883.10.20.24.3.55' => 'fetchPaymentSourceData', // Patient Characteristic Payer\n );\n foreach ($entryComponents['section']['entry'] as $entry) {\n $key = array_keys($entry)[0]; // need the entry template type i.e. observation, activity, substance etc.\n if (!empty($entry[$key]['templateId']['root'])) {\n if (!empty($qrda_oids[$entry[$key]['templateId']['root']])) {\n $this->currentOid = $entry[$key]['templateId']['root'];\n $func_name = $qrda_oids[$entry[$key]['templateId']['root']] ?? null;\n if (!empty($func_name)) {\n $this->$func_name($entry);\n }\n } else {\n $text = $entry[$key]['templateId']['root'] . ' ' . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Root Missing QDM: ' . $text);\n }\n } elseif (count($entry[$key]['templateId'] ?? []) > 1) {\n $key_1 = 1;\n if (!empty($qrda_oids[$entry[$key]['templateId'][$key_1]['root']])) {\n $this->currentOid = $entry[$key]['templateId'][$key_1]['root'];\n $func_name = $qrda_oids[$entry[$key]['templateId'][$key_1]['root']] ?? null;\n if (!empty($func_name)) {\n $this->$func_name($entry);\n } else {\n $text = $entry[$key]['templateId'][$key_1]['root'] . \" Key: $key_1 \" . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Missing Function for: ' . $text);\n }\n } elseif (count($entry[$key]['templateId'] ?? []) > 1) {\n $key_1 = 0;\n if (!empty($qrda_oids[$entry[$key]['templateId'][$key_1]['root']])) {\n $this->currentOid = $entry[$key]['templateId'][$key_1]['root'];\n $func_name = $qrda_oids[$entry[$key]['templateId'][$key_1]['root']] ?? null;\n if (!empty($func_name)) {\n $this->$func_name($entry);\n } else {\n $text = $entry[$key]['templateId'][$key_1]['root'] . \" Key: $key_1 \" . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Missing Function for: ' . $text);\n }\n } else {\n $text = $entry[$key]['templateId'][$key_1]['root'] . \" Key: $key_1 \" . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Missing QDM: ' . $text);\n }\n } else {\n $text = $entry[$key]['templateId'][$key_1]['root'] . ' ' . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Missing QDM: ' . $text);\n }\n } elseif (!empty($entry[$key]['root'])) {\n if (!empty($qrda_oids[$entry[$key]['root']])) {\n $this->currentOid = $entry[$key]['root'];\n $func_name = $qrda_oids[$entry[$key]['root']] ?? null;\n if (!empty($func_name)) {\n $this->$func_name($entry);\n }\n } else {\n $text = $entry[$key]['root'] . ' ' . ($entry[$key]['text'] ?: $entry[$key]['code']['displayName']);\n error_log('Root Missing QDM: ' . $text);\n }\n }\n }\n if (empty($this->templateData)) {\n error_log('Could not find any QDMs in document!');\n }\n return $this->templateData ?? [];\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function _buildWorkbookEscher()\n\t{\n\t\t$escher = null;\n\n\t\t// any drawings in this workbook?\n\t\t$found = false;\n\t\tforeach ($this->_phpExcel->getAllSheets() as $sheet) {\n\t\t\tif (count($sheet->getDrawingCollection()) > 0) {\n\t\t\t\t$found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// nothing to do if there are no drawings\n\t\tif (!$found) {\n\t\t\treturn;\n\t\t}\n\n\t\t// if we reach here, then there are drawings in the workbook\n\t\t$escher = new PHPExcel_Shared_Escher();\n\n\t\t// dggContainer\n\t\t$dggContainer = new PHPExcel_Shared_Escher_DggContainer();\n\t\t$escher->setDggContainer($dggContainer);\n\n\t\t// set IDCLs (identifier clusters)\n\t\t$dggContainer->setIDCLs($this->_IDCLs);\n\n\t\t// this loop is for determining maximum shape identifier of all drawing\n\t\t$spIdMax = 0;\n\t\t$totalCountShapes = 0;\n\t\t$countDrawings = 0;\n\n\t\tforeach ($this->_phpExcel->getAllsheets() as $sheet) {\n\t\t\t$sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet\n\n\t\t\tif (count($sheet->getDrawingCollection()) > 0) {\n\t\t\t\t++$countDrawings;\n\n\t\t\t\tforeach ($sheet->getDrawingCollection() as $drawing) {\n\t\t\t\t\t++$sheetCountShapes;\n\t\t\t\t\t++$totalCountShapes;\n\n\t\t\t\t\t$spId = $sheetCountShapes\n\t\t\t\t\t\t| ($this->_phpExcel->getIndex($sheet) + 1) << 10;\n\t\t\t\t\t$spIdMax = max($spId, $spIdMax);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t$dggContainer->setSpIdMax($spIdMax + 1);\n\t\t$dggContainer->setCDgSaved($countDrawings);\n\t\t$dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing\n\n\t\t// bstoreContainer\n\t\t$bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer();\n\t\t$dggContainer->setBstoreContainer($bstoreContainer);\n\n\t\t// the BSE's (all the images)\n\t\tforeach ($this->_phpExcel->getAllsheets() as $sheet) {\n\t\t\tforeach ($sheet->getDrawingCollection() as $drawing) {\n\t\t\t\tif ($drawing instanceof PHPExcel_Worksheet_Drawing) {\n\n\t\t\t\t\t$filename = $drawing->getPath();\n\n\t\t\t\t\tlist($imagesx, $imagesy, $imageFormat) = getimagesize($filename);\n\n\t\t\t\t\tswitch ($imageFormat) {\n\n\t\t\t\t\tcase 1: // GIF, not supported by BIFF8, we convert to PNG\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;\n\t\t\t\t\t\tob_start();\n\t\t\t\t\t\timagepng(imagecreatefromgif($filename));\n\t\t\t\t\t\t$blipData = ob_get_contents();\n\t\t\t\t\t\tob_end_clean();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 2: // JPEG\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;\n\t\t\t\t\t\t$blipData = file_get_contents($filename);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 3: // PNG\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;\n\t\t\t\t\t\t$blipData = file_get_contents($filename);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 6: // Windows DIB (BMP), we convert to PNG\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;\n\t\t\t\t\t\tob_start();\n\t\t\t\t\t\timagepng(PHPExcel_Shared_Drawing::imagecreatefrombmp($filename));\n\t\t\t\t\t\t$blipData = ob_get_contents();\n\t\t\t\t\t\tob_end_clean();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: continue 2;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t$blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();\n\t\t\t\t\t$blip->setData($blipData);\n\n\t\t\t\t\t$BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();\n\t\t\t\t\t$BSE->setBlipType($blipType);\n\t\t\t\t\t$BSE->setBlip($blip);\n\n\t\t\t\t\t$bstoreContainer->addBSE($BSE);\n\n\t\t\t\t} else if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {\n\n\t\t\t\t\tswitch ($drawing->getRenderingFunction()) {\n\n\t\t\t\t\tcase PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG;\n\t\t\t\t\t\t$renderingFunction = 'imagejpeg';\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:\n\t\t\t\t\tcase PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:\n\t\t\t\t\tcase PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:\n\t\t\t\t\t\t$blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG;\n\t\t\t\t\t\t$renderingFunction = 'imagepng';\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tob_start();\n\t\t\t\t\tcall_user_func($renderingFunction, $drawing->getImageResource());\n\t\t\t\t\t$blipData = ob_get_contents();\n\t\t\t\t\tob_end_clean();\n\n\t\t\t\t\t$blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();\n\t\t\t\t\t$blip->setData($blipData);\n\n\t\t\t\t\t$BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE();\n\t\t\t\t\t$BSE->setBlipType($blipType);\n\t\t\t\t\t$BSE->setBlip($blip);\n\n\t\t\t\t\t$bstoreContainer->addBSE($BSE);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Set the Escher object\n\t\t$this->_writerWorkbook->setEscher($escher);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public static function exec($hook_name, $hook_args = array(), $id_module = null, $array_return = false, $check_exceptions = true,\n $use_push = false, $id_shop = null)\n {\n if (defined('PS_INSTALLATION_IN_PROGRESS')) {\n return;\n }\n\n static $disable_non_native_modules = null;\n if ($disable_non_native_modules === null) {\n $disable_non_native_modules = (bool)Configuration::get('PS_DISABLE_NON_NATIVE_MODULE');\n }\n\n // Check arguments validity\n if (($id_module && !is_numeric($id_module)) || !Validate::isHookName($hook_name)) {\n throw new PrestaShopException('Invalid id_module or hook_name');\n }\n\n // If no modules associated to hook_name or recompatible hook name, we stop the function\n\n if (!$module_list = Hook::getHookModuleExecList($hook_name)) {\n return '';\n }\n\n // Check if hook exists\n if (!$id_hook = Hook::getIdByName($hook_name)) {\n return false;\n }\n\n // Store list of executed hooks on this page\n Hook::$executed_hooks[$id_hook] = $hook_name;\n\n $live_edit = false;\n $context = Context::getContext();\n if (!isset($hook_args['cookie']) || !$hook_args['cookie']) {\n $hook_args['cookie'] = $context->cookie;\n }\n if (!isset($hook_args['cart']) || !$hook_args['cart']) {\n $hook_args['cart'] = $context->cart;\n }\n\n $retro_hook_name = Hook::getRetroHookName($hook_name);\n\n // Look on modules list\n $altern = 0;\n if ($array_return) {\n $output = array();\n } else {\n $output = '';\n }\n\n if ($disable_non_native_modules && !isset(Hook::$native_module)) {\n Hook::$native_module = Module::getNativeModuleList();\n }\n\n $different_shop = false;\n if ($id_shop !== null && Validate::isUnsignedId($id_shop) && $id_shop != $context->shop->getContextShopID()) {\n $old_context = $context->shop->getContext();\n $old_shop = clone $context->shop;\n $shop = new Shop((int)$id_shop);\n if (Validate::isLoadedObject($shop)) {\n $context->shop = $shop;\n $context->shop->setContext(Shop::CONTEXT_SHOP, $shop->id);\n $different_shop = true;\n }\n }\n\n foreach ($module_list as $array) {\n // Check errors\n if ($id_module && $id_module != $array['id_module']) {\n continue;\n }\n\n if ((bool)$disable_non_native_modules && Hook::$native_module && count(Hook::$native_module) && !in_array($array['module'], Hook::$native_module)) {\n continue;\n }\n\n // Check permissions\n if ($check_exceptions) {\n $exceptions = Module::getExceptionsStatic($array['id_module'], $array['id_hook']);\n\n $controller = Dispatcher::getInstance()->getController();\n $controller_obj = Context::getContext()->controller;\n\n //check if current controller is a module controller\n if (isset($controller_obj->module) && Validate::isLoadedObject($controller_obj->module)) {\n $controller = 'module-'.$controller_obj->module->name.'-'.$controller;\n }\n\n if (in_array($controller, $exceptions)) {\n continue;\n }\n\n //Backward compatibility of controller names\n $matching_name = array(\n 'authentication' => 'auth',\n 'productscomparison' => 'compare'\n );\n if (isset($matching_name[$controller]) && in_array($matching_name[$controller], $exceptions)) {\n continue;\n }\n if (Validate::isLoadedObject($context->employee) && !Module::getPermissionStatic($array['id_module'], 'view', $context->employee)) {\n continue;\n }\n }\n\n if (!($moduleInstance = Module::getInstanceByName($array['module']))) {\n continue;\n }\n\n if ($use_push && !$moduleInstance->allow_push) {\n continue;\n }\n // Check which / if method is callable\n $hook_callable = is_callable(array($moduleInstance, 'hook'.$hook_name));\n $hook_retro_callable = is_callable(array($moduleInstance, 'hook'.$retro_hook_name));\n\n if (($hook_callable || $hook_retro_callable) && Module::preCall($moduleInstance->name)) {\n $hook_args['altern'] = ++$altern;\n\n if ($use_push && isset($moduleInstance->push_filename) && file_exists($moduleInstance->push_filename)) {\n Tools::waitUntilFileIsModified($moduleInstance->push_filename, $moduleInstance->push_time_limit);\n }\n\n // Call hook method\n if ($hook_callable) {\n $display = Hook::coreCallHook($moduleInstance, 'hook'.$hook_name, $hook_args);\n } elseif ($hook_retro_callable) {\n $display = Hook::coreCallHook($moduleInstance, 'hook'.$retro_hook_name, $hook_args);\n }\n\n // Live edit\n if (!$array_return && $array['live_edit'] && Tools::isSubmit('live_edit') && Tools::getValue('ad')\n && Tools::getValue('liveToken') == Tools::getAdminToken('AdminModulesPositions'\n .(int)Tab::getIdFromClassName('AdminModulesPositions').(int)Tools::getValue('id_employee'))) {\n $live_edit = true;\n $output .= self::wrapLiveEdit($display, $moduleInstance, $array['id_hook']);\n } elseif ($array_return) {\n $output[$moduleInstance->name] = $display;\n } else {\n $output .= $display;\n }\n }\n }\n\n if ($different_shop) {\n $context->shop = $old_shop;\n $context->shop->setContext($old_context, $shop->id);\n }\n\n if ($array_return) {\n return $output;\n } else {\n return ($live_edit ? '<script type=\"text/javascript\">hooks_list.push(\\''.$hook_name.'\\');</script>\n\t\t\t\t<div id=\"'.$hook_name.'\" class=\"dndHook\" style=\"min-height:50px\">' : '').$output.($live_edit ? '</div>' : '');\n }// Return html string\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function sanityCheckForeignCurrency(\n Validator $validator,\n AccountValidator $accountValidator,\n array $transaction,\n string $transactionType,\n int $index\n ): void {\n app('log')->debug('Now in sanityCheckForeignCurrency()');\n if (0 !== $validator->errors()->count()) {\n app('log')->debug('Already have errors, return');\n\n return;\n }\n if (null === $accountValidator->source) {\n app('log')->debug('No source, return');\n\n return;\n }\n if (null === $accountValidator->destination) {\n app('log')->debug('No destination, return');\n\n return;\n }\n $source = $accountValidator->source;\n $destination = $accountValidator->destination;\n\n app('log')->debug(sprintf('Source: #%d \"%s (%s)\"', $source->id, $source->name, $source->accountType->type));\n app('log')->debug(sprintf('Destination: #%d \"%s\" (%s)', $destination->id, $destination->name, $source->accountType->type));\n\n if (!$this->isLiabilityOrAsset($source) || !$this->isLiabilityOrAsset($destination)) {\n app('log')->debug('Any account must be liability or asset account to continue.');\n\n return;\n }\n\n /** @var AccountRepositoryInterface $accountRepository */\n $accountRepository = app(AccountRepositoryInterface::class);\n $defaultCurrency = app('amount')->getDefaultCurrency();\n $sourceCurrency = $accountRepository->getAccountCurrency($source) ?? $defaultCurrency;\n $destinationCurrency = $accountRepository->getAccountCurrency($destination) ?? $defaultCurrency;\n // if both accounts have the same currency, continue.\n if ($sourceCurrency->code === $destinationCurrency->code) {\n app('log')->debug('Both accounts have the same currency, continue.');\n\n return;\n }\n app('log')->debug(sprintf('Source account expects %s', $sourceCurrency->code));\n app('log')->debug(sprintf('Destination account expects %s', $destinationCurrency->code));\n\n app('log')->debug(sprintf('Amount is %s', $transaction['amount']));\n\n if (TransactionType::DEPOSIT === ucfirst($transactionType)) {\n app('log')->debug(sprintf('Processing as a \"%s\"', $transactionType));\n // use case: deposit from liability account to an asset account\n // the foreign amount must be in the currency of the source\n // the amount must be in the currency of the destination\n\n // no foreign currency information is present:\n if (!$this->hasForeignCurrencyInfo($transaction)) {\n $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_currency'));\n\n return;\n }\n\n // wrong currency information is present\n $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;\n $foreignCurrencyId = (int)($transaction['foreign_currency_id'] ?? 0);\n app('log')->debug(sprintf('Foreign currency code seems to be #%d \"%s\"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);\n if ($foreignCurrencyCode !== $sourceCurrency->code && $foreignCurrencyId !== $sourceCurrency->id) {\n $validator->errors()->add(sprintf('transactions.%d.foreign_currency_code', $index), (string)trans('validation.require_foreign_src'));\n\n return;\n }\n }\n if (TransactionType::TRANSFER === ucfirst($transactionType) || TransactionType::WITHDRAWAL === ucfirst($transactionType)) {\n app('log')->debug(sprintf('Processing as a \"%s\"', $transactionType));\n // use case: withdrawal from asset account to a liability account.\n // the foreign amount must be in the currency of the destination\n // the amount must be in the currency of the source\n\n // use case: transfer between accounts with different currencies.\n // the foreign amount must be in the currency of the destination\n // the amount must be in the currency of the source\n\n // no foreign currency information is present:\n if (!$this->hasForeignCurrencyInfo($transaction)) {\n $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_currency'));\n\n return;\n }\n\n // wrong currency information is present\n $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;\n $foreignCurrencyId = (int)($transaction['foreign_currency_id'] ?? 0);\n app('log')->debug(sprintf('Foreign currency code seems to be #%d \"%s\"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);\n if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {\n app('log')->debug(sprintf('No match on code, \"%s\" vs \"%s\"', $foreignCurrencyCode, $destinationCurrency->code));\n app('log')->debug(sprintf('No match on ID, #%d vs #%d', $foreignCurrencyId, $destinationCurrency->id));\n $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string)trans('validation.require_foreign_dest'));\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public static function getHookModuleExecList($hook_name = null)\n {\n $context = Context::getContext();\n $cache_id = self::MODULE_LIST_BY_HOOK_KEY.(isset($context->shop->id) ? '_'.$context->shop->id : '').((isset($context->customer)) ? '_'.$context->customer->id : '');\n if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayPaymentEU' || $hook_name == 'paymentOptions' || $hook_name == 'displayBackOfficeHeader') {\n $frontend = true;\n $groups = array();\n $use_groups = Group::isFeatureActive();\n if (isset($context->employee)) {\n $frontend = false;\n } else {\n // Get groups list\n if ($use_groups) {\n if (isset($context->customer) && $context->customer->isLogged()) {\n $groups = $context->customer->getGroups();\n } elseif (isset($context->customer) && $context->customer->isLogged(true)) {\n $groups = array((int)Configuration::get('PS_GUEST_GROUP'));\n } else {\n $groups = array((int)Configuration::get('PS_UNIDENTIFIED_GROUP'));\n }\n }\n }\n\n // SQL Request\n $sql = new DbQuery();\n $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module');\n $sql->from('module', 'm');\n if ($hook_name != 'displayBackOfficeHeader') {\n $sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & '.(int)Context::getContext()->getDevice()));\n $sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');\n }\n $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');\n $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');\n if ($hook_name != 'paymentOptions') {\n $sql->where('h.`name` != \"paymentOptions\"');\n }\n // For payment modules, we check that they are available in the contextual country\n elseif ($frontend) {\n if (Validate::isLoadedObject($context->country)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\")AND (SELECT `id_country` FROM `'._DB_PREFIX_.'module_country` mc WHERE mc.`id_module` = m.`id_module` AND `id_country` = '.(int)$context->country->id.' AND `id_shop` = '.(int)$context->shop->id.' LIMIT 1) = '.(int)$context->country->id.')');\n }\n if (Validate::isLoadedObject($context->currency)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\") AND (SELECT `id_currency` FROM `'._DB_PREFIX_.'module_currency` mcr WHERE mcr.`id_module` = m.`id_module` AND `id_currency` IN ('.(int)$context->currency->id.', -1, -2) LIMIT 1) IN ('.(int)$context->currency->id.', -1, -2))');\n }\n if (Validate::isLoadedObject($context->cart)) {\n $carrier = new Carrier($context->cart->id_carrier);\n if (Validate::isLoadedObject($carrier)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\") AND (SELECT `id_reference` FROM `'._DB_PREFIX_.'module_carrier` mcar WHERE mcar.`id_module` = m.`id_module` AND `id_reference` = '.(int)$carrier->id_reference.' AND `id_shop` = '.(int)$context->shop->id.' LIMIT 1) = '.(int)$carrier->id_reference.')');\n }\n }\n }\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('hm.`id_shop` = '.(int)$context->shop->id);\n }\n\n if ($frontend) {\n if ($use_groups) {\n $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('mg.id_shop = '.((int)$context->shop->id).(count($groups) ? ' AND mg.`id_group` IN ('.implode(', ', $groups).')' : ''));\n } elseif (count($groups)) {\n $sql->where('mg.`id_group` IN ('.implode(', ', $groups).')');\n }\n }\n }\n\n $sql->groupBy('hm.id_hook, hm.id_module');\n $sql->orderBy('hm.`position`');\n\n $list = array();\n if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {\n foreach ($result as $row) {\n $row['hook'] = strtolower($row['hook']);\n if (!isset($list[$row['hook']])) {\n $list[$row['hook']] = array();\n }\n\n $list[$row['hook']][] = array(\n 'id_hook' => $row['id_hook'],\n 'module' => $row['module'],\n 'id_module' => $row['id_module'],\n );\n }\n }\n if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU' && $hook_name != 'paymentOptions' && $hook_name != 'displayBackOfficeHeader') {\n Cache::store($cache_id, $list);\n // @todo remove this in 1.6, we keep it in 1.5 for backward compatibility\n self::$_hook_modules_cache_exec = $list;\n }\n } else {\n $list = Cache::retrieve($cache_id);\n }\n\n // If hook_name is given, just get list of modules for this hook\n if ($hook_name) {\n $retro_hook_name = strtolower(Hook::getRetroHookName($hook_name));\n $hook_name = strtolower($hook_name);\n\n $return = array();\n $inserted_modules = array();\n if (isset($list[$hook_name])) {\n $return = $list[$hook_name];\n }\n foreach ($return as $module) {\n $inserted_modules[] = $module['id_module'];\n }\n if (isset($list[$retro_hook_name])) {\n foreach ($list[$retro_hook_name] as $retro_module_call) {\n if (!in_array($retro_module_call['id_module'], $inserted_modules)) {\n $return[] = $retro_module_call;\n }\n }\n }\n\n return (count($return) > 0 ? $return : false);\n } else {\n return $list;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "#[Route('/{uuid}/save-tags', name: 'back_signalement_save_tags', methods: 'POST')]\n public function saveSignalementTags(\n Signalement $signalement,\n Request $request,\n TagRepository $tagRepository,\n EntityManagerInterface $entityManager\n ): Response {\n $this->denyAccessUnlessGranted('SIGN_EDIT', $signalement);\n\n if (\n $this->isCsrfTokenValid('signalement_save_tags', $request->request->get('_token'))\n ) {\n $tagIds = $request->request->get('tag-ids');\n $tagList = explode(',', $tagIds);\n foreach ($signalement->getTags() as $existingTag) {\n if (!\\in_array($existingTag->getId(), $tagList)) {\n $signalement->removeTag($existingTag);\n }\n }\n if (!empty($tagIds)) {\n foreach ($tagList as $tagId) {\n $tag = $tagRepository->findBy([\n 'id' => $tagId,\n 'territory' => $signalement->getTerritory(),\n 'isArchive' => 0,\n ]);\n if (!empty($tag)) {\n $signalement->addTag($tag[0]);\n }\n }\n }\n\n $entityManager->flush();\n\n $this->addFlash('success', 'Les \u00e9tiquettes ont bien \u00e9t\u00e9 enregistr\u00e9es.');\n } else {\n $this->addFlash('error', 'Erreur lors de la modification des \u00e9tiquettes !');\n }\n\n return $this->redirect($this->generateUrl('back_signalement_view', [\n 'uuid' => $signalement->getUuid(),\n ]));\n }", "smellKey": "S3776", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "function encrypt($plaintext)\n {\n if ($this->changed) {\n $this->_setup();\n }\n if ($this->use_inline_crypt) {\n $inline = $this->inline_crypt;\n return $inline('encrypt', $this, $plaintext);\n }\n if ($this->paddable) {\n $plaintext = $this->_pad($plaintext);\n }\n\n $block_size = $this->block_size;\n $buffer = &$this->enbuffer;\n $ciphertext = '';\n switch ($this->mode) {\n case CRYPT_RIJNDAEL_MODE_ECB:\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));\n }\n break;\n case CRYPT_RIJNDAEL_MODE_CBC:\n $xor = $this->encryptIV;\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $block = substr($plaintext, $i, $block_size);\n $block = $this->_encryptBlock($block ^ $xor);\n $xor = $block;\n $ciphertext.= $block;\n }\n if ($this->continuousBuffer) {\n $this->encryptIV = $xor;\n }\n break;\n case CRYPT_RIJNDAEL_MODE_CTR:\n $xor = $this->encryptIV;\n if (strlen($buffer['encrypted'])) {\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $block = substr($plaintext, $i, $block_size);\n if (strlen($block) > strlen($buffer['encrypted'])) {\n $buffer['encrypted'].= $this->_encryptBlock($this->_generate_xor($block_size, $xor));\n }\n $key = $this->_string_shift($buffer['encrypted'], $block_size);\n $ciphertext.= $block ^ $key;\n }\n } else {\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $block = substr($plaintext, $i, $block_size);\n $key = $this->_encryptBlock($this->_generate_xor($block_size, $xor));\n $ciphertext.= $block ^ $key;\n }\n }\n if ($this->continuousBuffer) {\n $this->encryptIV = $xor;\n if ($start = strlen($plaintext) % $block_size) {\n $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];\n }\n }\n break;\n case CRYPT_RIJNDAEL_MODE_CFB:\n // cfb loosely routines inspired by openssl's:\n // http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1\n if ($this->continuousBuffer) {\n $iv = &$this->encryptIV;\n $pos = &$buffer['pos'];\n } else {\n $iv = $this->encryptIV;\n $pos = 0;\n }\n $len = strlen($plaintext);\n $i = 0;\n if ($pos) {\n $orig_pos = $pos;\n $max = $block_size - $pos;\n if ($len >= $max) {\n $i = $max;\n $len-= $max;\n $pos = 0;\n } else {\n $i = $len;\n $pos+= $len;\n $len = 0;\n }\n // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize\n $ciphertext = substr($iv, $orig_pos) ^ $plaintext;\n $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);\n }\n while ($len >= $block_size) {\n $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);\n $ciphertext.= $iv;\n $len-= $block_size;\n $i+= $block_size;\n }\n if ($len) {\n $iv = $this->_encryptBlock($iv);\n $block = $iv ^ substr($plaintext, $i);\n $iv = substr_replace($iv, $block, 0, $len);\n $ciphertext.= $block;\n $pos = $len;\n }\n break;\n case CRYPT_RIJNDAEL_MODE_OFB:\n $xor = $this->encryptIV;\n if (strlen($buffer['xor'])) {\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $block = substr($plaintext, $i, $block_size);\n if (strlen($block) > strlen($buffer['xor'])) {\n $xor = $this->_encryptBlock($xor);\n $buffer['xor'].= $xor;\n }\n $key = $this->_string_shift($buffer['xor'], $block_size);\n $ciphertext.= $block ^ $key;\n }\n } else {\n for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {\n $xor = $this->_encryptBlock($xor);\n $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;\n }\n $key = $xor;\n }\n if ($this->continuousBuffer) {\n $this->encryptIV = $xor;\n if ($start = strlen($plaintext) % $block_size) {\n $buffer['xor'] = substr($key, $start) . $buffer['xor'];\n }\n }\n }\n\n return $ciphertext;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function actionAddMatrix()\n {\n $stages = $_POST['stages'];\n $disciplines = $_POST['disciplines'];\n $workload = $_POST['workload'];\n $credits = $_POST['credits'];\n if ($stages !== \"\" && $disciplines !== \"\" && $workload !== \"\" && $credits !== \"\") {\n foreach ($stages as $stage) {\n foreach ($disciplines as $discipline) {\n $matrix = CurricularMatrix::model()->find(\n \"stage_fk = :stage and discipline_fk = :discipline and school_year = :year\",\n [\n \":stage\" => $stage,\n \":discipline\" => $discipline,\n \":year\" => Yii::app()->user->year\n ]\n );\n $logSituation = \"U\";\n if ($matrix == null) {\n $matrix = new CurricularMatrix();\n $matrix->setAttributes(\n [\n \"stage_fk\" => $stage,\n \"discipline_fk\" => $discipline,\n \"school_year\" => Yii::app()->user->year\n ]\n );\n $logSituation = \"C\";\n }\n $matrix->setAttributes([\n \"workload\" => $workload,\n \"credits\" => $credits,\n ]);\n\n $stageName = EdcensoStageVsModality::model()->find(\"id = :stage\", [\":stage\" => $stage])->name;\n $disciplineName = EdcensoDiscipline::model()->find(\"id = :discipline\", [\":discipline\" => $discipline])->name;\n\n $result = $matrix->save();\n\n if ($result) {\n Log::model()->saveAction(\"curricular_matrix\", $stage . \"|\" . $discipline, $logSituation, $stageName . \"|\" . $disciplineName);\n }\n }\n }\n echo json_encode([\"valid\" => true, \"message\" => \"Matriz inserida com sucesso!\"]);\n } else {\n echo json_encode([\"valid\" => false, \"message\" => \"Preencha os campos de etapa, Componentes curriculares/eixos, carga hor\u00e1ria e horas semanais.\"]);\n }\n\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public static function registerHook($module_instance, $hook_name, $shop_list = null)\n {\n $return = true;\n $hook_names = (is_array($hook_name)) ? $hook_name : [$hook_name];\n\n foreach ($hook_names as $hook_name) {\n // Check hook name validation and if module is installed\n if (!Validate::isHookName($hook_name)) {\n throw new PrestaShopException('Invalid hook name');\n }\n if (!isset($module_instance->id) || !is_numeric($module_instance->id)) {\n return false;\n }\n\n Hook::exec(\n 'actionModuleRegisterHookBefore',\n [\n 'object' => $module_instance,\n 'hook_name' => $hook_name,\n ]\n );\n\n // Get hook id\n $id_hook = Hook::getIdByName($hook_name, false);\n\n // If hook does not exist, we create it\n if (!$id_hook) {\n $new_hook = new Hook();\n $new_hook->name = pSQL($hook_name);\n $new_hook->title = pSQL($hook_name);\n $new_hook->position = 1;\n $new_hook->add();\n $id_hook = $new_hook->id;\n if (!$id_hook) {\n return false;\n }\n }\n\n // If shop lists is null, we fill it with all shops\n if (null === $shop_list) {\n $shop_list = Shop::getCompleteListOfShopsID();\n }\n\n $shop_list_employee = Shop::getShops(true, null, true);\n\n foreach ($shop_list as $shop_id) {\n // Check if already registered\n $sql = 'SELECT hm.`id_module`\n FROM `' . _DB_PREFIX_ . 'hook_module` hm, `' . _DB_PREFIX_ . 'hook` h\n WHERE hm.`id_module` = ' . (int) $module_instance->id . ' AND h.`id_hook` = ' . $id_hook . '\n AND h.`id_hook` = hm.`id_hook` AND `id_shop` = ' . (int) $shop_id;\n if (Db::getInstance()->getRow($sql)) {\n continue;\n }\n\n // Get module position in hook\n $sql = 'SELECT MAX(`position`) AS position\n FROM `' . _DB_PREFIX_ . 'hook_module`\n WHERE `id_hook` = ' . (int) $id_hook . ' AND `id_shop` = ' . (int) $shop_id;\n if (!$position = Db::getInstance()->getValue($sql)) {\n $position = 0;\n }\n\n // Register module in hook\n $return = $return && Db::getInstance()->insert('hook_module', [\n 'id_module' => (int) $module_instance->id,\n 'id_hook' => (int) $id_hook,\n 'id_shop' => (int) $shop_id,\n 'position' => (int) ($position + 1),\n ]);\n\n if (!in_array($shop_id, $shop_list_employee)) {\n $where = '`id_module` = ' . (int) $module_instance->id . ' AND `id_shop` = ' . (int) $shop_id;\n $return = $return && Db::getInstance()->delete('module_shop', $where);\n }\n }\n\n Hook::exec(\n 'actionModuleRegisterHookAfter',\n [\n 'object' => $module_instance,\n 'hook_name' => $hook_name,\n ]\n );\n }\n\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function (Message $message, Database $dbForProject, Func $queueForFunctions, Client $statsd, callable $execute, Log $log) {\n $payload = $message->getPayload() ?? [];\n\n if (empty($payload)) {\n throw new Exception('Missing payload');\n }\n\n $type = $payload['type'] ?? '';\n $events = $payload['events'] ?? [];\n $data = $payload['body'] ?? '';\n $eventData = $payload['payload'] ?? '';\n $project = new Document($payload['project'] ?? []);\n $function = new Document($payload['function'] ?? []);\n $user = new Document($payload['user'] ?? []);\n\n if ($project->getId() === 'console') {\n return;\n }\n\n if (!empty($events)) {\n $limit = 30;\n $sum = 30;\n $offset = 0;\n $functions = [];\n /** @var Document[] $functions */\n while ($sum >= $limit) {\n $functions = $dbForProject->find('functions', [\n Query::limit($limit),\n Query::offset($offset)\n ]);\n\n $sum = \\count($functions);\n $offset = $offset + $limit;\n\n Console::log('Fetched ' . $sum . ' functions...');\n\n foreach ($functions as $function) {\n if (!array_intersect($events, $function->getAttribute('events', []))) {\n continue;\n }\n Console::success('Iterating function: ' . $function->getAttribute('name'));\n $execute(\n log: $log,\n statsd: $statsd,\n dbForProject: $dbForProject,\n project: $project,\n function: $function,\n queueForFunctions: $queueForFunctions,\n trigger: 'event',\n event: $events[0],\n eventData: \\is_string($eventData) ? $eventData : \\json_encode($eventData),\n user: $user,\n data: null,\n executionId: null,\n jwt: null,\n path: '/',\n method: 'POST',\n headers: [\n 'user-agent' => 'Appwrite/' . APP_VERSION_STABLE\n ],\n );\n Console::success('Triggered function: ' . $events[0]);\n }\n }\n return;\n }\n\n /**\n * Handle Schedule and HTTP execution.\n */\n switch ($type) {\n case 'http':\n $jwt = $payload['jwt'] ?? '';\n $execution = new Document($payload['execution'] ?? []);\n $user = new Document($payload['user'] ?? []);\n $execute(\n log: $log,\n project: $project,\n function: $function,\n dbForProject: $dbForProject,\n queueForFunctions: $queueForFunctions,\n trigger: 'http',\n executionId: $execution->getId(),\n event: null,\n eventData: null,\n data: $data,\n user: $user,\n jwt: $jwt,\n path: $payload['path'] ?? '',\n method: $payload['method'] ?? 'POST',\n headers: $payload['headers'] ?? [],\n statsd: $statsd,\n );\n break;\n case 'schedule':\n $execute(\n log: $log,\n project: $project,\n function: $function,\n dbForProject: $dbForProject,\n queueForFunctions: $queueForFunctions,\n trigger: 'schedule',\n executionId: null,\n event: null,\n eventData: null,\n data: null,\n user: null,\n jwt: null,\n path: $payload['path'] ?? '/',\n method: $payload['method'] ?? 'POST',\n headers: $payload['headers'] ?? [],\n statsd: $statsd,\n );\n break;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "private function extractXliff2(\\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)\n {\n $xml = simplexml_import_dom($dom);\n $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;\n\n $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');\n\n foreach ($xml->xpath('//xliff:unit') as $unit) {\n foreach ($unit->segment as $segment) {\n $attributes = $unit->attributes();\n $source = $attributes['name'] ?? $segment->source;\n\n // If the xlf file has another encoding specified, try to convert it because\n // simple_xml will always return utf-8 encoded values\n $target = $this->utf8ToCharset((string) ($segment->target ?? $segment->source), $encoding);\n\n $catalogue->set((string) $source, $target, $domain);\n\n $metadata = [];\n if (isset($segment->target) && $segment->target->attributes()) {\n $metadata['target-attributes'] = [];\n foreach ($segment->target->attributes() as $key => $value) {\n $metadata['target-attributes'][$key] = (string) $value;\n }\n }\n\n if (isset($unit->notes)) {\n $metadata['notes'] = [];\n foreach ($unit->notes->note as $noteNode) {\n $note = [];\n foreach ($noteNode->attributes() as $key => $value) {\n $note[$key] = (string) $value;\n }\n $note['content'] = (string) $noteNode;\n $metadata['notes'][] = $note;\n }\n }\n\n $catalogue->setMetadata((string) $source, $metadata, $domain);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function output($data, $params){\n\n if (!($data && @$data['status']==HEURIST_OK)){\n print print_r($data, true);//print out error array\n return;\n }\n\n $data = $data['data'];\n\n if(!(@$data['reccount']>0)){\n print 'EMPTY RESULT SET';\n return;\n }\n\n self::initialize();\n\n $isJoinTable = (isset($params['prefs']['join_record_types']) && $params['prefs']['join_record_types']) ? true : false;\n\n // Get the main record type IDs.\n $mainRecordTypeIDs = [];\n if (isset($params['prefs']['main_record_type_ids'])) {\n $mainRecordTypeIDs = $params['prefs']['main_record_type_ids'];\n } else {\n print 'No field selected from the main record type';\n return;\n }\n\n $save_to_file = @$params['save_to_file'] == 1;\n\n $term_ids_only = (@$params['prefs']['term_ids_only']==1);\n $include_term_ids = (@$params['prefs']['include_term_ids']==1) || $term_ids_only;\n $include_term_codes = (@$params['prefs']['include_term_codes']==1) && !$term_ids_only;\n $include_resource_titles = (@$params['prefs']['include_resource_titles']==1);\n $include_term_hierarchy = (@$params['prefs']['include_term_hierarchy']==1);\n $include_file_url = (@$params['prefs']['include_file_url']==1);\n $include_record_url_html = (@$params['prefs']['include_record_url_html']==1);\n $include_record_url_xml = (@$params['prefs']['include_record_url_xml']==1);\n $include_temporals = (@$params['prefs']['include_temporals']==1);\n\n $fields = @$params['prefs']['fields'];\n $details = array();//array of detail fields included into output\n $relmarker_details = array();//relmarker fields included into output\n\n // Handle final filename + directory\n $filename = basename('Export_'.self::$system->dbname());\n if(!empty(@$params['file']['filename'])){\n\n $filename = basename($params['file']['filename']);\n $filename = USanitize::sanitizeFileName($filename, false);\n $directory = @$params['file']['directory'];\n\n if(!empty($directory)){\n\n if(!folderExists($directory, true)){\n\n if(!$save_to_file) {\n print \"Unable to write to requested directory\";\n return;\n }\n return \"Unable to write to requested directory\";\n }\n\n $filename = rtrim($directory, '/') . \"/$filename\";\n }\n }\n\n if(self::$defRecTypes==null) {\n self::$defRecTypes = dbs_GetRectypeStructures(self::$system, null, 2);\n }\n $idx_name = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_DisplayName'];\n $idx_dtype = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['dty_Type'];\n $idx_term_tree = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_FilteredJsonTermIDTree'];\n $idx_term_nosel = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['dty_TermIDTreeNonSelectableIDs'];\n\n $defTerms = null;\n if(!$term_ids_only){\n $defTerms = dbs_GetTerms(self::$system);\n $defTerms = new \\DbsTerms(self::$system, $defTerms);\n }\n\n // Track column indices for advanced option fields.\n $groupFields = [];\n $sortFields = [];\n $countFields = [];\n $sumFields = [];\n $percentageFields = [];\n $groupColIndices = [];\n $sortColIndices = [];\n $sortOrders = [];\n $countColIndices = [];\n $sumColIndices = [];\n $percentageColIndices = [];\n\n $has_advanced = $isJoinTable;\n $need_check_memory = true;\n\n if (isset($params['prefs']['advanced_options']) || is_array($params['prefs']['advanced_options'])) {\n foreach ($params['prefs']['advanced_options'] as $fieldCode => $option) {\n $codeParts = explode(':', $fieldCode);\n if ($codeParts > 1) {\n $recordTypeID = $codeParts[count($codeParts) - 2];\n $fieldID = $codeParts[count($codeParts) - 1];\n $fieldKey = $recordTypeID . ':' . $fieldID;\n if (isset($option['total'])) {\n if ($option['total'] === 'group') {\n $groupFields[] = $fieldKey;\n $has_advanced = true;\n } elseif ($option['total'] === 'sum') {\n $sumFields[] = $fieldKey;\n $has_advanced = true;\n } elseif ($option['total'] === 'count') {\n $countFields[] = $fieldKey;\n $has_advanced = true;\n }\n }\n if (!empty($option['sort'])) {\n $sortFields[$fieldKey] = $option['sort'];\n $has_advanced = true;\n }\n\n if (isset($option['use_percentage']) && $option['use_percentage']) {\n $percentageFields[] = $fieldKey;\n $has_advanced = true;\n }\n }\n }\n\n\n }\n\n $memory_limit = USystem::getConfigBytes('memory_limit');\n\n //create header\n $any_rectype = null;\n $headers = array();\n $columnInfo = [];\n if($fields){\n foreach($fields as $rt=>$flds){\n\n if($flds[1] == 'rec_ID'){ // flip, so rec id is first\n list($flds[0], $flds[1]) = [$flds[1], $flds[0]];\n }\n\n //always include ID field into output\n if($flds[0]!='rec_ID') {array_unshift($flds, 'rec_ID');}\n $fields[$rt] = $flds;\n\n $details[$rt] = array();\n $headers[$rt] = array();\n $relmarker_details[$rt] = array();\n $columnInfo[$rt] = [];\n\n foreach($flds as $dt_id){\n\n $csvColIndex = null;\n $fieldFullID = $dt_id;\n\n $constr_rt_id = 0;\n if(strpos($dt_id,':')>0){ //for constrained resource (record pointer) fields\n //example author:person or organization\n list($dt_id, $constr_rt_id) = explode(':',$dt_id);\n }\n\n $field_name_title = '';\n\n if(is_numeric($dt_id) && $dt_id>0){\n\n if($dt_id==DT_PARENT_ENTITY){\n $field_name = 'Parent entity';\n $field_type = 'resource';\n }else{\n //get field name from structure\n $field_name = self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_name];\n $field_type = self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_dtype];\n }\n if($constr_rt_id>0){\n $rectypename_is_in_fieldname = (strpos(strtolower($field_name),\n strtolower(self::$defRecTypes['names'][$constr_rt_id]))!==false);\n $field_name_title = $field_name.($rectypename_is_in_fieldname\n ?'':' ('.self::$defRecTypes['names'][$constr_rt_id].')').' Record Title';\n\n $field_name = $field_name.($rectypename_is_in_fieldname\n ?'':' ('.self::$defRecTypes['names'][$constr_rt_id].')').H_ID;\n }else{\n $field_name_title = $field_name.' Record Title';\n }\n if($field_type=='relmarker'){\n $relmarker_details[$rt][$dt_id] = $constr_rt_id;\n }else{\n array_push($details[$rt], $dt_id);\n }\n\n }else{\n $field_type = null;\n\n if($dt_id=='rec_ID'){\n if($rt>0){\n $field_name = self::$defRecTypes['names'][$rt].H_ID;\n }else{\n $field_name = 'H-ID';\n $any_rectype = $rt;\n }\n }else{\n $field_name = $dt_id; //record header field\n }\n }\n\n if($field_type=='enum' || $field_type=='relationtype'){\n\n if(!$term_ids_only){\n array_push($headers[$rt], $field_name);//labels are always included by default\n $csvColIndex = count($headers[$rt]) - 1;\n $columnInfo[$rt][] = [\n 'index' => $csvColIndex,\n 'type' => 'value',\n 'field_id' => $fieldFullID,\n ];\n }\n\n if($include_term_ids){\n array_push($headers[$rt], $field_name.' ID');\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'term_id',\n 'field_id' => $fieldFullID,\n ];\n }\n\n if($include_term_codes){\n array_push($headers[$rt], $field_name.' StdCode' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'term_code',\n 'field_id' => $fieldFullID,\n ];\n }\n\n\n }else{\n array_push($headers[$rt], $field_name);\n $csvColIndex = count($headers[$rt]) - 1;\n $columnInfo[$rt][] = [\n 'index' => $csvColIndex,\n 'type' => 'value',\n 'field_id' => $fieldFullID,\n ];\n\n if($include_temporals && $field_type=='date'){\n array_push($headers[$rt], $field_name.'(temporal)');\n $csvColIndex = count($headers[$rt]) - 1;\n $columnInfo[$rt][] = [\n 'index' => $csvColIndex,\n 'type' => 'value',\n 'field_id' => $fieldFullID,\n ];\n }\n }\n\n if($dt_id == 'rec_ID'){\n if($include_record_url_html){ // Record URL in HTML\n array_push($headers[$rt], 'Record URL (HTML)' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'record_url_html',\n 'field_id' => $fieldFullID,\n ];\n }\n if($include_record_url_xml){ // Record URL in XML\n array_push($headers[$rt], 'Record URL (XML)' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'record_url_html',\n 'field_id' => $fieldFullID,\n ];\n }\n }\n\n if($field_type=='file'){ // Add extra details for files\n array_push($headers[$rt], $field_name.' ID' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'file_id',\n 'field_id' => $fieldFullID,\n ];\n array_push($headers[$rt], $field_name.' Name' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'file_name',\n 'field_id' => $fieldFullID,\n ];\n array_push($headers[$rt], $field_name.' Path' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'file_path',\n 'field_id' => $fieldFullID,\n ];\n if($include_file_url){\n array_push($headers[$rt], $field_name.' URL' );\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'file_url',\n 'field_id' => $fieldFullID,\n ];\n }\n }\n\n //add title for resource (record pointer) fields\n if($include_resource_titles && ($field_type=='resource' || $field_type=='relmarker')){\n\n array_push($headers[$rt], $field_name_title);\n $columnInfo[$rt][] = [\n 'index' => count($headers[$rt]) - 1,\n 'type' => 'value', //resource_title\n 'field_id' => $fieldFullID,\n ];\n }\n\n // Save column index for advanced options.\n if ($csvColIndex !== null) {\n $fieldKey = $rt . ':' . $dt_id;\n if (in_array($fieldKey, $groupFields)) {\n if (!isset($groupColIndices[$rt])) {\n $groupColIndices[$rt] = [];\n }\n $groupColIndices[$rt][] = $csvColIndex;\n }\n if (in_array($fieldKey, $countFields)) {\n if (!isset($countColIndices[$rt])) {\n $countColIndices[$rt] = [];\n }\n $countColIndices[$rt][] = $csvColIndex;\n $headers[$rt][$csvColIndex] = 'Count of ' . $headers[$rt][$csvColIndex];\n }\n if (in_array($fieldKey, $sumFields)) {\n if (!isset($sumColIndices[$rt])) {\n $sumColIndices[$rt] = [];\n }\n $sumColIndices[$rt][] = $csvColIndex;\n $headers[$rt][$csvColIndex] = 'Sum of ' . $headers[$rt][$csvColIndex];\n }\n if (in_array($fieldKey, $percentageFields)) {\n if (!isset($percentageColIndices[$rt])) {\n $percentageColIndices[$rt] = [];\n }\n $percentageColIndices[$rt][] = $csvColIndex;\n }\n if (!empty($sortFields[$fieldKey])) {\n if (!isset($sortColIndices[$rt])) {\n $sortColIndices[$rt] = [];\n }\n if (!isset($sortOrders[$rt])) {\n $sortOrders[$rt] = [];\n }\n $sortColIndices[$rt][] = $csvColIndex;\n $sortOrders[$rt][] = $sortFields[$fieldKey];\n }\n }\n }\n }\n }\n\n $csv_delimiter = $params['prefs']['csv_delimiter']?$params['prefs']['csv_delimiter']:',';\n $csv_enclosure = (@$params['prefs']['csv_enclosure']==null || $params['prefs']['csv_enclosure']=='0')\n ?null:$params['prefs']['csv_enclosure'];\n $csv_mvsep = $params['prefs']['csv_mvsep']?$params['prefs']['csv_mvsep']:'|';\n $csv_linebreak = $params['prefs']['csv_linebreak']?$params['prefs']['csv_linebreak']:'nix';//not used\n $csv_header = $params['prefs']['csv_header']?$params['prefs']['csv_header']:true;\n\n //------------\n $records = $data['records'];\n\n $streams = array();//one per record type\n $rt_counts = array();\n $csvData = [];\n\n $error_log = array();\n $error_log[] = 'Total rec count '.count($records);\n\n $idx = 0;\n if(is_array($records))\n {\n while ($idx<count($records)){\n\n $recID = $records[$idx];\n $record = recordSearchByID(self::$system, $recID, false);\n $rty_ID = ($any_rectype!=null)?$any_rectype :$record['rec_RecTypeID'];\n\n $idx++;\n\n if(!@$fields[$rty_ID]) {continue;} //none of fields for this record type marked to output\n\n\n if($has_advanced){ // everything is putting into memory\n\n if (!isset($csvData[$rty_ID])) {\n $csvData[$rty_ID] = [];\n if($csv_header) {\n $csvData[$rty_ID][] = $headers[$rty_ID];\n }\n\n $rt_counts[$rty_ID] = 1;\n } else {\n $rt_counts[$rty_ID]++;\n }\n\n }else {\n if(!@$streams[$rty_ID]){\n // create a temporary file\n $fd = fopen(TEMP_MEMORY, 'w');//less than 1MB in memory otherwise as temp file\n if (false === $fd) {\n self::$system->errorExitApi('Failed to create temporary file for csv output');\n }\n $streams[$rty_ID] = $fd;\n\n //write header\n if($csv_header){\n if($csv_enclosure){\n fputcsv($fd, $headers[$rty_ID], $csv_delimiter, $csv_enclosure);\n }else{\n fputs($fd, implode($csv_delimiter, $headers[$rty_ID]).\"\\n\"); \n }\n }\n\n $rt_counts[$rty_ID] = 1;\n }else{\n $fd = $streams[$rty_ID];\n\n $rt_counts[$rty_ID]++;\n }\n }\n\n if(!isEmptyArray(@$details[$rty_ID])){\n //fils $record\n recordSearchDetails(self::$system, $record, $details[$rty_ID]);\n }\n if(!isEmptyArray(@$relmarker_details[$rty_ID])){\n $related_recs = recordSearchRelated(self::$system, array($recID), 0);\n if(@$related_recs['status']==HEURIST_OK){\n $related_recs = $related_recs['data'];\n }else{\n $related_recs = array();\n }\n }else{\n $related_recs = array();\n }\n\n //prepare output array\n $record_row = array();\n foreach($fields[$rty_ID] as $dt_id){\n\n //suppl.fields for enum (terms) and resource (record pointer) fields\n $date_temporals = array();\n $enum_label = array();\n $enum_code = array();\n $resource_titles = array();\n $file_urls = array();\n $record_urls = array();\n $file_ids = array();\n $file_names = array();\n $file_paths = array();\n\n $constr_rt_id = 0;\n if(strpos($dt_id,':')>0){ //for constrained resource (record pointer) fields\n list($dt_id, $constr_rt_id) = explode(':', $dt_id);\n }\n\n if(is_numeric($dt_id) && $dt_id>0){\n\n if ($constr_rt_id>0 && @$relmarker_details[$rty_ID][$dt_id]==$constr_rt_id) { //relation\n\n $vals = array();\n\n foreach($related_recs['direct'] as $relation){\n $target_rt = $related_recs['headers'][$relation->targetID][1];\n if( $constr_rt_id==$target_rt && $relation->trmID>0){ //contrained rt and allowed relation type\n\n $all_terms = self::$defRecTypes['typedefs'][$rty_ID]['dtFields'][$dt_id][$idx_term_tree];\n $nonsel_terms = self::$defRecTypes['typedefs'][$rty_ID]['dtFields'][$dt_id][$idx_term_nosel];\n $is_allowed = \\VerifyValue::isValidTerm($all_terms, $nonsel_terms, $relation->trmID, $dt_id);\n\n if($is_allowed){\n //if record type among selected - add record to list to be exported\n //otherwise export only ID as field \"Rectype H-ID\"\n if($fields[$target_rt]){ //record type exists in output\n if(!in_array($relation->targetID, $records)){\n array_push($records, $relation->targetID);//add to be exported\n }\n }\n $vals[] = $relation->targetID;\n\n if($include_resource_titles){\n $resource_titles[] = $related_recs['headers'][$relation->targetID][0];\n }\n }\n }\n }//foreach\n\n //reverse will work only in case source record has detail id as in target\n foreach($related_recs['reverse'] as $relation){\n $source_rt = $related_recs['headers'][$relation->sourceID][1];\n if( $constr_rt_id==$source_rt && $relation->trmID>0\n && @self::$defRecTypes['typedefs'][$source_rt]['dtFields'][$dt_id]\n ){ //contrained rt and allowed relation type\n\n $all_terms = self::$defRecTypes['typedefs'][$source_rt]['dtFields'][$dt_id][$idx_term_tree];\n $nonsel_terms = self::$defRecTypes['typedefs'][$source_rt]['dtFields'][$dt_id][$idx_term_nosel];\n $is_allowed = \\VerifyValue::isValidTerm($all_terms, $nonsel_terms, $relation->trmID, $dt_id);\n\n if($is_allowed){\n //if record type among selected - add record to list to be exported\n //otherwise export only ID as field \"Rectype H-ID\"\n if($fields[$source_rt]){ //record type exists in output\n if(!in_array($relation->sourceID, $records)){\n array_push($records, $relation->sourceID);//add to be exported\n }\n }\n $vals[] = $relation->sourceID;\n\n if($include_resource_titles){\n $resource_titles[] = $related_recs['headers'][$relation->sourceID][0];\n }\n }\n }\n }\n\n $value = implode($csv_mvsep, $vals);\n\n if($include_resource_titles && empty($vals)){ //empty value\n $resource_titles[] = '';\n }\n\n }else{\n\n if($dt_id == DT_PARENT_ENTITY){\n $dt_type = 'resource';\n }else{\n $dt_type = self::$defRecTypes['typedefs'][$rty_ID]['dtFields'][$dt_id][$idx_dtype];\n }\n\n $values = @$record['details'][$dt_id];\n\n if(isset($values)){\n\n //$values = array_values($values);//get plain array\n $vals = array();\n\n if($dt_type==\"resource\"){\n\n //if record type among selected - add record to list to be exported\n //otherwise export only ID (and optionally title) as field \"Rectype H-ID\"\n foreach($values as $val){\n if( (!($constr_rt_id>0)) || $constr_rt_id==$val['type'] ){ //unconstrained or exact required rt\n\n if($fields[$val['type']]){ //record type exists in output\n if(!in_array($val['id'], $records)){\n array_push($records, $val['id']);//add to be exported\n }\n }\n $vals[] = $val['id'];\n\n if($include_resource_titles){\n $resource_titles[] = $val['title'];\n }\n }\n }\n }elseif($dt_type=='geo'){\n foreach($values as $val){\n $vals[] = $val['geo']['wkt'];\n }\n }elseif($dt_type=='file'){\n foreach($values as $val){\n\n $vals[] = 'ulf_' . $val['file']['ulf_ObfuscatedFileID'];\n\n $file_ids[] = $val['file']['ulf_ID'];\n $file_names[] = !empty($val['file']['ulf_OrigFileName']) ? $val['file']['ulf_OrigFileName'] : ULF_REMOTE;//$val['file']['ulf_ExternalFileReference']\n\n if(!empty($val['file']['fullPath'])){\n $file_paths[] = $val['file']['fullPath'];\n }elseif(!empty($val['file']['ulf_ExternalFileReference'])){\n $file_paths[] = $val['file']['ulf_ExternalFileReference'];//ULF_REMOTE\n }else{\n $file_paths[] = '';\n }\n\n if($include_file_url){\n if(@$val['file']['ulf_ExternalFileReference']){\n $file_urls[] = $val['file']['ulf_ExternalFileReference'];\n }else{\n $file_urls[] = HEURIST_BASE_URL.'?db='.self::$system->dbname().'&file='.$val['file']['ulf_ObfuscatedFileID'];\n }\n }\n }\n }elseif($dt_type=='date'){\n foreach($values as $val){\n $vals[] = \\Temporal::toHumanReadable(trim($val));\n if($include_temporals){\n $date_temporals[] = trim($val);\n }\n }\n }elseif($dt_type=='enum' || $dt_type=='relationtype'){\n\n if(!empty($defTerms) && !isEmptyArray($values) ){\n foreach($values as $val){\n $enum_label[] = $defTerms->getTermLabel($val, $include_term_hierarchy);\n // @$defTerms[$val][$idx_term_label]?$defTerms[$val][$idx_term_label]:'';\n $enum_code[] = $defTerms->getTermCode($val);\n //@$defTerms[$val][$idx_term_code]?$defTerms[$val][$idx_term_code]:'';\n }\n }else{\n $enum_label[] = '';\n $enum_code[] = '';\n }\n $vals = $values;\n }elseif($dt_type == 'freetext' && $dt_type == 'blocktext'){\n // escape all line feed (\\n) within text values, to avoid confusing the import\n // freetext shouldn't have any, but just in case\n foreach($values as $val){\n $vals[] = str_replace(\"\\n\", \"\\\\n\", $val);\n }\n }else{\n $vals = $values;\n }\n\n $value = implode($csv_mvsep, $vals);\n }else{\n $value = null;\n }\n\n //empty values\n if($value === null){\n if($dt_type=='enum' || $dt_type=='relationtype'){\n\n $enum_label[] = '';\n $enum_code[] = '';\n\n }elseif($include_resource_titles && $dt_type=='resource'){\n $resource_titles[] = '';\n }elseif($dt_type=='file'){\n $file_ids[] = '';\n $file_names[] = '';\n $file_paths[] = '';\n if($include_file_url){\n $file_urls[] = '';\n }\n }elseif($dt_type=='date' && $include_temporals){\n $date_temporals[] = '';\n }\n }\n\n }\n\n }elseif($dt_id=='rec_Tags'){\n\n $value = recordSearchPersonalTags(self::$system, $recID);\n $value = ($value===null)?'':implode($csv_mvsep, $value);\n\n }elseif($dt_id=='rec_RecTypeName'){\n $value = self::$defRecTypes['names'][$rty_ID];\n }elseif($dt_id=='rec_ID'){\n $value = @$record[$dt_id];\n $rec_url_base = HEURIST_BASE_URL_PRO . '?db=' . self::$system->dbname() . '&recID=' . $value;\n if($include_record_url_html){ // html\n $record_urls[] = $rec_url_base . '&fmt=html';\n }\n if($include_record_url_xml){ // xml\n $record_urls[] = $rec_url_base;\n }\n }else{\n $value = @$record[$dt_id];//from record header\n }\n if($value===null) {$value = ''; }\n\n\n if(!isEmptyArray($enum_label)){\n if(!$term_ids_only) {$record_row[] = implode($csv_mvsep,$enum_label);}\n if($include_term_ids) {$record_row[] = $value;}\n if($include_term_codes) {$record_row[] = implode($csv_mvsep,$enum_code);}\n }else {\n $record_row[] = $value;\n\n // Additional Date Field\n if(!empty($date_temporals)){\n $record_row[] = implode($csv_mvsep, $date_temporals);\n }\n\n // Additional File Fields\n if (!empty($file_ids)){\n $record_row[] = implode($csv_mvsep,$file_ids);\n }\n if (!empty($file_names)){\n $record_row[] = implode($csv_mvsep,$file_names);\n }\n if (!empty($file_paths)){\n $record_row[] = implode($csv_mvsep,$file_paths);\n }\n\n if (!empty($resource_titles)){\n $record_row[] = implode($csv_mvsep,$resource_titles);\n }elseif (!empty($file_urls)){\n $record_row[] = implode($csv_mvsep,$file_urls);\n }elseif (!empty($record_urls)){\n $record_row[] = implode($csv_delimiter,$record_urls);// two separate columns\n }\n\n if($value == '' && $dt_type==\"resource\" && $include_resource_titles && empty($resource_titles)){ // to avoid mismatched rows when adding details\n $record_row[] = $value;\n }\n }\n\n }//for fields\n\n // write the data to csv\n if(!isEmptyArray($record_row)) {\n if($has_advanced){\n $csvData[$rty_ID][] = $record_row;\n\n if($need_check_memory){\n $cnt = count($records);\n\n if($cnt>2000){\n\n if(strlen(implode(',',$record_row))*$cnt*1.5>$memory_limit){\n self::$system->errorExitApi('Sorry, this export exceeds the limit set for this server. Please reduce the number of records or the number of fields selected');\n }\n\n }\n $need_check_memory = false;\n }\n\n\n }elseif($csv_enclosure){\n fputcsv($fd, $record_row, $csv_delimiter, $csv_enclosure);\n }else{\n fputs($fd, implode($csv_delimiter, $record_row).\"\\n\"); \n }\n }\n\n }//for records\n }\n // Join csv tables.\n if ($isJoinTable && !empty($mainRecordTypeIDs)) {\n $mainRecordTypeID = $mainRecordTypeIDs[0];\n if (!empty($csvData[$mainRecordTypeID]) && !empty($columnInfo[$mainRecordTypeID])) {\n $csvData = [\n $mainRecordTypeID => self::createJointCSVTables($csvData, $columnInfo, $mainRecordTypeID, $csv_mvsep, $csv_header),\n ];\n\n // Change advanced option column indices.\n $groupColIndices = self::changeAdvancedOptionColumnIndex($groupColIndices, $mainRecordTypeID, $columnInfo);\n $sumColIndices = self::changeAdvancedOptionColumnIndex($sumColIndices, $mainRecordTypeID, $columnInfo);\n $countColIndices = self::changeAdvancedOptionColumnIndex($countColIndices, $mainRecordTypeID, $columnInfo);\n $percentageColIndices = self::changeAdvancedOptionColumnIndex($percentageColIndices, $mainRecordTypeID, $columnInfo);\n $sortColIndices = self::changeAdvancedOptionColumnIndex($sortColIndices, $mainRecordTypeID, $columnInfo);\n $sortOrders = self::changeSortOrders($sortOrders, $mainRecordTypeID);\n }\n }\n\n // Save data to streams.\n if ($has_advanced && !empty($csvData)) {\n foreach ($csvData as $recordTypeID => $rows) {\n $streams[$recordTypeID] = fopen(TEMP_MEMORY, 'w');\n\n if (is_array($rows) && !empty($rows)) {\n if ($csv_header) {\n $headerRow = array_shift($rows);\n if (!empty($percentageColIndices[$recordTypeID])) {\n $headerRow = self::usePercentageForCSVHeaders($headerRow, $percentageColIndices[$recordTypeID]);\n }\n if($csv_enclosure){\n fputcsv($streams[$recordTypeID], $headerRow, $csv_delimiter, $csv_enclosure);\n }else{\n fputs($streams[$recordTypeID], implode($csv_delimiter, $headerRow).\"\\n\"); \n }\n }\n // Apply advanced options.\n if (!empty($groupColIndices[$recordTypeID])) {\n $sumCols = empty($sumColIndices[$recordTypeID]) ? [] : $sumColIndices[$recordTypeID];\n $countCols = empty($countColIndices[$recordTypeID]) ? [] : $countColIndices[$recordTypeID];\n $rows = self::groupCSVRows($rows, $groupColIndices[$recordTypeID], $sumCols, $countCols);\n }\n if (!empty($percentageColIndices[$recordTypeID])) {\n $rows = self::usePercentageForCSVRows($rows, $percentageColIndices[$recordTypeID]);\n }\n if (!empty($sortColIndices[$recordTypeID]) && is_array($sortColIndices[$recordTypeID])) {\n // Mutate col indices as new columns inserted.\n for ($i = 0; $i < count($sortColIndices[$recordTypeID]); $i++) {\n $colIndex = $sortColIndices[$recordTypeID][$i];\n foreach ($percentageColIndices[$recordTypeID] as $percentageColIndex) {\n if ($colIndex > $percentageColIndex) {\n $sortColIndices[$recordTypeID][$i]++;\n }\n }\n }\n $rows = self::sortCSVRows($rows, $sortColIndices[$recordTypeID], $sortOrders[$recordTypeID]);\n }\n\n \n if($csv_enclosure){\n foreach ($rows as $row) {\n fputcsv($streams[$recordTypeID], $row, $csv_delimiter, $csv_enclosure);\n }\n }else{\n foreach ($rows as $row) {\n fputs($streams[$recordTypeID], implode($csv_delimiter, $row).\"\\n\");\n }\n }\n \n }\n }\n }//$has_advanced\n\n\n //calculate number of streams with columns more than one\n $count_streams = 0;\n foreach($headers as $rty_ID => $columns){\n if(is_array($columns) && count($columns)>1){\n $count_streams++;\n }\n }\n\n $error_log[] = print_r($rt_counts, true);\n\n return self::writeResults( $streams, $filename, $headers, $error_log, $save_to_file );\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public static function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)\n {\n // in case you pass directly readPHPArgv() as the first arg\n if (PEAR::isError($args)) {\n return $args;\n }\n\n if (empty($args)) {\n return array(array(), array());\n }\n\n $non_opts = $opts = array();\n\n settype($args, 'array');\n\n if ($long_options) {\n sort($long_options);\n }\n\n /*\n * Preserve backwards compatibility with callers that relied on\n * erroneous POSIX fix.\n */\n if ($version < 2) {\n if (isset($args[0][0]) && $args[0][0] != '-') {\n array_shift($args);\n }\n }\n\n for ($i = 0; $i < count($args); $i++) {\n $arg = $args[$i];\n /* The special element '--' means explicit end of\n options. Treat the rest of the arguments as non-options\n and end the loop. */\n if ($arg == '--') {\n $non_opts = array_merge($non_opts, array_slice($args, $i + 1));\n break;\n }\n\n if ($arg[0] != '-' || (strlen($arg) > 1 && $arg[1] == '-' && !$long_options)) {\n $non_opts = array_merge($non_opts, array_slice($args, $i));\n break;\n } elseif (strlen($arg) > 1 && $arg[1] == '-') {\n $error = Console_Getopt::_parseLongOption(substr($arg, 2),\n $long_options,\n $opts,\n $i,\n $args,\n $skip_unknown);\n if (PEAR::isError($error)) {\n return $error;\n }\n } elseif ($arg == '-') {\n // - is stdin\n $non_opts = array_merge($non_opts, array_slice($args, $i));\n break;\n } else {\n $error = Console_Getopt::_parseShortOption(substr($arg, 1),\n $short_options,\n $opts,\n $i,\n $args,\n $skip_unknown);\n if (PEAR::isError($error)) {\n return $error;\n }\n }\n }\n\n return array($opts, $non_opts);\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)\n {\n // Open file\n $this->openFile($pFilename);\n if (!$this->isValidFormat()) {\n fclose($this->fileHandle);\n throw new PHPExcel_Reader_Exception($pFilename . \" is an Invalid Spreadsheet file.\");\n }\n $fileHandle = $this->fileHandle;\n rewind($fileHandle);\n\n // Create new PHPExcel\n while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) {\n $objPHPExcel->createSheet();\n }\n $objPHPExcel->setActiveSheetIndex($this->sheetIndex);\n\n $fromFormats = array('\\-', '\\ ');\n $toFormats = array('-', ' ');\n\n // Loop through file\n $rowData = array();\n $column = $row = '';\n\n // loop through one row (line) at a time in the file\n while (($rowData = fgets($fileHandle)) !== false) {\n // convert SYLK encoded $rowData to UTF-8\n $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);\n\n // explode each row at semicolons while taking into account that literal semicolon (;)\n // is escaped like this (;;)\n $rowData = explode(\"\\t\", str_replace('\u00a4', ';', str_replace(';', \"\\t\", str_replace(';;', '\u00a4', rtrim($rowData)))));\n\n $dataType = array_shift($rowData);\n // Read shared styles\n if ($dataType == 'P') {\n $formatArray = array();\n foreach ($rowData as $rowDatum) {\n switch ($rowDatum{0}) {\n case 'P':\n $formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));\n break;\n case 'E':\n case 'F':\n $formatArray['font']['name'] = substr($rowDatum, 1);\n break;\n case 'L':\n $formatArray['font']['size'] = substr($rowDatum, 1);\n break;\n case 'S':\n $styleSettings = substr($rowDatum, 1);\n for ($i=0; $i<strlen($styleSettings); ++$i) {\n switch ($styleSettings{$i}) {\n case 'I':\n $formatArray['font']['italic'] = true;\n break;\n case 'D':\n $formatArray['font']['bold'] = true;\n break;\n case 'T':\n $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n break;\n case 'B':\n $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n break;\n case 'L':\n $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n break;\n case 'R':\n $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n break;\n }\n }\n break;\n }\n }\n $this->formats['P'.$this->format++] = $formatArray;\n // Read cell value data\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function fieldFormatter($value, $item = null, array $format = [])\n {\n// $event = new AdminListFieldFilterEvent($value, $item, $format);\n// $this->pixie->dispatcher->dispatch('PRE_ADMIN_LIST_FIELD_FORMAT', $event);\n// $value = $event->getValue();\n\n if ($format['max_length']) {\n $length = strlen($value);\n if ($length > $format['max_length']) {\n $value = substr($value, 0, $format['max_length']).'...';\n }\n }\n\n if ($format['strip_tags']) {\n $value = strip_tags($value);\n }\n\n $value = $format['value_prefix'] . $value;\n $value = htmlspecialchars($value);\n\n if ($format['type'] == 'image') {\n if ($value) {\n $value = '<img src=\"' . $format['dir_path'] . $value . '\" style=\"max-width: ' . $format['max_width'] . 'px; '\n . ' max-height: ' . $format['max_height'] . 'px;\" />';\n } else {\n $value = '';\n }\n }\n\n if ($format['type'] == 'boolean') {\n $value = '<span class=\"fa-boolean fa fa-circle' . ($value ? '' : '-o') . '\"></span>';\n }\n\n if ($format['type'] == 'html' && $format['template']) {\n $controller = $this;\n $value = preg_replace_callback('/%(.+?)%/', function ($match) use ($item, $controller, $value) {\n $prop = $match[1];\n $controller->checkSubProp($prop, $matches);\n if ($matches['model']) {\n $model = $matches['model'];\n $modelProp = $matches['model_prop'];\n $propValue = $item->$model->$modelProp;\n\n } else {\n $propValue = $item->$prop;\n }\n return $propValue;\n }, $format['template']);\n }\n\n $isLink = $format['type'] == 'link' || $format['is_link'];\n\n if ($isLink) {\n preg_match('/%(.+?)%/', $format['template'], $matches);\n $linkProp = $matches[1];\n if ($linkProp) {\n $this->checkSubProp($linkProp, $lpMatches);\n if ($lpMatches['model']) {\n $lpModel = $lpMatches['model'];\n $lpModelProp = $lpMatches['model_prop'];\n $linkPropValue = $item->$lpModel->$lpModelProp;\n\n } else {\n $linkPropValue = $item->$linkProp;\n }\n $value = '<a href=\"' . str_replace('%' . $linkProp . '%', $linkPropValue, $format['template']) . '\">'\n . ($format['text'] ?: $value) . '</a>';\n }\n }\n\n// $event = new AdminListFieldFilterEvent($value, $item, $format);\n// $this->pixie->dispatcher->dispatch('POST_ADMIN_LIST_FIELD_FORMAT', $event);\n// $value = $event->getValue();\n\n return $value;\n }", "smellKey": "S3776", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "public function log(mixed $level, string|Stringable $message, array $context = []): void\n {\n if (!isset($context['component'])) {\n $context['component'] = $this->component;\n }\n\n if (!isset($context['fileObject']) && $this->fileObject) {\n $context['fileObject'] = $this->fileObject;\n $this->fileObject = null;\n }\n\n if (isset($context['fileObject'])) {\n if (is_string($context['fileObject'])) {\n $context['fileObject'] = preg_replace('/^'.preg_quote(\\PIMCORE_PROJECT_ROOT, '/').'/', '', $context['fileObject']);\n } elseif ($context['fileObject'] instanceof FileObject) {\n $context['fileObject'] = $context['fileObject']->getFilename();\n } else {\n throw new InvalidArgumentException('fileObject must either be the path to a file as string or an instance of FileObject');\n }\n }\n\n $relatedObject = null;\n if (isset($context['relatedObject'])) {\n $relatedObject = $context['relatedObject'];\n }\n\n if (!$relatedObject && $this->relatedObject) {\n $relatedObject = $this->relatedObject;\n }\n\n if (is_numeric($relatedObject)) {\n $context['relatedObject'] = $relatedObject;\n $context['relatedObjectType'] = $this->relatedObjectType;\n } elseif ($relatedObject instanceof ElementInterface) {\n $context['relatedObject'] = $relatedObject->getId();\n $context['relatedObjectType'] = Service::getElementType($relatedObject);\n }\n\n if (!isset($context['source'])) {\n $context['source'] = $this->resolveLoggingSource();\n }\n\n foreach ($this->loggers as $logger) {\n if ($logger instanceof \\Psr\\Log\\LoggerInterface) {\n $logger->log($level, $message, $context);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function _ParseSearchResponse ( $response, $nreqs )\n\t{\n\t\t$p = 0; // current position\n\t\t$max = strlen($response); // max position for checks, to protect against broken responses\n\n\t\t$results = array ();\n\t\tfor ( $ires=0; $ires<$nreqs && $p<$max; $ires++ )\n\t\t{\n\t\t\t$results[] = array();\n\t\t\t$result =& $results[$ires];\n\n\t\t\t$result[\"error\"] = \"\";\n\t\t\t$result[\"warning\"] = \"\";\n\n\t\t\t// extract status\n\t\t\tlist(,$status) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t$result[\"status\"] = $status;\n\t\t\tif ( $status!=SEARCHD_OK )\n\t\t\t{\n\t\t\t\tlist(,$len) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t$message = substr ( $response, $p, $len ); $p += $len;\n\n\t\t\t\tif ( $status==SEARCHD_WARNING )\n\t\t\t\t{\n\t\t\t\t\t$result[\"warning\"] = $message;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t$result[\"error\"] = $message;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// read schema\n\t\t\t$fields = array ();\n\t\t\t$attrs = array ();\n\n\t\t\tlist(,$nfields) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\twhile ( $nfields-->0 && $p<$max )\n\t\t\t{\n\t\t\t\tlist(,$len) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t$fields[] = substr ( $response, $p, $len ); $p += $len;\n\t\t\t}\n\t\t\t$result[\"fields\"] = $fields;\n\n\t\t\tlist(,$nattrs) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\twhile ( $nattrs-->0 && $p<$max )\n\t\t\t{\n\t\t\t\tlist(,$len) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t$attr = substr ( $response, $p, $len ); $p += $len;\n\t\t\t\tlist(,$type) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t$attrs[$attr] = $type;\n\t\t\t}\n\t\t\t$result[\"attrs\"] = $attrs;\n\n\t\t\t// read match count\n\t\t\tlist(,$count) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\tlist(,$id64) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\n\t\t\t// read matches\n\t\t\t$idx = -1;\n\t\t\twhile ( $count-->0 && $p<$max )\n\t\t\t{\n\t\t\t\t// index into result array\n\t\t\t\t$idx++;\n\n\t\t\t\t// parse document id and weight\n\t\t\t\tif ( $id64 )\n\t\t\t\t{\n\t\t\t\t\t$doc = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;\n\t\t\t\t\tlist(,$weight) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tlist ( $doc, $weight ) = array_values ( unpack ( \"N*N*\",\n\t\t\t\t\t\tsubstr ( $response, $p, 8 ) ) );\n\t\t\t\t\t$p += 8;\n\t\t\t\t\t$doc = sphFixUint($doc);\n\t\t\t\t}\n\t\t\t\t$weight = sprintf ( \"%u\", $weight );\n\n\t\t\t\t// create match entry\n\t\t\t\tif ( $this->_arrayresult )\n\t\t\t\t\t$result[\"matches\"][$idx] = array ( \"id\"=>$doc, \"weight\"=>$weight );\n\t\t\t\telse\n\t\t\t\t\t$result[\"matches\"][$doc][\"weight\"] = $weight;\n\n\t\t\t\t// parse and create attributes\n\t\t\t\t$attrvals = array ();\n\t\t\t\tforeach ( $attrs as $attr=>$type )\n\t\t\t\t{\n\t\t\t\t\t// handle 64bit ints\n\t\t\t\t\tif ( $type==SPH_ATTR_BIGINT )\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// handle floats\n\t\t\t\t\tif ( $type==SPH_ATTR_FLOAT )\n\t\t\t\t\t{\n\t\t\t\t\t\tlist(,$uval) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t\t\tlist(,$fval) = unpack ( \"f*\", pack ( \"L\", $uval ) ); \n\t\t\t\t\t\t$attrvals[$attr] = $fval;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// handle double\n\t\t\t\t\tif ( $type==SPH_ATTR_DOUBLE )\n\t\t\t\t\t{\n\t\t\t\t\t\t$uval = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;\t\t\t\t\n\t\t\t\t\t\tlist(,$fval) = unpack ( \"d*\", pack ( \"Q\", $uval ) );\n\t\t\t\t\t\t$attrvals[$attr] = $fval;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// handle everything else as unsigned ints\n\t\t\t\t\tlist(,$val) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t\tif ( $type==SPH_ATTR_MULTI )\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = array ();\n\t\t\t\t\t\t$nvalues = $val;\n\t\t\t\t\t\twhile ( $nvalues-->0 && $p<$max )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlist(,$val) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t\t\t\t$attrvals[$attr][] = sphFixUint($val);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ( $type==SPH_ATTR_MULTI64 )\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = array ();\n\t\t\t\t\t\t$nvalues = $val;\n\t\t\t\t\t\twhile ( $nvalues>0 && $p<$max )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$attrvals[$attr][] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;\n\t\t\t\t\t\t\t$nvalues -= 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ( $type==SPH_ATTR_STRING )\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = substr ( $response, $p, $val );\n\t\t\t\t\t\t$p += $val;\t\t\t\t\t\t\n\t\t\t\t\t} else if ( $type==SPH_ATTR_FACTORS )\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = substr ( $response, $p, $val-4 );\n\t\t\t\t\t\t$p += $val-4;\t\t\t\t\t\t\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\t$attrvals[$attr] = sphFixUint($val);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( $this->_arrayresult )\n\t\t\t\t\t$result[\"matches\"][$idx][\"attrs\"] = $attrvals;\n\t\t\t\telse\n\t\t\t\t\t$result[\"matches\"][$doc][\"attrs\"] = $attrvals;\n\t\t\t}\n\n\t\t\tlist ( $total, $total_found, $msecs, $words ) =\n\t\t\t\tarray_values ( unpack ( \"N*N*N*N*\", substr ( $response, $p, 16 ) ) );\n\t\t\t$result[\"total\"] = sprintf ( \"%u\", $total );\n\t\t\t$result[\"total_found\"] = sprintf ( \"%u\", $total_found );\n\t\t\t$result[\"time\"] = sprintf ( \"%.3f\", $msecs/1000 );\n\t\t\t$p += 16;\n\n\t\t\twhile ( $words-->0 && $p<$max )\n\t\t\t{\n\t\t\t\tlist(,$len) = unpack ( \"N*\", substr ( $response, $p, 4 ) ); $p += 4;\n\t\t\t\t$word = substr ( $response, $p, $len ); $p += $len;\n\t\t\t\tlist ( $docs, $hits ) = array_values ( unpack ( \"N*N*\", substr ( $response, $p, 8 ) ) ); $p += 8;\n\t\t\t\t$result[\"words\"][$word] = array (\n\t\t\t\t\t\"docs\"=>sprintf ( \"%u\", $docs ),\n\t\t\t\t\t\"hits\"=>sprintf ( \"%u\", $hits ) );\n\t\t\t}\n\t\t}\n\n\t\t$this->_MBPop ();\n\t\treturn $results;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "abbas-sabra-sonarsource_manticoresearch", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['capacity'])) {\n $this->setCapacity($data['capacity']);\n }\n if (isset($data['specimenQuantity'])) {\n $this->setSpecimenQuantity($data['specimenQuantity']);\n }\n if (isset($data['additiveCodeableConcept'])) {\n $this->setAdditiveCodeableConcept($data['additiveCodeableConcept']);\n }\n if (isset($data['additiveReference'])) {\n $this->setAdditiveReference($data['additiveReference']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function simplexdisplaytable2() {\n\t//\n\t// DEFAULT colors\n\t$defaultMultipleSolutionpivotbordercolor = \"red\";\n\t$defaultMultipleSolutionpivottextcolor = \"blue\";\n\n\t$defaultpivotbordercolor = \"blue\";\n\t$defaultpivottextcolor = \"black\";\n\n\t$defaulttabletextcolor = \"black\";\n\t//\n\t// arguments list --------------------------------------------------\n\t// 0 = simplex solution sets\n\t//\t\t parent column\n\t//\t\t , pivot\n\t//\t\t , all pivot points\n\t//\t\t , simplex matrix\n\t//\t\t , solution\n\t// 1 = display ASCII tick marks (1=yes/0=no)\n\t// 2 = mode - no line, aumented, or simplex\n\t// 3 = show fractions (integer,1=yes/0=no)\n\t// 4 = header column names, default is not to show\n\t// 5 = CSS tabletextcolor.\n\t// 6 = Multiple Solution pivot border color\n\t// 7 = Multiple Solution pivot text color\n\t// 8 = pivot border color\n\t// 9 = pivot text color\n\t// 10 = Show Objective Column - Default yes/no\n\n\t// process arguments -----------------------------------------------\n\t$args = func_get_args();\n\tif (count($args)==0) {\n\t\techo \"Nothing to display - no simplex matrix supplied.<br/>\\r\\n\";\n\t\treturn \"\";\n\t}\n\n\t$simplexsolutionsets = $args[0];\n\n\t$rows = count($simplexsolutionsets);\n\t$cols = 1;\n\tfor($r = 0; $r < $rows; $r++){\n\t\t$cols = max($cols, count($simplexsolutionsets[$r]));\n\t}\n\n\t//displayASCII\n\tif((count($args)>1)&&(!is_null($args[1]))) {\n $tick = verifyASCIIticks(\"simplexdisplaytable2\",$args[1],\"`\");\n\t}\n\telse { $tick = \"`\"; }\n\n\t//mode\n\tif((count($args)>2)&&(!is_null($args[2]))) {\n\t\t$mode = verifymode(\"simplexdisplaytable2\",$args[2],2);\n\t}\n\telse { $mode=2; }\n\n\t//showfractions=1\n\tif((count($args)>3)&&(!is_null($args[3]))) {\n\t\t$showfractions = verifyshowfraction(\"simplexdisplaytable2\",$args[3],1,1);\n\t}\n\telse { $showfractions=1; }\n\n\t//header\n\tif((count($args)>4)&&(!is_null($args[4]))) {\n $headers = $args[4];\n if (!is_array($headers)) { $headers = explode(',',$headers); }\n\t}\n\telse {\n\t\t$headers = array();\n\t}\n\n\t//table text color\n\tif((count($args)>5)&&(!is_null($args[5]))) {\n\t\t$tabletextcolor = $args[5];\n\t\tif($tabletextcolor==\"\") { $tabletextcolor = $defaulttabletextcolor; }\n\t}\n\telse {\n\t\t$tabletextcolor = $defaulttabletextcolor;\n\t}\n\n\t//Multiple Solution pivot border color\n\tif((count($args)>6)&&(!is_null($args[6]))) {\n\t\t$MultipleSolutionpivotbordercolor = $args[6];\n\t\tif($MultipleSolutionpivotbordercolor==\"\") { $MultipleSolutionpivotbordercolor = $defaultMultipleSolutionpivotbordercolor; }\n\t}\n\telse {\n\t\t$MultipleSolutionpivotbordercolor = $defaultMultipleSolutionpivotbordercolor;\n\t}\n\n\t//Multiple Solution pivot text color\n\tif((count($args)>7)&&(!is_null($args[7]))) {\n\t\t$MultipleSolutionpivottextcolor = $args[7];\n\t\tif($MultipleSolutionpivottextcolor==\"\") { $MultipleSolutionpivottextcolor = $defaultMultipleSolutionpivottextcolor; }\n\t}\n\telse {\n\t\t$MultipleSolutionpivottextcolor = $defaultMultipleSolutionpivottextcolor;\n\t}\n\n\t// pivot border color\n\tif((count($args)>8)&&(!is_null($args[8]))) {\n\t\t$pivotbordercolor = $args[8];\n\t\tif($pivotbordercolor==\"\") { $pivotbordercolor = $defaultpivotbordercolor; }\n\t}\n\telse {\n\t\t$pivotbordercolor = $defaultpivotbordercolor;\n\t}\n\n\t// pivot text color\n\tif((count($args)>9)&&(!is_null($args[9]))) {\n\t\t$pivottextcolor = $args[9];\n\t\tif($pivottextcolor==\"\") { $pivottextcolor = $defaultpivottextcolor; }\n\t}\n\telse {\n\t\t$pivottextcolor = $defaultpivottextcolor;\n\t}\n\n\t// show objective ;\n\tif((count($args)>10)&&(!is_null($args[10]))) {\n\t\t$ShowObjective = verifyshowobjective(\"simplexdisplaylatex\",$args[10],1);\n\t}\n\telse {\n\t\t$ShowObjective = 1;\n\t}\n\n\t// Done processing arguments ---------------------------------------\n\n\t$solutionsetsreturn = array();\n\n\tfor($r = 0; $r < $rows; $r++){\n\t\t$solutionsetsreturn[$r] = array();\n\t\tfor($c = 0; $c < $cols; $c++){\n\t\t\t$temp = $simplexsolutionsets[$r];\n\n\t\t\tif(!isset($temp[$c])) {\n\t\t\t\t$smtable = \"&nbsp;\";\n\t\t\t}\n\t\t\telseif(is_null($temp[$c])) {\n\t\t\t\t$smtable = \"&nbsp;\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//\tparent column number: column of the parent simplex (zero based).\n\t\t\t\t//\tPivot Point Condition:\n\t\t\t\t//\tpivot point: point that will be pivoted on\n\t\t\t\t//\tpivot points: array of all possible pivots\n\t\t\t\t//\tsimplexmatrix: simplex matrix to pivot on\n\t\t\t\t//\tsolution: the solution to the simplex matrix\n\t\t\t\t$solutionset = $simplexsolutionsets[$r][$c];\n\t\t\t\t//$parentcolumn = $solutionset[0];\n\t\t\t\t$PivotPointCondition = $solutionset[1];\n\t\t\t\t$pivotpoint = $solutionset[2];\n\t\t\t\t$pivots = $solutionset[3];\n\t\t\t\t$sm = $solutionset[4];\n\t\t\t\t//$solution = $solutionset[5];\n\n\t\t\t\tif($PivotPointCondition ==PivotPointFoundMultipleSolutionList) {\n\t\t\t\t\t$bordercolor = $MultipleSolutionpivotbordercolor;\n\t\t\t\t\t$textcolor = $MultipleSolutionpivottextcolor;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$bordercolor = $pivotbordercolor;\n\t\t\t\t\t$textcolor = $pivottextcolor;\n\t\t\t\t}\n\n\t\t\t\tunset($pivotwithcolor); // clear array\n\n\t\t\t\tif(!is_null($pivotpoint)) {\n\t\t\t\t\t$pivotpoint[count($pivotpoint)] = $bordercolor;\n\t\t\t\t\t$pivotpoint[count($pivotpoint)] = $textcolor;\n\t\t\t\t\t$pivotwithcolor[0] = $pivotpoint;\n\t\t\t\t}\n\t\t\t\telseif(!is_null($pivots)) {\n\t\t\t\t\t// set the color to the pivot points\n\t\t\t\t\t$pivotwithcolor = $pivots;\n\t\t\t\t\tfor($color = 0,$size = count($pivots); $color < $size; $color++){\n\t\t\t\t\t\t$pivotwithcolor[$color][count($pivotwithcolor[$color])] = $bordercolor;\n\t\t\t\t\t\t$pivotwithcolor[$color][count($pivotwithcolor[$color])] = $textcolor;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$pivotwithcolor = array();\n\t\t\t\t}\n\t\t\t\t$smtable = simplexdisplaycolortable($sm, \"\", $tick, $mode, $showfractions, $pivotwithcolor, $headers, $tabletextcolor,$ShowObjective);\n\t\t\t}\n\n\t\t\t$solutionsetsreturn[$r][$c] = $smtable;\n\t\t}\n\t}\n\n\treturn $solutionsetsreturn;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function getAssignmentForm($source=null, $options=array()) {\n global $thisstaff;\n\n $prompt = $assignee = '';\n // Possible assignees\n $dept = $this->getDept();\n switch (strtolower($options['target'])) {\n case 'agents':\n if (!$source && $this->isOpen() && $this->staff)\n $assignee = sprintf('s%d', $this->staff->getId());\n $prompt = __('Select an Agent');\n break;\n case 'teams':\n if (!$source && $this->isOpen() && $this->team)\n $assignee = sprintf('t%d', $this->team->getId());\n $prompt = __('Select a Team');\n break;\n }\n\n // Default to current assignee if source is not set\n if (!$source)\n $source = array('assignee' => array($assignee));\n\n $form = AssignmentForm::instantiate($source, $options);\n\n if (($refer = $form->getField('refer'))) {\n if (!$assignee) {\n $visibility = new VisibilityConstraint(\n new Q(array()), VisibilityConstraint::HIDDEN);\n $refer->set('visibility', $visibility);\n } else {\n $refer->configure('desc', sprintf(__('Maintain referral access to %s'),\n $this->getAssigned()));\n }\n }\n\n // Field configurations\n if ($f=$form->getField('assignee')) {\n $f->configure('dept', $dept);\n $f->configure('staff', $thisstaff);\n if ($prompt)\n $f->configure('prompt', $prompt);\n if ($options['target'])\n $f->configure('target', $options['target']);\n }\n\n return $form;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "final public static function generateTrustedXml()\n {\n $modules_on_disk = Module::getModulesDirOnDisk();\n $trusted = array();\n $untrusted = array();\n\n $trusted_modules_xml = array(\n _PS_ROOT_DIR_ . self::CACHE_FILE_ALL_COUNTRY_MODULES_LIST,\n _PS_ROOT_DIR_ . self::CACHE_FILE_MUST_HAVE_MODULES_LIST,\n _PS_ROOT_DIR_ . self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST,\n );\n\n if (file_exists(_PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_MODULES_LIST)) {\n $trusted_modules_xml[] = _PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_MODULES_LIST;\n }\n\n // Create 2 arrays with trusted and untrusted modules\n foreach ($trusted_modules_xml as $file) {\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $trusted[] = Tools::strtolower((string) $modaddons->name);\n }\n }\n }\n\n foreach (glob(_PS_ROOT_DIR_ . '/config/xml/themes/*.xml') as $theme_xml) {\n if (file_exists($theme_xml)) {\n $content = Tools::file_get_contents($theme_xml);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml) {\n foreach ($xml->modules->module as $modaddons) {\n if ((string) $modaddons['action'] == 'install') {\n $trusted[] = Tools::strtolower((string) $modaddons['name']);\n }\n }\n }\n }\n }\n\n foreach ($modules_on_disk as $name) {\n if (!in_array($name, $trusted)) {\n if (Module::checkModuleFromAddonsApi($name)) {\n $trusted[] = Tools::strtolower($name);\n } else {\n $untrusted[] = Tools::strtolower($name);\n }\n }\n }\n\n $context = Context::getContext();\n\n // Save the 2 arrays into XML files\n $trusted_xml = new SimpleXMLElement('<modules_list/>');\n $trusted_xml->addAttribute('theme', $context->shop->theme->getName());\n $modules = $trusted_xml->addChild('modules');\n $modules->addAttribute('type', 'trusted');\n foreach ($trusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success = file_put_contents(_PS_ROOT_DIR_ . self::CACHE_FILE_TRUSTED_MODULES_LIST, $trusted_xml->asXML());\n\n $untrusted_xml = new SimpleXMLElement('<modules_list/>');\n $modules = $untrusted_xml->addChild('modules');\n $modules->addAttribute('type', 'untrusted');\n foreach ($untrusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success &= file_put_contents(_PS_ROOT_DIR_ . self::CACHE_FILE_UNTRUSTED_MODULES_LIST, $untrusted_xml->asXML());\n\n if ($success) {\n return true;\n } else {\n Context::getContext()->getTranslator()->trans('Trusted and Untrusted XML have not been generated properly', array(), 'Admin.Modules.Notification');\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function sendById(int $ID): bool\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $queued_webhook = new self();\n if (!$queued_webhook->getFromDB($ID)) {\n return false;\n }\n\n $guzzle_options = [\n 'timeout' => 5\n ];\n\n $webhook = new Webhook();\n if (!$webhook->getFromDB($queued_webhook->fields['webhooks_id'])) {\n return false;\n }\n\n if ($webhook->fields['use_cra_challenge']) {\n // Send CRA challenge\n $result = $webhook::validateCRAChallenge($queued_webhook->fields['url'], 'validate_cra_challenge', $webhook->fields['secret']);\n if ($result === false || $result['status'] !== true) {\n Toolbox::logInFile('webhook', \"CRA challenge failed for webhook {$webhook->fields['name']} ({$webhook->getID()})\");\n return false;\n }\n }\n\n $bearer_token = null;\n if ($webhook->fields['use_oauth']) {\n // Send OAuth Client Credentials\n $client = Toolbox::getGuzzleClient($guzzle_options);\n try {\n $response = $client->request('POST', $webhook->fields['oauth_url'], [\n RequestOptions::FORM_PARAMS => [\n 'grant_type' => 'client_credentials',\n 'client_id' => $webhook->fields['clientid'],\n 'client_secret' => $webhook->fields['clientsecret'],\n 'scope' => '',\n ],\n ]);\n $response = json_decode((string) $response->getBody(), true);\n if (isset($response['access_token'])) {\n $bearer_token = $response['access_token'];\n }\n } catch (GuzzleException $e) {\n Toolbox::logInFile(\n \"webhook\",\n \"OAuth authentication error for webhook {$webhook->fields['name']} ({$webhook->getID()}): \" . $e->getMessage()\n );\n }\n }\n\n $client = Toolbox::getGuzzleClient($guzzle_options);\n $headers = json_decode($queued_webhook->fields['headers'], true);\n // Remove headers with empty values\n $headers = array_filter($headers, static function ($value) {\n return !empty($value);\n });\n if ($bearer_token !== null) {\n $headers['Authorization'] = 'Bearer ' . $bearer_token;\n }\n\n try {\n $response = $client->request($queued_webhook->fields['http_method'], $queued_webhook->fields['url'], [\n RequestOptions::HEADERS => $headers,\n RequestOptions::BODY => $queued_webhook->fields['body'],\n ]);\n } catch (GuzzleException $e) {\n Toolbox::logInFile(\n \"webhook\",\n \"Error sending webhook {$webhook->fields['name']} ({$webhook->getID()}): \" . $e->getMessage()\n );\n if ($e instanceof RequestException) {\n $response = $e->getResponse();\n } else {\n $response = null;\n }\n }\n $input = [\n 'id' => $ID,\n 'sent_try' => $queued_webhook->fields['sent_try'] + 1,\n 'sent_time' => $_SESSION[\"glpi_currenttime\"],\n ];\n if ($response !== null) {\n $input['last_status_code'] = $response->getStatusCode();\n if ($queued_webhook->fields['save_response_body']) {\n $input['response_body'] = (string)$response->getBody();\n }\n\n if ($webhook->fields['log_in_item_history']) {\n /** @var class-string<CommonDBTM> $itemtype */\n $itemtype = $queued_webhook->fields['itemtype'];\n $item = new $itemtype();\n $item->getFromDB($queued_webhook->fields['items_id']);\n $tabs = $item->defineTabs();\n $has_history_tab = array_key_exists('Log$1', $tabs);\n\n if ($has_history_tab) {\n Log::history($queued_webhook->fields['items_id'], $queued_webhook->fields['itemtype'], [\n 30, $queued_webhook->fields['last_status_code'], $response->getStatusCode()\n ], $queued_webhook->fields['id'], Log::HISTORY_SEND_WEBHOOK);\n }\n }\n }\n\n return $queued_webhook->update($input) && $response !== null;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function cronPlanningRecall($task = null)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n if (!$CFG_GLPI[\"use_notifications\"]) {\n return 0;\n }\n\n $cron_status = 0;\n $iterator = $DB->request([\n 'SELECT' => 'glpi_planningrecalls.*',\n 'FROM' => 'glpi_planningrecalls',\n 'LEFT JOIN' => [\n 'glpi_alerts' => [\n 'ON' => [\n 'glpi_planningrecalls' => 'id',\n 'glpi_alerts' => 'items_id', [\n 'AND' => [\n 'glpi_alerts.itemtype' => 'PlanningRecall',\n 'glpi_alerts.type' => Alert::ACTION\n ]\n ]\n ]\n ]\n ],\n 'WHERE' => [\n 'NOT' => ['glpi_planningrecalls.when' => null],\n 'glpi_planningrecalls.when' => ['<', QueryFunction::now()],\n 'glpi_alerts.date' => null\n ]\n ]);\n\n $pr = new self();\n foreach ($iterator as $data) {\n if ($pr->getFromDB($data['id']) && $pr->getItem()) {\n $options = [];\n\n //retrieve entities id from parent linked item\n //planningrecall -> TicketTask -> Ticket which have entity notion\n // -> ChangeTask -> Change which have entity notion\n // -> ProblemTask -> Problem which have entity notion\n $itemToNotify = $pr->getItem();\n if ($itemToNotify instanceof \\CommonITILTask) {\n /** @var CommonITILObject $linkedItem */\n $linkedItem = $itemToNotify->getItem();\n // No recall, if the parent item is in a closed status\n if (in_array($linkedItem->fields['status'], array_merge($linkedItem->getSolvedStatusArray(), $linkedItem->getClosedStatusArray()))) {\n $pr->delete($data);\n continue;\n }\n if ($linkedItem && $linkedItem->isEntityAssign()) {\n $options['entities_id'] = $linkedItem->getEntityID();\n }\n }\n\n if (NotificationEvent::raiseEvent('planningrecall', $pr, $options, $itemToNotify)) {\n $cron_status = 1;\n $task->addVolume(1);\n $alert = new Alert();\n $input[\"itemtype\"] = __CLASS__;\n $input[\"type\"] = Alert::ACTION;\n $input[\"items_id\"] = $data['id'];\n\n $alert->add($input);\n }\n } else {\n // Clean item\n $pr->delete($data);\n }\n }\n return $cron_status;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getGbQuestionVersionData($qn, $generate_html = false, $ver = 'scored', $dispqn = null) {\n $by_question = ($this->assess_info->getSetting('submitby') == 'by_question');\n if ($by_question) {\n $aver = 0;\n } else if ($ver === 'scored') {\n $aver = $this->data['scored_version'];\n } else {\n $aver = $ver;\n }\n if (!$by_question) {\n $qver = 0;\n } else if ($ver === 'scored') {\n $qver = $this->data['assess_versions'][$aver]['questions'][$qn]['scored_version'];\n } else {\n $qver = $ver;\n }\n $qdata = $this->data['assess_versions'][$aver]['questions'][$qn]['question_versions'][$qver];\n\n $scoresInGb = $this->assess_info->getSetting('scoresingb');\n if ($this->teacherInGb ||\n $scoresInGb == 'immediately' ||\n ($scoresInGb == 'after_take' && $this->data['assess_versions'][$aver]['status'] == 1) ||\n ($scoresInGb == 'after_due' && time() > $this->assess_info->getSetting('enddate')) ||\n ($scoresInGb == 'after_lp' && time() > $this->assess_info->getSetting('latepass_enddate'))\n ) {\n $showScores = true;\n } else {\n $showScores = false;\n }\n\n $GLOBALS['useeditor'] = 'review'; //hacky\n if ($dispqn !== null) {\n $this->dispqn = $dispqn;\n }\n $GLOBALS['choicesdata'] = array();\n $GLOBALS['drawinitdata'] = array();\n $GLOBALS['capturechoices'] = true;\n $GLOBALS['capturedrawinit'] = true;\n\n $out = $this->getQuestionObject($qn, $showScores, true, $generate_html, $by_question ? $qver : $aver, $showScores ? 'scored' : 'last', true);\n $out['showscores'] = $scoresInGb;\n $this->dispqn = null;\n if ($generate_html) { // only include this if we're displaying the question\n $out['qid'] = $qdata['qid'];\n $out['qsetid'] = $this->assess_info->getQuestionSetting($qdata['qid'], 'questionsetid');\n $out['qowner'] = $this->assess_info->getQuestionSetData($out['qsetid'])['ownerid'];\n $out['seed'] = $qdata['seed'];\n if (isset($qdata['scoreoverride'])) {\n $out['scoreoverride'] = $qdata['scoreoverride'];\n }\n $out['timeactive'] = $this->calcTimeActive($qdata);\n $out['ver'] = $by_question ? $qver : $aver;\n if ($showScores) {\n $out['feedback'] = $qdata['feedback'] ?? '';\n }\n $out['other_tries'] = $this->getPreviousTries($qdata['tries'], $dispqn !== null ? $dispqn : $qn, $out);\n // include autosaves if teacher and last asssess & question version\n if ($this->teacherInGb &&\n $aver == count($this->data['assess_versions'])-1 &&\n $qver == count($this->data['assess_versions'][$aver]['questions'][$qn]['question_versions'])-1\n ) {\n $autosaves = $this->getAutoSaves($qn);\n if (!empty($autosaves) && !empty($autosaves['stuans'])) {\n // reformat like try data so we can reuse getPreviousTries / GbAllTries\n $autosavereformatted = array(array());\n foreach ($autosaves['stuans'] as $pn=>$val) {\n $autosavereformatted[$pn] = array(array('stuans'=>$val));\n }\n $out['autosaves'] = $this->getPreviousTries($autosavereformatted, $dispqn !== null ? $dispqn : $qn, $out);\n }\n }\n }\n return $out;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private static function getInstalled()\n {\n if (null === self::$canGetVendors) {\n self::$canGetVendors = method_exists('Composer\\Autoload\\ClassLoader', 'getRegisteredLoaders');\n }\n\n $installed = array();\n\n if (self::$canGetVendors) {\n foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {\n if (isset(self::$installedByVendor[$vendorDir])) {\n $installed[] = self::$installedByVendor[$vendorDir];\n } elseif (is_file($vendorDir.'/composer/installed.php')) {\n /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */\n $required = require $vendorDir.'/composer/installed.php';\n $installed[] = self::$installedByVendor[$vendorDir] = $required;\n if (null === self::$installed && strtr($vendorDir.'/composer', '\\\\', '/') === strtr(__DIR__, '\\\\', '/')) {\n self::$installed = $installed[count($installed) - 1];\n }\n }\n }\n }\n\n if (null === self::$installed) {\n // only require the installed.php file if this file is loaded from its dumped location,\n // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937\n if (substr(__DIR__, -8, 1) !== 'C') {\n /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */\n $required = require __DIR__ . '/installed.php';\n self::$installed = $required;\n } else {\n self::$installed = array();\n }\n }\n\n if (self::$installed !== array()) {\n $installed[] = self::$installed;\n }\n\n return $installed;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function ineqplot($funcs) {\n\tif (!is_array($funcs)) {\n\t\tsettype($funcs,\"array\");\n\t}\n\t$settings = array(-5,5,-5,5,1,1,200,200);\n\tfor ($i = 1; $i < func_num_args(); $i++) {\n\t\t$settings[$i-1] = func_get_arg($i);\n\t}\n\t$outstr = array();\n\tforeach ($funcs as $k=>$function) {\n\t\t$of = array_fill(0,6,'');\n\t\t$f = explode(\",\",$function);\n\t\t// function of x,filltype,fillcolor,linecolor,dash,strokewidth\n\t\tif ($f[1]=='above') {\n\t\t\tif (isset($f[4]) && $f[4]=='dash') {\n\t\t\t\t$of[0] = '>'.$f[0];\n\t\t\t} else {\n\t\t\t\t$of[0] = '>='.$f[0];\n\t\t\t}\n\t\t} else {\n\t\t\tif (isset($f[4]) && $f[4]=='dash') {\n\t\t\t\t$of[0] = '<'.$f[0];\n\t\t\t} else {\n\t\t\t\t$of[0] = '<='.$f[0];\n\t\t\t}\n\t\t}\n if (isset($f[2])) { \n\t\t $of[1] = $f[2];\n }\n if (isset($f[5])) {\n\t\t $of[6] = $f[5];\n }\n\t\t$outstr[] = implode(',', $of);\n\t}\n\treturn showplot($outstr,$settings[0],$settings[1],$settings[2],$settings[3],$settings[4],$settings[5],$settings[6],$settings[7]);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['title'])) {\n $this->setTitle($data['title']);\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['preConditions'])) {\n $this->setPreConditions($data['preConditions']);\n }\n if (isset($data['postConditions'])) {\n $this->setPostConditions($data['postConditions']);\n }\n if (isset($data['step'])) {\n if (is_array($data['step'])) {\n foreach ($data['step'] as $d) {\n $this->addStep($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"step\" must be array of objects or null, ' . gettype($data['step']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "final public static function renderDcBreadcrumb(int $items_id): string\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $breadcrumb = [];\n\n $item = new static();\n if ($item->getFromDB($items_id)) {\n $types = $CFG_GLPI['rackable_types'];\n\n if ($item instanceof PDU) {\n $pdu_rack = new PDU_Rack();\n $rack = new Rack();\n if (\n $pdu_rack->getFromDBByCrit(['pdus_id' => $item->getID()])\n && $rack->getFromDB($pdu_rack->fields['racks_id'])\n ) {\n $breadcrumb[Rack::getType()] = [\n 'link' => $rack->getLink(\n [\n 'class' => $rack->isDeleted() ? 'target-deleted' : '',\n 'icon' => true\n ]\n ),\n 'position' => $pdu_rack->fields['position'],\n 'side' => $pdu_rack->fields['side'],\n ];\n\n $item = $rack;\n }\n }\n\n // Add Enclosure part of breadcrumb\n $enclosure_types = $types;\n unset($enclosure_types[array_search('Enclosure', $enclosure_types)]);\n if (in_array($item->getType(), $enclosure_types) && $enclosure = $item->getParentEnclosure()) {\n $location = Location::getFromItem($enclosure) ?: null;\n $breadcrumb[Enclosure::getType()] = [\n 'link' => $enclosure->getLink(\n [\n 'class' => $enclosure->isDeleted() ? 'target-deleted' : '',\n 'icon' => true\n ]\n ),\n 'position' => $item->getPositionInEnclosure(),\n 'location' => $location !== null ? $location->fields : null,\n ];\n\n $item = $enclosure; // use Enclosure for previous breadcrumb item\n }\n\n // Add Rack part of breadcrumb\n if (in_array($item->getType(), $types) && $rack = $item->getParentRack()) {\n $location = Location::getFromItem($rack) ?: null;\n $breadcrumb[Rack::getType()] = [\n 'link' => $rack->getLink(\n [\n 'class' => $rack->isDeleted() ? 'target-deleted' : '',\n 'icon' => true\n ]\n ),\n 'position' => $item->getPositionInRack(),\n 'location' => $location !== null ? $location->fields : null,\n ];\n\n $item = $rack; // use Rack for previous breadcrumb item\n }\n\n // Add DCRoom part of breadcrumb\n $dcroom = new DCRoom();\n if (\n $item->getType() == Rack::getType()\n && $item->fields['dcrooms_id'] > 0\n && $dcroom->getFromDB($item->fields['dcrooms_id'])\n ) {\n $location = Location::getFromItem($dcroom) ?: null;\n $breadcrumb[DCRoom::getType()] = [\n 'link' => $dcroom->getLink(\n [\n 'class' => $dcroom->isDeleted() ? 'target-deleted' : '',\n 'icon' => true\n ]\n ),\n 'location' => $location !== null ? $location->fields : null,\n ];\n\n $item = $dcroom; // use DCRoom for previous breadcrumb item\n }\n\n // Add Datacenter part of breadcrumb\n $datacenter = new Datacenter();\n if (\n $item->getType() == DCRoom::getType()\n && $item->fields['datacenters_id'] > 0\n && $datacenter->getFromDB($item->fields['datacenters_id'])\n ) {\n $location = Location::getFromItem($datacenter) ?: null;\n $breadcrumb[Datacenter::getType()] = [\n 'link' => $datacenter->getLink(\n [\n 'class' => $datacenter->isDeleted() ? 'target-deleted' : '',\n 'icon' => true\n ]\n ),\n 'location' => $location !== null ? $location->fields : null,\n ];\n }\n\n $breadcrumb = array_reverse($breadcrumb);\n }\n\n return TemplateRenderer::getInstance()->render(\n 'layout/parts/dcbreadcrumbs.html.twig',\n [\n 'breadcrumbs' => $breadcrumb\n ]\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function output_header($data, $params)\n{\n\n self::initialize();\n\n $include_term_ids = (@$params['prefs']['include_term_ids']==1);\n $include_term_codes = (@$params['prefs']['include_term_codes']==1);\n $include_resource_titles = (@$params['prefs']['include_resource_titles']==1);\n $include_term_hierarchy = (@$params['prefs']['include_term_hierarchy']==1);\n $include_file_url = (@$params['prefs']['include_file_url']==1);\n $include_record_url_html = (@$params['prefs']['include_record_url_html']==1);\n $include_record_url_xml = (@$params['prefs']['include_record_url_xml']==1);\n $include_temporals = (@$params['prefs']['include_temporals']==1);\n $output_rows = (@$params['prefs']['output_rows'] == 1);// default output details as columns\n\n $fields = @$params['prefs']['fields'];\n $details = array();//array of detail fields included into output\n $relmarker_details = array();//relmarker fields included into output\n $fld_type_names = dbs_GetDtLookups();\n $base_fld_names = dbs_GetDetailTypes(self::$system, null, 0);\n\n if(self::$defRecTypes==null) {\n self::$defRecTypes = dbs_GetRectypeStructures(self::$system, null, 2);\n }\n $idx_cid = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['dty_ConceptID'];\n $idx_name = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_DisplayName'];\n $idx_dtype = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['dty_Type'];\n $idx_count = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_MaxValues'];\n $idx_require = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_RequirementType'];\n $idx_term_tree = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['rst_FilteredJsonTermIDTree'];\n $idx_term_nosel = self::$defRecTypes['typedefs']['dtFieldNamesToIndex']['dty_TermIDTreeNonSelectableIDs'];\n\n $fld_usages = array();\n $header_details = array('Field ID', 'Field name', 'Field type', 'Multivalue', 'Requirement', 'Usage count', 'Concept ID', 'Base name');// field details being exported\n $defRecStructure = new DbDefRecStructure(self::$system, null);\n $rst_data = array('a' => 'counts', 'mode' => 'rectype_field_usage', 'get_meta_counts' => 1, 'rtyID' => null);\n\n //create header\n $any_rectype = null;\n $headers = array();\n $fld_details = array();\n $terms_pickup = array();\n if($fields){\n foreach($fields as $rt=>$flds){\n\n if($flds[1] == 'rec_ID'){ // flip, so rec id is first\n list($flds[0], $flds[1]) = [$flds[1], $flds[0]];\n }\n\n //always include ID field into output\n if($flds[0]!='rec_ID') {array_unshift($flds, 'rec_ID');}\n $fields[$rt] = $flds;\n\n $details[$rt] = array();\n $headers[$rt] = array();\n $fld_details[$rt] = array();\n $relmarker_details[$rt] = array();\n\n // Get field usages\n if($rt > 0 && !array_key_exists($rt, $fld_usages)){\n // update rectype id\n $rst_data['rtyID'] = $rt;\n $defRecStructure->setData($rst_data);\n // retrieve usages\n $cnt_res = $defRecStructure->run();\n // save\n $fld_usages[$rt] = $cnt_res !== false ? $cnt_res : self::$system->getErrorMsg();\n //$fld_usages[$rt] = $cnt_res !== false ? $cnt_res : array();\n }\n\n foreach($flds as $dt_id){\n\n $constr_rt_id = 0;\n if(strpos($dt_id,':')>0){ //for constrained resource (record pointer) fields\n //example author:person or organization\n list($dt_id, $constr_rt_id) = explode(':',$dt_id);\n }\n\n $field_name_title = '';\n\n if(is_numeric($dt_id) && $dt_id>0){\n\n if($dt_id==DT_PARENT_ENTITY){\n $field_name = 'Parent entity';\n $field_type = 'resource';\n }else{\n //get field name from structure\n $field_name = self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_name];\n $field_type = self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_dtype];\n }\n if($constr_rt_id>0){\n $rectypename_is_in_fieldname = (strpos(strtolower($field_name),\n strtolower(self::$defRecTypes['names'][$constr_rt_id]))!==false);\n $field_name_title = $field_name.' '\n //.($rectypename_is_in_fieldname?'':(self::$defRecTypes['names'][$constr_rt_id].' '))\n .'RecordTitle';\n $field_name = $field_name.($rectypename_is_in_fieldname\n ?'':' ('.self::$defRecTypes['names'][$constr_rt_id].')').H_ID;\n }else{\n $field_name_title = $field_name.' RecordTitle';\n }\n if($field_type=='relmarker'){\n $relmarker_details[$rt][$dt_id] = $constr_rt_id;\n }else{\n array_push($details[$rt], $dt_id);\n }\n\n }else{\n //record header\n $field_type = null;\n\n if($dt_id=='rec_ID'){\n if($rt>0){\n $field_name = self::$defRecTypes['names'][$rt].H_ID;\n }else{\n $field_name = 'H-ID';\n $any_rectype = $rt;\n }\n }else{\n $field_name = $dt_id; //record header field\n }\n }\n\n if($field_type=='separator'){ // skip separator\n continue;\n }\n\n $fld = self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id];\n $count = $fld[$idx_count] != 1 ? 'Multivalue' : 'Single';\n $typename = !empty($fld_type_names[$field_type]) ? $fld_type_names[$field_type] : 'Built-in';\n $requirement = $fld[$idx_require];\n $usage = is_array($fld_usages[$rt]) && array_key_exists($dt_id, $fld_usages[$rt]) ? $fld_usages[$rt][$dt_id] : 0;\n $concept_id = $fld[$idx_cid];\n $base_name = $base_fld_names['names'][$dt_id];\n\n if($requirement == ''){\n if($dt_id == 'rec_ID'){\n $requirement = 'required';\n }else{\n $requirement = 'optional';\n }\n }\n\n array_push($fld_details[$rt], array($dt_id, $field_name, $typename, $count, ucfirst($requirement), \"N=$usage\", $concept_id, $base_name));\n\n if($field_type=='enum' || $field_type=='relationtype'){\n\n array_push($headers[$rt], $field_name);// labels are always included\n\n if($include_term_ids){\n array_push($headers[$rt], $field_name.' ID');\n }\n\n if($include_term_codes){\n array_push($headers[$rt], $field_name.' StdCode' );\n }\n\n //add terms pickup list\n if(!@$terms_pickup[$rt]) {$terms_pickup[$rt] = array();}\n $terms_pickup[$rt][$dt_id] = array('name'=>$field_name, 'domain'=>$field_type,\n 'term_ids'=>self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_term_tree],\n 'nonsel'=>self::$defRecTypes['typedefs'][$rt]['dtFields'][$dt_id][$idx_term_tree]);\n\n }else{\n array_push($headers[$rt], $field_name);\n if($include_temporals && $field_type=='date'){\n array_push($headers[$rt], $field_name.'(temporal)');\n }\n }\n\n //add title for resource (record pointer) fields\n if($include_resource_titles && ($field_type=='resource' || $field_type=='relmarker')){\n array_push($headers[$rt], $field_name_title);\n }\n }\n }\n }\n\n\n if(!isEmptyArray($terms_pickup)) {\n $defTerms = dbs_GetTerms(self::$system);\n $defTerms = new \\DbsTerms(self::$system, $defTerms);\n }\n\n\n $csv_delimiter = $params['prefs']['csv_delimiter']?$params['prefs']['csv_delimiter']:',';\n $csv_enclosure = $params['prefs']['csv_enclosure']?$params['prefs']['csv_enclosure']:'\"';\n\n $streams = array();//one per record type\n\n $temp_name = null;\n $print_header = true;\n //------------\n foreach($headers as $rty_ID => $columns){\n\n $placeholders = null;\n $cnt_cols = count($columns);\n if($cnt_cols>1){\n if(!@$fields[$rty_ID]) {continue;} //none of fields for this record type marked to output\n\n //prepare terms\n if(is_array(@$terms_pickup[$rty_ID])){ //there are enum fields for this rt\n\n $max_count = 0;\n $placeholders = array();\n\n foreach($terms_pickup[$rty_ID] as $dtid => $field){\n\n $placeholders[] = strtoupper($field['name']);\n $ph_help[] = '<Use to create value control lists>';\n //get list of terms\n $vocabId = $field['term_ids'];\n $terms = $defTerms->treeData($vocabId, 3);\n array_unshift($terms, $vocabId);\n $max_count = max($max_count, count($terms));\n $terms_pickup[$rty_ID][$dtid]['terms'] = $terms;\n }\n }\n\n $fd = fopen(TEMP_MEMORY, 'w');//less than 1MB in memory otherwise as temp file\n $streams[$rty_ID] = $fd;\n\n $header = $headers[$rty_ID];\n if($output_rows){\n $header = $header_details;\n }\n\n //write header\n if($print_header){\n fputcsv($fd, $header, $csv_delimiter, $csv_enclosure);\n //fwrite($fd, \"\\n\\n\");\n\n $print_header = $output_rows ? false : true; // print header once for rows output\n }\n\n //write field details\n if(array_key_exists($rty_ID, $fld_details)){\n\n if($output_rows){\n foreach ($fld_details[$rty_ID] as $details) {\n fputcsv($fd, $details, $csv_delimiter, $csv_enclosure);\n }\n }else{\n\n $max = count($header_details);\n $idx = 1; // ignore field name\n while($idx < $max){\n\n $dtl_row = array();\n foreach($fld_details[$rty_ID] as $dtls){\n array_push($dtl_row, $dtls[$idx]);\n }\n\n fputcsv($fd, $dtl_row, $csv_delimiter, $csv_enclosure);\n\n $idx ++;\n }\n }\n\n fwrite($fd, \"\\n\\n\");\n }\n\n //write terms\n if($placeholders!=null){\n\n fputcsv($fd, $placeholders, $csv_delimiter, $csv_enclosure);\n fputcsv($fd, $ph_help, $csv_delimiter, $csv_enclosure);\n\n $k = 0;\n while ($k<$max_count){\n\n $placeholders = array(); //no need to create empty columns: array_fill(0, $cnt_cols, '')\n\n foreach($terms_pickup[$rty_ID] as $dtid => $field){\n\n $terms = $terms_pickup[$rty_ID][$dtid]['terms'];\n\n if($k<count($terms)){\n $placeholders[] = $defTerms->getTermLabel($terms[$k], true);\n }else{\n $placeholders[] = '';\n }\n }//for fields\n\n fputcsv($fd, $placeholders, $csv_delimiter, $csv_enclosure);\n\n $k++;\n }//while\n\n }\n\n if($temp_name==null){\n $temp_name = 'Heurist_'.self::$system->dbname();//.'_t'.$rty_ID.'_'.self::$defRecTypes['names'][$rty_ID];\n }\n }\n }\n self::writeResults( $streams, $temp_name, $headers, null );\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function recordUpdateTitle($system, $recID, $rectype_or_mask, $recTitleDefault)\n{\n\n $mysqli = $system->get_mysqli();\n\n $mask = null;\n $rectype = null;\n\n if(is_numeric($rectype_or_mask) && $rectype_or_mask>0){\n $rectype = $rectype_or_mask;\n }elseif(!isEmptyStr($rectype_or_mask)){\n $mask = $rectype_or_mask;\n }\n\n if($mask == null)\n {\n if(!isPositiveInt($rectype)){\n $rectype = mysql__select_value($mysqli, \"select rec_RecTypeID from Records where rec_ID=\".$recID);\n }\n\n if(!isPositiveInt($rectype)){\n $system->addError(HEURIST_DB_ERROR, 'Cannot get record for title mask update. Rec#'.$recID);\n return false;\n }\n\n $mask = mysql__select_value($mysqli, 'select rty_TitleMask from defRecTypes where rty_ID='.$rectype);\n if(!$mask){\n $system->addError(HEURIST_DB_ERROR, 'Cannot get title mask for record type', $mysqli->error);\n return false;\n }\n }\n\n $new_title = TitleMask::fill($recID, $mask);\n\n if(($new_title==null || strpos($new_title, 'Title mask not generated.') === 0) && $recTitleDefault!=null) {\n $new_title = $recTitleDefault;\n }\n\n $new_title = trim($new_title);\n\n if(isEmptyStr($new_title)){\n return 'Can\\'t get title for #'.$recID;\n }\n\n if(mb_strlen($new_title)>1023){\n $new_title = mb_substr($new_title,0,1023);\n }\n\n $res = mysql__exec_param_query($mysqli, 'UPDATE Records set rec_Title=? where rec_ID='.intval($recID), array('s',$new_title) );\n if($res!==true){\n $system->addError(HEURIST_DB_ERROR, 'Cannot save record title', $res);\n return false;\n }\n\n\n return $new_title;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function getController($id_shop = null)\n {\n if (defined('_PS_ADMIN_DIR_')) {\n $_GET['controllerUri'] = Tools::getvalue('controller');\n }\n if ($this->controller) {\n $_GET['controller'] = $this->controller;\n return $this->controller;\n }\n\n if (isset(Context::getContext()->shop) && $id_shop === null) {\n $id_shop = (int)Context::getContext()->shop->id;\n }\n\n $controller = Tools::getValue('controller');\n\n if (isset($controller)\n && is_string($controller)\n && preg_match('/^([0-9a-z_-]+)\\?(.*)=(.*)$/Ui', $controller, $m)\n ) {\n $controller = $m[1];\n if (isset($_GET['controller'])) {\n $_GET[$m[2]] = $m[3];\n } elseif (isset($_POST['controller'])) {\n $_POST[$m[2]] = $m[3];\n }\n }\n\n if (!Validate::isControllerName($controller)) {\n $controller = false;\n }\n\n // Use routes ? (for url rewriting)\n if ($this->use_routes && !$controller && !defined('_PS_ADMIN_DIR_')) {\n if (!$this->request_uri) {\n return strtolower($this->controller_not_found);\n }\n $controller = $this->controller_not_found;\n $test_request_uri = preg_replace('/(=http:\\/\\/)/', '=', $this->request_uri);\n\n // If the request_uri matches a static file, then there is no need to check the routes, we keep\n // \"controller_not_found\" (a static file should not go through the dispatcher)\n if (!preg_match(\n '/\\.(gif|jpe?g|png|css|js|ico)$/i',\n parse_url($test_request_uri, PHP_URL_PATH)\n )) {\n // Add empty route as last route to prevent this greedy regexp to match request uri before right time\n if ($this->empty_route) {\n $this->addRoute(\n $this->empty_route['routeID'],\n $this->empty_route['rule'],\n $this->empty_route['controller'],\n Context::getContext()->language->id,\n array(),\n array(),\n $id_shop\n );\n }\n\n list($uri) = explode('?', $this->request_uri);\n\n if (isset($this->routes[$id_shop][Context::getContext()->language->id])) {\n foreach ($this->routes[$id_shop][Context::getContext()->language->id] as $route) {\n if (preg_match($route['regexp'], $uri, $m)) {\n // Route found ! Now fill $_GET with parameters of uri\n foreach ($m as $k => $v) {\n if (!is_numeric($k)) {\n $_GET[$k] = $v;\n }\n }\n\n $controller = $route['controller'] ? $route['controller'] : $_GET['controller'];\n if (!empty($route['params'])) {\n foreach ($route['params'] as $k => $v) {\n $_GET[$k] = $v;\n }\n }\n\n // A patch for module friendly urls\n if (preg_match('#module-([a-z0-9_-]+)-([a-z0-9_]+)$#i', $controller, $m)) {\n $_GET['module'] = $m[1];\n $_GET['fc'] = 'module';\n $controller = $m[2];\n }\n\n if (isset($_GET['fc']) && $_GET['fc'] == 'module') {\n $this->front_controller = self::FC_MODULE;\n }\n break;\n }\n }\n }\n }\n\n if ($controller == 'index' || preg_match('/^\\/index.php(?:\\?.*)?$/', $this->request_uri)) {\n $controller = $this->useDefaultController();\n }\n }\n\n $this->controller = str_replace('-', '', $controller);\n $_GET['controller'] = $this->controller;\n return $this->controller;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "static function searchable($text, $lang=false, $length=false) {\n global $cfg;\n\n if (function_exists('normalizer_normalize')) {\n // Normalize text input :: remove diacritics and such\n $text = normalizer_normalize($text, Normalizer::FORM_C);\n }\n\n if (false && class_exists('IntlBreakIterator')) {\n // Split by word boundaries\n if ($tokenizer = IntlBreakIterator::createWordInstance(\n $lang ?: ($cfg ? $cfg->getPrimaryLanguage() : 'en_US'))\n ) {\n $tokenizer->setText($text);\n $tokens = array();\n foreach ($tokenizer as $token)\n $tokens[] = $token;\n $text = implode(' ', $tokens);\n }\n }\n else {\n // Approximate word boundaries from Unicode chart at\n // http://www.unicode.org/reports/tr29/#Word_Boundaries\n\n // Punt for now\n\n // Drop extraneous whitespace\n $text = preg_replace('/(\\s)\\s+/u', '$1', $text);\n\n // Drop leading and trailing whitespace\n $text = trim($text);\n }\n\n if ($length && (str_word_count($text) > $length))\n return null;\n\n return $text;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function addAction(Request $request): JsonResponse\n {\n try {\n $type = $request->request->get('type');\n\n $className = User\\Service::getClassNameForType($type);\n $user = $className::create([\n 'parentId' => $request->request->getInt('parentId'),\n 'name' => trim($request->request->get('name', '')),\n 'password' => '',\n 'active' => $request->request->getBoolean('active'),\n ]);\n\n if ($request->get('rid')) {\n $rid = (int)$request->get('rid');\n $rObject = $className::getById($rid);\n if ($rObject) {\n if ($type == 'user' || $type == 'role') {\n $user->setParentId($rObject->getParentId());\n if ($rObject->getClasses()) {\n $user->setClasses(implode(',', $rObject->getClasses()));\n }\n if ($rObject->getDocTypes()) {\n $user->setDocTypes(implode(',', $rObject->getDocTypes()));\n }\n\n $keys = ['asset', 'document', 'object'];\n foreach ($keys as $key) {\n $getter = 'getWorkspaces' . ucfirst($key);\n $setter = 'setWorkspaces' . ucfirst($key);\n $workspaces = $rObject->$getter();\n $clonedWorkspaces = [];\n if (is_array($workspaces)) {\n /** @var User\\Workspace\\AbstractWorkspace $workspace */\n foreach ($workspaces as $workspace) {\n $vars = $workspace->getObjectVars();\n if ($key == 'object') {\n $workspaceClass = '\\\\Pimcore\\\\Model\\\\User\\\\Workspace\\\\DataObject';\n } else {\n $workspaceClass = '\\\\Pimcore\\\\Model\\\\User\\\\Workspace\\\\' . ucfirst($key);\n }\n $newWorkspace = new $workspaceClass();\n foreach ($vars as $varKey => $varValue) {\n $newWorkspace->setObjectVar($varKey, $varValue);\n }\n $newWorkspace->setUserId($user->getId());\n $clonedWorkspaces[] = $newWorkspace;\n }\n }\n\n $user->$setter($clonedWorkspaces);\n }\n\n $user->setPerspectives($rObject->getPerspectives());\n $user->setPermissions($rObject->getPermissions());\n\n if ($type == 'user') {\n $user->setAdmin(false);\n if ($this->getAdminUser()->isAdmin()) {\n $user->setAdmin($rObject->getAdmin());\n }\n $user->setActive($rObject->getActive());\n $user->setRoles($rObject->getRoles());\n $user->setWelcomeScreen($rObject->getWelcomescreen());\n $user->setMemorizeTabs($rObject->getMemorizeTabs());\n $user->setCloseWarning($rObject->getCloseWarning());\n }\n\n $user->setWebsiteTranslationLanguagesView($rObject->getWebsiteTranslationLanguagesView());\n $user->setWebsiteTranslationLanguagesEdit($rObject->getWebsiteTranslationLanguagesEdit());\n\n $user->save();\n }\n }\n }\n\n return $this->adminJson([\n 'success' => true,\n 'id' => $user->getId(),\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function Header()\n {\n if (!empty($this->pdfTemplatePath) && MiscUtility::fileExists($this->pdfTemplatePath)) {\n if (!$this->templateImported) {\n $this->setSourceFile($this->pdfTemplatePath);\n $this->templateImported = true;\n }\n $tplIdx = $this->importPage(1);\n $this->useTemplate($tplIdx, 0, 0);\n } else {\n if (!empty($this->htitle) && trim($this->htitle) != '') {\n if (!empty($this->logo) && trim($this->logo) != '') {\n if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo)) {\n $imageFilePath = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo;\n if ($this->formId == 3) {\n $this->Image($imageFilePath, 10, 5, 25, '', '', '', 'T');\n } else {\n $this->Image($imageFilePath, 95, 5, 15, '', '', '', 'T');\n }\n }\n }\n if ($this->formId == 3) {\n $this->SetFont('helvetica', 'B', 16);\n $this->writeHTMLCell(0, 0, 10, 03, $this->text, 0, 0, 0, true, 'C');\n if (!empty($this->lab) && trim($this->lab) != '') {\n $this->SetFont('helvetica', '', 10);\n $this->writeHTMLCell(0, 0, 10, 10, strtoupper($this->lab), 0, 0, 0, true, 'C');\n }\n $this->SetFont('helvetica', 'b', 10);\n $this->writeHTMLCell(0, 0, 10, 18, 'D\u00e9partement de Virologie', 0, 0, 0, true, 'C');\n $this->SetFont('helvetica', 'u', 10);\n $this->writeHTMLCell(0, 0, 10, 25, 'Laboratoire National de Reference pour la Grippe et les Virus Respiratoires', 0, 0, 0, true, 'C');\n $this->SetFont('helvetica', 'b', 12);\n $this->writeHTMLCell(0, 0, 10, 33, 'RESULTATS DE LABORATOIRE DES ECHANTIONS RESPIRATOIRES', 0, 0, 0, true, 'C');\n $this->SetFont('helvetica', 'u', 10);\n $this->writeHTMLCell(0, 0, 10, 40, 'TESTES AU COVID-19 PAR RT-PCR en temps r\u00e9el N\u00b0', 0, 0, 0, true, 'C');\n $this->writeHTMLCell(0, 0, 15, 48, '<hr>', 0, 0, 0, true, 'C');\n } else {\n $this->SetFont('helvetica', 'B', 16);\n $this->writeHTMLCell(0, 0, 10, 18, $this->text ?? '', 0, 0, 0, true, 'C');\n if (!empty($this->lab) && trim($this->lab) != '') {\n $this->SetFont('helvetica', '', 10);\n $this->writeHTMLCell(0, 0, 10, 25, strtoupper($this->lab), 0, 0, 0, true, 'C');\n }\n $this->SetFont('helvetica', '', 12);\n $this->writeHTMLCell(0, 0, 10, 30, 'COVID-19 TEST - PATIENT REPORT', 0, 0, 0, true, 'C');\n $this->writeHTMLCell(0, 0, 15, 38, '<hr>', 0, 0, 0, true, 'C');\n }\n } else {\n if (!empty($this->logo) && trim($this->logo) != '') {\n if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . \"facility-logo\" . DIRECTORY_SEPARATOR . $this->labFacilityId . DIRECTORY_SEPARATOR . $this->logo)) {\n $imageFilePath = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'facility-logo' . DIRECTORY_SEPARATOR . $this->labFacilityId . DIRECTORY_SEPARATOR . $this->logo;\n $this->Image($imageFilePath, 16, 13, 15, '', '', '', 'T');\n } else if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo)) {\n $imageFilePath = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . $this->logo;\n $this->Image($imageFilePath, 20, 13, 15, '', '', '', 'T');\n }\n }\n if (file_exists(UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . 'drc-logo.png')) {\n $imageFilePath = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR . 'drc-logo.png';\n $this->Image($imageFilePath, 180, 13, 15, '', '', '', 'T');\n }\n\n // $this->SetFont('helvetica', 'B', 7);\n // $this->writeHTMLCell(30,0,16,28,$this->text, 0, 0, 0, true, 'A', true);(this two lines comment out for drc)\n $this->SetFont('helvetica', '', 14);\n $this->writeHTMLCell(0, 0, 10, 9, 'MINISTERE DE LA SANTE PUBLIQUE', 0, 0, 0, true, 'C');\n if (!empty($this->text) && trim($this->text) != '') {\n $this->SetFont('helvetica', '', 12);\n // $this->writeHTMLCell(0,0,10,16,'PROGRAMME NATIONAL DE LUTTE CONTRE LE SIDA ET IST', 0, 0, 0, true, 'C', true);\n $this->writeHTMLCell(0, 0, 10, 16, strtoupper($this->text), 0, 0, 0, true, 'C');\n $thirdHeading = '23';\n $fourthHeading = '28';\n $hrLine = '36';\n $marginTop = '14';\n } else {\n $thirdHeading = '17';\n $fourthHeading = '23';\n $hrLine = '30';\n $marginTop = '9';\n }\n if (!empty($this->lab) && trim($this->lab) != '') {\n $this->SetFont('helvetica', '', 9);\n $this->writeHTMLCell(0, 0, 10, $thirdHeading, strtoupper($this->lab), 0, 0, 0, true, 'C');\n }\n $this->SetFont('helvetica', '', 12);\n $this->writeHTMLCell(0, 0, 10, $fourthHeading, 'RESULTATS CHARGE VIRALE', 0, 0, 0, true, 'C');\n $this->writeHTMLCell(0, 0, 15, $hrLine, '<hr>', 0, 0, 0, true, 'C');\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function resendEmailAction(Request $request): JsonResponse\n {\n if (!$this->getAdminUser()->isAllowed('emails')) {\n throw $this->createAccessDeniedHttpException(\"Permission denied, user needs 'emails' permission.\");\n }\n\n $success = false;\n $emailLog = Tool\\Email\\Log::getById((int) $request->get('id'));\n\n if ($emailLog instanceof Tool\\Email\\Log) {\n $mail = new Mail();\n $mail->preventDebugInformationAppending();\n $mail->setIgnoreDebugMode(true);\n\n if (!empty($request->get('to'))) {\n $emailLog->setTo(null);\n $emailLog->setCc(null);\n $emailLog->setBcc(null);\n } else {\n $mail->disableLogging();\n }\n\n if ($html = $emailLog->getHtmlLog()) {\n $mail->html($html);\n }\n\n if ($text = $emailLog->getTextLog()) {\n $mail->text($text);\n }\n\n foreach (['From', 'To', 'Cc', 'Bcc', 'ReplyTo'] as $field) {\n if (!$values = $request->get(strtolower($field))) {\n $getter = 'get' . $field;\n $values = $emailLog->{$getter}();\n }\n\n $values = \\Pimcore\\Helper\\Mail::parseEmailAddressField($values);\n\n if ($values) {\n [$value] = $values;\n $prefix = 'add';\n $mail->{$prefix . $field}(new Address($value['email'], $value['name']));\n }\n }\n\n $mail->subject($emailLog->getSubject());\n\n // add document\n if ($emailLog->getDocumentId()) {\n $mail->setDocument($emailLog->getDocumentId());\n }\n\n // re-add params\n try {\n $params = $emailLog->getParams();\n } catch (\\Exception $e) {\n Logger::warning('Could not decode JSON param string');\n $params = [];\n }\n\n foreach ($params as $entry) {\n $data = null;\n $hasChildren = isset($entry['children']) && is_array($entry['children']);\n\n if ($hasChildren) {\n $childData = [];\n foreach ($entry['children'] as $childParam) {\n $childData[$childParam['key']] = $this->parseLoggingParamObject($childParam);\n }\n $data = $childData;\n } else {\n $data = $this->parseLoggingParamObject($entry);\n }\n\n $mail->setParam($entry['key'], $data);\n }\n\n $mail->send();\n $success = true;\n }\n\n return $this->adminJson([\n 'success' => $success,\n ]);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function getLabeledValue(array|ElementInterface $element): ResultContainer|\\stdClass|null\n {\n $result = new \\stdClass();\n $result->label = $this->label;\n\n $children = $this->getChildren();\n\n if ($this->getOperator() !== 'and' && $this->getOperator() !== 'or') {\n return $result;\n }\n\n if (!$children) {\n return $result;\n } else {\n $valueArray = [];\n foreach ($children as $c) {\n $childResult = $c->getLabeledValue($element);\n $isArrayType = $childResult->isArrayType ?? false;\n $childValues = $childResult->value ?? null;\n if ($childValues && !$isArrayType) {\n $childValues = [$childValues];\n }\n\n if (is_array($childValues)) {\n foreach ($childValues as $value) {\n if (is_null($value) && $this->skipNull) {\n continue;\n }\n $valueArray[] = $value;\n }\n } else {\n if (!$this->skipNull) {\n $valueArray[] = null;\n }\n }\n }\n\n $resultValue = current($valueArray);\n foreach ($valueArray as $val) {\n if ($this->getOperator() === 'and') {\n $resultValue = $val && $resultValue;\n } else {\n $resultValue = $val || $resultValue;\n }\n }\n $result->value = $resultValue;\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function _fixupWidths(&$widths, $mins) {\n foreach ($widths as $i=>$w) {\n if ($w < $mins[$i]) {\n // Borrow from another column -- the furthest one away from\n // its minimum width\n $best = 0; $bestidx = false;\n foreach ($widths as $j=>$w) {\n if ($i == $j)\n continue;\n if ($w > $mins[$j]) {\n if ($w - $mins[$j] > $best) {\n $best = $w - $mins[$j];\n $bestidx = $j;\n }\n }\n }\n if ($bestidx !== false) {\n $widths[$bestidx]--;\n $widths[$i]++;\n return $this->_fixupWidths($widths, $mins);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function counts(){\n\n $mysqli = $this->system->getMysqli();\n $res = null;\n\n if(@$this->data['mode'] == 'rectype_field_usage'){\n\n $rty_ID = intval(@$this->data['rtyID'], 10);\n\n // For checking relation types\n $defTerms = dbs_GetTerms($this->system);\n $defTerms = new \\DbsTerms($this->system, $defTerms);\n\n if(isset($rty_ID) && is_numeric($rty_ID) && $rty_ID > 0){\n\n // Get count for all details, except relmarkers\n $query = 'SELECT dtl_DetailTypeID, count(dtl_ID) '\n . 'FROM recDetails '\n . 'INNER JOIN Records ON rec_ID=dtl_RecID '\n . 'WHERE rec_RecTypeID=' . $rty_ID . ' '\n . 'GROUP BY dtl_DetailTypeID';\n $detail_usage = mysql__select_assoc2($mysqli, $query);// [ dty_ID1 => count1, ... ]\n if($detail_usage){\n $res = $detail_usage;\n }elseif(empty($mysqli->error)){\n $res = array();\n }else{\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot retrieve field usages for record type #'.$rty_ID, $mysqli->error);\n return false;\n }\n\n // Check for relmarkers\n $query = 'SELECT dty_ID, dty_PtrTargetRectypeIDs, dty_JsonTermIDTree '\n . 'FROM defRecStructure '\n . 'INNER JOIN defDetailTypes ON rst_DetailTypeID=dty_ID '\n . 'WHERE dty_Type=\"relmarker\" AND rst_RecTypeID=' . $rty_ID;\n $relmarker_filters = mysql__select_assoc($mysqli, $query);// [ relmarker_fld_ID1 => [rty_id_list1, trm_id1], ... ]\n if($relmarker_filters && !empty($relmarker_filters)){\n\n // Retrieve record ids that are relevant\n $query = 'SELECT DISTINCT rec_ID FROM Records, recLinks WHERE rec_RecTypeID=' . $rty_ID\n . ' AND rl_RelationID > 0 AND (rl_SourceID=rec_ID OR rl_TargetID=rec_ID)';\n $ids = mysql__select_list2($mysqli, $query);// returns array of rec ids\n if(is_array($ids) && !empty($ids)){\n\n $rec_ids = implode(',', $ids);\n foreach ($relmarker_filters as $dty_id => $fld_details) {\n\n $allowed_recs = array();// records that meet the rectype requirement\n $not_allowed_recs = array();// records that don't meet the rectype requirement\n $count = 0;\n\n // Get possible related types (relation terms)\n $terms = $defTerms->treeData($fld_details['dty_JsonTermIDTree'], 'set');\n // Split possible related rectypes\n $rectypes = explode(',', $fld_details['dty_PtrTargetRectypeIDs']);\n $allow_all = empty($rectypes);\n\n if(is_array($terms) && !empty($terms)){\n // Retrieve relmarker count - from\n $query = 'SELECT rl_TargetID '\n . 'FROM recLinks '\n . 'WHERE rl_RelationTypeID IN (' . implode(',', $terms) . ') AND rl_SourceID IN ('. $rec_ids .')';\n $rel_usage_from = mysql__select_list2($mysqli, $query);// returns count\n if(!empty($mysqli->error)){\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot retrieve relationship marker usage for field #'.$dty_id.' from record type #'.$rty_ID, $mysqli->error);\n return false;\n }\n\n $query = 'SELECT rl_SourceID '\n . 'FROM recLinks '\n . 'WHERE rl_RelationTypeID IN (' . implode(',', $terms) . ') AND rl_TargetID IN ('. $rec_ids .')';\n $rel_usage_to = mysql__select_list2($mysqli, $query);// returns count\n if(!empty($mysqli->error)){\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot retrieve reverse relationship marker usage for field #'.$dty_id.' from record type #'.$rty_ID, $mysqli->error);\n return false;\n }\n\n $rel_usages = array_merge($rel_usage_from, $rel_usage_to);\n\n foreach($rel_usages as $rec_id){\n if(in_array($rec_id, $allowed_recs)){\n $count ++;\n continue;\n }elseif(in_array($rec_id, $not_allowed_recs)){\n continue;\n }\n\n $check_res = mysql__select_value($mysqli, \"SELECT rec_RecTypeID FROM Records WHERE rec_ID = $rec_id\");\n if(!empty($mysqli->error)){\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot retrieve record type id for record #'.$rec_id, $mysqli->error);\n return false;\n }\n\n if($allow_all || in_array($check_res, $rectypes)){\n $count ++;\n $allowed_recs[] = $rec_id;\n }else{\n $not_allowed_recs[] = $rec_id;\n }\n }\n }\n\n $res[$dty_id] = $count;\n }\n }elseif(!empty($mysqli->error)){\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot retrieve related records for counting relationship marker field usage for record type #'.$rty_ID, $mysqli->error);\n return false;\n }\n }elseif(!empty($mysqli->error)){\n $this->system->addError(HEURIST_DB_ERROR, 'Cannot check record type #'.$rty_ID.' for relationship marker fields', $mysqli->error);\n return false;\n }\n\n if(@$this->data['get_meta_counts'] == 1){ // Include count of rec_ field counts\n\n // Get number of records\n $query = \"SELECT count(rec_ID) \"\n . \"FROM Records \"\n . \"WHERE rec_RecTypeID = $rty_ID AND rec_FlagTemporary = 0\";\n\n $rec_counts = mysql__select_value($mysqli, $query);\n $res['rec_ID'] = !$rec_counts ? 0 : $rec_counts;\n\n // Get number of rec URLs\n $query = \"SELECT count(rec_URL) \"\n . \"FROM Records \"\n . \"WHERE rec_RecTypeID = $rty_ID AND rec_FlagTemporary = 0\";\n\n $url_counts = mysql__select_value($mysqli, $query);\n $res['rec_URL'] = !$url_counts ? 0 : $url_counts;\n\n // Get number of records with tags\n $query = \"SELECT DISTINCT count(rtl_RecID)\"\n . \"FROM usrRecTagLinks \"\n . \"INNER JOIN Records ON rec_ID = rtl_ID \"\n . \"WHERE rec_RecTypeID = $rty_ID AND rec_FlagTemporary = 0\";\n\n $tag_count = mysql__select_value($mysqli, $query);\n $res['rec_Tags'] = !$tag_count ? 0 : $tag_count;\n }\n\n if(!$res || empty($res)){\n $res = [0];\n }\n }else{\n $this->system->addError(HEURIST_ACTION_BLOCKED, 'Invalid record type id provided '.$rty_ID);\n $res = false;\n }\n }\n\n return $res;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['uri'])) {\n $this->setUri($data['uri']);\n }\n if (isset($data['version'])) {\n if (is_array($data['version'])) {\n foreach ($data['version'] as $d) {\n $this->addVersion($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"version\" must be array of objects or null, ' . gettype($data['version']) . ' seen.');\n }\n }\n if (isset($data['subsumption'])) {\n $this->setSubsumption($data['subsumption']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function createContentType(APIContentTypeCreateStruct $contentTypeCreateStruct, array $contentTypeGroups): APIContentTypeDraft\n {\n if (!$this->permissionResolver->canUser('class', 'create', $contentTypeCreateStruct, $contentTypeGroups)) {\n throw new UnauthorizedException('ContentType', 'create');\n }\n\n // Prevent argument mutation\n $contentTypeCreateStruct = clone $contentTypeCreateStruct;\n $this->validateInputContentTypeCreateStruct($contentTypeCreateStruct);\n $this->validateInputContentTypeGroups($contentTypeGroups);\n $initialLanguageId = $this->repository->getContentLanguageService()->loadLanguage(\n $contentTypeCreateStruct->mainLanguageCode\n )->id;\n\n try {\n $this->contentTypeHandler->loadByIdentifier(\n $contentTypeCreateStruct->identifier\n );\n\n throw new InvalidArgumentException(\n '$contentTypeCreateStruct',\n \"Another content type with identifier '{$contentTypeCreateStruct->identifier}' exists\"\n );\n } catch (APINotFoundException $e) {\n // Do nothing\n }\n\n if ($contentTypeCreateStruct->remoteId !== null) {\n try {\n $this->contentTypeHandler->loadByRemoteId(\n $contentTypeCreateStruct->remoteId\n );\n\n throw new InvalidArgumentException(\n '$contentTypeCreateStruct',\n \"Another content type with remoteId '{$contentTypeCreateStruct->remoteId}' exists\"\n );\n } catch (APINotFoundException $e) {\n // Do nothing\n }\n }\n\n $fieldDefinitionIdentifierSet = [];\n $fieldDefinitionPositionSet = [];\n foreach ($contentTypeCreateStruct->fieldDefinitions as $fieldDefinitionCreateStruct) {\n // Check for duplicate identifiers\n if (!isset($fieldDefinitionIdentifierSet[$fieldDefinitionCreateStruct->identifier])) {\n $fieldDefinitionIdentifierSet[$fieldDefinitionCreateStruct->identifier] = true;\n } else {\n throw new InvalidArgumentException(\n '$contentTypeCreateStruct',\n \"The argument contains duplicate Field definition identifier '{$fieldDefinitionCreateStruct->identifier}'\"\n );\n }\n\n // Check for duplicate positions\n if (!isset($fieldDefinitionPositionSet[$fieldDefinitionCreateStruct->position])) {\n $fieldDefinitionPositionSet[$fieldDefinitionCreateStruct->position] = true;\n } else {\n throw new InvalidArgumentException(\n '$contentTypeCreateStruct',\n \"The argument contains duplicate Field definition position '{$fieldDefinitionCreateStruct->position}'\"\n );\n }\n }\n\n $allValidationErrors = [];\n $spiFieldDefinitions = [];\n $fieldTypeIdentifierSet = [];\n foreach ($contentTypeCreateStruct->fieldDefinitions as $fieldDefinitionCreateStruct) {\n /** @var $fieldType \\Ibexa\\Contracts\\Core\\FieldType\\FieldType */\n $fieldType = $this->fieldTypeRegistry->getFieldType(\n $fieldDefinitionCreateStruct->fieldTypeIdentifier\n );\n\n if ($fieldType->isSingular() && isset($fieldTypeIdentifierSet[$fieldDefinitionCreateStruct->fieldTypeIdentifier])) {\n throw new ContentTypeValidationException(\n \"Field Type '%identifier%' is singular and cannot be used more than once in a content type\",\n ['%identifier%' => $fieldDefinitionCreateStruct->fieldTypeIdentifier]\n );\n }\n\n $fieldTypeIdentifierSet[$fieldDefinitionCreateStruct->fieldTypeIdentifier] = true;\n\n $fieldType->applyDefaultSettings($fieldDefinitionCreateStruct->fieldSettings);\n $fieldType->applyDefaultValidatorConfiguration($fieldDefinitionCreateStruct->validatorConfiguration);\n $validationErrors = $this->validateFieldDefinitionCreateStruct(\n $fieldDefinitionCreateStruct,\n $fieldType\n );\n\n if (!empty($validationErrors)) {\n $allValidationErrors[$fieldDefinitionCreateStruct->identifier] = $validationErrors;\n }\n\n if (!empty($allValidationErrors)) {\n continue;\n }\n\n $spiFieldDefinitions[] = $this->contentTypeDomainMapper->buildSPIFieldDefinitionFromCreateStruct(\n $fieldDefinitionCreateStruct,\n $fieldType,\n $contentTypeCreateStruct->mainLanguageCode\n );\n }\n\n if (!empty($allValidationErrors)) {\n throw new ContentTypeFieldDefinitionValidationException($allValidationErrors);\n }\n\n $groupIds = array_map(\n static function (APIContentTypeGroup $contentTypeGroup) {\n return $contentTypeGroup->id;\n },\n $contentTypeGroups\n );\n\n if ($contentTypeCreateStruct->creatorId === null) {\n $contentTypeCreateStruct->creatorId = $this->permissionResolver->getCurrentUserReference()->getUserId();\n }\n\n if ($contentTypeCreateStruct->creationDate === null) {\n $timestamp = time();\n } else {\n $timestamp = $contentTypeCreateStruct->creationDate->getTimestamp();\n }\n\n if ($contentTypeCreateStruct->remoteId === null) {\n $contentTypeCreateStruct->remoteId = $this->contentDomainMapper->getUniqueHash($contentTypeCreateStruct);\n }\n\n $spiContentTypeCreateStruct = new SPIContentTypeCreateStruct(\n [\n 'identifier' => $contentTypeCreateStruct->identifier,\n 'name' => $contentTypeCreateStruct->names,\n 'status' => APIContentType::STATUS_DRAFT,\n 'description' => $contentTypeCreateStruct->descriptions ?? [],\n 'created' => $timestamp,\n 'modified' => $timestamp,\n 'creatorId' => $contentTypeCreateStruct->creatorId,\n 'modifierId' => $contentTypeCreateStruct->creatorId,\n 'remoteId' => $contentTypeCreateStruct->remoteId,\n 'urlAliasSchema' => $contentTypeCreateStruct->urlAliasSchema ?? '',\n 'nameSchema' => $contentTypeCreateStruct->nameSchema ?? '',\n 'isContainer' => $contentTypeCreateStruct->isContainer ?? false,\n 'initialLanguageId' => $initialLanguageId,\n 'sortField' => $contentTypeCreateStruct->defaultSortField ?? Location::SORT_FIELD_PUBLISHED,\n 'sortOrder' => $contentTypeCreateStruct->defaultSortOrder ?? Location::SORT_ORDER_DESC,\n 'groupIds' => $groupIds,\n 'fieldDefinitions' => $spiFieldDefinitions,\n 'defaultAlwaysAvailable' => $contentTypeCreateStruct->defaultAlwaysAvailable,\n ]\n );\n\n $this->repository->beginTransaction();\n try {\n $spiContentType = $this->contentTypeHandler->create(\n $spiContentTypeCreateStruct\n );\n $this->repository->commit();\n } catch (Exception $e) {\n $this->repository->rollback();\n throw $e;\n }\n\n return $this->contentTypeDomainMapper->buildContentTypeDraftDomainObject($spiContentType);\n }", "smellKey": "S3776", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public static function getReports(): array\n {\n /**\n * @var array $CFG_GLPI\n * @var array $PLUGIN_HOOKS\n */\n global $CFG_GLPI, $PLUGIN_HOOKS;\n\n // Report generation\n // Default Report included\n $report_list = [];\n $report_list[\"default\"][\"name\"] = __('Default report');\n $report_list[\"default\"][\"file\"] = \"/front/report.default.php\";\n\n if (Contract::canView()) {\n $report_list[\"Contrats\"][\"name\"] = __('By contract');\n $report_list[\"Contrats\"][\"file\"] = \"/front/report.contract.php\";\n }\n if (Infocom::canView()) {\n $report_list[\"Par_annee\"][\"name\"] = __('By year');\n $report_list[\"Par_annee\"][\"file\"] = \"/front/report.year.php\";\n $report_list[\"Infocoms\"][\"name\"] = __('Hardware financial and administrative information');\n $report_list[\"Infocoms\"][\"file\"] = \"/front/report.infocom.php\";\n $report_list[\"Infocoms2\"][\"name\"] = __('Other financial and administrative information (licenses, cartridges, consumables)');\n $report_list[\"Infocoms2\"][\"file\"] = \"/front/report.infocom.conso.php\";\n }\n if (Session::haveRight(\"networking\", READ)) {\n // Network socket report\n $report_list[\"Rapport prises reseau\"][\"name\"] = __('Network report');\n $report_list[\"Rapport prises reseau\"][\"file\"] = \"/front/report.networking.php\";\n }\n if (Session::haveRight(\"reservation\", READ)) {\n $report_list[\"reservation\"][\"name\"] = __('Loan');\n $report_list[\"reservation\"][\"file\"] = \"/front/report.reservation.php\";\n }\n //TODO This should probably check all state_types\n if (\n Computer::canView()\n || Monitor::canView()\n || Session::haveRight(\"networking\", READ)\n || Peripheral::canView()\n || Printer::canView()\n || Phone::canView()\n ) {\n $report_list[\"state\"][\"name\"] = __('Status');\n $report_list[\"state\"][\"file\"] = \"/front/report.state.php\";\n }\n\n // Handle reports from plugins\n if (isset($PLUGIN_HOOKS[\"reports\"]) && is_array($PLUGIN_HOOKS[\"reports\"])) {\n foreach ($PLUGIN_HOOKS[\"reports\"] as $plug => $pages) {\n if (!Plugin::isPluginActive($plug)) {\n continue;\n }\n if (is_array($pages) && count($pages)) {\n foreach ($pages as $page => $name) {\n $report_list[Plugin::getInfo($plug, 'name')][$page] = [\n 'name' => $name,\n 'file' => \"{$CFG_GLPI['root_doc']}/plugins/{$plug}/{$page}\",\n 'plug' => $plug\n ];\n }\n }\n }\n }\n\n return $report_list;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function parseValidators($source): array\n {\n $rtn = ['fname' => '', 'lname' => '', 'DOB' => '', 'sex' => ''];\n $val = [\n 'fname' => [\"First Name\", \"first\", \"Patient.name\", \"Patient.given\"],\n 'lname' => [\"Last Name\", \"last\", \"Patient.name\", \"Patient.family\"],\n 'DOB' => [\"dob\", \"Date of Birth\", \"Birth\", \"Birthdate\", \"Patient.birthDate\"],\n 'sex' => [\"gender\", \"sex\", \"male\", \"female\", \"Sexual Orientation\", \"Patient.gender\"]\n ];\n\n foreach ($source as $src) {\n foreach ($val as $k => $v) {\n foreach ($v as $s) {\n if (stripos($src->Name, $s) !== false) {\n if ($k == \"sex\") {\n $src->Text = ucfirst($src->Text);\n $src->Text = stripos($src->Name, 'Male') !== false ? 'Male' : (stripos($src->Name, 'Female') !== false ? 'Female' : ($src->Text == 'M' ? 'Male' : ($src->Text == 'F' ? 'Female' : $src->Text)));\n }\n $rtn[$k] = $src->Text;\n }\n }\n }\n }\n\n return $rtn;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function cronCleanoldagents($task = null)\n {\n /**\n * @var \\DBmysql $DB\n * @var array $PLUGIN_HOOKS\n */\n global $DB, $PLUGIN_HOOKS;\n\n $config = \\Config::getConfigurationValues('inventory');\n\n $retention_time = $config['stale_agents_delay'] ?? 0;\n if ($retention_time <= 0) {\n return 0;\n }\n\n $total = 0;\n $errors = 0;\n\n $iterator = $DB->request([\n 'SELECT' => ['id'],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'last_contact' => ['<',\n QueryFunction::dateSub(\n date: QueryFunction::now(),\n interval: $retention_time,\n interval_unit: 'DAY'\n )\n ]\n ]\n ]);\n\n foreach ($iterator as $data) {\n $agent = new self();\n if (!$agent->getFromDB($data['id'])) {\n $errors++;\n continue;\n }\n\n $item = is_a($agent->fields['itemtype'], CommonDBTM::class, true) ? new $agent->fields['itemtype']() : null;\n if (\n $item !== null\n && (\n $item->getFromDB($agent->fields['items_id']) === false\n || $item->fields['is_dynamic'] != 1\n )\n ) {\n $item = null;\n }\n\n $actions = importArrayFromDB($config['stale_agents_action']);\n foreach ($actions as $action) {\n switch ($action) {\n case Conf::STALE_AGENT_ACTION_CLEAN:\n //delete agents\n if ($agent->delete($data)) {\n $task->addVolume(1);\n $total++;\n } else {\n $errors++;\n }\n break;\n case Conf::STALE_AGENT_ACTION_STATUS:\n if (isset($config['stale_agents_status']) && $item !== null) {\n $should_update = false;\n if (\n isset($config['stale_agents_status_condition'])\n && $config['stale_agents_status_condition'] != json_encode(['all']) // all status\n ) {\n $old_state_list = json_decode($config['stale_agents_status_condition']);\n if (in_array($item->fields['states_id'], $old_state_list)) {\n $should_update = true;\n }\n } else {\n $should_update = true;\n }\n if ($should_update) {\n //change status of agents linked assets\n $input = [\n 'id' => $item->fields['id'],\n 'states_id' => $config['stale_agents_status'],\n 'is_dynamic' => 1\n ];\n if ($item->update($input)) {\n $task->addVolume(1);\n $total++;\n } else {\n $errors++;\n }\n }\n }\n break;\n case Conf::STALE_AGENT_ACTION_TRASHBIN:\n //put linked assets in trashbin\n if ($item !== null) {\n if ($item->delete(['id' => $item->fields['id']])) {\n $task->addVolume(1);\n $total++;\n } else {\n $errors++;\n }\n }\n break;\n }\n }\n\n $plugin_actions = $PLUGIN_HOOKS[Hooks::STALE_AGENT_CONFIG] ?? [];\n /**\n * @var string $plugin\n * @phpstan-var array{label: string, item_action: boolean, render_callback: callable, action_callback: callable}[] $actions\n */\n foreach ($plugin_actions as $plugin => $actions) {\n if (is_array($actions) && Plugin::isPluginActive($plugin)) {\n foreach ($actions as $action) {\n if (!is_callable($action['action_callback'] ?? null)) {\n trigger_error(\n sprintf('Invalid plugin \"%s\" action callback for \"%s\" hook.', $plugin, Hooks::STALE_AGENT_CONFIG),\n E_USER_WARNING\n );\n continue;\n }\n // Run the action\n if ($action['action_callback']($agent, $config, $item)) {\n $task->addVolume(1);\n $total++;\n } else {\n $errors++;\n }\n }\n }\n }\n }\n\n return $errors > 0 ? -1 : ($total > 0 ? 1 : 0);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "#[Route('/edit-infos', name: 'back_profil_edit_infos', methods: ['POST'])]\n #[IsGranted('ROLE_USER_PARTNER')]\n public function editInfos(\n Request $request,\n ManagerRegistry $doctrine,\n ValidatorInterface $validator,\n UploadHandlerService $uploadHandlerService,\n LoggerInterface $logger,\n ImageManipulationHandler $imageManipulationHandler,\n FileScanner $fileScanner\n ): Response {\n $payload = $request->getPayload()->all();\n /** @var User $user */\n $user = $this->getUser();\n if ($this->isCsrfTokenValid(\n 'profil_edit_infos',\n $payload['_token']\n )) {\n $avatarFile = $request->files->get('profil_edit_infos')['avatar'] ?? null;\n $errorMessage = [];\n if (empty($payload['profil_edit_infos']['prenom'])) {\n $errorMessage['errors']['profil_edit_infos[prenom]']['errors'][] = 'Le pr\u00e9nom ne peut pas \u00eatre vide';\n } elseif (strlen($payload['profil_edit_infos']['prenom']) > 255) {\n $errorMessage['errors']['profil_edit_infos[prenom]']['errors'][] = 'Le pr\u00e9nom ne doit pas d\u00e9passer 255 caract\u00e8res';\n }\n if (empty($payload['profil_edit_infos']['nom'])) {\n $errorMessage['errors']['profil_edit_infos[nom]']['errors'][] = 'Le nom ne peut pas \u00eatre vide';\n } elseif (strlen($payload['profil_edit_infos']['nom']) > 255) {\n $errorMessage['errors']['profil_edit_infos[nom]']['errors'][] = 'Le nom ne doit pas d\u00e9passer 255 caract\u00e8res';\n }\n // Validation du fichier avatar\n if (empty($errorMessage) && $avatarFile instanceof UploadedFile) {\n $errors = $validator->validate(\n $avatarFile,\n [\n new Assert\\Image([\n 'maxSize' => '5M',\n 'mimeTypes' => ['image/jpeg', 'image/png', 'image/gif'],\n 'mimeTypesMessage' => 'Veuillez t\u00e9l\u00e9charger une image valide (JPEG, PNG ou GIF)',\n 'maxSizeMessage' => 'La taille du fichier ne doit pas d\u00e9passer 5 Mo.',\n ]),\n ]\n );\n if (count($errors) > 0) {\n foreach ($errors as $error) {\n $errorMessage['errors']['profil_edit_infos[avatar]']['errors'][] = $error->getMessage();\n }\n } elseif (!$fileScanner->isClean($avatarFile->getPathname())) {\n $errorMessage['errors']['profil_edit_infos[avatar]']['errors'][] = 'Le fichier est infect\u00e9';\n } else {\n try {\n $res = $uploadHandlerService->toTempFolder($avatarFile, 'avatar');\n\n if (\\is_array($res) && isset($res['error'])) {\n throw new \\Exception($res['error']);\n }\n $res = $uploadHandlerService->setKey('avatar');\n\n if (\\in_array($avatarFile->getMimeType(), File::IMAGE_MIME_TYPES)) {\n $imageManipulationHandler->avatar($res['filePath']);\n $uploadHandlerService->moveFilePath($res['filePath']);\n }\n\n if ($user->getAvatarFilename()) {\n $uploadHandlerService->deleteSingleFile($user->getAvatarFilename());\n }\n\n $user->setAvatarFilename($res['file']);\n } catch (FileException $e) {\n $logger->error($e->getMessage());\n $errorMessage['errors']['profil_edit_infos[avatar]']['errors'][] = '\u00c9chec du t\u00e9l\u00e9chargement de l\\'avatar.';\n }\n }\n }\n\n if (empty($errorMessage)) {\n $response = ['code' => Response::HTTP_OK];\n $user->setPrenom($payload['profil_edit_infos']['prenom']);\n $user->setNom($payload['profil_edit_infos']['nom']);\n $doctrine->getManager()->persist($user);\n $doctrine->getManager()->flush();\n $this->addFlash('success', 'Les informations de votre profil ont bien \u00e9t\u00e9 modifi\u00e9es.');\n } else {\n $response = ['code' => Response::HTTP_BAD_REQUEST];\n $response = [...$response, ...$errorMessage];\n }\n } else {\n $response = [\n 'code' => Response::HTTP_UNAUTHORIZED,\n 'message' => self::ERROR_MSG,\n ];\n }\n\n return $this->json($response, $response['code']);\n }", "smellKey": "S3776", "smellId": null, "repo": "MTES-MCT_histologe", "language": "php"} {"function": "private function getTransactionMeta(RecurrenceTransaction $transaction, array $array): array\n {\n app('log')->debug(sprintf('Now in %s', __METHOD__));\n $array['tags'] = [];\n $array['category_id'] = null;\n $array['category_name'] = null;\n $array['budget_id'] = null;\n $array['budget_name'] = null;\n $array['piggy_bank_id'] = null;\n $array['piggy_bank_name'] = null;\n $array['bill_id'] = null;\n $array['bill_name'] = null;\n\n /** @var RecurrenceTransactionMeta $transactionMeta */\n foreach ($transaction->recurrenceTransactionMeta as $transactionMeta) {\n switch ($transactionMeta->name) {\n default:\n throw new FireflyException(sprintf('Recurrence transformer cant handle field \"%s\"', $transactionMeta->name));\n\n case 'bill_id':\n $bill = $this->billRepos->find((int)$transactionMeta->value);\n if (null !== $bill) {\n $array['bill_id'] = (string)$bill->id;\n $array['bill_name'] = $bill->name;\n }\n\n break;\n\n case 'tags':\n $array['tags'] = json_decode($transactionMeta->value);\n\n break;\n\n case 'piggy_bank_id':\n $piggy = $this->piggyRepos->find((int)$transactionMeta->value);\n if (null !== $piggy) {\n $array['piggy_bank_id'] = (string)$piggy->id;\n $array['piggy_bank_name'] = $piggy->name;\n }\n\n break;\n\n case 'category_id':\n $category = $this->factory->findOrCreate((int)$transactionMeta->value, null);\n if (null !== $category) {\n $array['category_id'] = (string)$category->id;\n $array['category_name'] = $category->name;\n }\n\n break;\n\n case 'category_name':\n $category = $this->factory->findOrCreate(null, $transactionMeta->value);\n if (null !== $category) {\n $array['category_id'] = (string)$category->id;\n $array['category_name'] = $category->name;\n }\n\n break;\n\n case 'budget_id':\n $budget = $this->budgetRepos->find((int)$transactionMeta->value);\n if (null !== $budget) {\n $array['budget_id'] = (string)$budget->id;\n $array['budget_name'] = $budget->name;\n }\n\n break;\n }\n }\n\n return $array;\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public static function cronInfocom($task = null)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n if (!$CFG_GLPI[\"use_notifications\"]) {\n return 0;\n }\n\n $message = [];\n $cron_status = 0;\n $items_infos = [];\n $items_messages = [];\n\n foreach (Entity::getEntitiesToNotify('use_infocoms_alert') as $entity => $value) {\n $before = Entity::getUsedConfig('send_infocoms_alert_before_delay', $entity);\n $table = self::getTable();\n $iterator = $DB->request([\n 'SELECT' => \"$table.*\",\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_alerts' => [\n 'ON' => [\n 'glpi_alerts' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'glpi_alerts.itemtype' => self::getType(),\n 'glpi_alerts.type' => Alert::END\n ]\n ]\n ]\n ]\n ],\n 'WHERE' => [\n new QueryExpression(\n '(' . $DB->quoteName('glpi_infocoms.alert') . ' & ' . pow(2, Alert::END) . ') > 0'\n ),\n \"$table.entities_id\" => $entity,\n \"$table.warranty_duration\" => ['>', 0],\n 'NOT' => [\"$table.warranty_date\" => null],\n new QueryExpression(QueryFunction::dateDiff(\n expression1: QueryFunction::dateAdd(\n date: 'glpi_infocoms.warranty_date',\n interval: new QueryExpression($DB::quoteName('glpi_infocoms.warranty_duration')),\n interval_unit: 'MONTH'\n ),\n expression2: QueryFunction::curdate()\n ) . ' <= ' . $DB::quoteValue($before)),\n 'glpi_alerts.date' => null\n ]\n ]);\n\n foreach ($iterator as $data) {\n if ($item_infocom = getItemForItemtype($data[\"itemtype\"])) {\n if ($item_infocom->getFromDB($data[\"items_id\"])) {\n $entity = $data['entities_id'];\n $warranty = self::getWarrantyExpir($data[\"warranty_date\"], $data[\"warranty_duration\"]);\n //TRANS: %1$s is a type, %2$s is a name (used in croninfocom)\n $name = sprintf(\n __('%1$s - %2$s'),\n $item_infocom->getTypeName(1),\n $item_infocom->getName()\n );\n //TRANS: %1$s is the warranty end date and %2$s the name of the item\n $message = sprintf(\n __('Item reaching the end of warranty on %1$s: %2$s'),\n $warranty,\n $name\n ) . \"<br>\";\n\n $data['warrantyexpiration'] = $warranty;\n $data['item_name'] = $item_infocom->getName();\n $items_infos[$entity][$data['id']] = $data;\n\n if (!isset($items_messages[$entity])) {\n $items_messages[$entity] = __('No item reaching the end of warranty.') . \"<br>\";\n }\n $items_messages[$entity] .= $message;\n }\n }\n }\n }\n\n foreach ($items_infos as $entity => $items) {\n if (\n NotificationEvent::raiseEvent(\"alert\", new self(), ['entities_id' => $entity,\n 'items' => $items\n ])\n ) {\n $message = $items_messages[$entity];\n $cron_status = 1;\n if ($task) {\n $task->log(sprintf(\n __('%1$s: %2$s') . \"\\n\",\n Dropdown::getDropdownName(\"glpi_entities\", $entity),\n $message\n ));\n $task->addVolume(1);\n } else {\n Session::addMessageAfterRedirect(htmlescape(sprintf(\n __('%1$s: %2$s'),\n Dropdown::getDropdownName(\n \"glpi_entities\",\n $entity\n ),\n $message\n )));\n }\n\n $alert = new Alert();\n $input[\"itemtype\"] = 'Infocom';\n $input[\"type\"] = Alert::END;\n foreach ($items as $id => $item) {\n $input[\"items_id\"] = $id;\n $alert->add($input);\n unset($alert->fields['id']);\n }\n } else {\n $entityname = Dropdown::getDropdownName('glpi_entities', $entity);\n //TRANS: %s is entity name\n $msg = sprintf(__('%1$s: %2$s'), $entityname, __('send infocom alert failed'));\n if ($task) {\n $task->log($msg);\n } else {\n Session::addMessageAfterRedirect(htmlescape($msg), false, ERROR);\n }\n }\n }\n return $cron_status;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['priority'])) {\n $this->setPriority($data['priority']);\n }\n if (isset($data['purpose'])) {\n if (is_array($data['purpose'])) {\n foreach ($data['purpose'] as $d) {\n $this->addPurpose($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"purpose\" must be array of objects or null, ' . gettype($data['purpose']) . ' seen.');\n }\n }\n if (isset($data['patient'])) {\n $this->setPatient($data['patient']);\n }\n if (isset($data['servicedDate'])) {\n $this->setServicedDate($data['servicedDate']);\n }\n if (isset($data['servicedPeriod'])) {\n $this->setServicedPeriod($data['servicedPeriod']);\n }\n if (isset($data['created'])) {\n $this->setCreated($data['created']);\n }\n if (isset($data['enterer'])) {\n $this->setEnterer($data['enterer']);\n }\n if (isset($data['provider'])) {\n $this->setProvider($data['provider']);\n }\n if (isset($data['insurer'])) {\n $this->setInsurer($data['insurer']);\n }\n if (isset($data['facility'])) {\n $this->setFacility($data['facility']);\n }\n if (isset($data['supportingInfo'])) {\n if (is_array($data['supportingInfo'])) {\n foreach ($data['supportingInfo'] as $d) {\n $this->addSupportingInfo($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"supportingInfo\" must be array of objects or null, ' . gettype($data['supportingInfo']) . ' seen.');\n }\n }\n if (isset($data['insurance'])) {\n if (is_array($data['insurance'])) {\n foreach ($data['insurance'] as $d) {\n $this->addInsurance($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"insurance\" must be array of objects or null, ' . gettype($data['insurance']) . ' seen.');\n }\n }\n if (isset($data['item'])) {\n if (is_array($data['item'])) {\n foreach ($data['item'] as $d) {\n $this->addItem($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"item\" must be array of objects or null, ' . gettype($data['item']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function start(callable $callback = null, array $env = [])\n {\n if ($this->isRunning()) {\n throw new RuntimeException('Process is already running.');\n }\n\n $this->resetProcessData();\n $this->starttime = $this->lastOutputTime = microtime(true);\n $this->callback = $this->buildCallback($callback);\n $this->hasCallback = null !== $callback;\n $descriptors = $this->getDescriptors();\n\n if ($this->env) {\n $env += '\\\\' === \\DIRECTORY_SEPARATOR ? array_diff_ukey($this->env, $env, 'strcasecmp') : $this->env;\n }\n\n $env += '\\\\' === \\DIRECTORY_SEPARATOR ? array_diff_ukey($this->getDefaultEnv(), $env, 'strcasecmp') : $this->getDefaultEnv();\n\n if (\\is_array($commandline = $this->commandline)) {\n $commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline));\n\n if ('\\\\' !== \\DIRECTORY_SEPARATOR) {\n // exec is mandatory to deal with sending a signal to the process\n $commandline = 'exec '.$commandline;\n }\n } else {\n $commandline = $this->replacePlaceholders($commandline, $env);\n }\n\n if ('\\\\' === \\DIRECTORY_SEPARATOR) {\n $commandline = $this->prepareWindowsCommandLine($commandline, $env);\n } elseif (!$this->useFileHandles && $this->isSigchildEnabled()) {\n // last exit code is output on the fourth pipe and caught to work around --enable-sigchild\n $descriptors[3] = ['pipe', 'w'];\n\n // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input\n $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';\n $commandline .= 'pid=$!; echo $pid >&3; wait $pid 2>/dev/null; code=$?; echo $code >&3; exit $code';\n\n // Workaround for the bug, when PTS functionality is enabled.\n // @see : https://bugs.php.net/69442\n $ptsWorkaround = fopen(__FILE__, 'r');\n }\n\n $envPairs = [];\n foreach ($env as $k => $v) {\n if (false !== $v && false === \\in_array($k, ['argc', 'argv', 'ARGC', 'ARGV'], true)) {\n $envPairs[] = $k.'='.$v;\n }\n }\n\n if (!is_dir($this->cwd)) {\n throw new RuntimeException(sprintf('The provided cwd \"%s\" does not exist.', $this->cwd));\n }\n\n $this->process = @proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options);\n\n if (!\\is_resource($this->process)) {\n throw new RuntimeException('Unable to launch a new process.');\n }\n $this->status = self::STATUS_STARTED;\n\n if (isset($descriptors[3])) {\n $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);\n }\n\n if ($this->tty) {\n return;\n }\n\n $this->updateStatus(false);\n $this->checkTimeout();\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function privAddFile($p_filedescr, &$p_header, &$p_options)\n {\n $v_result=1;\n\n // ----- Working variable\n $p_filename = $p_filedescr['filename'];\n\n // TBC : Already done in the fileAtt check ... ?\n if ($p_filename == \"\") {\n // ----- Error log\n PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, \"Invalid file list parameter (invalid or empty list)\");\n\n // ----- Return\n return PclZip::errorCode();\n }\n\n // ----- Look for a stored different filename\n /* TBC : Removed\n if (isset($p_filedescr['stored_filename'])) {\n $v_stored_filename = $p_filedescr['stored_filename'];\n }\n else {\n $v_stored_filename = $p_filedescr['stored_filename'];\n }\n */\n\n // ----- Set the file properties\n clearstatcache();\n $p_header['version'] = 20;\n $p_header['version_extracted'] = 10;\n $p_header['flag'] = 0;\n $p_header['compression'] = 0;\n $p_header['crc'] = 0;\n $p_header['compressed_size'] = 0;\n $p_header['filename_len'] = strlen($p_filename);\n $p_header['extra_len'] = 0;\n $p_header['disk'] = 0;\n $p_header['internal'] = 0;\n $p_header['offset'] = 0;\n $p_header['filename'] = $p_filename;\n // TBC : Removed $p_header['stored_filename'] = $v_stored_filename;\n $p_header['stored_filename'] = $p_filedescr['stored_filename'];\n $p_header['extra'] = '';\n $p_header['status'] = 'ok';\n $p_header['index'] = -1;\n\n // ----- Look for regular file\n if ($p_filedescr['type']=='file') {\n $p_header['external'] = 0x00000000;\n $p_header['size'] = filesize($p_filename);\n } elseif ($p_filedescr['type']=='folder') {\n // ----- Look for regular folder\n $p_header['external'] = 0x00000010;\n $p_header['mtime'] = filemtime($p_filename);\n $p_header['size'] = filesize($p_filename);\n } elseif ($p_filedescr['type'] == 'virtual_file') {\n // ----- Look for virtual file\n $p_header['external'] = 0x00000000;\n $p_header['size'] = strlen($p_filedescr['content']);\n }\n\n // ----- Look for filetime\n if (isset($p_filedescr['mtime'])) {\n $p_header['mtime'] = $p_filedescr['mtime'];\n } elseif ($p_filedescr['type'] == 'virtual_file') {\n $p_header['mtime'] = time();\n } else {\n $p_header['mtime'] = filemtime($p_filename);\n }\n\n // ------ Look for file comment\n if (isset($p_filedescr['comment'])) {\n $p_header['comment_len'] = strlen($p_filedescr['comment']);\n $p_header['comment'] = $p_filedescr['comment'];\n } else {\n $p_header['comment_len'] = 0;\n $p_header['comment'] = '';\n }\n\n // ----- Look for pre-add callback\n if (isset($p_options[PCLZIP_CB_PRE_ADD])) {\n // ----- Generate a local information\n $v_local_header = array();\n $this->privConvertHeader2FileInfo($p_header, $v_local_header);\n\n // ----- Call the callback\n // Here I do not use call_user_func() because I need to send a reference to the\n // header.\n // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');\n $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);\n if ($v_result == 0) {\n // ----- Change the file status\n $p_header['status'] = \"skipped\";\n $v_result = 1;\n }\n\n // ----- Update the informations\n // Only some fields can be modified\n if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {\n $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);\n }\n }\n\n // ----- Look for empty stored filename\n if ($p_header['stored_filename'] == \"\") {\n $p_header['status'] = \"filtered\";\n }\n\n // ----- Check the path length\n if (strlen($p_header['stored_filename']) > 0xFF) {\n $p_header['status'] = 'filename_too_long';\n }\n\n // ----- Look if no error, or file not skipped\n if ($p_header['status'] == 'ok') {\n // ----- Look for a file\n if ($p_filedescr['type'] == 'file') {\n // ----- Look for using temporary file to zip\n if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])))) {\n $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);\n if ($v_result < PCLZIP_ERR_NO_ERROR) {\n return $v_result;\n }\n } else {\n // ----- Use \"in memory\" zip algo\n // ----- Open the source file\n if (($v_file = @fopen($p_filename, \"rb\")) == 0) {\n PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, \"Unable to open file '$p_filename' in binary read mode\");\n return PclZip::errorCode();\n }\n\n // ----- Read the file content\n $v_content = @fread($v_file, $p_header['size']);\n\n // ----- Close the file\n @fclose($v_file);\n\n // ----- Calculate the CRC\n $p_header['crc'] = @crc32($v_content);\n\n // ----- Look for no compression\n if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {\n // ----- Set header parameters\n $p_header['compressed_size'] = $p_header['size'];\n $p_header['compression'] = 0;\n } else {\n // ----- Look for normal compression\n // ----- Compress the content\n $v_content = @gzdeflate($v_content);\n\n // ----- Set header parameters\n $p_header['compressed_size'] = strlen($v_content);\n $p_header['compression'] = 8;\n }\n\n // ----- Call the header generation\n if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {\n @fclose($v_file);\n return $v_result;\n }\n\n // ----- Write the compressed (or not) content\n @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);\n }\n } elseif ($p_filedescr['type'] == 'virtual_file') {\n // ----- Look for a virtual file (a file from string)\n $v_content = $p_filedescr['content'];\n\n // ----- Calculate the CRC\n $p_header['crc'] = @crc32($v_content);\n\n // ----- Look for no compression\n if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {\n // ----- Set header parameters\n $p_header['compressed_size'] = $p_header['size'];\n $p_header['compression'] = 0;\n } else {\n // ----- Look for normal compression\n // ----- Compress the content\n $v_content = @gzdeflate($v_content);\n\n // ----- Set header parameters\n $p_header['compressed_size'] = strlen($v_content);\n $p_header['compression'] = 8;\n }\n\n // ----- Call the header generation\n if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {\n @fclose($v_file);\n return $v_result;\n }\n\n // ----- Write the compressed (or not) content\n @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);\n } elseif ($p_filedescr['type'] == 'folder') {\n // ----- Look for a directory\n // ----- Look for directory last '/'\n if (@substr($p_header['stored_filename'], -1) != '/') {\n $p_header['stored_filename'] .= '/';\n }\n\n // ----- Set the file properties\n $p_header['size'] = 0;\n //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked\n $p_header['external'] = 0x00000010; // Value for a folder : to be checked\n\n // ----- Call the header generation\n if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {\n return $v_result;\n }\n }\n }\n\n // ----- Look for post-add callback\n if (isset($p_options[PCLZIP_CB_POST_ADD])) {\n // ----- Generate a local information\n $v_local_header = array();\n $this->privConvertHeader2FileInfo($p_header, $v_local_header);\n\n // ----- Call the callback\n // Here I do not use call_user_func() because I need to send a reference to the\n // header.\n // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');\n $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);\n if ($v_result == 0) {\n // ----- Ignored\n $v_result = 1;\n }\n\n // ----- Update the informations\n // Nothing can be modified\n }\n\n // ----- Return\n return $v_result;\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function pagination($total_products = null)\n {\n if (!self::$initialized) {\n $this->init();\n } elseif (!$this->context) {\n $this->context = Context::getContext();\n }\n\n // Retrieve the default number of products per page and the other available selections\n $default_products_per_page = max(1, (int)Configuration::get('PS_PRODUCTS_PER_PAGE'));\n $n_array = array($default_products_per_page, $default_products_per_page * 2, $default_products_per_page * 5);\n\n if ((int)Tools::getValue('n') && (int)$total_products > 0) {\n $n_array[] = $total_products;\n }\n // Retrieve the current number of products per page (either the default, the GET parameter or the one in the cookie)\n $this->n = $default_products_per_page;\n if (isset($this->context->cookie->nb_item_per_page) && in_array($this->context->cookie->nb_item_per_page, $n_array)) {\n $this->n = (int)$this->context->cookie->nb_item_per_page;\n }\n\n if ((int)Tools::getValue('n') && in_array((int)Tools::getValue('n'), $n_array)) {\n $this->n = (int)Tools::getValue('n');\n }\n\n // Retrieve the page number (either the GET parameter or the first page)\n $this->p = (int)Tools::getValue('p', 1);\n // If the parameter is not correct then redirect (do not merge with the previous line, the redirect is required in order to avoid duplicate content)\n if (!is_numeric($this->p) || $this->p < 1) {\n Tools::redirect($this->context->link->getPaginationLink(false, false, $this->n, false, 1, false));\n }\n\n // Remove the page parameter in order to get a clean URL for the pagination template\n $current_url = preg_replace('/(?:(\\?)|&amp;)p=\\d+/', '$1', Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']));\n\n if ($this->n != $default_products_per_page || isset($this->context->cookie->nb_item_per_page)) {\n $this->context->cookie->nb_item_per_page = $this->n;\n }\n\n $pages_nb = ceil($total_products / (int)$this->n);\n if ($this->p > $pages_nb && $total_products != 0) {\n Tools::redirect($this->context->link->getPaginationLink(false, false, $this->n, false, $pages_nb, false));\n }\n\n $range = 2; /* how many pages around page selected */\n $start = (int)($this->p - $range);\n if ($start < 1) {\n $start = 1;\n }\n\n $stop = (int)($this->p + $range);\n if ($stop > $pages_nb) {\n $stop = (int)$pages_nb;\n }\n\n $this->context->smarty->assign(array(\n 'nb_products' => $total_products,\n 'products_per_page' => $this->n,\n 'pages_nb' => $pages_nb,\n 'p' => $this->p,\n 'n' => $this->n,\n 'nArray' => $n_array,\n 'range' => $range,\n 'start' => $start,\n 'stop' => $stop,\n 'current_url' => $current_url,\n ));\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['created'])) {\n $this->setCreated($data['created']);\n }\n if (isset($data['patient'])) {\n $this->setPatient($data['patient']);\n }\n if (isset($data['encounter'])) {\n $this->setEncounter($data['encounter']);\n }\n if (isset($data['dateWritten'])) {\n $this->setDateWritten($data['dateWritten']);\n }\n if (isset($data['prescriber'])) {\n $this->setPrescriber($data['prescriber']);\n }\n if (isset($data['lensSpecification'])) {\n if (is_array($data['lensSpecification'])) {\n foreach ($data['lensSpecification'] as $d) {\n $this->addLensSpecification($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"lensSpecification\" must be array of objects or null, ' . gettype($data['lensSpecification']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function quotedPrintableEncode($input , $line_max = 76, $eol = \"\\r\\n\")\n {\n /*\n // imap_8bit() is extremely fast, but doesn't handle properly some characters\n if (function_exists('imap_8bit') && $line_max == 76) {\n $input = preg_replace('/\\r?\\n/', \"\\r\\n\", $input);\n $input = imap_8bit($input);\n if ($eol != \"\\r\\n\") {\n $input = str_replace(\"\\r\\n\", $eol, $input);\n }\n return $input;\n }\n */\n $lines = preg_split(\"/\\r?\\n/\", $input);\n $escape = '=';\n $output = '';\n\n foreach ($lines as $idx=>$line) {\n $newline = '';\n $i = 0;\n\n while (isset($line[$i])) {\n $char = $line[$i];\n $dec = ord($char);\n $i++;\n\n if (($dec == 32) && (!isset($line[$i]))) {\n // convert space at eol only\n $char = '=20';\n } elseif ($dec == 9 && isset($line[$i])) {\n ; // Do nothing if a TAB is not on eol\n } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {\n $char = $escape . sprintf('%02X', $dec);\n } elseif (($dec == 46) && (($newline == '')\n || ((strlen($newline) + strlen(\"=2E\")) >= $line_max))\n ) {\n // Bug #9722: convert full-stop at bol,\n // some Windows servers need this, won't break anything (cipri)\n // Bug #11731: full-stop at bol also needs to be encoded\n // if this line would push us over the line_max limit.\n $char = '=2E';\n }\n\n // Note, when changing this line, also change the ($dec == 46)\n // check line, as it mimics this line due to Bug #11731\n // EOL is not counted\n if ((strlen($newline) + strlen($char)) >= $line_max) {\n // soft line break; \" =\\r\\n\" is okay\n $output .= $newline . $escape . $eol;\n $newline = '';\n }\n $newline .= $char;\n } // end of for\n $output .= $newline . $eol;\n unset($lines[$idx]);\n }\n // Don't want last crlf\n $output = substr($output, 0, -1 * strlen($eol));\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "protected function canonicalRedirection($canonical_url = '')\n {\n if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET' || Tools::getValue('live_edit')) {\n return;\n }\n\n $match_url = rawurldecode(Tools::getCurrentUrlProtocolPrefix().$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n if (!preg_match('/^'.Tools::pRegexp(rawurldecode($canonical_url), '/').'([&?].*)?$/', $match_url)) {\n $params = array();\n $url_details = parse_url($canonical_url);\n\n if (!empty($url_details['query'])) {\n parse_str($url_details['query'], $query);\n foreach ($query as $key => $value) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n $excluded_key = array('isolang', 'id_lang', 'controller', 'fc', 'id_product', 'id_category', 'id_manufacturer', 'id_supplier', 'id_cms');\n foreach ($_GET as $key => $value) {\n if (!in_array($key, $excluded_key) && Validate::isUrl($key) && Validate::isUrl($value)) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n\n $str_params = http_build_query($params, '', '&');\n if (!empty($str_params)) {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url).'?'.$str_params;\n } else {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url);\n }\n\n // Don't send any cookie\n Context::getContext()->cookie->disallowWriting();\n\n if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $_SERVER['REQUEST_URI'] != __PS_BASE_URI__) {\n die('[Debug] This page has moved<br />Please use the following URL instead: <a href=\"'.$final_url.'\">'.$final_url.'</a>');\n }\n\n $redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';\n header('HTTP/1.0 '.$redirect_type.' Moved');\n header('Cache-Control: no-cache');\n Tools::redirectLink($final_url);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function testProfileRightsHaveSearchOptions()\n {\n $search_opts = \\Search::getOptions(\\Profile::class);\n // We can keep only the options that have 'right' as the field\n $search_opts = array_filter($search_opts, static function ($opt) {\n return is_array($opt) && isset($opt['field']) && $opt['field'] === 'rights';\n });\n $failures = [];\n $all_rights = \\Profile::getRightsForForm();\n\n foreach ($all_rights as $interface => $forms) {\n foreach ($forms as $form => $groups) {\n foreach ($groups as $group => $rights) {\n $previous_right = null;\n foreach ($rights as $right) {\n if (empty($right['field'])) {\n echo 'A right is missing a field name. Please check that the class has the rightname property set or the right is otherwise defined with the field property in the array';\n if ($previous_right) {\n echo 'The previous right was: ' . print_r($previous_right, true) . \" in ${$interface}/${$form}/${$group}\";\n } else {\n echo \"The right was the first one in ${$interface}/${$form}/${$group}\";\n }\n continue;\n }\n $search_opt_matches = array_filter($search_opts, static function ($opt) use ($right) {\n return array_key_exists('rightname', $opt) && $opt['rightname'] === $right['field'];\n });\n if (!count($search_opt_matches)) {\n $failures[] = $right['field'];\n }\n $previous_right = $right;\n }\n }\n }\n }\n\n $failures = array_unique($failures);\n if (count($failures)) {\n echo sprintf('The following rights do not have a search option: %s', implode(', ', $failures));\n }\n $this->assertEmpty($failures);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private static function _searchInCache(){\n\n foreach (self::$cache_id as $idx=>$curr_recid){\n\n $group = array();\n //$group2 = array();\n\n $str1 = self::$cache_str[$idx];\n\n $str_exact = @self::$cache_str_exact[$idx];\n\n\n if($curr_recid==20 || $curr_recid==1169){\n\n $w = 1;\n }\n\n\n $len1 = strlen($str1);\n if($len1>255){\n $str1 = substr($str1,0,255);\n $len1 = 255;\n }\n $cnt = count(self::$cache_id);\n\n\n $i = array_search($curr_recid, self::$all_similar_ids, true);\n if($i==false && $len1>2){\n\n $dist = ceil($len1*self::$distance/100);//difference % set in client side\n if($dist==0){\n $dist = 1;\n }elseif($dist>10){\n $dist = 10;\n }\n\n for ($idx2=$idx+1; $idx2<$cnt; $idx2++){\n\n if($str_exact==null || ($curr_recid!=self::$cache_id[$idx2] && $str_exact==@self::$cache_str_exact[$idx2]))\n {\n $str2 = self::$cache_str[$idx2];\n\n $len2 = strlen($str2);\n if($len2>255){\n $str2 = substr($str2,0,255);\n $len2 = 255;\n }\n\n if(abs($len1-$len2)<=$dist){\n $d = levenshtein($str1, $str2);\n if($d<=$dist){\n $group[] = self::$cache_id[$idx2];\n //$group2[self::$cache_id[$idx2]] = '('.$d.' '.$dist.')';\n }\n }\n }\n\n }\n }\n\n if(!empty($group)){\n array_unshift($group, $curr_recid);//add current\n\n sort($group);\n $diffHash = implode(',',$group);\n if (is_array(self::$dupeIgnoring) && !in_array($diffHash, self::$dupeIgnoring))\n {\n\n self::$all_similar_ids = array_merge(self::$all_similar_ids, $group);//add new set of ids except first (current rec_id)\n\n //find titles\n $group = mysql__select_assoc2(self::$mysqli,'select rec_ID, rec_Title from Records where rec_ID in ('\n .implode(',',$group).')');\n\n foreach ($group as $recid=>$title){\n $group[$recid] = $title; //@$group2[$recid].' '.$title;\n }\n\n\n self::$all_similar_records[] = $group; //id=>title\n self::$all_similar_ids_cnt = self::$all_similar_ids_cnt + count($group);\n\n if(self::$all_similar_ids_cnt>self::$limit_cnt){\n return 1;\n }\n\n }\n }\n\n self::$processed++;\n\n\n //update session and check for termination\n if(self::$progress_session_id && (self::$processed % 10 == 0)){\n $session_val = self::$processed.','.self::$tot_count;\n $current_val = mysql__update_progress(null, self::$progress_session_id, false, $session_val);\n if($current_val && $current_val=='terminate'){\n $msg_termination = 'Operation is terminated by user';\n return 2;\n }\n }\n } //for\n\n return 0;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private function importItemsSpecifications()\n {\n\n $has_errors = false;\n\n $this->output->writeln(\n '<comment>' . __('Importing items specifications...') . '</comment>',\n OutputInterface::VERBOSITY_NORMAL\n );\n\n $specs_iterator = $this->db->request(\n [\n 'FROM' => 'glpi_plugin_racks_itemspecifications',\n 'ORDER' => 'id ASC'\n ]\n );\n\n if ($specs_iterator->count()) {\n $progress_bar = new ProgressBar($this->output, $specs_iterator->count());\n $progress_bar->start();\n\n foreach ($specs_iterator as $spec) {\n $progress_bar->advance(1);\n\n $message = sprintf(\n __('Importing specifications for model %s (%s)...'),\n $spec['itemtype'],\n $spec['model_id']\n );\n $this->writelnOutputWithProgressBar(\n $message,\n $progress_bar,\n OutputInterface::VERBOSITY_VERY_VERBOSE\n );\n\n $model = $this->getCorrespondingItem($spec['itemtype'], $spec['model_id']);\n\n if (null === $model) {\n $message = sprintf(\n __('Model %s (%s) not found.'),\n $spec['itemtype'],\n $spec['model_id']\n );\n $this->writelnOutputWithProgressBar(\n $message,\n $progress_bar,\n OutputInterface::VERBOSITY_VERBOSE\n );\n continue;\n }\n\n $model_input = [\n 'id' => $model->fields['id'],\n 'required_units' => $spec['size'],\n 'depth' => ($spec['length'] == 1 ? 1 : 0.5),\n 'weight' => $spec['weight'],\n 'is_half_rack' => 0,\n 'power_connections' => $spec['nb_alim'],\n ];\n\n if (!$model->update($model_input)) {\n $has_errors = true;\n\n $message = sprintf(\n __('Unable to update model %s (%s).'),\n $spec['itemtype'],\n $spec['model_id']\n );\n $this->outputImportError($message, $progress_bar);\n if ($this->input->getOption('skip-errors')) {\n continue;\n } else {\n return false;\n }\n }\n }\n\n $progress_bar->finish();\n $this->output->write(PHP_EOL);\n } else {\n $this->output->writeln(\n '<comment>' . __('No items specifications found.') . '</comment>',\n OutputInterface::VERBOSITY_NORMAL\n );\n }\n\n return !$has_errors;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function edit_group($group_id, $value=NULL, $name=NULL, $parent_id=NULL, $group_type='ARO') {\n\t\t$this->debug_text(\"edit_group(): ID: $group_id Name: $name Value: $value Parent ID: $parent_id Group Type: $group_type\");\n\n\t\tswitch(strtolower(trim($group_type))) {\n\t\t\tcase 'axo':\n\t\t\t\t$group_type = 'axo';\n\t\t\t\t$table = $this->_db_table_prefix .'axo_groups';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$group_type = 'aro';\n\t\t\t\t$table = $this->_db_table_prefix .'aro_groups';\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (empty($group_id) ) {\n\t\t\t$this->debug_text('edit_group(): Group ID ('. $group_id .') is empty, this is required');\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif ( !is_array($curr = $this->get_group_data($group_id, $group_type)) ) {\n\t\t\t$this->debug_text('edit_group(): Invalid Group ID: '. $group_id);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t$name = trim($name);\n\n\t\t// don't set name if it is unchanged\n\t\tif ($name == $curr[3]) {\n\t\t\tunset($name);\n\t\t}\n\n\t\t// don't set parent_id if it is unchanged\n\t\tif ($parent_id == $curr[1]) {\n\t\t\tunset($parent_id);\n\t\t}\n\n\t\tif (!empty($parent_id)) {\n\t\t\tif ($group_id == $parent_id) {\n\t\t\t\t$this->debug_text('edit_group(): Groups can\\'t be a parent to themselves. Incest is bad. ;)');\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\t//Make sure we don't re-parent to our own children.\n\t\t\t//Grab all children of this group_id.\n\t\t\t$children_ids = $this->get_group_children($group_id, $group_type, 'RECURSE');\n\t\t\tif (is_array($children_ids)) {\n\t\t\t\tif (@in_array($parent_id, $children_ids) ) {\n\t\t\t\t\t$this->debug_text('edit_group(): Groups can\\'t be re-parented to their own children, this would be incestuous!');\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tunset($children_ids);\n\n\t\t\t// make sure parent exists\n\t\t\tif (!$this->get_group_data($parent_id, $group_type)) {\n\t\t\t\t$this->debug_text('edit_group(): Parent Group ('. $parent_id .') doesn\\'t exist');\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\n\t\t$set = array();\n\n\t\t// update name if it is specified.\n\t\tif (!empty($name)) {\n\t\t\t$set[] = 'name='. $this->db->quote($name);\n\t\t}\n\n\t\t// update parent_id if it is specified.\n\t\tif (!empty($parent_id)) {\n\t\t\t$set[] = 'parent_id='. $this->db->quote($parent_id);\n\t\t}\n\n\t\t// update value if it is specified.\n\t\tif (!empty($value)) {\n\t\t\t$set[] = 'value='. $this->db->quote($value);\n\t\t}\n\n\t\tif (empty($set)) {\n\t\t\t$this->debug_text('edit_group(): Nothing to update.');\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t$this->db->BeginTrans();\n\n\t\t$query = 'UPDATE '. $table .' SET '. implode(',', $set) .' WHERE id='. $this->db->quote($group_id);\n\t\t$rs = $this->db->Execute($query);\n\n\t\tif (!is_object($rs)) {\n\t\t\t$this->debug_db('edit_group');\n\t\t\t$this->db->RollbackTrans();\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t$this->debug_text('edit_group(): Modified group ID: '. $group_id);\n\n\t\t// rebuild group tree if parent_id has changed\n\t\tif (!empty($parent_id)) {\n\t\t\tif (!$this->_rebuild_tree($table, $this->get_root_group_id($group_type))) {\n\t\t\t\t$this->db->RollbackTrans();\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\n\t\t$this->db->CommitTrans();\n\n\t\tif ($this->_caching == TRUE AND $this->_force_cache_expire == TRUE) {\n\t\t\t// Expire all cache.\n\t\t\t$this->Cache_Lite->clean('default');\n\t\t}\n\n\t\treturn TRUE;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getSheetGrade()\n {\n $disciplineCategory = [\n 'base' => [\n 3 => \"Matem\u00e1tica\",\n 6 => \"Portugu\u00eas\",\n 5 => \"Ci\u00eancias\",\n 13 => \"Geografia\",\n 12 => \"Hist\u00f3ria\",\n 10 => \"Artes\",\n 11 => \"Educa\u00e7\u00e3o F\u00edsica\",\n 26 => \"Ensino Religioso\",\n ]\n ];\n\n $disciplines = ClassroomController::classroomDisciplineLabelResumeArray();\n\n $disciplineCategory['diversified'] = array_diff_assoc($disciplines, $disciplineCategory['base']);\n\n $evaluations = [1 => [], 2 => [], 3 => [], 4 => []];\n\n $recovery = [1 => [], 2 => [], 3 => [], 4 => [], 'final' => []];\n\n $average = [1 => [], 2 => [], 'final' => [], 'year' => []];\n\n $workHours = [1 => null, 2 => null, 3 => null, 4 => null, 'final' => null];\n\n $workDays = [1 => null, 2 => null, 3 => null, 4 => null, 'final' => null];\n\n $frequency = [];\n\n $absences = [1 => null, 2 => null, 3 => null, 4 => null, 'base' => [], 'diversified' => [], 'percent' => null];\n\n $workDaysByDiscipline = ['base' => [], 'diversified' => []];\n\n $result = [];\n $grades = $this->grades;\n foreach ($grades as $grade) {\n if (isset($disciplines[$grade->discipline_fk])) {\n $frequencyAndMean = FrequencyAndMeanByDiscipline::model()->findByAttributes([\n \"enrollment_fk\" => $grade->enrollment_fk,\n \"discipline_fk\" => $grade->discipline_fk\n ]);\n\n $disciplineType = '';\n if (isset($disciplineCategory['base'][$grade->discipline_fk])) {\n $disciplineType = \"base\";\n } else {\n $disciplineType = \"diversified\";\n }\n\n $evaluations[1][$disciplineType][$grade->discipline_fk] = is_null($grade->grade1) ? '' : number_format($grade->grade1, 2, ',', '');\n $evaluations[2][$disciplineType][$grade->discipline_fk] = is_null($grade->grade2) ? '' : number_format($grade->grade2, 2, ',', '');\n $evaluations[3][$disciplineType][$grade->discipline_fk] = is_null($grade->grade3) ? '' : number_format($grade->grade3, 2, ',', '');\n $evaluations[4][$disciplineType][$grade->discipline_fk] = is_null($grade->grade4) ? '' : number_format($grade->grade4, 2, ',', '');\n\n $recovery[1][$disciplineType][$grade->discipline_fk] = is_null($grade->recovery_grade1) ? '' : number_format($grade->recovery_grade1, 2, ',', '');\n $recovery[2][$disciplineType][$grade->discipline_fk] = is_null($grade->recovery_grade2) ? '' : number_format($grade->recovery_grade2, 2, ',', '');\n $recovery[3][$disciplineType][$grade->discipline_fk] = is_null($grade->recovery_grade3) ? '' : number_format($grade->recovery_grade3, 2, ',', '');\n $recovery[4][$disciplineType][$grade->discipline_fk] = is_null($grade->recovery_grade4) ? '' : number_format($grade->recovery_grade4, 2, ',', '');\n $recovery['final'][$disciplineType][$grade->discipline_fk] = number_format($grade->recovery_final_grade, 2, ',', '');\n\n $frequency[$disciplineType][$grade->discipline_fk] = number_format($frequencyAndMean->frequency, 2, ',', '');\n $absences['percent'][$disciplineType][$grade->discipline_fk] = $frequencyAndMean->absences;\n\n $absences[$disciplineType][$grade->discipline_fk] = count($this->getFaultsByDiscipline($grade->discipline_fk));\n\n $average[1][$disciplineType][$grade->discipline_fk] = number_format(($grade->grade1 + $grade->grade2) / 2, 2, ',', '');\n $average[2][$disciplineType][$grade->discipline_fk] = number_format(($grade->grade3 + $grade->grade4) / 2, 2, ',', '');\n\n $average['final'][$disciplineType][$grade->discipline_fk] = number_format($frequencyAndMean->final_average, 2, ',', '');\n $average['year'][$disciplineType][$grade->discipline_fk] = number_format($frequencyAndMean->annual_average, 2, ',', '');\n $classroom = $this->classroomFk;\n\n $workDaysByDiscipline[$disciplineType][$grade->discipline_fk] = $classroom->getWorkingDaysByDiscipline($grade->discipline_fk);\n\n if (is_null($workDays[1])) {\n\n $workDays[1] = $classroom->getSchoolDaysByExam(1);\n $workDays[2] = $classroom->getSchoolDaysByExam(2);\n $workDays[3] = $classroom->getSchoolDaysByExam(3);\n $workDays[4] = $classroom->getSchoolDaysByExam(4);\n\n $workHours[1] = $classroom->getWorkingHoursByExam(1);\n $workHours[2] = $classroom->getWorkingHoursByExam(2);\n $workHours[3] = $classroom->getWorkingHoursByExam(3);\n $workHours[4] = $classroom->getWorkingHoursByExam(4);\n }\n\n if (is_null($absences[1])) {\n $absences[1] = count($this->getFaultsByExam(1));\n $absences[2] = count($this->getFaultsByExam(2));\n $absences[3] = count($this->getFaultsByExam(3));\n $absences[4] = count($this->getFaultsByExam(4));\n\n }\n\n }\n }\n\n $sort = function (&$array) {\n foreach ($array as $key => $value) {\n if (isset($array[$key]['base'])) {\n ksort($array[$key]['base']);\n }\n if (isset($array[$key]['diversified'])) {\n ksort($array[$key]['diversified']);\n }\n }\n };\n\n $fill = function (&$evaluations, &$recovery, &$frequency, &$absences, &$average, &$workDaysByDiscipline, $disciplineType) {\n $evaluations[1][$disciplineType][] = null;\n $evaluations[2][$disciplineType][] = null;\n $evaluations[3][$disciplineType][] = null;\n $evaluations[4][$disciplineType][] = null;\n\n $recovery[1][$disciplineType][] = null;\n $recovery[2][$disciplineType][] = null;\n $recovery[3][$disciplineType][] = null;\n $recovery[4][$disciplineType][] = null;\n $recovery['final'][$disciplineType][] = null;\n\n $frequency[$disciplineType][] = null;\n\n $absences['percent'][$disciplineType] = null;\n $absences[$disciplineType][] = null;\n\n $average[1][$disciplineType][] = null;\n $average[2][$disciplineType][] = null;\n $average['final'][$disciplineType][] = null;\n $average['year'][$disciplineType][] = null;\n\n $workDaysByDiscipline[$disciplineType][] = null;\n };\n\n $sort($evaluations);\n $sort($recovery);\n $sort($average);\n $sort($frequency);\n $sort($absences);\n $disciplineFilter['base'] = array_intersect_key($disciplineCategory['base'], $evaluations[1]['base']);\n $disciplineFilter['diversified'] = array_intersect_key($disciplineCategory['diversified'], $evaluations[1]['diversified']);\n ksort($disciplineFilter['base']);\n ksort($disciplineFilter['diversified']);\n\n // condi\u00e7\u00e3o adicionada para manter a quantidade de disciplinas padronizada\n if (count($disciplineFilter['base']) + count($disciplineFilter['diversified']) < 13) {\n while (count($disciplineFilter['base']) < 8) {\n $fill($evaluations, $recovery, $frequency, $absences, $average, $workDaysByDiscipline, 'base');\n $disciplineFilter['base'][] = null;\n }\n while (count($disciplineFilter['diversified']) < 4) {\n $fill($evaluations, $recovery, $frequency, $absences, $average, $workDaysByDiscipline, 'diversified');\n $disciplineFilter['diversified'][] = null;\n }\n\n }\n\n $result = [\n 'disciplines' => $disciplineFilter,\n 'evaluations' => $evaluations,\n 'recovery' => $recovery,\n 'average' => $average,\n 'work_hours' => $workHours,\n 'work_days' => $workDays,\n 'work_days_discipline' => $workDaysByDiscipline,\n 'frequency' => $frequency,\n 'absences' => $absences\n ];\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int {\n\t\t$mountId = $input->getArgument('mount_id');\n\t\ttry {\n\t\t\t$mount = $this->globalService->getStorage($mountId);\n\t\t} catch (NotFoundException $e) {\n\t\t\t$output->writeln('<error>Mount with id \"' . $mountId . ' not found, check \"occ files_external:list\" to get available mounts</error>');\n\t\t\treturn Response::HTTP_NOT_FOUND;\n\t\t}\n\n\t\tif ($mount->getType() === StorageConfig::MOUNT_TYPE_PERSONAL) {\n\t\t\t$output->writeln('<error>Can\\'t change applicables on personal mounts</error>');\n\t\t\treturn self::FAILURE;\n\t\t}\n\n\t\t$addUsers = $input->getOption('add-user');\n\t\t$removeUsers = $input->getOption('remove-user');\n\t\t$addGroups = $input->getOption('add-group');\n\t\t$removeGroups = $input->getOption('remove-group');\n\n\t\t$applicableUsers = $mount->getApplicableUsers();\n\t\t$applicableGroups = $mount->getApplicableGroups();\n\n\t\tif ((count($addUsers) + count($removeUsers) + count($addGroups) + count($removeGroups) > 0) || $input->getOption('remove-all')) {\n\t\t\tforeach ($addUsers as $addUser) {\n\t\t\t\tif (!$this->userManager->userExists($addUser)) {\n\t\t\t\t\t$output->writeln('<error>User \"' . $addUser . '\" not found</error>');\n\t\t\t\t\treturn Response::HTTP_NOT_FOUND;\n\t\t\t\t}\n\t\t\t}\n\t\t\tforeach ($addGroups as $addGroup) {\n\t\t\t\tif (!$this->groupManager->groupExists($addGroup)) {\n\t\t\t\t\t$output->writeln('<error>Group \"' . $addGroup . '\" not found</error>');\n\t\t\t\t\treturn Response::HTTP_NOT_FOUND;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($input->getOption('remove-all')) {\n\t\t\t\t$applicableUsers = [];\n\t\t\t\t$applicableGroups = [];\n\t\t\t} else {\n\t\t\t\t$applicableUsers = array_unique(array_merge($applicableUsers, $addUsers));\n\t\t\t\t$applicableUsers = array_values(array_diff($applicableUsers, $removeUsers));\n\t\t\t\t$applicableGroups = array_unique(array_merge($applicableGroups, $addGroups));\n\t\t\t\t$applicableGroups = array_values(array_diff($applicableGroups, $removeGroups));\n\t\t\t}\n\t\t\t$mount->setApplicableUsers($applicableUsers);\n\t\t\t$mount->setApplicableGroups($applicableGroups);\n\t\t\t$this->globalService->updateStorage($mount);\n\t\t}\n\n\t\t$this->writeArrayInOutputFormat($input, $output, [\n\t\t\t'users' => $applicableUsers,\n\t\t\t'groups' => $applicableGroups\n\t\t]);\n\t\treturn self::SUCCESS;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected static function _raiseError($object,\n $message = null,\n $code = null,\n $mode = null,\n $options = null,\n $userinfo = null,\n $error_class = null,\n $skipmsg = false)\n {\n // The error is yet a PEAR error object\n if (is_object($message)) {\n $code = $message->getCode();\n $userinfo = $message->getUserInfo();\n $error_class = $message->getType();\n $message->error_message_prefix = '';\n $message = $message->getMessage();\n }\n\n if (\n $object !== null &&\n isset($object->_expected_errors) &&\n count($object->_expected_errors) > 0 &&\n count($exp = end($object->_expected_errors))\n ) {\n if ($exp[0] === \"*\" ||\n (is_int(reset($exp)) && in_array($code, $exp)) ||\n (is_string(reset($exp)) && in_array($message, $exp))\n ) {\n $mode = PEAR_ERROR_RETURN;\n }\n }\n\n // No mode given, try global ones\n if ($mode === null) {\n // Class error handler\n if ($object !== null && isset($object->_default_error_mode)) {\n $mode = $object->_default_error_mode;\n $options = $object->_default_error_options;\n // Global error handler\n } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {\n $mode = $GLOBALS['_PEAR_default_error_mode'];\n $options = $GLOBALS['_PEAR_default_error_options'];\n }\n }\n\n if ($error_class !== null) {\n $ec = $error_class;\n } elseif ($object !== null && isset($object->_error_class)) {\n $ec = $object->_error_class;\n } else {\n $ec = 'PEAR_Error';\n }\n\n if ($skipmsg) {\n $a = new $ec($code, $mode, $options, $userinfo);\n } else {\n $a = new $ec($message, $code, $mode, $options, $userinfo);\n }\n\n return $a;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getEstimatedDimensions(): array\n {\n $dimensions = [];\n $transformations = $this->getItems();\n foreach ($transformations as $transformation) {\n if (!empty($transformation)) {\n if (is_array($transformation['arguments'])) {\n foreach ($transformation['arguments'] as $key => $value) {\n if ($key == 'width' || $key == 'height') {\n $dimensions[$key] = $value;\n }\n }\n }\n }\n }\n\n return $dimensions;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function transferInfocoms($itemtype, $ID, $newID): void\n {\n /** @var DBmysql $DB */\n global $DB;\n\n $ic = new Infocom();\n if ($ic->getFromDBforDevice($itemtype, $ID)) {\n switch ($this->options['keep_infocom']) {\n // delete\n case 0:\n // Same item -> delete\n if ($ID == $newID) {\n $DB->delete(\n 'glpi_infocoms',\n [\n 'items_id' => $ID,\n 'itemtype' => $itemtype\n ]\n );\n }\n // Copy : nothing to do\n break;\n\n // Keep\n default:\n // transfer supplier\n $suppliers_id = 0;\n if ($ic->fields['suppliers_id'] > 0) {\n $suppliers_id = $this->transferSingleSupplier($ic->fields['suppliers_id']);\n }\n\n // Copy : copy infocoms\n if ($ID != $newID) {\n // Copy items\n $input = $ic->fields;\n $input['items_id'] = $newID;\n $input['suppliers_id'] = $suppliers_id;\n unset($input['id']);\n unset($ic->fields);\n $ic->add($input);\n } else {\n // Same Item : manage only supplier move\n // Update supplier\n if (\n ($suppliers_id > 0)\n && ($suppliers_id != $ic->fields['suppliers_id'])\n ) {\n $ic->update(['id' => $ic->fields['id'],\n 'suppliers_id' => $suppliers_id\n ]);\n }\n }\n\n break;\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['reference'])) {\n $this->setReference($data['reference']);\n }\n if (isset($data['fhirVersion'])) {\n if (is_array($data['fhirVersion'])) {\n foreach ($data['fhirVersion'] as $d) {\n $this->addFhirVersion($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"fhirVersion\" must be array of objects or null, ' . gettype($data['fhirVersion']) . ' seen.');\n }\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['exampleBoolean'])) {\n $this->setExampleBoolean($data['exampleBoolean']);\n }\n if (isset($data['exampleCanonical'])) {\n $this->setExampleCanonical($data['exampleCanonical']);\n }\n if (isset($data['groupingId'])) {\n $this->setGroupingId($data['groupingId']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function checkreqtimes($tocheck,$rtimes) {\n\tglobal $mathfuncs, $myrights;\n\tif ($rtimes=='') {return 1;}\n\tif ($tocheck=='DNE' || $tocheck=='oo' || $tocheck=='+oo' || $tocheck=='-oo') {\n\t\treturn 1;\n\t}\n\t$cleanans = preg_replace('/[^\\w\\*\\/\\+\\-\\(\\)\\[\\],\\.\\^=\\|]+/','',$tocheck);\n\n\t//if entry used pow or exp, we want to replace them with their asciimath symbols for requiretimes purposes\n\t$cleanans = str_replace(\"pow\",\"^\",$cleanans);\n\t$cleanans = str_replace(\"exp\",\"e\",$cleanans);\n\t$cleanans = preg_replace('/\\^\\((-?[\\d\\.]+)\\)([^\\d]|$)/','^$1$2', $cleanans);\n\n\tif (is_numeric($cleanans) && $cleanans>0 && $cleanans<1) {\n\t\t$cleanans = ltrim($cleanans,'0');\n\t}\n\t$ignore_case = true;\n\tif ($rtimes != '') {\n\t\t$list = array_map('trim',explode(\",\",$rtimes));\n\t\tfor ($i=0;$i < count($list);$i+=2) {\n\t\t\tif ($list[$i]=='') {continue;}\n\t\t\tif (!isset($list[$i+1]) ||\n\t\t\t (strlen($list[$i+1])<2 && $list[$i]!='ignore_case' && $list[$i]!='ignore_commas' && $list[$i]!='ignore_symbol')) {\n\t\t\t\tif ($myrights>10) {\n\t\t\t\t\techo \"Invalid requiretimes - check format\";\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$list[$i+1] = trim($list[$i+1]);\n\t\t\tif ($list[$i]=='ignore_case') {\n\t\t\t\t$ignore_case = ($list[$i+1]==='1' || $list[$i+1]==='true' || $list[$i+1]==='=1');\n\t\t\t\tcontinue;\n\t\t\t} else if ($list[$i]=='ignore_commas') {\n\t\t\t\tif ($list[$i+1]==='1' || $list[$i+1]==='true' || $list[$i+1]==='=1') {\n\t\t\t\t\t$cleanans = str_replace(',','',$cleanans);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t} else if ($list[$i]=='ignore_symbol') {\n\t\t\t\t$cleanans = str_replace($list[$i+1],'',$cleanans);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$comp = substr($list[$i+1],0,1);\n\t\t\tif (substr($list[$i+1],1,1)==='=') { //<=, >=, ==, !=\n\t\t\t\tif ($comp=='<' || $comp=='>') {\n\t\t\t\t\t$comp .= '=';\n\t\t\t\t}\n\t\t\t\t$num = intval(substr($list[$i+1],2));\n\t\t\t} else {\n\t\t\t\t$num = intval(substr($list[$i+1],1));\n\t\t\t}\n $grouptocheck = array_map('trim', explode('||',$list[$i]));\n\t\t\t$okingroup = false;\n\t\t\tforeach ($grouptocheck as $lookfor) {\n\t\t\t\tif ($lookfor=='#') {\n\t\t\t\t\t$nummatch = preg_match_all('/[\\d\\.]+/',$cleanans,$m);\n\t\t\t\t} else if ($lookfor[0]=='#') {\n\t\t\t\t\tif (!isset($all_numbers)) {\n\t\t\t\t\t\tpreg_match_all('/[\\d\\.]+/',$cleanans,$matches);\n\t\t\t\t\t\t$all_numbers = $matches[0];\n\t\t\t\t\t\tarray_walk($all_numbers, 'ltrimzero');\n\t\t\t\t\t}\n\t\t\t\t\t$lookfor = ltrim(str_replace(array('-', ' '),'',substr($lookfor,1)), ' 0');\n\t\t\t\t\t$nummatch = count(array_keys($all_numbers,$lookfor));\n\t\t\t\t} else if (strlen($lookfor)>6 && substr($lookfor,0,6)=='regex:') {\n\t\t\t\t\t$regex = str_replace('/','\\\\/',substr($lookfor,6));\n\t\t\t\t\t$nummatch = preg_match_all('/'.$regex.'/'.($ignore_case?'i':''),$cleanans,$m);\n\t\t\t\t} else {\n\t\t\t\t\tif ($ignore_case || in_array($lookfor, $mathfuncs)) {\n $nummatch = substr_count(strtolower($cleanans),strtolower($lookfor));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$nummatch = substr_count($cleanans,$lookfor);\n }\n\t\t\t\t}\n\n\t\t\t\tif ($comp == \"=\") {\n\t\t\t\t\tif ($nummatch==$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($comp == \"<\") {\n\t\t\t\t\tif ($nummatch<$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($comp == \"<=\") {\n\t\t\t\t\tif ($nummatch<=$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($comp == \">\") {\n\t\t\t\t\tif ($nummatch>$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($comp == \">=\") {\n\t\t\t\t\tif ($nummatch>=$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($comp == \"!\") {\n\t\t\t\t\tif ($nummatch!=$num) {\n\t\t\t\t\t\t$okingroup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if ($myrights>10) {\n\t\t\t\t\techo \"Invalid requiretimes - check format\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!$okingroup) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function buildTicket($uid, \\Laminas\\Mail\\Storage\\Message $message, $options = [])\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $play_rules = (isset($options['play_rules']) && $options['play_rules']);\n $headers = $this->getHeaders($message);\n\n $tkt = [];\n $tkt['_blacklisted'] = false;\n // For RuleTickets\n $tkt['_mailgate'] = $options['mailgates_id'];\n $tkt['_uid'] = $uid;\n $tkt['_head'] = $headers;\n\n $createuserfromemail = $this->fields['create_user_from_email'];\n\n // Use mail date if it's defined\n if ($this->fields['use_mail_date'] && isset($headers['date'])) {\n $tkt['date'] = $headers['date'];\n }\n\n if ($this->isMessageSentByGlpi($message)) {\n // Message was sent by current instance of GLPI.\n // Message is blacklisted to avoid infinite loop (where GLPI creates a ticket from its own notification).\n $tkt['_blacklisted'] = true;\n return $tkt;\n } else if ($this->isResponseToMessageSentByAnotherGlpi($message)) {\n // Message is a response to a message sent by another GLPI.\n // Message is blacklisted as we consider that the other instance of GLPI is responsible to handle this thread.\n $tkt['_blacklisted'] = true;\n return $tkt;\n }\n\n // manage blacklist\n $blacklisted_emails = Blacklist::getEmails();\n // Add name of the mailcollector as blacklisted\n $blacklisted_emails[] = $this->fields['name'];\n if (Toolbox::inArrayCaseCompare($headers['from'], $blacklisted_emails)) {\n $tkt['_blacklisted'] = true;\n return $tkt;\n }\n\n // max size = 0 : no import attachments\n if ($this->fields['filesize_max'] > 0) {\n if (is_writable(GLPI_TMP_DIR)) {\n $tkt['_filename'] = $this->getAttached($message, GLPI_TMP_DIR . \"/\", $this->fields['filesize_max']);\n $tkt['_tag'] = $this->tags;\n } else {\n //TRANS: %s is a directory\n Toolbox::logInFile('mailgate', sprintf(__('%s is not writable'), GLPI_TMP_DIR . \"/\") . \"\\n\");\n }\n }\n\n // Who is the user ?\n $requester = $this->getRequesterEmail($message);\n\n $tkt['_users_id_requester'] = User::getOrImportByEmail($requester, $createuserfromemail);\n $tkt[\"_users_id_requester_notif\"]['use_notification'][0] = 1;\n // Set alternative email if user not found / used if anonymous mail creation is enable\n if (!$tkt['_users_id_requester']) {\n $tkt[\"_users_id_requester_notif\"]['alternative_email'][0] = $requester;\n }\n\n // Fix author of attachment\n // Move requester to author of followup\n $tkt['users_id'] = $tkt['_users_id_requester'];\n\n // Add to and cc as additional observer if user found\n $ccs = $headers['ccs'];\n if (is_array($ccs) && count($ccs) && $this->getField(\"add_cc_to_observer\")) {\n foreach ($ccs as $cc) {\n if (\n $cc != $requester\n && !Toolbox::inArrayCaseCompare($cc, $blacklisted_emails) // not blacklisted emails\n ) {\n // Skip if user is anonymous and anonymous users are not allowed\n $user_id = User::getOrImportByEmail($cc);\n if (!$user_id && !$CFG_GLPI['use_anonymous_helpdesk']) {\n continue;\n }\n\n $nb = (isset($tkt['_users_id_observer']) ? count($tkt['_users_id_observer']) : 0);\n $tkt['_users_id_observer'][$nb] = $user_id;\n $tkt['_users_id_observer_notif']['use_notification'][$nb] = 1;\n $tkt['_users_id_observer_notif']['alternative_email'][$nb] = $cc;\n }\n }\n }\n\n $tos = $headers['tos'];\n if (is_array($tos) && count($tos)) {\n foreach ($tos as $to) {\n if (\n $to != $requester\n && !Toolbox::inArrayCaseCompare($to, $blacklisted_emails) // not blacklisted emails\n ) {\n // Skip if user is anonymous and anonymous users are not allowed\n $user_id = User::getOrImportByEmail($to);\n if (!$user_id && !$CFG_GLPI['use_anonymous_helpdesk']) {\n continue;\n }\n\n $nb = (isset($tkt['_users_id_observer']) ? count($tkt['_users_id_observer']) : 0);\n $tkt['_users_id_observer'][$nb] = $user_id;\n $tkt['_users_id_observer_notif']['use_notification'][$nb] = 1;\n $tkt['_users_id_observer_notif']['alternative_email'][$nb] = $to;\n }\n }\n }\n\n // Auto_import\n $tkt['_auto_import'] = 1;\n // For followup : do not check users_id = login user\n $tkt['_do_not_check_users_id'] = 1;\n $body = $this->getBody($message);\n\n try {\n $subject = $message->getHeader('subject')->getFieldValue();\n } catch (\\Laminas\\Mail\\Storage\\Exception\\InvalidArgumentException $e) {\n $subject = '';\n }\n $tkt['name'] = $this->cleanSubject($subject);\n\n $tkt['_message'] = $message;\n\n $tkt['content'] = $body;\n\n // Search for referenced item in headers\n $found_item = $this->getItemFromHeaders($message);\n if ($found_item instanceof Ticket) {\n $tkt['tickets_id'] = $found_item->fields['id'];\n }\n\n // See in title\n if (\n !isset($tkt['tickets_id'])\n && preg_match('/\\[.+#(\\d+)\\]/', $subject, $match)\n ) {\n $tkt['tickets_id'] = intval($match[1]);\n }\n\n $tkt['_supplier_email'] = false;\n // Found ticket link\n if (isset($tkt['tickets_id'])) {\n // it's a reply to a previous ticket\n $job = new Ticket();\n $tu = new Ticket_User();\n $st = new Supplier_Ticket();\n\n // Check if ticket exists and users_id exists in GLPI\n if (\n $job->getFromDB($tkt['tickets_id'])\n && ($job->fields['status'] != CommonITILObject::CLOSED)\n && ($CFG_GLPI['use_anonymous_followups']\n || ($tkt['_users_id_requester'] > 0)\n || $tu->isAlternateEmailForITILObject($tkt['tickets_id'], $requester)\n || ($tkt['_supplier_email'] = $st->isSupplierEmail(\n $tkt['tickets_id'],\n $requester\n )))\n ) {\n if ($tkt['_supplier_email']) {\n $tkt['content'] = sprintf(__('From %s'), $requester)\n . ($this->body_is_html ? '<br /><br />' : \"\\n\\n\")\n . $tkt['content'];\n }\n\n $header_tag = NotificationTargetTicket::HEADERTAG;\n $header_pattern = $header_tag . '.*' . $header_tag;\n $footer_tag = NotificationTargetTicket::FOOTERTAG;\n $footer_pattern = $footer_tag . '.*' . $footer_tag;\n\n $has_header_line = preg_match('/' . $header_pattern . '/s', $tkt['content']);\n $has_footer_line = preg_match('/' . $footer_pattern . '/s', $tkt['content']);\n\n $stripped_content = null;\n if ($has_header_line && $has_footer_line) {\n // Strip all contents between header and footer line\n $stripped_content = preg_replace(\n '/\\s*' . $header_pattern . '.*' . $footer_pattern . '\\s*/s',\n \"\\r\\n\",\n $tkt['content']\n );\n } else if ($has_header_line) {\n // Strip all contents between header line and end of message\n $stripped_content = preg_replace(\n '/\\s*' . $header_pattern . '.*$/s',\n '',\n $tkt['content']\n );\n } else if ($has_footer_line) {\n // Strip all contents between begin of message and footer line\n $stripped_content = preg_replace(\n '/^.*' . $footer_pattern . '\\s*/s',\n '',\n $tkt['content']\n );\n }\n if (empty($stripped_content)) {\n // If stripped content is empty, it means that stripping was too agressive, probably because\n // end-user do not respect header/footer lines indications.\n // In this case, strip only header and footer lines to ensure they will not be duplicated in next notifications.\n $stripped_content = preg_replace(\n '/\\s*(' . $header_pattern . '|' . $footer_pattern . ')\\s*/s',\n '',\n $tkt['content']\n );\n }\n $tkt['content'] = trim($stripped_content);\n } else {\n // => to handle link in Ticket->post_addItem()\n $tkt['_linkedto'] = $tkt['tickets_id'];\n unset($tkt['tickets_id']);\n }\n }\n\n // Add message from getAttached\n if ($this->addtobody) {\n $tkt['content'] .= $this->addtobody;\n }\n\n //If files are present and content is html\n if (isset($this->files) && count($this->files) && $this->body_is_html) {\n $tkt['content'] = Ticket::convertContentForTicket(\n $tkt['content'],\n $this->files + $this->altfiles,\n $this->tags\n );\n }\n\n if (!$DB->use_utf8mb4) {\n // Replace emojis by their shortcode\n $tkt['content'] = LitEmoji::encodeShortcode($tkt['content']);\n $tkt['name'] = LitEmoji::encodeShortcode($tkt['name']);\n }\n\n // Clean mail content\n $tkt['content'] = $this->cleanContent($tkt['content']);\n\n if (!isset($tkt['tickets_id'])) {\n // Which entity ?\n //$tkt['entities_id']=$this->fields['entities_id'];\n //$tkt['Subject']= $message->subject; // not use for the moment\n // Medium\n $tkt['urgency'] = \"3\";\n // No hardware associated\n $tkt['itemtype'] = \"\";\n // Mail request type\n } else {\n // Reopen if needed\n $tkt['add_reopen'] = 1;\n }\n\n $tkt['requesttypes_id'] = RequestType::getDefault('mail');\n\n if ($play_rules) {\n $rule_options['ticket'] = $tkt;\n $rule_options['headers'] = $this->getHeaders($message);\n $rule_options['mailcollector'] = $options['mailgates_id'];\n $rule_options['_users_id_requester'] = $tkt['_users_id_requester'];\n $rulecollection = new RuleMailCollectorCollection();\n $output = $rulecollection->processAllRules(\n [],\n [],\n $rule_options\n );\n\n // New ticket : compute all\n if (!isset($tkt['tickets_id'])) {\n foreach ($output as $key => $value) {\n $tkt[$key] = $value;\n }\n } else { // Followup only copy refuse data\n $tkt['requesttypes_id'] = RequestType::getDefault('mailfollowup');\n $tobecopied = ['_refuse_email_no_response', '_refuse_email_with_response'];\n foreach ($tobecopied as $val) {\n if (isset($output[$val])) {\n $tkt[$val] = $output[$val];\n }\n }\n }\n }\n\n return $tkt;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function cronCertificate($task = null)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n if (!$CFG_GLPI['use_notifications']) {\n return 0; // Nothing to do\n }\n\n $errors = 0;\n $total = 0;\n\n foreach (array_keys(Entity::getEntitiesToNotify('use_certificates_alert')) as $entity) {\n $before = Entity::getUsedConfig('send_certificates_alert_before_delay', $entity);\n $repeat = Entity::getUsedConfig('certificates_alert_repeat_interval', $entity);\n if ($repeat > 0) {\n $where_date = [\n 'OR' => [\n ['glpi_alerts.date' => null],\n [\n 'glpi_alerts.date' => ['<',\n QueryFunction::dateSub(\n date: QueryFunction::now(),\n interval: $repeat,\n interval_unit: 'SECOND'\n )\n ]\n ],\n ]\n ];\n } else {\n $where_date = ['glpi_alerts.date' => null];\n }\n $iterator = $DB->request(\n [\n 'SELECT' => [\n 'glpi_certificates.id',\n ],\n 'FROM' => self::getTable(),\n 'LEFT JOIN' => [\n 'glpi_alerts' => [\n 'FKEY' => [\n 'glpi_alerts' => 'items_id',\n 'glpi_certificates' => 'id',\n [\n 'AND' => [\n 'glpi_alerts.itemtype' => __CLASS__,\n 'glpi_alerts.type' => Alert::END,\n ],\n ],\n ]\n ]\n ],\n 'WHERE' => [\n $where_date,\n 'glpi_certificates.is_deleted' => 0,\n 'glpi_certificates.is_template' => 0,\n [\n 'NOT' => ['glpi_certificates.date_expiration' => null],\n ],\n [\n 'RAW' => [\n 'DATEDIFF(' . DBmysql::quoteName('glpi_certificates.date_expiration') . ', CURDATE())' => ['<', $before]\n ]\n ],\n 'glpi_certificates.entities_id' => $entity,\n ],\n ]\n );\n\n foreach ($iterator as $certificate_data) {\n $certificate_id = $certificate_data['id'];\n $certificate = new self();\n if (!$certificate->getFromDB($certificate_id)) {\n $errors++;\n trigger_error(sprintf('Unable to load Certificate \"%s\".', $certificate_id), E_USER_WARNING);\n continue;\n }\n\n if (NotificationEvent::raiseEvent('alert', $certificate)) {\n $msg = sprintf(\n __('%1$s: %2$s'),\n Dropdown::getDropdownName('glpi_entities', $entity),\n sprintf(\n __('Certificate %1$s expired on %2$s'),\n $certificate->fields['name'] . (!empty($certificate->fields['serial']) ? ' - ' . $certificate->fields['serial'] : ''),\n Html::convDate($certificate->fields['date_expiration'])\n )\n );\n if ($task) {\n $task->log($msg);\n $task->addVolume(1);\n } else {\n Session::addMessageAfterRedirect(htmlspecialchars($msg));\n }\n\n // Add alert\n $input = [\n 'type' => Alert::END,\n 'itemtype' => __CLASS__,\n 'items_id' => $certificate_id,\n ];\n $alert = new Alert();\n $alert->deleteByCriteria($input, 1);\n $alert->add($input);\n\n $total++;\n } else {\n $errors++;\n\n $msg = sprintf(\n __('Certificate alerts sending failed for entity %1$s'),\n Dropdown::getDropdownName(\"glpi_entities\", $entity)\n );\n if ($task) {\n $task->log($msg);\n } else {\n Session::addMessageAfterRedirect(htmlspecialchars($msg), false, ERROR);\n }\n }\n }\n }\n\n return $errors > 0 ? -1 : ($total > 0 ? 1 : 0);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function changeActiveEntities($ID = \"all\", $is_recursive = false)\n {\n\n $newentities = [];\n $ancestors = [];\n\n $_SESSION[\"glpientity_fullstructure\"] = ($ID === 'all');\n\n if (isset($_SESSION['glpiactiveprofile'])) {\n if ($ID === \"all\") {\n foreach ($_SESSION['glpiactiveprofile']['entities'] as $val) {\n $ancestors = array_unique(array_merge(\n getAncestorsOf(\n \"glpi_entities\",\n $val['id']\n ),\n $ancestors\n ));\n $newentities[$val['id']] = $val['id'];\n\n if ($val['is_recursive']) {\n $entities = getSonsOf(\"glpi_entities\", $val['id']);\n if (count($entities)) {\n foreach ($entities as $key2 => $val2) {\n $newentities[$key2] = $key2;\n }\n }\n }\n }\n $is_recursive = true;\n } else {\n $ID = (int)$ID;\n\n /// Check entity validity\n $ancestors = getAncestorsOf(\"glpi_entities\", $ID);\n $ok = false;\n foreach ($_SESSION['glpiactiveprofile']['entities'] as $val) {\n if (($val['id'] == $ID) || in_array($val['id'], $ancestors)) {\n // Not recursive or recursive and root entity is recursive\n if (!$is_recursive || $val['is_recursive']) {\n $ok = true;\n }\n }\n }\n if (!$ok) {\n return false;\n }\n\n $newentities[$ID] = $ID;\n if ($is_recursive) {\n $entities = getSonsOf(\"glpi_entities\", $ID);\n if (count($entities)) {\n foreach ($entities as $key2 => $val2) {\n $newentities[$key2] = $key2;\n }\n }\n }\n }\n }\n\n if (count($newentities) > 0) {\n $_SESSION['glpiactiveentities'] = $newentities;\n $_SESSION['glpiactiveentities_string'] = \"'\" . implode(\"', '\", $newentities) . \"'\";\n $active = reset($newentities);\n $_SESSION['glpiparententities'] = $ancestors;\n $_SESSION['glpiparententities_string'] = implode(\"', '\", $ancestors);\n if (!empty($_SESSION['glpiparententities_string'])) {\n $_SESSION['glpiparententities_string'] = \"'\" . $_SESSION['glpiparententities_string'] . \"'\";\n }\n // Active entity loading\n $_SESSION[\"glpiactive_entity\"] = $active;\n $_SESSION[\"glpiactive_entity_recursive\"] = $is_recursive;\n $_SESSION[\"glpiactive_entity_name\"] = Dropdown::getDropdownName(\n \"glpi_entities\",\n $active\n );\n $_SESSION[\"glpiactive_entity_shortname\"] = getTreeLeafValueName(\"glpi_entities\", $active);\n if ($ID == \"all\") {\n //TRANS: %s is the entity name\n $_SESSION[\"glpiactive_entity_name\"] = sprintf(\n __('%1$s (%2$s)'),\n $_SESSION[\"glpiactive_entity_name\"],\n __('full structure')\n );\n $_SESSION[\"glpiactive_entity_shortname\"] = sprintf(\n __('%1$s (%2$s)'),\n $_SESSION[\"glpiactive_entity_shortname\"],\n __('full structure')\n );\n } elseif ($is_recursive) {\n //TRANS: %s is the entity name\n $_SESSION[\"glpiactive_entity_name\"] = sprintf(\n __('%1$s (%2$s)'),\n $_SESSION[\"glpiactive_entity_name\"],\n __('tree structure')\n );\n $_SESSION[\"glpiactive_entity_shortname\"] = sprintf(\n __('%1$s (%2$s)'),\n $_SESSION[\"glpiactive_entity_shortname\"],\n __('tree structure')\n );\n }\n\n if (countElementsInTable('glpi_entities') <= count($_SESSION['glpiactiveentities'])) {\n $_SESSION['glpishowallentities'] = 1;\n } else {\n $_SESSION['glpishowallentities'] = 0;\n }\n // Clean session variable to search system\n if (isset($_SESSION['glpisearch']) && count($_SESSION['glpisearch'])) {\n foreach ($_SESSION['glpisearch'] as $itemtype => $tab) {\n if (isset($tab['start']) && ($tab['start'] > 0)) {\n $_SESSION['glpisearch'][$itemtype]['start'] = 0;\n }\n }\n }\n self::loadGroups();\n Plugin::doHook(Hooks::CHANGE_ENTITY);\n return true;\n }\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function getLeftToSpendInfo(Carbon $start, Carbon $end): array\n {\n Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));\n app('log')->debug('Now in getLeftToSpendInfo');\n $return = [];\n $today = today(config('app.timezone'));\n $available = $this->abRepository->getAvailableBudgetWithCurrency($start, $end);\n $budgets = $this->budgetRepository->getActiveBudgets();\n $spent = $this->opsRepository->listExpenses($start, $end, null, $budgets);\n $default = app('amount')->getDefaultCurrency();\n $currencies = [];\n $converter = new ExchangeRateConverter();\n\n // native info:\n $nativeLeft = [\n 'key' => 'left-to-spend-in-native',\n 'value' => '0',\n 'currency_id' => (string)$default->id,\n 'currency_code' => $default->code,\n 'currency_symbol' => $default->symbol,\n 'currency_decimal_places' => $default->decimal_places,\n ];\n $nativePerDay = [\n 'key' => 'left-per-day-to-spend-in-native',\n 'value' => '0',\n 'currency_id' => (string)$default->id,\n 'currency_code' => $default->code,\n 'currency_symbol' => $default->symbol,\n 'currency_decimal_places' => $default->decimal_places,\n ];\n\n /**\n * @var int $currencyId\n * @var array $row\n */\n foreach ($spent as $currencyId => $row) {\n app('log')->debug(sprintf('Processing spent array in currency #%d', $currencyId));\n $spent = '0';\n $spentNative = '0';\n\n // get the sum from the array of transactions (double loop but who cares)\n /** @var array $budget */\n foreach ($row['budgets'] as $budget) {\n app('log')->debug(sprintf('Processing expenses in budget \"%s\".', $budget['name']));\n\n /** @var array $journal */\n foreach ($budget['transaction_journals'] as $journal) {\n $journalCurrencyId = $journal['currency_id'];\n $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId);\n $currencies[$currencyId] = $currency;\n $amount = app('steam')->negative($journal['amount']);\n $amountNative = $converter->convert($default, $currency, $start, $amount);\n if ((int)$journal['foreign_currency_id'] === $default->id) {\n $amountNative = $journal['foreign_amount'];\n }\n $spent = bcadd($spent, $amount);\n $spentNative = bcadd($spentNative, $amountNative);\n }\n app('log')->debug(sprintf('Total spent in budget \"%s\" is %s', $budget['name'], $spent));\n }\n\n // either an amount was budgeted or 0 is available.\n $currency = $currencies[$currencyId] ?? $this->currencyRepos->find($currencyId);\n $currencies[$currencyId] = $currency;\n $amount = $available[$currencyId]['amount'] ?? '0';\n $amountNative = $available[$currencyId]['native_amount'] ?? '0';\n $left = bcadd($amount, $spent);\n $leftNative = bcadd($amountNative, $spentNative);\n app('log')->debug(sprintf('Available amount is %s', $amount));\n app('log')->debug(sprintf('Amount left is %s', $left));\n\n // how much left per day?\n $days = (int)$today->diffInDays($end, true) + 1;\n $perDay = '0';\n $perDayNative = '0';\n if (0 !== $days && bccomp($left, '0') > -1) {\n $perDay = bcdiv($left, (string)$days);\n }\n if (0 !== $days && bccomp($leftNative, '0') > -1) {\n $perDayNative = bcdiv($leftNative, (string)$days);\n }\n\n // left\n $return[] = [\n 'key' => sprintf('left-to-spend-in-%s', $row['currency_code']),\n 'value' => $left,\n 'currency_id' => (string)$row['currency_id'],\n 'currency_code' => $row['currency_code'],\n 'currency_symbol' => $row['currency_symbol'],\n 'currency_decimal_places' => (int)$row['currency_decimal_places'],\n ];\n // left (native)\n $nativeLeft['value'] = $leftNative;\n\n // left per day:\n $return[] = [\n 'key' => sprintf('left-per-day-to-spend-in-%s', $row['currency_code']),\n 'value' => $perDay,\n 'currency_id' => (string)$row['currency_id'],\n 'currency_code' => $row['currency_code'],\n 'currency_symbol' => $row['currency_symbol'],\n 'currency_decimal_places' => (int)$row['currency_decimal_places'],\n ];\n\n // left per day (native)\n $nativePerDay['value'] = $perDayNative;\n }\n $return[] = $nativeLeft;\n $return[] = $nativePerDay;\n $converter->summarize();\n\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "function parseInterval($str, $islist = false) {\n if (strlen($str)<5) { return false; }\n\tif ($islist) {\n\t\t$ints = preg_split('/(?<=[\\)\\]])\\s*,\\s*(?=[\\(\\[])/',$str);\n\t} else {\n\t\t$ints = explode('U',$str);\n }\n\n\t$out = array();\n\tforeach ($ints as $int) {\n $int = trim($int);\n if (strlen($int) < 5) { return false;}\n\t\t$i = array();\n\t\t$i['lb'] = $int[0];\n\t\t$i['rb'] = $int[strlen($int)-1];\n\t\t$i['vals'] = array_map('trim', explode(',', substr($int,1,-1)));\n\t\tif (count($i['vals']) != 2) {\n\t\t\treturn false;\n\t\t}\n\t\tfor ($j=0;$j<2;$j++) {\n\t\t\tif ($i['vals'][$j] == '+oo') {\n\t\t\t\t$i['vals'][$j] = 'oo';\n\t\t\t}\n\t\t\tif (!is_numeric($i['vals'][$j]) &&\n\t\t\t \t$i['vals'][$j] != 'oo' && $i['vals'][$j] != '-oo'\n\t\t\t) {\n\t\t\t\t$i['vals'][$j] = evalMathParser($i['vals'][$j]);\n\t\t\t}\n\t\t}\n\t\t$out[] = $i;\n\t}\n\treturn $out;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['url'])) {\n $this->setUrl($data['url']);\n }\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['version'])) {\n $this->setVersion($data['version']);\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['title'])) {\n $this->setTitle($data['title']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['date'])) {\n $this->setDate($data['date']);\n }\n if (isset($data['publisher'])) {\n $this->setPublisher($data['publisher']);\n }\n if (isset($data['contact'])) {\n if (is_array($data['contact'])) {\n foreach ($data['contact'] as $d) {\n $this->addContact($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"contact\" must be array of objects or null, ' . gettype($data['contact']) . ' seen.');\n }\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n if (isset($data['useContext'])) {\n if (is_array($data['useContext'])) {\n foreach ($data['useContext'] as $d) {\n $this->addUseContext($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"useContext\" must be array of objects or null, ' . gettype($data['useContext']) . ' seen.');\n }\n }\n if (isset($data['jurisdiction'])) {\n if (is_array($data['jurisdiction'])) {\n foreach ($data['jurisdiction'] as $d) {\n $this->addJurisdiction($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"jurisdiction\" must be array of objects or null, ' . gettype($data['jurisdiction']) . ' seen.');\n }\n }\n if (isset($data['copyright'])) {\n $this->setCopyright($data['copyright']);\n }\n if (isset($data['approvalDate'])) {\n $this->setApprovalDate($data['approvalDate']);\n }\n if (isset($data['lastReviewDate'])) {\n $this->setLastReviewDate($data['lastReviewDate']);\n }\n if (isset($data['effectivePeriod'])) {\n $this->setEffectivePeriod($data['effectivePeriod']);\n }\n if (isset($data['topic'])) {\n if (is_array($data['topic'])) {\n foreach ($data['topic'] as $d) {\n $this->addTopic($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"topic\" must be array of objects or null, ' . gettype($data['topic']) . ' seen.');\n }\n }\n if (isset($data['author'])) {\n if (is_array($data['author'])) {\n foreach ($data['author'] as $d) {\n $this->addAuthor($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"author\" must be array of objects or null, ' . gettype($data['author']) . ' seen.');\n }\n }\n if (isset($data['editor'])) {\n if (is_array($data['editor'])) {\n foreach ($data['editor'] as $d) {\n $this->addEditor($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"editor\" must be array of objects or null, ' . gettype($data['editor']) . ' seen.');\n }\n }\n if (isset($data['reviewer'])) {\n if (is_array($data['reviewer'])) {\n foreach ($data['reviewer'] as $d) {\n $this->addReviewer($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"reviewer\" must be array of objects or null, ' . gettype($data['reviewer']) . ' seen.');\n }\n }\n if (isset($data['endorser'])) {\n if (is_array($data['endorser'])) {\n foreach ($data['endorser'] as $d) {\n $this->addEndorser($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"endorser\" must be array of objects or null, ' . gettype($data['endorser']) . ' seen.');\n }\n }\n if (isset($data['relatedArtifact'])) {\n if (is_array($data['relatedArtifact'])) {\n foreach ($data['relatedArtifact'] as $d) {\n $this->addRelatedArtifact($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"relatedArtifact\" must be array of objects or null, ' . gettype($data['relatedArtifact']) . ' seen.');\n }\n }\n if (isset($data['synthesisType'])) {\n $this->setSynthesisType($data['synthesisType']);\n }\n if (isset($data['studyType'])) {\n $this->setStudyType($data['studyType']);\n }\n if (isset($data['population'])) {\n $this->setPopulation($data['population']);\n }\n if (isset($data['exposure'])) {\n $this->setExposure($data['exposure']);\n }\n if (isset($data['outcome'])) {\n $this->setOutcome($data['outcome']);\n }\n if (isset($data['sampleSize'])) {\n $this->setSampleSize($data['sampleSize']);\n }\n if (isset($data['riskEstimate'])) {\n $this->setRiskEstimate($data['riskEstimate']);\n }\n if (isset($data['certainty'])) {\n if (is_array($data['certainty'])) {\n foreach ($data['certainty'] as $d) {\n $this->addCertainty($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"certainty\" must be array of objects or null, ' . gettype($data['certainty']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['instantiatesCanonical'])) {\n if (is_array($data['instantiatesCanonical'])) {\n foreach ($data['instantiatesCanonical'] as $d) {\n $this->addInstantiatesCanonical($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"instantiatesCanonical\" must be array of objects or null, ' . gettype($data['instantiatesCanonical']) . ' seen.');\n }\n }\n if (isset($data['instantiatesUri'])) {\n if (is_array($data['instantiatesUri'])) {\n foreach ($data['instantiatesUri'] as $d) {\n $this->addInstantiatesUri($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"instantiatesUri\" must be array of objects or null, ' . gettype($data['instantiatesUri']) . ' seen.');\n }\n }\n if (isset($data['basedOn'])) {\n if (is_array($data['basedOn'])) {\n foreach ($data['basedOn'] as $d) {\n $this->addBasedOn($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"basedOn\" must be array of objects or null, ' . gettype($data['basedOn']) . ' seen.');\n }\n }\n if (isset($data['partOf'])) {\n if (is_array($data['partOf'])) {\n foreach ($data['partOf'] as $d) {\n $this->addPartOf($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"partOf\" must be array of objects or null, ' . gettype($data['partOf']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['statusReason'])) {\n $this->setStatusReason($data['statusReason']);\n }\n if (isset($data['category'])) {\n $this->setCategory($data['category']);\n }\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['subject'])) {\n $this->setSubject($data['subject']);\n }\n if (isset($data['encounter'])) {\n $this->setEncounter($data['encounter']);\n }\n if (isset($data['performedDateTime'])) {\n $this->setPerformedDateTime($data['performedDateTime']);\n }\n if (isset($data['performedPeriod'])) {\n $this->setPerformedPeriod($data['performedPeriod']);\n }\n if (isset($data['performedString'])) {\n $this->setPerformedString($data['performedString']);\n }\n if (isset($data['performedAge'])) {\n $this->setPerformedAge($data['performedAge']);\n }\n if (isset($data['performedRange'])) {\n $this->setPerformedRange($data['performedRange']);\n }\n if (isset($data['recorder'])) {\n $this->setRecorder($data['recorder']);\n }\n if (isset($data['asserter'])) {\n $this->setAsserter($data['asserter']);\n }\n if (isset($data['performer'])) {\n if (is_array($data['performer'])) {\n foreach ($data['performer'] as $d) {\n $this->addPerformer($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"performer\" must be array of objects or null, ' . gettype($data['performer']) . ' seen.');\n }\n }\n if (isset($data['location'])) {\n $this->setLocation($data['location']);\n }\n if (isset($data['reasonCode'])) {\n if (is_array($data['reasonCode'])) {\n foreach ($data['reasonCode'] as $d) {\n $this->addReasonCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"reasonCode\" must be array of objects or null, ' . gettype($data['reasonCode']) . ' seen.');\n }\n }\n if (isset($data['reasonReference'])) {\n if (is_array($data['reasonReference'])) {\n foreach ($data['reasonReference'] as $d) {\n $this->addReasonReference($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"reasonReference\" must be array of objects or null, ' . gettype($data['reasonReference']) . ' seen.');\n }\n }\n if (isset($data['bodySite'])) {\n if (is_array($data['bodySite'])) {\n foreach ($data['bodySite'] as $d) {\n $this->addBodySite($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"bodySite\" must be array of objects or null, ' . gettype($data['bodySite']) . ' seen.');\n }\n }\n if (isset($data['outcome'])) {\n $this->setOutcome($data['outcome']);\n }\n if (isset($data['report'])) {\n if (is_array($data['report'])) {\n foreach ($data['report'] as $d) {\n $this->addReport($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"report\" must be array of objects or null, ' . gettype($data['report']) . ' seen.');\n }\n }\n if (isset($data['complication'])) {\n if (is_array($data['complication'])) {\n foreach ($data['complication'] as $d) {\n $this->addComplication($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"complication\" must be array of objects or null, ' . gettype($data['complication']) . ' seen.');\n }\n }\n if (isset($data['complicationDetail'])) {\n if (is_array($data['complicationDetail'])) {\n foreach ($data['complicationDetail'] as $d) {\n $this->addComplicationDetail($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"complicationDetail\" must be array of objects or null, ' . gettype($data['complicationDetail']) . ' seen.');\n }\n }\n if (isset($data['followUp'])) {\n if (is_array($data['followUp'])) {\n foreach ($data['followUp'] as $d) {\n $this->addFollowUp($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"followUp\" must be array of objects or null, ' . gettype($data['followUp']) . ' seen.');\n }\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n if (isset($data['focalDevice'])) {\n if (is_array($data['focalDevice'])) {\n foreach ($data['focalDevice'] as $d) {\n $this->addFocalDevice($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"focalDevice\" must be array of objects or null, ' . gettype($data['focalDevice']) . ' seen.');\n }\n }\n if (isset($data['usedReference'])) {\n if (is_array($data['usedReference'])) {\n foreach ($data['usedReference'] as $d) {\n $this->addUsedReference($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"usedReference\" must be array of objects or null, ' . gettype($data['usedReference']) . ' seen.');\n }\n }\n if (isset($data['usedCode'])) {\n if (is_array($data['usedCode'])) {\n foreach ($data['usedCode'] as $d) {\n $this->addUsedCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"usedCode\" must be array of objects or null, ' . gettype($data['usedCode']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['instantiatesCanonical'])) {\n $this->setInstantiatesCanonical($data['instantiatesCanonical']);\n }\n if (isset($data['instantiatesUri'])) {\n $this->setInstantiatesUri($data['instantiatesUri']);\n }\n if (isset($data['basedOn'])) {\n if (is_array($data['basedOn'])) {\n foreach ($data['basedOn'] as $d) {\n $this->addBasedOn($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"basedOn\" must be array of objects or null, ' . gettype($data['basedOn']) . ' seen.');\n }\n }\n if (isset($data['groupIdentifier'])) {\n $this->setGroupIdentifier($data['groupIdentifier']);\n }\n if (isset($data['partOf'])) {\n if (is_array($data['partOf'])) {\n foreach ($data['partOf'] as $d) {\n $this->addPartOf($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"partOf\" must be array of objects or null, ' . gettype($data['partOf']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['statusReason'])) {\n $this->setStatusReason($data['statusReason']);\n }\n if (isset($data['businessStatus'])) {\n $this->setBusinessStatus($data['businessStatus']);\n }\n if (isset($data['intent'])) {\n $this->setIntent($data['intent']);\n }\n if (isset($data['priority'])) {\n $this->setPriority($data['priority']);\n }\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['focus'])) {\n $this->setFocus($data['focus']);\n }\n if (isset($data['for'])) {\n $this->setFor($data['for']);\n }\n if (isset($data['encounter'])) {\n $this->setEncounter($data['encounter']);\n }\n if (isset($data['executionPeriod'])) {\n $this->setExecutionPeriod($data['executionPeriod']);\n }\n if (isset($data['authoredOn'])) {\n $this->setAuthoredOn($data['authoredOn']);\n }\n if (isset($data['lastModified'])) {\n $this->setLastModified($data['lastModified']);\n }\n if (isset($data['requester'])) {\n $this->setRequester($data['requester']);\n }\n if (isset($data['performerType'])) {\n if (is_array($data['performerType'])) {\n foreach ($data['performerType'] as $d) {\n $this->addPerformerType($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"performerType\" must be array of objects or null, ' . gettype($data['performerType']) . ' seen.');\n }\n }\n if (isset($data['owner'])) {\n $this->setOwner($data['owner']);\n }\n if (isset($data['location'])) {\n $this->setLocation($data['location']);\n }\n if (isset($data['reasonCode'])) {\n $this->setReasonCode($data['reasonCode']);\n }\n if (isset($data['reasonReference'])) {\n $this->setReasonReference($data['reasonReference']);\n }\n if (isset($data['insurance'])) {\n if (is_array($data['insurance'])) {\n foreach ($data['insurance'] as $d) {\n $this->addInsurance($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"insurance\" must be array of objects or null, ' . gettype($data['insurance']) . ' seen.');\n }\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n if (isset($data['relevantHistory'])) {\n if (is_array($data['relevantHistory'])) {\n foreach ($data['relevantHistory'] as $d) {\n $this->addRelevantHistory($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"relevantHistory\" must be array of objects or null, ' . gettype($data['relevantHistory']) . ' seen.');\n }\n }\n if (isset($data['restriction'])) {\n $this->setRestriction($data['restriction']);\n }\n if (isset($data['input'])) {\n if (is_array($data['input'])) {\n foreach ($data['input'] as $d) {\n $this->addInput($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"input\" must be array of objects or null, ' . gettype($data['input']) . ' seen.');\n }\n }\n if (isset($data['output'])) {\n if (is_array($data['output'])) {\n foreach ($data['output'] as $d) {\n $this->addOutput($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"output\" must be array of objects or null, ' . gettype($data['output']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function (SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) use ($register) {\n App::setResource('swooleRequest', fn () => $swooleRequest);\n App::setResource('swooleResponse', fn () => $swooleResponse);\n\n $request = new Request($swooleRequest);\n $response = new Response($swooleResponse);\n\n if (Files::isFileLoaded($request->getURI())) {\n $time = (60 * 60 * 24 * 365 * 2); // 45 days cache\n\n $response\n ->setContentType(Files::getFileMimeType($request->getURI()))\n ->addHeader('Cache-Control', 'public, max-age=' . $time)\n ->addHeader('Expires', \\date('D, d M Y H:i:s', \\time() + $time) . ' GMT') // 45 days cache\n ->send(Files::getFileContents($request->getURI()));\n\n return;\n }\n\n $app = new App('UTC');\n\n $pools = $register->get('pools');\n App::setResource('pools', fn () => $pools);\n\n try {\n Authorization::cleanRoles();\n Authorization::setRole(Role::any()->toString());\n\n $app->run($request, $response);\n } catch (\\Throwable $th) {\n $version = App::getEnv('_APP_VERSION', 'UNKNOWN');\n\n $logger = $app->getResource(\"logger\");\n if ($logger) {\n try {\n /** @var Utopia\\Database\\Document $user */\n $user = $app->getResource('user');\n } catch (\\Throwable $_th) {\n // All good, user is optional information for logger\n }\n\n $loggerBreadcrumbs = $app->getResource(\"loggerBreadcrumbs\");\n $route = $app->getRoute();\n\n $log = new Utopia\\Logger\\Log();\n\n if (isset($user) && !$user->isEmpty()) {\n $log->setUser(new User($user->getId()));\n }\n\n $log->setNamespace(\"http\");\n $log->setServer(\\gethostname());\n $log->setVersion($version);\n $log->setType(Log::TYPE_ERROR);\n $log->setMessage($th->getMessage());\n\n $log->addTag('method', $route->getMethod());\n $log->addTag('url', $route->getPath());\n $log->addTag('verboseType', get_class($th));\n $log->addTag('code', $th->getCode());\n // $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant\n $log->addTag('hostname', $request->getHostname());\n $log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')));\n\n $log->addExtra('file', $th->getFile());\n $log->addExtra('line', $th->getLine());\n $log->addExtra('trace', $th->getTraceAsString());\n $log->addExtra('detailedTrace', $th->getTrace());\n $log->addExtra('roles', Authorization::getRoles());\n\n $action = $route->getLabel(\"sdk.namespace\", \"UNKNOWN_NAMESPACE\") . '.' . $route->getLabel(\"sdk.method\", \"UNKNOWN_METHOD\");\n $log->setAction($action);\n\n $isProduction = App::getEnv('_APP_ENV', 'development') === 'production';\n $log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);\n\n foreach ($loggerBreadcrumbs as $loggerBreadcrumb) {\n $log->addBreadcrumb($loggerBreadcrumb);\n }\n\n $responseCode = $logger->addLog($log);\n Console::info('Log pushed with status code: ' . $responseCode);\n }\n\n Console::error('[Error] Type: ' . get_class($th));\n Console::error('[Error] Message: ' . $th->getMessage());\n Console::error('[Error] File: ' . $th->getFile());\n Console::error('[Error] Line: ' . $th->getLine());\n\n $swooleResponse->setStatusCode(500);\n\n $output = ((App::isDevelopment())) ? [\n 'message' => 'Error: ' . $th->getMessage(),\n 'code' => 500,\n 'file' => $th->getFile(),\n 'line' => $th->getLine(),\n 'trace' => $th->getTrace(),\n 'version' => $version,\n ] : [\n 'message' => 'Error: Server Error',\n 'code' => 500,\n 'version' => $version,\n ];\n\n $swooleResponse->end(\\json_encode($output));\n } finally {\n $pools->reclaim();\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public static function exec(\n $hook_name,\n $hook_args = array(),\n $id_module = null,\n $array_return = false,\n $check_exceptions = true,\n $use_push = false,\n $id_shop = null,\n $chain = false\n ) {\n if (defined('PS_INSTALLATION_IN_PROGRESS')) {\n return;\n }\n\n $hookRegistry = self::getHookRegistry();\n $isRegistryEnabled = null !== $hookRegistry;\n\n if ($isRegistryEnabled) {\n $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);\n $hookRegistry->selectHook($hook_name, $hook_args, $backtrace[0]['file'], $backtrace[0]['line']);\n }\n\n // $chain & $array_return are incompatible so if chained is set to true, we disable the array_return option\n if (true === $chain) {\n $array_return = false;\n }\n\n static $disable_non_native_modules = null;\n if ($disable_non_native_modules === null) {\n $disable_non_native_modules = (bool) Configuration::get('PS_DISABLE_NON_NATIVE_MODULE');\n }\n\n // Check arguments validity\n if (($id_module && !is_numeric($id_module)) || !Validate::isHookName($hook_name)) {\n throw new PrestaShopException('Invalid id_module or hook_name');\n }\n\n // If no modules associated to hook_name or recompatible hook name, we stop the function\n\n if (!$module_list = Hook::getHookModuleExecList($hook_name)) {\n if ($isRegistryEnabled) {\n $hookRegistry->collect();\n }\n if ($array_return) {\n return array();\n } else {\n return '';\n }\n }\n\n // Check if hook exists\n if (!$id_hook = Hook::getIdByName($hook_name)) {\n if ($isRegistryEnabled) {\n $hookRegistry->collect();\n }\n if ($array_return) {\n return array();\n } else {\n return false;\n }\n }\n\n if (array_key_exists($hook_name, self::$deprecated_hooks)) {\n $deprecVersion = isset(self::$deprecated_hooks[$hook_name]['from']) ?\n self::$deprecated_hooks[$hook_name]['from'] :\n _PS_VERSION_;\n Tools::displayAsDeprecated('The hook ' . $hook_name . ' is deprecated in PrestaShop v.' . $deprecVersion);\n }\n\n // Store list of executed hooks on this page\n Hook::$executed_hooks[$id_hook] = $hook_name;\n\n $context = Context::getContext();\n if (!isset($hook_args['cookie']) || !$hook_args['cookie']) {\n $hook_args['cookie'] = $context->cookie;\n }\n if (!isset($hook_args['cart']) || !$hook_args['cart']) {\n $hook_args['cart'] = $context->cart;\n }\n\n // Look on modules list\n $altern = 0;\n if ($array_return) {\n $output = array();\n } else {\n $output = '';\n }\n\n if ($disable_non_native_modules && !isset(Hook::$native_module)) {\n Hook::$native_module = Module::getNativeModuleList();\n }\n\n $different_shop = false;\n if ($id_shop !== null && Validate::isUnsignedId($id_shop) && $id_shop != $context->shop->getContextShopID()) {\n $old_context = $context->shop->getContext();\n $old_shop = clone $context->shop;\n $shop = new Shop((int) $id_shop);\n if (Validate::isLoadedObject($shop)) {\n $context->shop = $shop;\n $context->shop->setContext(Shop::CONTEXT_SHOP, $shop->id);\n $different_shop = true;\n }\n }\n\n foreach ($module_list as $key => $array) {\n // Check errors\n if ($id_module && $id_module != $array['id_module']) {\n continue;\n }\n\n if ((bool) $disable_non_native_modules && Hook::$native_module && count(Hook::$native_module) && !in_array($array['module'], Hook::$native_module)) {\n continue;\n }\n\n // Check permissions\n if ($check_exceptions) {\n $exceptions = Module::getExceptionsStatic($array['id_module'], $array['id_hook']);\n\n $controller_obj = Context::getContext()->controller;\n if ($controller_obj === null) {\n $controller = null;\n } else {\n $controller = isset($controller_obj->controller_name) ?\n $controller_obj->controller_name :\n $controller_obj->php_self;\n }\n\n //check if current controller is a module controller\n if (isset($controller_obj->module) && Validate::isLoadedObject($controller_obj->module)) {\n $controller = 'module-' . $controller_obj->module->name . '-' . $controller;\n }\n\n if (in_array($controller, $exceptions)) {\n continue;\n }\n\n //Backward compatibility of controller names\n $matching_name = array(\n 'authentication' => 'auth',\n );\n if (isset($matching_name[$controller]) && in_array($matching_name[$controller], $exceptions)) {\n continue;\n }\n if (Validate::isLoadedObject($context->employee) && !Module::getPermissionStatic($array['id_module'], 'view', $context->employee)) {\n continue;\n }\n }\n\n if (!($moduleInstance = Module::getInstanceByName($array['module']))) {\n continue;\n }\n\n if ($use_push && !$moduleInstance->allow_push) {\n continue;\n }\n\n if ($isRegistryEnabled) {\n $hookRegistry->hookedByModule($moduleInstance);\n }\n\n if (Hook::isHookCallableOn($moduleInstance, $hook_name)) {\n $hook_args['altern'] = ++$altern;\n\n if ($use_push && isset($moduleInstance->push_filename) && file_exists($moduleInstance->push_filename)) {\n Tools::waitUntilFileIsModified($moduleInstance->push_filename, $moduleInstance->push_time_limit);\n }\n\n if (0 !== $key && true === $chain) {\n $hook_args = $output;\n }\n\n $display = Hook::callHookOn($moduleInstance, $hook_name, $hook_args);\n\n if ($array_return) {\n $output[$moduleInstance->name] = $display;\n } else {\n if (true === $chain) {\n $output = $display;\n } else {\n $output .= $display;\n }\n }\n if ($isRegistryEnabled) {\n $hookRegistry->hookedByCallback($moduleInstance, $hook_args);\n }\n } elseif (Hook::isDisplayHookName($hook_name)) {\n if ($moduleInstance instanceof WidgetInterface) {\n if (0 !== $key && true === $chain) {\n $hook_args = $output;\n }\n\n $display = Hook::coreRenderWidget($moduleInstance, $hook_name, $hook_args);\n\n if ($array_return) {\n $output[$moduleInstance->name] = $display;\n } else {\n if (true === $chain) {\n $output = $display;\n } else {\n $output .= $display;\n }\n }\n }\n\n if ($isRegistryEnabled) {\n $hookRegistry->hookedByWidget($moduleInstance, $hook_args);\n }\n }\n }\n\n if ($different_shop) {\n $context->shop = $old_shop;\n $context->shop->setContext($old_context, $shop->id);\n }\n\n if (true === $chain) {\n if (isset($output['cookie'])) {\n unset($output['cookie']);\n }\n if (isset($output['cart'])) {\n unset($output['cart']);\n }\n }\n\n if ($isRegistryEnabled) {\n $hookRegistry->hookWasCalled();\n $hookRegistry->collect();\n }\n\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function user_saveRepositoryCredentials($system, $new_prefs, $to_remove) {\n\n $res = false;\n\n if(is_string($new_prefs)){\n $new_prefs = json_decode($new_prefs, true);\n }\n\n if(isEmptyArray($new_prefs) && isEmptyArray($to_remove)) {\n\n $system->addError(HEURIST_INVALID_REQUEST, 'Data to update repository configuration are not defined');\n return false;\n }\n\n //get groups for current user\n $wg_ids = array();\n $currentUser = $system->getCurrentUser();\n if($currentUser && @$currentUser['ugr_ID']>0)\n {\n if(@$currentUser['ugr_Groups']){\n $wg_ids = array_keys($currentUser['ugr_Groups']);\n }\n array_push($wg_ids, $currentUser['ugr_ID']);\n }else{\n $system->addError(HEURIST_REQUEST_DENIED);\n return false;\n }\n\n\n if($system->is_admin()){\n // be sure to include the generic everybody workgroup\n array_push($wg_ids, 0);\n }\n\n $mysqli = $system->get_mysqli();\n\n //prepare services - group by group/user ids\n $prepared = array();\n\n if(is_array($new_prefs)){\n foreach($new_prefs as $service_id=>$service){\n if(in_array($service['usr_ID'], $wg_ids)){\n $usr_ID = intval($service['usr_ID']);\n if(!@$prepared[$usr_ID]) {$prepared[$usr_ID] = array();}\n\n $prepared[$usr_ID][$service_id] = $service;\n }\n }\n }\n\n if(is_array($to_remove)){\n foreach($to_remove as $service_id){\n\n $parts = explode('_',$service_id);\n $usr_ID = end($parts);\n\n if(!@$prepared[$usr_ID][$service_id] && in_array($usr_ID, $wg_ids)){\n //new value does not exists\n $prepared[$usr_ID][$service_id] = 'delete';\n }\n }\n }\n\n //save into database\n if(empty($prepared)){\n $system->addError(HEURIST_INVALID_REQUEST, 'Data to update repository configuration are not defined');\n return false;\n }\n\n foreach($prepared as $usr_ID=>$services){\n\n $prefs = mysql__select_value( $mysqli, 'select ugr_Preferences from sysUGrps where ugr_ID='.$usr_ID);\n if($prefs!=null && $prefs!=''){\n $prefs = json_decode($prefs, true);\n }\n if($prefs==null || count($prefs)===0){\n $prefs = array();\n }\n\n $curr_services = @$prefs['externalRepositories'];\n //if password is not set take passwords from current settings\n foreach($services as $service_id=>$service){\n if(is_array($to_remove) && in_array($service_id,$to_remove)){\n\n if($service=='delete'){\n unset($services[$service_id]);\n }\n continue; //do not take password from the existing one - it was removed\n }\n /*\n if(!isEmptyArray($curr_services)){\n if(@$curr_services[$service_id]['params']['writePwd']){ //old passsword exists\n if(!@$service['params']['writePwd']){ //new password not defined\n $services[$service_id]['params']['writePwd'] = $curr_services[$service_id]['params']['writePwd'];\n }\n }\n if(@$curr_services[$service_id]['params']['readPwd']){ //old passsword exists\n if(!@$service['params']['readPwd']){ //new password not defined\n $services[$service_id]['params']['readPwd'] = $curr_services[$service_id]['params']['readPwd'];\n }\n }\n }*/\n }\n\n if(empty($services)){\n if(@$prefs['externalRepositories']){\n unset($prefs['externalRepositories']);\n }\n }else{\n $prefs['externalRepositories'] = $services;\n }\n\n //$res = mysql__insertupdate( $mysqli, 'sysUGrps', 'ugr', array(\n // 'ugr_ID'=>$usr_ID,\n // 'ugr_Preferences'=>json_encode($prefs) ));\n\n $res = mysql__exec_param_query($mysqli,\n 'UPDATE `sysUGrps` set ugr_Preferences=? WHERE ugr_ID='.$usr_ID,\n array('s', (empty($prefs)?'':json_encode($prefs))));\n\n if(!$res){\n break;\n }\n\n }//for\n\n return $res;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->type)) {\n $json['type'] = $this->type;\n }\n if (isset($this->orderable)) {\n $json['orderable'] = $this->orderable;\n }\n if (isset($this->referencedItem)) {\n $json['referencedItem'] = $this->referencedItem;\n }\n if (0 < count($this->additionalIdentifier)) {\n $json['additionalIdentifier'] = [];\n foreach ($this->additionalIdentifier as $additionalIdentifier) {\n $json['additionalIdentifier'][] = $additionalIdentifier;\n }\n }\n if (0 < count($this->classification)) {\n $json['classification'] = [];\n foreach ($this->classification as $classification) {\n $json['classification'][] = $classification;\n }\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->validityPeriod)) {\n $json['validityPeriod'] = $this->validityPeriod;\n }\n if (isset($this->validTo)) {\n $json['validTo'] = $this->validTo;\n }\n if (isset($this->lastUpdated)) {\n $json['lastUpdated'] = $this->lastUpdated;\n }\n if (0 < count($this->additionalCharacteristic)) {\n $json['additionalCharacteristic'] = [];\n foreach ($this->additionalCharacteristic as $additionalCharacteristic) {\n $json['additionalCharacteristic'][] = $additionalCharacteristic;\n }\n }\n if (0 < count($this->additionalClassification)) {\n $json['additionalClassification'] = [];\n foreach ($this->additionalClassification as $additionalClassification) {\n $json['additionalClassification'][] = $additionalClassification;\n }\n }\n if (0 < count($this->relatedEntry)) {\n $json['relatedEntry'] = [];\n foreach ($this->relatedEntry as $relatedEntry) {\n $json['relatedEntry'][] = $relatedEntry;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private function getPathSchemas(RoutePath $route_path): array\n {\n $path_schemas = [];\n $route_methods = $route_path->getRouteMethods();\n\n foreach ($route_methods as $route_method) {\n $route_doc = $route_path->getRouteDoc($route_method);\n $method = strtolower($route_method);\n $response_schema = $this->getPathResponseSchemas($route_path, $route_method);\n $path_schema = [\n 'tags' => $route_path->getRouteTags(),\n 'responses' => $response_schema,\n ];\n\n $default_responses = [\n '200' => [\n 'description' => 'Success',\n 'methods' => ['GET', 'PATCH'] // Usually only GET and PATCH methods return 200\n ],\n '201' => [\n 'description' => 'Success (created)',\n 'methods' => ['POST'],\n 'headers' => [\n 'Location' => [\n 'description' => 'The URL of the newly created resource',\n 'schema' => [\n 'type' => 'string'\n ]\n ]\n ],\n 'content' => [\n 'application/json' => [\n 'schema' => [\n 'type' => 'object',\n 'properties' => [\n 'id' => [\n 'type' => 'integer',\n 'format' => 'int64'\n ],\n 'href' => [\n 'type' => 'string'\n ]\n ]\n ]\n ]\n ]\n ],\n '204' => [\n 'description' => 'Success (no content)',\n 'methods' => ['DELETE']\n ],\n '400' => [\n 'description' => 'Bad request',\n ],\n '401' => [\n 'description' => 'Unauthorized',\n ],\n '403' => [\n 'description' => 'Forbidden',\n ],\n '404' => [\n 'description' => 'Not found',\n ],\n '500' => [\n 'description' => 'Internal server error',\n ],\n ];\n\n foreach ($default_responses as $code => $info) {\n if (isset($info['methods']) && !in_array(strtoupper($method), $info['methods'], true)) {\n continue;\n }\n if (!isset($path_schema['responses'][$code])) {\n $path_schema['responses'][$code] = [\n 'description' => $info['description'],\n ];\n if (isset($info['headers'])) {\n $path_schema['responses'][$code]['headers'] = $info['headers'];\n }\n if (isset($info['content'])) {\n $path_schema['responses'][$code]['content'] = $info['content'];\n }\n }\n }\n\n $request_body = $this->getRequestBodySchema($route_path, $route_method);\n\n if ($route_doc !== null) {\n $path_schema['description'] = $route_doc->getDescription();\n }\n\n $requirements = $route_path->getRouteRequirements();\n $path_schema['parameters'] = [];\n if ($route_doc !== null) {\n $route_params = $route_doc->getParameters();\n if (count($route_params) > 0) {\n foreach ($route_params as $route_param) {\n $location = $route_param->getLocation();\n if ($location !== Doc\\Parameter::LOCATION_BODY) {\n if ($location !== Doc\\Parameter::LOCATION_PATH || (array_key_exists($route_param->getName(), $requirements) && str_contains($route_path->getRoutePath(), '{' . $route_param->getName() . '}'))) {\n $path_schema['parameters'][$route_param->getName()] = $this->getPathParameterSchema($route_param);\n }\n }\n }\n }\n }\n if (count($requirements)) {\n foreach ($requirements as $name => $requirement) {\n if (!str_contains($route_path->getRoutePath(), '{' . $name . '}')) {\n continue;\n }\n if (is_callable($requirement)) {\n $values = $requirement();\n $requirement = implode('|', $values);\n }\n if ($requirement === '\\d+') {\n $param = [\n 'name' => $name,\n 'in' => 'path',\n 'required' => true,\n 'schema' => [\n 'type' => 'integer',\n 'pattern' => $requirement\n ]\n ];\n } else {\n $param = [\n 'name' => $name,\n 'in' => 'path',\n 'required' => true,\n 'schema' => [\n 'type' => 'string',\n 'pattern' => $requirement\n ]\n ];\n }\n\n $existing = $path_schema['parameters'][$param['name']] ?? [];\n $in = $existing['in'] ?? $param['in'];\n $path_schema['parameters'][$param['name']] = [\n 'name' => $existing['name'] ?? $param['name'],\n 'description' => $existing['description'] ?? '',\n 'in' => $in,\n 'required' => $in === Doc\\Parameter::LOCATION_PATH ? true : ($existing['required'] ?? $param['required']),\n ];\n /** @var SchemaArray $combined_schema */\n $combined_schema = $param['schema'];\n if (!empty($existing['schema'])) {\n $combined_schema = array_replace($existing['schema'], $param['schema']);\n }\n $path_schema['parameters'][$param['name']]['schema'] = $combined_schema;\n }\n }\n // Inject global headers\n if ($route_path->getRouteSecurityLevel() !== Route::SECURITY_NONE) {\n $path_schema['parameters']['GLPI-Entity'] = [\n 'name' => 'GLPI-Entity',\n 'in' => 'header',\n 'description' => 'The ID of the entity to use. If not specified, the default entity for the user is used.',\n 'schema' => ['type' => Schema::TYPE_INTEGER]\n ];\n $path_schema['parameters']['GLPI-Profile'] = [\n 'name' => 'GLPI-Profile',\n 'in' => 'header',\n 'description' => 'The ID of the profile to use. If not specified, the default profile for the user is used.',\n 'schema' => ['type' => Schema::TYPE_INTEGER]\n ];\n $path_schema['parameters']['GLPI-Entity-Recursive'] = [\n 'name' => 'GLPI-Entity-Recursive',\n 'in' => 'header',\n 'description' => '\"true\" if the entity access should include child entities. This is false by default.',\n 'schema' => [\n 'type' => Schema::TYPE_STRING,\n 'enum' => ['true', 'false']\n ],\n ];\n }\n // Language can always be specified, even if it may not always be respected if no temporary session is started\n $path_schema['parameters']['Accept-Language'] = [\n 'name' => 'Accept-Language',\n 'in' => 'header',\n 'description' => 'The language to use for the response. If not specified, the default language for the user is used.',\n 'schema' => ['type' => Schema::TYPE_STRING],\n 'examples' => [\n 'English_GB' => [\n 'value' => 'en_GB',\n 'summary' => 'English (United Kingdom)'\n ],\n 'French_FR' => [\n 'value' => 'fr_FR',\n 'summary' => 'French (France)'\n ],\n 'Portuguese_BR' => [\n 'value' => 'pt_BR',\n 'summary' => 'Portuguese (Brazil)'\n ],\n ]\n ];\n\n if (strcasecmp($method, 'delete') && $request_body !== null) {\n $path_schema['requestBody'] = $request_body;\n }\n $path_schema['security'] = $this->getPathSecuritySchema($route_path, $route_method);\n $path_schema['parameters'] = array_values($path_schema['parameters']);\n $path_schema['x-controller'] = $route_path->getController();\n $path_schemas[$method] = $path_schema;\n }\n return [\n $route_path->getRoutePath() => $path_schemas\n ];\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function deleteAttribute(Document $database, Document $collection, Document $attribute, Document $project): void\n {\n $projectId = $project->getId();\n $dbForConsole = $this->getConsoleDB();\n $dbForProject = $this->getProjectDB($project);\n\n $events = Event::generateEvents('databases.[databaseId].collections.[collectionId].attributes.[attributeId].delete', [\n 'databaseId' => $database->getId(),\n 'collectionId' => $collection->getId(),\n 'attributeId' => $attribute->getId()\n ]);\n $collectionId = $collection->getId();\n $key = $attribute->getAttribute('key', '');\n $status = $attribute->getAttribute('status', '');\n $type = $attribute->getAttribute('type', '');\n $project = $dbForConsole->getDocument('projects', $projectId);\n $options = $attribute->getAttribute('options', []);\n $relatedAttribute = new Document();\n $relatedCollection = new Document();\n // possible states at this point:\n // - available: should not land in queue; controller flips these to 'deleting'\n // - processing: hasn't finished creating\n // - deleting: was available, in deletion queue for first time\n // - failed: attribute was never created\n // - stuck: attribute was available but cannot be removed\n\n try {\n if ($status !== 'failed') {\n if ($type === Database::VAR_RELATIONSHIP) {\n if ($options['twoWay']) {\n $relatedCollection = $dbForProject->getDocument('database_' . $database->getInternalId(), $options['relatedCollection']);\n if ($relatedCollection->isEmpty()) {\n throw new DatabaseException('Collection not found');\n }\n $relatedAttribute = $dbForProject->getDocument('attributes', $database->getInternalId() . '_' . $relatedCollection->getInternalId() . '_' . $options['twoWayKey']);\n }\n\n if (!$dbForProject->deleteRelationship('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key)) {\n $dbForProject->updateDocument('attributes', $relatedAttribute->getId(), $relatedAttribute->setAttribute('status', 'stuck'));\n throw new DatabaseException('Failed to delete Relationship');\n }\n } elseif (!$dbForProject->deleteAttribute('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key)) {\n throw new DatabaseException('Failed to delete Attribute');\n }\n }\n\n $dbForProject->deleteDocument('attributes', $attribute->getId());\n\n if (!$relatedAttribute->isEmpty()) {\n $dbForProject->deleteDocument('attributes', $relatedAttribute->getId());\n }\n } catch (\\Exception $e) {\n Console::error($e->getMessage());\n\n if ($e instanceof DatabaseException) {\n $attribute->setAttribute('error', $e->getMessage());\n if (!$relatedAttribute->isEmpty()) {\n $relatedAttribute->setAttribute('error', $e->getMessage());\n }\n }\n $dbForProject->updateDocument(\n 'attributes',\n $attribute->getId(),\n $attribute->setAttribute('status', 'stuck')\n );\n if (!$relatedAttribute->isEmpty()) {\n $dbForProject->updateDocument(\n 'attributes',\n $relatedAttribute->getId(),\n $relatedAttribute->setAttribute('status', 'stuck')\n );\n }\n } finally {\n $target = Realtime::fromPayload(\n // Pass first, most verbose event pattern\n event: $events[0],\n payload: $attribute,\n project: $project\n );\n\n Realtime::send(\n projectId: 'console',\n payload: $attribute->getArrayCopy(),\n events: $events,\n channels: $target['channels'],\n roles: $target['roles'],\n options: [\n 'projectId' => $projectId,\n 'databaseId' => $database->getId(),\n 'collectionId' => $collection->getId()\n ]\n );\n }\n\n // The underlying database removes/rebuilds indexes when attribute is removed\n // Update indexes table with changes\n /** @var Document[] $indexes */\n $indexes = $collection->getAttribute('indexes', []);\n\n foreach ($indexes as $index) {\n /** @var string[] $attributes */\n $attributes = $index->getAttribute('attributes');\n $lengths = $index->getAttribute('lengths');\n $orders = $index->getAttribute('orders');\n\n $found = \\array_search($key, $attributes);\n\n if ($found !== false) {\n // If found, remove entry from attributes, lengths, and orders\n // array_values wraps array_diff to reindex array keys\n // when found attribute is removed from array\n $attributes = \\array_values(\\array_diff($attributes, [$attributes[$found]]));\n $lengths = \\array_values(\\array_diff($lengths, isset($lengths[$found]) ? [$lengths[$found]] : []));\n $orders = \\array_values(\\array_diff($orders, isset($orders[$found]) ? [$orders[$found]] : []));\n\n if (empty($attributes)) {\n $dbForProject->deleteDocument('indexes', $index->getId());\n } else {\n $index\n ->setAttribute('attributes', $attributes, Document::SET_TYPE_ASSIGN)\n ->setAttribute('lengths', $lengths, Document::SET_TYPE_ASSIGN)\n ->setAttribute('orders', $orders, Document::SET_TYPE_ASSIGN);\n\n // Check if an index exists with the same attributes and orders\n $exists = false;\n foreach ($indexes as $existing) {\n if (\n $existing->getAttribute('key') !== $index->getAttribute('key') // Ignore itself\n && $existing->getAttribute('attributes') === $index->getAttribute('attributes')\n && $existing->getAttribute('orders') === $index->getAttribute('orders')\n ) {\n $exists = true;\n break;\n }\n }\n\n if ($exists) { // Delete the duplicate if created, else update in db\n $this->deleteIndex($database, $collection, $index, $project);\n } else {\n $dbForProject->updateDocument('indexes', $index->getId(), $index);\n }\n }\n }\n }\n\n $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $collectionId);\n $dbForProject->deleteCachedCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId());\n\n if (!$relatedCollection->isEmpty() && !$relatedAttribute->isEmpty()) {\n $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $relatedCollection->getId());\n $dbForProject->deleteCachedCollection('database_' . $database->getInternalId() . '_collection_' . $relatedCollection->getInternalId());\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function removeOverride($classname)\n {\n $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');\n\n if ($orig_path && !$file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {\n return true;\n } elseif (!$orig_path && Module::getModuleIdByName($classname)) {\n $path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';\n }\n\n // Check if override file is writable\n if ($orig_path) {\n $override_path = _PS_ROOT_DIR_ . '/' . $file;\n } else {\n $override_path = _PS_OVERRIDE_DIR_ . $path;\n }\n\n if (!is_file($override_path)) {\n return true;\n }\n\n if (!is_writable($override_path)) {\n return false;\n }\n\n file_put_contents($override_path, preg_replace('#(\\r\\n|\\r)#ism', \"\\n\", file_get_contents($override_path)));\n\n if ($orig_path) {\n // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration\n do {\n $uniq = uniqid();\n } while (class_exists($classname . 'OverrideOriginal_remove', false));\n\n // Make a reflection of the override class and the module override class\n $override_file = file($override_path);\n\n eval(\n preg_replace(\n ['#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'],\n [' ', 'class ' . $classname . 'OverrideOriginal_remove' . $uniq . ' extends \\stdClass'],\n implode('', $override_file)\n )\n );\n $override_class = new ReflectionClass($classname . 'OverrideOriginal_remove' . $uniq);\n\n $module_file = file($this->getLocalPath() . 'override/' . $path);\n eval(\n preg_replace(\n ['#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'],\n [' ', 'class ' . $classname . 'Override_remove' . $uniq . ' extends \\stdClass'],\n implode('', $module_file)\n )\n );\n $module_class = new ReflectionClass($classname . 'Override_remove' . $uniq);\n\n // Remove methods from override file\n foreach ($module_class->getMethods() as $method) {\n if (!$override_class->hasMethod($method->getName())) {\n continue;\n }\n\n $method = $override_class->getMethod($method->getName());\n $length = $method->getEndLine() - $method->getStartLine() + 1;\n\n $module_method = $module_class->getMethod($method->getName());\n $module_length = $module_method->getEndLine() - $module_method->getStartLine() + 1;\n\n $override_file_orig = $override_file;\n\n $orig_content = preg_replace('/\\s/', '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad([], $length, '#--remove--#'))));\n $module_content = preg_replace('/\\s/', '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $length, array_pad([], $length, '#--remove--#'))));\n\n $replace = true;\n if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$method->getStartLine() - 5])) {\n $override_file[$method->getStartLine() - 6] = $override_file[$method->getStartLine() - 5] = $override_file[$method->getStartLine() - 4] = $override_file[$method->getStartLine() - 3] = $override_file[$method->getStartLine() - 2] = '#--remove--#';\n $replace = false;\n }\n\n if (md5($module_content) != md5($orig_content) && $replace) {\n $override_file = $override_file_orig;\n }\n }\n\n // Remove properties from override file\n foreach ($module_class->getProperties() as $property) {\n if (!$override_class->hasProperty($property->getName())) {\n continue;\n }\n\n // Replace the declaration line by #--remove--#\n foreach ($override_file as $line_number => &$line_content) {\n if (preg_match('/(public|private|protected)\\s+(static\\s+)?(\\$)?' . $property->getName() . '/i', $line_content)) {\n if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$line_number - 4])) {\n $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = $override_file[$line_number - 1] = '#--remove--#';\n }\n $line_content = '#--remove--#';\n\n break;\n }\n }\n }\n\n // Remove properties from override file\n foreach ($module_class->getConstants() as $constant => $value) {\n if (!$override_class->hasConstant($constant)) {\n continue;\n }\n\n // Replace the declaration line by #--remove--#\n foreach ($override_file as $line_number => &$line_content) {\n if (preg_match('/(const)\\s+(static\\s+)?(\\$)?' . $constant . '/i', $line_content)) {\n if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$line_number - 4])) {\n $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = $override_file[$line_number - 1] = '#--remove--#';\n }\n $line_content = '#--remove--#';\n\n break;\n }\n }\n }\n\n $count = count($override_file);\n for ($i = 0; $i < $count; ++$i) {\n if (preg_match('/(^\\s*\\/\\/.*)/i', $override_file[$i])) {\n $override_file[$i] = '#--remove--#';\n } elseif (preg_match('/(^\\s*\\/\\*)/i', $override_file[$i])) {\n if (!preg_match('/(^\\s*\\* module:)/i', $override_file[$i + 1])\n && !preg_match('/(^\\s*\\* date:)/i', $override_file[$i + 2])\n && !preg_match('/(^\\s*\\* version:)/i', $override_file[$i + 3])\n && !preg_match('/(^\\s*\\*\\/)/i', $override_file[$i + 4])) {\n for (; $override_file[$i] && !preg_match('/(.*?\\*\\/)/i', $override_file[$i]); ++$i) {\n $override_file[$i] = '#--remove--#';\n }\n $override_file[$i] = '#--remove--#';\n }\n }\n }\n\n // Rewrite nice code\n $code = '';\n foreach ($override_file as $line) {\n if ($line == '#--remove--#') {\n continue;\n }\n\n $code .= $line;\n }\n\n $to_delete = preg_match('/<\\?(?:php)?\\s+(?:abstract|interface)?\\s*?class\\s+' . $classname . '\\s+extends\\s+' . $classname . 'Core\\s*?[{]\\s*?[}]/ism', $code);\n }\n\n if (!isset($to_delete) || $to_delete) {\n unlink($override_path);\n } else {\n file_put_contents($override_path, $code);\n }\n\n // Re-generate the class index\n Tools::generateIndex();\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<Consent xmlns=\"http://hl7.org/fhir\"></Consent>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->status)) {\n $this->status->xmlSerialize(true, $sxe->addChild('status'));\n }\n if (isset($this->scope)) {\n $this->scope->xmlSerialize(true, $sxe->addChild('scope'));\n }\n if (0 < count($this->category)) {\n foreach ($this->category as $category) {\n $category->xmlSerialize(true, $sxe->addChild('category'));\n }\n }\n if (isset($this->patient)) {\n $this->patient->xmlSerialize(true, $sxe->addChild('patient'));\n }\n if (isset($this->dateTime)) {\n $this->dateTime->xmlSerialize(true, $sxe->addChild('dateTime'));\n }\n if (0 < count($this->performer)) {\n foreach ($this->performer as $performer) {\n $performer->xmlSerialize(true, $sxe->addChild('performer'));\n }\n }\n if (0 < count($this->organization)) {\n foreach ($this->organization as $organization) {\n $organization->xmlSerialize(true, $sxe->addChild('organization'));\n }\n }\n if (isset($this->sourceAttachment)) {\n $this->sourceAttachment->xmlSerialize(true, $sxe->addChild('sourceAttachment'));\n }\n if (isset($this->sourceReference)) {\n $this->sourceReference->xmlSerialize(true, $sxe->addChild('sourceReference'));\n }\n if (0 < count($this->policy)) {\n foreach ($this->policy as $policy) {\n $policy->xmlSerialize(true, $sxe->addChild('policy'));\n }\n }\n if (isset($this->policyRule)) {\n $this->policyRule->xmlSerialize(true, $sxe->addChild('policyRule'));\n }\n if (0 < count($this->verification)) {\n foreach ($this->verification as $verification) {\n $verification->xmlSerialize(true, $sxe->addChild('verification'));\n }\n }\n if (isset($this->provision)) {\n $this->provision->xmlSerialize(true, $sxe->addChild('provision'));\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function mediaQuery(&$out)\n {\n $expressions = null;\n $parts = [];\n\n if (\n ($this->literal('only', 4) && ($only = true) ||\n $this->literal('not', 3) && ($not = true) || true) &&\n $this->mixedKeyword($mediaType)\n ) {\n $prop = [Type::T_MEDIA_TYPE];\n\n if (isset($only)) {\n $prop[] = [Type::T_KEYWORD, 'only'];\n }\n\n if (isset($not)) {\n $prop[] = [Type::T_KEYWORD, 'not'];\n }\n\n $media = [Type::T_LIST, '', []];\n\n foreach ((array) $mediaType as $type) {\n if (\\is_array($type)) {\n $media[2][] = $type;\n } else {\n $media[2][] = [Type::T_KEYWORD, $type];\n }\n }\n\n $prop[] = $media;\n $parts[] = $prop;\n }\n\n if (empty($parts) || $this->literal('and', 3)) {\n $this->genericList($expressions, 'mediaExpression', 'and', false);\n\n if (\\is_array($expressions)) {\n $parts = array_merge($parts, $expressions[2]);\n }\n }\n\n $out = $parts;\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function mergeSettingsForSiteAccessGroup(\n int $options,\n array $defaultSettings,\n array $scopeSettings,\n array $globalSettings\n ): array {\n if ($options & static::MERGE_FROM_SECOND_LEVEL) {\n $mergedSettings = [];\n\n // array_merge() has to be used because we don't\n // know whether we have a hash or a plain array\n $keys = array_unique(\n array_merge(\n array_keys($defaultSettings),\n array_keys($scopeSettings),\n array_keys($globalSettings)\n )\n );\n foreach ($keys as $key) {\n // Only merge if actual setting is an array.\n // We assume default setting to be a clear reference for this.\n // If the setting is not an array, we copy the right value, in respect to the precedence:\n // 1. global\n // 3. Group\n // 4. default\n if (array_key_exists($key, $defaultSettings) && !is_array($defaultSettings[$key])) {\n if (array_key_exists($key, $globalSettings)) {\n $mergedSettings[$key] = $globalSettings[$key];\n } elseif (array_key_exists($key, $scopeSettings)) {\n $mergedSettings[$key] = $scopeSettings[$key];\n } else {\n $mergedSettings[$key] = $defaultSettings[$key];\n }\n } else {\n $mergedSettings[$key] = array_merge(\n $defaultSettings[$key] ?? [],\n $scopeSettings[$key] ?? [],\n $globalSettings[$key] ?? []\n );\n }\n }\n } else {\n $mergedSettings = array_merge(\n $defaultSettings,\n $scopeSettings,\n $globalSettings\n );\n }\n if ($options & static::UNIQUE) {\n $mergedSettings = array_values(\n array_unique($mergedSettings)\n );\n }\n\n return $mergedSettings;\n }", "smellKey": "S3776", "smellId": null, "repo": "ezsystems_ezplatform-kernel", "language": "php"} {"function": "public function getITILTemplateToUse(\n $force_template = 0,\n $type = null,\n $itilcategories_id = 0,\n $entities_id = -1\n ) {\n if (!$type && $this->getType() != Ticket::getType()) {\n $type = true;\n }\n // Load template if available :\n $tplclass = static::getTemplateClass();\n $tt = new $tplclass();\n $template_loaded = false;\n\n if ($force_template) {\n // with type and categ\n if ($tt->getFromDBWithData($force_template, true)) {\n $template_loaded = true;\n }\n }\n\n if (\n !$template_loaded\n && $type\n && $itilcategories_id\n ) {\n $categ = new ITILCategory();\n if ($categ->getFromDB($itilcategories_id)) {\n $field = $this->getTemplateFieldName($type);\n\n if (!empty($categ->fields[$field]) && $categ->fields[$field]) {\n // without type and categ\n if ($tt->getFromDBWithData($categ->fields[$field], false)) {\n $template_loaded = true;\n }\n }\n }\n }\n\n // If template loaded from type and category do not check after\n if ($template_loaded) {\n return $tt;\n }\n\n //Get template from profile\n if (!$template_loaded && $type) {\n $field = $this->getTemplateFieldName($type);\n $field = str_replace(['_incident', '_demand'], ['', ''], $field);\n // load default profile one if not already loaded\n if (\n isset($_SESSION['glpiactiveprofile'][$field])\n && $_SESSION['glpiactiveprofile'][$field]\n ) {\n // with type and categ\n if (\n $tt->getFromDBWithData(\n $_SESSION['glpiactiveprofile'][$field],\n true\n )\n ) {\n $template_loaded = true;\n }\n }\n }\n\n //Get template from entity\n if (\n !$template_loaded\n && ($entities_id >= 0)\n ) {\n // load default entity one if not already loaded\n $template_id = Entity::getUsedConfig(\n strtolower($this->getType()) . 'templates_strategy',\n $entities_id,\n strtolower($this->getType()) . 'templates_id',\n 0\n );\n if ($template_id > 0 && $tt->getFromDBWithData($template_id, true)) {\n $template_loaded = true;\n }\n }\n\n // Check if profile / entity set type and category and try to load template for these values\n if ($template_loaded) { // template loaded for profile or entity\n $newtype = $type;\n $newitilcategories_id = $itilcategories_id;\n // Get predefined values for ticket template\n if (isset($tt->predefined['itilcategories_id']) && $tt->predefined['itilcategories_id']) {\n $newitilcategories_id = $tt->predefined['itilcategories_id'];\n }\n if (isset($tt->predefined['type']) && $tt->predefined['type']) {\n $newtype = $tt->predefined['type'];\n }\n if (\n $newtype\n && $newitilcategories_id\n ) {\n $categ = new ITILCategory();\n if ($categ->getFromDB($newitilcategories_id)) {\n $field = $this->getTemplateFieldName($newtype);\n\n if (isset($categ->fields[$field]) && $categ->fields[$field]) {\n // without type and categ\n if ($tt->getFromDBWithData($categ->fields[$field], false)) {\n $template_loaded = true;\n }\n }\n }\n }\n }\n return $tt;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function action_shipping() {\n $this->restrictActions(CartModel::STEP_SHIPPING);\n\n $service = $this->pixie->cart;\n $customerAddresses = $service->getAddresses();\n\n if ($this->request->is_ajax()) {\n $this->checkCsrfToken('checkout_step2', null, false);\n\n $post = $this->request->postWrap();\n $addressId = $post['address_id']->raw() ? $post['address_id'] : $post['address_id']->copy(0);\n\n if ($post['full_form'] && $post['full_form']->raw()) {\n /** @var CustomerAddress $address */\n $address = $this->pixie->orm->get('CustomerAddress');\n $address->createFromArray($post);\n\n if ($addressId->raw()) {\n $existingAddress = $this->getAddressForUid($addressId->raw());\n\n if ($existingAddress->isSimilarTo($address)) {\n $service->setShippingAddressUid($addressId->raw());\n $service->setShippingAddress($existingAddress);\n\n } else {\n $service->setShippingAddressUid(null);\n $service->setShippingAddress($address);\n }\n\n } else {\n $service->setShippingAddressUid(null);\n $service->setShippingAddress($address);\n }\n\n } else {\n if ($addressId->raw()) {\n $existingAddress = $this->getAddressForUid($addressId->raw());\n\n if ($existingAddress) {\n $service->setShippingAddressUid($addressId->raw());\n $service->setShippingAddress($existingAddress);\n\n } else {\n throw new NotFoundException();\n }\n\n } else {\n throw new NotFoundException();\n }\n }\n\n $service->updateLastStep(CartModel::STEP_BILLING);\n $this->execute = false;\n\n } else {\n $this->prepareShippingAndBillingAddresses($service, $customerAddresses);\n\n $this->view->subview = 'cart/shipping';\n $this->view->tab = 'shipping';//active tab\n $this->view->step = $service->getStepLabel();//last step\n $currentAddress = $service->getShippingAddress();\n $this->view->shippingAddress = !$currentAddress ? [] : $currentAddress->as_array();\n $this->view->customerAddresses = $customerAddresses;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "xatziandreoy_hackazon", "language": "php"} {"function": "public function hasUpdated($path, $time) {\n\t\t$this->init();\n\t\t$path = $this->cleanPath($path);\n\t\ttry {\n\t\t\t// force refresh for $path\n\t\t\t$this->statCache->remove($path);\n\t\t\t$response = $this->propfind($path);\n\t\t\tif ($response === false) {\n\t\t\t\tif ($path === '') {\n\t\t\t\t\t// if root is gone it means the storage is not available\n\t\t\t\t\tthrow new StorageNotAvailableException('root is gone');\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (isset($response['{DAV:}getetag'])) {\n\t\t\t\t$cachedData = $this->getCache()->get($path);\n\t\t\t\t$etag = trim($response['{DAV:}getetag'], '\"');\n\t\t\t\tif (($cachedData === false) || (!empty($etag) && ($cachedData['etag'] !== $etag))) {\n\t\t\t\t\treturn true;\n\t\t\t\t} elseif (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {\n\t\t\t\t\t$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];\n\t\t\t\t\treturn $sharePermissions !== $cachedData['permissions'];\n\t\t\t\t} elseif (isset($response['{http://owncloud.org/ns}permissions'])) {\n\t\t\t\t\t$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);\n\t\t\t\t\treturn $permissions !== $cachedData['permissions'];\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} elseif (isset($response['{DAV:}getlastmodified'])) {\n\t\t\t\t$remoteMtime = strtotime($response['{DAV:}getlastmodified']);\n\t\t\t\treturn $remoteMtime > $time;\n\t\t\t} else {\n\t\t\t\t// neither `getetag` nor `getlastmodified` is set\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (ClientHttpException $e) {\n\t\t\tif ($e->getHttpStatus() === 405) {\n\t\t\t\tif ($path === '') {\n\t\t\t\t\t// if root is gone it means the storage is not available\n\t\t\t\t\tthrow new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t$this->convertException($e, $path);\n\t\t\treturn false;\n\t\t} catch (\\Exception $e) {\n\t\t\t$this->convertException($e, $path);\n\t\t\treturn false;\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['extends'])) {\n $this->setExtends($data['extends']);\n }\n if (isset($data['typeMode'])) {\n $this->setTypeMode($data['typeMode']);\n }\n if (isset($data['documentation'])) {\n $this->setDocumentation($data['documentation']);\n }\n if (isset($data['input'])) {\n if (is_array($data['input'])) {\n foreach ($data['input'] as $d) {\n $this->addInput($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"input\" must be array of objects or null, ' . gettype($data['input']) . ' seen.');\n }\n }\n if (isset($data['rule'])) {\n if (is_array($data['rule'])) {\n foreach ($data['rule'] as $d) {\n $this->addRule($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"rule\" must be array of objects or null, ' . gettype($data['rule']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function checkPrettyUrlAction(Request $request): JsonResponse\n {\n $docId = $request->request->getInt('id');\n $path = trim($request->request->get('path', ''));\n\n $success = true;\n\n if ($path === '') {\n return $this->adminJson([\n 'success' => $success,\n ]);\n }\n\n $message = [];\n $path = rtrim($path, '/');\n\n // must start with /\n if ($path !== '' && strpos($path, '/') !== 0) {\n $success = false;\n $message[] = 'URL must start with /.';\n }\n\n if (strlen($path) < 2) {\n $success = false;\n $message[] = 'URL must be at least 2 characters long.';\n }\n\n if (!Element\\Service::isValidPath($path, 'document')) {\n $success = false;\n $message[] = 'URL is invalid.';\n }\n\n $list = new Document\\Listing();\n $list->setCondition('(CONCAT(`path`, `key`) = ? OR id IN (SELECT id from documents_page WHERE prettyUrl = ?))\n AND id != ?', [\n $path, $path, $docId,\n ]);\n\n if ($list->getTotalCount() > 0) {\n $checkDocument = Document::getById($docId);\n $checkSite = Frontend::getSiteForDocument($checkDocument);\n $checkSiteId = empty($checkSite) ? 0 : $checkSite->getId();\n\n foreach ($list as $document) {\n if (empty($document)) {\n continue;\n }\n\n $site = Frontend::getSiteForDocument($document);\n $siteId = empty($site) ? 0 : $site->getId();\n\n if ($siteId === $checkSiteId) {\n $success = false;\n $message[] = 'URL path already exists.';\n\n break;\n }\n }\n }\n\n return $this->adminJson([\n 'success' => $success,\n 'message' => implode('<br>', $message),\n ]);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public static function getAllLinksFor($item, $params = [])\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $computedlinks = [];\n if (\n !isset($params['name'])\n || !isset($params['link'])\n || !isset($params['data'])\n || !isset($params['id'])\n ) {\n return $computedlinks;\n }\n\n if (!isset($params['open_window'])) {\n $params['open_window'] = true;\n }\n\n if (empty($params['name'])) {\n $params['name'] = $params['link'];\n }\n\n $names = $item->generateLinkContents($params['name'], $item, false);\n $file = trim($params['data']);\n\n if (empty($file)) {\n // Generate links\n $links = $item->generateLinkContents($params['link'], $item, true);\n $i = 1;\n foreach ($links as $key => $val) {\n $name = ($names[$key] ?? reset($names));\n $newlink = '<a href=\"' . htmlescape($val) . '\"';\n if ($params['open_window']) {\n $newlink .= \" target='_blank'\";\n }\n $newlink .= \">\";\n $linkname = htmlescape(sprintf(__('%1$s #%2$s'), $name, $i));\n $newlink .= htmlescape(sprintf(__('%1$s: %2$s'), $linkname, $val));\n $newlink .= \"</a>\";\n $computedlinks[] = $newlink;\n $i++;\n }\n } else {\n // Generate files\n $files = $item->generateLinkContents($params['link'], $item, false);\n $links = $item->generateLinkContents($params['data'], $item, false);\n $i = 1;\n foreach ($links as $key => $val) {\n $name = ($names[$key] ?? reset($names));\n if (isset($files[$key])) {\n // a different name for each file, ex name = foo-[IP].txt\n $file = $files[$key];\n } else {\n // same name for all files, ex name = foo.txt\n $file = reset($files);\n }\n $url = $CFG_GLPI[\"root_doc\"] . \"/front/link.send.php?lID=\" . $params['id'] .\n \"&itemtype=\" . $item::class .\n \"&id=\" . $item->getID() . \"&rank=$key\";\n $newlink = '<a href=\"' . htmlescape($url) . '\" target=\"_blank\">';\n $newlink .= \"<i class='fa-lg fa-fw fas fa-link me-2'></i>\";\n $linkname = htmlescape(sprintf(__('%1$s #%2$s'), $name, $i));\n $newlink .= htmlescape(sprintf(__('%1$s: %2$s'), $linkname, $val));\n $newlink .= \"</a>\";\n $computedlinks[] = $newlink;\n $i++;\n }\n }\n\n return $computedlinks;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function updateRecStructure( $dtFieldNames , $rtyID, $rt) {\n\n global $system, $mysqli, $rstColumnNames;\n\n $ret = array();//result\n $ret[$rtyID] = array();\n\n $res = mysql__select_value($mysqli, \"select rty_ID from defRecTypes where rty_ID = $rtyID\");\n\n if (!($res>0)) {\n $system->addError(HEURIST_NOT_FOUND, \"Record type not affected. Record type $rtyID not found\");\n return false;\n }\n\n $query2 = \"\";\n\n if (!isEmptyArray($dtFieldNames) && !empty($rt['dtFields']))\n {\n\n //if rst_OriginatingDBID>0 (means that rectype is registered) need to mark that\n //rectype structure was modified locally\n $wasLocallyModified = false;\n\n foreach ($rt['dtFields'] as $dtyID => $fieldVals)\n {\n //$ret['dtFields'][$dtyID] = array();\n $fieldNames = \"\";\n $parameters = array(\"\");//list of field date types\n\n $row = mysql__select_row_assoc($mysqli,\n \"select rst_ID, rst_OriginatingDBID from defRecStructure where rst_RecTypeID = $rtyID and rst_DetailTypeID = $dtyID\");\n\n $isInsert = !(@$row['rst_ID']>0);\n\n if($isInsert){\n $fieldNames = $fieldNames.\", rst_LocallyModified\";\n $query2 = \"9\";\n }else{\n $query2 = \"rst_LocallyModified=\".(($row['rst_OriginatingDBID']>0)?\"1\":\"0\");\n $wasLocallyModified = ($wasLocallyModified || ($row['rst_OriginatingDBID']>0));\n }\n\n //$fieldNames = \"rst_RecTypeID,rst_DetailTypeID,\".join(\",\",$dtFieldNames);\n\n $query = $query2;\n foreach ($dtFieldNames as $colName) {\n\n $val = array_shift($fieldVals);\n\n\n if (array_key_exists($colName, $rstColumnNames)\n && $colName!=\"rst_LocallyModified\") {\n //array_push($ret['error'], \"$colName is not a valid column name for defDetailTypes val= $val was not used\");\n\n if($isInsert){\n if($query!=\"\") {$query = $query.\",\";}\n $fieldNames = $fieldNames.\", $colName\";\n $query = $query.\"?\";\n }else{\n if($query!=\"\") {$query = $query.\",\";}\n $query = $query.\"$colName = ?\";\n }\n\n //special behaviour\n if($colName=='rst_MaxValues' && $val==null){\n $val = 0; //repeatbale\n }elseif($colName=='rst_PointerMode' && ($val=='' || $val==null)){\n $val = 'addorbrowse';\n }elseif($colName=='rst_Modified'){\n $val = date(DATE_8601);\n }\n\n $parameters = addParam($parameters, $rstColumnNames[$colName], $val);\n }\n }//for columns\n\n if($query!=\"\"){\n if($isInsert){\n $query = \"insert into defRecStructure (rst_RecTypeID, rst_DetailTypeID $fieldNames) values ($rtyID, $dtyID,\".$query.\")\";\n }else{\n $query = \"update defRecStructure set \".$query.\" where rst_RecTypeID = $rtyID and rst_DetailTypeID = $dtyID\";\n }\n\n $rows = mysql__exec_param_query($mysqli, $query, $parameters, true);\n\n if ( ($isInsert && $rows==0) || is_string($rows) ) {\n $oper = (($isInsert)?\"inserting\":\"updating\");\n\n $ret = \"Error on $oper field type $dtyID for record type $rtyID in updateRecStructure\";\n handleError($ret, $query, $rows);\n\n //array_push($ret[$rtyID], $ret);\n return false;\n } else {\n array_push($ret[$rtyID], $dtyID);//numeric ok\n }\n }\n }//for each dt\n\n if($wasLocallyModified){\n $query = \"update defRecTypes set rty_LocallyModified=1 where rty_ID = $rtyID\";\n mysql__exec_param_query($mysqli, $query, null, true);\n }\n\n } //if column names\n\n if (empty($ret[$rtyID])) {\n array_push($ret[$rtyID], \"no data supplied for updating record structure - $rtyID\");\n }\n\n return $ret;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public static function showListForCentral(bool $personal = true, bool $display = true)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $criteria = self::getListCriteria();\n $personal_criteria = $criteria['personal'];\n $public_criteria = $criteria['public'];\n\n // Only standard interface users have personal reminders\n $can_see_personal = Session::getCurrentInterface() === 'central';\n $can_see_public = (bool) Session::haveRight(self::$rightname, READ);\n\n $personal_reminders = [];\n $public_reminders = [];\n\n if ($personal && $can_see_personal) {\n $iterator = $DB->request($personal_criteria);\n foreach ($iterator as $data) {\n $personal_reminders[] = $data;\n }\n }\n if ($can_see_public) {\n $iterator = $DB->request($public_criteria);\n foreach ($iterator as $data) {\n $public_reminders[] = $data;\n }\n\n // Remove all reminders from the personal list that are already in the public list (Check by id)\n foreach ($public_reminders as $key => $public_reminder) {\n foreach ($personal_reminders as $key2 => $personal_reminder) {\n if ($personal_reminder['id'] === $public_reminder['id']) {\n unset($personal_reminders[$key2]);\n }\n }\n }\n }\n\n if ($personal) {\n $title = '<a href=\"' . $CFG_GLPI[\"root_doc\"] . '/front/reminder.php\">'\n . _sn('Personal reminder', 'Personal reminders', Session::getPluralNumber())\n . '</a>';\n } else {\n if (Session::getCurrentInterface() !== 'helpdesk') {\n $title = '<a href=\"' . $CFG_GLPI[\"root_doc\"] . '/front/reminder.php\">'\n . _sn('Public reminder', 'Public reminders', Session::getPluralNumber())\n . '</a>';\n } else {\n $title = _sn('Public reminder', 'Public reminders', Session::getPluralNumber());\n }\n }\n\n $reminders = $personal ? $personal_reminders : $public_reminders;\n $nb = count($reminders);\n $add_link = '';\n\n if (\n ($personal && self::canCreate())\n || (!$personal && Session::haveRight(self::$rightname, CREATE))\n ) {\n $add_link = self::getFormURL();\n }\n $rows = [];\n\n if ($nb) {\n $rand = mt_rand();\n\n foreach ($reminders as $data) {\n $row = [\n 'values' => []\n ];\n $name = $data['name'];\n\n if (!empty($data['transname'])) {\n $name = $data['transname'];\n }\n $link = sprintf(\n '<a id=\"content_reminder_%s\" href=\"%s\">%s</a>',\n htmlescape($data[\"id\"] . $rand),\n htmlescape(self::getFormURLWithID($data[\"id\"])),\n htmlescape($name)\n );\n $text = $data[\"text\"];\n if (!empty($data['transtext'])) {\n $text = $data['transtext'];\n }\n $tooltip = Html::showToolTip(\n RichText::getEnhancedHtml($text),\n [\n 'applyto' => \"content_reminder_\" . $data[\"id\"] . $rand,\n 'display' => false\n ]\n );\n $row['values'][] = sprintf(__('%1$s %2$s'), $link, $tooltip);\n\n if ($data[\"is_planned\"]) {\n $tab = explode(\" \", $data[\"begin\"]);\n $date_url = $tab[0];\n $planning_text = sprintf(\n __s('From %1$s to %2$s'),\n Html::convDateTime($data[\"begin\"]),\n Html::convDateTime($data[\"end\"])\n );\n $row['values'][] = sprintf(\n '<a href=\"%s\" class=\"pointer float-end\" title=\"%s\"><i class=\"ti ti-bell\"></i><span class=\"sr-only\">%s</span></a>',\n htmlescape(sprintf('%s/front/planning.php?date=%s&type=day', $CFG_GLPI['root_doc'], $date_url)),\n htmlescape($planning_text),\n __s('Planning')\n );\n } else {\n $row['values'][] = '';\n }\n $rows[] = $row;\n }\n }\n\n $output = TemplateRenderer::getInstance()->render('central/lists/table.html.twig', [\n 'title' => $title,\n 'add_link' => $add_link,\n 'rows' => $rows,\n ]);\n\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function loadRoutes($id_shop = null)\n {\n $context = Context::getContext();\n\n // Load custom routes from modules\n $modules_routes = Hook::exec('moduleRoutes', array('id_shop' => $id_shop), null, true, false);\n if (is_array($modules_routes) && count($modules_routes)) {\n foreach ($modules_routes as $module_route) {\n if (is_array($module_route) && count($module_route)) {\n foreach ($module_route as $route => $route_details) {\n if (array_key_exists('controller', $route_details) && array_key_exists('rule', $route_details)\n && array_key_exists('keywords', $route_details) && array_key_exists('params', $route_details)) {\n if (!isset($this->default_routes[$route])) {\n $this->default_routes[$route] = array();\n }\n $this->default_routes[$route] = array_merge($this->default_routes[$route], $route_details);\n }\n }\n }\n }\n }\n\n $language_ids = Language::getIDs();\n\n if (isset($context->language) && !in_array($context->language->id, $language_ids)) {\n $language_ids[] = (int)$context->language->id;\n }\n\n // Set default routes\n foreach ($language_ids as $id_lang) {\n foreach ($this->default_routes as $id => $route) {\n $this->addRoute(\n $id,\n $route['rule'],\n $route['controller'],\n $id_lang,\n $route['keywords'],\n isset($route['params']) ? $route['params'] : array(),\n $id_shop\n );\n }\n }\n\n // Load the custom routes prior the defaults to avoid infinite loops\n if ($this->use_routes) {\n // Load routes from meta table\n $sql = 'SELECT m.page, ml.url_rewrite, ml.id_lang\n\t\t\t\t\tFROM `'._DB_PREFIX_.'meta` m\n\t\t\t\t\tLEFT JOIN `'._DB_PREFIX_.'meta_lang` ml ON (m.id_meta = ml.id_meta'.Shop::addSqlRestrictionOnLang('ml', (int) $id_shop).')\n\t\t\t\t\tORDER BY LENGTH(ml.url_rewrite) DESC';\n if ($results = Db::getInstance()->executeS($sql)) {\n foreach ($results as $row) {\n if ($row['url_rewrite']) {\n $this->addRoute($row['page'], $row['url_rewrite'], $row['page'], $row['id_lang'], array(), array(), $id_shop);\n }\n }\n }\n\n // Set default empty route if no empty route (that's weird I know)\n if (!$this->empty_route) {\n $this->empty_route = array(\n 'routeID' => 'index',\n 'rule' => '',\n 'controller' => 'index',\n );\n }\n\n // Load custom routes\n foreach ($this->default_routes as $route_id => $route_data) {\n if ($custom_route = Configuration::get('PS_ROUTE_'.$route_id, null, null, $id_shop)) {\n if (isset($context->language) && !in_array($context->language->id, $language_ids)) {\n $language_ids[] = (int)$context->language->id;\n }\n\n foreach ($language_ids as $id_lang) {\n $this->addRoute(\n $route_id,\n $custom_route,\n $route_data['controller'],\n $id_lang,\n $route_data['keywords'],\n isset($route_data['params']) ? $route_data['params'] : array(),\n $id_shop\n );\n }\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function solve($B) {\n\t\tif ($B->getRowDimension() == $this->m) {\n\t\t\tif ($this->isNonsingular()) {\n\t\t\t\t// Copy right hand side with pivoting\n\t\t\t\t$nx = $B->getColumnDimension();\n\t\t\t\t$X = $B->getMatrix($this->piv, 0, $nx-1);\n\t\t\t\t// Solve L*Y = B(piv,:)\n\t\t\t\tfor ($k = 0; $k < $this->n; ++$k) {\n\t\t\t\t\tfor ($i = $k+1; $i < $this->n; ++$i) {\n\t\t\t\t\t\tfor ($j = 0; $j < $nx; ++$j) {\n\t\t\t\t\t\t\t$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Solve U*X = Y;\n\t\t\t\tfor ($k = $this->n-1; $k >= 0; --$k) {\n\t\t\t\t\tfor ($j = 0; $j < $nx; ++$j) {\n\t\t\t\t\t\t$X->A[$k][$j] /= $this->LU[$k][$k];\n\t\t\t\t\t}\n\t\t\t\t\tfor ($i = 0; $i < $k; ++$i) {\n\t\t\t\t\t\tfor ($j = 0; $j < $nx; ++$j) {\n\t\t\t\t\t\t\t$X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn $X;\n\t\t\t} else {\n\t\t\t\tthrow new PHPExcel_Calculation_Exception(self::MatrixSingularException);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new PHPExcel_Calculation_Exception(self::MatrixSquareException);\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "private static function __get_field_value( $rdt_id, $rt, $mode, $rec_id, $enum_param_name=null) {\n\n if($mode==0){\n\n $local_dt_id = self::__get_dt_field($rt, $rdt_id, $mode, 'dty_ID');//local dt id\n $dt_type = '';\n if($local_dt_id>0){\n $dt_type = self::__get_dt_field($rt, $local_dt_id, $mode, 'dty_Type');\n }\n if($dt_type=='relmarker'){\n //find related record id\n $res = self::__get_related_record_ids($rec_id, $local_dt_id);\n\n }else{\n\n $rec_values = self::__get_record_value($rec_id);\n\n if(!$rec_values){\n return \"\";\n }elseif (strcasecmp($rdt_id,'id')==0){\n return $rec_values['rec_ID'];\n }elseif (strcasecmp($rdt_id,'rectitle')==0) {\n return $rec_values['rec_Title'];\n }elseif (strcasecmp($rdt_id,'rectypeid')==0) {\n return $rec_values['rec_RecTypeID'];\n }elseif (strcasecmp($rdt_id,'rectypename')==0) {\n return $rec_values['rty_Name'];\n }elseif (strcasecmp($rdt_id,'modified')==0) {\n return $rec_values['rec_Modified'];\n }\n\n $details = $rec_values['rec_Details'];\n $rdt_id = $local_dt_id;\n\n //dtl_DetailTypeID, dtl_Value, dtl_UploadedFileID, rst_RequirementType\n $res = array();\n $found = false;\n foreach($details as $detail){\n if($detail['dtl_DetailTypeID']==$rdt_id){\n $found = true;\n if($dt_type==\"enum\" || $dt_type==\"relationtype\"){\n $value = self::__get_enum_value($detail['dtl_Value'], $enum_param_name);\n }elseif($dt_type=='date'){\n $value = Temporal::toHumanReadable(trim($detail['dtl_Value']));\n }elseif($dt_type==\"file\"){\n $value = self::__get_file_name(intval($detail['dtl_UploadedFileID']));\n }elseif($dt_type=='freetext' || $dt_type=='blocktext'){\n list(, $value) = extractLangPrefix($detail['dtl_Value']);// remove possible language prefix\n }else{\n $value = $detail['dtl_Value'];\n }\n if($value!=null && $value!=''){\n array_push($res, $value);\n }\n }elseif($found){\n break;\n }\n }\n\n }\n\n if(empty($res)){\n return \"\";\n /*}elseif($dt_type == 'file'){\n return count($res).\" file\".(count($res)>1?\"s\":\"\");*/\n }elseif($dt_type == 'geo') {\n return count($res).\" geographic object\".(count($res)>1?\"s\":\"\");\n }else{\n return implode(\",\", $res);\n }\n\n }else{\n\n if (strcasecmp($rdt_id,'id')==0 ||\n strcasecmp($rdt_id,'rectitle')==0 ||\n strcasecmp($rdt_id,'modified')==0){\n return $rdt_id;\n }elseif($mode==1){ //convert to\n return $rdt_id; //concept code\n } else {\n return self::__get_dt_field($rt, $rdt_id, $mode, 'originalName');//original name (with capital chars)\n }\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function conversionCapacity2() {\n\n\t$args = func_get_args();\n\n #region Argument verification\n\n if (count($args)==0) {\n\t\t$retval[0][0] = nothingtodisplay();\n echo $retval[0][0];\n return $retval;\n\t} else {\n $system = strtoupper($args[0]);\n if($system!='A' && $system!='M' && $system!='AM' && $system!='MA' ) {\n echo (string)$system.isnotvalidAMT();\n return \"\";\n }\n }\n\n if ( count($args)>1 && !is_null($args[1]) ) {\n $fullname = verifyFullName($args[1]);\n } else {\n $fullname = 0;\n }\n\n if ( count($args)>2 && !is_null($args[2]) ) {\n $rounding = verifyRounding($args[2]);\n } else {\n $rounding = 2;\n }\n\n if ( count($args)>3 && !is_null($args[3]) ) {\n $input = $args[3];\n $sign = verifyEqualSign($input);\n } else {\n $sign = \"=\";\n }\n\n if ( count($args)>4 && !is_null($args[4]) ) {\n $tick = verifyTickMarks($args[4]);\n } else {\n $tick = \"\";\n }\n\n $sign_tick = \"$tick$sign$tick\";\n\n\t#endregion\n\n $retval = array();\n\n // Get array values\n $unit=get_unit_capacities();\n $unitabbr = get_unit_capacity_abbreviations();\n\n\tif($system==\"A\"){\n\n #region American Conversion\n\n // don't allow an approximately equal symbol or ans ~\n $sign = \"=\";\n\n\t\tif($fullname==0) {\n $retval[0] = array(\"\",1,$unitabbr[\"cup\"],8,$unitabbr[\"fluid ounces\"]);\n $retval[1] = array(\"\",1,$unitabbr[\"tablespoon\"],3,$unitabbr[\"teaspoons\"]);\n $retval[2] = array(\"\",1,$unitabbr[\"cup\"],16,$unitabbr[\"tablespoons\"]);\n $retval[3] = array(\"\",1,$unitabbr[\"pint\"],2,$unitabbr[\"cups\"]);\n $retval[4] = array(\"\",1,$unitabbr[\"quart\"],2,$unitabbr[\"pints\"]);\n $retval[5] = array(\"\",1,$unitabbr[\"gallon\"],4,$unitabbr[\"quarts\"]);\n } else {\n $retval[0] = array(\"\",1,$unit[\"Cup\"],8,$unit[\"Fluid ounces\"]);\n $retval[1] = array(\"\",1,$unit[\"cup\"],3,$unit[\"teaspoons\"]);\n $retval[2] = array(\"\",1,$unit[\"tablespoon\"],16,$unit[\"tablespoons\"]);\n $retval[3] = array(\"\",1,$unit[\"Pint\"],2,$unit[\"Cups\"]);\n $retval[4] = array(\"\",1,$unit[\"Quart\"],2,$unit[\"Pints\"]);\n $retval[5] = array(\"\",1,$unit[\"Gallon\"],4,$unit[\"Quarts\"]);\n }\n for($i=0;$i<6;$i+=1){\n $retval[$i][0] = \"{$retval[$i][1]} {$retval[$i][2]} $sign {$retval[$i][3]} {$retval[$i][4]}\";\n }\n\n #endregion\n\n\t} elseif($system==\"M\"){\n\n #region Metric Conversion\n\n // don't allow an approximately equal symbol or ans ~\n $sign = \"=\";\n\n\t\tif($fullname==0) {\n $retval[0] = array(\"\",1,$unitabbr[\"Kiloliter\"],1000,$unitabbr[\"Liter\"]);\n $retval[1] = array(\"\",1,$unitabbr[\"Hectoliter\"],100,$unitabbr[\"Liter\"]);\n $retval[2] = array(\"\",1,conversionUnits2ScreenReader1(\"\",$unitabbr[\"Dekaliter\"],1,\"n\"),10,$unitabbr[\"Liter\"]);\n $retval[3] = array(\"\",1,$unitabbr[\"Liter\"],10,$unitabbr[\"Deciliter\"]);\n $retval[4] = array(\"\",1,$unitabbr[\"Liter\"],100,$unitabbr[\"Centiliter\"]);\n $retval[5] = array(\"\",1,$unitabbr[\"Liter\"],1000,$unitabbr[\"Milliliter\"]);\n } else {\n $retval[0] = array(\"\",1,$unit[\"Kiloliter\"],1000,$unit[\"Liter\"]);\n $retval[1] = array(\"\",1,$unit[\"Hectoliter\"],100,$unit[\"Liter\"]);\n $retval[2] = array(\"\",1,$unit[\"Dekaliter\"],10,$unit[\"Liter\"]);\n $retval[3] = array(\"\",1,$unit[\"Liter\"],10,$unit[\"Deciliter\"]);\n $retval[4] = array(\"\",1,$unit[\"Liter\"],100,$unit[\"Centiliter\"]);\n $retval[5] = array(\"\",1,$unit[\"Liter\"],1000,$unit[\"Milliliter\"]);\n }\n for($i=0;$i<6;$i+=1){\n $retval[$i][0] = \"{$retval[$i][1]} {$retval[$i][2]} $sign {$retval[$i][3]} {$retval[$i][4]}\";\n }\n\n #endregion\n\n\t} elseif($system==\"AM\"){\n\n #region American to Metric Conversion\n\n\t\tif($fullname==0) {\n\t\t\t$retval[0] = array(\"\",1,$unitabbr[\"fluid ounces\"],round(0.0295735296, $rounding),$unitabbr[\"Liter\"]);\n $retval[1] = array(\"\",1,$unitabbr[\"cup\"],round(0.236588236, $rounding),$unitabbr[\"Liter\"]);\n $retval[2] = array(\"\",1,$unitabbr[\"pint\"],round(0.473176473, $rounding),$unitabbr[\"Liter\"]);\n $retval[3] = array(\"\",1,$unitabbr[\"quart\"],round(0.946352946, $rounding),$unitabbr[\"Liter\"]);\n $retval[4] = array(\"\",1,$unitabbr[\"gallon\"],round(3.78541178, $rounding),$unitabbr[\"Liter\"]);\n } else {\n\t\t\t$retval[0] = array(\"\",1,$unit[\"fluid ounces\"],round(0.0295735296, $rounding),$unit[\"Liter\"]);\n $retval[1] = array(\"\",1,$unit[\"cup\"],round(0.236588236, $rounding),$unit[\"Liter\"]);\n $retval[2] = array(\"\",1,$unit[\"pint\"],round(0.473176473, $rounding),$unit[\"Liter\"]);\n $retval[3] = array(\"\",1,$unit[\"quart\"],round(0.946352946, $rounding),$unit[\"Liter\"]);\n $retval[4] = array(\"\",1,$unit[\"gallon\"],round(3.78541178, $rounding),$unit[\"Liter\"]);\n }\n for($i=0;$i<5;$i+=1){\n $retval[$i][0] = \"{$retval[$i][1]} {$retval[$i][2]} $sign_tick {$retval[$i][3]} {$retval[$i][4]}\";\n }\n\n #endregion\n\n\t} elseif($system==\"MA\"){\n\n #region Metric to American Conversion\n\n\t\tif($fullname==0) {\n\t\t\t$retval[0] = array(\"\",1,$unitabbr[\"Liter\"],round(33.8140227, $rounding),$unitabbr[\"fluid ounces\"]);\n $retval[1] = array(\"\",1,$unitabbr[\"Liter\"],round(4.22675284, $rounding),$unitabbr[\"cups\"]);\n $retval[2] = array(\"\",1,$unitabbr[\"Liter\"],round(2.11337642, $rounding),$unitabbr[\"pints\"]);\n $retval[3] = array(\"\",1,$unitabbr[\"Liter\"],round(1.05668821, $rounding),$unitabbr[\"quarts\"]);\n $retval[4] = array(\"\",1,$unitabbr[\"Liter\"],round(0.264172052, $rounding),$unitabbr[\"gallon\"]);\n } else {\n\t\t\t$retval[0] = array(\"\",1,$unit[\"Liter\"],round(33.8140227, $rounding),$unit[\"fluid ounces\"]);\n $retval[1] = array(\"\",1,$unit[\"Liter\"],round(4.22675284, $rounding),$unit[\"cups\"]);\n $retval[2] = array(\"\",1,$unit[\"Liter\"],round(2.11337642, $rounding),$unit[\"pints\"]);\n $retval[3] = array(\"\",1,$unit[\"Liter\"],round(1.05668821, $rounding),$unit[\"quarts\"]);\n $retval[4] = array(\"\",1,$unit[\"Liter\"],round(0.264172052, $rounding),$unit[\"gallon\"]);\n }\n for($i=0;$i<5;$i+=1){\n $retval[$i][0] = \"{$retval[$i][1]} {$retval[$i][2]} $sign_tick {$retval[$i][3]} {$retval[$i][4]}\";\n }\n\n #endregion\n\n\t} else {\n $retval[0][0] = \"'\".(string)$system.\"' \".isnotvalid();\n }\n\n\treturn $retval;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function readChart($chartElements,$chartName) {\n\t\t$namespacesChartMeta = $chartElements->getNamespaces(true);\n\t\t$chartElementsC = $chartElements->children($namespacesChartMeta['c']);\n\n\t\t$XaxisLabel = $YaxisLabel = $legend = $title = NULL;\n\t\t$dispBlanksAs = $plotVisOnly = NULL;\n\n\t\tforeach($chartElementsC as $chartElementKey => $chartElement) {\n\t\t\tswitch ($chartElementKey) {\n\t\t\t\tcase \"chart\":\n\t\t\t\t\tforeach($chartElement as $chartDetailsKey => $chartDetails) {\n\t\t\t\t\t\t$chartDetailsC = $chartDetails->children($namespacesChartMeta['c']);\n\t\t\t\t\t\tswitch ($chartDetailsKey) {\n\t\t\t\t\t\t\tcase \"plotArea\":\n\t\t\t\t\t\t\t\t\t$plotAreaLayout = $XaxisLable = $YaxisLable = null;\n\t\t\t\t\t\t\t\t\t$plotSeries = $plotAttributes = array();\n\t\t\t\t\t\t\t\t\tforeach($chartDetails as $chartDetailKey => $chartDetail) {\n\t\t\t\t\t\t\t\t\t\tswitch ($chartDetailKey) {\n\t\t\t\t\t\t\t\t\t\t\tcase \"layout\":\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAreaLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'plotArea');\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"catAx\":\n\t\t\t\t\t\t\t\t\t\t\t\tif (isset($chartDetail->title)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"dateAx\":\n\t\t\t\t\t\t\t\t\t\t\t\tif (isset($chartDetail->title)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t$XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"valAx\":\n\t\t\t\t\t\t\t\t\t\t\t\tif (isset($chartDetail->title)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t$YaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat');\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"barChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"bar3DChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$barDirection = self::_getAttribute($chartDetail->barDir, 'val', 'string');\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotDirection($barDirection);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"lineChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"line3DChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"areaChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"area3DChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"doughnutChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"pieChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"pie3DChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$explosion = isset($chartDetail->ser->explosion);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotStyle($explosion);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"scatterChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$scatterStyle = self::_getAttribute($chartDetail->scatterStyle, 'val', 'string');\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotStyle($scatterStyle);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"bubbleChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$bubbleScale = self::_getAttribute($chartDetail->bubbleScale, 'val', 'integer');\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotStyle($bubbleScale);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"radarChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$radarStyle = self::_getAttribute($chartDetail->radarStyle, 'val', 'string');\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotStyle($radarStyle);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"surfaceChart\":\n\t\t\t\t\t\t\t\t\t\t\tcase \"surface3DChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$wireFrame = self::_getAttribute($chartDetail->wireframe, 'val', 'boolean');\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSer->setPlotStyle($wireFrame);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = $plotSer;\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($chartDetail);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"stockChart\":\n\t\t\t\t\t\t\t\t\t\t\t\t$plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey);\n\t\t\t\t\t\t\t\t\t\t\t\t$plotAttributes = self::_readChartAttributes($plotAreaLayout);\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif ($plotAreaLayout == NULL) {\n\t\t\t\t\t\t\t\t\t\t$plotAreaLayout = new PHPExcel_Chart_Layout();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t$plotArea = new PHPExcel_Chart_PlotArea($plotAreaLayout,$plotSeries);\n\t\t\t\t\t\t\t\t\tself::_setChartAttributes($plotAreaLayout,$plotAttributes);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"plotVisOnly\":\n\t\t\t\t\t\t\t\t\t$plotVisOnly = self::_getAttribute($chartDetails, 'val', 'string');\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"dispBlanksAs\":\n\t\t\t\t\t\t\t\t\t$dispBlanksAs = self::_getAttribute($chartDetails, 'val', 'string');\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"title\":\n\t\t\t\t\t\t\t\t\t$title = self::_chartTitle($chartDetails,$namespacesChartMeta,'title');\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"legend\":\n\t\t\t\t\t\t\t\t\t$legendPos = 'r';\n\t\t\t\t\t\t\t\t\t$legendLayout = null;\n\t\t\t\t\t\t\t\t\t$legendOverlay = false;\n\t\t\t\t\t\t\t\t\tforeach($chartDetails as $chartDetailKey => $chartDetail) {\n\t\t\t\t\t\t\t\t\t\tswitch ($chartDetailKey) {\n\t\t\t\t\t\t\t\t\t\t\tcase \"legendPos\":\n\t\t\t\t\t\t\t\t\t\t\t\t$legendPos = self::_getAttribute($chartDetail, 'val', 'string');\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"overlay\":\n\t\t\t\t\t\t\t\t\t\t\t\t$legendOverlay = self::_getAttribute($chartDetail, 'val', 'boolean');\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"layout\":\n\t\t\t\t\t\t\t\t\t\t\t\t$legendLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'legend');\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t$legend = new PHPExcel_Chart_Legend($legendPos, $legendLayout, $legendOverlay);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$chart = new PHPExcel_Chart($chartName,$title,$legend,$plotArea,$plotVisOnly,$dispBlanksAs,$XaxisLabel,$YaxisLabel);\n\n\t\treturn $chart;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function downloadDocument($documentId, $patientUuid = null): ResponseInterface\n {\n $document = $this->findDocumentForDocumentId($documentId);\n if (empty($document)) {\n return (new Psr17Factory())->createResponse(StatusCode::NOT_FOUND);\n }\n\n // run file cleanup requests\n // grab all export db records w/ expired records & delete them\n\n // return 404 if our document is deleted.\n if ($document->is_deleted()) {\n return (new Psr17Factory())->createResponse(StatusCode::NOT_FOUND);\n }\n\n // patients need to be able to access their own documents, we expose that here if we have a patientUuid\n if (!empty($patientUuid)) {\n $pid = (new PatientService())->getPidByUuid(UuidRegistry::uuidToBytes($patientUuid));\n // allows for both checking the patient id, and any Information Blocking / Access rules to the document\n if (!$document->can_patient_access($pid)) {\n return (new Psr17Factory())->createResponse(StatusCode::UNAUTHORIZED);\n }\n }\n\n if (!$document->can_access()) {\n return (new Psr17Factory())->createResponse(StatusCode::UNAUTHORIZED);\n }\n\n if ($document->has_expired()) {\n // cleanup the document if we haven't already\n try {\n if (!$document->is_deleted()) {\n $document->process_deleted();\n }\n } catch (\\Exception $exception) {\n // we just continue as we still wanto to reject the response\n $this->logger->error(\n \"FhirDocumentRestController->downloadDocument() Failed to delete document with id\",\n ['document' => $documentId, 'username' => $_SESSION['authUser'], 'exception' => $exception->getMessage()]\n );\n }\n // need to return the fact that the document has expired\n return (new Psr17Factory())->createResponse(StatusCode::NOT_FOUND);\n } else {\n // if we have registered mime type handlers we will process them here, otherwise we use the default handler.\n foreach ($this->mimeTypeHandlers as $mimeType => $handler) {\n if ($mimeType === $document->get_mimetype()) {\n return $handler->downloadDocument($document);\n }\n }\n $this->logger->debug(\n \"FhirDocumentRestController->downloadDocument() Sending to default mime type handler\",\n ['document' => $documentId, 'username' => $_SESSION['authUser']]\n );\n $response = $this->defaultMimeTypeHandler->downloadDocument($document);\n $this->logger->debug(\n \"FhirDocumentRestController->downloadDocument() Response returned\",\n ['document' => $documentId, 'username' => $_SESSION['authUser'], 'contentLength' => $response->getHeader(\"Content-Length\")]\n );\n return $response;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function processBlackList(&$value)\n {\n\n if (\n property_exists($value, 'manufacturers_id')\n && !is_numeric($value->manufacturers_id)\n && '' == $this->process(self::MANUFACTURER, $value->manufacturers_id)\n ) {\n unset($value->manufacturers_id);\n }\n\n if (\n property_exists($value, 'uuid')\n && '' == $this->process(self::UUID, $value->uuid)\n ) {\n unset($value->uuid);\n }\n\n if (\n property_exists($value, 'mac')\n && '' == $this->process(self::MAC, $value->mac)\n ) {\n unset($value->mac);\n }\n\n if (\n property_exists($value, 'serial')\n && '' == $this->process(self::SERIAL, $value->serial)\n ) {\n unset($value->serial);\n }\n\n if (\n !property_exists($value, 'serial')\n && property_exists($value, 'mserial')\n && '' != $this->process(self::SERIAL, $value->mserial)\n ) {\n $value->serial = $value->mserial;\n }\n\n if (property_exists($value, 'ipaddress') || property_exists($value, 'ip')) {\n $property = property_exists($value, 'ipaddress') ? 'ipaddress' : 'ip';\n $ips = &$value->$property;\n if (is_array($ips)) {\n foreach ($ips as $k => $ip) {\n if ('' == $this->process(self::IP, $ip)) {\n unset($ips[$k]);\n }\n }\n } else if ('' == $this->process(self::IP, $ips)) {\n unset($value->$property);\n }\n }\n\n foreach ($value as $key => $val) {\n if (\n !is_numeric($value->$key)\n && preg_match('/^.+models_id/', $key)\n && '' == $this->process(self::MODEL, $value->$key)\n ) {\n unset($value->$key);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function mergeMediaTypes($type1, $type2)\n {\n if (empty($type1)) {\n return $type2;\n }\n\n if (empty($type2)) {\n return $type1;\n }\n\n if (\\count($type1) > 1) {\n $m1 = strtolower($type1[0]);\n $t1 = strtolower($type1[1]);\n } else {\n $m1 = '';\n $t1 = strtolower($type1[0]);\n }\n\n if (\\count($type2) > 1) {\n $m2 = strtolower($type2[0]);\n $t2 = strtolower($type2[1]);\n } else {\n $m2 = '';\n $t2 = strtolower($type2[0]);\n }\n\n if (($m1 === Type::T_NOT) ^ ($m2 === Type::T_NOT)) {\n if ($t1 === $t2) {\n return null;\n }\n\n return [\n $m1 === Type::T_NOT ? $m2 : $m1,\n $m1 === Type::T_NOT ? $t2 : $t1,\n ];\n }\n\n if ($m1 === Type::T_NOT && $m2 === Type::T_NOT) {\n // CSS has no way of representing \"neither screen nor print\"\n if ($t1 !== $t2) {\n return null;\n }\n\n return [Type::T_NOT, $t1];\n }\n\n if ($t1 !== $t2) {\n return null;\n }\n\n // t1 == t2, neither m1 nor m2 are \"not\"\n return [empty($m1) ? $m2 : $m1, $t1];\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getModulesOnDisk($use_config = false, $logged_on_addons = false, $id_employee = false)\n {\n global $_MODULES;\n\n // Init var\n $module_list = [];\n $module_name_list = [];\n $modules_name_to_cursor = [];\n $errors = [];\n\n // Get modules directory list and memory limit\n $modules_dir = Module::getModulesDirOnDisk();\n\n $modules_installed = [];\n $result = Db::getInstance()->executeS('\n SELECT m.name, m.version, mp.interest, module_shop.enable_device\n FROM `' . _DB_PREFIX_ . 'module` m\n ' . Shop::addSqlAssociation('module', 'm', false) . '\n LEFT JOIN `' . _DB_PREFIX_ . 'module_preference` mp ON (mp.`module` = m.`name` AND mp.`id_employee` = ' . (int) $id_employee . ')');\n foreach ($result as $row) {\n $modules_installed[$row['name']] = $row;\n }\n\n foreach ($modules_dir as $module) {\n $module_errors = [];\n if (Module::useTooMuchMemory()) {\n $module_errors[] = Context::getContext()->getTranslator()->trans('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration', [], 'Admin.Modules.Notification');\n\n break;\n }\n\n $iso = substr(Context::getContext()->language->iso_code, 0, 2);\n\n // Check if config.xml module file exists and if it's not outdated\n\n if ($iso == 'en') {\n $config_file = _PS_MODULE_DIR_ . $module . '/config.xml';\n } else {\n $config_file = _PS_MODULE_DIR_ . $module . '/config_' . $iso . '.xml';\n }\n\n $xml_exist = (file_exists($config_file));\n $need_new_config_file = $xml_exist ? (@filemtime($config_file) < @filemtime(_PS_MODULE_DIR_ . $module . '/' . $module . '.php')) : true;\n\n // If config.xml exists and that the use config flag is at true\n if ($use_config && $xml_exist && !$need_new_config_file) {\n // Load config.xml\n libxml_use_internal_errors(true);\n $xml_module = @simplexml_load_file($config_file);\n if (!$xml_module) {\n $module_errors[] = Context::getContext()->getTranslator()->trans(\n '%s could not be loaded.',\n [$config_file],\n 'Admin.Modules.Notification'\n );\n\n break;\n }\n foreach (libxml_get_errors() as $error) {\n $module_errors[] = '[' . $module . '] ' . Context::getContext()->getTranslator()->trans('Error found in config file:', [], 'Admin.Modules.Notification') . ' ' . htmlentities($error->message);\n }\n libxml_clear_errors();\n\n // If no errors in Xml, no need instand and no need new config.xml file, we load only translations\n if (!count($module_errors) && (int) $xml_module->need_instance == 0) {\n $file = _PS_MODULE_DIR_ . $module . '/' . Context::getContext()->language->iso_code . '.php';\n if (Tools::file_exists_cache($file) && include_once ($file)) {\n if (isset($_MODULE) && is_array($_MODULE)) {\n $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;\n }\n }\n\n $item = new \\stdClass();\n $item->id = 0;\n $item->warning = '';\n\n foreach ($xml_module as $k => $v) {\n $item->$k = (string) $v;\n }\n\n $item->displayName = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string) $xml_module->name));\n $item->description = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->description), (string) $xml_module->name));\n $item->author = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->author), (string) $xml_module->name));\n $item->author_uri = (isset($xml_module->author_uri) && $xml_module->author_uri) ? stripslashes($xml_module->author_uri) : false;\n\n if (isset($xml_module->confirmUninstall)) {\n $item->confirmUninstall = Translate::getModuleTranslation((string) $xml_module->name, html_entity_decode(Module::configXmlStringFormat($xml_module->confirmUninstall)), (string) $xml_module->name);\n }\n\n $item->active = 0;\n $item->onclick_option = false;\n $item->trusted = Module::isModuleTrusted($item->name);\n\n $module_list[$item->name . '_disk'] = $item;\n\n $module_name_list[] = '\\'' . pSQL($item->name) . '\\'';\n $modules_name_to_cursor[Tools::strtolower((string) ($item->name))] = $item;\n }\n }\n\n // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file\n if (!$use_config || !$xml_exist || (isset($xml_module->need_instance) && (int) $xml_module->need_instance == 1) || $need_new_config_file) {\n // If class does not exists, we include the file\n if (!class_exists($module, false)) {\n // Get content from php file\n $file_path = _PS_MODULE_DIR_ . $module . '/' . $module . '.php';\n $file = trim(file_get_contents(_PS_MODULE_DIR_ . $module . '/' . $module . '.php'));\n\n try {\n $parser = (new PhpParser\\ParserFactory())->create(PhpParser\\ParserFactory::ONLY_PHP7);\n $parser->parse($file);\n require_once $file_path;\n } catch (PhpParser\\Error $e) {\n $errors[] = Context::getContext()->getTranslator()->trans('%1$s (parse error in %2$s)', [$module, substr($file_path, strlen(_PS_ROOT_DIR_))], 'Admin.Modules.Notification');\n }\n\n preg_match('/\\n[\\s\\t]*?namespace\\s.*?;/', $file, $ns);\n if (!empty($ns)) {\n $ns = preg_replace('/\\n[\\s\\t]*?namespace\\s/', '', $ns[0]);\n $ns = rtrim($ns, ';');\n $module = $ns . '\\\\' . $module;\n }\n }\n\n // If class exists, we just instanciate it\n if (class_exists($module, false)) {\n try {\n $tmp_module = ServiceLocator::get($module);\n\n $item = new \\stdClass();\n\n $item->id = (int) $tmp_module->id;\n $item->warning = $tmp_module->warning;\n $item->name = $tmp_module->name;\n $item->version = $tmp_module->version;\n $item->tab = $tmp_module->tab;\n $item->displayName = $tmp_module->displayName;\n $item->description = stripslashes($tmp_module->description);\n $item->author = $tmp_module->author;\n $item->author_uri = (isset($tmp_module->author_uri) && $tmp_module->author_uri) ? $tmp_module->author_uri : false;\n $item->limited_countries = $tmp_module->limited_countries;\n $item->parent_class = get_parent_class($module);\n $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0;\n $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0;\n $item->active = $tmp_module->active;\n $item->trusted = Module::isModuleTrusted($tmp_module->name);\n $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null;\n $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null;\n $item->confirmUninstall = isset($tmp_module->confirmUninstall) ? html_entity_decode($tmp_module->confirmUninstall) : null;\n $item->description_full = stripslashes($tmp_module->description_full);\n $item->additional_description = isset($tmp_module->additional_description) ? stripslashes($tmp_module->additional_description) : null;\n $item->compatibility = isset($tmp_module->compatibility) ? (array) $tmp_module->compatibility : null;\n $item->nb_rates = isset($tmp_module->nb_rates) ? (array) $tmp_module->nb_rates : null;\n $item->avg_rate = isset($tmp_module->avg_rate) ? (array) $tmp_module->avg_rate : null;\n $item->badges = isset($tmp_module->badges) ? (array) $tmp_module->badges : null;\n $item->url = isset($tmp_module->url) ? $tmp_module->url : null;\n $item->onclick_option = method_exists($module, 'onclickOption') ? true : false;\n\n if ($item->onclick_option) {\n $href = Context::getContext()->link->getAdminLink('Module', true, [], ['module_name' => $tmp_module->name, 'tab_module' => $tmp_module->tab]);\n $item->onclick_option_content = [];\n $option_tab = ['desactive', 'reset', 'configure', 'delete'];\n\n foreach ($option_tab as $opt) {\n $item->onclick_option_content[$opt] = $tmp_module->onclickOption($opt, $href);\n }\n }\n\n $module_list[$item->name . '_disk'] = $item;\n\n if (!$xml_exist || $need_new_config_file) {\n static::$_generate_config_xml_mode = true;\n $tmp_module->_generateConfigXml();\n static::$_generate_config_xml_mode = false;\n }\n\n unset($tmp_module);\n } catch (Exception $e) {\n }\n } else {\n $module_errors[] = Context::getContext()->getTranslator()->trans('%1$s (class missing in %2$s)', [$module, substr($file_path, strlen(_PS_ROOT_DIR_))], 'Admin.Modules.Notification');\n }\n }\n $errors = array_merge($errors, $module_errors);\n }\n\n // Get modules information from database\n if (!empty($module_name_list)) {\n $list = Shop::getContextListShopID();\n $sql = 'SELECT m.id_module, m.name, (\n SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN (' . implode(',', $list) . ')\n ) as total\n FROM ' . _DB_PREFIX_ . 'module m\n WHERE LOWER(m.name) IN (' . Tools::strtolower(implode(',', $module_name_list)) . ')';\n $results = Db::getInstance()->executeS($sql);\n\n foreach ($results as $result) {\n if (isset($modules_name_to_cursor[Tools::strtolower($result['name'])])) {\n $module_cursor = $modules_name_to_cursor[Tools::strtolower($result['name'])];\n $module_cursor->id = (int) $result['id_module'];\n $module_cursor->active = ($result['total'] == count($list)) ? 1 : 0;\n }\n }\n }\n\n // Get Default Country Modules and customer module\n $files_list = [\n ['type' => 'addonsNative', 'file' => _PS_ROOT_DIR_ . static::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0],\n ['type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_ . static::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0],\n ['type' => 'addonsBought', 'file' => _PS_ROOT_DIR_ . static::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1],\n ];\n foreach ($files_list as $f) {\n if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $logged_on_addons)) {\n if (Module::useTooMuchMemory()) {\n $errors[] = Context::getContext()->getTranslator()->trans('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration', [], 'Admin.Modules.Notification');\n\n break;\n }\n\n $file = $f['file'];\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $flag_found = 0;\n\n foreach ($module_list as $k => &$m) {\n if (Tools::strtolower($m->name) == Tools::strtolower($modaddons->name) && !isset($m->available_on_addons)) {\n $flag_found = 1;\n if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1) {\n $module_list[$k]->version_addons = $modaddons->version;\n }\n }\n }\n\n if ($flag_found == 0) {\n $item = new \\stdClass();\n $item->id = 0;\n $item->warning = '';\n $item->type = strip_tags((string) $f['type']);\n $item->name = strip_tags((string) $modaddons->name);\n $item->version = strip_tags((string) $modaddons->version);\n $item->tab = strip_tags((string) $modaddons->tab);\n $item->displayName = strip_tags((string) $modaddons->displayName);\n $item->description = stripslashes(strip_tags((string) $modaddons->description));\n $item->description_full = stripslashes(strip_tags((string) $modaddons->description_full));\n $item->author = strip_tags((string) $modaddons->author);\n $item->limited_countries = [];\n $item->parent_class = '';\n $item->onclick_option = false;\n $item->is_configurable = 0;\n $item->need_instance = 0;\n $item->not_on_disk = 1;\n $item->available_on_addons = 1;\n $item->trusted = Module::isModuleTrusted($item->name);\n $item->active = 0;\n $item->description_full = stripslashes($modaddons->description_full);\n $item->additional_description = isset($modaddons->additional_description) ? stripslashes($modaddons->additional_description) : null;\n $item->compatibility = isset($modaddons->compatibility) ? (array) $modaddons->compatibility : null;\n $item->nb_rates = isset($modaddons->nb_rates) ? (array) $modaddons->nb_rates : null;\n $item->avg_rate = isset($modaddons->avg_rate) ? (array) $modaddons->avg_rate : null;\n $item->badges = isset($modaddons->badges) ? (array) $modaddons->badges : null;\n $item->url = isset($modaddons->url) ? $modaddons->url : null;\n if (isset($item->description_full) && trim($item->description_full) != '') {\n $item->show_quick_view = true;\n }\n\n if (isset($modaddons->img)) {\n $item->image = Module::copyModAddonsImg($modaddons);\n }\n\n if ($item->type == 'addonsMustHave') {\n $item->addons_buy_url = strip_tags((string) $modaddons->url);\n $prices = (array) $modaddons->price;\n $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');\n\n foreach ($prices as $currency => $price) {\n if ($id_currency = Currency::getIdByIsoCode($currency)) {\n $item->price = (float) $price;\n $item->id_currency = (int) $id_currency;\n\n if ($id_default_currency == $id_currency) {\n break;\n }\n }\n }\n }\n\n $module_list[$item->name . '_feed'] = $item;\n }\n\n if (isset($module_list[$modaddons->name . '_disk'])) {\n $module_list[$modaddons->name . '_disk']->description_full = stripslashes(strip_tags((string) $modaddons->description_full));\n $module_list[$modaddons->name . '_disk']->additional_description = stripslashes(strip_tags((string) $modaddons->additional_description));\n $module_list[$modaddons->name . '_disk']->image = Module::copyModAddonsImg($modaddons);\n $module_list[$modaddons->name . '_disk']->show_quick_view = true;\n }\n }\n }\n }\n }\n\n foreach ($module_list as $key => &$module) {\n if (!isset($module->tab)) {\n $module->tab = 'others';\n }\n if (defined('_PS_HOST_MODE_') && in_array($module->name, static::$hosted_modules_blacklist)) {\n unset($module_list[$key]);\n } elseif (isset($modules_installed[$module->name])) {\n $module->installed = true;\n $module->database_version = $modules_installed[$module->name]['version'];\n $module->interest = $modules_installed[$module->name]['interest'];\n $module->enable_device = $modules_installed[$module->name]['enable_device'];\n } else {\n $module->installed = false;\n $module->database_version = 0;\n $module->interest = 0;\n }\n }\n\n usort($module_list, function ($a, $b) {\n return strnatcasecmp($a->displayName, $b->displayName);\n });\n if ($errors) {\n if (!isset(Context::getContext()->controller) && !Context::getContext()->controller->controller_name) {\n echo '<div class=\"alert error\"><h3>' . Context::getContext()->getTranslator()->trans('The following module(s) could not be loaded', [], 'Admin.Modules.Notification') . ':</h3><ol>';\n foreach ($errors as $error) {\n echo '<li>' . $error . '</li>';\n }\n echo '</ol></div>';\n } else {\n foreach ($errors as $error) {\n Context::getContext()->controller->errors[] = $error;\n }\n }\n }\n\n return $module_list;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function render()\n\t{\n\t\t$album = $this->album;\n\t\t$arguments = $this->arguments;\n\t\tif (isset($arguments['slider'])) {\n\t\t\treturn $this->twig->render('fotoalbum/slider.html.twig', [\n\t\t\t\t'fotos' => ArrayUtil::array_shuffle($album->getFotos()),\n\t\t\t]);\n\t\t} else {\n\t\t\t$view = new FotoAlbumBBView($album);\n\n\t\t\tif ($this->env->quote_level > 0 || isset($arguments['compact'])) {\n\t\t\t\t$view->makeCompact();\n\t\t\t}\n\t\t\tif (isset($arguments['rows'])) {\n\t\t\t\t$view->setRows((int) $arguments['rows']);\n\t\t\t}\n\t\t\tif (isset($arguments['perrow'])) {\n\t\t\t\t$view->setPerRow((int) $arguments['perrow']);\n\t\t\t}\n\t\t\tif (isset($arguments['bigfirst'])) {\n\t\t\t\t$view->setBig(0);\n\t\t\t}\n\t\t\tif (isset($arguments['big'])) {\n\t\t\t\tif ($arguments['big'] == 'first') {\n\t\t\t\t\t$view->setBig(0);\n\t\t\t\t} else {\n\t\t\t\t\t$view->setBig($arguments['big']);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $view->getHtml();\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function addFiles(array $input, $options = [])\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $default_options = [\n 'force_update' => false,\n 'content_field' => 'content',\n 'name' => 'filename',\n 'date' => null,\n ];\n $options = array_merge($default_options, $options);\n\n $uploadName = '_' . $options['name'];\n $tagUploadName = '_tag_' . $options['name'];\n $prefixUploadName = '_prefix_' . $options['name'];\n\n if (\n !isset($input[$uploadName])\n || (count($input[$uploadName]) === 0)\n ) {\n return $input;\n }\n $docadded = [];\n $donotif = $input['_donotif'] ?? 0;\n $disablenotif = $input['_disablenotif'] ?? 0;\n\n foreach ($input[$uploadName] as $key => $file) {\n $doc = new Document();\n $docitem = new Document_Item();\n $docID = 0;\n $filename = GLPI_TMP_DIR . \"/\" . $file;\n $input2 = [];\n\n //If file tag is present\n if (\n isset($input[$tagUploadName])\n && !empty($input[$tagUploadName][$key])\n ) {\n $input['_tag'][$key] = $input[$tagUploadName][$key];\n }\n\n //retrieve entity\n $entities_id = $_SESSION['glpiactive_entity'] ?? 0;\n if (isset($this->fields[\"entities_id\"])) {\n $entities_id = $this->fields[\"entities_id\"];\n } else if (isset($input['entities_id'])) {\n $entities_id = $input['entities_id'];\n } else if (isset($input['_job']->fields['entities_id'])) {\n $entities_id = $input['_job']->fields['entities_id'];\n }\n\n //retrieve is_recursive\n $is_recursive = 0;\n if (isset($this->fields[\"is_recursive\"])) {\n $is_recursive = $this->fields[\"is_recursive\"];\n } else if (isset($input['is_recursive'])) {\n $is_recursive = $input['is_recursive'];\n } else if (isset($input['_job']->fields['is_recursive'])) {\n $is_recursive = $input['_job']->fields['is_recursive'];\n } else if ($this instanceof CommonDBVisible) {\n // CommonDBVisible visibility restriction is unpredictable as\n // it may change over time, and can be related to dynamic profiles assignation.\n // Related documents have to be available on all entities.\n $is_recursive = 1;\n }\n\n // Check for duplicate and availability (e.g. file deleted in _files)\n if ($doc->getDuplicateOf($entities_id, $filename)) {\n $docID = $doc->fields[\"id\"];\n // File already exist, we replace the tag by the existing one\n if (\n isset($input['_tag'][$key])\n && ($docID > 0)\n && isset($input[$options['content_field']])\n ) {\n $input[$options['content_field']] = str_replace(\n $input['_tag'][$key],\n $doc->fields[\"tag\"],\n $input[$options['content_field']]\n );\n $docadded[$docID]['tag'] = $doc->fields[\"tag\"];\n }\n if (!$doc->checkAvailability($filename)) {\n $input2 = [\n 'id' => $docID,\n '_only_if_upload_succeed' => 1,\n '_filename' => [$file],\n 'current_filepath' => $filename,\n ];\n if (isset($this->input[$prefixUploadName][$key])) {\n $input2[$prefixUploadName] = [$this->input[$prefixUploadName][$key]];\n }\n $doc->update($input2);\n }\n } else {\n if (static::class === Ticket::class) {\n //TRANS: Default document to files attached to tickets : %d is the ticket id\n $input2[\"name\"] = sprintf(__('Document Ticket %d'), $this->getID());\n $input2[\"tickets_id\"] = $this->getID();\n }\n\n if (isset($input['_tag'][$key])) {\n // Insert image tag\n $input2[\"tag\"] = $input['_tag'][$key];\n }\n\n $input2[\"entities_id\"] = $entities_id;\n $input2[\"is_recursive\"] = $is_recursive;\n $input2[\"documentcategories_id\"] = $CFG_GLPI[\"documentcategories_id_forticket\"];\n $input2[\"_only_if_upload_succeed\"] = 1;\n $input2[\"_filename\"] = [$file];\n if (isset($this->input[$prefixUploadName][$key])) {\n $input2[$prefixUploadName] = [$this->input[$prefixUploadName][$key]];\n }\n $docID = $doc->add($input2);\n\n if (isset($input['_tag'][$key])) {\n // Store image tag\n $docadded[$docID]['tag'] = $doc->fields[\"tag\"];\n }\n }\n\n if ($docID > 0) {\n // complete doc information\n $docadded[$docID]['data'] = sprintf(\n __('%1$s - %2$s'),\n $doc->fields[\"name\"],\n $doc->fields[\"filename\"]\n );\n $docadded[$docID]['filepath'] = $doc->fields[\"filepath\"];\n\n // add doc - item link\n $toadd = [\n 'documents_id' => $docID,\n '_do_notif' => $donotif,\n '_disablenotif' => $disablenotif,\n 'itemtype' => static::class,\n 'items_id' => $this->getID()\n ];\n // Set date, needed if it differs from the creation date\n $toadd['date'] = $options['date'] ?? $_SESSION['glpi_currenttime'];\n\n if (isset($input['users_id'])) {\n $toadd['users_id'] = $input['users_id'];\n }\n if (\n isset($input[$options['content_field']])\n && str_contains($input[$options['content_field']], $doc->fields[\"tag\"])\n && str_contains($doc->fields['mime'], 'image/')\n ) {\n //do not display inline docs in timeline\n $toadd['timeline_position'] = CommonITILObject::NO_TIMELINE;\n } else {\n //get timeline_position from parent (followup / task / doc)\n if (isset($input['timeline_position'])) {\n $toadd['timeline_position'] = $input['timeline_position'];\n }\n }\n\n $docitem->add($toadd);\n }\n // Only notification for the first New doc\n $donotif = false;\n }\n\n // manage content transformation\n if (isset($input[$options['content_field']])) {\n $input[$options['content_field']] = Toolbox::convertTagToImage(\n $input[$options['content_field']],\n $this,\n $docadded,\n $options['_add_link'] ?? true,\n );\n\n if (isset($this->input['_forcenotif'])) {\n $input['_forcenotif'] = $this->input['_forcenotif'];\n unset($input['_disablenotif']);\n }\n\n // force update of content on add process (we are in post_addItem function)\n if ($options['force_update']) {\n $this->fields[$options['content_field']] = $input[$options['content_field']];\n $this->updateInDB([$options['content_field']]);\n }\n }\n\n return $input;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['url'])) {\n $this->setUrl($data['url']);\n }\n if (isset($data['version'])) {\n $this->setVersion($data['version']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['legalState'])) {\n $this->setLegalState($data['legalState']);\n }\n if (isset($data['instantiatesCanonical'])) {\n $this->setInstantiatesCanonical($data['instantiatesCanonical']);\n }\n if (isset($data['instantiatesUri'])) {\n $this->setInstantiatesUri($data['instantiatesUri']);\n }\n if (isset($data['contentDerivative'])) {\n $this->setContentDerivative($data['contentDerivative']);\n }\n if (isset($data['issued'])) {\n $this->setIssued($data['issued']);\n }\n if (isset($data['applies'])) {\n $this->setApplies($data['applies']);\n }\n if (isset($data['expirationType'])) {\n $this->setExpirationType($data['expirationType']);\n }\n if (isset($data['subject'])) {\n if (is_array($data['subject'])) {\n foreach ($data['subject'] as $d) {\n $this->addSubject($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"subject\" must be array of objects or null, ' . gettype($data['subject']) . ' seen.');\n }\n }\n if (isset($data['authority'])) {\n if (is_array($data['authority'])) {\n foreach ($data['authority'] as $d) {\n $this->addAuthority($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"authority\" must be array of objects or null, ' . gettype($data['authority']) . ' seen.');\n }\n }\n if (isset($data['domain'])) {\n if (is_array($data['domain'])) {\n foreach ($data['domain'] as $d) {\n $this->addDomain($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"domain\" must be array of objects or null, ' . gettype($data['domain']) . ' seen.');\n }\n }\n if (isset($data['site'])) {\n if (is_array($data['site'])) {\n foreach ($data['site'] as $d) {\n $this->addSite($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"site\" must be array of objects or null, ' . gettype($data['site']) . ' seen.');\n }\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['title'])) {\n $this->setTitle($data['title']);\n }\n if (isset($data['subtitle'])) {\n $this->setSubtitle($data['subtitle']);\n }\n if (isset($data['alias'])) {\n if (is_array($data['alias'])) {\n foreach ($data['alias'] as $d) {\n $this->addAlias($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"alias\" must be array of objects or null, ' . gettype($data['alias']) . ' seen.');\n }\n }\n if (isset($data['author'])) {\n $this->setAuthor($data['author']);\n }\n if (isset($data['scope'])) {\n $this->setScope($data['scope']);\n }\n if (isset($data['topicCodeableConcept'])) {\n $this->setTopicCodeableConcept($data['topicCodeableConcept']);\n }\n if (isset($data['topicReference'])) {\n $this->setTopicReference($data['topicReference']);\n }\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['subType'])) {\n if (is_array($data['subType'])) {\n foreach ($data['subType'] as $d) {\n $this->addSubType($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"subType\" must be array of objects or null, ' . gettype($data['subType']) . ' seen.');\n }\n }\n if (isset($data['contentDefinition'])) {\n $this->setContentDefinition($data['contentDefinition']);\n }\n if (isset($data['term'])) {\n if (is_array($data['term'])) {\n foreach ($data['term'] as $d) {\n $this->addTerm($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"term\" must be array of objects or null, ' . gettype($data['term']) . ' seen.');\n }\n }\n if (isset($data['supportingInfo'])) {\n if (is_array($data['supportingInfo'])) {\n foreach ($data['supportingInfo'] as $d) {\n $this->addSupportingInfo($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"supportingInfo\" must be array of objects or null, ' . gettype($data['supportingInfo']) . ' seen.');\n }\n }\n if (isset($data['relevantHistory'])) {\n if (is_array($data['relevantHistory'])) {\n foreach ($data['relevantHistory'] as $d) {\n $this->addRelevantHistory($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"relevantHistory\" must be array of objects or null, ' . gettype($data['relevantHistory']) . ' seen.');\n }\n }\n if (isset($data['signer'])) {\n if (is_array($data['signer'])) {\n foreach ($data['signer'] as $d) {\n $this->addSigner($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"signer\" must be array of objects or null, ' . gettype($data['signer']) . ' seen.');\n }\n }\n if (isset($data['friendly'])) {\n if (is_array($data['friendly'])) {\n foreach ($data['friendly'] as $d) {\n $this->addFriendly($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"friendly\" must be array of objects or null, ' . gettype($data['friendly']) . ' seen.');\n }\n }\n if (isset($data['legal'])) {\n if (is_array($data['legal'])) {\n foreach ($data['legal'] as $d) {\n $this->addLegal($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"legal\" must be array of objects or null, ' . gettype($data['legal']) . ' seen.');\n }\n }\n if (isset($data['rule'])) {\n if (is_array($data['rule'])) {\n foreach ($data['rule'] as $d) {\n $this->addRule($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"rule\" must be array of objects or null, ' . gettype($data['rule']) . ' seen.');\n }\n }\n if (isset($data['legallyBindingAttachment'])) {\n $this->setLegallyBindingAttachment($data['legallyBindingAttachment']);\n }\n if (isset($data['legallyBindingReference'])) {\n $this->setLegallyBindingReference($data['legallyBindingReference']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "final public static function generateTrustedXml()\n {\n $modules_on_disk = Module::getModulesDirOnDisk();\n $trusted = array();\n $untrusted = array();\n\n $trusted_modules_xml = array(\n _PS_ROOT_DIR_.self::CACHE_FILE_ALL_COUNTRY_MODULES_LIST,\n _PS_ROOT_DIR_.self::CACHE_FILE_MUST_HAVE_MODULES_LIST,\n );\n\n if (file_exists(_PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST)) {\n $trusted_modules_xml[] = _PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST;\n }\n\n // Create 2 arrays with trusted and untrusted modules\n foreach ($trusted_modules_xml as $file) {\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $trusted[] = Tools::strtolower((string)$modaddons->name);\n }\n }\n }\n\n foreach (glob(_PS_ROOT_DIR_.'/config/xml/themes/*.xml') as $theme_xml) {\n if (file_exists($theme_xml)) {\n $content = Tools::file_get_contents($theme_xml);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml) {\n foreach ($xml->modules->module as $modaddons) {\n if ((string)$modaddons['action'] == 'install') {\n $trusted[] = Tools::strtolower((string)$modaddons['name']);\n }\n }\n }\n }\n }\n\n foreach ($modules_on_disk as $name) {\n if (!in_array($name, $trusted)) {\n if (Module::checkModuleFromAddonsApi($name)) {\n $trusted[] = Tools::strtolower($name);\n } else {\n $untrusted[] = Tools::strtolower($name);\n }\n }\n }\n\n $context = Context::getContext();\n\n // Save the 2 arrays into XML files\n $trusted_xml = new SimpleXMLElement('<modules_list/>');\n $trusted_xml->addAttribute('theme', $context->shop->theme->getName());\n $modules = $trusted_xml->addChild('modules');\n $modules->addAttribute('type', 'trusted');\n foreach ($trusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success = file_put_contents(_PS_ROOT_DIR_.self::CACHE_FILE_TRUSTED_MODULES_LIST, $trusted_xml->asXML());\n\n $untrusted_xml = new SimpleXMLElement('<modules_list/>');\n $modules = $untrusted_xml->addChild('modules');\n $modules->addAttribute('type', 'untrusted');\n foreach ($untrusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success &= file_put_contents(_PS_ROOT_DIR_.self::CACHE_FILE_UNTRUSTED_MODULES_LIST, $untrusted_xml->asXML());\n\n if ($success) {\n return true;\n } else {\n Tools::displayError('Trusted and Untrusted XML have not been generated properly');\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function createContainerClasses(): void\n {\n $containerDefinition = [];\n\n if (!empty($this->classDefinitions)) {\n foreach ($this->classDefinitions as $cl) {\n $class = DataObject\\ClassDefinition::getByName($cl['classname']);\n if (!$class) {\n throw new Exception('Could not load class ' . $cl['classname']);\n }\n\n $fd = $class->getFieldDefinition($cl['fieldname']);\n if (!$fd instanceof DataObject\\ClassDefinition\\Data\\Objectbricks) {\n throw new Exception('Could not resolve field definition for ' . $cl['fieldname']);\n }\n\n $old = $this->getAllowedTypesWithFieldname($class);\n\n $allowedTypes = $fd->getAllowedTypes() ?: [];\n\n if (!in_array($this->key, $allowedTypes)) {\n $allowedTypes[] = $this->key;\n }\n\n $fd->setAllowedTypes($allowedTypes);\n $new = $this->getAllowedTypesWithFieldname($class);\n\n if (array_diff($new, $old) || array_diff($old, $new)) {\n $class->save();\n } else {\n // still, the brick fields definitions could have changed.\n Cache::clearTag('class_'.$class->getId());\n Logger::debug('Objectbrick ' . $this->getKey() . ', no change for class ' . $class->getName());\n }\n }\n }\n\n Pimcore::getContainer()->get(PHPObjectBrickContainerClassDumperInterface::class)->dumpContainerClasses($this);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function _fieldsSetLocale( &$fields, $fields_locale ){\n\n foreach($fields as $idx=>$field){\n\n if(!isEmptyArray(@$field['children'])){\n\n $fld_loc = $this->_getFieldByID($field['dtID'], $fields_locale);\n if($fld_loc && @$fld_loc['groupHeader']){\n $fields[$idx]['groupHeader'] = $fld_loc['groupHeader'];\n }\n\n $this->_fieldsSetLocale($fields[$idx]['children'], $fields_locale);\n\n }else{\n\n $fld_loc = $this->_getFieldByID($field['dtID'], $fields_locale);\n if($fld_loc && @$fld_loc['dtFields']){\n if(@$fld_loc['dtFields']['rst_DisplayName']){\n $fields[$idx]['dtFields']['rst_DisplayName'] = $fld_loc['dtFields']['rst_DisplayName'];\n }\n if(@$fld_loc['dtFields']['rst_DisplayHelpText']){\n $fields[$idx]['dtFields']['rst_DisplayHelpText'] = $fld_loc['dtFields']['rst_DisplayHelpText'];\n }\n }\n\n\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function import(array $input)\n {\n if (empty($input['name']) && empty($input['completename'])) {\n return -1;\n }\n\n if (empty($input['completename'])) {\n $input['completename'] = $input['name'];\n unset($input['name']);\n }\n\n // Import a full tree from completename\n $names = explode('>', $input['completename']);\n $fk = $this->getForeignKeyField();\n $i = count($names);\n $parent = 0;\n\n foreach ($names as $name) {\n $i--;\n $name = trim($name);\n if (empty($name)) {\n // Skip empty name (completename starting/endind with >, double >, ...)\n continue;\n }\n\n $tmp = [\n 'name' => $name,\n $fk => $parent,\n ];\n\n if (isset($input['is_recursive'])) {\n $tmp['is_recursive'] = $input['is_recursive'];\n }\n if (isset($input['entities_id'])) {\n $tmp['entities_id'] = $input['entities_id'];\n }\n\n if (!$i) {\n // Other fields (comment, ...) only for last node of the tree\n foreach ($input as $key => $val) {\n if ($key != 'completename') {\n $tmp[$key] = $val;\n }\n }\n }\n\n $parent = parent::import($tmp);\n }\n return $parent;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function getExceptionsStatic($id_module, $id_hook, $dispatch = false)\n {\n $cache_id = 'exceptionsCache';\n if (!Cache::isStored($cache_id)) {\n $exceptions_cache = array();\n $sql = 'SELECT * FROM `'._DB_PREFIX_.'hook_module_exceptions`\n WHERE `id_shop` IN ('.implode(', ', Shop::getContextListShopID()).')';\n $db = Db::getInstance();\n $result = $db->executeS($sql, false);\n while ($row = $db->nextRow($result)) {\n if (!$row['file_name']) {\n continue;\n }\n $key = $row['id_hook'].'-'.$row['id_module'];\n if (!isset($exceptions_cache[$key])) {\n $exceptions_cache[$key] = array();\n }\n if (!isset($exceptions_cache[$key][$row['id_shop']])) {\n $exceptions_cache[$key][$row['id_shop']] = array();\n }\n $exceptions_cache[$key][$row['id_shop']][] = $row['file_name'];\n }\n Cache::store($cache_id, $exceptions_cache);\n } else {\n $exceptions_cache = Cache::retrieve($cache_id);\n }\n\n $key = $id_hook.'-'.$id_module;\n $array_return = array();\n if ($dispatch) {\n foreach (Shop::getContextListShopID() as $shop_id) {\n if (isset($exceptions_cache[$key], $exceptions_cache[$key][$shop_id])) {\n $array_return[$shop_id] = $exceptions_cache[$key][$shop_id];\n }\n }\n } else {\n foreach (Shop::getContextListShopID() as $shop_id) {\n if (isset($exceptions_cache[$key], $exceptions_cache[$key][$shop_id])) {\n foreach ($exceptions_cache[$key][$shop_id] as $file) {\n if (!in_array($file, $array_return)) {\n $array_return[] = $file;\n }\n }\n }\n }\n }\n return $array_return;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function getDataForField(DataObject\\Concrete $object, string $key, DataObject\\ClassDefinition\\Data $fielddefinition, bool $objectFromVersion, int $level = 0): void\n {\n $parent = DataObject\\Service::hasInheritableParentObject($object);\n $getter = 'get' . ucfirst($key);\n\n // Editmode optimization for lazy loaded relations (note that this is just for AbstractRelations, not for all\n // LazyLoadingSupportInterface types. It tries to optimize fetching the data needed for the editmode without\n // loading the entire target element.\n // ReverseObjectRelation should go in there anyway (regardless if it a version or not),\n // so that the values can be loaded.\n if (\n (!$objectFromVersion && $fielddefinition instanceof AbstractRelations)\n || $fielddefinition instanceof ReverseObjectRelation\n ) {\n $refId = null;\n\n if ($fielddefinition instanceof ReverseObjectRelation) {\n $refKey = $fielddefinition->getOwnerFieldName();\n $refClass = DataObject\\ClassDefinition::getByName($fielddefinition->getOwnerClassName());\n if ($refClass) {\n $refId = $refClass->getId();\n }\n } else {\n $refKey = $key;\n }\n\n $relations = $object->getRelationData($refKey, !$fielddefinition instanceof ReverseObjectRelation, $refId);\n\n if ($fielddefinition->supportsInheritance() && empty($relations) && !empty($parent)) {\n $this->getDataForField($parent, $key, $fielddefinition, $objectFromVersion, $level + 1);\n } else {\n $data = [];\n\n if ($fielddefinition instanceof DataObject\\ClassDefinition\\Data\\ManyToOneRelation) {\n if (isset($relations[0])) {\n $data = $relations[0];\n $data['published'] = (bool)$data['published'];\n } else {\n $data = null;\n }\n } elseif (\n ($fielddefinition instanceof DataObject\\ClassDefinition\\Data\\OptimizedAdminLoadingInterface && $fielddefinition->isOptimizedAdminLoading())\n || ($fielddefinition instanceof ManyToManyObjectRelation && !$fielddefinition->getVisibleFields() && !$fielddefinition instanceof DataObject\\ClassDefinition\\Data\\AdvancedManyToManyObjectRelation)\n ) {\n foreach ($relations as $rkey => $rel) {\n $index = $rkey + 1;\n $rel['fullpath'] = $rel['path'];\n $rel['classname'] = $rel['subtype'];\n $rel['rowId'] = $rel['id'] . AbstractRelations::RELATION_ID_SEPARATOR . $index . AbstractRelations::RELATION_ID_SEPARATOR . $rel['type'];\n $rel['published'] = (bool)$rel['published'];\n $data[] = $rel;\n }\n } else {\n $fieldData = $object->$getter();\n $data = $fielddefinition->getDataForEditmode($fieldData, $object, ['objectFromVersion' => $objectFromVersion]);\n }\n $this->objectData[$key] = $data;\n $this->metaData[$key]['objectid'] = $object->getId();\n $this->metaData[$key]['inherited'] = $level != 0;\n }\n } else {\n $fieldData = $object->$getter();\n $isInheritedValue = false;\n\n if ($fielddefinition instanceof DataObject\\ClassDefinition\\Data\\CalculatedValue) {\n $fieldData = new DataObject\\Data\\CalculatedValue($fielddefinition->getName());\n $fieldData->setContextualData('object', null, null, null, null, null, $fielddefinition);\n $value = $fielddefinition->getDataForEditmode($fieldData, $object, ['objectFromVersion' => $objectFromVersion]);\n } else {\n $value = $fielddefinition->getDataForEditmode($fieldData, $object, ['objectFromVersion' => $objectFromVersion]);\n }\n\n // following some exceptions for special data types (localizedfields, objectbricks)\n if ($value && ($fieldData instanceof DataObject\\Localizedfield || $fieldData instanceof DataObject\\Classificationstore)) {\n // make sure that the localized field participates in the inheritance detection process\n $isInheritedValue = $value['inherited'];\n }\n if ($fielddefinition instanceof DataObject\\ClassDefinition\\Data\\Objectbricks && is_array($value)) {\n // make sure that the objectbricks participate in the inheritance detection process\n foreach ($value as $singleBrickData) {\n if (!empty($singleBrickData['inherited'])) {\n $isInheritedValue = true;\n }\n }\n }\n\n if ($fielddefinition->isEmpty($fieldData) && !empty($parent)) {\n $this->getDataForField($parent, $key, $fielddefinition, $objectFromVersion, $level + 1);\n // exception for classification store. if there are no items then it is empty by definition.\n // consequence is that we have to preserve the metadata information\n // see https://github.com/pimcore/pimcore/issues/9329\n if ($fielddefinition instanceof DataObject\\ClassDefinition\\Data\\Classificationstore && $level == 0) {\n $this->objectData[$key]['metaData'] = $value['metaData'] ?? [];\n $this->objectData[$key]['inherited'] = true;\n }\n } else {\n $isInheritedValue = $isInheritedValue || ($level != 0);\n $this->metaData[$key]['objectid'] = $object->getId();\n\n $this->objectData[$key] = $value;\n $this->metaData[$key]['inherited'] = $isInheritedValue;\n\n if ($isInheritedValue && !$fielddefinition->isEmpty($fieldData) && !$fielddefinition->supportsInheritance()) {\n $this->objectData[$key] = null;\n $this->metaData[$key]['inherited'] = false;\n $this->metaData[$key]['hasParentValue'] = true;\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "function setStatus($status, $comments='', &$errors=array(), $set_closing_agent=true, $force_close=false) {\n global $cfg, $thisstaff;\n\n if ($thisstaff && !($role=$this->getRole($thisstaff)))\n return false;\n\n if ((!$status instanceof TicketStatus)\n && !($status = TicketStatus::lookup($status)))\n return false;\n\n // Double check permissions (when changing status)\n if ($role && $this->getStatusId()) {\n switch ($status->getState()) {\n case 'closed':\n if (!($role->hasPerm(Ticket::PERM_CLOSE)))\n return false;\n break;\n case 'deleted':\n // XXX: intercept deleted status and do hard delete TODO: soft deletes\n if ($role->hasPerm(Ticket::PERM_DELETE))\n return $this->delete($comments);\n // Agent doesn't have permission to delete tickets\n return false;\n break;\n }\n }\n\n $hadStatus = $this->getStatusId();\n if ($this->getStatusId() == $status->getId())\n return true;\n\n // Perform checks on the *new* status, _before_ the status changes\n $ecb = $refer = null;\n switch ($status->getState()) {\n case 'closed':\n // Check if ticket is closeable\n $closeable = $force_close ? true : $this->isCloseable();\n if ($closeable !== true)\n $errors['err'] = $closeable ?: sprintf(__('%s cannot be closed'), __('This ticket'));\n\n if ($errors)\n return false;\n\n $refer = $this->staff ?: $thisstaff;\n $this->closed = $this->lastupdate = SqlFunction::NOW();\n if ($thisstaff && $set_closing_agent)\n $this->staff = $thisstaff;\n // Clear overdue flags & due dates\n $this->clearOverdue(false);\n\n $ecb = function($t) use ($status) {\n $t->logEvent('closed', array('status' => array($status->getId(), $status->getName())), null, 'closed');\n $t->deleteDrafts();\n };\n break;\n case 'open':\n if ($this->isClosed() && $this->isReopenable()) {\n // Auto-assign to closing staff or the last respondent if the\n // agent is available and has access. Otherwise, put the ticket back\n // to unassigned pool.\n $dept = $this->getDept();\n $staff = $this->getStaff() ?: $this->getLastRespondent();\n $autoassign = (!$dept->disableReopenAutoAssign());\n if ($autoassign\n && $staff\n // Is agent on vacation ?\n && $staff->isAvailable()\n // Does the agent have access to dept?\n && $staff->canAccessDept($dept))\n $this->setStaffId($staff->getId());\n else\n $this->setStaffId(0); // Clear assignment\n }\n\n if ($this->isClosed()) {\n $this->closed = null;\n $this->lastupdate = $this->reopened = SqlFunction::NOW();\n $ecb = function ($t) {\n $t->logEvent('reopened', false, null, 'closed');\n // Set new sla duedate if any\n $t->updateEstDueDate();\n };\n }\n\n // If the ticket is not open then clear answered flag\n if (!$this->isOpen())\n $this->isanswered = 0;\n break;\n default:\n return false;\n\n }\n\n $this->status = $status;\n if (!$this->save(true))\n return false;\n\n // Refer thread to previously assigned or closing agent\n if ($refer && $cfg->autoReferTicketsOnClose())\n $this->getThread()->refer($refer);\n\n // Log status change b4 reload \u2014 if currently has a status. (On new\n // ticket, the ticket is opened and thereafter the status is set to\n // the requested status).\n if ($hadStatus) {\n $alert = false;\n if ($comments = ThreadEntryBody::clean($comments)) {\n // Send out alerts if comments are included\n $alert = true;\n $this->logNote(__('Status Changed'), $comments, $thisstaff, $alert);\n }\n }\n // Log events via callback\n if ($ecb)\n $ecb($this);\n elseif ($hadStatus)\n // Don't log the initial status change\n $this->logEvent('edited', array('status' => $status->getId()));\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function init()\n {\n Hook::exec(\n 'actionFrontControllerInitBefore',\n [\n 'controller' => $this,\n ]\n );\n\n /*\n * Globals are DEPRECATED as of version 1.5.0.1\n * Use the Context object to access objects instead.\n * Example: $this->context->cart\n */\n global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;\n\n if (self::$initialized) {\n return;\n }\n\n self::$initialized = true;\n\n parent::init();\n\n // enable Symfony error handler if debug mode enabled\n $this->initDebugguer();\n\n // If current URL use SSL, set it true (used a lot for module redirect)\n if (Tools::usingSecureMode()) {\n $useSSL = true;\n }\n\n // For compatibility with globals, DEPRECATED as of version 1.5.0.1\n $css_files = $this->css_files;\n $js_files = $this->js_files;\n\n $this->sslRedirection();\n\n if ($this->ajax) {\n $this->display_header = false;\n $this->display_footer = false;\n }\n\n // If account created with the 2 steps register process, remove 'account_created' from cookie\n if (isset($this->context->cookie->account_created)) {\n unset($this->context->cookie->account_created);\n }\n\n ob_start();\n\n $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://';\n $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false;\n $protocol_content = ($useSSL) ? 'https://' : 'http://';\n $link = new Link($protocol_link, $protocol_content);\n $this->context->link = $link;\n\n if ($id_cart = (int) $this->recoverCart()) {\n $this->context->cookie->id_cart = (int) $id_cart;\n }\n\n if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) {\n Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : ''));\n }\n\n /* Theme is missing */\n if (!is_dir(_PS_THEME_DIR_)) {\n throw new PrestaShopException($this->trans('Current theme is unavailable. Please check your theme\\'s directory name (\"%s\") and permissions.', [basename(rtrim(_PS_THEME_DIR_, '/\\\\'))], 'Admin.Design.Notification'));\n }\n\n if (Configuration::get('PS_GEOLOCATION_ENABLED')) {\n if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {\n $this->context->country = $new_default;\n }\n } elseif (Configuration::get('PS_DETECT_COUNTRY')) {\n $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency;\n $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;\n $has_address_type = false;\n\n if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {\n $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};\n }\n\n if ((!$has_currency || $has_country) && !$has_address_type) {\n $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ?\n (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry();\n\n $country = new Country($id_country, (int) $this->context->cookie->id_lang);\n\n if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {\n $this->context->country = $country;\n $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id;\n $this->context->cookie->iso_code_country = strtoupper($country->iso_code);\n }\n }\n }\n\n $currency = Tools::setCurrency($this->context->cookie);\n\n if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) {\n $this->context->customer->logout();\n\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n } elseif (isset($_GET['mylogout'])) {\n $this->context->customer->mylogout();\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n }\n\n /* Cart already exists */\n if ((int) $this->context->cookie->id_cart) {\n if (!isset($cart)) {\n $cart = new Cart($this->context->cookie->id_cart);\n }\n\n if (Validate::isLoadedObject($cart) && $cart->orderExists()) {\n PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);\n $this->context->cookie->check_cgv = false;\n } elseif ((int) (Configuration::get('PS_GEOLOCATION_ENABLED'))\n && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))\n && $cart->nbProducts()\n && (int) (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1\n && !FrontController::isInWhitelistForGeolocation()\n && !in_array($_SERVER['SERVER_NAME'], ['localhost', '127.0.0.1', '::1'])\n ) {\n /* Delete product of cart, if user can't make an order from his country */\n PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart);\n } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {\n // update cart values\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n }\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $currency->id;\n $cart->update();\n }\n /* Select an address if not set */\n if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||\n !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {\n $to_update = false;\n if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {\n $to_update = true;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {\n $to_update = true;\n $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if ($to_update) {\n $cart->update();\n }\n }\n }\n\n if (!isset($cart) || !$cart->id) {\n $cart = new Cart();\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $this->context->cookie->id_currency;\n $cart->id_guest = (int) $this->context->cookie->id_guest;\n $cart->id_shop_group = (int) $this->context->shop->id_shop_group;\n $cart->id_shop = $this->context->shop->id;\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n $cart->id_address_invoice = (int) $cart->id_address_delivery;\n } else {\n $cart->id_address_delivery = 0;\n $cart->id_address_invoice = 0;\n }\n\n // Needed if the merchant want to give a free product to every visitors\n $this->context->cart = $cart;\n CartRule::autoAddToCart($this->context);\n } else {\n $this->context->cart = $cart;\n }\n\n $this->context->cart->checkAndUpdateAddresses();\n\n $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));\n\n // Automatically redirect to the canonical URL if needed\n if (!empty($this->php_self) && !Tools::getValue('ajax')) {\n $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));\n }\n\n Product::initPricesComputation();\n\n $display_tax_label = $this->context->country->display_tax_label;\n if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {\n $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});\n $country = new Country((int) $infos['id_country']);\n $this->context->country = $country;\n if (Validate::isLoadedObject($country)) {\n $display_tax_label = $country->display_tax_label;\n }\n }\n\n /*\n * These shortcuts are DEPRECATED as of version 1.5.0.1\n * Use the Context to access objects instead.\n * Example: $this->context->cart\n */\n self::$cookie = $this->context->cookie;\n self::$cart = $cart;\n self::$smarty = $this->context->smarty;\n self::$link = $link;\n $defaultCountry = $this->context->country;\n\n $this->displayMaintenancePage();\n\n if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) {\n $this->displayRestrictedCountryPage();\n }\n\n $this->iso = $iso;\n $this->context->cart = $cart;\n $this->context->currency = $currency;\n\n Hook::exec(\n 'actionFrontControllerInitAfter',\n [\n 'controller' => $this,\n ]\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "protected function getGroupsObjects(array $gids, array $displayNames = []): array {\n\t\t$backends = [];\n\t\t$groups = [];\n\t\tforeach ($gids as $gid) {\n\t\t\t$backends[$gid] = [];\n\t\t\tif (!isset($displayNames[$gid])) {\n\t\t\t\t$displayNames[$gid] = null;\n\t\t\t}\n\t\t}\n\t\tforeach ($this->backends as $backend) {\n\t\t\tif ($backend instanceof IGroupDetailsBackend || $backend->implementsActions(GroupInterface::GROUP_DETAILS)) {\n\t\t\t\t/** @var IGroupDetailsBackend $backend */\n\t\t\t\tif ($backend instanceof IBatchMethodsBackend) {\n\t\t\t\t\t$groupDatas = $backend->getGroupsDetails($gids);\n\t\t\t\t} else {\n\t\t\t\t\t$groupDatas = [];\n\t\t\t\t\tforeach ($gids as $gid) {\n\t\t\t\t\t\t$groupDatas[$gid] = $backend->getGroupDetails($gid);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tforeach ($groupDatas as $gid => $groupData) {\n\t\t\t\t\tif (!empty($groupData)) {\n\t\t\t\t\t\t// take the display name from the last backend that has a non-null one\n\t\t\t\t\t\tif (isset($groupData['displayName'])) {\n\t\t\t\t\t\t\t$displayNames[$gid] = $groupData['displayName'];\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$backends[$gid][] = $backend;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ($backend instanceof IBatchMethodsBackend) {\n\t\t\t\t\t$existingGroups = $backend->groupsExists($gids);\n\t\t\t\t} else {\n\t\t\t\t\t$existingGroups = array_filter($gids, fn (string $gid): bool => $backend->groupExists($gid));\n\t\t\t\t}\n\t\t\t\tforeach ($existingGroups as $group) {\n\t\t\t\t\t$backends[$group][] = $backend;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tforeach ($gids as $gid) {\n\t\t\tif (count($backends[$gid]) === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$this->cachedGroups[$gid] = new Group($gid, $backends[$gid], $this->dispatcher, $this->userManager, $this, $displayNames[$gid]);\n\t\t\t$groups[$gid] = $this->cachedGroups[$gid];\n\t\t}\n\t\treturn $groups;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['active'])) {\n $this->setActive($data['active']);\n }\n if (isset($data['author'])) {\n $this->setAuthor($data['author']);\n }\n if (isset($data['item'])) {\n if (is_array($data['item'])) {\n foreach ($data['item'] as $d) {\n $this->addItem($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"item\" must be array of objects or null, ' . gettype($data['item']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getValidLayouts(Concrete $object): array\n {\n $layoutIds = null;\n $user = AdminTool::getCurrentUser();\n\n $resultList = [];\n $isMainAllowed = $user->getAdmin();\n\n $permissionSet = $object->getPermissions('layouts', $user);\n $layoutPermissions = self::getLayoutPermissions($object->getClassId(), $permissionSet);\n if (!$layoutPermissions || isset($layoutPermissions[0])) {\n $isMainAllowed = true;\n }\n\n if ($isMainAllowed) {\n $main = new ClassDefinition\\CustomLayout();\n $main->setId('0');\n $main->setName('Main');\n $resultList[0] = $main;\n }\n\n if ($user->getAdmin()) {\n $superLayout = new ClassDefinition\\CustomLayout();\n $superLayout->setId('-1');\n $superLayout->setName('Main (Admin Mode)');\n $resultList[-1] = $superLayout;\n }\n\n $classId = $object->getClassId();\n $list = new ClassDefinition\\CustomLayout\\Listing();\n $list->setOrder(function (ClassDefinition\\CustomLayout $a, ClassDefinition\\CustomLayout $b) {\n return strcmp($a->getName(), $b->getName());\n });\n if (is_array($layoutPermissions) && count($layoutPermissions)) {\n $layoutIds = array_values($layoutPermissions);\n }\n $list->setFilter(function (DataObject\\ClassDefinition\\CustomLayout $layout) use ($classId, $layoutIds) {\n $currentLayoutClassId = $layout->getClassId();\n $currentLayoutId = $layout->getId();\n $keep = $currentLayoutClassId === $classId && !str_contains($currentLayoutId, '.brick.');\n if ($keep && $layoutIds !== null) {\n $keep = in_array($currentLayoutId, $layoutIds);\n }\n\n return $keep;\n });\n $list = $list->load();\n\n if ((!count($resultList) && !count($list)) || (count($resultList) == 1 && !count($list))) {\n return [];\n }\n\n foreach ($list as $customLayout) {\n if ($customLayout instanceof ClassDefinition\\CustomLayout) {\n $resultList[$customLayout->getId()] = $customLayout;\n }\n }\n\n return $resultList;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function connectthedots($xarray,$yarray,$color='black',$thick=1,$startdot='',$enddot='') {\n if (!is_array($xarray) || !is_array($yarray)) {\n echo \"Error: x array and y array need to be arrays\";\n return [];\n }\n\tif (count($xarray)!=count($yarray)) {\n\t\techo \"Error: x array and y array need to have the same number of elements\";\n return [];\n\t}\n\t$outarr = array();\n\tfor ($i=1; $i<count($xarray); $i++) {\n\t\tif ($i==1) {$ed = $startdot;} else {$ed = '';}\n\t\tif ($i==count($xarray)-1) {$sd = $enddot;} else {$sd = '';}\n if (!isset($xarray[$i]) || !isset($xarray[$i-1]) || !isset($yarray[$i]) || !isset($yarray[$i-1])) {\n echo \"error: connectthedots needs arrays without missing elements\";\n return [];\n }\n\t\tif ($xarray[$i-1]==$xarray[$i]) {\n\t\t\t//vertical line\n\t\t\t$outarr[] = \"[{$xarray[$i]},t],$color,{$yarray[$i]},{$yarray[$i-1]},$sd,$ed,$thick\";\n\t\t} else {\n\t\t\t$xd = $xarray[$i-1] - $xarray[$i];\n\t\t\t$yd = $yarray[$i-1] - $yarray[$i];\n\t\t\t$outarr[] = \"[{$xarray[$i]}+t*($xd),{$yarray[$i]}+t*($yd)],$color,0,1,$sd,$ed,$thick\";\n\t\t}\n\t}\n\treturn $outarr;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function assignProperties(array $properties, $debug = false): void\n {\n foreach ($properties as $property) {\n $name = $property->key;\n $value = $property->value;\n\n switch($name) {\n case Property::AUDIO:\n case Property::AUDIO_URL:\n $this->audios[] = new Audio($value);\n break;\n case Property::AUDIO_SECURE_URL:\n case Property::AUDIO_TYPE:\n if (count($this->audios) > 0) {\n $this->handleAudioAttribute($this->audios[count($this->audios) - 1], $name, $value);\n } elseif ($debug) {\n throw new UnexpectedValueException(\n sprintf(\n \"Found '%s' property but no audio was found before.\",\n $name\n )\n );\n }\n break;\n case Property::DESCRIPTION:\n if ($this->description === null) {\n $this->description = $value;\n }\n break;\n case Property::DETERMINER:\n if ($this->determiner === null) {\n $this->determiner = $value;\n }\n break;\n case Property::IMAGE:\n case Property::IMAGE_URL:\n $this->images[] = new Image($value);\n break;\n case Property::IMAGE_HEIGHT:\n case Property::IMAGE_SECURE_URL:\n case Property::IMAGE_TYPE:\n case Property::IMAGE_WIDTH:\n case Property::IMAGE_USER_GENERATED:\n if (count($this->images) > 0) {\n $this->handleImageAttribute($this->images[count($this->images) - 1], $name, $value);\n } elseif ($debug) {\n throw new UnexpectedValueException(\n sprintf(\n \"Found '%s' property but no image was found before.\",\n $name\n )\n );\n }\n break;\n case Property::LOCALE:\n if ($this->locale === null) {\n $this->locale = $value;\n }\n break;\n case Property::LOCALE_ALTERNATE:\n $this->localeAlternate[] = $value;\n break;\n case Property::RICH_ATTACHMENT:\n $this->richAttachment = $this->convertToBoolean($value);\n break;\n case Property::SEE_ALSO:\n $this->seeAlso[] = $value;\n break;\n case Property::SITE_NAME:\n if ($this->siteName === null) {\n $this->siteName = $value;\n }\n break;\n case Property::TITLE:\n if ($this->title === null) {\n $this->title = $value;\n }\n break;\n case Property::UPDATED_TIME:\n if ($this->updatedTime === null) {\n $this->updatedTime = $this->convertToDateTime($value);\n }\n break;\n case Property::URL:\n if ($this->url === null) {\n $this->url = $value;\n }\n break;\n case Property::VIDEO:\n case Property::VIDEO_URL:\n $this->videos[] = new Video($value);\n break;\n case Property::VIDEO_HEIGHT:\n case Property::VIDEO_SECURE_URL:\n case Property::VIDEO_TYPE:\n case Property::VIDEO_WIDTH:\n if (count($this->videos) > 0) {\n $this->handleVideoAttribute($this->videos[count($this->videos) - 1], $name, $value);\n } elseif ($debug) {\n throw new UnexpectedValueException(sprintf(\n \"Found '%s' property but no video was found before.\",\n $name\n ));\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function addDataForTemplate($event, $options = [])\n {\n $events = $this->getAllEvents();\n $objettype = strtolower($this->obj->getType());\n\n // Get data from ITIL objects\n if ($event != 'alertnotclosed') {\n $this->data = $this->getDataForObject($this->obj, $options);\n } else {\n if (\n isset($options['entities_id'])\n && isset($options['items'])\n ) {\n $entity = new Entity();\n if ($entity->getFromDB($options['entities_id'])) {\n $this->data[\"##$objettype.entity##\"] = $entity->getField('completename');\n $this->data[\"##$objettype.shortentity##\"] = $entity->getField('name');\n }\n if ($item = getItemForItemtype($objettype)) {\n $objettypes = Toolbox::strtolower(getPlural($objettype));\n $items = [];\n foreach ($options['items'] as $object) {\n $item->getFromDB($object['id']);\n $tmp = $this->getDataForObject($item, $options, true);\n $this->data[$objettypes][] = $tmp;\n }\n }\n }\n }\n\n if (\n ($event == 'validation')\n && isset($options['validation_status'])\n ) {\n $this->data[\"##$objettype.action##\"]\n //TRANS: %s id of the approval's state\n = sprintf(\n __('%1$s - %2$s'),\n CommonITILValidation::getTypeName(1),\n TicketValidation::getStatus($options['validation_status'])\n );\n } else {\n $this->data[\"##$objettype.action##\"] = $events[$event];\n }\n\n $this->getTags();\n\n foreach ($this->tag_descriptions[parent::TAG_LANGUAGE] as $tag => $values) {\n if (!isset($this->data[$tag])) {\n $this->data[$tag] = $values['label'];\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function action_login()\n {\n $this->view = $this->view('user/login');\n\n if (!is_null($this->pixie->auth->user()) && $this->pixie->auth->has_role('admin')) {\n $this->redirect('/admin/');\n }\n\n $returnUrl = $this->request->get('return_url', '');\n $this->view->returnUrl = $returnUrl;\n\n if ($this->request->method == 'POST') {\n\n $login = $this->model->checkLoginUser($this->request->post('username'));\n $password = $this->request->post('password');\n\n $user = $this->model->loadUserModel($login);\n\n if($user && $user->active){\n //Attempt to login the user using his\n //username and password\n $logged = $this->pixie->auth\n ->provider('password')\n ->login($login, $password);\n\n if ($logged){\n\n if ($this->pixie->auth->has_role('admin')) {\n $user->last_login = date('Y-m-d H:i:s');\n $user->save();\n\n //On successful login redirect the user to\n //our protected page, or return_url, if specified\n if ($this->view->returnUrl) {\n $this->redirect($this->view->returnUrl);\n return;\n }\n\n $this->redirect($returnUrl ?: '/admin/');\n return;\n\n } else {\n $this->pixie->session->flash('error', 'You don\\'t have enough permissions to access admin area.');\n $this->redirect('/admin/user/login' . ($returnUrl ? '?return_url=' . rawurlencode($returnUrl) : ''));\n return;\n }\n }\n }\n $this->view->username = $this->request->post('username');\n $this->view->errorMessage = \"Username or password are incorrect.\";\n\n } else {\n $this->view->errorMessage = $this->pixie->session->flash('error');\n }\n\n $this->view->subview = 'user/login';\n }", "smellKey": "S3776", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n $this->setIdentifier($data['identifier']);\n }\n if (isset($data['role'])) {\n $this->setRole($data['role']);\n }\n if (isset($data['allergenicIndicator'])) {\n $this->setAllergenicIndicator($data['allergenicIndicator']);\n }\n if (isset($data['manufacturer'])) {\n if (is_array($data['manufacturer'])) {\n foreach ($data['manufacturer'] as $d) {\n $this->addManufacturer($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"manufacturer\" must be array of objects or null, ' . gettype($data['manufacturer']) . ' seen.');\n }\n }\n if (isset($data['specifiedSubstance'])) {\n if (is_array($data['specifiedSubstance'])) {\n foreach ($data['specifiedSubstance'] as $d) {\n $this->addSpecifiedSubstance($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"specifiedSubstance\" must be array of objects or null, ' . gettype($data['specifiedSubstance']) . ' seen.');\n }\n }\n if (isset($data['substance'])) {\n $this->setSubstance($data['substance']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function showMassiveActionsSubForm(MassiveAction $ma)\n {\n $input = $ma->getInput();\n\n switch ($ma->getAction()) {\n case 'changegroup':\n if (\n isset($input['is_tech'])\n && isset($input['check_items_id'])\n && isset($input['check_itemtype'])\n ) {\n if ($group = getItemForItemtype($input['check_itemtype'])) {\n if ($group->getFromDB($input['check_items_id'])) {\n $condition = [];\n if ($input['is_tech']) {\n $condition['is_assign'] = 1;\n } else {\n $condition['is_itemgroup'] = 1;\n }\n self::dropdown([\n 'entity' => $group->fields[\"entities_id\"],\n 'used' => [$group->fields[\"id\"]],\n 'condition' => $condition\n ]);\n echo \"<br><br><input type='submit' name='massiveaction' class='btn btn-primary' value='\" .\n _sx('button', 'Move') . \"'>\";\n return true;\n }\n }\n }\n return true;\n }\n return parent::showMassiveActionsSubForm($ma);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function sendmailSend($header, $body)\n {\n // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.\n if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {\n if ($this->Mailer == 'qmail') {\n $sendmailFmt = '%s -f%s';\n } else {\n $sendmailFmt = '%s -oi -f%s -t';\n }\n } else {\n if ($this->Mailer == 'qmail') {\n $sendmailFmt = '%s';\n } else {\n $sendmailFmt = '%s -oi -t';\n }\n }\n\n // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing.\n $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);\n\n if ($this->SingleTo) {\n foreach ($this->SingleToArray as $toAddr) {\n if (!@$mail = popen($sendmail, 'w')) {\n throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);\n }\n fputs($mail, 'To: ' . $toAddr . \"\\n\");\n fputs($mail, $header);\n fputs($mail, $body);\n $result = pclose($mail);\n $this->doCallback(\n ($result == 0),\n array($toAddr),\n $this->cc,\n $this->bcc,\n $this->Subject,\n $body,\n $this->From\n );\n if ($result != 0) {\n throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);\n }\n }\n } else {\n if (!@$mail = popen($sendmail, 'w')) {\n throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);\n }\n fputs($mail, $header);\n fputs($mail, $body);\n $result = pclose($mail);\n $this->doCallback(\n ($result == 0),\n $this->to,\n $this->cc,\n $this->bcc,\n $this->Subject,\n $body,\n $this->From\n );\n if ($result != 0) {\n throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);\n }\n }\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function prepare(): array\n {\n $mapping = [\n 'publisher' => 'manufacturers_id',\n 'comments' => 'comment',\n 'install_date' => 'date_install',\n 'system_category' => '_system_category'\n ];\n\n //Dictionary for software\n $rulecollection = new RuleDictionnarySoftwareCollection();\n\n //Count the number of software dictionary rules\n $count_rules = \\countElementsInTable(\n \"glpi_rules\",\n [\n 'sub_type' => 'RuleDictionnarySoftware',\n 'is_active' => 1,\n ]\n );\n\n $with_manufacturer = [];\n $without_manufacturer = [];\n\n foreach ($this->data as $k => &$val) {\n foreach ($mapping as $origin => $dest) {\n if (property_exists($val, $origin)) {\n $val->$dest = $val->$origin;\n }\n }\n\n if (property_exists($val, 'manufacturers_id')) {\n $val->manufacturers_id = $this->cleanName($val->manufacturers_id);\n }\n if (\n !property_exists($val, 'name')\n || $val->name == ''\n ) {\n if (property_exists($val, 'guid') && $val->guid != '') {\n $val->name = $val->guid;\n }\n }\n\n //If the software name exists and is defined\n if (property_exists($val, 'name') && $val->name != '') {\n $val->name = $this->cleanName($val->name);\n\n $res_rule = [];\n\n //Only play rules engine if there's at least one rule\n //for software dictionary\n if ($count_rules > 0) {\n $rule_input = [\n \"name\" => $val->name,\n \"manufacturer\" => $val->manufacturers_id ?? 0,\n \"old_version\" => $val->version ?? null,\n \"entities_id\" => $this->entities_id,\n \"_system_category\" => $val->_system_category ?? null\n ];\n $res_rule = $rulecollection->processAllRules($rule_input);\n }\n\n if (isset($res_rule['_ignore_import']) && $res_rule['_ignore_import'] == 1) {\n //ignored by rules\n unset($this->data[$k]);\n continue;\n }\n\n //If the name has been modified by the rules engine\n if (isset($res_rule[\"name\"])) {\n $val->name = $res_rule[\"name\"];\n }\n //If the version has been modified by the rules engine\n if (isset($res_rule[\"version\"])) {\n $val->version = $res_rule[\"version\"];\n }\n\n //If the software category has been modified or set by the rules engine\n if (isset($res_rule[\"softwarecategories_id\"])) {\n $sckey = md5('softwarecategories_id' . $res_rule[\"softwarecategories_id\"]);\n $this->known_links[$sckey] = $res_rule[\"softwarecategories_id\"];\n $sc = new \\SoftwareCategory();\n $sc->getFromDB($res_rule[\"softwarecategories_id\"]);\n $val->softwarecategories_id = $sc->fields['name'];\n } else if (\n property_exists($val, '_system_category')\n && $val->_system_category != ''\n && $val->_system_category != '0'\n ) {\n $val->softwarecategories_id = $val->_system_category;\n $sckey = md5('softwarecategories_id' . $val->_system_category);\n if (!isset($this->known_links[$sckey])) {\n $new_value = Dropdown::importExternal(\n 'SoftwareCategory',\n $val->_system_category,\n $this->entities_id\n );\n $this->known_links[$sckey] = $new_value;\n }\n } else {\n $val->softwarecategories_id = 0;\n }\n\n //If the manufacturer has been modified or set by the rules engine\n if (isset($res_rule[\"manufacturer\"])) {\n $mkey = md5('manufacturers_id' . mb_strtolower(transliterator_transliterate(\"Any-Latin; Latin-ASCII; [^a-zA-Z0-9\\.\\ -_] Remove;\", $res_rule['manufacturer'])));\n $mid = Dropdown::import(\n 'Manufacturer',\n ['name' => $res_rule['manufacturer']]\n );\n $this->known_links[$mkey] = $mid;\n $val->manufacturers_id = $res_rule['manufacturer'];\n } else if (\n property_exists($val, 'manufacturers_id')\n && $val->manufacturers_id != ''\n && $val->manufacturers_id != '0'\n ) {\n $mkey = md5('manufacturers_id' . mb_strtolower(transliterator_transliterate(\"Any-Latin; Latin-ASCII; [^a-zA-Z0-9\\.\\ -_] Remove;\", $val->manufacturers_id)));\n if (!isset($this->known_links[$mkey])) {\n $new_value = Dropdown::importExternal(\n 'Manufacturer',\n $val->manufacturers_id,\n $this->entities_id\n );\n $this->known_links[$mkey] = $new_value;\n }\n } else {\n $val->manufacturers_id = 0;\n }\n\n //version is undefined, set it to blank\n if (!property_exists($val, 'version')) {\n $val->version = '';\n }\n //arch is undefined, set it to blank\n if (!property_exists($val, 'arch')) {\n $val->arch = '';\n }\n\n //not a template, not deleted, ...\n $val->is_template_item = 0;\n $val->is_deleted_item = 0;\n $val->operatingsystems_id = 0;\n $val->entities_id = 0;\n $val->is_recursive = 0;\n\n //String with the manufacturer\n $comp_key = $this->getSimpleCompareKey($val);\n\n if ($val->manufacturers_id == 0) {\n //soft w/o manufacturer. Keep it to see later if one exists with manufacturer\n $without_manufacturer[$comp_key] = $k;\n } else {\n $with_manufacturer[$comp_key] = true;\n }\n }\n\n //ensure all columns are present\n if (!property_exists($val, 'comment')) {\n $val->comment = null;\n }\n }\n\n //NOTE: A same software may have a manufacturer or not. Keep the one with manufacturer.\n foreach ($without_manufacturer as $comp_key => $data_index) {\n if (isset($with_manufacturer[$comp_key])) {\n //same software do exists with a manufacturer, remove current duplicate\n unset($this->data[$data_index]);\n }\n }\n\n return $this->data;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getTimelimitStatus($aid, $ver) {\n\t\tglobal $DBH;\n $now = time();\n\t\tif ($ver > 1) {\n\t\t\t$query = 'SELECT iar.timelimitexp,iar.status,ia.timelimit FROM imas_assessment_records AS iar ';\n\t\t\t$query .= 'JOIN imas_assessments AS ia ON iar.assessmentid=ia.id ';\n\t\t\t$query .= 'WHERE iar.userid=? AND ia.id=?';\n\t\t\t$stm = $DBH->prepare($query);\n\t\t\t$stm->execute(array($this->uid, $aid));\n\t\t\tif ($stm->rowCount()==0) {\n\t\t\t\treturn 'noissue';\n\t\t\t} else {\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_ASSOC);\n\t\t\t\tif (($row['status']&32)==32) {\n\t\t\t\t\treturn 'outofattempts';\n\t\t\t\t} else if ($row['timelimit']==0 || ($row['status']&3)==0) {\n\t\t\t\t\treturn 'noissue';\n\t\t\t\t} else if ($row['timelimitexp'] > 0 && $now > $row['timelimitexp']) {\n\t\t\t\t\treturn 'expired';\n\t\t\t\t} else {\n\t\t\t\t\treturn 'started';\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$query = 'SELECT ias.starttime,ia.timelimit FROM imas_assessment_sessions AS ias ';\n\t\t\t$query .= 'JOIN imas_assessments AS ia ON ias.assessmentid=ia.id ';\n\t\t\t$query .= 'WHERE ias.userid=? AND ia.id=?';\n\t\t\t$stm = $DBH->prepare($query);\n\t\t\t$stm->execute(array($this->uid, $aid));\n\t\t\tif ($stm->rowCount()==0) {\n\t\t\t\treturn 'noissue';\n\t\t\t} else {\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_ASSOC);\n\t\t\t\tif ($row['timelimit']==0) {\n\t\t\t\t\treturn 'noissue';\n\t\t\t\t} else if ($now - $row['starttime'] > abs($row['timelimit'])) {\n\t\t\t\t\treturn 'expired';\n\t\t\t\t} else {\n\t\t\t\t\treturn 'started';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function IndexOldStuff() {\n $class = get_class();\n $auto_create = function($db_error) use ($class) {\n\n if ($db_error != 1146)\n // Perform the standard error handling\n return true;\n\n // Create the search table automatically\n $class::__init();\n\n };\n\n // THREADS ----------------------------------\n $sql = \"SELECT A1.`id`, A1.`title`, A1.`body`, A1.`format` FROM `\".THREAD_ENTRY_TABLE.\"` A1\n LEFT JOIN `\".TABLE_PREFIX.\"_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='H')\n WHERE A2.`object_id` IS NULL AND (A1.poster <> 'SYSTEM')\n AND (IFNULL(LENGTH(A1.`title`), 0) + IFNULL(LENGTH(A1.`body`), 0) > 0)\n ORDER BY A1.`id` DESC LIMIT 500\";\n if (!($res = db_query_unbuffered($sql, $auto_create)))\n return false;\n\n while ($row = db_fetch_row($res)) {\n $body = ThreadEntryBody::fromFormattedText($row[2], $row[3]);\n $body = $body->getSearchable();\n $title = Format::searchable($row[1]);\n if (!$body && !$title)\n continue;\n $record = array('H', $row[0], $title, $body);\n if (!$this->__index($record))\n return;\n }\n\n // TICKETS ----------------------------------\n\n $sql = \"SELECT A1.`ticket_id` FROM `\".TICKET_TABLE.\"` A1\n LEFT JOIN `\".TABLE_PREFIX.\"_search` A2 ON (A1.`ticket_id` = A2.`object_id` AND A2.`object_type`='T')\n WHERE A2.`object_id` IS NULL\n ORDER BY A1.`ticket_id` DESC LIMIT 300\";\n if (!($res = db_query_unbuffered($sql, $auto_create)))\n return false;\n\n while ($row = db_fetch_row($res)) {\n if (!($ticket = Ticket::lookup($row[0])))\n continue;\n $cdata = $ticket->loadDynamicData();\n $content = array();\n foreach ($cdata as $k=>$a)\n if ($k != 'subject' && ($v = $a->getSearchable()))\n $content[] = $v;\n $record = array('T', $ticket->getId(),\n Format::searchable($ticket->getNumber().' '.$ticket->getSubject()),\n implode(\"\\n\", $content));\n if (!$this->__index($record))\n return;\n }\n\n // USERS ------------------------------------\n\n $sql = \"SELECT A1.`id` FROM `\".USER_TABLE.\"` A1\n LEFT JOIN `\".TABLE_PREFIX.\"_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='U')\n WHERE A2.`object_id` IS NULL\";\n if (!($res = db_query_unbuffered($sql, $auto_create)))\n return false;\n\n while ($row = db_fetch_row($res)) {\n $user = User::lookup($row[0]);\n $cdata = $user->getDynamicData();\n $content = array();\n foreach ($user->emails as $e)\n $content[] = $e->address;\n foreach ($cdata as $e)\n foreach ($e->getAnswers() as $a)\n if ($c = $a->getSearchable())\n $content[] = $c;\n $record = array('U', $user->getId(),\n Format::searchable($user->getFullName()),\n trim(implode(\"\\n\", $content)));\n if (!$this->__index($record))\n return;\n }\n\n // ORGANIZATIONS ----------------------------\n\n $sql = \"SELECT A1.`id` FROM `\".ORGANIZATION_TABLE.\"` A1\n LEFT JOIN `\".TABLE_PREFIX.\"_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='O')\n WHERE A2.`object_id` IS NULL\";\n if (!($res = db_query_unbuffered($sql, $auto_create)))\n return false;\n\n while ($row = db_fetch_row($res)) {\n $org = Organization::lookup($row[0]);\n $cdata = $org->getDynamicData();\n $content = array();\n foreach ($cdata as $e)\n foreach ($e->getAnswers() as $a)\n if ($c = $a->getSearchable())\n $content[] = $c;\n $record = array('O', $org->getId(),\n Format::searchable($org->getName()),\n trim(implode(\"\\n\", $content)));\n if (!$this->__index($record))\n return null;\n }\n\n // KNOWLEDGEBASE ----------------------------\n\n require_once INCLUDE_DIR . 'class.faq.php';\n $sql = \"SELECT A1.`faq_id` FROM `\".FAQ_TABLE.\"` A1\n LEFT JOIN `\".TABLE_PREFIX.\"_search` A2 ON (A1.`faq_id` = A2.`object_id` AND A2.`object_type`='K')\n WHERE A2.`object_id` IS NULL\";\n if (!($res = db_query_unbuffered($sql, $auto_create)))\n return false;\n\n while ($row = db_fetch_row($res)) {\n if (!($faq = FAQ::lookup($row[0])))\n continue;\n $q = $faq->getQuestion();\n if ($k = $faq->getKeywords())\n $q = $k.' '.$q;\n $record = array('K', $faq->getId(),\n Format::searchable($q),\n $faq->getSearchableAnswer());\n if (!$this->__index($record))\n return;\n }\n\n // FILES ------------------------------------\n\n // Flush non-full batch of records\n $this->__index(null, true);\n\n if (!$this->_reindexed) {\n // Stop rebuilding the index\n $this->getConfig()->set('reindex', 0);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function parseOpenEMRRecord($dataRecord = array(), $encode = false)\n {\n $docReference = new FHIRDocumentReference();\n $fhirMeta = new FHIRMeta();\n $fhirMeta->setVersionId('1');\n if (!empty($dataRecord['date'])) {\n $fhirMeta->setLastUpdated(UtilsService::getLocalDateAsUTC($dataRecord['date']));\n } else {\n $fhirMeta->setLastUpdated(UtilsService::getDateFormattedAsUTC());\n }\n $docReference->setMeta($fhirMeta);\n\n $id = new FHIRId();\n $id->setValue($dataRecord['uuid']);\n $docReference->setId($id);\n\n $identifier = new FHIRIdentifier();\n $identifier->setValue(new FHIRString($dataRecord['uuid']));\n $docReference->addIdentifier($identifier);\n\n if (!empty($dataRecord['date'])) {\n $docReference->setDate(UtilsService::getLocalDateAsUTC($dataRecord['date']));\n } else {\n $docReference->setDate(UtilsService::createDataMissingExtension());\n }\n\n if (!empty($dataRecord['euuid'])) {\n $context = new FHIRDocumentReferenceContext();\n\n // we currently don't track anything dealing with start and end date for the context\n if (!empty($dataRecord['encounter_date'])) {\n $period = new FHIRPeriod();\n $period->setStart(UtilsService::getLocalDateAsUTC($dataRecord['encounter_date']));\n $context->setPeriod($period);\n }\n $context->addEncounter(UtilsService::createRelativeReference('Encounter', $dataRecord['euuid']));\n $docReference->setContext($context);\n }\n\n // populate our clinical narrative notes\n if (!empty($dataRecord['description'])) {\n $content = new FHIRDocumentReferenceContent();\n $attachment = new FHIRAttachment();\n $attachment->setContentType(\"text/plain\");\n $attachment->setData(base64_encode($dataRecord['description']));\n $content->setAttachment($attachment);\n // since it's plain text we have no other interpretation so we just use the mime type sufficient IHE Format code\n $contentCoding = UtilsService::createCoding(\n \"urn:ihe:iti:xds:2017:mimeTypeSufficient\",\n \"mimeType Sufficient\",\n FhirCodeSystemConstants::IHE_FORMATCODE_CODESYSTEM\n );\n $content->setFormat($contentCoding);\n $docReference->addContent($content);\n } else {\n // need to support data missing if its not there.\n $docReference->addContent(UtilsService::createDataMissingExtension());\n }\n\n if (!empty($dataRecord['puuid'])) {\n $docReference->setSubject(UtilsService::createRelativeReference('Patient', $dataRecord['puuid']));\n } else {\n $docReference->setSubject(UtilsService::createDataMissingExtension());\n }\n\n $docReference->addCategory(UtilsService::createCodeableConcept([\n 'clinical-note' => ['code' => 'clinical-note', 'description' => 'Clinical Note', 'system' => FhirCodeSystemConstants::DOCUMENT_REFERENCE_CATEGORY]\n ]));\n\n $fhirOrganizationService = new FhirOrganizationService();\n $orgReference = $fhirOrganizationService->getPrimaryBusinessEntityReference();\n $docReference->setCustodian($orgReference);\n\n if (!empty($dataRecord['user_uuid'])) {\n if (!empty($dataRecord['npi'])) {\n $docReference->addAuthor(UtilsService::createRelativeReference('Practitioner', $dataRecord['user_uuid']));\n } else {\n // if we don't have a practitioner reference then it is the business owner that will be the author on\n // the clinical notes\n $docReference->addAuthor($orgReference);\n }\n }\n\n if (!empty($dataRecord['activity'])) {\n if ($dataRecord['activity'] == ClinicalNotesService::ACTIVITY_ACTIVE) {\n $docReference->setStatus(\"current\");\n } else {\n $docReference->setStatus(\"entered-in-error\");\n }\n } else {\n $docReference->setStatus('current');\n }\n\n if (!empty($dataRecord['code'])) {\n $type = UtilsService::createCodeableConcept($dataRecord['code'], FhirCodeSystemConstants::LOINC, $dataRecord['codetext']);\n $docReference->setType($type);\n } else {\n $docReference->setType(UtilsService::createNullFlavorUnknownCodeableConcept());\n }\n\n return $docReference;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function run(): SetupResult {\n\t\t$version = null;\n\t\t$databasePlatform = $this->connection->getDatabasePlatform();\n\t\tif ($databasePlatform instanceof MySQLPlatform) {\n\t\t\t$result = $this->connection->prepare(\"SHOW VARIABLES LIKE 'version';\");\n\t\t\t$result->execute();\n\t\t\t$row = $result->fetch();\n\t\t\t$version = $row['Value'];\n\t\t\t$versionlc = strtolower($version);\n\n\t\t\tif (str_contains($versionlc, 'mariadb')) {\n\t\t\t\tif (version_compare($versionlc, '10.2', '<')) {\n\t\t\t\t\treturn SetupResult::warning($this->l10n->t('MariaDB version \"%s\" is used. Nextcloud 21 and higher do not support this version and require MariaDB 10.2 or higher.', $version));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (version_compare($versionlc, '8', '<')) {\n\t\t\t\t\treturn SetupResult::warning($this->l10n->t('MySQL version \"%s\" is used. Nextcloud 21 and higher do not support this version and require MySQL 8.0 or MariaDB 10.2 or higher.', $version));\n\t\t\t\t}\n\t\t\t}\n\t\t} elseif ($databasePlatform instanceof PostgreSQLPlatform) {\n\t\t\t$result = $this->connection->prepare('SHOW server_version;');\n\t\t\t$result->execute();\n\t\t\t$row = $result->fetch();\n\t\t\t$version = $row['server_version'];\n\t\t\tif (version_compare(strtolower($version), '9.6', '<')) {\n\t\t\t\treturn SetupResult::warning($this->l10n->t('PostgreSQL version \"%s\" is used. Nextcloud 21 and higher do not support this version and require PostgreSQL 9.6 or higher.', $version));\n\t\t\t}\n\t\t} elseif ($databasePlatform instanceof OraclePlatform) {\n\t\t\t$version = 'Oracle';\n\t\t} elseif ($databasePlatform instanceof SqlitePlatform) {\n\t\t\treturn SetupResult::warning(\n\t\t\t\t$this->l10n->t('SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend. This is particularly recommended when using the desktop client for file synchronisation. To migrate to another database use the command line tool: \"occ db:convert-type\".'),\n\t\t\t\t$this->urlGenerator->linkToDocs('admin-db-conversion')\n\t\t\t);\n\t\t} else {\n\t\t\treturn SetupResult::error($this->l10n->t('Unknown database platform'));\n\t\t}\n\t\treturn SetupResult::success($version);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function renewPasswordAction()\n {\n $pathAppConfigForm = '/meliscore/forms/meliscore_renewpass';\n $melisMelisCoreConfig = $this->getServiceManager()->get('MelisCoreConfig');\n $appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm);\n $translator = $this->getServiceManager()->get('translator');\n\n $rhash = $this->getHash();\n /** @var MelisCoreCreatePasswordService $melisCreatePass */\n $melisCreatePass = $this->getServiceManager()->get('MelisCoreCreatePassword');\n $hashExists = false;\n $textMessage = '';\n $success = 0;\n $login = '';\n $data = array();\n if($melisCreatePass->hashExists($rhash)) {\n $hashExists = true;\n $data = $melisCreatePass->getPasswordRequestData($rhash);\n foreach($data as $val) {\n $login = $val->mcp_login;\n }\n }\n\n $isRequestNotExpired = $melisCreatePass->isRequestExpired($login);\n $isUserExist = $melisCreatePass->isUserExist($login);\n\n $factory = new \\Laminas\\Form\\Factory();\n $forgotForm = $factory->createForm($appConfigForm);\n\n $translator = $this->getServiceManager()->get('translator');\n $this->getServiceManager()->get('ViewHelperManager')->get('HeadTitle')->set($translator->translate('tr_meliscore_reset_password_header') . ' - ');\n\n $view = new ViewModel();\n if($this->getRequest()->isPost())\n {\n\n if($isUserExist && $isRequestNotExpired) {\n $password = $this->getRequest()->getPost('usr_pass');\n $confirmPass = $this->getRequest()->getPost('usr_pass_confirm');\n $passValidator = new \\MelisCore\\Validator\\MelisPasswordValidator();\n\n if (strlen($password) >= 8) {\n // if (strlen($confirmPass) >= 8) {\n //$passValidator = new \\Laminas\\Validator\\Regex(array('pattern' => '/^(?=.*?[0-9])(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^\\w\\s]).{8,}$/'));\n $passValidator = new \\MelisCore\\Validator\\MelisPasswordValidator();\n if ($passValidator->isValid($password)) {\n // password and confirm password matching\n if ($password == $confirmPass) {\n $melisCreatePass->processUpdatePassword($rhash, $password);\n $textMessage = \"tr_meliscore_user_password_change_succes\";\n $success = 1;\n header(\"location:/melis/login\");\n } else {\n $success = 0;\n $textMessage = 'tr_meliscore_tool_user_usr_password_not_match';\n } // password and confirm password matching\n } else {\n $success = 0;\n $textMessage = 'tr_meliscore_tool_user_usr_password_regex_not_match';\n } // password regex validator\n // } else {\n // $success = 0;\n // $textMessage = 'tr_meliscore_tool_user_usr_confirm_password_error_low';\n // }// end confirm password length\n } else {\n $success = 0;\n $textMessage = 'tr_meliscore_tool_user_usr_password_error_low';\n }// end password length\n }\n else {\n $success = 0;\n $textMessage = 'tr_meliscore_tool_user_password_request_invalid';\n }// end confirm if link is valid\n }\n\n $config = $this->getServiceManager()->get('MelisCoreConfig')->getItem('meliscore/datas/login');\n\n $view->setVariable('meliscore_renewpass', $forgotForm);\n $view->setVariable('formFactory', $factory);\n $view->setVariable('formConfig', $appConfigForm);\n $view->setVariable('passwordValidityLifetime', $config['password_validity_lifetime']);\n $view->hashExists = $hashExists;\n $view->message = $translator->translate($textMessage);\n $view->success = $success;\n $view->isRequestNotExpired = $isRequestNotExpired;\n $view->isUserExist = $isUserExist;\n $view->rhash = $rhash;\n $this->layout()->schemes = $this->getSchemes();\n\n return $view;\n }", "smellKey": "S3776", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public function install()\n {\n Hook::exec('actionModuleInstallBefore', ['object' => $this]);\n // Check module name validation\n if (!Validate::isModuleName($this->name)) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Unable to install the module (Module name is not valid).', [], 'Admin.Modules.Notification');\n\n return false;\n }\n\n // Check PS version compliancy\n if (!$this->checkCompliancy()) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('The version of your module is not compliant with your PrestaShop version.', [], 'Admin.Modules.Notification');\n\n return false;\n }\n\n // Check module dependencies\n if (count($this->dependencies) > 0) {\n foreach ($this->dependencies as $dependency) {\n if (!Db::getInstance()->getRow('SELECT `id_module` FROM `' . _DB_PREFIX_ . 'module` WHERE LOWER(`name`) = \\'' . pSQL(Tools::strtolower($dependency)) . '\\'')) {\n $error = Context::getContext()->getTranslator()->trans('Before installing this module, you have to install this/these module(s) first:', [], 'Admin.Modules.Notification') . '<br />';\n foreach ($this->dependencies as $d) {\n $error .= '- ' . $d . '<br />';\n }\n $this->_errors[] = $error;\n\n return false;\n }\n }\n }\n\n // Check if module is installed\n $result = (new ModuleDataProvider(new LegacyLogger(), $this->getTranslator()))->isInstalled($this->name);\n if ($result) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('This module has already been installed.', [], 'Admin.Modules.Notification');\n\n return false;\n }\n\n if (!$this->installControllers()) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Could not install module controllers.', [], 'Admin.Modules.Notification');\n $this->uninstallOverrides();\n\n return false;\n }\n\n // Install module and retrieve the installation id\n $result = Db::getInstance()->insert($this->table, ['name' => $this->name, 'active' => 1, 'version' => $this->version]);\n if (!$result) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Technical error: PrestaShop could not install this module.', [], 'Admin.Modules.Notification');\n $this->uninstallTabs();\n $this->uninstallOverrides();\n\n return false;\n }\n $this->id = Db::getInstance()->Insert_ID();\n\n Cache::clean('Module::isInstalled' . $this->name);\n\n // Enable the module for current shops in context\n $this->enable();\n\n // Permissions management\n foreach (['CREATE', 'READ', 'UPDATE', 'DELETE'] as $action) {\n $slug = 'ROLE_MOD_MODULE_' . strtoupper($this->name) . '_' . $action;\n\n Db::getInstance()->execute(\n 'INSERT INTO `' . _DB_PREFIX_ . 'authorization_role` (`slug`) VALUES (\"' . $slug . '\")'\n );\n\n Db::getInstance()->execute('\n INSERT INTO `' . _DB_PREFIX_ . 'module_access` (`id_profile`, `id_authorization_role`) (\n SELECT id_profile, \"' . Db::getInstance()->Insert_ID() . '\"\n FROM ' . _DB_PREFIX_ . 'access a\n LEFT JOIN `' . _DB_PREFIX_ . 'authorization_role` r\n ON r.id_authorization_role = a.id_authorization_role\n WHERE r.slug = \"ROLE_MOD_TAB_ADMINMODULESSF_' . $action . '\"\n )');\n }\n\n // Adding Restrictions for client groups\n Group::addRestrictionsForModule($this->id, Shop::getShops(true, null, true));\n Hook::exec('actionModuleInstallAfter', ['object' => $this]);\n\n if (Module::$update_translations_after_install) {\n $this->updateModuleTranslations();\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {\n\t\tif ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {\n\t\t\t// convert SVG to raster image using GD or ImageMagick libraries\n\t\t\treturn $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);\n\t\t}\n\t\t$this->svgdir = dirname($file);\n\t\t$svgdata = file_get_contents($file);\n\t\tif ($svgdata === false) {\n\t\t\t$this->Error('SVG file not found: '.$file);\n\t\t}\n\t\tif ($x === '') {\n\t\t\t$x = $this->x;\n\t\t}\n\t\tif ($y === '') {\n\t\t\t$y = $this->y;\n\t\t}\n\t\t// check page for no-write regions and adapt page margins if necessary\n\t\t$this->checkPageRegions($x, $y);\n\t\t$k = $this->k;\n\t\t$ox = 0;\n\t\t$oy = 0;\n\t\t$ow = $w;\n\t\t$oh = $h;\n\t\t$aspect_ratio_align = 'xMidYMid';\n\t\t$aspect_ratio_ms = 'meet';\n\t\t$regs = array();\n\t\t// get original image width and height\n\t\tpreg_match('/<svg([^\\>]*)>/si', $svgdata, $regs);\n\t\tif (isset($regs[1]) AND !empty($regs[1])) {\n\t\t\t$tmp = array();\n\t\t\tif (preg_match('/[\\s]+x[\\s]*=[\\s]*\"([^\"]*)\"/si', $regs[1], $tmp)) {\n\t\t\t\t$ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);\n\t\t\t}\n\t\t\t$tmp = array();\n\t\t\tif (preg_match('/[\\s]+y[\\s]*=[\\s]*\"([^\"]*)\"/si', $regs[1], $tmp)) {\n\t\t\t\t$oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);\n\t\t\t}\n\t\t\t$tmp = array();\n\t\t\tif (preg_match('/[\\s]+width[\\s]*=[\\s]*\"([^\"]*)\"/si', $regs[1], $tmp)) {\n\t\t\t\t$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);\n\t\t\t}\n\t\t\t$tmp = array();\n\t\t\tif (preg_match('/[\\s]+height[\\s]*=[\\s]*\"([^\"]*)\"/si', $regs[1], $tmp)) {\n\t\t\t\t$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);\n\t\t\t}\n\t\t\t$tmp = array();\n\t\t\t$view_box = array();\n\t\t\tif (preg_match('/[\\s]+viewBox[\\s]*=[\\s]*\"[\\s]*([0-9\\.\\-]+)[\\s]+([0-9\\.\\-]+)[\\s]+([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]*\"/si', $regs[1], $tmp)) {\n\t\t\t\tif (count($tmp) == 5) {\n\t\t\t\t\tarray_shift($tmp);\n\t\t\t\t\tforeach ($tmp as $key => $val) {\n\t\t\t\t\t\t$view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);\n\t\t\t\t\t}\n\t\t\t\t\t$ox = $view_box[0];\n\t\t\t\t\t$oy = $view_box[1];\n\t\t\t\t}\n\t\t\t\t// get aspect ratio\n\t\t\t\t$tmp = array();\n\t\t\t\tif (preg_match('/[\\s]+preserveAspectRatio[\\s]*=[\\s]*\"([^\"]*)\"/si', $regs[1], $tmp)) {\n\t\t\t\t\t$aspect_ratio = preg_split('/[\\s]+/si', $tmp[1]);\n\t\t\t\t\tswitch (count($aspect_ratio)) {\n\t\t\t\t\t\tcase 3: {\n\t\t\t\t\t\t\t$aspect_ratio_align = $aspect_ratio[1];\n\t\t\t\t\t\t\t$aspect_ratio_ms = $aspect_ratio[2];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 2: {\n\t\t\t\t\t\t\t$aspect_ratio_align = $aspect_ratio[0];\n\t\t\t\t\t\t\t$aspect_ratio_ms = $aspect_ratio[1];\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 1: {\n\t\t\t\t\t\t\t$aspect_ratio_align = $aspect_ratio[0];\n\t\t\t\t\t\t\t$aspect_ratio_ms = 'meet';\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// calculate image width and height on document\n\t\tif (($w <= 0) AND ($h <= 0)) {\n\t\t\t// convert image size to document unit\n\t\t\t$w = $ow;\n\t\t\t$h = $oh;\n\t\t} elseif ($w <= 0) {\n\t\t\t$w = $h * $ow / $oh;\n\t\t} elseif ($h <= 0) {\n\t\t\t$h = $w * $oh / $ow;\n\t\t}\n\t\t// fit the image on available space\n\t\t$this->fitBlock($w, $h, $x, $y, $fitonpage);\n\t\tif ($this->rasterize_vector_images) {\n\t\t\t// convert SVG to raster image using GD or ImageMagick libraries\n\t\t\treturn $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);\n\t\t}\n\t\t// set alignment\n\t\t$this->img_rb_y = $y + $h;\n\t\t// set alignment\n\t\tif ($this->rtl) {\n\t\t\tif ($palign == 'L') {\n\t\t\t\t$ximg = $this->lMargin;\n\t\t\t} elseif ($palign == 'C') {\n\t\t\t\t$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($palign == 'R') {\n\t\t\t\t$ximg = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$ximg = $x - $w;\n\t\t\t}\n\t\t\t$this->img_rb_x = $ximg;\n\t\t} else {\n\t\t\tif ($palign == 'L') {\n\t\t\t\t$ximg = $this->lMargin;\n\t\t\t} elseif ($palign == 'C') {\n\t\t\t\t$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;\n\t\t\t} elseif ($palign == 'R') {\n\t\t\t\t$ximg = $this->w - $this->rMargin - $w;\n\t\t\t} else {\n\t\t\t\t$ximg = $x;\n\t\t\t}\n\t\t\t$this->img_rb_x = $ximg + $w;\n\t\t}\n\t\t// store current graphic vars\n\t\t$gvars = $this->getGraphicVars();\n\t\t// store SVG position and scale factors\n\t\t$svgoffset_x = ($ximg - $ox) * $this->k;\n\t\t$svgoffset_y = -($y - $oy) * $this->k;\n\t\tif (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {\n\t\t\t$ow = $view_box[2];\n\t\t\t$oh = $view_box[3];\n\t\t}\n\t\t$svgscale_x = $w / $ow;\n\t\t$svgscale_y = $h / $oh;\n\t\t// scaling and alignment\n\t\tif ($aspect_ratio_align != 'none') {\n\t\t\t// store current scaling values\n\t\t\t$svgscale_old_x = $svgscale_x;\n\t\t\t$svgscale_old_y = $svgscale_y;\n\t\t\t// force uniform scaling\n\t\t\tif ($aspect_ratio_ms == 'slice') {\n\t\t\t\t// the entire viewport is covered by the viewBox\n\t\t\t\tif ($svgscale_x > $svgscale_y) {\n\t\t\t\t\t$svgscale_y = $svgscale_x;\n\t\t\t\t} elseif ($svgscale_x < $svgscale_y) {\n\t\t\t\t\t$svgscale_x = $svgscale_y;\n\t\t\t\t}\n\t\t\t} else { // meet\n\t\t\t\t// the entire viewBox is visible within the viewport\n\t\t\t\tif ($svgscale_x < $svgscale_y) {\n\t\t\t\t\t$svgscale_y = $svgscale_x;\n\t\t\t\t} elseif ($svgscale_x > $svgscale_y) {\n\t\t\t\t\t$svgscale_x = $svgscale_y;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// correct X alignment\n\t\t\tswitch (substr($aspect_ratio_align, 1, 3)) {\n\t\t\t\tcase 'Min': {\n\t\t\t\t\t// do nothing\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'Max': {\n\t\t\t\t\t$svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\tcase 'Mid': {\n\t\t\t\t\t$svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// correct Y alignment\n\t\t\tswitch (substr($aspect_ratio_align, 5)) {\n\t\t\t\tcase 'Min': {\n\t\t\t\t\t// do nothing\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'Max': {\n\t\t\t\t\t$svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\tcase 'Mid': {\n\t\t\t\t\t$svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// store current page break mode\n\t\t$page_break_mode = $this->AutoPageBreak;\n\t\t$page_break_margin = $this->getBreakMargin();\n\t\t$cell_padding = $this->cell_padding;\n\t\t$this->SetCellPadding(0);\n\t\t$this->SetAutoPageBreak(false);\n\t\t// save the current graphic state\n\t\t$this->_out('q'.$this->epsmarker);\n\t\t// set initial clipping mask\n\t\t$this->Rect($x, $y, $w, $h, 'CNZ', array(), array());\n\t\t// scale and translate\n\t\t$e = $ox * $this->k * (1 - $svgscale_x);\n\t\t$f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);\n\t\t$this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $svgscale_x, 0, 0, $svgscale_y, $e + $svgoffset_x, $f + $svgoffset_y));\n\t\t// creates a new XML parser to be used by the other XML functions\n\t\t$this->parser = xml_parser_create('UTF-8');\n\t\t// the following function allows to use parser inside object\n\t\txml_set_object($this->parser, $this);\n\t\t// disable case-folding for this XML parser\n\t\txml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);\n\t\t// sets the element handler functions for the XML parser\n\t\txml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');\n\t\t// sets the character data handler function for the XML parser\n\t\txml_set_character_data_handler($this->parser, 'segSVGContentHandler');\n\t\t// start parsing an XML document\n\t\tif(!xml_parse($this->parser, $svgdata)) {\n\t\t\t$error_message = sprintf(\"SVG Error: %s at line %d\", xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser));\n\t\t\t$this->Error($error_message);\n\t\t}\n\t\t// free this XML parser\n\t\txml_parser_free($this->parser);\n\t\t// restore previous graphic state\n\t\t$this->_out($this->epsmarker.'Q');\n\t\t// restore graphic vars\n\t\t$this->setGraphicVars($gvars);\n\t\t$this->lasth = $gvars['lasth'];\n\t\tif (!empty($border)) {\n\t\t\t$bx = $this->x;\n\t\t\t$by = $this->y;\n\t\t\t$this->x = $ximg;\n\t\t\tif ($this->rtl) {\n\t\t\t\t$this->x += $w;\n\t\t\t}\n\t\t\t$this->y = $y;\n\t\t\t$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);\n\t\t\t$this->x = $bx;\n\t\t\t$this->y = $by;\n\t\t}\n\t\tif ($link) {\n\t\t\t$this->Link($ximg, $y, $w, $h, $link, 0);\n\t\t}\n\t\t// set pointer to align the next text/objects\n\t\tswitch($align) {\n\t\t\tcase 'T':{\n\t\t\t\t$this->y = $y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'M':{\n\t\t\t\t$this->y = $y + round($h/2);\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'B':{\n\t\t\t\t$this->y = $this->img_rb_y;\n\t\t\t\t$this->x = $this->img_rb_x;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'N':{\n\t\t\t\t$this->SetY($this->img_rb_y);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:{\n\t\t\t\t// restore pointer to starting position\n\t\t\t\t$this->x = $gvars['x'];\n\t\t\t\t$this->y = $gvars['y'];\n\t\t\t\t$this->page = $gvars['page'];\n\t\t\t\t$this->current_column = $gvars['current_column'];\n\t\t\t\t$this->tMargin = $gvars['tMargin'];\n\t\t\t\t$this->bMargin = $gvars['bMargin'];\n\t\t\t\t$this->w = $gvars['w'];\n\t\t\t\t$this->h = $gvars['h'];\n\t\t\t\t$this->wPt = $gvars['wPt'];\n\t\t\t\t$this->hPt = $gvars['hPt'];\n\t\t\t\t$this->fwPt = $gvars['fwPt'];\n\t\t\t\t$this->fhPt = $gvars['fhPt'];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$this->endlinex = $this->img_rb_x;\n\t\t// restore page break\n\t\t$this->SetAutoPageBreak($page_break_mode, $page_break_margin);\n\t\t$this->cell_padding = $cell_padding;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function FaireSauvegarde() {\n\t\n\t$host = 'mysql51-52.perso';\n\t$user = 'associatryagain';\n\t$pass = 'assORE1994';\n\t$name = 'associatryagain';\n\t$tables = '*';\n\t\n\t$link = mysql_connect($host,$user,$pass);\n\tmysql_select_db($name,$link);\n\t\n\t//get all of the tables\n\tif($tables == '*')\n\t{\n\t\t$tables = array();\n\t\t$result = mysql_query('SHOW TABLES');\n\t\twhile($row = mysql_fetch_row($result))\n\t\t{\n\t\t\t$tables[] = $row[0];\n\t\t}\n\t}\n\telse\n\t{\n\t\t$tables = is_array($tables) ? $tables : explode(',',$tables);\n\t}\n\t\n\t//cycle through\n\tforeach($tables as $table)\n\t{\n\t\t$result = mysql_query('SELECT * FROM '.$table);\n\t\t$num_fields = mysql_num_fields($result);\n\t\t\n\t\t$return.= 'DROP TABLE '.$table.';';\n\t\t$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));\n\t\t$return.= \"\\n\\n\".$row2[1].\";\\n\\n\";\n\t\t\n\t\tfor ($i = 0; $i < $num_fields; $i++) \n\t\t{\n\t\t\twhile($row = mysql_fetch_row($result))\n\t\t\t{\n\t\t\t\t$return.= 'INSERT INTO '.$table.' VALUES(';\n\t\t\t\tfor($j=0; $j < $num_fields; $j++) \n\t\t\t\t{\n\t\t\t\t\t$row[$j] = addslashes($row[$j]);\n\t\t\t\t\t$row[$j] = str_replace(\"\\n\",\"\\\\n\",$row[$j]);\n\t\t\t\t\tif (isset($row[$j])) { $return.= '\"'.$row[$j].'\"' ; } else { $return.= '\"\"'; }\n\t\t\t\t\tif ($j < ($num_fields-1)) { $return.= ','; }\n\t\t\t\t}\n\t\t\t\t$return.= \");\\n\";\n\t\t\t}\n\t\t}\n\t\t$return.=\"\\n\\n\\n\";\n\t}\n\t\n\t//save file\n\t$handle = fopen('sauvegardes/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');\n\tfwrite($handle,$return);\n\tfclose($handle);\n}", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function showDateTimeField($name, $options = [])\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $p = [\n 'value' => '',\n 'maybeempty' => true,\n 'canedit' => true,\n 'mindate' => '',\n 'maxdate' => '',\n 'mintime' => '',\n 'maxtime' => '',\n 'timestep' => -1,\n 'showyear' => true,\n 'display' => true,\n 'rand' => mt_rand(),\n 'required' => false,\n 'on_change' => '',\n ];\n\n foreach ($options as $key => $val) {\n if (isset($p[$key])) {\n $p[$key] = $val;\n }\n }\n\n if ($p['timestep'] < 0) {\n $p['timestep'] = $CFG_GLPI['time_step'];\n }\n\n $date_value = '';\n $hour_value = '';\n if (!empty($p['value'])) {\n list($date_value, $hour_value) = explode(' ', $p['value']);\n }\n\n if (!empty($p['mintime'])) {\n // Check time in interval\n if (!empty($hour_value) && ($hour_value < $p['mintime'])) {\n $hour_value = $p['mintime'];\n }\n }\n\n if (!empty($p['maxtime'])) {\n // Check time in interval\n if (!empty($hour_value) && ($hour_value > $p['maxtime'])) {\n $hour_value = $p['maxtime'];\n }\n }\n\n // reconstruct value to be valid\n if (!empty($date_value)) {\n $p['value'] = $date_value . ' ' . $hour_value;\n }\n\n $required = $p['required'] == true\n ? \" required='required'\"\n : \"\";\n $disabled = !$p['canedit']\n ? \" disabled='disabled'\"\n : \"\";\n $clear = $p['maybeempty'] && $p['canedit']\n ? \"<i class='input-group-text fas fa-times-circle fa-lg pointer' data-clear role='button' title='\" . __s('Clear') . \"'></i>\"\n : \"\";\n\n $output = <<<HTML\n <div class=\"input-group flex-grow-1 flatpickr\" id=\"showdate{$p['rand']}\">\n <input type=\"text\" name=\"{$name}\" value=\"{$p['value']}\"\n {$required} {$disabled} data-input class=\"form-control rounded-start ps-2\">\n <i class=\"input-group-text far fa-calendar-alt fa-lg pointer\" data-toggle=\"\" role=\"button\"></i>\n $clear\n </div>\nHTML;\n\n $date_format = Toolbox::getDateFormat('js') . \" H:i:S\";\n\n $min_attr = !empty($p['min'])\n ? \"minDate: '{$p['min']}',\"\n : \"\";\n $max_attr = !empty($p['max'])\n ? \"maxDate: '{$p['max']}',\"\n : \"\";\n\n $locale = Locale::parseLocale($_SESSION['glpilanguage']);\n $js = <<<JS\n $(function() {\n $(\"#showdate{$p['rand']}\").flatpickr({\n altInput: true, // Show the user a readable date (as per altFormat), but return something totally different to the server.\n altFormat: \"{$date_format}\",\n dateFormat: 'Y-m-d H:i:S',\n wrap: true, // permits to have controls in addition to input (like clear or open date buttons)\n enableTime: true,\n enableSeconds: true,\n weekNumbers: true,\n time_24hr: true,\n locale: getFlatPickerLocale(\"{$locale['language']}\", \"{$locale['region']}\"),\n minuteIncrement: \"{$p['timestep']}\",\n {$min_attr}\n {$max_attr}\n onChange: function(selectedDates, dateStr, instance) {\n {$p['on_change']}\n },\n allowInput: true,\n onClose(dates, currentdatestring, picker){\n picker.setDate(picker.altInput.value, true, picker.config.altFormat)\n },\n plugins: [\n CustomFlatpickrButtons()\n ]\n });\n });\nJS;\n $output .= Html::scriptBlock($js);\n\n if ($p['display']) {\n echo $output;\n return $p['rand'];\n }\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function showTeam(Project $project)\n {\n $ID = $project->fields['id'];\n $canedit = $project->can($ID, UPDATE);\n\n echo \"<div class='center'>\";\n\n $rand = mt_rand();\n $nb = $project->getTeamCount();\n\n if ($canedit) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='projectteam_form$rand' id='projectteam_form$rand' \";\n echo \" method='post' action='\" . Toolbox::getItemTypeFormURL('ProjectTeam') . \"'>\";\n echo \"<input type='hidden' name='projects_id' value='$ID'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_1'><th colspan='2'>\" . __s('Add a team member') . \"</tr>\";\n echo \"<tr class='tab_bg_2'><td>\";\n\n $params = ['itemtypes' => ProjectTeam::$available_types,\n 'entity_restrict' => ($project->fields['is_recursive']\n ? getSonsOf(\n 'glpi_entities',\n $project->fields['entities_id']\n )\n : $project->fields['entities_id']),\n ];\n Dropdown::showSelectItemFromItemtypes($params);\n\n echo \"</td>\";\n echo \"<td width='20%'>\";\n echo \"<input type='submit' name='add' value=\\\"\" . _sx('button', 'Add') . \"\\\"\n class='btn btn-primary'>\";\n echo \"</td>\";\n echo \"</tr>\";\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }\n echo \"<div class='spaced'>\";\n if ($canedit && $nb) {\n Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);\n $massiveactionparams = ['num_displayed' => min($_SESSION['glpilist_limit'], $nb),\n 'container' => 'mass' . __CLASS__ . $rand\n ];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';\n if ($canedit && $nb) {\n $header_begin .= \"<th width='10'>\";\n $header_top .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);\n $header_bottom .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);\n $header_end .= \"</th>\";\n }\n $header_end .= \"<th>\" . _sn('Type', 'Types', 1) . \"</th>\";\n $header_end .= \"<th>\" . _sn('Member', 'Members', Session::getPluralNumber()) . \"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin . $header_top . $header_end;\n\n foreach (ProjectTeam::$available_types as $type) {\n if (isset($project->team[$type]) && count($project->team[$type])) {\n if ($item = getItemForItemtype($type)) {\n foreach ($project->team[$type] as $data) {\n $item->getFromDB($data['items_id']);\n echo \"<tr class='tab_bg_2'>\";\n if ($canedit) {\n echo \"<td>\";\n Html::showMassiveActionCheckBox('ProjectTeam', $data[\"id\"]);\n echo \"</td>\";\n }\n echo \"<td>\" . htmlspecialchars($item->getTypeName(1)) . \"</td>\";\n echo \"<td>\" . $item->getLink() . \"</td>\";\n echo \"</tr>\";\n }\n }\n }\n }\n if ($nb) {\n echo $header_begin . $header_bottom . $header_end;\n }\n\n echo \"</table>\";\n if ($canedit && $nb) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n\n echo \"</div>\";\n // Add items\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getShipmentReportDetails($parameters)\n {\n /* Array of database columns which should be read and sent back to DataTables. Use a space where\n * you want to insert a non-database field (for example a counter or static image)\n */\n\n $aColumns = array('year(shipment_date)', 'DATE_FORMAT(shipment_date,\"%d-%b-%Y\")', 'scheme_type', 'shipment_code');\n $orderColumns = array('shipment_date', 'shipment_date', 'scheme_type', 'shipment_code');\n\n /* Indexed column (used for fast and accurate table cardinality) */\n $sIndexColumn = $this->_primary;\n\n $sTable = $this->_name;\n /*\n * Paging\n */\n $sLimit = \"\";\n if (isset($parameters['iDisplayStart']) && $parameters['iDisplayLength'] != '-1') {\n $sOffset = $parameters['iDisplayStart'];\n $sLimit = $parameters['iDisplayLength'];\n }\n\n /*\n * Ordering\n */\n\n $sOrder = \"\";\n if (isset($parameters['iSortCol_0'])) {\n for ($i = 0; $i < intval($parameters['iSortingCols']); $i++) {\n if ($parameters['bSortable_' . intval($parameters['iSortCol_' . $i])] == \"true\") {\n $sOrder .= $orderColumns[intval($parameters['iSortCol_' . $i])] . \" \" . ($parameters['sSortDir_' . $i]) . \",\";\n }\n }\n $sOrder = substr_replace($sOrder, \"\", -1);\n }\n\n /*\n * Filtering\n * NOTE this does not match the built-in DataTables filtering which does it\n * word by word on any field. It's possible to do here, but concerned about efficiency\n * on very large tables, and MySQL's regex functionality is very limited\n */\n\n $sWhere = \"\";\n if (isset($parameters['sSearch']) && $parameters['sSearch'] != \"\") {\n $searchArray = explode(\" \", $parameters['sSearch']);\n $sWhereSub = \"\";\n foreach ($searchArray as $search) {\n if ($sWhereSub == \"\") {\n $sWhereSub .= \"(\";\n } else {\n $sWhereSub .= \" AND (\";\n }\n $colSize = count($aColumns);\n\n for ($i = 0; $i < $colSize; $i++) {\n if ($i < $colSize - 1) {\n $sWhereSub .= $aColumns[$i] . \" LIKE '%\" . ($search) . \"%' OR \";\n } else {\n $sWhereSub .= $aColumns[$i] . \" LIKE '%\" . ($search) . \"%' \";\n }\n }\n $sWhereSub .= \")\";\n }\n $sWhere .= $sWhereSub;\n }\n\n /* Individual column filtering */\n for ($i = 0; $i < count($aColumns); $i++) {\n if (isset($parameters['bSearchable_' . $i]) && $parameters['bSearchable_' . $i] == \"true\" && $parameters['sSearch_' . $i] != '') {\n if ($sWhere == \"\") {\n $sWhere .= $aColumns[$i] . \" LIKE '%\" . ($parameters['sSearch_' . $i]) . \"%' \";\n } else {\n $sWhere .= \" AND \" . $aColumns[$i] . \" LIKE '%\" . ($parameters['sSearch_' . $i]) . \"%' \";\n }\n }\n }\n\n /*\n * SQL queries\n * Get data to display\n */\n $sQuery = $this->getAdapter()->select()->from(array('s' => 'shipment'), array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS s.scheme_type'), 'SHIP_YEAR' => 'year(s.shipment_date)', 's.shipment_date', 's.shipment_code', 's.shipment_id', 's.status'))\n ->join(array('spm' => 'shipment_participant_map'), 'spm.shipment_id=s.shipment_id', array('spm.map_id', \"spm.participant_id\"))\n ->join(array('p' => 'participant'), 'p.participant_id=spm.participant_id', array('p.first_name', 'p.last_name'))\n // ->join(array('pmm' => 'participant_manager_map'), 'pmm.participant_id=p.participant_id')\n ->join(array('dm' => 'data_manager'), 'dm.dm_id=pmm.dm_id', array('dm.institute'))\n // ->where(\"pmm.dm_id=?\", $this->_session->dm_id)\n ->where(\"s.status='shipped' OR s.status='evaluated' OR s.status='finalized'\")\n ->where(\"year(s.shipment_date) + 5 > year(CURDATE())\")\n ->group('s.shipment_id');\n $authNameSpace = new Zend_Session_Namespace('datamanagers');\n if (!empty($authNameSpace->dm_id)) {\n $sQuery = $sQuery\n ->joinLeft(array('pmm' => 'participant_manager_map'), 'pmm.participant_id=p.participant_id', array())\n ->where(\"pmm.dm_id = ?\", $authNameSpace->dm_id);\n }\n if (isset($sWhere) && $sWhere != \"\") {\n $sQuery = $sQuery->where($sWhere);\n }\n\n if (!empty($sOrder)) {\n $sQuery = $sQuery->order($sOrder);\n }\n\n if (isset($sLimit) && isset($sOffset)) {\n $sQuery = $sQuery->limit($sLimit, $sOffset);\n }\n //error_log($sQuery);\n $rResult = $this->getAdapter()->fetchAll($sQuery);\n\n $iTotal = $iFilteredTotal = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()');\n\n /*\n * Output\n */\n $output = array(\n \"sEcho\" => intval($parameters['sEcho']),\n \"iTotalRecords\" => $iTotal,\n \"iTotalDisplayRecords\" => $iFilteredTotal,\n \"aaData\" => array()\n );\n\n $general = new Pt_Commons_General();\n foreach ($rResult as $aRow) {\n $row = [];\n $report = \"\";\n $fileName = $aRow['shipment_code'] . \"-\" . $aRow['institute'] . $aRow['dm_id'] . \".pdf\";\n $fileName = preg_replace('/[^A-Za-z0-9.]/', '-', $fileName);\n $fileName = str_replace(\" \", \"-\", $fileName);\n\n $row[] = $aRow['SHIP_YEAR'];\n $row[] = Pt_Commons_General::humanReadableDateFormat($aRow['shipment_date']);\n $row[] = strtoupper($aRow['scheme_name']);\n $row[] = $aRow['shipment_code'];\n\n $filePath = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'reports' . DIRECTORY_SEPARATOR . $aRow['shipment_code'] . DIRECTORY_SEPARATOR . $fileName;\n if (file_exists($filePath) && $aRow['status'] == 'finalized') {\n $downloadFilePath = \"/uploads\" . DIRECTORY_SEPARATOR . 'reports' . DIRECTORY_SEPARATOR . $aRow['shipment_code'] . DIRECTORY_SEPARATOR . $fileName;\n $report = '<a href=\"' . $downloadFilePath . '\" style=\"text-decoration : underline;\" target=\"_BLANK\">Report</a>';\n }\n $row[] = $report;\n\n $output['aaData'][] = $row;\n }\n\n echo json_encode($output);\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "protected function _putfonts() {\n\t\t$nf = $this->n;\n\t\tforeach ($this->diffs as $diff) {\n\t\t\t//Encodings\n\t\t\t$this->_newobj();\n\t\t\t$this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'.\"\\n\".'endobj');\n\t\t}\n\t\t$mqr = $this->get_mqr();\n\t\t$this->set_mqr(false);\n\t\tforeach ($this->FontFiles as $file => $info) {\n\t\t\t// search and get font file to embedd\n\t\t\t$fontdir = $info['fontdir'];\n\t\t\t$file = strtolower($file);\n\t\t\t$fontfile = '';\n\t\t\t// search files on various directories\n\t\t\tif (($fontdir !== false) AND file_exists($fontdir.$file)) {\n\t\t\t\t$fontfile = $fontdir.$file;\n\t\t\t} elseif (file_exists($this->_getfontpath().$file)) {\n\t\t\t\t$fontfile = $this->_getfontpath().$file;\n\t\t\t} elseif (file_exists($file)) {\n\t\t\t\t$fontfile = $file;\n\t\t\t}\n\t\t\tif (!$this->empty_string($fontfile)) {\n\t\t\t\t$font = file_get_contents($fontfile);\n\t\t\t\t$compressed = (substr($file, -2) == '.z');\n\t\t\t\tif ((!$compressed) AND (isset($info['length2']))) {\n\t\t\t\t\t$header = (ord($font{0}) == 128);\n\t\t\t\t\tif ($header) {\n\t\t\t\t\t\t//Strip first binary header\n\t\t\t\t\t\t$font = substr($font, 6);\n\t\t\t\t\t}\n\t\t\t\t\tif ($header AND (ord($font{$info['length1']}) == 128)) {\n\t\t\t\t\t\t//Strip second binary header\n\t\t\t\t\t\t$font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));\n\t\t\t\t\t}\n\t\t\t\t} elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {\n\t\t\t\t\tif ($compressed) {\n\t\t\t\t\t\t// uncompress font\n\t\t\t\t\t\t$font = gzuncompress($font);\n\t\t\t\t\t}\n\t\t\t\t\t// merge subset characters\n\t\t\t\t\t$subsetchars = array(); // used chars\n\t\t\t\t\tforeach ($info['fontkeys'] as $fontkey) {\n\t\t\t\t\t\t$fontinfo = $this->getFontBuffer($fontkey);\n\t\t\t\t\t\t$subsetchars += $fontinfo['subsetchars'];\n\t\t\t\t\t}\n\t\t\t\t\t$font = $this->_getTrueTypeFontSubset($font, $subsetchars);\n\t\t\t\t\tif ($compressed) {\n\t\t\t\t\t\t// recompress font\n\t\t\t\t\t\t$font = gzcompress($font);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$this->_newobj();\n\t\t\t\t$this->FontFiles[$file]['n'] = $this->n;\n\t\t\t\t$stream = $this->_getrawstream($font);\n\t\t\t\t$out = '<< /Length '.strlen($stream);\n\t\t\t\tif ($compressed) {\n\t\t\t\t\t$out .= ' /Filter /FlateDecode';\n\t\t\t\t}\n\t\t\t\t$out .= ' /Length1 '.$info['length1'];\n\t\t\t\tif (isset($info['length2'])) {\n\t\t\t\t\t$out .= ' /Length2 '.$info['length2'].' /Length3 0';\n\t\t\t\t}\n\t\t\t\t$out .= ' >>';\n\t\t\t\t$out .= ' stream'.\"\\n\".$stream.\"\\n\".'endstream';\n\t\t\t\t$out .= \"\\n\".'endobj';\n\t\t\t\t$this->_out($out);\n\t\t\t}\n\t\t}\n\t\t$this->set_mqr($mqr);\n\t\tforeach ($this->fontkeys as $k) {\n\t\t\t//Font objects\n\t\t\t$font = $this->getFontBuffer($k);\n\t\t\t$type = $font['type'];\n\t\t\t$name = $font['name'];\n\t\t\tif ($type == 'core') {\n\t\t\t\t// standard core font\n\t\t\t\t$out = $this->_getobj($this->font_obj_ids[$k]).\"\\n\";\n\t\t\t\t$out .= '<</Type /Font';\n\t\t\t\t$out .= ' /Subtype /Type1';\n\t\t\t\t$out .= ' /BaseFont /'.$name;\n\t\t\t\t$out .= ' /Name /F'.$font['i'];\n\t\t\t\tif ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {\n\t\t\t\t\t$out .= ' /Encoding /WinAnsiEncoding';\n\t\t\t\t}\n\t\t\t\tif ($k == 'helvetica') {\n\t\t\t\t\t// add default font for annotations\n\t\t\t\t\t$this->annotation_fonts[$k] = $font['i'];\n\t\t\t\t}\n\t\t\t\t$out .= ' >>';\n\t\t\t\t$out .= \"\\n\".'endobj';\n\t\t\t\t$this->_out($out);\n\t\t\t} elseif (($type == 'Type1') OR ($type == 'TrueType')) {\n\t\t\t\t// additional Type1 or TrueType font\n\t\t\t\t$out = $this->_getobj($this->font_obj_ids[$k]).\"\\n\";\n\t\t\t\t$out .= '<</Type /Font';\n\t\t\t\t$out .= ' /Subtype /'.$type;\n\t\t\t\t$out .= ' /BaseFont /'.$name;\n\t\t\t\t$out .= ' /Name /F'.$font['i'];\n\t\t\t\t$out .= ' /FirstChar 32 /LastChar 255';\n\t\t\t\t$out .= ' /Widths '.($this->n + 1).' 0 R';\n\t\t\t\t$out .= ' /FontDescriptor '.($this->n + 2).' 0 R';\n\t\t\t\tif ($font['enc']) {\n\t\t\t\t\tif (isset($font['diff'])) {\n\t\t\t\t\t\t$out .= ' /Encoding '.($nf + $font['diff']).' 0 R';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$out .= ' /Encoding /WinAnsiEncoding';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$out .= ' >>';\n\t\t\t\t$out .= \"\\n\".'endobj';\n\t\t\t\t$this->_out($out);\n\t\t\t\t// Widths\n\t\t\t\t$this->_newobj();\n\t\t\t\t$cw = &$font['cw'];\n\t\t\t\t$s = '[';\n\t\t\t\tfor ($i = 32; $i < 256; ++$i) {\n\t\t\t\t\t$s .= $cw[$i].' ';\n\t\t\t\t}\n\t\t\t\t$s .= ']';\n\t\t\t\t$s .= \"\\n\".'endobj';\n\t\t\t\t$this->_out($s);\n\t\t\t\t//Descriptor\n\t\t\t\t$this->_newobj();\n\t\t\t\t$s = '<</Type /FontDescriptor /FontName /'.$name;\n\t\t\t\tforeach ($font['desc'] as $fdk => $fdv) {\n\t\t\t\t\tif(is_float($fdv)) {\n\t\t\t\t\t\t$fdv = sprintf('%.3F', $fdv);\n\t\t\t\t\t}\n\t\t\t\t\t$s .= ' /'.$fdk.' '.$fdv.'';\n\t\t\t\t}\n\t\t\t\tif (!$this->empty_string($font['file'])) {\n\t\t\t\t\t$s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';\n\t\t\t\t}\n\t\t\t\t$s .= '>>';\n\t\t\t\t$s .= \"\\n\".'endobj';\n\t\t\t\t$this->_out($s);\n\t\t\t} else {\n\t\t\t\t// additional types\n\t\t\t\t$mtd = '_put'.strtolower($type);\n\t\t\t\tif (!method_exists($this, $mtd)) {\n\t\t\t\t\t$this->Error('Unsupported font type: '.$type);\n\t\t\t\t}\n\t\t\t\t$this->$mtd($font);\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function __getTermTree($system, $termDomain, $matching = 'exact') { // termDomain can be empty, 'reltype' or 'enum' or any future term use domain defined in the trm_Domain enum\n $mysqli = $system->getMysqli();\n\n if($termDomain=='enum' && HEURIST_UNITED_TERMS){\n $whereClause = '1=1';\n }else{\n $whereClause = \"a.trm_Domain \" . ($matching == 'prefix' ? \" like '\" . $termDomain . \"%' \" : ($matching == 'postfix' ? \" like '%\" . $termDomain . \"' \" : \"='\" . $termDomain . \"'\"));\n }\n $query = \"select a.trm_ID as pID, b.trm_ID as cID\n from defTerms a\n left join defTerms b on a.trm_ID = b.trm_ParentTermID\n where $whereClause\n order by a.trm_Label, b.trm_Label\";\n\n $res = $mysqli->query($query);\n $terms = array();\n // create array of parent => child arrays\n while ($row = $res->fetch_assoc()) {\n if (!@$terms[$row[\"pID\"]]) {\n $terms[$row[\"pID\"]] = array();\n }\n if ($row['cID']) {//insert child under parent\n $terms[$row[\"pID\"]][$row['cID']] = array();\n }\n }//we have all the branches, now lets build a tree\n $res->close();\n\n foreach ($terms as $parentID => $childIDs) {\n foreach ($childIDs as $childID => $n) {\n //check that we have a child branch\n if ($childID != null && array_key_exists($childID, $terms)) {\n if (!isEmptyArray($terms[$childID])) {//yes then attach it and it's children's branches\n $terms = __attachChild($system, $parentID, $childID, $terms, null);\n } else {//no then it's a leaf in a branch, remove this redundant node.\n unset($terms[$childID]);\n }\n }\n }\n }\n\n return $terms;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function getResult(): ScorePartResult\n {\n global $mathfuncs;\n\n $scorePartResult = new ScorePartResult();\n\n $options = $this->scoreQuestionParams->getVarsForScorePart();\n $qn = $this->scoreQuestionParams->getQuestionNumber();\n $givenans = $this->scoreQuestionParams->getGivenAnswer();\n $multi = $this->scoreQuestionParams->getIsMultiPartQuestion();\n $partnum = $this->scoreQuestionParams->getQuestionPartNumber();\n\n $defaultreltol = .0015;\n\n $optionkeys = ['answer', 'reltolerance', 'abstolerance', 'answerformat',\n 'variables', 'domain', 'ansprompt', 'formatfeedbackon'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n $optionkeys = ['partialcredit'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum, 2);\n }\n $requiretimes = getOptionVal($options, 'requiretimes', $multi, $partnum, 1);\n\n if ($reltolerance === '' && $abstolerance === '') { $reltolerance = $defaultreltol;}\n \n $ansformats = array_map('trim',explode(',',$answerformat));\n\n if ($multi) { $qn = ($qn+1)*1000+$partnum; }\n\n $givenans = normalizemathunicode(trim($givenans, \" \\n\\r\\t\\v\\x00,\"));\n\n $givenans = preg_replace_callback(\n '/(arcsinh|arccosh|arctanh|arcsin|arccos|arctan|arcsec|arccsc|arccot|root|sqrt|sign|sinh|cosh|tanh|sech|csch|coth|abs|sin|cos|tan|sec|csc|cot|exp|log|ln)[\\(\\[]/i',\n function($m) { return strtolower($m[0]); },\n $givenans\n );\n $answer = normalizemathunicode($answer);\n \n if (in_array('nosoln',$ansformats) || in_array('nosolninf',$ansformats)) {\n list($givenans, $answer) = scorenosolninf($qn, $givenans, $answer, $ansprompt);\n }\n\n $scorePartResult->setLastAnswerAsGiven($givenans);\n\n $correct = true;\n\n if (empty($variables)) { $variables = \"x\";}\n list($variables, $tps, $flist) = numfuncGenerateTestpoints($variables, $domain);\n\n $givenans = numfuncPrepForEval($givenans, $variables);\n $answer = numfuncPrepForEval($answer, $variables);\n\n $vlist = implode(\",\",$variables);\n\n //handle nosolninf case\n if ($givenans==='oo' || $givenans==='DNE') {\n if (strcmp($answer,$givenans) === 0) {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n } else if ($answer==='DNE' || $answer==='oo') {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n if (!in_array('inequality',$ansformats) &&\n (strpos($answer,'<')!==false || strpos($answer,'>')!==false || strpos($answer,'!=')!==false)\n ) {\n echo 'Your $answer contains an inequality sign, but you do not have $answerformat=\"inequality\" set. This question probably will not work right.';\n } else if (!in_array('equation',$ansformats) &&\n !in_array('inequality',$ansformats) &&\n strpos($answer,'=')!==false\n ) {\n echo 'Your $answer contains an equal sign, but you do not have $answerformat=\"equation\" set. This question probably will not work right.';\n }\n\n $isComplex = in_array('generalcomplex', $ansformats);\n $isListAnswer = in_array('list',$ansformats);\n if (in_array('allowplusminus', $ansformats)) {\n if (!$isListAnswer) {\n $ansformats[] = 'list';\n $isListAnswer = true;\n }\n $answer = rewritePlusMinus($answer);\n $givenans = rewritePlusMinus($givenans);\n }\n\n if ($isListAnswer) {\n $givenanslist = explode(',', $givenans);\n } else {\n $givenanslist = [$givenans];\n }\n\n $givenanslistvals = array();\n $givenanslistineq = array();\n $givenanslistnormalized = array();\n $givenansused = array();\n foreach ($givenanslist as $givenans) {\n //build values for student answer\n $givenansvals = array();\n if (in_array('inequality',$ansformats)) {\n if (in_array('equation',$ansformats)) {\n preg_match('/(.*)(<=|>=|<|>|!=|=)(.*)/', $givenans, $matches);\n } else {\n preg_match('/(.*)(<=|>=|<|>|!=)(.*)/', $givenans, $matches);\n }\n if (!empty($matches)) {\n $toevalGivenans = $matches[3] . '-(' . $matches[1] . ')';\n $givenInequality = $matches[2];\n } else {\n continue;\n }\n } else if (in_array('equation',$ansformats)) {\n if (substr_count($givenans, '=')!=1) {\n continue;\n }\n $toevalGivenans = preg_replace('/(.*)=(.*)/','$1-($2)',$givenans);\n } else if (preg_match('/(=|<|>)/', $givenans)) {\n continue;\n } else {\n $toevalGivenans = $givenans;\n }\n\n $givenansfunc = parseMathQuiet($toevalGivenans, $vlist, [], $flist, true, $isComplex);\n if ($givenansfunc === false) { //parse error\n continue;\n }\n for ($i = 0; $i < 20; $i++) {\n $varvals = array();\n for($j=0; $j < count($variables); $j++) {\n $varvals[$variables[$j]] = $tps[$i][$j];\n }\n $givenansvals[] = $givenansfunc->evaluateQuiet($varvals);\n }\n $givenanslistvals[] = $givenansvals;\n if (isset($givenInequality)) {\n $givenanslistineq[] = $givenInequality;\n }\n if (in_array('sameform',$ansformats)) {\n $givenanslistnormalized[] = $givenansfunc->normalizeTreeString();\n }\n }\n\n if ($isListAnswer) {\n $answerlist = explode(',', $answer);\n } else {\n $answerlist = [$answer];\n }\n $correctscores = array();\n\n foreach ($answerlist as $alidx => $answer) {\n\n $ansarr = array_map('trim',explode(' or ',$answer));\n $partialpts = array_fill(0, count($ansarr), 1);\n $origanscnt = count($ansarr);\n if (!empty($partialcredit) && !$isListAnswer) { // partial credit only works for non-list answers\n if (!is_array($partialcredit)) {$partialcredit = explode(',',$partialcredit);}\n for ($i=0;$i<count($partialcredit);$i+=2) {\n $partialcredit[$i] = numfuncPrepForEval($partialcredit[$i], $variables);\n if (!in_array($partialcredit[$i], $ansarr) || $partialcredit[$i+1]<1) {\n $ansarr[] = $partialcredit[$i];\n $partialpts[] = $partialcredit[$i+1];\n }\n }\n }\n\n $rightanswrongformat = -1;\n\n foreach ($ansarr as $ansidx=>$answer) {\n if (is_array($requiretimes)) {\n if ($isListAnswer) {\n if (isset($requiretimes[$alidx])) {\n $thisreqtimes = $requiretimes[$alidx];\n } else {\n $thisreqtimes = '';\n }\n } else if ($ansidx<$origanscnt) {\n $thisreqtimes = $requiretimes[0] ?? '';\n } else {\n $thisreqtimes = $requiretimes[$ansidx-$origanscnt+1] ?? '';\n }\n } else {\n $thisreqtimes = $requiretimes;\n }\n $answer = preg_replace('/[^\\w\\*\\/\\+\\=\\-\\(\\)\\[\\]\\{\\}\\,\\.\\^\\$\\!\\s\\'<>]+/','',$answer);\n\n if (in_array('inequality',$ansformats)) {\n if (in_array('equation',$ansformats)) {\n preg_match('/(.*)(<=|>=|<|>|!=|=)(.*)/', $answer, $matches);\n } else {\n preg_match('/(.*)(<=|>=|<|>|!=)(.*)/', $answer, $matches);\n }\n $answer = $matches[3] . '-(' . $matches[1] . ')';\n $answerInequality = $matches[2];\n } else if (in_array('equation',$ansformats)) {\n $answer = preg_replace('/(.*)=(.*)/','$1-($2)',$answer);\n } \n if ($answer == '') {\n continue;\n }\n $origanswer = $answer;\n $answerfunc = parseMathQuiet(makepretty($answer), $vlist, [], $flist, false, $isComplex);\n if ($answerfunc === false) { // parse error on $answer - can't do much\n continue;\n }\n\n $realanstmp = array();\n for ($i = 0; $i < 20; $i++) {\n $varvals = array();\n for($j=0; $j < count($variables); $j++) {\n $varvals[$variables[$j]] = $tps[$i][$j];\n }\n $realans = $answerfunc->evaluateQuiet($varvals);\n $realanstmp[] = $realans;\n }\n foreach ($givenanslistvals as $gaidx => $givenansvals) {\n if (isset($givenansused[$gaidx])) {\n continue; // already used this givenans\n }\n\n $givenansnormalized = $givenanslistnormalized[$gaidx] ?? '';\n $correct = true;\n $cntnan = 0;\n $cntzero = 0;\n $cntbothzero = 0;\n $cntvals = 0;\n $stunan = 0;\n $ysqrtot = 0;\n $reldifftot = 0;\n $ratios = array();\n $diffs = array();\n $realanss = array();\n $rollingstu = [];\n $rollingstui = 0;\n $rollingreal = [];\n $rollingreali = 0;\n $rollingtotcnt = 0;\n\n foreach ($realanstmp as $i=>$realans) {\n //echo \"$answer, real: $realans, my: {$givenansvals[$i]},rel: \". (abs(10^16*$givenansvals[$i]-10^16*$realans)) .\"<br/>\";\n if (isNaN($realans)) {\n $cntnan++; continue;\n } //avoid NaN problems\n if (in_array('toconst',$ansformats) && in_array('scalarmult',$ansformats)) {\n // use triplets of values\n // want (g2 - g1) / (g3 -g2) = (r2 - r1) / (r3 - r2)\n if (isNaN($givenansvals[$i])) {\n $stunan++;\n continue;\n }\n \n if ($isComplex) {\n if (abs($givenansvals[$i][0])<.0000001 && abs($givenansvals[$i][1])<.00000001) {\n if (abs($realans[0])<.0000001 && abs($realans[1])<.00000001) {\n $cntbothzero++;\n } else {\n $cntzero++;\n }\n }\n } else {\n if (abs($givenansvals[$i])<.0000001) {\n if (abs($realans)<.0000001) {\n $cntbothzero++;\n } else {\n $cntzero++;\n }\n }\n }\n\n $rollingtotcnt++;\n // last 3 valid values\n $rollingstu[$rollingstui] = $givenansvals[$i];\n $rollingreal[$rollingreali] = $realans;\n $rollingstui = ($rollingstui+1)%3;\n $rollingreali = ($rollingreali+1)%3;\n\n if (count($rollingstu)==3) {\n if ($isComplex) {\n // want (g2 - g1) / (g3 -g2) == (r2 - r1) / (r3 - r2)\n $v1 = cplx_mult(cplx_subt($rollingstu[1],$rollingstu[0]), cplx_subt($rollingreal[2],$rollingreal[1]));\n $v2 = cplx_mult(cplx_subt($rollingreal[1],$rollingreal[0]), cplx_subt($rollingstu[2],$rollingstu[1]));\n for ($ci=0;$ci<2;$ci++) {\n // TODO: these tolerances may not make sense in this context\n if ($abstolerance !== '') {\n if (abs($v2[$ci] - $v1[$ci]) > $abstolerance+1E-12) { $correct = false; break 2;}\n } else {\n if ((abs($v2[$ci] - $v1[$ci])/(max(abs($v1[$ci]),abs($v2[$ci]))+.0001) > $reltolerance+1E-12)) {$correct = false; break 2;}\n }\n }\n } else {\n // don't want division, so do multiplications\n $v1 = ($rollingstu[1] - $rollingstu[0]) * ($rollingreal[2] - $rollingreal[1]);\n $v2 = ($rollingreal[1] - $rollingreal[0]) * ($rollingstu[2] - $rollingstu[1]);\n // TODO: these tolerances may not make sense in this context\n if ($abstolerance !== '') {\n if (abs($v2 - $v1) > $abstolerance+1E-12) { $correct = false; break;}\n } else {\n if ((abs($v2 - $v1)/(max(abs($v1),abs($v2))+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n }\n }\n } else if (in_array('equation',$ansformats) || in_array('inequality',$ansformats) || in_array('scalarmult',$ansformats)) { //if equation, store ratios\n if (isNaN($givenansvals[$i])) {\n $stunan++;\n } else if ($isComplex) {\n if (abs($realans[0])<.0000001 && abs($realans[1])<.00000001) {\n if (abs($givenansvals[$i][0])<.0000001 && abs($givenansvals[$i][1])<.00000001) {\n $cntbothzero++;\n }\n } else {\n $r = cplx_div($givenansvals[$i], $realans);\n // this is hacky, but to simplify thing, we'll use the magnitude of the\n // complex scaling factor, rather than the value itself.\n $ratios[] = sqrt($r[0]*$r[0] + $r[1]*$r[1]);\n if (abs($givenansvals[$i][0])<.0000001 && abs($givenansvals[$i][1])<.00000001) {\n $cntzero++;\n }\n }\n } else if (abs($realans)>.00000001 && is_numeric($givenansvals[$i])) {\n $ratios[] = $givenansvals[$i]/$realans;\n if (abs($givenansvals[$i])<=.00000001 && $realans!=0) {\n $cntzero++;\n }\n } else if (abs($realans)<=.00000001 && is_numeric($givenansvals[$i]) && abs($givenansvals[$i])<=.00000001) {\n $cntbothzero++;\n }\n } else if ($isComplex && in_array('toconst',$ansformats)) {\n if (isNaN($givenansvals[$i])) {\n $stunan++;\n continue;\n }\n $rollingstu[$rollingstui] = $givenansvals[$i];\n $rollingreal[$rollingreali] = $realans;\n $rollingstui = ($rollingstui+1)%2;\n $rollingreali = ($rollingreali+1)%2;\n // want g2-g1 == r2-r1. \n // This approach is simpler for complex than the meandiff approach\n if (count($rollingstu)==2) {\n $v1 = [$rollingstu[1][0]-$rollingstu[0][0], $rollingstu[1][1]-$rollingstu[0][1]];\n $v2 = [$rollingreal[1][0]-$rollingreal[0][0], $rollingreal[1][1]-$rollingreal[0][1]];\n for ($ci=0;$ci<2;$ci++) {\n // TODO: these tolerances may not make sense in this context\n if ($abstolerance !== '') {\n if (abs($v2[$ci] - $v1[$ci]) > $abstolerance+1E-12) { $correct = false; break 2;}\n } else {\n if ((abs($v2[$ci] - $v1[$ci])/(max(abs($v1[$ci]),abs($v2[$ci]))+.0001) > $reltolerance+1E-12)) {$correct = false; break 2;}\n }\n }\n }\n } else if (in_array('toconst',$ansformats)) {\n if (isNaN($givenansvals[$i])) {\n $stunan++;\n } else {\n $diffs[] = $givenansvals[$i] - $realans;\n /*\n $realanss[] = $realans;\n $ysqr = $realans*$realans;\n $ysqrtot += 1/($ysqr+.0001);\n $reldifftot += ($givenansvals[$i] - $realans)/($ysqr+.0001);\n */\n }\n } else if ($isComplex) { // compare complex points\n if (!is_array($givenansvals[$i])) {\n $stunan++;\n } else if ($abstolerance !== '') {\n if (abs($givenansvals[$i][0]-$realans[0]) > $abstolerance+1E-12) { $correct = false; break;}\n if (abs($givenansvals[$i][1]-$realans[1]) > $abstolerance+1E-12) { $correct = false; break;}\n } else {\n if ((abs($givenansvals[$i][0]-$realans[0])/(abs($realans[0])+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n if ((abs($givenansvals[$i][1]-$realans[1])/(abs($realans[1])+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n } else { //otherwise, compare points\n if (isNaN($givenansvals[$i])) {\n $stunan++;\n } else if ($abstolerance !== '') {\n if (abs($givenansvals[$i]-$realans) > $abstolerance+1E-12) { $correct = false; break;}\n } else {\n if ((abs($givenansvals[$i]-$realans)/(abs($realans)+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n }\n }\n\n if ($cntnan==20 && isset($GLOBALS['teacherid'])) {\n echo _('Debug info: function evaled to Not-a-number at all test points. Check $domain');\n }\n if ($stunan>1) { //if more than 1 student NaN response\n $correct = false; continue;\n }\n \n if (in_array('scalarmult',$ansformats) && in_array('toconst',$ansformats)) {\n // nothing to do; just need to catch combo and check for zeros\n if ($cntbothzero>18) {\n $correct = true;\n } else if ($rollingtotcnt==$cntzero) {\n $correct = false; continue;\n }\n } else if (in_array('equation',$ansformats) || in_array('inequality',$ansformats) || in_array('scalarmult',$ansformats)) {\n if ($cntbothzero>18) {\n $correct = true;\n } else if (count($ratios)>1) {\n if (count($ratios)==$cntzero) {\n $correct = false; continue;\n } else {\n $meanratio = array_sum($ratios)/count($ratios);\n if (in_array('inequality',$ansformats)) {\n if ($meanratio > 0) {\n if ($answerInequality != $givenanslistineq[$gaidx]) {\n $correct = false; continue;\n }\n } else {\n $flippedIneq = strtr($givenanslistineq[$gaidx], ['<'=>'>', '>'=>'<']);\n if ($answerInequality != $flippedIneq) {\n $correct = false; continue;\n }\n }\n }\n for ($i=0; $i<count($ratios); $i++) {\n if ($abstolerance !== '') {\n if (abs($ratios[$i]-$meanratio) > $abstolerance+1E-12) {$correct = false; break;}\n } else {\n if ((abs($ratios[$i]-$meanratio)/(abs($meanratio)+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n }\n }\n } else {\n $correct = false;\n }\n } else if (!$isComplex && in_array('toconst',$ansformats) && count($diffs)>0) {\n /* old method. Messy, confusing tolerances\n if ($abstolerance !== '') {\n //if abs, use mean diff - will minimize error in abs diffs\n $meandiff = array_sum($diffs)/count($diffs);\n } else {\n //if relative tol, use meandiff to minimize relative error\n $meandiff = $reldifftot/$ysqrtot;\n }\n if (is_nan($meandiff)) {\n $correct=false; continue;\n }\n for ($i=0; $i<count($diffs); $i++) {\n if ($abstolerance !== '') {\n if (abs($diffs[$i]-$meandiff) > $abstolerance+1E-12) {$correct = false; break;}\n } else {\n //if ((abs($diffs[$i]-$meandiff)/(abs($meandiff)+0.0001) > $reltolerance-1E-12)) {$correct = false; break;}\n if ((abs($diffs[$i]-$meandiff)/(abs($realanss[$i])+0.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n }\n */\n $meandiff = array_sum($diffs)/count($diffs);\n // do same comparison as for regular funcs, but subtracting meandiff\n foreach ($realanstmp as $i=>$realans) {\n if (isNaN($realans)) {\n continue;\n }\n if (isNaN($givenansvals[$i])) {\n continue;\n } else if ($abstolerance !== '') {\n if (abs($givenansvals[$i]-$meandiff-$realans) > $abstolerance+1E-12) { $correct = false; break;}\n } else {\n if ((abs($givenansvals[$i]-$meandiff-$realans)/(abs($realans)+.0001) > $reltolerance+1E-12)) {$correct = false; break;}\n }\n }\n }\n \n if ($correct == true) {\n //test for correct format, if specified\n if ($thisreqtimes!='' && checkreqtimes(str_replace(',','',$givenanslist[$gaidx]),$thisreqtimes)==0) {\n $rightanswrongformat = $ansidx;\n continue;\n //$correct = false;\n }\n if (in_array('sameform',$ansformats)) {\n if ($answerfunc->normalizeTreeString() != $givenanslistnormalized[$gaidx]) {\n $rightanswrongformat = $ansidx;\n continue;\n }\n }\n $correctscores[] = $partialpts[$ansidx] ?? 1;\n $givenansused[$gaidx] = 1;\n continue 3; // skip to next answer list entry\n }\n }\n }\n }\n \n if ($isListAnswer) {\n $score = array_sum($correctscores)/count($answerlist);\n if (count($givenanslist) > count($answerlist)) {\n $score -= (count($givenanslist) - count($answerlist))/(count($givenanslist) + count($answerlist));\n }\n $scorePartResult->setRawScore($score);\n return $scorePartResult;\n } else if (count($correctscores) > 0) {\n $scorePartResult->setRawScore($correctscores[0]);\n return $scorePartResult;\n } else if ($rightanswrongformat!=-1 && !empty($formatfeedbackon)) {\n $scorePartResult->setCorrectAnswerWrongFormat(true);\n }\n\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function draw_angle() {\n $input = func_get_args();\n if (empty($input)) {\n echo \"Eek! Must include an angle to draw.\";\n return '';\n }\n $argsArray = [];\n $args = '';\n $size = 300;\n $rot = 0;\n $ang = 0;\n $hasArc = false;\n $lab = \"\";\n $direction = \"\";\n $altLabel = \"\";\n $altTurnsLabel = \"\";\n $altAnother = \"\";\n $altDegSymbol = \"\";\n $hasUserAltText = false;\n foreach ($input as $list) {\n if (!is_array($list)) {\n $list = listtoarray($list);\n }\n $list = array_map('trim', $list);\n $argsArray[]=$list;\n }\n if (is_array($argsArray[0])) {\n if (!array_key_exists(0, $argsArray[0]) || !is_numeric($argsArray[0][0])) {\n echo \"Eek! Must include an angle to draw.\";\n return '';\n }\n } else {\n if (!is_numeric($argsArray[0])) {\n echo \"Eek! Must include an angle to draw.\";\n return '';\n }\n }\n\n foreach ($argsArray as $in) {\n if ($in[0] == \"rotate\") {\n if (isset($in[1])) {\n $rot = ($in[1]>=0) ? $in[1] : 360+$in[1];\n } elseif (!isset($in[1])) {\n $rot = $GLOBALS['RND']->rand(0,360);\n }\n }\n if ($in[0] == \"size\") {\n if (array_key_exists(1,$in)) {\n if (is_numeric($in[1])) {\n $size = $in[1];\n }\n }\n }\n if (in_array(\"axes\",$in)) {\n $args = $args . \"stroke='grey';line([-1.3,0],[1.3,0]);line([0,-1.3],[0,1.3]);stroke='black';\";\n }\n if ($in[0] == \"alttext\") {\n if (isset($in[1])) {\n $hasUserAltText = true;\n $userAltText = $in[1];\n }\n }\n }\n $rotRad = $rot*M_PI/180;\n if (is_numeric($argsArray[0][0])) {\n $ang = $argsArray[0][0];\n $hasArc = true;\n if (isset($argsArray[0][1])) {\n $lab = $argsArray[0][1];\n $degSymbol = \"&deg;\";\n }\n if (isset($argsArray[0][2])) {\n if ($argsArray[0][2] === \"noarc\") {$hasArc = false;}\n }\n }\n if (abs($ang)>=2000) {\n echo \"Angle must be strictly between -2000 degrees and 2000 degrees.\";\n return '';\n }\n $angRad = $ang*M_PI/180;\n $xStart = cos($rotRad);\n $yStart = sin($rotRad);\n $xEnd = cos($angRad+$rotRad);\n $yEnd = sin($angRad+$rotRad);\n \n // Draw the sides of the angle\n $args = $args.\"stroke='blue'; strokewidth=2;line([0,0],[$xStart,$yStart]);line([0,0],[$xEnd,$yEnd]);dot([0,0]);strokewidth=1; stroke='black';\";\n \n // Label the angle\n $belowFactor = 1;\n $labFact = 0.3;\n $halfAngle = ($ang+$rot)/2;\n if ($hasArc === true) {\n $labFact += 0.09*(abs($ang/360));\n }\n $quadAng = (abs($ang+$rot)%90 != 0) ? (4*($ang+$rot<0 || ($ang+$rot)%360>270) + 1*ceil((($ang+$rot)/90))%4) : 0;\n $quadRot = (abs($rot)%90 != 0) ? (4*($rot<0) + 1*ceil($rot/90)) : 0;\n $labAngArray = diffarrays([1,2,3,4],[$quadAng,$quadRot]);\n $labAng = ($labAngArray[$GLOBALS['RND']->rand(0,count($labAngArray)-1)]*90-45)*M_PI/180;\n [$xLabLoc,$yLabLoc] = [$labFact*cos($labAng),$labFact*sin($labAng)];\n\n $altAngleLab = $lab;\n $greekSpelled = [\"/alpha/\",\"/beta/\",\"/gamma/\",\"/theta/\",\"/phi/\",\"/tau/\",\"/pi/\",\"/rad/\"];\n $greekSymbol = [\"&alpha;\",\"&beta;\",\"&gamma;\",\"&theta;\",\"&phi;\",\"&tau;\",\"&pi;\",\"\"];\n $altGreekSymbol = [\" alpha\",\" beta\",\" gamma\",\" theta\",\" phi\",\" tau\",\" pi\",\"\"];\n if (!empty($lab)) {\n for ($j=0;$j<count($greekSpelled);$j++) {\n if (preg_match($greekSpelled[$j],$lab)) {\n $degSymbol = '';\n $lab = preg_replace($greekSpelled[$j],$greekSymbol[$j],$lab);\n $altAngleLab = preg_replace($greekSpelled[$j],$altGreekSymbol[$j],$altAngleLab);\n }\n } \n } elseif (empty($lab)) {$degSymbol='';}\n $args = $args.\"text([$xLabLoc,$yLabLoc],'$lab$degSymbol');\";\n \n // Draw the angle arc\n if ($hasArc === true) {\n if ($ang < 0) {\n [$xStartTmp,$yStartTmp] = [$xStart,$yStart];\n [$xStart,$yStart] = [$xEnd,$yEnd];\n [$xEnd,$yEnd] = [$xStartTmp,$yStartTmp]; \n }\n // Starting position of the arc\n $arcRad = (abs($ang)<=90) ? 0.85 : 0.15;\n if (abs($ang)>=0) {\n $minAng = $rotRad;\n $maxAng = $rotRad+$angRad;\n if ($ang<0) {\n $minAng = $rotRad+$angRad;\n $maxAng = $rotRad;\n }\n if (abs($ang) > 10) {\n $args = $args.\"plot(['($arcRad+.09/(2*pi)*abs(t-$rotRad))*cos(t)','($arcRad+.09/(2*pi)*abs(t-$rotRad))*sin(t)'],$minAng,$maxAng);\";\n }\n }\n if (abs($ang) <= 180) {\n $arrowOffset = (abs($ang)<=90) ? 0.2*abs($angRad) : 0.7;\n } elseif (abs($ang) > 180 && abs($ang) < 360) {\n $arrowOffset = (abs($ang)<=270) ? 0.15*abs($angRad) : 0.1*abs($angRad);\n } else {\n $arrowOffset = 0.7-0.01*abs($angRad);\n }\n $arrowWeight = 0;\n if ($angRad >= 0) {\n if ($ang > 10) {\n [$xArrowStart,$yArrowStart] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng-$arrowOffset),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng-$arrowOffset)];\n [$xArrowEnd,$yArrowEnd] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng)];\n } else {\n $arrowWeight = 1;\n [$xArrowStart,$yArrowStart] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng+0.3),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng+0.3)];\n [$xArrowEnd,$yArrowEnd] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng)];\n [$xArrowStart1,$yArrowStart1] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng-0.3),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng-0.3)];\n [$xArrowEnd1,$yArrowEnd1] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng)];\n }\n } else {\n if ($ang < -10) {\n [$xArrowStart,$yArrowStart] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng+$arrowOffset),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng+$arrowOffset)];\n [$xArrowEnd,$yArrowEnd] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng)];\n } else {\n $arrowWeight = 1;\n [$xArrowStart,$yArrowStart] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng-0.3),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng-0.3)];\n [$xArrowEnd,$yArrowEnd] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($minAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($minAng)];\n [$xArrowStart1,$yArrowStart1] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng+0.3),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng+0.3)];\n [$xArrowEnd1,$yArrowEnd1] = [($arcRad+.09/(2*M_PI)*abs($angRad))*cos($maxAng),($arcRad+.09/(2*M_PI)*abs($angRad))*sin($maxAng)];\n }\n }\n $args .= \"marker='arrow'; strokewidth=$arrowWeight; line([$xArrowStart,$yArrowStart],[$xArrowEnd,$yArrowEnd]); strokewidth=1; marker='none';\";\n if (abs($ang) <= 10) {\n $args .= \"marker='arrow'; line([$xArrowStart1,$yArrowStart1],[$xArrowEnd1,$yArrowEnd1]); strokewidth=1; marker='none';\";\n }\n }\n \n // Build alt text\n if ($hasUserAltText !== true) {\n $altRefLabel = \"\";\n $angRef = abs($ang)%360;\n $angTurns = floor(abs($ang)/360);\n if ($angTurns > 0) {\n $altAnother = \" an additional\";\n if ($angRef > 270 && $angRef < 360) {\n $altAnother = \" additional\";\n }\n }\n if ($angRef == 0 && $angTurns == 0) {\n $altRefLabel = \" with zero rotation\";\n }\n elseif ($angRef > 0 && $angRef < 90) {\n $altRefLabel = \" less than one quarter of\".$altAnother.\" rotation\";\n }\n elseif ($angRef == 90) {\n $altRefLabel = \" one quarter of\".$altAnother.\" rotation\";\n }\n elseif ($angRef > 90 && $angRef < 180) {\n $altRefLabel = \" between one quarter and one half of\".$altAnother.\" rotation\";\n }\n elseif ($angRef == 180) {\n $altRefLabel = \" one half of\".$altAnother.\" rotation\";\n }\n elseif ($angRef > 180 && $angRef < 270) {\n $altRefLabel = \" between one half and three quarters of\".$altAnother.\" rotation\";\n }\n elseif ($angRef == 270) {\n $altRefLabel = \" three quarters of\".$altAnother.\" rotation\";\n }\n elseif ($angRef > 270 && $angRef < 360) {\n $altRefLabel = \" between three quarters and one\".$altAnother.\" full rotation\";\n }\n \n if (abs($angTurns) > 0) {\n $altTurnsAnd = \"\";\n if ($angRef > 0) {\n $altTurnsAnd = \" and also \";\n }\n $howManyTurns = \"rotation\" . $altTurnsAnd;\n if (abs($angTurns) > 1) {\n $howManyTurns = \"rotations\" . $altTurnsAnd;\n }\n $altTurnsLabel = \" \".numtowords($angTurns).\" complete \".$howManyTurns;\n }\n if ($degSymbol == \"&deg;\") {\n $altDegSymbol = \" degrees\";\n }\n \n if ($ang > 0) {\n $direction = \" turned counterclockwise\";\n } elseif ($ang < 0) {\n $direction = \" turned clockwise\";\n }\n if (isset($argsArray[0][1])) {\n $altLabel = \", and labeled $altAngleLab$altDegSymbol\";\n }\n $alt = \"An angle\".$direction.$altTurnsLabel.$altRefLabel.$altLabel.\".\";\n } else {\n $alt = $userAltText;\n }\n $gr = showasciisvg(\"setBorder(5);initPicture(-1.1,1.1,-1.1,1.1);$args\",$size,$size,$alt);\n return $gr;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function getSettingsView(Request $request)\n {\n $data = $this->getSettings(true);\n\n // format display name for selected graph type\n $type_parts = explode('_', $data['graph_type']);\n $primary = array_shift($type_parts);\n $secondary = implode('_', $type_parts);\n $name = $primary . ' ' . (Graph::isMibGraph($primary, $secondary) ? $secondary : implode(' ', $type_parts));\n\n // format display for selected items\n if ($primary == 'device' && $data['graph_device']) {\n $device = Device::find($data['graph_device']);\n }\n $data['device_text'] = isset($device) ? $device->displayName() : __('Device does not exist');\n\n if ($primary == 'port' && $data['graph_port']) {\n $port = Port::find($data['graph_port']);\n }\n $data['port_text'] = isset($port) ? $port->getLabel() : __('Port does not exist');\n\n if ($primary == 'application' && $data['graph_application']) {\n $app = Application::find($data['graph_application']);\n }\n $data['application_text'] = isset($app) ? $app->displayName() . ' - ' . $app->device->displayName() : __('App does not exist');\n\n if ($primary == 'bill' && $data['graph_bill']) {\n $bill = Bill::find($data['graph_bill']);\n }\n $data['bill_text'] = isset($bill) ? $bill->bill_name : __('Bill does not exist');\n\n if ($primary == 'munin' && $data['graph_munin']) {\n $mplug = MuninPlugin::with('device')->find($data['graph_munin']);\n }\n $data['munin_text'] = isset($mplug) ? $mplug->device->displayName() . ' - ' . $mplug->mplug_type : __('Munin plugin does not exist');\n\n if ($primary == 'service' && $data['graph_service']) {\n $service = Service::with('device')->find($data['graph_service']);\n }\n $data['service_text'] = isset($service) ? $service->device->displayName() . ' - ' . $service->service_type . ' (' . $service->service_desc . ')' : __('Service does not exist');\n\n $data['graph_ports'] = Port::whereIntegerInRaw('port_id', $data['graph_ports'])\n ->select('ports.device_id', 'port_id', 'ifAlias', 'ifName', 'ifDescr')\n ->with(['device' => function ($query) {\n $query->select('device_id', 'hostname', 'sysName', 'display');\n }])->get();\n\n $data['graph_port_ids'] = $data['graph_ports']->pluck('port_id')->toJson();\n\n $data['graph_text'] = ucwords($name);\n\n return view('widgets.settings.graph', $data);\n }", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function registerHook($hook_name, $shop_list = null)\n {\n $return = true;\n if (is_array($hook_name)) {\n $hook_names = $hook_name;\n } else {\n $hook_names = array($hook_name);\n }\n\n foreach ($hook_names as $hook_name) {\n // Check hook name validation and if module is installed\n if (!Validate::isHookName($hook_name)) {\n throw new PrestaShopException('Invalid hook name');\n }\n if (!isset($this->id) || !is_numeric($this->id)) {\n return false;\n }\n\n // Retrocompatibility\n $hook_name_bak = $hook_name;\n if ($alias = Hook::getRetroHookName($hook_name)) {\n $hook_name = $alias;\n }\n\n Hook::exec('actionModuleRegisterHookBefore', array('object' => $this, 'hook_name' => $hook_name));\n // Get hook id\n $id_hook = Hook::getIdByName($hook_name);\n\n // If hook does not exist, we create it\n if (!$id_hook) {\n $new_hook = new Hook();\n $new_hook->name = pSQL($hook_name);\n $new_hook->title = pSQL($hook_name);\n $new_hook->live_edit = (bool)preg_match('/^display/i', $new_hook->name);\n $new_hook->position = (bool)$new_hook->live_edit;\n $new_hook->add();\n $id_hook = $new_hook->id;\n if (!$id_hook) {\n return false;\n }\n }\n\n // If shop lists is null, we fill it with all shops\n if (is_null($shop_list)) {\n $shop_list = Shop::getCompleteListOfShopsID();\n }\n\n $shop_list_employee = Shop::getShops(true, null, true);\n\n foreach ($shop_list as $shop_id) {\n // Check if already register\n $sql = 'SELECT hm.`id_module`\n\t\t\t\t\tFROM `'._DB_PREFIX_.'hook_module` hm, `'._DB_PREFIX_.'hook` h\n\t\t\t\t\tWHERE hm.`id_module` = '.(int)$this->id.' AND h.`id_hook` = '.$id_hook.'\n\t\t\t\t\tAND h.`id_hook` = hm.`id_hook` AND `id_shop` = '.(int)$shop_id;\n if (Db::getInstance()->getRow($sql)) {\n continue;\n }\n\n // Get module position in hook\n $sql = 'SELECT MAX(`position`) AS position\n\t\t\t\t\tFROM `'._DB_PREFIX_.'hook_module`\n\t\t\t\t\tWHERE `id_hook` = '.(int)$id_hook.' AND `id_shop` = '.(int)$shop_id;\n if (!$position = Db::getInstance()->getValue($sql)) {\n $position = 0;\n }\n\n // Register module in hook\n $return &= Db::getInstance()->insert('hook_module', array(\n 'id_module' => (int)$this->id,\n 'id_hook' => (int)$id_hook,\n 'id_shop' => (int)$shop_id,\n 'position' => (int)($position + 1),\n ));\n\n if (!in_array($shop_id, $shop_list_employee)) {\n $where = '`id_module` = '.(int)$this->id.' AND `id_shop` = '.(int)$shop_id;\n $return &= Db::getInstance()->delete('module_shop', $where);\n }\n }\n\n Hook::exec('actionModuleRegisterHookAfter', array('object' => $this, 'hook_name' => $hook_name));\n }\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function run()\n {\n $this->init();\n if ($this->checkAccess()) {\n // setMedia MUST be called before postProcess\n if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) {\n $this->setMedia();\n }\n\n // postProcess handles ajaxProcess\n $this->postProcess();\n\n if (!empty($this->redirect_after)) {\n $this->redirect();\n }\n\n if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) {\n $this->initHeader();\n }\n\n if ($this->viewAccess()) {\n $this->initContent();\n } else {\n $this->errors[] = $this->trans('Access denied.', array(), 'Admin.Notifications.Error');\n }\n\n if (!$this->content_only && ($this->display_footer || (isset($this->className) && $this->className))) {\n $this->initFooter();\n }\n\n // Default behavior for ajax process is to use $_POST[action] or $_GET[action]\n // then using displayAjax[action]\n if ($this->ajax) {\n $action = Tools::toCamelCase(Tools::getValue('action'), true);\n\n if (!empty($action) && method_exists($this, 'displayAjax'.$action)) {\n $this->{'displayAjax'.$action}();\n } elseif (method_exists($this, 'displayAjax')) {\n $this->displayAjax();\n }\n } else {\n $this->display();\n }\n } else {\n $this->initCursedPage();\n $this->smartyOutputContent($this->layout);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function deviceLink($device, $text = '', $vars = [], $start = 0, $end = 0, $escape_text = 1, $overlib = 1)\n {\n if (! $device instanceof Device || ! $device->hostname) {\n return $escape_text ? htmlentities($text) : (string) $text;\n }\n\n if (! $device->canAccess(Auth::user())) {\n return $escape_text ? htmlentities($device->displayName()) : $device->displayName();\n }\n\n if (! $start) {\n $start = Carbon::now()->subDay()->timestamp;\n }\n\n if (! $end) {\n $end = Carbon::now()->timestamp;\n }\n\n if (! $text) {\n $text = $device->displayName();\n }\n\n if ($escape_text) {\n $text = htmlentities($text);\n }\n\n $class = self::deviceLinkDisplayClass($device);\n $graphs = Graph::getOverviewGraphsForDevice($device);\n $url = Url::deviceUrl($device, $vars);\n\n // beginning of overlib box contains large hostname followed by hardware & OS details\n // because we are injecting this into javascript htmlentities alone won't work, so strip_tags too\n $contents = '<div><span class=\"list-large\">' . htmlentities(strip_tags($device->displayName())) . '</span>';\n $devinfo = '';\n if ($device->hardware) {\n $devinfo .= $device->hardware;\n }\n\n if ($device->os) {\n $devinfo .= ($devinfo ? ' - ' : '') . Config::getOsSetting($device->os, 'text');\n }\n\n if ($device->version) {\n $devinfo .= ($devinfo ? ' - ' : '') . $device->version;\n }\n\n if ($device->features) {\n $devinfo .= ' (' . $device->features . ')';\n }\n\n if ($devinfo) {\n $contents .= '<br />' . htmlentities(strip_tags($devinfo));\n }\n\n if ($device->location_id) {\n $contents .= '<br />' . htmlentities(strip_tags($device->location ?? ''));\n }\n\n $contents .= '</div><br />';\n\n foreach ((array) $graphs as $entry) {\n $graph = isset($entry['graph']) ? $entry['graph'] : 'unknown';\n $graphhead = isset($entry['text']) ? $entry['text'] : 'unknown';\n $contents .= '<div class=\"overlib-box\">';\n $contents .= '<span class=\"overlib-title\">' . $graphhead . '</span><br />';\n $contents .= Url::minigraphImage($device, $start, $end, $graph);\n $contents .= Url::minigraphImage($device, Carbon::now()->subWeek()->timestamp, $end, $graph);\n $contents .= '</div>';\n }\n\n if ($overlib == 0) {\n $link = $contents;\n } else {\n $contents = self::escapeBothQuotes($contents);\n $link = Url::overlibLink($url, $text, $contents, $class);\n }\n\n return $link;\n }", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function SetProtection($permissions=array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass='', $owner_pass=null, $mode=0, $pubkeys=null) {\n\t\t$this->encryptdata['protection'] = $this->getUserPermissionCode($permissions, $mode);\n\t\tif (($pubkeys !== null) AND (is_array($pubkeys))) {\n\t\t\t// public-key mode\n\t\t\t$this->encryptdata['pubkeys'] = $pubkeys;\n\t\t\tif ($mode == 0) {\n\t\t\t\t// public-Key Security requires at least 128 bit\n\t\t\t\t$mode = 1;\n\t\t\t}\n\t\t\tif (!function_exists('openssl_pkcs7_encrypt')) {\n\t\t\t\t$this->Error('Public-Key Security requires openssl library.');\n\t\t\t}\n\t\t\t// Set Public-Key filter (availabe are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)\n\t\t\t$this->encryptdata['pubkey'] = true;\n\t\t\t$this->encryptdata['Filter'] = 'Adobe.PubSec';\n\t\t\t$this->encryptdata['StmF'] = 'DefaultCryptFilter';\n\t\t\t$this->encryptdata['StrF'] = 'DefaultCryptFilter';\n\t\t} else {\n\t\t\t// standard mode (password mode)\n\t\t\t$this->encryptdata['pubkey'] = false;\n\t\t\t$this->encryptdata['Filter'] = 'Standard';\n\t\t\t$this->encryptdata['StmF'] = 'StdCF';\n\t\t\t$this->encryptdata['StrF'] = 'StdCF';\n\t\t}\n\t\tif ($mode > 1) { // AES\n\t\t\tif (!extension_loaded('mcrypt')) {\n\t\t\t\t$this->Error('AES encryption requires mcrypt library (http://www.php.net/manual/en/mcrypt.requirements.php).');\n\t\t\t}\n\t\t\tif (mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {\n\t\t\t\t$this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');\n\t\t\t}\n\t\t\tif (($mode == 3) AND !function_exists('hash')) {\n\t\t\t\t// the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.\n\t\t\t\t$this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');\n\t\t\t}\n\t\t}\n\t\tif ($owner_pass === null) {\n\t\t\t$owner_pass = md5($this->getRandomSeed());\n\t\t}\n\t\t$this->encryptdata['user_password'] = $user_pass;\n\t\t$this->encryptdata['owner_password'] = $owner_pass;\n\t\t$this->encryptdata['mode'] = $mode;\n\t\tswitch ($mode) {\n\t\t\tcase 0: { // RC4 40 bit\n\t\t\t\t$this->encryptdata['V'] = 1;\n\t\t\t\t$this->encryptdata['Length'] = 40;\n\t\t\t\t$this->encryptdata['CF']['CFM'] = 'V2';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1: { // RC4 128 bit\n\t\t\t\t$this->encryptdata['V'] = 2;\n\t\t\t\t$this->encryptdata['Length'] = 128;\n\t\t\t\t$this->encryptdata['CF']['CFM'] = 'V2';\n\t\t\t\tif ($this->encryptdata['pubkey']) {\n\t\t\t\t\t$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';\n\t\t\t\t\t$this->encryptdata['Recipients'] = array();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 2: { // AES 128 bit\n\t\t\t\t$this->encryptdata['V'] = 4;\n\t\t\t\t$this->encryptdata['Length'] = 128;\n\t\t\t\t$this->encryptdata['CF']['CFM'] = 'AESV2';\n\t\t\t\t$this->encryptdata['CF']['Length'] = 128;\n\t\t\t\tif ($this->encryptdata['pubkey']) {\n\t\t\t\t\t$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';\n\t\t\t\t\t$this->encryptdata['Recipients'] = array();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 3: { // AES 256 bit\n\t\t\t\t$this->encryptdata['V'] = 5;\n\t\t\t\t$this->encryptdata['Length'] = 256;\n\t\t\t\t$this->encryptdata['CF']['CFM'] = 'AESV3';\n\t\t\t\t$this->encryptdata['CF']['Length'] = 256;\n\t\t\t\tif ($this->encryptdata['pubkey']) {\n\t\t\t\t\t$this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';\n\t\t\t\t\t$this->encryptdata['Recipients'] = array();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$this->encrypted = true;\n\t\t$this->encryptdata['fileid'] = $this->convertHexStringToString($this->file_id);\n\t\t$this->_generateencryptionkey();\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['severity'])) {\n $this->setSeverity($data['severity']);\n }\n if (isset($data['patient'])) {\n $this->setPatient($data['patient']);\n }\n if (isset($data['identifiedDateTime'])) {\n $this->setIdentifiedDateTime($data['identifiedDateTime']);\n }\n if (isset($data['identifiedPeriod'])) {\n $this->setIdentifiedPeriod($data['identifiedPeriod']);\n }\n if (isset($data['author'])) {\n $this->setAuthor($data['author']);\n }\n if (isset($data['implicated'])) {\n if (is_array($data['implicated'])) {\n foreach ($data['implicated'] as $d) {\n $this->addImplicated($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"implicated\" must be array of objects or null, ' . gettype($data['implicated']) . ' seen.');\n }\n }\n if (isset($data['evidence'])) {\n if (is_array($data['evidence'])) {\n foreach ($data['evidence'] as $d) {\n $this->addEvidence($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"evidence\" must be array of objects or null, ' . gettype($data['evidence']) . ' seen.');\n }\n }\n if (isset($data['detail'])) {\n $this->setDetail($data['detail']);\n }\n if (isset($data['reference'])) {\n $this->setReference($data['reference']);\n }\n if (isset($data['mitigation'])) {\n if (is_array($data['mitigation'])) {\n foreach ($data['mitigation'] as $d) {\n $this->addMitigation($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"mitigation\" must be array of objects or null, ' . gettype($data['mitigation']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt)\n {\n $FILE = $this->_FILEH_;\n\n // Calculate Basic Setting\n $iBlCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;\n $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE;\n\n $iBdExL = 0;\n $iAll = $iBBcnt + $iPPScnt + $iSBDcnt;\n $iAllW = $iAll;\n $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);\n $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);\n\n // Calculate BD count\n if ($iBdCnt > $i1stBdL) {\n while (1) {\n ++$iBdExL;\n ++$iAllW;\n $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0);\n $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0);\n if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) {\n break;\n }\n }\n }\n\n // Save Header\n fwrite(\n $FILE,\n \"\\xD0\\xCF\\x11\\xE0\\xA1\\xB1\\x1A\\xE1\"\n . \"\\x00\\x00\\x00\\x00\"\n . \"\\x00\\x00\\x00\\x00\"\n . \"\\x00\\x00\\x00\\x00\"\n . \"\\x00\\x00\\x00\\x00\"\n . pack(\"v\", 0x3b)\n . pack(\"v\", 0x03)\n . pack(\"v\", -2)\n . pack(\"v\", 9)\n . pack(\"v\", 6)\n . pack(\"v\", 0)\n . \"\\x00\\x00\\x00\\x00\"\n . \"\\x00\\x00\\x00\\x00\"\n . pack(\"V\", $iBdCnt)\n . pack(\"V\", $iBBcnt+$iSBDcnt) //ROOT START\n . pack(\"V\", 0)\n . pack(\"V\", 0x1000)\n . pack(\"V\", $iSBDcnt ? 0 : -2) //Small Block Depot\n . pack(\"V\", $iSBDcnt)\n );\n // Extra BDList Start, Count\n if ($iBdCnt < $i1stBdL) {\n fwrite(\n $FILE,\n pack(\"V\", -2) // Extra BDList Start\n . pack(\"V\", 0)// Extra BDList Count\n );\n } else {\n fwrite($FILE, pack(\"V\", $iAll+$iBdCnt) . pack(\"V\", $iBdExL));\n }\n\n // BDList\n for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {\n fwrite($FILE, pack(\"V\", $iAll+$i));\n }\n if ($i < $i1stBdL) {\n $jB = $i1stBdL - $i;\n for ($j = 0; $j < $jB; ++$j) {\n fwrite($FILE, (pack(\"V\", -1)));\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public function addRoute($route_id, $rule, $controller, $id_lang = null, array $keywords = array(), array $params = array(), $id_shop = null)\n {\n if (isset(Context::getContext()->language) && $id_lang === null) {\n $id_lang = (int)Context::getContext()->language->id;\n }\n\n if (isset(Context::getContext()->shop) && $id_shop === null) {\n $id_shop = (int)Context::getContext()->shop->id;\n }\n\n $regexp = preg_quote($rule, '#');\n if ($keywords) {\n $transform_keywords = array();\n preg_match_all('#\\\\\\{(([^{}]*)\\\\\\:)?('.implode('|', array_keys($keywords)).')(\\\\\\:([^{}]*))?\\\\\\}#', $regexp, $m);\n for ($i = 0, $total = count($m[0]); $i < $total; $i++) {\n $prepend = $m[2][$i];\n $keyword = $m[3][$i];\n $append = $m[5][$i];\n $transform_keywords[$keyword] = array(\n 'required' => isset($keywords[$keyword]['param']),\n 'prepend' => stripslashes($prepend),\n 'append' => stripslashes($append),\n );\n\n $prepend_regexp = $append_regexp = '';\n if ($prepend || $append) {\n $prepend_regexp = '('.preg_quote($prepend);\n $append_regexp = preg_quote($append).')?';\n }\n\n if (isset($keywords[$keyword]['param'])) {\n $regexp = str_replace($m[0][$i], $prepend_regexp.'(?P<'.$keywords[$keyword]['param'].'>'.$keywords[$keyword]['regexp'].')'.$append_regexp, $regexp);\n } else {\n $regexp = str_replace($m[0][$i], $prepend_regexp.'('.$keywords[$keyword]['regexp'].')'.$append_regexp, $regexp);\n }\n }\n $keywords = $transform_keywords;\n }\n\n $regexp = '#^/'.$regexp.'$#u';\n if (!isset($this->routes[$id_shop])) {\n $this->routes[$id_shop] = array();\n }\n if (!isset($this->routes[$id_shop][$id_lang])) {\n $this->routes[$id_shop][$id_lang] = array();\n }\n\n $this->routes[$id_shop][$id_lang][$route_id] = array(\n 'rule' => $rule,\n 'regexp' => $regexp,\n 'controller' => $controller,\n 'keywords' => $keywords,\n 'params' => $params,\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "protected function parseWhereItem(Query $query, $field, $val, $rule = '', $binds = [])\n {\n // \u5b57\u6bb5\u5206\u6790\n $key = $field ? $this->parseKey($query, $field, true) : '';\n\n // \u67e5\u8be2\u89c4\u5219\u548c\u6761\u4ef6\n if (!is_array($val)) {\n $val = is_null($val) ? ['NULL', ''] : ['=', $val];\n }\n\n list($exp, $value) = $val;\n\n // \u5bf9\u4e00\u4e2a\u5b57\u6bb5\u4f7f\u7528\u591a\u4e2a\u67e5\u8be2\u6761\u4ef6\n if (is_array($exp)) {\n $item = array_pop($val);\n\n // \u4f20\u5165 or \u6216\u8005 and\n if (is_string($item) && in_array($item, ['AND', 'and', 'OR', 'or'])) {\n $rule = $item;\n } else {\n array_push($val, $item);\n }\n\n foreach ($val as $k => $item) {\n $str[] = $this->parseWhereItem($query, $field, $item, $rule, $binds);\n }\n\n return '( ' . implode(' ' . $rule . ' ', $str) . ' )';\n }\n\n // \u68c0\u6d4b\u64cd\u4f5c\u7b26\n $exp = strtoupper($exp);\n if (isset($this->exp[$exp])) {\n $exp = $this->exp[$exp];\n }\n\n if ($value instanceof Expression) {\n\n } elseif (is_object($value) && method_exists($value, '__toString')) {\n // \u5bf9\u8c61\u6570\u636e\u5199\u5165\n $value = $value->__toString();\n }\n\n if (strpos($field, '->')) {\n $jsonType = $query->getJsonFieldType($field);\n $bindType = $this->connection->getFieldBindType($jsonType);\n } else {\n $bindType = isset($binds[$field]) && 'LIKE' != $exp ? $binds[$field] : PDO::PARAM_STR;\n }\n\n if (is_scalar($value) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) {\n if (0 === strpos($value, ':') && $query->isBind(substr($value, 1))) {\n } else {\n $name = $query->bind($value, $bindType);\n $value = ':' . $name;\n }\n }\n\n // \u89e3\u6790\u67e5\u8be2\u8868\u8fbe\u5f0f\n foreach ($this->parser as $fun => $parse) {\n if (in_array($exp, $parse)) {\n $whereStr = $this->$fun($query, $key, $exp, $value, $field, $bindType, isset($val[2]) ? $val[2] : 'AND');\n break;\n }\n }\n\n if (!isset($whereStr)) {\n throw new Exception('where express error:' . $exp);\n }\n\n return $whereStr;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public static function validateImport($params) {\n\n self::initialize();\n\n $progress_session_id = @$params['session'];\n\n $imp_session = ImportSession::load(@$params['imp_ID']);\n if($imp_session==false){\n return false;\n }\n\n //add result of validation to session\n $imp_session['validation'] = array(\n \"count_update\"=>0,\n \"count_insert\"=>0, //records to be inserted\n \"count_update_rows\"=>0,\n \"count_insert_rows\"=>0, //row that are source of insertion\n \"count_ignore_rows\"=>0,\n \"count_error\"=>0,\n \"error\"=>array(),\n \"count_warning\"=>0,\n \"warning\"=>array(),\n \"utm_warning\"=>0,\n \"geo_invalid\"=>array(\n \"outOfBounds\"=>array(),\n \"invalid\"=>array()\n )\n );\n\n //get rectype to import\n $recordType = @$params['sa_rectype'];\n\n $currentSeqIndex = @$params['seq_index'];\n $sequence = null;\n if($currentSeqIndex>=0 && @$imp_session['sequence'] && is_array(@$imp_session['sequence'][$currentSeqIndex])){\n $sequence = $imp_session['sequence'][$currentSeqIndex];\n }\n\n if(intval($recordType)<1){\n self::$system->addError(HEURIST_INVALID_REQUEST, 'Record type not defined');\n return false;\n }\n\n $import_table = $imp_session['import_table'];\n $id_field = @$params['recid_field'];//record ID field is always defined explicitly\n $ignore_insert = (@$params['ignore_insert']==1);//ignore new records\n $ignore_update = (@$params['ignore_update']==1);//ignore update records\n\n $cnt_update_rows = 0;\n $cnt_insert_rows = 0;\n\n $mysqli = self::$system->get_mysqli();\n\n if($id_field!=null){\n $id_field = $mysqli->real_escape_string($id_field);\n }\n\n //get field mapping and selection query from _REQUEST(params)\n if(@$params['mapping']){ //new way\n $mapping_params = @$params['mapping'];\n\n $mapping = array();// fieldtype => fieldname in import table\n $sel_query = array();\n\n if(!isEmptyArray($mapping_params)){\n foreach ($mapping_params as $index => $field_type) {\n\n $field_name = \"field_\".$index;\n\n if(@$mapping[$field_type]){\n array_push($mapping[$field_type], $field_name);\n }else{\n $mapping[$field_type] = array($field_name);\n }\n\n $imp_session['validation']['mapped_fields'][$field_name] = $field_type;\n\n //all mapped fields - they will be used in validation query\n array_push($sel_query, $field_name);\n }\n }else{\n self::$system->addError(HEURIST_INVALID_REQUEST, 'Mapping not defined');\n return false;\n }\n }\n else{\n\n $mapping = array();// fieldtype ID => fieldname in import table\n $mapped_fields = array();\n $sel_query = array();\n foreach ($params as $key => $field_type) {\n if(strpos($key, \"sa_dt_\")===0 && $field_type){\n //get index\n $index = substr($key,6);\n $field_name = \"field_\".$index;\n\n //all mapped fields - they will be used in validation query\n array_push($sel_query, $field_name);\n if(@$mapping[$field_type]){\n array_push($mapping[$field_type], $field_name);\n }else{\n $mapping[$field_type] = array($field_name);\n }\n\n\n $mapped_fields[$field_name] = $field_type;\n }\n }\n if(count($sel_query)<1){\n self::$system->addError(HEURIST_INVALID_REQUEST, 'Mapping not defined');\n return false;\n }\n\n $imp_session['validation']['mapped_fields'] = $mapped_fields;\n }\n\n\n mysql__update_progress(null, $progress_session_id, true, '1,7,index fields validation');\n\n // calculate the number of records to insert, update and insert with existing ids\n // @todo - it has been implemented for non-multivalue indexes only\n if(!$id_field){ //ID field not defined - all records will be inserted\n if(!$ignore_insert){\n $imp_session['validation'][\"count_insert\"] = $imp_session['reccount'];\n $imp_session['validation'][\"count_insert_rows\"] = $imp_session['reccount'];//all rows will be imported as new records\n $select_query = self::composeQuery($sel_fields, $import_table).\" LIMIT 5000\";//for peview only\n $imp_session['validation']['recs_insert'] = mysql__select_all($mysqli, $select_query);\n }\n\n }else{\n\n $cnt_recs_insert_nonexist_id = 0;\n\n $id_field = preg_replace(REGEX_ALPHANUM, \"\", $id_field);//for snyk\n\n // validate selected record ID field\n // in case id field is not created on match step (it is from original set of columns)\n // we have to verify that its values are valid\n if(!@$imp_session['indexes'][$id_field]){\n\n //find recid with different rectype\n $fields = implode(\"`,`\",$sel_query);\n $query = \"SELECT imp_id, `$fields`, `$id_field` FROM `$import_table` \"\n .\" LEFT JOIN Records on rec_ID=`$id_field`\"\n .\" WHERE rec_RecTypeID<>\".$recordType;\n\n // TPDO: I'm not sure whether message below has been correctly interpreted\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"Your input data contain record IDs in the selected ID column for existing records which are not numeric IDs. \".\n \"The import cannot proceed until this is corrected.\",\"Incorrect record types\", $id_field);\n\n if(!isEmptyArray($wrong_records)) {\n $wrong_records['validation']['mapped_fields'][$id_field] = 'id';\n $imp_session = $wrong_records;\n }elseif($wrong_records) { //error\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n\n if(!$ignore_insert){ //WARNING - it ignores possible multivalue index field\n //find record ID that do not exist in HDB - to insert\n $query = \"select count(imp_id) \"\n .\" from `$import_table` \"\n .\" left join Records on rec_ID=`$id_field` \"\n .\" where `$id_field`>0 and rec_ID is null\";\n $cnt = mysql__select_value($mysqli, $query);\n if($cnt>0){\n $cnt_recs_insert_nonexist_id = $cnt;\n }\n }\n }\n\n // find records to update\n if(!$ignore_update){\n $select_query = \"SELECT count(DISTINCT `$id_field`) FROM `$import_table` \"\n .\" left join Records on rec_ID=`$id_field` WHERE rec_ID is not null and `$id_field`>0\";\n $cnt = mysql__select_value($mysqli, $select_query);\n if($cnt>0){\n\n $imp_session['validation']['count_update'] = $cnt;\n $imp_session['validation']['count_update_rows'] = $cnt;\n //find first 5000 records to display\n $select_query = \"SELECT `$id_field`, imp_id, `\".implode(\"`,`\",$sel_query)\n .\"` FROM `$import_table` \"\n .\" left join Records on rec_ID=`$id_field` \"\n .\" WHERE rec_ID is not null and `$id_field`>0\"\n .\" ORDER BY `$id_field` LIMIT 5000\";//for preview only\n $imp_session['validation']['recs_update'] = mysql__select_all($mysqli, $select_query);//for preview only\n\n }elseif($cnt==null){\n self::$system->addError(HEURIST_DB_ERROR,\n 'SQL error: Cannot execute query to calculate number of records to be updated!', $mysqli->error);\n return false;\n }\n }\n\n if(!$ignore_insert){\n\n // find records to insert\n $select_query = \"SELECT count(DISTINCT `$id_field`) FROM `$import_table` WHERE `$id_field`<0\";//$id_field.\" is null OR \".\n $cnt = mysql__select_value($mysqli, $select_query);\n $cnt = ($cnt>0)?intval($cnt):0;\n\n $select_query = \"SELECT count(*) FROM `$import_table` WHERE `$id_field` IS NULL\";\n $cnt2 = mysql__select_value($mysqli, $select_query);\n $cnt = $cnt + ($cnt2>0?intval($cnt2):0);\n\n if( $cnt>0 ){\n $imp_session['validation']['count_insert'] = $cnt;\n $imp_session['validation']['count_insert_rows'] = $cnt;\n\n //find first 5000 records to preview display\n $select_query = self::composeQuery($sel_query, $import_table)\n .\" WHERE `$id_field`<0 or `$id_field` IS NULL LIMIT 5000\";//for preview only\n $imp_session['validation']['recs_insert'] = mysql__select_all($mysqli, $select_query);\n }\n }\n //additional query for non-existing IDs\n if($cnt_recs_insert_nonexist_id>0){\n\n $imp_session['validation']['count_insert_nonexist_id'] = $cnt_recs_insert_nonexist_id;\n $imp_session['validation']['count_insert'] = $imp_session['validation']['count_insert']+$cnt_recs_insert_nonexist_id;\n $imp_session['validation']['count_insert_rows'] = $imp_session['validation']['count_insert'];\n\n $select_query = self::composeQuery($sel_query, $import_table)\n .\" LEFT JOIN Records on rec_ID=`$id_field` \"\n .\" WHERE `$id_field`>0 and rec_ID is null LIMIT 5000\";//for preview only\n $res = mysql__select_all($mysqli, $select_query);\n if(!isEmptyArray($res)){\n if(@$imp_session['validation']['recs_insert']){\n $imp_session['validation']['recs_insert'] = array_merge($imp_session['validation']['recs_insert'], $res);\n }else{\n $imp_session['validation']['recs_insert'] = $res;\n }\n }\n }\n\n }//id_field defined\n\n\n // fill array with field in import table to be validated\n $recStruc = dbs_GetRectypeStructures(self::$system, array($recordType), 2);\n $recStruc = $recStruc['typedefs'];\n $idx_reqtype = $recStruc['dtFieldNamesToIndex']['rst_RequirementType'];\n $idx_fieldtype = $recStruc['dtFieldNamesToIndex']['dty_Type'];\n\n $dt_mapping = array();//mapping to detail type ID\n\n $missed = array();\n $query_reqs = array();//fieldnames from import table\n $query_reqs_where = array();//where clause for validation of required fields\n\n $query_enum = array();\n $query_enum_join = array();\n $query_enum_where = array();\n\n $query_res = array();\n $query_res_join = array();\n $query_res_where = array();\n\n $query_num = array();\n $query_num_nam = array();\n $query_num_where = array();\n\n $query_date = array();\n $query_date_nam = array();\n $query_date_where = array();\n\n $numeric_regex = \"'^([+-]?[0-9]+\\.*)+'\";\n\n if($sequence){\n $mapping_prev_session = @$sequence['mapping_keys'];//OR mapping_flds???\n }else{\n $mapping_prev_session = @$imp_session['mapping'];\n }\n\n\n $geo_fields = null;\n\n\n //loop for all fields in record type structure\n foreach ($recStruc[$recordType]['dtFields'] as $ft_id => $ft_vals) {\n\n //find among mappings\n $field_name = @$mapping[$ft_id];//there may be several field_xx in csv to be imported\n if(!$field_name){\n\n if(is_array($mapping_prev_session)){\n $field_name = array_search($recordType.\".\".$ft_id, $mapping_prev_session, true);//from previous session\n\n if($field_name && !is_array($field_name)) {$field_name = array($field_name);}\n }\n }\n\n if(!$field_name && $ft_vals[$idx_fieldtype] == \"geo\"){\n //specific mapping for geo fields\n //it may be mapped to itself or mapped to two fields - lat and long\n\n $field_name1 = @$mapping[$ft_id.\"_lat\"];\n $field_name2 = @$mapping[$ft_id.\"_long\"];\n if(!$field_name1 && !$field_name2 && is_array($mapping_prev_session)){\n $field_name1 = array_search($recordType.\".\".$ft_id.\"_lat\", $mapping_prev_session, true);\n $field_name2 = array_search($recordType.\".\".$ft_id.\"_long\", $mapping_prev_session, true);\n }\n\n if(!isEmptyArray($field_name1)){\n $field_name1 = $field_name1[0];\n }\n if(!isEmptyArray($field_name2)){\n $field_name2 = $field_name2[0];\n }\n /*\n if($field_name1){\n $field_name1 = preg_replace(REGEX_ALPHANUM, \"\", $field_name1);//for snyk\n }\n if($field_name2){\n $field_name2 = preg_replace(REGEX_ALPHANUM, \"\", $field_name2);//for snyk\n }*/\n\n //search for empty required fields in import table\n if($ft_vals[$idx_reqtype] == \"required\"){\n if(!$field_name1 || !$field_name2){\n array_push($missed, $ft_vals[0]);\n }else{\n array_push($query_reqs, $field_name1);\n array_push($query_reqs, $field_name2);\n $field_name1 = preg_replace(REGEX_ALPHANUM, \"\", $field_name1);//for snyk\n $field_name2 = preg_replace(REGEX_ALPHANUM, \"\", $field_name2);//for snyk\n array_push($query_reqs_where, \"`$field_name1` is null or `$field_name1`=''\");\n array_push($query_reqs_where, \"`$field_name2` is null or `$field_name2`=''\");\n }\n }\n if($field_name1 && $field_name2){\n $field_name1 = preg_replace(REGEX_ALPHANUM, \"\", $field_name1);//for snyk\n $field_name2 = preg_replace(REGEX_ALPHANUM, \"\", $field_name2);//for snyk\n array_push($query_num, $field_name1);\n array_push($query_num_where, \"(NOT(`$field_name1` is null or `$field_name1`='' or `$field_name1`='NULL') and NOT(`$field_name1` REGEXP \".$numeric_regex.\"))\");\n array_push($query_num, $field_name2);\n array_push($query_num_where, \"(NOT(`$field_name2` is null or `$field_name2`='' or `$field_name2`='NULL') and NOT(`$field_name2` REGEXP \".$numeric_regex.\"))\");\n\n //if UTM zone is not specified need validate for possible UTM values\n // northing, easting\n $geo_fields = array($field_name1,$field_name2);\n }\n\n }else\n if($ft_vals[$idx_fieldtype] == \"geo\"){\n\n //for geo fields take first\n $geo_fields = array(preg_replace(REGEX_ALPHANUM, '', $field_name[0]));//WKT field\n\n }else\n if($ft_vals[$idx_reqtype] == \"required\"){\n if(!$field_name){ //required field is not mapped - error\n //$ft_vals[$idx_fieldtype] == \"file\" ||\n if(!($ft_vals[$idx_fieldtype] == \"resource\")){ //except file and resource (record pointer)\n array_push($missed, $ft_vals[0]);\n }\n\n }else{\n //not empty\n $squery = array();\n foreach($field_name as $f_name){\n\n $f_name = preg_replace(REGEX_ALPHANUM, \"\", $f_name);//for snyk\n\n if($ft_vals[$idx_fieldtype] == \"resource\"){ //|| $ft_vals[$idx_fieldtype] == \"enum\"){\n //$squery = \"not (\".$field_name.\">0)\";\n $squery[] = \"`$f_name`>0\";\n }else{\n $squery[] = \"`$f_name` is null or `$f_name`=''\";\n }\n array_push($query_reqs, $field_name);\n }\n if($ft_vals[$idx_fieldtype] == \"resource\"){\n $squery = 'not ('.implode(' OR ',$squery).')';\n }else{\n $squery = ' ('.implode(' OR ',$squery).')';\n }\n\n array_push($query_reqs_where, $squery);\n\n }\n }\n\n if($field_name){ //mapping exists\n\n foreach($field_name as $f_name){\n $dt_mapping[$f_name] = $ft_id;\n }\n\n if($ft_vals[$idx_fieldtype] == \"enum\" || $ft_vals[$idx_fieldtype] == \"relationtype\") {\n\n foreach($field_name as $f_name){\n\n $f_name = preg_replace(REGEX_ALPHANUM, \"\", $f_name);//for snyk\n\n array_push($query_enum, $f_name);\n $trm1 = \"trm\".count($query_enum);\n array_push($query_enum_join,\n \" defTerms $trm1 on ($trm1.trm_Code=`$f_name` OR \"\n .\" $trm1.trm_Label=`$f_name` OR $trm1.trm_Label=SUBSTRING_INDEX(`$f_name`,'.',-1))\"\n );\n array_push($query_enum_where, \"(\".$trm1.\".trm_Label is null and not (`$f_name` is null or `$f_name`='' or `$f_name`='NULL'))\");\n }\n\n }elseif($ft_vals[$idx_fieldtype] == \"resource\"){\n\n $f_name = $field_name[0];//@todo for multimapping as for enum\n\n $f_name = preg_replace(REGEX_ALPHANUM, \"\", $f_name);//for snyk\n\n array_push($query_res, $f_name);\n $trm1 = \"rec\".count($query_res);\n array_push($query_res_join, \" Records $trm1 on $trm1.rec_ID=$f_name \");\n array_push($query_res_where, \"(\".$trm1.\".rec_ID is null and not ($f_name is null or $f_name='' or $f_name='NULL'))\");\n\n }elseif($ft_vals[$idx_fieldtype] == \"float\" || $ft_vals[$idx_fieldtype] == \"integer\") {\n\n $f_name = $field_name[0];//@todo for multimapping as for enum\n $f_name = preg_replace(REGEX_ALPHANUM, \"\", $f_name);//for snyk\n\n array_push($query_num, $f_name);\n array_push($query_num_where, \"(NOT($f_name is null or $f_name='' or $f_name='NULL') and NOT($f_name REGEXP \".$numeric_regex.\"))\");\n\n\n\n }elseif($ft_vals[$idx_fieldtype] == \"date\" || $ft_vals[$idx_fieldtype] == \"year\") {\n\n $f_name = $field_name[0];//@todo for multimapping as for enum\n $f_name = preg_replace(REGEX_ALPHANUM, \"\", $f_name);//for snyk\n\n array_push($query_date, $f_name);\n if($ft_vals[$idx_fieldtype] == \"year\"){\n array_push($query_date_where, \"(concat('',$f_name * 1) != $f_name \"\n .\"and not ($f_name is null or $f_name='' or $f_name='NULL'))\");\n }else{\n array_push($query_date_where, \"(str_to_date($f_name, '%Y-%m-%d %H:%i:%s') is null \"\n .\"and str_to_date($f_name, '%d/%m/%Y') is null \"\n .\"and str_to_date($f_name, '%d-%m-%Y') is null \"\n .\"and not ($f_name is null or $f_name='' or $f_name='NULL'))\");\n }\n\n }\n\n }\n }\n\n //ignore_required\n\n //1. Verify that all required field are mapped =====================================================\n if(!empty($missed) &&\n ($imp_session['validation']['count_insert']>0 // there are records to be inserted\n // || ($params['sa_upd']==2 && $params['sa_upd2']==1) // Delete existing if no new data supplied for record\n )){\n /*\n self::$system->addError(HEURIST_ERROR, 'The following fields are required fields. You will need to map\nthem to incoming data before you can import new records:<br><br>'.implode(\",\", $missed));\n return false;\n */\n $imp_session['validation']['missed_required_fields_map'] = $missed;\n }\n\n if($id_field){ //validate only for defined records IDs\n $id_field = preg_replace(REGEX_ALPHANUM, \"\", $id_field);//for snyk\n if($ignore_insert){\n $only_for_specified_id = \" (`$id_field` > 0) AND \";\n }else{\n if($ignore_update){\n $only_for_specified_id = \" (NOT(`$id_field` > 0 OR `$id_field`='')) AND \";\n }else{\n $only_for_specified_id = \" (`$id_field`!='') AND \"; //otherwise it does not for skip matching \" (NOT(\".$id_field.\" is null OR \".$id_field.\"='')) AND \"\n }\n }\n }else{\n $only_for_specified_id = '';\n }\n\n //2. In DB: Verify that all required fields have values =============================================\n mysql__update_progress(null, $progress_session_id, false, '2,7,checking that required fields have values');\n\n $k=0;\n foreach ($query_reqs as $field){\n $query = self::composeQuery($sel_query, $import_table)\n .SQL_WHERE.$only_for_specified_id;\n if(@$query_reqs_where[$k]){\n $query = $query . ' ('.$query_reqs_where[$k].')'; // implode(\" or \",$query_reqs_where);\n }else{\n $query = $query . ' 1';\n }\n\n $k++;\n\n $field = preg_replace(REGEX_ALPHANUM, \"\", $field); //for snyk\n\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"This field is required. It is recommended that a value must be supplied for every record. \"\n .\"You can find and correct these values using Verify > Verify integrity\",\n \"Missing Values\", $field, 'warning');\n if(is_array($wrong_records)) {\n\n $cnt = count(@$imp_session['validation']['warning']);//was\n //@$imp_session['validation']['count_warning']\n $imp_session = $wrong_records;\n $imp_session['validation']['missed_required'] = true;\n\n //allow add records with empty required field - 2017/03/12\n if(false && count(@$imp_session['validation']['recs_insert'])>0 ){\n //--remove from array to be inserted - wrong records with missed required field\n $cnt2 = count(@$imp_session['validation']['warning']);//now\n if($cnt2>$cnt){\n $wrong_recs_ids = $imp_session['validation']['warning'][$cnt]['recs_error_ids'];\n if(!empty($wrong_recs_ids)){\n $badrecs = array();\n foreach($imp_session['validation']['recs_insert'] as $idx=>$flds){\n if(in_array($flds[0], $wrong_recs_ids)){\n array_push($badrecs, $idx);\n }\n }\n $imp_session['validation']['recs_insert'] = array_diff_key($imp_session['validation']['recs_insert'],\n array_flip($badrecs) );\n $imp_session['validation'][\"count_insert\"] = count($imp_session['validation']['recs_insert']);\n }\n }\n }\n\n\n }elseif($wrong_records) {\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n }\n\n\n //3. In DB: Verify that enumeration fields have correct values =====================================\n mysql__update_progress(null, $progress_session_id, false, '3,7,validation of enumeration fields');\n\n if(!@$imp_session['csv_enclosure']){\n $imp_session['csv_enclosure'] = @$params['csv_enclosure']?$params['csv_enclosure']:'\"';\n }\n if(!@$imp_session['csv_mvsep']){\n $imp_session['csv_mvsep'] = @$params['csv_mvsep']?$params['csv_mvsep']:'|';\n }\n\n\n $hwv = \" have incorrect values\";\n $k=0;\n foreach ($query_enum as $field){\n\n if(true || in_array(intval(substr($field,6)), $imp_session['multivals'])){ //this is multivalue field - perform special validation\n\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id.\" 1\";\n\n $idx = array_search($field, $sel_query)+1;\n\n $wrong_records = self::validateEnumerations($query, $imp_session, $field, $dt_mapping[$field],\n $idx, $recStruc, $recordType,\n \"Term list values read must match existing term labels OR standard codes defined for the field. Periods may be used as indicators of hierarchy (option in following screen if periods detected)\", \"new terms\", $progress_session_id);\n\n }else{\n\n $query = self::composeQuery($sel_query, $import_table)\n .\" left join \".$query_enum_join[$k] //implode(\" left join \", $query_enum_join)\n .SQL_WHERE.$only_for_specified_id;\n\n if(@$query_enum_where[$k]){\n $query = $query . ' ('.$query_enum_where[$k].')'; // implode(\" or \",$query_enum_where)\n }else{\n $query = $query . ' 1';\n }\n\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"Term list values read must match existing term labels OR standard codes defined for the field. Periods may be used as indicators of hierarchy (option in following screen if periods detected)\",\n \"Invalid Terms\", $field);\n }\n\n $k++;\n\n if(is_array($wrong_records)) {\n $imp_session = $wrong_records;\n }elseif($wrong_records) {\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n }\n\n //4. In DB: Verify resource (record pointer) fields ==================================================\n mysql__update_progress(null, $progress_session_id, false, '4,7,'.MSG_VALIDATION_2);\n\n $k=0;\n foreach ($query_res as $field){\n\n if(true || in_array(intval(substr($field,6)), $imp_session['multivals'])){ //this is multivalue field - perform special validation\n\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id.\" 1\";\n\n $idx = array_search($field, $sel_query)+1;\n\n $wrong_records = self::validateResourcePointers($mysqli, $query, $imp_session,\n $field, $dt_mapping[$field], $idx, $recStruc, $recordType, $progress_session_id);\n\n }else{\n $query = self::composeQuery($sel_query, $import_table).\" left join \".$query_res_join[$k] //implode(\" left join \", $query_res_join)\n .SQL_WHERE.$only_for_specified_id;\n\n if(@$query_res_where[$k]){\n $query = $query . ' ('.$query_res_where[$k].')'; // implode(\" or \",$query_res_where)\n }else{\n $query = $query . ' 1';\n }\n\n\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"Record pointer field values must reference an existing record in the database\",\n \"Invalid Pointers\", $field);\n }\n\n $k++;\n\n //\"Fields mapped as resources(pointers)\".$hwv,\n if(is_array($wrong_records)) {\n $imp_session = $wrong_records;\n }elseif($wrong_records) {\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n }\n\n //5. Verify numeric fields\n mysql__update_progress(null, $progress_session_id, false, '5,7,'.MSG_VALIDATION_1);\n\n $k=0;\n foreach ($query_num as $field){\n\n if(in_array(intval(substr($field,6)), $imp_session['multivals'])){ //this is multivalue field - perform special validation\n\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id.\" 1\";\n\n $idx = array_search($field, $sel_query)+1;\n\n $wrong_records = self::validateNumericField($mysqli, $query, $imp_session, $field, $idx, 'warning', $progress_session_id);\n\n }else{\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id;\n\n if(@$query_num_where[$k]){\n $query = $query . '('.$query_num_where[$k].')';\n }else{\n $query = $query . ' 1';\n }\n\n\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"Numeric fields must be pure numbers, they cannot include alphabetic characters or punctuation\",\n \"Invalid Numerics\", $field, 'warning');\n }\n\n $k++;\n\n // \"Fields mapped as numeric\".$hwv,\n if(is_array($wrong_records)) {\n $imp_session = $wrong_records;\n }elseif($wrong_records) {\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n }\n\n //6. Verify datetime fields\n mysql__update_progress(null, $progress_session_id, false, '6,7,validation of datetime fields');\n\n $k=0;\n foreach ($query_date as $field){\n\n if(true || in_array(intval(substr($field,6)), $imp_session['multivals'])){ //this is multivalue field - perform special validation\n\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id.\" 1\";\n\n $idx = array_search($field, $sel_query)+1;\n\n $wrong_records = self::validateDateField($query, $imp_session, $field, $idx, 'warning');\n\n }else{\n $query = self::composeQuery($sel_query, $import_table).SQL_WHERE.$only_for_specified_id;\n\n if(@$query_date_where[$k]){\n $query = $query . '('.$query_date_where[$k].')';\n }else{\n $query = $query . ' 1';\n }\n\n $wrong_records = self::getWrongRecords($query, $imp_session,\n \"Date values must be in dd-mm-yyyy, dd/mm/yyyy or yyyy-mm-dd formats\",\n \"Invalid Dates\", $field, 'warning');\n\n }\n\n $k++;\n //\"Fields mapped as date\".$hwv,\n if(is_array($wrong_records)) {\n $imp_session = $wrong_records;\n }elseif($wrong_records) {\n self::$system->addError(HEURIST_ERROR, $wrong_records);\n return false;\n }\n }\n\n //7. Verify geo fields, TODO: Verify geo fields for UTM\n if(!isEmptyArray($geo_fields)){\n\n foreach($geo_fields as $k=>$fld){ //for snyk\n $geo_fields[$k] = preg_replace(REGEX_ALPHANUM, \"\", $fld);\n }\n\n // northing, easting\n $query = \"select `\".implode('`,`',$geo_fields).\"`, imp_ID from `$import_table` \";\n\n if(count($geo_fields)==1){\n $query = $query . ' WHERE `'.$geo_fields[0].'` > \"\"';\n }else{\n $query = $query . ' LIMIT 5';\n }\n\n $res = $mysqli->query($query);\n $allInteger = true;\n $allOutWGS = true;\n if($res){\n if(count($geo_fields)==1){ //WKT field\n\n while ($row = $res->fetch_row()){\n\n $imp_id = $row[count($row)-1];\n $values = self::getMultiValues($row[0], $imp_session['csv_enclosure'], $imp_session['csv_mvsep']);\n\n foreach($values as $wkt){\n\n if(!preg_match('/\\d/', $wkt) && !in_array($imp_id, $imp_session['validation']['geo_invalid']['invalid'])){\n array_push($imp_session['validation']['geo_invalid']['invalid'], $imp_id);\n continue 2;\n }\n\n $allOutWGS = true;\n $valid_geo = false;\n\n try{\n\n $geom = geoPHP::load($wkt, 'wkt');\n if($geom!=null && !$geom->isEmpty()){\n $bbox = $geom->getBBox();\n $allOutWGS = (abs($bbox['minx'])<=180) && (abs($bbox['miny'])<=90)\n && (abs($bbox['maxx'])<=180) && (abs($bbox['maxy'])<=90);\n if (!$allOutWGS && !in_array($imp_id, $imp_session['validation']['geo_invalid']['outOfBounds'])){\n array_push($imp_session['validation']['geo_invalid']['outOfBounds'], $imp_id);\n }\n }else{\n // Attempt to convert to POINT(x,y)\n $valid_geo = self::validateGeoField($wkt, $imp_id, $import_table, $geo_fields[0]);\n\n if(!$valid_geo && !in_array($imp_id, $imp_session['validation']['geo_invalid']['invalid'])){\n array_push($imp_session['validation']['geo_invalid']['invalid'], $imp_id);\n }else{\n\n $geom = geoPHP::load($valid_geo, 'wkt');\n if($geom!=null && !$geom->isEmpty()){\n $bbox = $geom->getBBox();\n $allOutWGS = (abs($bbox['minx'])<=180) && (abs($bbox['miny'])<=90)\n && (abs($bbox['maxx'])<=180) && (abs($bbox['maxy'])<=90);\n if (!$allOutWGS && !in_array($imp_id, $imp_session['validation']['geo_invalid']['outOfBounds'])){\n array_push($imp_session['validation']['geo_invalid']['outOfBounds'], $imp_id);\n }\n }\n }\n }\n\n } catch (Exception $e){\n // Attempt to convert to POINT(x,y)\n $valid_geo = self::validateGeoField($wkt, $imp_id, $import_table, $geo_fields[0]);\n\n if(!$valid_geo && !in_array($imp_id, $imp_session['validation']['geo_invalid']['invalid'])){\n array_push($imp_session['validation']['geo_invalid']['invalid'], $imp_id);\n }else{\n\n $geom = geoPHP::load($valid_geo, 'wkt');\n if($geom!=null && !$geom->isEmpty()){\n $bbox = $geom->getBBox();\n $allOutWGS = (abs($bbox['minx'])<=180) && (abs($bbox['miny'])<=90)\n && (abs($bbox['maxx'])<=180) && (abs($bbox['maxy'])<=90);\n if (!$allOutWGS && !in_array($imp_id, $imp_session['validation']['geo_invalid']['outOfBounds'])){\n array_push($imp_session['validation']['geo_invalid']['outOfBounds'], $imp_id);\n }\n }\n }\n }\n\n if(!$allOutWGS){\n $allInteger = $allOutWGS;\n }\n }\n }\n }else{ //lat long fields\n while ($row = $res->fetch_row()){\n $northing = (float)$row[0];\n $easting = (float)$row[1];\n\n $allInteger = $allInteger && ($northing==round($northing)) && ($easting==round($easting));\n $allOutWGS = $allOutWGS && (abs($easting)>180) && (abs($northing)>90);\n if (!($allOutWGS && $allInteger)) {break;}\n }\n }\n\n if($allInteger || $allOutWGS){\n $imp_session['validation']['utm_warning'] = 1;\n }\n $res->close();\n }\n }\n\n mysql__update_progress(null, $progress_session_id, false, 'REMOVE');\n\n return $imp_session;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private function analyseFkey($values)\n {\n if (is_array($values)) {\n $keys = array_keys($values);\n if (count($values) == 2) {\n $t1 = $keys[0];\n $f1 = $values[$t1];\n $t2 = $keys[1];\n $f2 = $values[$t2];\n if ($f2 instanceof QuerySubQuery || $f2 instanceof QueryExpression) {\n return (is_numeric($t1) ? DBmysql::quoteName($f1) : DBmysql::quoteName($t1) . '.' . DBmysql::quoteName($f1)) . ' = ' .\n $f2;\n } else {\n return (is_numeric($t1) ? DBmysql::quoteName($f1) : DBmysql::quoteName($t1) . '.' . DBmysql::quoteName($f1)) . ' = ' .\n (is_numeric($t2) ? DBmysql::quoteName($f2) : DBmysql::quoteName($t2) . '.' . DBmysql::quoteName($f2));\n }\n } else if (count($values) == 3) {\n $real_values = [];\n foreach ($values as $k => $v) {\n if (is_array($v)) {\n $condition = $v;\n } else {\n $real_values[$k] = $v;\n }\n }\n\n if (!isset($condition)) {\n //in theory, should never happen\n $condition = array_pop($real_values);\n }\n\n $fkey = $this->analyseFkey($real_values);\n $condition_value = $this->analyseCrit(current($condition));\n if (!empty(trim($condition_value))) {\n return $fkey . ' ' . key($condition) . ' ' . $condition_value;\n }\n return $fkey;\n }\n } else if ($values instanceof QueryExpression) {\n return $values->getValue();\n }\n throw new \\LogicException('BAD FOREIGN KEY, should be [ table1 => key1, table2 => key2 ] or [ table1 => key1, table2 => key2, [criteria]].');\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function validatePassword(string $password, array &$errors = []): bool\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n // Clear errors\n $errors = [];\n\n // Validate security policies\n if ($CFG_GLPI[\"use_password_security\"]) {\n if (Toolbox::strlen($password) < $CFG_GLPI['password_min_length']) {\n $errors[] = __('Password too short!');\n }\n if ($CFG_GLPI[\"password_need_number\"] && !preg_match(\"/[0-9]+/\", $password)) {\n $errors[] = __('Password must include at least a digit!');\n }\n if ($CFG_GLPI[\"password_need_letter\"] && !preg_match(\"/[a-z]+/\", $password)) {\n $errors[] = __('Password must include at least a lowercase letter!');\n }\n if ($CFG_GLPI[\"password_need_caps\"] && !preg_match(\"/[A-Z]+/\", $password)) {\n $errors[] = __('Password must include at least a uppercase letter!');\n }\n if ($CFG_GLPI[\"password_need_symbol\"] && !preg_match(\"/\\W+/\", $password)) {\n $errors[] = __('Password must include at least a symbol!');\n }\n }\n\n // Validate password history\n if (!PasswordHistory::getInstance()->validatePassword($this, $password)) {\n $errors[] = __('Password was used too recently.');\n }\n\n // Success if no error found\n return count($errors) === 0;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "#[Route(path: '/fiscaat/pin/crediteer', methods: ['POST'])]\n\tpublic function crediteer()\n\t{\n\t\t$form = new PinBestellingCrediterenForm();\n\n\t\tif ($form->validate()) {\n\t\t\t$values = $form->getValues();\n\n\t\t\t$oudePinTransactieMatch = $this->pinTransactieMatchRepository->retrieveByUUID(\n\t\t\t\t$values['pinTransactieId']\n\t\t\t);\n\t\t\t$form = new PinBestellingCrediterenForm($oudePinTransactieMatch);\n\t\t\t$values = $form->getValues();\n\n\t\t\tif ($oudePinTransactieMatch->transactie !== null) {\n\t\t\t\tthrow new CsrGebruikerException('Er bestaat wel een transactie.');\n\t\t\t}\n\n\t\t\tif ($oudePinTransactieMatch->bestelling === null) {\n\t\t\t\tthrow new CsrGebruikerException(\n\t\t\t\t\t'Geen bestelling gevonden om een creditbestelling voor aan te maken'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t$account = $this->civiSaldoRepository->getSaldo(\n\t\t\t\t$oudePinTransactieMatch->bestelling->uid,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tif (!$account) {\n\t\t\t\tthrow new CsrGebruikerException(\n\t\t\t\t\t'Er is geen CiviSaldo voor dit lid gevonden.'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t/** @var PinTransactieMatch $nieuwePinTransactieMatch */\n\t\t\t$nieuwePinTransactieMatch = $this->em->transactional(function () use (\n\t\t\t\t$account,\n\t\t\t\t$oudePinTransactieMatch,\n\t\t\t\t$values\n\t\t\t) {\n\t\t\t\t$bestelling = $oudePinTransactieMatch->bestelling;\n\t\t\t\t$bestelling->comment = $values['commentOud'];\n\n\t\t\t\t$creditBestelling = $oudePinTransactieMatch->bouwBestelling(\n\t\t\t\t\t$this->civiProductRepository,\n\t\t\t\t\t$values['commentNieuw'] ?: null,\n\t\t\t\t\t$account->uid\n\t\t\t\t);\n\t\t\t\t$creditBestelling->id = $this->civiBestellingModel->create(\n\t\t\t\t\t$creditBestelling\n\t\t\t\t);\n\t\t\t\t$this->civiSaldoRepository->verlagen(\n\t\t\t\t\t$account->uid,\n\t\t\t\t\tabs($creditBestelling->totaal)\n\t\t\t\t);\n\n\t\t\t\t$manager = $this->getDoctrine()->getManager();\n\t\t\t\t$manager->flush();\n\n\t\t\t\t$oudePinTransactieMatch->status =\n\t\t\t\t\tPinTransactieMatchStatusEnum::STATUS_GENEGEERD;\n\t\t\t\t$oudePinTransactieMatch->notitie = $values['internOud'] ?: null;\n\t\t\t\t$nieuwePinTransactieMatch = PinTransactieMatch::negeer(\n\t\t\t\t\tnull,\n\t\t\t\t\t$creditBestelling\n\t\t\t\t);\n\t\t\t\t$nieuwePinTransactieMatch->notitie = $values['internNieuw'] ?: null;\n\t\t\t\t$manager->persist($nieuwePinTransactieMatch);\n\n\t\t\t\treturn $nieuwePinTransactieMatch;\n\t\t\t});\n\n\t\t\tif ($values['stuurMail']) {\n\t\t\t\t$datum = DateUtil::dateFormatIntl(\n\t\t\t\t\t$oudePinTransactieMatch->bestelling->moment,\n\t\t\t\t\t'cccc d MMMM y H:mm'\n\t\t\t\t);\n\t\t\t\t$bedrag = BedragUtil::format_bedrag_kaal(\n\t\t\t\t\t$nieuwePinTransactieMatch->bestelling->totaal\n\t\t\t\t);\n\t\t\t\t$this->stuurMail(\n\t\t\t\t\t$account->uid,\n\t\t\t\t\t'Uw CiviSaldo is verlaagd',\n\t\t\t\t\t\"Uit mijn administratie bleek dat uw pinbetaling van {$datum} niet binnengekomen is. \" .\n\t\t\t\t\t\t'Dit kan voorkomen als een betaling mislukt of niet goed ingevoerd is. ' .\n\t\t\t\t\t\t\"De pinbetaling is teruggedraaid, waardoor uw saldo met \u20ac {$bedrag} verlaagd is. \" .\n\t\t\t\t\t\t'Mocht dit een vergissing zijn, wilt u dan op dit bericht reageren met een schermafbeelding van de pintransactie?'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn $this->tableData([\n\t\t\t\t$oudePinTransactieMatch,\n\t\t\t\t$nieuwePinTransactieMatch,\n\t\t\t]);\n\t\t} else {\n\t\t\treturn $form;\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function actionGenerateTimesheet()\n {\n /**\n * @var $classroom Classroom\n * @var $instructorDisciplines InstructorDisciplines\n */\n $classroomId = $_POST[\"classroom\"];\n $classroom = Classroom::model()->find(\"id = :classroomId\", [\":classroomId\" => $classroomId]);\n $calendar = $classroom->calendarFk;\n\n $criteria = new CDbCriteria();\n $criteria->alias = \"cf\";\n $criteria->join = \"join schedule on schedule.id = cf.schedule_fk\";\n $criteria->condition = \"schedule.classroom_fk = :classroom_fk\";\n $criteria->params = [\"classroom_fk\" => $classroomId];\n $hasFrequency = ClassFaults::model()->exists($criteria);\n\n $criteria = new CDbCriteria();\n $criteria->alias = \"cc\";\n $criteria->join = \"join schedule on schedule.id = cc.schedule_fk\";\n $criteria->condition = \"schedule.classroom_fk = :classroom_fk\";\n $criteria->params = [\"classroom_fk\" => $classroomId];\n $hasClassContent = ClassContents::model()->exists($criteria);\n\n if (!$hasFrequency && !$hasClassContent) {\n $curricularMatrix = TimesheetCurricularMatrix::model()->findAll(\"stage_fk = :stage and school_year = :year\", [\n \":stage\" => $classroom->edcenso_stage_vs_modality_fk, \":year\" => Yii::app()->user->year\n ]);\n if ($curricularMatrix != null) {\n Schedule::model()->deleteAll(\"classroom_fk = :classroom\", [\":classroom\" => $classroomId]);\n\n $schedulesQuantity = 10;\n\n// $turn = 0;\n// if ($classroom->initial_hour < 12) {\n// $turn = 0;\n// }\n// if ($classroom->initial_hour >= 12 && $classroom->initial_hour < 19) {\n// $turn = 1;\n// }\n// if ($classroom->initial_hour >= 19) {\n// $turn = 2;\n// }\n\n\n $weekDays = [];\n if ($classroom->week_days_sunday) {\n array_push($weekDays, 0);\n }\n if ($classroom->week_days_monday) {\n array_push($weekDays, 1);\n }\n if ($classroom->week_days_tuesday) {\n array_push($weekDays, 2);\n }\n if ($classroom->week_days_wednesday) {\n array_push($weekDays, 3);\n }\n if ($classroom->week_days_thursday) {\n array_push($weekDays, 4);\n }\n if ($classroom->week_days_friday) {\n array_push($weekDays, 5);\n }\n if ($classroom->week_days_saturday) {\n array_push($weekDays, 6);\n }\n\n// $instructorDisciplines = InstructorDisciplines::model()->findAll(\"stage_vs_modality_fk = :svm\", [\":svm\" => $classroom->edcenso_stage_vs_modality_fk]);\n// $instructors = [];\n// foreach ($instructorDisciplines as $instructorDiscipline) {\n// if (!isset($instructors[$instructorDiscipline->instructor_fk])) {\n// $instructors[$instructorDiscipline->instructor_fk] = $instructorDiscipline->instructorFk;\n// }\n// }\n//\n// $instructorsUnavailabilities = [];\n// /** @var $instructor TimesheetInstructor */\n// $i = 0;\n// foreach ($instructors as $id => $instructor) {\n// $unavailabilities = $instructor->getInstructorUnavailabilities($turn);\n// if ($instructorsUnavailabilities == NULL) {\n// $instructorsUnavailabilities = [];\n// }\n// $instructorsUnavailabilities[$i++] = ['id' => $id, 'unavailabilities' => $unavailabilities];\n// }\n//\n// function compare($a, $b)\n// {\n// if ($a['unavailabilities']['count'] == $b['unavailabilities']['count']) {\n// return 0;\n// }\n// if ($a['unavailabilities']['count'] > $b['unavailabilities']['count']) {\n// return -1;\n// }\n//\n// return 1;\n// }\n//\n// usort($instructorsUnavailabilities, 'compare');\n\n $disciplines = [];\n $i = 0;\n /** @var CurricularMatrix $cm */\n foreach ($curricularMatrix as $cm) {\n $disciplines[$i] = [\n \"discipline\" => $cm->discipline_fk, \"instructor\" => NULL, \"credits\" => $cm->credits\n ];\n// $needed = $cm->credits;\n// if (count($instructors) > 0) {\n// $indexArray = array();\n//\t for ($idx = 0; $idx < count($instructors); $idx++) {\n//\t\t array_push($indexArray, $idx);\n//\t }\n//\t shuffle($indexArray);\n//\t\t for ($idx = 0; $idx < count($indexArray); $idx++) {\n//\t\t\t if ($instructorsUnavailabilities[$indexArray[$idx]]['unavailabilities']['count'] + $needed < $schedulesQuantity * 7) {\n//\t\t\t\t $disciplines[$i][\"instructor\"] = $instructorsUnavailabilities[$indexArray[$idx]]['id'];\n//\t\t\t\t $instructorsUnavailabilities[$indexArray[$idx]]['unavailabilities']['count'] += $needed;\n//\t\t\t\t break;\n//\t\t\t }\n//\t\t }\n// }\n $i++;\n }\n\n $schedules = [];\n\n for ($i = 1; $i <= $schedulesQuantity; $i++) {\n foreach ($weekDays as $wk) {\n $schedule = new Schedule();\n $schedule->week_day = $wk;\n $schedule->schedule = $i;\n array_push($schedules, $schedule);\n }\n }\n\n $batchInsert = [];\n foreach ($schedules as $schedule) {\n shuffle($disciplines);\n $rand = 0;\n// foreach ($disciplines as $index => $d) {\n// if ($d[\"instructor\"] == NULL) {\n// $rand = $index;\n// break;\n// }\n// $una = NULL;\n// foreach ($instructorsUnavailabilities as $iu) {\n// if ($iu == $d[\"instructor\"]) {\n// $una = $iu['unavailabilities'];\n// break;\n// }\n// }\n// if ($una == NULL) {\n// $rand = $index;\n// break;\n// }\n// $wk = $schedule->week_day;\n// $sc = $schedule->schedule;\n// if (!in_array($sc, $una[$wk])) {\n// $rand = $index;\n// break;\n// }\n// }\n// $instructor = $disciplines[$rand]['instructor'];\n $discipline = $disciplines[$rand]['discipline'];\n $disciplines[$rand]['credits']--;\n if ($disciplines[$rand]['credits'] <= 0) {\n unset($disciplines[$rand]);\n }\n\n if ($discipline !== null) {\n $unavailableEvents = Yii::app()->db->createCommand(\"select ce.start_date, ce.end_date, ce.calendar_event_type_fk from calendar_event as ce where ce.calendar_fk = :calendar_fk and (ce.calendar_event_type_fk = 101 or ce.calendar_event_type_fk = 102 or ce.calendar_event_type_fk = 104)\")->bindParam(\":calendar_fk\", $calendar->id)->queryAll();\n $hardUnavailableDaysArray = [];\n $softUnavailableDaysArray = [];\n foreach ($unavailableEvents as $unavailableEvent) {\n $startDate = new DateTime($unavailableEvent[\"start_date\"]);\n $endDate = new DateTime($unavailableEvent[\"end_date\"]);\n $endDate->modify('+1 day');\n $interval = DateInterval::createFromDateString('1 day');\n $period = new DatePeriod($startDate, $interval, $endDate);\n foreach ($period as $date) {\n if ($unavailableEvent[\"calendar_event_type_fk\"] == 102) {\n if (!in_array($date, $hardUnavailableDaysArray)) {\n array_push($hardUnavailableDaysArray, $date);\n }\n } else {\n if (!in_array($date, $softUnavailableDaysArray)) {\n array_push($softUnavailableDaysArray, $date);\n }\n }\n }\n }\n\n $firstDay = new DateTime($calendar->start_date);\n $lastDay = new DateTime($calendar->end_date);\n $lastDay->modify('+1 day');\n $interval = DateInterval::createFromDateString('1 day');\n $period = new DatePeriod($firstDay, $interval, $lastDay);\n foreach ($period as $date) {\n if ($schedule->week_day == date(\"w\", strtotime($date->format(\"Y-m-d\"))) && !in_array($date, $hardUnavailableDaysArray)) {\n $sc = new Schedule();\n $sc->discipline_fk = $discipline;\n $sc->classroom_fk = $classroomId;\n $sc->day = $date->format(\"j\");\n $sc->month = $date->format(\"n\");\n $sc->year = $date->format(\"Y\");\n $sc->week = $date->format(\"W\");\n $sc->week_day = $schedule->week_day;\n $sc->schedule = $schedule->schedule;\n $sc->unavailable = in_array($date, $softUnavailableDaysArray) ? 1 : 0;\n $sc->turn = $classroom->turn;\n array_push($batchInsert, $sc->getAttributes());\n }\n }\n }\n }\n Yii::app()->db->getCommandBuilder()->createMultipleInsertCommand('schedule', $batchInsert)->execute();\n Log::model()->saveAction(\"timesheet\", $classroom->id, \"U\", $classroom->name);\n }\n $this->actionGetTimesheet($classroomId);\n } else {\n echo json_encode([\"valid\" => false, \"error\" => \"frequencyOrClassContentFilled\"]);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function gen_hl7_order($orderid, &$out)\n{\n $labSample = '';\n $labNote = '';\n // Delimiters\n $d0 = \"\\r\";\n $d1 = '|';\n $d2 = '^';\n\n $today = time();\n $out = '';\n\n $porow = sqlQuery(\n \"SELECT \" .\n \"po.*, \" .\n \"pp.*, \" .\n \"pd.pid, pd.pubpid, pd.fname, pd.lname, pd.mname, pd.DOB, pd.ss, \" .\n \"pd.phone_home, pd.phone_biz, pd.sex, pd.street, pd.city, pd.state, pd.postal_code, \" .\n \"f.encounter, u.fname AS docfname, u.lname AS doclname, u.npi AS docnpi \" .\n \"FROM procedure_order AS po, procedure_providers AS pp, \" .\n \"forms AS f, patient_data AS pd, users AS u \" .\n \"WHERE \" .\n \"po.procedure_order_id = ? AND \" .\n \"pp.ppid = po.lab_id AND \" .\n \"f.formdir = 'procedure_order' AND \" .\n \"f.form_id = po.procedure_order_id AND \" .\n \"pd.pid = f.pid AND \" .\n \"u.id = po.provider_id\",\n array($orderid)\n );\n if (empty($porow)) {\n return \"Procedure order, ordering provider or lab is missing for order ID '$orderid'\";\n }\n\n $pcres = sqlStatement(\n \"SELECT \" .\n \"pc.procedure_code, pc.procedure_name, pc.procedure_order_seq, pc.diagnoses \" .\n \"FROM procedure_order_code AS pc \" .\n \"WHERE \" .\n \"pc.procedure_order_id = ? AND \" .\n \"pc.do_not_send = 0 \" .\n \"ORDER BY pc.procedure_order_seq\",\n array($orderid)\n );\n\n $padOrderId = trim($porow['send_fac_id']) . \"-\" . trim(str_pad((string)$orderid, 4, \"0\", STR_PAD_LEFT));\n // Message Header\n $out .= \"MSH\" .\n $d1 . \"$d2~\\\\&\" . // Encoding Characters (delimiters)\n $d1 . $porow['send_app_id'] . // Sending Application ID\n $d1 . $porow['send_fac_id'] . // Sending Facility ID\n $d1 . $porow['recv_app_id'] . // Receiving Application ID\n $d1 . $porow['recv_fac_id'] . // Receiving Facility ID\n $d1 . date('YmdHis', $today) . // Date and time of this message\n $d1 .\n $d1 . 'ORM' . $d2 . 'O01' . // Message Type\n $d1 . $padOrderId . // Unique Message Number\n $d1 . $porow['DorP'] . // D=Debugging, P=Production\n $d1 . '2.3' . // HL7 Version ID\n $d0;\n\n // Patient Identification\n $out .= \"PID\" .\n $d1 . \"1\" . // Set ID (always just 1 of these)\n $d1 . $porow['pid'] . // Patient ID (not required)\n $d1 . $porow['pid'] . // Patient ID (required)\n $d1 . // Alternate Patient ID (not required)\n $d1 . hl7Text($porow['lname']) .\n $d2 . hl7Text($porow['fname']);\n if ($porow['mname']) {\n $out .= $d2 . hl7Text($porow['mname']);\n }\n\n $out .=\n $d1 .\n $d1 . hl7Date($porow['DOB']) . // DOB\n $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U\n $d1 . $d1 .\n $d1 . hl7Text($porow['street']) .\n $d2 .\n $d2 . hl7Text($porow['city']) .\n $d2 . hl7Text($porow['state']) .\n $d2 . hl7Zip($porow['postal_code']) .\n $d1 .\n $d1 . hl7Phone($porow['phone_home']) .\n $d1 . hl7Phone($porow['phone_biz']) .\n $d1 . $d1 . $d1 .\n $d1 . $porow['encounter'] .\n $d1 . hl7SSN($porow['ss']) .\n $d1 . $d1 . $d1 .\n $d0;\n\n // NTE segment(s).\n $msql = sqlStatement(\"SELECT drug FROM prescriptions WHERE active=1 AND patient_id=?\", [$porow['pid']]);\n $drugs = array();\n while ($mres = sqlFetchArray($msql)) {\n $drugs[] = trim($mres['drug']);\n }\n $med_list = count($drugs) > 0 ? implode(\",\", $drugs) : 'NONE';\n\n $out .= \"NTE\" .\n $d1 . \"1\" .\n $d1 . \"L\" .\n $d1 . \"medications \" . $med_list .\n $d0;\n\n // Patient Visit.\n $out .= \"PV1\" .\n $d1 . \"1\" . // Set ID (always just 1 of these)\n $d1 . // Patient Class (if required, O for Outpatient)\n $d1 . // Patient Location (for inpatient only?)\n $d1 . $d1 . $d1 .\n $d1 . hl7Text($porow['docnpi']) . // Attending Doctor ID\n $d2 . hl7Text($porow['doclname']) . // Last Name\n $d2 . hl7Text($porow['docfname']) . // First Name\n str_repeat($d1, 11) . // PV1 8 to 18 all empty\n $d1 . $porow['encounter'] . // Encounter Number\n str_repeat($d1, 13) . // PV1 20 to 32 all empty\n $d0;\n\n // Insurance stuff.\n $ins_type = trim($porow['billing_type']);\n $payers = loadPayerInfo($porow['pid'], $porow['date_ordered']);\n $setid = 0;\n if ($ins_type == 'T') {\n // only send primary and secondary insurance\n foreach ($payers as $payer) {\n $payer_object = $payer['object'];\n $payer_address = $payer_object->get_address();\n $out .= \"IN1\" .\n $d1 . ++$setid . // Set ID\n $d1 . // Insurance Plan Identifier ??\n $d1 . hl7Text($payer['company']['ins_comp_id']) . // Insurance Company ID\n $d1 . hl7Text($payer['company']['name']) . // Insurance Company Name\n $d1 . hl7Text($payer_address->get_line1()) . // Street Address\n $d2 .\n $d2 . hl7Text($payer_address->get_city()) . // City\n $d2 . hl7Text($payer_address->get_state()) . // State\n $d2 . hl7Zip($payer_address->get_zip()) . // Zip Code\n $d1 .\n $d1 . hl7Phone($payer_object->get_phone()) . // Phone Number\n $d1 . hl7Text($payer['data']['group_number']) . // Insurance Company Group Number\n str_repeat($d1, 7) . // IN1 9-15 all empty\n $d1 . hl7Text($payer['data']['subscriber_lname']) . // Insured last name\n $d2 . hl7Text($payer['data']['subscriber_fname']) . // Insured first name\n $d2 . hl7Text($payer['data']['subscriber_mname']) . // Insured middle name\n $d1 . hl7Relation($payer['data']['subscriber_relationship']) .\n $d1 . hl7Date($payer['data']['subscriber_DOB']) . // Insured DOB\n $d1 . hl7Date($payer['data']['subscriber_street']) . // Insured Street Address\n $d2 .\n $d2 . hl7Text($payer['data']['subscriber_city']) . // City\n $d2 . hl7Text($payer['data']['subscriber_state']) . // State\n $d2 . hl7Zip($payer['data']['subscriber_postal_code']) . // Zip\n $d1 .\n $d1 .\n $d1 . $setid . // 1=Primary, 2=Secondary, 3=Tertiary\n str_repeat($d1, 13) . // IN1-23 to 35 all empty\n $d1 . hl7Text($payer['data']['policy_number']) . // Policy Number\n str_repeat($d1, 10) . // IN1-37 to 47 all empty\n $d1 . $ins_type . // Insurance Type\n $d1 .\n $d1 .\n $d0;\n if ($setid === 2) {\n break;\n }\n }\n if ($setid === 0) {\n return \"\\nInsurance is being billed but patient does not have any payers on record!\";\n }\n } else { // no insurance record\n ++$setid;\n $out .= \"IN1|$setid||||||||||||||||||||||||||||||||||||||||||||||$ins_type\" . $d0;\n }\n if ($ins_type != 'C') {\n $out .= \"GT1\" .\n $d1 . \"1\" . // Set ID (always just 1 of these)\n $d1 .\n $d1 . hl7Text($porow['lname']) .\n $d2 . hl7Text($porow['fname']);\n if ($porow['mname']) {\n $out .= $d2 . hl7Text($porow['mname']);\n }\n\n $out .=\n $d1 .\n $d1 . hl7Text($porow['street']) .\n $d2 .\n $d2 . hl7Text($porow['city']) .\n $d2 . hl7Text($porow['state']) .\n $d2 . hl7Zip($porow['postal_code']) .\n $d1 . hl7Phone($porow['phone_home']) .\n $d1 . hl7Phone($porow['phone_biz']) .\n $d1 . hl7Date($porow['DOB']) . // DOB\n $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U\n $d1 .\n $d1 . '1' . // Relationship\n $d1 . hl7SSN($porow['ss']) .\n $d0;\n }\n // Common Order.\n $out .= \"ORC\" .\n $d1 . \"NW\" . // New Order\n $d1 . $padOrderId . // Placer Order Number\n str_repeat($d1, 6) . // ORC 3-8 not used\n $d1 . date('YmdHis') . // Transaction date/time\n $d1 . $d1 .\n $d1 . hl7Text($porow['docnpi']) . // Ordering Provider\n $d2 . hl7Text($porow['doclname']) . // Last Name\n $d2 . hl7Text($porow['docfname']) . // First Name\n str_repeat($d1, 7) . // ORC 13-19 not used\n $d1 . \"2\" . // ABN Status: 2 = Notified & Signed, 4 = Unsigned\n $d0;\n\n $setid = 0;\n while ($pcrow = sqlFetchArray($pcres)) {\n // Observation Request.\n $out .= \"OBR\" .\n $d1 . ++$setid . // Set ID\n $d1 . $padOrderId . // Placer Order Number\n $d1 .\n $d1 . '^^^' . hl7Text($pcrow['procedure_code']) .\n $d2 . hl7Text($pcrow['procedure_name']) .\n $d1 . hl7Priority($porow['order_priority']) . // S=Stat, R=Routine\n $d1 .\n $d1 . hl7Time($porow['date_collected']) . // Observation Date/Time\n str_repeat($d1, 8) . // OBR 8-15 not used\n $d1 . hl7Text($porow['docnpi']) . // Physician ID\n $d2 . hl7Text($porow['doclname']) . // Last Name\n $d2 . hl7Text($porow['docfname']) . // First Name\n $d1 .\n $d1 . (count($payers) ? 'I' : 'P') . // I=Insurance, C=Client, P=Self Pay\n str_repeat($d1, 8) . // OBR 19-26 not used\n $d1 . '0' . // ?\n $d0;\n\n // Diagnoses. Currently hard-coded for ICD10 and we'll surely want to make\n // this more flexible (probably when some lab needs another diagnosis type).\n $test_diagnosis = $pcrow['diagnoses'];\n if (empty($test_diagnosis)) { // add default primary dianosis\n $test_diagnosis = $porow['order_diagnosis'];\n }\n $setid2 = 0;\n if (!empty($test_diagnosis)) {\n $relcodes = explode(';', $test_diagnosis);\n foreach ($relcodes as $codestring) {\n if ($codestring === '') {\n continue;\n }\n\n list($codetype, $code) = explode(':', $codestring);\n if ($codetype !== 'ICD10') {\n continue;\n }\n\n $desc = lookup_code_descriptions($codestring);\n $out .= \"DG1\" .\n $d1 . ++$setid2 . // Set ID\n $d1 . // Diagnosis Coding Method\n $d1 . $code . // Diagnosis Code\n $d2 . hl7Text(trim($desc)) . // Diagnosis Description\n $d2 . \"I10\" . // Diagnosis Type\n $d1 . $d0;\n }\n }\n\n // Order entry questions and answers.\n $qres = sqlStatement(\n \"SELECT \" .\n \"a.question_code, a.answer, q.fldtype \" .\n \"FROM procedure_answers AS a \" .\n \"LEFT JOIN procedure_questions AS q ON \" .\n \"q.lab_id = ? \" .\n \"AND q.procedure_code = ? AND \" .\n \"q.question_code = a.question_code \" .\n \"WHERE \" .\n \"a.procedure_order_id = ? AND \" .\n \"a.procedure_order_seq = ? \" .\n \"ORDER BY q.seq, a.answer_seq\",\n array($porow['ppid'], $pcrow['procedure_code'], $orderid, $pcrow['procedure_order_seq'])\n );\n $setid2 = 0;\n while ($qrow = sqlFetchArray($qres)) {\n // Formatting of these answer values may be lab-specific and we'll figure\n // out how to deal with that as more labs are supported.\n $answer = trim($qrow['answer']);\n $fldtype = $qrow['fldtype'];\n $datatype = 'ST';\n if ($fldtype == 'N') {\n $datatype = \"NM\";\n } elseif ($fldtype == 'D') {\n $answer = hl7Date($answer);\n } elseif ($fldtype == 'G') {\n $weeks = intval($answer / 7);\n $days = $answer % 7;\n $answer = $weeks . 'wks ' . $days . 'days';\n }\n\n $out .= \"OBX\" .\n $d1 . ++$setid2 . // Set ID\n $d1 . $datatype . // Structure of observation value\n $d1 . hl7Text($qrow['question_code']) . // Clinical question code\n $d1 .\n $d1 . hl7Text($answer) . // Clinical question answer\n $d0;\n }\n }\n //recreate OBX here to add to end of hl7\n $out .= \"OBX\" .\n $d1 . \"1\" .\n $d1 . \"ST\" .\n $d1 . \"PR101^CLINICAL INFORMATION\" .\n $d1 .\n $d1 . $porow['patient_instructions'] .\n $d0;\n\n $out .= \"OBX\" .\n $d1 . \"2\" .\n $d1 . \"ST\" .\n $d1 . \"PR300^SPECIMEN SOURCE/SAMPLE TYPE\" .\n $d1 .\n $d1 . $porow['clinical_hx'] .\n $d0;\n\n return '';\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function validateTransactionId(Recurrence $recurrence, Validator $validator): void\n {\n app('log')->debug('Now in validateTransactionId');\n $transactions = $this->getTransactionData();\n $submittedTrCount = count($transactions);\n\n if (0 === $submittedTrCount) {\n app('log')->warning('[b] User submitted no transactions.');\n $validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));\n\n return;\n }\n $originalTrCount = $recurrence->recurrenceTransactions()->count();\n if (1 === $submittedTrCount && 1 === $originalTrCount) {\n $first = $transactions[0]; // can safely assume index 0.\n if (!array_key_exists('id', $first)) {\n app('log')->debug('Single count and no ID, done.');\n\n return; // home safe!\n }\n $id = $first['id'];\n if ('' === (string)$id) {\n app('log')->debug('Single count and empty ID, done.');\n\n return; // home safe!\n }\n $integer = (int)$id;\n $secondCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', $integer)->count();\n app('log')->debug(sprintf('Result of ID count: %d', $secondCount));\n if (0 === $secondCount) {\n $validator->errors()->add('transactions.0.id', (string)trans('validation.id_does_not_match', ['id' => $integer]));\n }\n app('log')->debug('Single ID validation done.');\n\n return;\n }\n\n app('log')->debug('Multi ID validation.');\n $idsMandatory = false;\n if ($submittedTrCount < $originalTrCount) {\n app('log')->debug(sprintf('User submits %d transaction, recurrence has %d transactions. All entries must have ID.', $submittedTrCount, $originalTrCount));\n $idsMandatory = true;\n }\n\n /**\n * Loop all transactions submitted by the user.\n * If the user has submitted fewer transactions than the original recurrence has, all submitted entries must have an ID.\n * Any ID's missing will be deleted later on.\n *\n * If the user submits more or the same number of transactions (n), the following rules apply:\n *\n * 1. Any 1 transaction does not need to have an ID. Since the other n-1 can be matched, the last one can be assumed.\n * 2. If the user submits more transactions than already present, count the number of existing transactions. At least those must be matched. After that, submit as many as you like.\n * 3. If the user submits the same number of transactions as already present, all but one must have an ID.\n */\n $unmatchedIds = 0;\n\n foreach ($transactions as $index => $transaction) {\n app('log')->debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount));\n if (!is_array($transaction)) {\n app('log')->warning('Not an array. Give error.');\n $validator->errors()->add(sprintf('transactions.%d.id', $index), (string)trans('validation.at_least_one_transaction'));\n\n return;\n }\n if (!array_key_exists('id', $transaction) && $idsMandatory) {\n app('log')->warning('ID is mandatory but array has no ID.');\n $validator->errors()->add(sprintf('transactions.%d.id', $index), (string)trans('validation.need_id_to_match'));\n\n return;\n }\n if (array_key_exists('id', $transaction)) { // don't matter if $idsMandatory\n app('log')->debug('Array has ID.');\n $idCount = $recurrence->recurrenceTransactions()->where('recurrences_transactions.id', (int)$transaction['id'])->count();\n if (0 === $idCount) {\n app('log')->debug('ID does not exist or no match. Count another unmatched ID.');\n ++$unmatchedIds;\n }\n }\n if (!array_key_exists('id', $transaction) && !$idsMandatory) {\n app('log')->debug('Array has no ID but was not mandatory at this point.');\n ++$unmatchedIds;\n }\n }\n // if too many don't match, but you haven't submitted more than already present:\n $maxUnmatched = max(1, $submittedTrCount - $originalTrCount);\n app('log')->debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched));\n if ($unmatchedIds > $maxUnmatched) {\n app('log')->warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds));\n $validator->errors()->add('transactions.0.id', (string)trans('validation.too_many_unmatched'));\n\n return;\n }\n app('log')->debug('Done with ID validation.');\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "protected function value(&$out)\n {\n if (! isset($this->buffer[$this->count])) {\n return false;\n }\n\n $s = $this->count;\n $char = $this->buffer[$this->count];\n\n if (\n $this->literal('url(', 4) &&\n $this->match('data:([a-z]+)\\/([a-z0-9.+-]+);base64,', $m, false)\n ) {\n $len = strspn(\n $this->buffer,\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwyxz0123456789+/=',\n $this->count\n );\n\n $this->count += $len;\n\n if ($this->matchChar(')')) {\n $content = substr($this->buffer, $s, $this->count - $s);\n $out = [Type::T_KEYWORD, $content];\n\n return true;\n }\n }\n\n $this->seek($s);\n\n if (\n $this->literal('url(', 4, false) &&\n $this->match('\\s*(\\/\\/[^\\s\\)]+)\\s*', $m)\n ) {\n $content = 'url(' . $m[1];\n\n if ($this->matchChar(')')) {\n $content .= ')';\n $out = [Type::T_KEYWORD, $content];\n\n return true;\n }\n }\n\n $this->seek($s);\n\n // not\n if ($char === 'n' && $this->literal('not', 3, false)) {\n if (\n $this->whitespace() &&\n $this->value($inner)\n ) {\n $out = [Type::T_UNARY, 'not', $inner, $this->inParens];\n\n return true;\n }\n\n $this->seek($s);\n\n if ($this->parenValue($inner)) {\n $out = [Type::T_UNARY, 'not', $inner, $this->inParens];\n\n return true;\n }\n\n $this->seek($s);\n }\n\n // addition\n if ($char === '+') {\n $this->count++;\n\n $follow_white = $this->whitespace();\n\n if ($this->value($inner)) {\n $out = [Type::T_UNARY, '+', $inner, $this->inParens];\n\n return true;\n }\n\n if ($follow_white) {\n $out = [Type::T_KEYWORD, $char];\n return true;\n }\n\n $this->seek($s);\n\n return false;\n }\n\n // negation\n if ($char === '-') {\n if ($this->customProperty($out)) {\n return true;\n }\n\n $this->count++;\n\n $follow_white = $this->whitespace();\n\n if ($this->variable($inner) || $this->unit($inner) || $this->parenValue($inner)) {\n $out = [Type::T_UNARY, '-', $inner, $this->inParens];\n\n return true;\n }\n\n if (\n $this->keyword($inner) &&\n ! $this->func($inner, $out)\n ) {\n $out = [Type::T_UNARY, '-', $inner, $this->inParens];\n\n return true;\n }\n\n if ($follow_white) {\n $out = [Type::T_KEYWORD, $char];\n\n return true;\n }\n\n $this->seek($s);\n }\n\n // paren\n if ($char === '(' && $this->parenValue($out)) {\n return true;\n }\n\n if ($char === '#') {\n if ($this->interpolation($out) || $this->color($out)) {\n return true;\n }\n\n $this->count++;\n\n if ($this->keyword($keyword)) {\n $out = [Type::T_KEYWORD, '#' . $keyword];\n\n return true;\n }\n\n $this->count--;\n }\n\n if ($this->matchChar('&', true)) {\n $out = [Type::T_SELF];\n\n return true;\n }\n\n if ($char === '$' && $this->variable($out)) {\n return true;\n }\n\n if ($char === 'p' && $this->progid($out)) {\n return true;\n }\n\n if (($char === '\"' || $char === \"'\") && $this->string($out)) {\n return true;\n }\n\n if ($this->unit($out)) {\n return true;\n }\n\n // unicode range with wildcards\n if (\n $this->literal('U+', 2) &&\n $this->match('\\?+|([0-9A-F]+(\\?+|(-[0-9A-F]+))?)', $m, false)\n ) {\n $unicode = explode('-', $m[0]);\n if (strlen(reset($unicode)) <= 6 && strlen(end($unicode)) <= 6) {\n $out = [Type::T_KEYWORD, 'U+' . $m[0]];\n\n return true;\n }\n $this->count -= strlen($m[0]) + 2;\n }\n\n if ($this->keyword($keyword, false)) {\n if ($this->func($keyword, $out)) {\n return true;\n }\n\n $this->whitespace();\n\n if ($keyword === 'null') {\n $out = [Type::T_NULL];\n } else {\n $out = [Type::T_KEYWORD, $keyword];\n }\n\n return true;\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private static function _databaseInitForNew(&$user_record)\n {\n $warnings = array();\n\n $mysqli = self::$mysqli;\n\n //update owner user (#2) in new database\n $user_record['ugr_ID'] = 2;\n $user_record['ugr_NavigationTree'] = '\"bookmark\":{\"expanded\":true,\"key\":\"root_1\",\"title\":\"root\",\"children\":[{\"folder\":false,\"key\":\"_1\",\"title\":\"Recent changes\",\"data\":{\"url\":\"?w=bookmark&q=sortby:-m after:\\\"1 week ago\\\"&label=Recent changes\"}},{\"folder\":false,\"key\":\"_2\",\"title\":\"All (date order)\",\"data\":{\"url\":\"?w=bookmark&q=sortby:-m&label=All records\"}}]},\"all\":{\"expanded\":true,\"key\":\"root_2\",\"title\":\"root\",\"children\":[{\"folder\":false,\"key\":\"_3\",\"title\":\"Recent changes\",\"data\":{\"url\":\"?w=all&q=sortby:-m after:\\\"1 week ago\\\"&label=Recent changes\"}},{\"folder\":false,\"key\":\"_4\",\"title\":\"All (date order)\",\"data\":{\"url\":\"?w=all&q=sortby:-m&label=All records\"}}]}';\n//,{\"folder\":true,\"key\":\"_5\",\"title\":\"Rules\",\"children\":[{\"folder\":false,\"key\":\"12\",\"title\":\"Person > anything they created\",\"data\":{\"isfaceted\":false}},{\"folder\":false,\"key\":\"13\",\"title\":\"Organisation > Assoc. places\",\"data\":{\"isfaceted\":false}}]}\n $user_record['ugr_Preferences'] = '';\n\n $ret = mysql__insertupdate($mysqli, 'sysUGrps', 'ugr', $user_record);\n if($ret!=2){\n array_push($warnings, 'Cannot set owner user. '.$ret);\n }\n\n //add default saved searches and tree\n $navTree = '{\"expanded\":true,\"key\":\"root_3\",\"title\":\"root\",\"children\":[{\"expanded\":true,\"folder\":true,\"key\":\"_1\",\"title\":\"Save some filters here ...\",\"children\":[]}]}';\n//{\"key\":\"28\",\"title\":\"Organisations\",\"data\":{\"isfaceted\":false}},{\"key\":\"29\",\"title\":\"Persons\",\"data\":{\"isfaceted\":false}},{\"key\":\"30\",\"title\":\"Media items\",\"data\":{\"isfaceted\":false}}\n $ret = mysql__insertupdate($mysqli, 'sysUGrps', 'ugr', array('ugr_ID'=>1, 'ugr_NavigationTree'=>$navTree ));\n if($ret!=1){\n array_push($warnings, 'Cannot set navigation tree for group 1. '.$ret);\n }\n\n //ADD DEFAULT LOOKUPS\n $def_lookups = array();\n\n $to_replace = array('DB_ID', 'DTY_ID', 'RTY_ID');\n $dty_CCode = 'SELECT dty_ID FROM defDetailTypes INNER JOIN defRecStructure ON rst_DetailTypeID = dty_ID WHERE dty_OriginatingDBID = DB_ID AND dty_IDInOriginatingDB = DTY_ID AND rst_RecTypeID = RTY_ID';\n\n // GeoNames\n $rty_query = 'SELECT rty_ID FROM defRecTypes WHERE rty_OriginatingDBID = 3 AND rty_IDInOriginatingDB = 1009';\n $rty_id = mysql__select_value($mysqli, $rty_query);\n if(!empty($rty_id)){\n\n $fld_name = mysql__select_value($mysqli, str_replace($to_replace, array('2', '1', $rty_id), $dty_CCode));\n $fld_name = (empty($fld_name)) ? '' : $fld_name;\n\n $fld_geo = mysql__select_value($mysqli, str_replace($to_replace, array('2', '28', $rty_id), $dty_CCode));\n $fld_geo = (empty($fld_geo)) ? '' : $fld_geo;\n\n $fld_cc = mysql__select_value($mysqli, str_replace($to_replace, array('2', '26', $rty_id), $dty_CCode));\n $fld_cc = (empty($fld_cc)) ? '' : $fld_cc;\n\n $fld_fname = mysql__select_value($mysqli, str_replace($to_replace, array('3', '1068', $rty_id), $dty_CCode));\n $fld_fname = (empty($fld_fname)) ? '' : $fld_fname;\n\n $fld_id = mysql__select_value($mysqli, str_replace($to_replace, array('2', '581', $rty_id), $dty_CCode));\n $fld_id = (empty($fld_id)) ? '' : $fld_id;\n\n $key = 'geoName_' . $rty_id;\n $def_lookups[$key] = array('service' => 'geoName', 'rty_ID' => $rty_id, 'label' => 'GeoName', 'dialog' => 'lookupGN', 'fields' => null);\n $def_lookups[$key]['fields'] = array('name' => $fld_name, 'lng' => $fld_geo, 'lat' => $fld_geo, 'countryCode' => $fld_cc, 'adminCode1' => \"\", 'fclName' => $fld_fname, 'fcodeName' => \"\", 'geonameId' => $fld_id, 'population' => \"\");\n }\n\n // Nakala\n $rty_query = 'SELECT rty_ID FROM defRecTypes WHERE rty_OriginatingDBID = 2 AND rty_IDInOriginatingDB = 5';\n $rty_id = mysql__select_value($mysqli, $rty_query);\n if(!empty($rty_id)){\n\n $fld_url = mysql__select_value($mysqli, str_replace($to_replace, array('2', '38', $rty_id), $dty_CCode));\n $fld_url = (empty($fld_url)) ? '' : $fld_url;\n\n $fld_title = mysql__select_value($mysqli, str_replace($to_replace, array('2', '1', $rty_id), $dty_CCode));\n $fld_title = (empty($fld_title)) ? '' : $fld_title;\n\n $fld_aut = mysql__select_value($mysqli, str_replace($to_replace, array('2', '15', $rty_id), $dty_CCode));\n $fld_aut = (empty($fld_aut)) ? '' : $fld_aut;\n\n $fld_date = mysql__select_value($mysqli, str_replace($to_replace, array('2', '10', $rty_id), $dty_CCode));\n $fld_date = (empty($fld_date)) ? '' : $fld_date;\n\n $fld_lic = mysql__select_value($mysqli, str_replace($to_replace, array('1144', '318', $rty_id), $dty_CCode));\n $fld_lic = (empty($fld_lic)) ? '' : $fld_lic;\n\n $fld_type = mysql__select_value($mysqli, str_replace($to_replace, array('2', '41', $rty_id), $dty_CCode));\n $fld_type = (empty($fld_type)) ? '' : $fld_type;\n\n $fld_desc = mysql__select_value($mysqli, str_replace($to_replace, array('2', '3', $rty_id), $dty_CCode));\n $fld_desc = (empty($fld_desc)) ? '' : $fld_desc;\n\n $fld_name = mysql__select_value($mysqli, str_replace($to_replace, array('2', '62', $rty_id), $dty_CCode));\n $fld_name = (empty($fld_name)) ? '' : $fld_name;\n\n $key = 'nakala_' . $rty_id;\n $def_lookups[$key] = array('service' => 'nakala', 'rty_ID' => $rty_id, 'label' => 'Nakala Lookup', 'dialog' => 'lookupNakala', 'fields' => null);\n $def_lookups[$key]['fields'] = array('url' => $fld_url, 'title' => $fld_title, 'author' => $fld_aut, 'date' => $fld_date, 'license' => $fld_lic, 'mime_type' => $fld_type, 'abstract' => $fld_desc, 'rec_url' => '', 'filename' => $fld_name);\n }\n\n if(!empty($def_lookups)){\n\n $lookup_str = json_encode($def_lookups);\n $upd_query = \"UPDATE sysIdentification SET sys_ExternalReferenceLookups = ? WHERE sys_ID = 1\";\n mysql__exec_param_query($mysqli, $upd_query, array('s', $lookup_str));\n }else{\n array_push($warnings, 'Unable to setup default lookup services.');\n }\n\n return $warnings;\n\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "protected function findTemplate($name, $throw = true)\n {\n $name = $this->normalizeName($name);\n\n if (isset($this->cache[$name])) {\n return $this->cache[$name];\n }\n\n if (isset($this->errorCache[$name])) {\n if (!$throw) {\n return false;\n }\n\n throw new LoaderError($this->errorCache[$name]);\n }\n\n try {\n list($namespace, $shortname) = $this->parseName($name);\n\n $this->validateName($shortname);\n } catch (LoaderError $e) {\n if (!$throw) {\n return false;\n }\n\n throw $e;\n }\n\n if (!isset($this->paths[$namespace])) {\n $this->errorCache[$name] = sprintf('There are no registered paths for namespace \"%s\".', $namespace);\n\n if (!$throw) {\n return false;\n }\n\n throw new LoaderError($this->errorCache[$name]);\n }\n\n foreach ($this->paths[$namespace] as $path) {\n if (!$this->isAbsolutePath($path)) {\n $path = $this->rootPath.$path;\n }\n\n if (is_file($path.'/'.$shortname)) {\n if (false !== $realpath = realpath($path.'/'.$shortname)) {\n return $this->cache[$name] = $realpath;\n }\n\n return $this->cache[$name] = $path.'/'.$shortname;\n }\n }\n\n $this->errorCache[$name] = sprintf('Unable to find template \"%s\" (looked into: %s).', $name, implode(', ', $this->paths[$namespace]));\n\n if (!$throw) {\n return false;\n }\n\n throw new LoaderError($this->errorCache[$name]);\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "protected function geolocationManagement($defaultCountry)\n {\n if (!in_array(Tools::getRemoteAddr(), array('localhost', '127.0.0.1'))) {\n /* Check if Maxmind Database exists */\n if (@filemtime(_PS_GEOIP_DIR_._PS_GEOIP_CITY_FILE_)) {\n if (!isset($this->context->cookie->iso_code_country) || (isset($this->context->cookie->iso_code_country) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))))) {\n $reader = new GeoIp2\\Database\\Reader(_PS_GEOIP_DIR_._PS_GEOIP_CITY_FILE_);\n try {\n $record = $reader->city(Tools::getRemoteAddr());\n } catch (\\GeoIp2\\Exception\\AddressNotFoundException $e) {\n $record = null;\n }\n\n if (is_object($record)) {\n if (!in_array(strtoupper($record->country->isoCode), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && !FrontController::isInWhitelistForGeolocation()) {\n if (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_) {\n $this->restrictedCountry = Country::GEOLOC_FORBIDDEN;\n } elseif (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_) {\n $this->restrictedCountry = Country::GEOLOC_CATALOG_MODE;\n $this->warning[] = sprintf($this->l('You cannot place a new order from your country (%s).'), $record->country->name);\n }\n } else {\n $hasBeenSet = !isset($this->context->cookie->iso_code_country);\n $this->context->cookie->iso_code_country = strtoupper($record->country->isoCode);\n }\n }\n }\n\n if (isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country)) {\n $this->context->cookie->iso_code_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));\n }\n\n if (isset($this->context->cookie->iso_code_country) && ($idCountry = (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)))) {\n /* Update defaultCountry */\n if ($defaultCountry->iso_code != $this->context->cookie->iso_code_country) {\n $defaultCountry = new Country($idCountry);\n }\n if (isset($hasBeenSet) && $hasBeenSet) {\n $this->context->cookie->id_currency = (int) ($defaultCountry->id_currency ? (int) $defaultCountry->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'));\n }\n\n return $defaultCountry;\n } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_ && !FrontController::isInWhitelistForGeolocation()) {\n $this->restrictedCountry = Country::GEOLOC_FORBIDDEN;\n } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_ && !FrontController::isInWhitelistForGeolocation()) {\n $this->restrictedCountry = Country::GEOLOC_CATALOG_MODE;\n $this->warning[] = sprintf($this->l('You cannot place a new order from your country (%s).'), (isset($record->country->name) && $record->country->name) ? $record->country->name : $this->l('Undefined'));\n }\n }\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function edih_997_text($segments, $delimiter)\n{\n //\n $str_html = '';\n if (!is_array($segments) || !count($segments) || strlen($delimiter) != 1) {\n //debug\n csv_edihist_log('edih_997_text(): invalid segments');\n return $str_html;\n }\n\n //\n $de = $delimiter;\n $loopid = \"0\";\n //\n //echo 'edih_997_text() foreach segment count: '.count($segments).PHP_EOL;\n //\n foreach ($segments as $key => $seg) {\n //\n //echo var_dump($seg).PHP_EOL;\n //\n if (strncmp('TA1' . $de, $seg, 4) === 0) {\n $sar = explode($de, $seg);\n $rspicn = $sar[1];\n $loopid = 'ACK'; // not official\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n unset($sar);\n $loopid = ''; // reset loop for subsequent segments\n continue;\n }\n\n //\n if (strncmp('ST' . $de, $seg, 3) === 0) {\n $loopid = 'Header';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n continue;\n }\n\n //\n if (strncmp('AK1' . $de, $seg, 4) === 0) {\n $sar = explode($de, $seg);\n $rsptp = csv_file_type($sar[1]);\n if ($rspicn && $rsptp) {\n $rspfile = csv_file_by_controlnum($rsptp, $rspicn);\n }\n\n $title = ($rspfile) ? 'response to ' . $rspfile : '';\n $loopid = '2000';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td title='\" . attr($title) . \"' class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n unset($sar);\n continue;\n }\n\n //\n if (strncmp('AK2' . $de, $seg, 4) === 0) {\n $loopid = 'AK2';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n continue;\n }\n\n //\n if (strncmp('IK3' . $de, $seg, 4) === 0 || strncmp('AK3' . $de, $seg, 4) === 0) {\n $loopid = '2100';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n continue;\n }\n\n //\n if (strncmp('IK4' . $de, $seg, 4) === 0 || strncmp('AK4' . $de, $seg, 4) === 0) {\n $loopid = '2110';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n continue;\n }\n\n //\n if (strncmp('SE' . $de, $seg, 3) === 0) {\n $loopid = 'Trailer';\n $str_html .= \"<tr><td class='btloop'>\" . text($loopid) . \"</td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n continue;\n }\n\n // for all the segments that do not begin loops ;\n $str_html .= \"<tr><td class='btloop'> -- </td><td class='btnum'>\" . text($key) . \"</td><td class='btseg'>\" . text($seg) . \"</td></tr>\" . PHP_EOL;\n }\n\n //\n return $str_html;\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected static function getLocaleAlternatives($locale, $addFallback = true)\n {\n $result = array();\n $localeInfo = static::explodeLocale($locale);\n if (!is_array($localeInfo)) {\n throw new Exception\\InvalidLocale($locale);\n }\n $language = $localeInfo['language'];\n $script = $localeInfo['script'];\n $territory = $localeInfo['territory'];\n $parentLocale = $localeInfo['parentLocale'];\n if ($territory === '') {\n $fullLocale = static::guessFullLocale($language, $script);\n if ($fullLocale !== '') {\n $localeInfo = static::explodeLocale($fullLocale);\n $language = $localeInfo['language'];\n $script = $localeInfo['script'];\n $territory = $localeInfo['territory'];\n $parentLocale = $localeInfo['parentLocale'];\n }\n }\n $territories = array();\n while ($territory !== '') {\n $territories[] = $territory;\n $territory = Territory::getParentTerritoryCode($territory);\n }\n if ($script !== '') {\n foreach ($territories as $territory) {\n $result[] = \"{$language}-{$script}-{$territory}\";\n }\n }\n if ($script !== '') {\n $result[] = \"{$language}-{$script}\";\n }\n foreach ($territories as $territory) {\n $result[] = \"{$language}-{$territory}\";\n if (\"{$language}-{$territory}\" === 'en-US') {\n $result[] = 'root';\n }\n }\n if ($parentLocale !== '') {\n $result = array_merge($result, static::getLocaleAlternatives($parentLocale, false));\n }\n $result[] = $language;\n if ($addFallback && ($locale !== static::$fallbackLocale)) {\n $result = array_merge($result, static::getLocaleAlternatives(static::$fallbackLocale, false));\n }\n for ($i = count($result) - 1; $i > 1; $i--) {\n for ($j = 0; $j < $i; $j++) {\n if ($result[$i] === $result[$j]) {\n array_splice($result, $i, 1);\n break;\n }\n }\n }\n if ($locale !== 'root') {\n $i = array_search('root', $result, true);\n if ($i !== false) {\n array_splice($result, $i, 1);\n $result[] = 'root';\n }\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function divide($y)\n {\n switch ( BigInteger_MODE ) {\n case BigInteger_MODE_GMP:\n $quotient = new BigInteger();\n $remainder = new BigInteger();\n\n list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);\n\n if (gmp_sign($remainder->value) < 0) {\n $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));\n }\n\n return array($this->_normalize($quotient), $this->_normalize($remainder));\n case BigInteger_MODE_BCMATH:\n $quotient = new BigInteger();\n $remainder = new BigInteger();\n\n $quotient->value = bcdiv($this->value, $y->value, 0);\n $remainder->value = bcmod($this->value, $y->value);\n\n if ($remainder->value[0] == '-') {\n $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);\n }\n\n return array($this->_normalize($quotient), $this->_normalize($remainder));\n }\n\n if (count($y->value) == 1) {\n list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);\n $quotient = new BigInteger();\n $remainder = new BigInteger();\n $quotient->value = $q;\n $remainder->value = array($r);\n $quotient->is_negative = $this->is_negative != $y->is_negative;\n return array($this->_normalize($quotient), $this->_normalize($remainder));\n }\n\n static $zero;\n if ( !isset($zero) ) {\n $zero = new BigInteger();\n }\n\n $x = $this->copy();\n $y = $y->copy();\n\n $x_sign = $x->is_negative;\n $y_sign = $y->is_negative;\n\n $x->is_negative = $y->is_negative = false;\n\n $diff = $x->compare($y);\n\n if ( !$diff ) {\n $temp = new BigInteger();\n $temp->value = array(1);\n $temp->is_negative = $x_sign != $y_sign;\n return array($this->_normalize($temp), $this->_normalize(new BigInteger()));\n }\n\n if ( $diff < 0 ) {\n // if $x is negative, \"add\" $y.\n if ( $x_sign ) {\n $x = $y->subtract($x);\n }\n return array($this->_normalize(new BigInteger()), $this->_normalize($x));\n }\n\n // normalize $x and $y as described in HAC 14.23 / 14.24\n $msb = $y->value[count($y->value) - 1];\n for ($shift = 0; !($msb & 0x2000000); ++$shift) {\n $msb <<= 1;\n }\n $x->_lshift($shift);\n $y->_lshift($shift);\n $y_value = &$y->value;\n\n $x_max = count($x->value) - 1;\n $y_max = count($y->value) - 1;\n\n $quotient = new BigInteger();\n $quotient_value = &$quotient->value;\n $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1);\n\n static $temp, $lhs, $rhs;\n if (!isset($temp)) {\n $temp = new BigInteger();\n $lhs = new BigInteger();\n $rhs = new BigInteger();\n }\n $temp_value = &$temp->value;\n $rhs_value = &$rhs->value;\n\n // $temp = $y << ($x_max - $y_max-1) in base 2**26\n $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value);\n\n while ( $x->compare($temp) >= 0 ) {\n // calculate the \"common residue\"\n ++$quotient_value[$x_max - $y_max];\n $x = $x->subtract($temp);\n $x_max = count($x->value) - 1;\n }\n\n for ($i = $x_max; $i >= $y_max + 1; --$i) {\n $x_value = &$x->value;\n $x_window = array(\n isset($x_value[$i]) ? $x_value[$i] : 0,\n isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0,\n isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0\n );\n $y_window = array(\n $y_value[$y_max],\n ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0\n );\n\n $q_index = $i - $y_max - 1;\n if ($x_window[0] == $y_window[0]) {\n $quotient_value[$q_index] = 0x3FFFFFF;\n } else {\n $quotient_value[$q_index] = (int) (\n ($x_window[0] * 0x4000000 + $x_window[1])\n /\n $y_window[0]\n );\n }\n\n $temp_value = array($y_window[1], $y_window[0]);\n\n $lhs->value = array($quotient_value[$q_index]);\n $lhs = $lhs->multiply($temp);\n\n $rhs_value = array($x_window[2], $x_window[1], $x_window[0]);\n\n while ( $lhs->compare($rhs) > 0 ) {\n --$quotient_value[$q_index];\n\n $lhs->value = array($quotient_value[$q_index]);\n $lhs = $lhs->multiply($temp);\n }\n\n $adjust = $this->_array_repeat(0, $q_index);\n $temp_value = array($quotient_value[$q_index]);\n $temp = $temp->multiply($y);\n $temp_value = &$temp->value;\n $temp_value = array_merge($adjust, $temp_value);\n\n $x = $x->subtract($temp);\n\n if ($x->compare($zero) < 0) {\n $temp_value = array_merge($adjust, $y_value);\n $x = $x->add($temp);\n\n --$quotient_value[$q_index];\n }\n\n $x_max = count($x_value) - 1;\n }\n\n // unnormalize the remainder\n $x->_rshift($shift);\n\n $quotient->is_negative = $x_sign != $y_sign;\n\n // calculate the \"common residue\", if appropriate\n if ( $x_sign ) {\n $y->_rshift($shift);\n $x = $y->subtract($x);\n }\n\n return array($this->_normalize($quotient), $this->_normalize($x));\n }", "smellKey": "S3776", "smellId": null, "repo": "xatziandreoy_hackazon", "language": "php"} {"function": "protected function migrateCollections(): void\n {\n foreach ($this->collections as $collection) {\n $id = $collection['$id'];\n\n Console::log(\"Migrating Collection \\\"{$id}\\\"\");\n\n $this->projectDB->setNamespace(\"_{$this->project->getInternalId()}\");\n\n switch ($id) {\n case 'builds':\n try {\n /**\n * Create 'size' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'size');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'size' from {$id}: {$th->getMessage()}\");\n }\n\n break;\n case 'files':\n try {\n /**\n * Update 'mimeType' attribute size (127->255)\n */\n $this->projectDB->updateAttribute($id, 'mimeType', Database::VAR_STRING, 255, true, false);\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'mimeType' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Create 'bucketInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'bucketInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'deploymentInternalId' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'builds':\n try {\n /**\n * Delete 'endTime' attribute (use startTime+duration if needed)\n */\n $this->projectDB->deleteAttribute($id, 'endTime');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'endTime' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Rename 'outputPath' to 'path'\n */\n $this->projectDB->renameAttribute($id, 'outputPath', 'path');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'path' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Create 'deploymentInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'deploymentInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'deploymentInternalId' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'stats':\n try {\n /**\n * Delete 'type' attribute\n */\n $this->projectDB->deleteAttribute($id, 'type');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'type' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'schedules':\n try {\n /**\n * Create 'resourceInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'resourceInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'resourceInternalId' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'functions':\n try {\n /**\n * Create 'deploymentInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'deploymentInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'deploymentInternalId' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Create 'scheduleInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'scheduleInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'scheduleInternalId' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Delete 'scheduleUpdatedAt' attribute\n */\n $this->projectDB->deleteAttribute($id, 'scheduleUpdatedAt');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'scheduleUpdatedAt' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'deployments':\n try {\n /**\n * Create 'resourceInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'resourceInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'resourceInternalId' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Create 'buildInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'buildInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'buildInternalId' from {$id}: {$th->getMessage()}\");\n }\n break;\n\n case 'executions':\n try {\n /**\n * Create 'functionInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'functionInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'functionInternalId' from {$id}: {$th->getMessage()}\");\n }\n\n try {\n /**\n * Create 'deploymentInternalId' attribute\n */\n $this->createAttributeFromCollection($this->projectDB, $id, 'deploymentInternalId');\n $this->projectDB->deleteCachedCollection($id);\n } catch (\\Throwable $th) {\n Console::warning(\"'deploymentInternalId' from {$id}: {$th->getMessage()}\");\n }\n break;\n default:\n break;\n }\n\n usleep(50000);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function testImportNetworkEquipmentMultiConnections()\n {\n $json = json_decode(file_get_contents(self::INV_FIXTURES . 'networkequipment_3.json'));\n\n $date_now = date('Y-m-d H:i:s');\n $_SESSION['glpi_currenttime'] = $date_now;\n $inventory = $this->doInventory($json);\n\n //check inventory metadata\n $metadata = $inventory->getMetadata();\n\n $this->assertCount(5, $metadata);\n $this->assertSame('HP-2530-48G-2020-12-31-11-28-51', $metadata['deviceid']);\n $this->assertSame('2.5', $metadata['version']);\n $this->assertSame('NetworkEquipment', $metadata['itemtype']);\n $this->assertNull($metadata['port']);\n $this->assertSame('netinventory', $metadata['action']);\n\n global $DB;\n //check created agent\n $agenttype = $DB->request(['FROM' => \\AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current();\n $this->assertSame('HP-2530-48G-2020-12-31-11-28-51', $inventory->getAgent()->fields['deviceid']);\n $this->assertSame('HP-2530-48G-2020-12-31-11-28-51', $inventory->getAgent()->fields['name']);\n $this->assertSame('NetworkEquipment', $inventory->getAgent()->fields['itemtype']);\n $this->assertSame($agenttype['id'], $inventory->getAgent()->fields['agenttypes_id']);\n\n //get model, manufacturer, ...\n $autoupdatesystems = $DB->request(['FROM' => \\AutoupdateSystem::getTable(), 'WHERE' => ['name' => 'GLPI Native Inventory']])->current();\n $this->assertIsArray($autoupdatesystems);\n $autoupdatesystems_id = $autoupdatesystems['id'];\n\n $cmodels = $DB->request(['FROM' => \\NetworkEquipmentModel::getTable(), 'WHERE' => ['name' => '2530-48G']])->current();\n $this->assertIsArray($cmodels);\n $models_id = $cmodels['id'];\n\n $ctypes = $DB->request(['FROM' => \\NetworkEquipmentType::getTable(), 'WHERE' => ['name' => 'Networking']])->current();\n $this->assertIsArray($ctypes);\n $types_id = $ctypes['id'];\n\n $cmanuf = $DB->request(['FROM' => \\Manufacturer::getTable(), 'WHERE' => ['name' => 'Hewlett-Packard']])->current();\n $this->assertIsArray($cmanuf);\n $manufacturers_id = $cmanuf['id'];\n $locations_id = 0;\n\n //check created equipments\n $expected_count = 1;\n $iterator = $DB->request([\n 'FROM' => \\NetworkEquipment::getTable(),\n 'WHERE' => ['is_dynamic' => 1]\n ]);\n $this->assertCount($expected_count, $iterator);\n\n $expected = [\n 'id' => null,\n 'entities_id' => 0,\n 'is_recursive' => 0,\n 'name' => 'HP-2530-48G',\n 'ram' => null,\n 'serial' => 'CN5BFP62CP',\n 'otherserial' => null,\n 'contact' => null,\n 'contact_num' => null,\n 'users_id_tech' => 0,\n 'date_mod' => null,\n 'comment' => null,\n 'locations_id' => $locations_id,\n 'networks_id' => 0,\n 'networkequipmenttypes_id' => $types_id,\n 'networkequipmentmodels_id' => $models_id,\n 'manufacturers_id' => $manufacturers_id,\n 'is_deleted' => 0,\n 'is_template' => 0,\n 'template_name' => null,\n 'users_id' => 0,\n 'states_id' => 0,\n 'ticket_tco' => '0.0000',\n 'is_dynamic' => 1,\n 'uuid' => null,\n 'date_creation' => null,\n 'autoupdatesystems_id' => $autoupdatesystems_id,\n 'sysdescr' => null,\n 'cpu' => 0,\n 'uptime' => '(78894038) 9 days, 3:09:00.38',\n 'last_inventory_update' => $date_now,\n 'snmpcredentials_id' => 0,\n ];\n\n foreach ($iterator as $row) {\n $equipments_id = $row['id'];\n $expected['id'] = $equipments_id;\n $equipment = new \\NetworkEquipment();\n $this->assertTrue($equipment->getFromDB($equipments_id));\n $expected['date_mod'] = $row['date_mod'];\n $expected['date_creation'] = $row['date_creation'];\n $this->assertIsArray($row);\n $this->assertSame($expected, $row);\n\n //check network ports\n $expected_count = 53;\n $ports_iterator = $DB->request([\n 'FROM' => \\NetworkPort::getTable(),\n 'WHERE' => [\n 'items_id' => $equipments_id,\n 'itemtype' => 'NetworkEquipment',\n ],\n ]);\n $this->assertSame(\n $expected_count,\n count($ports_iterator),\n sprintf(\n '%s ports found on %s, %s expected',\n count($ports_iterator),\n $row['name'],\n $expected_count\n )\n );\n\n $expecteds = [\n ($expected_count - 1) => [\n 'logical_number' => 0,\n 'name' => 'Management',\n 'instantiation_type' => 'NetworkPortAggregate',\n 'mac' => 'b0:5a:da:10:10:80',\n ],\n ];\n\n $ips = [\n 'Management' => [\n '192.168.63.30',\n ]\n ];\n\n $i = 0;\n $netport = new \\NetworkPort();\n $all_ports_ids = [];\n foreach ($ports_iterator as $port) {\n $ports_id = $port['id'];\n $all_ports_ids[] = $port['id'];\n $this->assertTrue($netport->getFromDB($ports_id));\n $instantiation = $netport->getInstantiation();\n if ($port['instantiation_type'] === null) {\n $this->assertFalse($instantiation);\n } else {\n $this->assertInstanceOf($port['instantiation_type'], $instantiation);\n }\n\n unset($port['id']);\n unset($port['date_creation']);\n unset($port['date_mod']);\n unset($port['comment']);\n\n if (isset($expecteds[$i])) {\n $expected = $expecteds[$i];\n $expected = $expected + [\n 'items_id' => $equipments_id,\n 'itemtype' => 'NetworkEquipment',\n 'entities_id' => 0,\n 'is_recursive' => 0,\n 'is_deleted' => 0,\n 'is_dynamic' => 1,\n 'ifmtu' => 0,\n 'ifspeed' => 0,\n 'ifinternalstatus' => null,\n 'ifconnectionstatus' => 0,\n 'iflastchange' => null,\n 'ifinbytes' => 0,\n 'ifinerrors' => 0,\n 'ifoutbytes' => 0,\n 'ifouterrors' => 0,\n 'ifstatus' => null,\n 'ifdescr' => null,\n 'ifalias' => null,\n 'portduplex' => null,\n 'trunk' => 0,\n 'lastup' => null\n ];\n\n $this->assertIsArray($port);\n $this->assertEquals($expected, $port);\n } else {\n $this->assertSame('NetworkEquipment', $port['itemtype']);\n $this->assertSame($equipments_id, $port['items_id']);\n $this->assertSame('NetworkPortEthernet', $port['instantiation_type'], print_r($port, true));\n $this->assertMatchesRegularExpression(\n '/^(?:(?:[0-9a-f]{2}[\\:]{1}){5}|(?:[0-9a-f]{2}[-]{1}){5}|(?:[0-9a-f]{2}){5})[0-9a-f]{2}$/i',\n $port['mac']\n );\n $this->assertSame(1, $port['is_dynamic']);\n }\n ++$i;\n\n //check for ips\n $ip_iterator = $DB->request([\n 'SELECT' => [\n \\IPAddress::getTable() . '.name',\n \\IPAddress::getTable() . '.version'\n ],\n 'FROM' => \\IPAddress::getTable(),\n 'INNER JOIN' => [\n \\NetworkName::getTable() => [\n 'ON' => [\n \\IPAddress::getTable() => 'items_id',\n \\NetworkName::getTable() => 'id', [\n 'AND' => [\\IPAddress::getTable() . '.itemtype' => \\NetworkName::getType()]\n ]\n ]\n ]\n ],\n 'WHERE' => [\n \\NetworkName::getTable() . '.itemtype' => \\NetworkPort::getType(),\n \\NetworkName::getTable() . '.items_id' => $ports_id\n ]\n ]);\n\n $this->assertCount(count($ips[$port['name']] ?? []), $ip_iterator);\n if (isset($ips[$port['name']])) {\n foreach ($ip_iterator as $ip) {\n $this->assertIsArray($ips[$port['name']]);\n $this->assertTrue(in_array($ip['name'], $ips[$port['name']]));\n }\n }\n }\n\n //check for components\n $components = [];\n $allcount = 0;\n foreach (\\Item_Devices::getItemAffinities('NetworkEquipment') as $link_type) {\n $link = getItemForItemtype($link_type);\n $dev_iterator = $DB->request($link->getTableGroupCriteria($equipment));\n $allcount += count($dev_iterator);\n $components[$link_type] = [];\n\n foreach ($dev_iterator as $row) {\n $lid = $row['id'];\n unset($row['id']);\n $components[$link_type][$lid] = $row;\n }\n }\n\n $expecteds = [\n 'Item_DeviceFirmware' => 1,\n 'Item_DeviceMemory' => 0,\n 'Item_DeviceHardDrive' => 0,\n 'Item_DeviceNetworkCard' => 0,\n 'Item_DevicePci' => 0,\n 'Item_DevicePowerSupply' => 0,\n 'Item_DeviceGeneric' => 0,\n 'Item_DeviceSimcard' => 0,\n ];\n\n foreach ($expecteds as $type => $count) {\n $this->assertSame(\n $count,\n count($components[$type]),\n sprintf(\n 'Expected %1$s %2$s, got %3$s of them',\n $count,\n $type,\n count($components[$type])\n )\n );\n }\n\n $expecteds = [\n 'Item_DeviceFirmware' => [\n [\n 'items_id' => $equipments_id,\n 'itemtype' => 'NetworkEquipment',\n 'devicefirmwares_id' => 104,\n 'is_deleted' => 0,\n 'is_dynamic' => 1,\n 'entities_id' => 0,\n 'is_recursive' => 0,\n 'serial' => null,\n 'otherserial' => null,\n 'locations_id' => 0,\n 'states_id' => 0,\n ]\n ],\n 'Item_DeviceMemory' => [],\n 'Item_DeviceHardDrive' => [],\n 'Item_DeviceNetworkCard' => [],\n 'Item_DevicePci' => [],\n 'Item_DevicePowerSupply' => [],\n 'Item_DeviceGeneric' => [],\n 'Item_DeviceSimcard' => [],\n ];\n\n foreach ($expecteds as $type => $expected) {\n $component = array_values($components[$type]);\n //hack to replace expected fkeys\n foreach ($expected as $i => &$row) {\n foreach (array_keys($row) as $key) {\n if (isForeignKeyField($key)) {\n $row[$key] = $component[$i][$key];\n }\n }\n }\n $this->assertIsArray($component);\n $this->assertSame($expected, $component);\n }\n\n //ports connections\n $connections = $DB->request([\n 'FROM' => \\NetworkPort_NetworkPort::getTable(),\n ]);\n\n $this->assertCount(63, $connections);\n }\n\n $connections = $DB->request(['FROM' => \\NetworkPort_NetworkPort::getTable()]);\n $this->assertCount(63, $connections);\n\n $unmanageds = $DB->request(['FROM' => \\Unmanaged::getTable()]);\n $this->assertCount(63, $unmanageds);\n\n $expecteds = [\n [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.52',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.156',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.40',\n ], [\n 'name' => 'Hewlett Packard',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.55',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.81',\n ], [\n 'name' => 'Xiamen Yeastar Information Technology Co., Ltd.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.115',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.76',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.97',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.167',\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.82',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.112',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.80',\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.157',\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.87',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.108',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.54',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.88',\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Samsung Electronics Co.,Ltd',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Hon Hai Precision Ind. Co.,Ltd.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Hon Hai Precision Ind. Co.,Ltd.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Samsung Electronics Co.,Ltd',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Ubiquiti Inc',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Hub',\n 'accepted' => 0,\n 'hub' => 1,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Intel Corporate',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'SAMSUNG ELECTRO-MECHANICS(THAILAND)',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Ubiquiti Inc',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Hub',\n 'accepted' => 0,\n 'hub' => 1,\n 'ip' => null,\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'ASUSTek COMPUTER INC.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.146',\n ], [\n 'name' => 'G-PRO COMPUTER',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.140',\n ], [\n 'name' => 'KYOCERA Display Corporation',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Routerboard.com',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Routerboard.com',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Ubiquiti Inc',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Apple, Inc.',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Hub',\n 'accepted' => 0,\n 'hub' => 1,\n 'ip' => null,\n ], [\n 'name' => 'Microsoft Corporation',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => null,\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.51',\n ], [\n 'name' => 'Cisco IP Phone SPA303',\n 'accepted' => 0,\n 'hub' => 0,\n 'ip' => '192.168.63.128',\n ]\n ];\n\n $this->assertCount($unmanageds->count(), $expecteds);\n\n $i = 0;\n foreach ($unmanageds as $unmanaged) {\n foreach ($expecteds[$i] as $key => $value) {\n $this->assertEquals($value, $unmanaged[$key]);\n }\n ++$i;\n }\n\n //check matchedlogs\n $mlogs = new \\RuleMatchedLog();\n $found = $mlogs->find();\n $this->assertCount(61, $found);\n\n $mrules_criteria = [\n 'FROM' => \\RuleMatchedLog::getTable(),\n 'LEFT JOIN' => [\n \\Rule::getTable() => [\n 'ON' => [\n \\RuleMatchedLog::getTable() => 'rules_id',\n \\Rule::getTable() => 'id'\n ]\n ]\n ],\n 'WHERE' => []\n ];\n\n $neteq_criteria = $mrules_criteria;\n $neteq_criteria['WHERE'][] = ['itemtype' => \\NetworkEquipment::getType()];\n $iterator = $DB->request($neteq_criteria);\n $this->assertCount(1, $iterator);\n foreach ($iterator as $neteq) {\n $this->assertSame('NetworkEquipment import (by serial)', $neteq['name']);\n $this->assertSame($equipments_id, $neteq['items_id']);\n $this->assertSame(\\Glpi\\Inventory\\Request::INVENT_QUERY, $neteq['method']);\n }\n\n $unmanaged_criteria = $mrules_criteria;\n $unmanaged_criteria['WHERE'][] = ['itemtype' => \\Unmanaged::getType()];\n $iterator = $DB->request($unmanaged_criteria);\n $this->assertCount(60, $iterator);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function saveListItem($list_id, $item_id) {\n global $thisstaff;\n\n $errors = array();\n\n if (!$thisstaff)\n Http::response(403, 'Login required');\n\n $list = DynamicList::lookup($list_id);\n if (!$list)\n Http::response(404, 'No such list item');\n\n $list = CustomListHandler::forList($list);\n if (!$list || !($item = $list->getItem( (int) $item_id)))\n Http::response(404, 'No such list item');\n\n $item_form = $list->getListItemBasicForm($_POST, $item);\n\n if ($valid = $item_form->isValid()) {\n if ($_item = DynamicListItem::lookup(array(\n 'list_id' => $list->getId(), 'value'=>$item->getValue()))\n ) {\n if ($_item && $_item->id != $item->id)\n $item_form->getField('value')->addError(\n __('Value already in use'));\n }\n if ($item_form->isValid()) {\n // Update basic information\n $basic = $item_form->getClean();\n $item->update([\n 'name' => $basic['name'],\n 'value' => $basic['value'],\n 'abbrev' => $basic['extra'],\n ], $errors);\n }\n }\n\n // Context\n $action = \"#list/{$list->getId()}/item/{$item->getId()}/update\";\n $icon = ($list->get('sort_mode') == 'SortCol')\n ? '<i class=\"icon-sort\"></i>&nbsp;' : '';\n\n if (!$valid || !$item->setConfiguration($_POST)) {\n include STAFFINC_DIR . 'templates/list-item-properties.tmpl.php';\n return;\n }\n else {\n $item->save();\n }\n\n Http::response(201, $this->encode(array(\n 'id' => $item->getId(),\n 'row' => $this->_renderListItem($item, $list),\n 'success' => true,\n )));\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function registerMounts(IUser $user, array $mounts, ?array $mountProviderClasses = null) {\n\t\t$this->eventLogger->start('fs:setup:user:register', 'Registering mounts for user');\n\t\t/** @var array<string, ICachedMountInfo> $newMounts */\n\t\t$newMounts = [];\n\t\tforeach ($mounts as $mount) {\n\t\t\t// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)\n\t\t\tif ($mount->getStorageRootId() !== -1) {\n\t\t\t\t$mountInfo = new LazyStorageMountInfo($user, $mount);\n\t\t\t\t$newMounts[$mountInfo->getKey()] = $mountInfo;\n\t\t\t}\n\t\t}\n\n\t\t$cachedMounts = $this->getMountsForUser($user);\n\t\tif (is_array($mountProviderClasses)) {\n\t\t\t$cachedMounts = array_filter($cachedMounts, function (ICachedMountInfo $mountInfo) use ($mountProviderClasses, $newMounts) {\n\t\t\t\t// for existing mounts that didn't have a mount provider set\n\t\t\t\t// we still want the ones that map to new mounts\n\t\t\t\tif ($mountInfo->getMountProvider() === '' && isset($newMounts[$mountInfo->getKey()])) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn in_array($mountInfo->getMountProvider(), $mountProviderClasses);\n\t\t\t});\n\t\t}\n\n\t\t$addedMounts = [];\n\t\t$removedMounts = [];\n\n\t\tforeach ($newMounts as $mountKey => $newMount) {\n\t\t\tif (!isset($cachedMounts[$mountKey])) {\n\t\t\t\t$addedMounts[] = $newMount;\n\t\t\t}\n\t\t}\n\n\t\tforeach ($cachedMounts as $mountKey => $cachedMount) {\n\t\t\tif (!isset($newMounts[$mountKey])) {\n\t\t\t\t$removedMounts[] = $cachedMount;\n\t\t\t}\n\t\t}\n\n\t\t$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);\n\n\t\tif ($addedMounts || $removedMounts || $changedMounts) {\n\t\t\t$this->connection->beginTransaction();\n\t\t\t$userUID = $user->getUID();\n\t\t\ttry {\n\t\t\t\tforeach ($addedMounts as $mount) {\n\t\t\t\t\t$this->addToCache($mount);\n\t\t\t\t\t/** @psalm-suppress InvalidArgument */\n\t\t\t\t\t$this->mountsForUsers[$userUID][$mount->getKey()] = $mount;\n\t\t\t\t}\n\t\t\t\tforeach ($removedMounts as $mount) {\n\t\t\t\t\t$this->removeFromCache($mount);\n\t\t\t\t\tunset($this->mountsForUsers[$userUID][$mount->getKey()]);\n\t\t\t\t}\n\t\t\t\tforeach ($changedMounts as $mount) {\n\t\t\t\t\t$this->updateCachedMount($mount);\n\t\t\t\t\t/** @psalm-suppress InvalidArgument */\n\t\t\t\t\t$this->mountsForUsers[$userUID][$mount->getKey()] = $mount;\n\t\t\t\t}\n\t\t\t\t$this->connection->commit();\n\t\t\t} catch (\\Throwable $e) {\n\t\t\t\t$this->connection->rollBack();\n\t\t\t\tthrow $e;\n\t\t\t}\n\t\t}\n\t\t$this->eventLogger->end('fs:setup:user:register');\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function arrayTimesEquals() {\n\t\tif (func_num_args() > 0) {\n\t\t\t$args = func_get_args();\n\t\t\t$match = implode(\",\", array_map('gettype', $args));\n\n\t\t\tswitch($match) {\n\t\t\t\tcase 'object':\n\t\t\t\t\t\tif ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); }\n\t\t\t\t\t\tbreak;\n\t\t\t\tcase 'array':\n\t\t\t\t\t\t$M = new PHPExcel_Shared_JAMA_Matrix($args[0]);\n\t\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException);\n\t\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$this->checkMatrixDimensions($M);\n\t\t\tfor($i = 0; $i < $this->m; ++$i) {\n\t\t\t\tfor($j = 0; $j < $this->n; ++$j) {\n\t\t\t\t\t$validValues = True;\n\t\t\t\t\t$value = $M->get($i, $j);\n\t\t\t\t\tif ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) {\n\t\t\t\t\t\t$this->A[$i][$j] = trim($this->A[$i][$j],'\"');\n\t\t\t\t\t\t$validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]);\n\t\t\t\t\t}\n\t\t\t\t\tif ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) {\n\t\t\t\t\t\t$value = trim($value,'\"');\n\t\t\t\t\t\t$validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value);\n\t\t\t\t\t}\n\t\t\t\t\tif ($validValues) {\n\t\t\t\t\t\t$this->A[$i][$j] *= $value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn $this;\n\t\t} else {\n\t\t\tthrow new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException);\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->type)) {\n $json['type'] = $this->type;\n }\n if (isset($this->subType)) {\n $json['subType'] = $this->subType;\n }\n if (isset($this->use)) {\n $json['use'] = $this->use;\n }\n if (isset($this->patient)) {\n $json['patient'] = $this->patient;\n }\n if (isset($this->billablePeriod)) {\n $json['billablePeriod'] = $this->billablePeriod;\n }\n if (isset($this->created)) {\n $json['created'] = $this->created;\n }\n if (isset($this->enterer)) {\n $json['enterer'] = $this->enterer;\n }\n if (isset($this->insurer)) {\n $json['insurer'] = $this->insurer;\n }\n if (isset($this->provider)) {\n $json['provider'] = $this->provider;\n }\n if (isset($this->priority)) {\n $json['priority'] = $this->priority;\n }\n if (isset($this->fundsReserveRequested)) {\n $json['fundsReserveRequested'] = $this->fundsReserveRequested;\n }\n if (isset($this->fundsReserve)) {\n $json['fundsReserve'] = $this->fundsReserve;\n }\n if (0 < count($this->related)) {\n $json['related'] = [];\n foreach ($this->related as $related) {\n $json['related'][] = $related;\n }\n }\n if (isset($this->prescription)) {\n $json['prescription'] = $this->prescription;\n }\n if (isset($this->originalPrescription)) {\n $json['originalPrescription'] = $this->originalPrescription;\n }\n if (isset($this->payee)) {\n $json['payee'] = $this->payee;\n }\n if (isset($this->referral)) {\n $json['referral'] = $this->referral;\n }\n if (isset($this->facility)) {\n $json['facility'] = $this->facility;\n }\n if (isset($this->claim)) {\n $json['claim'] = $this->claim;\n }\n if (isset($this->claimResponse)) {\n $json['claimResponse'] = $this->claimResponse;\n }\n if (isset($this->outcome)) {\n $json['outcome'] = $this->outcome;\n }\n if (isset($this->disposition)) {\n $json['disposition'] = $this->disposition;\n }\n if (0 < count($this->preAuthRef)) {\n $json['preAuthRef'] = [];\n foreach ($this->preAuthRef as $preAuthRef) {\n $json['preAuthRef'][] = $preAuthRef;\n }\n }\n if (0 < count($this->preAuthRefPeriod)) {\n $json['preAuthRefPeriod'] = [];\n foreach ($this->preAuthRefPeriod as $preAuthRefPeriod) {\n $json['preAuthRefPeriod'][] = $preAuthRefPeriod;\n }\n }\n if (0 < count($this->careTeam)) {\n $json['careTeam'] = [];\n foreach ($this->careTeam as $careTeam) {\n $json['careTeam'][] = $careTeam;\n }\n }\n if (0 < count($this->supportingInfo)) {\n $json['supportingInfo'] = [];\n foreach ($this->supportingInfo as $supportingInfo) {\n $json['supportingInfo'][] = $supportingInfo;\n }\n }\n if (0 < count($this->diagnosis)) {\n $json['diagnosis'] = [];\n foreach ($this->diagnosis as $diagnosis) {\n $json['diagnosis'][] = $diagnosis;\n }\n }\n if (0 < count($this->procedure)) {\n $json['procedure'] = [];\n foreach ($this->procedure as $procedure) {\n $json['procedure'][] = $procedure;\n }\n }\n if (isset($this->precedence)) {\n $json['precedence'] = $this->precedence;\n }\n if (0 < count($this->insurance)) {\n $json['insurance'] = [];\n foreach ($this->insurance as $insurance) {\n $json['insurance'][] = $insurance;\n }\n }\n if (isset($this->accident)) {\n $json['accident'] = $this->accident;\n }\n if (0 < count($this->item)) {\n $json['item'] = [];\n foreach ($this->item as $item) {\n $json['item'][] = $item;\n }\n }\n if (0 < count($this->addItem)) {\n $json['addItem'] = [];\n foreach ($this->addItem as $addItem) {\n $json['addItem'][] = $addItem;\n }\n }\n if (0 < count($this->adjudication)) {\n $json['adjudication'] = [];\n foreach ($this->adjudication as $adjudication) {\n $json['adjudication'][] = $adjudication;\n }\n }\n if (0 < count($this->total)) {\n $json['total'] = [];\n foreach ($this->total as $total) {\n $json['total'][] = $total;\n }\n }\n if (isset($this->payment)) {\n $json['payment'] = $this->payment;\n }\n if (isset($this->formCode)) {\n $json['formCode'] = $this->formCode;\n }\n if (isset($this->form)) {\n $json['form'] = $this->form;\n }\n if (0 < count($this->processNote)) {\n $json['processNote'] = [];\n foreach ($this->processNote as $processNote) {\n $json['processNote'][] = $processNote;\n }\n }\n if (isset($this->benefitPeriod)) {\n $json['benefitPeriod'] = $this->benefitPeriod;\n }\n if (0 < count($this->benefitBalance)) {\n $json['benefitBalance'] = [];\n foreach ($this->benefitBalance as $benefitBalance) {\n $json['benefitBalance'][] = $benefitBalance;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<DetectedIssue xmlns=\"http://hl7.org/fhir\"></DetectedIssue>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->status)) {\n $this->status->xmlSerialize(true, $sxe->addChild('status'));\n }\n if (isset($this->code)) {\n $this->code->xmlSerialize(true, $sxe->addChild('code'));\n }\n if (isset($this->severity)) {\n $this->severity->xmlSerialize(true, $sxe->addChild('severity'));\n }\n if (isset($this->patient)) {\n $this->patient->xmlSerialize(true, $sxe->addChild('patient'));\n }\n if (isset($this->identifiedDateTime)) {\n $this->identifiedDateTime->xmlSerialize(true, $sxe->addChild('identifiedDateTime'));\n }\n if (isset($this->identifiedPeriod)) {\n $this->identifiedPeriod->xmlSerialize(true, $sxe->addChild('identifiedPeriod'));\n }\n if (isset($this->author)) {\n $this->author->xmlSerialize(true, $sxe->addChild('author'));\n }\n if (0 < count($this->implicated)) {\n foreach ($this->implicated as $implicated) {\n $implicated->xmlSerialize(true, $sxe->addChild('implicated'));\n }\n }\n if (0 < count($this->evidence)) {\n foreach ($this->evidence as $evidence) {\n $evidence->xmlSerialize(true, $sxe->addChild('evidence'));\n }\n }\n if (isset($this->detail)) {\n $this->detail->xmlSerialize(true, $sxe->addChild('detail'));\n }\n if (isset($this->reference)) {\n $this->reference->xmlSerialize(true, $sxe->addChild('reference'));\n }\n if (0 < count($this->mitigation)) {\n foreach ($this->mitigation as $mitigation) {\n $mitigation->xmlSerialize(true, $sxe->addChild('mitigation'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (0 < count($this->basedOn)) {\n $json['basedOn'] = [];\n foreach ($this->basedOn as $basedOn) {\n $json['basedOn'][] = $basedOn;\n }\n }\n if (0 < count($this->partOf)) {\n $json['partOf'] = [];\n foreach ($this->partOf as $partOf) {\n $json['partOf'][] = $partOf;\n }\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (0 < count($this->category)) {\n $json['category'] = [];\n foreach ($this->category as $category) {\n $json['category'][] = $category;\n }\n }\n if (isset($this->code)) {\n $json['code'] = $this->code;\n }\n if (isset($this->subject)) {\n $json['subject'] = $this->subject;\n }\n if (0 < count($this->focus)) {\n $json['focus'] = [];\n foreach ($this->focus as $focus) {\n $json['focus'][] = $focus;\n }\n }\n if (isset($this->encounter)) {\n $json['encounter'] = $this->encounter;\n }\n if (isset($this->effectiveDateTime)) {\n $json['effectiveDateTime'] = $this->effectiveDateTime;\n }\n if (isset($this->effectivePeriod)) {\n $json['effectivePeriod'] = $this->effectivePeriod;\n }\n if (isset($this->effectiveTiming)) {\n $json['effectiveTiming'] = $this->effectiveTiming;\n }\n if (isset($this->effectiveInstant)) {\n $json['effectiveInstant'] = $this->effectiveInstant;\n }\n if (isset($this->issued)) {\n $json['issued'] = $this->issued;\n }\n if (0 < count($this->performer)) {\n $json['performer'] = [];\n foreach ($this->performer as $performer) {\n $json['performer'][] = $performer;\n }\n }\n if (isset($this->valueQuantity)) {\n $json['valueQuantity'] = $this->valueQuantity;\n }\n if (isset($this->valueCodeableConcept)) {\n $json['valueCodeableConcept'] = $this->valueCodeableConcept;\n }\n if (isset($this->valueString)) {\n $json['valueString'] = $this->valueString;\n }\n if (isset($this->valueBoolean)) {\n $json['valueBoolean'] = $this->valueBoolean;\n }\n if (isset($this->valueInteger)) {\n $json['valueInteger'] = $this->valueInteger;\n }\n if (isset($this->valueRange)) {\n $json['valueRange'] = $this->valueRange;\n }\n if (isset($this->valueRatio)) {\n $json['valueRatio'] = $this->valueRatio;\n }\n if (isset($this->valueSampledData)) {\n $json['valueSampledData'] = $this->valueSampledData;\n }\n if (isset($this->valueTime)) {\n $json['valueTime'] = $this->valueTime;\n }\n if (isset($this->valueDateTime)) {\n $json['valueDateTime'] = $this->valueDateTime;\n }\n if (isset($this->valuePeriod)) {\n $json['valuePeriod'] = $this->valuePeriod;\n }\n if (isset($this->dataAbsentReason)) {\n $json['dataAbsentReason'] = $this->dataAbsentReason;\n }\n if (0 < count($this->interpretation)) {\n $json['interpretation'] = [];\n foreach ($this->interpretation as $interpretation) {\n $json['interpretation'][] = $interpretation;\n }\n }\n if (0 < count($this->note)) {\n $json['note'] = [];\n foreach ($this->note as $note) {\n $json['note'][] = $note;\n }\n }\n if (isset($this->bodySite)) {\n $json['bodySite'] = $this->bodySite;\n }\n if (isset($this->method)) {\n $json['method'] = $this->method;\n }\n if (isset($this->specimen)) {\n $json['specimen'] = $this->specimen;\n }\n if (isset($this->device)) {\n $json['device'] = $this->device;\n }\n if (0 < count($this->referenceRange)) {\n $json['referenceRange'] = [];\n foreach ($this->referenceRange as $referenceRange) {\n $json['referenceRange'][] = $referenceRange;\n }\n }\n if (0 < count($this->hasMember)) {\n $json['hasMember'] = [];\n foreach ($this->hasMember as $hasMember) {\n $json['hasMember'][] = $hasMember;\n }\n }\n if (0 < count($this->derivedFrom)) {\n $json['derivedFrom'] = [];\n foreach ($this->derivedFrom as $derivedFrom) {\n $json['derivedFrom'][] = $derivedFrom;\n }\n }\n if (0 < count($this->component)) {\n $json['component'] = [];\n foreach ($this->component as $component) {\n $json['component'][] = $component;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['party'])) {\n if (is_array($data['party'])) {\n foreach ($data['party'] as $d) {\n $this->addParty($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"party\" must be array of objects or null, ' . gettype($data['party']) . ' seen.');\n }\n }\n if (isset($data['topic'])) {\n $this->setTopic($data['topic']);\n }\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['decision'])) {\n $this->setDecision($data['decision']);\n }\n if (isset($data['decisionMode'])) {\n if (is_array($data['decisionMode'])) {\n foreach ($data['decisionMode'] as $d) {\n $this->addDecisionMode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"decisionMode\" must be array of objects or null, ' . gettype($data['decisionMode']) . ' seen.');\n }\n }\n if (isset($data['answer'])) {\n if (is_array($data['answer'])) {\n foreach ($data['answer'] as $d) {\n $this->addAnswer($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"answer\" must be array of objects or null, ' . gettype($data['answer']) . ' seen.');\n }\n }\n if (isset($data['text'])) {\n $this->setText($data['text']);\n }\n if (isset($data['linkId'])) {\n if (is_array($data['linkId'])) {\n foreach ($data['linkId'] as $d) {\n $this->addLinkId($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"linkId\" must be array of objects or null, ' . gettype($data['linkId']) . ' seen.');\n }\n }\n if (isset($data['securityLabelNumber'])) {\n if (is_array($data['securityLabelNumber'])) {\n foreach ($data['securityLabelNumber'] as $d) {\n $this->addSecurityLabelNumber($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"securityLabelNumber\" must be array of objects or null, ' . gettype($data['securityLabelNumber']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['param'])) {\n if (is_array($data['param'])) {\n foreach ($data['param'] as $d) {\n $this->addParam($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"param\" must be array of objects or null, ' . gettype($data['param']) . ' seen.');\n }\n }\n if (isset($data['documentation'])) {\n $this->setDocumentation($data['documentation']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "private static function validateEnumerations($query, $imp_session, $fields_checked, $dt_id, $field_idx, $recStruc, $recordType,\n $message, $short_message, $progress_session_id){\n\n $mysqli = self::$mysqli;\n\n $dt_def = $recStruc[$recordType]['dtFields'][$dt_id];\n\n $idx_fieldtype = $recStruc['dtFieldNamesToIndex']['dty_Type'];\n $idx_term_tree = $recStruc['dtFieldNamesToIndex']['rst_FilteredJsonTermIDTree'];\n $idx_term_nosel = $recStruc['dtFieldNamesToIndex']['dty_TermIDTreeNonSelectableIDs'];\n\n $dt_type = $dt_def[$idx_fieldtype];//for domain\n\n $res = $mysqli->query( $query );\n\n if($res){\n\n $cnt = 0;\n $tot_count = $imp_session['reccount']>0?$imp_session['reccount']:1000;\n if($tot_count>4000){\n mysql__update_progress(null, $progress_session_id, false, '0,'.$tot_count.',validation of enumeration fields');\n }\n\n $wrong_records = array();\n $wrong_values = array();\n\n $cc = 0;\n\n while ($row = $res->fetch_row()){\n\n $is_error = false;\n $newvalue = array();\n $values = self::getMultiValues($row[$field_idx], $imp_session['csv_enclosure'], $imp_session['csv_mvsep']);\n foreach($values as $idx=>$r_value){\n $r_value2 = trim_lower_accent($r_value);\n\n if($r_value2!='' && $r_value2!='null'){\n\n $is_termid = false;\n if(ctype_digit($r_value2)){ //value is numeric try to compare with trm_ID\n $is_termid = VerifyValue::isValidTerm( $dt_def[$idx_term_tree], $dt_def[$idx_term_nosel], $r_value2, $dt_id);\n }\n\n if($is_termid){\n $term_id = $r_value;\n }else{\n //strip accents on both sides\n $term_id = VerifyValue::isValidTermLabel($dt_def[$idx_term_tree], $dt_def[$idx_term_nosel], $r_value2, $dt_id, true );\n\n if(!$term_id){\n $term_id = VerifyValue::isValidTermCode($dt_def[$idx_term_tree], $dt_def[$idx_term_nosel], $r_value2, $dt_id );\n }\n }\n\n if (!$term_id)\n {//not found\n $is_error = true;\n array_push($newvalue, \"<span style=\\\"color:red\\\">$r_value</span>\");\n if(array_search($r_value, $wrong_values)===false){\n array_push($wrong_values, $r_value);\n }\n }else{\n array_push($newvalue, $r_value);\n }\n }\n }\n\n if($is_error){\n $row[$field_idx] = implode($imp_session['csv_mvsep'], $newvalue);\n array_push($wrong_records, $row);\n }\n\n $cnt++;\n if($tot_count>4000 && $cnt%2000==0){\n mysql__update_progress(null, $progress_session_id, false, $cnt.','.$tot_count.','.MSG_VALIDATION_2);\n\n }\n }\n $res->close();\n $cnt_error = count($wrong_records);\n if($cnt_error>0){\n $error = array();\n $error[\"count_error\"] = $cnt_error;\n $error[\"recs_error\"] = array_slice($wrong_records,0,1000);\n $error[\"values_error\"] = array_slice($wrong_values,0,1000);\n $error[\"field_checked\"] = $fields_checked;\n $error[\"err_message\"] = $message;\n $error[\"short_message\"] = $short_message;\n\n $imp_session['validation']['count_error'] = $imp_session['validation']['count_error']+$cnt_error;\n array_push($imp_session['validation']['error'], $error);\n\n return $imp_session;\n }\n\n }else{\n return ERR_VALIDATION_QUERY.$query;\n }\n return null;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function updateResults($params)\n {\n $sampleIds = $params['sampleId'];\n\n foreach ($sampleIds as $key => $sampleId) {\n $res = $this->fetchRow(\"shipment_map_id = \" . $params['smid'] . \" and sample_id = \" . $sampleId);\n $authNameSpace = new Zend_Session_Namespace('datamanagers');\n $data = [\n 'shipment_map_id' => $params['smid'],\n 'sample_id' => $sampleId,\n 'response_attributes' => (isset($params['cepheidMTBXDRTest'][$sampleId]) && !empty($params['cepheidMTBXDRTest'][$sampleId]) && $params['mtbcDetected'][$key] == \"detected\") ? json_encode($params['cepheidMTBXDRTest'][$sampleId]) : null,\n 'assay_id' => $params['assayName'],\n 'mtb_detected' => (isset($params['mtbcDetected'][$key]) && !empty($params['mtbcDetected'][$key])) ? $params['mtbcDetected'][$key] : null,\n 'rif_resistance' => (isset($params['rifResistance'][$key]) && !empty($params['rifResistance'][$key])) ? $params['rifResistance'][$key] : null,\n 'probe_d' => isset($params['probeD'][$key]) ? $params['probeD'][$key] : null,\n 'probe_c' => isset($params['probeC'][$key]) ? $params['probeC'][$key] : null,\n 'probe_e' => isset($params['probeE'][$key]) ? $params['probeE'][$key] : null,\n 'probe_b' => isset($params['probeB'][$key]) ? $params['probeB'][$key] : null,\n // 'spc' => isset($params['spc'][$key]) ? $params['spc'][$key] : null,\n 'probe_a' => isset($params['probeA'][$key]) ? $params['probeA'][$key] : null,\n 'is1081_is6110' => isset($params['ISI'][$key]) ? $params['ISI'][$key] : null,\n 'rpo_b1' => isset($params['rpoB1'][$key]) ? $params['rpoB1'][$key] : null,\n 'rpo_b2' => isset($params['rpoB2'][$key]) ? $params['rpoB2'][$key] : null,\n 'rpo_b3' => isset($params['rpoB3'][$key]) ? $params['rpoB3'][$key] : null,\n 'rpo_b4' => isset($params['rpoB4'][$key]) ? $params['rpoB4'][$key] : null,\n 'instrument_serial_no' => isset($params['instrumentSerialNo'][$key]) && !empty($params['instrumentSerialNo'][$key]) ? $params['instrumentSerialNo'][$key] : null,\n 'gene_xpert_module_no' => isset($params['geneXpertModuleNo'][$key]) && !empty($params['geneXpertModuleNo'][$key]) ? $params['geneXpertModuleNo'][$key] : null,\n 'test_date' => Pt_Commons_General::isoDateFormat($params['dateTested'][$key] ?? ''),\n 'tester_name' => isset($params['testerName'][$key]) && !empty($params['testerName'][$key]) ? $params['testerName'][$key] : null,\n 'error_code' => isset($params['errCode'][$key]) && !empty($params['errCode'][$key]) ? $params['errCode'][$key] : null\n ];\n /* Check if assay xpert or ultra */\n $db = Zend_Db_Table_Abstract::getDefaultAdapter();\n $sQuery = $db->select()->from('r_tb_assay', 'short_name')->where(\"id = \" . $params['assayName']);\n $assayName = $db->fetchRow($sQuery);\n if (isset($assayName['short_name']) && !empty($assayName['short_name']) && $assayName['short_name'] == 'xpert-mtb-rif') {\n $data['spc_xpert'] = $params['spc'][$key] ?? null;\n } elseif (isset($assayName['short_name']) && !empty($assayName['short_name']) && $assayName['short_name'] == 'xpert-mtb-rif-ultra') {\n $data['spc_xpert_ultra'] = $params['spc'][$key] ?? null;\n }\n if (empty($res)) {\n $data['created_by'] = $authNameSpace->dm_id;\n $data['created_on'] = new Zend_Db_Expr(self::NOW);\n $this->insert($data);\n } else {\n $data['updated_by'] = $authNameSpace->dm_id;\n $data['updated_on'] = new Zend_Db_Expr(self::NOW);\n $this->update($data, \"shipment_map_id = \" . $params['smid'] . \" and sample_id = \" . $sampleId);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_ept", "language": "php"} {"function": "public static function WORKDAY($startDate, $endDays)\n {\n // Retrieve the mandatory start date and days that are referenced in the function definition\n $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);\n $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays);\n // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days\n $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());\n array_shift($dateArgs);\n array_shift($dateArgs);\n\n if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) {\n return PHPExcel_Calculation_Functions::VALUE();\n }\n $startDate = (float) floor($startDate);\n $endDays = (int) floor($endDays);\n // If endDays is 0, we always return startDate\n if ($endDays == 0) {\n return $startDate;\n }\n\n $decrementing = ($endDays < 0) ? true : false;\n\n // Adjust the start date if it falls over a weekend\n\n $startDoW = self::DAYOFWEEK($startDate, 3);\n if (self::DAYOFWEEK($startDate, 3) >= 5) {\n $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;\n ($decrementing) ? $endDays++ : $endDays--;\n }\n\n // Add endDays\n $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);\n\n // Adjust the calculated end date if it falls over a weekend\n $endDoW = self::DAYOFWEEK($endDate, 3);\n if ($endDoW >= 5) {\n $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;\n }\n\n // Test any extra holiday parameters\n if (!empty($dateArgs)) {\n $holidayCountedArray = $holidayDates = array();\n foreach ($dateArgs as $holidayDate) {\n if (($holidayDate !== null) && (trim($holidayDate) > '')) {\n if (is_string($holidayDate = self::getDateValue($holidayDate))) {\n return PHPExcel_Calculation_Functions::VALUE();\n }\n if (self::DAYOFWEEK($holidayDate, 3) < 5) {\n $holidayDates[] = $holidayDate;\n }\n }\n }\n if ($decrementing) {\n rsort($holidayDates, SORT_NUMERIC);\n } else {\n sort($holidayDates, SORT_NUMERIC);\n }\n foreach ($holidayDates as $holidayDate) {\n if ($decrementing) {\n if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {\n if (!in_array($holidayDate, $holidayCountedArray)) {\n --$endDate;\n $holidayCountedArray[] = $holidayDate;\n }\n }\n } else {\n if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {\n if (!in_array($holidayDate, $holidayCountedArray)) {\n ++$endDate;\n $holidayCountedArray[] = $holidayDate;\n }\n }\n }\n // Adjust the calculated end date if it falls over a weekend\n $endDoW = self::DAYOFWEEK($endDate, 3);\n if ($endDoW >= 5) {\n $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;\n }\n }\n }\n\n switch (PHPExcel_Calculation_Functions::getReturnDateType()) {\n case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:\n return (float) $endDate;\n case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:\n return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);\n case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:\n return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "private function loadWarnsHtml($limit, $visibleWarningsCount)\n {\n $warns = [];\n\n //Verifica a exist\u00eancia de turmas na escola\n $listSchoolClassrooms = Classroom::model()->findallByAttributes([\"school_inep_fk\" => yii::app()->user->school, \"school_year\" => Yii::app()->user->year]);\n if (count($listSchoolClassrooms) == 0) {\n $schoolModel = SchoolIdentification::model()->findByAttributes(['inep_id' => yii::app()->user->school]);\n $warning = 'Escola <b>' . $schoolModel->name . '</b> est\u00e1 sem turmas cadastradas.';\n\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/turmas.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n\n array_push($warns, $htmlpart);\n } else {\n foreach ($listSchoolClassrooms as $classroom) {\n //Se houver turma, verificar se existe etapa vinculada \u00e0 turma\n $stage = $classroom->edcensoStageVsModalityFk;\n if ($stage == null) {\n $warning = 'Turma <b>' . $classroom->name . '</b> est\u00e1 sem etapa.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/plano_de_aula.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n } else {\n //Se houver etapa, verificar matriz curricular\n $listCurricularMatrixs = $stage->curricularMatrixes;\n if (count($listCurricularMatrixs) == 0) {\n $warning = 'Etapa <b>' . $stage->name . '</b> da turma <b>' . $classroom->name . '</b> est\u00e1 sem matriz curricular.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/matriz_curricular.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n //Se houver etapa, verificar se existe estrutura de notas\n $listGradeUnities = $stage->gradeUnities;\n if (count($listGradeUnities) == 0) {\n $warning = 'Etapa <b>' . $stage->name . '</b> da turma <b>' . $classroom->name . '</b> est\u00e1 sem estrutura de notas.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange; color:black;\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/notas.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n }\n\n //Se houver turma, verificar se existe calendario vinculado a ela\n $calendar = $classroom->calendarFk;\n if ($calendar == null) {\n $warning = 'Turma <b>' . $classroom->name . '</b> n\u00e3o possui calend\u00e1rio vinculado.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/calendario.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n //Se houver turma, verificar se existe quadro de hor\u00e1rios\n $listSchedules = $classroom->schedules;\n if (count($listSchedules) == 0) {\n $warning = 'Turma <b>' . $classroom->name . '</b> est\u00e1 sem quadro de hor\u00e1rios.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/quadro_de_horario.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n //Se houver turma, verificar se existe professor\n $listInstructors = $classroom->instructorTeachingDatas;\n if (count($listInstructors) == 0) {\n $warning = 'Turma <b>' . $classroom->name . '</b> est\u00e1 sem professores.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/professores.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n //Se houver turma, verificar se existe aluno matriculado\n $listStudentEnrollments = $classroom->studentEnrollments;\n if (count($listStudentEnrollments) == 0) {\n $warning = 'Turma <b>' . $classroom->name . '</b> est\u00e1 sem alunos matriculados.';\n $htmlpart = '<li class=\"row justify-content--start home-page-table-item blue\" title=\\'' . $warning . '\\'>'\n . '<div class=\"column align-items--center warn-div\" style=\"text-overflow: ellipsis;\">'\n . '<img style=\"background-color:orange\" src=\"' . Yii::app()->theme->baseUrl . '/img/homePageIcons/matricula.svg\"/>'\n . '<span>' . $warning . '</span>'\n . '</div>'\n . '</li>';\n array_push($warns, $htmlpart);\n }\n\n }\n }\n\n\n\n if (count($warns) == 0) {\n return [\n \"total\" => 0,\n \"html\" => '<div class=\"no-recent-activitive t-badge-info\" id=\"no-recent-warnings\"><span class=\"t-info_positive t-badge-info__icon\"></span>N\u00e3o h\u00e1 cadastros pendentes.</div>'\n ];\n } else {\n $html = \"\";\n $count = $limit + $visibleWarningsCount;\n for ($i = $visibleWarningsCount; $i < $count; $i++) {\n $html .= $warns[$i];\n }\n return [\n \"total\" => count($warns),\n \"html\" => $html\n ];\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public static function processMassiveActionsForOneItemtype(\n MassiveAction $ma,\n CommonDBTM $item,\n array $ids\n ) {\n\n switch ($ma->getAction()) {\n case 'add':\n Toolbox::deprecated('Ticket_Ticket \"add\" massive action is deprecated. Use CommonITILObject_CommonITILObject \"add\" massive action.');\n $input = $ma->getInput();\n $ticket = new Ticket();\n if (\n isset($input['link'])\n && isset($input['tickets_id_1'])\n ) {\n if ($item->getFromDB($input['tickets_id_1'])) {\n foreach ($ids as $id) {\n $input2 = [];\n $input2['id'] = $input['tickets_id_1'];\n $input2['_link']['tickets_id_1'] = $id;\n $input2['_link']['link'] = $input['link'];\n $input2['_link']['tickets_id_2'] = $input['tickets_id_1'];\n if ($item->can($input['tickets_id_1'], UPDATE)) {\n if ($ticket->update($input2)) {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n }\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);\n $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));\n }\n }\n }\n }\n return;\n }\n parent::processMassiveActionsForOneItemtype($ma, $item, $ids);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function outputLargeFilesTree(\n\t\tOutputInterface $output,\n\t\tFolder $node,\n\t\tstring $prefix,\n\t\tarray &$sizeLimits,\n\t\tbool $all,\n\t): int {\n\t\t/**\n\t\t * Algorithm to print the N largest items in a folder without requiring to query or sort the entire three\n\t\t *\n\t\t * This is done by keeping a list ($sizeLimits) of size N that contain the largest items outside of this\n\t\t * folders that are could be printed if there aren't enough items in this folder that are larger.\n\t\t *\n\t\t * We loop over the items in this folder by size descending until the size of the item falls before the smallest\n\t\t * size in $sizeLimits (at that point there are enough items outside this folder to complete the N items).\n\t\t *\n\t\t * When encountering a folder, we create an updated $sizeLimits with the largest items in the current folder still\n\t\t * remaining which we pass into the recursion. (We don't update the current $sizeLimits because that should only\n\t\t * hold items *outside* of the current folder.)\n\t\t *\n\t\t * For every item printed we remove the first item of $sizeLimits are there is no longer room in the output to print\n\t\t * items that small.\n\t\t */\n\n\t\t$count = 0;\n\t\t$children = $node->getDirectoryListing();\n\t\tusort($children, function (Node $a, Node $b) {\n\t\t\treturn $b->getSize() <=> $a->getSize();\n\t\t});\n\t\tforeach ($children as $i => $child) {\n\t\t\tif (!$all) {\n\t\t\t\tif (count($sizeLimits) === 0 || $child->getSize() < $sizeLimits[0]) {\n\t\t\t\t\treturn $count;\n\t\t\t\t}\n\t\t\t\tarray_shift($sizeLimits);\n\t\t\t}\n\t\t\t$count += 1;\n\n\t\t\t/** @var Node $child */\n\t\t\t$output->writeln(\"$prefix- \" . $child->getName() . \": <info>\" . Util::humanFileSize($child->getSize()) . \"</info>\");\n\t\t\tif ($child instanceof Folder) {\n\t\t\t\t$recurseSizeLimits = $sizeLimits;\n\t\t\t\tif (!$all) {\n\t\t\t\t\tfor ($j = 0; $j < count($recurseSizeLimits); $j++) {\n\t\t\t\t\t\tif (isset($children[$i + $j + 1])) {\n\t\t\t\t\t\t\t$nextChildSize = $children[$i + $j + 1]->getSize();\n\t\t\t\t\t\t\tif ($nextChildSize > $recurseSizeLimits[0]) {\n\t\t\t\t\t\t\t\tarray_shift($recurseSizeLimits);\n\t\t\t\t\t\t\t\t$recurseSizeLimits[] = $nextChildSize;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tsort($recurseSizeLimits);\n\t\t\t\t}\n\t\t\t\t$recurseCount = $this->outputLargeFilesTree($output, $child, $prefix . \" \", $recurseSizeLimits, $all);\n\t\t\t\t$sizeLimits = array_slice($sizeLimits, $recurseCount);\n\t\t\t\t$count += $recurseCount;\n\t\t\t}\n\t\t}\n\t\treturn $count;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function check(&$element, $schema = null, JsonPointer $path = null, $i = null)\n {\n if (!isset($schema->format) || $this->factory->getConfig(self::CHECK_MODE_DISABLE_FORMAT)) {\n return;\n }\n\n switch ($schema->format) {\n case 'date':\n if (!$date = $this->validateDateTime($element, 'Y-m-d')) {\n $this->addError($path, sprintf('Invalid date %s, expected format YYYY-MM-DD', json_encode($element)), 'format', array('format' => $schema->format));\n }\n break;\n\n case 'time':\n if (!$this->validateDateTime($element, 'H:i:s')) {\n $this->addError($path, sprintf('Invalid time %s, expected format hh:mm:ss', json_encode($element)), 'format', array('format' => $schema->format));\n }\n break;\n\n case 'date-time':\n if (null === Rfc3339::createFromString($element)) {\n $this->addError($path, sprintf('Invalid date-time %s, expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm', json_encode($element)), 'format', array('format' => $schema->format));\n }\n break;\n\n case 'utc-millisec':\n if (!$this->validateDateTime($element, 'U')) {\n $this->addError($path, sprintf('Invalid time %s, expected integer of milliseconds since Epoch', json_encode($element)), 'format', array('format' => $schema->format));\n }\n break;\n\n case 'regex':\n if (!$this->validateRegex($element)) {\n $this->addError($path, 'Invalid regex format ' . $element, 'format', array('format' => $schema->format));\n }\n break;\n\n case 'color':\n if (!$this->validateColor($element)) {\n $this->addError($path, 'Invalid color', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'style':\n if (!$this->validateStyle($element)) {\n $this->addError($path, 'Invalid style', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'phone':\n if (!$this->validatePhone($element)) {\n $this->addError($path, 'Invalid phone number', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'uri':\n if (null === filter_var($element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)) {\n $this->addError($path, 'Invalid URL format', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'uriref':\n case 'uri-reference':\n if (null === filter_var($element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)) {\n // FILTER_VALIDATE_URL does not conform to RFC-3986, and cannot handle relative URLs, but\n // the json-schema spec uses RFC-3986, so need a bit of hackery to properly validate them.\n // See https://tools.ietf.org/html/rfc3986#section-4.2 for additional information.\n if (substr($element, 0, 2) === '//') { // network-path reference\n $validURL = filter_var('scheme:' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);\n } elseif (substr($element, 0, 1) === '/') { // absolute-path reference\n $validURL = filter_var('scheme://host' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);\n } elseif (strlen($element)) { // relative-path reference\n $pathParts = explode('/', $element, 2);\n if (strpos($pathParts[0], ':') !== false) {\n $validURL = null;\n } else {\n $validURL = filter_var('scheme://host/' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);\n }\n } else {\n $validURL = null;\n }\n if ($validURL === null) {\n $this->addError($path, 'Invalid URL format', 'format', array('format' => $schema->format));\n }\n }\n break;\n\n case 'email':\n $filterFlags = FILTER_NULL_ON_FAILURE;\n if (defined('FILTER_FLAG_EMAIL_UNICODE')) {\n // Only available from PHP >= 7.1.0, so ignore it for coverage checks\n $filterFlags |= constant('FILTER_FLAG_EMAIL_UNICODE'); // @codeCoverageIgnore\n }\n if (null === filter_var($element, FILTER_VALIDATE_EMAIL, $filterFlags)) {\n $this->addError($path, 'Invalid email', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'ip-address':\n case 'ipv4':\n if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV4)) {\n $this->addError($path, 'Invalid IP address', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'ipv6':\n if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV6)) {\n $this->addError($path, 'Invalid IP address', 'format', array('format' => $schema->format));\n }\n break;\n\n case 'host-name':\n case 'hostname':\n if (!$this->validateHostname($element)) {\n $this->addError($path, 'Invalid hostname', 'format', array('format' => $schema->format));\n }\n break;\n\n default:\n // Empty as it should be:\n // The value of this keyword is called a format attribute. It MUST be a string.\n // A format attribute can generally only validate a given set of instance types.\n // If the type of the instance to validate is not in this set, validation for\n // this format attribute and instance SHOULD succeed.\n // http://json-schema.org/latest/json-schema-validation.html#anchor105\n break;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['url'])) {\n $this->setUrl($data['url']);\n }\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['version'])) {\n $this->setVersion($data['version']);\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['title'])) {\n $this->setTitle($data['title']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['experimental'])) {\n $this->setExperimental($data['experimental']);\n }\n if (isset($data['date'])) {\n $this->setDate($data['date']);\n }\n if (isset($data['publisher'])) {\n $this->setPublisher($data['publisher']);\n }\n if (isset($data['contact'])) {\n if (is_array($data['contact'])) {\n foreach ($data['contact'] as $d) {\n $this->addContact($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"contact\" must be array of objects or null, ' . gettype($data['contact']) . ' seen.');\n }\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['useContext'])) {\n if (is_array($data['useContext'])) {\n foreach ($data['useContext'] as $d) {\n $this->addUseContext($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"useContext\" must be array of objects or null, ' . gettype($data['useContext']) . ' seen.');\n }\n }\n if (isset($data['jurisdiction'])) {\n if (is_array($data['jurisdiction'])) {\n foreach ($data['jurisdiction'] as $d) {\n $this->addJurisdiction($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"jurisdiction\" must be array of objects or null, ' . gettype($data['jurisdiction']) . ' seen.');\n }\n }\n if (isset($data['purpose'])) {\n $this->setPurpose($data['purpose']);\n }\n if (isset($data['copyright'])) {\n $this->setCopyright($data['copyright']);\n }\n if (isset($data['keyword'])) {\n if (is_array($data['keyword'])) {\n foreach ($data['keyword'] as $d) {\n $this->addKeyword($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"keyword\" must be array of objects or null, ' . gettype($data['keyword']) . ' seen.');\n }\n }\n if (isset($data['fhirVersion'])) {\n $this->setFhirVersion($data['fhirVersion']);\n }\n if (isset($data['mapping'])) {\n if (is_array($data['mapping'])) {\n foreach ($data['mapping'] as $d) {\n $this->addMapping($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"mapping\" must be array of objects or null, ' . gettype($data['mapping']) . ' seen.');\n }\n }\n if (isset($data['kind'])) {\n $this->setKind($data['kind']);\n }\n if (isset($data['abstract'])) {\n $this->setAbstract($data['abstract']);\n }\n if (isset($data['context'])) {\n if (is_array($data['context'])) {\n foreach ($data['context'] as $d) {\n $this->addContext($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"context\" must be array of objects or null, ' . gettype($data['context']) . ' seen.');\n }\n }\n if (isset($data['contextInvariant'])) {\n if (is_array($data['contextInvariant'])) {\n foreach ($data['contextInvariant'] as $d) {\n $this->addContextInvariant($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"contextInvariant\" must be array of objects or null, ' . gettype($data['contextInvariant']) . ' seen.');\n }\n }\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['baseDefinition'])) {\n $this->setBaseDefinition($data['baseDefinition']);\n }\n if (isset($data['derivation'])) {\n $this->setDerivation($data['derivation']);\n }\n if (isset($data['snapshot'])) {\n $this->setSnapshot($data['snapshot']);\n }\n if (isset($data['differential'])) {\n $this->setDifferential($data['differential']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function conversionArea() {\n\n $args = func_get_args();\n\n #region Verify/set defaults for function arguments\n\n if (count($args)==0) {\n echo nothingtodisplay();\n return \"\";\n } else {\n $system = strtoupper($args[0]);\n }\n\n if ( count($args)>1 && !is_null($args[1]) ) {\n $fullname = verifyFullName($args[1]);\n } else {\n $fullname = 0;\n }\n\n if ( count($args)>2 && !is_null($args[2]) ) {\n $rounding = verifyRounding($args[2]);\n } else {\n $rounding = 2;\n }\n\n // in the original version the sign and tick argument\n // were reversed\n if ( count($args)>3 && !is_null($args[3]) ) {\n $args3input = $args[3];\n if ( count($args)>4 && !is_null($args[4]) ) {\n $args4input = $args[4];\n } else {\n $args4input = \"\";\n }\n\n // was args3input the tick argument and args4input the sign - if so switch\n // should not be needed - but this wll prevent anyone that used this before\n // the release from displaying about = signs (the default if the 3rd argument is not a = or ~)\n if($args3input==\"y\" || $args3input==\"n\" || $args4input = \"=\" || $args4input = \"~\") {\n $signinput = $args4input;\n $tickinput = $args3input;\n } else {\n $signinput = $args3input;\n $tickinput = $args4input;\n }\n $sign = verifyEqualSign($signinput);\n $tick = verifyTickMarks($tickinput);\n } else {\n $sign = \"=\";\n $tick = \"\";\n }\n\n\t#endregion\n\n return conversion_extract_column_array(conversionArea2($system,$fullname,$rounding,$sign,$tick),0);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function action(Group $pools, Database $dbForConsole, callable $getProjectDB): void\n {\n Console::title('Scheduler V1');\n Console::success(APP_NAME . ' Scheduler v1 has started');\n\n /**\n * Extract only nessessary attributes to lower memory used.\n *\n * @var Document $schedule\n * @return array\n */\n $getSchedule = function (Document $schedule) use ($dbForConsole, $getProjectDB): array {\n $project = $dbForConsole->getDocument('projects', $schedule->getAttribute('projectId'));\n\n $function = $getProjectDB($project)->getDocument('functions', $schedule->getAttribute('resourceId'));\n\n return [\n 'resourceId' => $schedule->getAttribute('resourceId'),\n 'schedule' => $schedule->getAttribute('schedule'),\n 'resourceUpdatedAt' => $schedule->getAttribute('resourceUpdatedAt'),\n 'project' => $project, // TODO: @Meldiron Send only ID to worker to reduce memory usage here\n 'function' => $function, // TODO: @Meldiron Send only ID to worker to reduce memory usage here\n ];\n };\n\n $schedules = []; // Local copy of 'schedules' collection\n $lastSyncUpdate = DateTime::now();\n\n $limit = 10000;\n $sum = $limit;\n $total = 0;\n $loadStart = \\microtime(true);\n $latestDocument = null;\n\n while ($sum === $limit) {\n $paginationQueries = [Query::limit($limit)];\n if ($latestDocument !== null) {\n $paginationQueries[] = Query::cursorAfter($latestDocument);\n }\n $results = $dbForConsole->find('schedules', \\array_merge($paginationQueries, [\n Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),\n Query::equal('resourceType', ['function']),\n Query::equal('active', [true]),\n ]));\n\n $sum = count($results);\n $total = $total + $sum;\n foreach ($results as $document) {\n try {\n $schedules[$document['resourceId']] = $getSchedule($document);\n } catch (\\Throwable $th) {\n Console::error(\"Failed to load schedule for project {$document['projectId']} and function {$document['resourceId']}\");\n Console::error($th->getMessage());\n }\n }\n\n $latestDocument = !empty(array_key_last($results)) ? $results[array_key_last($results)] : null;\n }\n\n $pools->reclaim();\n\n Console::success(\"{$total} functions were loaded in \" . (microtime(true) - $loadStart) . \" seconds\");\n\n Console::success(\"Starting timers at \" . DateTime::now());\n\n run(\n function () use ($dbForConsole, &$schedules, &$lastSyncUpdate, $getSchedule, $pools) {\n /**\n * The timer synchronize $schedules copy with database collection.\n */\n Timer::tick(self::FUNCTION_UPDATE_TIMER * 1000, function () use ($dbForConsole, &$schedules, &$lastSyncUpdate, $getSchedule, $pools) {\n $time = DateTime::now();\n $timerStart = \\microtime(true);\n\n $limit = 1000;\n $sum = $limit;\n $total = 0;\n $latestDocument = null;\n\n Console::log(\"Sync tick: Running at $time\");\n\n while ($sum === $limit) {\n $paginationQueries = [Query::limit($limit)];\n if ($latestDocument !== null) {\n $paginationQueries[] = Query::cursorAfter($latestDocument);\n }\n $results = $dbForConsole->find('schedules', \\array_merge($paginationQueries, [\n Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),\n Query::equal('resourceType', ['function']),\n Query::greaterThanEqual('resourceUpdatedAt', $lastSyncUpdate),\n ]));\n\n $sum = count($results);\n $total = $total + $sum;\n foreach ($results as $document) {\n $localDocument = $schedules[$document['resourceId']] ?? null;\n\n $org = $localDocument !== null ? strtotime($localDocument['resourceUpdatedAt']) : null;\n $new = strtotime($document['resourceUpdatedAt']);\n\n if ($document['active'] === false) {\n Console::info(\"Removing: {$document['resourceId']}\");\n unset($schedules[$document['resourceId']]);\n } elseif ($new !== $org) {\n Console::info(\"Updating: {$document['resourceId']}\");\n $schedules[$document['resourceId']] = $getSchedule($document);\n }\n }\n $latestDocument = !empty(array_key_last($results)) ? $results[array_key_last($results)] : null;\n }\n\n $lastSyncUpdate = $time;\n $timerEnd = \\microtime(true);\n\n $pools->reclaim();\n\n Console::log(\"Sync tick: {$total} schedules were updated in \" . ($timerEnd - $timerStart) . \" seconds\");\n });\n\n /**\n * The timer to prepare soon-to-execute schedules.\n */\n $lastEnqueueUpdate = null;\n $enqueueFunctions = function () use (&$schedules, $lastEnqueueUpdate, $pools) {\n $timerStart = \\microtime(true);\n $time = DateTime::now();\n\n $enqueueDiff = $lastEnqueueUpdate === null ? 0 : $timerStart - $lastEnqueueUpdate;\n $timeFrame = DateTime::addSeconds(new \\DateTime(), self::FUNCTION_ENQUEUE_TIMER - $enqueueDiff);\n\n Console::log(\"Enqueue tick: started at: $time (with diff $enqueueDiff)\");\n\n $total = 0;\n\n $delayedExecutions = []; // Group executions with same delay to share one coroutine\n\n foreach ($schedules as $key => $schedule) {\n $cron = new CronExpression($schedule['schedule']);\n $nextDate = $cron->getNextRunDate();\n $next = DateTime::format($nextDate);\n\n $currentTick = $next < $timeFrame;\n\n if (!$currentTick) {\n continue;\n }\n\n $total++;\n\n $promiseStart = \\time(); // in seconds\n $executionStart = $nextDate->getTimestamp(); // in seconds\n $delay = $executionStart - $promiseStart; // Time to wait from now until execution needs to be queued\n\n if (!isset($delayedExecutions[$delay])) {\n $delayedExecutions[$delay] = [];\n }\n\n $delayedExecutions[$delay][] = $key;\n }\n\n foreach ($delayedExecutions as $delay => $scheduleKeys) {\n \\go(function () use ($delay, $schedules, $scheduleKeys, $pools) {\n \\sleep($delay); // in seconds\n\n $queue = $pools->get('queue')->pop();\n $connection = $queue->getResource();\n\n foreach ($scheduleKeys as $scheduleKey) {\n // Ensure schedule was not deleted\n if (!isset($schedules[$scheduleKey])) {\n return;\n }\n\n $schedule = $schedules[$scheduleKey];\n\n $functions = new Func($connection);\n\n $functions\n ->setType('schedule')\n ->setFunction($schedule['function'])\n ->setMethod('POST')\n ->setPath('/')\n ->setProject($schedule['project'])\n ->trigger();\n }\n\n $queue->reclaim();\n });\n }\n\n $timerEnd = \\microtime(true);\n $lastEnqueueUpdate = $timerStart;\n Console::log(\"Enqueue tick: {$total} executions were enqueued in \" . ($timerEnd - $timerStart) . \" seconds\");\n };\n\n Timer::tick(self::FUNCTION_ENQUEUE_TIMER * 1000, fn() => $enqueueFunctions());\n $enqueueFunctions();\n }\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function getorg($it,$parent,&$res,$ind, $parentid) {\n\tglobal $DBH,$iteminfo,$newdir,$installname,$urlmode,$urlmode,$imasroot,$ccnt,$module_meta,$htmldir,$filedir, $toplevelitems, $inmodule;\n\tglobal $usechecked,$checked,$usedcats;\n\tglobal $datcnt, $newdir, $datcnt, $bbnow;\n\tglobal $gbitems, $crslinks, $courseexportid, $bbtemplates;\n\n\t$out = '';\n\n\tforeach ($it as $k=>$item) {\n\t\tif (is_array($item)) {\n\t\t\tif (!$usechecked || array_search($parent.'-'.($k+1),$checked)!==FALSE) {\n\t\t\t\t$resid = 'res'.leftpad($datcnt);\n\t\t\t\t$datcnt++;\n\t\t\t\t$blockid = '_6'.leftpad($item['id']).'_1';\n\t\t\t\tcreatebbitem($resid, $parentid, 'toctop', $item['name'], array(\n\t\t\t\t\t'{{id}}' => $blockid,\n\t\t\t\t\t'{{title}}' => xmlstr($item['name']),\n\t\t\t\t\t'{{parentid}}' => $parentid,\n\t\t\t\t\t'{{avail}}' => $item['avail']==0?'false':'true',\n\t\t\t\t\t'{{created}}' => $bbnow\n\t\t\t\t\t), 'folder', $res);\n\n\t\t\t\t$out .= $ind.'<item identifier=\"BLOCK'.$item['id'].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($item['name']).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.getorg($item['items'],$parent.'-'.($k+1),$res,$ind.' ', $blockid);\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\n\t\t\t} else {\n\t\t\t\t$out .= $ind.getorg($item['items'],$parent.'-'.($k+1),$res,$ind.' ', $parentid);\n\t\t\t}\n\n\t\t} else {\n\t\t\tif ($usechecked && array_search($item,$checked)===FALSE) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$resid = 'res'.leftpad($datcnt);\n\t\t\t$datcnt++;\n\t\t\tif ($iteminfo[$item][0]=='InlineText') {\n\t\t\t\t$filesout = array();\n\t\t\t\t$stm = $DBH->prepare(\"SELECT title,text,fileorder,avail FROM imas_inlinetext WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\tif ($row[2]!='') {\n\t\t\t\t\t$files = explode(',',$row[2]);\n\t\t\t\t\t$stm = $DBH->prepare(\"SELECT id,description,filename FROM imas_instr_files WHERE itemid=:itemid\");\n\t\t\t\t\t$stm->execute(array(':itemid'=>$iteminfo[$item][1]));\n\t\t\t\t\twhile ($r = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\t\t\t\t//do files as weblinks rather than including the file itself\n\t\t\t\t\t\tif (substr($r[2],0,4)=='http') {\n\t\t\t\t\t\t\t//do nothing\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$r[2] = getcoursefileurl($r[2], true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\taddbbfile($courseexportid, $r[2], 'LINK', $filesout, $crslinks);\n\t\t\t\t\t\t//$filesout[$r[0]] = array($r[1],$r[2]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($row[0]).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\t\t\t\t$text = $row[1];\n\t\t\t\t/*if ($row[2]!='') {\n\t\t\t\t\t$text .= '<ul>';\n\t\t\t\t\tforeach ($files as $f) {\n\t\t\t\t\t\t$text .= '<li><a href=\"'.$filesout[$f][1].'\">'.htmlentities($filesout[$f][0]).'</a></li>';\n\t\t\t\t\t}\n\t\t\t\t\t$text .= '</ul>';\n\t\t\t\t}*/\n\n\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($text)),\n\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t'{{avail}}' => $row[3]==0?'false':'true',\n\t\t\t\t\t'{{newwindow}}' => \"false\",\n\t\t\t\t\t'{{files}}' => implode(\"\\n\", $filesout)\n\t\t\t\t\t), 'text', $res);\n\n\t\t\t} else if ($iteminfo[$item][0]=='LinkedText') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT title,text,summary,avail FROM imas_linkedtext WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($row[0]).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\t\t\t\t//do files as weblinks rather than including the file itself\n\t\t\t\tif (substr(strip_tags($row[1]),0,5)==\"file:\") {\n\t\t\t\t\tif ($row[2]=='<p></p>') {\n\t\t\t\t\t\t$row[2] = '';\n\t\t\t\t\t}\n\t\t\t\t\t$filesout = array();\n\t\t\t\t\t$coursefileurl = getcoursefileurl(trim(substr(strip_tags($row[1]),5)), true);\n\t\t\t\t\taddbbfile($courseexportid, $coursefileurl, 'EMBED', $filesout, $crslinks);\n\t\t\t\t\t//$row[1] = getcoursefileurl(trim(substr(strip_tags($row[1]),5)), true);\n\t\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[2])),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[3]==0?'false':'true',\n\t\t\t\t\t\t'{{newwindow}}' => \"true\",\n\t\t\t\t\t\t'{{files}}' => $filesout[0]\n\t\t\t\t\t\t), 'file', $res);\n\t\t\t\t} else if ((substr($row[1],0,4)==\"http\") && (strpos(trim($row[1]),\" \")===false)) { //is a web link\n\t\t\t\t\t$alink = trim($row[1]);\n\t\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[2])),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[3]==0?'false':'true',\n\t\t\t\t\t\t'{{launchurl}}' => $alink,\n\t\t\t\t\t\t'{{newwindow}}' => \"true\",\n\t\t\t\t\t\t), 'link', $res);\n\t\t\t\t} else { //is text\n\t\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[1])),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[3]==0?'false':'true',\n\t\t\t\t\t\t'{{newwindow}}' => \"false\"\n\t\t\t\t\t\t), 'page', $res);\n\t\t\t\t}\n\t\t\t} else if ($iteminfo[$item][0]=='Forum') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,description,avail FROM imas_forums WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\n\t\t\t\t$forumresid = $resid;\n\t\t\t\tcreatebbitem($forumresid, $parentid, 'forum', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_8'.$item.'_1',\n\t\t\t\t\t\t'{{conferenceid}}' => 'conf1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[1])),\n\t\t\t\t\t\t'{{avail}}' => $row[2]==0?'false':'true',\n\t\t\t\t\t\t'{{created}}' => $bbnow\n\t\t\t\t\t\t), 'forum', $res);\n\n\t\t\t\t$resid = 'res'.leftpad($datcnt);\n\t\t\t\t$datcnt++;\n\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($row[0]).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[1])),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[2]==0?'false':'true',\n\t\t\t\t\t\t'{{newwindow}}' => \"false\"\n\t\t\t\t\t\t), 'forumitem', $res);\n\n\t\t\t\t$forumlinkresid = 'res'.leftpad($datcnt);\n\t\t\t\t$datcnt++;\n\n\t\t\t\tcreatebbitem($forumlinkresid, $parentid, 'forumlink', '', array(\n\t\t\t\t\t\t'{{id}}' => '_9'.$item.'_1',\n\t\t\t\t\t\t'{{itemdat}}' => $resid,\n\t\t\t\t\t\t'{{avail}}' => $row[2]==0?'false':'true',\n\t\t\t\t\t\t'{{forumdat}}' => $forumresid\n\t\t\t\t\t\t), 'forumlink', $res);\n\n\t\t\t} else if ($iteminfo[$item][0]=='Assessment') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,summary,defpoints,itemorder,enddate,gbcategory,avail,startdate,ptsposs FROM imas_assessments WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\tif ($row[8]==-1) {\n\t\t\t\t\trequire_once \"../includes/updateptsposs.php\";\n\t\t\t\t\t$row[8] = updatePointsPossible($iteminfo[$item][1], $row[3], $row[2]);\n\t\t\t\t}\n\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($row[0]).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\t\t\t\t$extended = '<ENTRY key=\"customParameters\"/>';\n\t\t\t\t$extended .= '<ENTRY key=\"alternateUrl\">http://'.Sanitize::domainNameWithPort($_SERVER['HTTP_HOST']) . $imasroot . '/bltilaunch.php?custom_place_aid='.$iteminfo[$item][1].'</ENTRY>';\n\t\t\t\t$extended .= '<ENTRY key=\"vendorInfo\">name='.$installname.'&amp;code=IMathAS</ENTRY>';\n\n\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($row[1])),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[6]==0?'false':'true',\n\t\t\t\t\t\t'{{newwindow}}' => \"false\",\n\t\t\t\t\t\t'{{launchurl}}' => $urlmode.Sanitize::domainNameWithPort($_SERVER['HTTP_HOST']) . $imasroot . '/bltilaunch.php?custom_place_aid='.$iteminfo[$item][1],\n\t\t\t\t\t\t'{{extendeddata}}' => $extended\n\t\t\t\t\t\t), 'lti', $res);\n\n\t\t\t\t$gbitem = $bbtemplates['outcomedef'];\n\t\t\t\t$gbitem = str_replace('{{defid}}', '_11'.$item.'_1', $gbitem);\n\t\t\t\t$gbitem = str_replace('{{resid}}', $resid, $gbitem);\n\t\t\t\t$includeduedate = ($_POST['includeduedates']==1 && $row[4]<2000000000);\n\t\t\t\t$gbitem = str_replace('{{duedate}}', $includeduedate?bbdate($row[4]):'', $gbitem);\n\t\t\t\t$gbitem = str_replace('{{title}}', xmlstr($row[0]), $gbitem);\n\t\t\t\t$gbitem = str_replace('{{ptsposs}}', $row[8], $gbitem);\n\t\t\t\t$gbitems[] = $gbitem;\n\n\t\t\t} else if ($iteminfo[$item][0]=='Wiki') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,avail FROM imas_wikis WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"'.$resid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.xmlstr($row[0]).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\n\t\t\t\t$stm = $DBH->prepare(\"SELECT revision FROM imas_wiki_revisions WHERE wikiid=:wikiid AND stugroupid=0 ORDER BY id DESC LIMIT 1\");\n\t\t\t\t$stm->execute(array(':wikiid'=>$iteminfo[$item][1]));\n\t\t\t\tif ($stm->rowCount()>0) {\n\t\t\t\t\t$text = $stm->fetchColumn(0);\n\t\t\t\t\tif (strlen($text)>6 && substr($text,0,6)=='**wver') {\n\t\t\t\t\t\t$wikiver = substr($text,6,strpos($text,'**',6)-6);\n\t\t\t\t\t\t$text = substr($text,strpos($text,'**',6)+2);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcreatebbitem($resid, $parentid, 'basicitem', $row[0], array(\n\t\t\t\t\t\t'{{id}}' => '_7'.$item.'_1',\n\t\t\t\t\t\t'{{title}}' => xmlstr($row[0]),\n\t\t\t\t\t\t'{{summary}}' => xmlstr(filtercapture($text)),\n\t\t\t\t\t\t'{{created}}' => $bbnow,\n\t\t\t\t\t\t'{{avail}}' => $row[1]==0?'false':'true',\n\t\t\t\t\t\t'{{newwindow}}' => \"false\"\n\t\t\t\t\t\t), 'page', $res);\n\n\t\t\t}\n\t\t}\n\t}\n\treturn $out;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function removeCSS($css_uri, $css_media_type = 'all', $check_path = true)\n {\n if (!is_array($css_uri)) {\n $css_uri = array($css_uri);\n }\n\n foreach ($css_uri as $css_file => $media) {\n if (is_string($css_file) && strlen($css_file) > 1) {\n if ($check_path) {\n $css_path = Media::getCSSPath($css_file, $media);\n } else {\n $css_path = array($css_file => $media);\n }\n } else {\n if ($check_path) {\n $css_path = Media::getCSSPath($media, $css_media_type);\n } else {\n $css_path = array($media => $css_media_type);\n }\n }\n\n if ($css_path && isset($this->css_files[key($css_path)]) && ($this->css_files[key($css_path)] == reset($css_path))) {\n unset($this->css_files[key($css_path)]);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function getCASStatus($public_only = true): array\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n static $status = null;\n\n if ($status === null) {\n $status['status'] = self::STATUS_NO_DATA;\n if (!empty($CFG_GLPI['cas_host'])) {\n $url = $CFG_GLPI['cas_host'];\n if (!empty($CFG_GLPI['cas_port'])) {\n $url .= ':' . (int)$CFG_GLPI['cas_port'];\n }\n $url .= '/' . $CFG_GLPI['cas_uri'];\n if (Toolbox::isUrlSafe($url)) {\n $data = Toolbox::getURLContent($url);\n if (!empty($data)) {\n $status['status'] = self::STATUS_OK;\n } else {\n $status['status'] = self::STATUS_PROBLEM;\n }\n } else {\n $status['status'] = self::STATUS_NO_DATA;\n if (!$public_only) {\n $status['status_msg'] = sprintf(\n __('URL \"%s\" is not considered safe and cannot be fetched from GLPI server.'),\n $url\n );\n }\n }\n }\n }\n\n return $status;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function get($allowUnstable = false) {\n\t\t$entries = parent::get(false);\n\t\t$now = new DateTimeImmutable();\n\n\t\treturn array_filter($entries, function (array $entry) use ($now, $allowUnstable) {\n\t\t\t// Always remove expired entries\n\t\t\tif (isset($entry['expiryDate'])) {\n\t\t\t\ttry {\n\t\t\t\t\t$expiryDate = new DateTimeImmutable($entry['expiryDate']);\n\t\t\t\t\tif ($expiryDate < $now) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} catch (\\Throwable $e) {\n\t\t\t\t\t// Invalid expiryDate format\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If not include upcoming entries, check for upcoming dates and remove those entries\n\t\t\tif (!$allowUnstable && isset($entry['date'])) {\n\t\t\t\ttry {\n\t\t\t\t\t$date = new DateTimeImmutable($entry['date']);\n\t\t\t\t\tif ($date > $now) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} catch (\\Throwable $e) {\n\t\t\t\t\t// Invalid date format\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Otherwise the entry is not time limited and should stay\n\t\t\treturn true;\n\t\t});\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function setContentMainDocumentId(int|string|null $contentMainDocumentId, bool $validate = false): static\n {\n // this is that the path is automatically converted to ID => when setting directly from admin UI\n if (!is_numeric($contentMainDocumentId) && !empty($contentMainDocumentId)) {\n if ($contentMainDocument = Document\\PageSnippet::getByPath($contentMainDocumentId)) {\n $contentMainDocumentId = $contentMainDocument->getId();\n } else {\n // Content main document was deleted or don't exist\n $contentMainDocumentId = null;\n }\n }\n\n // Don't set the content main document if the document is already part of the main document chain\n if ($contentMainDocumentId) {\n if ($currentContentMainDocument = Document\\PageSnippet::getById($contentMainDocumentId)) {\n $maxDepth = 20;\n do {\n if ($currentContentMainDocument->getId() === $this->getId()) {\n throw new Exception('This document is already part of the main document chain, please choose a different one.');\n }\n $currentContentMainDocument = $currentContentMainDocument->getContentMainDocument();\n } while ($currentContentMainDocument && $maxDepth-- > 0 && $validate);\n } else {\n // Content main document was deleted or don't exist\n $contentMainDocumentId = null;\n }\n }\n\n $this->contentMainDocumentId = ($contentMainDocumentId ? (int) $contentMainDocumentId : null);\n\n return $this;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function showDoubles(FieldUnicity $unicity)\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $fields = [];\n $where_fields = [];\n if (!$item = getItemForItemtype($unicity->fields['itemtype'])) {\n return;\n }\n foreach (explode(',', $unicity->fields['fields']) as $field) {\n $fields[] = $field;\n $where_fields[] = $field;\n }\n\n $entities = [$unicity->fields['entities_id']];\n if ($unicity->fields['is_recursive']) {\n $entities = getSonsOf('glpi_entities', $unicity->fields['entities_id']);\n }\n\n $where = [];\n if ($item->maybeTemplate()) {\n $where[$item::getTable() . '.is_template'] = 0;\n }\n\n foreach ($where_fields as $where_field) {\n $where += [\n 'NOT' => [$where_field => null],\n $where_field => ['<>', getTableNameForForeignKeyField($where_field) ? 0 : '']\n ];\n }\n $item_table = $item::getTable();\n\n $iterator = $DB->request([\n 'SELECT' => $fields,\n 'COUNT' => 'cpt',\n 'FROM' => $item_table,\n 'WHERE' => [\n $item_table . '.entities_id' => $entities\n ] + $where,\n 'GROUPBY' => $fields,\n 'ORDERBY' => 'cpt DESC'\n ]);\n\n $entries = [];\n foreach ($iterator as $data) {\n if ($data['cpt'] > 1) {\n $entry = [];\n foreach ($fields as $field) {\n $table = getTableNameForForeignKeyField($field);\n $entry[$field] = $table !== '' ? Dropdown::getDropdownName($table, $data[$field]) : $data[$field];\n }\n $entry['number'] = $data['cpt'];\n $entries[] = $entry;\n }\n }\n\n $columns = [];\n foreach ($fields as $field) {\n $searchOption = $item->getSearchOptionByField('field', $field);\n $columns[$field] = $searchOption[\"name\"];\n }\n $columns['number'] = _x('quantity', 'Number');\n TemplateRenderer::getInstance()->display('components/datatable.html.twig', [\n 'is_tab' => true,\n 'nopager' => true,\n 'nofilter' => true,\n 'columns' => $columns,\n 'entries' => $entries,\n 'total_number' => count($entries),\n 'filtered_number' => count($entries),\n 'showmassiveactions' => false,\n ]);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function uploadFileToNakala($system, $params) {\n\n global $glb_curl_code, $glb_curl_error, $system;\n $glb_curl_code = null;\n $glb_curl_error = null;\n\n $herror = HEURIST_ACTION_BLOCKED;\n\n $NAKALA_BASE_URL = @$params['use_test_url'] == 1 ? 'https://test.nakala.fr/u/datas/' : 'https://nakala.fr/u/datas/';\n $NAKALA_BASE_URL_API = @$params['use_test_url'] == 1 ? 'https://apitest.nakala.fr/datas/' : 'https://api.nakala.fr/datas/';\n\n $missing_key = '<br><br>Your Nakala API key is either missing or invalid, please ';\n $missing_key .= $system->is_admin() ? 'ask a database administrator to setup the key within' : 'ensure you\\'ve set it in';\n $missing_key .= ' Database properties';\n\n $unknow_error_msg = 'An unknown response was receiveed from Nakala after uploading the selected file.<br>Please contact the Heurist team if this persists.';\n\n if(!function_exists(\"curl_init\")) {\n\n $glb_curl_code = HEURIST_SYSTEM_FATAL;\n $glb_curl_error = 'Cannot init curl extension. Verify php installation';\n $system->addError(HEURIST_SYSTEM_FATAL, $glb_curl_error);\n\n return false;\n }\n\n $api_key = 'X-API-KEY: ' . $params['api_key'];\n $file_sha1 = '';\n\n $useragent = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6';\n\n $ch = curl_init();\n\n curl_setopt($ch, CURLOPT_HTTPHEADER, array($api_key));// USERs API KEY\n\n curl_setopt($ch, CURLOPT_COOKIEFILE, '/dev/null');\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//return the output as a string from curl_exec\n curl_setopt($ch, CURLOPT_NOBODY, 0);\n curl_setopt($ch, CURLOPT_HEADER, 0);//don't include header in output\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// follow server header redirects\n\n curl_setopt($ch, CURLOPT_TIMEOUT, 60);// timeout after sixty seconds\n curl_setopt($ch, CURLOPT_MAXREDIRS, 5);// no more than 5 redirections\n\n curl_setopt($ch, CURLOPT_USERAGENT, $useragent);\n\n curl_setopt($ch, CURLOPT_AUTOREFERER, true);\n\n if(defined(\"HEURIST_HTTP_PROXY\")) {\n curl_setopt($ch, CURLOPT_PROXY, HEURIST_HTTP_PROXY);\n if(defined('HEURIST_HTTP_PROXY_AUTH')) {\n curl_setopt($ch, CURLOPT_PROXYUSERPWD, HEURIST_HTTP_PROXY_AUTH);\n }\n }\n\n if(!file_exists($params['file']['path'])){\n $system->addError(HEURIST_ERROR, 'Could not locate the file to be uploaded to Nakala');\n return false;\n }\n\n $curl_file = new CURLFile($params['file']['path'], $params['file']['type'], $params['file']['name']);\n $local_sha1 = sha1_file($params['file']['path']);\n\n curl_setopt($ch, CURLOPT_URL, \"{$NAKALA_BASE_URL_API}uploads\");\n\n // Check if file has already been uploaded - may have previously failed\n $file_list = curl_exec($ch);\n\n $error = curl_error($ch);\n\n if ($error) {\n\n $glb_curl_code = 'curl';\n $glb_curl_error = $error;\n\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n } // other error do not matter here\n }\n\n $file_list = json_decode($file_list, TRUE);\n if(JSON_ERROR_NONE == json_last_error() && is_array($file_list)){\n\n if(array_key_exists('message', $file_list)){\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n } // other error do not matter here\n }else{\n foreach ($file_list as $file_dtls) {\n if($local_sha1 == $file_dtls['sha1']){\n $file_sha1 = $local_sha1;\n break;\n }\n }\n }\n }\n\n if($file_sha1 == ''){ // UPLOAD FILE - (upload one file at a time, collect all SHA1 values, then process all together)\n\n curl_setopt($ch, CURLOPT_POST, 1);\n curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => $curl_file));\n\n $file_details = curl_exec($ch);\n\n $error = curl_error($ch);\n\n if ($error) {\n\n $glb_curl_code = 'curl';\n $glb_curl_error = $error;\n\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n }else{\n $glb_curl_error = $file_details['message'];\n }\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n }\n\n $file_details = json_decode($file_details, TRUE);\n\n if(JSON_ERROR_NONE != json_last_error() || !is_array($file_details)){ // json error occurred | is not array | is missing information\n curl_close($ch);\n $system->addError(HEURIST_ACTION_BLOCKED, $unknow_error_msg);\n\n return false;\n }\n\n if(array_key_exists('message', $file_details)){\n\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n }else{\n $glb_curl_error = $file_details['message'];\n }\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n }\n\n $file_sha1 = $file_details['sha1'];\n\n if($local_sha1 != $file_sha1){\n $system->addError(HEURIST_ACTION_BLOCKED, 'The local file and uploaded file to Nakala do not match.<br>Please contact the Heurist team if this persists.');\n return false;\n }\n //$file_title = $upload_details['name']; Don't need it\n }\n\n $status = 'pending';\n if(array_key_exists('status', $params)){\n $status = $params['status'];\n }\n\n // UPLOAD METADATA\n $metadata = array('status' => $status, 'metas' => array(), 'files' => array());\n\n $metadata['files'][] = array( 'sha1' => $file_sha1 );\n if(!empty($params['file']['description'])){\n $metadata['files'][0]['description'] = htmlspecialchars($params['file']['description']);\n }\n\n foreach ($params['meta'] as $data) {\n $metadata['metas'][] = $data;\n }\n\n curl_setopt($ch, CURLOPT_HTTPHEADER, array($api_key, 'Content-Type:application/json'));// Reset headers to specify the return type\n curl_setopt($ch, CURLOPT_URL, \"{$NAKALA_BASE_URL_API}\");\n curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($metadata));\n\n $result = curl_exec($ch);\n\n $error = curl_error($ch);\n\n if ($error) {\n\n $glb_curl_code = 'curl';\n $glb_curl_error = $error;\n\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n }else{\n $glb_curl_error = $file_details['message'];\n }\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n }\n\n $result = json_decode($result, TRUE);\n\n if(JSON_ERROR_NONE != json_last_error() || !is_array($result)){ // json error occurred | is not array | is missing information\n curl_close($ch);\n $system->addError(HEURIST_ACTION_BLOCKED, $unknow_error_msg);\n\n return false;\n }\n\n if(array_key_exists('payload', $result)){\n $payload = $result['payload'];\n if(array_key_exists('id', $payload)){\n if(array_key_exists('return_type', $params) && $params['return_type'] == 'editor'){ // returns link to private view\n $external_url = \"{$NAKALA_BASE_URL}{$result['payload']['id']}\";\n }else{ // returns link to publically available file\n $external_url = \"{$NAKALA_BASE_URL_API}{$result['payload']['id']}/{$file_sha1}\";\n }\n }else{\n\n curl_close($ch);\n $msg = '';\n if(is_array($payload)){\n $msg = implode('<br>', array_values($payload));\n }else{\n $msg = $payload;\n }\n $system->addError($herror, $msg);\n\n return false;\n }\n }elseif(array_key_exists('message', $result)){\n\n $code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));\n\n if($code == 401 || $code == 403){ // invalid/missing api key, or unknown account/user\n $glb_curl_error .= $missing_key;\n $herror = HEURIST_INVALID_REQUEST;\n }else{\n $glb_curl_error = $result['message'];\n }\n\n curl_close($ch);\n $system->addError($herror, $glb_curl_error);\n\n return false;\n }else{\n curl_close($ch);\n $system->addError(HEURIST_ACTION_BLOCKED, $unknow_error_msg);\n\n return false;\n }\n\n return $external_url;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function TIquartile($a,$q) {\n\tif (!is_array($a)) {\n\t\techo 'percentile expects an array';\n\t\treturn false;\n\t}\n\tif ($q<0 || $q>4) {\n\t\techo 'invalid quartile number';\n\t\treturn false;\n\t}\n\tsort($a, SORT_NUMERIC);\n\t$n = count($a);\n\tif ($q==0) {\n\t\treturn $a[0];\n\t} else if ($q==4) {\n\t\treturn $a[count($a)-1];\n\t}\n\tif ($q==2) {\n\t\tif ($n%2==0) { //even\n\t\t\t$m = $n/2;\n\t\t\treturn (($a[$m-1] + $a[$m])/2);\n\t\t} else {\n\t\t\treturn ($a[floor($n/2)]);\n\t\t}\n\t} else {\n\t\tif ($n%2==0) { //even\n\t\t\tif ($n%4==0) { //lower half is even\n\t\t\t\t$m = $n/4;\n\t\t\t\tif ($q==3) { $m = $n-$m;}\n\t\t\t\treturn (($a[$m-1] + $a[$m])/2);\n\t\t\t} else {\n\t\t\t\t$m = floor($n/4);\n\t\t\t\tif ($q==3) { $m = $n-$m-1;}\n\t\t\t\treturn ($a[$m]);\n\t\t\t}\n\t\t} else {\n\t\t\tif ((($n-1)/2)%2==0) {//lower half is even\n\t\t\t\t$m = floor($n/4);\n\t\t\t\tif ($q==3) { $m = $n-$m;}\n\t\t\t\treturn (($a[$m-1] + $a[$m])/2);\n\t\t\t} else {\n\t\t\t\t$m = floor($n/4);\n\t\t\t\tif ($q==3) { $m = $n-$m-1;}\n\t\t\t\treturn ($a[$m]);\n\t\t\t}\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function buildInsertColumns($passed_in = array(), $options = array())\n {\n $keyset = '';\n $bind = array();\n $result = array();\n $null_value = array_key_exists('null_value', $options) ? $options['null_value'] : '';\n\n foreach ($passed_in as $key => $value) {\n // Ensure auto's not passed in.\n if (in_array($key, array_column($this->autoIncrements, 'Field'))) {\n continue;\n }\n // include existing columns\n if (!in_array($key, $this->fields)) {\n continue;\n }\n if ($value == 'YYYY-MM-DD' || $value == 'MM/DD/YYYY') {\n $value = \"\";\n } elseif ($value === \"NULL\") {\n // make it consistent with our update columns... I really don't like this magic string constant\n // if someone intends to actually store the value NULL as a string this will break....\n $value = $null_value;\n }\n if ($value === null || $value === false) {\n $value = $null_value;\n }\n if (!empty($key)) {\n $keyset .= ($keyset) ? \", `$key` = ? \" : \"`$key` = ? \";\n // for dates which should be saved as null\n if (empty($value) && (strpos($key, 'date') !== false)) {\n $bind[] = null;\n } else {\n $bind[] = ($value === null || $value === false) ? $null_value : $value;\n }\n }\n }\n\n $result['set'] = $keyset;\n $result['bind'] = $bind;\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function update(Recurrence $recurrence, array $data): Recurrence\n {\n $this->user = $recurrence->user;\n // update basic fields first:\n\n if (array_key_exists('recurrence', $data)) {\n $info = $data['recurrence'];\n if (array_key_exists('title', $info)) {\n $recurrence->title = $info['title'];\n }\n if (array_key_exists('description', $info)) {\n $recurrence->description = $info['description'];\n }\n if (array_key_exists('first_date', $info)) {\n $recurrence->first_date = $info['first_date'];\n $recurrence->first_date_tz = $info['first_date']?->format('e');\n }\n if (array_key_exists('repeat_until', $info)) {\n $recurrence->repeat_until = $info['repeat_until'];\n $recurrence->repeat_until_tz = $info['repeat_until']?->format('e');\n $recurrence->repetitions = 0;\n }\n if (array_key_exists('nr_of_repetitions', $info)) {\n if (0 !== (int)$info['nr_of_repetitions']) {\n $recurrence->repeat_until = null;\n }\n $recurrence->repetitions = $info['nr_of_repetitions'];\n }\n if (array_key_exists('apply_rules', $info)) {\n $recurrence->apply_rules = $info['apply_rules'];\n }\n if (array_key_exists('active', $info)) {\n $recurrence->active = $info['active'];\n }\n // update all meta data:\n if (array_key_exists('notes', $info)) {\n $this->setNoteText($recurrence, $info['notes']);\n }\n }\n $recurrence->save();\n\n // update all repetitions\n if (array_key_exists('repetitions', $data)) {\n app('log')->debug('Will update repetitions array');\n // update each repetition or throw error yay\n $this->updateRepetitions($recurrence, $data['repetitions'] ?? []);\n }\n // update all transactions:\n // update all transactions (and associated meta-data)\n if (array_key_exists('transactions', $data)) {\n $this->updateTransactions($recurrence, $data['transactions'] ?? []);\n }\n\n return $recurrence;\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (0 < count($this->instantiatesCanonical)) {\n $json['instantiatesCanonical'] = [];\n foreach ($this->instantiatesCanonical as $instantiatesCanonical) {\n $json['instantiatesCanonical'][] = $instantiatesCanonical;\n }\n }\n if (0 < count($this->instantiatesUri)) {\n $json['instantiatesUri'] = [];\n foreach ($this->instantiatesUri as $instantiatesUri) {\n $json['instantiatesUri'][] = $instantiatesUri;\n }\n }\n if (0 < count($this->basedOn)) {\n $json['basedOn'] = [];\n foreach ($this->basedOn as $basedOn) {\n $json['basedOn'][] = $basedOn;\n }\n }\n if (0 < count($this->replaces)) {\n $json['replaces'] = [];\n foreach ($this->replaces as $replaces) {\n $json['replaces'][] = $replaces;\n }\n }\n if (isset($this->groupIdentifier)) {\n $json['groupIdentifier'] = $this->groupIdentifier;\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->intent)) {\n $json['intent'] = $this->intent;\n }\n if (isset($this->priority)) {\n $json['priority'] = $this->priority;\n }\n if (isset($this->code)) {\n $json['code'] = $this->code;\n }\n if (isset($this->subject)) {\n $json['subject'] = $this->subject;\n }\n if (isset($this->encounter)) {\n $json['encounter'] = $this->encounter;\n }\n if (isset($this->authoredOn)) {\n $json['authoredOn'] = $this->authoredOn;\n }\n if (isset($this->author)) {\n $json['author'] = $this->author;\n }\n if (0 < count($this->reasonCode)) {\n $json['reasonCode'] = [];\n foreach ($this->reasonCode as $reasonCode) {\n $json['reasonCode'][] = $reasonCode;\n }\n }\n if (0 < count($this->reasonReference)) {\n $json['reasonReference'] = [];\n foreach ($this->reasonReference as $reasonReference) {\n $json['reasonReference'][] = $reasonReference;\n }\n }\n if (0 < count($this->note)) {\n $json['note'] = [];\n foreach ($this->note as $note) {\n $json['note'][] = $note;\n }\n }\n if (0 < count($this->action)) {\n $json['action'] = [];\n foreach ($this->action as $action) {\n $json['action'][] = $action;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function process_syslog($entry, $update)\n{\n global $dev_cache;\n\n foreach (Config::get('syslog_filter') as $bi) {\n if (strpos($entry['msg'], $bi) !== false) {\n return $entry;\n }\n }\n\n $entry['host'] = preg_replace('/^::ffff:/', '', $entry['host']);\n $syslog_xlate = Config::get('syslog_xlate');\n if (! empty($syslog_xlate[$entry['host']])) {\n $entry['host'] = $syslog_xlate[$entry['host']];\n }\n $entry['device_id'] = get_cache($entry['host'], 'device_id');\n if ($entry['device_id']) {\n $os = get_cache($entry['host'], 'os');\n $hostname = get_cache($entry['host'], 'hostname');\n\n if (Config::get('enable_syslog_hooks') && is_array(Config::getOsSetting($os, 'syslog_hook'))) {\n foreach (Config::getOsSetting($os, 'syslog_hook') as $k => $v) {\n $syslogprogmsg = $entry['program'] . ': ' . $entry['msg'];\n if ((isset($v['script'])) && (isset($v['regex'])) && preg_match($v['regex'], $syslogprogmsg)) {\n shell_exec(escapeshellcmd($v['script']) . ' ' . escapeshellarg($hostname) . ' ' . escapeshellarg($os) . ' ' . escapeshellarg($syslogprogmsg) . ' >/dev/null 2>&1 &');\n }\n }\n }\n\n if (in_array($os, ['ios', 'iosxe', 'catos'])) {\n // multipart message\n if (strpos($entry['msg'], ':') !== false) {\n $matches = [];\n $timestamp_prefix = '([\\*\\.]?[A-Z][a-z]{2} \\d\\d? \\d\\d:\\d\\d:\\d\\d(.\\d\\d\\d)?( [A-Z]{3})?: )?';\n $program_match = '(?<program>%?[A-Za-z\\d\\-_]+(:[A-Z]* %[A-Z\\d\\-_]+)?)';\n $message_match = '(?<msg>.*)';\n if (preg_match('/^' . $timestamp_prefix . $program_match . ': ?' . $message_match . '/', $entry['msg'], $matches)) {\n $entry['program'] = $matches['program'];\n $entry['msg'] = $matches['msg'];\n }\n unset($matches);\n } else {\n // if this looks like a program (no groups of 2 or more lowercase letters), move it to program\n if (! preg_match('/[(a-z)]{2,}/', $entry['msg'])) {\n $entry['program'] = $entry['msg'];\n unset($entry['msg']);\n }\n }\n } elseif ($os == 'linux' and get_cache($entry['host'], 'version') == 'Point') {\n // Cisco WAP200 and similar\n $matches = [];\n if (preg_match('#Log: \\[(?P<program>.*)\\] - (?P<msg>.*)#', $entry['msg'], $matches)) {\n $entry['msg'] = $matches['msg'];\n $entry['program'] = $matches['program'];\n }\n\n unset($matches);\n } elseif ($os == 'linux') {\n $matches = [];\n // pam_krb5(sshd:auth): authentication failure; logname=root uid=0 euid=0 tty=ssh ruser= rhost=123.213.132.231\n // pam_krb5[sshd:auth]: authentication failure; logname=root uid=0 euid=0 tty=ssh ruser= rhost=123.213.132.231\n if (empty($entry['program']) and preg_match('#^(?P<program>([^(:]+\\([^)]+\\)|[^\\[:]+\\[[^\\]]+\\])) ?: ?(?P<msg>.*)$#', $entry['msg'], $matches)) {\n $entry['msg'] = $matches['msg'];\n $entry['program'] = $matches['program'];\n } elseif (empty($entry['program']) and ! empty($entry['facility'])) {\n // SYSLOG CONNECTION BROKEN; FD='6', SERVER='AF_INET(123.213.132.231:514)', time_reopen='60'\n // pam_krb5: authentication failure; logname=root uid=0 euid=0 tty=ssh ruser= rhost=123.213.132.231\n // Disabled because broke this:\n // diskio.c: don't know how to handle 10 request\n // elseif($pos = strpos($entry['msg'], ';') or $pos = strpos($entry['msg'], ':')) {\n // $entry['program'] = substr($entry['msg'], 0, $pos);\n // $entry['msg'] = substr($entry['msg'], $pos+1);\n // }\n // fallback, better than nothing...\n $entry['program'] = $entry['facility'];\n }\n\n unset($matches);\n } elseif ($os == 'procurve') {\n $matches = [];\n if (preg_match('/^(?P<program>[A-Za-z]+): {2}(?P<msg>.*)/', $entry['msg'], $matches)) {\n $entry['msg'] = $matches['msg'] . ' [' . $entry['program'] . ']';\n $entry['program'] = $matches['program'];\n }\n unset($matches);\n } elseif ($os == 'zywall') {\n // Zwwall sends messages without all the fields, so the offset is wrong\n $msg = preg_replace('/\" /', '\";', stripslashes($entry['program'] . ':' . $entry['msg']));\n $msg = str_getcsv($msg, ';');\n $entry['program'] = null;\n foreach ($msg as $param) {\n [$var, $val] = explode('=', $param);\n if ($var == 'cat') {\n $entry['program'] = str_replace('\"', '', $val);\n }\n }\n $entry['msg'] = join(' ', $msg);\n }//end if\n\n if (! isset($entry['program'])) {\n $entry['program'] = $entry['msg'];\n unset($entry['msg']);\n }\n\n $entry['program'] = strtoupper($entry['program']);\n $entry = array_map('trim', $entry);\n\n if ($update) {\n dbInsert(\n [\n 'device_id' => $entry['device_id'],\n 'program' => $entry['program'],\n 'facility' => $entry['facility'],\n 'priority' => $entry['priority'],\n 'level' => $entry['level'],\n 'tag' => $entry['tag'],\n 'msg' => $entry['msg'],\n 'timestamp' => $entry['timestamp'],\n ],\n 'syslog'\n );\n }\n\n unset($os);\n }//end if\n\n return $entry;\n}", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function handle()\n {\n $this->console->displaySectionHeader('Resources Added');\n\n $resources = $this->parent->getResources();\n\n if (count($resources) == 0) {\n $this->console->displayMessage('No resources have been added.');\n $this->console->displayBlankLine();\n }\n\n $availableTypes = XdmodConfiguration::assocArrayFactory('resource_types.json', CONFIG_DIR)['resource_types'];\n $availableResourceAllocationTypes = XdmodConfiguration::assocArrayFactory('resource_allocation_types.json', CONFIG_DIR)['resource_allocation_types'];\n\n foreach ($resources as $resource) {\n $specs = $this->getSpecsForResource($resource['resource']);\n\n // Look up the resource type in the list of available types\n\n $resourceType = 'UNK';\n foreach ( $availableTypes as $name => $type ) {\n if ( $name === $resource['resource_type'] ) {\n // Note that Console::prompt() expects lowercase values for options\n $resourceType = strtolower($name);\n break;\n }\n }\n\n $resourceAllocationType = 'UNK';\n foreach ( $availableResourceAllocationTypes as $name => $type ) {\n if ( $name === $resource['resource_allocation_type'] ) {\n // Note that Console::prompt() expects lowercase values for options\n $resourceAllocationType = strtolower($name);\n break;\n }\n }\n\n $cpu_nodes_message = isset($specs['cpu_node_count']) ? $specs['cpu_node_count'] : \"No value available for CPU Node Count. Please update the resource_specs.json file\";\n $cpu_processors_message = isset($specs['cpu_processor_count']) ? $specs['cpu_processor_count'] : \"No value available for CPU Processor Count. Please update the resource_specs.json file\";\n $gpu_nodes_message = isset($specs['gpu_node_count']) ? $specs['gpu_node_count'] : \"No value available for GPU Node Count. Please update the resource_specs.json file\";\n $gpu_processors_message = isset($specs['gpu_processor_count']) ? $specs['gpu_processor_count'] : \"No value available for GPU Processor Count. Please update the resource_specs.json file\";\n $start_date_message = isset($specs['start_date']) ? $specs['start_date'] : \"No value available for Start Date. Please update the resource_specs.json file\";\n\n\n $this->console->displayMessage('Resource: ' . $resource['resource']);\n $this->console->displayMessage('Name: ' . $resource['name']);\n $this->console->displayMessage('Type: ' . $resourceType);\n $this->console->displayMessage('Resource Allocation Type: ' . $resourceAllocationType);\n $this->console->displayMessage('CPU Node count: ' . $cpu_nodes_message);\n $this->console->displayMessage('CPU Processor count: ' . $cpu_processors_message);\n $this->console->displayMessage('GPU Node count: ' . $gpu_nodes_message);\n $this->console->displayMessage('GPU Processor count: ' . $gpu_processors_message);\n $this->console->displayMessage('Resource Start Date: ' . $start_date_message);\n $this->console->displayMessage(str_repeat('-', 72));\n $this->console->displayBlankLine();\n }\n\n $this->console->prompt('Press ENTER to continue.');\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public static function importRecords($filename, $params){\n\n self::initialize();\n\n $is_debug = @$params['dbg'] == 1;\n $session_id = @$params['session'];\n $is_cms_init = (@$params['is_cms_init']===true || @$params['is_cms_init']==1);\n $make_public = !(@$params['make_public']===false || @$_REQUEST['make_public']==0);\n $owner_id = @$params['onwer_id']>0 ?$params['onwer_id'] :1;\n $mapping_defs = @$params['mapping_defs'];\n\n $unique_field_id = @$params['unique_field_id'];\n $allow_insert = true;\n $update_mode = 1; //by default 1 - overwrite, if zero - no update allowed\n if($unique_field_id){\n $allow_insert = (@$params['allow_insert']==1 || @$params['allow_insert']===true);\n $update_mode = @$params['update_mode'];\n }\n\n $mysqli = self::$system->get_mysqli();\n\n //init progress\n mysql__update_progress($mysqli, $session_id, true, '0,1');\n\n\n $res = false;\n $cnt_imported = 0;\n $cnt_inserted = 0;\n $cnt_updated = 0;\n $cnt_ignored = 0;\n $ids_exist = array();\n $rec_ids_details_empty = array();\n $resource_notfound = array();//target id, source id, field name, value\n\n $home_page_id = 0;\n $page_id_for_blog = 0; //for cms init find record with DT_EXTENDED_DESCRIPTION=='BLOG TEMPLATE'\n\n $data = self::_readDataFile( $filename );\n\n self::$system->defineConstant('DT_ORIGINAL_RECORD_ID');\n\n if($data!=null){\n\n $value_cms_info = '';\n\n if($is_cms_init){\n self::$system->defineConstant('RT_CMS_HOME');\n self::$system->defineConstant('DT_EXTENDED_DESCRIPTION');\n $value_cms_info = <<<'EOD'\n<p>-----</p>\n<p>This is default content generated by the CMS function of the Heurist data management system (<a title=\"Heurist Academic Knowledge Management System\" href=\"https://heuristnetwork.org/\" target=\"_blank\" rel=\"noopener\">HeuristNetwork.org</a>).</p>\n<p>Please edit the content to create an appropriate page, or delete the menu entry and page if not required.</p>\n<p>Please see <a href=\"../context_help/website_instructions.htm\">Heurist CMS instructions</a> for further information.</p>\n<table style=\"border-collapse: collapse;margin-top:40px\" border=\"1\">\n<tbody>\n<tr>\n<td style=\"width: 100%; padding-left: 30px; padding-right: 30px;\">\n<p><strong><span style=\"color: #ff0000;\">If you come across this page with dummy content, please email the website owner </span></strong></p>\n<p><strong><span style=\"color: #ff0000;\">(link at top right) and ask them to update or delete the page.</span></strong></p>\n</td>\n</tr>\n</tbody>\n</table>\n<p> </p>\nEOD;\n }\n else{\n $make_public = true;\n }\n\n $execution_counter = 0;\n\n $tot_count = 0;\n if(is_array(@$data['heurist']['database']['records'])){\n $tot_count = count(@$data['heurist']['database']['records']);\n }\n if(!($tot_count>0)){\n $tot_count = count($data['heurist']['records']);\n }\n\n //init progress\n mysql__update_progress($mysqli, $session_id, false, '0,'.$tot_count);\n\n $imp_rectypes = $data['heurist']['database']['rectypes'];\n\n //need to copy files\n $source_url = @$data['heurist']['database']['url'];//base url of database\n $source_db = @$data['heurist']['database']['db'];//name of database\n\n ini_set('max_execution_time', '0');\n\n // if database not defined or the same\n // is the same it is assumed that all local codes in $data are already found and exists in\n // target database, elements without local codes or if not found will be ignored\n //$dbsource_is_same = defined('HEURIST_DBID') && ((!(@$data['heurist']['database']['id']>0)) ||\n // @$data['heurist']['database']['id']==HEURIST_DBID);\n\n $dbsource_is_registered = (@$data['heurist']['database']['id']>0);\n\n if(defined('HEURIST_DBID') && HEURIST_DBID>0){ //target is registered\n $dbsource_is_same = ( !$dbsource_is_registered ||\n @$data['heurist']['database']['id']==HEURIST_DBID);\n }else{\n\n if(!$dbsource_is_registered){\n //if source is not smae, definitions with conceptcodes 0000-xx will be imported with concept codes 9999-xxx\n $dbsource_is_same = ($params['same_source']==1);\n }else{\n //if source is registered - source is different\n $dbsource_is_same = !$dbsource_is_registered;\n }\n }\n\n\n if($dbsource_is_same){\n\n $defs = array(\n 'rectypes' => dbs_GetRectypeStructures(self::$system, null, 2),\n 'detailtypes' => dbs_GetDetailTypes(self::$system, null, 2),\n 'terms' => dbs_GetTerms(self::$system));\n\n }else{\n\n $importDef = new DbsImport( self::$system );\n\n $databaseURL = null;\n if($source_url){\n if(strpos($source_url,'?db=')>0){\n $databaseURL = $source_url;\n }elseif($source_db){\n $databaseURL = $source_url.'?db='.$source_db;\n }\n }\n\n if($mapping_defs!=null){\n\n //for import records by mapping we check and import affected vocabularies only\n $res2 = $importDef->doPrepare( array('defType'=>'term',\n 'databaseID'=>@$data['heurist']['database']['id'],\n 'databaseURL'=>$databaseURL,\n 'definitionID'=>$mapping_defs['vocabularies']));//array of vocabularies to be imported\n\n if($res2 && @$mapping_defs['import_vocabularies']==1){\n $res2 = $importDef->doImport();//sync/import vocabularies\n }\n\n if($res2){\n //mapping for fields and rectypes\n $importDef->doMapping($mapping_defs);//need for getTargetIdBySourceId\n $defs = $importDef->getDefinitions();//terms aready here (target defs)\n\n $defs['rectypes'] = dbs_GetRectypeStructures(self::$system, null, 2);\n $defs['detailtypes'] = dbs_GetDetailTypes(self::$system, null, 2);\n }\n\n\n }else{\n //Finds all defintions to be imported\n $res2 = $importDef->doPrepare( array('defType'=>'rectype',\n 'databaseID'=>@$data['heurist']['database']['id'],\n 'databaseURL'=>$databaseURL,\n 'definitionID'=>array_keys($imp_rectypes), //array of record type source ids\n 'rectypes'=>$imp_rectypes ));\n\n //get target definitions (this database)\n $defs = $importDef->getDefinitions();\n\n }\n\n $src_defs = $importDef->getDefinitions('source');\n if(@$src_defs['databaseURL']){\n $source_url = $src_defs['databaseURL'];\n }\n\n if(!$res2){\n $err = self::$system->getError();\n if($err && $err['status']!=HEURIST_NOT_FOUND){\n mysql__update_progress($mysqli, $session_id, false, 'REMOVE');\n return false;\n }\n self::$system->clearError();\n }\n\n }\n\n $def_dts = $defs['detailtypes']['typedefs'];\n $idx_type = $def_dts['fieldNamesToIndex']['dty_Type'];\n $idx_name = $def_dts['fieldNamesToIndex']['dty_Name'];\n $def_rst = $defs['rectypes']['typedefs'];\n $idx_parent = $def_rst['dtFieldNamesToIndex']['rst_CreateChildIfRecPtr'];\n\n $file_entity = new DbRecUploadedFiles(self::$system);\n $file_entity->setNeedTransaction(false);\n\n $records = $data['heurist']['records'];//records to be imported\n\n $records_corr_alphanum = array();\n $records_corr = array();//correspondance: source rec id -> target rec id\n $resource_fields = array();//source rec id -> field type id -> field value (target recid)\n $keep_rectypes = array();//keep rectypes for furhter rectitle update\n $recid_already_checked = array();//keep verified H-ID resource records\n\n $parent_child_links = array();//keep parent_id => child_id\n\n //term\n $enum_fields = array();//source rec id -> field type id -> field value (term label)\n $enum_fields_values = array();//rectype -> field id -> value\n\n $is_rollback = false;\n $keep_autocommit = mysql__begin_transaction($mysqli);\n mysql__foreign_check($mysqli, false);\n\n self::$system->defineConstant('DT_PARENT_ENTITY');\n\n $record_count = count($records);\n foreach($records as $record_src){\n\n $is_blog_record = false;\n\n if(!is_array($record_src) && $record_src>0){\n //this is record id - record data in the separate file\n //@todo\n }\n\n $record_src_original_id = null;\n if($record_src['rec_ID']){\n $record_src_original_id = ((@$data['heurist']['database']['id']>0)\n ?$data['heurist']['database']['id']:'0').'-'\n .$record_src['rec_ID'];\n }\n\n $target_RecID = 0;\n\n if($dbsource_is_same){\n $recTypeID = DbsImport::getLocalCode('rectypes', $defs,\n $record_src['rec_RecTypeID']>0\n ?$record_src['rec_RecTypeID']\n :$record_src['rec_RecTypeConceptID'], false);\n }elseif($mapping_defs!=null){\n\n $recTypeID = @$mapping_defs[$record_src['rec_RecTypeID']]['rty_ID'];\n\n //check that record already exists in\n //get key value from target\n if($recTypeID>0){\n $keyDty_ID = $mapping_defs[$record_src['rec_RecTypeID']]['key'];\n $key_value = $record_src['details'][$keyDty_ID];\n if(is_array($key_value)) {$key_value = array_shift($key_value);}\n\n //search in target\n $keyDty_ID = $mapping_defs[$record_src['rec_RecTypeID']]['details'][$keyDty_ID];\n $target_RecID = mysql__select_value($mysqli, 'select rec_ID from Records, recDetails where dtl_RecID=rec_ID '\n .' AND rec_RecTypeID='.$recTypeID.' AND dtl_DetailTypeID='.$keyDty_ID.' AND dtl_Value=\"'.$key_value.'\"');\n\n $target_RecID = intval($target_RecID);\n if($target_RecID>0){\n $ids_exist[] = $target_RecID;\n\n $records_corr[$record_src['rec_ID']] = $target_RecID;\n $keep_rectypes[$target_RecID] = $recTypeID;\n\n continue; //only insert allowed\n }else{\n $target_RecID = 0;\n }\n }else{\n $cnt_ignored++;\n continue;\n }\n\n }else{\n $recTypeID = $importDef->getTargetIdBySourceId('rectypes',\n $record_src['rec_RecTypeID']>0\n ?$record_src['rec_RecTypeID']\n :$record_src['rec_RecTypeConceptID']);\n }\n\n if($mapping_defs==null && $unique_field_id){\n //detect insert, update or skip\n\n $query3 = null;\n\n if($unique_field_id!='rec_ID'){\n //this is detail field\n if($dbsource_is_same){\n $local_id = DbsImport::getLocalCode('detailtypes', $defs, $unique_field_id, false);\n }else{\n $local_id = DbsImport::getLocalCode('detailtypes', $importDef->getDefinitions('source'), $unique_field_id, false);\n }\n\n\n\n foreach($record_src['details'] as $dty_ID => $values){\n\n if(is_array($values) && @$values['dty_ID']>0){ //interpreatable format\n $dty_ID = $values['dty_ID'];\n $values = array($values['value']);\n }\n\n if($dty_ID==$local_id && is_array($values)){\n $record_src_original_id = array_shift($values);\n break;\n }\n }\n }\n\n if($record_src_original_id){\n\n$query3 = 'select rec_ID from Records, recDetails where dtl_RecID=rec_ID AND dtl_DetailTypeID='.DT_ORIGINAL_RECORD_ID.' AND dtl_Value=\"'.$record_src_original_id.'\"';\n\n $target_RecID = mysql__select_value($mysqli, $query3);\n\n $target_RecID = intval($target_RecID);\n if($target_RecID>0){\n //already exists\n $ids_exist[] = $target_RecID;\n $records_corr[$record_src['rec_ID']] = $target_RecID;\n $keep_rectypes[$target_RecID] = $recTypeID;\n\n if(!($update_mode>0)) {continue;} //no update allowed\n\n }else{\n if(!$allow_insert) {continue;}\n $target_RecID = 0;\n }\n\n }\n\n }\n\n if(!($recTypeID>0)) {\n //skip this record - record type not found\n $cnt_ignored++;\n continue;\n }\n\n // prepare records - replace all fields, terms, record types to local ones\n // keep record IDs in resource (record pointer)) fields to replace them later\n $record = array();\n $record['ID'] = $target_RecID; //0 - add new\n $record['RecTypeID'] = $recTypeID;\n\n\n if(!@$record_src['rec_ID']){ //if not defined assign arbitrary unique\n $record_src['rec_ID'] = uniqid();\n }else {\n\n //in case source id is not numerics or more than MAX INT\n if((!ctype_digit($record_src['rec_ID'])) || strlen($record_src['rec_ID'])>9 ){ //4 957 948 868\n $rec_id_low = strtolower($record_src['rec_ID']);\n if(@$records_corr_alphanum[$rec_id_low]){ //aplhanum->random int\n $record_src['rec_ID'] = $records_corr_alphanum[$rec_id_low];\n }else{\n $rand_id = rand(900000000,999999999);//random_int\n $records_corr_alphanum[$rec_id_low] = $rand_id;\n $record_src['rec_ID'] = $rand_id;\n }\n }\n }\n\n\n $record['AddedByImport'] = 2; //import without strict validation\n $record['no_validation'] = true;\n $record['URL'] = @$record_src['rec_URL'];\n $record['URLLastVerified'] = @$record_src['rec_URLLastVerified'];\n $record['ScratchPad'] = @$record_src['rec_ScratchPad'];\n $record['Title'] = @$record_src['rec_Title'];\n\n\n $record['OwnerUGrpID'] = $owner_id;\n $record['NonOwnerVisibility'] = ($make_public)?'public':'viewable';\n\n $record['details'] = array();\n\n if(@$record_src['details']==null){\n array_push($rec_ids_details_empty, $record_src['rec_ID']);\n continue;\n }\n\n\n foreach($record_src['details'] as $dty_ID => $values){\n\n if(is_array($values) && @$values['dty_ID']>0){ //interpreatable format\n $dty_ID = $values['dty_ID'];\n $values = array($values['value']);\n }\n\n //field id in target database\n if($dbsource_is_same){\n //$dty_ID can be local id or concept code\n $ftId = DbsImport::getLocalCode('detailtypes', $defs, $dty_ID, false);\n }elseif($mapping_defs!=null){\n\n $ftId = @$mapping_defs[$record_src['rec_RecTypeID']]['details'][$dty_ID];\n\n }else{\n $ftId = $importDef->getTargetIdBySourceId('detailtypes', $dty_ID);\n }\n\n if(!($ftId>0)){\n //target not found - field is ignored\n //@todo - add to report\n continue;\n }\n if(!@$def_dts[$ftId]){\n //definitions not found\n //@todo - add to report\n continue;\n }\n if($dty_ID==self::$system->getConstant('DT_PARENT_ENTITY',0)){ //ignore\n continue;\n }\n\n\n $def_field = $def_dts[$ftId]['commonFields'];\n\n if($def_field[$idx_type] == \"relmarker\"){ //ignore\n continue;\n }\n\n $new_values = array();\n if($def_field[$idx_type] == \"enum\" ||\n $def_field[$idx_type] == \"relationtype\")\n {\n foreach($values as $value){\n //change terms ids for enum and reltypes\n if($dbsource_is_same){\n //by local id or concept code\n $termID = DbsImport::getLocalCode($def_field[$idx_type], $defs, $value, false);\n }else{\n $termID = $importDef->getTargetIdBySourceId($def_field[$idx_type], $value);\n }\n // if not numeric - it can be term code or term label\n $termID = self::validateEnumeration($recTypeID, $ftId,\n ($termID>0 ?$termID:$value), $defs);\n\n if($termID>0){\n $new_values[] = $termID;\n }else{\n //either not allowed or not found\n if(ctype_digit($value) || strpos($value,'-')>0){\n //not allowed\n //@todo - add to report\n continue;\n }else{\n\n //keep label value\n if(!@$enum_fields_values[$recTypeID]){\n $enum_fields_values[$recTypeID] = array();\n }\n if(!@$enum_fields_values[$recTypeID][$ftId]){\n $enum_fields_values[$recTypeID][$ftId] = array();\n }\n\n $uid = array_search($value, $enum_fields_values[$recTypeID][$ftId]);\n if($uid===false){\n $uid = uniqid();\n $enum_fields_values[$recTypeID][$ftId][$uid] = $value;\n }\n\n //save $uid as field value, it will be replaced to term id\n //after new terms will be added\n if(!@$enum_fields[$record_src['rec_ID']]){\n $enum_fields[$record_src['rec_ID']] = array();\n }\n if(!@$enum_fields[$record_src['rec_ID']][$ftId]){\n $enum_fields[$record_src['rec_ID']][$ftId] = array();\n }\n $enum_fields[$record_src['rec_ID']][$ftId][] = $uid;\n\n $new_values[] = $uid;\n }\n }\n //replaceTermIds( $value, $def_field[$idx_type] );\n }\n }elseif($def_field[$idx_type] == \"geo\"){\n\n foreach($values as $value){\n //geo\n $geotype = '';\n if (@$value['geo']['type']){\n $geotype = $value['geo']['type'].' ';\n }\n $new_values[] = $geotype.$value['geo']['wkt'];\n }\n\n }elseif($def_field[$idx_type] == \"file\"){\n\n //copy remote file to target filestore, register and get ulf_ID\n foreach($values as $value){\n\n $tmp_file = null;\n $value = $value['file'];\n $dtl_UploadedFileID = null;\n\n if(@$value['ulf_ExternalFileReference'] &&\n (strpos($value['ulf_ExternalFileReference'],'http://')===0\n || strpos($value['ulf_ExternalFileReference'],'https://')===0)){ //remote URL\n\n //detect mimetype\n $ext = recognizeMimeTypeFromURL($mysqli, $value['ulf_ExternalFileReference']);\n if(@$ext['extension']){\n $value['ulf_MimeExt'] = $ext['extension'];\n }\n\n if(@$value['ulf_ID']>0) {$value['ulf_ID']=0;}\n\n $fileinfo = array('entity'=>'recUploadedFiles', 'fields'=>$value);\n\n $file_entity->setData($fileinfo);\n $file_entity->setRecords(null);//reset\n $dtl_UploadedFileID = $file_entity->save();//register remote url - it returns ulf_ID\n\n }elseif(!$dbsource_is_same || !defined('HEURIST_DBID')) { //do not copy file for the same database\n\n //download to scratch folder\n\n $tmp_file = tempnam(HEURIST_SCRATCH_DIR, '_temp_');\n $newfilename = USanitize::sanitizeFileName($value['ulf_OrigFileName']);\n\n //source on the same server as target\n if(strpos($source_url, HEURIST_SERVER_URL)===0 && @$value['fullPath'])\n {\n if (file_exists(HEURIST_FILESTORE_ROOT.$source_db.'/'.$value['fullPath'])) {\n copy(HEURIST_FILESTORE_ROOT.$source_db.'/'.$value['fullPath'] , $tmp_file);\n }\n }\n else\n {\n //$fileURL = @$value['url'];\n if(strpos($source_url,'?db=')===false){\n $file_URL = $source_url.'?db='.$source_db;\n }else{\n $file_URL = $source_url;\n }\n $file_URL = $file_URL.'&file='.$value['ulf_ObfuscatedFileID'];//download\n saveURLasFile($file_URL, $tmp_file);//save imported image to temp file in scratch folder\n }\n\n //register imported image\n if(file_exists($tmp_file)){\n $dtl_UploadedFileID = $file_entity->registerFile($tmp_file, $newfilename);//it returns ulf_ID\n }\n\n\n }elseif($dbsource_is_same) {\n\n $dtl_UploadedFileID = array($value['ulf_ID']);\n }\n\n if($dtl_UploadedFileID!=null){\n if($dtl_UploadedFileID===false){\n $err_msg = self::$system->getError();\n $err_msg = $err_msg['message'];\n self::$system->clearError();\n $dtl_UploadedFileID = null;\n }else{\n $dtl_UploadedFileID = $dtl_UploadedFileID[0];\n $new_values[] = $dtl_UploadedFileID;\n }\n }\n\n if($tmp_file && file_exists($tmp_file)){\n unlink($tmp_file);\n }\n\n\n }\n\n }\n elseif($def_field[$idx_type] == \"resource\"){\n\n $new_values = array();\n //keep source record id to replace it to new target record id\n if(!@$resource_fields[$record_src['rec_ID']]){\n $resource_fields[$record_src['rec_ID']] = array();\n }\n if(!@$resource_fields[$record_src['rec_ID']][$ftId]){\n $resource_fields[$record_src['rec_ID']][$ftId] = array();\n }\n $is_parent = false;\n if(@$def_rst[$recTypeID]['dtFields'][$ftId]!=null){\n $is_parent = ($def_rst[$recTypeID]['dtFields'][$ftId][$idx_parent]==1);\n }\n\n\n foreach($values as $value){\n\n $resourse_id = null;\n\n if(is_array($value)){\n $value = $value['id'];\n }\n if(strpos($value,'H-ID-')===0){ //there is such id in target\n $value = substr($value,5);\n\n if($recid_already_checked[$value]){\n $resourse_id = $value;\n }else\n if(is_numeric($value) && $value>0){\n //check existence\n $is_found = (mysql__select_value($mysqli,\n 'select rec_ID from Records where rec_ID='\n .$value)>0);\n if($is_found){\n $recid_already_checked[] = $value;\n $resourse_id = $value;\n }else{\n $resource_notfound[] = array(0, $record_src['rec_ID'], $def_field[$idx_name], 'H-ID-'.$value);\n }\n }\n\n }else{\n\n if((!ctype_digit($value)) || strlen($value)>9 ){ //8 724 803 625\n\n $rec_id_low = strtolower($value);\n if(@$records_corr_alphanum[$rec_id_low]){\n $value = $records_corr_alphanum[$rec_id_low];\n }else{\n $rand_id = rand(900000000,999999999);//was random_int\n $records_corr_alphanum[$rec_id_low] = $rand_id;\n $value = $rand_id;\n }\n }\n $resource_fields[$record_src['rec_ID']][$ftId][] = $value;\n $resourse_id = $value;\n }\n\n if($resourse_id!=null){\n $new_values[] = $resourse_id;\n if($is_parent && $record_src['rec_ID']!=null){\n $parent_child_links[] = array('parent'=>$record_src['rec_ID'], 'child'=>$resourse_id);\n }\n }\n\n }\n//\"2552\":{\"7462\":{\"id\":\"1326\",\"type\":\"98\",\"title\":\"Record to imported\",\"hhash\":null}}}\n }else{\n\n $new_values = $values;\n }\n\n if(!isEmptyArray($new_values))\n {\n if (isset($record['details'][$ftId])){\n array_push($record['details'][$ftId], ...$new_values);\n }else{\n $record['details'][$ftId] = $new_values;\n }\n\n if($is_cms_init && $dty_ID == DT_EXTENDED_DESCRIPTION && $new_values[0]=='BLOG TEMPLATE'){\n $is_blog_record = true;\n }\n }\n\n }//for details\n\n\n //keep original id\n if(defined('DT_ORIGINAL_RECORD_ID') && $record_src_original_id!=null){\n if(!is_array(@$record['details'][DT_ORIGINAL_RECORD_ID])){\n $record['details'][DT_ORIGINAL_RECORD_ID] = array();\n }\n $record['details'][DT_ORIGINAL_RECORD_ID][] = $record_src_original_id;\n }\n\n // note: we need to suppress creation of reverse 247 pointer for parent-child links\n\n //no transaction, suppress parent-child\n $out = recordSave(self::$system, $record, false, true, $update_mode, $record_count);//see recordModify.php\n\n if ( @$out['status'] != HEURIST_OK ) {\n $is_rollback = true;\n break;\n }\n\n //source rec id => target rec id\n $new_rec_id = intval($out['data']);//new record id\n $records_corr[$record_src['rec_ID']] = $new_rec_id;\n $keep_rectypes[$new_rec_id] = $record['RecTypeID'];\n\n if($is_cms_init){\n if($is_blog_record){\n $page_id_for_blog = $new_rec_id;\n }\n if($record['RecTypeID']==RT_CMS_HOME){\n $home_page_id = $new_rec_id;\n }\n }\n\n $execution_counter++;\n\n if($session_id!=null){\n $session_val = $execution_counter.','.$tot_count;\n $current_val = null;\n //check for termination and set new value\n if ($execution_counter % 100 == 0) { //(intdiv($execution_counter,100) == $execution_counter/100){\n $current_val = mysql__update_progress($mysqli, $session_id, false, $session_val);\n }\n\n if($current_val && $current_val=='terminate'){ //session was terminated from client side\n //need rollback\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Operation has been terminatated');\n $is_rollback = true;\n break;\n }\n }\n $cnt_imported++;\n\n if($target_RecID==0){\n $cnt_inserted++;\n }else{\n $cnt_updated++;\n }\n\n\n }//records\n\n if(!$is_rollback){\n\n //import new terms\n $new_terms = array();\n foreach ($enum_fields_values as $recTypeID=>$fields){\n foreach ($fields as $fieldtype_id=>$values){\n foreach ($values as $uid=>$term_label){\n\n //add new term\n $new_term_id = self::addNewTerm($recTypeID, $fieldtype_id, $term_label, $defs);\n //add new term id to correspondance array\n $new_terms[$uid] = $new_term_id;\n }\n }\n }\n //replace temp uniqid in records to new term ids\n foreach ($enum_fields as $src_recid=>$fields){\n //get new id in target db\n $trg_recid = @$records_corr[$src_recid];//source rec id -> target rec id\n if($trg_recid>0){\n foreach ($fields as $fieldtype_id=>$values){\n foreach ($values as $idx=>$uid){\n\n //get new terms id\n $term_id = @$new_terms[$uid];\n\n if($term_id>0){\n$query = \"UPDATE recDetails SET dtl_Value=$term_id WHERE dtl_RecID=$trg_recid AND dtl_DetailTypeID=$fieldtype_id AND dtl_Value='$uid'\";\n\n }else{\n //new terms was not added\n$query = \"DELETE FROM recDetails WHERE dtl_RecID=$trg_recid AND dtl_DetailTypeID=$fieldtype_id AND dtl_Value='$uid'\";\n }\n\n $ret = mysql__exec_param_query($mysqli, $query, null);\n if($ret!==true){\n self::$system->addError(HEURIST_DB_ERROR, 'Cannot update term fields', 'Query:'.$query.'. '.$ret);\n $is_rollback = true;\n break;\n }\n }\n }\n }\n }\n\n if(!$is_rollback){\n\n //set target id for $resource_notfound\n foreach ($resource_notfound as $idx=>$item){\n $resource_notfound[$idx][0] = @$records_corr[$item[1]];\n }\n\n //update resource (record pointer) fields with new record ids\n foreach ($resource_fields as $src_recid=>$fields){ //src recid => dty ids\n\n //get new id in target db\n $trg_recid = @$records_corr[$src_recid];//source rec id -> target rec id\n if($trg_recid>0){\n foreach ($fields as $fieldtype_id=>$old_values){\n foreach ($old_values as $old_value){\n //get new id in target db\n $query = null;\n $new_value = @$records_corr[$old_value];\n if($new_value>0){\n$query = \"UPDATE recDetails SET dtl_Value=$new_value WHERE dtl_RecID=$trg_recid AND dtl_DetailTypeID=$fieldtype_id AND dtl_Value=$old_value\";\n\n }elseif($old_value>0){\n //target record not found\n$query = \"DELETE FROM recDetails WHERE dtl_RecID=$trg_recid AND dtl_DetailTypeID=$fieldtype_id AND dtl_Value=$old_value\";\n\n $resource_notfound[] = array($trg_recid, $src_recid,\n $def_dts[$fieldtype_id]['commonFields'][$idx_name], $old_value);\n }\n if($query!=null){\n $ret = mysql__exec_param_query($mysqli, $query, null);\n if($ret!==true){\n self::$system->addError(HEURIST_DB_ERROR, 'Cannot update record pointer fields', 'Query:'.$query.'. '.$ret);\n $is_rollback = true;\n break;\n }\n }\n }\n }//for\n }\n }//for\n }\n //create reverse child to parent links if required\n if(!$is_rollback && !isEmptyArray($parent_child_links)){\n\n foreach($parent_child_links as $idx=>$link){\n\n $parent_id = $link['parent'];\n $child_id = $link['child'];\n\n $child_id = @$records_corr[$child_id];\n $parent_id = @$records_corr[$parent_id];\n\n if($parent_id>0 && $child_id>0){\n $res = addReverseChildToParentPointer($mysqli, $child_id, $parent_id, 1, false);\n\n if($res<0){\n $syserror = $mysqli->error;\n self::$system->addError(HEURIST_DB_ERROR, 'Cannot insert reverse pointer for child record', $syserror);\n $is_rollback = true;\n break;\n }\n }\n }//for\n }\n if(!$is_rollback){\n $idx_mask = $defs['rectypes']['typedefs']['commonNamesToIndex']['rty_TitleMask'];\n //update record title\n foreach ($keep_rectypes as $rec_id=>$rty_id){\n $mask = @$defs['rectypes']['typedefs'][$rty_id]['commonFields'][$idx_mask];\n recordUpdateTitle(self::$system, $rec_id, $mask, null);\n }\n\n //update special concept codes 9999-xxx to correct ones\n DbUtils::updateImportedOriginatingDB();\n }\n }\n\n if($is_rollback){\n $mysqli->rollback();\n if($keep_autocommit===true) {$mysqli->autocommit(TRUE);}\n $res = false;\n }else{\n $mysqli->commit();\n if($keep_autocommit===true) {$mysqli->autocommit(TRUE);}\n $res = array('count_imported'=>$cnt_imported,\n 'count_ignored'=>$cnt_ignored, //rectype not found\n 'count_inserted'=>$cnt_inserted,\n 'count_updated'=>$cnt_updated,\n 'cnt_exist'=>count($ids_exist), //such record already exists\n 'details_empty'=>$rec_ids_details_empty,\n 'home_page_id'=>$home_page_id,\n 'page_id_for_blog'=>$page_id_for_blog,\n 'resource_notfound'=>$resource_notfound );//if value is H-ID-nnn\n if(count($records_corr)<1000){\n $res['ids'] = array_values($records_corr);\n }\n if(count($ids_exist)<1000){\n $res['exists'] = $ids_exist;\n }\n }\n mysql__foreign_check($mysqli, true);\n\n }//$data\n\n //finish progress session\n mysql__update_progress($mysqli, $session_id, false, 'REMOVE');\n\n return $res;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "protected function updateComments(): void\n {\n $comments = $this->input['_comments'] ?? [];\n\n // Keep track of comments found\n $found_comments = [];\n\n // Parse each submitted comment\n foreach ($comments as $comment_data) {\n $comment = new Comment();\n\n if ($comment_data[\"_use_uuid_for_sections_id\"]) {\n // This question was added to a newly created section\n // We need to find the correct section id using the temporary UUID\n $uuid = $comment_data['forms_sections_id'];\n $comment_data['forms_sections_id'] = $_SESSION['form_editor_sections_uuid'][$uuid] ?? 0;\n }\n\n // Newly created comment, may need to be updated using temporary UUID instead of ID\n if ($comment_data['_use_uuid']) {\n $uuid = $comment_data['id'];\n $comment_data['id'] = $_SESSION['form_editor_comments_uuid'][$uuid] ?? 0;\n } else {\n $uuid = null;\n }\n\n if ($comment_data['id'] == 0) {\n // Add new comment\n unset($comment_data['id']);\n $id = $comment->add($comment_data);\n\n if (!$id) {\n throw new \\RuntimeException(\"Failed to add comment\");\n }\n\n // Store temporary UUID -> ID mapping in session\n if ($uuid !== null) {\n $_SESSION['form_editor_comments_uuid'][$uuid] = $id;\n }\n } else {\n // Update existing comment\n $success = $comment->update($comment_data);\n if (!$success) {\n throw new \\RuntimeException(\"Failed to update comment\");\n }\n $id = $comment->getID();\n }\n\n // Keep track of its id\n $found_comments[] = $id;\n }\n\n // Deletion will be handled in a separate method\n $this->input['_found_comments'] = $found_comments;\n\n // Special input has been handled, it can be deleted\n unset($this->input['_comments']);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function _normalizeOptions(array $options = []): array\n {\n // Ident\n if (isset($options['indent'])) {\n $options['indent'] = $this->_getWhitespace($options['indent']);\n } else {\n $options['indent'] = $this->getIndent();\n }\n\n // Inner ident\n if (isset($options['innerIndent'])) {\n $options['innerIndent'] =\n $this->_getWhitespace($options['innerIndent']);\n } else {\n $options['innerIndent'] = $this->getInnerIndent();\n }\n\n // UL class\n if (isset($options['ulClass']) && $options['ulClass'] !== null) {\n $options['ulClass'] = $options['ulClass'];\n } else {\n $options['ulClass'] = $this->getUlClass();\n }\n\n // UL id\n if (isset($options['ulId']) && $options['ulId'] !== null) {\n $options['ulId'] = (string) $options['ulId'];\n } else {\n $options['ulId'] = $this->getUlId();\n }\n\n // Active class\n if (isset($options['activeClass']) && $options['activeClass'] !== null\n ) {\n $options['activeClass'] = (string) $options['activeClass'];\n } else {\n $options['activeClass'] = $this->getActiveClass();\n }\n\n // Parent class\n if (isset($options['parentClass']) && $options['parentClass'] !== null) {\n $options['parentClass'] = (string) $options['parentClass'];\n } else {\n $options['parentClass'] = $this->getParentClass();\n }\n\n // Minimum depth\n if (array_key_exists('minDepth', $options)) {\n if (null !== $options['minDepth']) {\n $options['minDepth'] = (int) $options['minDepth'];\n }\n } else {\n $options['minDepth'] = $this->getMinDepth();\n }\n\n if ($options['minDepth'] < 0 || $options['minDepth'] === null) {\n $options['minDepth'] = 0;\n }\n\n // Maximum depth\n if (array_key_exists('maxDepth', $options)) {\n if (null !== $options['maxDepth']) {\n $options['maxDepth'] = (int) $options['maxDepth'];\n }\n } else {\n $options['maxDepth'] = $this->getMaxDepth();\n }\n\n // Only active branch\n if (!isset($options['onlyActiveBranch'])) {\n $options['onlyActiveBranch'] = $this->getOnlyActiveBranch();\n }\n\n // Expand sibling nodes of active branch\n if (!isset($options['expandSiblingNodesOfActiveBranch'])) {\n $options['expandSiblingNodesOfActiveBranch'] = $this->getExpandSiblingNodesOfActiveBranch();\n }\n\n // Render parents?\n if (!isset($options['renderParents'])) {\n $options['renderParents'] = $this->getRenderParents();\n }\n\n // Render parent class?\n if (!isset($options['renderParentClass'])) {\n $options['renderParentClass'] = $this->getRenderParentClass();\n }\n\n // Add page CSS class to LI element\n if (!isset($options['addPageClassToLi'])) {\n $options['addPageClassToLi'] = $this->getAddPageClassToLi();\n }\n\n return $options;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getSearchOptionsToAdd($itemtype = null)\n {\n $options = [];\n\n $classname = get_called_class();\n $method_name = 'rawSearchOptionsToAdd';\n if (!method_exists($classname, $method_name)) {\n return $options;\n }\n\n if (defined('TU_USER') && $itemtype != null && $itemtype != AllAssets::getType()) {\n $item = new $itemtype();\n $all_options = $item->searchOptions();\n }\n\n foreach ($classname::$method_name($itemtype) as $opt) {\n // FIXME In GLPI 11.0, trigger a warning on invalid datatype (see `tests\\units\\Search::testSearchOptionsDatatype()`)\n\n if (!isset($opt['id'])) {\n throw new \\Exception(get_called_class() . ': invalid search option! ' . print_r($opt, true));\n }\n $optid = $opt['id'];\n unset($opt['id']);\n\n if (defined('TU_USER') && $itemtype != null) {\n if (isset($all_options[$optid])) {\n $message = \"Duplicate key $optid ({$all_options[$optid]['name']}/{$opt['name']}) in \" .\n self::class . \" searchOptionsToAdd for $itemtype!\";\n\n trigger_error($message, E_USER_WARNING);\n }\n }\n\n foreach ($opt as $k => $v) {\n $options[$optid][$k] = $v;\n if (defined('TU_USER') && $itemtype != null) {\n $all_options[$optid][$k] = $v;\n }\n }\n }\n\n return $options;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected function update(array $params = []): void\n {\n $storage = Storage::get('asset');\n $this->updateModificationInfos();\n\n $path = $this->getRealFullPath();\n $typeChanged = false;\n\n if ($this->getType() != 'folder') {\n if ($this->getDataChanged()) {\n $src = $this->getStream();\n\n if (!$storage->fileExists($path) || !stream_is_local($storage->readStream($path))) {\n // write stream directly if target file doesn't exist or if target is a remote storage\n // this is because we don't have hardlinks there, so we don't need to consider them (see below)\n $storage->writeStream($path, $src);\n } else {\n // We don't open a stream on existing files, because they could be possibly used by versions\n // using hardlinks, so it's safer to write them to a temp file first, so the inode and therefore\n // also the versioning information persists. Using the stream on the existing file would overwrite the\n // contents of the inode and therefore leads to wrong version data\n $pathInfo = pathinfo($this->getFilename());\n $tempFilePath = $this->getRealPath() . uniqid('temp_');\n if ($pathInfo['extension'] ?? false) {\n $tempFilePath .= '.' . $pathInfo['extension'];\n }\n\n $storage->writeStream($tempFilePath, $src);\n $storage->delete($path);\n $storage->move($tempFilePath, $path);\n }\n\n //generate & save checksum in custom settings\n $this->generateChecksum();\n\n // delete old legacy file if exists\n $dbPath = $this->getDao()->getCurrentFullPath();\n if ($dbPath !== $path && $storage->fileExists($dbPath)) {\n $storage->delete($dbPath);\n }\n\n $this->closeStream(); // set stream to null, so that the source stream isn't used anymore after saving\n\n try {\n $mimeType = $storage->mimeType($path);\n } catch (UnableToRetrieveMetadata $e) {\n $mimeType = 'application/octet-stream';\n }\n $this->setMimeType($mimeType);\n\n // set type\n $type = self::getTypeFromMimeMapping($mimeType, $this->getFilename());\n if ($type != $this->getType()) {\n $this->setType($type);\n $typeChanged = true;\n }\n\n // not only check if the type is set but also if the implementation can be found\n $className = Pimcore::getContainer()->get('pimcore.class.resolver.asset')->resolve($type);\n\n if (!self::getModelFactory()->supports($className)) {\n throw new Exception('unable to resolve asset implementation with type: ' . $this->getType());\n }\n }\n } else {\n $storage->createDirectory($path);\n }\n\n if (!$this->getType()) {\n $this->setType('unknown');\n }\n\n $this->postPersistData();\n\n if ($this->isFieldDirty('properties')) {\n // save properties\n $properties = $this->getProperties();\n $this->getDao()->deleteAllProperties();\n foreach ($properties as $property) {\n if (!$property->getInherited()) {\n $property->setDao(null);\n $property->setCid($this->getId());\n $property->setCtype('asset');\n $property->setCpath($this->getRealFullPath());\n $property->save();\n }\n }\n }\n\n $this->getDao()->update();\n\n // set asset to registry\n $cacheKey = self::getCacheKey($this->getId());\n RuntimeCache::set($cacheKey, $this);\n if (static::class === Asset::class || $typeChanged) {\n // get concrete type of asset\n // this is important because at the time of creating an asset it's not clear which type (resp. class) it will have\n // the type (image, document, ...) depends on the mime-type\n RuntimeCache::set($cacheKey, null);\n Asset::getById($this->getId()); // call it to load it to the runtime cache again\n }\n\n $this->closeStream();\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function graphdrawit($pos,$g,$op) {\n\tif (!isset($op['width'])) {$op['width'] = 360;}\n\tif (!isset($op['height'])) {$op['height'] = 300;}\n\tif (!isset($op['weightoffset'])) { $op['weightoffset'] = .5; }\n if (isset($op['labels']) && is_array($op['labels']) && count($op['labels']) < count($g)) {\n echo \"insufficient labels for all vertices\";\n $op['labels'] = \"letters\";\n }\n\t$n = count($pos);\n\tif (!isset($op['xmin'])) {\n\t\t$pxmin = 10000; $pxmax = -10000; $pymin = 10000; $pymax = -10000;\n\t\tfor ($i=0; $i<$n; $i++) {\n\t\t\tif ($pos[$i][0]<$pxmin) {$pxmin = $pos[$i][0];}\n\t\t\tif ($pos[$i][0]>$pxmax) {$pxmax = $pos[$i][0];}\n\t\t\tif ($pos[$i][1]<$pymin) {$pymin = $pos[$i][1];}\n\t\t\tif ($pos[$i][1]>$pymax) {$pymax = $pos[$i][1];}\n\t\t}\n\t\t$op['xmin'] = $pxmin;\n\t\t$op['xmax'] = $pxmax;\n\t\t$op['ymin'] = $pymin;\n\t\t$op['ymax'] = $pymax;\n\t}\n\n\t$lettersarray = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');\n\t$com = \"setBorder(60,30,60,30);initPicture({$op['xmin']},{$op['xmax']},{$op['ymin']},{$op['ymax']}); fontsize=14;\";\n\t$cx = ($op['xmin'] + $op['xmax'])/2;\n\t$cy = ($op['ymin'] + $op['ymax'])/2;\n\n\t$com .= \"fontstyle='none';\";\n\tif (!empty($op['digraph'])) {\n\t\t$com .= 'marker=\"arrow\";';\n\t} else {\n\t\t$com .= 'marker=null;';\n\t}\n \n\tfor ($i=0; $i<$n; $i++) {\n\t\tfor ($j=$i+1; $j<$n; $j++) {\n\t\t\tif (!empty($op['digraph'])) {\n\t\t\t\tif ((isset($g[$j][$i]) && $g[$j][$i]>0) && (!isset($g[$i][$j]) || $g[$i][$j]<=0)) {\n\t\t\t\t\t$com .= \"line([\".$pos[$j][0].\",\".$pos[$j][1].\"],[\".$pos[$i][0].\",\".$pos[$i][1].\"]);\";\n\t\t\t\t} else if ((isset($g[$i][$j]) && $g[$i][$j]>0) && (!isset($g[$j][$i]) || $g[$j][$i]<=0)) {\n\t\t\t\t\t$com .= \"line([\".$pos[$i][0].\",\".$pos[$i][1].\"],[\".$pos[$j][0].\",\".$pos[$j][1].\"]);\";\n\t\t\t\t} else if ((isset($g[$i][$j]) && $g[$i][$j]>0) && (isset($g[$j][$i]) && $g[$j][$i]>0)) {\n\t\t\t\t\t$com .= \"line([\".$pos[$j][0].\",\".$pos[$j][1].\"],[\".$pos[$i][0].\",\".$pos[$i][1].\"]);line([\".$pos[$i][0].\",\".$pos[$i][1].\"],[\".$pos[$j][0].\",\".$pos[$j][1].\"]);\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ((isset($g[$i][$j]) && $g[$i][$j]>0) || (isset($g[$j][$i]) && $g[$j][$i]>0)) {\n\t\t\t\t\t$com .= \"line([\".$pos[$i][0].\",\".$pos[$i][1].\"],[\".$pos[$j][0].\",\".$pos[$j][1].\"]);\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t$com .= \"fontbackground='white';\";\n\tfor ($i=0; $i<$n; $i++) {\n\t\tif (isset($op['labels'])) {\n\t\t\tif (isset($op['labelposition'])) {\n\t\t\t\t$ps = $op['labelposition'];\n\t\t\t} else {\n\t\t\t\tif ($pos[$i][1]>$cy) { $ps = \"above\"; } else {$ps = \"below\";}\n\t\t\t\tif ($pos[$i][0]>$cx) { $ps .= \"right\"; } else {$ps .= \"left\";}\n\t\t\t}\n\t\t\tif (is_array($op['labels'])) {\n\t\t\t\t$com .= \"fontfill='blue';text([\".$pos[$i][0].\",\".$pos[$i][1].\"],'\".$op['labels'][$i].\"','$ps');\";\n\t\t\t} else {\n\t\t\t\t$com .= \"fontfill='blue';text([\".$pos[$i][0].\",\".$pos[$i][1].\"],'\".$lettersarray[$i].\"','$ps');\";\n\t\t\t}\n\t\t}\n\t\t$com .= \"dot([\".$pos[$i][0].\",\".$pos[$i][1].\"]);\";\n\t\tfor ($j=$i+1; $j<$n; $j++) {\n\t\t\tif (!empty($op['useweights']) && ((isset($g[$i][$j]) && $g[$i][$j]>0) || (isset($g[$j][$i]) && $g[$j][$i]>0))) {\n\t\t\t\tif (($i+$j)%2==0) {\n\t\t\t\t\t$mx = $pos[$j][0] + ($pos[$i][0] - $pos[$j][0])*($op['weightoffset']);\n\t\t\t\t\t$my = $pos[$j][1] + ($pos[$i][1] - $pos[$j][1])*($op['weightoffset']);\n\t\t\t\t} else {\n\t\t\t\t\t$mx = $pos[$j][0] + ($pos[$i][0] - $pos[$j][0])*(1-$op['weightoffset']);\n\t\t\t\t\t$my = $pos[$j][1] + ($pos[$i][1] - $pos[$j][1])*(1-$op['weightoffset']);\n\t\t\t\t}\n\t\t\t\t$com .= \"fontfill='red';text([$mx,$my],'\".max($g[$i][$j],$g[$j][$i]).\"');\";\n\n\t\t\t}\n\t\t}\n\t}\n\treturn showasciisvg($com,$op['width'],$op['height']);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function generate_hl7($fromDate, $toDate, $code_selected, $provider_selected, $start, $end)\n {\n $records = array();\n $query_string = array();\n\n $query = \"SELECT c.code_text,l.pid AS patientid,p.language,l.diagnosis,\n\t\t\tDATE_FORMAT(p.DOB,'%Y%m%d') as DOB, concat(p.street, '^',p.postal_code,'^', p.city, '^', p.state) as address,\n\t\t\tp.country_code, p.phone_home, p.phone_biz, p.status, p.sex, p.ethnoracial,p.county, c.code_text, c.code, c.code_type, DATE_FORMAT(l.date,'%Y%m%d') as issuedate,\n\t\t\tconcat(p.fname, '^',p.mname,'^', p.lname) as patientname, l.id AS issueid,l.title AS issuetitle,fac.name,fac.facility_npi,p.race,p.ethnicity,p.postal_code,fe.encounter\n\t\t\tFROM\n\t\t\t lists l, patient_data p, codes c, form_encounter AS fe\n LEFT JOIN facility AS fac ON fac.id = fe.facility_id\n\t\t\tWHERE c.reportable = 1 \";\n\n if ($provider_selected) {\n $query .= \" AND provider_id = ? \";\n $query_string[] = $provider_selected;\n }\n\n $query .= \" AND l.id NOT IN\n\t\t\t(SELECT\n\t\t\t lists_id\n\t\t\tFROM\n\t\t\t syndromic_surveillance)\n\t\t\tAND l.date >= ? AND l.date <= ? AND l.pid = p.pid \";\n $query_string[] = $fromDate;\n $query_string[] = $toDate;\n\n if ($code_selected) {\n $query .= \" AND c.id IN (?) \";\n $query_string[] = implode(',', $code_selected);\n }\n\n $query .= \" AND l.diagnosis LIKE 'ICD9:%'\n\t\t\t\tAND ( SUBSTRING(l.diagnosis, 6) = c.code || SUBSTRING(l.diagnosis, 6) = CONCAT_WS('', c.code, ';') )\n\t\t\t\tAND fe.pid = l.pid\n\t\t\t UNION DISTINCT\n\t\t\t SELECT c.code_text, b.pid AS patientid, p.language, b.code, DATE_FORMAT(p.DOB,'%Y%m%d') as DOB,\n\t\t\t\t concat(p.street, '^',p.postal_code,'^', p.city, '^', p.state) as address, p.country_code, p.phone_home, p.phone_biz, p.status,\n\t\t\t\t p.sex, p.ethnoracial,p.county, c.code_text, c.code, c.code_type, DATE_FORMAT(fe.date,'%Y%m%d') as issuedate, concat(p.fname, '^',p.mname,'^', p.lname) as patientname,\n\t\t\t\t b.id AS issueid, '' AS issuetitle ,fac.name,fac.facility_npi,p.race,p.ethnicity,p.postal_code,fe.encounter\n\t\t\t FROM\n\t\t\t\tbilling b, patient_data p, codes c, form_encounter fe\n LEFT JOIN facility AS fac ON fac.id = fe.facility_id\n\t\t\t WHERE c.reportable = 1\n\t\t\t\tAND b.code_type = 'ICD9' AND b.activity = '1' AND b.pid = p.pid AND fe.encounter = b.encounter \";\n\n if ($code_selected) {\n $query .= \" AND c.id IN (?) \";\n $query_string[] = implode(',', $code_selected);\n }\n\n $query .= \" AND c.code = b.code\n\t\t AND fe.date IN\n\t\t (SELECT\n\t\t\tMAX(fenc.date)\n\t\t FROM\n\t\t\tform_encounter AS fenc\n\t\t WHERE fenc.pid = fe.pid) \";\n\n if ($provider_selected) {\n $query .= \" AND provider_id = ? \";\n $query_string[] = $provider_selected;\n }\n\n $query .= \" AND fe.date >= ? AND fe.date <= ?\";\n $query_string[] = $fromDate;\n $query_string[] = $toDate;\n\n $content = '';\n\n $appTable = new ApplicationTable();\n $result = $appTable->zQuery($query, $query_string);\n\n $D = \"\\r\";\n $nowdate = date('YmdHis');\n $now = date('YmdGi');\n $now1 = date('Y-m-d G:i');\n $filename = \"syn_sur_\" . $now . \".hl7\";\n\n foreach ($result as $r) {\n $fac_name = $race_code = $ethnicity_code = $county_code = '';\n $o_query = \"SELECT * FROM `form_observation` WHERE `encounter` = ? AND `pid` = ? AND `activity` = ?\" ;\n $o_result = $appTable->zQuery($o_query, array($r['encounter'],$r['patientid'],1));\n $fac_name = preg_replace('/\\s+/', '', $r['name']);\n $race_code = $this->getCodes($r['race'], 'race');\n $ethnicity_code = $this->getCodes($r['ethnicity'], 'ethnicity');\n $county_code = $this->getCodes($r['county'], 'county');\n $content .= \"MSH|^~\\&|OPENEMR|\" . $fac_name . \"^\" . $r['facility_npi'] . \"^NPI|||\" . $nowdate . \"||\" .\n \"ADT^A04^ADT_A01|NIST-SS-TC-XXX.XX|P^T|2.5.1|||||||||PH_SS-NoAck^SS Sender^2.16.840.1.114222.4.10.3^ISO$D\";\n $content .= \"EVN|\" . // [[ 3.69 ]]\n \"|\" . // 1.B Event Type Code\n \"$nowdate|\" . // 2.R Recorded Date/Time\n \"|\" . // 3. Date/Time Planned Event\n \"|\" . // 4. Event Reason Cod\n \"|\" . // 5. Operator ID\n \"|\" . // 6. Event Occurred\n $fac_name . \"^\" . $r['facility_npi'] . \"^NPI\" . // 7. Event Facility\n \"$D\" ;\n if ($r['sex'] === 'Male') {\n $r['sex'] = 'M';\n }\n\n if ($r['sex'] === 'Female') {\n $r['sex'] = 'F';\n }\n\n if ($r['status'] === 'married') {\n $r['status'] = 'M';\n }\n\n if ($r['status'] === 'single') {\n $r['status'] = 'S';\n }\n\n if ($r['status'] === 'divorced') {\n $r['status'] = 'D';\n }\n\n if ($r['status'] === 'widowed') {\n $r['status'] = 'W';\n }\n\n if ($r['status'] === 'separated') {\n $r['status'] = 'A';\n }\n\n if ($r['status'] === 'domestic partner') {\n $r['status'] = 'P';\n }\n\n $content .= \"PID|\" . // [[ 3.72 ]]\n \"1|\" . // 1. Set id\n \"|\" . // 2. (B)Patient id\n $r['patientid'] . \"^^^^MR|\" . // 3. (R) Patient identifier list\n \"|\" . // 4. (B) Alternate PID\n \"^^^^^^~^^^^^^S|\" . // 5.R. Name\n \"|\" . // 6. Mather Maiden Name\n $r['DOB'] . \"|\" . // 7. Date, time of birth\n $r['sex'] . \"|\" . // 8. Sex\n \"|\" . // 9.B Patient Alias\n $race_code . \"^^CDCREC|\" . // 10. Race\n \"^^^^\" . $r['postal_code'] . \"^^^^\" . $county_code . \"|\" . // 11. Address\n \"|\" . // 12. county code\n $r['phone_home'] . \"|\" . // 13. Phone Home\n $r['phone_biz'] . \"|\" . // 14. Phone Bussines\n \"|\" . // 15. Primary language\n $r['status'] . \"|\" . // 16. Marital status\n \"|\" . // 17. Religion\n \"|\" . // 18. patient Account Number\n \"|\" . // 19.B SSN Number\n \"|\" . // 20.B Driver license number\n \"|\" . // 21. Mathers Identifier\n $ethnicity_code . \"^^CDCREC\" . // 22. Ethnic Group\n //\"|\" . // 23. Birth Plase\n //\"|\" . // 24. Multiple birth indicator\n //\"|\" . // 25. Birth order\n //\"|\" . // 26. Citizenship\n //\"|\" . // 27. Veteran military status\n //\"|\" . // 28.B Nationality\n //\"|\" . // 29. Patient Death Date and Time\n //\"|\" . // 30. Patient Death Indicator\n //\"|\" . // 31. Identity Unknown Indicator\n //\"|\" . // 32. Identity Reliability Code\n //\"|\" . // 33. Last Update Date/Time\n //\"|\" . // 34. Last Update Facility\n //\"|\" . // 35. Species Code\n //\"|\" . // 36. Breed Code\n //\"|\" . // 37. Breed Code\n //\"|\" . // 38. Production Class Code\n //\"\" . // 39. Tribal Citizenship\n \"$D\" ;\n $content .= \"PV1|\" . // [[ 3.86 ]]\n \"1|\" . // 1. Set ID\n \"|\" . // 2.R Patient Class (U - unknown)\n \"|\" . // 3.\n \"|\" . // 4.\n \"|\" . // 5.\n \"|\" . // 6.\n \"|\" . // 7.\n \"|\" . // 8.\n \"|\" . // 9.\n \"|\" . // 10.\n \"|\" . // 11.\n \"|\" . // 12.\n \"|\" . // 13.\n \"|\" . // 14.\n \"|\" . // 15.\n \"|\" . // 16.\n \"|\" . // 17.\n \"|\" . // 18.\n $r['encounter'] . \"^^^^VN|\" . // 19.\n \"|\" . // 20.\n \"|\" . // 21.\n \"|\" . // 22.\n \"|\" . // 23.\n \"|\" . // 24.\n \"|\" . // 25.\n \"|\" . // 26.\n \"|\" . // 27.\n \"|\" . // 28.\n \"|\" . // 29.\n \"|\" . // 30.\n \"|\" . // 31.\n \"|\" . // 32.\n \"|\" . // 33.\n \"|\" . // 34.\n \"|\" . // 35.\n \"|\" . // 36. Discharge Disposition\n \"|\" . // 37.\n \"|\" . // 38.\n \"|\" . // 39.\n \"|\" . // 40.\n \"|\" . // 41.\n \"|\" . // 42.\n \"|\" . // 43.\n $nowdate . // 44. Admit Date/Time\n \"$D\" ;\n $i = 0;\n foreach ($o_result as $row) {\n $i++;\n if ($row['code'] == 'SS003') {\n if ($row['ob_value'] == '261QE0002X') {\n $text = 'Emergency Care';\n } elseif ($row['ob_value'] == '261QM2500X') {\n $text = 'Medical Specialty';\n } elseif ($row['ob_value'] == '261QP2300X') {\n $text = 'Primary Care';\n } elseif ($row['ob_value'] == '261QU0200X') {\n $text = 'Urgent Care';\n }\n\n $content .= \"OBX|\" .\n $i . \"|\" . //1. Set ID\n \"CWE|\" . //2. Value Type\n $row['code'] . \"^^\" . $row['table_code'] . \"|\" . //3. Observation Identifier\n \"|\" . //4.\n $row['ob_value'] . \"^\" . $text . \"^NUCC|\" . //5. Observation Value\n \"|\" . //6. Units\n \"|\" . //7.\n \"|\" . //8.\n \"|\" . //9.\n \"|\" . //10.\n \"F\" . //11. Observation Result Status\n \"$D\";\n } elseif ($row['code'] == '21612-7') {\n $content .= \"OBX|\" .\n $i . \"|\" . //1. Set ID\n \"NM|\" . //2. Value Type\n $row['code'] . \"^^\" . $row['table_code'] . \"|\" . //3. Observation Identifier\n \"|\" . //4.\n $row['ob_value'] . \"|\" . //5. Observation Value\n $row['ob_unit'] . \"^^UCUM|\" . //6. Units\n \"|\" . //7.\n \"|\" . //8.\n \"|\" . //9.\n \"|\" . //10.\n \"F\" . //11. Observation Result Status\n \"$D\";\n } elseif ($row['code'] == '8661-1') {\n $content .= \"OBX|\" .\n $i . \"|\" . //1. Set ID\n \"CWE|\" . //2. Value Type\n $row['code'] . \"^^\" . $row['table_code'] . \"|\" . //3. Observation Identifier\n \"|\" . //4.\n \"^^^^^^^^\" . $row['ob_value'] . \"|\" . //5. Observation Value\n \"|\" . //6. Units\n \"|\" . //7.\n \"|\" . //8.\n \"|\" . //9.\n \"|\" . //10.\n \"F\" . //11. Observation Result Status\n \"$D\";\n }\n }\n\n $content .= \"DG1|\" . // [[ 6.24 ]]\n \"1|\" . // 1. Set ID\n \"|\" . // 2.B.R Diagnosis Coding Method\n $r['code'] . \"^\" . $r['code_text'] . \"^I9CDX|\" . // 3. Diagnosis Code - DG1\n \"|\" . // 4.B Diagnosis Description\n $r['issuedate'] . \"|\" . // 5. Diagnosis Date/Time\n \"W\" . // 6.R Diagnosis Type // A - Admiting, W - working\n //\"|\" . // 7.B Major Diagnostic Category\n //\"|\" . // 8.B Diagnostic Related Group\n //\"|\" . // 9.B DRG Approval Indicator\n //\"|\" . // 10.B DRG Grouper Review Code\n //\"|\" . // 11.B Outlier Type\n //\"|\" . // 12.B Outlier Days\n //\"|\" . // 13.B Outlier Cost\n //\"|\" . // 14.B Grouper Version And Type\n //\"|\" . // 15. Diagnosis Priority\n //\"|\" . // 16. Diagnosing Clinician\n //\"|\" . // 17. Diagnosis Classification\n //\"|\" . // 18. Confidential Indicator\n //\"|\" . // 19. Attestation Date/Time\n //\"|\" . // 20.C Diagnosis Identifier\n //\"\" . // 21.C Diagnosis Action Code\n \"$D\" ;\n\n //mark if issues generated/sent\n $query_insert = \"insert into syndromic_surveillance(lists_id,submission_date,filename) values (?, ?, ?)\";\n $appTable->zQuery($query_insert, array($r['issueid'], $now1, $filename));\n }\n\n //send the header here\n header('Content-type: text/plain');\n header('Content-Disposition: attachment; filename=' . $filename);\n\n // put the content in the file\n echo($content);\n exit;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getEnumKeys(string $service, string $method, string $param): array\n {\n $values = [];\n switch ($service) {\n case 'avatars':\n switch ($method) {\n case 'getBrowser':\n $codes = Config::getParam('avatar-browsers');\n foreach ($codes as $code => $value) {\n $values[] = $value['name'];\n }\n return $values;\n case 'getCreditCard':\n $codes = Config::getParam('avatar-credit-cards');\n foreach ($codes as $code => $value) {\n $values[] = $value['name'];\n }\n return $values;\n case 'getFlag':\n $codes = Config::getParam('avatar-flags');\n foreach ($codes as $code => $value) {\n $values[] = $value['name'];\n }\n return $values;\n }\n break;\n case 'databases':\n switch ($method) {\n case 'getUsage':\n case 'getCollectionUsage':\n case 'getDatabaseUsage':\n // Range Enum Keys\n $values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];\n return $values;\n }\n break;\n case 'function':\n switch ($method) {\n case 'getUsage':\n case 'getFunctionUsage':\n // Range Enum Keys\n $values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];\n return $values;\n }\n break;\n case 'users':\n switch ($method) {\n case 'getUsage':\n case 'getUserUsage':\n // Range Enum Keys\n if ($param == 'range') {\n $values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];\n return $values;\n }\n }\n break;\n case 'storage':\n switch ($method) {\n case 'getUsage':\n case 'getBucketUsage':\n // Range Enum Keys\n $values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];\n return $values;\n }\n }\n return $values;\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "function is_conflicting_acl($aco_array, $aro_array, $aro_group_ids=NULL, $axo_array=NULL, $axo_group_ids=NULL, $ignore_acl_ids=NULL) {\n\t\t//Check for potential conflicts. Ignore groups, as groups will almost always have \"conflicting\" ACLs.\n\t\t//Thats part of inheritance.\n\n\t\tif (!is_array($aco_array)) {\n\t\t\t$this->debug_text('is_conflicting_acl(): Invalid ACO Array.');\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (!is_array($aro_array)) {\n\t\t\t$this->debug_text('is_conflicting_acl(): Invalid ARO Array.');\n\t\t\treturn FALSE;\n\t\t}\n\n\t\t$query = '\n\t\t\tSELECT\t\ta.id\n\t\t\tFROM\t\t'. $this->_db_table_prefix .'acl a\n\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aco_map ac ON ac.acl_id=a.id\n\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'aro_map ar ON ar.acl_id=a.id\n\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_map ax ON ax.acl_id=a.id\n\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_groups_map axg ON axg.acl_id=a.id\n\t\t\tLEFT JOIN\t'. $this->_db_table_prefix .'axo_groups xg ON xg.id=axg.group_id\n\t\t\t';\n\n\t\t//ACO\n\t\tforeach ($aco_array as $aco_section_value => $aco_value_array) {\n\t\t\t$this->debug_text(\"is_conflicting_acl(): ACO Section Value: $aco_section_value ACO VALUE: \" . implode(',', $aco_value_array));\n\t\t\t//$this->showarray($aco_array);\n\n\t\t\tif (!is_array($aco_value_array)) {\n\t\t\t\t$this->debug_text('is_conflicting_acl(): Invalid Format for ACO Array item. Skipping...');\n\t\t\t\tcontinue;\n\t\t\t\t// return TRUE;\n\t\t\t}\n\t\t\t//Move the below line in to the LEFT JOIN above for PostgreSQL sake.\n\t\t\t//'ac1' => 'ac.acl_id=a.id',\n\t\t\t$where_query = array(\n\t\t\t\t'ac2' => '(ac.section_value=' . $this->db->quote($aco_section_value) . ' AND ac.value IN (\\'' . implode('\\',\\'', array_map('add_escape_custom', $aco_value_array)) . '\\'))'\n\t\t\t);\n\n\t\t\t//ARO\n\t\t\tforeach ($aro_array as $aro_section_value => $aro_value_array) {\n\t\t\t\t$this->debug_text(\"is_conflicting_acl(): ARO Section Value: $aro_section_value ARO VALUE: $aro_value_array\");\n\n\t\t\t\tif (!is_array($aro_value_array))\n\t\t\t\t{\n\t\t\t\t\t$this->debug_text('is_conflicting_acl(): Invalid Format for ARO Array item. Skipping...');\n\t\t\t\t\tcontinue;\n\t\t\t\t\t// return TRUE;\n\t\t\t\t}\n\n\t\t\t\t$this->debug_text(\"is_conflicting_acl(): Search: ACO Section: $aco_section_value ACO Value: $aco_value_array ARO Section: $aro_section_value ARO Value: $aro_value_array\");\n\n\t\t\t\t//Move the below line in to the LEFT JOIN above for PostgreSQL sake.\n\t\t\t\t//$where_query['ar1'] = 'ar.acl_id=a.id';\n\n $where_query['ar2'] = '(ar.section_value=' . $this->db->quote($aro_section_value) . ' AND ar.value IN (' . implode('\\',\\'', array_map('add_escape_custom', $aro_value_array)) . '\\'))';\n\n\t\t\t\tif (is_array($axo_array) AND count($axo_array) > 0) {\n\t\t\t\t\tforeach ($axo_array as $axo_section_value => $axo_value_array) {\n\t\t\t\t\t\t$this->debug_text(\"is_conflicting_acl(): AXO Section Value: $axo_section_value AXO VALUE: $axo_value_array\");\n\n\t\t\t\t\t\tif (!is_array($axo_value_array)) {\n\t\t\t\t\t\t\t$this->debug_text('is_conflicting_acl(): Invalid Format for AXO Array item. Skipping...');\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t// return TRUE;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t$this->debug_text(\"is_conflicting_acl(): Search: ACO Section: $aco_section_value ACO Value: $aco_value_array ARO Section: $aro_section_value ARO Value: $aro_value_array AXO Section: $axo_section_value AXO Value: $axo_value_array\");\n\n\t\t\t\t\t\t//$where_query['ax1'] = 'ax.acl_id=x.id';\n\t\t\t\t\t\t$where_query['ax1'] = 'ax.acl_id=a.id';\n\t\t\t\t\t\t$where_query['ax2'] = '(ax.section_value='. $this->db->quote($axo_section_value) .' AND ax.value IN (' . implode('\\',\\'', array_map('add_escape_custom', $axo_value_array)) . '\\'))';\n\n\t\t\t\t\t\t$where = 'WHERE ' . implode(' AND ', $where_query);\n\n\t\t\t\t\t\t$conflict_result = $this->db->GetCol($query . $where);\n\n\t\t\t\t\t\tif (is_array($conflict_result) AND !empty($conflict_result)) {\n\t\t\t\t\t\t\t// showarray($conflict_result);\n\n\t\t\t\t\t\t\tif (is_array($ignore_acl_ids)) {\n\t\t\t\t\t\t\t\t$conflict_result = array_diff($conflict_result, $ignore_acl_ids);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (count($conflict_result) > 0) {\n\t\t\t\t\t\t\t\t$conflicting_acls_str = implode(',', $conflict_result);\n\t\t\t\t\t\t\t\t$this->debug_text(\"is_conflicting_acl(): Conflict FOUND!!! ACL_IDS: ($conflicting_acls_str)\");\n\t\t\t\t\t\t\t\treturn TRUE;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$where_query['ax1'] = '(ax.section_value IS NULL AND ax.value IS NULL)';\n\t\t\t\t\t$where_query['ax2'] = 'xg.name IS NULL';\n\n\t\t\t\t\t$where = 'WHERE ' . implode(' AND ', $where_query);\n\n\t\t\t\t\t$conflict_result = $this->db->GetCol($query . $where);\n\n\t\t\t\t\tif (is_array($conflict_result) AND !empty($conflict_result)) {\n\t\t\t\t\t\t// showarray($conflict_result);\n\n\t\t\t\t\t\tif (is_array($ignore_acl_ids)) {\n\t\t\t\t\t\t\t$conflict_result = array_diff($conflict_result, $ignore_acl_ids);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (count($conflict_result) > 0) {\n\t\t\t\t\t\t\t$conflicting_acls_str = implode(',', $conflict_result);\n\t\t\t\t\t\t\t$this->debug_text(\"is_conflicting_acl(): Conflict FOUND!!! ACL_IDS: ($conflicting_acls_str)\");\n\t\t\t\t\t\t\treturn TRUE;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t$this->debug_text('is_conflicting_acl(): No conflicting ACL found.');\n\t\treturn FALSE;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function executeActions($output, $params, array $input = [])\n {\n foreach ($this->actions as $action) {\n switch ($action->fields[\"action_type\"]) {\n case \"assign\":\n $output[$action->fields[\"field\"]] = $action->fields[\"value\"];\n break;\n case 'regex_result':\n if ($action->fields[\"field\"] === \"locations_id\") {\n foreach ($this->regex_results as $regex_result) {\n $regexvalue = RuleAction::getRegexResultById(\n $action->fields[\"value\"],\n $regex_result\n );\n\n // from rule test context just assign regex value to key\n if ($this->is_preview) {\n $output['locations_id'] = $regexvalue;\n } else {\n $compute_entities_id = $input['entities_id'] ?? 0;\n $location = new Location();\n $output['locations_id'] = $location->importExternal($regexvalue, $compute_entities_id);\n }\n }\n }\n break;\n }\n }\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function processLogin()\n {\n /* Check fields validity */\n $passwd = trim(Tools::getValue('passwd'));\n $email = trim(Tools::getValue('email'));\n if (empty($email)) {\n $this->errors[] = $this->trans('Email is empty.', array(), 'Admin.Notifications.Error');\n } elseif (!Validate::isEmail($email)) {\n $this->errors[] = $this->trans('Invalid email address.', array(), 'Admin.Notifications.Error');\n }\n\n if (empty($passwd)) {\n $this->errors[] = $this->trans('The password field is blank.', array(), 'Admin.Notifications.Error');\n } elseif (!Validate::isPasswd($passwd)) {\n $this->errors[] = $this->trans('Invalid password.', array(), 'Admin.Notifications.Error');\n }\n\n if (!count($this->errors)) {\n // Find employee\n $this->context->employee = new Employee();\n $is_employee_loaded = $this->context->employee->getByEmail($email, $passwd);\n $employee_associated_shop = $this->context->employee->getAssociatedShops();\n if (!$is_employee_loaded) {\n $this->errors[] = $this->trans('The employee does not exist, or the password provided is incorrect.', array(), 'Admin.Login.Notification');\n $this->context->employee->logout();\n } elseif (empty($employee_associated_shop) && !$this->context->employee->isSuperAdmin()) {\n $this->errors[] = $this->trans('This employee does not manage the shop anymore (either the shop has been deleted or permissions have been revoked).', array(), 'Admin.Login.Notification');\n $this->context->employee->logout();\n } else {\n PrestaShopLogger::addLog($this->trans('Back office connection from %ip%', array('%ip%' => Tools::getRemoteAddr()), 'Admin.Advparameters.Feature'), 1, null, '', 0, true, (int) $this->context->employee->id);\n\n $this->context->employee->remote_addr = (int) ip2long(Tools::getRemoteAddr());\n // Update cookie\n $cookie = Context::getContext()->cookie;\n $cookie->id_employee = $this->context->employee->id;\n $cookie->email = $this->context->employee->email;\n $cookie->profile = $this->context->employee->id_profile;\n $cookie->passwd = $this->context->employee->passwd;\n $cookie->remote_addr = $this->context->employee->remote_addr;\n $cookie->registerSession(new EmployeeSession());\n\n if (!Tools::getValue('stay_logged_in')) {\n $cookie->last_activity = time();\n }\n\n $cookie->write();\n\n // If there is a valid controller name submitted, redirect to it\n if (isset($_POST['redirect']) && Validate::isControllerName($_POST['redirect'])) {\n $url = $this->context->link->getAdminLink($_POST['redirect']);\n } else {\n $tab = new Tab((int) $this->context->employee->default_tab);\n $url = $this->context->link->getAdminLink($tab->class_name);\n }\n\n if (Tools::isSubmit('ajax')) {\n die(json_encode(array('hasErrors' => false, 'redirect' => $url)));\n } else {\n $this->redirect_after = $url;\n }\n }\n }\n if (Tools::isSubmit('ajax')) {\n die(json_encode(array('hasErrors' => true, 'errors' => $this->errors)));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function generate(): void\n {\n global $RND, $myrights, $useeqnhelper, $showtips, $imasroot;\n\n $anstype = $this->answerBoxParams->getAnswerType();\n $qn = $this->answerBoxParams->getQuestionNumber();\n $multi = $this->answerBoxParams->getIsMultiPartQuestion();\n $isConditional = $this->answerBoxParams->getIsConditional();\n $partnum = $this->answerBoxParams->getQuestionPartNumber();\n $la = $this->answerBoxParams->getStudentLastAnswers();\n $options = $this->answerBoxParams->getQuestionWriterVars();\n $colorbox = $this->answerBoxParams->getColorboxKeyword();\n $assessmentId = $this->answerBoxParams->getAssessmentId();\n\n // FIXME: The following code needs to be updated\n // - $qn is always the question number (never $qn+1)\n // - $multi is now a boolean\n // - $partnum is now available\n\n $out = '';\n $tip = '';\n $sa = '';\n $preview = '';\n\n $optionkeys = ['questiontitle', 'answertitle', 'matchlist', 'noshuffle',\n 'displayformat', 'readerlabel', 'ansprompt'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n $questions = getOptionVal($options, 'questions', $multi, $partnum, 2);\n $answers = getOptionVal($options, 'answers', $multi, $partnum, 2);\n\n if ($multi) {$qn = ($qn + 1) * 1000 + $partnum;}\n\n if (!is_array($questions)) {\n echo _('Eeek! $questions is not defined or needs to be an array');\n $questions = array();\n }\n if (!is_array($answers)) {\n echo _('Eeek! $answers is not defined or needs to be an array');\n $answers = array();\n }\n if (!empty($matchlist)) {\n $matchlist = array_map('trim', explode(',', $matchlist));\n if (count($matchlist) != count($questions)) {\n echo _('$questions and $matchlist should have the same number of entries');\n }\n }\n if ($noshuffle == \"questions\" || $noshuffle == 'all') {\n $randqkeys = array_keys($questions);\n } else {\n $randqkeys = (array) $RND->array_rand($questions, count($questions));\n $RND->shuffle($randqkeys);\n }\n if ($noshuffle == \"answers\" || $noshuffle == 'all') {\n $randakeys = array_keys($answers);\n } else {\n $randakeys = (array) $RND->array_rand($answers, count($answers));\n $RND->shuffle($randakeys);\n }\n $_SESSION['choicemap'][$assessmentId][$qn] = array($randqkeys, $randakeys);\n if (!empty($GLOBALS['inline_choicemap'])) {\n $params['choicemap'] = encryptval(array($randqkeys, $randakeys), $GLOBALS['inline_choicemap']);\n }\n if (isset($GLOBALS['capturechoices'])) {\n $GLOBALS['choicesdata'][$qn] = array($randqkeys, $answers);\n }\n if (isset($GLOBALS['capturechoiceslivepoll'])) {\n /* TODO\n $params['livepoll_choices'] = $questions;\n $params['livepoll_ans'] = $answer;\n $params['livepoll_randkeys'] = $randakeys;\n */\n }\n\n $ncol = 1;\n\n if (substr($displayformat, 1) == 'columnselect') {\n $ncol = $displayformat[0];\n $itempercol = ceil(count($randqkeys) / $ncol);\n $displayformat = 'select';\n } else if (substr($displayformat, 1) == 'columnstacked') {\n $ncol = $displayformat[0];\n $itempercol = ceil(count($randqkeys) / $ncol);\n $itemperanscol = ceil(count($randakeys) / $ncol);\n }\n if (substr($displayformat, 0, 8) == \"limwidth\") {\n $divstyle = 'style=\"max-width:' . substr($displayformat, 8) . 'px;\"';\n } else {\n $divstyle = '';\n }\n $out = '<div id=\"qnwrap' . $qn . '\" role=\"group\" ';\n if ($colorbox != '') {\n $out .= 'class=\"' . $colorbox . '\" ';\n }\n $out .= 'aria-label=\"' . $this->answerBoxParams->getQuestionIdentifierString() .\n (!empty($readerlabel) ? ' ' . Sanitize::encodeStringForDisplay($readerlabel) : '') . '\">';\n $out .= \"<div class=\\\"match\\\" $divstyle>\\n\";\n if (!empty($questiontitle)) {\n $out .= \"<p class=\\\"centered\\\">$questiontitle</p>\\n\";\n }\n $out .= \"<ul class=\\\"nomark\\\">\\n\";\n if ($la == '' || is_array($la)) { // no reason for $la to be array, but catch case\n $las = array();\n } else {\n $las = explode(\"|\", $la);\n }\n\n $letters = array_slice(explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az'), 0, count($answers));\n\n for ($i = 0; $i < count($randqkeys); $i++) {\n if (isset($las[$randqkeys[$i]])) {\n $laval = $las[$randqkeys[$i]];\n } else {\n $laval = '-';\n }\n if ($ncol > 1) {\n if ($i > 0 && $i % $itempercol == 0) {\n $out .= '</ul></div><div class=\"match\"><ul class=nomark>';\n }\n }\n if (strpos($questions[$randqkeys[$i]], ' ') === false || strlen($questions[$randqkeys[$i]]) < 12) {\n $out .= '<li class=\"nowrap\">';\n } else {\n $out .= '<li>';\n }\n $out .= \"<select name=\\\"qn$qn-$i\\\" id=\\\"qn$qn-$i\\\">\";\n $out .= '<option value=\"-\" ';\n if ($laval == '-' || strcmp($laval, '') == 0) {\n $out .= 'selected=\"1\"';\n }\n $out .= '>' . ($ansprompt !== '' ? $ansprompt : '-') . '</option>';\n if ($displayformat == \"select\") {\n for ($j = 0; $j < count($randakeys); $j++) {\n $out .= \"<option value=\\\"\" . $j . \"\\\" \";\n if (strcmp($laval, $randakeys[$j]) == 0) {\n $out .= 'selected=\"1\"';\n }\n $out .= \">\" . str_replace('`', '', $answers[$randakeys[$j]]) . \"</option>\\n\";\n }\n } else {\n foreach ($letters as $j => $v) {\n //$out .= \"<option value=\\\"$v\\\" \";\n $out .= \"<option value=\\\"$j\\\" \";\n if (strcmp($laval, $randakeys[$j]) == 0) {\n $out .= 'selected=\"1\"';\n }\n $out .= \">$v</option>\";\n }\n }\n $out .= \"</select>&nbsp;<label for=\\\"qn$qn-$i\\\">{$questions[$randqkeys[$i]]}</label></li>\\n\";\n }\n $out .= \"</ul>\\n\";\n $out .= \"</div>\";\n\n if (empty($displayformat) || $displayformat != \"select\") {\n if (!empty($itemperanscol)) {\n $out .= \"<div class=spacer>&nbsp;</div>\";\n }\n $out .= \"<div class=\\\"match\\\" $divstyle>\\n\";\n if (!empty($answertitle)) {\n $out .= \"<p class=centered>$answertitle</p>\\n\";\n }\n\n $out .= \"<ol class=lalpha>\\n\";\n for ($i = 0; $i < count($randakeys); $i++) {\n if ($ncol > 1 && $i > 0 && $i % $itemperanscol == 0) {\n $out .= '</ol></div><div class=\"match\"><ol class=lalpha start=' . ($i + 1) . '>';\n }\n $out .= \"<li>{$answers[$randakeys[$i]]}</li>\\n\";\n }\n $out .= \"</ol>\";\n $out .= \"</div>\";\n }\n $out .= \"<div class=spacer>&nbsp;</div>\";\n $out .= '</div>';\n //$tip = \"In each box provided, type the letter (a, b, c, etc.) of the matching answer in the right-hand column\";\n if ($displayformat == \"select\") {\n $tip = _('In each pull-down, select the item that matches with the displayed item');\n } else {\n $tip = _('In each pull-down on the left, select the letter (a, b, c, etc.) of the matching answer in the right-hand column');\n }\n if (!$isConditional) {\n for ($i = 0; $i < count($randqkeys); $i++) {\n if (!empty($matchlist)) {\n $anss = array_map('trim', explode(' or ', $matchlist[$randqkeys[$i]]));\n $ansopts = [];\n foreach ($anss as $v) {\n $akey = array_search($v, $randakeys);\n if ($displayformat == \"select\") {\n $ansopts[] = $answers[$randakeys[$akey]];\n } else {\n $ansopts[] = chr($akey + 97);\n }\n }\n if ($displayformat == \"select\") {\n $sa .= '<br/>' . implode(' or ', $ansopts);\n } else if (count($ansopts) > 1) {\n $sa .= '(' . implode(' or ', $ansopts) . ') ';\n } else {\n $sa .= $ansopts[0] . ' ';\n }\n } else {\n $akey = array_search($randqkeys[$i], $randakeys);\n if ($displayformat == \"select\") {\n $sa .= '<br/>' . $answers[$randakeys[$akey]];\n } else {\n $sa .= chr($akey + 97) . \" \";\n }\n }\n }\n }\n\n // Done!\n $this->answerBox = $out;\n $this->entryTip = $tip;\n $this->correctAnswerForPart = (string) $sa;\n $this->previewLocation = $preview;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function canonicalRedirection($canonical_url = '')\n {\n if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET') {\n return;\n }\n\n $canonical_url = preg_replace('/#.*$/', '', $canonical_url);\n\n $match_url = rawurldecode(Tools::getCurrentUrlProtocolPrefix() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);\n if (!preg_match('/^' . Tools::pRegexp(rawurldecode($canonical_url), '/') . '([&?].*)?$/', $match_url)) {\n $params = array();\n $url_details = parse_url($canonical_url);\n\n if (!empty($url_details['query'])) {\n parse_str($url_details['query'], $query);\n foreach ($query as $key => $value) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n $excluded_key = array('isolang', 'id_lang', 'controller', 'fc', 'id_product', 'id_category', 'id_manufacturer', 'id_supplier', 'id_cms');\n $excluded_key = array_merge($excluded_key, $this->redirectionExtraExcludedKeys);\n foreach ($_GET as $key => $value) {\n if (!in_array($key, $excluded_key) && Validate::isUrl($key) && Validate::isUrl($value)) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n\n $str_params = http_build_query($params, '', '&');\n if (!empty($str_params)) {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url) . '?' . $str_params;\n } else {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url);\n }\n\n // Don't send any cookie\n Context::getContext()->cookie->disallowWriting();\n if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $_SERVER['REQUEST_URI'] != __PS_BASE_URI__) {\n die('[Debug] This page has moved<br />Please use the following URL instead: <a href=\"' . $final_url . '\">' . $final_url . '</a>');\n }\n\n $redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';\n header('HTTP/1.0 ' . $redirect_type . ' Moved');\n header('Cache-Control: no-cache');\n Tools::redirectLink($final_url);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function dropdown($options = [])\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $p['name'] = 'documents_id';\n $p['entity'] = '';\n $p['used'] = [];\n $p['display'] = true;\n $p['hide_if_no_elements'] = false;\n $p['readonly'] = false;\n\n if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }\n\n if (isset($p['value']) && ($p['value'] > 0)) {\n $document = new Document();\n $document->getFromDB($p['value']);\n $p['rubdoc'] = $document->fields['documentcategories_id'];\n }\n\n $subwhere = [\n 'glpi_documents.is_deleted' => 0,\n ] + getEntitiesRestrictCriteria('glpi_documents', '', $p['entity'], true);\n\n if (count($p['used'])) {\n $subwhere['NOT'] = ['id' => array_merge([0], $p['used'])];\n }\n\n $criteria = [\n 'FROM' => 'glpi_documentcategories',\n 'WHERE' => [\n 'id' => new QuerySubQuery([\n 'SELECT' => 'documentcategories_id',\n 'DISTINCT' => true,\n 'FROM' => 'glpi_documents',\n 'WHERE' => $subwhere\n ])\n ],\n 'ORDER' => 'name'\n ];\n $iterator = $DB->request($criteria);\n\n if ($p['hide_if_no_elements'] && $iterator->count() === 0) {\n return;\n }\n\n $values = [];\n foreach ($iterator as $data) {\n $values[$data['id']] = $data['name'];\n }\n $rand = mt_rand();\n $readonly = $p['readonly'];\n $out = '';\n $width = '30%';\n if ($readonly) {\n $width = '100%';\n $out .= '<div class=\"row\">';\n $out .= '<div class=\"col-xxl-5 p-0\">';\n }\n $out .= Dropdown::showFromArray('_rubdoc', $values, [\n 'width' => $width,\n 'rand' => $rand,\n 'display' => false,\n 'display_emptychoice' => true,\n 'value' => $p['rubdoc'] ?? 0,\n 'readonly' => $readonly\n ]);\n $field_id = Html::cleanId(\"dropdown__rubdoc$rand\");\n\n $params = ['rubdoc' => '__VALUE__',\n 'entity' => $p['entity'],\n 'rand' => $rand,\n 'myname' => $p['name'],\n 'used' => $p['used']\n ];\n\n if ($readonly) {\n $out .= '</div>';\n $out .= '<div class=\"col-xxl-7 p-0\">';\n }\n $out .= Ajax::updateItemOnSelectEvent(\n $field_id,\n \"show_\" . $p['name'] . $rand,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownRubDocument.php\",\n $params,\n false\n );\n $out .= \"<span id='show_\" . $p['name'] . \"$rand'>\";\n $out .= \"</span>\\n\";\n\n $params['rubdoc'] = $p['rubdoc'] ?? 0;\n $params['value'] = $p['value'] ?? 0;\n if ($readonly) {\n $document = new Document();\n $doclist = $document->find([]);\n foreach ($doclist as $doc) {\n $docvalue[$doc['id']] = $doc['name'];\n }\n\n $out .= Dropdown::showFromArray('document', $docvalue ?? [], [\n 'width' => $width,\n 'rand' => $rand,\n 'display' => false,\n 'display_emptychoice' => true,\n 'value' => $p['value'] ?? 0,\n 'readonly' => $readonly\n ]);\n $out .= '</div>';\n $out .= '</div>';\n } else {\n $out .= Ajax::updateItem(\n \"show_\" . $p['name'] . $rand,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/dropdownRubDocument.php\",\n $params,\n false\n );\n }\n if ($p['display']) {\n echo $out;\n return $rand;\n }\n return $out;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<Schedule xmlns=\"http://hl7.org/fhir\"></Schedule>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->active)) {\n $this->active->xmlSerialize(true, $sxe->addChild('active'));\n }\n if (0 < count($this->serviceCategory)) {\n foreach ($this->serviceCategory as $serviceCategory) {\n $serviceCategory->xmlSerialize(true, $sxe->addChild('serviceCategory'));\n }\n }\n if (0 < count($this->serviceType)) {\n foreach ($this->serviceType as $serviceType) {\n $serviceType->xmlSerialize(true, $sxe->addChild('serviceType'));\n }\n }\n if (0 < count($this->specialty)) {\n foreach ($this->specialty as $specialty) {\n $specialty->xmlSerialize(true, $sxe->addChild('specialty'));\n }\n }\n if (0 < count($this->actor)) {\n foreach ($this->actor as $actor) {\n $actor->xmlSerialize(true, $sxe->addChild('actor'));\n }\n }\n if (isset($this->planningHorizon)) {\n $this->planningHorizon->xmlSerialize(true, $sxe->addChild('planningHorizon'));\n }\n if (isset($this->comment)) {\n $this->comment->xmlSerialize(true, $sxe->addChild('comment'));\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['timingTiming'])) {\n $this->setTimingTiming($data['timingTiming']);\n }\n if (isset($data['timingReference'])) {\n $this->setTimingReference($data['timingReference']);\n }\n if (isset($data['timingDate'])) {\n $this->setTimingDate($data['timingDate']);\n }\n if (isset($data['timingDateTime'])) {\n $this->setTimingDateTime($data['timingDateTime']);\n }\n if (isset($data['data'])) {\n if (is_array($data['data'])) {\n foreach ($data['data'] as $d) {\n $this->addData($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"data\" must be array of objects or null, ' . gettype($data['data']) . ' seen.');\n }\n }\n if (isset($data['condition'])) {\n $this->setCondition($data['condition']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function edih_upload_sftp()\n{\n //\n $html_str = '';\n //\n $sftp_dir = 'path/to/dir';\n // if ($_FILES) ) {\n //csv_edihist_log('Error: upload files indicated, but none received.');\n //return false;\n //} elseif\n if (is_dir($sftp_dir) && is_readable($sftp_dir)) {\n $sftp_dir = realpath($sftp_dir);\n $fn_ar = scandir($sftp_dir);\n } else {\n $html_str = 'unable to read the directory for sftp file uploads <br />';\n csv_edihist_log('unable to read the directory for sftp file uploads');\n return $html_str;\n }\n\n //\n $m_types = array('application/octet-stream', 'text/plain', 'application/zip', 'application/x-zip-compressed');\n //\n // some unwanted file extensions that might be accidentally included in upload files\n $ext_types = 'sh|asp|html|htm|cm|js|xml|jpg|png|tif|xpm|pdf|php|py|pl|tcl|doc|pub|ppt|xls|xla|vsd|rtf|odt|ods|odp';\n // we get the parameters here to send to ibr_upload_match_file()\n $param_ar = csv_parameters();\n //if ( class_exists('finfo') )\n foreach ($fn_ar as $idx => $fn) {\n $fa = array();\n $fa['tmp_name'] = tempnam($sftp_dir . DS . $fn, 'x12_');\n $fa['name'] = $sftp_dir . DS . $fn;\n $fa['type'] = mime_content_type($sftp_dir . DS . $fn);\n $fa['size'] = filesize($sftp_dir . DS . $fn);\n // now do verifications\n if (!in_array($fa['type'], $m_types)) {\n //$html_str .= \"Error: mime-type {$fa['type']} not accepted for {$fa['name']} <br />\" . PHP_EOL;\n $f_ar['reject'][] = array('name' => $fa['name'],'comment' => 'mime-type ' . $fa['type']);\n csv_edihist_log('edih_upload_sftp: error mime-type ' . $fa['name'] . ' mime-type ' . $fa['type']);\n unset($fn_ar[$idx]);\n continue;\n }\n\n // verify that we have a usable name\n $fext = (strpos($fa['name'], '.')) ? pathinfo($fa['name'], PATHINFO_EXTENSION) : '';\n if ($fext && preg_match('/' . $ext_types . '\\?/i', $fext)) {\n //$html_str .= 'Error: uploaded_file error for '.$fa['name'].' extension '.$fext.'<br />'. PHP_EOL;\n $f_ar['reject'][] = array('name' => $fa['name'],'comment' => 'extension ' . $fext);\n csv_edihist_log('edih_upload_sftp: _FILES error name ' . $fa['name'] . ' extension ' . $fext);\n unset($fn_ar[$idx]);\n continue;\n }\n\n if (is_string($fa['name'])) {\n // check for null byte in file name, linux hidden file, directory\n if (strpos($fa['name'], '.') === 0 || strpos($fa['name'], \"\\0\") !== false || strpos($fa['name'], \"./\") !== false) {\n //$html_str .= \"Error: uploaded_file error for \" . $fa['name'] . \"<br />\". PHP_EOL;\n $fname = preg_replace(\"/[^a-zA-Z0-9_.-]/\", \"_\", $fa['name']);\n $f_ar['reject'][] = array('name' => $fname,'comment' => 'null byte, hidden, invalid');\n csv_edihist_log('edih_upload_sftp: null byte, hidden, invalid ' . $fname);\n unset($fn_ar[$idx]);\n continue;\n }\n\n // replace spaces in file names -- should not happen, but response files from payers might have spaces\n // $fname = preg_replace(\"/[^a-zA-Z0-9_.-]/\",\"_\",$fname);\n $fa['name'] = str_replace(' ', '_', $fa['name']);\n } else {\n // name is not a string\n //$html_str .= \"Error: uploaded_file error for \" . $fa['tmp_name'] . \"<br />\". PHP_EOL;\n $f_ar['reject'][] = array('name' => (string)$fa['name'],'comment' => 'invalid name');\n unset($fn_ar[$idx]);\n continue;\n }\n\n if (!$fa['tmp_name'] || !$fa['size']) {\n //$html_str .= \"Error: file name or size error <br />\" . PHP_EOL;\n $f_ar['reject'][] = array('name' => (string)$fa['name'],'comment' => 'php file upload error');\n unset($files[$uplkey][$idx]);\n continue;\n }\n\n //\n if (strpos(strtolower($fa['name']), '.zip') || strpos($fa['type'], 'zip')) {\n //\n $f_upl = edih_ziptoarray($fa['tmp_name'], $param_ar, false);\n //\n // put them in the correct type array\n if (is_array($f_upl) && count($f_upl)) {\n foreach ($f_upl as $tp => $fz) {\n if ($tp == 'reject') {\n if (isset($f_ar['reject']) && is_array($fz)) {\n array_merge($f_ar['reject'], $fz);\n } else {\n $f_ar['reject'] = (is_array($fz)) ? $fz : array();\n }\n } else {\n // expect $fz to be an array of file names\n foreach ($fz as $zf) {\n $f_ar[$tp][] = $zf;\n $p_ct++;\n }\n }\n }\n } else {\n // nothing good from edih_ziptoarray()\n // $html_str .= \"error with zip file or no files accepted for \" . $fa['name'] . \"<br />\" .PHP_EOL;\n $f_ar['reject'][] = array('name' => $fa['name'],'comment' => 'error with zip archive');\n unset($files[$uplkey][$idx]);\n }\n\n // continue, since we have done everything that would happen below\n continue;\n }\n\n //\n $f_upl = edih_upload_match_file($param_ar, $fa);\n //\n if (is_array($f_upl) && count($f_upl) > 0) {\n $f_ar[$f_upl['type']][] = $f_upl['name'];\n $p_ct++;\n } else {\n // verification failed\n csv_edihist_log('edih_upload_file: verification failed for ' . $fa['name']);\n $f_ar['reject'][] = array('name' => $fa['name'], 'comment' => 'verification failed');\n unset($fn_ar[$idx]);\n }\n } // end foreach($files[$uplkey] as $idx=>$fa)\n //\n $f_ar['remark'][] = \"Received $f_ct files, accepted $p_ct\" . PHP_EOL;\n return $f_ar;\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function runWizard(Request $request)\n {\n if (!$this->initialized) {\n throw new \\LogicException('Installator must be initialized before running');\n }\n\n $this->request = $request;\n $this->checkSessionStarted();\n\n $step = $request->param('id');\n $result = new Result();\n\n if (!$step) {\n $step = $this->firstStep->getName();\n }\n\n // Traverse all steps until current\n $stepObj = $this->firstStep;\n $lastStartedStep = $stepObj;\n\n while ($stepObj) {\n // Forbid executing not started steps.\n if (!$stepObj->isStarted()) {\n break;\n }\n\n $lastStartedStep = $stepObj;\n\n // Execute current step and stop.\n if ($step == $stepObj->getName()) {\n $result = $stepObj->execute(strtoupper($this->request->method), $this->request->getRequestData());\n\n if ($stepObj->getCompleted()) {\n if ($nextStep = $stepObj->getNextStep()) {\n $nextStep->start();\n\n } else {\n $result->setCompleted(true);\n }\n }\n break;\n }\n\n // If invalid step is before current one, stop propagation, and ask user to fix it.\n if (!$stepObj->isValid()) {\n $result->setStep($stepObj);\n $result->redirectToStep();\n break;\n }\n\n $stepObj = $stepObj->getNextStep();\n }\n\n $this->stepsData['steps'][$stepObj->getName()]['current'] = true;\n\n $this->stepsData = ArraysHelper::arrayMergeRecursiveDistinct($this->stepsData, $stepObj->getViewData());\n $result->setViewData($this->stepsData);\n $result->setLastStartedStep($lastStartedStep);\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "public function toReadable($out_calendar='both'){\n if($this->tDate){\n\n $date = $this->tDate;\n\n $calendar = @$date['calendar'];\n\n $native = null;\n $is_greg_or_julian = (!$calendar || strtolower($calendar)=='gregorian');// || strtolower($calendar)=='julian'\n if(@$date['native'] && !$is_greg_or_julian){\n $native = @$date['native'];\n }\n\n if(@$date['timestamp']){\n\n //one date value with possible deviation\n $res = Temporal::dateToString(@$date['timestamp']['in'], $calendar);\n if($res){\n $res = $res.Temporal::_deviationSuffix( $date['timestamp'] );\n }\n\n $prefix = null;\n if(@$date['timestamp']['circa']){\n $prefix = 'circa ';\n }elseif(@$date['timestamp']['before']){\n $prefix = 'before ';\n }elseif(@$date['timestamp']['after']){\n $prefix = 'after ';\n }\n\n if($prefix){\n $res = $prefix.$res;\n if($native){\n $native = $prefix.$native;\n }\n }\n\n }else{\n\n $from = '';\n $to = '';\n\n if(@$date['start'] && @$date['start']['in']){\n $from = Temporal::dateToString($date['start']['in'], $calendar);\n if($from && strpos($from,'unknown')===false){\n $from = $from.Temporal::_deviationSuffix( $date['start'] );\n }\n }elseif(@$date['start']['earliest']){\n $from = Temporal::dateToString($date['start']['earliest'], $calendar);\n }\n\n if(@$date['end'] && @$date['end']['in']){\n $to = Temporal::dateToString($date['end']['in'], $calendar);\n if($to && strpos($to,'unknown')===false){\n $to = $to.Temporal::_deviationSuffix( $date['end'] );\n }\n }elseif(@$date['end']['latest']){\n $to = Temporal::dateToString($date['end']['latest'], $calendar);\n }\n $res = $from.' to '.$to;\n }\n\n //add native decription as prefix\n if($native){\n if($out_calendar=='native'){\n $res = $native; //native only\n }elseif($out_calendar!='gregorian'){\n //both gregorian and native\n $res = $native.' '.$calendar.' (Gregorian '.$res.')';\n }\n }\n\n return $res;\n\n }else{\n return 'undefined temporal';\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function prepareHeaders($headers)\n {\n $lines = array();\n $from = null;\n\n foreach ($headers as $key => $value) {\n if (strcasecmp($key, 'From') === 0) {\n include_once 'Mail/RFC822.php';\n $parser = new Mail_RFC822();\n $addresses = $parser->parseAddressList($value, 'localhost', false);\n if (is_a($addresses, 'PEAR_Error')) {\n return $addresses;\n }\n\n $from = $addresses[0]->mailbox . '@' . $addresses[0]->host;\n\n // Reject envelope From: addresses with spaces.\n if (strstr($from, ' ')) {\n return false;\n }\n\n $lines[] = $key . ': ' . $value;\n } elseif (strcasecmp($key, 'Received') === 0) {\n $received = array();\n if (is_array($value)) {\n foreach ($value as $line) {\n $received[] = $key . ': ' . $line;\n }\n }\n else {\n $received[] = $key . ': ' . $value;\n }\n // Put Received: headers at the top. Spam detectors often\n // flag messages with Received: headers after the Subject:\n // as spam.\n $lines = array_merge($received, $lines);\n } else {\n // If $value is an array (i.e., a list of addresses), convert\n // it to a comma-delimited string of its elements (addresses).\n if (is_array($value)) {\n $value = implode(', ', $value);\n }\n $lines[] = $key . ': ' . $value;\n }\n }\n\n return array($from, join($this->sep, $lines));\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function find(bool $includeArgs = true)\n {\n if ($php = getenv('PHP_BINARY')) {\n if (!is_executable($php)) {\n $command = '\\\\' === \\DIRECTORY_SEPARATOR ? 'where' : 'command -v';\n if ($php = strtok(exec($command.' '.escapeshellarg($php)), \\PHP_EOL)) {\n if (!is_executable($php)) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (@is_dir($php)) {\n return false;\n }\n\n return $php;\n }\n\n $args = $this->findArguments();\n $args = $includeArgs && $args ? ' '.implode(' ', $args) : '';\n\n // PHP_BINARY return the current sapi executable\n if (\\PHP_BINARY && \\in_array(\\PHP_SAPI, ['cli', 'cli-server', 'phpdbg'], true)) {\n return \\PHP_BINARY.$args;\n }\n\n if ($php = getenv('PHP_PATH')) {\n if (!@is_executable($php) || @is_dir($php)) {\n return false;\n }\n\n return $php;\n }\n\n if ($php = getenv('PHP_PEAR_PHP_BIN')) {\n if (@is_executable($php) && !@is_dir($php)) {\n return $php;\n }\n }\n\n if (@is_executable($php = \\PHP_BINDIR.('\\\\' === \\DIRECTORY_SEPARATOR ? '\\\\php.exe' : '/php')) && !@is_dir($php)) {\n return $php;\n }\n\n $dirs = [\\PHP_BINDIR];\n if ('\\\\' === \\DIRECTORY_SEPARATOR) {\n $dirs[] = 'C:\\xampp\\php\\\\';\n }\n\n return $this->executableFinder->find('php', false, $dirs);\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getComputedVulnerability($name, $flags = 0)\n {\n if (!is_string($name)) {\n throw new \\InvalidArgumentException(\"Vulnerability name must be a string. Provided: '$name'\");\n }\n\n $computeOnlyRoot = (boolean) ($flags & self::COMPUTE_ONLY_ROOT);\n\n if ($computeOnlyRoot && $this->getParent()) {\n return $this->getParent()->getComputedVulnerability($name, $flags);\n }\n\n if ($this->cachedVulnerabilities->hasOwnVulnerability($name)) {\n return $this->cachedVulnerabilities->get($name);\n }\n\n if ($this->vulnerabilitySet->hasOwnVulnerability($name)) {\n $vuln = $this->vulnerabilitySet->get($name);\n\n } else {\n $parent = $this->getParent();\n\n if ($parent) {\n $vuln = $this->getParent()->getComputedVulnerability($name, $flags);\n\n } else if ($this->host) {\n $vuln = $this->host->getParentVulnerability($name, null, null, $computeOnlyRoot);\n if ($vuln === null) {\n $vuln = VulnerabilityFactory::instance()->create($name, false);\n }\n\n } else {\n $vuln = VulnerabilityFactory::instance()->create($name, false);\n }\n }\n\n if ($vuln) {\n if (!$vuln->isTargetedAt($this->targets)) {\n $this->cachedVulnerabilities->set(false, $name);\n $vuln = false;\n\n } else {\n $this->cachedVulnerabilities->set($vuln);\n }\n\n } else {\n $this->cachedVulnerabilities->set(false, $name);\n $vuln = false;\n }\n\n return $vuln;\n }", "smellKey": "S3776", "smellId": null, "repo": "dit21123_hackazon", "language": "php"} {"function": "function banzhafpower($weight, $quota, $format = \"decimal\") {\n \t\t\t \n $max_order = array_sum($weight);\t\t# compute the maximum order for our polynomial\n $polynomial = array_fill(0, $max_order+1,0);\n $polynomial[0] = 1;\n \n $current_order = 0; # compute the polynomial coefficients\n $aux_polynomial = array_values($polynomial);\n for ($i=0;$i<count($weight);$i++) {\n $current_order += $weight[$i];\n \n for ($j=0;$j<$current_order+1;$j++) {\n \t$aux_polynomial[$j] = $polynomial[$j] + (($j<$weight[$i])?0:$polynomial[$j-$weight[$i]]);\n }\n $polynomial = array_values($aux_polynomial);\n }\n $banzhaf_power = array_fill(0, count($weight), 0); # create a list to hold the Banzhaf Power for each voter\n $swings = array_fill(0, $quota, 0); # create a list to compute the swings for each voter\n \n for ($i=0;$i<count($weight);$i++) {\n \t for ($j=0;$j<$quota;$j++) {\t\t\t\t # fill the swings list\n \t \t if ($j<$weight[$i]) {\n \t \t \t $swings[$j] = $polynomial[$j];\n \t \t } else {\n \t \t \t $swings[$j] = $polynomial[$j] - $swings[$j - $weight[$i]];\n \t \t }\n \t }\n \t for ($k=0;$k<$weight[$i];$k++) {\n \t \t $banzhaf_power[$i] += $swings[$quota-1-$k];\t# fill the Banzhaf Power vector\n \t }\n }\n \n $total_power = array_sum($banzhaf_power); # compute the Total Banzhaf Power\n \n if ($format==\"frac\") {\n \t foreach ($banzhaf_power as $i=>$c) {\n \t \t $banzhaf_power[$i] = \"$c/$total_power\";\n \t }\n } else if ($format==\"decimal\") {\n \t foreach ($banzhaf_power as $i=>$c) {\n \t \t $banzhaf_power[$i] = $c/$total_power;\n \t }\n }\n \n return $banzhaf_power;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<RiskEvidenceSynthesis xmlns=\"http://hl7.org/fhir\"></RiskEvidenceSynthesis>');\n }\n parent::xmlSerialize(true, $sxe);\n if (isset($this->url)) {\n $this->url->xmlSerialize(true, $sxe->addChild('url'));\n }\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->version)) {\n $this->version->xmlSerialize(true, $sxe->addChild('version'));\n }\n if (isset($this->name)) {\n $this->name->xmlSerialize(true, $sxe->addChild('name'));\n }\n if (isset($this->title)) {\n $this->title->xmlSerialize(true, $sxe->addChild('title'));\n }\n if (isset($this->status)) {\n $this->status->xmlSerialize(true, $sxe->addChild('status'));\n }\n if (isset($this->date)) {\n $this->date->xmlSerialize(true, $sxe->addChild('date'));\n }\n if (isset($this->publisher)) {\n $this->publisher->xmlSerialize(true, $sxe->addChild('publisher'));\n }\n if (0 < count($this->contact)) {\n foreach ($this->contact as $contact) {\n $contact->xmlSerialize(true, $sxe->addChild('contact'));\n }\n }\n if (isset($this->description)) {\n $this->description->xmlSerialize(true, $sxe->addChild('description'));\n }\n if (0 < count($this->note)) {\n foreach ($this->note as $note) {\n $note->xmlSerialize(true, $sxe->addChild('note'));\n }\n }\n if (0 < count($this->useContext)) {\n foreach ($this->useContext as $useContext) {\n $useContext->xmlSerialize(true, $sxe->addChild('useContext'));\n }\n }\n if (0 < count($this->jurisdiction)) {\n foreach ($this->jurisdiction as $jurisdiction) {\n $jurisdiction->xmlSerialize(true, $sxe->addChild('jurisdiction'));\n }\n }\n if (isset($this->copyright)) {\n $this->copyright->xmlSerialize(true, $sxe->addChild('copyright'));\n }\n if (isset($this->approvalDate)) {\n $this->approvalDate->xmlSerialize(true, $sxe->addChild('approvalDate'));\n }\n if (isset($this->lastReviewDate)) {\n $this->lastReviewDate->xmlSerialize(true, $sxe->addChild('lastReviewDate'));\n }\n if (isset($this->effectivePeriod)) {\n $this->effectivePeriod->xmlSerialize(true, $sxe->addChild('effectivePeriod'));\n }\n if (0 < count($this->topic)) {\n foreach ($this->topic as $topic) {\n $topic->xmlSerialize(true, $sxe->addChild('topic'));\n }\n }\n if (0 < count($this->author)) {\n foreach ($this->author as $author) {\n $author->xmlSerialize(true, $sxe->addChild('author'));\n }\n }\n if (0 < count($this->editor)) {\n foreach ($this->editor as $editor) {\n $editor->xmlSerialize(true, $sxe->addChild('editor'));\n }\n }\n if (0 < count($this->reviewer)) {\n foreach ($this->reviewer as $reviewer) {\n $reviewer->xmlSerialize(true, $sxe->addChild('reviewer'));\n }\n }\n if (0 < count($this->endorser)) {\n foreach ($this->endorser as $endorser) {\n $endorser->xmlSerialize(true, $sxe->addChild('endorser'));\n }\n }\n if (0 < count($this->relatedArtifact)) {\n foreach ($this->relatedArtifact as $relatedArtifact) {\n $relatedArtifact->xmlSerialize(true, $sxe->addChild('relatedArtifact'));\n }\n }\n if (isset($this->synthesisType)) {\n $this->synthesisType->xmlSerialize(true, $sxe->addChild('synthesisType'));\n }\n if (isset($this->studyType)) {\n $this->studyType->xmlSerialize(true, $sxe->addChild('studyType'));\n }\n if (isset($this->population)) {\n $this->population->xmlSerialize(true, $sxe->addChild('population'));\n }\n if (isset($this->exposure)) {\n $this->exposure->xmlSerialize(true, $sxe->addChild('exposure'));\n }\n if (isset($this->outcome)) {\n $this->outcome->xmlSerialize(true, $sxe->addChild('outcome'));\n }\n if (isset($this->sampleSize)) {\n $this->sampleSize->xmlSerialize(true, $sxe->addChild('sampleSize'));\n }\n if (isset($this->riskEstimate)) {\n $this->riskEstimate->xmlSerialize(true, $sxe->addChild('riskEstimate'));\n }\n if (0 < count($this->certainty)) {\n foreach ($this->certainty as $certainty) {\n $certainty->xmlSerialize(true, $sxe->addChild('certainty'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function permissionByTypes(array $columns, User $user, string $tableSuffix): array\n {\n $permissions = [];\n foreach ($columns as $type) {\n $permissions[$type] = 0;\n }\n\n $parentIds = $this->getParentIds();\n if ($id = $this->model->getId()) {\n $parentIds[] = $id;\n }\n\n $currentUserId = $user->getId();\n $userIds = $user->getRoles();\n $userIds[] = $currentUserId;\n\n $highestWorkspaceQuery = '\n SELECT userId,cid,`'. implode('`,`', $columns) .'` FROM users_workspaces_'.$tableSuffix.'\n WHERE cid IN (' . implode(',', $parentIds) . ') AND userId IN (' . implode(',', $userIds) . ')\n ORDER BY LENGTH(cpath) DESC, FIELD(userId, ' . $currentUserId . ') DESC LIMIT 1\n ';\n\n $highestWorkspace = $this->db->fetchAssociative($highestWorkspaceQuery);\n\n if ($highestWorkspace) {\n //if it's the current user, this is the permission that rules them all, no need to check others\n if ($highestWorkspace['userId'] == $currentUserId) {\n foreach ($columns as $type) {\n $permissions[$type] = (int) $highestWorkspace[$type];\n }\n\n if ($permissions['list'] == 0) {\n $permissions['list'] = $this->checkChildrenForPathTraversal($tableSuffix, $userIds);\n }\n\n return $permissions;\n }\n\n //if not found, having already the longest cpath from first query,\n //we either have role permission for the same object, or it could be any of its parents permission.\n\n $roleWorkspaceSql = '\n SELECT userId,`'. implode('`,`', $columns) .'` FROM users_workspaces_'.$tableSuffix.'\n WHERE cid = ' . $highestWorkspace['cid'] . ' AND userId IN (' . implode(',', $userIds) . ')\n ORDER BY FIELD(userId, ' . $currentUserId . ') DESC\n ';\n $objectPermissions = $this->db->fetchAllAssociative($roleWorkspaceSql);\n\n //this performs the additive rule when conflicting rules with multiple roles,\n //breaks the loop when permission=1 is found and move on to check next permission type.\n foreach ($columns as $type) {\n foreach ($objectPermissions as $workspace) {\n if ($workspace[$type] == 1) {\n $permissions[$type] = 1;\n\n break;\n }\n }\n }\n }\n\n //when list=0, we look for any allowed children, so that can make possible to list the path of the folder in between\n //to reach that children by \"exceptionally\" turning list=0 to list=1\n if ($permissions['list']==0) {\n $permissions['list'] = $this->checkChildrenForPathTraversal($tableSuffix, $userIds);\n }\n\n return $permissions;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function parseShortVersion(IEvent $event) {\n\t\t$parsedParameters = $this->getParsedParameters($event);\n\n\t\tif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {\n\t\t\t$event->setRichSubject($this->l->t('Shared with {email}'), [\n\t\t\t\t'email' => $parsedParameters['email'],\n\t\t\t]);\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {\n\t\t\t$event->setRichSubject($this->l->t('Shared with {email} by {actor}'), [\n\t\t\t\t'email' => $parsedParameters['email'],\n\t\t\t\t'actor' => $parsedParameters['actor'],\n\t\t\t]);\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_SELF) {\n\t\t\t$event->setRichSubject($this->l->t('Unshared from {email}'), [\n\t\t\t\t'email' => $parsedParameters['email'],\n\t\t\t]);\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_BY) {\n\t\t\t$event->setRichSubject($this->l->t('Unshared from {email} by {actor}'), [\n\t\t\t\t'email' => $parsedParameters['email'],\n\t\t\t\t'actor' => $parsedParameters['actor'],\n\t\t\t]);\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {\n\t\t\t$event->setRichSubject($this->l->t('Password for mail share sent to {email}'), [\n\t\t\t\t'email' => $parsedParameters['email']\n\t\t\t]);\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {\n\t\t\t$event->setRichSubject($this->l->t('Password for mail share sent to you'));\n\t\t\tif ($this->activityManager->getRequirePNG()) {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));\n\t\t\t} else {\n\t\t\t\t$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new \\InvalidArgumentException();\n\t\t}\n\n\t\treturn $event;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function updateEventTimes($params = [])\n {\n if ($item = getItemForItemtype($params['itemtype'])) {\n $params = self::cleanDates($params);\n\n if (\n $item->getFromDB($params['items_id'])\n && empty($item->fields['is_deleted'])\n && $item::canUpdate()\n && $item->canUpdateItem()\n ) {\n // item exists and is not in bin\n\n $abort = false;\n\n // if event has rrule property, check if we need to create a clone instance\n if (\n isset($item->fields['rrule'])\n && strlen($item->fields['rrule'])\n ) {\n if (\n isset($params['move_instance'])\n && filter_var($params['move_instance'], FILTER_VALIDATE_BOOLEAN)\n && method_exists($item, 'createInstanceClone')\n ) {\n $item = $item->createInstanceClone(\n $item->fields['id'],\n $params['old_start']\n );\n $params['items_id'] = $item->fields['id'];\n }\n }\n\n if (!$abort) {\n $update = [\n 'id' => $params['items_id'],\n 'plan' => [\n 'begin' => $params['start'],\n 'end' => $params['end']\n ]\n ];\n\n if (isset($item->fields['users_id_tech'])) {\n $update['users_id_tech'] = $item->fields['users_id_tech'];\n }\n\n // manage moving event between resource (actors)\n if (!empty($params['new_actor_itemtype']) && !empty($params['new_actor_items_id'])) {\n $new_actor_itemtype = strtolower($params['new_actor_itemtype']);\n\n // reminders don't have group assignement for planning\n if (\n !($new_actor_itemtype === 'group'\n && $item instanceof Reminder)\n ) {\n switch ($new_actor_itemtype) {\n case \"group\":\n $update['groups_id_tech'] = $params['new_actor_items_id'];\n if (strtolower($params['old_actor_itemtype']) === \"user\") {\n $update['users_id_tech'] = 0;\n }\n break;\n\n case \"user\":\n if (isset($item->fields['users_id_tech'])) {\n $update['users_id_tech'] = $params['new_actor_items_id'];\n if (strtolower($params['old_actor_itemtype']) === \"group\") {\n $update['groups_id_tech'] = 0;\n }\n } else {\n $update['users_id'] = $params['new_actor_items_id'];\n }\n break;\n }\n }\n\n // special case for project tasks\n // which have a link tables for their relation with groups/users\n if ($item instanceof ProjectTask) {\n // get actor for finding relation with item\n $actor = new $params['old_actor_itemtype']();\n $actor->getFromDB((int) $params['old_actor_items_id']);\n\n // get current relation\n $team_old = new ProjectTaskTeam();\n $team_old->getFromDBForItems($item, $actor);\n\n // if new relation already exists, delete old relation\n $actor_new = new $params['new_actor_itemtype']();\n $actor_new->getFromDB((int) $params['new_actor_items_id']);\n $team_new = new ProjectTaskTeam();\n if ($team_new->getFromDBForItems($item, $actor_new)) {\n $team_old->delete([\n 'id' => $team_old->fields['id']\n ]);\n } else {\n // else update relation\n $team_old->update([\n 'id' => $team_old->fields['id'],\n 'itemtype' => $params['new_actor_itemtype'],\n 'items_id' => $params['new_actor_items_id'],\n ]);\n }\n }\n }\n\n if (is_subclass_of($item, \"CommonITILTask\")) {\n $parentitemtype = $item::getItilObjectItemType();\n if (!$update[\"_job\"] = getItemForItemtype($parentitemtype)) {\n return;\n }\n\n $fkfield = $update[\"_job\"]::getForeignKeyField();\n $update[$fkfield] = $item->fields[$fkfield];\n }\n\n return $item->update($update);\n }\n }\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "static function lookupByEmailHeaders(&$mailinfo) {\n $possibles = array();\n foreach (array('mid', 'in-reply-to', 'references') as $header) {\n $matches = array();\n if (!isset($mailinfo[$header]) || !$mailinfo[$header])\n continue;\n // Header may have multiple entries (usually separated by\n // spaces ( )\n elseif (!preg_match_all('/<([^>@]+@[^>]+)>/', $mailinfo[$header],\n $matches))\n continue;\n\n // The References header will have the most recent message-id\n // (parent) on the far right.\n // @see rfc 1036, section 2.2.5\n // @see http://www.jwz.org/doc/threading.html\n $possibles = array_merge($possibles, array_reverse($matches[1]));\n }\n\n // Add the message id if it is embedded in the body\n $match = array();\n if (preg_match('`(?:class=\"mid-|Ref-Mid: )([^\"\\s]*)(?:$|\")`',\n $mailinfo['message'], $match)\n && !in_array($match[1], $possibles)\n ) {\n $possibles[] = $match[1];\n }\n\n foreach ($possibles as $mid) {\n // Attempt to detect the ticket and user ids from the\n // message-id header. If the message originated from\n // osTicket, the Mailer class can break it apart. If it came\n // from this help desk, the 'loopback' property will be set\n // to true.\n $mid_info = osTicket\\Mail\\Mailer::decodeMessageId($mid);\n if (!$mid_info || !$mid_info['loopback'])\n continue;\n if (isset($mid_info['uid'])\n && @$mid_info['threadId']\n && ($t = Thread::lookup($mid_info['threadId']))\n ) {\n if (@$mid_info['userId']) {\n $mailinfo['userId'] = $mid_info['userId'];\n }\n elseif (@$mid_info['staffId']) {\n $mailinfo['staffId'] = $mid_info['staffId'];\n }\n // ThreadEntry was positively identified\n return $t;\n }\n }\n\n return null;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "private function findStrictRule(Rule $rule): Collection\n {\n app('log')->debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0));\n $searchArray = [];\n $triggers = [];\n if ($this->refreshTriggers) {\n $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();\n }\n if (!$this->refreshTriggers) {\n $triggers = $rule->ruleTriggers;\n }\n\n /** @var RuleTrigger $ruleTrigger */\n foreach ($triggers as $ruleTrigger) {\n if (false === $ruleTrigger->active) {\n continue;\n }\n $contextSearch = $ruleTrigger->trigger_type;\n if (str_starts_with($ruleTrigger->trigger_type, '-')) {\n $contextSearch = substr($ruleTrigger->trigger_type, 1);\n }\n\n // if the trigger needs no context, value is different:\n $needsContext = (bool)(config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true);\n if (false === $needsContext) {\n app('log')->debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type));\n $searchArray[$ruleTrigger->trigger_type][] = 'true';\n }\n if (true === $needsContext) {\n app('log')->debug(sprintf('SearchRuleEngine:: add a rule trigger (context): %s:\"%s\"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value));\n $searchArray[$ruleTrigger->trigger_type][] = sprintf('\"%s\"', $ruleTrigger->trigger_value);\n }\n }\n\n // add local operators:\n foreach ($this->operators as $operator) {\n app('log')->debug(sprintf('SearchRuleEngine:: add local added operator: %s:\"%s\"', $operator['type'], $operator['value']));\n $searchArray[$operator['type']][] = sprintf('\"%s\"', $operator['value']);\n }\n $date = today(config('app.timezone'));\n if ($this->hasSpecificJournalTrigger($searchArray)) {\n $date = $this->setDateFromJournalTrigger($searchArray);\n }\n\n // build and run the search engine.\n $searchEngine = app(SearchInterface::class);\n $searchEngine->setUser($this->user);\n $searchEngine->setPage(1);\n $searchEngine->setLimit(31337);\n $searchEngine->setDate($date);\n app('log')->debug('Search array', $searchArray);\n foreach ($searchArray as $type => $searches) {\n foreach ($searches as $value) {\n $query = sprintf('%s:%s', $type, $value);\n app('log')->debug(sprintf('SearchRuleEngine:: add query \"%s\"', $query));\n $searchEngine->parseQuery($query);\n }\n }\n\n $result = $searchEngine->searchTransactions();\n\n return $result->getCollection();\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "protected function parseChunk()\n {\n $s = $this->count;\n\n // the directives\n if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] === '@') {\n if (\n $this->literal('@at-root', 8) &&\n ($this->selectors($selector) || true) &&\n ($this->map($with) || true) &&\n (($this->matchChar('(') &&\n $this->interpolation($with) &&\n $this->matchChar(')')) || true) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $atRoot = new AtRootBlock();\n $this->registerPushedBlock($atRoot, $s);\n $atRoot->selector = $selector;\n $atRoot->with = $with;\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@media', 6) &&\n $this->mediaQueryList($mediaQueryList) &&\n $this->matchChar('{', false)\n ) {\n $media = new MediaBlock();\n $this->registerPushedBlock($media, $s);\n $media->queryList = $mediaQueryList[2];\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@mixin', 6) &&\n $this->keyword($mixinName) &&\n ($this->argumentDef($args) || true) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $mixin = new CallableBlock(Type::T_MIXIN);\n $this->registerPushedBlock($mixin, $s);\n $mixin->name = $mixinName;\n $mixin->args = $args;\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n ($this->literal('@include', 8) &&\n $this->keyword($mixinName) &&\n ($this->matchChar('(') &&\n ($this->argValues($argValues) || true) &&\n $this->matchChar(')') || true) &&\n ($this->end()) ||\n ($this->literal('using', 5) &&\n $this->argumentDef($argUsing) &&\n ($this->end() || $this->matchChar('{') && $hasBlock = true)) ||\n $this->matchChar('{') && $hasBlock = true)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $child = [\n Type::T_INCLUDE,\n $mixinName,\n isset($argValues) ? $argValues : null,\n null,\n isset($argUsing) ? $argUsing : null\n ];\n\n if (! empty($hasBlock)) {\n $include = new ContentBlock();\n $this->registerPushedBlock($include, $s);\n $include->child = $child;\n } else {\n $this->append($child, $s);\n }\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@scssphp-import-once', 20) &&\n $this->valueList($importPath) &&\n $this->end()\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n list($line, $column) = $this->getSourcePosition($s);\n $file = $this->sourceName;\n $this->logger->warn(\"The \\\"@scssphp-import-once\\\" directive is deprecated and will be removed in ScssPhp 2.0, in \\\"$file\\\", line $line, column $column.\", true);\n\n $this->append([Type::T_SCSSPHP_IMPORT_ONCE, $importPath], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@import', 7) &&\n $this->valueList($importPath) &&\n $importPath[0] !== Type::T_FUNCTION_CALL &&\n $this->end()\n ) {\n if ($this->cssOnly) {\n $this->assertPlainCssValid([Type::T_IMPORT, $importPath], $s);\n $this->append([Type::T_COMMENT, rtrim(substr($this->buffer, $s, $this->count - $s))]);\n return true;\n }\n\n $this->append([Type::T_IMPORT, $importPath], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@import', 7) &&\n $this->url($importPath) &&\n $this->end()\n ) {\n if ($this->cssOnly) {\n $this->assertPlainCssValid([Type::T_IMPORT, $importPath], $s);\n $this->append([Type::T_COMMENT, rtrim(substr($this->buffer, $s, $this->count - $s))]);\n return true;\n }\n\n $this->append([Type::T_IMPORT, $importPath], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@extend', 7) &&\n $this->selectors($selectors) &&\n $this->end()\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n // check for '!flag'\n $optional = $this->stripOptionalFlag($selectors);\n $this->append([Type::T_EXTEND, $selectors, $optional], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@function', 9) &&\n $this->keyword($fnName) &&\n $this->argumentDef($args) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $func = new CallableBlock(Type::T_FUNCTION);\n $this->registerPushedBlock($func, $s);\n $func->name = $fnName;\n $func->args = $args;\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@return', 7) &&\n ($this->valueList($retVal) || true) &&\n $this->end()\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $this->append([Type::T_RETURN, isset($retVal) ? $retVal : [Type::T_NULL]], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@each', 5) &&\n $this->genericList($varNames, 'variable', ',', false) &&\n $this->literal('in', 2) &&\n $this->valueList($list) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $each = new EachBlock();\n $this->registerPushedBlock($each, $s);\n\n foreach ($varNames[2] as $varName) {\n $each->vars[] = $varName[1];\n }\n\n $each->list = $list;\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@while', 6) &&\n $this->expression($cond) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n while (\n $cond[0] === Type::T_LIST &&\n ! empty($cond['enclosing']) &&\n $cond['enclosing'] === 'parent' &&\n \\count($cond[2]) == 1\n ) {\n $cond = reset($cond[2]);\n }\n\n $while = new WhileBlock();\n $this->registerPushedBlock($while, $s);\n $while->cond = $cond;\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@for', 4) &&\n $this->variable($varName) &&\n $this->literal('from', 4) &&\n $this->expression($start) &&\n ($this->literal('through', 7) ||\n ($forUntil = true && $this->literal('to', 2))) &&\n $this->expression($end) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $for = new ForBlock();\n $this->registerPushedBlock($for, $s);\n $for->var = $varName[1];\n $for->start = $start;\n $for->end = $end;\n $for->until = isset($forUntil);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@if', 3) &&\n $this->functionCallArgumentsList($cond, false, '{', false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $if = new IfBlock();\n $this->registerPushedBlock($if, $s);\n\n while (\n $cond[0] === Type::T_LIST &&\n ! empty($cond['enclosing']) &&\n $cond['enclosing'] === 'parent' &&\n \\count($cond[2]) == 1\n ) {\n $cond = reset($cond[2]);\n }\n\n $if->cond = $cond;\n $if->cases = [];\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@debug', 6) &&\n $this->functionCallArgumentsList($value, false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $this->append([Type::T_DEBUG, $value], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@warn', 5) &&\n $this->functionCallArgumentsList($value, false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $this->append([Type::T_WARN, $value], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@error', 6) &&\n $this->functionCallArgumentsList($value, false)\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $this->append([Type::T_ERROR, $value], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@content', 8) &&\n ($this->end() ||\n $this->matchChar('(') &&\n $this->argValues($argContent) &&\n $this->matchChar(')') &&\n $this->end())\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n $this->append([Type::T_MIXIN_CONTENT, isset($argContent) ? $argContent : null], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n $last = $this->last();\n\n if (isset($last) && $last[0] === Type::T_IF) {\n list(, $if) = $last;\n assert($if instanceof IfBlock);\n\n if ($this->literal('@else', 5)) {\n if ($this->matchChar('{', false)) {\n $else = new ElseBlock();\n } elseif (\n $this->literal('if', 2) &&\n $this->functionCallArgumentsList($cond, false, '{', false)\n ) {\n $else = new ElseifBlock();\n $else->cond = $cond;\n }\n\n if (isset($else)) {\n $this->registerPushedBlock($else, $s);\n $if->cases[] = $else;\n\n return true;\n }\n }\n\n $this->seek($s);\n }\n\n // only retain the first @charset directive encountered\n if (\n $this->literal('@charset', 8) &&\n $this->valueList($charset) &&\n $this->end()\n ) {\n return true;\n }\n\n $this->seek($s);\n\n if (\n $this->literal('@supports', 9) &&\n ($t1 = $this->supportsQuery($supportQuery)) &&\n ($t2 = $this->matchChar('{', false))\n ) {\n $directive = new DirectiveBlock();\n $this->registerPushedBlock($directive, $s);\n $directive->name = 'supports';\n $directive->value = $supportQuery;\n\n return true;\n }\n\n $this->seek($s);\n\n // doesn't match built in directive, do generic one\n if (\n $this->matchChar('@', false) &&\n $this->mixedKeyword($dirName) &&\n $this->directiveValue($dirValue, '{')\n ) {\n if (count($dirName) === 1 && is_string(reset($dirName))) {\n $dirName = reset($dirName);\n } else {\n $dirName = [Type::T_STRING, '', $dirName];\n }\n if ($dirName === 'media') {\n $directive = new MediaBlock();\n } else {\n $directive = new DirectiveBlock();\n $directive->name = $dirName;\n }\n $this->registerPushedBlock($directive, $s);\n\n if (isset($dirValue)) {\n ! $this->cssOnly || ($dirValue = $this->assertPlainCssValid($dirValue));\n $directive->value = $dirValue;\n }\n\n return true;\n }\n\n $this->seek($s);\n\n // maybe it's a generic blockless directive\n if (\n $this->matchChar('@', false) &&\n $this->mixedKeyword($dirName) &&\n ! $this->isKnownGenericDirective($dirName) &&\n ($this->end(false) || ($this->directiveValue($dirValue, '') && $this->end(false)))\n ) {\n if (\\count($dirName) === 1 && \\is_string(\\reset($dirName))) {\n $dirName = \\reset($dirName);\n } else {\n $dirName = [Type::T_STRING, '', $dirName];\n }\n if (\n ! empty($this->env->parent) &&\n $this->env->type &&\n ! \\in_array($this->env->type, [Type::T_DIRECTIVE, Type::T_MEDIA])\n ) {\n $plain = \\trim(\\substr($this->buffer, $s, $this->count - $s));\n throw $this->parseError(\n \"Unknown directive `{$plain}` not allowed in `\" . $this->env->type . \"` block\"\n );\n }\n // blockless directives with a blank line after keeps their blank lines after\n // sass-spec compliance purpose\n $s = $this->count;\n $hasBlankLine = false;\n if ($this->match('\\s*?\\n\\s*\\n', $out, false)) {\n $hasBlankLine = true;\n $this->seek($s);\n }\n $isNotRoot = ! empty($this->env->parent);\n $this->append([Type::T_DIRECTIVE, [$dirName, $dirValue, $hasBlankLine, $isNotRoot]], $s);\n $this->whitespace();\n\n return true;\n }\n\n $this->seek($s);\n\n return false;\n }\n\n $inCssSelector = null;\n if ($this->cssOnly) {\n $inCssSelector = (! empty($this->env->parent) &&\n ! in_array($this->env->type, [Type::T_DIRECTIVE, Type::T_MEDIA]));\n }\n // custom properties : right part is static\n if (($this->customProperty($name) ) && $this->matchChar(':', false)) {\n $start = $this->count;\n\n // but can be complex and finish with ; or }\n foreach ([';','}'] as $ending) {\n if (\n $this->openString($ending, $stringValue, '(', ')', false) &&\n $this->end()\n ) {\n $end = $this->count;\n $value = $stringValue;\n\n // check if we have only a partial value due to nested [] or { } to take in account\n $nestingPairs = [['[', ']'], ['{', '}']];\n\n foreach ($nestingPairs as $nestingPair) {\n $p = strpos($this->buffer, $nestingPair[0], $start);\n\n if ($p && $p < $end) {\n $this->seek($start);\n\n if (\n $this->openString($ending, $stringValue, $nestingPair[0], $nestingPair[1], false) &&\n $this->end() &&\n $this->count > $end\n ) {\n $end = $this->count;\n $value = $stringValue;\n }\n }\n }\n\n $this->seek($end);\n $this->append([Type::T_CUSTOM_PROPERTY, $name, $value], $s);\n\n return true;\n }\n }\n\n // TODO: output an error here if nothing found according to sass spec\n }\n\n $this->seek($s);\n\n // property shortcut\n // captures most properties before having to parse a selector\n if (\n $this->keyword($name, false) &&\n $this->literal(': ', 2) &&\n $this->valueList($value) &&\n $this->end()\n ) {\n $name = [Type::T_STRING, '', [$name]];\n $this->append([Type::T_ASSIGN, $name, $value], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n // variable assigns\n if (\n $this->variable($name) &&\n $this->matchChar(':') &&\n $this->valueList($value) &&\n $this->end()\n ) {\n ! $this->cssOnly || $this->assertPlainCssValid(false, $s);\n\n // check for '!flag'\n $assignmentFlags = $this->stripAssignmentFlags($value);\n $this->append([Type::T_ASSIGN, $name, $value, $assignmentFlags], $s);\n\n return true;\n }\n\n $this->seek($s);\n\n // opening css block\n if (\n $this->selectors($selectors) &&\n $this->matchChar('{', false)\n ) {\n ! $this->cssOnly || ! $inCssSelector || $this->assertPlainCssValid(false);\n\n $this->pushBlock($selectors, $s);\n\n if ($this->eatWhiteDefault) {\n $this->whitespace();\n $this->append(null); // collect comments at the beginning if needed\n }\n\n return true;\n }\n\n $this->seek($s);\n\n // property assign, or nested assign\n if (\n $this->propertyName($name) &&\n $this->matchChar(':')\n ) {\n $foundSomething = false;\n\n if ($this->valueList($value)) {\n if (empty($this->env->parent)) {\n throw $this->parseError('expected \"{\"');\n }\n\n $this->append([Type::T_ASSIGN, $name, $value], $s);\n $foundSomething = true;\n }\n\n if ($this->matchChar('{', false)) {\n ! $this->cssOnly || $this->assertPlainCssValid(false);\n\n $propBlock = new NestedPropertyBlock();\n $this->registerPushedBlock($propBlock, $s);\n $propBlock->prefix = $name;\n $propBlock->hasValue = $foundSomething;\n\n $foundSomething = true;\n } elseif ($foundSomething) {\n $foundSomething = $this->end();\n }\n\n if ($foundSomething) {\n return true;\n }\n }\n\n $this->seek($s);\n\n // closing a block\n if ($this->matchChar('}', false)) {\n $block = $this->popBlock();\n\n if (! isset($block->type) || $block->type !== Type::T_IF) {\n assert($this->env !== null);\n\n if ($this->env->parent) {\n $this->append(null); // collect comments before next statement if needed\n }\n }\n\n if ($block instanceof ContentBlock) {\n $include = $block->child;\n assert(\\is_array($include));\n unset($block->child);\n $include[3] = $block;\n $this->append($include, $s);\n } elseif (!$block instanceof ElseBlock && !$block instanceof ElseifBlock) {\n $type = isset($block->type) ? $block->type : Type::T_BLOCK;\n $this->append([$type, $block], $s);\n }\n\n // collect comments just after the block closing if needed\n if ($this->eatWhiteDefault) {\n $this->whitespace();\n assert($this->env !== null);\n\n if ($this->env->comments) {\n $this->append(null);\n }\n }\n\n return true;\n }\n\n // extra stuff\n if ($this->matchChar(';')) {\n return true;\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function findLanguage(?string $appId = null): string {\n\t\t// Step 1: Forced language always has precedence over anything else\n\t\t$forceLang = $this->config->getSystemValue('force_language', false);\n\t\tif (is_string($forceLang)) {\n\t\t\t$this->requestLanguage = $forceLang;\n\t\t}\n\n\t\t// Step 2: Return cached language\n\t\tif ($this->requestLanguage !== '' && $this->languageExists($appId, $this->requestLanguage)) {\n\t\t\treturn $this->requestLanguage;\n\t\t}\n\n\t\t/**\n\t\t * Step 3: At this point Nextcloud might not yet be installed and thus the lookup\n\t\t * in the preferences table might fail. For this reason we need to check\n\t\t * whether the instance has already been installed\n\t\t *\n\t\t * @link https://github.com/owncloud/core/issues/21955\n\t\t */\n\t\tif ($this->config->getSystemValueBool('installed', false)) {\n\t\t\t$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;\n\t\t\tif (!is_null($userId)) {\n\t\t\t\t$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);\n\t\t\t} else {\n\t\t\t\t$userLang = null;\n\t\t\t}\n\t\t} else {\n\t\t\t$userId = null;\n\t\t\t$userLang = null;\n\t\t}\n\t\tif ($userLang) {\n\t\t\t$this->requestLanguage = $userLang;\n\t\t\tif ($this->languageExists($appId, $userLang)) {\n\t\t\t\treturn $userLang;\n\t\t\t}\n\t\t}\n\n\t\t// Step 4: Check the request headers\n\t\ttry {\n\t\t\t// Try to get the language from the Request\n\t\t\t$lang = $this->getLanguageFromRequest($appId);\n\t\t\tif ($userId !== null && $appId === null && !$userLang) {\n\t\t\t\t$this->config->setUserValue($userId, 'core', 'lang', $lang);\n\t\t\t}\n\t\t\treturn $lang;\n\t\t} catch (LanguageNotFoundException $e) {\n\t\t\t// Finding language from request failed fall back to default language\n\t\t\t$defaultLanguage = $this->config->getSystemValue('default_language', false);\n\t\t\tif ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {\n\t\t\t\treturn $defaultLanguage;\n\t\t\t}\n\t\t}\n\n\t\t// Step 5: fall back to English\n\t\treturn 'en';\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function sanitizeZip($zipLocation)\n {\n // TODO: @adunsulag NOTE that zip files can be in any order... so we can't assume that this is alphabetical\n // to fix this may involve extracting the zip and re-ordering all of the entries...\n // another one would be to just create hash map indexes with patient names mapped to nested documents...\n // this will only be an issue if we are migrating documents as the CCDA files themselves are self-contained\n // TODO: fire off an event about sanitizing the zip file\n // should have sanitization settings and let someone filter them...\n // event response should have a boolean for skipSanitization in case a module has already done the sanitization\n\n $z = new \\ZipArchive();\n // if a zip file exist we want to overwrite it when we save\n $z->open($zipLocation);\n $z->setArchiveComment(\"\"); // remove any comments so we don't deal with buffer overflows on the zip extraction\n $patientCountHash = [];\n $patientCount = 0;\n $patientNameIndex = 1;\n $patientDocumentsIndex = 2;\n $maxPatients = 500;\n $maxDocuments = 500;\n $maxFileComponents = 5;\n\n for ($i = 0; $i < $z->numFiles; $i++) {\n $stat = $z->statIndex($i);\n // explode and make sure we have our three parts\n // our max directory structure is 4... anything more than that and we will bail\n $fileComponents = explode(\"/\", str_replace('\\\\', '/', $stat['name']), 5);\n $componentCount = count($fileComponents);\n $shouldDeleteIndex = false;\n\n // now we need to do our document import for our ccda for this patient\n if ($componentCount <= $patientNameIndex) {\n $shouldDeleteIndex = false; // we don't want to delete if we are in folders before our patient name index\n } elseif ($componentCount == ($patientNameIndex + 1)) {\n // if they have more than maxDocuments in ccd files we need to break out of someone trying to directory\n // bomb the file system\n $patientCountHash[$patientNameIndex] = $patientCountHash[$patientNameIndex] ?? 0;\n\n // let's check for ccda\n if ($patientCount > $maxPatients) {\n $shouldDeleteIndex = true; // no more processing of patient ccdas as we've reached our max import size\n } elseif ($patientCountHash[$patientNameIndex] > $maxDocuments) {\n $shouldDeleteIndex = true;\n // can fire off events for modifying what files we keep / process...\n // we don't process anything but xml ccds\n } elseif (strrpos($fileComponents[$patientNameIndex], '.xml') === false) {\n $shouldDeleteIndex = true;\n // if we have a ccd we need to set our document count and increment our patient count\n // note this logic allows multiple patient ccds to be here as long as they are in the same folder\n } elseif (!isset($patientCountHash[$fileComponents[$patientNameIndex]])) {\n $patientCountHash[$patientNameIndex] = 0;\n $patientCount++;\n } else {\n $patientCountHash[$patientNameIndex];\n }\n } elseif ($componentCount == ($patientDocumentsIndex + 1)) {\n if ($patientCountHash[$patientNameIndex] ?? '' > $maxDocuments) {\n $shouldDeleteIndex = true;\n } else {\n if (!empty($patientCountHash[$patientNameIndex])) {\n $patientCountHash[$patientNameIndex] += 1;\n } else {\n $patientCountHash[$patientNameIndex] = 0;\n }\n }\n } else {\n $shouldDeleteIndex = true;\n }\n\n // TODO: fire off an event with the patient name, current index, file name, and zip archive object\n // we can filter on whether we should keep this and let module writers do their own thing if they want to\n // retain any of the documents or not for their own custom processing.\n if ($shouldDeleteIndex) {\n $z->deleteIndex($i);\n }\n }\n $z->close();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct($webRoot, \\OC\\Config $config) {\n\t\tparent::__construct();\n\t\t$this->webRoot = $webRoot;\n\n\t\t// To find out if we are running from CLI or not\n\t\t$this->registerParameter('isCLI', \\OC::$CLI);\n\t\t$this->registerParameter('serverRoot', \\OC::$SERVERROOT);\n\n\t\t$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {\n\t\t\treturn $c;\n\t\t});\n\t\t$this->registerService(\\OCP\\IServerContainer::class, function (ContainerInterface $c) {\n\t\t\treturn $c;\n\t\t});\n\n\t\t$this->registerAlias(\\OCP\\Calendar\\IManager::class, \\OC\\Calendar\\Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CalendarManager', \\OC\\Calendar\\Manager::class);\n\n\t\t$this->registerAlias(\\OCP\\Calendar\\Resource\\IManager::class, \\OC\\Calendar\\Resource\\Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CalendarResourceBackendManager', \\OC\\Calendar\\Resource\\Manager::class);\n\n\t\t$this->registerAlias(\\OCP\\Calendar\\Room\\IManager::class, \\OC\\Calendar\\Room\\Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CalendarRoomBackendManager', \\OC\\Calendar\\Room\\Manager::class);\n\n\t\t$this->registerAlias(\\OCP\\Contacts\\IManager::class, \\OC\\ContactsManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('ContactsManager', \\OCP\\Contacts\\IManager::class);\n\n\t\t$this->registerAlias(\\OCP\\DirectEditing\\IManager::class, \\OC\\DirectEditing\\Manager::class);\n\t\t$this->registerAlias(ITemplateManager::class, TemplateManager::class);\n\n\t\t$this->registerAlias(IActionFactory::class, ActionFactory::class);\n\n\t\t$this->registerService(View::class, function (Server $c) {\n\t\t\treturn new View();\n\t\t}, false);\n\n\t\t$this->registerService(IPreview::class, function (ContainerInterface $c) {\n\t\t\treturn new PreviewManager(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\tnew \\OC\\Preview\\Storage\\Root(\n\t\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\t\t$c->get(SystemConfig::class)\n\t\t\t\t),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t\t$c->get(GeneratorHelper::class),\n\t\t\t\t$c->get(ISession::class)->get('user_id'),\n\t\t\t\t$c->get(Coordinator::class),\n\t\t\t\t$c->get(IServerContainer::class),\n\t\t\t\t$c->get(IBinaryFinder::class),\n\t\t\t\t$c->get(IMagickSupport::class)\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('PreviewManager', IPreview::class);\n\t\t$this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);\n\n\t\t$this->registerService(\\OC\\Preview\\Watcher::class, function (ContainerInterface $c) {\n\t\t\treturn new \\OC\\Preview\\Watcher(\n\t\t\t\tnew \\OC\\Preview\\Storage\\Root(\n\t\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\t\t$c->get(SystemConfig::class)\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService(IProfiler::class, function (Server $c) {\n\t\t\treturn new Profiler($c->get(SystemConfig::class));\n\t\t});\n\n\t\t$this->registerService(\\OCP\\Encryption\\IManager::class, function (Server $c): Encryption\\Manager {\n\t\t\t$view = new View();\n\t\t\t$util = new Encryption\\Util(\n\t\t\t\t$view,\n\t\t\t\t$c->get(IUserManager::class),\n\t\t\t\t$c->get(IGroupManager::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class)\n\t\t\t);\n\t\t\treturn new Encryption\\Manager(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->getL10N('core'),\n\t\t\t\tnew View(),\n\t\t\t\t$util,\n\t\t\t\tnew ArrayCache()\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('EncryptionManager', \\OCP\\Encryption\\IManager::class);\n\n\t\t/** @deprecated 21.0.0 */\n\t\t$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);\n\t\t$this->registerService(IFile::class, function (ContainerInterface $c) {\n\t\t\t$util = new Encryption\\Util(\n\t\t\t\tnew View(),\n\t\t\t\t$c->get(IUserManager::class),\n\t\t\t\t$c->get(IGroupManager::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class)\n\t\t\t);\n\t\t\treturn new Encryption\\File(\n\t\t\t\t$util,\n\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\t$c->get(\\OCP\\Share\\IManager::class)\n\t\t\t);\n\t\t});\n\n\t\t/** @deprecated 21.0.0 */\n\t\t$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);\n\t\t$this->registerService(IStorage::class, function (ContainerInterface $c) {\n\t\t\t$view = new View();\n\t\t\t$util = new Encryption\\Util(\n\t\t\t\t$view,\n\t\t\t\t$c->get(IUserManager::class),\n\t\t\t\t$c->get(IGroupManager::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class)\n\t\t\t);\n\n\t\t\treturn new Encryption\\Keys\\Storage(\n\t\t\t\t$view,\n\t\t\t\t$util,\n\t\t\t\t$c->get(ICrypto::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class)\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 20.0.0 */\n\t\t$this->registerDeprecatedAlias('TagMapper', TagMapper::class);\n\n\t\t$this->registerAlias(\\OCP\\ITagManager::class, TagManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('TagManager', \\OCP\\ITagManager::class);\n\n\t\t$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {\n\t\t\t/** @var \\OCP\\IConfig $config */\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);\n\t\t\treturn new $factoryClass($this);\n\t\t});\n\t\t$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {\n\t\t\treturn $c->get('SystemTagManagerFactory')->getManager();\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);\n\n\t\t$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {\n\t\t\treturn $c->get('SystemTagManagerFactory')->getObjectMapper();\n\t\t});\n\t\t$this->registerAlias(IFileAccess::class, FileAccess::class);\n\t\t$this->registerService('RootFolder', function (ContainerInterface $c) {\n\t\t\t$manager = \\OC\\Files\\Filesystem::getMountManager();\n\t\t\t$view = new View();\n\t\t\t/** @var IUserSession $userSession */\n\t\t\t$userSession = $c->get(IUserSession::class);\n\t\t\t$root = new Root(\n\t\t\t\t$manager,\n\t\t\t\t$view,\n\t\t\t\t$userSession->getUser(),\n\t\t\t\t$c->get(IUserMountCache::class),\n\t\t\t\t$this->get(LoggerInterface::class),\n\t\t\t\t$this->get(IUserManager::class),\n\t\t\t\t$this->get(IEventDispatcher::class),\n\t\t\t\t$this->get(ICacheFactory::class),\n\t\t\t);\n\n\t\t\t$previewConnector = new \\OC\\Preview\\WatcherConnector(\n\t\t\t\t$root,\n\t\t\t\t$c->get(SystemConfig::class)\n\t\t\t);\n\t\t\t$previewConnector->connectWatcher();\n\n\t\t\treturn $root;\n\t\t});\n\t\t$this->registerService(HookConnector::class, function (ContainerInterface $c) {\n\t\t\treturn new HookConnector(\n\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\tnew View(),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t\t$c->get(LoggerInterface::class)\n\t\t\t);\n\t\t});\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);\n\n\t\t$this->registerService(IRootFolder::class, function (ContainerInterface $c) {\n\t\t\treturn new LazyRoot(function () use ($c) {\n\t\t\t\treturn $c->get('RootFolder');\n\t\t\t});\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('UserManager', \\OC\\User\\Manager::class);\n\t\t$this->registerAlias(\\OCP\\IUserManager::class, \\OC\\User\\Manager::class);\n\n\t\t$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {\n\t\t\treturn $c->get(\\OC\\User\\Manager::class)->getDisplayNameCache();\n\t\t});\n\n\t\t$this->registerService(\\OCP\\IGroupManager::class, function (ContainerInterface $c) {\n\t\t\t$groupManager = new \\OC\\Group\\Manager(\n\t\t\t\t$this->get(IUserManager::class),\n\t\t\t\t$this->get(IEventDispatcher::class),\n\t\t\t\t$this->get(LoggerInterface::class),\n\t\t\t\t$this->get(ICacheFactory::class)\n\t\t\t);\n\t\t\treturn $groupManager;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('GroupManager', \\OCP\\IGroupManager::class);\n\n\t\t$this->registerService(Store::class, function (ContainerInterface $c) {\n\t\t\t$session = $c->get(ISession::class);\n\t\t\tif (\\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {\n\t\t\t\t$tokenProvider = $c->get(IProvider::class);\n\t\t\t} else {\n\t\t\t\t$tokenProvider = null;\n\t\t\t}\n\t\t\t$logger = $c->get(LoggerInterface::class);\n\t\t\treturn new Store($session, $logger, $tokenProvider);\n\t\t});\n\t\t$this->registerAlias(IStore::class, Store::class);\n\t\t$this->registerAlias(IProvider::class, Authentication\\Token\\Manager::class);\n\t\t$this->registerAlias(OCPIProvider::class, Authentication\\Token\\Manager::class);\n\n\t\t$this->registerService(\\OC\\User\\Session::class, function (Server $c) {\n\t\t\t$manager = $c->get(IUserManager::class);\n\t\t\t$session = new \\OC\\Session\\Memory();\n\t\t\t$timeFactory = new TimeFactory();\n\t\t\t// Token providers might require a working database. This code\n\t\t\t// might however be called when Nextcloud is not yet setup.\n\t\t\tif (\\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {\n\t\t\t\t$provider = $c->get(IProvider::class);\n\t\t\t} else {\n\t\t\t\t$provider = null;\n\t\t\t}\n\n\t\t\t$userSession = new \\OC\\User\\Session(\n\t\t\t\t$manager,\n\t\t\t\t$session,\n\t\t\t\t$timeFactory,\n\t\t\t\t$provider,\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(ISecureRandom::class),\n\t\t\t\t$c->get('LockdownManager'),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t);\n\t\t\t/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */\n\t\t\t$userSession->listen('\\OC\\User', 'preCreateUser', function ($uid, $password) {\n\t\t\t\t\\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);\n\t\t\t});\n\t\t\t/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */\n\t\t\t$userSession->listen('\\OC\\User', 'postCreateUser', function ($user, $password) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);\n\t\t\t});\n\t\t\t/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */\n\t\t\t$userSession->listen('\\OC\\User', 'preDelete', function ($user) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);\n\t\t\t});\n\t\t\t/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */\n\t\t\t$userSession->listen('\\OC\\User', 'postDelete', function ($user) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'preLogin', function ($uid, $password) {\n\t\t\t\t\\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);\n\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);\n\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'preRememberedLogin', function ($uid) {\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'postRememberedLogin', function ($user, $password) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);\n\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'logout', function ($user) {\n\t\t\t\t\\OC_Hook::emit('OC_User', 'logout', []);\n\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'postLogout', function ($user) {\n\t\t\t\t/** @var IEventDispatcher $dispatcher */\n\t\t\t\t$dispatcher = $this->get(IEventDispatcher::class);\n\t\t\t\t$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));\n\t\t\t});\n\t\t\t$userSession->listen('\\OC\\User', 'changeUser', function ($user, $feature, $value, $oldValue) {\n\t\t\t\t/** @var \\OC\\User\\User $user */\n\t\t\t\t\\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);\n\t\t\t});\n\t\t\treturn $userSession;\n\t\t});\n\t\t$this->registerAlias(\\OCP\\IUserSession::class, \\OC\\User\\Session::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('UserSession', \\OC\\User\\Session::class);\n\n\t\t$this->registerAlias(\\OCP\\Authentication\\TwoFactorAuth\\IRegistry::class, \\OC\\Authentication\\TwoFactorAuth\\Registry::class);\n\n\t\t$this->registerAlias(INavigationManager::class, \\OC\\NavigationManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('AllConfig', \\OC\\AllConfig::class);\n\t\t$this->registerAlias(\\OCP\\IConfig::class, \\OC\\AllConfig::class);\n\n\t\t$this->registerService(\\OC\\SystemConfig::class, function ($c) use ($config) {\n\t\t\treturn new \\OC\\SystemConfig($config);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('SystemConfig', \\OC\\SystemConfig::class);\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('AppConfig', \\OC\\AppConfig::class);\n\t\t$this->registerAlias(IAppConfig::class, \\OC\\AppConfig::class);\n\n\t\t$this->registerService(IFactory::class, function (Server $c) {\n\t\t\treturn new \\OC\\L10N\\Factory(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->getRequest(),\n\t\t\t\t$c->get(IUserSession::class),\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t\\OC::$SERVERROOT\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('L10NFactory', IFactory::class);\n\n\t\t$this->registerAlias(IURLGenerator::class, URLGenerator::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);\n\n\t\t$this->registerService(ICache::class, function ($c) {\n\t\t\treturn new Cache\\File();\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('UserCache', ICache::class);\n\n\t\t$this->registerService(Factory::class, function (Server $c) {\n\t\t\t$profiler = $c->get(IProfiler::class);\n\t\t\t$arrayCacheFactory = new \\OC\\Memcache\\Factory('', $c->get(LoggerInterface::class),\n\t\t\t\t$profiler,\n\t\t\t\tArrayCache::class,\n\t\t\t\tArrayCache::class,\n\t\t\t\tArrayCache::class\n\t\t\t);\n\t\t\t/** @var \\OCP\\IConfig $config */\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\n\t\t\tif ($config->getSystemValueBool('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {\n\t\t\t\tif (!$config->getSystemValueBool('log_query')) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t$v = \\OC_App::getAppVersions();\n\t\t\t\t\t} catch (\\Doctrine\\DBAL\\Exception $e) {\n\t\t\t\t\t\t// Database service probably unavailable\n\t\t\t\t\t\t// Probably related to https://github.com/nextcloud/server/issues/37424\n\t\t\t\t\t\treturn $arrayCacheFactory;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// If the log_query is enabled, we can not get the app versions\n\t\t\t\t\t// as that does a query, which will be logged and the logging\n\t\t\t\t\t// depends on redis and here we are back again in the same function.\n\t\t\t\t\t$v = [\n\t\t\t\t\t\t'log_query' => 'enabled',\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\t$v['core'] = implode(',', \\OC_Util::getVersion());\n\t\t\t\t$version = implode(',', $v);\n\t\t\t\t$instanceId = \\OC_Util::getInstanceId();\n\t\t\t\t$path = \\OC::$SERVERROOT;\n\t\t\t\t$prefix = md5($instanceId . '-' . $version . '-' . $path);\n\t\t\t\treturn new \\OC\\Memcache\\Factory($prefix,\n\t\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t\t$profiler,\n\t\t\t\t\t$config->getSystemValue('memcache.local', null),\n\t\t\t\t\t$config->getSystemValue('memcache.distributed', null),\n\t\t\t\t\t$config->getSystemValue('memcache.locking', null),\n\t\t\t\t\t$config->getSystemValueString('redis_log_file')\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn $arrayCacheFactory;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);\n\t\t$this->registerAlias(ICacheFactory::class, Factory::class);\n\n\t\t$this->registerService('RedisFactory', function (Server $c) {\n\t\t\t$systemConfig = $c->get(SystemConfig::class);\n\t\t\treturn new RedisFactory($systemConfig, $c->get(IEventLogger::class));\n\t\t});\n\n\t\t$this->registerService(\\OCP\\Activity\\IManager::class, function (Server $c) {\n\t\t\t$l10n = $this->get(IFactory::class)->get('lib');\n\t\t\treturn new \\OC\\Activity\\Manager(\n\t\t\t\t$c->getRequest(),\n\t\t\t\t$c->get(IUserSession::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(IValidator::class),\n\t\t\t\t$l10n\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('ActivityManager', \\OCP\\Activity\\IManager::class);\n\n\t\t$this->registerService(\\OCP\\Activity\\IEventMerger::class, function (Server $c) {\n\t\t\treturn new \\OC\\Activity\\EventMerger(\n\t\t\t\t$c->getL10N('lib')\n\t\t\t);\n\t\t});\n\t\t$this->registerAlias(IValidator::class, Validator::class);\n\n\t\t$this->registerService(AvatarManager::class, function (Server $c) {\n\t\t\treturn new AvatarManager(\n\t\t\t\t$c->get(IUserSession::class),\n\t\t\t\t$c->get(\\OC\\User\\Manager::class),\n\t\t\t\t$c->getAppDataDir('avatar'),\n\t\t\t\t$c->getL10N('lib'),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(IAccountManager::class),\n\t\t\t\t$c->get(KnownUserService::class)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerAlias(IAvatarManager::class, AvatarManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);\n\n\t\t$this->registerAlias(\\OCP\\Support\\CrashReport\\IRegistry::class, \\OC\\Support\\CrashReport\\Registry::class);\n\t\t$this->registerAlias(\\OCP\\Support\\Subscription\\IRegistry::class, \\OC\\Support\\Subscription\\Registry::class);\n\t\t$this->registerAlias(\\OCP\\Support\\Subscription\\IAssertion::class, \\OC\\Support\\Subscription\\Assertion::class);\n\n\t\t$this->registerService(\\OC\\Log::class, function (Server $c) {\n\t\t\t$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');\n\t\t\t$factory = new LogFactory($c, $this->get(SystemConfig::class));\n\t\t\t$logger = $factory->get($logType);\n\t\t\t$registry = $c->get(\\OCP\\Support\\CrashReport\\IRegistry::class);\n\n\t\t\treturn new Log($logger, $this->get(SystemConfig::class), null, $registry);\n\t\t});\n\t\t$this->registerAlias(ILogger::class, \\OC\\Log::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Logger', \\OC\\Log::class);\n\t\t// PSR-3 logger\n\t\t$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);\n\n\t\t$this->registerService(ILogFactory::class, function (Server $c) {\n\t\t\treturn new LogFactory($c, $this->get(SystemConfig::class));\n\t\t});\n\n\t\t$this->registerAlias(IJobList::class, \\OC\\BackgroundJob\\JobList::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('JobList', IJobList::class);\n\n\t\t$this->registerService(Router::class, function (Server $c) {\n\t\t\t$cacheFactory = $c->get(ICacheFactory::class);\n\t\t\tif ($cacheFactory->isLocalCacheAvailable()) {\n\t\t\t\t$router = $c->resolve(CachingRouter::class);\n\t\t\t} else {\n\t\t\t\t$router = $c->resolve(Router::class);\n\t\t\t}\n\t\t\treturn $router;\n\t\t});\n\t\t$this->registerAlias(IRouter::class, Router::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Router', IRouter::class);\n\n\t\t$this->registerAlias(ISearch::class, Search::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Search', ISearch::class);\n\n\t\t$this->registerService(\\OC\\Security\\RateLimiting\\Backend\\IBackend::class, function ($c) {\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\tif (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\\\') === \\OC\\Memcache\\Redis::class) {\n\t\t\t\t$backend = new \\OC\\Security\\RateLimiting\\Backend\\MemoryCacheBackend(\n\t\t\t\t\t$c->get(AllConfig::class),\n\t\t\t\t\t$this->get(ICacheFactory::class),\n\t\t\t\t\tnew \\OC\\AppFramework\\Utility\\TimeFactory()\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t$backend = new \\OC\\Security\\RateLimiting\\Backend\\DatabaseBackend(\n\t\t\t\t\t$c->get(AllConfig::class),\n\t\t\t\t\t$c->get(IDBConnection::class),\n\t\t\t\t\tnew \\OC\\AppFramework\\Utility\\TimeFactory()\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn $backend;\n\t\t});\n\n\t\t$this->registerAlias(\\OCP\\Security\\ISecureRandom::class, SecureRandom::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('SecureRandom', \\OCP\\Security\\ISecureRandom::class);\n\t\t$this->registerAlias(\\OCP\\Security\\IRemoteHostValidator::class, \\OC\\Security\\RemoteHostValidator::class);\n\t\t$this->registerAlias(IVerificationToken::class, VerificationToken::class);\n\n\t\t$this->registerAlias(ICrypto::class, Crypto::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Crypto', ICrypto::class);\n\n\t\t$this->registerAlias(IHasher::class, Hasher::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Hasher', IHasher::class);\n\n\t\t$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);\n\n\t\t$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);\n\t\t$this->registerService(Connection::class, function (Server $c) {\n\t\t\t$systemConfig = $c->get(SystemConfig::class);\n\t\t\t$factory = new \\OC\\DB\\ConnectionFactory($systemConfig);\n\t\t\t$type = $systemConfig->getValue('dbtype', 'sqlite');\n\t\t\tif (!$factory->isValidType($type)) {\n\t\t\t\tthrow new \\OC\\DatabaseException('Invalid database type');\n\t\t\t}\n\t\t\t$connection = $factory->getConnection($type, []);\n\t\t\treturn $connection;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);\n\n\t\t$this->registerAlias(ICertificateManager::class, CertificateManager::class);\n\t\t$this->registerAlias(IClientService::class, ClientService::class);\n\t\t$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {\n\t\t\treturn new NegativeDnsCache(\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t);\n\t\t});\n\t\t$this->registerDeprecatedAlias('HttpClientService', IClientService::class);\n\t\t$this->registerService(IEventLogger::class, function (ContainerInterface $c) {\n\t\t\treturn new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);\n\n\t\t$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {\n\t\t\t$queryLogger = new QueryLogger();\n\t\t\tif ($c->get(SystemConfig::class)->getValue('debug', false)) {\n\t\t\t\t// In debug mode, module is being activated by default\n\t\t\t\t$queryLogger->activate();\n\t\t\t}\n\t\t\treturn $queryLogger;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);\n\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('TempManager', TempManager::class);\n\t\t$this->registerAlias(ITempManager::class, TempManager::class);\n\n\t\t$this->registerService(AppManager::class, function (ContainerInterface $c) {\n\t\t\t// TODO: use auto-wiring\n\t\t\treturn new \\OC\\App\\AppManager(\n\t\t\t\t$c->get(IUserSession::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(\\OC\\AppConfig::class),\n\t\t\t\t$c->get(IGroupManager::class),\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('AppManager', AppManager::class);\n\t\t$this->registerAlias(IAppManager::class, AppManager::class);\n\n\t\t$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);\n\n\t\t$this->registerService(IDateTimeFormatter::class, function (Server $c) {\n\t\t\t$language = $c->get(\\OCP\\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);\n\n\t\t\treturn new DateTimeFormatter(\n\t\t\t\t$c->get(IDateTimeZone::class)->getTimeZone(),\n\t\t\t\t$c->getL10N('lib', $language)\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);\n\n\t\t$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {\n\t\t\t$mountCache = $c->get(UserMountCache::class);\n\t\t\t$listener = new UserMountCacheListener($mountCache);\n\t\t\t$listener->listen($c->get(IUserManager::class));\n\t\t\treturn $mountCache;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);\n\n\t\t$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {\n\t\t\t$loader = $c->get(IStorageFactory::class);\n\t\t\t$mountCache = $c->get(IUserMountCache::class);\n\t\t\t$eventLogger = $c->get(IEventLogger::class);\n\t\t\t$manager = new MountProviderCollection($loader, $mountCache, $eventLogger);\n\n\t\t\t// builtin providers\n\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$logger = $c->get(LoggerInterface::class);\n\t\t\t$manager->registerProvider(new CacheMountProvider($config));\n\t\t\t$manager->registerHomeProvider(new LocalHomeMountProvider());\n\t\t\t$manager->registerHomeProvider(new ObjectHomeMountProvider($config));\n\t\t\t$manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));\n\t\t\t$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));\n\n\t\t\treturn $manager;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);\n\n\t\t/** @deprecated 20.0.0 */\n\t\t$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);\n\t\t$this->registerService(IBus::class, function (ContainerInterface $c) {\n\t\t\t$busClass = $c->get(\\OCP\\IConfig::class)->getSystemValueString('commandbus');\n\t\t\tif ($busClass) {\n\t\t\t\t[$app, $class] = explode('::', $busClass, 2);\n\t\t\t\tif ($c->get(IAppManager::class)->isInstalled($app)) {\n\t\t\t\t\t\\OC_App::loadApp($app);\n\t\t\t\t\treturn $c->get($class);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ServiceUnavailableException(\"The app providing the command bus ($app) is not enabled\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$jobList = $c->get(IJobList::class);\n\t\t\t\treturn new CronBus($jobList);\n\t\t\t}\n\t\t});\n\t\t$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);\n\t\t/** @deprecated 20.0.0 */\n\t\t$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);\n\t\t$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Throttler', Throttler::class);\n\t\t$this->registerAlias(IThrottler::class, Throttler::class);\n\n\t\t$this->registerService(\\OC\\Security\\Bruteforce\\Backend\\IBackend::class, function ($c) {\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\tif (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\\\') === \\OC\\Memcache\\Redis::class) {\n\t\t\t\t$backend = $c->get(\\OC\\Security\\Bruteforce\\Backend\\MemoryCacheBackend::class);\n\t\t\t} else {\n\t\t\t\t$backend = $c->get(\\OC\\Security\\Bruteforce\\Backend\\DatabaseBackend::class);\n\t\t\t}\n\n\t\t\treturn $backend;\n\t\t});\n\n\t\t$this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);\n\t\t$this->registerService(Checker::class, function (ContainerInterface $c) {\n\t\t\t// IConfig and IAppManager requires a working database. This code\n\t\t\t// might however be called when ownCloud is not yet setup.\n\t\t\tif (\\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {\n\t\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t\t$appConfig = $c->get(\\OCP\\IAppConfig::class);\n\t\t\t\t$appManager = $c->get(IAppManager::class);\n\t\t\t} else {\n\t\t\t\t$config = $appConfig = $appManager = null;\n\t\t\t}\n\n\t\t\treturn new Checker(\n\t\t\t\tnew EnvironmentHelper(),\n\t\t\t\tnew FileAccessHelper(),\n\t\t\t\tnew AppLocator(),\n\t\t\t\t$config,\n\t\t\t\t$appConfig,\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t$appManager,\n\t\t\t\t$c->get(IMimeTypeDetector::class)\n\t\t\t);\n\t\t});\n\t\t$this->registerService(\\OCP\\IRequest::class, function (ContainerInterface $c) {\n\t\t\tif (isset($this['urlParams'])) {\n\t\t\t\t$urlParams = $this['urlParams'];\n\t\t\t} else {\n\t\t\t\t$urlParams = [];\n\t\t\t}\n\n\t\t\tif (defined('PHPUNIT_RUN') && PHPUNIT_RUN\n\t\t\t\t&& in_array('fakeinput', stream_get_wrappers())\n\t\t\t) {\n\t\t\t\t$stream = 'fakeinput://data';\n\t\t\t} else {\n\t\t\t\t$stream = 'php://input';\n\t\t\t}\n\n\t\t\treturn new Request(\n\t\t\t\t[\n\t\t\t\t\t'get' => $_GET,\n\t\t\t\t\t'post' => $_POST,\n\t\t\t\t\t'files' => $_FILES,\n\t\t\t\t\t'server' => $_SERVER,\n\t\t\t\t\t'env' => $_ENV,\n\t\t\t\t\t'cookies' => $_COOKIE,\n\t\t\t\t\t'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))\n\t\t\t\t\t\t? $_SERVER['REQUEST_METHOD']\n\t\t\t\t\t\t: '',\n\t\t\t\t\t'urlParams' => $urlParams,\n\t\t\t\t],\n\t\t\t\t$this->get(IRequestId::class),\n\t\t\t\t$this->get(\\OCP\\IConfig::class),\n\t\t\t\t$this->get(CsrfTokenManager::class),\n\t\t\t\t$stream\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Request', \\OCP\\IRequest::class);\n\n\t\t$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {\n\t\t\treturn new RequestId(\n\t\t\t\t$_SERVER['UNIQUE_ID'] ?? '',\n\t\t\t\t$this->get(ISecureRandom::class)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService(IMailer::class, function (Server $c) {\n\t\t\treturn new Mailer(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->get(Defaults::class),\n\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t$c->getL10N('lib'),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t\t$c->get(IFactory::class)\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Mailer', IMailer::class);\n\n\t\t/** @deprecated 21.0.0 */\n\t\t$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);\n\n\t\t$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$factoryClass = $config->getSystemValue('ldapProviderFactory', null);\n\t\t\tif (is_null($factoryClass) || !class_exists($factoryClass)) {\n\t\t\t\treturn new NullLDAPProviderFactory($this);\n\t\t\t}\n\t\t\t/** @var \\OCP\\LDAP\\ILDAPProviderFactory $factory */\n\t\t\treturn new $factoryClass($this);\n\t\t});\n\t\t$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {\n\t\t\t$factory = $c->get(ILDAPProviderFactory::class);\n\t\t\treturn $factory->getLDAPProvider();\n\t\t});\n\t\t$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {\n\t\t\t$ini = $c->get(IniGetWrapper::class);\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));\n\t\t\tif ($config->getSystemValueBool('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {\n\t\t\t\t/** @var \\OC\\Memcache\\Factory $memcacheFactory */\n\t\t\t\t$memcacheFactory = $c->get(ICacheFactory::class);\n\t\t\t\t$memcache = $memcacheFactory->createLocking('lock');\n\t\t\t\tif (!($memcache instanceof \\OC\\Memcache\\NullCache)) {\n\t\t\t\t\t$timeFactory = $c->get(ITimeFactory::class);\n\t\t\t\t\treturn new MemcacheLockingProvider($memcache, $timeFactory, $ttl);\n\t\t\t\t}\n\t\t\t\treturn new DBLockingProvider(\n\t\t\t\t\t$c->get(IDBConnection::class),\n\t\t\t\t\tnew TimeFactory(),\n\t\t\t\t\t$ttl,\n\t\t\t\t\t!\\OC::$CLI\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn new NoopLockingProvider();\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);\n\n\t\t$this->registerService(ILockManager::class, function (Server $c): LockManager {\n\t\t\treturn new LockManager();\n\t\t});\n\n\t\t$this->registerAlias(ILockdownManager::class, 'LockdownManager');\n\t\t$this->registerService(SetupManager::class, function ($c) {\n\t\t\t// create the setupmanager through the mount manager to resolve the cyclic dependency\n\t\t\treturn $c->get(\\OC\\Files\\Mount\\Manager::class)->getSetupManager();\n\t\t});\n\t\t$this->registerAlias(IMountManager::class, \\OC\\Files\\Mount\\Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('MountManager', IMountManager::class);\n\n\t\t$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {\n\t\t\treturn new \\OC\\Files\\Type\\Detection(\n\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t\\OC::$configDir,\n\t\t\t\t\\OC::$SERVERROOT . '/resources/config/'\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);\n\n\t\t$this->registerAlias(IMimeTypeLoader::class, Loader::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);\n\t\t$this->registerService(BundleFetcher::class, function () {\n\t\t\treturn new BundleFetcher($this->getL10N('lib'));\n\t\t});\n\t\t$this->registerAlias(\\OCP\\Notification\\IManager::class, Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('NotificationManager', \\OCP\\Notification\\IManager::class);\n\n\t\t$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {\n\t\t\t$manager = new CapabilitiesManager($c->get(LoggerInterface::class));\n\t\t\t$manager->registerCapability(function () use ($c) {\n\t\t\t\treturn new \\OC\\OCS\\CoreCapabilities($c->get(\\OCP\\IConfig::class));\n\t\t\t});\n\t\t\t$manager->registerCapability(function () use ($c) {\n\t\t\t\treturn $c->get(\\OC\\Security\\Bruteforce\\Capabilities::class);\n\t\t\t});\n\t\t\treturn $manager;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);\n\n\t\t$this->registerService(ICommentsManager::class, function (Server $c) {\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);\n\t\t\t/** @var \\OCP\\Comments\\ICommentsManagerFactory $factory */\n\t\t\t$factory = new $factoryClass($this);\n\t\t\t$manager = $factory->getManager();\n\n\t\t\t$manager->registerDisplayNameResolver('user', function ($id) use ($c) {\n\t\t\t\t$manager = $c->get(IUserManager::class);\n\t\t\t\t$userDisplayName = $manager->getDisplayName($id);\n\t\t\t\tif ($userDisplayName === null) {\n\t\t\t\t\t$l = $c->get(IFactory::class)->get('core');\n\t\t\t\t\treturn $l->t('Unknown account');\n\t\t\t\t}\n\t\t\t\treturn $userDisplayName;\n\t\t\t});\n\n\t\t\treturn $manager;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);\n\n\t\t$this->registerAlias(\\OC_Defaults::class, 'ThemingDefaults');\n\t\t$this->registerService('ThemingDefaults', function (Server $c) {\n\t\t\ttry {\n\t\t\t\t$classExists = class_exists('OCA\\Theming\\ThemingDefaults');\n\t\t\t} catch (\\OCP\\AutoloadNotAllowedException $e) {\n\t\t\t\t// App disabled or in maintenance mode\n\t\t\t\t$classExists = false;\n\t\t\t}\n\n\t\t\tif ($classExists && $c->get(\\OCP\\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {\n\t\t\t\t$imageManager = new ImageManager(\n\t\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t\t$c->getAppDataDir('theming'),\n\t\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t\t$this->get(ICacheFactory::class),\n\t\t\t\t\t$this->get(LoggerInterface::class),\n\t\t\t\t\t$this->get(ITempManager::class)\n\t\t\t\t);\n\t\t\t\treturn new ThemingDefaults(\n\t\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t\t$c->getL10N('theming'),\n\t\t\t\t\t$c->get(IUserSession::class),\n\t\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t\tnew Util($c->get(\\OCP\\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),\n\t\t\t\t\t$imageManager,\n\t\t\t\t\t$c->get(IAppManager::class),\n\t\t\t\t\t$c->get(INavigationManager::class)\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn new \\OC_Defaults();\n\t\t});\n\t\t$this->registerService(JSCombiner::class, function (Server $c) {\n\t\t\treturn new JSCombiner(\n\t\t\t\t$c->getAppDataDir('js'),\n\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t$this->get(ICacheFactory::class),\n\t\t\t\t$c->get(SystemConfig::class),\n\t\t\t\t$c->get(LoggerInterface::class)\n\t\t\t);\n\t\t});\n\t\t$this->registerAlias(\\OCP\\EventDispatcher\\IEventDispatcher::class, \\OC\\EventDispatcher\\EventDispatcher::class);\n\n\t\t$this->registerService('CryptoWrapper', function (ContainerInterface $c) {\n\t\t\t// FIXME: Instantiated here due to cyclic dependency\n\t\t\t$request = new Request(\n\t\t\t\t[\n\t\t\t\t\t'get' => $_GET,\n\t\t\t\t\t'post' => $_POST,\n\t\t\t\t\t'files' => $_FILES,\n\t\t\t\t\t'server' => $_SERVER,\n\t\t\t\t\t'env' => $_ENV,\n\t\t\t\t\t'cookies' => $_COOKIE,\n\t\t\t\t\t'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))\n\t\t\t\t\t\t? $_SERVER['REQUEST_METHOD']\n\t\t\t\t\t\t: null,\n\t\t\t\t],\n\t\t\t\t$c->get(IRequestId::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class)\n\t\t\t);\n\n\t\t\treturn new CryptoWrapper(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(ICrypto::class),\n\t\t\t\t$c->get(ISecureRandom::class),\n\t\t\t\t$request\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);\n\t\t$this->registerService(SessionStorage::class, function (ContainerInterface $c) {\n\t\t\treturn new SessionStorage($c->get(ISession::class));\n\t\t});\n\t\t$this->registerAlias(\\OCP\\Security\\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);\n\n\t\t$this->registerService(IProviderFactory::class, function (ContainerInterface $c) {\n\t\t\t$config = $c->get(\\OCP\\IConfig::class);\n\t\t\t$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);\n\t\t\t/** @var \\OCP\\Share\\IProviderFactory $factory */\n\t\t\treturn new $factoryClass($this);\n\t\t});\n\n\t\t$this->registerAlias(\\OCP\\Share\\IManager::class, \\OC\\Share20\\Manager::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('ShareManager', \\OCP\\Share\\IManager::class);\n\n\t\t$this->registerService(\\OCP\\Collaboration\\Collaborators\\ISearch::class, function (Server $c) {\n\t\t\t$instance = new Collaboration\\Collaborators\\Search($c);\n\n\t\t\t// register default plugins\n\t\t\t$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);\n\t\t\t$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);\n\t\t\t$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);\n\t\t\t$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);\n\t\t\t$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);\n\n\t\t\treturn $instance;\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('CollaboratorSearch', \\OCP\\Collaboration\\Collaborators\\ISearch::class);\n\t\t$this->registerAlias(\\OCP\\Collaboration\\Collaborators\\ISearchResult::class, \\OC\\Collaboration\\Collaborators\\SearchResult::class);\n\n\t\t$this->registerAlias(\\OCP\\Collaboration\\AutoComplete\\IManager::class, \\OC\\Collaboration\\AutoComplete\\Manager::class);\n\n\t\t$this->registerAlias(\\OCP\\Collaboration\\Resources\\IProviderManager::class, \\OC\\Collaboration\\Resources\\ProviderManager::class);\n\t\t$this->registerAlias(\\OCP\\Collaboration\\Resources\\IManager::class, \\OC\\Collaboration\\Resources\\Manager::class);\n\n\t\t$this->registerAlias(IReferenceManager::class, ReferenceManager::class);\n\t\t$this->registerAlias(ITeamManager::class, TeamManager::class);\n\n\t\t$this->registerDeprecatedAlias('SettingsManager', \\OC\\Settings\\Manager::class);\n\t\t$this->registerAlias(\\OCP\\Settings\\IManager::class, \\OC\\Settings\\Manager::class);\n\t\t$this->registerService(\\OC\\Files\\AppData\\Factory::class, function (ContainerInterface $c) {\n\t\t\treturn new \\OC\\Files\\AppData\\Factory(\n\t\t\t\t$c->get(IRootFolder::class),\n\t\t\t\t$c->get(SystemConfig::class)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService('LockdownManager', function (ContainerInterface $c) {\n\t\t\treturn new LockdownManager(function () use ($c) {\n\t\t\t\treturn $c->get(ISession::class);\n\t\t\t});\n\t\t});\n\n\t\t$this->registerService(\\OCP\\OCS\\IDiscoveryService::class, function (ContainerInterface $c) {\n\t\t\treturn new DiscoveryService(\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t$c->get(IClientService::class)\n\t\t\t);\n\t\t});\n\t\t$this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);\n\n\t\t$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {\n\t\t\treturn new CloudIdManager(\n\t\t\t\t$c->get(\\OCP\\Contacts\\IManager::class),\n\t\t\t\t$c->get(IURLGenerator::class),\n\t\t\t\t$c->get(IUserManager::class),\n\t\t\t\t$c->get(ICacheFactory::class),\n\t\t\t\t$c->get(IEventDispatcher::class),\n\t\t\t);\n\t\t});\n\n\t\t$this->registerAlias(\\OCP\\GlobalScale\\IConfig::class, \\OC\\GlobalScale\\Config::class);\n\n\t\t$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {\n\t\t\treturn new CloudFederationProviderManager(\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t$c->get(IAppManager::class),\n\t\t\t\t$c->get(IClientService::class),\n\t\t\t\t$c->get(ICloudIdManager::class),\n\t\t\t\t$c->get(IOCMDiscoveryService::class),\n\t\t\t\t$c->get(LoggerInterface::class)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService(ICloudFederationFactory::class, function (Server $c) {\n\t\t\treturn new CloudFederationFactory();\n\t\t});\n\n\t\t$this->registerAlias(\\OCP\\AppFramework\\Utility\\IControllerMethodReflector::class, \\OC\\AppFramework\\Utility\\ControllerMethodReflector::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('ControllerMethodReflector', \\OCP\\AppFramework\\Utility\\IControllerMethodReflector::class);\n\n\t\t$this->registerAlias(\\OCP\\AppFramework\\Utility\\ITimeFactory::class, \\OC\\AppFramework\\Utility\\TimeFactory::class);\n\t\t$this->registerAlias(\\Psr\\Clock\\ClockInterface::class, \\OCP\\AppFramework\\Utility\\ITimeFactory::class);\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('TimeFactory', \\OCP\\AppFramework\\Utility\\ITimeFactory::class);\n\n\t\t$this->registerService(Defaults::class, function (Server $c) {\n\t\t\treturn new Defaults(\n\t\t\t\t$c->get('ThemingDefaults')\n\t\t\t);\n\t\t});\n\t\t/** @deprecated 19.0.0 */\n\t\t$this->registerDeprecatedAlias('Defaults', \\OCP\\Defaults::class);\n\n\t\t$this->registerService(\\OCP\\ISession::class, function (ContainerInterface $c) {\n\t\t\treturn $c->get(\\OCP\\IUserSession::class)->getSession();\n\t\t}, false);\n\n\t\t$this->registerService(IShareHelper::class, function (ContainerInterface $c) {\n\t\t\treturn new ShareHelper(\n\t\t\t\t$c->get(\\OCP\\Share\\IManager::class)\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService(Installer::class, function (ContainerInterface $c) {\n\t\t\treturn new Installer(\n\t\t\t\t$c->get(AppFetcher::class),\n\t\t\t\t$c->get(IClientService::class),\n\t\t\t\t$c->get(ITempManager::class),\n\t\t\t\t$c->get(LoggerInterface::class),\n\t\t\t\t$c->get(\\OCP\\IConfig::class),\n\t\t\t\t\\OC::$CLI\n\t\t\t);\n\t\t});\n\n\t\t$this->registerService(IApiFactory::class, function (ContainerInterface $c) {\n\t\t\treturn new ApiFactory($c->get(IClientService::class));\n\t\t});\n\n\t\t$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {\n\t\t\t$memcacheFactory = $c->get(ICacheFactory::class);\n\t\t\treturn new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));\n\t\t});\n\n\t\t$this->registerAlias(IContactsStore::class, ContactsStore::class);\n\t\t$this->registerAlias(IAccountManager::class, AccountManager::class);\n\n\t\t$this->registerAlias(IStorageFactory::class, StorageFactory::class);\n\n\t\t$this->registerAlias(\\OCP\\Dashboard\\IManager::class, \\OC\\Dashboard\\Manager::class);\n\n\t\t$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);\n\t\t$this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);\n\n\t\t$this->registerAlias(ISubAdmin::class, SubAdmin::class);\n\n\t\t$this->registerAlias(IInitialStateService::class, InitialStateService::class);\n\n\t\t$this->registerAlias(\\OCP\\IEmojiHelper::class, \\OC\\EmojiHelper::class);\n\n\t\t$this->registerAlias(\\OCP\\UserStatus\\IManager::class, \\OC\\UserStatus\\Manager::class);\n\n\t\t$this->registerAlias(IBroker::class, Broker::class);\n\n\t\t$this->registerAlias(\\OCP\\Files\\AppData\\IAppDataFactory::class, \\OC\\Files\\AppData\\Factory::class);\n\n\t\t$this->registerAlias(IBinaryFinder::class, BinaryFinder::class);\n\n\t\t$this->registerAlias(\\OCP\\Share\\IPublicShareTemplateFactory::class, \\OC\\Share20\\PublicShareTemplateFactory::class);\n\n\t\t$this->registerAlias(ITranslationManager::class, TranslationManager::class);\n\n\t\t$this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);\n\n\t\t$this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);\n\n\t\t$this->registerAlias(\\OCP\\TextProcessing\\IManager::class, \\OC\\TextProcessing\\Manager::class);\n\n\t\t$this->registerAlias(\\OCP\\TextToImage\\IManager::class, \\OC\\TextToImage\\Manager::class);\n\n\t\t$this->registerAlias(ILimiter::class, Limiter::class);\n\n\t\t$this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);\n\n\t\t$this->registerAlias(IOCMProvider::class, OCMProvider::class);\n\n\t\t$this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);\n\n\t\t$this->registerAlias(IProfileManager::class, ProfileManager::class);\n\n\t\t$this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);\n\n\t\t$this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);\n\n\t\t$this->connectDispatcher();\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n if (isset($data['type'])) {\n $this->setType($data['type']);\n }\n if (isset($data['variantState'])) {\n $this->setVariantState($data['variantState']);\n }\n if (isset($data['value'])) {\n $this->setValue($data['value']);\n }\n if (isset($data['unitOfMeasure'])) {\n $this->setUnitOfMeasure($data['unitOfMeasure']);\n }\n if (isset($data['precisionEstimate'])) {\n if (is_array($data['precisionEstimate'])) {\n foreach ($data['precisionEstimate'] as $d) {\n $this->addPrecisionEstimate($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"precisionEstimate\" must be array of objects or null, ' . gettype($data['precisionEstimate']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function postcalendar_getDate($format = 'Ymd')\n{\n list($Date, $jumpday, $jumpmonth, $jumpyear, $jumpdate) =\n pnVarCleanFromInput('Date', 'jumpday', 'jumpmonth', 'jumpyear', 'jumpdate');\n if (!isset($Date)) {\n // if we still don't have a date then calculate it\n // check the jump menu, might be a 'jumpdate' input field or m/d/y select lists\n if ($jumpdate) {\n $jumpyear = substr($jumpdate, 0, 4);\n $jumpmonth = substr($jumpdate, 5, 2);\n $jumpday = substr($jumpdate, 8, 2);\n } else {\n if (!empty($_SESSION['lastcaldate'])) {\n $time = strtotime($_SESSION['lastcaldate']);\n } else {\n $time = time();\n }\n\n if (!isset($jumpday)) {\n $jumpday = date('d', $time);\n }\n\n if (!isset($jumpmonth)) {\n $jumpmonth = date('m', $time);\n }\n\n if (!isset($jumpyear)) {\n $jumpyear = date('Y', $time);\n }\n }\n\n // create the correct date string\n $Date = (int) \"$jumpyear$jumpmonth$jumpday\";\n }\n\n $y = substr($Date, 0, 4);\n $m = substr($Date, 4, 2);\n $d = substr($Date, 6, 2);\n OpenEMR\\Common\\Session\\SessionUtil::setSession('lastcaldate', \"$y-$m-$d\"); // remember the last chosen date\n return date($format, mktime(0, 0, 0, $m, $d, $y));\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function calculate($trendType = self::TREND_BEST_FIT, $yValues, $xValues = array(), $const = true)\n {\n // Calculate number of points in each dataset\n $nY = count($yValues);\n $nX = count($xValues);\n\n // Define X Values if necessary\n if ($nX == 0) {\n $xValues = range(1, $nY);\n $nX = $nY;\n } elseif ($nY != $nX) {\n // Ensure both arrays of points are the same size\n trigger_error(\"trend(): Number of elements in coordinate arrays do not match.\", E_USER_ERROR);\n }\n\n $key = md5($trendType.$const.serialize($yValues).serialize($xValues));\n // Determine which trend method has been requested\n switch ($trendType) {\n // Instantiate and return the class for the requested trend method\n case self::TREND_LINEAR:\n case self::TREND_LOGARITHMIC:\n case self::TREND_EXPONENTIAL:\n case self::TREND_POWER:\n if (!isset(self::$trendCache[$key])) {\n $className = 'PHPExcel_'.$trendType.'_Best_Fit';\n self::$trendCache[$key] = new $className($yValues, $xValues, $const);\n }\n return self::$trendCache[$key];\n case self::TREND_POLYNOMIAL_2:\n case self::TREND_POLYNOMIAL_3:\n case self::TREND_POLYNOMIAL_4:\n case self::TREND_POLYNOMIAL_5:\n case self::TREND_POLYNOMIAL_6:\n if (!isset(self::$trendCache[$key])) {\n $order = substr($trendType, -1);\n self::$trendCache[$key] = new PHPExcel_Polynomial_Best_Fit($order, $yValues, $xValues, $const);\n }\n return self::$trendCache[$key];\n case self::TREND_BEST_FIT:\n case self::TREND_BEST_FIT_NO_POLY:\n // If the request is to determine the best fit regression, then we test each trend line in turn\n // Start by generating an instance of each available trend method\n foreach (self::$trendTypes as $trendMethod) {\n $className = 'PHPExcel_'.$trendMethod.'BestFit';\n $bestFit[$trendMethod] = new $className($yValues, $xValues, $const);\n $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit();\n }\n if ($trendType != self::TREND_BEST_FIT_NO_POLY) {\n foreach (self::$trendTypePolynomialOrders as $trendMethod) {\n $order = substr($trendMethod, -1);\n $bestFit[$trendMethod] = new PHPExcel_Polynomial_Best_Fit($order, $yValues, $xValues, $const);\n if ($bestFit[$trendMethod]->getError()) {\n unset($bestFit[$trendMethod]);\n } else {\n $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit();\n }\n }\n }\n // Determine which of our trend lines is the best fit, and then we return the instance of that trend class\n arsort($bestFitValue);\n $bestFitType = key($bestFitValue);\n return $bestFit[$bestFitType];\n default:\n return false;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "protected function updateQuestions(): void\n {\n $questions = $this->input['_questions'] ?? [];\n\n // Keep track of questions found\n $found_questions = [];\n\n // Parse each submitted question\n foreach ($questions as $question_data) {\n $question = new Question();\n\n // Read uuids\n $uuid = $question_data['uuid'] ?? '';\n if (empty($uuid)) {\n throw new RuntimeException(\n \"UUID is missing: \" . json_encode($question_data)\n );\n }\n $section_uuid = $question_data['forms_sections_uuid'] ?? '';\n if (empty($section_uuid)) {\n throw new RuntimeException(\n \"Parent section UUID is missing: \" . json_encode($question_data)\n );\n }\n\n // Get parent id\n $section = Section::getByUuid($section_uuid);\n if ($section === null) {\n throw new RuntimeException(\"Parent section not found: $section_uuid\");\n }\n $question_data['forms_sections_id'] = $section->getID();\n\n $question = Question::getByUuid($uuid);\n if ($question === null) {\n // Add new question\n $question = new Question();\n $id = $question->add($question_data);\n\n if (!$id) {\n throw new RuntimeException(\"Failed to add question\");\n }\n } else {\n // Update existing question\n $question_data['id'] = $question->getID();\n\n $success = $question->update($question_data);\n if (!$success) {\n throw new RuntimeException(\"Failed to update question\");\n }\n $id = $question->getID();\n }\n\n // Keep track of its id\n $found_questions[] = $id;\n }\n\n // Deletion will be handled in a separate method\n $this->input['_found_questions'] = $found_questions;\n\n // Special input has been handled, it can be deleted\n unset($this->input['_questions']);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getController($id_shop = null)\n {\n if (defined('_PS_ADMIN_DIR_')) {\n $_GET['controllerUri'] = Tools::getvalue('controller');\n }\n if ($this->controller) {\n $_GET['controller'] = $this->controller;\n return $this->controller;\n }\n\n if (isset(Context::getContext()->shop) && $id_shop === null) {\n $id_shop = (int)Context::getContext()->shop->id;\n }\n\n $controller = Tools::getValue('controller');\n\n if (isset($controller) && is_string($controller) && preg_match('/^([0-9a-z_-]+)\\?(.*)=(.*)$/Ui', $controller, $m)) {\n $controller = $m[1];\n if (isset($_GET['controller'])) {\n $_GET[$m[2]] = $m[3];\n } elseif (isset($_POST['controller'])) {\n $_POST[$m[2]] = $m[3];\n }\n }\n\n if (!Validate::isControllerName($controller)) {\n $controller = false;\n }\n\n // Use routes ? (for url rewriting)\n if ($this->use_routes && !$controller && !defined('_PS_ADMIN_DIR_')) {\n if (!$this->request_uri) {\n return strtolower($this->controller_not_found);\n }\n $controller = $this->controller_not_found;\n $test_request_uri = preg_replace('/(=http:\\/\\/)/', '=', $this->request_uri);\n\n // If the request_uri matches a static file, then there is no need to check the routes, we keep \"controller_not_found\" (a static file should not go through the dispatcher)\n if (!preg_match('/\\.(gif|jpe?g|png|css|js|ico)$/i', parse_url($test_request_uri, PHP_URL_PATH))) {\n // Add empty route as last route to prevent this greedy regexp to match request uri before right time\n if ($this->empty_route) {\n $this->addRoute($this->empty_route['routeID'], $this->empty_route['rule'], $this->empty_route['controller'], Context::getContext()->language->id, array(), array(), $id_shop);\n }\n\n list($uri) = explode('?', $this->request_uri);\n\n if (isset($this->routes[$id_shop][Context::getContext()->language->id])) {\n foreach ($this->routes[$id_shop][Context::getContext()->language->id] as $route) {\n if (preg_match($route['regexp'], $uri, $m)) {\n // Route found ! Now fill $_GET with parameters of uri\n foreach ($m as $k => $v) {\n if (!is_numeric($k)) {\n $_GET[$k] = $v;\n }\n }\n\n $controller = $route['controller'] ? $route['controller'] : $_GET['controller'];\n if (!empty($route['params'])) {\n foreach ($route['params'] as $k => $v) {\n $_GET[$k] = $v;\n }\n }\n\n // A patch for module friendly urls\n if (preg_match('#module-([a-z0-9_-]+)-([a-z0-9_]+)$#i', $controller, $m)) {\n $_GET['module'] = $m[1];\n $_GET['fc'] = 'module';\n $controller = $m[2];\n }\n\n if (isset($_GET['fc']) && $_GET['fc'] == 'module') {\n $this->front_controller = self::FC_MODULE;\n }\n break;\n }\n }\n }\n }\n\n if ($controller == 'index' || preg_match('/^\\/index.php(?:\\?.*)?$/', $this->request_uri)) {\n $controller = $this->useDefaultController();\n }\n }\n\n $this->controller = str_replace('-', '', $controller);\n $_GET['controller'] = $this->controller;\n return $this->controller;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function parseOpenEMRRecord($dataRecord = array(), $encode = false)\n {\n $medRequestResource = new FHIRMedicationRequest();\n\n $meta = new FHIRMeta();\n $meta->setVersionId('1');\n if (!empty($dataRecord['date_modified'])) {\n $meta->setLastUpdated(UtilsService::getLocalDateAsUTC($dataRecord['date_modified']));\n } else {\n $meta->setLastUpdated(UtilsService::getDateFormattedAsUTC());\n }\n $medRequestResource->setMeta($meta);\n\n $id = new FHIRId();\n $id->setValue($dataRecord['uuid']);\n $medRequestResource->setId($id);\n\n // status required\n $validStatii = [self::MEDICATION_REQUEST_STATUS_STOPPED,\n self::MEDICATION_REQUEST_STATUS_ACTIVE, self::MEDICATION_REQUEST_STATUS_COMPLETED];\n if (\n !empty($dataRecord['status'])\n && array_search($dataRecord['status'], $validStatii) !== false\n ) {\n $medRequestResource->setStatus($dataRecord['status']);\n } else {\n $medRequestResource->setStatus(self::MEDICATION_REQUEST_STATUS_UNKNOWN);\n }\n\n // intent required\n if (isset($dataRecord['intent'])) {\n $medRequestResource->setIntent($dataRecord['intent']);\n } else {\n // if we are missing the intent for whatever reason we should convey the code that does the least harm\n // which is that this is a plan but does not have authorization\n $medRequestResource->setIntent(self::MEDICATION_REQUEST_INTENT_PLAN);\n }\n\n // category must support\n if (isset($dataRecord['category'])) {\n $medRequestResource->addCategory(UtilsService::createCodeableConcept(\n [\n $dataRecord['category'] =>\n ['code' => $dataRecord['category'], 'description' => xlt($dataRecord['category_title'])\n ,'system' => FhirCodeSystemConstants::HL7_MEDICATION_REQUEST_CATEGORY]\n ]\n ));\n } else {\n // if no category has been sent then the default is home usage\n $medRequestResource->addCategory(UtilsService::createCodeableConcept(\n [\n self::MEDICATION_REQUEST_CATEGORY_COMMUNITY => [\n 'code' => self::MEDICATION_REQUEST_CATEGORY_COMMUNITY,\n 'description' => xlt(self::MEDICATION_REQUEST_CATEGORY_COMMUNITY_TITLE),\n 'system' => FhirCodeSystemConstants::HL7_MEDICATION_REQUEST_CATEGORY\n ]\n ],\n ));\n }\n\n // reported must support\n // we will treat everything as a primary source as OpenEMR has no way of differentiating right now primary versus secondary.\n $medRequestResource->setReportedBoolean(self::MEDICATION_REQUEST_REPORTED_PRIMARY_SOURCE);\n\n // medication[x] required\n /**\n * US Core Requirements\n * The MedicationRequest resources can represent a medication using either a code, or reference a Medication resource.\n * When referencing a Medication resource, the resource may be contained or an external resource.\n * The server systems are not required to support both a code and a reference, but SHALL support at least one of these methods.\n * If an external reference to Medication is used, the server SHALL support the _include parameter for searching this element.\n * The client application SHALL support all methods.\n *\n * NOTE: for our requirements we support ONLY the medicationCodeableConcept requirement ie code option and NOT the\n * embedded medication.\n */\n if (!empty($dataRecord['drugcode'])) {\n// $rxnormCoding = new FHIRCoding();\n $rxnormCode = UtilsService::createCodeableConcept($dataRecord['drugcode'], FhirCodeSystemConstants::RXNORM);\n// $rxnormCoding->addCoding($rxNormConcept);\n// $rxnormCode = new FHIRCodeableConcept();\n// $rxnormCoding->setSystem(FhirCodeSystemConstants::RXNORM);\n// foreach ($dataRecord['drugcode'] as $code => $codeValues) {\n//\n// }\n $medRequestResource->setMedicationCodeableConcept($rxnormCode);\n } else {\n $textOnlyCode = new FHIRCodeableConcept();\n $textOnlyCode->setText($dataRecord['drug']);\n $medRequestResource->setMedicationCodeableConcept($textOnlyCode);\n }\n\n // subject required\n if (!empty($dataRecord['puuid'])) {\n $medRequestResource->setSubject(UtilsService::createRelativeReference('Patient', $dataRecord['puuid']));\n } else {\n $medRequestResource->setSubject(UtilsService::createDataMissingExtension());\n }\n\n // encounter must support\n if (!empty($dataRecord['euuid'])) {\n $medRequestResource->setEncounter(UtilsService::createRelativeReference(\"Encounter\", $dataRecord['euuid']));\n }\n\n // authoredOn must support\n if (!empty($dataRecord['date_added'])) {\n $authored_on = new FHIRDateTime();\n $authored_on->setValue(UtilsService::getLocalDateAsUTC($dataRecord['date_added']));\n $medRequestResource->setAuthoredOn($authored_on);\n }\n\n // requester required\n if (!empty($dataRecord['pruuid'])) {\n $medRequestResource->setRequester(UtilsService::createRelativeReference('Practitioner', $dataRecord['pruuid']));\n } else {\n // if we have no practitioner we need to default it to the organization\n $fhirOrgService = new FhirOrganizationService();\n $medRequestResource->setRequester($fhirOrgService->getPrimaryBusinessEntityReference());\n }\n\n // dosageInstructions must support\n // we ignore unit,interval,and route for now as WENO does not populate it and NewCrop does not either inside OpenEMR\n // instead we will populate the dosageInstructions if we have it in order to meet ONC certification\n // TODO: @adunsulag if we actually support specific dosage instruction fields like period, interval, etc that\n // can be used to report in FHIR, populate the dosage instructions here.\n\n if (!empty($dataRecord['drug_dosage_instructions'])) {\n $dosage = new FHIRDosage();\n // TODO: @adunsulag if inferno fixes their testsuite change to use the object. The inferno test suite fails\n // to recognize resourceType even though Dosage is a BackboneElement subtype, so this is one of the few times\n // we will use an array dataset instead of the actual class\n $dosageArray = [];\n if (!empty($dataRecord['route'])) {\n $this->populateRouteOptions($dataRecord, $dosage);\n if (!empty($dosage->getRoute())) {\n $dosageArray['route'] = $dosage->getRoute()->jsonSerialize();\n }\n }\n\n if (!empty($dataRecord['drug_dosage_instructions'])) {\n// $dosage->setText($dataRecord['drug_dosage_instructions']);\n $dosageArray['text'] = $dataRecord['drug_dosage_instructions'];\n }\n\n\n $medRequestResource->addDosageInstruction($dosageArray);\n }\n\n if (!empty($dataRecord['note'])) {\n $note = new FHIRAnnotation();\n $note->setText($dataRecord['note']);\n }\n\n if ($encode) {\n return json_encode($medRequestResource);\n } else {\n return $medRequestResource;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function initContent()\n {\n if (!Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) {\n // You can uncomment these lines if you want to force https even from localhost and automatically redirect\n // header('HTTP/1.1 301 Moved Permanently');\n // header('Location: '.Tools::getShopDomainSsl(true).$_SERVER['REQUEST_URI']);\n // exit();\n $clientIsMaintenanceOrLocal = in_array(Tools::getRemoteAddr(), array_merge(array('127.0.0.1'), explode(',', Configuration::get('PS_MAINTENANCE_IP'))));\n // If ssl is enabled, https protocol is required. Exception for maintenance and local (127.0.0.1) IP\n if ($clientIsMaintenanceOrLocal) {\n $warningSslMessage = Tools::displayError('SSL is activated. However, your IP is allowed to enter unsecure mode for maintenance or local IP issues.');\n } else {\n $url = 'https://'.Tools::safeOutput(Tools::getServerName()).Tools::safeOutput($_SERVER['REQUEST_URI']);\n $warningSslMessage = sprintf(\n Translate::ppTags(\n Tools::displayError('SSL is activated. Please connect using the following link to [1]log into secure mode (https://)[/1]', false),\n array('<a href=\"%s\">')\n ),\n $url\n );\n }\n $this->context->smarty->assign('warningSslMessage', $warningSslMessage);\n }\n\n if (file_exists(_PS_ADMIN_DIR_.'/../install')) {\n $this->context->smarty->assign('wrong_install_name', true);\n }\n\n if (basename(_PS_ADMIN_DIR_) == 'admin' && file_exists(_PS_ADMIN_DIR_.'/../admin/')) {\n $rand = 'admin'.sprintf('%03d', rand(0, 999)).Tools::strtolower(Tools::passwdGen(6)).'/';\n if (@rename(_PS_ADMIN_DIR_.'/../admin/', _PS_ADMIN_DIR_.'/../'.$rand)) {\n Tools::redirectAdmin('../'.$rand);\n } else {\n $this->context->smarty->assign(array(\n 'wrong_folder_name' => true\n ));\n }\n } else {\n $rand = basename(_PS_ADMIN_DIR_).'/';\n }\n\n $this->context->smarty->assign(array(\n 'randomNb' => $rand,\n 'adminUrl' => Tools::getCurrentUrlProtocolPrefix().Tools::getShopDomain().__PS_BASE_URI__.$rand\n ));\n\n // Redirect to admin panel\n if (Tools::isSubmit('redirect') && Validate::isControllerName(Tools::getValue('redirect'))) {\n $this->context->smarty->assign('redirect', Tools::getValue('redirect'));\n } else {\n $tab = new Tab((int)$this->context->employee->default_tab);\n $this->context->smarty->assign('redirect', $this->context->link->getAdminLink($tab->class_name));\n }\n\n if ($nb_errors = count($this->errors)) {\n $this->context->smarty->assign(array(\n 'errors' => $this->errors,\n 'nbErrors' => $nb_errors,\n 'shop_name' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME')),\n 'disableDefaultErrorOutPut' => true,\n ));\n }\n\n if ($email = Tools::getValue('email')) {\n $this->context->smarty->assign('email', $email);\n }\n if ($password = Tools::getValue('password')) {\n $this->context->smarty->assign('password', $password);\n }\n\n $this->setMedia();\n $this->initHeader();\n parent::initContent();\n $this->initFooter();\n\n //force to disable modals\n $this->context->smarty->assign('modals', null);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function action_index()\n {\n $contextName = $this->request->get('context');\n $editModeEnabled = (boolean) $this->request->get('edit');\n\n $reader = new PHPFileReader($this->vulnConfigDir);\n\n $contextNames = $reader->getOwnContextNames();\n $originalContextNames = $reader->getReferenceContextNames();\n\n $allContextNames = $reader->getAllContextNames();\n\n $restorableContext = $contextName && in_array($contextName, $contextNames) && in_array($contextName, $originalContextNames);\n\n if ($contextName && !in_array($contextName, $allContextNames)) {\n throw new NotFoundException(\"The config '$contextName' does not exist.\");\n }\n\n $paramsStr = http_build_query(array_diff_key($this->request->get(), ['admin/vulnerability' => '']));\n $actionUrl = '/admin/vulnerability' . ($paramsStr ? '?'.$paramsStr : '');\n $templatesHtml = '';\n $permissionError = '';\n /** @var PhpEngine $templating */\n $templating = $this->pixie->container['templating'];\n\n\n if ($contextName) {\n if (!$this->isConfigDirWritable) {\n $permissionError = \"The config directory is not writable and you cannot save the configs. To be able \"\n . \"to modify configs please modify the permissions to the config directory: \" . realpath($this->vulnConfigDir);\n }\n\n $configName = $this->vulnConfigDir . '/' . $contextName.'.php';\n if (file_exists($configName) && !is_writable($configName)) {\n $sampleConfigName = $this->vulnConfigDir . '/../vuln.sample/' . $contextName.'.php';\n if (!(file_exists($sampleConfigName) && is_writable($sampleConfigName))) {\n $permissionError = \"The config file is not writable and you cannot save the config. To be able \"\n . \"to save config please modify the permissions to the config file: \" . realpath($configName);\n $this->isConfigDirWritable = false;\n }\n }\n\n if ($this->request->method == Request::METHOD_POST) {\n if (!$this->isConfigDirWritable) {\n throw new HttpException(\"Config directory is not writable: \" . $this->vulnConfigDir);\n }\n\n $form = $this->buildContextForm(new Context($contextName), $actionUrl, $editModeEnabled);\n $post = $this->request->post();\n\n try {\n $form->submit($post['context_form']);\n\n } catch (\\Exception $e) {\n $form->addError(new FormError($e->getMessage()));\n }\n\n if ($form->isValid()) {\n $context = $form->getData();\n $context = $context['context'];\n /** @var Context $context */\n $context->setStorageRole(Context::STORAGE_ROLE_ROOT);\n\n $writer = new PHPFileWriter($this->pixie, $this->vulnConfigDir);\n $writer->write($context);\n\n $this->pixie->session->flash('message', 'The config \"' . $context->getName() . '\" has been saved.');\n\n $this->redirect($actionUrl);\n return null;\n }\n\n } else {\n $context = $reader->read($contextName);\n\n $form = $this->buildContextForm($context, $actionUrl, $editModeEnabled);\n }\n\n $formView = $form->createView();\n $formHtml = $templating->render('context_form', ['form' => $formView]);\n $templatesHtml = $this->renderTemplates();\n\n } else {\n $formHtml = '';\n }\n $this->view->restorableContext = $restorableContext;\n $this->view->contextNames = $allContextNames;\n $this->view->contextName = $contextName;\n $this->view->editModeEnabled = $editModeEnabled;\n $this->view->templating = $templating;\n $this->view->form = $formHtml;\n $this->view->subview = 'vulnerability/index';\n $this->view->pageHeader = \"Vulnerability Injection Configuration\";\n $this->view->pageTitle = $this->view->pageHeader . ($contextName ? ' - ' . $contextName : '');\n $this->view->headCSS = '<link href=\"/js/jqueryui-sortable/jquery-ui.css\" rel=\"stylesheet\" />';\n $this->view->headScripts = '<script type=\"text/javascript\" charset=\"utf-8\" src=\"/js/can.custom.min.js\"></script>';\n $this->view->headScripts .= '<script type=\"text/javascript\" charset=\"utf-8\" src=\"/js/jqueryui-sortable/jquery-ui.min.js\"></script>';\n $this->view->headScripts .= \"<script type='application/javascript' src='/js/vuln-config.js'></script>\";\n $this->view->permissionError = $permissionError ?: '';\n $this->view->configDir = realpath($this->vulnConfigDir);\n $this->view->templatesHtml = $templatesHtml;\n $this->view->flash = $this->pixie->session->flash('message') ?: '';\n\n return $this->view->render();\n }", "smellKey": "S3776", "smellId": null, "repo": "Tmlrb2xhb3M_hackazon", "language": "php"} {"function": "public function regenQuestionAndSeed($oldquestion, $oldseeds, $oldquestions=array()) {\n $newq = $oldquestion; //by default, reuse same question\n if (!in_array($oldquestion, $this->assessData['itemorder'])) {\n //the question must be in a grouping. Find the group.\n foreach ($this->assessData['itemorder'] as $qid) {\n if (is_array($qid) && in_array($oldquestion, $qid['qids'])) {\n if ($qid['type'] == 'pool' && $qid['n'] < count($qid['qids'])) {\n // only do redraw if not picking n from n\n $group = $qid['qids'];\n $grouptype = $qid['type'];\n }\n break;\n }\n }\n //if it's a pool, pick an unused question from the pool\n if (isset($group) && $grouptype == 'pool') {\n $unused = array_diff($group, $oldquestions);\n if (count($unused) == 0) {\n //if all of them have been used, just make sure we don't pick\n //the current one again\n $unused = array_diff($group, array($oldquestion));\n }\n $newq = $unused[array_rand($unused,1)];\n }\n }\n if (!isset($this->questionData[$newq])) {\n $this->loadQuestionSettings([$newq], true);\n }\n\n if ($this->assessData['shuffle']&2) {\n //all questions same seed - don't regen\n $newseed = $oldseeds[0];\n } else {\n if (!empty($this->questionData[$newq]['fixedseeds'])) {\n //using fixed seed list. find any unused seeds\n if (count($this->questionData[$newq]['fixedseeds']) == 1) {\n //only one seed so use it\n $newseed = $this->questionData[$newq]['fixedseeds'][0];\n } else if ($this->assessData['shuffle']&4) {\n //all stu same seed using fixed seed list, pick next in list\n $n = count($this->questionData[$newq]['fixedseeds']);\n $newseed = $this->questionData[$newq]['fixedseeds'][(count($oldseeds)) % $n];\n } else {\n $unused = array_diff($this->questionData[$newq]['fixedseeds'], $oldseeds);\n if (count($unused) == 0) {\n //if all used, just make sure it's not the same as the last\n $unused = array_diff($this->questionData[$newq]['fixedseeds'], array($oldseeds[count($oldseeds)-1]));\n }\n $newseed = $unused[array_rand($unused, 1)];\n }\n } else if ($this->assessData['shuffle']&4) {\n // all stu same seed - increment seed by 1\n $newseed = max($oldseeds) + 1;\n } else {\n //regular seed pick\n $looplimit = 0;\n do {\n $newseed = rand(1,9999);\n $looplimit++;\n } while ($looplimit < 10 && in_array($newseed, $oldseeds));\n }\n }\n // make sure they're ints\n $newq = intval($newq);\n $newseed = intval($newseed);\n return array($newq, $newseed);\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function showForContact(Contact $contact)\n {\n\n $instID = (int)$contact->fields['id'];\n\n if (!$contact->can($instID, READ)) {\n return;\n }\n\n $canedit = $contact->can($instID, UPDATE);\n $rand = mt_rand();\n\n $iterator = self::getListForItem($contact);\n $number = count($iterator);\n\n $suppliers = [];\n $used = [];\n foreach ($iterator as $data) {\n $suppliers[$data['linkid']] = $data;\n $used[$data['id']] = $data['id'];\n }\n\n if ($canedit) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='contactsupplier_form$rand' id='contactsupplier_form$rand'\n method='post' action='\";\n echo Toolbox::getItemTypeFormURL(__CLASS__) . \"'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_1'><th colspan='2'>\" . __s('Add a supplier') . \"</tr>\";\n\n echo \"<tr class='tab_bg_2'><td class='center'>\";\n echo \"<input type='hidden' name='contacts_id' value='$instID'>\";\n Supplier::dropdown(['used' => $used,\n 'entity' => $contact->fields[\"entities_id\"],\n 'entity_sons' => $contact->fields[\"is_recursive\"]\n ]);\n echo \"</td><td class='center'>\";\n echo \"<input type='submit' name='add' value=\\\"\" . _sx('button', 'Add') . \"\\\" class='btn btn-primary'>\";\n echo \"</td></tr>\";\n\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }\n\n echo \"<div class='spaced'>\";\n if ($canedit && $number) {\n Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);\n $massiveactionparams = ['num_displayed' => min($_SESSION['glpilist_limit'], $number),\n 'container' => 'mass' . __CLASS__ . $rand\n ];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';\n if ($canedit && $number) {\n $header_top .= \"<th width='10'>\" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);\n $header_top .= \"</th>\";\n $header_bottom .= \"<th width='10'>\" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);\n $header_bottom .= \"</th>\";\n }\n $header_end .= \"<th>\" . htmlescape(Supplier::getTypeName(1)) . \"</th>\";\n $header_end .= \"<th>\" . htmlescape(Entity::getTypeName(1)) . \"</th>\";\n $header_end .= \"<th>\" . htmlescape(SupplierType::getTypeName(1)) . \"</th>\";\n $header_end .= \"<th>\" . htmlescape(Phone::getTypeName(1)) . \"</th>\";\n $header_end .= \"<th>\" . __s('Fax') . \"</th>\";\n $header_end .= \"<th>\" . __s('Website') . \"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin . $header_top . $header_end;\n\n if ($number > 0) {\n Session::initNavigateListItems(\n 'Supplier',\n //TRANS : %1$s is the itemtype name,\n // %2$s is the name of the item (used for headings of a list)\n sprintf(\n __('%1$s = %2$s'),\n Contact::getTypeName(1),\n $contact->getName()\n )\n );\n\n foreach ($suppliers as $data) {\n $assocID = $data[\"linkid\"];\n Session::addToNavigateListItems('Supplier', $data[\"id\"]);\n $website = $data[\"website\"];\n\n if (!empty($website)) {\n $website = $data[\"website\"];\n\n if (!preg_match(\"?https*://?\", $website)) {\n $website = \"http://\" . $website;\n }\n $website = \"<a target=_blank href='$website'>\" . $data[\"website\"] . \"</a>\";\n }\n\n echo \"<tr class='tab_bg_1\" . ($data[\"is_deleted\"] ? \"_2\" : \"\") . \"'>\";\n if ($canedit) {\n echo \"<td>\" . Html::getMassiveActionCheckBox(__CLASS__, $assocID) . \"</td>\";\n }\n echo \"<td class='center'>\";\n echo \"<a href='\" . Supplier::getFormURLWithID($data[\"id\"]) . \"'>\" .\n htmlescape(Dropdown::getDropdownName(\"glpi_suppliers\", $data[\"id\"])) . \"</a></td>\";\n echo \"<td class='center'>\" . htmlescape(Dropdown::getDropdownName(\"glpi_entities\", $data[\"entity\"]));\n echo \"</td>\";\n echo \"<td class='center'>\" . htmlescape(Dropdown::getDropdownName(\"glpi_suppliertypes\", $data[\"suppliertypes_id\"]));\n echo \"</td>\";\n echo \"<td class='center' width='80'>\" . htmlescape($data[\"phonenumber\"]) . \"</td>\";\n echo \"<td class='center' width='80'>\" . htmlescape($data[\"fax\"]) . \"</td>\";\n echo \"<td class='center'>\" . $website . \"</td>\";\n echo \"</tr>\";\n }\n echo $header_begin . $header_bottom . $header_end;\n }\n\n echo \"</table>\";\n if ($canedit && $number) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n echo \"</div>\";\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "static function OutputAsExcel(array $objects, Phreezer $phreezer, $reportTitle = \"Data Export\", $fileName = \"export.xls\", $creator = \"Phreeze Library\")\n {\n require_once(\"PEAR/PHPExcel.php\");\n\n // create the workbook and worksheet\n $workbook = new PHPExcel();\n\n // set workbook properties\n $workbook->getProperties()->setCreator($creator)->setTitle($fileName);\n\n $workbook->setActiveSheetIndex(0);\n $worksheet = $workbook->getActiveSheet();\n\n $current_column = \"A\";\n $current_row = 1;\n\n $worksheet->setCellValue($current_column . $current_row, $reportTitle);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setBold(true)->setSize(16);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setName('Arial');\n\n // default to no columns\n $fields = array ();\n $columns = array ();\n $is_numeric = array ();\n $fieldmap_exists = false;\n\n $current_row = 3;\n\n // print the headers\n // while we're looping, also parse the fields so we don't have to do\n // it repeatedly when looping through data\n if (isset($objects [0])) {\n try {\n // see if there is a fieldmap for this object\n $fields = $phreezer->GetFieldMaps(get_class($objects [0]));\n $fieldmap_exists = true;\n\n // these are the columns we'll use for enumeration from here on\n $columns = array_keys($fields);\n } catch (Exception $ex) {\n // no fieldmaps exist, so use the reflection class instead\n $reflect = new ReflectionClass($objects [0]);\n $publicAttributes = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);\n $staticAttributes = $reflect->getStaticProperties();\n // only include non-static public properties\n $props = array_diff($publicAttributes, $staticAttributes);\n\n foreach ($props as $prop) {\n $column = $prop->getName();\n $columns [] = $column;\n }\n }\n\n foreach ($columns as $column) {\n // save this so we don't check it every time when looping through data\n $is_numeric [$column] = $fieldmap_exists ? $fields [$column]->IsNumeric() : false;\n\n $worksheet->setCellValue($current_column . $current_row, $column);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setBold(true)->setSize(11);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setName('Arial');\n\n $current_column++;\n }\n }\n\n $current_row = 4;\n\n // loop through all of the data\n foreach ($objects as $object) {\n $current_column = \"A\";\n foreach ($columns as $column) {\n if ($fieldmap_exists == false || $is_numeric [$column] == true) {\n $worksheet->setCellValue($current_column . $current_row, $object->$column);\n } else {\n $worksheet->setCellValue($current_column . $current_row, $object->$column);\n }\n\n $current_column++;\n }\n\n $current_row++;\n }\n\n // lastly write to the footer to sum the numeric columns\n $current_column = \"A\";\n foreach ($columns as $column) {\n if ($is_numeric [$column]) {\n $columnLetter = ExportUtility::GetColumnLetter($current_column);\n $formula = \"=SUM(\" . $columnLetter . \"3:\" . $columnLetter . ($current_row - 1) . \")\";\n\n // notice the @ sign in front because this will fire a deprecated warning due to use of \"split\"\n @$worksheet->setCellValue($current_column . $current_row, $formula);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setBold(true);\n $worksheet->getStyle($current_column . $current_row)->getFont()->setName('Arial');\n }\n\n $current_column++;\n }\n\n $workbook->getDefaultStyle()->getFont()->setName('Arial')->setSize(11);\n\n $workbook->setActiveSheetIndex(0);\n $writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel5');\n\n // set headers to excel:\n header('Content-type: application/vnd.ms-excel');\n header('Content-Disposition: attachment; filename=\"' . $fileName . '\"');\n header('Cache-Control: max-age=0');\n $writer->save('php://output');\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function renewReferences(mixed $data, bool $initial = true, string $key = null): mixed\n {\n if ($data instanceof __PHP_Incomplete_Class) {\n Logger::err(sprintf('Renew References: Cannot read data (%s) of incomplete class.', is_null($key) ? 'not available' : $key));\n\n return null;\n }\n\n if (is_array($data)) {\n foreach ($data as $dataKey => &$value) {\n $value = self::renewReferences($value, false, (string)$dataKey);\n }\n\n return $data;\n }\n if (is_object($data)) {\n if ($data instanceof UnitEnum) {\n return $data;\n }\n\n if ($data instanceof ElementInterface && !$initial) {\n return self::getElementById(self::getElementType($data), $data->getId());\n }\n\n // if this is the initial element set the correct path and key\n if ($data instanceof ElementInterface && !DataObject\\AbstractObject::doNotRestoreKeyAndPath()) {\n $originalElement = self::getElementById(self::getElementType($data), $data->getId());\n\n if ($originalElement) {\n //do not override filename for Assets https://github.com/pimcore/pimcore/issues/8316\n // if ($data instanceof Asset) {\n // /** @var Asset $originalElement */\n // $data->setFilename($originalElement->getFilename());\n // } else\n if ($data instanceof Document) {\n /** @var Document $originalElement */\n $data->setKey($originalElement->getKey());\n } elseif ($data instanceof DataObject\\AbstractObject) {\n /** @var AbstractObject $originalElement */\n $data->setKey($originalElement->getKey());\n }\n\n $data->setPath($originalElement->getRealPath());\n }\n }\n\n if ($data instanceof Model\\AbstractModel) {\n $properties = $data->getObjectVars();\n foreach ($properties as $name => $value) {\n //do not renew object reference of ObjectAwareFieldInterface - as object might point to a\n //specific version of the object and must not be reloaded with DB version of object\n if ($data instanceof ObjectAwareFieldInterface && $name === 'object') {\n continue;\n }\n\n $data->setObjectVar($name, self::renewReferences($value, false, $name), true);\n }\n } else {\n $properties = method_exists($data, 'getObjectVars') ? $data->getObjectVars() : get_object_vars($data);\n foreach ($properties as $name => $value) {\n if (method_exists($data, 'setObjectVar')) {\n $data->setObjectVar($name, self::renewReferences($value, false, $name), true);\n } else {\n $data->$name = self::renewReferences($value, false, $name);\n }\n }\n }\n\n return $data;\n }\n\n return $data;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '')\n {\n if (empty($field)) {\n return $this;\n } elseif ($field instanceof Expression) {\n $this->options['field'][] = $field;\n return $this;\n }\n\n if (is_string($field)) {\n if (preg_match('/[\\<\\'\\\"\\(]/', $field)) {\n return $this->fieldRaw($field);\n }\n\n $field = array_map('trim', explode(',', $field));\n }\n\n if (true === $field) {\n // \u83b7\u53d6\u5168\u90e8\u5b57\u6bb5\n $fields = $this->getTableFields($tableName);\n $field = $fields ?: ['*'];\n } elseif ($except) {\n // \u5b57\u6bb5\u6392\u9664\n $fields = $this->getTableFields($tableName);\n $field = $fields ? array_diff($fields, $field) : $field;\n }\n\n if ($tableName) {\n // \u6dfb\u52a0\u7edf\u4e00\u7684\u524d\u7f00\n $prefix = $prefix ?: $tableName;\n foreach ($field as $key => &$val) {\n if (is_numeric($key) && $alias) {\n $field[$prefix . '.' . $val] = $alias . $val;\n unset($field[$key]);\n } elseif (is_numeric($key)) {\n $val = $prefix . '.' . $val;\n }\n }\n }\n\n if (isset($this->options['field'])) {\n $field = array_merge((array) $this->options['field'], $field);\n }\n\n $this->options['field'] = array_unique($field);\n\n return $this;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "Function Connect($domain=\"\")\n\t{\n\t\tif(strcmp($this->state,\"Disconnected\"))\n\t\t{\n\t\t\t$this->error=\"connection is already established\";\n\t\t\treturn(0);\n\t\t}\n\t\t$this->disconnected_error=0;\n\t\t$this->error=$error=\"\";\n\t\t$this->esmtp_host=\"\";\n\t\t$this->esmtp_extensions=array();\n\t\t$hosts=array();\n\t\tif($this->direct_delivery)\n\t\t{\n\t\t\tif(strlen($domain)==0)\n\t\t\t\treturn(1);\n\t\t\t$hosts=$weights=$mxhosts=array();\n\t\t\t$getmxrr=$this->getmxrr;\n\t\t\tif(function_exists($getmxrr)\n\t\t\t&& $getmxrr($domain,$hosts,$weights))\n\t\t\t{\n\t\t\t\tfor($host=0;$host<count($hosts);$host++)\n\t\t\t\t\t$mxhosts[$weights[$host]]=$hosts[$host];\n\t\t\t\tKSort($mxhosts);\n\t\t\t\tfor(Reset($mxhosts),$host=0;$host<count($mxhosts);Next($mxhosts),$host++)\n\t\t\t\t\t$hosts[$host]=$mxhosts[Key($mxhosts)];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(strcmp(@gethostbyname($domain),$domain)!=0)\n\t\t\t\t\t$hosts[]=$domain;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(strlen($this->host_name))\n\t\t\t\t$hosts[]=$this->host_name;\n\t\t\tif(strlen($this->pop3_auth_host))\n\t\t\t{\n\t\t\t\t$user=$this->user;\n\t\t\t\tif(strlen($user)==0)\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"it was not specified the POP3 authentication user\";\n\t\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t\t$password=$this->password;\n\t\t\t\tif(strlen($password)==0)\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"it was not specified the POP3 authentication password\";\n\t\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t\t$domain=$this->pop3_auth_host;\n\t\t\t\t$this->error=$this->ConnectToHost($domain, $this->pop3_auth_port, \"Resolving POP3 authentication host \\\"\".$domain.\"\\\"...\");\n\t\t\t\tif(strlen($this->error))\n\t\t\t\t\treturn(0);\n\t\t\t\tif(strlen($response=$this->GetLine())==0)\n\t\t\t\t\treturn(0);\n\t\t\t\tif(strcmp($this->Tokenize($response,\" \"),\"+OK\"))\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"POP3 authentication server greeting was not found\";\n\t\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t\tif(!$this->PutLine(\"USER \".$this->user)\n\t\t\t\t|| strlen($response=$this->GetLine())==0)\n\t\t\t\t\treturn(0);\n\t\t\t\tif(strcmp($this->Tokenize($response,\" \"),\"+OK\"))\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"POP3 authentication user was not accepted: \".$this->Tokenize(\"\\r\\n\");\n\t\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t\tif(!$this->PutLine(\"PASS \".$password)\n\t\t\t\t|| strlen($response=$this->GetLine())==0)\n\t\t\t\t\treturn(0);\n\t\t\t\tif(strcmp($this->Tokenize($response,\" \"),\"+OK\"))\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"POP3 authentication password was not accepted: \".$this->Tokenize(\"\\r\\n\");\n\t\t\t\t\treturn(0);\n\t\t\t\t}\n\t\t\t\tfclose($this->connection);\n\t\t\t\t$this->connection=0;\n\t\t\t}\n\t\t}\n\t\tif(count($hosts)==0)\n\t\t{\n\t\t\t$this->error=\"could not determine the SMTP to connect\";\n\t\t\treturn(0);\n\t\t}\n\t\tfor($host=0, $error=\"not connected\";strlen($error) && $host<count($hosts);$host++)\n\t\t{\n\t\t\t$domain=$hosts[$host];\n\t\t\t$error=$this->ConnectToHost($domain, $this->host_port, \"Resolving SMTP server domain \\\"$domain\\\"...\");\n\t\t}\n\t\tif(strlen($error))\n\t\t{\n\t\t\t$this->error=$error;\n\t\t\treturn(0);\n\t\t}\n\t\t$timeout=($this->data_timeout ? $this->data_timeout : $this->timeout);\n\t\tif($timeout\n\t\t&& function_exists(\"socket_set_timeout\"))\n\t\t\tsocket_set_timeout($this->connection,$timeout,0);\n\t\tif($this->debug)\n\t\t\t$this->OutputDebug(\"Connected to SMTP server \\\"\".$domain.\"\\\".\");\n\t\tif(!strcmp($localhost=$this->localhost,\"\")\n\t\t&& !strcmp($localhost=getenv(\"SERVER_NAME\"),\"\")\n\t\t&& !strcmp($localhost=getenv(\"HOST\"),\"\"))\n\t\t\t$localhost=\"localhost\";\n\t\t$success=0;\n\t\tif($this->VerifyResultLines(\"220\",$responses)>0)\n\t\t{\n\t\t\t$fallback=1;\n\t\t\tif($this->esmtp\n\t\t\t|| strlen($this->user))\n\t\t\t{\n\t\t\t\tif($this->PutLine(\"EHLO $localhost\"))\n\t\t\t\t{\n\t\t\t\t\tif(($success_code=$this->VerifyResultLines(\"250\",$responses))>0)\n\t\t\t\t\t{\n\t\t\t\t\t\t$this->esmtp_host=$this->Tokenize($responses[0],\" \");\n\t\t\t\t\t\tfor($response=1;$response<count($responses);$response++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$extension=strtoupper($this->Tokenize($responses[$response],\" \"));\n\t\t\t\t\t\t\t$this->esmtp_extensions[$extension]=$this->Tokenize(\"\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$success=1;\n\t\t\t\t\t\t$fallback=0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif($success_code==0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$code=$this->Tokenize($this->error,\" -\");\n\t\t\t\t\t\t\tswitch($code)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase \"421\":\n\t\t\t\t\t\t\t\t\t$fallback=0;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t$fallback=0;\n\t\t\t}\n\t\t\tif($fallback)\n\t\t\t{\n\t\t\t\tif($this->PutLine(\"HELO $localhost\")\n\t\t\t\t&& $this->VerifyResultLines(\"250\",$responses)>0)\n\t\t\t\t\t$success=1;\n\t\t\t}\n\t\t\tif($success\n\t\t\t&& strlen($this->user)\n\t\t\t&& strlen($this->pop3_auth_host)==0)\n\t\t\t{\n\t\t\t\tif(!IsSet($this->esmtp_extensions[\"AUTH\"]))\n\t\t\t\t{\n\t\t\t\t\t$this->error=\"server does not require authentication\";\n\t\t\t\t\t$success=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(strlen($this->authentication_mechanism))\n\t\t\t\t\t\t$mechanisms=array($this->authentication_mechanism);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$mechanisms=array();\n\t\t\t\t\t\tfor($authentication=$this->Tokenize($this->esmtp_extensions[\"AUTH\"],\" \");strlen($authentication);$authentication=$this->Tokenize(\" \"))\n\t\t\t\t\t\t\t$mechanisms[]=$authentication;\n\t\t\t\t\t}\n\t\t\t\t\t$credentials=array(\n\t\t\t\t\t\t\"user\"=>$this->user,\n\t\t\t\t\t\t\"password\"=>$this->password\n\t\t\t\t\t);\n\t\t\t\t\tif(strlen($this->realm))\n\t\t\t\t\t\t$credentials[\"realm\"]=$this->realm;\n\t\t\t\t\tif(strlen($this->workstation))\n\t\t\t\t\t\t$credentials[\"workstation\"]=$this->workstation;\n\t\t\t\t\t$success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism);\n\t\t\t\t\tif(!$success\n\t\t\t\t\t&& !strcmp($mechanism,\"PLAIN\"))\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Author: Russell Robinson, 25 May 2003, http://www.tectite.com/\n\t\t\t\t\t\t * Purpose: Try various AUTH PLAIN authentication methods.\n\t\t\t\t\t\t */\n\t\t\t\t\t\t$mechanisms=array(\"PLAIN\");\n\t\t\t\t\t\t$credentials=array(\n\t\t\t\t\t\t\t\"user\"=>$this->user,\n\t\t\t\t\t\t\t\"password\"=>$this->password\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif(strlen($this->realm))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * According to: http://www.sendmail.org/~ca/email/authrealms.html#authpwcheck_method\n\t\t\t\t\t\t\t * some sendmails won't accept the realm, so try again without it\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t$success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(!$success)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * It was seen an EXIM configuration like this:\n\t\t\t\t\t\t\t * user^password^unused\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t$credentials[\"mode\"]=SASL_PLAIN_EXIM_DOCUMENTATION_MODE;\n\t\t\t\t\t\t\t$success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(!$success)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * ... though: http://exim.work.de/exim-html-3.20/doc/html/spec_36.html\n\t\t\t\t\t\t\t * specifies: ^user^password\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t$credentials[\"mode\"]=SASL_PLAIN_EXIM_MODE;\n\t\t\t\t\t\t\t$success=$this->SASLAuthenticate($mechanisms,$credentials,$authenticated,$mechanism);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif($success\n\t\t\t\t\t&& strlen($mechanism)==0)\n\t\t\t\t\t{\n\t\t\t\t\t\t$this->error=\"it is not supported any of the authentication mechanisms required by the server\";\n\t\t\t\t\t\t$success=0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif($success)\n\t\t{\n\t\t\t$this->state=\"Connected\";\n\t\t\t$this->connected_domain=$domain;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfclose($this->connection);\n\t\t\t$this->connection=0;\n\t\t}\n\t\treturn($success);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getUsers($values, &$results, &$limitexceeded)\n {\n $users = [];\n $ldap_users = self::getAllUsers($values, $results, $limitexceeded);\n\n $config_ldap = new AuthLDAP();\n $config_ldap->getFromDB($values['authldaps_id']);\n\n if (!is_array($ldap_users) || count($ldap_users) === 0) {\n return $users;\n }\n\n\n $sync_field = $config_ldap->isSyncFieldEnabled() ? $config_ldap->fields['sync_field'] : null;\n\n foreach ($ldap_users as $userinfos) {\n $user_to_add = [];\n $user = new User();\n\n $user_sync_field = $config_ldap->isSyncFieldEnabled() && isset($userinfos[$sync_field])\n ? self::getFieldValue($userinfos, $sync_field)\n : null;\n\n $user = $config_ldap->getLdapExistingUser(\n $userinfos['user'],\n $values['authldaps_id'],\n $user_sync_field\n );\n if (isset($_SESSION['ldap_import']) && !$_SESSION['ldap_import']['mode'] && $user) {\n continue;\n }\n $user_to_add['link'] = $userinfos[\"user\"];\n if (isset($userinfos['id']) && User::canView()) {\n $user_to_add['id'] = $userinfos['id'];\n $user_to_add['name'] = $user->fields['name'];\n $user_to_add['link'] = Toolbox::getItemTypeFormURL('User') . '?id=' . $userinfos['id'];\n }\n\n $user_to_add['stamp'] = $userinfos[\"timestamp\"] ?? '';\n $user_to_add['date_sync'] = $userinfos[\"date_sync\"] ?? '';\n\n $user_to_add['uid'] = $userinfos['user'];\n if ($config_ldap->isSyncFieldEnabled()) {\n if (isset($userinfos[$sync_field])) {\n $user_to_add['uid'] = self::getFieldValue($userinfos, $sync_field);\n }\n\n $field_for_sync = $config_ldap->getLdapIdentifierToUse();\n if (isset($userinfos[$field_for_sync])) {\n $user_to_add['sync_field'] = $userinfos[$field_for_sync];\n }\n }\n\n $users[] = $user_to_add;\n }\n\n return $users;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function action(): void\n {\n $platforms = Config::getParam('platforms');\n $selectedPlatform = Console::confirm('Choose Platform (\"' . APP_PLATFORM_CLIENT . '\", \"' . APP_PLATFORM_SERVER . '\", \"' . APP_PLATFORM_CONSOLE . '\" or \"*\" for all):');\n $selectedSDK = \\strtolower(Console::confirm('Choose SDK (\"*\" for all):'));\n $version = Console::confirm('Choose an Appwrite version');\n $git = (Console::confirm('Should we use git push? (yes/no)') == 'yes');\n $production = ($git) ? (Console::confirm('Type \"Appwrite\" to push code to production git repos') == 'Appwrite') : false;\n $message = ($git) ? Console::confirm('Please enter your commit message:') : '';\n\n if (!in_array($version, ['0.6.x', '0.7.x', '0.8.x', '0.9.x', '0.10.x', '0.11.x', '0.12.x', '0.13.x', '0.14.x', '0.15.x', '1.0.x', '1.1.x', '1.2.x', '1.3.x', '1.4.x', 'latest'])) {\n throw new Exception('Unknown version given');\n }\n\n foreach ($platforms as $key => $platform) {\n if ($selectedPlatform !== $key && $selectedPlatform !== '*') {\n continue;\n }\n\n foreach ($platform['sdks'] as $language) {\n if ($selectedSDK !== $language['key'] && $selectedSDK !== '*') {\n continue;\n }\n\n if (!$language['enabled']) {\n Console::warning($language['name'] . ' for ' . $platform['name'] . ' is disabled');\n continue;\n }\n\n Console::info('Fetching API Spec for ' . $language['name'] . ' for ' . $platform['name'] . ' (version: ' . $version . ')');\n\n $spec = file_get_contents(__DIR__ . '/../../../../app/config/specs/swagger2-' . $version . '-' . $language['family'] . '.json');\n\n $cover = 'https://appwrite.io/images/github.png';\n $result = \\realpath(__DIR__ . '/../../../../app') . '/sdks/' . $key . '-' . $language['key'];\n $resultExamples = \\realpath(__DIR__ . '/../../../..') . '/docs/examples/' . $version . '/' . $key . '-' . $language['key'];\n $target = \\realpath(__DIR__ . '/../../../../app') . '/sdks/git/' . $language['key'] . '/';\n $readme = \\realpath(__DIR__ . '/../../../../docs/sdks/' . $language['key'] . '/README.md');\n $readme = ($readme) ? \\file_get_contents($readme) : '';\n $gettingStarted = \\realpath(__DIR__ . '/../../../../docs/sdks/' . $language['key'] . '/GETTING_STARTED.md');\n $gettingStarted = ($gettingStarted) ? \\file_get_contents($gettingStarted) : '';\n $examples = \\realpath(__DIR__ . '/../../../../docs/sdks/' . $language['key'] . '/EXAMPLES.md');\n $examples = ($examples) ? \\file_get_contents($examples) : '';\n $changelog = \\realpath(__DIR__ . '/../../../../docs/sdks/' . $language['key'] . '/CHANGELOG.md');\n $changelog = ($changelog) ? \\file_get_contents($changelog) : '# Change Log';\n $warning = '**This SDK is compatible with Appwrite server version ' . $version . '. For older versions, please check [previous releases](' . $language['url'] . '/releases).**';\n $license = 'BSD-3-Clause';\n $licenseContent = 'Copyright (c) ' . date('Y') . ' Appwrite (https://appwrite.io) and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.';\n\n switch ($language['key']) {\n case 'web':\n $config = new Web();\n if ($platform['key'] === APP_PLATFORM_CONSOLE) {\n $config->setNPMPackage('@appwrite.io/console');\n $config->setBowerPackage('@appwrite.io/console');\n } else {\n $config->setNPMPackage('appwrite');\n $config->setBowerPackage('appwrite');\n }\n break;\n case 'cli':\n $config = new CLI();\n $config->setNPMPackage('appwrite-cli');\n $config->setExecutableName('appwrite');\n $config->setLogo(json_encode(\"\n _ _ _ ___ __ _____ \n /_\\ _ __ _ ____ ___ __(_) |_ ___ / __\\ / / \\_ \\\n //_\\\\\\| '_ \\| '_ \\ \\ /\\ / / '__| | __/ _ \\ / / / / / /\\/\n / _ \\ |_) | |_) \\ V V /| | | | || __/ / /___/ /___/\\/ /_ \n \\_/ \\_/ .__/| .__/ \\_/\\_/ |_| |_|\\__\\___| \\____/\\____/\\____/ \n |_| |_| \n\n\"));\n $config->setLogoUnescaped(\"\n _ _ _ ___ __ _____ \n /_\\ _ __ _ ____ ___ __(_) |_ ___ / __\\ / / \\_ \\\n //_\\\\\\| '_ \\| '_ \\ \\ /\\ / / '__| | __/ _ \\ / / / / / /\\/\n / _ \\ |_) | |_) \\ V V /| | | | || __/ / /___/ /___/\\/ /_ \n \\_/ \\_/ .__/| .__/ \\_/\\_/ |_| |_|\\__\\___| \\____/\\____/\\____/ \n |_| |_| \");\n break;\n case 'php':\n $config = new PHP();\n $config->setComposerVendor('appwrite');\n $config->setComposerPackage('appwrite');\n break;\n case 'nodejs':\n $config = new Node();\n $config->setNPMPackage('node-appwrite');\n $config->setBowerPackage('appwrite');\n $warning = $warning . \"\\n\\n > This is the Node.js SDK for integrating with Appwrite from your Node.js server-side code.\n If you're looking to integrate from the browser, you should check [appwrite/sdk-for-web](https://github.com/appwrite/sdk-for-web)\";\n break;\n case 'deno':\n $config = new Deno();\n break;\n case 'python':\n $config = new Python();\n $config->setPipPackage('appwrite');\n $license = 'BSD License'; // license edited due to classifiers in pypi\n break;\n case 'ruby':\n $config = new Ruby();\n $config->setGemPackage('appwrite');\n break;\n case 'flutter':\n $config = new Flutter();\n $config->setPackageName('appwrite');\n break;\n case 'flutter-dev':\n $config = new Flutter();\n $config->setPackageName('appwrite_dev');\n break;\n case 'dart':\n $config = new Dart();\n $config->setPackageName('dart_appwrite');\n $warning = $warning . \"\\n\\n > This is the Dart SDK for integrating with Appwrite from your Dart server-side code. If you're looking for the Flutter SDK you should check [appwrite/sdk-for-flutter](https://github.com/appwrite/sdk-for-flutter)\";\n break;\n case 'go':\n $config = new Go();\n break;\n case 'swift':\n $config = new Swift();\n $warning = $warning . \"\\n\\n > This is the Swift SDK for integrating with Appwrite from your Swift server-side code. If you're looking for the Apple SDK you should check [appwrite/sdk-for-apple](https://github.com/appwrite/sdk-for-apple)\";\n break;\n case 'apple':\n $config = new Apple();\n break;\n case 'dotnet':\n $cover = '';\n $config = new DotNet();\n break;\n case 'android':\n $config = new Android();\n break;\n case 'kotlin':\n $config = new Kotlin();\n $warning = $warning . \"\\n\\n > This is the Kotlin SDK for integrating with Appwrite from your Kotlin server-side code. If you're looking for the Android SDK you should check [appwrite/sdk-for-android](https://github.com/appwrite/sdk-for-android)\";\n break;\n case 'graphql':\n $config = new GraphQL();\n break;\n case 'rest':\n $config = new REST();\n break;\n default:\n throw new Exception('Language \"' . $language['key'] . '\" not supported');\n }\n\n Console::info(\"Generating {$language['name']} SDK...\");\n\n $sdk = new SDK($config, new Swagger2($spec));\n\n $sdk\n ->setName($language['name'])\n ->setNamespace('io appwrite')\n ->setDescription(\"Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the {$language['name']} SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)\")\n ->setShortDescription('Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API')\n ->setLicense($license)\n ->setLicenseContent($licenseContent)\n ->setVersion($language['version'])\n ->setPlatform($key)\n ->setGitURL($language['url'])\n ->setGitRepo($language['gitUrl'])\n ->setGitRepoName($language['gitRepoName'])\n ->setGitUserName($language['gitUserName'])\n ->setLogo($cover)\n ->setURL('https://appwrite.io')\n ->setShareText('Appwrite is a backend as a service for building web or mobile apps')\n ->setShareURL('http://appwrite.io')\n ->setShareTags('JS,javascript,reactjs,angular,ios,android,serverless')\n ->setShareVia('appwrite')\n ->setWarning($warning)\n ->setReadme($readme)\n ->setGettingStarted($gettingStarted)\n ->setChangelog($changelog)\n ->setExamples($examples)\n ->setTwitter(APP_SOCIAL_TWITTER_HANDLE)\n ->setDiscord(APP_SOCIAL_DISCORD_CHANNEL, APP_SOCIAL_DISCORD)\n ->setDefaultHeaders([\n 'X-Appwrite-Response-Format' => '1.4.0',\n ]);\n\n try {\n $sdk->generate($result);\n } catch (Exception $exception) {\n Console::error($exception->getMessage());\n } catch (Throwable $exception) {\n Console::error($exception->getMessage());\n }\n\n $gitUrl = $language['gitUrl'];\n $gitBranch = $language['gitBranch'];\n\n\n if (!$production) {\n $gitUrl = 'git@github.com:aw-tests/' . $language['gitRepoName'] . '.git';\n }\n\n if ($git && !empty($gitUrl)) {\n \\exec('rm -rf ' . $target . ' && \\\n mkdir -p ' . $target . ' && \\\n cd ' . $target . ' && \\\n git init --initial-branch=' . $gitBranch . ' && \\\n git remote add origin ' . $gitUrl . ' && \\\n git fetch origin ' . $gitBranch . ' && \\\n git pull origin ' . $gitBranch . ' && \\\n rm -rf ' . $target . '/* && \\\n cp -r ' . $result . '/* ' . $target . '/ && \\\n git add . && \\\n git commit -m \"' . $message . '\" && \\\n git push -u origin ' . $gitBranch . '\n ');\n\n Console::success(\"Pushed {$language['name']} SDK to {$gitUrl}\");\n\n \\exec('rm -rf ' . $target);\n Console::success(\"Remove temp directory '{$target}' for {$language['name']} SDK\");\n }\n\n $docDirectories = $language['docDirectories'] ?? [''];\n\n if ($version === 'latest') {\n continue;\n }\n\n foreach ($docDirectories as $languageTitle => $path) {\n $languagePath = strtolower($languageTitle !== 0 ? '/' . $languageTitle : '');\n \\exec(\n 'mkdir -p ' . $resultExamples . $languagePath . ' && \\\n cp -r ' . $result . '/docs/examples' . $languagePath . ' ' . $resultExamples\n );\n Console::success(\"Copied code examples for {$language['name']} SDK to: {$resultExamples}\");\n }\n }\n }\n\n Console::exit();\n }", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_appwrite", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['product'])) {\n $this->setProduct($data['product']);\n }\n if (isset($data['eye'])) {\n $this->setEye($data['eye']);\n }\n if (isset($data['sphere'])) {\n $this->setSphere($data['sphere']);\n }\n if (isset($data['cylinder'])) {\n $this->setCylinder($data['cylinder']);\n }\n if (isset($data['axis'])) {\n $this->setAxis($data['axis']);\n }\n if (isset($data['prism'])) {\n if (is_array($data['prism'])) {\n foreach ($data['prism'] as $d) {\n $this->addPrism($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"prism\" must be array of objects or null, ' . gettype($data['prism']) . ' seen.');\n }\n }\n if (isset($data['add'])) {\n $this->setAdd($data['add']);\n }\n if (isset($data['power'])) {\n $this->setPower($data['power']);\n }\n if (isset($data['backCurve'])) {\n $this->setBackCurve($data['backCurve']);\n }\n if (isset($data['diameter'])) {\n $this->setDiameter($data['diameter']);\n }\n if (isset($data['duration'])) {\n $this->setDuration($data['duration']);\n }\n if (isset($data['color'])) {\n $this->setColor($data['color']);\n }\n if (isset($data['brand'])) {\n $this->setBrand($data['brand']);\n }\n if (isset($data['note'])) {\n if (is_array($data['note'])) {\n foreach ($data['note'] as $d) {\n $this->addNote($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"note\" must be array of objects or null, ' . gettype($data['note']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function edih_277_csv_data($obj277)\n{\n //\n $ret_ar = array();\n //\n $seg_ar = $obj277->edih_segments();\n $env_ar = $obj277->edih_envelopes();\n $de = $obj277->edih_delimiters()['e'];\n $fn = $obj277->edih_filename();\n $tp = $obj277->edih_type();\n // 'HN' 277 'HR' 276 )\n $env_ar = $obj277->edih_envelopes();\n //\n if (!isset($env_ar['ST'])) {\n csv_edihist_log('edih_277_csv_data: envelope error');\n return $ret_ar;\n }\n\n if (!isset($env_ar['GS'])) {\n csv_edihist_log('edih_277_csv_data: envelope error');\n return $ret_ar;\n }\n\n //\n foreach ($env_ar['ISA'] as $icn => $isa) {\n //\n $ret_ar[$icn]['claim'] = array();\n $ret_ar[$icn]['file'] = array();\n //\n $rspdate = $isa['date'];\n foreach ($env_ar['GS'] as $gs) {\n if ($gs['icn'] == $icn) {\n $ret_ar[$icn]['type'] = csv_file_type($gs['type']);\n $rspdate = $gs['date'];\n break;\n }\n }\n\n //$ret_ar[$icn]['type'] = csv_file_type($ft);\n //\n $fdx = count($ret_ar[$icn]['file']);\n //['f277']['file'] = array('Date', 'FileName', 'Control', 'Accept', 'AccAmt', 'Reject', 'RejAmt');\n //'f276': $hdr = array('Date', 'FileName', 'Control', 'Claim_ct', 'x12Partner');\n $ret_ar[$icn]['file'][$fdx]['Date'] = $rspdate;\n $ret_ar[$icn]['file'][$fdx]['FileName'] = $fn;\n // could be GS06 for 276 if it were unique\n $ret_ar[$icn]['file'][$fdx]['Control'] = (string)$icn;\n if ($tp == 'HN') {\n $ret_ar[$icn]['file'][$fdx]['Accept'] = 0;\n $ret_ar[$icn]['file'][$fdx]['Reject'] = 0;\n $ret_ar[$icn]['file'][$fdx]['AccAmt'] = 0;\n $ret_ar[$icn]['file'][$fdx]['RejAmt'] = 0;\n } else {\n $ret_ar[$icn]['file'][$fdx]['Claim_ct'] = 0;\n $ret_ar[$icn]['file'][$fdx]['x12Partner'] = $isa['receiver'];\n }\n\n //\n $clmct = 0;\n //\n //['ST'][$stky]=>['start']['count']['stn']['gsn']['icn']['type']['trace']['acct']\n // ['ST'][$stky]['acct'][i]=>pid-enc\n //'f277': $hdr = array('PtName', 'SvcDate', 'CLM01', 'Status', 'BHT03', 'FileName', 'Payer', 'Trace');\n foreach ($env_ar['ST'] as $st) {\n //\n if ($st['icn'] != $icn) {\n continue;\n }\n\n //\n $stsegs = array_slice($seg_ar, $st['start'], $st['count']);\n $stacct = array_values(array_unique($st['bht03']));\n $clmct += count($stacct);\n $st_icn = $st['icn']; // same value as $obj277->envelopes['ISA']['icn']\n $stn = $st['stn'];\n //\n if ($tp == 'HR') {\n $ret_ar[$icn]['file'][$fdx]['Claim_ct'] = $clmct;\n }\n\n //\n //for($i=0; $i<$clmct; $i++) {\n for ($i = 0; $i < count($stacct); $i++) {\n //\n $asegs = $obj277->edih_x12_transaction($stacct[$i]);\n //\n foreach ($asegs as $trans) {\n //\n foreach ($trans as $seg) {\n //\n if (strncmp($seg, 'BHT' . $de, 4) === 0) {\n $cdx = count($ret_ar[$icn]['claim']);\n //\n $sar = explode($de, $seg);\n if ($sar[2] != '08') {\n csv_edihist_log('Claim Status BHT purpose code: ' . $sar[2] . ' in ST ' . $st['stn'] . ' in file ' . $fn);\n }\n\n $trns_tp = (isset($sar[6]) && $sar[6]) ? $sar[6] : '';\n if ($trns_tp == 'TH') {\n $bht_id = 'ack'; // 277CA\n } elseif ($trns_tp == 'DG') {\n $bht_id = 'rsp'; // 277\n } else {\n $bht_id = 'sub'; // 276\n }\n\n //\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = '';\n $ret_ar[$icn]['claim'][$cdx]['SvcDate'] = '';\n $ret_ar[$icn]['claim'][$cdx]['CLM01'] = '';\n //\n if ($tp == 'HN') {\n // 277\n $ret_ar[$icn]['claim'][$cdx]['Status'] = '';\n $ret_ar[$icn]['claim'][$cdx]['BHT03'] = $sar[3];\n } elseif ($tp == 'HR') {\n //276\n $ret_ar[$icn]['claim'][$cdx]['ClaimID'] = '';\n $ret_ar[$icn]['claim'][$cdx]['BHT03'] = sprintf(\"%s%04d\", $st_icn, $stn);\n }\n\n //\n\n $ret_ar[$icn]['claim'][$cdx]['FileName'] = $fn;\n //\n $ret_ar[$icn]['claim'][$cdx]['Payer'] = '';\n //$ret_ar[$icn]['claim'][$cdx]['Ins_ID'] = '';\n $ret_ar[$icn]['claim'][$cdx]['Trace'] = '';\n continue;\n }\n\n //\n if (strncmp($seg, 'HL' . $de, 3) === 0) {\n $sar = explode($de, $seg);\n $hl = (string)$sar[3];\n }\n\n //\n if ($hl == '20') {\n // information source\n if (strncmp($seg, 'NM1' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Payer'] = ($sar[1] == 'PR' || $sar[1] == 'AY') ? $sar[3] : '';\n continue;\n }\n }\n\n //\n if ($hl == '21') {\n // information source or receiver level rejection\n // -- user should view the transaction\n // -- don't include in csv data so Trace only refers to 276\n //if ( strncmp($seg, 'TRN'.$de, 4) === 0) {\n //$sar = explode($de, $seg);\n //$ret_ar[$icn]['claim'][$cdx]['Trace'] = $sar[2];\n //}\n if (strncmp($seg, 'STC' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Status'] = $sar[1];\n }\n\n if (strncmp($seg, 'QTY' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n if ($sar[1] == '90') {\n $ret_ar[$icn]['file'][$fdx]['Accept'] += $sar[2];\n }\n\n if ($sar[1] == 'AA') {\n $ret_ar[$icn]['file'][$fdx]['Reject'] += $sar[2];\n }\n }\n\n if (strncmp($seg, 'AMT' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n if ($sar[1] == 'YU') {\n $ret_ar[$icn]['file'][$fdx]['AccAmt'] += $sar[2];\n }\n\n if ($sar[1] == 'YY') {\n $ret_ar[$icn]['file'][$fdx]['RejAmt'] += $sar[2];\n }\n }\n\n continue;\n }\n\n //\n if ($hl == '19') {\n // provider level rejection\n // -- user should view the transaction\n // -- don't include in csv data so Trace only refers to 276\n //if ( strncmp($seg, 'TRN'.$de, 4) === 0) {\n //$sar = explode($de, $seg);\n //$ret_ar[$icn]['claim'][$cdx]['Trace'] = $sar[2];\n //}\n if (strncmp($seg, 'STC' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Status'] = $sar[1];\n }\n\n continue;\n }\n\n //\n if ($hl == '22' || $hl == '23') {\n // subscriber or dependent\n if (strncmp($seg, 'NM1' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n if ($sar[1] == 'IL' || $sar[1] == 'QC') {\n $midn = ( isset($sar[5]) && strlen($sar[5]) ) ? ', ' . $sar[5] : \"\";\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = $sar[3] . ', ' . $sar[4] . $midn;\n //if (isset($sar[8]) && $sar[8] == 'MI') {\n //$ret_ar[$icn]['claim'][$cdx]['Ins_ID'] = (isset($sar[9])) ? $sar[9] : '';\n //}\n }\n\n continue;\n }\n\n // in response to 276, this is the reference given in TRN02\n if (strncmp($seg, 'TRN' . $de . '2' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Trace'] = $sar[2];\n continue;\n }\n\n // REF*EJ* will give the payer assigned claim number\n // not used much in 277CA files\n if (strncmp($seg, 'REF' . $de . 'EJ' . $de, 7) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['CLM01'] = $sar[2];\n continue;\n }\n\n if (strncmp($seg, 'REF' . $de . '1K' . $de, 7) === 0) {\n // hopefully OpenEMR will include the claim number in 276\n if ($tp == 'HR') {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['ClaimID'] = $sar[2];\n }\n\n continue;\n }\n\n // REF*D9*(Claim number)~\n\n if (strncmp($seg, 'STC' . $de, 4) === 0) {\n // STC is only present in 277\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Status'] = $sar[1];\n continue;\n }\n\n continue;\n }\n\n if ($hl == 'PT') {\n // 277CA\n if (strncmp($seg, 'NM1' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n if ($sar[1] == 'IL' || $sar[1] == 'QC') {\n $midn = ( isset($sar[5]) && strlen($sar[5]) ) ? ', ' . $sar[5] : \"\";\n $ret_ar[$icn]['claim'][$cdx]['PtName'] = $sar[3] . ', ' . $sar[4] . $midn;\n //$ret_ar[$icn]['claim'][$cdx]['Ins_ID'] = (isset($sar[9])) ? $sar[9] : '';\n }\n\n continue;\n }\n\n if (strncmp($seg, 'TRN' . $de . '2' . $de, 6) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['CLM01'] = $sar[2];\n continue;\n }\n\n if (strncmp($seg, 'STC' . $de, 4) === 0) {\n $sar = explode($de, $seg);\n $ret_ar[$icn]['claim'][$cdx]['Status'] = $sar[1];\n continue;\n }\n\n //if ( strncmp($seg, 'REF'.$de.'1K'.$de, 7) === 0) {\n //$sar = explode($de, $seg);\n //$ret_ar[$icn]['claim'][$cdx]['ClaimID'] = $sar[2];\n //continue;\n //}\n if (strncmp($seg, 'DTP' . $de . '472' . $de, 8) === 0) {\n $sar = explode($de, $seg);\n // D8-CCYYMMDD RD8-CCYYMMDD-CCYYMMDD only take initial date\n $ret_ar[$icn]['claim'][$cdx]['SvcDate'] = substr($sar[3], 0, 8);\n continue;\n }\n }\n } // end foreach($trans as $seg)\n } // end foreach($asegs as $trans)\n } // end for($i=0; $i<$clmct; $i++)\n }// end foreach($obj277->envelopes['ST'] as $st)\n } // end foreach($env_ar['ISA'] as $icn => $isa)\n //\n return $ret_ar;\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getTimezoneNameLocationSpecific($value, $locale = '')\n {\n $result = '';\n if (!empty($value)) {\n if (is_string($value)) {\n $timezoneID = static::getTimezoneCanonicalID($value);\n $timezone = null;\n try {\n $timezone = new DateTimeZone($timezoneID);\n } catch (\\Exception $x) {\n return '';\n }\n $location = $timezone->getLocation();\n } elseif ($value instanceof DateTimeInterface || $value instanceof DateTime) {\n $timezone = $value->getTimezone();\n $location = self::getTimezoneLocationFromDatetime($value);\n } elseif ($value instanceof DateTimeZone) {\n $timezone = $value;\n $location = $timezone->getLocation();\n } else {\n throw new Exception\\BadArgumentType($value, 'string, DateTime, or DateTimeZone');\n }\n\n $name = '';\n if (isset($location['country_code']) && $location['country_code'] !== '??') {\n $data = Data::getGeneric('primaryZones');\n if (isset($data[$location['country_code']])\n || count(DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $location['country_code'])) === 1) {\n $name = Territory::getName($location['country_code'], $locale);\n }\n }\n\n if ($name === '' && substr($timezone->getName(), 0, 7) !== 'Etc/GMT') {\n $name = static::getTimezoneExemplarCity($value, false, $locale);\n }\n\n if ($name !== '') {\n $data = Data::get('timeZoneNames', $locale);\n $result = sprintf($data['regionFormat'], $name);\n }\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (isset($this->url)) {\n $json['url'] = $this->url;\n }\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->version)) {\n $json['version'] = $this->version;\n }\n if (isset($this->name)) {\n $json['name'] = $this->name;\n }\n if (isset($this->title)) {\n $json['title'] = $this->title;\n }\n if (0 < count($this->replaces)) {\n $json['replaces'] = [];\n foreach ($this->replaces as $replaces) {\n $json['replaces'][] = $replaces;\n }\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->experimental)) {\n $json['experimental'] = $this->experimental;\n }\n if (isset($this->date)) {\n $json['date'] = $this->date;\n }\n if (isset($this->publisher)) {\n $json['publisher'] = $this->publisher;\n }\n if (0 < count($this->contact)) {\n $json['contact'] = [];\n foreach ($this->contact as $contact) {\n $json['contact'][] = $contact;\n }\n }\n if (isset($this->description)) {\n $json['description'] = $this->description;\n }\n if (0 < count($this->useContext)) {\n $json['useContext'] = [];\n foreach ($this->useContext as $useContext) {\n $json['useContext'][] = $useContext;\n }\n }\n if (0 < count($this->jurisdiction)) {\n $json['jurisdiction'] = [];\n foreach ($this->jurisdiction as $jurisdiction) {\n $json['jurisdiction'][] = $jurisdiction;\n }\n }\n if (isset($this->purpose)) {\n $json['purpose'] = $this->purpose;\n }\n if (isset($this->copyright)) {\n $json['copyright'] = $this->copyright;\n }\n if (isset($this->base)) {\n $json['base'] = $this->base;\n }\n if (0 < count($this->parent)) {\n $json['parent'] = [];\n foreach ($this->parent as $parent) {\n $json['parent'][] = $parent;\n }\n }\n if (isset($this->eventCoding)) {\n $json['eventCoding'] = $this->eventCoding;\n }\n if (isset($this->eventUri)) {\n $json['eventUri'] = $this->eventUri;\n }\n if (isset($this->category)) {\n $json['category'] = $this->category;\n }\n if (0 < count($this->focus)) {\n $json['focus'] = [];\n foreach ($this->focus as $focus) {\n $json['focus'][] = $focus;\n }\n }\n if (isset($this->responseRequired)) {\n $json['responseRequired'] = $this->responseRequired;\n }\n if (0 < count($this->allowedResponse)) {\n $json['allowedResponse'] = [];\n foreach ($this->allowedResponse as $allowedResponse) {\n $json['allowedResponse'][] = $allowedResponse;\n }\n }\n if (0 < count($this->graph)) {\n $json['graph'] = [];\n foreach ($this->graph as $graph) {\n $json['graph'][] = $graph;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function setDataFromEditmode(mixed $data): static\n {\n if (!is_array($data)) {\n $data = [];\n }\n\n $path = $data['path'] ?? null;\n\n if (!empty($path)) {\n $target = null;\n\n if ($data['linktype'] == 'internal' && $data['internalType']) {\n $target = Model\\Element\\Service::getElementByPath($data['internalType'], $path);\n if ($target) {\n $data['internal'] = true;\n $data['internalId'] = $target->getId();\n }\n }\n\n if (!$target) {\n if ($target = Document::getByPath($path)) {\n $data['internal'] = true;\n $data['internalId'] = $target->getId();\n $data['internalType'] = 'document';\n } elseif ($target = Asset::getByPath($path)) {\n $data['internal'] = true;\n $data['internalId'] = $target->getId();\n $data['internalType'] = 'asset';\n } elseif ($target = Model\\DataObject\\Concrete::getByPath($path)) {\n $data['internal'] = true;\n $data['internalId'] = $target->getId();\n $data['internalType'] = 'object';\n } else {\n $data['internal'] = false;\n $data['internalId'] = null;\n $data['internalType'] = null;\n $data['linktype'] = 'direct';\n }\n\n if ($target) {\n $data['linktype'] = 'internal';\n }\n }\n }\n\n $this->data = $data;\n\n return $this;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function syncStudentWithSED($id, $modelEnrollment, $type)\n {\n\n $studentInfo = $this->getStudentInformation($id);\n $studentIdentification = $studentInfo['studentIdentification'];\n $studentIdentification->sedsp_sync = 0;\n\n $studentIdentification->tag_to_sed = 1;\n $studentIdentification->save();\n\n $studentToSedMapper = new StudentMapper();\n $student = (object) $studentToSedMapper->parseToSEDAlunoFicha(\n $studentIdentification,\n $studentInfo['modelStudentDocumentsAndAddress']\n );\n\n $studentDatasource = new StudentSEDDataSource();\n\n $dataSource = new StudentSEDDataSource();\n $outListStudent = $dataSource->getListStudents($this->createInListarAlunos($studentIdentification->name, $studentIdentification->filiation_1, $studentIdentification->filiation_2));\n\n $return[\"identification\"] = \"\";\n $return[\"enrollment\"] = \"\";\n if (method_exists($outListStudent, 'getCode') && $this->handleUnauthorizedError($outListStudent->getCode())) {\n return false;\n }\n\n if ($type == self::CREATE || ($type == self::UPDATE && $outListStudent->outListaAlunos === null)) {\n if ($outListStudent->outErro !== null || !is_null($outListStudent)) {\n $inConsult = $this->createInConsult($student);\n $statusAdd = $dataSource->addStudentToSed($inConsult);\n\n if (method_exists($statusAdd, 'getCode') && $this->handleUnauthorizedError($statusAdd->getCode())) {\n return false;\n }\n\n if ($statusAdd->outErro === null) {\n $studentFromSed = StudentIdentification::model()->findByPk($id);\n $studentFromSed->gov_id = $statusAdd->outAluno->outNumRA;\n $studentFromSed->sedsp_sync = 1;\n\n $studentFromSed->save();\n\n if ($modelEnrollment->id !== null) {\n $enrollmentResult = $this->processEnrollment($studentFromSed, $modelEnrollment);\n }\n }\n $result[\"identification\"] = $statusAdd;\n $result[\"enrollment\"] = $enrollmentResult;\n }\n } elseif ($type == self::UPDATE) {\n\n $govId = $studentIdentification->gov_id === null ? $outListStudent->outListaAlunos[0]->getOutNumRa() : $studentIdentification->gov_id;\n\n $response = $studentDatasource->exibirFichaAluno(new InAluno($govId, null, \"SP\"));\n if (method_exists($response, 'getCode') && $this->handleUnauthorizedError($response->getCode())) {\n return false;\n }\n\n $infoAluno = $response->outDadosPessoais->getOutNomeAluno();\n $filiation1 = $response->outDadosPessoais->getOutNomeMae();\n $filiation2 = $response->outDadosPessoais->getOutNomePai();\n\n $inListarAlunos = $this->createInListarAlunos($infoAluno, $filiation1, $filiation2);\n $dataSource = new StudentSEDDataSource();\n $outListStudent = $dataSource->getListStudents($inListarAlunos);\n\n if ($outListStudent->outErro === null) {\n\n $studentIdentification->gov_id = $govId;\n $studentIdentification->save();\n\n $dataSource = new StudentSEDDataSource();\n $student->InAluno->setInNumRA($govId);\n $inManutencao = $this->createInManutencao($student);\n $statusAdd = $dataSource->editStudent($inManutencao);\n\n if ($statusAdd->outErro === null) {\n $studentIdentification->sedsp_sync = 1;\n $studentIdentification->save();\n }\n }\n\n if ($modelEnrollment->id !== null) {\n $enrollmentResult = $this->processEnrollment($studentIdentification, $modelEnrollment);\n }\n\n $result[\"identification\"] = $statusAdd;\n $result[\"enrollment\"] = $enrollmentResult;\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function action_edit_profile()\n {\n if ($this->useRest) {\n throw new NotFoundException;\n }\n $user = $this->getUser();\n $fields = ['first_name', 'last_name', 'user_phone'];\n $errors = [];\n $this->view->success = false;\n\n if ($this->request->method == 'POST') {\n $this->checkCsrfToken('profile');\n\n $photo = $this->request->uploadedFile($this->request->postWrap('photo'), [\n 'extensions' => ['jpeg', 'jpg', 'gif', 'png'],\n 'types' => ['image']\n ]);\n\n if ($photo->isLoaded() && !$photo->isValid()) {\n $errors[] = 'Incorrect avatar file';\n }\n\n $data = $user->filterValues($this->request->postWrap(), $fields);\n\n if (!count($errors)) {\n UserPictureUploader::create($this->pixie, $user, $photo, $this->request->post('remove_photo'))\n ->execute();\n\n $user->values($data);\n $user->save();\n\n $this->pixie->session->flash('success', 'You have successfully updated your profile.');\n\n if ($this->request->post('_submit_save_and_exit')) {\n $this->redirect('/account#profile');\n\n } else {\n $this->redirect('/account/profile/edit');\n }\n\n return;\n\n } else {\n $data['photo'] = $user->photo;\n $this->response->add_header(\"HTTP/1.1 400 Bad Request\");\n }\n\n } else {\n $service = $this->pixie->vulnService;\n $data = $user->getFields(array_merge($fields, ['photo']));\n foreach ($data as $key => $value) {\n $data[$key] = $service->wrapValueByPath($value, 'default->account->edit_profile|'.$key.':body|0', true);\n }\n }\n\n foreach ($data as $key => $value) {\n $this->view->$key = $value;\n }\n\n if ($data['photo']) {\n $this->view->photoUrl = $data['photo'];\n }\n\n if (isset($data['photo']) && is_numeric($data['photo'])) {\n /** @var File $photoObj */\n $photoObj = $this->pixie->orm->get('file', $data['photo']);\n if ($photoObj->loaded() && $photoObj->user_id == $user->id()) {\n $this->view->photoUrl = preg_replace('#.*?([^\\\\\\\\/]{2}[\\\\\\\\/][^\\\\\\\\/]+)$#', '$1', $photoObj->path);\n }\n }\n\n $this->view->success = $this->pixie->session->flash('success') ?: '';\n $this->view->errorMessage = implode('<br>', $errors);\n $this->view->user = $user;\n $this->view->subview = 'account/edit_profile';\n }", "smellKey": "S3776", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "function ParsePost()\n\t{\n\t\t$this->Seek('post');\n\t\t$version = $this->ReadULong();\n\t\t$this->italicAngle = $this->ReadShort();\n\t\t$this->Skip(2); // Skip decimal part\n\t\t$this->underlinePosition = $this->ReadShort();\n\t\t$this->underlineThickness = $this->ReadShort();\n\t\t$this->isFixedPitch = ($this->ReadULong()!=0);\n\t\tif($version==0x20000)\n\t\t{\n\t\t\t// Extract glyph names\n\t\t\t$this->Skip(4*4); // min/max usage\n\t\t\t$this->Skip(2); // numberOfGlyphs\n\t\t\t$glyphNameIndex = array();\n\t\t\t$names = array();\n\t\t\t$numNames = 0;\n\t\t\tfor($i=0;$i<$this->numGlyphs;$i++)\n\t\t\t{\n\t\t\t\t$index = $this->ReadUShort();\n\t\t\t\t$glyphNameIndex[] = $index;\n\t\t\t\tif($index>=258 && $index-257>$numNames)\n\t\t\t\t\t$numNames = $index-257;\n\t\t\t}\n\t\t\tfor($i=0;$i<$numNames;$i++)\n\t\t\t{\n\t\t\t\t$len = ord($this->Read(1));\n\t\t\t\t$names[] = $this->Read($len);\n\t\t\t}\n\t\t\tforeach($glyphNameIndex as $i=>$index)\n\t\t\t{\n\t\t\t\tif($index>=258)\n\t\t\t\t\t$this->glyphs[$i]['name'] = $names[$index-258];\n\t\t\t\telse\n\t\t\t\t\t$this->glyphs[$i]['name'] = $index;\n\t\t\t}\n\t\t\t$this->glyphNames = true;\n\t\t}\n\t\telse\n\t\t\t$this->glyphNames = false;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "public static function main(string $controllerName, string $methodName, DIContainer $container, ?array $urlParams = null) {\n\t\t/** @var IProfiler $profiler */\n\t\t$profiler = $container->get(IProfiler::class);\n\t\t$eventLogger = $container->get(IEventLogger::class);\n\t\t// Disable profiler on the profiler UI\n\t\t$profiler->setEnabled($profiler->isEnabled() && !is_null($urlParams) && isset($urlParams['_route']) && !str_starts_with($urlParams['_route'], 'profiler.'));\n\t\tif ($profiler->isEnabled()) {\n\t\t\t\\OC::$server->get(IEventLogger::class)->activate();\n\t\t\t$profiler->add(new RoutingDataCollector($container['AppName'], $controllerName, $methodName));\n\t\t}\n\n\t\t$eventLogger->start('app:controller:params', 'Gather controller parameters');\n\n\t\tif (!is_null($urlParams)) {\n\t\t\t/** @var Request $request */\n\t\t\t$request = $container->get(IRequest::class);\n\t\t\t$request->setUrlParameters($urlParams);\n\t\t} elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) {\n\t\t\t/** @var Request $request */\n\t\t\t$request = $container->get(IRequest::class);\n\t\t\t$request->setUrlParameters($container['urlParams']);\n\t\t}\n\t\t$appName = $container['AppName'];\n\n\t\t$eventLogger->end('app:controller:params');\n\n\t\t$eventLogger->start('app:controller:load', 'Load app controller');\n\n\t\t// first try $controllerName then go for \\OCA\\AppName\\Controller\\$controllerName\n\t\ttry {\n\t\t\t$controller = $container->get($controllerName);\n\t\t} catch (QueryException $e) {\n\t\t\tif (str_contains($controllerName, '\\\\Controller\\\\')) {\n\t\t\t\t// This is from a global registered app route that is not enabled.\n\t\t\t\t[/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\\\', $controllerName, 3);\n\t\t\t\tthrow new HintException('App ' . strtolower($app) . ' is not enabled');\n\t\t\t}\n\n\t\t\tif ($appName === 'core') {\n\t\t\t\t$appNameSpace = 'OC\\\\Core';\n\t\t\t} else {\n\t\t\t\t$appNameSpace = self::buildAppNamespace($appName);\n\t\t\t}\n\t\t\t$controllerName = $appNameSpace . '\\\\Controller\\\\' . $controllerName;\n\t\t\t$controller = $container->query($controllerName);\n\t\t}\n\n\t\t$eventLogger->end('app:controller:load');\n\n\t\t$eventLogger->start('app:controller:dispatcher', 'Initialize dispatcher and pre-middleware');\n\n\t\t// initialize the dispatcher and run all the middleware before the controller\n\t\t/** @var Dispatcher $dispatcher */\n\t\t$dispatcher = $container['Dispatcher'];\n\n\t\t$eventLogger->end('app:controller:dispatcher');\n\n\t\t$eventLogger->start('app:controller:run', 'Run app controller');\n\n\t\t[\n\t\t\t$httpHeaders,\n\t\t\t$responseHeaders,\n\t\t\t$responseCookies,\n\t\t\t$output,\n\t\t\t$response\n\t\t] = $dispatcher->dispatch($controller, $methodName);\n\n\t\t$eventLogger->end('app:controller:run');\n\n\t\t$io = $container[IOutput::class];\n\n\t\tif ($profiler->isEnabled()) {\n\t\t\t$eventLogger->end('runtime');\n\t\t\t$profile = $profiler->collect($container->get(IRequest::class), $response);\n\t\t\t$profiler->saveProfile($profile);\n\t\t\t$io->setHeader('X-Debug-Token:' . $profile->getToken());\n\t\t\t$io->setHeader('Server-Timing: token;desc=\"' . $profile->getToken() . '\"');\n\t\t}\n\n\t\tif (!is_null($httpHeaders)) {\n\t\t\t$io->setHeader($httpHeaders);\n\t\t}\n\n\t\tforeach ($responseHeaders as $name => $value) {\n\t\t\t$io->setHeader($name . ': ' . $value);\n\t\t}\n\n\t\tforeach ($responseCookies as $name => $value) {\n\t\t\t$expireDate = null;\n\t\t\tif ($value['expireDate'] instanceof \\DateTime) {\n\t\t\t\t$expireDate = $value['expireDate']->getTimestamp();\n\t\t\t}\n\t\t\t$sameSite = $value['sameSite'] ?? 'Lax';\n\n\t\t\t$io->setCookie(\n\t\t\t\t$name,\n\t\t\t\t$value['value'],\n\t\t\t\t$expireDate,\n\t\t\t\t$container->getServer()->getWebRoot(),\n\t\t\t\tnull,\n\t\t\t\t$container->getServer()->getRequest()->getServerProtocol() === 'https',\n\t\t\t\ttrue,\n\t\t\t\t$sameSite\n\t\t\t);\n\t\t}\n\n\t\t/*\n\t\t * Status 204 does not have a body and no Content Length\n\t\t * Status 304 does not have a body and does not need a Content Length\n\t\t * https://tools.ietf.org/html/rfc7230#section-3.3\n\t\t * https://tools.ietf.org/html/rfc7230#section-3.3.2\n\t\t */\n\t\t$emptyResponse = false;\n\t\tif (preg_match('/^HTTP\\/\\d\\.\\d (\\d{3}) .*$/', $httpHeaders, $matches)) {\n\t\t\t$status = (int)$matches[1];\n\t\t\tif ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) {\n\t\t\t\t$emptyResponse = true;\n\t\t\t}\n\t\t}\n\n\t\tif (!$emptyResponse) {\n\t\t\tif ($response instanceof ICallbackResponse) {\n\t\t\t\t$response->callback($io);\n\t\t\t} elseif (!is_null($output)) {\n\t\t\t\t$io->setHeader('Content-Length: ' . strlen($output));\n\t\t\t\t$io->setOutput($output);\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function getTimelineItems(array $options = [])\n {\n\n $params = [\n 'with_documents' => true,\n 'with_logs' => true,\n 'with_validations' => true,\n 'sort_by_date_desc' => $_SESSION['glpitimeline_order'] == CommonITILObject::TIMELINE_ORDER_REVERSE,\n\n // params used by notifications process (as session cannot be used there)\n 'check_view_rights' => true,\n 'hide_private_items' => false,\n ];\n\n if (array_key_exists('bypass_rights', $options) && $options['bypass_rights']) {\n Toolbox::deprecated('Using `bypass_rights` parameter is deprecated.');\n $params['check_view_rights'] = false;\n }\n if (array_key_exists('expose_private', $options) && $options['expose_private']) {\n Toolbox::deprecated('Using `expose_private` parameter is deprecated.');\n $params['hide_private_items'] = false;\n }\n if (array_key_exists('is_self_service', $options) && $options['is_self_service']) {\n Toolbox::deprecated('Using `is_self_service` parameter is deprecated.');\n $params['hide_private_items'] = false;\n }\n\n if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }\n\n if ($this->isNewItem()) {\n return [];\n }\n\n if ($params['check_view_rights'] && !$this->canViewItem()) {\n return [];\n }\n\n $objType = static::getType();\n $foreignKey = static::getForeignKeyField();\n $timeline = [];\n\n $canupdate_parent = $this->canUpdateItem() && !in_array($this->fields['status'], $this->getClosedStatusArray());\n\n //checks rights\n $restrict_fup = $restrict_task = [];\n if (\n $params['hide_private_items']\n || ($params['check_view_rights'] && !Session::haveRight(\"followup\", ITILFollowup::SEEPRIVATE))\n ) {\n if (!$params['check_view_rights']) {\n // notification case, we cannot rely on session\n $restrict_fup = [\n 'is_private' => 0,\n ];\n } else {\n $restrict_fup = [\n 'OR' => [\n 'is_private' => 0,\n 'users_id' => Session::getCurrentInterface() === \"central\" ? (int)Session::getLoginUserID() : 0,\n ]\n ];\n }\n }\n\n $restrict_fup['itemtype'] = static::getType();\n $restrict_fup['items_id'] = $this->getID();\n\n $taskClass = $objType . \"Task\";\n $task_obj = new $taskClass();\n if (\n $task_obj->maybePrivate()\n && (\n $params['hide_private_items']\n || ($params['check_view_rights'] && !Session::haveRight($task_obj::$rightname, CommonITILTask::SEEPRIVATE))\n )\n ) {\n if (!$params['check_view_rights']) {\n // notification case, we cannot rely on session\n $restrict_task = [\n 'is_private' => 0,\n ];\n } else {\n $restrict_task = [\n 'OR' => [\n 'is_private' => 0,\n 'users_id' => Session::getCurrentInterface() === \"central\" ? (int)Session::getLoginUserID() : 0,\n 'users_id_tech' => Session::getCurrentInterface() === \"central\" ? (int)Session::getLoginUserID() : 0,\n ]\n ];\n }\n }\n\n // Add followups to timeline\n $followup_obj = new ITILFollowup();\n if (!$params['check_view_rights'] || $followup_obj->canview()) {\n $followups = $followup_obj->find(\n ['items_id' => $this->getID()] + $restrict_fup,\n ['date_creation DESC', 'id DESC']\n );\n\n foreach ($followups as $followups_id => $followup_row) {\n // Safer to use a clean object to load our data\n $followup = new ITILFollowup();\n $followup->setParentItem($this);\n $followup->fields = $followup_row;\n $followup->post_getFromDB();\n\n if (!$params['check_view_rights'] || $followup->canViewItem()) {\n $followup_row['can_edit'] = $followup->canUpdateItem();\n $followup_row['can_promote'] =\n Session::getCurrentInterface() === 'central'\n && $this instanceof Ticket\n && Ticket::canCreate()\n ;\n $timeline[\"ITILFollowup_\" . $followups_id] = [\n 'type' => ITILFollowup::class,\n 'item' => $followup_row,\n 'object' => $followup,\n 'itiltype' => 'Followup'\n ];\n }\n }\n }\n\n // Add tasks to timeline\n if (!$params['check_view_rights'] || $task_obj->canview()) {\n $tasks = $task_obj->find(\n [$foreignKey => $this->getID()] + $restrict_task,\n 'date_creation DESC'\n );\n\n foreach ($tasks as $tasks_id => $task_row) {\n // Safer to use a clean object to load our data\n $task = new $taskClass();\n $task->fields = $task_row;\n $task->post_getFromDB();\n\n if (!$params['check_view_rights'] || $task->canViewItem()) {\n $task_row['can_edit'] = $task->canUpdateItem();\n $task_row['can_promote'] =\n Session::getCurrentInterface() === 'central'\n && $this instanceof Ticket\n && Ticket::canCreate()\n ;\n $timeline[$task::getType() . \"_\" . $tasks_id] = [\n 'type' => $taskClass,\n 'item' => $task_row,\n 'object' => $task,\n 'itiltype' => 'Task'\n ];\n }\n }\n }\n\n // Add solutions to timeline\n $solution_obj = new ITILSolution();\n $solution_items = $solution_obj->find([\n 'itemtype' => static::getType(),\n 'items_id' => $this->getID()\n ]);\n\n foreach ($solution_items as $solution_item) {\n // Safer to use a clean object to load our data\n $solution = new ITILSolution();\n $solution->setParentItem($this);\n $solution->fields = $solution_item;\n $solution->post_getFromDB();\n\n $timeline[\"ITILSolution_\" . $solution_item['id'] ] = [\n 'type' => ITILSolution::class,\n 'itiltype' => 'Solution',\n 'item' => [\n 'id' => $solution_item['id'],\n 'content' => $solution_item['content'],\n 'date' => $solution_item['date_creation'],\n 'users_id' => $solution_item['users_id'],\n 'solutiontypes_id' => $solution_item['solutiontypes_id'],\n 'can_edit' => $objType::canUpdate() && $this->canSolve(),\n 'timeline_position' => self::TIMELINE_RIGHT,\n 'users_id_editor' => $solution_item['users_id_editor'],\n 'date_creation' => $solution_item['date_creation'],\n 'date_mod' => $solution_item['date_mod'],\n 'users_id_approval' => $solution_item['users_id_approval'],\n 'date_approval' => $solution_item['date_approval'],\n 'status' => $solution_item['status']\n ],\n 'object' => $solution,\n ];\n }\n\n // Add validation to timeline\n $validation_class = $objType . \"Validation\";\n if (\n class_exists($validation_class) && $params['with_validations']\n && (!$params['check_view_rights'] || $validation_class::canView())\n ) {\n $validation_obj = new $validation_class();\n $validations = $validation_obj->find([\n $foreignKey => $this->getID()\n ]);\n\n foreach ($validations as $validations_id => $validation_row) {\n // Safer to use a clean object to load our data\n $validation = new $validation_class();\n $validation->fields = $validation_row;\n $validation->post_getFromDB();\n\n $canedit = $validation_obj->can($validations_id, UPDATE);\n $cananswer = ($validation_obj->canValidate($this->getID())\n && $validation_row['status'] == CommonITILValidation::WAITING);\n $user = new User();\n $user->getFromDB($validation_row['users_id_validate']);\n\n $request_key = $validation_obj::getType() . '_' . $validations_id\n . (empty($validation_row['validation_date']) ? '' : '_request'); // If no answer, no suffix to see attached documents on request\n\n $content = __('Validation request');\n if (is_a($validation_row['itemtype_target'], CommonDBTM::class, true)) {\n $validation_target = new $validation_row['itemtype_target']();\n if ($validation_target->getFromDB($validation_row['items_id_target'])) {\n $content .= \" <i class='ti ti-arrow-right'></i><i class='{$validation_target->getIcon()} text-muted me-1'></i>\"\n . $validation_target->getlink();\n }\n }\n $timeline[$request_key] = [\n 'type' => $validation_class,\n 'item' => [\n 'id' => $validations_id,\n 'date' => $validation_row['submission_date'],\n 'content' => $content,\n 'comment_submission' => $validation_row['comment_submission'],\n 'users_id' => $validation_row['users_id'],\n 'can_edit' => $canedit,\n 'can_answer' => $cananswer,\n 'users_id_validate' => ((int) $validation_row['users_id_validate'] > 0)\n ? $validation_row['users_id_validate']\n // 'users_id_validate' will be set to current user id once answer will be submitted\n : ($cananswer ? Session::getLoginUserID() : 0),\n 'timeline_position' => $validation_row['timeline_position']\n ],\n 'itiltype' => 'Validation',\n 'class' => 'validation-request ' .\n ($validation_row['status'] == CommonITILValidation::WAITING ? \"validation-waiting\" : \"\") .\n ($validation_row['status'] == CommonITILValidation::ACCEPTED ? \"validation-accepted\" : \"\") .\n ($validation_row['status'] == CommonITILValidation::REFUSED ? \"validation-refused\" : \"\"),\n 'item_action' => 'validation-request',\n 'object' => $validation,\n ];\n\n if (!empty($validation_row['validation_date'])) {\n $timeline[$validation_obj::getType() . \"_\" . $validations_id] = [\n 'type' => $validation_class,\n 'item' => [\n 'id' => $validations_id,\n 'date' => $validation_row['validation_date'],\n 'content' => __('Validation request answer') . \" : \" .\n _sx('status', ucfirst($validation_class::getStatus($validation_row['status']))),\n 'comment_validation' => $validation_row['comment_validation'],\n 'users_id' => $validation_row['users_id_validate'],\n 'status' => \"status_\" . $validation_row['status'],\n 'can_edit' => $canedit,\n 'timeline_position' => $validation_row['timeline_position'],\n 'itemtype_target' => $validation_row['itemtype_target'],\n 'items_id_target' => $validation_row['items_id_target']\n ],\n 'class' => 'validation-answer',\n 'itiltype' => 'Validation',\n 'item_action' => 'validation-answer',\n 'object' => $validation,\n ];\n }\n }\n }\n\n // Add documents to timeline\n if ($params['with_documents']) {\n $document_item_obj = new Document_Item();\n $document_obj = new Document();\n $document_items = $document_item_obj->find([\n $this->getAssociatedDocumentsCriteria(!$params['check_view_rights']),\n 'timeline_position' => ['>', self::NO_TIMELINE]\n ]);\n foreach ($document_items as $document_item) {\n if (!$document_obj->getFromDB($document_item['documents_id'])) {\n // Orphan `Document_Item`\n continue;\n }\n\n $item = $document_obj->fields;\n $item['date'] = $document_item['date'] ?? $document_item['date_creation'];\n // #1476 - set date_creation, date_mod and owner to attachment ones\n $item['date_creation'] = $document_item['date_creation'];\n $item['date_mod'] = $document_item['date_mod'];\n $item['users_id'] = $document_item['users_id'];\n $item['documents_item_id'] = $document_item['id'];\n\n $item['timeline_position'] = $document_item['timeline_position'];\n $item['_can_edit'] = Document::canUpdate() && $document_obj->canUpdateItem();\n $item['_can_delete'] = Document::canDelete() && $document_obj->canDeleteItem() && $canupdate_parent;\n\n $timeline_key = $document_item['itemtype'] . \"_\" . $document_item['items_id'];\n if ($document_item['itemtype'] == static::getType()) {\n // document associated directly to itilobject\n $timeline[\"Document_\" . $document_item['documents_id']] = [\n 'type' => 'Document_Item',\n 'item' => $item,\n 'object' => $document_obj,\n ];\n } elseif (isset($timeline[$timeline_key])) {\n // document associated to a sub item of itilobject\n if (!isset($timeline[$timeline_key]['documents'])) {\n $timeline[$timeline_key]['documents'] = [];\n }\n\n $docpath = GLPI_DOC_DIR . \"/\" . $item['filepath'];\n $is_image = Document::isImage($docpath);\n $sub_document = [\n 'type' => 'Document_Item',\n 'item' => $item,\n ];\n if ($is_image) {\n $sub_document['_is_image'] = true;\n $sub_document['_size'] = getimagesize($docpath);\n }\n $timeline[$timeline_key]['documents'][] = $sub_document;\n }\n }\n }\n\n // Add logs to timeline\n if ($params['with_logs'] && Session::getCurrentInterface() == \"central\") {\n //add logs to timeline\n $log_items = Log::getHistoryData($this, 0, 0, [\n 'OR' => [\n 'id_search_option' => ['>', 0],\n 'itemtype_link' => ['User', 'Group', 'Supplier'],\n ]\n ]);\n\n foreach ($log_items as $log_row) {\n // Safer to use a clean object to load our data\n $log = new Log();\n $log->fields = $log_row;\n $log->post_getFromDB();\n\n $content = $log_row['change'];\n if (strlen($log_row['field']) > 0) {\n $content = sprintf(__s(\"%s: %s\"), htmlspecialchars($log_row['field']), $content);\n }\n $content = \"<i class='fas fa-history me-1' title='\" . __s(\"Log entry\") . \"' data-bs-toggle='tooltip'></i>\" . $content;\n $user_id = 0;\n // try to extract ID from \"user_name\" (which was created using User::getNameForLog)\n if (preg_match('/ \\((\\d+)\\)$/', $log_row[\"user_name\"], $m)) {\n $user_id = $m[1];\n }\n $timeline[\"Log_\" . $log_row['id'] ] = [\n 'type' => 'Log',\n 'class' => 'text-muted d-none',\n 'item' => [\n 'id' => $log_row['id'],\n 'content' => $content,\n 'is_content_safe' => true,\n 'date' => $log_row['date_mod'],\n 'users_id' => $user_id,\n 'can_edit' => false,\n 'timeline_position' => self::TIMELINE_LEFT,\n ],\n 'object' => $log,\n ];\n }\n }\n\n // add autoreminders to timeline\n $autoreminder_obj = new ITILReminder();\n $autoreminders = $autoreminder_obj->find(['items_id' => $this->getID()]);\n foreach ($autoreminders as $autoreminder_id => $autoreminder) {\n $autoreminder_obj = ITILReminder::getByID($autoreminder_id);\n $pending_reason = $autoreminder_obj->getPendingReason();\n $followup_template = ITILFollowupTemplate::getById($pending_reason->fields['itilfollowuptemplates_id']);\n $content = sprintf(\n '<span>%1$s%2$s (<span data-bs-toggle=\"popover\" data-bs-html=\"true\" data-bs-sanitize=\"true\" data-bs-content=\"%3$s\"><u>%4$s</u></span>)</span>',\n '<i class=\"ti ti-refresh-alert text-warning me-1\"></i>',\n ITILReminder::getTypeName(1),\n $autoreminder_obj->fields['content'] ?? '',\n $autoreminder_obj->fields['name']\n );\n\n $timeline[\"ITILReminder_\" . $autoreminder_id] = [\n 'type' => ITILReminder::class,\n 'item' => [\n 'id' => $autoreminder_id,\n 'content' => $content,\n 'is_content_safe' => true,\n 'date' => $autoreminder['date_creation'],\n 'users_id' => 0,\n 'can_edit' => false,\n 'timeline_position' => self::TIMELINE_LEFT,\n ],\n 'object' => $autoreminder_obj,\n ];\n }\n\n Plugin::doHook(Hooks::SHOW_IN_TIMELINE, ['item' => $this, 'timeline' => &$timeline]);\n\n //sort timeline items by date. If items have the same date, sort by id\n $reverse = $params['sort_by_date_desc'];\n usort($timeline, function ($a, $b) use ($reverse) {\n $date_a = $a['item']['date_creation'] ?? $a['item']['date'];\n $date_b = $b['item']['date_creation'] ?? $b['item']['date'];\n $diff = strtotime($date_a) - strtotime($date_b);\n if ($diff === 0) {\n $diff = $a['item']['id'] - $b['item']['id'];\n }\n return $reverse ? 0 - $diff : $diff;\n });\n\n return $timeline;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function _calculateSummaryExtent($is_return_rec){\n\n $zoomKm = 0;\n $mbookmark = null;\n $mbox = array();\n foreach($this->maplayer_extents as $dtl_ID=>$values){\n foreach($values as $value){\n if(is_array($value) && @$value['geo']){\n $wkt = $value['geo']['wkt'];\n $bbox = self::_getExtentFromWkt($wkt);\n if($bbox!=null){\n if( !@$mbox['maxy'] || $mbox['maxy']<$bbox['maxy'] ){\n $mbox['maxy'] = $bbox['maxy'];\n }\n if( !@$mbox['maxx'] || $mbox['maxx']<$bbox['maxx'] ){\n $mbox['maxx'] = $bbox['maxx'];\n }\n if( !@$mbox['miny'] || $mbox['miny']>$bbox['miny'] ){\n $mbox['miny'] = $bbox['miny'];\n }\n if( !@$mbox['minx'] || $mbox['minx']>$bbox['minx'] ){\n $mbox['minx'] = $bbox['minx'];\n }\n }\n }\n }\n }\n if(count($mbox)==4){\n\n $gPoint = new \\GpointConverter();\n $gPoint->setLongLat($mbox['minx'], $mbox['miny']);\n $zoomKm = round($gPoint->distanceFrom($mbox['maxx'], $mbox['minx'])/100000,0);\n\n\n $mbookmark = 'Extent,'.$mbox['miny'].','.$mbox['minx']\n .','.$mbox['maxy'].','.$mbox['maxx'].',1800,2050';\n\n $mbox = array($mbox['minx'].' '.$mbox['miny'], $mbox['minx'].' '.$mbox['maxy'],\n $mbox['maxx'].' '.$mbox['maxy'], $mbox['maxx'].' '.$mbox['miny'],\n $mbox['minx'].' '.$mbox['miny']);\n $mbox = 'POLYGON(('.implode(',',$mbox).'))';\n\n }\n\n if($is_return_rec){\n\n //add constructed mapspace record\n $record['rec_ID'] = 999999999;\n $record['rec_RecTypeID'] = RT_MAP_DOCUMENT;\n $record['rec_Title'] = $this->tlc_mapdoc_name;\n $record['rec_URL'] = '';\n $record['rec_ScratchPad'] = '';\n $record[\"details\"] = array(\n DT_NAME=>array('1'=>$this->tlc_mapdoc_name),\n DT_MAP_BOOKMARK=>array('2'=>($mbookmark!=null?$mbookmark:$this->mapdoc_defaults[DT_MAP_BOOKMARK])),\n DT_ZOOM_KM_POINT=>array('3'=>($zoomKm>0?$zoomKm:$this->mapdoc_defaults[DT_ZOOM_KM_POINT])),\n DT_GEO_OBJECT=>array('4'=>($mbox!=null?array('geo'=>array(\"type\"=>\"pl\", \"wkt\"=>$mbox)):null)),\n DT_MAP_LAYER=>$this->maplayer_records\n );\n\n return $record;\n }else{\n return $mbox;\n }\n\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "function scoreinventory($stua, $answer, $invs, $rowper, $sn) {\n\tforeach($invs as $inv) {\n\t\tif ($inv[0]=='init') {\n\t\t\t$sn += 9;\n\t\t} else {\n\t\t\t$sn += 3; //skip past purch\n\t\t\tfor ($i=$sn+3;$i<$sn+$rowper*6;$i+=6) { //start on inventory\n\t\t\t\tif (!isset($stua[$i]) || $stua[$i]=='') {continue;}\n\t\t\t\t$foundmatch = false;\n\t\t\t\tfor ($j=$sn+3;$j<$sn+$rowper*6;$j+=6) {\n\t\t\t\t\tif (trim($stua[$i])==$answer[$j] && trim($stua[$i+1])==$answer[$j+1]) {\n\t\t\t\t\t\t$foundmatch = true;\n\t\t\t\t\t\t$matchloc = $j;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ($foundmatch && $i != $matchloc) {\n\t\t\t\t\t$tmp = array();\n\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t$tmp[$k] = $answer[$i+$k];\n\t\t\t\t\t}\n\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t$answer[$i+$k] = $answer[$matchloc+$k];\n\t\t\t\t\t}\n\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t$answer[$matchloc+$k] = $tmp[$k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ($inv[0]=='sale') {\n\t\t\t\tfor ($i=$sn;$i<$sn+$rowper*6;$i+=6) { //do cogs\n\t\t\t\t\tif (!isset($stua[$i]) || $stua[$i]=='') {continue;}\n\t\t\t\t\t$foundmatch = false;\n\t\t\t\t\tfor ($j=$sn;$j<$sn+$rowper*6;$j+=6) {\n\t\t\t\t\t\tif (trim($stua[$i])==$answer[$j] && trim($stua[$i+1])==$answer[$j+1]) {\n\t\t\t\t\t\t\t$foundmatch = true;\n\t\t\t\t\t\t\t$matchloc = $j;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ($foundmatch && $i != $matchloc) {\n\t\t\t\t\t\t$tmp = array();\n\t\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t\t$tmp[$k] = $answer[$i+$k];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t\t$answer[$i+$k] = $answer[$matchloc+$k];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor ($k=0;$k<3;$k++) {\n\t\t\t\t\t\t\t$answer[$matchloc+$k] = $tmp[$k];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$sn += $rowper*6;\n\t\t}\n\n\t}\n\treturn $answer;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function getToken(\n\t\tstring $grant_type, ?string $code, ?string $refresh_token,\n\t\t?string $client_id, ?string $client_secret\n\t): JSONResponse {\n\n\t\t// We only handle two types\n\t\tif ($grant_type !== 'authorization_code' && $grant_type !== 'refresh_token') {\n\t\t\t$response = new JSONResponse([\n\t\t\t\t'error' => 'invalid_grant',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t$response->throttle(['invalid_grant' => $grant_type]);\n\t\t\treturn $response;\n\t\t}\n\n\t\t// We handle the initial and refresh tokens the same way\n\t\tif ($grant_type === 'refresh_token') {\n\t\t\t$code = $refresh_token;\n\t\t}\n\n\t\ttry {\n\t\t\t$accessToken = $this->accessTokenMapper->getByCode($code);\n\t\t} catch (AccessTokenNotFoundException $e) {\n\t\t\t$response = new JSONResponse([\n\t\t\t\t'error' => 'invalid_request',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t$response->throttle(['invalid_request' => 'token not found', 'code' => $code]);\n\t\t\treturn $response;\n\t\t}\n\n\t\tif ($grant_type === 'authorization_code') {\n\t\t\t// check this token is in authorization code state\n\t\t\t$deliveredTokenCount = $accessToken->getTokenCount();\n\t\t\tif ($deliveredTokenCount > 0) {\n\t\t\t\t$response = new JSONResponse([\n\t\t\t\t\t'error' => 'invalid_request',\n\t\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t\t$response->throttle(['invalid_request' => 'authorization_code_received_for_active_token']);\n\t\t\t\treturn $response;\n\t\t\t}\n\n\t\t\t// check authorization code expiration\n\t\t\t$now = $this->timeFactory->now()->getTimestamp();\n\t\t\t$codeCreatedAt = $accessToken->getCodeCreatedAt();\n\t\t\tif ($codeCreatedAt < $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER) {\n\t\t\t\t// we know this token is not useful anymore\n\t\t\t\t$this->accessTokenMapper->delete($accessToken);\n\n\t\t\t\t$response = new JSONResponse([\n\t\t\t\t\t'error' => 'invalid_request',\n\t\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t\t$expiredSince = $now - self::AUTHORIZATION_CODE_EXPIRES_AFTER - $codeCreatedAt;\n\t\t\t\t$response->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]);\n\t\t\t\treturn $response;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t$client = $this->clientMapper->getByUid($accessToken->getClientId());\n\t\t} catch (ClientNotFoundException $e) {\n\t\t\t$response = new JSONResponse([\n\t\t\t\t'error' => 'invalid_request',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t$response->throttle(['invalid_request' => 'client not found', 'client_id' => $accessToken->getClientId()]);\n\t\t\treturn $response;\n\t\t}\n\n\t\tif (isset($this->request->server['PHP_AUTH_USER'])) {\n\t\t\t$client_id = $this->request->server['PHP_AUTH_USER'];\n\t\t\t$client_secret = $this->request->server['PHP_AUTH_PW'];\n\t\t}\n\n\t\ttry {\n\t\t\t$storedClientSecret = $this->crypto->decrypt($client->getSecret());\n\t\t} catch (\\Exception $e) {\n\t\t\t$this->logger->error('OAuth client secret decryption error', ['exception' => $e]);\n\t\t\t// we don't throttle here because it might not be a bruteforce attack\n\t\t\treturn new JSONResponse([\n\t\t\t\t'error' => 'invalid_client',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t}\n\t\t// The client id and secret must match. Else we don't provide an access token!\n\t\tif ($client->getClientIdentifier() !== $client_id || $storedClientSecret !== $client_secret) {\n\t\t\t$response = new JSONResponse([\n\t\t\t\t'error' => 'invalid_client',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t$response->throttle(['invalid_client' => 'client ID or secret does not match']);\n\t\t\treturn $response;\n\t\t}\n\n\t\t$decryptedToken = $this->crypto->decrypt($accessToken->getEncryptedToken(), $code);\n\n\t\t// Obtain the appToken associated\n\t\ttry {\n\t\t\t$appToken = $this->tokenProvider->getTokenById($accessToken->getTokenId());\n\t\t} catch (ExpiredTokenException $e) {\n\t\t\t$appToken = $e->getToken();\n\t\t} catch (InvalidTokenException $e) {\n\t\t\t//We can't do anything...\n\t\t\t$this->accessTokenMapper->delete($accessToken);\n\t\t\t$response = new JSONResponse([\n\t\t\t\t'error' => 'invalid_request',\n\t\t\t], Http::STATUS_BAD_REQUEST);\n\t\t\t$response->throttle(['invalid_request' => 'token is invalid']);\n\t\t\treturn $response;\n\t\t}\n\n\t\t// Rotate the apptoken (so the old one becomes invalid basically)\n\t\t$newToken = $this->secureRandom->generate(72, ISecureRandom::CHAR_ALPHANUMERIC);\n\n\t\t$appToken = $this->tokenProvider->rotate(\n\t\t\t$appToken,\n\t\t\t$decryptedToken,\n\t\t\t$newToken\n\t\t);\n\n\t\t// Expiration is in 1 hour again\n\t\t$appToken->setExpires($this->time->getTime() + 3600);\n\t\t$this->tokenProvider->updateToken($appToken);\n\n\t\t// Generate a new refresh token and encrypt the new apptoken in the DB\n\t\t$newCode = $this->secureRandom->generate(128, ISecureRandom::CHAR_ALPHANUMERIC);\n\t\t$accessToken->setHashedCode(hash('sha512', $newCode));\n\t\t$accessToken->setEncryptedToken($this->crypto->encrypt($newToken, $newCode));\n\t\t// increase the number of delivered oauth token\n\t\t// this helps with cleaning up DB access token when authorization code has expired\n\t\t// and it never delivered any oauth token\n\t\t$tokenCount = $accessToken->getTokenCount();\n\t\t$accessToken->setTokenCount($tokenCount + 1);\n\t\t$this->accessTokenMapper->update($accessToken);\n\n\t\t$this->throttler->resetDelay($this->request->getRemoteAddress(), 'login', ['user' => $appToken->getUID()]);\n\n\t\treturn new JSONResponse(\n\t\t\t[\n\t\t\t\t'access_token' => $newToken,\n\t\t\t\t'token_type' => 'Bearer',\n\t\t\t\t'expires_in' => 3600,\n\t\t\t\t'refresh_token' => $newCode,\n\t\t\t\t'user_id' => $appToken->getUID(),\n\t\t\t]\n\t\t);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function handleArray(array $srcStruct, array $desStruct, string $path): array\n {\n $changes = [];\n\n if ($diff = $this->arrayDiff($desStruct, $srcStruct)) {\n foreach ($diff as $key => $val) {\n if (is_object($val)) {\n $changes = array_merge($changes, $this->makeDiff($srcStruct[$key], $val, $this->path($path, $key)));\n } else {\n $op = array_key_exists($key, $srcStruct) && !in_array($srcStruct[$key], $desStruct, true)\n ? self::OP_REPLACE : self::OP_ADD;\n $changes[] = $this->makePatch($op, $this->path($path, $key), $val);\n }\n }\n } elseif ($srcStruct != $desStruct) {\n foreach ($srcStruct as $key => $val) {\n if (!in_array($val, $desStruct, true)) {\n $changes[] = $this->makePatch(self::OP_REMOVE, $this->path($path, $key));\n }\n }\n }\n\n return $changes;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct(string $appName, Connection $connection, ?IOutput $output = null, ?AppLocator $appLocator = null, ?LoggerInterface $logger = null) {\n\t\t$this->appName = $appName;\n\t\t$this->connection = $connection;\n\t\tif ($logger === null) {\n\t\t\t$this->logger = Server::get(LoggerInterface::class);\n\t\t} else {\n\t\t\t$this->logger = $logger;\n\t\t}\n\t\tif ($output === null) {\n\t\t\t$this->output = new SimpleOutput($this->logger, $appName);\n\t\t} else {\n\t\t\t$this->output = $output;\n\t\t}\n\n\t\tif ($appName === 'core') {\n\t\t\t$this->migrationsPath = \\OC::$SERVERROOT . '/core/Migrations';\n\t\t\t$this->migrationsNamespace = 'OC\\\\Core\\\\Migrations';\n\t\t\t$this->checkOracle = true;\n\t\t} else {\n\t\t\tif ($appLocator === null) {\n\t\t\t\t$appLocator = new AppLocator();\n\t\t\t}\n\t\t\t$appPath = $appLocator->getAppPath($appName);\n\t\t\t$namespace = App::buildAppNamespace($appName);\n\t\t\t$this->migrationsPath = \"$appPath/lib/Migration\";\n\t\t\t$this->migrationsNamespace = $namespace . '\\\\Migration';\n\n\t\t\t$infoParser = new InfoParser();\n\t\t\t$info = $infoParser->parse($appPath . '/appinfo/info.xml');\n\t\t\tif (!isset($info['dependencies']['database'])) {\n\t\t\t\t$this->checkOracle = true;\n\t\t\t} else {\n\t\t\t\t$this->checkOracle = false;\n\t\t\t\tforeach ($info['dependencies']['database'] as $database) {\n\t\t\t\t\tif (\\is_string($database) && $database === 'oci') {\n\t\t\t\t\t\t$this->checkOracle = true;\n\t\t\t\t\t} elseif (\\is_array($database) && isset($database['@value']) && $database['@value'] === 'oci') {\n\t\t\t\t\t\t$this->checkOracle = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$this->migrationTableCreated = false;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function lookup_code_descriptions($codes, $desc_detail = \"code_text\")\n{\n global $code_types, $code_external_tables;\n\n // ensure $desc_detail is set properly\n if (($desc_detail != \"code_text\") && ($desc_detail != \"code_text_short\")) {\n $desc_detail = \"code_text\";\n }\n\n $code_text = '';\n if (!empty($codes)) {\n $relcodes = explode(';', $codes);\n foreach ($relcodes as $codestring) {\n if ($codestring === '') {\n continue;\n }\n\n // added $modifier for HCPCS and other internal codesets so can grab exact entry in codes table\n $code_parts = explode(':', $codestring);\n $codetype = $code_parts[0] ?? null;\n $code = $code_parts[1] ?? null;\n $modifier = $code_parts[2] ?? null;\n // if we don't have the code types we can't do much here\n if (!isset($code_types[$codetype])) {\n // we can't do much so we will just continue here...\n continue;\n }\n\n $table_id = $code_types[$codetype]['external'] ?? '';\n if (!isset($code_external_tables[$table_id])) {\n //using an external code that is not yet supported, so skip.\n continue;\n }\n\n $table_info = $code_external_tables[$table_id];\n $table_name = $table_info[EXT_TABLE_NAME];\n $code_col = $table_info[EXT_COL_CODE];\n $desc_col = $table_info[DISPLAY_DESCRIPTION] == \"\" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];\n $desc_col_short = $table_info[DISPLAY_DESCRIPTION] == \"\" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];\n $sqlArray = array();\n $sql = \"SELECT \" . $desc_col . \" as code_text,\" . $desc_col_short . \" as code_text_short FROM \" . $table_name;\n\n // include the \"JOINS\" so that we get the preferred term instead of the FullySpecifiedName when appropriate.\n foreach ($table_info[EXT_JOINS] as $join_info) {\n $join_table = $join_info[JOIN_TABLE];\n $check_table = sqlQuery(\"SHOW TABLES LIKE '\" . $join_table . \"'\");\n if ((empty($check_table))) {\n HelpfulDie(\"Missing join table in code set search:\" . $join_table);\n }\n\n $sql .= \" INNER JOIN \" . $join_table;\n $sql .= \" ON \";\n $not_first = false;\n foreach ($join_info[JOIN_FIELDS] as $field) {\n if ($not_first) {\n $sql .= \" AND \";\n }\n\n $sql .= $field;\n $not_first = true;\n }\n }\n\n $sql .= \" WHERE \";\n\n\n // Start building up the WHERE clause\n\n // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)\n if ($table_id == 0) {\n $sql .= \" code_type = '\" . add_escape_custom($code_types[$codetype]['id']) . \"' AND \";\n }\n\n // Specify the code in the query.\n $sql .= $table_name . \".\" . $code_col . \"=? \";\n $sqlArray[] = $code;\n\n // Add the modifier if necessary for CPT and HCPCS which differentiates code\n if ($modifier) {\n $sql .= \" AND modifier = ? \";\n $sqlArray[] = $modifier;\n }\n\n // We need to include the filter clauses\n // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate\n // It also prevents returning \"inactive\" results\n foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {\n $sql .= \" AND \" . $filter_clause;\n }\n\n // END building the WHERE CLAUSE\n\n\n if ($table_info[EXT_VERSION_ORDER]) {\n $sql .= \" ORDER BY \" . $table_info[EXT_VERSION_ORDER];\n }\n\n $sql .= \" LIMIT 1\";\n $crow = sqlQuery($sql, $sqlArray);\n if (!empty($crow[$desc_detail])) {\n if ($code_text) {\n $code_text .= '; ';\n }\n\n $code_text .= $crow[$desc_detail];\n }\n }\n }\n\n return $code_text;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function _createFormulaFromTokens($tokens, $additionalData)\n\t{\n\t\t// empty formula?\n\t\tif (empty($tokens)) {\n\t\t\treturn '';\n\t\t}\n\n\t\t$formulaStrings = array();\n\t\tforeach ($tokens as $token) {\n\t\t\t// initialize spaces\n\t\t\t$space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen\n\t\t\t$space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen\n\t\t\t$space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis\n\t\t\t$space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis\n\t\t\t$space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis\n\t\t\t$space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis\n\n\t\t\tswitch ($token['name']) {\n\t\t\tcase 'tAdd': // addition\n\t\t\tcase 'tConcat': // addition\n\t\t\tcase 'tDiv': // division\n\t\t\tcase 'tEQ': // equality\n\t\t\tcase 'tGE': // greater than or equal\n\t\t\tcase 'tGT': // greater than\n\t\t\tcase 'tIsect': // intersection\n\t\t\tcase 'tLE': // less than or equal\n\t\t\tcase 'tList': // less than or equal\n\t\t\tcase 'tLT': // less than\n\t\t\tcase 'tMul': // multiplication\n\t\t\tcase 'tNE': // multiplication\n\t\t\tcase 'tPower': // power\n\t\t\tcase 'tRange': // range\n\t\t\tcase 'tSub': // subtraction\n\t\t\t\t$op2 = array_pop($formulaStrings);\n\t\t\t\t$op1 = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$op1$space1$space0{$token['data']}$op2\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tUplus': // unary plus\n\t\t\tcase 'tUminus': // unary minus\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}$op\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tPercent': // percent sign\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$op$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrVolatile': // indicates volatile function\n\t\t\tcase 'tAttrIf':\n\t\t\tcase 'tAttrSkip':\n\t\t\tcase 'tAttrChoose':\n\t\t\t\t// token is only important for Excel formula evaluator\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrSpace': // space / carriage return\n\t\t\t\t// space will be used when next token arrives, do not alter formulaString stack\n\t\t\t\tswitch ($token['data']['spacetype']) {\n\t\t\t\tcase 'type0':\n\t\t\t\t\t$space0 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type1':\n\t\t\t\t\t$space1 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type2':\n\t\t\t\t\t$space2 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type3':\n\t\t\t\t\t$space3 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type4':\n\t\t\t\t\t$space4 = str_repeat(' ', $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'type5':\n\t\t\t\t\t$space5 = str_repeat(\"\\n\", $token['data']['spacecount']);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'tAttrSum': // SUM function with one parameter\n\t\t\t\t$op = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"{$space1}{$space0}SUM($op)\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tFunc': // function with fixed number of arguments\n\t\t\tcase 'tFuncV': // function with variable number of arguments\n\t\t\t\tif ($token['data']['function'] != '') {\n\t\t\t\t\t// normal function\n\t\t\t\t\t$ops = array(); // array of operators\n\t\t\t\t\tfor ($i = 0; $i < $token['data']['args']; ++$i) {\n\t\t\t\t\t\t$ops[] = array_pop($formulaStrings);\n\t\t\t\t\t}\n\t\t\t\t\t$ops = array_reverse($ops);\n\t\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']['function']}(\" . implode(',', $ops) . \")\";\n\t\t\t\t\tunset($space0, $space1);\n\t\t\t\t} else {\n\t\t\t\t\t// add-in function\n\t\t\t\t\t$ops = array(); // array of operators\n\t\t\t\t\tfor ($i = 0; $i < $token['data']['args'] - 1; ++$i) {\n\t\t\t\t\t\t$ops[] = array_pop($formulaStrings);\n\t\t\t\t\t}\n\t\t\t\t\t$ops = array_reverse($ops);\n\t\t\t\t\t$function = array_pop($formulaStrings);\n\t\t\t\t\t$formulaStrings[] = \"$space1$space0$function(\" . implode(',', $ops) . \")\";\n\t\t\t\t\tunset($space0, $space1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'tParen': // parenthesis\n\t\t\t\t$expression = array_pop($formulaStrings);\n\t\t\t\t$formulaStrings[] = \"$space3$space2($expression$space5$space4)\";\n\t\t\t\tunset($space2, $space3, $space4, $space5);\n\t\t\t\tbreak;\n\t\t\tcase 'tArray': // array constant\n\t\t\t\t$constantArray = self::_readBIFF8ConstantArray($additionalData);\n\t\t\t\t$formulaStrings[] = $space1 . $space0 . $constantArray['value'];\n\t\t\t\t$additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tMemArea':\n\t\t\t\t// bite off chunk of additional data\n\t\t\t\t$cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($additionalData);\n\t\t\t\t$additionalData = substr($additionalData, $cellRangeAddressList['size']);\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\tcase 'tArea': // cell range address\n\t\t\tcase 'tBool': // boolean\n\t\t\tcase 'tErr': // error code\n\t\t\tcase 'tInt': // integer\n\t\t\tcase 'tMemErr':\n\t\t\tcase 'tMemFunc':\n\t\t\tcase 'tMissArg':\n\t\t\tcase 'tName':\n\t\t\tcase 'tNameX':\n\t\t\tcase 'tNum': // number\n\t\t\tcase 'tRef': // single cell reference\n\t\t\tcase 'tRef3d': // 3d cell reference\n\t\t\tcase 'tArea3d': // 3d cell range reference\n\t\t\tcase 'tRefN':\n\t\t\tcase 'tAreaN':\n\t\t\tcase 'tStr': // string\n\t\t\t\t$formulaStrings[] = \"$space1$space0{$token['data']}\";\n\t\t\t\tunset($space0, $space1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t$formulaString = $formulaStrings[0];\n\n\t\t// for debug: dump the human readable formula\n\t\t//echo '----' . \"\\n\";\n\t\t//echo 'Formula: ' . $formulaString;\n\n\t\treturn $formulaString;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function preProcessPreviewResults($output)\n {\n /** @var array $PLUGIN_HOOKS */\n global $PLUGIN_HOOKS;\n\n if (isset($PLUGIN_HOOKS['use_rules'])) {\n $params['rule_itemtype'] = static::class;\n foreach ($PLUGIN_HOOKS['use_rules'] as $plugin => $val) {\n if (!Plugin::isPluginActive($plugin)) {\n continue;\n }\n if (is_array($val) && in_array($params['rule_itemtype'], $val, true)) {\n $results = Plugin::doOneHook(\n $plugin,\n \"preProcessRuleCollectionPreviewResults\",\n ['output' => $output,\n 'params' => $params\n ]\n );\n if (is_array($results)) {\n foreach ($results as $id => $result) {\n $output[$id] = $result;\n }\n }\n }\n }\n }\n return $this->cleanTestOutputCriterias($output);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function executeActions($output, $params, array $input = [])\n {\n if (count($this->actions)) {\n foreach ($this->actions as $action) {\n switch ($action->fields[\"action_type\"]) {\n case \"assign\":\n $output[$action->fields[\"field\"]] = $action->fields[\"value\"];\n break;\n\n case \"regex_result\":\n //Assign entity using the regex's result\n if ($action->fields[\"field\"] === \"_affect_entity_by_tag\") {\n //Get the TAG from the regex's results\n if (isset($this->regex_results[0])) {\n $res = RuleAction::getRegexResultById(\n $action->fields[\"value\"],\n $this->regex_results[0]\n );\n } else {\n $res = $action->fields[\"value\"];\n }\n if ($res !== null) {\n // Get the entity associated with the TAG\n $target_entity = Entity::getEntityIDByTag($res);\n if ($target_entity != '') {\n $output[\"entities_id\"] = $target_entity;\n }\n }\n }\n break;\n }\n }\n }\n return $output;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['display'])) {\n $this->setDisplay($data['display']);\n }\n if (isset($data['equivalence'])) {\n $this->setEquivalence($data['equivalence']);\n }\n if (isset($data['comment'])) {\n $this->setComment($data['comment']);\n }\n if (isset($data['dependsOn'])) {\n if (is_array($data['dependsOn'])) {\n foreach ($data['dependsOn'] as $d) {\n $this->addDependsOn($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"dependsOn\" must be array of objects or null, ' . gettype($data['dependsOn']) . ' seen.');\n }\n }\n if (isset($data['product'])) {\n if (is_array($data['product'])) {\n foreach ($data['product'] as $d) {\n $this->addProduct($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"product\" must be array of objects or null, ' . gettype($data['product']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function updateConfigProperties(array $properties, $update_slave = true, string $config_dir = GLPI_CONFIG_DIR): bool\n {\n $main_config_file = 'config_db.php';\n $slave_config_file = 'config_db_slave.php';\n\n if (!file_exists($config_dir . '/' . $main_config_file)) {\n return false;\n }\n\n $files = [$main_config_file];\n if ($update_slave && file_exists($config_dir . '/' . $slave_config_file)) {\n $files[] = $slave_config_file;\n }\n\n foreach ($files as $file) {\n if (($config_str = file_get_contents($config_dir . '/' . $file)) === false) {\n return false;\n }\n\n foreach ($properties as $name => $value) {\n if ($name === 'password') {\n $value = rawurlencode($value);\n }\n\n $pattern = '/(?<line>' . preg_quote('$' . $name, '/') . '\\s*=\\s*(?<value>[^;]+)\\s*;)' . '/';\n\n $matches = [];\n if (preg_match($pattern, $config_str, $matches)) {\n // Property declaration is located in config file, we have to update it.\n $updated_line = str_replace($matches['value'], var_export($value, true), $matches['line']);\n $config_str = str_replace($matches['line'], $updated_line, $config_str);\n } else {\n // Property declaration is not located in config file, we have to add it.\n $ending_bracket_pos = mb_strrpos($config_str, '}');\n $config_str = mb_substr($config_str, 0, $ending_bracket_pos)\n . sprintf(' public $%s = %s;', $name, var_export($value, true)) . \"\\n\"\n . mb_substr($config_str, $ending_bracket_pos);\n }\n }\n\n if (!Toolbox::writeConfig($file, $config_str, $config_dir)) {\n return false;\n }\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function send($method, $url, $post_data = null)\n {\n if ($GLOBALS['couchdb_connection_ssl']) {\n // encrypt couchdb over the wire\n if (\n file_exists($GLOBALS['OE_SITE_DIR'] . \"/documents/certificates/couchdb-ca\") &&\n file_exists($GLOBALS['OE_SITE_DIR'] . \"/documents/certificates/couchdb-cert\") &&\n file_exists($GLOBALS['OE_SITE_DIR'] . \"/documents/certificates/couchdb-key\")\n ) {\n // support cacert_file and client certificates\n $stream_context = stream_context_create(\n [\n 'ssl' =>\n [\n 'cafile' => \"${GLOBALS['OE_SITE_DIR']}/documents/certificates/couchdb-ca\",\n 'local_cert' => \"${GLOBALS['OE_SITE_DIR']}/documents/certificates/couchdb-cert\",\n 'local_pk' => \"${GLOBALS['OE_SITE_DIR']}/documents/certificates/couchdb-key\"\n ]\n ]\n );\n $s = stream_socket_client('ssl://' . $this->host . \":\" . $this->port, $errno, $errstr, ini_get(\"default_socket_timeout\"), STREAM_CLIENT_CONNECT, $stream_context);\n } elseif (file_exists($GLOBALS['OE_SITE_DIR'] . \"/documents/certificates/couchdb-ca\")) {\n // support cacert_file\n $stream_context = stream_context_create(\n [\n 'ssl' =>\n [\n 'cafile' => \"${GLOBALS['OE_SITE_DIR']}/documents/certificates/couchdb-ca\"\n ]\n ]\n );\n $s = stream_socket_client('ssl://' . $this->host . \":\" . $this->port, $errno, $errstr, ini_get(\"default_socket_timeout\"), STREAM_CLIENT_CONNECT, $stream_context);\n } else {\n if ($GLOBALS['couchdb_ssl_allow_selfsigned']) {\n // support self-signed\n $stream_context = stream_context_create(\n [\n 'ssl' =>\n [\n 'verify_peer' => false,\n 'allow_self_signed' => true\n ]\n ]\n );\n $s = stream_socket_client('ssl://' . $this->host . \":\" . $this->port, $errno, $errstr, ini_get(\"default_socket_timeout\"), STREAM_CLIENT_CONNECT, $stream_context);\n } else {\n // self-signed, not supported so do not proceed and return false\n return false;\n }\n }\n } else {\n // do not encrypt couchdb over the wire\n $s = stream_socket_client('tcp://' . $this->host . \":\" . $this->port, $errno, $errstr);\n }\n\n if (!$s) {\n return false;\n }\n\n $request = \"$method $url HTTP/1.0\\r\\nHost: $this->host\\r\\n\";\n\n if ($this->user) {\n $request .= 'Authorization: Basic ' . base64_encode($this->user . ':' . $this->pass) . \"\\r\\n\";\n }\n\n if ($post_data) {\n $request .= \"Content-Length: \" . strlen($post_data) . \"\\r\\n\\r\\n\";\n $request .= \"$post_data\\r\\n\";\n } else {\n $request .= \"\\r\\n\";\n }\n\n fwrite($s, $request);\n $response = \"\";\n\n while (!feof($s)) {\n $response .= fgets($s);\n }\n\n list($this->headers, $this->body) = explode(\"\\r\\n\\r\\n\", $response);\n return $this->body;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function updateRectypeGroup($columnNames, $rtgID, $rt) {\n global $system, $mysqli, $rtgColumnNames;\n\n $rtg_ID = mysql__select_value($mysqli, \"select rtg_ID from defRecTypeGroups where rtg_ID = $rtgID\");\n\n if (!($rtg_ID>0)){\n $system->addError(HEURIST_NOT_FOUND, \"Record type group $rtgID not found\");\n return false;\n }\n\n $ret = array();\n $query = \"\";\n $rtg_Name = null;\n if ( !isEmptyArray($columnNames) ) {\n\n $vals = $rt;\n $parameters = array(\"\");//list of field date types\n foreach ($columnNames as $colName) {\n $val = array_shift($vals);\n\n if (array_key_exists($colName, $rtgColumnNames)) {\n //array_push($ret['error'], array('wrongname'=>\"$colName is not a valid column name for defRecTypeGroups val= $val was not used\"));\n\n if($query!=\"\") {$query = $query.\",\";}\n $query = $query.\"$colName = ?\";\n\n $parameters = addParam($parameters, $rtgColumnNames[$colName], $val);\n\n if($colName=='rtg_Name'){\n $rtg_Name = $val;\n }\n }\n }\n //\n\n if($rtg_Name){\n $rtg_ID = mysql__select_value($mysqli, \"select rtg_ID from defRecTypeGroups where rtg_Name = '$rtg_Name' and rtg_ID != $rtgID\");\n if ($rtg_ID>0){\n $system->addError(HEURIST_ACTION_BLOCKED, \"There is already group with name '$rtg_Name'\");\n return false;\n }\n }\n\n\n if($query!=\"\"){\n $query = \"update defRecTypeGroups set \".$query.\" where rtg_ID = $rtgID\";\n\n $rows = mysql__exec_param_query($mysqli, $query, $parameters, true);\n if (is_string($rows) ) {\n return handleError(\"SQL error updating $colName in updateRectypeGroup\",\n $query, $rows.' params:'.print_r($parameters,true));\n } else {\n $ret['result'] = $rtgID;\n }\n }\n }\n if (!@$ret['result']) {\n $system->addError(HEURIST_NOT_FOUND, 'Error: no data supplied for updating record type group $rtgID in defRecTypeGroups table');\n $ret = false;\n }\n\n return $ret;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function escapeXliff(string $content): string\n {\n $count = 1;\n $openTags = [];\n $final = [];\n\n // remove nasty device control characters\n $content = preg_replace('/[\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F]/', '', $content);\n\n if (!preg_match_all('/<([^>]+)>([^<]+)?/', $content, $matches)) {\n // return original content if it doesn't contain HTML tags\n return $this->encodeData($content);\n }\n\n // Handle text before the first HTML tag\n $firstTagPosition = strpos($content, '<');\n $preText = ($firstTagPosition > 0) ? $this->encodeData(substr($content, 0, $firstTagPosition)) : '';\n\n foreach ($matches[0] as $match) {\n $parts = explode('>', $match);\n $parts[0] .= '>';\n foreach ($parts as $part) {\n if (!empty(trim($part)) || trim($part) === '0') {\n if (preg_match(\"/<([a-z0-9\\/]+)/\", $part, $tag)) {\n $tagName = str_replace('/', '', $tag[1]);\n if (in_array($tagName, self::SELFCLOSING_TAGS)) {\n $part = '<ph id=\"' . $count . '\">' . $this->encodeData($part) . '</ph>';\n\n $count++;\n } elseif (!str_contains($tag[1], '/')) {\n $openTags[$count] = ['tag' => $tagName, 'id' => $count];\n $part = '<bpt id=\"' . $count . '\">' . $this->encodeData($part) . '</bpt>';\n\n $count++;\n } else {\n $closingTag = array_pop($openTags);\n $part = '<ept id=\"' . $closingTag['id'] . '\">' . $this->encodeData($part) . '</ept>';\n }\n } else {\n $part = $this->encodeData($part);\n }\n\n if (!empty($part)) {\n $final[] = $part;\n }\n }\n }\n }\n\n $content = $preText . implode('', $final);\n\n return $content;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "private function convertLayoutProperties()\n {\n $res = sqlStatement(\"SELECT DISTINCT form_id FROM layout_options ORDER BY form_id\");\n while ($row = sqlFetchArray($res)) {\n $form_id = $row['form_id'];\n $props = array(\n 'title' => 'Unknown',\n 'mapping' => 'Core',\n 'notes' => '',\n 'activity' => '1',\n 'option_value' => '0',\n );\n if (substr($form_id, 0, 3) == 'LBF') {\n $props = sqlQuery(\n \"SELECT title, mapping, notes, activity, option_value FROM list_options WHERE list_id = 'lbfnames' AND option_id = ?\",\n array($form_id)\n );\n if (empty($props)) {\n continue;\n }\n if (empty($props['mapping'])) {\n $props['mapping'] = 'Clinical';\n }\n } elseif (substr($form_id, 0, 3) == 'LBT') {\n $props = sqlQuery(\n \"SELECT title, mapping, notes, activity, option_value FROM list_options WHERE list_id = 'transactions' AND option_id = ?\",\n array($form_id)\n );\n if (empty($props)) {\n continue;\n }\n if (empty($props['mapping'])) {\n $props['mapping'] = 'Transactions';\n }\n } elseif ($form_id == 'DEM') {\n $props['title'] = 'Demographics';\n } elseif ($form_id == 'HIS') {\n $props['title'] = 'History';\n } elseif ($form_id == 'FACUSR') {\n $props['title'] = 'Facility Specific User Information';\n } elseif ($form_id == 'CON') {\n $props['title'] = 'Contraception Issues';\n } elseif ($form_id == 'GCA') {\n $props['title'] = 'Abortion Issues';\n } elseif ($form_id == 'SRH') {\n $props['title'] = 'IPPF SRH Data';\n }\n\n $query = \"INSERT INTO layout_group_properties SET \" .\n \"grp_form_id = ?, \" .\n \"grp_group_id = '', \" .\n \"grp_title = ?, \" .\n \"grp_mapping = ?, \" .\n \"grp_activity = ?, \" .\n \"grp_repeats = ?\";\n $sqlvars = array($form_id, $props['title'], $props['mapping'], $props['activity'], $props['option_value']);\n if ($props['notes']) {\n $jobj = json_decode($props['notes'], true);\n if (isset($jobj['columns'])) {\n $query .= \", grp_columns = ?\";\n $sqlvars[] = $jobj['columns'];\n }\n if (isset($jobj['size'])) {\n $query .= \", grp_size = ?\";\n $sqlvars[] = $jobj['size'];\n }\n if (isset($jobj['issue'])) {\n $query .= \", grp_issue_type = ?\";\n $sqlvars[] = $jobj['issue'];\n }\n if (isset($jobj['aco'])) {\n $query .= \", grp_aco_spec = ?\";\n $sqlvars[] = $jobj['aco'];\n }\n if (isset($jobj['services'])) {\n $query .= \", grp_services = ?\";\n // if present but empty, means all services\n $sqlvars[] = $jobj['services'] ? $jobj['services'] : '*';\n }\n if (isset($jobj['products'])) {\n $query .= \", grp_products = ?\";\n // if present but empty, means all products\n $sqlvars[] = $jobj['products'] ? $jobj['products'] : '*';\n }\n if (isset($jobj['diags'])) {\n $query .= \", grp_diags = ?\";\n // if present but empty, means all diags\n $sqlvars[] = $jobj['diags'] ? $jobj['diags'] : '*';\n }\n }\n sqlStatement($query, $sqlvars);\n\n $gres = sqlStatement(\n \"SELECT DISTINCT group_name FROM layout_options WHERE form_id = ? ORDER BY group_name\",\n array($form_id)\n );\n\n // For each group within this layout...\n while ($grow = sqlFetchArray($gres)) {\n $group_name = $grow['group_name'];\n $group_id = '';\n $title = '';\n $a = explode('|', $group_name);\n foreach ($a as $tmp) {\n $group_id .= substr($tmp, 0, 1);\n $title = substr($tmp, 1);\n }\n sqlStatement(\n \"UPDATE layout_options SET group_id = ? WHERE form_id = ? AND group_name = ?\",\n array($group_id, $form_id, $group_name)\n );\n $query = \"INSERT IGNORE INTO layout_group_properties SET \" .\n \"grp_form_id = ?, \" .\n \"grp_group_id = ?, \" .\n \"grp_title = '\" . add_escape_custom($title) . \"'\";\n // grp_title not using $sqlvars because of a bug causing '' to become '0'.\n $sqlvars = array($form_id, $group_id);\n /****************************************************************\n if ($props['notes']) {\n if (isset($jobj['columns'])) {\n $query .= \", grp_columns = ?\";\n $sqlvars[] = $jobj['columns'];\n }\n if (isset($jobj['size'])) {\n $query .= \", grp_size = ?\";\n $sqlvars[] = $jobj['size'];\n }\n }\n ****************************************************************/\n // $this->echo($query); foreach ($sqlvars as $tmp) $this->echo(\" '$tmp'\"); $this->echo(\"<br />\\n\"); // debugging\n sqlStatement($query, $sqlvars);\n } // end group\n } // end form\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function validate($uploaded_file, $file, $error, $index, $content_range)\n {\n if ($error) {\n $file->error = $this->get_error_message($error);\n return false;\n }\n $content_length = $this->fix_integer_overflow(\n (int)$this->get_server_var('CONTENT_LENGTH')\n );\n $post_max_size = $this->get_config_bytes(ini_get('post_max_size'));\n if ($post_max_size && ($content_length > $post_max_size)) {\n $file->error = $this->get_error_message('post_max_size');\n return false;\n }\n if (!preg_match($this->options['accept_file_types'], $file->name)) {\n $file->error = $this->get_error_message('accept_file_types');\n return false;\n }\n if ($uploaded_file && is_uploaded_file($uploaded_file)) {\n $file_size = $this->get_file_size($uploaded_file);\n } else {\n $file_size = $content_length;\n }\n if (\n $this->options['max_file_size'] && (\n $file_size > $this->options['max_file_size'] ||\n $file->size > $this->options['max_file_size'])\n ) {\n $file->error = $this->get_error_message('max_file_size');\n return false;\n }\n if (\n $this->options['min_file_size'] &&\n $file_size < $this->options['min_file_size']\n ) {\n $file->error = $this->get_error_message('min_file_size');\n return false;\n }\n if (\n is_int($this->options['max_number_of_files']) &&\n ($this->count_file_objects() >= $this->options['max_number_of_files']) &&\n // Ignore additional chunks of existing files:\n !is_file($this->get_upload_path($file->name))\n ) {\n $file->error = $this->get_error_message('max_number_of_files');\n return false;\n }\n if (!$content_range && $this->has_image_file_extension($file->name)) {\n return $this->validate_image_file($uploaded_file, $file, $error, $index);\n }\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function init()\n {\n /*\n * Globals are DEPRECATED as of version 1.5.0.1\n * Use the Context object to access objects instead.\n * Example: $this->context->cart\n */\n global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;\n\n if (self::$initialized) {\n return;\n }\n\n self::$initialized = true;\n\n parent::init();\n\n // enable Symfony error handler if debug mode enabled\n $this->initDebugguer();\n\n // If current URL use SSL, set it true (used a lot for module redirect)\n if (Tools::usingSecureMode()) {\n $useSSL = true;\n }\n\n // For compatibility with globals, DEPRECATED as of version 1.5.0.1\n $css_files = $this->css_files;\n $js_files = $this->js_files;\n\n $this->sslRedirection();\n\n if ($this->ajax) {\n $this->display_header = false;\n $this->display_footer = false;\n }\n\n // If account created with the 2 steps register process, remove 'account_created' from cookie\n if (isset($this->context->cookie->account_created)) {\n unset($this->context->cookie->account_created);\n }\n\n ob_start();\n\n // Init cookie language\n // @TODO This method must be moved into switchLanguage\n Tools::setCookieLanguage($this->context->cookie);\n\n $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://';\n $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false;\n $protocol_content = ($useSSL) ? 'https://' : 'http://';\n $link = new Link($protocol_link, $protocol_content);\n $this->context->link = $link;\n\n if ($id_cart = (int) $this->recoverCart()) {\n $this->context->cookie->id_cart = (int) $id_cart;\n }\n\n if ($this->auth && !$this->context->customer->isLogged()) {\n Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));\n }\n\n /* Theme is missing */\n if (!is_dir(_PS_THEME_DIR_)) {\n throw new PrestaShopException(\n $this->trans(\n 'Current theme is unavailable. Please check your theme\\'s directory name (\"%s\") and permissions.',\n array(basename(rtrim(_PS_THEME_DIR_, '/\\\\'))),\n 'Admin.Design.Notification'\n ));\n }\n\n if (Configuration::get('PS_GEOLOCATION_ENABLED')) {\n if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {\n $this->context->country = $new_default;\n }\n } elseif (Configuration::get('PS_DETECT_COUNTRY')) {\n $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency;\n $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;\n $has_address_type = false;\n\n if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {\n $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};\n }\n\n if ((!$has_currency || $has_country) && !$has_address_type) {\n $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ?\n (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry();\n\n $country = new Country($id_country, (int) $this->context->cookie->id_lang);\n\n if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {\n $this->context->country = $country;\n $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id;\n $this->context->cookie->iso_code_country = strtoupper($country->iso_code);\n }\n }\n }\n\n $currency = Tools::setCurrency($this->context->cookie);\n\n if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) {\n $this->context->customer->logout();\n\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n } elseif (isset($_GET['mylogout'])) {\n $this->context->customer->mylogout();\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n }\n\n /* Cart already exists */\n if ((int) $this->context->cookie->id_cart) {\n if (!isset($cart)) {\n $cart = new Cart($this->context->cookie->id_cart);\n }\n\n if (Validate::isLoadedObject($cart) && $cart->OrderExists()) {\n PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);\n $this->context->cookie->check_cgv = false;\n } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED'))\n && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))\n && $cart->nbProducts()\n && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1\n && !FrontController::isInWhitelistForGeolocation()\n && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))\n ) {\n /* Delete product of cart, if user can't make an order from his country */\n PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart);\n } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {\n // update cart values\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n }\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $currency->id;\n $cart->update();\n }\n /* Select an address if not set */\n if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||\n !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {\n $to_update = false;\n if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {\n $to_update = true;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {\n $to_update = true;\n $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if ($to_update) {\n $cart->update();\n }\n }\n }\n\n if (!isset($cart) || !$cart->id) {\n $cart = new Cart();\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $this->context->cookie->id_currency;\n $cart->id_guest = (int) $this->context->cookie->id_guest;\n $cart->id_shop_group = (int) $this->context->shop->id_shop_group;\n $cart->id_shop = $this->context->shop->id;\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n $cart->id_address_invoice = (int) $cart->id_address_delivery;\n } else {\n $cart->id_address_delivery = 0;\n $cart->id_address_invoice = 0;\n }\n\n // Needed if the merchant want to give a free product to every visitors\n $this->context->cart = $cart;\n CartRule::autoAddToCart($this->context);\n } else {\n $this->context->cart = $cart;\n }\n\n $this->context->cart->checkAndUpdateAddresses();\n\n $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));\n\n // Automatically redirect to the canonical URL if needed\n if (!empty($this->php_self) && !Tools::getValue('ajax')) {\n $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));\n }\n\n Product::initPricesComputation();\n\n $display_tax_label = $this->context->country->display_tax_label;\n if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {\n $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});\n $country = new Country((int) $infos['id_country']);\n $this->context->country = $country;\n if (Validate::isLoadedObject($country)) {\n $display_tax_label = $country->display_tax_label;\n }\n }\n\n $languages = Language::getLanguages(true, $this->context->shop->id);\n $meta_language = array();\n foreach ($languages as $lang) {\n $meta_language[] = $lang['iso_code'];\n }\n\n /*\n * These shortcuts are DEPRECATED as of version 1.5.0.1\n * Use the Context to access objects instead.\n * Example: $this->context->cart\n */\n self::$cookie = $this->context->cookie;\n self::$cart = $cart;\n self::$smarty = $this->context->smarty;\n self::$link = $link;\n $defaultCountry = $this->context->country;\n\n $this->displayMaintenancePage();\n\n if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) {\n $this->displayRestrictedCountryPage();\n }\n\n $this->iso = $iso;\n $this->context->cart = $cart;\n $this->context->currency = $currency;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function update(Query $query)\n {\n $options = $query->getOptions();\n\n if (isset($options['cache']) && is_string($options['cache']['key'])) {\n $key = $options['cache']['key'];\n }\n\n $pk = $query->getPk($options);\n $data = $options['data'];\n\n if (empty($options['where'])) {\n // \u5982\u679c\u5b58\u5728\u4e3b\u952e\u6570\u636e \u5219\u81ea\u52a8\u4f5c\u4e3a\u66f4\u65b0\u6761\u4ef6\n if (is_string($pk) && isset($data[$pk])) {\n $where[$pk] = [$pk, '=', $data[$pk]];\n if (!isset($key)) {\n $key = $this->getCacheKey($query, $data[$pk]);\n }\n unset($data[$pk]);\n } elseif (is_array($pk)) {\n // \u589e\u52a0\u590d\u5408\u4e3b\u952e\u652f\u6301\n foreach ($pk as $field) {\n if (isset($data[$field])) {\n $where[$field] = [$field, '=', $data[$field]];\n } else {\n // \u5982\u679c\u7f3a\u5c11\u590d\u5408\u4e3b\u952e\u6570\u636e\u5219\u4e0d\u6267\u884c\n throw new Exception('miss complex primary data');\n }\n unset($data[$field]);\n }\n }\n\n if (!isset($where)) {\n // \u5982\u679c\u6ca1\u6709\u4efb\u4f55\u66f4\u65b0\u6761\u4ef6\u5219\u4e0d\u6267\u884c\n throw new Exception('miss update condition');\n } else {\n $options['where']['AND'] = $where;\n $query->setOption('where', ['AND' => $where]);\n }\n } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'])) {\n foreach ($options['where']['AND'] as $val) {\n if (is_array($val) && $val[0] == $pk) {\n $key = $this->getCacheKey($query, $val);\n }\n }\n }\n\n // \u66f4\u65b0\u6570\u636e\n $query->setOption('data', $data);\n\n // \u751f\u6210UPDATE SQL\u8bed\u53e5\n $sql = $this->builder->update($query);\n $bind = $query->getBind();\n\n if (!empty($options['fetch_sql'])) {\n // \u83b7\u53d6\u5b9e\u9645\u6267\u884c\u7684SQL\u8bed\u53e5\n return $this->getRealSql($sql, $bind);\n }\n\n // \u68c0\u6d4b\u7f13\u5b58\n $cache = Container::get('cache');\n\n if (isset($key) && $cache->get($key)) {\n // \u5220\u9664\u7f13\u5b58\n $cache->rm($key);\n } elseif (!empty($options['cache']['tag'])) {\n $cache->clear($options['cache']['tag']);\n }\n\n // \u6267\u884c\u64cd\u4f5c\n $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query);\n\n if ($result) {\n if (is_string($pk) && isset($where[$pk])) {\n $data[$pk] = $where[$pk];\n } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {\n list($a, $val) = explode('|', $key);\n $data[$pk] = $val;\n }\n\n $query->setOption('data', $data);\n $query->trigger('after_update');\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false)\n {\n if (null !== $s && !\\is_scalar($s) && !(\\is_object($s) && method_exists($s, '__toString'))) {\n trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\\gettype($s).' given', \\E_USER_WARNING);\n\n return null;\n }\n\n if (!\\is_array($convmap) || (80000 > \\PHP_VERSION_ID && !$convmap)) {\n return false;\n }\n\n if (null !== $encoding && !\\is_scalar($encoding)) {\n trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\\gettype($s).' given', \\E_USER_WARNING);\n\n return null; // Instead of '' (cf. mb_decode_numericentity).\n }\n\n if (null !== $is_hex && !\\is_scalar($is_hex)) {\n trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\\gettype($s).' given', \\E_USER_WARNING);\n\n return null;\n }\n\n $s = (string) $s;\n if ('' === $s) {\n return '';\n }\n\n $encoding = self::getEncoding($encoding);\n\n if ('UTF-8' === $encoding) {\n $encoding = null;\n if (!preg_match('//u', $s)) {\n $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);\n }\n } else {\n $s = iconv($encoding, 'UTF-8//IGNORE', $s);\n }\n\n static $ulenMask = [\"\\xC0\" => 2, \"\\xD0\" => 2, \"\\xE0\" => 3, \"\\xF0\" => 4];\n\n $cnt = floor(\\count($convmap) / 4) * 4;\n $i = 0;\n $len = \\strlen($s);\n $result = '';\n\n while ($i < $len) {\n $ulen = $s[$i] < \"\\x80\" ? 1 : $ulenMask[$s[$i] & \"\\xF0\"];\n $uchr = substr($s, $i, $ulen);\n $i += $ulen;\n $c = self::mb_ord($uchr);\n\n for ($j = 0; $j < $cnt; $j += 4) {\n if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) {\n $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3];\n $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';';\n continue 2;\n }\n }\n $result .= $uchr;\n }\n\n if (null === $encoding) {\n return $result;\n }\n\n return iconv('UTF-8', $encoding.'//IGNORE', $result);\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, array $params = []): void\n {\n if (!$omitMandatoryCheck) {\n if (is_array($data)) {\n $blockDefinitions = $this->getFieldDefinitions();\n\n $validationExceptions = [];\n\n $idx = -1;\n foreach ($data as $item) {\n $idx++;\n if (!is_array($item)) {\n continue;\n }\n\n foreach ($blockDefinitions as $fd) {\n try {\n $blockElement = $item[$fd->getName()] ?? null;\n if (!$blockElement) {\n if ($fd->getMandatory()) {\n throw new Element\\ValidationException('Block element empty [ ' . $fd->getName() . ' ]');\n } else {\n continue;\n }\n }\n\n $data = $blockElement->getData();\n\n if ($data instanceof DataObject\\Localizedfield && $fd instanceof Localizedfields) {\n foreach ($data->getInternalData() as $language => $fields) {\n foreach ($fields as $fieldName => $values) {\n $lfd = $fd->getFieldDefinition($fieldName);\n if ($lfd instanceof ManyToManyRelation || $lfd instanceof ManyToManyObjectRelation) {\n if (!method_exists($lfd, 'getAllowMultipleAssignments') || !$lfd->getAllowMultipleAssignments()) {\n $lfd->performMultipleAssignmentCheck($values);\n }\n }\n }\n }\n } elseif ($fd instanceof ManyToManyRelation || $fd instanceof ManyToManyObjectRelation) {\n $fd->performMultipleAssignmentCheck($data);\n }\n\n if ($fd instanceof Link) {\n $params['resetInvalidFields'] = true;\n }\n $fd->checkValidity($data, false, $params);\n } catch (Model\\Element\\ValidationException $ve) {\n $ve->addContext($this->getName() . '-' . $idx);\n $validationExceptions[] = $ve;\n }\n }\n }\n\n if ($validationExceptions) {\n $errors = [];\n /** @var Element\\ValidationException $e */\n foreach ($validationExceptions as $e) {\n $errors[] = $e->getAggregatedMessage();\n }\n $message = implode(' / ', $errors);\n\n throw new Model\\Element\\ValidationException($message);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function parseEvent($calendar, $userHref, $oldCalendar = null)\n {\n if ($oldCalendar) {\n if (is_string($oldCalendar)) {\n $oldCalendar = Reader::read($oldCalendar);\n }\n if (!isset($oldCalendar->VEVENT)) {\n // We only support events at the moment\n return [];\n }\n\n $oldEventInfo = $this->parseEventInfo($oldCalendar);\n } else {\n $oldEventInfo = [\n 'organizer' => null,\n 'significantChangeHash' => '',\n 'attendees' => [],\n ];\n }\n\n $userHref = (array) $userHref;\n\n if (!is_null($calendar)) {\n if (is_string($calendar)) {\n $calendar = Reader::read($calendar);\n }\n if (!isset($calendar->VEVENT)) {\n // We only support events at the moment\n return [];\n }\n $eventInfo = $this->parseEventInfo($calendar);\n if (!$eventInfo['attendees'] && !$oldEventInfo['attendees']) {\n // If there were no attendees on either side of the equation,\n // we don't need to do anything.\n return [];\n }\n if (!$eventInfo['organizer'] && !$oldEventInfo['organizer']) {\n // There was no organizer before or after the change.\n return [];\n }\n\n $baseCalendar = $calendar;\n\n // If the new object didn't have an organizer, the organizer\n // changed the object from a scheduling object to a non-scheduling\n // object. We just copy the info from the old object.\n if (!$eventInfo['organizer'] && $oldEventInfo['organizer']) {\n $eventInfo['organizer'] = $oldEventInfo['organizer'];\n $eventInfo['organizerName'] = $oldEventInfo['organizerName'];\n }\n } else {\n // The calendar object got deleted, we need to process this as a\n // cancellation / decline.\n if (!$oldCalendar) {\n // No old and no new calendar, there's no thing to do.\n return [];\n }\n\n $eventInfo = $oldEventInfo;\n\n if (in_array($eventInfo['organizer'], $userHref)) {\n // This is an organizer deleting the event.\n $eventInfo['attendees'] = [];\n // Increasing the sequence, but only if the organizer deleted\n // the event.\n ++$eventInfo['sequence'];\n } else {\n // This is an attendee deleting the event.\n foreach ($eventInfo['attendees'] as $key => $attendee) {\n if (in_array($attendee['href'], $userHref)) {\n $eventInfo['attendees'][$key]['instances'] = ['master' => ['id' => 'master', 'partstat' => 'DECLINED'],\n ];\n }\n }\n }\n $baseCalendar = $oldCalendar;\n }\n\n if (in_array($eventInfo['organizer'], $userHref)) {\n return $this->parseEventForOrganizer($baseCalendar, $eventInfo, $oldEventInfo);\n } elseif ($oldCalendar) {\n // We need to figure out if the user is an attendee, but we're only\n // doing so if there's an oldCalendar, because we only want to\n // process updates, not creation of new events.\n foreach ($eventInfo['attendees'] as $attendee) {\n if (in_array($attendee['href'], $userHref)) {\n return $this->parseEventForAttendee($baseCalendar, $eventInfo, $oldEventInfo, $attendee['href']);\n }\n }\n }\n\n return [];\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getComponentReference(string $name, string $controller): ?array\n {\n $components = self::getComponentSchemas($this->api_version);\n // Try matching by name and controller first\n $match = null;\n $is_ref_array = str_ends_with($name, '[]');\n if ($is_ref_array) {\n $name = substr($name, 0, -2);\n }\n if ($name === '{itemtype}') {\n // Placeholder that will be replaced after route paths are expanded\n $match = $name;\n }\n if ($match === null) {\n foreach ($components as $component_name => $component) {\n if ($component['x-controller'] === $controller && $component['x-schemaname'] === $name) {\n $match = $component_name;\n break;\n }\n }\n }\n // If no match was found, try matching by name only\n if ($match === null) {\n foreach ($components as $component_name => $component) {\n if ($component['x-schemaname'] === $name) {\n $match = $component_name;\n break;\n }\n }\n }\n if ($match === null) {\n return null;\n }\n if ($is_ref_array) {\n return [\n 'type' => 'array',\n 'items' => [\n '$ref' => '#/components/schemas/' . $match,\n ],\n ];\n }\n return [\n '$ref' => '#/components/schemas/' . $match,\n ];\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function stem_plot($data,$options=array()) {\n\t\n\tif (!is_array($data)) {\n\t\techo 'stem_plot expects an array of numerical data';\n\t\treturn 0;\n } else {\n\t\t\n\t\t$data = array_map(function($v){return round($v,0);}, $data) ;\n\t}\n\t\n\tif (isset($options['split'])){\n\t\t$split = $options['split'];\n\t} else {\n\t\t$split = false;\n\t}\n\t\n\tif(isset($options['space']) && $options['space']==false){\n\t\t$spc = \"\";\n\t} else {\n\t\t$spc = \" \";\n\t}\n\n\tif(isset($options['customkey'])) {\n\t\t$key = \"<caption style='caption-side:bottom; text-align: center;'>{$options['customkey']}</caption>\";\n\t} elseif(isset($options['key']) && $options['key']==false){\n\t\t$key = \"\";\n\t} else {\n\t\t$keyval = randfrom($data);\n\t\tif($keyval < 0){\n\t\t\tif(intdiv($keyval,10) == 0){\n\t\t\t\t$keytmp = \"Key: -0|\".(abs($keyval%10)).\" = \".$keyval;\t\n\t\t\t} else {\n\t\t\t\t$keytmp = \"Key: \".(intdiv($keyval,10)).\"|\".(abs($keyval%10)).\" = \".$keyval;\t\n\t\t\t}\n\t\t} else {\n\t\t\t$keytmp = \"Key: \".(intdiv($keyval,10)).\"|\".(abs($keyval%10)).\" = \".$keyval;\t\n\t\t}\n\t\t$key = \"<caption style='caption-side:bottom; text-align: center;'>$keytmp</caption>\";\n\t}\n\n\tif(isset($options[\"stemlabel\"])){\n\t\t$stemlabel = $options[\"stemlabel\"];\n\t} else {\n\t\t$stemlabel = \"Stem\";\n\t}\n\n\tif(isset($options[\"leaflabel\"])){\n\t\t$leaflabel = $options['leaflabel'];\n\t} else {\n\t\t$leaflabel = \"Leaf\";\n\t}\n\n\tsort($data, SORT_NUMERIC);\n\n\t$display = \"<table style='align: center; border:0;'>$key\";\n\t$display .= \"<thead><tr><th></th><th style='border-bottom: 1px solid;'>$stemlabel</th><th style='border-bottom: 1px solid; text-align: left;'>$leaflabel</th></tr></thead><tbody>\";\n\n\t$data_neg = array();\n\t$data_pos = array();\n\n\tfor($i = 0; $i < count($data); $i++){\n\t\tif($data[$i] < 0){\n\t\t\t$data_neg[] = $data[$i];\n\t\t} else {\n\t\t\t$data_pos[] = $data[$i];\n\t\t}\n\t}\n\t\n\tif(count($data_neg) > 0){\n\t\t$size = count($data_neg);\n\t\t$min = $data_neg[0];\n\t\t$max = max($data_neg);\n\t\t$start = intdiv($min,10); \n\t\t$finish = intdiv($max,10)+1;\n\t\t$chk = 0;\n\t\n\t\tfor($stem=$start; $stem < $finish; $stem++){\n\t\t\t$leaf = \"\";\n\n\t\t\tif($split == false){\n\t\t\t\tif($stem == 0){\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>-0</td>\";\n\t\t\t\t} else {\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\t}\n\t\t\t\n\t\t\t\twhile($chk != $size && intdiv($data_neg[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_neg[$chk]%10);\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tif($stem == 0){\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>-0</td>\";\n\t\t\t\t} else {\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\t}\n\n\t\t\t\twhile($chk != $size && intdiv($data_neg[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_neg[$chk]%10);\n\t\t\t\t\tif($tmp < 5){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\t\t\t\t\t\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\n\t\t\t\t$display .= \"<td>$leaf</td></tr>\";\n\t\t\t\t$leaf = \"\";\n\n\t\t\t\tif($stem == 0){\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>-0</td>\";\n\t\t\t\t} else {\n\t\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\t}\n\n\t\t\t\twhile($chk != $size && intdiv($data_neg[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_neg[$chk]%10);\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\t\t\t\t\t\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$display .= \"<td>$leaf</td></tr>\";\n\t\t}\n\t}\n\t\n\tif(count($data_pos)>0){\n\t\t$min = $data_pos[0];\n\t\t$max = max($data_pos);\n\t\t$size = count($data_pos);\n\t\t$start = intdiv($min,10); \n\t\t$finish = intdiv($max,10)+1;\n\t\t$chk = 0;\n\n\t\tif($split == false){\n\t\t\tfor($stem=$start; $stem < $finish; $stem++){\n\t\t\t\t$leaf = \"\";\t\t\n\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\n\t\t\t\twhile($chk != $size && intdiv($data_pos[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_pos[$chk]%10);\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\t\t\t\t$display .= \"<td>$leaf</td></tr>\";\n\t\t\t}\n\t\t} else {\n\t\t\tfor($stem=$start; $stem < $finish; $stem++){\n\t\t\t\t$leaf = \"\";\t\t\n\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\n\t\t\t\twhile($chk != $size && intdiv($data_pos[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_pos[$chk]%10);\n\t\t\t\t\tif($tmp > 4){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\t\t\t\t$display .= \"<td>$leaf</td></tr>\";\n\t\t\t\t$display .= \"<tr><td></td><td style='text-align: right; border-right: 1px solid;'>$stem</td>\";\n\t\t\t\t$leaf = \"\";\n\n\t\t\t\twhile($chk != $size && intdiv($data_pos[$chk],10) == $stem){\n\t\t\t\t\t$tmp = abs($data_pos[$chk]%10);\n\t\t\t\t\t$leaf .= $spc.\"$tmp\";\n\t\t\t\t\t$chk++;\n\t\t\t\t}\n\t\t\t\t$display .= \"<td>$leaf</td></tr>\";\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t$display .= \"<tr><td></td><td></td><td></td></tr></tbody></table>\";\n\treturn $display;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function grapheme_extract($s, $size, $type = \\GRAPHEME_EXTR_COUNT, $start = 0, &$next = 0)\n {\n if (0 > $start) {\n $start = \\strlen($s) + $start;\n }\n\n if (!\\is_scalar($s)) {\n $hasError = false;\n set_error_handler(function () use (&$hasError) { $hasError = true; });\n $next = substr($s, $start);\n restore_error_handler();\n if ($hasError) {\n substr($s, $start);\n $s = '';\n } else {\n $s = $next;\n }\n } else {\n $s = substr($s, $start);\n }\n $size = (int) $size;\n $type = (int) $type;\n $start = (int) $start;\n\n if (\\GRAPHEME_EXTR_COUNT !== $type && \\GRAPHEME_EXTR_MAXBYTES !== $type && \\GRAPHEME_EXTR_MAXCHARS !== $type) {\n if (80000 > \\PHP_VERSION_ID) {\n return false;\n }\n\n throw new \\ValueError('grapheme_extract(): Argument #3 ($type) must be one of GRAPHEME_EXTR_COUNT, GRAPHEME_EXTR_MAXBYTES, or GRAPHEME_EXTR_MAXCHARS');\n }\n\n if (!isset($s[0]) || 0 > $size || 0 > $start) {\n return false;\n }\n if (0 === $size) {\n return '';\n }\n\n $next = $start;\n\n $s = preg_split('/('.SYMFONY_GRAPHEME_CLUSTER_RX.')/u', \"\\r\\n\".$s, $size + 1, \\PREG_SPLIT_NO_EMPTY | \\PREG_SPLIT_DELIM_CAPTURE);\n\n if (!isset($s[1])) {\n return false;\n }\n\n $i = 1;\n $ret = '';\n\n do {\n if (\\GRAPHEME_EXTR_COUNT === $type) {\n --$size;\n } elseif (\\GRAPHEME_EXTR_MAXBYTES === $type) {\n $size -= \\strlen($s[$i]);\n } else {\n $size -= iconv_strlen($s[$i], 'UTF-8//IGNORE');\n }\n\n if ($size >= 0) {\n $ret .= $s[$i];\n }\n } while (isset($s[++$i]) && $size > 0);\n\n $next += \\strlen($ret);\n\n return $ret;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function chem_makeioniccompound($cation,$anion) {\n\tif (!is_array($cation)) {\n\t\tglobal $chem_cations;\n\t\t$found = false;\n\t\tforeach($chem_cations as $c) {\n\t\t\tif ($c[0]==$cation) {\n\t\t\t\t$cation = $c;\n\t\t\t\t$found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!$found) {\n\t\t\techo \"Cation not found.\";\n\t\t}\n\t}\n\tif (!is_array($anion)) {\n\t\tglobal $chem_anions;\n\t\t$found = false;\n\t\tforeach($chem_anions as $c) {\n\t\t\tif ($c[0]==$anion) {\n\t\t\t\t$anion = $c;\n\t\t\t\t$found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!$found) {\n\t\t\techo \"Anion not found.\";\n\t\t}\n\t}\n if (!isset($cation) || !isset($anion)) {\n return false;\n }\n\t$lcm = lcm($cation[1],$anion[1]);\n\t$catsub = $lcm/$cation[1];\n\tif ($catsub==1) {\n\t\t$formula = $cation[0];\n\t} else {\n\t\tif (strpos($cation[0],' ')!==false) {\n\t\t\t$formula = '('.$cation[0].')';\n\t\t\t$formula .= '_'.$catsub;\n\t\t} else if (strpos($cation[0],'_')!==false) {\n\t\t\t//this is Hg_2 only\n\t\t\t$pts = explode('_',$cation[0]);\n\t\t\t$formula = $pts[0].'_'.($pts[1]*$catsub);\n\t\t} else {\n\t\t\t$formula = $cation[0];\n\t\t\t$formula .= '_'.$catsub;\n\t\t}\n\n\t}\n\t$ansub = $lcm/$anion[1];\n\tif ($ansub==1) {\n\t\t$formula .= ' '.$anion[0];\n\t} else {\n\t\tif (strpos($anion[0],' ')!==false) {\n\t\t\t$formula .= ' ('.$anion[0].')';\n\t\t\t$formula .= '_'.$ansub;\n\t\t} else if (strpos($anion[0],'_')!==false) {\n\t\t\t$pts = explode('_',$anion[0]);\n\t\t\t$formula .= ' '.$pts[0].'_'.($ansub*$pts[1]);\n\t\t} else {\n\t\t\t$formula .= ' '.$anion[0];\n\t\t\t$formula .= '_'.$ansub;\n\t\t}\n\n\t}\n\t$name = $cation[2].' '.$anion[2];\n\treturn array($formula,$name);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private static function findRecordIds($imp_session, $params){\n\n $progress_session_id = @$params['session'];\n\n //result array\n $imp_session['validation'] = array(\n \"count_update\"=>0,\n \"count_insert\"=>0,\n \"count_update_rows\"=>0,\n \"count_insert_rows\"=>0,\n \"count_ignore_rows\"=>0, //all key fields are empty - ignore\n \"count_error\"=>0, //NOT USED total number of errors (may be several per row)\n \"error\"=>array(),\n \"recs_insert\"=>array(), //full record\n \"recs_update\"=>array() );\n\n $import_table = $imp_session['import_table'];\n $multivalue_field_name = @$params['multifield'];//name of multivalue field - among mapped fields ONLY ONE can be multivalued\n\n if( $multivalue_field_name!=null && $multivalue_field_name>=0 ) {$multivalue_field_name = 'field_'.$multivalue_field_name;}\n\n $cnt_update_rows = 0;\n $cnt_insert_rows = 0;\n\n //disambiguation resolution\n $disamb_resolv = @$params['disamb_resolv'];//record id => $keyvalue\n if($disamb_resolv!=null && !is_array($disamb_resolv)){\n $disamb_resolv = json_decode($disamb_resolv, true);\n }\n if(!$disamb_resolv){ //old way\n $disamb_ids = @$params['disamb_id'];//record ids\n $disamb_keys = @$params['disamb_key'];//key values\n $disamb_resolv = array();\n if($disamb_keys){\n foreach($disamb_keys as $idx => $keyvalue){\n array_push($disamb_resolv, array('recid'=>$disamb_ids[$idx], 'key'=>str_replace(\"\\'\", \"'\", $keyvalue) ));\n //$disamb_resolv[$disamb_ids[$idx]] = str_replace(\"\\'\", \"'\", $keyvalue);//rec_id => keyvalue\n }\n }\n }\n\n //get rectype to import\n $recordType = @$params['sa_rectype'];\n $currentSeqIndex = @$params['seq_index'];\n $ignore_rectype = @$params['ignore_rectype'] ? $params['ignore_rectype'] : 0;\n\n $detDefs = dbs_GetDetailTypes(self::$system, 'all', 1 );\n\n $detDefs = $detDefs['typedefs'];\n $idx_dt_type = $detDefs['fieldNamesToIndex']['dty_Type'];\n\n $mapped_fields = array();\n $mapping = @$params['mapping'];\n $sel_fields = array();\n $mapping_fieldname_to_index = array();//field_x => x for quick access\n\n //get arrays of field_XXX => field type, field_XXX=>index in mapping\n if(is_array($mapping))\n {\n foreach ($mapping as $index => $field_type) {\n if($field_type==\"url\" || $field_type==\"id\" || @$detDefs[$field_type]){\n $field_name = \"field_\".$index;\n $mapping_fieldname_to_index[$field_name] = $index;\n\n $mapped_fields[$field_name] = $field_type;\n $sel_fields[] = $field_name;\n }\n }\n }\n\n if(empty($mapped_fields)){\n self::$system->addError(HEURIST_ACTION_BLOCKED, 'Import CSV. Matching step failed. No mapping defined');\n return false;\n }\n\n //keep mapping field_XXX => dty_ID\n $imp_session['validation']['mapped_fields'] = $mapped_fields;\n\n //already founded IDs\n $pairs = array();//to avoid search $keyvalue=>new_recID\n $mapping_keys_values = array();//new_recID => array(field idx=>value,.... - for multivalue keyvalues\n\n $records = array();\n $disambiguation = array();\n $disambiguation_lines = array();\n $tmp_idx_insert = array();//to keep indexes\n $tmp_idx_update = array();//to keep indexes\n\n $mysqli = self::$mysqli;\n\n //--------------------------------------------------------------------------\n //loop all records in import table and detect what is for insert and what for update\n\n $tot_count = $imp_session['reccount'];\n $cnt = 0;\n $step = ceil($tot_count/100);\n if($step>100) {$step = 100;}\n elseif($step<10) {$step=10;}\n\n $select_query = self::composeQuery($sel_fields, $import_table);\n\n $res = $mysqli->query($select_query);\n if($res){\n mysql__update_progress(null, $progress_session_id, true, '0,'.$tot_count);\n\n $ind = -1;\n while ($row = $res->fetch_assoc()){\n\n $imp_id = $row['imp_id'];\n\n $values_tobind = array();\n $values_tobind[] = '';//first element for bind_param must be a string with field types\n $keys_values = array();//field index => keyvalue from csv\n $keys_values_all = array();//all field values including empty\n\n //BEGIN statement constructor\n $select_query_match_from = array(\"Records\");\n $select_query_match_where = array();\n if($ignore_rectype != 1){\n array_push($select_query_match_where, \"rec_RecTypeID=\".$recordType);\n }\n\n $multivalue_selquery_from = null;\n $multivalue_selquery_where = null;\n $multivalue_field_value = null;\n\n $index = 0;\n foreach ($mapped_fields as $fieldname => $field_type) {\n\n\n if($row[$fieldname]==null || trim($row[$fieldname])=='') {\n\n //$keys_values_all[] = '';\n //continue; //ignore empty values\n\n if($field_type>0){\n array_push($select_query_match_where, 'NOT exists (select dtl_ID from recDetails '\n .' WHERE dtl_DetailTypeID='.$field_type\n .' AND rec_ID=dtl_RecID)');\n\n //$multivalue_selquery_from = '';\n }\n\n\n }else{\n $fieldvalue = super_trim($row[$fieldname]);\n\n\n if($field_type==\"url\" || $field_type==\"id\"){ // || $field_type==\"scratchpad\"){\n array_push($select_query_match_where, \"rec_\".$field_type.\"=?\");\n $values_tobind[] = $fieldvalue;\n $keys_values_all[] = $fieldvalue;\n }elseif(is_numeric($field_type)){\n\n $from = '';\n $where = \"d\".$index.\".dtl_DetailTypeID=\".$field_type.SQL_AND;\n $dt_type = $detDefs[$field_type]['commonFields'][$idx_dt_type];\n\n if( $dt_type == \"enum\" || $dt_type == \"relationtype\") {\n //if fieldname is numeric - compare it with dtl_Value directly\n $where = $where.\"( d\".$index.\".dtl_Value=t\".$index.\".trm_ID and \"\n .\" (? in (t\".$index.\".trm_Label, t\".$index.\".trm_Code)))\";\n\n $from = 'defTerms t'.$index.',';\n }else{\n $where = $where.\" (d\".$index.\".dtl_Value=?)\";\n }\n\n $where = 'rec_ID=d'.$index.'.dtl_RecID and '.$where;\n $from = $from.'recDetails d'.$index;\n\n // we may work with the only multivalue field for matching\n // otherwise it is not possible to detect proper combination\n if($multivalue_field_name==$fieldname){\n $multivalue_selquery_from = $from;\n $multivalue_selquery_where = $where;\n $multivalue_field_value = $fieldvalue;\n }else{\n array_push($select_query_match_where, $where);\n array_push($select_query_match_from, $from);\n $values_tobind[] = $fieldvalue;\n $keys_values_all[] = $fieldvalue;\n $values_tobind[0] = $values_tobind[0].'s';\n\n if(@$mapping_fieldname_to_index[$fieldname]>=0){\n $keys_values[$mapping_fieldname_to_index[$fieldname]] = $fieldvalue;\n }\n }\n\n }\n }\n $index++;\n }//for all fields in match array\n\n $cnt++;\n if($cnt % $step == 0){\n mysql__update_progress(null, $progress_session_id, true, $cnt.','.$tot_count);\n }\n\n if($index==0){//all matching fields in import table are empty - skip it\n $imp_session['validation']['count_ignore_rows']++;\n continue;\n }\n\n\n $is_update = false;\n $is_insert = false;\n\n $ids = array();\n $values = array('');\n //split multivalue field\n if($multivalue_field_name!=null && $multivalue_field_value!=null && $multivalue_field_name!=='' && $multivalue_field_value!==''){\n $values = self::getMultiValues($multivalue_field_value, $imp_session['csv_enclosure'], $imp_session['csv_mvsep']);\n if(isEmptyArray($values)){\n $values = array('');//at least one value\n }\n }\n\n //keyvalue = values from other field + value from multivalue\n foreach($values as $idx=>$value){ //from multivalue matching field\n\n $a_tobind = $values_tobind; //values for prepared query\n $a_from = $select_query_match_from;\n $a_where = $select_query_match_where;\n\n $a_keys = $keys_values_all;\n\n if($multivalue_field_name!=null){\n\n $row[$multivalue_field_name] = $value;\n\n if(@$mapping_fieldname_to_index[$multivalue_field_name]>=0){\n $keys_values[$mapping_fieldname_to_index[$multivalue_field_name]] = $value;\n }\n }\n\n if(super_trim($value)!=''){ //if multivalue field has values use $values_tobind\n $a_tobind[0] = $a_tobind[0].'s';\n $a_tobind[] = $value;\n $a_keys[] = $value;\n\n $a_from[] = $multivalue_selquery_from;\n $a_where[] = $multivalue_selquery_where;\n }\n\n //merge all values - to create unuque key for combination of values\n //$keyvalue = implode('\u25ab',$keys_values2);\n $keyvalue = implode('\u25ab', $a_keys);\n\n /*\n $fc = $a_tobind;\n array_shift($fc);//remove ssssss\n if($imp_session['csv_mvsep']=='none'){\n $keyvalue = implode('', $fc);\n }else{\n $keyvalue = implode($imp_session['csv_mvsep'], $fc);//csv_mvsep - separator\n }\n */\n\n if($keyvalue=='') {continue;}\n\n\n if(@$pairs[$keyvalue]){ //we already found record for this combination\n//disambiguation\n\n if(array_key_exists($keyvalue, $tmp_idx_insert)){\n $imp_session['validation']['recs_insert'][$tmp_idx_insert[$keyvalue]][0] .= (','.$imp_id);\n $is_insert = true;\n }elseif(array_key_exists($keyvalue, $tmp_idx_update)) {\n\n // make first field (id) - csv\n $imp_session['validation']['recs_update'][$tmp_idx_update[$keyvalue]][0] .= (','.$imp_id);\n\n $is_update = true;\n }\n array_push($ids, $pairs[$keyvalue]);\n\n }else{\n\n //query to search record ids\n $search_query = \"SELECT rec_ID, rec_Title \"\n .\" FROM \".implode(\",\",$a_from)\n .SQL_WHERE.implode(SQL_AND,$a_where);\n\n $search_stmt = $mysqli->prepare($search_query);\n //$search_stmt->bind_param('s', $field_value);\n $search_stmt->bind_result($rec_ID, $rec_Title);\n\n //assign parameters for search query\n //Call the $stmt->bind_param() method with atrguments (string $types, mixed &...$vars)\n call_user_func_array(array($search_stmt, 'bind_param'), referenceValues($a_tobind));\n $search_stmt->execute();\n $disamb = array();\n while ($search_stmt->fetch()) {\n //keep pair ID => key value\n $disamb[$rec_ID] = $rec_Title; //get value from binding\n }\n\n $search_stmt->close();\n\n if(count($disamb)>1){\n $resolved_recid = self::findDisambResolution($keyvalue, $disamb_resolv);\n }else{\n $resolved_recid = null;\n }\n\n if(empty($disamb) || $resolved_recid<0){ //nothing found - insert\n\n if($ignore_rectype == 1){ // never create new records when ignoring record type\n continue;\n }\n\n $new_id = $ind;\n $ind--;\n $rec = $row;\n $rec[0] = $imp_id;\n $tmp_idx_insert[$keyvalue] = count($imp_session['validation']['recs_insert']);//keep index in rec_insert\n array_push($imp_session['validation']['recs_insert'], $rec);//group_concat(imp_id), \".implode(\",\",$sel_query)\n $is_insert = true;\n\n }elseif(count($disamb)==1 || $resolved_recid!=null){\n //array_search($keyvalue, $disamb_resolv, true)!==false){ @$disamb_resolv[addslashes($keyvalue)]){\n //either found exact or disamiguation is resolved\n if($resolved_recid!=null){\n $rec_ID = $resolved_recid;\n }\n\n //find in rec_update\n\n $new_id = $rec_ID;\n $rec = $row;\n $rec[0] = $imp_id;\n\n //array_unshift($rec, $rec_ID);//add as first element\n //$tmp_idx_update[$keyvalue] = count($imp_session['validation']['recs_update']);//keep index in rec_update\n //array_push($imp_session['validation']['recs_update'], $rec);//rec_ID, group_concat(imp_id), \".implode(\",\",$sel_query)\n\n $tmp_idx_update[$keyvalue] = $rec_ID;\n if(@$imp_session['validation']['recs_update'][$rec_ID]){\n $imp_session['validation']['recs_update'][$rec_ID][0] .= (','.$imp_id);\n }else{\n $imp_session['validation']['recs_update'][$rec_ID] = $rec;\n }\n\n $is_update = true;\n }else{\n $new_id = 'Found:'.count($disamb);//Disambiguation!\n $disambiguation[$keyvalue] = $disamb;\n $disambiguation_lines[$keyvalue] = $imp_id;\n }\n $pairs[$keyvalue] = $new_id;\n\n $mapping_keys_values[$new_id] = $keys_values;\n\n array_push($ids, $new_id);\n\n }\n\n }//for multivalues\n\n if($imp_session['csv_mvsep']=='none'){\n $records[$imp_id] = !empty($ids)?$ids[0]:'';\n }else{\n $records[$imp_id] = implode($imp_session['csv_mvsep'], $ids);//IDS to be added to import table\n }\n\n\n if($is_update) {$cnt_update_rows++;}\n if($is_insert) {$cnt_insert_rows++;}\n if(!$is_update && !$is_insert && $ignore_rectype == 1) {$imp_session['validation']['count_ignore_rows']++;}\n\n }//while import table\n\n }\n else{\n self::$system->addError(HEURIST_DB_ERROR, 'Can not query import table '.$import_table, $mysqli->error);\n return false;\n }\n\n // result of work - counts of records to be inserted, updated\n $imp_session['validation']['count_update'] = count($imp_session['validation']['recs_update']);\n $imp_session['validation']['count_insert'] = count($imp_session['validation']['recs_insert']);\n $imp_session['validation']['count_update_rows'] = $cnt_update_rows;\n $imp_session['validation']['count_insert_rows'] = $cnt_insert_rows;\n $imp_session['validation']['disambiguation'] = $disambiguation;\n $imp_session['validation']['disambiguation_lines'] = $disambiguation_lines;\n $imp_session['validation']['pairs'] = $pairs; //keyvalues => record id - count number of unique values\n\n if($multivalue_field_name!=null){\n $imp_session['validation']['mapping_keys_values'] = $mapping_keys_values;\n }\n\n //MAIN RESULT - ids to be assigned to each record in import table\n $imp_session['validation']['records'] = $records; //imp_id(line#) => list of records ids\n\n return $imp_session;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function generateSheetData() {\n\t\t// PHPExcel object known?\n\t\tif (is_null($this->_phpExcel)) {\n\t\t\tthrow new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.');\n\t\t}\n\n\t\t// Ensure that Spans have been calculated?\n\t\tif (!$this->_spansAreCalculated) {\n\t\t\t$this->_calculateSpans();\n\t\t}\n\n\t\t// Fetch sheets\n\t\t$sheets = array();\n\t\tif (is_null($this->_sheetIndex)) {\n\t\t\t$sheets = $this->_phpExcel->getAllSheets();\n\t\t} else {\n\t\t\t$sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex);\n\t\t}\n\n\t\t// Construct HTML\n\t\t$html = '';\n\n\t\t// Loop all sheets\n\t\t$sheetId = 0;\n\t\tforeach ($sheets as $sheet) {\n\t\t\t// Write table header\n\t\t\t$html .= $this->_generateTableHeader($sheet);\n\n\t\t\t// Get worksheet dimension\n\t\t\t$dimension = explode(':', $sheet->calculateWorksheetDimension());\n\t\t\t$dimension[0] = PHPExcel_Cell::coordinateFromString($dimension[0]);\n\t\t\t$dimension[0][0] = PHPExcel_Cell::columnIndexFromString($dimension[0][0]) - 1;\n\t\t\t$dimension[1] = PHPExcel_Cell::coordinateFromString($dimension[1]);\n\t\t\t$dimension[1][0] = PHPExcel_Cell::columnIndexFromString($dimension[1][0]) - 1;\n\n\t\t\t// row min,max\n\t\t\t$rowMin = $dimension[0][1];\n\t\t\t$rowMax = $dimension[1][1];\n\n\t\t\t// calculate start of <tbody>, <thead>\n\t\t\t$tbodyStart = $rowMin;\n\t\t\t$theadStart = $theadEnd = 0; // default: no <thead>\tno </thead>\n\t\t\tif ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {\n\t\t\t\t$rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();\n\n\t\t\t\t// we can only support repeating rows that start at top row\n\t\t\t\tif ($rowsToRepeatAtTop[0] == 1) {\n\t\t\t\t\t$theadStart = $rowsToRepeatAtTop[0];\n\t\t\t\t\t$theadEnd = $rowsToRepeatAtTop[1];\n\t\t\t\t\t$tbodyStart = $rowsToRepeatAtTop[1] + 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Loop through cells\n\t\t\t$row = $rowMin-1;\n\t\t\twhile($row++ < $rowMax) {\n\t\t\t\t// <thead> ?\n\t\t\t\tif ($row == $theadStart) {\n\t\t\t\t\t$html .= '\t\t<thead>' . PHP_EOL;\n\t\t\t\t}\n\n\t\t\t\t// <tbody> ?\n\t\t\t\tif ($row == $tbodyStart) {\n\t\t\t\t\t$html .= '\t\t<tbody>' . PHP_EOL;\n\t\t\t\t}\n\n\t\t\t\t// Write row if there are HTML table cells in it\n\t\t\t\tif ( !isset($this->_isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row]) ) {\n\t\t\t\t\t// Start a new rowData\n\t\t\t\t\t$rowData = array();\n\t\t\t\t\t// Loop through columns\n\t\t\t\t\t$column = $dimension[0][0] - 1;\n\t\t\t\t\twhile($column++ < $dimension[1][0]) {\n\t\t\t\t\t\t// Cell exists?\n\t\t\t\t\t\tif ($sheet->cellExistsByColumnAndRow($column, $row)) {\n\t\t\t\t\t\t\t$rowData[$column] = $sheet->getCellByColumnAndRow($column, $row);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$rowData[$column] = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$html .= $this->_generateRow($sheet, $rowData, $row - 1);\n\t\t\t\t}\n\n\t\t\t\t// </thead> ?\n\t\t\t\tif ($row == $theadEnd) {\n\t\t\t\t\t$html .= '\t\t</thead>' . PHP_EOL;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$html .= $this->_extendRowsForChartsAndImages($sheet, $row);\n\n\t\t\t// Close table body.\n\t\t\t$html .= '\t\t</tbody>' . PHP_EOL;\n\n\t\t\t// Write table footer\n\t\t\t$html .= $this->_generateTableFooter();\n\n\t\t\t// Writing PDF?\n\t\t\tif ($this->_isPdf) {\n\t\t\t\tif (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) {\n\t\t\t\t\t$html .= '<div style=\"page-break-before:always\" />';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Next sheet\n\t\t\t++$sheetId;\n\t\t}\n\n\t\t// Return\n\t\treturn $html;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function checkCsvExport($testName, $input, $expectedFile, $userRole)\n {\n $aggUnit = $input['aggregation_unit'];\n $datasetType = $input['dataset_type'];\n $fullTestName = $testName . $datasetType . '-' . $aggUnit . '-' . $userRole;\n\n if (in_array($testName, self::$skip)) {\n throw new SkippedTestError($fullTestName . ' intentionally skipped');\n }\n\n list($csvdata, $curldata) = self::post('/controllers/user_interface.php', null, $input);\n if (!empty(self::$timingOutputDir)) {\n $time_data = $fullTestName . \",\" . $curldata['total_time'] . \",\" . $curldata['starttransfer_time'] . \"\\n\";\n $outputCSV = self::$timingOutputDir . \"timings.csv\";\n file_put_contents($outputCSV, $time_data, FILE_APPEND | LOCK_EX);\n }\n\n // This allows the \"failed\" tests of the public user to pass. Need a\n // more robust way for public user not having access to pass.\n if (gettype($csvdata) === \"array\") {\n if ($csvdata['message'] == 'Session Expired') {\n throw new IncompleteTestError($fullTestName . ' user session expired...');\n }\n $csvdata = json_encode($csvdata, JSON_PRETTY_PRINT) . \"\\n\";\n }\n\n $csvdata = preg_replace(self::$replaceRegex, self::$replacements, $csvdata);\n\n if (getenv('REG_TEST_FORCE_GENERATION') !== '1') {\n $expected = file_get_contents($expectedFile);\n $expected = preg_replace(self::$replaceRegex, self::$replacements, $expected);\n\n if ($expected === $csvdata) {\n return true;\n } else {\n try {\n $decodedCsv = json_decode($csvdata);\n if ($decodedCsv !== false && !is_null($decodedCsv)) {\n $actualJson = json_encode($decodedCsv, JSON_PRETTY_PRINT);\n $expectedJson = json_encode(json_decode($expected), JSON_PRETTY_PRINT);\n\n if (trim($expectedJson) === trim($actualJson)) {\n return true;\n }\n }\n } catch (\\Exception $e) {\n // go ahead and ignore as this is just for json data and will fail w/ actual csv data.\n }\n }\n\n $this->messages[] = sprintf(\n \"%s:\\nRaw Expected:\\n%s\\n\\nRaw Actual:\\n%s\\n\",\n $fullTestName,\n $expected,\n $csvdata\n );\n\n $failures = $this->compareCsvData($expected, $csvdata);\n\n if (empty($failures)) {\n // This happens because of floating point math.\n $this->messages[] = \"$fullTestName IS ONLY ==\";\n return true;\n }\n\n throw new ExpectationFailedException(\n sprintf(\n \"%d assertions failed:\\n\\t%s\",\n count($failures),\n implode(\"\\n\\t\", $failures)\n )\n );\n }\n\n // Artifact generation mode below (REG_TEST_FORCE_GENERATION=1).\n return $this->generateArtifact(\n $testName,\n $fullTestName,\n $csvdata,\n (\n \"$datasetType-$aggUnit-\"\n . ($userRole == 'public' ? 'reference' : $userRole)\n . '.csv'\n ),\n \"$datasetType-$aggUnit-reference.csv\"\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "private function addReadRestrictCriteria(array &$criteria): void\n {\n $read_right_criteria = $this->schema['x-rights-conditions']['read'] ?? [];\n if (is_callable($read_right_criteria)) {\n $read_right_criteria = $read_right_criteria();\n }\n if (!empty($read_right_criteria)) {\n $join_types = ['LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN'];\n foreach ($join_types as $join_type) {\n if (isset($read_right_criteria[$join_type])) {\n foreach ($read_right_criteria[$join_type] as $join_table => $join_clauses) {\n if (!isset($criteria[$join_type][$join_table])) {\n $criteria[$join_type][$join_table] = $join_clauses;\n }\n }\n }\n }\n if (isset($read_right_criteria['WHERE'])) {\n if (!isset($criteria['WHERE'])) {\n $criteria['WHERE'] = [];\n }\n $criteria['WHERE'][] = $read_right_criteria['WHERE'];\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function spacecurve($func,$tmin,$tmax) {\n\tglobal $imasroot, $staticroot;\n\tif ($GLOBALS['inquestiondisplay'] == false) {return '';}\n\tif (func_num_args()>3) {\n\t\t$disc = func_get_arg(3);\n\t\tif (!is_numeric($disc)) {\n\t\t\t$disc = 50;\n\t\t}\n\t} else {\n\t\t$disc = 50;\n\t}\n\tif (func_num_args()>5) {\n\t\t$width = func_get_arg(4);\n\t\t$height = func_get_arg(5);\n\t} else {\n\t\t$width = 300;\n\t\t$height = 300;\n\t}\n\tif (func_num_args()>6) {\n\t\t$axes = func_get_arg(6);\n\t} else {\n\t\t$axes = 1;\n\t}\n\tif (func_num_args()>12) {\n\t\t$bounds = array_slice(func_get_args(),7,6);\n\t}\n\tif (func_num_args()>13) {\n\t\t$alt = func_get_arg(13);\n\t} else {\n\t\t$alt = '3D Spacecurve';\n\t}\n\n\t$useragent = $_SERVER['HTTP_USER_AGENT'];\n\t$oldschool = false;\n\tif (isset($_SESSION['useflash'])) {\n\t\t$oldschool = true;\n\t} else if (preg_match('/MSIE\\s*(\\d+)/i',$useragent,$matches)) {\n\t\tif ($matches[1]<9) {\n\t\t\t$oldschool =true;\n\t\t}\n\t}\n\n\tif ($oldschool) {\n\n\t\t$func = str_replace('[','',$func);\n\t\t$func = str_replace(']','',$func);\n\t\t$func = explode(',',$func);\n\t\t$func[0] = \"(1+.01*cos(u))*({$func[0]})\";\n\t\t$func[1] = \"(1+.01*cos(u))*({$func[1]})\";\n\t\t$func[2] = \"(1+.01*sin(u))*({$func[2]})\";\n\t\tforeach ($func as $k=>$v) {\n\t\t\t$usefunc[$k] = makeMathFunction($func[$k], \"u,v\");\n\t\t}\n\n\t\t$count = 0;\n\t\t$dt = ($tmax-$tmin)/($disc-1);\n $verts = '';\n\t\tfor ($i=0; $i<4;$i++) {\n\t\t\t for ($j=0;$j<$disc;$j++) {\n\t\t\t\t if ($count > 0) { $verts .= '~';}\n\t\t\t\t $u = 1.571*$i;\n\t\t\t\t $t = $tmin+$dt*$j;\n\n\t\t\t\t $x = $usefunc[0](['u'=>$u, 't'=>$t]);\n\t\t\t\t $y = $usefunc[1](['u'=>$u, 't'=>$t]);\n\t\t\t\t $z = $usefunc[2](['u'=>$u, 't'=>$t]);\n\t\t\t\t $verts .= \"$x,$y,$z\";\n\n\t\t\t\t $count++;\n\t\t\t }\n\t\t }\n\t\t $count = 0;\n $faces = '';\n\t\t for ($i=0; $i<3;$i++) {\n\t\t\t for ($j=0;$j<$disc-1;$j++) {\n\t\t\t\t if ($count > 0) { $faces .= '~';}\n\t\t\t\t $faces .= ($i*$disc+$j) . ',' ;\n\t\t\t\t $faces .= (($i+1)*$disc+$j) . ',';\n\t\t\t\t $faces .= (($i+1)*$disc+$j+1) . ',';\n\t\t\t\t $faces .= ($i*$disc+$j+1);\n\n\t\t\t\t $count++;\n\t\t\t }\n\t\t }\n\t\t $r = uniqid();\n\t\t $GLOBALS['3dplotcnt'] = $r;\n $html = '';\n\t\t $html .= \"<div id=\\\"plot3d$r\\\">\";\n\t\t $html .= '<p><a href=\"http://www.adobe.com/go/getflashplayer\"><img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" /></a></p>';\n\t\t $html .= '</div>';\n\t\t $html .= '<script type=\"text/javascript\">';\n\t\t $html .= 'var FlashVars = {';\n\t\t $html .= ' verts: \"'.$verts.'\",';\n\t\t $html .= ' faces: \"'.$faces.'\",';\n\t\t $html .= \" width: $width, height: $height };\";\n\t\t $html .= \" swfobject.embedSWF(\\\"$imasroot/assessment/libs/viewer3d.swf\\\", \\\"plot3d$r\\\", \\\"$width\\\", \\\"$height\\\", \\\"9.0.0\\\", \\\"$imasroot/assessment/libs/expressInstall.swf\\\",FlashVars);\";\n\t\t $html .= '</script>';\n\t} else {\n\t\t//new approach\n\t\t$func = str_replace('[','',$func);\n\t\t$func = str_replace(']','',$func);\n\t\t$func = explode(',',$func);\n\t\tforeach ($func as $k=>$v) {\n\t\t\t$usefunc[$k] = makeMathFunction($func[$k], \"t\");\n\t\t}\n\n\t\t$count = 0;\n\t\t$dt = ($tmax-$tmin)/($disc-1);\n $verts = '';\n\t\tfor ($j=0;$j<$disc;$j++) {\n\t\t\t if ($count > 0) { $verts .= '~';}\n\t\t\t $t = $tmin+$dt*$j;\n\n\t\t\t $x = $usefunc[0](['t'=>$t]);\n\t\t\t $y = $usefunc[1](['t'=>$t]);\n\t\t\t $z = $usefunc[2](['t'=>$t]);\n\t\t\t $verts .= \"$x,$y,$z\";\n\n\t\t\t $count++;\n\t\t }\n\n\t $r = uniqid();\n $html = '';\n\t\t if (!isset($GLOBALS['3dplotcnt']) || (isset($GLOBALS['assessUIver']) && $GLOBALS['assessUIver'] > 1)) {\n\t\t\t $html .= '<script type=\"text/javascript\" src=\"'.$staticroot.'/javascript/3dviewer.js\"></script>';\n\t\t }\n\t \t $GLOBALS['3dplotcnt'] = $r;\n\t \t $html .= \"<canvas id=\\\"plot3d$r\\\" width=\\\"$width\\\" height=\\\"$height\\\" \";\n\t \t $html .= 'role=\"img\" tabindex=\"0\" aria-label=\"'.Sanitize::encodeStringForDisplay($alt).'\" ';\n\t \t $html .= \">\";\n\n\t \t $url = $GLOBALS['basesiteurl'] . substr($_SERVER['SCRIPT_NAME'],strlen($imasroot)) . (isset($_SERVER['QUERY_STRING'])?'?'.Sanitize::encodeStringForDisplay($_SERVER['QUERY_STRING']).'&useflash=true':'?useflash=true');\n\n\t\t $html .= \"<span aria-hidden=true>Not seeing the 3D graph? <a href=\\\"$url\\\">Try Alternate</a></span>\";\n\t \t $html .= \"</canvas>\";\n if (isset($bounds)) {\n $bndtxt = 'bounds:\"' . implode(',',$bounds) . '\",';\n } else {\n $bndtxt='';\n }\n\t\t\t $init = \"var plot3d$r = new Viewer3D({verts: '$verts', curves: true, $bndtxt width: '$width', height:'$height', showaxes:$axes}, 'plot3d$r');\";\n\t\t\t if (isset($GLOBALS['assessUIver']) && $GLOBALS['assessUIver'] > 1) {\n\t\t\t\t $html .= \"<script type=\\\"text/javascript\\\"> $init </script>\";\n\t\t\t } else {\n\t\t\t\t $html .= \"<script type=\\\"text/javascript\\\">$(window).on('load',function() { $init });</script>\";\n\t\t\t }\n\t}\n\n\t return $html;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function getParameters(): ParameterBag\n {\n $bag = new ParameterBag();\n $page = (int)request()->get('page');\n if ($page < 1) {\n $page = 1;\n }\n if ($page > 2 ** 16) {\n $page = 2 ** 16;\n }\n $bag->set('page', $page);\n\n // some date fields:\n $dates = ['start', 'end', 'date'];\n foreach ($dates as $field) {\n $date = null;\n\n try {\n $date = request()->query->get($field);\n } catch (BadRequestException $e) {\n app('log')->error(sprintf('Request field \"%s\" contains a non-scalar value. Value set to NULL.', $field));\n app('log')->error($e->getMessage());\n app('log')->error($e->getTraceAsString());\n $value = null;\n }\n $obj = null;\n if (null !== $date) {\n try {\n $obj = Carbon::parse((string)$date);\n } catch (InvalidDateException|InvalidFormatException $e) {\n // don't care\n app('log')->warning(\n sprintf(\n 'Ignored invalid date \"%s\" in API controller parameter check: %s',\n substr((string)$date, 0, 20),\n $e->getMessage()\n )\n );\n }\n }\n $bag->set($field, $obj);\n }\n\n // integer fields:\n $integers = ['limit'];\n foreach ($integers as $integer) {\n try {\n $value = request()->query->get($integer);\n } catch (BadRequestException $e) {\n app('log')->error(sprintf('Request field \"%s\" contains a non-scalar value. Value set to NULL.', $integer));\n app('log')->error($e->getMessage());\n app('log')->error($e->getTraceAsString());\n $value = null;\n }\n if (null !== $value) {\n $bag->set($integer, (int)$value);\n }\n if (null === $value\n && 'limit' === $integer // @phpstan-ignore-line\n && auth()->check()) {\n // set default for user:\n /** @var User $user */\n $user = auth()->user();\n\n /** @var Preference $pageSize */\n $pageSize = (int)app('preferences')->getForUser($user, 'listPageSize', 50)->data;\n $bag->set($integer, $pageSize);\n }\n }\n\n // sort fields:\n return $this->getSortParameters($bag);\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function _readPpsWks($blockId)\n {\n $fh = $this->getStream($blockId);\n for ($pos = 0;; $pos += 128) {\n fseek($fh, $pos, SEEK_SET);\n $nameUtf16 = fread($fh, 64);\n $nameLength = self::_readInt2($fh);\n $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);\n // Simple conversion from UTF-16LE to ISO-8859-1\n $name = str_replace(\"\\x00\", \"\", $nameUtf16);\n $type = self::_readInt1($fh);\n switch ($type) {\n case self::OLE_PPS_TYPE_ROOT:\n $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array());\n $this->root = $pps;\n break;\n case self::OLE_PPS_TYPE_DIR:\n $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, null, null, null, null, array());\n break;\n case self::OLE_PPS_TYPE_FILE:\n $pps = new PHPExcel_Shared_OLE_PPS_File($name);\n break;\n default:\n continue;\n }\n fseek($fh, 1, SEEK_CUR);\n $pps->Type = $type;\n $pps->Name = $name;\n $pps->PrevPps = self::_readInt4($fh);\n $pps->NextPps = self::_readInt4($fh);\n $pps->DirPps = self::_readInt4($fh);\n fseek($fh, 20, SEEK_CUR);\n $pps->Time1st = self::OLE2LocalDate(fread($fh, 8));\n $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));\n $pps->_StartBlock = self::_readInt4($fh);\n $pps->Size = self::_readInt4($fh);\n $pps->No = count($this->_list);\n $this->_list[] = $pps;\n\n // check if the PPS tree (starting from root) is complete\n if (isset($this->root) && $this->_ppsTreeComplete($this->root->No)) {\n break;\n }\n }\n fclose($fh);\n\n // Initialize $pps->children on directories\n foreach ($this->_list as $pps) {\n if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {\n $nos = array($pps->DirPps);\n $pps->children = array();\n while ($nos) {\n $no = array_pop($nos);\n if ($no != -1) {\n $childPps = $this->_list[$no];\n $nos[] = $childPps->PrevPps;\n $nos[] = $childPps->NextPps;\n $pps->children[] = $childPps;\n }\n }\n }\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function cx_matrixreduce($A, $rref = False, $disp = False, $roundto = 4) {\n\t\n require_once \"matrix.php\";\n if (!isMatrix($A)) { echo 'error: input not a matrix'; return '';}\n \n\t// number of rows\n $N = count($A);\n // number of columns\n $M = count($A[0]);\n \n\tfor ($i=0; $i<$N; $i++){\n\t\tfor ($j=0; $j<$M; $j++){\n\t\t\tif(!is_array($A[$i][$j])){\n\t\t\t\t$A[$i][$j]=[$A[$i][$j],0];\n\t\t\t}\n\t\t\tif(count($A[$i][$j])==1){\n\t\t\t\t$A[$i][$j]=[$A[$i][$j][0],0];\n\t\t\t}\n\t\t\n\t\t}\n\n\t}\n\t\n $r = 0; $c = 0;\n while ($r < $N && $c < $M) {\n\t\tif (cx_modul($A[$r][$c]) == 0) { //swap only if there's a 0 entry $A[$r][$c]==0\n\t\t\t$max = $r;\n\t\t\tfor ($i = $r+1; $i<$N; $i++) {\n\t\t\t\tif (cx_modul($A[$i][$c]) > cx_modul($A[$max][$c])) {\n\t\t\t\t\t$max = $i;\n\t\t\t\t} \n\t\t\t}\n\t\t\tif ($max != $r) {\n\t\t\t\t$temp = $A[$r]; $A[$r] = $A[$max]; $A[$max] = $temp;\n\t\t\t}\n\t\t}\t\n\n\t if (cx_modul($A[$r][$c]) < 1e-10){\n\t \t$c++;\n\t \tcontinue;\n\t }\n\t\t\n\t //scale pivot rows\n\t if ($rref==True) {\n\t\t\tif(cx_modul($A[$r][$c])!=0){\n\t\t \t$divisor = $A[$r][$c];\n\t\t\t} else {$divisor=[1,0];}\n\t\t for ($j = $c; $j < $M; $j++) {\n\t\t\t\t$A[$r][$j] = cx_div([$A[$r][$j],$divisor]);\n\t\t\t}\n\t }\n\t\t\n\t for ($i = ($rref?0:$r+1); $i < $N; $i++) {\n\t \t if ($i==$r) {continue;}\n\t\t\t\tif (cx_modul($A[$r][$c])!=0 && cx_modul($A[$i][$c])!=0){\n\t\t\t\t\n\t\t\t\t\t$mult = cx_div([$A[$i][$c],$A[$r][$c]]); \n\t\t\t\t} else {$mult=[0,0];}\n\t \t if ( cx_modul($mult)==0) {continue;}\n\t \t \n\t\t\t\tfor ($j = $c; $j < $M; $j++) {\n\t\t\t\t\tif(cx_modul($mult)!=0 && cx_modul($A[$r][$j])!=0){\n\n\t\t\t\t\t\t$A[$i][$j] = cx_sub([$A[$i][$j],cx_mul([$mult,$A[$r][$j]])]); \n\t\t\t\t\t} \n\t\t\t\t\t\t\n if (cx_modul($A[$i][$j]) <= 1e-10) {\n $A[$i][$j] = [0,0]; //treat values close to 0 as 0\n }\t\t\n\t \t }\n\t }\n\n\t $r++; $c++;\n }\n\t\n\tif($disp == True){\n \n\t\tfor ($i=0; $i<$N; $i++){\n\t\t\t\n\t\t\t$A[$i] = cx_format2std($A[$i], $roundto);\n\t\t}\n $A = matrixformat($A);\n\t}\n\t\t\n return ($A); \n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function sphUnpackU64 ( $v )\n{\n\tlist ( $hi, $lo ) = array_values ( unpack ( \"N*N*\", $v ) );\n\n\tif ( PHP_INT_SIZE>=8 )\n\t{\n\t\tif ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again\n\t\tif ( $lo<0 ) $lo += (1<<32);\n\n\t\t// x64, int\n\t\tif ( $hi<=2147483647 )\n\t\t\treturn ($hi<<32) + $lo;\n\n\t\t// x64, bcmath\n\t\tif ( function_exists(\"bcmul\") )\n\t\t\treturn bcadd ( $lo, bcmul ( $hi, \"4294967296\" ) );\n\n\t\t// x64, no-bcmath\n\t\t$C = 100000;\n\t\t$h = ((int)($hi / $C) << 32) + (int)($lo / $C);\n\t\t$l = (($hi % $C) << 32) + ($lo % $C);\n\t\tif ( $l>$C )\n\t\t{\n\t\t\t$h += (int)($l / $C);\n\t\t\t$l = $l % $C;\n\t\t}\n\n\t\tif ( $h==0 )\n\t\t\treturn $l;\n\t\treturn sprintf ( \"%d%05d\", $h, $l );\n\t}\n\n\t// x32, int\n\tif ( $hi==0 )\n\t{\n\t\tif ( $lo>0 )\n\t\t\treturn $lo;\n\t\treturn sprintf ( \"%u\", $lo );\n\t}\n\n\t$hi = sprintf ( \"%u\", $hi );\n\t$lo = sprintf ( \"%u\", $lo );\n\n\t// x32, bcmath\n\tif ( function_exists(\"bcmul\") )\n\t\treturn bcadd ( $lo, bcmul ( $hi, \"4294967296\" ) );\n\t\n\t// x32, no-bcmath\n\t$hi = (float)$hi;\n\t$lo = (float)$lo;\n\t\n\t$q = floor($hi/10000000.0);\n\t$r = $hi - $q*10000000.0;\n\t$m = $lo + $r*4967296.0;\n\t$mq = floor($m/10000000.0);\n\t$l = $m - $mq*10000000.0;\n\t$h = $q*4294967296.0 + $r*429.0 + $mq;\n\n\t$h = sprintf ( \"%.0f\", $h );\n\t$l = sprintf ( \"%07.0f\", $l );\n\tif ( $h==\"0\" )\n\t\treturn sprintf( \"%.0f\", (float)$l );\n\treturn $h . $l;\n}", "smellKey": "S3776", "smellId": null, "repo": "abbas-sabra-sonarsource_manticoresearch", "language": "php"} {"function": "public function getResult(): ScorePartResult\n {\n global $mathfuncs;\n\n $scorePartResult = new ScorePartResult();\n\n $RND = $this->scoreQuestionParams->getRandWrapper();\n $options = $this->scoreQuestionParams->getVarsForScorePart();\n $qn = $this->scoreQuestionParams->getQuestionNumber();\n $givenans = $this->scoreQuestionParams->getGivenAnswer();\n $multi = $this->scoreQuestionParams->getIsMultiPartQuestion();\n $partnum = $this->scoreQuestionParams->getQuestionPartNumber();\n $anstype = $this->scoreQuestionParams->getAnswerType();\n\n $defaultreltol = .0015;\n\n $optionkeys = ['answer', 'reltolerance', 'abstolerance', \n 'answerformat', 'requiretimes', 'requiretimeslistpart', 'ansprompt', \n 'scoremethod', 'partweights', 'domain', 'variables'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n if ($reltolerance === '' && $abstolerance === '') { $reltolerance = $defaultreltol;}\n\n if ($multi) { $qn = ($qn+1)*1000+$partnum; }\n \n $givenans = normalizemathunicode($givenans);\n $givenans = str_replace(array('(:',':)','<<','>>'), array('<','>','<','>'), $givenans);\n $givenans = trim($givenans,\" ,\");\n $answer = normalizemathunicode($answer);\n \n $ansformats = array_map('trim',explode(',',$answerformat));\n $checkSameform = (in_array('sameform',$ansformats));\n\n $answer = str_replace(' ','',$answer);\n if (!is_array($partweights) && $partweights !== '') {\n $partweights = array_map('trim',explode(',',$partweights));\n }\n\n if (in_array('nosoln',$ansformats) || in_array('nosolninf',$ansformats)) {\n list($givenans, $answer) = scorenosolninf($qn, $givenans, $answer, $ansprompt);\n if ($givenans === 'DNE' || $givenans === 'oo') {\n $_POST[\"qn$qn-val\"] = $givenans;\n }\n }\n\n $scorePartResult->setLastAnswerAsGiven($givenans);\n\n $givenans = str_replace(' ','',$givenans);\n\n if ($answer=='DNE') {\n if (strtoupper($givenans)=='DNE') {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n } else if ($answer=='oo') {\n if ($givenans=='oo') {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n } else if (strtoupper($givenans)=='DNE' || $givenans=='oo') {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n // clean up givenans\n $givenans = preg_replace_callback(\n '/(arcsinh|arccosh|arctanh|arcsin|arccos|arctan|arcsec|arccsc|arccot|root|sqrt|sign|sinh|cosh|tanh|sech|csch|coth|abs|sin|cos|tan|sec|csc|cot|exp|log|ln)[\\(\\[]/i',\n function($m) { return strtolower($m[0]); },\n $givenans\n );\n\n $gaarr = parseNtuple($givenans, false, false);\n \n if ($givenans == null) {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n if (empty($variables)) { $variables = \"x\";}\n list($variables, $tps, $flist) = numfuncGenerateTestpoints($variables, $domain);\n $vlist = implode(\",\",$variables);\n $isComplex = in_array('generalcomplex', $ansformats);\n\n //test for correct format, if specified\n if (checkreqtimes($givenans,$requiretimes)==0) {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n if ($checkSameform) {\n $normalizedGivenAnswer = $gaarr;\n }\n\n // check formats and generate test values\n foreach($gaarr as $i=>$chkme) {\n foreach ($chkme['vals'] as $k=>$chkval) {\n if ($chkval != 'oo' && $chkval != '-oo') {\n $gafunc = parseMathQuiet($chkval, $vlist, [], $flist, true, $isComplex);\n if ($gafunc === false) {\n $gaarr[$i]['tvals'][$k] = false;\n $normalizedGivenAnswer[$i]['vals'][$k] = '';\n continue;\n }\n $gvals = [];\n for ($c = 0; $c < 20; $c++) {\n $varvals = array();\n for($j=0; $j < count($variables); $j++) {\n $varvals[$variables[$j]] = $tps[$c][$j];\n }\n $gvals[] = $gafunc->evaluateQuiet($varvals);\n }\n $gaarr[$i]['tvals'][$k] = $gvals;\n // generate normalized trees for sameform check\n if ($checkSameform) {\n $normalizedGivenAnswer[$i]['vals'][$k] = $gafunc->normalizeTreeString();\n }\n }\n }\n }\n \n if (!empty($requiretimeslistpart)) {\n if (checkreqtimes($chkme['lb'].implode(',', $chkme['vals']).$chkme['rb'],$requiretimeslistpart)==0) {\n unset($gaarr[$i]);\n }\n }\n \n if (!is_array($gaarr) || count($gaarr)==0) {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n $answer = makepretty($answer);\n // parse and evaluate the answer, capturing \"or\"s\n $anarr = parseNtuple($answer, true, false);\n if ($checkSameform) {\n $normalizedAnswer = $anarr;\n }\n foreach($anarr as $i=>$anors) {\n foreach ($anors as $oi=>$chkme) {\n foreach ($chkme['vals'] as $k=>$chkval) {\n if ($chkval != 'oo' && $chkval != '-oo') {\n // generate normalized trees for sameform check\n $anfunc = parseMathQuiet($chkval, $vlist, [], $flist, true, $isComplex);\n if ($anfunc === false) {\n $anarr[$i][$oi]['tvals'][$k] = false;\n $normalizedAnswer[$i][$oi]['vals'][$k] = '';\n }\n $anvals = [];\n for ($c = 0; $c < 20; $c++) {\n $varvals = array();\n for($j=0; $j < count($variables); $j++) {\n $varvals[$variables[$j]] = $tps[$c][$j];\n }\n $anvals[] = $anfunc->evaluateQuiet($varvals);\n }\n $anarr[$i][$oi]['tvals'][$k] = $anvals;\n if ($checkSameform) {\n $normalizedAnswer[$i][$oi]['vals'][$k] = $anfunc->normalizeTreeString();\n }\n }\n }\n }\n }\n \n $gaarrcnt = count($gaarr);\n $extrapennum = count($gaarr)+count($anarr);\n $correct = 0;\n $partialmatches = array();\n $matchedans = array();\n $matchedgivenans = array();\n\n foreach ($anarr as $ai=>$ansors) {\n $foundloc = -1;\n foreach ($ansors as $ao=>$answer) { //each of the \"or\" options\n foreach ($gaarr as $j=>$givenans) {\n\n if (isset($matchedgivenans[$j])) {continue;}\n\n if ($answer['lb']!=$givenans['lb'] || $answer['rb']!=$givenans['rb']) {\n continue;\n }\n\n if (count($answer['vals'])!=count($givenans['vals'])) {\n continue;\n }\n\n $matchedparts = [];\n foreach ($answer['vals'] as $i=>$ansval) {\n $gansval = $givenans['vals'][$i];\n if (($ansval==='oo' && $gansval==='oo') || ($ansval==='-oo' && $gansval==='-oo')) {\n $matchedparts[$i] = 1;\n //is ok\n continue;\n } \n $cntnan = 0;\n $stunan = 0;\n if ($answer['tvals'][$i] === false) {\n continue; // invalid answer\n }\n if ($givenans['tvals'][$i] === false) {\n // student answer didn't parse\n continue;\n }\n foreach ($answer['tvals'][$i] as $tvi=>$ansval) {\n if (isNaN($ansval)) {\n $cntnan++; \n continue;\n }\n $stuval = $givenans['tvals'][$i][$tvi];\n $vcorrect = true;\n if ($isComplex) {\n if (!is_array($stuval)) {\n $stunan++; \n } else if ($abstolerance !== '') {\n if (abs($stuval[0]-$ansval[0]) > $abstolerance+1E-12) { $vcorrect=false; break;}\n if (abs($stuval[1]-$ansval[1]) > $abstolerance+1E-12) { $vcorrect=false; break;}\n } else {\n if ((abs($stuval[0]-$ansval[0])/(abs($ansval[0])+.0001) > $reltolerance+1E-12)) {$vcorrect=false; break;}\n if ((abs($stuval[1]-$ansval[1])/(abs($ansval[1])+.0001) > $reltolerance+1E-12)) {$vcorrect=false; break;}\n }\n } else {\n if (isNaN($stuval)) {\n $stunan++; \n } else if ($abstolerance !== '') {\n if (abs($stuval-$ansval) > $abstolerance+1E-12) { $vcorrect=false; break;}\n } else {\n if ((abs($stuval-$ansval)/(abs($ansval)+.0001) > $reltolerance+1E-12)) { $vcorrect=false; break;}\n }\n }\n }\n if ($cntnan==20 && isset($GLOBALS['teacherid'])) {\n echo _('Debug info: function evaled to Not-a-number at all test points. Check $domain');\n }\n if ($stunan>1) { //if more than 1 student NaN response\n $vcorrect = false; continue;\n }\n if ($vcorrect) {\n $matchedparts[$i] = 1;\n }\n }\n\n if ($checkSameform && $normalizedAnswer[$ai][$ao] != $normalizedGivenAnswer[$j]) {\n continue;\n }\n\n if (count($matchedparts)==count($answer['vals'])) { //if totally correct\n $correct += 1; $foundloc = $j; break 2;\n } else if ($scoremethod=='byelement' && count($matchedparts)>0) { //if partially correct\n if (is_array($partweights)) {\n $fraccorrect = 0;\n foreach ($partweights as $pwi => $pwv) {\n if (!empty($matchedparts[$pwi])) {\n $fraccorrect += $pwv;\n }\n }\n $fraccorrect /= array_sum($partweights);\n } else {\n $fraccorrect = count($matchedparts)/count($answer['vals']);\n }\n if (!isset($partialmatches[\"$ai-$j\"]) || $fraccorrect>$partialmatches[\"$ai-$j\"]) {\n $partialmatches[\"$ai-$j\"] = $fraccorrect;\n }\n }\n }\n }\n if ($foundloc>-1) {\n //array_splice($gaarr,$foundloc,1); // remove from list\n $matchedgivenans[$foundloc] = 1;\n $matchedans[$ai] = 1;\n if (count($gaarr)==count($matchedgivenans)) {\n break;\n }\n }\n }\n if ($scoremethod=='byelement') {\n arsort($partialmatches);\n foreach ($partialmatches as $k=>$v) {\n $kp = explode('-', $k);\n if (isset($matchedans[$kp[0]]) || isset($matchedgivenans[$kp[1]])) {\n //already used this ans or stuans\n continue;\n } else {\n $correct += $v;\n $matchedans[$kp[0]] = 1;\n $matchedgivenans[$kp[1]] = 1;\n if (count($gaarr)==count($matchedgivenans)) {\n break;\n }\n }\n }\n }\n if (count($anarr)==0) { // no answers\n if ($GLOBALS['myrights']>10) {\n echo _('Eeek: No valid $answer values provided');\n }\n $score = 0;\n } else if ($gaarrcnt<=count($anarr)) {\n $score = $correct/count($anarr);\n } else {\n $score = $correct/count($anarr) - ($gaarrcnt-count($anarr))/$extrapennum; //take off points for extranous stu answers\n }\n\n //$score = $correct/count($anarr) - count($gaarr)/$extrapennum;\n if ($score<0) { $score = 0; }\n\n $scorePartResult->setRawScore($score);\n return $scorePartResult;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function getItemtype($index = 0, $recursive = true, $all_assets = false)\n {\n\n if (isset($this->url_elements[$index])) {\n $all_assets = $all_assets && $this->url_elements[$index] == AllAssets::getType();\n $valid_class = Toolbox::isCommonDBTM($this->url_elements[$index])\n || Toolbox::isAPIDeprecated($this->url_elements[$index]);\n\n if ($all_assets || $valid_class) {\n $itemtype = $this->url_elements[$index];\n\n if (\n $recursive\n && ($additional_itemtype = $this->getItemtype(2, false))\n ) {\n $this->parameters['parent_itemtype'] = $itemtype;\n $itemtype = $additional_itemtype;\n }\n\n // AllAssets\n if ($all_assets) {\n return AllAssets::getType();\n }\n\n // Load namespace for deprecated\n $deprecated = Toolbox::isAPIDeprecated($itemtype);\n if ($deprecated) {\n $itemtype = \"Glpi\\Api\\Deprecated\\\\$itemtype\";\n }\n\n // Get case sensitive itemtype name\n $itemtype = (new \\ReflectionClass($itemtype))->getName();\n if ($deprecated) {\n // Remove deprecated namespace\n $itemtype = str_replace(\"Glpi\\Api\\Deprecated\\\\\", \"\", $itemtype);\n }\n return $itemtype;\n }\n $this->returnError(\n __(\"resource not found or not an instance of CommonDBTM\"),\n 400,\n \"ERROR_RESOURCE_NOT_FOUND_NOR_COMMONDBTM\"\n );\n } else if ($recursive) {\n $this->returnError(__(\"missing resource\"), 400, \"ERROR_RESOURCE_MISSING\");\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function postmode_file_selection() {\n\n $param_name = 'file';\n\n // there are two ways into the file selection mode;\n // either the user has just arrived at the import page,\n // or they've selected a file *and might progress to file-parsing mode*\n $error = '';\n if (@$_FILES[$param_name]) {\n if ($_FILES[$param_name]['size'] == 0) {\n $error = 'no file was uploaded';\n } else {\n switch ($_FILES[$param_name]['error']) {\n case UPLOAD_ERR_OK:\n break;\n case UPLOAD_ERR_INI_SIZE:\n case UPLOAD_ERR_FORM_SIZE:\n $error = \"The uploaded file was too large. Please consider importing it in several stages.\";\n break;\n case UPLOAD_ERR_PARTIAL:\n $error = \"The uploaded file was only partially uploaded.\";\n break;\n case UPLOAD_ERR_NO_FILE:\n $error = \"No file was uploaded.\";\n break;\n case UPLOAD_ERR_NO_TMP_DIR:\n $error = \"Missing a temporary folder.\";\n break;\n case UPLOAD_ERR_CANT_WRITE:\n $error = \"Failed to write file to disk\";\n break;\n default:\n $error = \"Unknown file error\";\n }\n\n\n $content_length = USystem::fixIntegerOverflow((int)@$_SERVER['CONTENT_LENGTH']);\n\n $post_max_size = USystem::getConfigBytes('post_max_size');\n if ($post_max_size && ($content_length > $post_max_size)) {\n $error = 'The uploaded file exceeds the post_max_size directive in php.ini';\n }else{\n if ($_FILES[$param_name]['tmp_name'] && is_uploaded_file($_FILES[$param_name]['tmp_name'])) {\n $file_size = getFileSize($_FILES[$param_name]['tmp_name']);\n } else {\n $file_size = $content_length;\n }\n $file_max_size = USystem::getConfigBytes('upload_max_filesize');\n if ($file_max_size && ($content_length > $file_max_size)) {\n $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';\n }\n\n }\n }\n\n if (!$error) { // move on to the next stage!\n //$error = postmode_file_load_to_db($_FILES[$param_name]['tmp_name'], $_FILES[$param_name]['name'], true);\n }\n }\n\n return $error;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['code'])) {\n $this->setCode($data['code']);\n }\n if (isset($data['isDefault'])) {\n $this->setIsDefault($data['isDefault']);\n }\n if (isset($data['compositional'])) {\n $this->setCompositional($data['compositional']);\n }\n if (isset($data['language'])) {\n if (is_array($data['language'])) {\n foreach ($data['language'] as $d) {\n $this->addLanguage($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"language\" must be array of objects or null, ' . gettype($data['language']) . ' seen.');\n }\n }\n if (isset($data['filter'])) {\n if (is_array($data['filter'])) {\n foreach ($data['filter'] as $d) {\n $this->addFilter($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"filter\" must be array of objects or null, ' . gettype($data['filter']) . ' seen.');\n }\n }\n if (isset($data['property'])) {\n if (is_array($data['property'])) {\n foreach ($data['property'] as $d) {\n $this->addProperty($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"property\" must be array of objects or null, ' . gettype($data['property']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function testGetMenus(array $options)\n {\n $user = $options['user'];\n $additionalData = $options['data'];\n\n $defaultExpected = array(\n \"output\" => \"$user-get_menus\",\n \"http_code\" => 200,\n \"content_type\" => 'application/json'\n );\n\n $expectedConfig = isset($options['expected']) ? $options['expected'] : $defaultExpected;\n $expectedOutputFileName = $expectedConfig['output'];\n $expectedHttpCode = isset($expectedConfig['http_code']) ? $expectedConfig['http_code'] : 200;\n $expectedContentType = isset($expectedConfig['content_type']) ? $expectedConfig['content_type'] : 'application/json';\n\n // Make sure to authenticate the user if necessary.\n if ($user !== ROLE_ID_PUBLIC) {\n $this->helper->authenticate($user);\n }\n\n $data = array_merge(\n array(\n 'operation' => 'get_menus',\n 'query_group' => 'tg_usage'\n ),\n $additionalData\n );\n\n $response = $this->helper->post(\"controllers/user_interface.php\", null, $data);\n\n if ($user !== ROLE_ID_PUBLIC) {\n $this->helper->logout();\n }\n\n $this->validateResponse($response, $expectedHttpCode, $expectedContentType);\n\n $actual = $response[0];\n\n $this->validateJsonAgainstFile($actual, 'schema', 'get-menus.spec');\n\n # Check expected file\n $expected = array();\n foreach(self::$XDMOD_REALMS as $realm) {\n $expectedOutputFile = $this->getTestFiles()->getFile('user_interface', $expectedOutputFileName, \"output/$realm\");\n\n # Create missing files/directories\n if (!is_file($expectedOutputFile)) {\n $newFile = array();\n foreach ($actual as $arr) {\n if (isset($arr['realm'])) {\n if (strtolower($arr['realm']) == $realm) {\n array_push($newFile, $arr);\n }\n }\n }\n $separator = array(\n \"text\" => \"\",\n \"id\" => \"-111\",\n \"node_type\" => \"separator\",\n \"iconCls\" => \"blank\",\n \"leaf\" => true,\n \"disabled\" => true\n );\n array_push($newFile, $separator);\n $filePath = dirname($expectedOutputFile);\n if (!is_dir($filePath)){\n mkdir($filePath);\n }\n file_put_contents($expectedOutputFile, json_encode($newFile, JSON_PRETTY_PRINT) . \"\\n\");\n $this->markTestSkipped(\"Generated Expected Output for UserInterfaceTest testGetMenus: $expectedOutputFile\\n\");\n }\n\n $expected = array_merge($expected, json_decode(file_get_contents($expectedOutputFile), true));\n\n }\n\n $this->assertEquals($expected, $actual);\n\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function gridSaveColumnConfigAction(Request $request): JsonResponse\n {\n $objectId = $request->request->getInt('id');\n $object = DataObject::getById($objectId);\n\n if ($object->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');\n\n $searchType = $request->get('searchType');\n\n // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();\n\n $gridConfigData['context'] = $context;\n\n unset($gridConfigData['settings']['isShared']);\n\n $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);\n\n $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = null;\n if ($gridConfigId) {\n $gridConfig = GridConfig::getById($gridConfigId);\n }\n\n if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin()) {\n throw new \\Exception(\"don't mess around with somebody elses configuration\");\n }\n\n $this->updateGridConfigShares($gridConfig, $metadata);\n\n if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata, $objectId);\n }\n\n if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);\n\n $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }\n\n if ($metadata) {\n $gridConfig->setName(SecurityHelper::convertHtmlSpecialChars($metadata['gridConfigName']));\n $gridConfig->setDescription(SecurityHelper::convertHtmlSpecialChars($metadata['gridConfigDescription']));\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSaveFilters($metadata['saveFilters'] ?? false);\n }\n\n $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();\n\n $userId = $this->getAdminUser()->getId();\n\n $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);\n\n $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = SecurityHelper::convertHtmlSpecialChars($gridConfig->getName());\n $settings['gridConfigDescription'] = SecurityHelper::convertHtmlSpecialChars($gridConfig->getDescription());\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['saveFilters'] = $gridConfig->isSaveFilters();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin();\n\n return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }\n\n throw $this->createAccessDeniedHttpException();\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function navigation($logged_in)\n {\n global $setting_bootstrap_submenu;\n\n ?>\n <script>\n function toggle_menu() {\n var x = document.getElementById('hide_nav');\n if (x.style.display === 'none') {\n $.post( \"<?php echo $GLOBALS['webroot'] . \"/interface/main/messages/messages.php\"; ?>\", {\n 'setting_bootstrap_submenu' : 'show',\n success: function (data) {\n x.style.display = 'block';\n }\n });\n\n } else {\n $.post( \"<?php echo $GLOBALS['webroot'] . \"/interface/main/messages/messages.php\"; ?>\", {\n 'setting_bootstrap_submenu' : 'hide',\n success: function (data) {\n x.style.display = 'none';\n }\n });\n }\n $(\"#patient_caret\").toggleClass('fa-caret-up').toggleClass('fa-caret-down');\n }\n\n function SMS_bot_list() {\n top.restoreSession();\n var myWindow = window.open('<?php echo $GLOBALS['webroot']; ?>/interface/main/messages/messages.php?nomenu=1&go=SMS_bot&dir=back&show=new','SMS_bot', 'width=400,height=650');\n myWindow.focus();\n return false;\n }\n </script>\n <i class=\"fa fa-caret-<?php\n if ($setting_bootstrap_submenu == 'hide') {\n echo 'down';\n } else {\n echo 'up';\n } ?> menu_arrow\" style=\"position:fixed;left:5px;top:10px;z-index:1200;\" id=\"patient_caret\" onclick='toggle_menu();' aria-hidden=\"true\"></i>\n\n <div id=\"hide_nav\" style=\"<?php if ($setting_bootstrap_submenu == 'hide') {\n echo \"display:none;\"; } ?>\">\n\n <nav id=\"navbar_oe\" class=\"navbar navbar-expand-sm p-0 pl-1\" name=\"kiosk_hide\" data-role=\"page banner navigation\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#oer-navbar-collapse-1\" aria-controls=\"oer-navbar-collapse-1\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n <div class=\"collapse navbar-collapse\" id=\"oer-navbar-collapse-1\">\n <ul class=\"navbar-nav\">\n <?php if ($GLOBALS['medex_enable'] == '1') { ?>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link\" data-toggle=\"dropdown\" id=\"menu_dropdown_file\" role=\"button\" aria-expanded=\"true\"><?php echo xlt(\"File\"); ?> </a>\n <ul class=\"bgcolor2 dropdown-menu\" aria-labelledby=\"menu_dropdown_file\">\n <?php if ($logged_in) { ?>\n <li id=\"menu_PREFERENCES\" name=\"menu_PREFERENCES\" class=\"\"><a class=\"dropdown-item\" onclick=\"tabYourIt('prefs','main/messages/messages.php?go=Preferences');\"><?php echo xlt(\"Preferences\"); ?></a></li>\n <li id=\"icons\" name=\"icons\"><a class=\"dropdown-item\" onclick=\"doRecallclick_edit('icons');\"><?php echo xlt('Icon Legend'); ?></a></li>\n <?php\n } else {\n ?>\n <li id=\"menu_PREFERENCES\" name=\"menu_PREFERENCES\" class=\"\">\n <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?go=setup&stage=1\"><?php echo xlt(\"Setup MedEx\"); ?></a></li>\n <?php } ?>\n </ul>\n </li>\n <?php } ?>\n\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link\" data-toggle=\"dropdown\" id=\"menu_dropdown_msg\" role=\"button\" aria-expanded=\"true\"><?php echo xlt(\"Messages\"); ?> </a>\n <ul class=\"bgcolor2 dropdown-menu\" aria-labelledby=\"menu_dropdown_msg\">\n <li id=\"menu_new_msg\"> <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?showall=no&sortby=users.lname&sortorder=asc&begin=0&task=addnew&form_active=1\"> <?php echo xlt(\"New Message\"); ?></a></li>\n <li class=\"dropdown-divider\"></li>\n <li id=\"menu_new_msg\"> <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?show_all=no&form_active=1\"> <?php echo xlt(\"My Messages\"); ?></a></li>\n <li id=\"menu_all_msg\"> <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?show_all=yes&form_active=1\"> <?php echo xlt(\"All Messages\"); ?></a></li>\n <li class=\"dropdown-divider\"></li>\n <li id=\"menu_active_msg\"> <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?show_all=yes&form_active=1\"> <?php echo xlt(\"Active Messages\"); ?></a></li>\n <li id=\"menu_inactive_msg\"> <a class=\"dropdown-item\" href=\"<?php echo $GLOBALS['web_root']; ?>/interface/main/messages/messages.php?form_inactive=1\"> <?php echo xlt(\"Inactive Messages\"); ?></a></li>\n <li id=\"menu_log_msg\"> <a class=\"dropdown-item\" onclick=\"openLogScreen();\" > <?php echo xlt(\"Message Log\"); ?></a></li>\n </ul>\n </li>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link\" data-toggle=\"dropdown\" id=\"menu_dropdown_recalls\" role=\"button\" aria-expanded=\"true\"><?php echo xlt(\"Appt. Reminders\"); ?></a>\n <ul class=\"bgcolor2 dropdown-menu\" aria-labelledby=\"menu_dropdown_recalls\">\n <?php\n if ($GLOBALS['disable_calendar'] != '1') { ?>\n <li><a class=\"dropdown-item\" id=\"BUTTON_ApRem_menu\" onclick=\"tabYourIt('cal','main/main_info.php');\"> <?php echo xlt(\"Calendar\"); ?></a></li>\n <li class=\"dropdown-divider\"></li>\n <?php\n }\n if ($GLOBALS['disable_pat_trkr'] != '1') {\n ?>\n <li id=\"menu_pend_recalls\" name=\"menu_pend_recalls\"> <a class=\"dropdown-item\" id=\"BUTTON_pend_recalls_menu\" onclick=\"tabYourIt('flb','patient_tracker/patient_tracker.php?skip_timeout_reset=1');\"> <?php echo xlt(\"Flow Board\"); ?></a></li>\n <?php }\n if ($logged_in) {\n ?>\n <li class=\"dropdown-divider\"></li>\n <li id=\"menu_pend_recalls\" name=\"menu_pend_recalls\"> <a href='https://medexbank.com/cart/upload/index.php?route=information/campaigns&g=rem' target=\"_medex\" class='dropdown-item nowrap text-left' id=\"BUTTON_pend_recalls_menu\"> <?php echo xlt(\"Reminder Campaigns\"); ?></a></li>\n <?php\n }\n ?>\n </ul>\n </li>\n <?php\n\n if ($GLOBALS['disable_rcb'] != '1') { ?>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link\" data-toggle=\"dropdown\" id=\"menu_dropdown_recalls\" role=\"button\" aria-expanded=\"true\"><?php echo xlt(\"Patient Recalls\"); ?> </a>\n <ul class=\"bgcolor2 dropdown-menu\" aria-labelledby=\"menu_dropdown_recalls\">\n <li id=\"menu_new_recall\" name=\"menu_new_recall\"> <a class=\"dropdown-item\" id=\"BUTTON_new_recall_menu\" onclick=\"tabYourIt('rcb','main/messages/messages.php?go=addRecall');\"> <?php echo xlt(\"New Recall\"); ?></a></li>\n <li id=\"menu_pend_recalls\" name=\"menu_pend_recalls\"> <a class=\"dropdown-item\" onclick=\"goReminderRecall('Recalls');\" id=\"BUTTON_pend_recalls_menu\" href=\"#\"> <?php echo xlt(\"Recall Board\"); ?></a></li>\n <?php\n if ($logged_in) {\n ?>\n <li class=\"dropdown-divider\"></li>\n <li id=\"menu_pend_recalls\" name=\"menu_pend_recalls\"> <a href='https://medexbank.com/cart/upload/index.php?route=information/campaigns&g=rec' target=\"_medex\" class='dropdown-item nowrap text-left' id=\"BUTTON_pend_recalls_menu\"> <?php echo xlt(\"Recall Campaigns\"); ?></a></li>\n <?php\n }\n ?>\n </ul>\n </li>\n <?php\n }\n\n if ($logged_in) {\n if (!empty($logged_in['products']['ordered'])) {\n foreach ($logged_in['products']['ordered'] as $ordered) {\n echo $ordered['menu'];\n }\n }\n }\n ?>\n </ul>\n </div>\n </nav>\n </div>\n <?php\n if ($GLOBALS['medex_enable'] == '1') {\n $error = $this->MedEx->getLastError();\n if (!empty($error['ip'])) {\n ?>\n <div class=\"alert alert-danger text-center w-50\" style=\"margin:30px auto 5px; font-size:0.9rem;\">\n <?php\n echo $error['ip'];\n ?>\n </div>\n <?php\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function scan($dir = '', $recursive = \\OC\\Files\\Cache\\Scanner::SCAN_RECURSIVE, ?callable $mountFilter = null) {\n\t\tif (!Filesystem::isValidPath($dir)) {\n\t\t\tthrow new \\InvalidArgumentException('Invalid path to scan');\n\t\t}\n\t\t$mounts = $this->getMounts($dir);\n\t\tforeach ($mounts as $mount) {\n\t\t\tif ($mountFilter && !$mountFilter($mount)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$storage = $mount->getStorage();\n\t\t\tif (is_null($storage)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// don't bother scanning failed storages (shortcut for same result)\n\t\t\tif ($storage->instanceOfStorage(FailedStorage::class)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// if the home storage isn't writable then the scanner is run as the wrong user\n\t\t\tif ($storage->instanceOfStorage(Home::class)) {\n\t\t\t\t/** @var Home $storage */\n\t\t\t\tforeach (['', 'files'] as $path) {\n\t\t\t\t\tif (!$storage->isCreatable($path)) {\n\t\t\t\t\t\t$fullPath = $storage->getSourcePath($path);\n\t\t\t\t\t\tif (!$storage->is_dir($path) && $storage->getCache()->inCache($path)) {\n\t\t\t\t\t\t\tthrow new NotFoundException(\"User folder $fullPath exists in cache but not on disk\");\n\t\t\t\t\t\t} elseif ($storage->is_dir($path)) {\n\t\t\t\t\t\t\t$ownerUid = fileowner($fullPath);\n\t\t\t\t\t\t\t$owner = posix_getpwuid($ownerUid);\n\t\t\t\t\t\t\t$owner = $owner['name'] ?? $ownerUid;\n\t\t\t\t\t\t\t$permissions = decoct(fileperms($fullPath));\n\t\t\t\t\t\t\tthrow new ForbiddenException(\"User folder $fullPath is not writable, folders is owned by $owner and has mode $permissions\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// if the root exists in neither the cache nor the storage the user isn't setup yet\n\t\t\t\t\t\t\tbreak 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// don't scan received local shares, these can be scanned when scanning the owner's storage\n\t\t\tif ($storage->instanceOfStorage(SharedStorage::class)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$relativePath = $mount->getInternalPath($dir);\n\t\t\t$scanner = $storage->getScanner();\n\t\t\t$scanner->setUseTransactions(false);\n\t\t\t$this->attachListener($mount);\n\n\t\t\t$scanner->listen('\\OC\\Files\\Cache\\Scanner', 'removeFromCache', function ($path) use ($storage) {\n\t\t\t\t$this->postProcessEntry($storage, $path);\n\t\t\t\t$this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));\n\t\t\t});\n\t\t\t$scanner->listen('\\OC\\Files\\Cache\\Scanner', 'updateCache', function ($path) use ($storage) {\n\t\t\t\t$this->postProcessEntry($storage, $path);\n\t\t\t\t$this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));\n\t\t\t});\n\t\t\t$scanner->listen('\\OC\\Files\\Cache\\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage) {\n\t\t\t\t$this->postProcessEntry($storage, $path);\n\t\t\t\tif ($fileId) {\n\t\t\t\t\t$this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));\n\t\t\t\t} else {\n\t\t\t\t\t$this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (!$storage->file_exists($relativePath)) {\n\t\t\t\tthrow new NotFoundException($dir);\n\t\t\t}\n\n\t\t\tif ($this->useTransaction) {\n\t\t\t\t$this->db->beginTransaction();\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t$propagator = $storage->getPropagator();\n\t\t\t\t$propagator->beginBatch();\n\t\t\t\t$scanner->scan($relativePath, $recursive, \\OC\\Files\\Cache\\Scanner::REUSE_ETAG | \\OC\\Files\\Cache\\Scanner::REUSE_SIZE);\n\t\t\t\t$cache = $storage->getCache();\n\t\t\t\tif ($cache instanceof Cache) {\n\t\t\t\t\t// only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner\n\t\t\t\t\t$cache->correctFolderSize($relativePath);\n\t\t\t\t}\n\t\t\t\t$propagator->commitBatch();\n\t\t\t} catch (StorageNotAvailableException $e) {\n\t\t\t\t$this->logger->error('Storage ' . $storage->getId() . ' not available', ['exception' => $e]);\n\t\t\t\t$this->emit('\\OC\\Files\\Utils\\Scanner', 'StorageNotAvailable', [$e]);\n\t\t\t}\n\t\t\tif ($this->useTransaction) {\n\t\t\t\t$this->db->commit();\n\t\t\t}\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function validateFieldSettings($fieldSettings)\n {\n $validationErrors = [];\n\n foreach ($fieldSettings as $name => $value) {\n if (isset($this->settingsSchema[$name])) {\n switch ($name) {\n case 'useSeconds':\n if (!is_bool($value)) {\n $validationErrors[] = new ValidationError(\n \"Setting 'Use seconds' value must be of boolean type\",\n null,\n [],\n \"[$name]\"\n );\n }\n break;\n case 'defaultType':\n $definedTypes = [\n self::DEFAULT_EMPTY,\n self::DEFAULT_CURRENT_DATE,\n self::DEFAULT_CURRENT_DATE_ADJUSTED,\n ];\n if (!in_array($value, $definedTypes, true)) {\n $validationErrors[] = new ValidationError(\n \"Setting 'Default value' is of unknown type\",\n null,\n [],\n \"[$name]\"\n );\n }\n break;\n case 'dateInterval':\n if (isset($value)) {\n if ($value instanceof DateInterval) {\n // String conversion of $value, because DateInterval objects cannot be compared directly\n if (\n isset($fieldSettings['defaultType'])\n && $fieldSettings['defaultType'] !== self::DEFAULT_CURRENT_DATE_ADJUSTED\n && $value->format('%y%m%d%h%i%s') !== '000000'\n ) {\n $validationErrors[] = new ValidationError(\n \"Setting 'Current date and time adjusted by' can be used only when setting 'Default value' is set to 'Adjusted current datetime'\",\n null,\n [],\n \"[$name]\"\n );\n }\n } else {\n $validationErrors[] = new ValidationError(\n \"Setting 'Current date and time adjusted by' value must be an instance of 'DateInterval' class\",\n null,\n [],\n \"[$name]\"\n );\n }\n }\n break;\n }\n } else {\n $validationErrors[] = new ValidationError(\n \"Setting '%setting%' is unknown\",\n null,\n ['%setting%' => $name],\n \"[$name]\"\n );\n }\n }\n\n return $validationErrors;\n }", "smellKey": "S3776", "smellId": null, "repo": "ibexa_core", "language": "php"} {"function": "public function preferences($prefs = '')\n {\n global $logged_in;\n if (empty($prefs)) {\n $prefs = $this->MedEx->getPreferences();\n }\n ?>\n <div class=\"row\">\n <div class=\"col-sm-12 text-center\">\n <div class=\"showRecalls\" id=\"show_recalls\">\n <div class=\"title\">MedEx <?php echo xlt('Preferences'); ?></div>\n <div name=\"div_response\" id=\"div_response\"><br />\n </div>\n <form action=\"#\" name=\"save_prefs\" id=\"save_prefs\">\n <div class=\"row\">\n <input type=\"hidden\" name=\"go\" id=\"go\" value=\"Preferences\" />\n <div class=\"col-sm-5 div-center offset-sm-1\" id=\"daform2\">\n <div class=\"divTable2\">\n <div class=\"divTableBody prefs\">\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\">MedEx <?php echo xlt('Username'); ?></div>\n <div class=\"divTableCell indent20\">\n <?php echo text($prefs['ME_username']); ?>\n </div>\n </div>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('General'); ?></div>\n <div class=\"divTableCell indent20\">\n <input type=\"checkbox\" class=\"update\" name=\"ME_hipaa_default_override\" id=\"ME_hipaa_default_override\" value=\"1\"\n <?php\n if ($prefs['ME_hipaa_default_override'] == '1') {\n echo 'checked =\"checked\"';\n }\n ?> />\n <label for=\"ME_hipaa_default_override\" class=\"input-helper input-helper--checkbox\"\n data-toggle='tooltip'\n data-placement='auto right'\n title='<?php echo xla('Default'); ?>: \"<?php echo xla('checked'); ?>\".\n <?php echo xla('When checked, messages are processed for patients with Patient Demographic Choice: \"Hipaa Notice Received\" set to \"Unassigned\" or \"Yes\". When unchecked, this choice must = \"YES\" to process the patient reminder. For patients with Choice =\"No\", Reminders will need to be processed manually.'); //or no translation... ?>'>\n <?php echo xlt('Assume patients receive HIPAA policy'); ?>\n </label>\n </div>\n </div>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Enable Facility'); ?></div>\n <div class=\"divTableCell indent20\">\n <?php\n $count = \"1\";\n $query = \"SELECT * FROM facility\";\n $result = sqlStatement($query);\n while ($fac = sqlFetchArray($result)) {\n $checked = \"\";\n if ($prefs) {\n $facs = explode('|', $prefs['ME_facilities']);\n foreach ($facs as $place) {\n if ($place == $fac['id']) {\n $checked = 'checked =\"checked\"';\n }\n }\n }\n ?>\n <input <?php echo $checked; ?> class=\"update\" type=\"checkbox\" name=\"facilities[]\" id=\"facility_<?php echo attr($fac['id']); ?>\" value=\"<?php echo attr($fac['id']); ?>\" />\n <label for=\"facility_<?php echo attr($fac['id']); ?>\"><?php echo text($fac['name']); ?></label><br /><?php\n }\n ?>\n </div>\n </div>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Included Providers'); ?></div>\n <div class=\"divTableCell indent20\">\n <?php\n $count = \"1\";\n $ures = sqlStatement(\"SELECT * FROM users WHERE authorized != 0 AND active = 1 ORDER BY lname, fname\");\n while ($prov = sqlFetchArray($ures)) {\n $checked = \"\";\n $suffix = \"\";\n if ($prefs) {\n $provs = explode('|', $prefs['ME_providers']);\n foreach ($provs as $doc) {\n if ($doc == $prov['id']) {\n $checked = 'checked =\"checked\"';\n }\n }\n }\n if (!empty($prov['suffix'])) {\n $suffix = ', ' . $prov['suffix'];\n }\n ?>\n <input <?php echo $checked; ?> class=\"update\" type=\"checkbox\" name=\"providers[]\" id=\"provider_<?php echo attr($prov['id']); ?>\" value=\"<?php echo attr($prov['id']); ?>\">\n <label for=\"provider_<?php echo attr($prov['id']); ?>\"><?php echo text($prov['fname']) . \" \" . text($prov['lname']) . text($suffix); ?></label><br /><?php\n }\n ?>\n </div>\n </div>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Labels'); ?></div>\n <div class=\"divTableCell indent20\">\n <input type=\"checkbox\" class=\"update\" name=\"LABELS_local\" id=\"LABELS_local\" value=\"1\" <?php if ($prefs['LABELS_local']) {\n echo \"checked='checked'\";} ?> />\n <label for=\"LABELS_local\" class=\"input-helper input-helper--checkbox\" data-toggle='tooltip' data-placement='auto' title='<?php echo xla('Check if you plan to use Avery Labels for Reminders or Recalls'); ?>'>\n <?php echo xlt('Use Avery Labels'); ?></label>\n <select class=\"update form-control ui-selectmenu-button ui-button ui-widget ui-selectmenu-button-closed ui-corner-all\" id=\"chart_label_type\" name=\"chart_label_type\">\n <option value='1' <?php if ($prefs['LABELS_choice'] == '1') {\n echo \"selected\";} ?>>5160</option>\n <option value='2' <?php if ($prefs['LABELS_choice'] == '2') {\n echo \"selected\";} ?>>5161</option>\n <option value='3' <?php if ($prefs['LABELS_choice'] == '3') {\n echo \"selected\";} ?>>5162</option>\n <option value='4' <?php if ($prefs['LABELS_choice'] == '4') {\n echo \"selected\";} ?>>5163</option>\n <option value='5' <?php if ($prefs['LABELS_choice'] == '5') {\n echo \"selected\";} ?>>5164</option>\n <option value='6' <?php if ($prefs['LABELS_choice'] == '6') {\n echo \"selected\";} ?>>8600</option>\n <option value='7' <?php if ($prefs['LABELS_choice'] == '7') {\n echo \"selected\";} ?>>L7163</option>\n <option value='8' <?php if ($prefs['LABELS_choice'] == '8') {\n echo \"selected\";} ?>>3422</option>\n </select>\n\n </div>\n </div>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Postcards'); ?></div>\n <div class=\"divTableCell indent20\">\n <!--\n <input type=\"checkbox\" class=\"update\" name=\"POSTCARDS_local\" id=\"POSTCARDS_local\" value=\"1\" <?php if ($prefs['POSTCARDS_local']) {\n echo \"checked='checked'\";} ?>\" />\n <label for=\"POSTCARDS_local\" name=\"POSTCARDS_local\" class=\"input-helper input-helper--checkbox\" data-toggle='tooltip' data-placement='auto' title='<?php echo xla('Check if you plan to print postcards locally'); ?>'><?php echo xlt('Print locally'); ?></label><br />\n <input type=\"checkbox\" class=\"update\" name=\"POSTCARDS_remote\" id=\"POSTCARDS_remote\" value=\"1\" <?php if ($prefs['POSTCARDS_remote']) {\n echo \"checked='checked'\";} ?>\" />\n <label for=\"POSTCARDS_remote\" name=\"POSTCARDS_remote\" class=\"input-helper input-helper--checkbox\" data-toggle='tooltip' data-placement='auto' title='<?php echo xla('Check if you plan to send postcards via MedEx'); ?>'><?php echo xlt('Print remotely'); ?></label>\n -->\n <label for=\"postcards_top\" data-toggle=\"tooltip\" data-placement=\"auto\" title=\"<?php echo xla('Custom text for Flow Board postcards. After changing text, print samples before printing mass quantities!'); ?>\"><u><?php echo xlt('Custom Greeting'); ?>:</u></label><br />\n <textarea rows=3 columns=70 id=\"postcard_top\" name=\"postcard_top\" class=\"update form-control\" style=\"font-weight:400;\"><?php echo nl2br(text($prefs['postcard_top'])); ?></textarea>\n </div>\n </div>\n <input type=\"hidden\" name=\"ME_username\" id=\"ME_username\" value=\"<?php echo attr($prefs['ME_username']);?>\" />\n <input type=\"hidden\" name=\"ME_api_key\" id=\"ME_api_key\" value=\"<?php echo attr($prefs['ME_api_key']);?>\" />\n </div>\n </div>\n </div>\n <div class=\"col-sm-5 div-center\" id=\"daform3\">\n <div class=\"divTable2\">\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Sync Frequency'); ?></div>\n <div class=\"divTableCell indent20\">\n <input name=\"execute_interval\"\n id=\"execute_interval\"\n class=\"form-control-range update\"\n min=\"0\" max=\"360\" step=\"1\"\n type=\"range\"\n value=\"<?php echo attr($prefs['execute_interval']); ?>\">\n <span id=\"active_sync\"><?php echo xlt('During the work-day, syncs occurs every'); ?>\n <span id=\"display_interval\"><?php echo text($prefs['execute_interval']); ?></span> <?php echo xlt('minutes'); ?>\n </span>\n <span id=\"paused\"><?php echo xlt(\"Synchronization with MedEx is paused\"); ?></span>\n </div>\n </div>\n <?php if (count($logged_in['products']['ordered']) > '0') { ?>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Enabled Services'); ?></div>\n <div class=\"divTableCell\">\n <ul>\n <?php\n foreach ($logged_in['products']['ordered'] as $service) {\n ?><li><a href=\"<?php echo $service['view']; ?>\" target=\"_medex\"><?php echo $service['model']; ?> </a></li>\n <?php echo $service['list'];\n } ?>\n </ul>\n </div>\n </div>\n <?php\n }\n if (!empty($logged_in['products']['not_ordered'])) {\n ?>\n <div class=\"divTableRow\">\n <div class=\"divTableCell divTableHeading\"><?php echo xlt('Available Services'); ?></div>\n <div class=\"divTableCell\">\n <ul>\n <?php\n foreach ($logged_in['products']['not_ordered'] as $service) {\n ?><li><a href=\"<?php echo $service['view']; ?>\" target=\"_medex\"><?php echo $service['model']; ?> </a></li>\n <?php\n if ($service['product_id'] == '54') {\n ?>\n <div style=\"margin-left: 10px;\">Appointment Reminders<br />Patient Recalls<br />SMS Bot<br />Go Green Messages</div>\n <?php\n }\n } ?>\n </ul>\n </div>\n </div>\n <?php\n } ?>\n\n </div>\n </div>\n </div>\n <div class=\"col-sm-1\"></div>\n <div class=\"clearfix text-center\" id=\"msg bottom\"><br />\n </div>\n </form>\n </div>\n </div>\n </div>\n <?php\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function simplexsolve2() {\n\t// arguments list -------------------------------------------------\n\t// 0 = simplex matrix\n\t// 1 = type\n\t// 2 = show fractions (0 or 1)\n\n\t// save start time -------------------------------------------------\n\t$starttime = microtime(true); // for function timing\n\n#region process arguments -----------------------------------------------\n\n\t$args = func_get_args();\n\tif (count($args)==0) {\n\t\techo \"Nothing to solve - no simplex matrix supplied.<br/>\\r\\n\";\n\t\treturn \"\";\n\t}\n\t$sm = $args[0];\n\n\tif(count($sm)<2) {\n\t\t// only 1 row\n\t\techo \"Error - a simplex matrix must have at least two rows.<br/>\\r\\n\";\n\t\treturn \"\";\n\t}\n\n\t// simplex type\n\tif((count($args)>1)&&(!is_null($args[1]))) {\n $type = verifytype(\"simplexsolve2\",$args[1],\"max\");\n\t} else {\n $type = \"max\";\n\t}\n\n\t// showfractions\n\tif((count($args)>2)&&(!is_null($args[2]))) {\n $showfractions = verifyshowfraction(\"simplexsolve2\",$args[2],1);\n\t} else {\n $showfractions = 1;\n\t}\n\n#endregion\n\n\t// Done processing arguments ---------------------------------------\n\t$simplexstack = array();\t\t// a stack of simplexset object that need to be pivoted on\n\t$simplexsets = array();\t\t\t// simplex list of matricies\n\t$objectivereached = array();\t// list of solution that have been optimized\n\t$sm = simplextoarray($sm);\t\t// make sure that all elements are fraction arrays\n\t$rows = 0;\t\t\t\t\t\t// set to the initial simplex matrix row\n\t$simplexsets[$rows] = null; // set initial condition\n\t$columns = 0;\t\t\t\t\t// set to the initial simplex matrix column\n\t$parentcolumn = $columns;\t\t// set to the current active column\n\t$exitwhile = FALSE;\t\t\t\t// flag to exit loop\n\t$popstack = FALSE;\t\t\t\t// flag to get an item from the stack\n\n\t// flag for simplexreadsolutionarray\n\t$ismixed = simplexhasmixedconstrants($sm);\n\n\t// step 1\n\t$solution = simplexreadsolutionarray($sm,$type,$showfractions,$ismixed);\n\n\t// step 2- is this a objective reached?\n\tif($solution[(count($solution)-1)]==\"Yes\") {\n\t\t$objectivereached[] = $solution;\n\t}\n\n\t//TODO - verify this for max mixed constraints\n\t//TODO - verify this for min mixed constraints\n\n\tdo {\n\t\t// check for mixed constraints\n $hasmixedconstraints = simplexhasmixedconstrants($sm);\n\n\t\t#region step 3 - get pivot points\n\n\t\t$pivots = NULL;\n\n\t\tif((!$popstack)&&($parentcolumn==$columns)) {\n // Need to find all pivot(s) for the simplex matrix\n $pivotpoint = NULL;\n\n\t\t\t// See if this is a mixed constraint simplex matrix\n if($hasmixedconstraints)\n\t\t\t{\n\t\t\t\t$pivotpointList\t = simplexfindpivotpointmixed($sm);\n $PivotPointCondition = $pivotpointList[0];\n $pivotpoints\t\t = $pivotpointList[1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$pivotpointList = simplexfindpivotpoint($sm);\n $PivotPointCondition = $pivotpointList[0];\n $pivotpoints\t= $pivotpointList[1];\n }\n }\n\t\telse {\n\t\t\t// use the pivot point from the stack\n\t\t\t$pivotpoint = $pivotpoints[0];\n }\n\n\t\t#endregion\n\n\t\t#region step 4 - test for no solution\n\t\tif ($PivotPointCondition == PivotPointNoSolution) {\n\t\t\t//\t\t\t\t\t\t\t\t parent column\n\t\t\t//\t\t\t\t\t\t\t\t , Pivot Point Condition\n\t\t\t//\t\t\t\t\t\t\t\t , pivot\n\t\t\t//\t\t\t\t\t\t\t\t , all pivot points\n\t\t\t//\t\t\t\t\t\t\t\t , simplex matrix\n\t\t\t//\t\t\t\t\t\t\t\t , soluiton\n if(!isset($simplexsets[$rows])) {\n $simplexsets[$rows] = array();\n\t\t\t}\n\t\t\t//2021-03-29 fixed typo row-->rows\n\t\t\t$simplexsets[$rows][$columns] = array($parentcolumn, $PivotPointCondition, NULL, NULL, $sm, $solution);\n\t\t\t$exitwhile = TRUE;\n\t\t\tbreak;\n\t\t}\n\n\t\t#endregion\n\n\t\t#region step 5 - count the number of pivots points and add to stack if needed\n\n\t\tif(count($pivotpoints) > 1) {\n\t\t\t// add the multiple pivot point matrix to the output\n\t\t\tif(!isset($simplexsets[$rows])) {\n $simplexsets[$rows] = array();\n\t\t\t}\n\n\t\t\t// parent column, pivot, all pivot points, simplex matrix, soluiton\n\t\t\t$simplexsets[$rows++][$columns] = array($parentcolumn, $PivotPointCondition, NULL, $pivotpoints, $sm, $solution);\n\n\t\t\t// push all extra pivot points to the stack the zero number will be processes this round\n\t\t\t$i = 1;\n\t\t\twhile ($i <count($pivotpoints)):\n // might need to keep all possible pivot points on the stack?\n array_push($simplexstack, array($rows, $parentcolumn, $PivotPointCondition, $pivotpoints[$i], $sm, $solution) );\n $i++;\n\t\t\tendwhile;\n\n\t\t\t// override defaults\n\t\t\t$pivotpoint = $pivotpoints[0];\n\t\t\t$pivots = $pivotpoints;\n\t\t} elseif(count($pivotpoints) == 1) {\n\t\t\tif($parentcolumn==$columns) {\n\t\t\t\t$pivotpoint = $pivotpoints[0];\n\t\t\t}\n\t\t}\n\n\t\t#endregion\n\n\t\t#region step 6 - add to $simplexsets (parent column, pivot, all pivot points, simplex matrix, solution)\n\n if(array_key_exists($rows, $simplexsets)) {\n\t\t\tif(is_null($simplexsets[$rows])) {\n\t\t\t\t$simplexsets[] = array();\n }\n } else {\n $simplexsets[] = array();\n }\n\n\t\t$simplexsets[$rows][$columns] = array($parentcolumn, $PivotPointCondition, $pivotpoint, $pivots, $sm, $solution);\n\n\t\t// add one to the rows\n\t\t$rows++;\n\n\t\t#endregion\n\n\t\t// step 7 - set the $parentcolumn to the current column\n\t\t$parentcolumn = $columns;\n\n\t\t#region step 8 - pivot if possible\n\n\t\tif (!is_null($pivotpoint)) {\n\t\t\t$sm = simplexpivot($sm,$pivotpoint);\n\t\t\t$solution = simplexreadsolutionarray($sm,$type,$showfractions,$ismixed);\n\t\t}\n\n\t\t#endregion\n\n\t\t// step 9 - set to not pop off the stack\n\t\t$popstack = FALSE;\n\n\t\t#region step 10 test pivot point type (Multiple solutions, one solution, or no solutions)\n\n\t\tif ($PivotPointCondition == PivotPointFoundMultipleSolutionList) {\n\n\t\t\t// add the result of the pivot\n\t\t\t$simplexsets[$rows++][$columns] = array($parentcolumn, $PivotPointCondition, $pivotpoint, $pivots, $sm, $solution);\n\n\t\t\t// compare the new solution found in step 8 above to all previous solutions\n\t\t\t// and see if it is unique\n\t\t\tif(simplexfindsolutioninlist($objectivereached,$solution)==1) {\n\t\t\t\t// solution is already in the list return the results\n\t\t\t\t$popstack = true;\n\t\t\t} else {\n\t\t\t\t$objectivereached[count($objectivereached)] = $solution;\n\t\t\t}\n\t\t} elseif ($PivotPointCondition == PivotPointNone) {\n\t\t\t$popstack = true;\n\t\t} elseif ($PivotPointCondition == PivotPointFoundList) {\n\t\t\t// is this a objective reached?\n\t\t\tif($solution[(count($solution)-1)]==\"Yes\") {\n\t\t\t\tif(simplexfindsolutioninlist($objectivereached,$solution)==1) {\n\t\t\t\t\t// solution is already in the list return the results - don't save it'\n\t\t\t\t} else {\n\t\t\t\t\t$objectivereached[count($objectivereached)] = $solution;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t#endregion\n\n\t\t#region step 11 - do we need to pop the stack?\n\n\t\tif($popstack) {\n\t\t\t// is there any item in the stack?\n\t\t\tif(count($simplexstack) > 0) {\n\n\t\t\t\t// pop the Stack and set the variables\n\t\t\t\t$stack = array_pop($simplexstack);\n\t\t\t\t$rows = $stack[0];\n\t\t\t\t$parentcolumn = $stack[1];\n\t\t\t\t$PivotPointCondition = $stack[2];\n\t\t\t\t$pivotpoints = array(); // clear\n\t\t\t\t$pivotpoints[0] = $stack[3];\n\t\t\t\t$pivotpoint = $stack[3];\n\t\t\t\t$sm= $stack[4];\n\t\t\t\t$solution = $stack[5];\n\n\t\t\t\t$columns++;\n\t\t\t} else {\n\t\t\t\t$exitwhile = TRUE;\n\t\t\t}\n\t\t}\n\n\t\t#endregion\n\n\t\t// this is here to prevent a run away loop\n\t\tif(($rows > 30)||($columns>30)) {\n\t\t\t// failsafe - tripped\n\t\t\t$exitwhile = TRUE;\n }\n\n\t} while (!$exitwhile);\n\n\t// make sure there are no missing array elements from the above\n\t// creation of the jagged array\n\tif($columns>0){\n\t\tfor($r = 0,$size = count($simplexsets); $r < $size; $r++){\n\t\t\tfor($c = 0; $c < $columns; $c++){\n\t\t\t\t$temp = $simplexsets[$r];\n\n\t\t\t\tif(!isset($temp[$c])) {\n\t\t\t\t\t$simplexsets[$r][$c] = NULL; // this avoids Undefined offset errors by assigning each element NULL\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\t$r = count($simplexsets)-1;\n\t\twhile($r>=0){\n\t\t\tif(count($simplexsets[$r])==0) {\n\t\t\t\t// row is empty\n\t\t\t\tunset($simplexsets[$r]);\n\t\t\t\t$r--;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\treturn array($simplexsets, simplexsolutionconverttofraction($objectivereached), (microtime(true)-$starttime), $objectivereached);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "final public static function generateTrustedXml()\n {\n $modules_on_disk = Module::getModulesDirOnDisk();\n $trusted = array();\n $untrusted = array();\n\n $trusted_modules_xml = array(\n _PS_ROOT_DIR_.self::CACHE_FILE_ALL_COUNTRY_MODULES_LIST,\n _PS_ROOT_DIR_.self::CACHE_FILE_MUST_HAVE_MODULES_LIST,\n );\n\n if (file_exists(_PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST)) {\n $trusted_modules_xml[] = _PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST;\n }\n\n // Create 2 arrays with trusted and untrusted modules\n foreach ($trusted_modules_xml as $file) {\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $trusted[] = Tools::strtolower((string)$modaddons->name);\n }\n }\n }\n\n foreach (glob(_PS_ROOT_DIR_.'/config/xml/themes/*.xml') as $theme_xml) {\n if (file_exists($theme_xml)) {\n $content = Tools::file_get_contents($theme_xml);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml) {\n foreach ($xml->modules->module as $modaddons) {\n if ((string)$modaddons['action'] == 'install') {\n $trusted[] = Tools::strtolower((string)$modaddons['name']);\n }\n }\n }\n }\n }\n\n foreach ($modules_on_disk as $name) {\n if (!in_array($name, $trusted)) {\n if (Module::checkModuleFromAddonsApi($name)) {\n $trusted[] = Tools::strtolower($name);\n } else {\n $untrusted[] = Tools::strtolower($name);\n }\n }\n }\n\n $context = Context::getContext();\n\n // Save the 2 arrays into XML files\n $trusted_xml = new SimpleXMLElement('<modules_list/>');\n $trusted_xml->addAttribute('theme', $context->shop->theme->getName());\n $modules = $trusted_xml->addChild('modules');\n $modules->addAttribute('type', 'trusted');\n foreach ($trusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success = file_put_contents(_PS_ROOT_DIR_.self::CACHE_FILE_TRUSTED_MODULES_LIST, $trusted_xml->asXML());\n\n $untrusted_xml = new SimpleXMLElement('<modules_list/>');\n $modules = $untrusted_xml->addChild('modules');\n $modules->addAttribute('type', 'untrusted');\n foreach ($untrusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success &= file_put_contents(_PS_ROOT_DIR_.self::CACHE_FILE_UNTRUSTED_MODULES_LIST, $untrusted_xml->asXML());\n\n if ($success) {\n return true;\n } else {\n Context::getContext()->getTranslator()->trans('Trusted and Untrusted XML have not been generated properly', array(), 'Admin.Modules.Notification');\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct(array $params)\n {\n if (isset($params['handler'])) {\n if (! $params['handler'] instanceof AbstractStorage) {\n throw new Exception\\InvalidArgumentException('handler is not a valid mail handler');\n }\n if (! isset($params['id'])) {\n throw new Exception\\InvalidArgumentException('need a message id with a handler');\n }\n\n $this->mail = $params['handler'];\n $this->messageNum = $params['id'];\n }\n\n $params['strict'] ??= false;\n\n if (isset($params['raw'])) {\n Mime\\Decode::splitMessage(\n $params['raw'],\n $this->headers,\n $this->content,\n Mime\\Mime::LINEEND,\n $params['strict']\n );\n } elseif (isset($params['headers'])) {\n if (is_array($params['headers'])) {\n $this->headers = new Headers();\n $this->headers->addHeaders($params['headers']);\n } else {\n if (empty($params['noToplines'])) {\n Mime\\Decode::splitMessage($params['headers'], $this->headers, $this->topLines);\n } else {\n $this->headers = Headers::fromString($params['headers']);\n }\n }\n\n if (isset($params['content'])) {\n $this->content = $params['content'];\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function createUrl(\n $route_id,\n $id_lang = null,\n array $params = [],\n $force_routes = false,\n $anchor = '',\n $id_shop = null\n ) {\n if ($id_lang === null) {\n $id_lang = (int) Context::getContext()->language->id;\n }\n if ($id_shop === null) {\n $id_shop = (int) Context::getContext()->shop->id;\n }\n\n if (!isset($this->routes[$id_shop])) {\n $this->loadRoutes($id_shop);\n }\n\n if (!isset($this->routes[$id_shop][$id_lang][$route_id])) {\n $query = http_build_query($params, '', '&');\n $index_link = $this->use_routes ? '' : 'index.php';\n\n return ($route_id == 'index') ? $index_link . (($query) ? '?' . $query : '') :\n ((trim($route_id) == '') ? '' : 'index.php?controller=' . $route_id) . (($query) ? '&' . $query : '') . $anchor;\n }\n $route = $this->routes[$id_shop][$id_lang][$route_id];\n // Check required fields\n $query_params = isset($route['params']) ? $route['params'] : [];\n foreach ($route['keywords'] as $key => $data) {\n if (!$data['required']) {\n continue;\n }\n\n if (!array_key_exists($key, $params)) {\n throw new PrestaShopException('Dispatcher::createUrl() miss required parameter \"' . $key . '\" for route \"' . $route_id . '\"');\n }\n if (isset($this->default_routes[$route_id])) {\n $query_params[$this->default_routes[$route_id]['keywords'][$key]['param']] = $params[$key];\n }\n }\n\n // Build an url which match a route\n if ($this->use_routes || $force_routes) {\n $url = $route['rule'];\n $add_param = [];\n\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key])) {\n if (!isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_param[$key] = $value;\n }\n } else {\n if ($params[$key]) {\n $parameter = $params[$key];\n if (is_array($parameter)) {\n if (array_key_exists($id_lang, $parameter)) {\n $parameter = $parameter[$id_lang];\n } else {\n // made the choice to return the first element of the array\n $parameter = reset($parameter);\n }\n }\n $replace = $route['keywords'][$key]['prepend'] . $parameter . $route['keywords'][$key]['append'];\n } else {\n $replace = '';\n }\n $url = preg_replace('#\\{([^{}]*:)?' . $key . '(:[^{}]*)?\\}#', $replace, $url);\n }\n }\n $url = preg_replace('#\\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\\}#', '', $url);\n if (count($add_param)) {\n $url .= '?' . http_build_query($add_param, '', '&');\n }\n } else {\n // Build a classic url index.php?controller=foo&...\n $add_params = [];\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key]) && !isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_params[$key] = $value;\n }\n }\n\n if (!empty($route['controller'])) {\n $query_params['controller'] = $route['controller'];\n }\n $query = http_build_query(array_merge($add_params, $query_params), '', '&');\n if ($this->multilang_activated) {\n $query .= (!empty($query) ? '&' : '') . 'id_lang=' . (int) $id_lang;\n }\n $url = 'index.php?' . $query;\n }\n\n return $url . $anchor;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function writeContentTypes(PHPExcel $pPHPExcel = null, $includeCharts = FALSE)\n\t{\n\t\t// Create XML writer\n\t\t$objWriter = null;\n\t\tif ($this->getParentWriter()->getUseDiskCaching()) {\n\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());\n\t\t} else {\n\t\t\t$objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);\n\t\t}\n\n\t\t// XML header\n\t\t$objWriter->startDocument('1.0','UTF-8','yes');\n\n\t\t// Types\n\t\t$objWriter->startElement('Types');\n\t\t$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');\n\n\t\t\t// Theme\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'\n\t\t\t);\n\n\t\t\t// Styles\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'\n\t\t\t);\n\n\t\t\t// Rels\n\t\t\t$this->_writeDefaultContentType(\n\t\t\t\t$objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'\n\t\t\t);\n\n\t\t\t// XML\n\t\t\t$this->_writeDefaultContentType(\n\t\t\t\t$objWriter, 'xml', 'application/xml'\n\t\t\t);\n\n\t\t\t// VML\n\t\t\t$this->_writeDefaultContentType(\n\t\t\t\t$objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'\n\t\t\t);\n\n\t\t\t// Workbook\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'\n\t\t\t);\n\n\t\t\t// DocProps\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'\n\t\t\t);\n\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'\n\t\t\t);\n\n\t\t\t$customPropertyList = $pPHPExcel->getProperties()->getCustomProperties();\n\t\t\tif (!empty($customPropertyList)) {\n\t\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t\t$objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Worksheets\n\t\t\t$sheetCount = $pPHPExcel->getSheetCount();\n\t\t\tfor ($i = 0; $i < $sheetCount; ++$i) {\n\t\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t\t$objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Shared strings\n\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t$objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'\n\t\t\t);\n\n\t\t\t// Add worksheet relationship content types\n\t\t\t$chart = 1;\n\t\t\tfor ($i = 0; $i < $sheetCount; ++$i) {\n\t\t\t\t$drawings = $pPHPExcel->getSheet($i)->getDrawingCollection();\n\t\t\t\t$drawingCount = count($drawings);\n\t\t\t\t$chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0;\n\n\t\t\t\t//\tWe need a drawing relationship for the worksheet if we have either drawings or charts\n\t\t\t\tif (($drawingCount > 0) || ($chartCount > 0)) {\n\t\t\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t\t\t$objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t//\tIf we have charts, then we need a chart relationship for every individual chart\n\t\t\t\tif ($chartCount > 0) {\n\t\t\t\t\tfor ($c = 0; $c < $chartCount; ++$c) {\n\t\t\t\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t\t\t\t$objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Comments\n\t\t\tfor ($i = 0; $i < $sheetCount; ++$i) {\n\t\t\t\tif (count($pPHPExcel->getSheet($i)->getComments()) > 0) {\n\t\t\t\t\t$this->_writeOverrideContentType(\n\t\t\t\t\t\t$objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add media content-types\n\t\t\t$aMediaContentTypes = array();\n\t\t\t$mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();\n\t\t\tfor ($i = 0; $i < $mediaCount; ++$i) {\n\t\t\t\t$extension \t= '';\n\t\t\t\t$mimeType \t= '';\n\n\t\t\t\tif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {\n\t\t\t\t\t$extension \t= strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());\n\t\t\t\t\t$mimeType \t= $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() );\n\t\t\t\t} else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {\n\t\t\t\t\t$extension \t= strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());\n\t\t\t\t\t$extension \t= explode('/', $extension);\n\t\t\t\t\t$extension \t= $extension[1];\n\n\t\t\t\t\t$mimeType \t= $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();\n\t\t\t\t}\n\n\t\t\t\tif (!isset( $aMediaContentTypes[$extension]) ) {\n\t\t\t\t\t\t$aMediaContentTypes[$extension] = $mimeType;\n\n\t\t\t\t\t\t$this->_writeDefaultContentType(\n\t\t\t\t\t\t\t$objWriter, $extension, $mimeType\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t$sheetCount = $pPHPExcel->getSheetCount();\n\t\t\tfor ($i = 0; $i < $sheetCount; ++$i) {\n\t\t\t\tif (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) {\n\t\t\t\t\tforeach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) {\n\t\t\t\t\t\tif (!isset( $aMediaContentTypes[strtolower($image->getExtension())]) ) {\n\t\t\t\t\t\t\t$aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType( $image->getPath() );\n\n\t\t\t\t\t\t\t$this->_writeDefaultContentType(\n\t\t\t\t\t\t\t\t$objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t$objWriter->endElement();\n\n\t\t// Return\n\t\treturn $objWriter->getData();\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function action_edit()\n {\n $id = $this->request->param('id');\n $roles = self::getRoleOptions($this->pixie);\n\n if ($this->request->method == 'POST') {\n $user = null;\n if ($id) {\n /** @var BaseModel $user */\n $user = $this->pixie->orm->get($this->model->model_name, $id);\n }\n\n if (!$user || !$user->loaded()) {\n throw new NotFoundException();\n }\n\n $data = $this->request->post();\n $this->processRequestFilesForItem($user, $data);\n $user->values($user->filterValues($data));\n $user->save();\n\n $requestUserRoles = $data['roles'] ?: [];\n $userRoles = array_intersect_key($roles, array_flip($requestUserRoles));\n\n foreach ($this->pixie->orm->get('role')->find_all() as $role) {\n if (array_key_exists($role->id(), $userRoles)) {\n $user->add('roles', $role);\n } else {\n $user->remove('roles', $role);\n }\n }\n\n if ($user->loaded()) {\n $this->redirect('/admin/' . strtolower($user->model_name) . '/edit/'.$user->id());\n return;\n }\n\n } else {\n\n if (!$id) {\n throw new NotFoundException();\n }\n\n $user = $this->pixie->orm->get($this->model->model_name, $id);\n if (!$user || !$user->loaded()) {\n throw new NotFoundException();\n }\n }\n\n $editFields = $this->prepareEditFields();\n $this->view->pageTitle = $this->modelName;\n $this->view->pageHeader = $this->view->pageTitle;\n $this->view->modelName = $this->model->model_name;\n $this->view->item = $user;\n $this->view->editFields = $editFields;\n $this->view->formatter = new FieldFormatter($user, $editFields);\n $this->view->formatter->setPixie($this->pixie);\n\n $this->view->roles = self::getRoleOptions($this->pixie);\n $this->view->subview = 'user/edit';\n $this->view->userRoles = $this->getUserRolesOptions($user);\n }", "smellKey": "S3776", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "public function addCSS($css_uri, $css_media_type = 'all', $offset = null, $check_path = true)\n {\n if (!is_array($css_uri)) {\n $css_uri = array($css_uri);\n }\n\n foreach ($css_uri as $css_file => $media) {\n if (is_string($css_file) && strlen($css_file) > 1) {\n if ($check_path) {\n $css_path = Media::getCSSPath($css_file, $media);\n } else {\n $css_path = array($css_file => $media);\n }\n } else {\n if ($check_path) {\n $css_path = Media::getCSSPath($media, $css_media_type);\n } else {\n $css_path = array($media => $css_media_type);\n }\n }\n\n $key = is_array($css_path) ? key($css_path) : $css_path;\n if ($css_path && (!isset($this->css_files[$key]) || ($this->css_files[$key] != reset($css_path)))) {\n $size = count($this->css_files);\n if ($offset === null || $offset > $size || $offset < 0 || !is_numeric($offset)) {\n $offset = $size;\n }\n\n $this->css_files = array_merge(array_slice($this->css_files, 0, $offset), $css_path, array_slice($this->css_files, $offset));\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct()\n {\n $this->algo = $GLOBALS['gbl_auth_hash_algo'];\n\n // If SHA512HASH is selected, then ensure CRYPT_SHA512 is supported\n if ($this->algo == \"SHA512HASH\") {\n if (CRYPT_SHA512 != 1) {\n $this->algo == \"DEFAULT\";\n error_log(\"OpenEMR WARNING: SHA512HASH not supported, so using DEFAULT instead\");\n }\n }\n\n // If set to php default algorithm, then figure out what it is.\n // This basically resolves what PHP is using as PASSWORD_DEFAULT,\n // which has been PASSWORD_BCRYPT since PHP 5.5. In future PHP versions,\n // though, it will likely change to one of the Argon2 algorithms. And\n // in this case, the below block of code will automatically support this\n // transition.\n if ($this->algo == \"DEFAULT\") {\n if (PASSWORD_DEFAULT == PASSWORD_BCRYPT) {\n $this->algo = \"BCRYPT\";\n } elseif (PASSWORD_DEFAULT == PASSWORD_ARGON2I) {\n $this->algo = \"ARGON2I\";\n } elseif (PASSWORD_DEFAULT == PASSWORD_ARGON2ID) {\n $this->algo = \"ARGON2ID\";\n } elseif (PASSWORD_DEFAULT == \"\") {\n // In theory, should never get here, however:\n // php 7.4 changed to using strings rather than integers for these constants\n // and notably appears to have left PASSWORD_DEFAULT blank in several php 7.4\n // releases rather than setting it to a default (this was fixed in php8).\n // So, in this situation, best to default to php 7.4 default protocol\n // (since will only get here in php 7.4), which is BCRYPT.\n $this->algo = \"BCRYPT\";\n } else {\n // $this->algo will stay \"DEFAULT\", which should never happen.\n // But if this does happen, will then not support any custom\n // options in below code since not sure what the algorithm is.\n }\n }\n\n // Ensure things don't break by only using a supported algorithm\n if (($this->algo == \"ARGON2ID\") && (!defined('PASSWORD_ARGON2ID'))) {\n // argon2id not supported, so will try argon2i instead\n $this->algo = \"ARGON2I\";\n error_log(\"OpenEMR WARNING: ARGON2ID not supported, so using ARGON2I instead\");\n }\n if (($this->algo == \"ARGON2I\") && (!defined('PASSWORD_ARGON2I'))) {\n // argon2i not supported, so will use bcrypt instead\n $this->algo = \"BCRYPT\";\n error_log(\"OpenEMR WARNING: ARGON2I not supported, so using BCRYPT instead\");\n }\n\n // Now can safely set up the algorithm and algorithm options\n if (($this->algo == \"ARGON2ID\") || ($this->algo == \"ARGON2I\")) {\n // Argon2\n if ($this->algo == \"ARGON2ID\") {\n // Using argon2ID\n $this->algo_constant = PASSWORD_ARGON2ID;\n }\n if ($this->algo == \"ARGON2I\") {\n // Using argon2I\n $this->algo_constant = PASSWORD_ARGON2I;\n }\n // Set up Argon2 options\n $temp_array = [];\n if (($GLOBALS['gbl_auth_argon_hash_memory_cost'] != \"DEFAULT\") && (check_integer($GLOBALS['gbl_auth_argon_hash_memory_cost']))) {\n $temp_array['memory_cost'] = $GLOBALS['gbl_auth_argon_hash_memory_cost'];\n }\n if (($GLOBALS['gbl_auth_argon_hash_time_cost'] != \"DEFAULT\") && (check_integer($GLOBALS['gbl_auth_argon_hash_time_cost']))) {\n $temp_array['time_cost'] = $GLOBALS['gbl_auth_argon_hash_time_cost'];\n }\n if (($GLOBALS['gbl_auth_argon_hash_thread_cost'] != \"DEFAULT\") && (check_integer($GLOBALS['gbl_auth_argon_hash_thread_cost']))) {\n $temp_array['threads'] = $GLOBALS['gbl_auth_argon_hash_thread_cost'];\n }\n if (!empty($temp_array)) {\n $this->options = $temp_array;\n }\n } elseif ($this->algo == \"BCRYPT\") {\n // Bcrypt - Using bcrypt and set up bcrypt options\n $this->algo_constant = PASSWORD_BCRYPT;\n if (($GLOBALS['gbl_auth_bcrypt_hash_cost'] != \"DEFAULT\") && (check_integer($GLOBALS['gbl_auth_bcrypt_hash_cost']))) {\n $this->options = ['cost' => $GLOBALS['gbl_auth_bcrypt_hash_cost']];\n }\n } elseif ($this->algo == \"SHA512HASH\") {\n // SHA512HASH - Using crypt and set up crypt option for this algo\n $this->algo_constant = $this->algo;\n if (check_integer($GLOBALS['gbl_auth_sha512_rounds'])) {\n $this->options = ['rounds' => $GLOBALS['gbl_auth_sha512_rounds']];\n } else {\n $this->options = ['rounds' => 100000];\n }\n } else {\n // This should never happen.\n // Will only happen if unable to map the DEFAULT setting above or if using a invalid setting other than\n // BCRYPT, ARGON2I, or ARGON2ID.\n // If this happens, then will just go with PHP Default (ie. go with default php algorithm and options).\n $this->algo_constant = PASSWORD_DEFAULT;\n error_log(\"OpenEMR WARNING: Unable to resolve hashing preference, so using PHP Default\");\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getByUrl(string $url): ?Document\n {\n $urlParts = parse_url($url);\n $document = null;\n\n if ($urlParts['path']) {\n $document = Document::getByPath($urlParts['path']);\n\n // search for a page in a site\n if (!$document && isset($urlParts['host'])) {\n $sitesList = new Model\\Site\\Listing();\n $sitesObjects = $sitesList->load();\n\n foreach ($sitesObjects as $site) {\n if ($site->getRootDocument() && (in_array($urlParts['host'], $site->getDomains()) || $site->getMainDomain() == $urlParts['host'])) {\n if ($document = Document::getByPath($site->getRootDocument() . $urlParts['path'])) {\n break;\n }\n }\n }\n }\n }\n\n return $document;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function ASplot($function) {\n\tif (!$this->isinit) {$this->ASinitPicture();}\n\t$funcstr = implode(',',$function);\n\t/* safety check now in mathphp\n\tpreg_match_all('/[a-zA-Z]+/',$funcstr,$matches,PREG_PATTERN_ORDER);\n\t$okfunc = array('sin','cos','tan','sec','csc','cot','arcsin','arccos','arctan','x','t','log','ln','e','pi','abs','sqrt','safepow');\n\tforeach ($matches[0] as $m) {\n\t\tif (!in_array($m,$okfunc)) { echo \"$m\"; return;}\n\t} //do safety check, as this will be eval'ed\n\t*/\n\t//$function = explode(',',str_replace(array('\"','\\'',';'),'',$function));\n\t$function = str_replace(array('\"','\\'',';'),'',$function);\n\tif (strpos($function[0],'[')===0) {\n\t\t$funcp = explode(',',$function[0]);\n\t\t$isparametric = true;\n\t\t$xfunc = str_replace(\"[\",\"\",$funcp[0]);\n\t\t$exfunc = makeMathFunction($xfunc, \"t\");\n\t\t$yfunc = str_replace(\"]\",\"\",$funcp[1]);\n\t\t$eyfunc = makeMathFunction($yfunc, \"t\");\n if ($exfunc === false || $eyfunc === false) {\n return;\n }\n\t} else {\n\t\t$isparametric = false;\n\t\t$efunc = makeMathFunction($function[0], \"x\");\n if ($efunc === false) {\n return;\n }\n\t}\n\t$avoid = array();\n\tif (isset($function[1]) && $function[1]!='' && $function[1]!='null') {\n\t\t$xmin = $this->evalifneeded($function[1]);\n\t} else {\n\t\t$xmin = $this->xmin - min($this->border[0],5)/$this->xunitlength;\n\t}\n\tif (isset($function[2]) && $function[2]!='' && $function[2]!='null') {\n\t\t$xmaxarr = explode('!',$function[2]);\n\t\t$xmax = $this->evalifneeded($xmaxarr[0]);\n\t\t$avoid = array_slice($xmaxarr,1);\n\t} else {\n\t\t$xmax = $this->xmax + min($this->border[2],5)/$this->xunitlength;\n\t}\n\t$xmin += ($xmax - $xmin)/100000; //avoid divide by zero errors\n\tif (isset($function[3]) && $function[3]!='' && $function[3]!='null') {\n\t\t$dx = ($xmax - $xmin)/($function[3]-1);\n\t\t$stopat = $function[3];\n\t} else {\n\t\t$dx = ($xmax - $xmin)/100;\n\t\t$stopat = 101;\n\t}\n\t$yymax = $this->ymax + $this->border[3]/$this->yunitlength;\n\t$yymin = $this->ymin - $this->border[1]/$this->yunitlength;\n\t$px = null;\n\t$py = null;\n\t$lasty = 0;\n\t$lastl = 0;\n\n\tfor ($i = 0; $i<$stopat;$i++) {\n\n\t\tif ($isparametric) {\n\t\t\t$t = $xmin + $dx*$i;\n\t\t\tif (in_array($t,$avoid)) { continue;}\n\t\t\t$x = $exfunc(['t'=>$t]);\n\t\t\t$y = $eyfunc(['t'=>$t]);\n\t\t\tif (is_infinite($x) || is_infinite($y) || is_nan($x) || is_nan($y)) { continue; }\n\t\t} else {\n\t\t\t$x = $xmin + $dx*$i;\n\t\t\tif (in_array($x,$avoid)) { continue;}\n\t\t\t$y = $efunc(['x'=>$x]);\n\t\t\tif (is_infinite($y) || is_nan($y)) { continue;}\n\t\t}\n\t\tif ($i<2 || $i==$stopat-2) {\n\t\t\t$fx[$i] = $x;\n\t\t\t$fy[$i] = $y;\n\t\t}\n\t\t$lastx = $x;\n\t\t/*if (abs($y-$lasty) > ($this->ymax-$this->ymin)) {\n\t\t\tif ($lastl > 1) { $lastl = 0; }//break path\n\t\t\t$lasty = $y;\n\t\t} else {\n\n\t\t\t$lasty = $y;\n\t\t\tif ($lastl > 0) {\n\t\t\t\t$this->ASline(array(\"[$px,$py]\",\"[$x,$y]\"));\n\t\t\t}\n\t\t\t$px = $x;\n\t\t\t$py = $y;\n\n\t\t\t$lastl++;\n\t\t}*/\n\t\tif ($py===null) { //starting line\n\n\t\t} else if ($y>$yymax || $y<$yymin) { //going or still out of bounds\n\t\t\tif ($py <= $yymax && $py >= $yymin) { //going out\n\t\t\t\tif ($yymax-$py < .5*($yymax-$yymin)) { //closer to top\n\t\t\t\t\t$iy = $yymax;\n\t\t\t\t\t//if jumping from top of graph to bottom, change value\n\t\t\t\t\t//for interpolation purposes\n\t\t\t\t\tif ($y<$yymin) { $y = $yymax+.5*($yymax-$yymin);}\n\t\t\t\t} else { //going down\n\t\t\t\t\t$iy = $yymin;\n\t\t\t\t\tif ($y>$yymax) { $y = $yymin-.5*($yymax-$yymin);}\n\t\t\t\t}\n\t\t\t\t$ix = ($x-$px)*($iy - $py)/($y-$py) + $px;\n\t\t\t\t$this->ASline(array(\"[$px,$py]\",\"[$ix,$iy]\"));\n\t\t\t} else { //still out\n\n\t\t\t}\n\t\t} else if ($py>$yymax || $py<$yymin) { //coming or staying in bounds?\n\t\t\tif ($y <= $yymax && $y >= $yymin) { //coming in\n\t\t\t\tif ($yymax-$y < .5*($yymax-$yymin)) { //closer to top\n\t\t\t\t\t$iy = $yymax;\n\t\t\t\t\tif ($py<$yymin) { $py = $yymax+.5*($ymax-$ymin);}\n\t\t\t\t} else { //coming from bottom\n\t\t\t\t\t$iy = $yymin;\n\t\t\t\t\tif ($py>$yymax) { $py = $yymin-.5*($ymax-$ymin);}\n\t\t\t\t}\n\t\t\t\t$ix = ($x-$px)*($iy - $py)/($y-$py) + $px;\n\t\t\t\t$this->ASline(array(\"[$ix,$iy]\",\"[$x,$y]\"));\n\t\t\t} else { //still out\n\n\t\t\t}\n\t\t} else { //all in\n\t\t\t$this->ASline(array(\"[$px,$py]\",\"[$x,$y]\"));\n\t\t}\n\t\t$px = $x;\n\t\t$py = $y;\n\t}\n\tif (isset($function[5]) && $function[5]!='' && $function[5]!='null') {\n\t\tif ($function[5]==1) {\n\t\t\t//need pt2arr for xunit adjust\n\t\t\t$this->ASarrowhead(\"{$fx[1]},{$fy[1]}\",\"{$fx[0]},{$fy[0]}\");\n\t\t} else if ($function[5]==2) {\n\t\t\t$this->ASdot2(array(\"[{$fx[0]},{$fy[0]}]\",\"open\"));\n\t\t} else if ($function[5]==3) {\n\t\t\t$this->ASdot2(array(\"[{$fx[0]},{$fy[0]}]\",\"closed\"));\n\t\t}\n\t}\n\tif (isset($function[6]) && $function[6]!='' && $function[6]!='null') {\n\t\tif ($function[6]==1) {\n\t\t\t$this->ASarrowhead(\"{$fx[$stopat-2]},{$fy[$stopat-2]}\",\"$x,$y\");\n\t\t} else if ($function[6]==2) {\n\t\t\t$this->ASdot2(array(\"[$x,$y]\",\"open\"));\n\t\t} else if ($function[6]==3) {\n\t\t\t$this->ASdot2(array(\"[$x,$y]\",\"closed\"));\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<PlanDefinitionAction xmlns=\"http://hl7.org/fhir\"></PlanDefinitionAction>');\n }\n parent::xmlSerialize(true, $sxe);\n if (isset($this->prefix)) {\n $this->prefix->xmlSerialize(true, $sxe->addChild('prefix'));\n }\n if (isset($this->title)) {\n $this->title->xmlSerialize(true, $sxe->addChild('title'));\n }\n if (isset($this->description)) {\n $this->description->xmlSerialize(true, $sxe->addChild('description'));\n }\n if (isset($this->textEquivalent)) {\n $this->textEquivalent->xmlSerialize(true, $sxe->addChild('textEquivalent'));\n }\n if (isset($this->priority)) {\n $this->priority->xmlSerialize(true, $sxe->addChild('priority'));\n }\n if (0 < count($this->code)) {\n foreach ($this->code as $code) {\n $code->xmlSerialize(true, $sxe->addChild('code'));\n }\n }\n if (0 < count($this->reason)) {\n foreach ($this->reason as $reason) {\n $reason->xmlSerialize(true, $sxe->addChild('reason'));\n }\n }\n if (0 < count($this->documentation)) {\n foreach ($this->documentation as $documentation) {\n $documentation->xmlSerialize(true, $sxe->addChild('documentation'));\n }\n }\n if (0 < count($this->goalId)) {\n foreach ($this->goalId as $goalId) {\n $goalId->xmlSerialize(true, $sxe->addChild('goalId'));\n }\n }\n if (isset($this->subjectCodeableConcept)) {\n $this->subjectCodeableConcept->xmlSerialize(true, $sxe->addChild('subjectCodeableConcept'));\n }\n if (isset($this->subjectReference)) {\n $this->subjectReference->xmlSerialize(true, $sxe->addChild('subjectReference'));\n }\n if (0 < count($this->trigger)) {\n foreach ($this->trigger as $trigger) {\n $trigger->xmlSerialize(true, $sxe->addChild('trigger'));\n }\n }\n if (0 < count($this->condition)) {\n foreach ($this->condition as $condition) {\n $condition->xmlSerialize(true, $sxe->addChild('condition'));\n }\n }\n if (0 < count($this->input)) {\n foreach ($this->input as $input) {\n $input->xmlSerialize(true, $sxe->addChild('input'));\n }\n }\n if (0 < count($this->output)) {\n foreach ($this->output as $output) {\n $output->xmlSerialize(true, $sxe->addChild('output'));\n }\n }\n if (0 < count($this->relatedAction)) {\n foreach ($this->relatedAction as $relatedAction) {\n $relatedAction->xmlSerialize(true, $sxe->addChild('relatedAction'));\n }\n }\n if (isset($this->timingDateTime)) {\n $this->timingDateTime->xmlSerialize(true, $sxe->addChild('timingDateTime'));\n }\n if (isset($this->timingAge)) {\n $this->timingAge->xmlSerialize(true, $sxe->addChild('timingAge'));\n }\n if (isset($this->timingPeriod)) {\n $this->timingPeriod->xmlSerialize(true, $sxe->addChild('timingPeriod'));\n }\n if (isset($this->timingDuration)) {\n $this->timingDuration->xmlSerialize(true, $sxe->addChild('timingDuration'));\n }\n if (isset($this->timingRange)) {\n $this->timingRange->xmlSerialize(true, $sxe->addChild('timingRange'));\n }\n if (isset($this->timingTiming)) {\n $this->timingTiming->xmlSerialize(true, $sxe->addChild('timingTiming'));\n }\n if (0 < count($this->participant)) {\n foreach ($this->participant as $participant) {\n $participant->xmlSerialize(true, $sxe->addChild('participant'));\n }\n }\n if (isset($this->type)) {\n $this->type->xmlSerialize(true, $sxe->addChild('type'));\n }\n if (isset($this->groupingBehavior)) {\n $this->groupingBehavior->xmlSerialize(true, $sxe->addChild('groupingBehavior'));\n }\n if (isset($this->selectionBehavior)) {\n $this->selectionBehavior->xmlSerialize(true, $sxe->addChild('selectionBehavior'));\n }\n if (isset($this->requiredBehavior)) {\n $this->requiredBehavior->xmlSerialize(true, $sxe->addChild('requiredBehavior'));\n }\n if (isset($this->precheckBehavior)) {\n $this->precheckBehavior->xmlSerialize(true, $sxe->addChild('precheckBehavior'));\n }\n if (isset($this->cardinalityBehavior)) {\n $this->cardinalityBehavior->xmlSerialize(true, $sxe->addChild('cardinalityBehavior'));\n }\n if (isset($this->definitionCanonical)) {\n $this->definitionCanonical->xmlSerialize(true, $sxe->addChild('definitionCanonical'));\n }\n if (isset($this->definitionUri)) {\n $this->definitionUri->xmlSerialize(true, $sxe->addChild('definitionUri'));\n }\n if (isset($this->transform)) {\n $this->transform->xmlSerialize(true, $sxe->addChild('transform'));\n }\n if (0 < count($this->dynamicValue)) {\n foreach ($this->dynamicValue as $dynamicValue) {\n $dynamicValue->xmlSerialize(true, $sxe->addChild('dynamicValue'));\n }\n }\n if (0 < count($this->action)) {\n foreach ($this->action as $action) {\n $action->xmlSerialize(true, $sxe->addChild('action'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function getEffectiveTriggerTime()\n {\n $trigger = $this->TRIGGER;\n if (!isset($trigger['VALUE']) || 'DURATION' === strtoupper($trigger['VALUE'])) {\n $triggerDuration = VObject\\DateTimeParser::parseDuration($this->TRIGGER);\n $related = (isset($trigger['RELATED']) && 'END' == strtoupper($trigger['RELATED'])) ? 'END' : 'START';\n\n $parentComponent = $this->parent;\n if ('START' === $related) {\n if ('VTODO' === $parentComponent->name) {\n $propName = 'DUE';\n } else {\n $propName = 'DTSTART';\n }\n\n $effectiveTrigger = $parentComponent->$propName->getDateTime();\n $effectiveTrigger = $effectiveTrigger->add($triggerDuration);\n } else {\n if ('VTODO' === $parentComponent->name) {\n $endProp = 'DUE';\n } elseif ('VEVENT' === $parentComponent->name) {\n $endProp = 'DTEND';\n } else {\n throw new InvalidDataException('time-range filters on VALARM components are only supported when they are a child of VTODO or VEVENT');\n }\n\n if (isset($parentComponent->$endProp)) {\n $effectiveTrigger = $parentComponent->$endProp->getDateTime();\n $effectiveTrigger = $effectiveTrigger->add($triggerDuration);\n } elseif (isset($parentComponent->DURATION)) {\n $effectiveTrigger = $parentComponent->DTSTART->getDateTime();\n $duration = VObject\\DateTimeParser::parseDuration($parentComponent->DURATION);\n $effectiveTrigger = $effectiveTrigger->add($duration);\n $effectiveTrigger = $effectiveTrigger->add($triggerDuration);\n } else {\n $effectiveTrigger = $parentComponent->DTSTART->getDateTime();\n $effectiveTrigger = $effectiveTrigger->add($triggerDuration);\n }\n }\n } else {\n $effectiveTrigger = $trigger->getDateTime();\n }\n\n return $effectiveTrigger;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function getSupportedEncryptionAlgorithms()\n {\n $algos = array(\n // from <http://tools.ietf.org/html/rfc4345#section-4>:\n 'arcfour256',\n 'arcfour128',\n\n //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key\n\n // CTR modes from <http://tools.ietf.org/html/rfc4344#section-4>:\n 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key\n 'aes192-ctr', // RECOMMENDED AES with 192-bit key\n 'aes256-ctr', // RECOMMENDED AES with 256-bit key\n\n 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key\n 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key\n 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key\n\n 'aes128-cbc', // RECOMMENDED AES with a 128-bit key\n 'aes192-cbc', // OPTIONAL AES with a 192-bit key\n 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key\n\n 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key\n 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key\n 'twofish256-cbc',\n 'twofish-cbc', // OPTIONAL alias for \"twofish256-cbc\"\n // (this is being retained for historical reasons)\n\n 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode\n\n 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode\n\n '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode\n\n '3des-cbc', // REQUIRED three-key 3DES in CBC mode\n\n //'none' // OPTIONAL no encryption; NOT RECOMMENDED\n );\n\n if ($this->crypto_engine) {\n $engines = array($this->crypto_engine);\n } else {\n $engines = array(\n Base::ENGINE_OPENSSL,\n Base::ENGINE_MCRYPT,\n Base::ENGINE_INTERNAL\n );\n }\n\n $ciphers = array();\n foreach ($engines as $engine) {\n foreach ($algos as $algo) {\n $obj = $this->_encryption_algorithm_to_crypt_instance($algo);\n if ($obj instanceof Rijndael) {\n $obj->setKeyLength(preg_replace('#[^\\d]#', '', $algo));\n }\n switch ($algo) {\n case 'arcfour128':\n case 'arcfour256':\n if ($engine != Base::ENGINE_INTERNAL) {\n continue 2;\n }\n }\n if ($obj->isValidEngine($engine)) {\n $algos = array_diff($algos, array($algo));\n $ciphers[] = $algo;\n }\n }\n }\n\n return $ciphers;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['cors'])) {\n $this->setCors($data['cors']);\n }\n if (isset($data['service'])) {\n if (is_array($data['service'])) {\n foreach ($data['service'] as $d) {\n $this->addService($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"service\" must be array of objects or null, ' . gettype($data['service']) . ' seen.');\n }\n }\n if (isset($data['description'])) {\n $this->setDescription($data['description']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getExceptionsStatic($id_module, $id_hook, $dispatch = false)\n {\n $cache_id = 'exceptionsCache';\n if (!Cache::isStored($cache_id)) {\n $exceptions_cache = array();\n $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'hook_module_exceptions`\n WHERE `id_shop` IN (' . implode(', ', Shop::getContextListShopID()) . ')';\n $db = Db::getInstance();\n $result = $db->executeS($sql, false);\n while ($row = $db->nextRow($result)) {\n if (!$row['file_name']) {\n continue;\n }\n $key = $row['id_hook'] . '-' . $row['id_module'];\n if (!isset($exceptions_cache[$key])) {\n $exceptions_cache[$key] = array();\n }\n if (!isset($exceptions_cache[$key][$row['id_shop']])) {\n $exceptions_cache[$key][$row['id_shop']] = array();\n }\n $exceptions_cache[$key][$row['id_shop']][] = $row['file_name'];\n }\n Cache::store($cache_id, $exceptions_cache);\n } else {\n $exceptions_cache = Cache::retrieve($cache_id);\n }\n\n $key = $id_hook . '-' . $id_module;\n $array_return = array();\n if ($dispatch) {\n foreach (Shop::getContextListShopID() as $shop_id) {\n if (isset($exceptions_cache[$key], $exceptions_cache[$key][$shop_id])) {\n $array_return[$shop_id] = $exceptions_cache[$key][$shop_id];\n }\n }\n } else {\n foreach (Shop::getContextListShopID() as $shop_id) {\n if (isset($exceptions_cache[$key], $exceptions_cache[$key][$shop_id])) {\n foreach ($exceptions_cache[$key][$shop_id] as $file) {\n if (!in_array($file, $array_return)) {\n $array_return[] = $file;\n }\n }\n }\n }\n }\n\n return $array_return;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function getDimensionValues(\n XDUser $user,\n $dimension_id,\n array $realms = null,\n $offset = 0,\n $limit = null,\n $searchText = null,\n array $selectedFilterIds = null,\n $includePub = true,\n $showAllDimensionValues = false\n ) {\n // Check if the realms were specified, and if not, use all realms.\n $realmsSpecified = !empty($realms);\n if (!$realmsSpecified) {\n $realms = Realms::getRealmIdsForUser($user);\n }\n\n // Determine which aggregation unit to use for dimension values queries.\n $queryAggregationUnit = FilterListHelper::getQueryAggregationUnit();\n\n // Get a dimension values query for each valid realm.\n $dimensionValuesQueries = array();\n foreach ($realms as $realm) {\n\n // Attempt to get the group by object for this realm to check that\n // the dimension exists for this realm.\n $realmObj = \\Realm\\Realm::factory($realm);\n\n if ( ! $realmObj->groupByExists($dimension_id) ) {\n if ( $realmsSpecified ) {\n // If the group by does not exist and realms were explicitly\n // specified, throw an exception. Otherwise, just continue to\n // the next realm.\n throw new UnknownGroupByException(\n sprintf(\"Dimension '%s' does not exist for realm '%s'.\", $dimension_id, $realm)\n );\n } else {\n continue;\n }\n }\n\n $group_by = $realmObj->getGroupByObject($dimension_id);\n\n // Get the user's roles that are authorized to view this data.\n try {\n $realmAuthorizedRoles = MetricExplorer::checkDataAccess(\n $user,\n $realm,\n $dimension_id,\n null,\n $includePub\n );\n } catch (AccessDeniedException $e) {\n // Only throw an exception that the user is not authorized if\n // they requested this realm's data explicitly. Otherwise, just\n // skip this realm.\n if ($realmsSpecified) {\n throw $e;\n }\n continue;\n }\n\n // Generate the dimension values query for this realm.\n $query = new \\DataWarehouse\\Query\\AggregateQuery(\n $realm,\n $queryAggregationUnit,\n null,\n null,\n $dimension_id\n );\n\n if($showAllDimensionValues && $group_by->showAllDimensionValues()){\n $dimensionValuesQueries[] = $query->getDimensionValuesQuery();\n }else{\n $query->setMultipleRoleParameters($realmAuthorizedRoles, $user);\n $dimensionValuesQueries[] = $query->getDimensionValuesQuery();\n }\n }\n\n // Throw an exception if no queries could be generated.\n $numDimensionValuesQueries = count($dimensionValuesQueries);\n if ($numDimensionValuesQueries === 0) {\n throw new UnknownGroupByException(\"Dimension \\\"$dimension_id\\\" either does not exist or you are not authorized to view its values in any realm.\");\n }\n\n // Execute the queries as a single query. If only one query was\n // generated, execute it as is. Otherwise, union the queries together\n // and sort the result set by the specified ordering value.\n //\n // Requesting the entire set all at once and not specifying limiting\n // criteria allows us to make optimal use of the database's cache.\n //\n // If each realm's data is requested individually, the server needs to\n // remove the duplicates between realms on each request. This solution\n // has the database performing this task and caching the result.\n //\n // If limiting criteria are added to the query, only the final results\n // are cached, meaning that the base queries need to be rerun each time\n // the criteria are changed. In this case, the server is better off\n // filtering the results.\n $db = DB::factory('datawarehouse');\n try {\n if ($numDimensionValuesQueries === 1) {\n $dimensionValues = $db->query($dimensionValuesQueries[0]);\n foreach ($dimensionValues as &$dimensionValue) {\n unset($dimensionValue['_dimensionOrderValue']);\n }\n } else {\n $combinedDimensionValuesSortOrder = 'ASC';\n foreach ($dimensionValuesQueries as $dimensionValuesQuery) {\n if (preg_match(\n '/ORDER\\s+BY\\s+[^,\\s]+\\s+DESC/i',\n $dimensionValuesQuery\n )) {\n $combinedDimensionValuesSortOrder = 'DESC';\n break;\n }\n }\n\n $dimensionValuesUnion = '(' . implode(') UNION (', $dimensionValuesQueries) . ')';\n $combinedDimensionValuesQuery = \"\n SELECT\n id,\n name,\n short_name\n FROM\n ($dimensionValuesUnion) AS dimensionValuesUnion\n GROUP BY id\n ORDER BY _dimensionOrderValue $combinedDimensionValuesSortOrder\n \";\n $dimensionValues = $db->query($combinedDimensionValuesQuery);\n }\n } catch (PDOException $e) {\n // If the filter table was missing from the schema,\n // throw a more user-friendly exception.\n if (\n $e->getCode() === '42S02'\n && strpos($e->getMessage(), 'modw_filters') !== false\n ) {\n throw new MissingFilterListTableException();\n }\n\n // If the schema does not exist or is not accessible,\n // also throw that exception.\n if ($e->getCode() === '42000') {\n $missingSchema = false;\n try {\n $schemaCheckResults = $db->query(\"SHOW SCHEMAS LIKE 'modw_filters'\");\n $missingSchema = empty($schemaCheckResults);\n } catch (Exception $schemaCheckException) {\n }\n\n if ($missingSchema) {\n throw new MissingFilterListTableException();\n }\n }\n\n throw $e;\n }\n\n // If a search string was given, filter the result set to values with\n // labels containing each word in the string.\n if ($searchText !== null) {\n $searchComponents = preg_split('/\\s+/', $searchText, null, PREG_SPLIT_NO_EMPTY);\n foreach ($searchComponents as $searchComponent) {\n $dimensionValues = array_filter(\n $dimensionValues,\n function($dimensionValue) use ($searchComponent) {\n return stripos($dimensionValue['short_name'], $searchComponent) !== false\n || stripos($dimensionValue['name'], $searchComponent) !== false;\n }\n );\n }\n }\n\n // Remove rows with duplicate names from the result set, favoring later\n // entries in the result set.\n $uniqueNameValues = array();\n foreach ($dimensionValues as &$dimensionValue) {\n $uniqueNameValues[$dimensionValue['name']] = &$dimensionValue;\n }\n $dimensionValues = array_values($uniqueNameValues);\n\n // Before applying any length-based filtering, count the number of\n // values found.\n $totalDimensionValues = count($dimensionValues);\n\n // If a non-null limit or non-zero offset was given, reduce the\n // result set to the specified slice.\n $limitGiven = $limit !== null;\n $offsetGiven = $offset !== 0;\n if ($limitGiven || $offsetGiven) {\n $dimensionValues = array_slice($dimensionValues, $offset, $limit);\n }\n\n // If a set of selected IDs is given, check the result set against\n // this set to determine what matches.\n if ($selectedFilterIds !== null) {\n foreach ($dimensionValues as &$dimensionValue) {\n $dimensionValue['checked'] = in_array($dimension_id.'='.$dimensionValue['id'], $selectedFilterIds);\n }\n }\n\n // Return the results.\n return array(\n 'totalCount' => $totalDimensionValues,\n 'data' => $dimensionValues,\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<HealthcareService xmlns=\"http://hl7.org/fhir\"></HealthcareService>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (isset($this->active)) {\n $this->active->xmlSerialize(true, $sxe->addChild('active'));\n }\n if (isset($this->providedBy)) {\n $this->providedBy->xmlSerialize(true, $sxe->addChild('providedBy'));\n }\n if (0 < count($this->category)) {\n foreach ($this->category as $category) {\n $category->xmlSerialize(true, $sxe->addChild('category'));\n }\n }\n if (0 < count($this->type)) {\n foreach ($this->type as $type) {\n $type->xmlSerialize(true, $sxe->addChild('type'));\n }\n }\n if (0 < count($this->specialty)) {\n foreach ($this->specialty as $specialty) {\n $specialty->xmlSerialize(true, $sxe->addChild('specialty'));\n }\n }\n if (0 < count($this->location)) {\n foreach ($this->location as $location) {\n $location->xmlSerialize(true, $sxe->addChild('location'));\n }\n }\n if (isset($this->name)) {\n $this->name->xmlSerialize(true, $sxe->addChild('name'));\n }\n if (isset($this->comment)) {\n $this->comment->xmlSerialize(true, $sxe->addChild('comment'));\n }\n if (isset($this->extraDetails)) {\n $this->extraDetails->xmlSerialize(true, $sxe->addChild('extraDetails'));\n }\n if (isset($this->photo)) {\n $this->photo->xmlSerialize(true, $sxe->addChild('photo'));\n }\n if (0 < count($this->telecom)) {\n foreach ($this->telecom as $telecom) {\n $telecom->xmlSerialize(true, $sxe->addChild('telecom'));\n }\n }\n if (0 < count($this->coverageArea)) {\n foreach ($this->coverageArea as $coverageArea) {\n $coverageArea->xmlSerialize(true, $sxe->addChild('coverageArea'));\n }\n }\n if (0 < count($this->serviceProvisionCode)) {\n foreach ($this->serviceProvisionCode as $serviceProvisionCode) {\n $serviceProvisionCode->xmlSerialize(true, $sxe->addChild('serviceProvisionCode'));\n }\n }\n if (0 < count($this->eligibility)) {\n foreach ($this->eligibility as $eligibility) {\n $eligibility->xmlSerialize(true, $sxe->addChild('eligibility'));\n }\n }\n if (0 < count($this->program)) {\n foreach ($this->program as $program) {\n $program->xmlSerialize(true, $sxe->addChild('program'));\n }\n }\n if (0 < count($this->characteristic)) {\n foreach ($this->characteristic as $characteristic) {\n $characteristic->xmlSerialize(true, $sxe->addChild('characteristic'));\n }\n }\n if (0 < count($this->communication)) {\n foreach ($this->communication as $communication) {\n $communication->xmlSerialize(true, $sxe->addChild('communication'));\n }\n }\n if (0 < count($this->referralMethod)) {\n foreach ($this->referralMethod as $referralMethod) {\n $referralMethod->xmlSerialize(true, $sxe->addChild('referralMethod'));\n }\n }\n if (isset($this->appointmentRequired)) {\n $this->appointmentRequired->xmlSerialize(true, $sxe->addChild('appointmentRequired'));\n }\n if (0 < count($this->availableTime)) {\n foreach ($this->availableTime as $availableTime) {\n $availableTime->xmlSerialize(true, $sxe->addChild('availableTime'));\n }\n }\n if (0 < count($this->notAvailable)) {\n foreach ($this->notAvailable as $notAvailable) {\n $notAvailable->xmlSerialize(true, $sxe->addChild('notAvailable'));\n }\n }\n if (isset($this->availabilityExceptions)) {\n $this->availabilityExceptions->xmlSerialize(true, $sxe->addChild('availabilityExceptions'));\n }\n if (0 < count($this->endpoint)) {\n foreach ($this->endpoint as $endpoint) {\n $endpoint->xmlSerialize(true, $sxe->addChild('endpoint'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getHookModuleExecList($hook_name = null)\n {\n $context = Context::getContext();\n $cache_id = self::MODULE_LIST_BY_HOOK_KEY . (isset($context->shop->id) ? '_' . $context->shop->id : '') . ((isset($context->customer)) ? '_' . $context->customer->id : '');\n if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayPaymentEU' || $hook_name == 'paymentOptions' || $hook_name == 'displayBackOfficeHeader') {\n $frontend = true;\n $groups = array();\n $use_groups = Group::isFeatureActive();\n if (isset($context->employee)) {\n $frontend = false;\n } else {\n // Get groups list\n if ($use_groups) {\n if (isset($context->customer) && $context->customer->isLogged()) {\n $groups = $context->customer->getGroups();\n } elseif (isset($context->customer) && $context->customer->isLogged(true)) {\n $groups = array((int) Configuration::get('PS_GUEST_GROUP'));\n } else {\n $groups = array((int) Configuration::get('PS_UNIDENTIFIED_GROUP'));\n }\n }\n }\n\n // SQL Request\n $sql = new DbQuery();\n $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module');\n $sql->from('module', 'm');\n if ($hook_name != 'displayBackOfficeHeader') {\n $sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & ' . (int) Context::getContext()->getDevice()));\n $sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');\n }\n $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');\n $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');\n if ($hook_name != 'paymentOptions') {\n $sql->where('h.`name` != \"paymentOptions\"');\n } elseif ($frontend) {\n // For payment modules, we check that they are available in the contextual country\n if (Validate::isLoadedObject($context->country)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\")AND (SELECT `id_country` FROM `' . _DB_PREFIX_ . 'module_country` mc WHERE mc.`id_module` = m.`id_module` AND `id_country` = ' . (int) $context->country->id . ' AND `id_shop` = ' . (int) $context->shop->id . ' LIMIT 1) = ' . (int) $context->country->id . ')');\n }\n if (Validate::isLoadedObject($context->currency)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\") AND (SELECT `id_currency` FROM `' . _DB_PREFIX_ . 'module_currency` mcr WHERE mcr.`id_module` = m.`id_module` AND `id_currency` IN (' . (int) $context->currency->id . ', -1, -2) LIMIT 1) IN (' . (int) $context->currency->id . ', -1, -2))');\n }\n if (Validate::isLoadedObject($context->cart)) {\n $carrier = new Carrier($context->cart->id_carrier);\n if (Validate::isLoadedObject($carrier)) {\n $sql->where('((h.`name` = \"displayPayment\" OR h.`name` = \"displayPaymentEU\" OR h.`name` = \"paymentOptions\") AND (SELECT `id_reference` FROM `' . _DB_PREFIX_ . 'module_carrier` mcar WHERE mcar.`id_module` = m.`id_module` AND `id_reference` = ' . (int) $carrier->id_reference . ' AND `id_shop` = ' . (int) $context->shop->id . ' LIMIT 1) = ' . (int) $carrier->id_reference . ')');\n }\n }\n }\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('hm.`id_shop` = ' . (int) $context->shop->id);\n }\n\n if ($frontend) {\n if ($use_groups) {\n $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');\n if (Validate::isLoadedObject($context->shop)) {\n $sql->where('mg.id_shop = ' . ((int) $context->shop->id) . (count($groups) ? ' AND mg.`id_group` IN (' . implode(', ', $groups) . ')' : ''));\n } elseif (count($groups)) {\n $sql->where('mg.`id_group` IN (' . implode(', ', $groups) . ')');\n }\n }\n }\n\n $sql->groupBy('hm.id_hook, hm.id_module');\n $sql->orderBy('hm.`position`');\n\n $list = array();\n if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {\n foreach ($result as $row) {\n $row['hook'] = strtolower($row['hook']);\n if (!isset($list[$row['hook']])) {\n $list[$row['hook']] = array();\n }\n\n $list[$row['hook']][] = array(\n 'id_hook' => $row['id_hook'],\n 'module' => $row['module'],\n 'id_module' => $row['id_module'],\n );\n }\n }\n if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU' && $hook_name != 'paymentOptions' && $hook_name != 'displayBackOfficeHeader') {\n Cache::store($cache_id, $list);\n // @todo remove this in 1.6, we keep it in 1.5 for backward compatibility\n self::$_hook_modules_cache_exec = $list;\n }\n } else {\n $list = Cache::retrieve($cache_id);\n }\n\n // If hook_name is given, just get list of modules for this hook\n if ($hook_name) {\n $retro_hook_name = strtolower(Hook::getRetroHookName($hook_name));\n $hook_name = strtolower($hook_name);\n\n $return = array();\n $inserted_modules = array();\n if (isset($list[$hook_name])) {\n $return = $list[$hook_name];\n }\n foreach ($return as $module) {\n $inserted_modules[] = $module['id_module'];\n }\n if (isset($list[$retro_hook_name])) {\n foreach ($list[$retro_hook_name] as $retro_module_call) {\n if (!in_array($retro_module_call['id_module'], $inserted_modules)) {\n $return[] = $retro_module_call;\n }\n }\n }\n\n return count($return) > 0 ? $return : false;\n } else {\n return $list;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function showqinfobar($qn,$inreview,$single,$showqnum=0) {\n\tglobal $qi,$questions,$attempts,$seeds,$testsettings,$noindivscores,$showeachscore,$scores,$bestscores,$imasroot,$CFG;\n\t$qn = intval($qn);\n if (!$_SESSION['istutorial']) {\n\t\tif ($inreview) {\n\t\t\techo '<div class=\"review clearfix\">';\n\t\t}\n\t\tif ($_SESSION['isteacher']) {\n\t\t\techo '<span style=\"float:right;font-size:70%;text-align:right;\">'._('Question ID: ').Sanitize::onlyInt($qi[$questions[$qn]]['questionsetid']);\n\t\t\techo '<br/><a target=\"license\" href=\"'.$imasroot.'/course/showlicense.php?id='.Sanitize::onlyInt($qi[$questions[$qn]]['questionsetid']).'\">'._('License').'</a>';\n\t\t\tif (isset($CFG['GEN']['sendquestionproblemsthroughcourse'])) {\n\t\t\t\techo \"<br/><a href=\\\"$imasroot/msgs/msglist.php?add=new&cid={$CFG['GEN']['sendquestionproblemsthroughcourse']}&\";\n\t\t\t\techo \"quoteq=\".Sanitize::encodeUrlParam(\"0-{$qi[$questions[$qn]]['questionsetid']}-{$seeds[$qn]}-reperr-{$GLOBALS['assessver']}\").\"\\\" target=\\\"reperr\\\">Report Problems</a>\";\n\t\t\t}\n\t\t\techo '</span>';\n\t\t} else {\n\t\t\techo '<span style=\"float:right;font-size:70%\"><a target=\"license\" href=\"'.$imasroot.'/course/showlicense.php?id='.$qi[$questions[$qn]]['questionsetid'].'\">'._('License').'</a></span>';\n\t\t}\n\t\tif ($showqnum==1) {\n\t\t\techo _('Question').' '.($qn+1).'. ';\n\t\t} else if ($showqnum==2) {\n\t\t\techo sprintf(_('Question %d of %d'), $qn+1, count($questions)).'<br/>';\n\t\t}\n\t\tif ($qi[$questions[$qn]]['withdrawn']==1) {\n\t\t\techo '<span class=\"noticetext\">', _('Question Withdrawn'), '</span> ';\n\t\t}\n\t\tif ($attempts[$qn]<$qi[$questions[$qn]]['attempts'] || $qi[$questions[$qn]]['attempts']==0) {\n\t\t\t$pointsremaining = getremainingpossible($qn,$qi[$questions[$qn]],$testsettings,$attempts[$qn]);\n\t\t\tif ($pointsremaining == $qi[$questions[$qn]]['points']) {\n\t\t\t\techo _('Points possible: '), $qi[$questions[$qn]]['points'], '<br/>';\n\t\t\t} else {\n\t\t\t\techo sprintf(_('Points available on this attempt: %1$g of original %2$g'), $pointsremaining, $qi[$questions[$qn]]['points']), '<br/>';\n\t\t\t}\n\t\t}\n\n\t\tif ($qi[$questions[$qn]]['attempts']==0) {\n\t\t\techo _('Unlimited attempts.');\n\t\t} else if ($attempts[$qn]>=$qi[$questions[$qn]]['attempts']) {\n\t\t\techo _('No attempts remain.');\n\t\t} else {\n\t\t\t//echo '<br/>'.($qi[$questions[$qn]]['attempts']-$attempts[$qn]).\" attempts of \".$qi[$questions[$qn]]['attempts'].\" remaining.\";\n\t\t\techo sprintf(_('This is attempt %1$d of %2$d.'), ($attempts[$qn]+1), $qi[$questions[$qn]]['attempts']);\n\t\t}\n\t\tif ($testsettings['showcat']>0 && $qi[$questions[$qn]]['category']!='0') {\n\t\t\techo \" \", _('Category:'), \" {$qi[$questions[$qn]]['category']}.\";\n\t\t}\n\t\tif ($attempts[$qn]>0 && $showeachscore) {\n\t\t\tif (strpos($scores[$qn],'~')===false) {\n\t\t\t\techo \"<br/>\", _('Score on last attempt:'). \" \".($scores[$qn]<0? 'N/A':$scores[$qn]).\". \";\n\t\t\t} else {\n\t\t\t\techo \"<br/>\", _('Score on last attempt:'), \" (\" . str_replace('~', ', ',$scores[$qn]) . '). ';\n\t\t\t}\n\t\t\tif (strpos($bestscores[$qn],'~')===false) {\n\t\t\t\techo _('Score in gradebook:'), \" \".($bestscores[$qn]<0? 'N/A':$bestscores[$qn]);\n\t\t\t} else {\n\t\t\t\techo _('Score in gradebook:'), \" (\" . str_replace('~', ', ',$bestscores[$qn]) . ') ';\n\t\t\t\tif (isset($qi[$questions[$qn]]['answeights']) &&\n\t\t\t\t\tcount($qi[$questions[$qn]]['answeights']) == substr_count($bestscores[$qn], '~') + 1\n\t\t\t\t) {\n\t\t\t\t\t$ptposs = $qi[$questions[$qn]]['answeights'];\n\t\t\t\t\tfor ($i=0; $i<count($ptposs)-1; $i++) {\n\t\t\t\t\t\t$ptposs[$i] = round($ptposs[$i]*$qi[$questions[$qn]]['points'],2);\n\t\t\t\t\t}\n\t\t\t\t\t//adjust for rounding\n\t\t\t\t\t$diff = $qi[$questions[$qn]]['points'] - array_sum($ptposs);\n\t\t\t\t\t$ptposs[count($ptposs)-1] += $diff;\n\t\t\t\t\t$ptposs = implode(', ',$ptposs);\n\t\t\t\t\techo ', ', _('Out of:'), \" ($ptposs)\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//if (!$noindivscores) {\n\t\t//\techo \"<br/>Score in gradebook: \".printscore2($bestscores[$qn]).\".\";\n\t\t//}\n\t}\n\tif ($single) {\n\t\techo \"<input type=hidden id=\\\"verattempts\\\" name=\\\"verattempts\\\" value=\\\"{$attempts[$qn]}\\\" />\";\n\t} else {\n\t\techo \"<input type=hidden id=\\\"verattempts$qn\\\" name=\\\"verattempts[$qn]\\\" value=\\\"{$attempts[$qn]}\\\" />\";\n\t}\n\tif (!$_SESSION['istutorial']) {\n\t\t$contactlinks = showquestioncontactlinks($qn);\n\t\tif ($contactlinks!='') {\n\t\t\techo '<br/>'.$contactlinks;\n\t\t}\n\t\tif ($inreview) {\n\t\t\techo '</div>';\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function importItemsRelations(): void\n {\n $this->output->writeln(\n '<comment>' . __('Importing relations with other itemtypes...') . '</comment>',\n OutputInterface::VERBOSITY_NORMAL\n );\n\n $relations_itemtypes = [\n Item_Ticket::class,\n Item_Problem::class,\n Change_Item::class,\n Item_Project::class,\n Document_Item::class,\n Contract_Item::class,\n KnowbaseItem_Item::class,\n ];\n\n foreach ($relations_itemtypes as $relation_itemtype) {\n $this->output->writeln(\n '<comment>' . sprintf(__('Importing %s...'), $relation_itemtype::getTypeName(Session::getPluralNumber())) . '</comment>',\n OutputInterface::VERBOSITY_NORMAL\n );\n\n $iterator = $this->db->request([\n 'FROM' => $relation_itemtype::getTable(),\n 'WHERE' => ['itemtype' => 'PluginDatabasesDatabase'],\n 'ORDER' => 'id ASC'\n ]);\n\n if ($iterator->count() === 0) {\n $this->output->writeln('<comment>' . __('No elements found.') . '</comment>');\n return;\n }\n\n $opposite_fkey = $relation_itemtype::$items_id_1;\n\n $progress_bar = new ProgressBar($this->output);\n\n foreach ($progress_bar->iterate($iterator) as $relation_data) {\n $mapped_database = $this->getTargetItem('PluginDatabasesDatabase', $relation_data['items_id']);\n if ($mapped_database === null) {\n $this->handleImportError(\n sprintf(\n __('Unable to find target item for %s #%s.'),\n 'PluginDatabasesDatabase',\n $relation_data['items_id']\n ),\n $progress_bar,\n true // Do not block migration as this error is probably resulting in presence of obsolete data in DB\n );\n continue;\n }\n\n $database_id = $mapped_database->fields['id'];\n\n $core_relation_id = $this->getMatchingElementId(\n $relation_itemtype,\n [\n $opposite_fkey => $relation_data[$opposite_fkey],\n 'itemtype' => DatabaseInstance::class,\n 'items_id' => $database_id,\n ]\n );\n\n $this->writelnOutputWithProgressBar(\n sprintf(\n $core_relation_id !== null ? __('Skip existing %s \"%s\".') : __('Importing %s \"%s\"...'),\n $relation_itemtype::getTypeName(),\n $relation_data[$opposite_fkey] . ' ' . DatabaseInstance::class . ' ' . $database_id\n ),\n $progress_bar,\n OutputInterface::VERBOSITY_VERY_VERBOSE\n );\n\n if ($core_relation_id !== null) {\n // If relation already exist in DB, there is nothing to change\n continue;\n }\n\n $relation_input = $relation_data;\n unset($relation_input['id']);\n $relation_input['itemtype'] = DatabaseInstance::class;\n $relation_input['items_id'] = $database_id;\n\n $item = new $relation_itemtype();\n if ($item->add($relation_input) === false) {\n $message = sprintf(\n __('Unable to create %s \"%s\" (%d).'),\n $relation_itemtype::getTypeName(),\n $relation_data[$opposite_fkey] . ' ' . DatabaseInstance::class . ' ' . $database_id\n );\n $this->handleImportError($message, $progress_bar);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function checkCriterias($input)\n {\n reset($this->criterias);\n\n if ($this->fields[\"match\"] == self::AND_MATCHING) {\n $doactions = true;\n\n foreach ($this->criterias as $criterion) {\n $definition_criterion = $this->getCriteria($criterion->fields['criteria']);\n if (!isset($definition_criterion['is_global']) || !$definition_criterion['is_global']) {\n $doactions &= $this->checkCriteria($criterion, $input);\n if (!$doactions) {\n break;\n }\n }\n }\n } else { // OR MATCHING\n $doactions = false;\n foreach ($this->criterias as $criterion) {\n $definition_criterion = $this->getCriteria($criterion->fields['criteria']);\n\n if (\n !isset($definition_criterion['is_global'])\n || !$definition_criterion['is_global']\n ) {\n $doactions |= $this->checkCriteria($criterion, $input);\n if ($doactions) {\n break;\n }\n }\n }\n }\n\n //If all simple criteria match, and if necessary, check complex criteria\n if ($doactions) {\n return $this->findWithGlobalCriteria($input);\n }\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function up(): void\n {\n // add decimal places to \"transaction currencies\".\n if (!Schema::hasColumn('transaction_currencies', 'decimal_places')) {\n try {\n Schema::table(\n 'transaction_currencies',\n static function (Blueprint $table): void {\n $table->smallInteger('decimal_places', false, true)->default(2);\n }\n );\n } catch (QueryException $e) {\n app('log')->error(sprintf('Could not execute query: %s', $e->getMessage()));\n app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');\n }\n }\n\n // change field \"startdate\" to \"start_date\"\n if (Schema::hasColumn('budget_limits', 'startdate') && !Schema::hasColumn('budget_limits', 'start_date')) {\n try {\n Schema::table(\n 'budget_limits',\n static function (Blueprint $table): void {\n $table->renameColumn('startdate', 'start_date');\n }\n );\n } catch (QueryException $e) {\n app('log')->error(sprintf('Could not execute query: %s', $e->getMessage()));\n app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');\n }\n }\n\n // add date field \"end_date\" after \"start_date\"\n if (!Schema::hasColumn('budget_limits', 'end_date')) {\n try {\n Schema::table(\n 'budget_limits',\n static function (Blueprint $table): void {\n $table->date('end_date')->nullable()->after('start_date');\n }\n );\n } catch (QueryException $e) {\n app('log')->error(sprintf('Could not execute query: %s', $e->getMessage()));\n app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');\n }\n }\n\n // drop \"repeats\" and \"repeat_freq\".\n if (Schema::hasColumn('budget_limits', 'repeats')) {\n try {\n Schema::table(\n 'budget_limits',\n static function (Blueprint $table): void {\n $table->dropColumn('repeats');\n }\n );\n } catch (QueryException $e) {\n app('log')->error(sprintf('Could not execute query: %s', $e->getMessage()));\n app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');\n }\n }\n if (Schema::hasColumn('budget_limits', 'repeat_freq')) {\n try {\n Schema::table(\n 'budget_limits',\n static function (Blueprint $table): void {\n $table->dropColumn('repeat_freq');\n }\n );\n } catch (QueryException $e) {\n app('log')->error(sprintf('Could not execute query: %s', $e->getMessage()));\n app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public function addRoute($route_id, $rule, $controller, $id_lang = null, array $keywords = array(), array $params = array(), $id_shop = null)\n {\n if (isset(Context::getContext()->language) && $id_lang === null) {\n $id_lang = (int)Context::getContext()->language->id;\n }\n\n if (isset(Context::getContext()->shop) && $id_shop === null) {\n $id_shop = (int)Context::getContext()->shop->id;\n }\n\n $regexp = preg_quote($rule, '#');\n if ($keywords) {\n $transform_keywords = array();\n preg_match_all('#\\\\\\{(([^{}]*)\\\\\\:)?('.implode('|', array_keys($keywords)).')(\\\\\\:([^{}]*))?\\\\\\}#', $regexp, $m);\n for ($i = 0, $total = count($m[0]); $i < $total; $i++) {\n $prepend = $m[2][$i];\n $keyword = $m[3][$i];\n $append = $m[5][$i];\n $transform_keywords[$keyword] = array(\n 'required' => isset($keywords[$keyword]['param']),\n 'prepend' => stripslashes($prepend),\n 'append' => stripslashes($append),\n );\n\n $prepend_regexp = $append_regexp = '';\n if ($prepend || $append) {\n $prepend_regexp = '('.$prepend;\n $append_regexp = $append.')?';\n }\n\n if (isset($keywords[$keyword]['param'])) {\n $regexp = str_replace($m[0][$i], $prepend_regexp.'(?P<'.$keywords[$keyword]['param'].'>'.$keywords[$keyword]['regexp'].')'.$append_regexp, $regexp);\n } else {\n $regexp = str_replace($m[0][$i], $prepend_regexp.'('.$keywords[$keyword]['regexp'].')'.$append_regexp, $regexp);\n }\n }\n $keywords = $transform_keywords;\n }\n\n $regexp = '#^/'.$regexp.'$#u';\n if (!isset($this->routes[$id_shop])) {\n $this->routes[$id_shop] = array();\n }\n if (!isset($this->routes[$id_shop][$id_lang])) {\n $this->routes[$id_shop][$id_lang] = array();\n }\n\n $this->routes[$id_shop][$id_lang][$route_id] = array(\n 'rule' => $rule,\n 'regexp' => $regexp,\n 'controller' => $controller,\n 'keywords' => $keywords,\n 'params' => $params,\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function saveAuth($auth, $form, &$errors) {\n // Validate the form\n if (!$form->isValid())\n return false;\n $vars = $form->getClean();\n list($type, $provider) = explode(':', $auth);\n switch ($type) {\n case 'basic':\n // Set username and password\n if (!$this->updateCredentials($auth, $vars, $errors)\n && !isset($errors['err']))\n $errors['err'] = sprintf('%s %s',\n __('Error Saving'),\n __('Authentication'));\n break;\n case 'oauth2':\n // For OAuth we are simply saving configuration -\n // credetials are saved post successful authorization\n // redirect.\n\n // Lookup OAuth backend\n if (($bk=$this->getOAuth2Backend($auth))) {\n // Merge form data, post vars and any defaults\n $vars = array_merge($this->getOAuth2ConfigDefaults(),\n array_intersect_key($_POST, $this->getOAuth2ConfigDefaults()),\n $vars);\n // Update or add OAuth2 instance\n if ($this->getAuthId()\n && ($i=$bk->getPluginInstance($this->getAuthId()))) {\n $vars = array_merge($bk->getDefaults(), $vars); #nolint\n if ($i->update($vars, $errors)) {\n // Disable account if backend is changed\n if (strcasecmp($this->auth_bk, $auth))\n $this->active = 0;\n // Auth backend can be changed on update\n $this->auth_bk = $auth;\n $this->save();\n // Update Strict Matching\n $this->getConfig()->setStrictMatching($_POST['strict_matching'] ? 1 : 0);\n } elseif (!isset($errors['err'])) {\n $errors['err'] = sprintf('%s %s',\n __('Error Saving'),\n __('Authentication'));\n }\n } else {\n // Ask the backend to add OAuth2 instance for this account\n if (($i=$bk->addPluginInstance($vars, $errors))) { #nolint\n // Cache instance\n $this->instance = $i;\n $this->auth_bk = $auth;\n $this->auth_id = $i->getId();\n $this->save();\n } else {\n $errors['err'] = __('Error Adding OAuth2 Instance');\n }\n }\n }\n break;\n default:\n $errors['err'] = __('Unknown Authentication Type');\n }\n return !($errors);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function renderField($field, array $options = null)\n {\n if (in_array($field, $this->renderedFields)) {\n return;\n }\n\n if (!is_array($options)) {\n $options = $this->formatOptions[$field];\n } else {\n $options = array_merge($this->formatOptions[$field], $options);\n }\n\n if (isset($options['value'])) {\n $value = $options['value'];\n } else if ($options['type'] == 'extra') {\n $value = $options['title'];\n\n } else {\n $value = isset($this->item->$field) ? $this->item->$field : $options['default_value'];\n }\n\n $type = $options['type'];\n $escapedValue = htmlspecialchars($value);\n $fieldId = 'field_'.$field;\n $commonAttrs = ' name=\"'.$field.'\" id=\"'.$fieldId.'\" ';\n if ($options['required']) {\n $commonAttrs .= ' required ';\n }\n $label = '<label for=\"'.$fieldId.'\">'.$options['label'].'</label>';\n\n echo '<div class=\"form-group\"> ';\n\n $method = 'render' . strtoupper($options['type'] . 'Field');\n if (method_exists($this, $method)) {\n $this->$method();\n\n } else if ($options['readonly'] && in_array($options['type'], ['text', 'textarea', 'password', 'select'])) {\n echo $label.': '.$escapedValue;\n\n } else if ($options['type'] == 'hidden') {\n echo '<input type=\"hidden\" value=\"'.$escapedValue.'\" '.$commonAttrs.' />';\n\n } else if ($options['type'] == 'textarea') {\n echo $label.'<textarea cols=\"40\" rows=\"4\" '.$commonAttrs.' '\n .'class=\"form-control '.$options['class_names'].'\">'.$escapedValue.'</textarea>';\n\n } else if ($type == 'select') {\n $optionList = $options['option_list'];\n if (is_callable($optionList)) {\n $optionList = call_user_func_array($optionList, [$this->pixie, $options]);\n } else if (!is_array($optionList)) {\n $optionList = ArraysHelper::arrayFillEqualPairs([$optionList]);\n }\n echo $label . '<br>' . $this->renderSelect($value, $optionList, array_merge([\n 'name' => $field,\n 'id' => $fieldId,\n 'class' => 'form-control '.$options['class_names'],\n ], $options['required'] ? ['required' => 'required'] : []));\n\n } else if ($options['type'] == 'image') {\n echo $label;\n if ($value) {\n if ($options['use_external_dir']) {\n $src = \"/upload/download.php?image=\".$escapedValue;\n } else {\n $src = htmlspecialchars($options['dir_path'].$value);\n }\n\n echo '<br><img src=\"'.$src.'\" alt=\"\" '\n . 'class=\"model-image model-'.htmlspecialchars($this->item->model_name).'-image\" /> <br>'\n . '<label><input type=\"checkbox\" name=\"remove_image_'.htmlspecialchars($field).'\" /> Remove image</label>';\n }\n echo '<br><input type=\"file\" '.$commonAttrs.' class=\"file-input btn btn-default btn-primary btn-lg\" '\n . 'title=\"Select image\" value=\"'.$escapedValue.'\">';\n\n } else if ($options['type'] == 'boolean') {\n $checked = $value ? ' checked ' : (!$this->item->loaded() && $options['default_value'] ? ' checked ' : '');\n echo $label.' <input type=\"checkbox\" '.$commonAttrs.$checked.' class=\"form-horizontal '.$options['class_names'].'\" value=\"1\" />';\n\n } else {\n $dataType = $options['data_type'] == 'email' ? 'email' : 'text';\n echo $label.'<input type=\"'.$dataType.'\" value=\"'.$escapedValue.'\" '.$commonAttrs.' class=\"form-control '.$options['class_names'].'\"/>';\n }\n\n echo '</div>';\n $this->renderedFields[] = $field;\n }", "smellKey": "S3776", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "function check_service($command)\n{\n // This array is used to test for valid UOM's to be used for graphing.\n // Valid values from: https://nagios-plugins.org/doc/guidelines.html#AEN200\n // Note: This array must be decend from 2 char to 1 char so that the search works correctly.\n $valid_uom = ['us', 'ms', 'KB', 'MB', 'GB', 'TB', 'c', 's', '%', 'B'];\n\n // Make our command safe.\n $parts = preg_split('~(?:\\'[^\\']*\\'|\"[^\"]*\")(*SKIP)(*F)|\\h+~', trim($command));\n $safe_command = implode(' ', array_map(function ($part) {\n $trimmed = preg_replace('/^(\\'(.*)\\'|\"(.*)\")$/', '$2$3', $part);\n\n return escapeshellarg($trimmed);\n }, $parts));\n\n d_echo(\"Request: $safe_command\\n\");\n\n // Run the command and return its response.\n exec('LC_NUMERIC=\"C\" ' . $safe_command, $response_array, $status);\n\n // exec returns an array, lets implode it back to a string.\n $response_string = implode(\"\\n\", $response_array);\n\n // Split out the response and the performance data.\n [$response, $perf] = explode('|', $response_string);\n\n // Split performance metrics into an array\n preg_match_all('/\\'[^\\']*\\'\\S*|\\S+/', $perf, $perf_arr);\n // preg_match_all returns a 2D array, we only need the first one\n $perf_arr = $perf_arr[0];\n\n // Create an array for our metrics.\n $metrics = [];\n\n // Loop through the perf string extracting our metric data\n foreach ($perf_arr as $string) {\n // Separate the DS and value: DS=value\n [$ds,$values] = explode('=', trim($string));\n\n // Keep the first value, discard the others.\n $value = explode(';', trim($values));\n $value = trim($value[0] ?? '');\n\n // Set an empty uom\n $uom = '';\n\n // is the UOM valid - https://nagios-plugins.org/doc/guidelines.html#AEN200\n foreach ($valid_uom as $v) {\n if ((strlen($value) - strlen($v)) === strpos($value, $v)) {\n // Yes, store and strip it off the value\n $uom = $v;\n $value = substr($value, 0, -strlen($v));\n break;\n }\n }\n\n if ($ds != '') {\n // Normalize ds for rrd : ds-name must be 1 to 19 characters long in the characters [a-zA-Z0-9_]\n // http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html\n $normalized_ds = preg_replace('/[^a-zA-Z0-9_]/', '', $ds);\n // if ds_name is longer than 19 characters, only use the first 19\n if (strlen($normalized_ds) > 19) {\n $normalized_ds = substr($normalized_ds, 0, 19);\n d_echo($ds . ' exceeded 19 characters, renaming to ' . $normalized_ds . \"\\n\");\n }\n if ($ds != $normalized_ds) {\n // ds has changed. check if normalized_ds is already in the array\n if (isset($metrics[$normalized_ds])) {\n d_echo($normalized_ds . \" collides with an existing index\\n\");\n $perf_unique = 0;\n // Try to generate a unique name\n for ($i = 0; $i < 10; $i++) {\n $tmp_ds_name = substr($normalized_ds, 0, 18) . $i;\n if (! isset($metrics[$tmp_ds_name])) {\n d_echo($normalized_ds . \" collides with an existing index\\n\");\n $normalized_ds = $tmp_ds_name;\n $perf_unique = 1;\n break;\n }\n }\n if ($perf_unique == 0) {\n // Try harder to generate a unique name\n for ($i = 0; $i < 10; $i++) {\n for ($j = 0; $j < 10; $j++) {\n $tmp_ds_name = substr($normalized_ds, 0, 17) . $j . $i;\n if (! isset($perf[$tmp_ds_name])) {\n $normalized_ds = $tmp_ds_name;\n $perf_unique = 1;\n break 2;\n }\n }\n }\n }\n if ($perf_unique == 0) {\n d_echo('could not generate a unique ds-name for ' . $ds . \"\\n\");\n }\n }\n $ds = $normalized_ds;\n }\n // We have a DS. Add an entry to the array.\n d_echo('Perf Data - DS: ' . $ds . ', Value: ' . $value . ', UOM: ' . $uom . \"\\n\");\n $metrics[$ds] = ['value' => $value, 'uom' => $uom];\n } else {\n // No DS. Don't add an entry to the array.\n d_echo(\"Perf Data - None.\\n\");\n }\n }\n\n return [$status, $response, $metrics];\n}", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function mb_detect_encoding($str, $encodingList = null, $strict = false)\n {\n if (null === $encodingList) {\n $encodingList = self::$encodingList;\n } else {\n if (!\\is_array($encodingList)) {\n $encodingList = array_map('trim', explode(',', $encodingList));\n }\n $encodingList = array_map('strtoupper', $encodingList);\n }\n\n foreach ($encodingList as $enc) {\n switch ($enc) {\n case 'ASCII':\n if (!preg_match('/[\\x80-\\xFF]/', $str)) {\n return $enc;\n }\n break;\n\n case 'UTF8':\n case 'UTF-8':\n if (preg_match('//u', $str)) {\n return 'UTF-8';\n }\n break;\n\n default:\n if (0 === strncmp($enc, 'ISO-8859-', 9)) {\n return $enc;\n }\n }\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function getFormsByCategory($state = '1', $lbfonly = false)\n{\n global $attendant_type;\n $all = array();\n if (!$lbfonly) {\n // First get the traditional form types from the registry table.\n $sql = \"SELECT category, nickname, name, state, directory, id, sql_run, \" .\n \"unpackaged, date, priority, aco_spec FROM registry WHERE \";\n if (($attendant_type ?? 'pid') == 'pid') {\n $sql .= \"patient_encounter = 1 AND \";\n } else {\n $sql .= \"therapy_group_encounter = 1 AND \";\n }\n $sql .= \"state LIKE ? ORDER BY category, priority, name\";\n $res = sqlStatement($sql, array($state));\n if ($res) {\n while ($row = sqlFetchArray($res)) {\n // Flag this entry as not LBF\n $row['LBF'] = false;\n $all[] = $row;\n }\n }\n }\n\n // Merge LBF form types into the registry array of form types.\n // Note that the mapping value is used as the category name.\n $lres = sqlStatement(\n \"SELECT * FROM layout_group_properties \" .\n \"WHERE grp_form_id LIKE 'LBF%' AND grp_group_id = '' AND grp_activity = 1 \" .\n \"ORDER BY grp_mapping, grp_seq, grp_title\"\n );\n while ($lrow = sqlFetchArray($lres)) {\n $rrow = array();\n $rrow['category'] = $lrow['grp_mapping'] ? $lrow['grp_mapping'] : 'Clinical';\n $rrow['name'] = $lrow['grp_title'];\n $rrow['nickname'] = $lrow['grp_title'];\n $rrow['directory'] = $lrow['grp_form_id']; // should start with LBF\n $rrow['priority'] = $lrow['grp_seq'];\n $rrow['aco_spec'] = $lrow['grp_aco_spec'];\n $rrow['LBF'] = true; // Flag this form as LBF\n $all[] = $rrow;\n }\n\n // Sort by category, priority, is lbf, name.\n usort($all, function ($a, $b) {\n // Anonymous functions supported as of PHP 5.3. Yay!\n if ($a['category'] == $b['category']) {\n if ($a['priority'] == $b['priority']) {\n if ($a['LBF'] == $b['LBF']) {\n $name1 = $a['nickname'] ? $a['nickname'] : $a['name'];\n $name2 = $b['nickname'] ? $b['nickname'] : $b['name'];\n if ($name1 == $name2) {\n return 0;\n }\n return $name1 < $name2 ? -1 : 1;\n } else {\n // Sort LBF with the same priority after standard forms\n return $b['LBF'] ? -1 : 1;\n }\n }\n return $a['priority'] < $b['priority'] ? -1 : 1;\n }\n return $a['category'] < $b['category'] ? -1 : 1;\n });\n return $all;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function run($args, $options) {\n global $ost, $cfg;\n\n Bootstrap::connect();\n\n if (!($ost=osTicket::start()) || !($cfg = $ost->getConfig()))\n $this->fail('Unable to load config info!');\n\n switch ($args['action']) {\n case 'import':\n if (!$options['file'] || $options['file'] == '-')\n $options['file'] = 'php://stdin';\n if (!($this->stream = fopen($options['file'], 'rb')))\n $this->fail(\"Unable to open input file [{$options['file']}]\");\n\n // Defaults\n $extras = array(\n 'isadmin' => 0,\n 'isactive' => 1,\n 'isvisible' => 1,\n 'dept_id' => $cfg->getDefaultDeptId(),\n 'timezone' => $cfg->getDefaultTimezone(),\n 'welcome_email' => $options['welcome'],\n );\n\n if ($options['backend'])\n $extras['backend'] = $options['backend'];\n\n $stderr = $this->stderr;\n $status = Staff::importCsv($this->stream, $extras,\n function ($agent, $data) use ($stderr, $options) {\n if (!$options['verbose'])\n return;\n $stderr->write(\n sprintf(\"\\n%s - %s --- imported!\",\n $agent->getName(),\n $agent->getUsername()));\n }\n );\n if (is_numeric($status))\n $this->stderr->write(\"Successfully processed $status agents\\n\");\n else\n $this->fail($status);\n break;\n\n case 'export':\n $stream = $options['file'] ?: 'php://stdout';\n if (!($this->stream = fopen($stream, 'c')))\n $this->fail(\"Unable to open output file [{$options['file']}]\");\n\n fputcsv($this->stream, array('First Name', 'Last Name', 'Email', 'UserName'));\n foreach ($this->getAgents($options) as $agent)\n fputcsv($this->stream, array(\n $agent->getFirstName(),\n $agent->getLastName(),\n $agent->getEmail(),\n $agent->getUserName(),\n ));\n break;\n\n case 'list':\n $agents = $this->getAgents($options);\n foreach ($agents as $A) {\n $this->stdout->write(sprintf(\n \"%d \\t - %s\\t<%s>\\n\",\n $A->staff_id, $A->getName(), $A->getEmail()));\n }\n break;\n\n case 'login':\n $this->stderr->write('Username: ');\n $username = trim(fgets(STDIN));\n $this->stderr->write('Password: ');\n $password = trim(fgets(STDIN));\n\n $agent = null;\n foreach (StaffAuthenticationBackend::allRegistered() as $id=>$bk) {\n if ((!$options['backend'] || $options['backend'] == $id)\n && $bk->supportsInteractiveAuthentication()\n && ($agent = $bk->authenticate($username, $password))\n && $agent instanceof AuthenticatedUser\n ) {\n break;\n }\n }\n\n if ($agent instanceof Staff) {\n $this->stdout->write(sprintf(\"Successfully authenticated as '%s', using '%s'\\n\",\n (string) $agent->getName(),\n $bk->getName()\n ));\n }\n else {\n $this->stdout->write('Authentication failed');\n }\n break;\n\n case 'backends':\n foreach (StaffAuthenticationBackend::allRegistered() as $name=>$bk) {\n if (!$bk->supportsInteractiveAuthentication())\n continue;\n $this->stdout->write(sprintf(\"%s\\t%s\\n\",\n $name, $bk->getName()\n ));\n }\n break;\n\n default:\n $this->fail($args['action'].': Unknown action!');\n }\n @fclose($this->stream);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "function resolve(string $basePath, string $newPath): string\n{\n $delta = parse($newPath);\n\n // If the new path defines a scheme, it's absolute and we can just return\n // that.\n if (null !== $delta['scheme']) {\n return build($delta);\n }\n\n $base = parse($basePath);\n $pick = function ($part) use ($base, $delta) {\n if (null !== $delta[$part]) {\n return $delta[$part];\n } elseif (null !== $base[$part]) {\n return $base[$part];\n }\n\n return null;\n };\n\n $newParts = [];\n\n $newParts['scheme'] = $pick('scheme');\n $newParts['host'] = $pick('host');\n $newParts['port'] = $pick('port');\n\n if (is_string($delta['path']) and strlen($delta['path']) > 0) {\n // If the path starts with a slash\n if ('/' === $delta['path'][0]) {\n $path = $delta['path'];\n } else {\n // Removing last component from base path.\n $path = (string) $base['path'];\n $length = strrpos($path, '/');\n if (false !== $length) {\n $path = substr($path, 0, $length);\n }\n $path .= '/'.$delta['path'];\n }\n } else {\n $path = $base['path'] ?? '/';\n if ('' === $path) {\n $path = '/';\n }\n }\n // Removing .. and .\n $pathParts = explode('/', $path);\n $newPathParts = [];\n foreach ($pathParts as $pathPart) {\n switch ($pathPart) {\n // case '' :\n case '.':\n break;\n case '..':\n array_pop($newPathParts);\n break;\n default:\n $newPathParts[] = $pathPart;\n break;\n }\n }\n\n $path = implode('/', $newPathParts);\n\n // If the source url ended with a /, we want to preserve that.\n $newParts['path'] = 0 === strpos($path, '/') ? $path : '/'.$path;\n // From PHP 8, no \"?\" query at all causes 'query' to be null.\n // An empty query \"http://example.com/foo?\" causes 'query' to be the empty string\n if (null !== $delta['query'] && '' !== $delta['query']) {\n $newParts['query'] = $delta['query'];\n } elseif (isset($base['query']) && null === $delta['host'] && null === $delta['path']) {\n // Keep the old query if host and path didn't change\n $newParts['query'] = $base['query'];\n }\n // From PHP 8, no \"#\" fragment at all causes 'fragment' to be null.\n // An empty fragment \"http://example.com/foo#\" causes 'fragment' to be the empty string\n if (null !== $delta['fragment'] && '' !== $delta['fragment']) {\n $newParts['fragment'] = $delta['fragment'];\n }\n\n return build($newParts);\n}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['purpose'])) {\n if (is_array($data['purpose'])) {\n foreach ($data['purpose'] as $d) {\n $this->addPurpose($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"purpose\" must be array of objects or null, ' . gettype($data['purpose']) . ' seen.');\n }\n }\n if (isset($data['patient'])) {\n $this->setPatient($data['patient']);\n }\n if (isset($data['servicedDate'])) {\n $this->setServicedDate($data['servicedDate']);\n }\n if (isset($data['servicedPeriod'])) {\n $this->setServicedPeriod($data['servicedPeriod']);\n }\n if (isset($data['created'])) {\n $this->setCreated($data['created']);\n }\n if (isset($data['requestor'])) {\n $this->setRequestor($data['requestor']);\n }\n if (isset($data['request'])) {\n $this->setRequest($data['request']);\n }\n if (isset($data['outcome'])) {\n $this->setOutcome($data['outcome']);\n }\n if (isset($data['disposition'])) {\n $this->setDisposition($data['disposition']);\n }\n if (isset($data['insurer'])) {\n $this->setInsurer($data['insurer']);\n }\n if (isset($data['insurance'])) {\n if (is_array($data['insurance'])) {\n foreach ($data['insurance'] as $d) {\n $this->addInsurance($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"insurance\" must be array of objects or null, ' . gettype($data['insurance']) . ' seen.');\n }\n }\n if (isset($data['preAuthRef'])) {\n $this->setPreAuthRef($data['preAuthRef']);\n }\n if (isset($data['form'])) {\n $this->setForm($data['form']);\n }\n if (isset($data['error'])) {\n if (is_array($data['error'])) {\n foreach ($data['error'] as $d) {\n $this->addError($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"error\" must be array of objects or null, ' . gettype($data['error']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public static function getDropdownNumber($post, $json = true)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n $used = [];\n\n if (isset($post['used'])) {\n $used = $post['used'];\n }\n\n if (!isset($post['value'])) {\n $post['value'] = 0;\n }\n\n if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }\n\n if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }\n\n $data = [];\n // Count real items returned\n $count = 0;\n\n if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $data[] = ['id' => $key,\n 'text' => (string)$val\n ];\n }\n }\n }\n\n $values = [];\n\n if (!isset($post['min'])) {\n $post['min'] = 1;\n }\n\n if (!isset($post['step'])) {\n $post['step'] = 1;\n }\n\n if (!isset($post['max'])) {\n //limit max entries to avoid loop issues\n $post['max'] = $CFG_GLPI['dropdown_max'] * $post['step'];\n }\n\n for ($i = $post['min']; $i <= $post['max']; $i += $post['step']) {\n if (!empty($post['searchText']) && strstr($i, $post['searchText']) || empty($post['searchText'])) {\n if (!in_array($i, $used)) {\n $values[\"$i\"] = $i;\n }\n }\n }\n\n if (count($values)) {\n $start = ($post['page'] - 1) * $post['page_limit'];\n $tosend = array_splice($values, $start, $post['page_limit']);\n foreach ($tosend as $i) {\n $txt = $i;\n if (isset($post['unit'])) {\n $decimals = Toolbox::isFloat($i) ? Toolbox::getDecimalNumbers($post['step']) : 0;\n $txt = Dropdown::getValueWithUnit($i, $post['unit'], $decimals);\n }\n $data[] = ['id' => $i,\n 'text' => (string)$txt\n ];\n $count++;\n }\n } else {\n if (!isset($toadd[-1])) {\n $value = -1;\n if (isset($post['min']) && $value < $post['min']) {\n $value = $post['min'];\n } else if (isset($post['max']) && $value > $post['max']) {\n $value = $post['max'];\n }\n\n $txt = $value;\n if (isset($post['unit'])) {\n $decimals = Toolbox::isFloat($value) ? Toolbox::getDecimalNumbers($post['step']) : 0;\n $txt = Dropdown::getValueWithUnit($value, $post['unit'], $decimals);\n }\n $data[] = [\n 'id' => $value,\n 'text' => (string)$txt\n ];\n $count++;\n }\n }\n\n $ret['results'] = $data;\n $ret['count'] = $count;\n\n return ($json === true) ? json_encode($ret) : $ret;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function call(): void\n {\n /**\n * @var \\DBmysql|null $DB\n * @var array $CFG_GLPI\n * @var array $PLUGIN_HOOKS\n */\n global $DB, $CFG_GLPI, $PLUGIN_HOOKS;\n\n // If config_db doesn't exist -> start installation\n if (!file_exists(GLPI_CONFIG_DIR . \"/config_db.php\") || !class_exists('DB', false)) {\n if (file_exists(GLPI_ROOT . '/install/install.php')) {\n Html::redirect(\"install/install.php\");\n } else {\n Session::loadLanguage('', false);\n // Prevent inclusion of debug information in footer, as they are based on vars that are not initialized here.\n $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;\n\n // no translation\n $title_text = 'GLPI seems to not be configured properly.';\n $missing_conf_text = sprintf('Database configuration file \"%s\" is missing.', GLPI_CONFIG_DIR . '/config_db.php');\n $hint_text = 'You have to either restart the install process, either restore this file.';\n\n Html::nullHeader('Missing configuration');\n echo '<div class=\"container-fluid mb-4\">';\n echo '<div class=\"row justify-content-center\">';\n echo '<div class=\"col-xl-6 col-lg-7 col-md-9 col-sm-12\">';\n echo '<h2>' . $title_text . '</h2>';\n echo '<p class=\"mt-2 mb-n2 alert alert-warning\">';\n echo $missing_conf_text;\n echo ' ';\n echo $hint_text;\n echo '</p>';\n echo '</div>';\n echo '</div>';\n echo '</div>';\n Html::nullFooter();\n return;\n }\n }\n\n Session::checkCookieSecureConfig();\n\n $_SESSION[\"glpicookietest\"] = 'testcookie';\n\n // For compatibility reason\n if (isset($_GET[\"noCAS\"])) {\n $_GET[\"noAUTO\"] = $_GET[\"noCAS\"];\n }\n\n if (!isset($_GET[\"noAUTO\"])) {\n Auth::redirectIfAuthenticated();\n }\n\n $redirect = $_GET['redirect'] ?? '';\n\n Auth::checkAlternateAuthSystems(true, $redirect);\n\n $errors = [];\n if (isset($_GET['error']) && $redirect !== '') {\n switch ($_GET['error']) {\n case 1: // cookie error\n $errors[] = __('You must accept cookies to reach this application');\n break;\n\n case 2: // GLPI_SESSION_DIR not writable\n $errors[] = __('Logins are not possible at this time. Please contact your administrator.');\n break;\n\n case 3:\n $errors[] = __('Your session has expired. Please log in again.');\n break;\n }\n }\n\n if (count($errors) > 0) {\n TemplateRenderer::getInstance()->display('pages/login_error.html.twig', [\n 'errors' => $errors,\n 'login_url' => $CFG_GLPI[\"root_doc\"] . '/front/logout.php?noAUTO=1&redirect=' . \\rawurlencode($redirect),\n ]);\n } else {\n if ($redirect !== '') {\n Toolbox::manageRedirect($redirect);\n }\n\n if (isset($_SESSION['mfa_pre_auth'], $_POST['skip_mfa'])) {\n Html::redirect($CFG_GLPI['root_doc'] . '/front/login.php?skip_mfa=1');\n }\n if (isset($_SESSION['mfa_pre_auth'])) {\n if (isset($_GET['mfa_setup'])) {\n if (isset($_POST['secret'], $_POST['totp_code'])) {\n $code = is_array($_POST['totp_code']) ? implode('', $_POST['totp_code']) : $_POST['totp_code'];\n $totp = new \\Glpi\\Security\\TOTPManager();\n if (Session::validateIDOR($_POST) && ($algorithm = $totp->verifyCodeForSecret($code, $_POST['secret'])) !== false) {\n $totp->setSecretForUser((int)$_SESSION['mfa_pre_auth']['user']['id'], $_POST['secret'], $algorithm);\n } else {\n Session::addMessageAfterRedirect(__s('Invalid code'), false, ERROR);\n }\n Html::redirect(Preference::getSearchURL());\n } else {\n // Login started. 2FA needs configured.\n $totp = new \\Glpi\\Security\\TOTPManager();\n $totp->showTOTPSetupForm((int)$_SESSION['mfa_pre_auth']['user']['id']);\n }\n } else {\n // Login started. Need to ask for the TOTP code.\n $totp = new \\Glpi\\Security\\TOTPManager();\n $totp->showTOTPPrompt((int) $_SESSION['mfa_pre_auth']['user']['id']);\n }\n } else {\n // Random number for html id/label\n $rand = mt_rand();\n\n // Regular login\n TemplateRenderer::getInstance()->display('pages/login.html.twig', [\n 'rand' => $rand,\n 'card_bg_width' => true,\n 'lang' => $CFG_GLPI[\"languages\"][$_SESSION['glpilanguage']][3],\n 'title' => __('Authentication'),\n 'noAuto' => $_GET[\"noAUTO\"] ?? 0,\n 'redirect' => $redirect,\n 'text_login' => $CFG_GLPI['text_login'],\n 'namfield' => ($_SESSION['namfield'] = \\uniqid('fielda')),\n 'pwdfield' => ($_SESSION['pwdfield'] = \\uniqid('fieldb')),\n 'rmbfield' => ($_SESSION['rmbfield'] = \\uniqid('fieldc')),\n 'show_lost_password' => $CFG_GLPI[\"notifications_mailing\"]\n && countElementsInTable('glpi_notifications', [\n 'itemtype' => 'User',\n 'event' => 'passwordforget',\n 'is_active' => 1\n ]),\n 'languages_dropdown' => Dropdown::showLanguages('language', [\n 'display' => false,\n 'rand' => $rand,\n 'display_emptychoice' => true,\n 'emptylabel' => __('Default (from user profile)'),\n 'width' => '100%'\n ]),\n 'right_panel' => strlen($CFG_GLPI['text_login']) > 0\n || count($PLUGIN_HOOKS[Hooks::DISPLAY_LOGIN] ?? []) > 0\n || $CFG_GLPI[\"use_public_faq\"],\n 'auth_dropdown_login' => Auth::dropdownLogin(false, $rand),\n 'copyright_message' => Html::getCopyrightMessage(false)\n ]);\n }\n }\n\n // call cron\n CronTask::callCronForce();\n\n echo \"</body></html>\";\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function doSoftValidation() {\n\t\t//if User or Group Base are not set, take over Base DN setting\n\t\tforeach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {\n\t\t\t$val = $this->configuration->$keyBase;\n\t\t\tif (empty($val)) {\n\t\t\t\t$this->configuration->$keyBase = $this->configuration->ldapBase;\n\t\t\t}\n\t\t}\n\n\t\tforeach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',\n\t\t\t'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']\n\t\t\t\tas $expertSetting => $effectiveSetting) {\n\t\t\t$uuidOverride = $this->configuration->$expertSetting;\n\t\t\tif (!empty($uuidOverride)) {\n\t\t\t\t$this->configuration->$effectiveSetting = $uuidOverride;\n\t\t\t} else {\n\t\t\t\t$uuidAttributes = Access::UUID_ATTRIBUTES;\n\t\t\t\tarray_unshift($uuidAttributes, 'auto');\n\t\t\t\tif (!in_array($this->configuration->$effectiveSetting, $uuidAttributes)\n\t\t\t\t\t&& !is_null($this->configID)) {\n\t\t\t\t\t$this->configuration->$effectiveSetting = 'auto';\n\t\t\t\t\t$this->configuration->saveConfiguration();\n\t\t\t\t\t$this->logger->info(\n\t\t\t\t\t\t'Illegal value for the '.$effectiveSetting.', reset to autodetect.',\n\t\t\t\t\t\t['app' => 'user_ldap']\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t$backupPort = (int)$this->configuration->ldapBackupPort;\n\t\tif ($backupPort <= 0) {\n\t\t\t$this->configuration->ldapBackupPort = $this->configuration->ldapPort;\n\t\t}\n\n\t\t//make sure empty search attributes are saved as simple, empty array\n\t\t$saKeys = ['ldapAttributesForUserSearch',\n\t\t\t'ldapAttributesForGroupSearch'];\n\t\tforeach ($saKeys as $key) {\n\t\t\t$val = $this->configuration->$key;\n\t\t\tif (is_array($val) && count($val) === 1 && empty($val[0])) {\n\t\t\t\t$this->configuration->$key = [];\n\t\t\t}\n\t\t}\n\n\t\tif ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)\n\t\t\t&& $this->configuration->ldapTLS) {\n\t\t\t$this->configuration->ldapTLS = false;\n\t\t\t$this->logger->info(\n\t\t\t\t'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',\n\t\t\t\t['app' => 'user_ldap']\n\t\t\t);\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public static function getTreeCategoryList(string $itemtype, array $params): array\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n /** @var class-string<CommonDBTM> $cat_itemtype */\n $cat_itemtype = static::getCategoryItemType($itemtype);\n $cat_item = new $cat_itemtype();\n\n $params['export_all'] = true;\n\n $data = Search::prepareDatasForSearch($itemtype, $params);\n Search::constructSQL($data);\n // This query is used to get the IDs of all results matching the search criteria\n $sql = $data['sql']['search'];\n // We can remove all the SELECT fields and replace it with just the ID field\n $raw_select = $data['sql']['raw']['SELECT'];\n $replacement_select = 'SELECT DISTINCT ' . $itemtype::getTableField('id');\n $sql_id = preg_replace('/^' . preg_quote($raw_select, '/') . '/', $replacement_select, $sql, 1);\n // Remove GROUP BY and ORDER BY clauses\n $sql_id = str_replace([$data['sql']['raw']['GROUPBY'], $data['sql']['raw']['ORDER']], '', $sql_id);\n\n $id_criteria = new QueryExpression($itemtype::getTableField('id') . ' IN ( SELECT * FROM (' . $sql_id . ') AS id_criteria )');\n\n $cat_table = $cat_itemtype::getTable();\n $cat_fk = $cat_itemtype::getForeignKeyField();\n $cat_join = $itemtype . '_' . $cat_itemtype;\n\n if (class_exists($cat_join)) {\n $cat_criteria = [1];\n // If there is a category filter, apply this filter to the tree too\n if (preg_match(\"/$cat_table/\", $data['sql']['raw']['WHERE'])) {\n // This query is used to get the IDs of all results matching the search criteria\n // We can remove all the SELECT fields and replace it with just the ID field\n $replacement_select = \"SELECT DISTINCT \" . $cat_join::getTableField($cat_fk);\n $sql_cat = preg_replace('/^' . preg_quote($raw_select, '/') . '/', $replacement_select, $sql, 1);\n // Remove GROUP BY and ORDER BY clauses\n $sql_cat = str_replace([$data['sql']['raw']['GROUPBY'], $data['sql']['raw']['ORDER']], '', $sql_cat);\n\n $cat_criteria = new QueryExpression($cat_join::getTableField($cat_fk) . ' IN ( SELECT * FROM (' . $sql_cat . ') AS cat_criteria )');\n }\n\n $join = [\n $cat_join::getTable() => [\n 'ON' => [\n $cat_join::getTable() => $itemtype::getForeignKeyField(),\n $itemtype::getTable() => 'id'\n ],\n $cat_criteria,\n ]\n ];\n } else {\n $join = [];\n $cat_join = $itemtype;\n }\n\n $items_subquery = new QuerySubQuery(\n [\n 'SELECT' => ['COUNT DISTINCT' => $itemtype::getTableField('id') . ' AS cpt'],\n 'FROM' => $itemtype::getTable(),\n 'LEFT JOIN' => $join,\n 'WHERE' => [\n $cat_join::getTableField($cat_fk) => new QueryExpression(\n $DB->quoteName($cat_itemtype::getTableField('id'))\n ),\n $id_criteria\n ]\n ],\n 'items_count'\n );\n\n $select[] = $cat_itemtype::getTableField('id');\n $select[] = $cat_itemtype::getTableField('name');\n if ($cat_item instanceof CommonTreeDropdown) {\n $select[] = $cat_itemtype::getTableField($cat_fk);\n }\n $select[] = $items_subquery;\n\n if ($cat_item instanceof CommonTreeDropdown) {\n $order[] = $cat_itemtype::getTableField('level') . ' DESC';\n $order[] = $cat_itemtype::getTableField('name');\n } else {\n $order[] = $cat_itemtype::getTableField('name') . ' DESC';\n }\n\n $cat_iterator = $DB->request([\n 'SELECT' => $select,\n 'FROM' => $cat_table,\n 'ORDER' => $order\n ]);\n\n $inst = new $cat_itemtype();\n $categories = [];\n $parents = [];\n foreach ($cat_iterator as $category) {\n if ($category instanceof CommonDropdown && $category->maybeTranslated()) {\n $tname = DropdownTranslation::getTranslatedValue(\n $category['id'],\n $inst->getType()\n );\n if (!empty($tname)) {\n $category['name'] = $tname;\n }\n }\n if (($category['items_count'] > 0) || (in_array($category['id'], $parents))) {\n $parents[] = $category[$cat_fk];\n $categories[] = $category;\n }\n }\n\n // Without category\n $join[$cat_table] = [\n 'ON' => [\n $cat_join::getTable() => $cat_itemtype::getForeignKeyField(),\n $cat_table => 'id'\n ]\n ];\n $no_cat_count = $DB->request(\n [\n 'SELECT' => ['COUNT DISTINCT' => $itemtype::getTableField('id') . ' as cpt'],\n 'FROM' => $itemtype::getTable(),\n 'LEFT JOIN' => $join,\n 'WHERE' => [\n $cat_itemtype::getTableField('id') => null,\n $id_criteria,\n ]\n ]\n )->current();\n $categories[] = [\n 'id' => -1,\n 'name' => __('Without Category'),\n 'items_count' => $no_cat_count['cpt'],\n $cat_fk => 0,\n ];\n\n // construct flat data\n $nodes = [];\n foreach ($categories as $category) {\n $cat_id = $category['id'];\n $node = [\n 'key' => $cat_id,\n 'title' => $category['name'],\n 'parent' => $category[$cat_fk] ?? 0,\n 'a_attr' => [\n 'data-id' => $cat_id\n ],\n ];\n\n if ($category['items_count'] > 0) {\n $node['title'] .= ' <span class=\"badge bg-azure-lt\" title=\"' . __s('This category contains ') . $itemtype::getTypeName() . '\">'\n . $category['items_count']\n . '</span>';\n }\n\n $nodes[] = $node;\n }\n\n // recursive construct tree data\n $buildtree = function (array &$elements, $parent = 0) use (&$buildtree) {\n $branch = [];\n\n foreach ($elements as $index => $element) {\n if ($element['parent'] === $parent) {\n $children = $buildtree($elements, $element['key']);\n if (count($children) > 0) {\n $element['children'] = $children;\n }\n $branch[] = $element;\n unset($elements[$index]);\n }\n }\n return $branch;\n };\n\n $newtree = $buildtree($nodes);\n\n return $newtree;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function get_potential_courses(array $target, int $lastcopied, int $userid): array\n {\n // see if we're allowed to do copies of copies\n $stm = $this->dbh->prepare('SELECT jsondata,UIver FROM imas_courses WHERE id=:sourcecid');\n $stm->execute(array(':sourcecid' => $target['refcid']));\n list($sourcejsondata, $sourceUIver) = $stm->fetch(PDO::FETCH_NUM);\n $sourcejsondata = json_decode($sourcejsondata, true);\n $blockLTICopyOfCopies = ($sourcejsondata !== null && !empty($sourcejsondata['blockLTICopyOfCopies']));\n\n $othercourses = array();\n\n if ($target['type'] == 'aid') {\n // look for other courses we could associate with\n $query = \"SELECT DISTINCT ic.id,ic.name FROM imas_courses AS ic JOIN imas_teachers AS imt ON ic.id=imt.courseid \";\n $query .= \"AND imt.userid=:userid JOIN imas_assessments AS ia ON ic.id=ia.courseid \";\n $query .= \"WHERE ic.available<4 AND ic.ancestors REGEXP :cregex AND ia.ancestors REGEXP :aregex ORDER BY ic.name\";\n $stm = $this->dbh->prepare($query);\n $stm->execute(array(\n ':userid' => $userid,\n ':cregex' => MYSQL_LEFT_WRDBND . $target['refcid'] . MYSQL_RIGHT_WRDBND,\n ':aregex' => MYSQL_LEFT_WRDBND . $target['refaid'] . MYSQL_RIGHT_WRDBND));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $othercourses[$row[0]] = $row[1];\n }\n } else if ($target['type'] == 'course') {\n // look for other courses we could associate with\n $query = \"SELECT DISTINCT ic.id,ic.name FROM imas_courses AS ic JOIN imas_teachers AS imt ON ic.id=imt.courseid \";\n $query .= \"AND imt.userid=:userid \";\n $query .= \"WHERE ic.available<4 AND ic.ancestors REGEXP :cregex ORDER BY ic.name\";\n $stm = $this->dbh->prepare($query);\n $stm->execute(array(\n ':userid' => $userid,\n ':cregex' => MYSQL_LEFT_WRDBND . $target['refcid'] . MYSQL_RIGHT_WRDBND));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $othercourses[$row[0]] = $row[1];\n }\n } else if (function_exists('lti_get_othercourses')) {\n $othercourses = lti_get_othercourses($target, $userid);\n }\n\n if ($blockLTICopyOfCopies) {\n $copycourses = array();\n } else {\n $copycourses = $othercourses;\n if ($lastcopied > 0 && !isset($copycourses[$lastcopied])) {\n // have a last copied courseid, but wasn't in the list above,\n // possible if user isn't owner. We'll add as an option anyway.\n $stm = $this->dbh->prepare('SELECT DISTINCT id,name FROM imas_courses WHERE id=?');\n $stm->execute(array($lastcopied));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $copycourses[$row[0]] = $row[1];\n }\n }\n }\n\n // get origin course\n $query = 'SELECT DISTINCT ic.id,ic.name,it.userid FROM imas_courses AS ic ';\n $query .= 'LEFT JOIN imas_teachers AS it ON it.courseid=ic.id AND it.userid=? WHERE ic.id=?';\n $stm = $this->dbh->prepare($query);\n $stm->execute(array($userid, $target['refcid']));\n while ($row = $stm->fetch(PDO::FETCH_NUM)) {\n $copycourses[$row[0]] = $row[1];\n // if it's user's course, also include in assoc list\n if ($row[2] == $userid) {\n $othercourses[$row[0]] = $row[1];\n }\n }\n return array($copycourses, $othercourses, $sourceUIver);\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function get2FAEnforcement(int $users_id): int\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $user_optional = $DB->request([\n 'SELECT' => ['2fa_unenforced'],\n 'FROM' => 'glpi_users',\n 'WHERE' => [\n 'id' => $users_id\n ],\n 'LIMIT' => 1\n ])->current()['2fa_unenforced'] ?? 0;\n\n if ($user_optional) {\n return self::ENFORCEMENT_OPTIONAL;\n }\n\n $enforced = false;\n if ((int) $CFG_GLPI['2fa_enforced'] === 1) {\n $enforced = true;\n } else {\n // Check entity configuration\n $entities = PermissionManager::getInstance()->getAllEntities($users_id);\n foreach ($entities as $entity) {\n if ((int) \\Entity::getUsedConfig('2fa_enforcement_strategy', $entity, '', 0) === 1) {\n $enforced = true;\n break;\n }\n }\n if (!$enforced) {\n // Check profile configuration\n $profiles = \\Profile_User::getUserProfiles($users_id);\n if (!empty($profiles)) {\n $enforced = $DB->request([\n 'SELECT' => ['2fa_enforced'],\n 'FROM' => 'glpi_profiles',\n 'WHERE' => [\n 'id' => $profiles,\n '2fa_enforced' => 1\n ]\n ])->count() > 0;\n }\n }\n if (!$enforced) {\n // Check group configuration\n $groups = \\Group_User::getUserGroups($users_id);\n $enforced = count(array_filter($groups, static fn ($group) => $group['2fa_enforced'])) > 0;\n }\n }\n\n if ($enforced) {\n $in_grace_period = $this->getGracePeriodDaysLeft() > 0;\n return $in_grace_period ? self::ENFORCEMENT_MANDATORY_GRACE_PERIOD : self::ENFORCEMENT_MANDATORY;\n }\n return self::ENFORCEMENT_OPTIONAL;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<TimingRepeat xmlns=\"http://hl7.org/fhir\"></TimingRepeat>');\n }\n parent::xmlSerialize(true, $sxe);\n if (isset($this->boundsDuration)) {\n $this->boundsDuration->xmlSerialize(true, $sxe->addChild('boundsDuration'));\n }\n if (isset($this->boundsRange)) {\n $this->boundsRange->xmlSerialize(true, $sxe->addChild('boundsRange'));\n }\n if (isset($this->boundsPeriod)) {\n $this->boundsPeriod->xmlSerialize(true, $sxe->addChild('boundsPeriod'));\n }\n if (isset($this->count)) {\n $this->count->xmlSerialize(true, $sxe->addChild('count'));\n }\n if (isset($this->countMax)) {\n $this->countMax->xmlSerialize(true, $sxe->addChild('countMax'));\n }\n if (isset($this->duration)) {\n $this->duration->xmlSerialize(true, $sxe->addChild('duration'));\n }\n if (isset($this->durationMax)) {\n $this->durationMax->xmlSerialize(true, $sxe->addChild('durationMax'));\n }\n if (isset($this->durationUnit)) {\n $this->durationUnit->xmlSerialize(true, $sxe->addChild('durationUnit'));\n }\n if (isset($this->frequency)) {\n $this->frequency->xmlSerialize(true, $sxe->addChild('frequency'));\n }\n if (isset($this->frequencyMax)) {\n $this->frequencyMax->xmlSerialize(true, $sxe->addChild('frequencyMax'));\n }\n if (isset($this->period)) {\n $this->period->xmlSerialize(true, $sxe->addChild('period'));\n }\n if (isset($this->periodMax)) {\n $this->periodMax->xmlSerialize(true, $sxe->addChild('periodMax'));\n }\n if (isset($this->periodUnit)) {\n $this->periodUnit->xmlSerialize(true, $sxe->addChild('periodUnit'));\n }\n if (0 < count($this->dayOfWeek)) {\n foreach ($this->dayOfWeek as $dayOfWeek) {\n $dayOfWeek->xmlSerialize(true, $sxe->addChild('dayOfWeek'));\n }\n }\n if (0 < count($this->timeOfDay)) {\n foreach ($this->timeOfDay as $timeOfDay) {\n $timeOfDay->xmlSerialize(true, $sxe->addChild('timeOfDay'));\n }\n }\n if (0 < count($this->when)) {\n foreach ($this->when as $when) {\n $when->xmlSerialize(true, $sxe->addChild('when'));\n }\n }\n if (isset($this->offset)) {\n $this->offset->xmlSerialize(true, $sxe->addChild('offset'));\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function parselibs($file) {\n\tif (!function_exists('gzopen')) {\n\t\t$handle = fopen($file,\"r\");\n\t\t$nogz = true;\n\t} else {\n\t\t$nogz = false;\n\t\t$handle = gzopen($file,\"r\");\n\t}\n\tif (!$handle) {\n\t\techo \"eek! handle doesn't exist\";\n\t\texit;\n\t}\n\t$line = '';\n\twhile (((!$nogz || !feof($handle)) && ($nogz || !gzeof($handle))) && $line!=\"START QUESTION\") {\n\t\tif ($nogz) {\n\t\t\t$line = rtrim(fgets($handle, 4096));\n\t\t} else {\n\t\t\t$line = rtrim(gzgets($handle, 4096));\n\t\t}\n\t\tif ($line==\"PACKAGE DESCRIPTION\") {\n\t\t\t$dopackd = true;\n\t\t\t$packname = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"INSTALLNAME\") {\n\t\t\t$dopackd = false;\n\t\t\t$sourceinstall = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"START LIBRARY\") {\n\t\t\t$dopackd = false;\n\t\t\t$libid = -1;\n\t\t} else if ($line==\"ID\") {\n\t\t\t$libid = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"UID\") {\n\t\t\t$unique[$libid] = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"LASTMODDATE\") {\n\t\t\t$lastmoddate[$libid] = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"OWNERID\") {\n\t\t\t$ownerid[$libid] = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"USERIGHTS\") {\n\t\t\t$userights[$libid] = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"NAME\") {\n\t\t\tif ($libid != -1) {\n\t\t\t\t$names[$libid] = rtrim(fgets($handle, 4096));\n\t\t\t}\n\t\t} else if ($line==\"PARENT\") {\n\t\t\tif ($libid != -1) {\n\t\t\t\t$parents[$libid]= rtrim(fgets($handle, 4096));\n\t\t\t}\n\t\t} else if ($line==\"START LIBRARY ITEMS\") {\n\t\t\t$libitemid = -1;\n\t\t} else if ($line==\"LIBID\") {\n\t\t\t$libitemid = rtrim(fgets($handle, 4096));\n\t\t} else if ($line==\"QSETIDS\") {\n\t\t\tif ($libitemid!=-1) {\n\t\t\t\t$libitems[$libitemid] = rtrim(fgets($handle, 4096));\n\t\t\t}\n\t\t} else if ($dopackd ==true) {\n\t\t\t$packname .= rtrim($line);\n\t\t}\n\t}\n\tif ($nogz) {\n\t\tfclose($handle);\n\t} else {\n\t\tgzclose($handle);\n\t}\n\treturn array($packname,$names,$parents,$libitems,$unique,$lastmoddate,$ownerid,$userights,$sourceinstall);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function transfer(TransferForm $form, &$errors, $alert=true) {\n global $thisstaff, $cfg;\n\n // Check if staff can do the transfer\n if (!$this->checkStaffPerm($thisstaff, Ticket::PERM_TRANSFER))\n return false;\n\n $cdept = $this->getDept(); // Current department\n $dept = $form->getDept(); // Target department\n if (!$dept || !($dept instanceof Dept))\n $errors['dept'] = __('Department selection required');\n elseif ($dept->getid() == $this->getDeptId())\n $errors['dept'] = sprintf(\n __('%s already in the department'), __('Ticket'));\n else {\n $this->dept_id = $dept->getId();\n\n // Make sure the new department allows assignment to the\n // currently assigned agent (if any)\n if ($this->isAssigned()\n && ($staff=$this->getStaff())\n && $dept->assignMembersOnly()\n && !$dept->isMember($staff)\n ) {\n $this->staff_id = 0;\n }\n }\n\n if ($errors || !$this->save(true))\n return false;\n\n // Reopen ticket if closed\n if ($this->isClosed())\n $this->reopen();\n\n // Set SLA of the new department\n if (!$this->getSLAId() || $this->getSLA()->isTransient())\n if (($slaId=$this->getDept()->getSLAId()))\n $this->selectSLAId($slaId);\n\n // Log transfer event\n $this->logEvent('transferred', array('dept' => $dept->getName()));\n\n if (($referral=$this->hasReferral($dept,ObjectModel::OBJECT_TYPE_DEPT)))\n $referral->delete();\n\n // Post internal note if any\n $note = null;\n $comments = $form->getField('comments')->getClean();\n if ($comments) {\n $title = sprintf(__('%1$s transferred from %2$s to %3$s'),\n __('Ticket'),\n $cdept->getName(),\n $dept->getName());\n\n $_errors = array();\n $note = $this->postNote(\n array('note' => $comments, 'title' => $title),\n $_errors, $thisstaff, false);\n }\n\n if ($form->refer() && $cdept)\n $this->getThread()->refer($cdept);\n\n //Send out alerts if enabled AND requested\n if (!$alert || !$cfg->alertONTransfer() || !$dept->getNumMembersForAlerts())\n return true; //no alerts!!\n\n if (($email = $dept->getAlertEmail())\n && ($tpl = $dept->getTemplate())\n && ($msg=$tpl->getTransferAlertMsgTemplate())\n ) {\n $msg = $this->replaceVars($msg->asArray(),\n array('comments' => $note, 'staff' => $thisstaff));\n // Recipients\n $recipients = array();\n // Assigned staff or team... if any\n if($this->isAssigned() && $cfg->alertAssignedONTransfer()) {\n if($this->getStaffId())\n $recipients[] = $this->getStaff();\n elseif ($this->getTeamId()\n && ($team=$this->getTeam())\n && ($members=$team->getMembersForAlerts())\n ) {\n $recipients = array_merge($recipients, $members);\n }\n }\n elseif ($cfg->alertDeptMembersONTransfer() && !$this->isAssigned()) {\n // Only alerts dept members if the ticket is NOT assigned.\n foreach ($dept->getMembersForAlerts() as $M)\n $recipients[] = $M;\n }\n\n // Always alert dept manager??\n if ($cfg->alertDeptManagerONTransfer()\n && $dept\n && ($manager=$dept->getManager())\n ) {\n $recipients[] = $manager;\n }\n $sentlist = $options = array();\n if ($note) {\n $options += array('thread'=>$note);\n }\n foreach ($recipients as $k=>$staff) {\n if (!is_object($staff)\n || !$staff->isAvailable()\n || in_array($staff->getEmail(), $sentlist)\n ) {\n continue;\n }\n $alert = $this->replaceVars($msg, array('recipient' => $staff));\n $email->sendAlert($staff, $alert['subj'], $alert['body'], null, $options);\n $sentlist[] = $staff->getEmail();\n }\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function fullOutputHtml($showUdi = true)\n {\n $html = '';\n if (!empty($this->udi_data['standard_elements']['deviceName'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Name (GMDN PT Name)') . ': </span>' . text($this->udi_data['standard_elements']['deviceName']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['deviceDescription'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Description') . ': </span>' . text($this->udi_data['standard_elements']['deviceDescription']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['brandName'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Brand Name') . ': </span>' . text($this->udi_data['standard_elements']['brandName']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['companyName'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Company Name') . ': </span>' . text($this->udi_data['standard_elements']['companyName']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['versionModelNumber'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Version/Model Number') . ': </span>' . text($this->udi_data['standard_elements']['versionModelNumber']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['di'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('DI (Device Identifier)') . ': </span>' . text($this->udi_data['standard_elements']['di']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['serialNumber'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Serial Number') . ': </span>' . text($this->udi_data['standard_elements']['serialNumber']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['lotNumber'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Lot Number') . ': </span>' . text($this->udi_data['standard_elements']['lotNumber']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['donationId'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Donation ID') . ': </span>' . text($this->udi_data['standard_elements']['donationId']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['expirationDate'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Expiration Date') . ': </span>' . text($this->udi_data['standard_elements']['expirationDate']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['manufacturingDate'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Manufacturing Date') . ': </span>' . text($this->udi_data['standard_elements']['manufacturingDate']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['MRISafetyStatus'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('MRI Safety Status') . ': </span>' . text($this->udi_data['standard_elements']['MRISafetyStatus']) . '<br>';\n }\n if (!empty($this->udi_data['standard_elements']['labeledContainsNRL'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('This device is required to be labeled as containing natural rubber latex or dry natural rubber.') . '</span><br>';\n }\n if (!empty($this->udi_data['standard_elements']['deviceHCTP'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('This device is labeled as a Human Cell, Tissue or Cellular or Tissue-Based Product (HCT/P).') . '</span><br>';\n }\n if (!empty($this->udi_data['standard_elements']['issuingAgency'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('Issuing Agency') . ': </span>' . text($this->udi_data['standard_elements']['issuingAgency']);\n $html .= '<br>';\n\n if (in_array($this->udi_data['standard_elements']['issuingAgency'], self::ISSUING_AGENCY_FDA_AUTHORITY)) {\n // we don't translate the FDA as its a US agency.\n $html .= '<span class=\"font-weight-bold\">' . xlt('Assigning Authority') . ': </span>FDA<br />';\n }\n }\n if ($showUdi && !empty($this->udi_data['standard_elements']['udi'])) {\n $html .= '<span class=\"font-weight-bold\">' . xlt('UDI (Unique Device Identifier)') . ': </span>' . text($this->udi_data['standard_elements']['udi']) . '<br>';\n }\n return $html;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function canRead($pFilename)\n {\n // Check if file exists\n if (!file_exists($pFilename)) {\n throw new PHPExcel_Reader_Exception(\"Could not open \" . $pFilename . \" for reading! File does not exist.\");\n }\n\n $zipClass = PHPExcel_Settings::getZipClass();\n\n // Check if zip class exists\n// if (!class_exists($zipClass, false)) {\n// throw new PHPExcel_Reader_Exception($zipClass . \" library is not enabled\");\n// }\n\n $mimeType = 'UNKNOWN';\n // Load file\n $zip = new $zipClass;\n if ($zip->open($pFilename) === true) {\n // check if it is an OOXML archive\n $stat = $zip->statName('mimetype');\n if ($stat && ($stat['size'] <= 255)) {\n $mimeType = $zip->getFromName($stat['name']);\n } elseif ($stat = $zip->statName('META-INF/manifest.xml')) {\n $xml = simplexml_load_string($this->securityScan($zip->getFromName('META-INF/manifest.xml')), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());\n $namespacesContent = $xml->getNamespaces(true);\n if (isset($namespacesContent['manifest'])) {\n $manifest = $xml->children($namespacesContent['manifest']);\n foreach ($manifest as $manifestDataSet) {\n $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);\n if ($manifestAttributes->{'full-path'} == '/') {\n $mimeType = (string) $manifestAttributes->{'media-type'};\n break;\n }\n }\n }\n }\n\n $zip->close();\n\n return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet');\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "SonarCloudOre_Ore", "language": "php"} {"function": "function multiprintplain_header($p)\n {\n $this->providerid = $p->provider->id;\n $sql = \"SELECT f.name, f.street, f.state, f.postal_code, f.phone, if(f.fax != '', f.fax, '') FROM users JOIN facility AS f ON f.name = users.facility where users.id = ?\";\n $result = QueryUtils::fetchRecords($sql, [$p->provider->id]);\n $address = '';\n if (!empty($result)) {\n $res = $result[0];\n $parts = [];\n $parts[] = $res['name'];\n $parts[] = $res['street'];\n if (!empty($res['city'])) {\n $parts[] = $res['city'] ?? '' . ', ' . $res['state'] ?? '' . ' ' . $res['postal_code'] ?? '';\n } else if (!empty($res['state']) && !empty($res['postal_code'])) {\n $parts[] = $res['state'] ?? '' . ' ' . $res['postal_code'] ?? '';\n }\n if (!empty($res['phone'])) {\n $parts[] = xl('Tel:') . $res['phone'] ?? '';\n }\n if (!empty($res['fax'])) {\n $parts[] = xl('Fax:') . $res['fax'] ?? '';\n }\n $address = implode(\"\\n\", $parts);\n if (trim($address) == \"\") {\n $address = \"\";\n }\n }\n echo xl(\"Digital Prescription Information\") . \"\\n\";\n echo xl(\"Prescriber\") . \"\\n\";\n echo $address;\n echo (\"\\n\");\n echo (\"\\n\");\n echo ($p->provider->get_name_display()) . \"\\n\";\n\n if ($GLOBALS['rx_enable_DEA']) {\n if ($GLOBALS['rx_show_DEA']) {\n echo (xl('DEA') . ':' . $p->provider->federal_drug_id . \"\\n\");\n } else {\n echo (xl('DEA') . \": ________________________\\n\" );\n }\n }\n\n if ($GLOBALS['rx_enable_NPI']) {\n if ($GLOBALS['rx_show_NPI']) {\n echo (xl('NPI') . ':' . $p->provider->npi . '') . \"\\n\";\n } else {\n echo ('' . xl('NPI') . \": ________________________\\n\");\n }\n }\n\n if ($GLOBALS['rx_enable_SLN']) {\n if ($GLOBALS['rx_show_SLN']) {\n echo (xl('State Lic. #') . ':' . $p->provider->state_license_number . \"\\n\");\n } else {\n echo (xl('State Lic. #') . \": ________________________\\n\");\n }\n }\n echo \"\\n\\n\";\n echo (xl('Patient Name & Address') . \"\\n\");\n echo ($p->patient->get_name_display() . \"\\n\");\n $sql = \"SELECT street, city, `state`, postal_code, if(phone_home!='',phone_home,if(phone_cell!='',phone_cell,if(phone_biz!='',phone_biz,''))) AS phone from patient_data where pid = ?\";\n $result = QueryUtils::fetchRecords($sql, [$p->patient->id]);\n $address = '';\n if (!empty($result)) {\n $res = $result[0];\n $parts = [];\n $parts[] = $res['street'];\n if (!empty($res['city'])) {\n $parts[] = $res['city'] ?? '' . ', ' . $res['state'] ?? '' . ' ' . $res['postal_code'] ?? '';\n } else if (!empty($res['state']) && !empty($res['postal_code'])) {\n $parts[] = $res['state'] ?? '' . ' ' . $res['postal_code'] ?? '';\n }\n\n if (!empty($res['phone'])) {\n $parts[] = xl('Tel:') . $res['phone'] ?? '';\n }\n $address = implode(\"\\n\", $parts);\n $address = trim($address);\n }\n\n echo ($address);\n echo \"\\n\";\n echo (xl('Date of Birth')) . \" \";\n echo ($p->patient->date_of_birth );\n echo \"\\n\";\n echo xl('Medical Record #');\n echo (str_pad($p->patient->get_pubpid(), 10, \"0\", STR_PAD_LEFT));\n echo \"\\n\\n\";\n echo xl('Prescriptions') . \"\\n\";\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function processReset()\n {\n $reset_token_value = trim(Tools::getValue('reset_token'));\n $id_employee = trim(Tools::getValue('id_employee'));\n $reset_email = $this->IDNConverter->emailToUtf8(trim(Tools::getValue('reset_email')));\n $reset_password = trim(Tools::getValue('reset_passwd'));\n $reset_confirm = trim(Tools::getValue('reset_confirm'));\n Hook::exec(\n 'actionAdminLoginControllerResetBefore',\n [\n 'controller' => $this,\n 'reset_token_value' => $reset_token_value,\n 'id_employee' => $id_employee,\n 'reset_email' => $reset_email,\n 'reset_password' => $reset_password,\n 'reset_confirm' => $reset_confirm,\n ]\n );\n\n if (_PS_MODE_DEMO_) {\n $this->errors[] = $this->trans('This functionality has been disabled.', [], 'Admin.Notifications.Error');\n } elseif (!$reset_token_value) {\n // hidden fields\n $this->errors[] = $this->trans('Some identification information is missing.', [], 'Admin.Login.Notification');\n } elseif (!$id_employee) {\n $this->errors[] = $this->trans('Some identification information is missing.', [], 'Admin.Login.Notification');\n } elseif (!$reset_email) {\n $this->errors[] = $this->trans('Some identification information is missing.', [], 'Admin.Login.Notification');\n } elseif (!$reset_password) {\n // password (twice)\n $this->errors[] = $this->trans('The password is missing: please enter your new password.', [], 'Admin.Login.Notification');\n } elseif (!Validate::isPasswd($reset_password)) {\n $this->errors[] = $this->trans('The password is not in a valid format.', [], 'Admin.Login.Notification');\n } elseif (!$reset_confirm) {\n $this->errors[] = $this->trans('The confirmation is empty: please fill in the password confirmation as well.', [], 'Admin.Login.Notification');\n } elseif ($reset_password !== $reset_confirm) {\n $this->errors[] = $this->trans('The password and its confirmation do not match. Please double check both passwords.', [], 'Admin.Login.Notification');\n } else {\n $employee = new Employee();\n if (!$employee->getByEmail($reset_email) || !$employee || $employee->id != $id_employee) { // check matching employee id with its email\n $this->errors[] = $this->trans('This account does not exist.', [], 'Admin.Login.Notification');\n } elseif ((strtotime($employee->last_passwd_gen . '+' . Configuration::get('PS_PASSWD_TIME_BACK') . ' minutes') - time()) > 0) {\n $this->errors[] = $this->trans('You can reset your password every %interval% minute(s) only. Please try again later.', ['%interval%' => Configuration::get('PS_PASSWD_TIME_BACK')], 'Admin.Login.Notification');\n } elseif ($employee->getValidResetPasswordToken() !== $reset_token_value) {\n // To update password, we must have the temporary reset token that matches.\n $this->errors[] = $this->trans('Your password reset request expired. Please start again.', [], 'Admin.Login.Notification');\n }\n }\n\n if (!count($this->errors)) {\n $employee->passwd = $this->get('hashing')->hash($reset_password, _COOKIE_KEY_);\n $employee->last_passwd_gen = date('Y-m-d H:i:s', time());\n\n $params = [\n '{email}' => $employee->email,\n '{lastname}' => $employee->lastname,\n '{firstname}' => $employee->firstname,\n ];\n\n $employeeLanguage = new Language((int) $this->context->employee->id_lang);\n\n if (\n Mail::Send(\n $employee->id_lang,\n 'password',\n $this->trans(\n 'Your new password',\n [],\n 'Emails.Subject',\n $employeeLanguage->locale\n ),\n $params,\n $employee->email,\n $employee->firstname . ' ' . $employee->lastname\n )\n ) {\n // Update employee only if the mail can be sent\n Shop::setContext(Shop::CONTEXT_SHOP, (int) min($employee->getAssociatedShops()));\n\n $result = $employee->update();\n if (!$result) {\n $this->errors[] = $this->trans('An error occurred while attempting to change your password.', [], 'Admin.Login.Notification');\n } else {\n $employee->removeResetPasswordToken(); // Delete temporary reset token\n $employee->update();\n\n Hook::exec(\n 'actionAdminLoginControllerResetAfter',\n [\n 'controller' => $this,\n 'employee' => $employee,\n ]\n );\n die(Tools::jsonEncode([\n 'hasErrors' => false,\n 'confirm' => $this->trans('The password has been changed successfully.', [], 'Admin.Login.Notification'),\n ]));\n }\n } else {\n die(Tools::jsonEncode([\n 'hasErrors' => true,\n 'errors' => [$this->trans('An error occurred while attempting to change your password.', [], 'Admin.Login.Notification')],\n ]));\n }\n } elseif (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(['hasErrors' => true, 'errors' => $this->errors]));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function dispatch()\n {\n $controller_class = '';\n\n // Get current controller\n $this->getController();\n if (!$this->controller) {\n $this->controller = $this->useDefaultController();\n }\n // Dispatch with right front controller\n switch ($this->front_controller) {\n // Dispatch front office controller\n case self::FC_FRONT :\n $controllers = Dispatcher::getControllers(array(_PS_FRONT_CONTROLLER_DIR_, _PS_OVERRIDE_DIR_.'controllers/front/'));\n $controllers['index'] = 'IndexController';\n if (isset($controllers['auth'])) {\n $controllers['authentication'] = $controllers['auth'];\n }\n if (isset($controllers['contact'])) {\n $controllers['contactform'] = $controllers['contact'];\n }\n\n if (!isset($controllers[strtolower($this->controller)])) {\n $this->controller = $this->controller_not_found;\n }\n $controller_class = $controllers[strtolower($this->controller)];\n $params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 0);\n break;\n\n // Dispatch module controller for front office\n case self::FC_MODULE :\n $module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';\n $module = Module::getInstanceByName($module_name);\n $controller_class = 'PageNotFoundController';\n if (Validate::isLoadedObject($module) && $module->active) {\n $controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$module_name.'/controllers/front/');\n if (isset($controllers[strtolower($this->controller)])) {\n include_once(_PS_MODULE_DIR_.$module_name.'/controllers/front/'.$this->controller.'.php');\n $controller_class = $module_name.$this->controller.'ModuleFrontController';\n }\n }\n $params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 1);\n break;\n\n // Dispatch back office controller + module back office controller\n case self::FC_ADMIN :\n if ($this->use_default_controller && !Tools::getValue('token') && Validate::isLoadedObject(Context::getContext()->employee) && Context::getContext()->employee->isLoggedBack()) {\n Tools::redirectAdmin('index.php?controller='.$this->controller.'&token='.Tools::getAdminTokenLite($this->controller));\n }\n\n $tab = Tab::getInstanceFromClassName($this->controller, Configuration::get('PS_LANG_DEFAULT'));\n $retrocompatibility_admin_tab = null;\n\n if ($tab->module) {\n if (file_exists(_PS_MODULE_DIR_.$tab->module.'/'.$tab->class_name.'.php')) {\n $retrocompatibility_admin_tab = _PS_MODULE_DIR_.$tab->module.'/'.$tab->class_name.'.php';\n } else {\n $controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$tab->module.'/controllers/admin/');\n if (!isset($controllers[strtolower($this->controller)])) {\n $this->controller = $this->controller_not_found;\n $controller_class = 'AdminNotFoundController';\n } else {\n // Controllers in modules can be named AdminXXX.php or AdminXXXController.php\n include_once(_PS_MODULE_DIR_.$tab->module.'/controllers/admin/'.$controllers[strtolower($this->controller)].'.php');\n $controller_class = $controllers[strtolower($this->controller)].(strpos($controllers[strtolower($this->controller)], 'Controller') ? '' : 'Controller');\n }\n }\n $params_hook_action_dispatcher = array('controller_type' => self::FC_ADMIN, 'controller_class' => $controller_class, 'is_module' => 1);\n } else {\n $controllers = Dispatcher::getControllers(array(_PS_ADMIN_DIR_.'/tabs/', _PS_ADMIN_CONTROLLER_DIR_, _PS_OVERRIDE_DIR_.'controllers/admin/'));\n if (!isset($controllers[strtolower($this->controller)])) {\n // If this is a parent tab, load the first child\n if (Validate::isLoadedObject($tab) && $tab->id_parent == 0 && ($tabs = Tab::getTabs(Context::getContext()->language->id, $tab->id)) && isset($tabs[0])) {\n Tools::redirectAdmin(Context::getContext()->link->getAdminLink($tabs[0]['class_name']));\n }\n $this->controller = $this->controller_not_found;\n }\n\n $controller_class = $controllers[strtolower($this->controller)];\n $params_hook_action_dispatcher = array('controller_type' => self::FC_ADMIN, 'controller_class' => $controller_class, 'is_module' => 0);\n\n if (file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php')) {\n $retrocompatibility_admin_tab = _PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php';\n }\n }\n\n // @retrocompatibility with admin/tabs/ old system\n if ($retrocompatibility_admin_tab) {\n include_once($retrocompatibility_admin_tab);\n include_once(_PS_ADMIN_DIR_.'/functions.php');\n runAdminTab($this->controller, !empty($_REQUEST['ajaxMode']));\n return;\n }\n\n break;\n\n default :\n throw new PrestaShopException('Bad front controller chosen');\n }\n\n // Instantiate controller\n try {\n // Loading controller\n $controller = Controller::getController($controller_class);\n\n // Execute hook dispatcher\n if (isset($params_hook_action_dispatcher)) {\n Hook::exec('actionDispatcher', $params_hook_action_dispatcher);\n }\n\n // Running controller\n $controller->run();\n } catch (PrestaShopException $e) {\n $e->displayMessage();\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function fetchProcedureActivityData($entry): void\n {\n if (\n (!empty($entry['procedure']['code']['code']) || !empty($entry['procedure']['code'][\"nullFlavor\"] ?? ''))\n && ($entry['procedure']['code'][\"nullFlavor\"] ?? '') != 'NI'\n ) {\n $i = 1;\n if (!empty($this->templateData['field_name_value_array']['procedure'])) {\n $i += count($this->templateData['field_name_value_array']['procedure']);\n }\n\n $code = $this->codeService->resolveCode(\n $entry['procedure']['code']['code'] ?? '',\n ($entry['procedure']['code']['codeSystemName'] ?? '') ?: $entry['procedure']['code']['codeSystem'] ?? null,\n $entry['procedure']['code']['displayName'] ?? ''\n );\n if (!empty($entry['procedure']['code'][\"nullFlavor\"]) && !empty($entry['procedure']['code'][\"valueSet\"])) {\n $code['code'] = $entry['procedure']['code'][\"valueSet\"] ?? null;\n $code['formatted_code'] = 'OID:' . $entry['procedure']['code'][\"valueSet\"] ?? null;\n $code['code_text'] = $entry['procedure']['text'] ?? '';\n }\n\n $procedure_type = 'order';\n\n $this->templateData['field_name_value_array']['procedure'][$i]['extension'] = $entry['procedure']['id']['extension'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['root'] = $entry['procedure']['id']['root'] ?? null;\n\n $this->templateData['field_name_value_array']['procedure'][$i]['code'] = $code['formatted_code'];\n $this->templateData['field_name_value_array']['procedure'][$i]['code_text'] = $code['code_text'];\n $this->templateData['field_name_value_array']['procedure'][$i]['codeSystemName'] = $code['formatted_code_type'];\n\n $this->templateData['field_name_value_array']['procedure'][$i]['procedure_type'] = $procedure_type;\n $this->templateData['field_name_value_array']['procedure'][$i]['status'] = $entry['procedure']['statusCode']['code'] ?? '';\n\n if (!empty($entry['procedure']['effectiveTime']['low']['value'])) {\n $this->templateData['field_name_value_array']['procedure'][$i]['date'] = $entry['procedure']['effectiveTime']['low']['value'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['date_end'] = $entry['procedure']['effectiveTime']['high']['value'] ?? null;\n } else {\n $this->templateData['field_name_value_array']['procedure'][$i]['date'] = $entry['procedure']['effectiveTime']['value'] ?? null;\n }\n\n // check for a reason code if observation.\n if (is_array($entry['procedure']['entryRelationship'] ?? '')) {\n $entryRelationship = $entry['procedure']['entryRelationship'][1];\n } else {\n $entryRelationship = $entry['procedure']['entryRelationship'] ?? '';\n }\n if ($entryRelationship['observation']['value']['code'] ?? '') {\n $code = $this->codeService->resolveCode(\n $entryRelationship['observation']['value']['code'],\n $entryRelationship['observation']['value']['codeSystemName'] ?: $entryRelationship['observation']['value']['codeSystem'] ?? '',\n $entryRelationship['observation']['value']['displayName']\n );\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_code'] = $code['formatted_code'];\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_code_text'] = $code['code_text'];\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_description'] = $code['code_text'] ?? $entry['observation']['text'];\n $date_low = $entryRelationship['observation']['effectiveTime']['low']['value'] ?? null;\n $date_high = $entryRelationship['observation']['effectiveTime']['high']['value'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_date_low'] = $date_low;\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_date_high'] = $date_high;\n }\n\n $this->templateData['field_name_value_array']['procedure'][$i]['reason_status'] = (($entry['procedure']['negationInd'] ?? 'false') == 'true') ? 'negated' : null;\n\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization1'] = $entry['procedure']['performer']['assignedEntity']['representedOrganization']['name'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_address1'] = $entry['procedure']['performer']['assignedEntity']['addr']['streetAddressLine'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_city1'] = $entry['procedure']['performer']['assignedEntity']['addr']['city'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_state1'] = $entry['procedure']['performer']['assignedEntity']['addr']['state'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_postalcode1'] = $entry['procedure']['performer']['assignedEntity']['addr']['postalCode'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_country1'] = $entry['procedure']['performer']['assignedEntity']['addr']['country'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_telecom1'] = $entry['procedure']['performer']['assignedEntity']['telecom']['value'] ?? null;\n\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization2'] = $entry['procedure']['participant']['participantRole']['playingEntity']['name'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_address2'] = $entry['procedure']['participant']['participantRole']['addr']['streetAddressLine'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_city2'] = $entry['procedure']['participant']['participantRole']['addr']['city'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_state2'] = $entry['procedure']['participant']['participantRole']['addr']['state'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_postalcode2'] = $entry['procedure']['participant']['participantRole']['addr']['postalCode'] ?? null;\n $this->templateData['field_name_value_array']['procedure'][$i]['represented_organization_country2'] = $entry['procedure']['participant']['participantRole']['addr']['country'] ?? null;\n\n $this->templateData['entry_identification_array']['procedure'][$i] = $i;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getResult(): ScorePartResult\n {\n global $mathfuncs;\n\n $scorePartResult = new ScorePartResult();\n\n $RND = $this->scoreQuestionParams->getRandWrapper();\n $options = $this->scoreQuestionParams->getVarsForScorePart();\n $qn = $this->scoreQuestionParams->getQuestionNumber();\n $givenans = $this->scoreQuestionParams->getGivenAnswer();\n $multi = $this->scoreQuestionParams->getIsMultiPartQuestion();\n $partnum = $this->scoreQuestionParams->getQuestionPartNumber();\n $isRescore = $this->scoreQuestionParams->getIsRescore();\n\n $defaultreltol = .0015;\n\n $optionkeys = ['answer', 'reltolerance', 'abstolerance', 'answerformat',\n 'answersize', 'answerformat', 'ansprompt', 'scoremethod'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n if ($reltolerance === '' && $abstolerance === '') { $reltolerance = $defaultreltol;}\n\n $ansformats = array_map('trim',explode(',',$answerformat));\n\n if ($multi) { $qn = ($qn+1)*1000+$partnum; }\n $correct = true;\n\n $givenans = normalizemathunicode($givenans);\n\n if (in_array('nosoln',$ansformats) || in_array('nosolninf',$ansformats)) {\n list($givenans, $answer) = scorenosolninf($qn, $givenans, $answer, $ansprompt);\n }\n\n if ($givenans==='oo' || $givenans==='DNE') {\n $scorePartResult->setLastAnswerAsGiven($givenans);\n } else if (!empty($answersize)) {\n $sizeparts = explode(',',$answersize);\n $N = $sizeparts[0];\n $stuN = $sizeparts[0];\n if ($isRescore) {\n $givenanslist = explode('|', $givenans);\n } else {\n for ($i=0; $i<$sizeparts[0]*$sizeparts[1]; $i++) {\n $givenanslist[$i] = $_POST[\"qn$qn-$i\"];\n }\n }\n $scorePartResult->setLastAnswerAsGiven(implode(\"|\",$givenanslist));\n } else {\n //$givenans = preg_replace('/\\)\\s*,\\s*\\(/','),(',$givenans);\n $scorePartResult->setLastAnswerAsGiven($givenans);\n //$givenanslist = explode(\",\",preg_replace('/[^\\d,\\.\\-]/','',$givenans));\n list($givenanslist, $stuN) = parseMatrixToArray($givenans);\n }\n \n //handle nosolninf case\n if ($givenans==='oo' || $givenans==='DNE') {\n if ($answer==$givenans) {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n } else if ($answer==='DNE' || $answer==='oo') {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n $fullmatrix = true;\n foreach ($givenanslist as $j=>$v) {\n if (!is_numeric($v)) {\n $fullmatrix = false;\n }\n }\n /*\n $answer = preg_replace('/\\)\\s*,\\s*\\(/','),(',$answer);\n if (strlen($answer)>1 && $answer[1] != '(') {\n $ansr = substr($answer,1,-1);\n } else {\n $ansr = substr($answer,2,-2);\n }\n $ansr = preg_replace('/\\)\\s*\\,\\s*\\(/',',',$ansr);\n $answerlist = explode(',',$ansr);\n */\n list($answerlist, $N) = parseMatrixToArray($answer);\n\n if ($stuN != $N) {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n\n if (count($answerlist) != count($givenanslist) || $answerlist[0]==='' || $givenanslist[0]==='') {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n foreach ($answerlist as $k=>$v) {\n $v = evalMathParser($v);\n if (is_nan($v)) {\n if (isset($GLOBALS['teacherid'])) {\n echo _('Debug info: invalid $answer');\n }\n $answerlist[$k] = 0;\n } else {\n $answerlist[$k] = preg_replace('/[^\\d\\.,\\-E]/','',$v);\n }\n }\n\n if ($fullmatrix && in_array('scalarmult',$ansformats)) {\n //scale givenanslist to the magnitude of $answerlist\n $mag = sqrt(array_sum(array_map(function($x) {return $x*$x;}, $answerlist)));\n $mag2 = sqrt(array_sum(array_map(function($x) {return $x*$x;}, $givenanslist)));\n if ($mag > 0 && $mag2 > 0) {\n foreach ($answerlist as $j=>$v) {\n if (abs($v)>1e-10) {\n if ($answerlist[$j]*$givenanslist[$j]<0) {\n $mag *= -1;\n }\n break;\n }\n }\n foreach ($givenanslist as $j=>$v) {\n $givenanslist[$j] = $mag/$mag2*$v;\n }\n }\n }\n\n if ($fullmatrix && (in_array('ref',$ansformats) || in_array('rowequiv',$ansformats))) {\n // reduce correct answer to rref\n $answerlist = matrix_scorer_rref($answerlist, $N);\n $M = count($answerlist) / $N;\n if (in_array('ref',$ansformats)) {\n for ($r=0;$r<$N;$r++) {\n $c = 0;\n while ($c < $M && abs($answerlist[$r*$M+$c]) < 1e-10) {\n if (abs($givenanslist[$r*$M+$c]) > 1e-10) {\n $correct = false; // nonzero where 0 expected\n }\n $c++;\n }\n /* Removed: Not all ref defs include leading 1's\n if ($c < $M) { // if there's a first non-zero entry, should be 1\n if (abs($givenanslist[$r*$M+$c] - 1) > 1e-10) {\n $correct = false;\n }\n }\n */\n }\n }\n // now reduce given answer to rref\n if ($correct) {\n $givenanslist = matrix_scorer_rref($givenanslist, $N);\n }\n } else if ($fullmatrix && in_array('anyroworder',$ansformats)) {\n $answerlist = matrix_scorer_roworder($answerlist, $N);\n $givenanslist = matrix_scorer_roworder($givenanslist, $N);\n }\n\n $incorrect = 0;\n for ($i=0; $i<count($answerlist); $i++) {\n if (!is_numeric($givenanslist[$i])) {\n $incorrect++;\n continue;\n } else if ($abstolerance !== '') {\n if (abs($answerlist[$i] - $givenanslist[$i]) > $abstolerance+1E-12) {\n $incorrect++;\n continue;\n }\n } else {\n if (abs($answerlist[$i] - $givenanslist[$i])/(abs($answerlist[$i])+.0001) > $reltolerance+1E-12) {\n $incorrect++;\n continue;\n }\n }\n }\n\n if ($correct && $incorrect == 0) {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else if ($correct && $scoremethod == 'byelement') {\n $score = (count($answerlist) - $incorrect)/count($answerlist);\n $scorePartResult->setRawScore($score);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "#[Override]\n public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n // The Item_Ticket tab is only supported on CommonDBTM objects\n if (!($item instanceof CommonDBTM)) {\n return \"\";\n }\n\n // This tab might be hidden on assets\n if (in_array($item::getType(), $CFG_GLPI['asset_types']) && !$this->shouldDisplayTabForAsset($item)) {\n return '';\n }\n\n $nb = 0;\n if (!($item instanceof Ticket)) {\n $title = Ticket::getTypeName(Session::getPluralNumber());\n\n if ($_SESSION['glpishow_count_on_tabs']) {\n // Direct one\n $nb = countElementsInTable(\n 'glpi_items_tickets',\n [\n 'INNER JOIN' => [\n 'glpi_tickets' => [\n 'FKEY' => [\n 'glpi_items_tickets' => 'tickets_id',\n 'glpi_tickets' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->getID(),\n 'is_deleted' => 0\n ]\n ]\n );\n\n // Linked items\n $linkeditems = $item->getLinkedItems();\n if (count($linkeditems)) {\n foreach ($linkeditems as $type => $tab) {\n $nb += countElementsInTable(\n 'glpi_items_tickets',\n [\n 'INNER JOIN' => [\n 'glpi_tickets' => [\n 'FKEY' => [\n 'glpi_items_tickets' => 'tickets_id',\n 'glpi_tickets' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'itemtype' => $type,\n 'items_id' => $tab,\n 'is_deleted' => 0\n ]\n ]\n );\n }\n }\n }\n } else {\n $title = _n('Item', 'Items', Session::getPluralNumber());\n if ($_SESSION['glpishow_count_on_tabs']) {\n $nb = self::countForMainItem($item);\n }\n }\n\n return self::createTabEntry($title, $nb, $item::getType());\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function smarty_function_html_radios($params, &$smarty)\n{\n require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');\n \n $name = 'radio';\n $values = null;\n $options = null;\n $selected = null;\n $separator = '';\n $labels = true;\n $label_ids = false;\n $output = null;\n $extra = '';\n\n foreach($params as $_key => $_val) {\n switch($_key) {\n case 'name':\n case 'separator':\n $$_key = (string)$_val;\n break;\n\n case 'checked':\n case 'selected':\n if(is_array($_val)) {\n $smarty->trigger_error('html_radios: the \"' . $_key . '\" attribute cannot be an array', E_USER_WARNING);\n } else {\n $selected = (string)$_val;\n }\n break;\n\n case 'labels':\n case 'label_ids':\n $$_key = (bool)$_val;\n break;\n\n case 'options':\n $$_key = (array)$_val;\n break;\n\n case 'values':\n case 'output':\n $$_key = array_values((array)$_val);\n break;\n\n case 'radios':\n $smarty->trigger_error('html_radios: the use of the \"radios\" attribute is deprecated, use \"options\" instead', E_USER_WARNING);\n $options = (array)$_val;\n break;\n\n case 'assign':\n break;\n\n default:\n if(!is_array($_val)) {\n $extra .= ' '.$_key.'=\"'.smarty_function_escape_special_chars($_val).'\"';\n } else {\n $smarty->trigger_error(\"html_radios: extra attribute '$_key' cannot be an array\", E_USER_NOTICE);\n }\n break;\n }\n }\n\n if (!isset($options) && !isset($values))\n return ''; /* raise error here? */\n\n $_html_result = array();\n\n if (isset($options)) {\n\n foreach ($options as $_key=>$_val)\n $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids);\n\n } else {\n\n foreach ($values as $_i=>$_key) {\n $_val = isset($output[$_i]) ? $output[$_i] : '';\n $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids);\n }\n\n }\n\n if(!empty($params['assign'])) {\n $smarty->assign($params['assign'], $_html_result);\n } else {\n return implode(\"\\n\",$_html_result);\n }\n\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function processUploads()\n {\n $uploadFields = $this->getUploadFields();\n if (!$uploadFields) {\n return;\n }\n\n foreach ($uploadFields as $field) {\n if ($field->getRelationship()) {\n $name = $field->getRelationshipName();\n $dataItem = $this->relations[$name] ?? null;\n } else {\n $name = $field->name;\n $dataItem = $this->data[$name] ?? null;\n }\n if (!$dataItem) {\n continue;\n }\n if ($dataItem instanceof UploadedFile) {\n if ($field->getRelationship()) {\n $this->relations[$name] = $this->storeUploadedFile($dataItem, $field)->id;\n } else {\n $this->data[$name] = $this->storeUploadedFile($dataItem, $field)->file_path ?? '';\n }\n } elseif (is_array($dataItem)) {\n if ($field->getRelationship()) {\n $this->relations[$name] = $this->storeUploadedFiles($dataItem, $field);\n } else {\n $this->data[$name] = $this->storeUploadedFiles($dataItem, $field);\n }\n }\n }\n\n }", "smellKey": "S3776", "smellId": null, "repo": "trihai306_tts-demo", "language": "php"} {"function": "public function parseFhirResource(FHIRDomainResource $fhirResource)\n {\n // TODO: ONC certification only deals with READ operations, the mapping of FHIR values such as language,ethnicity\n // etc are NOT being done here and so the creation/updating of resources is currently NOT correct, this will\n // need to be addressed by future development work.\n if (!$fhirResource instanceof FHIRPatient) {\n throw new \\BadMethodCallException(\"fhir resource must be of type \" . FHIRPractitioner::class);\n }\n\n $data = array();\n $data['uuid'] = (string)$fhirResource->getId() ?? null;\n\n if (!empty($fhirResource->getName())) {\n $name = new FHIRHumanName();\n foreach ($fhirResource->getName() as $sub_name) {\n if ((string)$sub_name->getUse() === 'official') {\n $name = $sub_name;\n break;\n }\n }\n $data['lname'] = (string)$name->getFamily() ?? null;\n\n $given = $name->getGiven() ?? [];\n // we cast due to the way FHIRString works\n $data['fname'] = (string)($given[0] ?? null);\n $data['mname'] = (string)($given[1] ?? null);\n\n $prefix = $name->getPrefix() ?? [];\n // we don't support updating the title right now, it requires updating another table which is breaking\n // the service class. As far as I can tell, this was never tested and never worked.\n $data['title'] = $prefix[0] ?? null;\n }\n\n $addresses = $fhirResource->getAddress();\n if (!empty($addresses)) {\n $activeAddress = $addresses[0];\n $mostRecentPeriods = UtilsService::getPeriodTimestamps($activeAddress->getPeriod());\n foreach ($fhirResource->getAddress() as $address) {\n $addressPeriod = UtilsService::getPeriodTimestamps($address->getPeriod());\n if (empty($addressPeriod['end'])) {\n $activeAddress = $address;\n } elseif (!empty($mostRecentPeriods['end']) && $addressPeriod['end'] > $mostRecentPeriods['end']) {\n // if our current period is more recent than our most recent address we want to grab that one\n $mostRecentPeriods = $addressPeriod;\n $activeAddress = $address;\n }\n }\n\n $lineValues = array_map(function ($val) {\n return (string)$val;\n }, $activeAddress->getLine() ?? []);\n $data['street'] = implode(\"\\n\", $lineValues) ?? null;\n $data['postal_code'] = (string)$activeAddress->getPostalCode() ?? null;\n $data['city'] = (string)$activeAddress->getCity() ?? null;\n $data['state'] = (string)$activeAddress->getState() ?? null;\n }\n\n $telecom = $fhirResource->getTelecom();\n if (!empty($telecom)) {\n foreach ($telecom as $contactPoint) {\n $systemValue = (string)$contactPoint->getSystem() ?? \"contact_other\";\n $contactValue = (string)$contactPoint->getValue();\n if ($systemValue === 'email') {\n $use = (string)$contactPoint->getUse() ?? \"home\";\n $useMapping = ['mobile' => 'email_direct'];\n if (isset($useMapping[$use])) {\n $data[$useMapping[$use]] = $contactValue;\n } else {\n $data[$systemValue] = (string)$contactValue;\n }\n } elseif ($systemValue == \"phone\") {\n $use = (string)$contactPoint->getUse() ?? \"work\";\n $useMapping = ['mobile' => 'phone_cell', 'home' => 'phone_home', 'work' => 'phone_biz'];\n if (isset($useMapping[$use])) {\n $data[$useMapping[$use]] = $contactValue;\n }\n }\n }\n }\n\n $data['DOB'] = (string)$fhirResource->getBirthDate();\n $data['sex'] = (string)$fhirResource->getGender();\n\n foreach ($fhirResource->getIdentifier() as $index => $identifier) {\n $type = $identifier->getType();\n $validCodes = ['SS' => 'ss', 'PT' => 'pubpid'];\n $coding = $type->getCoding() ?? [];\n foreach ($coding as $codingItem) {\n $codingCode = (string)$codingItem->getCode();\n\n if (isset($validCodes[$codingCode])) {\n $data[$validCodes[$codingCode]] = $identifier->getValue() ?? null;\n }\n }\n }\n\n if (!empty($fhirResource->getGeneralPractitioner())) {\n $providerReference = UtilsService::parseReference($fhirResource->getGeneralPractitioner()[0]);\n if (!empty($providerReference) && $providerReference['resourceType'] === 'Practitioner' && $providerReference['localResource']) {\n $data['provider_uuid'] = $providerReference['uuid'];\n }\n }\n\n return $data;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function generate(): void\n {\n global $RND, $myrights, $useeqnhelper, $showtips, $imasroot;\n\n $anstype = $this->answerBoxParams->getAnswerType();\n $qn = $this->answerBoxParams->getQuestionNumber();\n $multi = $this->answerBoxParams->getIsMultiPartQuestion();\n $partnum = $this->answerBoxParams->getQuestionPartNumber();\n $la = $this->answerBoxParams->getStudentLastAnswers();\n $options = $this->answerBoxParams->getQuestionWriterVars();\n $colorbox = $this->answerBoxParams->getColorboxKeyword();\n $isConditional = $this->answerBoxParams->getIsConditional();\n\n $out = '';\n $tip = '';\n $sa = '';\n $preview = '';\n $params = [];\n\n $optionkeys = ['answerboxsize', 'answerformat', 'answer', 'displayformat',\n 'ansprompt', 'readerlabel'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n\n $ansformats = array_map('trim', explode(',', $answerformat));\n if (empty($answerboxsize)) {$answerboxsize = 20;}\n if ($multi) {$qn = ($qn + 1) * 1000 + $partnum;}\n\n if (in_array('list', $ansformats)) {\n if (in_array('allowjcomplex', $ansformats)) {\n $tip = _('Enter your answer as a list of complex numbers in a+bj form separated with commas. Example: 2+5.5172j,-3-4j') . \"<br/>\";\n } else {\n $tip = _('Enter your answer as a list of complex numbers in a+bi form separated with commas. Example: 2+5.5172i,-3-4i') . \"<br/>\";\n }\n $shorttip = _('Enter a list of complex numbers');\n } else {\n if (in_array('allowjcomplex', $ansformats)) {\n $tip = _('Enter your answer as a complex number in a+bj form. Example: 2+5.5172j') . \"<br/>\";\n } else {\n $tip = _('Enter your answer as a complex number in a+bi form. Example: 2+5.5172i') . \"<br/>\";\n }\n $shorttip = _('Enter a complex number');\n }\n if (!in_array('nosoln', $ansformats) && !in_array('nosolninf', $ansformats)) {\n $tip .= _('Enter DNE for Does Not Exist');\n }\n\n $classes = ['text'];\n if ($colorbox != '') {\n $classes[] = $colorbox;\n }\n $attributes = [\n 'type' => 'text',\n 'size' => $answerboxsize,\n 'name' => \"qn$qn\",\n 'id' => \"qn$qn\",\n 'value' => $la,\n 'autocomplete' => 'off',\n 'aria-label' => $this->answerBoxParams->getQuestionIdentifierString() .\n (!empty($readerlabel) ? ' ' . Sanitize::encodeStringForDisplay($readerlabel) : ''),\n ];\n $params['tip'] = $shorttip;\n $params['longtip'] = $tip;\n $params['calcformat'] = $answerformat . ($answerformat == '' ? '' : ',') . 'decimal';\n $out .= '<input ' .\n Sanitize::generateAttributeString($attributes) .\n 'class=\"' . implode(' ', $classes) .\n '\" />';\n $out .= \"<span id=p$qn></span>\";\n if (in_array('nosoln', $ansformats) || in_array('nosolninf', $ansformats)) {\n list($out, $answer) = setupnosolninf($qn, $out, $answer, $ansformats, $la, $ansprompt, $colorbox);\n $answer = str_replace('\"', '', $answer);\n }\n if ($answer !== '' && !is_array($answer) && !$isConditional) {\n $sa = makepretty($answer);\n }\n\n // Done!\n $this->answerBox = $out;\n $this->jsParams = $params;\n $this->entryTip = $tip;\n $this->correctAnswerForPart = (string) $sa;\n $this->previewLocation = $preview;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->subject)) {\n $json['subject'] = $this->subject;\n }\n if (0 < count($this->country)) {\n $json['country'] = [];\n foreach ($this->country as $country) {\n $json['country'][] = $country;\n }\n }\n if (0 < count($this->jurisdiction)) {\n $json['jurisdiction'] = [];\n foreach ($this->jurisdiction as $jurisdiction) {\n $json['jurisdiction'][] = $jurisdiction;\n }\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->statusDate)) {\n $json['statusDate'] = $this->statusDate;\n }\n if (isset($this->restoreDate)) {\n $json['restoreDate'] = $this->restoreDate;\n }\n if (isset($this->validityPeriod)) {\n $json['validityPeriod'] = $this->validityPeriod;\n }\n if (isset($this->dataExclusivityPeriod)) {\n $json['dataExclusivityPeriod'] = $this->dataExclusivityPeriod;\n }\n if (isset($this->dateOfFirstAuthorization)) {\n $json['dateOfFirstAuthorization'] = $this->dateOfFirstAuthorization;\n }\n if (isset($this->internationalBirthDate)) {\n $json['internationalBirthDate'] = $this->internationalBirthDate;\n }\n if (isset($this->legalBasis)) {\n $json['legalBasis'] = $this->legalBasis;\n }\n if (0 < count($this->jurisdictionalAuthorization)) {\n $json['jurisdictionalAuthorization'] = [];\n foreach ($this->jurisdictionalAuthorization as $jurisdictionalAuthorization) {\n $json['jurisdictionalAuthorization'][] = $jurisdictionalAuthorization;\n }\n }\n if (isset($this->holder)) {\n $json['holder'] = $this->holder;\n }\n if (isset($this->regulator)) {\n $json['regulator'] = $this->regulator;\n }\n if (isset($this->procedure)) {\n $json['procedure'] = $this->procedure;\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function auth($uid, $pwd , $method = '', $tls = true, $authz = '')\n {\n /* We can only attempt a TLS connection if one has been requested,\n * we're running PHP 5.1.0 or later, have access to the OpenSSL\n * extension, are connected to an SMTP server which supports the\n * STARTTLS extension, and aren't already connected over a secure\n * (SSL) socket connection. */\n if ($tls && version_compare(PHP_VERSION, '5.1.0', '>=')\n && extension_loaded('openssl') && isset($this->esmtp['STARTTLS'])\n && strncasecmp($this->host, 'ssl://', 6) !== 0\n ) {\n /* Start the TLS connection attempt. */\n if (PEAR::isError($result = $this->put('STARTTLS'))) {\n return $result;\n }\n if (PEAR::isError($result = $this->parseResponse(220))) {\n return $result;\n }\n if (isset($this->socket_options['ssl']['crypto_method'])) {\n $crypto_method = $this->socket_options['ssl']['crypto_method'];\n } else {\n /* STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT constant does not exist\n * and STREAM_CRYPTO_METHOD_SSLv23_CLIENT constant is\n * inconsistent across PHP versions. */\n $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT\n | @STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT\n | @STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;\n }\n if (PEAR::isError($result = $this->socket->enableCrypto(true, $crypto_method))) {\n return $result;\n } elseif ($result !== true) {\n return PEAR::raiseError('STARTTLS failed');\n }\n\n /* Send EHLO again to recieve the AUTH string from the\n * SMTP server. */\n $this->negotiate();\n }\n\n if (empty($this->esmtp['AUTH'])) {\n return PEAR::raiseError('SMTP server does not support authentication');\n }\n\n /* If no method has been specified, get the name of the best\n * supported method advertised by the SMTP server. */\n if (empty($method)) {\n if (PEAR::isError($method = $this->getBestAuthMethod())) {\n /* Return the PEAR_Error object from _getBestAuthMethod(). */\n return $method;\n }\n } else {\n $method = strtoupper($method);\n if (!array_key_exists($method, $this->auth_methods)) {\n return PEAR::raiseError(\"$method is not a supported authentication method\");\n }\n }\n\n if (!isset($this->auth_methods[$method])) {\n return PEAR::raiseError(\"$method is not a supported authentication method\");\n }\n\n if (!is_callable($this->auth_methods[$method], false)) {\n return PEAR::raiseError(\"$method authentication method cannot be called\");\n }\n\n if (is_array($this->auth_methods[$method])) {\n list($object, $method) = $this->auth_methods[$method];\n $result = $object->{$method}($uid, $pwd, $authz, $this);\n } else {\n $func = $this->auth_methods[$method];\n $result = $func($uid, $pwd, $authz, $this);\n }\n\n /* If an error was encountered, return the PEAR_Error object. */\n if (PEAR::isError($result)) {\n return $result;\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "protected function updateQueryString(array $extraParams = null)\n {\n $uriWithoutParams = explode('?', $_SERVER['REQUEST_URI'])[0];\n $url = Tools::getCurrentUrlProtocolPrefix() . $_SERVER['HTTP_HOST'] . $uriWithoutParams;\n $params = array();\n $paramsFromUri = '';\n if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {\n $paramsFromUri = explode('?', $_SERVER['REQUEST_URI'])[1];\n }\n parse_str($paramsFromUri, $params);\n\n if (null !== $extraParams) {\n foreach ($extraParams as $key => $value) {\n if (null === $value) {\n unset($params[$key]);\n } else {\n $params[$key] = $value;\n }\n }\n }\n\n if (null !== $extraParams) {\n foreach ($params as $key => $param) {\n if (null === $param || '' === $param) {\n unset($params[$key]);\n }\n }\n } else {\n $params = array();\n }\n\n $queryString = str_replace('%2F', '/', http_build_query($params, '', '&'));\n\n return $url . ($queryString ? \"?$queryString\" : '');\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function _generateTableHeader($pSheet) {\n\t\t$sheetIndex = $pSheet->getParent()->getIndex($pSheet);\n\n\t\t// Construct HTML\n\t\t$html = '';\n\n\t\tif (!$this->_useInlineCss) {\n\t\t\t$gridlines = $pSheet->getShowGridLines() ? ' gridlines' : '';\n\t\t\t$html .= '\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"sheet' . $sheetIndex . '\" class=\"sheet' . $sheetIndex . $gridlines . '\">' . PHP_EOL;\n\t\t} else {\n\t\t\t$style = isset($this->_cssStyles['table']) ?\n\t\t\t\t$this->_assembleCSS($this->_cssStyles['table']) : '';\n\n\t\t\tif ($this->_isPdf && $pSheet->getShowGridLines()) {\n\t\t\t\t$html .= '\t<table border=\"1\" cellpadding=\"1\" id=\"sheet' . $sheetIndex . '\" cellspacing=\"4\" style=\"' . $style . '\">' . PHP_EOL;\n\t\t\t} else {\n\t\t\t\t$html .= '\t<table border=\"0\" cellpadding=\"1\" id=\"sheet' . $sheetIndex . '\" cellspacing=\"4\" style=\"' . $style . '\">' . PHP_EOL;\n\t\t\t}\n\t\t}\n\n\t\t// Write <col> elements\n\t\t$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1;\n\t\t$i = -1;\n\t\twhile($i++ < $highestColumnIndex) {\n\t\t\tif (!$this->_useInlineCss) {\n\t\t\t\t$html .= '\t\t<col class=\"col' . $i . '\">' . PHP_EOL;\n\t\t\t} else {\n\t\t\t\t$style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?\n\t\t\t\t\t$this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';\n\t\t\t\t$html .= '\t\t<col style=\"' . $style . '\">' . PHP_EOL;\n\t\t\t}\n\t\t}\n\n\t\t// Return\n\t\treturn $html;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "function notifyCollaborators($entry, $vars = array()) {\n global $cfg;\n\n if (!$entry instanceof ThreadEntry\n || !($recipients=$this->getRecipients())\n || !($dept=$this->getDept())\n || !($tpl=$dept->getTemplate())\n || !($msg=$tpl->getActivityNoticeMsgTemplate())\n || !($email=$dept->getEmail())\n ) {\n return;\n }\n\n $poster = User::lookup($entry->user_id);\n $posterEmail = $poster->getEmail()->address;\n\n $vars = array_merge($vars, array(\n 'message' => (string) $entry,\n 'poster' => $poster ?: _S('A collaborator'),\n )\n );\n\n $msg = $this->replaceVars($msg->asArray(), $vars);\n\n $attachments = $cfg->emailAttachments()?$entry->getAttachments():array();\n $options = array('thread' => $entry);\n\n if ($vars['from_name'])\n $options += array('from_name' => $vars['from_name']);\n\n $skip = array();\n if ($entry instanceof MessageThreadEntry) {\n foreach ($entry->getAllEmailRecipients() as $R) {\n $skip[] = $R->mailbox.'@'.$R->host;\n }\n }\n\n foreach ($recipients as $key => $recipient) {\n $recipient = $recipient->getContact();\n\n if(get_class($recipient) == 'TicketOwner')\n $owner = $recipient;\n\n if ((get_class($recipient) == 'Collaborator' ? $recipient->getUserId() : $recipient->getId()) == $entry->user_id)\n unset($recipients[$key]);\n }\n\n if (!count($recipients))\n return true;\n\n //see if the ticket user is a recipient\n if ($owner->getEmail()->address != $poster->getEmail()->address && !in_array($owner->getEmail()->address, $skip))\n $owner_recip = $owner->getEmail()->address;\n\n //say dear collaborator if the ticket user is not a recipient\n if (!$owner_recip) {\n $nameFormats = array_keys(PersonsName::allFormats());\n $names = array();\n foreach ($nameFormats as $key => $value) {\n $names['recipient.name.' . $value] = __('Collaborator');\n }\n $names = array_merge($names, array('recipient' => $recipient));\n $cnotice = $this->replaceVars($msg, $names);\n }\n //otherwise address email to ticket user\n else\n $cnotice = $this->replaceVars($msg, array('recipient' => $owner));\n\n $email->send($recipients, $cnotice['subj'], $cnotice['body'], $attachments,\n $options);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "public function copyInfoAction(Request $request): JsonResponse\n {\n $transactionId = time();\n $pasteJobs = [];\n\n Tool\\Session::useBag($request->getSession(), function (AttributeBagInterface $session) use ($transactionId) {\n $session->set((string) $transactionId, ['idMapping' => []]);\n }, 'pimcore_copy');\n\n if ($request->get('type') == 'recursive' || $request->get('type') == 'recursive-update-references') {\n $object = DataObject::getById((int) $request->get('sourceId'));\n\n // first of all the new parent\n $pasteJobs[] = [[\n 'url' => $this->generateUrl('pimcore_admin_dataobject_dataobject_copy'),\n 'method' => 'POST',\n 'params' => [\n 'sourceId' => $request->get('sourceId'),\n 'targetId' => $request->get('targetId'),\n 'type' => 'child',\n 'transactionId' => $transactionId,\n 'saveParentId' => true,\n ],\n ]];\n\n if ($object->hasChildren(DataObject::$types)) {\n // get amount of children\n $list = new DataObject\\Listing();\n $list->setCondition('`path` LIKE ' . $list->quote($list->escapeLike($object->getRealFullPath()) . '/%'));\n $list->setOrderKey('LENGTH(`path`)', false);\n $list->setOrder('ASC');\n $list->setObjectTypes(DataObject::$types);\n $childIds = $list->loadIdList();\n\n if (count($childIds) > 0) {\n foreach ($childIds as $id) {\n $pasteJobs[] = [[\n 'url' => $this->generateUrl('pimcore_admin_dataobject_dataobject_copy'),\n 'method' => 'POST',\n 'params' => [\n 'sourceId' => $id,\n 'targetParentId' => $request->get('targetId'),\n 'sourceParentId' => $request->get('sourceId'),\n 'type' => 'child',\n 'transactionId' => $transactionId,\n ],\n ]];\n }\n }\n\n // add id-rewrite steps\n if ($request->get('type') == 'recursive-update-references') {\n for ($i = 0; $i < (count($childIds) + 1); $i++) {\n $pasteJobs[] = [[\n 'url' => $this->generateUrl('pimcore_admin_dataobject_dataobject_copyrewriteids'),\n 'method' => 'PUT',\n 'params' => [\n 'transactionId' => $transactionId,\n '_dc' => uniqid(),\n ],\n ]];\n }\n }\n }\n } elseif ($request->get('type') == 'child' || $request->get('type') == 'replace') {\n // the object itself is the last one\n $pasteJobs[] = [[\n 'url' => $this->generateUrl('pimcore_admin_dataobject_dataobject_copy'),\n 'method' => 'POST',\n 'params' => [\n 'sourceId' => $request->get('sourceId'),\n 'targetId' => $request->get('targetId'),\n 'type' => $request->get('type'),\n 'transactionId' => $transactionId,\n ],\n ]];\n }\n\n return $this->adminJson([\n 'pastejobs' => $pasteJobs,\n ]);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public static function sys_get_temp_dir()\n\t{\n\t\t// sys_get_temp_dir is only available since PHP 5.2.1\n\t\t// http://php.net/manual/en/function.sys-get-temp-dir.php#94119\n\n\t\tif ( !function_exists('sys_get_temp_dir')) {\n\t\t\tif ($temp = getenv('TMP') ) {\n\t\t\t\tif (file_exists($temp)) { return realpath($temp); }\n\t\t\t}\n\t\t\tif ($temp = getenv('TEMP') ) {\n\t\t\t\tif (file_exists($temp)) { return realpath($temp); }\n\t\t\t}\n\t\t\tif ($temp = getenv('TMPDIR') ) {\n\t\t\t\tif (file_exists($temp)) { return realpath($temp); }\n\t\t\t}\n\n\t\t\t// trick for creating a file in system's temporary dir\n\t\t\t// without knowing the path of the system's temporary dir\n\t\t\t$temp = tempnam(__FILE__, '');\n\t\t\tif (file_exists($temp)) {\n\t\t\t\tunlink($temp);\n\t\t\t\treturn realpath(dirname($temp));\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\t// use ordinary built-in PHP function\n\t\t//\tThere should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only\n\t\t//\t\tbe called if we're running 5.2.1 or earlier\n\t\treturn realpath(sys_get_temp_dir());\n\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function processReset()\n {\n if (_PS_MODE_DEMO_) {\n $this->errors[] = $this->trans('This functionality has been disabled.', array(), 'Admin.Notifications.Error');\n } elseif (!($reset_token_value = trim(Tools::getValue('reset_token')))) {\n // hidden fields\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($id_employee = trim(Tools::getValue('id_employee')))) {\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_email = trim(Tools::getValue('reset_email')))) {\n $this->errors[] = $this->trans('Some identification information is missing.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_password = trim(Tools::getValue('reset_passwd')))) {\n // password (twice)\n $this->errors[] = $this->trans('The password is missing: please enter your new password.', array(), 'Admin.Login.Notification');\n } elseif (!Validate::isPasswd($reset_password)) {\n $this->errors[] = $this->trans('The password is not in a valid format.', array(), 'Admin.Login.Notification');\n } elseif (!($reset_confirm = trim(Tools::getValue('reset_confirm')))) {\n $this->errors[] = $this->trans('The confirmation is empty: please fill in the password confirmation as well.', array(), 'Admin.Login.Notification');\n } elseif ($reset_password !== $reset_confirm) {\n $this->errors[] = $this->trans('The password and its confirmation do not match. Please double check both passwords.', array(), 'Admin.Login.Notification');\n } else {\n $employee = new Employee();\n if (!$employee->getByEmail($reset_email) || !$employee || $employee->id != $id_employee) { // check matching employee id with its email\n $this->errors[] = $this->trans('This account does not exist.', array(), 'Admin.Login.Notification');\n } elseif ((strtotime($employee->last_passwd_gen . '+' . Configuration::get('PS_PASSWD_TIME_BACK') . ' minutes') - time()) > 0) {\n $this->errors[] = $this->trans('You can reset your password every %interval% minute(s) only. Please try again later.', array('%interval%' => Configuration::get('PS_PASSWD_TIME_BACK')), 'Admin.Login.Notification');\n } elseif ($employee->getValidResetPasswordToken() !== $reset_token_value) {\n // To update password, we must have the temporary reset token that matches.\n $this->errors[] = $this->trans('Your password reset request expired. Please start again.', array(), 'Admin.Login.Notification');\n }\n }\n\n if (!count($this->errors)) {\n $employee->passwd = $this->get('hashing')->hash($reset_password, _COOKIE_KEY_);\n $employee->last_passwd_gen = date('Y-m-d H:i:s', time());\n\n $params = array(\n '{email}' => $employee->email,\n '{lastname}' => $employee->lastname,\n '{firstname}' => $employee->firstname,\n );\n\n $employeeLanguage = new Language((int) $this->context->employee->id_lang);\n\n if (\n Mail::Send(\n $employee->id_lang,\n 'password',\n $this->trans(\n 'Your new password',\n array(),\n 'Emails.Subject',\n $employeeLanguage->locale\n ),\n $params,\n $employee->email,\n $employee->firstname . ' ' . $employee->lastname\n )\n ) {\n // Update employee only if the mail can be sent\n Shop::setContext(Shop::CONTEXT_SHOP, (int) min($employee->getAssociatedShops()));\n\n $result = $employee->update();\n if (!$result) {\n $this->errors[] = $this->trans('An error occurred while attempting to change your password.', array(), 'Admin.Login.Notification');\n } else {\n $employee->removeResetPasswordToken(); // Delete temporary reset token\n $employee->update();\n die(Tools::jsonEncode(array(\n 'hasErrors' => false,\n 'confirm' => $this->trans('The password has been changed successfully.', array(), 'Admin.Login.Notification'),\n )));\n }\n } else {\n die(Tools::jsonEncode(array(\n 'hasErrors' => true,\n 'errors' => array($this->trans('An error occurred while attempting to change your password.', array(), 'Admin.Login.Notification')),\n )));\n }\n } elseif (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function removeCSS($css_uri, $css_media_type = 'all', $check_path = true)\n {\n if (!is_array($css_uri)) {\n $css_uri = array($css_uri);\n }\n\n foreach ($css_uri as $css_file => $media) {\n if (is_string($css_file) && strlen($css_file) > 1) {\n if ($check_path) {\n $css_path = Media::getCSSPath($css_file, $media);\n } else {\n $css_path = array($css_file => $media);\n }\n } else {\n if ($check_path) {\n $css_path = Media::getCSSPath($media, $css_media_type);\n } else {\n $css_path = array($media => $css_media_type);\n }\n }\n\n if (\n $css_path\n && isset($this->css_files[key($css_path)])\n && ($this->css_files[key($css_path)] == reset($css_path))\n ) {\n unset($this->css_files[key($css_path)]);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function _add($x_value, $x_negative, $y_value, $y_negative)\n {\n $x_size = count($x_value);\n $y_size = count($y_value);\n\n if ($x_size == 0) {\n return array(\n self::VALUE => $y_value,\n self::SIGN => $y_negative\n );\n } elseif ($y_size == 0) {\n return array(\n self::VALUE => $x_value,\n self::SIGN => $x_negative\n );\n }\n\n // subtract, if appropriate\n if ($x_negative != $y_negative) {\n if ($x_value == $y_value) {\n return array(\n self::VALUE => array(),\n self::SIGN => false\n );\n }\n\n $temp = $this->_subtract($x_value, false, $y_value, false);\n $temp[self::SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?\n $x_negative : $y_negative;\n\n return $temp;\n }\n\n if ($x_size < $y_size) {\n $size = $x_size;\n $value = $y_value;\n } else {\n $size = $y_size;\n $value = $x_value;\n }\n\n $value[count($value)] = 0; // just in case the carry adds an extra digit\n\n $carry = 0;\n for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {\n $sum = $x_value[$j] * self::$baseFull + $x_value[$i] + $y_value[$j] * self::$baseFull + $y_value[$i] + $carry;\n $carry = $sum >= self::$maxDigit2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1\n $sum = $carry ? $sum - self::$maxDigit2 : $sum;\n\n $temp = self::$base === 26 ? intval($sum / 0x4000000) : ($sum >> 31);\n\n $value[$i] = (int) ($sum - self::$baseFull * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)\n $value[$j] = $temp;\n }\n\n if ($j == $size) { // ie. if $y_size is odd\n $sum = $x_value[$i] + $y_value[$i] + $carry;\n $carry = $sum >= self::$baseFull;\n $value[$i] = $carry ? $sum - self::$baseFull : $sum;\n ++$i; // ie. let $i = $j since we've just done $value[$i]\n }\n\n if ($carry) {\n for (; $value[$i] == self::$maxDigit; ++$i) {\n $value[$i] = 0;\n }\n ++$value[$i];\n }\n\n return array(\n self::VALUE => $this->_trim($value),\n self::SIGN => $x_negative\n );\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "protected function write($str)\n {\n if (! empty($this->strippedSemicolon)) {\n echo $this->strippedSemicolon;\n\n $this->strippedSemicolon = '';\n }\n\n /*\n * Maybe Strip semi-colon appended by property(); it's a separator, not a terminator\n * will be striped for real before a closing, otherwise displayed unchanged starting the next write\n */\n if (\n ! $this->keepSemicolons &&\n $str &&\n (strpos($str, ';') !== false) &&\n (substr($str, -1) === ';')\n ) {\n $str = substr($str, 0, -1);\n\n $this->strippedSemicolon = ';';\n }\n\n if ($this->sourceMapGenerator) {\n $lines = explode(\"\\n\", $str);\n $lastLine = array_pop($lines);\n\n foreach ($lines as $line) {\n // If the written line starts is empty, adding a mapping would add it for\n // a non-existent column as we are at the end of the line\n if ($line !== '') {\n assert($this->currentBlock->sourceLine !== null);\n assert($this->currentBlock->sourceName !== null);\n $this->sourceMapGenerator->addMapping(\n $this->currentLine,\n $this->currentColumn,\n $this->currentBlock->sourceLine,\n //columns from parser are off by one\n $this->currentBlock->sourceColumn > 0 ? $this->currentBlock->sourceColumn - 1 : 0,\n $this->currentBlock->sourceName\n );\n }\n\n $this->currentLine++;\n $this->currentColumn = 0;\n }\n\n if ($lastLine !== '') {\n assert($this->currentBlock->sourceLine !== null);\n assert($this->currentBlock->sourceName !== null);\n $this->sourceMapGenerator->addMapping(\n $this->currentLine,\n $this->currentColumn,\n $this->currentBlock->sourceLine,\n //columns from parser are off by one\n $this->currentBlock->sourceColumn > 0 ? $this->currentBlock->sourceColumn - 1 : 0,\n $this->currentBlock->sourceName\n );\n }\n\n $this->currentColumn += \\strlen($lastLine);\n }\n\n echo $str;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function printMappingReport_dt($arr, $rt_id, $dt_id, $extra_info){\n global $rectypes, $is_verbose, $mapping_errors, $transfer_errors, $successful_rows, $warning_count;\n\n if($is_verbose){\n\n if(is_object($arr)){\n $label = $arr['value'];\n $code = $arr[H_ID];\n }elseif(is_array($arr)){\n $label = $arr[3][0];\n $code = $arr[2];\n }else{\n $label = '';\n $code = $arr;\n\n if(is_array($arr)){ error_log(print_r($arr, TRUE));}\n }\n\n if($extra_info == null){\n if(is_array($arr)){\n $extra_info = $arr;\n }\n }\n\n if(is_array($extra_info)){\n\n if(is_empty($extra_info[0])){\n $extra_info[0] = $rt_id;\n }\n if($label == ''){\n $dt_str = $extra_info[3][0].\"(\".$code.\")\";\n }else{\n $dt_str = $label.\"(\".$code.\")\";\n }\n }\n\n if($dt_id==null){\n\n if($extra_info != null){\n\n if(array_key_exists($extra_info[1], $mapping_errors)){ // NOT FOUND\n\n if(strpos($mapping_errors[$extra_info[1]], $dt_str) === false){ // Check if field is already listed\n $mapping_errors[$extra_info[1]] = str_replace(TR_E, \"\", $mapping_errors[$extra_info[1]]).\", \".$dt_str.TR_E;\n $warning_count ++;\n }\n }else{\n $mapping_errors[$extra_info[1]] = \"<tr class='tbl-row'><td colspan='3'><strong>\".$extra_info[1].\" (\".$extra_info[0].\"):</strong></td><td colspan='4'>unmapped fields: \".$dt_str.TR_E;\n $warning_count ++;\n }\n }\n }else{\n if(@$rectypes['typedefs'][$rt_id]['dtFields'][$dt_id]){\n $successful_rows[] = \"<tr class='tbl-row'><td></td><td>\".$label.TD.$code.\"</td><td>&rArr;\".$rectypes['typedefs'][$rt_id]['dtFields'][$dt_id][0].TD.$dt_id.TR_E;\n }else{ // NOT IN RECORD TYPE STRUCTURE\n\n if($extra_info != null){\n\n if(array_key_exists($extra_info[1], $transfer_errors)){\n\n if(strpos($transfer_errors[$extra_info[1]], $dt_str) === false){\n $transfer_errors[$extra_info[1]] = str_replace(TR_E, \"\", $transfer_errors[$extra_info[1]]).\", \".$dt_str.TR_E;\n $warning_count ++;\n }\n }else{\n $transfer_errors[$extra_info[1]] = \"<tr class='tbl-row'><td colspan='3'><strong>\".$extra_info[1].\" (\".$extra_info[0].\"):</strong></td><td colspan='4'>\".$dt_str.TR_E;\n $warning_count ++;\n }\n }\n }\n }\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private function parseSums(array $groups): array\n {\n /**\n * @var int $groudId\n * @var array $group\n */\n foreach ($groups as $groudId => $group) {\n /** @var array $transaction */\n foreach ($group['transactions'] as $transaction) {\n $currencyId = (int)$transaction['currency_id'];\n if (null === $transaction['amount']) {\n throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId));\n }\n\n // set default:\n if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {\n $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;\n $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code'];\n $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol'];\n $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places'];\n $groups[$groudId]['sums'][$currencyId]['amount'] = '0';\n }\n $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']);\n\n if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {\n $currencyId = (int)$transaction['foreign_currency_id'];\n\n // set default:\n if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {\n $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;\n $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code'];\n $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol'];\n $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places'];\n $groups[$groudId]['sums'][$currencyId]['amount'] = '0';\n }\n $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['foreign_amount']);\n }\n }\n }\n\n return $groups;\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "protected function calcVulnerableElementVulns(VulnerableElement $elem, $parentVulns = null, $onlyChildren = false,\n $inherits = false)\n {\n $vulns = [];\n /** @var \\VulnModule\\Vulnerability[] $computedVulns */\n $computedVulns = $elem->getComputedVulnerabilities(VulnerableElement::COMPUTE_ONLY_ROOT);\n\n if (!$onlyChildren) {\n // Show disabled for any context except default and for conditional elements\n $showDisabledVulns = (boolean)(!$elem->getHost() || $elem->getHost()->getParent());\n $customVulns = [];\n $vulnList = !!$parentVulns ? $elem->getVulnerabilitySet()->getVulnerabilities() : $computedVulns;\n\n foreach ($vulnList as $vuln) {\n if (!$vuln) {\n continue;\n }\n $hasOwnVuln = $elem->hasOwnVulnerability($vuln->getName());\n\n if ($vuln->isEnabled() || ($showDisabledVulns && $hasOwnVuln)) {\n if (!$parentVulns || !$parentVulns[$vuln->getName()]->equalsTo($vuln)) {\n $customVulns[$vuln->getName()]['props'] = $vuln->asArray();\n $customVulns[$vuln->getName()]['inherited'] = $inherits || !$hasOwnVuln;\n $customVulns[$vuln->getName()]['vuln'] = $vuln;\n }\n }\n }\n\n if (count($customVulns)) {\n $vulns['vulns'] = $customVulns;\n }\n }\n\n if ($elem->hasChildren()) {\n $childVulns = [];\n foreach ($elem->getChildren() as $child) {\n if ($childVuln = $this->calcVulnerableElementVulns($child, $computedVulns, false, $inherits)) {\n $childVulns[] = $childVuln;\n }\n }\n if (count($childVulns)) {\n $vulns['children'] = $childVulns;\n }\n }\n\n if ($elem instanceof ConditionalVulnerableElement) {\n $conditions = [];\n if ($elem->hasConditions()) {\n foreach ($elem->getConditions()->getConditions() as $condition) {\n $conditions[$condition->getName()] = $condition->__toString();\n }\n }\n\n if (count($conditions)) {\n $vulns['conditions'] = $conditions;\n }\n }\n\n if (count($vulns)) {\n if ($inherits) {\n $vulns['inherited_block'] = true;\n }\n }\n\n return $vulns;\n }", "smellKey": "S3776", "smellId": null, "repo": "Mathewargy_hackazon", "language": "php"} {"function": "public function parsePrimaryExpression()\n {\n $token = $this->parser->getCurrentToken();\n switch ($token->getType()) {\n case /* Token::NAME_TYPE */ 5:\n $this->parser->getStream()->next();\n switch ($token->getValue()) {\n case 'true':\n case 'TRUE':\n $node = new ConstantExpression(true, $token->getLine());\n break;\n\n case 'false':\n case 'FALSE':\n $node = new ConstantExpression(false, $token->getLine());\n break;\n\n case 'none':\n case 'NONE':\n case 'null':\n case 'NULL':\n $node = new ConstantExpression(null, $token->getLine());\n break;\n\n default:\n if ('(' === $this->parser->getCurrentToken()->getValue()) {\n $node = $this->getFunctionNode($token->getValue(), $token->getLine());\n } else {\n $node = new NameExpression($token->getValue(), $token->getLine());\n }\n }\n break;\n\n case /* Token::NUMBER_TYPE */ 6:\n $this->parser->getStream()->next();\n $node = new ConstantExpression($token->getValue(), $token->getLine());\n break;\n\n case /* Token::STRING_TYPE */ 7:\n case /* Token::INTERPOLATION_START_TYPE */ 10:\n $node = $this->parseStringExpression();\n break;\n\n case /* Token::OPERATOR_TYPE */ 8:\n if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) {\n // in this context, string operators are variable names\n $this->parser->getStream()->next();\n $node = new NameExpression($token->getValue(), $token->getLine());\n break;\n } elseif (isset($this->unaryOperators[$token->getValue()])) {\n $class = $this->unaryOperators[$token->getValue()]['class'];\n\n $ref = new \\ReflectionClass($class);\n if (!(\\in_array($ref->getName(), [NegUnary::class, PosUnary::class, 'Twig_Node_Expression_Unary_Neg', 'Twig_Node_Expression_Unary_Pos'])\n || $ref->isSubclassOf(NegUnary::class) || $ref->isSubclassOf(PosUnary::class)\n || $ref->isSubclassOf('Twig_Node_Expression_Unary_Neg') || $ref->isSubclassOf('Twig_Node_Expression_Unary_Pos'))\n ) {\n throw new SyntaxError(sprintf('Unexpected unary operator \"%s\".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());\n }\n\n $this->parser->getStream()->next();\n $expr = $this->parsePrimaryExpression();\n\n $node = new $class($expr, $token->getLine());\n break;\n }\n\n // no break\n default:\n if ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '[')) {\n $node = $this->parseArrayExpression();\n } elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '{')) {\n $node = $this->parseHashExpression();\n } elseif ($token->test(/* Token::OPERATOR_TYPE */ 8, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) {\n throw new SyntaxError(sprintf('Unexpected operator of value \"%s\". Did you try to use \"===\" or \"!==\" for strict comparison? Use \"is same as(value)\" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());\n } else {\n throw new SyntaxError(sprintf('Unexpected token \"%s\" of value \"%s\".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());\n }\n }\n\n return $this->parsePostfixExpression($node);\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "protected function canonicalRedirection($canonical_url = '')\n {\n if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET') {\n return;\n }\n\n $canonical_url = preg_replace('/#.*$/', '', $canonical_url);\n\n $match_url = rawurldecode(Tools::getCurrentUrlProtocolPrefix().$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n if (!preg_match('/^'.Tools::pRegexp(rawurldecode($canonical_url), '/').'([&?].*)?$/', $match_url)) {\n $params = array();\n $url_details = parse_url($canonical_url);\n\n if (!empty($url_details['query'])) {\n parse_str($url_details['query'], $query);\n foreach ($query as $key => $value) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n $excluded_key = array('isolang', 'id_lang', 'controller', 'fc', 'id_product', 'id_category', 'id_manufacturer', 'id_supplier', 'id_cms');\n $excluded_key = array_merge($excluded_key, $this->redirectionExtraExcludedKeys);\n foreach ($_GET as $key => $value) {\n if (!in_array($key, $excluded_key) && Validate::isUrl($key) && Validate::isUrl($value)) {\n $params[Tools::safeOutput($key)] = Tools::safeOutput($value);\n }\n }\n\n $str_params = http_build_query($params, '', '&');\n if (!empty($str_params)) {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url).'?'.$str_params;\n } else {\n $final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url);\n }\n\n // Don't send any cookie\n Context::getContext()->cookie->disallowWriting();\n if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $_SERVER['REQUEST_URI'] != __PS_BASE_URI__) {\n die('[Debug] This page has moved<br />Please use the following URL instead: <a href=\"'.$final_url.'\">'.$final_url.'</a>');\n }\n\n $redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';\n header('HTTP/1.0 '.$redirect_type.' Moved');\n header('Cache-Control: no-cache');\n Tools::redirectLink($final_url);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->administrableDoseForm)) {\n $json['administrableDoseForm'] = $this->administrableDoseForm;\n }\n if (isset($this->unitOfPresentation)) {\n $json['unitOfPresentation'] = $this->unitOfPresentation;\n }\n if (0 < count($this->ingredient)) {\n $json['ingredient'] = [];\n foreach ($this->ingredient as $ingredient) {\n $json['ingredient'][] = $ingredient;\n }\n }\n if (0 < count($this->device)) {\n $json['device'] = [];\n foreach ($this->device as $device) {\n $json['device'][] = $device;\n }\n }\n if (0 < count($this->characteristics)) {\n $json['characteristics'] = [];\n foreach ($this->characteristics as $characteristics) {\n $json['characteristics'][] = $characteristics;\n }\n }\n if (0 < count($this->routeOfAdministration)) {\n $json['routeOfAdministration'] = [];\n foreach ($this->routeOfAdministration as $routeOfAdministration) {\n $json['routeOfAdministration'][] = $routeOfAdministration;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function end_row()\n{\n global $cell_count, $CPR, $historical_ids, $USING_BOOTSTRAP;\n end_cell();\n if ($USING_BOOTSTRAP) {\n if ($cell_count > 0 && $cell_count < $CPR) {\n // Create a cell occupying the remaining bootstrap columns.\n // BS columns will be less than 12 if $CPR is not 2, 3, 4, 6 or 12.\n $bs_cols_remaining = ($CPR - $cell_count) * intval(12 / $CPR);\n echo \"<div class='$BS_COL_CLASS-$bs_cols_remaining'></div>\";\n }\n if ($cell_count > 0) {\n echo \"</div><!-- End BS row -->\\n\";\n }\n } else {\n if ($cell_count > 0) {\n for (; $cell_count < $CPR; ++$cell_count) {\n echo \"<td class='border-top-0'></td>\";\n foreach ($historical_ids as $key => $dummy) {\n $historical_ids[$key] .= \"<td class='border-top-0'></td>\";\n }\n }\n foreach ($historical_ids as $key => $dummy) {\n echo $historical_ids[$key];\n }\n echo \"</tr>\\n\";\n }\n }\n $cell_count = 0;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function alert_details($details)\n{\n if (is_string($details)) {\n $details = json_decode(gzuncompress($details), true);\n } elseif (! is_array($details)) {\n $details = [];\n }\n\n $max_row_length = 0;\n $all_fault_detail = '';\n foreach ($details['rule'] ?? [] as $o => $tmp_alerts) {\n $fault_detail = '';\n $fallback = true;\n $fault_detail .= '#' . ($o + 1) . ':&nbsp;';\n if (isset($tmp_alerts['bill_id'])) {\n $fault_detail .= '<a href=\"' . \\LibreNMS\\Util\\Url::generate(['page' => 'bill', 'bill_id' => $tmp_alerts['bill_id']], []) . '\">' . $tmp_alerts['bill_name'] . '</a>;&nbsp;';\n $fallback = false;\n }\n\n if (isset($tmp_alerts['port_id'])) {\n if ($tmp_alerts['isisISAdjState']) {\n $fault_detail .= 'Adjacent ' . $tmp_alerts['isisISAdjIPAddrAddress'];\n $port = \\App\\Models\\Port::find($tmp_alerts['port_id']);\n $fault_detail .= ', Interface ' . \\LibreNMS\\Util\\Url::portLink($port);\n } else {\n $tmp_alerts = cleanPort($tmp_alerts);\n $fault_detail .= generate_port_link($tmp_alerts) . ';&nbsp;';\n }\n $fallback = false;\n }\n\n if (isset($tmp_alerts['accesspoint_id'])) {\n $fault_detail .= generate_ap_link($tmp_alerts, $tmp_alerts['name']) . ';&nbsp;';\n $fallback = false;\n }\n\n if (isset($tmp_alerts['sensor_id'])) {\n if ($tmp_alerts['sensor_class'] == 'state') {\n // Give more details for a state (textual form)\n $details = 'State: ' . $tmp_alerts['state_descr'] . ' (numerical ' . $tmp_alerts['sensor_current'] . ')<br> ';\n } else {\n // Other sensors\n $details = 'Value: ' . $tmp_alerts['sensor_current'] . ' (' . $tmp_alerts['sensor_class'] . ')<br> ';\n }\n $details_a = [];\n\n if ($tmp_alerts['sensor_limit_low']) {\n $details_a[] = 'low: ' . $tmp_alerts['sensor_limit_low'];\n }\n if ($tmp_alerts['sensor_limit_low_warn']) {\n $details_a[] = 'low_warn: ' . $tmp_alerts['sensor_limit_low_warn'];\n }\n if ($tmp_alerts['sensor_limit_warn']) {\n $details_a[] = 'high_warn: ' . $tmp_alerts['sensor_limit_warn'];\n }\n if ($tmp_alerts['sensor_limit']) {\n $details_a[] = 'high: ' . $tmp_alerts['sensor_limit'];\n }\n $details .= implode(', ', $details_a);\n\n $fault_detail .= generate_sensor_link($tmp_alerts, $tmp_alerts['name']) . ';&nbsp; <br>' . $details;\n $fallback = false;\n }\n\n if (isset($tmp_alerts['service_id'])) {\n $fault_detail .= \"Service: <a href='\" .\n \\LibreNMS\\Util\\Url::generate([\n 'page' => 'device',\n 'device' => $tmp_alerts['device_id'],\n 'tab' => 'services',\n 'view' => 'detail',\n ]) .\n \"'>\" . ($tmp_alerts['service_name'] ?? '') . ' (' . $tmp_alerts['service_type'] . ')' . '</a>';\n $fault_detail .= 'Service Host: ' . ($tmp_alerts['service_ip'] != '' ? $tmp_alerts['service_ip'] : format_hostname(DeviceCache::get($tmp_alerts['device_id']))) . ',<br>';\n $fault_detail .= ($tmp_alerts['service_desc'] != '') ? ('Description: ' . $tmp_alerts['service_desc'] . ',<br>') : '';\n $fault_detail .= ($tmp_alerts['service_param'] != '') ? ('Param: ' . $tmp_alerts['service_param'] . ',<br>') : '';\n $fault_detail .= 'Msg: ' . $tmp_alerts['service_message'];\n $fallback = false;\n }\n\n if (isset($tmp_alerts['bgpPeer_id'])) {\n // If we have a bgpPeer_id, we format the data accordingly\n $fault_detail .= \"BGP peer <a href='\" .\n \\LibreNMS\\Util\\Url::generate([\n 'page' => 'device',\n 'device' => $tmp_alerts['device_id'],\n 'tab' => 'routing',\n 'proto' => 'bgp',\n ]) .\n \"'>\" . $tmp_alerts['bgpPeerIdentifier'] . '</a>';\n $fault_detail .= ', Desc ' . $tmp_alerts['bgpPeerDescr'] ?? '';\n $fault_detail .= ', AS' . $tmp_alerts['bgpPeerRemoteAs'];\n $fault_detail .= ', State ' . $tmp_alerts['bgpPeerState'];\n $fallback = false;\n }\n\n if (isset($tmp_alerts['mempool_id'])) {\n // If we have a mempool_id, we format the data accordingly\n $fault_detail .= \"MemoryPool <a href='\" .\n \\LibreNMS\\Util\\Url::generate([\n 'page' => 'graphs',\n 'id' => $tmp_alerts['mempool_id'],\n 'type' => 'mempool_usage',\n ]) .\n \"'>\" . ($tmp_alerts['mempool_descr'] ?? 'link') . '</a>';\n $fault_detail .= '<br> &nbsp; &nbsp; &nbsp; Usage ' . $tmp_alerts['mempool_perc'] . '%, &nbsp; Free ' . \\LibreNMS\\Util\\Number::formatSi($tmp_alerts['mempool_free']) . ',&nbsp; Size ' . \\LibreNMS\\Util\\Number::formatSi($tmp_alerts['mempool_total']);\n $fallback = false;\n }\n\n if ($tmp_alerts['type'] && isset($tmp_alerts['label'])) {\n if ($tmp_alerts['error'] == '') {\n $fault_detail .= ' ' . $tmp_alerts['type'] . ' - ' . $tmp_alerts['label'] . ';&nbsp;';\n } else {\n $fault_detail .= ' ' . $tmp_alerts['type'] . ' - ' . $tmp_alerts['label'] . ' - ' . $tmp_alerts['error'] . ';&nbsp;';\n }\n $fallback = false;\n }\n\n if (in_array('app_id', array_keys($tmp_alerts))) {\n $fault_detail .= \"<a href='\" .\n \\LibreNMS\\Util\\Url::generate([\n 'page' => 'device',\n 'device' => $tmp_alerts['device_id'],\n 'tab' => 'apps',\n 'app' => $tmp_alerts['app_type'],\n ]) . \"'>\";\n $fault_detail .= $tmp_alerts['app_type'];\n $fault_detail .= '</a>';\n\n if ($tmp_alerts['app_status']) {\n $fault_detail .= ' => ' . $tmp_alerts['app_status'];\n }\n if ($tmp_alerts['metric']) {\n $fault_detail .= ' : ' . $tmp_alerts['metric'] . ' => ' . $tmp_alerts['value'];\n }\n $fallback = false;\n }\n\n if ($fallback === true) {\n $fault_detail_data = [];\n foreach ($tmp_alerts as $k => $v) {\n if (in_array($k, ['device_id', 'sysObjectID', 'sysDescr', 'location_id'])) {\n continue;\n }\n if (! empty($v) && str_i_contains($k, ['id', 'desc', 'msg', 'last'])) {\n $fault_detail_data[] = \"$k => '$v'\";\n }\n }\n $fault_detail .= count($fault_detail_data) ? implode('<br>&nbsp;&nbsp;&nbsp', $fault_detail_data) : '';\n\n $fault_detail = rtrim($fault_detail, ', ');\n }\n\n $fault_detail .= '<br>';\n\n $max_row_length = strlen(strip_tags($fault_detail)) > $max_row_length ? strlen(strip_tags($fault_detail)) : $max_row_length;\n\n $all_fault_detail .= $fault_detail;\n }//end foreach\n\n return [$all_fault_detail, $max_row_length];\n}", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "function matrixCompare($m,$n,$tol='.001') {\n\t// $m stu, $n correct\n\tif (!is_array($m) || !is_array($n) || !is_array($m[0]) || !is_array($n[0])) {\n\t\treturn false;\n\t}\n\tif (count($m) != count($n) || count($m[0]) != count($n[0])) {\n\t\treturn false;\n\t}\n\t$toltype = 'rel';\n\tif (strval($tol)[0]=='|') {\n\t\t$toltype = 'abs';\n\t\t$tol = substr($tol,1);\n\t}\n\t$isequiv = true;\n\tfor ($r = 0 ; $r < count($m); $r++) {\n\t\tfor ($c = 0; $c < count($m[0]); $c++) {\n\t\t\tif ($toltype == 'rel') {\n\t\t\t\tif (abs($n[$r][$c]) < 1E-12) {\n\t\t\t\t\tif (abs($m[$r][$c] - $n[$r][$c]) > $tol/1000 + 1E-12) {\n\t\t\t\t\t\t$isequiv = false;\n\t\t\t\t\t\tbreak 2;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (abs($m[$r][$c] - $n[$r][$c])/(abs($n[$r][$c])+1E-12) > $tol + 1E-12) {\n\t\t\t\t\t\t$isequiv = false;\n\t\t\t\t\t\tbreak 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (abs($m[$r][$c] - $n[$r][$c]) > $tol + 1E-12) {\n\t\t\t\t\t$isequiv = false;\n\t\t\t\t\tbreak 2;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn $isequiv;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function getDropdownName($table, $id, $withcomment = false, $translate = true, $tooltip = true, string $default = '')\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $itemtype = getItemTypeForTable($table);\n\n if (!is_a($itemtype, CommonDBTM::class, true)) {\n return $default;\n }\n\n if (is_a($itemtype, CommonTreeDropdown::class, true)) {\n return getTreeValueCompleteName($table, $id, $withcomment, $translate, $tooltip, $default);\n }\n\n $name = \"\";\n $comment = \"\";\n\n if ($id) {\n $SELECTNAME = new QueryExpression(\"'' AS \" . $DB->quoteName('transname'));\n $SELECTCOMMENT = new QueryExpression(\"'' AS \" . $DB->quoteName('transcomment'));\n $JOIN = [];\n $JOINS = [];\n if ($translate) {\n if (Session::haveTranslations(getItemTypeForTable($table), 'name')) {\n $SELECTNAME = 'namet.value AS transname';\n $JOINS['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => getItemTypeForTable($table),\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations(getItemTypeForTable($table), 'comment')) {\n $SELECTCOMMENT = 'namec.value AS transcomment';\n $JOINS['glpi_dropdowntranslations AS namec'] = [\n 'ON' => [\n 'namec' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namec.itemtype' => getItemTypeForTable($table),\n 'namec.language' => $_SESSION['glpilanguage'],\n 'namec.field' => 'comment'\n ]\n ]\n ]\n ];\n }\n\n if (count($JOINS)) {\n $JOIN = ['LEFT JOIN' => $JOINS];\n }\n }\n\n $criteria = [\n 'SELECT' => [\n \"$table.*\",\n $SELECTNAME,\n $SELECTCOMMENT\n ],\n 'FROM' => $table,\n 'WHERE' => [\"$table.id\" => $id]\n ] + $JOIN;\n $iterator = $DB->request($criteria);\n\n /// TODO review comment management...\n /// TODO getDropdownName need to return only name\n /// When needed to use comment use class instead : getComments function\n /// GetName of class already give Name !!\n /// TODO CommonDBTM : review getComments to be recursive and add information from class hierarchy\n /// getUserName have the same system : clean it too\n /// Need to study the problem\n if (count($iterator)) {\n $data = $iterator->current();\n if ($translate && !empty($data['transname'])) {\n $name = $data['transname'];\n } else {\n $name = $data[$itemtype::getNameField()];\n }\n if (isset($data[\"comment\"])) {\n if ($translate && !empty($data['transcomment'])) {\n $comment = $data['transcomment'];\n } else {\n $comment = $data[\"comment\"];\n }\n }\n\n switch ($table) {\n case \"glpi_computers\":\n if (empty($name)) {\n $name = \"($id)\";\n }\n break;\n\n case \"glpi_contacts\":\n //TRANS: %1$s is the name, %2$s is the firstname\n $name = sprintf(__('%1$s %2$s'), $name, $data[\"firstname\"]);\n if ($tooltip) {\n if (!empty($data[\"phone\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . htmlspecialchars(Phone::getTypeName(1)),\n \"</span>\" . htmlspecialchars($data['phone'])\n );\n }\n if (!empty($data[\"phone2\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('Phone 2'),\n \"</span>\" . htmlspecialchars($data['phone2'])\n );\n }\n if (!empty($data[\"mobile\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('Mobile phone'),\n \"</span>\" . htmlspecialchars($data['mobile'])\n );\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('Fax'),\n \"</span>\" . htmlspecialchars($data['fax'])\n );\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . _n('Email', 'Emails', 1),\n \"</span>\" . htmlspecialchars($data['email'])\n );\n }\n }\n break;\n\n case \"glpi_suppliers\":\n if ($tooltip) {\n if (!empty($data[\"phonenumber\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . htmlspecialchars(Phone::getTypeName(1)),\n \"</span>\" . htmlspecialchars($data['phonenumber'])\n );\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('Fax'),\n \"</span>\" . htmlspecialchars($data['fax'])\n );\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . _sn('Email', 'Emails', 1),\n \"</span>\" . htmlspecialchars($data['email'])\n );\n }\n }\n break;\n\n case \"glpi_sockets\":\n $name = sprintf(\n __('%1$s (%2$s)'),\n $name,\n self::getDropdownName(\n \"glpi_locations\",\n $data[\"locations_id\"],\n false,\n $translate\n )\n );\n break;\n\n case \"glpi_budgets\":\n if ($tooltip) {\n if (!empty($data['locations_id'])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . htmlspecialchars(Location::getTypeName(1)) . \"</span>\",\n self::getDropdownName(\n \"glpi_locations\",\n $data[\"locations_id\"],\n false,\n $translate\n )\n );\n }\n if (!empty($data['budgettypes_id'])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . _sn('Type', 'Types', 1) . \"</span>\",\n self::getDropdownName(\n \"glpi_budgettypes\",\n $data[\"budgettypes_id\"],\n false,\n $translate\n )\n );\n }\n if (!empty($data['begin_date'])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('Start date') . \"</span>\",\n Html::convDateTime($data[\"begin_date\"])\n );\n }\n if (!empty($data['end_date'])) {\n $comment .= \"<br>\" . sprintf(\n __('%1$s: %2$s'),\n \"<span class='b'>\" . __s('End date') . \"</span>\",\n Html::convDateTime($data[\"end_date\"])\n );\n }\n }\n }\n }\n }\n\n if (empty($name)) {\n $name = $default;\n }\n\n if ($withcomment) {\n return [\n 'name' => $name,\n 'comment' => $comment\n ];\n }\n\n return $name;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "final public static function generateTrustedXml()\n {\n $modules_on_disk = Module::getModulesDirOnDisk();\n $trusted = [];\n $untrusted = [];\n\n $trusted_modules_xml = [\n _PS_ROOT_DIR_ . static::CACHE_FILE_ALL_COUNTRY_MODULES_LIST,\n _PS_ROOT_DIR_ . static::CACHE_FILE_MUST_HAVE_MODULES_LIST,\n _PS_ROOT_DIR_ . static::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST,\n ];\n\n if (file_exists(_PS_ROOT_DIR_ . static::CACHE_FILE_CUSTOMER_MODULES_LIST)) {\n $trusted_modules_xml[] = _PS_ROOT_DIR_ . static::CACHE_FILE_CUSTOMER_MODULES_LIST;\n }\n\n // Create 2 arrays with trusted and untrusted modules\n foreach ($trusted_modules_xml as $file) {\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $trusted[] = Tools::strtolower((string) $modaddons->name);\n }\n }\n }\n\n foreach (glob(_PS_ROOT_DIR_ . '/config/xml/themes/*.xml') as $theme_xml) {\n if (file_exists($theme_xml)) {\n $content = Tools::file_get_contents($theme_xml);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml) {\n foreach ($xml->modules->module as $modaddons) {\n if ((string) $modaddons['action'] == 'install') {\n $trusted[] = Tools::strtolower((string) $modaddons['name']);\n }\n }\n }\n }\n }\n\n foreach ($modules_on_disk as $name) {\n if (!in_array($name, $trusted)) {\n if (Module::checkModuleFromAddonsApi($name)) {\n $trusted[] = Tools::strtolower($name);\n } else {\n $untrusted[] = Tools::strtolower($name);\n }\n }\n }\n\n $context = Context::getContext();\n\n // Save the 2 arrays into XML files\n $trusted_xml = new SimpleXMLElement('<modules_list/>');\n $trusted_xml->addAttribute('theme', $context->shop->theme->getName());\n $modules = $trusted_xml->addChild('modules');\n $modules->addAttribute('type', 'trusted');\n foreach ($trusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success = file_put_contents(_PS_ROOT_DIR_ . static::CACHE_FILE_TRUSTED_MODULES_LIST, $trusted_xml->asXML());\n\n $untrusted_xml = new SimpleXMLElement('<modules_list/>');\n $modules = $untrusted_xml->addChild('modules');\n $modules->addAttribute('type', 'untrusted');\n foreach ($untrusted as $key => $name) {\n $module = $modules->addChild('module');\n $module->addAttribute('name', $name);\n }\n $success &= file_put_contents(_PS_ROOT_DIR_ . static::CACHE_FILE_UNTRUSTED_MODULES_LIST, $untrusted_xml->asXML());\n\n if ($success) {\n return true;\n } else {\n Context::getContext()->getTranslator()->trans('Trusted and Untrusted XML have not been generated properly', [], 'Admin.Modules.Notification');\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['eventCoding'])) {\n $this->setEventCoding($data['eventCoding']);\n }\n if (isset($data['eventUri'])) {\n $this->setEventUri($data['eventUri']);\n }\n if (isset($data['destination'])) {\n if (is_array($data['destination'])) {\n foreach ($data['destination'] as $d) {\n $this->addDestination($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"destination\" must be array of objects or null, ' . gettype($data['destination']) . ' seen.');\n }\n }\n if (isset($data['sender'])) {\n $this->setSender($data['sender']);\n }\n if (isset($data['enterer'])) {\n $this->setEnterer($data['enterer']);\n }\n if (isset($data['author'])) {\n $this->setAuthor($data['author']);\n }\n if (isset($data['source'])) {\n $this->setSource($data['source']);\n }\n if (isset($data['responsible'])) {\n $this->setResponsible($data['responsible']);\n }\n if (isset($data['reason'])) {\n $this->setReason($data['reason']);\n }\n if (isset($data['response'])) {\n $this->setResponse($data['response']);\n }\n if (isset($data['focus'])) {\n if (is_array($data['focus'])) {\n foreach ($data['focus'] as $d) {\n $this->addFocus($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"focus\" must be array of objects or null, ' . gettype($data['focus']) . ' seen.');\n }\n }\n if (isset($data['definition'])) {\n $this->setDefinition($data['definition']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function getPaymentModules()\n {\n $context = Context::getContext();\n if (isset($context->cart)) {\n $billing = new Address((int) $context->cart->id_address_invoice);\n }\n\n $use_groups = Group::isFeatureActive();\n\n $frontend = true;\n $groups = array();\n if (isset($context->employee)) {\n $frontend = false;\n } elseif (isset($context->customer) && $use_groups) {\n $groups = $context->customer->getGroups();\n if (!count($groups)) {\n $groups = array(Configuration::get('PS_UNIDENTIFIED_GROUP'));\n }\n }\n\n $hook_payment = 'Payment';\n if (Db::getInstance()->getValue('SELECT `id_hook` FROM `' . _DB_PREFIX_ . 'hook` WHERE `name` = \\'paymentOptions\\'')) {\n $hook_payment = 'paymentOptions';\n }\n\n $list = Shop::getContextListShopID();\n\n return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT DISTINCT m.`id_module`, h.`id_hook`, m.`name`, hm.`position`\n FROM `' . _DB_PREFIX_ . 'module` m\n ' . ($frontend ? 'LEFT JOIN `' . _DB_PREFIX_ . 'module_country` mc ON (m.`id_module` = mc.`id_module` AND mc.id_shop = ' . (int) $context->shop->id . ')' : '') . '\n ' . ($frontend && $use_groups ? 'INNER JOIN `' . _DB_PREFIX_ . 'module_group` mg ON (m.`id_module` = mg.`id_module` AND mg.id_shop = ' . (int) $context->shop->id . ')' : '') . '\n ' . ($frontend && isset($context->customer) && $use_groups ? 'INNER JOIN `' . _DB_PREFIX_ . 'customer_group` cg on (cg.`id_group` = mg.`id_group`AND cg.`id_customer` = ' . (int) $context->customer->id . ')' : '') . '\n LEFT JOIN `' . _DB_PREFIX_ . 'hook_module` hm ON hm.`id_module` = m.`id_module`\n LEFT JOIN `' . _DB_PREFIX_ . 'hook` h ON hm.`id_hook` = h.`id_hook`\n WHERE h.`name` = \\'' . pSQL($hook_payment) . '\\'\n ' . (isset($billing) && $frontend ? 'AND mc.id_country = ' . (int) $billing->id_country : '') . '\n AND (SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'module_shop ms WHERE ms.id_module = m.id_module AND ms.id_shop IN(' . implode(', ', $list) . ')) = ' . count($list) . '\n AND hm.id_shop IN(' . implode(', ', $list) . ')\n ' . ((count($groups) && $frontend && $use_groups) ? 'AND (mg.`id_group` IN (' . implode(', ', $groups) . '))' : '') . '\n GROUP BY hm.id_hook, hm.id_module\n ORDER BY hm.`position`, m.`name` DESC');\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function lbf_current_value($frow, $formid, $encounter)\n{\n global $pid;\n $formname = $frow['form_id'];\n $field_id = $frow['field_id'];\n $source = $frow['source'];\n $currvalue = '';\n $deffname = $formname . '_default_' . $field_id;\n if ($source == 'D' || $source == 'H') {\n // Get from patient_data, employer_data or history_data.\n if ($source == 'H') {\n $table = 'history_data';\n $orderby = 'ORDER BY date DESC LIMIT 1';\n } elseif (strpos($field_id, 'em_') === 0) {\n $field_id = substr($field_id, 3);\n $table = 'employer_data';\n $orderby = 'ORDER BY date DESC LIMIT 1';\n } else {\n $table = 'patient_data';\n $orderby = '';\n }\n\n // It is an error if the field does not exist, but don't crash.\n $tmp = sqlQuery(\"SHOW COLUMNS FROM \" . escape_table_name($table) . \" WHERE Field = ?\", array($field_id));\n if (empty($tmp)) {\n return '*?*';\n }\n\n $pdrow = sqlQuery(\"SELECT `$field_id` AS field_value FROM \" . escape_table_name($table) . \" WHERE pid = ? $orderby\", array($pid));\n if (isset($pdrow)) {\n $currvalue = $pdrow['field_value'];\n }\n } elseif ($source == 'E') {\n $sarow = false;\n if ($encounter) {\n // Get value from shared_attributes of the current encounter.\n $sarow = sqlQuery(\n \"SELECT field_value FROM shared_attributes WHERE \" .\n \"pid = ? AND encounter = ? AND field_id = ?\",\n array($pid, $encounter, $field_id)\n );\n if (!empty($sarow)) {\n $currvalue = $sarow['field_value'];\n }\n } elseif ($formid) {\n // Get from shared_attributes of the encounter that this form is linked to.\n // Note the importance of having an index on forms.form_id.\n $sarow = sqlQuery(\n \"SELECT sa.field_value \" .\n \"FROM forms AS f, shared_attributes AS sa WHERE \" .\n \"f.form_id = ? AND f.formdir = ? AND f.deleted = 0 AND \" .\n \"sa.pid = f.pid AND sa.encounter = f.encounter AND sa.field_id = ?\",\n array($formid, $formname, $field_id)\n );\n if (!empty($sarow)) {\n $currvalue = $sarow['field_value'];\n }\n } else {\n // New form and encounter not available, this should not happen.\n }\n if (empty($sarow) && !$formid) {\n // New form, see if there is a custom default from a plugin.\n if (function_exists($deffname)) {\n $currvalue = call_user_func($deffname);\n }\n }\n } elseif ($source == 'V') {\n if ($encounter) {\n // Get value from the current encounter's form_encounter.\n $ferow = sqlQuery(\n \"SELECT * FROM form_encounter WHERE \" .\n \"pid = ? AND encounter = ?\",\n array($pid, $encounter)\n );\n if (isset($ferow[$field_id])) {\n $currvalue = $ferow[$field_id];\n }\n } elseif ($formid) {\n // Get value from the form_encounter that this form is linked to.\n $ferow = sqlQuery(\n \"SELECT fe.* \" .\n \"FROM forms AS f, form_encounter AS fe WHERE \" .\n \"f.form_id = ? AND f.formdir = ? AND f.deleted = 0 AND \" .\n \"fe.pid = f.pid AND fe.encounter = f.encounter\",\n array($formid, $formname)\n );\n if (isset($ferow[$field_id])) {\n $currvalue = $ferow[$field_id];\n }\n } else {\n // New form and encounter not available, this should not happen.\n }\n } elseif ($formid) {\n // This is a normal form field.\n $ldrow = sqlQuery(\"SELECT field_value FROM lbf_data WHERE \" .\n \"form_id = ? AND field_id = ?\", array($formid, $field_id));\n if (!empty($ldrow)) {\n $currvalue = $ldrow['field_value'];\n }\n } else {\n // New form, see if there is a custom default from a plugin.\n if (function_exists($deffname)) {\n $currvalue = call_user_func($deffname);\n }\n }\n\n return $currvalue;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function isUsed()\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n $RELATION = getDbRelations();\n\n if (!array_key_exists($this->getTable(), $RELATION)) {\n return false;\n }\n\n foreach ($RELATION[$this->getTable()] as $tablename => $fields) {\n if ($tablename[0] == '_') {\n continue; // Ignore relations prefxed by `_`\n }\n\n $or_criteria = [];\n\n foreach ($fields as $field) {\n if (is_array($field)) {\n // Relation based on 'itemtype'/'items_id' (polymorphic relationship)\n if ($this instanceof IPAddress && in_array('mainitemtype', $field) && in_array('mainitems_id', $field)) {\n // glpi_ipaddresses relationship that does not respect naming conventions\n $itemtype_field = 'mainitemtype';\n $items_id_field = 'mainitems_id';\n } else {\n $itemtype_matches = preg_grep('/^itemtype/', $field);\n $items_id_matches = preg_grep('/^items_id/', $field);\n $itemtype_field = reset($itemtype_matches);\n $items_id_field = reset($items_id_matches);\n }\n $or_criteria[] = [\n $itemtype_field => $this->getType(),\n $items_id_field => $this->getID(),\n ];\n } else {\n // Relation based on single foreign key\n $or_criteria[] = [\n $field => $this->getID(),\n ];\n }\n }\n\n if (count($or_criteria) === 0) {\n return false;\n }\n\n $row = $DB->request([\n 'FROM' => $tablename,\n 'COUNT' => 'cpt',\n 'WHERE' => ['OR' => $or_criteria]\n ])->current();\n if ($row['cpt'] > 0) {\n return true;\n }\n }\n\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getItemTypeForTable($table)\n {\n /** @var array $CFG_GLPI */\n global $CFG_GLPI;\n\n if (isset($CFG_GLPI['glpiitemtypetables'][$table])) {\n return $CFG_GLPI['glpiitemtypetables'][$table];\n } else {\n $inittable = $table;\n $table = str_replace(\"glpi_\", \"\", $table);\n $prefix = \"\";\n $pref2 = NS_GLPI;\n $is_plugin = false;\n\n $matches = [];\n if (preg_match('/^plugin_([a-z0-9]+)_/', $table, $matches)) {\n $table = preg_replace('/^plugin_[a-z0-9]+_/', '', $table);\n $prefix = \"Plugin\" . Toolbox::ucfirst($matches[1]);\n $pref2 = NS_PLUG . ucfirst($matches[1]) . '\\\\';\n $is_plugin = true;\n }\n\n if (strstr($table, '_')) {\n $split = explode('_', $table);\n\n foreach ($split as $key => $part) {\n $split[$key] = Toolbox::ucfirst($this->getSingular($part));\n }\n $table = implode('_', $split);\n } else {\n $table = Toolbox::ucfirst($this->getSingular($table));\n }\n\n $base_itemtype = $this->fixItemtypeCase($prefix . $table);\n\n $itemtype = null;\n if (class_exists($base_itemtype)) {\n $class_file = (new ReflectionClass($base_itemtype))->getFileName();\n $is_glpi_class = $class_file !== false && (\n str_starts_with(realpath($class_file), realpath(GLPI_ROOT))\n || str_starts_with(realpath($class_file), realpath(GLPI_MARKETPLACE_DIR))\n || str_starts_with(realpath($class_file), realpath(GLPI_PLUGIN_DOC_DIR))\n );\n if ($is_glpi_class) {\n $itemtype = $base_itemtype;\n }\n }\n\n // Handle namespaces\n if ($itemtype === null) {\n $namespaced_itemtype = $this->fixItemtypeCase($pref2 . str_replace('_', '\\\\', $table));\n\n if (class_exists($namespaced_itemtype)) {\n $itemtype = $namespaced_itemtype;\n } else {\n // Handle namespace + db relation\n // On the previous step we converted all '_' into '\\'\n // However some '_' must be kept in case of an item relation\n // For example, with the `glpi_namespace1_namespace2_items_filters` table\n // the expected itemtype is Glpi\\Namespace1\\Namespace2\\Item_Filter\n // NOT Glpi\\Namespace1\\Namespace2\\Item\\Filter\n // To avoid this, we can revert the last '_' and check if the itemtype exists\n $check_alternative = $is_plugin\n ? substr_count($table, '_') >= 1 // for plugin classes, always keep the first+second namespace levels (GlpiPlugin\\\\PluginName\\\\)\n : substr_count($table, '_') > 0 // for GLPI classes, always keep the first namespace level (Glpi\\\\)\n ;\n if ($check_alternative) {\n $last_backslash_position = strrpos($namespaced_itemtype, \"\\\\\");\n // Replace last '\\' into '_'\n $alternative_namespaced_itemtype = substr_replace(\n $namespaced_itemtype,\n '_',\n $last_backslash_position,\n 1\n );\n $alternative_namespaced_itemtype = $this->fixItemtypeCase($alternative_namespaced_itemtype);\n\n if (class_exists($alternative_namespaced_itemtype)) {\n $itemtype = $alternative_namespaced_itemtype;\n }\n }\n }\n }\n\n if ($itemtype !== null && ($classname = $this->getClassForItemtype($itemtype)) !== null) {\n $CFG_GLPI['glpiitemtypetables'][$inittable] = $classname;\n $CFG_GLPI['glpitablesitemtype'][$classname] = $inittable;\n return $itemtype;\n }\n\n return \"UNKNOWN\";\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function detectCredentials(): void\n {\n if ($this->device->snmp_disable) {\n return;\n }\n\n $host_unreachable_exception = new HostUnreachableSnmpException($this->device->hostname);\n\n // which snmp version should we try (and in what order)\n $snmp_versions = $this->device->snmpver ? [$this->device->snmpver] : Config::get('snmp.version');\n\n $communities = Arr::where(Arr::wrap(Config::get('snmp.community')), function ($community) {\n return $community && is_string($community);\n });\n if ($this->device->community) {\n array_unshift($communities, $this->device->community);\n }\n $communities = array_unique($communities);\n\n $v3_credentials = Config::get('snmp.v3');\n array_unshift($v3_credentials, $this->device->only(['authlevel', 'authname', 'authpass', 'authalgo', 'cryptopass', 'cryptoalgo']));\n $v3_credentials = array_unique($v3_credentials, SORT_REGULAR);\n\n foreach ($snmp_versions as $snmp_version) {\n $this->device->snmpver = $snmp_version;\n\n if ($snmp_version === 'v3') {\n // Try each set of parameters from config\n foreach ($v3_credentials as $v3) {\n $this->device->fill(Arr::only($v3, ['authlevel', 'authname', 'authpass', 'authalgo', 'cryptopass', 'cryptoalgo']));\n\n if ($this->connectivity->isSNMPable()) {\n return;\n } else {\n $host_unreachable_exception->addReason($snmp_version, $this->device->authname . '/' . $this->device->authlevel);\n }\n }\n } elseif ($snmp_version === 'v2c' || $snmp_version === 'v1') {\n // try each community from config\n foreach ($communities as $community) {\n $this->device->community = $community;\n if ($this->connectivity->isSNMPable()) {\n return;\n } else {\n $host_unreachable_exception->addReason($snmp_version, $this->device->community);\n }\n }\n } else {\n throw new SnmpVersionUnsupportedException($snmp_version);\n }\n }\n\n if ($this->ping_fallback) {\n $this->device->snmp_disable = true;\n $this->device->os = 'ping';\n\n return;\n }\n\n throw $host_unreachable_exception;\n }", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public static function getOrderByCriteria(string $itemtype, array $sort_fields): array\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n $orderby_criteria = [];\n $searchopt = SearchOption::getOptionsForItemtype($itemtype);\n\n foreach ($sort_fields as $sort_field) {\n $ID = $sort_field['searchopt_id'];\n if (isset($searchopt[$ID]['nosort']) && $searchopt[$ID]['nosort']) {\n continue;\n }\n $order = $sort_field['order'] ?? 'ASC';\n // Order security check\n if ($order != 'ASC') {\n $order = 'DESC';\n }\n\n $criterion = null;\n\n $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];\n\n $addtable = '';\n\n $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);\n $orig_table = SearchEngine::getOrigTableName($itemtype);\n if (\n ($is_fkey_composite_on_self || $table != $orig_table)\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable .= \"_\" . $searchopt[$ID][\"linkfield\"];\n }\n\n if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);\n\n if (!empty($complexjoin)) {\n $addtable .= \"_\" . $complexjoin;\n }\n }\n\n if (isset($CFG_GLPI[\"union_search_type\"][$itemtype])) {\n $criterion = \"`ITEM_{$itemtype}_{$ID}` $order\";\n }\n\n // Plugin can override core definition for its type\n if ($criterion === null && $plug = isPluginItemType($itemtype)) {\n $out = \\Plugin::doOneHook(\n $plug['plugin'],\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }\n\n if ($criterion === null) {\n switch ($table . \".\" . $field) {\n case \"glpi_users.name\":\n if ($itemtype != 'User') {\n if ($_SESSION[\"glpinames_format\"] == \\User::FIRSTNAME_BEFORE) {\n $name1 = 'firstname';\n $name2 = 'realname';\n } else {\n $name1 = 'realname';\n $name2 = 'firstname';\n }\n $addaltemail = \"\";\n if (\n in_array($itemtype, ['Ticket', 'Change', 'Problem'])\n && isset($searchopt[$ID]['joinparams']['beforejoin']['table'])\n && in_array($searchopt[$ID]['joinparams']['beforejoin']['table'], ['glpi_tickets_users', 'glpi_changes_users', 'glpi_problems_users'])\n ) { // For tickets_users\n $ticket_user_table = $searchopt[$ID]['joinparams']['beforejoin']['table'] . \"_\" .\n self::computeComplexJoinID($searchopt[$ID]['joinparams']['beforejoin']['joinparams']);\n $addaltemail = \",\n IFNULL(`$ticket_user_table`.`alternative_email`, '')\";\n }\n if ((isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])) {\n $criterion = \"GROUP_CONCAT(DISTINCT CONCAT(\n IFNULL(`$table$addtable`.`$name1`, ''),\n IFNULL(`$table$addtable`.`$name2`, ''),\n IFNULL(`$table$addtable`.`name`, '')$addaltemail\n ) ORDER BY CONCAT(\n IFNULL(`$table$addtable`.`$name1`, ''),\n IFNULL(`$table$addtable`.`$name2`, ''),\n IFNULL(`$table$addtable`.`name`, '')$addaltemail) ASC\n ) $order\";\n } else {\n $criterion = \"CONCAT(\n IFNULL(`$table$addtable`.`$name1`, ''),\n IFNULL(`$table$addtable`.`$name2`, ''),\n IFNULL(`$table$addtable`.`name`, '')$addaltemail\n ) $order\";\n }\n } else {\n $criterion = \"`\" . $table . $addtable . \"`.`name` $order\";\n }\n break;\n case \"glpi_ipaddresses.name\":\n $criterion = \"INET6_ATON(`$table$addtable`.`$field`) $order\";\n break;\n }\n }\n\n //// Default cases\n\n // Link with plugin tables\n if ($criterion === null && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = \\Plugin::doOneHook(\n $plug,\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }\n }\n\n // Preformat items\n if ($criterion === null && isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"date_delay\":\n $interval = \"MONTH\";\n if (isset($searchopt[$ID]['delayunit'])) {\n $interval = $searchopt[$ID]['delayunit'];\n }\n\n $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"- `$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n $criterion = QueryFunction::dateAdd(\n date: \"{$table}{$addtable}.{$searchopt[$ID]['datafields'][1]}\",\n interval: new QueryExpression($DB::quoteName(\"{$table}{$addtable}.{$searchopt[$ID]['datafields'][2]}\") . \" $add_minus\"),\n interval_unit: $interval,\n ) . \" $order\";\n }\n }\n\n $orderby_criteria[] = new QueryExpression($criterion ?? \"`ITEM_{$itemtype}_{$ID}` $order\");\n }\n\n return $orderby_criteria;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function toArray()\n {\n $item = [];\n $hasVisible = false;\n\n foreach ($this->visible as $key => $val) {\n if (is_string($val)) {\n if (strpos($val, '.')) {\n list($relation, $name) = explode('.', $val);\n $this->visible[$relation][] = $name;\n } else {\n $this->visible[$val] = true;\n $hasVisible = true;\n }\n unset($this->visible[$key]);\n }\n }\n\n foreach ($this->hidden as $key => $val) {\n if (is_string($val)) {\n if (strpos($val, '.')) {\n list($relation, $name) = explode('.', $val);\n $this->hidden[$relation][] = $name;\n } else {\n $this->hidden[$val] = true;\n }\n unset($this->hidden[$key]);\n }\n }\n\n // \u5408\u5e76\u5173\u8054\u6570\u636e\n $data = array_merge($this->data, $this->relation);\n\n foreach ($data as $key => $val) {\n if ($val instanceof Model || $val instanceof ModelCollection) {\n // \u5173\u8054\u6a21\u578b\u5bf9\u8c61\n if (isset($this->visible[$key]) && is_array($this->visible[$key])) {\n $val->visible($this->visible[$key]);\n } elseif (isset($this->hidden[$key]) && is_array($this->hidden[$key])) {\n $val->hidden($this->hidden[$key]);\n }\n // \u5173\u8054\u6a21\u578b\u5bf9\u8c61\n if (!isset($this->hidden[$key]) || true !== $this->hidden[$key]) {\n $item[$key] = $val->toArray();\n }\n } elseif (isset($this->visible[$key])) {\n $item[$key] = $this->getAttr($key);\n } elseif (!isset($this->hidden[$key]) && !$hasVisible) {\n $item[$key] = $this->getAttr($key);\n }\n }\n\n // \u8ffd\u52a0\u5c5e\u6027\uff08\u5fc5\u987b\u5b9a\u4e49\u83b7\u53d6\u5668\uff09\n if (!empty($this->append)) {\n foreach ($this->append as $key => $name) {\n if (is_array($name)) {\n // \u8ffd\u52a0\u5173\u8054\u5bf9\u8c61\u5c5e\u6027\n $relation = $this->getRelation($key);\n\n if (!$relation) {\n $relation = $this->getAttr($key);\n if ($relation) {\n $relation->visible($name);\n }\n }\n\n $item[$key] = $relation ? $relation->append($name)->toArray() : [];\n } elseif (strpos($name, '.')) {\n list($key, $attr) = explode('.', $name);\n // \u8ffd\u52a0\u5173\u8054\u5bf9\u8c61\u5c5e\u6027\n $relation = $this->getRelation($key);\n\n if (!$relation) {\n $relation = $this->getAttr($key);\n if ($relation) {\n $relation->visible([$attr]);\n }\n }\n\n $item[$key] = $relation ? $relation->append([$attr])->toArray() : [];\n } else {\n $item[$name] = $this->getAttr($name, $item);\n }\n }\n }\n\n return $item;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "protected function buildTree(int $currentParentId, string $fields = '', array $parentIdGroups = null, array $params = []): array\n {\n $objects = [];\n $storeTable = $this->storetable;\n $idfield = $this->idField;\n\n if (!$parentIdGroups) {\n $object = DataObject::getById($currentParentId);\n if (isset($params['language'])) {\n $language = $params['language'];\n\n $query = \"\n WITH RECURSIVE cte(id, classId, parentId, path) as (\n SELECT c.id AS id, c.classId AS classId, c.parentid AS parentId, c.path as `path`\n FROM objects c\n WHERE c.parentid = $currentParentId\n UNION ALL\n SELECT p.id AS id, p.classId AS classId, p.parentid AS parentId, p.path as `path`\n FROM objects p\n INNER JOIN cte on (p.parentid = cte.id)\n ) SELECT l.language AS `language`,\n x.id AS id,\n x.classId AS classId,\n x.parentId AS parentId\n $fields\n FROM cte x\n LEFT JOIN $storeTable l ON x.id = l.$idfield\n WHERE COALESCE(`language`, \" . $this->db->quote($language) . ') = ' . $this->db->quote($language) .\n ' ORDER BY x.path ASC';\n } else {\n $query = \"\n WITH RECURSIVE cte(id, classId, parentId, path) as (\n SELECT c.id AS id, c.classId AS classId, c.parentid AS parentId, c.path as `path`\n FROM objects c\n WHERE c.parentid = $currentParentId\n UNION ALL\n SELECT p.id AS id, p.classId AS classId, p.parentid AS parentId, p.path as `path`\n FROM objects p\n INNER JOIN cte on (p.parentid = cte.id)\n )\tSELECT x.id AS id,\n x.classId AS classId,\n x.parentId AS parentId\n $fields\n FROM cte x\n LEFT JOIN $storeTable a ON x.id = a.$idfield\n GROUP BY x.id\n ORDER BY x.path ASC\";\n }\n $queryCacheKey = 'tree_'.md5($query);\n\n if (self::$useRuntimeCache) {\n $parentIdGroups = self::$runtimeCache[$queryCacheKey] ?? null;\n }\n\n if (!$parentIdGroups) {\n $result = $this->db->fetchAllAssociative($query);\n\n if (isset($params['language'])) {\n $result = $this->filterResultByLanguage($result, $params['language'], 'language');\n }\n\n // group the results together based on the parent id's\n $parentIdGroups = [];\n $rowCount = count($result);\n for ($rowIdx = 0; $rowIdx < $rowCount; ++$rowIdx) {\n // assign the reference\n $rowData = &$result[$rowIdx];\n\n if (!isset($parentIdGroups[$rowData['parentId']])) {\n $parentIdGroups[$rowData['parentId']] = [];\n }\n\n $parentIdGroups[$rowData['parentId']][] = &$rowData;\n }\n if (self::$useRuntimeCache) {\n self::$runtimeCache[$queryCacheKey] = $parentIdGroups;\n }\n }\n }\n\n if (isset($parentIdGroups[$currentParentId])) {\n $childData = $parentIdGroups[$currentParentId];\n $childCount = count($childData);\n for ($childIdx = 0; $childIdx < $childCount; ++$childIdx) {\n $rowData = &$childData[$childIdx];\n\n if ($rowData['classId'] == $this->classId) {\n $this->childFound = true;\n }\n\n $id = $rowData['id'];\n\n $o = [\n 'id' => $id,\n 'children' => $this->buildTree($id, $fields, $parentIdGroups, $params),\n 'values' => $rowData,\n ];\n\n $objects[] = $o;\n }\n }\n\n return $objects;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getStats() {\n\t\tglobal $config, $db;\n\n\t\t$ret = array();\n\n\t\t$ret['unique_id'] = hash('sha1', $config['server_path']);\n\t\t$ret['server_os'] = php_uname('s') . ' ' . php_uname('r');\n\n\t\t$ret['myaac_version'] = MYAAC_VERSION;\n\t\t$ret['myaac_db_version'] = DATABASE_VERSION;\n\n\t\tif($db->hasTable('server_config')) {\n\t\t\t$query = $db->query('SELECT `value` FROM `server_config` WHERE `config` = ' . $db->quote('database_version'));\n\t\t\tif($query->rowCount() == 1) {\n\t\t\t\t$query = $query->fetch();\n\t\t\t\t$ret['otserv_db_version'] = $query['value'];\n\t\t\t}\n\t\t}\n\n\t\t$ret['client_version'] = $config['client'];\n\n\t\t$ret['php_version'] = phpversion();\n\n\t\t$query = $db->query('SELECT VERSION() as `version`;');\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['mysql_version'] = $query['version'];\n\t\t}\n\n\t\t$query = $db->query('SELECT SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 ), 0)) AS \"size\"\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = \"' . $config['database_name'] . '\";');\n\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['database_size'] = $query['size'];\n\t\t}\n\n\t\t$ret['views_counter'] = getDatabaseConfig('views_counter');\n\n\t\t$query = $db->query('SELECT COUNT(`id`) as `size` FROM `accounts`;');\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['accounts_size'] = $query['size'];\n\t\t}\n\n\t\t$query = $db->query('SELECT COUNT(`id`) as `size` FROM `players`;');\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['players_size'] = $query['size'];\n\t\t}\n\n\t\t$query = $db->query('SELECT COUNT(`id`) as `size` FROM `' . TABLE_PREFIX . 'monsters`;');\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['monsters_size'] = $query['size'];\n\t\t}\n\n\t\t$query = $db->query('SELECT COUNT(`id`) as `size` FROM `' . TABLE_PREFIX . 'spells`;');\n\t\tif($query->rowCount() == 1) {\n\t\t\t$query = $query->fetch();\n\t\t\t$ret['spells_size'] = $query['size'];\n\t\t}\n\n\t\t$ret['locales'] = get_locales();\n\t\t$ret['plugins'] = array();\n\t\tforeach(get_plugins() as $plugin) {\n\t\t\t$string = file_get_contents(BASE . 'plugins/' . $plugin . '.json');\n\t\t\t$plugin_info = json_decode($string, true);\n\t\t\tif($plugin_info != false) {\n\t\t\t\tif(isset($plugin_info['version'])) {\n\t\t\t\t\t$ret['plugins'][$plugin] = $plugin_info['version'];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$ret['templates'] = get_templates();\n\n\t\t$ret['date_timezone'] = $config['date_timezone'];\n\t\t$ret['backward_support'] = $config['backward_support'];\n\n\t\t$cache_engine = strtolower($config['cache_engine']);\n\t\tif($cache_engine == 'auto') {\n\t\t\t$cache_engine = Cache::detect();\n\t\t}\n\n\t\t$ret['cache_engine'] = $cache_engine;\n\t\treturn $ret;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "public function sumPaidInRange(Carbon $start, Carbon $end): array\n {\n Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));\n $bills = $this->getActiveBills();\n $default = app('amount')->getDefaultCurrency();\n $return = [];\n $converter = new ExchangeRateConverter();\n\n /** @var Bill $bill */\n foreach ($bills as $bill) {\n /** @var Collection $set */\n $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']);\n $currency = $bill->transactionCurrency;\n $currencyId = $bill->transaction_currency_id;\n\n $return[$currencyId] ??= [\n 'currency_id' => (string)$currency->id,\n 'currency_name' => $currency->name,\n 'currency_symbol' => $currency->symbol,\n 'currency_code' => $currency->code,\n 'currency_decimal_places' => $currency->decimal_places,\n 'native_currency_id' => (string)$default->id,\n 'native_currency_name' => $default->name,\n 'native_currency_symbol' => $default->symbol,\n 'native_currency_code' => $default->code,\n 'native_currency_decimal_places' => $default->decimal_places,\n 'sum' => '0',\n 'native_sum' => '0',\n ];\n\n /** @var TransactionJournal $transactionJournal */\n foreach ($set as $transactionJournal) {\n /** @var null|Transaction $sourceTransaction */\n $sourceTransaction = $transactionJournal->transactions()->where('amount', '<', 0)->first();\n if (null !== $sourceTransaction) {\n $amount = $sourceTransaction->amount;\n if ((int)$sourceTransaction->foreign_currency_id === $currency->id) {\n // use foreign amount instead!\n $amount = (string)$sourceTransaction->foreign_amount;\n }\n // convert to native currency\n $nativeAmount = $amount;\n if ($currencyId !== $default->id) {\n // get rate and convert.\n $nativeAmount = $converter->convert($currency, $default, $transactionJournal->date, $amount);\n }\n if ((int)$sourceTransaction->foreign_currency_id === $default->id) {\n // ignore conversion, use foreign amount\n $nativeAmount = (string)$sourceTransaction->foreign_amount;\n }\n $return[$currencyId]['sum'] = bcadd($return[$currencyId]['sum'], $amount);\n $return[$currencyId]['native_sum'] = bcadd($return[$currencyId]['native_sum'], $nativeAmount);\n }\n }\n }\n $converter->summarize();\n\n return $return;\n }", "smellKey": "S3776", "smellId": null, "repo": "firefly-iii_firefly-iii", "language": "php"} {"function": "public static function discover($force = false, LoggerInterface $logger = null)\n {\n if ( null !== self::$endpointClassMap && ! $force ) {\n return;\n }\n\n // As per PSR-4 (http://www.php-fig.org/psr/psr-4/) the contiguous sub-namespace\n // names after the \"namespace prefix\" correspond to a subdirectory within a \"base\n // directory\", in which the namespace separators represent directory separators.\n // This means that we can assume subdirectories under the directory where this\n // file resides represent sub-namespaces.\n\n // The endpoint directory is relative to the directory where this file is found\n $endpointDir = dirname(__FILE__)\n . DIRECTORY_SEPARATOR\n . strtr(self::DATA_ENDPOINT_RELATIVE_NS, '\\\\', DIRECTORY_SEPARATOR);\n $endpointDirLength = strlen($endpointDir);\n\n // Recursively traverse the directory where the endpoints live and discover any\n // defined endpoints.\n\n $dirIterator = new \\RecursiveDirectoryIterator($endpointDir);\n $flattenedIterator = new \\RecursiveIteratorIterator($dirIterator);\n self::$endpointClassMap = array();\n\n // The iterator returns SplFileInfo objects where the keys are the path to the\n // file.\n\n foreach ( $flattenedIterator as $path => $fileInfo ) {\n\n if ( $flattenedIterator->isDot() ) {\n continue;\n }\n\n // Set up an array so we can programmatically construct the namespace based on\n // the path to the class file\n\n $constructedNamespace = array(__NAMESPACE__, self::DATA_ENDPOINT_RELATIVE_NS);\n\n // Construct any additional sub-namespaces for subdirectories discovered under\n // the endpoint namespace (e.g. the subdirectory DataEndpoint/Filters\n // translates to the namespace DataEndpoint\\Filters.\n\n $subDirNs = strtr(substr($fileInfo->getPath(), $endpointDirLength + 1), DIRECTORY_SEPARATOR, '\\\\');\n if ( \"\" !== $subDirNs) {\n $constructedNamespace[] = $subDirNs;\n }\n\n // Discover the class name based on the file name. The file name is expected\n // to be named <class>.<extension>\n\n // SplFileInfo::getExtension() is not defined until PHP 5.3.6\n\n $filename = $fileInfo->getFilename();\n $extension = '';\n if ( false !== ($pos = strrpos($filename, '.')) ) {\n $extension = substr($filename, $pos + 1);\n }\n\n // Handle the case where there is no extension\n $length = ( strlen($extension) > 0 ? -1 * (strlen($extension) + 1) : strlen($filename) );\n $className = substr($filename, 0, $length);\n $constructedNamespace[] = $className;\n\n $nsClass = implode('\\\\', $constructedNamespace);\n\n try {\n $r = new \\ReflectionClass($nsClass);\n\n // Ensure that the class is not abstract and implements the required\n // interface\n\n if ( ! $r->isAbstract() && $r->implementsInterface(self::DATA_ENDPOINT_REQUIRED_INTERFACE) ) {\n\n if ( $r->hasConstant(self::ENDPOINT_NAME_CONSTANT) ) {\n\n $name = $r->getConstant(self::ENDPOINT_NAME_CONSTANT);\n if ( ! array_key_exists($name, self::$endpointClassMap) ) {\n self::$endpointClassMap[$name] = $r->getName();\n } elseif ( null !== $logger ) {\n $logger->warning(\n sprintf(\n \"%s Endpoint with name '%s' already exists, skipping\",\n __CLASS__,\n $name\n )\n );\n }\n\n } elseif ( null !== $logger ) {\n\n $logger->warning(\n sprintf(\n \"%s Class '%s' does not define %s, skipping\",\n __CLASS__,\n $r->getName(),\n self::ENDPOINT_NAME_CONSTANT\n )\n );\n\n }\n }\n } catch ( \\ReflectionException $e ) {\n // The class does not exist\n continue;\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected static function loadUpgradeVersionList($module_name, $module_version, $registered_version)\n {\n $list = [];\n\n $upgrade_path = _PS_MODULE_DIR_ . $module_name . '/upgrade/';\n\n // Check if folder exist and it could be read\n if (file_exists($upgrade_path) && ($files = scandir($upgrade_path, SCANDIR_SORT_NONE))) {\n // Read each file name\n foreach ($files as $file) {\n if (!in_array($file, ['.', '..', '.svn', 'index.php']) && preg_match('/\\.php$/', $file)) {\n $tab = explode('-', $file);\n\n if (!isset($tab[1])) {\n continue;\n }\n\n $file_version = basename($tab[1], '.php');\n // Compare version, if minor than actual, we need to upgrade the module\n if (count($tab) == 2 &&\n (Tools::version_compare($file_version, $module_version, '<=') &&\n Tools::version_compare($file_version, $registered_version, '>'))) {\n $list[] = [\n 'file' => $upgrade_path . $file,\n 'version' => $file_version,\n 'upgrade_function' => [\n 'upgrade_module_' . str_replace('.', '_', $file_version),\n 'upgradeModule' . str_replace('.', '', $file_version), ],\n ];\n }\n }\n }\n }\n\n // No files upgrade, then upgrade succeed\n if (count($list) == 0) {\n self::$modules_cache[$module_name]['upgrade']['success'] = true;\n Module::upgradeModuleVersion($module_name, $module_version);\n }\n\n usort($list, 'ps_module_version_sort');\n\n // Set the list to module cache\n self::$modules_cache[$module_name]['upgrade']['upgrade_file_left'] = $list;\n self::$modules_cache[$module_name]['upgrade']['available_upgrade'] = count($list);\n\n return (bool) count($list);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function showListForItem(CommonDBTM $item, $withtemplate = 0, $options = [])\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n if (!static::$itemtype_1::canView()) {\n return false;\n }\n\n if ($item->isNewID($item->getID())) {\n return false;\n }\n\n $criteria = static::$itemtype_1::getCommonCriteria();\n $params = [\n 'criteria' => $options['criteria'] ?? [],\n 'reset' => 'reset',\n 'restrict' => $options['restrict'] ?? [],\n ];\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n $restrict = $params['restrict'];\n\n $params['criteria'][0]['field'] = 12;\n $params['criteria'][0]['searchtype'] = 'equals';\n $params['criteria'][0]['value'] = 'all';\n $params['criteria'][0]['link'] = 'AND';\n\n $params['metacriteria'][0]['itemtype'] = $item->getType();\n $params['metacriteria'][0]['field'] = Search::getOptionNumber(\n $item->getType(),\n 'id'\n );\n $params['metacriteria'][0]['searchtype'] = 'equals';\n $params['metacriteria'][0]['value'] = $item->getID();\n $params['metacriteria'][0]['link'] = 'AND';\n // overide value from options\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n\n $criteria['WHERE'] = $restrict + getEntitiesRestrictCriteria(static::$itemtype_1::getTable());\n $criteria['WHERE'][static::$itemtype_1::getTable() . \".is_deleted\"] = 0;\n $criteria['LIMIT'] = (int)$_SESSION['glpilist_limit'];\n $iterator = $DB->request($criteria);\n $number = count($iterator);\n\n $colspan = 12;\n if (count($_SESSION[\"glpiactiveentities\"]) > 1) {\n $colspan++;\n }\n\n // Object for the item\n // Link to open a new ITIL object\n if (\n $item->getID()\n && !$item->isDeleted()\n && CommonITILObject::isPossibleToAssignType($item->getType())\n && static::canCreate()\n && !(!empty($withtemplate) && ($withtemplate == 2))\n && (!isset($item->fields['is_template']) || ($item->fields['is_template'] == 0))\n ) {\n $linknewitil = true;\n }\n\n if ($number > 0) {\n if (Session::haveRight(static::$itemtype_1::$rightname, static::$itemtype_1::READALL)) {\n $readall = true;\n }\n }\n\n // Object for linked items\n $linkeditems = $item->getLinkedItems();\n $restrict = [];\n if (count($linkeditems)) {\n foreach ($linkeditems as $ltype => $tab) {\n foreach ($tab as $lID) {\n $restrict[] = ['AND' => ['itemtype' => $ltype, 'items_id' => $lID]];\n }\n }\n }\n\n if (\n count($restrict)\n && Session::haveRight(static::$itemtype_1::$rightname, static::$itemtype_1::READALL)\n ) {\n $criteria = static::$itemtype_1::getCommonCriteria();\n $criteria['WHERE'] = ['OR' => $restrict]\n + getEntitiesRestrictCriteria(static::$itemtype_1::getTable());\n $iterator2 = $DB->request($criteria);\n $number2 = count($iterator2);\n $showform = true;\n } // Subquery for linked item\n\n TemplateRenderer::getInstance()->display('components/form/item_itilobject_item_list.html.twig', [\n 'item' => $item,\n 'linknewitil' => $linknewitil ?? false,\n 'itemtype_1' => static::$itemtype_1,\n 'colspan' => $colspan,\n 'number' => $number,\n 'number2' => $number2 ?? 0,\n 'showform' => $showform ?? false,\n 'readall' => $readall ?? false,\n 'params' => $params,\n 'html_output' => Search::HTML_OUTPUT,\n 'iterator' => $iterator,\n 'iterator2' => $iterator2 ?? [],\n ]);\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getDataForGrid(?DataObject\\Fieldcollection $data, DataObject\\Concrete $object = null, array $params = []): ?array\n {\n if (null === $data) {\n return null;\n }\n\n $dataForGrid = [];\n\n foreach ($data as $item) {\n if (!$item instanceof DataObject\\Fieldcollection\\Data\\AbstractData) {\n continue;\n }\n\n $itemData = [];\n $collectionDef = DataObject\\Fieldcollection\\Definition::getByKey($item->getType());\n if ($collectionDef instanceof DataObject\\Fieldcollection\\Definition) {\n foreach ($collectionDef->getFieldDefinitions() as $fd) {\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n foreach ($fd->getFieldDefinitions() as $localizedFieldDefinition) {\n $getter = 'get'.ucfirst($localizedFieldDefinition->getName());\n $itemData[$localizedFieldDefinition->getName()] = [\n 'title' => $localizedFieldDefinition->getTitle(),\n 'value' => $localizedFieldDefinition->getVersionPreview($item->$getter(), $object, $params),\n ];\n }\n } else {\n $getter = 'get'.ucfirst($fd->getName());\n $itemData[$fd->getName()] = [\n 'title' => $fd->getTitle(),\n 'value' => $fd->getVersionPreview($item->$getter(), $object, $params),\n ];\n }\n }\n }\n\n $dataForGrid[] = [\n 'type' => $collectionDef->getKey(),\n 'data' => $itemData,\n ];\n }\n\n return $dataForGrid;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function fixsub(&$items) {\n\tglobal $allitems,$itemsfnd;\n\tforeach($items as $k=>$item) {\n\t\tif ($item==null) {\n\t\t\tunset($items[$k]);\n\t\t} else if (is_array($item)) {\n\t\t\tif (!isset($item['items']) || !is_array($item['items'])) {\n\t\t\t\tunset($items[$k]);\n\t\t\t} else if (count($item['items'])>0) {\n\t\t\t\tfixsub($items[$k]['items']);\n\t\t\t}\n\t\t} else {\n\t\t\tif ($item==null || $item=='') {\n\t\t\t\tunset($items[$k]);\n\t\t\t} else if (!in_array($item,$allitems)) {\n\t\t\t\tunset($items[$k]);\n\t\t\t\techo \"Removed unused item from itemorder<br/>\";\n\t\t\t} else {\n\t\t\t\t$itemsfnd[] = $item;\n\t\t\t}\n\t\t}\n\t}\n\t$items = array_values($items);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function _get_binary_packet($skip_channel_filter = false)\n {\n if ($skip_channel_filter) {\n $read = array($this->fsock);\n $write = $except = null;\n\n if (!$this->curTimeout) {\n if ($this->keepAlive <= 0) {\n @stream_select($read, $write, $except, null);\n } else {\n if (!@stream_select($read, $write, $except, $this->keepAlive) && !count($read)) {\n $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_IGNORE, 0));\n return $this->_get_binary_packet(true);\n }\n }\n } else {\n if ($this->curTimeout < 0) {\n $this->is_timeout = true;\n return true;\n }\n\n $read = array($this->fsock);\n $write = $except = null;\n\n $start = microtime(true);\n\n if ($this->keepAlive > 0 && $this->keepAlive < $this->curTimeout) {\n if (!@stream_select($read, $write, $except, $this->keepAlive) && !count($read)) {\n $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_IGNORE, 0));\n $elapsed = microtime(true) - $start;\n $this->curTimeout-= $elapsed;\n return $this->_get_binary_packet(true);\n }\n $elapsed = microtime(true) - $start;\n $this->curTimeout-= $elapsed;\n }\n\n $sec = (int)floor($this->curTimeout);\n $usec = (int)(1000000 * ($this->curTimeout - $sec));\n\n // on windows this returns a \"Warning: Invalid CRT parameters detected\" error\n if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {\n $this->is_timeout = true;\n return true;\n }\n $elapsed = microtime(true) - $start;\n $this->curTimeout-= $elapsed;\n }\n }\n\n if (!is_resource($this->fsock) || feof($this->fsock)) {\n $this->bitmap = 0;\n $str = 'Connection closed (by server) prematurely';\n if (isset($elapsed)) {\n $str.= ' ' . $elapsed . 's';\n }\n user_error($str);\n return false;\n }\n\n $start = microtime(true);\n $sec = (int) floor($this->curTimeout);\n $usec = (int) (1000000 * ($this->curTimeout - $sec));\n stream_set_timeout($this->fsock, $sec, $usec);\n $raw = stream_get_contents($this->fsock, $this->decrypt_block_size);\n\n if (!strlen($raw)) {\n user_error('No data received from server');\n return false;\n }\n\n if ($this->decrypt !== false) {\n $raw = $this->decrypt->decrypt($raw);\n }\n if ($raw === false) {\n user_error('Unable to decrypt content');\n return false;\n }\n\n if (strlen($raw) < 5) {\n return false;\n }\n extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));\n\n $remaining_length = $packet_length + 4 - $this->decrypt_block_size;\n\n // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,\n // \"implementations SHOULD check that the packet length is reasonable\"\n // PuTTY uses 0x9000 as the actual max packet size and so to shall we\n if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {\n if (!$this->bad_key_size_fix && $this->_bad_algorithm_candidate($this->decryptName) && !($this->bitmap & SSH2::MASK_LOGIN)) {\n $this->bad_key_size_fix = true;\n $this->_reset_connection(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);\n return false;\n }\n user_error('Invalid size');\n return false;\n }\n\n $buffer = '';\n while ($remaining_length > 0) {\n $temp = stream_get_contents($this->fsock, $remaining_length);\n if ($temp === false || feof($this->fsock)) {\n $this->bitmap = 0;\n user_error('Error reading from socket');\n return false;\n }\n $buffer.= $temp;\n $remaining_length-= strlen($temp);\n }\n\n $stop = microtime(true);\n if (strlen($buffer)) {\n $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;\n }\n\n $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);\n $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty\n\n if ($this->hmac_check !== false) {\n $hmac = stream_get_contents($this->fsock, $this->hmac_size);\n if ($hmac === false || strlen($hmac) != $this->hmac_size) {\n $this->bitmap = 0;\n user_error('Error reading socket');\n return false;\n } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {\n user_error('Invalid HMAC');\n return false;\n }\n }\n\n switch ($this->decompress) {\n case self::NET_SSH2_COMPRESSION_ZLIB_AT_OPENSSH:\n if (!$this->isAuthenticated()) {\n break;\n }\n case self::NET_SSH2_COMPRESSION_ZLIB:\n if ($this->regenerate_decompression_context) {\n $this->regenerate_decompression_context = false;\n\n $cmf = ord($payload[0]);\n $cm = $cmf & 0x0F;\n if ($cm != 8) { // deflate\n user_error(\"Only CM = 8 ('deflate') is supported ($cm)\");\n }\n $cinfo = ($cmf & 0xF0) >> 4;\n if ($cinfo > 7) {\n user_error(\"CINFO above 7 is not allowed ($cinfo)\");\n }\n $windowSize = 1 << ($cinfo + 8);\n\n $flg = ord($payload[1]);\n //$fcheck = $flg && 0x0F;\n if ((($cmf << 8) | $flg) % 31) {\n user_error('fcheck failed');\n }\n $fdict = boolval($flg & 0x20);\n $flevel = ($flg & 0xC0) >> 6;\n\n $this->decompress_context = inflate_init(ZLIB_ENCODING_RAW, array('window' => $cinfo + 8));\n $payload = substr($payload, 2);\n }\n if ($this->decompress_context) {\n $payload = inflate_add($this->decompress_context, $payload, ZLIB_PARTIAL_FLUSH);\n }\n }\n\n $this->get_seq_no++;\n\n if (defined('NET_SSH2_LOGGING')) {\n $current = microtime(true);\n $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';\n $message_number = '<- ' . $message_number .\n ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';\n $this->_append_log($message_number, $payload);\n $this->last_packet = $current;\n }\n\n return $this->_filter($payload, $skip_channel_filter);\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function actionUpdate($id)\n {\n $modelStudentIdentification = $this->loadModel($id, $this->STUDENT_IDENTIFICATION);\n $modelStudentDocumentsAndAddress = $this->loadModel($id, $this->STUDENT_DOCUMENTS_AND_ADDRESS);\n $modelStudentRestrictions = $this->loadModel($id, $this->STUDENT_RESTRICTIONS);\n $modelStudentDisorder = $this->loadModel($id, $this->STUDENT_DISORDER);\n\n $oldCpf = $modelStudentDocumentsAndAddress->cpf;\n\n $vaccines = Vaccine::model()->findAll(array('order' => 'name'));\n $studentVaccinesSaves = StudentVaccine::model()->findAll(['select' => 'vaccine_id', 'condition' => 'student_id=:student_id', 'params' => [':student_id' => $id]]);\n if ($studentVaccinesSaves) {\n $studentVaccinesSaves = array_map(function ($item) {\n return $item->vaccine_id;\n }, $studentVaccinesSaves);\n }\n $modelEnrollment = new StudentEnrollment();\n\n if (\n isset($_POST[$this->STUDENT_IDENTIFICATION]) && isset($_POST[$this->STUDENT_DOCUMENTS_AND_ADDRESS])\n && isset($_POST[$this->STUDENT_RESTRICTIONS]) && isset($_POST[$this->STUDENT_DISORDER])\n ) {\n $modelStudentIdentification->attributes = $_POST[$this->STUDENT_IDENTIFICATION];\n $modelStudentDocumentsAndAddress->attributes = $_POST[$this->STUDENT_DOCUMENTS_AND_ADDRESS];\n $modelStudentRestrictions->attributes = $_POST[$this->STUDENT_RESTRICTIONS];\n $modelStudentDisorder->attributes = $_POST[$this->STUDENT_DISORDER];\n //Atributos comuns entre as tabelas\n $modelStudentDocumentsAndAddress->id = $modelStudentIdentification->id;\n $modelStudentDocumentsAndAddress->school_inep_id_fk = $modelStudentIdentification->school_inep_id_fk;\n $modelStudentDocumentsAndAddress->student_fk = $modelStudentIdentification->id;\n date_default_timezone_set(\"America/Recife\");\n $modelStudentIdentification->last_change = date('Y-m-d G:i:s');\n\n $newCpf = $_POST[$this->STUDENT_DOCUMENTS_AND_ADDRESS]['cpf'];\n\n if($oldCpf !== $newCpf && $newCpf !== \"\") {\n $existCpf = StudentDocumentsAndAddress::model()->findByAttributes(array('cpf' => $modelStudentDocumentsAndAddress->cpf));\n\n if($existCpf !== null) {\n Yii::app()->user->setFlash(\n 'error', Yii::t('default', 'J\u00e1 existe um registro associado a este CPF de um aluno cadastrado!')\n );\n $this->redirect(array('/student/update', 'id' => $modelStudentDocumentsAndAddress->id));\n }\n }\n\n if ($modelStudentIdentification->validate() && $modelStudentDocumentsAndAddress->validate()) {\n if ($modelStudentIdentification->save()) {\n $modelStudentRestrictions->student_fk = $modelStudentIdentification->id;\n $modelStudentDisorder->student_fk = $modelStudentIdentification->id;\n $modelStudentDocumentsAndAddress->id = $modelStudentIdentification->id;\n if ($modelStudentDocumentsAndAddress->save() && $modelStudentRestrictions->save() && $modelStudentDisorder->save()) {\n $saved = true;\n if (\n isset($_POST[$this->STUDENT_ENROLLMENT], $_POST[$this->STUDENT_ENROLLMENT][\"classroom_fk\"])\n && !empty($_POST[$this->STUDENT_ENROLLMENT][\"classroom_fk\"])\n ) {\n $modelEnrollment = new StudentEnrollment;\n $modelEnrollment->attributes = $_POST[$this->STUDENT_ENROLLMENT];\n $modelEnrollment->school_inep_id_fk = $modelStudentIdentification->school_inep_id_fk;\n $modelEnrollment->student_fk = $modelStudentIdentification->id;\n $modelEnrollment->student_inep_id = $modelStudentIdentification->inep_id;\n $modelEnrollment->create_date = date('Y-m-d');\n $modelEnrollment->daily_order = $modelEnrollment->getDailyOrder();\n $saved = false;\n\n\n $hasDuplicate = $modelEnrollment->alreadyExists();\n if ($modelEnrollment->validate() && !$hasDuplicate) {\n $saved = $modelEnrollment->save();\n }\n\n if ($hasDuplicate) {\n Yii::app()->user->setFlash(\n 'error', Yii::t('default', 'Aluno j\u00e1 est\u00e1 matriculado nessa turma.')\n );\n }\n }\n\n if (isset($_POST['Vaccine']['vaccine_id'])) {\n if (count($_POST['Vaccine']['vaccine_id']) > 0) {\n if ($studentVaccinesSaves) {\n StudentVaccine::model()->deleteAll(\"student_id = $modelStudentIdentification->id\");\n }\n\n foreach ($_POST['Vaccine']['vaccine_id'] as $vaccine_id) {\n $studentVaccine = new StudentVaccine();\n $studentVaccine->student_id = $modelStudentIdentification->id;\n $studentVaccine->vaccine_id = $vaccine_id;\n $studentVaccine->save();\n }\n }\n }\n\n if ($saved) {\n $flash = \"success\";\n $msg = 'O Cadastro de ' . $modelStudentIdentification->name . ' foi alterado com sucesso!';\n\n if (Yii::app()->features->isEnable(\"FEAT_SEDSP\")) {\n\n $this->authenticateSedToken();\n $syncResult = (object) $modelStudentIdentification->syncStudentWithSED($id, $modelEnrollment, self::UPDATE);\n\n if ($syncResult->identification->outErro !== null || $syncResult->enrollment->outErro !== null) {\n $flash = \"error\";\n $msg = '<span style=\"color: white;background: #23b923;\n padding:10px;border-radius: 4px;\">Cadastro do aluno ' . $modelStudentIdentification->name .\n ' alterado com sucesso no TAG, mas n\u00e3o foi poss\u00edvel sincroniz\u00e1-lo com a SEDSP. Motivo: </span>';\n if ($syncResult->identification->outErro) {\n $msg .= \"<br>Ficha do Aluno: \" . $syncResult->identification->outErro;\n }\n if ($syncResult->enrollment->outErro) {\n $msg .= \"<br>Matr\u00edcula: \" . $syncResult->enrollment->outErro;\n }\n }\n }\n\n Log::model()->saveAction(\n \"student\", $modelStudentIdentification->id,\n \"U\", $modelStudentIdentification->name\n );\n\n Yii::app()->user->setFlash($flash, Yii::t('default', $msg));\n $this->redirect(array('index', 'id' => $modelStudentIdentification->id));\n } else {\n $msg = 'N\u00e3o foi poss\u00edvel realizar as modifica\u00e7\u00f5es do aluno: ' .\n $modelStudentIdentification->name;\n\n Yii::app()->user->setFlash('error', Yii::t('default', $msg));\n $this->redirect(array('index', 'id' => $modelStudentIdentification->id));\n }\n }\n }\n }\n }\n\n $this->render('update', array(\n 'modelStudentIdentification' => $modelStudentIdentification,\n 'modelStudentDocumentsAndAddress' => $modelStudentDocumentsAndAddress,\n 'modelStudentRestrictions' => $modelStudentRestrictions,\n 'modelStudentDisorder' => $modelStudentDisorder,\n 'modelEnrollment' => $modelEnrollment,\n 'vaccines' => $vaccines,\n 'studentVaccinesSaves' => $studentVaccinesSaves\n ));\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "function &postcalendar_userapi_pcQueryEventsFA($args)\n{\n\n $end = '0000-00-00';\n extract($args);\n $eventstatus = 1;\n if (is_numeric($event_status)) {\n $eventstatus = $event_status;\n }\n\n if (!isset($start)) {\n $start = Date_Calc::dateNow('%Y-%m-%d');\n }\n\n list($sy,$sm,$sd) = explode('-', $start);\n\n list($dbconn) = pnDBGetConn();\n $pntable = pnDBGetTables();\n // link to the events tables\n $table = $pntable['postcalendar_events'];\n $cattable = $pntable['postcalendar_categories'];\n\n $sql = \"SELECT DISTINCT a.pc_eid, a.pc_informant, a.pc_catid, a.pc_title, \" .\n \"a.pc_time, a.pc_hometext, a.pc_eventDate, a.pc_duration, a.pc_endDate, \" .\n \"a.pc_startTime, a.pc_recurrtype, a.pc_recurrfreq, a.pc_recurrspec, \" .\n \"a.pc_topic, a.pc_alldayevent, a.pc_location, a.pc_conttel, \" .\n \"a.pc_contname, a.pc_contemail, a.pc_website, a.pc_fee, a.pc_sharing, \" .\n \"a.pc_prefcatid, \" .\n \"b.pc_catcolor, b.pc_catname, b.pc_catdesc, a.pc_pid, a.pc_aid, \" .\n \"concat(u.fname,' ',u.lname) as provider_name, \" .\n \"concat(pd.fname,' ',pd.lname) as patient_name, \" .\n \"concat(u2.fname, ' ', u2.lname) as owner_name, pd.DOB as patient_dob, \" .\n \"a.pc_facility\" .\n \"FROM $table AS a \" .\n \"LEFT JOIN $cattable AS b ON b.pc_catid = a.pc_catid \" .\n \"LEFT JOIN users as u ON a.pc_aid = u.id \" .\n \"LEFT JOIN users as u2 ON a.pc_aid = u2.id \" .\n \"LEFT JOIN patient_data as pd ON a.pc_pid=pd.pid \" .\n \"WHERE a.pc_eventstatus = '\" . pnVarPrepForStore($eventstatus) . \"' \" .\n \"AND (a.pc_endDate >= '\" . pnVarPrepForStore($start) . \"' OR a.pc_endDate = '0000-00-00') \" .\n \"AND a.pc_eventDate <= '\" . pnVarPrepForStore($end) . \"' \" .\n \"AND (a.pc_aid = '\" . pnVarPrepForStore($provider_id) . \"' OR a.pc_aid = '')\";\n\n //======================================================================\n // START SEARCH FUNCTIONALITY\n //======================================================================\n if (!empty($s_keywords)) {\n $sql .= \"AND ($s_keywords) \";\n }\n\n if (!empty($s_category)) {\n $sql .= \"AND ($s_category) \";\n }\n\n if (!empty($s_topic)) {\n $sql .= \"AND ($s_topic) \";\n }\n\n if (!empty($collide_etime) && !empty($collide_stime)) {\n $sql .= \"AND NOT ((pc_endTime <= '\" . pnVarPrepForStore($collide_stime) . \"') OR (pc_startTime >= '\" . pnVarPrepForStore($collide_etime) . \"')) AND pc_endTime IS NOT NULL \";\n }\n\n if (!empty($category)) {\n $sql .= \"AND (a.pc_catid = '\" . pnVarPrepForStore($category) . \"') \";\n }\n\n if (!empty($topic)) {\n $sql .= \"AND (a.pc_topic = '\" . pnVarPrepForStore($topic) . \"') \";\n }\n\n //======================================================================\n // Search sort and limitation\n //======================================================================\n if (empty($sort)) {\n $sql .= \"GROUP BY a.pc_eid ORDER BY a.pc_startTime ASC\";\n } else {\n $sql .= \"GROUP BY a.pc_eid ORDER BY a.$sort\";\n }\n\n //======================================================================\n // END SEARCH FUNCTIONALITY\n //======================================================================\n //echo \"<Br />sql: $sql<br />\";\n $result = $dbconn->Execute($sql);\n if ($dbconn->ErrorNo() != 0) {\n die(text($dbconn->ErrorMsg()));\n }\n\n // put the information into an array for easy access\n $events = array();\n // return an empty array if we don't have any results\n if (!isset($result)) {\n return $events;\n }\n\n for ($i = 0; !$result->EOF; $result->MoveNext()) {\n // get the results from the query\n if (isset($tmp)) {\n unset($tmp);\n } $tmp = array();\n list($tmp['eid'], $tmp['uname'], $tmp['catid'],\n $tmp['title'], $tmp['time'], $tmp['hometext'],\n $tmp['eventDate'], $tmp['duration'], $tmp['endDate'],\n $tmp['startTime'], $tmp['recurrtype'], $tmp['recurrfreq'],\n $tmp['recurrspec'], $tmp['topic'], $tmp['alldayevent'],\n $tmp['location'], $tmp['conttel'], $tmp['contname'],\n $tmp['contemail'], $tmp['website'], $tmp['fee'],\n $tmp['sharing'], $tmp['prefcatid'], $tmp['catcolor'],\n $tmp['catname'], $tmp['catdesc'], $tmp['pid'],\n $tmp['aid'], $tmp['provider_name'], $tmp['patient_name'],\n $tmp['owner_name'], $tmp['patient_dob'], $tmp['facility']) = $result->fields;\n\n // grab the name of the topic\n $topicname = pcGetTopicName($tmp['topic']);\n // get the user id of event's author\n $cuserid = @$nuke_users[strtolower($tmp['uname'])];\n // check the current event's permissions\n // the user does not have permission to view this event\n // if any of the following evaluate as false\n if ($tmp['sharing'] == SHARING_PRIVATE && $cuserid != $userid) {\n continue;\n }\n\n // add event to the array if we passed the permissions check\n // this is the common information\n $events[$i]['eid'] = $tmp['eid'];\n $events[$i]['uname'] = $tmp['uname'];\n $events[$i]['uid'] = $cuserid;\n $events[$i]['catid'] = $tmp['catid'];\n $events[$i]['time'] = $tmp['time'];\n $events[$i]['eventDate'] = $tmp['eventDate'];\n $events[$i]['duration'] = $tmp['duration'];\n // there has to be a more intelligent way to do this\n\n @list($events[$i]['duration_hours'],$dmin) = @explode('.', ($tmp['duration'] / 60 / 60));\n $events[$i]['duration_minutes'] = substr(sprintf('%.2f', '.' . 60 * ($dmin / 100)), 2, 2);\n //''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n $events[$i]['endDate'] = $tmp['endDate'];\n $events[$i]['startTime'] = $tmp['startTime'];\n $events[$i]['recurrtype'] = $tmp['recurrtype'];\n $events[$i]['recurrfreq'] = $tmp['recurrfreq'];\n $events[$i]['recurrspec'] = $tmp['recurrspec'];\n\n $rspecs = unserialize($tmp['recurrspec'], ['allowed_classes' => false]);\n $events[$i]['event_repeat_freq'] = $rspecs['event_repeat_freq'];\n $events[$i]['event_repeat_freq_type'] = $rspecs['event_repeat_freq_type'];\n $events[$i]['event_repeat_on_num'] = $rspecs['event_repeat_on_num'];\n $events[$i]['event_repeat_on_day'] = $rspecs['event_repeat_on_day'];\n $events[$i]['event_repeat_on_freq'] = $rspecs['event_repeat_on_freq'];\n\n $events[$i]['topic'] = $tmp['topic'];\n $events[$i]['alldayevent'] = $tmp['alldayevent'];\n $events[$i]['catcolor'] = $tmp['catcolor'];\n $events[$i]['catname'] = $tmp['catname'];\n $events[$i]['catdesc'] = $tmp['catdesc'];\n $events[$i]['pid'] = $tmp['pid'];\n $events[$i]['patient_name'] = $tmp['patient_name'];\n $events[$i]['provider_name'] = $tmp['provider_name'];\n $events[$i]['owner_name'] = $tmp['owner_name'];\n $events[$i]['patient_dob'] = $tmp['patient_dob'];\n $events[$i]['patient_age'] = date(\"Y\") - substr(($tmp['patient_dob']), 0, 4);\n $events[$i]['facility'] = getfacility($tmp['facility']);\n $events[$i]['sharing'] = $tmp['sharing'];\n $events[$i]['prefcatid'] = $tmp['prefcatid'];\n $events[$i]['aid'] = $tmp['aid'];\n $events[$i]['intervals'] = ceil(($tmp['duration'] / 60) / $GLOBALS['calendar_interval']);\n if ($events[$i]['intervals'] == 0) {\n $events[$i]['intervals'] = 1;\n }\n\n // is this a public event to be shown as busy?\n if ($tmp['sharing'] == SHARING_BUSY && $cuserid != $userid) {\n // make it not display any information\n $events[$i]['title'] = _USER_BUSY_TITLE;\n $events[$i]['hometext'] = _USER_BUSY_MESSAGE;\n $events[$i]['desc'] = _USER_BUSY_MESSAGE;\n $events[$i]['conttel'] = '';\n $events[$i]['contname'] = '';\n $events[$i]['contemail'] = '';\n $events[$i]['website'] = '';\n $events[$i]['fee'] = '';\n $events[$i]['location'] = '';\n $events[$i]['street1'] = '';\n $events[$i]['street2'] = '';\n $events[$i]['city'] = '';\n $events[$i]['state'] = '';\n $events[$i]['postal'] = '';\n } else {\n $display_type = substr($tmp['hometext'], 0, 6);\n if ($display_type == ':text:') {\n $prepFunction = 'pcVarPrepForDisplay';\n $tmp['hometext'] = substr($tmp['hometext'], 6);\n } elseif ($display_type == ':html:') {\n $prepFunction = 'pcVarPrepHTMLDisplay';\n $tmp['hometext'] = substr($tmp['hometext'], 6);\n } else {\n $prepFunction = 'pcVarPrepHTMLDisplay';\n }\n\n unset($display_type);\n $events[$i]['title'] = $prepFunction($tmp['title']);\n $events[$i]['hometext'] = $prepFunction($tmp['hometext']);\n $events[$i]['desc'] = $events[$i]['hometext'];\n $events[$i]['conttel'] = $prepFunction($tmp['conttel']);\n $events[$i]['contname'] = $prepFunction($tmp['contname']);\n $events[$i]['contemail'] = $prepFunction($tmp['contemail']);\n $events[$i]['website'] = $prepFunction(postcalendar_makeValidURL($tmp['website']));\n $events[$i]['fee'] = $prepFunction($tmp['fee']);\n $loc = unserialize($tmp['location'], ['allowed_classes' => false]);\n $events[$i]['location'] = $prepFunction($loc['event_location']);\n $events[$i]['street1'] = $prepFunction($loc['event_street1']);\n $events[$i]['street2'] = $prepFunction($loc['event_street2']);\n $events[$i]['city'] = $prepFunction($loc['event_city']);\n $events[$i]['state'] = $prepFunction($loc['event_state']);\n $events[$i]['postal'] = $prepFunction($loc['event_postal']);\n }\n\n $i++;\n }\n\n unset($tmp);\n $result->Close();\n return $events;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function run($time) {\n global $ost;\n // Migrate old config to Plugin Instance store\n foreach (Plugin::objects() as $plugin) {\n $c = new OldPluginConfig($plugin->getId());\n $config = $c->getInfo() ?: [];\n $instance = [\n 'name' => $plugin->getName(),\n 'plugin_id' => $plugin->getId(),\n 'config' => Format::json_encode($config)];\n $i = PluginInstance::create($instance);\n $i->setStatus($plugin->isActive());\n $i->updated = SqlFunction::NOW();\n $i->save();\n // Delete old config entries\n $c->destroy();\n }\n // Update Plugin ids used to the new format.\n PluginManager::clearCache();\n $ost->plugins->bootstrap();\n // Staff auth backends\n foreach (StaffAuthenticationBackend::allRegistered() as $p) {\n if ($p::$id && $p->getBkId() == $p::$id)\n continue;\n Staff::objects()\n ->filter(['backend' => $p::$id])\n ->update(['backend' => $p->getBkId()]);\n }\n // User auth backends\n foreach (UserAuthenticationBackend::allRegistered() as $p) {\n if ($p::$id && $p->getBkId() == $p::$id)\n continue;\n UserAccount::objects()\n ->filter(['backend' => $p::$id])\n ->update(['backend' => $p->getBkId()]);\n }\n // Password Policies\n $config = $ost->getConfig();\n foreach (PasswordPolicy::allActivePolicies() as $p) {\n if ($config->get('agent_passwd_policy') == $p::$id)\n $config->set('agent_passwd_policy', $p->getBkId());\n if ($config->get('client_passwd_policy') == $p::$id)\n $config->set('client_passwd_policy', $p->getBkId());\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_osTicket", "language": "php"} {"function": "protected function forwardEntityInformations()\n {\n /** @var \\DBmysql $DB */\n global $DB;\n\n if (!isset($this->fields['id']) || !($this->fields['id'] >= 0)) {\n return false;\n }\n\n if (count(static::$forward_entity_to)) {\n foreach (static::$forward_entity_to as $type) {\n $item = new $type();\n $query = [\n 'SELECT' => ['id'],\n 'FROM' => $item->getTable()\n ];\n\n $OR = [];\n if ($item->isField('itemtype')) {\n $OR[] = [\n 'itemtype' => $this->getType(),\n 'items_id' => $this->getID()\n ];\n }\n if ($item->isField($this->getForeignKeyField())) {\n $OR[] = [$this->getForeignKeyField() => $this->getID()];\n }\n $query['WHERE'][] = ['OR' => $OR];\n\n $input = [\n 'entities_id' => $this->getEntityID(),\n '_transfer' => 1\n ];\n if ($this->maybeRecursive()) {\n $input['is_recursive'] = $this->isRecursive();\n }\n\n $iterator = $DB->request($query);\n foreach ($iterator as $data) {\n $input['id'] = $data['id'];\n // No history for such update\n $item->update($input, 0);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function prepareInput($input)\n {\n $error_detected = [];\n\n //check for requirements\n if ($this->isNewItem()) {\n if (!isset($input['pdus_id'])) {\n $error_detected[] = __('A pdu is required');\n }\n\n if (!isset($input['racks_id'])) {\n $error_detected[] = __('A rack is required');\n }\n\n if (!isset($input['position'])) {\n $error_detected[] = __('A position is required');\n }\n\n if (!isset($input['side'])) {\n $error_detected[] = __('A side is required');\n }\n }\n\n $pdus_id = $input['pdus_id'] ?? $this->fields['pdus_id'] ?? null;\n $racks_id = $input['racks_id'] ?? $this->fields['racks_id'] ?? null;\n $position = $input['position'] ?? $this->fields['position'] ?? 0;\n $side = $input['side'] ?? $this->fields['side'] ?? null;\n\n if (!count($error_detected)) {\n //check if required U are available at position\n $required_units = 1;\n\n $rack = new Rack();\n $rack->getFromDB($racks_id);\n\n $pdu = new PDU();\n $pdu->getFromDB($pdus_id);\n\n $filled = self::getFilled($rack, $side);\n\n $model = new PDUModel();\n if ($model->getFromDB($pdu->fields['pdumodels_id'])) {\n if ($model->fields['required_units'] > 1) {\n $required_units = (int)$model->fields['required_units'];\n }\n }\n\n if (\n in_array($side, [self::SIDE_LEFT, self::SIDE_RIGHT])\n && ($position > $rack->fields['number_units']\n || $position + $required_units > (int)$rack->fields['number_units'] + 1)\n ) {\n $error_detected[] = __('Item is out of rack bounds');\n } else {\n for ($i = 0; $i < $required_units; $i++) {\n if (\n $filled[$position + $i] > 0\n && $filled[$position + $i] != $pdus_id\n ) {\n $error_detected[] = __('Not enough space available to place item');\n break;\n }\n }\n }\n }\n\n if (count($error_detected)) {\n foreach ($error_detected as $error) {\n Session::addMessageAfterRedirect(\n htmlescape($error),\n true,\n ERROR\n );\n }\n return false;\n }\n\n return $input;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getResult(): ScorePartResult\n {\n global $mathfuncs;\n\n $scorePartResult = new ScorePartResult();\n\n $RND = $this->scoreQuestionParams->getRandWrapper();\n $options = $this->scoreQuestionParams->getVarsForScorePart();\n $qn = $this->scoreQuestionParams->getQuestionNumber();\n $givenans = $this->scoreQuestionParams->getGivenAnswer();\n $multi = $this->scoreQuestionParams->getIsMultiPartQuestion();\n $partnum = $this->scoreQuestionParams->getQuestionPartNumber();\n $isRescore = $this->scoreQuestionParams->getIsRescore();\n\n $defaultreltol = .0015;\n\n $optionkeys = ['answer', 'noshuffle'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum);\n }\n $optionkeys = ['questions', 'partialcredit'];\n foreach ($optionkeys as $optionkey) {\n ${$optionkey} = getOptionVal($options, $optionkey, $multi, $partnum, 2);\n }\n\n if (!empty($partialcredit)) {\n if (!is_array($partialcredit)) {\n $partialcredit = explode(',',$partialcredit);\n }\n $creditweight = array();\n for ($i=0;$i<count($partialcredit);$i+=2) {\n $creditweight[$partialcredit[$i]] = floatval($partialcredit[$i+1]);\n }\n }\n\n if (!is_array($questions)) {\n echo _('Eeek! $questions is not defined or needs to be an array. Make sure $questions is defined in the Common Control section.');\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n if ($multi) { $qn = ($qn+1)*1000+$partnum; }\n\n if ($noshuffle == \"last\") {\n $randkeys = (array) $RND->array_rand(array_slice($questions,0,count($questions)-1),count($questions)-1);\n $RND->shuffle($randkeys);\n array_push($randkeys,count($questions)-1);\n } else if ($noshuffle == \"all\") {\n $randkeys = array_keys($questions);\n } else if (strlen($noshuffle)>4 && substr($noshuffle,0,4)==\"last\") {\n $n = intval(substr($noshuffle,4));\n if ($n>count($questions)) {\n $n = count($questions);\n }\n $randkeys = (array) $RND->array_rand(array_slice($questions,0,count($questions)-$n),count($questions)-$n);\n $RND->shuffle($randkeys);\n for ($i=count($questions)-$n;$i<count($questions);$i++) {\n array_push($randkeys,$i);\n }\n } else {\n $randkeys = (array) $RND->array_rand($questions,count($questions));\n $RND->shuffle($randkeys);\n }\n\n if ($givenans==='NA' || $givenans === null || $givenans === '' || $isRescore) {\n $scorePartResult->setLastAnswerAsGiven($givenans);\n } else {\n $scorePartResult->setLastAnswerAsGiven($randkeys[$givenans]);\n }\n\n if (isset($GLOBALS['CFG']['hooks']['assess2/questions/scorepart/choices_score_part'])) {\n require_once $GLOBALS['CFG']['hooks']['assess2/questions/scorepart/choices_score_part'];\n if (isset($onGetResult) && is_callable($onGetResult)) {\n $onGetResult();\n }\n }\n\n if ($givenans ==='NA' || $givenans === null || $givenans === '') {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n\n $anss = explode(' or ',$answer);\n foreach ($anss as $k=>$v) {\n $anss[$k] = intval($v);\n }\n //if ($randkeys[$givenans] == $answer) {return 1;} else { return 0;}\n $adjGiven = ($isRescore || !isset($randkeys[$givenans])) ? $givenans : $randkeys[$givenans];\n\n if (in_array($adjGiven,$anss)) {\n $scorePartResult->setRawScore(1);\n return $scorePartResult;\n } else if (!empty($partialcredit) && !empty($creditweight[$adjGiven])) {\n $scorePartResult->setRawScore($creditweight[$adjGiven]);\n return $scorePartResult;\n } else {\n $scorePartResult->setRawScore(0);\n return $scorePartResult;\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function createUrl(\n $route_id,\n $id_lang = null,\n array $params = array(),\n $force_routes = false,\n $anchor = '',\n $id_shop = null\n ) {\n if ($id_lang === null) {\n $id_lang = (int) Context::getContext()->language->id;\n }\n if ($id_shop === null) {\n $id_shop = (int) Context::getContext()->shop->id;\n }\n\n if (!isset($this->routes[$id_shop])) {\n $this->loadRoutes($id_shop);\n }\n\n if (!isset($this->routes[$id_shop][$id_lang][$route_id])) {\n $query = http_build_query($params, '', '&');\n $index_link = $this->use_routes ? '' : 'index.php';\n\n return ($route_id == 'index') ? $index_link . (($query) ? '?' . $query : '') :\n ((trim($route_id) == '') ? '' : 'index.php?controller=' . $route_id) . (($query) ? '&' . $query : '') . $anchor;\n }\n $route = $this->routes[$id_shop][$id_lang][$route_id];\n // Check required fields\n $query_params = isset($route['params']) ? $route['params'] : array();\n foreach ($route['keywords'] as $key => $data) {\n if (!$data['required']) {\n continue;\n }\n\n if (!array_key_exists($key, $params)) {\n throw new PrestaShopException('Dispatcher::createUrl() miss required parameter \"' .\n $key . '\" for route \"' . $route_id . '\"');\n }\n if (isset($this->default_routes[$route_id])) {\n $query_params[$this->default_routes[$route_id]['keywords'][$key]['param']] = $params[$key];\n }\n }\n\n // Build an url which match a route\n if ($this->use_routes || $force_routes) {\n $url = $route['rule'];\n $add_param = array();\n\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key])) {\n if (!isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_param[$key] = $value;\n }\n } else {\n if ($params[$key]) {\n $replace = $route['keywords'][$key]['prepend'] . $params[$key] . $route['keywords'][$key]['append'];\n } else {\n $replace = '';\n }\n $url = preg_replace('#\\{([^{}]*:)?' . $key . '(:[^{}]*)?\\}#', $replace, $url);\n }\n }\n $url = preg_replace('#\\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\\}#', '', $url);\n if (count($add_param)) {\n $url .= '?' . http_build_query($add_param, '', '&');\n }\n } else {\n // Build a classic url index.php?controller=foo&...\n $add_params = array();\n foreach ($params as $key => $value) {\n if (!isset($route['keywords'][$key]) && !isset($this->default_routes[$route_id]['keywords'][$key])) {\n $add_params[$key] = $value;\n }\n }\n\n if (!empty($route['controller'])) {\n $query_params['controller'] = $route['controller'];\n }\n $query = http_build_query(array_merge($add_params, $query_params), '', '&');\n if ($this->multilang_activated) {\n $query .= (!empty($query) ? '&' : '') . 'id_lang=' . (int) $id_lang;\n }\n $url = 'index.php?' . $query;\n }\n\n return $url . $anchor;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function postProcess(string $eventName): void\n {\n unset($this->wrappedListeners[$eventName]);\n $skipped = false;\n foreach ($this->dispatcher->getListeners($eventName) as $listener) {\n if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.\n continue;\n }\n // Unwrap listener\n $priority = $this->getListenerPriority($eventName, $listener);\n $this->dispatcher->removeListener($eventName, $listener);\n $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);\n\n if (null !== $this->logger) {\n $context = ['event' => $eventName, 'listener' => $listener->getPretty()];\n }\n\n if ($listener->wasCalled()) {\n if (null !== $this->logger) {\n $this->logger->debug('Notified event \"{event}\" to listener \"{listener}\".', $context);\n }\n } else {\n $this->callStack->detach($listener);\n }\n\n if (null !== $this->logger && $skipped) {\n $this->logger->debug('Listener \"{listener}\" was not called for event \"{event}\".', $context);\n }\n\n if ($listener->stoppedPropagation()) {\n if (null !== $this->logger) {\n $this->logger->debug('Listener \"{listener}\" stopped propagation of the event \"{event}\".', $context);\n }\n\n $skipped = true;\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function updateStorage(StorageConfig $updatedStorage) {\n\t\t$id = $updatedStorage->getId();\n\n\t\t$existingMount = $this->dbConfig->getMountById($id);\n\n\t\tif (!is_array($existingMount)) {\n\t\t\tthrow new NotFoundException('Storage with ID \"' . $id . '\" not found while updating storage');\n\t\t}\n\n\t\t$oldStorage = $this->getStorageConfigFromDBMount($existingMount);\n\n\t\tif ($oldStorage->getBackend() instanceof InvalidBackend) {\n\t\t\tthrow new NotFoundException('Storage with id \"' . $id . '\" cannot be edited due to missing backend');\n\t\t}\n\n\t\t$removedUsers = array_diff($oldStorage->getApplicableUsers(), $updatedStorage->getApplicableUsers());\n\t\t$removedGroups = array_diff($oldStorage->getApplicableGroups(), $updatedStorage->getApplicableGroups());\n\t\t$addedUsers = array_diff($updatedStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());\n\t\t$addedGroups = array_diff($updatedStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());\n\n\t\t$oldUserCount = count($oldStorage->getApplicableUsers());\n\t\t$oldGroupCount = count($oldStorage->getApplicableGroups());\n\t\t$newUserCount = count($updatedStorage->getApplicableUsers());\n\t\t$newGroupCount = count($updatedStorage->getApplicableGroups());\n\t\t$wasGlobal = ($oldUserCount + $oldGroupCount) === 0;\n\t\t$isGlobal = ($newUserCount + $newGroupCount) === 0;\n\n\t\tforeach ($removedUsers as $user) {\n\t\t\t$this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);\n\t\t}\n\t\tforeach ($removedGroups as $group) {\n\t\t\t$this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);\n\t\t}\n\t\tforeach ($addedUsers as $user) {\n\t\t\t$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);\n\t\t}\n\t\tforeach ($addedGroups as $group) {\n\t\t\t$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);\n\t\t}\n\n\t\tif ($wasGlobal && !$isGlobal) {\n\t\t\t$this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);\n\t\t} elseif (!$wasGlobal && $isGlobal) {\n\t\t\t$this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);\n\t\t}\n\n\t\t$changedConfig = array_diff_assoc($updatedStorage->getBackendOptions(), $oldStorage->getBackendOptions());\n\t\t$changedOptions = array_diff_assoc($updatedStorage->getMountOptions(), $oldStorage->getMountOptions());\n\n\t\tforeach ($changedConfig as $key => $value) {\n\t\t\tif ($value !== DefinitionParameter::UNMODIFIED_PLACEHOLDER) {\n\t\t\t\t$this->dbConfig->setConfig($id, $key, $value);\n\t\t\t}\n\t\t}\n\t\tforeach ($changedOptions as $key => $value) {\n\t\t\t$this->dbConfig->setOption($id, $key, $value);\n\t\t}\n\n\t\tif ($updatedStorage->getMountPoint() !== $oldStorage->getMountPoint()) {\n\t\t\t$this->dbConfig->setMountPoint($id, $updatedStorage->getMountPoint());\n\t\t}\n\n\t\tif ($updatedStorage->getAuthMechanism()->getIdentifier() !== $oldStorage->getAuthMechanism()->getIdentifier()) {\n\t\t\t$this->dbConfig->setAuthBackend($id, $updatedStorage->getAuthMechanism()->getIdentifier());\n\t\t}\n\n\t\t$this->triggerChangeHooks($oldStorage, $updatedStorage);\n\n\t\tif (($wasGlobal && !$isGlobal) || count($removedGroups) > 0) { // to expensive to properly handle these on the fly\n\t\t\t$this->userMountCache->remoteStorageMounts($this->getStorageId($updatedStorage));\n\t\t} else {\n\t\t\t$storageId = $this->getStorageId($updatedStorage);\n\t\t\tforeach ($removedUsers as $userId) {\n\t\t\t\t$this->userMountCache->removeUserStorageMount($storageId, $userId);\n\t\t\t}\n\t\t}\n\n\t\treturn $this->getStorage($id);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function display()\n {\n Tools::safePostVars();\n\n // assign css_files and js_files at the very last time\n if ((Configuration::get('PS_CSS_THEME_CACHE') || Configuration::get('PS_JS_THEME_CACHE')) && is_writable(_PS_THEME_DIR_.'cache')) {\n // CSS compressor management\n if (Configuration::get('PS_CSS_THEME_CACHE')) {\n $this->css_files = Media::cccCss($this->css_files);\n }\n //JS compressor management\n if (Configuration::get('PS_JS_THEME_CACHE') && !$this->useMobileTheme()) {\n $this->js_files = Media::cccJs($this->js_files);\n }\n }\n\n $this->context->smarty->assign(array(\n 'css_files' => $this->css_files,\n 'js_files' => ($this->getLayout() && (bool)Configuration::get('PS_JS_DEFER')) ? array() : $this->js_files,\n 'js_defer' => (bool)Configuration::get('PS_JS_DEFER'),\n 'errors' => $this->errors,\n 'display_header' => $this->display_header,\n 'display_footer' => $this->display_footer,\n ));\n\n $layout = $this->getLayout();\n if ($layout) {\n if ($this->template) {\n $template = $this->context->smarty->fetch($this->template);\n } else {\n // For retrocompatibility with 1.4 controller\n\n ob_start();\n $this->displayContent();\n $template = ob_get_contents();\n ob_clean();\n }\n $this->context->smarty->assign('template', $template);\n $this->smartyOutputContent($layout);\n } else {\n Tools::displayAsDeprecated('layout.tpl is missing in your theme directory');\n if ($this->display_header) {\n $this->smartyOutputContent(_PS_THEME_DIR_.'header.tpl');\n }\n\n if ($this->template) {\n $this->smartyOutputContent($this->template);\n } else { // For retrocompatibility with 1.4 controller\n $this->displayContent();\n }\n\n if ($this->display_footer) {\n $this->smartyOutputContent(_PS_THEME_DIR_.'footer.tpl');\n }\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "protected function _execute($aggregationUnit)\n {\n $time_start = microtime(true);\n\n $this->logger->notice(array(\n \"message\" => \"aggregate start\",\n \"action\" => (string) $this,\n \"unit\" => $aggregationUnit,\n \"start_date\" => ( null === $this->currentStartDate ? \"none\" : $this->currentStartDate ),\n \"end_date\" => ( null === $this->currentEndDate ? \"none\" : $this->currentEndDate )\n ));\n\n // Batching options\n\n\n // Get the list of periods that need to be aggregated\n $aggregationPeriodList = $this->getDirtyAggregationPeriods($aggregationUnit);\n $numAggregationPeriods = count($aggregationPeriodList);\n $firstPeriod = current($aggregationPeriodList);\n\n // There are instances where $firstPeriod is a bool not an array ( when $aggregationPeriodList is empty or at the end of the array)\n // the following code takes that into account.\n $periodSize = 0;\n if (!is_bool($firstPeriod)) {\n $periodSize = $firstPeriod['period_end_day_id'] - $firstPeriod['period_start_day_id'];\n }\n\n $batchSliceSize = $this->options->batch_aggregation_periods_per_batch;\n $tmpTableName = null;\n $qualifiedTmpTableName = null;\n\n // If aggregation batching is enabled, calculate whether or not it is beneficial using the\n // following formula derrived from trial and error:\n //\n // Nperiod = # periods to process = $numAggregationPeriods\n // Psize = # days per period = $period['period_end_day_id'] - $period['period_start_day_id']\n // Bsize = # Periods per batch = $this->options->batch_aggregation_periods_per_bin\n // Threshold1 = $this->options->batch_aggregation_min_num_periods = 25\n // Threshold2 = $this->options->batch_aggregation_max_num_days_per_batch = 300\n //\n // Enable = ( Nperiod >= Threshold1 (25) ) && ( Psize * Bsize <= Threshold2 (300) )\n\n $enableBatchAggregation =\n $this->options->enable_batch_aggregation\n && $numAggregationPeriods >= $this->options->batch_aggregation_min_num_periods\n && ($periodSize * $batchSliceSize) <= $this->options->batch_aggregation_max_num_days_per_batch;\n\n $this->logger->debug(\"Enable batch aggregation: \" . ($enableBatchAggregation ? \"true\" : \"false\"));\n\n if ( $enableBatchAggregation ) {\n $tmpTableName = self::BATCH_TMP_TABLE_NAME;\n $qualifiedTmpTableName = $this->sourceEndpoint->getSchema(true) . \".\" . $this->sourceEndpoint->quoteSystemIdentifier($tmpTableName);\n }\n\n if ( $enableBatchAggregation && ! $this->etlSourceQueryModified ) {\n\n $this->logger->info(\"[batch aggregation] Replace first table with temp table\");\n\n // Optimize for large numbers of periods. Modify the source query to use the temporary table\n // Remove the first join (from) and replace it with the temporary table that we are\n // going to create\n\n $sourceJoins = $this->etlSourceQuery->joins;\n $firstJoin = array_shift($sourceJoins);\n $newFirstJoin = clone $firstJoin;\n $newFirstJoin->name = $tmpTableName;\n $newFirstJoin->schema = $this->sourceEndpoint->getSchema();\n\n $this->etlSourceQuery->joins = array($newFirstJoin);\n foreach ( $sourceJoins as $join ) {\n $this->etlSourceQuery->addJoin($join);\n }\n $this->etlSourceQueryModified = true;\n\n } elseif ( ! $enableBatchAggregation && $this->etlSourceQueryModified ) {\n\n $this->logger->info(\"[batch aggregation] Restore original first table\");\n\n // We are not optimizing but have previously, restore the original FROM clause\n\n $sourceJoins = $this->etlSourceQuery->joins;\n array_shift($sourceJoins);\n $this->etlSourceQuery->joins = array($this->etlSourceQueryOrigFromTable);\n foreach ( $sourceJoins as $join ) {\n $this->etlSourceQuery->addJoin($join);\n }\n $this->etlSourceQueryModified = false;\n } // else ( $enableBatchAggregation && ! $this->etlSourceQueryModified )\n\n $this->buildSqlStatements($aggregationUnit);\n\n // ------------------------------------------------------------------------------------------\n // Set up the select and insert statements used for aggregation and determine if we can\n // optimized the operation.\n\n $bindParamRegex = '/(:[a-zA-Z0-9_-]+)/';\n $discoveredBindParams = array();\n\n $selectStmt = null;\n $insertStmt = null;\n\n $optimize = $this->allowSingleDatabaseOptimization();\n\n $this->executeSqlList(array(\n \"SET SESSION sql_mode = CONCAT('ONLY_FULL_GROUP_BY,',@@SESSION.sql_mode)\"\n ), $this->sourceEndpoint);\n\n if ( $optimize ) {\n\n $this->logger->info(\"Allowing same-server SQL optimizations\");\n\n try {\n $insertStmt = $this->destinationHandle->prepare($this->optimizedInsertSql);\n } catch (PDOException $e) {\n $this->logAndThrowException(\n \"Error preparing optimized aggregation insert statement\",\n array('exception' => $e, 'sql' => $this->optimizedInsertSql)\n );\n }\n\n // Detect the bind variables used in the query so we can filter these later. PDO will\n // throw an error if there are unused bind variables.\n\n $matches = array();\n preg_match_all($bindParamRegex, $this->optimizedInsertSql, $matches);\n $discoveredBindParams['insert'] = array_unique($matches[0]);\n\n $this->logger->debug(\"Aggregation optimized INSERT SQL ($aggregationUnit) \" . $this->destinationEndpoint . \":\\n\" . $this->optimizedInsertSql);\n\n } else {\n\n try {\n $selectStmt = $this->sourceHandle->prepare($this->selectSql);\n } catch (PDOException $e) {\n $this->logAndThrowException(\n \"Error preparing aggregation select statement\",\n array('exception' => $e, 'sql' => $this->selectSql)\n );\n }\n\n try {\n $insertStmt = $this->destinationHandle->prepare($this->insertSql);\n } catch (PDOException $e) {\n $this->logAndThrowException(\n \"Error preparing aggregation insert statement\",\n array('exception' => $e, 'sql' => $this->insertSql)\n );\n }\n\n // Detect the bind variables used in the query so we can filter these later. PDO will\n // throw an error if there are unused bind variables.\n\n $matches = array();\n preg_match_all($bindParamRegex, $this->selectSql, $matches);\n $discoveredBindParams['select'] = $matches[0];\n preg_match_all($bindParamRegex, $this->insertSql, $matches);\n $discoveredBindParams['insert'] = $matches[0];\n\n $this->logger->debug(\"Aggregation SELECT SQL ($aggregationUnit) \" . $this->sourceEndpoint . \":\\n\" . $this->selectSql);\n $this->logger->debug(\"Aggregation INSERT SQL ($aggregationUnit) \" . $this->destinationEndpoint . \":\\n\" . $this->insertSql);\n\n } // else ($optimize)\n\n // --------------------------------------------------------------------------------\n // Iterate over each aggregation period that we are processing.\n //\n // NOTE: The ETL date range is supported when querying for dirty aggregation periods\n\n $this->logger->info(\"Aggregate over $numAggregationPeriods ${aggregationUnit}s\");\n\n if ( ! $enableBatchAggregation ) {\n\n $this->processAggregationPeriods(\n $aggregationUnit,\n $aggregationPeriodList,\n $selectStmt,\n $insertStmt,\n $discoveredBindParams,\n $numAggregationPeriods\n );\n\n } else {\n\n $aggregationPeriodListOffset = 0;\n $done = false;\n\n $sourceJoins = $this->etlSourceQuery->joins;\n $firstJoin = current($sourceJoins);\n $tmpTableAlias = $firstJoin->alias;\n\n while ( ! $done ) {\n\n // Process the aggregation periods in batches\n\n $this->logger->debug(\"[batch aggregation] Processing batch offset $aggregationPeriodListOffset - \" . ($aggregationPeriodListOffset + $batchSliceSize));\n\n $batchStartTime = microtime(true);\n\n $aggregationPeriodSlice = array_slice($aggregationPeriodList, $aggregationPeriodListOffset, $batchSliceSize);\n if ( count($aggregationPeriodSlice) == 0 ) {\n break;\n }\n\n // Is this the last slice?\n $done = ( count($aggregationPeriodSlice) < $batchSliceSize );\n\n // Find the min/max time range and day id for this slice so we know which jobs to\n // include in the temporary table.\n\n $firstSlice = current($aggregationPeriodSlice);\n $lastSlice = end($aggregationPeriodSlice);\n reset($aggregationPeriodSlice);\n\n // Note that slices are ordered newest to oldest\n\n $minDayId = $lastSlice['period_start_day_id'];\n $maxDayId = $firstSlice['period_end_day_id'];\n $minPeriodId = $lastSlice['period_id'];\n $maxPeriodId = $firstSlice['period_id'];\n\n // Set up the temporary table that we are going to use\n\n $this->logger->debug(\"[batch aggregation] Create temporary table $qualifiedTmpTableName with min period = $minDayId, max period = $maxDayId\");\n\n $sql = \"DROP TEMPORARY TABLE IF EXISTS $qualifiedTmpTableName\";\n\n try {\n $result = $this->sourceHandle->execute($sql);\n } catch (PDOException $e ) {\n $this->logAndThrowException(\n \"Error removing temporary batch aggregation table\",\n array('exception' => $e, 'sql' => $sql)\n );\n }\n\n $origTableName =\n $this->sourceEndpoint->getSchema(true)\n . \".\"\n . $this->sourceEndpoint->quoteSystemIdentifier($this->etlSourceQueryOrigFromTable->name);\n\n try {\n // Use the where clause from the aggregation query to create the temporary table\n\n $whereClause = $this->variableStore->substitute(\n implode(\" AND \", $this->etlSourceQuery->where),\n \"Undefined macros found in WHERE clause\"\n );\n\n // A subset of the bind variables are available. We should check to see if there\n // are more that we can't handle.\n\n // We are taking the WHERE clause from source query so we need to\n // support all bind parameters available to that query. Min and max\n // information will need to come from the last and first slice,\n // respecitively (see note below).\n\n $availableParamKeys = Utilities::createPdoBindVarsFromArrayKeys($firstSlice);\n\n // NOTE 1\n //\n // The aggregation periods are supplied in reverse order so newer\n // periods are processed first. This means we need to invert the\n // start/end slices.\n //\n // NOTE 2\n //\n // Since the WHERE clause was meant to be used with a SINGLE\n // aggregation period, parameters such as period_hours and\n // period_seconds are not summed and chosen arbitrarily from one of\n // the periods. Similarly, period_id and period_value are chosen\n // arbitrarily.\n\n $availableParamValues = array_map(\n function ($k, $first, $last) {\n if ( false !== strpos($k, '_end') || false !== strpos($k, 'end_') ) {\n return $first;\n } else {\n return $last;\n }\n },\n array_keys($firstSlice),\n $firstSlice,\n $lastSlice\n );\n\n $availableParams = array_combine($availableParamKeys, $availableParamValues);\n\n $bindParams = array();\n preg_match_all($bindParamRegex, $whereClause, $matches);\n $bindParams = $matches[0];\n $usedParams = array_intersect_key($availableParams, array_fill_keys($bindParams, 0));\n\n $sql =\n \"CREATE TEMPORARY TABLE $qualifiedTmpTableName AS \"\n . \"SELECT * FROM $origTableName $tmpTableAlias WHERE \" . $whereClause;\n $this->logger->debug(\n sprintf(\"[batch aggregation] Batch temp table %s: %s\", $this->sourceEndpoint, $sql)\n );\n $result = $this->sourceHandle->execute($sql, $usedParams);\n } catch (PDOException $e ) {\n $this->logAndThrowException(\n \"Error creating temporary batch aggregation table\",\n array('exception' => $e, 'sql' => $sql)\n );\n }\n\n $this->logger->info(\"[batch aggregation] Setup for batch $minPeriodId - $maxPeriodId (day_id $minDayId - $maxDayId): \"\n . round((microtime(true) - $batchStartTime), 2) . \"s\");\n\n $this->processAggregationPeriods(\n $aggregationUnit,\n $aggregationPeriodSlice,\n $selectStmt,\n $insertStmt,\n $discoveredBindParams,\n $numAggregationPeriods,\n $aggregationPeriodListOffset\n );\n\n $this->logger->info(\n \"[batch aggregation] Total time for batch (day_id $minDayId - $maxDayId): \"\n . round((microtime(true) - $batchStartTime), 2) . \"s \"\n . \"(\" . round((microtime(true) - $batchStartTime) / count($aggregationPeriodSlice), 3) . \"s/period)\"\n );\n\n $aggregationPeriodListOffset += $batchSliceSize;\n\n } // while ( ! $done )\n\n $sql = \"DROP TEMPORARY TABLE IF EXISTS $tmpTableName\";\n\n try {\n $result = $this->sourceHandle->execute($sql);\n } catch (PDOException $e ) {\n $this->logAndThrowException(\n \"Error removing temporary batch aggregation table\",\n array('exception' => $e, 'sql' => $sql)\n );\n }\n\n } // else ( ! $enableBatchAggregation )\n\n $time_end = microtime(true);\n $time = $time_end - $time_start;\n\n $this->logger->notice(array(\"message\" => \"aggregate end\",\n \"action\" => (string) $this,\n \"unit\" => $aggregationUnit,\n \"periods\" => $numAggregationPeriods,\n \"start_date\" => ( null === $this->currentStartDate ? \"none\" : $this->currentStartDate ),\n \"end_date\" => ( null === $this->currentEndDate ? \"none\" : $this->currentEndDate ),\n \"start_time\" => $time_start,\n \"end_time\" => $time_end,\n \"elapsed_time\" => round($time, 5)\n ));\n\n return $numAggregationPeriods;\n\n }", "smellKey": "S3776", "smellId": null, "repo": "ubccr_xdmod", "language": "php"} {"function": "protected static function checkDiscovery(Device $device, array $array, $mibdir): bool\n {\n // all items must be true\n foreach ($array as $key => $value) {\n if ($check = Str::endsWith($key, '_except')) {\n $key = substr($key, 0, -7);\n }\n\n if ($key == 'sysObjectID') {\n if (Str::startsWith($device['sysObjectID'] ?? '', $value) == $check) {\n return false;\n }\n } elseif ($key == 'sysDescr') {\n if (Str::contains($device['sysDescr'] ?? '', $value) == $check) {\n return false;\n }\n } elseif ($key == 'sysDescr_regex') {\n if (preg_match_any($device['sysDescr'] ?? '', $value) == $check) {\n return false;\n }\n } elseif ($key == 'sysObjectID_regex') {\n if (preg_match_any($device['sysObjectID'] ?? '', $value) == $check) {\n return false;\n }\n } elseif ($key == 'snmpget') {\n $get_value = SnmpQuery::device($device)\n ->options($value['options'] ?? null)\n ->mibDir($value['mib_dir'] ?? $mibdir)\n ->get(isset($value['mib']) ? \"{$value['mib']}::{$value['oid']}\" : $value['oid'])\n ->value();\n if (Compare::values($get_value, $value['value'], $value['op'] ?? 'contains') == $check) {\n return false;\n }\n } elseif ($key == 'snmpwalk') {\n $walk_value = SnmpQuery::device($device)\n ->options($value['options'] ?? null)\n ->mibDir($value['mib_dir'] ?? $mibdir)\n ->walk(isset($value['mib']) ? \"{$value['mib']}::{$value['oid']}\" : $value['oid'])\n ->raw;\n if (Compare::values($walk_value, $value['value'], $value['op'] ?? 'contains') == $check) {\n return false;\n }\n }\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "config-services_librenms", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['target'])) {\n if (is_array($data['target'])) {\n foreach ($data['target'] as $d) {\n $this->addTarget($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"target\" must be array of objects or null, ' . gettype($data['target']) . ' seen.');\n }\n }\n if (isset($data['targetLocation'])) {\n if (is_array($data['targetLocation'])) {\n foreach ($data['targetLocation'] as $d) {\n $this->addTargetLocation($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"targetLocation\" must be array of objects or null, ' . gettype($data['targetLocation']) . ' seen.');\n }\n }\n if (isset($data['need'])) {\n $this->setNeed($data['need']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['statusDate'])) {\n $this->setStatusDate($data['statusDate']);\n }\n if (isset($data['validationType'])) {\n $this->setValidationType($data['validationType']);\n }\n if (isset($data['validationProcess'])) {\n if (is_array($data['validationProcess'])) {\n foreach ($data['validationProcess'] as $d) {\n $this->addValidationProcess($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"validationProcess\" must be array of objects or null, ' . gettype($data['validationProcess']) . ' seen.');\n }\n }\n if (isset($data['frequency'])) {\n $this->setFrequency($data['frequency']);\n }\n if (isset($data['lastPerformed'])) {\n $this->setLastPerformed($data['lastPerformed']);\n }\n if (isset($data['nextScheduled'])) {\n $this->setNextScheduled($data['nextScheduled']);\n }\n if (isset($data['failureAction'])) {\n $this->setFailureAction($data['failureAction']);\n }\n if (isset($data['primarySource'])) {\n if (is_array($data['primarySource'])) {\n foreach ($data['primarySource'] as $d) {\n $this->addPrimarySource($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"primarySource\" must be array of objects or null, ' . gettype($data['primarySource']) . ' seen.');\n }\n }\n if (isset($data['attestation'])) {\n $this->setAttestation($data['attestation']);\n }\n if (isset($data['validator'])) {\n if (is_array($data['validator'])) {\n foreach ($data['validator'] as $d) {\n $this->addValidator($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"validator\" must be array of objects or null, ' . gettype($data['validator']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function lineboundarycoord($xmin,$xmax,$ymin,$ymax,$m,$b,$order=array(\"right\",\"top\",\"left\",\"bottom\")) {\n\tforeach ($order as $ord) {\n\t\tif ($ord=='right') {\n\t\t\t$yr = $m*$xmax+$b;\n\t\t\tif ($yr<=$ymax && $yr >= $ymin) {\n\t\t\t\treturn array($xmax,$yr,($m>0)?\"aboveleft\":\"belowleft\");\n\t\t\t}\n\t\t} else if ($ord=='top' && $m!=0) {\n\t\t\t$xt = ($ymax - $b)/$m;\n\t\t\tif ($xt<=$xmax && $xt >= $xmin) {\n\t\t\t\treturn array($xt,$ymax,($m>0)?\"belowright\":\"belowleft\");\n\t\t\t}\n\t\t} else if ($ord=='left') {\n\t\t\t$yl = $m*$xmin+$b;\n\t\t\tif ($yl<=$ymax && $yl >= $ymin) {\n\t\t\t\treturn array($xmin,$yl,($m>0)?\"belowright\":\"aboveright\");\n\t\t\t}\n\t\t} else if ($ord=='bottom' && $m!=0) {\n\t\t\t$xb = ($ymin - $b)/$m;\n\t\t\tif ($xb<=$xmax && $xb >= $xmin) {\n\t\t\t\treturn array($xb,$ymin,($m>0)?\"aboveleft\":\"aboveright\");\n\t\t\t}\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function getDefaultKeyBindings(Pimcore\\Model\\User|UserProxy|null $user = null): string\n {\n if ($user instanceof Pimcore\\Model\\User && $user->getKeyBindings()) {\n return $user->getKeyBindings();\n }\n\n $defaultKeyBindings = [];\n $container = Pimcore::getContainer();\n $userConfig = $container->getParameter('pimcore_admin.user');\n // make sure the default key binding node is in the config\n if (is_array($userConfig) && array_key_exists(self::DEFAULT_KEY_BINDINGS, $userConfig)) {\n $defaultKeyBindingsConfig = $userConfig[self::DEFAULT_KEY_BINDINGS];\n if (!empty($defaultKeyBindingsConfig)) {\n foreach ($defaultKeyBindingsConfig as $keys) {\n $defaultKeyBinding = [];\n // we do not check if the keys are empty because key is required\n foreach ($keys as $index => $value) {\n if ($index === 'key') {\n $value = ord($value);\n }\n $defaultKeyBinding[$index] = $value;\n }\n $defaultKeyBindings[] = $defaultKeyBinding;\n }\n }\n }\n\n return json_encode($defaultKeyBindings);\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function inepHeadSchool($value, $offer_or_linked_unity, $current_inep_id,\n $head_school_situation, $head_of_head_school)\n {\n if ($offer_or_linked_unity == '1') {\n if ($value == \"\" && $value == null) {\n return array(\"status\" => false, \"erro\" => \"O campo n\u00e3o foi preenchido quando deveria ser preenchido.\");\n }\n if (!is_numeric($value)) {\n return array(\"status\" => false, \"erro\" => \"Apenas n\u00fameros s\u00e3o permitidos\");\n }\n if (strlen($value) != 8) {\n return array(\"status\" => false, \"erro\" => \"Deve conter 8 caracteres\");\n }\n if ($value == $current_inep_id) {\n return array(\"status\" => false, \"erro\" => \"N\u00e3o pode ser preenchido com o mesmo c\u00f3digo INEP da escola.\");\n }\n if ($head_school_situation != '1') {\n return array(\"status\" => false, \"erro\" => \"Escola sede n\u00e3o est\u00e1 em atividade\");\n }\n if (substr($current_inep_id, 0, 2) != substr($value, 0, 2)) {\n return array(\"status\" => false, \"erro\" => \"Escolas n\u00e3o s\u00e3o do mesmo estado\");\n }\n if ($current_inep_id == $head_of_head_school) {\n return array(\"status\" => false, \"erro\" => \"Escola sede n\u00e3o pode ter atual como sede\");\n }\n\n } else {\n if ($value != null) {\n return array(\"status\" => false, \"erro\" => \"Valor $value deveria ser nulo\");\n }\n }\n\n return array(\"status\" => true, \"erro\" => \"\");\n\n }", "smellKey": "S3776", "smellId": null, "repo": "ipti_br.tag", "language": "php"} {"function": "public function createGroup($gid) {\n\t\tif ($gid === '' || $gid === null) {\n\t\t\treturn null;\n\t\t} elseif ($group = $this->get($gid)) {\n\t\t\treturn $group;\n\t\t} elseif (mb_strlen($gid) > self::MAX_GROUP_LENGTH) {\n\t\t\tthrow new \\Exception('Group name is limited to '. self::MAX_GROUP_LENGTH.' characters');\n\t\t} else {\n\t\t\t$this->dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));\n\t\t\t$this->emit('\\OC\\Group', 'preCreate', [$gid]);\n\t\t\tforeach ($this->backends as $backend) {\n\t\t\t\tif ($backend->implementsActions(Backend::CREATE_GROUP)) {\n\t\t\t\t\tif ($backend instanceof ICreateNamedGroupBackend) {\n\t\t\t\t\t\t$groupName = $gid;\n\t\t\t\t\t\tif (($gid = $backend->createGroup($groupName)) !== null) {\n\t\t\t\t\t\t\t$group = $this->getGroupObject($gid);\n\t\t\t\t\t\t\t$this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));\n\t\t\t\t\t\t\t$this->emit('\\OC\\Group', 'postCreate', [$group]);\n\t\t\t\t\t\t\treturn $group;\n\t\t\t\t\t\t}\n\t\t\t\t\t} elseif ($backend->createGroup($gid)) {\n\t\t\t\t\t\t$group = $this->getGroupObject($gid);\n\t\t\t\t\t\t$this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));\n\t\t\t\t\t\t$this->emit('\\OC\\Group', 'postCreate', [$group]);\n\t\t\t\t\t\treturn $group;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (0 < count($this->identifier)) {\n $json['identifier'] = [];\n foreach ($this->identifier as $identifier) {\n $json['identifier'][] = $identifier;\n }\n }\n if (isset($this->type)) {\n $json['type'] = $this->type;\n }\n if (isset($this->coordinateSystem)) {\n $json['coordinateSystem'] = $this->coordinateSystem;\n }\n if (isset($this->patient)) {\n $json['patient'] = $this->patient;\n }\n if (isset($this->specimen)) {\n $json['specimen'] = $this->specimen;\n }\n if (isset($this->device)) {\n $json['device'] = $this->device;\n }\n if (isset($this->performer)) {\n $json['performer'] = $this->performer;\n }\n if (isset($this->quantity)) {\n $json['quantity'] = $this->quantity;\n }\n if (isset($this->referenceSeq)) {\n $json['referenceSeq'] = $this->referenceSeq;\n }\n if (0 < count($this->variant)) {\n $json['variant'] = [];\n foreach ($this->variant as $variant) {\n $json['variant'][] = $variant;\n }\n }\n if (isset($this->observedSeq)) {\n $json['observedSeq'] = $this->observedSeq;\n }\n if (0 < count($this->quality)) {\n $json['quality'] = [];\n foreach ($this->quality as $quality) {\n $json['quality'][] = $quality;\n }\n }\n if (isset($this->readCoverage)) {\n $json['readCoverage'] = $this->readCoverage;\n }\n if (0 < count($this->repository)) {\n $json['repository'] = [];\n foreach ($this->repository as $repository) {\n $json['repository'][] = $repository;\n }\n }\n if (0 < count($this->pointer)) {\n $json['pointer'] = [];\n foreach ($this->pointer as $pointer) {\n $json['pointer'][] = $pointer;\n }\n }\n if (0 < count($this->structureVariant)) {\n $json['structureVariant'] = [];\n foreach ($this->structureVariant as $structureVariant) {\n $json['structureVariant'][] = $structureVariant;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function rcopy($source, $destination, $is_rec = false)\n{\n\tif (is_dir($source))\n\t{\n\t\tif ($is_rec === false)\n\t\t{\n\t\t\t$pinfo = pathinfo($source);\n\t\t\t$destination = rtrim($destination, '/') . DIRECTORY_SEPARATOR . $pinfo['basename'];\n\t\t}\n\t\tif (is_dir($destination) === false)\n\t\t{\n\t\t\tmkdir($destination, 0755, true);\n\t\t}\n\n\t\t$files = scandir($source);\n\t\tforeach ($files as $file)\n\t\t{\n\t\t\tif ($file != \".\" && $file != \"..\")\n\t\t\t{\n\t\t\t\trcopy($source . DIRECTORY_SEPARATOR . $file, rtrim($destination, '/') . DIRECTORY_SEPARATOR . $file, true);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (file_exists($source))\n\t\t{\n\t\t\tif (is_dir($destination) === true)\n\t\t\t{\n\t\t\t\t$pinfo = pathinfo($source);\n\t\t\t\t$dest2 = rtrim($destination, '/') . DIRECTORY_SEPARATOR . $pinfo['basename'];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$dest2 = $destination;\n\t\t\t}\n\n\t\t\tcopy($source, $dest2);\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "melisplatform_melis-core", "language": "php"} {"function": "public static function getDropdownValue($post, $json = true)\n {\n /**\n * @var array $CFG_GLPI\n * @var \\DBmysql $DB\n */\n global $CFG_GLPI, $DB;\n\n // check if asked itemtype is the one originally requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }\n\n if (isset($post['entity_restrict']) && 'default' === $post['entity_restrict']) {\n $post['entity_restrict'] = $_SESSION['glpiactiveentities'];\n } elseif (\n isset($post[\"entity_restrict\"])\n && !is_array($post[\"entity_restrict\"])\n && (substr($post[\"entity_restrict\"], 0, 1) === '[')\n && (substr($post[\"entity_restrict\"], -1) === ']')\n ) {\n $decoded = Toolbox::jsonDecode($post['entity_restrict']);\n $entities = [];\n if (is_array($decoded)) {\n foreach ($decoded as $value) {\n $entities[] = (int)$value;\n }\n }\n $post[\"entity_restrict\"] = Session::getMatchingActiveEntities($entities);\n }\n\n // Security\n if (!($item = getItemForItemtype($post['itemtype']))) {\n return;\n }\n\n $table = $item->getTable();\n $datas = [];\n\n $displaywith = false;\n if (isset($post['displaywith'])) {\n if (is_array($post['displaywith']) && count($post['displaywith'])) {\n $post['displaywith'] = self::filterDisplayWith($item, $post['displaywith']);\n\n if (count($post['displaywith'])) {\n $displaywith = true;\n }\n }\n }\n\n if (!isset($post['permit_select_parent'])) {\n $post['permit_select_parent'] = false;\n }\n\n if (isset($post['condition']) && !empty($post['condition']) && !is_array($post['condition'])) {\n // Retreive conditions from SESSION using its key\n $key = $post['condition'];\n if (isset($_SESSION['glpicondition']) && isset($_SESSION['glpicondition'][$key])) {\n $post['condition'] = $_SESSION['glpicondition'][$key];\n } else {\n $post['condition'] = [];\n }\n }\n\n if (!isset($post['emptylabel']) || ($post['emptylabel'] == '')) {\n $post['emptylabel'] = Dropdown::EMPTY_VALUE;\n }\n\n $where = $item->getSystemSQLCriteria();\n\n if (Toolbox::hasTrait($post['itemtype'], AssignableItem::class)) {\n $visibility_criteria = $post['itemtype']::getAssignableVisiblityCriteria();\n if (count($visibility_criteria)) {\n $where[] = $visibility_criteria;\n }\n }\n\n if ($item->maybeDeleted()) {\n $where[\"$table.is_deleted\"] = 0;\n }\n if ($item->maybeTemplate()) {\n $where[\"$table.is_template\"] = 0;\n }\n\n if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }\n\n $start = intval(($post['page'] - 1) * $post['page_limit']);\n $limit = intval($post['page_limit']);\n\n if (isset($post['used'])) {\n $used = $post['used'];\n\n if (count($used)) {\n $where['NOT'] = [\"$table.id\" => $used];\n }\n }\n\n if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }\n\n $ljoin = [];\n\n if (isset($post['condition']) && !empty($post['condition'])) {\n if (isset($post['condition']['LEFT JOIN'])) {\n $ljoin = $post['condition']['LEFT JOIN'];\n unset($post['condition']['LEFT JOIN']);\n }\n if (isset($post['condition']['WHERE'])) {\n $where = array_merge($where, $post['condition']['WHERE']);\n } else {\n foreach ($post['condition'] as $key => $value) {\n if (!is_numeric($key) && !in_array($key, ['AND', 'OR', 'NOT']) && !str_contains($key, '.')) {\n // Ensure condition contains table name to prevent ambiguity with fields from `glpi_entities` table\n $where[\"$table.$key\"] = $value;\n } else {\n $where[$key] = $value;\n }\n }\n }\n }\n\n $one_item = -1;\n if (isset($post['_one_id'])) {\n $one_item = $post['_one_id'];\n }\n\n // Count real items returned\n $count = 0;\n if ($item instanceof CommonTreeDropdown) {\n if (isset($post['parent_id']) && $post['parent_id'] != '') {\n $sons = getSonsOf($table, $post['parent_id']);\n $where[] = [\n [\"$table.id\" => $sons],\n [\"NOT\" => [\"$table.id\" => $post['parent_id']]],\n ];\n }\n if ($one_item >= 0) {\n $where[\"$table.id\"] = $one_item;\n } else {\n if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);\n\n $swhere = [\n \"OR\" => [\n \"$table.completename\" => ['LIKE', $search]\n ]\n ];\n if ($item->isField('code')) {\n $swhere[\"OR\"][\"$table.code\"] = ['LIKE', $search];\n }\n if ($item->isField('alias')) {\n $swhere[\"OR\"][\"$table.alias\"] = ['LIKE', $search];\n }\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $swhere[\"namet.value\"] = ['LIKE', $search];\n }\n\n if (\n $_SESSION['glpiis_ids_visible']\n && is_numeric($post['searchText']) && (int)$post['searchText'] == $post['searchText']\n ) {\n $swhere[$table . '.' . $item->getIndexName()] = ['LIKE', \"%{$post['searchText']}%\"];\n }\n\n // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $swhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }\n\n $where[] = ['OR' => $swhere];\n }\n }\n\n $multi = false;\n\n // Manage multiple Entities dropdowns\n $order = [\"$table.completename\"];\n\n // No multi if get one item\n if ($item->isEntityAssign()) {\n $recur = $item->maybeRecursive();\n\n // Entities are not really recursive : do not display parents\n if ($post['itemtype'] == 'Entity') {\n $recur = false;\n }\n\n if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n '',\n $post[\"entity_restrict\"],\n $recur\n );\n\n if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }\n } else {\n // If private item do not use entity\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $recur);\n\n if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }\n\n // Force recursive items to multi entity view\n if ($recur) {\n $multi = true;\n }\n\n // no multi view for entitites\n if ($post['itemtype'] == \"Entity\") {\n $multi = false;\n }\n\n if ($multi) {\n $ljoin['glpi_entities'] = [\n 'ON' => [\n 'glpi_entities' => 'id',\n $table => 'entities_id'\n ]\n ];\n array_unshift($order, \"glpi_entities.completename\");\n }\n }\n\n $addselect = [];\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $addselect[] = \"namet.value AS transcompletename\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'completename'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'name')) {\n $addselect[] = \"namet2.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet2'] = [\n 'ON' => [\n 'namet2' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet2.itemtype' => $post['itemtype'],\n 'namet2.language' => $_SESSION['glpilanguage'],\n 'namet2.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }\n\n if ($start > 0 && $multi) {\n //we want to load last entry of previous page\n //(and therefore one more result) to check if\n //entity name must be displayed again\n --$start;\n ++$limit;\n }\n\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'WHERE' => $where,\n 'ORDER' => $order,\n 'START' => $start,\n 'LIMIT' => $limit\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n $iterator = $DB->request($criteria);\n\n // Empty search text : display first\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if ($post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post['emptylabel']\n ];\n }\n }\n\n if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => $val\n ];\n }\n }\n }\n $last_level_displayed = [];\n $datastoadd = [];\n\n // Ignore first item for all pages except first page\n $firstitem = (($post['page'] > 1));\n $firstitem_entity = -1;\n $prev = -1;\n if (count($iterator)) {\n foreach ($iterator as $data) {\n $ID = $data['id'];\n $level = $data['level'];\n\n if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else {\n $outputval = $data['name'];\n }\n\n if (\n $multi\n && ($data[\"entities_id\"] != $prev)\n ) {\n // Do not do it for first item for next page load\n if (!$firstitem) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd,\n 'itemtype' => \"Entity\",\n ];\n }\n }\n }\n $prev = $data[\"entities_id\"];\n if ($firstitem) {\n $firstitem_entity = $prev;\n }\n // Reset last level displayed :\n $datastoadd = [];\n }\n\n if ($_SESSION['glpiuse_flat_dropdowntree']) {\n if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $outputval = $data['transcompletename'];\n } else {\n $outputval = $data['completename'];\n }\n\n $level = 0;\n } else { // Need to check if parent is the good one\n // Do not do if only get one item\n if (($level > 1)) {\n // Last parent is not the good one need to display arbo\n if (\n !isset($last_level_displayed[$level - 1])\n || ($last_level_displayed[$level - 1] != $data[$item->getForeignKeyField()])\n ) {\n $work_level = $level - 1;\n $work_parentID = $data[$item->getForeignKeyField()];\n $parent_datas = [];\n do {\n // Get parent\n if ($item->getFromDB($work_parentID)) {\n // Do not do for first item for next page load\n if (!$firstitem) {\n $title = $item->fields['completename'];\n\n $selection_text = $title;\n\n if (isset($item->fields[\"comment\"])) {\n $addcomment\n = DropdownTranslation::getTranslatedValue(\n $ID,\n $post['itemtype'],\n 'comment',\n $_SESSION['glpilanguage'],\n $item->fields['comment']\n );\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $output2 = DropdownTranslation::getTranslatedValue(\n $item->fields['id'],\n $post['itemtype'],\n 'name',\n $_SESSION['glpilanguage'],\n $item->fields['name']\n );\n\n $temp = ['id' => $work_parentID,\n 'text' => $output2,\n 'level' => (int)$work_level,\n 'disabled' => true\n ];\n if ($post['permit_select_parent']) {\n $temp['title'] = $title;\n $temp['selection_text'] = $selection_text;\n unset($temp['disabled']);\n }\n array_unshift($parent_datas, $temp);\n }\n $last_level_displayed[$work_level] = $item->fields['id'];\n $work_level--;\n $work_parentID = $item->fields[$item->getForeignKeyField()];\n } else { // Error getting item : stop\n $work_level = -1;\n }\n } while (\n ($work_level >= 1)\n && (!isset($last_level_displayed[$work_level])\n || ($last_level_displayed[$work_level] != $work_parentID))\n );\n // Add parents\n foreach ($parent_datas as $val) {\n $datastoadd[] = $val;\n }\n }\n }\n $last_level_displayed[$level] = $data['id'];\n }\n\n // Do not do for first item for next page load\n if (!$firstitem) {\n if (\n $_SESSION[\"glpiis_ids_visible\"]\n || (Toolbox::strlen($outputval) == 0)\n ) {\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }\n\n if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $title = $data['transcompletename'];\n } else {\n $title = $data['completename'];\n }\n\n if (isset($data['alias']) && !empty($data['alias'])) {\n $outputval = $data['alias'];\n $title = $data['alias'];\n }\n if (isset($data['code']) && !empty($data['code'])) {\n $outputval .= ' - ' . $data['code'];\n $title .= ' - ' . $data['code'];\n }\n\n $selection_text = $title;\n\n if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment = $data['transcomment'];\n } else {\n $addcomment = $data['comment'];\n }\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'level' => (int)$level,\n 'title' => $title,\n 'selection_text' => $selection_text\n ];\n $count++;\n }\n $firstitem = false;\n }\n }\n\n if ($multi) {\n if (count($datastoadd)) {\n // On paging mode do not add entity information each time\n if ($prev == $firstitem_entity) {\n $datas = array_merge($datas, $datastoadd);\n } else {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd,\n 'itemtype' => \"Entity\",\n ];\n }\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n } else { // Not a dropdowntree\n $multi = false;\n // No multi if get one item\n if ($item->isEntityAssign()) {\n $multi = $item->maybeRecursive();\n\n if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n \"entities_id\",\n $post[\"entity_restrict\"],\n $multi\n );\n\n if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }\n } else {\n // Do not use entity if may be private\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $multi);\n\n if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }\n }\n\n $field = \"name\";\n if ($item instanceof CommonDevice) {\n $field = \"designation\";\n } else if ($item instanceof Item_Devices) {\n $field = \"itemtype\";\n }\n\n if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);\n $orwhere = [\"$table.$field\" => ['LIKE', $search]];\n\n if (\n $_SESSION['glpiis_ids_visible'] && (int) $post['searchText'] === $post['searchText']\n ) {\n $orwhere[$table . '.' . $item::getIndexName()] = ['LIKE', \"{$post['searchText']}%\"];\n }\n\n if ($item instanceof CommonDCModelDropdown) {\n $orwhere[$table . '.product_number'] = ['LIKE', $search];\n }\n\n if (Session::haveTranslations($post['itemtype'], $field)) {\n $orwhere['namet.value'] = ['LIKE', $search];\n }\n if ($post['itemtype'] == \"SoftwareLicense\") {\n $orwhere['glpi_softwares.name'] = ['LIKE', $search];\n }\n\n // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $orwhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }\n\n $where[] = ['OR' => $orwhere];\n }\n $addselect = [];\n\n if (Session::haveTranslations($post['itemtype'], $field)) {\n $addselect[] = \"namet.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => $field\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }\n\n $criteria = [];\n switch ($post['itemtype']) {\n case \"Contact\":\n $criteria = [\n 'SELECT' => [\n \"$table.entities_id\",\n QueryFunction::concat(\n params: [\n QueryFunction::ifnull('name', new QueryExpression($DB::quoteValue(''))),\n new QueryExpression($DB::quoteValue(' ')),\n QueryFunction::ifnull('firstname', new QueryExpression($DB::quoteValue('')))\n ],\n alias:$field\n ),\n \"$table.comment\",\n \"$table.id\"\n ],\n 'FROM' => $table\n ];\n break;\n\n case \"SoftwareLicense\":\n $criteria = [\n 'SELECT' => [\n \"$table.*\",\n QueryFunction::concat(\n params: ['glpi_softwares.name', new QueryExpression($DB::quoteValue(' - ')), 'glpi_softwarelicenses.name'],\n alias: $field\n ),\n ],\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_softwares' => [\n 'ON' => [\n 'glpi_softwarelicenses' => 'softwares_id',\n 'glpi_softwares' => 'id'\n ]\n ]\n ]\n ];\n break;\n\n case \"Profile\":\n $criteria = [\n 'SELECT' => \"$table.*\",\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_profilerights' => [\n 'ON' => [\n 'glpi_profilerights' => 'profiles_id',\n $table => 'id'\n ]\n ]\n ]\n ];\n break;\n\n case KnowbaseItem::getType():\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'DISTINCT' => true,\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n\n $visibility = KnowbaseItem::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $criteria['LEFT JOIN'] = array_merge(\n (isset($criteria['LEFT JOIN']) ? $criteria['LEFT JOIN'] : []),\n $visibility['LEFT JOIN']\n );\n //Do not use where??\n /*if (isset($visibility['WHERE'])) {\n $where = $visibility['WHERE'];\n }*/\n }\n break;\n\n case Ticket::class:\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table,\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n if (!Session::haveRight(Ticket::$rightname, Ticket::READALL)) {\n $unused_ref = [];\n $joins_str = Search::addDefaultJoin(Ticket::class, Ticket::getTable(), $unused_ref);\n if (!empty($joins_str)) {\n $criteria['LEFT JOIN'] = [new QueryExpression($joins_str)];\n }\n $where[] = new QueryExpression(Search::addDefaultWhere(Ticket::class));\n }\n break;\n\n case Project::getType():\n $visibility = Project::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $ljoin = array_merge($ljoin, $visibility['LEFT JOIN']);\n if (isset($visibility['WHERE'])) {\n $where[] = $visibility['WHERE'];\n }\n }\n //no break to reach default case.\n\n default:\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n }\n\n $criteria = array_merge(\n $criteria,\n [\n 'DISTINCT' => true,\n 'WHERE' => $where,\n 'START' => $start,\n 'LIMIT' => $limit\n ]\n );\n\n $order_field = \"$table.$field\";\n if (isset($post['order']) && !empty($post['order'])) {\n $order_field = $post['order'];\n }\n if ($multi) {\n $criteria['ORDERBY'] = [\"$table.entities_id\", $order_field];\n } else {\n $criteria['ORDERBY'] = [$order_field];\n }\n\n $iterator = $DB->request($criteria);\n\n // Display first if no search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if (!isset($post['display_emptychoice']) || $post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post[\"emptylabel\"]\n ];\n }\n }\n if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => $val\n ];\n }\n }\n }\n\n $datastoadd = [];\n\n if (count($iterator)) {\n $prev = -1;\n\n foreach ($iterator as $data) {\n if (\n $multi\n && ($data[\"entities_id\"] != $prev)\n ) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd,\n 'itemtype' => \"Entity\",\n ];\n }\n }\n $prev = $data[\"entities_id\"];\n $datastoadd = [];\n }\n\n if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else if ($field == 'itemtype' && class_exists($data['itemtype'])) {\n $tmpitem = new $data[$field]();\n if ($tmpitem->getFromDB($data['items_id'])) {\n $outputval = sprintf(__('%1$s - %2$s'), $tmpitem->getTypeName(), $tmpitem->getName());\n } else {\n $outputval = $tmpitem->getTypeName();\n }\n } else if ($item instanceof CommonDCModelDropdown) {\n $outputval = sprintf(__('%1$s - %2$s'), $data[$field], $data['product_number']);\n } else {\n $outputval = $data[$field] ?? \"\";\n }\n\n $ID = $data['id'];\n $addcomment = \"\";\n $title = $outputval;\n if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment .= $data['transcomment'];\n } else {\n $addcomment .= $data[\"comment\"];\n }\n\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n if (\n $_SESSION[\"glpiis_ids_visible\"]\n || (strlen($outputval) == 0)\n ) {\n //TRANS: %1$s is the name, %2$s the ID\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }\n if ($displaywith) {\n foreach ($post['displaywith'] as $key) {\n if (isset($data[$key])) {\n $withoutput = $data[$key];\n if (isForeignKeyField($key)) {\n $withoutput = Dropdown::getDropdownName(\n getTableNameForForeignKeyField($key),\n $data[$key]\n );\n }\n if ((strlen($withoutput) > 0) && ($withoutput != '&nbsp;')) {\n $outputval = sprintf(__('%1$s - %2$s'), $outputval, $withoutput);\n }\n }\n }\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'title' => $title\n ];\n $count++;\n }\n if ($multi) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd,\n 'itemtype' => \"Entity\",\n ];\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n }\n }\n\n $ret['results'] = $datas;\n $ret['count'] = $count;\n\n return ($json === true) ? json_encode($ret) : $ret;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function getPlanOfCare($pid, $encounter)\n {\n $wherCon = '';\n $appTable = new ApplicationTable();\n $sqlBindArray = ['Plan_of_Care_Type', $pid, 'care_plan', 0];\n\n if (!empty($this->encounterFilterList)) {\n $wherCon = \" AND f.encounter IN (\" . implode(\",\", array_map(\"intval\", $this->encounterFilterList)) . \")\";\n } elseif ($this->searchFiltered) {\n // there are no encounters to filter on in the form and we are filtering the data...\n return \"<planofcare></planofcare><goals></goals><health_concerns></health_concerns>\";\n }\n\n UuidRegistry::createMissingUuidsForTables(['lists']);\n // TODO: implement referrals. Our transactions table does not keep a code value which is required to report for ccda.\n // We used to grab the referrals but since we have no codes for the referral we ended up just skipping all the data\n // We removed the care plan transaction information here as it wasn't being used here or with serveccda. When we\n // support codes in the transaction table we can add that back in.\n $query = \"SELECT 'care_plan' AS source,fcp.encounter,fcp.code,fcp.codetext,fcp.description,fcp.date,l.`notes` AS moodCode,fcp.care_plan_type AS care_plan_type,fcp.note_related_to as note_issues\n , u.id AS provenance_updated_by, f.date AS modifydate, f.form_id\n FROM forms AS f\n LEFT JOIN form_care_plan AS fcp ON fcp.id = f.form_id\n LEFT JOIN codes AS c ON c.code = fcp.code\n LEFT JOIN code_types AS ct ON c.`code_type` = ct.ct_id\n LEFT JOIN users as u on u.username = fcp.user\n LEFT JOIN `list_options` l ON l.`option_id` = fcp.`care_plan_type` AND l.`list_id`=?\n WHERE f.pid = ? AND f.formdir = ? AND f.deleted = ? $wherCon Order By fcp.encounter DESC\";\n $res = $appTable->zQuery($query, $sqlBindArray);\n $status = 'Pending';\n $status_entry = 'active';\n $planofcare = '<planofcare>';\n $goals = '<goals>';\n $concerns = '<health_concerns>';\n foreach ($res as $row) {\n // we are handling the dates differently here than the other filtered data types because the transaction\n // table stores the refer_date as a textual string and we can't convert it in a cross-database fashion right\n // now to do our date comparisons like we do all of the other fields.\n if ($this->searchFiltered) {\n $rowDate = strtotime($row['date']);\n // if we can't format the date and we are filtering then we exclude it,\n if (\n $rowDate === false\n // we have a from date so we filter by it\n || (isset($this->searchFromDate) && $rowDate < $this->searchFromDate)\n // we have a to date so we filter by it\n || (isset($this->searchToDate) && $rowDate > $this->searchToDate)\n ) {\n continue;\n }\n }\n $provenanceRecord = [\n 'author_id' => $row['provenance_updated_by']\n ,'time' => $row['modifydate']\n ];\n $provenanceXml = $this->getAuthorXmlForRecord($provenanceRecord, $pid, $encounter);\n $row['description'] = preg_replace(\"/\\{\\|([^\\]]*)\\|}/\", '', $row['description']);\n $tmp = explode(\":\", $row['code']);\n $code_type = $tmp[0];\n $code = $tmp[1] ?? '';\n if ($row['care_plan_type'] === 'health_concern') {\n $issue_uuid = \"<issues>\\n\";\n if (!empty($row['note_issues'])) {\n $issues = json_decode($row['note_issues'], true);\n foreach ($issues as $issue) {\n $q = \"Select uuid from lists Where id = ?\";\n $uuid = sqlQuery($q, array($issue))['uuid'];\n if (empty($uuid)) {\n continue;\n }\n $uuid_problem = UuidRegistry::uuidToString($uuid);\n $issue_uuid .= \"<issue_uuid>\" . xmlEscape($uuid_problem) . \"</issue_uuid>\\n\";\n }\n }\n $concerns .= \"<concern>\" . $provenanceXml .\n $issue_uuid . \"</issues>\" .\n \"<encounter>\" . xmlEscape($row['encounter']) . \"</encounter>\n <extension>\" . xmlEscape(base64_encode($_SESSION['site_id'] . $row['encounter'])) . \"</extension>\n <sha_extension>\" . xmlEscape($this->formatUid($row['form_id'] . $row['description'])) . \"</sha_extension>\n <text>\" . xmlEscape($row['date'] . \" \" . $row['description']) . '</text>\n <code>' . xmlEscape($code) . '</code>\n <code_type>' . xmlEscape($code_type) . '</code_type>\n <code_text>' . xmlEscape($row['codetext']) . '</code_text>\n <date>' . xmlEscape($row['date']) . '</date>\n <date_formatted>' . xmlEscape(str_replace(\"-\", '', $row['date'])) . '</date_formatted>\n </concern>';\n }\n if ($row['care_plan_type'] === 'goal') {\n $goals .= '<item>' . $provenanceXml . '\n <extension>' . xmlEscape(base64_encode($_SESSION['site_id'] . $row['encounter'])) . '</extension>\n <sha_extension>' . xmlEscape($this->formatUid($row['form_id'] . $row['description'])) . '</sha_extension>\n <care_plan_type>' . xmlEscape($row['care_plan_type']) . '</care_plan_type>\n <encounter>' . xmlEscape($row['encounter']) . '</encounter>\n <code>' . xmlEscape($code) . '</code>\n <code_text>' . xmlEscape($row['codetext']) . '</code_text>\n <description>' . xmlEscape($row['description']) . '</description>\n <date>' . xmlEscape($row['date']) . '</date>\n <date_formatted>' . xmlEscape(str_replace(\"-\", '', $row['date'])) . '</date_formatted>\n <status>' . xmlEscape($status) . '</status>\n <status_entry>' . xmlEscape($status_entry) . '</status_entry>\n <code_type>' . xmlEscape($code_type) . '</code_type>\n <moodCode>' . xmlEscape($row['moodCode']) . '</moodCode>\n </item>';\n } elseif ($row['care_plan_type'] !== 'health_concern') {\n $planofcare .= '<item>' . $provenanceXml . '\n <extension>' . xmlEscape(base64_encode($_SESSION['site_id'] . $row['encounter'])) . '</extension>\n <sha_extension>' . xmlEscape($this->formatUid($row['form_id'] . $row['description'])) . '</sha_extension>\n <care_plan_type>' . xmlEscape($row['care_plan_type']) . '</care_plan_type>\n <encounter>' . xmlEscape($row['encounter']) . '</encounter>\n <code>' . xmlEscape($code) . '</code>\n <code_text>' . xmlEscape($row['codetext']) . '</code_text>\n <description>' . xmlEscape($row['description']) . '</description>\n <date>' . xmlEscape($row['date']) . '</date>\n <date_formatted>' . xmlEscape(str_replace(\"-\", '', $row['date'])) . '</date_formatted>\n <status>' . xmlEscape($status) . '</status>\n <status_entry>' . xmlEscape($status_entry) . '</status_entry>\n <code_type>' . xmlEscape($code_type) . '</code_type>\n <moodCode>' . xmlEscape($row['moodCode']) . '</moodCode>\n </item>';\n }\n }\n\n $planofcare .= '</planofcare>';\n $goals .= '</goals>';\n $concerns .= '</health_concerns>';\n return $planofcare . $goals . $concerns;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function runUpgradeModule()\n {\n $upgrade = &self::$modules_cache[$this->name]['upgrade'];\n foreach ($upgrade['upgrade_file_left'] as $num => $file_detail) {\n foreach ($file_detail['upgrade_function'] as $item) {\n if (function_exists($item)) {\n $upgrade['success'] = false;\n $upgrade['duplicate'] = true;\n\n break 2;\n }\n }\n\n include $file_detail['file'];\n\n // Call the upgrade function if defined\n $upgrade['success'] = false;\n foreach ($file_detail['upgrade_function'] as $item) {\n if (function_exists($item)) {\n $upgrade['success'] = $item($this);\n }\n }\n\n // Set detail when an upgrade succeed or failed\n if ($upgrade['success']) {\n ++$upgrade['number_upgraded'];\n $upgrade['upgraded_to'] = $file_detail['version'];\n\n unset($upgrade['upgrade_file_left'][$num]);\n } else {\n $upgrade['version_fail'] = $file_detail['version'];\n\n // If any errors, the module is disabled\n $this->disable();\n\n break;\n }\n }\n\n $upgrade['number_upgrade_left'] = count($upgrade['upgrade_file_left']);\n\n // Update module version in DB with the last succeed upgrade\n if ($upgrade['upgraded_to']) {\n Module::upgradeModuleVersion($this->name, $upgrade['upgraded_to']);\n }\n $this->setUpgradeMessage($upgrade);\n\n return $upgrade;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function getDBStatus($public_only = true): array\n {\n static $status = null;\n\n if ($status === null) {\n $status = [\n 'status' => self::STATUS_OK,\n 'main' => [\n 'status' => self::STATUS_OK,\n ],\n 'replicas' => [\n 'status' => self::STATUS_NO_DATA,\n 'servers' => []\n ]\n ];\n // Check replica SQL server connection\n if (DBConnection::isDBSlaveActive()) {\n $DBslave = DBConnection::getDBSlaveConf();\n if (is_array($DBslave->dbhost)) {\n $hosts = $DBslave->dbhost;\n } else {\n $hosts = [$DBslave->dbhost];\n }\n\n if (count($hosts)) {\n $status['replicas']['status'] = self::STATUS_OK;\n }\n\n foreach ($hosts as $num => $name) {\n $diff = DBConnection::getReplicateDelay($num);\n if (abs($diff) > 1000000000) {\n $status['replicas']['servers'][$num] = [\n 'status' => self::STATUS_PROBLEM,\n 'replication_delay' => '-1',\n 'status_msg' => _x('glpi_status', 'Replication delay is too high')\n ];\n $status['replicas']['status'] = self::STATUS_PROBLEM;\n $status['status'] = self::STATUS_PROBLEM;\n } else if (abs($diff) > HOUR_TIMESTAMP) {\n $status['replicas']['servers'][$num] = [\n 'status' => self::STATUS_PROBLEM,\n 'replication_delay' => abs($diff),\n 'status_msg' => _x('glpi_status', 'Replication delay is too high')\n ];\n $status['replicas']['status'] = self::STATUS_PROBLEM;\n $status['status'] = self::STATUS_PROBLEM;\n } else {\n $status['replicas']['servers'][$num] = [\n 'status' => self::STATUS_OK,\n 'replication_delay' => abs($diff)\n ];\n }\n }\n }\n\n // Check main server connection\n if (!@DBConnection::establishDBConnection(false, true)) {\n $status['main'] = [\n 'status' => self::STATUS_PROBLEM,\n 'status_msg' => _x('glpi_status', 'Unable to connect to the main database')\n ];\n $status['status'] = self::STATUS_PROBLEM;\n }\n }\n\n return $status;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function index($groupId = null)\n {\n\n $data = array();\n if ($groupId) {\n self::setSession($groupId);\n }\n\n //Load models\n $this->therapyGroupModel = $this->loadModel('therapy_groups');\n $this->counselorsModel = $this->loadModel('Therapy_Groups_Counselors');\n $eventsModel = $this->loadModel('Therapy_Groups_Events');\n $userModel = $this->loadModel('Users');\n\n //Get group events\n if ($groupId) {\n $events = $eventsModel->getGroupEvents($groupId);\n $data['events'] = $events;\n }\n\n //Get users\n $users = $userModel->getAllUsers();\n $data['users'] = $users;\n\n //Get statuses\n $data['statuses'] = self::prepareStatusesList();\n\n $_POST['group_start_date'] = DateToYYYYMMDD($_POST['group_start_date']);\n $_POST['group_end_date'] = DateToYYYYMMDD($_POST['group_end_date']);\n\n if (isset($_POST['save'])) {\n $isEdit = empty($_POST['group_id']) ? false : true;\n\n // for new group - checking if already exist same name\n if ($_POST['save'] != 'save_anyway' && $this->alreadyExist($_POST, $isEdit)) {\n $data['message'] = xlt('Failed - already has group with the same name') . '.';\n $data['savingStatus'] = 'exist';\n $data['groupData'] = $_POST;\n if ($isEdit) {\n $this->loadView('groupDetailsGeneralData', $data);\n } else {\n $this->loadView('addGroup', $data);\n }\n }\n\n $filters = array(\n 'group_name' => FILTER_DEFAULT,\n 'group_start_date' => FILTER_SANITIZE_SPECIAL_CHARS,\n 'group_type' => FILTER_VALIDATE_INT,\n 'group_participation' => FILTER_VALIDATE_INT,\n 'group_status' => FILTER_VALIDATE_INT,\n 'group_notes' => FILTER_DEFAULT,\n 'group_guest_counselors' => FILTER_DEFAULT,\n 'counselors' => array('filter' => FILTER_VALIDATE_INT,\n 'flags' => FILTER_FORCE_ARRAY)\n );\n if ($isEdit) {\n $filters['group_end_date'] = FILTER_SANITIZE_SPECIAL_CHARS;\n $filters['group_id'] = FILTER_VALIDATE_INT;\n }\n\n //filter and sanitize all post data.\n $data['groupData'] = filter_var_array($_POST, $filters);\n if (!$data['groupData']) {\n $data['message'] = xlt('Failed to create new group') . '.';\n $data['savingStatus'] = 'failed';\n } else {\n if (!$isEdit) {\n // save new group\n $id = $this->saveNewGroup($data['groupData']);\n $data['groupData']['group_id'] = $id;\n $data['message'] = xlt('New group was saved successfully') . '.';\n $data['savingStatus'] = 'success';\n self::setSession($id);\n $events = $eventsModel->getGroupEvents($id);\n $data['events'] = $events;\n $data['readonly'] = 'disabled';\n\n $this->loadView('groupDetailsGeneralData', $data);\n } else {\n //update group\n $this->updateGroup($data['groupData']);\n $data['message'] = xlt(\"Detail's group was saved successfully\") . '.';\n $data['savingStatus'] = 'success';\n $data['readonly'] = 'disabled';\n $this->loadView('groupDetailsGeneralData', $data);\n }\n }\n\n // before saving\n } else {\n if (is_null($groupId)) {\n //for new form\n $data['groupData'] = array('group_name' => null,\n 'group_start_date' => date('Y-m-d'),\n 'group_type' => null,\n 'group_participation' => null,\n 'group_notes' => null,\n 'group_guest_counselors' => null,\n 'group_status' => null\n );\n $this->loadView('addGroup', $data);\n } else {\n //for exist group screen\n $data['groupData'] = $this->therapyGroupModel->getGroup($groupId);\n $data['groupData']['counselors'] = $this->counselorsModel->getCounselors($groupId);\n $data['readonly'] = isset($_GET['editGroup']) ? '' : 'disabled';\n\n $this->loadView('groupDetailsGeneralData', $data);\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function getfeedbacktxt($stu,$fbtxt,$ans) {\n\tglobal $imasroot,$staticroot;\n\tif (isset($GLOBALS['testsettings']['testtype']) && ($GLOBALS['testsettings']['testtype']=='NoScores' || $GLOBALS['testsettings']['testtype']=='EndScore')) {\n\t\treturn '';\n\t}\n\tif ($stu===null || !is_scalar($stu) || !is_scalar($ans)) {\n\t\treturn \" \";\n\t} else if ($stu==='NA') {\n\t\treturn '<div class=\"feedbackwrap\"><img src=\"'.$staticroot.'/img/redx.gif\" alt=\"Incorrect\"/> ' . _(\"No answer selected. Try again.\") . '</div>';\n } else {\n $anss = explode(' or ', $ans);\n foreach ($anss as $ans) {\n if ($stu==$ans) {\n $out = '<div class=\"feedbackwrap correct\"><img src=\"'.$staticroot.'/img/gchk.gif\" alt=\"Correct\"/> ';\n if (isset($fbtxt[$stu])) {\n $out .= $fbtxt[$stu];\n }\n return $out .= '</div>';\n } \n }\n $out = '<div class=\"feedbackwrap incorrect\"><img src=\"'.$staticroot.'/img/redx.gif\" alt=\"Incorrect\"/> ';\n if (isset($fbtxt[$stu])) {\n $out .= $fbtxt[$stu];\n }\n return $out .= '</div>';\n } \n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "protected function processRequest(array $data = [])\n {\n $this->isValid = false;\n\n $this->type = $data['type'];\n\n if (!in_array($this->type, $this->getValidTypes())) {\n $this->errors[] = 'Please select correct type.';\n return false;\n }\n\n if ($this->type == 'native') {\n $this->mail_parameters = $data['mail_parameters'] ?: null;\n\n } else if ($this->type == 'sendmail') {\n $this->sendmail_command = $data['sendmail_command'] ?: null;\n\n } else if ($this->type == 'smtp') {\n $this->useExistingPassword = (boolean) $data['use_existing_password'];\n $this->hostname = $data['hostname'];\n $this->port = $data['port'];\n $this->username = $data['username'] ?: null;\n $this->password = $this->useExistingPassword ? $this->defaultPassword : $data['password'];\n $this->encryption = $data['encryption'] ?: null;\n $this->timeout = $data['timeout'] ?: null;\n\n if (!$data['hostname']) {\n $this->errors[] = 'Please enter hostname.';\n }\n\n if (!$data['port']) {\n $this->errors[] = 'Please enter port.';\n }\n\n if ($this->encryption && !in_array($this->encryption, ['ssl', 'tls'])) {\n $this->errors[] = 'Please enter correct encryption.';\n }\n }\n\n if (count($this->errors)) {\n return false;\n }\n\n $this->isValid = true;\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "public function postFile($url, $fileName, $jsonFilePath, $params = [], $gzip = true): ?string\n {\n // Prepare multipart data\n $multipartData = [];\n\n try {\n\n if ($gzip) {\n $fileContents = gzencode(file_get_contents($jsonFilePath));\n } else {\n $fileContents = fopen($jsonFilePath, 'r');\n }\n\n // Prepare file content for multipart\n $multipartData = [\n [\n 'name' => $fileName,\n 'contents' => $fileContents,\n 'filename' => basename($jsonFilePath) . ($gzip ? '.gz' : ''),\n ]\n ];\n\n // Add additional parameters to multipart data\n // Check if params are in ['name' => 'x','contents' => 'y'] format or associative array\n if (isset($params[0]['contents']) && isset($params[0]['name'])) {\n // Params are in the ['name' => 'x','contents' => 'y'] format, merge them directly\n $multipartData = array_merge($multipartData, $params);\n } else {\n // Params are in associative array format, handle them as key-value pairs\n foreach ($params as $name => $value) {\n $multipartData[] = [\n 'name' => $name,\n 'contents' => $value\n ];\n }\n }\n // Prepare headers\n $headers = [\n 'X-Timestamp' => time(),\n 'X-Request-ID' => MiscUtility::generateULID()\n ];\n\n // Initialize the options array for multipart form data\n $options = [\n RequestOptions::MULTIPART => $multipartData,\n RequestOptions::HEADERS => $headers\n ];\n\n if (!empty($this->headers)) {\n $options[RequestOptions::HEADERS] = array_merge($options[RequestOptions::HEADERS], $this->headers);\n }\n\n // Add Authorization header if a bearer token is provided\n if (!empty($this->bearerToken) && $this->bearerToken != '') {\n $options[RequestOptions::HEADERS]['Authorization'] = \"Bearer $this->bearerToken\";\n }\n\n // Send the request\n $response = $this->client->post($url, $options);\n\n $apiResponse = $response->getBody()->getContents();\n } catch (RequestException $e) {\n // Extract the response body from the exception, if available\n $responseBody = $e->hasResponse() ? $e->getResponse()->getBody()->getContents() : null;\n $errorCode = $e->getResponse() ? $e->getResponse()->getStatusCode() : 500;\n // Log the error along with the response body\n $this->logError($e, \"Unable to post to $url. Server responded with $errorCode : \" . ($responseBody ?? 'No response body'));\n\n $apiResponse = $responseBody ?? null;\n } catch (Throwable $e) {\n $this->logError($e, \"Unable to post to $url\");\n $apiResponse = null; // Error occurred while making the request\n }\n return $apiResponse;\n }", "smellKey": "S3776", "smellId": null, "repo": "deforay_vlsm", "language": "php"} {"function": "public function buildForm(FormBuilderInterface $builder, array $options)\n {\n parent::buildForm($builder, $options);\n\n $preListener = function (FormEvent $event/*, $eventName, EventDispatcher $dispatcher*/) use ($options) {\n /** @var Form $form */\n $form = $event->getForm();\n $data = $event->getData();\n\n if (null === $data) {\n $data = array();\n }\n\n if (!is_array($data) && !($data instanceof \\Traversable && $data instanceof \\ArrayAccess)) {\n throw new UnexpectedTypeException($data, 'array or (\\Traversable and \\ArrayAccess)');\n }\n\n // First remove all rows\n foreach ($form as $name => $child) {\n $form->remove($name);\n }\n\n // Then add all rows again in the correct order\n foreach ($data as $name => $value) {\n $className = 'VulnModule\\\\Form\\\\Vulnerability\\\\' . $name . 'Type';\n $type = class_exists($className) ? new $className : 'vulnerability';\n\n $opts = array_replace(array('property_path' => '['.$name.']'), $options['options'] ?: []);\n $opts['cascade_validation'] = $options['cascade_validation'];\n $form->add($name, $type, $opts);\n }\n };\n\n $builder->addEventListener(FormEvents::PRE_SET_DATA, $preListener);\n $builder->addEventListener(FormEvents::PRE_SUBMIT, $preListener);\n\n $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event/*, $eventName, EventDispatcher $dispatcher*/) use ($options) {\n $data = $event->getData();\n\n if (null === $data) {\n return;\n }\n\n if (!is_array($data) && !($data instanceof \\Traversable && $data instanceof \\ArrayAccess)) {\n throw new UnexpectedTypeException($data, 'array or (\\Traversable and \\ArrayAccess)');\n }\n\n /**\n * @var string $name\n * @var Vulnerability $value\n */\n foreach ($data as $name => $value) {\n if ($value->getName() == $name) {\n continue;\n }\n $className = 'VulnModule\\\\Vulnerability\\\\' . $name;\n /** @var Vulnerability $element */\n $element = new $className;\n $element->fillFromArray($value->asArray());\n $data[$name] = $element;\n\n }\n\n $event->setData($data);\n });\n }", "smellKey": "S3776", "smellId": null, "repo": "antonisLem_hackazon", "language": "php"} {"function": "public static function getLDAPStatus($public_only = true): array\n {\n static $status = null;\n\n if ($status === null) {\n $status = [\n 'status' => self::STATUS_NO_DATA,\n 'servers' => []\n ];\n if (self::isDBAvailable()) {\n // Check LDAP Auth connections\n $ldap_methods = getAllDataFromTable('glpi_authldaps', ['is_active' => 1]);\n\n $total_servers = count($ldap_methods);\n $total_error = 0;\n $global_status = self::STATUS_NO_DATA;\n $message = null;\n if ($total_servers > 0) {\n $global_status = self::STATUS_OK;\n foreach ($ldap_methods as $method) {\n $ldap = null;\n try {\n if (\n @AuthLDAP::tryToConnectToServer(\n $method,\n $method['rootdn'],\n (new \\GLPIKey())->decrypt($method['rootdn_passwd'])\n )\n ) {\n $status['servers'][$method['name']] = [\n 'status' => self::STATUS_OK\n ];\n } else {\n $status['servers'][$method['name']] = [\n 'status' => self::STATUS_PROBLEM,\n 'status_msg' => _x('glpi_status', 'Unable to connect to the LDAP server')\n ];\n $total_error++;\n $global_status = self::STATUS_PROBLEM;\n }\n } catch (\\RuntimeException $e) {\n // May be missing LDAP extension (Probably test environment)\n $status['servers'][$method['name']] = [\n 'status' => self::STATUS_PROBLEM\n ];\n $total_error++;\n $global_status = self::STATUS_PROBLEM;\n }\n }\n\n if ($global_status !== self::STATUS_OK) {\n $message = sprintf(_x('glpi_status', 'OK: %d, WARNING: %d, PROBLEM: %d, TOTAL: %d'), $total_servers - $total_error, 0, $total_error, $total_servers);\n }\n }\n $status['status'] = $global_status;\n if ($message !== null) {\n $status['status_msg'] = $message;\n }\n }\n }\n\n return $status;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function countLinksByStatus(string $itemtype, int $items_id, array $status = [], array $link_types = []): int\n {\n if (static::class === self::class) {\n throw new \\LogicException(sprintf('%s should be called only from sub classes.', __METHOD__));\n }\n\n /** @var \\DBmysql $DB */\n global $DB;\n\n $count = 0;\n\n if (static::$itemtype_1 === static::$itemtype_2) {\n $linked_table = $itemtype::getTable();\n $linked_fk = static::$items_id_1;\n\n $where = [\n 'links.' . static::$items_id_2 => $items_id,\n ];\n\n if (in_array(self::PARENT_OF, $link_types, true)) {\n if (($key = array_search(self::PARENT_OF, $link_types, true)) !== false) {\n unset($link_types[$key]);\n }\n $other_link_types = $link_types;\n if (($key = array_search(self::SON_OF, $other_link_types, true)) !== false) {\n unset($other_link_types[$key]);\n }\n // Count everything except SON_OF links using original parameters\n if (!empty($other_link_types)) {\n $count = static::countLinksByStatus($itemtype, $items_id, $status, $other_link_types);\n }\n\n // Count only SON_OF links here using swapped parameters\n $where = [\n 'links.' . static::$items_id_1 => $items_id,\n ];\n $link_types = [self::SON_OF];\n $linked_fk = static::$items_id_2;\n }\n } else {\n $linked_table = static::$itemtype_1 === $itemtype ? static::$itemtype_2::getTable() : static::$itemtype_1::getTable();\n $linked_fk = static::$itemtype_1 === $itemtype ? static::$items_id_2 : static::$items_id_1;\n\n $where_fk = static::$itemtype_1 === $itemtype ? static::$items_id_1 : static::$items_id_2;\n $where = [\n 'links.' . $where_fk => $items_id\n ];\n }\n\n if (!empty($link_types)) {\n $where['links.link'] = $link_types;\n }\n\n if (!empty($status)) {\n $where['items.status'] = $status;\n }\n\n $result = $DB->request([\n 'COUNT' => 'cpt',\n 'FROM' => static::getTable() . ' AS links',\n 'INNER JOIN' => [\n $linked_table . ' AS items' => [\n 'ON' => [\n 'links' => $linked_fk,\n 'items' => 'id'\n ]\n ],\n ],\n 'WHERE' => $where\n ])->current();\n return ((int)$result['cpt']) + $count;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "#[DataProvider('testAnonymizeSettingProvider')]\n public function testAnonymizeSetting(\n string $interface,\n int $setting,\n string $expected,\n string $user_nick = \"\"\n ) {\n global $DB;\n\n $this->login();\n $possible_values = ['test_anon_user', 'user_nick_6436345654', \"Helpdesk user\"];\n\n // Set entity setting\n $entity = getItemByTypeName(\"Entity\", \"_test_root_entity\");\n $update = $entity->update([\n 'id' => $entity->getID(),\n 'anonymize_support_agents' => $setting,\n ]);\n $this->assertTrue($update);\n\n // create a user for this test (avoid using current logged user as we don't anonymize him)\n $user_obj = new \\User();\n $user_obj->add([\n 'name' => 'test_anon_user',\n 'password' => 'test_anon_user'\n ]);\n\n // Set user nickname\n $user = getItemByTypeName('User', 'test_anon_user');\n\n if ($user_nick == \"\" && $user->fields['nickname'] == null) {\n // Special case, glpi wont update null to \"\" so we need to set\n // another value first\n $update = $user->update([\n 'id' => $user->getID(),\n 'nickname' => 'TMP',\n ]);\n $this->assertTrue($update);\n $this->assertTrue($user->getFromDB($user->getID()));\n $this->assertEquals('TMP', $user->fields['nickname']);\n }\n\n $update = $user->update([\n 'id' => $user->getID(),\n 'nickname' => $user_nick,\n ]);\n $this->assertTrue($update);\n $this->assertTrue($user->getFromDB($user->getID()));\n $this->assertEquals($user_nick, $user->fields['nickname']);\n\n // Build test ticket\n $this->login('tech', 'tech');\n\n //force set entity because $_SESSION['glpiactive_entity'] contains 0 without\n //and break test from NotificationTargetCommonITILObject::getDataForObject()\n //and fails to recover the configuration of the anonymization\n $this->setEntity($entity->getID(), true);\n\n $ticket = new Ticket();\n $tickets_id = $ticket->add($input = [\n 'name' => 'test',\n 'content' => 'test',\n '_users_id_assign' => getItemByTypeName('User', 'test_anon_user', true),\n '_users_id_requester' => getItemByTypeName('User', 'post-only', true),\n 'entities_id' => $entity->getID(),\n 'users_id_recipient' => getItemByTypeName('User', 'tech', true),\n 'users_id_lastupdater' => getItemByTypeName('User', 'tech', true),\n // The default requesttype is \"Helpdesk\" and will mess up our tests,\n // we need another one to be sure the \"Helpdesk\" string will only be\n // printed by the anonymization code\n 'requesttypes_id' => 4,\n ]);\n $this->assertGreaterThan(0, $tickets_id);\n\n // Unset temporary fields that will not be found in tickets table\n unset($input['_users_id_assign']);\n unset($input['_users_id_requester']);\n\n // Check expected fields and reload object from DB\n $this->checkInput($ticket, $tickets_id, $input);\n\n // Check linked users\n $ticket_users = $DB->request([\n 'SELECT' => ['tickets_id', 'users_id', 'type'],\n 'FROM' => Ticket_User::getTable(),\n 'WHERE' => ['tickets_id' => $tickets_id],\n ]);\n $this->assertEquals(\n [\n 0 => [\n 'tickets_id' => $tickets_id,\n 'users_id' => getItemByTypeName('User', 'post-only', true),\n 'type' => CommonITILActor::REQUESTER,\n ],\n 1 => [\n 'tickets_id' => $tickets_id,\n 'users_id' => getItemByTypeName('User', 'test_anon_user', true),\n 'type' => CommonITILActor::ASSIGN,\n ],\n ],\n iterator_to_array($ticket_users)\n );\n\n // Add followup to test ticket\n $fup = new ITILFollowup();\n $fup_id = $fup->add([\n 'content' => 'test',\n 'users_id' => getItemByTypeName('User', 'test_anon_user', true),\n 'users_id_editor' => getItemByTypeName('User', 'test_anon_user', true),\n 'itemtype' => 'Ticket',\n 'items_id' => $tickets_id,\n ]);\n $this->assertGreaterThan(0, $fup_id);\n\n // Add solution to test ticket\n $solution = new ITILSolution();\n $solutions_id = $solution->add([\n 'content' => 'test',\n 'users_id' => getItemByTypeName('User', 'test_anon_user', true),\n 'users_id_editor' => getItemByTypeName('User', 'test_anon_user', true),\n 'itemtype' => 'Ticket',\n 'items_id' => $tickets_id,\n ]);\n $this->assertGreaterThan(0, $solutions_id);\n\n // Save and replace session data\n $old_interface = $_SESSION['glpiactiveprofile']['interface'];\n $_SESSION['glpiactiveprofile']['interface'] = $interface;\n\n // Case 1: removed (test values recovered from CommonITILObject::showUsersAssociated())\n\n // Case 2: test values recovered from CommonITILObject:::showShort()\n $entries = Ticket::getDatatableEntries([\n [\n 'item_id' => $tickets_id,\n 'id' => $tickets_id,\n 'itemtype' => 'Ticket',\n ]\n ]);\n $entry = $entries[0];\n\n $entry_contents = array_reduce(array_keys($entry), static function ($carry, $key) use ($entry) {\n return $carry . $entry[$key];\n }, '');\n foreach ($possible_values as $value) {\n if ($value === $expected) {\n $this->assertStringContainsString(\n $value,\n $entry_contents,\n \"Ticket getDatatableEntries must contains '$value' in interface '$interface' with settings '$setting'\"\n );\n } else {\n $this->assertStringNotContainsString(\n $value,\n $entry_contents,\n \"Ticket form must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'\"\n );\n }\n }\n\n // Case 3: removed (timeline merged with main form)\n\n // Case 4: test values recovered from NotificationTargetCommonITILObject::getDataForObject()\n $notification = new NotificationTargetTicket();\n $notif_data = $notification->getDataForObject($ticket, [\n 'additionnaloption' => [\n 'usertype' => NotificationTarget::GLPI_USER,\n // Workaround to \"simulate\" different notification target and test\n // this part more easily\n 'is_self_service' => $interface == 'helpdesk',\n ]\n ]);\n foreach ($notif_data['followups'] as $n_fup) {\n if ($n_fup['##followup.author##'] !== null) {\n foreach ($possible_values as $value) {\n if ($value == $expected) {\n $this->assertStringContainsString(\n $value,\n $n_fup['##followup.author##']\n );\n } else {\n $this->assertStringNotContainsString(\n $value,\n $n_fup['##followup.author##']\n );\n }\n }\n }\n }\n\n // Case 5: test values recovered from Ticket::showForm()\n ob_start();\n $ticket->showForm($tickets_id);\n $html = ob_get_clean();\n // Drop answers form, as new validation form contains current user name\n $html = preg_replace('/<div id=\"new-itilobject-form\".*$/s', '', $html);\n\n foreach ($possible_values as $value) {\n if ($value == $expected) {\n $this->assertStringContainsString(\n $value,\n $html,\n \"Ticket form must contains '$value' in interface '$interface' with settings '$setting'\"\n );\n } else {\n $this->assertStringNotContainsString(\n $value,\n $html,\n \"Ticket form must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'\"\n );\n }\n }\n\n // Reset session\n $_SESSION['glpiactiveprofile']['interface'] = $old_interface;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "private function lexExpression()\n {\n // whitespace\n if (preg_match('/\\s+/A', $this->code, $match, 0, $this->cursor)) {\n $this->moveCursor($match[0]);\n\n if ($this->cursor >= $this->end) {\n throw new SyntaxError(sprintf('Unclosed \"%s\".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source);\n }\n }\n\n // arrow function\n if ('=' === $this->code[$this->cursor] && '>' === $this->code[$this->cursor + 1]) {\n $this->pushToken(Token::ARROW_TYPE, '=>');\n $this->moveCursor('=>');\n }\n // operators\n elseif (preg_match($this->regexes['operator'], $this->code, $match, 0, $this->cursor)) {\n $this->pushToken(/* Token::OPERATOR_TYPE */ 8, preg_replace('/\\s+/', ' ', $match[0]));\n $this->moveCursor($match[0]);\n }\n // names\n elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0, $this->cursor)) {\n $this->pushToken(/* Token::NAME_TYPE */ 5, $match[0]);\n $this->moveCursor($match[0]);\n }\n // numbers\n elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, 0, $this->cursor)) {\n $number = (float) $match[0]; // floats\n if (ctype_digit($match[0]) && $number <= \\PHP_INT_MAX) {\n $number = (int) $match[0]; // integers lower than the maximum\n }\n $this->pushToken(/* Token::NUMBER_TYPE */ 6, $number);\n $this->moveCursor($match[0]);\n }\n // punctuation\n elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) {\n // opening bracket\n if (false !== strpos('([{', $this->code[$this->cursor])) {\n $this->brackets[] = [$this->code[$this->cursor], $this->lineno];\n }\n // closing bracket\n elseif (false !== strpos(')]}', $this->code[$this->cursor])) {\n if (empty($this->brackets)) {\n throw new SyntaxError(sprintf('Unexpected \"%s\".', $this->code[$this->cursor]), $this->lineno, $this->source);\n }\n\n list($expect, $lineno) = array_pop($this->brackets);\n if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {\n throw new SyntaxError(sprintf('Unclosed \"%s\".', $expect), $lineno, $this->source);\n }\n }\n\n $this->pushToken(/* Token::PUNCTUATION_TYPE */ 9, $this->code[$this->cursor]);\n ++$this->cursor;\n }\n // strings\n elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0, $this->cursor)) {\n $this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes(substr($match[0], 1, -1)));\n $this->moveCursor($match[0]);\n }\n // opening double quoted string\n elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) {\n $this->brackets[] = ['\"', $this->lineno];\n $this->pushState(self::STATE_STRING);\n $this->moveCursor($match[0]);\n }\n // unlexable\n else {\n throw new SyntaxError(sprintf('Unexpected character \"%s\".', $this->code[$this->cursor]), $this->lineno, $this->source);\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int {\n\t\tif ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false') {\n\t\t\t$shippedFilter = $input->getOption('shipped') === 'true';\n\t\t} else {\n\t\t\t$shippedFilter = null;\n\t\t}\n\n\t\t$showEnabledApps = $input->getOption('enabled') || !$input->getOption('disabled');\n\t\t$showDisabledApps = $input->getOption('disabled') || !$input->getOption('enabled');\n\n\t\t$apps = \\OC_App::getAllApps();\n\t\t$enabledApps = $disabledApps = [];\n\t\t$versions = \\OC_App::getAppVersions();\n\n\t\t//sort enabled apps above disabled apps\n\t\tforeach ($apps as $app) {\n\t\t\tif ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ($this->manager->isInstalled($app)) {\n\t\t\t\t$enabledApps[] = $app;\n\t\t\t} else {\n\t\t\t\t$disabledApps[] = $app;\n\t\t\t}\n\t\t}\n\n\t\t$apps = [];\n\n\t\tif ($showEnabledApps) {\n\t\t\t$apps['enabled'] = [];\n\n\t\t\tsort($enabledApps);\n\t\t\tforeach ($enabledApps as $app) {\n\t\t\t\t$apps['enabled'][$app] = $versions[$app] ?? true;\n\t\t\t}\n\t\t}\n\n\t\tif ($showDisabledApps) {\n\t\t\t$apps['disabled'] = [];\n\n\t\t\tsort($disabledApps);\n\t\t\tforeach ($disabledApps as $app) {\n\t\t\t\t$apps['disabled'][$app] = $this->manager->getAppVersion($app) . (isset($versions[$app]) ? ' (installed ' . $versions[$app] . ')' : '');\n\t\t\t}\n\t\t}\n\n\t\t$this->writeAppList($input, $output, $apps);\n\t\treturn 0;\n\t}", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "function update91xto920()\n{\n /**\n * @var \\DBmysql $DB\n * @var \\Migration $migration\n */\n global $DB, $migration;\n\n $current_config = Config::getConfigurationValues('core');\n $updateresult = true;\n $ADDTODISPLAYPREF = [];\n\n //TRANS: %s is the number of new version\n $migration->displayTitle(sprintf(__('Update to %s'), '9.2'));\n $migration->setVersion('9.2');\n\n // add business criticity\n $migration->addField(\"glpi_infocoms\", \"businesscriticities_id\", \"integer\");\n $migration->migrationOneTable('glpi_infocoms');\n $migration->addKey(\"glpi_infocoms\", \"businesscriticities_id\");\n\n if (!$DB->tableExists(\"glpi_businesscriticities\")) {\n $query = \"CREATE TABLE `glpi_businesscriticities` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n `businesscriticities_id` int NOT NULL DEFAULT '0',\n `completename` text COLLATE utf8_unicode_ci,\n `level` int NOT NULL DEFAULT '0',\n `ancestors_cache` longtext COLLATE utf8_unicode_ci,\n `sons_cache` longtext COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `unicity` (`businesscriticities_id`,`name`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"Add business criticity table\");\n }\n\n // Issue #1250 - Add decimal to monitor size\n $migration->changeField('glpi_monitors', 'size', 'size', 'DECIMAL(5,2) NOT NULL DEFAULT \"0\"');\n\n //Make software license type a tree dropdown\n $migration->addField(\"glpi_softwarelicensetypes\", \"softwarelicensetypes_id\", \"integer\");\n $migration->addField(\"glpi_softwarelicensetypes\", \"level\", \"integer\");\n $migration->addField(\"glpi_softwarelicensetypes\", \"ancestors_cache\", \"longtext\");\n $migration->addField(\"glpi_softwarelicensetypes\", \"sons_cache\", \"longtext\");\n $migration->addField(\"glpi_softwarelicensetypes\", \"entities_id\", \"integer\");\n $migration->addField(\"glpi_softwarelicensetypes\", \"is_recursive\", \"bool\");\n $tree = $migration->addField(\"glpi_softwarelicensetypes\", \"completename\", \"text\");\n $migration->migrationOneTable('glpi_softwarelicensetypes');\n $migration->addKey(\"glpi_softwarelicensetypes\", \"softwarelicensetypes_id\");\n\n //First time the dropdown is changed from CommonDropdown to CommonTreeDropdown\n if ($tree) {\n $DB->updateOrDie(\n \"glpi_softwarelicensetypes\",\n [\n 'completename' => new QueryExpression(DBmysql::quoteName(\"name\")),\n 'is_recursive' => \"1\"\n ],\n [true],\n \"9.2 make glpi_softwarelicensetypes a tree dropdown\"\n );\n }\n\n // give READ right on components to profiles having UPDATE right\n $DB->updateOrDie(\n \"glpi_profilerights\",\n [\n 'rights' => new QueryExpression($DB->quoteName(\"rights\") . \" | \" . READ)\n ],\n [\n new QueryExpression(DBmysql::quoteName(\"rights\") . \" & \" . DBmysql::quoteValue(UPDATE)),\n 'name' => \"device\"\n ],\n \"grant READ right on components to profiles having UPDATE right\"\n );\n\n $migration->displayMessage(sprintf(__('Add of - %s to database'), 'Knowbase item link to tickets'));\n if (!$DB->tableExists('glpi_knowbaseitems_items')) {\n $query = \"CREATE TABLE `glpi_knowbaseitems_items` (\n `id` int NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int NOT NULL,\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `items_id` int NOT NULL DEFAULT '0',\n `date_creation` datetime DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`itemtype`,`items_id`,`knowbaseitems_id`),\n KEY `itemtype` (`itemtype`),\n KEY `item_id` (`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_knowbaseitems_items\");\n }\n\n $migration->displayMessage(sprintf(__('Add of - %s to database'), 'Knowbase item revisions'));\n if (!$DB->tableExists('glpi_knowbaseitems_revisions')) {\n $query = \"CREATE TABLE `glpi_knowbaseitems_revisions` (\n `id` int NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int NOT NULL,\n `revision` int NOT NULL,\n `name` text COLLATE utf8_unicode_ci,\n `answer` longtext COLLATE utf8_unicode_ci,\n `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n `users_id` int NOT NULL DEFAULT '0',\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`knowbaseitems_id`, `revision`, `language`),\n KEY `revision` (`revision`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_knowbaseitems_revisions\");\n }\n\n $migration->addField(\"glpi_knowbaseitemtranslations\", \"users_id\", \"integer\");\n $migration->migrationOneTable(\"glpi_knowbaseitemtranslations\");\n $migration->addKey(\"glpi_knowbaseitemtranslations\", \"users_id\");\n\n //set kb translations users...\n $knowitems_iterator = $DB->request([\n 'SELECT' => ['glpi_knowbaseitems.id', 'glpi_knowbaseitems.users_id'],\n 'FROM' => 'glpi_knowbaseitems',\n 'INNER JOIN' => [\n \"glpi_knowbaseitemtranslations\" => [\n 'FKEY' => [\n 'glpi_knowbaseitemtranslations' => 'knowbaseitems_id',\n 'glpi_knowbaseitems' => 'id'\n ]\n ]\n ]\n ]);\n foreach ($knowitems_iterator as $knowitems) {\n $DB->updateOrDie(\n \"glpi_knowbaseitemtranslations\",\n ['users_id' => $knowitems['users_id']],\n ['knowbaseitems_id' => $knowitems['id']],\n \"Set knowledge base translations users\"\n );\n }\n\n $migration->addField(\"glpi_knowbaseitemtranslations\", \"date_mod\", \"DATETIME\");\n $migration->addField(\"glpi_knowbaseitemtranslations\", \"date_creation\", \"DATETIME\");\n\n $migration->displayMessage(sprintf(__('Add of - %s to database'), 'Knowbase item comments'));\n if (!$DB->tableExists('glpi_knowbaseitems_comments')) {\n $query = \"CREATE TABLE `glpi_knowbaseitems_comments` (\n `id` int NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int NOT NULL,\n `users_id` int NOT NULL DEFAULT '0',\n `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci NOT NULL,\n `parent_comment_id` int DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_knowbaseitems_comments\");\n }\n\n $DB->updateOrDie(\n \"glpi_profilerights\",\n [\n 'rights' => new QueryExpression(\n DBmysql::quoteName(\"rights\") . \" | \" . DBmysql::quoteValue(KnowbaseItem::COMMENTS)\n )\n ],\n ['name' => \"knowbase\"],\n \"9.2 update knowledge base with comment right\"\n );\n\n // add kb category to task categories\n $migration->addField(\"glpi_taskcategories\", \"knowbaseitemcategories_id\", \"integer\");\n $migration->migrationOneTable(\"glpi_taskcategories\");\n $migration->addKey(\"glpi_taskcategories\", \"knowbaseitemcategories_id\");\n\n // #1476 - Add users_id on glpi_documents_items\n $migration->addField(\"glpi_documents_items\", \"users_id\", \"integer\", ['null' => true]);\n $migration->migrationOneTable(\"glpi_documents_items\");\n $migration->addKey(\"glpi_documents_items\", \"users_id\");\n $migration->addPostQuery(\n $DB->buildUpdate(\n 'glpi_documents_items',\n [\n 'glpi_documents_items.users_id' => new QueryExpression(DBmysql::quoteName('glpi_documents.users_id'))\n ],\n [\n 'glpi_documents_items.documents_id' => new QueryExpression(DBmysql::quoteName('glpi_documents.id'))\n ],\n [\n 'LEFT JOIN' => [\n 'glpi_documents' => [\n 'ON' => [\n 'glpi_documents_items' => 'documents_id',\n 'glpi_documents' => 'id'\n ]\n ]\n ]\n ]\n ),\n \"9.2 update set users_id on glpi_documents_items\",\n [],\n true\n );\n\n //add product number\n $product_types = ['Computer',\n 'Printer',\n 'NetworkEquipment',\n 'Phone',\n 'Peripheral',\n 'Monitor'\n ];\n\n foreach ($product_types as $type) {\n if (class_exists($type . 'Model')) {\n $table = getTableForItemType($type . 'Model');\n $migration->addField($table, 'product_number', 'string', ['after' => 'comment']);\n $migration->migrationOneTable($table);\n $migration->addKey($table, 'product_number');\n }\n }\n\n // add fields on every item_device tables\n $tables = ['glpi_items_devicecases',\n 'glpi_items_devicecontrols',\n 'glpi_items_devicedrives',\n 'glpi_items_devicegraphiccards',\n 'glpi_items_deviceharddrives',\n 'glpi_items_devicememories',\n 'glpi_items_devicemotherboards',\n 'glpi_items_devicenetworkcards',\n 'glpi_items_devicepcis',\n 'glpi_items_devicepowersupplies',\n 'glpi_items_deviceprocessors',\n 'glpi_items_devicesoundcards'\n ];\n\n //add serial, location and state on each devices items\n foreach ($tables as $table) {\n $migration->addField($table, \"otherserial\", \"varchar(255) NULL DEFAULT NULL\");\n $migration->addField($table, \"locations_id\", \"int NOT NULL DEFAULT '0'\");\n $migration->addField($table, \"states_id\", \"int NOT NULL DEFAULT '0'\");\n $migration->migrationOneTable($table);\n $migration->addKey($table, 'otherserial');\n $migration->addKey($table, 'locations_id');\n $migration->addKey($table, 'states_id');\n }\n\n // Create tables :\n $tables = ['glpi_devicecasemodels',\n 'glpi_devicecontrolmodels',\n 'glpi_devicedrivemodels',\n 'glpi_devicegraphiccardmodels',\n 'glpi_deviceharddrivemodels',\n 'glpi_devicememorymodels',\n 'glpi_devicemotherboardmodels',\n 'glpi_devicenetworkcardmodels',\n 'glpi_devicepcimodels',\n 'glpi_devicepowersupplymodels',\n 'glpi_deviceprocessormodels',\n 'glpi_devicesoundcardmodels',\n 'glpi_devicegenericmodels',\n 'glpi_devicebatterymodels',\n 'glpi_devicefirmwaremodels',\n 'glpi_devicesensormodels'\n ];\n\n foreach ($tables as $table) {\n if (!$DB->tableExists($table)) {\n $query = \"CREATE TABLE `$table` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `comment` TEXT NULL COLLATE 'utf8_unicode_ci',\n `product_number` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n PRIMARY KEY (`id`),\n INDEX `name` (`name`),\n INDEX `product_number` (`product_number`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add model tables for devices\");\n }\n }\n\n // Add a field in glpi_device* tables :\n $tables = ['glpi_devicecases' => 'devicecasemodels_id',\n 'glpi_devicecontrols' => 'devicecontrolmodels_id',\n 'glpi_devicedrives' => 'devicedrivemodels_id',\n 'glpi_devicegraphiccards' => 'devicegraphiccardmodels_id',\n 'glpi_deviceharddrives' => 'deviceharddrivemodels_id',\n 'glpi_devicememories' => 'devicememorymodels_id',\n 'glpi_devicemotherboards' => 'devicemotherboardmodels_id',\n 'glpi_devicenetworkcards' => 'devicenetworkcardmodels_id',\n 'glpi_devicepcis' => 'devicepcimodels_id',\n 'glpi_devicepowersupplies' => 'devicepowersupplymodels_id',\n 'glpi_deviceprocessors' => 'deviceprocessormodels_id',\n 'glpi_devicesoundcards' => 'devicesoundcardmodels_id'\n ];\n\n foreach ($tables as $table => $field) {\n $migration->addField($table, $field, 'int DEFAULT NULL', ['after' => 'is_recursive']);\n $migration->migrationOneTable($table);\n $migration->addKey($table, $field);\n }\n\n if (!$DB->tableExists('glpi_devicegenerics')) {\n $query = \"CREATE TABLE `glpi_devicegenerics` (\n `id` int NOT NULL AUTO_INCREMENT,\n `designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `devicegenerictypes_id` int NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `manufacturers_id` int NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `locations_id` int NOT NULL DEFAULT '0',\n `states_id` int NOT NULL DEFAULT '0',\n `devicegenericmodels_id` int DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `designation` (`designation`),\n KEY `manufacturers_id` (`manufacturers_id`),\n KEY `devicegenerictypes_id` (`devicegenerictypes_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `locations_id` (`locations_id`),\n KEY `states_id` (`states_id`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n KEY `devicegenericmodels_id` (`devicegenericmodels_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicegenerics\");\n }\n\n if (!$DB->tableExists('glpi_items_devicegenerics')) {\n $query = \"CREATE TABLE `glpi_items_devicegenerics` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `items_id` INT NOT NULL DEFAULT '0',\n `itemtype` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `devicegenerics_id` INT NOT NULL DEFAULT '0',\n `is_deleted` TINYINT NOT NULL DEFAULT '0',\n `is_dynamic` TINYINT NOT NULL DEFAULT '0',\n `entities_id` INT NOT NULL DEFAULT '0',\n `is_recursive` TINYINT NOT NULL DEFAULT '0',\n `serial` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `otherserial` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `locations_id` INT NOT NULL DEFAULT '0',\n `states_id` INT NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n INDEX `computers_id` (`items_id`),\n INDEX `devicegenerics_id` (`devicegenerics_id`),\n INDEX `is_deleted` (`is_deleted`),\n INDEX `is_dynamic` (`is_dynamic`),\n INDEX `entities_id` (`entities_id`),\n INDEX `is_recursive` (`is_recursive`),\n INDEX `serial` (`serial`),\n INDEX `item` (`itemtype`, `items_id`),\n INDEX `otherserial` (`otherserial`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_devicegenerics\");\n }\n\n if (!$DB->tableExists('glpi_devicegenerictypes')) {\n $query = \"CREATE TABLE `glpi_devicegenerictypes` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `comment` TEXT NULL COLLATE 'utf8_unicode_ci',\n PRIMARY KEY (`id`),\n INDEX `name` (`name`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicegenerictypes\");\n }\n\n if (!$DB->tableExists('glpi_devicebatteries')) {\n $query = \"CREATE TABLE `glpi_devicebatteries` (\n `id` int NOT NULL AUTO_INCREMENT,\n `designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `manufacturers_id` int NOT NULL DEFAULT '0',\n `voltage` int DEFAULT NULL,\n `capacity` int DEFAULT NULL,\n `devicebatterytypes_id` int NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `devicebatterymodels_id` int DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `designation` (`designation`),\n KEY `manufacturers_id` (`manufacturers_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n KEY `devicebatterymodels_id` (`devicebatterymodels_id`),\n KEY `devicebatterytypes_id` (`devicebatterytypes_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicebatteries\");\n }\n\n if (!$DB->tableExists('glpi_items_devicebatteries')) {\n $query = \"CREATE TABLE `glpi_items_devicebatteries` (\n `id` int NOT NULL AUTO_INCREMENT,\n `items_id` int NOT NULL DEFAULT '0',\n `itemtype` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `devicebatteries_id` int NOT NULL DEFAULT '0',\n `manufacturing_date` date DEFAULT NULL,\n `is_deleted` tinyint NOT NULL DEFAULT '0',\n `is_dynamic` tinyint NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `serial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `otherserial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `locations_id` int NOT NULL DEFAULT '0',\n `states_id` int NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `computers_id` (`items_id`),\n KEY `devicebatteries_id` (`devicebatteries_id`),\n KEY `is_deleted` (`is_deleted`),\n KEY `is_dynamic` (`is_dynamic`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `serial` (`serial`),\n KEY `item` (`itemtype`,`items_id`),\n KEY `otherserial` (`otherserial`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_devicebatteries\");\n }\n\n if (!$DB->tableExists('glpi_devicebatterytypes')) {\n $query = \"CREATE TABLE `glpi_devicebatterytypes` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicebatterytypes\");\n }\n\n if (!$DB->tableExists('glpi_devicefirmwares')) {\n $query = \"CREATE TABLE `glpi_devicefirmwares` (\n `id` int NOT NULL AUTO_INCREMENT,\n `designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `manufacturers_id` int NOT NULL DEFAULT '0',\n `date` date DEFAULT NULL,\n `version` varchar(255) DEFAULT NULL,\n `devicefirmwaretypes_id` int NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `devicefirmwaremodels_id` int DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `designation` (`designation`),\n KEY `manufacturers_id` (`manufacturers_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n KEY `devicefirmwaremodels_id` (`devicefirmwaremodels_id`),\n KEY `devicefirmwaretypes_id` (`devicefirmwaretypes_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicefirmwares\");\n }\n if (!$DB->tableExists('glpi_items_devicefirmwares')) {\n $query = \"CREATE TABLE `glpi_items_devicefirmwares` (\n `id` int NOT NULL AUTO_INCREMENT,\n `items_id` int NOT NULL DEFAULT '0',\n `itemtype` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `devicefirmwares_id` int NOT NULL DEFAULT '0',\n `is_deleted` tinyint NOT NULL DEFAULT '0',\n `is_dynamic` tinyint NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `serial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `otherserial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `locations_id` int NOT NULL DEFAULT '0',\n `states_id` int NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `computers_id` (`items_id`),\n KEY `devicefirmwares_id` (`devicefirmwares_id`),\n KEY `is_deleted` (`is_deleted`),\n KEY `is_dynamic` (`is_dynamic`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `serial` (`serial`),\n KEY `item` (`itemtype`,`items_id`),\n KEY `otherserial` (`otherserial`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_devicefirmwares\");\n }\n if (!$DB->tableExists('glpi_devicefirmwaretypes')) {\n $query = \"CREATE TABLE `glpi_devicefirmwaretypes` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicefirmwaretypes\");\n\n $DB->insertOrDie(\"glpi_devicefirmwaretypes\", [\n 'id' => \"1\",\n 'name' => \"BIOS\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n\n $DB->insertOrDie(\"glpi_devicefirmwaretypes\", [\n 'id' => \"2\",\n 'name' => \"UEFI\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n\n $DB->insertOrDie(\"glpi_devicefirmwaretypes\", [\n 'id' => \"3\",\n 'name' => \"Firmware\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n }\n\n //Device sensors\n if (!$DB->tableExists('glpi_devicesensors')) {\n $query = \"CREATE TABLE `glpi_devicesensors` (\n `id` int NOT NULL AUTO_INCREMENT,\n `designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `devicesensortypes_id` int NOT NULL DEFAULT '0',\n `devicesensormodels_id` int NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `manufacturers_id` int NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `locations_id` int NOT NULL DEFAULT '0',\n `states_id` int NOT NULL DEFAULT '0',\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `designation` (`designation`),\n KEY `manufacturers_id` (`manufacturers_id`),\n KEY `devicesensortypes_id` (`devicesensortypes_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `locations_id` (`locations_id`),\n KEY `states_id` (`states_id`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicesensors\");\n }\n\n if (!$DB->tableExists('glpi_items_devicesensors')) {\n $query = \"CREATE TABLE `glpi_items_devicesensors` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `items_id` INT NOT NULL DEFAULT '0',\n `itemtype` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `devicesensors_id` INT NOT NULL DEFAULT '0',\n `is_deleted` TINYINT NOT NULL DEFAULT '0',\n `is_dynamic` TINYINT NOT NULL DEFAULT '0',\n `entities_id` INT NOT NULL DEFAULT '0',\n `is_recursive` TINYINT NOT NULL DEFAULT '0',\n `serial` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `otherserial` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `locations_id` INT NOT NULL DEFAULT '0',\n `states_id` INT NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n INDEX `computers_id` (`items_id`),\n INDEX `devicesensors_id` (`devicesensors_id`),\n INDEX `is_deleted` (`is_deleted`),\n INDEX `is_dynamic` (`is_dynamic`),\n INDEX `entities_id` (`entities_id`),\n INDEX `is_recursive` (`is_recursive`),\n INDEX `serial` (`serial`),\n INDEX `item` (`itemtype`, `items_id`),\n INDEX `otherserial` (`otherserial`)\n )\n COLLATE='utf8_unicode_ci'\n ENGINE=InnoDB;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_devicesensors\");\n }\n\n if (!$DB->tableExists('glpi_devicesensortypes')) {\n $query = \"CREATE TABLE `glpi_devicesensortypes` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',\n `comment` TEXT NULL COLLATE 'utf8_unicode_ci',\n PRIMARY KEY (`id`),\n INDEX `name` (`name`)\n )\n COLLATE='utf8_unicode_ci' ENGINE=InnoDB;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicesensortypes\");\n }\n\n //Father/son for Software licenses\n $migration->addField(\"glpi_softwarelicenses\", \"softwarelicenses_id\", \"integer\", ['after' => 'softwares_id']);\n $new = $migration->addField(\"glpi_softwarelicenses\", \"completename\", \"text\", ['after' => 'softwarelicenses_id']);\n $migration->addField(\"glpi_softwarelicenses\", \"level\", \"integer\", ['after' => 'completename']);\n $migration->migrationOneTable(\"glpi_softwarelicenses\");\n if ($new) {\n $DB->updateOrDie(\n \"glpi_softwarelicenses\",\n [\n 'completename' => new QueryExpression(DBmysql::quoteName(\"name\"))\n ],\n [true],\n \"9.2 copy name to completename for software licenses\"\n );\n }\n\n // add template key to itiltasks\n $migration->addField(\"glpi_tickettasks\", \"tasktemplates_id\", \"integer\");\n $migration->migrationOneTable('glpi_tickettasks');\n $migration->addKey(\"glpi_tickettasks\", \"tasktemplates_id\");\n\n $migration->addField(\"glpi_problemtasks\", \"tasktemplates_id\", \"integer\");\n $migration->migrationOneTable('glpi_problemtasks');\n $migration->addKey(\"glpi_problemtasks\", \"tasktemplates_id\");\n\n $migration->addField(\"glpi_changetasks\", \"tasktemplates_id\", \"integer\");\n $migration->migrationOneTable('glpi_changetasks');\n $migration->addKey(\"glpi_changetasks\", \"tasktemplates_id\");\n\n // add missing fields to tasktemplate\n $migration->addField(\"glpi_tasktemplates\", \"state\", \"integer\");\n $migration->addField(\"glpi_tasktemplates\", \"is_private\", \"bool\");\n $migration->addField(\"glpi_tasktemplates\", \"users_id_tech\", \"integer\");\n $migration->addField(\"glpi_tasktemplates\", \"groups_id_tech\", \"integer\");\n $migration->migrationOneTable('glpi_tasktemplates');\n $migration->addKey(\"glpi_tickettasks\", \"is_private\");\n $migration->addKey(\"glpi_tickettasks\", \"users_id_tech\");\n $migration->addKey(\"glpi_tickettasks\", \"groups_id_tech\");\n\n // #1735 - Add new notifications\n $notification = new Notification();\n $notificationtarget = new NotificationTarget();\n $new_notifications = [\n 'requester_user' => ['label' => 'New user in requesters',\n 'targets_id' => Notification::AUTHOR\n ],\n 'requester_group' => ['label' => 'New group in requesters',\n 'targets_id' => Notification::REQUESTER_GROUP\n ],\n 'observer_user' => ['label' => 'New user in observers',\n 'targets_id' => Notification::OBSERVER\n ],\n 'observer_group' => ['label' => 'New group in observers',\n 'targets_id' => Notification::OBSERVER_GROUP\n ],\n 'assign_user' => ['label' => 'New user in assignees',\n 'targets_id' => Notification::ASSIGN_TECH\n ],\n 'assign_group' => ['label' => 'New group in assignees',\n 'targets_id' => Notification::ITEM_TECH_GROUP_IN_CHARGE\n ],\n 'assign_supplier' => ['label' => 'New supplier in assignees',\n 'targets_id' => Notification::SUPPLIER\n ],\n ];\n\n if ($DB->fieldExists(\"glpi_notifications\", \"mode\", false)) {\n $notificationtemplates_id = 0;\n $notificationtemplate = new NotificationTemplate();\n if ($notificationtemplate->getFromDBByCrit(['name' => 'Tickets', 'itemtype' => 'Ticket'])) {\n $notificationtemplates_id = $notificationtemplate->fields['id'];\n }\n\n foreach ($new_notifications as $event => $notif_options) {\n $notifications_id = $notification->add([\n 'name' => $notif_options['label'],\n 'itemtype' => 'Ticket',\n 'event' => $event,\n 'mode' => Notification_NotificationTemplate::MODE_MAIL,\n 'notificationtemplates_id' => $notificationtemplates_id,\n 'is_recursive' => 1,\n 'is_active' => 0,\n ]);\n\n $notificationtarget->add([\n 'items_id' => $notif_options['targets_id'],\n 'type' => 1,\n 'notifications_id' => $notifications_id,\n ]);\n }\n }\n\n $migration->addField('glpi_states', 'is_visible_certificate', 'bool', ['value' => 1]);\n $migration->addKey('glpi_states', 'is_visible_certificate');\n\n /** ************ New SLM structure ************ */\n if (!$DB->tableExists('glpi_olas')) {\n $query = \"CREATE TABLE `glpi_olas` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `type` int NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `number_time` int NOT NULL,\n `calendars_id` int NOT NULL DEFAULT '0',\n `date_mod` datetime DEFAULT NULL,\n `definition_time` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `end_of_working_day` tinyint NOT NULL DEFAULT '0',\n `date_creation` datetime DEFAULT NULL,\n `slms_id` int NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `calendars_id` (`calendars_id`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n KEY `slms_id` (`slms_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_olas\");\n }\n\n if (!$DB->tableExists('glpi_olalevelactions')) {\n $query = \"CREATE TABLE `glpi_olalevelactions` (\n `id` int NOT NULL AUTO_INCREMENT,\n `olalevels_id` int NOT NULL DEFAULT '0',\n `action_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `field` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `olalevels_id` (`olalevels_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_olalevelactions\");\n }\n\n if (!$DB->tableExists('glpi_olalevelcriterias')) {\n $query = \"CREATE TABLE `glpi_olalevelcriterias` (\n `id` int NOT NULL AUTO_INCREMENT,\n `olalevels_id` int NOT NULL DEFAULT '0',\n `criteria` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `condition` int NOT NULL DEFAULT '0' COMMENT 'see define.php PATTERN_* and REGEX_* constant',\n `pattern` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `olalevels_id` (`olalevels_id`),\n KEY `condition` (`condition`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_olalevelcriterias\");\n }\n\n if (!$DB->tableExists('glpi_olalevels')) {\n $query = \"CREATE TABLE `glpi_olalevels` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `olas_id` int NOT NULL DEFAULT '0',\n `execution_time` int NOT NULL,\n `is_active` tinyint NOT NULL DEFAULT '1',\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `match` char(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'see define.php *_MATCHING constant',\n `uuid` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `is_active` (`is_active`),\n KEY `olas_id` (`olas_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_olalevels\");\n }\n\n if (!$DB->tableExists('glpi_olalevels_tickets')) {\n $query = \"CREATE TABLE `glpi_olalevels_tickets` (\n `id` int NOT NULL AUTO_INCREMENT,\n `tickets_id` int NOT NULL DEFAULT '0',\n `olalevels_id` int NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `tickets_id` (`tickets_id`),\n KEY `olalevels_id` (`olalevels_id`),\n KEY `unicity` (`tickets_id`,`olalevels_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_olalevels_tickets\");\n\n $DB->updateOrInsert(\"glpi_crontasks\", [\n 'frequency' => \"604800\",\n 'param' => null,\n 'state' => \"1\",\n 'mode' => \"1\",\n 'allowmode' => \"3\",\n 'hourmin' => \"0\",\n 'hourmax' => \"24\",\n 'logs_lifetime' => \"30\",\n 'lastrun' => null,\n 'lastcode' => null,\n 'comment' => null\n ], [\n 'itemtype' => \"OlaLevel_Ticket\",\n 'name' => \"olaticket\"\n ]);\n }\n\n if (!$DB->tableExists('glpi_slms')) {\n // Changing the structure of the table 'glpi_slas'\n $migration->renameTable('glpi_slas', 'glpi_slms');\n $migration->migrationOneTable('glpi_slas');\n }\n\n // Changing the structure of the table 'glpi_slts'\n if ($DB->tableExists('glpi_slts')) {\n $migration->renameTable('glpi_slts', 'glpi_slas');\n $migration->migrationOneTable('glpi_slts');\n $migration->changeField('glpi_slas', 'slas_id', 'slms_id', 'integer');\n $migration->dropKey('glpi_slas', 'slas_id');\n $migration->addKey('glpi_slas', 'slms_id');\n }\n\n // Slalevels changes\n if ($DB->fieldExists(\"glpi_slalevels\", \"slts_id\")) {\n $migration->changeField('glpi_slalevels', 'slts_id', 'slas_id', 'integer');\n $migration->migrationOneTable('glpi_slalevels');\n $migration->dropKey('glpi_slalevels', 'slts_id');\n $migration->addKey('glpi_slalevels', 'slas_id');\n }\n\n // Ticket changes\n if (!$DB->fieldExists(\"glpi_tickets\", \"ola_waiting_duration\", false)) {\n $migration->addField(\n \"glpi_tickets\",\n \"ola_waiting_duration\",\n \"integer\",\n ['after' => 'sla_waiting_duration']\n );\n $migration->migrationOneTable('glpi_tickets');\n }\n\n if (!$DB->fieldExists(\"glpi_tickets\", \"olas_tto_id\", false)) {\n $migration->addField(\"glpi_tickets\", \"olas_tto_id\", \"integer\", ['after' => 'ola_waiting_duration']);\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'olas_tto_id');\n }\n\n if (!$DB->fieldExists(\"glpi_tickets\", \"olas_ttr_id\", false)) {\n $migration->addField(\"glpi_tickets\", \"olas_ttr_id\", \"integer\", ['after' => 'olas_tto_id']);\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'olas_ttr_id');\n }\n\n if (!$DB->fieldExists(\"glpi_tickets\", \"ttr_olalevels_id\", false)) {\n $migration->addField(\"glpi_tickets\", \"ttr_olalevels_id\", \"integer\", ['after' => 'olas_ttr_id']);\n $migration->migrationOneTable('glpi_tickets');\n }\n\n if (!$DB->fieldExists(\"glpi_tickets\", \"internal_time_to_resolve\", false)) {\n $migration->addField(\n \"glpi_tickets\",\n \"internal_time_to_resolve\",\n \"datetime\",\n ['after' => 'ttr_olalevels_id']\n );\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'internal_time_to_resolve');\n }\n\n if (!$DB->fieldExists(\"glpi_tickets\", \"internal_time_to_own\", false)) {\n $migration->addField(\n \"glpi_tickets\",\n \"internal_time_to_own\",\n \"datetime\",\n ['after' => 'internal_time_to_resolve']\n );\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'internal_time_to_own');\n }\n\n if ($DB->fieldExists(\"glpi_tickets\", \"slts_tto_id\")) {\n $migration->changeField(\"glpi_tickets\", \"slts_tto_id\", \"slas_tto_id\", \"integer\");\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'slas_tto_id');\n $migration->dropKey('glpi_tickets', 'slts_tto_id');\n }\n\n if ($DB->fieldExists(\"glpi_tickets\", \"slts_ttr_id\")) {\n $migration->changeField(\"glpi_tickets\", \"slts_ttr_id\", \"slas_ttr_id\", \"integer\");\n $migration->migrationOneTable('glpi_tickets');\n $migration->addKey('glpi_tickets', 'slas_ttr_id');\n $migration->dropKey('glpi_tickets', 'slts_ttr_id');\n }\n if ($DB->fieldExists(\"glpi_tickets\", \"due_date\")) {\n $migration->changeField('glpi_tickets', 'due_date', 'time_to_resolve', 'datetime');\n $migration->migrationOneTable('glpi_tickets');\n $migration->dropKey('glpi_tickets', 'due_date');\n $migration->addKey('glpi_tickets', 'time_to_resolve');\n }\n\n //Change changes\n if ($DB->fieldExists(\"glpi_changes\", \"due_date\")) {\n $migration->changeField('glpi_changes', 'due_date', 'time_to_resolve', 'datetime');\n $migration->migrationOneTable('glpi_changes');\n $migration->dropKey('glpi_changes', 'due_date');\n $migration->addKey('glpi_changes', 'time_to_resolve');\n }\n\n //Problem changes\n if ($DB->fieldExists(\"glpi_problems\", \"due_date\")) {\n $migration->changeField('glpi_problems', 'due_date', 'time_to_resolve', 'datetime');\n $migration->migrationOneTable('glpi_problems');\n $migration->dropKey('glpi_problems', 'due_date');\n $migration->addKey('glpi_problems', 'time_to_resolve');\n }\n\n // ProfileRights changes\n $DB->updateOrDie(\n \"glpi_profilerights\",\n ['name' => \"slm\"],\n ['name' => \"sla\"],\n \"SLM profilerights migration\"\n );\n\n //Sla rules criterias migration\n $DB->updateOrDie(\n \"glpi_rulecriterias\",\n ['criteria' => \"slas_ttr_id\"],\n ['criteria' => \"slts_ttr_id\"],\n \"SLA rulecriterias migration\"\n );\n\n $DB->updateOrDie(\n \"glpi_rulecriterias\",\n ['criteria' => \"slas_tto_id\"],\n ['criteria' => \"slts_tto_id\"],\n \"SLA rulecriterias migration\"\n );\n\n // Sla rules actions migration\n $DB->updateOrDie(\n \"glpi_ruleactions\",\n ['field' => \"slas_ttr_id\"],\n ['field' => \"slts_ttr_id\"],\n \"SLA ruleactions migration\"\n );\n\n $DB->updateOrDie(\n \"glpi_ruleactions\",\n ['field' => \"slas_tto_id\"],\n ['field' => \"slts_tto_id\"],\n \"SLA ruleactions migration\"\n );\n\n /************** Auto login **************/\n $migration->addConfig([\n 'login_remember_time' => 604800,\n 'login_remember_default' => 1\n ]);\n\n if ($DB->tableExists('glpi_bookmarks')) {\n $migration->renameTable(\"glpi_bookmarks\", \"glpi_savedsearches\");\n\n $migration->addField(\"glpi_savedsearches\", \"last_execution_time\", \"int NULL DEFAULT NULL\");\n $migration->addField(\n \"glpi_savedsearches\",\n \"do_count\",\n \"tinyint NOT NULL DEFAULT '2' COMMENT 'Do or do not count results on list display; see SavedSearch::COUNT_* constants'\"\n );\n $migration->addField(\n \"glpi_savedsearches\",\n \"last_execution_date\",\n \"DATETIME NULL DEFAULT NULL\"\n );\n $migration->addField(\"glpi_savedsearches\", \"counter\", \"int NOT NULL DEFAULT '0'\");\n $migration->migrationOneTable(\"glpi_savedsearches\");\n $migration->addKey(\"glpi_savedsearches\", 'last_execution_time');\n $migration->addKey(\"glpi_savedsearches\", 'do_count');\n $migration->addKey(\"glpi_savedsearches\", 'last_execution_date');\n }\n //ensure do_count is set to AUTO\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_savedsearches\",\n ['do_count' => SavedSearch::COUNT_AUTO],\n [new QueryExpression('true')]\n ),\n 'Set count auto on saved searches'\n );\n\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_savedsearches\",\n ['entities_id' => 0],\n ['entities_id' => -1]\n ),\n 'Update entities_id in saved searches'\n );\n\n if (\n !countElementsInTable(\n 'glpi_rules',\n ['sub_type' => 'RuleSoftwareCategory',\n 'uuid' => '500717c8-2bd6e957-53a12b5fd38869.86003425'\n ]\n )\n ) {\n $rule = new Rule();\n $rules_id = $rule->add(['name' => 'Import category from inventory tool',\n 'is_active' => 0,\n 'uuid' => '500717c8-2bd6e957-53a12b5fd38869.86003425',\n 'entities_id' => 0,\n 'is_recursive' => 1,\n 'sub_type' => 'RuleSoftwareCategory',\n 'match' => Rule::AND_MATCHING,\n 'condition' => 1,\n 'description' => ''\n ]);\n if ($rules_id) {\n $criteria = new RuleCriteria();\n $criteria->add(['rules_id' => $rules_id,\n 'criteria' => 'name',\n 'condition' => '0',\n 'pattern' => '*'\n ]);\n\n $action = new RuleAction();\n $action->add(['rules_id' => $rules_id,\n 'action_type' => 'assign',\n 'field' => '_import_category',\n 'value' => '1'\n ]);\n }\n }\n\n if ($DB->tableExists('glpi_queuedmails')) {\n $migration->renameTable(\"glpi_queuedmails\", \"glpi_queuednotifications\");\n }\n\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_crontasks\",\n ['itemtype' => \"QueuedNotification\"],\n ['itemtype' => \"QueuedMail\"]\n )\n );\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_crontasks\",\n ['name' => \"queuednotification\"],\n ['name' => \"queuedmail\"]\n )\n );\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_crontasks\",\n ['name' => \"queuednotificationclean\"],\n ['name' => \"queuedmailclean\"]\n )\n );\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_profilerights\",\n ['name' => \"queuednotification\"],\n ['name' => \"queuedmail\"]\n )\n );\n\n if (isset($current_config['use_mailing']) && !isset($current_config['use_notifications'])) {\n /** Notifications modes */\n $migration->addConfig([\n 'use_notifications' => $current_config['use_mailing'],\n 'notifications_mailing' => $current_config['use_mailing'],\n 'notifications_ajax' => 0,\n 'notifications_ajax_check_interval' => '5',\n 'notifications_ajax_sound' => null,\n 'notifications_ajax_icon_url' => '/pics/glpi.png'\n ]);\n }\n\n if (!$DB->tableExists('glpi_notifications_notificationtemplates')) {\n $query = \"CREATE TABLE `glpi_notifications_notificationtemplates` (\n `id` int NOT NULL AUTO_INCREMENT,\n `notifications_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `mode` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT 'See Notification_NotificationTemplate::MODE_* constants',\n `notificationtemplates_id` int NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`notifications_id`, `mode`, `notificationtemplates_id`),\n KEY `notifications_id` (`notifications_id`),\n KEY `notificationtemplates_id` (`notificationtemplates_id`),\n KEY `mode` (`mode`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_notifications_notificationtemplates\");\n }\n\n if ($DB->fieldExists(\"glpi_notifications\", \"mode\", false)) {\n // TODO can be done when DB::updateOrInsert() supports SELECT\n $query = \"REPLACE INTO `glpi_notifications_notificationtemplates`\n (`notifications_id`, `mode`, `notificationtemplates_id`)\n SELECT `id`, `mode`, `notificationtemplates_id`\n FROM `glpi_notifications`\";\n $DB->doQueryOrDie($query, \"9.2 migrate notifications templates\");\n\n //migrate any existing mode before removing the field\n $migration->dropField('glpi_notifications', 'mode');\n $migration->dropField('glpi_notifications', 'notificationtemplates_id');\n\n $migration->migrationOneTable(\"glpi_notifications\");\n }\n\n $migration->addField(\n 'glpi_queuednotifications',\n 'mode',\n 'varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT \\'See Notification_NotificationTemplate::MODE_* constants\\''\n );\n $migration->migrationOneTable(\"glpi_queuednotifications\");\n $migration->addKey('glpi_queuednotifications', 'mode');\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_queuednotifications\",\n ['mode' => Notification_NotificationTemplate::MODE_MAIL],\n [true]\n ),\n \"9.2 set default mode in queue\"\n );\n\n $migration->addPostQuery(\n $DB->buildUpdate(\n \"glpi_notifications_notificationtemplates\",\n ['mode' => Notification_NotificationTemplate::MODE_MAIL],\n ['mode' => \"mail\"]\n ),\n \"9.2 set default mode in notifications templates\"\n );\n\n // Migration Bookmark -> SavedSearch_Alert\n //TRANS: %s is the table or item to migrate\n if ($DB->tableExists('glpi_bookmarks_users')) {\n $migration->renameTable(\"glpi_bookmarks_users\", \"glpi_savedsearches_users\");\n $migration->changeField(\n 'glpi_savedsearches_users',\n 'bookmarks_id',\n 'savedsearches_id',\n 'int NOT NULL DEFAULT \"0\"'\n );\n }\n\n if (!$DB->tableExists('glpi_savedsearches_alerts')) {\n $query = \"CREATE TABLE `glpi_savedsearches_alerts` (\n `id` int NOT NULL AUTO_INCREMENT,\n `savedsearches_id` int NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `is_active` tinyint NOT NULL DEFAULT '0',\n `operator` tinyint NOT NULL,\n `value` int NOT NULL,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `is_active` (`is_active`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n UNIQUE KEY `unicity` (`savedsearches_id`,`operator`, `value`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_savedsearches_alerts\");\n }\n\n $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));\n\n $ADDTODISPLAYPREF['SavedSearch'] = [8, 9, 3, 10, 11];\n foreach ($ADDTODISPLAYPREF as $type => $tab) {\n $rank = 1;\n foreach ($tab as $newval) {\n $DB->updateOrInsert(\"glpi_displaypreferences\", [\n 'rank' => $rank++\n ], [\n 'users_id' => \"0\",\n 'itemtype' => $type,\n 'num' => $newval,\n ]);\n }\n }\n\n if (countElementsInTable('glpi_logs') < 2000000) {\n //add index only if this sounds... possible.\n $migration->addKey(\"glpi_logs\", \"id_search_option\");\n } else {\n //Just display a Warning to the user.\n $migration->displayWarning(\"An index must be added in the 'id_search_option' field \" .\n \"of the 'glpi_logs table'; but your glpi_logs table is \" .\n \"too huge. You'll have to add it on your database \" .\n \"with the following query:\\n\" .\n \"'ALTER TABLE glpi_logs ADD INDEX id_search_option(id_search_option);'\");\n }\n\n // count cron task\n if (\n !countElementsInTable(\n 'glpi_crontasks',\n ['itemtype' => 'SavedSearch', 'name' => 'countAll']\n )\n ) {\n $DB->insertOrDie(\n \"glpi_crontasks\",\n [\n 'itemtype' => \"SavedSearch\",\n 'name' => \"countAll\",\n 'frequency' => \"604800\",\n 'param' => null,\n 'state' => \"0\",\n 'mode' => \"1\",\n 'allowmode' => \"3\",\n 'hourmin' => \"0\",\n 'hourmax' => \"24\",\n 'logs_lifetime' => \"30\",\n 'lastrun' => null,\n 'lastcode' => null,\n 'comment' => null\n ],\n \"9.2 Add countAll SavedSearch cron task\"\n );\n };\n\n // alerts cron task\n if (\n !countElementsInTable(\n 'glpi_crontasks',\n ['itemtype' => 'SavedSearch_Alert', 'name' => 'savedsearchesalerts']\n )\n ) {\n $DB->insertOrDie(\n \"glpi_crontasks\",\n [\n 'itemtype' => \"SavedSearch_Alert\",\n 'name' => \"savedsearchesalerts\",\n 'frequency' => \"86400\",\n 'param' => null,\n 'state' => \"0\",\n 'mode' => \"1\",\n 'allowmode' => \"3\",\n 'hourmin' => \"0\",\n 'hourmax' => \"24\",\n 'logs_lifetime' => \"30\",\n 'lastrun' => null,\n 'lastcode' => null,\n 'comment' => null\n ],\n \"9.2 Add saved searches alerts cron task\"\n );\n }\n\n if (\n !countElementsInTable(\n 'glpi_notifications',\n ['itemtype' => 'SavedSearch_Alert']\n )\n ) {\n $DB->insertOrDie(\n \"glpi_notifications\",\n [\n 'id' => null,\n 'name' => \"Saved searches\",\n 'entities_id' => \"0\",\n 'itemtype' => \"SavedSearch_Alert\",\n 'event' => \"alert\",\n 'comment' => \"\",\n 'is_recursive' => \"1\",\n 'is_active' => \"1\",\n 'date_creation' => new QueryExpression(\"NOW()\"),\n 'date_mod' => new QueryExpression(\"NOW()\")\n ],\n \"9.2 Add saved search alerts notification\"\n );\n $notid = $DB->insertId();\n\n $DB->insertOrDie(\n \"glpi_notificationtemplates\",\n [\n 'name' => \"Saved searches alerts\",\n 'itemtype' => \"SavedSearch_Alert\",\n 'date_mod' => new QueryExpression(\"NOW()\")\n ],\n \"9.2 Add saved search alerts notification template\"\n );\n $nottid = $DB->insertId();\n\n $where = [\n 'notifications_id' => $notid,\n 'mode' => Notification_NotificationTemplate::MODE_MAIL,\n 'notificationtemplates_id' => $nottid\n ];\n if (countElementsInTable('glpi_notifications_notificationtemplates', $where)) {\n $DB->updateOrInsert(\"glpi_notifications_notificationtemplates\", [\n 'id' => null\n ], [\n 'notifications_id' => $notid,\n 'mode' => Notification_NotificationTemplate::MODE_MAIL,\n 'notificationtemplates_id' => $nottid\n ]);\n }\n\n $DB->insertOrDie(\n \"glpi_notificationtargets\",\n [\n 'id' => null,\n 'items_id' => \"19\",\n 'type' => \"1\",\n 'notifications_id' => $notid\n ],\n \"9.2 Add saved search alerts notification targets\"\n );\n\n $query = \"INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`,`subject`,\n `content_text`,\n `content_html`)\n VALUES ($notid, '', '##savedsearch.action## ##savedsearch.name##',\n '##savedsearch.type## ###savedsearch.id## - ##savedsearch.name##\n\n##savedsearch.message##\n\n##lang.savedsearch.url##\n##savedsearch.url##\n\nRegards,',\n '&lt;table&gt;\n &lt;tbody&gt;\n &lt;tr&gt;&lt;th colspan=\\\"2\\\"&gt;&lt;a href=\\\"##savedsearch.url##\\\"&gt;##savedsearch.type## ###savedsearch.id## - ##savedsearch.name##&lt;/a&gt;&lt;/th&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td colspan=\\\"2\\\"&gt;&lt;a href=\\\"##savedsearch.url##\\\"&gt;##savedsearch.message##&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;##lang.savedsearch.url##&lt;/td&gt;\n &lt;td&gt;##savedsearch.url##&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;p&gt;&lt;span style=\\\"font-size: small;\\\"&gt;Hello &lt;br /&gt;Regards,&lt;/span&gt;&lt;/p&gt;')\";\n\n $DB->doQueryOrDie($query, \"9.2 add saved searches alerts notification translation\");\n }\n\n // Create a dedicated token for api\n if (!$DB->fieldExists('glpi_users', 'api_token')) {\n $migration->addField('glpi_users', 'api_token', 'string', ['after' => 'personal_token_date']);\n $migration->addField('glpi_users', 'api_token_date', 'datetime', ['after' => 'api_token']);\n $migration->displayWarning(\n \"Api users tokens has been reset, if you use REST/XMLRPC api with personal token for authentication, please reset your user's token.\",\n true\n );\n }\n\n if (!$DB->tableExists('glpi_items_operatingsystems')) {\n $query = \"CREATE TABLE `glpi_items_operatingsystems` (\n `id` int NOT NULL AUTO_INCREMENT,\n `items_id` int NOT NULL DEFAULT '0',\n `itemtype` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `operatingsystems_id` int NOT NULL DEFAULT '0',\n `operatingsystemversions_id` int NOT NULL DEFAULT '0',\n `operatingsystemservicepacks_id` int NOT NULL DEFAULT '0',\n `operatingsystemarchitectures_id` int NOT NULL DEFAULT '0',\n `operatingsystemkernelversions_id` int NOT NULL DEFAULT '0',\n `license_number` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `license_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `operatingsystemeditions_id` int NOT NULL DEFAULT '0',\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `items_id` (`items_id`),\n KEY `item` (`itemtype`,`items_id`),\n KEY `operatingsystems_id` (`operatingsystems_id`),\n KEY `operatingsystemservicepacks_id` (`operatingsystemservicepacks_id`),\n KEY `operatingsystemversions_id` (`operatingsystemversions_id`),\n KEY `operatingsystemarchitectures_id` (`operatingsystemarchitectures_id`),\n KEY `operatingsystemkernelversions_id` (`operatingsystemkernelversions_id`),\n KEY `operatingsystemeditions_id` (`operatingsystemeditions_id`),\n UNIQUE KEY `unicity`(`items_id`,`itemtype`, `operatingsystems_id`,\n `operatingsystemarchitectures_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_operatingsystems\");\n }\n\n if (!$DB->tableExists('glpi_operatingsystemkernels')) {\n $query = \"CREATE TABLE `glpi_operatingsystemkernels` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_operatingsystemkernels\");\n }\n\n if (!$DB->tableExists('glpi_operatingsystemkernelversions')) {\n $query = \"CREATE TABLE `glpi_operatingsystemkernelversions` (\n `id` int NOT NULL AUTO_INCREMENT,\n `operatingsystemkernels_id` int NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `operatingsystemkernels_id` (`operatingsystemkernels_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_operatingsystemversions\");\n }\n\n if (!$DB->tableExists('glpi_operatingsystemeditions')) {\n $query = \"CREATE TABLE `glpi_operatingsystemeditions` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_operatingsystemeditions\");\n }\n\n if ($DB->fieldExists('glpi_computers', 'operatingsystems_id')) {\n //migrate data from computers table, and drop old fields\n // TODO can be done when DB::updateOrInsert() supports SELECT\n $query = \"REPLACE INTO `glpi_items_operatingsystems`\n (`itemtype`, `items_id`, `operatingsystems_id`, `operatingsystemversions_id`,\n `operatingsystemservicepacks_id`, `operatingsystemarchitectures_id`,\n `license_number`, `license_id`)\n SELECT 'Computer', `id`, `operatingsystems_id`, `operatingsystemversions_id`,\n `operatingsystemservicepacks_id`, `operatingsystemarchitectures_id`,\n `os_license_number`, `os_licenseid`\n FROM `glpi_computers`\n WHERE `operatingsystems_id` != 0\n OR `operatingsystemservicepacks_id` != 0\n OR `operatingsystemarchitectures_id` != 0\n OR `os_license_number` IS NOT NULL\n OR `os_kernel_version` IS NOT NULL\n OR `os_licenseid` IS NOT NULL\";\n $DB->doQueryOrDie($query, \"9.2 migrate main operating system information\");\n\n //migrate kernel versions.\n $kver = new OperatingSystemKernelVersion();\n $mapping = [];\n foreach (\n $DB->request(['SELECT' => ['id', 'os_kernel_version'],\n 'FROM' => 'glpi_computers',\n 'NOT' => ['os_kernel_version' => null]\n ]) as $data\n ) {\n $key = md5($data['os_kernel_version']);\n if (!isset($mapping[$key])) {\n $mapping[$key] = [];\n }\n $kver->add(['version' => $data['os_kernel_version']]);\n $mapping[$key][$data['id']] = $kver->getID();\n }\n\n foreach ($mapping as $map) {\n foreach ($map as $computers_id => $kver_id) {\n $DB->updateOrDie(\n \"glpi_items_operatingsystems\",\n ['operatingsystemkernelversions_id' => $kver_id],\n [\n 'itemtype' => \"Computer\",\n 'items_id' => $computers_id\n ]\n );\n }\n }\n\n $migration->dropKey('glpi_computers', 'operatingsystems_id');\n $migration->dropField('glpi_computers', 'operatingsystems_id');\n $migration->dropKey('glpi_computers', 'operatingsystemservicepacks_id');\n $migration->dropField('glpi_computers', 'operatingsystemservicepacks_id');\n $migration->dropKey('glpi_computers', 'operatingsystemversions_id');\n $migration->dropField('glpi_computers', 'operatingsystemversions_id');\n $migration->dropKey('glpi_computers', 'operatingsystemarchitectures_id');\n $migration->dropField('glpi_computers', 'operatingsystemarchitectures_id');\n $migration->dropField('glpi_computers', 'os_license_number');\n $migration->dropField('glpi_computers', 'os_licenseid');\n $migration->dropField('glpi_computers', 'os_kernel_version');\n }\n\n if (!$DB->fieldExists('glpi_items_operatingsystems', 'is_deleted')) {\n $migration->addField(\n 'glpi_items_operatingsystems',\n 'is_deleted',\n \"tinyint NOT NULL DEFAULT '0'\"\n );\n $migration->addKey('glpi_items_operatingsystems', 'is_deleted');\n }\n\n if (!$DB->fieldExists('glpi_items_operatingsystems', 'is_dynamic')) {\n $migration->addField(\n 'glpi_items_operatingsystems',\n 'is_dynamic',\n \"tinyint NOT NULL DEFAULT '0'\"\n );\n $migration->addKey('glpi_items_operatingsystems', 'is_dynamic');\n }\n\n if (!$DB->fieldExists('glpi_items_operatingsystems', 'entities_id')) {\n $migration->addField(\n 'glpi_items_operatingsystems',\n 'entities_id',\n \"int NOT NULL DEFAULT '0'\"\n );\n $migration->addKey('glpi_items_operatingsystems', 'entities_id');\n }\n\n //add db version\n $migration->addConfig(['dbversion' => '9.1.3']);\n\n // Add certificates management\n if (!$DB->tableExists('glpi_certificates')) {\n $query = \"CREATE TABLE `glpi_certificates` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `serial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `otherserial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `entities_id` INT NOT NULL DEFAULT '0',\n `is_recursive` TINYINT NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `is_deleted` tinyint NOT NULL DEFAULT '0',\n `is_template` tinyint NOT NULL DEFAULT '0',\n `template_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `certificatetypes_id` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_certificatetypes (id)',\n `dns_name` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `dns_suffix` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `users_id_tech` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_users (id)',\n `groups_id_tech` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_groups (id)',\n `locations_id` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_locations (id)',\n `manufacturers_id` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_manufacturers (id)',\n `users_id` int NOT NULL DEFAULT '0',\n `groups_id` int NOT NULL DEFAULT '0',\n `is_autosign` TINYINT NOT NULL DEFAULT '0',\n `date_expiration` DATE DEFAULT NULL,\n `states_id` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to states (id)',\n `command` TEXT COLLATE utf8_unicode_ci,\n `certificate_request` TEXT COLLATE utf8_unicode_ci,\n `certificate_item` TEXT COLLATE utf8_unicode_ci,\n `date_creation` DATETIME DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_template` (`is_template`),\n KEY `is_deleted` (`is_deleted`),\n KEY `certificatetypes_id` (`certificatetypes_id`),\n KEY `users_id_tech` (`users_id_tech`),\n KEY `groups_id_tech` (`groups_id_tech`),\n KEY `groups_id` (`groups_id`),\n KEY `users_id` (`users_id`),\n KEY `locations_id` (`locations_id`),\n KEY `manufacturers_id` (`manufacturers_id`),\n KEY `states_id` (`states_id`),\n KEY `date_creation` (`date_creation`),\n KEY `date_mod` (`date_mod`)\n ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 copy add certificate table\");\n }\n\n if (!$DB->tableExists('glpi_certificates_items')) {\n $query = \"CREATE TABLE `glpi_certificates_items` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `certificates_id` INT NOT NULL DEFAULT '0',\n `items_id` INT NOT NULL DEFAULT '0' COMMENT 'RELATION to various tables, according to itemtype (id)',\n `itemtype` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'see .class.php file',\n `date_creation` DATETIME DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`certificates_id`, `itemtype`, `items_id`),\n KEY `device` (`items_id`, `itemtype`),\n KEY `item` (`itemtype`, `items_id`),\n KEY `date_creation` (`date_creation`),\n KEY `date_mod` (`date_mod`)\n ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 copy add certificate items table\");\n }\n\n if (!$DB->tableExists('glpi_certificatetypes')) {\n $query = \"CREATE TABLE `glpi_certificatetypes` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `entities_id` INT NOT NULL DEFAULT '0',\n `is_recursive` TINYINT NOT NULL DEFAULT '0',\n `name` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` TEXT COLLATE utf8_unicode_ci,\n `date_creation` DATETIME DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `name` (`name`),\n KEY `date_creation` (`date_creation`),\n KEY `date_mod` (`date_mod`)\n ) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 copy add certificate type table\");\n }\n\n if (countElementsInTable(\"glpi_profilerights\", ['name' => 'certificate']) == 0) {\n //new right for certificate\n //give full rights to profiles having config right\n $prights = $DB->request(['FROM' => 'glpi_profilerights', 'WHERE' => ['name' => 'config']]);\n foreach ($prights as $profrights) {\n if ($profrights['rights'] && (READ + UPDATE)) {\n $rightValue = CREATE | READ | UPDATE | DELETE | PURGE | READNOTE | UPDATENOTE | UNLOCK;\n } else {\n $rightValue = 0;\n }\n\n $DB->insertOrDie(\n \"glpi_profilerights\",\n [\n 'id' => null,\n 'profiles_id' => $profrights['profiles_id'],\n 'name' => \"certificate\",\n 'rights' => $rightValue,\n ],\n \"9.2 add right for certificates\"\n );\n }\n }\n\n // add alert for certificates\n $migration->addField(\n \"glpi_entities\",\n 'use_certificates_alert',\n \"integer\",\n ['value' => -2,\n 'after' => 'send_licenses_alert_before_delay'\n ]\n );\n $migration->addField(\n \"glpi_entities\",\n 'send_certificates_alert_before_delay',\n \"integer\",\n ['value' => -2,\n 'after' => 'use_certificates_alert',\n 'update' => '0', // No delay for root entity\n 'condition' => 'WHERE `id` = 0'\n ]\n );\n CronTask::register(\n 'Certificate',\n 'certificate',\n DAY_TIMESTAMP,\n [\n 'comment' => '',\n 'mode' => CronTask::MODE_INTERNAL\n ]\n );\n if (!countElementsInTable('glpi_notifications', ['itemtype' => 'Certificate'])) {\n $DB->insertOrDie(\n \"glpi_notifications\",\n [\n 'id' => null,\n 'name' => \"Certificates\",\n 'entities_id' => \"0\",\n 'itemtype' => \"Certificate\",\n 'event' => \"alert\",\n 'comment' => \"\",\n 'is_recursive' => \"1\",\n 'is_active' => \"1\",\n 'date_creation' => new QueryExpression(\"NOW()\"),\n 'date_mod' => new QueryExpression(\"NOW()\")\n ],\n \"9.2 Add certificate alerts notification\"\n );\n $notid = $DB->insertId();\n\n $DB->insertOrDie(\n \"glpi_notificationtemplates\",\n [\n 'name' => \"Certificates\",\n 'itemtype' => \"Certificate\",\n 'date_mod' => new QueryExpression(\"NOW()\")\n ],\n \"9.2 Add certifcate alerts notification template\"\n );\n $nottid = $DB->insertId();\n\n $where = [\n 'notifications_id' => $notid,\n 'mode' => Notification_NotificationTemplate::MODE_MAIL,\n 'notificationtemplates_id' => $nottid\n ];\n if (!countElementsInTable('glpi_notifications_notificationtemplates', $where)) {\n $DB->updateOrInsert(\"glpi_notifications_notificationtemplates\", [\n 'id' => null\n ], [\n 'notifications_id' => $notid,\n 'mode' => Notification_NotificationTemplate::MODE_MAIL,\n 'notificationtemplates_id' => $nottid,\n ]);\n }\n\n $query = \"INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`, `content_text`, `content_html`)\n VALUES ($notid, '', '##certificate.action## ##certificate.entity##',\n '##lang.certificate.entity## : ##certificate.entity##\n\n##FOREACHcertificates##\n\n##lang.certificate.serial## : ##certificate.serial##\n\n##lang.certificate.expirationdate## : ##certificate.expirationdate##\n\n##certificate.url##\n ##ENDFOREACHcertificates##','&lt;p&gt;\n##lang.certificate.entity## : ##certificate.entity##&lt;br /&gt;\n##FOREACHcertificates##\n&lt;br /&gt;##lang.certificate.name## : ##certificate.name##&lt;br /&gt;\n##lang.certificate.serial## : ##certificate.serial##&lt;br /&gt;\n##lang.certificate.expirationdate## : ##certificate.expirationdate##\n&lt;br /&gt; &lt;a href=\\\"##certificate.url##\\\"&gt; ##certificate.url##\n&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHcertificates##&lt;/p&gt;')\";\n\n $DB->doQueryOrDie($query, \"9.2 add certificates alerts notification translation\");\n\n $DB->insertOrDie(\n \"glpi_notificationtargets\",\n [\n 'id' => null,\n 'notifications_id' => $notid,\n 'type' => Notification::USER_TYPE,\n 'items_id' => Notification::ITEM_TECH_IN_CHARGE\n ],\n \"9.2 add certificates alerts notification target\"\n );\n $DB->insertOrDie(\n \"glpi_notificationtargets\",\n [\n 'id' => null,\n 'notifications_id' => $notid,\n 'type' => Notification::USER_TYPE,\n 'items_id' => Notification::ITEM_TECH_GROUP_IN_CHARGE\n ],\n \"9.2 add certificates alerts notification target\"\n );\n }\n\n /************** Simcard component **************/\n $migration->addField(\"glpi_states\", \"is_visible_line\", \"bool\", [\"after\" => \"is_visible_softwarelicense\"]);\n\n if (!$DB->tableExists('glpi_lineoperators')) {\n $query = \"CREATE TABLE IF NOT EXISTS `glpi_lineoperators` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) NOT NULL DEFAULT '',\n `comment` text COLLATE utf8_unicode_ci,\n `mcc` int DEFAULT NULL,\n `mnc` int DEFAULT NULL,\n `entities_id` INT NOT NULL DEFAULT 0,\n `is_recursive` TINYINT NOT NULL DEFAULT 0,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n UNIQUE KEY `unicity` (`mcc`,`mnc`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_lineoperators\");\n }\n\n if (!$DB->tableExists('glpi_linetypes')) {\n $query = \"CREATE TABLE IF NOT EXISTS `glpi_linetypes` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_linetypes\");\n }\n\n if (!$DB->tableExists('glpi_lines')) {\n $query = \"CREATE TABLE `glpi_lines` (\n `id` INT NOT NULL auto_increment,\n `name` VARCHAR(255) NOT NULL DEFAULT '',\n `entities_id` INT NOT NULL DEFAULT 0,\n `is_recursive` TINYINT NOT NULL DEFAULT 0,\n `is_deleted` TINYINT NOT NULL DEFAULT 0,\n `caller_num` VARCHAR(255) NOT NULL DEFAULT '',\n `caller_name` VARCHAR(255) NOT NULL DEFAULT '',\n `users_id` INT NOT NULL DEFAULT 0,\n `groups_id` INT NOT NULL DEFAULT 0,\n `lineoperators_id` INT NOT NULL DEFAULT 0,\n `locations_id` INT NOT NULL DEFAULT '0',\n `states_id` INT NOT NULL DEFAULT '0',\n `linetypes_id` INT NOT NULL DEFAULT '0',\n `date_creation` DATETIME DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n `comment` TEXT DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `users_id` (`users_id`),\n KEY `lineoperators_id` (`lineoperators_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_lines\");\n }\n\n if (!$DB->tableExists('glpi_devicesimcardtypes')) {\n $query = \"CREATE TABLE IF NOT EXISTS `glpi_devicesimcardtypes` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(255) NOT NULL DEFAULT '',\n `comment` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicesimcardtypes\");\n }\n\n if (!countElementsInTable('glpi_devicesimcardtypes', ['name' => 'Full SIM'])) {\n $DB->insertOrDie(\"glpi_devicesimcardtypes\", [\n 'id' => null,\n 'name' => \"Full SIM\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n }\n if (!countElementsInTable('glpi_devicesimcardtypes', ['name' => 'Mini SIM'])) {\n $DB->insertOrDie(\"glpi_devicesimcardtypes\", [\n 'id' => null,\n 'name' => \"Mini SIM\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n }\n if (!countElementsInTable('glpi_devicesimcardtypes', ['name' => 'Micro SIM'])) {\n $DB->insertOrDie(\"glpi_devicesimcardtypes\", [\n 'id' => null,\n 'name' => \"Micro SIM\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n }\n if (!countElementsInTable('glpi_devicesimcardtypes', ['name' => 'Nano SIM'])) {\n $DB->insertOrDie(\"glpi_devicesimcardtypes\", [\n 'id' => null,\n 'name' => \"Nano SIM\",\n 'comment' => null,\n 'date_mod' => null,\n 'date_creation' => null\n ]);\n }\n\n if (!$DB->tableExists('glpi_devicesimcards')) {\n $query = \"CREATE TABLE IF NOT EXISTS `glpi_devicesimcards` (\n `id` int NOT NULL AUTO_INCREMENT,\n `designation` varchar(255) DEFAULT NULL,\n `comment` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL,\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `manufacturers_id` int NOT NULL DEFAULT '0',\n `voltage` int DEFAULT NULL,\n `devicesimcardtypes_id` int NOT NULL DEFAULT '0',\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n `allow_voip` tinyint NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `designation` (`designation`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `devicesimcardtypes_id` (`devicesimcardtypes_id`),\n KEY `date_mod` (`date_mod`),\n KEY `date_creation` (`date_creation`),\n KEY `manufacturers_id` (`manufacturers_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_devicesimcards\");\n }\n\n if (!$DB->tableExists('glpi_items_devicesimcards')) {\n $query = \"CREATE TABLE IF NOT EXISTS `glpi_items_devicesimcards` (\n `id` int NOT NULL AUTO_INCREMENT,\n `items_id` int NOT NULL DEFAULT '0' COMMENT 'RELATION to various table, according to itemtype (id)',\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `devicesimcards_id` int NOT NULL DEFAULT '0',\n `is_deleted` tinyint NOT NULL DEFAULT '0',\n `is_dynamic` tinyint NOT NULL DEFAULT '0',\n `entities_id` int NOT NULL DEFAULT '0',\n `serial` varchar(255) NULL DEFAULT NULL,\n `otherserial` varchar(255) NULL DEFAULT NULL,\n `states_id` int NOT NULL DEFAULT '0',\n `locations_id` int NOT NULL DEFAULT '0',\n `lines_id` int NOT NULL DEFAULT '0',\n `pin` varchar(255) NOT NULL DEFAULT '',\n `pin2` varchar(255) NOT NULL DEFAULT '',\n `puk` varchar(255) NOT NULL DEFAULT '',\n `puk2` varchar(255) NOT NULL DEFAULT '',\n PRIMARY KEY (`id`),\n KEY `item` (`itemtype`,`items_id`),\n KEY `devicesimcards_id` (`devicesimcards_id`),\n KEY `is_deleted` (`is_deleted`),\n KEY `is_dynamic` (`is_dynamic`),\n KEY `entities_id` (`entities_id`),\n KEY `serial` (`serial`),\n KEY `otherserial` (`otherserial`),\n KEY `states_id` (`states_id`),\n KEY `locations_id` (`locations_id`),\n KEY `lines_id` (`lines_id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_items_devicesimcards\");\n }\n\n if (countElementsInTable(\"glpi_profilerights\", ['name' => 'line']) == 0) {\n //new right for line\n //give full rights to profiles having config right\n $prights = $DB->request(['FROM' => 'glpi_profilerights', 'WHERE' => ['name' => 'config']]);\n foreach ($prights as $profrights) {\n if ($profrights['rights'] && (READ + UPDATE)) {\n $rightValue = CREATE | READ | UPDATE | DELETE | PURGE | READNOTE | UPDATENOTE;\n } else {\n $rightValue = 0;\n }\n $DB->insertOrDie(\n \"glpi_profilerights\",\n [\n 'id' => null,\n 'profiles_id' => $profrights['profiles_id'],\n 'name' => \"line\",\n 'rights' => $rightValue\n ],\n \"9.2 add right for line\"\n );\n }\n }\n\n if (countElementsInTable(\"glpi_profilerights\", ['name' => 'lineoperator']) == 0) {\n //new right for lineoperator\n //give full rights to profiles having config right\n $prights = $DB->request(['FROM' => 'glpi_profilerights', 'WHERE' => ['name' => 'config']]);\n foreach ($prights as $profrights) {\n if ($profrights['rights'] && (READ + UPDATE)) {\n $rightValue = CREATE | READ | UPDATE | DELETE | PURGE;\n } else {\n $rightValue = 0;\n }\n $DB->insertOrDie(\n \"glpi_profilerights\",\n [\n 'id' => null,\n 'profiles_id' => $profrights['profiles_id'],\n 'name' => \"lineoperator\",\n 'rights' => $rightValue\n ],\n \"9.2 add right for lineoperator\"\n );\n }\n }\n\n if (countElementsInTable(\"glpi_profilerights\", ['name' => 'devicesimcard_pinpuk']) == 0) {\n //new right for simcard pin and puk\n //give full rights to profiles having config right\n $prights = $DB->request(['FROM' => 'glpi_profilerights', 'WHERE' => ['name' => 'config']]);\n foreach ($prights as $profrights) {\n if ($profrights['rights'] && (READ + UPDATE)) {\n $rightValue = READ | UPDATE;\n } else {\n $rightValue = 0;\n }\n $DB->insertOrDie(\n \"glpi_profilerights\",\n [\n 'id' => null,\n 'profiles_id' => $profrights['profiles_id'],\n 'name' => \"devicesimcard_pinpuk\",\n 'rights' => $rightValue\n ],\n \"9.2 add right for simcards pin and puk codes\"\n );\n }\n }\n\n //Firmware for phones\n if ($DB->fieldExists('glpi_phones', 'firmware')) {\n $iterator = $DB->request([\n 'SELECT' => ['id', 'firmware'],\n 'FROM' => 'glpi_phones',\n 'NOT' => ['firmware' => null]\n ]);\n\n $firmwares = [];\n foreach ($iterator as $row) {\n if (!isset($firmwares[$row['firmware']])) {\n $fw = new DeviceFirmware();\n if ($fw->getFromDBByCrit(['designation' => $row['firmware']])) {\n $firmwares[$row['firmware']] = $fw->getID();\n } else {\n $id = $fw->add([\n 'designation' => $row['firmware'],\n 'devicefirmwaretypes_id' => '3' //type \"firmware\"\n ]);\n $firmwares[$row['firmware']] = $id;\n }\n }\n\n //add link\n $item_fw = new Item_DeviceFirmware();\n $item_fw->add([\n 'itemtype' => 'Phone',\n 'items_id' => $row['id'],\n 'devicefirmwares_id' => $firmwares[$row['firmware']]\n ]);\n }\n\n $migration->dropField('glpi_phones', 'firmware');\n }\n\n //Firmware for network equipements\n if ($DB->tableExists('glpi_networkequipmentfirmwares')) {\n $mapping = [];\n $iterator = $DB->request(['FROM' => 'glpi_networkequipmentfirmwares']);\n foreach ($iterator as $row) {\n $fw = new DeviceFirmware();\n $id = $fw->add([\n 'designation' => $row['name'],\n 'comment' => $row['comment'],\n 'devicefirmwaretypes_id' => 3, //type \"Firmware\"\n 'date_creation' => $row['date_creation'],\n 'date_mod' => $row['date_mod']\n ]);\n $mapping[$row['id']] = $id;\n }\n\n $iterator = $DB->request(['FROM' => 'glpi_networkequipments']);\n foreach ($iterator as $row) {\n if (isset($mapping[$row['networkequipmentfirmwares_id']])) {\n $itemdevice = new Item_DeviceFirmware();\n $itemdevice->add([\n 'itemtype' => 'NetworkEquipment',\n 'items_id' => $row['id'],\n 'devicefirmwares_id' => $mapping[$row['networkequipmentfirmwares_id']]\n ]);\n }\n }\n\n $migration->dropKey('glpi_networkequipments', 'networkequipmentfirmwares_id');\n $migration->dropField('glpi_networkequipments', 'networkequipmentfirmwares_id');\n $migration->dropTable('glpi_networkequipmentfirmwares');\n }\n\n // add projecttemplate\n if (!$DB->fieldExists('glpi_projects', 'projecttemplates_id')) {\n $migration->addField(\"glpi_projects\", \"projecttemplates_id\", \"integer\");\n $migration->addField(\"glpi_projects\", \"is_template\", \"bool\");\n $migration->addField(\"glpi_projects\", \"template_name\", \"string\");\n $migration->addKey(\"glpi_projects\", \"projecttemplates_id\");\n }\n\n if (!$DB->fieldExists('glpi_projecttasks', 'projecttasktemplates_id')) {\n $migration->addField(\"glpi_projecttasks\", \"projecttasktemplates_id\", \"integer\");\n $migration->addField(\"glpi_projecttasks\", \"is_template\", \"bool\");\n $migration->addField(\"glpi_projecttasks\", \"template_name\", \"string\");\n $migration->addKey(\"glpi_projecttasks\", \"projecttasktemplates_id\");\n }\n\n if (!$DB->tableExists('glpi_projecttasktemplates')) {\n $query = \"CREATE TABLE `glpi_projecttasktemplates` (\n `id` int NOT NULL AUTO_INCREMENT,\n `entities_id` int NOT NULL DEFAULT '0',\n `is_recursive` tinyint NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `description` longtext COLLATE utf8_unicode_ci,\n `comment` longtext COLLATE utf8_unicode_ci,\n `projects_id` int NOT NULL DEFAULT '0',\n `projecttasks_id` int NOT NULL DEFAULT '0',\n `plan_start_date` datetime DEFAULT NULL,\n `plan_end_date` datetime DEFAULT NULL,\n `real_start_date` datetime DEFAULT NULL,\n `real_end_date` datetime DEFAULT NULL,\n `planned_duration` int NOT NULL DEFAULT '0',\n `effective_duration` int NOT NULL DEFAULT '0',\n `projectstates_id` int NOT NULL DEFAULT '0',\n `projecttasktypes_id` int NOT NULL DEFAULT '0',\n `users_id` int NOT NULL DEFAULT '0',\n `percent_done` int NOT NULL DEFAULT '0',\n `is_milestone` tinyint NOT NULL DEFAULT '0',\n `comments` text COLLATE utf8_unicode_ci,\n `date_mod` datetime DEFAULT NULL,\n `date_creation` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `projects_id` (`projects_id`),\n KEY `projecttasks_id` (`projecttasks_id`),\n KEY `date_creation` (`date_creation`),\n KEY `date_mod` (`date_mod`),\n KEY `users_id` (`users_id`),\n KEY `plan_start_date` (`plan_start_date`),\n KEY `plan_end_date` (`plan_end_date`),\n KEY `real_start_date` (`real_start_date`),\n KEY `real_end_date` (`real_end_date`),\n KEY `percent_done` (`percent_done`),\n KEY `projectstates_id` (`projectstates_id`),\n KEY `projecttasktypes_id` (`projecttasktypes_id`),\n KEY `is_milestone` (`is_milestone`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\";\n $DB->doQueryOrDie($query, \"9.2 add table glpi_projecttasktemplates\");\n }\n\n //add editor in followupps\n if (!$DB->fieldExists('glpi_ticketfollowups', 'users_id_editor')) {\n $migration->addField(\"glpi_ticketfollowups\", \"users_id_editor\", \"int NOT NULL DEFAULT '0'\", ['after' => 'users_id']);\n $migration->addKey(\"glpi_ticketfollowups\", \"users_id_editor\");\n }\n\n //add editor in *tasks\n if (!$DB->fieldExists('glpi_tickettasks', 'users_id_editor')) {\n $migration->addField(\"glpi_tickettasks\", \"users_id_editor\", \"int NOT NULL DEFAULT '0'\", ['after' => 'users_id']);\n $migration->addKey(\"glpi_tickettasks\", \"users_id_editor\");\n }\n if (!$DB->fieldExists('glpi_changetasks', 'users_id_editor')) {\n $migration->addField(\"glpi_changetasks\", \"users_id_editor\", \"int NOT NULL DEFAULT '0'\", ['after' => 'users_id']);\n $migration->addKey(\"glpi_changetasks\", \"users_id_editor\");\n }\n if (!$DB->fieldExists('glpi_problemtasks', 'users_id_editor')) {\n $migration->addField(\"glpi_problemtasks\", \"users_id_editor\", \"int NOT NULL DEFAULT '0'\", ['after' => 'users_id']);\n $migration->addKey(\"glpi_problemtasks\", \"users_id_editor\");\n }\n\n //Add a new sync_field in LDAP configuration\n if (!$DB->fieldExists('glpi_authldaps', 'sync_field')) {\n $migration->addField(\"glpi_authldaps\", \"sync_field\", \"string\", ['after' => 'login_field', 'null' => true]);\n $migration->addKey('glpi_authldaps', 'sync_field');\n }\n //Add a new sync_field for users\n if (!$DB->fieldExists('glpi_users', 'sync_field')) {\n $migration->addField(\"glpi_users\", \"sync_field\", \"string\", ['null' => true]);\n $migration->addKey('glpi_users', 'sync_field');\n }\n\n $migration->addConfig([\n 'smtp_max_retries' => 5,\n 'smtp_sender' => 'NULL',\n 'from_email' => 'NULL',\n 'from_email_name' => 'NULL'\n ]);\n\n //register telemetry crontask\n CronTask::register(\n 'Telemetry',\n 'telemetry',\n MONTH_TIMESTAMP,\n [\n 'comment' => '',\n 'mode' => CronTask::MODE_INTERNAL,\n 'state' => CronTask::STATE_DISABLE\n ]\n );\n $migration->addConfig([\n 'instance_uuid' => Telemetry::generateInstanceUuid(),\n 'registration_uuid' => Telemetry::generateRegistrationUuid()\n ]);\n\n if (isIndex('glpi_authldaps', 'use_tls')) {\n $query = \"ALTER TABLE `glpi_authldaps` DROP INDEX `use_tls`\";\n $DB->doQueryOrDie($query, \"9.2 drop index use_tls for glpi_authldaps\");\n }\n\n //Fix some field order from old migrations\n $migration->migrationOneTable('glpi_states');\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_budgets` CHANGE `date_creation` `date_creation` DATETIME NULL DEFAULT NULL AFTER `date_mod`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_changetasks` CHANGE `groups_id_tech` `groups_id_tech` INT NOT NULL DEFAULT '0' AFTER `users_id_tech`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_problemtasks` CHANGE `groups_id_tech` `groups_id_tech` INT NOT NULL DEFAULT '0' AFTER `users_id_tech`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_tickettasks` CHANGE `groups_id_tech` `groups_id_tech` INT NOT NULL DEFAULT '0' AFTER `users_id_tech`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_knowbaseitemcategories` CHANGE `sons_cache` `sons_cache` LONGTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `level`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_requesttypes` CHANGE `is_followup_default` `is_followup_default` TINYINT NOT NULL DEFAULT '0' AFTER `is_helpdesk_default`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_requesttypes` CHANGE `is_mailfollowup_default` `is_mailfollowup_default` TINYINT NOT NULL DEFAULT '0' AFTER `is_mail_default`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_requesttypes` CHANGE `comment` `comment` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `is_ticketfollowup`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_requesttypes` CHANGE `date_mod` `date_mod` DATETIME NULL DEFAULT NULL AFTER `comment`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_requesttypes` CHANGE `date_creation` `date_creation` DATETIME NULL DEFAULT NULL AFTER `date_mod`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_groups` CHANGE `is_task` `is_task` TINYINT NOT NULL DEFAULT '1' AFTER `is_assign`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_states` CHANGE `date_mod` `date_mod` DATETIME NULL DEFAULT NULL AFTER `is_visible_certificate`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_states` CHANGE `date_creation` `date_creation` DATETIME NULL DEFAULT NULL AFTER `date_mod`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_taskcategories` CHANGE `is_active` `is_active` TINYINT NOT NULL DEFAULT '1' AFTER `sons_cache`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_users` CHANGE `palette` `palette` CHAR(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `layout`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_users` CHANGE `set_default_requester` `set_default_requester` TINYINT NULL DEFAULT NULL AFTER `ticket_timeline_keep_replaced_tabs`\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_users` CHANGE `plannings` `plannings` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `highcontrast_css`\");\n\n //Fix bad default values\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_states` CHANGE `is_visible_softwarelicense` `is_visible_softwarelicense` TINYINT NOT NULL DEFAULT '1'\");\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_states` CHANGE `is_visible_line` `is_visible_line` TINYINT NOT NULL DEFAULT '1'\");\n\n //Fields added in 0905_91 script but not in empty sql...\n if (!$DB->fieldExists('glpi_changetasks', 'date_creation', false)) {\n $migration->addField('glpi_changetasks', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_changetasks', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_networkportfiberchannels', 'date_mod', false)) {\n $migration->addField('glpi_networkportfiberchannels', 'date_mod', 'datetime', ['after' => 'speed']);\n $migration->addKey('glpi_networkportfiberchannels', 'date_mod');\n }\n if (!$DB->fieldExists('glpi_networkportfiberchannels', 'date_creation', false)) {\n $migration->addField('glpi_networkportfiberchannels', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_networkportfiberchannels', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_problemtasks', 'date_creation', false)) {\n $migration->addField('glpi_problemtasks', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_problemtasks', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_slms', 'date_creation', false)) {\n $migration->addField('glpi_slms', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_slms', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_ticketfollowups', 'date_creation', false)) {\n $migration->addField('glpi_ticketfollowups', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_ticketfollowups', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_tickettasks', 'date_creation', false)) {\n $migration->addField('glpi_tickettasks', 'date_creation', 'datetime', ['after' => 'date_mod']);\n $migration->addKey('glpi_tickettasks', 'date_creation');\n }\n if (!$DB->fieldExists('glpi_softwarelicenses', 'contact_num', false)) {\n $migration->addField(\n \"glpi_softwarelicenses\",\n \"contact_num\",\n \"varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL\",\n ['after' => 'contact']\n );\n }\n\n //Fix comments...\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_savedsearches` CHANGE `type` `type` INT NOT NULL DEFAULT '0' COMMENT 'see SavedSearch:: constants'\");\n\n //Fix unicity...\n $tables = [\n 'glpi_slalevels_tickets' => ['tickets_id', 'slalevels_id'],\n 'glpi_businesscriticities' => ['businesscriticities_id', 'name'],\n 'glpi_documentcategories' => ['documentcategories_id', 'name'],\n 'glpi_olalevels_tickets' => ['tickets_id', 'olalevels_id'],\n 'glpi_states' => ['states_id', 'name'],\n 'glpi_tickets_tickets' => ['tickets_id_1', 'tickets_id_2'],\n 'glpi_tickettemplatehiddenfields' => ['tickettemplates_id', 'num'],\n 'glpi_tickettemplatemandatoryfields' => ['tickettemplates_id', 'num']\n ];\n foreach ($tables as $table => $fields) {\n $add = true;\n $result = $DB->doQuery(\"SHOW INDEX FROM `$table` WHERE Key_name='unicity'\");\n if ($result && $DB->numrows($result)) {\n $row = $DB->fetchAssoc($result);\n if ($row['Non_unique'] == 1) {\n $migration->dropKey($table, 'unicity');\n $migration->migrationOneTable($table);\n } else {\n $add = false;\n }\n }\n\n if ($add) {\n //missing or bad unique key ==> add it.\n $migration->addKey(\n $table,\n $fields,\n 'unicity',\n 'UNIQUE'\n );\n }\n }\n\n // unique index added in a previous 9.2-dev\n $migration->dropKey('glpi_tickettemplatepredefinedfields', 'unicity');\n $migration->addKey(\n 'glpi_tickettemplatepredefinedfields',\n ['tickettemplates_id', 'num'],\n 'tickettemplates_id_id_num'\n );\n\n //removed field\n if ($DB->fieldExists('glpi_slms', 'resolution_time')) {\n $migration->dropField('glpi_slms', 'resolution_time');\n }\n\n //wrong type\n $DB->doQueryOrDie(\"ALTER TABLE `glpi_users` CHANGE `keep_devices_when_purging_item` `keep_devices_when_purging_item` TINYINT NULL DEFAULT NULL\");\n\n //missing index\n $migration->addKey('glpi_networknames', 'is_deleted');\n $migration->addKey('glpi_networknames', 'is_dynamic');\n $migration->addKey('glpi_projects', 'is_template');\n $migration->addKey('glpi_projecttasks', 'is_template');\n $migration->dropKey('glpi_savedsearches_users', 'bookmarks_id');\n $migration->addKey('glpi_savedsearches_users', 'savedsearches_id');\n //this one was not on the correct field\n $migration->dropKey('glpi_softwarelicenses', 'is_deleted');\n $migration->migrationOneTable('glpi_softwarelicenses');\n $migration->addKey('glpi_softwarelicenses', 'is_deleted');\n $migration->addKey('glpi_states', 'is_visible_line');\n $migration->addKey('glpi_tasktemplates', 'is_private');\n $migration->addKey('glpi_tasktemplates', 'users_id_tech');\n $migration->addKey('glpi_tasktemplates', 'groups_id_tech');\n\n //add timeline_position in ticketfollowups\n //add timeline_position in tickettasks\n //add timeline_position in documents_items\n //add timeline_position in ticketvalidations\n $timeline_tables = ['glpi_ticketfollowups', 'glpi_tickettasks', 'glpi_documents_items', 'glpi_ticketvalidations'];\n foreach ($timeline_tables as $tl_table) {\n //add timeline_position in $tl_table\n if (!$DB->fieldExists($tl_table, 'timeline_position')) {\n $migration->addField($tl_table, \"timeline_position\", \"tinyint NOT NULL DEFAULT '0'\");\n $where = [\n \"$tl_table.tickets_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_tickets_users.tickets_id\")\n ),\n \"$tl_table.users_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_tickets_users.users_id\")\n ),\n ];\n if (!$DB->fieldExists($tl_table, 'tickets_id')) {\n $where = [\n \"$tl_table.itemtype\" => \"Ticket\",\n \"$tl_table.items_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_tickets_users.tickets_id\")\n ),\n \"$tl_table.users_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_tickets_users.users_id\")\n ),\n ];\n }\n\n $update = new QueryExpression(\n DBmysql::quoteName($tl_table) . \", \" . DBmysql::quoteName(\"glpi_tickets_users\")\n );\n $migration->addPostQuery(\n $DB->buildUpdate(\n $update,\n [\n \"$tl_table.timeline_position\" => new QueryExpression(\"IF(\" .\n DBmysql::quoteName(\"glpi_tickets_users.type\") . \" NOT IN (1,3) AND \" .\n DBmysql::quoteName(\"glpi_tickets_users.type\") . \" IN (2), 4, 1)\")\n ],\n $where\n )\n );\n\n $where = [\n \"$tl_table.tickets_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_tickets.tickets_id\")\n ),\n \"glpi_groups_users.groups_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_tickets.groups_id\")\n ),\n \"$tl_table.users_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_users.users_id\")\n ),\n ];\n if (!$DB->fieldExists($tl_table, 'tickets_id')) {\n $where = [\n \"$tl_table.itemtype\" => \"Ticket\",\n \"$tl_table.items_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_tickets.tickets_id\")\n ),\n \"glpi_groups_users.groups_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_tickets.groups_id\")\n ),\n \"$tl_table.users_id\" => new QueryExpression(\n DBmysql::quoteName(\"glpi_groups_users.users_id\")\n ),\n ];\n }\n\n $update = new QueryExpression(\n DBmysql::quoteName($tl_table) . \", \" . DBmysql::quoteName(\"glpi_groups_tickets\") .\n \", \" . DBmysql::quoteName(\"glpi_groups_users\")\n );\n $migration->addPostQuery(\n $DB->buildUpdate(\n $update,\n [\n \"$tl_table.timeline_position\" => new QueryExpression(\"IF(\" .\n DBmysql::quoteName(\"glpi_groups_tickets.type\") . \" NOT IN (1,3) AND \" .\n DBmysql::quoteName(\"glpi_groups_tickets.type\") . \" IN (2), 4, 1)\")\n ],\n $where\n )\n );\n\n $migration->addPostQuery(\n $DB->buildUpdate(\n $tl_table,\n [\"$tl_table.timeline_position\" => 1],\n [\"$tl_table.timeline_position\" => 0]\n )\n );\n }\n }\n\n // ************ Keep it at the end **************\n $migration->executeMigration();\n\n return $updateresult;\n}", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public function propFind(DAV\\PropFind $propFind, DAV\\INode $node)\n {\n $path = $propFind->getPath();\n\n // Checking the read permission\n if (!$this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false)) {\n // User is not allowed to read properties\n\n // Returning false causes the property-fetching system to pretend\n // that the node does not exist, and will cause it to be hidden\n // from listings such as PROPFIND or the browser plugin.\n if ($this->hideNodesFromListings) {\n return false;\n }\n\n // Otherwise we simply mark every property as 403.\n foreach ($propFind->getRequestedProperties() as $requestedProperty) {\n $propFind->set($requestedProperty, null, 403);\n }\n\n return;\n }\n\n /* Adding principal properties */\n if ($node instanceof IPrincipal) {\n $propFind->handle('{DAV:}alternate-URI-set', function () use ($node) {\n return new Href($node->getAlternateUriSet());\n });\n $propFind->handle('{DAV:}principal-URL', function () use ($node) {\n return new Href($node->getPrincipalUrl().'/');\n });\n $propFind->handle('{DAV:}group-member-set', function () use ($node) {\n $members = $node->getGroupMemberSet();\n foreach ($members as $k => $member) {\n $members[$k] = rtrim($member, '/').'/';\n }\n\n return new Href($members);\n });\n $propFind->handle('{DAV:}group-membership', function () use ($node) {\n $members = $node->getGroupMembership();\n foreach ($members as $k => $member) {\n $members[$k] = rtrim($member, '/').'/';\n }\n\n return new Href($members);\n });\n $propFind->handle('{DAV:}displayname', [$node, 'getDisplayName']);\n }\n\n $propFind->handle('{DAV:}principal-collection-set', function () {\n $val = $this->principalCollectionSet;\n // Ensuring all collections end with a slash\n foreach ($val as $k => $v) {\n $val[$k] = $v.'/';\n }\n\n return new Href($val);\n });\n $propFind->handle('{DAV:}current-user-principal', function () {\n if ($url = $this->getCurrentUserPrincipal()) {\n return new Xml\\Property\\Principal(Xml\\Property\\Principal::HREF, $url.'/');\n } else {\n return new Xml\\Property\\Principal(Xml\\Property\\Principal::UNAUTHENTICATED);\n }\n });\n $propFind->handle('{DAV:}supported-privilege-set', function () use ($node) {\n return new Xml\\Property\\SupportedPrivilegeSet($this->getSupportedPrivilegeSet($node));\n });\n $propFind->handle('{DAV:}current-user-privilege-set', function () use ($node, $propFind, $path) {\n if (!$this->checkPrivileges($path, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) {\n $propFind->set('{DAV:}current-user-privilege-set', null, 403);\n } else {\n $val = $this->getCurrentUserPrivilegeSet($node);\n\n return new Xml\\Property\\CurrentUserPrivilegeSet($val);\n }\n });\n $propFind->handle('{DAV:}acl', function () use ($node, $propFind, $path) {\n /* The ACL property contains all the permissions */\n if (!$this->checkPrivileges($path, '{DAV:}read-acl', self::R_PARENT, false)) {\n $propFind->set('{DAV:}acl', null, 403);\n } else {\n $acl = $this->getACL($node);\n\n return new Xml\\Property\\Acl($this->getACL($node));\n }\n });\n $propFind->handle('{DAV:}acl-restrictions', function () {\n return new Xml\\Property\\AclRestrictions();\n });\n\n /* Adding ACL properties */\n if ($node instanceof IACL) {\n $propFind->handle('{DAV:}owner', function () use ($node) {\n return new Href($node->getOwner().'/');\n });\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function initContent()\n {\n if (!Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) {\n // You can uncomment these lines if you want to force https even from localhost and automatically redirect\n // header('HTTP/1.1 301 Moved Permanently');\n // header('Location: '.Tools::getShopDomainSsl(true).$_SERVER['REQUEST_URI']);\n // exit();\n $clientIsMaintenanceOrLocal = in_array(Tools::getRemoteAddr(), array_merge(['127.0.0.1'], explode(',', Configuration::get('PS_MAINTENANCE_IP'))));\n // If ssl is enabled, https protocol is required. Exception for maintenance and local (127.0.0.1) IP\n if ($clientIsMaintenanceOrLocal) {\n $warningSslMessage = $this->trans('SSL is activated. However, your IP is allowed to enter unsecure mode for maintenance or local IP issues.', [], 'Admin.Login.Notification');\n } else {\n $url = 'https://' . Tools::safeOutput(Tools::getServerName()) . Tools::safeOutput($_SERVER['REQUEST_URI']);\n $warningSslMessage = $this->trans(\n 'SSL is activated. Please connect using the following link to [1]log in to secure mode (https://)[/1]',\n ['[1]' => '<a href=\"' . $url . '\">', '[/1]' => '</a>'],\n 'Admin.Login.Notification'\n );\n }\n $this->context->smarty->assign('warningSslMessage', $warningSslMessage);\n }\n\n if (file_exists(_PS_ADMIN_DIR_ . '/../install')) {\n $this->context->smarty->assign('wrong_install_name', true);\n }\n\n if (basename(_PS_ADMIN_DIR_) == 'admin' && file_exists(_PS_ADMIN_DIR_ . '/../admin/')) {\n $rand = 'admin' . sprintf('%03d', mt_rand(0, 999)) . Tools::strtolower(Tools::passwdGen(6)) . '/';\n if (@rename(_PS_ADMIN_DIR_ . '/../admin/', _PS_ADMIN_DIR_ . '/../' . $rand)) {\n Tools::redirectAdmin('../' . $rand);\n } else {\n $this->context->smarty->assign([\n 'wrong_folder_name' => true,\n ]);\n }\n } else {\n $rand = basename(_PS_ADMIN_DIR_) . '/';\n }\n\n $this->context->smarty->assign([\n 'randomNb' => $rand,\n 'adminUrl' => Tools::getCurrentUrlProtocolPrefix() . Tools::getShopDomain() . __PS_BASE_URI__ . $rand,\n ]);\n\n // Redirect to admin panel\n if (Tools::isSubmit('redirect') && Validate::isControllerName(Tools::getValue('redirect'))) {\n $this->context->smarty->assign('redirect', Tools::getValue('redirect'));\n } else {\n $tab = new Tab((int) $this->context->employee->default_tab);\n $this->context->smarty->assign('redirect', $this->context->link->getAdminLink($tab->class_name));\n }\n\n if ($nb_errors = count($this->errors)) {\n $this->context->smarty->assign([\n 'errors' => $this->errors,\n 'nbErrors' => $nb_errors,\n 'shop_name' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME')),\n 'disableDefaultErrorOutPut' => true,\n ]);\n }\n\n if ($email = Tools::getValue('email')) {\n $this->context->smarty->assign('email', $email);\n }\n if ($password = Tools::getValue('password')) {\n $this->context->smarty->assign('password', $password);\n }\n\n // For reset password feature\n if ($reset_token = Tools::getValue('reset_token')) {\n $this->context->smarty->assign('reset_token', $reset_token);\n }\n if ($id_employee = Tools::getValue('id_employee')) {\n $this->context->smarty->assign('id_employee', $id_employee);\n $employee = new Employee($id_employee);\n if (Validate::isLoadedObject($employee)) {\n $this->context->smarty->assign('reset_email', $employee->email);\n }\n }\n\n $this->setMedia($isNewTheme = false);\n $this->initHeader();\n parent::initContent();\n $this->initFooter();\n\n //force to disable modals\n $this->context->smarty->assign('modals', null);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function getUniqueItemByIPAddress($value, $entity)\n {\n\n $addressesWithItems = self::getItemsByIPAddress($value);\n\n // Filter : Do not keep ip not linked to asset\n if (count($addressesWithItems)) {\n foreach ($addressesWithItems as $key => $tab) {\n if (\n isset($tab[0])\n && (($tab[0] instanceof NetworkName)\n || ($tab[0] instanceof IPAddress)\n || ($tab[0] instanceof NetworkPort)\n || $tab[0]->isDeleted()\n || $tab[0]->isTemplate()\n || ($tab[0]->getEntityID() != $entity))\n ) {\n unset($addressesWithItems[$key]);\n }\n }\n }\n\n if (count($addressesWithItems)) {\n // Get the first item that is matching entity\n foreach ($addressesWithItems as $items) {\n foreach ($items as $item) {\n if ($item->getEntityID() == $entity) {\n $result = [\"id\" => $item->getID(),\n \"itemtype\" => $item->getType()\n ];\n unset($addressesWithItems);\n return $result;\n }\n }\n }\n }\n return [];\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function user_SyncCommonCredentials($system, $userID, $is_approvement){\n\n $dbname_full = $system->dbnameFull();\n $mysqli = $system->getMysqli();\n //1. find sys_UGrpsDatabase in this database\n $linked_dbs = mysql__select_value($mysqli, 'select sys_UGrpsDatabase from sysIdentification');\n if($linked_dbs)\n {\n\n $userEmail = mysql__select_value($mysqli, 'select ugr_eMail from sysUGrps where ugr_ID='.$userID);\n\n $linked_dbs = explode(',', $linked_dbs);\n foreach ($linked_dbs as $ldb){\n if(strpos($ldb, HEURIST_DB_PREFIX)!==0){\n $ldb = HEURIST_DB_PREFIX.$ldb;\n }\n //database exists\n $dbname = mysql__select_value($mysqli,\n 'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = \\''\n .$mysqli->real_escape_string($ldb).'\\'');\n if(!$dbname) {continue;}\n\n $ldb = preg_replace(REGEX_ALPHANUM, '', $ldb);//for snyk\n\n //2. find sys_UGrpsDatabase in linked database - this database must be in list\n $linked_dbs2 = mysql__select_value($mysqli, 'select sys_UGrpsDatabase from '.$ldb.'.sysIdentification');\n if(!$linked_dbs2) {continue;} //this database is not mutually linked\n $linked_dbs2 = explode(',', $linked_dbs2);\n foreach ($linked_dbs2 as $ldb2){\n if(strpos($ldb2, HEURIST_DB_PREFIX)!==0){\n $ldb2 = HEURIST_DB_PREFIX.$ldb2;\n }\n if( strcasecmp($dbname_full, $ldb2)==0 ){\n //yes database is mutually linked\n //3. find user email in linked database\n $userEmail_in_linkedDB = mysql__select_value($mysqli, 'select ugr_eMail from `'\n .$ldb.'`.sysUGrps where ugr_eMail=\"'.$userEmail.'\"');\n if(!$userEmail_in_linkedDB){\n //add new user to linked database\n\n $fields = 'ugr_LongName,ugr_Description,ugr_Password,ugr_eMail,'.\n 'ugr_FirstName,ugr_LastName,ugr_Department,ugr_Organisation,ugr_City,'.\n 'ugr_State,ugr_Postcode,ugr_Interests,ugr_Enabled,ugr_LastLoginTime,'.\n 'ugr_MinHyperlinkWords,ugr_IsModelUser,'. //ugr_LoginCount,\n 'ugr_IncomingEmailAddresses,ugr_TargetEmailAddresses,ugr_URLs,ugr_FlagJT';\n\n $query1 = \"insert into `$ldb`.sysUGrps (ugr_Type,ugr_Name,$fields) \".\n \"SELECT ugr_Type,ugr_eMail,$fields \".\n \"FROM sysUGrps where ugr_ID=\".intval($userID);\n\n\n }elseif($is_approvement){\n //enable user\n $query1 = \"update `$ldb`.sysUGrps set ugr_Enabled='\". $is_approvement .\"' where ugr_ID=\".intval($userID);\n }\n\n $res = $mysqli->query($query1);\n break;\n }\n }\n }\n }\n\n\n\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n $this->setIdentifier($data['identifier']);\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['status'])) {\n $this->setStatus($data['status']);\n }\n if (isset($data['testScript'])) {\n $this->setTestScript($data['testScript']);\n }\n if (isset($data['result'])) {\n $this->setResult($data['result']);\n }\n if (isset($data['score'])) {\n $this->setScore($data['score']);\n }\n if (isset($data['tester'])) {\n $this->setTester($data['tester']);\n }\n if (isset($data['issued'])) {\n $this->setIssued($data['issued']);\n }\n if (isset($data['participant'])) {\n if (is_array($data['participant'])) {\n foreach ($data['participant'] as $d) {\n $this->addParticipant($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"participant\" must be array of objects or null, ' . gettype($data['participant']) . ' seen.');\n }\n }\n if (isset($data['setup'])) {\n $this->setSetup($data['setup']);\n }\n if (isset($data['test'])) {\n if (is_array($data['test'])) {\n foreach ($data['test'] as $d) {\n $this->addTest($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"test\" must be array of objects or null, ' . gettype($data['test']) . ' seen.');\n }\n }\n if (isset($data['teardown'])) {\n $this->setTeardown($data['teardown']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function reflectCallable($callable)\n {\n if (null !== $this->reflector) {\n return $this->reflector;\n }\n\n if (\\is_string($callable) && false !== $pos = strpos($callable, '::')) {\n $callable = [substr($callable, 0, $pos), substr($callable, 2 + $pos)];\n }\n\n if (\\is_array($callable) && method_exists($callable[0], $callable[1])) {\n $r = new \\ReflectionMethod($callable[0], $callable[1]);\n\n return $this->reflector = [$r, $callable, $r->class.'::'.$r->name];\n }\n\n $checkVisibility = $callable instanceof \\Closure;\n try {\n $closure = \\Closure::fromCallable($callable);\n } catch (\\TypeError $e) {\n throw new \\LogicException(sprintf('Callback for %s \"%s\" is not callable in the current scope.', $this->getAttribute('type'), $this->getAttribute('name')), 0, $e);\n }\n $r = new \\ReflectionFunction($closure);\n\n if (false !== strpos($r->name, '{closure}')) {\n return $this->reflector = [$r, $callable, 'Closure'];\n }\n\n if ($object = $r->getClosureThis()) {\n $callable = [$object, $r->name];\n $callableName = (\\function_exists('get_debug_type') ? get_debug_type($object) : \\get_class($object)).'::'.$r->name;\n } elseif (\\PHP_VERSION_ID >= 80111 && $class = $r->getClosureCalledClass()) {\n $callableName = $class->name.'::'.$r->name;\n } elseif (\\PHP_VERSION_ID < 80111 && $class = $r->getClosureScopeClass()) {\n $callableName = (\\is_array($callable) ? $callable[0] : $class->name).'::'.$r->name;\n } else {\n $callable = $callableName = $r->name;\n }\n\n if ($checkVisibility && \\is_array($callable) && method_exists(...$callable) && !(new \\ReflectionMethod(...$callable))->isPublic()) {\n $callable = $r->getClosure();\n }\n\n return $this->reflector = [$r, $callable, $callableName];\n }", "smellKey": "S3776", "smellId": null, "repo": "tibia-oce_website", "language": "php"} {"function": "function thisLineItem($row, $xfer = false)\n{\n global $grandtotal, $grandqty, $encount, $form_action;\n\n $invnumber = '';\n $dpname = '';\n\n if (!empty($row['pid'])) {\n $ttype = xl('Sale');\n $dpname = $row['plname'];\n if (!empty($row['pfname'])) {\n $dpname .= ', ' . $row['pfname'];\n if (!empty($row['pmname'])) {\n $dpname .= ' ' . $row['pmname'];\n }\n }\n\n $invnumber = empty($row['invoice_refno']) ?\n \"{$row['pid']}.{$row['encounter']}\" : $row['invoice_refno'];\n } elseif (!empty($row['distributor_id'])) {\n $ttype = xl('Distribution');\n if (!empty($row['organization'])) {\n $dpname = $row['organization'];\n } else {\n $dpname = $row['dlname'];\n if (!empty($row['dfname'])) {\n $dpname .= ', ' . $row['dfname'];\n if (!empty($row['dmname'])) {\n $dpname .= ' ' . $row['dmname'];\n }\n }\n }\n } elseif (!empty($row['xfer_inventory_id']) || $xfer) {\n $ttype = xl('Transfer');\n } elseif ($row['fee'] != 0) {\n $ttype = xl('Purchase');\n } else {\n $ttype = xl('Adjustment');\n }\n\n if ($form_action == 'export') {\n echo csvEscape(oeFormatShortDate($row['sale_date'])) . ',';\n echo csvEscape($ttype) . ',';\n echo csvEscape($row['name']) . ',';\n echo csvEscape($row['lot_number']) . ',';\n echo csvEscape($row['warehouse']) . ',';\n echo csvEscape($dpname) . ',';\n echo csvEscape(0 - $row['quantity']) . ',';\n echo csvEscape(FormatMoney::getBucks($row['fee'])) . ',';\n echo csvEscape($row['billed']) . ',';\n echo csvEscape($row['notes']) . \"\\n\";\n } else {\n $bgcolor = (++$encount & 1) ? \"#ddddff\" : \"#ffdddd\";\n ?>\n\n <tr bgcolor=\"<?php echo $bgcolor; ?>\">\n <td class=\"detail\">\n <?php echo text(oeFormatShortDate($row['sale_date'])); ?>\n </td>\n <td class=\"detail\">\n <?php echo text($ttype); ?>\n </td>\n <td class=\"detail\">\n <?php echo text($row['name']); ?>\n </td>\n <td class=\"detail\">\n <?php echo text($row['lot_number']); ?>\n </td>\n <td class=\"detail\">\n <?php echo text($row['warehouse']); ?>\n </td>\n <td class=\"detail\">\n <?php echo text($dpname); ?>\n </td>\n <td class=\"detail\" align=\"right\">\n <?php echo text(0 - $row['quantity']); ?>\n </td>\n <td class=\"detail\" align=\"right\">\n <?php echo text(FormatMoney::getBucks($row['fee'])); ?>\n </td>\n <td class=\"detail\" align=\"center\">\n <?php echo empty($row['billed']) ? '&nbsp;' : '*'; ?>\n </td>\n <td class=\"detail\">\n <?php echo text($row['notes']); ?>\n </td>\n </tr>\n <?php\n } // End not csv export\n\n $grandtotal += $row['fee'];\n $grandqty -= $row['quantity'];\n\n // In the special case of a transfer, generate a second line item for\n // the source lot.\n if (!empty($row['xfer_inventory_id'])) {\n $row['xfer_inventory_id'] = 0;\n $row['lot_number'] = $row['lot_number_2'];\n $row['warehouse'] = $row['warehouse_2'];\n $row['quantity'] = 0 - $row['quantity'];\n $row['fee'] = 0 - $row['fee'];\n thisLineItem($row, true);\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "protected function buildResourceRule()\n {\n $origin = $this->router->getGroup();\n $this->router->setGroup($this);\n\n $rule = $this->resource;\n $option = $this->option;\n\n if (strpos($rule, '.')) {\n // \u6ce8\u518c\u5d4c\u5957\u8d44\u6e90\u8def\u7531\n $array = explode('.', $rule);\n $last = array_pop($array);\n $item = [];\n\n foreach ($array as $val) {\n $item[] = $val . '/<' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id') . '>';\n }\n\n $rule = implode('/', $item) . '/' . $last;\n }\n\n $prefix = substr($rule, strlen($this->name) + 1);\n\n // \u6ce8\u518c\u8d44\u6e90\u8def\u7531\n foreach ($this->rest as $key => $val) {\n if ((isset($option['only']) && !in_array($key, $option['only']))\n || (isset($option['except']) && in_array($key, $option['except']))) {\n continue;\n }\n\n if (isset($last) && strpos($val[1], '<id>') && isset($option['var'][$last])) {\n $val[1] = str_replace('<id>', '<' . $option['var'][$last] . '>', $val[1]);\n } elseif (strpos($val[1], '<id>') && isset($option['var'][$rule])) {\n $val[1] = str_replace('<id>', '<' . $option['var'][$rule] . '>', $val[1]);\n }\n\n $this->addRule(trim($prefix . $val[1], '/'), $this->route . '/' . $val[2], $val[0]);\n }\n\n $this->router->setGroup($origin);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_Spblog", "language": "php"} {"function": "function getAllNames($allactions) {\n global $stunames, $offlinenames, $DBH;\n $uids = [];\n foreach ($allactions as $action) {\n if ($action['action'] == 'Delete Item' || $action['action'] == 'Clear Attempts') {\n $data = json_decode($action['metadata'], true);\n if (isset($data['grades'])) {\n if (isset($data['type']) && $data['type']=='Delete Offline') { // these are grades=>itemid=>uid=>grade\n foreach ($data['grades'] as $itemid=>$grades) {\n $uids = array_merge($uids, array_keys($grades));\n }\n foreach ($data['items'] as $itemid=>$data) {\n $offlinenames[$itemid] = $data['name'];\n }\n } else { // others are grades=>uid=>grade\n $uids = array_merge($uids, array_keys($data['grades']));\n }\n }\n } else if ($action['action'] == 'Unenroll') {\n $data = json_decode($action['metadata'], true);\n $uids = array_merge($uids, explode(',', $data['unenrolled']));\n }\n }\n $uids = array_values(array_unique($uids));\n if (count($uids)>0) {\n $ph = Sanitize::generateQueryPlaceholders($uids);\n $stm = $DBH->prepare(\"SELECT id,FirstName,LastName FROM imas_users WHERE id IN ($ph)\");\n $stm->execute($uids);\n while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {\n $stunames[$row['id']] = $row['LastName'] . ', ' . $row['FirstName'];\n }\n }\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function active_alert_summary($patient_id, $mode, $dateTarget = '', $organize_mode = 'default', $user = '', $test = false)\n{\n\n // Set date to current if not set\n $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');\n\n // Collect active actions\n $actions = test_rules_clinic('', 'active_alert', $dateTarget, $mode, $patient_id, '', $organize_mode, array(), 'primary', null, null, $user);\n\n if (empty($actions)) {\n return false;\n }\n\n $returnOutput = \"\";\n $current_targets = array();\n\n // Display the actions\n foreach ($actions as $action) {\n // Deal with plan names first\n if ($action['is_plan']) {\n $returnOutput .= \"<br /><b>\";\n $returnOutput .= xlt(\"Plan\") . \": \";\n $returnOutput .= generate_display_field(array('data_type' => '1','list_id' => 'clinical_plans'), $action['id']);\n $returnOutput .= \"</b><br />\";\n continue;\n }\n\n // Display Reminder Details\n $returnOutput .= generate_display_field(array('data_type' => '1','list_id' => 'rule_action_category'), $action['category']) .\n \": \" . generate_display_field(array('data_type' => '1','list_id' => 'rule_action'), $action['item']);\n\n // Display due status\n if ($action['due_status']) {\n // Color code the status (red for past due, purple for due, green for not due and black for soon due)\n if ($action['due_status'] == \"past_due\") {\n $returnOutput .= \"&nbsp;&nbsp;(<span style='color:red'>\";\n } elseif ($action['due_status'] == \"due\") {\n $returnOutput .= \"&nbsp;&nbsp;(<span style='color:purple'>\";\n } elseif ($action['due_status'] == \"not_due\") {\n $returnOutput .= \"&nbsp;&nbsp;(<span style='color:green'>\";\n } else {\n $returnOutput .= \"&nbsp;&nbsp;(<span>\";\n }\n\n $returnOutput .= generate_display_field(array('data_type' => '1','list_id' => 'rule_reminder_due_opt'), $action['due_status']) . \"</span>)<br />\";\n } else {\n $returnOutput .= \"<br />\";\n }\n\n // Add the target(and rule id and room for future elements as needed) to the $current_targets array.\n // Only when $mode is reminders-due and $test is FALSE\n if (($mode == \"reminders-due\") && ($test === false) && ($GLOBALS['enable_alert_log'])) {\n $target_temp = $action['category'] . \":\" . $action['item'];\n $current_targets[$target_temp] = array('rule_id' => $action['rule_id'],'due_status' => $action['due_status']);\n }\n }\n\n // Compare the current with most recent action log (this function will also log the current actions)\n // Only when $mode is reminders-due and $test is FALSE\n if (($mode == \"reminders-due\") && ($test === false) && ($GLOBALS['enable_alert_log'])) {\n $new_targets = compare_log_alerts($patient_id, $current_targets, 'active_reminder_popup', $_SESSION['authUserID']);\n if (!empty($new_targets)) {\n $returnOutput .= \"<br />\" . xlt('New Items (see above for details)') . \":<br />\";\n foreach ($new_targets as $key => $value) {\n $category_item = explode(\":\", $key);\n $category = $category_item[0];\n $item = $category_item[1];\n $returnOutput .= generate_display_field(array('data_type' => '1','list_id' => 'rule_action_category'), $category) .\n ': ' . generate_display_field(array('data_type' => '1','list_id' => 'rule_action'), $item) . '<br />';\n }\n }\n }\n\n return $returnOutput;\n}", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public static function databaseCreate($database_name, $level=2, $dumpfile=null){\n\n self::initialize();\n\n list($database_name_full, $database_name) = mysql__get_names( $database_name );\n\n $error_msg = self::databaseValidateName($database_name, 1);//unique\n if ($error_msg!=null) {\n self::$system->addError(HEURIST_ACTION_BLOCKED, $error_msg);\n return false;\n }\n\n $database_folder = null;\n\n if($dumpfile==null){\n $dumpfile = 'blankDBStructure.sql';\n }else{\n $dumpfile = basename($dumpfile);\n\n $upload_root = self::$system->getFileStoreRootFolder();\n $database_folder = $upload_root.$database_name.'/';\n\n //remove COLLATE= for huma-num\n if(defined('HEURIST_SERVER_NAME') && HEURIST_SERVER_NAME=='heurist.huma-num.fr'){\n $dump_name_full = $database_folder.$dumpfile;\n $cmd = \"sed -i 's/ COLLATE=utf8mb4_0900_ai_ci//g' \".escapeshellarg($dump_name_full);\n exec($cmd, $arr_out, $res2);\n\n if ($res2 != 0 ) {\n $error = 'Error: '.print_r($res2, true);\n error_log($error);\n }\n }\n }\n\n $mysqli = self::$mysqli;\n\n $res = mysql__create_database($mysqli, $database_name_full);\n\n if (is_array($res)){\n self::$system->addErrorArr($res);//can't create\n mysql__drop_database($mysqli, $database_name_full);\n return false;\n }elseif($level<1){\n return true; //create empty database\n }\n\n //restore data from sql dump\n $res = mysql__script($database_name_full, $dumpfile, $database_folder);//restore from dump\n if($res!==true){\n $res[1] = 'Cannot create database tables. '.$res[1];\n self::$system->addErrorArr($res);\n }elseif($level<2){\n return true; //without constraints and triggers\n }elseif(self::databaseCreateConstraintsAndTriggers($database_name_full)){\n return true;\n }\n//----------------------\n\n if (is_array($res)){\n self::$system->addErrorArr($res);//can't create\n mysql__drop_database($mysqli, $database_name_full);\n return false;\n }elseif($level<1){\n return true; //create empty database\n }\n\n //restore data from sql dump\n $res = mysql__script($database_name_full, $dumpfile, $database_folder);//restore from dump\n if($res!==true){\n $res[1] = 'Cannot create database tables. '.$res[1];\n self::$system->addErrorArr($res);\n }elseif($level<2){\n return true; //without constraints and triggers\n }elseif(self::databaseCreateConstraintsAndTriggers($database_name_full)){\n return true;\n }\n\n //fails\n mysql__drop_database($mysqli, $database_name_full);\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private function getAssetCode(bool $inAdmin = false): string\n {\n $asset = Asset::getById((int)$this->id);\n $config = $this->getConfig();\n $thumbnailConfig = $config['thumbnail'] ?? null;\n\n // compatibility mode when FFMPEG is not present or no thumbnail config is given\n if (!\\Pimcore\\Video::isAvailable() || !$thumbnailConfig) {\n if ($asset instanceof Asset\\Video && preg_match(\"/\\.(f4v|flv|mp4)/i\", $asset->getFullPath())) {\n $image = $this->getPosterThumbnailImage($asset);\n\n return $this->getHtml5Code(['mp4' => (string) $asset], $image);\n }\n\n return $this->getErrorCode('Asset is not a video, or missing thumbnail configuration');\n }\n\n if ($asset instanceof Asset\\Video) {\n $thumbnail = $asset->getThumbnail($thumbnailConfig);\n if ($thumbnail) {\n $image = $this->getPosterThumbnailImage($asset);\n\n if ($inAdmin && isset($config['editmodeImagePreview']) && $config['editmodeImagePreview']) {\n $code = '<div id=\"pimcore_video_' . $this->getName() . '\" class=\"pimcore_editable_video '. ($config['class'] ?? '') .'\">';\n $code .= '<img width=\"' . $this->getWidth() . '\" src=\"' . $image . '\" />';\n $code .= '</div>';\n\n return $code;\n }\n\n if ($thumbnail['status'] === 'finished') {\n return $this->getHtml5Code($thumbnail['formats'], $image);\n }\n\n if ($thumbnail['status'] === 'inprogress') {\n // disable the output-cache if enabled\n $cacheService = Pimcore::getContainer()->get(FullPageCacheListener::class);\n $cacheService->disable('Video rendering in progress');\n\n return $this->getProgressCode((string)$image);\n }\n\n return $this->getErrorCode(\n 'The video conversion failed, please see the log files in /var/log for more details.'\n );\n }\n\n return $this->getErrorCode(\"The given thumbnail doesn't exist: '\" . $thumbnailConfig . \"'\");\n }\n\n return $this->getEmptyCode();\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['sequence'])) {\n $this->setSequence($data['sequence']);\n }\n if (isset($data['revenue'])) {\n $this->setRevenue($data['revenue']);\n }\n if (isset($data['category'])) {\n $this->setCategory($data['category']);\n }\n if (isset($data['productOrService'])) {\n $this->setProductOrService($data['productOrService']);\n }\n if (isset($data['modifier'])) {\n if (is_array($data['modifier'])) {\n foreach ($data['modifier'] as $d) {\n $this->addModifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"modifier\" must be array of objects or null, ' . gettype($data['modifier']) . ' seen.');\n }\n }\n if (isset($data['programCode'])) {\n if (is_array($data['programCode'])) {\n foreach ($data['programCode'] as $d) {\n $this->addProgramCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"programCode\" must be array of objects or null, ' . gettype($data['programCode']) . ' seen.');\n }\n }\n if (isset($data['quantity'])) {\n $this->setQuantity($data['quantity']);\n }\n if (isset($data['unitPrice'])) {\n $this->setUnitPrice($data['unitPrice']);\n }\n if (isset($data['factor'])) {\n $this->setFactor($data['factor']);\n }\n if (isset($data['net'])) {\n $this->setNet($data['net']);\n }\n if (isset($data['udi'])) {\n if (is_array($data['udi'])) {\n foreach ($data['udi'] as $d) {\n $this->addUdi($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"udi\" must be array of objects or null, ' . gettype($data['udi']) . ' seen.');\n }\n }\n if (isset($data['noteNumber'])) {\n if (is_array($data['noteNumber'])) {\n foreach ($data['noteNumber'] as $d) {\n $this->addNoteNumber($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"noteNumber\" must be array of objects or null, ' . gettype($data['noteNumber']) . ' seen.');\n }\n }\n if (isset($data['adjudication'])) {\n if (is_array($data['adjudication'])) {\n foreach ($data['adjudication'] as $d) {\n $this->addAdjudication($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"adjudication\" must be array of objects or null, ' . gettype($data['adjudication']) . ' seen.');\n }\n }\n if (isset($data['subDetail'])) {\n if (is_array($data['subDetail'])) {\n foreach ($data['subDetail'] as $d) {\n $this->addSubDetail($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"subDetail\" must be array of objects or null, ' . gettype($data['subDetail']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function boxplot($arr,$label=\"\",$options = array()) {\n\tif (isset($arr[0]) && is_array($arr[0]) && count($options)==count($arr) && isset($options[0])) {\n\t\t$dlbls = $options;\n\t\t$options = array();\n\t} else if (isset($options['datalabels'])) {\n\t\t$dlbls = $options['datalabels'];\n\t}\n\tif (isset($arr[0]) && is_array($arr[0])) { $multi = count($arr);} else {$multi = 1;}\n\t$qmethod = 'quartile';\n\tif (isset($options['qmethod'])) {\n\t\tif ($options['qmethod']=='TI') {\n\t\t\t$qmethod = 'TIquartile';\n\t\t} else if ($options['qmethod']=='Excel') {\n\t\t\t$qmethod = 'Excelquartile';\n\t\t} else if ($options['qmethod']=='Excel.exc') {\n\t\t\t$qmethod = 'Excelquartileexc';\n\t\t} else if ($options['qmethod']=='N') {\n\t\t\t$qmethod = 'quartile';\n\t\t} else if ($options['qmethod']=='Nplus1') {\n\t\t\t$qmethod = 'Nplus1quartile';\n\t\t}\n\t}\n\n\t$st = '';\n\t$bigmax = -10000000;\n\t$bigmin = 100000000;\n\t$alt = \"Boxplot, axis label: $label. \";\n\t$ybase = 2;\n\tfor ($i=0;$i<$multi;$i++) {\n\t\tif ($multi==1) { $a = $arr;} else {$a = $arr[$i];}\n $a = arrayremovenull($a);\n\t\tsort($a,SORT_NUMERIC);\n\t\t$min = $a[0]*1;\n\t\t$max = $a[count($a)-1]*1;\n\t\tif ($max>$bigmax) { $bigmax = $max;}\n\t\tif ($a[0]<$bigmin) {$bigmin = $a[0];}\n\t\t$q1 = $qmethod($a,1)*1;\n\t\t$q2 = $qmethod($a,2)*1;\n\t\t$q3 = $qmethod($a,3)*1;\n\t\t$outliers = array();\n\t\tif (count($a)>5 && isset($options['showoutliers'])) {\n\t\t\t$iqr = $q3-$q1;\n\t\t\t$lfence = $q1 - 1.5*$iqr;\n\t\t\t$rfence = $q3 + 1.5*$iqr;\n $mininside = 1e50;\n $maxinside = -1e50;\n\t\t\tforeach ($a as $v) {\n\t\t\t\tif ($v<$lfence || $v>$rfence) {\n\t\t\t\t\t$outliers[] = $v*1;\n\t\t\t\t} else if ($v < $mininside) {\n $mininside = $v*1;\n } else if ($v > $maxinside) {\n $maxinside = $v*1;\n }\n\t\t\t}\n\t\t\tif (count($outliers)>0) {\n\t\t\t\tif ($lfence>$min) {\n\t\t\t\t\t$min = $mininside;\n\t\t\t\t}\n\t\t\t\tif ($rfence<$max) {\n\t\t\t\t\t$max = $maxinside;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$yl = $ybase;\n\t\t$ym = $yl+1;\n\t\t$yh = $ym+1;\n\t\t$st .= \"line([$min,$yl],[$min,$yh]); rect([$q1,$yl],[$q3,$yh]); line([$q2,$yl],[$q2,$yh]);\";\n\t\t$st .= \"line([$max,$yl],[$max,$yh]); line([$min,$ym],[$q1,$ym]); line([$q3,$ym],[$max,$ym]);\";\n\t\tif (isset($options['showvals'])) {\n\t\t\t$st .= \"fontsize*=.8;fontfill='blue';text([$min,$yh],'$min','above');\";\n\t\t\t$st .= \"text([$q1,$yh],'$q1','above');\";\n\t\t\t$st .= \"text([$q2,$yh],'$q2','above');\";\n\t\t\t$st .= \"text([$q3,$yh],'$q3','above');\";\n\t\t\t$st .= \"text([$max,$yh],'$max','above');fontfill='black';fontsize*=1.25;\";\n\t\t\t$ybase += 2;\n\t\t}\n\t\t$alt .= 'Boxplot ';\n\t\tif (isset($dlbls[$i])) {\n\t\t\t$alt .= \"for {$dlbls[$i]}\";\n\t\t\t$ybase += 2;\n\t\t} else {\n\t\t\t$alt .= ($i+1);\n\t\t}\n\t\t$ybase += 3;\n\t\t$alt .= \": Left whisker at {$a[0]}. Left side of box at $q1. Line through box at $q2. Right side of box at $q3. Right whisker at $max.\\n\";\n\t\tif (count($outliers)>0) {\n\t\t\tforeach ($outliers as $v) {\n\t\t\t\t$st .= \"dot([$v,$ym],'open');\";\n\t\t\t\t$alt .= \"Dot at $v. \";\n\t\t\t}\n\t\t}\n\t}\n\t$ycnt = $ybase-1;\n\tif ($_SESSION['graphdisp']==0) {\n\t\treturn $alt;\n\t}\n\t$dw = $bigmax-$bigmin;\n\n\tif ($dw>100) {$step = 20;} else if ($dw > 50) { $step = 10; } else if ($dw > 20) { $step = 5;} else {$step=1;}\n\t$bigmin = floor($bigmin/$step)*$step;\n\t$bigmax = ceil($bigmax/$step)*$step;\n\n\t$outst = \"setBorder(15); initPicture($bigmin,$bigmax,-3,\".($ycnt).\");\";\n\t$outst .= \"axes($step,100,1,null,null,1,'off');\";\n\t$outst .= \"text([\". ($bigmin+.5*$dw) . \",-3],\\\"$label\\\");\";\n\tif (isset($dlbls)) {\n\t\t$ybase = 0;\n\t\tfor ($i=0;$i<$multi;$i++) {\n\t\t\t$ybase += isset($options['showvals'])?7:5;\n\t\t\tif ($multi>1) { $dlbl = $dlbls[$i];} else {$dlbl = $dlbls;}\n\t\t\t$st .= \"text([$bigmin,\". $ybase .\"],\\\"$dlbl\\\",\\\"right\\\");\";\n\t\t}\n\t}\n\t$outst .= $st;\n\t$width = isset($options['width'])?$options['width']:400;\n\treturn showasciisvg($outst,$width*1,50+12*$ycnt);\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function graphgetedgesarray($g,$op=[]) {\n\t$n = count($g[0]);\n\t$good = array();\n\tfor ($i=0; $i<$n; $i++) {\n\t\tfor ($j=$i+1;$j<$n;$j++) {\n\t\t\tif (!empty($op['digraph'])) {\n\t\t\t\tif(isset($g[$i][$j]) && $g[$i][$j]>0) {\n\t\t\t\t\t$good[] = array($i,$j);\n\t\t\t\t}\n\t\t\t\tif(isset($g[$j][$i]) && $g[$j][$i]>0) {\n\t\t\t\t\t$good[] = array($j,$i);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ((isset($g[$i][$j]) && $g[$i][$j]>0) || (isset($g[$j][$i]) && $g[$j][$i]>0)) {\n\t\t\t\t\t$good[] = array($i,$j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn $good;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function _smartTrim($text, $max_len, $trim_middle = false, $trim_chars = '...')\n\t{\n\t\t$text = trim($text);\n\n\t\tif (strlen($text) < $max_len) {\n\n\t\t\treturn $text;\n\n\t\t} elseif ($trim_middle) {\n\n\t\t\t$hasSpace = strpos($text, ' ');\n\t\t\tif (!$hasSpace) {\n\t\t\t\t/**\n\t\t\t\t * The entire string is one word. Just take a piece of the\n\t\t\t\t * beginning and a piece of the end.\n\t\t\t\t */\n\t\t\t\t$first_half = substr($text, 0, $max_len / 2);\n\t\t\t\t$last_half = substr($text, -($max_len - strlen($first_half)));\n\t\t\t} else {\n\t\t\t\t/**\n\t\t\t\t * Get last half first as it makes it more likely for the first\n\t\t\t\t * half to be of greater length. This is done because usually the\n\t\t\t\t * first half of a string is more recognizable. The last half can\n\t\t\t\t * be at most half of the maximum length and is potentially\n\t\t\t\t * shorter (only the last word).\n\t\t\t\t */\n\t\t\t\t$last_half = substr($text, -($max_len / 2));\n\t\t\t\t$last_half = trim($last_half);\n\t\t\t\t$last_space = strrpos($last_half, ' ');\n\t\t\t\tif (!($last_space === false)) {\n\t\t\t\t\t$last_half = substr($last_half, $last_space + 1);\n\t\t\t\t}\n\t\t\t\t$first_half = substr($text, 0, $max_len - strlen($last_half));\n\t\t\t\t$first_half = trim($first_half);\n\t\t\t\tif (substr($text, $max_len - strlen($last_half), 1) == ' ') {\n\t\t\t\t\t/**\n\t\t\t\t\t * The first half of the string was chopped at a space.\n\t\t\t\t\t */\n\t\t\t\t\t$first_space = $max_len - strlen($last_half);\n\t\t\t\t} else {\n\t\t\t\t\t$first_space = strrpos($first_half, ' ');\n\t\t\t\t}\n\t\t\t\tif (!($first_space === false)) {\n\t\t\t\t\t$first_half = substr($text, 0, $first_space);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn $first_half.$trim_chars.$last_half;\n\n\t\t} else {\n\n\t\t\t$trimmed_text = substr($text, 0, $max_len);\n\t\t\t$trimmed_text = trim($trimmed_text);\n\t\t\tif (substr($text, $max_len, 1) == ' ') {\n\t\t\t\t/**\n\t\t\t\t * The string was chopped at a space.\n\t\t\t\t */\n\t\t\t\t$last_space = $max_len;\n\t\t\t} else {\n\t\t\t\t/**\n\t\t\t\t * In PHP5, we can use 'offset' here -Mike\n\t\t\t\t */\n\t\t\t\t$last_space = strrpos($trimmed_text, ' ');\n\t\t\t}\n\t\t\tif (!($last_space === false)) {\n\t\t\t\t$trimmed_text = substr($trimmed_text, 0, $last_space);\n\t\t\t}\n\t\t\treturn $this->_removeTrailingPunctuation($trimmed_text).$trim_chars;\n\n\t\t}\n\n\t}", "smellKey": "S3776", "smellId": null, "repo": "MYOB09_hackazon", "language": "php"} {"function": "protected function geolocationManagement($default_country)\n {\n if (!in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {\n /* Check if Maxmind Database exists */\n if (@filemtime(_PS_GEOIP_DIR_._PS_GEOIP_CITY_FILE_)) {\n if (!isset($this->context->cookie->iso_code_country) || (isset($this->context->cookie->iso_code_country) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))))) {\n include_once(_PS_GEOIP_DIR_.'geoipcity.inc');\n\n $gi = geoip_open(realpath(_PS_GEOIP_DIR_._PS_GEOIP_CITY_FILE_), GEOIP_STANDARD);\n $record = geoip_record_by_addr($gi, Tools::getRemoteAddr());\n\n if (is_object($record)) {\n if (!in_array(strtoupper($record->country_code), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && !FrontController::isInWhitelistForGeolocation()) {\n if (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_) {\n $this->restrictedCountry = true;\n } elseif (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_) {\n $this->context->smarty->assign(array(\n 'restricted_country_mode' => true,\n 'geolocation_country' => $record->country_name\n ));\n }\n } else {\n $has_been_set = !isset($this->context->cookie->iso_code_country);\n $this->context->cookie->iso_code_country = strtoupper($record->country_code);\n }\n }\n }\n\n if (isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country)) {\n $this->context->cookie->iso_code_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));\n }\n\n if (isset($this->context->cookie->iso_code_country) && ($id_country = (int)Country::getByIso(strtoupper($this->context->cookie->iso_code_country)))) {\n /* Update defaultCountry */\n if ($default_country->iso_code != $this->context->cookie->iso_code_country) {\n $default_country = new Country($id_country);\n }\n if (isset($has_been_set) && $has_been_set) {\n $this->context->cookie->id_currency = (int)($default_country->id_currency ? (int)$default_country->id_currency : (int)Configuration::get('PS_CURRENCY_DEFAULT'));\n }\n return $default_country;\n } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_ && !FrontController::isInWhitelistForGeolocation()) {\n $this->restrictedCountry = true;\n } elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_ && !FrontController::isInWhitelistForGeolocation()) {\n $this->context->smarty->assign(array(\n 'restricted_country_mode' => true,\n 'geolocation_country' => isset($record->country_name) && $record->country_name ? $record->country_name : 'Undefined'\n ));\n }\n }\n }\n return false;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function runUpgradeModule()\n {\n $upgrade = &self::$modules_cache[$this->name]['upgrade'];\n foreach ($upgrade['upgrade_file_left'] as $num => $file_detail) {\n foreach ($file_detail['upgrade_function'] as $item) {\n if (function_exists($item)) {\n $upgrade['success'] = false;\n $upgrade['duplicate'] = true;\n break 2;\n }\n }\n\n include($file_detail['file']);\n\n // Call the upgrade function if defined\n $upgrade['success'] = false;\n foreach ($file_detail['upgrade_function'] as $item) {\n if (function_exists($item)) {\n $upgrade['success'] = $item($this);\n }\n }\n\n // Set detail when an upgrade succeed or failed\n if ($upgrade['success']) {\n $upgrade['number_upgraded'] += 1;\n $upgrade['upgraded_to'] = $file_detail['version'];\n\n unset($upgrade['upgrade_file_left'][$num]);\n } else {\n $upgrade['version_fail'] = $file_detail['version'];\n\n // If any errors, the module is disabled\n $this->disable();\n break;\n }\n }\n\n $upgrade['number_upgrade_left'] = count($upgrade['upgrade_file_left']);\n\n // Update module version in DB with the last succeed upgrade\n if ($upgrade['upgraded_to']) {\n Module::upgradeModuleVersion($this->name, $upgrade['upgraded_to']);\n }\n $this->setUpgradeMessage($upgrade);\n return $upgrade;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function simulateDirectConnections(): void\n {\n /** @var DBmysql $DB */\n global $DB;\n\n $DC_CONNECT = [];\n // TODO base on directconnect_types dynamically\n if ($this->options['keep_dc_monitor']) {\n $DC_CONNECT[] = 'Monitor';\n }\n if ($this->options['keep_dc_phone']) {\n $DC_CONNECT[] = 'Phone';\n }\n if ($this->options['keep_dc_peripheral']) {\n $DC_CONNECT[] = 'Peripheral';\n }\n if ($this->options['keep_dc_printer']) {\n $DC_CONNECT[] = 'Printer';\n }\n\n if (empty($DC_CONNECT)) {\n return;\n }\n\n foreach (Asset_PeripheralAsset::getPeripheralHostItemtypes() as $asset_itemtype) {\n if ($this->haveItemsToTransfer($asset_itemtype)) {\n foreach ($DC_CONNECT as $peripheral_itemtype) {\n $peripheral_itemtable = getTableForItemType($peripheral_itemtype);\n $relation_table = Asset_PeripheralAsset::getTable();\n\n // Clean DB / Search unexisting links and force disconnect\n $DB->delete(\n $relation_table,\n [\n $peripheral_itemtable . '.id' => null,\n $relation_table . '.itemtype_asset' => $asset_itemtype,\n $relation_table . '.itemtype_peripheral' => $peripheral_itemtype,\n ],\n [\n 'LEFT JOIN' => [\n $peripheral_itemtable => [\n 'ON' => [\n $relation_table => 'items_id_peripheral',\n $peripheral_itemtable => 'id',\n ]\n ]\n ]\n ]\n );\n\n if (!($peripheral = getItemForItemtype($peripheral_itemtype))) {\n continue;\n }\n if (!$this->haveItemsToTransfer($asset_itemtype)) {\n continue;\n }\n\n $iterator = $DB->request([\n 'SELECT' => ['items_id_peripheral'],\n 'DISTINCT' => true,\n 'FROM' => $relation_table,\n 'WHERE' => [\n 'itemtype_peripheral' => $peripheral_itemtype,\n 'itemtype_asset' => $asset_itemtype,\n 'items_id_asset' => $this->needtobe_transfer[$asset_itemtype]\n ]\n ]);\n\n foreach ($iterator as $data) {\n $this->evaluateTransfer($peripheral_itemtype, $data['items_id_peripheral']);\n }\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function draw_square() {\n \n $input = func_get_args();\n $argsArray = [];\n $args = '';\n $hasBase = false;\n $hasHeight = false;\n $hasUserAltText = false;\n $baseKey = \"\";\n $heightKey = \"\";\n $pointKey = \"\";\n $altPoint = \"\";\n $altBase = \"\";\n $altHeight = \"\";\n $colorFill = 'none';\n foreach ($input as $list) {\n if (!is_array($list)) {\n $list = listtoarray($list);\n }\n $list = array_map('trim', $list);\n $argsArray[]=$list;\n }\n $hasPoints = false;\n $size = 300;\n foreach ($argsArray as $key => $in) {\n if (empty($in) || count($in) == 0) {\n $in = [\"\",\"\"];\n }\n if ($in[0] == \"alttext\") {\n if (isset($in[1])) {\n $hasUserAltText = true;\n $userAltText = $in[1];\n }\n }\n if ($in[0] == \"colorfill\") {\n $colorFill = 'none';\n if (array_key_exists(1,$in)) {\n if ($in[1] == \"\") {\n $in[1] = 'none';\n }\n $colorFill = $in[1];\n }\n }\n if ($in[0]==\"size\" && isset($in[1])) {\n $size = $in[1];\n }\n if ($in[0]==\"base\") {\n $baseKey = $key;\n $hasBase = true;\n }\n if ($in[0]==\"height\") {\n $heightKey = $key;\n $hasHeight = true;\n }\n if ($in[0]==\"points\") {\n $hasPoints = true;\n $pointKey = $key;\n }\n }\n $args = \"fill='$colorFill';rect([-1,-1],[1,1]);fill='none';\";\n //echo $baseKey . $argsArray[$baseKey][1];\n if (!isset($argsArray[$baseKey][1])) {\n $argsArray[$baseKey][1] = \"\";\n }\n //echo $baseKey . $argsArray[$baseKey][1];\n if (!isset($argsArray[$heightKey][1])) {\n $argsArray[$heightKey][1] = \"\";\n }\n \n $baseLab = $argsArray[$baseKey][1];\n $heightLab = $argsArray[$heightKey][1];\n for ($i=0;$i<4;$i++) {\n if (!isset($argsArray[$pointKey][$i+1])) {\n $argsArray[$pointKey][$i+1] = '';\n }\n $pointLab[$i] = $argsArray[$pointKey][$i+1];\n $pointLab[$i] = preg_replace('/;/',',',$pointLab[$i]);\n }\n $args = $args . \"text([0,-1],'$baseLab',below);\";\n $args = $args . \"text([1,0],'$heightLab',right);\";\n \n if ($hasPoints === true) {\n $args = $args . \"dot([-1,-1]);dot([1,-1]);dot([1,1]);dot([-1,1]);\";\n $args = $args . \"text([-1,-1],'$pointLab[0]',below);\";\n $args = $args . \"text([1,-1],'$pointLab[1]',below);\";\n $args = $args . \"text([1,1],'$pointLab[2]',above);\";\n $args = $args . \"text([-1,1],'$pointLab[3]',above);\";\n $altPointLoc = [\"bottom left\",\"bottom right\",\"top right\",\"top left\"];\n }\n \n // Build alt text\n if ($hasUserAltText !== true) {\n $alt = \"A square\";\n $usedLab = array_filter($pointLab,'strlen');\n $countLab = count($usedLab);\n if ($countLab > 0) {\n $alt .= \" with\";\n $pointLabKeys = array_keys($usedLab);\n for ($i=0; $i<$countLab; $i++) {\n $altPoint .= ($countLab > 1 && $i == $countLab-1) ? \" and\" : \"\";\n $altPoint .= \" a point at {$altPointLoc[$pointLabKeys[$i]]} labeled {$pointLab[$pointLabKeys[$i]]}\";\n $altPoint .= ($countLab > 2 && $i < $countLab-1) ? \",\" : \"\";\n }\n }\n if ($hasBase === true) {\n $altBase = ($hasPoints === true) ? \",\" : \"\";\n $altBase .= \" with base labeled $baseLab\";\n }\n if ($hasHeight === true) {\n $altHeight = ($hasBase === true) ? \", and\" : (($hasPoints === true) ? \",\" : \"\");\n $altHeight .= \" with height labeled $heightLab\";\n }\n $alt = $alt.$altPoint.$altBase.$altHeight.\".\";\n } else {\n $alt = $userAltText;\n }\n $gr = showasciisvg(\"setBorder(5);initPicture(-1.5,1.5,-1.5,1.5);$args\",$size,$size,$alt);\n return $gr;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "private function buildCreateTableSQL(Table $table, bool $createIndexes, bool $createForeignKeys): array\n {\n if (count($table->getColumns()) === 0) {\n throw Exception::noColumnsSpecifiedForTable($table->getName());\n }\n\n $tableName = $table->getQuotedName($this);\n $options = $table->getOptions();\n $options['uniqueConstraints'] = [];\n $options['indexes'] = [];\n $options['primary'] = [];\n\n if ($createIndexes) {\n foreach ($table->getIndexes() as $index) {\n if (! $index->isPrimary()) {\n $options['indexes'][$index->getQuotedName($this)] = $index;\n\n continue;\n }\n\n $options['primary'] = $index->getQuotedColumns($this);\n $options['primary_index'] = $index;\n }\n\n foreach ($table->getUniqueConstraints() as $uniqueConstraint) {\n $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;\n }\n }\n\n if ($createForeignKeys) {\n $options['foreignKeys'] = [];\n\n foreach ($table->getForeignKeys() as $fkConstraint) {\n $options['foreignKeys'][] = $fkConstraint;\n }\n }\n\n $columnSql = [];\n $columns = [];\n\n foreach ($table->getColumns() as $column) {\n if (\n $this->_eventManager !== null\n && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)\n ) {\n Deprecation::trigger(\n 'doctrine/dbal',\n 'https://github.com/doctrine/dbal/issues/5784',\n 'Subscribing to %s events is deprecated.',\n Events::onSchemaCreateTableColumn,\n );\n\n $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);\n\n $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);\n\n $columnSql = array_merge($columnSql, $eventArgs->getSql());\n\n if ($eventArgs->isDefaultPrevented()) {\n continue;\n }\n }\n\n $columnData = $this->columnToArray($column);\n\n if (in_array($column->getName(), $options['primary'], true)) {\n $columnData['primary'] = true;\n }\n\n $columns[$columnData['name']] = $columnData;\n }\n\n if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {\n Deprecation::trigger(\n 'doctrine/dbal',\n 'https://github.com/doctrine/dbal/issues/5784',\n 'Subscribing to %s events is deprecated.',\n Events::onSchemaCreateTable,\n );\n\n $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);\n\n $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);\n\n if ($eventArgs->isDefaultPrevented()) {\n return array_merge($eventArgs->getSql(), $columnSql);\n }\n }\n\n $sql = $this->_getCreateTableSQL($tableName, $columns, $options);\n\n if ($this->supportsCommentOnStatement()) {\n if ($table->hasOption('comment')) {\n $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));\n }\n\n foreach ($table->getColumns() as $column) {\n $comment = $this->getColumnComment($column);\n\n if ($comment === null || $comment === '') {\n continue;\n }\n\n $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);\n }\n }\n\n return array_merge($sql, $columnSql);\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n if (isset($this->Account)) {\n return $this->Account;\n }\n if (isset($this->ActivityDefinition)) {\n return $this->ActivityDefinition;\n }\n if (isset($this->AdverseEvent)) {\n return $this->AdverseEvent;\n }\n if (isset($this->AllergyIntolerance)) {\n return $this->AllergyIntolerance;\n }\n if (isset($this->Appointment)) {\n return $this->Appointment;\n }\n if (isset($this->AppointmentResponse)) {\n return $this->AppointmentResponse;\n }\n if (isset($this->AuditEvent)) {\n return $this->AuditEvent;\n }\n if (isset($this->Basic)) {\n return $this->Basic;\n }\n if (isset($this->Binary)) {\n return $this->Binary;\n }\n if (isset($this->BiologicallyDerivedProduct)) {\n return $this->BiologicallyDerivedProduct;\n }\n if (isset($this->BodyStructure)) {\n return $this->BodyStructure;\n }\n if (isset($this->Bundle)) {\n return $this->Bundle;\n }\n if (isset($this->CapabilityStatement)) {\n return $this->CapabilityStatement;\n }\n if (isset($this->CarePlan)) {\n return $this->CarePlan;\n }\n if (isset($this->CareTeam)) {\n return $this->CareTeam;\n }\n if (isset($this->CatalogEntry)) {\n return $this->CatalogEntry;\n }\n if (isset($this->ChargeItem)) {\n return $this->ChargeItem;\n }\n if (isset($this->ChargeItemDefinition)) {\n return $this->ChargeItemDefinition;\n }\n if (isset($this->Claim)) {\n return $this->Claim;\n }\n if (isset($this->ClaimResponse)) {\n return $this->ClaimResponse;\n }\n if (isset($this->ClinicalImpression)) {\n return $this->ClinicalImpression;\n }\n if (isset($this->CodeSystem)) {\n return $this->CodeSystem;\n }\n if (isset($this->Communication)) {\n return $this->Communication;\n }\n if (isset($this->CommunicationRequest)) {\n return $this->CommunicationRequest;\n }\n if (isset($this->CompartmentDefinition)) {\n return $this->CompartmentDefinition;\n }\n if (isset($this->Composition)) {\n return $this->Composition;\n }\n if (isset($this->ConceptMap)) {\n return $this->ConceptMap;\n }\n if (isset($this->Condition)) {\n return $this->Condition;\n }\n if (isset($this->Consent)) {\n return $this->Consent;\n }\n if (isset($this->Contract)) {\n return $this->Contract;\n }\n if (isset($this->Coverage)) {\n return $this->Coverage;\n }\n if (isset($this->CoverageEligibilityRequest)) {\n return $this->CoverageEligibilityRequest;\n }\n if (isset($this->CoverageEligibilityResponse)) {\n return $this->CoverageEligibilityResponse;\n }\n if (isset($this->DetectedIssue)) {\n return $this->DetectedIssue;\n }\n if (isset($this->Device)) {\n return $this->Device;\n }\n if (isset($this->DeviceDefinition)) {\n return $this->DeviceDefinition;\n }\n if (isset($this->DeviceMetric)) {\n return $this->DeviceMetric;\n }\n if (isset($this->DeviceRequest)) {\n return $this->DeviceRequest;\n }\n if (isset($this->DeviceUseStatement)) {\n return $this->DeviceUseStatement;\n }\n if (isset($this->DiagnosticReport)) {\n return $this->DiagnosticReport;\n }\n if (isset($this->DocumentManifest)) {\n return $this->DocumentManifest;\n }\n if (isset($this->DocumentReference)) {\n return $this->DocumentReference;\n }\n if (isset($this->EffectEvidenceSynthesis)) {\n return $this->EffectEvidenceSynthesis;\n }\n if (isset($this->Encounter)) {\n return $this->Encounter;\n }\n if (isset($this->Endpoint)) {\n return $this->Endpoint;\n }\n if (isset($this->EnrollmentRequest)) {\n return $this->EnrollmentRequest;\n }\n if (isset($this->EnrollmentResponse)) {\n return $this->EnrollmentResponse;\n }\n if (isset($this->EpisodeOfCare)) {\n return $this->EpisodeOfCare;\n }\n if (isset($this->EventDefinition)) {\n return $this->EventDefinition;\n }\n if (isset($this->Evidence)) {\n return $this->Evidence;\n }\n if (isset($this->EvidenceVariable)) {\n return $this->EvidenceVariable;\n }\n if (isset($this->ExampleScenario)) {\n return $this->ExampleScenario;\n }\n if (isset($this->ExplanationOfBenefit)) {\n return $this->ExplanationOfBenefit;\n }\n if (isset($this->FamilyMemberHistory)) {\n return $this->FamilyMemberHistory;\n }\n if (isset($this->Flag)) {\n return $this->Flag;\n }\n if (isset($this->Goal)) {\n return $this->Goal;\n }\n if (isset($this->GraphDefinition)) {\n return $this->GraphDefinition;\n }\n if (isset($this->Group)) {\n return $this->Group;\n }\n if (isset($this->GuidanceResponse)) {\n return $this->GuidanceResponse;\n }\n if (isset($this->HealthcareService)) {\n return $this->HealthcareService;\n }\n if (isset($this->ImagingStudy)) {\n return $this->ImagingStudy;\n }\n if (isset($this->Immunization)) {\n return $this->Immunization;\n }\n if (isset($this->ImmunizationEvaluation)) {\n return $this->ImmunizationEvaluation;\n }\n if (isset($this->ImmunizationRecommendation)) {\n return $this->ImmunizationRecommendation;\n }\n if (isset($this->ImplementationGuide)) {\n return $this->ImplementationGuide;\n }\n if (isset($this->InsurancePlan)) {\n return $this->InsurancePlan;\n }\n if (isset($this->Invoice)) {\n return $this->Invoice;\n }\n if (isset($this->Library)) {\n return $this->Library;\n }\n if (isset($this->Linkage)) {\n return $this->Linkage;\n }\n if (isset($this->List)) {\n return $this->List;\n }\n if (isset($this->Location)) {\n return $this->Location;\n }\n if (isset($this->Measure)) {\n return $this->Measure;\n }\n if (isset($this->MeasureReport)) {\n return $this->MeasureReport;\n }\n if (isset($this->Media)) {\n return $this->Media;\n }\n if (isset($this->Medication)) {\n return $this->Medication;\n }\n if (isset($this->MedicationAdministration)) {\n return $this->MedicationAdministration;\n }\n if (isset($this->MedicationDispense)) {\n return $this->MedicationDispense;\n }\n if (isset($this->MedicationKnowledge)) {\n return $this->MedicationKnowledge;\n }\n if (isset($this->MedicationRequest)) {\n return $this->MedicationRequest;\n }\n if (isset($this->MedicationStatement)) {\n return $this->MedicationStatement;\n }\n if (isset($this->MedicinalProduct)) {\n return $this->MedicinalProduct;\n }\n if (isset($this->MedicinalProductAuthorization)) {\n return $this->MedicinalProductAuthorization;\n }\n if (isset($this->MedicinalProductContraindication)) {\n return $this->MedicinalProductContraindication;\n }\n if (isset($this->MedicinalProductIndication)) {\n return $this->MedicinalProductIndication;\n }\n if (isset($this->MedicinalProductIngredient)) {\n return $this->MedicinalProductIngredient;\n }\n if (isset($this->MedicinalProductInteraction)) {\n return $this->MedicinalProductInteraction;\n }\n if (isset($this->MedicinalProductManufactured)) {\n return $this->MedicinalProductManufactured;\n }\n if (isset($this->MedicinalProductPackaged)) {\n return $this->MedicinalProductPackaged;\n }\n if (isset($this->MedicinalProductPharmaceutical)) {\n return $this->MedicinalProductPharmaceutical;\n }\n if (isset($this->MedicinalProductUndesirableEffect)) {\n return $this->MedicinalProductUndesirableEffect;\n }\n if (isset($this->MessageDefinition)) {\n return $this->MessageDefinition;\n }\n if (isset($this->MessageHeader)) {\n return $this->MessageHeader;\n }\n if (isset($this->MolecularSequence)) {\n return $this->MolecularSequence;\n }\n if (isset($this->NamingSystem)) {\n return $this->NamingSystem;\n }\n if (isset($this->NutritionOrder)) {\n return $this->NutritionOrder;\n }\n if (isset($this->Observation)) {\n return $this->Observation;\n }\n if (isset($this->ObservationDefinition)) {\n return $this->ObservationDefinition;\n }\n if (isset($this->OperationDefinition)) {\n return $this->OperationDefinition;\n }\n if (isset($this->OperationOutcome)) {\n return $this->OperationOutcome;\n }\n if (isset($this->Organization)) {\n return $this->Organization;\n }\n if (isset($this->OrganizationAffiliation)) {\n return $this->OrganizationAffiliation;\n }\n if (isset($this->Patient)) {\n return $this->Patient;\n }\n if (isset($this->PaymentNotice)) {\n return $this->PaymentNotice;\n }\n if (isset($this->PaymentReconciliation)) {\n return $this->PaymentReconciliation;\n }\n if (isset($this->Person)) {\n return $this->Person;\n }\n if (isset($this->PlanDefinition)) {\n return $this->PlanDefinition;\n }\n if (isset($this->Practitioner)) {\n return $this->Practitioner;\n }\n if (isset($this->PractitionerRole)) {\n return $this->PractitionerRole;\n }\n if (isset($this->Procedure)) {\n return $this->Procedure;\n }\n if (isset($this->Provenance)) {\n return $this->Provenance;\n }\n if (isset($this->Questionnaire)) {\n return $this->Questionnaire;\n }\n if (isset($this->QuestionnaireResponse)) {\n return $this->QuestionnaireResponse;\n }\n if (isset($this->RelatedPerson)) {\n return $this->RelatedPerson;\n }\n if (isset($this->RequestGroup)) {\n return $this->RequestGroup;\n }\n if (isset($this->ResearchDefinition)) {\n return $this->ResearchDefinition;\n }\n if (isset($this->ResearchElementDefinition)) {\n return $this->ResearchElementDefinition;\n }\n if (isset($this->ResearchStudy)) {\n return $this->ResearchStudy;\n }\n if (isset($this->ResearchSubject)) {\n return $this->ResearchSubject;\n }\n if (isset($this->RiskAssessment)) {\n return $this->RiskAssessment;\n }\n if (isset($this->RiskEvidenceSynthesis)) {\n return $this->RiskEvidenceSynthesis;\n }\n if (isset($this->Schedule)) {\n return $this->Schedule;\n }\n if (isset($this->SearchParameter)) {\n return $this->SearchParameter;\n }\n if (isset($this->ServiceRequest)) {\n return $this->ServiceRequest;\n }\n if (isset($this->Slot)) {\n return $this->Slot;\n }\n if (isset($this->Specimen)) {\n return $this->Specimen;\n }\n if (isset($this->SpecimenDefinition)) {\n return $this->SpecimenDefinition;\n }\n if (isset($this->StructureDefinition)) {\n return $this->StructureDefinition;\n }\n if (isset($this->StructureMap)) {\n return $this->StructureMap;\n }\n if (isset($this->Subscription)) {\n return $this->Subscription;\n }\n if (isset($this->Substance)) {\n return $this->Substance;\n }\n if (isset($this->SubstanceNucleicAcid)) {\n return $this->SubstanceNucleicAcid;\n }\n if (isset($this->SubstancePolymer)) {\n return $this->SubstancePolymer;\n }\n if (isset($this->SubstanceProtein)) {\n return $this->SubstanceProtein;\n }\n if (isset($this->SubstanceReferenceInformation)) {\n return $this->SubstanceReferenceInformation;\n }\n if (isset($this->SubstanceSourceMaterial)) {\n return $this->SubstanceSourceMaterial;\n }\n if (isset($this->SubstanceSpecification)) {\n return $this->SubstanceSpecification;\n }\n if (isset($this->SupplyDelivery)) {\n return $this->SupplyDelivery;\n }\n if (isset($this->SupplyRequest)) {\n return $this->SupplyRequest;\n }\n if (isset($this->Task)) {\n return $this->Task;\n }\n if (isset($this->TerminologyCapabilities)) {\n return $this->TerminologyCapabilities;\n }\n if (isset($this->TestReport)) {\n return $this->TestReport;\n }\n if (isset($this->TestScript)) {\n return $this->TestScript;\n }\n if (isset($this->ValueSet)) {\n return $this->ValueSet;\n }\n if (isset($this->VerificationResult)) {\n return $this->VerificationResult;\n }\n if (isset($this->VisionPrescription)) {\n return $this->VisionPrescription;\n }\n if (isset($this->Parameters)) {\n return $this->Parameters;\n }\n return null;\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "private function transferLinkedSuppliers($itemtype, $ID, $newID): void\n {\n /** @var DBmysql $DB */\n global $DB;\n\n if (!is_a($itemtype, CommonITILObject::class, true)) {\n return;\n }\n\n /* @var CommonITILObject $item */\n $item = new $itemtype();\n $linkclass = $item->supplierlinkclass;\n if (!is_a($linkclass, CommonITILActor::class, true)) {\n return;\n }\n\n /* @var CommonITILActor $link */\n $link = new $linkclass();\n $field = getForeignKeyFieldForItemType($itemtype);\n $table = $link::getTable();\n\n $iterator = $DB->request([\n 'FROM' => $table,\n 'WHERE' => [$field => $ID]\n ]);\n\n foreach ($iterator as $data) {\n $input = [];\n\n if ($data['suppliers_id'] > 0) {\n $supplier = new Supplier();\n\n if ($supplier->getFromDB($data['suppliers_id'])) {\n $newID = -1;\n $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_suppliers',\n 'WHERE' => [\n 'entities_id' => $this->to,\n 'name' => $supplier->fields['name']\n ]\n ]);\n\n if (count($iterator)) {\n $result = $iterator->current();\n $newID = $result['id'];\n }\n if ($newID < 0) {\n // 1 - create new item\n unset($supplier->fields['id']);\n $input = $supplier->fields;\n $input['entities_id'] = $this->to;\n // Not set new entity Do by transferItem\n unset($supplier->fields);\n $newID = $supplier->add($input);\n }\n\n $input2['id'] = $data['id'];\n $input2[$field] = $ID;\n $input2['suppliers_id'] = $newID;\n $link->update($input2);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "protected static function loadUpgradeVersionList($module_name, $module_version, $registered_version)\n {\n $list = array();\n\n $upgrade_path = _PS_MODULE_DIR_.$module_name.'/upgrade/';\n\n // Check if folder exist and it could be read\n if (file_exists($upgrade_path) && ($files = scandir($upgrade_path))) {\n // Read each file name\n foreach ($files as $file) {\n if (!in_array($file, array('.', '..', '.svn', 'index.php')) && preg_match('/\\.php$/', $file)) {\n $tab = explode('-', $file);\n\n if (!isset($tab[1])) {\n continue;\n }\n\n $file_version = basename($tab[1], '.php');\n // Compare version, if minor than actual, we need to upgrade the module\n if (count($tab) == 2 &&\n (Tools::version_compare($file_version, $module_version, '<=') &&\n Tools::version_compare($file_version, $registered_version, '>'))) {\n $list[] = array(\n 'file' => $upgrade_path.$file,\n 'version' => $file_version,\n 'upgrade_function' => array(\n 'upgrade_module_'.str_replace('.', '_', $file_version),\n 'upgradeModule'.str_replace('.', '', $file_version))\n );\n }\n }\n }\n }\n\n // No files upgrade, then upgrade succeed\n if (count($list) == 0) {\n self::$modules_cache[$module_name]['upgrade']['success'] = true;\n Module::upgradeModuleVersion($module_name, $module_version);\n }\n\n usort($list, 'ps_module_version_sort');\n\n // Set the list to module cache\n self::$modules_cache[$module_name]['upgrade']['upgrade_file_left'] = $list;\n self::$modules_cache[$module_name]['upgrade']['available_upgrade'] = count($list);\n return (bool)count($list);\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function smarty_core_get_php_resource(&$params, &$smarty)\n{\n\n $params['resource_base_path'] = $smarty->trusted_dir;\n $smarty->_parse_resource_name($params, $smarty);\n\n /*\n * Find out if the resource exists.\n */\n\n if ($params['resource_type'] == 'file') {\n $_readable = false;\n if(file_exists($params['resource_name']) && is_readable($params['resource_name'])) {\n $_readable = true;\n } else {\n // test for file in include_path\n $_params = array('file_path' => $params['resource_name']);\n require_once(SMARTY_CORE_DIR . 'core.get_include_path.php');\n if(smarty_core_get_include_path($_params, $smarty)) {\n $_include_path = $_params['new_file_path'];\n $_readable = true;\n }\n }\n } else if ($params['resource_type'] != 'file') {\n $_template_source = null;\n $_readable = is_callable($smarty->_plugins['resource'][$params['resource_type']][0][0])\n && call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][0],\n array($params['resource_name'], &$_template_source, &$smarty));\n }\n\n /*\n * Set the error function, depending on which class calls us.\n */\n if (method_exists($smarty, '_syntax_error')) {\n $_error_funcc = '_syntax_error';\n } else {\n $_error_funcc = 'trigger_error';\n }\n\n if ($_readable) {\n if ($smarty->security) {\n require_once(SMARTY_CORE_DIR . 'core.is_trusted.php');\n if (!smarty_core_is_trusted($params, $smarty)) {\n $smarty->$_error_funcc('(secure mode) ' . $params['resource_type'] . ':' . $params['resource_name'] . ' is not trusted');\n return false;\n }\n }\n } else {\n $smarty->$_error_funcc($params['resource_type'] . ':' . $params['resource_name'] . ' is not readable');\n return false;\n }\n\n if ($params['resource_type'] == 'file') {\n $params['php_resource'] = $params['resource_name'];\n } else {\n $params['php_resource'] = $_template_source;\n }\n return true;\n}", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "protected function initialize(InputInterface $input, OutputInterface $output): void\n {\n if ($onlySteps = $input->getOption('only-steps')) {\n $onlySteps = array_map('trim', explode(',', $onlySteps));\n $this->installer->setRunInstallSteps($onlySteps);\n }\n\n if ($input->getOption('skip-database-config')) {\n $this->installer->setSkipDatabaseConfig(true);\n }\n\n //check skipping database creation or database data\n if ($input->getOption('skip-database-structure')) {\n $this->installer->setCreateDatabaseStructure(false);\n }\n if ($input->getOption('skip-database-data')) {\n $this->installer->setImportDatabaseData(false);\n }\n if ($input->getOption('skip-database-data-dump')) {\n $this->installer->setImportDatabaseDataDump(false);\n }\n $bundleOption = $input->getOption('install-bundles');\n if (false !== $bundleOption) {\n $bundleSetupEvent = $this->installer->dispatchBundleSetupEvent();\n\n if (null === $bundleOption) {\n $bundles = [];\n } else {\n $bundles = explode(',', $bundleOption);\n }\n\n $installableBundles = $bundleSetupEvent->getInstallableBundles($bundles);\n $this->installer->setBundlesToInstall($installableBundles, $bundleSetupEvent->getAvailableBundles(), $bundleSetupEvent->getExcludeBundlesFromPhpBundles());\n }\n\n $this->io = new PimcoreStyle($input, $output);\n\n foreach ($this->getOptions() as $name => $config) {\n if (!$this->installerNeedsOption($config)) {\n continue;\n }\n\n $value = $input->getOption($name);\n $isDefaultValue = isset($config['default']) && $value === $config['default'];\n\n // show warning for insecure options\n if ($value && ($config['insecure'] ?? false)) {\n $this->io->writeln([\n sprintf(\n '<comment>[WARNING]</comment> Using sensitive options (<comment>--%s</comment>) on the command line interface can be insecure.',\n $name\n ),\n sprintf(\n 'Consider using the interactive prompt or the <comment>%s</comment> environment variable instead.',\n $config['env']\n ),\n ]);\n\n $this->io->newLine();\n }\n\n // set option values from env vars\n if (!$value || $isDefaultValue) {\n if ($env = getenv($config['env'])) {\n $input->setOption($name, $env);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public static function getModuleControllers($type = 'all', $module = null)\n {\n $modules_controllers = array();\n if (is_null($module)) {\n $modules = Module::getModulesOnDisk(true);\n } elseif (!is_array($module)) {\n $modules = array(Module::getInstanceByName($module));\n } else {\n $modules = array();\n foreach ($module as $_mod) {\n $modules[] = Module::getInstanceByName($_mod);\n }\n }\n\n foreach ($modules as $mod) {\n foreach (Dispatcher::getControllersInDirectory(_PS_MODULE_DIR_.$mod->name.'/controllers/') as $controller) {\n if ($type == 'admin') {\n if (strpos($controller, 'Admin') !== false) {\n $modules_controllers[$mod->name][] = $controller;\n }\n } elseif ($type == 'front') {\n if (strpos($controller, 'Admin') === false) {\n $modules_controllers[$mod->name][] = $controller;\n }\n } else {\n $modules_controllers[$mod->name][] = $controller;\n }\n }\n }\n return $modules_controllers;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "private function fillNextRows(array $rows, int $line): array\n {\n $unmergedRows = [];\n foreach ($rows[$line] as $column => $cell) {\n if (null !== $cell && !$cell instanceof TableCell && !\\is_scalar($cell) && !(\\is_object($cell) && method_exists($cell, '__toString'))) {\n throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing \"__toString()\", \"%s\" given.', get_debug_type($cell)));\n }\n if ($cell instanceof TableCell && $cell->getRowspan() > 1) {\n $nbLines = $cell->getRowspan() - 1;\n $lines = [$cell];\n if (strstr($cell, \"\\n\")) {\n $lines = explode(\"\\n\", str_replace(\"\\n\", \"<fg=default;bg=default>\\n</>\", $cell));\n $nbLines = \\count($lines) > $nbLines ? substr_count($cell, \"\\n\") : $nbLines;\n\n $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]);\n unset($lines[0]);\n }\n\n // create a two dimensional array (rowspan x colspan)\n $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);\n foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {\n $value = $lines[$unmergedRowKey - $line] ?? '';\n $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan(), 'style' => $cell->getStyle()]);\n if ($nbLines === $unmergedRowKey - $line) {\n break;\n }\n }\n }\n }\n\n foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {\n // we need to know if $unmergedRow will be merged or inserted into $rows\n if (isset($rows[$unmergedRowKey]) && \\is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {\n foreach ($unmergedRow as $cellKey => $cell) {\n // insert cell into row at cellKey position\n array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);\n }\n } else {\n $row = $this->copyRow($rows, $unmergedRowKey - 1);\n foreach ($unmergedRow as $column => $cell) {\n if (!empty($cell)) {\n $row[$column] = $unmergedRow[$column];\n }\n }\n array_splice($rows, $unmergedRowKey, 0, [$row]);\n }\n }\n\n return $rows;\n }", "smellKey": "S3776", "smellId": null, "repo": "LT-Linas35_nextcloud_server", "language": "php"} {"function": "private function getMaaltijd($mid): array\n\t{\n\t\t// @TODO clean up this ugly code\n\t\t$maaltijd2 = null;\n\n\t\ttry {\n\t\t\tif (\n\t\t\t\t$mid === 'next' ||\n\t\t\t\t$mid === 'eerstvolgende' ||\n\t\t\t\t$mid === 'next2' ||\n\t\t\t\t$mid === 'eerstvolgende2'\n\t\t\t) {\n\t\t\t\t$maaltijden = $this->maaltijdenService->getKomendeMaaltijdenVoorLid(\n\t\t\t\t\tLoginService::getProfiel()\n\t\t\t\t); // met filter\n\t\t\t\t$aantal = sizeof($maaltijden);\n\t\t\t\tif ($aantal < 1) {\n\t\t\t\t\tthrow new BbException(\n\t\t\t\t\t\t'<div class=\"bb-block bb-maaltijd\">Geen aankomende maaltijd.</div>'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t$maaltijd = reset($maaltijden);\n\t\t\t\tif (str_ends_with($mid, '2') && $aantal >= 2) {\n\t\t\t\t\tunset($maaltijden[$maaltijd->maaltijd_id]);\n\t\t\t\t\t$maaltijd2 = reset($maaltijden);\n\t\t\t\t}\n\t\t\t} elseif ($mid === 'beoordeling') {\n\t\t\t\t$timestamp = date_create_immutable(\n\t\t\t\t\tInstellingUtil::instelling('maaltijden', 'beoordeling_periode')\n\t\t\t\t);\n\t\t\t\t$recent = $this->maaltijdAanmeldingenService->getRecenteAanmeldingenVoorLid(\n\t\t\t\t\tLoginService::getUid(),\n\t\t\t\t\t$timestamp\n\t\t\t\t);\n\t\t\t\t$recent = array_slice(array_map(fn($m) => $m->maaltijd, $recent), -2);\n\t\t\t\tif (count($recent) === 0) {\n\t\t\t\t\tthrow new BbException('');\n\t\t\t\t}\n\t\t\t\t$maaltijd = array_values($recent)[0];\n\t\t\t\tif (count($recent) > 1) {\n\t\t\t\t\t$maaltijd2 = array_values($recent)[1];\n\t\t\t\t}\n\t\t\t} elseif (preg_match('/\\d+/', (string) $mid)) {\n\t\t\t\t$maaltijd = $this->maaltijdenService->getMaaltijdVoorKetzer((int) $mid); // met filter\n\n\t\t\t\tif (!$maaltijd) {\n\t\t\t\t\tthrow new BbException('');\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (CsrException $e) {\n\t\t\tif (str_contains($e->getMessage(), 'Not found')) {\n\t\t\t\tthrow new BbException(\n\t\t\t\t\t'<div class=\"bb-block bb-maaltijd\">Maaltijd niet gevonden: ' .\n\t\t\t\t\t\thtmlspecialchars((string) $mid) .\n\t\t\t\t\t\t'</div>'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new BbException($e->getMessage());\n\t\t}\n\t\tif (!isset($maaltijd)) {\n\t\t\tthrow new BbException(\n\t\t\t\t'<div class=\"bb-block bb-maaltijd\">Maaltijd niet gevonden: ' .\n\t\t\t\t\thtmlspecialchars((string) $mid) .\n\t\t\t\t\t'</div>'\n\t\t\t);\n\t\t}\n\t\treturn [$maaltijd, $maaltijd2];\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "private function doVersionCleanup(): void\n {\n $systemSettingsConfig = $this->config->getSystemSettingsConfig();\n $conf = [\n 'document' => $systemSettingsConfig['documents']['versions'] ?? null,\n 'asset' => $systemSettingsConfig['assets']['versions'] ?? null,\n 'object' => $systemSettingsConfig['objects']['versions'] ?? null,\n ];\n\n $elementTypes = [];\n\n foreach ($conf as $elementType => $tConf) {\n $versioningType = 'steps';\n //skip cleanup if element is null\n if (is_null($tConf)) {\n continue;\n }\n //skip cleanup if both, 'steps' & 'days', is null\n if (is_null($tConf['steps']) && is_null($tConf['days'])) {\n continue;\n }\n $value = $tConf['steps'] ?? 10;\n\n if (isset($tConf['days'])) {\n $versioningType = 'days';\n $value = (int)$tConf['days'];\n }\n\n $elementTypes[] = [\n 'elementType' => $elementType,\n $versioningType => $value,\n ];\n }\n\n $list = new Version\\Listing();\n $ignoredIds = $list->setLoadAutoSave(true)->setCondition(' autoSave = 1 ')->loadIdList();\n\n // Not very pretty and should be solved using a repository....\n $dao = new Version();\n $dao = $dao->getDao();\n\n while (true) {\n $versions = $dao->maintenanceGetOutdatedVersions($elementTypes, $ignoredIds);\n\n if (count($versions) === 0) {\n break;\n }\n\n $counter = 0;\n\n $this->logger->debug('versions to check: ' . count($versions));\n\n $totalCount = count($versions);\n foreach ($versions as $index => $id) {\n if (!$version = Version::getById($id)) {\n $ignoredIds[] = $id;\n $this->logger->debug('Version with ' . $id . \" not found\\n\");\n\n continue;\n }\n\n $counter++;\n\n // do not delete public versions\n if ($version->getPublic()) {\n $ignoredIds[] = $version->getId();\n\n continue;\n }\n\n // do not delete versions referenced in the scheduler\n if ($dao->isVersionUsedInScheduler($version)) {\n $ignoredIds[] = $version->getId();\n\n continue;\n }\n\n $element = null;\n\n if ($version->getCtype() === 'document') {\n $element = Document::getById($version->getCid());\n } elseif ($version->getCtype() === 'asset') {\n $element = Asset::getById($version->getCid());\n } elseif ($version->getCtype() === 'object') {\n $element = DataObject::getById($version->getCid());\n }\n\n if ($element instanceof Element\\ElementInterface) {\n $this->logger->debug('currently checking Element-ID: ' . $element->getId() . ' Element-Type: ' . Element\\Service::getElementType($element) . ' in cycle: ' . $counter . '/' . $totalCount);\n\n if ($element->getModificationDate() >= $version->getDate()) {\n // delete version if it is outdated\n $this->logger->debug('delete version: ' . $version->getId() . ' because it is outdated');\n $version->delete();\n } else {\n $ignoredIds[] = $version->getId();\n $this->logger->debug('do not delete version (' . $version->getId() . \") because version's date is newer than the actual modification date of the element. Element-ID: \" . $element->getId() . ' Element-Type: ' . Element\\Service::getElementType($element));\n }\n } else {\n // delete version if the corresponding element doesn't exist anymore\n $this->logger->debug('delete version (' . $version->getId() . \") because the corresponding element doesn't exist anymore\");\n $version->delete();\n }\n\n // call the garbage collector if memory consumption is > 100MB\n if (memory_get_usage() > 100000000) {\n Pimcore::collectGarbage();\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function folderSubs($src, $exclude=null, $full_path=true) {\n $res = array();\n\n $src = $src . ((substr($src,-1)=='/')?'':'/');\n\n if(file_exists($src)){\n\n $dir = opendir($src);\n if($dir!==false){\n\n\n while(false !== ( $file = readdir($dir)) ) {\n if (( $file != '.' ) && ( $file != '..' ) && is_dir($src . $file)) {\n\n if(is_array($exclude) && in_array($file, $exclude)){\n continue;\n }\n\n if($full_path){\n $res[] = $src.$file.'/';\n }else{\n $res[] = $file;\n }\n\n }\n }\n closedir($dir);\n }\n }\n\n return $res;\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['height'])) {\n $this->setHeight($data['height']);\n }\n if (isset($data['width'])) {\n $this->setWidth($data['width']);\n }\n if (isset($data['depth'])) {\n $this->setDepth($data['depth']);\n }\n if (isset($data['weight'])) {\n $this->setWeight($data['weight']);\n }\n if (isset($data['nominalVolume'])) {\n $this->setNominalVolume($data['nominalVolume']);\n }\n if (isset($data['externalDiameter'])) {\n $this->setExternalDiameter($data['externalDiameter']);\n }\n if (isset($data['shape'])) {\n $this->setShape($data['shape']);\n }\n if (isset($data['color'])) {\n if (is_array($data['color'])) {\n foreach ($data['color'] as $d) {\n $this->addColor($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"color\" must be array of objects or null, ' . gettype($data['color']) . ' seen.');\n }\n }\n if (isset($data['imprint'])) {\n if (is_array($data['imprint'])) {\n foreach ($data['imprint'] as $d) {\n $this->addImprint($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"imprint\" must be array of objects or null, ' . gettype($data['imprint']) . ' seen.');\n }\n }\n if (isset($data['image'])) {\n if (is_array($data['image'])) {\n foreach ($data['image'] as $d) {\n $this->addImage($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"image\" must be array of objects or null, ' . gettype($data['image']) . ' seen.');\n }\n }\n if (isset($data['scoring'])) {\n $this->setScoring($data['scoring']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function export(ExportStreamWriter $writer, ExportJob $job, $lastResourceIdExported = null): void\n {\n if (!($this instanceof IResourceReadableService)) {\n // we need to ensure we only get called in a method that implements the getAll method.\n throw new \\BadMethodCallException(\"Trait can only be used in classes that implement the \" . IResourceReadableService::class . \" interface\");\n }\n $type = $job->getExportType();\n\n // algorithm\n // go through each resource and grab the related service\n // check if the service is a PatientCompartment resource, if so, set the patient uuids to export\n // if we are a Medication request since we are using RXCUI for our drug formulariesthere is no Provenance resource and we can just skip it\n\n $servicesByResource = $this->serviceLocator->findServices(IResourceUSCIGProfileService::class);\n\n $patientUuids = [];\n if ($type == ExportJob::EXPORT_OPERATION_GROUP) {\n $patientUuids = $job->getPatientUuidsToExport();\n }\n\n foreach ($job->getResources() as $resource) {\n $searchParams = [];\n $searchParams['_revinclude'] = 'Provenance:target';\n if ($resource != \"Provenance\" && isset($servicesByResource[$resource]) && $servicesByResource[$resource] instanceof IResourceReadableService) {\n $service = $servicesByResource[$resource];\n if ($type == ExportJob::EXPORT_OPERATION_GROUP) {\n // service supports filtering by patients so let's do that\n if ($service instanceof IPatientCompartmentResourceService) {\n $searchField = $service->getPatientContextSearchField();\n $searchParams[$searchField->getName()] = implode(\",\", $patientUuids);\n }\n }\n $searchParams['_lastUpdated'] = $job->getResourceIncludeSearchParamValue();\n try {\n $serviceResult = $service->getAll($searchParams);\n // now loop through and grab all of our provenance resources\n if ($serviceResult->hasData()) {\n foreach ($serviceResult->getData() as $record) {\n if (!($record instanceof FHIRDomainResource)) {\n throw new ExportException(self::class . \" returned records that are not a valid fhir resource type for this class\", 0, $lastResourceIdExported);\n }\n // we only want to write out provenance records\n if (!($record instanceof FHIRProvenance)) {\n continue;\n }\n $writer->append($record);\n $lastResourceIdExported = $record->getId();\n }\n }\n } catch (SearchFieldException $exception) {\n $message = $exception->getMessage() . \" Search Field \" . $exception->getField();\n throw new ExportException($message, 0, $lastResourceIdExported);\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function createRecord($users = false, $stugroupid = 0, $recordStart = true, $lti_sourcedid = '') {\n // if group, lookup group members. Otherwise just use current user\n $lti_sourcedidarr = [];\n if ($users === false) {\n $users = array($this->curUid);\n } else if (is_array($lti_sourcedid)) {\n $lti_sourcedidarr = $lti_sourcedid;\n if (isset($lti_sourcedidarr[$this->curUid])) {\n $lti_sourcedid = $lti_sourcedidarr[$this->curUid];\n } else {\n $lti_sourcedid = '';\n }\n }\n\n //initialize a blank record\n $this->assessRecord = array(\n 'assessmentid' => $this->curAid,\n 'userid' => $this->curUid,\n 'agroupid' => $stugroupid,\n 'lti_sourcedid' => $lti_sourcedid,\n 'ver' => 2,\n 'timeontask' => 0,\n 'timelimitexp' => 0,\n 'starttime' => $recordStart ? $this->now : 0,\n 'lastchange' => 0,\n 'score' => 0,\n 'status' => 0, // overridden later\n 'scoreddata' => '',\n 'practicedata' => ''\n );\n\n // generate practice data if in practice\n $waspractice = $this->is_practice;\n if ($this->is_practice) {\n $this->buildAssessData($recordStart);\n $practicetosave = (!empty($this->data)) ? gzcompress(json_encode($this->data, JSON_INVALID_UTF8_IGNORE)) : '';\n $this->assessRecord['practicedata'] = $practicetosave;\n $this->setInPractice(false);\n } else {\n $practicetosave = '';\n }\n\n //generate scored data\n $this->buildAssessData($recordStart && !$waspractice);\n $scoredtosave = (!empty($this->data)) ? gzcompress(json_encode($this->data, JSON_INVALID_UTF8_IGNORE)) : '';\n $this->assessRecord['scoreddata'] = $scoredtosave;\n\n // switch back to practice if started that way\n if ($waspractice) {\n $this->setInPractice(true);\n }\n\n // Save to Database\n $qarr = array();\n $vals = array();\n foreach ($users as $uid) {\n $vals[] = '(?,?,?,?,?,?,?,?,?)';\n $this_lti_sourcedid = '';\n if (isset($lti_sourcedidarr[$uid])) {\n $this_lti_sourcedid = $lti_sourcedidarr[$uid];\n } else if ($uid==$this->curUid) {\n $this_lti_sourcedid = $lti_sourcedid;\n }\n array_push($qarr,\n $uid,\n $this->curAid,\n $stugroupid,\n $this_lti_sourcedid,\n $recordStart ? $this->now : 0,\n 2,\n $this->assessRecord['status'],\n $scoredtosave,\n $practicetosave\n );\n }\n $query = 'INSERT INTO imas_assessment_records (userid, assessmentid,\n agroupid, lti_sourcedid, starttime, ver, status, scoreddata, practicedata)\n VALUES '.implode(',', $vals);\n $stm = $this->DBH->prepare($query);\n $stm->execute($qarr);\n\n $this->hasRecord = true;\n }", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function __call($name, $args)\n {\n static $_prefixes = array('set' => true, 'get' => true);\n static $_resolved_property_name = array();\n static $_resolved_property_source = array();\n\n // method of Smarty object?\n if (method_exists($this->smarty, $name)) {\n return call_user_func_array(array($this->smarty, $name), $args);\n }\n // see if this is a set/get for a property\n $first3 = strtolower(substr($name, 0, 3));\n if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== '_') {\n if (isset($_resolved_property_name[$name])) {\n $property_name = $_resolved_property_name[$name];\n } else {\n // try to keep case correct for future PHP 6.0 case-sensitive class methods\n // lcfirst() not available < PHP 5.3.0, so improvise\n $property_name = strtolower(substr($name, 3, 1)) . substr($name, 4);\n // convert camel case to underscored name\n $property_name = preg_replace_callback('/([A-Z])/', array($this, 'replaceCamelcase'), $property_name);\n $_resolved_property_name[$name] = $property_name;\n }\n if (isset($_resolved_property_source[$property_name])) {\n $_is_this = $_resolved_property_source[$property_name];\n } else {\n $_is_this = null;\n if (property_exists($this, $property_name)) {\n $_is_this = true;\n } elseif (property_exists($this->smarty, $property_name)) {\n $_is_this = false;\n }\n $_resolved_property_source[$property_name] = $_is_this;\n }\n if ($_is_this) {\n if ($first3 == 'get') {\n return $this->$property_name;\n } else {\n return $this->$property_name = $args[0];\n }\n } elseif ($_is_this === false) {\n if ($first3 == 'get') {\n return $this->smarty->$property_name;\n } else {\n return $this->smarty->$property_name = $args[0];\n }\n } else {\n throw new SmartyException(\"property '$property_name' does not exist.\");\n }\n }\n if ($name == 'Smarty') {\n throw new SmartyException(\"PHP5 requires you to call __construct() instead of Smarty()\");\n }\n // must be unknown\n throw new SmartyException(\"Call of unknown method '$name'.\");\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "function mysql__script($database_name_full, $script_file, $dbfolder=null) {\n global $errorScriptExecution;\n\n $error = '';\n $res = false;\n\n //0: use 3d party PDO mysqldump, 2 - call mysql via shell (default)\n $dbScriptMode = defined('HEURIST_DB_MYSQL_SCRIPT_MODE')?HEURIST_DB_MYSQL_SCRIPT_MODE :0;\n\n $script_file = basename($script_file);\n if($dbfolder!=null){\n $script_file = $dbfolder.$script_file;\n }else{\n //all scripts are in admin/setup/dbcreate\n $script_file = HEURIST_DIR.'admin/setup/dbcreate/'.$script_file;\n }\n\n\n if(!file_exists($script_file)){\n $res = 'Unable to find sql script '.htmlspecialchars($script_file);\n }else{\n\n if($dbScriptMode==2){\n if (!defined('HEURIST_DB_MYSQLPATH') || !file_exists(HEURIST_DB_MYSQLPATH)){\n\n $msg = 'The path to mysql executable has not been correctly specified. '\n .'Please ask your system administrator to fix this in the heuristConfigIni.php '\n .'(note the settings required for a single server vs mysql running on a separate server)';\n\n return array(HEURIST_SYSTEM_CONFIG, $msg);\n }\n }else {\n $dbScriptMode = 0;\n }\n\n // cat sourcefile.sql | sed '/^CREATE DATABASE/d' | sed '/^USE/d' > destfile.sql\n // cat sourcefile.sql | sed '/^CREATE DATABASE/d' | sed '/^USE/d' | mysql newdbname\n\n //$dbScriptMode = 0; //disable all others\n\n if($dbScriptMode==2){ //DEFAULT\n //shell script - server admin must specify \"local\" login-path with mysql_config_editor\n // mysql_config_editor set --login-path=local --host=127.0.0.1 --user=username --password\n\n $arr_out = array();\n $res2 = null;\n\n $cmd = escapeshellcmd(HEURIST_DB_MYSQLPATH);\n if(strpos(HEURIST_DB_MYSQLPATH,' ')>0){\n $cmd = '\"'.$cmd.'\"';\n }\n\n $port = '';\n if(HEURIST_DB_PORT){\n $port = \" -P \".HEURIST_DB_PORT;\n }\n\n /* remarked temporary to avoid security warnings */\n $cmd = $cmd //.\" --login-path=local \"\n .\" -h \".HEURIST_DBSERVER_NAME.\" \".$port\n .\" -u\".ADMIN_DBUSERNAME.\" -p\".ADMIN_DBUSERPSWD\n .\" -D \".escapeshellarg($database_name_full).\" < \".escapeshellarg($script_file). ' 2>&1';\n\n $shell_res = exec($cmd, $arr_out, $res2);\n\n if ($res2 != 0) { // $shell_res is either empty or contains $arr_out as a string\n $error = 'Error. Shell returns status: '.($res2!=null?intval($res2):'unknown')\n .'. Output: '.(!isEmptyArray($arr_out)?print_r($arr_out, true):'');\n }else{\n $res = true;\n }\n\n\n }else{ //3d party function that uses PDO\n\n if(!function_exists('execute_db_script')){\n include_once dirname(__FILE__).'/../utilities/utils_db_load_script.php';// used to load procedures/triggers\n }\n if(db_script($database_name_full, $script_file, false)){\n $res = true;\n }else{\n $error = $errorScriptExecution;\n }\n }\n\n if(!$res){\n $res = 'Unable to execute script '.htmlspecialchars(basename($script_file)).' for database '.$database_name_full;\n }\n }\n\n if($res!==true){\n $res = array(HEURIST_DB_ERROR, $res, $error);\n }\n\n return $res;\n }", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "public function execute(): void\n {\n /**\n * @var \\DBmysql|null $DB\n * @var array $CFG_GLPI\n * @var \\Psr\\SimpleCache\\CacheInterface $GLPI_CACHE\n */\n global $DB,\n $CFG_GLPI,\n $GLPI_CACHE\n ;\n\n if (isset($_SESSION['is_installing'])) {\n $GLPI_CACHE = (new CacheManager())->getInstallerCacheInstance();\n\n Session::loadLanguage(with_plugins: false);\n return;\n }\n\n $skip_db_checks = false;\n $skip_maintenance_checks = false;\n if (array_key_exists('REQUEST_URI', $_SERVER)) {\n if (preg_match('#^' . $CFG_GLPI['root_doc'] . '/front/(css|locale).php#', $_SERVER['REQUEST_URI']) === 1) {\n $skip_db_checks = true;\n $skip_maintenance_checks = true;\n }\n\n $no_db_checks_scripts = [\n '#^' . $CFG_GLPI['root_doc'] . '/$#',\n '#^' . $CFG_GLPI['root_doc'] . '/index.php#',\n '#^' . $CFG_GLPI['root_doc'] . '/install/install.php#',\n '#^' . $CFG_GLPI['root_doc'] . '/install/update.php#',\n ];\n foreach ($no_db_checks_scripts as $pattern) {\n if (preg_match($pattern, $_SERVER['REQUEST_URI']) === 1) {\n $skip_db_checks = true;\n break;\n }\n }\n }\n\n //init cache\n $cache_manager = new CacheManager();\n $GLPI_CACHE = $cache_manager->getCoreCacheInstance();\n\n // Check if the DB is configured properly\n if (!$skip_db_checks) {\n if ($DB instanceof DBmysql) {\n //Database connection\n if (!$DB->connected) {\n DBConnection::displayMySQLError();\n exit(1);\n }\n\n //Options from DB, do not touch this part.\n if (!Config::isLegacyConfigurationLoaded()) {\n echo \"Error accessing config table\";\n exit(1);\n }\n } else {\n Session::loadLanguage('', false);\n\n if (!isCommandLine()) {\n // Prevent inclusion of debug information in footer, as they are based on vars that are not initialized here.\n $debug_mode = $_SESSION['glpi_use_mode'];\n $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;\n\n Html::nullHeader('Missing configuration', $CFG_GLPI[\"root_doc\"]);\n $twig_params = [\n 'config_db' => GLPI_CONFIG_DIR . '/config_db.php',\n 'install_exists' => file_exists($this->projectDir . '/install/install.php'),\n ];\n // language=Twig\n echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG\n <div class=\"container-fluid mb-4\">\n <div class=\"row justify-content-center\">\n <div class=\"col-xl-6 col-lg-7 col-md-9 col-sm-12\">\n <h2>GLPI seems to not be configured properly.</h2>\n <p class=\"mt-2 mb-n2 alert alert-warning\">\n Database configuration file \"{{ config_db }}\" is missing or is corrupted.\n You have to either restart the install process, either restore this file.\n <br />\n <br />\n {% if install_exists %}\n <a class=\"btn btn-primary\" href=\"{{ path('install/install.php') }}\">Go to install page</a>\n {% endif %}\n </p>\n </div>\n </div>\n </div>\n TWIG, $twig_params);\n Html::nullFooter();\n $_SESSION['glpi_use_mode'] = $debug_mode;\n } else {\n echo \"GLPI seems to not be configured properly.\\n\";\n echo sprintf('Database configuration file \"%s\" is missing or is corrupted.', GLPI_CONFIG_DIR . '/config_db.php') . \"\\n\";\n echo \"You have to either restart the install process, either restore this file.\\n\";\n }\n exit(1);\n }\n }\n\n if (\n isCommandLine()\n && !defined('TU_USER') // In test suite context, used --debug option is the atoum one\n && isset($_SERVER['argv'])\n ) {\n $key = array_search('--debug', $_SERVER['argv']);\n if ($key) {\n $_SESSION['glpi_use_mode'] = Session::DEBUG_MODE;\n unset($_SERVER['argv'][$key]);\n $_SERVER['argv'] = array_values($_SERVER['argv']);\n $_SERVER['argc']--;\n }\n }\n\n // Override cfg_features by session value\n foreach ($CFG_GLPI['user_pref_field'] as $field) {\n if (!isset($_SESSION[\"glpi$field\"]) && isset($CFG_GLPI[$field])) {\n $_SESSION[\"glpi$field\"] = $CFG_GLPI[$field];\n }\n }\n\n // Check maintenance mode\n if (\n !$skip_maintenance_checks\n && isset($CFG_GLPI[\"maintenance_mode\"])\n && $CFG_GLPI[\"maintenance_mode\"]\n ) {\n if (isset($_GET['skipMaintenance']) && $_GET['skipMaintenance']) {\n $_SESSION[\"glpiskipMaintenance\"] = 1;\n }\n\n if (!isset($_SESSION[\"glpiskipMaintenance\"]) || !$_SESSION[\"glpiskipMaintenance\"]) {\n Session::loadLanguage('', false);\n if (isCommandLine()) {\n echo __('Service is down for maintenance. It will be back shortly.');\n echo \"\\n\";\n } else {\n TemplateRenderer::getInstance()->display('maintenance.html.twig', [\n 'title' => \"MAINTENANCE MODE\",\n 'maintenance_text' => $CFG_GLPI[\"maintenance_text\"] ?? \"\",\n ]);\n }\n exit();\n }\n }\n\n // Check version\n if (!$skip_db_checks && !defined('SKIP_UPDATES') && !Update::isDbUpToDate()) {\n Session::checkCookieSecureConfig();\n\n // Prevent debug bar to be displayed when an admin user was connected with debug mode when codebase was updated.\n $debug_mode = $_SESSION['glpi_use_mode'];\n Toolbox::setDebugMode(Session::NORMAL_MODE);\n\n Session::loadLanguage('', false);\n\n if (isCommandLine()) {\n echo __('The GLPI codebase has been updated. The update of the GLPI database is necessary.');\n echo \"\\n\";\n exit();\n }\n\n /** @var \\DBmysql $DB */\n global $DB;\n\n $requirements = (new RequirementsManager())->getCoreRequirementList($DB);\n $requirements->add(new DatabaseTablesEngine($DB));\n\n $twig_params = [\n 'core_requirements' => $requirements,\n 'try_again' => __('Try again'),\n 'update_needed' => __('The GLPI codebase has been updated. The update of the GLPI database is necessary.'),\n 'upgrade' => _sx('button', 'Upgrade'),\n 'outdated_files' => __('You are trying to use GLPI with outdated files compared to the version of the database. Please install the correct GLPI files corresponding to the version of your database.'),\n 'stable_release' => VersionParser::isStableRelease(GLPI_VERSION),\n 'agree_unstable' => Config::agreeUnstableMessage(VersionParser::isDevVersion(GLPI_VERSION)),\n 'outdated' => version_compare(\n VersionParser::getNormalizedVersion($CFG_GLPI['version'] ?? '0.0.0-dev'),\n VersionParser::getNormalizedVersion(GLPI_VERSION),\n '>'\n )\n ];\n\n Html::nullHeader(__('Update needed'), $CFG_GLPI[\"root_doc\"]);\n // language=Twig\n echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG\n <div class=\"container-fluid mb-4\">\n <div class=\"row justify-content-evenly\">\n <div class=\"col-12 col-xxl-6\">\n <div class=\"card text-center mb-4\">\n {% include 'install/blocks/requirements_table.html.twig' with {'requirements': core_requirements} %}\n {% if core_requirements.hasMissingMandatoryRequirements() or core_requirements.hasMissingOptionalRequirements() %}\n <form action=\"{{ path('index.php') }}\" method=\"post\">\n <button type=\"submit\" class=\"btn btn-primary\">\n <i class=\"fas fa-redo\"></i>{{ try_again }}\n </button>\n </form>\n {% endif %}\n {% if not core_requirements.hasMissingMandatoryRequirements() %}\n {% if not outdated %}\n <form method=\"post\" action=\"{{ path('install/update.php') }}\">\n <input type=\"hidden\" name=\"_glpi_csrf_token\" value=\"{{ csrf_token() }}\">\n {% if not stable_release %}\n {{ agree_unstable|raw }}\n {% endif %}\n <p class=\"mt-2 mb-n2 alert alert-important alert-warning\">\n {{ update_needed }}\n </p>\n <button type=\"submit\" name=\"from_update\" class=\"btn btn-primary\">\n <i class=\"fas fa-check\"></i>{{ upgrade }}\n </button>\n </form>\n {% else %}\n <p class=\"mt-2 mb-n2 alert alert-important alert-warning\">\n {{ outdated_files }}\n </p>\n {% endif %}\n {% endif %}\n </div>\n </div>\n </div>\n </div>\nTWIG, $twig_params);\n Html::nullFooter();\n $_SESSION['glpi_use_mode'] = $debug_mode;\n exit();\n }\n\n // Load Language file\n Session::loadLanguage();\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "function matrixFromEigenvals($values) {\n $size = 0;\n foreach ($values as $v) {\n $size += is_array($v) ? 2 : 1;\n }\n $m = matrixidentity($size);\n $mi = matrixidentity($size);\n $d = [];\n $ops = array();\n if ($size > 2) {\n $ord = diffrands(0,$size-2,$size-1);\n } else {\n $ord = [0];\n }\n $ord[] = $size-1;\n $mults = nonzerodiffrands(-3,3,$size*2,'def',true);\n\tfor ($i=1; $i<$size; $i++) {\n $er = $ord[$i];\n $sr = $ord[$i-1];\n $ops[] = array($sr, $er, $mults[$i-1]);\n\t\t$m = matrixrowcombine($m,$sr,$mults[$i-1],$er,1,$er);\n }\n\n $n = 0;\n // real evals will get one row as evec\n // complex evals will get one row for imag, and next for real part\n $realrows = [];\n foreach ($values as $i=>$v) {\n $d[$n] = array_fill(0,$size,0);\n if (is_array($v)) {\n // add multiple of last row to real rows\n if ($n+1 != $size-1) {\n $mult = abs($mults[$size+$i]);\n $ops[] = array($size-1, $n+1, $mult);\n $m = matrixrowcombine($m,$size-1,$mult,$n+1,1,$n+1);\n $realrows[] = $n+1;\n }\n $d[$n+1] = array_fill(0,$size,0);\n $d[$n][$n] = $values[$i][0];\n $d[$n][$n+1] = -$values[$i][1];\n $d[$n+1][$n] = $values[$i][1];\n $d[$n+1][$n+1] = $values[$i][0];\n $n += 2;\n } else {\n // add multiple of last row to real rows\n if ($n != $size-1) {\n $mult = $mults[$size+$i];\n $ops[] = array($size-1, $n, $mult);\n $m = matrixrowcombine($m,$size-1,$mult,$n,1,$n);\n $realrows[] = $n;\n }\n $d[$n][$n] = $values[$i];\n $n++;\n }\n }\n\n if (count($realrows)>0) {\n $sr = randfrom($realrows);\n $mult = $GLOBALS['RND']->rand(-1,1);\n if (is_array($values[count($values)-1]) && $m[$sr][$size-1]*$mult < 0) {\n $mult *= -1;\n }\n $ops[] = array($sr,$size-1, $mult);\n $m = matrixrowcombine($m,$sr,$mult,$size-1,1,$size-1);\n }\n for ($i=count($ops)-1; $i>-1; $i--) {\n $mi = matrixrowcombine($mi,$ops[$i][0],-1*$ops[$i][2],$ops[$i][1],1,$ops[$i][1]);\n }\n\n $evecs = [];\n $r = 0;\n foreach ($values as $v) {\n if (!is_array($v)) { // real: use row as e-vec\n $evecs[] = $m[$r];\n $r++;\n } else { // complex: use two rows as real and complex\n $vec = [];\n for ($i=0; $i<$size; $i++) {\n $vec[] = [$m[$r+1][$i], $m[$r][$i]];\n }\n $evecs[] = $vec;\n $r += 2;\n }\n }\n\n $p = matrixtranspose($m);\n $pinv = matrixtranspose($mi);\n $A = matrixprod(matrixprod($p, $d), $pinv);\n return [$A,$evecs];\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public function jsonSerialize(): mixed\n {\n $json = parent::jsonSerialize();\n $json['resourceType'] = $this->_fhirElementName;\n if (isset($this->code)) {\n $json['code'] = $this->code;\n }\n if (isset($this->status)) {\n $json['status'] = $this->status;\n }\n if (isset($this->manufacturer)) {\n $json['manufacturer'] = $this->manufacturer;\n }\n if (isset($this->doseForm)) {\n $json['doseForm'] = $this->doseForm;\n }\n if (isset($this->amount)) {\n $json['amount'] = $this->amount;\n }\n if (0 < count($this->synonym)) {\n $json['synonym'] = [];\n foreach ($this->synonym as $synonym) {\n $json['synonym'][] = $synonym;\n }\n }\n if (0 < count($this->relatedMedicationKnowledge)) {\n $json['relatedMedicationKnowledge'] = [];\n foreach ($this->relatedMedicationKnowledge as $relatedMedicationKnowledge) {\n $json['relatedMedicationKnowledge'][] = $relatedMedicationKnowledge;\n }\n }\n if (0 < count($this->associatedMedication)) {\n $json['associatedMedication'] = [];\n foreach ($this->associatedMedication as $associatedMedication) {\n $json['associatedMedication'][] = $associatedMedication;\n }\n }\n if (0 < count($this->productType)) {\n $json['productType'] = [];\n foreach ($this->productType as $productType) {\n $json['productType'][] = $productType;\n }\n }\n if (0 < count($this->monograph)) {\n $json['monograph'] = [];\n foreach ($this->monograph as $monograph) {\n $json['monograph'][] = $monograph;\n }\n }\n if (0 < count($this->ingredient)) {\n $json['ingredient'] = [];\n foreach ($this->ingredient as $ingredient) {\n $json['ingredient'][] = $ingredient;\n }\n }\n if (isset($this->preparationInstruction)) {\n $json['preparationInstruction'] = $this->preparationInstruction;\n }\n if (0 < count($this->intendedRoute)) {\n $json['intendedRoute'] = [];\n foreach ($this->intendedRoute as $intendedRoute) {\n $json['intendedRoute'][] = $intendedRoute;\n }\n }\n if (0 < count($this->cost)) {\n $json['cost'] = [];\n foreach ($this->cost as $cost) {\n $json['cost'][] = $cost;\n }\n }\n if (0 < count($this->monitoringProgram)) {\n $json['monitoringProgram'] = [];\n foreach ($this->monitoringProgram as $monitoringProgram) {\n $json['monitoringProgram'][] = $monitoringProgram;\n }\n }\n if (0 < count($this->administrationGuidelines)) {\n $json['administrationGuidelines'] = [];\n foreach ($this->administrationGuidelines as $administrationGuidelines) {\n $json['administrationGuidelines'][] = $administrationGuidelines;\n }\n }\n if (0 < count($this->medicineClassification)) {\n $json['medicineClassification'] = [];\n foreach ($this->medicineClassification as $medicineClassification) {\n $json['medicineClassification'][] = $medicineClassification;\n }\n }\n if (isset($this->packaging)) {\n $json['packaging'] = $this->packaging;\n }\n if (0 < count($this->drugCharacteristic)) {\n $json['drugCharacteristic'] = [];\n foreach ($this->drugCharacteristic as $drugCharacteristic) {\n $json['drugCharacteristic'][] = $drugCharacteristic;\n }\n }\n if (0 < count($this->contraindication)) {\n $json['contraindication'] = [];\n foreach ($this->contraindication as $contraindication) {\n $json['contraindication'][] = $contraindication;\n }\n }\n if (0 < count($this->regulatory)) {\n $json['regulatory'] = [];\n foreach ($this->regulatory as $regulatory) {\n $json['regulatory'][] = $regulatory;\n }\n }\n if (0 < count($this->kinetics)) {\n $json['kinetics'] = [];\n foreach ($this->kinetics as $kinetics) {\n $json['kinetics'][] = $kinetics;\n }\n }\n return $json;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "public function parseFhirResource($fhirResource = array())\n {\n $data = array();\n\n if (isset($fhirResource['id'])) {\n $data['uuid'] = $fhirResource['id'];\n }\n\n if (isset($fhirResource['name'])) {\n $name = [];\n foreach ($fhirResource['name'] as $sub_name) {\n if ($sub_name['use'] === 'official') {\n $name = $sub_name;\n break;\n }\n }\n if (isset($name['family'])) {\n $data['lname'] = $name['family'];\n }\n if ($name['given'][0]) {\n $data['fname'] = $name['given'][0];\n }\n if (isset($name['given'][1])) {\n $data['mname'] = $name['given'][1];\n }\n if (isset($name['prefix'][0])) {\n $data['title'] = $name['prefix'][0];\n }\n }\n if (isset($fhirResource['address'])) {\n if (isset($fhirResource['address'][0]['line'][0])) {\n $data['street'] = $fhirResource['address'][0]['line'][0];\n }\n if (isset($fhirResource['address'][0]['postalCode'][0])) {\n $data['zip'] = $fhirResource['address'][0]['postalCode'];\n }\n if (isset($fhirResource['address'][0]['city'][0])) {\n $data['city'] = $fhirResource['address'][0]['city'];\n }\n if (isset($fhirResource['address'][0]['state'][0])) {\n $data['state'] = $fhirResource['address'][0]['state'];\n }\n }\n if (isset($fhirResource['telecom'])) {\n foreach ($fhirResource['telecom'] as $telecom) {\n switch ($telecom['system']) {\n case 'phone':\n switch ($telecom['use']) {\n case 'mobile':\n $data['phonecell'] = $telecom['value'];\n break;\n case 'home':\n $data['phone'] = $telecom['value'];\n break;\n case 'work':\n $data['phonew1'] = $telecom['value'];\n break;\n }\n break;\n case 'email':\n $data['email'] = $telecom['value'];\n break;\n default:\n //Should give Error for incapability\n break;\n }\n }\n }\n if (isset($fhirResource['gender'])) {\n $data['sex'] = $fhirResource['gender'];\n }\n\n return $data;\n }", "smellKey": "S3776", "smellId": null, "repo": "gilbeb_CYBR8420_Fall24-openemr", "language": "php"} {"function": "function getorg($it,$parent,&$res,$ind,$mod_depth) {\n\tglobal $DBH,$iteminfo,$newdir,$installname,$urlmode,$linktype,$urlmode,$imasroot,$ccnt,$module_meta,$htmldir,$filedir, $toplevelitems, $inmodule;\n\tglobal $usechecked,$checked,$usedcats;\n\n\t$out = '';\n\n\tforeach ($it as $k=>$item) {\n\t\t$canvout = '';\n\t\tif (is_array($item)) {\n\t\t\tif (!$usechecked || array_search($parent.'-'.($k+1),$checked)!==FALSE) {\n\t\t\t\t$mod_depth_change = 1;\n\t\t\t\t$blockid = uniqid();\n\t\t\t\tif ($mod_depth>0 || strlen($ind)>2) {\n\t\t\t\t\t$canvout .= '<item identifier=\"BLOCK'.$blockid.'\">'.\"\\n\";\n\t\t\t\t\t$canvout .= '<content_type>ContextModuleSubHeader</content_type>';\n\t\t\t\t\t$canvout .= '<title>'.htmlentities($item['name'],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$canvout .= ' <workflow_state>'.($item['avail']==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t\t$ccnt++;\n\t\t\t\t\tif ($inmodule && $mod_depth>0) {\n\t\t\t\t\t\t$module_meta .= $canvout;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$toplevelitems .= $canvout;\n\t\t\t\t\t\t$mod_depth_change = 2;\n\t\t\t\t\t\tif ($inmodule) {\n\t\t\t\t\t\t\t$module_meta .= '</items></module>';\n\t\t\t\t\t\t\t$inmodule = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ($inmodule) {\n\t\t\t\t\t\t$module_meta .= '</items></module>';\n\t\t\t\t\t}\n\t\t\t\t\t$inmodule = true;\n\t\t\t\t\t$module_meta .= '<module identifier=\"BLOCK'.$blockid.'\">'.\"\\n\";\n\t\t\t\t\t$module_meta .= ' <title>'.htmlentities($item['name'],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$module_meta .= ' <workflow_state>'.($item['avail']==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\tif ($item['avail'] == 1 && $item['SH'][0] == 'H' && $item['startdate'] > 0 && isset($_POST['includestartdates'])) {\n\t\t\t\t\t\t$module_meta .= ' <unlock_at>'.gmdate(\"Y-m-d\\TH:i:s\", $item['startdate']).'</unlock_at>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\t$module_meta .= ' <items>';\n\t\t\t\t}\n\t\t\t\t$out .= $ind.'<item identifier=\"BLOCK'.$blockid.'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.htmlentities($item['name'],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.getorg($item['items'],$parent.'-'.($k+1),$res,$ind.' ', $mod_depth+$mod_depth_change);\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t} else {\n\t\t\t\t$out .= $ind.getorg($item['items'],$parent.'-'.($k+1),$res,$ind.' ', $mod_depth);\n\t\t\t}\n\n\t\t} else {\n\t\t\tif ($usechecked && array_search($item,$checked)===FALSE) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ($iteminfo[$item][0]=='InlineText') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT title,text,fileorder,avail FROM imas_inlinetext WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\tif ($row[2]!='') {\n\t\t\t\t\t$files = explode(',',$row[2]);\n\t\t\t\t\t$stm = $DBH->prepare(\"SELECT id,description,filename FROM imas_instr_files WHERE itemid=:itemid\");\n\t\t\t\t\t$stm->execute(array(':itemid'=>$iteminfo[$item][1]));\n\t\t\t\t\t$filesout = array();\n\t\t\t\t\twhile ($r = $stm->fetch(PDO::FETCH_NUM)) {\n\t\t\t\t\t\t//if s3 filehandler, do files as weblinks rather than including the file itself\n\t\t\t\t\t\tif (substr($r[2],0,4)=='http') {\n\t\t\t\t\t\t\t//do nothing\n\t\t\t\t\t\t} else if (getfilehandlertype('filehandlertypecfiles') == 's3') {\n\t\t\t\t\t\t\t$r[2] = getcoursefileurl($r[2]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//copy(\"../course/files/{$r[2]}\",$newdir.'/'.$r[2]);\n\t\t\t\t\t\t\tcopycoursefile($r[2], $newdir.'/'.$filedir.basename($r[2]));\n\t\t\t\t\t\t\t$resitem = '<resource href=\"'.$filedir.basename($r[2]).'\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'file'.$r[0].'\" type=\"webcontent\">'.\"\\n\";\n\t\t\t\t\t\t\t$resitem .= ' <file href=\"'.$filedir.basename($r[2]).'\" />'.\"\\n\";\n\t\t\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$filesout[$r[0]] = array($r[1],$r[2]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$canvout .= '<content_type>WikiPage</content_type>';\n\t\t\t\t$canvout .= '<workflow_state>'.($row[3]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t$ccnt++;\n\n\t\t\t\t$fp = fopen($newdir.'/'.$htmldir.'inlinetext'.$iteminfo[$item][1].'.html','w');\n\t\t\t\tfwrite($fp,'<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">');\n\t\t\t\tfwrite($fp,'<title>'.htmlentities($row[0]).'</title>');\n\t\t\t\tfwrite($fp,'<meta name=\"identifier\" content=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\"/>');\n\t\t\t\tif ($linktype==\"canvas\") {\n\t\t\t\t\tfwrite($fp,'<meta name=\"editing_roles\" content=\"teachers\"/>');\n\t\t\t\t\tfwrite($fp,'<meta name=\"workflow_state\" content=\"'.($row[3]==0?'unpublished':'active').'\"/>');\n\t\t\t\t}\n\t\t\t\tfwrite($fp,\"</head><body>\");\n\t\t\t\tfwrite($fp,filtercapture($row[1],$res));\n\t\t\t\tif ($row[2]!='') {\n\t\t\t\t\tfwrite($fp,'<ul>');\n\t\t\t\t\tforeach ($files as $f) {\n\t\t\t\t\t\tif (getfilehandlertype('filehandlertypecfiles') == 's3') {\n\t\t\t\t\t\t\tfwrite($fp,'<li><a href=\"'.$filesout[$f][1].'\">'.htmlentities($filesout[$f][0]).'</a></li>');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfwrite($fp,'<li><a href=\"'.$filedir.basename($filesout[$f][1]).'\">'.htmlentities($filesout[$f][0]).'</a></li>');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfwrite($fp,'</ul>');\n\t\t\t\t}\n\t\t\t\tfwrite($fp,'</body></html>');\n\t\t\t\tfclose($fp);\n\t\t\t\t$resitem = '<resource href=\"'.$htmldir.'inlinetext'.$iteminfo[$item][1].'.html\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"webcontent\">'.\"\\n\";\n\t\t\t\t$resitem .= ' <file href=\"'.$htmldir.'inlinetext'.$iteminfo[$item][1].'.html\" />'.\"\\n\";\n\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t$res[] = $resitem;\n\t\t\t} else if ($iteminfo[$item][0]=='LinkedText') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT title,text,summary,avail FROM imas_linkedtext WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\n\t\t\t\t//if s3 filehandler, do files as weblinks rather than including the file itself\n\t\t\t\tif (getfilehandlertype('filehandlertypecfiles') == 's3' && substr(strip_tags($row[1]),0,5)==\"file:\") {\n\t\t\t\t\t$row[1] = getcoursefileurl(trim(substr(strip_tags($row[1]),5)));\n\t\t\t\t}\n\n\t\t\t\tif ((substr($row[1],0,4)==\"http\") && (strpos(trim($row[1]),\" \")===false)) { //is a web link\n\t\t\t\t\t$alink = trim($row[1]);\n\t\t\t\t\t$fp = fopen($newdir.'/weblink'.$iteminfo[$item][1].'.xml','w');\n\t\t\t\t\tfwrite($fp,'<webLink xmlns=\"http://www.imsglobal.org/xsd/imsccv1p1/imswl_v1p1\">');\n\t\t\t\t\tfwrite($fp,' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>');\n\t\t\t\t\tfwrite($fp,' <url href=\"'.htmlentities($alink,ENT_XML1,'UTF-8',false).'\" target=\"_blank\"/>');\n\t\t\t\t\tfwrite($fp,'</webLink>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$canvout .= '<content_type>ExternalUrl</content_type>';\n\t\t\t\t\t$canvout .= '<workflow_state>'.($row[3]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<url>'.htmlentities($alink,ENT_XML1,'UTF-8',false).'</url>';\n\t\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t\t$ccnt++;\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"imswl_xmlv1p1\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"weblink'.$iteminfo[$item][1].'.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t} else if (substr(strip_tags($row[1]),0,5)==\"file:\") { //is a file\n\t\t\t\t\t$filename = trim(substr(strip_tags($row[1]),5));\n\t\t\t\t\t//copy(\"../course/files/$filename\",$newdir.'/'.$filedir.$filename);\n\t\t\t\t\tcopycoursefile($filename, $newdir.'/'.$filedir.basename($filename));\n\n\t\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$canvout .= '<content_type>Attachment</content_type>';\n\t\t\t\t\t$canvout .= '<workflow_state>'.($row[3]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t\t$ccnt++;\n\t\t\t\t\t$resitem = '<resource href=\"'.$filedir.basename($filename).'\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"webcontent\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"'.$filedir.basename($filename).'\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t} else { //is text\n\t\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$canvout .= '<content_type>WikiPage</content_type>';\n\t\t\t\t\t$canvout .= '<workflow_state>'.($row[3]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t\t$ccnt++;\n\t\t\t\t\t$fp = fopen($newdir.'/'.$htmldir.'linkedtext'.$iteminfo[$item][1].'.html','w');\n\t\t\t\t\tfwrite($fp,'<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">');\n\t\t\t\t\tfwrite($fp,'<title>'.htmlentities($row[0]).'</title>');\n\t\t\t\t\tfwrite($fp,'<meta name=\"identifier\" content=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\"/>');\n\t\t\t\t\tif ($linktype==\"canvas\") {\n\t\t\t\t\t\tfwrite($fp,'<meta name=\"editing_roles\" content=\"teachers\"/>');\n\t\t\t\t\t\tfwrite($fp,'<meta name=\"workflow_state\" content=\"'.($row[3]==0?'unpublished':'active').'\"/>');\n\t\t\t\t\t}\n\t\t\t\t\tfwrite($fp,\"</head><body>\");\n\t\t\t\t\tfwrite($fp,filtercapture($row[1],$res));\n\t\t\t\t\tfwrite($fp,'</body></html>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$resitem = '<resource href=\"'.$htmldir.'linkedtext'.$iteminfo[$item][1].'.html\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"webcontent\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"'.$htmldir.'linkedtext'.$iteminfo[$item][1].'.html\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t}\n\t\t\t} else if ($iteminfo[$item][0]=='Forum') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,description,avail FROM imas_forums WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$canvout .= '<content_type>DiscussionTopic</content_type>';\n\t\t\t\t$canvout .= '<workflow_state>'.($row[2]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t$ccnt++;\n\t\t\t\t$fp = fopen($newdir.'/forum'.$iteminfo[$item][1].'.xml','w');\n\t\t\t\tfwrite($fp,'<topic xmlns=\"http://www.imsglobal.org/xsd/imsccv1p1/imsdt_v1p1\">');\n\t\t\t\tfwrite($fp,' <title >'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>');\n\t\t\t\tfwrite($fp,' <text texttype=\"text/html\">'.htmlentities(filtercapture($row[1],$res),ENT_XML1,'UTF-8',false).'</text>');\n\t\t\t\tfwrite($fp,'</topic>');\n\t\t\t\tfclose($fp);\n\n\t\t\t\tif ($linktype=='canvas') {\n\t\t\t\t\t$fp = fopen($newdir.'/RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta.xml','w');\n\t\t\t\t\tfwrite($fp,'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\t\t\t\t\t\t<topicMeta xsi:schemaLocation=\"http://canvas.instructure.com/xsd/cccv1p0 http://canvas.instructure.com/xsd/cccv1p0.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta\" xmlns=\"http://canvas.instructure.com/xsd/cccv1p0\">\n\t\t\t\t\t\t <topic_id>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</topic_id>\n\t\t\t\t\t\t <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>\n\t\t\t\t\t\t <type>topic</type>\n\t\t\t\t\t\t <workflow_state>'.($row[2]==0?'unpublished':'active').'</workflow_state>\n\t\t\t\t\t\t</topicMeta>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta\" type=\"associatedcontent/imscc_xmlv1p1/learning-application-resource\" href=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta.xml\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"imsdt_xmlv1p1\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"forum'.$iteminfo[$item][1].'.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <dependency identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'meta\"/>';\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t} else {\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"imsdt_xmlv1p1\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"forum'.$iteminfo[$item][1].'.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t}\n\t\t\t\t$res[] = $resitem;\n\n\t\t\t} else if ($iteminfo[$item][0]=='Assessment') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,summary,defpoints,itemorder,enddate,gbcategory,avail,startdate,ptsposs FROM imas_assessments WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\tif ($row[8]==-1) {\n\t\t\t\t\trequire_once \"../includes/updateptsposs.php\";\n\t\t\t\t\t$row[8] = updatePointsPossible($iteminfo[$item][1], $row[3], $row[2]);\n\t\t\t\t}\n\t\t\t\t//echo \"encoding {$row[0]} as \".htmlentities($row[0],ENT_XML1,'UTF-8',false).'<br/>';\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\tif ($linktype=='canvas') {\n\t\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t\t$canvout .= '<content_type>Assignment</content_type>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<workflow_state>'.($row[6]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>'.\"\\n\";\n\t\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t\t$ccnt++;\n\t\t\t\t\t$aitems = explode(',',$row[3]);\n\t\t\t\t\tforeach ($aitems as $k=>$v) {\n\t\t\t\t\t\tif (strpos($v,'~')!==FALSE) {\n\t\t\t\t\t\t\t$sub = explode('~',$v);\n\t\t\t\t\t\t\tif (strpos($sub[0],'|')===false) { //backwards compat\n\t\t\t\t\t\t\t\t$aitems[$k] = $sub[0];\n\t\t\t\t\t\t\t\t$aitemcnt[$k] = 1;\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$grpparts = explode('|',$sub[0]);\n\t\t\t\t\t\t\t\t$aitems[$k] = $sub[1];\n\t\t\t\t\t\t\t\t$aitemcnt[$k] = $grpparts[0];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$aitemcnt[$k] = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmkdir($newdir.'/assn'.$iteminfo[$item][1]);\n\t\t\t\t\t$fp = fopen($newdir.'/assn'.$iteminfo[$item][1].'/assignment_settings.xml','w');\n\t\t\t\t\tfwrite($fp,'<assignment xmlns=\"http://canvas.instructure.com/xsd/cccv1p0\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://canvas.instructure.com/xsd/cccv1p0 http://canvas.instructure.com/xsd/cccv1p0.xsd\">'.\"\\n\");\n\t\t\t\t\tfwrite($fp,'<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\");\n\t\t\t\t\tfwrite($fp,'<workflow_state>'.($row[6]==0?'unpublished':'published').'</workflow_state>'.\"\\n\");\n\t\t\t\t\tfwrite($fp,'<points_possible>'.$row[8].'</points_possible>'.\"\\n\");\n\t\t\t\t\tfwrite($fp,'<grading_type>points</grading_type>'.\"\\n\");\n\t\t\t\t\tif (isset($_POST['includeduedates']) && $row[4]<2000000000) {\n\t\t\t\t\t\tfwrite($fp,'<due_at>'.gmdate(\"Y-m-d\\TH:i:s\", $row[4]).'</due_at>'.\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif ($row[7] > 0 && isset($_POST['includestartdates'])) {\n\t\t\t\t\t\tfwrite($fp,'<unlock_at>'.gmdate(\"Y-m-d\\TH:i:s\", $row[7]).'</unlock_at>'.\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (isset($_POST['includegbcats'])) {\n\t\t\t\t\t\tfwrite($fp,'<assignment_group_identifierref>GBCAT'.$row[5].'</assignment_group_identifierref>'.\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\t$usedcats[$row[5]]++;\n\t\t\t\t\tfwrite($fp,'<submission_types>external_tool</submission_types>'.\"\\n\");\n\t\t\t\t\tfwrite($fp,'<external_tool_url>'. $GLOBALS['basesiteurl'] . '/bltilaunch.php?custom_place_aid='.$iteminfo[$item][1].'</external_tool_url>'.\"\\n\");\n\t\t\t\t\tif (isset($_POST['newtab'])) {\n\t\t\t\t\t\tfwrite($fp, '<external_tool_new_tab>true</external_tool_new_tab>');\n\t\t\t\t\t}\n\t\t\t\t\tfwrite($fp,'</assignment>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$fp = fopen($newdir.'/assn'.$iteminfo[$item][1].'/assignmenthtml'.$iteminfo[$item][1].'.html','w');\n\t\t\t\t\tfwrite($fp,'<html><body> </body></html>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"associatedcontent/imscc_xmlv1p1/learning-application-resource\" href=\"assn'.$iteminfo[$item][1].'/assignmenthtml'.$iteminfo[$item][1].'.html\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"assn'.$iteminfo[$item][1].'/assignmenthtml'.$iteminfo[$item][1].'.html\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"assn'.$iteminfo[$item][1].'/assignment_settings.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t} else {\n\t\t\t\t\t$fp = fopen($newdir.'/blti'.$iteminfo[$item][1].'.xml','w');\n\t\t\t\t\tfwrite($fp,'<cartridge_basiclti_link xmlns=\"http://www.imsglobal.org/xsd/imslticc_v1p0\" xmlns:blti=\"http://www.imsglobal.org/xsd/imsbasiclti_v1p0\" xmlns:lticm =\"http://www.imsglobal.org/xsd/imslticm_v1p0\" xmlns:lticp =\"http://www.imsglobal.org/xsd/imslticp_v1p0\">');\n\t\t\t\t\tfwrite($fp,'<blti:title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</blti:title>');\n\t\t\t\t\tfwrite($fp,'<blti:description>'.htmlentities(html_entity_decode($row[1]),ENT_XML1,'UTF-8',false).'</blti:description>');\n\t\t\t\t\tif ($linktype=='url') {\n\t\t\t\t\t\t$urladd = '?custom_place_aid='.$iteminfo[$item][1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfwrite($fp,'<blti:custom><lticm:property name=\"place_aid\">'.$iteminfo[$item][1].'</lticm:property></blti:custom>');\n\t\t\t\t\t\t$urladd = '';\n\t\t\t\t\t}\n\t\t\t\t\tif ($urlmode == 'https://') {\n\t\t\t\t\t\tfwrite($fp,'<blti:launch_url>https://' . Sanitize::domainNameWithPort($_SERVER['HTTP_HOST']) . $imasroot . '/bltilaunch.php'.$urladd.'</blti:launch_url>');\n\t\t\t\t\t\tfwrite($fp,'<blti:secure_launch_url>https://' . Sanitize::domainNameWithPort($_SERVER['HTTP_HOST']) . $imasroot . '/bltilaunch.php'.$urladd.'</blti:secure_launch_url>');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfwrite($fp,'<blti:launch_url>http://' . Sanitize::domainNameWithPort($_SERVER['HTTP_HOST']) . $imasroot . '/bltilaunch.php'.$urladd.'</blti:launch_url>');\n\t\t\t\t\t}\n\t\t\t\t\tfwrite($fp,'<blti:vendor><lticp:code>IMathAS</lticp:code><lticp:name>'.$installname.'</lticp:name></blti:vendor>');\n\t\t\t\t\tfwrite($fp,'</cartridge_basiclti_link>');\n\t\t\t\t\tfclose($fp);\n\t\t\t\t\t$resitem = '<resource identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"imsbasiclti_xmlv1p0\">'.\"\\n\";\n\t\t\t\t\t$resitem .= ' <file href=\"blti'.$iteminfo[$item][1].'.xml\" />'.\"\\n\";\n\t\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t\t$res[] = $resitem;\n\t\t\t\t}\n\t\t\t} else if ($iteminfo[$item][0]=='Wiki') {\n\t\t\t\t$stm = $DBH->prepare(\"SELECT name,avail FROM imas_wikis WHERE id=:id\");\n\t\t\t\t$stm->execute(array(':id'=>$iteminfo[$item][1]));\n\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\t$out .= $ind.'<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\" identifierref=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$out .= $ind.' <title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$out .= $ind.'</item>'.\"\\n\";\n\t\t\t\t$canvout .= '<item identifier=\"'.$iteminfo[$item][0].$iteminfo[$item][1].'\">'.\"\\n\";\n\t\t\t\t$canvout .= '<content_type>WikiPage</content_type>';\n\t\t\t\t$canvout .= '<workflow_state>'.($row[1]==0?'unpublished':'active').'</workflow_state>'.\"\\n\";\n\t\t\t\t$canvout .= '<identifierref>RES'.$iteminfo[$item][0].$iteminfo[$item][1].'</identifierref>';\n\t\t\t\t$canvout .= '<title>'.htmlentities($row[0],ENT_XML1,'UTF-8',false).'</title>'.\"\\n\";\n\t\t\t\t$canvout .= \"<position>$ccnt</position> <indent>\".max($mod_depth-1,0).\"</indent> </item>\";\n\t\t\t\t$ccnt++;\n\n\t\t\t\t$fp = fopen($newdir.'/'.$htmldir.'wikitext'.$iteminfo[$item][1].'.html','w');\n\t\t\t\tfwrite($fp,'<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">');\n\t\t\t\tfwrite($fp,'<title>'.htmlentities($row[0]).'</title>');\n\t\t\t\tfwrite($fp,'<meta name=\"identifier\" content=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\"/>');\n\t\t\t\tif ($linktype==\"canvas\") {\n\t\t\t\t\tfwrite($fp,'<meta name=\"editing_roles\" content=\"teachers\"/>');\n\t\t\t\t\tfwrite($fp,'<meta name=\"workflow_state\" content=\"'.($row[1]==0?'unpublished':'active').'\"/>');\n\t\t\t\t}\n\t\t\t\tfwrite($fp,\"</head><body>\");\n\t\t\t\t$stm = $DBH->prepare(\"SELECT revision FROM imas_wiki_revisions WHERE wikiid=:wikiid AND stugroupid=0 ORDER BY id DESC LIMIT 1\");\n\t\t\t\t$stm->execute(array(':wikiid'=>$iteminfo[$item][1]));\n\t\t\t\tif ($stm->rowCount()>0) {\n\t\t\t\t\t$row = $stm->fetch(PDO::FETCH_NUM);\n\t\t\t\t\t$text = $row[0];\n\t\t\t\t\tif (strlen($text)>6 && substr($text,0,6)=='**wver') {\n\t\t\t\t\t\t$wikiver = substr($text,6,strpos($text,'**',6)-6);\n\t\t\t\t\t\t$text = substr($text,strpos($text,'**',6)+2);\n\t\t\t\t\t}\n\t\t\t\t\tfwrite($fp,filtercapture($text,$res));\n\t\t\t\t}\n\n\t\t\t\tfwrite($fp,'</body></html>');\n\t\t\t\tfclose($fp);\n\t\t\t\t$resitem = '<resource href=\"'.$htmldir.'wikitext'.$iteminfo[$item][1].'.html\" identifier=\"RES'.$iteminfo[$item][0].$iteminfo[$item][1].'\" type=\"webcontent\">'.\"\\n\";\n\t\t\t\t$resitem .= ' <file href=\"'.$htmldir.'wikitext'.$iteminfo[$item][1].'.html\" />'.\"\\n\";\n\t\t\t\t$resitem .= '</resource>';\n\t\t\t\t$res[] = $resitem;\n\t\t\t}\n\t\t\tif ($inmodule && $mod_depth>0) {\n\t\t\t\t$module_meta .= $canvout;\n\t\t\t} else {\n\t\t\t\t$toplevelitems .= $canvout;\n\t\t\t}\n\t\t}\n\t}\n\treturn $out;\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)\n {\n if ($item::class === self::class) {\n $item->cleanProfile();\n switch ($tabnum) {\n case 2:\n $item->showFormAsset();\n break;\n\n case 3:\n if ($item->fields['interface'] === 'helpdesk') {\n $item->showFormTrackingHelpdesk();\n } else {\n $item->showFormTracking();\n }\n break;\n\n case 4:\n if ($item->fields['interface'] === 'helpdesk') {\n $item->showFormLifeCycleHelpdesk();\n } else {\n $item->showFormLifeCycle();\n }\n break;\n\n case 5:\n $item->showFormManagement();\n break;\n\n case 6:\n if ($item->fields['interface'] === 'helpdesk') {\n $item->showFormToolsHelpdesk();\n } else {\n $item->showFormTools();\n }\n break;\n\n case 7:\n $item->showFormAdmin();\n break;\n\n case 8:\n if ($item->fields['interface'] === 'helpdesk') {\n $item->showFormSetupHelpdesk();\n } else {\n $item->showFormSetup();\n }\n break;\n\n case 9:\n $item->showFormSecurity();\n break;\n }\n }\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "public static function getCalculatedFieldValue(Fieldcollection\\Data\\AbstractData|Objectbrick\\Data\\AbstractData|Concrete $object, ?Data\\CalculatedValue $data): mixed\n {\n if (!$data) {\n return null;\n }\n $fieldname = $data->getFieldname();\n $ownerType = $data->getOwnerType();\n\n $fd = $data->getKeyDefinition();\n if ($fd === null) {\n if ($ownerType === 'object') {\n $fd = $object->getClass()->getFieldDefinition($fieldname);\n } elseif ($ownerType === 'localizedfield') {\n /** @var Model\\DataObject\\ClassDefinition\\Data\\Localizedfields $lfDef */\n $lfDef = $object->getClass()->getFieldDefinition('localizedfields');\n $fd = $lfDef->getFieldDefinition($fieldname);\n }\n }\n\n if (!$fd instanceof Model\\DataObject\\ClassDefinition\\Data\\CalculatedValue) {\n return null;\n }\n\n if (\n $object instanceof Model\\DataObject\\Fieldcollection\\Data\\AbstractData ||\n $object instanceof Model\\DataObject\\Objectbrick\\Data\\AbstractData\n ) {\n $object = $object->getObject();\n }\n\n return DataObject\\Service::useInheritedValues(true, static function () use ($object, $fd, $data) {\n switch ($fd->getCalculatorType()) {\n case DataObject\\ClassDefinition\\Data\\CalculatedValue::CALCULATOR_TYPE_CLASS:\n $className = $fd->getCalculatorClass();\n $calculator = Model\\DataObject\\ClassDefinition\\Helper\\CalculatorClassResolver::resolveCalculatorClass($className);\n if (!$calculator instanceof DataObject\\ClassDefinition\\CalculatorClassInterface) {\n Logger::error('Class does not exist or is not valid: ' . $className);\n\n return null;\n }\n\n return $calculator->compute($object, $data);\n\n case DataObject\\ClassDefinition\\Data\\CalculatedValue::CALCULATOR_TYPE_EXPRESSION:\n\n try {\n return self::evaluateExpression($fd, $object, $data);\n } catch (SyntaxError $exception) {\n return $exception->getMessage();\n }\n\n default:\n return null;\n }\n });\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['text'])) {\n $this->setText($data['text']);\n }\n if (isset($data['contained'])) {\n if (is_array($data['contained'])) {\n foreach ($data['contained'] as $d) {\n $this->addContained($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"contained\" must be array of objects or null, ' . gettype($data['contained']) . ' seen.');\n }\n }\n if (isset($data['extension'])) {\n if (is_array($data['extension'])) {\n foreach ($data['extension'] as $d) {\n $this->addExtension($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"extension\" must be array of objects or null, ' . gettype($data['extension']) . ' seen.');\n }\n }\n if (isset($data['modifierExtension'])) {\n if (is_array($data['modifierExtension'])) {\n foreach ($data['modifierExtension'] as $d) {\n $this->addModifierExtension($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"modifierExtension\" must be array of objects or null, ' . gettype($data['modifierExtension']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "function processShortScript($script) {\n\t//$xmin = -5; $xmax = 5; $ymin = -5; $ymax = 5; $border = 5;\n\t//$stroke = 'black'; $fill = 'none'; $curdash=''; $isdashed=false; $marker='none';\n //$markerfill = 'green'; $gridcolor = 'gray'; $axescolor = 'black';\n\t//$strokewidth = 1; $dotradius=8; $ticklength=4; $fontsize = 12;\n\n\t$sa = explode(',',$script);\n\tif (count($sa)>10) {\n\t\t$this->border = 5;\n\t\t$this->AStoIMG($sa[9],$sa[10]);\n\t\t$this->ASinitPicture(array_slice($sa,0,4));//$sa[0] .','. $sa[1] .','. $sa[2] .','. $sa[3]);\n\t\t$this->ASaxes(array_slice($sa,4,5));//$sa[4] .','. $sa[5] .','. $sa[6] .','. $sa[7] .','. $sa[8]);\n\t\t$inx = 11;\n\t\twhile (count($sa) > $inx+9) {\n\t\t\t$this->stroke = $sa[$inx+7];\n\t\t\t$this->strokewidth = $sa[$inx+8];\n\t\t\tif ($this->usegd2) {\n\t\t\t\timagesetthickness($this->img,(int) round($this->strokewidth > 0.5 ? $this->strokewidth : 1));\n\t\t\t}\n\t\t\tif ($sa[$inx+9] != \"\") {\n\t\t\t\t$this->ASsetdash($sa[$inx+9]);\n\t\t\t} else {\n\t\t\t\t$this->ASsetdash('none');\n\t\t\t}\n\t\t\tif ($sa[$inx]=='slope') {\n\t\t\t\t$this->ASslopefield(array($sa[$inx+1],$sa[$inx+2],$sa[$inx+2]));\n\t\t\t} else if ($sa[$inx]=='label') {\n\t\t\t\t$this->AStext(array($sa[$inx+5].','.$sa[$inx+6],$sa[$inx+1]));\n\t\t\t} else {\n\t\t\t\tif ($sa[$inx]=='func') {\n\t\t\t\t\t$eqn = $sa[$inx+1];\n\t\t\t\t} else if ($sa[$inx]=='polar') {\n\t\t\t\t\t$eqn = '[cos(t)*('.$sa[$inx+1].'),sin(t)*('.$sa[$inx+1].')]';\n\t\t\t\t} else if ($sa[$inx]=='param') {\n\t\t\t\t\t$eqn = '['.$sa[$inx+1].','.$sa[$inx+2].']';\n\t\t\t\t}\n\t\t\t\tif (is_numeric($sa[$inx+5])) {\n\t\t\t\t\t$this->ASplot(array($eqn,$sa[$inx+5],$sa[$inx+6],null,null,$sa[$inx+3],$sa[$inx+4]));\n\t\t\t\t} else {\n\t\t\t\t\t$this->ASplot(array($eqn,null,null,null,null,$sa[$inx+3],$sa[$inx+4]));\n\t\t\t\t}\n\t\t\t}\n\t\t\t$inx += 10;\n\t\t}\n\t}\n}", "smellKey": "S3776", "smellId": null, "repo": "drlippman_IMathAS", "language": "php"} {"function": "function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)\n\t{\n\t\t// Open file\n\t\t$this->_openFile($pFilename);\n\t\tif (!$this->_isValidFormat()) {\n\t\t\tfclose ($this->_fileHandle);\n\t\t\tthrow new PHPExcel_Reader_Exception($pFilename . \" is an Invalid Spreadsheet file.\");\n\t\t}\n\t\t$fileHandle = $this->_fileHandle;\n\t\trewind($fileHandle);\n\n\t\t// Create new PHPExcel\n\t\twhile ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {\n\t\t\t$objPHPExcel->createSheet();\n\t\t}\n\t\t$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );\n\n\t\t$fromFormats\t= array('\\-',\t'\\ ');\n\t\t$toFormats\t\t= array('-',\t' ');\n\n\t\t// Loop through file\n\t\t$rowData = array();\n\t\t$column = $row = '';\n\n\t\t// loop through one row (line) at a time in the file\n\t\twhile (($rowData = fgets($fileHandle)) !== FALSE) {\n\n\t\t\t// convert SYLK encoded $rowData to UTF-8\n\t\t\t$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);\n\n\t\t\t// explode each row at semicolons while taking into account that literal semicolon (;)\n\t\t\t// is escaped like this (;;)\n\t\t\t$rowData = explode(\"\\t\",str_replace('\u00a4',';',str_replace(';',\"\\t\",str_replace(';;','\u00a4',rtrim($rowData)))));\n\n\t\t\t$dataType = array_shift($rowData);\n\t\t\t//\tRead shared styles\n\t\t\tif ($dataType == 'P') {\n\t\t\t\t$formatArray = array();\n\t\t\t\tforeach($rowData as $rowDatum) {\n\t\t\t\t\tswitch($rowDatum{0}) {\n\t\t\t\t\t\tcase 'P' :\t$formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'E' :\n\t\t\t\t\t\tcase 'F' :\t$formatArray['font']['name'] = substr($rowDatum,1);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'L' :\t$formatArray['font']['size'] = substr($rowDatum,1);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'S' :\t$styleSettings = substr($rowDatum,1);\n\t\t\t\t\t\t\t\t\tfor ($i=0;$i<strlen($styleSettings);++$i) {\n\t\t\t\t\t\t\t\t\t\tswitch ($styleSettings{$i}) {\n\t\t\t\t\t\t\t\t\t\t\tcase 'I' :\t$formatArray['font']['italic'] = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase 'D' :\t$formatArray['font']['bold'] = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase 'T' :\t$formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase 'B' :\t$formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase 'L' :\t$formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase 'R' :\t$formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$this->_formats['P'.$this->_format++] = $formatArray;\n\t\t\t//\tRead cell value data\n\t\t\t}", "smellKey": "S3776", "smellId": null, "repo": "gbGop_Formacion", "language": "php"} {"function": "public function init()\n {\n /*\n * Globals are DEPRECATED as of version 1.5.0.1\n * Use the Context object to access objects instead.\n * Example: $this->context->cart\n */\n global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;\n\n if (self::$initialized) {\n return;\n }\n\n self::$initialized = true;\n\n parent::init();\n\n // enable Symfony error handler if debug mode enabled\n $this->initDebugguer();\n\n // If current URL use SSL, set it true (used a lot for module redirect)\n if (Tools::usingSecureMode()) {\n $useSSL = true;\n }\n\n // For compatibility with globals, DEPRECATED as of version 1.5.0.1\n $css_files = $this->css_files;\n $js_files = $this->js_files;\n\n $this->sslRedirection();\n\n if ($this->ajax) {\n $this->display_header = false;\n $this->display_footer = false;\n }\n\n // If account created with the 2 steps register process, remove 'account_created' from cookie\n if (isset($this->context->cookie->account_created)) {\n unset($this->context->cookie->account_created);\n }\n\n ob_start();\n\n // Init cookie language\n // @TODO This method must be moved into switchLanguage\n Tools::setCookieLanguage($this->context->cookie);\n\n $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://';\n $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false;\n $protocol_content = ($useSSL) ? 'https://' : 'http://';\n $link = new Link($protocol_link, $protocol_content);\n $this->context->link = $link;\n\n if ($id_cart = (int) $this->recoverCart()) {\n $this->context->cookie->id_cart = (int) $id_cart;\n }\n\n if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) {\n Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));\n }\n\n /* Theme is missing */\n if (!is_dir(_PS_THEME_DIR_)) {\n throw new PrestaShopException(\n $this->trans(\n 'Current theme is unavailable. Please check your theme\\'s directory name (\"%s\") and permissions.',\n array(basename(rtrim(_PS_THEME_DIR_, '/\\\\'))),\n 'Admin.Design.Notification'\n ));\n }\n\n if (Configuration::get('PS_GEOLOCATION_ENABLED')) {\n if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {\n $this->context->country = $new_default;\n }\n } elseif (Configuration::get('PS_DETECT_COUNTRY')) {\n $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency;\n $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;\n $has_address_type = false;\n\n if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {\n $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};\n }\n\n if ((!$has_currency || $has_country) && !$has_address_type) {\n $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ?\n (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry();\n\n $country = new Country($id_country, (int) $this->context->cookie->id_lang);\n\n if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {\n $this->context->country = $country;\n $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id;\n $this->context->cookie->iso_code_country = strtoupper($country->iso_code);\n }\n }\n }\n\n $currency = Tools::setCurrency($this->context->cookie);\n\n if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) {\n $this->context->customer->logout();\n\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n } elseif (isset($_GET['mylogout'])) {\n $this->context->customer->mylogout();\n Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);\n }\n\n /* Cart already exists */\n if ((int) $this->context->cookie->id_cart) {\n if (!isset($cart)) {\n $cart = new Cart($this->context->cookie->id_cart);\n }\n\n if (Validate::isLoadedObject($cart) && $cart->OrderExists()) {\n PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);\n $this->context->cookie->check_cgv = false;\n } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED'))\n && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))\n && $cart->nbProducts()\n && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1\n && !FrontController::isInWhitelistForGeolocation()\n && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))\n ) {\n /* Delete product of cart, if user can't make an order from his country */\n PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);\n unset($this->context->cookie->id_cart, $cart);\n } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {\n // update cart values\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n }\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $currency->id;\n $cart->update();\n }\n /* Select an address if not set */\n if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||\n !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {\n $to_update = false;\n if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {\n $to_update = true;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {\n $to_update = true;\n $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n }\n if ($to_update) {\n $cart->update();\n }\n }\n }\n\n if (!isset($cart) || !$cart->id) {\n $cart = new Cart();\n $cart->id_lang = (int) $this->context->cookie->id_lang;\n $cart->id_currency = (int) $this->context->cookie->id_currency;\n $cart->id_guest = (int) $this->context->cookie->id_guest;\n $cart->id_shop_group = (int) $this->context->shop->id_shop_group;\n $cart->id_shop = $this->context->shop->id;\n if ($this->context->cookie->id_customer) {\n $cart->id_customer = (int) $this->context->cookie->id_customer;\n $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);\n $cart->id_address_invoice = (int) $cart->id_address_delivery;\n } else {\n $cart->id_address_delivery = 0;\n $cart->id_address_invoice = 0;\n }\n\n // Needed if the merchant want to give a free product to every visitors\n $this->context->cart = $cart;\n CartRule::autoAddToCart($this->context);\n } else {\n $this->context->cart = $cart;\n }\n\n $this->context->cart->checkAndUpdateAddresses();\n\n $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));\n\n // Automatically redirect to the canonical URL if needed\n if (!empty($this->php_self) && !Tools::getValue('ajax')) {\n $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));\n }\n\n Product::initPricesComputation();\n\n $display_tax_label = $this->context->country->display_tax_label;\n if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {\n $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});\n $country = new Country((int) $infos['id_country']);\n $this->context->country = $country;\n if (Validate::isLoadedObject($country)) {\n $display_tax_label = $country->display_tax_label;\n }\n }\n\n $languages = Language::getLanguages(true, $this->context->shop->id);\n $meta_language = array();\n foreach ($languages as $lang) {\n $meta_language[] = $lang['iso_code'];\n }\n\n /*\n * These shortcuts are DEPRECATED as of version 1.5.0.1\n * Use the Context to access objects instead.\n * Example: $this->context->cart\n */\n self::$cookie = $this->context->cookie;\n self::$cart = $cart;\n self::$smarty = $this->context->smarty;\n self::$link = $link;\n $defaultCountry = $this->context->country;\n\n $this->displayMaintenancePage();\n\n if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) {\n $this->displayRestrictedCountryPage();\n }\n\n $this->iso = $iso;\n $this->context->cart = $cart;\n $this->context->currency = $currency;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public static function getModulesOnDisk($use_config = false, $logged_on_addons = false, $id_employee = false)\n {\n global $_MODULES;\n\n // Init var\n $module_list = array();\n $module_name_list = array();\n $modules_name_to_cursor = array();\n $errors = array();\n\n // Get modules directory list and memory limit\n $modules_dir = Module::getModulesDirOnDisk();\n\n $modules_installed = array();\n $result = Db::getInstance()->executeS('\n SELECT m.name, m.version, mp.interest, module_shop.enable_device\n FROM `'._DB_PREFIX_.'module` m\n '.Shop::addSqlAssociation('module', 'm').'\n LEFT JOIN `'._DB_PREFIX_.'module_preference` mp ON (mp.`module` = m.`name` AND mp.`id_employee` = '.(int)$id_employee.')');\n foreach ($result as $row) {\n $modules_installed[$row['name']] = $row;\n }\n\n foreach ($modules_dir as $module) {\n $module_errors = array();\n if (Module::useTooMuchMemory()) {\n $module_errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration');\n break;\n }\n\n $iso = substr(Context::getContext()->language->iso_code, 0, 2);\n\n // Check if config.xml module file exists and if it's not outdated\n\n if ($iso == 'en') {\n $config_file = _PS_MODULE_DIR_.$module.'/config.xml';\n } else {\n $config_file = _PS_MODULE_DIR_.$module.'/config_'.$iso.'.xml';\n }\n\n $xml_exist = (file_exists($config_file));\n $need_new_config_file = $xml_exist ? (@filemtime($config_file) < @filemtime(_PS_MODULE_DIR_.$module.'/'.$module.'.php')) : true;\n\n // If config.xml exists and that the use config flag is at true\n if ($use_config && $xml_exist && !$need_new_config_file) {\n // Load config.xml\n libxml_use_internal_errors(true);\n $xml_module = @simplexml_load_file($config_file);\n if (!$xml_module) {\n $module_errors[] = Tools::displayError(sprintf('%1s could not be loaded.', $config_file));\n break;\n }\n foreach (libxml_get_errors() as $error) {\n $module_errors[] = '['.$module.'] '.Tools::displayError('Error found in config file:').' '.htmlentities($error->message);\n }\n libxml_clear_errors();\n\n // If no errors in Xml, no need instand and no need new config.xml file, we load only translations\n if (!count($module_errors) && (int)$xml_module->need_instance == 0) {\n $file = _PS_MODULE_DIR_.$module.'/'.Context::getContext()->language->iso_code.'.php';\n if (Tools::file_exists_cache($file) && include_once($file)) {\n if (isset($_MODULE) && is_array($_MODULE)) {\n $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;\n }\n }\n\n $item = new stdClass();\n $item->id = 0;\n $item->warning = '';\n\n foreach ($xml_module as $k => $v) {\n $item->$k = (string)$v;\n }\n\n $item->displayName = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string)$xml_module->name));\n $item->description = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->description), (string)$xml_module->name));\n $item->author = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->author), (string)$xml_module->name));\n $item->author_uri = (isset($xml_module->author_uri) && $xml_module->author_uri) ? stripslashes($xml_module->author_uri) : false;\n\n if (isset($xml_module->confirmUninstall)) {\n $item->confirmUninstall = Translate::getModuleTranslation((string)$xml_module->name, html_entity_decode(Module::configXmlStringFormat($xml_module->confirmUninstall)), (string)$xml_module->name);\n }\n\n $item->active = 0;\n $item->onclick_option = false;\n $item->trusted = Module::isModuleTrusted($item->name);\n\n $module_list[$item->name.'_disk'] = $item;\n\n $module_name_list[] = '\\''.pSQL($item->name).'\\'';\n $modules_name_to_cursor[Tools::strtolower(strval($item->name))] = $item;\n }\n }\n\n // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file\n if (!$use_config || !$xml_exist || (isset($xml_module->need_instance) && (int)$xml_module->need_instance == 1) || $need_new_config_file) {\n // If class does not exists, we include the file\n if (!class_exists($module, false)) {\n // Get content from php file\n $file_path = _PS_MODULE_DIR_.$module.'/'.$module.'.php';\n $file = trim(file_get_contents(_PS_MODULE_DIR_.$module.'/'.$module.'.php'));\n\n if (substr($file, 0, 5) == '<?php') {\n $file = substr($file, 5);\n }\n\n if (substr($file, -2) == '?>') {\n $file = substr($file, 0, -2);\n }\n\n // We check any parse error before including the file.\n // If (false) is a trick to not load the class with \"eval\".\n // This way require_once will works correctly\n // But namespace and use statements need to be removed\n $content = preg_replace('/\\n[\\s\\t]*?use\\s.*?;/', '', $file);\n $content = preg_replace('/\\n[\\s\\t]*?namespace\\s.*?;/', '', $content);\n try {\n if (substr(`php -l $file_path`, 0, 16) == 'No syntax errors' || eval('if (false){\t'.$content.' }') !== false) {\n require_once(_PS_MODULE_DIR_.$module.'/'.$module.'.php');\n } else {\n throw new ParseError(\"Parse error\");\n }\n } catch (ParseError $e) {\n $errors[] = sprintf(Tools::displayError('%1$s (parse error in %2$s)'), $module, substr($file_path, strlen(_PS_ROOT_DIR_)));\n }\n\n preg_match('/\\n[\\s\\t]*?namespace\\s.*?;/', $file, $ns);\n if (!empty($ns)) {\n $ns = preg_replace('/\\n[\\s\\t]*?namespace\\s/', '', $ns[0]);\n $ns = rtrim($ns, ';');\n $module = $ns.'\\\\'.$module;\n }\n }\n\n // If class exists, we just instanciate it\n if (class_exists($module, false)) {\n try {\n $tmp_module = \\PrestaShop\\PrestaShop\\Adapter\\ServiceLocator::get($module);\n\n $item = new stdClass();\n\n $item->id = (int)$tmp_module->id;\n $item->warning = $tmp_module->warning;\n $item->name = $tmp_module->name;\n $item->version = $tmp_module->version;\n $item->tab = $tmp_module->tab;\n $item->displayName = $tmp_module->displayName;\n $item->description = stripslashes($tmp_module->description);\n $item->author = $tmp_module->author;\n $item->author_uri = (isset($tmp_module->author_uri) && $tmp_module->author_uri) ? $tmp_module->author_uri : false;\n $item->limited_countries = $tmp_module->limited_countries;\n $item->parent_class = get_parent_class($module);\n $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0;\n $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0;\n $item->active = $tmp_module->active;\n $item->trusted = Module::isModuleTrusted($tmp_module->name);\n $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null;\n $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null;\n $item->confirmUninstall = isset($tmp_module->confirmUninstall) ? html_entity_decode($tmp_module->confirmUninstall) : null;\n $item->description_full = stripslashes($tmp_module->description_full);\n $item->additional_description = isset($tmp_module->additional_description) ? stripslashes($tmp_module->additional_description) : null;\n $item->compatibility = isset($tmp_module->compatibility) ? (array)$tmp_module->compatibility : null;\n $item->nb_rates = isset($tmp_module->nb_rates) ? (array)$tmp_module->nb_rates : null;\n $item->avg_rate = isset($tmp_module->avg_rate) ? (array)$tmp_module->avg_rate : null;\n $item->badges = isset($tmp_module->badges) ? (array)$tmp_module->badges : null;\n $item->url = isset($tmp_module->url) ? $tmp_module->url : null;\n $item->onclick_option = method_exists($module, 'onclickOption') ? true : false;\n\n if ($item->onclick_option) {\n $href = Context::getContext()->link->getAdminLink('Module', true).'&module_name='.$tmp_module->name.'&tab_module='.$tmp_module->tab;\n $item->onclick_option_content = array();\n $option_tab = array('desactive', 'reset', 'configure', 'delete');\n\n foreach ($option_tab as $opt) {\n $item->onclick_option_content[$opt] = $tmp_module->onclickOption($opt, $href);\n }\n }\n\n $module_list[$item->name.'_disk'] = $item;\n\n if (!$xml_exist || $need_new_config_file) {\n self::$_generate_config_xml_mode = true;\n $tmp_module->_generateConfigXml();\n self::$_generate_config_xml_mode = false;\n }\n\n unset($tmp_module);\n } catch (Exception $e) {\n }\n } else {\n $module_errors[] = sprintf(Tools::displayError('%1$s (class missing in %2$s)'), $module, substr($file_path, strlen(_PS_ROOT_DIR_)));\n }\n }\n $errors = array_merge($errors, $module_errors);\n }\n\n // Get modules information from database\n if (!empty($module_name_list)) {\n $list = Shop::getContextListShopID();\n $sql = 'SELECT m.id_module, m.name, (\n SELECT COUNT(*) FROM '._DB_PREFIX_.'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN ('.implode(',', $list).')\n ) as total\n FROM '._DB_PREFIX_.'module m\n WHERE LOWER(m.name) IN ('.Tools::strtolower(implode(',', $module_name_list)).')';\n $results = Db::getInstance()->executeS($sql);\n\n foreach ($results as $result) {\n if (isset($modules_name_to_cursor[Tools::strtolower($result['name'])])) {\n $module_cursor = $modules_name_to_cursor[Tools::strtolower($result['name'])];\n $module_cursor->id = (int)$result['id_module'];\n $module_cursor->active = ($result['total'] == count($list)) ? 1 : 0;\n }\n }\n }\n\n // Get Default Country Modules and customer module\n $files_list = array(\n array('type' => 'addonsNative', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0),\n array('type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0),\n array('type' => 'addonsBought', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1),\n );\n foreach ($files_list as $f) {\n if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $logged_on_addons)) {\n if (Module::useTooMuchMemory()) {\n $errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration');\n break;\n }\n\n $file = $f['file'];\n $content = Tools::file_get_contents($file);\n $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);\n\n if ($xml && isset($xml->module)) {\n foreach ($xml->module as $modaddons) {\n $flag_found = 0;\n\n foreach ($module_list as $k => &$m) {\n if (Tools::strtolower($m->name) == Tools::strtolower($modaddons->name) && !isset($m->available_on_addons)) {\n $flag_found = 1;\n if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1) {\n $module_list[$k]->version_addons = $modaddons->version;\n }\n }\n }\n\n if ($flag_found == 0) {\n $item = new stdClass();\n $item->id = 0;\n $item->warning = '';\n $item->type = strip_tags((string)$f['type']);\n $item->name = strip_tags((string)$modaddons->name);\n $item->version = strip_tags((string)$modaddons->version);\n $item->tab = strip_tags((string)$modaddons->tab);\n $item->displayName = strip_tags((string)$modaddons->displayName);\n $item->description = stripslashes(strip_tags((string)$modaddons->description));\n $item->description_full = stripslashes(strip_tags((string)$modaddons->description_full));\n $item->author = strip_tags((string)$modaddons->author);\n $item->limited_countries = array();\n $item->parent_class = '';\n $item->onclick_option = false;\n $item->is_configurable = 0;\n $item->need_instance = 0;\n $item->not_on_disk = 1;\n $item->available_on_addons = 1;\n $item->trusted = Module::isModuleTrusted($item->name);\n $item->active = 0;\n $item->description_full = stripslashes($modaddons->description_full);\n $item->additional_description = isset($modaddons->additional_description) ? stripslashes($modaddons->additional_description) : null;\n $item->compatibility = isset($modaddons->compatibility) ? (array)$modaddons->compatibility : null;\n $item->nb_rates = isset($modaddons->nb_rates) ? (array)$modaddons->nb_rates : null;\n $item->avg_rate = isset($modaddons->avg_rate) ? (array)$modaddons->avg_rate : null;\n $item->badges = isset($modaddons->badges) ? (array)$modaddons->badges : null;\n $item->url = isset($modaddons->url) ? $modaddons->url : null;\n if (isset($item->description_full) && trim($item->description_full) != '') {\n $item->show_quick_view = true;\n }\n\n if (isset($modaddons->img)) {\n $item->image = Module::copyModAddonsImg($modaddons);\n }\n\n\n if ($item->type == 'addonsMustHave') {\n $item->addons_buy_url = strip_tags((string)$modaddons->url);\n $prices = (array)$modaddons->price;\n $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');\n\n foreach ($prices as $currency => $price) {\n if ($id_currency = Currency::getIdByIsoCode($currency)) {\n $item->price = (float)$price;\n $item->id_currency = (int)$id_currency;\n\n if ($id_default_currency == $id_currency) {\n break;\n }\n }\n }\n }\n\n $module_list[$item->name.'_feed'] = $item;\n }\n\n if (isset($module_list[$modaddons->name.'_disk'])) {\n $module_list[$modaddons->name.'_disk']->description_full = stripslashes(strip_tags((string)$modaddons->description_full));\n $module_list[$modaddons->name.'_disk']->additional_description = stripslashes(strip_tags((string)$modaddons->additional_description));\n $module_list[$modaddons->name.'_disk']->image = Module::copyModAddonsImg($modaddons);\n $module_list[$modaddons->name.'_disk']->show_quick_view = true;\n }\n }\n }\n }\n }\n\n foreach ($module_list as $key => &$module) {\n if (defined('_PS_HOST_MODE_') && in_array($module->name, self::$hosted_modules_blacklist)) {\n unset($module_list[$key]);\n } elseif (isset($modules_installed[$module->name])) {\n $module->installed = true;\n $module->database_version = $modules_installed[$module->name]['version'];\n $module->interest = $modules_installed[$module->name]['interest'];\n $module->enable_device = $modules_installed[$module->name]['enable_device'];\n } else {\n $module->installed = false;\n $module->database_version = 0;\n $module->interest = 0;\n }\n }\n\n usort($module_list, create_function('$a,$b', 'return strnatcasecmp($a->displayName, $b->displayName);'));\n if ($errors) {\n if (!isset(Context::getContext()->controller) && !Context::getContext()->controller->controller_name) {\n echo '<div class=\"alert error\"><h3>'.Tools::displayError('The following module(s) could not be loaded').':</h3><ol>';\n foreach ($errors as $error) {\n echo '<li>'.$error.'</li>';\n }\n echo '</ol></div>';\n } else {\n foreach ($errors as $error) {\n Context::getContext()->controller->errors[] = $error;\n }\n }\n }\n\n return $module_list;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function getLabeledValue(array|ElementInterface $element): ResultContainer|\\stdClass|null\n {\n $result = new \\stdClass();\n $result->label = $this->label;\n\n $children = $this->getChildren();\n\n if (!$children) {\n return $result;\n } else {\n $c = $children[0];\n\n $valueArray = [];\n\n $childResult = $c->getLabeledValue($element);\n\n $childValues = $childResult->value;\n $isArrayType = is_array($childValues);\n\n if ($childValues && !is_array($childValues)) {\n $childValues = [$childValues];\n }\n\n if (is_array($childValues)) {\n foreach ($childValues as $childValue) {\n $valueArray[] = $childValue;\n }\n } else {\n $valueArray[] = null;\n }\n\n if ($isArrayType) {\n $result->value = $valueArray;\n } else {\n $result->value = $valueArray[0];\n }\n }\n\n if ($this->mode === 'e') {\n $result->value = json_encode($result->value);\n } elseif ($this->mode === 'd') {\n $result->value = json_decode($result->value, true);\n }\n\n return $result;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_admin-ui-classic-bundle", "language": "php"} {"function": "public function install()\n {\n Hook::exec('actionModuleInstallBefore', array('object' => $this));\n // Check module name validation\n if (!Validate::isModuleName($this->name)) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Unable to install the module (Module name is not valid).', array(), 'Admin.Modules.Notification');\n return false;\n }\n\n // Check PS version compliancy\n if (!$this->checkCompliancy()) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('The version of your module is not compliant with your PrestaShop version.', array(), 'Admin.Modules.Notification');\n return false;\n }\n\n // Check module dependencies\n if (count($this->dependencies) > 0) {\n foreach ($this->dependencies as $dependency) {\n if (!Db::getInstance()->getRow('SELECT `id_module` FROM `'._DB_PREFIX_.'module` WHERE LOWER(`name`) = \\''.pSQL(Tools::strtolower($dependency)).'\\'')) {\n $error = Context::getContext()->getTranslator()->trans('Before installing this module, you have to install this/these module(s) first:', array(), 'Admin.Modules.Notification').'<br />';\n foreach ($this->dependencies as $d) {\n $error .= '- '.$d.'<br />';\n }\n $this->_errors[] = $error;\n return false;\n }\n }\n }\n\n // Check if module is installed\n $result = (new ModuleDataProvider(new LegacyLogger(), $this->getTranslator()))->isInstalled($this->name);\n if ($result) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('This module has already been installed.', array(), 'Admin.Modules.Notification');\n return false;\n }\n\n if (!$this->installControllers()) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Could not install module controllers.', array(), 'Admin.Modules.Notification');\n $this->uninstallOverrides();\n return false;\n }\n\n // Install module and retrieve the installation id\n $result = Db::getInstance()->insert($this->table, array('name' => $this->name, 'active' => 1, 'version' => $this->version));\n if (!$result) {\n $this->_errors[] = Context::getContext()->getTranslator()->trans('Technical error: PrestaShop could not install this module.', array(), 'Admin.Modules.Notification');\n $this->uninstallTabs();\n $this->uninstallOverrides();\n return false;\n }\n $this->id = Db::getInstance()->Insert_ID();\n\n Cache::clean('Module::isInstalled'.$this->name);\n\n // Enable the module for current shops in context\n $this->enable();\n\n // Permissions management\n foreach (array('CREATE', 'READ', 'UPDATE', 'DELETE') as $action) {\n $slug = 'ROLE_MOD_MODULE_'.strtoupper($this->name).'_'.$action;\n\n Db::getInstance()->execute(\n 'INSERT INTO `'._DB_PREFIX_.'authorization_role` (`slug`) VALUES (\"'.$slug.'\")'\n );\n\n Db::getInstance()->execute('\n INSERT INTO `'._DB_PREFIX_.'module_access` (`id_profile`, `id_authorization_role`) (\n SELECT id_profile, \"'.Db::getInstance()->Insert_ID().'\"\n FROM '._DB_PREFIX_.'access a\n LEFT JOIN `'._DB_PREFIX_.'authorization_role` r\n ON r.id_authorization_role = a.id_authorization_role\n WHERE r.slug = \"ROLE_MOD_TAB_ADMINMODULESSF_'.$action.'\"\n )');\n }\n\n // Adding Restrictions for client groups\n Group::addRestrictionsForModule($this->id, Shop::getShops(true, null, true));\n Hook::exec('actionModuleInstallAfter', array('object' => $this));\n\n if (Module::$update_translations_after_install) {\n $this->updateModuleTranslations();\n }\n\n return true;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $details = $input->getOption('details');\n $returnData = [\n 'headers' => [\n 'Bundle',\n 'Enabled',\n 'Installed',\n $input->hasOption('json') ? 'Installable' : 'I?',\n $input->hasOption('json') ? 'Uninstallable' : 'UI?',\n 'Priority',\n ],\n 'rows' => [],\n ];\n\n if ($details) {\n array_splice($returnData['headers'], 1, 0, ['Description', 'Version']);\n }\n\n foreach ($this->bundleManager->getAvailableBundles() as $bundleClass) {\n $row = [];\n $row[] = $input->getOption('fully-qualified-classnames') ? $bundleClass : $this->getShortClassName($bundleClass);\n\n try {\n $bundle = $this->bundleManager->getActiveBundle($bundleClass, false);\n if ($details) {\n $row[] = substr($bundle->getDescription(), 0, 30) . (strlen($bundle->getDescription()) > 30 ? '...' : '');\n $row[] = $bundle->getVersion();\n }\n $row[] = true;\n $row[] = $this->bundleManager->isInstalled($bundle);\n $row[] = $this->bundleManager->canBeInstalled($bundle);\n $row[] = $this->bundleManager->canBeUninstalled($bundle);\n $row[] = $this->bundleManager->getManuallyRegisteredBundleState($bundleClass)['priority'];\n } catch (BundleNotFoundException $e) {\n if ($details) {\n $row[] = '';\n $row[] = '';\n }\n $row[] = $row[] = $row[] = $row[] = false;\n $row[] = 0;\n }\n\n $returnData['rows'][] = $row;\n }\n\n if ($input->getOption('json')) {\n $jsonData = array_map(fn ($row) => array_combine($returnData['headers'], $row), $returnData['rows']);\n $output->write(json_encode($jsonData, JSON_PRETTY_PRINT));\n } else {\n $table = new Table($output);\n\n $table->setHeaders($returnData['headers']);\n\n $returnData['rows'] = array_map(function ($row) {\n foreach ($row as $idx => $column) {\n if (is_bool($column)) {\n $row[$idx] = $this->formatBool($column);\n }\n }\n\n return $row;\n }, $returnData['rows']);\n\n $table->addRows($returnData['rows']);\n\n $table->render();\n\n $this->io->newLine();\n $this->io->writeln(implode(' ', [\n 'Legend:',\n '<comment>I?</comment>: Can be installed?',\n '<comment>UI?</comment>: Can be uninstalled?',\n '<comment>UP?</comment>: Can be updated?',\n ]));\n }\n\n return 0;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "function _prepareDetails($system, $rectype, $record, $validation_mode, $recID, $modeImport)\n{\n global $terms, $useNewTemporalFormatInRecDetails;\n\n $details = $record['details'];\n\n /*\n * $details is the form\n * $details = array(\"t:1\" => array(\"bd:234463\" => \"7th Ave\"),\n * ,,,\n * \"t:11\" => array(\"0\" => \"p POINT (-73.951172 40.805661)\"));\n * where t:id means detail type id and bd:id means detail record id\n * new details are array values without a preceeding detail ID as in the last line of this example\n */\n\n //1. load record structure\n //2. verify (value, termid, file id, resource id) and prepare details (geo field). verify required field presence\n //3. delete existing details\n //4. insert new set\n\n\n $mysqli = $system->get_mysqli();\n\n //exlude empty and wrong entries t:dty_ID:[0:value, 1:value]\n $details2 = array();\n foreach ($details as $dtyID => $pairs) {\n\n if( (is_array($pairs) && empty($pairs)) || $pairs=='') {continue;} //empty value\n\n if(preg_match(\"/^t:\\\\d+$/\", $dtyID)){ //old format with t:NNN\n $dtyID = substr($dtyID, 2);\n }\n if(is_numeric($dtyID) && $dtyID>0){ //ignore header and supplementary fields\n $details2[$dtyID] = is_array($pairs)?$pairs:array($pairs);\n }\n }\n\n //get list of fieldtypes for all details\n $query = 'SELECT dty_ID, dty_Type FROM defDetailTypes WHERE dty_ID in (' . implode(',', array_keys($details2)) . ')';\n $det_types = mysql__select_assoc2($mysqli, $query);\n\n $det_required = array();\n if($validation_mode>1){\n //load list of required details except relmarker\n $query = 'SELECT rst_DetailTypeID, IF((rst_DisplayName=\\'\\' OR rst_DisplayName IS NULL), dty_Name, rst_DisplayName) as rst_DisplayName '\n .'FROM defRecStructure, defDetailTypes WHERE '\n .\"rst_RecTypeID=$rectype and rst_RequirementType='required' and dty_ID=rst_DetailTypeID \"\n .\" and dty_Type!='relmarker' and dty_Type!='separator'\";\n $det_required = mysql__select_assoc2($mysqli, $query);\n }\n\n $det_childpointers = mysql__select_list($mysqli, \"defRecStructure\",\n \"rst_DetailTypeID\",\n \"rst_RecTypeID=$rectype and rst_CreateChildIfRecPtr=1\");\n\n\n //$query_size = 'select LENGTH(?)';\n //$stmt_size = $mysqli->prepare($query_size);\n\n $system->defineConstant('RT_CMS_HOME');\n $system->defineConstant('RT_CMS_MENU');\n $system->defineConstant('DT_EXTENDED_DESCRIPTION');\n\n //list of field ids that will not html purified\n $not_purify = array();\n /*if($system->defineConstant('DT_CMS_SCRIPT')){ array_push($not_purify, DT_CMS_SCRIPT);}\n if($system->defineConstant('DT_CMS_CSS')){ array_push($not_purify, DT_CMS_CSS);}\n if($system->defineConstant('DT_SYMBOLOGY')){ array_push($not_purify, DT_SYMBOLOGY);}\n if($system->defineConstant('DT_KML')){ array_push($not_purify, DT_KML);}\n if($system->defineConstant('DT_QUERY_STRING')){ array_push($not_purify, DT_QUERY_STRING);}\n if($system->defineConstant('DT_SERVICE_URL')){ array_push($not_purify, DT_SERVICE_URL);}*/\n if($system->defineConstant('DT_CMS_EXTFILES')){ array_push($not_purify, DT_CMS_EXTFILES);}\n // $purifier = USanitize::getHTMLPurifier();\n //2. verify (value, termid, file id, resource id) and prepare details (geo field). verify required field presence\n\n $insertValues = array();\n $errorValues = array();\n $cntErrors = 0;\n\n foreach ($details2 as $dtyID => $values) {\n\n $splitValues = array();\n $idx_in_vis = 0;\n\n foreach ($values as $eltID => $dtl_Value) {\n\n if(!is_array($dtl_Value) && strlen(super_trim($dtl_Value))==0){\n $idx_in_vis++;\n continue;\n }\n\n $dtl_HideFromPublic = null;\n if(@$record['details_visibility'][$dtyID]){\n $dtl_HideFromPublic = (@$record['details_visibility'][$dtyID][$idx_in_vis]>0)?1:0;\n }\n $idx_in_vis++;\n\n $dval = array('dtl_DetailTypeID'=>$dtyID);\n\n $dtl_UploadedFileID = null;\n $dtl_Geo = null;\n $isValid = false;\n $err_msg = '';\n\n if(!(is_array($dtl_Value) || $det_types[$dtyID]=='geo' || $det_types[$dtyID]=='file')){\n $rval = $mysqli->real_escape_string( $dtl_Value );\n\n\n //special case: split huge web content\n if(defined('RT_CMS_MENU') && $rectype==RT_CMS_MENU && $dtyID==DT_EXTENDED_DESCRIPTION){\n $lim = checkMaxLength2($rval);\n //TEST $lim = 100;\n if($lim>0){\n //remove script tag\n $dtl_Value = super_trim($dtl_Value);\n $dtl_Value = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $dtl_Value);\n\n //$dtl_Value = $purifier->purify($dtl_Value);\n //$dtl_Value = htmlspecialchars_decode( $dtl_Value );\n\n $iStart = 0;\n while($iStart<mb_strlen($dtl_Value)){\n array_push($splitValues, mb_substr($dtl_Value, $iStart, $lim));\n $iStart = $iStart + $lim;\n }\n }\n }else{\n $err_msg = checkMaxLength('#'.$dtyID, $rval);\n if($err_msg!=null) {break;}\n }\n }\n\n switch ($det_types[$dtyID]) {\n\n case \"freetext\":\n case \"blocktext\":\n $len = strlen(super_trim($dtl_Value));\n $isValid = ($len > 0);\n if(!$isValid ){\n $err_msg = 'Value is empty';\n }elseif(!in_array($dtyID, $not_purify)){\n $dtl_Value = super_trim($dtl_Value);\n $dtl_Value = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $dtl_Value);\n\n if($det_types[$dtyID]==\"freetext\"){ //remove non standard attributes\n //(\\w+)\n $allowed = array('src','class','style','href');\n $allowed2 = implode('=|',$allowed).'=';\n $regex = ')[^>]))*((?:';\n $allowed = implode('|',$allowed);\n$dtl_Value = preg_replace('#<([A-Z][A-Z0-9]*)(\\s*)(?:(?:(?:(?!'.$allowed2.$regex.$allowed\n .')=[\\'\"][^\\'\"]*[\\'\"]\\s*)?)(?:(?:(?:(?!'.$allowed2.$regex.$allowed\n .')=[\\'\"][^\\'\"]*[\\'\"]\\s*)?)(?:(?:(?:(?!'.$allowed2.$regex.$allowed\n .')=[\\'\"][^\\'\"]*[\\'\"]\\s*)?)[^>]*>#si','<$1$2$3$4$5>',$dtl_Value);\n }\n\n }\n break;\n\n case \"date\":\n\n if(is_array($dtl_Value)){ //date is temporal json array\n $isValid = count($dtl_Value)>1 && (@$dtl_Value['timestamp'] || @$dtl_Value['start']);\n }else{\n $len = strlen(super_trim($dtl_Value));\n $isValid = ($len > 0);\n }\n\n if(!$isValid ){\n $err_msg = 'Value is empty';\n }else{\n\n $dtl_Value = Temporal::getValueForRecDetails( $dtl_Value, $useNewTemporalFormatInRecDetails );\n\n/* Use old plain temporals\n }else{\n //yesterday, today, tomorrow, now\n $sdate = strtolower(super_trim($dtl_Value));\n if($sdate=='today'){\n $dtl_Value = date('Y-m-d');\n }elseif($sdate=='now'){\n $dtl_Value = date(DATE_8601);\n }elseif($sdate=='yesterday'){\n $dtl_Value = date('Y-m-d',strtotime(\"-1 days\"));\n }elseif($sdate=='tomorrow'){\n $dtl_Value = date('Y-m-d',strtotime(\"+1 days\"));\n }elseif(strlen($dtl_Value)>=8 && strpos($dtl_Value,'-')==false){\n\n try{\n $t2 = new DateTime($dtl_Value);\n\n $format = 'Y-m-d';\n if($t2->format('H')>0 || $t2->format('i')>0 || $t2->format('s')>0){\n //strlen($dtl_Value)>=12 || strpos($dtl_Value,'T')>7 || strpos($dtl_Value,' ')>7){\n if($t2->format('s')>0){\n $format .= ' H:i:s';\n }else{\n $format .= ' H:i';\n }\n }\n $dtl_Value = $t2->format($format);\n\n }catch(Exception $e){\n //skip conversion\n\n }\n }\n }\n*/\n }\n break;\n case \"float\":\n $isValid = preg_match(\"/^\\\\s*-?(?:\\\\d+[.]?|\\\\d*[.]\\\\d+(?:[eE]-?\\\\d+)?)\\\\s*$/\", $dtl_Value);\n //preg_match('/^0(?:[.]0*)?$/', $dtl_Value)\n if(!$isValid ) {$err_msg = 'Not valid float value '.htmlspecialchars($dtl_Value);}\n break;\n case \"enum\":\n case \"relationtype\":\n\n if($validation_mode>1){\n\n if(!$terms){\n $terms = new DbsTerms($system, dbs_GetTerms($system));\n }\n\n $term_domain = ($det_types[$dtyID]==\"enum\"?\"enum\":\"relation\");\n\n if (is_numeric($dtl_Value)){\n $term_tocheck = $dtl_Value;\n }else{\n $term_tocheck = $terms->getTermByLabel($term_domain, $dtl_Value);//within domain\n }\n $isValid = isValidTerm($system, $term_tocheck, $term_domain, $dtyID, $rectype);\n if($isValid){\n $dtl_Value = $term_tocheck;\n }else{\n $trm = $terms->getTerm($dtl_Value);\n $err_msg = 'Term ID '.htmlspecialchars($dtl_Value)\n . ($trm!=null\n ?( ' <i>'.htmlspecialchars($trm[0]).'</i> is not in the list of values defined for this field')\n :' not found');\n }\n }else{\n $isValid = (intval($dtl_Value)>0);\n }\n\n break;\n\n case \"resource\":\n\n if($validation_mode>1){\n //check if resource record exists\n $rectype_tocheck = mysql__select_row($mysqli, 'select rec_RecTypeID, rec_Title '\n .'from Records where rec_ID = '.$dtl_Value);//or dbs_GetRectypeByID from db_strucuture\n if($rectype_tocheck){\n\n\n //check that this rectype is valid for given detail (constrained pointer)\n $isValid = isValidRectype($system, $rectype_tocheck[0], $dtyID, $rectype);\n if(!$isValid){\n\n $err_msg = '<div style=\"padding-left:30px\">'\n . _getRtConstraintNames($system, $dtyID, $rectype)\n . '<br>Target ID:'.$dtl_Value.' '.USanitize::sanitizeString($rectype_tocheck[1], false).DIV_E;\n\n\n //$err_msg = 'Record type '.$rectype_tocheck.' is not valid for specified constraints';\n }\n }else{\n $err_msg = 'Record with specified id '.htmlspecialchars($dtl_Value).' does not exist';\n }\n }else{\n $isValid = (intval($dtl_Value)>0);\n if(!$isValid){\n $err_msg = 'Record ID '.htmlspecialchars($dtl_Value).' is not valid integer';\n }\n }\n //this is parent-child resource (record pointer)\n if($isValid && in_array($dtyID, $det_childpointers)){\n $dval['dtl_ParentChild'] = true;\n }\n\n break;\n\n\n case \"file\": //@TODO\n\n if($dtl_Value=='generate_thumbnail_from_url' && @$record['URL']){\n\n $tmp_file = UImage::makeURLScreenshot($record['URL']);\n\n if(!is_a($tmp_file,'stdClass')){\n $err_msg = is_array($tmp_file) ?$tmp_file['error'] :('System message: '.$tmp_file);\n }else{\n $entity = new DbRecUploadedFiles($system);\n\n $dtl_UploadedFileID = $entity->registerFile($tmp_file, null);//it returns ulf_ID\n\n if($dtl_UploadedFileID===false){\n $err_msg = $system->getError();\n $err_msg = $err_msg['message'];\n $system->clearError();\n }else{\n $dtl_UploadedFileID = $dtl_UploadedFileID[0];\n }\n }\n\n if($err_msg!=''){\n //send email to heurist team about fail generation from url\n $msg = 'The thumbnailer fails to return an image '.$record['URL'].'. '.$err_msg;\n sendEmail(HEURIST_MAIL_TO_ADMIN, 'The thumbnailer fails to return an image '.$system->dbname(), $msg);\n $err_msg = '';\n $dtl_Value = '';\n $isValid = 'ignore';\n break; //just ignore this value\n }\n\n }elseif(is_numeric($dtl_Value)){ //this is ulf_ID\n $dtl_UploadedFileID = intval($dtl_Value);\n\n //TODO !!! mysql_num_rows(mysql_query(\"select ulf_ID from recUploadedFiles where ulf_ID=\".dtl_UploadedFileID)) <=0 )\n\n }elseif(is_string($dtl_Value)){ //this is base64 encoded image\n\n //save encoded image as file and register it\n $entity = new DbRecUploadedFiles($system);\n $dtl_UploadedFileID = $entity->registerImage($dtl_Value, 'map_snapshot_'.$recID);//it returns ulf_ID\n if( is_bool($dtl_UploadedFileID) && !$dtl_UploadedFileID ){\n $dtl_UploadedFileID = -1; //fail\n $err_msg = 'Can\\'t register snapshot image';\n }\n if(is_array($dtl_UploadedFileID)){\n $dtl_UploadedFileID = $dtl_UploadedFileID[0];\n }\n\n\n }else{ // new way - URL or JSON string with file data array (structure similar get_uploaded_file_info)\n //TODO!!!!!\n // $dtl_UploadedFileID = register_external($dtl_Value);\n $dtl_UploadedFileID = intval(@$dtl_Value['ulf_ID']);\n }\n\n\n $dtl_Value = null;\n $isValid = ($dtl_UploadedFileID>0);\n\n if($validation_mode==0 && !$isValid) {$isValid = 'ignore';}\n\n break;\n\n case \"geo\":\n\n //note geoType can be not defined - detect it from dtl_Geo\n list($dtl_Value, $dtl_Geo) = prepareGeoValue($mysqli, $dtl_Value);\n if($dtl_Value===false){\n $err_msg = $dtl_Geo;\n $isValid = ($validation_mode==0)?'ignore':false;\n if(!$isValid && $modeImport == 1){\n $dval['dtl_Value'] = $values[$eltID];\n $dval['dtl_UploadedFileID'] = null;\n $dval['dtl_Geo'] = null;\n array_push($insertValues, $dval);\n $isValid = 'ignore';\n }\n }else{\n $isValid = true;\n }\n\n\n /*\n $res = $mysqli->query(\"select ST_asWKT(ST_GeomFromText('\".addslashes($dtl_Geo).\"'))\");\n if ($res){\n if($res->fetch_row()){\n $dtl_Value = $geoType;\n $isValid = true;\n }\n $res->close();\n }*/\n break;\n // retained for backward compatibility\n case \"year\":\n $isValid = preg_match(\"/^\\\\s*(?:(?:-|ad\\\\s*)?\\\\d+(?:\\\\s*bce?)?|in\\\\s+press)\\\\s*$/i\", $dtl_Value);\n if(!$isValid){\n $err_msg = htmlspecialchars($dtl_Value);\n $err_msg = \"Value $err_msg is not valid Year\";\n }\n break;\n case \"boolean\":\n\n $isValid = preg_match(\"/^(?:yes|true|no|false|1|0|T|F|Y|N)$/\", $dtl_Value);\n if($isValid){\n if ($dtl_Value==1 || $dtl_Value == 'T' || $dtl_Value == 'Y'\n || $dtl_Value == \"yes\" || $dtl_Value == \"true\"){\n $dtl_Value = \"true\";\n }else{\n $dtl_Value = \"false\";\n }\n }else{\n $err_msg = htmlspecialchars($dtl_Value);\n $err_msg = \"Value $err_msg is not valid boolean\";\n }\n break;\n case \"integer\":\n $isValid = preg_match(\"/^\\\\s*-?\\\\d+\\\\s*$/\", $dtl_Value);\n if(!$isValid){\n $err_msg = htmlspecialchars($dtl_Value);\n $err_msg = \"Value $err_msg is not valid integer\";\n }\n break;\n\n case \"separator\":\n case \"relmarker\":\n default:\n break; //noop since separators and relmarker have no detail values\n } //switch\n\n\n if($isValid==='ignore') {continue;}\n\n //ignore all errors and skip empty values\n if($validation_mode==0 && $isValid!==true){\n if(strlen(super_trim($dtl_Value))==0) {continue;}\n $isValid = true;\n }\n\n if($isValid == true){\n\n if(@$det_required[$dtyID]!=null){\n unset($det_required[$dtyID]);//value is valid - removes from list of required\n }\n\n $dval['dtl_UploadedFileID'] = $dtl_UploadedFileID;\n $dval['dtl_Geo'] = $dtl_Geo;\n $dval['dtl_HideFromPublic'] = $dtl_HideFromPublic;\n if(!empty($splitValues)){\n foreach($splitValues as $val){\n $dval['dtl_Value'] = $val;\n array_push($insertValues, $dval);\n }\n }else{\n $dval['dtl_Value'] = $dtl_Value;\n array_push($insertValues, $dval);\n }\n }else{\n if(!@$errorValues[$dtyID])\n {\n $query = 'SELECT rst_DisplayName FROM defRecStructure WHERE rst_RecTypeID='.$rectype\n .' and rst_DetailTypeID='.$dtyID;\n $field_name = mysql__select_value($mysqli, $query);\n if(!$field_name){\n $query = 'SELECT dty_Name FROM defDetailTypes WHERE dty_ID='.$dtyID;\n $field_name = mysql__select_value($mysqli, $query);\n }\n\n $dt_names = dbs_GetDtLookups();\n\n if($modeImport>0){\n $errorValues[$dtyID] = $field_name;\n }else{\n $errorValues[$dtyID] = '<br><div>Field ID '.$dtyID.': \"'\n .$field_name.'\" ('.@$dt_names[$det_types[$dtyID]].')</div>';\n }\n }\n if($modeImport>0){\n $errorValues[$dtyID] .= (' '.$err_msg);\n }else{\n $errorValues[$dtyID] .= ('<div style=\"padding-left:20px\">'.$err_msg.DIV_E);\n }\n $cntErrors++;\n }\n\n }//for values\n }//for detail types\n\n //$stmt_size->close();\n\n\n $res = false;\n\n //there is undefined required details\n if ($cntErrors>0) {\n\n $ss = ($cntErrors>1?'s':'');\n /*\n array_push($errorValues,\n '<br><br>Please run Verify > Verify integrity to check for and fix data problems.<br>'\n .'If the problem cannot be fixed, or re-occurs frequently, please '.CONTACT_HEURIST_TEAM);\n */\n\n if($modeImport>0){\n $sMsg = implode(' ',$errorValues);\n }else{\n $sMsg = 'Encountered invalid value'.$ss\n .' for Record# '.$recID.'<br>'.implode(' ',$errorValues)\n .'<br> This may be due to your browser cache being out-of-date (use Ctrl-F5 to reload the page)';\n }\n\n $system->addError(HEURIST_ACTION_BLOCKED, $sMsg, null);\n\n }else{\n\n if (!isEmptyArray($det_required)) {\n\n $missed_req_dty = array_keys($det_required);\n foreach($missed_req_dty as $dty_ID){\n //try to add default values for missed required fields\n $query = 'SELECT rst_DefaultValue FROM defRecStructure WHERE rst_RecTypeID='.$rectype\n .' and rst_DetailTypeID='.$dty_ID;\n $defaultValue = mysql__select_value($mysqli, $query);\n if($defaultValue!=null && $defaultValue!=''){\n array_push($insertValues, array('dtl_DetailTypeID'=>$dty_ID, 'dtl_Value'=>$defaultValue));\n unset($det_required[$dty_ID]);\n }\n }\n }\n\n if (!isEmptyArray($det_required)) {\n $isMulti = (count($det_required)>1);\n $query = 'SELECT rty_Name FROM defRecTypes WHERE rty_ID='.$rectype;\n $rty_Name = mysql__select_value($mysqli, $query);\n\n $system->addError(HEURIST_ACTION_BLOCKED, 'Required field'.($isMulti?'s':'')\n .' missing value or '.\n (count($det_required)>1?'have':'has')\n .' invalid value:<div style=\"padding-left:10px;font-style:italic;\">'.implode('<br>',array_values($det_required)).DIV_E\n .' <br>Please change '.($isMulti?'these fields':'this field')\n .' in record type \"'.htmlspecialchars($rty_Name)\n .'\" to \"optional\" or specify default value for the field');\n\n }elseif (!is_array($insertValues) || count($insertValues)<1) {\n $system->addError(HEURIST_INVALID_REQUEST, \"It is not possible save record. No fields are defined\");\n }else{\n $res = $insertValues;\n }\n }\n\n return $res;\n\n}", "smellKey": "S3776", "smellId": null, "repo": "HeuristNetwork_heurist", "language": "php"} {"function": "private static function getAllHookRegistrations(Context $context, ?string $hookName): array\n {\n $shop = $context->shop;\n $customer = $context->customer;\n\n $cache_id = self::MODULE_LIST_BY_HOOK_KEY\n . (isset($shop->id) ? '_' . $shop->id : '')\n . (isset($customer->id) ? '_' . $customer->id : '');\n\n $useCache = (\n !in_array(\n $hookName,\n [\n 'displayPayment',\n 'displayPaymentEU',\n 'paymentOptions',\n 'displayBackOfficeHeader',\n 'displayAdminLogin',\n ]\n )\n );\n\n if ($useCache && Cache::isStored($cache_id)) {\n return Cache::retrieve($cache_id);\n }\n\n $groups = [];\n $use_groups = Group::isFeatureActive();\n $frontend = !$context->employee instanceof Employee;\n if ($frontend) {\n // Get groups list\n if ($use_groups) {\n if ($customer instanceof Customer && $customer->isLogged()) {\n $groups = $customer->getGroups();\n } elseif ($customer instanceof Customer && $customer->isLogged(true)) {\n $groups = [(int) Configuration::get('PS_GUEST_GROUP')];\n } else {\n $groups = [(int) Configuration::get('PS_UNIDENTIFIED_GROUP')];\n }\n }\n }\n\n // SQL Request\n $sql = new DbQuery();\n $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module');\n $sql->from('module', 'm');\n if (!in_array($hookName, ['displayBackOfficeHeader', 'displayAdminLogin'])) {\n $sql->join(\n Shop::addSqlAssociation(\n 'module',\n 'm',\n true,\n 'module_shop.enable_device & ' . (int) Context::getContext()->getDevice()\n )\n );\n $sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');\n }\n $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');\n $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');\n if ($hookName !== 'paymentOptions') {\n $sql->where('h.`name` != \"paymentOptions\"');\n } elseif ($frontend) {\n // For payment modules, we check that they are available in the contextual country\n if (Validate::isLoadedObject($context->country)) {\n $sql->where(\n '(\n h.`name` IN (\"displayPayment\", \"displayPaymentEU\", \"paymentOptions\")\n AND (\n SELECT `id_country`\n FROM `' . _DB_PREFIX_ . 'module_country` mc\n WHERE mc.`id_module` = m.`id_module`\n AND `id_country` = ' . (int) $context->country->id . '\n AND `id_shop` = ' . (int) $shop->id . '\n LIMIT 1\n ) = ' . (int) $context->country->id . ')'\n );\n }\n if (Validate::isLoadedObject($context->currency)) {\n $sql->where(\n '(\n h.`name` IN (\"displayPayment\", \"displayPaymentEU\", \"paymentOptions\")\n AND (\n SELECT `id_currency`\n FROM `' . _DB_PREFIX_ . 'module_currency` mcr\n WHERE mcr.`id_module` = m.`id_module`\n AND `id_currency` IN (' . (int) $context->currency->id . ', -1, -2)\n LIMIT 1\n ) IN (' . (int) $context->currency->id . ', -1, -2))'\n );\n }\n if (Validate::isLoadedObject($context->cart)) {\n $carrier = new Carrier($context->cart->id_carrier);\n if (Validate::isLoadedObject($carrier)) {\n $sql->where(\n '(\n h.`name` IN (\"displayPayment\", \"displayPaymentEU\", \"paymentOptions\")\n AND (\n SELECT `id_reference`\n FROM `' . _DB_PREFIX_ . 'module_carrier` mcar\n WHERE mcar.`id_module` = m.`id_module`\n AND `id_reference` = ' . (int) $carrier->id_reference . '\n AND `id_shop` = ' . (int) $shop->id . '\n LIMIT 1\n ) = ' . (int) $carrier->id_reference . ')'\n );\n }\n }\n }\n if (Validate::isLoadedObject($shop) && $hookName !== 'displayAdminLogin') {\n $sql->where('hm.`id_shop` = ' . (int) $shop->id);\n }\n\n if ($frontend) {\n if ($use_groups) {\n $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');\n if (Validate::isLoadedObject($shop)) {\n $sql->where(\n 'mg.id_shop = ' . ((int) $shop->id)\n . (count($groups) ? ' AND mg.`id_group` IN (' . implode(', ', $groups) . ')' : '')\n );\n } elseif (count($groups)) {\n $sql->where('mg.`id_group` IN (' . implode(', ', $groups) . ')');\n }\n }\n }\n\n $sql->groupBy('hm.id_hook, hm.id_module');\n $sql->orderBy('hm.`position`');\n\n $allHookRegistrations = [];\n if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {\n foreach ($result as $row) {\n $row['hook'] = strtolower($row['hook']);\n if (!isset($allHookRegistrations[$row['hook']])) {\n $allHookRegistrations[$row['hook']] = [];\n }\n\n $allHookRegistrations[$row['hook']][] = [\n 'id_hook' => $row['id_hook'],\n 'module' => $row['module'],\n 'id_module' => $row['id_module'],\n ];\n }\n }\n\n if ($useCache) {\n Cache::store($cache_id, $allHookRegistrations);\n // @todo remove this in 1.6, we keep it in 1.5 for backward compatibility\n static::$_hook_modules_cache_exec = $allHookRegistrations;\n }\n\n return $allHookRegistrations;\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['purpose'])) {\n $this->setPurpose($data['purpose']);\n }\n if (isset($data['name'])) {\n $this->setName($data['name']);\n }\n if (isset($data['telecom'])) {\n if (is_array($data['telecom'])) {\n foreach ($data['telecom'] as $d) {\n $this->addTelecom($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"telecom\" must be array of objects or null, ' . gettype($data['telecom']) . ' seen.');\n }\n }\n if (isset($data['address'])) {\n $this->setAddress($data['address']);\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['characteristicCodeableConcept'])) {\n $this->setCharacteristicCodeableConcept($data['characteristicCodeableConcept']);\n }\n if (isset($data['characteristicQuantity'])) {\n $this->setCharacteristicQuantity($data['characteristicQuantity']);\n }\n if (isset($data['value'])) {\n if (is_array($data['value'])) {\n foreach ($data['value'] as $d) {\n $this->addValue($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"value\" must be array of objects or null, ' . gettype($data['value']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function __construct(Profiel $profiel, $inschrijven)\n\t{\n\t\tif ($profiel->uid) {\n\t\t\tparent::__construct($profiel, '/profiel/' . $profiel->uid . '/bewerken');\n\t\t} else {\n\t\t\tparent::__construct(\n\t\t\t\t$profiel,\n\t\t\t\t'/profiel/' .\n\t\t\t\t\t$profiel->lidjaar .\n\t\t\t\t\t'/nieuw/' .\n\t\t\t\t\tstrtolower(substr($profiel->status, 2))\n\t\t\t);\n\t\t}\n\n\t\t$admin = LoginService::mag(P_LEDEN_MOD);\n\t\t$novCie = LoginService::mag('commissie:NovCie');\n\n\t\t$fields = [];\n\t\tif ($inschrijven) {\n\t\t\t$this->titel = 'Welkom bij C.S.R.!';\n\t\t\t$fields[] = new HtmlComment('<p>\n\t\t\t\tHieronder mag je gegevens invullen in het databeest van de Civitas. Zo kunnen we contact met je houden,\n\t\t\t\tkunnen andere leden opzoeken waar je woont en kun je (na het novitiaat) op het forum berichten plaatsen.\n\t\t\t</p>');\n\t\t} else {\n\t\t\t$this->titel = 'Bewerk het profiel van ' . $profiel->getNaam('volledig');\n\t\t\t$fields[] = new HtmlComment(\n\t\t\t\t'<p>\n\t\t\t\tHieronder kunt u uw eigen gegevens wijzigen. Voor enkele velden is het niet mogelijk zelf\n\t\t\t\twijzigingen door te voeren. Voor de meeste velden geldt daarnaast dat de ingevulde gegevens\n\t\t\t\teen geldig formaat moeten hebben. Mochten er fouten in het gedeelte van uw profiel staan,\n\t\t\t\tdat u niet zelf kunt wijzigen, meld het dan bij de <a href=\"mailto:' .\n\t\t\t\t\t$_ENV['EMAIL_VAB'] .\n\t\t\t\t\t'\">Vice-Abactis</a>.\n\t\t\t</p>'\n\t\t\t);\n\t\t}\n\t\t$fields[] = new HtmlComment('<p>\n\t\t\tAls er <span class=\"waarschuwing\">tekst in rode letters</span> wordt afgebeeld bij een veld, dan\n\t\t\tbetekent dat dat de invoer niet geaccepteerd is, en dat u die zult moeten aanpassen aan het\n\t\t\tgevraagde formaat. Een aantal velden kan leeg gelaten worden als er geen zinvolle informatie voor is.\n\t\t</p>');\n\n\t\tif ($admin) {\n\t\t\t$statussen = [];\n\t\t\tforeach (LidStatus::getEnumValues() as $optie) {\n\t\t\t\t$statussen[$optie] = LidStatus::from($optie)->getDescription();\n\t\t\t}\n\t\t\t$fields[] = new SelectField(\n\t\t\t\t'status',\n\t\t\t\t$profiel->status,\n\t\t\t\t'Lidstatus',\n\t\t\t\t$statussen\n\t\t\t);\n\t\t\t$fields[] = new HtmlComment(\n\t\t\t\t'<p>Bij het wijzigen van de lidstatus worden overbodige <span class=\"waarschuwing\">gegevens verwijderd</span>, onomkeerbaar, opletten dus!</p>'\n\t\t\t);\n\n\t\t\t$profielService = ContainerFacade::getContainer()->get(\n\t\t\t\tProfielService::class\n\t\t\t);\n\n\t\t\tif ($profiel->voornaam == '') {\n\t\t\t\t$gelijknamigenovieten = [];\n\t\t\t} else {\n\t\t\t\t$gelijknamigenovieten = $profielService->zoekLeden(\n\t\t\t\t\t$profiel->voornaam,\n\t\t\t\t\t'voornaam',\n\t\t\t\t\t'alle',\n\t\t\t\t\t'achternaam',\n\t\t\t\t\t[LidStatus::Noviet]\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ($profiel->achternaam == '') {\n\t\t\t\t$gelijknamigeleden = [];\n\t\t\t} else {\n\t\t\t\t$gelijknamigeleden = $profielService->zoekLeden(\n\t\t\t\t\t$profiel->achternaam,\n\t\t\t\t\t'achternaam',\n\t\t\t\t\t'alle',\n\t\t\t\t\t'lidjaar',\n\t\t\t\t\t[LidStatus::Lid, LidStatus::Gastlid]\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t$html = '<div class=\"novieten\">';\n\t\t\tif (\n\t\t\t\tcount($gelijknamigenovieten) > 1 ||\n\t\t\t\t($profiel->status !== LidStatus::Noviet &&\n\t\t\t\t\t!empty($gelijknamigenovieten))\n\t\t\t) {\n\t\t\t\t$html .= 'Gelijknamige novieten:<ul class=\"nobullets\">';\n\t\t\t\tforeach ($gelijknamigenovieten as $noviet) {\n\t\t\t\t\t$html .= '<li>' . $noviet->getLink('volledig') . '</li>';\n\t\t\t\t}\n\t\t\t\t$html .= '</ul>';\n\t\t\t} else {\n\t\t\t\t$html .= 'Geen novieten met overeenkomstige namen.';\n\t\t\t}\n\t\t\t$html .= '</div><div class=\"leden\">';\n\t\t\tif (\n\t\t\t\tcount($gelijknamigeleden) > 1 ||\n\t\t\t\t(!(\n\t\t\t\t\t$profiel->status == LidStatus::Lid ||\n\t\t\t\t\t$profiel->status == LidStatus::Gastlid\n\t\t\t\t) &&\n\t\t\t\t\t!empty($gelijknamigeleden))\n\t\t\t) {\n\t\t\t\t$html .= 'Gelijknamige (gast)leden:<ul class=\"nobullets\">';\n\t\t\t\tforeach ($gelijknamigeleden as $lid) {\n\t\t\t\t\t$html .= '<li>' . $lid->getLink('volledig') . '</li>';\n\t\t\t\t}\n\t\t\t\t$html .= '</ul>';\n\t\t\t} else {\n\t\t\t\t$html .= 'Geen (gast)leden met overeenkomstige namen.';\n\t\t\t}\n\t\t\t$html .= '</div>';\n\n\t\t\t$fields[] = new HtmlComment($html);\n\t\t}\n\t\t$fields[] = new Subkopje('Identiteit');\n\t\tif ($admin || $inschrijven || $profiel->isOudlid()) {\n\t\t\t$fields[] = new RequiredTextField(\n\t\t\t\t'voornaam',\n\t\t\t\t$profiel->voornaam,\n\t\t\t\t'Voornaam',\n\t\t\t\t50\n\t\t\t);\n\t\t\t$fields[] = new RequiredTextField(\n\t\t\t\t'voorletters',\n\t\t\t\t$profiel->voorletters,\n\t\t\t\t'Voorletters',\n\t\t\t\t10\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'tussenvoegsel',\n\t\t\t\t$profiel->tussenvoegsel,\n\t\t\t\t'Tussenvoegsel',\n\t\t\t\t15\n\t\t\t);\n\t\t\t$fields[] = new RequiredTextField(\n\t\t\t\t'achternaam',\n\t\t\t\t$profiel->achternaam,\n\t\t\t\t'Achternaam',\n\t\t\t\t50\n\t\t\t);\n\t\t}\n\t\t$fields['bijnaam'] = new TextField(\n\t\t\t'nickname',\n\t\t\t$profiel->nickname,\n\t\t\t'Bijnaam',\n\t\t\t20\n\t\t);\n\t\t$fields[\n\t\t\t'bijnaam'\n\t\t]->title = \"Bijnaam is zichtbaar op profiel, kan op worden gezocht in de zoekbalk en wordt\n\t\tweergegeven op het forum bij gebruikers waarbij als profielinstelling de naamweergave 'bijnaam' is ingesteld.\";\n\t\tif ($admin || $inschrijven || $profiel->isOudlid()) {\n\t\t\tif ($admin || $inschrijven) {\n\t\t\t\t$fields[] = new RequiredEnumSelectField(\n\t\t\t\t\t'geslacht',\n\t\t\t\t\t$profiel->geslacht,\n\t\t\t\t\t'Geslacht',\n\t\t\t\t\tGeslacht::class\n\t\t\t\t);\n\t\t\t\t$fields[] = new TextField(\n\t\t\t\t\t'voornamen',\n\t\t\t\t\t$profiel->voornamen,\n\t\t\t\t\t'Voornamen',\n\t\t\t\t\t100\n\t\t\t\t);\n\t\t\t\tif (!$inschrijven) {\n\t\t\t\t\t$fields[] = new TextField('postfix', $profiel->postfix, 'Postfix', 7);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$fields[] = new RequiredDateObjectField(\n\t\t\t\t'gebdatum',\n\t\t\t\t$profiel->gebdatum,\n\t\t\t\t'Geboortedatum',\n\t\t\t\tdate('Y') - 15,\n\t\t\t\t1900\n\t\t\t);\n\t\t\tif ($admin && $profiel->status === LidStatus::Overleden) {\n\t\t\t\t$fields[] = new DateObjectField(\n\t\t\t\t\t'sterfdatum',\n\t\t\t\t\t$profiel->sterfdatum,\n\t\t\t\t\t'Overleden op'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t($admin ||\n\t\t\t\t\t$profiel->isOudlid() ||\n\t\t\t\t\t$profiel->status === LidStatus::Overleden) &&\n\t\t\t\t!$inschrijven\n\t\t\t) {\n\t\t\t\t$fields[] = new LidField(\n\t\t\t\t\t'echtgenoot',\n\t\t\t\t\t$profiel->echtgenoot,\n\t\t\t\t\t'Echtgenoot',\n\t\t\t\t\t'allepersonen'\n\t\t\t\t);\n\t\t\t\t$fields[] = new Subkopje('Oudledenpost');\n\t\t\t\t$fields[] = new TextField(\n\t\t\t\t\t'adresseringechtpaar',\n\t\t\t\t\t$profiel->adresseringechtpaar,\n\t\t\t\t\t'Tenaamstelling post echtpaar',\n\t\t\t\t\t250\n\t\t\t\t);\n\n\t\t\t\t$fields[] = new EnumSelectField(\n\t\t\t\t\t'ontvangtcontactueel',\n\t\t\t\t\t$profiel->ontvangtcontactueel,\n\t\t\t\t\t'Ontvangt Contactueel?',\n\t\t\t\t\tOntvangtContactueel::class\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t$fields[] = new Subkopje('Adres');\n\t\t$fields[] = new RequiredTextField(\n\t\t\t'adres',\n\t\t\t$profiel->adres,\n\t\t\t'Straatnaam + Huisnummer',\n\t\t\t100\n\t\t);\n\t\t$fields[] = new RequiredTextField(\n\t\t\t'postcode',\n\t\t\t$profiel->postcode,\n\t\t\t'Postcode',\n\t\t\t20\n\t\t);\n\t\t$fields[] = new RequiredTextField(\n\t\t\t'woonplaats',\n\t\t\t$profiel->woonplaats,\n\t\t\t'Woonplaats',\n\t\t\t50\n\t\t);\n\t\t$fields[] = new RequiredLandField('land', $profiel->land, 'Land');\n\n\t\tif ($profiel->propertyMogelijk('o_adres') || $inschrijven) {\n\t\t\t$fields[] = new Subkopje('Adres ouders');\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'o_adres',\n\t\t\t\t$profiel->o_adres,\n\t\t\t\t'Straatnaam + Huisnummer',\n\t\t\t\t100\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'o_postcode',\n\t\t\t\t$profiel->o_postcode,\n\t\t\t\t'Postcode',\n\t\t\t\t20\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'o_woonplaats',\n\t\t\t\t$profiel->o_woonplaats,\n\t\t\t\t'Woonplaats',\n\t\t\t\t50\n\t\t\t);\n\t\t\t$fields[] = new LandField('o_land', $profiel->o_land, 'Land');\n\t\t\t$fields[] = new TelefoonField(\n\t\t\t\t'o_telefoon',\n\t\t\t\t$profiel->o_telefoon,\n\t\t\t\t'Telefoonnummer',\n\t\t\t\t20\n\t\t\t);\n\t\t}\n\n\t\t$fields[] = new Subkopje('Contact');\n\t\t//TODO: email & multiple contacts\n\t\t$fields['email'] = new RequiredEmailField(\n\t\t\t'email',\n\t\t\t$profiel->email,\n\t\t\t'E-mailadres'\n\t\t);\n\t\t$fields['sec_email'] = new EmailField(\n\t\t\t'sec_email',\n\t\t\t$profiel->sec_email,\n\t\t\t'Secundair e-mailadres'\n\t\t);\n\t\tif (!$inschrijven) {\n\t\t\t$fields['email']->readonly = true;\n\t\t\t$fields['email']->required = false;\n\t\t\t$fields['email']->title =\n\t\t\t\t'Wijzig je e-mailadres met het inloggegevens-formulier.';\n\t\t\t$fields[] = new UrlField(\n\t\t\t\t'linkedin',\n\t\t\t\t$profiel->linkedin,\n\t\t\t\t'Publiek LinkedIn-profiel'\n\t\t\t);\n\t\t\t$fields[] = new UrlField('website', $profiel->website, 'Website');\n\t\t}\n\t\t// Mobiel & telefoon, mobiel verplicht voor (nieuwe) leden\n\t\t$fields['mobiel'] = new TelefoonField(\n\t\t\t'mobiel',\n\t\t\t$profiel->mobiel,\n\t\t\t'Mobiel',\n\t\t\t20\n\t\t);\n\t\t$fields['mobiel']->required = $inschrijven || $profiel->isLid();\n\t\t$fields[] = new TelefoonField(\n\t\t\t'telefoon',\n\t\t\t$profiel->telefoon,\n\t\t\t'Telefoonnummer (vast)',\n\t\t\t20\n\t\t);\n\n\t\t$fields[] = new Subkopje('Boekhouding');\n\n\t\t// Bankrekeningnummer: verplicht voor (nieuwe) leden\n\t\t$fields['bankrekening'] = new IBANField(\n\t\t\t'bankrekening',\n\t\t\t$profiel->bankrekening,\n\t\t\t'Bankrekening',\n\t\t\t34\n\t\t);\n\t\t$fields['bankrekening']->required = $inschrijven || $profiel->isLid();\n\n\t\tif ($admin && !$inschrijven) {\n\t\t\t$fields[] = new JaNeeField(\n\t\t\t\t'machtiging',\n\t\t\t\t$profiel->machtiging,\n\t\t\t\t'Machtiging getekend?'\n\t\t\t);\n\t\t}\n\n\t\t$fields[] = new Subkopje('Studie');\n\t\t$fields['studie'] = new StudieField('studie', $profiel->studie, 'Studie');\n\t\t$fields['studie']->title = 'Onderwijsinstelling - Studie';\n\t\t$fields['studiejaar'] = new IntField(\n\t\t\t'studiejaar',\n\t\t\t(int) $profiel->studiejaar,\n\t\t\t'Beginjaar studie',\n\t\t\t1950,\n\t\t\tdate('Y')\n\t\t);\n\t\t$fields['studiejaar']->leden_mod = $admin;\n\n\t\tif (!$inschrijven && ($admin || $profiel->isOudlid())) {\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'beroep',\n\t\t\t\t$profiel->beroep,\n\t\t\t\t'Beroep/werk',\n\t\t\t\t4096\n\t\t\t);\n\t\t\t$fields[] = new IntField(\n\t\t\t\t'lidjaar',\n\t\t\t\t(int) $profiel->lidjaar,\n\t\t\t\t'Lid sinds',\n\t\t\t\t1950,\n\t\t\t\tdate('Y')\n\t\t\t);\n\t\t\t$fields[] = new DateObjectField(\n\t\t\t\t'lidafdatum',\n\t\t\t\t$profiel->lidafdatum,\n\t\t\t\t'Lid-af sinds'\n\t\t\t);\n\t\t}\n\n\t\tif ($admin && !$inschrijven) {\n\t\t\t$fields[] = new VerticaleField(\n\t\t\t\t'verticale',\n\t\t\t\t$profiel->verticale,\n\t\t\t\t'Verticale'\n\t\t\t);\n\t\t\tif ($profiel->isLid()) {\n\t\t\t\t$fields[] = new JaNeeField(\n\t\t\t\t\t'verticaleleider',\n\t\t\t\t\t$profiel->verticaleleider,\n\t\t\t\t\t'Verticaleleider'\n\t\t\t\t);\n\t\t\t\t$fields[] = new JaNeeField(\n\t\t\t\t\t'kringcoach',\n\t\t\t\t\t$profiel->kringcoach,\n\t\t\t\t\t'Kringcoach'\n\t\t\t\t);\n\t\t\t}\n\t\t\t$fields[] = new LidField(\n\t\t\t\t'patroon',\n\t\t\t\t$profiel->patroon,\n\t\t\t\t'Patroon',\n\t\t\t\t'allepersonen'\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'profielOpties',\n\t\t\t\t$profiel->profielOpties,\n\t\t\t\t'Profielopties'\n\t\t\t);\n\t\t}\n\n\t\t$fields[] = new Subkopje('Persoonlijk');\n\t\t$fields[] = new TextField(\n\t\t\t'eetwens',\n\t\t\t$profiel->eetwens,\n\t\t\t'Dieet/voedselallergie'\n\t\t);\n\t\t$fields[] = new RequiredIntField(\n\t\t\t'lengte',\n\t\t\t(int) $profiel->lengte,\n\t\t\t'Lengte (cm)',\n\t\t\t50,\n\t\t\t250\n\t\t);\n\t\t$fields[] = new TextField('kerk', $profiel->kerk, 'Kerk', 50);\n\t\t$fields[] = new TextField(\n\t\t\t'muziek',\n\t\t\t$profiel->muziek,\n\t\t\t'Muziekinstrument',\n\t\t\t50\n\t\t);\n\t\t$fields[] = new SelectField('zingen', $profiel->zingen, 'Zingen', [\n\t\t\t'' => 'Kies...',\n\t\t\t'ja' => 'Ja, ik zing in een band/koor',\n\t\t\t'nee' => 'Nee, ik houd niet van zingen',\n\t\t\t'soms' => 'Alleen onder de douche',\n\t\t\t'anders' => 'Anders',\n\t\t]);\n\n\t\tif ($admin || $inschrijven || $novCie) {\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'vrienden',\n\t\t\t\t$profiel->vrienden,\n\t\t\t\t'Vrienden binnnen C.S.R.',\n\t\t\t\t300\n\t\t\t);\n\t\t\t$fields['middelbareSchool'] = new TextField(\n\t\t\t\t'middelbareSchool',\n\t\t\t\t$profiel->middelbareSchool,\n\t\t\t\t'Middelbare school',\n\t\t\t\t200\n\t\t\t);\n\t\t\t$fields['middelbareSchool']->required = $inschrijven;\n\t\t}\n\n\t\tif ($inschrijven) {\n\t\t\t// Zorg ervoor dat toestemming bij inschrijven wordt opgegeven.\n\t\t\t$fields[] = new Subkopje('Privacy');\n\t\t\t$fields[] = new HiddenField('toestemming_geven', 'true');\n\t\t\t$lidToestemmingRepository = ContainerFacade::getContainer()->get(\n\t\t\t\tLidToestemmingRepository::class\n\t\t\t);\n\t\t\t$fields = array_merge(\n\t\t\t\t$fields,\n\t\t\t\t(new ToestemmingModalForm($lidToestemmingRepository, true))->getFields()\n\t\t\t);\n\t\t}\n\n\t\t$fields[] = new Subkopje(\n\t\t\t'<b>Einde vragenlijst</b><br /><br /><br /><br /><br />'\n\t\t);\n\t\tif (\n\t\t\t($admin || $novCie) &&\n\t\t\t($profiel->propertyMogelijk('novitiaat') || $inschrijven)\n\t\t) {\n\t\t\t$fields[] = new CollapsableSubkopje('In te vullen door NovCie', true);\n\n\t\t\tif ($inschrijven) {\n\t\t\t\t// Alleen als inschrijven, anders bovenin voor admin\n\t\t\t\t$fields[] = new JaNeeField(\n\t\t\t\t\t'machtiging',\n\t\t\t\t\t$profiel->machtiging,\n\t\t\t\t\t'Machtiging getekend?'\n\t\t\t\t);\n\t\t\t}\n\t\t\t$fields[] = new JaNeeField(\n\t\t\t\t'toestemmingAfschrijven',\n\t\t\t\t$profiel->toestemmingAfschrijven,\n\t\t\t\t'Toestemming afschrijven?'\n\t\t\t);\n\n\t\t\t$fields['novitiaat'] = new TextareaField(\n\t\t\t\t'novitiaat',\n\t\t\t\t$profiel->novitiaat,\n\t\t\t\t'Wat verwacht Noviet van novitiaat?'\n\t\t\t);\n\t\t\t$fields['novitiaat']->required = $inschrijven;\n\t\t\t$fields['novietSoort'] = new SelectField(\n\t\t\t\t'novietSoort',\n\t\t\t\t$profiel->novietSoort,\n\t\t\t\t'Soort Noviet',\n\t\t\t\t['noviet', 'nanoviet']\n\t\t\t);\n\t\t\t$fields['novietSoort']->required = $inschrijven;\n\t\t\t$fields['matrixPlek'] = new SelectField(\n\t\t\t\t'matrixPlek',\n\t\t\t\t$profiel->matrixPlek,\n\t\t\t\t'Matrix plek',\n\t\t\t\t['voor', 'midden', 'achter']\n\t\t\t);\n\t\t\t$fields['matrixPlek']->required = $inschrijven;\n\t\t\t$fields['startkamp'] = new SelectField(\n\t\t\t\t'startkamp',\n\t\t\t\t$profiel->startkamp,\n\t\t\t\t'Startkamp',\n\t\t\t\t['ja', 'nee']\n\t\t\t);\n\t\t\t$fields['startkamp']->required = $inschrijven;\n\n\t\t\t$fields[] = new TextareaField(\n\t\t\t\t'novitiaatBijz',\n\t\t\t\t$profiel->novitiaatBijz,\n\t\t\t\t'Bijzonderheden novitiaat (op dag x ...)'\n\t\t\t);\n\t\t\t$fields[] = new TextareaField(\n\t\t\t\t'kgb',\n\t\t\t\t$profiel->kgb,\n\t\t\t\t'Overige NovCie-opmerking'\n\t\t\t);\n\n\t\t\t$fields[] = new Subkopje('Medisch');\n\t\t\t$fields[] = new TextareaField(\n\t\t\t\t'medisch',\n\t\t\t\t$profiel->medisch,\n\t\t\t\t'medisch (NB alleen als relevant voor hele NovCie, bijv. allergieen)'\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'huisarts',\n\t\t\t\t$profiel->huisarts,\n\t\t\t\t'Naam huisarts'\n\t\t\t);\n\t\t\t$fields[] = new TelefoonField(\n\t\t\t\t'huisartsTelefoon',\n\t\t\t\t$profiel->huisartsTelefoon,\n\t\t\t\t'Telefoonnummer'\n\t\t\t);\n\t\t\t$fields[] = new TextField(\n\t\t\t\t'huisartsPlaats',\n\t\t\t\t$profiel->huisartsPlaats,\n\t\t\t\t'Plaats'\n\t\t\t);\n\n\t\t\t$fields[] = new HtmlComment('</div>');\n\t\t}\n\t\t$fields[] = new FormDefaultKnoppen('/profiel/' . $profiel->uid);\n\n\t\t$this->addFields($fields);\n\t}", "smellKey": "S3776", "smellId": null, "repo": "csrdelft_csrdelft.nl", "language": "php"} {"function": "public function processForgot()\n {\n if (_PS_MODE_DEMO_) {\n $this->errors[] = Tools::displayError('This functionality has been disabled.');\n } elseif (!($email = trim(Tools::getValue('email_forgot')))) {\n $this->errors[] = Tools::displayError('Email is empty.');\n } elseif (!Validate::isEmail($email)) {\n $this->errors[] = Tools::displayError('Invalid email address.');\n } else {\n $employee = new Employee();\n if (!$employee->getByEmail($email) || !$employee) {\n $this->errors[] = Tools::displayError('This account does not exist.');\n } elseif ((strtotime($employee->last_passwd_gen.'+'.Configuration::get('PS_PASSWD_TIME_BACK').' minutes') - time()) > 0) {\n $this->errors[] = sprintf(\n Tools::displayError('You can regenerate your password only every %d minute(s)'),\n Configuration::get('PS_PASSWD_TIME_BACK')\n );\n }\n }\n\n if (!count($this->errors)) {\n $pwd = Tools::passwdGen(10, 'RANDOM');\n $employee->passwd = Tools::encrypt($pwd);\n $employee->last_passwd_gen = date('Y-m-d H:i:s', time());\n\n $params = array(\n '{email}' => $employee->email,\n '{lastname}' => $employee->lastname,\n '{firstname}' => $employee->firstname,\n '{passwd}' => $pwd\n );\n\n if (Mail::Send($employee->id_lang, 'employee_password', Mail::l('Your new password', $employee->id_lang), $params, $employee->email, $employee->firstname.' '.$employee->lastname)) {\n // Update employee only if the mail can be sent\n Shop::setContext(Shop::CONTEXT_SHOP, (int)min($employee->getAssociatedShops()));\n\n $result = $employee->update();\n if (!$result) {\n $this->errors[] = Tools::displayError('An error occurred while attempting to change your password.');\n } else {\n die(Tools::jsonEncode(array(\n 'hasErrors' => false,\n 'confirm' => $this->l('Your password has been emailed to you.', 'AdminTab', false, false)\n )));\n }\n } else {\n die(Tools::jsonEncode(array(\n 'hasErrors' => true,\n 'errors' => array(Tools::displayError('An error occurred while attempting to change your password.'))\n )));\n }\n } elseif (Tools::isSubmit('ajax')) {\n die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors)));\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "Howlscry_blmvuln", "language": "php"} {"function": "public function __construct($data = [])\n {\n if (is_array($data)) {\n if (isset($data['identifier'])) {\n if (is_array($data['identifier'])) {\n foreach ($data['identifier'] as $d) {\n $this->addIdentifier($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"identifier\" must be array of objects or null, ' . gettype($data['identifier']) . ' seen.');\n }\n }\n if (isset($data['active'])) {\n $this->setActive($data['active']);\n }\n if (isset($data['period'])) {\n $this->setPeriod($data['period']);\n }\n if (isset($data['practitioner'])) {\n $this->setPractitioner($data['practitioner']);\n }\n if (isset($data['organization'])) {\n $this->setOrganization($data['organization']);\n }\n if (isset($data['code'])) {\n if (is_array($data['code'])) {\n foreach ($data['code'] as $d) {\n $this->addCode($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"code\" must be array of objects or null, ' . gettype($data['code']) . ' seen.');\n }\n }\n if (isset($data['specialty'])) {\n if (is_array($data['specialty'])) {\n foreach ($data['specialty'] as $d) {\n $this->addSpecialty($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"specialty\" must be array of objects or null, ' . gettype($data['specialty']) . ' seen.');\n }\n }\n if (isset($data['location'])) {\n if (is_array($data['location'])) {\n foreach ($data['location'] as $d) {\n $this->addLocation($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"location\" must be array of objects or null, ' . gettype($data['location']) . ' seen.');\n }\n }\n if (isset($data['healthcareService'])) {\n if (is_array($data['healthcareService'])) {\n foreach ($data['healthcareService'] as $d) {\n $this->addHealthcareService($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"healthcareService\" must be array of objects or null, ' . gettype($data['healthcareService']) . ' seen.');\n }\n }\n if (isset($data['telecom'])) {\n if (is_array($data['telecom'])) {\n foreach ($data['telecom'] as $d) {\n $this->addTelecom($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"telecom\" must be array of objects or null, ' . gettype($data['telecom']) . ' seen.');\n }\n }\n if (isset($data['availableTime'])) {\n if (is_array($data['availableTime'])) {\n foreach ($data['availableTime'] as $d) {\n $this->addAvailableTime($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"availableTime\" must be array of objects or null, ' . gettype($data['availableTime']) . ' seen.');\n }\n }\n if (isset($data['notAvailable'])) {\n if (is_array($data['notAvailable'])) {\n foreach ($data['notAvailable'] as $d) {\n $this->addNotAvailable($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"notAvailable\" must be array of objects or null, ' . gettype($data['notAvailable']) . ' seen.');\n }\n }\n if (isset($data['availabilityExceptions'])) {\n $this->setAvailabilityExceptions($data['availabilityExceptions']);\n }\n if (isset($data['endpoint'])) {\n if (is_array($data['endpoint'])) {\n foreach ($data['endpoint'] as $d) {\n $this->addEndpoint($d);\n }\n } else {\n throw new \\InvalidArgumentException('\"endpoint\" must be array of objects or null, ' . gettype($data['endpoint']) . ' seen.');\n }\n }\n } elseif (null !== $data) {\n throw new \\InvalidArgumentException('$data expected to be array of values, saw \"' . gettype($data) . '\"');\n }\n parent::__construct($data);\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function xmlSerialize($returnSXE = false, $sxe = null)\n {\n if (null === $sxe) {\n $sxe = new \\SimpleXMLElement('<ChargeItem xmlns=\"http://hl7.org/fhir\"></ChargeItem>');\n }\n parent::xmlSerialize(true, $sxe);\n if (0 < count($this->identifier)) {\n foreach ($this->identifier as $identifier) {\n $identifier->xmlSerialize(true, $sxe->addChild('identifier'));\n }\n }\n if (0 < count($this->definitionUri)) {\n foreach ($this->definitionUri as $definitionUri) {\n $definitionUri->xmlSerialize(true, $sxe->addChild('definitionUri'));\n }\n }\n if (0 < count($this->definitionCanonical)) {\n foreach ($this->definitionCanonical as $definitionCanonical) {\n $definitionCanonical->xmlSerialize(true, $sxe->addChild('definitionCanonical'));\n }\n }\n if (isset($this->status)) {\n $this->status->xmlSerialize(true, $sxe->addChild('status'));\n }\n if (0 < count($this->partOf)) {\n foreach ($this->partOf as $partOf) {\n $partOf->xmlSerialize(true, $sxe->addChild('partOf'));\n }\n }\n if (isset($this->code)) {\n $this->code->xmlSerialize(true, $sxe->addChild('code'));\n }\n if (isset($this->subject)) {\n $this->subject->xmlSerialize(true, $sxe->addChild('subject'));\n }\n if (isset($this->context)) {\n $this->context->xmlSerialize(true, $sxe->addChild('context'));\n }\n if (isset($this->occurrenceDateTime)) {\n $this->occurrenceDateTime->xmlSerialize(true, $sxe->addChild('occurrenceDateTime'));\n }\n if (isset($this->occurrencePeriod)) {\n $this->occurrencePeriod->xmlSerialize(true, $sxe->addChild('occurrencePeriod'));\n }\n if (isset($this->occurrenceTiming)) {\n $this->occurrenceTiming->xmlSerialize(true, $sxe->addChild('occurrenceTiming'));\n }\n if (0 < count($this->performer)) {\n foreach ($this->performer as $performer) {\n $performer->xmlSerialize(true, $sxe->addChild('performer'));\n }\n }\n if (isset($this->performingOrganization)) {\n $this->performingOrganization->xmlSerialize(true, $sxe->addChild('performingOrganization'));\n }\n if (isset($this->requestingOrganization)) {\n $this->requestingOrganization->xmlSerialize(true, $sxe->addChild('requestingOrganization'));\n }\n if (isset($this->costCenter)) {\n $this->costCenter->xmlSerialize(true, $sxe->addChild('costCenter'));\n }\n if (isset($this->quantity)) {\n $this->quantity->xmlSerialize(true, $sxe->addChild('quantity'));\n }\n if (0 < count($this->bodysite)) {\n foreach ($this->bodysite as $bodysite) {\n $bodysite->xmlSerialize(true, $sxe->addChild('bodysite'));\n }\n }\n if (isset($this->factorOverride)) {\n $this->factorOverride->xmlSerialize(true, $sxe->addChild('factorOverride'));\n }\n if (isset($this->priceOverride)) {\n $this->priceOverride->xmlSerialize(true, $sxe->addChild('priceOverride'));\n }\n if (isset($this->overrideReason)) {\n $this->overrideReason->xmlSerialize(true, $sxe->addChild('overrideReason'));\n }\n if (isset($this->enterer)) {\n $this->enterer->xmlSerialize(true, $sxe->addChild('enterer'));\n }\n if (isset($this->enteredDate)) {\n $this->enteredDate->xmlSerialize(true, $sxe->addChild('enteredDate'));\n }\n if (0 < count($this->reason)) {\n foreach ($this->reason as $reason) {\n $reason->xmlSerialize(true, $sxe->addChild('reason'));\n }\n }\n if (0 < count($this->service)) {\n foreach ($this->service as $service) {\n $service->xmlSerialize(true, $sxe->addChild('service'));\n }\n }\n if (isset($this->productReference)) {\n $this->productReference->xmlSerialize(true, $sxe->addChild('productReference'));\n }\n if (isset($this->productCodeableConcept)) {\n $this->productCodeableConcept->xmlSerialize(true, $sxe->addChild('productCodeableConcept'));\n }\n if (0 < count($this->account)) {\n foreach ($this->account as $account) {\n $account->xmlSerialize(true, $sxe->addChild('account'));\n }\n }\n if (0 < count($this->note)) {\n foreach ($this->note as $note) {\n $note->xmlSerialize(true, $sxe->addChild('note'));\n }\n }\n if (0 < count($this->supportingInformation)) {\n foreach ($this->supportingInformation as $supportingInformation) {\n $supportingInformation->xmlSerialize(true, $sxe->addChild('supportingInformation'));\n }\n }\n if ($returnSXE) {\n return $sxe;\n }\n return $sxe->saveXML();\n }", "smellKey": "S3776", "smellId": null, "repo": "achibear_openemr", "language": "php"} {"function": "public function getCacheTags(Model\\Document\\PageSnippet $ownerDocument, array $tags = []): array\n {\n $image = $this->getImage();\n\n if ($image instanceof Asset) {\n if (!array_key_exists($image->getCacheTag(), $tags)) {\n $tags = $image->getCacheTags($tags);\n }\n }\n\n $getMetaDataCacheTags = function ($data, $tags) {\n if (!is_array($data)) {\n return $tags;\n }\n\n foreach ($data as $element) {\n if (array_key_exists('data', $element) && is_array($element['data']) && count($element['data']) > 0) {\n foreach ($element['data'] as $metaData) {\n if ($metaData instanceof Element\\Data\\MarkerHotspotItem) {\n $metaData = get_object_vars($metaData);\n }\n\n if ($metaData['value'] instanceof Element\\ElementInterface) {\n if (!array_key_exists($metaData['value']->getCacheTag(), $tags)) {\n $tags = $metaData['value']->getCacheTags($tags);\n }\n }\n }\n }\n }\n\n return $tags;\n };\n\n $tags = $getMetaDataCacheTags($this->marker, $tags);\n $tags = $getMetaDataCacheTags($this->hotspots, $tags);\n\n return $tags;\n }", "smellKey": "S3776", "smellId": null, "repo": "pimcore_pimcore", "language": "php"} {"function": "public function execute()\n {\n if ($this->processed) {\n return;\n }\n\n $this->pixie->session->get();\n if ($this->pixie->getParameter('parameters.use_external_dir')) {\n if ($this->removeOld) {\n if ($this->modifyUser) {\n $this->user->photo = '';\n }\n }\n\n if ($this->picture->isLoaded()) {\n $uploadDir = $this->pixie->getParameter('parameters.user_pictures_external_dir');\n $uploadPath = $uploadDir . \"/sess_\".session_id().\"_uploadto\";\n if (!file_exists($uploadPath) || !is_dir($uploadPath)) {\n mkdir($uploadPath, 0777, true);\n }\n $photoName = $this->generatePhotoName($this->picture);\n\n if ($this->pixie->getParameter('parameters.use_perl_upload')) {\n $scriptName = $this->pixie->isWindows() ? 'uploadwin.pl' : 'uploadux.pl';\n $headers = $this->picture->upload('http' . ($_SERVER['HTTPS'] == 'on' ? 's' : '') . '://'\n . $_SERVER['HTTP_HOST'] . '/upload/' . $scriptName, $photoName);\n\n if ($headers['X-Created-Filename']) {\n /** @var File $newFile */\n $newFile = $this->pixie->orm->get('file');\n $newFile->path = $headers['X-Created-Filename'];\n $newFile->user_id = $this->user->id();\n $newFile->save();\n $this->result = $newFile->id();\n if ($this->modifyUser) {\n $this->user->photo = $newFile->id();\n }\n }\n\n } else {\n $uniqueUploadPath = $uploadPath . '/' . substr(sha1(time() . $this->picture->getName()), 0, 2);\n if (!file_exists($uniqueUploadPath) || !is_dir($uniqueUploadPath)) {\n mkdir($uniqueUploadPath, 0777, true);\n }\n $newPhotoPath = $uniqueUploadPath.'/'.$photoName;\n $this->picture->move($newPhotoPath);\n /** @var File $newFile */\n $newFile = $this->pixie->orm->get('file');\n $newFile->path = $newPhotoPath;\n $newFile->user_id = $this->user->id();\n $newFile->save();\n $this->result = $newFile->id();\n if ($this->modifyUser) {\n $this->user->photo = $newFile->id();\n }\n }\n }\n\n } else {\n $relativePath = $this->pixie->getParameter('parameters.user_pictures_path');\n $pathDelimiter = preg_match('|^[/\\\\\\\\]|', $relativePath) ? '' : DIRECTORY_SEPARATOR;\n $photoPath = preg_replace('#/+$#i', '', $this->pixie->root_dir) . $pathDelimiter . $relativePath;\n\n if ($this->removeOld && $this->user->photo && file_exists($photoPath . $this->user->photo)) {\n unlink($photoPath . $this->user->photo);\n if ($this->modifyUser) {\n $this->user->photo = '';\n }\n }\n\n if ($this->picture->isLoaded()) {\n if ($this->user->photo && file_exists($photoPath . $this->user->photo)) {\n unlink($photoPath . $this->user->photo);\n }\n\n $photoName = $this->generatePhotoName($this->picture);\n $uniquePhotoDirName = substr(sha1(time() . $this->picture->getName()), 0, 2);\n $uniquePhotoDir = $photoPath . $uniquePhotoDirName;\n if (!file_exists($uniquePhotoDir) || !is_dir($uniquePhotoDir)) {\n mkdir($uniquePhotoDir, 0777, true);\n }\n $this->picture->move($uniquePhotoDir . '/' . $photoName);\n $uniquePhotoName = $uniquePhotoDirName . '/' . $photoName;\n $this->result = $uniquePhotoName;\n if ($this->modifyUser) {\n $this->user->photo = $uniquePhotoName;\n }\n }\n }\n $this->processed = true;\n }", "smellKey": "S3776", "smellId": null, "repo": "lefos-og_hackazon", "language": "php"} {"function": "private function loadActorsForRules(array &$input, array &$unchanged, array &$toclean_postrules): void\n {\n $usertypes = [\n CommonITILActor::ASSIGN => 'assign',\n CommonITILActor::REQUESTER => 'requester',\n CommonITILActor::OBSERVER => 'observer'\n ];\n foreach ($usertypes as $k => $t) {\n //handle new input\n if (isset($input['_itil_' . $t]) && isset($input['_itil_' . $t]['_type'])) {\n // FIXME Deprecate these keys in GLPI 11.0.\n $field = $input['_itil_' . $t]['_type'] . 's_id';\n if (\n isset($input['_itil_' . $t][$field])\n && !isset($input[$field . '_' . $t])\n ) {\n $input['_' . $field . '_' . $t][] = $input['_itil_' . $t][$field];\n $toclean_postrules['_' . $field . '_' . $t][] = $input['_itil_' . $t][$field];\n }\n }\n\n //handle existing actors: load all existing actors from ticket\n //to make sure business rules will receive all information, and not just\n //what have been entered in the html form.\n $existing_actors = [\n User::class => $this->getUsers($k),\n Group::class => $this->getGroups($k),\n Supplier::class => $this->getSuppliers($k),\n ];\n foreach ($existing_actors as $actor_itemtype => $actors) {\n $field = getForeignKeyFieldForItemType($actor_itemtype);\n $input_key = '_' . $field . '_' . $t;\n $deleted_key = $input_key . '_deleted';\n $deleted_actors = array_key_exists($deleted_key, $input) && is_array($input[$deleted_key]) ? array_column($input[$deleted_key], 'items_id') : [];\n $tmp_input = $input[$input_key] ?? [];\n if (!is_array($tmp_input)) {\n $tmp_input = [$tmp_input];\n }\n $added_actors = array_diff($tmp_input, array_column($actors, $field));\n if (empty($added_actors) && empty($deleted_actors)) {\n $unchanged[] = $input_key;\n }\n foreach ($actors as $actor) {\n if (\n !isset($input[$input_key])\n || (is_array($input[$input_key]) && !in_array($actor[$field], $input[$input_key]))\n || (is_numeric($input[$input_key]) && $actor[$field] !== $input[$input_key])\n ) {\n if (\n !array_key_exists($input_key, $input)\n || (!is_array($input[$input_key]) && !is_numeric($input[$input_key]) && empty($input[$input_key]))\n ) {\n $input[$input_key] = [];\n } elseif (!is_array($input[$input_key])) {\n $input[$input_key] = [$input[$input_key]];\n }\n if (!in_array($actor[$field], $deleted_actors)) {\n $input[$input_key][] = $actor[$field];\n $toclean_postrules[$input_key][] = $actor[$field];\n }\n }\n }\n }\n }\n }", "smellKey": "S3776", "smellId": null, "repo": "glpi-project_glpi", "language": "php"} {"function": "def test_update_illumina_sequencing_run_has_backup(store_with_illumina_sequencing_data: Store):\n # GIVEN a store with Illumina Sequencing Runs that have backup status False\n sequencing_run: IlluminaSequencingRun = store_with_illumina_sequencing_data._get_query(\n IlluminaSequencingRun\n ).all()[0]\n assert sequencing_run.has_backup is False\n\n # WHEN updating the backup status of a sequencing run\n store_with_illumina_sequencing_data.update_illumina_sequencing_run_has_backup(\n sequencing_run=sequencing_run, has_backup=True\n )\n\n # THEN the backup status of the sequencing run is updated\n assert sequencing_run.has_backup is True", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_remove_ozone_sensors(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n mock_accuweather_client: AsyncMock,\n) -> None:\n \"\"\"Test remove ozone sensors from registry.\"\"\"\n entity_registry.async_get_or_create(\n SENSOR_PLATFORM,\n DOMAIN,\n \"0123456-ozone-0\",\n suggested_object_id=\"home_ozone_0d\",\n disabled_by=None,\n )\n\n await init_integration(hass)\n\n entry = entity_registry.async_get(\"sensor.home_ozone_0d\")\n assert entry is None", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_nodeports_auto_updates(\n mock_db_manager: Callable,\n default_configuration: dict[str, Any],\n user_id: int,\n project_id: str,\n node_uuid: str,\n auto_update: bool,\n):\n db_manager = mock_db_manager(default_configuration)\n\n original_inputs = create_valid_port_mapping(InputsList, suffix=\"original\")\n original_outputs = create_valid_port_mapping(OutputsList, suffix=\"original\")\n\n updated_inputs = create_valid_port_mapping(InputsList, suffix=\"updated\")\n updated_outputs = create_valid_port_mapping(OutputsList, suffix=\"updated\")\n\n async def mock_save_db_cb(*args, **kwargs):\n pass\n\n async def mock_node_port_creator_cb(*args, **kwargs):\n return Nodeports(\n inputs=updated_inputs,\n outputs=updated_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=False,\n )\n\n node_ports = Nodeports(\n inputs=original_inputs,\n outputs=original_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=auto_update,\n )\n\n assert node_ports.internal_inputs == original_inputs\n assert node_ports.internal_outputs == original_outputs\n\n # this triggers an auto_update if auto_update is True\n node_inputs = await node_ports.inputs\n assert node_inputs == updated_inputs if auto_update else original_inputs\n node_outputs = await node_ports.outputs\n assert node_outputs == updated_outputs if auto_update else original_outputs", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def store_sequencing_data_in_housekeeper(\n self,\n run_directory_data: IlluminaRunDirectoryData,\n store: Store,\n ) -> None:\n \"\"\"Store fastq files, demux logs and run parameters for sequencing run in Housekeeper.\"\"\"\n LOG.info(f\"Add sequencing and demux data to Housekeeper for run {run_directory_data.id}\")\n\n self.hk_api.add_bundle_and_version_if_non_existent(run_directory_data.id)\n tags: list[str] = [\n SequencingFileTag.FASTQ,\n SequencingFileTag.RUN_PARAMETERS,\n run_directory_data.id,\n ]\n self.hk_api.add_tags_if_non_existent(tags)\n add_sample_fastq_files_to_housekeeper(\n run_directory_data=run_directory_data, hk_api=self.hk_api, store=store\n )\n store_undetermined_fastq_files(\n run_directory_data=run_directory_data, hk_api=self.hk_api, store=store\n )\n add_demux_logs_to_housekeeper(\n run_directory_data=run_directory_data,\n hk_api=self.hk_api,\n )\n add_run_parameters_file_to_housekeeper(\n run_directory_data=run_directory_data,\n hk_api=self.hk_api,\n )", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def store_housekeeper(context: CGConfig, case_id: str, dry_run: bool, force: bool) -> None:\n \"\"\"\n Store a finished NF-analysis in Housekeeper.\n\n Raises:\n click.Abort: If an error occurs while storing a case bundle in Housekeeper.\n \"\"\"\n analysis_api: NfAnalysisAPI = context.meta_apis[MetaApis.ANALYSIS_API]\n try:\n analysis_api.store_analysis_housekeeper(case_id=case_id, dry_run=dry_run, force=force)\n except HousekeeperStoreError as error:\n LOG.error(f\"Could not store bundle in Housekeeper and StatusDB: {error}!\")\n raise click.Abort()", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_make_items_product_specific():\n rule = ssg.build_yaml.Rule(\"something\")\n\n rule.identifiers = {\n \"cce@rhel7\": \"CCE-27445-6\",\n \"cce@rhel8\": \"CCE-80901-2\",\n }\n\n rule.template = TEST_TEMPLATE_DICT.copy()\n\n rule.normalize(\"rhel7\")\n assert \"cce@rhel7\" not in rule.identifiers\n assert \"cce@rhel8\" not in rule.identifiers\n assert rule.identifiers[\"cce\"] == \"CCE-27445-6\"\n\n assert \"filesystem@rhel7\" not in rule.template[\"vars\"]\n assert rule.template[\"vars\"][\"filesystem\"] == \"\"\n assert \"anaconda@rhel7\" not in rule.template[\"backends\"]\n assert not rule.template[\"backends\"][\"anaconda\"]\n\n rule.identifiers = {\n \"cce\": \"CCE-27100-7\",\n \"cce@rhel7\": \"CCE-27445-6\",\n }\n with pytest.raises(Exception) as exc:\n rule.normalize(\"rhel7\")\n assert \"'cce'\" in str(exc)\n assert \"identifiers\" in str(exc)\n\n rule.identifiers = {\n \"cce@rhel7\": \"CCE-27445-6\",\n \"cce\": \"CCE-27445-6\",\n }\n rule.normalize(\"rhel7\")\n assert \"cce@rhel7\" not in rule.identifiers\n assert rule.identifiers[\"cce\"] == \"CCE-27445-6\"\n\n rule.references = {\n \"stigid@rhel7\": \"RHEL-07-040370\",\n \"stigid\": \"tralala\",\n }\n with pytest.raises(ValueError) as exc:\n rule.make_refs_and_identifiers_product_specific(\"rhel7\")\n assert \"stigid\" in str(exc)\n\n rule.references = {\n \"stigid@rhel7\": \"RHEL-07-040370\",\n }\n rule.normalize(\"rhel7\")\n assert rule.references[\"stigid\"] == \"RHEL-07-040370\"\n\n rule.references = {\n \"stigid@rhel7\": \"RHEL-07-040370\",\n }\n rule.template = TEST_TEMPLATE_DICT.copy()\n\n assert \"filesystem@rhel8\" not in rule.template[\"vars\"]\n assert rule.template[\"vars\"][\"filesystem\"] == \"tmpfs\"\n assert \"anaconda@rhel8\" not in rule.template[\"backends\"]\n assert rule.template[\"backends\"][\"anaconda\"]\n\n rule.references = {\n \"stigid@rhel8\": \"RHEL-08-020012,RHEL-08-020013\",\n }\n rule.normalize(\"rhel8\")\n assert rule.references[\"stigid\"] == \"RHEL-08-020012,RHEL-08-020013\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def assign_bom_items(apps, schema_editor):\n \"\"\"\n Run through existing BuildItem objects,\n and assign a matching BomItem\n \"\"\"\n\n BuildItem = apps.get_model('build', 'builditem')\n BomItem = apps.get_model('part', 'bomitem')\n Part = apps.get_model('part', 'part')\n\n count_valid = 0\n count_total = 0\n\n for build_item in BuildItem.objects.all(): # pragma: no cover\n\n # Try to find a BomItem which matches the BuildItem\n # Note: Before this migration, variant stock assignment was not allowed,\n # so BomItem lookup should be pretty easy\n\n if count_total == 0:\n # First time around\n logger.info(\"Assigning BomItems to existing BuildItem objects\")\n\n count_total += 1\n\n try:\n bom_item = BomItem.objects.get(\n part__id=build_item.build.part.pk,\n sub_part__id=build_item.stock_item.part.pk,\n )\n\n build_item.bom_item = bom_item\n build_item.save()\n\n count_valid += 1\n\n except BomItem.DoesNotExist:\n pass\n\n if count_total > 0: # pragma: no cover\n logger.info(f\"Assigned BomItem for {count_valid}/{count_total} entries\")", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "async def test_async_extract_config_entry_ids(hass: HomeAssistant) -> None:\n \"\"\"Test we can find devices that have no entities.\"\"\"\n\n device_no_entities = dr.DeviceEntry(id=\"device-no-entities\", config_entries={\"abc\"})\n\n call = ServiceCall(\n \"homeassistant\",\n \"reload_config_entry\",\n {\n \"device_id\": \"device-no-entities\",\n },\n )\n\n mock_device_registry(\n hass,\n {\n device_no_entities.id: device_no_entities,\n },\n )\n\n assert await service.async_extract_config_entry_ids(hass, call) == {\"abc\"}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_light_color_temp_legacy(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a legacy light entity that does supports color temp.\"\"\"\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153.846161,\n max_mireds=370.370361,\n supported_color_modes=[\n LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n ],\n legacy_supports_brightness=True,\n legacy_supports_color_temperature=True,\n )\n ]\n states = [\n LightState(\n key=1,\n state=True,\n brightness=100,\n red=1,\n green=1,\n blue=1,\n white=1,\n cold_white=1,\n color_temperature=153.846161,\n color_mode=19,\n )\n ]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n attributes = state.attributes\n\n assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP\n assert attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.COLOR_TEMP]\n assert attributes[ATTR_MIN_MIREDS] == 153\n assert attributes[ATTR_MAX_MIREDS] == 370\n\n assert attributes[ATTR_MIN_COLOR_TEMP_KELVIN] == 2700\n assert attributes[ATTR_MAX_COLOR_TEMP_KELVIN] == 6500\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_OFF,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls([call(key=1, state=False)])\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_user_by_email_returns_none_for_nonexisting_email(\n store_with_users: Store, non_existent_email: str\n):\n \"\"\"Test getting user by email when the email does not exist.\"\"\"\n\n # GIVEN a non-existing email\n\n # WHEN retrieving the user by email\n filtered_user: User = store_with_users.get_user_by_email(email=non_existent_email)\n\n # THEN no user should be returned\n assert filtered_user is None", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_deep_mixed_backward(self):\n self.assertQuerySetEqual(\n Contact.objects.filter(customer__address=self.address),\n [self.contact1.id],\n attrgetter(\"id\"),\n )", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def escape_special_chars(text, table=_escape_table):\n \"\"\"Escape & and < for Pango Markup.\"\"\"\n return text.translate(table)", "smellKey": "0", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def test_write_buffer_set_bit_x2_big_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.BIG_ENDIAN)\n wb.write_bit(True)\n wb.write_bit(True)\n ba: memoryview = wb.get_bytes()\n assert b\"\\xc0\" == ba.tobytes()", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def get_obj_conf(cluster_id, service_id):\n cluster = check_obj(Cluster, cluster_id)\n if service_id:\n service = check_obj(ClusterObject, {\"cluster\": cluster, \"id\": service_id})\n obj = service\n else:\n obj = cluster\n\n if not obj:\n raise AdcmEx(\"CONFIG_NOT_FOUND\", \"this object has no config\")\n if not obj.config:\n raise AdcmEx(\"CONFIG_NOT_FOUND\", \"this object has no config\")\n\n return obj", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('gen_email', 'custom')\n op.drop_column('client_user', 'name')\n op.drop_column('client_user', 'default_avatar')\n # ### end Alembic commands ###", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def glibc_version_string_confstr() -> Optional[str]:\n \"Primary implementation of glibc_version_string using os.confstr.\"\n # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n # to be broken or missing. This strategy is used in the standard library\n # platform module:\n # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183\n if sys.platform == \"win32\":\n return None\n try:\n gnu_libc_version = os.confstr(\"CS_GNU_LIBC_VERSION\")\n if gnu_libc_version is None:\n return None\n # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\":\n _, version = gnu_libc_version.split()\n except (AttributeError, OSError, ValueError):\n # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n return None\n return version", "smellKey": "0", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "async def test_hardware_info(\n hass: HomeAssistant, hass_ws_client: WebSocketGenerator\n) -> None:\n \"\"\"Test we can get the board info.\"\"\"\n mock_integration(hass, MockModule(\"hassio\"))\n await async_setup_component(hass, HASSIO_DOMAIN, {})\n\n # Setup the config entry\n config_entry = MockConfigEntry(\n data={},\n domain=DOMAIN,\n options={},\n title=\"Hardkernel\",\n )\n config_entry.add_to_hass(hass)\n with patch(\n \"homeassistant.components.hardkernel.get_os_info\",\n return_value={\"board\": \"odroid-n2\"},\n ):\n assert await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n client = await hass_ws_client(hass)\n\n with patch(\n \"homeassistant.components.hardkernel.hardware.get_os_info\",\n return_value={\"board\": \"odroid-n2\"},\n ):\n await client.send_json({\"id\": 1, \"type\": \"hardware/info\"})\n msg = await client.receive_json()\n\n assert msg[\"id\"] == 1\n assert msg[\"success\"]\n assert msg[\"result\"] == {\n \"hardware\": [\n {\n \"board\": {\n \"hassio_board_id\": \"odroid-n2\",\n \"manufacturer\": \"hardkernel\",\n \"model\": \"odroid-n2\",\n \"revision\": None,\n },\n \"config_entries\": [config_entry.entry_id],\n \"dongle\": None,\n \"name\": \"Home Assistant Blue / Hardkernel ODROID-N2/N2+\",\n \"url\": None,\n }\n ]\n }", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_is_case_down_sampled_true(base_store: Store, case: Case, sample_id: str):\n \"\"\"Tests the down sampling check when all samples are down sampled.\"\"\"\n # GIVEN a case where all samples are down sampled\n for sample in case.samples:\n sample.from_sample = sample_id\n base_store.session.commit()\n\n # WHEN checking if all sample in the case are down sampled\n is_down_sampled: bool = base_store.is_case_down_sampled(case_id=case.internal_id)\n\n # THEN the return value should be True\n assert is_down_sampled", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_call_no_context_target_specific(\n hass: HomeAssistant, mock_handle_entity_call, mock_entities\n) -> None:\n \"\"\"Check we can target specified entities.\"\"\"\n await service.entity_service_call(\n hass,\n mock_entities,\n Mock(),\n ServiceCall(\n \"test_domain\",\n \"test_service\",\n {\"entity_id\": [\"light.kitchen\", \"light.non-existing\"]},\n ),\n )\n\n assert len(mock_handle_entity_call.mock_calls) == 1\n assert mock_handle_entity_call.mock_calls[0][1][1].entity_id == \"light.kitchen\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_project_directories(project_id: str, directory: Path) -> list[str]:\n return [sub_dir for sub_dir in os.listdir(directory) if sub_dir.startswith(project_id)]", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Create the switches for the Ring devices.\"\"\"\n ring_data: RingData = hass.data[DOMAIN][config_entry.entry_id]\n devices_coordinator = ring_data.devices_coordinator\n\n async_add_entities(\n SirenSwitch(device, devices_coordinator)\n for device in ring_data.devices.stickup_cams\n if device.has_capability(\"siren\")\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def report_deliver(context: CGConfig, case_id: str, dry_run: bool, force: bool) -> None:\n \"\"\"\n Create a Housekeeper deliverables file for a given case ID.\n\n Raises:\n click.Abort: If an error occurs during the deliverables report generation or validation.\n \"\"\"\n analysis_api: NfAnalysisAPI = context.meta_apis[MetaApis.ANALYSIS_API]\n try:\n analysis_api.report_deliver(case_id=case_id, dry_run=dry_run, force=force)\n except CgError as error:\n LOG.error(f\"Could not create report file: {error}\")\n raise click.Abort()", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_write_buffer_get_bytes(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(10, ByteOrder.LITTLE_ENDIAN)\n ba: memoryview = wb.get_bytes()\n assert 10 == ba.nbytes", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "async def test_light_rgbww_with_cold_warm_white_support(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a generic RGBWW light entity with cold warm white support.\"\"\"\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153,\n max_mireds=400,\n supported_color_modes=[\n LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n ],\n )\n ]\n states = [\n LightState(\n key=1,\n state=True,\n color_brightness=1,\n brightness=100,\n red=1,\n green=1,\n blue=1,\n warm_white=1,\n cold_white=1,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n )\n ]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.RGBWW]\n assert state.attributes[ATTR_COLOR_MODE] == ColorMode.RGBWW\n assert state.attributes[ATTR_RGBWW_COLOR] == (255, 255, 255, 255, 255)\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_BRIGHTNESS: 127},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n brightness=pytest.approx(0.4980392156862745),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {\n ATTR_ENTITY_ID: \"light.test_mylight\",\n ATTR_BRIGHTNESS: 127,\n ATTR_HS_COLOR: (100, 100),\n },\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_brightness=1.0,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n cold_white=0,\n warm_white=0,\n rgb=(pytest.approx(0.32941176470588235), 1.0, 0.0),\n brightness=pytest.approx(0.4980392156862745),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_RGB_COLOR: (255, 255, 255)},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_brightness=pytest.approx(0.4235294117647059),\n cold_white=1,\n warm_white=1,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n rgb=(0, pytest.approx(0.5462962962962963), 1.0),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_RGBW_COLOR: (255, 255, 255, 255)},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_brightness=pytest.approx(0.4235294117647059),\n cold_white=1,\n warm_white=1,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n rgb=(0, pytest.approx(0.5462962962962963), 1.0),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {\n ATTR_ENTITY_ID: \"light.test_mylight\",\n ATTR_RGBWW_COLOR: (255, 255, 255, 255, 255),\n },\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_brightness=1,\n cold_white=1,\n warm_white=1,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n rgb=(1, 1, 1),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_COLOR_TEMP_KELVIN: 2500},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_brightness=0,\n cold_white=0,\n warm_white=100,\n color_mode=LightColorCapability.RGB\n | LightColorCapability.WHITE\n | LightColorCapability.COLOR_TEMPERATURE\n | LightColorCapability.COLD_WARM_WHITE\n | LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n rgb=(0, 0, 0),\n )\n ]\n )\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def add_credential(self, credential):\n with suppress(exc.NoContent):\n self.related.credentials.post(dict(id=credential.id, associate=True))", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def test_light_legacy_white_converted_to_brightness(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a generic light entity that only supports legacy white.\"\"\"\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153,\n max_mireds=400,\n supported_color_modes=[\n LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n | LightColorCapability.WHITE\n ],\n )\n ]\n states = [LightState(key=1, state=True, brightness=100)]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n | LightColorCapability.WHITE,\n )\n ]\n )\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def download_file(self, filename, prefix):\n \"\"\"Function to `download`(copy) a file to a temporary firectory.\"\"\"\n url = os.path.join(prefix, filename)\n\n response = self.client.get(url)\n\n here = os.path.abspath(os.path.dirname(__file__))\n\n output_dir = os.path.join(here, '..', '..', 'js_tmp')\n\n output_dir = os.path.abspath(output_dir)\n\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n output_file = os.path.join(output_dir, filename)\n\n with open(output_file, 'wb') as output:\n output.write(response.content)", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def wallet(self) -> BaseWallet:\n \"\"\"Get the `BaseWallet` implementation (helper specific to in-memory profile).\"\"\"\n return self._context.inject(BaseWallet)", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "async def async_unlock(self, **kwargs: Any) -> None:\n \"\"\"Send the unlock command.\"\"\"\n _LOGGER.debug(\"Unlocking doors for: %s\", self.car_name)\n await async_call_remote_service(\n self.controller,\n SERVICE_UNLOCK,\n self.vehicle_info,\n UNLOCK_VALID_DOORS[UNLOCK_DOOR_ALL],\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def batch_request(data_asset: DataAsset) -> BatchRequest:\n \"\"\"Build a BatchRequest depending on the types of Data Assets tested in the module.\"\"\"\n return data_asset.build_batch_request()", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_do_activationkey_enable_noargs(self, shell):\n \"\"\"\n Test do_activationkey_enable command triggers help on no args.\n \"\"\"\n shell.help_activationkey_enable = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_enable(shell, \"\")\n assert shell.help_activationkey_enable.called\n assert not shell.client.activationkey.setDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_is_case_down_sampled_false(base_store: Store, case: Case, sample_id: str):\n \"\"\"Tests the down sampling check when none of the samples are down sampled.\"\"\"\n # GIVEN a case where all samples are not down sampled\n for sample in case.samples:\n assert not sample.from_sample\n\n # WHEN checking if all sample in the case are down sampled\n is_down_sampled: bool = base_store.is_case_down_sampled(case_id=case.internal_id)\n\n # THEN the return value should be False\n assert not is_down_sampled", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def _handle_coordinator_update(self) -> None:\n \"\"\"Handle updated data from the coordinator.\"\"\"\n self._update_from_coordinator()\n super()._handle_coordinator_update()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_unique_name_creation_and_removal(faker: Faker):\n unique_volume_name = DynamicSidecarVolumesPathsResolver.source(\n path=Path(\"/some/random/path/to/a/workspace/folder\"),\n node_uuid=faker.uuid4(cast_to=None),\n run_id=RunID.create(),\n )\n\n await assert_creation_and_removal(unique_volume_name)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_do_activationkey_enableconfigdeployment_noargs(self, shell):\n \"\"\"\n Test activationkey_enableconfigdeployment command is invoking help message on insufficient arguments.\n \"\"\"\n shell.help_activationkey_enableconfigdeployment = MagicMock()\n shell.client.activationkey.enableConfigDeployment = MagicMock()\n\n spacecmd.activationkey.do_activationkey_enableconfigdeployment(shell, \"\")\n assert shell.help_activationkey_enableconfigdeployment.called\n assert not shell.client.activationkey.enableConfigDeployment.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def _clone(self, g):\n if isinstance(g, GEOM_PTR):\n return capi.geom_clone(g)\n else:\n return capi.geom_clone(g.ptr)", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def mock_freedompro_put_state():\n \"\"\"Mock freedompro put_state.\"\"\"\n with patch(\"homeassistant.components.freedompro.light.put_state\"):\n yield", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def set_plan_for_user(user: User, plan: SLPlan, partner: Partner):\n partner_user = PartnerUser.get_by(partner_id=partner.id, user_id=user.id)\n if partner_user is None:\n return\n return set_plan_for_partner_user(partner_user, plan)", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def test_capture_respx_api_server(params: tuple[str, Path, str]):\n _, openapi_path, example = params\n assert _DUMMY_API_SERVER_OPENAPI.is_file()\n openapi_spec: dict[str, Any] = jsonref.loads(_DUMMY_API_SERVER_OPENAPI.read_text())\n url_path: PathDescription = _determine_path(\n openapi_spec=openapi_spec, response_path=openapi_path\n )\n path_pattern = str(openapi_path)\n for p in url_path.path_parameters:\n path_pattern = path_pattern.replace(\"{\" + p.name + \"}\", p.respx_lookup)\n\n def side_effect(request, **kwargs):\n return httpx.Response(status_code=200, json=kwargs)\n\n my_route = respx.get(url__regex=\"https://example.org\" + path_pattern).mock(\n side_effect=side_effect\n )\n response = httpx.get(\"https://example.org\" + example)\n assert my_route.called\n assert response.status_code == 200\n assert all(param.name in response.json() for param in url_path.path_parameters)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def send_confirmation_mail(self, request, emailconfirmation, signup):\n current_site = get_current_site(request)\n\n activate_url = self.get_email_confirmation_url(\n request,\n emailconfirmation)\n\n ctx = {\n \"activate_url\": activate_url,\n \"current_site\": current_site,\n \"key\": emailconfirmation.key,\n }\n\n email_template = 'mail/email_confirmation'\n\n self.send_mail(email_template,\n emailconfirmation.email_address.email,\n ctx)", "smellKey": "0", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def is_spotify_media_type(media_content_type: str) -> bool:\n \"\"\"Return whether the media_content_type is a valid Spotify media_id.\"\"\"\n return media_content_type.startswith(MEDIA_PLAYER_PREFIX)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def delete_dynamic_service(\n self,\n *,\n node_id: NodeID,\n simcore_user_agent: str,\n save_state: bool,\n timeout: datetime.timedelta,\n ) -> Response:\n @retry_on_errors(total_retry_timeout_overwrite=timeout.total_seconds())\n @expect_status(status.HTTP_204_NO_CONTENT)\n async def _(\n self, # NOTE: required by retry_on_errors\n ) -> Response:\n headers = {X_SIMCORE_USER_AGENT: simcore_user_agent}\n\n return cast(\n Response,\n await self.client.delete(\n f\"dynamic_services/{node_id}?can_save={f'{save_state}'.lower()}\",\n headers=headers,\n timeout=timeout.total_seconds(),\n follow_redirects=True,\n ),\n )\n\n return await _(self)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_do_activationkey_clone_noargs_to_clone(self, shell):\n \"\"\"\n Test do_activationkey_clone no arguments to a clone name passed to the arguments.\n \"\"\"\n shell.do_activationkey_list = MagicMock(return_value=[\"key_some_clone_name\"])\n shell.help_activationkey_clone = MagicMock()\n shell.export_activationkey_getdetails = MagicMock()\n shell.list_base_channels = MagicMock()\n shell.list_child_channels = MagicMock()\n shell.do_configchannel_list = MagicMock()\n shell.import_activtionkey_fromdetails = MagicMock()\n\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n ret = spacecmd.activationkey.do_activationkey_clone(shell, \"-c key_clone_name\")\n\n assert logger.error.called\n assert shell.help_activationkey_clone.called\n assert shell.do_activationkey_list.called\n assert not shell.export_activationkey_getdetails.called\n assert not shell.list_base_channels.called\n assert not shell.list_child_channels.called\n assert not shell.do_configchannel_list.called\n assert not shell.import_activtionkey_fromdetails.called\n assert logger.error.call_args_list[0][0][0] == \"Error no activationkey to clone passed!\"\n assert ret is 1", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def async_close_cover(self, **kwargs: Any) -> None:\n \"\"\"Close the cover.\"\"\"\n await self._channel.close()\n self._assumed_closed = True", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_case_with_name_does_not_exist(\n store_with_case_and_sample_with_reads: Store,\n):\n # GIVEN a store with a case\n\n # WHEN checking if a case that is not in the store exists\n does_exist: bool = store_with_case_and_sample_with_reads.case_with_name_exists(\n case_name=\"does_not_exist\",\n )\n # THEN the case does not exist\n assert not does_exist", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def _media_type(self, media_path: Any = None) -> Any:\n \"\"\"Get media Type.\"\"\"\n (media_type, _) = mimetypes.guess_type(media_path)\n\n return media_type", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def subgraph_get_2_hop_edges(ctx: mgp.ProcCtx, vertex: mgp.Vertex) -> mgp.Record(edge=mgp.Edge):\n out_edges = vertex.out_edges\n records = []\n for edge in out_edges:\n vertex = edge.to_vertex\n properties = vertex.properties\n print(properties)\n records.extend([mgp.Record(edge=edge) for edge in edge.to_vertex.out_edges])\n return records", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def _pandas(cls, column, **kwargs):\n return column.apply(lambda x: is_valid_dash_address(x))", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(\n self,\n hass: HomeAssistant,\n session: ClientSession,\n api_key: str,\n latitude: float,\n longitude: float,\n update_interval: timedelta,\n use_nearest: bool,\n ) -> None:\n \"\"\"Initialize.\"\"\"\n self.latitude = latitude\n self.longitude = longitude\n # Currently, Airly only supports Polish and English\n language = \"pl\" if hass.config.language == \"pl\" else \"en\"\n self.airly = Airly(api_key, session, language=language)\n self.use_nearest = use_nearest\n\n super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_node_ports_v2_packages(\n mock_db_manager: Callable,\n default_configuration: dict[str, Any],\n user_id: int,\n project_id: str,\n node_uuid: str,\n):\n db_manager = mock_db_manager(default_configuration)\n node_ports = await ports(user_id, project_id, node_uuid)\n node_ports = await ports(user_id, project_id, node_uuid, db_manager=db_manager)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def async_browse_media_applications(self, expanded):\n \"\"\"Return application media objects.\"\"\"\n if expanded:\n children = [\n BrowseMedia(\n title=application[\"label\"],\n media_class=MediaClass.APP,\n media_content_id=application_id,\n media_content_type=MediaType.APP,\n can_play=True,\n can_expand=False,\n thumbnail=self.get_browse_image_url(\n MediaType.APP, application_id, media_image_id=None\n ),\n )\n for application_id, application in self._tv.applications.items()\n ]\n else:\n children = None\n\n return BrowseMedia(\n title=\"Applications\",\n media_class=MediaClass.DIRECTORY,\n media_content_id=\"applications\",\n media_content_type=MediaType.APPS,\n children_media_class=MediaClass.APP,\n can_play=False,\n can_expand=True,\n children=children,\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_addchildchannels_args(self, shell):\n \"\"\"\n Test \"addchildchannels\" method calls \"addChildChannels\" API call.\n \"\"\"\n shell.help_activationkey_addchildchannels = MagicMock()\n shell.client.activationkey.addChildChannels = MagicMock()\n\n spacecmd.activationkey.do_activationkey_addchildchannels(shell, \"key some_channel\")\n assert not shell.help_activationkey_addchildchannels.called\n assert shell.client.activationkey.addChildChannels.called\n session, fun, args = shell.client.activationkey.addChildChannels.call_args_list[0][0]\n assert session == shell.session\n assert fun == \"key\"\n assert isinstance(args, list)\n assert len(args) == 1\n assert args == ['some_channel']", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_setup_entry_no_options(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n config_entry_mock: MockConfigEntry,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test async_setup_entry creates a DlnaDmrEntity when no options are set.\n\n Check that the device is constructed properly as part of the test.\n \"\"\"\n config_entry_mock.add_to_hass(hass)\n hass.config_entries.async_update_entry(config_entry_mock, options={})\n mock_entity_id = await setup_mock_component(hass, config_entry_mock)\n await async_update_entity(hass, mock_entity_id)\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n\n # Check device was created from the supplied URL\n domain_data_mock.upnp_factory.async_create_device.assert_awaited_once_with(\n MOCK_DEVICE_LOCATION\n )\n # Check event notifiers are acquired\n domain_data_mock.async_get_event_notifier.assert_awaited_once_with(\n EventListenAddr(LOCAL_IP, 0, None), hass\n )\n # Check UPnP services are subscribed\n dmr_device_mock.async_subscribe_services.assert_awaited_once_with(\n auto_resubscribe=True\n )\n assert dmr_device_mock.on_event is not None\n # Check SSDP notifications are registered\n ssdp_scanner_mock.async_register_callback.assert_any_call(\n ANY, {\"USN\": MOCK_DEVICE_USN}\n )\n ssdp_scanner_mock.async_register_callback.assert_any_call(\n ANY, {\"_udn\": MOCK_DEVICE_UDN, \"NTS\": \"ssdp:byebye\"}\n )\n # Quick check of the state to verify the entity has a connected DmrDevice\n assert mock_state.state == MediaPlayerState.IDLE\n # Check the name matches that supplied\n assert mock_state.name == MOCK_DEVICE_NAME\n\n # Check that an update retrieves state from the device, but does not ping,\n # because poll_availability is False\n await async_update_entity(hass, mock_entity_id)\n dmr_device_mock.async_update.assert_awaited_with(do_ping=False)\n\n # Unload config entry to clean up\n assert await hass.config_entries.async_remove(config_entry_mock.entry_id) == {\n \"require_restart\": False\n }\n\n # Confirm SSDP notifications unregistered\n assert ssdp_scanner_mock.async_register_callback.return_value.call_count == 2\n\n # Confirm the entity has disconnected from the device\n domain_data_mock.async_release_event_notifier.assert_awaited_once()\n dmr_device_mock.async_unsubscribe_services.assert_awaited_once()\n assert dmr_device_mock.on_event is None\n # Entity should be removed by the cleanup\n assert hass.states.get(mock_entity_id) is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def cancel_payment(\n app: FastAPI,\n *,\n payment_id: PaymentID,\n user_id: UserID,\n wallet_id: WalletID,\n) -> None:\n\n with log_context(\n _logger,\n logging.INFO,\n \"Cancel payment in %s\",\n f\"{wallet_id=}\",\n extra=get_log_record_extra(user_id=user_id),\n ):\n await payments.cancel_one_time_payment(\n gateway=PaymentsGatewayApi.get_from_app_state(app),\n repo=PaymentsTransactionsRepo(db_engine=app.state.engine),\n payment_id=payment_id,\n user_id=user_id,\n wallet_id=wallet_id,\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_invalid_vulnerability_report():\n exc = InvalidVulnerabilityReportError(\"error string\", \"reason\")\n\n assert str(exc) == \"error string\"\n assert exc.reason == \"reason\"", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "async def _make_entry() -> None:\n task_uid = await task_tracker.get_new_unique_identifier()\n await task_tracker.save(task_uid, task_schedule)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_location_info_with_partial(self, db_request):\n db_request.ip_address.geoip_info = {\"country_code3\": \"USA\"}\n\n organization = DBOrganizationFactory.create()\n organization.record_event(\n tag=\"\",\n request=db_request,\n additional={},\n )\n\n event = organization.events[0]\n\n assert event.additional == {\n \"organization_name\": organization.name,\n \"geoip_info\": {\"country_code3\": \"USA\"},\n }\n assert event.location_info == db_request.ip_address", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def extra_state_attributes(self) -> dict[str, Any]:\n \"\"\"Return the device-specific state attributes.\"\"\"\n return {ATTR_NUMBER: self._index}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_serialize_rule():\n filename = PROJECT_ROOT + \"/linux_os/guide/system/accounts/accounts-restrictions/password_storage/no_empty_passwords/rule.yml\"\n rule_ds = ssg.build_yaml.Rule.from_yaml(filename)\n rule_as_dict = rule_ds.represent_as_dict()\n\n with tempfile.NamedTemporaryFile(\"w+\", delete=True) as f:\n yaml.dump(rule_as_dict, f)\n rule_ds_reloaded = ssg.build_yaml.Rule.from_yaml(f.name)\n\n reloaded_dict = rule_ds_reloaded.represent_as_dict()\n\n # Those two should be really equal if there are no jinja macros in the rule def.\n assert rule_as_dict == reloaded_dict", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def link(self) -> Optional[Link]:\n return self._link", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def test_iid_storage_filename(\n hass: HomeAssistant, iid_storage, hass_storage: dict[str, Any]\n) -> None:\n \"\"\"Test iid storage uses the expected filename.\"\"\"\n entry = MockConfigEntry(domain=DOMAIN)\n\n iid_storage = AccessoryIIDStorage(hass, entry.entry_id)\n await iid_storage.async_initialize()\n assert iid_storage.store.path.endswith(\n get_iid_storage_filename_for_entry_id(entry.entry_id)\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_blueprint_inputs(blueprint_2: models.Blueprint) -> None:\n \"\"\"Test blueprint inputs.\"\"\"\n inputs = models.BlueprintInputs(\n blueprint_2,\n {\n \"use_blueprint\": {\n \"path\": \"bla\",\n \"input\": {\"test-input\": 1, \"test-input-default\": 12},\n },\n \"example-default\": {\"overridden\": \"via-config\"},\n },\n )\n inputs.validate()\n assert inputs.inputs == {\"test-input\": 1, \"test-input-default\": 12}\n assert inputs.async_substitute() == {\n \"example\": 1,\n \"example-default\": {\"overridden\": \"via-config\"},\n }", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def app(self) -> web.Application:\n return self._app", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def test_sensor_off(hass: HomeAssistant, load_yaml_integration: None) -> None:\n \"\"\"Test setting the state with a template.\"\"\"\n\n entity_state = hass.states.get(\"binary_sensor.test\")\n assert entity_state\n assert entity_state.state == STATE_OFF", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def url_to_path(url: str) -> str:\n \"\"\"\n Convert a file: URL to a path.\n \"\"\"\n assert url.startswith(\n \"file:\"\n ), f\"You can only turn file: urls into filenames (not {url!r})\"\n\n _, netloc, path, _, _ = urllib.parse.urlsplit(url)\n\n if not netloc or netloc == \"localhost\":\n # According to RFC 8089, same as empty authority.\n netloc = \"\"\n elif WINDOWS:\n # If we have a UNC path, prepend UNC share notation.\n netloc = \"\\\\\\\\\" + netloc\n else:\n raise ValueError(\n f\"non-local file URIs are not supported on this platform: {url!r}\"\n )\n\n path = urllib.request.url2pathname(netloc + path)\n\n # On Windows, urlsplit parses the path as something like \"/C:/Users/foo\".\n # This creates issues for path-related functions like io.open(), so we try\n # to detect and strip the leading slash.\n if (\n WINDOWS\n and not netloc # Not UNC.\n and len(path) >= 3\n and path[0] == \"/\" # Leading slash to strip.\n and path[1] in string.ascii_letters # Drive letter.\n and path[2:4] in (\":\", \":/\") # Colon + end of string, or colon + absolute path.\n ):\n path = path[1:]\n\n return path", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n check_custom_perm(request.user, \"view_host_components_of\", \"cluster\", cluster, \"view_hostcomponent\")\n hostcomponent = self.filter_queryset(\n queryset=self.get_queryset().prefetch_related(\"service\", \"component\", \"host\").filter(cluster=cluster)\n )\n if self._is_for_ui():\n ui_hc = HostComponent()\n ui_hc.hc = hostcomponent # because pylint disable invalid-name not working here somehow\n serializer = self.get_serializer(ui_hc, context={\"request\": request, \"cluster\": cluster})\n else:\n serializer = self.get_serializer(hostcomponent, many=True)\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def test_session(\n cls,\n settings: Mapping[str, Any] = None,\n bind: Mapping[Type, Any] = None,\n profile_class: Optional[Any] = None,\n ) -> \"InMemoryProfileSession\":\n \"\"\"Used in tests to quickly create InMemoryProfileSession.\"\"\"\n if profile_class is not None:\n test_profile = cls.test_profile(profile_class=profile_class)\n else:\n test_profile = cls.test_profile()\n session = InMemoryProfileSession(test_profile, settings=settings)\n session._active = True\n session._init_context()\n if bind:\n for k, v in bind.items():\n if v:\n session.context.injector.bind_instance(k, v)\n else:\n session.context.injector.clear_binding(k)\n return session", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def release_url(self) -> str | None:\n \"\"\"URL to the full release notes of the latest version available.\"\"\"\n return self.coordinator.release_url", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_check_activationkey_correct_key(self, shell):\n \"\"\"\n Test check activation key helper returns True if a key is correct.\n \"\"\"\n shell.is_activationkey = MagicMock(return_value=True)\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n assert spacecmd.activationkey.check_activationkey(shell, \"some_not_a_key\")\n assert not logger.error.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def _recovery_after_reauth_failure_works(\n hass: HomeAssistant, mock_fibaro_client: Mock, result: FlowResult\n) -> None:\n mock_fibaro_client.connect.side_effect = None\n mock_fibaro_client.connect.return_value = True\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={CONF_PASSWORD: \"other_fake_password\"},\n )\n\n assert result[\"type\"] is FlowResultType.ABORT\n assert result[\"reason\"] == \"reauth_successful\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def async_added_to_hass(self) -> None:\n \"\"\"Handle entity which will be added.\"\"\"\n LOGGER.info(\"Restoring entity %s\", self.name)\n\n last_state = await self.async_get_last_state()\n if last_state is not None:\n self.last_state = last_state\n self.last_state_attributes = self.last_state.attributes\n self._preset_modes = cast(\n list, self.last_state.attributes.get(\"preset_modes\")\n )\n\n last_extra_data = await self.async_get_last_extra_data()\n if last_extra_data is not None:\n self._last_target_temp = last_extra_data.as_dict()[\"last_target_temp\"]\n\n await super().async_added_to_hass()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_listconfigchannels_noargs(self, shell):\n \"\"\"\n Test listconfigchannels command triggers help on no args\n \"\"\"\n shell.help_activationkey_listconfigchannels = MagicMock()\n shell.client.activationkey.listConfigChannels = MagicMock()\n\n spacecmd.activationkey.do_activationkey_listconfigchannels(shell, \"\")\n assert shell.help_activationkey_listconfigchannels.called\n assert not shell.client.activationkey.listConfigChannels.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_port_forwarding_switches(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n aioclient_mock: AiohttpClientMocker,\n mock_unifi_websocket,\n websocket_mock,\n) -> None:\n \"\"\"Test control of UniFi port forwarding.\"\"\"\n _data = {\n \"_id\": \"5a32aa4ee4b0412345678911\",\n \"dst_port\": \"12345\",\n \"enabled\": True,\n \"fwd_port\": \"23456\",\n \"fwd\": \"10.0.0.2\",\n \"name\": \"plex\",\n \"pfwd_interface\": \"wan\",\n \"proto\": \"tcp_udp\",\n \"site_id\": \"5a32aa4ee4b0412345678910\",\n \"src\": \"any\",\n }\n config_entry = await setup_unifi_integration(\n hass, aioclient_mock, port_forward_response=[_data.copy()]\n )\n\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n\n ent_reg_entry = entity_registry.async_get(\"switch.unifi_network_plex\")\n assert ent_reg_entry.unique_id == \"port_forward-5a32aa4ee4b0412345678911\"\n assert ent_reg_entry.entity_category is EntityCategory.CONFIG\n\n # Validate state object\n switch_1 = hass.states.get(\"switch.unifi_network_plex\")\n assert switch_1 is not None\n assert switch_1.state == STATE_ON\n assert switch_1.attributes.get(ATTR_DEVICE_CLASS) == SwitchDeviceClass.SWITCH\n\n # Update state object\n data = _data.copy()\n data[\"enabled\"] = False\n mock_unifi_websocket(message=MessageKey.PORT_FORWARD_UPDATED, data=data)\n await hass.async_block_till_done()\n assert hass.states.get(\"switch.unifi_network_plex\").state == STATE_OFF\n\n # Disable port forward\n aioclient_mock.clear_requests()\n aioclient_mock.put(\n f\"https://{config_entry.data[CONF_HOST]}:1234\"\n f\"/api/s/{config_entry.data[CONF_SITE_ID]}/rest/portforward/{data['_id']}\",\n )\n\n await hass.services.async_call(\n SWITCH_DOMAIN,\n \"turn_off\",\n {\"entity_id\": \"switch.unifi_network_plex\"},\n blocking=True,\n )\n assert aioclient_mock.call_count == 1\n data = _data.copy()\n data[\"enabled\"] = False\n assert aioclient_mock.mock_calls[0][2] == data\n\n # Enable port forward\n await hass.services.async_call(\n SWITCH_DOMAIN,\n \"turn_on\",\n {\"entity_id\": \"switch.unifi_network_plex\"},\n blocking=True,\n )\n assert aioclient_mock.call_count == 2\n assert aioclient_mock.mock_calls[1][2] == _data\n\n # Availability signalling\n\n # Controller disconnects\n await websocket_mock.disconnect()\n assert hass.states.get(\"switch.unifi_network_plex\").state == STATE_UNAVAILABLE\n\n # Controller reconnects\n await websocket_mock.reconnect()\n assert hass.states.get(\"switch.unifi_network_plex\").state == STATE_OFF\n\n # Remove entity on deleted message\n mock_unifi_websocket(message=MessageKey.PORT_FORWARD_DELETED, data=_data)\n await hass.async_block_till_done()\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_create_job(\n auth: httpx.BasicAuth,\n client: httpx.AsyncClient,\n solver_key: str,\n solver_version: str,\n mocked_backend_services_apis_for_create_and_delete_solver_job: MockedBackendApiDict,\n hidden: bool,\n parent_project_id: UUID | None,\n parent_node_id: UUID | None,\n):\n\n mock_webserver_router = (\n mocked_backend_services_apis_for_create_and_delete_solver_job[\"webserver\"]\n )\n assert mock_webserver_router is not None\n callback = mock_webserver_router[\"create_projects\"].side_effect\n assert callback is not None\n\n def create_project_side_effect(request: httpx.Request):\n # check `hidden` bool\n query = dict(elm.split(\"=\") for elm in request.url.query.decode().split(\"&\"))\n _hidden = query.get(\"hidden\")\n assert _hidden == (\"true\" if hidden else \"false\")\n\n # check parent project and node id\n if parent_project_id is not None:\n assert f\"{parent_project_id}\" == dict(request.headers).get(\n X_SIMCORE_PARENT_PROJECT_UUID.lower()\n )\n if parent_node_id is not None:\n assert f\"{parent_node_id}\" == dict(request.headers).get(\n X_SIMCORE_PARENT_NODE_ID.lower()\n )\n return callback(request)\n\n mock_webserver_router[\"create_projects\"].side_effect = create_project_side_effect\n\n # create Job\n header_dict = {}\n if parent_project_id is not None:\n header_dict[X_SIMCORE_PARENT_PROJECT_UUID] = f\"{parent_project_id}\"\n if parent_node_id is not None:\n header_dict[X_SIMCORE_PARENT_NODE_ID] = f\"{parent_node_id}\"\n resp = await client.post(\n f\"/{API_VTAG}/solvers/{solver_key}/releases/{solver_version}/jobs\",\n auth=auth,\n params={\"hidden\": f\"{hidden}\"},\n headers=header_dict,\n json=JobInputs(\n values={\n \"x\": 3.14,\n \"n\": 42,\n }\n ).dict(),\n )\n assert resp.status_code == status.HTTP_201_CREATED\n job = Job.parse_obj(resp.json())", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def as_short_dict(self) -> dict[str, Any]:\n \"\"\"Return a brief dictionary version of this ActionTrace.\"\"\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_get_orders_empty_store(store: Store):\n # GIVEN a store without any orders\n\n # WHEN fetching orders\n orders, total = store.get_orders(OrdersRequest())\n\n # THEN none should be returned\n assert not orders\n assert not total", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_group_addsystems_ssm_no_systems(self, shell):\n \"\"\"\n Test do_group_addsystems with SSM argument, without systems.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_addsystems = MagicMock()\n shell.get_system_id = MagicMock()\n shell.expand_systems = MagicMock()\n shell.client.systemgroup.addOrRemoveSystems = MagicMock()\n shell.ssm.keys = MagicMock(return_value=[])\n mprint = MagicMock()\n logger = MagicMock()\n with patch(\"spacecmd.group.print\", mprint) as prn, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_addsystems(shell, \"groupname ssm\")\n\n assert not shell.get_system_id.called\n assert not shell.expand_systems.called\n assert not shell.client.systemgroup.addOrRemoveSystems.called\n assert not mprint.called\n assert not logger.error.called\n assert not shell.help_group_addsystems.called\n assert shell.ssm.keys.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def async_get_config_entry_diagnostics(\n hass: HomeAssistant, config_entry: ConfigEntry\n) -> dict[str, dict[str, Any]]:\n \"\"\"Return diagnostics for a config entry.\"\"\"\n data = {\"config_entry\": async_redact_data(config_entry.as_dict(), TO_REDACT)}\n\n plenticore: Plenticore = hass.data[DOMAIN][config_entry.entry_id]\n\n # Get information from Kostal Plenticore library\n available_process_data = await plenticore.client.get_process_data()\n available_settings_data = await plenticore.client.get_settings()\n data[\"client\"] = {\n \"version\": str(await plenticore.client.get_version()),\n \"me\": str(await plenticore.client.get_me()),\n \"available_process_data\": available_process_data,\n \"available_settings_data\": {\n module_id: [str(setting) for setting in settings]\n for module_id, settings in available_settings_data.items()\n },\n }\n\n device_info = {**plenticore.device_info}\n device_info[ATTR_IDENTIFIERS] = REDACTED # contains serial number\n data[\"device\"] = device_info\n\n return data", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_addentitlements_help_args(self, shell):\n \"\"\"\n Test addentitlements method call shows help if only one argument is passed.\n \"\"\"\n shell.help_activationkey_addentitlements = MagicMock()\n shell.client.activationkey.addEntitlements = MagicMock()\n\n spacecmd.activationkey.do_activationkey_addentitlements(shell, \"key\")\n assert shell.help_activationkey_addentitlements.called\n assert not shell.client.activationkey.addEntitlements.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def assert_balances(node, mine, margin=0.001):\n '''Make assertions about a node's getbalances output'''\n got = node.getbalances()[\"mine\"]\n for k,v in mine.items():\n assert_approx(got[k], v, margin)", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "async def test_node_ports_set_file_by_keymap(\n mock_db_manager: Callable,\n default_configuration: dict[str, Any],\n user_id: int,\n project_id: str,\n node_uuid: str,\n mock_upload_path: MockFixture,\n):\n db_manager = mock_db_manager(default_configuration)\n\n original_inputs = create_valid_port_mapping(InputsList, suffix=\"original\")\n original_outputs = create_valid_port_mapping(\n OutputsList, suffix=\"original\", file_to_key=Path(__file__).name\n )\n\n async def mock_save_db_cb(*args, **kwargs):\n pass\n\n async def mock_node_port_creator_cb(*args, **kwargs):\n return Nodeports(\n inputs=original_inputs,\n outputs=original_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=False,\n )\n\n node_ports = Nodeports(\n inputs=original_inputs,\n outputs=original_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=False,\n )\n\n await node_ports.set_file_by_keymap(Path(__file__))\n\n with pytest.raises(exceptions.PortNotFound):\n await node_ports.set_file_by_keymap(Path(\"/whatever/file/that/is/invalid\"))", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def __init__(self, data: dict[str, Any]) -> None:\n \"\"\"Restore from dict.\"\"\"\n extended_dict = data[\"extended_dict\"]\n short_dict = data[\"short_dict\"]\n context = Context(\n user_id=extended_dict[\"context\"][\"user_id\"],\n parent_id=extended_dict[\"context\"][\"parent_id\"],\n id=extended_dict[\"context\"][\"id\"],\n )\n self.context = context\n self.key = f\"{extended_dict['domain']}.{extended_dict['item_id']}\"\n self.run_id = extended_dict[\"run_id\"]\n self._dict = extended_dict\n self._short_dict = short_dict", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def highlight(code, lexer, formatter, outfile=None):\n \"\"\"\n This is the most high-level highlighting function. It combines `lex` and\n `format` in one function.\n \"\"\"\n return format(lex(code, lexer), formatter, outfile)", "smellKey": "0", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "async def test_config_auth_failed(hass: HomeAssistant) -> None:\n \"\"\"Test for setup failure if the auth fails.\"\"\"\n entry = MockConfigEntry(\n domain=DOMAIN,\n title=\"10.10.2.3\",\n unique_id=\"aa:bb:cc:dd:ee:ff\",\n data={\"host\": \"10.10.2.3\"},\n )\n entry.add_to_hass(hass)\n\n with patch(\n \"homeassistant.components.nam.NettigoAirMonitor.async_check_credentials\",\n side_effect=AuthFailedError(\"Authorization has failed\"),\n ):\n await hass.config_entries.async_setup(entry.entry_id)\n assert entry.state is ConfigEntryState.SETUP_ERROR", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_clone_keyargs_to_clone_filtered(self, shell):\n \"\"\"\n Test do_activationkey_clone filtered out keys.\n \"\"\"\n shell.do_activationkey_list = MagicMock(return_value=[\"key_some_clone_name\"])\n shell.help_activationkey_clone = MagicMock()\n shell.export_activationkey_getdetails = MagicMock()\n shell.list_base_channels = MagicMock()\n shell.list_child_channels = MagicMock()\n shell.do_configchannel_list = MagicMock()\n shell.import_activtionkey_fromdetails = MagicMock()\n\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n ret = spacecmd.activationkey.do_activationkey_clone(shell, \"orig_key -c key_clone_name\")\n\n assert not logger.error.called\n assert not shell.help_activationkey_clone.called\n assert shell.do_activationkey_list.called\n assert not shell.export_activationkey_getdetails.called\n assert not shell.list_base_channels.called\n assert not shell.list_child_channels.called\n assert not shell.do_configchannel_list.called\n assert not shell.import_activtionkey_fromdetails.called\n\n expectations = [\n \"Got args=['orig_key'] 1\",\n \"Filtered akeys []\",\n \"all akeys ['key_some_clone_name']\",\n ]\n for idx, call in enumerate(logger.debug.call_args_list):\n assert call[0][0] == expectations[idx]", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_update_interval(\n hass: HomeAssistant,\n mock_accuweather_client: AsyncMock,\n freezer: FrozenDateTimeFactory,\n) -> None:\n \"\"\"Test correct update interval.\"\"\"\n entry = await init_integration(hass)\n\n assert entry.state is ConfigEntryState.LOADED\n\n assert mock_accuweather_client.async_get_current_conditions.call_count == 1\n assert mock_accuweather_client.async_get_daily_forecast.call_count == 1\n\n freezer.tick(UPDATE_INTERVAL_OBSERVATION)\n async_fire_time_changed(hass)\n await hass.async_block_till_done()\n\n assert mock_accuweather_client.async_get_current_conditions.call_count == 2\n\n freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)\n async_fire_time_changed(hass)\n await hass.async_block_till_done()\n\n assert mock_accuweather_client.async_get_daily_forecast.call_count == 2", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def entry(hass):\n \"\"\"Mock config entry added to HA.\"\"\"\n entry = MockConfigEntry(domain=DOMAIN, data={\"host\": \"1.2.3.4\"})\n entry.add_to_hass(hass)\n return entry", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_switch_state(\n hass: HomeAssistant,\n snapshot: SnapshotAssertion,\n config_entry: MockConfigEntry,\n device_registry: dr.DeviceRegistry,\n entity_registry: er.EntityRegistry,\n requests_mock: requests_mock.Mocker,\n device_name: str,\n) -> None:\n \"\"\"Test the resulting setup state is as expected for the platform.\"\"\"\n\n # Configure the API devices call for device_name\n mock_devices_response(requests_mock, device_name)\n\n # setup platform - only including the named device\n await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n # Check device registry\n devices = dr.async_entries_for_config_entry(device_registry, config_entry.entry_id)\n assert devices == snapshot(name=\"devices\")\n\n # Check entity registry\n entities = [\n entity\n for entity in er.async_entries_for_config_entry(\n entity_registry, config_entry.entry_id\n )\n if entity.domain == SWITCH_DOMAIN\n ]\n assert entities == snapshot(name=\"entities\")\n\n # Check states\n for entity in entities:\n assert hass.states.get(entity.entity_id) == snapshot(name=entity.entity_id)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_fieldset(self):\n class TestForm(Form):\n template_name = \"forms_tests/use_fieldset.html\"\n field = CharField(widget=self.widget)\n\n form = TestForm()\n self.assertIs(self.widget.use_fieldset, False)\n self.assertHTMLEqual(\n '<div><label for=\"id_field\">Field:</label>'\n '<input id=\"id_field\" max=\"12345\" min=\"1234\" '\n 'name=\"field\" required step=\"9999\" type=\"number\"></div>',\n form.render(),\n )", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_do_activationkey_fromdetails_cfgdeploy(self, shell):\n \"\"\"\n Test import_activationkey_fromdetails configuration deployment was set.\n \"\"\"\n shell.client.activationkey.create = MagicMock(return_value={\"name\": \"whatever\"})\n shell.do_activationkey_list = MagicMock(return_value=[\"some_existing_key\"])\n shell.client.activationkey.addChildChannels = MagicMock()\n shell.client.activationkey.enableConfigDeployment = MagicMock()\n shell.client.activationkey.disableConfigDeployment = MagicMock()\n shell.client.activationkey.addConfigChannels = MagicMock()\n shell.client.activationkey.addServerGroups = MagicMock()\n shell.client.activationkey.addPackages = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock(return_value=None)\n shell.client.systemgroup.create = MagicMock(\n side_effect=[\n {\"id\": 1},\n {\"id\": 2},\n {\"id\": 3},\n ]\n )\n\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n ret = spacecmd.activationkey.import_activationkey_fromdetails(\n shell,\n {\n \"key\": \"somekey\",\n \"usage_limit\": 42,\n \"base_channel_label\": \"none\",\n \"description\": \"Key description\",\n \"entitlements\": [\"one\", \"two\", \"three\"],\n \"universal_default\": True,\n \"child_channel_labels\": \"child_channel_labels\",\n \"config_channels\": [\"config_channel\"],\n \"server_groups\": [\"one\", \"two\", \"three\"],\n \"packages\": [\"emacs\"],\n \"config_deploy\": 1,\n }\n )\n assert shell.client.activationkey.enableConfigDeployment.called\n assert not shell.client.activationkey.disableConfigDeployment.called\n session, keydata = shell.client.activationkey.enableConfigDeployment.call_args_list[0][0]\n assert shell.session == session\n assert keydata == shell.client.activationkey.create()", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_dpi_switches_add_second_app(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, mock_unifi_websocket\n) -> None:\n \"\"\"Test the update_items function with some clients.\"\"\"\n await setup_unifi_integration(\n hass,\n aioclient_mock,\n dpigroup_response=DPI_GROUPS,\n dpiapp_response=DPI_APPS,\n )\n\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n assert hass.states.get(\"switch.block_media_streaming\").state == STATE_ON\n\n second_app_event = {\n \"apps\": [524292],\n \"blocked\": False,\n \"cats\": [],\n \"enabled\": False,\n \"log\": False,\n \"site_id\": \"name\",\n \"_id\": \"61783e89c1773a18c0c61f00\",\n }\n mock_unifi_websocket(message=MessageKey.DPI_APP_ADDED, data=second_app_event)\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.block_media_streaming\").state == STATE_ON\n\n add_second_app_to_group = {\n \"_id\": \"5f976f4ae3c58f018ec7dff6\",\n \"name\": \"Block Media Streaming\",\n \"site_id\": \"name\",\n \"dpiapp_ids\": [\"5f976f62e3c58f018ec7e17d\", \"61783e89c1773a18c0c61f00\"],\n }\n mock_unifi_websocket(\n message=MessageKey.DPI_GROUP_UPDATED, data=add_second_app_to_group\n )\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.block_media_streaming\").state == STATE_OFF\n\n second_app_event_enabled = {\n \"apps\": [524292],\n \"blocked\": False,\n \"cats\": [],\n \"enabled\": True,\n \"log\": False,\n \"site_id\": \"name\",\n \"_id\": \"61783e89c1773a18c0c61f00\",\n }\n mock_unifi_websocket(\n message=MessageKey.DPI_APP_UPDATED, data=second_app_event_enabled\n )\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.block_media_streaming\").state == STATE_ON", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_banner_str_method(self):\n test_banner = Banner(title=\"Test banner\")\n self.assertEqual(str(test_banner), test_banner.title)", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "async def test_reauth_connect_failure(\n hass: HomeAssistant,\n mock_config_entry: MockConfigEntry,\n mock_fibaro_client: Mock,\n) -> None:\n \"\"\"Successful reauth flow initialized by the user.\"\"\"\n result = await mock_config_entry.start_reauth_flow(hass)\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] == {}\n\n mock_fibaro_client.connect.side_effect = Exception()\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={CONF_PASSWORD: \"other_fake_password\"},\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] == {\"base\": \"cannot_connect\"}\n\n await _recovery_after_reauth_failure_works(hass, mock_fibaro_client, result)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_play_media_no_autoplay(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test play_media with autoplay=False.\"\"\"\n # play_media performs a few calls to the device for setup and play\n dmr_device_mock.can_stop = True\n dmr_device_mock.transport_state = TransportState.STOPPED\n await hass.services.async_call(\n MP_DOMAIN,\n mp_const.SERVICE_PLAY_MEDIA,\n {\n ATTR_ENTITY_ID: mock_entity_id,\n mp_const.ATTR_MEDIA_CONTENT_TYPE: MediaType.MUSIC,\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"http://198.51.100.20:8200/MediaItems/17621.mp3\"\n ),\n mp_const.ATTR_MEDIA_ENQUEUE: False,\n mp_const.ATTR_MEDIA_EXTRA: {\"autoplay\": False},\n },\n blocking=True,\n )\n\n dmr_device_mock.construct_play_media_metadata.assert_awaited_once_with(\n media_url=\"http://198.51.100.20:8200/MediaItems/17621.mp3\",\n media_title=\"Home Assistant\",\n override_upnp_class=\"object.item.audioItem.musicTrack\",\n meta_data={},\n )\n dmr_device_mock.async_stop.assert_awaited_once_with()\n dmr_device_mock.async_set_transport_uri.assert_awaited_once_with(\n \"http://198.51.100.20:8200/MediaItems/17621.mp3\", \"Home Assistant\", ANY\n )\n dmr_device_mock.async_wait_for_can_play.assert_not_awaited()\n dmr_device_mock.async_play.assert_not_awaited()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_config_flow_user_initiated_unknown_failure_1(\n hass: HomeAssistant, mock_fibaro_client: Mock\n) -> None:\n \"\"\"Unknown failure in flow manually initialized by the user.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": config_entries.SOURCE_USER}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {}\n\n mock_fibaro_client.connect.side_effect = HTTPError(response=Mock(status_code=500))\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n {\n CONF_URL: TEST_URL,\n CONF_USERNAME: TEST_USERNAME,\n CONF_PASSWORD: TEST_PASSWORD,\n },\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {\"base\": \"cannot_connect\"}\n\n await _recovery_after_failure_works(hass, mock_fibaro_client, result)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_migrate_pipeline_invalid_platform(hass: HomeAssistant) -> None:\n \"\"\"Test migrate pipeline with invalid platform.\"\"\"\n await async_setup_component(hass, \"assist_pipeline\", {})\n with pytest.raises(ValueError):\n await async_migrate_cloud_pipeline_engine(\n hass, Platform.BINARY_SENSOR, \"test-engine-id\"\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def _supported(event: RFXtrxEvent) -> bool:\n return isinstance(event, (ControlEvent, SensorEvent))", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_group_addsystems_expand_no_systems(self, shell):\n \"\"\"\n Test do_group_addsystems with API call to find systems, without success getting one.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_addsystems = MagicMock()\n shell.get_system_id = MagicMock()\n shell.expand_systems = MagicMock(return_value=[])\n shell.client.systemgroup.addOrRemoveSystems = MagicMock()\n shell.ssm.keys = MagicMock()\n mprint = MagicMock()\n logger = MagicMock()\n with patch(\"spacecmd.group.print\", mprint) as prn, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_addsystems(shell, \"groupname something*\")\n\n assert not shell.get_system_id.called\n assert not shell.client.systemgroup.addOrRemoveSystems.called\n assert not mprint.called\n assert not logger.error.called\n assert not shell.help_group_addsystems.called\n assert not shell.ssm.keys.called\n assert shell.expand_systems.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_get_actions_hidden_auxiliary(\n hass: HomeAssistant,\n device_registry: dr.DeviceRegistry,\n entity_registry: er.EntityRegistry,\n hidden_by,\n entity_category,\n) -> None:\n \"\"\"Test we get the expected actions from a hidden or auxiliary entity.\"\"\"\n config_entry = MockConfigEntry(domain=\"test\", data={})\n config_entry.add_to_hass(hass)\n device_entry = device_registry.async_get_or_create(\n config_entry_id=config_entry.entry_id,\n connections={(dr.CONNECTION_NETWORK_MAC, \"12:34:56:AB:CD:EF\")},\n )\n entity_entry = entity_registry.async_get_or_create(\n DOMAIN,\n \"test\",\n \"5678\",\n device_id=device_entry.id,\n entity_category=entity_category,\n hidden_by=hidden_by,\n )\n expected_actions = []\n expected_actions += [\n {\n \"domain\": DOMAIN,\n \"type\": action,\n \"device_id\": device_entry.id,\n \"entity_id\": entity_entry.id,\n \"metadata\": {\"secondary\": True},\n }\n for action in [\"turn_off\", \"turn_on\", \"toggle\"]\n ]\n actions = await async_get_device_automations(\n hass, DeviceAutomationType.ACTION, device_entry.id\n )\n assert actions == unordered(expected_actions)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def cpu_nonlinear(host: Host, capacity: float, n: int) -> float:\n \"\"\" Non-linear resource sharing for CPU \"\"\"\n # emulates a degradation in CPU according to the number of tasks\n # totally unrealistic but for learning purposes\n capacity = capacity / 2 if n > 1 else capacity\n this_actor.info(\"Host %s, %d concurrent tasks, new capacity %f\" %\n (host.name, n, capacity))\n return capacity", "smellKey": "0", "smellId": null, "repo": "simgrid_simgrid", "language": "python"} {"function": "def check_for_block(self, node, hash):\n try:\n self.nodes[node].getblock(hash)\n return True\n except JSONRPCException:\n return False", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def test_write_buffer_set_signed_byte_three(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN)\n wb.write_signed_byte(3, 8)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00000011\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def hash(self) -> str:\n return mmh3.hash_bytes(f\"{self.id}-{self.name}\").hex()", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def periodic_backup_prod_db() -> None:\n subprocess.run([\"bash\", \"/app/scripts/database/backup_prod_db.sh\"])", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "async def test_migrate_unique_id(\n hass: HomeAssistant, entity_registry: er.EntityRegistry\n) -> None:\n \"\"\"Test a we can migrate a button unique id.\"\"\"\n aid = get_next_aid()\n button_entry = entity_registry.async_get_or_create(\n \"button\",\n \"homekit_controller\",\n f\"homekit-0001-aid:{aid}-sid:1-cid:2\",\n )\n await setup_test_component(hass, create_switch_with_ecobee_clear_hold_button)\n assert (\n entity_registry.async_get(button_entry.entity_id).unique_id\n == f\"00:00:00:00:00:00_{aid}_1_2\"\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_config_flow_user_initiated_unknown_failure_2(\n hass: HomeAssistant, mock_fibaro_client: Mock\n) -> None:\n \"\"\"Unknown failure in flow manually initialized by the user.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": config_entries.SOURCE_USER}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {}\n\n mock_fibaro_client.connect.side_effect = Exception()\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n {\n CONF_URL: TEST_URL,\n CONF_USERNAME: TEST_USERNAME,\n CONF_PASSWORD: TEST_PASSWORD,\n },\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {\"base\": \"cannot_connect\"}\n\n await _recovery_after_failure_works(hass, mock_fibaro_client, result)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def preset_mode(self) -> str | None:\n \"\"\"Preset current mode.\"\"\"\n if self.device_block is None:\n return self.last_state_attributes.get(\"preset_mode\")\n if self.device_block.mode is None:\n return PRESET_NONE\n return self._preset_modes[cast(int, self.device_block.mode)]", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n candidates_from_page: CandidatesFromPage,\n path: str,\n project_name: str,\n ) -> None:\n self._candidates_from_page = candidates_from_page\n self._project_name = canonicalize_name(project_name)\n\n # Get existing instance of _FlatDirectoryToUrls if it exists\n if path in self._paths_to_urls:\n self._path_to_urls = self._paths_to_urls[path]\n else:\n self._path_to_urls = _FlatDirectoryToUrls(path=path)\n self._paths_to_urls[path] = self._path_to_urls", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def http422_error_handler(\n request: Request,\n exc: RequestValidationError | ValidationError,\n) -> JSONResponse:\n assert request # nosec\n\n return create_error_json_response(\n *exc.errors(), status_code=status.HTTP_422_UNPROCESSABLE_ENTITY\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n check_custom_perm(request.user, \"view_import_of\", \"cluster\", cluster, \"view_clusterbind\")\n obj = self.get_queryset().filter(cluster=cluster, service=None)\n serializer = self.get_serializer(obj, many=True)\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def add_instance_group(self, instance_group):\n with suppress(exc.NoContent):\n self.related.instance_groups.post(dict(id=instance_group.id))", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def device_id(self):\n \"\"\"Return the device ID used for calling pylutron_caseta.\"\"\"\n return self._device[\"occupancy_group_id\"]", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n host_components = self.get_queryset().filter(cluster=cluster)\n if self._is_for_ui():\n return Response(make_ui_cluster_status(cluster, host_components))\n else:\n serializer = self.get_serializer(host_components, many=True)\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def __init__(self, hass: HomeAssistant, entry: RadioBrowserConfigEntry) -> None:\n \"\"\"Initialize RadioMediaSource.\"\"\"\n super().__init__(DOMAIN)\n self.hass = hass\n self.entry = entry", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_diagnostics(\n hass: HomeAssistant,\n hass_client: ClientSessionGenerator,\n load_int: ConfigEntry,\n snapshot: SnapshotAssertion,\n) -> None:\n \"\"\"Test generating diagnostics for a config entry.\"\"\"\n entry = load_int\n\n diag = await get_diagnostics_for_config_entry(hass, hass_client, entry)\n\n assert diag == snapshot(\n exclude=props(\"full_features\", \"created_at\", \"modified_at\"),\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def _async_build_popular(\n self, radios: RadioBrowser, item: MediaSourceItem\n ) -> list[BrowseMediaSource]:\n \"\"\"Handle browsing popular radio stations.\"\"\"\n if item.identifier == \"popular\":\n stations = await radios.stations(\n hide_broken=True,\n limit=250,\n order=Order.CLICK_COUNT,\n reverse=True,\n )\n return self._async_build_stations(radios, stations)\n\n if not item.identifier:\n return [\n BrowseMediaSource(\n domain=DOMAIN,\n identifier=\"popular\",\n media_class=MediaClass.DIRECTORY,\n media_content_type=MediaType.MUSIC,\n title=\"Popular\",\n can_play=False,\n can_expand=True,\n )\n ]\n\n return []", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_config_not_ready(\n hass: HomeAssistant, mock_accuweather_client: AsyncMock\n) -> None:\n \"\"\"Test for setup failure if connection to AccuWeather is missing.\"\"\"\n entry = MockConfigEntry(\n domain=DOMAIN,\n title=\"Home\",\n unique_id=\"0123456\",\n data={\n \"api_key\": \"32-character-string-1234567890qw\",\n \"latitude\": 55.55,\n \"longitude\": 122.12,\n \"name\": \"Home\",\n },\n )\n\n mock_accuweather_client.async_get_current_conditions.side_effect = ApiError(\n \"API Error\"\n )\n\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n assert entry.state is ConfigEntryState.SETUP_RETRY", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def async_process_events(self, sse_client: CrownstoneSSEAsync) -> None:\n \"\"\"Asynchronous iteration of Crownstone SSE events.\"\"\"\n async with sse_client as client:\n async for event in client:\n if event is not None:\n async_dispatcher_send(self.hass, f\"{DOMAIN}_{event.type}\", event)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_edit_endpoint(self):\n # Login to the site. Password will have to be modified\n # to match an admin password in your own container\n driver = self.driver\n # Navigate to the endpoint page\n driver.get(self.base_url + \"endpoint\")\n # Select one of the previously created endpoint to edit\n driver.find_element(By.LINK_TEXT, \"moving.com.rnd\").click()\n # \"Click\" the dropdown button to see options\n driver.find_element(By.ID, \"dropdownMenu1\").click()\n # \"Click\" the Edit Endpoint\n driver.find_element(By.LINK_TEXT, \"Edit Endpoint\").click()\n # Clear the old endpoint host name\n driver.find_element(By.ID, \"id_host\").clear()\n # Fill in the endpoint host name\n driver.find_element(By.ID, \"id_host\").send_keys(\"rnd.moving.com\")\n # Fill in port for endpoint\n driver.find_element(By.ID, \"id_port\").clear()\n driver.find_element(By.ID, \"id_port\").send_keys(\"8080\")\n # \"Click\" the submit button to complete the transaction\n driver.find_element(By.CSS_SELECTOR, \"input.btn.btn-primary\").click()\n # Query the site to determine if the product has been added\n\n # Assert ot the query to dtermine status of failure\n self.assertTrue(self.is_success_message_present(text=\"Endpoint updated successfully\"))", "smellKey": "0", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "async def async_volume_down(self) -> None:\n \"\"\"Send volume down command.\"\"\"\n await self._tv.sendKey(\"VolumeDown\")\n await self._async_update_soon()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_add_sub_element_with_sub():\n parent = ET.Element(\"{%s}cheese\" % XCCDF12_NS)\n text = \"The horse sings <sub idref=\\\"green\\\"/> and eats my igloo\"\n child = ssg.build_yaml.add_sub_element(\n parent, \"shop\", XCCDF12_NS, text)\n assert \"\".join(child.itertext()) == \"The horse sings and eats my igloo\"\n sub_els = child.findall(\"{%s}sub\" % XCCDF12_NS)\n assert len(sub_els) == 1\n sub_el = sub_els[0]\n assert len(sub_el) == 0\n assert len(sub_el.attrib) == 2\n assert sub_el.get(\"idref\") == \"xccdf_org.ssgproject.content_value_green\"\n assert sub_el.get(\"use\") == \"legacy\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_get_organism_by_internal_id_returns_none_when_id_is_none(\n store_with_organisms: Store,\n):\n \"\"\"Test finding an organism by internal ID None returns None.\"\"\"\n\n # GIVEN a store with multiple organisms\n organisms: Query = store_with_organisms._get_query(table=Organism)\n assert organisms.count() > 0\n\n # WHEN finding the organism by internal ID None\n filtered_organism: Organism = store_with_organisms.get_organism_by_internal_id(internal_id=None)\n\n # THEN the filtered organism should be None\n assert filtered_organism is None", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def logout():\n # remove the username from the session if it is there\n session.pop('username', None)\n return redirect(url_for('index'))", "smellKey": "0", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "async def test_bad_template(hass: HomeAssistant) -> None:\n \"\"\"Test passing bad template.\"\"\"\n calls = async_mock_service(hass, \"test_domain\", \"test_service\")\n config = {\n \"service_template\": \"{{ var_service }}\",\n \"entity_id\": \"hello.world\",\n \"data_template\": {\"hello\": \"{{ states + unknown_var }}\"},\n }\n\n await service.async_call_from_config(\n hass,\n config,\n variables={\n \"var_service\": \"test_domain.test_service\",\n \"var_data\": \"goodbye\",\n },\n )\n await hass.async_block_till_done()\n\n assert len(calls) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_write_buffer_write_unsigned_int_little_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN)\n # Testing incompatible format being sent to it.\n wb.write_unsigned_int(0x12, 32)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00010010 00000000 00000000 00000000\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def test_are_all_illumina_runs_on_disk_when_not_on_disk(\n store_with_illumina_sequencing_data_on_disk: Store,\n selected_novaseq_x_case_ids: str,\n):\n \"\"\"Test check if all sequencing runs on a case is on disk when not on disk.\"\"\"\n # GIVEN a store with two sequencing runs on a case that are not on disk\n sequencing_runs: list[IlluminaSequencingRun] = (\n store_with_illumina_sequencing_data_on_disk.get_illumina_sequencing_runs_by_case(\n selected_novaseq_x_case_ids[0]\n )\n )\n assert sequencing_runs\n assert len(sequencing_runs) == 2\n for sequencing_run in sequencing_runs:\n sequencing_run.data_availability = SequencingRunDataAvailability.RETRIEVED\n\n # WHEN fetching the sequencing runs for a case\n is_on_disk = store_with_illumina_sequencing_data_on_disk.are_all_illumina_runs_on_disk(\n case_id=selected_novaseq_x_case_ids[0]\n )\n\n # THEN return false\n assert is_on_disk is False", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_get_bed_by_entry_id(base_store: Store, entry_id: int = 1):\n \"\"\"Test returning panel bed by entry id.\"\"\"\n\n # GIVEN a store with bed records\n\n # WHEN getting the query for the bed\n bed: Bed = base_store.get_bed_by_entry_id(entry_id)\n\n # THEN return a bed with the supplied bed id\n assert bed.id == entry_id", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_service_template_service_call(hass: HomeAssistant) -> None:\n \"\"\"Test legacy service_template call with templating.\"\"\"\n calls = async_mock_service(hass, \"test_domain\", \"test_service\")\n config = {\n \"service_template\": \"{{ 'test_domain.test_service' }}\",\n \"entity_id\": \"hello.world\",\n \"data\": {\"hello\": \"goodbye\"},\n }\n\n await service.async_call_from_config(hass, config)\n await hass.async_block_till_done()\n\n assert calls[0].data == {\"hello\": \"goodbye\", \"entity_id\": [\"hello.world\"]}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_updating_manually(\n hass: HomeAssistant, caplog: pytest.LogCaptureFixture\n) -> None:\n \"\"\"Test handling manual updating using homeassistant udate_entity service.\"\"\"\n await setup.async_setup_component(hass, HA_DOMAIN, {})\n called = []\n\n class MockCommandBinarySensor(CommandBinarySensor):\n \"\"\"Mock entity that updates.\"\"\"\n\n async def _async_update(self) -> None:\n \"\"\"Update.\"\"\"\n called.append(1)\n\n with patch(\n \"homeassistant.components.command_line.binary_sensor.CommandBinarySensor\",\n side_effect=MockCommandBinarySensor,\n ):\n await setup.async_setup_component(\n hass,\n DOMAIN,\n {\n \"command_line\": [\n {\n \"binary_sensor\": {\n \"name\": \"Test\",\n \"command\": \"echo 1\",\n \"payload_on\": \"1\",\n \"payload_off\": \"0\",\n \"scan_interval\": 10,\n }\n }\n ]\n },\n )\n await hass.async_block_till_done()\n\n assert called\n called.clear()\n\n await hass.services.async_call(\n HA_DOMAIN,\n SERVICE_UPDATE_ENTITY,\n {ATTR_ENTITY_ID: [\"binary_sensor.test\"]},\n blocking=True,\n )\n await hass.async_block_till_done()\n assert called", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_activate(hass: HomeAssistant, mock_litejet) -> None:\n \"\"\"Test activating the scene.\"\"\"\n\n await async_init_integration(hass, use_scene=True)\n\n state = hass.states.get(ENTITY_SCENE)\n assert state is not None\n\n await hass.services.async_call(\n scene.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_SCENE}, blocking=True\n )\n\n mock_litejet.activate_scene.assert_called_once_with(ENTITY_SCENE_NUMBER)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_iid_migration_to_v2(\n hass: HomeAssistant, iid_storage, hass_storage: dict[str, Any]\n) -> None:\n \"\"\"Test iid storage migration.\"\"\"\n v1_iids = json_loads(load_fixture(\"iids_v1\", DOMAIN))\n v2_iids = json_loads(load_fixture(\"iids_v2\", DOMAIN))\n hass_storage[\"homekit.v1.iids\"] = v1_iids\n hass_storage[\"homekit.v2.iids\"] = v2_iids\n\n iid_storage_v2 = AccessoryIIDStorage(hass, \"v1\")\n await iid_storage_v2.async_initialize()\n\n iid_storage_v1 = AccessoryIIDStorage(hass, \"v2\")\n await iid_storage_v1.async_initialize()\n\n assert iid_storage_v1.allocations == iid_storage_v2.allocations\n assert iid_storage_v1.allocated_iids == iid_storage_v2.allocated_iids\n\n assert len(iid_storage_v2.allocations) == 12\n\n for allocations in iid_storage_v2.allocations.values():\n assert allocations[\"3E___\"] == 1", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_added_to_hass(self) -> None:\n \"\"\"Register callbacks.\"\"\"\n self._smartbridge.add_occupancy_subscriber(\n self.device_id, self.async_write_ha_state\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_remove_switches(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, mock_unifi_websocket\n) -> None:\n \"\"\"Test the update_items function with some clients.\"\"\"\n await setup_unifi_integration(\n hass,\n aioclient_mock,\n options={CONF_BLOCK_CLIENT: [UNBLOCKED[\"mac\"]]},\n clients_response=[UNBLOCKED],\n dpigroup_response=DPI_GROUPS,\n dpiapp_response=DPI_APPS,\n )\n\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2\n\n assert hass.states.get(\"switch.block_client_2\") is not None\n assert hass.states.get(\"switch.block_media_streaming\") is not None\n\n mock_unifi_websocket(message=MessageKey.CLIENT_REMOVED, data=[UNBLOCKED])\n await hass.async_block_till_done()\n\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n\n assert hass.states.get(\"switch.block_client_2\") is None\n assert hass.states.get(\"switch.block_media_streaming\") is not None\n\n mock_unifi_websocket(data=DPI_GROUP_REMOVED_EVENT)\n await hass.async_block_till_done()\n\n assert hass.states.get(\"switch.block_media_streaming\") is None\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def is_same_value_different_endpoints(self, other: ValueID) -> bool:\n \"\"\"Return whether two value IDs are the same excluding endpoint.\"\"\"\n return (\n self.command_class == other.command_class\n and self.property_ == other.property_\n and self.property_key == other.property_key\n and self.endpoint != other.endpoint\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def page_candidates(self) -> FoundCandidates:\n if not self._page_validator(self._link):\n return\n yield from self._candidates_from_page(self._link)", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def client(self) -> aioredis.Redis:\n client: aioredis.Redis = get_redis_resources_client(self.app)\n return client", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def kml(self):\n \"Return the KML representation of this Polygon.\"\n inner_kml = \"\".join(\n \"<innerBoundaryIs>%s</innerBoundaryIs>\" % self[i + 1].kml\n for i in range(self.num_interior_rings)\n )\n return \"<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>\" % (\n self[0].kml,\n inner_kml,\n )", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_group_restore_catch_empty_directory(self, shell):\n \"\"\"\n test do_group_restore catch empty directory.\n\n :param shell:\n :return:\n \"\"\"\n def _abspath(path):\n \"\"\"\n Fake os.path.abspath that expands to /tmp/test\n\n :param path:\n :return:\n \"\"\"\n return os.path.join(\"/tmp/test\", path.strip(\"/\"))\n\n shell.help_group_restore = MagicMock()\n shell.do_group_list = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock()\n shell.client.systemgroup.update = MagicMock()\n shell.client.systemgroup.create = MagicMock()\n logger = MagicMock()\n mprint = MagicMock()\n\n with patch(\"spacecmd.group.print\", mprint) as prn, \\\n patch(\"spacecmd.group.logging\", logger) as lgr, \\\n patch(\"spacecmd.group.os.path.abspath\", _abspath) as abp:\n spacecmd.group.do_group_restore(shell, \"ALL\")\n\n assert not shell.do_group_list.called\n assert not shell.client.systemgroup.getDetails.called\n assert not shell.client.systemgroup.update.called\n assert not shell.client.systemgroup.create.called\n assert not logger.info.called\n assert not mprint.called\n assert not shell.help_group_restore.called\n assert logger.debug.called\n assert logger.error.called\n\n assert_expect(logger.debug.call_args_list,\n \"Input Directory: /tmp/test/ALL\")\n assert_expect(logger.error.call_args_list,\n 'Restore dir /tmp/test/ALL has no restore items')", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def get_rules(self) -> Optional[List[Rule]]:\n \"\"\"\n Returns:\n Optional custom list of \"Rule\" objects implementing particular \"DataAssistant\" functionality.\n \"\"\"\n numeric_rule: Rule = self._build_numeric_rule()\n float_rule: Rule = self._build_float_rule()\n\n return [\n numeric_rule,\n float_rule,\n ]", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_blueprint_inputs_validation(blueprint_1: models.Blueprint) -> None:\n \"\"\"Test blueprint input validation.\"\"\"\n inputs = models.BlueprintInputs(\n blueprint_1,\n {\"use_blueprint\": {\"path\": \"bla\", \"input\": {\"non-existing-placeholder\": 1}}},\n )\n with pytest.raises(errors.MissingInput):\n inputs.validate()", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def filter_org_roles(self, queryset, name, value):\n queryset = self._filter_roles(queryset=queryset, value=value, scope=Role.Scope.org.value)\n return queryset", "smellKey": "0", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def _export_images(dst_file, temp_dir, task_data, save_images=False):\n with GetCVATDataExtractor(\n task_data, include_images=save_images, format_type='sly_pointcloud',\n dimension=DimensionType.DIM_3D,\n ) as extractor:\n dataset = Dataset.from_extractors(extractor, env=dm_env)\n dataset.export(temp_dir, 'sly_pointcloud', save_images=save_images, allow_undeclared_attrs=True)\n\n make_zip_archive(temp_dir, dst_file)", "smellKey": "0", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "async def test_async_extract_entities_warn_referenced(\n hass: HomeAssistant, caplog: pytest.LogCaptureFixture\n) -> None:\n \"\"\"Test we only warn for referenced entities in async_extract_entities.\"\"\"\n call = ServiceCall(\n \"light\",\n \"turn_on\",\n {\n \"area_id\": \"non-existent-area\",\n \"entity_id\": \"non.existent\",\n \"device_id\": \"non-existent-device\",\n \"floor_id\": \"non-existent-floor\",\n \"label_id\": \"non-existent-label\",\n },\n )\n extracted = await service.async_extract_entities(hass, {}, call)\n assert len(extracted) == 0\n assert (\n \"Referenced floors non-existent-floor, areas non-existent-area, \"\n \"devices non-existent-device, entities non.existent, \"\n \"labels non-existent-label are missing or not currently available\"\n ) in caplog.text", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_normalize_url(url_path: str) -> None:\n \"\"\"Test that the url is normalized for different entered values.\"\"\"\n assert _normalize_url(f\"http://192.168.1.1{url_path}\") == \"http://192.168.1.1/api/\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_switches(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n aioclient_mock: AiohttpClientMocker,\n) -> None:\n \"\"\"Test the update_items function with some clients.\"\"\"\n config_entry = await setup_unifi_integration(\n hass,\n aioclient_mock,\n options={\n CONF_BLOCK_CLIENT: [BLOCKED[\"mac\"], UNBLOCKED[\"mac\"]],\n CONF_TRACK_CLIENTS: False,\n CONF_TRACK_DEVICES: False,\n },\n clients_response=[CLIENT_4],\n clients_all_response=[BLOCKED, UNBLOCKED, CLIENT_1],\n dpigroup_response=DPI_GROUPS,\n dpiapp_response=DPI_APPS,\n )\n\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 3\n\n switch_4 = hass.states.get(\"switch.poe_client_4\")\n assert switch_4 is None\n\n blocked = hass.states.get(\"switch.block_client_1\")\n assert blocked is not None\n assert blocked.state == \"off\"\n\n unblocked = hass.states.get(\"switch.block_client_2\")\n assert unblocked is not None\n assert unblocked.state == \"on\"\n\n dpi_switch = hass.states.get(\"switch.block_media_streaming\")\n assert dpi_switch is not None\n assert dpi_switch.state == \"on\"\n assert dpi_switch.attributes[\"icon\"] == \"mdi:network\"\n\n for entry_id in (\"switch.block_client_1\", \"switch.block_media_streaming\"):\n assert (\n entity_registry.async_get(entry_id).entity_category is EntityCategory.CONFIG\n )\n\n # Block and unblock client\n aioclient_mock.clear_requests()\n aioclient_mock.post(\n f\"https://{config_entry.data[CONF_HOST]}:1234\"\n f\"/api/s/{config_entry.data[CONF_SITE_ID]}/cmd/stamgr\",\n )\n\n await hass.services.async_call(\n SWITCH_DOMAIN, \"turn_off\", {\"entity_id\": \"switch.block_client_1\"}, blocking=True\n )\n assert aioclient_mock.call_count == 1\n assert aioclient_mock.mock_calls[0][2] == {\n \"mac\": \"00:00:00:00:01:01\",\n \"cmd\": \"block-sta\",\n }\n\n await hass.services.async_call(\n SWITCH_DOMAIN, \"turn_on\", {\"entity_id\": \"switch.block_client_1\"}, blocking=True\n )\n assert aioclient_mock.call_count == 2\n assert aioclient_mock.mock_calls[1][2] == {\n \"mac\": \"00:00:00:00:01:01\",\n \"cmd\": \"unblock-sta\",\n }\n\n # Enable and disable DPI\n aioclient_mock.clear_requests()\n aioclient_mock.put(\n f\"https://{config_entry.data[CONF_HOST]}:1234\"\n f\"/api/s/{config_entry.data[CONF_SITE_ID]}/rest/dpiapp/{DPI_APPS[0]['_id']}\",\n )\n\n await hass.services.async_call(\n SWITCH_DOMAIN,\n \"turn_off\",\n {\"entity_id\": \"switch.block_media_streaming\"},\n blocking=True,\n )\n assert aioclient_mock.call_count == 1\n assert aioclient_mock.mock_calls[0][2] == {\"enabled\": False}\n\n await hass.services.async_call(\n SWITCH_DOMAIN,\n \"turn_on\",\n {\"entity_id\": \"switch.block_media_streaming\"},\n blocking=True,\n )\n assert aioclient_mock.call_count == 2\n assert aioclient_mock.mock_calls[1][2] == {\"enabled\": True}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def target_temperature(self) -> None:\n \"\"\"Return the temperature.\"\"\"\n if self.hvac_mode == HVACMode.AUTO:\n self.executor.select_state(OverkizState.IO_EFFECTIVE_TEMPERATURE_SETPOINT)\n else:\n self.executor.select_state(OverkizState.CORE_TARGET_TEMPERATURE)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def hvac_mode(self) -> HVACMode:\n \"\"\"Return hvac operation ie. heat, cool mode.\"\"\"\n if OverkizState.CORE_OPERATING_MODE in self.device.states:\n return OVERKIZ_TO_HVAC_MODE[\n cast(str, self.executor.select_state(OverkizState.CORE_OPERATING_MODE))\n ]\n\n return HVACMode.OFF", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_clone_wrongargs(self, shell):\n \"\"\"\n Test do_activationkey_clone wrong arguments prompts for correction.\n \"\"\"\n shell.do_activationkey_list = MagicMock()\n shell.help_activationkey_clone = MagicMock()\n shell.export_activationkey_getdetails = MagicMock()\n shell.list_base_channels = MagicMock()\n shell.list_child_channels = MagicMock()\n shell.do_configchannel_list = MagicMock()\n shell.import_activtionkey_fromdetails = MagicMock()\n\n with pytest.raises(Exception) as exc:\n spacecmd.activationkey.do_activationkey_clone(shell, \"--nonsense=true\")\n\n assert \"unrecognized arguments: --nonsense=true\" in exc2str(exc)", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_group_details_noargs(self, shell):\n \"\"\"\n Test do_group_details with no arguments.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_details = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock()\n shell.client.systemgroup.listSystems = MagicMock()\n\n mprint = MagicMock()\n logger = MagicMock()\n with patch(\"spacecmd.group.print\", mprint) as prt, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_details(shell, \"\")\n\n assert not logger.warning.called\n assert not shell.client.systemgroup.getDetails.called\n assert not shell.client.systemgroup.listSystems.called\n assert not mprint.called\n assert shell.help_group_details.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def async_unload(self) -> bool:\n \"\"\"Unload the current config entry.\"\"\"\n # Authentication failed\n if self.cloud.cloud_data is None:\n return True\n\n self.sse.close_client()\n for sse_unsub in self.listeners[SSE_LISTENERS]:\n sse_unsub()\n\n if self.uart:\n self.uart.stop()\n for subscription_id in self.listeners[UART_LISTENERS]:\n UartEventBus.unsubscribe(subscription_id)\n\n unload_ok = await self.hass.config_entries.async_unload_platforms(\n self.config_entry, PLATFORMS\n )\n\n if unload_ok:\n self.hass.data[DOMAIN].pop(self.config_entry.entry_id)\n\n return unload_ok", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def setUpTestData(cls):\n cls.address = Address.objects.create(company=1, customer_id=20)\n cls.customer1 = Customer.objects.create(company=1, customer_id=20)\n cls.contact1 = Contact.objects.create(company_code=1, customer_code=20)", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_raise_called(\n self, flag: ConcernFlag, task: Task, arguments: str | dict, targets: Collection[CoreObjectDescriptor]\n ) -> None:\n (\n raise_flag_mock,\n lower_flag_mock,\n lower_all_flags_mock,\n update_hierarchy_for_flag_mock,\n ) = self.execute_plugin_patched(task, arguments)\n\n raise_flag_mock.assert_called_once_with(flag=flag, on_objects=targets)\n update_hierarchy_for_flag_mock.assert_called_once_with(flag=flag, on_objects=targets)\n lower_flag_mock.assert_not_called()\n lower_all_flags_mock.assert_not_called()", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def test_unique_id(\n hass: HomeAssistant, entity_registry: er.EntityRegistry, load_yaml_integration: None\n) -> None:\n \"\"\"Test unique_id option and if it only creates one binary sensor per id.\"\"\"\n\n assert len(hass.states.async_all()) == 2\n\n assert len(entity_registry.entities) == 2\n assert entity_registry.async_get_entity_id(\n \"binary_sensor\", \"command_line\", \"unique\"\n )\n assert entity_registry.async_get_entity_id(\n \"binary_sensor\", \"command_line\", \"not-so-unique-anymore\"\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def _set_ext_ring(self, ring):\n \"Set the exterior ring of the Polygon.\"\n self[0] = ring", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def page_candidates(self) -> FoundCandidates:\n \"\"\"Candidates found by parsing an archive listing HTML file.\"\"\"\n raise NotImplementedError()", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def test_update_sample_reads_illumina_fail_q30(\n store_with_illumina_sequencing_data: Store, selected_novaseq_x_sample_ids: list[str]\n):\n # GIVEN a store with Illumina Sequencing Runs and a sample id\n sample: Sample = store_with_illumina_sequencing_data.get_sample_by_internal_id(\n selected_novaseq_x_sample_ids[0]\n )\n assert sample.reads == 0\n # GIVEN that the q30 for the lane is below the threshold for the sequencer type\n sample.sample_run_metrics[0].base_passing_q30_percent = 30\n\n # WHEN updating the sample reads for a sequencing run\n store_with_illumina_sequencing_data.update_sample_reads_illumina(\n internal_id=selected_novaseq_x_sample_ids[0], sequencer_type=Sequencers.NOVASEQX\n )\n\n # THEN the total reads for the sample is updated\n assert sample.reads == 0", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def subgraph_get_path_edges(ctx: mgp.ProcCtx, path: mgp.Path) -> mgp.Record(edge=mgp.Edge):\n return [mgp.Record(edge=edge) for edge in path.edges]", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def session(self, context: Optional[InjectionContext] = None) -> \"ProfileSession\":\n \"\"\"Start a new interactive session with no transaction support requested.\"\"\"\n return InMemoryProfileSession(self, context=context)", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_write_buffer_write_unsigned_short_big_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN)\n wb.write_unsigned_short(0x12, 16)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00000000 00010010\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def variables_names(self):\n return self._variables_getters.keys()", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def async_set_temperature(self, **kwargs: Any) -> None:\n \"\"\"Set new target temperature.\"\"\"\n if (current_temp := kwargs.get(ATTR_TEMPERATURE)) is None:\n return\n\n # Shelly TRV accepts target_t in Fahrenheit or Celsius, but you must\n # send the units that the device expects\n if self.block is not None and self.block.channel is not None:\n therm = self.coordinator.device.settings[\"thermostats\"][\n int(self.block.channel)\n ]\n LOGGER.debug(\"Themostat settings: %s\", therm)\n if therm.get(\"target_t\", {}).get(\"units\", \"C\") == \"F\":\n current_temp = TemperatureConverter.convert(\n cast(float, current_temp),\n UnitOfTemperature.CELSIUS,\n UnitOfTemperature.FAHRENHEIT,\n )\n\n await self.set_state_full_path(target_t_enabled=1, target_t=f\"{current_temp}\")", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def next_pickup_event(self) -> RidwellPickupEvent:\n \"\"\"Get the next pickup event.\"\"\"\n return next(\n event\n for event in self.coordinator.data[self._account.account_id]\n if event.pickup_date >= date.today()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def extra_restore_state_data(self) -> ShellyClimateExtraStoredData:\n \"\"\"Return text specific state data to be restored.\"\"\"\n return ShellyClimateExtraStoredData(self._last_target_temp)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_group_listsystems_nodata(self, shell):\n \"\"\"\n Test do_group_listsystems without data return, but STDOUT.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_listsystems = MagicMock()\n shell.client.systemgroup.listSystems = MagicMock(return_value=[\n {\"profile_name\": \"system-d\"}, {\"profile_name\": \"system-c\"},\n {\"profile_name\": \"system-b\"}, {\"profile_name\": \"system-a\"},\n ])\n mprint = MagicMock()\n logger = MagicMock()\n\n with patch(\"spacecmd.group.print\", mprint) as prt, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n out = spacecmd.group.do_group_listsystems(shell, \"group-a\", doreturn=False)\n\n assert not shell.help_group_listsystems.called\n assert not logger.warning.called\n assert shell.client.systemgroup.listSystems.called\n assert out is None\n assert mprint.called\n assert_expect(mprint.call_args_list, \"system-a\\nsystem-b\\nsystem-c\\nsystem-d\")", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_ensure_date_string(self):\n tmpl = self.engine.from_string(\"{{ ensure_date(d) }}\")\n self.assertEqual(tmpl.render({\"d\": \"2018-02-01\"}), \"2018-02-01\")", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "async def test_multiple_configs(hass: HomeAssistant) -> None:\n \"\"\"Test: multiple select entities get created.\"\"\"\n with assert_setup_component(1, \"template\"):\n assert await setup.async_setup_component(\n hass,\n \"template\",\n {\n \"template\": {\n \"select\": [\n {\n \"state\": \"{{ 'a' }}\",\n \"select_option\": {\"service\": \"script.select_option\"},\n \"options\": \"{{ ['a', 'b'] }}\",\n },\n {\n \"state\": \"{{ 'a' }}\",\n \"select_option\": {\"service\": \"script.select_option\"},\n \"options\": \"{{ ['a', 'b'] }}\",\n },\n ]\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n _verify(hass, \"a\", [\"a\", \"b\"])\n _verify(hass, \"a\", [\"a\", \"b\"], f\"{_TEST_SELECT}_2\")", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def as_json(self):\n return {\n \"name\": self.name,\n \"value\": self.value,\n }", "smellKey": "0", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the Lutron Caseta binary_sensor platform.\n\n Adds occupancy groups from the Caseta bridge associated with the\n config_entry as binary_sensor entities.\n \"\"\"\n data: LutronCasetaData = hass.data[CASETA_DOMAIN][config_entry.entry_id]\n bridge = data.bridge\n occupancy_groups = bridge.occupancy_groups\n async_add_entities(\n LutronOccupancySensor(occupancy_group, data)\n for occupancy_group in occupancy_groups.values()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def configure_settings(self, settings):\n settings.IS_K8S = True", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def reload_targets(service_call: ServiceCall) -> set[str | None]:\n if target_id := service_call.data.get(\"target\"):\n return {target_id}\n return {\"target1\", \"target2\", \"target3\", \"target4\"}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __modify_schema__(cls, field_schema: Dict[str, Any], field: Union[fields.ModelField, None]):\n if field:\n field_schema[\"title\"] = \"Value Set\"\n field_schema[\"description\"] = VALUE_SET_DESCRIPTION\n field_schema[\"oneOf\"] = [\n {\n \"title\": \"Text\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n },\n \"minItems\": 1,\n \"examples\": [\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n [\n \"2024-01-01\",\n \"2024-01-02\",\n \"2024-01-03\",\n \"2024-01-04\",\n \"2024-01-05\",\n ],\n ],\n },\n {\n \"title\": \"Numbers\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\",\n },\n \"minItems\": 1,\n \"examples\": [\n [1, 2, 3, 4, 5],\n [1.1, 2.2, 3.3, 4.4, 5.5],\n [1, 2.2, 3, 4.4, 5],\n ],\n },\n ]", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_case_with_name_exists(\n store_with_case_and_sample_with_reads: Store, downsample_case_internal_id: str\n):\n # GIVEN a store with a case and a sample\n\n # WHEN checking if a case that is in the store exists\n does_exist: bool = store_with_case_and_sample_with_reads.case_with_name_exists(\n case_name=downsample_case_internal_id,\n )\n # THEN the case does exist\n assert does_exist", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_delete_project_in_multiple_products_forbidden(\n client: TestClient,\n logged_user: UserInfoDict,\n user_project_in_2_products: ProjectDict,\n expected: ExpectedResponse,\n):\n assert client.app\n await _request_delete_project(client, user_project_in_2_products, expected.conflict)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_do_activationkey_removeentitlements_args(self, shell):\n \"\"\"\n Test \"removeentitlements\" method calls \"removeEntitlements\" API call.\n \"\"\"\n shell.help_activationkey_removeentitlements = MagicMock()\n shell.client.activationkey.removeEntitlements = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removeentitlements(shell, \"key entitlement\")\n assert not shell.help_activationkey_removeentitlements.called\n assert shell.client.activationkey.removeEntitlements.called\n session, fun, args = shell.client.activationkey.removeEntitlements.call_args_list[0][0]\n assert session == shell.session\n assert fun == \"key\"\n assert isinstance(args, list)\n assert len(args) == 1\n assert args == ['entitlement']", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def include_case_files(self):\n \"\"\"Include case level files for mip case\"\"\"\n LOG.info(\"Including MIP specific case level files\")\n self.load_config.peddy_check = self.get_file_from_hk(self.case_tags.peddy_check)\n self.load_config.peddy_ped = self.get_file_from_hk(self.case_tags.peddy_ped)\n self.load_config.peddy_sex = self.get_file_from_hk(self.case_tags.peddy_sex)\n self.load_config.smn_tsv = self.get_file_from_hk(self.case_tags.smn_tsv)\n self.load_config.vcf_mei = self.get_file_from_hk(self.case_tags.vcf_mei)\n self.load_config.vcf_mei_research = self.get_file_from_hk(self.case_tags.vcf_mei_research)\n self.load_config.vcf_snv = self.get_file_from_hk(self.case_tags.snv_vcf)\n self.load_config.vcf_snv_research = self.get_file_from_hk(self.case_tags.snv_research_vcf)\n self.load_config.vcf_str = self.get_file_from_hk(self.case_tags.vcf_str)\n self.load_config.vcf_sv = self.get_file_from_hk(self.case_tags.sv_vcf)\n self.load_config.vcf_sv_research = self.get_file_from_hk(self.case_tags.sv_research_vcf)\n self.include_multiqc_report()", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_get_pools_to_render_with_customer(\n store_with_multiple_pools_for_customer: Store,\n):\n \"\"\"Test that pools can be fetched from the store by customer id.\"\"\"\n # GIVEN a database with two pools\n\n # WHEN getting pools by customer id\n pools: list[Pool] = store_with_multiple_pools_for_customer.get_pools_to_render(\n customers=store_with_multiple_pools_for_customer.get_customers()\n )\n\n # THEN two pools should be returned\n assert len(pools) == 2", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the Zigbee Home Automation device tracker from config entry.\"\"\"\n zha_data = get_zha_data(hass)\n entities_to_create = zha_data.platforms[Platform.DEVICE_TRACKER]\n\n unsub = async_dispatcher_connect(\n hass,\n SIGNAL_ADD_ENTITIES,\n functools.partial(\n zha_async_add_entities,\n async_add_entities,\n ZHADeviceScannerEntity,\n entities_to_create,\n ),\n )\n config_entry.async_on_unload(unsub)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def lex(code, lexer):\n \"\"\"\n Lex `code` with the `lexer` (must be a `Lexer` instance)\n and return an iterable of tokens. Currently, this only calls\n `lexer.get_tokens()`.\n \"\"\"\n try:\n return lexer.get_tokens(code)\n except TypeError:\n # Heuristic to catch a common mistake.\n from pip._vendor.pygments.lexer import RegexLexer\n if isinstance(lexer, type) and issubclass(lexer, RegexLexer):\n raise TypeError('lex() argument must be a lexer instance, '\n 'not a class')\n raise", "smellKey": "0", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def test_do_activationkey_removeconfigchannels_args(self, shell):\n \"\"\"\n Test removeconfigchannels command is calling removeConfigChannels API by the activation key passed.\n \"\"\"\n shell.help_activationkey_removeconfigchannels = MagicMock()\n shell.client.activationkey.removeConfigChannels = MagicMock()\n\n mprint = MagicMock()\n spacecmd.activationkey.do_activationkey_removeconfigchannels(shell, \"key some_patches\")\n assert not shell.help_activationkey_removeconfigchannels.called\n assert shell.client.activationkey.removeConfigChannels.called\n\n session, keys, channels = shell.client.activationkey.removeConfigChannels.call_args_list[0][0]\n assert shell.session == session\n assert \"key\" in keys\n assert \"some_patches\" in channels\n assert len(keys) == len(channels) == 1", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_priority_ordering():\n ORDER = [\"ga\", \"be\", \"al\"]\n to_order = [\"alpha\", \"beta\", \"gamma\"]\n ordered = ssg.build_yaml.reorder_according_to_ordering(to_order, ORDER)\n assert ordered == [\"gamma\", \"beta\", \"alpha\"]\n\n to_order = [\"alpha\", \"beta\", \"gamma\", \"epsilon\"]\n ordered = ssg.build_yaml.reorder_according_to_ordering(to_order, ORDER)\n assert ordered == [\"gamma\", \"beta\", \"alpha\", \"epsilon\"]\n\n to_order = [\"alpha\"]\n ordered = ssg.build_yaml.reorder_according_to_ordering(to_order, ORDER)\n assert ordered == [\"alpha\"]\n\n to_order = [\"x\"]\n ordered = ssg.build_yaml.reorder_according_to_ordering(to_order, ORDER)\n assert ordered == [\"x\"]\n\n to_order = [\"alpha\", \"beta\", \"alnum\", \"gaha\"]\n ordered = ssg.build_yaml.reorder_according_to_ordering(\n to_order, ORDER + [\"gaha\"], regex=\".*ha\")\n assert ordered[:2] == [\"gaha\", \"alpha\"]", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_do_activationkey_addconfigchannels_setusagelimit_args(self, shell):\n \"\"\"\n Test do_activationkey_addconfigchannels_setbasechannel resets usage limit from 0 to -1.\n \"\"\"\n key_details = {\n \"base_channel_label\": \"death_star_channel\",\n \"description\": \"Darth Vader's base channel\",\n \"usage_limit\": 0,\n \"universal_default\": True,\n }\n shell.help_activationkey_setusagelimit = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n shell.client.activationkey.getDetails = MagicMock(return_value=key_details)\n\n spacecmd.activationkey.do_activationkey_setusagelimit(shell, \"red_key 42\")\n session, keyname, details = shell.client.activationkey.setDetails.call_args_list[0][0]\n assert shell.session == session\n assert keyname == \"red_key\"\n\n for dkey in [\"description\", \"universal_default\", \"base_channel_label\"]:\n assert dkey in details\n assert key_details[dkey] == details[dkey]\n assert type(details[\"usage_limit\"]) == int\n assert details[\"usage_limit\"] == 42", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_call_no_context_target_all(\n hass: HomeAssistant, mock_handle_entity_call, mock_entities\n) -> None:\n \"\"\"Check we target all if no user context given.\"\"\"\n await service.entity_service_call(\n hass,\n mock_entities,\n Mock(),\n ServiceCall(\n \"test_domain\", \"test_service\", data={\"entity_id\": ENTITY_MATCH_ALL}\n ),\n )\n\n assert len(mock_handle_entity_call.mock_calls) == 4\n assert [call[1][1] for call in mock_handle_entity_call.mock_calls] == list(\n mock_entities.values()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def tuple(self):\n \"Get the tuple for each ring in this Polygon.\"\n return tuple(self[i].tuple for i in range(len(self)))", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def target_temperature(self) -> float | None:\n \"\"\"Set target temperature.\"\"\"\n return cast(float, self.status[\"target_C\"])", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_setup(self) -> bool:\n \"\"\"Set up a Crownstone config entry.\n\n Returns True if the setup was successful.\n \"\"\"\n email = self.config_entry.data[CONF_EMAIL]\n password = self.config_entry.data[CONF_PASSWORD]\n\n self.cloud = CrownstoneCloud(\n email=email,\n password=password,\n clientsession=aiohttp_client.async_get_clientsession(self.hass),\n )\n # Login & sync all user data\n try:\n await self.cloud.async_initialize()\n except CrownstoneAuthenticationError as auth_err:\n _LOGGER.error(\n \"Auth error during login with type: %s and message: %s\",\n auth_err.type,\n auth_err.message,\n )\n return False\n except CrownstoneUnknownError as unknown_err:\n _LOGGER.error(\"Unknown error during login\")\n raise ConfigEntryNotReady from unknown_err\n\n # A new clientsession is created because the default one does not cleanup on unload\n self.sse = CrownstoneSSEAsync(\n email=email,\n password=password,\n access_token=self.cloud.access_token,\n websession=aiohttp_client.async_create_clientsession(self.hass),\n project_name=PROJECT_NAME,\n )\n # Listen for events in the background, without task tracking\n self.config_entry.async_create_background_task(\n self.hass, self.async_process_events(self.sse), \"crownstone-sse\"\n )\n setup_sse_listeners(self)\n\n # Set up a Crownstone USB only if path exists\n if self.config_entry.options[CONF_USB_PATH] is not None:\n await self.async_setup_usb()\n\n # Save the sphere where the USB is located\n # Makes HA aware of the Crownstone environment HA is placed in, a user can have multiple\n self.usb_sphere_id = self.config_entry.options[CONF_USB_SPHERE]\n\n await self.hass.config_entries.async_forward_entry_setups(\n self.config_entry, PLATFORMS\n )\n\n # HA specific listeners\n self.config_entry.async_on_unload(\n self.config_entry.add_update_listener(_async_update_listener)\n )\n self.config_entry.async_on_unload(\n self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.on_shutdown)\n )\n\n return True", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_platform_from_text_complex_expression(product_cpes):\n platform = ssg.build_yaml.Platform.from_text(\n \"systemd and !yum and (ntp or chrony)\", product_cpes)\n assert platform.test(**{'systemd': True, 'ntp': False, 'chrony': True, 'yum': False})\n platform_el = platform.to_xml_element()\n assert platform_el.tag == \"{%s}platform\" % cpe_language_namespace\n logical_tests = platform_el.findall(\n \"{%s}logical-test\" % cpe_language_namespace)\n assert len(logical_tests) == 1\n assert logical_tests[0].get(\"operator\") == \"AND\"\n assert logical_tests[0].get(\"negate\") == \"false\"\n logical_tests_2 = logical_tests[0].findall(\n \"{%s}logical-test\" % cpe_language_namespace)\n assert len(logical_tests_2) == 2\n assert logical_tests_2[0].get(\"operator\") == \"OR\"\n assert logical_tests_2[0].get(\"negate\") == \"false\"\n check_fact_refs = logical_tests_2[0].findall(\n \"{%s}check-fact-ref\" % cpe_language_namespace)\n assert len(check_fact_refs) == 2\n assert check_fact_refs[0].get(\"id-ref\") == \"oval:ssg-installed_env_has_chrony_package:def:1\"\n assert check_fact_refs[1].get(\"id-ref\") == \"oval:ssg-installed_env_has_ntp_package:def:1\"\n assert logical_tests_2[1].get(\"operator\") == \"AND\"\n assert logical_tests_2[1].get(\"negate\") == \"true\"\n check_fact_refs_2 = logical_tests_2[1].findall(\n \"{%s}check-fact-ref\" % cpe_language_namespace)\n assert len(check_fact_refs_2) == 1\n assert check_fact_refs_2[0].get(\"id-ref\") == \"oval:ssg-installed_env_has_yum_package:def:1\"\n check_fact_refs_3 = logical_tests[0].findall(\n \"{%s}check-fact-ref\" % cpe_language_namespace)\n assert len(check_fact_refs_3) == 1\n assert check_fact_refs_3[0].get(\"id-ref\") == \"oval:ssg-installed_env_has_systemd_package:def:1\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_do_activationkey_removeentitlements_noargs(self, shell):\n \"\"\"\n Test removeentitlements without args calls help.\n \"\"\"\n shell.help_activationkey_removeentitlements = MagicMock()\n shell.client.activationkey.removeEntitlements = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removeentitlements(shell, \"\")\n assert shell.help_activationkey_removeentitlements.called\n assert not shell.client.activationkey.removeEntitlements.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def setUp(self) -> None:\n self.client.login(username=\"admin\", password=\"admin\")\n\n cluster_bundle_1_path = self.test_bundles_dir / \"cluster_one\"\n cluster_bundle_2_path = self.test_bundles_dir / \"cluster_two\"\n provider_bundle_path = self.test_bundles_dir / \"provider\"\n\n self.bundle_1 = self.add_bundle(source_dir=cluster_bundle_1_path)\n self.bundle_2 = self.add_bundle(source_dir=cluster_bundle_2_path)\n self.provider_bundle = self.add_bundle(source_dir=provider_bundle_path)\n\n self.cluster_1 = self.add_cluster(bundle=self.bundle_1, name=\"cluster_1\", description=\"cluster_1\")\n self.cluster_2 = self.add_cluster(bundle=self.bundle_2, name=\"cluster_2\", description=\"cluster_2\")\n self.provider = self.add_provider(bundle=self.provider_bundle, name=\"provider\", description=\"provider\")", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def test_play_media_metadata(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test play_media constructs useful metadata from user params.\"\"\"\n await hass.services.async_call(\n MP_DOMAIN,\n mp_const.SERVICE_PLAY_MEDIA,\n {\n ATTR_ENTITY_ID: mock_entity_id,\n mp_const.ATTR_MEDIA_CONTENT_TYPE: MediaType.MUSIC,\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"http://198.51.100.20:8200/MediaItems/17621.mp3\"\n ),\n mp_const.ATTR_MEDIA_ENQUEUE: False,\n mp_const.ATTR_MEDIA_EXTRA: {\n \"title\": \"Mock song\",\n \"thumb\": \"http://198.51.100.20:8200/MediaItems/17621.jpg\",\n \"metadata\": {\"artist\": \"Mock artist\", \"album\": \"Mock album\"},\n },\n },\n blocking=True,\n )\n\n dmr_device_mock.construct_play_media_metadata.assert_awaited_once_with(\n media_url=\"http://198.51.100.20:8200/MediaItems/17621.mp3\",\n media_title=\"Mock song\",\n override_upnp_class=\"object.item.audioItem.musicTrack\",\n meta_data={\n \"artist\": \"Mock artist\",\n \"album\": \"Mock album\",\n \"album_art_uri\": \"http://198.51.100.20:8200/MediaItems/17621.jpg\",\n },\n )\n\n # Check again for a different media type\n dmr_device_mock.construct_play_media_metadata.reset_mock()\n await hass.services.async_call(\n MP_DOMAIN,\n mp_const.SERVICE_PLAY_MEDIA,\n {\n ATTR_ENTITY_ID: mock_entity_id,\n mp_const.ATTR_MEDIA_CONTENT_TYPE: MediaType.TVSHOW,\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"http://198.51.100.20:8200/MediaItems/123.mkv\"\n ),\n mp_const.ATTR_MEDIA_ENQUEUE: False,\n mp_const.ATTR_MEDIA_EXTRA: {\n \"title\": \"Mock show\",\n \"metadata\": {\"season\": 1, \"episode\": 12},\n },\n },\n blocking=True,\n )\n\n dmr_device_mock.construct_play_media_metadata.assert_awaited_once_with(\n media_url=\"http://198.51.100.20:8200/MediaItems/123.mkv\",\n media_title=\"Mock show\",\n override_upnp_class=\"object.item.videoItem.videoBroadcast\",\n meta_data={\"episodeSeason\": 1, \"episodeNumber\": 12},\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_setcontactmethod_noargs(self, shell):\n \"\"\"\n Test do_activationkey_setcontactmethod command triggers help on no args.\n \"\"\"\n shell.help_activationkey_setcontactmethod = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_setcontactmethod(shell, \"\")\n assert shell.help_activationkey_setcontactmethod.called\n assert not shell.client.activationkey.setDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n bind = check_obj(ClusterBind, {\"cluster\": cluster, \"id\": kwargs[\"bind_id\"]})\n check_custom_perm(request.user, \"view_import_of\", \"cluster\", cluster, \"view_clusterbind\")\n serializer = self.get_serializer(bind)\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def get_status(self, node_id: NodeID) -> Response:\n return await self.client.get(\n f\"/dynamic_services/{node_id}\", follow_redirects=True\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def get_url_scheme(url: str) -> Optional[str]:\n if \":\" not in url:\n return None\n return url.split(\":\", 1)[0].lower()", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def test_query(octopoes_api_connector: OctopoesAPIConnector, valid_time: datetime):\n network = Network(name=\"test\")\n octopoes_api_connector.save_declaration(Declaration(ooi=network, valid_time=valid_time))\n\n hostnames: list[OOI] = [Hostname(network=network.reference, name=f\"test{i}\") for i in range(10)]\n\n addresses = [IPAddressV6(network=network.reference, address=ip_address(\"3e4d:64a2:cb49:bd48:a1ba:def3:d15d:9230\"))]\n v4_addresses = [IPAddressV4(network=network.reference, address=ip_address(\"127.0.0.1\"))]\n ports = [\n IPPort(address=addresses[0].reference, protocol=\"tcp\", port=22),\n IPPort(address=v4_addresses[0].reference, protocol=\"tcp\", port=443),\n ]\n services = [Service(name=\"https\")]\n ip_services = [IPService(ip_port=ports[0].reference, service=services[0].reference)]\n\n dns_ns_records = [\n DNSNSRecord(hostname=hostnames[i].reference, name_server_hostname=hostnames[3].reference, value=\"test\")\n for i in range(3)\n ]\n dns_aaaa_records = [DNSAAAARecord(hostname=hostnames[3].reference, address=addresses[0].reference, value=\"test\")]\n dns_mx_records = [DNSMXRecord(hostname=hostnames[1].reference, mail_hostname=hostnames[3].reference, value=\"test\")]\n dns_a_records = [DNSARecord(hostname=hostnames[3].reference, address=v4_addresses[0].reference, value=\"test\")]\n sites = [Website(ip_service=ip_services[0].reference, hostname=hostnames[0].reference)]\n\n all_new_oois = (\n hostnames\n + addresses\n + v4_addresses\n + ports\n + services\n + ip_services\n + dns_ns_records\n + dns_a_records\n + dns_aaaa_records\n + dns_mx_records\n + sites\n )\n octopoes_api_connector.save_observation(\n Observation(\n method=\"normalizer_id\",\n source=network.reference,\n source_method=\"manual\",\n task_id=uuid.uuid4(),\n valid_time=valid_time,\n result=all_new_oois,\n )\n )\n\n octopoes_api_connector.save_many_scan_profiles(\n [DeclaredScanProfile(reference=ooi.reference, level=ScanLevel.L2) for ooi in all_new_oois + [network]],\n valid_time,\n )\n\n # Regarding these queries, we test the following relations:\n # websites[0] -{hostname}-> hostnames[0]\n # <-{hostname}- dns_ns_records[0] -{name_server_hostname}-> hostnames[3]\n # <-{hostname}- dns_aaa_records[0] -> ip_addresses[0]\n\n # Hostname -> Network\n query = \"Hostname.network\"\n results = octopoes_api_connector.query(query, valid_time)\n assert len(results) == 10\n\n # Website -> Hostname -> DNSNSRecord\n query = \"Website.hostname.<hostname[is DNSNSRecord]\"\n results = octopoes_api_connector.query(query, valid_time)\n assert len(results) == 1\n\n # Website -> Hostname -> DNSNSRecord -> Hostname -> DNSAAAARecord\n query = \"Website.hostname.<hostname[is DNSNSRecord].name_server_hostname.<hostname[is DNSAAAARecord].address\"\n results = octopoes_api_connector.query(query, valid_time)\n assert len(results) == 1\n assert str(results[0].address) == \"3e4d:64a2:cb49:bd48:a1ba:def3:d15d:9230\"\n\n # Regarding this query, we test the following relations:\n # -{mail_hostname}-> hostnames[3] <-{hostname}- dns_a_records[0]\n # -{address}-> v4_addresses[0] <-{address}- ip_ports[1]\n\n # Hostname -> DNSMXRecord -> Hostname -> DNSARecord -> IPAddress -> IPPort\n query = \"Hostname.<hostname[is DNSMXRecord].mail_hostname.<hostname[is DNSARecord].address.<address[is IPPort]\"\n results = octopoes_api_connector.query(query, valid_time)\n assert len(results) == 1\n assert str(results[0].port) == \"443\"\n\n results = octopoes_api_connector.query(query, valid_time, source=hostnames[0])\n assert len(results) == 0\n\n results = octopoes_api_connector.query(query, valid_time, source=hostnames[1])\n assert len(results) == 1\n\n query = \"Hostname.<hostname[is DNSNSRecord]\"\n assert len(octopoes_api_connector.query(query, valid_time, hostnames[0])) == 1\n assert len(octopoes_api_connector.query(query, valid_time, hostnames[1])) == 1\n assert len(octopoes_api_connector.query(query, valid_time, hostnames[2])) == 1\n assert len(octopoes_api_connector.query(query, valid_time, hostnames[3])) == 0\n\n result = octopoes_api_connector.query_many(\n query, valid_time, [hostnames[0], hostnames[1], hostnames[2], hostnames[3]]\n )\n assert len(result) == 3\n assert result[0][0] == hostnames[0].reference\n assert result[0][1] == dns_ns_records[0]", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "async def resolve_variables_from_context(\n variables_getters: dict[str, ContextGetter],\n context: ContextDict,\n *,\n resolve_in_parallel: bool = True,\n) -> dict[str, SubstitutionValue]:\n \"\"\"Resolves variables given a list of handlers and a context\n containing vars which can be used by the handlers.\n\n Arguments:\n variables_getters -- mapping of awaitables which resolve the value\n context -- variables which can be passed to the awaitables\n\n Keyword Arguments:\n resolve_in_parallel -- sometimes the variable_getters cannot be ran in parallel,\n for example due to race conditions,\n for those situations set to False (default: {True})\n \"\"\"\n # evaluate getters from context values\n pre_environs: dict[str, SubstitutionValue | RequestTuple] = {\n key: fun(context) for key, fun in variables_getters.items()\n }\n\n environs: dict[str, SubstitutionValue] = {}\n\n coros = {}\n for key, value in pre_environs.items():\n if isinstance(value, RequestTuple):\n handler, kwargs = value\n coro = handler(**kwargs)\n # extra wrap to control timeout\n coros[key] = asyncio.wait_for(coro, timeout=_HANDLERS_TIMEOUT)\n else:\n environs[key] = value\n\n # evaluates handlers\n values = await logged_gather(\n *coros.values(),\n max_concurrency=0 if resolve_in_parallel else 1,\n )\n for handler_key, handler_value in zip(coros.keys(), values, strict=True):\n environs[handler_key] = handler_value\n\n assert set(environs.keys()) == set(variables_getters.keys()) # nosec\n return environs", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def get(request, *args, **kwargs): # noqa: ARG001, ARG002, ARG004\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n check_custom_perm(request.user, \"view_import_of\", \"cluster\", cluster, \"view_clusterbind\")\n res = get_import(cluster)\n\n return Response(res)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def mock_disconnected_entity_id(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n config_entry_mock: MockConfigEntry,\n ssdp_scanner_mock: Mock,\n dmr_device_mock: Mock,\n) -> AsyncIterable[str]:\n \"\"\"Fixture to set up a mock DlnaDmrEntity in a disconnected state.\n\n Yields the entity ID. Cleans up the entity after the test is complete.\n \"\"\"\n # Cause the connection attempt to fail\n domain_data_mock.upnp_factory.async_create_device.side_effect = UpnpConnectionError\n config_entry_mock.add_to_hass(hass)\n entity_id = await setup_mock_component(hass, config_entry_mock)\n\n # Check the entity has registered all needed listeners\n assert len(config_entry_mock.update_listeners) == 1\n assert ssdp_scanner_mock.async_register_callback.await_count == 2\n assert ssdp_scanner_mock.async_register_callback.return_value.call_count == 0\n\n # The DmrDevice hasn't been instantiated yet\n assert domain_data_mock.async_get_event_notifier.await_count == 0\n assert domain_data_mock.async_release_event_notifier.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 0\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.on_event is None\n\n # Run the test\n yield entity_id\n\n # Unload config entry to clean up\n assert await hass.config_entries.async_remove(config_entry_mock.entry_id) == {\n \"require_restart\": False\n }\n\n # Check entity has cleaned up its resources\n assert not config_entry_mock.update_listeners\n assert (\n domain_data_mock.async_get_event_notifier.await_count\n == domain_data_mock.async_release_event_notifier.await_count\n )\n assert (\n ssdp_scanner_mock.async_register_callback.await_count\n == ssdp_scanner_mock.async_register_callback.return_value.call_count\n )\n assert (\n dmr_device_mock.async_subscribe_services.await_count\n == dmr_device_mock.async_unsubscribe_services.await_count\n )\n assert dmr_device_mock.on_event is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_get_triggers_rpc_device(\n hass: HomeAssistant, device_registry: dr.DeviceRegistry, mock_rpc_device: Mock\n) -> None:\n \"\"\"Test we get the expected triggers from a shelly RPC device.\"\"\"\n entry = await init_integration(hass, 2)\n device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0]\n\n expected_triggers = [\n {\n CONF_PLATFORM: \"device\",\n CONF_DEVICE_ID: device.id,\n CONF_DOMAIN: DOMAIN,\n CONF_TYPE: trigger_type,\n CONF_SUBTYPE: \"button1\",\n \"metadata\": {},\n }\n for trigger_type in (\n \"btn_down\",\n \"btn_up\",\n \"single_push\",\n \"double_push\",\n \"triple_push\",\n \"long_push\",\n )\n ]\n\n triggers = await async_get_device_automations(\n hass, DeviceAutomationType.TRIGGER, device.id\n )\n triggers = [value for value in triggers if value[\"domain\"] == DOMAIN]\n assert triggers == unordered(expected_triggers)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def check_last_audit_record(\n self,\n model: type[AuditLog | AuditSession] = AuditLog,\n *,\n expect_object_changes_: bool = True,\n **kwargs,\n ) -> AuditLog:\n last_audit_record = model.objects.order_by(\"pk\").last()\n self.assertIsNotNone(last_audit_record, f\"{model.__name__} table is empty\")\n\n # we always want to check who performed the audited action\n if model is AuditLog:\n kwargs.setdefault(\"user__username\", \"admin\")\n\n object_changes = kwargs.pop(\"object_changes\", {})\n\n expected_record = model.objects.filter(**kwargs).order_by(\"pk\").last()\n self.assertIsNotNone(expected_record, \"Can't find audit record\")\n self.assertEqual(last_audit_record.pk, expected_record.pk, \"Expected audit record is not last\")\n\n # Object changes are {} for most cases,\n # we always want to check it, but providing it each time is redundant.\n # But sometimes structure is too complex for sqlite/ORM to handle,\n # so we have to check changes separately.\n #\n # Check is on equality after retrieve for more clear message\n # and to avoid object changes filtering\n if (model is AuditLog) and expect_object_changes_:\n self.assertDictEqual(expected_record.object_changes, object_changes)\n\n return last_audit_record", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def test_check_warnings():\n warnings = [\n {\n \"general\": \"hot beverage\",\n \"error\": \"explosive\"\n }\n ]\n XCCDFStructure = collections.namedtuple(\"XCCDFStructure\", \"warnings\")\n s = XCCDFStructure(warnings=warnings)\n with pytest.raises(ValueError) as e:\n ssg.build_yaml.check_warnings(s)\n msg = \"Only one key/value pair should exist for each warnings dictionary\"\n assert msg in str(e)", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_write_buffer_write_unsigned_short_bit_big_endian_full(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN)\n wb.write_bit(True)\n wb.write_bit(False)\n wb.write_unsigned_short(0xFFFF, 14)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"10111111 11111111\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "async def test_create_and_delete_solver_job(\n auth: httpx.BasicAuth,\n client: httpx.AsyncClient,\n solver_key: str,\n solver_version: str,\n mocked_backend_services_apis_for_create_and_delete_solver_job: MockedBackendApiDict,\n):\n # create Job\n resp = await client.post(\n f\"/{API_VTAG}/solvers/{solver_key}/releases/{solver_version}/jobs\",\n auth=auth,\n json=JobInputs(\n values={\n \"x\": 3.14,\n \"n\": 42,\n }\n ).dict(),\n )\n assert resp.status_code == status.HTTP_201_CREATED\n job = Job.parse_obj(resp.json())\n\n # Delete Job after creation\n resp = await client.delete(\n f\"/{API_VTAG}/solvers/{solver_key}/releases/{solver_version}/jobs/{job.id}\",\n auth=auth,\n )\n assert resp.status_code == status.HTTP_204_NO_CONTENT\n\n mock_webserver_router = (\n mocked_backend_services_apis_for_create_and_delete_solver_job[\"webserver\"]\n )\n assert mock_webserver_router\n assert mock_webserver_router[\"delete_project\"].called\n\n mock_catalog_router = mocked_backend_services_apis_for_create_and_delete_solver_job[\n \"catalog\"\n ]\n assert mock_catalog_router\n assert mock_catalog_router[\"get_service\"].called\n\n # NOTE: ideas for further tests\n # Run job and try to delete while running\n # Run a job and delete when finished", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def test_update_entity(hass: HomeAssistant, knx: KNXTestKit) -> None:\n \"\"\"Test update climate entity for KNX.\"\"\"\n await knx.setup_integration(\n {\n ClimateSchema.PLATFORM: {\n CONF_NAME: \"test\",\n ClimateSchema.CONF_TEMPERATURE_ADDRESS: \"1/2/3\",\n ClimateSchema.CONF_TARGET_TEMPERATURE_ADDRESS: \"1/2/4\",\n ClimateSchema.CONF_TARGET_TEMPERATURE_STATE_ADDRESS: \"1/2/5\",\n ClimateSchema.CONF_OPERATION_MODE_ADDRESS: \"1/2/6\",\n ClimateSchema.CONF_OPERATION_MODE_STATE_ADDRESS: \"1/2/7\",\n }\n }\n )\n assert await async_setup_component(hass, \"homeassistant\", {})\n\n # read states state updater\n await knx.assert_read(\"1/2/3\")\n await knx.assert_read(\"1/2/5\")\n # StateUpdater initialize state\n await knx.receive_response(\"1/2/3\", RAW_FLOAT_21_0)\n await knx.receive_response(\"1/2/5\", RAW_FLOAT_22_0)\n await knx.assert_read(\"1/2/7\")\n await knx.receive_response(\"1/2/7\", (0x01,))\n\n # verify update entity retriggers group value reads to the bus\n await hass.services.async_call(\n \"homeassistant\",\n \"update_entity\",\n target={\"entity_id\": \"climate.test\"},\n blocking=True,\n )\n\n await knx.assert_read(\"1/2/3\")\n await knx.assert_read(\"1/2/5\")\n await knx.assert_read(\"1/2/7\")", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_completer_ak_addpackages(self, shell):\n \"\"\"\n Test tab completer activation keys on addpackages.\n \"\"\"\n text = \"Communications satellite used by the military for star wars.\"\n completer = MagicMock()\n with patch(\"spacecmd.activationkey.tab_completer\", completer):\n spacecmd.activationkey.complete_activationkey_addpackages(shell, text, \"do this\", None, None)\n assert completer.called\n call_id, ret_text = completer.call_args_list[0][0]\n assert call_id == \"do_activation_list\"\n assert ret_text == text", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_get_pools_by_order_enquiry(\n store_with_multiple_pools_for_customer: Store, pool_order_1: str\n):\n \"\"\"Test that pools can be fetched from the store by customer id.\"\"\"\n # GIVEN a database with two pools\n\n # WHEN getting pools by customer id\n pools: list[Pool] = store_with_multiple_pools_for_customer.get_pools_by_order_enquiry(\n order_enquiry=pool_order_1\n )\n\n # THEN one pool should be returned\n assert len(pools) == 1", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def _create(context: ContextDict):\n # NOTE: we could delay this as well ...\n kwargs_from_context = {\n param.name: factory_context_getter(param.name)(context)\n for param in inspect.signature(coro).parameters.values()\n }\n return RequestTuple(handler=coro, kwargs=kwargs_from_context)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def extract_generic_filepath(file_path: str | None) -> str | None:\n \"\"\"Remove a file's suffix and identifying integer or X/Y\n Example:\n `/some/path/gatkcomb_rhocall_vt_af_chromograph_sites_X.png` becomes\n `/some/path/gatkcomb_rhocall_vt_af_chromograph_sites_`\"\"\"\n if file_path is None:\n return file_path\n return re.split(\"(\\d+|X|Y)\\.png\", file_path)[0]", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_extract_entity_ids(hass: HomeAssistant) -> None:\n \"\"\"Test extract_entity_ids method.\"\"\"\n hass.states.async_set(\"light.Bowl\", STATE_ON)\n hass.states.async_set(\"light.Ceiling\", STATE_OFF)\n hass.states.async_set(\"light.Kitchen\", STATE_OFF)\n\n assert await async_setup_component(hass, \"group\", {})\n await hass.async_block_till_done()\n await Group.async_create_group(\n hass,\n \"test\",\n created_by_service=False,\n entity_ids=[\"light.Ceiling\", \"light.Kitchen\"],\n icon=None,\n mode=None,\n object_id=None,\n order=None,\n )\n\n call = ServiceCall(\"light\", \"turn_on\", {ATTR_ENTITY_ID: \"light.Bowl\"})\n\n assert {\"light.bowl\"} == await service.async_extract_entity_ids(hass, call)\n\n call = ServiceCall(\"light\", \"turn_on\", {ATTR_ENTITY_ID: \"group.test\"})\n\n assert {\"light.ceiling\", \"light.kitchen\"} == await service.async_extract_entity_ids(\n hass, call\n )\n\n assert {\"group.test\"} == await service.async_extract_entity_ids(\n hass, call, expand_group=False\n )\n\n assert (\n await service.async_extract_entity_ids(\n hass,\n ServiceCall(\"light\", \"turn_on\", {ATTR_ENTITY_ID: ENTITY_MATCH_NONE}),\n )\n == set()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:\n \"\"\"Handle options update.\"\"\"\n await hass.config_entries.async_reload(entry.entry_id)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def get_template_sources(self, template_name):\n \"\"\"\n Return an Origin object pointing to an absolute path in each directory\n in template_dirs. For security reasons, if a path doesn't lie inside\n one of the template_dirs it is excluded from the result set.\n \"\"\"\n for template_dir in self.get_dirs():\n try:\n name = safe_join(template_dir, template_name)\n except SuspiciousFileOperation:\n # The joined path was located outside of this template_dir\n # (it might be inside another one, so this isn't fatal).\n continue\n\n yield Origin(\n name=name,\n template_name=template_name,\n loader=self,\n )", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def quality_control(self, case_metrics_file_path: Path) -> QualityResult:\n quality_metrics: QualityMetrics = MetricsParser.parse(case_metrics_file_path)\n sample_results: list[SampleQualityResult] = self.quality_control_samples(quality_metrics)\n case_result: CaseQualityResult = quality_control_case(sample_results)\n report_file: Path = get_report_path(case_metrics_file_path)\n ReportGenerator.report(out_file=report_file, samples=sample_results, case=case_result)\n ResultLogger.log_results(case=case_result, samples=sample_results, report=report_file)\n summary: str = ReportGenerator.get_summary(\n case=case_result, samples=sample_results, report_path=report_file\n )\n return QualityResult(case=case_result, samples=sample_results, summary=summary)", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def current_temperature(self) -> float | None:\n \"\"\"Return current temperature.\"\"\"\n return cast(float, self.status[\"current_C\"])", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_random01(self):\n output = self.engine.render_to_string(\n \"random01\", {\"a\": [\"a&b\", \"a&b\"], \"b\": [mark_safe(\"a&b\"), mark_safe(\"a&b\")]}\n )\n self.assertEqual(output, \"a&amp;b a&b\")", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def async_added_to_hass(self) -> None:\n \"\"\"Subscribe to needed data on add.\"\"\"\n await super().async_added_to_hass()\n self.router.subscriptions[self.key].append(f\"{SELECT_DOMAIN}/{self.item}\")", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_available_device(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test a DlnaDmrEntity with a connected DmrDevice.\"\"\"\n # Check hass device information is filled in\n await async_update_entity(hass, mock_entity_id)\n await hass.async_block_till_done()\n dev_reg = async_get_dr(hass)\n device = dev_reg.async_get_device(\n connections={(CONNECTION_UPNP, MOCK_DEVICE_UDN)},\n identifiers=set(),\n )\n assert device is not None\n # Device properties are set in dmr_device_mock before the entity gets constructed\n assert device.manufacturer == \"device_manufacturer\"\n assert device.model == \"device_model_name\"\n assert device.name == \"device_name\"\n\n # Check entity state gets updated when device changes state\n for dev_state, ent_state in [\n (None, MediaPlayerState.ON),\n (TransportState.STOPPED, MediaPlayerState.IDLE),\n (TransportState.PLAYING, MediaPlayerState.PLAYING),\n (TransportState.TRANSITIONING, MediaPlayerState.PLAYING),\n (TransportState.PAUSED_PLAYBACK, MediaPlayerState.PAUSED),\n (TransportState.PAUSED_RECORDING, MediaPlayerState.PAUSED),\n (TransportState.RECORDING, MediaPlayerState.IDLE),\n (TransportState.NO_MEDIA_PRESENT, MediaPlayerState.IDLE),\n (TransportState.VENDOR_DEFINED, ha_const.STATE_UNKNOWN),\n ]:\n dmr_device_mock.profile_device.available = True\n dmr_device_mock.transport_state = dev_state\n await async_update_entity(hass, mock_entity_id)\n entity_state = hass.states.get(mock_entity_id)\n assert entity_state is not None\n assert entity_state.state == ent_state\n\n dmr_device_mock.profile_device.available = False\n dmr_device_mock.transport_state = TransportState.PLAYING\n await async_update_entity(hass, mock_entity_id)\n entity_state = hass.states.get(mock_entity_id)\n assert entity_state is not None\n assert entity_state.state == ha_const.STATE_UNAVAILABLE", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_write_buffer_set_unsigned_byte_little_endian_niblet(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN)\n wb.write_unsigned_byte(0x12, 4)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00100000\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def test_is_fresh_freshness(empty_cloud_context_fluent):\n # Ephemeral/file use a cacheable datasource dict so freshness\n # with batch definitions is a Cloud-only concern\n context = empty_cloud_context_fluent\n batch_definition = (\n context.data_sources.add_pandas(name=\"my_pandas_ds\")\n .add_csv_asset(name=\"my_csv_asset\", filepath_or_buffer=\"data.csv\")\n .add_batch_definition(name=\"my_batch_def\")\n )\n\n batching_regex = re.compile(r\"data_(?P<year>\\d{4})-(?P<month>\\d{2}).csv\")\n partitioner = FileNamePartitionerYearly(regex=batching_regex)\n batch_definition.partitioner = partitioner\n\n diagnostics = batch_definition.is_fresh()\n assert diagnostics.success is False\n assert len(diagnostics.errors) == 1\n assert isinstance(diagnostics.errors[0], BatchDefinitionNotFreshError)", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def get_instances(test_name: str):\n return {\n INSTANCE_NAME: {\n \"args\": [\"--bolt-port=7687\", \"--log-level=TRACE\", \"--data-recovery-on-startup=true\"],\n \"log_file\": f\"{get_logs_path(file, test_name)}/test_instance.log\",\n \"data_directory\": f\"{get_data_path(file, test_name)}\",\n \"setup_queries\": [],\n }\n }", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def reset_balance(node, discardaddr):\n '''Throw away all owned coins by the node so it gets a balance of 0.'''\n balance = node.getbalance(avoid_reuse=False)\n if balance > 0.5:\n node.sendtoaddress(address=discardaddr, amount=balance, subtractfeefromamount=True, avoid_reuse=False)", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def native_value(self) -> float | int | None:\n \"\"\"Return the state of the device.\"\"\"\n return self.roller.battery # type: ignore[no-any-return]", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def run(self, scenario, group_name, scenario_name, runner):\n runner.start()\n\n log.info(\"Executing setup\")\n runner.setup(scenario.get(\"setup\")())\n\n config = next(scenario.get(\"config\")())\n duration = config[\"duration\"]\n if self.args.duration:\n duration = self.args.duration\n log.info(\"Executing run for {} seconds\".format(\n duration))\n results = runner.run(next(scenario.get(\"run\")()), duration, config[\"client\"])\n\n runner.stop()\n\n measurements = []\n summary_format = \"{:>15} {:>22} {:>22}\\n\"\n self.summary = summary_format.format(\n \"elapsed_time\", \"num_executed_queries\", \"num_executed_steps\")\n for result in results:\n self.summary += summary_format.format(\n result[\"elapsed_time\"], result[\"num_executed_queries\"],\n result[\"num_executed_steps\"])\n measurements.append({\n \"target\": \"throughput\",\n \"time\": result[\"elapsed_time\"],\n \"value\": result[\"num_executed_queries\"],\n \"steps\": result[\"num_executed_steps\"],\n \"unit\": \"number of executed queries\",\n \"type\": \"throughput\"})\n self.summary += \"\\n\\nThroughput: \" + str(measurements[-1][\"value\"])\n self.summary += \"\\nExecuted steps: \" + str(measurements[-1][\"steps\"])\n return measurements", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def test_do_activationkey_removegroups_help_args(self, shell):\n \"\"\"\n Test remove groups method call shows help if only one argument is passed.\n \"\"\"\n shell.help_activationkey_removegroups = MagicMock()\n shell.client.activationkey.removeServerGroups = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removegroups(shell, \"key\")\n assert shell.help_activationkey_removegroups.called\n assert not shell.client.activationkey.removeServerGroups.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def simulate_finished_task(\n self, object_: Cluster | ClusterObject | ServiceComponent, action: Action\n ) -> (TaskLog, JobLog):\n with RunTaskMock() as run_task:\n (self.client.v2[object_] / \"actions\" / action / \"run\").post(\n data={\"configuration\": None, \"isVerbose\": True, \"hostComponentMap\": []}\n )\n\n run_task.run()\n run_task.target_task.refresh_from_db()\n\n return run_task.target_task, run_task.target_task.joblog_set.last()", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def getsearchdirs() -> tuple[list[str], list[str]]:\n return (getsyspath(), getsitepackages())", "smellKey": "0", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "async def test_aiohttp_client_frozen_router_view(\n hass: HomeAssistant,\n hass_client: ClientSessionGenerator,\n) -> None:\n \"\"\"Test aiohttp_client fixture patches frozen router for views.\"\"\"\n assert await async_setup_component(hass, \"http\", {})\n await hass.async_block_till_done()\n\n # Registering the view after starting the server should still work.\n client = await hass_client()\n register_view(hass)\n\n response = await client.get(\"/api/test\")\n assert response.status == HTTPStatus.OK\n result = await response.json()\n assert result[\"test\"] is True", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:\n \"\"\"Resolve selected Radio station to a streaming URL.\"\"\"\n radios = self.radios\n\n station = await radios.station(uuid=item.identifier)\n if not station:\n raise Unresolvable(\"Radio station is no longer available\")\n\n if not (mime_type := self._async_get_station_mime_type(station)):\n raise Unresolvable(\"Could not determine stream type of radio station\")\n\n # Register \"click\" with Radio Browser\n await radios.station_click(uuid=station.uuid)\n\n return PlayMedia(station.url, mime_type)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def periodic_send_meter_readings_application_reminder() -> None:\n create_meter_readings_application_reminder()", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def update_data(self, data):\n \"\"\"Mark the device as seen.\"\"\"\n self._data = data\n if self.hass:\n self.async_write_ha_state()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_case(self, case_id: str) -> dict | None:\n \"\"\"Return a case found in Loqusdb.\"\"\"\n cases_parameters = [\"cases\", \"-c\", case_id, \"--to-json\"]\n self.process.run_command(parameters=cases_parameters)\n if not self.process.stdout: # Case not in loqusdb, stdout of loqusdb command will be empty.\n LOG.info(f\"Case {case_id} not found in {repr(self)}\")\n return None\n\n return ReadStream.get_content_from_stream(\n file_format=FileFormat.JSON, stream=self.process.stdout\n )[0]", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_get_application_by_case(case_id: str, rml_pool_store: Store):\n \"\"\"Test that the correct application is returned on a case.\"\"\"\n # GIVEN a case with a sample with an application version\n application_version: ApplicationVersion = (\n rml_pool_store.get_case_by_internal_id(internal_id=case_id)\n .links[0]\n .sample.application_version\n )\n\n # WHEN the application is fetched from the case\n application: Application = rml_pool_store.get_application_by_case(case_id=case_id)\n\n # THEN the fetched application should be equal to the application version application\n assert application_version.application == application", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_subscribe_forecast_unsupported(\n hass: HomeAssistant,\n hass_ws_client: WebSocketGenerator,\n config_flow_fixture: None,\n) -> None:\n \"\"\"Test multiple forecast.\"\"\"\n\n class MockWeatherMock(MockWeatherTest):\n \"\"\"Mock weather class.\"\"\"\n\n kwargs = {\n \"native_temperature\": 38,\n \"native_temperature_unit\": UnitOfTemperature.CELSIUS,\n }\n weather_entity = await create_entity(hass, MockWeatherMock, None, **kwargs)\n client = await hass_ws_client(hass)\n\n await client.send_json_auto_id(\n {\n \"type\": \"weather/subscribe_forecast\",\n \"forecast_type\": \"daily\",\n \"entity_id\": weather_entity.entity_id,\n }\n )\n msg = await client.receive_json()\n assert not msg[\"success\"]\n assert msg[\"error\"] == {\n \"code\": \"forecast_not_supported\",\n \"message\": \"The weather entity does not support forecast type: daily\",\n }", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_orders_mip_dna_and_limit_filter(\n store: Store,\n order: Order,\n order_another: Order,\n order_balsamic: Order,\n limit: int | None,\n expected_returned: int,\n):\n # GIVEN a store with three orders, two of which are MIP-DNA orders\n orders_request = OrdersRequest(workflow=Workflow.MIP_DNA, pageSize=limit)\n # WHEN fetching only MIP-DNA orders\n orders, _ = store.get_orders(orders_request)\n\n # THEN we should get the expected number of orders returned\n assert len(orders) == expected_returned", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_write_buffer_get_pos(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(10, ByteOrder.LITTLE_ENDIAN)\n pos: int = wb.get_pos()\n assert 0 == pos", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def update_found_by_for_findings(sender, instance, **kwargs):\n with contextlib.suppress(sender.DoesNotExist):\n obj = sender.objects.get(pk=instance.pk)\n # Check if the test type has changed\n if obj.test_type != instance.test_type:\n # Save a reference to the old test type ID to replace with the new one\n old_test_type = obj.test_type\n new_test_type = instance.test_type\n # Get all the findings in this test\n findings = Finding.objects.filter(test=instance)\n # Update each of the findings found by column\n for find in findings:\n find.found_by.remove(old_test_type)\n find.found_by.add(new_test_type)", "smellKey": "0", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def _build_float_rule() -> Rule:\n \"\"\"\n This method builds \"Rule\" object configured to emit \"ExpectationConfiguration\" objects for column \"Domain\" type.\n\n This rule holds expectations which are associated with the float metrics in the data profiler report. There\n are additional rules which are planned to be created, such as timestamp_rule, text_rule, categorical_rule, etc.\n Currently, the float_rule uses DataProfilerColumnDomainBuilder, so it doesn't discriminate by data type when applying the\n rule.\n \"\"\"\n data_profiler_column_domain_builder: DomainBuilder = DataProfilerColumnDomainBuilder()\n\n data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_metric_single_batch_parameter_builder(\n metric_name=\"data_profiler.column_profile_report\",\n suffix=None,\n metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,\n metric_value_kwargs={\n \"profile_path\": f\"{VARIABLES_KEY}profile_path\",\n },\n )\n\n data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations: ParameterBuilder = data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics\n\n validation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]\n\n validation_parameter_builder_configs = [\n ParameterBuilderConfig(\n **data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.to_json_dict(),\n ),\n ]\n expect_column_min_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(\n expectation_type=\"expect_column_min_to_be_between\",\n validation_parameter_builder_configs=validation_parameter_builder_configs,\n column=f\"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column\",\n min_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.min\",\n max_value=None,\n strict_min=f\"{VARIABLES_KEY}strict_min\",\n strict_max=None,\n meta={\n \"profiler_details\": f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}\",\n },\n )\n\n expect_column_max_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(\n expectation_type=\"expect_column_max_to_be_between\",\n validation_parameter_builder_configs=validation_parameter_builder_configs,\n column=f\"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column\",\n min_value=None,\n max_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.max\",\n strict_min=None,\n strict_max=f\"{VARIABLES_KEY}strict_max\",\n meta={\n \"profiler_details\": f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}\",\n },\n )\n\n expect_column_mean_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(\n expectation_type=\"expect_column_mean_to_be_between\",\n validation_parameter_builder_configs=validation_parameter_builder_configs,\n column=f\"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column\",\n min_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.mean\",\n max_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.mean\",\n strict_min=f\"{VARIABLES_KEY}strict_min\",\n strict_max=f\"{VARIABLES_KEY}strict_max\",\n meta={\n \"profiler_details\": f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}\",\n },\n )\n\n expect_column_stddev_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(\n expectation_type=\"expect_column_stdev_to_be_between\",\n validation_parameter_builder_configs=validation_parameter_builder_configs,\n column=f\"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column\",\n min_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.std\",\n max_value=f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.std\",\n strict_min=f\"{VARIABLES_KEY}strict_min\",\n strict_max=f\"{VARIABLES_KEY}strict_max\",\n meta={\n \"profiler_details\": f\"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}\",\n },\n )\n\n variables: dict = {\n \"strict_min\": False,\n \"strict_max\": False,\n \"profile_path\": \"default_profiler_path\",\n \"profile_report_filtering_key\": \"data_type\",\n \"profile_report_accepted_filtering_values\": [\"float\"],\n }\n\n parameter_builders: List[ParameterBuilder] = [\n data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics,\n ]\n\n expectation_configuration_builders: List[ExpectationConfigurationBuilder] = [\n expect_column_min_to_be_between_expectation_configuration_builder,\n expect_column_max_to_be_between_expectation_configuration_builder,\n expect_column_mean_to_be_between_expectation_configuration_builder,\n expect_column_stddev_to_be_between_expectation_configuration_builder,\n ]\n\n rule = Rule(\n name=\"float_rule\",\n variables=variables,\n domain_builder=data_profiler_column_domain_builder,\n parameter_builders=parameter_builders,\n expectation_configuration_builders=expectation_configuration_builders,\n )\n\n return rule", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def periodic_update_redcert_certificates() -> None:\n update_redcert_certificates(email=True)", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def link(self) -> Optional[Link]:\n \"\"\"Returns the underlying link, if there's one.\"\"\"\n raise NotImplementedError()", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def test_coordinates_function_device_tracker_from_input_select(\n hass: HomeAssistant,\n) -> None:\n \"\"\"Test coordinates function.\"\"\"\n hass.states.async_set(\n \"input_select.select\",\n \"device_tracker.device\",\n {\"options\": \"device_tracker.device\"},\n )\n hass.states.async_set(\"device_tracker.device\", \"32.87336,-117.22943\")\n assert (\n location.find_coordinates(hass, \"input_select.select\") == \"32.87336,-117.22943\"\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def _async_create_session(self, code):\n \"\"\"Create point session and entries.\"\"\"\n\n flow = self.hass.data[DATA_FLOW_IMPL][DOMAIN]\n client_id = flow[CONF_CLIENT_ID]\n client_secret = flow[CONF_CLIENT_SECRET]\n point_session = PointSession(\n async_get_clientsession(self.hass),\n client_id,\n client_secret,\n )\n token = await point_session.get_access_token(code)\n _LOGGER.debug(\"Got new token\")\n if not point_session.is_authorized:\n _LOGGER.error(\"Authentication Error\")\n return self.async_abort(reason=\"auth_error\")\n\n _LOGGER.info(\"Successfully authenticated Point\")\n user_email = (await point_session.user()).get(\"email\") or \"\"\n\n return self.async_create_entry(\n title=user_email,\n data={\n \"token\": token,\n \"refresh_args\": {\n CONF_CLIENT_ID: client_id,\n CONF_CLIENT_SECRET: client_secret,\n },\n },\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_reauth_success(\n hass: HomeAssistant, mock_config_entry: MockConfigEntry\n) -> None:\n \"\"\"Successful reauth flow initialized by the user.\"\"\"\n result = await mock_config_entry.start_reauth_flow(hass)\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] == {}\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={CONF_PASSWORD: \"other_fake_password\"},\n )\n\n assert result[\"type\"] is FlowResultType.ABORT\n assert result[\"reason\"] == \"reauth_successful\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def requirements_to_install(self) -> List[InstallRequirement]:\n \"\"\"Return the list of requirements that need to be installed.\n\n TODO remove this property together with the legacy resolver, since the new\n resolver only returns requirements that need to be installed.\n \"\"\"\n return [\n install_req\n for install_req in self.all_requirements\n if not install_req.constraint and not install_req.satisfied_by\n ]", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "async def test_image_update_unavailable(\n hass: HomeAssistant,\n fc_class_mock,\n fh_class_mock,\n) -> None:\n \"\"\"Test image update when fritzbox is unavailable.\"\"\"\n\n # setup component with image platform only\n with patch(\n \"homeassistant.components.fritz.PLATFORMS\",\n [Platform.IMAGE],\n ):\n entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n\n await hass.async_block_till_done()\n assert entry.state is ConfigEntryState.LOADED\n\n state = hass.states.get(\"image.mock_title_guestwifi\")\n assert state\n\n # fritzbox becomes unavailable\n fc_class_mock().call_action_side_effect(ReadTimeout)\n async_fire_time_changed(hass, utcnow() + timedelta(seconds=60))\n await hass.async_block_till_done(wait_background_tasks=True)\n\n state = hass.states.get(\"image.mock_title_guestwifi\")\n assert state.state == STATE_UNKNOWN\n\n # fritzbox is available again\n fc_class_mock().call_action_side_effect(None)\n async_fire_time_changed(hass, utcnow() + timedelta(seconds=60))\n await hass.async_block_till_done(wait_background_tasks=True)\n\n state = hass.states.get(\"image.mock_title_guestwifi\")\n assert state.state != STATE_UNKNOWN", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(\n self, device: RingStickUpCam, coordinator: RingDataCoordinator, device_type: str\n ) -> None:\n \"\"\"Initialize the switch.\"\"\"\n super().__init__(device, coordinator)\n self._device_type = device_type\n self._attr_unique_id = f\"{self._device.id}-{self._device_type}\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_call_with_omit_entity_id(\n hass: HomeAssistant, mock_handle_entity_call, mock_entities\n) -> None:\n \"\"\"Check service call if we do not pass an entity ID.\"\"\"\n await service.entity_service_call(\n hass,\n mock_entities,\n Mock(),\n ServiceCall(\"test_domain\", \"test_service\"),\n )\n\n assert len(mock_handle_entity_call.mock_calls) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def register_from_context(self, name: str, context_name: str):\n self.register({name: factory_context_getter(context_name)})", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_write_buffer_set_bit_get_pos_dual(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN)\n wb.write_bit(True)\n wb.write_bit(True)\n pos: int = wb.get_pos()\n assert pos == 2", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def unique_id(self):\n \"\"\"Return a unique identifier.\"\"\"\n return f\"occupancygroup_{self._bridge_unique_id}_{self.device_id}\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def is_qc_required(self, case_run_dir: Path) -> bool:\n if not case_run_dir:\n LOG.warning(f\"Skipping QC, run directory {case_run_dir} does not exist.\")\n return False\n qc_done_path: Path = case_run_dir.joinpath(QUALITY_REPORT_FILE_NAME)\n qc_already_done: bool = qc_done_path.exists()\n if qc_already_done:\n LOG.warning(f\"Skipping QC, report {qc_done_path} already exists.\")\n return not qc_done_path.exists()", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_entity(hass: HomeAssistant) -> None:\n \"\"\"Test entity attributes.\"\"\"\n assert hass.states.get(ENTITY_ID)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_device_class_units(\n hass: HomeAssistant, hass_ws_client: WebSocketGenerator\n) -> None:\n \"\"\"Test we can get supported units.\"\"\"\n assert await async_setup_component(hass, DOMAIN, {})\n\n client = await hass_ws_client(hass)\n\n await client.send_json(\n {\n \"id\": 1,\n \"type\": \"weather/convertible_units\",\n }\n )\n msg = await client.receive_json()\n assert msg[\"success\"]\n assert msg[\"result\"] == {\n \"units\": {\n \"precipitation_unit\": [\"in\", \"mm\"],\n \"pressure_unit\": [\"hPa\", \"inHg\", \"mbar\", \"mmHg\"],\n \"temperature_unit\": [\"\u00b0C\", \"\u00b0F\"],\n \"visibility_unit\": [\"km\", \"mi\"],\n \"wind_speed_unit\": [\"ft/s\", \"km/h\", \"kn\", \"m/s\", \"mph\"],\n }\n }", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def setUp(self):\n self.composite = CompositePreValidator()\n self.composite.add_validator(PreHeaderValidator())", "smellKey": "0", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def test_do_activationkey_export_filename_arg(self, shell):\n \"\"\"\n Test do_activationkey_export exports to 'akey_all.json' if not specified otherwise.\n \"\"\"\n logger = MagicMock()\n shell.do_activationkey_list = MagicMock(return_value=[\"one\", \"two\", \"three\"])\n shell.export_activationkey_getdetails = MagicMock(side_effect=[{}, {}, {}])\n shell.client.activationkey.checkConfigDeployment = MagicMock(return_value=True)\n\n with patch(\"spacecmd.activationkey.logging\", logger):\n spacecmd.activationkey.do_activationkey_export(shell, \"-f somefile.json\")\n\n assert logger.debug.called\n assert logger.error.called\n assert logger.info.called\n\n assert logger.error.call_args_list[0][0][0] == \"Failed to save exported keys to file: somefile.json\"\n assert logger.debug.call_args_list[0][0][0] == \"Passed filename do_activationkey_export somefile.json\"\n\n expectation = [\n 'Exporting ALL activation keys to somefile.json',\n 'Exporting key one to somefile.json',\n 'Exporting key two to somefile.json',\n 'Exporting key three to somefile.json',\n ]\n for idx, call in enumerate(logger.info.call_args_list):\n assert call[0][0] == expectation[idx]", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def latest_version(self) -> str | None:\n \"\"\"Latest version available for install.\"\"\"\n if self.coordinator.update_available:\n return self.coordinator.latest_firmware\n return self.coordinator.current_firmware", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def config_case(context: CGConfig, case_id: str, dry_run: bool) -> None:\n \"\"\"Create config files required by a workflow for a case.\"\"\"\n analysis_api: NfAnalysisAPI = context.meta_apis[MetaApis.ANALYSIS_API]\n try:\n analysis_api.config_case(case_id=case_id, dry_run=dry_run)\n except (CgError, ValidationError) as error:\n LOG.error(f\"Could not create config files for {case_id}: {error}\")\n raise click.Abort() from error", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_async_setup_entry(\n hass: HomeAssistant, mock_accuweather_client: AsyncMock\n) -> None:\n \"\"\"Test a successful setup entry.\"\"\"\n await init_integration(hass)\n\n state = hass.states.get(\"weather.home\")\n assert state is not None\n assert state.state != STATE_UNAVAILABLE\n assert state.state == \"sunny\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_ssdp_bootid(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n mock_disconnected_entity_id: str,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test an alive with a new BOOTID.UPNP.ORG header causes a reconnect.\"\"\"\n # Start with a disconnected device\n entity_id = mock_disconnected_entity_id\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == ha_const.STATE_UNAVAILABLE\n\n # \"Reconnect\" the device\n domain_data_mock.upnp_factory.async_create_device.side_effect = None\n\n # Send SSDP alive with boot ID\n ssdp_callback = ssdp_scanner_mock.async_register_callback.call_args.args[0].target\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"1\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_subscribe_services.call_count == 1\n assert dmr_device_mock.async_unsubscribe_services.call_count == 0\n\n # Send SSDP alive with same boot ID, nothing should happen\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"1\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_subscribe_services.call_count == 1\n assert dmr_device_mock.async_unsubscribe_services.call_count == 0\n\n # Send a new SSDP alive with an incremented boot ID, device should be dis/reconnected\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"2\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_subscribe_services.call_count == 2\n assert dmr_device_mock.async_unsubscribe_services.call_count == 1", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Add Airzone sensors from a config_entry.\"\"\"\n coordinator = hass.data[DOMAIN][entry.entry_id]\n\n sensors: list[AirzoneSensor] = [\n AirzoneZoneSensor(\n coordinator,\n description,\n entry,\n system_zone_id,\n zone_data,\n )\n for system_zone_id, zone_data in coordinator.data[AZD_ZONES].items()\n for description in ZONE_SENSOR_TYPES\n if description.key in zone_data\n ]\n\n if AZD_HOT_WATER in coordinator.data:\n sensors.extend(\n AirzoneHotWaterSensor(\n coordinator,\n description,\n entry,\n )\n for description in HOT_WATER_SENSOR_TYPES\n if description.key in coordinator.data[AZD_HOT_WATER]\n )\n\n if AZD_WEBSERVER in coordinator.data:\n sensors.extend(\n AirzoneWebServerSensor(\n coordinator,\n description,\n entry,\n )\n for description in WEBSERVER_SENSOR_TYPES\n if description.key in coordinator.data[AZD_WEBSERVER]\n )\n\n async_add_entities(sensors)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def client(\n mock_static_webserver: None,\n app_environment: EnvVarsDict,\n event_loop: asyncio.AbstractEventLoop,\n aiohttp_client: Callable,\n app_cfg: ConfigDict,\n postgres_db: sa.engine.Engine,\n monkeypatch_setenv_from_app_config: Callable,\n) -> TestClient:\n cfg = deepcopy(app_cfg)\n\n port = cfg[\"main\"][\"port\"]\n\n assert cfg[\"rest\"][\"version\"] == API_VTAG\n monkeypatch_setenv_from_app_config(cfg)\n\n # fake config\n app = create_safe_application(cfg)\n\n settings = setup_settings(app)\n print(settings.json(indent=1))\n\n setup_rest(app)\n setup_db(app)\n setup_products(app)\n setup_statics(app)\n\n return event_loop.run_until_complete(\n aiohttp_client(app, server_kwargs={\"port\": port, \"host\": \"localhost\"})\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def add_lot(request, entity):\n d = get_prefetched_data(entity)\n lot_data = request.POST.dict()\n\n lot, errors = construct_carbure_lot(d, entity, lot_data)\n if not lot:\n return ErrorResponse(400, AddLotError.LOT_CREATION_FAILED)\n\n # run sanity checks, insert lot and errors\n with transaction.atomic():\n lots_created = bulk_insert_lots(entity, [lot], [errors], d)\n\n if len(lots_created) == 0:\n return ErrorResponse(400, AddLotError.LOT_CREATION_FAILED)\n\n background_bulk_scoring(lots_created)\n\n CarbureLotEvent.objects.create(\n event_type=CarbureLotEvent.CREATED,\n lot_id=lots_created[0].id,\n user=request.user,\n metadata={\"source\": \"MANUAL\"},\n )\n\n data = CarbureLotPublicSerializer(lots_created[0]).data\n return SuccessResponse(data)", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback\n) -> None:\n \"\"\"Set up OwnTracks based off an entry.\"\"\"\n # Restore previously loaded devices\n dev_reg = dr.async_get(hass)\n dev_ids = {\n identifier[1]\n for device in dev_reg.devices.get_devices_for_config_entry_id(entry.entry_id)\n for identifier in device.identifiers\n }\n\n entities = []\n for dev_id in dev_ids:\n entity = hass.data[OT_DOMAIN][\"devices\"][dev_id] = OwnTracksEntity(dev_id)\n entities.append(entity)\n\n @callback\n def _receive_data(dev_id, **data):\n \"\"\"Receive set location.\"\"\"\n entity = hass.data[OT_DOMAIN][\"devices\"].get(dev_id)\n\n if entity is not None:\n entity.update_data(data)\n return\n\n entity = hass.data[OT_DOMAIN][\"devices\"][dev_id] = OwnTracksEntity(dev_id, data)\n async_add_entities([entity])\n\n hass.data[OT_DOMAIN][\"context\"].set_async_see(_receive_data)\n\n async_add_entities(entities)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def bind_providers(self):\n \"\"\"Initialize the profile-level instance providers.\"\"\"\n injector = self._context.injector\n\n injector.bind_instance(BaseStorageSearch, STORAGE_CLASS(self))\n\n injector.bind_provider(\n VCHolder,\n ClassProvider(\n \"acapy_agent.storage.vc_holder.in_memory.InMemoryVCHolder\",\n ref(self),\n ),\n )", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_do_activationkey_listbasechannel_noargs(self, shell):\n \"\"\"\n Test listbasechannels command triggers help on no args\n \"\"\"\n shell.help_activationkey_listbasechannel = MagicMock()\n shell.client.activationkey.getDetails = MagicMock(return_value={\"base_channel_label\"})\n\n spacecmd.activationkey.do_activationkey_listbasechannel(shell, \"\")\n assert shell.help_activationkey_listbasechannel.called\n assert not shell.client.activationkey.getDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_get_user_by_email_returns_correct_user(store_with_users: Store):\n \"\"\"Test fetching a user by email.\"\"\"\n\n # GIVEN a store with multiple users\n num_users: int = store_with_users._get_query(table=User).count()\n assert num_users > 0\n\n # Select a random user from the store\n user: User = store_with_users._get_query(table=User).first()\n assert user is not None\n\n # WHEN fetching the user by email\n filtered_user: User = store_with_users.get_user_by_email(email=user.email)\n\n # THEN a user should be returned\n assert isinstance(filtered_user, User)\n\n # THEN the email should match\n assert filtered_user.email == user.email", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def setUpClass(cls):\n super().setUpClass()\n\n cls.test_bundles_dir = Path(__file__).parent / \"bundles\"\n cls.test_files_dir = Path(__file__).parent / \"files\"\n\n init_roles()\n init()\n\n adcm = ADCM.objects.first()\n config_log = ConfigLog.objects.get(id=adcm.config.current)\n config_log.config[\"auth_policy\"][\"max_password_length\"] = 20\n config_log.save(update_fields=[\"config\"])", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def from_string_id(value_id_str: str) -> ValueID:\n \"\"\"Get a ValueID from a string representation of the value ID.\"\"\"\n parts = value_id_str.split(\"-\")\n property_key = parts[4] if len(parts) > 4 else None\n return ValueID(parts[1], parts[2], parts[3], property_key=property_key)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_details_args(self, shell):\n \"\"\"\n Test activationkey_details returns key details if proper arguments passed.\n \"\"\"\n shell.help_activationkey_details = MagicMock()\n\n shell.client.activationkey.getDetails = MagicMock(\n return_value={\n \"key\": \"somekey\",\n \"description\": \"Key description\",\n \"universal_default\": \"yes\",\n \"usage_limit\": \"42\",\n \"contact_method\": \"230V/AC\",\n \"server_group_ids\": [\"a\", \"b\", \"c\"],\n \"child_channel_labels\": [\"child_channel_1\", \"child_channel_2\"],\n \"entitlements\": [\"entitlement_1\", \"entitlement_2\"],\n \"packages\": [{\"name\": \"emacs\"}],\n \"base_channel_label\": \"base_channel\",\n }\n )\n shell.client.activationkey.listConfigChannels = MagicMock(\n return_value=[\n {\"label\": \"somekey_config_channel_1\"},\n {\"label\": \"somekey_config_channel_2\"},\n ]\n )\n shell.client.activationkey.checkConfigDeployment = MagicMock(return_value=0)\n shell.client.systemgroup.getDetails = MagicMock(\n side_effect=[\n {\"name\": \"group_a\"},\n {\"name\": \"group_b\"},\n {\"name\": \"group_c\"},\n ]\n )\n\n mprint = MagicMock()\n with patch(\"spacecmd.activationkey.print\", mprint) as mpr: \n out = spacecmd.activationkey.do_activationkey_details(shell, \"somekey\")\n assert mprint.called\n\n expectation = ['Key: somekey',\n 'Description: Key description', 'Universal Default: yes',\n 'Usage Limit: 42', 'Deploy Config Channels: False',\n 'Contact Method: 230V/AC', '', 'Software Channels', '-----------------',\n 'base_channel', ' |-- child_channel_1', ' |-- child_channel_2', '',\n 'Configuration Channels', '----------------------', 'somekey_config_channel_1',\n 'somekey_config_channel_2', '', 'Entitlements', '------------',\n 'entitlement_1\\nentitlement_2', '', 'System Groups', '-------------',\n 'group_a\\ngroup_b\\ngroup_c', '', 'Packages', '--------', 'emacs']\n assert len(out) == len(expectation)\n for idx, line in enumerate(out):\n assert line == expectation[idx]", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def body(self) -> bytes:\n return self.json().encode()", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def is_closing(self) -> bool:\n \"\"\"Return if the cover is closing.\"\"\"\n return self._channel.is_closing()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_clone_project(\n client: TestClient,\n logged_user: UserInfoDict,\n user_project: ProjectDict,\n # mocks backend\n storage_subsystem_mock: MockedStorageSubsystem,\n mock_catalog_service_api_responses: None,\n project_db_cleaner: None,\n create_workspace_and_folder: tuple[WorkspaceID, FolderID],\n):\n assert client.app\n\n project = user_project\n await move_project_into_folder(\n client.app,\n user_id=logged_user[\"id\"],\n project_id=project[\"uuid\"],\n folder_id=create_workspace_and_folder[1],\n product_name=\"osparc\",\n )\n\n base_url = client.app.router[\"list_projects\"].url_for()\n query_parameters = {\n \"workspace_id\": f\"{create_workspace_and_folder[0]}\",\n \"folder_id\": f\"{create_workspace_and_folder[1]}\",\n }\n url = base_url.with_query(**query_parameters)\n resp = await client.get(url)\n data = await resp.json()\n assert resp.status == 200\n assert len(data[\"data\"]) == 1\n\n url = client.app.router[\"clone_project\"].url_for(project_id=project[\"uuid\"])\n assert f\"/v0/projects/{project['uuid']}:clone\" == url.path\n\n cloned_project = await _request_clone_project(client, url)\n\n # check whether it's a clone\n assert ProjectID(project[\"uuid\"]) != cloned_project.uuid\n assert cloned_project.workspace_id == create_workspace_and_folder[0]\n\n # check whether it's in right folder\n base_url = client.app.router[\"list_projects\"].url_for()\n query_parameters = {\n \"workspace_id\": f\"{create_workspace_and_folder[0]}\",\n \"folder_id\": f\"{create_workspace_and_folder[1]}\",\n }\n url = base_url.with_query(**query_parameters)\n resp = await client.get(url)\n data = await resp.json()\n assert resp.status == 200\n assert len(data[\"data\"]) == 2", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def link_user(\n link_request: PartnerLinkRequest, current_user: User, partner: Partner\n) -> LinkResult:\n # Sanitize email just in case\n link_request.email = sanitize_email(link_request.email)\n # If it was scheduled to be deleted. Unschedule it.\n current_user.delete_on = None\n partner_user = ensure_partner_user_exists_for_user(\n link_request, current_user, partner\n )\n set_plan_for_partner_user(partner_user, link_request.plan)\n\n agent.record_custom_event(\"AccountLinked\", {\"partner\": partner.name})\n Session.commit()\n return LinkResult(\n user=current_user,\n strategy=\"Link\",\n )", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def user_project_in_2_products(\n logged_user: UserInfoDict,\n user_project: ProjectDict,\n postgres_db: sa.engine.Engine,\n faker: Faker,\n) -> Iterator[ProjectDict]:\n fake_product_name = faker.name()\n with postgres_db.connect() as conn:\n conn.execute(products.insert().values(name=fake_product_name, host_regex=\"\"))\n conn.execute(\n projects_to_products.insert().values(\n project_uuid=user_project[\"uuid\"], product_name=fake_product_name\n )\n )\n yield user_project\n # cleanup\n with postgres_db.connect() as conn:\n conn.execute(products.delete().where(products.c.name == fake_product_name))", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def __init__(self, **kwargs):\n \"\"\"Initialize a menu request object.\"\"\"\n super().__init__(**kwargs)", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def async_add_acmeda_sensors() -> None:\n async_add_acmeda_entities(\n hass, AcmedaBattery, config_entry, current, async_add_entities\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def page_candidates(self) -> FoundCandidates:\n if not _is_html_file(self._link.url):\n return\n yield from self._candidates_from_page(self._link)", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def test_expected_paths(\n swarm_stack_name: str,\n node_uuid: UUID,\n state_paths: list[Path],\n expected_volume_config: Callable[[str, str], dict[str, Any]],\n run_id: RunID,\n project_id: ProjectID,\n user_id: UserID,\n) -> None:\n fake = Faker()\n\n inputs_path = Path(fake.file_path(depth=3)).parent\n assert DynamicSidecarVolumesPathsResolver.mount_entry(\n swarm_stack_name, inputs_path, node_uuid, run_id, project_id, user_id, None\n ) == expected_volume_config(\n source=f\"dyv_{run_id}_{node_uuid}_{f'{inputs_path}'.replace('/', '_')[::-1]}\",\n target=str(Path(\"/dy-volumes\") / inputs_path.relative_to(\"/\")),\n )\n\n outputs_path = Path(fake.file_path(depth=3)).parent\n assert DynamicSidecarVolumesPathsResolver.mount_entry(\n swarm_stack_name, outputs_path, node_uuid, run_id, project_id, user_id, None\n ) == expected_volume_config(\n source=f\"dyv_{run_id}_{node_uuid}_{f'{outputs_path}'.replace('/', '_')[::-1]}\",\n target=str(Path(\"/dy-volumes\") / outputs_path.relative_to(\"/\")),\n )\n\n for path in state_paths:\n name_from_path = f\"{path}\".replace(os.sep, \"_\")[::-1]\n assert DynamicSidecarVolumesPathsResolver.mount_entry(\n swarm_stack_name, path, node_uuid, run_id, project_id, user_id, None\n ) == expected_volume_config(\n source=f\"dyv_{run_id}_{node_uuid}_{name_from_path}\",\n target=str(Path(\"/dy-volumes/\") / path.relative_to(\"/\")),\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def login():\n if request.method == 'POST':\n session['username'] = request.form['username']\n return redirect(url_for('index'))\n return '''\n\t\n <form action = \"\" method = \"post\">\n <p><input type = text name = username/></p>\n <p<<input type = submit value = Login/></p>\n </form>\n\t\n '''", "smellKey": "0", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "def test_group_list_data(self, shell):\n \"\"\"\n Test do_group_list with data return.\n\n :param shell:\n :return:\n \"\"\"\n shell.client.systemgroup.listAllGroups = MagicMock(return_value=[\n {\"name\": \"group-a\"}, {\"name\": \"group-b\"}\n ])\n mprint = MagicMock()\n with patch(\"spacecmd.group.print\", mprint):\n out = spacecmd.group.do_group_list(shell, \"\", doreturn=True)\n\n assert shell.client.systemgroup.listAllGroups.called\n assert out is not None\n assert len(out) == 2\n assert out == [\"group-a\", \"group-b\"]", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_ssdp_update_seen_bootid(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n mock_disconnected_entity_id: str,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test device does not reconnect when it gets ssdp:update with next bootid.\"\"\"\n # Start with a disconnected device\n entity_id = mock_disconnected_entity_id\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == ha_const.STATE_UNAVAILABLE\n\n # \"Reconnect\" the device\n domain_data_mock.upnp_factory.async_create_device.side_effect = None\n\n # Send SSDP alive with boot ID\n ssdp_callback = ssdp_scanner_mock.async_register_callback.call_args.args[0].target\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"1\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n # Send SSDP update with next boot ID\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_udn=MOCK_DEVICE_UDN,\n ssdp_headers={\n \"NTS\": \"ssdp:update\",\n ssdp.ATTR_SSDP_BOOTID: \"1\",\n ssdp.ATTR_SSDP_NEXTBOOTID: \"2\",\n },\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.UPDATE,\n )\n await hass.async_block_till_done()\n\n # Device was not reconnected, even with a new boot ID\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 1\n\n # Send SSDP update with same next boot ID, again\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_udn=MOCK_DEVICE_UDN,\n ssdp_headers={\n \"NTS\": \"ssdp:update\",\n ssdp.ATTR_SSDP_BOOTID: \"1\",\n ssdp.ATTR_SSDP_NEXTBOOTID: \"2\",\n },\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.UPDATE,\n )\n await hass.async_block_till_done()\n\n # Nothing should change\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 1\n\n # Send SSDP update with bad next boot ID\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_udn=MOCK_DEVICE_UDN,\n ssdp_headers={\n \"NTS\": \"ssdp:update\",\n ssdp.ATTR_SSDP_BOOTID: \"2\",\n ssdp.ATTR_SSDP_NEXTBOOTID: \"7c848375-a106-4bd1-ac3c-8e50427c8e4f\",\n },\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.UPDATE,\n )\n await hass.async_block_till_done()\n\n # Nothing should change\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 1\n\n # Send a new SSDP alive with the new boot ID, device should not reconnect\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"2\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 1", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def include_pedigree_picture(self) -> None:\n if self.is_multi_sample_case(self.load_config):\n if self.is_family_case(self.load_config):\n svg_path: Path = self.run_madeline(self.analysis_obj.case)\n self.load_config.madeline = str(svg_path)\n else:\n LOG.info(\"family of unconnected samples - skip pedigree graph\")\n else:\n LOG.info(\"family of 1 sample - skip pedigree graph\")", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_write_buffer_set_float_little_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN)\n wb.write_float(-1, 32)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00000000000000001000000010111111\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def profile_with_version(profile_ospp):\n profile_ospp.metadata[\"version\"] = \"3.2.1\"\n return profile_ospp", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def __get_validators__(cls) -> Generator[Callable, None, None]:\n yield cls.validate", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def get_plex_server(hass: HomeAssistant, server_id: str) -> PlexServer:\n \"\"\"Get Plex server from hass.data.\"\"\"\n return get_plex_data(hass)[SERVERS][server_id]", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_parse_file(self):\n testfile = open(\"unittests/scans/ibm_app/testfire.xml\", encoding=\"utf-8\")\n parser = IbmAppParser()\n findings = parser.get_findings(testfile, Test())\n for finding in findings:\n for endpoint in finding.unsaved_endpoints:\n endpoint.clean()\n testfile.close()\n self.assertEqual(27, len(findings))\n\n finding = findings[15]\n self.assertEqual(\"High\", finding.severity)\n self.assertEqual(79, finding.cwe)\n self.assertEqual(1, len(finding.unsaved_vulnerability_ids))\n self.assertEqual(\"CVE-2022-00001\", finding.unsaved_vulnerability_ids[0])\n\n finding = findings[1]\n self.assertEqual(\"Info\", finding.severity)", "smellKey": "0", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def test_get_batch_identifiers_list_with_batch_parameters(mocker: pytest_mock.MockFixture):\n # Arrange\n batch_definition = BatchDefinition[None](name=\"test_batch_definition\")\n mock_asset = mocker.Mock(spec=DataAsset)\n batch_definition.set_data_asset(mock_asset)\n\n mock_batch_identifiers_list = [{\"foo\": \"bar\"}, {\"baz\": \"qux\"}]\n mock_asset.get_batch_identifiers_list.return_value = mock_batch_identifiers_list\n\n # Act\n batch_parameters: BatchParameters = {\"path\": \"my_path\"}\n batch_identifiers_list = batch_definition.get_batch_identifiers_list(batch_parameters)\n\n # Assert\n assert batch_identifiers_list == mock_batch_identifiers_list\n mock_asset.get_batch_identifiers_list.assert_called_once_with(\n batch_definition.build_batch_request(batch_parameters)\n )", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_write_buffer_write_unsigned_short_little_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN)\n wb.write_unsigned_short(0x12, 16)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00010010 00000000\", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "async def test_version_sensor(hass: HomeAssistant) -> None:\n \"\"\"Test the Version sensor with different sources.\"\"\"\n await setup_version_integration(hass)\n\n state = hass.states.get(\"sensor.local_installation\")\n assert state.state == MOCK_VERSION\n assert \"source\" not in state.attributes\n assert \"channel\" not in state.attributes", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def sort_project_directories_by_date(project_directories: list[str]) -> list[str]:\n return sorted(project_directories, key=get_project_directory_date, reverse=True)", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_do_activationkey_removechildchannels_args(self, shell):\n \"\"\"\n Test \"removechildchannels\" method calls \"removeChildChannels\" API call.\n \"\"\"\n shell.help_activationkey_removechildchannels = MagicMock()\n shell.client.activationkey.removeChildChannels = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removechildchannels(shell, \"key some_channel\")\n assert not shell.help_activationkey_removechildchannels.called\n assert shell.client.activationkey.removeChildChannels.called\n session, fun, args = shell.client.activationkey.removeChildChannels.call_args_list[0][0]\n assert session == shell.session\n assert fun == \"key\"\n assert isinstance(args, list)\n assert len(args) == 1\n assert args == ['some_channel']", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def is_prod_appengine():\n return \"APPENGINE_RUNTIME\" in os.environ and os.environ.get(\n \"SERVER_SOFTWARE\", \"\"\n ).startswith(\"Google App Engine/\")", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def test_get_bed_version_by_file_name(base_store: Store, bed_version_file_name: str):\n \"\"\"Test function to return the bed version by file name.\"\"\"\n\n # GIVEN a store with bed versions records\n\n # WHEN getting the query for the bed versions\n bed_version: BedVersion = base_store.get_bed_version_by_file_name(\n bed_version_file_name=bed_version_file_name\n )\n\n # THEN return a bed version with the supplied bed version file_name\n assert bed_version.filename == bed_version_file_name", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def radios(self) -> RadioBrowser:\n \"\"\"Return the radio browser.\"\"\"\n return self.entry.runtime_data", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def async_get_service(\n hass: HomeAssistant,\n config: ConfigType,\n discovery_info: DiscoveryInfoType | None = None,\n) -> MastodonNotificationService | None:\n \"\"\"Get the Mastodon notification service.\"\"\"\n\n if not discovery_info:\n # Import config entry\n\n import_result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": SOURCE_IMPORT},\n data=config,\n )\n\n if (\n import_result[\"type\"] == FlowResultType.ABORT\n and import_result[\"reason\"] != \"already_configured\"\n ):\n ir.async_create_issue(\n hass,\n DOMAIN,\n f\"deprecated_yaml_import_issue_{import_result[\"reason\"]}\",\n breaks_in_ha_version=\"2025.2.0\",\n is_fixable=False,\n issue_domain=DOMAIN,\n severity=ir.IssueSeverity.WARNING,\n translation_key=f\"deprecated_yaml_import_issue_{import_result[\"reason\"]}\",\n translation_placeholders={\n \"domain\": DOMAIN,\n \"integration_title\": INTEGRATION_TITLE,\n },\n )\n return None\n\n ir.async_create_issue(\n hass,\n HOMEASSISTANT_DOMAIN,\n f\"deprecated_yaml_{DOMAIN}\",\n breaks_in_ha_version=\"2025.2.0\",\n is_fixable=False,\n issue_domain=DOMAIN,\n severity=ir.IssueSeverity.WARNING,\n translation_key=\"deprecated_yaml\",\n translation_placeholders={\n \"domain\": DOMAIN,\n \"integration_title\": INTEGRATION_TITLE,\n },\n )\n\n return None\n\n client: Mastodon = discovery_info.get(\"client\")\n\n return MastodonNotificationService(hass, client)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(self, path: str) -> None:\n self._path = path\n self._page_candidates: List[str] = []\n self._project_name_to_urls: Dict[str, List[str]] = defaultdict(list)\n self._scanned_directory = False", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def groups(self):\n return [\"pokec\", \"card_fraud\", \"bfs_pokec\"]", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "async def test_attributes(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test attributes of a connected DlnaDmrEntity.\"\"\"\n # Check attributes come directly from the device\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_VOLUME_LEVEL] is dmr_device_mock.volume_level\n assert attrs[mp_const.ATTR_MEDIA_VOLUME_MUTED] is dmr_device_mock.is_volume_muted\n assert attrs[mp_const.ATTR_MEDIA_DURATION] is dmr_device_mock.media_duration\n assert attrs[mp_const.ATTR_MEDIA_POSITION] is dmr_device_mock.media_position\n assert (\n attrs[mp_const.ATTR_MEDIA_POSITION_UPDATED_AT]\n is dmr_device_mock.media_position_updated_at\n )\n assert attrs[mp_const.ATTR_MEDIA_CONTENT_ID] is dmr_device_mock.current_track_uri\n assert attrs[mp_const.ATTR_MEDIA_ARTIST] is dmr_device_mock.media_artist\n assert attrs[mp_const.ATTR_MEDIA_ALBUM_NAME] is dmr_device_mock.media_album_name\n assert attrs[mp_const.ATTR_MEDIA_ALBUM_ARTIST] is dmr_device_mock.media_album_artist\n assert attrs[mp_const.ATTR_MEDIA_TRACK] is dmr_device_mock.media_track_number\n assert attrs[mp_const.ATTR_MEDIA_SERIES_TITLE] is dmr_device_mock.media_series_title\n assert attrs[mp_const.ATTR_MEDIA_SEASON] is dmr_device_mock.media_season_number\n assert attrs[mp_const.ATTR_MEDIA_EPISODE] is dmr_device_mock.media_episode_number\n assert attrs[mp_const.ATTR_MEDIA_CHANNEL] is dmr_device_mock.media_channel_name\n assert attrs[mp_const.ATTR_SOUND_MODE_LIST] is dmr_device_mock.preset_names\n\n # Entity picture is cached, won't correspond to remote image\n assert isinstance(attrs[ha_const.ATTR_ENTITY_PICTURE], str)\n\n # media_title depends on what is available\n assert attrs[mp_const.ATTR_MEDIA_TITLE] is dmr_device_mock.media_program_title\n dmr_device_mock.media_program_title = None\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_TITLE] is dmr_device_mock.media_title\n\n # media_content_type is mapped from UPnP class to MediaPlayer type\n dmr_device_mock.media_class = \"object.item.audioItem.musicTrack\"\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_CONTENT_TYPE] == MediaType.MUSIC\n dmr_device_mock.media_class = \"object.item.videoItem.movie\"\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_CONTENT_TYPE] == MediaType.MOVIE\n dmr_device_mock.media_class = \"object.item.videoItem.videoBroadcast\"\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_CONTENT_TYPE] == MediaType.TVSHOW\n\n # media_season & media_episode have a special case\n dmr_device_mock.media_season_number = \"0\"\n dmr_device_mock.media_episode_number = \"123\"\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_SEASON] == \"1\"\n assert attrs[mp_const.ATTR_MEDIA_EPISODE] == \"23\"\n dmr_device_mock.media_season_number = \"0\"\n dmr_device_mock.media_episode_number = \"S1E23\" # Unexpected and not parsed\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_SEASON] == \"0\"\n assert attrs[mp_const.ATTR_MEDIA_EPISODE] == \"S1E23\"\n\n # shuffle and repeat is based on device's play mode\n for play_mode, shuffle, repeat in [\n (PlayMode.NORMAL, False, RepeatMode.OFF),\n (PlayMode.SHUFFLE, True, RepeatMode.OFF),\n (PlayMode.REPEAT_ONE, False, RepeatMode.ONE),\n (PlayMode.REPEAT_ALL, False, RepeatMode.ALL),\n (PlayMode.RANDOM, True, RepeatMode.ALL),\n (PlayMode.DIRECT_1, False, RepeatMode.OFF),\n (PlayMode.INTRO, False, RepeatMode.OFF),\n ]:\n dmr_device_mock.play_mode = play_mode\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[mp_const.ATTR_MEDIA_SHUFFLE] is shuffle\n assert attrs[mp_const.ATTR_MEDIA_REPEAT] == repeat\n for bad_play_mode in [None, PlayMode.VENDOR_DEFINED]:\n dmr_device_mock.play_mode = bad_play_mode\n attrs = await get_attrs(hass, mock_entity_id)\n assert mp_const.ATTR_MEDIA_SHUFFLE not in attrs\n assert mp_const.ATTR_MEDIA_REPEAT not in attrs", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def set_state_full_path(self, **kwargs: Any) -> Any:\n \"\"\"Set block state (HTTP request).\"\"\"\n LOGGER.debug(\"Setting state for entity %s, state: %s\", self.name, kwargs)\n try:\n return await self.coordinator.device.http_request(\n \"get\", f\"thermostat/{self._channel}\", kwargs\n )\n except DeviceConnectionError as err:\n self.coordinator.last_update_success = False\n raise HomeAssistantError(\n f\"Setting state for entity {self.name} failed, state: {kwargs}, error:\"\n f\" {repr(err)}\"\n ) from err\n except InvalidAuthError:\n await self.coordinator.async_shutdown_device_and_start_reauth()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_record_event_with_geoip(self, db_request):\n \"\"\"\n Test to cover condition when record_event is called with geoip_info as\n part of the inbound request.\n Possibly could be removed once more comprehensive tests are in place,\n but nothing explicitly covers `HasEvents.record_event`\n \"\"\"\n db_request.ip_address.geoip_info = {\"country_name\": \"United States\"}\n\n organization = DBOrganizationFactory.create()\n\n organization.record_event(\n tag=\"\",\n request=db_request,\n additional={},\n )\n\n event = organization.events[0]\n\n assert event.additional == {\n \"organization_name\": organization.name,\n \"geoip_info\": {\"country_name\": \"United States\"},\n }\n assert event.location_info == \"United States\"", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def profile_without_version(profile_ospp):\n profile_ospp.metadata.pop('version', None)\n return profile_ospp", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "async def test_get_actions(\n hass: HomeAssistant,\n device_registry: dr.DeviceRegistry,\n entity_registry: er.EntityRegistry,\n) -> None:\n \"\"\"Test we get the expected actions from a remote.\"\"\"\n config_entry = MockConfigEntry(domain=\"test\", data={})\n config_entry.add_to_hass(hass)\n device_entry = device_registry.async_get_or_create(\n config_entry_id=config_entry.entry_id,\n connections={(dr.CONNECTION_NETWORK_MAC, \"12:34:56:AB:CD:EF\")},\n )\n entity_entry = entity_registry.async_get_or_create(\n DOMAIN, \"test\", \"5678\", device_id=device_entry.id\n )\n expected_actions = [\n {\n \"domain\": DOMAIN,\n \"type\": action,\n \"device_id\": device_entry.id,\n \"entity_id\": entity_entry.id,\n \"metadata\": {\"secondary\": False},\n }\n for action in [\"turn_off\", \"turn_on\", \"toggle\"]\n ]\n actions = await async_get_device_automations(\n hass, DeviceAutomationType.ACTION, device_entry.id\n )\n assert actions == unordered(expected_actions)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_disableconfigdeployment_noargs(self, shell):\n \"\"\"\n Test activationkey_disableconfigdeployment command is invoking help message on insufficient arguments.\n \"\"\"\n shell.help_activationkey_disableconfigdeployment = MagicMock()\n shell.client.activationkey.disableConfigDeployment = MagicMock()\n\n spacecmd.activationkey.do_activationkey_disableconfigdeployment(shell, \"\")\n assert shell.help_activationkey_disableconfigdeployment.called\n assert not shell.client.activationkey.disableConfigDeployment.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_is_all_illumina_runs_on_disk_when_no_illumina_run(\n store_with_illumina_sequencing_data: Store,\n selected_novaseq_x_case_ids: str,\n):\n \"\"\"Test check if all sequencing runs for samples on a case are on disk when there are no sequencing runs.\"\"\"\n # GIVEN a store with a case that has no sequencing runs\n sequencing_runs: list[IlluminaSequencingRun] = (\n store_with_illumina_sequencing_data.get_illumina_sequencing_runs_by_case(\n selected_novaseq_x_case_ids[0]\n )\n )\n assert sequencing_runs\n store_with_illumina_sequencing_data.delete_illumina_flow_cell(\n sequencing_runs[0].device.internal_id\n )\n deleted_run: list[IlluminaSequencingRun] = (\n store_with_illumina_sequencing_data.get_illumina_sequencing_runs_by_case(\n selected_novaseq_x_case_ids[0]\n )\n )\n assert not deleted_run\n\n # WHEN fetching the illumina runs for a case\n is_on_disk = store_with_illumina_sequencing_data.are_all_illumina_runs_on_disk(\n case_id=selected_novaseq_x_case_ids[0]\n )\n\n # THEN return false\n assert is_on_disk is False", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_do_activationkey_removechildchannels_help_args(self, shell):\n \"\"\"\n Test removechildchannels method call shows help if only one argument is passed.\n \"\"\"\n shell.help_activationkey_removechildchannels = MagicMock()\n shell.client.activationkey.removeChildChannels = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removechildchannels(shell, \"key\")\n assert shell.help_activationkey_removechildchannels.called\n assert not shell.client.activationkey.removeChildChannels.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_domain_control_unauthorized(\n hass: HomeAssistant, hass_read_only_user: MockUser\n) -> None:\n \"\"\"Test domain verification in a service call with an unauthorized user.\"\"\"\n mock_registry(\n hass,\n {\n \"light.kitchen\": er.RegistryEntry(\n entity_id=\"light.kitchen\",\n unique_id=\"kitchen\",\n platform=\"test_domain\",\n )\n },\n )\n\n calls = []\n\n async def mock_service_log(call):\n \"\"\"Define a protected service.\"\"\"\n calls.append(call)\n\n protected_mock_service = service.verify_domain_control(hass, \"test_domain\")(\n mock_service_log\n )\n\n hass.services.async_register(\n \"test_domain\", \"test_service\", protected_mock_service, schema=None\n )\n\n with pytest.raises(exceptions.Unauthorized):\n await hass.services.async_call(\n \"test_domain\",\n \"test_service\",\n {},\n blocking=True,\n context=Context(user_id=hass_read_only_user.id),\n )\n\n assert len(calls) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_non_zero_exit_status_when_path_to_db_is_path(self):\n sqlite_with_path = {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": Path(\"test.db.sqlite3\"),\n }\n cmd_args = self.settings_to_cmd_args_env(sqlite_with_path)[0]\n\n msg = '\"sqlite3 test.db.sqlite3\" returned non-zero exit status 1.'\n with (\n mock.patch(\n \"django.db.backends.sqlite3.client.DatabaseClient.runshell\",\n side_effect=subprocess.CalledProcessError(returncode=1, cmd=cmd_args),\n ),\n self.assertRaisesMessage(CommandError, msg),\n ):\n call_command(\"dbshell\")", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def set_resource(\n self, key: UserSessionDict, resource: tuple[str, str]\n ) -> None:\n hash_key = f\"{self._hash_key(key)}:{_RESOURCE_SUFFIX}\"\n field, value = resource\n await handle_redis_returns_union_types(\n self.client.hset(hash_key, mapping={field: value})\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def rule_accounts_tmout():\n rule_file = os.path.join(DATADIR, \"accounts_tmout.yml\")\n return ssg.build_yaml.Rule.from_yaml(rule_file)", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_group_listsystems_noargs(self, shell):\n \"\"\"\n Test do_group_listsystems with no arguments passed.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_listsystems = MagicMock()\n shell.client.systemgroup.listSystems = MagicMock()\n mprint = MagicMock()\n logger = MagicMock()\n\n with patch(\"spacecmd.group.print\", mprint) as prt, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n out = spacecmd.group.do_group_listsystems(shell, \"\", doreturn=True)\n\n assert not shell.client.systemgroup.listSystems.called\n assert not mprint.called\n assert not logger.warning.called\n assert out is None\n assert shell.help_group_listsystems.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def mock_static_webserver(aioresponses_mocker: aioresponses) -> None:\n aioresponses_mocker.get(\n re.compile(r\"http://static-webserver:8000/.*\"),\n status=status.HTTP_200_OK,\n repeat=True,\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def _async_add_new_lock(lock_id: int) -> None:\n lock = coordinator.data[lock_id]\n if lock.is_enabled_pullspring:\n async_add_entities([TedeeLockWithLatchEntity(lock, coordinator)])\n else:\n async_add_entities([TedeeLockEntity(lock, coordinator)])", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_become_available(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n config_entry_mock: MockConfigEntry,\n dmr_device_mock: Mock,\n core_state: CoreState,\n) -> None:\n \"\"\"Test a device becoming available after the entity is constructed.\"\"\"\n # Cause connection attempts to fail before adding entity\n hass.set_state(core_state)\n domain_data_mock.upnp_factory.async_create_device.side_effect = UpnpConnectionError\n config_entry_mock.add_to_hass(hass)\n mock_entity_id = await setup_mock_component(hass, config_entry_mock)\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n assert mock_state.state == ha_const.STATE_UNAVAILABLE\n\n # Check hass device information has not been filled in yet\n dev_reg = async_get_dr(hass)\n device = dev_reg.async_get_device(\n connections={(CONNECTION_UPNP, MOCK_DEVICE_UDN)},\n identifiers=set(),\n )\n assert device is not None\n\n # Mock device is now available.\n domain_data_mock.upnp_factory.async_create_device.side_effect = None\n domain_data_mock.upnp_factory.async_create_device.reset_mock()\n\n # Send an SSDP notification from the now alive device\n ssdp_callback = ssdp_scanner_mock.async_register_callback.call_args.args[0].target\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=NEW_DEVICE_LOCATION,\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n # Check device was created from the supplied URL\n domain_data_mock.upnp_factory.async_create_device.assert_awaited_once_with(\n NEW_DEVICE_LOCATION\n )\n # Check event notifiers are acquired\n domain_data_mock.async_get_event_notifier.assert_awaited_once_with(\n EventListenAddr(LOCAL_IP, 0, None), hass\n )\n # Check UPnP services are subscribed\n dmr_device_mock.async_subscribe_services.assert_awaited_once_with(\n auto_resubscribe=True\n )\n assert dmr_device_mock.on_event is not None\n # Quick check of the state to verify the entity has a connected DmrDevice\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n # Check hass device information is now filled in\n dev_reg = async_get_dr(hass)\n device = dev_reg.async_get_device(\n connections={(CONNECTION_UPNP, MOCK_DEVICE_UDN)},\n identifiers=set(),\n )\n assert device is not None\n assert device.manufacturer == \"device_manufacturer\"\n assert device.model == \"device_model_name\"\n assert device.name == \"device_name\"\n\n # Unload config entry to clean up\n assert await hass.config_entries.async_remove(config_entry_mock.entry_id) == {\n \"require_restart\": False\n }\n\n # Confirm SSDP notifications unregistered\n assert ssdp_scanner_mock.async_register_callback.return_value.call_count == 2\n\n # Confirm the entity has disconnected from the device\n domain_data_mock.async_release_event_notifier.assert_awaited_once()\n dmr_device_mock.async_unsubscribe_services.assert_awaited_once()\n assert dmr_device_mock.on_event is None\n # Entity should be removed by the cleanup\n assert hass.states.get(mock_entity_id) is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def _entry_dict(entry: LabelEntry) -> dict[str, Any]:\n \"\"\"Convert entry to API format.\"\"\"\n return {\n \"color\": entry.color,\n \"created_at\": entry.created_at.timestamp(),\n \"description\": entry.description,\n \"icon\": entry.icon,\n \"label_id\": entry.label_id,\n \"name\": entry.name,\n \"modified_at\": entry.modified_at.timestamp(),\n }", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_domain_blueprints_caching(domain_bps: models.DomainBlueprints) -> None:\n \"\"\"Test domain blueprints cache blueprints.\"\"\"\n obj = object()\n with patch.object(domain_bps, \"_load_blueprint\", return_value=obj):\n assert await domain_bps.async_get_blueprint(\"something\") is obj\n\n # Now we hit cache\n assert await domain_bps.async_get_blueprint(\"something\") is obj\n\n obj_2 = object()\n await domain_bps.async_reset_cache()\n\n # Now we call this method again.\n with patch.object(domain_bps, \"_load_blueprint\", return_value=obj_2):\n assert await domain_bps.async_get_blueprint(\"something\") is obj_2", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def _setup(self):\n \"\"\"Create the session or transaction connection, if needed.\"\"\"\n await super()._setup()\n self._init_context()\n self._handle: Optional[Session] = None", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_get_latest_ticket_from_case(case_id: str, analysis_store_single_case, ticket_id: str):\n \"\"\"Tests if the correct ticket is returned for the given case.\"\"\"\n # GIVEN a populated store with a case\n\n # WHEN the function is called\n ticket_from_case: str = analysis_store_single_case.get_latest_ticket_from_case(case_id=case_id)\n\n # THEN the ticket should be correct\n assert ticket_id == ticket_from_case", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def remove_credential(self, credential):\n with suppress(exc.NoContent):\n self.related.credentials.post(dict(id=credential.id, disassociate=True))", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def remove_resource(self, key: UserSessionDict, resource_name: str) -> None:\n hash_key = f\"{self._hash_key(key)}:{_RESOURCE_SUFFIX}\"\n await handle_redis_returns_union_types(\n self.client.hdel(hash_key, resource_name)\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def NextPress():\n\tif ColorWindow:\n\t\tColorWindow.Close()\n\n\tMyChar = GemRB.GetVar (\"Slot\")\n\tGUICommon.SetColorStat (MyChar, IE_HAIR_COLOR, HairColor)\n\tGUICommon.SetColorStat (MyChar, IE_SKIN_COLOR, SkinColor)\n\tGUICommon.SetColorStat (MyChar, IE_MAJOR_COLOR, MajorColor)\n\tGUICommon.SetColorStat (MyChar, IE_MINOR_COLOR, MinorColor)\n\t# ignore IE_METAL_COLOR, IE_LEATHER_COLOR, IE_ARMOR_COLOR as they're set by equipment\n\tif GameCheck.IsBG1 ():\n\t\tCharGenCommon.next()\n\telse:\n\t\tGemRB.SetNextScript (\"GUICG19\") #sounds\n\treturn", "smellKey": "0", "smellId": null, "repo": "gemrb_gemrb", "language": "python"} {"function": "def _resolve_char_detection():\n \"\"\"Find supported character detection libraries.\"\"\"\n chardet = None\n return chardet", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_pip", "language": "python"} {"function": "def test_get_samples_from_illumina_flow_cell_internal_id(\n novaseq_x_flow_cell_id: str, store_with_illumina_sequencing_data: Store\n):\n \"\"\"Test getting samples from an Illumina flow cell by internal ID\"\"\"\n # GIVEN a store with an Illumina flow cell and samples\n\n # WHEN fetching the samples from the flow cell\n samples: list[Sample] = store_with_illumina_sequencing_data.get_samples_by_illumina_flow_cell(\n flow_cell_id=novaseq_x_flow_cell_id\n )\n\n # THEN a list of samples should be returned\n assert isinstance(samples, list)\n assert isinstance(samples[0], Sample)\n\n # THEN the samples should be from the flow cell\n assert samples[0].run_devices[0].internal_id == novaseq_x_flow_cell_id", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_get_pools(store_with_multiple_pools_for_customer: Store):\n \"\"\"Test that pools can be fetched from the store.\"\"\"\n # GIVEN a database with two pools\n\n # WHEN getting all pools\n pools: list[Pool] = store_with_multiple_pools_for_customer.get_pools()\n\n # THEN two pools should be returned\n assert len(pools) == 2", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_issubclass_of_autofield(self):\n class MyBigAutoField(models.BigAutoField):\n pass\n\n class MySmallAutoField(models.SmallAutoField):\n pass\n\n tests = [\n MyBigAutoField,\n MySmallAutoField,\n models.BigAutoField,\n models.SmallAutoField,\n ]\n for field in tests:\n with self.subTest(field.__name__):\n self.assertTrue(issubclass(field, models.AutoField))", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def async_update(self) -> None:\n \"\"\"Update state.\"\"\"\n try:\n value = self.router.data[self.key][self.item]\n except KeyError:\n _LOGGER.debug(\"%s[%s] not in data\", self.key, self.item)\n self._available = False\n return\n self._available = True\n self._raw_state = str(value)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_config_flow_user_initiated_success(hass: HomeAssistant) -> None:\n \"\"\"Successful flow manually initialized by the user.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": config_entries.SOURCE_USER}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {}\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n {\n CONF_URL: TEST_URL,\n CONF_USERNAME: TEST_USERNAME,\n CONF_PASSWORD: TEST_PASSWORD,\n },\n )\n\n assert result[\"type\"] is FlowResultType.CREATE_ENTRY\n assert result[\"title\"] == TEST_NAME\n assert result[\"data\"] == {\n CONF_URL: TEST_URL,\n CONF_USERNAME: TEST_USERNAME,\n CONF_PASSWORD: TEST_PASSWORD,\n CONF_IMPORT_PLUGINS: False,\n }", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_extract_entity_ids_from_area(\n hass: HomeAssistant, floor_area_mock\n) -> None:\n \"\"\"Test extract_entity_ids method with areas.\"\"\"\n call = ServiceCall(\"light\", \"turn_on\", {\"area_id\": \"own-area\"})\n\n assert {\n \"light.in_own_area\",\n } == await service.async_extract_entity_ids(hass, call)\n\n call = ServiceCall(\"light\", \"turn_on\", {\"area_id\": \"test-area\"})\n\n assert {\n \"light.in_area\",\n \"light.assigned_to_area\",\n } == await service.async_extract_entity_ids(hass, call)\n\n call = ServiceCall(\"light\", \"turn_on\", {\"area_id\": [\"test-area\", \"diff-area\"]})\n\n assert {\n \"light.in_area\",\n \"light.diff_area\",\n \"light.assigned_to_area\",\n } == await service.async_extract_entity_ids(hass, call)\n\n assert (\n await service.async_extract_entity_ids(\n hass, ServiceCall(\"light\", \"turn_on\", {\"area_id\": ENTITY_MATCH_NONE})\n )\n == set()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def make_approval_node(self, **kwargs):\n if 'name' not in kwargs:\n kwargs['name'] = 'approval node {}'.format(random_title())\n self.related.create_approval_template.post(kwargs)\n return self.get()", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def test_inspect_established_receptor_connections(self):\n '''\n Change link state from ADDING to ESTABLISHED\n if the receptor status KnownConnectionCosts field\n has an entry for the source and target node.\n '''\n hop1 = Instance.objects.create(hostname='hop1')\n hop2 = Instance.objects.create(hostname='hop2')\n hop2addr = ReceptorAddress.objects.create(instance=hop2, address='hop2', port=5678)\n InstanceLink.objects.create(source=hop1, target=hop2addr, link_state=InstanceLink.States.ADDING)\n\n # calling with empty KnownConnectionCosts should not change the link state\n inspect_established_receptor_connections({\"KnownConnectionCosts\": {}})\n assert InstanceLink.objects.get(source=hop1, target=hop2addr).link_state == InstanceLink.States.ADDING\n\n mesh_state = {\"KnownConnectionCosts\": {\"hop1\": {\"hop2\": 1}}}\n inspect_established_receptor_connections(mesh_state)\n assert InstanceLink.objects.get(source=hop1, target=hop2addr).link_state == InstanceLink.States.ESTABLISHED", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def file_links(self) -> FoundLinks:\n return ()", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def test_platform_from_text_simple(product_cpes):\n platform = ssg.build_yaml.Platform.from_text(\"machine\", product_cpes)\n assert platform.get_remediation_conditional(\"ansible\") == \\\n \"ansible_virtualization_type not in [\\\"docker\\\", \\\"lxc\\\", \\\"openvz\\\", \\\"podman\\\", \\\"container\\\"]\"\n assert platform.get_remediation_conditional(\"bash\") == \\\n \"[ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ]\"\n platform_el = platform.to_xml_element()\n assert platform_el.tag == \"{%s}platform\" % cpe_language_namespace\n assert platform_el.get(\"id\") == \"machine\"\n logical_tests = platform_el.findall(\n \"{%s}logical-test\" % cpe_language_namespace)\n assert len(logical_tests) == 1\n assert logical_tests[0].get(\"operator\") == \"AND\"\n assert logical_tests[0].get(\"negate\") == \"false\"\n check_fact_refs = logical_tests[0].findall(\n \"{%s}check-fact-ref\" % cpe_language_namespace)\n assert len(check_fact_refs) == 1\n assert check_fact_refs[0].get(\"system\") == \"http://oval.mitre.org/XMLSchema/oval-definitions-5\"\n assert check_fact_refs[0].get(\"href\") == \"ssg-rhel9-cpe-oval.xml\"\n assert check_fact_refs[0].get(\"id-ref\") == \"oval:ssg-installed_env_is_a_machine:def:1\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def helpscout(request):\n \"\"\"Integration for user details in Help Scout UI.\"\"\"\n if not validate_helpscout_signature(request):\n request.response.status = 403\n return {\"Error\": \"NotAuthorized\"}\n\n email = (\n request.db.query(Email)\n .where(\n func.regexp_replace(Email.email, r\"\\+[^)]*@\", \"@\").ilike(\n re.sub(\n r\"\\+[^)]*@\",\n \"@\",\n request.json_body.get(\"customer\", {}).get(\"email\", \"\"),\n )\n )\n )\n .all()\n )\n\n if len(email) == 0:\n return {\"html\": '<span class=\"badge pending\">No PyPI user found</span>'}\n\n env = request.registry.queryUtility(IJinja2Environment, name=\".jinja2\")\n context = {\"users\": [e.user for e in email]}\n template = env.get_template(\"admin/templates/admin/helpscout/app.html\")\n content = template.render(**context, request=request)\n\n return {\"html\": content}", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def test_blueprint_update_metadata() -> None:\n \"\"\"Test update metadata.\"\"\"\n bp = models.Blueprint(\n {\n \"blueprint\": {\n \"name\": \"Hello\",\n \"domain\": \"automation\",\n },\n }\n )\n\n bp.update_metadata(source_url=\"http://bla.com\")\n assert bp.metadata[\"source_url\"] == \"http://bla.com\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_group_restore_noargs(self, shell):\n \"\"\"\n test do_group_restore with no arguments.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_restore = MagicMock()\n shell.do_group_list = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock()\n shell.client.systemgroup.update = MagicMock()\n shell.client.systemgroup.create = MagicMock()\n logger = MagicMock()\n mprint = MagicMock()\n\n with patch(\"spacecmd.group.print\", mprint) as prn, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_restore(shell, \"\")\n\n assert not shell.do_group_list.called\n assert not shell.client.systemgroup.getDetails.called\n assert not shell.client.systemgroup.update.called\n assert not shell.client.systemgroup.create.called\n assert not logger.debug.called\n assert not logger.error.called\n assert not logger.info.called\n assert not mprint.called\n assert shell.help_group_restore.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_render_files(self):\n \"\"\"Look for all javascript files.\"\"\"\n n = 0\n\n print('Rendering javascript files...')\n\n n += self.download_files('translated', '/js/i18n')\n n += self.download_files('dynamic', '/js/dynamic')\n\n print(f'Rendered {n} javascript files.')", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def HairPress():\n\tglobal ColorIndex, PickedColor\n\n\tColorIndex = 0\n\tPickedColor = HairColor\n\tGetColor()\n\treturn", "smellKey": "0", "smellId": null, "repo": "gemrb_gemrb", "language": "python"} {"function": "async def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up config entry.\"\"\"\n\n def _supported(event: RFXtrxEvent) -> bool:\n return isinstance(event, (ControlEvent, SensorEvent))\n\n def _constructor(\n event: RFXtrxEvent,\n auto: RFXtrxEvent | None,\n device_id: DeviceTuple,\n entity_info: dict[str, Any],\n ) -> list[Entity]:\n entities: list[Entity] = []\n\n if hasattr(event.device, \"COMMANDS\"):\n entities.append(\n RfxtrxEventEntity(\n event.device, device_id, \"COMMANDS\", \"Command\", \"command\"\n )\n )\n\n if hasattr(event.device, \"STATUS\"):\n entities.append(\n RfxtrxEventEntity(\n event.device, device_id, \"STATUS\", \"Sensor Status\", \"status\"\n )\n )\n\n return entities\n\n await async_setup_platform_entry(\n hass, config_entry, async_add_entities, _supported, _constructor\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def validate_auth(\n host: str,\n username: str,\n password: str,\n) -> PyObihai | None:\n \"\"\"Test if the given setting works as expected.\"\"\"\n\n obi = get_pyobihai(host, username, password)\n\n login = obi.check_account()\n if not login:\n LOGGER.debug(\"Invalid credentials\")\n return None\n\n return obi", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __str__(self) -> str:\n requirements = sorted(\n (req for req in self.requirements.values() if not req.comes_from),\n key=lambda req: canonicalize_name(req.name or \"\"),\n )\n return \" \".join(str(req.req) for req in requirements)", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def test_volumes_get_truncated_as_expected(faker: Faker):\n node_uuid = faker.uuid4(cast_to=None)\n run_id = RunID.create()\n assert node_uuid != run_id\n unique_volume_name = DynamicSidecarVolumesPathsResolver.source(\n path=Path(\n f\"/home/user/a-{'-'.join(['very' for _ in range(34)])}-long-home-path/workspace\"\n ),\n node_uuid=node_uuid,\n run_id=run_id,\n )\n\n # if below fails the agent will have issues please check\n constant_part = unique_volume_name[: CHARS_IN_VOLUME_NAME_BEFORE_DIR_NAME - 1]\n assert constant_part == f\"dyv_{run_id}_{node_uuid}\"\n\n assert len(unique_volume_name) == 255\n assert f\"{run_id}\" in unique_volume_name\n assert f\"{node_uuid}\" in unique_volume_name", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_traversal_cant_find(self, db_request):\n organization = DBOrganizationFactory.create()\n root = OrganizationFactory(db_request)\n\n with pytest.raises(KeyError):\n root[organization.name + \"invalid\"]", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "async def test_event_subscribe_rejected(\n hass: HomeAssistant,\n config_entry_mock: MockConfigEntry,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test _device_connect continues when the device rejects a subscription.\n\n Device state will instead be obtained via polling in async_update.\n \"\"\"\n dmr_device_mock.async_subscribe_services.side_effect = UpnpResponseError(status=501)\n config_entry_mock.add_to_hass(hass)\n\n mock_entity_id = await setup_mock_component(hass, config_entry_mock)\n await async_update_entity(hass, mock_entity_id)\n await hass.async_block_till_done()\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n\n # Device should be connected\n assert mock_state.state == MediaPlayerState.IDLE\n\n # Device should not be unsubscribed\n dmr_device_mock.async_unsubscribe_services.assert_not_awaited()\n\n # Unload config entry to clean up\n assert await hass.config_entries.async_remove(config_entry_mock.entry_id) == {\n \"require_restart\": False\n }", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def handle(self, *args, **options):\n output_filename = options[\"output_filename\"]\n logger.info(\"geocoding zipcodes to %s\", output_filename)\n\n if options[\"continue_file\"]:\n mode = \"a\"\n zipcodes = GeocodedZipCodeCsv.read(output_filename)\n start = int(max(zipcodes.keys())) + 1\n else:\n mode = \"w\"\n start = 0\n\n logger.info(\"starting geocoding at %s\", start)\n zipcodes = BulkZipCodeGeocoder().geocode_zipcodes(start=start)\n\n with open(output_filename, mode) as f:\n GeocodedZipCodeCsv.write(f, zipcodes)", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "async def test_remove_volumes_without_backup_for_service(\n rpc_client: RabbitMQRPCClient,\n swarm_stack_name: str,\n docker_node_id: str,\n mocked_remove_service_volumes: AsyncMock,\n):\n assert mocked_remove_service_volumes.call_count == 0\n await volumes.remove_volumes_without_backup_for_service(\n rpc_client,\n docker_node_id=docker_node_id,\n swarm_stack_name=swarm_stack_name,\n node_id=uuid4(),\n )\n assert mocked_remove_service_volumes.call_count == 1", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def mocked_remove_all_volumes(mocker: pytest_mock.MockerFixture) -> AsyncMock:\n return mocker.patch(\n \"simcore_service_agent.services.volumes_manager.VolumesManager.remove_all_volumes\"\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def async_get_translations(\n hass: HomeAssistant,\n language: str,\n category: str,\n integrations: Iterable[str] | None = None,\n config_flow: bool | None = None,\n ) -> dict[str, Any]:\n \"\"\"Return all backend translations.\"\"\"\n translations_called.set()\n await translations_wait.wait()\n translation_key_prefix = f\"component.{logger_domain}.services.set_default_level\"\n return {\n f\"{translation_key_prefix}.name\": \"Translated name\",\n f\"{translation_key_prefix}.description\": \"Translated description\",\n f\"{translation_key_prefix}.fields.level.name\": \"Field name\",\n f\"{translation_key_prefix}.fields.level.description\": \"Field description\",\n f\"{translation_key_prefix}.fields.level.example\": \"Field example\",\n }", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __rich_console__(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> \"RenderResult\":\n width, height = options.size\n style = console.get_style(self.style) if self.style else None\n render_options = options.update(width=width, height=height)\n lines = console.render_lines(\n self.renderable or \"\", render_options, style=style, pad=True\n )\n lines = Segment.set_shape(lines, width, height, style=style)\n new_line = Segment(\"\\n\\r\") if self.application_mode else Segment.line()\n for last, line in loop_last(lines):\n yield from line\n if not last:\n yield new_line", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def get_name(channel):\n channel_data = self._tv.channels.get(str(channel[\"ccid\"]))\n if channel_data:\n return channel_data[\"name\"]\n return f\"Channel: {channel['ccid']}\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_certificate_snapshot(request, *args, **kwargs):\n snapshot_form = ElecSnapshotForm(request.GET)\n\n if not snapshot_form.is_valid():\n return ErrorResponse(400, ElecSnapshotError.MALFORMED_PARAMS, snapshot_form.errors)\n\n entity_id = snapshot_form.cleaned_data[\"entity_id\"]\n year = snapshot_form.cleaned_data[\"year\"]\n\n try:\n provision_certificates = ElecProvisionCertificate.objects.filter(cpo_id=entity_id)\n provision_certificates_of_year = provision_certificates.filter(year=year)\n\n transfer_certificates = ElecTransferCertificate.objects.filter(transfer_date__year=year, supplier_id=entity_id)\n\n return SuccessResponse(\n {\n \"provisioned_energy\": provision_certificates.aggregate(Sum(\"energy_amount\"))[\"energy_amount__sum\"] or 0,\n \"remaining_energy\": provision_certificates.aggregate(Sum(\"remaining_energy_amount\"))[\n \"remaining_energy_amount__sum\"\n ]\n or 0,\n \"provision_certificates_available\": provision_certificates_of_year.filter(\n remaining_energy_amount__gt=0\n ).count(),\n \"provision_certificates_history\": provision_certificates_of_year.filter(remaining_energy_amount=0).count(),\n \"transferred_energy\": transfer_certificates.aggregate(Sum(\"energy_amount\"))[\"energy_amount__sum\"] or 0,\n \"transfer_certificates_pending\": transfer_certificates.filter(\n status=ElecTransferCertificate.PENDING\n ).count(),\n \"transfer_certificates_accepted\": transfer_certificates.filter(\n status=ElecTransferCertificate.ACCEPTED\n ).count(),\n \"transfer_certificates_rejected\": transfer_certificates.filter(\n status=ElecTransferCertificate.REJECTED\n ).count(),\n }\n )\n except Exception:\n traceback.print_exc()\n return ErrorResponse(400, ElecSnapshotError.SNAPSHOT_FAILED)", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def run_test(self):\n self.log.info(\"Mine 4 blocks on Node 0\")\n self.generate(self.nodes[0], 4, sync_fun=self.no_op)\n assert_equal(self.nodes[0].getblockcount(), 204)\n\n self.log.info(\"Mine competing 3 blocks on Node 1\")\n self.generate(self.nodes[1], 3, sync_fun=self.no_op)\n assert_equal(self.nodes[1].getblockcount(), 203)\n short_tip = self.nodes[1].getbestblockhash()\n\n self.log.info(\"Connect nodes to sync headers\")\n self.connect_nodes(0, 1)\n self.sync_blocks(self.nodes[0:2])\n\n self.log.info(\"Node 0 should only have the header for node 1's block 3\")\n x = next(filter(lambda x: x['hash'] == short_tip, self.nodes[0].getchaintips()))\n assert_equal(x['status'], \"headers-only\")\n assert_raises_rpc_error(-1, \"Block not found on disk\", self.nodes[0].getblock, short_tip)\n\n self.log.info(\"Fetch block from node 1\")\n peers = self.nodes[0].getpeerinfo()\n assert_equal(len(peers), 1)\n peer_0_peer_1_id = peers[0][\"id\"]\n\n self.log.info(\"Arguments must be valid\")\n assert_raises_rpc_error(-8, \"hash must be of length 64 (not 4, for '1234')\", self.nodes[0].getblockfrompeer, \"1234\", peer_0_peer_1_id)\n assert_raises_rpc_error(-3, \"JSON value of type number is not of expected type string\", self.nodes[0].getblockfrompeer, 1234, peer_0_peer_1_id)\n assert_raises_rpc_error(-3, \"JSON value of type string is not of expected type number\", self.nodes[0].getblockfrompeer, short_tip, \"0\")\n\n self.log.info(\"We must already have the header\")\n assert_raises_rpc_error(-1, \"Block header missing\", self.nodes[0].getblockfrompeer, \"00\" * 32, 0)\n\n self.log.info(\"Non-existent peer generates error\")\n for peer_id in [-1, peer_0_peer_1_id + 1]:\n assert_raises_rpc_error(-1, \"Peer does not exist\", self.nodes[0].getblockfrompeer, short_tip, peer_id)\n\n self.log.info(\"Fetching from pre-segwit peer generates error\")\n self.nodes[0].add_p2p_connection(P2PInterface(), services=P2P_SERVICES & ~NODE_WITNESS)\n peers = self.nodes[0].getpeerinfo()\n assert_equal(len(peers), 2)\n presegwit_peer_id = peers[1][\"id\"]\n assert_raises_rpc_error(-1, \"Pre-SegWit peer\", self.nodes[0].getblockfrompeer, short_tip, presegwit_peer_id)\n\n self.log.info(\"Successful fetch\")\n result = self.nodes[0].getblockfrompeer(short_tip, peer_0_peer_1_id)\n self.wait_until(lambda: self.check_for_block(node=0, hash=short_tip), timeout=1)\n assert_equal(result, {})\n\n self.log.info(\"Don't fetch blocks we already have\")\n assert_raises_rpc_error(-1, \"Block already downloaded\", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id)\n\n self.log.info(\"Don't fetch blocks while the node has not synced past it yet\")\n # For this test we need node 1 in prune mode and as a side effect this also disconnects\n # the nodes which is also necessary for the rest of the test.\n self.restart_node(1, [\"-prune=550\"])\n\n # Generate a block on the disconnected node that the pruning node is not connected to\n blockhash = self.generate(self.nodes[0], 1, sync_fun=self.no_op)[0]\n block_hex = self.nodes[0].getblock(blockhash=blockhash, verbosity=0)\n block = from_hex(CBlock(), block_hex)\n\n # Connect a P2PInterface to the pruning node and have it submit only the header of the\n # block that the pruning node has not seen\n node1_interface = self.nodes[1].add_p2p_connection(P2PInterface())\n node1_interface.send_and_ping(msg_headers([block]))\n\n # Get the peer id of the P2PInterface from the pruning node\n node1_peers = self.nodes[1].getpeerinfo()\n assert_equal(len(node1_peers), 1)\n node1_interface_id = node1_peers[0][\"id\"]\n\n # Trying to fetch this block from the P2PInterface should not be possible\n error_msg = \"In prune mode, only blocks that the node has already synced previously can be fetched from a peer\"\n assert_raises_rpc_error(-1, error_msg, self.nodes[1].getblockfrompeer, blockhash, node1_interface_id)\n\n self.log.info(\"Connect pruned node\")\n # We need to generate more blocks to be able to prune\n self.connect_nodes(0, 2)\n pruned_node = self.nodes[2]\n self.generate(self.nodes[0], 400, sync_fun=self.no_op)\n self.sync_blocks([self.nodes[0], pruned_node])\n pruneheight = pruned_node.pruneblockchain(300)\n assert_equal(pruneheight, 248)\n # Ensure the block is actually pruned\n pruned_block = self.nodes[0].getblockhash(2)\n assert_raises_rpc_error(-1, \"Block not available (pruned data)\", pruned_node.getblock, pruned_block)\n\n self.log.info(\"Fetch pruned block\")\n peers = pruned_node.getpeerinfo()\n assert_equal(len(peers), 1)\n pruned_node_peer_0_id = peers[0][\"id\"]\n result = pruned_node.getblockfrompeer(pruned_block, pruned_node_peer_0_id)\n self.wait_until(lambda: self.check_for_block(node=2, hash=pruned_block), timeout=1)\n assert_equal(result, {})\n\n self.log.info(\"Fetched block persists after next pruning event\")\n self.generate(self.nodes[0], 250, sync_fun=self.no_op)\n self.sync_blocks([self.nodes[0], pruned_node])\n pruneheight += 251\n assert_equal(pruned_node.pruneblockchain(700), pruneheight)\n assert_equal(pruned_node.getblock(pruned_block)[\"hash\"], \"36c56c5b5ebbaf90d76b0d1a074dcb32d42abab75b7ec6fa0ffd9b4fbce8f0f7\")\n\n self.log.info(\"Fetched block can be pruned again when prune height exceeds the height of the tip at the time when the block was fetched\")\n self.generate(self.nodes[0], 250, sync_fun=self.no_op)\n self.sync_blocks([self.nodes[0], pruned_node])\n pruneheight += 250\n assert_equal(pruned_node.pruneblockchain(1000), pruneheight)\n assert_raises_rpc_error(-1, \"Block not available (pruned data)\", pruned_node.getblock, pruned_block)", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def __class__(self):\n \"\"\"Return the given profile class.\"\"\"\n return self.profile_class", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def app_resources(package_dir: Path) -> list[str]:\n return [\n str(p.relative_to(package_dir)) for p in (package_dir / \"api\").rglob(\"*.y*ml\")\n ]", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def is_opening(self) -> bool:\n \"\"\"Return if the cover is opening.\"\"\"\n return self._channel.is_opening()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_setup_integration_yaml(\n hass: HomeAssistant, load_yaml_integration: None\n) -> None:\n \"\"\"Test sensor setup.\"\"\"\n\n entity_state = hass.states.get(\"binary_sensor.test\")\n assert entity_state\n assert entity_state.state == STATE_ON\n assert entity_state.name == \"Test\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(self, app: web.Application):\n self._app = app", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def is_key_alive(self, key: UserSessionDict) -> bool:\n hash_key = f\"{self._hash_key(key)}:{_ALIVE_SUFFIX}\"\n return bool(await self.client.exists(hash_key) > 0)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def test_camera_disabled(hass: HomeAssistant) -> None:\n \"\"\"Test that Axis camera platform is loaded properly but does not create camera entity.\"\"\"\n assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 0", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def async_select_source(self, source: str) -> None:\n \"\"\"Set the input source.\"\"\"\n if source_id := _inverted(self._sources).get(source):\n await self._tv.setSource(source_id)\n await self._async_update_soon()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_turn_off(self, **kwargs: Any) -> None:\n \"\"\"Turn the device off.\"\"\"\n await self.coordinator.roku.remote(\"poweroff\")\n await self.coordinator.async_request_refresh()", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n device: RFXtrxDevice,\n device_id: DeviceTuple,\n device_attribute: str,\n value_attribute: str,\n translation_key: str,\n ) -> None:\n \"\"\"Initialize the sensor.\"\"\"\n super().__init__(device, device_id)\n commands: dict[int, str] = getattr(device, device_attribute)\n self._attr_name = None\n self._attr_unique_id = \"_\".join(x for x in device_id)\n self._attr_event_types = [slugify(command) for command in commands.values()]\n self._attr_translation_key = translation_key\n self._value_attribute = value_attribute", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def subgraph_get_vertices(ctx: mgp.ProcCtx) -> mgp.Record(node=mgp.Vertex):\n return [mgp.Record(node=vertex) for vertex in ctx.graph.vertices]", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def resource_tracker_service_run_db(\n postgres_db: sa.engine.Engine, random_resource_tracker_service_run\n) -> Iterator[list]:\n with postgres_db.connect() as con:\n # removes all projects before continuing\n con.execute(resource_tracker_service_runs.delete())\n created_services = []\n for _ in range(_TOTAL_GENERATED_RESOURCE_TRACKER_SERVICE_RUNS_ROWS):\n result = con.execute(\n resource_tracker_service_runs.insert()\n .values(**random_resource_tracker_service_run(user_id=_USER_ID))\n .returning(resource_tracker_service_runs)\n )\n row = result.first()\n assert row\n created_services.append(row)\n yield created_services\n\n con.execute(resource_tracker_service_runs.delete())", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_case_in_uploaded_observations(helpers: StoreHelpers, sample_store: Store, loqusdb_id: str):\n \"\"\"Test retrieval of uploaded observations.\"\"\"\n\n # GIVEN a case with observations that has been uploaded to Loqusdb\n analysis: Analysis = helpers.add_analysis(store=sample_store, workflow=Workflow.MIP_DNA)\n analysis.case.customer.loqus_upload = True\n sample: Sample = helpers.add_sample(sample_store, loqusdb_id=loqusdb_id)\n link = sample_store.relate_sample(analysis.case, sample, PhenotypeStatus.UNKNOWN)\n sample_store.session.add(link)\n assert analysis.case.analyses\n for link in analysis.case.links:\n assert link.sample.loqusdb_id is not None\n\n # WHEN getting observations to upload\n uploaded_observations: Query = sample_store.observations_uploaded()\n\n # THEN the case should be in the returned query\n assert analysis.case in uploaded_observations", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_setup_entry_mac_address(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n config_entry_mock: MockConfigEntry,\n ssdp_scanner_mock: Mock,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Entry with a MAC address will set up and set the device registry connection.\"\"\"\n config_entry_mock.add_to_hass(hass)\n mock_entity_id = await setup_mock_component(hass, config_entry_mock)\n await async_update_entity(hass, mock_entity_id)\n await hass.async_block_till_done()\n # Check the device registry connections for MAC address\n dev_reg = async_get_dr(hass)\n device = dev_reg.async_get_device(\n connections={(CONNECTION_UPNP, MOCK_DEVICE_UDN)},\n identifiers=set(),\n )\n assert device is not None\n assert (CONNECTION_NETWORK_MAC, MOCK_MAC_ADDRESS) in device.connections", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_lock(\n hass: HomeAssistant,\n matter_client: MagicMock,\n door_lock: MatterNode,\n) -> None:\n \"\"\"Test door lock.\"\"\"\n await hass.services.async_call(\n \"lock\",\n \"unlock\",\n {\n \"entity_id\": \"lock.mock_door_lock\",\n },\n blocking=True,\n )\n\n assert matter_client.send_device_command.call_count == 1\n assert matter_client.send_device_command.call_args == call(\n node_id=door_lock.node_id,\n endpoint_id=1,\n command=clusters.DoorLock.Commands.UnlockDoor(),\n timed_request_timeout_ms=1000,\n )\n matter_client.send_device_command.reset_mock()\n\n await hass.services.async_call(\n \"lock\",\n \"lock\",\n {\n \"entity_id\": \"lock.mock_door_lock\",\n },\n blocking=True,\n )\n\n assert matter_client.send_device_command.call_count == 1\n assert matter_client.send_device_command.call_args == call(\n node_id=door_lock.node_id,\n endpoint_id=1,\n command=clusters.DoorLock.Commands.LockDoor(),\n timed_request_timeout_ms=1000,\n )\n matter_client.send_device_command.reset_mock()\n\n state = hass.states.get(\"lock.mock_door_lock\")\n assert state\n assert state.state == STATE_LOCKED\n\n set_node_attribute(door_lock, 1, 257, 0, 0)\n await trigger_subscription_callback(hass, matter_client)\n\n state = hass.states.get(\"lock.mock_door_lock\")\n assert state\n assert state.state == STATE_UNLOCKING\n\n set_node_attribute(door_lock, 1, 257, 0, 2)\n await trigger_subscription_callback(hass, matter_client)\n\n state = hass.states.get(\"lock.mock_door_lock\")\n assert state\n assert state.state == STATE_UNLOCKED\n\n set_node_attribute(door_lock, 1, 257, 0, 0)\n await trigger_subscription_callback(hass, matter_client)\n\n state = hass.states.get(\"lock.mock_door_lock\")\n assert state\n assert state.state == STATE_LOCKING\n\n set_node_attribute(door_lock, 1, 257, 0, None)\n await trigger_subscription_callback(hass, matter_client)\n\n state = hass.states.get(\"lock.mock_door_lock\")\n assert state\n assert state.state == STATE_UNKNOWN", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_activationkey_list_args(self, shell):\n \"\"\"\n Test activationkey_list command is calling listActivationKeys API.\n \"\"\"\n shell.client.activationkey.listActivationKeys = MagicMock(\n return_value=[\n {\"key\": \"some_patches\", \"description\": \"Some key\"},\n {\"key\": \"some_stuff\", \"description\": \"Some other key\"},\n {\"key\": \"some_reactivation\", \"description\": \"Kickstart re-activation key\"},\n ]\n )\n\n mprint = MagicMock()\n with patch(\"spacecmd.activationkey.print\", mprint) as mpr:\n ret = sorted(spacecmd.activationkey.do_activationkey_list(shell, \"key some*\", doreturn=True))\n assert len(ret) == 2\n assert ret == ['some_patches', 'some_stuff']", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def background_create_ticket_sources_from_lots(lots: QuerySet) -> None:\n create_ticket_sources_from_lots(lots)", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def periodic_update_2bs_certificates() -> None:\n update_2bs_certificates(email=True)", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def start(self):\n self.database.start()", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def test_do_activationkey_addconfigchannels_setusagelimit_noargs(self, shell):\n \"\"\"\n Test do_activationkey_addconfigchannels_setusagelimit involes help message on issuficient arguments.\n \"\"\"\n shell.help_activationkey_setusagelimit = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n shell.client.activationkey.getDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_setusagelimit(shell, \"\")\n assert shell.help_activationkey_setusagelimit.called\n assert not shell.client.activationkey.setDetails.called\n assert not shell.client.activationkey.getDetails.called\n\n spacecmd.activationkey.do_activationkey_setusagelimit(shell, \"key\")\n assert shell.help_activationkey_setusagelimit.called\n assert not shell.client.activationkey.setDetails.called\n assert not shell.client.activationkey.getDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def _scan_directory(self) -> None:\n \"\"\"Scans directory once and populates both page_candidates\n and project_name_to_urls at the same time\n \"\"\"\n for entry in os.scandir(self._path):\n url = path_to_url(entry.path)\n if _is_html_file(url):\n self._page_candidates.append(url)\n continue\n\n # File must have a valid wheel or sdist name,\n # otherwise not worth considering as a package\n try:\n project_filename = parse_wheel_filename(entry.name)[0]\n except (InvalidWheelFilename, InvalidVersion):\n try:\n project_filename = parse_sdist_filename(entry.name)[0]\n except (InvalidSdistFilename, InvalidVersion):\n continue\n\n self._project_name_to_urls[project_filename].append(url)\n self._scanned_directory = True", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def index(request):\n active_users = User.objects.filter(is_active=True).order_by(\"username\")\n inactive_users = User.objects.filter(is_active=False).order_by(\"username\")\n groups = Group.objects.all().order_by(\"name\")\n\n return render(\n request,\n \"permissions_viewer/index.html\",\n {\n \"active_users\": active_users,\n \"inactive_users\": inactive_users,\n \"groups\": groups,\n },\n )", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "def test_get_application_by_tag(microbial_store: Store, tag: str = MicrosaltAppTags.MWRNXTR003):\n \"\"\"Test function to return the application by tag.\"\"\"\n\n # GIVEN a store with application records\n\n # WHEN getting the query for the flow cells\n application: Application = microbial_store.get_application_by_tag(tag=tag)\n\n # THEN return a application with the supplied application tag\n assert application.tag == tag", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def setUp(self):\n self.engine = engines[\"wagtail-env\"]", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "async def test_update(\n hass: HomeAssistant,\n caplog: pytest.LogCaptureFixture,\n freezer: FrozenDateTimeFactory,\n) -> None:\n \"\"\"Test updates.\"\"\"\n await setup_version_integration(hass)\n assert hass.states.get(\"sensor.local_installation\").state == MOCK_VERSION\n\n await mock_get_version_update(hass, freezer, version=\"1970.1.1\")\n assert hass.states.get(\"sensor.local_installation\").state == \"1970.1.1\"\n\n assert \"Error fetching version data\" not in caplog.text\n await mock_get_version_update(hass, freezer, side_effect=HaVersionException)\n assert hass.states.get(\"sensor.local_installation\").state == \"unavailable\"\n assert \"Error fetching version data\" in caplog.text", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n obj = self.get_obj(kwargs[\"cluster_id\"], kwargs[\"hs_id\"])\n serializer = self.get_serializer(obj)\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def test_date_formatter_default_format(self):\n tmpl = self.engine.from_string(\"{{ date_formatter(d) }}\")\n self.assertEqual(tmpl.render({\"d\": date(2018, 2, 1)}), \"Feb 01, 2018\")", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "def test_add_warning_elements():\n rule_el = ET.Element(\"{%s}Rule\" % XCCDF12_NS)\n warnings = [\n {\"general\": \"hot beverage\"},\n {\"general\": \"inflammable material\"}\n ]\n ssg.build_yaml.add_warning_elements(rule_el, warnings)\n assert rule_el.tag == \"{%s}Rule\" % XCCDF12_NS\n assert len(rule_el) == 2\n warning_els = rule_el.findall(\"{%s}warning\" % XCCDF12_NS)\n assert len(warning_els) == 2\n for warning_el in warning_els:\n assert len(warning_el) == 0\n assert len(warning_el.attrib) == 1\n assert warning_el.get(\"category\") == \"general\"\n texts = [x.text for x in warning_els]\n assert \"hot beverage\" in texts\n assert \"inflammable material\" in texts", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "async def _on_startup() -> None:\n assert app.state.rabbitmq_client # nosec\n\n # Connect to the as an external process in write-only mode\n # SEE https://python-socketio.readthedocs.io/en/stable/server.html#emitting-from-external-processes\n assert settings.RABBIT_SETTINGS # nosec\n app.state.external_socketio = socketio.AsyncAioPikaManager(\n url=settings.RABBIT_SETTINGS.dsn, logger=_logger, write_only=True\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'alias_used_on', type_='foreignkey')\n op.drop_column('alias_used_on', 'user_id')\n # ### end Alembic commands ###", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def test_active_subscription(self, db_session):\n organization = DBOrganizationFactory.create()\n stripe_customer = DBStripeCustomerFactory.create()\n DBOrganizationStripeCustomerFactory.create(\n organization=organization, customer=stripe_customer\n )\n subscription = DBStripeSubscriptionFactory.create(customer=stripe_customer)\n DBOrganizationStripeSubscriptionFactory.create(\n organization=organization, subscription=subscription\n )\n assert organization.active_subscription is not None", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "async def test_option_block_clients(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test the changes to option reflects accordingly.\"\"\"\n config_entry = await setup_unifi_integration(\n hass,\n aioclient_mock,\n options={CONF_BLOCK_CLIENT: [BLOCKED[\"mac\"]]},\n clients_all_response=[BLOCKED, UNBLOCKED],\n )\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n\n # Add a second switch\n hass.config_entries.async_update_entry(\n config_entry,\n options={CONF_BLOCK_CLIENT: [BLOCKED[\"mac\"], UNBLOCKED[\"mac\"]]},\n )\n await hass.async_block_till_done()\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n\n # Remove the second switch again\n hass.config_entries.async_update_entry(\n config_entry,\n options={CONF_BLOCK_CLIENT: [BLOCKED[\"mac\"]]},\n )\n await hass.async_block_till_done()\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1\n\n # Enable one and remove another one\n hass.config_entries.async_update_entry(\n config_entry,\n options={CONF_BLOCK_CLIENT: [UNBLOCKED[\"mac\"]]},\n )\n await hass.async_block_till_done()\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0\n\n # Remove one\n hass.config_entries.async_update_entry(\n config_entry,\n options={CONF_BLOCK_CLIENT: []},\n )\n await hass.async_block_till_done()\n assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def get(self, request: web.Request) -> web.Response:\n \"\"\"Return a test result.\"\"\"\n return self.json({\"test\": True})", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n coordinator: AirzoneUpdateCoordinator,\n description: SensorEntityDescription,\n entry: ConfigEntry,\n ) -> None:\n \"\"\"Initialize.\"\"\"\n super().__init__(coordinator, entry)\n self._attr_unique_id = f\"{self._attr_unique_id}_ws_{description.key}\"\n self.entity_description = description\n self._async_update_attrs()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def set_trace(self, trace: dict[str, deque[TraceElement]] | None) -> None:\n \"\"\"Set action trace.\"\"\"\n self._trace = trace", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n name: str,\n validator: Validator,\n ) -> None:\n super().__init__(\n name=name,\n validator=validator,\n )", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(\n self,\n candidates_from_page: CandidatesFromPage,\n page_validator: PageValidator,\n link: Link,\n ) -> None:\n self._candidates_from_page = candidates_from_page\n self._page_validator = page_validator\n self._link = link", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def test_volumes_unique_name_max_length_can_be_created(\n faker: Faker, docker_swarm: None\n):\n a_uuid = faker.uuid4()\n volume_name_len_255 = (a_uuid * 100)[:255]\n await assert_creation_and_removal(volume_name_len_255)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def runners(self):\n return {\"MemgraphRunner\": MemgraphRunner, \"NeoRunner\": NeoRunner}", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "async def test_call_with_both_required_features(\n hass: HomeAssistant, mock_entities\n) -> None:\n \"\"\"Test service calls invoked only if entity has both features.\"\"\"\n test_service_mock = AsyncMock(return_value=None)\n await service.entity_service_call(\n hass,\n mock_entities,\n HassJob(test_service_mock),\n ServiceCall(\"test_domain\", \"test_service\", {\"entity_id\": \"all\"}),\n required_features=[SUPPORT_A | SUPPORT_B],\n )\n\n assert test_service_mock.call_count == 1\n assert [call[0][0] for call in test_service_mock.call_args_list] == [\n mock_entities[\"light.bedroom\"]\n ]", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_illumina_metrics_entry_by_device_sample_and_lane(\n store_with_illumina_sequencing_data: Store,\n novaseq_x_flow_cell_id: str,\n selected_novaseq_x_sample_ids: list[str],\n):\n \"\"\"Test that Illumina sample sequencing metrics are filtered by sample, device and lane.\"\"\"\n # GIVEN a store with Illumina Sample Sequencing Metrics for each sample in the run directories\n\n # GIVEN a sample id and a lane\n sample_id: str = selected_novaseq_x_sample_ids[0]\n lane: int = 1\n\n # WHEN fetching an Illumina sample sequencing metrics\n metrics: IlluminaSampleSequencingMetrics = (\n store_with_illumina_sequencing_data.get_illumina_metrics_entry_by_device_sample_and_lane(\n device_internal_id=novaseq_x_flow_cell_id, sample_internal_id=sample_id, lane=lane\n )\n )\n\n # THEN assert that the correct metrics object is returned\n assert metrics\n assert metrics.sample.internal_id == sample_id\n assert metrics.instrument_run.device.internal_id == novaseq_x_flow_cell_id\n assert metrics.flow_cell_lane == lane", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def num_interior_rings(self):\n \"Return the number of interior rings.\"\n # Getting the number of rings\n return capi.get_nrings(self.ptr)", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def _async_build_by_language(\n self, radios: RadioBrowser, item: MediaSourceItem\n ) -> list[BrowseMediaSource]:\n \"\"\"Handle browsing radio stations by language.\"\"\"\n category, _, language = (item.identifier or \"\").partition(\"/\")\n if category == \"language\" and language:\n stations = await radios.stations(\n filter_by=FilterBy.LANGUAGE_EXACT,\n filter_term=language,\n hide_broken=True,\n order=Order.NAME,\n reverse=False,\n )\n return self._async_build_stations(radios, stations)\n\n if category == \"language\":\n languages = await radios.languages(order=Order.NAME, hide_broken=True)\n return [\n BrowseMediaSource(\n domain=DOMAIN,\n identifier=f\"language/{language.code}\",\n media_class=MediaClass.DIRECTORY,\n media_content_type=MediaType.MUSIC,\n title=language.name,\n can_play=False,\n can_expand=True,\n thumbnail=language.favicon,\n )\n for language in languages\n ]\n\n if not item.identifier:\n return [\n BrowseMediaSource(\n domain=DOMAIN,\n identifier=\"language\",\n media_class=MediaClass.DIRECTORY,\n media_content_type=MediaType.MUSIC,\n title=\"By Language\",\n can_play=False,\n can_expand=True,\n )\n ]\n\n return []", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def get(request):\n \"\"\"Receive authorization code.\"\"\"\n hass = request.app[KEY_HASS]\n if \"code\" in request.query:\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": \"code\"}, data=request.query[\"code\"]\n )\n )\n return \"OK!\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def validate(cls, v: float) -> float:\n if v is None:\n msg = \"Mostly cannot be None\"\n raise TypeError(msg)\n if not isinstance(v, Number):\n msg = \"Mostly is not a valid float.\"\n raise TypeError(msg)\n if v < 0.0:\n msg = \"Mostly must be greater than or equal to 0.\"\n raise TypeError(msg)\n if v > 1.0:\n msg = \"Mostly must be less than or equal to 1.\"\n raise TypeError(msg)\n return v", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "async def async_turn_off(self, **kwargs: Any) -> None:\n \"\"\"Turn the switch off.\"\"\"\n await self._async_set_state(False)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def handler(context, event):\n context.logger.info(\"Run faster_rcnn_inception_v2_coco model\")\n data = event.body\n buf = io.BytesIO(base64.b64decode(data[\"image\"]))\n threshold = float(data.get(\"threshold\", 0.5))\n image = Image.open(buf)\n\n (boxes, scores, classes, num_detections) = context.user_data.model_handler.infer(image)\n\n results = []\n for i in range(int(num_detections[0])):\n obj_class = int(classes[0][i])\n obj_score = scores[0][i]\n obj_label = context.user_data.labels.get(obj_class, \"unknown\")\n if obj_score >= threshold:\n xtl = boxes[0][i][1] * image.width\n ytl = boxes[0][i][0] * image.height\n xbr = boxes[0][i][3] * image.width\n ybr = boxes[0][i][2] * image.height\n\n results.append({\n \"confidence\": str(obj_score),\n \"label\": obj_label,\n \"points\": [xtl, ytl, xbr, ybr],\n \"type\": \"rectangle\",\n })\n\n return context.Response(body=json.dumps(results), headers={},\n content_type='application/json', status_code=200)", "smellKey": "0", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def test_check_activationkey_not_a_key(self, shell):\n \"\"\"\n Test check activation key helper returns False on not a key.\n \"\"\"\n shell.is_activationkey = MagicMock(return_value=False)\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n assert not spacecmd.activationkey.check_activationkey(shell, \"some_not_a_key\")\n assert logger.error.called\n assert logger.error.call_args_list[0][0][0] == 'invalid activationkey label some_not_a_key'", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def async_media_stop(self) -> None:\n \"\"\"Send play command to media player.\"\"\"\n await self._tv.sendKey(\"Stop\")\n await self._async_update_soon()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def handle(self, *args, **options):\n menu = Menu.objects.get(language=options[\"language\"])\n json.dump(list(menu.submenus.raw_data), options[\"filename\"], indent=4)", "smellKey": "0", "smellId": null, "repo": "cfpb_consumerfinance", "language": "python"} {"function": "def test_do_activationkey_removepackages_args(self, shell):\n \"\"\"\n Test remove packages method calls \"removePackages\" API call.\n \"\"\"\n shell.help_activationkey_removepackages = MagicMock()\n shell.client.activationkey.removePackages = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removepackages(shell, \"key package\")\n assert not shell.help_activationkey_removepackages.called\n assert shell.client.activationkey.removePackages.called\n session, fun, args = shell.client.activationkey.removePackages.call_args_list[0][0]\n assert session == shell.session\n assert fun == \"key\"\n assert isinstance(args, list)\n assert len(args) == 1\n assert \"name\" in args[0]\n assert args[0][\"name\"] == \"package\"", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_do_activationkey_details_noargs(self, shell):\n \"\"\"\n Test activationkey_details shows a help screen if no sufficient arguments has been passed.\n \"\"\"\n shell.help_activationkey_details = MagicMock()\n shell.client.activationkey.getDetails = MagicMock()\n shell.client.activationkey.listConfigChannels = MagicMock()\n shell.client.activationkey.checkConfigDeployment = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_listsystems(shell, \"\")\n assert shell.help_activationkey_listsystems.called\n assert not shell.client.activationkey.getDetails.called\n assert not shell.client.systemgroup.getDetails.called\n assert not shell.client.activationkey.listConfigChannels.called\n assert not shell.client.activationkey.checkConfigDeployment.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def __init__(\n self,\n coordinator: PowerviewShadeUpdateCoordinator,\n device_info: PowerviewDeviceInfo,\n room_name: str,\n shade: BaseShade,\n name: str,\n description: PowerviewButtonDescription,\n ) -> None:\n \"\"\"Initialize the button entity.\"\"\"\n super().__init__(coordinator, device_info, room_name, shade, name)\n self.entity_description: PowerviewButtonDescription = description\n self._attr_unique_id = f\"{self._attr_unique_id}_{description.key}\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def _async_update(self) -> None:\n \"\"\"Update.\"\"\"\n called.append(1)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def is_appengine():\n return is_local_appengine() or is_prod_appengine()", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def async_turn_on(self, **kwargs: Any) -> None:\n \"\"\"Turn the siren on for 30 seconds.\"\"\"\n await self._async_set_switch(1)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def battery_level(self) -> int | None:\n \"\"\"Return the battery level of the device.\n\n Percentage from 0-100.\n \"\"\"\n return self.entity_data.entity.battery_level", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_platform_from_text_or(product_cpes):\n platform = ssg.build_yaml.Platform.from_text(\"ntp or chrony\", product_cpes)\n assert platform.get_remediation_conditional(\"bash\") == \"( rpm --quiet -q chrony || rpm --quiet -q ntp )\"\n assert platform.get_remediation_conditional(\"ansible\") == \\\n \"( \\\"chrony\\\" in ansible_facts.packages or \\\"ntp\\\" in ansible_facts.packages )\"\n platform_el = platform.to_xml_element()\n assert platform_el.tag == \"{%s}platform\" % cpe_language_namespace\n assert platform_el.get(\"id\") == \"chrony_or_ntp\"\n logical_tests = platform_el.findall(\n \"{%s}logical-test\" % cpe_language_namespace)\n assert len(logical_tests) == 1\n assert logical_tests[0].get(\"operator\") == \"OR\"\n assert logical_tests[0].get(\"negate\") == \"false\"\n check_fact_refs = logical_tests[0].findall(\n \"{%s}check-fact-ref\" % cpe_language_namespace)\n assert len(check_fact_refs) == 2\n assert check_fact_refs[0].get(\"system\") == \"http://oval.mitre.org/XMLSchema/oval-definitions-5\"\n assert check_fact_refs[0].get(\"href\") == \"ssg-rhel9-cpe-oval.xml\"\n assert check_fact_refs[0].get(\"id-ref\") == \"oval:ssg-installed_env_has_chrony_package:def:1\"\n assert check_fact_refs[1].get(\"system\") == \"http://oval.mitre.org/XMLSchema/oval-definitions-5\"\n assert check_fact_refs[1].get(\"href\") == \"ssg-rhel9-cpe-oval.xml\"\n assert check_fact_refs[1].get(\"id-ref\") == \"oval:ssg-installed_env_has_ntp_package:def:1\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "async def async_activate(self, **kwargs: Any) -> None:\n \"\"\"Activate the scene.\"\"\"\n try:\n await self._lj.activate_scene(self._index)\n except LiteJetError as exc:\n raise HomeAssistantError from exc", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(self) -> None:\n \"\"\"Initialize the config flow.\"\"\"\n self._discovered_devices: dict[str, str] = {}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n avm_wrapper: AvmWrapper,\n device_friendly_name: str,\n ) -> None:\n \"\"\"Init FRITZ!Box connectivity class.\"\"\"\n description = FritzUpdateEntityDescription(\n key=\"update\", name=\"FRITZ!OS\", value_fn=None\n )\n super().__init__(avm_wrapper, device_friendly_name, description)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def is_valid_dash_address(addr: str) -> bool:\n try:\n res = coinaddrvalidator.validate(\"dash\", addr).valid\n return res\n except Exception:\n return False", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def installed_version(self) -> str | None:\n \"\"\"Version currently in use.\"\"\"\n return self.coordinator.current_firmware", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def simulate_running_task(\n self, object_: Cluster | ClusterObject | ServiceComponent, action: Action\n ) -> (TaskLog, JobLog):\n with RunTaskMock() as run_task:\n (self.client.v2[object_] / \"actions\" / action / \"run\").post(\n data={\"configuration\": None, \"isVerbose\": True, \"hostComponentMap\": []}\n )\n\n run_task.run()\n run_task.target_task.refresh_from_db()\n task = run_task.target_task\n job = task.joblog_set.last()\n task.status = JobStatus.RUNNING\n task.save(update_fields=[\"status\"])\n job.status = JobStatus.RUNNING\n job.pid = 5_000_000\n job.save(update_fields=[\"status\", \"pid\"])\n\n return task, job", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def test_get_case_by_name_and_customer_case_found(store_with_multiple_cases_and_samples: Store):\n \"\"\"Test that a case can be found by customer and case name.\"\"\"\n # GIVEN a database with multiple cases for a customer\n case: Case = store_with_multiple_cases_and_samples._get_query(table=Case).first()\n customer: Customer = store_with_multiple_cases_and_samples._get_query(table=Customer).first()\n\n assert case.customer == customer\n\n # WHEN fetching a case by customer and case name\n filtered_case: Case = store_with_multiple_cases_and_samples.get_case_by_name_and_customer(\n customer=customer,\n case_name=case.name,\n )\n\n # THEN the correct case should be returned\n assert filtered_case is not None\n assert filtered_case.customer_id == customer.id\n assert filtered_case.name == case.name", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def underlying_graph_is_mutable(ctx: mgp.ProcCtx, object: mgp.Any) -> mgp.Record(mutable=bool):\n return mgp.Record(mutable=object.underlying_graph_is_mutable())", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "async def test_extract_entity_ids_from_floor(hass: HomeAssistant) -> None:\n \"\"\"Test extract_entity_ids method with floors.\"\"\"\n call = ServiceCall(\"light\", \"turn_on\", {\"floor_id\": \"test-floor\"})\n\n assert {\n \"light.in_area\",\n \"light.assigned_to_area\",\n } == await service.async_extract_entity_ids(hass, call)\n\n call = ServiceCall(\"light\", \"turn_on\", {\"floor_id\": [\"test-floor\", \"floor-a\"]})\n\n assert {\n \"light.in_area\",\n \"light.assigned_to_area\",\n \"light.in_area_a\",\n } == await service.async_extract_entity_ids(hass, call)\n\n assert (\n await service.async_extract_entity_ids(\n hass, ServiceCall(\"light\", \"turn_on\", {\"floor_id\": ENTITY_MATCH_NONE})\n )\n == set()\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def run_test(self):\n '''Set up initial chain and run tests defined below'''\n\n self.test_persistence()\n self.test_immutable()\n\n self.generate(self.nodes[0], 110)\n self.test_change_remains_change(self.nodes[1])\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_sending_from_reused_address_without_avoid_reuse()\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_sending_from_reused_address_fails(\"legacy\")\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_sending_from_reused_address_fails(\"p2sh-segwit\")\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_sending_from_reused_address_fails(\"bech32\")\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_getbalances_used()\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_full_destination_group_is_preferred()\n reset_balance(self.nodes[1], self.nodes[0].getnewaddress())\n self.test_all_destination_groups_are_used()", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def test_serde(self):\n \"\"\"Test de/serialization.\"\"\"\n detail_options = LDProofVCDetailOptions.deserialize(VC_DETAIL_OPTIONS)\n assert type(detail_options) is LDProofVCDetailOptions\n\n detail_options_dict = detail_options.serialize()\n assert detail_options_dict == VC_DETAIL_OPTIONS", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_group_details_long_report(self, shell):\n \"\"\"\n Test do_group_details long report.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_details = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock(side_effect=[\n {\"id\": 1, \"name\": \"Group A\", \"description\": \"Test group A\", \"system_count\": 5},\n {\"id\": 2, \"name\": \"Group B\", \"description\": \"Test group B\", \"system_count\": 10},\n {\"id\": 3, \"name\": \"Group C\", \"description\": \"Test group C\", \"system_count\": 25}\n ])\n shell.client.systemgroup.listSystems = MagicMock(side_effect=[\n [{\"profile_name\": \"prf-a\"}, {\"profile_name\": \"prf-b\"}],\n [{\"profile_name\": \"prf-c\"}, {\"profile_name\": \"prf-d\"}],\n [{\"profile_name\": \"prf-e\"}, {\"profile_name\": \"prf-f\"}],\n ])\n\n mprint = MagicMock()\n logger = MagicMock()\n with patch(\"spacecmd.group.print\", mprint) as prt, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_details(shell, \"group-a group-b group-c\")\n\n assert not shell.help_group_details.called\n assert not logger.warning.called\n assert shell.client.systemgroup.getDetails.called\n assert shell.client.systemgroup.listSystems.called\n assert mprint.called\n\n assert_list_args_expect(mprint.call_args_list,\n ['ID: 1',\n 'Name: Group A',\n 'Description: Test group A',\n 'Number of Systems: 5',\n '',\n 'Members',\n '-------',\n 'prf-a\\nprf-b',\n '----------',\n 'ID: 2',\n 'Name: Group B',\n 'Description: Test group B',\n 'Number of Systems: 10',\n '',\n 'Members',\n '-------',\n 'prf-c\\nprf-d',\n '----------',\n 'ID: 3',\n 'Name: Group C',\n 'Description: Test group C',\n 'Number of Systems: 25',\n '',\n 'Members',\n '-------',\n 'prf-e\\nprf-f'])", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def open(\n self, context: InjectionContext, config: Mapping[str, Any] = None\n ) -> Profile:\n \"\"\"Open an instance of an existing profile.\"\"\"\n return await self.provision(context, config)", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def side_effect(request, **kwargs):\n return httpx.Response(status_code=200, json=kwargs)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_verify_case_exists(\n caplog, case_id_with_multiple_samples: str, store_with_multiple_cases_and_samples: Store\n):\n \"\"\"Test validating a case that exists in the database.\"\"\"\n\n caplog.set_level(logging.INFO)\n\n # GIVEN a database containing the case\n\n # WHEN validating if the case exists\n store_with_multiple_cases_and_samples.verify_case_exists(\n case_internal_id=case_id_with_multiple_samples\n )\n\n # THEN the case is found\n assert f\"Case {case_id_with_multiple_samples} exists in Status DB\" in caplog.text", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def test_iid_migration_to_v2_with_underscore(\n hass: HomeAssistant, iid_storage, hass_storage: dict[str, Any]\n) -> None:\n \"\"\"Test iid storage migration with underscore.\"\"\"\n v1_iids = json_loads(load_fixture(\"iids_v1_with_underscore\", DOMAIN))\n v2_iids = json_loads(load_fixture(\"iids_v2_with_underscore\", DOMAIN))\n hass_storage[\"homekit.v1_with_underscore.iids\"] = v1_iids\n hass_storage[\"homekit.v2_with_underscore.iids\"] = v2_iids\n\n iid_storage_v2 = AccessoryIIDStorage(hass, \"v1_with_underscore\")\n await iid_storage_v2.async_initialize()\n\n iid_storage_v1 = AccessoryIIDStorage(hass, \"v2_with_underscore\")\n await iid_storage_v1.async_initialize()\n\n assert iid_storage_v1.allocations == iid_storage_v2.allocations\n assert iid_storage_v1.allocated_iids == iid_storage_v2.allocated_iids\n\n assert len(iid_storage_v2.allocations) == 2\n\n for allocations in iid_storage_v2.allocations.values():\n assert allocations[\"3E___\"] == 1", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def _init_context(self):\n \"\"\"Initialize the session context.\"\"\"\n self._context.injector.bind_instance(\n BaseStorage, self.profile.inject(BaseStorageSearch)\n )\n self._context.injector.bind_instance(BaseWallet, WALLET_CLASS(self.profile))", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "async def test_camera(hass: HomeAssistant) -> None:\n \"\"\"Test that Axis camera platform is loaded properly.\"\"\"\n assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 1\n\n entity_id = f\"{CAMERA_DOMAIN}.{NAME}\"\n\n cam = hass.states.get(entity_id)\n assert cam.state == STATE_IDLE\n assert cam.name == NAME\n\n camera_entity = camera._get_camera_from_entity_id(hass, entity_id)\n assert camera_entity.image_source == \"http://1.2.3.4:80/axis-cgi/jpg/image.cgi\"\n assert camera_entity.mjpeg_source == \"http://1.2.3.4:80/axis-cgi/mjpg/video.cgi\"\n assert (\n await camera_entity.stream_source()\n == \"rtsp://root:pass@1.2.3.4/axis-media/media.amp?videocodec=h264\"\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_image_update(\n hass: HomeAssistant,\n hass_client: ClientSessionGenerator,\n snapshot: SnapshotAssertion,\n fc_class_mock,\n fh_class_mock,\n) -> None:\n \"\"\"Test image update.\"\"\"\n\n # setup component with image platform only\n with patch(\n \"homeassistant.components.fritz.PLATFORMS\",\n [Platform.IMAGE],\n ):\n entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n\n await hass.async_block_till_done()\n assert entry.state is ConfigEntryState.LOADED\n\n client = await hass_client()\n resp = await client.get(\"/api/image_proxy/image.mock_title_guestwifi\")\n resp_body = await resp.read()\n assert resp.status == HTTPStatus.OK\n\n fc_class_mock().override_services({**MOCK_FB_SERVICES, **GUEST_WIFI_CHANGED})\n async_fire_time_changed(hass, utcnow() + timedelta(seconds=60))\n await hass.async_block_till_done(wait_background_tasks=True)\n\n resp = await client.get(\"/api/image_proxy/image.mock_title_guestwifi\")\n resp_body_new = await resp.read()\n\n assert resp_body != resp_body_new\n assert resp_body_new == snapshot", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_orders_populated_store(store: Store, order: Order, order_another: Order):\n # GIVEN a store with two orders\n\n # WHEN fetching orders\n orders, total = store.get_orders(OrdersRequest())\n\n # THEN both should be returned\n assert len(orders) == 2\n assert total == 2", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def format_unencoded(self, tokensource, outfile):\n lastval = ''\n lasttype = None\n\n outfile.write('<tt>')\n\n for ttype, value in tokensource:\n while ttype not in self.styles:\n ttype = ttype.parent\n if ttype == lasttype:\n lastval += escape_special_chars(value)\n else:\n if lastval:\n stylebegin, styleend = self.styles[lasttype]\n outfile.write(stylebegin + lastval + styleend)\n lastval = escape_special_chars(value)\n lasttype = ttype\n\n if lastval:\n stylebegin, styleend = self.styles[lasttype]\n outfile.write(stylebegin + lastval + styleend)\n\n outfile.write('</tt>')", "smellKey": "0", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def remove_all_credentials(self):\n for cred in self.related.credentials.get().results:\n with suppress(exc.NoContent):\n self.related.credentials.post(dict(id=cred.id, disassociate=True))", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def connection():\n connection = connect()\n yield connection\n cursor = connection.cursor()\n execute_and_fetch_all(cursor, \"MATCH (n) DETACH DELETE n\")", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def __iadd__(self, other):\n self.__nb_highres_called += int(other)\n return self", "smellKey": "0", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "async def test_multiple_ssdp_alive(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n mock_disconnected_entity_id: str,\n) -> None:\n \"\"\"Test multiple SSDP alive notifications is ok, only connects to device once.\"\"\"\n domain_data_mock.upnp_factory.async_create_device.reset_mock()\n\n # Contacting the device takes long enough that 2 simultaneous attempts could be made\n async def create_device_delayed(_location):\n \"\"\"Delay before continuing with async_create_device.\n\n This gives a chance for parallel calls to `_device_connect` to occur.\n \"\"\"\n await asyncio.sleep(0.1)\n return DEFAULT\n\n domain_data_mock.upnp_factory.async_create_device.side_effect = (\n create_device_delayed\n )\n\n # Send two SSDP notifications with the new device URL\n ssdp_callback = ssdp_scanner_mock.async_register_callback.call_args.args[0].target\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=NEW_DEVICE_LOCATION,\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=NEW_DEVICE_LOCATION,\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n # Check device is contacted exactly once\n domain_data_mock.upnp_factory.async_create_device.assert_awaited_once_with(\n NEW_DEVICE_LOCATION\n )\n\n # Device should be available\n mock_state = hass.states.get(mock_disconnected_entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def downgrade():\n op.alter_column(\n \"pending_oidc_publishers\",\n \"added_by_id\",\n existing_type=postgresql.UUID(),\n nullable=True,\n )", "smellKey": "0", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "async def test_node_ports_accessors(\n mock_db_manager: Callable,\n default_configuration: dict[str, Any],\n user_id: int,\n project_id: str,\n node_uuid: str,\n faker: Faker,\n):\n db_manager = mock_db_manager(default_configuration)\n\n original_inputs = create_valid_port_mapping(InputsList, suffix=\"original\")\n original_outputs = create_valid_port_mapping(OutputsList, suffix=\"original\")\n\n async def mock_save_db_cb(*args, **kwargs):\n pass\n\n async def mock_node_port_creator_cb(*args, **kwargs):\n return Nodeports(\n inputs=original_inputs,\n outputs=original_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=False,\n )\n\n node_ports = Nodeports(\n inputs=original_inputs,\n outputs=original_outputs,\n db_manager=db_manager,\n user_id=user_id,\n project_id=project_id,\n node_uuid=node_uuid,\n save_to_db_cb=mock_save_db_cb,\n node_port_creator_cb=mock_node_port_creator_cb,\n auto_update=False,\n )\n\n for port in original_inputs.values():\n assert await node_ports.get(port.key) == port.value\n await node_ports.set(port.key, port.value)\n\n with pytest.raises(exceptions.UnboundPortError):\n await node_ports.get(\"some_invalid_key\") # type: ignore\n\n for port in original_outputs.values():\n assert await node_ports.get(port.key) == port.value\n await node_ports.set(port.key, port.value)\n\n # test batch add\n async with ProgressBarData(num_steps=1, description=faker.pystr()) as progress_bar:\n await node_ports.set_multiple(\n {\n port.key: (port.value, None)\n for port in list(original_inputs.values())\n + list(original_outputs.values())\n },\n progress_bar=progress_bar,\n outputs_callbacks=AsyncMock(),\n )\n assert progress_bar._current_steps == pytest.approx(1) # noqa: SLF001", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "async def test_press_button(hass: HomeAssistant) -> None:\n \"\"\"Test a switch service that has a button characteristic is correctly handled.\"\"\"\n helper = await setup_test_component(hass, create_switch_with_setup_button)\n\n # Helper will be for the primary entity, which is the outlet. Make a helper for the button.\n button = Helper(\n hass,\n \"button.testdevice_setup\",\n helper.pairing,\n helper.accessory,\n helper.config_entry,\n )\n\n await hass.services.async_call(\n \"button\",\n \"press\",\n {\"entity_id\": \"button.testdevice_setup\"},\n blocking=True,\n )\n button.async_assert_service_values(\n ServicesTypes.OUTLET,\n {\n CharacteristicsTypes.VENDOR_HAA_SETUP: \"#HAA@trcmd\",\n },\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_rgb_color_temp_light(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a generic light that supports color temp and RGB.\"\"\"\n color_modes = [\n LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS,\n LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n | LightColorCapability.COLOR_TEMPERATURE,\n LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n | LightColorCapability.RGB,\n ]\n\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153,\n max_mireds=400,\n supported_color_modes=color_modes,\n )\n ]\n states = [LightState(key=1, state=True, brightness=100)]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_BRIGHTNESS: 127},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n brightness=pytest.approx(0.4980392156862745),\n )\n ]\n )\n mock_client.light_command.reset_mock()\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_COLOR_TEMP_KELVIN: 2500},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS\n | LightColorCapability.COLOR_TEMPERATURE,\n color_temperature=400,\n )\n ]\n )\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def validate_field_defaults(value):\n \"\"\"Validate that the provided value is a valid dict.\"\"\"\n if value is None:\n return\n\n if type(value) is not dict:\n # OK if we can parse it as JSON\n try:\n value = json.loads(value)\n except json.JSONDecodeError:\n raise ValidationError(_('Value must be a valid dictionary object'))", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "async def test_disappearing_device(\n hass: HomeAssistant,\n mock_disconnected_entity_id: str,\n) -> None:\n \"\"\"Test attribute update or service call as device disappears.\n\n Normally HA will check if the entity is available before updating attributes\n or calling a service, but it's possible for the device to go offline in\n between the check and the method call. Here we test by accessing the entity\n directly to skip the availability check.\n \"\"\"\n # Retrieve entity directly.\n entity: DlnaDmrEntity = hass.data[MP_DOMAIN].get_entity(mock_disconnected_entity_id)\n\n # Test attribute access\n for attr in ATTR_TO_PROPERTY:\n value = getattr(entity, attr)\n assert value is None\n\n # media_image_url is normally hidden by entity_picture, but we want a direct check\n assert entity.media_image_url is None\n\n # Check attributes that are normally pre-checked\n assert entity.sound_mode_list is None\n\n # Test service calls\n await entity.async_set_volume_level(0.1)\n await entity.async_mute_volume(True)\n await entity.async_media_pause()\n await entity.async_media_play()\n await entity.async_media_stop()\n await entity.async_media_seek(22.0)\n await entity.async_play_media(\"\", \"\")\n await entity.async_media_previous_track()\n await entity.async_media_next_track()\n await entity.async_set_shuffle(True)\n await entity.async_set_repeat(RepeatMode.ALL)\n await entity.async_select_sound_mode(\"Default\")", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_fromdetails_newkey_fixed_usage_limit(self, shell):\n \"\"\"\n Test import_activationkey_fromdetails usage limit given.\n \"\"\"\n shell.client.activationkey.create = MagicMock(return_value={})\n shell.do_activationkey_list = MagicMock(return_value=[\"some_existing_key\"])\n shell.client.activationkey.addChildChannels = MagicMock()\n shell.client.activationkey.enableConfigDeployment = MagicMock()\n shell.client.activationkey.disableConfigDeployment = MagicMock()\n shell.client.activationkey.addConfigChannels = MagicMock()\n shell.client.activationkey.addServerGroups = MagicMock()\n shell.client.activationkey.addPackages = MagicMock()\n\n logger = MagicMock()\n with patch(\"spacecmd.activationkey.logging\", logger):\n ret = spacecmd.activationkey.import_activationkey_fromdetails(\n shell,\n {\n \"key\": \"somekey\",\n \"usage_limit\": 42,\n \"base_channel_label\": \"none\",\n \"description\": \"Key description\",\n \"entitlements\": [\"one\", \"two\", \"three\"],\n \"universal_default\": True,\n }\n )\n assert len(shell.client.activationkey.create.call_args_list[0][0]) == 7\n session, keyname, descr, basech, ulim, entl, udef = shell.client.activationkey.create.call_args_list[0][0]\n assert shell.session == session\n assert keyname == \"somekey\"\n assert descr == \"Key description\"\n assert basech == \"\"\n assert ulim == 42\n assert entl == [\"one\", \"two\", \"three\"]\n assert udef\n\n # This is expected: see mock return on API call \"create\".\n assert logger.error.call_args_list[0][0][0] == 'Failed to import key somekey'", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_locations(client: TestClient, user_id: UserID):\n resp = await client.get(f\"/v0/locations?user_id={user_id}\")\n\n payload = await resp.json()\n assert resp.status == 200, str(payload)\n\n data, error = tuple(payload.get(k) for k in (\"data\", \"error\"))\n\n _locs = 2 if has_datcore_tokens() else 1\n assert len(data) == _locs\n assert not error", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_do_activationkey_addentitlements_args(self, shell):\n \"\"\"\n Test \"addentitlements\" method calls \"addEntitlements\" API call.\n \"\"\"\n shell.help_activationkey_addentitlements = MagicMock()\n shell.client.activationkey.addEntitlements = MagicMock()\n\n spacecmd.activationkey.do_activationkey_addentitlements(shell, \"key entitlement\")\n assert not shell.help_activationkey_addentitlements.called\n assert shell.client.activationkey.addEntitlements.called\n session, fun, args = shell.client.activationkey.addEntitlements.call_args_list[0][0]\n assert session == shell.session\n assert fun == \"key\"\n assert isinstance(args, list)\n assert len(args) == 1\n assert args == ['entitlement']", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def wrapper(request):\n # 1. Create roles\n\n test_name = request.function.__name__\n instances = get_instances(test_name)\n interactive_mg_runner.start_all(instances)\n\n with GraphDatabase.driver(MG_URI, auth=(\"\", \"\")) as client:\n client.verify_connectivity()\n with client.session() as session:\n session.run(\"CREATE ROLE architect;\")\n session.run(\"GRANT ALL PRIVILEGES TO architect;\")\n\n interactive_mg_runner.stop(instances, INSTANCE_NAME)\n\n # 2. Restart to use SSO\n instances[INSTANCE_NAME][\"args\"].append(f\"--auth-module-mappings=saml-entra-id:{AUTH_MODULE_PATH}\")\n interactive_mg_runner.start_all(instances)\n\n # 3. Run test\n yield None\n\n # 4. Stop intance\n interactive_mg_runner.stop(instances, INSTANCE_NAME, keep_directories=False)", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def __iter__(self):\n \"Iterate over each ring in the polygon.\"\n for i in range(len(self)):\n yield self[i]", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def remove_key(self, key: UserSessionDict) -> None:\n await self.client.delete(\n f\"{self._hash_key(key)}:{_RESOURCE_SUFFIX}\",\n f\"{self._hash_key(key)}:{_ALIVE_SUFFIX}\",\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n pass\n # ### end Alembic commands ###", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "async def test_missing_entry_unique_id(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n mock_config_entry: MockConfigEntry,\n mock_ipp: AsyncMock,\n) -> None:\n \"\"\"Test the unique_id of IPP sensor when printer is missing identifiers.\"\"\"\n mock_config_entry.add_to_hass(hass)\n hass.config_entries.async_update_entry(mock_config_entry, unique_id=None)\n\n await hass.config_entries.async_setup(mock_config_entry.entry_id)\n await hass.async_block_till_done()\n\n entity = entity_registry.async_get(\"sensor.test_ha_1000_series\")\n assert entity\n assert entity.unique_id == f\"{mock_config_entry.entry_id}_printer\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_body_image_normalizer(normalizer_runner):\n meta = NormalizerMeta.model_validate_json(get_dummy_data(\"bodyimage-normalize.json\"))\n output = normalizer_runner.run(meta, get_dummy_data(\"cat_image\")).observations[0].results\n\n assert len(output) == 1\n assert {\n \"object_type\": \"ImageMetadata\",\n \"primary_key\": \"ImageMetadata|internet|134.209.85.72|tcp|443|https|internet\"\n \"|mispo.es|https|internet|mispo.es|443|/\",\n \"resource\": \"HTTPResource|internet|134.209.85.72|tcp|443|https|internet\"\n \"|mispo.es|https|internet|mispo.es|443|/\",\n \"scan_profile\": None,\n \"user_id\": None,\n \"image_info\": {\n \"format\": \"JPEG\",\n \"frames\": 1,\n \"height\": 600,\n \"is_animated\": False,\n \"mode\": \"RGB\",\n \"size\": (600, 600),\n \"width\": 600,\n },\n } == output[0].dict()", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def teardown(self) -> None:\n \"\"\"Reset this device to default state.\"\"\"\n self.event_source.teardown()", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def get_from_email(self):\n return settings.DEFAULT_FROM_EMAIL", "smellKey": "0", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def test_get_application_limitations_by_tag(\n store_with_application_limitations: Store,\n tag: str = StoreConstants.TAG_APPLICATION_WITHOUT_ATTRIBUTES.value,\n):\n \"\"\"Test get application limitations by application tag.\"\"\"\n\n # GIVEN a store with some application limitations\n\n # WHEN filtering by a given application tag\n application_limitations: list[ApplicationLimitations] = (\n store_with_application_limitations.get_application_limitations_by_tag(tag=tag)\n )\n\n # THEN assert that the application limitations were found\n assert (\n application_limitations\n and len(application_limitations) == 2\n and [\n application_limitation.application.tag == tag\n for application_limitation in application_limitations\n ]\n )", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def add_label(self, label):\n with suppress(exc.NoContent):\n self.related.labels.post(dict(id=label.id))", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def test_play_media_local_source(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test play_media with a media_id from a local media_source.\"\"\"\n # Based on roku's test_services_play_media_local_source and cast's\n # test_entity_browse_media\n await async_setup_component(hass, MS_DOMAIN, {MS_DOMAIN: {}})\n await hass.async_block_till_done()\n\n await hass.services.async_call(\n MP_DOMAIN,\n mp_const.SERVICE_PLAY_MEDIA,\n {\n ATTR_ENTITY_ID: mock_entity_id,\n mp_const.ATTR_MEDIA_CONTENT_TYPE: \"video/mp4\",\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"media-source://media_source/local/Epic Sax Guy 10 Hours.mp4\"\n ),\n },\n blocking=True,\n )\n\n assert dmr_device_mock.construct_play_media_metadata.await_count == 1\n assert (\n \"/media/local/Epic%20Sax%20Guy%2010%20Hours.mp4?authSig=\"\n in dmr_device_mock.construct_play_media_metadata.call_args.kwargs[\"media_url\"]\n )\n assert dmr_device_mock.async_set_transport_uri.await_count == 1\n assert dmr_device_mock.async_play.await_count == 1\n call_args = dmr_device_mock.async_set_transport_uri.call_args.args\n assert \"/media/local/Epic%20Sax%20Guy%2010%20Hours.mp4?authSig=\" in call_args[0]", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def tearDown(self) -> None:\n dirs_to_clear = (\n *Path(settings.BUNDLE_DIR).iterdir(),\n *Path(settings.DOWNLOAD_DIR).iterdir(),\n *Path(settings.FILE_DIR).iterdir(),\n *Path(settings.LOG_DIR).iterdir(),\n *Path(settings.RUN_DIR).iterdir(),\n *Path(settings.VAR_DIR).iterdir(),\n )\n\n for item in dirs_to_clear:\n if item.is_dir():\n rmtree(item)\n else:\n if item.name != \".gitkeep\":\n item.unlink()", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def __init__(self, args):\n argp = ArgumentParser(\"NeoRunnerArgumentParser\")\n argp.add_argument(\"--runner-config\",\n default=get_absolute_path(\"config/neo4j.conf\"),\n help=\"Path to neo config file\")\n argp.add_argument(\"--num-client-workers\", type=int, default=24,\n help=\"Number of clients\")\n argp.add_argument(\"--workload\", type=str, default=\"\",\n help=\"Type of client workload. Sets \\\n scenario flag for 'TestClient'\")\n self.args, remaining_args = argp.parse_known_args(args)\n assert not APOLLO or self.args.num_client_workers, \\\n \"--client-num-clients is obligatory flag on apollo\"\n database = Neo(remaining_args, self.args.runner_config)\n super(NeoRunner, self).__init__(\n remaining_args, database, self.args.num_client_workers,\n self.args.workload)", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "async def get_attrs(hass: HomeAssistant, entity_id: str) -> Mapping[str, Any]:\n \"\"\"Get updated device attributes.\"\"\"\n await async_update_entity(hass, entity_id)\n entity_state = hass.states.get(entity_id)\n assert entity_state is not None\n attrs = entity_state.attributes\n assert attrs is not None\n return attrs", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def _on_connected_changed(self, connected: bool, reason: str) -> None:\n self._attr_available = connected\n self.async_write_ha_state()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __modify_schema__(cls, field_schema: Dict[str, Any], field: Union[fields.ModelField, None]):\n if field:\n field_schema[\"description\"] = MOSTLY_DESCRIPTION\n field_schema[\"type\"] = \"number\"\n field_schema[\"minimum\"] = 0.0\n field_schema[\"maximum\"] = 1.0\n field_schema[\"multipleOf\"] = 0.01", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_analyses_to_upload_when_not_completed_at(helpers, sample_store):\n \"\"\"Test analyses to upload with no completed_at date.\"\"\"\n # GIVEN a store with an analysis without a completed_at date\n helpers.add_analysis(store=sample_store)\n\n # WHEN fetching all analyses that are ready for upload\n records: list[Analysis] = [\n analysis_obj for analysis_obj in sample_store.get_analyses_to_upload()\n ]\n\n # THEN no analysis object should be returned since they did not have a completed_at entry\n assert len(records) == 0", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "async def async_turn_on(self, **kwargs: Any) -> None:\n \"\"\"Turn the device on.\"\"\"\n await self.coordinator.roku.remote(\"poweron\")\n await self.coordinator.async_request_refresh()", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_empty_list(self):\n output = self.engine.render_to_string(\"empty_list\", {\"list\": []})\n self.assertEqual(output, \"\")", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_identifier_bundle_success(in_memory_runtime_context):\n context = in_memory_runtime_context\n ds = context.data_sources.add_pandas(\"pandas_datasource\")\n asset = ds.add_csv_asset(\"my_asset\", \"data.csv\")\n batch_definition = asset.add_batch_definition(\"my_batch_definition\")\n\n result = batch_definition.identifier_bundle()\n assert result.datasource.name == \"pandas_datasource\" and result.datasource.id is not None\n assert result.asset.name == \"my_asset\" and result.asset.id is not None\n assert (\n result.batch_definition.name == \"my_batch_definition\"\n and result.batch_definition.id is not None\n )", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(self, args):\n argp = ArgumentParser(\"MemgraphRunnerArgumentParser\")\n argp.add_argument(\"--num-database-workers\", type=int, default=8,\n help=\"Number of workers\")\n argp.add_argument(\"--num-client-workers\", type=int, default=24,\n help=\"Number of clients\")\n argp.add_argument(\"--workload\", type=str, default=\"\",\n help=\"Type of client workload. Sets \\\n scenario flag for 'TestClient'\")\n self.args, remaining_args = argp.parse_known_args(args)\n assert not APOLLO or self.args.num_database_workers, \\\n \"--num-database-workers is obligatory flag on apollo\"\n assert not APOLLO or self.args.num_client_workers, \\\n \"--num-client-workers is obligatory flag on apollo\"\n database = Memgraph(remaining_args, self.args.num_database_workers)\n super(MemgraphRunner, self).__init__(\n remaining_args, database, self.args.num_client_workers,\n self.args.workload)", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def test_group_details_no_valid_group(self, shell):\n \"\"\"\n Test do_group_details with no arguments.\n\n :param shell:\n :return:\n \"\"\"\n shell.help_group_details = MagicMock()\n shell.client.systemgroup.getDetails = MagicMock(\n side_effect=xmlrpclib.Fault(faultCode=42, faultString=\"kaboom!\"))\n shell.client.systemgroup.listSystems = MagicMock()\n\n mprint = MagicMock()\n logger = MagicMock()\n with patch(\"spacecmd.group.print\", mprint) as prt, \\\n patch(\"spacecmd.group.logging\", logger) as lgr:\n spacecmd.group.do_group_details(shell, \"cucumber-group\")\n\n assert not shell.client.systemgroup.listSystems.called\n assert not mprint.called\n assert not shell.help_group_details.called\n assert logger.warning.called\n assert shell.client.systemgroup.getDetails.called\n\n assert_expect(logger.warning.call_args_list,\n 'The group \"cucumber-group\" is invalid')", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_play_media_didl_metadata(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test play_media passes available DIDL-Lite metadata to the DMR.\"\"\"\n\n @dataclass\n class DidlPlayMedia(PlayMedia):\n \"\"\"Playable media with DIDL metadata.\"\"\"\n\n didl_metadata: didl_lite.DidlObject\n\n didl_metadata = didl_lite.VideoItem(\n id=\"120$22$33\",\n restricted=\"false\",\n title=\"Epic Sax Guy 10 Hours\",\n res=[\n didl_lite.Resource(uri=\"unused-URI\", protocol_info=\"http-get:*:video/mp4:\")\n ],\n )\n\n play_media = DidlPlayMedia(\n url=\"/media/local/Epic Sax Guy 10 Hours.mp4\",\n mime_type=\"video/mp4\",\n didl_metadata=didl_metadata,\n )\n\n await async_setup_component(hass, MS_DOMAIN, {MS_DOMAIN: {}})\n await hass.async_block_till_done()\n\n with patch(\n \"homeassistant.components.media_source.async_resolve_media\",\n return_value=play_media,\n ):\n await hass.services.async_call(\n MP_DOMAIN,\n mp_const.SERVICE_PLAY_MEDIA,\n {\n ATTR_ENTITY_ID: mock_entity_id,\n mp_const.ATTR_MEDIA_CONTENT_TYPE: \"video/mp4\",\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"media-source://media_source/local/Epic Sax Guy 10 Hours.mp4\"\n ),\n },\n blocking=True,\n )\n\n assert dmr_device_mock.construct_play_media_metadata.await_count == 0\n assert dmr_device_mock.async_set_transport_uri.await_count == 1\n assert dmr_device_mock.async_play.await_count == 1\n call_args = dmr_device_mock.async_set_transport_uri.call_args.args\n assert \"/media/local/Epic%20Sax%20Guy%2010%20Hours.mp4?authSig=\" in call_args[0]\n assert call_args[1] == \"Epic Sax Guy 10 Hours\"\n assert call_args[2] == didl_lite.to_xml_string(didl_metadata).decode()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_cases_not_analysed_by_sample_internal_id_multiple_cases(\n store_with_multiple_cases_and_samples: Store,\n sample_id_in_multiple_cases: str,\n):\n \"\"\"Test that multiple cases are returned when more than one case matches the sample internal id.\"\"\"\n # GIVEN a store with multiple cases having the same sample internal id\n cases_query: Query = store_with_multiple_cases_and_samples._get_query(table=Case)\n\n # Set all cases to not analysed and HOLD action\n for case in cases_query.all():\n case.action = CaseActions.HOLD\n\n # WHEN getting cases not analysed by the shared sample internal id\n cases = store_with_multiple_cases_and_samples.get_not_analysed_cases_by_sample_internal_id(\n sample_id_in_multiple_cases\n )\n\n # THEN multiple cases should be returned\n assert len(cases) > 1\n\n # Check that all returned cases have the matching sample and are not analysed\n for case in cases:\n assert not case.analyses\n assert any(sample.internal_id == sample_id_in_multiple_cases for sample in case.samples)", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_do_activationkey_listgroups_args(self, shell):\n \"\"\"\n Test listgroups command prints groups by the activation key passed.\n \"\"\"\n shell.help_activationkey_listgroups = MagicMock()\n shell.client.activationkey.getDetails = MagicMock(return_value={\"server_group_ids\": [2, 3]})\n shell.client.systemgroup.getDetails = MagicMock(side_effect=[{\"name\": \"RD-2D\"}, {\"name\": \"C-3PO\"}])\n\n mprint = MagicMock()\n with patch(\"spacecmd.activationkey.print\", mprint):\n spacecmd.activationkey.do_activationkey_listgroups(shell, \"key\")\n assert len(mprint.call_args_list) == 2\n assert mprint.call_args_list[0][0][0] == \"RD-2D\"\n assert mprint.call_args_list[1][0][0] == \"C-3PO\"", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_do_activationkey_listentitlements_noargs(self, shell):\n \"\"\"\n Test listentitlements command triggers help on no args\n \"\"\"\n shell.help_activationkey_listentitlements = MagicMock()\n shell.client.activationkey.getDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_listentitlements(shell, \"\")\n assert shell.help_activationkey_listentitlements.called\n assert not shell.client.activationkey.getDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_get_customer_by_internal_id(base_store: Store, customer_id: str):\n \"\"\"Test function to return the customer by customer id.\"\"\"\n\n # GIVEN a store with customer records\n\n # WHEN getting the query for the customer\n customer: Customer = base_store.get_customer_by_internal_id(customer_internal_id=customer_id)\n\n # THEN return a customer with the supplied customer internal id\n assert customer.internal_id == customer_id", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def as_extended_dict(self) -> dict[str, Any]:\n \"\"\"Return an extended dictionary version of this ActionTrace.\"\"\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_addconfigchannels_setuniversaldefault_noargs(self, shell):\n \"\"\"\n Test do_activationkey_addconfigchannels_setuniversaldefault involes help message on issuficient arguments.\n \"\"\"\n shell.help_activationkey_setuniversaldefault = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n shell.client.activationkey.getDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_setuniversaldefault(shell, \"\")\n assert shell.help_activationkey_setuniversaldefault.called\n assert not shell.client.activationkey.setDetails.called\n assert not shell.client.activationkey.getDetails.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def post_dynamic_service(\n self, dynamic_service_start: DynamicServiceStart\n ) -> Response:\n post_data = {\n \"product_name\": dynamic_service_start.product_name,\n \"can_save\": dynamic_service_start.can_save,\n \"user_id\": dynamic_service_start.user_id,\n \"project_id\": dynamic_service_start.project_id,\n \"key\": dynamic_service_start.key,\n \"version\": dynamic_service_start.version,\n \"node_uuid\": dynamic_service_start.node_uuid,\n \"basepath\": f\"/x/{dynamic_service_start.node_uuid}\",\n \"service_resources\": ServiceResourcesDictHelpers.create_jsonable(\n dynamic_service_start.service_resources\n ),\n \"wallet_info\": dynamic_service_start.wallet_info,\n \"pricing_info\": dynamic_service_start.pricing_info,\n \"hardware_info\": dynamic_service_start.hardware_info,\n }\n\n headers = {\n X_DYNAMIC_SIDECAR_REQUEST_DNS: dynamic_service_start.request_dns,\n X_DYNAMIC_SIDECAR_REQUEST_SCHEME: dynamic_service_start.request_scheme,\n X_SIMCORE_USER_AGENT: dynamic_service_start.simcore_user_agent,\n }\n\n return await self.client.post(\n \"/dynamic_services\",\n content=json_dumps(post_data),\n headers=headers,\n follow_redirects=True,\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def factory_handler(coro: Callable) -> Callable[[ContextDict], RequestTuple]:\n assert inspect.iscoroutinefunction(coro) # nosec\n\n def _create(context: ContextDict):\n # NOTE: we could delay this as well ...\n kwargs_from_context = {\n param.name: factory_context_getter(param.name)(context)\n for param in inspect.signature(coro).parameters.values()\n }\n return RequestTuple(handler=coro, kwargs=kwargs_from_context)\n\n return _create", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def _get_role(value):\n from rbac.builtin import BuiltinRole\n roles = BuiltinRole.get_roles()\n for role in roles.values():\n if _(role.name) == value:\n return role\n\n if is_uuid(value):\n return Role.objects.filter(id=value).first()\n else:\n return Role.objects.filter(name=value).first()", "smellKey": "0", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "async def provision(\n self, context: InjectionContext, config: Mapping[str, Any] = None\n ) -> Profile:\n \"\"\"Provision a new instance of a profile.\"\"\"\n return InMemoryProfile(context=context, name=(config or {}).get(\"name\"))", "smellKey": "0", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def __init__(self, name: str, value: Any, scope: str = OPENC3_SCOPE):\n super().__init__(f\"{scope}__{StashModel.PRIMARY_KEY}\", name=name, scope=scope)\n self.value = value", "smellKey": "0", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "async def test_climate_basic_temperature_set(\n hass: HomeAssistant, knx: KNXTestKit\n) -> None:\n \"\"\"Test KNX climate basic.\"\"\"\n await knx.setup_integration(\n {\n ClimateSchema.PLATFORM: {\n CONF_NAME: \"test\",\n ClimateSchema.CONF_TEMPERATURE_ADDRESS: \"1/2/3\",\n ClimateSchema.CONF_TARGET_TEMPERATURE_ADDRESS: \"1/2/4\",\n ClimateSchema.CONF_TARGET_TEMPERATURE_STATE_ADDRESS: \"1/2/5\",\n }\n }\n )\n events = async_capture_events(hass, \"state_changed\")\n\n # read temperature\n await knx.assert_read(\"1/2/3\")\n # read target temperature\n await knx.assert_read(\"1/2/5\")\n # StateUpdater initialize state\n await knx.receive_response(\"1/2/3\", RAW_FLOAT_21_0)\n await knx.receive_response(\"1/2/5\", RAW_FLOAT_22_0)\n events.clear()\n\n # set new temperature\n await hass.services.async_call(\n \"climate\",\n \"set_temperature\",\n {\"entity_id\": \"climate.test\", \"temperature\": 20},\n blocking=True,\n )\n await knx.assert_write(\"1/2/4\", RAW_FLOAT_20_0)\n assert len(events) == 1", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def assert_creation_and_removal(volume_name: str) -> None:\n print(f\"Ensure creation and removal of len={len(volume_name)} {volume_name=}\")\n async with aiodocker.Docker() as client:\n named_volume = await client.volumes.create({\"Name\": volume_name})\n await named_volume.delete()", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_do_activationkey_addconfigchannels_setuniversaldefault_args(self, shell):\n \"\"\"\n Test do_activationkey_addconfigchannels_setuniversaldefault calls API to set the key settings.\n \"\"\"\n key_details = {\n \"base_channel_label\": \"death_star_channel\",\n \"description\": \"Darth Vader's base channel\",\n \"usage_limit\": 42,\n \"universal_default\": False,\n }\n shell.help_activationkey_setuniversaldefault = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n shell.client.activationkey.getDetails = MagicMock(return_value=key_details)\n\n spacecmd.activationkey.do_activationkey_setuniversaldefault(shell, \"red_key 42\")\n session, keyname, details = shell.client.activationkey.setDetails.call_args_list[0][0]\n assert shell.session == session\n assert keyname == \"red_key\"\n\n for dkey in [\"description\", \"usage_limit\", \"base_channel_label\"]:\n assert dkey in details\n assert key_details[dkey] == details[dkey]\n assert type(details[\"universal_default\"]) == bool\n assert details[\"universal_default\"]", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_coordinates_function_returns_none_on_recursion(hass: HomeAssistant) -> None:\n \"\"\"Test coordinates function.\"\"\"\n hass.states.async_set(\n \"test.first\",\n \"test.second\",\n )\n hass.states.async_set(\"test.second\", \"test.first\")\n assert location.find_coordinates(hass, \"test.first\") is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_reauth_auth_failure(\n hass: HomeAssistant,\n mock_config_entry: MockConfigEntry,\n mock_fibaro_client: Mock,\n) -> None:\n \"\"\"Successful reauth flow initialized by the user.\"\"\"\n result = await mock_config_entry.start_reauth_flow(hass)\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] == {}\n\n mock_fibaro_client.connect.side_effect = HTTPError(response=Mock(status_code=403))\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={CONF_PASSWORD: \"other_fake_password\"},\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] == {\"base\": \"invalid_auth\"}\n\n await _recovery_after_reauth_failure_works(hass, mock_fibaro_client, result)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_become_unavailable(\n hass: HomeAssistant,\n mock_entity_id: str,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test a device becoming unavailable.\"\"\"\n # Check async_update currently works\n await async_update_entity(hass, mock_entity_id)\n dmr_device_mock.async_update.assert_called_with(do_ping=False)\n\n # Now break the network connection and try to contact the device\n dmr_device_mock.async_set_volume_level.side_effect = UpnpConnectionError\n dmr_device_mock.async_update.reset_mock()\n\n # Interface service calls should flag that the device is unavailable, but\n # not disconnect it immediately\n await hass.services.async_call(\n MP_DOMAIN,\n ha_const.SERVICE_VOLUME_SET,\n {ATTR_ENTITY_ID: mock_entity_id, mp_const.ATTR_MEDIA_VOLUME_LEVEL: 0.80},\n blocking=True,\n )\n\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n # With a working connection, the state should be restored\n await async_update_entity(hass, mock_entity_id)\n dmr_device_mock.async_update.assert_any_call(do_ping=True)\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n # Break the service again, and the connection too. An update will cause the\n # device to be disconnected\n dmr_device_mock.async_update.reset_mock()\n dmr_device_mock.async_update.side_effect = UpnpConnectionError\n\n await hass.services.async_call(\n MP_DOMAIN,\n ha_const.SERVICE_VOLUME_SET,\n {ATTR_ENTITY_ID: mock_entity_id, mp_const.ATTR_MEDIA_VOLUME_LEVEL: 0.80},\n blocking=True,\n )\n await async_update_entity(hass, mock_entity_id)\n dmr_device_mock.async_update.assert_called_with(do_ping=True)\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n assert mock_state.state == ha_const.STATE_UNAVAILABLE", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_browse_media(\n self,\n item: MediaSourceItem,\n ) -> BrowseMediaSource:\n \"\"\"Return media.\"\"\"\n radios = self.radios\n\n return BrowseMediaSource(\n domain=DOMAIN,\n identifier=None,\n media_class=MediaClass.CHANNEL,\n media_content_type=MediaType.MUSIC,\n title=self.entry.title,\n can_play=False,\n can_expand=True,\n children_media_class=MediaClass.DIRECTORY,\n children=[\n *await self._async_build_popular(radios, item),\n *await self._async_build_by_tag(radios, item),\n *await self._async_build_by_language(radios, item),\n *await self._async_build_by_country(radios, item),\n ],\n )", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_group_delete_noarg(self, shell):\n \"\"\"\n Test do_group_delete without no arguments\n\n :param shell:\n :return:\n \"\"\"\n shell.client.systemgroup.delete = MagicMock()\n shell.user_confirm = MagicMock(return_value=False)\n shell.help_group_delete = MagicMock()\n\n spacecmd.group.do_group_delete(shell, \"\")\n\n assert not shell.client.systemgroup.delete.called\n assert not shell.user_confirm.called\n assert shell.help_group_delete.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def _filter_roles(self, queryset, value, scope):\n role = self._get_role(value)\n if not role:\n return queryset.none()\n \n rb_model = SystemRoleBinding if scope == Role.Scope.system.value else OrgRoleBinding\n user_ids = rb_model.objects.filter(role_id=role.id).values_list('user_id', flat=True)\n queryset = queryset.filter(id__in=user_ids).distinct()\n return queryset", "smellKey": "0", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def media_image_url(self) -> str | None:\n \"\"\"Image url of current playing media.\"\"\"\n if self._attr_media_content_id and self._attr_media_content_type in (\n MediaType.APP,\n MediaType.CHANNEL,\n ):\n return self.get_browse_image_url(\n self._attr_media_content_type,\n self._attr_media_content_id,\n media_image_id=None,\n )\n return None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_listpackages_args_noarch(self, shell):\n \"\"\"\n Test listpackages command prints packages by the activation key passed without architecture included.\n \"\"\"\n shell.help_activationkey_listpackages = MagicMock()\n shell.client.activationkey.getDetails = MagicMock(\n return_value={\"packages\": [\n {\"name\": \"libzypp\"},\n {\"name\": \"java-17-openjdk-devel\"},\n ]}\n )\n\n mprint = MagicMock()\n with patch(\"spacecmd.activationkey.print\", mprint):\n spacecmd.activationkey.do_activationkey_listpackages(shell, \"key\")\n assert mprint.called\n assert len(mprint.call_args_list) == 2\n # keep ordering\n assert mprint.call_args_list[0][0][0] == \"libzypp\"\n assert mprint.call_args_list[1][0][0] == \"java-17-openjdk-devel\"", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def validate_elements_tags(elements):\n \"\"\"Recursively validates elements for being in the allow list\"\"\"\n errors = None\n for element in elements:\n if element.tag not in allowed_html_tags:\n error = f'ERROR: Element <{element.tag}> is not allowed.\\n'\n errors = (errors or '') + error\n rec_errors = validate_elements_tags(list(element))\n if rec_errors is not None:\n errors = (errors or '') + rec_errors\n return errors", "smellKey": "0", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def test_parameters(self):\n self.assertEqual(\n self.settings_to_cmd_args_env({\"NAME\": \"test.db.sqlite3\"}, [\"-help\"]),\n ([\"sqlite3\", \"test.db.sqlite3\", \"-help\"], None),\n )", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_write_buffer_write_unsigned_short_large_number_big_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN)\n wb.write_unsigned_short(0x1213, 16)\n ba: memoryview = wb.get_bytes()\n assert ba.obj == bitarray(\"00010010 00010011 \", endian=\"big\")", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "async def test_missing_required_keys(hass: HomeAssistant) -> None:\n \"\"\"Test: missing required fields will fail.\"\"\"\n with assert_setup_component(0, \"template\"):\n assert await setup.async_setup_component(\n hass,\n \"template\",\n {\n \"template\": {\n \"select\": {\n \"select_option\": {\"service\": \"script.select_option\"},\n \"options\": \"{{ ['a', 'b'] }}\",\n }\n }\n },\n )\n\n with assert_setup_component(0, \"select\"):\n assert await setup.async_setup_component(\n hass,\n \"select\",\n {\n \"template\": {\n \"select\": {\n \"state\": \"{{ 'a' }}\",\n \"select_option\": {\"service\": \"script.select_option\"},\n }\n }\n },\n )\n\n with assert_setup_component(0, \"select\"):\n assert await setup.async_setup_component(\n hass,\n \"select\",\n {\n \"template\": {\n \"select\": {\n \"state\": \"{{ 'a' }}\",\n \"options\": \"{{ ['a', 'b'] }}\",\n }\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n assert hass.states.async_all(\"select\") == []", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def get(cls, name: str, scope: str = OPENC3_SCOPE):\n return super().get(f\"{scope}__{StashModel.PRIMARY_KEY}\", name=name)", "smellKey": "0", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def test_mixin(self):\n \"\"\"Test that MixinNotImplementedError is raised.\"\"\"\n # Test location locator\n with self.assertRaises(MixinNotImplementedError):\n\n class Wrong(LocateMixin, InvenTreePlugin):\n pass\n\n plugin = Wrong()\n plugin.locate_stock_location(1)\n\n # Test item locator\n with self.assertRaises(MixinNotImplementedError):\n plugin.locate_stock_item(1)", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def mock_setup_entry() -> Generator[AsyncMock]:\n \"\"\"Override async_setup_entry.\"\"\"\n with patch(\n \"homeassistant.components.sanix.async_setup_entry\",\n return_value=True,\n ) as mock_setup_entry:\n yield mock_setup_entry", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_get_invoice_by_id(store_with_an_invoice_with_and_without_attributes: Store):\n \"\"\"Test that invoices can be fetched by invoice id.\"\"\"\n # GIVEN a database with two invoices of which one has attributes\n\n # WHEN fetching the invoice by invoice id\n invoice: Invoice = store_with_an_invoice_with_and_without_attributes.get_invoice_by_entry_id(\n entry_id=1\n )\n\n # THEN one invoice should be returned\n assert invoice\n\n # THEN the invoice should have id 1\n assert invoice.id == 1", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def get_login_strategy(\n link_request: PartnerLinkRequest, user: Optional[User], partner: Partner\n) -> ClientMergeStrategy:\n if user is None:\n # We couldn't find any SimpleLogin user with the requested e-mail\n return NewUserStrategy(link_request, user, partner)\n # Check if user is already linked with another partner_user\n other_partner_user = PartnerUser.get_by(partner_id=partner.id, user_id=user.id)\n if other_partner_user is not None:\n return LinkedWithAnotherPartnerUserStrategy(link_request, user, partner)\n # There is a SimpleLogin user with the partner_user's e-mail\n return ExistingUnlinkedUserStrategy(link_request, user, partner)", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def _abspath(path):\n \"\"\"\n Fake os.path.abspath that expands to /tmp/test\n\n :param path:\n :return:\n \"\"\"\n return os.path.join(\"/tmp/test\", path.strip(\"/\"))", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def location_name(self):\n \"\"\"Return a location name for the current location of the device.\"\"\"\n return self._data.get(\"location_name\")", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_flatpages(parser, token):\n \"\"\"\n Retrieve all flatpage objects available for the current site and\n visible to the specific user (or visible to all users if no user is\n specified). Populate the template context with them in a variable\n whose name is defined by the ``as`` clause.\n\n An optional ``for`` clause controls the user whose permissions are used in\n determining which flatpages are visible.\n\n An optional argument, ``starts_with``, limits the returned flatpages to\n those beginning with a particular base URL. This argument can be a variable\n or a string, as it resolves from the template context.\n\n Syntax::\n\n {% get_flatpages ['url_starts_with'] [for user] as context_name %}\n\n Example usage::\n\n {% get_flatpages as flatpages %}\n {% get_flatpages for someuser as flatpages %}\n {% get_flatpages '/about/' as about_pages %}\n {% get_flatpages prefix as about_pages %}\n {% get_flatpages '/about/' for someuser as about_pages %}\n \"\"\"\n bits = token.split_contents()\n syntax_message = (\n \"%(tag_name)s expects a syntax of %(tag_name)s \"\n \"['url_starts_with'] [for user] as context_name\" % {\"tag_name\": bits[0]}\n )\n # Must have at 3-6 bits in the tag\n if 3 <= len(bits) <= 6:\n # If there's an even number of bits, there's no prefix\n if len(bits) % 2 == 0:\n prefix = bits[1]\n else:\n prefix = None\n\n # The very last bit must be the context name\n if bits[-2] != \"as\":\n raise template.TemplateSyntaxError(syntax_message)\n context_name = bits[-1]\n\n # If there are 5 or 6 bits, there is a user defined\n if len(bits) >= 5:\n if bits[-4] != \"for\":\n raise template.TemplateSyntaxError(syntax_message)\n user = bits[-3]\n else:\n user = None\n\n return FlatpageNode(context_name, starts_with=prefix, user=user)\n else:\n raise template.TemplateSyntaxError(syntax_message)", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def test_full_flow(hass: HomeAssistant) -> None:\n \"\"\"Check setup.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": SOURCE_USER}\n )\n\n assert result.get(\"type\") is FlowResultType.FORM\n assert result.get(\"errors\") == {}\n assert result.get(\"step_id\") == \"user\"\n\n mock_youless = _get_mock_youless_api(\n initialize={\"homes\": [{\"id\": 1, \"name\": \"myhome\"}]}\n )\n with patch(\n \"homeassistant.components.youless.config_flow.YoulessAPI\",\n return_value=mock_youless,\n ) as mocked_youless:\n result2 = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n {\"host\": \"localhost\"},\n )\n\n assert result2.get(\"type\") is FlowResultType.CREATE_ENTRY\n assert result2.get(\"title\") == \"localhost\"\n assert len(mocked_youless.mock_calls) == 1", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def subgraph_get_in_edges(ctx: mgp.ProcCtx, vertex: mgp.Vertex) -> mgp.Record(edge=mgp.Edge):\n return [mgp.Record(edge=edge) for edge in vertex.in_edges]", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def add_one(self):\n self.__nb_highres_called += 1", "smellKey": "0", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "async def test_coordinates_function_zone_friendly_name(hass: HomeAssistant) -> None:\n \"\"\"Test coordinates function.\"\"\"\n hass.states.async_set(\n \"zone.home\",\n \"zoning\",\n {\"latitude\": 32.87336, \"longitude\": -117.22943, ATTR_FRIENDLY_NAME: \"my_home\"},\n )\n hass.states.async_set(\n \"test.object\",\n \"my_home\",\n )\n assert location.find_coordinates(hass, \"test.object\") == \"32.87336,-117.22943\"\n assert location.find_coordinates(hass, \"my_home\") == \"32.87336,-117.22943\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def handle(self, *args, **options):\n if options[\"username\"]:\n username = options[\"username\"]\n else:\n username = getpass.getuser()\n\n try:\n u = UserModel._default_manager.using(options[\"database\"]).get(\n **{UserModel.USERNAME_FIELD: username}\n )\n except UserModel.DoesNotExist:\n raise CommandError(\"user '%s' does not exist\" % username)\n\n self.stdout.write(\"Changing password for user '%s'\" % u)\n\n MAX_TRIES = 3\n count = 0\n p1, p2 = 1, 2 # To make them initially mismatch.\n password_validated = False\n while (p1 != p2 or not password_validated) and count < MAX_TRIES:\n p1 = self._get_pass()\n p2 = self._get_pass(\"Password (again): \")\n if p1 != p2:\n self.stdout.write(\"Passwords do not match. Please try again.\")\n count += 1\n # Don't validate passwords that don't match.\n continue\n try:\n validate_password(p2, u)\n except ValidationError as err:\n self.stderr.write(\"\\n\".join(err.messages))\n count += 1\n else:\n password_validated = True\n\n if count == MAX_TRIES:\n raise CommandError(\n \"Aborting password change for user '%s' after %s attempts\" % (u, count)\n )\n\n u.set_password(p1)\n u.save()\n\n return \"Password changed successfully for user '%s'\" % u", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def mocked_remove_service_volumes(mocker: pytest_mock.MockerFixture) -> AsyncMock:\n return mocker.patch(\n \"simcore_service_agent.services.volumes_manager.VolumesManager.remove_service_volumes\"\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def downgrade():\n op.alter_column(\"order\", \"workflow\", type_=old_analysis_enum)", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def settings_to_cmd_args_env(self, settings_dict, parameters=None):\n if parameters is None:\n parameters = []\n return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)", "smellKey": "0", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_project_optional_config_comment_matches_default(\n project_optional_config_comment,\n):\n \"\"\"\n What does this test and why?\n Make sure that the templates built on data_context.types.base.DataContextConfigDefaults match the desired default.\n \"\"\" # noqa: E501\n\n assert project_optional_config_comment == templates.PROJECT_OPTIONAL_CONFIG_COMMENT", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def _build_data_assistant_result(\n self, data_assistant_result: DataAssistantResult\n ) -> DataAssistantResult:\n return DataProfilerStructuredDataAssistantResult(\n _batch_id_to_batch_identifier_display_name_map=data_assistant_result._batch_id_to_batch_identifier_display_name_map,\n profiler_config=data_assistant_result.profiler_config,\n profiler_execution_time=data_assistant_result.profiler_execution_time,\n rule_domain_builder_execution_time=data_assistant_result.rule_domain_builder_execution_time,\n rule_execution_time=data_assistant_result.rule_execution_time,\n rule_exception_tracebacks=data_assistant_result.rule_exception_tracebacks,\n metrics_by_domain=data_assistant_result.metrics_by_domain,\n expectation_configurations=data_assistant_result.expectation_configurations,\n citation=data_assistant_result.citation,\n _usage_statistics_handler=data_assistant_result._usage_statistics_handler,\n )", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(\n self,\n coordinator: AirzoneUpdateCoordinator,\n description: SensorEntityDescription,\n entry: ConfigEntry,\n ) -> None:\n \"\"\"Initialize.\"\"\"\n super().__init__(coordinator, entry)\n\n self._attr_unique_id = f\"{self._attr_unique_id}_dhw_{description.key}\"\n self.entity_description = description\n\n self._attr_native_unit_of_measurement = TEMP_UNIT_LIB_TO_HASS.get(\n self.get_airzone_value(AZD_TEMP_UNIT)\n )\n\n self._async_update_attrs()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_unload_entry(\n hass: HomeAssistant, mock_accuweather_client: AsyncMock\n) -> None:\n \"\"\"Test successful unload of entry.\"\"\"\n entry = await init_integration(hass)\n\n assert len(hass.config_entries.async_entries(DOMAIN)) == 1\n assert entry.state is ConfigEntryState.LOADED\n\n assert await hass.config_entries.async_unload(entry.entry_id)\n await hass.async_block_till_done()\n\n assert entry.state is ConfigEntryState.NOT_LOADED\n assert not hass.data.get(DOMAIN)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def payload(self, workflow_job_template, unified_job_template, **kwargs):\n if not unified_job_template:\n # May pass \"None\" to explicitly create an approval node\n payload = PseudoNamespace(workflow_job_template=workflow_job_template.id)\n else:\n payload = PseudoNamespace(workflow_job_template=workflow_job_template.id, unified_job_template=unified_job_template.id)\n\n optional_fields = (\n 'diff_mode',\n 'extra_data',\n 'limit',\n 'scm_branch',\n 'job_tags',\n 'job_type',\n 'skip_tags',\n 'verbosity',\n 'extra_data',\n 'identifier',\n 'all_parents_must_converge',\n # prompt fields for JTs\n 'job_slice_count',\n 'forks',\n 'timeout',\n 'execution_environment',\n )\n\n update_payload(payload, optional_fields, kwargs)\n\n if 'inventory' in kwargs:\n payload['inventory'] = kwargs['inventory'].id\n\n return payload", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) -> None:\n \"\"\"Test starting a reauthentication flow but no connection found.\"\"\"\n\n mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_BRIDGE_DATA)\n mock_config.add_to_hass(hass)\n\n with (\n patch(\"aiocomelit.api.ComeliteSerialBridgeApi.login\", side_effect=side_effect),\n patch(\n \"aiocomelit.api.ComeliteSerialBridgeApi.logout\",\n ),\n patch(\"homeassistant.components.comelit.async_setup_entry\"),\n ):\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": SOURCE_REAUTH, \"entry_id\": mock_config.entry_id},\n data=mock_config.data,\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={\n CONF_PIN: FAKE_PIN,\n },\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n assert result[\"errors\"] is not None\n assert result[\"errors\"][\"base\"] == error", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_feature_flags(\n hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str\n) -> None:\n \"\"\"Test feature flags of a connected DlnaDmrEntity.\"\"\"\n # Check supported feature flags, one at a time.\n FEATURE_FLAGS: list[tuple[str, int]] = [\n (\"has_volume_level\", MediaPlayerEntityFeature.VOLUME_SET),\n (\"has_volume_mute\", MediaPlayerEntityFeature.VOLUME_MUTE),\n (\"can_play\", MediaPlayerEntityFeature.PLAY),\n (\"can_pause\", MediaPlayerEntityFeature.PAUSE),\n (\"can_stop\", MediaPlayerEntityFeature.STOP),\n (\"can_previous\", MediaPlayerEntityFeature.PREVIOUS_TRACK),\n (\"can_next\", MediaPlayerEntityFeature.NEXT_TRACK),\n (\n \"has_play_media\",\n MediaPlayerEntityFeature.PLAY_MEDIA | MediaPlayerEntityFeature.BROWSE_MEDIA,\n ),\n (\"can_seek_rel_time\", MediaPlayerEntityFeature.SEEK),\n (\"has_presets\", MediaPlayerEntityFeature.SELECT_SOUND_MODE),\n ]\n\n # Clear all feature properties\n dmr_device_mock.valid_play_modes = set()\n for feat_prop, _ in FEATURE_FLAGS:\n setattr(dmr_device_mock, feat_prop, False)\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[ha_const.ATTR_SUPPORTED_FEATURES] == 0\n\n # Test the properties cumulatively\n expected_features = 0\n for feat_prop, flag in FEATURE_FLAGS:\n setattr(dmr_device_mock, feat_prop, True)\n expected_features |= flag\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[ha_const.ATTR_SUPPORTED_FEATURES] == expected_features\n\n # shuffle and repeat features depend on the available play modes\n PLAY_MODE_FEATURE_FLAGS: list[tuple[PlayMode, int]] = [\n (PlayMode.NORMAL, 0),\n (PlayMode.SHUFFLE, MediaPlayerEntityFeature.SHUFFLE_SET),\n (PlayMode.REPEAT_ONE, MediaPlayerEntityFeature.REPEAT_SET),\n (PlayMode.REPEAT_ALL, MediaPlayerEntityFeature.REPEAT_SET),\n (PlayMode.RANDOM, MediaPlayerEntityFeature.SHUFFLE_SET),\n (PlayMode.DIRECT_1, 0),\n (PlayMode.INTRO, 0),\n (PlayMode.VENDOR_DEFINED, 0),\n ]\n for play_modes, flag in PLAY_MODE_FEATURE_FLAGS:\n dmr_device_mock.valid_play_modes = {play_modes}\n attrs = await get_attrs(hass, mock_entity_id)\n assert attrs[ha_const.ATTR_SUPPORTED_FEATURES] == expected_features | flag", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def routing_key(self) -> str | None:\n return f\"{self.wallet_id}\"", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def validate_data_file(data_file):\n \"\"\"Validate the provided data file.\"\"\"\n import importer.operations\n\n filesize = data_file.size\n\n if filesize > IMPORTER_MAX_FILE_SIZE:\n raise ValidationError(_('Data file exceeds maximum size limit'))\n\n dataset = importer.operations.load_data_file(data_file)\n\n if not dataset.headers or len(dataset.headers) == 0:\n raise ValidationError(_('Data file contains no headers'))\n\n if len(dataset.headers) > IMPORTER_MAX_COLS:\n raise ValidationError(_('Data file contains too many columns'))\n\n if len(dataset) > IMPORTER_MAX_ROWS:\n raise ValidationError(_('Data file contains too many rows'))", "smellKey": "0", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def get_parsed_rows(self) -> List[dict]:\n return self._parse(self._file)", "smellKey": "0", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def periodic_send_notification_emails() -> None:\n send_notification_emails()", "smellKey": "0", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def test_is_fresh_fails_on_batch_definition_retrieval(in_memory_runtime_context):\n context = in_memory_runtime_context\n datasource = context.data_sources.add_pandas(name=\"my_pandas_ds\")\n asset = datasource.add_csv_asset(name=\"my_csv_asset\", filepath_or_buffer=\"data.csv\")\n batch_definition = asset.add_batch_definition(name=\"my_batch_def\")\n\n asset.delete_batch_definition(\"my_batch_def\")\n\n diagnostics = batch_definition.is_fresh()\n assert diagnostics.success is False\n assert len(diagnostics.errors) == 1\n assert isinstance(diagnostics.errors[0], BatchDefinitionNotFoundError)", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "async def set_key_alive(self, key: UserSessionDict, timeout: int) -> None:\n # setting the timeout to always expire, timeout > 0\n timeout = int(max(1, timeout))\n hash_key = f\"{self._hash_key(key)}:{_ALIVE_SUFFIX}\"\n await self.client.set(hash_key, 1, ex=timeout)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_persistence(self):\n '''Test that wallet files persist the avoid_reuse flag.'''\n self.log.info(\"Test wallet files persist avoid_reuse flag\")\n\n # Configure node 1 to use avoid_reuse\n self.nodes[1].setwalletflag('avoid_reuse')\n\n # Flags should be node1.avoid_reuse=false, node2.avoid_reuse=true\n assert_equal(self.nodes[0].getwalletinfo()[\"avoid_reuse\"], False)\n assert_equal(self.nodes[1].getwalletinfo()[\"avoid_reuse\"], True)\n\n self.restart_node(1)\n self.connect_nodes(0, 1)\n\n # Flags should still be node1.avoid_reuse=false, node2.avoid_reuse=true\n assert_equal(self.nodes[0].getwalletinfo()[\"avoid_reuse\"], False)\n assert_equal(self.nodes[1].getwalletinfo()[\"avoid_reuse\"], True)\n\n # Attempting to set flag to its current state should throw\n assert_raises_rpc_error(-8, \"Wallet flag is already set to false\", self.nodes[0].setwalletflag, 'avoid_reuse', False)\n assert_raises_rpc_error(-8, \"Wallet flag is already set to true\", self.nodes[1].setwalletflag, 'avoid_reuse', True)\n\n assert_raises_rpc_error(-8, \"Unknown wallet flag: abc\", self.nodes[0].setwalletflag, 'abc', True)\n\n # Create a wallet with avoid reuse, and test that disabling it afterwards persists\n self.nodes[1].createwallet(wallet_name=\"avoid_reuse_persist\", avoid_reuse=True)\n w = self.nodes[1].get_wallet_rpc(\"avoid_reuse_persist\")\n assert_equal(w.getwalletinfo()[\"avoid_reuse\"], True)\n w.setwalletflag(\"avoid_reuse\", False)\n assert_equal(w.getwalletinfo()[\"avoid_reuse\"], False)\n w.unloadwallet()\n self.nodes[1].loadwallet(\"avoid_reuse_persist\")\n assert_equal(w.getwalletinfo()[\"avoid_reuse\"], False)\n w.unloadwallet()", "smellKey": "0", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "async def find_keys(self, resource: tuple[str, str]) -> list[UserSessionDict]:\n if not resource:\n return []\n\n field, value = resource\n return [\n self._decode_hash_key(hash_key)\n async for hash_key in self.client.scan_iter(match=f\"*:{_RESOURCE_SUFFIX}\")\n if value\n == await handle_redis_returns_union_types(self.client.hget(hash_key, field))\n ]", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def setup_socketio(app: FastAPI):\n settings: ApplicationSettings = app.state.settings\n\n async def _on_startup() -> None:\n assert app.state.rabbitmq_client # nosec\n\n # Connect to the as an external process in write-only mode\n # SEE https://python-socketio.readthedocs.io/en/stable/server.html#emitting-from-external-processes\n assert settings.RABBIT_SETTINGS # nosec\n app.state.external_socketio = socketio.AsyncAioPikaManager(\n url=settings.RABBIT_SETTINGS.dsn, logger=_logger, write_only=True\n )\n\n async def _on_shutdown() -> None:\n if external_socketio := getattr(app.state, \"external_socketio\"): # noqa: B009\n await cleanup_socketio_async_pubsub_manager(\n server_manager=external_socketio\n )\n\n app.add_event_handler(\"startup\", _on_startup)\n app.add_event_handler(\"shutdown\", _on_shutdown)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_analyses_to_upload_when_filtering_with_workflow(helpers, sample_store, timestamp):\n \"\"\"Test analyses to upload to when existing workflow and using it in filtering.\"\"\"\n # GIVEN a store with an analysis that is analysed with MIP\n workflow = Workflow.MIP_DNA\n helpers.add_analysis(store=sample_store, completed_at=timestamp, workflow=workflow)\n\n # WHEN fetching all workflows that are analysed with MIP\n records: list[Analysis] = [\n analysis_obj for analysis_obj in sample_store.get_analyses_to_upload(workflow=workflow)\n ]\n\n for analysis_obj in records:\n # THEN the workflow should be MIP in the analysis object\n assert analysis_obj.workflow == workflow", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_xml_content():\n root = ET.parse(data_stream_path).getroot()\n xml_content = ssg.xml.XMLContent(root)\n expected_component_refs = {\n \"#scap_org.open-scap_comp_test_single_rule.oval.xml\":\n \"scap_org.open-scap_cref_test_single_rule.oval.xml\",\n \"#scap_org.open-scap_comp_cpe.oval.xml\":\n \"scap_org.open-scap_cref_cpe.oval.xml\"\n }\n assert xml_content.component_refs == expected_component_refs\n expected_uris = {\n \"#scap_org.open-scap_cref_test_single_rule.oval.xml\":\n \"test_single_rule.oval.xml\",\n \"#scap_org.open-scap_cref_cpe.oval.xml\":\n \"cpe.oval.xml\"\n }\n assert xml_content.uris == expected_uris\n assert \"OVAL\" in xml_content.components\n assert \"test_single_rule.oval.xml\" in xml_content.components[\"OVAL\"]\n assert \"cpe.oval.xml\" in xml_content.components[\"OVAL\"]\n xml_component = xml_content.components[\"OVAL\"][\"test_single_rule.oval.xml\"]\n assert type(xml_component) is ssg.xml.XMLComponent", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def test_group_delete(self, shell):\n \"\"\"\n Test do_group_delete with confirmation\n\n :param shell:\n :return:\n \"\"\"\n shell.client.systemgroup.delete = MagicMock()\n shell.user_confirm = MagicMock(return_value=True)\n shell.help_group_delete = MagicMock()\n\n spacecmd.group.do_group_delete(shell, \"groupone grouptwo groupthree\")\n\n assert not shell.help_group_delete.called\n assert shell.client.systemgroup.delete.called\n assert shell.user_confirm.called\n\n groups = [[((shell.session, \"groupone\"), {})],\n [((shell.session, \"grouptwo\"), {})],\n [((shell.session, \"groupthree\"), {})],]\n for call in shell.client.systemgroup.delete.call_args_list:\n assert_args_expect([call], next(iter(groups)))\n groups.pop(0)\n assert not groups", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def logout(self):\n \"\"\"Log out the user by removing the cookies and session object.\"\"\"\n from django.contrib.auth import get_user, logout\n\n request = HttpRequest()\n if self.session:\n request.session = self.session\n request.user = get_user(request)\n else:\n engine = import_module(settings.SESSION_ENGINE)\n request.session = engine.SessionStore()\n logout(request)\n self.cookies = SimpleCookie()", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def test_update_analysis_uploaded_at(\n store_with_analyses_for_cases_not_uploaded_fluffy: Store, timestamp_yesterday: datetime\n):\n # GIVEN a store with an analysis\n analysis: Analysis = store_with_analyses_for_cases_not_uploaded_fluffy._get_query(\n Analysis\n ).first()\n assert analysis.uploaded_at != timestamp_yesterday\n\n # WHEN updating the uploaded_at field\n store_with_analyses_for_cases_not_uploaded_fluffy.update_analysis_uploaded_at(\n analysis_id=analysis.id, uploaded_at=timestamp_yesterday\n )\n\n # THEN the uploaded_at field is updated\n assert analysis.uploaded_at == timestamp_yesterday", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def _handle_coordinator_update(self) -> None:\n \"\"\"Update attributes when the coordinator updates.\"\"\"\n self._async_update_attrs()\n super()._handle_coordinator_update()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_step_user(\n self, user_input: dict[str, Any] | None = None\n ) -> ConfigFlowResult:\n \"\"\"Handle the user step to pick discovered device.\"\"\"\n if user_input is not None:\n address = user_input[CONF_ADDRESS]\n await self.async_set_unique_id(address, raise_on_progress=False)\n self._abort_if_unique_id_configured()\n return self.async_create_entry(\n title=self._discovered_devices[address], data={}\n )\n\n current_addresses = self._async_current_ids()\n for discovery_info in async_discovered_service_info(self.hass, False):\n address = discovery_info.address\n if address in current_addresses or address in self._discovered_devices:\n continue\n device = DeviceData()\n if device.supported(discovery_info):\n self._discovered_devices[address] = (\n device.title or device.get_device_name() or discovery_info.name\n )\n\n if not self._discovered_devices:\n return self.async_abort(reason=\"no_devices_found\")\n\n return self.async_show_form(\n step_id=\"user\",\n data_schema=vol.Schema(\n {vol.Required(CONF_ADDRESS): vol.In(self._discovered_devices)}\n ),\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_unlock(self, **kwargs: Any) -> None:\n \"\"\"Unlock the door.\"\"\"\n try:\n self._lock.state = TedeeLockState.UNLOCKING\n self.async_write_ha_state()\n\n await self.coordinator.tedee_client.unlock(self._lock.lock_id)\n await self.coordinator.async_request_refresh()\n except (TedeeClientException, Exception) as ex:\n raise HomeAssistantError(\n \"Failed to unlock the door. Lock %s\" % self._lock.lock_id\n ) from ex", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_button(\n hass: HomeAssistant,\n load_int: ConfigEntry,\n) -> None:\n \"\"\"Test the Coolmaster button.\"\"\"\n assert hass.states.get(\"binary_sensor.l1_101_clean_filter\").state == \"on\"\n\n button = hass.states.get(\"button.l1_101_reset_filter\")\n assert button is not None\n await hass.services.async_call(\n BUTTON_DOMAIN,\n SERVICE_PRESS,\n {\n ATTR_ENTITY_ID: button.entity_id,\n },\n blocking=True,\n )\n await hass.async_block_till_done()\n\n assert hass.states.get(\"binary_sensor.l1_101_clean_filter\").state == \"off\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_ssdp_update_missed_bootid(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n mock_disconnected_entity_id: str,\n dmr_device_mock: Mock,\n) -> None:\n \"\"\"Test device disconnects when it gets ssdp:update bootid it wasn't expecting.\"\"\"\n # Start with a disconnected device\n entity_id = mock_disconnected_entity_id\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == ha_const.STATE_UNAVAILABLE\n\n # \"Reconnect\" the device\n domain_data_mock.upnp_factory.async_create_device.side_effect = None\n\n # Send SSDP alive with boot ID\n ssdp_callback = ssdp_scanner_mock.async_register_callback.call_args.args[0].target\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"1\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n # Send SSDP update with skipped boot ID (not previously seen)\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_udn=MOCK_DEVICE_UDN,\n ssdp_headers={\n \"NTS\": \"ssdp:update\",\n ssdp.ATTR_SSDP_BOOTID: \"2\",\n ssdp.ATTR_SSDP_NEXTBOOTID: \"3\",\n },\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.UPDATE,\n )\n await hass.async_block_till_done()\n\n # Device should not reconnect yet\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 0\n assert dmr_device_mock.async_subscribe_services.await_count == 1\n\n # Send a new SSDP alive with the new boot ID, device should reconnect\n await ssdp_callback(\n ssdp.SsdpServiceInfo(\n ssdp_usn=MOCK_DEVICE_USN,\n ssdp_location=MOCK_DEVICE_LOCATION,\n ssdp_headers={ssdp.ATTR_SSDP_BOOTID: \"3\"},\n ssdp_st=MOCK_DEVICE_TYPE,\n upnp={},\n ),\n ssdp.SsdpChange.ALIVE,\n )\n await hass.async_block_till_done()\n\n mock_state = hass.states.get(entity_id)\n assert mock_state is not None\n assert mock_state.state == MediaPlayerState.IDLE\n\n assert dmr_device_mock.async_unsubscribe_services.await_count == 1\n assert dmr_device_mock.async_subscribe_services.await_count == 2", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def getDownloads(self):\n return self.downloads", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def async_set_cover_position(self, **kwargs: Any) -> None:\n \"\"\"Move the cover to a specific position.\"\"\"\n await self._channel.set_position(100 - kwargs[ATTR_POSITION])", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_light_set_on(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n init_integration: MockConfigEntry,\n) -> None:\n \"\"\"Test set on of the light.\"\"\"\n\n entity_id = \"light.lightbulb\"\n state = hass.states.get(entity_id)\n assert state\n assert state.state == STATE_ON\n assert state.attributes.get(\"friendly_name\") == \"lightbulb\"\n\n entry = entity_registry.async_get(entity_id)\n assert entry\n assert (\n entry.unique_id\n == \"3WRRJR6RCZQZSND8VP0YTO3YXCSOFPKBMW8T51TU-LQ*JHJZIZ9ORJNHB7DZNBNAOSEDECVTTZ48SABTCA3WA3M\"\n )\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: [entity_id]},\n blocking=True,\n )\n\n state = hass.states.get(entity_id)\n assert state\n assert state.state == STATE_ON", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_changed_on_raise(self) -> None:\n task = self.prepare_task(owner=self.cluster, name=\"dummy\")\n job, *_ = JobRepoImpl.get_task_jobs(task.id)\n executor = self.prepare_executor(\n executor_type=ADCMChangeFlagPluginExecutor,\n call_arguments={\n \"operation\": \"up\",\n \"name\": \"adcm_outdated_config\",\n \"objects\": [\n {\"type\": \"component\", \"service_name\": self.service_1.name, \"component_name\": self.component_2.name},\n ],\n },\n call_context=job,\n )\n\n result = executor.execute()\n self.assertIsNone(result.error)\n self.assertTrue(result.changed)\n\n result = executor.execute()\n self.assertIsNone(result.error)\n self.assertFalse(result.changed)\n\n result = executor.execute()\n self.assertIsNone(result.error)\n self.assertFalse(result.changed)\n\n lower_all_flags(on_objects=[CoreObjectDescriptor(id=self.component_2.id, type=ADCMCoreType.COMPONENT)])\n\n result = executor.execute()\n self.assertIsNone(result.error)\n self.assertTrue(result.changed)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def test_validate_trigger_invalid_triggers(\n hass: HomeAssistant,\n device_registry: dr.DeviceRegistry,\n mock_block_device: Mock,\n caplog: pytest.LogCaptureFixture,\n) -> None:\n \"\"\"Test for click_event with invalid triggers.\"\"\"\n entry = await init_integration(hass, 1)\n device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0]\n\n assert await async_setup_component(\n hass,\n automation.DOMAIN,\n {\n automation.DOMAIN: [\n {\n \"trigger\": {\n CONF_PLATFORM: \"device\",\n CONF_DOMAIN: DOMAIN,\n CONF_DEVICE_ID: device.id,\n CONF_TYPE: \"single\",\n CONF_SUBTYPE: \"button3\",\n },\n \"action\": {\n \"service\": \"test.automation\",\n \"data_template\": {\"some\": \"test_trigger_single_click\"},\n },\n },\n ]\n },\n )\n\n assert \"Invalid (type,subtype): ('single', 'button3')\" in caplog.text", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def test_group_list_no_data(self, shell):\n \"\"\"\n Test do_group_list with no data return.\n\n :param shell:\n :return:\n \"\"\"\n shell.client.systemgroup.listAllGroups = MagicMock(return_value=[\n {\"name\": \"group-a\"}, {\"name\": \"group-b\"}\n ])\n mprint = MagicMock()\n with patch(\"spacecmd.group.print\", mprint):\n out = spacecmd.group.do_group_list(shell, \"\", doreturn=False)\n\n assert shell.client.systemgroup.listAllGroups.called\n assert out is None\n assert mprint.called\n\n assert_expect(mprint.call_args_list,\n \"group-a\\ngroup-b\")", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "async def test_service_call_all_none(hass: HomeAssistant, target) -> None:\n \"\"\"Test service call targeting all.\"\"\"\n calls = async_mock_service(hass, \"test_domain\", \"test_service\")\n\n config = {\n \"service\": \"test_domain.test_service\",\n \"target\": {\"entity_id\": target},\n }\n\n await service.async_call_from_config(hass, config)\n await hass.async_block_till_done()\n\n assert dict(calls[0].data) == {\"entity_id\": target}", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def mocked_backend_services_apis_for_delete_non_existing_project(\n mocked_webserver_service_api: MockRouter,\n project_tests_dir: Path,\n) -> MockedBackendApiDict:\n mock_name = \"delete_project_not_found.json\"\n environment = jinja2.Environment(\n loader=jinja2.FileSystemLoader(project_tests_dir / \"mocks\"), autoescape=True\n )\n template = environment.get_template(mock_name)\n\n def _response(request: httpx.Request, project_id: str):\n capture = HttpApiCallCaptureModel.parse_raw(\n template.render(project_id=project_id)\n )\n return httpx.Response(\n status_code=capture.status_code, json=capture.response_body\n )\n\n mocked_webserver_service_api.delete(\n path__regex=rf\"/projects/(?P<project_id>{UUID_RE_BASE})$\",\n name=\"delete_project\",\n ).mock(side_effect=_response)\n\n return MockedBackendApiDict(webserver=mocked_webserver_service_api, catalog=None)", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_lower_with_name_component_host_action_from_context_success(self) -> None:\n flag_name = \"some_flag\"\n\n self.check_lower_called(\n flag_name=flag_name,\n task=self.prepare_task(owner=self.component_2, name=\"on_host\", host=self.host_1),\n arguments=f\"\"\"\n operation: down\n name: {flag_name}\n \"\"\",\n targets=(CoreObjectDescriptor(id=self.component_2.id, type=ADCMCoreType.COMPONENT),),\n )", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def expectation_suite(\n context: CloudDataContext,\n expectation_suite: ExpectationSuite,\n) -> ExpectationSuite:\n \"\"\"Add Expectations for the Data Assets defined in this module.\n Note: There is no need to test Expectation Suite CRUD.\n Those assertions can be found in the expectation_suite fixture.\"\"\"\n expectation_suite.add_expectation_configuration(\n expectation_configuration=ExpectationConfiguration(\n type=\"expect_column_values_to_not_be_null\",\n kwargs={\n \"column\": \"name\",\n \"mostly\": 1,\n },\n )\n )\n return expectation_suite", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def test_get_applications(microbial_store: Store, expected_number_of_applications):\n \"\"\"Test function to return the applications.\"\"\"\n\n # GIVEN a store with application records\n\n # WHEN getting the query for the flow cells\n applications: list[Application] = microbial_store.get_applications()\n\n # THEN return an application with the supplied application tag\n assert len(applications) == expected_number_of_applications", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def page_candidates(self) -> List[str]:\n if not self._scanned_directory:\n self._scan_directory()\n\n return self._page_candidates", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def test_light_effects(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a generic light entity that supports on and on and brightness.\"\"\"\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153,\n max_mireds=400,\n effects=[\"effect1\", \"effect2\"],\n supported_color_modes=[\n LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS,\n ],\n )\n ]\n states = [LightState(key=1, state=True, brightness=100)]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n assert state.attributes[ATTR_EFFECT_LIST] == [\"effect1\", \"effect2\"]\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\", ATTR_EFFECT: \"effect1\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [\n call(\n key=1,\n state=True,\n color_mode=LightColorCapability.ON_OFF\n | LightColorCapability.BRIGHTNESS,\n effect=\"effect1\",\n )\n ]\n )\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_removeconfigchannels_noargs(self, shell):\n \"\"\"\n Test removeconfigchannels command triggers help on no args.\n \"\"\"\n shell.help_activationkey_removeconfigchannels = MagicMock()\n shell.client.activationkey.removeConfigChannels = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removeconfigchannels(shell, \"\")\n assert shell.help_activationkey_removeconfigchannels.called\n assert not shell.client.activationkey.removeConfigChannels.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_container_group_create(run_module, admin_user, kube_credential):\n pod_spec = \"{ 'Nothing': True }\"\n\n result = run_module('instance_group', {'name': 'foo-c-group', 'credential': kube_credential.id, 'is_container_group': True, 'state': 'present'}, admin_user)\n assert not result.get('failed', False), result['msg']\n assert result['changed']\n\n ig = InstanceGroup.objects.get(name='foo-c-group')\n assert ig.pod_spec_override == ''\n\n result = run_module(\n 'instance_group',\n {'name': 'foo-c-group', 'credential': kube_credential.id, 'is_container_group': True, 'pod_spec_override': pod_spec, 'state': 'present'},\n admin_user,\n )\n assert not result.get('failed', False), result['msg']\n assert result['changed']\n\n ig = InstanceGroup.objects.get(name='foo-c-group')\n assert ig.pod_spec_override == pod_spec", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def mock_upload_path(mocker: MockFixture, e_tag: str) -> MockFixture:\n return mocker.patch(\n \"simcore_sdk.node_ports_common.filemanager.upload_path\",\n return_value=UploadedFile(0, e_tag),\n autospec=True,\n )", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_project_help_comment_matches_default(project_help_comment):\n \"\"\"\n What does this test and why?\n Make sure that the templates built on data_context.types.base.DataContextConfigDefaults match the desired default.\n \"\"\" # noqa: E501\n\n assert project_help_comment == templates.PROJECT_HELP_COMMENT", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def mock_data_asset(monkeypatch, mocker: pytest_mock.MockerFixture) -> DataAsset:\n monkeypatch.setattr(DataAsset, \"build_batch_request\", mocker.Mock())\n data_asset: DataAsset = DataAssetForTests(name=\"my_data_asset\", type=\"table\")\n\n return data_asset", "smellKey": "0", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(self) -> None:\n \"\"\"Initialize flow.\"\"\"\n self.flow_impl = None", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def temporary_filename():\n import tempfile\n try:\n tmp = tempfile.NamedTemporaryFile(delete=False)\n tmp_name = tmp.name\n tmp.close()\n yield tmp_name\n finally:\n os.unlink(tmp_name)", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "async def test_coordinates_function_returns_state_if_no_coords(\n hass: HomeAssistant,\n) -> None:\n \"\"\"Test test_coordinates function.\"\"\"\n hass.states.async_set(\n \"test.object\",\n \"abc\",\n )\n assert location.find_coordinates(hass, \"test.object\") == \"abc\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_applications_is_not_archived(\n microbial_store: Store, expected_number_of_not_archived_applications\n):\n \"\"\"Test function to return the application when not archived.\"\"\"\n\n # GIVEN a store with application records\n\n # WHEN getting the query for the flow cells\n applications: list[Application] = microbial_store.get_applications_is_not_archived()\n\n # THEN return an application with the supplied application tag\n assert len(applications) == expected_number_of_not_archived_applications\n for application in applications:\n assert not application.is_archived", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_pre_delete(sender, instance, **kwargs):\n delete_related_notes(instance)", "smellKey": "0", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def unique_id(self) -> str:\n \"\"\"Set unique id of entity.\"\"\"\n return self._unique_id", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_extract_from_service_label_id(hass: HomeAssistant) -> None:\n \"\"\"Test the extraction using label ID as reference.\"\"\"\n entities = [\n MockEntity(name=\"with_my_label\", entity_id=\"light.with_my_label\"),\n MockEntity(name=\"no_labels\", entity_id=\"light.no_labels\"),\n MockEntity(\n name=\"with_labels_from_device\", entity_id=\"light.with_labels_from_device\"\n ),\n ]\n\n call = ServiceCall(\"light\", \"turn_on\", {\"label_id\": \"label_area\"})\n extracted = await service.async_extract_entities(hass, entities, call)\n assert len(extracted) == 1\n assert extracted[0].entity_id == \"light.with_labels_from_device\"\n\n call = ServiceCall(\"light\", \"turn_on\", {\"label_id\": \"my-label\"})\n extracted = await service.async_extract_entities(hass, entities, call)\n assert len(extracted) == 1\n assert extracted[0].entity_id == \"light.with_my_label\"\n\n call = ServiceCall(\"light\", \"turn_on\", {\"label_id\": [\"my-label\", \"label1\"]})\n extracted = await service.async_extract_entities(hass, entities, call)\n assert len(extracted) == 2\n assert sorted(ent.entity_id for ent in extracted) == [\n \"light.with_labels_from_device\",\n \"light.with_my_label\",\n ]\n\n call = ServiceCall(\n \"light\",\n \"turn_on\",\n {\"label_id\": [\"my-label\", \"label1\"], \"device_id\": \"device-no-labels\"},\n )\n extracted = await service.async_extract_entities(hass, entities, call)\n assert len(extracted) == 3\n assert sorted(ent.entity_id for ent in extracted) == [\n \"light.no_labels\",\n \"light.with_labels_from_device\",\n \"light.with_my_label\",\n ]", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def quality_control_sample(self, sample_id: str, metrics: SampleMetrics) -> SampleQualityResult:\n \"\"\"Perform a quality control of a sample given its metrics.\"\"\"\n valid_read_count: bool = self.has_valid_total_reads(sample_id)\n valid_mapping: bool = has_valid_mapping_rate(metrics)\n valid_duplication: bool = has_valid_duplication_rate(metrics)\n valid_inserts: bool = has_valid_median_insert_size(metrics)\n valid_coverage: bool = has_valid_average_coverage(metrics)\n valid_10x_coverage: bool = has_valid_10x_coverage(metrics)\n\n sample: Sample = self.status_db.get_sample_by_internal_id(sample_id)\n application_tag: str = get_application_tag(sample)\n\n if is_control := is_sample_negative_control(sample):\n sample_quality = SampleQualityResult(\n sample_id=sample_id,\n passes_qc=valid_read_count,\n is_control=is_control,\n passes_reads_qc=valid_read_count,\n application_tag=application_tag,\n )\n ResultLogger.log_sample_result(sample_quality)\n return sample_quality\n\n sample_passes_qc: bool = (\n valid_read_count\n and valid_mapping\n and valid_duplication\n and valid_inserts\n and valid_coverage\n and valid_10x_coverage\n )\n\n if has_non_microbial_apptag(sample):\n sample_passes_qc = valid_read_count\n\n sample_quality = SampleQualityResult(\n sample_id=sample_id,\n passes_qc=sample_passes_qc,\n is_control=is_control,\n application_tag=application_tag,\n passes_reads_qc=valid_read_count,\n passes_mapping_qc=valid_mapping,\n passes_duplication_qc=valid_duplication,\n passes_inserts_qc=valid_inserts,\n passes_coverage_qc=valid_coverage,\n passes_10x_coverage_qc=valid_10x_coverage,\n )\n ResultLogger.log_sample_result(sample_quality)\n return sample_quality", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_do_activationkey_addpackages_help_args(self, shell):\n \"\"\"\n Test add packages method call shows help on help args passed.\n \"\"\"\n shell.help_activationkey_addpackages = MagicMock()\n shell.client.activationkey.addPackages = MagicMock()\n\n spacecmd.activationkey.do_activationkey_addpackages(shell, \"help\")\n assert shell.help_activationkey_addpackages.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def __init__(self, check_supported_wheels: bool = True) -> None:\n \"\"\"Create a RequirementSet.\"\"\"\n\n self.requirements: Dict[str, InstallRequirement] = OrderedDict()\n self.check_supported_wheels = check_supported_wheels\n\n self.unnamed_requirements: List[InstallRequirement] = []", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "async def async_alarm_trigger(self, code: str | None = None) -> None:\n \"\"\"Send alarm trigger command.\"\"\"\n self._client.alarm_control_panel_command(\n self._key, AlarmControlPanelCommand.TRIGGER, code\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n coordinator: ShellyBlockCoordinator,\n sensor_block: Block | None,\n device_block: Block | None,\n entry: RegistryEntry | None = None,\n ) -> None:\n \"\"\"Initialize climate.\"\"\"\n super().__init__(coordinator)\n\n self.block: Block | None = sensor_block\n self.control_result: dict[str, Any] | None = None\n self.device_block: Block | None = device_block\n self.last_state: State | None = None\n self.last_state_attributes: Mapping[str, Any]\n self._preset_modes: list[str] = []\n self._last_target_temp = SHTRV_01_TEMPERATURE_SETTINGS[\"default\"]\n self._attr_name = coordinator.name\n\n if self.block is not None and self.device_block is not None:\n self._unique_id = f\"{self.coordinator.mac}-{self.block.description}\"\n assert self.block.channel\n self._preset_modes = [\n PRESET_NONE,\n *coordinator.device.settings[\"thermostats\"][int(self.block.channel)][\n \"schedule_profile_names\"\n ],\n ]\n elif entry is not None:\n self._unique_id = entry.unique_id\n self._attr_device_info = DeviceInfo(\n connections={(CONNECTION_NETWORK_MAC, coordinator.mac)},\n )\n\n self._channel = cast(int, self._unique_id.split(\"_\")[1])", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_browse_media_favorites(\n self, list_id: str, expanded: bool\n ) -> BrowseMedia:\n \"\"\"Return channel media objects.\"\"\"\n if expanded:\n favorites = self._tv.favorite_lists.get(list_id)\n if favorites:\n\n def get_name(channel):\n channel_data = self._tv.channels.get(str(channel[\"ccid\"]))\n if channel_data:\n return channel_data[\"name\"]\n return f\"Channel: {channel['ccid']}\"\n\n children = [\n BrowseMedia(\n title=get_name(channel),\n media_class=MediaClass.CHANNEL,\n media_content_id=f\"{list_id}/{channel['ccid']}\",\n media_content_type=MediaType.CHANNEL,\n can_play=True,\n can_expand=False,\n )\n for channel in favorites.get(\"channels\", [])\n ]\n else:\n children = None\n else:\n children = None\n\n favorite = self._tv.favorite_lists[list_id]\n return BrowseMedia(\n title=favorite.get(\"name\", f\"Favorites {list_id}\"),\n media_class=MediaClass.DIRECTORY,\n media_content_id=f\"favorites/{list_id}\",\n media_content_type=MediaType.CHANNELS,\n children_media_class=MediaClass.CHANNEL,\n can_play=False,\n can_expand=True,\n children=children,\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_image_entity(\n hass: HomeAssistant,\n hass_client: ClientSessionGenerator,\n snapshot: SnapshotAssertion,\n fc_class_mock,\n fh_class_mock,\n) -> None:\n \"\"\"Test image entity.\"\"\"\n\n # setup component with image platform only\n with patch(\n \"homeassistant.components.fritz.PLATFORMS\",\n [Platform.IMAGE],\n ):\n entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)\n entry.add_to_hass(hass)\n await hass.config_entries.async_setup(entry.entry_id)\n\n await hass.async_block_till_done()\n assert entry.state is ConfigEntryState.LOADED\n\n # test image entity is generated as expected\n states = hass.states.async_all(IMAGE_DOMAIN)\n assert len(states) == 1\n\n state = states[0]\n assert state.name == \"Mock Title GuestWifi\"\n assert state.entity_id == \"image.mock_title_guestwifi\"\n\n access_token = state.attributes[\"access_token\"]\n assert state.attributes == {\n \"access_token\": access_token,\n \"entity_picture\": f\"/api/image_proxy/image.mock_title_guestwifi?token={access_token}\",\n \"friendly_name\": \"Mock Title GuestWifi\",\n }\n\n entity_registry = async_get_entity_registry(hass)\n entity_entry = entity_registry.async_get(\"image.mock_title_guestwifi\")\n assert entity_entry.unique_id == \"1c_ed_6f_12_34_11_guestwifi_qr_code\"\n\n # test image download\n client = await hass_client()\n resp = await client.get(\"/api/image_proxy/image.mock_title_guestwifi\")\n assert resp.status == HTTPStatus.OK\n\n body = await resp.read()\n assert body == snapshot", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_customer_id_from_ticket(analysis_store, customer_id, ticket_id: str):\n \"\"\"Tests if the function in fact returns the correct customer.\"\"\"\n # Given a store with a ticket\n\n # Then the function should return the customer connected to the ticket\n assert analysis_store.get_customer_id_from_ticket(ticket_id) == customer_id", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def stop(self) -> None:\n pass", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def store(\n context: click.Context, case_id: str, comment: str | None, dry_run: bool, force: bool\n) -> None:\n \"\"\"\n Store deliverable files in Housekeeper after meeting QC metrics criteria.\n\n Raises:\n click.Abort: If an error occurs during the deliverables file generation, metrics\n validation, or storage processes.\n \"\"\"\n validate_force_store_option(force=force, comment=comment)\n analysis_api: NfAnalysisAPI = context.obj.meta_apis[MetaApis.ANALYSIS_API]\n try:\n analysis_api.store(case_id=case_id, comment=comment, dry_run=dry_run, force=force)\n except Exception as error:\n LOG.error(repr(error))\n raise click.Abort()", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def test_website_analysis_for_image(boefje_runner, mocker):\n do_request_mock = mocker.patch(\"boefjes.plugins.kat_webpage_analysis.main.do_request\", spec=Response)\n meta = BoefjeMeta.model_validate_json(get_dummy_data(\"webpage-analysis.json\"))\n\n mock_response = Response()\n mock_response._content = bytes(get_dummy_data(\"cat_image\"))\n mock_response.request = mocker.MagicMock(spec=PreparedRequest())\n mock_response.request.url = \"\"\n mock_response.request.method = \"GET\"\n mock_response.headers = CaseInsensitiveDict(json.loads(get_dummy_data(\"download_image_headers.json\")))\n\n do_request_mock.return_value = mock_response\n\n output = boefje_runner.run(meta, {})\n assert \"image/jpeg\" in output[2][0]", "smellKey": "0", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "async def mock_save_db_cb(*args, **kwargs):\n pass", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_platform_from_text_and_empty_conditionals(product_cpes):\n platform = ssg.build_yaml.Platform.from_text(\n \"krb5_server_older_than_1_17-18 and krb5_workstation_older_than_1_17-18\", product_cpes)\n assert platform.get_remediation_conditional(\"bash\") == \"\"\n assert platform.get_remediation_conditional(\"ansible\") == \"\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def pretty_title(media, short_name=False):\n \"\"\"Return a formatted title for the given media item.\"\"\"\n year = None\n if media.type == \"album\":\n if short_name:\n title = media.title\n else:\n title = f\"{media.parentTitle} - {media.title}\"\n elif media.type == \"episode\":\n title = f\"{media.seasonEpisode.upper()} - {media.title}\"\n if not short_name:\n title = f\"{media.grandparentTitle} - {title}\"\n elif media.type == \"season\":\n title = media.title\n if not short_name:\n title = f\"{media.parentTitle} - {title}\"\n elif media.type == \"track\":\n title = f\"{media.index}. {media.title}\"\n else:\n title = media.title\n\n if media.type in [\"album\", \"movie\", \"season\"]:\n year = media.year\n\n if year:\n title += f\" ({year!s})\"\n\n return title", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def subgraph_get_path_vertices(ctx: mgp.ProcCtx, path: mgp.Path) -> mgp.Record(node=mgp.Vertex):\n return [mgp.Record(node=node) for node in path.vertices]", "smellKey": "0", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def async_setup_climate_entities(\n async_add_entities: AddEntitiesCallback,\n coordinator: ShellyBlockCoordinator,\n) -> None:\n \"\"\"Set up online climate devices.\"\"\"\n\n device_block: Block | None = None\n sensor_block: Block | None = None\n\n assert coordinator.device.blocks\n\n for block in coordinator.device.blocks:\n if block.type == \"device\":\n device_block = block\n if hasattr(block, \"targetTemp\"):\n sensor_block = block\n\n if sensor_block and device_block:\n LOGGER.debug(\"Setup online climate device %s\", coordinator.name)\n async_add_entities(\n [BlockSleepingClimate(coordinator, sensor_block, device_block)]\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def set_plan_for_partner_user(partner_user: PartnerUser, plan: SLPlan):\n sub = PartnerSubscription.get_by(partner_user_id=partner_user.id)\n if plan.type == SLPlanType.Free:\n if sub is not None:\n LOG.i(\n f\"Deleting partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]\"\n )\n PartnerSubscription.delete(sub.id)\n agent.record_custom_event(\"PlanChange\", {\"plan\": \"free\"})\n else:\n if sub is None:\n LOG.i(\n f\"Creating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]\"\n )\n create_partner_subscription(\n partner_user=partner_user,\n expiration=plan.expiration,\n msg=\"Upgraded via partner. User did not have a previous partner subscription\",\n )\n agent.record_custom_event(\"PlanChange\", {\"plan\": \"premium\", \"type\": \"new\"})\n else:\n if sub.end_at != plan.expiration:\n LOG.i(\n f\"Updating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]\"\n )\n agent.record_custom_event(\n \"PlanChange\", {\"plan\": \"premium\", \"type\": \"extension\"}\n )\n sub.end_at = plan.expiration\n emit_user_audit_log(\n user=partner_user.user,\n action=UserAuditLogAction.SubscriptionExtended,\n message=\"Extended partner subscription\",\n )\n Session.commit()", "smellKey": "0", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "async def async_press(self) -> None:\n \"\"\"Handle the button press.\"\"\"\n async with self.coordinator.radio_operation_lock:\n await self.entity_description.press_action(self._shade)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_task_tracker_list_all_entries(\n redis_client_sdk_deferred_tasks: RedisClientSDK,\n task_schedule: TaskScheduleModel,\n count: int,\n):\n task_tracker = RedisTaskTracker(redis_client_sdk_deferred_tasks)\n\n async def _make_entry() -> None:\n task_uid = await task_tracker.get_new_unique_identifier()\n await task_tracker.save(task_uid, task_schedule)\n\n await logged_gather(*(_make_entry() for _ in range(count)))\n\n entries = await task_tracker.all()\n assert len(entries) == count\n assert entries == [task_schedule for _ in range(count)]", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def test_write_buffer_set_bit_little_endian(mocker) -> None:\n wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN)\n wb.write_bit(True)\n ba: memoryview = wb.get_bytes()\n assert b\"\\x80\" == ba.tobytes()", "smellKey": "0", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "async def test_call_context_target_specific(\n hass: HomeAssistant, mock_handle_entity_call, mock_entities\n) -> None:\n \"\"\"Check targeting specific entities.\"\"\"\n with patch(\n \"homeassistant.auth.AuthManager.async_get_user\",\n return_value=Mock(\n permissions=PolicyPermissions(\n {\"entities\": {\"entity_ids\": {\"light.kitchen\": True}}}, None\n )\n ),\n ):\n await service.entity_service_call(\n hass,\n mock_entities,\n Mock(),\n ServiceCall(\n \"test_domain\",\n \"test_service\",\n {\"entity_id\": \"light.kitchen\"},\n context=Context(user_id=\"mock-id\"),\n ),\n )\n\n assert len(mock_handle_entity_call.mock_calls) == 1\n assert mock_handle_entity_call.mock_calls[0][1][1].entity_id == \"light.kitchen\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_closest_with_no_states_with_location() -> None:\n \"\"\"Set up the tests.\"\"\"\n state = State(\"light.test\", \"on\")\n state2 = State(\n \"light.test\", \"on\", {ATTR_LATITUDE: \"invalid\", ATTR_LONGITUDE: 123.45}\n )\n state3 = State(\"light.test\", \"on\", {ATTR_LONGITUDE: 123.45})\n\n assert location.closest(123.45, 123.45, [state, state2, state3]) is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def is_prod_appengine_mvms():\n \"\"\"Deprecated.\"\"\"\n return False", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def _async_build_by_country(\n self, radios: RadioBrowser, item: MediaSourceItem\n ) -> list[BrowseMediaSource]:\n \"\"\"Handle browsing radio stations by country.\"\"\"\n category, _, country_code = (item.identifier or \"\").partition(\"/\")\n if country_code:\n stations = await radios.stations(\n filter_by=FilterBy.COUNTRY_CODE_EXACT,\n filter_term=country_code,\n hide_broken=True,\n order=Order.NAME,\n reverse=False,\n )\n return self._async_build_stations(radios, stations)\n\n # We show country in the root additionally, when there is no item\n if not item.identifier or category == \"country\":\n # Trigger the lazy loading of the country database to happen inside the executor\n await self.hass.async_add_executor_job(lambda: len(pycountry.countries))\n countries = await radios.countries(order=Order.NAME)\n return [\n BrowseMediaSource(\n domain=DOMAIN,\n identifier=f\"country/{country.code}\",\n media_class=MediaClass.DIRECTORY,\n media_content_type=MediaType.MUSIC,\n title=country.name,\n can_play=False,\n can_expand=True,\n thumbnail=country.favicon,\n )\n for country in countries\n ]\n\n return []", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def add_named_requirement(self, install_req: InstallRequirement) -> None:\n assert install_req.name\n\n project_name = canonicalize_name(install_req.name)\n self.requirements[project_name] = install_req", "smellKey": "0", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "async def test_send_command(command: str, method: str, hold_secs: float) -> None:\n \"\"\"Test \"send_command\" method.\"\"\"\n remote = AppleTVRemote(\"test\", \"test\", None)\n remote.atv = AsyncMock()\n await remote.async_send_command(\n [command],\n **{ATTR_NUM_REPEATS: 1, ATTR_DELAY_SECS: 0, ATTR_HOLD_SECS: hold_secs},\n )\n assert len(remote.atv.method_calls) == 1\n if hold_secs >= 1:\n assert (\n str(remote.atv.method_calls[0])\n == f\"call.{method}(action=<InputAction.Hold: 2>)\"\n )\n else:\n assert str(remote.atv.method_calls[0]) == f\"call.{method}()\"", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def build_source(\n location: str,\n *,\n candidates_from_page: CandidatesFromPage,\n page_validator: PageValidator,\n expand_dir: bool,\n cache_link_parsing: bool,\n project_name: str,\n) -> Tuple[Optional[str], Optional[LinkSource]]:\n path: Optional[str] = None\n url: Optional[str] = None\n if os.path.exists(location): # Is a local path.\n url = path_to_url(location)\n path = location\n elif location.startswith(\"file:\"): # A file: URL.\n url = location\n path = url_to_path(location)\n elif is_url(location):\n url = location\n\n if url is None:\n msg = (\n \"Location '%s' is ignored: \"\n \"it is either a non-existing path or lacks a specific scheme.\"\n )\n logger.warning(msg, location)\n return (None, None)\n\n if path is None:\n source: LinkSource = _RemoteFileSource(\n candidates_from_page=candidates_from_page,\n page_validator=page_validator,\n link=Link(url, cache_link_parsing=cache_link_parsing),\n )\n return (url, source)\n\n if os.path.isdir(path):\n if expand_dir:\n source = _FlatDirectorySource(\n candidates_from_page=candidates_from_page,\n path=path,\n project_name=project_name,\n )\n else:\n source = _IndexDirectorySource(\n candidates_from_page=candidates_from_page,\n link=Link(url, cache_link_parsing=cache_link_parsing),\n )\n return (url, source)\n elif os.path.isfile(path):\n source = _LocalFileSource(\n candidates_from_page=candidates_from_page,\n link=Link(url, cache_link_parsing=cache_link_parsing),\n )\n return (url, source)\n logger.warning(\n \"Location '%s' is ignored: it is neither a file nor a directory.\",\n location,\n )\n return (url, None)", "smellKey": "0", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "async def create_device_delayed(_location):\n \"\"\"Delay before continuing with async_create_device.\n\n This gives a chance for parallel calls to `_device_connect` to occur.\n \"\"\"\n await asyncio.sleep(0.1)\n return DEFAULT", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_get_organism_by_internal_id_returns_none_when_id_does_not_exist(\n store_with_organisms: Store,\n non_existent_id: str,\n):\n \"\"\"Test finding an organism by internal ID when the ID does not exist.\"\"\"\n\n # GIVEN a store with multiple organisms\n organisms: Query = store_with_organisms._get_query(table=Organism)\n assert organisms.count() > 0\n\n # WHEN finding the organism by internal ID that does not exist\n filtered_organism: Organism = store_with_organisms.get_organism_by_internal_id(\n internal_id=non_existent_id\n )\n\n # THEN the filtered organism should be None\n assert filtered_organism is None", "smellKey": "0", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def current_cover_position(self) -> int | None:\n \"\"\"Return current position of cover.\n\n None is unknown, 0 is closed, 100 is fully open\n Velbus: 100 = closed, 0 = open\n \"\"\"\n pos = self._channel.get_position()\n if pos is not None:\n return 100 - pos\n return None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def mock_entities(hass: HomeAssistant) -> dict[str, MockEntity]:\n \"\"\"Return mock entities in an ordered dict.\"\"\"\n kitchen = MockEntity(\n entity_id=\"light.kitchen\",\n available=True,\n should_poll=False,\n supported_features=SUPPORT_A,\n )\n living_room = MockEntity(\n entity_id=\"light.living_room\",\n available=True,\n should_poll=False,\n supported_features=SUPPORT_B,\n )\n bedroom = MockEntity(\n entity_id=\"light.bedroom\",\n available=True,\n should_poll=False,\n supported_features=(SUPPORT_A | SUPPORT_B),\n )\n bathroom = MockEntity(\n entity_id=\"light.bathroom\",\n available=True,\n should_poll=False,\n supported_features=(SUPPORT_B | SUPPORT_C),\n )\n entities = {}\n entities[kitchen.entity_id] = kitchen\n entities[living_room.entity_id] = living_room\n entities[bedroom.entity_id] = bedroom\n entities[bathroom.entity_id] = bathroom\n for entity in entities.values():\n entity.hass = hass\n return entities", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_group_create_name_only(self, shell):\n \"\"\"\n Test do_group_create with name argument (half-fall back to interactive).\n\n :param shell:\n :return:\n \"\"\"\n msg = \"Great group for nothing\"\n shell.client.systemgroup.create = MagicMock()\n prompter = MagicMock(return_value=msg)\n\n with patch(\"spacecmd.group.prompt_user\", prompter):\n spacecmd.group.do_group_create(shell, \"Jeff\")\n\n assert prompter.called\n assert shell.client.systemgroup.create.called\n\n assert_args_expect(shell.client.systemgroup.create.call_args_list,\n [((shell.session, 'Jeff', msg), {})])", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def app_cfg(default_app_cfg, unused_tcp_port_factory, monkeypatch) -> dict[str, Any]:\n \"\"\"App's configuration used for every test in this module\n\n NOTE: Overrides services/web/server/tests/unit/with_dbs/conftest.py::app_cfg to influence app setup\n \"\"\"\n cfg = deepcopy(default_app_cfg)\n\n monkeypatch.setenv(\"WEBSERVER_DEV_FEATURES_ENABLED\", \"1\")\n\n cfg[\"main\"][\"port\"] = unused_tcp_port_factory()\n cfg[\"main\"][\"studies_access_enabled\"] = True\n\n exclude = {\n \"activity\",\n \"clusters\",\n \"computation\",\n \"diagnostics\",\n \"garbage_collector\",\n \"groups\",\n \"publications\",\n \"smtp\",\n \"socketio\",\n \"storage\",\n \"studies_dispatcher\",\n \"tags\",\n \"tracing\",\n }\n include = {\n \"catalog\",\n \"db\",\n \"login\",\n \"meta_modeling\", # MODULE UNDER TEST\n \"products\",\n \"projects\",\n \"redis\",\n \"resource_manager\",\n \"rest\",\n \"users\",\n \"version_control\",\n }\n\n assert include.intersection(exclude) == set()\n\n for section in include:\n cfg[section][\"enabled\"] = True\n for section in exclude:\n cfg[section][\"enabled\"] = False\n\n # NOTE: To see logs, use pytest -s --log-cli-level=DEBUG\n setup_logging(level=logging.DEBUG, log_format_local_dev_enabled=True)\n\n # Enforces smallest GC in the background task\n cfg[\"resource_manager\"][\"garbage_collection_interval_seconds\"] = 1\n\n return cfg", "smellKey": "0", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def hvac_action(self) -> HVACAction:\n \"\"\"HVAC current action.\"\"\"\n if not self.status[\"output\"]:\n return HVACAction.IDLE\n\n return (\n HVACAction.COOLING\n if self._thermostat_type == \"cooling\"\n else HVACAction.HEATING\n )", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def test_do_activationkey_setdescription_args(self, shell):\n \"\"\"\n Test do_activationkey_setdescription command triggers activationkey.setDetails API call.\n \"\"\"\n shell.help_activationkey_enable = MagicMock()\n shell.client.activationkey.setDetails = MagicMock()\n\n spacecmd.activationkey.do_activationkey_setdescription(shell, \"key_one some description of it here\")\n assert not shell.help_activationkey_enable.called\n assert shell.client.activationkey.setDetails.called\n\n for call in shell.client.activationkey.setDetails.call_args_list:\n session, key, arg = call[0]\n assert shell.session == session\n assert \"description\" in arg\n assert arg[\"description\"] == \"some description of it here\"", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def test_profile_to_xml_element_extends(profile_ospp_with_extends):\n profile_el = profile_ospp_with_extends.to_xml_element()\n assert profile_el.get(\"extends\") == \\\n \"xccdf_org.ssgproject.content_profile_standard\"", "smellKey": "0", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "async def test_unavailable_device(\n hass: HomeAssistant,\n domain_data_mock: Mock,\n ssdp_scanner_mock: Mock,\n config_entry_mock: MockConfigEntry,\n core_state: CoreState,\n) -> None:\n \"\"\"Test a DlnaDmrEntity with out a connected DmrDevice.\"\"\"\n # Cause connection attempts to fail\n hass.set_state(core_state)\n domain_data_mock.upnp_factory.async_create_device.side_effect = UpnpConnectionError\n config_entry_mock.add_to_hass(hass)\n\n with patch(\n \"homeassistant.components.dlna_dmr.media_player.DmrDevice\", autospec=True\n ) as dmr_device_constructor_mock:\n mock_entity_id = await setup_mock_component(hass, config_entry_mock)\n mock_state = hass.states.get(mock_entity_id)\n assert mock_state is not None\n\n # Check device is not created\n dmr_device_constructor_mock.assert_not_called()\n\n # Check attempt was made to create a device from the supplied URL\n domain_data_mock.upnp_factory.async_create_device.assert_awaited_once_with(\n MOCK_DEVICE_LOCATION\n )\n # Check event notifiers are not acquired\n domain_data_mock.async_get_event_notifier.assert_not_called()\n # Check SSDP notifications are registered\n ssdp_scanner_mock.async_register_callback.assert_any_call(\n ANY, {\"USN\": MOCK_DEVICE_USN}\n )\n ssdp_scanner_mock.async_register_callback.assert_any_call(\n ANY, {\"_udn\": MOCK_DEVICE_UDN, \"NTS\": \"ssdp:byebye\"}\n )\n # Quick check of the state to verify the entity has no connected DmrDevice\n assert mock_state.state == ha_const.STATE_UNAVAILABLE\n # Check the name matches that supplied\n assert mock_state.name == MOCK_DEVICE_NAME\n\n # Check that an update does not attempt to contact the device because\n # poll_availability is False\n domain_data_mock.upnp_factory.async_create_device.reset_mock()\n await async_update_entity(hass, mock_entity_id)\n domain_data_mock.upnp_factory.async_create_device.assert_not_called()\n\n # Now set poll_availability = True and expect construction attempt\n hass.config_entries.async_update_entry(\n config_entry_mock, options={CONF_POLL_AVAILABILITY: True}\n )\n await hass.async_block_till_done()\n await async_update_entity(hass, mock_entity_id)\n domain_data_mock.upnp_factory.async_create_device.assert_awaited_once_with(\n MOCK_DEVICE_LOCATION\n )\n\n # Check attributes are unavailable\n attrs = mock_state.attributes\n for attr in ATTR_TO_PROPERTY:\n assert attr not in attrs\n\n assert attrs[ha_const.ATTR_FRIENDLY_NAME] == MOCK_DEVICE_NAME\n assert attrs[ha_const.ATTR_SUPPORTED_FEATURES] == 0\n assert mp_const.ATTR_SOUND_MODE_LIST not in attrs\n\n # Check service calls do nothing\n SERVICES: list[tuple[str, dict]] = [\n (ha_const.SERVICE_VOLUME_SET, {mp_const.ATTR_MEDIA_VOLUME_LEVEL: 0.80}),\n (ha_const.SERVICE_VOLUME_MUTE, {mp_const.ATTR_MEDIA_VOLUME_MUTED: True}),\n (ha_const.SERVICE_MEDIA_PAUSE, {}),\n (ha_const.SERVICE_MEDIA_PLAY, {}),\n (ha_const.SERVICE_MEDIA_STOP, {}),\n (ha_const.SERVICE_MEDIA_NEXT_TRACK, {}),\n (ha_const.SERVICE_MEDIA_PREVIOUS_TRACK, {}),\n (ha_const.SERVICE_MEDIA_SEEK, {mp_const.ATTR_MEDIA_SEEK_POSITION: 33}),\n (\n mp_const.SERVICE_PLAY_MEDIA,\n {\n mp_const.ATTR_MEDIA_CONTENT_TYPE: MediaType.MUSIC,\n mp_const.ATTR_MEDIA_CONTENT_ID: (\n \"http://198.51.100.20:8200/MediaItems/17621.mp3\"\n ),\n mp_const.ATTR_MEDIA_ENQUEUE: False,\n },\n ),\n (mp_const.SERVICE_SELECT_SOUND_MODE, {mp_const.ATTR_SOUND_MODE: \"Default\"}),\n (ha_const.SERVICE_SHUFFLE_SET, {mp_const.ATTR_MEDIA_SHUFFLE: True}),\n (ha_const.SERVICE_REPEAT_SET, {mp_const.ATTR_MEDIA_REPEAT: \"all\"}),\n ]\n for service, data in SERVICES:\n await hass.services.async_call(\n MP_DOMAIN,\n service,\n {ATTR_ENTITY_ID: mock_entity_id, **data},\n blocking=True,\n )\n\n # Check hass device information has not been filled in yet\n dev_reg = async_get_dr(hass)\n device = dev_reg.async_get_device(\n connections={(CONNECTION_UPNP, MOCK_DEVICE_UDN)},\n identifiers=set(),\n )\n assert device is not None\n assert device.name is None\n assert device.manufacturer is None\n\n # Unload config entry to clean up\n assert await hass.config_entries.async_remove(config_entry_mock.entry_id) == {\n \"require_restart\": False\n }\n\n # Confirm SSDP notifications unregistered\n assert ssdp_scanner_mock.async_register_callback.return_value.call_count == 2\n\n # Check event notifiers are not released\n domain_data_mock.async_release_event_notifier.assert_not_called()\n\n # Entity should be removed by the cleanup\n assert hass.states.get(mock_entity_id) is None", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def async_new_address_callback(\n hass: HomeAssistant, config_entry: AxisConfigEntry\n ) -> None:\n \"\"\"Handle signals of device getting new address.\n\n Called when config entry is updated.\n This is a static method because a class method (bound method),\n cannot be used with weak references.\n \"\"\"\n hub = config_entry.runtime_data\n hub.config = AxisConfig.from_config_entry(config_entry)\n hub.event_source.config_entry = config_entry\n hub.api.config.host = hub.config.host\n async_dispatcher_send(hass, hub.signal_new_address)", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def get(self, request, *args, **kwargs): # noqa: ARG001, ARG002\n cluster = get_object_for_user(request.user, VIEW_CLUSTER_PERM, Cluster, id=kwargs[\"cluster_id\"])\n check_custom_perm(request.user, \"add_service_to\", \"cluster\", cluster)\n bundle = self.get_queryset().filter(bundle=cluster.prototype.bundle)\n shared = self.get_queryset().filter(shared=True).exclude(bundle=cluster.prototype.bundle)\n serializer = self.get_serializer(\n list(chain(self.filter_queryset(queryset=bundle), self.filter_queryset(queryset=shared))),\n many=True,\n context={\"request\": request, \"cluster\": cluster},\n )\n\n return Response(serializer.data)", "smellKey": "0", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "async def async_added_to_hass(self) -> None:\n \"\"\"Run when this Entity has been added to HA.\"\"\"\n self._lj.on_connected_changed(self._on_connected_changed)", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "async def test_validate_trigger_rpc_device_not_ready(\n hass: HomeAssistant,\n device_registry: dr.DeviceRegistry,\n service_calls: list[ServiceCall],\n mock_rpc_device: Mock,\n monkeypatch: pytest.MonkeyPatch,\n) -> None:\n \"\"\"Test validate trigger config when RPC device is not ready.\"\"\"\n monkeypatch.setattr(mock_rpc_device, \"initialized\", False)\n entry = await init_integration(hass, 2)\n device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0]\n\n assert await async_setup_component(\n hass,\n automation.DOMAIN,\n {\n automation.DOMAIN: [\n {\n \"trigger\": {\n CONF_PLATFORM: \"device\",\n CONF_DOMAIN: DOMAIN,\n CONF_DEVICE_ID: device.id,\n CONF_TYPE: \"single_push\",\n CONF_SUBTYPE: \"button1\",\n },\n \"action\": {\n \"service\": \"test.automation\",\n \"data_template\": {\"some\": \"test_trigger_single_push\"},\n },\n },\n ]\n },\n )\n message = {\n CONF_DEVICE_ID: device.id,\n ATTR_CLICK_TYPE: \"single_push\",\n ATTR_CHANNEL: 1,\n }\n hass.bus.async_fire(EVENT_SHELLY_CLICK, message)\n await hass.async_block_till_done()\n\n assert len(service_calls) == 1\n assert service_calls[0].data[\"some\"] == \"test_trigger_single_push\"", "smellKey": "0", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def test_light_on_and_brightness(\n hass: HomeAssistant, mock_client: APIClient, mock_generic_device_entry\n) -> None:\n \"\"\"Test a generic light entity that supports on and on and brightness.\"\"\"\n mock_client.api_version = APIVersion(1, 7)\n entity_info = [\n LightInfo(\n object_id=\"mylight\",\n key=1,\n name=\"my light\",\n unique_id=\"my_light\",\n min_mireds=153,\n max_mireds=400,\n supported_color_modes=[\n LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS,\n LightColorCapability.ON_OFF,\n ],\n )\n ]\n states = [LightState(key=1, state=True, brightness=100)]\n user_service = []\n await mock_generic_device_entry(\n mock_client=mock_client,\n entity_info=entity_info,\n user_service=user_service,\n states=states,\n )\n state = hass.states.get(\"light.test_mylight\")\n assert state is not None\n assert state.state == STATE_ON\n\n await hass.services.async_call(\n LIGHT_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"light.test_mylight\"},\n blocking=True,\n )\n mock_client.light_command.assert_has_calls(\n [call(key=1, state=True, color_mode=LightColorCapability.ON_OFF)]\n )\n mock_client.light_command.reset_mock()", "smellKey": "0", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_job_node(self, workflow_job):\n candidates = workflow_job.get_related('workflow_nodes', identifier=self.identifier)\n return candidates.results.pop()", "smellKey": "0", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def test_do_activationkey_removeentitlements_help_args(self, shell):\n \"\"\"\n Test removeentitlements method call shows help if only one argument is passed.\n \"\"\"\n shell.help_activationkey_removeentitlements = MagicMock()\n shell.client.activationkey.removeEntitlements = MagicMock()\n\n spacecmd.activationkey.do_activationkey_removeentitlements(shell, \"key\")\n assert shell.help_activationkey_removeentitlements.called\n assert not shell.client.activationkey.removeEntitlements.called", "smellKey": "0", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n image_size=224,\n patch_size=16,\n num_channels=3,\n qkv_bias=True,\n encoder_stride=16,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.encoder_stride = encoder_stride", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_features: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`\n or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is\n only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> import torch\n >>> from transformers import Speech2TextProcessor, Speech2TextForConditionalGeneration\n >>> from datasets import load_dataset\n\n >>> model = Speech2TextForConditionalGeneration.from_pretrained(\"facebook/s2t-small-librispeech-asr\")\n >>> processor = Speech2TextProcessor.from_pretrained(\"facebook/s2t-small-librispeech-asr\")\n\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n >>> inputs = processor(\n ... ds[0][\"audio\"][\"array\"], sampling_rate=ds[0][\"audio\"][\"sampling_rate\"], return_tensors=\"pt\"\n ... )\n >>> input_features = inputs.input_features\n\n >>> generated_ids = model.generate(inputs=input_features)\n\n >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\n >>> transcription\n 'mister quilter is the apostle of the middle classes and we are glad to welcome his gospel'\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_features,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0])\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=XLMForQuestionAnsweringOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n is_impossible: Optional[torch.Tensor] = None,\n cls_index: Optional[torch.Tensor] = None,\n p_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, XLMForQuestionAnsweringOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels whether a question has an answer or no answer (SQuAD 2.0)\n cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the classification token to use as input for computing plausibility of the\n answer.\n p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be\n masked. 0.0 mean token is not masked.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, XLMForQuestionAnswering\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"FacebookAI/xlm-mlm-en-2048\")\n >>> model = XLMForQuestionAnswering.from_pretrained(\"FacebookAI/xlm-mlm-en-2048\")\n\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(\n ... 0\n ... ) # Batch size 1\n >>> start_positions = torch.tensor([1])\n >>> end_positions = torch.tensor([3])\n\n >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)\n >>> loss = outputs.loss\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n output = transformer_outputs[0]\n\n outputs = self.qa_outputs(\n output,\n start_positions=start_positions,\n end_positions=end_positions,\n cls_index=cls_index,\n is_impossible=is_impossible,\n p_mask=p_mask,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return outputs + transformer_outputs[1:]\n\n return XLMForQuestionAnsweringOutput(\n loss=outputs.loss,\n start_top_log_probs=outputs.start_top_log_probs,\n start_top_index=outputs.start_top_index,\n end_top_log_probs=outputs.end_top_log_probs,\n end_top_index=outputs.end_top_index,\n cls_logits=outputs.cls_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=8,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=8,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n num_queries=12,\n num_channels=3,\n image_size=196,\n n_targets=8,\n num_labels=91,\n num_feature_levels=4,\n encoder_n_points=2,\n decoder_n_points=6,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_queries = num_queries\n self.num_channels = num_channels\n self.image_size = image_size\n self.n_targets = n_targets\n self.num_labels = num_labels\n self.num_feature_levels = num_feature_levels\n self.encoder_n_points = encoder_n_points\n self.decoder_n_points = decoder_n_points\n\n # we also set the expected seq length for both encoder and decoder\n self.encoder_seq_length = (\n math.ceil(self.image_size / 8) ** 2\n + math.ceil(self.image_size / 16) ** 2\n + math.ceil(self.image_size / 32) ** 2\n + math.ceil(self.image_size / 64) ** 2\n )\n self.decoder_seq_length = self.num_queries", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def compile_dir(dir, maxlevels=None, ddir=None, force=False,\n rx=None, quiet=0, legacy=False, optimize=-1, workers=1,\n invalidation_mode=None, *, stripdir=None,\n prependdir=None, limit_sl_dest=None, hardlink_dupes=False):\n \"\"\"Byte-compile all modules in the given directory tree.\n\n Arguments (only dir is required):\n\n dir: the directory to byte-compile\n maxlevels: maximum recursion level (default `sys.getrecursionlimit()`)\n ddir: the directory that will be prepended to the path to the\n file as it is compiled into each byte-code file.\n force: if True, force compilation, even if timestamps are up-to-date\n quiet: full output with False or 0, errors only with 1,\n no output with 2\n legacy: if True, produce legacy pyc paths instead of PEP 3147 paths\n optimize: int or list of optimization levels or -1 for level of\n the interpreter. Multiple levels leads to multiple compiled\n files each with one optimization level.\n workers: maximum number of parallel workers\n invalidation_mode: how the up-to-dateness of the pyc will be checked\n stripdir: part of path to left-strip from source file path\n prependdir: path to prepend to beginning of original file path, applied\n after stripdir\n limit_sl_dest: ignore symlinks if they are pointing outside of\n the defined path\n hardlink_dupes: hardlink duplicated pyc files\n \"\"\"\n ProcessPoolExecutor = None\n if ddir is not None and (stripdir is not None or prependdir is not None):\n raise ValueError((\"Destination dir (ddir) cannot be used \"\n \"in combination with stripdir or prependdir\"))\n if ddir is not None:\n stripdir = dir\n prependdir = ddir\n ddir = None\n if workers < 0:\n raise ValueError('workers must be greater or equal to 0')\n if workers != 1:\n # Check if this is a system where ProcessPoolExecutor can function.\n from concurrent.futures.process import _check_system_limits\n try:\n _check_system_limits()\n except NotImplementedError:\n workers = 1\n else:\n from concurrent.futures import ProcessPoolExecutor\n if maxlevels is None:\n maxlevels = sys.getrecursionlimit()\n files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels)\n success = True\n if workers != 1 and ProcessPoolExecutor is not None:\n import multiprocessing\n if multiprocessing.get_start_method() == 'fork':\n mp_context = multiprocessing.get_context('forkserver')\n else:\n mp_context = None\n # If workers == 0, let ProcessPoolExecutor choose\n workers = workers or None\n with ProcessPoolExecutor(max_workers=workers,\n mp_context=mp_context) as executor:\n results = executor.map(partial(compile_file,\n ddir=ddir, force=force,\n rx=rx, quiet=quiet,\n legacy=legacy,\n optimize=optimize,\n invalidation_mode=invalidation_mode,\n stripdir=stripdir,\n prependdir=prependdir,\n limit_sl_dest=limit_sl_dest,\n hardlink_dupes=hardlink_dupes),\n files,\n chunksize=4)\n success = min(results, default=True)\n else:\n for file in files:\n if not compile_file(file, ddir, force, rx, quiet,\n legacy, optimize, invalidation_mode,\n stripdir=stripdir, prependdir=prependdir,\n limit_sl_dest=limit_sl_dest,\n hardlink_dupes=hardlink_dupes):\n success = False\n return success", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LUKE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=LukeSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n entity_ids: Optional[torch.LongTensor] = None,\n entity_attention_mask: Optional[torch.FloatTensor] = None,\n entity_token_type_ids: Optional[torch.LongTensor] = None,\n entity_position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LukeSequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.luke(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=True,\n )\n\n pooled_output = outputs.pooler_output\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(logits.device)\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if not return_dict:\n return tuple(\n v\n for v in [loss, logits, outputs.hidden_states, outputs.entity_hidden_states, outputs.attentions]\n if v is not None\n )\n\n return LukeSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n entity_hidden_states=outputs.entity_hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size: int = 250002,\n hidden_size: int = 768,\n num_hidden_layers: int = 12,\n num_attention_heads: int = 12,\n intermediate_size: int = 3072,\n hidden_act: str = \"gelu\",\n hidden_dropout_prob: float = 0.1,\n attention_probs_dropout_prob: float = 0.1,\n max_position_embeddings: int = 514,\n initializer_range: float = 0.02,\n pad_token_id: int = 1,\n layer_norm_eps: float = 1e-05,\n classifier_dropout=None,\n act_dropout=0.0,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.classifier_dropout = classifier_dropout\n self.act_dropout = act_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file=None,\n merges_file=None,\n tokenizer_file=None,\n errors=\"replace\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n add_prefix_space=False,\n trim_offsets=True,\n **kwargs,\n ):\n mask_token = (\n AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)\n if isinstance(mask_token, str)\n else mask_token\n )\n super().__init__(\n vocab_file,\n merges_file,\n tokenizer_file=tokenizer_file,\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n sep_token=sep_token,\n cls_token=cls_token,\n unk_token=unk_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n trim_offsets=trim_offsets,\n **kwargs,\n )\n\n pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())\n if pre_tok_state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop(\"type\"))\n pre_tok_state[\"add_prefix_space\"] = add_prefix_space\n self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)\n\n self.add_prefix_space = add_prefix_space\n\n tokenizer_component = \"post_processor\"\n tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)\n if tokenizer_component_instance:\n state = json.loads(tokenizer_component_instance.__getstate__())\n\n # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`\n if \"sep\" in state:\n state[\"sep\"] = tuple(state[\"sep\"])\n if \"cls\" in state:\n state[\"cls\"] = tuple(state[\"cls\"])\n\n changes_to_apply = False\n\n if state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n state[\"add_prefix_space\"] = add_prefix_space\n changes_to_apply = True\n\n if state.get(\"trim_offsets\", trim_offsets) != trim_offsets:\n state[\"trim_offsets\"] = trim_offsets\n changes_to_apply = True\n\n if changes_to_apply:\n component_class = getattr(processors, state.pop(\"type\"))\n new_value = component_class(**state)\n setattr(self.backend_tokenizer, tokenizer_component, new_value)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@deprecate_kwarg(\"reduce_labels\", new_name=\"do_reduce_labels\", version=\"4.41.0\")\n @filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n segmentation_maps: Optional[ImageInput] = None,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_reduce_labels: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n segmentation_maps (`ImageInput`, *optional*)\n Segmentation maps to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after resizing.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be\n padded with zeros and then cropped\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0\n is used for background, and background itself is not included in all classes of a dataset (e.g.\n ADE20k). The background label will be replaced by 255.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=True, param_name=\"size\")\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, default_to_square=True, param_name=\"crop_size\")\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels\n\n images = make_list_of_images(images)\n\n if segmentation_maps is not None:\n segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)\n\n if segmentation_maps is not None and not valid_images(segmentation_maps):\n raise ValueError(\n \"Invalid segmentation_maps type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n images = [\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n do_center_crop=do_center_crop,\n do_rescale=do_rescale,\n do_normalize=do_normalize,\n resample=resample,\n size=size,\n rescale_factor=rescale_factor,\n crop_size=crop_size,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in images\n ]\n\n data = {\"pixel_values\": images}\n\n if segmentation_maps is not None:\n segmentation_maps = [\n self._preprocess_segmentation_map(\n segmentation_map=segmentation_map,\n do_reduce_labels=do_reduce_labels,\n do_resize=do_resize,\n resample=resample,\n size=size,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n )\n for segmentation_map in segmentation_maps\n ]\n data[\"labels\"] = segmentation_maps\n\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n num_key_value_heads=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n router_jitter_noise=0.1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope\n self.router_jitter_noise = router_jitter_noise", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=267735,\n cutoffs=[20000, 40000, 200000],\n d_model=1024,\n d_embed=1024,\n n_head=16,\n d_head=64,\n d_inner=4096,\n div_val=4,\n pre_lnorm=False,\n n_layer=18,\n mem_len=1600,\n clamp_len=1000,\n same_length=True,\n proj_share_all_but_first=True,\n attn_type=0,\n sample_softmax=-1,\n adaptive=True,\n dropout=0.1,\n dropatt=0.0,\n untie_r=True,\n init=\"normal\",\n init_range=0.01,\n proj_init_std=0.01,\n init_std=0.02,\n layer_norm_epsilon=1e-5,\n eos_token_id=0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.cutoffs = []\n self.cutoffs.extend(cutoffs)\n if proj_share_all_but_first:\n self.tie_projs = [False] + [True] * len(self.cutoffs)\n else:\n self.tie_projs = [False] + [False] * len(self.cutoffs)\n self.d_model = d_model\n self.d_embed = d_embed\n self.d_head = d_head\n self.d_inner = d_inner\n self.div_val = div_val\n self.pre_lnorm = pre_lnorm\n self.n_layer = n_layer\n self.n_head = n_head\n self.mem_len = mem_len\n self.same_length = same_length\n self.attn_type = attn_type\n self.clamp_len = clamp_len\n self.sample_softmax = sample_softmax\n self.adaptive = adaptive\n self.dropout = dropout\n self.dropatt = dropatt\n self.untie_r = untie_r\n self.init = init\n self.init_range = init_range\n self.proj_init_std = proj_init_std\n self.init_std = init_std\n self.layer_norm_epsilon = layer_norm_epsilon\n super().__init__(eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def batch_encode_plus(\n self,\n batch_text_or_text_pairs: Union[\n List[TextInput],\n List[TextInputPair],\n List[PreTokenizedInput],\n List[PreTokenizedInputPair],\n List[EncodedInput],\n List[EncodedInputPair],\n ],\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n is_split_into_words: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n split_special_tokens: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.\n\n <Tip warning={true}>\n\n This method is deprecated, `__call__` should be used instead.\n\n </Tip>\n\n Args:\n batch_text_or_text_pairs (`List[str]`, `List[Tuple[str, str]]`, `List[List[str]]`, `List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also `List[List[int]]`, `List[Tuple[List[int], List[int]]]`):\n Batch of sequences or pair of sequences to be encoded. This can be a list of\n string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see\n details in `encode_plus`).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._batch_encode_plus(\n batch_text_or_text_pairs=batch_text_or_text_pairs,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n split_special_tokens=split_special_tokens,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"relu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=10000,\n decoder_layers=6,\n decoder_ffn_dim=2048,\n decoder_attention_heads=4,\n decoder_layerdrop=0.0,\n use_cache=True,\n activation_function=\"relu\",\n d_model=256,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=2,\n scale_embedding=True,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n max_target_positions=1024,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = decoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n self.max_target_positions = max_target_positions\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n decoder_start_token_id=decoder_start_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(REMBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=\"google/rembert\",\n output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n \"\"\"\n outputs = self.rembert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n patch_size=4,\n num_channels=3,\n embed_dim=64,\n depths=[3, 4, 6, 5],\n num_heads=[2, 4, 8, 16],\n kernel_size=7,\n dilations=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]],\n mlp_ratio=3.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n layer_scale_init_value=0.0,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_layers = len(depths)\n self.num_heads = num_heads\n self.kernel_size = kernel_size\n self.dilations = dilations\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel\n # this indicates the channel dimension after the last stage of the model\n self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))\n self.layer_scale_init_value = layer_scale_init_value\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(\n FLAUBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\")\n )\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFMultipleChoiceModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n langs: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n lengths: np.ndarray | tf.Tensor | None = None,\n cache: Optional[Dict[str, tf.Tensor]] = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: bool = False,\n ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:\n if input_ids is not None:\n num_choices = shape_list(input_ids)[1]\n seq_length = shape_list(input_ids)[2]\n else:\n num_choices = shape_list(inputs_embeds)[1]\n seq_length = shape_list(inputs_embeds)[2]\n\n flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None\n flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None\n flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None\n flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None\n flat_langs = tf.reshape(langs, (-1, seq_length)) if langs is not None else None\n flat_inputs_embeds = (\n tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))\n if inputs_embeds is not None\n else None\n )\n\n if lengths is not None:\n logger.warning(\n \"The `lengths` parameter cannot be used with the Flaubert multiple choice models. Please use the \"\n \"attention mask instead.\",\n )\n lengths = None\n\n transformer_outputs = self.transformer(\n flat_input_ids,\n flat_attention_mask,\n flat_langs,\n flat_token_type_ids,\n flat_position_ids,\n lengths,\n cache,\n head_mask,\n flat_inputs_embeds,\n output_attentions,\n output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n output = transformer_outputs[0]\n logits = self.sequence_summary(output)\n logits = self.logits_proj(logits)\n reshaped_logits = tf.reshape(logits, (-1, num_choices))\n\n loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)\n\n if not return_dict:\n output = (reshaped_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFMultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LUKE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=EntityClassificationOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n entity_ids: Optional[torch.LongTensor] = None,\n entity_attention_mask: Optional[torch.FloatTensor] = None,\n entity_token_type_ids: Optional[torch.LongTensor] = None,\n entity_position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, EntityClassificationOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)` or `(batch_size, num_labels)`, *optional*):\n Labels for computing the classification loss. If the shape is `(batch_size,)`, the cross entropy loss is\n used for the single-label classification. In this case, labels should contain the indices that should be in\n `[0, ..., config.num_labels - 1]`. If the shape is `(batch_size, num_labels)`, the binary cross entropy\n loss is used for the multi-label classification. In this case, labels should only contain `[0, 1]`, where 0\n and 1 indicate false and true, respectively.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, LukeForEntityClassification\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"studio-ousia/luke-large-finetuned-open-entity\")\n >>> model = LukeForEntityClassification.from_pretrained(\"studio-ousia/luke-large-finetuned-open-entity\")\n\n >>> text = \"Beyonc\u00e9 lives in Los Angeles.\"\n >>> entity_spans = [(0, 7)] # character-based entity span corresponding to \"Beyonc\u00e9\"\n >>> inputs = tokenizer(text, entity_spans=entity_spans, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> logits = outputs.logits\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print(\"Predicted class:\", model.config.id2label[predicted_class_idx])\n Predicted class: person\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.luke(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=True,\n )\n\n feature_vector = outputs.entity_last_hidden_state[:, 0, :]\n feature_vector = self.dropout(feature_vector)\n logits = self.classifier(feature_vector)\n\n loss = None\n if labels is not None:\n # When the number of dimension of `labels` is 1, cross entropy is used as the loss function. The binary\n # cross entropy is used otherwise.\n # move labels to correct device to enable model parallelism\n labels = labels.to(logits.device)\n if labels.ndim == 1:\n loss = nn.functional.cross_entropy(logits, labels)\n else:\n loss = nn.functional.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits))\n\n if not return_dict:\n return tuple(\n v\n for v in [loss, logits, outputs.hidden_states, outputs.entity_hidden_states, outputs.attentions]\n if v is not None\n )\n\n return EntityClassificationOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n entity_hidden_states=outputs.entity_hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(FSMT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(FSMT_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,\n past_key_values: Optional[Tuple[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n use_cache = False\n\n outputs = self.model(\n input_ids,\n inputs_embeds=inputs_embeds,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_inputs_embeds=decoder_inputs_embeds,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = outputs[0]\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # TODO(SS): do we need to ignore pad tokens in labels?\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.tgt_vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def query(\n self,\n projects: Sequence[Project],\n environments: Sequence[Environment] | None = None,\n sort_by: str = \"date\",\n limit: int = 100,\n cursor: Cursor | None = None,\n count_hits: bool = False,\n paginator_options: Mapping[str, Any] | None = None,\n search_filters: Sequence[SearchFilter] | None = None,\n date_from: datetime | None = None,\n date_to: datetime | None = None,\n max_hits: int | None = None,\n referrer: str | None = None,\n actor: Any | None = None,\n aggregate_kwargs: TrendsSortWeights | None = None,\n ) -> CursorResult[Group]:\n raise NotImplementedError", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@pytest.mark.parametrize(\n [\"detector_cls\", \"object_name\", \"baseline\", \"regressed\", \"escalated\", \"issue_type\"],\n [\n pytest.param(\n EndpointRegressionDetector,\n \"transaction_1\",\n 100,\n 300,\n 500,\n PerformanceP95EndpointRegressionGroupType,\n id=\"endpoint\",\n ),\n pytest.param(\n FunctionRegressionDetector,\n 123,\n 100_000_000,\n 300_000_000,\n 500_000_000,\n ProfileFunctionRegressionType,\n id=\"function\",\n ),\n ],\n)\n@pytest.mark.parametrize(\n [\"status\", \"substatus\", \"should_escalate\"],\n [\n pytest.param(GroupStatus.UNRESOLVED, GroupSubStatus.ESCALATING, False, id=\"escalating\"),\n pytest.param(GroupStatus.UNRESOLVED, GroupSubStatus.ONGOING, True, id=\"ongoing\"),\n pytest.param(GroupStatus.UNRESOLVED, GroupSubStatus.REGRESSED, False, id=\"regressed\"),\n pytest.param(GroupStatus.UNRESOLVED, GroupSubStatus.NEW, False, id=\"new\"),\n pytest.param(GroupStatus.RESOLVED, None, False, id=\"resolved\"),\n pytest.param(\n GroupStatus.IGNORED, GroupSubStatus.UNTIL_ESCALATING, True, id=\"until escalating\"\n ),\n pytest.param(\n GroupStatus.IGNORED, GroupSubStatus.UNTIL_CONDITION_MET, False, id=\"until condition met\"\n ),\n pytest.param(GroupStatus.IGNORED, GroupSubStatus.FOREVER, False, id=\"forever\"),\n ],\n)\n@mock.patch(\"sentry.issues.status_change_message.uuid4\", return_value=uuid.UUID(int=0))\n@mock.patch(\"sentry.statistical_detectors.detector.produce_occurrence_to_kafka\")\n@django_db_all\ndef test_redirect_escalations(\n produce_occurrence_to_kafka,\n mock_uuid4,\n detector_cls,\n object_name,\n baseline,\n regressed,\n escalated,\n issue_type,\n status,\n substatus,\n should_escalate,\n project,\n timestamp,\n django_cache, # the environment can persist in the cache otherwise\n):\n fingerprint = generate_fingerprint(detector_cls.regression_type, object_name)\n\n RegressionGroup.objects.create(\n type=detector_cls.regression_type.value,\n date_regressed=timestamp - timedelta(days=1),\n version=1,\n active=True,\n project_id=project.id,\n fingerprint=fingerprint,\n baseline=baseline,\n regressed=regressed,\n )\n\n event_id = uuid.uuid4().hex\n message = {\n \"id\": uuid.uuid4().hex,\n \"project_id\": project.id,\n \"event_id\": event_id,\n \"fingerprint\": [fingerprint],\n \"issue_title\": issue_type.description,\n \"subtitle\": \"\",\n \"resource_id\": None,\n \"evidence_data\": {},\n \"evidence_display\": [],\n \"type\": issue_type.type_id,\n \"detection_time\": timestamp.isoformat(),\n \"level\": \"info\",\n \"culprit\": \"\",\n \"payload_type\": PayloadType.OCCURRENCE.value,\n \"event\": {\n \"timestamp\": timestamp.isoformat(),\n \"project_id\": project.id,\n \"transaction\": \"\",\n \"event_id\": event_id,\n \"platform\": \"python\",\n \"received\": timestamp.isoformat(),\n \"tags\": {},\n },\n }\n\n result = _process_message(message)\n assert result is not None\n _, group_info = result\n assert group_info is not None\n group = group_info.group\n group.status = status\n group.substatus = substatus\n group.save()\n\n def get_trends(ts):\n payload = DetectorPayload(\n project_id=project.id,\n group=object_name,\n fingerprint=\"\", # this fingerprint isn't used so leave it blank\n count=100,\n value=escalated,\n timestamp=ts - timedelta(hours=1),\n )\n state = MovingAverageDetectorState(\n timestamp=ts - timedelta(hours=1),\n count=100,\n moving_avg_short=escalated,\n moving_avg_long=escalated,\n )\n yield TrendBundle(\n type=TrendType.Unchanged,\n score=1,\n payload=payload,\n state=state,\n )\n\n trends = get_trends(timestamp)\n trends = detector_cls.get_regression_groups(trends)\n trends = detector_cls.redirect_escalations(trends, timestamp)\n\n assert len(list(trends)) == 0\n\n if should_escalate:\n assert produce_occurrence_to_kafka.called\n status_change = StatusChangeMessage(\n fingerprint=[fingerprint],\n project_id=project.id,\n new_status=GroupStatus.UNRESOLVED,\n new_substatus=GroupSubStatus.ESCALATING,\n )\n produce_occurrence_to_kafka.assert_has_calls(\n [mock.call(payload_type=PayloadType.STATUS_CHANGE, status_change=status_change)]\n )\n\n # version 1 should be inactive now\n assert (\n RegressionGroup.objects.get(\n type=detector_cls.regression_type.value,\n version=1,\n project_id=project.id,\n fingerprint=fingerprint,\n active=False,\n )\n is not None\n )\n\n # version 2 should be created and active\n assert (\n RegressionGroup.objects.get(\n type=detector_cls.regression_type.value,\n version=2,\n project_id=project.id,\n fingerprint=fingerprint,\n active=True,\n )\n is not None\n )\n else:\n assert not produce_occurrence_to_kafka.called\n\n # version 1 should still be active\n assert (\n RegressionGroup.objects.get(\n type=detector_cls.regression_type.value,\n version=1,\n project_id=project.id,\n fingerprint=fingerprint,\n active=True,\n )\n is not None\n )\n\n # version 2 should not exist\n assert (\n RegressionGroup.objects.filter(\n type=detector_cls.regression_type.value,\n version=2,\n project_id=project.id,\n fingerprint=fingerprint,\n ).first()\n is None\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n type_sequence_label_size=10,\n initializer_range=0.02,\n scope=None,\n encoder_stride=2,\n mask_ratio=0.5,\n attn_implementation=\"eager\",\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.scope = scope\n self.encoder_stride = encoder_stride\n self.attn_implementation = attn_implementation\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1\n self.mask_ratio = mask_ratio\n self.num_masks = int(mask_ratio * self.seq_length)\n self.mask_length = num_patches", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def request(\n self,\n method,\n url,\n *,\n auth=None,\n status=HTTPStatus.OK,\n text=None,\n data=None,\n content=None,\n json=None,\n params=None,\n headers=None,\n exc=None,\n cookies=None,\n side_effect=None,\n closing=None,\n ):\n \"\"\"Mock a request.\"\"\"\n if not isinstance(url, RETYPE):\n url = URL(url)\n if params:\n url = url.with_query(params)\n\n self._mocks.append(\n AiohttpClientMockResponse(\n method=method,\n url=url,\n status=status,\n response=content,\n json=json,\n text=text,\n cookies=cookies,\n exc=exc,\n headers=headers,\n side_effect=side_effect,\n closing=closing,\n )\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=RetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n context_input_ids: Optional[torch.LongTensor] = None,\n context_attention_mask: Optional[torch.LongTensor] = None,\n doc_scores: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_retrieved: Optional[bool] = None,\n exclude_bos_score: Optional[bool] = None,\n reduce_loss: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n n_docs: Optional[int] = None,\n **kwargs, # needs kwargs for generation\n ) -> RetrievAugLMMarginOutput:\n r\"\"\"\n exclude_bos_score (`bool`, *optional*):\n Only relevant if `labels` is passed. If `True`, the score of the BOS token is disregarded when computing\n the loss.\n reduce_loss (`bool`, *optional*):\n Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`\n operation.\n kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):\n Legacy dictionary, which is required so that model can use *generate()* function.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RagRetriever, RagSequenceForGeneration\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/rag-sequence-nq\")\n >>> retriever = RagRetriever.from_pretrained(\n ... \"facebook/rag-sequence-nq\", index_name=\"exact\", use_dummy_dataset=True\n ... )\n >>> # initialize with RagRetriever to do everything in one forward call\n >>> model = RagSequenceForGeneration.from_pretrained(\"facebook/rag-token-nq\", retriever=retriever)\n\n >>> inputs = tokenizer(\"How many people live in Paris?\", return_tensors=\"pt\")\n >>> targets = tokenizer(text_target=\"In Paris, there are 10 million people.\", return_tensors=\"pt\")\n >>> input_ids = inputs[\"input_ids\"]\n >>> labels = targets[\"input_ids\"]\n >>> outputs = model(input_ids=input_ids, labels=labels)\n\n >>> # or use retriever separately\n >>> model = RagSequenceForGeneration.from_pretrained(\"facebook/rag-sequence-nq\", use_dummy_dataset=True)\n >>> # 1. Encode\n >>> question_hidden_states = model.question_encoder(input_ids)[0]\n >>> # 2. Retrieve\n >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors=\"pt\")\n >>> doc_scores = torch.bmm(\n ... question_hidden_states.unsqueeze(1), docs_dict[\"retrieved_doc_embeds\"].float().transpose(1, 2)\n ... ).squeeze(1)\n >>> # 3. Forward to generator\n >>> outputs = model(\n ... context_input_ids=docs_dict[\"context_input_ids\"],\n ... context_attention_mask=docs_dict[\"context_attention_mask\"],\n ... doc_scores=doc_scores,\n ... decoder_input_ids=labels,\n ... )\n ```\"\"\"\n n_docs = n_docs if n_docs is not None else self.config.n_docs\n exclude_bos_score = exclude_bos_score if exclude_bos_score is not None else self.config.exclude_bos_score\n reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss\n\n if labels is not None:\n if decoder_input_ids is None:\n decoder_input_ids = labels\n use_cache = False\n\n outputs = self.rag(\n input_ids=input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n context_input_ids=context_input_ids,\n context_attention_mask=context_attention_mask,\n doc_scores=doc_scores,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_retrieved=output_retrieved,\n n_docs=n_docs,\n )\n\n loss = None\n if labels is not None:\n loss = self.get_nll(\n outputs.logits,\n outputs.doc_scores,\n decoder_input_ids,\n reduce_loss=reduce_loss,\n epsilon=self.config.label_smoothing,\n exclude_bos_score=exclude_bos_score,\n n_docs=n_docs,\n )\n\n return RetrievAugLMMarginOutput(\n loss=loss,\n logits=outputs.logits,\n doc_scores=outputs.doc_scores,\n past_key_values=outputs.past_key_values,\n context_input_ids=outputs.context_input_ids,\n context_attention_mask=outputs.context_attention_mask,\n retrieved_doc_embeds=outputs.retrieved_doc_embeds,\n retrieved_doc_ids=outputs.retrieved_doc_ids,\n question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,\n question_enc_hidden_states=outputs.question_enc_hidden_states,\n question_enc_attentions=outputs.question_enc_attentions,\n generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,\n generator_enc_hidden_states=outputs.generator_enc_hidden_states,\n generator_enc_attentions=outputs.generator_enc_attentions,\n generator_dec_hidden_states=outputs.generator_dec_hidden_states,\n generator_dec_attentions=outputs.generator_dec_attentions,\n generator_cross_attentions=outputs.generator_cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n pre_norm=False,\n layerdrop=0.0,\n vocab_size=30145,\n emb_dim=2048,\n n_layers=12,\n n_heads=16,\n dropout=0.1,\n attention_dropout=0.1,\n gelu_activation=True,\n sinusoidal_embeddings=False,\n causal=False,\n asm=False,\n n_langs=1,\n use_lang_emb=True,\n max_position_embeddings=512,\n embed_init_std=2048**-0.5,\n layer_norm_eps=1e-12,\n init_std=0.02,\n bos_index=0,\n eos_index=1,\n pad_index=2,\n unk_index=3,\n mask_index=5,\n is_encoder=True,\n summary_type=\"first\",\n summary_use_proj=True,\n summary_activation=None,\n summary_proj_to_labels=True,\n summary_first_dropout=0.1,\n start_n_top=5,\n end_n_top=5,\n mask_token_id=0,\n lang_id=0,\n pad_token_id=2,\n bos_token_id=0,\n **kwargs,\n ):\n \"\"\"Constructs FlaubertConfig.\"\"\"\n self.pre_norm = pre_norm\n self.layerdrop = layerdrop\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.n_layers = n_layers\n self.n_heads = n_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.gelu_activation = gelu_activation\n self.sinusoidal_embeddings = sinusoidal_embeddings\n self.causal = causal\n self.asm = asm\n self.n_langs = n_langs\n self.use_lang_emb = use_lang_emb\n self.layer_norm_eps = layer_norm_eps\n self.bos_index = bos_index\n self.eos_index = eos_index\n self.pad_index = pad_index\n self.unk_index = unk_index\n self.mask_index = mask_index\n self.is_encoder = is_encoder\n self.max_position_embeddings = max_position_embeddings\n self.embed_init_std = embed_init_std\n self.init_std = init_std\n self.summary_type = summary_type\n self.summary_use_proj = summary_use_proj\n self.summary_activation = summary_activation\n self.summary_proj_to_labels = summary_proj_to_labels\n self.summary_first_dropout = summary_first_dropout\n self.start_n_top = start_n_top\n self.end_n_top = end_n_top\n self.mask_token_id = mask_token_id\n self.lang_id = lang_id\n\n if \"n_words\" in kwargs:\n self.n_words = kwargs[\"n_words\"]\n\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n embed_dim=96,\n image_size=[224, 224],\n patch_size=[7, 7],\n patch_stride=[4, 4],\n patch_padding=[3, 3],\n mlp_ratio=4.0,\n depths=[2, 3, 16, 3],\n num_heads=[1, 2, 4, 8],\n embed_dim_multiplier=2.0,\n num_query_pool=3,\n query_stride=[2, 2],\n masked_unit_size=[8, 8],\n masked_unit_attention=[True, True, False, False],\n drop_path_rate=0.0,\n num_channels=3,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n layer_norm_init=1.0,\n layer_norm_eps=1e-6,\n decoder_hidden_size=None,\n decoder_depth=None,\n decoder_num_heads=None,\n normalize_pixel_loss=True,\n mask_ratio=0.6,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if masked_unit_size[0] % query_stride[0] ** (len(depths) - 1) != 0:\n raise ValueError(\n f\"masked_unit_size[0] ({masked_unit_size[0]}) must be divisible by query_stride[0] ({query_stride[0]}) \"\n f\"raised to the power of the number of layers ({len(depths) - 1})\"\n )\n\n if num_query_pool >= len(depths):\n raise ValueError(\n f\"num_query_pool ({num_query_pool}) must be less than the number of layers ({len(depths)})\"\n )\n\n self.embed_dim = embed_dim\n self.image_size = image_size\n self.patch_size = patch_size\n self.patch_stride = patch_stride\n self.patch_padding = patch_padding\n self.mlp_ratio = mlp_ratio\n self.depths = depths\n self.num_heads = num_heads\n self.num_layers = len(depths)\n self.embed_dim_multiplier = embed_dim_multiplier\n self.num_query_pool = num_query_pool\n self.query_stride = query_stride\n self.masked_unit_size = masked_unit_size\n self.masked_unit_attention = masked_unit_attention\n self.drop_path_rate = drop_path_rate\n self.num_channels = num_channels\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.layer_norm_init = layer_norm_init\n self.layer_norm_eps = layer_norm_eps\n self.decoder_hidden_size = decoder_hidden_size\n self.decoder_depth = decoder_depth\n self.decoder_num_heads = decoder_num_heads\n self.normalize_pixel_loss = normalize_pixel_loss\n self.mask_ratio = mask_ratio\n # we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel\n # this indicates the channel dimension after the last stage of the model\n self.hidden_size = int(embed_dim * embed_dim_multiplier ** (len(depths) - 1))\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=250880,\n hidden_size=64,\n n_layer=2,\n n_head=8,\n layer_norm_epsilon=1e-5,\n initializer_range=0.02,\n use_cache=True,\n bos_token_id=1,\n eos_token_id=2,\n apply_residual_connection_post_layernorm=False,\n hidden_dropout=0.0,\n attention_dropout=0.0,\n pretraining_tp=1, # TP rank used when training with megatron\n slow_but_exact=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n # Backward compatibility with n_embed kwarg\n n_embed = kwargs.pop(\"n_embed\", None)\n self.hidden_size = hidden_size if n_embed is None else n_embed\n self.n_layer = n_layer\n self.n_head = n_head\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.use_cache = use_cache\n self.pretraining_tp = pretraining_tp\n self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n self.slow_but_exact = slow_but_exact\n\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqQuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n # Copied from transformers.models.bart.modeling_bart.BartForQuestionAnswering.forward\n def forward(\n self,\n input_ids: torch.Tensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n start_positions: Optional[torch.LongTensor] = None,\n end_positions: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqQuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if start_positions is not None and end_positions is not None:\n use_cache = False\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (\n start_logits,\n end_logits,\n ) + outputs[1:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return Seq2SeqQuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3,\n image_size=32,\n num_channels=3,\n embeddings_size=10,\n hidden_sizes=[8, 16, 32, 64],\n depths=[1, 1, 2, 1],\n is_training=True,\n use_labels=True,\n hidden_act=\"relu\",\n num_labels=3,\n scope=None,\n out_features=[\"stage2\", \"stage3\", \"stage4\"],\n out_indices=[2, 3, 4],\n num_groups=1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.embeddings_size = embeddings_size\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_act = hidden_act\n self.num_labels = num_labels\n self.scope = scope\n self.num_stages = len(hidden_sizes)\n self.out_features = out_features\n self.out_indices = out_indices\n self.num_groups = num_groups", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_validator( # noqa: PLR0913\n self,\n datasource_name: Optional[str] = None,\n data_connector_name: Optional[str] = None,\n data_asset_name: Optional[str] = None,\n batch: Optional[Batch] = None,\n batch_list: Optional[List[Batch]] = None,\n batch_request: Optional[Union[BatchRequestBase, FluentBatchRequest]] = None,\n batch_request_list: Optional[List[BatchRequestBase]] = None,\n batch_data: Optional[Any] = None,\n data_connector_query: Optional[Union[IDDict, dict]] = None,\n batch_identifiers: Optional[dict] = None,\n limit: Optional[int] = None,\n index: Optional[Union[int, list, tuple, slice, str]] = None,\n custom_filter_function: Optional[Callable] = None,\n sampling_method: Optional[str] = None,\n sampling_kwargs: Optional[dict] = None,\n partitioner_method: Optional[str] = None,\n partitioner_kwargs: Optional[dict] = None,\n runtime_parameters: Optional[dict] = None,\n query: Optional[str] = None,\n path: Optional[str] = None,\n batch_filter_parameters: Optional[dict] = None,\n batch_spec_passthrough: Optional[dict] = None,\n expectation_suite_id: Optional[str] = None,\n expectation_suite_name: Optional[str] = None,\n expectation_suite: Optional[ExpectationSuite] = None,\n create_expectation_suite_with_name: Optional[str] = None,\n **kwargs,\n ) -> Validator:\n \"\"\"Retrieve a Validator with a batch list and an `ExpectationSuite`.\n\n `get_validator` first calls `get_batch_list` to retrieve a batch list, then creates or retrieves\n an `ExpectationSuite` used to validate the Batches in the list.\n\n Args:\n datasource_name: The name of the Datasource that defines the Data Asset to retrieve the batch for\n data_connector_name: The Data Connector within the datasource for the Data Asset\n data_asset_name: The name of the Data Asset within the Data Connector\n batch: The Batch to use with the Validator\n batch_list: The List of Batches to use with the Validator\n batch_request: Encapsulates all the parameters used here to retrieve a BatchList. Use either\n `batch_request` or the other params (but not both)\n batch_request_list: A List of `BatchRequest` to use with the Validator\n batch_data: Provides runtime data for the batch; is added as the key `batch_data` to\n the `runtime_parameters` dictionary of a BatchRequest\n query: Provides runtime data for the batch; is added as the key `query` to\n the `runtime_parameters` dictionary of a BatchRequest\n path: Provides runtime data for the batch; is added as the key `path` to\n the `runtime_parameters` dictionary of a BatchRequest\n runtime_parameters: Specifies runtime parameters for the BatchRequest; can includes keys `batch_data`,\n `query`, and `path`\n data_connector_query: Used to specify connector query parameters; specifically `batch_filter_parameters`,\n `limit`, `index`, and `custom_filter_function`\n batch_identifiers: Any identifiers of batches for the BatchRequest\n batch_filter_parameters: Filter parameters used in the data connector query\n limit: Part of the data_connector_query, limits the number of batches in the batch list\n index: Part of the data_connector_query, used to specify the index of which batch to return. Negative\n numbers retrieve from the end of the list (ex: `-1` retrieves the last or latest batch)\n custom_filter_function: A `Callable` function that accepts `batch_identifiers` and returns a `bool`\n sampling_method: The method used to sample Batch data (see: Partitioning and Sampling)\n sampling_kwargs: Arguments for the sampling method\n partitioner_method: The method used to partition the Data Asset into Batches\n partitioner_kwargs: Arguments for the partitioning method\n batch_spec_passthrough: Arguments specific to the `ExecutionEngine` that aid in Batch retrieval\n expectation_suite_id: The identifier of the ExpectationSuite to retrieve from the DataContext\n (can be used in place of `expectation_suite_name`)\n expectation_suite_name: The name of the ExpectationSuite to retrieve from the DataContext\n expectation_suite: The ExpectationSuite to use with the validator\n create_expectation_suite_with_name: Creates a Validator with a new ExpectationSuite with the provided name\n **kwargs: Used to specify either `batch_identifiers` or `batch_filter_parameters`\n\n Returns:\n Validator: A Validator with the specified Batch list and ExpectationSuite\n\n Raises:\n DatasourceError: If the specified `datasource_name` does not exist in the DataContext\n TypeError: If the specified types of the `batch_request` are not supported, or if the\n `datasource_name` is not a `str`\n ValueError: If more than one exclusive parameter is specified (ex: specifing more than one\n of `batch_data`, `query` or `path`), or if the `ExpectationSuite` cannot be created or\n retrieved using either the provided name or identifier\n \"\"\" # noqa: E501\n expectation_suite = self._get_expectation_suite_from_inputs(\n expectation_suite=expectation_suite,\n expectation_suite_name=expectation_suite_name,\n create_expectation_suite_with_name=create_expectation_suite_with_name,\n expectation_suite_id=expectation_suite_id,\n )\n batch_list = self._get_batch_list_from_inputs(\n datasource_name=datasource_name,\n data_connector_name=data_connector_name,\n data_asset_name=data_asset_name,\n batch=batch,\n batch_list=batch_list,\n batch_request=batch_request,\n batch_request_list=batch_request_list,\n batch_data=batch_data,\n data_connector_query=data_connector_query,\n batch_identifiers=batch_identifiers,\n limit=limit,\n index=index,\n custom_filter_function=custom_filter_function,\n sampling_method=sampling_method,\n sampling_kwargs=sampling_kwargs,\n partitioner_method=partitioner_method,\n partitioner_kwargs=partitioner_kwargs,\n runtime_parameters=runtime_parameters,\n query=query,\n path=path,\n batch_filter_parameters=batch_filter_parameters,\n batch_spec_passthrough=batch_spec_passthrough,\n **kwargs,\n )\n return self.get_validator_using_batch_list(\n expectation_suite=expectation_suite,\n batch_list=batch_list,\n )", "smellKey": "S107", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFCausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: Optional[bool] = False,\n ) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have\n their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past`). Set to `False` during training, `True` during generation\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,\n config.vocab_size - 1]`.\n \"\"\"\n\n transformer_outputs = self.transformer(\n input_ids=input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n hidden_states = transformer_outputs[0]\n logits = tf.matmul(hidden_states, self.transformer.wte.weights, transpose_b=True)\n\n loss = None\n if labels is not None:\n # shift labels to the left and cut last logit token\n shifted_logits = logits[:, :-1]\n labels = labels[:, 1:]\n loss = self.hf_compute_loss(labels, shifted_logits)\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFCausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n cross_attentions=transformer_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_convert_rgb: Optional[bool] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_image_splitting: Optional[bool] = None,\n do_rescale: Optional[bool] = None,\n max_image_size: Optional[Dict[str, int]] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_row_col_info: bool = False,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ):\n \"\"\"\n Preprocess a batch of images.\n Args:\n images (`ImageInput`):\n A list of images to preprocess.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after resizing. With the longest edge resized to keep the input aspect ratio.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):\n Whether to split the image into sub-images concatenated with the original image. They are split into patches\n such that each patch has a size of `max_image_size[\"height\"]` x `max_image_size[\"width\"]`.\n max_image_size (`Dict`, *optional*, defaults to `self.max_image_size`):\n Maximum resolution of the images. If the image is larger than this size, the image is split into patches.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether or not to pad the images to the largest height and width in the batch.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n return_row_col_info (`bool`, *optional*, default to `False`):\n Whether to return the number of rows and columns of the split images. This is used for the\n `Idefics3Processor` to generate prompt strings based on the number of rows and columns.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_image_splitting = do_image_splitting if do_image_splitting is not None else self.do_image_splitting\n max_image_size = max_image_size if max_image_size is not None else self.max_image_size\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n do_pad = do_pad if do_pad is not None else self.do_pad\n\n images_list = make_list_of_images(images)\n\n if not valid_images(images_list[0]):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n # save the palettes for conversion to RGB\n palettes_list = [\n [im.getpalette() if isinstance(im, Image.Image) and im.mode == \"P\" else None for im in images]\n for images in images_list\n ]\n\n # All transformations expect numpy arrays.\n images_list = [[to_numpy_array(image) for image in images] for images in images_list]\n\n if is_scaled_image(images_list[0][0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n # We assume that all images have the same channel dimension format.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(images_list[0][0], num_channels=(1, 3, 4))\n\n # Extra channel dimension for grayscale images\n if input_data_format == ChannelDimension.LAST:\n images_list = [\n [np.expand_dims(img, axis=-1) if img.ndim == 2 else img for img in images] for images in images_list\n ]\n elif input_data_format == ChannelDimension.FIRST:\n images_list = [\n [np.expand_dims(img, axis=0) if img.ndim == 2 else img for img in images] for images in images_list\n ]\n else:\n raise ValueError(f\"Invalid channel dimension format {input_data_format}.\")\n\n if do_resize:\n images_list = [\n [\n self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n if do_image_splitting:\n # We first resize both height and width of each image to the nearest max_image_size multiple, disregarding the aspect ratio\n # for size=(10, max_image_size) -> rescaled_size=(max_image_size, max_image_size)\n # for size=(11, max_image_size+1) -> rescaled_size=(max_image_size, max_image_size*2)\n images_list = [\n [\n self.resize_for_vision_encoder(\n image, max_image_size[\"longest_edge\"], resample=resample, input_data_format=input_data_format\n )\n for image in images\n ]\n for images in images_list\n ]\n images_list_split_arrays = []\n palettes_list_split_arrays = []\n images_list_rows = []\n images_list_cols = []\n for images, palettes in zip(images_list, palettes_list):\n split_image_arrays = []\n split_palettes_arrays = []\n image_rows = []\n image_cols = []\n for image, palette in zip(images, palettes):\n split_image_array, rows, cols = self.split_image(\n image,\n max_image_size=max_image_size,\n input_data_format=input_data_format,\n )\n split_image_arrays.extend(split_image_array)\n split_palettes_arrays.extend([palette] * len(split_image_array))\n image_rows.append(rows)\n image_cols.append(cols)\n images_list_split_arrays.append(split_image_arrays)\n palettes_list_split_arrays.append(split_palettes_arrays)\n images_list_rows.append(image_rows)\n images_list_cols.append(image_cols)\n images_list = images_list_split_arrays\n palettes_list = palettes_list_split_arrays\n else:\n # We square the images to max_image_size\n images_list = [\n [\n self.resize(\n image=image,\n size={\"height\": max_image_size[\"longest_edge\"], \"width\": max_image_size[\"longest_edge\"]},\n resample=resample,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n for images in images_list\n ]\n images_list_rows = [[0] * len(images) for images in images_list]\n images_list_cols = [[0] * len(images) for images in images_list]\n\n if do_convert_rgb:\n images_list = [\n [convert_to_rgb(img, palette) for img, palette in zip(images, palettes)]\n for images, palettes in zip(images_list, palettes_list)\n ]\n\n if do_rescale:\n images_list = [\n [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]\n for images in images_list\n ]\n\n if do_normalize:\n images_list = [\n [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n pixel_attention_mask = None\n if do_pad:\n images_list, pixel_attention_mask = self.pad(\n images_list, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=input_data_format\n )\n\n if data_format is not None:\n images_list = [\n [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n # Faster tensor conversion\n data = {\"pixel_values\": np.array(images_list) if do_pad and return_tensors is not None else images_list}\n if pixel_attention_mask is not None:\n data[\"pixel_attention_mask\"] = (\n np.array(pixel_attention_mask) if do_pad and return_tensors is not None else pixel_attention_mask\n )\n\n encoding = BatchFeature(data=data, tensor_type=return_tensors)\n\n # This is needed for generating correct text inputs in the processor - we don't pad to the max number of images\n if return_row_col_info:\n encoding[\"rows\"] = images_list_rows\n encoding[\"cols\"] = images_list_cols\n\n return encoding", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _preprocess_image(\n self,\n image: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n offset: bool = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> np.ndarray:\n \"\"\"Preprocesses a single image.\"\"\"\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if offset and not do_rescale:\n raise ValueError(\"For offset, do_rescale must also be set to True.\")\n\n # All transformations expect numpy arrays.\n image = to_numpy_array(image)\n\n if is_scaled_image(image) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n\n if do_resize:\n image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n\n if do_center_crop:\n image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)\n\n if do_rescale:\n image = self.rescale(image=image, scale=rescale_factor, offset=offset, input_data_format=input_data_format)\n\n if do_normalize:\n image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def add_item(\n self,\n title,\n link,\n description,\n author_email=None,\n author_name=None,\n author_link=None,\n pubdate=None,\n comments=None,\n unique_id=None,\n unique_id_is_permalink=None,\n categories=(),\n item_copyright=None,\n ttl=None,\n updateddate=None,\n enclosures=None,\n **kwargs,\n ):\n \"\"\"\n Add an item to the feed. All args are expected to be strings except\n pubdate and updateddate, which are datetime.datetime objects, and\n enclosures, which is an iterable of instances of the Enclosure class.\n \"\"\"\n\n def to_str(s):\n return str(s) if s is not None else s\n\n categories = categories and [to_str(c) for c in categories]\n self.items.append(\n {\n \"title\": to_str(title),\n \"link\": iri_to_uri(link),\n \"description\": to_str(description),\n \"author_email\": to_str(author_email),\n \"author_name\": to_str(author_name),\n \"author_link\": iri_to_uri(author_link),\n \"pubdate\": pubdate,\n \"updateddate\": updateddate,\n \"comments\": to_str(comments),\n \"unique_id\": to_str(unique_id),\n \"unique_id_is_permalink\": unique_id_is_permalink,\n \"enclosures\": enclosures or (),\n \"categories\": categories or (),\n \"item_copyright\": to_str(item_copyright),\n \"ttl\": to_str(ttl),\n **kwargs,\n }\n )", "smellKey": "S107", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=1024,\n num_hidden_layers=24,\n num_attention_heads=16,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-6,\n image_size=[896, 448],\n patch_size=16,\n num_channels=3,\n qkv_bias=True,\n mlp_dim=None,\n drop_path_rate=0.1,\n pretrain_image_size=224,\n decoder_hidden_size=64,\n use_relative_position_embeddings=True,\n merge_index=2,\n intermediate_hidden_state_indices=[5, 11, 17, 23],\n beta=0.01,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n if merge_index > min(intermediate_hidden_state_indices):\n raise ValueError(\n f\"Merge index must be less than the minimum encoder output index, but got {merge_index=} and {intermediate_hidden_state_indices=}\"\n )\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.drop_path_rate = drop_path_rate\n self.pretrain_image_size = pretrain_image_size\n self.decoder_hidden_size = decoder_hidden_size\n self.use_relative_position_embeddings = use_relative_position_embeddings\n self.merge_index = merge_index\n self.intermediate_hidden_state_indices = intermediate_hidden_state_indices\n self.beta = beta\n self.mlp_dim = int(hidden_size * 4) if mlp_dim is None else mlp_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n image_grid_pinpoints: List = None,\n resample: PILImageResampling = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n do_convert_rgb: bool = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ):\n \"\"\"\n Args:\n images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):\n The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch\n tensor. Both channels-first and channels-last formats are supported.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after resizing. Shortest edge of the image is resized to size[\"shortest_edge\"], with\n the longest edge resized to keep the input aspect ratio.\n image_grid_pinpoints (`List` *optional*, defaults to `self.image_grid_pinpoints`):\n A list of possible resolutions to use for processing high resolution images. The best resolution is\n selected based on the original size of the image.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest\n number of patches in the batch. Padding will be applied to the bottom and right with zeros.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n image_grid_pinpoints = image_grid_pinpoints if image_grid_pinpoints is not None else self.image_grid_pinpoints\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_pad = do_pad if do_pad is not None else self.do_pad\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n\n images = make_batched_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if do_convert_rgb:\n images = [convert_to_rgb(image) for image in images]\n\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n new_images = []\n image_sizes = [get_image_size(image, channel_dim=input_data_format) for image in images]\n for image in images:\n # convert image into a list of patches\n # we intentially use the same data format as the input data format\n size_tuple = (\n (size[\"height\"], size[\"width\"])\n if \"height\" in size and \"width\" in size\n else (size[\"shortest_edge\"], size[\"shortest_edge\"])\n )\n image_patches = self.get_image_patches(\n image,\n image_grid_pinpoints,\n size=size_tuple,\n patch_size=size[\"height\"],\n resample=resample,\n data_format=input_data_format,\n input_data_format=input_data_format,\n )\n\n # preprocess patches\n pixel_values = self._preprocess(\n image_patches,\n do_resize=do_resize,\n size=size_tuple,\n resample=resample,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n pixel_values = np.array(pixel_values)\n new_images.append(pixel_values)\n\n if do_pad:\n processed_images = self._pad_for_batching(new_images)\n\n return BatchFeature(\n data={\"pixel_values\": processed_images, \"image_sizes\": image_sizes}, tensor_type=return_tensors\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def command(self, dbname, spec, slave_ok=False,\n read_preference=ReadPreference.PRIMARY,\n codec_options=DEFAULT_CODEC_OPTIONS, check=True,\n allowable_errors=None, check_keys=False,\n read_concern=None,\n write_concern=None,\n parse_write_concern_error=False,\n collation=None,\n session=None,\n client=None,\n retryable_write=False,\n publish_events=True,\n user_fields=None):\n \"\"\"Execute a command or raise an error.\n\n :Parameters:\n - `dbname`: name of the database on which to run the command\n - `spec`: a command document as a dict, SON, or mapping object\n - `slave_ok`: whether to set the SlaveOkay wire protocol bit\n - `read_preference`: a read preference\n - `codec_options`: a CodecOptions instance\n - `check`: raise OperationFailure if there are errors\n - `allowable_errors`: errors to ignore if `check` is True\n - `check_keys`: if True, check `spec` for invalid keys\n - `read_concern`: The read concern for this command.\n - `write_concern`: The write concern for this command.\n - `parse_write_concern_error`: Whether to parse the\n ``writeConcernError`` field in the command response.\n - `collation`: The collation for this command.\n - `session`: optional ClientSession instance.\n - `client`: optional MongoClient for gossipping $clusterTime.\n - `retryable_write`: True if this command is a retryable write.\n - `publish_events`: Should we publish events for this command?\n - `user_fields` (optional): Response fields that should be decoded\n using the TypeDecoders from codec_options, passed to\n bson._decode_all_selective.\n \"\"\"\n self.validate_session(client, session)\n session = _validate_session_write_concern(session, write_concern)\n\n # Ensure command name remains in first place.\n if not isinstance(spec, ORDERED_TYPES):\n spec = SON(spec)\n\n if (read_concern and self.max_wire_version < 4\n and not read_concern.ok_for_legacy):\n raise ConfigurationError(\n 'read concern level of %s is not valid '\n 'with a max wire version of %d.'\n % (read_concern.level, self.max_wire_version))\n if not (write_concern is None or write_concern.acknowledged or\n collation is None):\n raise ConfigurationError(\n 'Collation is unsupported for unacknowledged writes.')\n if (self.max_wire_version >= 5 and\n write_concern and\n not write_concern.is_server_default):\n spec['writeConcern'] = write_concern.document\n elif self.max_wire_version < 5 and collation is not None:\n raise ConfigurationError(\n 'Must be connected to MongoDB 3.4+ to use a collation.')\n\n if session:\n session._apply_to(spec, retryable_write, read_preference)\n self.send_cluster_time(spec, session, client)\n listeners = self.listeners if publish_events else None\n unacknowledged = write_concern and not write_concern.acknowledged\n if self.op_msg_enabled:\n self._raise_if_not_writable(unacknowledged)\n try:\n return command(self.sock, dbname, spec, slave_ok,\n self.is_mongos, read_preference, codec_options,\n session, client, check, allowable_errors,\n self.address, check_keys, listeners,\n self.max_bson_size, read_concern,\n parse_write_concern_error=parse_write_concern_error,\n collation=collation,\n compression_ctx=self.compression_context,\n use_op_msg=self.op_msg_enabled,\n unacknowledged=unacknowledged,\n user_fields=user_fields)\n except OperationFailure:\n raise\n # Catch socket.error, KeyboardInterrupt, etc. and close ourselves.\n except BaseException as error:\n self._raise_connection_failure(error)", "smellKey": "S107", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(PROPHETNET_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=ProphetNetSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.Tensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, ProphetNetSeq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, ProphetNetModel\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"microsoft/prophetnet-large-uncased\")\n >>> model = ProphetNetModel.from_pretrained(\"microsoft/prophetnet-large-uncased\")\n\n >>> input_ids = tokenizer(\n ... \"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> decoder_input_ids = tokenizer(\"Studies show that\", return_tensors=\"pt\").input_ids # Batch size 1\n >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)\n\n >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states\n >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n use_cache=use_cache,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n return ProphetNetSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n last_hidden_state_ngram=decoder_outputs.last_hidden_state_ngram,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_ngram_hidden_states=decoder_outputs.hidden_states_ngram,\n decoder_attentions=decoder_outputs.attentions,\n decoder_ngram_attentions=decoder_outputs.ngram_attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n d_model=1024,\n n_layer=24,\n n_head=16,\n d_inner=4096,\n ff_activation=\"gelu\",\n untie_r=True,\n attn_type=\"bi\",\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n dropout=0.1,\n mem_len=512,\n reuse_len=None,\n use_mems_eval=True,\n use_mems_train=False,\n bi_data=False,\n clamp_len=-1,\n same_length=False,\n summary_type=\"last\",\n summary_use_proj=True,\n summary_activation=\"tanh\",\n summary_last_dropout=0.1,\n start_n_top=5,\n end_n_top=5,\n pad_token_id=5,\n bos_token_id=1,\n eos_token_id=2,\n **kwargs,\n ):\n \"\"\"Constructs XLNetConfig.\"\"\"\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.n_layer = n_layer\n self.n_head = n_head\n if d_model % n_head != 0:\n raise ValueError(f\"'d_model % n_head' ({d_model % n_head}) should be equal to 0\")\n if \"d_head\" in kwargs:\n if kwargs[\"d_head\"] != d_model // n_head:\n raise ValueError(\n f\"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})\"\n )\n self.d_head = d_model // n_head\n self.ff_activation = ff_activation\n self.d_inner = d_inner\n self.untie_r = untie_r\n self.attn_type = attn_type\n\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n\n self.dropout = dropout\n self.mem_len = mem_len\n self.reuse_len = reuse_len\n self.bi_data = bi_data\n self.clamp_len = clamp_len\n self.same_length = same_length\n\n self.summary_type = summary_type\n self.summary_use_proj = summary_use_proj\n self.summary_activation = summary_activation\n self.summary_last_dropout = summary_last_dropout\n self.start_n_top = start_n_top\n self.end_n_top = end_n_top\n\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.eos_token_id = eos_token_id\n\n if \"use_cache\" in kwargs:\n warnings.warn(\n \"The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`\"\n \" instead.\",\n FutureWarning,\n )\n use_mems_eval = kwargs[\"use_cache\"]\n\n self.use_mems_eval = use_mems_eval\n self.use_mems_train = use_mems_train\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n d_model=16,\n decoder_seq_length=7,\n is_training=True,\n is_decoder=True,\n use_attention_mask=True,\n use_cache=False,\n use_labels=True,\n decoder_start_token_id=2,\n decoder_ffn_dim=32,\n decoder_layers=2,\n encoder_attention_heads=4,\n decoder_attention_heads=4,\n max_position_embeddings=30,\n is_encoder_decoder=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.hidden_size = d_model\n self.num_hidden_layers = decoder_layers\n self.decoder_layers = decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_attention_heads = decoder_attention_heads\n self.num_attention_heads = decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.use_cache = use_cache\n self.max_position_embeddings = max_position_embeddings\n self.is_encoder_decoder = is_encoder_decoder\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 2\n self.decoder_attention_idx = 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n vocab_size=102,\n type_vocab_size=2,\n max_position_embeddings=512,\n position_embedding_type=\"absolute\",\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n qkv_bias=True,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.seq_length = seq_length\n self.vocab_size = vocab_size\n self.type_vocab_size = type_vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.position_embedding_type = position_embedding_type\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.qkv_bias = qkv_bias\n self.pad_token_id = pad_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_channels=3,\n embedding_size=64,\n hidden_sizes=[256, 512, 1024, 2048],\n depths=[3, 4, 6, 3],\n layer_type=\"preactivation\",\n hidden_act=\"relu\",\n global_padding=None,\n num_groups=32,\n drop_path_rate=0.0,\n embedding_dynamic_padding=False,\n output_stride=32,\n width_factor=1,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if layer_type not in self.layer_types:\n raise ValueError(f\"layer_type={layer_type} is not one of {','.join(self.layer_types)}\")\n if global_padding is not None:\n if global_padding.upper() in self.supported_padding:\n global_padding = global_padding.upper()\n else:\n raise ValueError(f\"Padding strategy {global_padding} not supported\")\n self.num_channels = num_channels\n self.embedding_size = embedding_size\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.layer_type = layer_type\n self.hidden_act = hidden_act\n self.global_padding = global_padding\n self.num_groups = num_groups\n self.drop_path_rate = drop_path_rate\n self.embedding_dynamic_padding = embedding_dynamic_padding\n self.output_stride = output_stride\n self.width_factor = width_factor\n\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def xfr(\n where: str,\n zone: Union[dns.name.Name, str],\n rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.AXFR,\n rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,\n timeout: Optional[float] = None,\n port: int = 53,\n keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,\n keyname: Optional[Union[dns.name.Name, str]] = None,\n relativize: bool = True,\n lifetime: Optional[float] = None,\n source: Optional[str] = None,\n source_port: int = 0,\n serial: int = 0,\n use_udp: bool = False,\n keyalgorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,\n) -> Any:\n \"\"\"Return a generator for the responses to a zone transfer.\n\n *where*, a ``str`` containing an IPv4 or IPv6 address, where\n to send the message.\n\n *zone*, a ``dns.name.Name`` or ``str``, the name of the zone to transfer.\n\n *rdtype*, an ``int`` or ``str``, the type of zone transfer. The\n default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be\n used to do an incremental transfer instead.\n\n *rdclass*, an ``int`` or ``str``, the class of the zone transfer.\n The default is ``dns.rdataclass.IN``.\n\n *timeout*, a ``float``, the number of seconds to wait for each\n response message. If None, the default, wait forever.\n\n *port*, an ``int``, the port send the message to. The default is 53.\n\n *keyring*, a ``dict``, the keyring to use for TSIG.\n\n *keyname*, a ``dns.name.Name`` or ``str``, the name of the TSIG\n key to use.\n\n *relativize*, a ``bool``. If ``True``, all names in the zone will be\n relativized to the zone origin. It is essential that the\n relativize setting matches the one specified to\n ``dns.zone.from_xfr()`` if using this generator to make a zone.\n\n *lifetime*, a ``float``, the total number of seconds to spend\n doing the transfer. If ``None``, the default, then there is no\n limit on the time the transfer may take.\n\n *source*, a ``str`` containing an IPv4 or IPv6 address, specifying\n the source address. The default is the wildcard address.\n\n *source_port*, an ``int``, the port from which to send the message.\n The default is 0.\n\n *serial*, an ``int``, the SOA serial number to use as the base for\n an IXFR diff sequence (only meaningful if *rdtype* is\n ``dns.rdatatype.IXFR``).\n\n *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR).\n\n *keyalgorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use.\n\n Raises on errors, and so does the generator.\n\n Returns a generator of ``dns.message.Message`` objects.\n \"\"\"\n\n if isinstance(zone, str):\n zone = dns.name.from_text(zone)\n rdtype = dns.rdatatype.RdataType.make(rdtype)\n q = dns.message.make_query(zone, rdtype, rdclass)\n if rdtype == dns.rdatatype.IXFR:\n rrset = dns.rrset.from_text(zone, 0, \"IN\", \"SOA\", \". . %u 0 0 0 0\" % serial)\n q.authority.append(rrset)\n if keyring is not None:\n q.use_tsig(keyring, keyname, algorithm=keyalgorithm)\n wire = q.to_wire()\n (af, destination, source) = _destination_and_source(\n where, port, source, source_port\n )\n if use_udp and rdtype != dns.rdatatype.IXFR:\n raise ValueError(\"cannot do a UDP AXFR\")\n sock_type = socket.SOCK_DGRAM if use_udp else socket.SOCK_STREAM\n with _make_socket(af, sock_type, source) as s:\n (_, expiration) = _compute_times(lifetime)\n _connect(s, destination, expiration)\n l = len(wire)\n if use_udp:\n _udp_send(s, wire, None, expiration)\n else:\n tcpmsg = struct.pack(\"!H\", l) + wire\n _net_write(s, tcpmsg, expiration)\n done = False\n delete_mode = True\n expecting_SOA = False\n soa_rrset = None\n if relativize:\n origin = zone\n oname = dns.name.empty\n else:\n origin = None\n oname = zone\n tsig_ctx = None\n while not done:\n (_, mexpiration) = _compute_times(timeout)\n if mexpiration is None or (\n expiration is not None and mexpiration > expiration\n ):\n mexpiration = expiration\n if use_udp:\n (wire, _) = _udp_recv(s, 65535, mexpiration)\n else:\n ldata = _net_read(s, 2, mexpiration)\n (l,) = struct.unpack(\"!H\", ldata)\n wire = _net_read(s, l, mexpiration)\n is_ixfr = rdtype == dns.rdatatype.IXFR\n r = dns.message.from_wire(\n wire,\n keyring=q.keyring,\n request_mac=q.mac,\n xfr=True,\n origin=origin,\n tsig_ctx=tsig_ctx,\n multi=True,\n one_rr_per_rrset=is_ixfr,\n )\n rcode = r.rcode()\n if rcode != dns.rcode.NOERROR:\n raise TransferError(rcode)\n tsig_ctx = r.tsig_ctx\n answer_index = 0\n if soa_rrset is None:\n if not r.answer or r.answer[0].name != oname:\n raise dns.exception.FormError(\"No answer or RRset not for qname\")\n rrset = r.answer[0]\n if rrset.rdtype != dns.rdatatype.SOA:\n raise dns.exception.FormError(\"first RRset is not an SOA\")\n answer_index = 1\n soa_rrset = rrset.copy()\n if rdtype == dns.rdatatype.IXFR:\n if dns.serial.Serial(soa_rrset[0].serial) <= serial:\n #\n # We're already up-to-date.\n #\n done = True\n else:\n expecting_SOA = True\n #\n # Process SOAs in the answer section (other than the initial\n # SOA in the first message).\n #\n for rrset in r.answer[answer_index:]:\n if done:\n raise dns.exception.FormError(\"answers after final SOA\")\n if rrset.rdtype == dns.rdatatype.SOA and rrset.name == oname:\n if expecting_SOA:\n if rrset[0].serial != serial:\n raise dns.exception.FormError(\"IXFR base serial mismatch\")\n expecting_SOA = False\n elif rdtype == dns.rdatatype.IXFR:\n delete_mode = not delete_mode\n #\n # If this SOA RRset is equal to the first we saw then we're\n # finished. If this is an IXFR we also check that we're\n # seeing the record in the expected part of the response.\n #\n if rrset == soa_rrset and (\n rdtype == dns.rdatatype.AXFR\n or (rdtype == dns.rdatatype.IXFR and delete_mode)\n ):\n done = True\n elif expecting_SOA:\n #\n # We made an IXFR request and are expecting another\n # SOA RR, but saw something else, so this must be an\n # AXFR response.\n #\n rdtype = dns.rdatatype.AXFR\n expecting_SOA = False\n if done and q.keyring and not r.had_tsig:\n raise dns.exception.FormError(\"missing TSIG\")\n yield r", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def get_batch_request_from_acceptable_arguments( # noqa: PLR0913\n datasource_name: str | None = None,\n data_connector_name: str | None = None,\n data_asset_name: str | None = None,\n *,\n batch_request: BatchRequestBase | None = None,\n batch_data: Any | None = None,\n data_connector_query: dict | None = None,\n batch_identifiers: dict | None = None,\n limit: int | None = None,\n index: int | list | tuple | slice | str | None = None,\n custom_filter_function: Callable | None = None,\n batch_spec_passthrough: dict | None = None,\n sampling_method: str | None = None,\n sampling_kwargs: dict | None = None,\n partitioner_method: str | None = None,\n partitioner_kwargs: dict | None = None,\n runtime_parameters: dict | None = None,\n query: str | None = None,\n path: str | None = None,\n batch_filter_parameters: dict | None = None,\n batch_parameters: dict | BatchParameters | None = None,\n **kwargs,\n) -> BatchRequest | RuntimeBatchRequest | FluentBatchRequest:\n \"\"\"Obtain formal BatchRequest typed object from allowed attributes (supplied as arguments).\n This method applies only to the new (V3) Datasource schema.\n\n Args:\n datasource_name\n data_connector_name\n data_asset_name\n\n batch_request\n batch_data\n query\n path\n runtime_parameters\n data_connector_query\n batch_identifiers\n batch_filter_parameters\n\n limit\n index\n custom_filter_function\n\n sampling_method\n sampling_kwargs\n\n partitioner_method\n partitioner_kwargs\n\n batch_spec_passthrough\n\n batch_parameters\n\n **kwargs\n\n Returns:\n (BatchRequest, RuntimeBatchRequest or FluentBatchRequest) The formal BatchRequest, RuntimeBatchRequest or FluentBatchRequest object\n \"\"\" # noqa: E501\n\n # block-style batch-request args, includes arguments for both runtime and basic batch requests\n block_config_args = {\n \"batch_data\": batch_data,\n \"query\": query,\n \"path\": path,\n \"runtime_parameters\": runtime_parameters,\n \"data_connector_query\": data_connector_query,\n \"batch_identifiers\": batch_identifiers,\n \"batch_filter_parameters\": batch_filter_parameters,\n \"limit\": limit,\n \"index\": index,\n \"custom_filter_function\": custom_filter_function,\n \"sampling_method\": sampling_method,\n \"sampling_kwargs\": sampling_kwargs,\n \"partitioner_method\": partitioner_method,\n \"partitioner_kwargs\": partitioner_kwargs,\n \"batch_spec_passthrough\": batch_spec_passthrough,\n }\n\n def block_style_args() -> list[str]:\n \"\"\"Returns a list of the block-config batch request arguments\"\"\"\n return [k for k, v in block_config_args.items() if v]\n\n # ensure that the first parameter is datasource_name, which should be a str. This check prevents users # noqa: E501\n # from passing in batch_request as an unnamed parameter.\n if datasource_name and not isinstance(datasource_name, str):\n raise TypeError( # noqa: TRY003\n f\"the first parameter, datasource_name, must be a str, not {type(datasource_name)}\"\n )\n\n # if batch_request is specified, ignore all other arguments and return the batch_request\n if batch_request:\n if not isinstance(\n batch_request,\n (BatchRequest, RuntimeBatchRequest, _get_fluent_batch_request_class()),\n ):\n raise TypeError( # noqa: TRY003\n \"batch_request must be a BatchRequest, RuntimeBatchRequest, or a \"\n f\"fluent BatchRequest object, not {type(batch_request)}\"\n )\n\n return batch_request\n\n # try to get a runtime batch request\n result: RuntimeBatchRequest | FluentBatchRequest | None\n result = _get_runtime_batch_request(\n datasource_name=datasource_name, # type: ignore[arg-type] # could be None\n data_connector_name=data_connector_name, # type: ignore[arg-type] # could be None\n data_asset_name=data_asset_name, # type: ignore[arg-type] # could be None\n runtime_parameters=runtime_parameters,\n batch_identifiers=batch_identifiers,\n batch_spec_passthrough=batch_spec_passthrough,\n batch_data=batch_data,\n query=query,\n path=path,\n **kwargs,\n )\n if result:\n return result\n\n # try to get a fluent batch request\n if (datasource_name and data_asset_name) and not data_connector_name:\n block_args = block_style_args()\n if block_args:\n raise ValueError( # noqa: TRY003\n f\"Arguments: {', '.join(block_args)} are not supported for Fluent Batch Requests. Block-config Requests require a data connector name\" # noqa: E501\n )\n\n result = _get_fluent_batch_request_class()(\n datasource_name=datasource_name,\n data_asset_name=data_asset_name,\n options=batch_parameters,\n )\n return result\n\n # try to get a block batch request\n return _get_block_batch_request(\n datasource_name=datasource_name,\n data_connector_name=data_connector_name,\n data_asset_name=data_asset_name,\n batch_identifiers=batch_identifiers,\n batch_spec_passthrough=batch_spec_passthrough,\n batch_filter_parameters=batch_filter_parameters,\n data_connector_query=data_connector_query,\n limit=limit,\n index=index,\n custom_filter_function=custom_filter_function,\n sampling_method=sampling_method,\n sampling_kwargs=sampling_kwargs,\n partitioner_method=partitioner_method,\n partitioner_kwargs=partitioner_kwargs,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50257,\n n_positions=1024,\n n_embd=768,\n n_layer=12,\n n_head=12,\n n_inner=None,\n activation_function=\"gelu_pytorch_tanh\",\n resid_pdrop=0.1,\n embd_pdrop=0.1,\n attn_pdrop=0.1,\n layer_norm_epsilon=1e-5,\n initializer_range=0.02,\n scale_attn_weights=True,\n use_cache=True,\n bos_token_id=50256,\n eos_token_id=50256,\n attention_softmax_in_fp32=True,\n scale_attention_softmax_in_fp32=True,\n multi_query=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.n_positions = n_positions\n self.n_embd = n_embd\n self.n_layer = n_layer\n self.n_head = n_head\n self.n_inner = n_inner\n self.activation_function = activation_function\n self.resid_pdrop = resid_pdrop\n self.embd_pdrop = embd_pdrop\n self.attn_pdrop = attn_pdrop\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.scale_attn_weights = scale_attn_weights\n self.use_cache = use_cache\n self.attention_softmax_in_fp32 = attention_softmax_in_fp32\n self.scale_attention_softmax_in_fp32 = scale_attention_softmax_in_fp32\n self.multi_query = multi_query\n\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[TFSeq2SeqModelOutput, Tuple[tf.Tensor]]:\n # different to other models, Bart automatically creates decoder_input_ids from\n # input_ids if no decoder_input_ids are provided\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n if input_ids is None:\n raise ValueError(\n \"If no `decoder_input_ids` or `decoder_inputs_embeds` are \"\n \"passed, `input_ids` cannot be `None`. Please pass either \"\n \"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.\"\n )\n\n decoder_input_ids = shift_tokens_right(\n input_ids, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False\n elif not return_dict and not isinstance(encoder_outputs, tuple):\n encoder_outputs = encoder_outputs.to_tuple()\n\n decoder_outputs = self.decoder(\n decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MVP_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(MVP_CONDITIONAL_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n num_channels=3,\n depths=[3, 3, 6, 4],\n embed_dims=[48, 56, 112, 220],\n mlp_ratio=4,\n downsamples=[True, True, True, True],\n hidden_act=\"gelu\",\n down_patch_size=3,\n down_stride=2,\n down_pad=1,\n drop_path_rate=0.0,\n drop_mlp_rate=0.0,\n drop_conv_encoder_rate=0.0,\n use_layer_scale=True,\n layer_scale_init_value=1e-5,\n batch_norm_eps=1e-5,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.image_size = image_size\n self.num_channels = num_channels\n self.depths = depths\n self.embed_dims = embed_dims\n self.mlp_ratio = mlp_ratio\n self.downsamples = downsamples\n self.hidden_act = hidden_act\n self.down_patch_size = down_patch_size\n self.down_stride = down_stride\n self.down_pad = down_pad\n self.drop_path_rate = drop_path_rate\n self.drop_mlp_rate = drop_mlp_rate\n self.drop_conv_encoder_rate = drop_conv_encoder_rate\n self.use_layer_scale = use_layer_scale\n self.layer_scale_init_value = layer_scale_init_value\n self.batch_norm_eps = batch_norm_eps", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n intermediate_size=3072,\n num_hidden_layers=12,\n num_attention_heads=12,\n mit_hidden_size=512,\n mit_intermediate_size=2048,\n mit_num_hidden_layers=1,\n mit_num_attention_heads=8,\n num_channels=3,\n image_size=224,\n patch_size=32,\n num_frames=8,\n hidden_act=\"quick_gelu\",\n layer_norm_eps=1e-5,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n drop_path_rate=0.0,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.mit_hidden_size = mit_hidden_size\n self.mit_intermediate_size = mit_intermediate_size\n self.mit_num_hidden_layers = mit_num_hidden_layers\n self.mit_num_attention_heads = mit_num_attention_heads\n self.num_channels = num_channels\n self.patch_size = patch_size\n self.num_frames = num_frames\n self.image_size = image_size\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.attention_dropout = attention_dropout\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.drop_path_rate = drop_path_rate", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,\n return_segmentation_masks: bool = None,\n masks_path: Optional[Union[str, pathlib.Path]] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample=None, # PILImageResampling\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[Union[int, float]] = None,\n do_normalize: Optional[bool] = None,\n do_convert_annotations: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n format: Optional[Union[str, AnnotationFormat]] = None,\n return_tensors: Optional[Union[TensorType, str]] = None,\n data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n pad_size: Optional[Dict[str, int]] = None,\n **kwargs,\n ) -> BatchFeature:\n \"\"\"\n Preprocess an image or a batch of images so that it can be used by the model.\n\n Args:\n images (`ImageInput`):\n Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging\n from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):\n List of annotations associated with the image or batch of images. If annotation is for object\n detection, the annotations should be a dictionary with the following keys:\n - \"image_id\" (`int`): The image id.\n - \"annotations\" (`List[Dict]`): List of annotations for an image. Each annotation should be a\n dictionary. An image can have no annotations, in which case the list should be empty.\n If annotation is for segmentation, the annotations should be a dictionary with the following keys:\n - \"image_id\" (`int`): The image id.\n - \"segments_info\" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.\n An image can have no segments, in which case the list should be empty.\n - \"file_name\" (`str`): The file name of the image.\n return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):\n Whether to return segmentation masks.\n masks_path (`str` or `pathlib.Path`, *optional*):\n Path to the directory containing the segmentation masks.\n do_resize (`bool`, *optional*, defaults to self.do_resize):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to self.size):\n Size of the image's `(height, width)` dimensions after resizing. Available options are:\n - `{\"height\": int, \"width\": int}`: The image will be resized to the exact size `(height, width)`.\n Do NOT keep the aspect ratio.\n - `{\"shortest_edge\": int, \"longest_edge\": int}`: The image will be resized to a maximum size respecting\n the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge\n less or equal to `longest_edge`.\n - `{\"max_height\": int, \"max_width\": int}`: The image will be resized to the maximum size respecting the\n aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to\n `max_width`.\n resample (`PILImageResampling`, *optional*, defaults to self.resample):\n Resampling filter to use when resizing the image.\n do_rescale (`bool`, *optional*, defaults to self.do_rescale):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to self.rescale_factor):\n Rescale factor to use when rescaling the image.\n do_normalize (`bool`, *optional*, defaults to self.do_normalize):\n Whether to normalize the image.\n do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):\n Whether to convert the annotations to the format expected by the model. Converts the bounding\n boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`\n and in relative coordinates.\n image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):\n Mean to use when normalizing the image.\n image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):\n Standard deviation to use when normalizing the image.\n do_pad (`bool`, *optional*, defaults to self.do_pad):\n Whether to pad the image. If `True`, padding will be applied to the bottom and right of\n the image with zeros. If `pad_size` is provided, the image will be padded to the specified\n dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.\n format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):\n Format of the annotations.\n return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):\n Type of tensors to return. If `None`, will return the list of images.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n pad_size (`Dict[str, int]`, *optional*):\n The size `{\"height\": int, \"width\" int}` to pad the images to. Must be larger than any image size\n provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest\n height and width in the batch.\n \"\"\"\n if \"pad_and_return_pixel_mask\" in kwargs:\n logger.warning_once(\n \"The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, \"\n \"use `do_pad` instead.\"\n )\n do_pad = kwargs.pop(\"pad_and_return_pixel_mask\")\n\n max_size = None\n if \"max_size\" in kwargs:\n logger.warning_once(\n \"The `max_size` argument is deprecated and will be removed in a future version, use\"\n \" `size['longest_edge']` instead.\"\n )\n size = kwargs.pop(\"max_size\")\n\n do_resize = self.do_resize if do_resize is None else do_resize\n size = self.size if size is None else size\n size = get_size_dict(size=size, max_size=max_size, default_to_square=False)\n resample = self.resample if resample is None else resample\n do_rescale = self.do_rescale if do_rescale is None else do_rescale\n rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor\n do_normalize = self.do_normalize if do_normalize is None else do_normalize\n image_mean = self.image_mean if image_mean is None else image_mean\n image_std = self.image_std if image_std is None else image_std\n do_convert_annotations = (\n self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations\n )\n do_pad = self.do_pad if do_pad is None else do_pad\n pad_size = self.pad_size if pad_size is None else pad_size\n format = self.format if format is None else format\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)\n\n # Here, the pad() method pads to the maximum of (width, height). It does not need to be validated.\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if annotations is not None and isinstance(annotations, dict):\n annotations = [annotations]\n\n if annotations is not None and len(images) != len(annotations):\n raise ValueError(\n f\"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match.\"\n )\n\n format = AnnotationFormat(format)\n if annotations is not None:\n validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)\n\n if (\n masks_path is not None\n and format == AnnotationFormat.COCO_PANOPTIC\n and not isinstance(masks_path, (pathlib.Path, str))\n ):\n raise ValueError(\n \"The path to the directory containing the mask PNG files should be provided as a\"\n f\" `pathlib.Path` or string object, but is {type(masks_path)} instead.\"\n )\n\n # All transformations expect numpy arrays\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)\n if annotations is not None:\n prepared_images = []\n prepared_annotations = []\n for image, target in zip(images, annotations):\n target = self.prepare_annotation(\n image,\n target,\n format,\n return_segmentation_masks=return_segmentation_masks,\n masks_path=masks_path,\n input_data_format=input_data_format,\n )\n prepared_images.append(image)\n prepared_annotations.append(target)\n images = prepared_images\n annotations = prepared_annotations\n del prepared_images, prepared_annotations\n\n # transformations\n if do_resize:\n if annotations is not None:\n resized_images, resized_annotations = [], []\n for image, target in zip(images, annotations):\n orig_size = get_image_size(image, input_data_format)\n resized_image = self.resize(\n image, size=size, max_size=max_size, resample=resample, input_data_format=input_data_format\n )\n resized_annotation = self.resize_annotation(\n target, orig_size, get_image_size(resized_image, input_data_format)\n )\n resized_images.append(resized_image)\n resized_annotations.append(resized_annotation)\n images = resized_images\n annotations = resized_annotations\n del resized_images, resized_annotations\n else:\n images = [\n self.resize(image, size=size, resample=resample, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_rescale:\n images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]\n\n if do_normalize:\n images = [\n self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images\n ]\n\n if do_convert_annotations and annotations is not None:\n annotations = [\n self.normalize_annotation(annotation, get_image_size(image, input_data_format))\n for annotation, image in zip(annotations, images)\n ]\n\n if do_pad:\n # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}\n encoded_inputs = self.pad(\n images,\n annotations=annotations,\n return_pixel_mask=True,\n data_format=data_format,\n input_data_format=input_data_format,\n update_bboxes=do_convert_annotations,\n return_tensors=return_tensors,\n pad_size=pad_size,\n )\n else:\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n for image in images\n ]\n encoded_inputs = BatchFeature(data={\"pixel_values\": images}, tensor_type=return_tensors)\n if annotations is not None:\n encoded_inputs[\"labels\"] = [\n BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations\n ]\n\n return encoded_inputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n api: SemanticAnalyzerCoreInterface,\n tvar_scope: TypeVarLikeScope,\n plugin: Plugin,\n options: Options,\n is_typeshed_stub: bool,\n *,\n defining_alias: bool = False,\n python_3_12_type_alias: bool = False,\n allow_tuple_literal: bool = False,\n allow_unbound_tvars: bool = False,\n allow_placeholder: bool = False,\n allow_typed_dict_special_forms: bool = False,\n allow_param_spec_literals: bool = False,\n allow_unpack: bool = False,\n report_invalid_types: bool = True,\n prohibit_self_type: str | None = None,\n allowed_alias_tvars: list[TypeVarLikeType] | None = None,\n allow_type_any: bool = False,\n alias_type_params_names: list[str] | None = None,\n ) -> None:\n self.api = api\n self.fail_func = api.fail\n self.note_func = api.note\n self.tvar_scope = tvar_scope\n # Are we analysing a type alias definition rvalue?\n self.defining_alias = defining_alias\n self.python_3_12_type_alias = python_3_12_type_alias\n self.allow_tuple_literal = allow_tuple_literal\n # Positive if we are analyzing arguments of another (outer) type\n self.nesting_level = 0\n # Should we allow new type syntax when targeting older Python versions\n # like 'list[int]' or 'X | Y' (allowed in stubs and with `__future__` import)?\n self.always_allow_new_syntax = self.api.is_stub_file or self.api.is_future_flag_set(\n \"annotations\"\n )\n # Should we accept unbound type variables? This is currently used for class bases,\n # and alias right hand sides (before they are analyzed as type aliases).\n self.allow_unbound_tvars = allow_unbound_tvars\n if allowed_alias_tvars is None:\n allowed_alias_tvars = []\n self.allowed_alias_tvars = allowed_alias_tvars\n self.alias_type_params_names = alias_type_params_names\n # If false, record incomplete ref if we generate PlaceholderType.\n self.allow_placeholder = allow_placeholder\n # Are we in a context where Required[] is allowed?\n self.allow_typed_dict_special_forms = allow_typed_dict_special_forms\n # Are we in a context where ParamSpec literals are allowed?\n self.allow_param_spec_literals = allow_param_spec_literals\n # Are we in context where literal \"...\" specifically is allowed?\n self.allow_ellipsis = False\n # Should we report an error whenever we encounter a RawExpressionType outside\n # of a Literal context: e.g. whenever we encounter an invalid type? Normally,\n # we want to report an error, but the caller may want to do more specialized\n # error handling.\n self.report_invalid_types = report_invalid_types\n self.plugin = plugin\n self.options = options\n self.is_typeshed_stub = is_typeshed_stub\n # Names of type aliases encountered while analysing a type will be collected here.\n self.aliases_used: set[str] = set()\n self.prohibit_self_type = prohibit_self_type\n # Allow variables typed as Type[Any] and type (useful for base classes).\n self.allow_type_any = allow_type_any\n self.allow_type_var_tuple = False\n self.allow_unpack = allow_unpack", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def __init__(\n self,\n init_env_path: os.PathLike,\n init_grid_path: os.PathLike,\n parameters: Parameters,\n voltagecontrolerClass: type,\n name=\"unknown\",\n thermal_limit_a: Optional[np.ndarray] = None,\n epsilon_poly: float = 1e-4, # precision of the redispatching algorithm\n tol_poly: float = 1e-2, # i need to compute a redispatching if the actual values are \"more than tol_poly\" the values they should be\n other_rewards: dict = None,\n with_forecast: bool = True,\n opponent_space_type: type = OpponentSpace,\n opponent_action_class: type = DontAct,\n opponent_class: type = BaseOpponent,\n opponent_init_budget: float = 0.0,\n opponent_budget_per_ts: float = 0.0,\n opponent_budget_class: type = NeverAttackBudget,\n opponent_attack_duration: int = 0,\n opponent_attack_cooldown: int = 99999,\n kwargs_opponent: dict = None,\n has_attention_budget: bool = False,\n attention_budget_cls: type = LinearAttentionBudget,\n kwargs_attention_budget: dict = None,\n logger: Optional[logging.Logger] = None,\n kwargs_observation: Optional[dict] = None,\n observation_bk_class=None, # type of backend for the observation space\n observation_bk_kwargs=None, # type of backend for the observation space\n highres_sim_counter=None,\n update_obs_after_reward=False,\n n_busbar=2,\n _is_test: bool = False, # TODO not implemented !!\n _init_obs: Optional[BaseObservation] =None,\n _local_dir_cls=None,\n _read_from_local_dir=None,\n _raw_backend_class=None,\n ):\n #: flag to indicate not to erase the directory when the env has been used\n self._do_not_erase_local_dir_cls = False\n GridObjects.__init__(self)\n RandomObject.__init__(self)\n self.name = name\n self._local_dir_cls = _local_dir_cls # suppose it's the second path to the environment, so the classes are already in the files\n self._read_from_local_dir = _read_from_local_dir\n if self._read_from_local_dir is not None:\n if os.path.split(self._read_from_local_dir)[1] == \"_grid2op_classes\":\n # legacy behaviour (using experimental_read_from_local_dir kwargs in env.make)\n self._do_not_erase_local_dir_cls = True\n else:\n self._do_not_erase_local_dir_cls = True\n \n self._actionClass_orig = None\n self._observationClass_orig = None\n \n self._raw_backend_class = _raw_backend_class\n \n self._n_busbar = n_busbar # env attribute not class attribute !\n if other_rewards is None:\n other_rewards = {}\n if kwargs_attention_budget is None:\n kwargs_attention_budget = {}\n if kwargs_opponent is None:\n kwargs_opponent = {}\n \n self._is_test: bool = _is_test\n if logger is None:\n self.logger = logging.getLogger(__name__)\n self.logger.disabled = True\n else:\n self.logger: logging.Logger = logger.getChild(\"grid2op_BaseEnv\")\n\n if init_grid_path is not None:\n self._init_grid_path: os.PathLike = os.path.abspath(init_grid_path)\n else:\n self._init_grid_path = None\n\n self._DEBUG: bool = False\n self._complete_action_cls: type = None\n self.__closed: bool = False # by default the environment is not closed\n\n # specific to power system\n if not isinstance(parameters, Parameters):\n raise Grid2OpException(\n 'Parameter \"parameters\" used to build the Environment should derived form the '\n 'grid2op.Parameters class, type provided is \"{}\"'.format(\n type(parameters)\n )\n )\n parameters.check_valid() # check the provided parameters are valid\n self._parameters: Parameters = copy.deepcopy(parameters)\n self.with_forecast: bool = with_forecast\n self._forecasts = None\n\n # some timers\n self._time_apply_act: float = dt_float(0)\n self._time_powerflow: float = dt_float(0)\n self._time_extract_obs: float = dt_float(0)\n self._time_create_bk_act: float = dt_float(0)\n self._time_opponent: float = dt_float(0)\n self._time_redisp: float = dt_float(0)\n self._time_step: float = dt_float(0)\n\n # data relative to interpolation\n self._epsilon_poly: float = dt_float(epsilon_poly)\n self._tol_poly: float = dt_float(tol_poly)\n\n # class used for the action spaces\n self._helper_action_class: ActionSpace = None\n self._helper_observation_class: ObservationSpace = None\n\n # and calendar data\n self.time_stamp: time.struct_time = datetime(year=2019, month=1, day=1)\n self.nb_time_step: datetime.timedelta = dt_int(0)\n self.delta_time_seconds = None # number of seconds between two consecutive step\n\n # observation\n self.current_obs: Optional[BaseObservation] = None\n self._line_status: np.ndarray = None\n\n self._ignore_min_up_down_times: bool = self._parameters.IGNORE_MIN_UP_DOWN_TIME\n self._forbid_dispatch_off: bool = (\n not self._parameters.ALLOW_DISPATCH_GEN_SWITCH_OFF\n )\n\n # type of power flow to play\n # if True, then it will not disconnect lines above their thermal limits\n self._no_overflow_disconnection: bool = (\n self._parameters.NO_OVERFLOW_DISCONNECTION\n )\n self._timestep_overflow: np.ndarray = None\n self._nb_timestep_overflow_allowed: np.ndarray = None\n self._hard_overflow_threshold: np.ndarray = None\n\n # store actions \"cooldown\"\n self._times_before_line_status_actionable: np.ndarray = None\n self._max_timestep_line_status_deactivated: int = (\n self._parameters.NB_TIMESTEP_COOLDOWN_LINE\n )\n self._times_before_topology_actionable: np.ndarray = None\n self._max_timestep_topology_deactivated: int = (\n self._parameters.NB_TIMESTEP_COOLDOWN_SUB\n )\n self._nb_ts_reco: int = self._parameters.NB_TIMESTEP_RECONNECTION\n\n # for maintenance operation\n self._time_next_maintenance: np.ndarray = None\n self._duration_next_maintenance: np.ndarray = None\n\n # hazard (not used outside of this class, information is given in `times_before_line_status_actionable`\n self._hazard_duration: np.ndarray = None\n\n self._env_dc = self._parameters.ENV_DC\n\n # redispatching data\n self._target_dispatch: np.ndarray = None\n self._already_modified_gen: np.ndarray = None\n self._actual_dispatch: np.ndarray = None\n self._gen_uptime: np.ndarray = None\n self._gen_downtime: np.ndarray = None\n self._gen_activeprod_t: np.ndarray = None\n self._gen_activeprod_t_redisp: np.ndarray = None\n\n self._thermal_limit_a: np.ndarray = thermal_limit_a\n self._disc_lines: np.ndarray = None\n\n # store environment modifications\n self._injection = None\n self._maintenance = None\n self._hazards = None\n self._env_modification = None\n\n # to use the data\n self.done = False\n self.current_reward = None\n self._helper_action_env: ActionSpace = None\n self.chronics_handler : ChronicsHandler = None\n self._game_rules = None\n self._action_space: ActionSpace = None\n\n self._rewardClass: type = None\n self._actionClass: type = None\n self._observationClass: type = None\n self._legalActClass: type = None\n self._observation_space: ObservationSpace = None\n self._names_chronics_to_backend: dict = None\n self._reward_helper = None\n\n # gym compatibility\n self.reward_range = None, None\n self._viewer = None\n self.viewer_fig = None\n\n # other rewards\n self.other_rewards = {}\n for k, v in other_rewards.items():\n if isinstance(v, type):\n if not issubclass(v, BaseReward):\n raise Grid2OpException(\n 'All values of \"rewards\" key word argument should be classes that inherit '\n 'from \"grid2op.BaseReward\"'\n )\n else:\n if not isinstance(v, BaseReward):\n raise Grid2OpException(\n 'All values of \"rewards\" key word argument should be classes that inherit '\n 'from \"grid2op.BaseReward\"'\n )\n\n if not isinstance(k, str):\n raise Grid2OpException(\n 'All keys of \"rewards\" should be of string type.'\n )\n self.other_rewards[k] = RewardHelper(v, self.logger)\n\n # opponent\n self._opponent_action_class = (\n opponent_action_class # class of the action of the opponent\n )\n self._opponent_space_type = opponent_space_type # type of the opponent action space\n self._opponent_class = opponent_class # class of the opponent\n self._opponent_init_budget = dt_float(opponent_init_budget)\n self._opponent_attack_duration = dt_int(opponent_attack_duration)\n self._opponent_attack_cooldown = dt_int(opponent_attack_cooldown)\n self._opponent_budget_per_ts = dt_float(opponent_budget_per_ts)\n self._kwargs_opponent = kwargs_opponent\n self._opponent_budget_class = opponent_budget_class\n\n # below initialized by _create_env, above: need to be called\n self._opponent_action_space = None\n self._compute_opp_budget = None\n self._opponent = None\n self._oppSpace = None\n\n # voltage\n self._voltagecontrolerClass = voltagecontrolerClass\n self._voltage_controler = None\n\n # backend action\n self._backend_action_class : type = None\n self._backend_action : _BackendAction = None\n\n # specific to Basic Env, do not change\n self.backend : Backend = None\n self.__is_init = False\n self.debug_dispatch = False\n\n # to change the parameters\n self.__new_param = None\n self.__new_forecast_param = None\n self.__new_reward_func = None\n\n # storage units\n # TODO storage: what to do when self.storage_Emin >0. and self.storage_loss > 0.\n # TODO and we have self._storage_current_charge - self.storage_loss < self.storage_Emin\n self._storage_current_charge = None # the current storage charge\n self._storage_previous_charge = None # the previous storage charge\n self._action_storage = None # the storage action performed\n self._amount_storage = None # total amount of storage to be dispatched\n self._amount_storage_prev = None\n self._storage_power = None\n self._storage_power_prev = None\n\n # curtailment\n self._limit_curtailment = None\n self._limit_curtailment_prev = None\n self._gen_before_curtailment = None\n self._sum_curtailment_mw = None\n self._sum_curtailment_mw_prev = None\n self._limited_before = 0.0 # TODO curt\n\n # attention budget\n self._has_attention_budget = has_attention_budget\n self._attention_budget = None\n self._attention_budget_cls = attention_budget_cls\n self._is_alarm_illegal = False\n self._is_alarm_used_in_reward = False\n\n # alert infos\n self._is_alert_illegal = False\n self._is_alert_used_in_reward = False\n\n self._kwargs_attention_budget = copy.deepcopy(kwargs_attention_budget)\n\n # to ensure self.get_obs() has a reproducible behaviour\n self._last_obs = None\n\n # to retrieve previous result (before 1.6.5 the seed of the\n # action space or observation space was not done each reset)\n self._has_just_been_seeded = False\n if kwargs_observation is not None:\n self._kwargs_observation = copy.deepcopy(kwargs_observation)\n else:\n self._kwargs_observation = {}\n\n if init_env_path is not None:\n self._init_env_path = os.path.abspath(init_env_path)\n else:\n self._init_env_path = None\n \n # time_dependant attributes for the \"forecast env\"\n if _init_obs is not None:\n self._init_obs = _init_obs.copy()\n self._init_obs._obs_env = None\n else:\n self._init_obs = None\n \n self._observation_bk_class = observation_bk_class\n self._observation_bk_kwargs = observation_bk_kwargs\n \n if highres_sim_counter is not None:\n self._highres_sim_counter = highres_sim_counter\n else:\n self._highres_sim_counter = HighResSimCounter()\n \n self._update_obs_after_reward = update_obs_after_reward\n \n # alert\n self._last_alert = None\n self._time_since_last_alert = None\n self._alert_duration= None\n self._total_number_of_alert = 0\n self._time_since_last_attack = None\n self._was_alert_used_after_attack = None\n self._attack_under_alert = None\n self._is_already_attacked = None\n \n # general things that can be used by the reward\n self._reward_to_obs = {}", "smellKey": "S107", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "def __init__(self, paths, resume=True, use_cache=True, reporter=None,\n name=None, owner_uuid=None, api_client=None, batch_mode=False,\n ensure_unique_name=False, num_retries=None,\n put_threads=None, replication_desired=None, filename=None,\n update_time=60.0, update_collection=None, storage_classes=None,\n logger=logging.getLogger('arvados.arv_put'), dry_run=False,\n follow_links=True, exclude_paths=[], exclude_names=None,\n trash_at=None):\n self.paths = paths\n self.resume = resume\n self.use_cache = use_cache\n self.batch_mode = batch_mode\n self.update = False\n self.reporter = reporter\n # This will set to 0 before start counting, if no special files are going\n # to be read.\n self.bytes_expected = None\n self.bytes_written = 0\n self.bytes_skipped = 0\n self.name = name\n self.owner_uuid = owner_uuid\n self.ensure_unique_name = ensure_unique_name\n self.num_retries = num_retries\n self.replication_desired = replication_desired\n self.put_threads = put_threads\n self.filename = filename\n self.storage_classes = storage_classes\n self._api_client = api_client\n self._state_lock = threading.Lock()\n self._state = None # Previous run state (file list & manifest)\n self._current_files = [] # Current run file list\n self._cache_file = None\n self._collection_lock = threading.Lock()\n self._remote_collection = None # Collection being updated (if asked)\n self._local_collection = None # Collection from previous run manifest\n self._file_paths = set() # Files to be updated in remote collection\n self._stop_checkpointer = threading.Event()\n self._checkpointer = threading.Thread(target=self._update_task)\n self._checkpointer.daemon = True\n self._update_task_time = update_time # How many seconds wait between update runs\n self._files_to_upload = FileUploadList(dry_run=dry_run)\n self._upload_started = False\n self.logger = logger\n self.dry_run = dry_run\n self._checkpoint_before_quit = True\n self.follow_links = follow_links\n self.exclude_paths = exclude_paths\n self.exclude_names = exclude_names\n self._trash_at = trash_at\n\n if self._trash_at is not None:\n if type(self._trash_at) not in [datetime.datetime, datetime.timedelta]:\n raise TypeError('trash_at should be None, timezone-naive datetime or timedelta')\n if type(self._trash_at) == datetime.datetime and self._trash_at.tzinfo is not None:\n raise TypeError('provided trash_at datetime should be timezone-naive')\n\n if not self.use_cache and self.resume:\n raise ArvPutArgumentConflict('resume cannot be True when use_cache is False')\n\n # Check for obvious dry-run responses\n if self.dry_run and (not self.use_cache or not self.resume):\n raise ArvPutUploadIsPending()\n\n # Load cached data if any and if needed\n self._setup_state(update_collection)\n\n # Build the upload file list, excluding requested files and counting the\n # bytes expected to be uploaded.\n self._build_upload_list()", "smellKey": "S107", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n do_resize: Optional[bool] = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: Optional[bool] = None,\n crop_size: Optional[Dict[str, int]] = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n # Mask related params\n return_image_mask: Optional[bool] = None,\n input_size_patches: Optional[int] = None,\n total_mask_patches: Optional[int] = None,\n mask_group_min_patches: Optional[int] = None,\n mask_group_max_patches: Optional[int] = None,\n mask_group_min_aspect_ratio: Optional[float] = None,\n mask_group_max_aspect_ratio: Optional[float] = None,\n # Codebook related params\n return_codebook_pixels: Optional[bool] = None,\n codebook_do_resize: Optional[bool] = None,\n codebook_size: Optional[Dict[str, int]] = None,\n codebook_resample: Optional[int] = None,\n codebook_do_center_crop: Optional[bool] = None,\n codebook_crop_size: Optional[Dict[str, int]] = None,\n codebook_do_rescale: Optional[bool] = None,\n codebook_rescale_factor: Optional[float] = None,\n codebook_do_map_pixels: Optional[bool] = None,\n codebook_do_normalize: Optional[bool] = None,\n codebook_image_mean: Optional[Iterable[float]] = None,\n codebook_image_std: Optional[Iterable[float]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n return_image_mask (`bool`, *optional*, defaults to `self.return_image_mask`):\n Whether to return the image mask.\n input_size_patches (`int`, *optional*, defaults to `self.input_size_patches`):\n Size of the patches to extract from the image.\n total_mask_patches (`int`, *optional*, defaults to `self.total_mask_patches`):\n Total number of patches to extract from the image.\n mask_group_min_patches (`int`, *optional*, defaults to `self.mask_group_min_patches`):\n Minimum number of patches to extract from the image.\n mask_group_max_patches (`int`, *optional*, defaults to `self.mask_group_max_patches`):\n Maximum number of patches to extract from the image.\n mask_group_min_aspect_ratio (`float`, *optional*, defaults to `self.mask_group_min_aspect_ratio`):\n Minimum aspect ratio of the patches to extract from the image.\n mask_group_max_aspect_ratio (`float`, *optional*, defaults to `self.mask_group_max_aspect_ratio`):\n Maximum aspect ratio of the patches to extract from the image.\n return_codebook_pixels (`bool`, *optional*, defaults to `self.return_codebook_pixels`):\n Whether to return the codebook pixels.\n codebook_do_resize (`bool`, *optional*, defaults to `self.codebook_do_resize`):\n Whether to resize the codebook pixels.\n codebook_size (`Dict[str, int]`, *optional*, defaults to `self.codebook_size`):\n Size of the codebook pixels.\n codebook_resample (`int`, *optional*, defaults to `self.codebook_resample`):\n Resampling filter to use if resizing the codebook pixels. This can be one of the enum\n `PILImageResampling`, Only has an effect if `codebook_do_resize` is set to `True`.\n codebook_do_center_crop (`bool`, *optional*, defaults to `self.codebook_do_center_crop`):\n Whether to center crop the codebook pixels.\n codebook_crop_size (`Dict[str, int]`, *optional*, defaults to `self.codebook_crop_size`):\n Size of the center crop of the codebook pixels. Only has an effect if `codebook_do_center_crop` is set\n to `True`.\n codebook_do_rescale (`bool`, *optional*, defaults to `self.codebook_do_rescale`):\n Whether to rescale the codebook pixels values between [0 - 1].\n codebook_rescale_factor (`float`, *optional*, defaults to `self.codebook_rescale_factor`):\n Rescale factor to rescale the codebook pixels by if `codebook_do_rescale` is set to `True`.\n codebook_do_map_pixels (`bool`, *optional*, defaults to `self.codebook_do_map_pixels`):\n Whether to map the codebook pixels values.\n codebook_do_normalize (`bool`, *optional*, defaults to `self.codebook_do_normalize`):\n Whether to normalize the codebook pixels.\n codebook_image_mean (`float` or `List[float]`, *optional*, defaults to `self.codebook_image_mean`):\n Codebook pixels mean to normalize the codebook pixels by if `codebook_do_normalize` is set to `True`.\n codebook_image_std (`float` or `List[float]`, *optional*, defaults to `self.codebook_image_std`):\n Codebook pixels standard deviation to normalize the codebook pixels by if `codebook_do_normalize` is\n set to `True`.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size)\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\")\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n return_image_mask = return_image_mask if return_image_mask is not None else self.return_image_mask\n input_size_patches = input_size_patches if input_size_patches is not None else self.input_size_patches\n total_mask_patches = total_mask_patches if total_mask_patches is not None else self.total_mask_patches\n mask_group_min_patches = (\n mask_group_min_patches if mask_group_min_patches is not None else self.mask_group_min_patches\n )\n mask_group_max_patches = (\n mask_group_max_patches if mask_group_max_patches is not None else self.mask_group_max_patches\n )\n mask_group_min_aspect_ratio = (\n mask_group_min_aspect_ratio\n if mask_group_min_aspect_ratio is not None\n else self.mask_group_min_aspect_ratio\n )\n mask_group_max_aspect_ratio = (\n mask_group_max_aspect_ratio\n if mask_group_max_aspect_ratio is not None\n else self.mask_group_max_aspect_ratio\n )\n\n return_codebook_pixels = (\n return_codebook_pixels if return_codebook_pixels is not None else self.return_codebook_pixels\n )\n codebook_do_resize = codebook_do_resize if codebook_do_resize is not None else self.codebook_do_resize\n codebook_size = codebook_size if codebook_size is not None else self.codebook_size\n codebook_size = get_size_dict(codebook_size, param_name=\"codebook_size\")\n codebook_resample = codebook_resample if codebook_resample is not None else self.codebook_resample\n codebook_do_rescale = codebook_do_rescale if codebook_do_rescale is not None else self.codebook_do_rescale\n codebook_rescale_factor = (\n codebook_rescale_factor if codebook_rescale_factor is not None else self.codebook_rescale_factor\n )\n codebook_do_center_crop = (\n codebook_do_center_crop if codebook_do_center_crop is not None else self.codebook_do_center_crop\n )\n codebook_crop_size = codebook_crop_size if codebook_crop_size is not None else self.codebook_crop_size\n codebook_crop_size = get_size_dict(codebook_crop_size, param_name=\"codebook_crop_size\")\n codebook_do_map_pixels = (\n codebook_do_map_pixels if codebook_do_map_pixels is not None else self.codebook_do_map_pixels\n )\n codebook_do_normalize = (\n codebook_do_normalize if codebook_do_normalize is not None else self.codebook_do_normalize\n )\n codebook_image_mean = codebook_image_mean if codebook_image_mean is not None else self.codebook_image_mean\n codebook_image_std = codebook_image_std if codebook_image_std is not None else self.codebook_image_std\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n processed_images = [\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_map_pixels=False,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in images\n ]\n data = {\"pixel_values\": processed_images}\n\n if return_codebook_pixels:\n codebook_images = [\n self._preprocess_image(\n image=img,\n do_resize=codebook_do_resize,\n size=codebook_size,\n resample=codebook_resample,\n do_center_crop=codebook_do_center_crop,\n crop_size=codebook_crop_size,\n do_rescale=codebook_do_rescale,\n rescale_factor=codebook_rescale_factor,\n do_normalize=codebook_do_normalize,\n image_mean=codebook_image_mean,\n image_std=codebook_image_std,\n do_map_pixels=codebook_do_map_pixels,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in images\n ]\n data[\"codebook_pixel_values\"] = codebook_images\n\n if return_image_mask:\n mask_generator = self.masking_generator(\n input_size_patches=input_size_patches,\n total_mask_patches=total_mask_patches,\n mask_group_min_patches=mask_group_min_patches,\n mask_group_max_patches=mask_group_max_patches,\n mask_group_min_aspect_ratio=mask_group_min_aspect_ratio,\n mask_group_max_aspect_ratio=mask_group_max_aspect_ratio,\n )\n masks = [mask_generator() for _ in images]\n data[\"bool_masked_pos\"] = masks\n\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_mel_bins=128,\n encoder_layers=32,\n encoder_attention_heads=20,\n encoder_ffn_dim=5120,\n encoder_layerdrop=0.0,\n d_model=1280,\n dropout=0.0,\n attention_dropout=0.0,\n activation_function=\"gelu\",\n activation_dropout=0.0,\n scale_embedding=False,\n init_std=0.02,\n max_source_positions=1500,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.num_mel_bins = num_mel_bins\n self.d_model = d_model\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.encoder_ffn_dim = encoder_ffn_dim\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_function = activation_function\n self.activation_dropout = activation_dropout\n self.encoder_layerdrop = encoder_layerdrop\n self.num_hidden_layers = encoder_layers\n self.init_std = init_std\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n self.max_source_positions = max_source_positions", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MT5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)\n # Copied from transformers.models.t5.modeling_t5.T5ForSequenceClassification.forward\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n if input_ids is None and inputs_embeds is not None:\n raise NotImplementedError(\n f\"Passing input embeddings is currently not supported for {self.__class__.__name__}\"\n )\n\n # Copied from models.bart.modeling_bart.BartModel.forward different to other models, T5 automatically creates\n # decoder_input_ids from input_ids if no decoder_input_ids are provided\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n if input_ids is None:\n raise ValueError(\n \"If no `decoder_input_ids` or `decoder_inputs_embeds` are \"\n \"passed, `input_ids` cannot be `None`. Please pass either \"\n \"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.\"\n )\n decoder_input_ids = self._shift_right(input_ids)\n\n outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = outputs[0]\n\n eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)\n\n if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:\n raise ValueError(\"All examples must have the same number of <eos> tokens.\")\n batch_size, _, hidden_size = sequence_output.shape\n sentence_representation = sequence_output[eos_mask, :].view(batch_size, -1, hidden_size)[:, -1, :]\n logits = self.classification_head(sentence_representation)\n\n loss = None\n if labels is not None:\n labels = labels.to(logits.device)\n if self.config.problem_type is None:\n if self.config.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.config.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = 13\n self.seq_length = 7\n self.is_training = True\n self.use_input_mask = True\n self.use_token_type_ids = True\n self.use_labels = True\n self.vocab_size = 99\n self.hidden_size = 32\n self.num_hidden_layers = 2\n self.num_attention_heads = 4\n self.intermediate_size = 37\n self.hidden_act = \"gelu\"\n self.hidden_dropout_prob = 0.1\n self.attention_probs_dropout_prob = 0.1\n self.max_position_embeddings = 512\n self.type_vocab_size = 16\n self.type_sequence_label_size = 2\n self.initializer_range = 0.02\n self.num_labels = 3\n self.num_choices = 4\n self.scope = None", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n iterations=10,\n lr=0.01,\n vqgan=None,\n vqgan_config=None,\n vqgan_checkpoint=None,\n clip=None,\n clip_preprocessor=None,\n device=None,\n log=False,\n save_vector=True,\n return_val=\"image\",\n quantize=True,\n save_intermediate=False,\n show_intermediate=False,\n make_grid=False,\n ) -> None:\n \"\"\"\n Instantiate a VQGAN_CLIP model. If you want to use a custom VQGAN model, pass it as vqgan.\n \"\"\"\n super().__init__()\n self.latent = None\n self.device = device if device else get_device()\n if vqgan:\n self.vqgan = vqgan\n else:\n self.vqgan = load_vqgan(self.device, conf_path=vqgan_config, ckpt_path=vqgan_checkpoint)\n self.vqgan.eval()\n if clip:\n self.clip = clip\n else:\n self.clip = CLIPModel.from_pretrained(\"openai/clip-vit-base-patch32\")\n self.clip.to(self.device)\n self.clip_preprocessor = ProcessorGradientFlow(device=self.device)\n\n self.iterations = iterations\n self.lr = lr\n self.log = log\n self.make_grid = make_grid\n self.return_val = return_val\n self.quantize = quantize\n self.latent_dim = self.vqgan.decoder.z_shape", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_chart_releases_v3_get(\n self,\n app_version_branch: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to the app's mainline branch if no other app version info is present\")] = None,\n app_version_commit: Optional[StrictStr] = None,\n app_version_exact: Optional[StrictStr] = None,\n app_version_follow_chart_release: Optional[StrictStr] = None,\n app_version_reference: Optional[StrictStr] = None,\n app_version_resolver: Annotated[Optional[StrictStr], Field(description=\"// When creating, will default to automatically reference any provided app version fields\")] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n chart_version_exact: Optional[StrictStr] = None,\n chart_version_follow_chart_release: Optional[StrictStr] = None,\n chart_version_reference: Optional[StrictStr] = None,\n chart_version_resolver: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to automatically reference any provided chart version\")] = None,\n cluster: Annotated[Optional[StrictStr], Field(description=\"When creating, will default the environment's default cluster, if provided. Either this or environment must be provided.\")] = None,\n created_at: Optional[datetime] = None,\n destination_type: Annotated[Optional[StrictStr], Field(description=\"Calculated field\")] = None,\n environment: Annotated[Optional[StrictStr], Field(description=\"Either this or cluster must be provided.\")] = None,\n helmfile_ref: Optional[StrictStr] = None,\n helmfile_ref_enabled: Optional[StrictBool] = None,\n id: Optional[StrictInt] = None,\n included_in_bulk_changesets: Optional[StrictBool] = None,\n name: Annotated[Optional[StrictStr], Field(description=\"When creating, will be calculated if left empty\")] = None,\n namespace: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to the environment's default namespace, if provided\")] = None,\n pagerduty_integration: Optional[StrictStr] = None,\n port: Annotated[Optional[StrictInt], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n protocol: Annotated[Optional[StrictStr], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n resolved_at: Optional[datetime] = None,\n subdomain: Annotated[Optional[StrictStr], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many ChartReleases are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned ChartReleases (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockChartReleaseV3]:\n \"\"\"List ChartReleases matching a filter\n\n List ChartReleases matching a filter.\n\n :param app_version_branch: When creating, will default to the app's mainline branch if no other app version info is present\n :type app_version_branch: str\n :param app_version_commit:\n :type app_version_commit: str\n :param app_version_exact:\n :type app_version_exact: str\n :param app_version_follow_chart_release:\n :type app_version_follow_chart_release: str\n :param app_version_reference:\n :type app_version_reference: str\n :param app_version_resolver: // When creating, will default to automatically reference any provided app version fields\n :type app_version_resolver: str\n :param chart: Required when creating\n :type chart: str\n :param chart_version_exact:\n :type chart_version_exact: str\n :param chart_version_follow_chart_release:\n :type chart_version_follow_chart_release: str\n :param chart_version_reference:\n :type chart_version_reference: str\n :param chart_version_resolver: When creating, will default to automatically reference any provided chart version\n :type chart_version_resolver: str\n :param cluster: When creating, will default the environment's default cluster, if provided. Either this or environment must be provided.\n :type cluster: str\n :param created_at:\n :type created_at: datetime\n :param destination_type: Calculated field\n :type destination_type: str\n :param environment: Either this or cluster must be provided.\n :type environment: str\n :param helmfile_ref:\n :type helmfile_ref: str\n :param helmfile_ref_enabled:\n :type helmfile_ref_enabled: bool\n :param id:\n :type id: int\n :param included_in_bulk_changesets:\n :type included_in_bulk_changesets: bool\n :param name: When creating, will be calculated if left empty\n :type name: str\n :param namespace: When creating, will default to the environment's default namespace, if provided\n :type namespace: str\n :param pagerduty_integration:\n :type pagerduty_integration: str\n :param port: When creating, will use the chart's default if left empty\n :type port: int\n :param protocol: When creating, will use the chart's default if left empty\n :type protocol: str\n :param resolved_at:\n :type resolved_at: datetime\n :param subdomain: When creating, will use the chart's default if left empty\n :type subdomain: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many ChartReleases are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned ChartReleases (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_chart_releases_v3_get_serialize(\n app_version_branch=app_version_branch,\n app_version_commit=app_version_commit,\n app_version_exact=app_version_exact,\n app_version_follow_chart_release=app_version_follow_chart_release,\n app_version_reference=app_version_reference,\n app_version_resolver=app_version_resolver,\n chart=chart,\n chart_version_exact=chart_version_exact,\n chart_version_follow_chart_release=chart_version_follow_chart_release,\n chart_version_reference=chart_version_reference,\n chart_version_resolver=chart_version_resolver,\n cluster=cluster,\n created_at=created_at,\n destination_type=destination_type,\n environment=environment,\n helmfile_ref=helmfile_ref,\n helmfile_ref_enabled=helmfile_ref_enabled,\n id=id,\n included_in_bulk_changesets=included_in_bulk_changesets,\n name=name,\n namespace=namespace,\n pagerduty_integration=pagerduty_integration,\n port=port,\n protocol=protocol,\n resolved_at=resolved_at,\n subdomain=subdomain,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartReleaseV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XMOD_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n lang_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns: `transformers.modeling_outputs.CausalLMOutputWithCrossAttentions` or `tuple(torch.FloatTensor)`\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, XmodForCausalLM, AutoConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"FacebookAI/xlm-roberta-base\")\n >>> config = AutoConfig.from_pretrained(\"facebook/xmod-base\")\n >>> config.is_decoder = True\n >>> model = XmodForCausalLM.from_pretrained(\"facebook/xmod-base\", config=config)\n >>> model.set_default_language(\"en_XX\")\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.roberta(\n input_ids,\n lang_ids=lang_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def run_tests(\n self,\n tests: Union[str, List[str]],\n parse_all: bool = True,\n comment: typing.Optional[Union[\"ParserElement\", str]] = \"#\",\n full_dump: bool = True,\n print_results: bool = True,\n failure_tests: bool = False,\n post_parse: typing.Optional[Callable[[str, ParseResults], str]] = None,\n file: typing.Optional[TextIO] = None,\n with_line_numbers: bool = False,\n *,\n parseAll: bool = True,\n fullDump: bool = True,\n printResults: bool = True,\n failureTests: bool = False,\n postParse: typing.Optional[Callable[[str, ParseResults], str]] = None,\n ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:\n \"\"\"\n Execute the parse expression on a series of test strings, showing each\n test, the parsed results or where the parse failed. Quick and easy way to\n run a parse expression against a list of sample strings.\n\n Parameters:\n\n - ``tests`` - a list of separate test strings, or a multiline string of test strings\n - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test\n string; pass None to disable comment filtering\n - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;\n if False, only dump nested list\n - ``print_results`` - (default= ``True``) prints test output to stdout\n - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing\n - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as\n `fn(test_string, parse_results)` and returns a string to be added to the test output\n - ``file`` - (default= ``None``) optional file-like object to which test output will be written;\n if None, will default to ``sys.stdout``\n - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers\n\n Returns: a (success, results) tuple, where success indicates that all tests succeeded\n (or failed if ``failure_tests`` is True), and the results contain a list of lines of each\n test's output\n\n Example::\n\n number_expr = pyparsing_common.number.copy()\n\n result = number_expr.run_tests('''\n # unsigned integer\n 100\n # negative integer\n -100\n # float with scientific notation\n 6.02e23\n # integer with scientific notation\n 1e-12\n ''')\n print(\"Success\" if result[0] else \"Failed!\")\n\n result = number_expr.run_tests('''\n # stray character\n 100Z\n # missing leading digit before '.'\n -.100\n # too many '.'\n 3.14.159\n ''', failure_tests=True)\n print(\"Success\" if result[0] else \"Failed!\")\n\n prints::\n\n # unsigned integer\n 100\n [100]\n\n # negative integer\n -100\n [-100]\n\n # float with scientific notation\n 6.02e23\n [6.02e+23]\n\n # integer with scientific notation\n 1e-12\n [1e-12]\n\n Success\n\n # stray character\n 100Z\n ^\n FAIL: Expected end of text (at char 3), (line:1, col:4)\n\n # missing leading digit before '.'\n -.100\n ^\n FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)\n\n # too many '.'\n 3.14.159\n ^\n FAIL: Expected end of text (at char 4), (line:1, col:5)\n\n Success\n\n Each test string must be on a single line. If you want to test a string that spans multiple\n lines, create a test like this::\n\n expr.run_tests(r\"this is a test\\\\n of strings that spans \\\\n 3 lines\")\n\n (Note that this is a raw string literal, you must include the leading ``'r'``.)\n \"\"\"\n from .testing import pyparsing_test\n\n parseAll = parseAll and parse_all\n fullDump = fullDump and full_dump\n printResults = printResults and print_results\n failureTests = failureTests or failure_tests\n postParse = postParse or post_parse\n if isinstance(tests, str_type):\n tests = typing.cast(str, tests)\n line_strip = type(tests).strip\n tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]\n comment_specified = comment is not None\n if comment_specified:\n if isinstance(comment, str_type):\n comment = typing.cast(str, comment)\n comment = Literal(comment)\n comment = typing.cast(ParserElement, comment)\n if file is None:\n file = sys.stdout\n print_ = file.write\n\n result: Union[ParseResults, Exception]\n allResults: List[Tuple[str, Union[ParseResults, Exception]]] = []\n comments: List[str] = []\n success = True\n NL = Literal(r\"\\n\").add_parse_action(replace_with(\"\\n\")).ignore(quoted_string)\n BOM = \"\\ufeff\"\n for t in tests:\n if comment_specified and comment.matches(t, False) or comments and not t:\n comments.append(\n pyparsing_test.with_line_numbers(t) if with_line_numbers else t\n )\n continue\n if not t:\n continue\n out = [\n \"\\n\" + \"\\n\".join(comments) if comments else \"\",\n pyparsing_test.with_line_numbers(t) if with_line_numbers else t,\n ]\n comments = []\n try:\n # convert newline marks to actual newlines, and strip leading BOM if present\n t = NL.transform_string(t.lstrip(BOM))\n result = self.parse_string(t, parse_all=parseAll)\n except ParseBaseException as pe:\n fatal = \"(FATAL)\" if isinstance(pe, ParseFatalException) else \"\"\n out.append(pe.explain())\n out.append(\"FAIL: \" + str(pe))\n if ParserElement.verbose_stacktrace:\n out.extend(traceback.format_tb(pe.__traceback__))\n success = success and failureTests\n result = pe\n except Exception as exc:\n out.append(f\"FAIL-EXCEPTION: {type(exc).__name__}: {exc}\")\n if ParserElement.verbose_stacktrace:\n out.extend(traceback.format_tb(exc.__traceback__))\n success = success and failureTests\n result = exc\n else:\n success = success and not failureTests\n if postParse is not None:\n try:\n pp_value = postParse(t, result)\n if pp_value is not None:\n if isinstance(pp_value, ParseResults):\n out.append(pp_value.dump())\n else:\n out.append(str(pp_value))\n else:\n out.append(result.dump())\n except Exception as e:\n out.append(result.dump(full=fullDump))\n out.append(\n f\"{postParse.__name__} failed: {type(e).__name__}: {e}\"\n )\n else:\n out.append(result.dump(full=fullDump))\n out.append(\"\")\n\n if printResults:\n print_(\"\\n\".join(out))\n\n allResults.append((t, result))\n\n return success, allResults", "smellKey": "S107", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=5,\n num_channels=1,\n is_training=False,\n intermediate_size=40,\n hidden_size=32,\n num_filters=8,\n num_residual_layers=1,\n upsampling_ratios=[8, 4],\n codebook_size=64,\n vector_quantization_hidden_dimension=64,\n codebook_dim=64,\n upsample_groups=32,\n num_hidden_layers=2,\n num_attention_heads=2,\n num_key_value_heads=2,\n sliding_window=4,\n use_cache=False,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.intermediate_size = intermediate_size\n self.hidden_size = hidden_size\n self.num_filters = num_filters\n self.num_residual_layers = num_residual_layers\n self.upsampling_ratios = upsampling_ratios\n self.codebook_size = codebook_size\n self.vector_quantization_hidden_dimension = vector_quantization_hidden_dimension\n self.codebook_dim = codebook_dim\n self.upsample_groups = upsample_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.sliding_window = sliding_window\n self.use_cache = use_cache", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=51865,\n num_mel_bins=80,\n encoder_layers=4,\n encoder_attention_heads=6,\n decoder_layers=4,\n decoder_attention_heads=6,\n decoder_ffn_dim=1536,\n encoder_ffn_dim=1536,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n decoder_start_token_id=50257,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=384,\n dropout=0.0,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n scale_embedding=False,\n max_source_positions=1500,\n max_target_positions=448,\n pad_token_id=50256,\n bos_token_id=50256,\n eos_token_id=50256,\n suppress_tokens=None,\n begin_suppress_tokens=[220, 50256],\n use_weighted_layer_sum=False,\n classifier_proj_size=256,\n apply_spec_augment=False,\n mask_time_prob=0.05,\n mask_time_length=10,\n mask_time_min_masks=2,\n mask_feature_prob=0.0,\n mask_feature_length=10,\n mask_feature_min_masks=0,\n median_filter_width=7,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.num_mel_bins = num_mel_bins\n self.d_model = d_model\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_ffn_dim = encoder_ffn_dim\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n\n # Audio Classification-specific parameters. Feel free to ignore for other classes.\n self.classifier_proj_size = classifier_proj_size\n self.use_weighted_layer_sum = use_weighted_layer_sum\n\n # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779\n self.apply_spec_augment = apply_spec_augment\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.mask_time_min_masks = mask_time_min_masks\n self.mask_feature_prob = mask_feature_prob\n self.mask_feature_length = mask_feature_length\n self.mask_feature_min_masks = mask_feature_min_masks\n\n self.median_filter_width = median_filter_width\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n suppress_tokens=suppress_tokens,\n begin_suppress_tokens=begin_suppress_tokens,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden layers\n is_training=True,\n use_labels=False,\n vocab_size=200,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n input_channels=1,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n max_source_positions=30,\n max_target_positions=40,\n bos_token_id=98,\n eos_token_id=98,\n pad_token_id=0,\n num_mel_bins=80,\n decoder_start_token_id=85,\n num_conv_layers=1,\n suppress_tokens=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.input_channels = input_channels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_mel_bins = num_mel_bins\n self.max_position_embeddings = max_position_embeddings\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.num_conv_layers = num_conv_layers\n self.suppress_tokens = suppress_tokens", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _group_attributes_side_query(\n events_only_search_results: CursorResult[Group],\n builder: Callable[[], BaseQuerySet[Group, Group]],\n projects: Sequence[Project],\n retention_window_start: datetime | None,\n group_queryset: BaseQuerySet[Group, Group],\n environments: Sequence[Environment] | None = None,\n sort_by: str = \"date\",\n limit: int = 100,\n cursor: Cursor | None = None,\n count_hits: bool = False,\n paginator_options: Mapping[str, Any] | None = None,\n search_filters: Sequence[SearchFilter] | None = None,\n date_from: datetime | None = None,\n date_to: datetime | None = None,\n max_hits: int | None = None,\n referrer: str | None = None,\n actor: Any | None = None,\n aggregate_kwargs: TrendsSortWeights | None = None,\n) -> None:\n def __run_joined_query_and_log_metric(\n events_only_search_results: CursorResult[Group],\n builder: Callable[[], BaseQuerySet[Group, Group]],\n projects: Sequence[Project],\n retention_window_start: datetime | None,\n group_queryset: BaseQuerySet[Group, Group],\n environments: Sequence[Environment] | None = None,\n sort_by: str = \"date\",\n limit: int = 100,\n cursor: Cursor | None = None,\n count_hits: bool = False,\n paginator_options: Mapping[str, Any] | None = None,\n search_filters: Sequence[SearchFilter] | None = None,\n date_from: datetime | None = None,\n date_to: datetime | None = None,\n max_hits: int | None = None,\n referrer: str | None = None,\n actor: Any | None = None,\n aggregate_kwargs: TrendsSortWeights | None = None,\n ) -> None:\n from sentry.utils import metrics\n\n try:\n from sentry.search.snuba.executors import GroupAttributesPostgresSnubaQueryExecutor\n\n executor = GroupAttributesPostgresSnubaQueryExecutor()\n with metrics.timer(\"snuba.search.group_attributes_joined.duration\"):\n cursor_results = executor.query(\n projects,\n retention_window_start,\n builder(),\n environments,\n sort_by,\n limit,\n cursor,\n count_hits,\n paginator_options,\n search_filters,\n date_from,\n date_to,\n max_hits,\n referrer,\n actor,\n aggregate_kwargs,\n )\n joined_hits = len(cursor_results.results)\n events_only_search_hits = len(events_only_search_results.results)\n if events_only_search_hits > 0:\n if joined_hits == events_only_search_hits:\n comparison = \"equal\"\n elif joined_hits > events_only_search_hits:\n comparison = \"greater\"\n else:\n # the joined query shouldn't have fewer hits since the query is deliberately less restrictive\n comparison = \"less\"\n\n metrics.incr(\n \"snuba.search.group_attributes_joined.events_compared\",\n tags={\"comparison\": comparison},\n )\n\n metrics.incr(\"snuba.search.group_attributes_joined.query\", tags={\"exception\": \"none\"})\n except InvalidQueryForExecutor as e:\n logger.info(\n \"unsupported query received in GroupAttributesPostgresSnubaQueryExecutor\",\n exc_info=True,\n )\n metrics.incr(\n \"snuba.search.group_attributes_joined.query\",\n tags={\n \"exception\": f\"{type(e).__module__}.{type(e).__qualname__}\",\n },\n )\n except Exception as e:\n logger.warning(\n \"failed to load side query from _group_attributes_side_query\", exc_info=True\n )\n metrics.incr(\n \"snuba.search.group_attributes_joined.query\",\n tags={\n \"exception\": f\"{type(e).__module__}.{type(e).__qualname__}\",\n },\n )\n finally:\n # since this code is running in a thread and django establishes a connection per thread, we need to\n # explicitly close the connection assigned to this thread to avoid linger connections\n from django.db import connection\n\n connection.close()\n\n try:\n _side_query_pool.submit(\n __run_joined_query_and_log_metric,\n events_only_search_results,\n builder,\n projects,\n retention_window_start,\n group_queryset,\n environments,\n sort_by,\n limit,\n cursor,\n count_hits,\n paginator_options,\n search_filters,\n date_from,\n date_to,\n max_hits,\n referrer,\n actor,\n aggregate_kwargs,\n )\n except Exception:\n logger.exception(\"failed to submit group-attributes search side-query to pool\")", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _api_environments_v3_get_serialize(\n self,\n auto_populate_chart_releases,\n base,\n base_domain,\n created_at,\n default_cluster,\n default_namespace,\n delete_after,\n description,\n enable_janitor,\n helmfile_ref,\n id,\n lifecycle,\n name,\n name_prefixes_domain,\n offline,\n offline_schedule_begin_enabled,\n offline_schedule_begin_time,\n offline_schedule_end_enabled,\n offline_schedule_end_time,\n offline_schedule_end_weekends,\n owner,\n pact_identifier,\n pagerduty_integration,\n prevent_deletion,\n required_role,\n requires_suitability,\n template_environment,\n unique_resource_prefix,\n updated_at,\n values_name,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if auto_populate_chart_releases is not None:\n \n _query_params.append(('autoPopulateChartReleases', auto_populate_chart_releases))\n \n if base is not None:\n \n _query_params.append(('base', base))\n \n if base_domain is not None:\n \n _query_params.append(('baseDomain', base_domain))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if default_cluster is not None:\n \n _query_params.append(('defaultCluster', default_cluster))\n \n if default_namespace is not None:\n \n _query_params.append(('defaultNamespace', default_namespace))\n \n if delete_after is not None:\n if isinstance(delete_after, datetime):\n _query_params.append(\n (\n 'deleteAfter',\n delete_after.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('deleteAfter', delete_after))\n \n if description is not None:\n \n _query_params.append(('description', description))\n \n if enable_janitor is not None:\n \n _query_params.append(('enableJanitor', enable_janitor))\n \n if helmfile_ref is not None:\n \n _query_params.append(('helmfileRef', helmfile_ref))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if lifecycle is not None:\n \n _query_params.append(('lifecycle', lifecycle))\n \n if name is not None:\n \n _query_params.append(('name', name))\n \n if name_prefixes_domain is not None:\n \n _query_params.append(('namePrefixesDomain', name_prefixes_domain))\n \n if offline is not None:\n \n _query_params.append(('offline', offline))\n \n if offline_schedule_begin_enabled is not None:\n \n _query_params.append(('offlineScheduleBeginEnabled', offline_schedule_begin_enabled))\n \n if offline_schedule_begin_time is not None:\n if isinstance(offline_schedule_begin_time, datetime):\n _query_params.append(\n (\n 'offlineScheduleBeginTime',\n offline_schedule_begin_time.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('offlineScheduleBeginTime', offline_schedule_begin_time))\n \n if offline_schedule_end_enabled is not None:\n \n _query_params.append(('offlineScheduleEndEnabled', offline_schedule_end_enabled))\n \n if offline_schedule_end_time is not None:\n if isinstance(offline_schedule_end_time, datetime):\n _query_params.append(\n (\n 'offlineScheduleEndTime',\n offline_schedule_end_time.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('offlineScheduleEndTime', offline_schedule_end_time))\n \n if offline_schedule_end_weekends is not None:\n \n _query_params.append(('offlineScheduleEndWeekends', offline_schedule_end_weekends))\n \n if owner is not None:\n \n _query_params.append(('owner', owner))\n \n if pact_identifier is not None:\n \n _query_params.append(('PactIdentifier', pact_identifier))\n \n if pagerduty_integration is not None:\n \n _query_params.append(('pagerdutyIntegration', pagerduty_integration))\n \n if prevent_deletion is not None:\n \n _query_params.append(('preventDeletion', prevent_deletion))\n \n if required_role is not None:\n \n _query_params.append(('requiredRole', required_role))\n \n if requires_suitability is not None:\n \n _query_params.append(('requiresSuitability', requires_suitability))\n \n if template_environment is not None:\n \n _query_params.append(('templateEnvironment', template_environment))\n \n if unique_resource_prefix is not None:\n \n _query_params.append(('uniqueResourcePrefix', unique_resource_prefix))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if values_name is not None:\n \n _query_params.append(('valuesName', values_name))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/environments/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@validate_call\n def api_charts_v3_get_without_preload_content(\n self,\n app_image_git_main_branch: Optional[StrictStr] = None,\n app_image_git_repo: Optional[StrictStr] = None,\n chart_exposes_endpoint: Annotated[Optional[StrictBool], Field(description=\"Indicates if the default subdomain, protocol, and port fields are relevant for this chart\")] = None,\n chart_repo: Optional[StrictStr] = None,\n created_at: Optional[datetime] = None,\n default_port: Optional[StrictInt] = None,\n default_protocol: Optional[StrictStr] = None,\n default_subdomain: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to the name of the chart\")] = None,\n description: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n name: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n pact_participant: Optional[StrictBool] = None,\n playbook_url: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Charts are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Charts (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> RESTResponseType:\n \"\"\"List Charts matching a filter\n\n List Charts matching a filter.\n\n :param app_image_git_main_branch:\n :type app_image_git_main_branch: str\n :param app_image_git_repo:\n :type app_image_git_repo: str\n :param chart_exposes_endpoint: Indicates if the default subdomain, protocol, and port fields are relevant for this chart\n :type chart_exposes_endpoint: bool\n :param chart_repo:\n :type chart_repo: str\n :param created_at:\n :type created_at: datetime\n :param default_port:\n :type default_port: int\n :param default_protocol:\n :type default_protocol: str\n :param default_subdomain: When creating, will default to the name of the chart\n :type default_subdomain: str\n :param description:\n :type description: str\n :param id:\n :type id: int\n :param name: Required when creating\n :type name: str\n :param pact_participant:\n :type pact_participant: bool\n :param playbook_url:\n :type playbook_url: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many Charts are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned Charts (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_charts_v3_get_serialize(\n app_image_git_main_branch=app_image_git_main_branch,\n app_image_git_repo=app_image_git_repo,\n chart_exposes_endpoint=chart_exposes_endpoint,\n chart_repo=chart_repo,\n created_at=created_at,\n default_port=default_port,\n default_protocol=default_protocol,\n default_subdomain=default_subdomain,\n description=description,\n id=id,\n name=name,\n pact_participant=pact_participant,\n playbook_url=playbook_url,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n return response_data.response", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n hidden_size: int = 1280,\n hidden_act: str = \"gelu\",\n num_hidden_layers: int = 32,\n num_global_layers: int = 8,\n num_attention_heads: int = 16,\n num_channels: int = 3,\n intermediate_size: int = 5120,\n vision_output_dim: int = 7680,\n image_size: int = 448,\n patch_size: int = 14,\n norm_eps: float = 1e-5,\n max_num_tiles: int = 4,\n intermediate_layers_indices: Optional[List[int]] = None,\n supported_aspect_ratios: Optional[List[List[int]]] = None,\n initializer_range: float = 0.02,\n **kwargs,\n ):\n if supported_aspect_ratios is None:\n if max_num_tiles != 4:\n raise ValueError(\"max_num_tiles must be 4 for default supported aspect ratios\")\n supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]\n\n if intermediate_layers_indices is None:\n intermediate_layers_indices = [3, 7, 15, 23, 30]\n\n self.hidden_size = hidden_size\n self.hidden_act = hidden_act\n self.num_hidden_layers = num_hidden_layers\n self.num_channels = num_channels\n self.intermediate_size = intermediate_size\n self.image_size = image_size\n self.vision_output_dim = vision_output_dim\n self.patch_size = patch_size\n self.intermediate_layers_indices = intermediate_layers_indices\n self.num_global_layers = num_global_layers\n self.max_num_tiles = max_num_tiles\n self.norm_eps = norm_eps\n self.attention_heads = num_attention_heads\n self.supported_aspect_ratios = supported_aspect_ratios\n self.initializer_range = initializer_range\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n bos_token_id=0,\n eos_token_id=2,\n max_xpath_tag_unit_embeddings=256,\n max_xpath_subs_unit_embeddings=1024,\n tag_pad_id=216,\n subs_pad_id=1001,\n xpath_unit_hidden_size=32,\n max_depth=50,\n position_embedding_type=\"absolute\",\n use_cache=True,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n **kwargs,\n )\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout\n # additional properties\n self.max_depth = max_depth\n self.max_xpath_tag_unit_embeddings = max_xpath_tag_unit_embeddings\n self.max_xpath_subs_unit_embeddings = max_xpath_subs_unit_embeddings\n self.tag_pad_id = tag_pad_id\n self.subs_pad_id = subs_pad_id\n self.xpath_unit_hidden_size = xpath_unit_hidden_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)\n @unpack_inputs\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: tf.Tensor | None = None,\n position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n inputs_embeds: tf.Tensor | None = None,\n encoder_embeds: tf.Tensor | None = None,\n encoder_hidden_states: tf.Tensor | None = None,\n encoder_attention_mask: tf.Tensor | None = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n use_cache: bool | None = None,\n output_attentions: bool | None = None,\n output_hidden_states: bool | None = None,\n return_dict: bool | None = None,\n is_decoder: bool = False,\n training: bool = False,\n ) -> Tuple[tf.Tensor] | TFBaseModelOutputWithPoolingAndCrossAttentions:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if is_decoder:\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n else:\n use_cache = False\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = shape_list(input_ids)\n batch_size, seq_length = input_shape\n elif inputs_embeds is not None:\n input_shape = shape_list(inputs_embeds)[:-1]\n batch_size, seq_length = input_shape\n elif encoder_embeds is not None:\n input_shape = shape_list(encoder_embeds)[:-1]\n batch_size, seq_length = input_shape\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds or encoder_embeds\")\n\n # past_key_values_length\n past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0\n\n if attention_mask is None:\n attention_mask = tf.ones(((batch_size, seq_length + past_key_values_length)))\n\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n extended_attention_mask: tf.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, is_decoder)\n\n # If a 2D or 3D attention mask is provided for the cross-attention\n # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]\n if encoder_hidden_states is not None:\n if isinstance(encoder_hidden_states, list):\n encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states[0])\n else:\n encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states)\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n\n if isinstance(encoder_attention_mask, list):\n encoder_extended_attention_mask = [invert_attention_mask(mask) for mask in encoder_attention_mask]\n elif encoder_attention_mask is None:\n encoder_attention_mask = tf.ones(encoder_hidden_shape)\n encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)\n else:\n encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)\n else:\n encoder_extended_attention_mask = None\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n if encoder_embeds is None:\n embedding_output = self.embeddings(\n input_ids=input_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n past_key_values_length=past_key_values_length,\n )\n else:\n embedding_output = encoder_embeds\n\n encoder_outputs = self.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_extended_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output) if self.pooler is not None else None\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return TFBaseModelOutputWithPoolingAndCrossAttentions(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n past_key_values=encoder_outputs.past_key_values,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n cross_attentions=encoder_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,\n config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for\n labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, UMT5ForConditionalGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/umt5-small\")\n >>> model = UMT5ForConditionalGeneration.from_pretrained(\"google/umt5-small\")\n\n >>> # training\n >>> input_ids = tokenizer(\"The <extra_id_0> walks in <extra_id_1> park\", return_tensors=\"pt\").input_ids\n >>> labels = tokenizer(\"<extra_id_0> cute dog <extra_id_1> the <extra_id_2>\", return_tensors=\"pt\").input_ids\n >>> outputs = model(input_ids=input_ids, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> input_ids = tokenizer(\"Studies have shown that <extra_id_0> good for you\", return_tensors=\"pt\").input_ids\n >>> outputs = model.generate(input_ids)\n >>> tokenizer.decode(outputs[0], skip_special_tokens=True)\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n # Convert encoder inputs in embeddings if needed\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n if self.config.tie_word_embeddings:\n # Rescale output before projecting on vocab\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\n sequence_output = sequence_output * (self.model_dim**-0.5)\n\n lm_logits = self.lm_head(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-100)\n # move labels to correct device to enable PP\n labels = labels.to(lm_logits.device)\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n patch_size=4,\n num_channels=3,\n embed_dim=64,\n depths=[3, 4, 6, 5],\n num_heads=[2, 4, 8, 16],\n kernel_size=7,\n mlp_ratio=3.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n layer_scale_init_value=0.0,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_layers = len(depths)\n self.num_heads = num_heads\n self.kernel_size = kernel_size\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel\n # this indicates the channel dimension after the last stage of the model\n self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))\n self.layer_scale_init_value = layer_scale_init_value\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MMBT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_modal,\n input_ids=None,\n modal_start_tokens=None,\n modal_end_tokens=None,\n attention_mask=None,\n token_type_ids=None,\n modal_token_type_ids=None,\n position_ids=None,\n modal_position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n Returns:\n\n Examples:\n\n ```python\n # For example purposes. Not runnable.\n transformer = BertModel.from_pretrained(\"google-bert/bert-base-uncased\")\n encoder = ImageEncoder(args)\n mmbt = MMBTModel(config, transformer, encoder)\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_txt_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_txt_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n modal_embeddings = self.modal_encoder(\n input_modal,\n start_token=modal_start_tokens,\n end_token=modal_end_tokens,\n position_ids=modal_position_ids,\n token_type_ids=modal_token_type_ids,\n )\n\n input_modal_shape = modal_embeddings.size()[:-1]\n\n if token_type_ids is None:\n token_type_ids = torch.ones(input_txt_shape, dtype=torch.long, device=device)\n\n txt_embeddings = self.transformer.embeddings(\n input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds\n )\n\n embedding_output = torch.cat([modal_embeddings, txt_embeddings], 1)\n\n input_shape = embedding_output.size()[:-1]\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device)\n else:\n attention_mask = torch.cat(\n [torch.ones(input_modal_shape, device=device, dtype=torch.long), attention_mask], dim=1\n )\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(input_shape, device=device)\n else:\n encoder_attention_mask = torch.cat(\n [torch.ones(input_modal_shape, device=device), encoder_attention_mask], dim=1\n )\n\n extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)\n encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n encoder_outputs = self.transformer.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_extended_attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = encoder_outputs[0]\n pooled_output = self.transformer.pooler(sequence_output)\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return BaseModelOutputWithPooling(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n type_sequence_label_size=10,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n\n # in Dinov2, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=128,\n num_hidden_layers=4,\n intermediate_size=256,\n ema_projection_size=16,\n bidirectional=True,\n shared_representation_size=64,\n use_chunking=False,\n chunk_size=-1,\n truncation=None,\n normalize_before_mega=True,\n normalization_type=\"scalenorm\",\n norm_affine=True,\n activation=\"silu\",\n attention_activation=\"softmax\",\n dropout_prob=0.1,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n use_feature_dropout=False,\n use_normalized_ffn=True,\n nffn_hidden_size=256,\n normalize_before_ffn=True,\n nffn_activation_dropout_prob=0.1,\n max_positions=2048,\n add_token_type_embeddings=False,\n type_vocab_size=2,\n initializer_range=0.02,\n ema_delta_alpha_range=0.2,\n ema_beta_range=0.02,\n ema_gamma_omega_range=1.0,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n relative_positional_bias=\"rotary\",\n classifier_dropout=None,\n use_cache=True,\n add_lm_hidden_dense_layer=True,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.activation = activation\n self.attention_activation = attention_activation\n self.intermediate_size = intermediate_size\n self.ema_projection_size = ema_projection_size\n self.bidirectional = bidirectional\n self.shared_representation_size = shared_representation_size\n self.use_chunking = use_chunking\n self.chunk_size = chunk_size\n self.truncation = truncation\n self.normalize_before_mega = normalize_before_mega\n self.normalization_type = normalization_type\n self.norm_affine = norm_affine\n self.dropout_prob = dropout_prob\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.use_feature_dropout = use_feature_dropout\n self.use_normalized_ffn = use_normalized_ffn\n self.nffn_hidden_size = nffn_hidden_size\n self.normalize_before_ffn = normalize_before_ffn\n self.nffn_activation_dropout_prob = nffn_activation_dropout_prob\n self.max_positions = max_positions\n self.add_token_type_embeddings = add_token_type_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.ema_delta_alpha_range = ema_delta_alpha_range\n self.ema_beta_range = ema_beta_range\n self.ema_gamma_omega_range = ema_gamma_omega_range\n self.relative_positional_bias = relative_positional_bias\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout\n self.add_lm_hidden_dense_layer = add_lm_hidden_dense_layer\n self.num_attention_heads = 1 # not used but required by Hugging Face", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def modelformset_factory(\n model,\n form=ModelForm,\n formfield_callback=None,\n formset=BaseModelFormSet,\n extra=1,\n can_delete=False,\n can_order=False,\n max_num=None,\n fields=None,\n exclude=None,\n widgets=None,\n validate_max=False,\n localized_fields=None,\n labels=None,\n help_texts=None,\n error_messages=None,\n min_num=None,\n validate_min=False,\n field_classes=None,\n absolute_max=None,\n can_delete_extra=True,\n renderer=None,\n edit_only=False,\n):\n \"\"\"Return a FormSet class for the given Django model class.\"\"\"\n meta = getattr(form, \"Meta\", None)\n if (\n getattr(meta, \"fields\", fields) is None\n and getattr(meta, \"exclude\", exclude) is None\n ):\n raise ImproperlyConfigured(\n \"Calling modelformset_factory without defining 'fields' or \"\n \"'exclude' explicitly is prohibited.\"\n )\n\n form = modelform_factory(\n model,\n form=form,\n fields=fields,\n exclude=exclude,\n formfield_callback=formfield_callback,\n widgets=widgets,\n localized_fields=localized_fields,\n labels=labels,\n help_texts=help_texts,\n error_messages=error_messages,\n field_classes=field_classes,\n )\n FormSet = formset_factory(\n form,\n formset,\n extra=extra,\n min_num=min_num,\n max_num=max_num,\n can_order=can_order,\n can_delete=can_delete,\n validate_min=validate_min,\n validate_max=validate_max,\n absolute_max=absolute_max,\n can_delete_extra=can_delete_extra,\n renderer=renderer,\n )\n FormSet.model = model\n FormSet.edit_only = edit_only\n return FormSet", "smellKey": "S107", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def call_boxes(\n self,\n text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],\n text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,\n boxes: Union[List[List[int]], List[List[List[int]]]] = None,\n word_labels: Optional[Union[List[int], List[List[int]]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of\n sequences with word-level normalized bounding boxes and optional labels.\n\n Args:\n text (`str`, `List[str]`, `List[List[str]]`):\n The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings\n (words of a single example or questions of a batch of examples) or a list of list of strings (batch of\n words).\n text_pair (`List[str]`, `List[List[str]]`):\n The sequence or batch of sequences to be encoded. Each sequence should be a list of strings\n (pretokenized string).\n boxes (`List[List[int]]`, `List[List[List[int]]]`):\n Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.\n word_labels (`List[int]`, `List[List[int]]`, *optional*):\n Word-level integer labels (for token classification tasks such as FUNSD, CORD).\n \"\"\"\n\n # Input type checking for clearer error\n def _is_valid_text_input(t):\n if isinstance(t, str):\n # Strings are fine\n return True\n elif isinstance(t, (list, tuple)):\n # List are fine as long as they are...\n if len(t) == 0:\n # ... empty\n return True\n elif isinstance(t[0], str):\n # ... list of strings\n return True\n elif isinstance(t[0], (list, tuple)):\n # ... list with an empty list or with a list of strings\n return len(t[0]) == 0 or isinstance(t[0][0], str)\n else:\n return False\n else:\n return False\n\n if text_pair is not None:\n # in case text + text_pair are provided, text = questions, text_pair = words\n if not _is_valid_text_input(text):\n raise ValueError(\"text input must of type `str` (single example) or `List[str]` (batch of examples). \")\n if not isinstance(text_pair, (list, tuple)):\n raise ValueError(\n \"words must of type `List[str]` (single pretokenized example), \"\n \"or `List[List[str]]` (batch of pretokenized examples).\"\n )\n else:\n # in case only text is provided => must be words\n if not isinstance(text, (list, tuple)):\n raise ValueError(\n \"Words must of type `List[str]` (single pretokenized example), \"\n \"or `List[List[str]]` (batch of pretokenized examples).\"\n )\n\n if text_pair is not None:\n is_batched = isinstance(text, (list, tuple))\n else:\n is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))\n\n words = text if text_pair is None else text_pair\n if boxes is None:\n raise ValueError(\"You must provide corresponding bounding boxes\")\n if is_batched:\n if len(words) != len(boxes):\n raise ValueError(\"You must provide words and boxes for an equal amount of examples\")\n for words_example, boxes_example in zip(words, boxes):\n if len(words_example) != len(boxes_example):\n raise ValueError(\"You must provide as many words as there are bounding boxes\")\n else:\n if len(words) != len(boxes):\n raise ValueError(\"You must provide as many words as there are bounding boxes\")\n\n if is_batched:\n if text_pair is not None and len(text) != len(text_pair):\n raise ValueError(\n f\"batch length of `text`: {len(text)} does not match batch length of `text_pair`:\"\n f\" {len(text_pair)}.\"\n )\n batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text\n is_pair = bool(text_pair is not None)\n return self.batch_encode_plus_boxes(\n batch_text_or_text_pairs=batch_text_or_text_pairs,\n is_pair=is_pair,\n boxes=boxes,\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )\n else:\n return self.encode_plus_boxes(\n text=text,\n text_pair=text_pair,\n boxes=boxes,\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=32,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n decoder_start_token_id=2,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.initializer_range = initializer_range\n super().__init__()", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n num_channels=3,\n kernel_size=3,\n stride=2,\n padding=1,\n patch_size=16,\n hidden_sizes=[128, 256, 384],\n num_attention_heads=[4, 8, 12],\n depths=[4, 4, 4],\n key_dim=[16, 16, 16],\n drop_path_rate=0,\n mlp_ratio=[2, 2, 2],\n attention_ratio=[2, 2, 2],\n initializer_range=0.02,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.image_size = image_size\n self.num_channels = num_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.hidden_sizes = hidden_sizes\n self.num_attention_heads = num_attention_heads\n self.depths = depths\n self.key_dim = key_dim\n self.drop_path_rate = drop_path_rate\n self.patch_size = patch_size\n self.attention_ratio = attention_ratio\n self.mlp_ratio = mlp_ratio\n self.initializer_range = initializer_range\n self.down_ops = [\n [\"Subsample\", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],\n [\"Subsample\", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],\n ]", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_app_versions_v3_get_serialize(\n self,\n app_version,\n authored_by,\n chart,\n created_at,\n description,\n git_branch,\n git_commit,\n id,\n parent_app_version,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if app_version is not None:\n \n _query_params.append(('appVersion', app_version))\n \n if authored_by is not None:\n \n _query_params.append(('authoredBy', authored_by))\n \n if chart is not None:\n \n _query_params.append(('chart', chart))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if description is not None:\n \n _query_params.append(('description', description))\n \n if git_branch is not None:\n \n _query_params.append(('gitBranch', git_branch))\n \n if git_commit is not None:\n \n _query_params.append(('gitCommit', git_commit))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if parent_app_version is not None:\n \n _query_params.append(('parentAppVersion', parent_app_version))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/app-versions/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden_layers because of #29297\n seq_length=7,\n is_training=True,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=100,\n pad_token_id=99,\n bos_token_id=99,\n num_codebooks=4,\n num_filters=4,\n codebook_size=128,\n conditional_seq_length=3,\n chroma_length=24,\n audio_channels=1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.num_codebooks = num_codebooks\n self.num_filters = num_filters\n self.codebook_size = codebook_size\n self.conditional_seq_length = conditional_seq_length\n self.chroma_length = chroma_length\n self.encoder_seq_length = conditional_seq_length + seq_length\n self.audio_channels = audio_channels", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_charts_v3_get_serialize(\n self,\n app_image_git_main_branch,\n app_image_git_repo,\n chart_exposes_endpoint,\n chart_repo,\n created_at,\n default_port,\n default_protocol,\n default_subdomain,\n description,\n id,\n name,\n pact_participant,\n playbook_url,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if app_image_git_main_branch is not None:\n \n _query_params.append(('appImageGitMainBranch', app_image_git_main_branch))\n \n if app_image_git_repo is not None:\n \n _query_params.append(('appImageGitRepo', app_image_git_repo))\n \n if chart_exposes_endpoint is not None:\n \n _query_params.append(('chartExposesEndpoint', chart_exposes_endpoint))\n \n if chart_repo is not None:\n \n _query_params.append(('chartRepo', chart_repo))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if default_port is not None:\n \n _query_params.append(('defaultPort', default_port))\n \n if default_protocol is not None:\n \n _query_params.append(('defaultProtocol', default_protocol))\n \n if default_subdomain is not None:\n \n _query_params.append(('defaultSubdomain', default_subdomain))\n \n if description is not None:\n \n _query_params.append(('description', description))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if name is not None:\n \n _query_params.append(('name', name))\n \n if pact_participant is not None:\n \n _query_params.append(('pactParticipant', pact_participant))\n \n if playbook_url is not None:\n \n _query_params.append(('playbookURL', playbook_url))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/charts/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n position_embedding_type=\"absolute\",\n use_cache=True,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=4,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n num_queries=2,\n num_channels=3,\n image_size=98,\n n_targets=8,\n num_labels=3,\n num_feature_levels=4,\n encoder_n_points=2,\n decoder_n_points=6,\n max_text_len=7,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_queries = num_queries\n self.num_channels = num_channels\n self.image_size = image_size\n self.n_targets = n_targets\n self.num_labels = num_labels\n self.num_feature_levels = num_feature_levels\n self.encoder_n_points = encoder_n_points\n self.decoder_n_points = decoder_n_points\n self.max_text_len = max_text_len\n\n # we also set the expected seq length for both encoder and decoder\n self.encoder_seq_length_vision = (\n math.ceil(self.image_size / 8) ** 2\n + math.ceil(self.image_size / 16) ** 2\n + math.ceil(self.image_size / 32) ** 2\n + math.ceil(self.image_size / 64) ** 2\n )\n\n self.encoder_seq_length_text = self.max_text_len\n\n self.decoder_seq_length = self.num_queries", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=8008,\n max_position_embeddings=128,\n encoder_layers=2,\n encoder_ffn_dim=10240,\n encoder_attention_heads=32,\n decoder_layers=24,\n decoder_ffn_dim=10240,\n decoder_attention_heads=32,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=2560,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=1,\n scale_embedding=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n encoder_no_repeat_ngram_size=3,\n forced_eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config = AutoConfig.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config.is_decoder = True\n >>> model = RobertaForCausalLM.from_pretrained(\"FacebookAI/roberta-base\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.roberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(prediction_scores.device)\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n mem_len=10,\n clamp_len=-1,\n reuse_len=15,\n is_training=True,\n use_labels=True,\n vocab_size=99,\n cutoffs=[10, 50, 80],\n hidden_size=32,\n num_attention_heads=4,\n d_inner=128,\n num_hidden_layers=2,\n type_sequence_label_size=2,\n untie_r=True,\n bi_data=False,\n same_length=False,\n initializer_range=0.05,\n seed=1,\n type_vocab_size=2,\n bos_token_id=1,\n eos_token_id=2,\n pad_token_id=5,\n num_choices=4,\n ):\n self.parent = parent\n self.batch_size = 14\n self.seq_length = 7\n self.mem_len = 10\n # self.key_len = seq_length + mem_len\n self.clamp_len = -1\n self.reuse_len = 15\n self.is_training = True\n self.use_labels = True\n self.vocab_size = 99\n self.cutoffs = [10, 50, 80]\n self.hidden_size = 32\n self.num_attention_heads = 4\n self.d_inner = 128\n self.num_hidden_layers = 5\n self.type_sequence_label_size = 2\n self.untie_r = True\n self.bi_data = False\n self.same_length = False\n self.initializer_range = 0.05\n self.seed = 1\n self.type_vocab_size = 2\n self.bos_token_id = 1\n self.eos_token_id = 2\n self.pad_token_id = 5\n self.num_choices = 4", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n do_lower_case=True,\n do_basic_tokenize=True,\n never_split=None,\n unk_token=\"<unk>\",\n sep_token=\"<sep>\",\n pad_token=\"<pad>\",\n cls_token=\"<cls>\",\n mask_token=\"<mask>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n tokenize_chinese_chars=True,\n strip_accents=None,\n clean_up_tokenization_spaces=True,\n **kwargs,\n ):\n if not os.path.isfile(vocab_file):\n raise ValueError(\n f\"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained\"\n \" model use `tokenizer = FunnelTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\"\n )\n self.vocab = load_vocab(vocab_file)\n self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])\n self.do_basic_tokenize = do_basic_tokenize\n if do_basic_tokenize:\n self.basic_tokenizer = BasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n )\n self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))\n\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=do_basic_tokenize,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n bos_token=bos_token,\n eos_token=eos_token,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def main_run(\n path_casefile=None,\n path_chronics=None,\n path_parameters=None,\n chronics_class=Multifolder,\n backend_class=PandaPowerBackend,\n agent_class=DoNothingAgent,\n reward_class=FlatReward,\n observation_class=CompleteObservation,\n legalAct_class=AlwaysLegal,\n nb_episode=3,\n nb_process=1,\n path_save=None,\n names_chronics_to_backend=None,\n gridStateclass_kwargs={},\n):\n init_grid_path = os.path.abspath(path_casefile)\n\n path_chron = os.path.abspath(path_chronics)\n\n parameters_path = path_parameters\n\n runner = Runner(\n init_grid_path=init_grid_path,\n path_chron=path_chron,\n parameters_path=parameters_path,\n names_chronics_to_backend=names_chronics_to_backend,\n gridStateclass=chronics_class,\n gridStateclass_kwargs=gridStateclass_kwargs,\n backendClass=backend_class,\n rewardClass=reward_class,\n agentClass=agent_class,\n observationClass=observation_class,\n legalActClass=legalAct_class,\n )\n\n res = runner.run(nb_episode=nb_episode, nb_process=nb_process, path_save=path_save)\n return res", "smellKey": "S107", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ):\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n use_cache = False\n\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False\n elif not return_dict and not isinstance(encoder_outputs, tuple):\n encoder_outputs = encoder_outputs.to_tuple()\n\n decoder_outputs = self.decoder(\n decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,\n _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,\n ## HACK: hand-optimized bytecode; turn globals into locals\n ValueError=ValueError,\n dict=dict,\n float=float,\n id=id,\n int=int,\n isinstance=isinstance,\n list=list,\n str=str,\n tuple=tuple,\n _intstr=int.__repr__,\n ):\n\n def _iterencode_list(lst, _current_indent_level):\n if not lst:\n yield '[]'\n return\n if markers is not None:\n markerid = id(lst)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid] = lst\n buf = '['\n if _indent is not None:\n _current_indent_level += 1\n newline_indent = '\\n' + _indent * _current_indent_level\n separator = _item_separator + newline_indent\n buf += newline_indent\n else:\n newline_indent = None\n separator = _item_separator\n for i, value in enumerate(lst):\n if i:\n buf = separator\n try:\n if isinstance(value, str):\n yield buf + _encoder(value)\n elif value is None:\n yield buf + 'null'\n elif value is True:\n yield buf + 'true'\n elif value is False:\n yield buf + 'false'\n elif isinstance(value, int):\n # Subclasses of int/float may override __repr__, but we still\n # want to encode them as integers/floats in JSON. One example\n # within the standard library is IntEnum.\n yield buf + _intstr(value)\n elif isinstance(value, float):\n # see comment above for int\n yield buf + _floatstr(value)\n else:\n yield buf\n if isinstance(value, (list, tuple)):\n chunks = _iterencode_list(value, _current_indent_level)\n elif isinstance(value, dict):\n chunks = _iterencode_dict(value, _current_indent_level)\n else:\n chunks = _iterencode(value, _current_indent_level)\n yield from chunks\n except GeneratorExit:\n raise\n except BaseException as exc:\n exc.add_note(f'when serializing {type(lst).__name__} item {i}')\n raise\n if newline_indent is not None:\n _current_indent_level -= 1\n yield '\\n' + _indent * _current_indent_level\n yield ']'\n if markers is not None:\n del markers[markerid]\n\n def _iterencode_dict(dct, _current_indent_level):\n if not dct:\n yield '{}'\n return\n if markers is not None:\n markerid = id(dct)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid] = dct\n yield '{'\n if _indent is not None:\n _current_indent_level += 1\n newline_indent = '\\n' + _indent * _current_indent_level\n item_separator = _item_separator + newline_indent\n yield newline_indent\n else:\n newline_indent = None\n item_separator = _item_separator\n first = True\n if _sort_keys:\n items = sorted(dct.items())\n else:\n items = dct.items()\n for key, value in items:\n if isinstance(key, str):\n pass\n # JavaScript is weakly typed for these, so it makes sense to\n # also allow them. Many encoders seem to do something like this.\n elif isinstance(key, float):\n # see comment for int/float in _make_iterencode\n key = _floatstr(key)\n elif key is True:\n key = 'true'\n elif key is False:\n key = 'false'\n elif key is None:\n key = 'null'\n elif isinstance(key, int):\n # see comment for int/float in _make_iterencode\n key = _intstr(key)\n elif _skipkeys:\n continue\n else:\n raise TypeError(f'keys must be str, int, float, bool or None, '\n f'not {key.__class__.__name__}')\n if first:\n first = False\n else:\n yield item_separator\n yield _encoder(key)\n yield _key_separator\n try:\n if isinstance(value, str):\n yield _encoder(value)\n elif value is None:\n yield 'null'\n elif value is True:\n yield 'true'\n elif value is False:\n yield 'false'\n elif isinstance(value, int):\n # see comment for int/float in _make_iterencode\n yield _intstr(value)\n elif isinstance(value, float):\n # see comment for int/float in _make_iterencode\n yield _floatstr(value)\n else:\n if isinstance(value, (list, tuple)):\n chunks = _iterencode_list(value, _current_indent_level)\n elif isinstance(value, dict):\n chunks = _iterencode_dict(value, _current_indent_level)\n else:\n chunks = _iterencode(value, _current_indent_level)\n yield from chunks\n except GeneratorExit:\n raise\n except BaseException as exc:\n exc.add_note(f'when serializing {type(dct).__name__} item {key!r}')\n raise\n if newline_indent is not None:\n _current_indent_level -= 1\n yield '\\n' + _indent * _current_indent_level\n yield '}'\n if markers is not None:\n del markers[markerid]\n\n def _iterencode(o, _current_indent_level):\n if isinstance(o, str):\n yield _encoder(o)\n elif o is None:\n yield 'null'\n elif o is True:\n yield 'true'\n elif o is False:\n yield 'false'\n elif isinstance(o, int):\n # see comment for int/float in _make_iterencode\n yield _intstr(o)\n elif isinstance(o, float):\n # see comment for int/float in _make_iterencode\n yield _floatstr(o)\n elif isinstance(o, (list, tuple)):\n yield from _iterencode_list(o, _current_indent_level)\n elif isinstance(o, dict):\n yield from _iterencode_dict(o, _current_indent_level)\n else:\n if markers is not None:\n markerid = id(o)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid] = o\n newobj = _default(o)\n try:\n yield from _iterencode(newobj, _current_indent_level)\n except GeneratorExit:\n raise\n except BaseException as exc:\n exc.add_note(f'when serializing {type(o).__name__} object')\n raise\n if markers is not None:\n del markers[markerid]\n return _iterencode", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(self, cfg, target,\n pyocd='pyocd',\n dev_id=None, flash_addr=0x0, erase=False, flash_opts=None,\n gdb_port=DEFAULT_PYOCD_GDB_PORT,\n telnet_port=DEFAULT_PYOCD_TELNET_PORT, tui=False,\n pyocd_config=None,\n daparg=None, frequency=None, tool_opt=None):\n super().__init__(cfg)\n\n default = path.join(cfg.board_dir, 'support', 'pyocd.yaml')\n if path.exists(default):\n self.pyocd_config = default\n else:\n self.pyocd_config = None\n\n\n self.target_args = ['-t', target]\n self.pyocd = pyocd\n self.flash_addr_args = ['-a', hex(flash_addr)] if flash_addr else []\n self.erase = erase\n self.gdb_cmd = [cfg.gdb] if cfg.gdb is not None else None\n self.gdb_port = gdb_port\n self.telnet_port = telnet_port\n self.tui_args = ['-tui'] if tui else []\n self.hex_name = cfg.hex_file\n self.bin_name = cfg.bin_file\n self.elf_name = cfg.elf_file\n\n pyocd_config_args = []\n\n if self.pyocd_config is not None:\n pyocd_config_args = ['--config', self.pyocd_config]\n\n self.pyocd_config_args = pyocd_config_args\n\n board_args = []\n if dev_id is not None:\n board_args = ['-u', dev_id]\n self.board_args = board_args\n\n daparg_args = []\n if daparg is not None:\n daparg_args = ['-da', daparg]\n self.daparg_args = daparg_args\n\n frequency_args = []\n if frequency is not None:\n frequency_args = ['-f', frequency]\n self.frequency_args = frequency_args\n\n self.tool_opt_args = tool_opt or []\n\n self.flash_extra = flash_opts if flash_opts else []", "smellKey": "S107", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_convert_rgb: Optional[bool] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: Optional[PILImageResampling] = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n max_image_tiles: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n ):\n \"\"\"\n Preprocess a batch of images.\n\n Args:\n images (`ImageInput`):\n A list of images to preprocess.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values.\n The height and width values should be equal.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether or not to pad the images to the largest height and width in the batch.\n max_image_tiles (`int`, *optional*, defaults to `self.max_image_tiles`):\n The maximum number of tiles to split the image into.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n\n Returns:\n `BatchFeature` of the following structure:\n - **pixel_values** (`TensorType`): The preprocessed pixel values.\n - **aspect_ratio_ids** (`TensorType`): The aspect ratio ids of the images.\n - **num_tiles** (`List[List[int]]`): The number of tiles for each image in the batch.\n \"\"\"\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_pad = do_pad if do_pad is not None else self.do_pad\n max_image_tiles = max_image_tiles if max_image_tiles is not None else self.max_image_tiles\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n # extra validation\n _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles)\n\n images_list = make_list_of_images(images)\n\n if self.do_convert_rgb:\n images_list = [[convert_to_rgb(image) for image in images] for images in images_list]\n\n images_list = [[to_numpy_array(image) for image in images] for images in images_list]\n\n batch_images = []\n batch_aspect_ratios = []\n\n # iterate over batch samples\n for images in images_list:\n sample_images = []\n sample_aspect_ratios = []\n\n # iterate over images in a batch sample\n for image in images:\n # convert images to channels first format for faster processing\n # LAST is slower for `pad` and not supported by `split_to_tiles`\n data_format = ChannelDimension.FIRST\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n\n # do_resize=False is not supported, validated\n image, aspect_ratio = self.resize(\n image=image,\n size=size,\n resample=resample,\n max_image_tiles=max_image_tiles,\n input_data_format=data_format,\n data_format=data_format,\n )\n\n # do_pad=False is not supported, validated\n image = self.pad(\n image=image,\n size=size,\n aspect_ratio=aspect_ratio,\n input_data_format=data_format,\n data_format=data_format,\n )\n\n if do_rescale:\n image = self.rescale(\n image=image,\n scale=rescale_factor,\n input_data_format=input_data_format,\n data_format=data_format,\n )\n\n if do_normalize:\n image = self.normalize(\n image=image,\n mean=image_mean,\n std=image_std,\n input_data_format=input_data_format,\n data_format=data_format,\n )\n\n num_tiles_height, num_tiles_width = aspect_ratio\n image = split_to_tiles(image, num_tiles_height, num_tiles_width)\n\n sample_images.append(image)\n sample_aspect_ratios.append((num_tiles_height, num_tiles_width))\n\n batch_images.append(sample_images)\n batch_aspect_ratios.append(sample_aspect_ratios)\n\n images, num_tiles = pack_images(batch_images, max_image_tiles)\n\n aspect_ratio_ids = convert_aspect_ratios_to_ids(batch_aspect_ratios, max_image_tiles=max_image_tiles)\n aspect_ratio_mask = build_aspect_ratio_mask(batch_aspect_ratios, max_image_tiles=max_image_tiles)\n\n # images (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width)\n # aspect_ratio_ids (np.ndarray) with shape (batch_size, max_num_images) - aspect ratio ids for each image, padded to max_num_images with 0\n # num_tiles (List[List[int]]) with (batch_size, num_images_in_batch) - real number of tiles for each image, not padded\n # aspect_ratio_mask (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles) - number of tiles for each image, padded to max_num_images with 0\n encoded_inputs = BatchFeature(\n data={\n \"pixel_values\": images,\n \"aspect_ratio_ids\": aspect_ratio_ids,\n \"aspect_ratio_mask\": aspect_ratio_mask,\n },\n tensor_type=return_tensors,\n )\n encoded_inputs[\"num_tiles\"] = num_tiles\n\n return encoded_inputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@array_function_dispatch(_array2string_dispatcher, module='numpy')\ndef array2string(a, max_line_width=None, precision=None,\n suppress_small=None, separator=' ', prefix=\"\",\n style=np._NoValue, formatter=None, threshold=None,\n edgeitems=None, sign=None, floatmode=None, suffix=\"\",\n *, legacy=None):\n \"\"\"\n Return a string representation of an array.\n\n Parameters\n ----------\n a : ndarray\n Input array.\n max_line_width : int, optional\n Inserts newlines if text is longer than `max_line_width`.\n Defaults to ``numpy.get_printoptions()['linewidth']``.\n precision : int or None, optional\n Floating point precision.\n Defaults to ``numpy.get_printoptions()['precision']``.\n suppress_small : bool, optional\n Represent numbers \"very close\" to zero as zero; default is False.\n Very close is defined by precision: if the precision is 8, e.g.,\n numbers smaller (in absolute value) than 5e-9 are represented as\n zero.\n Defaults to ``numpy.get_printoptions()['suppress']``.\n separator : str, optional\n Inserted between elements.\n prefix : str, optional\n suffix : str, optional\n The length of the prefix and suffix strings are used to respectively\n align and wrap the output. An array is typically printed as::\n\n prefix + array2string(a) + suffix\n\n The output is left-padded by the length of the prefix string, and\n wrapping is forced at the column ``max_line_width - len(suffix)``.\n It should be noted that the content of prefix and suffix strings are\n not included in the output.\n style : _NoValue, optional\n Has no effect, do not use.\n\n .. deprecated:: 1.14.0\n formatter : dict of callables, optional\n If not None, the keys should indicate the type(s) that the respective\n formatting function applies to. Callables should return a string.\n Types that are not specified (by their corresponding keys) are handled\n by the default formatters. Individual types for which a formatter\n can be set are:\n\n - 'bool'\n - 'int'\n - 'timedelta' : a `numpy.timedelta64`\n - 'datetime' : a `numpy.datetime64`\n - 'float'\n - 'longfloat' : 128-bit floats\n - 'complexfloat'\n - 'longcomplexfloat' : composed of two 128-bit floats\n - 'void' : type `numpy.void`\n - 'numpystr' : types `numpy.bytes_` and `numpy.str_`\n\n Other keys that can be used to set a group of types at once are:\n\n - 'all' : sets all types\n - 'int_kind' : sets 'int'\n - 'float_kind' : sets 'float' and 'longfloat'\n - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'\n - 'str_kind' : sets 'numpystr'\n threshold : int, optional\n Total number of array elements which trigger summarization\n rather than full repr.\n Defaults to ``numpy.get_printoptions()['threshold']``.\n edgeitems : int, optional\n Number of array items in summary at beginning and end of\n each dimension.\n Defaults to ``numpy.get_printoptions()['edgeitems']``.\n sign : string, either '-', '+', or ' ', optional\n Controls printing of the sign of floating-point types. If '+', always\n print the sign of positive values. If ' ', always prints a space\n (whitespace character) in the sign position of positive values. If\n '-', omit the sign character of positive values.\n Defaults to ``numpy.get_printoptions()['sign']``.\n floatmode : str, optional\n Controls the interpretation of the `precision` option for\n floating-point types.\n Defaults to ``numpy.get_printoptions()['floatmode']``.\n Can take the following values:\n\n - 'fixed': Always print exactly `precision` fractional digits,\n even if this would print more or fewer digits than\n necessary to specify the value uniquely.\n - 'unique': Print the minimum number of fractional digits necessary\n to represent each value uniquely. Different elements may\n have a different number of digits. The value of the\n `precision` option is ignored.\n - 'maxprec': Print at most `precision` fractional digits, but if\n an element can be uniquely represented with fewer digits\n only print it with that many.\n - 'maxprec_equal': Print at most `precision` fractional digits,\n but if every element in the array can be uniquely\n represented with an equal number of fewer digits, use that\n many digits for all elements.\n legacy : string or `False`, optional\n If set to the string `'1.13'` enables 1.13 legacy printing mode. This\n approximates numpy 1.13 print output by including a space in the sign\n position of floats and different behavior for 0d arrays. If set to\n `False`, disables legacy mode. Unrecognized strings will be ignored\n with a warning for forward compatibility.\n\n .. versionadded:: 1.14.0\n\n Returns\n -------\n array_str : str\n String representation of the array.\n\n Raises\n ------\n TypeError\n if a callable in `formatter` does not return a string.\n\n See Also\n --------\n array_str, array_repr, set_printoptions, get_printoptions\n\n Notes\n -----\n If a formatter is specified for a certain type, the `precision` keyword is\n ignored for that type.\n\n This is a very flexible function; `array_repr` and `array_str` are using\n `array2string` internally so keywords with the same name should work\n identically in all three functions.\n\n Examples\n --------\n >>> x = np.array([1e-16,1,2,3])\n >>> np.array2string(x, precision=2, separator=',',\n ... suppress_small=True)\n '[0.,1.,2.,3.]'\n\n >>> x = np.arange(3.)\n >>> np.array2string(x, formatter={'float_kind':lambda x: \"%.2f\" % x})\n '[0.00 1.00 2.00]'\n\n >>> x = np.arange(3)\n >>> np.array2string(x, formatter={'int':lambda x: hex(x)})\n '[0x0 0x1 0x2]'\n\n \"\"\"\n\n overrides = _make_options_dict(precision, threshold, edgeitems,\n max_line_width, suppress_small, None, None,\n sign, formatter, floatmode, legacy)\n options = _format_options.copy()\n options.update(overrides)\n\n if options['legacy'] <= 113:\n if style is np._NoValue:\n style = repr\n\n if a.shape == () and a.dtype.names is None:\n return style(a.item())\n elif style is not np._NoValue:\n # Deprecation 11-9-2017 v1.14\n warnings.warn(\"'style' argument is deprecated and no longer functional\"\n \" except in 1.13 'legacy' mode\",\n DeprecationWarning, stacklevel=2)\n\n if options['legacy'] > 113:\n options['linewidth'] -= len(suffix)\n\n # treat as a null array if any of shape elements == 0\n if a.size == 0:\n return \"[]\"\n\n return _array2string(a, options, separator, prefix)", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str,\n zerofill_results: bool = True,\n allow_metric_aggregates=True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n has_metrics: bool = True,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n groupby: Column | None = None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n\n metrics_query = TimeseriesSpansMetricsQueryBuilder(\n params={},\n interval=rollup,\n snuba_params=snuba_params,\n dataset=Dataset.PerformanceMetrics,\n query=query,\n selected_columns=selected_columns,\n groupby=groupby,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n allow_metric_aggregates=allow_metric_aggregates,\n use_metrics_layer=use_metrics_layer,\n ),\n )\n result = metrics_query.run_query(referrer=referrer, query_source=query_source)\n\n result = metrics_query.process_results(result)\n result[\"data\"] = (\n discover.zerofill(\n result[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n \"time\",\n )\n if zerofill_results\n else result[\"data\"]\n )\n\n result[\"meta\"][\"isMetricsData\"] = True\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"isMetricsData\": True,\n \"meta\": result[\"meta\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_features=None,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n head_mask=None,\n decoder_head_mask=None,\n cross_attn_head_mask=None,\n encoder_outputs=None,\n past_key_values=None,\n decoder_inputs_embeds=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_features=input_features,\n attention_mask=attention_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False\n elif not return_dict and not isinstance(encoder_outputs, tuple):\n encoder_outputs = encoder_outputs.to_tuple()\n\n # downsample encoder attention mask\n if attention_mask is not None:\n encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(\n tf.shape(encoder_outputs[0])[1], attention_mask\n )\n else:\n encoder_attention_mask = None\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=encoder_attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=[64, 64],\n mlp_ratio=1.0,\n num_channels=3,\n depths=[1, 1, 1, 1],\n patch_stride=[4, 4],\n patch_size=[7, 7],\n patch_padding=[3, 3],\n masked_unit_size=[8, 8],\n num_heads=[1, 1, 1, 1],\n embed_dim_multiplier=2.0,\n is_training=True,\n use_labels=True,\n embed_dim=8,\n hidden_act=\"gelu\",\n decoder_hidden_size=2,\n decoder_depth=1,\n decoder_num_heads=1,\n initializer_range=0.02,\n scope=None,\n type_sequence_label_size=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.mlp_ratio = mlp_ratio\n self.num_channels = num_channels\n self.depths = depths\n self.patch_stride = patch_stride\n self.patch_size = patch_size\n self.patch_padding = patch_padding\n self.masked_unit_size = masked_unit_size\n self.num_heads = num_heads\n self.embed_dim_multiplier = embed_dim_multiplier\n self.is_training = is_training\n self.use_labels = use_labels\n self.embed_dim = embed_dim\n self.hidden_act = hidden_act\n self.decoder_hidden_size = decoder_hidden_size\n self.decoder_depth = decoder_depth\n self.decoder_num_heads = decoder_num_heads\n self.initializer_range = initializer_range\n self.scope = scope\n self.type_sequence_label_size = type_sequence_label_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: List[tf.Tensor] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: tf.Tensor | None = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:\n r\"\"\"\n labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n if labels is not None:\n labels = tf.where(\n labels == self.config.pad_token_id,\n tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),\n labels,\n )\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)\n lm_logits = self.bias_layer(lm_logits)\n masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n return TFSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values, # index 1 of d outputs\n decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs\n decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs\n cross_attentions=outputs.cross_attentions, # index 4 of d outputs\n encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs\n encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out\n encoder_attentions=outputs.encoder_attentions, # 2 of e out\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LLAVA_NEXT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=LlavaNextCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n pixel_values: torch.FloatTensor = None,\n image_sizes: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n vision_feature_layer: Optional[int] = None,\n vision_feature_select_strategy: Optional[str] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n cache_position: Optional[torch.LongTensor] = None,\n num_logits_to_keep: int = 0,\n ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n num_logits_to_keep (`int`, *optional*):\n Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all\n `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that\n token can save memory, which becomes pretty significant for long sequences or large vocabulary size.\n\n Returns:\n\n Example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration\n\n >>> model = LlavaNextForConditionalGeneration.from_pretrained(\"llava-hf/llava-v1.6-mistral-7b-hf\")\n >>> processor = AutoProcessor.from_pretrained(\"llava-hf/llava-v1.6-mistral-7b-hf\")\n\n >>> prompt = \"[INST] <image>\\nWhat is shown in this image? [/INST]\"\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, text=prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(**inputs, max_length=30)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"[INST] \\nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n vision_feature_layer = (\n vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n )\n vision_feature_select_strategy = (\n vision_feature_select_strategy\n if vision_feature_select_strategy is not None\n else self.config.vision_feature_select_strategy\n )\n\n if (input_ids is None) ^ (inputs_embeds is not None):\n raise ValueError(\"You must specify exactly one of input_ids or inputs_embeds\")\n\n if pixel_values is not None and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one\"\n )\n\n legacy_processing = False\n if inputs_embeds is None:\n inputs_embeds = self.get_input_embeddings()(input_ids)\n\n # if the number of image tokens is more than image embeddings seq length, then prob we expanded it in processing\n # not very reliable, but we don't expect one to actually pass 500+ images for one prompt\n # In case we're in decoding stage, legacy behavior is checked by presence of pixel values even if use_cache=True\n legacy_processing = (\n (input_ids == self.config.image_token_index).sum(1).max() < self.config.image_seq_length\n ) or (input_ids.shape[-1] == 1 and pixel_values is not None)\n\n if pixel_values is not None and pixel_values.size(0) > 0:\n # ! infer image_num_patches from image_sizes\n image_num_patches = [\n image_size_to_num_patches(\n image_size=imsize,\n grid_pinpoints=self.config.image_grid_pinpoints,\n patch_size=self.config.vision_config.image_size,\n )\n for imsize in image_sizes\n ]\n # figure out if pixel_values is concatenated or stacked\n if pixel_values.dim() == 5:\n # stacking when input is (batch_size, num_patches, num_channels, height, width)\n _pixel_values_list = [\n pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)\n ]\n pixel_values = torch.cat(_pixel_values_list, dim=0)\n elif pixel_values.dim() != 4:\n # otherwise has to be stacked from list of (num_patches, num_channels, height, width)\n raise ValueError(f\"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions\")\n\n image_features = self.vision_tower(pixel_values, output_hidden_states=True)\n selected_image_feature = image_features.hidden_states[vision_feature_layer]\n if vision_feature_select_strategy == \"default\":\n selected_image_feature = selected_image_feature[:, 1:]\n elif vision_feature_select_strategy == \"full\":\n selected_image_feature = selected_image_feature\n image_features = self.multi_modal_projector(selected_image_feature)\n image_features = torch.split(image_features, image_num_patches, dim=0)\n\n # NOTE we only support multimodal_patch_merge_type == \"spatial_unpad\"\n image_features, feature_lens = self.pack_image_features(\n image_features,\n image_sizes,\n vision_feature_select_strategy=vision_feature_select_strategy,\n image_newline=self.image_newline,\n )\n if legacy_processing:\n logger.warning_once(\n \"Expanding inputs for image tokens in LLaVa-NeXT should be done in processing. \"\n \"Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly \"\n \"with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. \"\n \"Using processors without these attributes in the config is deprecated and will throw an error in v4.47.\"\n )\n if input_ids.shape[1] != 1:\n inputs_embeds = inputs_embeds.to(image_features.dtype)\n inputs_embeds, attention_mask, position_ids, labels, _ = self._merge_input_ids_with_image_features(\n image_features,\n feature_lens,\n inputs_embeds,\n input_ids,\n attention_mask,\n position_ids,\n labels=labels,\n )\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)\n else:\n # Retrieve the first layer to inspect the logits and mask out the hidden states\n # that are set to 0\n first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]\n\n # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941\n batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)\n\n # Get the target length\n target_length = input_ids.shape[1]\n past_length = first_layer_past_key_value.shape[-1]\n\n extended_attention_mask = torch.ones(\n (attention_mask.shape[0], past_length),\n dtype=attention_mask.dtype,\n device=attention_mask.device,\n )\n\n # Filter out only the tokens that can be un-attended, this can happen\n # if one uses Llava + Fused modules where the cache on the\n # first iteration is already big enough, or if one passes custom cache\n valid_indices = non_attended_tokens < extended_attention_mask.size(-1)\n new_batch_index = batch_index[valid_indices]\n new_non_attended_tokens = non_attended_tokens[valid_indices]\n\n # Zero-out the places where we don't need to attend\n extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0\n attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)\n position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)[\n -target_length:\n ]\n\n # TODO: @raushan retain only the new behavior after v4.47\n else:\n special_image_mask = (\n (input_ids == self.config.image_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)\n\n outputs = self.language_model(\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n cache_position=cache_position,\n num_logits_to_keep=num_logits_to_keep,\n )\n\n logits = outputs[0]\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n # we use the input attention mask to shift the logits and labels, because it is 2D.\n # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft\n shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)\n shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()\n shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()\n else:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(\n shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)\n )\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return LlavaNextCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=image_features if pixel_values is not None else None,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n key_file=None,\n cert_file=None,\n cert_reqs=None,\n key_password=None,\n ca_certs=None,\n ssl_version=None,\n assert_hostname=None,\n assert_fingerprint=None,\n ca_cert_dir=None,\n **conn_kw\n ):\n\n HTTPConnectionPool.__init__(\n self,\n host,\n port,\n strict,\n timeout,\n maxsize,\n block,\n headers,\n retries,\n _proxy,\n _proxy_headers,\n **conn_kw\n )\n\n self.key_file = key_file\n self.cert_file = cert_file\n self.cert_reqs = cert_reqs\n self.key_password = key_password\n self.ca_certs = ca_certs\n self.ca_cert_dir = ca_cert_dir\n self.ssl_version = ssl_version\n self.assert_hostname = assert_hostname\n self.assert_fingerprint = assert_fingerprint", "smellKey": "S107", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n do_lower_case=True,\n do_basic_tokenize=True,\n never_split=None,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n cls_token_box=[0, 0, 0, 0],\n sep_token_box=[1000, 1000, 1000, 1000],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n tokenize_chinese_chars=True,\n strip_accents=None,\n model_max_length: int = 512,\n additional_special_tokens: Optional[List[str]] = None,\n **kwargs,\n ):\n sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token\n unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token\n cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token\n mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token\n\n if not os.path.isfile(vocab_file):\n raise ValueError(\n f\"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained\"\n \" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\"\n )\n self.vocab = load_vocab(vocab_file)\n self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])\n self.do_basic_tokenize = do_basic_tokenize\n if do_basic_tokenize:\n self.basic_tokenizer = BasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n )\n self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))\n\n # additional properties\n self.cls_token_box = cls_token_box\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=do_basic_tokenize,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n cls_token_box=cls_token_box,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n model_max_length=model_max_length,\n additional_special_tokens=additional_special_tokens,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n past_key_values: Optional[List[tf.Tensor]] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n pixel_values: Optional[tf.Tensor] = None,\n image_encoder_embeddings: Optional[tf.Tensor] = None,\n perceiver_embeddings: Optional[tf.Tensor] = None,\n image_attention_mask: Optional[tf.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n interpolate_pos_encoding: Optional[bool] = False,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = None,\n ) -> Union[TFIdeficsBaseModelOutputWithPast, Tuple[tf.Tensor]]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # retrieve input_ids and inputs_embeds\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time\")\n elif input_ids is not None:\n batch_size, seq_length = shape_list(input_ids)\n elif inputs_embeds is not None:\n batch_size, seq_length, _ = shape_list(inputs_embeds)\n else:\n raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\n\n seq_length_with_past = seq_length\n past_key_values_length = 0\n\n if past_key_values is not None:\n past_key_values_length = shape_list(past_key_values[0][0])[2]\n seq_length_with_past = seq_length_with_past + past_key_values_length\n\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = tf.math.cumsum(tf.cast(attention_mask, dtype=tf.int32), axis=-1) - 1\n position_ids = tf.where(attention_mask == 0, 1, position_ids)\n elif position_ids is None:\n position_ids = tf.range(past_key_values_length, seq_length + past_key_values_length, dtype=tf.int32)\n position_ids = tf.expand_dims(position_ids, 0)\n\n no_images = False\n if (\n sum((int(pixel_values is None), int(image_encoder_embeddings is None), int(perceiver_embeddings is None)))\n != 2\n ):\n raise ValueError(\n \"Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None.\"\n )\n\n elif pixel_values is not None:\n no_images = tf.reduce_sum(tf.cast(pixel_values, dtype=tf.int32)) == 0\n pixel_values = tf.cast(pixel_values, dtype=self.dtype) # fp16 compatibility\n # Below hack is because when cross-loading pytorch weights, there is an\n # initial forward pass with dummy input and code below is here to handle that\n if len(pixel_values.shape) == 4:\n batch_size = shape_list(pixel_values)[0]\n num_images = shape_list(pixel_values)[0]\n # pixel_values = tf.reshape(pixel_values, [batch_size * num_images, *pixel_values.shape[1:]])\n elif len(pixel_values.shape) == 5:\n batch_size, num_images = shape_list(pixel_values)[:2]\n pixel_values = tf.reshape(pixel_values, [batch_size * num_images, *pixel_values.shape[2:]])\n\n # Get sequence from the vision encoder\n image_hidden_states = self.vision_model(\n pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding\n ).last_hidden_state\n\n elif image_encoder_embeddings is not None:\n batch_size, num_images, image_seq_len, image_hidden_size = shape_list(image_encoder_embeddings)\n image_hidden_states = tf.cast(image_encoder_embeddings, dtype=self.dtype)\n image_hidden_states = tf.reshape(\n image_hidden_states, (batch_size * num_images, image_seq_len, image_hidden_size)\n )\n\n if self.config.use_resampler:\n if perceiver_embeddings is None:\n perceiver_embeddings = self.perceiver_resampler(image_hidden_states)\n image_seq_len, image_hidden_size = shape_list(perceiver_embeddings)[1:3]\n else:\n batch_size, num_images, image_seq_len, image_hidden_size = shape_list(perceiver_embeddings)\n image_hidden_states = perceiver_embeddings\n elif perceiver_embeddings is None:\n image_seq_len, image_hidden_size = shape_list(image_hidden_states)[1:3]\n else:\n raise ValueError(\"If `perceiver_embeddings` are passed, use_resampler should be True\")\n\n image_hidden_states = tf.reshape(\n image_hidden_states, (batch_size, num_images * image_seq_len, image_hidden_size)\n )\n # # Hack to use the model in full language modeling mode\n # image_attention_mask = tf.zeros((batch_size, seq_length, 1), dtype=tf.int32)\n\n # this is to account for the dummy inputs\n if pixel_values is not None and len(pixel_values.shape) == 4 and image_attention_mask is None:\n image_attention_mask = tf.zeros((batch_size, seq_length, 1), dtype=tf.int32)\n\n text_seq_len = shape_list(image_attention_mask)[1]\n image_attention_mask = tf.expand_dims(image_attention_mask, -1)\n image_attention_mask = tf.repeat(image_attention_mask, repeats=image_seq_len)\n image_attention_mask = tf.reshape(image_attention_mask, (batch_size, text_seq_len, num_images * image_seq_len))\n\n if image_hidden_states is not None:\n image_batch_size, image_sequence_length, _ = shape_list(image_hidden_states)\n image_hidden_shape = (image_batch_size, image_sequence_length)\n if image_attention_mask is None:\n image_attention_mask = tf.ones(image_hidden_shape, dtype=tf.int32)\n image_attention_mask = invert_attention_mask(image_attention_mask)\n else:\n image_attention_mask = None\n\n cross_attention_gate = tf.squeeze(\n tf.cast(tf.reduce_any(image_attention_mask == 0, axis=-1), dtype=self.dtype), axis=1\n )\n if inputs_embeds is None:\n inputs_embeds = self.embed_tokens(input_ids)\n # embed positions\n if attention_mask is None:\n attention_mask = tf.ones((batch_size, seq_length_with_past), dtype=tf.bool)\n attention_mask = self._prepare_decoder_attention_mask(\n attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length\n )\n\n hidden_states = inputs_embeds\n\n if self.gradient_checkpointing and training:\n if use_cache:\n logger.warning_once(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n\n # decoder layers\n all_hidden_states = () if output_hidden_states else None\n all_self_attns = () if output_attentions else None\n next_decoder_cache = () if use_cache else None\n\n for idx, decoder_layer in enumerate(self.decoder_layers):\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n past_key_value = past_key_values[idx] if past_key_values is not None else None\n\n def vblock(\n main_block,\n hidden_states,\n attention_mask,\n position_ids,\n past_key_value,\n image_hidden_states,\n image_attention_mask,\n cross_attention_gate,\n output_attentions,\n use_cache,\n layer_idx,\n cross_layer_interval,\n gated_cross_attn_layers,\n ):\n # TODO(ls): Add cross attention values to respective lists\n if layer_idx % cross_layer_interval == 0:\n xblock = gated_cross_attn_layers[layer_idx // cross_layer_interval]\n outputs = xblock(\n hidden_states,\n attention_mask=attention_mask,\n image_hidden_states=image_hidden_states,\n image_attention_mask=image_attention_mask,\n cross_attention_gate=cross_attention_gate,\n output_attentions=output_attentions,\n use_cache=use_cache,\n past_key_value=None, # not implemented\n )\n hidden_states = outputs[0]\n\n layer_outputs = main_block(\n hidden_states,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_value=past_key_value,\n output_attentions=output_attentions,\n use_cache=use_cache,\n )\n\n return layer_outputs\n\n if self.gradient_checkpointing and training:\n past_key_value = None\n if use_cache:\n logger.warning_once(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n\n layer_outputs = tf.recompute_grad(\n vblock,\n decoder_layer,\n hidden_states,\n attention_mask,\n position_ids,\n past_key_value,\n image_hidden_states,\n image_attention_mask,\n output_attentions,\n use_cache,\n no_images,\n idx,\n self.cross_layer_interval,\n self.gated_cross_attn_layers,\n )\n else:\n layer_outputs = vblock(\n decoder_layer,\n hidden_states,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_value=past_key_value,\n image_hidden_states=image_hidden_states,\n image_attention_mask=image_attention_mask,\n cross_attention_gate=cross_attention_gate,\n output_attentions=output_attentions,\n use_cache=use_cache,\n layer_idx=idx,\n cross_layer_interval=self.cross_layer_interval,\n gated_cross_attn_layers=self.gated_cross_attn_layers,\n )\n\n hidden_states = layer_outputs[0]\n\n if use_cache:\n next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)\n\n if output_attentions:\n all_self_attns += (layer_outputs[1],)\n\n hidden_states = self.norm(hidden_states)\n\n # add hidden states from the last decoder layer\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n next_cache = next_decoder_cache if use_cache else None\n image_hidden_states = tf.reshape(\n image_hidden_states, (batch_size, num_images, image_seq_len, image_hidden_size)\n )\n if not return_dict:\n return tuple(\n v\n for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, image_hidden_states]\n if v is not None\n )\n return TFIdeficsBaseModelOutputWithPast(\n last_hidden_state=hidden_states,\n past_key_values=next_cache,\n hidden_states=all_hidden_states,\n attentions=all_self_attns,\n image_hidden_states=image_hidden_states,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n channel_label,\n repo_type=None,\n url=None,\n fail=False,\n filters=None,\n no_errata=False,\n sync_kickstart=False,\n latest=False,\n metadata_only=False,\n strict=False,\n excluded_urls=None,\n no_packages=False,\n log_dir=\"reposync\",\n log_level=None,\n force_kickstart=False,\n force_all_errata=False,\n check_ssl_dates=True,\n force_null_org_content=False,\n show_packages_only=False,\n noninteractive=False,\n deep_verify=False,\n ):\n self.regen = False\n self.fail = fail\n self.filters = filters or []\n self.no_packages = no_packages\n self.no_errata = no_errata\n self.sync_kickstart = sync_kickstart\n self.force_all_errata = force_all_errata\n self.force_kickstart = force_kickstart\n self.latest = latest\n self.metadata_only = metadata_only\n self.ks_tree_type = \"externally-managed\"\n self.interactive = not noninteractive\n self.deep_verify = deep_verify\n self.error_messages = []\n self.available_packages = {}\n self.ks_install_type = None\n self.show_packages_only = show_packages_only\n self.regenerate_bootstrap_repo = False\n\n rhnSQL.initDB()\n\n # setup logging\n log_filename = channel_label + \".log\"\n log_path = default_log_location + log_dir + \"/\" + log_filename\n if log_level is None:\n log_level = 0\n # pylint: disable-next=invalid-name\n with cfg_component(\"server.susemanager\") as CFG:\n CFG.set(\"DEBUG\", log_level)\n rhnLog.initLOG(log_path, log_level)\n # os.fchown isn't in 2.4 :/\n os.system(\"chgrp \" + CFG.httpd_group + \" \" + log_path)\n\n # pylint: disable-next=consider-using-f-string\n log2disk(0, \"Command: %s\" % str(sys.argv))\n log2disk(0, \"Sync of channel started.\")\n\n self.channel_label = channel_label\n self.channel = self.load_channel()\n if not self.channel:\n # pylint: disable-next=consider-using-f-string\n log(0, \"Channel %s does not exist.\" % channel_label)\n sys.exit(1)\n\n if not self.channel[\"org_id\"] or force_null_org_content:\n self.org_id = None\n else:\n self.org_id = int(self.channel[\"org_id\"])\n\n if not url:\n # TODO:need to look at user security across orgs\n h = rhnSQL.prepare(\n \"\"\"\n select s.id, s.source_url, s.metadata_signed, s.label as repo_label, cst.label as repo_type_label\n from rhnContentSource s,\n rhnChannelContentSource cs,\n rhnContentSourceType cst\n where s.id = cs.source_id\n and cst.id = s.type_id\n and cs.channel_id = :channel_id\"\"\"\n )\n h.execute(channel_id=int(self.channel[\"id\"]))\n sources = h.fetchall_dict()\n self.urls = []\n if excluded_urls is None:\n excluded_urls = []\n if sources:\n self.urls = self._format_sources(sources, excluded_urls, repo_type)\n else:\n # generate empty metadata and quit\n taskomatic.add_to_repodata_queue_for_channel_package_subscription(\n [channel_label], [], \"server.app.yumreposync\"\n )\n rhnSQL.commit()\n log2(0, 0, \"Channel has no URL associated\", stream=sys.stderr)\n if not self.org_id:\n # RES base vendor channels do not have a URL. This is not an error\n sys.exit(0)\n sys.exit(1)\n else:\n if repo_type:\n repo_type_label = repo_type\n else:\n repo_type_label = \"yum\"\n self.urls = [\n {\n \"id\": None,\n \"source_url\": url,\n \"metadata_signed\": \"N\",\n \"repo_label\": None,\n \"repo_type\": repo_type_label,\n }\n ]\n\n if not self.urls:\n log2(\n 0,\n 0,\n # pylint: disable-next=consider-using-f-string\n \"Channel %s has no URL associated\" % channel_label,\n stream=sys.stderr,\n )\n\n self.repo_plugin = None\n self.strict = strict\n self.all_packages = set()\n self.all_errata = set()\n self.check_ssl_dates = check_ssl_dates\n # Init cache for computed checksums to not compute it on each reposync run again\n # self.checksum_cache = rhnCache.get(checksum_cache_filename)\n # if self.checksum_cache is None:\n # self.checksum_cache = {}\n self.arches = self.get_compatible_arches(int(self.channel[\"id\"]))\n self.channel_arch = self.get_channel_arch(int(self.channel[\"id\"]))\n self.import_batch_size = default_import_batch_size", "smellKey": "S107", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def target_call_func(\n self,\n answer: Union[str, List[str]],\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n The method tokenizes and prepares the answer label for the model.\n\n Args:\n answer (`str` or `List[str]`):\n Corresponding answer supervision to the queries for training the model.\n \"\"\"\n is_batched = isinstance(answer, (list, tuple))\n\n if is_batched:\n return self.target_batch_encode_plus(\n answer=answer,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )\n else:\n return self.target_encode_plus(\n answer=answer,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "async def create_invitation(\n self,\n my_label: Optional[str] = None,\n my_endpoint: Optional[str] = None,\n auto_accept: Optional[bool] = None,\n public: bool = False,\n use_did: Optional[str] = None,\n use_did_method: Optional[str] = None,\n hs_protos: Optional[Sequence[HSProto]] = None,\n multi_use: bool = False,\n create_unique_did: bool = False,\n alias: Optional[str] = None,\n attachments: Optional[Sequence[Mapping]] = None,\n metadata: Optional[dict] = None,\n mediation_id: Optional[str] = None,\n service_accept: Optional[Sequence[Text]] = None,\n protocol_version: Optional[Text] = None,\n goal_code: Optional[Text] = None,\n goal: Optional[Text] = None,\n ) -> InvitationRecord:\n \"\"\"Generate new connection invitation.\n\n This method generates a new connection invitation, which represents an out-of-band\n communication channel. In the future and in practice, these sort of invitations\n will be received over any number of channels such as SMS, Email, QR Code, NFC,\n etc.\n\n Args:\n my_label (Optional[str]): Label for this connection.\n my_endpoint (Optional[str]): Endpoint where the other party can reach me.\n auto_accept (Optional[bool]): Auto-accept a corresponding connection request\n (None to use config).\n public (bool): Set to True to create an invitation from the public DID.\n use_did (Optional[str]): DID to use for the invitation.\n use_did_method (Optional[str]): DID method to use for the invitation.\n hs_protos (Optional[Sequence[HSProto]]): List of handshake protocols to\n include.\n multi_use (bool): Set to True to create an invitation for multiple-use\n connection.\n create_unique_did (bool): Set to True to create a unique DID for the\n invitation.\n alias (Optional[str]): Optional alias to apply to the connection for later\n use.\n attachments (Optional[Sequence[Mapping]]): List of attachments in the form of\n {\"id\": ..., \"type\": ...}.\n metadata (Optional[dict]): Additional metadata for the invitation.\n mediation_id (Optional[str]): Mediation ID for the invitation.\n service_accept (Optional[Sequence[Text]]): Optional list of mime types in the\n order of preference of the sender that the receiver can use in responding\n to the message.\n protocol_version (Optional[Text]): OOB protocol version [1.0, 1.1].\n goal_code (Optional[Text]): Optional self-attested code for receiver logic.\n goal (Optional[Text]): Optional self-attested string for receiver logic.\n\n Returns:\n InvitationRecord: The generated invitation record.\n\n \"\"\"\n creator = InvitationCreator(\n self.profile,\n self._route_manager,\n self,\n my_label,\n my_endpoint,\n auto_accept,\n public,\n use_did,\n use_did_method,\n hs_protos,\n multi_use,\n create_unique_did,\n alias,\n attachments,\n metadata,\n mediation_id,\n service_accept,\n protocol_version,\n goal_code,\n goal,\n )\n return await creator.create()", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, Data2VecTextForCausalLM, Data2VecTextConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/data2vec-text-base\")\n >>> config = Data2VecTextConfig.from_pretrained(\"facebook/data2vec-text-base\")\n >>> config.is_decoder = True\n >>> model = Data2VecTextForCausalLM.from_pretrained(\"facebook/data2vec-text-base\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.data2vec_text(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n\n labels = labels.to(shifted_prediction_scores.device)\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n do_resize: bool = True,\n size: Dict[str, int] = None,\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n do_center_crop: bool = True,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = True,\n rescale_factor: Union[int, float] = 1 / 255,\n do_pad: bool = True,\n pad_size: Dict[str, int] = None,\n constant_values: Union[float, Iterable[float]] = 0,\n pad_mode: PaddingMode = PaddingMode.CONSTANT,\n do_normalize: bool = True,\n do_flip_channel_order: bool = True,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n **kwargs,\n ) -> None:\n super().__init__(**kwargs)\n size = size if size is not None else {\"longest_edge\": 448}\n crop_size = crop_size if crop_size is not None else {\"height\": 448, \"width\": 448}\n pad_size = pad_size if pad_size is not None else {\"height\": 448, \"width\": 448}\n\n self.do_resize = do_resize\n self.size = size\n self.do_center_crop = do_center_crop\n self.crop_size = crop_size\n self.resample = resample\n self.do_rescale = do_rescale\n self.rescale_factor = rescale_factor\n self.do_pad = do_pad\n self.pad_size = pad_size\n self.constant_values = constant_values\n self.pad_mode = pad_mode\n self.do_normalize = do_normalize\n self.do_flip_channel_order = do_flip_channel_order\n self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN\n self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=9,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n scope=None,\n decoder_layers=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = decoder_layers", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n modulename,\n sources,\n extra_objects,\n build_dir,\n include_dirs,\n library_dirs,\n libraries,\n define_macros,\n undef_macros,\n f2py_flags,\n sysinfo_flags,\n fc_flags,\n flib_flags,\n setup_flags,\n remove_build_dir,\n extra_dat,\n ):\n self.modulename = modulename\n self.sources = sources\n self.extra_objects = extra_objects\n self.build_dir = build_dir\n self.include_dirs = include_dirs\n self.library_dirs = library_dirs\n self.libraries = libraries\n self.define_macros = define_macros\n self.undef_macros = undef_macros\n self.f2py_flags = f2py_flags\n self.sysinfo_flags = sysinfo_flags\n self.fc_flags = fc_flags\n self.flib_flags = flib_flags\n self.setup_flags = setup_flags\n self.remove_build_dir = remove_build_dir\n self.extra_dat = extra_dat", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=TFXLNetLMHeadModelOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n mems: np.ndarray | tf.Tensor | None = None,\n perm_mask: np.ndarray | tf.Tensor | None = None,\n target_mapping: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n input_mask: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_mems: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: bool = False,\n ) -> Union[TFXLNetLMHeadModelOutput, Tuple[tf.Tensor]]:\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,\n config.vocab_size - 1]`.\n\n Return:\n\n Examples:\n\n ```python\n >>> import tensorflow as tf\n >>> import numpy as np\n >>> from transformers import AutoTokenizer, TFXLNetLMHeadModel\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"xlnet/xlnet-large-cased\")\n >>> model = TFXLNetLMHeadModel.from_pretrained(\"xlnet/xlnet-large-cased\")\n\n >>> # We show how to setup inputs to predict a next token using a bi-directional context.\n >>> input_ids = tf.constant(tokenizer.encode(\"Hello, my dog is very <mask>\", add_special_tokens=True))[\n ... None, :\n ... ] # We will predict the masked token\n\n >>> perm_mask = np.zeros((1, input_ids.shape[1], input_ids.shape[1]))\n >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token\n\n >>> target_mapping = np.zeros(\n ... (1, 1, input_ids.shape[1])\n ... ) # Shape [1, 1, seq_length] => let's predict one token\n >>> target_mapping[\n ... 0, 0, -1\n ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)\n\n >>> outputs = model(\n ... input_ids,\n ... perm_mask=tf.constant(perm_mask, dtype=tf.float32),\n ... target_mapping=tf.constant(target_mapping, dtype=tf.float32),\n ... )\n\n >>> next_token_logits = outputs[\n ... 0\n ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]\n ```\"\"\"\n transformer_outputs = self.transformer(\n input_ids=input_ids,\n attention_mask=attention_mask,\n mems=mems,\n perm_mask=perm_mask,\n target_mapping=target_mapping,\n token_type_ids=token_type_ids,\n input_mask=input_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_mems=use_mems,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n hidden_state = transformer_outputs[0]\n logits = self.lm_loss(hidden_state, training=training)\n\n loss = None\n if labels is not None:\n loss = self.hf_compute_loss(labels, logits)\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFXLNetLMHeadModelOutput(\n loss=loss,\n logits=logits,\n mems=transformer_outputs.mems,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFRetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: np.ndarray | tf.Tensor | None = None,\n past_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = None,\n doc_scores: np.ndarray | tf.Tensor | None = None,\n context_input_ids: np.ndarray | tf.Tensor | None = None,\n context_attention_mask: np.ndarray | tf.Tensor | None = None,\n use_cache: bool | None = None,\n output_attentions: bool | None = None,\n output_hidden_states: bool | None = None,\n output_retrieved: bool | None = None,\n n_docs: int | None = None,\n do_marginalize: bool | None = None,\n labels: np.ndarray | tf.Tensor | None = None,\n reduce_loss: bool | None = None,\n return_dict: bool | None = None,\n training: bool = False,\n **kwargs, # needs kwargs for generation\n ) -> TFRetrievAugLMMarginOutput:\n r\"\"\"\n do_marginalize (`bool`, *optional*):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the cross entropy classification loss according to Rag-Token model formulation See\n https://arxiv.org/pdf/2005.11401.pdf Section 2.1 for details about Rag-Token formulation. Indices should be\n in `[0, ..., config.vocab_size - 1]`.\n reduce_loss (`bool`, *optional*):\n Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `tf.Tensor.sum`\n operation.\n kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):\n Legacy dictionary, which is required so that model can use *generate()* function.\n\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import AutoTokenizer, RagRetriever, TFRagTokenForGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/rag-token-nq\")\n >>> retriever = RagRetriever.from_pretrained(\n ... \"facebook/rag-token-nq\", index_name=\"exact\", use_dummy_dataset=True\n ... )\n >>> # initialize with RagRetriever to do everything in one forward call\n >>> model = TFRagTokenForGeneration.from_pretrained(\"facebook/rag-token-nq\", retriever=retriever, from_pt=True)\n\n >>> input_dict = tokenizer.prepare_seq2seq_batch(\n ... \"How many people live in Paris?\", \"In Paris, there are 10 million people.\", return_tensors=\"tf\"\n ... )\n >>> outputs = model(input_dict, output_retrieved=True)\n\n >>> # or use retriever separately\n >>> # 1. Encode\n >>> input_ids = input_dict[\"input_ids\"]\n >>> question_hidden_states = model.question_encoder(input_ids)[0]\n >>> # 2. Retrieve\n >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors=\"tf\")\n >>> doc_scores = tf.squeeze(\n ... tf.matmul(\n ... tf.expand_dims(question_hidden_states, axis=1), docs_dict[\"retrieved_doc_embeds\"], transpose_b=True\n ... ),\n ... axis=1,\n ... )\n >>> # 3. Forward to generator\n >>> outputs = model(\n ... inputs=None,\n ... context_input_ids=docs_dict[\"context_input_ids\"],\n ... context_attention_mask=docs_dict[\"context_attention_mask\"],\n ... doc_scores=doc_scores,\n ... decoder_input_ids=input_dict[\"labels\"],\n ... )\n\n >>> # or directly generate\n >>> generated = model.generate(\n ... context_input_ids=docs_dict[\"context_input_ids\"],\n ... context_attention_mask=docs_dict[\"context_attention_mask\"],\n ... doc_scores=doc_scores,\n ... )\n >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)\n ```\"\"\"\n\n assert (\n \"decoder_cached_states\" not in kwargs\n ), \"Please use past_key_values to cache intermediate outputs\" # from modeling_tf_bart.py\n\n do_marginalize = do_marginalize if do_marginalize else self.config.do_marginalize\n reduce_loss = reduce_loss if reduce_loss else self.config.reduce_loss\n\n if labels is not None:\n if decoder_input_ids is None:\n decoder_input_ids = labels\n use_cache = False\n\n outputs = self.rag(\n input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n context_input_ids=context_input_ids,\n context_attention_mask=context_attention_mask,\n doc_scores=doc_scores,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_retrieved=output_retrieved,\n n_docs=n_docs,\n training=training,\n )\n\n loss = None\n logits = outputs.logits\n if labels is not None:\n assert decoder_input_ids is not None\n loss = self.get_nll(\n outputs.logits,\n outputs.doc_scores,\n labels,\n reduce_loss=reduce_loss,\n epsilon=self.config.label_smoothing,\n n_docs=n_docs,\n )\n\n if do_marginalize:\n logits = self.marginalize(logits, outputs.doc_scores, n_docs)\n\n return TFRetrievAugLMMarginOutput(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n doc_scores=outputs.doc_scores,\n context_input_ids=outputs.context_input_ids,\n context_attention_mask=outputs.context_attention_mask,\n retrieved_doc_embeds=outputs.retrieved_doc_embeds,\n retrieved_doc_ids=outputs.retrieved_doc_ids,\n question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,\n question_enc_hidden_states=outputs.question_enc_hidden_states,\n question_enc_attentions=outputs.question_enc_attentions,\n generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,\n generator_enc_hidden_states=outputs.generator_enc_hidden_states,\n generator_enc_attentions=outputs.generator_enc_attentions,\n generator_dec_hidden_states=outputs.generator_dec_hidden_states,\n generator_dec_attentions=outputs.generator_dec_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=5,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=80,\n do_resize=True,\n size=None,\n do_center_crop=True,\n crop_size=None,\n do_normalize=True,\n image_mean=OPENAI_CLIP_MEAN,\n image_std=OPENAI_CLIP_STD,\n do_convert_rgb=True,\n ):\n super().__init__()\n size = size if size is not None else {\"shortest_edge\": 20}\n crop_size = crop_size if crop_size is not None else {\"height\": 18, \"width\": 18}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_center_crop = do_center_crop\n self.crop_size = crop_size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(ROBERTA_PRELAYERNORM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple, TFBaseModelOutputWithPoolingAndCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n \"\"\"\n outputs = self.roberta_prelayernorm(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(PIX2STRUCT_TEXT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n return_dict: Optional[bool] = None,\n **kwargs,\n ) -> Union[Tuple[torch.FloatTensor, ...], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoProcessor, Pix2StructTextModel\n\n >>> processor = AutoProcessor.from_pretrained(\"google/pix2struct-textcaps-base\")\n >>> model = Pix2StructTextModel.from_pretrained(\"google/pix2struct-textcaps-base\")\n\n >>> inputs = processor(text=\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> loss = outputs.loss\n ```\n \"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n input_ids = input_ids.view(-1, input_shape[-1])\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\n\n if inputs_embeds is None:\n assert self.embed_tokens is not None, \"You have to initialize the model with valid token embeddings\"\n inputs_embeds = self.embed_tokens(input_ids)\n\n batch_size, seq_length = input_shape\n\n # required mask seq length can be calculated via length of past\n mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length\n\n if attention_mask is None:\n attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)\n if encoder_attention_mask is None and encoder_hidden_states is not None:\n encoder_seq_length = encoder_hidden_states.shape[1]\n encoder_attention_mask = torch.ones(\n batch_size, encoder_seq_length, device=inputs_embeds.device, dtype=torch.long\n )\n\n # initialize past_key_values with `None` if past does not exist\n if past_key_values is None:\n past_key_values = [None] * len(self.layer)\n\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)\n\n # If a 2D or 3D attention mask is provided for the cross-attention\n # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]\n if encoder_hidden_states is not None:\n encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(encoder_hidden_shape, device=inputs_embeds.device)\n encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)\n else:\n encoder_extended_attention_mask = None\n\n # Prepare head mask if needed\n head_mask = self.get_head_mask(head_mask, self.config.num_layers)\n cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)\n present_key_value_states = () if use_cache else None\n all_hidden_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n all_cross_attentions = () if (output_attentions) else None\n position_bias = None\n encoder_decoder_position_bias = None\n\n hidden_states = self.dropout(inputs_embeds)\n\n for i, (layer_module, past_key_value) in enumerate(zip(self.layer, past_key_values)):\n layer_head_mask = head_mask[i]\n cross_attn_layer_head_mask = cross_attn_head_mask[i]\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.gradient_checkpointing and self.training:\n if use_cache:\n logger.warning(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n layer_outputs = self._gradient_checkpointing_func(\n layer_module.forward,\n hidden_states,\n extended_attention_mask,\n position_bias,\n encoder_hidden_states,\n encoder_extended_attention_mask,\n encoder_decoder_position_bias,\n layer_head_mask,\n cross_attn_layer_head_mask,\n None, # past_key_value is always None with gradient checkpointing\n use_cache,\n output_attentions,\n )\n else:\n layer_outputs = layer_module(\n hidden_states,\n attention_mask=extended_attention_mask,\n position_bias=position_bias,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_extended_attention_mask,\n encoder_decoder_position_bias=encoder_decoder_position_bias,\n layer_head_mask=layer_head_mask,\n cross_attn_layer_head_mask=cross_attn_layer_head_mask,\n past_key_value=past_key_value,\n use_cache=use_cache,\n output_attentions=output_attentions,\n )\n\n # layer_outputs is a tuple with:\n # hidden-states, key-value-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)\n if use_cache is False:\n layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]\n\n hidden_states, present_key_value_state = layer_outputs[:2]\n\n # We share the position biases between the layers - the first layer store them\n # layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),\n # (cross-attention position bias), (cross-attention weights)\n position_bias = layer_outputs[2]\n if encoder_hidden_states is not None:\n encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]\n # append next layer key value states\n if use_cache:\n present_key_value_states = present_key_value_states + (present_key_value_state,)\n\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[3],)\n if encoder_hidden_states is not None:\n all_cross_attentions = all_cross_attentions + (layer_outputs[5],)\n\n hidden_states = self.final_layer_norm(hidden_states)\n hidden_states = self.dropout(hidden_states)\n\n logits = self.lm_head(hidden_states)\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(logits.device)\n loss_fct = nn.CrossEntropyLoss(ignore_index=-100, reduction=\"mean\")\n\n loss = loss_fct(logits.contiguous().view(-1, logits.size(-1)), labels.contiguous().view(-1))\n\n if not return_dict:\n return tuple(\n v\n for v in [\n loss,\n logits,\n present_key_value_states,\n all_hidden_states,\n all_attentions,\n all_cross_attentions,\n ]\n if v is not None\n )\n return CausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=logits,\n past_key_values=present_key_value_states,\n hidden_states=all_hidden_states,\n attentions=all_attentions,\n cross_attentions=all_cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "async def async_turn_on(\n hass: HomeAssistant,\n entity_id: str = ENTITY_MATCH_ALL,\n transition: float | None = None,\n brightness: int | None = None,\n brightness_pct: float | None = None,\n rgb_color: tuple[int, int, int] | None = None,\n rgbw_color: tuple[int, int, int, int] | None = None,\n rgbww_color: tuple[int, int, int, int, int] | None = None,\n xy_color: tuple[float, float] | None = None,\n hs_color: tuple[float, float] | None = None,\n color_temp: int | None = None,\n kelvin: int | None = None,\n profile: str | None = None,\n flash: str | None = None,\n effect: str | None = None,\n color_name: str | None = None,\n white: bool | None = None,\n) -> None:\n \"\"\"Turn all or specified light on.\"\"\"\n data = {\n key: value\n for key, value in (\n (ATTR_ENTITY_ID, entity_id),\n (ATTR_PROFILE, profile),\n (ATTR_TRANSITION, transition),\n (ATTR_BRIGHTNESS, brightness),\n (ATTR_BRIGHTNESS_PCT, brightness_pct),\n (ATTR_RGB_COLOR, rgb_color),\n (ATTR_RGBW_COLOR, rgbw_color),\n (ATTR_RGBWW_COLOR, rgbww_color),\n (ATTR_XY_COLOR, xy_color),\n (ATTR_HS_COLOR, hs_color),\n (ATTR_COLOR_TEMP, color_temp),\n (ATTR_KELVIN, kelvin),\n (ATTR_FLASH, flash),\n (ATTR_EFFECT, effect),\n (ATTR_COLOR_NAME, color_name),\n (ATTR_WHITE, white),\n )\n if value is not None\n }\n\n await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data, blocking=True)", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(self, args, bufsize=-1, executable=None,\n stdin=None, stdout=None, stderr=None,\n preexec_fn=None, close_fds=True,\n shell=False, cwd=None, env=None, universal_newlines=None,\n startupinfo=None, creationflags=0,\n restore_signals=True, start_new_session=False,\n pass_fds=(), *, user=None, group=None, extra_groups=None,\n encoding=None, errors=None, text=None, umask=-1, pipesize=-1,\n process_group=None):\n \"\"\"Create new Popen instance.\"\"\"\n if not _can_fork_exec:\n raise OSError(\n errno.ENOTSUP, f\"{sys.platform} does not support processes.\"\n )\n\n _cleanup()\n # Held while anything is calling waitpid before returncode has been\n # updated to prevent clobbering returncode if wait() or poll() are\n # called from multiple threads at once. After acquiring the lock,\n # code must re-check self.returncode to see if another thread just\n # finished a waitpid() call.\n self._waitpid_lock = threading.Lock()\n\n self._input = None\n self._communication_started = False\n if bufsize is None:\n bufsize = -1 # Restore default\n if not isinstance(bufsize, int):\n raise TypeError(\"bufsize must be an integer\")\n\n if stdout is STDOUT:\n raise ValueError(\"STDOUT can only be used for stderr\")\n\n if pipesize is None:\n pipesize = -1 # Restore default\n if not isinstance(pipesize, int):\n raise TypeError(\"pipesize must be an integer\")\n\n if _mswindows:\n if preexec_fn is not None:\n raise ValueError(\"preexec_fn is not supported on Windows \"\n \"platforms\")\n else:\n # POSIX\n if pass_fds and not close_fds:\n warnings.warn(\"pass_fds overriding close_fds.\", RuntimeWarning)\n close_fds = True\n if startupinfo is not None:\n raise ValueError(\"startupinfo is only supported on Windows \"\n \"platforms\")\n if creationflags != 0:\n raise ValueError(\"creationflags is only supported on Windows \"\n \"platforms\")\n\n self.args = args\n self.stdin = None\n self.stdout = None\n self.stderr = None\n self.pid = None\n self.returncode = None\n self.encoding = encoding\n self.errors = errors\n self.pipesize = pipesize\n\n # Validate the combinations of text and universal_newlines\n if (text is not None and universal_newlines is not None\n and bool(universal_newlines) != bool(text)):\n raise SubprocessError('Cannot disambiguate when both text '\n 'and universal_newlines are supplied but '\n 'different. Pass one or the other.')\n\n self.text_mode = encoding or errors or text or universal_newlines\n if self.text_mode and encoding is None:\n self.encoding = encoding = _text_encoding()\n\n # How long to resume waiting on a child after the first ^C.\n # There is no right value for this. The purpose is to be polite\n # yet remain good for interactive users trying to exit a tool.\n self._sigint_wait_secs = 0.25 # 1/xkcd221.getRandomNumber()\n\n self._closed_child_pipe_fds = False\n\n if self.text_mode:\n if bufsize == 1:\n line_buffering = True\n # Use the default buffer size for the underlying binary streams\n # since they don't support line buffering.\n bufsize = -1\n else:\n line_buffering = False\n\n if process_group is None:\n process_group = -1 # The internal APIs are int-only\n\n gid = None\n if group is not None:\n if not hasattr(os, 'setregid'):\n raise ValueError(\"The 'group' parameter is not supported on the \"\n \"current platform\")\n\n elif isinstance(group, str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"The group parameter cannot be a string \"\n \"on systems without the grp module\")\n\n gid = grp.getgrnam(group).gr_gid\n elif isinstance(group, int):\n gid = group\n else:\n raise TypeError(\"Group must be a string or an integer, not {}\"\n .format(type(group)))\n\n if gid < 0:\n raise ValueError(f\"Group ID cannot be negative, got {gid}\")\n\n gids = None\n if extra_groups is not None:\n if not hasattr(os, 'setgroups'):\n raise ValueError(\"The 'extra_groups' parameter is not \"\n \"supported on the current platform\")\n\n elif isinstance(extra_groups, str):\n raise ValueError(\"Groups must be a list, not a string\")\n\n gids = []\n for extra_group in extra_groups:\n if isinstance(extra_group, str):\n try:\n import grp\n except ImportError:\n raise ValueError(\"Items in extra_groups cannot be \"\n \"strings on systems without the \"\n \"grp module\")\n\n gids.append(grp.getgrnam(extra_group).gr_gid)\n elif isinstance(extra_group, int):\n gids.append(extra_group)\n else:\n raise TypeError(\"Items in extra_groups must be a string \"\n \"or integer, not {}\"\n .format(type(extra_group)))\n\n # make sure that the gids are all positive here so we can do less\n # checking in the C code\n for gid_check in gids:\n if gid_check < 0:\n raise ValueError(f\"Group ID cannot be negative, got {gid_check}\")\n\n uid = None\n if user is not None:\n if not hasattr(os, 'setreuid'):\n raise ValueError(\"The 'user' parameter is not supported on \"\n \"the current platform\")\n\n elif isinstance(user, str):\n try:\n import pwd\n except ImportError:\n raise ValueError(\"The user parameter cannot be a string \"\n \"on systems without the pwd module\")\n uid = pwd.getpwnam(user).pw_uid\n elif isinstance(user, int):\n uid = user\n else:\n raise TypeError(\"User must be a string or an integer\")\n\n if uid < 0:\n raise ValueError(f\"User ID cannot be negative, got {uid}\")\n\n # Input and output objects. The general principle is like\n # this:\n #\n # Parent Child\n # ------ -----\n # p2cwrite ---stdin---> p2cread\n # c2pread <--stdout--- c2pwrite\n # errread <--stderr--- errwrite\n #\n # On POSIX, the child objects are file descriptors. On\n # Windows, these are Windows file handles. The parent objects\n # are file descriptors on both platforms. The parent objects\n # are -1 when not using PIPEs. The child objects are -1\n # when not redirecting.\n\n (p2cread, p2cwrite,\n c2pread, c2pwrite,\n errread, errwrite) = self._get_handles(stdin, stdout, stderr)\n\n # From here on, raising exceptions may cause file descriptor leakage\n\n # We wrap OS handles *before* launching the child, otherwise a\n # quickly terminating child could make our fds unwrappable\n # (see #8458).\n\n if _mswindows:\n if p2cwrite != -1:\n p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)\n if c2pread != -1:\n c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)\n if errread != -1:\n errread = msvcrt.open_osfhandle(errread.Detach(), 0)\n\n try:\n if p2cwrite != -1:\n self.stdin = io.open(p2cwrite, 'wb', bufsize)\n if self.text_mode:\n self.stdin = io.TextIOWrapper(self.stdin, write_through=True,\n line_buffering=line_buffering,\n encoding=encoding, errors=errors)\n if c2pread != -1:\n self.stdout = io.open(c2pread, 'rb', bufsize)\n if self.text_mode:\n self.stdout = io.TextIOWrapper(self.stdout,\n encoding=encoding, errors=errors)\n if errread != -1:\n self.stderr = io.open(errread, 'rb', bufsize)\n if self.text_mode:\n self.stderr = io.TextIOWrapper(self.stderr,\n encoding=encoding, errors=errors)\n\n self._execute_child(args, executable, preexec_fn, close_fds,\n pass_fds, cwd, env,\n startupinfo, creationflags, shell,\n p2cread, p2cwrite,\n c2pread, c2pwrite,\n errread, errwrite,\n restore_signals,\n gid, gids, uid, umask,\n start_new_session, process_group)\n except:\n # Cleanup if the child failed starting.\n for f in filter(None, (self.stdin, self.stdout, self.stderr)):\n try:\n f.close()\n except OSError:\n pass # Ignore EBADF or other errors.\n\n if not self._closed_child_pipe_fds:\n to_close = []\n if stdin == PIPE:\n to_close.append(p2cread)\n if stdout == PIPE:\n to_close.append(c2pwrite)\n if stderr == PIPE:\n to_close.append(errwrite)\n if hasattr(self, '_devnull'):\n to_close.append(self._devnull)\n for fd in to_close:\n try:\n if _mswindows and isinstance(fd, Handle):\n fd.Close()\n else:\n os.close(fd)\n except OSError:\n pass\n\n raise", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n entity_vocab_file,\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n task=None,\n max_entity_length=32,\n max_mention_length=30,\n entity_token_1=\"<ent>\",\n entity_token_2=\"<ent2>\",\n entity_unk_token=\"[UNK]\",\n entity_pad_token=\"[PAD]\",\n entity_mask_token=\"[MASK]\",\n entity_mask2_token=\"[MASK2]\",\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n **kwargs,\n ) -> None:\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n # we add 2 special tokens for downstream tasks\n # for more information about lstrip and rstrip, see https://github.com/huggingface/transformers/pull/2778\n entity_token_1 = (\n AddedToken(entity_token_1, lstrip=False, rstrip=False)\n if isinstance(entity_token_1, str)\n else entity_token_1\n )\n entity_token_2 = (\n AddedToken(entity_token_2, lstrip=False, rstrip=False)\n if isinstance(entity_token_2, str)\n else entity_token_2\n )\n additional_special_tokens = kwargs.pop(\"additional_special_tokens\", [])\n additional_special_tokens += [entity_token_1, entity_token_2]\n\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.Load(str(vocab_file))\n self.vocab_file = vocab_file\n\n # Original fairseq vocab and spm vocab must be \"aligned\":\n # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----\n # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '\u2581' | 's' | '\u2581de' | '-'\n # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '\u2581' | 's' | '\u2581de' | '-' | '\u2581a'\n\n # Mimic fairseq token-to-id alignment for the first 4 token\n self.fairseq_tokens_to_ids = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3}\n\n # The first \"real\" token \",\" has position 4 in the original fairseq vocab and position 3 in the spm vocab\n self.fairseq_offset = 1\n\n self.fairseq_tokens_to_ids[\"<mask>\"] = len(self.sp_model) + self.fairseq_offset\n self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}\n\n with open(entity_vocab_file, encoding=\"utf-8\") as entity_vocab_handle:\n self.entity_vocab = json.load(entity_vocab_handle)\n for entity_special_token in [entity_unk_token, entity_pad_token, entity_mask_token, entity_mask2_token]:\n if entity_special_token not in self.entity_vocab:\n raise ValueError(\n f\"Specified entity special token ``{entity_special_token}`` is not found in entity_vocab. \"\n f\"Probably an incorrect entity vocab file is loaded: {entity_vocab_file}.\"\n )\n self.entity_unk_token_id = self.entity_vocab[entity_unk_token]\n self.entity_pad_token_id = self.entity_vocab[entity_pad_token]\n self.entity_mask_token_id = self.entity_vocab[entity_mask_token]\n self.entity_mask2_token_id = self.entity_vocab[entity_mask2_token]\n\n self.task = task\n if task is None or task == \"entity_span_classification\":\n self.max_entity_length = max_entity_length\n elif task == \"entity_classification\":\n self.max_entity_length = 1\n elif task == \"entity_pair_classification\":\n self.max_entity_length = 2\n else:\n raise ValueError(\n f\"Task {task} not supported. Select task from ['entity_classification', 'entity_pair_classification',\"\n \" 'entity_span_classification'] only.\"\n )\n\n self.max_mention_length = max_mention_length\n\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n sp_model_kwargs=self.sp_model_kwargs,\n task=task,\n max_entity_length=max_entity_length,\n max_mention_length=max_mention_length,\n entity_token_1=entity_token_1,\n entity_token_2=entity_token_2,\n entity_unk_token=entity_unk_token,\n entity_pad_token=entity_pad_token,\n entity_mask_token=entity_mask_token,\n entity_mask2_token=entity_mask2_token,\n additional_special_tokens=additional_special_tokens,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n title,\n link,\n description,\n language=None,\n author_email=None,\n author_name=None,\n author_link=None,\n subtitle=None,\n categories=None,\n feed_url=None,\n feed_copyright=None,\n feed_guid=None,\n ttl=None,\n stylesheets=None,\n **kwargs,\n ):\n def to_str(s):\n return str(s) if s is not None else s\n\n def to_stylesheet(s):\n return s if isinstance(s, Stylesheet) else Stylesheet(s)\n\n categories = categories and [str(c) for c in categories]\n\n if stylesheets is not None:\n if isinstance(stylesheets, (Stylesheet, str)):\n raise TypeError(\n f\"stylesheets should be a list, not {stylesheets.__class__}\"\n )\n stylesheets = [to_stylesheet(s) for s in stylesheets]\n\n self.feed = {\n \"title\": to_str(title),\n \"link\": iri_to_uri(link),\n \"description\": to_str(description),\n \"language\": to_str(language),\n \"author_email\": to_str(author_email),\n \"author_name\": to_str(author_name),\n \"author_link\": iri_to_uri(author_link),\n \"subtitle\": to_str(subtitle),\n \"categories\": categories or (),\n \"feed_url\": iri_to_uri(feed_url),\n \"feed_copyright\": to_str(feed_copyright),\n \"id\": feed_guid or link,\n \"ttl\": to_str(ttl),\n \"stylesheets\": stylesheets,\n **kwargs,\n }\n self.items = []", "smellKey": "S107", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=XLNetLMHeadModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n mems: Optional[torch.Tensor] = None,\n perm_mask: Optional[torch.Tensor] = None,\n target_mapping: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n input_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n use_mems: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n **kwargs, # delete when `use_cache` is removed in XLNetModel\n ) -> Union[Tuple, XLNetLMHeadModelOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):\n Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If\n `target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.\n\n The labels should correspond to the masked input words that should be predicted and depends on\n `target_mapping`. Note in order to perform standard auto-regressive language modeling a *<mask>* token has\n to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)\n\n Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss\n is only computed for labels in `[0, ..., config.vocab_size]`\n\n Return:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, XLNetLMHeadModel\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"xlnet/xlnet-large-cased\")\n >>> model = XLNetLMHeadModel.from_pretrained(\"xlnet/xlnet-large-cased\")\n\n >>> # We show how to setup inputs to predict a next token using a bi-directional context.\n >>> input_ids = torch.tensor(\n ... tokenizer.encode(\"Hello, my dog is very <mask>\", add_special_tokens=False)\n ... ).unsqueeze(\n ... 0\n ... ) # We will predict the masked token\n >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)\n >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token\n >>> target_mapping = torch.zeros(\n ... (1, 1, input_ids.shape[1]), dtype=torch.float\n ... ) # Shape [1, 1, seq_length] => let's predict one token\n >>> target_mapping[\n ... 0, 0, -1\n ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)\n\n >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)\n >>> next_token_logits = outputs[\n ... 0\n ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]\n\n >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.\n >>> input_ids = torch.tensor(\n ... tokenizer.encode(\"Hello, my dog is very <mask>\", add_special_tokens=False)\n ... ).unsqueeze(\n ... 0\n ... ) # We will predict the masked token\n >>> labels = torch.tensor(tokenizer.encode(\"cute\", add_special_tokens=False)).unsqueeze(0)\n >>> assert labels.shape[0] == 1, \"only one word will be predicted\"\n >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)\n >>> perm_mask[\n ... :, :, -1\n ... ] = 1.0 # Previous tokens don't see last token as is done in standard auto-regressive lm training\n >>> target_mapping = torch.zeros(\n ... (1, 1, input_ids.shape[1]), dtype=torch.float\n ... ) # Shape [1, 1, seq_length] => let's predict one token\n >>> target_mapping[\n ... 0, 0, -1\n ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)\n\n >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)\n >>> loss = outputs.loss\n >>> next_token_logits = (\n ... outputs.logits\n ... ) # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n mems=mems,\n perm_mask=perm_mask,\n target_mapping=target_mapping,\n token_type_ids=token_type_ids,\n input_mask=input_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_mems=use_mems,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n **kwargs,\n )\n\n logits = self.lm_loss(transformer_outputs[0])\n\n loss = None\n if labels is not None:\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return XLNetLMHeadModelOutput(\n loss=loss,\n logits=logits,\n mems=transformer_outputs.mems,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.fixture(scope=\"function\")\ndef tomte_context(\n cg_context: CGConfig,\n helpers: StoreHelpers,\n nf_analysis_housekeeper: HousekeeperAPI,\n trailblazer_api: MockTB,\n hermes_api: HermesApi,\n cg_dir: Path,\n tomte_case_id: str,\n sample_id: str,\n no_sample_case_id: str,\n total_sequenced_reads_pass: int,\n apptag_rna: str,\n case_id_not_enough_reads: str,\n sample_id_not_enough_reads: str,\n total_sequenced_reads_not_pass: int,\n) -> CGConfig:\n \"\"\"Context to use in CLI.\"\"\"\n cg_context.housekeeper_api_ = nf_analysis_housekeeper\n cg_context.trailblazer_api_ = trailblazer_api\n cg_context.meta_apis[\"analysis_api\"] = TomteAnalysisAPI(config=cg_context)\n status_db: Store = cg_context.status_db\n\n # NB: the order in which the cases are added matters for the tests of store_available\n\n # Create ERROR case with NO SAMPLES\n helpers.add_case(status_db, internal_id=no_sample_case_id, name=no_sample_case_id)\n\n # Create a textbook case with enough reads\n case_enough_reads: Case = helpers.add_case(\n store=status_db,\n internal_id=tomte_case_id,\n name=tomte_case_id,\n data_analysis=Workflow.TOMTE,\n panels=[GenePanelMasterList.OMIM_AUTO],\n )\n\n sample_enough_reads: Sample = helpers.add_sample(\n status_db,\n application_tag=apptag_rna,\n internal_id=sample_id,\n reads=total_sequenced_reads_pass,\n last_sequenced_at=datetime.now(),\n reference_genome=GenomeVersion.HG38,\n )\n\n helpers.add_relationship(\n status_db,\n case=case_enough_reads,\n sample=sample_enough_reads,\n )\n\n # Create a case without enough reads\n case_not_enough_reads: Case = helpers.add_case(\n store=status_db,\n internal_id=case_id_not_enough_reads,\n name=case_id_not_enough_reads,\n data_analysis=Workflow.TOMTE,\n )\n\n sample_not_enough_reads: Sample = helpers.add_sample(\n status_db,\n application_tag=apptag_rna,\n internal_id=sample_id_not_enough_reads,\n reads=total_sequenced_reads_not_pass,\n last_sequenced_at=datetime.now(),\n )\n\n helpers.add_relationship(status_db, case=case_not_enough_reads, sample=sample_not_enough_reads)\n\n return cg_context", "smellKey": "S107", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32064,\n hidden_size=4096,\n intermediate_size=6400,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=8,\n hidden_act=\"silu\",\n max_position_embeddings=4096 * 32,\n initializer_range=0.02,\n rms_norm_eps=1e-5,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n rope_theta=1e6,\n rope_scaling=None,\n sliding_window=None,\n attention_dropout=0.0,\n num_experts_per_tok=2,\n num_local_experts=16,\n output_router_logits=False,\n router_aux_loss_coef=0.001,\n router_jitter_noise=0.01,\n input_jitter_noise=0.0,\n attention_bias=False,\n lm_head_bias=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.sliding_window = sliding_window\n self.attention_bias = attention_bias\n self.lm_head_bias = lm_head_bias\n # for backward compatibility\n if num_key_value_heads is None:\n num_key_value_heads = num_attention_heads\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.attention_dropout = attention_dropout\n\n self.num_experts_per_tok = num_experts_per_tok\n self.num_local_experts = num_local_experts\n self.output_router_logits = output_router_logits\n self.router_aux_loss_coef = router_aux_loss_coef\n self.router_jitter_noise = router_jitter_noise\n self.input_jitter_noise = input_jitter_noise\n\n self.rope_scaling = rope_scaling\n if isinstance(self.rope_scaling, dict):\n if \"rope_type\" not in self.rope_scaling:\n self.rope_scaling[\"rope_type\"] = self.rope_scaling.get(\"type\", None)\n if \"original_max_position_embeddings\" in self.rope_scaling:\n self.original_max_position_embeddings = self.rope_scaling[\"original_max_position_embeddings\"]\n rope_scaling_short_mscale = self.rope_scaling.get(\"short_mscale\", None)\n rope_scaling_long_mscale = self.rope_scaling.get(\"long_mscale\", None)\n if not isinstance(rope_scaling_short_mscale, (int, float)):\n raise ValueError(\n f\"`rope_scaling`'s short_mscale field must be a number, got {rope_scaling_short_mscale}\"\n )\n if not isinstance(rope_scaling_long_mscale, (int, float)):\n raise ValueError(\n f\"`rope_scaling`'s long_mscale field must be a number, got {rope_scaling_long_mscale}\"\n )\n\n rope_config_validation(self)\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n hidden_size=4096,\n intermediate_size=14336,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=8,\n hidden_act=\"silu\",\n max_position_embeddings=4096 * 32,\n initializer_range=0.02,\n rms_norm_eps=1e-5,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n rope_theta=1e6,\n sliding_window=None,\n attention_dropout=0.0,\n num_experts_per_tok=2,\n num_local_experts=8,\n output_router_logits=False,\n router_aux_loss_coef=0.001,\n router_jitter_noise=0.0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.sliding_window = sliding_window\n\n # for backward compatibility\n if num_key_value_heads is None:\n num_key_value_heads = num_attention_heads\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.attention_dropout = attention_dropout\n\n self.num_experts_per_tok = num_experts_per_tok\n self.num_local_experts = num_local_experts\n self.output_router_logits = output_router_logits\n self.router_aux_loss_coef = router_aux_loss_coef\n self.router_jitter_noise = router_jitter_noise\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format(\"reader_beam_size, sequence_length\"))\n @replace_return_docstrings(output_type=RealmReaderOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n relevance_score: Optional[torch.FloatTensor] = None,\n block_mask: Optional[torch.BoolTensor] = None,\n start_positions: Optional[torch.LongTensor] = None,\n end_positions: Optional[torch.LongTensor] = None,\n has_answers: Optional[torch.BoolTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, RealmReaderOutput]:\n r\"\"\"\n relevance_score (`torch.FloatTensor` of shape `(searcher_beam_size,)`, *optional*):\n Relevance score, which must be specified if you want to compute the logits and marginal log loss.\n block_mask (`torch.BoolTensor` of shape `(searcher_beam_size, sequence_length)`, *optional*):\n The mask of the evidence block, which must be specified if you want to compute the logits and marginal log\n loss.\n start_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n has_answers (`torch.BoolTensor` of shape `(searcher_beam_size,)`, *optional*):\n Whether or not the evidence block has answer(s).\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if relevance_score is None:\n raise ValueError(\"You have to specify `relevance_score` to calculate logits and loss.\")\n if block_mask is None:\n raise ValueError(\"You have to specify `block_mask` to separate question block and evidence block.\")\n if token_type_ids.size(1) < self.config.max_span_width:\n raise ValueError(\"The input sequence length must be greater than or equal to config.max_span_width.\")\n outputs = self.realm(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n # [reader_beam_size, joint_seq_len, hidden_size]\n sequence_output = outputs[0]\n\n # [reader_beam_size, num_candidates], [num_candidates], [num_candidates]\n reader_logits, candidate_starts, candidate_ends = self.qa_outputs(\n sequence_output, block_mask[0 : self.config.reader_beam_size]\n )\n # [searcher_beam_size, 1]\n retriever_logits = torch.unsqueeze(relevance_score[0 : self.config.reader_beam_size], -1)\n # [reader_beam_size, num_candidates]\n reader_logits += retriever_logits\n # []\n predicted_block_index = torch.argmax(torch.max(reader_logits, dim=1).values)\n # []\n predicted_candidate = torch.argmax(torch.max(reader_logits, dim=0).values)\n # [1]\n predicted_start = torch.index_select(candidate_starts, dim=0, index=predicted_candidate)\n # [1]\n predicted_end = torch.index_select(candidate_ends, dim=0, index=predicted_candidate)\n\n total_loss = None\n retriever_loss = None\n reader_loss = None\n retriever_correct = None\n reader_correct = None\n if start_positions is not None and end_positions is not None and has_answers is not None:\n\n def compute_correct_candidates(candidate_starts, candidate_ends, gold_starts, gold_ends):\n \"\"\"Compute correct span.\"\"\"\n # [reader_beam_size, num_answers, num_candidates]\n is_gold_start = torch.eq(\n torch.unsqueeze(torch.unsqueeze(candidate_starts, 0), 0), torch.unsqueeze(gold_starts, -1)\n )\n is_gold_end = torch.eq(\n torch.unsqueeze(torch.unsqueeze(candidate_ends, 0), 0), torch.unsqueeze(gold_ends, -1)\n )\n\n # [reader_beam_size, num_candidates]\n return torch.any(torch.logical_and(is_gold_start, is_gold_end), 1)\n\n def marginal_log_loss(logits, is_correct):\n \"\"\"Loss based on the negative marginal log-likelihood.\"\"\"\n\n def mask_to_score(mask, dtype=torch.float32):\n return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min\n\n # []\n log_numerator = torch.logsumexp(logits + mask_to_score(is_correct, dtype=logits.dtype), dim=-1)\n log_denominator = torch.logsumexp(logits, dim=-1)\n return log_denominator - log_numerator\n\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n # `-1` is reserved for no answer.\n ignored_index = sequence_output.size(1)\n start_positions = start_positions.clamp(-1, ignored_index)\n end_positions = end_positions.clamp(-1, ignored_index)\n\n retriever_correct = has_answers\n any_retriever_correct = torch.any(retriever_correct)\n\n reader_correct = compute_correct_candidates(\n candidate_starts=candidate_starts,\n candidate_ends=candidate_ends,\n gold_starts=start_positions[0 : self.config.reader_beam_size],\n gold_ends=end_positions[0 : self.config.reader_beam_size],\n )\n any_reader_correct = torch.any(reader_correct)\n\n retriever_loss = marginal_log_loss(relevance_score, retriever_correct)\n reader_loss = marginal_log_loss(reader_logits.view(-1), reader_correct.view(-1))\n retriever_loss *= any_retriever_correct.type(torch.float32)\n reader_loss *= any_reader_correct.type(torch.float32)\n\n total_loss = (retriever_loss + reader_loss).mean()\n\n if not return_dict:\n output = (predicted_block_index, predicted_candidate, predicted_start, predicted_end) + outputs[2:]\n return (\n ((total_loss, retriever_loss, reader_loss, retriever_correct, reader_correct) + output)\n if total_loss is not None\n else output\n )\n\n return RealmReaderOutput(\n loss=total_loss,\n retriever_loss=retriever_loss,\n reader_loss=reader_loss,\n retriever_correct=retriever_correct,\n reader_correct=reader_correct,\n block_idx=predicted_block_index,\n candidate=predicted_candidate,\n start_pos=predicted_start,\n end_pos=predicted_end,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32128,\n d_model=512,\n d_kv=64,\n d_ff=2048,\n num_layers=6,\n num_decoder_layers=None,\n num_heads=8,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n dropout_rate=0.1,\n layer_norm_epsilon=1e-6,\n initializer_factor=1.0,\n feed_forward_proj=\"relu\",\n is_encoder_decoder=True,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n classifier_dropout=0.0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.d_kv = d_kv\n self.d_ff = d_ff\n self.num_layers = num_layers\n self.num_decoder_layers = (\n num_decoder_layers if num_decoder_layers is not None else self.num_layers\n ) # default = symmetry\n self.num_heads = num_heads\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n self.dropout_rate = dropout_rate\n self.classifier_dropout = classifier_dropout\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_factor = initializer_factor\n self.feed_forward_proj = feed_forward_proj\n self.use_cache = use_cache\n\n act_info = self.feed_forward_proj.split(\"-\")\n self.dense_act_fn = act_info[-1]\n self.is_gated_act = act_info[0] == \"gated\"\n\n if len(act_info) > 1 and act_info[0] != \"gated\" or len(act_info) > 2:\n raise ValueError(\n f\"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. \"\n \"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. \"\n \"'gated-gelu' or 'relu'\"\n )\n\n # for backwards compatibility\n if feed_forward_proj == \"gated-gelu\":\n self.dense_act_fn = \"gelu_new\"\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n word_shape_file,\n word_pronunciation_file,\n do_lower_case=True,\n do_basic_tokenize=True,\n never_split=None,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n tokenize_chinese_chars=True,\n strip_accents=None,\n **kwargs,\n ):\n for cur_file in [vocab_file, word_shape_file, word_pronunciation_file]:\n if cur_file is None or not os.path.isfile(cur_file):\n raise ValueError(\n f\"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google \"\n \"pretrained model use `tokenizer = RoCBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\"\n )\n\n self.vocab = load_vocab(vocab_file)\n\n with open(word_shape_file, \"r\", encoding=\"utf8\") as in_file:\n self.word_shape = json.load(in_file)\n\n with open(word_pronunciation_file, \"r\", encoding=\"utf8\") as in_file:\n self.word_pronunciation = json.load(in_file)\n\n self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])\n\n self.do_basic_tokenize = do_basic_tokenize\n if do_basic_tokenize:\n self.basic_tokenizer = RoCBertBasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n )\n self.wordpiece_tokenizer = RoCBertWordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=do_basic_tokenize,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n flags: int,\n db: str,\n coll: str,\n ntoskip: int,\n spec: Mapping[str, Any],\n fields: Optional[Mapping[str, Any]],\n codec_options: CodecOptions,\n read_preference: _ServerMode,\n limit: int,\n batch_size: int,\n read_concern: ReadConcern,\n collation: Optional[Mapping[str, Any]],\n session: Optional[ClientSession],\n client: MongoClient,\n allow_disk_use: Optional[bool],\n exhaust: bool,\n ):\n self.flags = flags\n self.db = db\n self.coll = coll\n self.ntoskip = ntoskip\n self.spec = spec\n self.fields = fields\n self.codec_options = codec_options\n self.read_preference = read_preference\n self.read_concern = read_concern\n self.limit = limit\n self.batch_size = batch_size\n self.collation = collation\n self.session = session\n self.client = client\n self.allow_disk_use = allow_disk_use\n self.name = \"find\"\n self._as_command: Optional[tuple[dict[str, Any], str]] = None\n self.exhaust = exhaust", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=38,\n hidden_size=192,\n num_hidden_layers=6,\n num_attention_heads=2,\n window_size=4,\n use_bias=True,\n ffn_dim=768,\n layerdrop=0.1,\n ffn_kernel_size=3,\n flow_size=192,\n spectrogram_bins=513,\n hidden_act=\"relu\",\n hidden_dropout=0.1,\n attention_dropout=0.1,\n activation_dropout=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n use_stochastic_duration_prediction=True,\n num_speakers=1,\n speaker_embedding_size=0,\n upsample_initial_channel=512,\n upsample_rates=[8, 8, 2, 2],\n upsample_kernel_sizes=[16, 16, 4, 4],\n resblock_kernel_sizes=[3, 7, 11],\n resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],\n leaky_relu_slope=0.1,\n depth_separable_channels=2,\n depth_separable_num_layers=3,\n duration_predictor_flow_bins=10,\n duration_predictor_tail_bound=5.0,\n duration_predictor_kernel_size=3,\n duration_predictor_dropout=0.5,\n duration_predictor_num_flows=4,\n duration_predictor_filter_channels=256,\n prior_encoder_num_flows=4,\n prior_encoder_num_wavenet_layers=4,\n posterior_encoder_num_wavenet_layers=16,\n wavenet_kernel_size=5,\n wavenet_dilation_rate=1,\n wavenet_dropout=0.0,\n speaking_rate=1.0,\n noise_scale=0.667,\n noise_scale_duration=0.8,\n sampling_rate=16_000,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.window_size = window_size\n self.use_bias = use_bias\n self.ffn_dim = ffn_dim\n self.layerdrop = layerdrop\n self.ffn_kernel_size = ffn_kernel_size\n self.flow_size = flow_size\n self.spectrogram_bins = spectrogram_bins\n self.hidden_act = hidden_act\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.use_stochastic_duration_prediction = use_stochastic_duration_prediction\n self.num_speakers = num_speakers\n self.speaker_embedding_size = speaker_embedding_size\n self.upsample_initial_channel = upsample_initial_channel\n self.upsample_rates = upsample_rates\n self.upsample_kernel_sizes = upsample_kernel_sizes\n self.resblock_kernel_sizes = resblock_kernel_sizes\n self.resblock_dilation_sizes = resblock_dilation_sizes\n self.leaky_relu_slope = leaky_relu_slope\n self.depth_separable_channels = depth_separable_channels\n self.depth_separable_num_layers = depth_separable_num_layers\n self.duration_predictor_flow_bins = duration_predictor_flow_bins\n self.duration_predictor_tail_bound = duration_predictor_tail_bound\n self.duration_predictor_kernel_size = duration_predictor_kernel_size\n self.duration_predictor_dropout = duration_predictor_dropout\n self.duration_predictor_num_flows = duration_predictor_num_flows\n self.duration_predictor_filter_channels = duration_predictor_filter_channels\n self.prior_encoder_num_flows = prior_encoder_num_flows\n self.prior_encoder_num_wavenet_layers = prior_encoder_num_wavenet_layers\n self.posterior_encoder_num_wavenet_layers = posterior_encoder_num_wavenet_layers\n self.wavenet_kernel_size = wavenet_kernel_size\n self.wavenet_dilation_rate = wavenet_dilation_rate\n self.wavenet_dropout = wavenet_dropout\n self.speaking_rate = speaking_rate\n self.noise_scale = noise_scale\n self.noise_scale_duration = noise_scale_duration\n self.sampling_rate = sampling_rate\n\n if len(upsample_kernel_sizes) != len(upsample_rates):\n raise ValueError(\n f\"The length of `upsample_kernel_sizes` ({len(upsample_kernel_sizes)}) must match the length of \"\n f\"`upsample_rates` ({len(upsample_rates)})\"\n )\n\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _encode_plus_boxes(\n self,\n text: Union[TextInput, PreTokenizedInput],\n text_pair: Optional[PreTokenizedInput] = None,\n boxes: Optional[List[List[int]]] = None,\n word_labels: Optional[List[int]] = None,\n add_special_tokens: bool = True,\n padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,\n truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[bool] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n # make it a batched input\n # 2 options:\n # 1) only text, in case text must be a list of str\n # 2) text + text_pair, in which case text = str and text_pair a list of str\n batched_input = [(text, text_pair)] if text_pair else [text]\n batched_boxes = [boxes]\n batched_word_labels = [word_labels] if word_labels is not None else None\n batched_output = self._batch_encode_plus_boxes(\n batched_input,\n is_pair=bool(text_pair is not None),\n boxes=batched_boxes,\n word_labels=batched_word_labels,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )\n\n # Return tensor is None, then we can remove the leading batch axis\n # Overflowing tokens are returned as a batch of output so we keep them in this case\n if return_tensors is None and not return_overflowing_tokens:\n batched_output = BatchEncoding(\n {\n key: value[0] if len(value) > 0 and isinstance(value[0], list) else value\n for key, value in batched_output.items()\n },\n batched_output.encodings,\n )\n\n self._eventual_warn_about_too_long_sequence(batched_output[\"input_ids\"], max_length, verbose)\n\n return batched_output", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=100,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n embed_dim=16,\n num_labels=3,\n word_embed_proj_dim=16,\n type_sequence_label_size=2,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.embed_dim = embed_dim\n self.num_labels = num_labels\n self.type_sequence_label_size = type_sequence_label_size\n self.word_embed_proj_dim = word_embed_proj_dim\n self.is_encoder_decoder = False", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n prediction_length=7,\n context_length=14,\n cardinality=19,\n embedding_dimension=5,\n num_time_features=4,\n is_training=True,\n hidden_size=64,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n lags_sequence=[1, 2, 3, 4, 5],\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.prediction_length = prediction_length\n self.context_length = context_length\n self.cardinality = cardinality\n self.num_time_features = num_time_features\n self.lags_sequence = lags_sequence\n self.embedding_dimension = embedding_dimension\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n\n self.encoder_seq_length = context_length\n self.decoder_seq_length = prediction_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _preprocess_image(\n self,\n image: ImageInput = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_center_crop: bool = None,\n crop_size: int = None,\n do_convert_rgb: bool = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> np.ndarray:\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n # PIL RGBA images are converted to RGB\n if do_convert_rgb:\n image = convert_to_rgb(image)\n\n # All transformations expect numpy arrays.\n image = to_numpy_array(image)\n\n if is_scaled_image(image) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images/video frames. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(image)\n\n if do_resize:\n image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n\n if do_center_crop:\n image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)\n\n if do_rescale:\n image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n\n if do_normalize:\n image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n\n return image", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BROS_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n bbox: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:\n r\"\"\"\n Returns:\n\n Examples:\n\n ```python\n >>> import torch\n >>> from transformers import BrosProcessor, BrosModel\n\n >>> processor = BrosProcessor.from_pretrained(\"jinho8345/bros-base-uncased\")\n\n >>> model = BrosModel.from_pretrained(\"jinho8345/bros-base-uncased\")\n\n >>> encoding = processor(\"Hello, my dog is cute\", add_special_tokens=False, return_tensors=\"pt\")\n >>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding[\"input_ids\"].shape[-1], 1)\n >>> encoding[\"bbox\"] = bbox\n\n >>> outputs = model(**encoding)\n >>> last_hidden_states = outputs.last_hidden_state\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if self.config.is_decoder:\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n else:\n use_cache = False\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if bbox is None:\n raise ValueError(\"You have to specify bbox\")\n\n batch_size, seq_length = input_shape\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n # past_key_values_length\n past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device)\n\n if token_type_ids is None:\n if hasattr(self.embeddings, \"token_type_ids\"):\n buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]\n buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)\n token_type_ids = buffered_token_type_ids_expanded\n else:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)\n\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)\n\n # If a 2D or 3D attention mask is provided for the cross-attention\n # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]\n if self.config.is_decoder and encoder_hidden_states is not None:\n encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)\n encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)\n else:\n encoder_extended_attention_mask = None\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n embedding_output = self.embeddings(\n input_ids=input_ids,\n position_ids=position_ids,\n token_type_ids=token_type_ids,\n inputs_embeds=inputs_embeds,\n past_key_values_length=past_key_values_length,\n )\n\n # if bbox has 2 points (4 float tensors) per token, convert it to 4 points (8 float tensors) per token\n if bbox.shape[-1] == 4:\n bbox = bbox[:, :, [0, 1, 2, 1, 2, 3, 0, 3]]\n scaled_bbox = bbox * self.config.bbox_scale\n bbox_position_embeddings = self.bbox_embeddings(scaled_bbox)\n\n encoder_outputs = self.encoder(\n embedding_output,\n bbox_pos_emb=bbox_position_embeddings,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_extended_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output) if self.pooler is not None else None\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return BaseModelOutputWithPoolingAndCrossAttentions(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n past_key_values=encoder_outputs.past_key_values,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n cross_attentions=encoder_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\"org_id\", [2])\n @pytest.mark.parametrize(\"source_type\", [\"job\", \"task\", \"project\"])\n @pytest.mark.parametrize(\"role\", [\"worker\", \"supervisor\"])\n @pytest.mark.parametrize(\"staff\", [True, False])\n def test_staff_can_list_labels_in_org(\n self,\n org_id,\n source_type,\n role,\n staff,\n labels,\n jobs_wlc,\n tasks_wlc,\n projects_wlc,\n users,\n is_project_staff,\n is_task_staff,\n is_job_staff,\n memberships,\n users_by_name,\n ):\n labels_by_project = self._labels_by_source(labels, source_key=\"project_id\")\n labels_by_task = self._labels_by_source(labels, source_key=\"task_id\")\n if source_type == \"project\":\n sources = [\n p for p in projects_wlc if p[\"labels\"][\"count\"] > 0 and p[\"organization\"] == org_id\n ]\n labels_by_source = labels_by_project\n is_staff = is_project_staff\n elif source_type == \"task\":\n sources = [\n t for t in tasks_wlc if t[\"labels\"][\"count\"] > 0 and t[\"organization\"] == org_id\n ]\n labels_by_source = {\n task[\"id\"]: (\n labels_by_task.get(task[\"id\"]) or labels_by_project.get(task.get(\"project_id\"))\n )\n for task in sources\n }\n is_staff = is_task_staff\n elif source_type == \"job\":\n sources = [\n j\n for j in jobs_wlc\n if j[\"labels\"][\"count\"] > 0\n if next(t for t in tasks_wlc if t[\"id\"] == j[\"task_id\"])[\"organization\"] == org_id\n ]\n labels_by_source = {\n job[\"id\"]: (\n labels_by_task.get(job[\"task_id\"]) or labels_by_project.get(job[\"project_id\"])\n )\n for job in sources\n }\n is_staff = is_job_staff\n else:\n assert False\n\n staff_by_role = {}\n for m in memberships:\n if m[\"organization\"] == org_id:\n staff_by_role.setdefault(m[\"role\"], []).append(users_by_name[m[\"user\"][\"username\"]])\n\n for source in sources:\n user = next(\n (\n u\n for u in users\n if not u[\"is_superuser\"]\n if is_staff(u[\"id\"], source[\"id\"]) == staff\n if u in staff_by_role[role]\n ),\n None,\n )\n if user:\n break\n\n assert source\n assert user\n\n labels = labels_by_source[source[\"id\"]]\n\n kwargs = {\n \"org_id\": org_id,\n f\"{source_type}_id\": source[\"id\"],\n }\n\n if staff:\n self._test_list_ok(user[\"username\"], labels, **kwargs)\n else:\n self._test_list_denied(user[\"username\"], **kwargs)", "smellKey": "S107", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(WHISPER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n @unpack_inputs\n def call(\n self,\n input_features: TFModelInputType | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n decoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n ) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import TFWhisperModel, AutoFeatureExtractor\n >>> from datasets import load_dataset\n\n >>> model = TFWhisperModel.from_pretrained(\"openai/whisper-base\")\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"openai/whisper-base\")\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> inputs = feature_extractor(ds[0][\"audio\"][\"array\"], return_tensors=\"tf\")\n >>> input_features = inputs.input_features\n >>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id\n >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state\n >>> list(last_hidden_state.shape)\n [1, 2, 512]\n ```\"\"\"\n outputs = self.model(\n input_features=input_features,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n window_size=7,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.window_size = window_size\n self.initializer_range = initializer_range\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n cls_token_box=[0, 0, 0, 0],\n sep_token_box=[1000, 1000, 1000, 1000],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n **kwargs,\n ) -> None:\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token\n\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.Load(str(vocab_file))\n self.vocab_file = vocab_file\n\n # Original fairseq vocab and spm vocab must be \"aligned\":\n # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----\n # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '\u2581' | 's' | '\u2581de' | '-'\n # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '\u2581' | 's' | '\u2581de' | '-' | '\u2581a'\n\n # Mimic fairseq token-to-id alignment for the first 4 token\n self.fairseq_tokens_to_ids = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3}\n\n # The first \"real\" token \",\" has position 4 in the original fairseq vocab and position 3 in the spm vocab\n self.fairseq_offset = 1\n\n self.fairseq_tokens_to_ids[\"<mask>\"] = len(self.sp_model) + self.fairseq_offset\n self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}\n\n # additional properties\n self.cls_token_box = cls_token_box\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword\n\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n cls_token_box=cls_token_box,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n sp_model_kwargs=self.sp_model_kwargs,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=False,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n mlp_ratio=2.0,\n merge_index=0,\n intermediate_hidden_state_indices=[1],\n pretrain_image_size=10,\n decoder_hidden_size=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.mlp_ratio = mlp_ratio\n self.merge_index = merge_index\n self.intermediate_hidden_state_indices = intermediate_hidden_state_indices\n self.pretrain_image_size = pretrain_image_size\n self.decoder_hidden_size = decoder_hidden_size\n\n # in SegGpt, the seq length equals the number of patches (we don't use the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=1024, # speech is longer\n is_training=False,\n hidden_size=16,\n feat_extract_norm=\"group\",\n feat_extract_dropout=0.0,\n feat_extract_activation=\"gelu\",\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n num_hidden_layers=2,\n num_attention_heads=2,\n hidden_dropout_prob=0.1, # this is most likely not correctly set yet\n intermediate_size=20,\n layer_norm_eps=1e-5,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n vocab_size=32,\n do_stable_layer_norm=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_dropout = feat_extract_dropout\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.intermediate_size = intermediate_size\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.scope = scope\n\n output_seq_length = self.seq_length\n for kernel, stride in zip(self.conv_kernel, self.conv_stride):\n output_seq_length = (output_seq_length - (kernel - 1)) / stride\n self.output_seq_length = int(math.ceil(output_seq_length))\n self.encoder_seq_length = self.output_seq_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def generate_text_pplm(\n model,\n tokenizer,\n context=None,\n past=None,\n device=\"cuda\",\n perturb=True,\n bow_indices=None,\n classifier=None,\n class_label=None,\n loss_type=0,\n length=100,\n stepsize=0.02,\n temperature=1.0,\n top_k=10,\n sample=False,\n num_iterations=3,\n grad_length=10000,\n horizon_length=1,\n window_length=0,\n decay=False,\n gamma=1.5,\n gm_scale=0.9,\n kl_scale=0.01,\n repetition_penalty=1.0,\n):\n output_so_far = None\n if context:\n context_t = torch.tensor(context, device=device, dtype=torch.long)\n while len(context_t.shape) < 2:\n context_t = context_t.unsqueeze(0)\n output_so_far = context_t\n\n # collect one hot vectors for bags of words\n one_hot_bows_vectors = build_bows_one_hot_vectors(bow_indices, tokenizer, device)\n\n grad_norms = None\n last = None\n unpert_discrim_loss = 0\n loss_in_time = []\n for i in trange(length, ascii=True):\n # Get past/probs for current output, except for last word\n # Note that GPT takes 2 inputs: past + current_token\n\n # run model forward to obtain unperturbed\n if past is None and output_so_far is not None:\n last = output_so_far[:, -1:]\n if output_so_far.shape[1] > 1:\n past = model(output_so_far[:, :-1])[\"past_key_values\"]\n\n lm_output = model(output_so_far)\n unpert_logits, unpert_past, unpert_all_hidden = (\n lm_output[\"logits\"],\n lm_output[\"past_key_values\"],\n lm_output[\"hidden_states\"],\n )\n unpert_last_hidden = unpert_all_hidden[-1]\n\n # check if we are abowe grad max length\n if i >= grad_length:\n current_stepsize = stepsize * 0\n else:\n current_stepsize = stepsize\n\n # modify the past if necessary\n if not perturb or num_iterations == 0:\n pert_past = past\n\n else:\n accumulated_hidden = unpert_last_hidden[:, :-1, :]\n accumulated_hidden = torch.sum(accumulated_hidden, dim=1)\n\n if past is not None:\n pert_past, _, grad_norms, loss_this_iter = perturb_past(\n past,\n model,\n last,\n unpert_past=unpert_past,\n unpert_logits=unpert_logits,\n accumulated_hidden=accumulated_hidden,\n grad_norms=grad_norms,\n stepsize=current_stepsize,\n one_hot_bows_vectors=one_hot_bows_vectors,\n classifier=classifier,\n class_label=class_label,\n loss_type=loss_type,\n num_iterations=num_iterations,\n horizon_length=horizon_length,\n window_length=window_length,\n decay=decay,\n gamma=gamma,\n kl_scale=kl_scale,\n device=device,\n )\n loss_in_time.append(loss_this_iter)\n else:\n pert_past = past\n\n lm_output = model(last, past_key_values=pert_past)\n pert_logits, past = (\n lm_output[\"logits\"],\n lm_output[\"past_key_values\"],\n )\n pert_logits = pert_logits[:, -1, :] / temperature # + SMALL_CONST\n\n for token_idx in set(output_so_far[0].tolist()):\n if pert_logits[0, token_idx] < 0:\n pert_logits[0, token_idx] *= repetition_penalty\n else:\n pert_logits[0, token_idx] /= repetition_penalty\n\n pert_probs = nn.functional.softmax(pert_logits, dim=-1)\n\n if classifier is not None:\n ce_loss = nn.CrossEntropyLoss()\n prediction = classifier(torch.mean(unpert_last_hidden, dim=1))\n label = torch.tensor([class_label], device=device, dtype=torch.long)\n unpert_discrim_loss = ce_loss(prediction, label)\n print(\"unperturbed discrim loss\", unpert_discrim_loss.data.cpu().numpy())\n else:\n unpert_discrim_loss = 0\n\n # Fuse the modified model and original model\n if perturb:\n unpert_probs = nn.functional.softmax(unpert_logits[:, -1, :], dim=-1)\n\n pert_probs = (pert_probs**gm_scale) * (unpert_probs ** (1 - gm_scale)) # + SMALL_CONST\n pert_probs = top_k_filter(pert_probs, k=top_k, probs=True) # + SMALL_CONST\n\n # rescale\n if torch.sum(pert_probs) <= 1:\n pert_probs = pert_probs / torch.sum(pert_probs)\n\n else:\n pert_logits = top_k_filter(pert_logits, k=top_k) # + SMALL_CONST\n pert_probs = nn.functional.softmax(pert_logits, dim=-1)\n\n # sample or greedy\n if sample:\n last = torch.multinomial(pert_probs, num_samples=1)\n\n else:\n _, last = torch.topk(pert_probs, k=1, dim=-1)\n\n # update context/output_so_far appending the new token\n output_so_far = last if output_so_far is None else torch.cat((output_so_far, last), dim=1)\n\n print(tokenizer.decode(output_so_far.tolist()[0]))\n\n return output_so_far, unpert_discrim_loss, loss_in_time", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, timestamp = 0, pitch = 0.0, roll = 0.0, throttle = 0.0, yaw = 0.0, switch1 = 0,\n switch2 = 0, switch3 = 0, switch4 = 0, switch5 = 0, switch6 = 0, switch7 = 0, switch8 = 0, is_initialized = False, is_valid = False):\n self.timestamp = timestamp\n self.pitch = pitch\n self.roll = roll\n self.throttle = throttle\n self.yaw = yaw\n self.switch1 = switch1\n self.switch2 = switch2\n self.switch3 = switch3\n self.switch4 = switch4\n self.switch5 = switch5\n self.switch6 = switch6\n self.switch7 = switch7\n self.switch8 = switch8\n self.is_initialized = is_initialized\n self.is_valid = is_valid", "smellKey": "S107", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n image_size=32,\n patch_size=16,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n backbone_out_indices=[0, 1, 2, 3],\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n num_labels=3,\n neck_hidden_sizes=[16, 32],\n is_hybrid=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.backbone_out_indices = backbone_out_indices\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.scope = scope\n self.is_hybrid = is_hybrid\n self.neck_hidden_sizes = neck_hidden_sizes\n # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(BART_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n lm_logits = self.lm_head(outputs[0])\n lm_logits = lm_logits + self.final_logits_bias.to(lm_logits.device)\n\n masked_lm_loss = None\n if labels is not None:\n labels = labels.to(lm_logits.device)\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n d_model=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n ffn_dim=37,\n activation_function=\"gelu\",\n activation_dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = d_model\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.ffn_dim = ffn_dim\n self.activation_function = activation_function\n self.activation_dropout = activation_dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = None\n self.bos_token_id = 0\n self.eos_token_id = 2\n self.pad_token_id = 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(SPEECH_ENCODER_DECODER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n inputs: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n input_values: Optional[torch.FloatTensor] = None,\n input_features: Optional[torch.FloatTensor] = None,\n return_dict: Optional[bool] = None,\n **kwargs,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import SpeechEncoderDecoderModel, AutoProcessor\n >>> from datasets import load_dataset\n >>> import torch\n\n >>> processor = AutoProcessor.from_pretrained(\"facebook/wav2vec2-xls-r-300m-en-to-15\")\n >>> model = SpeechEncoderDecoderModel.from_pretrained(\"facebook/wav2vec2-xls-r-300m-en-to-15\")\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n >>> input_values = processor(ds[0][\"audio\"][\"array\"], return_tensors=\"pt\").input_values\n >>> # Inference: Translate English speech to German\n >>> generated = model.generate(input_values)\n >>> decoded = processor.batch_decode(generated, skip_special_tokens=True)[0]\n >>> decoded\n 'Mr. Quilter ist der Apostel der Mittelschicht und wir freuen uns, sein Evangelium willkommen hei\u00dfen zu k\u00f6nnen.'\n\n >>> # Training: Train model on English transcription\n >>> labels = processor(text=ds[0][\"text\"], return_tensors=\"pt\").input_ids\n\n >>> loss = model(input_values, labels=labels).loss\n >>> loss.backward()\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith(\"decoder_\")}\n\n kwargs_decoder = {\n argument[len(\"decoder_\") :]: value for argument, value in kwargs.items() if argument.startswith(\"decoder_\")\n }\n\n if encoder_outputs is None:\n if inputs is None:\n if input_values is not None and input_features is not None:\n raise ValueError(\"You cannot specify both input_values and input_features at the same time\")\n elif input_values is not None:\n inputs = input_values\n elif input_features is not None:\n inputs = input_features\n else:\n raise ValueError(\"You have to specify either input_values or input_features\")\n\n encoder_outputs = self.encoder(\n inputs,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n **kwargs_encoder,\n )\n elif isinstance(encoder_outputs, tuple):\n encoder_outputs = BaseModelOutput(*encoder_outputs)\n\n encoder_hidden_states = encoder_outputs[0]\n\n # optionally project encoder_hidden_states\n if (\n self.encoder_output_dim != self.decoder.config.hidden_size\n and self.decoder.config.cross_attention_hidden_size is None\n ):\n encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)\n\n # compute correct encoder attention mask\n if attention_mask is not None:\n encoder_attention_mask = self.encoder._get_feature_vector_attention_mask(\n encoder_hidden_states.shape[1], attention_mask\n )\n else:\n encoder_attention_mask = None\n\n if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n use_cache=use_cache,\n past_key_values=past_key_values,\n return_dict=return_dict,\n **kwargs_decoder,\n )\n\n # Compute loss independent from decoder (as some shift the logits inside them)\n loss = None\n if labels is not None:\n logits = decoder_outputs.logits if return_dict else decoder_outputs[0]\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.reshape(-1))\n\n if not return_dict:\n if loss is not None:\n return (loss,) + decoder_outputs + encoder_outputs\n else:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=decoder_outputs.logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_hidden_states,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden layers\n seq_length=60,\n is_training=True,\n use_labels=True,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n input_channels=1,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n max_source_positions=30,\n num_mel_bins=80,\n num_conv_layers=1,\n suppress_tokens=None,\n classifier_proj_size=4,\n num_labels=2,\n is_encoder_decoder=False,\n is_decoder=False,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.input_channels = input_channels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_mel_bins = num_mel_bins\n self.max_position_embeddings = max_position_embeddings\n self.max_source_positions = max_source_positions\n self.num_conv_layers = num_conv_layers\n self.suppress_tokens = suppress_tokens\n self.classifier_proj_size = classifier_proj_size\n self.num_labels = num_labels\n self.is_encoder_decoder = is_encoder_decoder\n self.is_decoder = is_decoder", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_github_actions_jobs_v3_get_with_http_info(\n self,\n created_at: Optional[datetime] = None,\n github_actions_attempt_number: Optional[StrictInt] = None,\n github_actions_job_id: Optional[StrictInt] = None,\n github_actions_owner: Optional[StrictStr] = None,\n github_actions_repo: Optional[StrictStr] = None,\n github_actions_run_id: Optional[StrictInt] = None,\n id: Optional[StrictInt] = None,\n job_created_at: Optional[datetime] = None,\n job_started_at: Optional[datetime] = None,\n job_terminal_at: Optional[datetime] = None,\n status: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many GithubActionsJobs are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned GithubActionsJobs (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockGithubActionsJobV3]]:\n \"\"\"List GithubActionsJobs matching a filter\n\n List GithubActionsJobs matching a filter. Results are ordered by start time, starting at most recent.\n\n :param created_at:\n :type created_at: datetime\n :param github_actions_attempt_number:\n :type github_actions_attempt_number: int\n :param github_actions_job_id:\n :type github_actions_job_id: int\n :param github_actions_owner:\n :type github_actions_owner: str\n :param github_actions_repo:\n :type github_actions_repo: str\n :param github_actions_run_id:\n :type github_actions_run_id: int\n :param id:\n :type id: int\n :param job_created_at:\n :type job_created_at: datetime\n :param job_started_at:\n :type job_started_at: datetime\n :param job_terminal_at:\n :type job_terminal_at: datetime\n :param status:\n :type status: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many GithubActionsJobs are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned GithubActionsJobs (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_github_actions_jobs_v3_get_serialize(\n created_at=created_at,\n github_actions_attempt_number=github_actions_attempt_number,\n github_actions_job_id=github_actions_job_id,\n github_actions_owner=github_actions_owner,\n github_actions_repo=github_actions_repo,\n github_actions_run_id=github_actions_run_id,\n id=id,\n job_created_at=job_created_at,\n job_started_at=job_started_at,\n job_terminal_at=job_terminal_at,\n status=status,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockGithubActionsJobV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n min_seq_length=400,\n max_seq_length=2000,\n feature_size=1,\n padding_value=0.0,\n sampling_rate=16000,\n do_normalize=True,\n num_mel_bins=80,\n hop_length=16,\n win_length=64,\n win_function=\"hann_window\",\n fmin=80,\n fmax=7600,\n mel_floor=1e-10,\n return_attention_mask=True,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.min_seq_length = min_seq_length\n self.max_seq_length = max_seq_length\n self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)\n self.feature_size = feature_size\n self.padding_value = padding_value\n self.sampling_rate = sampling_rate\n self.do_normalize = do_normalize\n self.num_mel_bins = num_mel_bins\n self.hop_length = hop_length\n self.win_length = win_length\n self.win_function = win_function\n self.fmin = fmin\n self.fmax = fmax\n self.mel_floor = mel_floor\n self.return_attention_mask = return_attention_mask", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n squeeze_factor=2,\n hidden_act=\"gelu\",\n hidden_dropout=0.1,\n activation_dropout=0.1,\n attention_dropout=0.1,\n feat_proj_dropout=0.0,\n final_dropout=0.1,\n layerdrop=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n feat_extract_norm=\"group\",\n feat_extract_activation=\"gelu\",\n conv_dim=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512),\n conv_stride=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1),\n conv_kernel=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1),\n conv_bias=False,\n num_conv_pos_embeddings=128,\n num_conv_pos_embedding_groups=16,\n apply_spec_augment=True,\n mask_time_prob=0.05,\n mask_time_length=10,\n mask_time_min_masks=2,\n mask_feature_prob=0.0,\n mask_feature_length=10,\n mask_feature_min_masks=0,\n ctc_loss_reduction=\"mean\",\n ctc_zero_infinity=False,\n use_weighted_layer_sum=False,\n classifier_proj_size=256,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n **kwargs,\n ):\n super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = list(conv_dim)\n self.conv_stride = list(conv_stride)\n self.conv_kernel = list(conv_kernel)\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_feat_extract_layers = len(self.conv_dim)\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.squeeze_factor = squeeze_factor\n self.hidden_act = hidden_act\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.feat_proj_dropout = feat_proj_dropout\n self.final_dropout = final_dropout\n self.layerdrop = layerdrop\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n\n if (\n (len(self.conv_stride) != self.num_feat_extract_layers)\n or (len(self.conv_kernel) != self.num_feat_extract_layers)\n or (len(self.conv_dim) != self.num_feat_extract_layers)\n ):\n raise ValueError(\n \"Configuration for convolutional layers is incorrect. \"\n \"It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, \"\n f\"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) \"\n f\"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.\"\n )\n\n # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779\n self.apply_spec_augment = apply_spec_augment\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.mask_time_min_masks = mask_time_min_masks\n self.mask_feature_prob = mask_feature_prob\n self.mask_feature_length = mask_feature_length\n self.mask_feature_min_masks = mask_feature_min_masks\n\n # ctc loss\n self.ctc_loss_reduction = ctc_loss_reduction\n self.ctc_zero_infinity = ctc_zero_infinity\n\n # sequence classification\n self.use_weighted_layer_sum = use_weighted_layer_sum\n self.classifier_proj_size = classifier_proj_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: Optional[PILImageResampling] = None,\n do_pad: Optional[bool] = None,\n padding_value: Optional[float] = None,\n padding_mode: Optional[str] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[float] = None,\n image_std: Optional[float] = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n patch_size: Optional[Dict[str, int]] = None,\n data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n return_tensors: Optional[TensorType] = None,\n ):\n \"\"\"\n\n Utility function to preprocess the images and extract necessary information about original formats.\n\n Args:\n images (`ImageInput`):\n Images to preprocess. Expects a single image, a list or images or a list of lists of images. Pixel\n values range from 0 to 255, or between 0 and 1 if `do_rescale` is `False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image to `size`.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether to pad the image to `size`.\n padding_value (`float`, *optional*, defaults to `self.padding_value`):\n The value to pad the image with.\n padding_mode (`str`, *optional*, defaults to `self.padding_mode`):\n The padding mode to use when padding the image.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float`, *optional*, defaults to `self.image_mean`):\n The mean to use when normalizing the image.\n image_std (`float`, *optional*, defaults to `self.image_std`):\n The standard deviation to use when normalizing the image.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n The factor to use when rescaling the image.\n patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the patches.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format of the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n \"\"\"\n\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n resample = resample if resample is not None else self.resample\n do_pad = do_pad if do_pad is not None else self.do_pad\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n padding_value = padding_value if padding_value is not None else self.padding_value\n padding_mode = padding_mode if padding_mode is not None else self.padding_mode\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n patch_size = patch_size if patch_size is not None else self.patch_size\n\n if isinstance(images, list) and any(isinstance(elem, list) and len(elem) >= 2 for elem in images):\n raise ValueError(\"Multiple images for a single sample are not yet supported.\")\n\n batch_images = make_list_of_list_of_images(images)\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_pad=do_pad,\n size_divisibility=size, # There is no pad divisibility in this processor, but pad requires the size arg.\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # All transformations expect numpy arrays.\n batch_images = [[to_numpy_array(image) for image in images] for images in batch_images]\n\n if is_scaled_image(batch_images[0][0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(batch_images[0][0])\n\n original_image_sizes = [get_image_size(images[0], channel_dim=input_data_format) for images in batch_images]\n\n if do_resize:\n batch_images = [\n [self.resize(image, size=size, input_data_format=input_data_format) for image in images]\n for images in batch_images\n ]\n\n image_sizes = [get_image_size(images[0], channel_dim=input_data_format) for images in batch_images]\n image_unpadded_heights = [[image_size[0]] for image_size in image_sizes]\n image_unpadded_widths = [[image_size[1]] for image_size in image_sizes]\n\n # scale_h is the same as scale_w\n image_scale_factors = [\n [resized_size[0] / original_size[0]]\n for original_size, resized_size in zip(original_image_sizes, image_sizes)\n ]\n\n if do_pad:\n batch_images = [\n [\n self.pad_image(\n image,\n size=size,\n mode=padding_mode,\n constant_values=padding_value,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n for images in batch_images\n ]\n\n if do_rescale:\n batch_images = [\n [self.rescale(image, scale=rescale_factor, input_data_format=input_data_format) for image in images]\n for images in batch_images\n ]\n\n if do_normalize:\n batch_images = [\n [\n self.normalize(image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n for images in batch_images\n ]\n\n if data_format is not None:\n batch_images = [\n [to_channel_dimension_format(image, data_format, input_data_format) for image in images]\n for images in batch_images\n ]\n\n data = {\n \"images\": batch_images,\n \"image_unpadded_heights\": image_unpadded_heights,\n \"image_unpadded_widths\": image_unpadded_widths,\n \"image_scale_factors\": image_scale_factors,\n }\n return FuyuBatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30145,\n emb_dim=2048,\n n_layers=12,\n n_heads=16,\n dropout=0.1,\n attention_dropout=0.1,\n gelu_activation=True,\n sinusoidal_embeddings=False,\n causal=False,\n asm=False,\n n_langs=1,\n use_lang_emb=True,\n max_position_embeddings=512,\n embed_init_std=2048**-0.5,\n layer_norm_eps=1e-12,\n init_std=0.02,\n bos_index=0,\n eos_index=1,\n pad_index=2,\n unk_index=3,\n mask_index=5,\n is_encoder=True,\n summary_type=\"first\",\n summary_use_proj=True,\n summary_activation=None,\n summary_proj_to_labels=True,\n summary_first_dropout=0.1,\n start_n_top=5,\n end_n_top=5,\n mask_token_id=0,\n lang_id=0,\n pad_token_id=2,\n bos_token_id=0,\n **kwargs,\n ):\n \"\"\"Constructs XLMConfig.\"\"\"\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.n_layers = n_layers\n self.n_heads = n_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.gelu_activation = gelu_activation\n self.sinusoidal_embeddings = sinusoidal_embeddings\n self.causal = causal\n self.asm = asm\n self.n_langs = n_langs\n self.use_lang_emb = use_lang_emb\n self.layer_norm_eps = layer_norm_eps\n self.bos_index = bos_index\n self.eos_index = eos_index\n self.pad_index = pad_index\n self.unk_index = unk_index\n self.mask_index = mask_index\n self.is_encoder = is_encoder\n self.max_position_embeddings = max_position_embeddings\n self.embed_init_std = embed_init_std\n self.init_std = init_std\n self.summary_type = summary_type\n self.summary_use_proj = summary_use_proj\n self.summary_activation = summary_activation\n self.summary_proj_to_labels = summary_proj_to_labels\n self.summary_first_dropout = summary_first_dropout\n self.start_n_top = start_n_top\n self.end_n_top = end_n_top\n self.mask_token_id = mask_token_id\n self.lang_id = lang_id\n\n if \"n_words\" in kwargs:\n self.n_words = kwargs[\"n_words\"]\n\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LUKE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=EntityPairClassificationOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n entity_ids: Optional[torch.LongTensor] = None,\n entity_attention_mask: Optional[torch.FloatTensor] = None,\n entity_token_type_ids: Optional[torch.LongTensor] = None,\n entity_position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, EntityPairClassificationOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)` or `(batch_size, num_labels)`, *optional*):\n Labels for computing the classification loss. If the shape is `(batch_size,)`, the cross entropy loss is\n used for the single-label classification. In this case, labels should contain the indices that should be in\n `[0, ..., config.num_labels - 1]`. If the shape is `(batch_size, num_labels)`, the binary cross entropy\n loss is used for the multi-label classification. In this case, labels should only contain `[0, 1]`, where 0\n and 1 indicate false and true, respectively.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, LukeForEntityPairClassification\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"studio-ousia/luke-large-finetuned-tacred\")\n >>> model = LukeForEntityPairClassification.from_pretrained(\"studio-ousia/luke-large-finetuned-tacred\")\n\n >>> text = \"Beyonc\u00e9 lives in Los Angeles.\"\n >>> entity_spans = [\n ... (0, 7),\n ... (17, 28),\n ... ] # character-based entity spans corresponding to \"Beyonc\u00e9\" and \"Los Angeles\"\n >>> inputs = tokenizer(text, entity_spans=entity_spans, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> logits = outputs.logits\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print(\"Predicted class:\", model.config.id2label[predicted_class_idx])\n Predicted class: per:cities_of_residence\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.luke(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=True,\n )\n\n feature_vector = torch.cat(\n [outputs.entity_last_hidden_state[:, 0, :], outputs.entity_last_hidden_state[:, 1, :]], dim=1\n )\n feature_vector = self.dropout(feature_vector)\n logits = self.classifier(feature_vector)\n\n loss = None\n if labels is not None:\n # When the number of dimension of `labels` is 1, cross entropy is used as the loss function. The binary\n # cross entropy is used otherwise.\n # move labels to correct device to enable model parallelism\n labels = labels.to(logits.device)\n if labels.ndim == 1:\n loss = nn.functional.cross_entropy(logits, labels)\n else:\n loss = nn.functional.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits))\n\n if not return_dict:\n return tuple(\n v\n for v in [loss, logits, outputs.hidden_states, outputs.entity_hidden_states, outputs.attentions]\n if v is not None\n )\n\n return EntityPairClassificationOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n entity_hidden_states=outputs.entity_hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def apply_chat_template(\n self,\n conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],\n tools: Optional[List[Dict]] = None,\n documents: Optional[List[Dict[str, str]]] = None,\n chat_template: Optional[str] = None,\n add_generation_prompt: bool = False,\n continue_final_message: bool = False,\n tokenize: bool = True,\n padding: bool = False,\n truncation: bool = False,\n max_length: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_dict: bool = False,\n return_assistant_tokens_mask: bool = False,\n tokenizer_kwargs: Optional[Dict[str, Any]] = None,\n **kwargs,\n ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:\n \"\"\"\n Converts a list of dictionaries with `\"role\"` and `\"content\"` keys to a list of token\n ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n determine the format and control tokens to use when converting.\n\n Args:\n conversation (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]): A list of dicts\n with \"role\" and \"content\" keys, representing the chat history so far.\n tools (`List[Dict]`, *optional*):\n A list of tools (callable functions) that will be accessible to the model. If the template does not\n support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n giving the name, description and argument types for the tool. See our\n [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n for more information.\n documents (`List[Dict[str, str]]`, *optional*):\n A list of dicts representing documents that will be accessible to the model if it is performing RAG\n (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n for examples of passing documents with chat templates.\n chat_template (`str`, *optional*):\n A Jinja template to use for this conversion. It is usually not necessary to pass anything to this\n argument, as the model's template will be used by default.\n add_generation_prompt (bool, *optional*):\n If this is set, a prompt with the token(s) that indicate\n the start of an assistant message will be appended to the formatted output. This is useful when you want to generate a response from the model.\n Note that this argument will be passed to the chat template, and so it must be supported in the\n template for this argument to have any effect.\n continue_final_message (bool, *optional*):\n If this is set, the chat will be formatted so that the final\n message in the chat is open-ended, without any EOS tokens. The model will continue this message\n rather than starting a new one. This allows you to \"prefill\" part of\n the model's response for it. Cannot be used at the same time as `add_generation_prompt`.\n tokenize (`bool`, defaults to `True`):\n Whether to tokenize the output. If `False`, the output will be a string.\n padding (`bool`, defaults to `False`):\n Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`.\n truncation (`bool`, defaults to `False`):\n Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.\n max_length (`int`, *optional*):\n Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If\n not specified, the tokenizer's `max_length` attribute will be used as a default.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable\n values are:\n - `'tf'`: Return TensorFlow `tf.Tensor` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return NumPy `np.ndarray` objects.\n - `'jax'`: Return JAX `jnp.ndarray` objects.\n return_dict (`bool`, defaults to `False`):\n Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.\n tokenizer_kwargs (`Dict[str: Any]`, *optional*): Additional kwargs to pass to the tokenizer.\n return_assistant_tokens_mask (`bool`, defaults to `False`):\n Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant,\n the mask will contain 1. For user and system tokens, the mask will contain 0.\n This functionality is only available for chat templates that support it via the `{% generation %}` keyword.\n **kwargs: Additional kwargs to pass to the template renderer. Will be accessible by the chat template.\n\n Returns:\n `Union[List[int], Dict]`: A list of token ids representing the tokenized chat so far, including control tokens. This\n output is ready to pass to the model, either directly or via methods like `generate()`. If `return_dict` is\n set, will return a dict of tokenizer outputs instead.\n \"\"\"\n\n if return_dict and not tokenize:\n raise ValueError(\n \"`return_dict=True` is incompatible with `tokenize=False`, because there is no dict \"\n \"of tokenizer outputs to return.\"\n )\n\n if return_assistant_tokens_mask and not return_dict:\n raise ValueError(\"`return_assistant_tokens_mask=True` is incompatible with `return_dict=False`\")\n\n if tokenizer_kwargs is None:\n tokenizer_kwargs = {}\n\n chat_template = self.get_chat_template(chat_template, tools)\n\n if return_assistant_tokens_mask and not re.search(r\"\\{\\%-?\\s*generation\\s*-?\\%\\}\", chat_template):\n logger.warning_once(\n \"return_assistant_tokens_mask==True but chat template does not contain `{% generation %}` keyword.\"\n )\n\n # Compilation function uses a cache to avoid recompiling the same template\n compiled_template = _compile_jinja_template(chat_template)\n\n if isinstance(conversation, (list, tuple)) and (\n isinstance(conversation[0], (list, tuple)) or hasattr(conversation[0], \"messages\")\n ):\n conversations = conversation\n is_batched = True\n else:\n conversations = [conversation]\n is_batched = False\n\n if continue_final_message:\n if add_generation_prompt:\n raise ValueError(\n \"continue_final_message and add_generation_prompt are not compatible. Use continue_final_message when you want the model to continue the final message, and add_generation_prompt when you want to add a header that will prompt it to start a new assistant message instead.\"\n )\n if return_assistant_tokens_mask:\n raise ValueError(\"continue_final_message is not compatible with return_assistant_tokens_mask.\")\n\n # We accept either JSON schemas or functions for tools. If we get functions, we convert them to schemas\n if tools is not None:\n tool_schemas = []\n for tool in tools:\n if isinstance(tool, dict):\n tool_schemas.append(tool)\n elif isfunction(tool):\n tool_schemas.append(get_json_schema(tool))\n else:\n raise ValueError(\n \"Tools should either be a JSON schema, or a callable function with type hints \"\n \"and a docstring suitable for auto-conversion to a schema.\"\n )\n else:\n tool_schemas = None\n\n if documents is not None:\n for document in documents:\n if not isinstance(document, dict):\n raise TypeError(\"Documents should be a list of dicts with 'title' and 'text' keys!\")\n\n rendered = []\n all_generation_indices = []\n template_kwargs = {**self.special_tokens_map, **kwargs} # kwargs overwrite special tokens if both are present\n for chat in conversations:\n if hasattr(chat, \"messages\"):\n # Indicates it's a Conversation object\n chat = chat.messages\n if return_assistant_tokens_mask:\n rendered_chat, generation_indices = _render_with_assistant_indices(\n compiled_template=compiled_template,\n messages=chat,\n tools=tool_schemas,\n documents=documents,\n add_generation_prompt=add_generation_prompt,\n **template_kwargs,\n )\n all_generation_indices.append(generation_indices)\n else:\n rendered_chat = compiled_template.render(\n messages=chat,\n tools=tool_schemas,\n documents=documents,\n add_generation_prompt=add_generation_prompt,\n **template_kwargs,\n )\n if continue_final_message:\n final_message = chat[-1][\"content\"]\n rendered_chat = rendered_chat[: rendered_chat.rindex(final_message) + len(final_message)].rstrip()\n rendered.append(rendered_chat)\n\n if not is_batched:\n rendered = rendered[0]\n\n if tokenize:\n out = self(\n rendered,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n add_special_tokens=False,\n return_tensors=return_tensors,\n **tokenizer_kwargs,\n )\n if return_dict:\n if return_assistant_tokens_mask:\n assistant_masks = []\n if is_batched or return_tensors:\n input_ids = out[\"input_ids\"]\n else:\n input_ids = [out[\"input_ids\"]]\n for i in range(len(input_ids)):\n current_mask = [0] * len(input_ids[i])\n for assistant_start_char, assistant_end_char in all_generation_indices[i]:\n start_token = out.char_to_token(i, assistant_start_char)\n end_token = out.char_to_token(i, assistant_end_char - 1)\n if start_token is None:\n # start_token is out of bounds maybe due to truncation.\n break\n for token_id in range(start_token, end_token + 1 if end_token else len(input_ids)):\n current_mask[token_id] = 1\n assistant_masks.append(current_mask)\n out[\"assistant_masks\"] = assistant_masks if is_batched else assistant_masks[0]\n return out\n else:\n return out[\"input_ids\"]\n else:\n return rendered", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n is_training=True,\n use_labels=True,\n num_labels=10,\n image_size=10,\n num_frames=8, # decreased, because default 32 takes too much RAM at inference\n tubelet_size=[2, 4, 4],\n num_channels=3,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu_fast\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-06,\n qkv_bias=True,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_labels = use_labels\n self.num_labels = num_labels\n self.image_size = image_size\n self.num_frames = num_frames\n self.tubelet_size = tubelet_size\n self.num_channels = num_channels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.qkv_bias = qkv_bias\n self.scope = scope\n\n self.seq_length = (\n (self.image_size // self.tubelet_size[2])\n * (self.image_size // self.tubelet_size[1])\n * (self.num_frames // self.tubelet_size[0])\n ) + 1 # CLS token", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@callback\n def async_update_device( # noqa: C901\n self,\n device_id: str,\n *,\n add_config_entry: ConfigEntry | UndefinedType = UNDEFINED,\n add_config_entry_id: str | UndefinedType = UNDEFINED,\n # Temporary flag so we don't blow up when collisions are implicitly introduced\n # by calls to async_get_or_create. Must not be set by integrations.\n allow_collisions: bool = False,\n area_id: str | None | UndefinedType = UNDEFINED,\n configuration_url: str | URL | None | UndefinedType = UNDEFINED,\n device_info_type: str | UndefinedType = UNDEFINED,\n disabled_by: DeviceEntryDisabler | None | UndefinedType = UNDEFINED,\n entry_type: DeviceEntryType | None | UndefinedType = UNDEFINED,\n hw_version: str | None | UndefinedType = UNDEFINED,\n labels: set[str] | UndefinedType = UNDEFINED,\n manufacturer: str | None | UndefinedType = UNDEFINED,\n merge_connections: set[tuple[str, str]] | UndefinedType = UNDEFINED,\n merge_identifiers: set[tuple[str, str]] | UndefinedType = UNDEFINED,\n model: str | None | UndefinedType = UNDEFINED,\n model_id: str | None | UndefinedType = UNDEFINED,\n name_by_user: str | None | UndefinedType = UNDEFINED,\n name: str | None | UndefinedType = UNDEFINED,\n new_connections: set[tuple[str, str]] | UndefinedType = UNDEFINED,\n new_identifiers: set[tuple[str, str]] | UndefinedType = UNDEFINED,\n remove_config_entry_id: str | UndefinedType = UNDEFINED,\n serial_number: str | None | UndefinedType = UNDEFINED,\n suggested_area: str | None | UndefinedType = UNDEFINED,\n sw_version: str | None | UndefinedType = UNDEFINED,\n via_device_id: str | None | UndefinedType = UNDEFINED,\n ) -> DeviceEntry | None:\n \"\"\"Update device attributes.\"\"\"\n old = self.devices[device_id]\n\n new_values: dict[str, Any] = {} # Dict with new key/value pairs\n old_values: dict[str, Any] = {} # Dict with old key/value pairs\n\n config_entries = old.config_entries\n\n if add_config_entry_id is not UNDEFINED and add_config_entry is UNDEFINED:\n config_entry = self.hass.config_entries.async_get_entry(add_config_entry_id)\n if config_entry is None:\n raise HomeAssistantError(\n f\"Can't link device to unknown config entry {add_config_entry_id}\"\n )\n add_config_entry = config_entry\n\n if not new_connections and not new_identifiers:\n raise HomeAssistantError(\n \"A device must have at least one of identifiers or connections\"\n )\n\n if merge_connections is not UNDEFINED and new_connections is not UNDEFINED:\n raise HomeAssistantError(\n \"Cannot define both merge_connections and new_connections\"\n )\n\n if merge_identifiers is not UNDEFINED and new_identifiers is not UNDEFINED:\n raise HomeAssistantError(\n \"Cannot define both merge_identifiers and new_identifiers\"\n )\n\n if isinstance(disabled_by, str) and not isinstance(\n disabled_by, DeviceEntryDisabler\n ):\n report( # type: ignore[unreachable]\n (\n \"uses str for device registry disabled_by. This is deprecated and\"\n \" will stop working in Home Assistant 2022.3, it should be updated\"\n \" to use DeviceEntryDisabler instead\"\n ),\n error_if_core=False,\n )\n disabled_by = DeviceEntryDisabler(disabled_by)\n\n if (\n suggested_area is not None\n and suggested_area is not UNDEFINED\n and suggested_area != \"\"\n and area_id is UNDEFINED\n and old.area_id is None\n ):\n # Circular dep\n # pylint: disable-next=import-outside-toplevel\n from . import area_registry as ar\n\n area = ar.async_get(self.hass).async_get_or_create(suggested_area)\n area_id = area.id\n\n if add_config_entry is not UNDEFINED:\n primary_entry_id = old.primary_config_entry\n if (\n device_info_type == \"primary\"\n and add_config_entry.entry_id != primary_entry_id\n ):\n if (\n primary_entry_id is None\n or not (\n primary_entry := self.hass.config_entries.async_get_entry(\n primary_entry_id\n )\n )\n or primary_entry.domain in LOW_PRIO_CONFIG_ENTRY_DOMAINS\n ):\n new_values[\"primary_config_entry\"] = add_config_entry.entry_id\n old_values[\"primary_config_entry\"] = old.primary_config_entry\n\n if add_config_entry.entry_id not in old.config_entries:\n config_entries = old.config_entries | {add_config_entry.entry_id}\n\n if (\n remove_config_entry_id is not UNDEFINED\n and remove_config_entry_id in config_entries\n ):\n if config_entries == {remove_config_entry_id}:\n self.async_remove_device(device_id)\n return None\n\n if remove_config_entry_id == old.primary_config_entry:\n new_values[\"primary_config_entry\"] = None\n old_values[\"primary_config_entry\"] = old.primary_config_entry\n\n config_entries = config_entries - {remove_config_entry_id}\n\n if config_entries != old.config_entries:\n new_values[\"config_entries\"] = config_entries\n old_values[\"config_entries\"] = old.config_entries\n\n for attr_name, setvalue in (\n (\"connections\", merge_connections),\n (\"identifiers\", merge_identifiers),\n ):\n old_value = getattr(old, attr_name)\n # If not undefined, check if `value` contains new items.\n if setvalue is not UNDEFINED and not setvalue.issubset(old_value):\n new_values[attr_name] = old_value | setvalue\n old_values[attr_name] = old_value\n\n if merge_connections is not UNDEFINED:\n normalized_connections = self._validate_connections(\n device_id,\n merge_connections,\n allow_collisions,\n )\n old_connections = old.connections\n if not normalized_connections.issubset(old_connections):\n new_values[\"connections\"] = old_connections | normalized_connections\n old_values[\"connections\"] = old_connections\n\n if merge_identifiers is not UNDEFINED:\n merge_identifiers = self._validate_identifiers(\n device_id, merge_identifiers, allow_collisions\n )\n old_identifiers = old.identifiers\n if not merge_identifiers.issubset(old_identifiers):\n new_values[\"identifiers\"] = old_identifiers | merge_identifiers\n old_values[\"identifiers\"] = old_identifiers\n\n if new_connections is not UNDEFINED:\n new_values[\"connections\"] = self._validate_connections(\n device_id, new_connections, False\n )\n old_values[\"connections\"] = old.connections\n\n if new_identifiers is not UNDEFINED:\n new_values[\"identifiers\"] = self._validate_identifiers(\n device_id, new_identifiers, False\n )\n old_values[\"identifiers\"] = old.identifiers\n\n if configuration_url is not UNDEFINED:\n configuration_url = _validate_configuration_url(configuration_url)\n\n for attr_name, value in (\n (\"area_id\", area_id),\n (\"configuration_url\", configuration_url),\n (\"disabled_by\", disabled_by),\n (\"entry_type\", entry_type),\n (\"hw_version\", hw_version),\n (\"labels\", labels),\n (\"manufacturer\", manufacturer),\n (\"model\", model),\n (\"model_id\", model_id),\n (\"name\", name),\n (\"name_by_user\", name_by_user),\n (\"serial_number\", serial_number),\n (\"suggested_area\", suggested_area),\n (\"sw_version\", sw_version),\n (\"via_device_id\", via_device_id),\n ):\n if value is not UNDEFINED and value != getattr(old, attr_name):\n new_values[attr_name] = value\n old_values[attr_name] = getattr(old, attr_name)\n\n if old.is_new:\n new_values[\"is_new\"] = False\n\n if not new_values:\n return old\n\n if not RUNTIME_ONLY_ATTRS.issuperset(new_values):\n # Change modified_at if we are changing something that we store\n new_values[\"modified_at\"] = utcnow()\n\n self.hass.verify_event_loop_thread(\"device_registry.async_update_device\")\n new = attr.evolve(old, **new_values)\n self.devices[device_id] = new\n\n # If its only run time attributes (suggested_area)\n # that do not get saved we do not want to write\n # to disk or fire an event as we would end up\n # firing events for data we have nothing to compare\n # against since its never saved on disk\n if RUNTIME_ONLY_ATTRS.issuperset(new_values):\n return new\n\n self.async_schedule_save()\n\n data: EventDeviceRegistryUpdatedData\n if old.is_new:\n data = {\"action\": \"create\", \"device_id\": new.id}\n else:\n data = {\"action\": \"update\", \"device_id\": new.id, \"changes\": old_values}\n\n self.hass.bus.async_fire_internal(EVENT_DEVICE_REGISTRY_UPDATED, data)\n\n return new", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(SPEECHT5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_values: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n ) -> Union[Tuple, Seq2SeqLMOutput]:\n r\"\"\"\n input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file\n into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (*pip install\n soundfile*). To prepare the array into `input_values`, the [`SpeechT5Processor`] should be used for padding\n and conversion into a tensor of type `torch.FloatTensor`. See [`SpeechT5Processor.__call__`] for details.\n\n decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):\n Indices of decoder input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`SpeechT5Tokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are decoder input IDs?](../glossary#decoder-input-ids)\n\n SpeechT5 uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If\n `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see\n `past_key_values`).\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`\n or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is\n only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Label indices can be obtained using [`SpeechT5Tokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import SpeechT5Processor, SpeechT5ForSpeechToText\n >>> from datasets import load_dataset\n\n >>> dataset = load_dataset(\n ... \"hf-internal-testing/librispeech_asr_demo\", \"clean\", split=\"validation\", trust_remote_code=True\n ... ) # doctest: +IGNORE_RESULT\n >>> dataset = dataset.sort(\"id\")\n >>> sampling_rate = dataset.features[\"audio\"].sampling_rate\n\n >>> processor = SpeechT5Processor.from_pretrained(\"microsoft/speecht5_asr\")\n >>> model = SpeechT5ForSpeechToText.from_pretrained(\"microsoft/speecht5_asr\")\n\n >>> # audio file is decoded on the fly\n >>> inputs = processor(audio=dataset[0][\"audio\"][\"array\"], sampling_rate=sampling_rate, return_tensors=\"pt\")\n >>> predicted_ids = model.generate(**inputs, max_length=100)\n\n >>> # transcribe speech\n >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)\n >>> transcription[0]\n 'mister quilter is the apostle of the middle classes and we are glad to welcome his gospel'\n ```\n\n ```python\n >>> inputs[\"labels\"] = processor(text_target=dataset[0][\"text\"], return_tensors=\"pt\").input_ids\n\n >>> # compute loss\n >>> loss = model(**inputs).loss\n >>> round(loss.item(), 2)\n 19.68\n ```\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.speecht5(\n input_values=input_values,\n attention_mask=attention_mask,\n decoder_input_values=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=True,\n )\n\n logits = self.text_decoder_postnet(outputs[0])\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n mlp_ratio=4,\n hidden_act=\"gelu\",\n dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-6,\n image_size=224,\n pretrain_image_size=224,\n patch_size=16,\n num_channels=3,\n qkv_bias=True,\n drop_path_rate=0.0,\n window_block_indices=[],\n residual_block_indices=[],\n use_absolute_position_embeddings=True,\n use_relative_position_embeddings=False,\n window_size=0,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.mlp_ratio = mlp_ratio\n self.hidden_act = hidden_act\n self.dropout_prob = dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.pretrain_image_size = pretrain_image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.drop_path_rate = drop_path_rate\n self.window_block_indices = window_block_indices\n self.residual_block_indices = residual_block_indices\n self.use_absolute_position_embeddings = use_absolute_position_embeddings\n self.use_relative_position_embeddings = use_relative_position_embeddings\n self.window_size = window_size\n\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, self.num_hidden_layers + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n kms_providers: Mapping[str, Any],\n key_vault_namespace: str,\n key_vault_client: Optional[MongoClient[_DocumentTypeArg]] = None,\n schema_map: Optional[Mapping[str, Any]] = None,\n bypass_auto_encryption: bool = False,\n mongocryptd_uri: str = \"mongodb://localhost:27020\",\n mongocryptd_bypass_spawn: bool = False,\n mongocryptd_spawn_path: str = \"mongocryptd\",\n mongocryptd_spawn_args: Optional[list[str]] = None,\n kms_tls_options: Optional[Mapping[str, Any]] = None,\n crypt_shared_lib_path: Optional[str] = None,\n crypt_shared_lib_required: bool = False,\n bypass_query_analysis: bool = False,\n encrypted_fields_map: Optional[Mapping[str, Any]] = None,\n ) -> None:\n \"\"\"Options to configure automatic client-side field level encryption.\n\n Automatic client-side field level encryption requires MongoDB >=4.2\n enterprise or a MongoDB >=4.2 Atlas cluster. Automatic encryption is not\n supported for operations on a database or view and will result in\n error.\n\n Although automatic encryption requires MongoDB >=4.2 enterprise or a\n MongoDB >=4.2 Atlas cluster, automatic *decryption* is supported for all\n users. To configure automatic *decryption* without automatic\n *encryption* set ``bypass_auto_encryption=True``. Explicit\n encryption and explicit decryption is also supported for all users\n with the :class:`~pymongo.encryption.ClientEncryption` class.\n\n See :ref:`automatic-client-side-encryption` for an example.\n\n :param kms_providers: Map of KMS provider options. The `kms_providers`\n map values differ by provider:\n\n - `aws`: Map with \"accessKeyId\" and \"secretAccessKey\" as strings.\n These are the AWS access key ID and AWS secret access key used\n to generate KMS messages. An optional \"sessionToken\" may be\n included to support temporary AWS credentials.\n - `azure`: Map with \"tenantId\", \"clientId\", and \"clientSecret\" as\n strings. Additionally, \"identityPlatformEndpoint\" may also be\n specified as a string (defaults to 'login.microsoftonline.com').\n These are the Azure Active Directory credentials used to\n generate Azure Key Vault messages.\n - `gcp`: Map with \"email\" as a string and \"privateKey\"\n as `bytes` or a base64 encoded string.\n Additionally, \"endpoint\" may also be specified as a string\n (defaults to 'oauth2.googleapis.com'). These are the\n credentials used to generate Google Cloud KMS messages.\n - `kmip`: Map with \"endpoint\" as a host with required port.\n For example: ``{\"endpoint\": \"example.com:443\"}``.\n - `local`: Map with \"key\" as `bytes` (96 bytes in length) or\n a base64 encoded string which decodes\n to 96 bytes. \"key\" is the master key used to encrypt/decrypt\n data keys. This key should be generated and stored as securely\n as possible.\n\n KMS providers may be specified with an optional name suffix\n separated by a colon, for example \"kmip:name\" or \"aws:name\".\n Named KMS providers do not support :ref:`CSFLE on-demand credentials`.\n Named KMS providers enables more than one of each KMS provider type to be configured.\n For example, to configure multiple local KMS providers::\n\n kms_providers = {\n \"local\": {\"key\": local_kek1}, # Unnamed KMS provider.\n \"local:myname\": {\"key\": local_kek2}, # Named KMS provider with name \"myname\".\n }\n\n :param key_vault_namespace: The namespace for the key vault collection.\n The key vault collection contains all data keys used for encryption\n and decryption. Data keys are stored as documents in this MongoDB\n collection. Data keys are protected with encryption by a KMS\n provider.\n :param key_vault_client: By default, the key vault collection\n is assumed to reside in the same MongoDB cluster as the encrypted\n MongoClient. Use this option to route data key queries to a\n separate MongoDB cluster.\n :param schema_map: Map of collection namespace (\"db.coll\") to\n JSON Schema. By default, a collection's JSONSchema is periodically\n polled with the listCollections command. But a JSONSchema may be\n specified locally with the schemaMap option.\n\n **Supplying a `schema_map` provides more security than relying on\n JSON Schemas obtained from the server. It protects against a\n malicious server advertising a false JSON Schema, which could trick\n the client into sending unencrypted data that should be\n encrypted.**\n\n Schemas supplied in the schemaMap only apply to configuring\n automatic encryption for client side encryption. Other validation\n rules in the JSON schema will not be enforced by the driver and\n will result in an error.\n :param bypass_auto_encryption: If ``True``, automatic\n encryption will be disabled but automatic decryption will still be\n enabled. Defaults to ``False``.\n :param mongocryptd_uri: The MongoDB URI used to connect\n to the *local* mongocryptd process. Defaults to\n ``'mongodb://localhost:27020'``.\n :param mongocryptd_bypass_spawn: If ``True``, the encrypted\n MongoClient will not attempt to spawn the mongocryptd process.\n Defaults to ``False``.\n :param mongocryptd_spawn_path: Used for spawning the\n mongocryptd process. Defaults to ``'mongocryptd'`` and spawns\n mongocryptd from the system path.\n :param mongocryptd_spawn_args: A list of string arguments to\n use when spawning the mongocryptd process. Defaults to\n ``['--idleShutdownTimeoutSecs=60']``. If the list does not include\n the ``idleShutdownTimeoutSecs`` option then\n ``'--idleShutdownTimeoutSecs=60'`` will be added.\n :param kms_tls_options: A map of KMS provider names to TLS\n options to use when creating secure connections to KMS providers.\n Accepts the same TLS options as\n :class:`pymongo.mongo_client.MongoClient`. For example, to\n override the system default CA file::\n\n kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}}\n\n Or to supply a client certificate::\n\n kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}\n :param crypt_shared_lib_path: Override the path to load the crypt_shared library.\n :param crypt_shared_lib_required: If True, raise an error if libmongocrypt is\n unable to load the crypt_shared library.\n :param bypass_query_analysis: If ``True``, disable automatic analysis\n of outgoing commands. Set `bypass_query_analysis` to use explicit\n encryption on indexed fields without the MongoDB Enterprise Advanced\n licensed crypt_shared library.\n :param encrypted_fields_map: Map of collection namespace (\"db.coll\") to documents\n that described the encrypted fields for Queryable Encryption. For example::\n\n {\n \"db.encryptedCollection\": {\n \"escCollection\": \"enxcol_.encryptedCollection.esc\",\n \"ecocCollection\": \"enxcol_.encryptedCollection.ecoc\",\n \"fields\": [\n {\n \"path\": \"firstName\",\n \"keyId\": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')),\n \"bsonType\": \"string\",\n \"queries\": {\"queryType\": \"equality\"}\n },\n {\n \"path\": \"ssn\",\n \"keyId\": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')),\n \"bsonType\": \"string\"\n }\n ]\n }\n }\n\n .. versionchanged:: 4.2\n Added `encrypted_fields_map` `crypt_shared_lib_path`, `crypt_shared_lib_required`,\n and `bypass_query_analysis` parameters.\n\n .. versionchanged:: 4.0\n Added the `kms_tls_options` parameter and the \"kmip\" KMS provider.\n\n .. versionadded:: 3.9\n \"\"\"\n if not _HAVE_PYMONGOCRYPT:\n raise ConfigurationError(\n \"client side encryption requires the pymongocrypt library: \"\n \"install a compatible version with: \"\n \"python -m pip install 'pymongo[encryption]'\"\n )\n if encrypted_fields_map:\n validate_is_mapping(\"encrypted_fields_map\", encrypted_fields_map)\n self._encrypted_fields_map = encrypted_fields_map\n self._bypass_query_analysis = bypass_query_analysis\n self._crypt_shared_lib_path = crypt_shared_lib_path\n self._crypt_shared_lib_required = crypt_shared_lib_required\n self._kms_providers = kms_providers\n self._key_vault_namespace = key_vault_namespace\n self._key_vault_client = key_vault_client\n self._schema_map = schema_map\n self._bypass_auto_encryption = bypass_auto_encryption\n self._mongocryptd_uri = mongocryptd_uri\n self._mongocryptd_bypass_spawn = mongocryptd_bypass_spawn\n self._mongocryptd_spawn_path = mongocryptd_spawn_path\n if mongocryptd_spawn_args is None:\n mongocryptd_spawn_args = [\"--idleShutdownTimeoutSecs=60\"]\n self._mongocryptd_spawn_args = mongocryptd_spawn_args\n if not isinstance(self._mongocryptd_spawn_args, list):\n raise TypeError(\"mongocryptd_spawn_args must be a list\")\n if not any(\"idleShutdownTimeoutSecs\" in s for s in self._mongocryptd_spawn_args):\n self._mongocryptd_spawn_args.append(\"--idleShutdownTimeoutSecs=60\")\n # Maps KMS provider name to a SSLContext.\n self._kms_ssl_contexts = _parse_kms_tls_options(kms_tls_options)\n self._bypass_query_analysis = bypass_query_analysis", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def _target_encode_plus(\n self,\n answer: str,\n add_special_tokens: bool = True,\n padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,\n truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n if return_offsets_mapping:\n raise NotImplementedError(\n \"return_offset_mapping is not available when using Python tokenizers. \"\n \"To use this feature, change your tokenizer to one deriving from \"\n \"transformers.PreTrainedTokenizerFast. \"\n \"More information on available tokenizers at \"\n \"https://github.com/huggingface/transformers/pull/2674\"\n )\n\n text = answer\n\n # if necessary, perform lower case\n if self.do_lower_case:\n text = text.lower()\n\n tokens = self.tokenize(text)\n\n return self.prepare_for_model(\n ids=self.convert_tokens_to_ids(tokens),\n add_special_tokens=add_special_tokens,\n padding=padding_strategy.value,\n truncation=truncation_strategy.value,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n return_tensors=return_tensors,\n prepend_batch_axis=True,\n return_attention_mask=return_attention_mask,\n return_token_type_ids=return_token_type_ids,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_length=return_length,\n verbose=verbose,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30524,\n hidden_size=768,\n encoder_hidden_size=768,\n intermediate_size=3072,\n projection_dim=768,\n num_hidden_layers=12,\n num_attention_heads=8,\n max_position_embeddings=512,\n hidden_act=\"gelu\",\n layer_norm_eps=1e-12,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n bos_token_id=30522,\n eos_token_id=2,\n pad_token_id=0,\n sep_token_id=102,\n is_decoder=True,\n use_cache=True,\n label_smoothing=0.0,\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n sep_token_id=sep_token_id,\n **kwargs,\n )\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.encoder_hidden_size = encoder_hidden_size\n self.intermediate_size = intermediate_size\n self.projection_dim = projection_dim\n self.hidden_dropout_prob = hidden_dropout_prob\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.max_position_embeddings = max_position_embeddings\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.is_decoder = is_decoder\n self.use_cache = use_cache\n self.label_smoothing = label_smoothing", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=IdeficsCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n pixel_values: Optional[torch.FloatTensor] = None,\n image_encoder_embeddings: Optional[torch.FloatTensor] = None,\n perceiver_embeddings: Optional[torch.FloatTensor] = None,\n image_attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n interpolate_pos_encoding: Optional[bool] = False,\n return_dict: Optional[bool] = None,\n cache_position: Optional[torch.LongTensor] = None,\n ) -> Union[Tuple, IdeficsCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoProcessor, IdeficsForVisionText2Text\n\n >>> model = IdeficsForVisionText2Text.from_pretrained(\"HuggingFaceM4/idefics-9b\")\n >>> processor = AutoProcessor.from_pretrained(\"HuggingFaceM4/idefics-9b\")\n\n >>> dogs_image_url_1 = \"https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg\"\n >>> dogs_image_url_2 = \"https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg\"\n\n >>> prompts = [\n ... [\n ... \"User:\",\n ... dogs_image_url_1,\n ... \"Describe this image.\\nAssistant: An image of two dogs.\\n\",\n ... \"User:\",\n ... dogs_image_url_2,\n ... \"Describe this image.\\nAssistant:\",\n ... ]\n ... ]\n >>> inputs = processor(prompts, return_tensors=\"pt\")\n >>> generate_ids = model.generate(**inputs, max_new_tokens=6)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True)\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n pixel_values=pixel_values,\n image_encoder_embeddings=image_encoder_embeddings,\n perceiver_embeddings=perceiver_embeddings,\n image_attention_mask=image_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n interpolate_pos_encoding=interpolate_pos_encoding,\n return_dict=return_dict,\n cache_position=cache_position,\n )\n\n hidden_states = outputs[0]\n logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n labels = labels.to(logits.device)\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n # we use the input attention mask to shift the logits and labels, because it is 2D.\n # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft\n shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)\n shift_logits = logits[..., :-1, :][shift_attention_mask != 0].contiguous()\n shift_labels = labels[..., 1:][shift_attention_mask != 0].contiguous()\n else:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return IdeficsCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=outputs.image_hidden_states,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=64,\n num_channels=3,\n num_encoder_blocks=4,\n depths=[2, 2, 2, 2],\n sr_ratios=[8, 4, 2, 1],\n hidden_sizes=[16, 32, 64, 128],\n downsampling_rates=[1, 4, 8, 16],\n num_attention_heads=[1, 2, 4, 8],\n is_training=True,\n use_labels=True,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.num_encoder_blocks = num_encoder_blocks\n self.sr_ratios = sr_ratios\n self.depths = depths\n self.hidden_sizes = hidden_sizes\n self.downsampling_rates = downsampling_rates\n self.num_attention_heads = num_attention_heads\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n position_embedding_type=\"absolute\",\n use_cache=True,\n classifier_dropout=None,\n pre_norm=False,\n adapter_reduction_factor=2,\n adapter_layer_norm=False,\n adapter_reuse_layer_norm=True,\n ln_before_adapter=True,\n languages=(\"en_XX\",),\n default_language=None,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout\n self.pre_norm = pre_norm\n self.adapter_reduction_factor = adapter_reduction_factor\n self.adapter_layer_norm = adapter_layer_norm\n self.adapter_reuse_layer_norm = adapter_reuse_layer_norm\n self.ln_before_adapter = ln_before_adapter\n self.languages = list(languages)\n self.default_language = default_language", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFSeq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: tf.Tensor | None = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: bool | None = None,\n output_attentions: bool | None = None,\n output_hidden_states: bool | None = None,\n return_dict: bool | None = None,\n training: bool = False,\n **kwargs,\n ) -> Tuple[tf.Tensor] | TFSeq2SeqModelOutput:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_chart_versions_v3_get_serialize(\n self,\n authored_by,\n chart,\n chart_version,\n created_at,\n description,\n id,\n parent_chart_version,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if authored_by is not None:\n \n _query_params.append(('authoredBy', authored_by))\n \n if chart is not None:\n \n _query_params.append(('chart', chart))\n \n if chart_version is not None:\n \n _query_params.append(('chartVersion', chart_version))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if description is not None:\n \n _query_params.append(('description', description))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if parent_chart_version is not None:\n \n _query_params.append(('parentChartVersion', parent_chart_version))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/chart-versions/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@typing.overload\ndef open(\n file: Union[str, \"PathLike[str]\", bytes],\n mode: Union[Literal[\"rt\"], Literal[\"r\"]],\n buffering: int = -1,\n encoding: Optional[str] = None,\n errors: Optional[str] = None,\n newline: Optional[str] = None,\n *,\n total: Optional[int] = None,\n description: str = \"Reading...\",\n auto_refresh: bool = True,\n console: Optional[Console] = None,\n transient: bool = False,\n get_time: Optional[Callable[[], float]] = None,\n refresh_per_second: float = 10,\n style: StyleType = \"bar.back\",\n complete_style: StyleType = \"bar.complete\",\n finished_style: StyleType = \"bar.finished\",\n pulse_style: StyleType = \"bar.pulse\",\n disable: bool = False,\n) -> ContextManager[TextIO]:\n pass", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n max_num_images_per_sample=3,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n patch_size=None,\n do_normalize=True,\n image_mean=[0.48145466, 0.4578275, 0.40821073],\n image_std=[0.26862954, 0.26130258, 0.27577711],\n do_convert_rgb=True,\n ):\n size = size if size is not None else {\"longest_edge\": 24}\n patch_size = patch_size if patch_size is not None else {\"height\": 8, \"width\": 8}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.max_num_images_per_sample = max_num_images_per_sample\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.patch_size = patch_size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_roles_v3_get_with_http_info(\n self,\n auto_assign_all_users: Annotated[Optional[StrictBool], Field(description=\"When true, Sherlock will automatically assign all users to this role who do not already have a role assignment\")] = None,\n can_be_glass_broken_by_role: Optional[StrictInt] = None,\n created_at: Optional[datetime] = None,\n default_glass_break_duration: Optional[StrictStr] = None,\n grants_broad_institute_group: Optional[StrictStr] = None,\n grants_dev_azure_account: Optional[StrictBool] = None,\n grants_dev_azure_directory_roles: Optional[StrictBool] = None,\n grants_dev_azure_group: Optional[StrictStr] = None,\n grants_dev_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_dev_firecloud_group: Optional[StrictStr] = None,\n grants_prod_azure_account: Optional[StrictBool] = None,\n grants_prod_azure_directory_roles: Optional[StrictBool] = None,\n grants_prod_azure_group: Optional[StrictStr] = None,\n grants_prod_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_prod_firecloud_group: Optional[StrictStr] = None,\n grants_qa_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_qa_firecloud_group: Optional[StrictStr] = None,\n grants_sherlock_super_admin: Optional[StrictBool] = None,\n id: Optional[StrictInt] = None,\n name: Optional[StrictStr] = None,\n suspend_non_suitable_users: Annotated[Optional[StrictBool], Field(description=\"When true, the \\\"suspended\\\" field on role assignments will be computed by Sherlock based on suitability instead of being a mutable API field\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Roles are returned (default 0, no limit)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Roles (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockRoleV3]]:\n \"\"\"List Roles matching a filter\n\n List Roles matching a filter.\n\n :param auto_assign_all_users: When true, Sherlock will automatically assign all users to this role who do not already have a role assignment\n :type auto_assign_all_users: bool\n :param can_be_glass_broken_by_role:\n :type can_be_glass_broken_by_role: int\n :param created_at:\n :type created_at: datetime\n :param default_glass_break_duration:\n :type default_glass_break_duration: str\n :param grants_broad_institute_group:\n :type grants_broad_institute_group: str\n :param grants_dev_azure_account:\n :type grants_dev_azure_account: bool\n :param grants_dev_azure_directory_roles:\n :type grants_dev_azure_directory_roles: bool\n :param grants_dev_azure_group:\n :type grants_dev_azure_group: str\n :param grants_dev_firecloud_folder_owner:\n :type grants_dev_firecloud_folder_owner: str\n :param grants_dev_firecloud_group:\n :type grants_dev_firecloud_group: str\n :param grants_prod_azure_account:\n :type grants_prod_azure_account: bool\n :param grants_prod_azure_directory_roles:\n :type grants_prod_azure_directory_roles: bool\n :param grants_prod_azure_group:\n :type grants_prod_azure_group: str\n :param grants_prod_firecloud_folder_owner:\n :type grants_prod_firecloud_folder_owner: str\n :param grants_prod_firecloud_group:\n :type grants_prod_firecloud_group: str\n :param grants_qa_firecloud_folder_owner:\n :type grants_qa_firecloud_folder_owner: str\n :param grants_qa_firecloud_group:\n :type grants_qa_firecloud_group: str\n :param grants_sherlock_super_admin:\n :type grants_sherlock_super_admin: bool\n :param id:\n :type id: int\n :param name:\n :type name: str\n :param suspend_non_suitable_users: When true, the \\\"suspended\\\" field on role assignments will be computed by Sherlock based on suitability instead of being a mutable API field\n :type suspend_non_suitable_users: bool\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many Roles are returned (default 0, no limit)\n :type limit: int\n :param offset: Control the offset for the returned Roles (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_roles_v3_get_serialize(\n auto_assign_all_users=auto_assign_all_users,\n can_be_glass_broken_by_role=can_be_glass_broken_by_role,\n created_at=created_at,\n default_glass_break_duration=default_glass_break_duration,\n grants_broad_institute_group=grants_broad_institute_group,\n grants_dev_azure_account=grants_dev_azure_account,\n grants_dev_azure_directory_roles=grants_dev_azure_directory_roles,\n grants_dev_azure_group=grants_dev_azure_group,\n grants_dev_firecloud_folder_owner=grants_dev_firecloud_folder_owner,\n grants_dev_firecloud_group=grants_dev_firecloud_group,\n grants_prod_azure_account=grants_prod_azure_account,\n grants_prod_azure_directory_roles=grants_prod_azure_directory_roles,\n grants_prod_azure_group=grants_prod_azure_group,\n grants_prod_firecloud_folder_owner=grants_prod_firecloud_folder_owner,\n grants_prod_firecloud_group=grants_prod_firecloud_group,\n grants_qa_firecloud_folder_owner=grants_qa_firecloud_folder_owner,\n grants_qa_firecloud_group=grants_qa_firecloud_group,\n grants_sherlock_super_admin=grants_sherlock_super_admin,\n id=id,\n name=name,\n suspend_non_suitable_users=suspend_non_suitable_users,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockRoleV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_lengths=True,\n use_token_type_ids=True,\n use_labels=True,\n gelu_activation=True,\n sinusoidal_embeddings=False,\n causal=False,\n asm=False,\n n_langs=2,\n vocab_size=99,\n n_special=0,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=2,\n num_choices=4,\n summary_type=\"last\",\n use_proj=True,\n scope=None,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_lengths = use_input_lengths\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.gelu_activation = gelu_activation\n self.sinusoidal_embeddings = sinusoidal_embeddings\n self.causal = causal\n self.asm = asm\n self.n_langs = n_langs\n self.vocab_size = vocab_size\n self.n_special = n_special\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.summary_type = summary_type\n self.use_proj = use_proj\n self.scope = scope\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _execute_child(self, args, executable, preexec_fn, close_fds,\n pass_fds, cwd, env,\n startupinfo, creationflags, shell,\n p2cread, p2cwrite,\n c2pread, c2pwrite,\n errread, errwrite,\n restore_signals,\n gid, gids, uid, umask,\n start_new_session, process_group):\n \"\"\"Execute program (POSIX version)\"\"\"\n\n if isinstance(args, (str, bytes)):\n args = [args]\n elif isinstance(args, os.PathLike):\n if shell:\n raise TypeError('path-like args is not allowed when '\n 'shell is true')\n args = [args]\n else:\n args = list(args)\n\n if shell:\n # On Android the default shell is at '/system/bin/sh'.\n unix_shell = ('/system/bin/sh' if\n hasattr(sys, 'getandroidapilevel') else '/bin/sh')\n args = [unix_shell, \"-c\"] + args\n if executable:\n args[0] = executable\n\n if executable is None:\n executable = args[0]\n\n sys.audit(\"subprocess.Popen\", executable, args, cwd, env)\n\n if (_USE_POSIX_SPAWN\n and os.path.dirname(executable)\n and preexec_fn is None\n and (not close_fds or _HAVE_POSIX_SPAWN_CLOSEFROM)\n and not pass_fds\n and cwd is None\n and (p2cread == -1 or p2cread > 2)\n and (c2pwrite == -1 or c2pwrite > 2)\n and (errwrite == -1 or errwrite > 2)\n and not start_new_session\n and process_group == -1\n and gid is None\n and gids is None\n and uid is None\n and umask < 0):\n self._posix_spawn(args, executable, env, restore_signals, close_fds,\n p2cread, p2cwrite,\n c2pread, c2pwrite,\n errread, errwrite)\n return\n\n orig_executable = executable\n\n # For transferring possible exec failure from child to parent.\n # Data format: \"exception name:hex errno:description\"\n # Pickle is not used; it is complex and involves memory allocation.\n errpipe_read, errpipe_write = os.pipe()\n # errpipe_write must not be in the standard io 0, 1, or 2 fd range.\n low_fds_to_close = []\n while errpipe_write < 3:\n low_fds_to_close.append(errpipe_write)\n errpipe_write = os.dup(errpipe_write)\n for low_fd in low_fds_to_close:\n os.close(low_fd)\n try:\n try:\n # We must avoid complex work that could involve\n # malloc or free in the child process to avoid\n # potential deadlocks, thus we do all this here.\n # and pass it to fork_exec()\n\n if env is not None:\n env_list = []\n for k, v in env.items():\n k = os.fsencode(k)\n if b'=' in k:\n raise ValueError(\"illegal environment variable name\")\n env_list.append(k + b'=' + os.fsencode(v))\n else:\n env_list = None # Use execv instead of execve.\n executable = os.fsencode(executable)\n if os.path.dirname(executable):\n executable_list = (executable,)\n else:\n # This matches the behavior of os._execvpe().\n executable_list = tuple(\n os.path.join(os.fsencode(dir), executable)\n for dir in os.get_exec_path(env))\n fds_to_keep = set(pass_fds)\n fds_to_keep.add(errpipe_write)\n self.pid = _fork_exec(\n args, executable_list,\n close_fds, tuple(sorted(map(int, fds_to_keep))),\n cwd, env_list,\n p2cread, p2cwrite, c2pread, c2pwrite,\n errread, errwrite,\n errpipe_read, errpipe_write,\n restore_signals, start_new_session,\n process_group, gid, gids, uid, umask,\n preexec_fn)\n self._child_created = True\n finally:\n # be sure the FD is closed no matter what\n os.close(errpipe_write)\n\n self._close_pipe_fds(p2cread, p2cwrite,\n c2pread, c2pwrite,\n errread, errwrite)\n\n # Wait for exec to fail or succeed; possibly raising an\n # exception (limited in size)\n errpipe_data = bytearray()\n while True:\n part = os.read(errpipe_read, 50000)\n errpipe_data += part\n if not part or len(errpipe_data) > 50000:\n break\n finally:\n # be sure the FD is closed no matter what\n os.close(errpipe_read)\n\n if errpipe_data:\n try:\n pid, sts = os.waitpid(self.pid, 0)\n if pid == self.pid:\n self._handle_exitstatus(sts)\n else:\n self.returncode = sys.maxsize\n except ChildProcessError:\n pass\n\n try:\n exception_name, hex_errno, err_msg = (\n errpipe_data.split(b':', 2))\n # The encoding here should match the encoding\n # written in by the subprocess implementations\n # like _posixsubprocess\n err_msg = err_msg.decode()\n except ValueError:\n exception_name = b'SubprocessError'\n hex_errno = b'0'\n err_msg = 'Bad exception data from child: {!r}'.format(\n bytes(errpipe_data))\n child_exception_type = getattr(\n builtins, exception_name.decode('ascii'),\n SubprocessError)\n if issubclass(child_exception_type, OSError) and hex_errno:\n errno_num = int(hex_errno, 16)\n if err_msg == \"noexec:chdir\":\n err_msg = \"\"\n # The error must be from chdir(cwd).\n err_filename = cwd\n elif err_msg == \"noexec\":\n err_msg = \"\"\n err_filename = None\n else:\n err_filename = orig_executable\n if errno_num != 0:\n err_msg = os.strerror(errno_num)\n if err_filename is not None:\n raise child_exception_type(errno_num, err_msg, err_filename)\n else:\n raise child_exception_type(errno_num, err_msg)\n raise child_exception_type(err_msg)", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\n \"discovery_info\",\n \"entry_data\",\n \"old_addon_options\",\n \"new_addon_options\",\n \"disconnect_calls\",\n \"server_version_side_effect\",\n ),\n [\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n different_device_server_version,\n ),\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n \"log_level\": \"info\",\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n different_device_server_version,\n ),\n ],\n)\nasync def test_options_different_device(\n hass: HomeAssistant,\n client,\n supervisor,\n integration,\n addon_running,\n addon_options,\n set_addon_options,\n restart_addon,\n get_addon_discovery_info,\n discovery_info,\n entry_data,\n old_addon_options,\n new_addon_options,\n disconnect_calls,\n server_version_side_effect,\n) -> None:\n \"\"\"Test options flow and configuring a different device.\"\"\"\n addon_options.update(old_addon_options)\n entry = integration\n data = {**entry.data, **entry_data}\n hass.config_entries.async_update_entry(entry, data=data, unique_id=\"1234\")\n\n assert entry.data[\"url\"] == \"ws://test.org\"\n\n assert client.connect.call_count == 1\n assert client.disconnect.call_count == 0\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"on_supervisor\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"], {\"use_addon\": True}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"configure_addon\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n new_addon_options,\n )\n\n assert set_addon_options.call_count == 1\n new_addon_options[\"device\"] = new_addon_options.pop(\"usb_path\")\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": new_addon_options},\n )\n assert client.disconnect.call_count == disconnect_calls\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n\n assert restart_addon.call_count == 1\n assert restart_addon.call_args == call(hass, \"core_zwave_js\")\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n\n # Default emulate_hardware is False.\n addon_options = {\"emulate_hardware\": False} | old_addon_options\n # Legacy network key is not reset.\n addon_options.pop(\"network_key\")\n\n assert set_addon_options.call_count == 2\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": addon_options},\n )\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n\n assert restart_addon.call_count == 2\n assert restart_addon.call_args == call(hass, \"core_zwave_js\")\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n\n assert result[\"type\"] is FlowResultType.ABORT\n assert result[\"reason\"] == \"different_device\"\n assert entry.data == data\n assert client.connect.call_count == 2\n assert client.disconnect.call_count == 1", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n vision_config=None,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=6,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=1024,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n position_embedding_type=\"absolute\",\n use_cache=True,\n tie_word_embeddings=False,\n bos_token_id=101,\n eos_token_id=102,\n num_image_with_embedding=None,\n **kwargs,\n ):\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs)\n\n if vision_config is None:\n vision_config = {}\n logger.info(\"vision_config is None. initializing the GitVisionConfig with default values.\")\n\n self.vision_config = GitVisionConfig(**vision_config)\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.tie_word_embeddings = tie_word_embeddings\n self.num_image_with_embedding = num_image_with_embedding\n\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str,\n zerofill_results: bool = True,\n allow_metric_aggregates=True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n has_metrics: bool = True,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type=None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n equations, columns = categorize_columns(selected_columns)\n metrics_compatible = not equations\n\n if metrics_compatible:\n try:\n return metrics_timeseries_query(\n selected_columns,\n query,\n snuba_params,\n rollup,\n referrer=referrer,\n zerofill_results=zerofill_results,\n allow_metric_aggregates=allow_metric_aggregates,\n comparison_delta=comparison_delta,\n functions_acl=functions_acl,\n use_metrics_layer=use_metrics_layer,\n on_demand_metrics_enabled=on_demand_metrics_enabled,\n on_demand_metrics_type=on_demand_metrics_type,\n query_source=query_source,\n )\n # raise Invalid Queries since the same thing will happen with discover\n except InvalidSearchQuery:\n raise\n # any remaining errors mean we should try again with discover\n except IncompatibleMetricsQuery as error:\n sentry_sdk.set_tag(\"performance.mep_incompatible\", str(error))\n metrics_compatible = False\n\n # This isn't a query we can enhance with metrics\n if not metrics_compatible:\n sentry_sdk.set_tag(\"performance.dataset\", \"discover\")\n return discover.timeseries_query(\n selected_columns,\n query,\n snuba_params,\n rollup=rollup,\n referrer=referrer,\n zerofill_results=zerofill_results,\n comparison_delta=comparison_delta,\n functions_acl=functions_acl,\n has_metrics=has_metrics,\n query_source=query_source,\n )\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, [\"time\"]\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n image_size=30,\n patch_size=15,\n num_channels=3,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=300,\n hidden_size=28,\n num_attention_heads=2,\n num_labels=2,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n num_qa_labels=30,\n num_object_labels=16,\n num_attr_labels=4,\n num_visual_features=10,\n l_layers=2,\n x_layers=1,\n r_layers=1,\n visual_feat_dim=128,\n visual_pos_dim=4,\n visual_loss_normalizer=6.67,\n seq_length=20,\n batch_size=4,\n is_training=True,\n task_matched=True,\n task_mask_lm=True,\n task_obj_predict=True,\n task_qa=True,\n visual_obj_loss=True,\n visual_attr_loss=True,\n visual_feat_loss=True,\n use_token_type_ids=True,\n use_lang_mask=True,\n output_attentions=False,\n output_hidden_states=False,\n scope=None,\n ):\n self.parent = parent\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_labels = num_labels\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.pad_token_id = pad_token_id\n self.num_qa_labels = num_qa_labels\n self.num_object_labels = num_object_labels\n self.num_attr_labels = num_attr_labels\n self.l_layers = l_layers\n self.x_layers = x_layers\n self.r_layers = r_layers\n self.visual_feat_dim = visual_feat_dim\n self.visual_pos_dim = visual_pos_dim\n self.visual_loss_normalizer = visual_loss_normalizer\n self.seq_length = seq_length\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_lang_mask = use_lang_mask\n self.task_matched = task_matched\n self.task_mask_lm = task_mask_lm\n self.task_obj_predict = task_obj_predict\n self.task_qa = task_qa\n self.visual_obj_loss = visual_obj_loss\n self.visual_attr_loss = visual_attr_loss\n self.visual_feat_loss = visual_feat_loss\n self.num_visual_features = num_visual_features\n self.use_token_type_ids = use_token_type_ids\n self.output_attentions = output_attentions\n self.output_hidden_states = output_hidden_states\n self.scope = scope\n self.num_hidden_layers = {\"vision\": r_layers, \"cross_encoder\": x_layers, \"language\": l_layers}", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)\n @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqMoEModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_router_logits: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], Seq2SeqMoEModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, NllbMoeModel\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"hf-internal-testing/random-nllb-moe-2-experts\")\n >>> model = SwitchTransformersModel.from_pretrained(\"hf-internal-testing/random-nllb-moe-2-experts\")\n\n >>> input_ids = tokenizer(\n ... \"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> decoder_input_ids = tokenizer(\"Studies show that\", return_tensors=\"pt\").input_ids # Batch size 1\n\n >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for NllbMoeModel\n >>> decoder_input_ids = model._shift_right(decoder_input_ids)\n\n >>> # forward pass\n >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)\n >>> last_hidden_states = outputs.last_hidden_state\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_router_logits=output_router_logits,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, MoEModelOutput):\n encoder_outputs = MoEModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n router_probs=encoder_outputs[3] if len(encoder_outputs) > 3 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_router_logits=output_router_logits,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqMoEModelOutput(\n past_key_values=decoder_outputs.past_key_values,\n cross_attentions=decoder_outputs.cross_attentions,\n last_hidden_state=decoder_outputs.last_hidden_state,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n decoder_hidden_states=decoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n decoder_attentions=decoder_outputs.attentions,\n encoder_router_logits=encoder_outputs.router_probs,\n decoder_router_logits=decoder_outputs.router_probs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50272,\n hidden_size=768,\n num_hidden_layers=12,\n ffn_dim=3072,\n max_position_embeddings=2048,\n do_layer_norm_before=True,\n _remove_final_layer_norm=False,\n word_embed_proj_dim=None,\n dropout=0.1,\n attention_dropout=0.0,\n num_attention_heads=12,\n activation_function=\"relu\",\n layerdrop=0.0,\n init_std=0.02,\n use_cache=True,\n pad_token_id=1,\n bos_token_id=2,\n eos_token_id=2,\n enable_bias=True,\n layer_norm_elementwise_affine=True,\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n **kwargs,\n )\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.num_attention_heads = num_attention_heads\n self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size\n self.ffn_dim = ffn_dim\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.layerdrop = layerdrop\n self.use_cache = use_cache\n self.do_layer_norm_before = do_layer_norm_before\n # We keep these variables at `True` for backward compatibility.\n self.enable_bias = enable_bias\n self.layer_norm_elementwise_affine = layer_norm_elementwise_affine\n\n # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility\n # with checkpoints that have been fine-tuned before transformers v4.20.1\n # see https://github.com/facebookresearch/metaseq/pull/164\n self._remove_final_layer_norm = _remove_final_layer_norm", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n d_model=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n ffn_dim=37,\n activation_function=\"gelu\",\n activation_dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = d_model\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.ffn_dim = ffn_dim\n self.activation_function = activation_function\n self.activation_dropout = activation_dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = None\n self.bos_token_id = 0\n self.eos_token_id = 2\n self.pad_token_id = 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=False,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n image_token_id=98,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=2,\n num_key_value_heads=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n vq_num_embeds=12,\n vq_embed_dim=12,\n vq_channel_multiplier=[1, 2],\n vq_img_token_start_id=10, # has to be less than vocab size when added with vq_num_embeds\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.image_token_id = image_token_id\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope\n self.vq_num_embeds = vq_num_embeds\n self.vq_embed_dim = vq_embed_dim\n self.vq_channel_multiplier = vq_channel_multiplier\n self.vq_img_token_start_id = vq_img_token_start_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_chart_versions_v3_get_with_http_info(\n self,\n authored_by: Optional[StrictStr] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n chart_version: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n description: Annotated[Optional[StrictStr], Field(description=\"Generally the Git commit message\")] = None,\n id: Optional[StrictInt] = None,\n parent_chart_version: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many ChartVersions are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned ChartVersions (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockChartVersionV3]]:\n \"\"\"List ChartVersions matching a filter\n\n List ChartVersions matching a filter.\n\n :param authored_by:\n :type authored_by: str\n :param chart: Required when creating\n :type chart: str\n :param chart_version: Required when creating\n :type chart_version: str\n :param created_at:\n :type created_at: datetime\n :param description: Generally the Git commit message\n :type description: str\n :param id:\n :type id: int\n :param parent_chart_version:\n :type parent_chart_version: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many ChartVersions are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned ChartVersions (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_chart_versions_v3_get_serialize(\n authored_by=authored_by,\n chart=chart,\n chart_version=chart_version,\n created_at=created_at,\n description=description,\n id=id,\n parent_chart_version=parent_chart_version,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartVersionV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30000,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu_new\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=510,\n type_vocab_size=2,\n segment_means_seq_len=64,\n num_landmarks=64,\n conv_kernel_size=65,\n inv_coeff_init_option=False,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.type_vocab_size = type_vocab_size\n self.segment_means_seq_len = segment_means_seq_len\n self.num_landmarks = num_landmarks\n self.conv_kernel_size = conv_kernel_size\n self.inv_coeff_init_option = inv_coeff_init_option\n self.layer_norm_eps = layer_norm_eps\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n attention_window=4,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.attention_window = attention_window\n\n # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size\n # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention\n # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]\n # because its local attention only attends to `self.attention_window` and one before and one after\n self.key_length = self.attention_window + 2\n\n # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for\n # the `test_attention_outputs` and `test_hidden_states_output` tests\n self.encoder_seq_length = (\n self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_key_value_heads=2,\n kv_channels=8,\n intermediate_size=37,\n hidden_act=\"silu\",\n num_local_experts=4,\n num_experts_per_tok=2,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.kv_channels = kv_channels\n self.num_attention_heads = num_key_value_heads * num_experts_per_tok\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.num_local_experts = num_local_experts\n self.num_experts_per_tok = num_experts_per_tok\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LUKE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=LukeTokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n entity_ids: Optional[torch.LongTensor] = None,\n entity_attention_mask: Optional[torch.FloatTensor] = None,\n entity_token_type_ids: Optional[torch.LongTensor] = None,\n entity_position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LukeTokenClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,\n num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See\n `input_ids` above)\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.luke(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=True,\n )\n\n sequence_output = outputs.last_hidden_state\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(logits.device)\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n if not return_dict:\n return tuple(\n v\n for v in [loss, logits, outputs.hidden_states, outputs.entity_hidden_states, outputs.attentions]\n if v is not None\n )\n\n return LukeTokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n entity_hidden_states=outputs.entity_hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n use_timm_backbone=True,\n backbone_config=None,\n num_channels=3,\n num_queries=300,\n encoder_layers=6,\n encoder_ffn_dim=2048,\n encoder_attention_heads=8,\n decoder_layers=6,\n decoder_ffn_dim=2048,\n decoder_attention_heads=8,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n is_encoder_decoder=True,\n activation_function=\"relu\",\n d_model=256,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n init_xavier_std=1.0,\n auxiliary_loss=False,\n position_embedding_type=\"sine\",\n backbone=\"resnet50\",\n use_pretrained_backbone=True,\n backbone_kwargs=None,\n dilation=False,\n class_cost=2,\n bbox_cost=5,\n giou_cost=2,\n mask_loss_coefficient=1,\n dice_loss_coefficient=1,\n cls_loss_coefficient=2,\n bbox_loss_coefficient=5,\n giou_loss_coefficient=2,\n focal_alpha=0.25,\n **kwargs,\n ):\n # We default to values which were previously hard-coded in the model. This enables configurability of the config\n # while keeping the default behavior the same.\n if use_timm_backbone and backbone_kwargs is None:\n backbone_kwargs = {}\n if dilation:\n backbone_kwargs[\"output_stride\"] = 16\n backbone_kwargs[\"out_indices\"] = [1, 2, 3, 4]\n backbone_kwargs[\"in_chans\"] = num_channels\n # Backwards compatibility\n elif not use_timm_backbone and backbone in (None, \"resnet50\"):\n if backbone_config is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\")\n backbone_config = CONFIG_MAPPING[\"resnet\"](out_features=[\"stage4\"])\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.get(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n self.use_timm_backbone = use_timm_backbone\n self.backbone_config = backbone_config\n self.num_channels = num_channels\n self.num_queries = num_queries\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.init_xavier_std = init_xavier_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.num_hidden_layers = encoder_layers\n self.auxiliary_loss = auxiliary_loss\n self.position_embedding_type = position_embedding_type\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.backbone_kwargs = backbone_kwargs\n self.dilation = dilation\n # Hungarian matcher\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n # Loss coefficients\n self.mask_loss_coefficient = mask_loss_coefficient\n self.dice_loss_coefficient = dice_loss_coefficient\n self.cls_loss_coefficient = cls_loss_coefficient\n self.bbox_loss_coefficient = bbox_loss_coefficient\n self.giou_loss_coefficient = giou_loss_coefficient\n self.focal_alpha = focal_alpha\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __get_data_legacy(\n self,\n model,\n keys,\n start,\n end,\n rollup=None,\n environment_ids=None,\n aggregation=\"count()\",\n group_on_model=True,\n group_on_time=False,\n conditions=None,\n use_cache=False,\n jitter_value=None,\n tenant_ids=None,\n referrer_suffix=None,\n ):\n \"\"\"\n Normalizes all the TSDB parameters and sends a query to snuba.\n\n `group_on_time`: whether to add a GROUP BY clause on the 'time' field.\n `group_on_model`: whether to add a GROUP BY clause on the primary model.\n \"\"\"\n # XXX: to counteract the hack in project_key_stats.py\n if model in [\n TSDBModel.key_total_received,\n TSDBModel.key_total_blacklisted,\n TSDBModel.key_total_rejected,\n ]:\n keys = list(set(map(lambda x: int(x), keys)))\n\n model_requires_manual_group_on_time = model in (\n TSDBModel.group_generic,\n TSDBModel.users_affected_by_generic_group,\n )\n group_on_time_column_alias = \"grouped_time\"\n\n model_query_settings = self.model_query_settings.get(model)\n\n if model_query_settings is None:\n raise Exception(f\"Unsupported TSDBModel: {model.name}\")\n\n model_group = model_query_settings.groupby\n model_aggregate = model_query_settings.aggregate\n\n # 10s is the only rollup under an hour that we support\n if rollup == 10 and model_query_settings.dataset == Dataset.Outcomes:\n model_dataset = Dataset.OutcomesRaw\n else:\n model_dataset = model_query_settings.dataset\n\n groupby = []\n if group_on_model and model_group is not None:\n groupby.append(model_group)\n if group_on_time:\n if not model_requires_manual_group_on_time:\n groupby.append(\"time\")\n else:\n groupby.append(group_on_time_column_alias)\n if aggregation == \"count()\" and model_aggregate is not None:\n # Special case, because count has different semantics, we change:\n # `COUNT(model_aggregate)` to `COUNT() GROUP BY model_aggregate`\n groupby.append(model_aggregate)\n model_aggregate = None\n\n columns = (model_query_settings.groupby, model_query_settings.aggregate)\n keys_map = dict(zip(columns, self.flatten_keys(keys)))\n keys_map = {k: v for k, v in keys_map.items() if k is not None and v is not None}\n if environment_ids is not None:\n keys_map[\"environment\"] = environment_ids\n\n aggregated_as = \"aggregate\"\n aggregations = [[aggregation, model_aggregate, aggregated_as]]\n\n # For historical compatibility with bucket-counted TSDB implementations\n # we grab the original bucketed series and add the rollup time to the\n # timestamp of the last bucket to get the end time.\n rollup, series = self.get_optimal_rollup_series(start, end, rollup)\n\n if group_on_time and model_requires_manual_group_on_time:\n aggregations.append(\n self.__manual_group_on_time_aggregation(rollup, group_on_time_column_alias)\n )\n\n # If jitter_value is provided then we use it to offset the buckets we round start/end to by\n # up to `rollup` seconds.\n series = self._add_jitter_to_series(series, start, rollup, jitter_value)\n\n start = to_datetime(series[0])\n end = to_datetime(series[-1] + rollup)\n limit = min(10000, int(len(keys) * ((end - start).total_seconds() / rollup)))\n\n conditions = conditions if conditions is not None else []\n if model_query_settings.conditions is not None:\n conditions += deepcopy(model_query_settings.conditions)\n # copy because we modify the conditions in snuba.query\n\n orderby = []\n if group_on_time:\n if not model_requires_manual_group_on_time:\n orderby.append(\"-time\")\n else:\n orderby.append(f\"-{group_on_time_column_alias}\")\n if group_on_model and model_group is not None:\n orderby.append(model_group)\n\n if keys:\n referrer = f\"tsdb-modelid:{model.value}\"\n\n if referrer_suffix:\n referrer += f\".{referrer_suffix}\"\n\n query_func_without_selected_columns = functools.partial(\n snuba.query,\n dataset=model_dataset,\n start=start,\n end=end,\n groupby=groupby,\n conditions=conditions,\n filter_keys=keys_map,\n aggregations=aggregations,\n rollup=rollup,\n limit=limit,\n orderby=orderby,\n referrer=referrer,\n is_grouprelease=(model == TSDBModel.frequent_releases_by_group),\n use_cache=use_cache,\n tenant_ids=tenant_ids or dict(),\n )\n if model_query_settings.selected_columns:\n result = query_func_without_selected_columns(\n selected_columns=model_query_settings.selected_columns\n )\n self.unnest(result, aggregated_as)\n else:\n result = query_func_without_selected_columns()\n else:\n result = {}\n\n if group_on_time:\n if not model_requires_manual_group_on_time:\n keys_map[\"time\"] = series\n else:\n keys_map[group_on_time_column_alias] = series\n\n self.zerofill(result, groupby, keys_map)\n self.trim(result, groupby, keys)\n\n if group_on_time and model_requires_manual_group_on_time:\n # unroll aggregated data\n self.unnest(result, aggregated_as)\n return result\n else:\n return result", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n prediction_length: Optional[int] = None,\n context_length: Optional[int] = None,\n distribution_output: str = \"student_t\",\n loss: str = \"nll\",\n input_size: int = 1,\n lags_sequence: List[int] = [1, 2, 3, 4, 5, 6, 7],\n scaling: Optional[Union[str, bool]] = \"mean\",\n num_dynamic_real_features: int = 0,\n num_static_categorical_features: int = 0,\n num_static_real_features: int = 0,\n num_time_features: int = 0,\n cardinality: Optional[List[int]] = None,\n embedding_dimension: Optional[List[int]] = None,\n encoder_ffn_dim: int = 32,\n decoder_ffn_dim: int = 32,\n encoder_attention_heads: int = 2,\n decoder_attention_heads: int = 2,\n encoder_layers: int = 2,\n decoder_layers: int = 2,\n is_encoder_decoder: bool = True,\n activation_function: str = \"gelu\",\n d_model: int = 64,\n dropout: float = 0.1,\n encoder_layerdrop: float = 0.1,\n decoder_layerdrop: float = 0.1,\n attention_dropout: float = 0.1,\n activation_dropout: float = 0.1,\n num_parallel_samples: int = 100,\n init_std: float = 0.02,\n use_cache=True,\n **kwargs,\n ):\n # time series specific configuration\n self.prediction_length = prediction_length\n self.context_length = context_length or prediction_length\n self.distribution_output = distribution_output\n self.loss = loss\n self.input_size = input_size\n self.num_time_features = num_time_features\n self.lags_sequence = lags_sequence\n self.scaling = scaling\n self.num_dynamic_real_features = num_dynamic_real_features\n self.num_static_real_features = num_static_real_features\n self.num_static_categorical_features = num_static_categorical_features\n if cardinality and num_static_categorical_features > 0:\n if len(cardinality) != num_static_categorical_features:\n raise ValueError(\n \"The cardinality should be a list of the same length as `num_static_categorical_features`\"\n )\n self.cardinality = cardinality\n else:\n self.cardinality = [0]\n if embedding_dimension and num_static_categorical_features > 0:\n if len(embedding_dimension) != num_static_categorical_features:\n raise ValueError(\n \"The embedding dimension should be a list of the same length as `num_static_categorical_features`\"\n )\n self.embedding_dimension = embedding_dimension\n else:\n self.embedding_dimension = [min(50, (cat + 1) // 2) for cat in self.cardinality]\n self.num_parallel_samples = num_parallel_samples\n\n # Transformer architecture configuration\n self.feature_size = input_size * len(lags_sequence) + self._number_of_features\n self.d_model = d_model\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_attention_heads = decoder_attention_heads\n self.encoder_ffn_dim = encoder_ffn_dim\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.decoder_layers = decoder_layers\n\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n\n self.activation_function = activation_function\n self.init_std = init_std\n\n self.use_cache = use_cache\n\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=60,\n is_training=True,\n use_labels=True,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n input_channels=1,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n max_source_positions=30,\n num_mel_bins=80,\n num_conv_layers=1,\n suppress_tokens=None,\n classifier_proj_size=4,\n num_labels=2,\n is_encoder_decoder=False,\n is_decoder=False,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.input_channels = input_channels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_mel_bins = num_mel_bins\n self.max_position_embeddings = max_position_embeddings\n self.max_source_positions = max_source_positions\n self.num_conv_layers = num_conv_layers\n self.suppress_tokens = suppress_tokens\n self.classifier_proj_size = classifier_proj_size\n self.num_labels = num_labels\n self.is_encoder_decoder = is_encoder_decoder\n self.is_decoder = is_decoder", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=9,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n decoder_layers=None,\n sparse_step=1,\n num_sparse_decoder_layers=2,\n num_sparse_encoder_layers=2,\n expert_capacity=100,\n router_jitter_noise=0.0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = decoder_layers\n self.sparse_step = sparse_step\n self.num_sparse_decoder_layers = num_sparse_decoder_layers\n self.num_sparse_encoder_layers = num_sparse_encoder_layers\n self.expert_capacity = expert_capacity\n self.router_jitter_noise = router_jitter_noise", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_end_docstrings(LAYOUTXLM_ENCODE_KWARGS_DOCSTRING)\n def prepare_for_model(\n self,\n text: Union[TextInput, PreTokenizedInput],\n text_pair: Optional[PreTokenizedInput] = None,\n boxes: Optional[List[List[int]]] = None,\n word_labels: Optional[List[int]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n prepend_batch_axis: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,\n truncates sequences if overflowing while taking into account the special tokens and manages a moving window\n (with user defined stride) for overflowing tokens.\n\n Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into\n token-level `labels`. The word label is used for the first token of the word, while remaining tokens are\n labeled with -100, such that they will be ignored by the loss function.\n\n Args:\n text (`str`, `List[str]`, `List[List[str]]`):\n The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.\n text_pair (`List[str]` or `List[int]`, *optional*):\n Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a\n list of list of strings (words of a batch of examples).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n tokens = []\n pair_tokens = []\n token_boxes = []\n pair_token_boxes = []\n labels = []\n\n if text_pair is None:\n if word_labels is None:\n # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)\n for word, box in zip(text, boxes):\n if len(word) < 1: # skip empty words\n continue\n word_tokens = self.tokenize(word)\n tokens.extend(word_tokens)\n token_boxes.extend([box] * len(word_tokens))\n else:\n # CASE 2: token classification (training)\n for word, box, label in zip(text, boxes, word_labels):\n if len(word) < 1: # skip empty words\n continue\n word_tokens = self.tokenize(word)\n tokens.extend(word_tokens)\n token_boxes.extend([box] * len(word_tokens))\n if self.only_label_first_subword:\n # Use the real label id for the first token of the word, and padding ids for the remaining tokens\n labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))\n else:\n labels.extend([label] * len(word_tokens))\n else:\n # CASE 3: document visual question answering (inference)\n # text = question\n # text_pair = words\n tokens = self.tokenize(text)\n token_boxes = [self.pad_token_box for _ in range(len(tokens))] + [self.sep_token_box]\n\n for word, box in zip(text_pair, boxes):\n if len(word) < 1: # skip empty words\n continue\n word_tokens = self.tokenize(word)\n pair_tokens.extend(word_tokens)\n pair_token_boxes.extend([box] * len(word_tokens))\n\n # Create ids + pair_ids\n ids = self.convert_tokens_to_ids(tokens)\n pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None\n\n # Compute the total size of the returned encodings\n pair = bool(pair_ids is not None)\n len_ids = len(ids)\n len_pair_ids = len(pair_ids) if pair else 0\n total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)\n\n # Truncation: Handle max sequence length\n overflowing_tokens = []\n overflowing_token_boxes = []\n overflowing_labels = []\n if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:\n (\n ids,\n token_boxes,\n pair_ids,\n pair_token_boxes,\n labels,\n overflowing_tokens,\n overflowing_token_boxes,\n overflowing_labels,\n ) = self.truncate_sequences(\n ids,\n token_boxes,\n pair_ids=pair_ids,\n pair_token_boxes=pair_token_boxes,\n labels=labels,\n num_tokens_to_remove=total_len - max_length,\n truncation_strategy=truncation_strategy,\n stride=stride,\n )\n\n if return_token_type_ids and not add_special_tokens:\n raise ValueError(\n \"Asking to return token_type_ids while setting add_special_tokens to False \"\n \"results in an undefined behavior. Please set add_special_tokens to True or \"\n \"set return_token_type_ids to None.\"\n )\n\n # Load from model defaults\n if return_token_type_ids is None:\n return_token_type_ids = \"token_type_ids\" in self.model_input_names\n if return_attention_mask is None:\n return_attention_mask = \"attention_mask\" in self.model_input_names\n\n encoded_inputs = {}\n\n if return_overflowing_tokens:\n encoded_inputs[\"overflowing_tokens\"] = overflowing_tokens\n encoded_inputs[\"overflowing_token_boxes\"] = overflowing_token_boxes\n encoded_inputs[\"overflowing_labels\"] = overflowing_labels\n encoded_inputs[\"num_truncated_tokens\"] = total_len - max_length\n\n # Add special tokens\n if add_special_tokens:\n sequence = self.build_inputs_with_special_tokens(ids, pair_ids)\n token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)\n token_boxes = [self.cls_token_box] + token_boxes + [self.sep_token_box]\n if pair_token_boxes:\n pair_token_boxes = pair_token_boxes + [self.sep_token_box]\n if labels:\n labels = [self.pad_token_label] + labels + [self.pad_token_label]\n else:\n sequence = ids + pair_ids if pair else ids\n token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])\n\n # Build output dictionary\n encoded_inputs[\"input_ids\"] = sequence\n encoded_inputs[\"bbox\"] = token_boxes + pair_token_boxes\n if return_token_type_ids:\n encoded_inputs[\"token_type_ids\"] = token_type_ids\n if return_special_tokens_mask:\n if add_special_tokens:\n encoded_inputs[\"special_tokens_mask\"] = self.get_special_tokens_mask(ids, pair_ids)\n else:\n encoded_inputs[\"special_tokens_mask\"] = [0] * len(sequence)\n\n if labels:\n encoded_inputs[\"labels\"] = labels\n\n # Check lengths\n self._eventual_warn_about_too_long_sequence(encoded_inputs[\"input_ids\"], max_length, verbose)\n\n # Padding\n if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:\n encoded_inputs = self.pad(\n encoded_inputs,\n max_length=max_length,\n padding=padding_strategy.value,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_attention_mask=return_attention_mask,\n )\n\n if return_length:\n encoded_inputs[\"length\"] = len(encoded_inputs[\"input_ids\"])\n\n batch_outputs = BatchEncoding(\n encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis\n )\n\n return batch_outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_channels: int = 3,\n image_size: int = 600,\n width_coefficient: float = 2.0,\n depth_coefficient: float = 3.1,\n depth_divisor: int = 8,\n kernel_sizes: List[int] = [3, 3, 5, 3, 5, 5, 3],\n in_channels: List[int] = [32, 16, 24, 40, 80, 112, 192],\n out_channels: List[int] = [16, 24, 40, 80, 112, 192, 320],\n depthwise_padding: List[int] = [],\n strides: List[int] = [1, 2, 2, 2, 1, 2, 1],\n num_block_repeats: List[int] = [1, 2, 2, 3, 3, 4, 1],\n expand_ratios: List[int] = [1, 6, 6, 6, 6, 6, 6],\n squeeze_expansion_ratio: float = 0.25,\n hidden_act: str = \"swish\",\n hidden_dim: int = 2560,\n pooling_type: str = \"mean\",\n initializer_range: float = 0.02,\n batch_norm_eps: float = 0.001,\n batch_norm_momentum: float = 0.99,\n drop_connect_rate: float = 0.2,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.num_channels = num_channels\n self.image_size = image_size\n self.width_coefficient = width_coefficient\n self.depth_coefficient = depth_coefficient\n self.depth_divisor = depth_divisor\n self.kernel_sizes = kernel_sizes\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.depthwise_padding = depthwise_padding\n self.strides = strides\n self.num_block_repeats = num_block_repeats\n self.expand_ratios = expand_ratios\n self.squeeze_expansion_ratio = squeeze_expansion_ratio\n self.hidden_act = hidden_act\n self.hidden_dim = hidden_dim\n self.pooling_type = pooling_type\n self.initializer_range = initializer_range\n self.batch_norm_eps = batch_norm_eps\n self.batch_norm_momentum = batch_norm_momentum\n self.drop_connect_rate = drop_connect_rate\n self.num_hidden_layers = sum(num_block_repeats) * 4", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n req: Optional[Requirement],\n comes_from: Optional[Union[str, \"InstallRequirement\"]],\n editable: bool = False,\n link: Optional[Link] = None,\n markers: Optional[Marker] = None,\n use_pep517: Optional[bool] = None,\n isolated: bool = False,\n install_options: Optional[List[str]] = None,\n global_options: Optional[List[str]] = None,\n hash_options: Optional[Dict[str, List[str]]] = None,\n constraint: bool = False,\n extras: Collection[str] = (),\n user_supplied: bool = False,\n permit_editable_wheels: bool = False,\n ) -> None:\n assert req is None or isinstance(req, Requirement), req\n self.req = req\n self.comes_from = comes_from\n self.constraint = constraint\n self.editable = editable\n self.permit_editable_wheels = permit_editable_wheels\n self.legacy_install_reason: Optional[int] = None\n\n # source_dir is the local directory where the linked requirement is\n # located, or unpacked. In case unpacking is needed, creating and\n # populating source_dir is done by the RequirementPreparer. Note this\n # is not necessarily the directory where pyproject.toml or setup.py is\n # located - that one is obtained via unpacked_source_directory.\n self.source_dir: Optional[str] = None\n if self.editable:\n assert link\n if link.is_file:\n self.source_dir = os.path.normpath(os.path.abspath(link.file_path))\n\n if link is None and req and req.url:\n # PEP 508 URL requirement\n link = Link(req.url)\n self.link = self.original_link = link\n self.original_link_is_in_wheel_cache = False\n\n # Path to any downloaded or already-existing package.\n self.local_file_path: Optional[str] = None\n if self.link and self.link.is_file:\n self.local_file_path = self.link.file_path\n\n if extras:\n self.extras = extras\n elif req:\n self.extras = {safe_extra(extra) for extra in req.extras}\n else:\n self.extras = set()\n if markers is None and req:\n markers = req.marker\n self.markers = markers\n\n # This holds the Distribution object if this requirement is already installed.\n self.satisfied_by: Optional[BaseDistribution] = None\n # Whether the installation process should try to uninstall an existing\n # distribution before installing this requirement.\n self.should_reinstall = False\n # Temporary build location\n self._temp_build_dir: Optional[TempDirectory] = None\n # Set to True after successful installation\n self.install_succeeded: Optional[bool] = None\n # Supplied options\n self.install_options = install_options if install_options else []\n self.global_options = global_options if global_options else []\n self.hash_options = hash_options if hash_options else {}\n # Set to True after successful preparation of this requirement\n self.prepared = False\n # User supplied requirement are explicitly requested for installation\n # by the user via CLI arguments or requirements files, as opposed to,\n # e.g. dependencies, extras or constraints.\n self.user_supplied = user_supplied\n\n self.isolated = isolated\n self.build_env: BuildEnvironment = NoOpBuildEnvironment()\n\n # For PEP 517, the directory where we request the project metadata\n # gets stored. We need this to pass to build_wheel, so the backend\n # can ensure that the wheel matches the metadata (see the PEP for\n # details).\n self.metadata_directory: Optional[str] = None\n\n # The static build requirements (from pyproject.toml)\n self.pyproject_requires: Optional[List[str]] = None\n\n # Build requirements that we will check are available\n self.requirements_to_check: List[str] = []\n\n # The PEP 517 backend we should use to build the project\n self.pep517_backend: Optional[Pep517HookCaller] = None\n\n # Are we using PEP 517 for this requirement?\n # After pyproject.toml has been loaded, the only valid values are True\n # and False. Before loading, None is valid (meaning \"use the default\").\n # Setting an explicit value before loading pyproject.toml is supported,\n # but after loading this flag should be treated as read only.\n self.use_pep517 = use_pep517\n\n # This requirement needs more preparation before it can be built\n self.needs_more_preparation = False", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLM_ROBERTA_XL_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RobertaForCausalLM, RobertaConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config = RobertaConfig.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config.is_decoder = True\n >>> model = RobertaForCausalLM.from_pretrained(\"FacebookAI/roberta-base\", config=config)\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> prediction_logits = outputs.logits\n ```\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.roberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqQuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n start_positions: Optional[torch.LongTensor] = None,\n end_positions: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqQuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n if start_positions is not None and end_positions is not None:\n use_cache = False\n\n # Copied from models.bart.modeling_bart.BartModel.forward\n # different to other models, T5 automatically creates decoder_input_ids from\n # input_ids if no decoder_input_ids are provided\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n if input_ids is None:\n raise ValueError(\n \"If no `decoder_input_ids` or `decoder_inputs_embeds` are \"\n \"passed, `input_ids` cannot be `None`. Please pass either \"\n \"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.\"\n )\n decoder_input_ids = self._shift_right(input_ids)\n\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=None,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1).to(start_logits.device)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1).to(end_logits.device)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + decoder_outputs[1:] + encoder_outputs\n return ((total_loss,) + output) if total_loss is not None else output\n\n return Seq2SeqQuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\n \"discovery_info\",\n \"entry_data\",\n \"old_addon_options\",\n \"new_addon_options\",\n \"disconnect_calls\",\n ),\n [\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"abc123\",\n \"s0_legacy_key\": \"abc123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n ),\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {\"use_addon\": True},\n {\n \"device\": \"/test\",\n \"network_key\": \"abc123\",\n \"s0_legacy_key\": \"abc123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 1,\n ),\n ],\n)\nasync def test_options_addon_not_installed(\n hass: HomeAssistant,\n client,\n supervisor,\n addon_not_installed,\n install_addon,\n integration,\n addon_options,\n set_addon_options,\n start_addon,\n get_addon_discovery_info,\n discovery_info,\n entry_data,\n old_addon_options,\n new_addon_options,\n disconnect_calls,\n) -> None:\n \"\"\"Test options flow and add-on not installed on Supervisor.\"\"\"\n addon_options.update(old_addon_options)\n entry = integration\n data = {**entry.data, **entry_data}\n hass.config_entries.async_update_entry(entry, data=data, unique_id=\"1234\")\n\n assert entry.data[\"url\"] == \"ws://test.org\"\n\n assert client.connect.call_count == 1\n assert client.disconnect.call_count == 0\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"on_supervisor\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"], {\"use_addon\": True}\n )\n\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"install_addon\"\n\n # Make sure the flow continues when the progress task is done.\n await hass.async_block_till_done()\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n\n assert install_addon.call_args == call(hass, \"core_zwave_js\")\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"configure_addon\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n new_addon_options,\n )\n\n new_addon_options[\"device\"] = new_addon_options.pop(\"usb_path\")\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": new_addon_options},\n )\n assert client.disconnect.call_count == disconnect_calls\n\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n\n assert start_addon.call_count == 1\n assert start_addon.call_args == call(hass, \"core_zwave_js\")\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n await hass.async_block_till_done()\n\n assert result[\"type\"] is FlowResultType.CREATE_ENTRY\n assert entry.data[\"url\"] == \"ws://host1:3001\"\n assert entry.data[\"usb_path\"] == new_addon_options[\"device\"]\n assert entry.data[\"s0_legacy_key\"] == new_addon_options[\"s0_legacy_key\"]\n assert entry.data[\"use_addon\"] is True\n assert entry.data[\"integration_created_addon\"] is True\n assert client.connect.call_count == 2\n assert client.disconnect.call_count == 1", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=1024, # speech is longer\n is_training=False,\n hidden_size=16,\n feat_extract_norm=\"group\",\n feat_extract_dropout=0.0,\n feat_extract_activation=\"gelu\",\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n num_hidden_layers=2,\n num_attention_heads=2,\n hidden_dropout_prob=0.1, # this is most likely not correctly set yet\n intermediate_size=20,\n layer_norm_eps=1e-5,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n vocab_size=32,\n do_stable_layer_norm=False,\n tdnn_dim=(32, 32),\n tdnn_kernel=(3, 3),\n tdnn_dilation=(1, 1),\n xvector_output_dim=32,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_dropout = feat_extract_dropout\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.intermediate_size = intermediate_size\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.tdnn_dim = tdnn_dim\n self.tdnn_kernel = tdnn_kernel\n self.tdnn_dilation = tdnn_dilation\n self.xvector_output_dim = xvector_output_dim\n self.scope = scope\n\n output_seq_length = self.seq_length\n for kernel, stride in zip(self.conv_kernel, self.conv_stride):\n output_seq_length = (output_seq_length - (kernel - 1)) / stride\n self.output_seq_length = int(math.ceil(output_seq_length))\n self.encoder_seq_length = self.output_seq_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __call__(\n self,\n text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n return_tensors: Optional[Union[str, TensorType]] = None,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n This method uses [`BertTokenizerFast.__call__`] to prepare text for the model.\n\n Please refer to the docstring of the above two methods for more information.\n \"\"\"\n encoding = self.tokenizer(\n text=text,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n return_tensors=return_tensors,\n **kwargs,\n )\n\n return encoding", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=False,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=False,\n vocab_size=19,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def reimport_scan_with_params(self, test_id, filename, scan_type=\"ZAP Scan\", engagement=1, minimum_severity=\"Low\", active=True, verified=False, push_to_jira=None,\n tags=None, close_old_findings=True, group_by=None, engagement_name=None, scan_date=None,\n product_name=None, product_type_name=None, auto_create_context=None, expected_http_status_code=201, test_title=None):\n with open(get_unit_tests_path() + \"/\" + filename, encoding=\"utf-8\") as testfile:\n payload = {\n \"minimum_severity\": minimum_severity,\n \"active\": active,\n \"verified\": verified,\n \"scan_type\": scan_type,\n \"file\": testfile,\n \"version\": \"1.0.1\",\n \"close_old_findings\": close_old_findings,\n }\n\n if test_id is not None:\n payload[\"test\"] = test_id\n\n if engagement:\n payload[\"engagement\"] = engagement\n\n if engagement_name:\n payload[\"engagement_name\"] = engagement_name\n\n if product_name:\n payload[\"product_name\"] = product_name\n\n if product_type_name:\n payload[\"product_type_name\"] = product_type_name\n\n if auto_create_context:\n payload[\"auto_create_context\"] = auto_create_context\n\n if push_to_jira is not None:\n payload[\"push_to_jira\"] = push_to_jira\n\n if tags is not None:\n payload[\"tags\"] = tags\n\n if group_by is not None:\n payload[\"group_by\"] = group_by\n\n if test_title is not None:\n payload[\"test_title\"] = test_title\n\n if scan_date is not None:\n payload[\"scan_date\"] = scan_date\n\n return self.reimport_scan(payload, expected_http_status_code=expected_http_status_code)", "smellKey": "S107", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n type_sequence_label_size=10,\n initializer_range=0.02,\n scope=None,\n attn_implementation=\"eager\",\n mask_ratio=0.5,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.scope = scope\n self.attn_implementation = attn_implementation\n self.mask_ratio = mask_ratio\n\n # in Dinov2, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1\n self.num_masks = int(self.mask_ratio * self.seq_length)\n self.mask_length = num_patches", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file=None,\n tokenizer_file=None,\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n cls_token_box=[0, 0, 0, 0],\n sep_token_box=[1000, 1000, 1000, 1000],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n **kwargs,\n ):\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n super().__init__(\n vocab_file,\n tokenizer_file=tokenizer_file,\n bos_token=bos_token,\n eos_token=eos_token,\n sep_token=sep_token,\n cls_token=cls_token,\n unk_token=unk_token,\n pad_token=pad_token,\n mask_token=mask_token,\n cls_token_box=cls_token_box,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n **kwargs,\n )\n\n self.vocab_file = vocab_file\n\n # additional properties\n self.cls_token_box = cls_token_box\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def forward(\n self,\n hidden_states,\n attention_mask=None,\n head_mask=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n past_key_values=None,\n use_cache=None,\n output_attentions=False,\n output_hidden_states=False,\n band_mask=None,\n from_mask=None,\n to_mask=None,\n blocked_encoder_mask=None,\n return_dict=True,\n ) -> Union[BaseModelOutputWithPastAndCrossAttentions, Tuple]:\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None\n\n if self.gradient_checkpointing and self.training:\n if use_cache:\n logger.warning_once(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n\n next_decoder_cache = () if use_cache else None\n\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n layer_head_mask = head_mask[i] if head_mask is not None else None\n past_key_value = past_key_values[i] if past_key_values is not None else None\n\n if self.gradient_checkpointing and self.training:\n layer_outputs = self._gradient_checkpointing_func(\n layer_module.__call__,\n hidden_states,\n attention_mask,\n layer_head_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n band_mask,\n from_mask,\n to_mask,\n blocked_encoder_mask,\n past_key_value,\n output_attentions,\n )\n else:\n layer_outputs = layer_module(\n hidden_states,\n attention_mask,\n layer_head_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n band_mask,\n from_mask,\n to_mask,\n blocked_encoder_mask,\n past_key_value,\n output_attentions,\n )\n\n hidden_states = layer_outputs[0]\n if use_cache:\n next_decoder_cache += (layer_outputs[-1],)\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n if self.config.add_cross_attention:\n all_cross_attentions = all_cross_attentions + (layer_outputs[2],)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(\n v\n for v in [\n hidden_states,\n next_decoder_cache,\n all_hidden_states,\n all_self_attentions,\n all_cross_attentions,\n ]\n if v is not None\n )\n return BaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n past_key_values=next_decoder_cache,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n cross_attentions=all_cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n # Copied from transformers.models.bart.modeling_bart.BartForSequenceClassification.forward\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n if input_ids is None and inputs_embeds is not None:\n raise NotImplementedError(\n f\"Passing input embeddings is currently not supported for {self.__class__.__name__}\"\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = outputs[0] # last hidden state\n\n eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)\n\n if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:\n raise ValueError(\"All examples must have the same number of <eos> tokens.\")\n sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[\n :, -1, :\n ]\n logits = self.classification_head(sentence_representation)\n\n loss = None\n if labels is not None:\n labels = labels.to(logits.device)\n if self.config.problem_type is None:\n if self.config.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.config.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_deploy_hooks_slack_v3_get_serialize(\n self,\n created_at,\n id,\n mention_people,\n on_chart_release,\n on_environment,\n on_failure,\n on_success,\n slack_channel,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if mention_people is not None:\n \n _query_params.append(('mentionPeople', mention_people))\n \n if on_chart_release is not None:\n \n _query_params.append(('onChartRelease', on_chart_release))\n \n if on_environment is not None:\n \n _query_params.append(('onEnvironment', on_environment))\n \n if on_failure is not None:\n \n _query_params.append(('onFailure', on_failure))\n \n if on_success is not None:\n \n _query_params.append(('onSuccess', on_success))\n \n if slack_channel is not None:\n \n _query_params.append(('slackChannel', slack_channel))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/deploy-hooks/slack/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n additional_vocab_size=0,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n dropout=0.0,\n hidden_act=\"silu\",\n initializer_range=0.02,\n alpha_initializer=\"zeros\",\n alphas_initializer_range=0.0,\n alpha_type=\"float\",\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n cross_layer_interval=1,\n qk_layer_norms=False,\n freeze_text_layers=True,\n freeze_text_module_exceptions=[],\n freeze_lm_head=False,\n freeze_vision_layers=True,\n freeze_vision_module_exceptions=[],\n use_resampler=False,\n vision_config=None,\n perceiver_config=None,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.additional_vocab_size = additional_vocab_size\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.dropout = dropout\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.alpha_initializer = alpha_initializer\n self.alphas_initializer_range = alphas_initializer_range\n self.alpha_type = alpha_type\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n\n self.cross_layer_interval = cross_layer_interval\n self.qk_layer_norms = qk_layer_norms\n self.freeze_vision_layers = freeze_vision_layers\n\n self.freeze_text_layers = freeze_text_layers\n self.freeze_text_module_exceptions = freeze_text_module_exceptions\n self.freeze_vision_module_exceptions = freeze_vision_module_exceptions\n self.freeze_lm_head = freeze_lm_head\n\n self.use_resampler = use_resampler\n\n if perceiver_config is None:\n self.perceiver_config = IdeficsPerceiverConfig()\n elif isinstance(perceiver_config, dict):\n self.perceiver_config = IdeficsPerceiverConfig(**perceiver_config)\n elif isinstance(perceiver_config, IdeficsPerceiverConfig):\n self.perceiver_config = perceiver_config\n\n if vision_config is None:\n self.vision_config = IdeficsVisionConfig()\n elif isinstance(vision_config, dict):\n self.vision_config = IdeficsVisionConfig(**vision_config)\n elif isinstance(vision_config, IdeficsVisionConfig):\n self.vision_config = vision_config\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )\n\n # IMPORTANT: Do not do any __init__ args-based checks in the constructor, since\n # PretrainedConfig.from_dict first instantiates the class with the config dict and only then\n # updates the config object with `kwargs` from from_pretrained, so during the instantiation\n # of this object many attributes have default values and haven't yet been overridden.\n # Do any required checks inside `from_pretrained` once the superclass' `from_pretrained` was run.", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(QWEN2_VL_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Qwen2VLCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n pixel_values: Optional[torch.Tensor] = None,\n pixel_values_videos: Optional[torch.FloatTensor] = None,\n image_grid_thw: Optional[torch.LongTensor] = None,\n video_grid_thw: Optional[torch.LongTensor] = None,\n rope_deltas: Optional[torch.LongTensor] = None,\n ) -> Union[Tuple, Qwen2VLCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration\n\n >>> model = Qwen2VLForConditionalGeneration.from_pretrained(\"Qwen/Qwen2-VL-7B-Instruct\")\n >>> processor = AutoProcessor.from_pretrained(\"Qwen/Qwen2-VL-7B-Instruct\")\n\n >>> messages = [\n {\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"image\"},\n {\"type\": \"text\", \"text\": \"What is shown in this image?\"},\n ],\n },\n ]\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ...\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if inputs_embeds is None:\n inputs_embeds = self.model.embed_tokens(input_ids)\n if pixel_values is not None:\n pixel_values = pixel_values.type(self.visual.get_dtype())\n image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)\n image_mask = (\n (input_ids == self.config.image_token_id)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)\n\n if pixel_values_videos is not None:\n pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())\n video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)\n video_mask = (\n (input_ids == self.config.video_token_id)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)\n\n if attention_mask is not None:\n attention_mask = attention_mask.to(inputs_embeds.device)\n\n outputs = self.model(\n input_ids=None,\n position_ids=position_ids,\n attention_mask=attention_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n logits = self.lm_head(hidden_states)\n logits = logits.float()\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n shift_logits = shift_logits.view(-1, self.config.vocab_size)\n shift_labels = shift_labels.view(-1)\n # Enable model parallelism\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return Qwen2VLCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n rope_deltas=rope_deltas,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=40,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _update_retryable(\n self,\n criteria: Mapping[str, Any],\n document: Union[Mapping[str, Any], _Pipeline],\n operation: str,\n upsert: bool = False,\n multi: bool = False,\n write_concern: Optional[WriteConcern] = None,\n op_id: Optional[int] = None,\n ordered: bool = True,\n bypass_doc_val: Optional[bool] = False,\n collation: Optional[_CollationIn] = None,\n array_filters: Optional[Sequence[Mapping[str, Any]]] = None,\n hint: Optional[_IndexKeyHint] = None,\n session: Optional[ClientSession] = None,\n let: Optional[Mapping[str, Any]] = None,\n comment: Optional[Any] = None,\n ) -> Optional[Mapping[str, Any]]:\n \"\"\"Internal update / replace helper.\"\"\"\n\n def _update(\n session: Optional[ClientSession], conn: Connection, retryable_write: bool\n ) -> Optional[Mapping[str, Any]]:\n return self._update(\n conn,\n criteria,\n document,\n upsert=upsert,\n multi=multi,\n write_concern=write_concern,\n op_id=op_id,\n ordered=ordered,\n bypass_doc_val=bypass_doc_val,\n collation=collation,\n array_filters=array_filters,\n hint=hint,\n session=session,\n retryable_write=retryable_write,\n let=let,\n comment=comment,\n )\n\n return self.__database.client._retryable_write(\n (write_concern or self.write_concern).acknowledged and not multi,\n _update,\n session,\n operation,\n )", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n max_position_embeddings=1024,\n encoder_layers=12,\n encoder_ffn_dim=4096,\n encoder_attention_heads=16,\n decoder_layers=12,\n decoder_ffn_dim=4096,\n decoder_attention_heads=16,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=1024,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=0,\n scale_embedding=False,\n pad_token_id=0,\n eos_token_id=1,\n forced_eos_token_id=1,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=64,\n num_channels=3,\n kernel_size=3,\n stride=2,\n padding=1,\n patch_size=16,\n hidden_sizes=[16, 32, 48],\n num_attention_heads=[1, 2, 3],\n depths=[2, 3, 4],\n key_dim=[8, 8, 8],\n drop_path_rate=0,\n mlp_ratio=[2, 2, 2],\n attention_ratio=[2, 2, 2],\n initializer_range=0.02,\n is_training=True,\n use_labels=True,\n num_labels=2, # Check\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.hidden_sizes = hidden_sizes\n self.num_attention_heads = num_attention_heads\n self.depths = depths\n self.key_dim = key_dim\n self.drop_path_rate = drop_path_rate\n self.patch_size = patch_size\n self.attention_ratio = attention_ratio\n self.mlp_ratio = mlp_ratio\n self.initializer_range = initializer_range\n self.down_ops = [\n [\"Subsample\", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],\n [\"Subsample\", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],\n ]\n self.is_training = is_training\n self.use_labels = use_labels\n self.num_labels = num_labels\n self.initializer_range = initializer_range", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str,\n zerofill_results: bool = True,\n allow_metric_aggregates=True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n has_metrics: bool = True,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n groupby: Column | None = None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n equations, columns = categorize_columns(selected_columns)\n metrics_compatible = not equations\n\n def run_metrics_query(inner_params: SnubaParams):\n with sentry_sdk.start_span(op=\"mep\", name=\"TimeseriesMetricQueryBuilder\"):\n metrics_query = TimeseriesMetricQueryBuilder(\n params={},\n interval=rollup,\n snuba_params=inner_params,\n dataset=Dataset.PerformanceMetrics,\n query=query,\n selected_columns=columns,\n groupby=groupby,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n allow_metric_aggregates=allow_metric_aggregates,\n use_metrics_layer=use_metrics_layer,\n on_demand_metrics_enabled=on_demand_metrics_enabled,\n on_demand_metrics_type=on_demand_metrics_type,\n ),\n )\n metrics_referrer = referrer + \".metrics-enhanced\"\n result = metrics_query.run_query(referrer=metrics_referrer, query_source=query_source)\n with sentry_sdk.start_span(op=\"mep\", name=\"query.transform_results\"):\n result = metrics_query.process_results(result)\n result[\"data\"] = (\n discover.zerofill(\n result[\"data\"],\n inner_params.start_date,\n inner_params.end_date,\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else result[\"data\"]\n )\n sentry_sdk.set_tag(\"performance.dataset\", \"metrics\")\n result[\"meta\"][\"isMetricsData\"] = True\n sentry_sdk.set_tag(\"on_demand.is_extracted\", metrics_query.use_on_demand)\n result[\"meta\"][\"isMetricsExtractedData\"] = metrics_query.use_on_demand\n\n return {\n \"data\": result[\"data\"],\n \"isMetricsData\": True,\n \"isMetricsExtractedData\": metrics_query.use_on_demand,\n \"meta\": result[\"meta\"],\n }\n\n if metrics_compatible:\n # We could run these two queries in a batch but this would require a big refactor in the `get_snql_query` method\n # of the TimeseriesMetricQueryBuilder. In case this becomes a performance bottleneck, we should invest more\n # time into properly performing batching.\n #\n # In case we want to support multiple aggregate comparisons, we can just remove the condition below and rework\n # the implementation of the `comparisonCount` field.\n result = run_metrics_query(inner_params=snuba_params)\n if comparison_delta:\n comparison_params = snuba_params.copy()\n assert comparison_params.start is not None, \"start is required\"\n assert comparison_params.end is not None, \"end is required\"\n comparison_params.start -= comparison_delta\n comparison_params.end -= comparison_delta\n result_to_compare = run_metrics_query(inner_params=comparison_params)\n\n aliased_columns = [\n get_function_alias(selected_column) for selected_column in selected_columns\n ]\n if len(aliased_columns) != 1:\n raise IncompatibleMetricsQuery(\n \"The comparison query for metrics supports only one aggregate.\"\n )\n\n merged_data = []\n for data, data_to_compare in zip(result[\"data\"], result_to_compare[\"data\"]):\n merged_item = {\"time\": data[\"time\"]}\n\n for aliased_column in aliased_columns:\n # We only add data in the dictionary in case it's not `None`, since the serializer,\n # will convert all missing dictionary values to 0.\n if (column := data.get(aliased_column)) is not None:\n # We get from the main timeseries the actual result.\n merged_item[aliased_column] = column\n\n # It can be that we have the data in the comparison, in that case want to show it.\n if (column := data_to_compare.get(aliased_column)) is not None:\n # TODO: this implementation was copied over from discover to reduce the refactor size but it\n # would be better to prefix the comparisons with like `comparison_[alias]` and convert them\n # in the serializer.\n merged_item[\"comparisonCount\"] = column\n\n merged_data.append(merged_item)\n\n result[\"data\"] = merged_data\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"isMetricsData\": True,\n \"meta\": result[\"meta\"],\n },\n # We keep the params passed in the function as the time interval.\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n\n # In case the query was not compatible with metrics we return empty data.\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, [\"time\"]\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@pytest.fixture(scope=\"function\")\ndef taxprofiler_context(\n cg_context: CGConfig,\n helpers: StoreHelpers,\n trailblazer_api: MockTB,\n hermes_api: HermesApi,\n nf_analysis_housekeeper: HousekeeperAPI,\n cg_dir: Path,\n taxprofiler_case_id: str,\n sample_id: str,\n father_sample_id: str,\n sample_name: str,\n another_sample_name: str,\n no_sample_case_id: str,\n total_sequenced_reads_pass: int,\n metagenomics_application_tag: str,\n case_id_not_enough_reads: str,\n sample_id_not_enough_reads: str,\n total_sequenced_reads_not_pass: int,\n) -> CGConfig:\n \"\"\"Context to use in cli.\"\"\"\n cg_context.housekeeper_api_ = nf_analysis_housekeeper\n cg_context.trailblazer_api_ = trailblazer_api\n cg_context.meta_apis[\"analysis_api\"] = TaxprofilerAnalysisAPI(config=cg_context)\n status_db: Store = cg_context.status_db\n\n # NB: the order in which the cases are added matters for the tests of store_available\n\n # Create case with no associate samples\n helpers.add_case(status_db, internal_id=no_sample_case_id, name=no_sample_case_id)\n\n # Create case with associated samples\n taxprofiler_case: Case = helpers.add_case(\n store=status_db,\n internal_id=taxprofiler_case_id,\n name=taxprofiler_case_id,\n data_analysis=Workflow.TAXPROFILER,\n )\n\n taxprofiler_sample: Sample = helpers.add_sample(\n status_db,\n application_tag=\"multiqc\",\n internal_id=sample_id,\n reads=total_sequenced_reads_pass,\n name=sample_name,\n last_sequenced_at=datetime.now(),\n )\n\n taxprofiler_another_sample: Sample = helpers.add_sample(\n status_db,\n application_tag=\"multiqc\",\n internal_id=father_sample_id,\n last_sequenced_at=datetime.now(),\n name=another_sample_name,\n reads=total_sequenced_reads_pass,\n )\n\n helpers.add_relationship(\n status_db,\n case=taxprofiler_case,\n sample=taxprofiler_sample,\n )\n\n helpers.add_relationship(\n status_db,\n case=taxprofiler_case,\n sample=taxprofiler_another_sample,\n )\n\n # Create case without enough reads\n case_not_enough_reads: Case = helpers.add_case(\n store=status_db,\n internal_id=case_id_not_enough_reads,\n name=case_id_not_enough_reads,\n data_analysis=Workflow.TAXPROFILER,\n )\n\n sample_not_enough_reads: Sample = helpers.add_sample(\n status_db,\n application_tag=metagenomics_application_tag,\n internal_id=sample_id_not_enough_reads,\n reads=total_sequenced_reads_not_pass,\n last_sequenced_at=datetime.now(),\n )\n\n helpers.add_relationship(status_db, case=case_not_enough_reads, sample=sample_not_enough_reads)\n\n return cg_context", "smellKey": "S107", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "@pytest.mark.parametrize(\n 'ready, type_str, seed, platform_name, platform_arch, defconfig, harness,' \\\n ' expect_duts, expect_parse_generated, expect_seed,' \\\n ' expect_extra_test_args, expect_pytest, expect_handle',\n TESTDATA_14,\n ids=['pytest full', 'not pytest minimal', 'not ready']\n)\ndef test_projectbuilder_run(\n mocked_jobserver,\n ready,\n type_str,\n seed,\n platform_name,\n platform_arch,\n defconfig,\n harness,\n expect_duts,\n expect_parse_generated,\n expect_seed,\n expect_extra_test_args,\n expect_pytest,\n expect_handle\n):\n pytest_mock = mock.Mock(spec=Pytest)\n harness_mock = mock.Mock()\n\n def mock_harness(name):\n if name == 'Pytest':\n return pytest_mock\n else:\n return harness_mock\n\n instance_mock = mock.Mock()\n instance_mock.handler.get_test_timeout = mock.Mock(return_value=60)\n instance_mock.handler.seed = 123\n instance_mock.handler.ready = ready\n instance_mock.handler.type_str = type_str\n instance_mock.handler.duts = [mock.Mock(name='dummy dut')]\n instance_mock.platform.name = platform_name\n instance_mock.platform.arch = platform_arch\n instance_mock.testsuite.harness = harness\n env_mock = mock.Mock()\n\n pb = ProjectBuilder(instance_mock, env_mock, mocked_jobserver)\n pb.options.extra_test_args = ['dummy_arg1', 'dummy_arg2']\n pb.duts = ['another dut']\n pb.options.seed = seed\n pb.defconfig = defconfig\n pb.parse_generated = mock.Mock()\n\n with mock.patch('twisterlib.runner.HarnessImporter.get_harness',\n mock_harness):\n pb.run()\n\n if expect_duts:\n assert pb.instance.handler.duts == ['another dut']\n\n if expect_parse_generated:\n pb.parse_generated.assert_called_once()\n\n if expect_seed:\n assert pb.instance.handler.seed == seed\n\n if expect_extra_test_args:\n assert pb.instance.handler.extra_test_args == ['dummy_arg1',\n 'dummy_arg2']\n\n if expect_pytest:\n pytest_mock.pytest_run.assert_called_once_with(60)\n\n if expect_handle:\n pb.instance.handler.handle.assert_called_once_with(harness_mock)", "smellKey": "S107", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def _target_batch_encode_plus(\n self,\n answer: List[str],\n add_special_tokens: bool = True,\n padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,\n truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n batch_outputs = {}\n for text in answer:\n if self.do_lower_case:\n text = text.lower()\n\n tokens = self.tokenize(text)\n outputs = self.prepare_for_model(\n ids=self.convert_tokens_to_ids(tokens),\n add_special_tokens=add_special_tokens,\n padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards\n truncation=truncation_strategy.value,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=None, # we pad in batch afterwards\n return_attention_mask=False, # we pad in batch afterwards\n return_token_type_ids=return_token_type_ids,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_length=return_length,\n return_tensors=None, # We convert the whole batch to tensors at the end\n prepend_batch_axis=False,\n verbose=verbose,\n )\n\n for key, value in outputs.items():\n if key not in batch_outputs:\n batch_outputs[key] = []\n batch_outputs[key].append(value)\n\n batch_outputs = self.pad(\n batch_outputs,\n padding=padding_strategy.value,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n return_attention_mask=return_attention_mask,\n )\n\n batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)\n\n return BatchEncoding(batch_outputs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n context_length: int = 32,\n patch_length: int = 8,\n num_input_channels: int = 3,\n patch_stride: int = 8,\n # d_model: int = 128,\n hidden_size: int = 8,\n # num_layers: int = 8,\n num_hidden_layers: int = 2,\n expansion_factor: int = 2,\n dropout: float = 0.5,\n mode: str = \"common_channel\",\n gated_attn: bool = True,\n norm_mlp=\"LayerNorm\",\n swin_hier: int = 0,\n # masking related\n mask_type: str = \"forecast\",\n random_mask_ratio=0.5,\n mask_patches: list = [2, 3],\n forecast_mask_ratios: list = [1, 1],\n mask_value=0,\n masked_loss: bool = False,\n mask_mode: str = \"mask_before_encoder\",\n channel_consistent_masking: bool = True,\n scaling: Optional[Union[str, bool]] = \"std\",\n # Head related\n head_dropout: float = 0.2,\n # forecast related\n prediction_length: int = 16,\n out_channels: int = None,\n # Classification/regression related\n # num_labels: int = 3,\n num_targets: int = 3,\n output_range: list = None,\n head_aggregation: str = None,\n # Trainer related\n batch_size=13,\n is_training=True,\n seed_number=42,\n post_init=True,\n num_parallel_samples=4,\n ):\n self.num_input_channels = num_input_channels\n self.context_length = context_length\n self.patch_length = patch_length\n self.patch_stride = patch_stride\n # self.d_model = d_model\n self.hidden_size = hidden_size\n self.expansion_factor = expansion_factor\n # self.num_layers = num_layers\n self.num_hidden_layers = num_hidden_layers\n self.dropout = dropout\n self.mode = mode\n self.gated_attn = gated_attn\n self.norm_mlp = norm_mlp\n self.swin_hier = swin_hier\n self.scaling = scaling\n self.head_dropout = head_dropout\n # masking related\n self.mask_type = mask_type\n self.random_mask_ratio = random_mask_ratio\n self.mask_patches = mask_patches\n self.forecast_mask_ratios = forecast_mask_ratios\n self.mask_value = mask_value\n self.channel_consistent_masking = channel_consistent_masking\n self.mask_mode = mask_mode\n self.masked_loss = masked_loss\n # patching related\n self.patch_last = True\n # forecast related\n self.prediction_length = prediction_length\n self.out_channels = out_channels\n # classification/regression related\n # self.num_labels = num_labels\n self.num_targets = num_targets\n self.output_range = output_range\n self.head_aggregation = head_aggregation\n # Trainer related\n self.batch_size = batch_size\n self.is_training = is_training\n self.seed_number = seed_number\n self.post_init = post_init\n self.num_parallel_samples = num_parallel_samples", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n tokenizer_file=None,\n src_lang=None,\n tgt_lang=None,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n additional_special_tokens=None,\n legacy_behaviour=False,\n **kwargs,\n ):\n if additional_special_tokens is None:\n additional_special_tokens = FAIRSEQ_LANGUAGE_CODES\n bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token\n pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token\n eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token\n unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = (\n AddedToken(mask_token, normalized=True, lstrip=True, special=True)\n if isinstance(mask_token, str)\n else mask_token\n )\n\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n self.legacy_behaviour = legacy_behaviour\n\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.Load(str(vocab_file))\n self.vocab_file = vocab_file\n # Original fairseq vocab and spm vocab must be \"aligned\":\n # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ----\n # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '\u2581n' | '\u2581m' | '\u2581t' | '\u2581k' | '\u2581a'\n # spm | '<unk>' | '<s>' | '</s>' | 'an' | '\u2581n' | '\u2581m' | '\u2581t' | '\u2581k' | '\u2581a' | '\u2581s'\n\n # unk token needs to be in the vocab with correct index\n self._added_tokens_decoder = {0: bos_token, 1: pad_token, 2: eos_token, 3: unk_token}\n # The first \"real\" token \",\" has position 4 in the original fairseq vocab and position 3 in the spm vocab\n self.fairseq_offset = 1\n self.sp_model_size = len(self.sp_model)\n\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n tokenizer_file=tokenizer_file,\n src_lang=src_lang,\n tgt_lang=tgt_lang,\n additional_special_tokens=additional_special_tokens,\n sp_model_kwargs=self.sp_model_kwargs,\n legacy_behaviour=legacy_behaviour,\n **kwargs,\n )\n\n self._src_lang = src_lang if src_lang is not None else \"eng_Latn\"\n self.cur_lang_code_id = self.convert_tokens_to_ids(self._src_lang)\n self.tgt_lang = tgt_lang\n self.set_src_lang_special_tokens(self._src_lang)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_database_instances_v3_get_without_preload_content(\n self,\n chart_release: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n default_database: Annotated[Optional[StrictStr], Field(description=\"When creating, defaults to the chart name\")] = None,\n google_project: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google'\")] = None,\n id: Optional[StrictInt] = None,\n instance_name: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google' or 'azure'\")] = None,\n platform: Annotated[Optional[StrictStr], Field(description=\"'google', 'azure', or default 'kubernetes'\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many DatabaseInstances are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned DatabaseInstances (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> RESTResponseType:\n \"\"\"List DatabaseInstances matching a filter\n\n List DatabaseInstances matching a filter.\n\n :param chart_release: Required when creating\n :type chart_release: str\n :param created_at:\n :type created_at: datetime\n :param default_database: When creating, defaults to the chart name\n :type default_database: str\n :param google_project: Required if platform is 'google'\n :type google_project: str\n :param id:\n :type id: int\n :param instance_name: Required if platform is 'google' or 'azure'\n :type instance_name: str\n :param platform: 'google', 'azure', or default 'kubernetes'\n :type platform: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many DatabaseInstances are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned DatabaseInstances (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_database_instances_v3_get_serialize(\n chart_release=chart_release,\n created_at=created_at,\n default_database=default_database,\n google_project=google_project,\n id=id,\n instance_name=instance_name,\n platform=platform,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockDatabaseInstanceV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n return response_data.response", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@validate_call\n def api_deploy_hooks_github_actions_v3_get(\n self,\n created_at: Optional[datetime] = None,\n github_actions_default_ref: Optional[StrictStr] = None,\n github_actions_owner: Optional[StrictStr] = None,\n github_actions_ref_behavior: Annotated[Optional[StrictStr], Field(description=\"This field determines what git ref the workflow will be run on. The default of always-use-default-ref always uses the default ref; use-app-version-as-ref will use the app version (when available) as the ref, useful when versions are always commit hashes or tags; use-app-version-commit-as-ref will use the app version's commit (when available) as the ref, useful when the repo is configured to fully report app versions to Sherlock.\")] = None,\n github_actions_repo: Optional[StrictStr] = None,\n github_actions_workflow_path: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n on_chart_release: Optional[StrictStr] = None,\n on_environment: Optional[StrictStr] = None,\n on_failure: Optional[StrictBool] = None,\n on_success: Optional[StrictBool] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many GithubActionsDeployHooks are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned GithubActionsDeployHooks (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockGithubActionsDeployHookV3]:\n \"\"\"List GithubActionsDeployHooks matching a filter\n\n List GithubActionsDeployHooks matching a filter.\n\n :param created_at:\n :type created_at: datetime\n :param github_actions_default_ref:\n :type github_actions_default_ref: str\n :param github_actions_owner:\n :type github_actions_owner: str\n :param github_actions_ref_behavior: This field determines what git ref the workflow will be run on. The default of always-use-default-ref always uses the default ref; use-app-version-as-ref will use the app version (when available) as the ref, useful when versions are always commit hashes or tags; use-app-version-commit-as-ref will use the app version's commit (when available) as the ref, useful when the repo is configured to fully report app versions to Sherlock.\n :type github_actions_ref_behavior: str\n :param github_actions_repo:\n :type github_actions_repo: str\n :param github_actions_workflow_path:\n :type github_actions_workflow_path: str\n :param id:\n :type id: int\n :param on_chart_release:\n :type on_chart_release: str\n :param on_environment:\n :type on_environment: str\n :param on_failure:\n :type on_failure: bool\n :param on_success:\n :type on_success: bool\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many GithubActionsDeployHooks are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned GithubActionsDeployHooks (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_deploy_hooks_github_actions_v3_get_serialize(\n created_at=created_at,\n github_actions_default_ref=github_actions_default_ref,\n github_actions_owner=github_actions_owner,\n github_actions_ref_behavior=github_actions_ref_behavior,\n github_actions_repo=github_actions_repo,\n github_actions_workflow_path=github_actions_workflow_path,\n id=id,\n on_chart_release=on_chart_release,\n on_environment=on_environment,\n on_failure=on_failure,\n on_success=on_success,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockGithubActionsDeployHookV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(self, session, text, type=TYPE_YESNO, timeout=-1, list=None, default=True, closeOnAnyKey=False, enableInput=True, msgBoxID=None, typeIcon=None, timeoutDefault=None, windowTitle=None, skinName=None, close_on_any_key=False, enable_input=True, timeout_default=None, title=None, picon=None, skin_name=None, simple=None):\n\t\tScreen.__init__(self, session, mandatoryWidgets=[\"icon\", \"list\", \"text\"], enableHelp=True)\n\t\tself.text = text\n\t\tself[\"text\"] = Label(text)\n\t\tself.type = type\n\t\tif type == self.TYPE_YESNO:\n\t\t\tself.list = [(_(\"Yes\"), True), (_(\"No\"), False)] if list is None else list\n\t\t\tself[\"list\"] = MenuList(self.list)\n\t\t\tif isinstance(default, bool):\n\t\t\t\tself.startIndex = 0 if default else 1\n\t\t\telif isinstance(default, int):\n\t\t\t\tself.startIndex = default\n\t\t\telse:\n\t\t\t\tprint(f\"[MessageBox] Error: The context of the default ({default}) can't be determined!\")\n\t\telse:\n\t\t\tself[\"list\"] = MenuList([])\n\t\t\tself[\"list\"].hide()\n\t\t\tself.list = None\n\t\tself.timeout = timeout\n\t\tif close_on_any_key is True: # Process legacy close_on_any_key argument.\n\t\t\tcloseOnAnyKey = True\n\t\tself.closeOnAnyKey = closeOnAnyKey\n\t\tif enable_input is False: # Process legacy enable_input argument.\n\t\t\tenableInput = False\n\t\tif enableInput:\n\t\t\tself.createActionMap(0)\n\t\tself.msgBoxID = msgBoxID\n\t\tif picon is not None: # Process legacy picon argument.\n\t\t\ttypeIcon = picon\n\t\tif typeIcon is None:\n\t\t\ttypeIcon = type\n\t\tself.typeIcon = typeIcon\n\t\tself.picon = (typeIcon != self.TYPE_NOICON) # Legacy picon argument to support old skins.\n\t\tif typeIcon:\n\t\t\tself[\"icon\"] = MultiPixmap()\n\t\tif timeout_default is not None: # Process legacy timeout_default argument.\n\t\t\ttimeoutDefault = timeout_default\n\t\tself.timeoutDefault = timeoutDefault\n\t\tif title is not None: # Process legacy title argument.\n\t\t\twindowTitle = title\n\t\tself.windowTitle = windowTitle or self.TYPE_PREFIX.get(type, _(\"Message\"))\n\t\tself.baseTitle = self.windowTitle\n\t\tself.activeTitle = self.windowTitle\n\t\tif skin_name is not None: # Process legacy skin_name argument.\n\t\t\tskinName = skin_name\n\t\tself.skinName = [\"MessageBox\"]\n\t\tif simple: # Process legacy simple argument, use skinName instead.\n\t\t\tself.skinName.insert(0, \"MessageBoxSimple\")\n\t\tif skinName:\n\t\t\tif isinstance(skinName, str):\n\t\t\t\tself.skinName.insert(0, skinName)\n\t\t\telse:\n\t\t\t\tself.skinName = skinName + self.skinName\n\t\tself.timer = eTimer()\n\t\tself.timer.callback.append(self.processTimer)\n\t\tself.onLayoutFinish.append(self.layoutFinished)", "smellKey": "S107", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def __init__(\n self,\n *,\n transaction_id: Optional[str] = None,\n _type: Optional[str] = None,\n comment: Optional[str] = None,\n signature_request: Optional[list] = None,\n signature_response: Optional[list] = None,\n timing: Optional[dict] = None,\n formats: Optional[list] = None,\n messages_attach: Optional[list] = None,\n thread_id: Optional[str] = None,\n connection_id: Optional[str] = None,\n state: Optional[str] = None,\n endorser_write_txn: Optional[bool] = None,\n meta_data: Optional[dict] = None,\n **kwargs,\n ):\n \"\"\"Initialize a new TransactionRecord.\"\"\"\n\n super().__init__(transaction_id, state or self.STATE_INIT, **kwargs)\n self._type = _type\n self.comment = comment\n self.signature_request = signature_request or []\n self.signature_response = signature_response or []\n self.timing = timing or {}\n self.formats = formats or []\n self.messages_attach = messages_attach or []\n self.thread_id = thread_id\n self.connection_id = connection_id\n self.endorser_write_txn = endorser_write_txn\n self.meta_data = meta_data or {\"context\": {}, \"processing\": {}}", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n attention_window=4,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.attention_window = attention_window\n\n # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size\n # [num_attention_heads, encoder_seq_length, encoder_key_length], but LongformerSelfAttention\n # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]\n # because its local attention only attends to `self.attention_window + 1` locations\n # (assuming no token with global attention, otherwise the last dimension of attentions\n # is x + self.attention_window + 1, where x is the number of tokens with global attention)\n self.key_length = self.attention_window + 2", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def run_tests(\n self,\n tests: Union[str, List[str]],\n parse_all: bool = True,\n comment: OptionalType[Union[\"ParserElement\", str]] = \"#\",\n full_dump: bool = True,\n print_results: bool = True,\n failure_tests: bool = False,\n post_parse: Callable[[str, ParseResults], str] = None,\n file: OptionalType[TextIO] = None,\n with_line_numbers: bool = False,\n *,\n parseAll: bool = True,\n fullDump: bool = True,\n printResults: bool = True,\n failureTests: bool = False,\n postParse: Callable[[str, ParseResults], str] = None,\n ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:\n \"\"\"\n Execute the parse expression on a series of test strings, showing each\n test, the parsed results or where the parse failed. Quick and easy way to\n run a parse expression against a list of sample strings.\n\n Parameters:\n - ``tests`` - a list of separate test strings, or a multiline string of test strings\n - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test\n string; pass None to disable comment filtering\n - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;\n if False, only dump nested list\n - ``print_results`` - (default= ``True``) prints test output to stdout\n - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing\n - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as\n `fn(test_string, parse_results)` and returns a string to be added to the test output\n - ``file`` - (default= ``None``) optional file-like object to which test output will be written;\n if None, will default to ``sys.stdout``\n - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers\n\n Returns: a (success, results) tuple, where success indicates that all tests succeeded\n (or failed if ``failure_tests`` is True), and the results contain a list of lines of each\n test's output\n\n Example::\n\n number_expr = pyparsing_common.number.copy()\n\n result = number_expr.run_tests('''\n # unsigned integer\n 100\n # negative integer\n -100\n # float with scientific notation\n 6.02e23\n # integer with scientific notation\n 1e-12\n ''')\n print(\"Success\" if result[0] else \"Failed!\")\n\n result = number_expr.run_tests('''\n # stray character\n 100Z\n # missing leading digit before '.'\n -.100\n # too many '.'\n 3.14.159\n ''', failure_tests=True)\n print(\"Success\" if result[0] else \"Failed!\")\n\n prints::\n\n # unsigned integer\n 100\n [100]\n\n # negative integer\n -100\n [-100]\n\n # float with scientific notation\n 6.02e23\n [6.02e+23]\n\n # integer with scientific notation\n 1e-12\n [1e-12]\n\n Success\n\n # stray character\n 100Z\n ^\n FAIL: Expected end of text (at char 3), (line:1, col:4)\n\n # missing leading digit before '.'\n -.100\n ^\n FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)\n\n # too many '.'\n 3.14.159\n ^\n FAIL: Expected end of text (at char 4), (line:1, col:5)\n\n Success\n\n Each test string must be on a single line. If you want to test a string that spans multiple\n lines, create a test like this::\n\n expr.run_tests(r\"this is a test\\\\n of strings that spans \\\\n 3 lines\")\n\n (Note that this is a raw string literal, you must include the leading ``'r'``.)\n \"\"\"\n from .testing import pyparsing_test\n\n parseAll = parseAll and parse_all\n fullDump = fullDump and full_dump\n printResults = printResults and print_results\n failureTests = failureTests or failure_tests\n postParse = postParse or post_parse\n if isinstance(tests, str_type):\n line_strip = type(tests).strip\n tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]\n if isinstance(comment, str_type):\n comment = Literal(comment)\n if file is None:\n file = sys.stdout\n print_ = file.write\n\n result: Union[ParseResults, Exception]\n allResults = []\n comments = []\n success = True\n NL = Literal(r\"\\n\").add_parse_action(replace_with(\"\\n\")).ignore(quoted_string)\n BOM = \"\\ufeff\"\n for t in tests:\n if comment is not None and comment.matches(t, False) or comments and not t:\n comments.append(\n pyparsing_test.with_line_numbers(t) if with_line_numbers else t\n )\n continue\n if not t:\n continue\n out = [\n \"\\n\" + \"\\n\".join(comments) if comments else \"\",\n pyparsing_test.with_line_numbers(t) if with_line_numbers else t,\n ]\n comments = []\n try:\n # convert newline marks to actual newlines, and strip leading BOM if present\n t = NL.transform_string(t.lstrip(BOM))\n result = self.parse_string(t, parse_all=parseAll)\n except ParseBaseException as pe:\n fatal = \"(FATAL)\" if isinstance(pe, ParseFatalException) else \"\"\n out.append(pe.explain())\n out.append(\"FAIL: \" + str(pe))\n if ParserElement.verbose_stacktrace:\n out.extend(traceback.format_tb(pe.__traceback__))\n success = success and failureTests\n result = pe\n except Exception as exc:\n out.append(\"FAIL-EXCEPTION: {}: {}\".format(type(exc).__name__, exc))\n if ParserElement.verbose_stacktrace:\n out.extend(traceback.format_tb(exc.__traceback__))\n success = success and failureTests\n result = exc\n else:\n success = success and not failureTests\n if postParse is not None:\n try:\n pp_value = postParse(t, result)\n if pp_value is not None:\n if isinstance(pp_value, ParseResults):\n out.append(pp_value.dump())\n else:\n out.append(str(pp_value))\n else:\n out.append(result.dump())\n except Exception as e:\n out.append(result.dump(full=fullDump))\n out.append(\n \"{} failed: {}: {}\".format(\n postParse.__name__, type(e).__name__, e\n )\n )\n else:\n out.append(result.dump(full=fullDump))\n out.append(\"\")\n\n if printResults:\n print_(\"\\n\".join(out))\n\n allResults.append((t, result))\n\n return success, allResults", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n hidden_size: int = 768,\n num_hidden_layers: int = 12,\n num_attention_heads: int = 12,\n intermediate_size: int = 3072,\n hidden_act: int = \"gelu\",\n hidden_dropout_prob: float = 0.0,\n attention_probs_dropout_prob: float = 0.0,\n initializer_range: float = 0.02,\n layer_norm_eps: float = 1e-12,\n image_size: int = 224,\n patch_size: int = 16,\n num_channels: int = 3,\n qkv_bias: bool = True,\n mask_token: bool = True,\n vocab_size: int = 8192,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.mask_token = mask_token\n self.vocab_size = vocab_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n block_sizes=[4, 4, 4],\n block_repeats=None,\n num_decoder_layers=2,\n d_model=768,\n n_head=12,\n d_head=64,\n d_inner=3072,\n hidden_act=\"gelu_new\",\n hidden_dropout=0.1,\n attention_dropout=0.1,\n activation_dropout=0.0,\n initializer_range=0.1,\n initializer_std=None,\n layer_norm_eps=1e-9,\n pooling_type=\"mean\",\n attention_type=\"relative_shift\",\n separate_cls=True,\n truncate_seq=True,\n pool_q_only=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.block_sizes = block_sizes\n self.block_repeats = [1] * len(block_sizes) if block_repeats is None else block_repeats\n assert len(block_sizes) == len(\n self.block_repeats\n ), \"`block_sizes` and `block_repeats` should have the same length.\"\n self.num_decoder_layers = num_decoder_layers\n self.d_model = d_model\n self.n_head = n_head\n self.d_head = d_head\n self.d_inner = d_inner\n self.hidden_act = hidden_act\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.initializer_range = initializer_range\n self.initializer_std = initializer_std\n self.layer_norm_eps = layer_norm_eps\n assert pooling_type in [\n \"mean\",\n \"max\",\n ], f\"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported.\"\n self.pooling_type = pooling_type\n assert attention_type in [\n \"relative_shift\",\n \"factorized\",\n ], f\"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported.\"\n self.attention_type = attention_type\n self.separate_cls = separate_cls\n self.truncate_seq = truncate_seq\n self.pool_q_only = pool_q_only\n\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def create_and_check_for_entity_pair_classification(\n self,\n config,\n input_ids,\n attention_mask,\n token_type_ids,\n entity_ids,\n entity_attention_mask,\n entity_token_type_ids,\n entity_position_ids,\n sequence_labels,\n token_labels,\n choice_labels,\n entity_labels,\n entity_classification_labels,\n entity_pair_classification_labels,\n entity_span_classification_labels,\n ):\n config.num_labels = self.num_entity_pair_classification_labels\n model = LukeForEntityClassification(config)\n model.to(torch_device)\n model.eval()\n\n result = model(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n labels=entity_pair_classification_labels,\n )\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_pair_classification_labels))", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n position_embedding_type=\"absolute\",\n quant_mode=False,\n force_dequant=\"none\",\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.quant_mode = quant_mode\n self.force_dequant = force_dequant", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=BaseModelOutputWithPoolingAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n task_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if self.config.is_decoder:\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n else:\n use_cache = False\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n batch_size, seq_length = input_shape\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n # past_key_values_length\n past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0\n\n if attention_mask is None:\n attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)\n\n if token_type_ids is None:\n if hasattr(self.embeddings, \"token_type_ids\"):\n buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]\n buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)\n token_type_ids = buffered_token_type_ids_expanded\n else:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)\n\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)\n\n # If a 2D or 3D attention mask is provided for the cross-attention\n # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]\n if self.config.is_decoder and encoder_hidden_states is not None:\n encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)\n encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)\n else:\n encoder_extended_attention_mask = None\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n embedding_output = self.embeddings(\n input_ids=input_ids,\n position_ids=position_ids,\n token_type_ids=token_type_ids,\n task_type_ids=task_type_ids,\n inputs_embeds=inputs_embeds,\n past_key_values_length=past_key_values_length,\n )\n encoder_outputs = self.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_extended_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output) if self.pooler is not None else None\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return BaseModelOutputWithPoolingAndCrossAttentions(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n past_key_values=encoder_outputs.past_key_values,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n cross_attentions=encoder_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n patch_size=4,\n num_channels=3,\n embed_dim=96,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n window_size=7,\n pretrained_window_sizes=[0, 0, 0, 0],\n mlp_ratio=4.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n use_absolute_embeddings=False,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n encoder_stride=32,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_layers = len(depths)\n self.num_heads = num_heads\n self.window_size = window_size\n self.pretrained_window_sizes = pretrained_window_sizes\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.use_absolute_embeddings = use_absolute_embeddings\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.encoder_stride = encoder_stride\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )\n # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel\n # this indicates the channel dimension after the last stage of the model\n self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n do_resize: bool = True,\n size: Dict[str, int] = None,\n size_divisor: int = 32,\n do_rescale: bool = True,\n rescale_factor: Union[int, float] = 1 / 255,\n do_normalize: bool = True,\n do_center_crop: bool = True,\n image_mean: Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073],\n image_std: Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711],\n do_pad: bool = True,\n batch_size=7,\n min_resolution=30,\n max_resolution=400,\n num_channels=3,\n ):\n super().__init__()\n self.parent = parent\n self.do_resize = do_resize\n self.size = size if size is not None else {\"shortest_edge\": 288}\n self.size_divisor = size_divisor\n self.do_rescale = do_rescale\n self.rescale_factor = rescale_factor\n self.do_normalize = do_normalize\n self.do_center_crop = do_center_crop\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_pad = do_pad\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n encoder_seq_length=1024, # speech is longer\n decoder_seq_length=1024,\n is_training=False,\n hidden_size=24,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=4,\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n vocab_size=81,\n num_mel_bins=20,\n reduction_factor=2,\n speech_decoder_postnet_layers=2,\n speech_decoder_postnet_units=32,\n speech_decoder_prenet_units=32,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.vocab_size = vocab_size\n self.num_mel_bins = num_mel_bins\n self.reduction_factor = reduction_factor\n self.speech_decoder_postnet_layers = speech_decoder_postnet_layers\n self.speech_decoder_postnet_units = speech_decoder_postnet_units\n self.speech_decoder_prenet_units = speech_decoder_prenet_units", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=384,\n vocab_size=78,\n num_mel_bins=80,\n encoder_num_attention_heads=2,\n encoder_layers=4,\n encoder_linear_units=1536,\n decoder_layers=4,\n decoder_num_attention_heads=2,\n decoder_linear_units=1536,\n speech_decoder_postnet_layers=5,\n speech_decoder_postnet_units=256,\n speech_decoder_postnet_kernel=5,\n positionwise_conv_kernel_size=3,\n encoder_normalize_before=False,\n decoder_normalize_before=False,\n encoder_concat_after=False,\n decoder_concat_after=False,\n reduction_factor=1,\n speaking_speed=1.0,\n use_macaron_style_in_conformer=True,\n use_cnn_in_conformer=True,\n encoder_kernel_size=7,\n decoder_kernel_size=31,\n duration_predictor_layers=2,\n duration_predictor_channels=256,\n duration_predictor_kernel_size=3,\n energy_predictor_layers=2,\n energy_predictor_channels=256,\n energy_predictor_kernel_size=3,\n energy_predictor_dropout=0.5,\n energy_embed_kernel_size=1,\n energy_embed_dropout=0.0,\n stop_gradient_from_energy_predictor=False,\n pitch_predictor_layers=5,\n pitch_predictor_channels=256,\n pitch_predictor_kernel_size=5,\n pitch_predictor_dropout=0.5,\n pitch_embed_kernel_size=1,\n pitch_embed_dropout=0.0,\n stop_gradient_from_pitch_predictor=True,\n encoder_dropout_rate=0.2,\n encoder_positional_dropout_rate=0.2,\n encoder_attention_dropout_rate=0.2,\n decoder_dropout_rate=0.2,\n decoder_positional_dropout_rate=0.2,\n decoder_attention_dropout_rate=0.2,\n duration_predictor_dropout_rate=0.2,\n speech_decoder_postnet_dropout=0.5,\n max_source_positions=5000,\n use_masking=True,\n use_weighted_masking=False,\n num_speakers=None,\n num_languages=None,\n speaker_embed_dim=None,\n is_encoder_decoder=True,\n **kwargs,\n ):\n if positionwise_conv_kernel_size % 2 == 0:\n raise ValueError(\n f\"positionwise_conv_kernel_size must be odd, but got {positionwise_conv_kernel_size} instead.\"\n )\n if encoder_kernel_size % 2 == 0:\n raise ValueError(f\"encoder_kernel_size must be odd, but got {encoder_kernel_size} instead.\")\n if decoder_kernel_size % 2 == 0:\n raise ValueError(f\"decoder_kernel_size must be odd, but got {decoder_kernel_size} instead.\")\n if duration_predictor_kernel_size % 2 == 0:\n raise ValueError(\n f\"duration_predictor_kernel_size must be odd, but got {duration_predictor_kernel_size} instead.\"\n )\n if energy_predictor_kernel_size % 2 == 0:\n raise ValueError(\n f\"energy_predictor_kernel_size must be odd, but got {energy_predictor_kernel_size} instead.\"\n )\n if energy_embed_kernel_size % 2 == 0:\n raise ValueError(f\"energy_embed_kernel_size must be odd, but got {energy_embed_kernel_size} instead.\")\n if pitch_predictor_kernel_size % 2 == 0:\n raise ValueError(\n f\"pitch_predictor_kernel_size must be odd, but got {pitch_predictor_kernel_size} instead.\"\n )\n if pitch_embed_kernel_size % 2 == 0:\n raise ValueError(f\"pitch_embed_kernel_size must be odd, but got {pitch_embed_kernel_size} instead.\")\n if hidden_size % encoder_num_attention_heads != 0:\n raise ValueError(\"The hidden_size must be evenly divisible by encoder_num_attention_heads.\")\n if hidden_size % decoder_num_attention_heads != 0:\n raise ValueError(\"The hidden_size must be evenly divisible by decoder_num_attention_heads.\")\n if use_masking and use_weighted_masking:\n raise ValueError(\"Either use_masking or use_weighted_masking can be True, but not both.\")\n\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.num_mel_bins = num_mel_bins\n self.encoder_config = {\n \"num_attention_heads\": encoder_num_attention_heads,\n \"layers\": encoder_layers,\n \"kernel_size\": encoder_kernel_size,\n \"attention_dropout_rate\": encoder_attention_dropout_rate,\n \"dropout_rate\": encoder_dropout_rate,\n \"positional_dropout_rate\": encoder_positional_dropout_rate,\n \"linear_units\": encoder_linear_units,\n \"normalize_before\": encoder_normalize_before,\n \"concat_after\": encoder_concat_after,\n }\n self.decoder_config = {\n \"num_attention_heads\": decoder_num_attention_heads,\n \"layers\": decoder_layers,\n \"kernel_size\": decoder_kernel_size,\n \"attention_dropout_rate\": decoder_attention_dropout_rate,\n \"dropout_rate\": decoder_dropout_rate,\n \"positional_dropout_rate\": decoder_positional_dropout_rate,\n \"linear_units\": decoder_linear_units,\n \"normalize_before\": decoder_normalize_before,\n \"concat_after\": decoder_concat_after,\n }\n self.encoder_num_attention_heads = encoder_num_attention_heads\n self.encoder_layers = encoder_layers\n self.duration_predictor_channels = duration_predictor_channels\n self.duration_predictor_kernel_size = duration_predictor_kernel_size\n self.duration_predictor_layers = duration_predictor_layers\n self.energy_embed_dropout = energy_embed_dropout\n self.energy_embed_kernel_size = energy_embed_kernel_size\n self.energy_predictor_channels = energy_predictor_channels\n self.energy_predictor_dropout = energy_predictor_dropout\n self.energy_predictor_kernel_size = energy_predictor_kernel_size\n self.energy_predictor_layers = energy_predictor_layers\n self.pitch_embed_dropout = pitch_embed_dropout\n self.pitch_embed_kernel_size = pitch_embed_kernel_size\n self.pitch_predictor_channels = pitch_predictor_channels\n self.pitch_predictor_dropout = pitch_predictor_dropout\n self.pitch_predictor_kernel_size = pitch_predictor_kernel_size\n self.pitch_predictor_layers = pitch_predictor_layers\n self.positionwise_conv_kernel_size = positionwise_conv_kernel_size\n self.speech_decoder_postnet_units = speech_decoder_postnet_units\n self.speech_decoder_postnet_dropout = speech_decoder_postnet_dropout\n self.speech_decoder_postnet_kernel = speech_decoder_postnet_kernel\n self.speech_decoder_postnet_layers = speech_decoder_postnet_layers\n self.reduction_factor = reduction_factor\n self.speaking_speed = speaking_speed\n self.stop_gradient_from_energy_predictor = stop_gradient_from_energy_predictor\n self.stop_gradient_from_pitch_predictor = stop_gradient_from_pitch_predictor\n self.max_source_positions = max_source_positions\n self.use_cnn_in_conformer = use_cnn_in_conformer\n self.use_macaron_style_in_conformer = use_macaron_style_in_conformer\n self.use_masking = use_masking\n self.use_weighted_masking = use_weighted_masking\n self.num_speakers = num_speakers\n self.num_languages = num_languages\n self.speaker_embed_dim = speaker_embed_dim\n self.duration_predictor_dropout_rate = duration_predictor_dropout_rate\n self.is_encoder_decoder = is_encoder_decoder\n\n super().__init__(\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n node_id: str,\n title: str,\n description: str,\n thumbnail_filename: Optional[str],\n thumbnail_bg_color: Optional[str],\n thumbnail_size_in_bytes: Optional[int],\n destination_node_ids: List[str],\n acquired_skill_ids: List[str],\n prerequisite_skill_ids: List[str],\n outline: str,\n outline_is_finalized: bool,\n exploration_id: Optional[str],\n status: Optional[str],\n planned_publication_date: Optional[datetime.datetime],\n last_modified: Optional[datetime.datetime],\n first_publication_date: Optional[datetime.datetime],\n unpublishing_reason: Optional[str]\n ) -> None:\n \"\"\"Initializes a StoryNode domain object.\n\n Args:\n node_id: str. The unique id for each node.\n title: str. The title of the story node.\n description: str. The description for the story node.\n thumbnail_filename: str|None. The thumbnail filename of the story\n node.\n thumbnail_bg_color: str|None. The thumbnail background color of\n the story node.\n thumbnail_size_in_bytes: int|None. The size of thumbnail in bytes.\n destination_node_ids: list(str). The list of destination node ids\n that this node points to in the story graph.\n acquired_skill_ids: list(str). The list of skill ids acquired by\n the user on completion of the node.\n prerequisite_skill_ids: list(str). The list of skill ids required\n before starting a node.\n outline: str. Free-form annotations that a lesson implementer\n can use to construct the exploration. It describes the basic\n theme or template of the story and is to be provided in html\n form.\n outline_is_finalized: bool. Whether the outline for the story\n node is finalized or not.\n exploration_id: str or None. The valid exploration id that fits the\n story node. It can be None initially, when the story creator\n has just created a story with the basic storyline (by providing\n outlines) without linking an exploration to any node.\n status: str. It is the publication status of the node.\n planned_publication_date: datetime.datetime | None. It is the\n expected publication date for a node.\n last_modified: datetime.datetime | None. The date time when a node\n was last modified.\n first_publication_date: datetime.datetime | None. The date when\n the node was first published.\n unpublishing_reason: str or None. The reason for unpublishing this\n node. It is None when the node is published.\n \"\"\"\n self.id = node_id\n self.title = title\n self.description = description\n self.thumbnail_filename = thumbnail_filename\n self.thumbnail_bg_color = thumbnail_bg_color\n self.thumbnail_size_in_bytes = thumbnail_size_in_bytes\n self.destination_node_ids = destination_node_ids\n self.acquired_skill_ids = acquired_skill_ids\n self.prerequisite_skill_ids = prerequisite_skill_ids\n self.outline = html_cleaner.clean(outline)\n self.outline_is_finalized = outline_is_finalized\n self.exploration_id = exploration_id\n self.status = status\n self.planned_publication_date = planned_publication_date\n self.last_modified = last_modified\n self.first_publication_date = first_publication_date\n self.unpublishing_reason = unpublishing_reason", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=2048,\n max_position_embeddings=2048,\n num_hidden_layers=24,\n ffn_dim=4096,\n num_attention_heads=16,\n layerdrop=0.0,\n use_cache=True,\n activation_function=\"gelu\",\n hidden_size=1024,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n initializer_factor=0.02,\n scale_embedding=False,\n num_codebooks=4,\n audio_channels=1,\n pad_token_id=2048,\n bos_token_id=2048,\n eos_token_id=None,\n tie_word_embeddings=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.ffn_dim = ffn_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.initializer_factor = initializer_factor\n self.layerdrop = layerdrop\n self.use_cache = use_cache\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n self.num_codebooks = num_codebooks\n\n if audio_channels not in [1, 2]:\n raise ValueError(f\"Expected 1 (mono) or 2 (stereo) audio channels, got {audio_channels} channels.\")\n self.audio_channels = audio_channels\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ROFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[CausalLMOutputWithCrossAttentions, Tuple[torch.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RoFormerForCausalLM, RoFormerConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"junnyu/roformer_chinese_base\")\n >>> config = RoFormerConfig.from_pretrained(\"junnyu/roformer_chinese_base\")\n >>> config.is_decoder = True\n >>> model = RoFormerForCausalLM.from_pretrained(\"junnyu/roformer_chinese_base\", config=config)\n\n >>> inputs = tokenizer(\"\u4eca\u5929\u5929\u6c14\u975e\u5e38\u597d\u3002\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.roformer(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[1:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n name: str,\n folder_name: str = None,\n cmd: Optional[list] = None,\n work_dir: str = \".\",\n ports: Optional[list] = None,\n env: Optional[dict] = None,\n topics: Optional[list] = None,\n target_names: Optional[list] = None,\n options: Optional[list] = None,\n parent=None,\n container=None,\n updated_at: Optional[float] = None,\n plugin=None,\n needs_dependencies=False,\n secrets: Optional[list] = None,\n prefix=None,\n disable_erb=None,\n scope: str = OPENC3_SCOPE,\n ):\n parts = name.split(\"__\")\n if len(parts) != 3:\n raise RuntimeError(f\"name '{name}' must be formatted as SCOPE__TYPE__NAME\")\n if parts[0] != scope:\n raise RuntimeError(f\"name '{name}' scope '{parts[0]}' doesn't match scope parameter '{scope}'\")\n\n cmd = [] if cmd is None else cmd\n ports = [] if ports is None else ports\n env = {} if env is None else env\n topics = [] if topics is None else topics\n target_names = [] if target_names is None else target_names\n options = [] if options is None else options\n secrets = [] if secrets is None else secrets\n\n super().__init__(\n MicroserviceModel.PRIMARY_KEY,\n name=name,\n updated_at=updated_at,\n plugin=plugin,\n scope=scope,\n )\n self.folder_name = folder_name\n self.cmd = cmd\n self.work_dir = work_dir\n self.ports = ports\n self.env = env\n self.topics = topics\n self.target_names = target_names\n self.options = options\n self.parent = parent\n self.container = container\n self.needs_dependencies = needs_dependencies\n self.secrets = secrets\n self.prefix = prefix\n self.disable_erb = disable_erb\n self.bucket = Bucket.getClient()", "smellKey": "S107", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "@validate_call\n def api_environments_v3_get(\n self,\n auto_populate_chart_releases: Annotated[Optional[StrictBool], Field(description=\"If true when creating, dynamic environments copy from template and template environments get the honeycomb chart\")] = None,\n base: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n base_domain: Optional[StrictStr] = None,\n created_at: Optional[datetime] = None,\n default_cluster: Optional[StrictStr] = None,\n default_namespace: Annotated[Optional[StrictStr], Field(description=\"When creating, will be calculated if left empty\")] = None,\n delete_after: Annotated[Optional[datetime], Field(description=\"If set, the BEE will be automatically deleted after this time. Can be set to \\\"\\\" or Go's zero time value to clear the field.\")] = None,\n description: Optional[StrictStr] = None,\n enable_janitor: Annotated[Optional[StrictBool], Field(description=\"If true, janitor resource cleanup will be enabled for this environment. BEEs default to template's value, templates default to true, and static/live environments default to false.\")] = None,\n helmfile_ref: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n lifecycle: Optional[StrictStr] = None,\n name: Annotated[Optional[StrictStr], Field(description=\"When creating, will be calculated if dynamic, required otherwise\")] = None,\n name_prefixes_domain: Optional[StrictBool] = None,\n offline: Annotated[Optional[StrictBool], Field(description=\"Applicable for BEEs only, whether Thelma should render the BEE as \\\"offline\\\" zero replicas (this field is a target state, not a status)\")] = None,\n offline_schedule_begin_enabled: Annotated[Optional[StrictBool], Field(description=\"When enabled, the BEE will be slated to go offline around the begin time each day\")] = None,\n offline_schedule_begin_time: Annotated[Optional[datetime], Field(description=\"Stored with timezone to determine day of the week\")] = None,\n offline_schedule_end_enabled: Annotated[Optional[StrictBool], Field(description=\"When enabled, the BEE will be slated to come online around the end time each weekday (each day if weekends enabled)\")] = None,\n offline_schedule_end_time: Annotated[Optional[datetime], Field(description=\"Stored with timezone to determine day of the week\")] = None,\n offline_schedule_end_weekends: Optional[StrictBool] = None,\n owner: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to you\")] = None,\n pact_identifier: Optional[StrictStr] = None,\n pagerduty_integration: Optional[StrictStr] = None,\n prevent_deletion: Annotated[Optional[StrictBool], Field(description=\"Used to protect specific BEEs from deletion (thelma checks this field)\")] = None,\n required_role: Annotated[Optional[StrictStr], Field(description=\"If present, requires membership in the given role for mutations. Set to an empty string to clear.\")] = None,\n requires_suitability: Optional[StrictBool] = None,\n template_environment: Annotated[Optional[StrictStr], Field(description=\"Required for dynamic environments\")] = None,\n unique_resource_prefix: Annotated[Optional[StrictStr], Field(description=\"When creating, will be calculated if left empty\")] = None,\n updated_at: Optional[datetime] = None,\n values_name: Annotated[Optional[StrictStr], Field(description=\"When creating, defaults to template name or environment name\")] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Environments are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Environments (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockEnvironmentV3]:\n \"\"\"List Environments matching a filter\n\n List Environments matching a filter.\n\n :param auto_populate_chart_releases: If true when creating, dynamic environments copy from template and template environments get the honeycomb chart\n :type auto_populate_chart_releases: bool\n :param base: Required when creating\n :type base: str\n :param base_domain:\n :type base_domain: str\n :param created_at:\n :type created_at: datetime\n :param default_cluster:\n :type default_cluster: str\n :param default_namespace: When creating, will be calculated if left empty\n :type default_namespace: str\n :param delete_after: If set, the BEE will be automatically deleted after this time. Can be set to \\\"\\\" or Go's zero time value to clear the field.\n :type delete_after: datetime\n :param description:\n :type description: str\n :param enable_janitor: If true, janitor resource cleanup will be enabled for this environment. BEEs default to template's value, templates default to true, and static/live environments default to false.\n :type enable_janitor: bool\n :param helmfile_ref:\n :type helmfile_ref: str\n :param id:\n :type id: int\n :param lifecycle:\n :type lifecycle: str\n :param name: When creating, will be calculated if dynamic, required otherwise\n :type name: str\n :param name_prefixes_domain:\n :type name_prefixes_domain: bool\n :param offline: Applicable for BEEs only, whether Thelma should render the BEE as \\\"offline\\\" zero replicas (this field is a target state, not a status)\n :type offline: bool\n :param offline_schedule_begin_enabled: When enabled, the BEE will be slated to go offline around the begin time each day\n :type offline_schedule_begin_enabled: bool\n :param offline_schedule_begin_time: Stored with timezone to determine day of the week\n :type offline_schedule_begin_time: datetime\n :param offline_schedule_end_enabled: When enabled, the BEE will be slated to come online around the end time each weekday (each day if weekends enabled)\n :type offline_schedule_end_enabled: bool\n :param offline_schedule_end_time: Stored with timezone to determine day of the week\n :type offline_schedule_end_time: datetime\n :param offline_schedule_end_weekends:\n :type offline_schedule_end_weekends: bool\n :param owner: When creating, will default to you\n :type owner: str\n :param pact_identifier:\n :type pact_identifier: str\n :param pagerduty_integration:\n :type pagerduty_integration: str\n :param prevent_deletion: Used to protect specific BEEs from deletion (thelma checks this field)\n :type prevent_deletion: bool\n :param required_role: If present, requires membership in the given role for mutations. Set to an empty string to clear.\n :type required_role: str\n :param requires_suitability:\n :type requires_suitability: bool\n :param template_environment: Required for dynamic environments\n :type template_environment: str\n :param unique_resource_prefix: When creating, will be calculated if left empty\n :type unique_resource_prefix: str\n :param updated_at:\n :type updated_at: datetime\n :param values_name: When creating, defaults to template name or environment name\n :type values_name: str\n :param limit: Control how many Environments are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned Environments (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_environments_v3_get_serialize(\n auto_populate_chart_releases=auto_populate_chart_releases,\n base=base,\n base_domain=base_domain,\n created_at=created_at,\n default_cluster=default_cluster,\n default_namespace=default_namespace,\n delete_after=delete_after,\n description=description,\n enable_janitor=enable_janitor,\n helmfile_ref=helmfile_ref,\n id=id,\n lifecycle=lifecycle,\n name=name,\n name_prefixes_domain=name_prefixes_domain,\n offline=offline,\n offline_schedule_begin_enabled=offline_schedule_begin_enabled,\n offline_schedule_begin_time=offline_schedule_begin_time,\n offline_schedule_end_enabled=offline_schedule_end_enabled,\n offline_schedule_end_time=offline_schedule_end_time,\n offline_schedule_end_weekends=offline_schedule_end_weekends,\n owner=owner,\n pact_identifier=pact_identifier,\n pagerduty_integration=pagerduty_integration,\n prevent_deletion=prevent_deletion,\n required_role=required_role,\n requires_suitability=requires_suitability,\n template_environment=template_environment,\n unique_resource_prefix=unique_resource_prefix,\n updated_at=updated_at,\n values_name=values_name,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockEnvironmentV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@validate_call\n def api_database_instances_v3_get(\n self,\n chart_release: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n default_database: Annotated[Optional[StrictStr], Field(description=\"When creating, defaults to the chart name\")] = None,\n google_project: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google'\")] = None,\n id: Optional[StrictInt] = None,\n instance_name: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google' or 'azure'\")] = None,\n platform: Annotated[Optional[StrictStr], Field(description=\"'google', 'azure', or default 'kubernetes'\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many DatabaseInstances are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned DatabaseInstances (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockDatabaseInstanceV3]:\n \"\"\"List DatabaseInstances matching a filter\n\n List DatabaseInstances matching a filter.\n\n :param chart_release: Required when creating\n :type chart_release: str\n :param created_at:\n :type created_at: datetime\n :param default_database: When creating, defaults to the chart name\n :type default_database: str\n :param google_project: Required if platform is 'google'\n :type google_project: str\n :param id:\n :type id: int\n :param instance_name: Required if platform is 'google' or 'azure'\n :type instance_name: str\n :param platform: 'google', 'azure', or default 'kubernetes'\n :type platform: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many DatabaseInstances are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned DatabaseInstances (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_database_instances_v3_get_serialize(\n chart_release=chart_release,\n created_at=created_at,\n default_database=default_database,\n google_project=google_project,\n id=id,\n instance_name=instance_name,\n platform=platform,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockDatabaseInstanceV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n image_size=[512, 864],\n patch_size=16,\n num_channels=3,\n qkv_bias=True,\n num_detection_tokens=100,\n use_mid_position_embeddings=True,\n auxiliary_loss=False,\n class_cost=1,\n bbox_cost=5,\n giou_cost=2,\n bbox_loss_coefficient=5,\n giou_loss_coefficient=2,\n eos_coefficient=0.1,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.num_detection_tokens = num_detection_tokens\n self.use_mid_position_embeddings = use_mid_position_embeddings\n self.auxiliary_loss = auxiliary_loss\n # Hungarian matcher\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n # Loss coefficients\n self.bbox_loss_coefficient = bbox_loss_coefficient\n self.giou_loss_coefficient = giou_loss_coefficient\n self.eos_coefficient = eos_coefficient", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n unk_token=\"<unk>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n prefix_token=\"\u2581<PRE>\",\n middle_token=\"\u2581<MID>\",\n suffix_token=\"\u2581<SUF>\",\n eot_token=\"\u2581<EOT>\",\n fill_token=\"<FILL_ME>\",\n suffix_first=False,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n add_bos_token=True,\n add_eos_token=False,\n clean_up_tokenization_spaces=False,\n additional_special_tokens=None,\n use_default_system_prompt=False,\n **kwargs,\n ):\n requires_backends(self, \"protobuf\")\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token\n unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token\n\n self.use_default_system_prompt = use_default_system_prompt\n # mark tokens special to skip them\n additional_special_tokens = additional_special_tokens or []\n for token in [prefix_token, middle_token, suffix_token, eot_token]:\n additional_special_tokens += [token] if token is not None else []\n\n self.vocab_file = vocab_file\n self.add_bos_token = add_bos_token\n self.add_eos_token = add_eos_token\n self._prefix_token = prefix_token\n self._middle_token = middle_token\n self._suffix_token = suffix_token\n self._eot_token = eot_token\n self.fill_token = fill_token\n self.suffix_first = suffix_first\n self.sp_model = self.get_spm_processor()\n\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n add_bos_token=add_bos_token,\n add_eos_token=add_eos_token,\n prefix_token=prefix_token,\n middle_token=middle_token,\n suffix_token=suffix_token,\n eot_token=eot_token,\n fill_token=fill_token,\n sp_model_kwargs=self.sp_model_kwargs,\n suffix_first=suffix_first,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n additional_special_tokens=additional_special_tokens,\n use_default_system_prompt=use_default_system_prompt,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\n crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\n soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for\n Console default. Defaults to ``None``.\n new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.\n \"\"\"\n if not objects:\n objects = (NewLine(),)\n\n if soft_wrap is None:\n soft_wrap = self.soft_wrap\n if soft_wrap:\n if no_wrap is None:\n no_wrap = True\n if overflow is None:\n overflow = \"ignore\"\n crop = False\n render_hooks = self._render_hooks[:]\n with self:\n renderables = self._collect_renderables(\n objects,\n sep,\n end,\n justify=justify,\n emoji=emoji,\n markup=markup,\n highlight=highlight,\n )\n for hook in render_hooks:\n renderables = hook.process_renderables(renderables)\n render_options = self.options.update(\n justify=justify,\n overflow=overflow,\n width=min(width, self.width) if width is not None else NO_CHANGE,\n height=height,\n no_wrap=no_wrap,\n markup=markup,\n highlight=highlight,\n )\n\n new_segments: List[Segment] = []\n extend = new_segments.extend\n render = self.render\n if style is None:\n for renderable in renderables:\n extend(render(renderable, render_options))\n else:\n for renderable in renderables:\n extend(\n Segment.apply_style(\n render(renderable, render_options), self.get_style(style)\n )\n )\n if new_line_start:\n if (\n len(\"\".join(segment.text for segment in new_segments).splitlines())\n > 1\n ):\n new_segments.insert(0, Segment.line())\n if crop:\n buffer_extend = self._buffer.extend\n for line in Segment.split_and_crop_lines(\n new_segments, self.width, pad=False\n ):\n buffer_extend(line)\n else:\n self._buffer.extend(new_segments)", "smellKey": "S107", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=384,\n intermediate_size=1536,\n depths=[6, 3, 3],\n num_hidden_layers=12,\n num_group_tokens=[64, 8, 0],\n num_output_groups=[64, 8, 8],\n num_attention_heads=6,\n image_size=224,\n patch_size=16,\n num_channels=3,\n hidden_act=\"gelu\",\n layer_norm_eps=1e-5,\n dropout=0.0,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n assign_eps=1.0,\n assign_mlp_ratio=[0.5, 4],\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.depths = depths\n if num_hidden_layers != sum(depths):\n logger.warning(\n f\"Manually setting num_hidden_layers to {num_hidden_layers}, but we expect num_hidden_layers =\"\n f\" sum(depth) = {sum(depths)}\"\n )\n self.num_hidden_layers = num_hidden_layers\n self.num_group_tokens = num_group_tokens\n self.num_output_groups = num_output_groups\n self.num_attention_heads = num_attention_heads\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.hidden_act = hidden_act\n self.layer_norm_eps = layer_norm_eps\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.assign_eps = assign_eps\n self.assign_mlp_ratio = assign_mlp_ratio", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n d_model=1024,\n decoder_layers=12,\n decoder_attention_heads=16,\n decoder_ffn_dim=4096,\n activation_function=\"gelu\",\n max_position_embeddings=512,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n decoder_start_token_id=2,\n init_std=0.02,\n decoder_layerdrop=0.0,\n use_cache=True,\n scale_embedding=False,\n use_learned_position_embeddings=True,\n layernorm_embedding=True,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.activation_function = activation_function\n self.max_position_embeddings = max_position_embeddings\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.init_std = init_std\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.scale_embedding = scale_embedding\n self.use_learned_position_embeddings = use_learned_position_embeddings\n self.layernorm_embedding = layernorm_embedding\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n decoder_start_token_id=decoder_start_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n ensure_multiple_of=32,\n keep_aspect_ratio=False,\n do_normalize=True,\n image_mean=[0.5, 0.5, 0.5],\n image_std=[0.5, 0.5, 0.5],\n do_pad=False,\n ):\n super().__init__()\n size = size if size is not None else {\"height\": 18, \"width\": 18}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.ensure_multiple_of = ensure_multiple_of\n self.keep_aspect_ratio = keep_aspect_ratio\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_pad = do_pad", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=128100,\n hidden_size=1536,\n num_hidden_layers=24,\n num_attention_heads=24,\n intermediate_size=6144,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=0,\n initializer_range=0.02,\n layer_norm_eps=1e-7,\n relative_attention=False,\n max_relative_positions=-1,\n pad_token_id=0,\n position_biased_input=True,\n pos_att_type=None,\n pooler_dropout=0,\n pooler_hidden_act=\"gelu\",\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.relative_attention = relative_attention\n self.max_relative_positions = max_relative_positions\n self.pad_token_id = pad_token_id\n self.position_biased_input = position_biased_input\n\n # Backwards compatibility\n if isinstance(pos_att_type, str):\n pos_att_type = [x.strip() for x in pos_att_type.lower().split(\"|\")]\n\n self.pos_att_type = pos_att_type\n self.vocab_size = vocab_size\n self.layer_norm_eps = layer_norm_eps\n\n self.pooler_hidden_size = kwargs.get(\"pooler_hidden_size\", hidden_size)\n self.pooler_dropout = pooler_dropout\n self.pooler_hidden_act = pooler_hidden_act", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def request(\n self,\n method,\n url,\n params=None,\n data=None,\n headers=None,\n cookies=None,\n files=None,\n auth=None,\n timeout=None,\n allow_redirects=True,\n proxies=None,\n hooks=None,\n stream=None,\n verify=None,\n cert=None,\n json=None,\n ):\n \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n Returns :class:`Response <Response>` object.\n\n :param method: method for the new :class:`Request` object.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary or bytes to be sent in the query\n string for the :class:`Request`.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) json to send in the body of the\n :class:`Request`.\n :param headers: (optional) Dictionary of HTTP Headers to send with the\n :class:`Request`.\n :param cookies: (optional) Dict or CookieJar object to send with the\n :class:`Request`.\n :param files: (optional) Dictionary of ``'filename': file-like-objects``\n for multipart encoding upload.\n :param auth: (optional) Auth tuple or callable to enable\n Basic/Digest/Custom HTTP Auth.\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) <timeouts>` tuple.\n :type timeout: float or tuple\n :param allow_redirects: (optional) Set to True by default.\n :type allow_redirects: bool\n :param proxies: (optional) Dictionary mapping protocol or protocol and\n hostname to the URL of the proxy.\n :param stream: (optional) whether to immediately download the response\n content. Defaults to ``False``.\n :param verify: (optional) Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n to a CA bundle to use. Defaults to ``True``. When set to\n ``False``, requests will accept any TLS certificate presented by\n the server, and will ignore hostname mismatches and/or expired\n certificates, which will make your application vulnerable to\n man-in-the-middle (MitM) attacks. Setting verify to ``False``\n may be useful during local development or testing.\n :param cert: (optional) if String, path to ssl client cert file (.pem).\n If Tuple, ('cert', 'key') pair.\n :rtype: requests.Response\n \"\"\"\n # Create the Request.\n req = Request(\n method=method.upper(),\n url=url,\n headers=headers,\n files=files,\n data=data or {},\n json=json,\n params=params or {},\n auth=auth,\n cookies=cookies,\n hooks=hooks,\n )\n prep = self.prepare_request(req)\n\n proxies = proxies or {}\n\n settings = self.merge_environment_settings(\n prep.url, proxies, stream, verify, cert\n )\n\n # Send the request.\n send_kwargs = {\n \"timeout\": timeout,\n \"allow_redirects\": allow_redirects,\n }\n send_kwargs.update(settings)\n resp = self.send(prep, **send_kwargs)\n\n return resp", "smellKey": "S107", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n **kwargs,\n ):\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n use_cache = False\n\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False\n elif not return_dict and not isinstance(encoder_outputs, tuple):\n encoder_outputs = encoder_outputs.to_tuple()\n\n decoder_outputs = self.decoder(\n decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, cfg, device, dev_id=None,\n commander=DEFAULT_JLINK_EXE,\n dt_flash=True, erase=True, reset=False,\n iface='swd', speed='auto',\n loader=None,\n gdbserver='JLinkGDBServer',\n gdb_host='',\n gdb_port=DEFAULT_JLINK_GDB_PORT,\n rtt_port=DEFAULT_JLINK_RTT_PORT,\n tui=False, tool_opt=[]):\n super().__init__(cfg)\n self.file = cfg.file\n self.file_type = cfg.file_type\n self.hex_name = cfg.hex_file\n self.bin_name = cfg.bin_file\n self.elf_name = cfg.elf_file\n self.gdb_cmd = [cfg.gdb] if cfg.gdb else None\n self.device = device\n self.dev_id = dev_id\n self.commander = commander\n self.dt_flash = dt_flash\n self.erase = erase\n self.reset = reset\n self.gdbserver = gdbserver\n self.iface = iface\n self.speed = speed\n self.gdb_host = gdb_host\n self.gdb_port = gdb_port\n self.tui_arg = ['-tui'] if tui else []\n self.loader = loader\n self.rtt_port = rtt_port\n\n self.tool_opt = []\n for opts in [shlex.split(opt) for opt in tool_opt]:\n self.tool_opt += opts", "smellKey": "S107", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def __init__(\n self,\n story_id: str,\n title: str,\n thumbnail_filename: Optional[str],\n thumbnail_bg_color: Optional[str],\n thumbnail_size_in_bytes: Optional[int],\n description: str,\n notes: str,\n story_contents: StoryContents,\n story_contents_schema_version: int,\n language_code: str,\n corresponding_topic_id: str,\n version: int,\n url_fragment: str,\n meta_tag_content: str,\n created_on: Optional[datetime.datetime] = None,\n last_updated: Optional[datetime.datetime] = None\n ) -> None:\n \"\"\"Constructs a Story domain object.\n\n Args:\n story_id: str. The unique ID of the story.\n title: str. The title of the story.\n description: str. The high level description of the story.\n notes: str. A set of notes, that describe the characters,\n main storyline, and setting. To be provided in html form.\n story_contents: StoryContents. The StoryContents instance\n representing the contents (like nodes) that are part of the\n story.\n story_contents_schema_version: int. The schema version for the\n story contents object.\n language_code: str. The ISO 639-1 code for the language this\n story is written in.\n corresponding_topic_id: str. The id of the topic to which the story\n belongs.\n version: int. The version of the story.\n created_on: datetime.datetime. Date and time when the story is\n created.\n last_updated: datetime.datetime. Date and time when the\n story was last updated.\n thumbnail_filename: str|None. The thumbnail filename of the story.\n thumbnail_bg_color: str|None. The thumbnail background color of\n the story.\n thumbnail_size_in_bytes: int|None. The size of thumbnail in bytes.\n url_fragment: str. The url fragment for the story.\n meta_tag_content: str. The meta tag content in the topic viewer\n page.\n \"\"\"\n self.id = story_id\n self.title = title\n self.thumbnail_filename = thumbnail_filename\n self.thumbnail_bg_color = thumbnail_bg_color\n self.thumbnail_size_in_bytes = thumbnail_size_in_bytes\n self.description = description\n self.notes = html_cleaner.clean(notes)\n self.story_contents = story_contents\n self.story_contents_schema_version = story_contents_schema_version\n self.language_code = language_code\n self.corresponding_topic_id = corresponding_topic_id\n self.created_on = created_on\n self.last_updated = last_updated\n self.version = version\n self.url_fragment = url_fragment\n self.meta_tag_content = meta_tag_content", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=32,\n patch_size=2,\n num_channels=3,\n last_hidden_size=32,\n num_attention_heads=4,\n hidden_act=\"silu\",\n conv_kernel_size=3,\n output_stride=32,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n classifier_dropout_prob=0.1,\n initializer_range=0.02,\n is_training=True,\n use_labels=True,\n num_labels=10,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.last_hidden_size = last_hidden_size\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.conv_kernel_size = conv_kernel_size\n self.output_stride = output_stride\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.classifier_dropout_prob = classifier_dropout_prob\n self.use_labels = use_labels\n self.is_training = is_training\n self.num_labels = num_labels\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BIGBIRD_PEGASUS_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(BIGBIRD_PEGASUS_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n lm_logits = self.lm_head(outputs[0])\n lm_logits = lm_logits + self.final_logits_bias.to(lm_logits.device)\n\n masked_lm_loss = None\n if labels is not None:\n labels = labels.to(lm_logits.device)\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n pattern=None,\n top_level=None,\n verbosity=1,\n interactive=True,\n failfast=False,\n keepdb=False,\n reverse=False,\n debug_mode=False,\n debug_sql=False,\n parallel=0,\n tags=None,\n exclude_tags=None,\n test_name_patterns=None,\n pdb=False,\n buffer=False,\n enable_faulthandler=True,\n timing=False,\n shuffle=False,\n logger=None,\n durations=None,\n **kwargs,\n ):\n self.pattern = pattern\n self.top_level = top_level\n self.verbosity = verbosity\n self.interactive = interactive\n self.failfast = failfast\n self.keepdb = keepdb\n self.reverse = reverse\n self.debug_mode = debug_mode\n self.debug_sql = debug_sql\n self.parallel = parallel\n self.tags = set(tags or [])\n self.exclude_tags = set(exclude_tags or [])\n if not faulthandler.is_enabled() and enable_faulthandler:\n try:\n faulthandler.enable(file=sys.stderr.fileno())\n except (AttributeError, io.UnsupportedOperation):\n faulthandler.enable(file=sys.__stderr__.fileno())\n self.pdb = pdb\n if self.pdb and self.parallel > 1:\n raise ValueError(\n \"You cannot use --pdb with parallel tests; pass --parallel=1 to use it.\"\n )\n self.buffer = buffer\n self.test_name_patterns = None\n self.time_keeper = TimeKeeper() if timing else NullTimeKeeper()\n if test_name_patterns:\n # unittest does not export the _convert_select_pattern function\n # that converts command-line arguments to patterns.\n self.test_name_patterns = {\n pattern if \"*\" in pattern else \"*%s*\" % pattern\n for pattern in test_name_patterns\n }\n self.shuffle = shuffle\n self._shuffler = None\n self.logger = logger\n self.durations = durations", "smellKey": "S107", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(\n self,\n share_cross_modal_transformer_layers=True,\n hidden_act=\"gelu\",\n hidden_size=768,\n initializer_factor=1,\n layer_norm_eps=1e-05,\n share_link_tower_layers=False,\n link_tower_type=\"add\",\n num_attention_heads=12,\n num_hidden_layers=6,\n tie_word_embeddings=False,\n init_layernorm_from_vision_encoder=False,\n text_config=None,\n vision_config=None,\n **kwargs,\n ):\n # TODO: remove this once the Hub files are updated.\n _ = kwargs.pop(\"text_config_dict\", None)\n _ = kwargs.pop(\"vision_config_dict\", None)\n\n super().__init__(**kwargs)\n self.share_cross_modal_transformer_layers = share_cross_modal_transformer_layers\n self.hidden_act = hidden_act\n self.hidden_size = hidden_size\n self.initializer_factor = initializer_factor\n self.layer_norm_eps = layer_norm_eps\n self.share_link_tower_layers = share_link_tower_layers\n self.link_tower_type = link_tower_type\n self.num_attention_heads = num_attention_heads\n self.num_hidden_layers = num_hidden_layers\n self.tie_word_embeddings = tie_word_embeddings\n self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder\n\n if text_config is None:\n text_config = {}\n logger.info(\"`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.\")\n\n if vision_config is None:\n vision_config = {}\n logger.info(\"`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.\")\n\n self.text_config = BridgeTowerTextConfig(**text_config)\n self.vision_config = BridgeTowerVisionConfig(**vision_config)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=256000,\n hidden_size=6144,\n intermediate_size=24576,\n num_hidden_layers=32,\n num_attention_heads=48,\n head_dim=None,\n num_key_value_heads=None,\n hidden_act=\"relu2\",\n max_position_embeddings=4096,\n initializer_range=0.0134,\n norm_eps=1e-5,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=2,\n eos_token_id=3,\n tie_word_embeddings=False,\n rope_theta=10000.0,\n partial_rotary_factor=0.5,\n attention_bias=False,\n attention_dropout=0.0,\n mlp_bias=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.norm_eps = norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.partial_rotary_factor = partial_rotary_factor\n rope_config_validation(self)\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n self.mlp_bias = mlp_bias\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(MARIAN_GENERATION_EXAMPLE)\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: TFBaseModelOutput | None = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: bool | None = None,\n output_attentions: bool | None = None,\n output_hidden_states: bool | None = None,\n return_dict: bool | None = None,\n labels: tf.Tensor | None = None,\n training: bool = False,\n ) -> Tuple[tf.Tensor] | TFSeq2SeqLMOutput:\n r\"\"\"\n labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n\n if labels is not None:\n labels = tf.where(\n labels == self.config.pad_token_id,\n tf.fill(shape_list(labels), tf.cast(-100, labels.dtype)),\n labels,\n )\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)\n lm_logits = self.bias_layer(lm_logits)\n masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n return TFSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values, # index 1 of d outputs\n decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs\n decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs\n cross_attentions=outputs.cross_attentions, # index 4 of d outputs\n encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs\n encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out\n encoder_attentions=outputs.encoder_attentions, # 2 of e out\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\n \"unit_system\",\n \"native_unit\",\n \"automatic_unit\",\n \"suggested_unit\",\n \"custom_unit\",\n \"suggested_precision\",\n \"native_value\",\n \"native_state\",\n \"automatic_state\",\n \"suggested_state\",\n \"custom_state\",\n \"device_class\",\n ),\n [\n # Distance\n (\n US_CUSTOMARY_SYSTEM,\n UnitOfLength.KILOMETERS,\n UnitOfLength.MILES,\n UnitOfLength.METERS,\n UnitOfLength.YARDS,\n 2,\n 1000,\n \"1000\",\n 621.371,\n 1000000,\n 1093613,\n SensorDeviceClass.DISTANCE,\n ),\n ],\n)\nasync def test_unit_conversion_priority_precision(\n hass: HomeAssistant,\n entity_registry: er.EntityRegistry,\n unit_system,\n native_unit,\n automatic_unit,\n suggested_unit,\n custom_unit,\n suggested_precision,\n native_value,\n native_state,\n automatic_state,\n suggested_state,\n custom_state,\n device_class,\n) -> None:\n \"\"\"Test priority of unit conversion for sensors with suggested_display_precision.\"\"\"\n\n hass.config.units = unit_system\n\n entity0 = MockSensor(\n name=\"Test\",\n device_class=device_class,\n native_unit_of_measurement=native_unit,\n native_value=str(native_value),\n suggested_display_precision=suggested_precision,\n unique_id=\"very_unique\",\n )\n entity1 = MockSensor(\n name=\"Test\",\n device_class=device_class,\n native_unit_of_measurement=native_unit,\n native_value=str(native_value),\n suggested_display_precision=suggested_precision,\n )\n entity2 = MockSensor(\n name=\"Test\",\n device_class=device_class,\n native_unit_of_measurement=native_unit,\n native_value=str(native_value),\n suggested_display_precision=suggested_precision,\n suggested_unit_of_measurement=suggested_unit,\n unique_id=\"very_unique_2\",\n )\n entity3 = MockSensor(\n name=\"Test\",\n device_class=device_class,\n native_unit_of_measurement=native_unit,\n native_value=str(native_value),\n suggested_display_precision=suggested_precision,\n suggested_unit_of_measurement=suggested_unit,\n )\n entity4 = MockSensor(\n name=\"Test\",\n device_class=device_class,\n native_unit_of_measurement=native_unit,\n native_value=str(native_value),\n suggested_display_precision=None,\n unique_id=\"very_unique_4\",\n )\n setup_test_component_platform(\n hass,\n sensor.DOMAIN,\n [\n entity0,\n entity1,\n entity2,\n entity3,\n entity4,\n ],\n )\n\n assert await async_setup_component(hass, \"sensor\", {\"sensor\": {\"platform\": \"test\"}})\n await hass.async_block_till_done()\n\n # Registered entity -> Follow automatic unit conversion\n state = hass.states.get(entity0.entity_id)\n assert float(state.state) == pytest.approx(automatic_state)\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == automatic_unit\n # Assert the automatic unit conversion is stored in the registry\n entry = entity_registry.async_get(entity0.entity_id)\n assert entry.unit_of_measurement == automatic_unit\n assert entry.options == {\n \"sensor\": {\"suggested_display_precision\": 2},\n \"sensor.private\": {\"suggested_unit_of_measurement\": automatic_unit},\n }\n assert float(async_rounded_state(hass, entity0.entity_id, state)) == pytest.approx(\n round(automatic_state, 2)\n )\n\n # Unregistered entity -> Follow native unit\n state = hass.states.get(entity1.entity_id)\n assert state.state == native_state\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == native_unit\n\n # Registered entity with suggested unit\n state = hass.states.get(entity2.entity_id)\n assert float(state.state) == pytest.approx(suggested_state)\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == suggested_unit\n # Assert the suggested unit is stored in the registry\n entry = entity_registry.async_get(entity2.entity_id)\n assert entry.unit_of_measurement == suggested_unit\n assert entry.options == {\n \"sensor\": {\"suggested_display_precision\": 2},\n \"sensor.private\": {\"suggested_unit_of_measurement\": suggested_unit},\n }\n\n # Unregistered entity with suggested unit\n state = hass.states.get(entity3.entity_id)\n assert float(state.state) == pytest.approx(suggested_state)\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == suggested_unit\n\n # Set a custom unit, this should have priority over the automatic unit conversion\n entity_registry.async_update_entity_options(\n entity0.entity_id, \"sensor\", {\"unit_of_measurement\": custom_unit}\n )\n await hass.async_block_till_done()\n\n state = hass.states.get(entity0.entity_id)\n assert float(state.state) == pytest.approx(custom_state)\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == custom_unit\n\n entity_registry.async_update_entity_options(\n entity2.entity_id, \"sensor\", {\"unit_of_measurement\": custom_unit}\n )\n await hass.async_block_till_done()\n\n state = hass.states.get(entity2.entity_id)\n assert float(state.state) == pytest.approx(custom_state)\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == custom_unit\n\n # Set a display_precision, this should have priority over suggested_display_precision\n entity_registry.async_update_entity_options(\n entity0.entity_id,\n \"sensor\",\n {\"suggested_display_precision\": 2, \"display_precision\": 4},\n )\n entry0 = entity_registry.async_get(entity0.entity_id)\n assert entry0.options[\"sensor\"][\"suggested_display_precision\"] == 2\n assert entry0.options[\"sensor\"][\"display_precision\"] == 4\n await hass.async_block_till_done()\n assert float(async_rounded_state(hass, entity0.entity_id, state)) == pytest.approx(\n round(custom_state, 4)\n )\n\n # Set a display_precision without having suggested_display_precision\n entity_registry.async_update_entity_options(\n entity4.entity_id,\n \"sensor\",\n {\"display_precision\": 4},\n )\n entry4 = entity_registry.async_get(entity4.entity_id)\n assert \"suggested_display_precision\" not in entry4.options[\"sensor\"]\n assert entry4.options[\"sensor\"][\"display_precision\"] == 4\n await hass.async_block_till_done()\n state = hass.states.get(entity4.entity_id)\n assert float(async_rounded_state(hass, entity4.entity_id, state)) == pytest.approx(\n round(automatic_state, 4)\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def _batch_encode_plus_boxes(\n self,\n batch_text_or_text_pairs: Union[\n List[TextInput],\n List[TextInputPair],\n List[PreTokenizedInput],\n ],\n is_pair: bool = None,\n boxes: Optional[List[List[List[int]]]] = None,\n word_labels: Optional[List[List[int]]] = None,\n add_special_tokens: bool = True,\n padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,\n truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[str] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n if not isinstance(batch_text_or_text_pairs, list):\n raise TypeError(f\"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})\")\n\n # Set the truncation and padding strategy and restore the initial configuration\n self.set_truncation_and_padding(\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n )\n\n if is_pair:\n batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]\n\n encodings = self._tokenizer.encode_batch(\n batch_text_or_text_pairs,\n add_special_tokens=add_special_tokens,\n is_pretokenized=True, # we set this to True as LayoutLMv2 always expects pretokenized inputs\n )\n\n # Convert encoding to dict\n # `Tokens` has type: Tuple[\n # List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],\n # List[EncodingFast]\n # ]\n # with nested dimensions corresponding to batch, overflows, sequence length\n tokens_and_encodings = [\n self._convert_encoding(\n encoding=encoding,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=True\n if word_labels is not None\n else return_offsets_mapping, # we use offsets to create the labels\n return_length=return_length,\n verbose=verbose,\n )\n for encoding in encodings\n ]\n\n # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension\n # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)\n # (we say ~ because the number of overflow varies with the example in the batch)\n #\n # To match each overflowing sample with the original sample in the batch\n # we add an overflow_to_sample_mapping array (see below)\n sanitized_tokens = {}\n for key in tokens_and_encodings[0][0].keys():\n stack = [e for item, _ in tokens_and_encodings for e in item[key]]\n sanitized_tokens[key] = stack\n sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]\n\n # If returning overflowing tokens, we need to return a mapping\n # from the batch idx to the original sample\n if return_overflowing_tokens:\n overflow_to_sample_mapping = []\n for i, (toks, _) in enumerate(tokens_and_encodings):\n overflow_to_sample_mapping += [i] * len(toks[\"input_ids\"])\n sanitized_tokens[\"overflow_to_sample_mapping\"] = overflow_to_sample_mapping\n\n for input_ids in sanitized_tokens[\"input_ids\"]:\n self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)\n\n # create the token boxes\n token_boxes = []\n for batch_index in range(len(sanitized_tokens[\"input_ids\"])):\n if return_overflowing_tokens:\n original_index = sanitized_tokens[\"overflow_to_sample_mapping\"][batch_index]\n else:\n original_index = batch_index\n token_boxes_example = []\n for id, sequence_id, word_id in zip(\n sanitized_tokens[\"input_ids\"][batch_index],\n sanitized_encodings[batch_index].sequence_ids,\n sanitized_encodings[batch_index].word_ids,\n ):\n if word_id is not None:\n if is_pair and sequence_id == 0:\n token_boxes_example.append(self.pad_token_box)\n else:\n token_boxes_example.append(boxes[original_index][word_id])\n else:\n if id == self.sep_token_id:\n token_boxes_example.append(self.sep_token_box)\n elif id == self.pad_token_id:\n token_boxes_example.append(self.pad_token_box)\n else:\n raise ValueError(\"Id not recognized\")\n token_boxes.append(token_boxes_example)\n\n sanitized_tokens[\"bbox\"] = token_boxes\n\n # optionally, create the labels\n if word_labels is not None:\n labels = []\n for batch_index in range(len(sanitized_tokens[\"input_ids\"])):\n if return_overflowing_tokens:\n original_index = sanitized_tokens[\"overflow_to_sample_mapping\"][batch_index]\n else:\n original_index = batch_index\n labels_example = []\n previous_token_empty = False\n for id, offset, word_id in zip(\n sanitized_tokens[\"input_ids\"][batch_index],\n sanitized_tokens[\"offset_mapping\"][batch_index],\n sanitized_encodings[batch_index].word_ids,\n ):\n if word_id is not None:\n if self.only_label_first_subword:\n if offset[0] == 0 and not previous_token_empty:\n # Use the real label id for the first token of the word, and padding ids for the remaining tokens\n labels_example.append(word_labels[original_index][word_id])\n else:\n labels_example.append(self.pad_token_label)\n else:\n labels_example.append(word_labels[original_index][word_id])\n if self.decode(id) == \"\":\n previous_token_empty = True\n else:\n previous_token_empty = False\n else:\n labels_example.append(self.pad_token_label)\n labels.append(labels_example)\n\n sanitized_tokens[\"labels\"] = labels\n # finally, remove offsets if the user didn't want them\n if not return_offsets_mapping:\n del sanitized_tokens[\"offset_mapping\"]\n\n return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def preprocess(\n self,\n videos: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n patch_size: List[int] = None,\n num_frames: int = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n is_mixed: bool = False,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> BatchFeature:\n \"\"\"\n Preprocess an videos or image or batch of videos or images.\n\n Args:\n videos (`ImageInput`):\n Images or videos to preprocess. Expects a single or batch of frames with pixel values ranging from 0 to\n 255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after applying resize.\n patch_size (`List[int]` *optional*, defaults to self.patch_size):\n The patch size of image patch embedding.\n num_frames (`int` *optional*, defaults to self.num_frames):\n The maximum number of video frames.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):\n Whether to centre crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the image after applying the centre crop.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n is_mixed (`bool`, *optional*):\n If the input video has negative samples.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the inferred channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n Returns:\n [`BatchFeature`]: A [`BatchFeature`] with the following fields:\n\n - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,\n width).\n\n - **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).\n\n - **pixel_values_mixed** -- Pixel values with both postive or negative to be fed to a model, of shape\n (batch_size, num_channels, height, width).\n\n - **pixel_mask_mixed** -- Pixel masks with both postive or negative to be fed to a model, of shape\n (batch_size, num_pixel_patches).\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\")\n patch_size = patch_size if patch_size is not None else self.patch_size\n num_frames = num_frames if patch_size is not None else self.num_frames\n\n validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)\n\n if not valid_images(videos):\n raise ValueError(\n \"Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n videos = make_batched(videos)\n\n # Check number of frames is fewer than maximum frames\n for video in videos:\n if len(video) > self.num_frames:\n raise ValueError(\n f\"number of frames must not be greater than the maximum frames of the model {self.num_frames}.\"\n )\n\n max_num_frames = max([len(video) for video in videos])\n num_patches_per_image = (size[\"shortest_edge\"] // patch_size[0]) ** 2\n video_masks = np.array(\n [\n len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]\n for video in videos\n ]\n )\n\n videos = [\n [\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in video\n ]\n for video in videos\n ]\n\n # If videos contain both positive/negative, use mixed key for video-audio matching task\n if is_mixed:\n data = {\"pixel_values_mixed\": videos, \"pixel_mask_mixed\": video_masks}\n else:\n data = {\"pixel_values\": videos, \"pixel_mask\": video_masks}\n\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(LED_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n global_attention_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Conditional generation example:\n\n ```python\n >>> from transformers import AutoTokenizer, LEDForConditionalGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"allenai/led-base-16384\")\n >>> TXT = \"My friends are <mask> but they eat too many carbs.\"\n\n >>> model = LEDForConditionalGeneration.from_pretrained(\"allenai/led-base-16384\")\n >>> input_ids = tokenizer([TXT], return_tensors=\"pt\")[\"input_ids\"]\n\n >>> prediction = model.generate(input_ids)[0]\n >>> print(tokenizer.decode(prediction, skip_special_tokens=True))\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.led(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n encoder_outputs=encoder_outputs,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return LEDSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n encoder_global_attentions=outputs.encoder_global_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=49152,\n hidden_size=3072,\n intermediate_size=12288,\n num_hidden_layers=30,\n num_attention_heads=24,\n num_key_value_heads=2,\n hidden_act=\"gelu_pytorch_tanh\",\n max_position_embeddings=4096,\n initializer_range=0.018042,\n norm_epsilon=1e-5,\n use_cache=True,\n bos_token_id=50256,\n eos_token_id=50256,\n rope_theta=10000.0,\n rope_scaling=None,\n sliding_window=None,\n attention_dropout=0.0,\n residual_dropout=0.0,\n embedding_dropout=0.0,\n use_bias=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.sliding_window = sliding_window\n self.use_bias = use_bias\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.norm_epsilon = norm_epsilon\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.rope_scaling = rope_scaling\n self.attention_dropout = attention_dropout\n self.residual_dropout = residual_dropout\n self.embedding_dropout = embedding_dropout\n # Validate the correctness of rotary position embeddings parameters\n # BC: if there is a 'type' field, move it to 'rope_type'.\n if self.rope_scaling is not None and \"type\" in self.rope_scaling:\n self.rope_scaling[\"rope_type\"] = self.rope_scaling[\"type\"]\n rope_config_validation(self)\n\n super().__init__(\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_channels=3,\n image_size=256,\n patch_size=2,\n expand_ratio=2.0,\n hidden_act=\"swish\",\n conv_kernel_size=3,\n output_stride=32,\n classifier_dropout_prob=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n aspp_out_channels=512,\n atrous_rates=[6, 12, 18],\n aspp_dropout_prob=0.1,\n semantic_loss_ignore_index=255,\n n_attn_blocks=[2, 4, 3],\n base_attn_unit_dims=[128, 192, 256],\n width_multiplier=1.0,\n ffn_multiplier=2,\n attn_dropout=0.0,\n ffn_dropout=0.0,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.num_channels = num_channels\n self.image_size = image_size\n self.patch_size = patch_size\n self.expand_ratio = expand_ratio\n self.hidden_act = hidden_act\n self.conv_kernel_size = conv_kernel_size\n self.output_stride = output_stride\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.n_attn_blocks = n_attn_blocks\n self.base_attn_unit_dims = base_attn_unit_dims\n self.width_multiplier = width_multiplier\n self.ffn_multiplier = ffn_multiplier\n self.ffn_dropout = ffn_dropout\n self.attn_dropout = attn_dropout\n self.classifier_dropout_prob = classifier_dropout_prob\n\n # decode head attributes for semantic segmentation\n self.aspp_out_channels = aspp_out_channels\n self.atrous_rates = atrous_rates\n self.aspp_dropout_prob = aspp_dropout_prob\n self.semantic_loss_ignore_index = semantic_loss_ignore_index", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n patch_size=4,\n num_channels=3,\n embed_dim=96,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n window_size=7,\n mlp_ratio=4.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n use_absolute_embeddings=False,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_layers = len(depths)\n self.num_heads = num_heads\n self.window_size = window_size\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.use_absolute_embeddings = use_absolute_embeddings\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel\n # this indicates the channel dimension after the last stage of the model\n self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n hidden_act=\"silu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n num_experts_per_tok=2,\n num_experts=8,\n norm_topk_prob=False,\n output_router_logits=False,\n router_aux_loss_coef=0.001,\n intermediate_size=12,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope\n self.num_experts_per_tok = num_experts_per_tok\n self.num_experts = num_experts\n self.norm_topk_prob = norm_topk_prob\n self.output_router_logits = output_router_logits\n self.router_aux_loss_coef = router_aux_loss_coef", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n encoder_seq_length=1024, # speech is longer\n decoder_seq_length=7,\n is_training=False,\n hidden_size=24,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=4,\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n vocab_size=81,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.vocab_size = vocab_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(WHISPER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @unpack_inputs\n def call(\n self,\n input_features=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n decoder_position_ids=None,\n head_mask=None,\n decoder_head_mask=None,\n cross_attn_head_mask=None,\n encoder_outputs=None,\n past_key_values=None,\n decoder_inputs_embeds=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n ):\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import TFWhisperModel, AutoFeatureExtractor\n >>> from datasets import load_dataset\n\n >>> model = TFWhisperModel.from_pretrained(\"openai/whisper-base\")\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"openai/whisper-base\")\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> inputs = feature_extractor(ds[0][\"audio\"][\"array\"], return_tensors=\"tf\")\n >>> input_features = inputs.input_features\n >>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id\n >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state\n >>> list(last_hidden_state.shape)\n [1, 2, 512]\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_features,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\n \"discovery_info\",\n \"entry_data\",\n \"old_addon_options\",\n \"new_addon_options\",\n \"disconnect_calls\",\n \"restart_addon_side_effect\",\n ),\n [\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n [HassioAPIError(), None],\n ),\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n [\n HassioAPIError(),\n HassioAPIError(),\n ],\n ),\n ],\n)\nasync def test_options_addon_restart_failed(\n hass: HomeAssistant,\n client,\n supervisor,\n integration,\n addon_running,\n addon_options,\n set_addon_options,\n restart_addon,\n get_addon_discovery_info,\n discovery_info,\n entry_data,\n old_addon_options,\n new_addon_options,\n disconnect_calls,\n restart_addon_side_effect,\n) -> None:\n \"\"\"Test options flow and add-on restart failure.\"\"\"\n addon_options.update(old_addon_options)\n entry = integration\n data = {**entry.data, **entry_data}\n hass.config_entries.async_update_entry(entry, data=data, unique_id=\"1234\")\n\n assert entry.data[\"url\"] == \"ws://test.org\"\n\n assert client.connect.call_count == 1\n assert client.disconnect.call_count == 0\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"on_supervisor\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"], {\"use_addon\": True}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"configure_addon\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n new_addon_options,\n )\n\n assert set_addon_options.call_count == 1\n new_addon_options[\"device\"] = new_addon_options.pop(\"usb_path\")\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": new_addon_options},\n )\n assert client.disconnect.call_count == disconnect_calls\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n\n assert restart_addon.call_count == 1\n assert restart_addon.call_args == call(hass, \"core_zwave_js\")\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n\n # The legacy network key should not be reset.\n old_addon_options.pop(\"network_key\")\n assert set_addon_options.call_count == 2\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": old_addon_options},\n )\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n\n assert restart_addon.call_count == 2\n assert restart_addon.call_args == call(hass, \"core_zwave_js\")\n\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n\n assert result[\"type\"] is FlowResultType.ABORT\n assert result[\"reason\"] == \"addon_start_failed\"\n assert entry.data == data\n assert client.connect.call_count == 2\n assert client.disconnect.call_count == 1", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def call_nmcli(\n self,\n args,\n langs=None,\n lang=None,\n check_on_disk=_DEFAULT_ARG,\n fatal_warnings=_DEFAULT_ARG,\n expected_returncode=_DEFAULT_ARG,\n expected_stdout=_DEFAULT_ARG,\n expected_stderr=_DEFAULT_ARG,\n replace_stdout=None,\n replace_stderr=None,\n replace_cmd=None,\n sort_lines_stdout=False,\n extra_env=None,\n sync_barrier=None,\n ):\n frame = sys._getframe(1)\n\n if langs is not None:\n assert lang is None\n else:\n if lang is None:\n lang = \"C\"\n langs = [lang]\n\n if sync_barrier is None:\n sync_barrier = len(langs) == 1\n\n for lang in langs:\n self._call_nmcli(\n args,\n lang,\n check_on_disk,\n fatal_warnings,\n expected_returncode,\n expected_stdout,\n expected_stderr,\n replace_stdout,\n replace_stderr,\n replace_cmd,\n sort_lines_stdout,\n extra_env,\n sync_barrier,\n frame,\n )", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n def __call__(\n self,\n input_ids,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n params: dict = None,\n dropout_rng: jax.random.PRNGKey = None,\n train: bool = False,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n past_key_values: dict = None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n\n # init input tensors if not passed\n if token_type_ids is None:\n token_type_ids = jnp.zeros_like(input_ids)\n\n if position_ids is None:\n position_ids = create_position_ids_from_input_ids(input_ids, self.config.pad_token_id)\n\n if attention_mask is None:\n attention_mask = jnp.ones_like(input_ids)\n\n if head_mask is None:\n head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))\n\n # Handle any PRNG if needed\n rngs = {}\n if dropout_rng is not None:\n rngs[\"dropout\"] = dropout_rng\n\n inputs = {\"params\": params or self.params}\n\n if self.config.add_cross_attention:\n # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed\n # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be\n # changed by FlaxRobertaAttention module\n if past_key_values:\n inputs[\"cache\"] = past_key_values\n mutable = [\"cache\"]\n else:\n mutable = False\n\n outputs = self.module.apply(\n inputs,\n jnp.array(input_ids, dtype=\"i4\"),\n jnp.array(attention_mask, dtype=\"i4\"),\n token_type_ids=jnp.array(token_type_ids, dtype=\"i4\"),\n position_ids=jnp.array(position_ids, dtype=\"i4\"),\n head_mask=jnp.array(head_mask, dtype=\"i4\"),\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n deterministic=not train,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n rngs=rngs,\n mutable=mutable,\n )\n\n # add updated cache to model output\n if past_key_values is not None and return_dict:\n outputs, past_key_values = outputs\n outputs[\"past_key_values\"] = unfreeze(past_key_values[\"cache\"])\n return outputs\n elif past_key_values is not None and not return_dict:\n outputs, past_key_values = outputs\n outputs = outputs[:1] + (unfreeze(past_key_values[\"cache\"]),) + outputs[1:]\n\n else:\n outputs = self.module.apply(\n inputs,\n jnp.array(input_ids, dtype=\"i4\"),\n jnp.array(attention_mask, dtype=\"i4\"),\n token_type_ids=jnp.array(token_type_ids, dtype=\"i4\"),\n position_ids=jnp.array(position_ids, dtype=\"i4\"),\n head_mask=jnp.array(head_mask, dtype=\"i4\"),\n deterministic=not train,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n rngs=rngs,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_token_type_ids=True,\n use_input_mask=True,\n use_labels=True,\n use_mc_token_ids=True,\n vocab_size=99,\n hidden_size=32,\n rotary_dim=4,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.rotary_dim = rotary_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n import_ctx: list[tuple[str, int]],\n *,\n file: str,\n module: str | None,\n typ: str | None,\n function_or_member: str | None,\n line: int,\n column: int,\n end_line: int,\n end_column: int,\n severity: str,\n message: str,\n code: ErrorCode | None,\n blocker: bool,\n only_once: bool,\n allow_dups: bool,\n origin: tuple[str, Iterable[int]] | None = None,\n target: str | None = None,\n priority: int = 0,\n ) -> None:\n self.import_ctx = import_ctx\n self.file = file\n self.module = module\n self.type = typ\n self.function_or_member = function_or_member\n self.line = line\n self.column = column\n self.end_line = end_line\n self.end_column = end_column\n self.severity = severity\n self.message = message\n self.code = code\n self.blocker = blocker\n self.only_once = only_once\n self.allow_dups = allow_dups\n self.origin = origin or (file, [line])\n self.target = target\n self.priority = priority", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _bigbird_block_rand_mask_with_head(\n self,\n from_seq_length,\n to_seq_length,\n from_block_size,\n to_block_size,\n num_heads,\n plan_from_length,\n plan_num_rand_blocks,\n indices_prng_key: Optional[jax.random.PRNGKey] = None,\n deterministic: Optional[bool] = True,\n window_block_left=1,\n window_block_right=1,\n global_block_top=1,\n global_block_bottom=1,\n global_block_left=1,\n global_block_right=1,\n ):\n \"\"\"\n Create adjacency list of random attention.\n\n Args:\n from_seq_length: int. length of from sequence.\n to_seq_length: int. length of to sequence.\n from_block_size: int. size of block in from sequence.\n to_block_size: int. size of block in to sequence.\n num_heads: int. total number of heads.\n plan_from_length: list. plan from length where num_random_blocks are choosen from.\n plan_num_rand_blocks: list. number of rand blocks within the plan.\n indices_prng_key: jax.random.PRNGKey. PRNG key that is used to perform random jax operations.\n deterministic: bool. When False random attention will be used.\n window_block_left: int. number of blocks of window to left of a block.\n window_block_right: int. number of blocks of window to right of a block.\n global_block_top: int. number of blocks at the top.\n global_block_bottom: int. number of blocks at the bottom.\n global_block_left: int. Number of blocks globally used to the left.\n global_block_right: int. Number of blocks globally used to the right.\n\n Returns:\n adjacency list of size num_head where each element is of size from_seq_length//from_block_size-2 by\n num_rand_blocks\n \"\"\"\n # using this method when from_seq_length not in [1024, 3072, 4096]\n\n if from_seq_length // from_block_size != to_seq_length // to_block_size:\n raise ValueError(\"Error the number of blocks needs to be same!\")\n\n if from_seq_length not in plan_from_length:\n raise ValueError(\"Error from sequence length not in plan!\")\n\n # Total number of blocks in the mmask\n num_blocks = from_seq_length // from_block_size\n # Number of blocks per plan\n plan_block_length = jnp.array(plan_from_length) // from_block_size\n # till when to follow plan\n max_plan_idx = plan_from_length.index(from_seq_length)\n\n # Random Attention adjacency list\n rand_attn = [\n jnp.zeros((num_blocks, sum(plan_num_rand_blocks[: max_plan_idx + 1])), dtype=jnp.int32)\n for i in range(num_heads)\n ]\n\n # deterministic\n if deterministic:\n for nh in range(num_heads):\n rand_attn[nh] = rand_attn[nh][global_block_top : num_blocks - global_block_bottom, :]\n return rand_attn\n\n # We will go iteratively over the plan blocks and pick random number of\n # Attention blocks from the legally allowed blocks\n for plan_idx in range(max_plan_idx + 1):\n rnd_r_cnt = 0\n if plan_idx > 0:\n # set the row for all from_blocks starting from 0 to\n # plan_block_length[plan_idx-1]\n # column indx start fromm plan_block_length[plan_idx-1] and ends at\n # plan_block_length[plan_idx]\n if plan_num_rand_blocks[plan_idx] > 0:\n rnd_r_cnt = int(sum(plan_num_rand_blocks[:plan_idx]))\n curr_r_cnt = int(sum(plan_num_rand_blocks[: plan_idx + 1]))\n for blk_rw_idx in range(global_block_top, plan_block_length[plan_idx - 1]):\n for h in range(num_heads):\n single_block_row_attention = self._get_single_block_row_attention(\n block_id=blk_rw_idx,\n to_start_block_id=plan_block_length[plan_idx - 1],\n to_end_block_id=plan_block_length[plan_idx],\n num_rand_blocks=plan_num_rand_blocks[plan_idx],\n window_block_left=window_block_left,\n window_block_right=window_block_right,\n global_block_left=global_block_left,\n global_block_right=global_block_right,\n indices_prng_key=indices_prng_key,\n )\n rand_attn[h] = (\n rand_attn[h].at[blk_rw_idx, rnd_r_cnt:curr_r_cnt].set(single_block_row_attention)\n )\n\n for pl_id in range(plan_idx):\n if plan_num_rand_blocks[pl_id] == 0:\n continue\n for blk_rw_idx in range(plan_block_length[plan_idx - 1], plan_block_length[plan_idx]):\n rnd_r_cnt = 0\n to_start_block_id = 0\n if pl_id > 0:\n rnd_r_cnt = int(sum(plan_num_rand_blocks[:pl_id]))\n to_start_block_id = plan_block_length[pl_id - 1]\n curr_r_cnt = int(sum(plan_num_rand_blocks[: pl_id + 1]))\n for h in range(num_heads):\n single_block_row_attention = self._get_single_block_row_attention(\n block_id=blk_rw_idx,\n to_start_block_id=to_start_block_id,\n to_end_block_id=plan_block_length[pl_id],\n num_rand_blocks=plan_num_rand_blocks[pl_id],\n window_block_left=window_block_left,\n window_block_right=window_block_right,\n global_block_left=global_block_left,\n global_block_right=global_block_right,\n indices_prng_key=indices_prng_key,\n )\n rand_attn[h] = (\n rand_attn[h].at[blk_rw_idx, rnd_r_cnt:curr_r_cnt].set(single_block_row_attention)\n )\n\n if plan_num_rand_blocks[plan_idx] == 0:\n continue\n curr_r_cnt = int(sum(plan_num_rand_blocks[: plan_idx + 1]))\n from_start_block_id = global_block_top\n to_start_block_id = 0\n if plan_idx > 0:\n rnd_r_cnt = int(sum(plan_num_rand_blocks[:plan_idx]))\n from_start_block_id = plan_block_length[plan_idx - 1]\n to_start_block_id = plan_block_length[plan_idx - 1]\n for blk_rw_idx in range(from_start_block_id, plan_block_length[plan_idx]):\n for h in range(num_heads):\n single_block_row_attention = self._get_single_block_row_attention(\n block_id=blk_rw_idx,\n to_start_block_id=to_start_block_id,\n to_end_block_id=plan_block_length[plan_idx],\n num_rand_blocks=plan_num_rand_blocks[plan_idx],\n window_block_left=window_block_left,\n window_block_right=window_block_right,\n global_block_left=global_block_left,\n global_block_right=global_block_right,\n indices_prng_key=indices_prng_key,\n )\n rand_attn[h] = rand_attn[h].at[blk_rw_idx, rnd_r_cnt:curr_r_cnt].set(single_block_row_attention)\n\n for nh in range(num_heads):\n rand_attn[nh] = rand_attn[nh][global_block_top : num_blocks - global_block_bottom, :]\n return rand_attn", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n verbose_name=None,\n name=None,\n primary_key=False,\n max_length=None,\n unique=False,\n blank=False,\n null=False,\n db_index=False,\n rel=None,\n default=NOT_PROVIDED,\n editable=True,\n serialize=True,\n unique_for_date=None,\n unique_for_month=None,\n unique_for_year=None,\n choices=None,\n help_text=\"\",\n db_column=None,\n db_tablespace=None,\n auto_created=False,\n validators=(),\n error_messages=None,\n db_comment=None,\n db_default=NOT_PROVIDED,\n ):\n self.name = name\n self.verbose_name = verbose_name # May be set by set_attributes_from_name\n self._verbose_name = verbose_name # Store original for deconstruction\n self.primary_key = primary_key\n self.max_length, self._unique = max_length, unique\n self.blank, self.null = blank, null\n self.remote_field = rel\n self.is_relation = self.remote_field is not None\n self.default = default\n self.db_default = db_default\n self.editable = editable\n self.serialize = serialize\n self.unique_for_date = unique_for_date\n self.unique_for_month = unique_for_month\n self.unique_for_year = unique_for_year\n self.choices = choices\n self.help_text = help_text\n self.db_index = db_index\n self.db_column = db_column\n self.db_comment = db_comment\n self._db_tablespace = db_tablespace\n self.auto_created = auto_created\n\n # Adjust the appropriate creation counter, and save our local copy.\n if auto_created:\n self.creation_counter = Field.auto_creation_counter\n Field.auto_creation_counter -= 1\n else:\n self.creation_counter = Field.creation_counter\n Field.creation_counter += 1\n\n self._validators = list(validators) # Store for deconstruction later\n\n self._error_messages = error_messages # Store for deconstruction later", "smellKey": "S107", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n seq_length=7,\n # For common tests\n is_training=False,\n use_attention_mask=True,\n hidden_size=32,\n num_hidden_layers=5,\n decoder_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=32,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n scope=None,\n range_bbox=1000,\n ):\n self.parent = parent\n self.batch_size = batch_size\n # For common tests\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.decoder_layers = decoder_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.scope = None\n self.range_bbox = range_bbox", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=32,\n patch_size=4,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=1e-10,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=1024, # speech is longer\n is_training=False,\n hidden_size=24,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=4,\n vocab_size=81,\n num_mel_bins=20,\n reduction_factor=2,\n speech_decoder_postnet_layers=2,\n speech_decoder_postnet_units=32,\n speech_decoder_prenet_units=32,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.vocab_size = vocab_size\n self.num_mel_bins = num_mel_bins\n self.reduction_factor = reduction_factor\n self.speech_decoder_postnet_layers = speech_decoder_postnet_layers\n self.speech_decoder_postnet_units = speech_decoder_postnet_units\n self.speech_decoder_prenet_units = speech_decoder_prenet_units", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=7,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=False,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n scope=None,\n decoder_layers=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = decoder_layers", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=250002,\n hidden_size=1024,\n num_hidden_layers=24,\n num_attention_heads=16,\n intermediate_size=4096,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=514,\n type_vocab_size=1,\n initializer_range=0.02,\n initializer_factor=0.02,\n layer_norm_eps=1e-05,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n position_embedding_type=\"absolute\",\n use_cache=True,\n project_dim=768,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.project_dim = project_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_clusters_v3_get_serialize(\n self,\n address,\n azure_subscription,\n base,\n created_at,\n google_project,\n helmfile_ref,\n id,\n location,\n name,\n provider,\n required_role,\n requires_suitability,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if address is not None:\n \n _query_params.append(('address', address))\n \n if azure_subscription is not None:\n \n _query_params.append(('azureSubscription', azure_subscription))\n \n if base is not None:\n \n _query_params.append(('base', base))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if google_project is not None:\n \n _query_params.append(('googleProject', google_project))\n \n if helmfile_ref is not None:\n \n _query_params.append(('helmfileRef', helmfile_ref))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if location is not None:\n \n _query_params.append(('location', location))\n \n if name is not None:\n \n _query_params.append(('name', name))\n \n if provider is not None:\n \n _query_params.append(('provider', provider))\n \n if required_role is not None:\n \n _query_params.append(('requiredRole', required_role))\n \n if requires_suitability is not None:\n \n _query_params.append(('requiresSuitability', requires_suitability))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/clusters/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n hidden_size=2048,\n num_hidden_layers=12,\n num_key_value_heads=16,\n kv_channels=128,\n intermediate_size=5632,\n max_position_embeddings=4096,\n activation_function=\"silu\",\n num_local_experts=8,\n num_experts_per_tok=2,\n output_router_logits=False,\n aux_loss_coef=0.01,\n use_cache=True,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=True,\n rope_theta=10000.0,\n rms_norm_eps=1e-6,\n initializer_range=0.01,\n attention_dropout=0.0,\n **kwargs,\n ):\n if num_experts_per_tok > num_local_experts:\n raise ValueError(\"`num_experts_per_tok` must be less than or equal to `num_local_experts`\")\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_key_value_heads * num_experts_per_tok\n self.num_key_value_heads = num_key_value_heads\n self.kv_channels = kv_channels\n self.intermediate_size = intermediate_size\n self.max_position_embeddings = max_position_embeddings\n self.activation_function = activation_function\n self.num_local_experts = num_local_experts\n self.num_experts_per_tok = num_experts_per_tok\n self.output_router_logits = output_router_logits\n self.aux_loss_coef = aux_loss_coef\n self.use_cache = use_cache\n self.initializer_range = initializer_range\n self.attention_dropout = attention_dropout\n\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n\n self.rope_theta = rope_theta\n self.rms_norm_eps = rms_norm_eps\n\n super().__init__(\n bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout=0.1,\n activation_dropout=0.1,\n attention_dropout=0.1,\n feat_proj_dropout=0.0,\n feat_quantizer_dropout=0.0,\n final_dropout=0.1,\n layerdrop=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n feat_extract_norm=\"group\",\n feat_extract_activation=\"gelu\",\n conv_dim=(512, 512, 512, 512, 512, 512, 512),\n conv_stride=(5, 2, 2, 2, 2, 2, 2),\n conv_kernel=(10, 3, 3, 3, 3, 2, 2),\n conv_bias=False,\n num_conv_pos_embeddings=128,\n num_conv_pos_embedding_groups=16,\n do_stable_layer_norm=False,\n apply_spec_augment=True,\n mask_time_prob=0.05,\n mask_time_length=10,\n mask_time_min_masks=2,\n mask_feature_prob=0.0,\n mask_feature_length=10,\n mask_feature_min_masks=0,\n num_codevectors_per_group=320,\n num_codevector_groups=2,\n contrastive_logits_temperature=0.1,\n num_negatives=100,\n codevector_dim=256,\n proj_codevector_dim=256,\n diversity_loss_weight=0.1,\n ctc_loss_reduction=\"mean\",\n ctc_zero_infinity=False,\n use_weighted_layer_sum=False,\n classifier_proj_size=256,\n tdnn_dim=(512, 512, 512, 512, 1500),\n tdnn_kernel=(5, 3, 3, 1, 1),\n tdnn_dilation=(1, 2, 3, 1, 1),\n xvector_output_dim=512,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n num_clusters=504,\n **kwargs,\n ):\n super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = list(conv_dim)\n self.conv_stride = list(conv_stride)\n self.conv_kernel = list(conv_kernel)\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_feat_extract_layers = len(self.conv_dim)\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.feat_proj_dropout = feat_proj_dropout\n self.final_dropout = final_dropout\n self.layerdrop = layerdrop\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.num_clusters = num_clusters\n self.do_stable_layer_norm = do_stable_layer_norm\n self.use_weighted_layer_sum = use_weighted_layer_sum\n\n if (\n (len(self.conv_stride) != self.num_feat_extract_layers)\n or (len(self.conv_kernel) != self.num_feat_extract_layers)\n or (len(self.conv_dim) != self.num_feat_extract_layers)\n ):\n raise ValueError(\n \"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==\"\n \" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =\"\n f\" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,\"\n f\" `len(config.conv_kernel) = {len(self.conv_kernel)}`.\"\n )\n\n # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779\n self.apply_spec_augment = apply_spec_augment\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.mask_time_min_masks = mask_time_min_masks\n self.mask_feature_prob = mask_feature_prob\n self.mask_feature_length = mask_feature_length\n self.mask_feature_min_masks = mask_feature_min_masks\n\n # parameters for pretraining with codevector quantized representations\n self.num_codevectors_per_group = num_codevectors_per_group\n self.num_codevector_groups = num_codevector_groups\n self.contrastive_logits_temperature = contrastive_logits_temperature\n self.feat_quantizer_dropout = feat_quantizer_dropout\n self.num_negatives = num_negatives\n self.codevector_dim = codevector_dim\n self.proj_codevector_dim = proj_codevector_dim\n self.diversity_loss_weight = diversity_loss_weight\n\n # ctc loss\n self.ctc_loss_reduction = ctc_loss_reduction\n self.ctc_zero_infinity = ctc_zero_infinity\n\n # SequenceClassification-specific parameter. Feel free to ignore for other classes.\n self.classifier_proj_size = classifier_proj_size\n\n # XVector-specific parameters. Feel free to ignore for other classes.\n self.tdnn_dim = list(tdnn_dim)\n self.tdnn_kernel = list(tdnn_kernel)\n self.tdnn_dilation = list(tdnn_dilation)\n self.xvector_output_dim = xvector_output_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n embed_dim=16,\n word_embed_proj_dim=16,\n initializer_range=0.02,\n attn_implemetation=\"eager\",\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.embed_dim = embed_dim\n self.word_embed_proj_dim = word_embed_proj_dim\n self.initializer_range = initializer_range\n self.is_encoder_decoder = False\n self.attn_implementation = attn_implemetation", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def command(\n conn: Connection,\n dbname: str,\n spec: MutableMapping[str, Any],\n is_mongos: bool,\n read_preference: Optional[_ServerMode],\n codec_options: CodecOptions[_DocumentType],\n session: Optional[ClientSession],\n client: Optional[MongoClient],\n check: bool = True,\n allowable_errors: Optional[Sequence[Union[str, int]]] = None,\n address: Optional[_Address] = None,\n listeners: Optional[_EventListeners] = None,\n max_bson_size: Optional[int] = None,\n read_concern: Optional[ReadConcern] = None,\n parse_write_concern_error: bool = False,\n collation: Optional[_CollationIn] = None,\n compression_ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None,\n use_op_msg: bool = False,\n unacknowledged: bool = False,\n user_fields: Optional[Mapping[str, Any]] = None,\n exhaust_allowed: bool = False,\n write_concern: Optional[WriteConcern] = None,\n) -> _DocumentType:\n \"\"\"Execute a command over the socket, or raise socket.error.\n\n :param conn: a Connection instance\n :param dbname: name of the database on which to run the command\n :param spec: a command document as an ordered dict type, eg SON.\n :param is_mongos: are we connected to a mongos?\n :param read_preference: a read preference\n :param codec_options: a CodecOptions instance\n :param session: optional ClientSession instance.\n :param client: optional MongoClient instance for updating $clusterTime.\n :param check: raise OperationFailure if there are errors\n :param allowable_errors: errors to ignore if `check` is True\n :param address: the (host, port) of `conn`\n :param listeners: An instance of :class:`~pymongo.monitoring.EventListeners`\n :param max_bson_size: The maximum encoded bson size for this server\n :param read_concern: The read concern for this command.\n :param parse_write_concern_error: Whether to parse the ``writeConcernError``\n field in the command response.\n :param collation: The collation for this command.\n :param compression_ctx: optional compression Context.\n :param use_op_msg: True if we should use OP_MSG.\n :param unacknowledged: True if this is an unacknowledged command.\n :param user_fields: Response fields that should be decoded\n using the TypeDecoders from codec_options, passed to\n bson._decode_all_selective.\n :param exhaust_allowed: True if we should enable OP_MSG exhaustAllowed.\n \"\"\"\n name = next(iter(spec))\n ns = dbname + \".$cmd\"\n speculative_hello = False\n\n # Publish the original command document, perhaps with lsid and $clusterTime.\n orig = spec\n if is_mongos and not use_op_msg:\n assert read_preference is not None\n spec = message._maybe_add_read_preference(spec, read_preference)\n if read_concern and not (session and session.in_transaction):\n if read_concern.level:\n spec[\"readConcern\"] = read_concern.document\n if session:\n session._update_read_concern(spec, conn)\n if collation is not None:\n spec[\"collation\"] = collation\n\n publish = listeners is not None and listeners.enabled_for_commands\n start = datetime.datetime.now()\n if publish:\n speculative_hello = _is_speculative_authenticate(name, spec)\n\n if compression_ctx and name.lower() in _NO_COMPRESSION:\n compression_ctx = None\n\n if client and client._encrypter and not client._encrypter._bypass_auto_encryption:\n spec = orig = client._encrypter.encrypt(dbname, spec, codec_options)\n\n # Support CSOT\n if client:\n conn.apply_timeout(client, spec)\n _csot.apply_write_concern(spec, write_concern)\n\n if use_op_msg:\n flags = _OpMsg.MORE_TO_COME if unacknowledged else 0\n flags |= _OpMsg.EXHAUST_ALLOWED if exhaust_allowed else 0\n request_id, msg, size, max_doc_size = message._op_msg(\n flags, spec, dbname, read_preference, codec_options, ctx=compression_ctx\n )\n # If this is an unacknowledged write then make sure the encoded doc(s)\n # are small enough, otherwise rely on the server to return an error.\n if unacknowledged and max_bson_size is not None and max_doc_size > max_bson_size:\n message._raise_document_too_large(name, size, max_bson_size)\n else:\n request_id, msg, size = message._query(\n 0, ns, 0, -1, spec, None, codec_options, compression_ctx\n )\n\n if max_bson_size is not None and size > max_bson_size + message._COMMAND_OVERHEAD:\n message._raise_document_too_large(name, size, max_bson_size + message._COMMAND_OVERHEAD)\n if client is not None:\n if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG):\n _debug_log(\n _COMMAND_LOGGER,\n clientId=client._topology_settings._topology_id,\n message=_CommandStatusMessage.STARTED,\n command=spec,\n commandName=next(iter(spec)),\n databaseName=dbname,\n requestId=request_id,\n operationId=request_id,\n driverConnectionId=conn.id,\n serverConnectionId=conn.server_connection_id,\n serverHost=conn.address[0],\n serverPort=conn.address[1],\n serviceId=conn.service_id,\n )\n if publish:\n assert listeners is not None\n assert address is not None\n listeners.publish_command_start(\n orig,\n dbname,\n request_id,\n address,\n conn.server_connection_id,\n service_id=conn.service_id,\n )\n\n try:\n conn.conn.sendall(msg)\n if use_op_msg and unacknowledged:\n # Unacknowledged, fake a successful command response.\n reply = None\n response_doc: _DocumentOut = {\"ok\": 1}\n else:\n reply = receive_message(conn, request_id)\n conn.more_to_come = reply.more_to_come\n unpacked_docs = reply.unpack_response(\n codec_options=codec_options, user_fields=user_fields\n )\n\n response_doc = unpacked_docs[0]\n if client:\n client._process_response(response_doc, session)\n if check:\n helpers._check_command_response(\n response_doc,\n conn.max_wire_version,\n allowable_errors,\n parse_write_concern_error=parse_write_concern_error,\n )\n except Exception as exc:\n duration = datetime.datetime.now() - start\n if isinstance(exc, (NotPrimaryError, OperationFailure)):\n failure: _DocumentOut = exc.details # type: ignore[assignment]\n else:\n failure = message._convert_exception(exc)\n if client is not None:\n if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG):\n _debug_log(\n _COMMAND_LOGGER,\n clientId=client._topology_settings._topology_id,\n message=_CommandStatusMessage.FAILED,\n durationMS=duration,\n failure=failure,\n commandName=next(iter(spec)),\n databaseName=dbname,\n requestId=request_id,\n operationId=request_id,\n driverConnectionId=conn.id,\n serverConnectionId=conn.server_connection_id,\n serverHost=conn.address[0],\n serverPort=conn.address[1],\n serviceId=conn.service_id,\n isServerSideError=isinstance(exc, OperationFailure),\n )\n if publish:\n assert listeners is not None\n assert address is not None\n listeners.publish_command_failure(\n duration,\n failure,\n name,\n request_id,\n address,\n conn.server_connection_id,\n service_id=conn.service_id,\n database_name=dbname,\n )\n raise\n duration = datetime.datetime.now() - start\n if client is not None:\n if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG):\n _debug_log(\n _COMMAND_LOGGER,\n clientId=client._topology_settings._topology_id,\n message=_CommandStatusMessage.SUCCEEDED,\n durationMS=duration,\n reply=response_doc,\n commandName=next(iter(spec)),\n databaseName=dbname,\n requestId=request_id,\n operationId=request_id,\n driverConnectionId=conn.id,\n serverConnectionId=conn.server_connection_id,\n serverHost=conn.address[0],\n serverPort=conn.address[1],\n serviceId=conn.service_id,\n speculative_authenticate=\"speculativeAuthenticate\" in orig,\n )\n if publish:\n assert listeners is not None\n assert address is not None\n listeners.publish_command_success(\n duration,\n response_doc,\n name,\n request_id,\n address,\n conn.server_connection_id,\n service_id=conn.service_id,\n speculative_hello=speculative_hello,\n database_name=dbname,\n )\n\n if client and client._encrypter and reply:\n decrypted = client._encrypter.decrypt(reply.raw_command_response())\n response_doc = cast(\n \"_DocumentOut\", _decode_all_selective(decrypted, codec_options, user_fields)[0]\n )\n\n return response_doc # type: ignore[return-value]", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def f(\n add: a + b,\n sub: a - b,\n mul: a * b,\n matmul: a @ b,\n truediv: a / b,\n mod: a % b,\n lshift: a << b,\n rshift: a >> b,\n or_: a | b,\n xor: a ^ b,\n and_: a & b,\n floordiv: a // b,\n pow_: a**b,\n lt: a < b,\n le: a <= b,\n eq: a == b,\n ne: a != b,\n gt: a > b,\n ge: a >= b,\n invert: ~a,\n neg: -a,\n pos: +a,\n getitem: a[b],\n getattr: a.b,\n call: a(b, *c, d=e), # **kwargs are not supported\n *args: *a,\n ):\n pass", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(\n self,\n load_p: np.ndarray,\n load_q: np.ndarray,\n prod_p: np.ndarray,\n prod_v: Optional[np.ndarray] = None,\n hazards: Optional[np.ndarray] = None,\n maintenance: Optional[np.ndarray] = None,\n load_p_forecast: Optional[np.ndarray] = None, # TODO forecasts !!\n load_q_forecast: Optional[np.ndarray] = None,\n prod_p_forecast: Optional[np.ndarray] = None,\n prod_v_forecast: Optional[np.ndarray] = None,\n time_interval: timedelta = timedelta(minutes=5),\n max_iter: int = -1,\n start_datetime: datetime = datetime(year=2019, month=1, day=1),\n chunk_size: Optional[int] = None,\n i_start: Optional[int] = None,\n i_end: Optional[int] = None, # excluded, as always in python\n init_state: Optional[\"grid2op.Action.BaseAction\"] = None,\n **kwargs\n ):\n GridValue.__init__(\n self,\n time_interval=time_interval,\n max_iter=max_iter,\n start_datetime=start_datetime,\n chunk_size=chunk_size,\n )\n self._i_start: int = i_start if i_start is not None else 0\n self.__new_istart: Optional[int] = i_start\n self.n_gen: int = prod_p.shape[1]\n self.n_load: int = load_p.shape[1]\n self.n_line: Union[int, None] = None\n\n self._load_p: np.ndarray = 1.0 * load_p\n self._load_q: np.ndarray = 1.0 * load_q\n self._prod_p: np.ndarray = 1.0 * prod_p\n\n self._prod_v = None\n if prod_v is not None:\n self._prod_v = 1.0 * prod_v\n\n self.__new_load_p: Optional[np.ndarray] = None\n self.__new_prod_p: Optional[np.ndarray] = None\n self.__new_prod_v: Optional[np.ndarray] = None\n self.__new_load_q: Optional[np.ndarray] = None\n\n self._i_end: int = i_end if i_end is not None else load_p.shape[0]\n self.__new_iend: Optional[int] = i_end\n\n self.has_maintenance = False\n self.maintenance = None\n self.maintenance_duration = None\n self.maintenance_time = None\n if maintenance is not None:\n self.has_maintenance = True\n self.n_line = maintenance.shape[1]\n assert load_p.shape[0] == maintenance.shape[0]\n self.maintenance = maintenance # TODO copy\n\n self.maintenance_time = (\n np.zeros(shape=(self.maintenance.shape[0], self.n_line), dtype=dt_int)\n - 1\n )\n self.maintenance_duration = np.zeros(\n shape=(self.maintenance.shape[0], self.n_line), dtype=dt_int\n )\n for line_id in range(self.n_line):\n self.maintenance_time[:, line_id] = self.get_maintenance_time_1d(\n self.maintenance[:, line_id]\n )\n self.maintenance_duration[\n :, line_id\n ] = self.get_maintenance_duration_1d(self.maintenance[:, line_id])\n\n self.has_hazards = False\n self.hazards = None\n self.hazard_duration = None\n if hazards is not None:\n raise ChronicsError(\n \"This feature is not available at the moment. Fill a github issue at \"\n \"https://github.com/Grid2Op/grid2op/issues/new?assignees=&labels=enhancement&template=feature_request.md&title=\"\n )\n\n self._forecasts = None\n if load_p_forecast is not None:\n assert load_q_forecast is not None\n assert prod_p_forecast is not None\n self._forecasts = FromNPY(\n load_p=load_p_forecast,\n load_q=load_q_forecast,\n prod_p=prod_p_forecast,\n prod_v=prod_v_forecast,\n load_p_forecast=None,\n load_q_forecast=None,\n prod_p_forecast=None,\n prod_v_forecast=None,\n i_start=i_start,\n i_end=i_end,\n )\n elif load_q_forecast is not None:\n raise ChronicsError(\n \"if load_q_forecast is not None, then load_p_forecast should not be None\"\n )\n elif prod_p_forecast is not None:\n raise ChronicsError(\n \"if prod_p_forecast is not None, then load_p_forecast should not be None\"\n )\n \n self._init_state = init_state\n self._max_iter = min(self._i_end - self._i_start, load_p.shape[0])", "smellKey": "S107", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(PIX2STRUCT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n flattened_patches: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n labels: Optional[torch.LongTensor] = None,\n decoder_inputs_embeds: Optional[torch.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n Inference:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, Pix2StructForConditionalGeneration\n\n >>> processor = AutoProcessor.from_pretrained(\"google/pix2struct-textcaps-base\")\n >>> model = Pix2StructForConditionalGeneration.from_pretrained(\"google/pix2struct-textcaps-base\")\n\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n\n >>> # autoregressive generation\n >>> generated_ids = model.generate(**inputs, max_new_tokens=50)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\n >>> print(generated_text)\n A stop sign is on a street corner.\n\n >>> # conditional generation\n >>> text = \"A picture of\"\n >>> inputs = processor(text=text, images=image, return_tensors=\"pt\", add_special_tokens=False)\n\n >>> generated_ids = model.generate(**inputs, max_new_tokens=50)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\n >>> print(generated_text)\n A picture of a stop sign with a red stop sign\n ```\n\n Training:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, Pix2StructForConditionalGeneration\n\n >>> processor = AutoProcessor.from_pretrained(\"google/pix2struct-base\")\n >>> model = Pix2StructForConditionalGeneration.from_pretrained(\"google/pix2struct-base\")\n\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> text = \"A stop sign is on the street corner.\"\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n >>> labels = processor(text=text, return_tensors=\"pt\").input_ids\n\n >>> # forward pass\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> print(f\"{loss.item():.5f}\")\n 5.94282\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.text_config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n flattened_patches=flattened_patches,\n attention_mask=attention_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n decoder_attention_mask = (\n decoder_attention_mask\n if decoder_attention_mask is not None\n else decoder_input_ids.ne(self.config.pad_token_id).float()\n )\n # Always attend to the first token\n decoder_attention_mask[:, 0] = 1\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n labels=labels,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqLMOutput(\n loss=decoder_outputs.loss,\n logits=decoder_outputs.logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=1,\n seq_length=7,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=5,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n alpha_initializer=\"ones\",\n num_labels=3,\n scope=None,\n modality_type_vocab_size=2,\n vision_embed_dim=32,\n vision_patch_size=2,\n vision_image_size=30,\n vision_num_attention_heads=4,\n vision_num_hidden_layers=5,\n vision_intermediate_size=37,\n perceiver_qk_layer_norms_perceiver=False,\n perceiver_resampler_depth=2,\n perceiver_resampler_head_dim=8,\n perceiver_resampler_n_heads=2,\n perceiver_resampler_n_latents=16,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.alpha_initializer = alpha_initializer\n self.num_labels = num_labels\n self.scope = scope\n self.modality_type_vocab_size = modality_type_vocab_size\n\n self.vision_embed_dim = vision_embed_dim\n self.vision_patch_size = vision_patch_size\n self.vision_image_size = vision_image_size\n self.vision_num_attention_heads = vision_num_attention_heads\n self.vision_num_hidden_layers = vision_num_hidden_layers\n self.vision_intermediate_size = vision_intermediate_size\n\n self.vision_config = IdeficsVisionConfig(\n embed_dim=self.vision_embed_dim,\n patch_size=self.vision_patch_size,\n image_size=self.vision_image_size,\n num_attention_heads=self.vision_num_attention_heads,\n num_hidden_layers=self.vision_num_hidden_layers,\n intermediate_size=self.vision_intermediate_size,\n )\n\n self.perceiver_qk_layer_norms_perceiver = perceiver_qk_layer_norms_perceiver\n self.perceiver_resampler_depth = perceiver_resampler_depth\n self.perceiver_resampler_head_dim = perceiver_resampler_head_dim\n self.perceiver_resampler_n_heads = perceiver_resampler_n_heads\n self.perceiver_resampler_n_latents = perceiver_resampler_n_latents\n\n self.perceiver_config = IdeficsPerceiverConfig(\n qk_layer_norms_perceiver=self.perceiver_qk_layer_norms_perceiver,\n resampler_depth=self.perceiver_resampler_depth,\n resampler_head_dim=self.perceiver_resampler_head_dim,\n resampler_n_heads=self.perceiver_resampler_n_heads,\n resampler_n_latents=self.perceiver_resampler_n_latents,\n )\n\n # we set the expected sequence length (which is used in several tests)\n # this is equal to the seq length of the text tokens + number of image patches + 1 for the CLS token\n self.expected_seq_len = self.seq_length + (self.image_size // self.patch_size) ** 2 + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_chart_versions_v3_get(\n self,\n authored_by: Optional[StrictStr] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n chart_version: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n description: Annotated[Optional[StrictStr], Field(description=\"Generally the Git commit message\")] = None,\n id: Optional[StrictInt] = None,\n parent_chart_version: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many ChartVersions are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned ChartVersions (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockChartVersionV3]:\n \"\"\"List ChartVersions matching a filter\n\n List ChartVersions matching a filter.\n\n :param authored_by:\n :type authored_by: str\n :param chart: Required when creating\n :type chart: str\n :param chart_version: Required when creating\n :type chart_version: str\n :param created_at:\n :type created_at: datetime\n :param description: Generally the Git commit message\n :type description: str\n :param id:\n :type id: int\n :param parent_chart_version:\n :type parent_chart_version: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many ChartVersions are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned ChartVersions (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_chart_versions_v3_get_serialize(\n authored_by=authored_by,\n chart=chart,\n chart_version=chart_version,\n created_at=created_at,\n description=description,\n id=id,\n parent_chart_version=parent_chart_version,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartVersionV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n level: Union[int, str] = logging.NOTSET,\n console: Optional[Console] = None,\n *,\n show_time: bool = True,\n omit_repeated_times: bool = True,\n show_level: bool = True,\n show_path: bool = True,\n enable_link_path: bool = True,\n highlighter: Optional[Highlighter] = None,\n markup: bool = False,\n rich_tracebacks: bool = False,\n tracebacks_width: Optional[int] = None,\n tracebacks_extra_lines: int = 3,\n tracebacks_theme: Optional[str] = None,\n tracebacks_word_wrap: bool = True,\n tracebacks_show_locals: bool = False,\n locals_max_length: int = 10,\n locals_max_string: int = 80,\n log_time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n ) -> None:\n super().__init__(level=level)\n self.console = console or get_console()\n self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()\n self._log_render = LogRender(\n show_time=show_time,\n show_level=show_level,\n show_path=show_path,\n time_format=log_time_format,\n omit_repeated_times=omit_repeated_times,\n level_width=None,\n )\n self.enable_link_path = enable_link_path\n self.markup = markup\n self.rich_tracebacks = rich_tracebacks\n self.tracebacks_width = tracebacks_width\n self.tracebacks_extra_lines = tracebacks_extra_lines\n self.tracebacks_theme = tracebacks_theme\n self.tracebacks_word_wrap = tracebacks_word_wrap\n self.tracebacks_show_locals = tracebacks_show_locals\n self.locals_max_length = locals_max_length\n self.locals_max_string = locals_max_string", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@validate_call\n def api_deploy_hooks_slack_v3_get(\n self,\n created_at: Optional[datetime] = None,\n id: Optional[StrictInt] = None,\n mention_people: Optional[StrictBool] = None,\n on_chart_release: Optional[StrictStr] = None,\n on_environment: Optional[StrictStr] = None,\n on_failure: Optional[StrictBool] = None,\n on_success: Optional[StrictBool] = None,\n slack_channel: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many SlackDeployHooks are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned SlackDeployHooks (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockSlackDeployHookV3]:\n \"\"\"List SlackDeployHooks matching a filter\n\n List SlackDeployHooks matching a filter.\n\n :param created_at:\n :type created_at: datetime\n :param id:\n :type id: int\n :param mention_people:\n :type mention_people: bool\n :param on_chart_release:\n :type on_chart_release: str\n :param on_environment:\n :type on_environment: str\n :param on_failure:\n :type on_failure: bool\n :param on_success:\n :type on_success: bool\n :param slack_channel:\n :type slack_channel: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many SlackDeployHooks are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned SlackDeployHooks (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_deploy_hooks_slack_v3_get_serialize(\n created_at=created_at,\n id=id,\n mention_people=mention_people,\n on_chart_release=on_chart_release,\n on_environment=on_environment,\n on_failure=on_failure,\n on_success=on_success,\n slack_channel=slack_channel,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockSlackDeployHookV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n backbone_config=None,\n backbone=None,\n use_pretrained_backbone=False,\n use_timm_backbone=False,\n backbone_kwargs=None,\n num_queries=900,\n max_position_embeddings=2048,\n encoder_layers=6,\n encoder_ffn_dim=2048,\n encoder_attention_heads=8,\n decoder_layers=6,\n decoder_ffn_dim=1024,\n decoder_attention_heads=8,\n encoder_layerdrop=0.0,\n is_encoder_decoder=True,\n activation_function=\"relu\",\n d_model=256,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n init_xavier_std=1.0,\n return_intermediate=True,\n auxiliary_loss=False,\n position_embedding_type=\"sine\",\n num_feature_levels=5,\n encoder_n_points=4,\n decoder_n_points=4,\n two_stage=True,\n two_stage_num_proposals=300,\n with_box_refine=True,\n assign_first_stage=True,\n assign_second_stage=True,\n class_cost=1,\n bbox_cost=5,\n giou_cost=2,\n mask_loss_coefficient=1,\n dice_loss_coefficient=1,\n bbox_loss_coefficient=5,\n giou_loss_coefficient=2,\n eos_coefficient=0.1,\n focal_alpha=0.25,\n disable_custom_kernels=True,\n **kwargs,\n ):\n if use_pretrained_backbone:\n raise ValueError(\"Pretrained backbones are not supported yet.\")\n\n if backbone_config is not None and backbone is not None:\n raise ValueError(\"You can't specify both `backbone` and `backbone_config`.\")\n\n if backbone_config is None and backbone is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\")\n backbone_config = CONFIG_MAPPING[\"resnet\"](out_features=[\"stage2\", \"stage3\", \"stage4\"])\n else:\n if isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.pop(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:\n raise ValueError(\"You can't specify both `backbone_kwargs` and `backbone_config`.\")\n\n self.backbone_config = backbone_config\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n self.num_queries = num_queries\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.init_xavier_std = init_xavier_std\n self.encoder_layerdrop = encoder_layerdrop\n self.auxiliary_loss = auxiliary_loss\n self.position_embedding_type = position_embedding_type\n # deformable attributes\n self.num_feature_levels = num_feature_levels\n self.encoder_n_points = encoder_n_points\n self.decoder_n_points = decoder_n_points\n self.two_stage = two_stage\n self.two_stage_num_proposals = two_stage_num_proposals\n self.with_box_refine = with_box_refine\n self.assign_first_stage = assign_first_stage\n self.assign_second_stage = assign_second_stage\n if two_stage is True and with_box_refine is False:\n raise ValueError(\"If two_stage is True, with_box_refine must be True.\")\n # Hungarian matcher\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n # Loss coefficients\n self.mask_loss_coefficient = mask_loss_coefficient\n self.dice_loss_coefficient = dice_loss_coefficient\n self.bbox_loss_coefficient = bbox_loss_coefficient\n self.giou_loss_coefficient = giou_loss_coefficient\n self.eos_coefficient = eos_coefficient\n self.focal_alpha = focal_alpha\n self.disable_custom_kernels = disable_custom_kernels\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n q_groups=2,\n k_groups=2,\n v_groups=2,\n post_attention_groups=2,\n intermediate_groups=4,\n output_groups=1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.q_groups = q_groups\n self.k_groups = k_groups\n self.v_groups = v_groups\n self.post_attention_groups = post_attention_groups\n self.intermediate_groups = intermediate_groups\n self.output_groups = output_groups", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n position_embedding_type=\"absolute\",\n use_cache=True,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.pad_token_id = pad_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n num_key_value_heads=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_changesets_v3_get(\n self,\n applied_at: Optional[datetime] = None,\n applied_by: Optional[StrictStr] = None,\n chart_release: Optional[StrictStr] = None,\n from_app_version_branch: Optional[StrictStr] = None,\n from_app_version_commit: Optional[StrictStr] = None,\n from_app_version_exact: Optional[StrictStr] = None,\n from_app_version_follow_chart_release: Optional[StrictStr] = None,\n from_app_version_reference: Optional[StrictStr] = None,\n from_app_version_resolver: Optional[StrictStr] = None,\n from_chart_version_exact: Optional[StrictStr] = None,\n from_chart_version_follow_chart_release: Optional[StrictStr] = None,\n from_chart_version_reference: Optional[StrictStr] = None,\n from_chart_version_resolver: Optional[StrictStr] = None,\n from_helmfile_ref: Optional[StrictStr] = None,\n from_helmfile_ref_enabled: Optional[StrictBool] = None,\n from_resolved_at: Optional[datetime] = None,\n planned_by: Optional[StrictStr] = None,\n superseded_at: Optional[datetime] = None,\n to_app_version_branch: Optional[StrictStr] = None,\n to_app_version_commit: Optional[StrictStr] = None,\n to_app_version_exact: Optional[StrictStr] = None,\n to_app_version_follow_chart_release: Optional[StrictStr] = None,\n to_app_version_reference: Optional[StrictStr] = None,\n to_app_version_resolver: Optional[StrictStr] = None,\n to_chart_version_exact: Optional[StrictStr] = None,\n to_chart_version_follow_chart_release: Optional[StrictStr] = None,\n to_chart_version_reference: Optional[StrictStr] = None,\n to_chart_version_resolver: Optional[StrictStr] = None,\n to_helmfile_ref: Optional[StrictStr] = None,\n to_helmfile_ref_enabled: Optional[StrictBool] = None,\n to_resolved_at: Optional[datetime] = None,\n id: Annotated[Optional[List[StrictInt]], Field(description=\"Get specific changesets by their IDs, can be passed multiple times and/or be comma-separated\")] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Changesets are returned (default 100), ignored if specific IDs are passed\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Changesets (default 0), ignored if specific IDs are passed\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockChangesetV3]:\n \"\"\"List Changesets matching a filter\n\n List Changesets matching a filter.\n\n :param applied_at:\n :type applied_at: datetime\n :param applied_by:\n :type applied_by: str\n :param chart_release:\n :type chart_release: str\n :param from_app_version_branch:\n :type from_app_version_branch: str\n :param from_app_version_commit:\n :type from_app_version_commit: str\n :param from_app_version_exact:\n :type from_app_version_exact: str\n :param from_app_version_follow_chart_release:\n :type from_app_version_follow_chart_release: str\n :param from_app_version_reference:\n :type from_app_version_reference: str\n :param from_app_version_resolver:\n :type from_app_version_resolver: str\n :param from_chart_version_exact:\n :type from_chart_version_exact: str\n :param from_chart_version_follow_chart_release:\n :type from_chart_version_follow_chart_release: str\n :param from_chart_version_reference:\n :type from_chart_version_reference: str\n :param from_chart_version_resolver:\n :type from_chart_version_resolver: str\n :param from_helmfile_ref:\n :type from_helmfile_ref: str\n :param from_helmfile_ref_enabled:\n :type from_helmfile_ref_enabled: bool\n :param from_resolved_at:\n :type from_resolved_at: datetime\n :param planned_by:\n :type planned_by: str\n :param superseded_at:\n :type superseded_at: datetime\n :param to_app_version_branch:\n :type to_app_version_branch: str\n :param to_app_version_commit:\n :type to_app_version_commit: str\n :param to_app_version_exact:\n :type to_app_version_exact: str\n :param to_app_version_follow_chart_release:\n :type to_app_version_follow_chart_release: str\n :param to_app_version_reference:\n :type to_app_version_reference: str\n :param to_app_version_resolver:\n :type to_app_version_resolver: str\n :param to_chart_version_exact:\n :type to_chart_version_exact: str\n :param to_chart_version_follow_chart_release:\n :type to_chart_version_follow_chart_release: str\n :param to_chart_version_reference:\n :type to_chart_version_reference: str\n :param to_chart_version_resolver:\n :type to_chart_version_resolver: str\n :param to_helmfile_ref:\n :type to_helmfile_ref: str\n :param to_helmfile_ref_enabled:\n :type to_helmfile_ref_enabled: bool\n :param to_resolved_at:\n :type to_resolved_at: datetime\n :param id: Get specific changesets by their IDs, can be passed multiple times and/or be comma-separated\n :type id: List[int]\n :param limit: Control how many Changesets are returned (default 100), ignored if specific IDs are passed\n :type limit: int\n :param offset: Control the offset for the returned Changesets (default 0), ignored if specific IDs are passed\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_changesets_v3_get_serialize(\n applied_at=applied_at,\n applied_by=applied_by,\n chart_release=chart_release,\n from_app_version_branch=from_app_version_branch,\n from_app_version_commit=from_app_version_commit,\n from_app_version_exact=from_app_version_exact,\n from_app_version_follow_chart_release=from_app_version_follow_chart_release,\n from_app_version_reference=from_app_version_reference,\n from_app_version_resolver=from_app_version_resolver,\n from_chart_version_exact=from_chart_version_exact,\n from_chart_version_follow_chart_release=from_chart_version_follow_chart_release,\n from_chart_version_reference=from_chart_version_reference,\n from_chart_version_resolver=from_chart_version_resolver,\n from_helmfile_ref=from_helmfile_ref,\n from_helmfile_ref_enabled=from_helmfile_ref_enabled,\n from_resolved_at=from_resolved_at,\n planned_by=planned_by,\n superseded_at=superseded_at,\n to_app_version_branch=to_app_version_branch,\n to_app_version_commit=to_app_version_commit,\n to_app_version_exact=to_app_version_exact,\n to_app_version_follow_chart_release=to_app_version_follow_chart_release,\n to_app_version_reference=to_app_version_reference,\n to_app_version_resolver=to_app_version_resolver,\n to_chart_version_exact=to_chart_version_exact,\n to_chart_version_follow_chart_release=to_chart_version_follow_chart_release,\n to_chart_version_reference=to_chart_version_reference,\n to_chart_version_resolver=to_chart_version_resolver,\n to_helmfile_ref=to_helmfile_ref,\n to_helmfile_ref_enabled=to_helmfile_ref_enabled,\n to_resolved_at=to_resolved_at,\n id=id,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChangesetV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n num_conv_layers=2,\n conv_kernel_sizes=(5, 5),\n conv_channels=32,\n input_feat_per_channel=24,\n input_channels=1,\n hidden_act=\"relu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n max_source_positions=20,\n max_target_positions=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.num_conv_layers = num_conv_layers\n self.conv_kernel_sizes = conv_kernel_sizes\n self.conv_channels = conv_channels\n self.input_feat_per_channel = input_feat_per_channel\n self.input_channels = input_channels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hass: HomeAssistant,\n sequence: Sequence[dict[str, Any]],\n name: str,\n domain: str,\n *,\n # Used in \"Running <running_description>\" log message\n change_listener: Callable[[], Any] | None = None,\n copy_variables: bool = False,\n log_exceptions: bool = True,\n logger: logging.Logger | None = None,\n max_exceeded: str = DEFAULT_MAX_EXCEEDED,\n max_runs: int = DEFAULT_MAX,\n running_description: str | None = None,\n script_mode: str = DEFAULT_SCRIPT_MODE,\n top_level: bool = True,\n variables: ScriptVariables | None = None,\n ) -> None:\n \"\"\"Initialize the script.\"\"\"\n if not (all_scripts := hass.data.get(DATA_SCRIPTS)):\n all_scripts = hass.data[DATA_SCRIPTS] = []\n hass.bus.async_listen_once(\n EVENT_HOMEASSISTANT_STOP, partial(_async_stop_scripts_at_shutdown, hass)\n )\n self.top_level = top_level\n if top_level:\n all_scripts.append(\n {\"instance\": self, \"started_before_shutdown\": not hass.is_stopping}\n )\n if DATA_SCRIPT_BREAKPOINTS not in hass.data:\n hass.data[DATA_SCRIPT_BREAKPOINTS] = {}\n\n self._hass = hass\n self.sequence = sequence\n self.name = name\n self.unique_id = f\"{domain}.{name}-{id(self)}\"\n self.domain = domain\n self.running_description = running_description or f\"{domain} script\"\n self._change_listener = change_listener\n self._change_listener_job = (\n None if change_listener is None else HassJob(change_listener)\n )\n\n self.script_mode = script_mode\n self._set_logger(logger)\n self._log_exceptions = log_exceptions\n\n self.last_action: str | None = None\n self.last_triggered: datetime | None = None\n\n self._runs: list[_ScriptRun] = []\n self.max_runs = max_runs\n self._max_exceeded = max_exceeded\n if script_mode == SCRIPT_MODE_QUEUED:\n self._queue_lck = asyncio.Lock()\n self._config_cache: dict[frozenset[tuple[str, str]], ConditionCheckerType] = {}\n self._repeat_script: dict[int, Script] = {}\n self._choose_data: dict[int, _ChooseData] = {}\n self._if_data: dict[int, _IfData] = {}\n self._parallel_scripts: dict[int, list[Script]] = {}\n self._sequence_scripts: dict[int, Script] = {}\n self.variables = variables\n self._variables_dynamic = template.is_complex(variables)\n self._copy_variables_on_run = copy_variables", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n num_latents=256,\n d_latents=1280,\n d_model=768,\n num_blocks=1,\n num_self_attends_per_block=26,\n num_self_attention_heads=8,\n num_cross_attention_heads=8,\n qk_channels=None,\n v_channels=None,\n cross_attention_shape_for_attention=\"kv\",\n self_attention_widening_factor=1,\n cross_attention_widening_factor=1,\n hidden_act=\"gelu\",\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n use_query_residual=True,\n vocab_size=262,\n max_position_embeddings=2048,\n image_size=56,\n train_size=[368, 496],\n num_frames=16,\n audio_samples_per_frame=1920,\n samples_per_patch=16,\n output_shape=[1, 16, 224, 224],\n output_num_channels=512,\n _label_trainable_num_channels=1024,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.num_latents = num_latents\n self.d_latents = d_latents\n self.d_model = d_model\n self.num_blocks = num_blocks\n self.num_self_attends_per_block = num_self_attends_per_block\n self.num_self_attention_heads = num_self_attention_heads\n self.num_cross_attention_heads = num_cross_attention_heads\n self.qk_channels = qk_channels\n self.v_channels = v_channels\n self.cross_attention_shape_for_attention = cross_attention_shape_for_attention\n self.self_attention_widening_factor = self_attention_widening_factor\n self.cross_attention_widening_factor = cross_attention_widening_factor\n self.hidden_act = hidden_act\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.use_query_residual = use_query_residual\n # masked language modeling attributes\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n # image classification attributes\n self.image_size = image_size\n # flow attributes\n self.train_size = train_size\n # multimodal autoencoding attributes\n self.num_frames = num_frames\n self.audio_samples_per_frame = audio_samples_per_frame\n self.samples_per_patch = samples_per_patch\n self.output_shape = output_shape\n self.output_num_channels = output_num_channels\n self._label_trainable_num_channels = _label_trainable_num_channels", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple, TFBaseModelOutputWithPoolingAndCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n \"\"\"\n outputs = self.roberta(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n eos_token=\"</s>\",\n unk_token=\"<unk>\",\n sep_token=\"</s>\",\n pad_token=\"<pad>\",\n sep_token_box=[1000, 1000, 1000, 1000],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n additional_special_tokens=None,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n legacy=True,\n add_prefix_space=True,\n **kwargs,\n ) -> None:\n eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token\n unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token\n sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token\n pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token\n\n self.legacy = legacy\n self.add_prefix_space = add_prefix_space\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n\n self.vocab_file = vocab_file\n\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.Load(vocab_file)\n\n # additional properties\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword\n\n super().__init__(\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n additional_special_tokens=additional_special_tokens,\n sp_model_kwargs=self.sp_model_kwargs,\n legacy=legacy,\n add_prefix_space=add_prefix_space,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n videos: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n offset: bool = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n videos (`ImageInput`):\n Video frames to preprocess. Expects a single or batch of video frames with pixel values ranging from 0\n to 255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after applying resize.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):\n Whether to centre crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the image after applying the centre crop.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between `[-1 - 1]` if `offset` is `True`, `[0, 1]` otherwise.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n offset (`bool`, *optional*, defaults to `self.offset`):\n Whether to scale the image in both negative and positive directions.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the inferred channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n offset = offset if offset is not None else self.offset\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\")\n\n if not valid_images(videos):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n videos = make_batched(videos)\n\n videos = [\n [\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n offset=offset,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in video\n ]\n for video in videos\n ]\n\n data = {\"pixel_values\": videos}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_users_v3_get_with_http_info(\n self,\n created_at: Optional[datetime] = None,\n deactivated_at: Annotated[Optional[StrictStr], Field(description=\"If set, indicates that the user is currently deactivated\")] = None,\n email: Optional[StrictStr] = None,\n github_id: Optional[StrictStr] = None,\n github_username: Optional[StrictStr] = None,\n google_id: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n name: Optional[StrictStr] = None,\n name_from: Optional[StrictStr] = None,\n slack_id: Optional[StrictStr] = None,\n slack_username: Optional[StrictStr] = None,\n suitability_description: Annotated[Optional[StrictStr], Field(description=\"Available only in responses; describes the user's production-suitability\")] = None,\n suitable: Annotated[Optional[StrictBool], Field(description=\"Available only in responses; indicates whether the user is production-suitable\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Users are returned (default 0, no limit)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Users (default 0)\")] = None,\n include_deactivated: Annotated[Optional[StrictBool], Field(description=\"Include deactivated users in the results (default false)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockUserV3]]:\n \"\"\"List Users matching a filter\n\n List Users matching a filter. The results will include suitability and other information. Note that the suitability info can't directly be filtered for at this time.\n\n :param created_at:\n :type created_at: datetime\n :param deactivated_at: If set, indicates that the user is currently deactivated\n :type deactivated_at: str\n :param email:\n :type email: str\n :param github_id:\n :type github_id: str\n :param github_username:\n :type github_username: str\n :param google_id:\n :type google_id: str\n :param id:\n :type id: int\n :param name:\n :type name: str\n :param name_from:\n :type name_from: str\n :param slack_id:\n :type slack_id: str\n :param slack_username:\n :type slack_username: str\n :param suitability_description: Available only in responses; describes the user's production-suitability\n :type suitability_description: str\n :param suitable: Available only in responses; indicates whether the user is production-suitable\n :type suitable: bool\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many Users are returned (default 0, no limit)\n :type limit: int\n :param offset: Control the offset for the returned Users (default 0)\n :type offset: int\n :param include_deactivated: Include deactivated users in the results (default false)\n :type include_deactivated: bool\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_users_v3_get_serialize(\n created_at=created_at,\n deactivated_at=deactivated_at,\n email=email,\n github_id=github_id,\n github_username=github_username,\n google_id=google_id,\n id=id,\n name=name,\n name_from=name_from,\n slack_id=slack_id,\n slack_username=slack_username,\n suitability_description=suitability_description,\n suitable=suitable,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n include_deactivated=include_deactivated,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockUserV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n type_sequence_label_size=10,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.scope = scope\n\n self.num_patches_one_direction = self.image_size // self.patch_size\n self.seq_length = (self.image_size // self.patch_size) ** 2", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n fpn_feature_size: int = 256,\n mask_feature_size: int = 256,\n no_object_weight: float = 0.1,\n use_auxiliary_loss: bool = False,\n backbone_config: Optional[Dict] = None,\n decoder_config: Optional[Dict] = None,\n init_std: float = 0.02,\n init_xavier_std: float = 1.0,\n dice_weight: float = 1.0,\n cross_entropy_weight: float = 1.0,\n mask_weight: float = 20.0,\n output_auxiliary_logits: Optional[bool] = None,\n backbone: Optional[str] = None,\n use_pretrained_backbone: bool = False,\n use_timm_backbone: bool = False,\n backbone_kwargs: Optional[Dict] = None,\n **kwargs,\n ):\n if backbone_config is None and backbone is None:\n # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k\n backbone_config = SwinConfig(\n image_size=384,\n in_channels=3,\n patch_size=4,\n embed_dim=128,\n depths=[2, 2, 18, 2],\n num_heads=[4, 8, 16, 32],\n window_size=12,\n drop_path_rate=0.3,\n out_features=[\"stage1\", \"stage2\", \"stage3\", \"stage4\"],\n )\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.pop(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n # verify that the backbone is supported\n if backbone_config is not None and backbone_config.model_type not in self.backbones_supported:\n logger.warning_once(\n f\"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. \"\n f\"Supported model types: {','.join(self.backbones_supported)}\"\n )\n\n if decoder_config is None:\n # fall back to https://huggingface.co/facebook/detr-resnet-50\n decoder_config = DetrConfig()\n else:\n # verify that the decoder is supported\n decoder_type = (\n decoder_config.pop(\"model_type\") if isinstance(decoder_config, dict) else decoder_config.model_type\n )\n if decoder_type not in self.decoders_supported:\n raise ValueError(\n f\"Transformer Decoder {decoder_type} not supported, please use one of\"\n f\" {','.join(self.decoders_supported)}\"\n )\n if isinstance(decoder_config, dict):\n config_class = CONFIG_MAPPING[decoder_type]\n decoder_config = config_class.from_dict(decoder_config)\n\n self.backbone_config = backbone_config\n self.decoder_config = decoder_config\n # main feature dimension for the model\n self.fpn_feature_size = fpn_feature_size\n self.mask_feature_size = mask_feature_size\n # initializer\n self.init_std = init_std\n self.init_xavier_std = init_xavier_std\n # Hungarian matcher && loss\n self.cross_entropy_weight = cross_entropy_weight\n self.dice_weight = dice_weight\n self.mask_weight = mask_weight\n self.use_auxiliary_loss = use_auxiliary_loss\n self.no_object_weight = no_object_weight\n self.output_auxiliary_logits = output_auxiliary_logits\n\n self.num_attention_heads = self.decoder_config.encoder_attention_heads\n self.num_hidden_layers = self.decoder_config.num_hidden_layers\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n init_env_path: str,\n init_grid_path: str,\n path_chron, # path where chronics of injections are stored\n n_busbar=DEFAULT_N_BUSBAR_PER_SUB,\n name_env=\"unknown\",\n parameters_path=None,\n names_chronics_to_backend=None,\n actionClass=TopologyAction,\n observationClass=CompleteObservation,\n rewardClass=FlatReward,\n legalActClass=AlwaysLegal,\n envClass=Environment,\n other_env_kwargs=None,\n gridStateclass=GridStateFromFile,\n # type of chronics to use. For example GridStateFromFile if forecasts are not used,\n # or GridStateFromFileWithForecasts otherwise\n backendClass=PandaPowerBackend,\n backend_kwargs=None,\n agentClass=DoNothingAgent, # class used to build the agent\n agentInstance=None,\n verbose=False,\n gridStateclass_kwargs={},\n voltageControlerClass=ControlVoltageFromFile,\n thermal_limit_a=None,\n max_iter=-1,\n other_rewards={},\n opponent_space_type=OpponentSpace,\n opponent_action_class=DontAct,\n opponent_class=BaseOpponent,\n opponent_init_budget=0.0,\n opponent_budget_per_ts=0.0,\n opponent_budget_class=NeverAttackBudget,\n opponent_attack_duration=0,\n opponent_attack_cooldown=99999,\n opponent_kwargs={},\n grid_layout=None,\n with_forecast=True,\n attention_budget_cls=LinearAttentionBudget,\n kwargs_attention_budget=None,\n has_attention_budget=False,\n logger=None,\n use_compact_episode_data=False,\n kwargs_observation=None,\n observation_bk_class=None,\n observation_bk_kwargs=None,\n mp_context=None,\n # experimental: whether to read from local dir or generate the classes on the fly:\n _read_from_local_dir=None,\n _is_test=False, # TODO not implemented !!\n _local_dir_cls=None,\n _overload_name_multimix=None\n ):\n \"\"\"\n Initialize the Runner.\n\n Parameters\n ----------\n init_grid_path: ``str``\n Madantory, used to initialize :attr:`Runner.init_grid_path`.\n\n path_chron: ``str``\n Madantory where to look for chronics data, used to initialize :attr:`Runner.path_chron`.\n\n parameters_path: ``str`` or ``dict``, optional\n Used to initialize :attr:`Runner.parameters_path`. If it's a string, this will suppose parameters are\n located at this path, if it's a dictionary, this will use the parameters converted from this dictionary.\n\n names_chronics_to_backend: ``dict``, optional\n Used to initialize :attr:`Runner.names_chronics_to_backend`.\n\n actionClass: ``type``, optional\n Used to initialize :attr:`Runner.actionClass`.\n\n observationClass: ``type``, optional\n Used to initialize :attr:`Runner.observationClass`.\n\n rewardClass: ``type``, optional\n Used to initialize :attr:`Runner.rewardClass`. Default to :class:`grid2op.ConstantReward` that\n *should not** be used to train or evaluate an agent, but rather as debugging purpose.\n\n legalActClass: ``type``, optional\n Used to initialize :attr:`Runner.legalActClass`.\n\n envClass: ``type``, optional\n Used to initialize :attr:`Runner.envClass`.\n\n gridStateclass: ``type``, optional\n Used to initialize :attr:`Runner.gridStateclass`.\n\n backendClass: ``type``, optional\n Used to initialize :attr:`Runner.backendClass`.\n\n agentClass: ``type``, optional\n Used to initialize :attr:`Runner.agentClass`.\n\n agentInstance: :class:`grid2op.Agent.Agent`\n Used to initialize the agent. Note that either :attr:`agentClass` or :attr:`agentInstance` is used\n at the same time. If both ot them are ``None`` or both of them are \"not ``None``\" it throw an error.\n\n verbose: ``bool``, optional\n Used to initialize :attr:`Runner.verbose`.\n\n thermal_limit_a: ``numpy.ndarray``\n The thermal limit for the environment (if any).\n\n voltagecontrolerClass: :class:`grid2op.VoltageControler.ControlVoltageFromFile`, optional\n The controler that will change the voltage setpoints of the generators.\n\n use_compact_episode_data: ``bool``, optional\n Whether to use :class:`grid2op.Episode.CompactEpisodeData` instead of :class:`grid2op.Episode.EpisodeData` to store \n Episode to disk (allows it to be replayed later). Defaults to False.\n\n # TODO documentation on the opponent\n # TOOD doc for the attention budget\n \"\"\"\n self._n_busbar = n_busbar\n self.with_forecast = with_forecast\n self.name_env = name_env\n self._overload_name_multimix = _overload_name_multimix\n if not isinstance(envClass, type):\n raise Grid2OpException(\n 'Parameter \"envClass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(type(envClass))\n )\n if not issubclass(envClass, Environment):\n raise RuntimeError(\n \"Impossible to create a runner without an evnrionment derived from grid2op.Environement\"\n ' class. Please modify \"envClass\" parameter.'\n )\n self.envClass = envClass\n if other_env_kwargs is not None:\n self.other_env_kwargs = other_env_kwargs\n else:\n self.other_env_kwargs = {}\n if not isinstance(actionClass, type):\n raise Grid2OpException(\n 'Parameter \"actionClass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(\n type(actionClass)\n )\n )\n if not issubclass(actionClass, BaseAction):\n raise RuntimeError(\n \"Impossible to create a runner without an action class derived from grid2op.BaseAction. \"\n 'Please modify \"actionClass\" parameter.'\n )\n self.actionClass = actionClass\n\n if not isinstance(observationClass, type):\n raise Grid2OpException(\n 'Parameter \"observationClass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(\n type(observationClass)\n )\n )\n if not issubclass(observationClass, BaseObservation):\n raise RuntimeError(\n \"Impossible to create a runner without an observation class derived from \"\n 'grid2op.BaseObservation. Please modify \"observationClass\" parameter.'\n )\n self.observationClass = observationClass\n if isinstance(rewardClass, type):\n if not issubclass(rewardClass, BaseReward):\n raise RuntimeError(\n \"Impossible to create a runner without an observation class derived from \"\n 'grid2op.BaseReward. Please modify \"rewardClass\" parameter.'\n )\n else:\n if not isinstance(rewardClass, BaseReward):\n raise RuntimeError(\n \"Impossible to create a runner without an observation class derived from \"\n 'grid2op.BaseReward. Please modify \"rewardClass\" parameter.'\n )\n\n self.rewardClass = rewardClass\n\n if not isinstance(gridStateclass, type):\n raise Grid2OpException(\n 'Parameter \"gridStateclass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(\n type(gridStateclass)\n )\n )\n if not issubclass(gridStateclass, GridValue):\n raise RuntimeError(\n \"Impossible to create a runner without an chronics class derived from \"\n 'grid2op.GridValue. Please modify \"gridStateclass\" parameter.'\n )\n self.gridStateclass = gridStateclass\n if issubclass(gridStateclass, MultifolderWithCache):\n warnings.warn(\"We do not recommend to use the `MultifolderWithCache` during the \"\n \"evaluation of your agents. It is possible but you might end up with \"\n \"side effects (see issue 616 for example). It is safer to use the \"\n \"`Multifolder` class as a drop-in replacement.\")\n self.envClass._check_rules_correct(legalActClass)\n self.legalActClass = legalActClass\n\n if not isinstance(backendClass, type):\n raise Grid2OpException(\n 'Parameter \"legalActClass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(\n type(backendClass)\n )\n )\n if not issubclass(backendClass, Backend):\n raise RuntimeError(\n \"Impossible to create a runner without a backend class derived from grid2op.GridValue. \"\n 'Please modify \"backendClass\" parameter.'\n )\n self.backendClass = backendClass\n if backend_kwargs is not None:\n self._backend_kwargs = backend_kwargs\n else:\n self._backend_kwargs = {}\n \n # we keep a reference to the local directory (tmpfile) where\n # the classes definition are stored while the runner lives\n self._local_dir_cls = _local_dir_cls \n \n # multi processing context that controls the way the computations are \n # distributed when using multiple processes \n self._mp_context = mp_context\n \n self.__can_copy_agent = True\n if agentClass is not None:\n if agentInstance is not None:\n raise RuntimeError(\n \"Impossible to build the Runner. Only one of agentClass or agentInstance can be \"\n \"used (both are set / both are not None).\"\n )\n if not isinstance(agentClass, type):\n raise Grid2OpException(\n 'Parameter \"agentClass\" used to build the Runner should be a type (a class) and not an object '\n '(an instance of a class). It is currently \"{}\"'.format(\n type(agentClass)\n )\n )\n if not issubclass(agentClass, BaseAgent):\n raise RuntimeError(\n \"Impossible to create a runner without an agent class derived from \"\n \"grid2op.BaseAgent. \"\n 'Please modify \"agentClass\" parameter.'\n )\n self.agentClass = agentClass\n self._useclass = True\n self.agent = None\n elif agentInstance is not None:\n if not isinstance(agentInstance, BaseAgent):\n raise RuntimeError(\n \"Impossible to create a runner without an agent class derived from \"\n \"grid2op.BaseAgent. \"\n 'Please modify \"agentInstance\" parameter.'\n )\n self.agentClass = None\n self._useclass = False\n self.agent = agentInstance\n # Test if we can copy the agent for parallel runs\n try:\n copy.copy(self.agent)\n except Exception as exc_:\n self.__can_copy_agent = False\n else:\n raise RuntimeError(\n \"Impossible to build the backend. Either AgentClass or agentInstance must be provided \"\n \"and both are None.\"\n )\n self.agentInstance = agentInstance\n\n self._read_from_local_dir = _read_from_local_dir\n self._observation_bk_class = observation_bk_class\n self._observation_bk_kwargs = observation_bk_kwargs\n\n self.logger = ConsoleLog(DoNothingLog.INFO if verbose else DoNothingLog.ERROR)\n if logger is None:\n import logging\n\n self.logger = logging.getLogger(__name__)\n if verbose:\n self.logger.setLevel(\"debug\")\n else:\n self.logger.disabled = True\n else:\n self.logger = logger.getChild(\"grid2op_Runner\")\n\n self.use_compact_episode_data = use_compact_episode_data\n\n # store _parameters\n self.init_env_path = init_env_path\n self.init_grid_path = init_grid_path\n self.names_chronics_to_backend = names_chronics_to_backend\n\n # game _parameters\n self.parameters_path = parameters_path\n if isinstance(parameters_path, str):\n self.parameters = Parameters(parameters_path)\n elif isinstance(parameters_path, dict):\n self.parameters = Parameters()\n self.parameters.init_from_dict(parameters_path)\n elif parameters_path is None:\n self.parameters = Parameters()\n else:\n raise RuntimeError(\n 'Impossible to build the parameters. The argument \"parameters_path\" should either '\n \"be a string or a dictionary.\"\n )\n\n # chronics of grid state\n self.path_chron = path_chron\n self.gridStateclass_kwargs = gridStateclass_kwargs\n self.max_iter = max_iter\n if max_iter > 0:\n self.gridStateclass_kwargs[\"max_iter\"] = max_iter\n\n self.verbose = verbose\n self.thermal_limit_a = thermal_limit_a\n\n # controler for voltage\n if not issubclass(voltageControlerClass, ControlVoltageFromFile):\n raise Grid2OpException(\n 'Parameter \"voltagecontrolClass\" should derive from \"ControlVoltageFromFile\".'\n )\n self.voltageControlerClass = voltageControlerClass\n self._other_rewards = other_rewards\n\n # for opponent (should be defined here) after the initialization of BaseEnv\n self._opponent_space_type = opponent_space_type\n if not issubclass(opponent_action_class, BaseAction):\n raise EnvError(\n \"Impossible to make an environment with an opponent action class not \"\n \"derived from BaseAction\"\n )\n try:\n self.opponent_init_budget = dt_float(opponent_init_budget)\n except Exception as e:\n raise EnvError(\n 'Impossible to convert \"opponent_init_budget\" to a float with error {}'.format(\n e\n )\n )\n if self.opponent_init_budget < 0.0:\n raise EnvError(\n \"If you want to deactive the opponent, please don't set its budget to a negative number.\"\n 'Prefer the use of the DontAct action type (\"opponent_action_class=DontAct\" '\n \"and / or set its budget to 0.\"\n )\n if not issubclass(opponent_class, BaseOpponent):\n raise EnvError(\n \"Impossible to make an opponent with a type that does not inherit from BaseOpponent.\"\n )\n self.opponent_action_class = opponent_action_class\n self.opponent_class = opponent_class\n self.opponent_init_budget = opponent_init_budget\n self.opponent_budget_per_ts = opponent_budget_per_ts\n self.opponent_budget_class = opponent_budget_class\n self.opponent_attack_duration = opponent_attack_duration\n self.opponent_attack_cooldown = opponent_attack_cooldown\n self.opponent_kwargs = opponent_kwargs\n self.grid_layout = grid_layout\n\n # attention budget\n self._attention_budget_cls = attention_budget_cls\n self._kwargs_attention_budget = copy.deepcopy(kwargs_attention_budget)\n self._has_attention_budget = has_attention_budget\n\n # custom observation building\n if kwargs_observation is None:\n kwargs_observation = {}\n self._kwargs_observation = copy.deepcopy(kwargs_observation)\n\n # otherwise on windows / macos it sometimes fail in the runner in multi process\n # on linux like OS i prefer to generate all the proper classes accordingly\n if _IS_LINUX:\n pass\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n with self.init_env() as env:\n bk_class = type(env.backend)\n pass\n\n # not implemented !\n self._is_test = _is_test\n\n self.__used = False", "smellKey": "S107", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "def create_and_check_for_question_answering(\n self,\n config,\n input_ids,\n attention_mask,\n token_type_ids,\n entity_ids,\n entity_attention_mask,\n entity_token_type_ids,\n entity_position_ids,\n sequence_labels,\n token_labels,\n choice_labels,\n entity_labels,\n entity_classification_labels,\n entity_pair_classification_labels,\n entity_span_classification_labels,\n ):\n model = LukeForQuestionAnswering(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n start_positions=sequence_labels,\n end_positions=sequence_labels,\n )\n self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=512 + 1, # add one for start of sentence (sos) token\n n_positions=32 * 32,\n n_embd=512,\n n_layer=24,\n n_head=8,\n n_inner=None,\n activation_function=\"quick_gelu\",\n resid_pdrop=0.1,\n embd_pdrop=0.1,\n attn_pdrop=0.1,\n layer_norm_epsilon=1e-5,\n initializer_range=0.02,\n scale_attn_weights=True,\n use_cache=True,\n tie_word_embeddings=False,\n scale_attn_by_inverse_layer_idx=False,\n reorder_and_upcast_attn=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.n_positions = n_positions\n self.n_embd = n_embd\n self.n_layer = n_layer\n self.n_head = n_head\n self.n_inner = n_inner\n self.activation_function = activation_function\n self.resid_pdrop = resid_pdrop\n self.embd_pdrop = embd_pdrop\n self.attn_pdrop = attn_pdrop\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.scale_attn_weights = scale_attn_weights\n self.use_cache = use_cache\n self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx\n self.reorder_and_upcast_attn = reorder_and_upcast_attn\n self.tie_word_embeddings = tie_word_embeddings\n\n super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hass: HomeAssistant,\n name: str,\n heater_entity_id: str,\n sensor_entity_id: str,\n min_temp: float | None,\n max_temp: float | None,\n target_temp: float | None,\n ac_mode: bool | None,\n min_cycle_duration: timedelta | None,\n cold_tolerance: float,\n hot_tolerance: float,\n keep_alive: timedelta | None,\n initial_hvac_mode: HVACMode | None,\n presets: dict[str, float],\n precision: float | None,\n target_temperature_step: float | None,\n unit: UnitOfTemperature,\n unique_id: str | None,\n ) -> None:\n \"\"\"Initialize the thermostat.\"\"\"\n self._attr_name = name\n self.heater_entity_id = heater_entity_id\n self.sensor_entity_id = sensor_entity_id\n self._attr_device_info = async_device_info_to_link_from_entity(\n hass,\n heater_entity_id,\n )\n self.ac_mode = ac_mode\n self.min_cycle_duration = min_cycle_duration\n self._cold_tolerance = cold_tolerance\n self._hot_tolerance = hot_tolerance\n self._keep_alive = keep_alive\n self._hvac_mode = initial_hvac_mode\n self._saved_target_temp = target_temp or next(iter(presets.values()), None)\n self._temp_precision = precision\n self._temp_target_temperature_step = target_temperature_step\n if self.ac_mode:\n self._attr_hvac_modes = [HVACMode.COOL, HVACMode.OFF]\n else:\n self._attr_hvac_modes = [HVACMode.HEAT, HVACMode.OFF]\n self._active = False\n self._cur_temp: float | None = None\n self._temp_lock = asyncio.Lock()\n self._min_temp = min_temp\n self._max_temp = max_temp\n self._attr_preset_mode = PRESET_NONE\n self._target_temp = target_temp\n self._attr_temperature_unit = unit\n self._attr_unique_id = unique_id\n self._attr_supported_features = (\n ClimateEntityFeature.TARGET_TEMPERATURE\n | ClimateEntityFeature.TURN_OFF\n | ClimateEntityFeature.TURN_ON\n )\n if len(presets):\n self._attr_supported_features |= ClimateEntityFeature.PRESET_MODE\n self._attr_preset_modes = [PRESET_NONE, *presets.keys()]\n else:\n self._attr_preset_modes = [PRESET_NONE]\n self._presets = presets", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_attention_heads=12,\n num_qa_labels=9500,\n num_object_labels=1600,\n num_attr_labels=400,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n l_layers=9,\n x_layers=5,\n r_layers=5,\n visual_feat_dim=2048,\n visual_pos_dim=4,\n visual_loss_normalizer=6.67,\n task_matched=True,\n task_mask_lm=True,\n task_obj_predict=True,\n task_qa=True,\n visual_obj_loss=True,\n visual_attr_loss=True,\n visual_feat_loss=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.num_qa_labels = num_qa_labels\n self.num_object_labels = num_object_labels\n self.num_attr_labels = num_attr_labels\n self.l_layers = l_layers\n self.x_layers = x_layers\n self.r_layers = r_layers\n self.visual_feat_dim = visual_feat_dim\n self.visual_pos_dim = visual_pos_dim\n self.visual_loss_normalizer = visual_loss_normalizer\n self.task_matched = task_matched\n self.task_mask_lm = task_mask_lm\n self.task_obj_predict = task_obj_predict\n self.task_qa = task_qa\n self.visual_obj_loss = visual_obj_loss\n self.visual_attr_loss = visual_attr_loss\n self.visual_feat_loss = visual_feat_loss\n self.num_hidden_layers = {\"vision\": r_layers, \"cross_encoder\": x_layers, \"language\": l_layers}\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(VIDEO_LLAVA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=VideoLlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n pixel_values_images: torch.FloatTensor = None,\n pixel_values_videos: torch.FloatTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n vision_feature_layer: Optional[int] = None,\n vision_feature_select_strategy: Optional[str] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n cache_position: Optional[torch.LongTensor] = None,\n num_logits_to_keep: int = 0,\n ) -> Union[Tuple, VideoLlavaCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n num_logits_to_keep (`int`, *optional*):\n Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all\n `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that\n token can save memory, which becomes pretty significant for long sequences or large vocabulary size.\n\n Returns:\n\n Example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> import numpy as np\n >>> import av\n >>> from huggingface_hub import hf_hub_download\n >>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration\n\n\n >>> def read_video_pyav(container, indices):\n ... '''\n ... Decode the video with PyAV decoder.\n ... Args:\n ... container (`av.container.input.InputContainer`): PyAV container.\n ... indices (`List[int]`): List of frame indices to decode.\n ... Returns:\n ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).\n ... '''\n ... frames = []\n ... container.seek(0)\n ... start_index = indices[0]\n ... end_index = indices[-1]\n ... for i, frame in enumerate(container.decode(video=0)):\n ... if i > end_index:\n ... break\n ... if i >= start_index and i in indices:\n ... frames.append(frame)\n ... return np.stack([x.to_ndarray(format=\"rgb24\") for x in frames])\n\n >>> model = VideoLlavaForConditionalGeneration.from_pretrained(\"LanguageBind/Video-LLaVA-7B-hf\")\n >>> processor = VideoLlavaProcessor.from_pretrained(\"LanguageBind/Video-LLaVA-7B-hf\")\n\n >>> prompt = \"USER: <video>\\nWhy is this video funny? ASSISTANT:\"\n >>> video_path = hf_hub_download(repo_id=\"raushan-testing-hf/videos-test\", filename=\"sample_demo_1.mp4\", repo_type=\"dataset\")\n >>> container = av.open(video_path)\n\n >>> # sample uniformly 8 frames from the video\n >>> total_frames = container.streams.video[0].frames\n >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)\n >>> clip = read_video_pyav(container, indices)\n\n >>> inputs = processor(text=prompt, videos=clip, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(**inputs, max_length=80)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"USER: Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.\u042a. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a\"\n\n >>> # to generate from image and video mix\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> prompt = [\n ... \"USER: <image>\\nHow many cats do you see? ASSISTANT:\",\n ... \"USER: <video>\\nWhy is this video funny? ASSISTANT:\"\n ... ]\n >>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(**inputs, max_length=50)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)\n ['USER: How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER: Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.\u042a. The baby is holding the remote']\n ```\n \"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n vision_feature_layer = (\n vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n )\n vision_feature_select_strategy = (\n vision_feature_select_strategy\n if vision_feature_select_strategy is not None\n else self.config.vision_feature_select_strategy\n )\n\n if (input_ids is None) ^ (inputs_embeds is not None):\n raise ValueError(\"You must specify exactly one of input_ids or inputs_embeds\")\n\n if (pixel_values_images is not None or pixel_values_videos is not None) and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one\"\n )\n\n legacy_processing = False\n if inputs_embeds is None:\n inputs_embeds = self.get_input_embeddings()(input_ids)\n\n # if the number of image/video tokens is more than image embeddings seq length, then prob we expanded it in processing\n # not very reliable, but we don't expect one to actually pass 500+ images for one prompt\n img_token_not_enough = (input_ids == self.config.image_token_index).sum(\n 1\n ).max() < self.config.image_seq_length\n video_token_not_enough = (input_ids == self.config.video_token_index).sum(\n 1\n ).max() < self.config.video_seq_length\n inputs_not_expanded = (img_token_not_enough and pixel_values_images is not None) or (\n video_token_not_enough and pixel_values_videos is not None\n )\n pixels_present = input_ids.shape[-1] == 1 and (\n pixel_values_images is not None or pixel_values_videos is not None\n )\n legacy_processing = inputs_not_expanded or pixels_present\n\n if pixel_values_images is not None or pixel_values_videos is not None:\n image_outputs, video_outputs, num_frames = self._get_vision_features(\n pixel_values_images=pixel_values_images,\n pixel_values_videos=pixel_values_videos,\n vision_feature_layer=vision_feature_layer,\n vision_feature_select_strategy=vision_feature_select_strategy,\n )\n\n image_features = video_features = None\n if image_outputs is not None:\n image_features = self.multi_modal_projector(image_outputs)\n if video_outputs is not None:\n video_features = self.multi_modal_projector(video_outputs)\n\n if legacy_processing:\n logger.warning_once(\n \"Expanding inputs for image tokens in Video-LLaVa should be done in processing. \"\n \"Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly \"\n \"with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. \"\n \"Using processors without these attributes in the config is deprecated and will throw an error in v4.47.\"\n )\n if input_ids.shape[1] != 1:\n for features, frames in ((image_features, 1), (video_features, num_frames)):\n if features is not None:\n (\n inputs_embeds,\n attention_mask,\n labels,\n position_ids,\n input_ids,\n ) = self._merge_input_ids_with_visual_features(\n features,\n inputs_embeds,\n input_ids,\n attention_mask,\n labels,\n num_frames=frames,\n )\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)\n else:\n # Retrieve the first layer to inspect the logits and mask out the hidden states\n # that are set to 0\n first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]\n\n # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941\n batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)\n\n target_length = input_ids.shape[1]\n past_length = first_layer_past_key_value.shape[-1]\n\n extended_attention_mask = torch.ones(\n (attention_mask.shape[0], past_length),\n dtype=attention_mask.dtype,\n device=attention_mask.device,\n )\n\n # Filter out only the tokens that can be un-attended, this can happen\n # if one uses Llava + Fused modules where the cache on the\n # first iteration is already big enough, or if one passes custom cache\n valid_indices = non_attended_tokens < extended_attention_mask.size(-1)\n new_batch_index = batch_index[valid_indices]\n new_non_attended_tokens = non_attended_tokens[valid_indices]\n\n # Zero-out the places where we don't need to attend\n extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0\n\n attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)\n position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)[\n -target_length:\n ]\n\n # TODO: @raushan retain only the new behavior after v4.47\n else:\n if image_outputs is not None:\n special_image_mask = (\n (input_ids == self.config.image_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)\n\n if video_outputs is not None:\n special_image_mask = (\n (input_ids == self.config.video_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, video_features)\n\n outputs = self.language_model(\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n cache_position=cache_position,\n num_logits_to_keep=num_logits_to_keep,\n )\n\n logits = outputs[0]\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n # we use the input attention mask to shift the logits and labels, because it is 2D.\n # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft\n shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)\n shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()\n shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()\n else:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(\n shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)\n )\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return VideoLlavaCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=image_features if pixel_values_images is not None else None,\n video_hidden_states=video_features if pixel_values_videos is not None else None,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=96103,\n max_position_embeddings=16384,\n encoder_layers=16,\n encoder_ffn_dim=4096,\n encoder_attention_heads=16,\n decoder_layers=16,\n decoder_ffn_dim=4096,\n decoder_attention_heads=16,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=1024,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=0,\n scale_embedding=True,\n pad_token_id=0,\n eos_token_id=1,\n forced_eos_token_id=1,\n num_global_tokens=32,\n block_size=512,\n stagger_local_blocks=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n\n self.num_global_tokens = num_global_tokens\n self.block_size = block_size\n self.stagger_local_blocks = stagger_local_blocks\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutputWithPastAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have\n their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past`). Set to `False` during training, `True` during generation\n \"\"\"\n\n outputs = self.transformer(\n input_ids=input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n global_attention_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqSequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n if input_ids is None and inputs_embeds is not None:\n raise NotImplementedError(\n f\"Passing input embeddings is currently not supported for {self.__class__.__name__}\"\n )\n\n outputs = self.led(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = outputs[0] # last hidden state\n\n eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)\n\n if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:\n raise ValueError(\"All examples must have the same number of <eos> tokens.\")\n sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[\n :, -1, :\n ]\n logits = self.classification_head(sentence_representation)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.config.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.config.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return LEDSeq2SeqSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n encoder_global_attentions=outputs.encoder_global_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n seq_length=8,\n is_training=True,\n use_token_type_ids=False,\n use_input_mask=False,\n use_labels=False,\n use_mc_token_ids=False,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n num_buckets=32,\n max_distance=128,\n prompt_length=8,\n prompt_types=8,\n segment_types=8,\n init_std=0.02,\n return_dict=True,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.num_buckets = num_buckets\n self.max_distance = max_distance\n self.prompt_length = prompt_length\n self.prompt_types = prompt_types\n self.segment_types = segment_types\n self.init_std = init_std\n self.return_dict = return_dict", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=32,\n patch_size=16,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n projection_dim=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_token_type_ids=False,\n use_input_mask=True,\n use_labels=True,\n use_mc_token_ids=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_dropout_prob = attention_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n global_attention_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # Using this like Bart, as LED is derived from it. So far\n # No checkpoint on the hub exists that uses that in practice.\n # https://github.com/huggingface/transformers/blob/ac3cb660cad283163f7c73cad511124e845ca388/src/transformers/models/bart/modeling_bart.py#L1153\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n input_ids, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a LEDEncoderBaseModelOutput when return_dict=False\n elif return_dict and not isinstance(encoder_outputs, LEDEncoderBaseModelOutput):\n encoder_outputs = LEDEncoderBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n global_attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return LEDSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n encoder_global_attentions=encoder_outputs.global_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def install(\n install_options: List[str],\n global_options: Sequence[str],\n root: Optional[str],\n home: Optional[str],\n prefix: Optional[str],\n use_user_site: bool,\n pycompile: bool,\n scheme: Scheme,\n setup_py_path: str,\n isolated: bool,\n req_name: str,\n build_env: BuildEnvironment,\n unpacked_source_directory: str,\n req_description: str,\n) -> bool:\n\n header_dir = scheme.headers\n\n with TempDirectory(kind=\"record\") as temp_dir:\n try:\n record_filename = os.path.join(temp_dir.path, \"install-record.txt\")\n install_args = make_setuptools_install_args(\n setup_py_path,\n global_options=global_options,\n install_options=install_options,\n record_filename=record_filename,\n root=root,\n prefix=prefix,\n header_dir=header_dir,\n home=home,\n use_user_site=use_user_site,\n no_user_config=isolated,\n pycompile=pycompile,\n )\n\n runner = runner_with_spinner_message(\n f\"Running setup.py install for {req_name}\"\n )\n with build_env:\n runner(\n cmd=install_args,\n cwd=unpacked_source_directory,\n )\n\n if not os.path.exists(record_filename):\n logger.debug(\"Record file %s not found\", record_filename)\n # Signal to the caller that we didn't install the new package\n return False\n\n except Exception as e:\n # Signal to the caller that we didn't install the new package\n raise LegacyInstallFailure(package_details=req_name) from e\n\n # At this point, we have successfully installed the requirement.\n\n # We intentionally do not use any encoding to read the file because\n # setuptools writes the file using distutils.file_util.write_file,\n # which does not specify an encoding.\n with open(record_filename) as f:\n record_lines = f.read().splitlines()\n\n write_installed_files_from_setuptools_record(record_lines, root, req_description)\n return True", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"silu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *,\n cred_ex_id: Optional[str] = None,\n connection_id: Optional[str] = None,\n verification_method: Optional[str] = None,\n thread_id: Optional[str] = None,\n parent_thread_id: Optional[str] = None,\n initiator: Optional[str] = None,\n role: Optional[str] = None,\n state: Optional[str] = None,\n cred_proposal: Union[Mapping, V20CredProposal] = None, # aries message\n cred_offer: Union[Mapping, V20CredOffer] = None, # aries message\n cred_request: Union[Mapping, V20CredRequest] = None, # aries message\n cred_issue: Union[Mapping, V20CredIssue] = None, # aries message\n auto_offer: bool = False,\n auto_issue: bool = False,\n auto_remove: bool = True,\n error_msg: Optional[str] = None,\n trace: bool = False, # backward compat: BaseRecord.from_storage()\n cred_id_stored: Optional[\n str\n ] = None, # backward compat: BaseRecord.from_storage()\n conn_id: Optional[str] = None, # backward compat: BaseRecord.from_storage()\n by_format: Optional[Mapping] = None, # backward compat: BaseRecord.from_storage()\n **kwargs,\n ):\n \"\"\"Initialize a new V20CredExRecord.\"\"\"\n super().__init__(cred_ex_id, state, trace=trace, **kwargs)\n self._id = cred_ex_id\n self.connection_id = connection_id or conn_id\n self.verification_method = verification_method\n self.thread_id = thread_id\n self.parent_thread_id = parent_thread_id\n self.initiator = initiator\n self.role = role\n self.state = state\n self._cred_proposal = V20CredProposal.serde(cred_proposal)\n self._cred_offer = V20CredOffer.serde(cred_offer)\n self._cred_request = V20CredRequest.serde(cred_request)\n self._cred_issue = V20CredIssue.serde(cred_issue)\n self.auto_offer = auto_offer\n self.auto_issue = auto_issue\n self.auto_remove = auto_remove\n self.error_msg = error_msg", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def __init__(\n self,\n vocab_file=None,\n merges_file=None,\n tokenizer_file=None,\n errors=\"replace\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n add_prefix_space=False,\n trim_offsets=True,\n **kwargs,\n ):\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token\n cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n super().__init__(\n vocab_file,\n merges_file,\n tokenizer_file=tokenizer_file,\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n sep_token=sep_token,\n cls_token=cls_token,\n unk_token=unk_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n trim_offsets=trim_offsets,\n **kwargs,\n )\n\n pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())\n if pre_tok_state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop(\"type\"))\n pre_tok_state[\"add_prefix_space\"] = add_prefix_space\n self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)\n\n self.add_prefix_space = add_prefix_space\n\n # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`\n tokenizer_component = \"post_processor\"\n tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)\n if tokenizer_component_instance:\n state = json.loads(tokenizer_component_instance.__getstate__())\n\n # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`\n if \"sep\" in state:\n state[\"sep\"] = tuple(state[\"sep\"])\n if \"cls\" in state:\n state[\"cls\"] = tuple(state[\"cls\"])\n\n changes_to_apply = False\n\n if state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n state[\"add_prefix_space\"] = add_prefix_space\n changes_to_apply = True\n\n if state.get(\"trim_offsets\", trim_offsets) != trim_offsets:\n state[\"trim_offsets\"] = trim_offsets\n changes_to_apply = True\n\n if changes_to_apply:\n component_class = getattr(processors, state.pop(\"type\"))\n new_value = component_class(**state)\n setattr(self.backend_tokenizer, tokenizer_component, new_value)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=32,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *,\n created_at: datetime | None = None,\n data: Mapping[str, Any],\n disabled_by: ConfigEntryDisabler | None = None,\n domain: str,\n entry_id: str | None = None,\n minor_version: int,\n modified_at: datetime | None = None,\n options: Mapping[str, Any] | None,\n pref_disable_new_entities: bool | None = None,\n pref_disable_polling: bool | None = None,\n source: str,\n state: ConfigEntryState = ConfigEntryState.NOT_LOADED,\n title: str,\n unique_id: str | None,\n version: int,\n ) -> None:\n \"\"\"Initialize a config entry.\"\"\"\n _setter = object.__setattr__\n # Unique id of the config entry\n _setter(self, \"entry_id\", entry_id or ulid_util.ulid_now())\n\n # Version of the configuration.\n _setter(self, \"version\", version)\n _setter(self, \"minor_version\", minor_version)\n\n # Domain the configuration belongs to\n _setter(self, \"domain\", domain)\n\n # Title of the configuration\n _setter(self, \"title\", title)\n\n # Config data\n _setter(self, \"data\", MappingProxyType(data))\n\n # Entry options\n _setter(self, \"options\", MappingProxyType(options or {}))\n\n # Entry system options\n if pref_disable_new_entities is None:\n pref_disable_new_entities = False\n\n _setter(self, \"pref_disable_new_entities\", pref_disable_new_entities)\n\n if pref_disable_polling is None:\n pref_disable_polling = False\n\n _setter(self, \"pref_disable_polling\", pref_disable_polling)\n\n # Source of the configuration (user, discovery, cloud)\n _setter(self, \"source\", source)\n\n # State of the entry (LOADED, NOT_LOADED)\n _setter(self, \"state\", state)\n\n # Unique ID of this entry.\n _setter(self, \"unique_id\", unique_id)\n\n # Config entry is disabled\n if isinstance(disabled_by, str) and not isinstance(\n disabled_by, ConfigEntryDisabler\n ):\n report( # type: ignore[unreachable]\n (\n \"uses str for config entry disabled_by. This is deprecated and will\"\n \" stop working in Home Assistant 2022.3, it should be updated to\"\n \" use ConfigEntryDisabler instead\"\n ),\n error_if_core=False,\n )\n disabled_by = ConfigEntryDisabler(disabled_by)\n _setter(self, \"disabled_by\", disabled_by)\n\n # Supports unload\n _setter(self, \"supports_unload\", None)\n\n # Supports remove device\n _setter(self, \"supports_remove_device\", None)\n\n # Supports options\n _setter(self, \"_supports_options\", None)\n\n # Supports reconfigure\n _setter(self, \"_supports_reconfigure\", None)\n\n # Listeners to call on update\n _setter(self, \"update_listeners\", [])\n\n # Reason why config entry is in a failed state\n _setter(self, \"reason\", None)\n _setter(self, \"error_reason_translation_key\", None)\n _setter(self, \"error_reason_translation_placeholders\", None)\n\n # Function to cancel a scheduled retry\n _setter(self, \"_async_cancel_retry_setup\", None)\n\n # Hold list for actions to call on unload.\n _setter(self, \"_on_unload\", None)\n\n # Reload lock to prevent conflicting reloads\n _setter(self, \"setup_lock\", asyncio.Lock())\n # Reauth lock to prevent concurrent reauth flows\n _setter(self, \"_reauth_lock\", asyncio.Lock())\n # Reconfigure lock to prevent concurrent reconfigure flows\n _setter(self, \"_reconfigure_lock\", asyncio.Lock())\n\n _setter(self, \"_tasks\", set())\n _setter(self, \"_background_tasks\", set())\n\n _setter(self, \"_integration_for_domain\", None)\n _setter(self, \"_tries\", 0)\n _setter(self, \"created_at\", created_at or utcnow())\n _setter(self, \"modified_at\", modified_at or utcnow())", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n intermediate_size=3072,\n projection_dim=512,\n num_hidden_layers=12,\n num_attention_heads=12,\n num_channels=3,\n image_size=224,\n patch_size=32,\n hidden_act=\"quick_gelu\",\n layer_norm_eps=1e-5,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_channels = num_channels\n self.patch_size = patch_size\n self.image_size = image_size\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.attention_dropout = attention_dropout\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_center_crop=True,\n crop_size=None,\n do_normalize=True,\n image_mean=[0.48145466, 0.4578275, 0.40821073],\n image_std=[0.26862954, 0.26130258, 0.27577711],\n do_convert_rgb=True,\n ):\n size = size if size is not None else {\"shortest_edge\": 20}\n crop_size = crop_size if crop_size is not None else {\"height\": 18, \"width\": 18}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_center_crop = do_center_crop\n self.crop_size = crop_size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _api_database_instances_v3_get_serialize(\n self,\n chart_release,\n created_at,\n default_database,\n google_project,\n id,\n instance_name,\n platform,\n updated_at,\n limit,\n offset,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if chart_release is not None:\n \n _query_params.append(('chartRelease', chart_release))\n \n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if default_database is not None:\n \n _query_params.append(('defaultDatabase', default_database))\n \n if google_project is not None:\n \n _query_params.append(('googleProject', google_project))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if instance_name is not None:\n \n _query_params.append(('instanceName', instance_name))\n \n if platform is not None:\n \n _query_params.append(('platform', platform))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/database-instances/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[TFBaseModelOutput] = None,\n past_key_values: List[tf.Tensor] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: tf.Tensor | None = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:\n r\"\"\"\n labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n\n if labels is not None:\n labels = tf.where(\n labels == self.config.pad_token_id,\n tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),\n labels,\n )\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)\n lm_logits = self.bias_layer(lm_logits)\n masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n return TFSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values, # index 1 of d outputs\n decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs\n decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs\n cross_attentions=outputs.cross_attentions, # index 4 of d outputs\n encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs\n encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out\n encoder_attentions=outputs.encoder_attentions, # 2 of e out\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n prediction_length: Optional[int] = None,\n context_length: Optional[int] = None,\n distribution_output: str = \"student_t\",\n loss: str = \"nll\",\n input_size: int = 1,\n lags_sequence: List[int] = [1, 2, 3, 4, 5, 6, 7],\n scaling: bool = True,\n num_time_features: int = 0,\n num_dynamic_real_features: int = 0,\n num_static_categorical_features: int = 0,\n num_static_real_features: int = 0,\n cardinality: Optional[List[int]] = None,\n embedding_dimension: Optional[List[int]] = None,\n d_model: int = 64,\n encoder_attention_heads: int = 2,\n decoder_attention_heads: int = 2,\n encoder_layers: int = 2,\n decoder_layers: int = 2,\n encoder_ffn_dim: int = 32,\n decoder_ffn_dim: int = 32,\n activation_function: str = \"gelu\",\n dropout: float = 0.1,\n encoder_layerdrop: float = 0.1,\n decoder_layerdrop: float = 0.1,\n attention_dropout: float = 0.1,\n activation_dropout: float = 0.1,\n num_parallel_samples: int = 100,\n init_std: float = 0.02,\n use_cache: bool = True,\n is_encoder_decoder=True,\n # Autoformer arguments\n label_length: int = 10,\n moving_average: int = 25,\n autocorrelation_factor: int = 3,\n **kwargs,\n ):\n # time series specific configuration\n self.prediction_length = prediction_length\n self.context_length = context_length if context_length is not None else prediction_length\n self.distribution_output = distribution_output\n self.loss = loss\n self.input_size = input_size\n self.num_time_features = num_time_features\n self.lags_sequence = lags_sequence\n self.scaling = scaling\n self.num_dynamic_real_features = num_dynamic_real_features\n self.num_static_real_features = num_static_real_features\n self.num_static_categorical_features = num_static_categorical_features\n if cardinality is not None and num_static_categorical_features > 0:\n if len(cardinality) != num_static_categorical_features:\n raise ValueError(\n \"The cardinality should be a list of the same length as `num_static_categorical_features`\"\n )\n self.cardinality = cardinality\n else:\n self.cardinality = [0]\n if embedding_dimension is not None and num_static_categorical_features > 0:\n if len(embedding_dimension) != num_static_categorical_features:\n raise ValueError(\n \"The embedding dimension should be a list of the same length as `num_static_categorical_features`\"\n )\n self.embedding_dimension = embedding_dimension\n else:\n self.embedding_dimension = [min(50, (cat + 1) // 2) for cat in self.cardinality]\n self.num_parallel_samples = num_parallel_samples\n\n # Transformer architecture configuration\n self.feature_size = input_size * len(self.lags_sequence) + self._number_of_features\n self.d_model = d_model\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_attention_heads = decoder_attention_heads\n self.encoder_ffn_dim = encoder_ffn_dim\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.decoder_layers = decoder_layers\n\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n\n self.activation_function = activation_function\n self.init_std = init_std\n\n self.use_cache = use_cache\n\n # Autoformer\n self.label_length = label_length\n self.moving_average = moving_average\n self.autocorrelation_factor = autocorrelation_factor\n\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=9,\n local_radius=5,\n encoder_attention_type=\"local\",\n global_block_size=3,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n scope=None,\n decoder_layers=None,\n large_model_config_path=\"google/long-t5-local-large\",\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n self.local_radius = local_radius\n self.block_len = local_radius + 1\n self.encoder_attention_type = encoder_attention_type\n self.global_block_size = global_block_size\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = decoder_layers\n self.large_model_config_path = large_model_config_path", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFXLNetForQuestionAnsweringSimpleOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n mems: np.ndarray | tf.Tensor | None = None,\n perm_mask: np.ndarray | tf.Tensor | None = None,\n target_mapping: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n input_mask: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_mems: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n start_positions: np.ndarray | tf.Tensor | None = None,\n end_positions: np.ndarray | tf.Tensor | None = None,\n training: bool = False,\n ) -> Union[TFXLNetForQuestionAnsweringSimpleOutput, Tuple[tf.Tensor]]:\n r\"\"\"\n start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\n transformer_outputs = self.transformer(\n input_ids=input_ids,\n attention_mask=attention_mask,\n mems=mems,\n perm_mask=perm_mask,\n target_mapping=target_mapping,\n token_type_ids=token_type_ids,\n input_mask=input_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_mems=use_mems,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n sequence_output = transformer_outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = tf.split(logits, 2, axis=-1)\n start_logits = tf.squeeze(start_logits, axis=-1)\n end_logits = tf.squeeze(end_logits, axis=-1)\n\n loss = None\n if start_positions is not None and end_positions is not None:\n labels = {\"start_position\": start_positions}\n labels[\"end_position\"] = end_positions\n loss = self.hf_compute_loss(labels, (start_logits, end_logits))\n\n if not return_dict:\n output = (start_logits, end_logits) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFXLNetForQuestionAnsweringSimpleOutput(\n loss=loss,\n start_logits=start_logits,\n end_logits=end_logits,\n mems=transformer_outputs.mems,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n feature_size: int = 1,\n sampling_rate: int = 24000,\n padding_value: float = 0.0,\n do_normalize: bool = False,\n num_mel_bins: int = 100,\n hop_length: int = 256,\n win_length: int = 1024,\n win_function: str = \"hann_window\",\n filter_length: Optional[int] = 1024,\n max_length_s: int = 10,\n fmin: float = 0.0,\n fmax: Optional[float] = None,\n mel_floor: float = 1e-9,\n center: bool = False,\n compression_factor: float = 1.0,\n compression_clip_val: float = 1e-5,\n normalize_min: float = -11.512925148010254,\n normalize_max: float = 2.3143386840820312,\n model_in_channels: int = 64,\n pad_end_length: int = 10,\n return_attention_mask=True,\n **kwargs,\n ):\n super().__init__(\n feature_size=feature_size,\n sampling_rate=sampling_rate,\n padding_value=padding_value,\n return_attention_mask=return_attention_mask,\n **kwargs,\n )\n\n self.do_normalize = do_normalize\n\n self.num_mel_bins = num_mel_bins\n self.hop_length = hop_length\n self.win_length = win_length\n self.win_function = win_function\n self.filter_length = filter_length\n self.fmin = fmin\n if fmax is None:\n # Follows the librosa.filters.mel implementation\n fmax = float(sampling_rate) / 2\n self.fmax = fmax\n self.mel_floor = mel_floor\n\n self.max_length_s = max_length_s\n self.num_max_samples = max_length_s * sampling_rate\n\n if self.filter_length is None:\n self.n_fft = optimal_fft_length(self.win_length)\n else:\n self.n_fft = self.filter_length\n self.n_freqs = (self.n_fft // 2) + 1\n\n self.window = window_function(window_length=self.win_length, name=self.win_function, periodic=True)\n\n self.mel_filters = mel_filter_bank(\n num_frequency_bins=self.n_freqs,\n num_mel_filters=self.num_mel_bins,\n min_frequency=self.fmin,\n max_frequency=self.fmax,\n sampling_rate=self.sampling_rate,\n norm=\"slaney\",\n mel_scale=\"slaney\",\n )\n\n self.center = center\n self.compression_factor = compression_factor\n self.compression_clip_val = compression_clip_val\n self.normalize_min = normalize_min\n self.normalize_max = normalize_max\n self.model_in_channels = model_in_channels\n self.pad_end_length = pad_end_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@_handle_reauth\n def command(\n self,\n dbname: str,\n spec: MutableMapping[str, Any],\n read_preference: _ServerMode = ReadPreference.PRIMARY,\n codec_options: CodecOptions = DEFAULT_CODEC_OPTIONS,\n check: bool = True,\n allowable_errors: Optional[Sequence[Union[str, int]]] = None,\n read_concern: Optional[ReadConcern] = None,\n write_concern: Optional[WriteConcern] = None,\n parse_write_concern_error: bool = False,\n collation: Optional[_CollationIn] = None,\n session: Optional[ClientSession] = None,\n client: Optional[MongoClient] = None,\n retryable_write: bool = False,\n publish_events: bool = True,\n user_fields: Optional[Mapping[str, Any]] = None,\n exhaust_allowed: bool = False,\n ) -> dict[str, Any]:\n \"\"\"Execute a command or raise an error.\n\n :param dbname: name of the database on which to run the command\n :param spec: a command document as a dict, SON, or mapping object\n :param read_preference: a read preference\n :param codec_options: a CodecOptions instance\n :param check: raise OperationFailure if there are errors\n :param allowable_errors: errors to ignore if `check` is True\n :param read_concern: The read concern for this command.\n :param write_concern: The write concern for this command.\n :param parse_write_concern_error: Whether to parse the\n ``writeConcernError`` field in the command response.\n :param collation: The collation for this command.\n :param session: optional ClientSession instance.\n :param client: optional MongoClient for gossipping $clusterTime.\n :param retryable_write: True if this command is a retryable write.\n :param publish_events: Should we publish events for this command?\n :param user_fields: Response fields that should be decoded\n using the TypeDecoders from codec_options, passed to\n bson._decode_all_selective.\n \"\"\"\n self.validate_session(client, session)\n session = _validate_session_write_concern(session, write_concern)\n\n # Ensure command name remains in first place.\n if not isinstance(spec, ORDERED_TYPES): # type:ignore[arg-type]\n spec = dict(spec)\n\n if not (write_concern is None or write_concern.acknowledged or collation is None):\n raise ConfigurationError(\"Collation is unsupported for unacknowledged writes.\")\n\n self.add_server_api(spec)\n if session:\n session._apply_to(spec, retryable_write, read_preference, self)\n self.send_cluster_time(spec, session, client)\n listeners = self.listeners if publish_events else None\n unacknowledged = bool(write_concern and not write_concern.acknowledged)\n if self.op_msg_enabled:\n self._raise_if_not_writable(unacknowledged)\n try:\n return command(\n self,\n dbname,\n spec,\n self.is_mongos,\n read_preference,\n codec_options,\n session,\n client,\n check,\n allowable_errors,\n self.address,\n listeners,\n self.max_bson_size,\n read_concern,\n parse_write_concern_error=parse_write_concern_error,\n collation=collation,\n compression_ctx=self.compression_context,\n use_op_msg=self.op_msg_enabled,\n unacknowledged=unacknowledged,\n user_fields=user_fields,\n exhaust_allowed=exhaust_allowed,\n write_concern=write_concern,\n )\n except (OperationFailure, NotPrimaryError):\n raise\n # Catch socket.error, KeyboardInterrupt, etc. and close ourselves.\n except BaseException as error:\n self._raise_connection_failure(error)", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n use_cache=True,\n pad_token_id=0,\n position_embedding_type=\"absolute\",\n classifier_dropout=None,\n enable_pronunciation=True,\n enable_shape=True,\n pronunciation_embed_dim=768,\n pronunciation_vocab_size=910,\n shape_embed_dim=512,\n shape_vocab_size=24858,\n concat_input=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.type_vocab_size = type_vocab_size\n self.layer_norm_eps = layer_norm_eps\n self.use_cache = use_cache\n self.enable_pronunciation = enable_pronunciation\n self.enable_shape = enable_shape\n self.pronunciation_embed_dim = pronunciation_embed_dim\n self.pronunciation_vocab_size = pronunciation_vocab_size\n self.shape_embed_dim = shape_embed_dim\n self.shape_vocab_size = shape_vocab_size\n self.concat_input = concat_input\n self.position_embedding_type = position_embedding_type\n self.classifier_dropout = classifier_dropout\n super().__init__(pad_token_id=pad_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=1024, # speech is longer\n is_training=False,\n hidden_size=16,\n feat_extract_norm=\"group\",\n feat_extract_dropout=0.0,\n feat_extract_activation=\"gelu\",\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n num_hidden_layers=2,\n num_attention_heads=2,\n hidden_dropout_prob=0.1,\n intermediate_size=20,\n layer_norm_eps=1e-5,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n mask_time_prob=0.5,\n mask_time_length=2,\n vocab_size=32,\n do_stable_layer_norm=False,\n num_adapter_layers=1,\n adapter_stride=2,\n tdnn_dim=(32, 32),\n tdnn_kernel=(5, 3),\n tdnn_dilation=(1, 2),\n xvector_output_dim=32,\n position_embeddings_type=\"relative\",\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_dropout = feat_extract_dropout\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.intermediate_size = intermediate_size\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.num_adapter_layers = num_adapter_layers\n self.adapter_stride = adapter_stride\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.scope = scope\n self.tdnn_dim = tdnn_dim\n self.tdnn_kernel = tdnn_kernel\n self.tdnn_dilation = tdnn_dilation\n self.xvector_output_dim = xvector_output_dim\n self.position_embeddings_type = position_embeddings_type\n\n output_seq_length = self.seq_length\n for kernel, stride in zip(self.conv_kernel, self.conv_stride):\n output_seq_length = (output_seq_length - (kernel - 1)) / stride\n self.output_seq_length = int(math.ceil(output_seq_length))\n self.encoder_seq_length = self.output_seq_length\n\n self.adapter_output_seq_length = (self.output_seq_length - 1) // adapter_stride + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50358,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu_new\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=4096,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n use_cache=True,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n sep_token_id=66,\n attention_type=\"block_sparse\",\n use_bias=True,\n rescale_embeddings=False,\n block_size=64,\n num_random_blocks=3,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n sep_token_id=sep_token_id,\n **kwargs,\n )\n\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.type_vocab_size = type_vocab_size\n self.layer_norm_eps = layer_norm_eps\n self.use_cache = use_cache\n\n self.rescale_embeddings = rescale_embeddings\n self.attention_type = attention_type\n self.use_bias = use_bias\n self.block_size = block_size\n self.num_random_blocks = num_random_blocks\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *,\n connection_id: Optional[str] = None,\n my_did: Optional[str] = None,\n their_did: Optional[str] = None,\n their_label: Optional[str] = None,\n their_role: Union[str, \"ConnRecord.Role\", None] = None,\n invitation_key: Optional[str] = None,\n invitation_msg_id: Optional[str] = None,\n request_id: Optional[str] = None,\n state: Union[str, \"ConnRecord.State\", None] = None,\n inbound_connection_id: Optional[str] = None,\n error_msg: Optional[str] = None,\n accept: Optional[str] = None,\n invitation_mode: Optional[str] = None,\n alias: Optional[str] = None,\n their_public_did: Optional[str] = None,\n connection_protocol: Optional[str] = None,\n # from state: formalism for base_record.from_storage()\n rfc23_state: Optional[str] = None,\n # for backward compat with old records\n routing_state: Optional[str] = None,\n # for backward compatibility with old ConnectionRecord\n initiator: Optional[str] = None,\n **kwargs,\n ):\n \"\"\"Initialize a new ConnRecord.\"\"\"\n super().__init__(\n connection_id,\n state=(ConnRecord.State.get(state) or ConnRecord.State.INIT).rfc160,\n **kwargs,\n )\n self.my_did = my_did\n self.their_did = their_did\n self.their_label = their_label\n self.their_role = (\n ConnRecord.Role.get(their_role).rfc160\n if isinstance(their_role, str)\n else None\n if their_role is None\n else their_role.rfc160\n )\n self.invitation_key = invitation_key\n self.invitation_msg_id = invitation_msg_id\n self.request_id = request_id\n self.error_msg = error_msg\n self.inbound_connection_id = inbound_connection_id\n self.accept = accept or self.ACCEPT_MANUAL\n self.invitation_mode = invitation_mode or self.INVITATION_MODE_ONCE\n self.alias = alias\n self.their_public_did = their_public_did\n self.connection_protocol = (\n connection_protocol\n if connection_protocol in self.SUPPORTED_PROTOCOLS\n else None\n )", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids: TFModelInputType = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[TFSeq2SeqModelOutput, tf.Tensor]:\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n use_cache = False\n\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n\n if decoder_input_ids is None and input_ids is not None:\n decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id)\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):\n encoder_outputs = TFBaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False\n elif not return_dict and not isinstance(encoder_outputs, tuple):\n encoder_outputs = encoder_outputs.to_tuple()\n\n decoder_outputs = self.decoder(\n decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "async def create_server(\n self, protocol_factory, host=None, port=None,\n *,\n family=socket.AF_UNSPEC,\n flags=socket.AI_PASSIVE,\n sock=None,\n backlog=100,\n ssl=None,\n reuse_address=None,\n reuse_port=None,\n keep_alive=None,\n ssl_handshake_timeout=None,\n ssl_shutdown_timeout=None,\n start_serving=True):\n \"\"\"Create a TCP server.\n\n The host parameter can be a string, in that case the TCP server is\n bound to host and port.\n\n The host parameter can also be a sequence of strings and in that case\n the TCP server is bound to all hosts of the sequence. If a host\n appears multiple times (possibly indirectly e.g. when hostnames\n resolve to the same IP address), the server is only bound once to that\n host.\n\n Return a Server object which can be used to stop the service.\n\n This method is a coroutine.\n \"\"\"\n if isinstance(ssl, bool):\n raise TypeError('ssl argument must be an SSLContext or None')\n\n if ssl_handshake_timeout is not None and ssl is None:\n raise ValueError(\n 'ssl_handshake_timeout is only meaningful with ssl')\n\n if ssl_shutdown_timeout is not None and ssl is None:\n raise ValueError(\n 'ssl_shutdown_timeout is only meaningful with ssl')\n\n if sock is not None:\n _check_ssl_socket(sock)\n\n if host is not None or port is not None:\n if sock is not None:\n raise ValueError(\n 'host/port and sock can not be specified at the same time')\n\n if reuse_address is None:\n reuse_address = os.name == \"posix\" and sys.platform != \"cygwin\"\n sockets = []\n if host == '':\n hosts = [None]\n elif (isinstance(host, str) or\n not isinstance(host, collections.abc.Iterable)):\n hosts = [host]\n else:\n hosts = host\n\n fs = [self._create_server_getaddrinfo(host, port, family=family,\n flags=flags)\n for host in hosts]\n infos = await tasks.gather(*fs)\n infos = set(itertools.chain.from_iterable(infos))\n\n completed = False\n try:\n for res in infos:\n af, socktype, proto, canonname, sa = res\n try:\n sock = socket.socket(af, socktype, proto)\n except socket.error:\n # Assume it's a bad family/type/protocol combination.\n if self._debug:\n logger.warning('create_server() failed to create '\n 'socket.socket(%r, %r, %r)',\n af, socktype, proto, exc_info=True)\n continue\n sockets.append(sock)\n if reuse_address:\n sock.setsockopt(\n socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n if reuse_port:\n _set_reuseport(sock)\n if keep_alive:\n sock.setsockopt(\n socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)\n # Disable IPv4/IPv6 dual stack support (enabled by\n # default on Linux) which makes a single socket\n # listen on both address families.\n if (_HAS_IPv6 and\n af == socket.AF_INET6 and\n hasattr(socket, 'IPPROTO_IPV6')):\n sock.setsockopt(socket.IPPROTO_IPV6,\n socket.IPV6_V6ONLY,\n True)\n try:\n sock.bind(sa)\n except OSError as err:\n msg = ('error while attempting '\n 'to bind on address %r: %s'\n % (sa, str(err).lower()))\n if err.errno == errno.EADDRNOTAVAIL:\n # Assume the family is not enabled (bpo-30945)\n sockets.pop()\n sock.close()\n if self._debug:\n logger.warning(msg)\n continue\n raise OSError(err.errno, msg) from None\n\n if not sockets:\n raise OSError('could not bind on any address out of %r'\n % ([info[4] for info in infos],))\n\n completed = True\n finally:\n if not completed:\n for sock in sockets:\n sock.close()\n else:\n if sock is None:\n raise ValueError('Neither host/port nor sock were specified')\n if sock.type != socket.SOCK_STREAM:\n raise ValueError(f'A Stream Socket was expected, got {sock!r}')\n sockets = [sock]\n\n for sock in sockets:\n sock.setblocking(False)\n\n server = Server(self, sockets, protocol_factory,\n ssl, backlog, ssl_handshake_timeout,\n ssl_shutdown_timeout)\n if start_serving:\n server._start_serving()\n # Skip one loop iteration so that all 'loop.add_reader'\n # go through.\n await tasks.sleep(0)\n\n if self._debug:\n logger.info(\"%r is serving\", server)\n return server", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n pruning_method=\"topK\",\n mask_init=\"constant\",\n mask_scale=0.0,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.pruning_method = pruning_method\n self.mask_init = mask_init\n self.mask_scale = mask_scale", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n input_modality=\"speech\",\n batch_size=2,\n seq_length=4,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n max_new_tokens=None,\n num_labels=3,\n num_choices=4,\n scope=None,\n vocab_size=20,\n t2u_vocab_size=20,\n hidden_size=6,\n num_hidden_layers=2,\n intermediate_size=6,\n max_position_embeddings=256,\n encoder_layers=2,\n decoder_layers=2,\n encoder_ffn_dim=6,\n decoder_ffn_dim=6,\n t2u_encoder_layers=2,\n t2u_decoder_layers=2,\n t2u_encoder_ffn_dim=6,\n t2u_decoder_ffn_dim=6,\n num_heads=2,\n vocoder_num_spkrs=5,\n vocoder_num_langs=5,\n upsample_initial_channel=32,\n unit_embed_dim=25,\n spkr_embed_dim=6,\n lang_embed_dim=6,\n num_conv_pos_embeddings=8,\n unit_hifi_gan_vocab_size=20,\n t2u_num_langs=0,\n t2u_offset_tgt_lang=0,\n vocoder_offset=0,\n t2u_variance_predictor_hidden_dim=4,\n char_vocab_size=4,\n left_max_position_embeddings=2,\n right_max_position_embeddings=1,\n speech_encoder_chunk_size=2,\n speech_encoder_left_chunk_num=1,\n ):\n self.parent = parent\n self.input_modality = input_modality\n\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n\n self.vocab_size = vocab_size\n self.t2u_vocab_size = t2u_vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.max_position_embeddings = max_position_embeddings\n self.encoder_layers = encoder_layers\n self.decoder_layers = decoder_layers\n self.encoder_ffn_dim = encoder_ffn_dim\n self.decoder_ffn_dim = decoder_ffn_dim\n self.t2u_encoder_layers = t2u_encoder_layers\n self.t2u_decoder_layers = t2u_decoder_layers\n self.t2u_encoder_ffn_dim = t2u_encoder_ffn_dim\n self.t2u_decoder_ffn_dim = t2u_decoder_ffn_dim\n self.num_heads = num_heads\n self.num_attention_heads = num_heads\n\n self.vocoder_num_spkrs = vocoder_num_spkrs\n self.vocoder_num_langs = vocoder_num_langs\n self.upsample_initial_channel = upsample_initial_channel\n self.unit_embed_dim = unit_embed_dim\n self.spkr_embed_dim = spkr_embed_dim\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.lang_embed_dim = lang_embed_dim\n\n self.max_new_tokens = max_new_tokens\n\n self.unit_hifi_gan_vocab_size = unit_hifi_gan_vocab_size\n self.t2u_num_langs = t2u_num_langs\n self.t2u_offset_tgt_lang = t2u_offset_tgt_lang\n self.vocoder_offset = vocoder_offset\n\n self.t2u_variance_predictor_hidden_dim = t2u_variance_predictor_hidden_dim\n self.char_vocab_size = char_vocab_size\n self.left_max_position_embeddings = left_max_position_embeddings\n self.right_max_position_embeddings = right_max_position_embeddings\n self.speech_encoder_chunk_size = speech_encoder_chunk_size\n self.speech_encoder_left_chunk_num = speech_encoder_left_chunk_num", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=256000,\n hidden_size=3072,\n intermediate_size=24576,\n num_hidden_layers=28,\n num_attention_heads=16,\n num_key_value_heads=16,\n head_dim=256,\n hidden_activation=\"gelu_pytorch_tanh\",\n max_position_embeddings=8192,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n bos_token_id=2,\n tie_word_embeddings=True,\n rope_theta=10000.0,\n attention_bias=False,\n attention_dropout=0.0,\n query_pre_attn_scalar=224,\n sliding_window=4096,\n final_logit_softcapping=30.0,\n attn_logit_softcapping=50.0,\n cache_implementation=\"hybrid\",\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.head_dim = head_dim\n self.num_key_value_heads = num_key_value_heads\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n self.hidden_activation = hidden_activation\n self.query_pre_attn_scalar = query_pre_attn_scalar\n self.sliding_window = sliding_window\n self.final_logit_softcapping = final_logit_softcapping\n self.attn_logit_softcapping = attn_logit_softcapping\n self.cache_implementation = cache_implementation", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *headers: Union[Column, str],\n title: Optional[TextType] = None,\n caption: Optional[TextType] = None,\n width: Optional[int] = None,\n min_width: Optional[int] = None,\n box: Optional[box.Box] = box.HEAVY_HEAD,\n safe_box: Optional[bool] = None,\n padding: PaddingDimensions = (0, 1),\n collapse_padding: bool = False,\n pad_edge: bool = True,\n expand: bool = False,\n show_header: bool = True,\n show_footer: bool = False,\n show_edge: bool = True,\n show_lines: bool = False,\n leading: int = 0,\n style: StyleType = \"none\",\n row_styles: Optional[Iterable[StyleType]] = None,\n header_style: Optional[StyleType] = \"table.header\",\n footer_style: Optional[StyleType] = \"table.footer\",\n border_style: Optional[StyleType] = None,\n title_style: Optional[StyleType] = None,\n caption_style: Optional[StyleType] = None,\n title_justify: \"JustifyMethod\" = \"center\",\n caption_justify: \"JustifyMethod\" = \"center\",\n highlight: bool = False,\n ) -> None:\n self.columns: List[Column] = []\n self.rows: List[Row] = []\n self.title = title\n self.caption = caption\n self.width = width\n self.min_width = min_width\n self.box = box\n self.safe_box = safe_box\n self._padding = Padding.unpack(padding)\n self.pad_edge = pad_edge\n self._expand = expand\n self.show_header = show_header\n self.show_footer = show_footer\n self.show_edge = show_edge\n self.show_lines = show_lines\n self.leading = leading\n self.collapse_padding = collapse_padding\n self.style = style\n self.header_style = header_style or \"\"\n self.footer_style = footer_style or \"\"\n self.border_style = border_style\n self.title_style = title_style\n self.caption_style = caption_style\n self.title_justify: \"JustifyMethod\" = title_justify\n self.caption_justify: \"JustifyMethod\" = caption_justify\n self.highlight = highlight\n self.row_styles: Sequence[StyleType] = list(row_styles or [])\n append_column = self.columns.append\n for header in headers:\n if isinstance(header, str):\n self.add_column(header=header)\n else:\n header._index = len(self.columns)\n append_column(header)", "smellKey": "S107", "smellId": null, "repo": "shenxianpeng_pip", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_resize: Optional[bool] = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: int = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> BatchFeature:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Dictionary in the format `{\"height\": h, \"width\": w}` specifying the size of the output image after\n resizing.\n resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):\n `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has\n an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use if `do_normalize` is set to `True`.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\", default_to_square=True)\n resample = resample if resample is not None else self.resample\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n size = size if size is not None else self.size\n size_dict = get_size_dict(size)\n\n validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)\n\n if not is_batched(images):\n images = [images]\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n if do_resize:\n images = [\n self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_center_crop:\n images = [\n self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images\n ]\n\n if do_rescale:\n images = [\n self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_normalize:\n images = [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images\n ]\n\n data = {\"pixel_values\": images}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden_layers because of #29297\n seq_length=7,\n is_training=True,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=100,\n pad_token_id=99,\n bos_token_id=99,\n num_codebooks=4,\n conditional_seq_length=4,\n audio_channels=1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.num_codebooks = num_codebooks\n self.conditional_seq_length = conditional_seq_length\n self.encoder_seq_length = conditional_seq_length + seq_length\n self.audio_channels = audio_channels", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@bind_hass\ndef toggle(\n hass: HomeAssistant,\n entity_id: str = ENTITY_MATCH_ALL,\n transition: float | None = None,\n brightness: int | None = None,\n brightness_pct: float | None = None,\n rgb_color: tuple[int, int, int] | None = None,\n xy_color: tuple[float, float] | None = None,\n hs_color: tuple[float, float] | None = None,\n color_temp: int | None = None,\n kelvin: int | None = None,\n profile: str | None = None,\n flash: str | None = None,\n effect: str | None = None,\n color_name: str | None = None,\n) -> None:\n \"\"\"Toggle all or specified light.\"\"\"\n hass.add_job(\n async_toggle,\n hass,\n entity_id,\n transition,\n brightness,\n brightness_pct,\n rgb_color,\n xy_color,\n hs_color,\n color_temp,\n kelvin,\n profile,\n flash,\n effect,\n color_name,\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=2400,\n composer_vocab_size=21,\n d_model=512,\n d_kv=64,\n d_ff=2048,\n num_layers=6,\n num_decoder_layers=None,\n num_heads=8,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n dropout_rate=0.1,\n layer_norm_epsilon=1e-6,\n initializer_factor=1.0,\n feed_forward_proj=\"gated-gelu\", # noqa\n is_encoder_decoder=True,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n dense_act_fn=\"relu\",\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.composer_vocab_size = composer_vocab_size\n self.d_model = d_model\n self.d_kv = d_kv\n self.d_ff = d_ff\n self.num_layers = num_layers\n self.num_decoder_layers = num_decoder_layers if num_decoder_layers is not None else self.num_layers\n self.num_heads = num_heads\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n self.dropout_rate = dropout_rate\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_factor = initializer_factor\n self.feed_forward_proj = feed_forward_proj\n self.use_cache = use_cache\n self.dense_act_fn = dense_act_fn\n self.is_gated_act = self.feed_forward_proj.split(\"-\")[0] == \"gated\"\n self.hidden_size = self.d_model\n self.num_attention_heads = num_heads\n self.num_hidden_layers = num_layers\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(PEGASUS_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(PEGASUS_GENERATION_EXAMPLE)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: Optional[TFBaseModelOutput] = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: bool = False,\n ) -> Union[TFSeq2SeqLMOutput, Tuple[tf.Tensor]]:\n \"\"\"\n labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n\n if labels is not None:\n labels = tf.where(\n labels == self.config.pad_token_id,\n tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),\n labels,\n )\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)\n lm_logits = self.bias_layer(lm_logits)\n masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n return TFSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values, # index 1 of d outputs\n decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs\n decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs\n cross_attentions=outputs.cross_attentions, # index 4 of d outputs\n encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs\n encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out\n encoder_attentions=outputs.encoder_attentions, # 2 of e out\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def query(\n selected_columns: list[str],\n query: str,\n snuba_params: SnubaParams,\n equations: list[str] | None = None,\n orderby: list[str] | None = None,\n offset: int | None = None,\n limit: int = 50,\n referrer: str | None = None,\n auto_fields: bool = False,\n auto_aggregations: bool = False,\n include_equation_fields: bool = False,\n allow_metric_aggregates: bool = False,\n use_aggregate_conditions: bool = False,\n conditions: list[Condition] | None = None,\n functions_acl: list[str] | None = None,\n transform_alias_to_input_format: bool = False,\n sample: float | None = None,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n skip_tag_resolution: bool = False,\n extra_columns: list[Column] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n fallback_to_transactions: bool = False,\n query_source: QuerySource | None = None,\n) -> EventsResponse:\n \"\"\"\n High-level API for doing arbitrary user queries against events.\n\n This function operates on the Discover public event schema and\n virtual fields/aggregate functions for selected columns and\n conditions are supported through this function.\n\n The resulting list will have all internal field names mapped\n back into their public schema names.\n\n selected_columns - List of public aliases to fetch.\n query - Filter query string to create conditions from.\n snuba_params - Filtering parameters with start, end, project_id, environment\n equations - List of equations to calculate for the query\n orderby - The field to order results by.\n offset - The record offset to read.\n limit - The number of records to fetch.\n referrer - A referrer string to help locate the origin of this query.\n auto_fields - Set to true to have project + eventid fields automatically added.\n auto_aggregations - Whether aggregates should be added automatically if they're used\n in conditions, and there's at least one aggregate already.\n include_equation_fields - Whether fields should be added automatically if they're used in\n equations\n allow_metric_aggregates - Ignored here, only used in metric enhanced performance\n use_aggregate_conditions - Set to true if aggregates conditions should be used at all.\n conditions - List of conditions that are passed directly to snuba without\n any additional processing.\n transform_alias_to_input_format - Whether aggregate columns should be returned in the originally\n requested function format.\n sample - The sample rate to run the query with\n fallback_to_transactions - Whether to fallback to the transactions dataset if the query\n fails in metrics enhanced requests. To be removed once the discover dataset is split.\n \"\"\"\n if not selected_columns:\n raise InvalidSearchQuery(\"No columns selected\")\n\n assert dataset in [\n Dataset.Discover,\n Dataset.Transactions,\n ], \"A dataset is required to query discover\"\n\n builder = DiscoverQueryBuilder(\n dataset,\n params={},\n snuba_params=snuba_params,\n query=query,\n selected_columns=selected_columns,\n equations=equations,\n orderby=orderby,\n limit=limit,\n offset=offset,\n sample_rate=sample,\n config=QueryBuilderConfig(\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n functions_acl=functions_acl,\n equation_config={\"auto_add\": include_equation_fields},\n has_metrics=has_metrics,\n transform_alias_to_input_format=transform_alias_to_input_format,\n skip_tag_resolution=skip_tag_resolution,\n ),\n )\n if conditions is not None:\n builder.add_conditions(conditions)\n if extra_columns is not None:\n builder.columns.extend(extra_columns)\n\n result = builder.process_results(\n builder.run_query(referrer=referrer, query_source=query_source)\n )\n result[\"meta\"][\"tips\"] = transform_tips(builder.tips)\n return result", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50267,\n entity_vocab_size=500000,\n hidden_size=768,\n entity_emb_size=256,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n use_entity_aware_attention=True,\n classifier_dropout=None,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n **kwargs,\n ):\n \"\"\"Constructs LukeConfig.\"\"\"\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.entity_vocab_size = entity_vocab_size\n self.hidden_size = hidden_size\n self.entity_emb_size = entity_emb_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.use_entity_aware_attention = use_entity_aware_attention\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def create_and_check_for_entity_classification(\n self,\n config,\n input_ids,\n attention_mask,\n token_type_ids,\n entity_ids,\n entity_attention_mask,\n entity_token_type_ids,\n entity_position_ids,\n sequence_labels,\n token_labels,\n choice_labels,\n entity_labels,\n entity_classification_labels,\n entity_pair_classification_labels,\n entity_span_classification_labels,\n ):\n config.num_labels = self.num_entity_classification_labels\n model = LukeForEntityClassification(config)\n model.to(torch_device)\n model.eval()\n\n result = model(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n entity_ids=entity_ids,\n entity_attention_mask=entity_attention_mask,\n entity_token_type_ids=entity_token_type_ids,\n entity_position_ids=entity_position_ids,\n labels=entity_classification_labels,\n )\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_classification_labels))", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n hidden_size=36,\n intermediate_size=72,\n projection_dim=62,\n output_channels=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n num_channels=3,\n image_size=24,\n patch_size=2,\n hidden_act=\"gelu\",\n layer_norm_eps=1e-06,\n dropout=0.0,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n qkv_bias=True,\n mlp_ratio=4.0,\n use_abs_pos=True,\n use_rel_pos=True,\n rel_pos_zero_init=False,\n window_size=14,\n global_attn_indexes=[2, 5, 8, 11],\n num_pos_feats=16,\n mlp_dim=None,\n batch_size=2,\n ):\n self.parent = parent\n self.image_size = image_size\n self.patch_size = patch_size\n self.output_channels = output_channels\n self.num_channels = num_channels\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.hidden_act = hidden_act\n self.layer_norm_eps = layer_norm_eps\n self.qkv_bias = qkv_bias\n self.mlp_ratio = mlp_ratio\n self.use_abs_pos = use_abs_pos\n self.use_rel_pos = use_rel_pos\n self.rel_pos_zero_init = rel_pos_zero_init\n self.window_size = window_size\n self.global_attn_indexes = global_attn_indexes\n self.num_pos_feats = num_pos_feats\n self.mlp_dim = mlp_dim\n self.batch_size = batch_size\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1\n\n self.prompt_encoder_tester = SamPromptEncoderTester()\n self.mask_decoder_tester = SamMaskDecoderTester()", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_token_type_ids=True,\n use_input_mask=True,\n use_labels=True,\n use_mc_token_ids=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n max_xpath_tag_unit_embeddings=20,\n max_xpath_subs_unit_embeddings=30,\n tag_pad_id=2,\n subs_pad_id=2,\n max_depth=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.scope = scope\n self.max_xpath_tag_unit_embeddings = max_xpath_tag_unit_embeddings\n self.max_xpath_subs_unit_embeddings = max_xpath_subs_unit_embeddings\n self.tag_pad_id = tag_pad_id\n self.subs_pad_id = subs_pad_id\n self.max_depth = max_depth", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=FlaubertForQuestionAnsweringOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n is_impossible: Optional[torch.Tensor] = None,\n cls_index: Optional[torch.Tensor] = None,\n p_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, FlaubertForQuestionAnsweringOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels whether a question has an answer or no answer (SQuAD 2.0)\n cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the classification token to use as input for computing plausibility of the\n answer.\n p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be\n masked. 0.0 mean token is not masked.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import XLMTokenizer, XLMForQuestionAnswering\n >>> import torch\n\n >>> tokenizer = XLMTokenizer.from_pretrained(\"FacebookAI/xlm-mlm-en-2048\")\n >>> model = XLMForQuestionAnswering.from_pretrained(\"FacebookAI/xlm-mlm-en-2048\")\n\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(\n ... 0\n ... ) # Batch size 1\n >>> start_positions = torch.tensor([1])\n >>> end_positions = torch.tensor([3])\n\n >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)\n >>> loss = outputs.loss\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n output = transformer_outputs[0]\n\n outputs = self.qa_outputs(\n output,\n start_positions=start_positions,\n end_positions=end_positions,\n cls_index=cls_index,\n is_impossible=is_impossible,\n p_mask=p_mask,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return outputs + transformer_outputs[1:]\n\n return FlaubertForQuestionAnsweringOutput(\n loss=outputs.loss,\n start_top_log_probs=outputs.start_top_log_probs,\n start_top_index=outputs.start_top_index,\n end_top_log_probs=outputs.end_top_log_probs,\n end_top_index=outputs.end_top_index,\n cls_logits=outputs.cls_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *,\n presentation_exchange_id: Optional[str] = None,\n connection_id: Optional[str] = None,\n thread_id: Optional[str] = None,\n initiator: Optional[str] = None,\n role: Optional[str] = None,\n state: Optional[str] = None,\n presentation_proposal_dict: Union[\n PresentationProposal, Mapping\n ] = None, # aries message: ..._dict for historic compat on all aries msgs\n presentation_request: Union[IndyProofRequest, Mapping] = None, # indy proof req\n presentation_request_dict: Union[\n PresentationRequest, Mapping\n ] = None, # aries message\n presentation: Union[IndyProof, Mapping] = None, # indy proof\n verified: Optional[str] = None,\n verified_msgs: Optional[list] = None,\n auto_present: bool = False,\n auto_verify: bool = False,\n error_msg: Optional[str] = None,\n trace: bool = False, # backward compat: BaseRecord.from_storage()\n auto_remove: bool = False,\n **kwargs,\n ):\n \"\"\"Initialize a new PresentationExchange.\"\"\"\n super().__init__(presentation_exchange_id, state, trace=trace, **kwargs)\n self.connection_id = connection_id\n self.thread_id = thread_id\n self.initiator = initiator\n self.role = role\n self.state = state\n self._presentation_proposal_dict = PresentationProposal.serde(\n presentation_proposal_dict\n )\n self._presentation_request = IndyProofRequest.serde(presentation_request)\n self._presentation_request_dict = PresentationRequest.serde(\n presentation_request_dict\n )\n self._presentation = IndyProof.serde(presentation)\n self.verified = verified\n self.verified_msgs = verified_msgs\n self.auto_present = auto_present\n self.auto_verify = auto_verify\n self.error_msg = error_msg\n self.auto_remove = auto_remove", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def __init__(\n self,\n # time series specific configuration\n num_input_channels: int = 1,\n context_length: int = 32,\n distribution_output: str = \"student_t\",\n loss: str = \"mse\",\n # PatchTST arguments\n patch_length: int = 1,\n patch_stride: int = 1,\n # Transformer architecture configuration\n num_hidden_layers: int = 3,\n d_model: int = 128,\n num_attention_heads: int = 4,\n share_embedding: bool = True,\n channel_attention: bool = False,\n ffn_dim: int = 512,\n norm_type: str = \"batchnorm\",\n norm_eps: float = 1e-05,\n attention_dropout: float = 0.0,\n positional_dropout: float = 0.0,\n path_dropout: float = 0.0,\n ff_dropout: float = 0.0,\n bias: bool = True,\n activation_function: str = \"gelu\",\n pre_norm: bool = True,\n positional_encoding_type: str = \"sincos\",\n use_cls_token: bool = False,\n init_std: float = 0.02,\n share_projection: bool = True,\n scaling: Optional[Union[str, bool]] = \"std\",\n # mask pretraining\n do_mask_input: Optional[bool] = None,\n mask_type: str = \"random\",\n random_mask_ratio: float = 0.5,\n num_forecast_mask_patches: Optional[Union[List[int], int]] = [2],\n channel_consistent_masking: Optional[bool] = False,\n unmasked_channel_indices: Optional[List[int]] = None,\n mask_value: int = 0,\n # head\n pooling_type: str = \"mean\",\n head_dropout: float = 0.0,\n prediction_length: int = 24,\n num_targets: int = 1,\n output_range: Optional[List] = None,\n # distribution head\n num_parallel_samples: int = 100,\n **kwargs,\n ):\n # time series specific configuration\n self.context_length = context_length\n self.num_input_channels = num_input_channels # n_vars\n self.loss = loss\n self.distribution_output = distribution_output\n self.num_parallel_samples = num_parallel_samples\n\n # Transformer architecture configuration\n self.d_model = d_model\n self.num_attention_heads = num_attention_heads\n self.ffn_dim = ffn_dim\n self.num_hidden_layers = num_hidden_layers\n self.attention_dropout = attention_dropout\n self.share_embedding = share_embedding\n self.channel_attention = channel_attention\n self.norm_type = norm_type\n self.norm_eps = norm_eps\n self.positional_dropout = positional_dropout\n self.path_dropout = path_dropout\n self.ff_dropout = ff_dropout\n self.bias = bias\n self.activation_function = activation_function\n self.pre_norm = pre_norm\n self.positional_encoding_type = positional_encoding_type\n self.use_cls_token = use_cls_token\n self.init_std = init_std\n self.scaling = scaling\n\n # PatchTST parameters\n self.patch_length = patch_length\n self.patch_stride = patch_stride\n\n # Mask pretraining\n self.do_mask_input = do_mask_input\n self.mask_type = mask_type\n self.random_mask_ratio = random_mask_ratio # for random masking\n self.num_forecast_mask_patches = num_forecast_mask_patches # for forecast masking\n self.channel_consistent_masking = channel_consistent_masking\n self.unmasked_channel_indices = unmasked_channel_indices\n self.mask_value = mask_value\n\n # general head params\n self.pooling_type = pooling_type\n self.head_dropout = head_dropout\n\n # For prediction head\n self.share_projection = share_projection\n self.prediction_length = prediction_length\n\n # For prediction and regression head\n self.num_parallel_samples = num_parallel_samples\n\n # Regression\n self.num_targets = num_targets\n self.output_range = output_range\n\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n decoder_seq_length=7,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n scope=None,\n decoder_layers=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = decoder_layers", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFRetrievAugLMOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = None,\n doc_scores: np.ndarray | tf.Tensor | None = None,\n context_input_ids: np.ndarray | tf.Tensor | None = None,\n context_attention_mask: np.ndarray | tf.Tensor | None = None,\n use_cache: bool | None = None,\n output_attentions: bool | None = None,\n output_hidden_states: bool | None = None,\n output_retrieved: bool | None = None,\n n_docs: int | None = None,\n return_dict: bool | None = None,\n training: bool = False,\n **kwargs,\n ) -> TFRetrievAugLMOutput:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RagRetriever, TFRagModel\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/rag-token-base\")\n >>> retriever = RagRetriever.from_pretrained(\n ... \"facebook/rag-token-base\", index_name=\"exact\", use_dummy_dataset=True\n ... )\n >>> # initialize with RagRetriever to do everything in one forward call\n >>> model = TFRagModel.from_pretrained(\"facebook/rag-token-base\", retriever=retriever, from_pt=True)\n\n >>> input_dict = tokenizer.prepare_seq2seq_batch(\n ... \"How many people live in Paris?\", \"In Paris, there are 10 million people.\", return_tensors=\"tf\"\n ... )\n >>> input_ids = input_dict[\"input_ids\"]\n >>> outputs = model(input_ids)\n ```\"\"\"\n assert (\n \"decoder_cached_states\" not in kwargs\n ), \"Please use past_key_values to cache intermediate outputs\" # from modeling_tf_bart.py\n\n # aliasing to minimize code changing\n n_docs = n_docs if n_docs is not None else self.config.n_docs\n\n # whether retriever has to be used\n has_to_retrieve = (\n self.retriever is not None\n and (context_input_ids is None or context_attention_mask is None or doc_scores is None)\n and encoder_outputs is None\n )\n\n # encoder_outputs are pre-computed during RAG-token generation\n if encoder_outputs is None:\n if has_to_retrieve:\n question_enc_outputs = self.question_encoder(\n input_ids, attention_mask=attention_mask, return_dict=True, training=training\n )\n # see https://github.com/huggingface/transformers/blob/main/src/transformers/models/dpr/modeling_tf_dpr.py#L91\n question_encoder_last_hidden_state = question_enc_outputs[\n 0\n ] # hidden states of question encoder => pooler_output\n\n retriever_outputs = self.retriever(\n input_ids,\n question_encoder_last_hidden_state.numpy(),\n prefix=self.generator.config.prefix,\n n_docs=n_docs,\n return_tensors=\"tf\",\n )\n context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (\n retriever_outputs[\"context_input_ids\"],\n retriever_outputs[\"context_attention_mask\"],\n retriever_outputs[\"retrieved_doc_embeds\"],\n retriever_outputs[\"doc_ids\"],\n )\n\n context_input_ids = tf.cast(context_input_ids, tf.int32)\n context_attention_mask = tf.cast(context_attention_mask, tf.int32)\n retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)\n retrieved_doc_ids = tf.cast(retrieved_doc_ids, tf.int32)\n\n # compute doc_scores\n doc_scores = tf.squeeze(\n tf.matmul(\n tf.expand_dims(question_encoder_last_hidden_state, axis=1),\n retrieved_doc_embeds,\n transpose_b=True,\n ),\n axis=1,\n )\n\n else:\n assert context_input_ids is not None, (\n \"Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can\"\n \" set a retriever using the `set_retriever(...)` function.\"\n )\n assert context_attention_mask is not None, (\n \"Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you\"\n \" can set a retriever using the `set_retriever(...)` function.\"\n )\n assert doc_scores is not None, (\n \"Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a\"\n \" retriever using the `set_retriever(...)` function.\"\n )\n\n assert (\n doc_scores is not None\n ), \"Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function.\"\n\n assert (doc_scores.shape[1] % n_docs) == 0, (\n f\" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is\"\n f\" {context_input_ids.shape[0]}.\"\n )\n\n # Decoder input without context documents\n if decoder_input_ids is not None:\n decoder_input_ids = tf.repeat(decoder_input_ids, n_docs, axis=0)\n\n if decoder_attention_mask is not None:\n decoder_attention_mask = tf.repeat(decoder_attention_mask, n_docs, axis=0)\n\n gen_outputs = self.generator(\n context_input_ids,\n attention_mask=context_attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n return_dict=True,\n training=training,\n )\n\n if not has_to_retrieve:\n question_encoder_last_hidden_state = None\n question_enc_hidden_states = None\n question_enc_attentions = None\n retrieved_doc_embeds = None\n retrieved_doc_ids = None\n else:\n question_enc_hidden_states = question_enc_outputs.hidden_states\n question_enc_attentions = question_enc_outputs.attentions\n\n if not has_to_retrieve or not output_retrieved:\n # don't output retrieved docs\n context_input_ids = (None,)\n context_attention_mask = None\n retrieved_doc_embeds = None\n retrieved_doc_ids = None\n\n return TFRetrievAugLMOutput(\n logits=gen_outputs.logits,\n doc_scores=doc_scores,\n past_key_values=gen_outputs.past_key_values,\n context_input_ids=context_input_ids,\n context_attention_mask=context_attention_mask,\n retrieved_doc_embeds=retrieved_doc_embeds,\n retrieved_doc_ids=retrieved_doc_ids,\n question_encoder_last_hidden_state=question_encoder_last_hidden_state,\n question_enc_hidden_states=question_enc_hidden_states,\n question_enc_attentions=question_enc_attentions,\n generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,\n generator_enc_hidden_states=gen_outputs.encoder_hidden_states,\n generator_enc_attentions=gen_outputs.encoder_attentions,\n generator_dec_hidden_states=gen_outputs.decoder_hidden_states,\n generator_dec_attentions=gen_outputs.decoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n merges_file,\n errors=\"replace\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n add_prefix_space=True,\n cls_token_box=[0, 0, 0, 0],\n sep_token_box=[0, 0, 0, 0],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n **kwargs,\n ):\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token\n cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n with open(vocab_file, encoding=\"utf-8\") as vocab_handle:\n self.encoder = json.load(vocab_handle)\n self.decoder = {v: k for k, v in self.encoder.items()}\n self.errors = errors # how to handle errors in decoding\n self.byte_encoder = bytes_to_unicode()\n self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}\n with open(merges_file, encoding=\"utf-8\") as merges_handle:\n bpe_merges = merges_handle.read().split(\"\\n\")[1:-1]\n bpe_merges = [tuple(merge.split()) for merge in bpe_merges]\n self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))\n self.cache = {}\n self.add_prefix_space = add_prefix_space\n\n # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions\n self.pat = re.compile(r\"\"\"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\"\"\")\n\n # additional properties\n self.cls_token_box = cls_token_box\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword\n\n super().__init__(\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n cls_token_box=cls_token_box,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "async def resolve_at(\n where: Union[dns.name.Name, str],\n qname: Union[dns.name.Name, str],\n rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,\n rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,\n tcp: bool = False,\n source: Optional[str] = None,\n raise_on_no_answer: bool = True,\n source_port: int = 0,\n lifetime: Optional[float] = None,\n search: Optional[bool] = None,\n backend: Optional[dns.asyncbackend.Backend] = None,\n port: int = 53,\n family: int = socket.AF_UNSPEC,\n resolver: Optional[Resolver] = None,\n) -> dns.resolver.Answer:\n \"\"\"Query nameservers to find the answer to the question.\n\n This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()``\n to make a resolver, and then uses it to resolve the query.\n\n See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution\n parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the\n resolver parameters *where*, *port*, *family*, and *resolver*.\n\n If making more than one query, it is more efficient to call\n ``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries\n instead of calling ``resolve_at()`` multiple times.\n \"\"\"\n res = await make_resolver_at(where, port, family, resolver)\n return await res.resolve(\n qname,\n rdtype,\n rdclass,\n tcp,\n source,\n raise_on_no_answer,\n source_port,\n lifetime,\n search,\n backend,\n )", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids=None,\n inputs_embeds=None,\n attention_mask=None,\n position_ids=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n head_mask=None,\n cross_attn_head_mask=None,\n past_key_values=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n ):\n r\"\"\"\n Args:\n input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you\n provide it.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the\n range `[0, config.max_position_embeddings - 1]`.\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention\n of the decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):\n Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values\n selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up\n decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those\n that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of\n all `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value\n in the config will be used instead.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail. This argument can be used only in eager mode, in graph mode the value in the config\n will be used instead.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used\n in eager mode, in graph mode the value will always be set to True.\n training (`bool`, *optional*, defaults to `False`):\n Whether or not to use the model in training mode (some modules like dropout modules have different\n behaviors between training and evaluation).\n \"\"\"\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = shape_list(input_ids)\n elif inputs_embeds is not None:\n input_shape = shape_list(inputs_embeds)[:-1]\n else:\n raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\n\n past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0\n\n if inputs_embeds is None:\n check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)\n inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale\n\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n if input_shape[-1] > 1:\n combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)\n else:\n combined_attention_mask = _expand_mask(\n tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]\n )\n\n if attention_mask is not None:\n combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])\n\n if encoder_hidden_states is not None and encoder_attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])\n\n # embed positions\n if position_ids is None:\n positions = self.embed_positions(input_shape, past_key_values_length)\n else:\n positions = self.embed_positions(input_shape, position_ids=position_ids)\n\n hidden_states = self.layernorm_embedding(inputs_embeds) + positions\n hidden_states = self.dropout(hidden_states, training=training)\n\n # decoder layers\n all_hidden_states = () if output_hidden_states else None\n all_self_attns = () if output_attentions else None\n all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None\n present_key_values = () if use_cache else None\n\n # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired\n for attn_mask_name, attn_mask in [(\"head_mask\", head_mask), (\"cross_attn_head_mask\", cross_attn_head_mask)]:\n if attn_mask is not None:\n tf.debugging.assert_equal(\n shape_list(attn_mask)[0],\n len(self.layers),\n message=(\n f\"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for\"\n f\" {shape_list(attn_mask)[0]}.\"\n ),\n )\n\n for idx, decoder_layer in enumerate(self.layers):\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n dropout_probability = random.uniform(0, 1)\n\n if training and (dropout_probability < self.layerdrop):\n continue\n\n past_key_value = past_key_values[idx] if past_key_values is not None else None\n\n hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(\n hidden_states,\n attention_mask=combined_attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n layer_head_mask=head_mask[idx] if head_mask is not None else None,\n cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,\n past_key_value=past_key_value,\n )\n\n if use_cache:\n present_key_values += (present_key_value,)\n\n if output_attentions:\n all_self_attns += (layer_self_attn,)\n\n if encoder_hidden_states is not None:\n all_cross_attns += (layer_cross_attn,)\n\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n if not return_dict:\n return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns\n else:\n return TFBaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n past_key_values=present_key_values,\n hidden_states=all_hidden_states,\n attentions=all_self_attns,\n cross_attentions=all_cross_attns,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n backbone_config=None,\n backbone=None,\n use_pretrained_backbone=False,\n use_timm_backbone=False,\n backbone_kwargs=None,\n text_config=None,\n num_queries=900,\n encoder_layers=6,\n encoder_ffn_dim=2048,\n encoder_attention_heads=8,\n decoder_layers=6,\n decoder_ffn_dim=2048,\n decoder_attention_heads=8,\n is_encoder_decoder=True,\n activation_function=\"relu\",\n d_model=256,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n auxiliary_loss=False,\n position_embedding_type=\"sine\",\n num_feature_levels=4,\n encoder_n_points=4,\n decoder_n_points=4,\n two_stage=True,\n class_cost=1.0,\n bbox_cost=5.0,\n giou_cost=2.0,\n bbox_loss_coefficient=5.0,\n giou_loss_coefficient=2.0,\n focal_alpha=0.25,\n disable_custom_kernels=False,\n # other parameters\n max_text_len=256,\n text_enhancer_dropout=0.0,\n fusion_droppath=0.1,\n fusion_dropout=0.0,\n embedding_init_target=True,\n query_dim=4,\n decoder_bbox_embed_share=True,\n two_stage_bbox_embed_share=False,\n positional_embedding_temperature=20,\n init_std=0.02,\n layer_norm_eps=1e-5,\n **kwargs,\n ):\n if backbone_config is None and backbone is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.\")\n backbone_config = CONFIG_MAPPING[\"swin\"](\n window_size=7,\n image_size=224,\n embed_dim=96,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n out_indices=[2, 3, 4],\n )\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.pop(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n if text_config is None:\n text_config = {}\n logger.info(\"text_config is None. Initializing the text config with default values (`BertConfig`).\")\n\n self.backbone_config = backbone_config\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n self.num_queries = num_queries\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.auxiliary_loss = auxiliary_loss\n self.position_embedding_type = position_embedding_type\n # deformable attributes\n self.num_feature_levels = num_feature_levels\n self.encoder_n_points = encoder_n_points\n self.decoder_n_points = decoder_n_points\n self.two_stage = two_stage\n # Hungarian matcher\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n # Loss coefficients\n self.bbox_loss_coefficient = bbox_loss_coefficient\n self.giou_loss_coefficient = giou_loss_coefficient\n self.focal_alpha = focal_alpha\n self.disable_custom_kernels = disable_custom_kernels\n # Text backbone\n if isinstance(text_config, dict):\n text_config[\"model_type\"] = text_config[\"model_type\"] if \"model_type\" in text_config else \"bert\"\n text_config = CONFIG_MAPPING[text_config[\"model_type\"]](**text_config)\n elif text_config is None:\n text_config = CONFIG_MAPPING[\"bert\"]()\n\n self.text_config = text_config\n self.max_text_len = max_text_len\n\n # Text Enhancer\n self.text_enhancer_dropout = text_enhancer_dropout\n # Fusion\n self.fusion_droppath = fusion_droppath\n self.fusion_dropout = fusion_dropout\n # Others\n self.embedding_init_target = embedding_init_target\n self.query_dim = query_dim\n self.decoder_bbox_embed_share = decoder_bbox_embed_share\n self.two_stage_bbox_embed_share = two_stage_bbox_embed_share\n if two_stage_bbox_embed_share and not decoder_bbox_embed_share:\n raise ValueError(\"If two_stage_bbox_embed_share is True, decoder_bbox_embed_share must be True.\")\n self.positional_embedding_temperature = positional_embedding_temperature\n self.init_std = init_std\n self.layer_norm_eps = layer_norm_eps\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32128,\n d_model=512,\n d_kv=64,\n d_ff=2048,\n num_layers=6,\n num_decoder_layers=None,\n num_heads=8,\n local_radius=127,\n global_block_size=16,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n dropout_rate=0.1,\n layer_norm_epsilon=1e-6,\n initializer_factor=1.0,\n feed_forward_proj=\"relu\",\n is_encoder_decoder=True,\n encoder_attention_type=\"local\",\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.d_kv = d_kv\n self.d_ff = d_ff\n self.num_layers = num_layers\n # default = symmetry\n self.num_decoder_layers = num_decoder_layers if num_decoder_layers is not None else self.num_layers\n self.num_heads = num_heads\n self.local_radius = local_radius\n self.global_block_size = global_block_size\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n self.dropout_rate = dropout_rate\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_factor = initializer_factor\n self.feed_forward_proj = feed_forward_proj\n self.encoder_attention_type = encoder_attention_type\n self.use_cache = use_cache\n\n act_info = self.feed_forward_proj.split(\"-\")\n self.dense_act_fn = act_info[-1]\n self.is_gated_act = act_info[0] == \"gated\"\n\n if len(act_info) > 1 and act_info[0] != \"gated\" or len(act_info) > 2:\n raise ValueError(\n f\"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. \"\n \"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. \"\n \"'gated-gelu' or 'relu'\"\n )\n\n # for backwards compatibility\n if feed_forward_proj == \"gated-gelu\":\n self.dense_act_fn = \"gelu_new\"\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(PEGASUS_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFSeq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n **kwargs,\n ) -> Union[TFSeq2SeqModelOutput, Tuple[tf.Tensor]]:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n renderable: \"RenderableType\",\n box: Box = ROUNDED,\n *,\n title: Optional[TextType] = None,\n title_align: AlignMethod = \"center\",\n subtitle: Optional[TextType] = None,\n subtitle_align: AlignMethod = \"center\",\n safe_box: Optional[bool] = None,\n expand: bool = True,\n style: StyleType = \"none\",\n border_style: StyleType = \"none\",\n width: Optional[int] = None,\n height: Optional[int] = None,\n padding: PaddingDimensions = (0, 1),\n highlight: bool = False,\n ) -> None:\n self.renderable = renderable\n self.box = box\n self.title = title\n self.title_align: AlignMethod = title_align\n self.subtitle = subtitle\n self.subtitle_align = subtitle_align\n self.safe_box = safe_box\n self.expand = expand\n self.style = style\n self.border_style = border_style\n self.width = width\n self.height = height\n self.padding = padding\n self.highlight = highlight", "smellKey": "S107", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], Seq2SeqModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n name,\n config_params: Optional[list] = None,\n target_names: Optional[list] = None,\n cmd_target_names: Optional[list] = None,\n tlm_target_names: Optional[list] = None,\n connect_on_startup: bool = True,\n auto_reconnect: bool = True,\n reconnect_delay: float = 5.0,\n disable_disconnect: bool = False,\n options: Optional[list] = None,\n secret_options: Optional[list] = None,\n protocols: Optional[list] = None,\n log_stream=None,\n updated_at: Optional[float] = None,\n plugin: Optional[str] = None,\n needs_dependencies: bool = False,\n secrets: Optional[list] = None,\n cmd: str = None,\n work_dir: str = \"/openc3/lib/openc3/microservices\",\n ports: Optional[list] = None,\n env: Optional[dict] = None,\n container=None,\n prefix=None,\n scope: str = OPENC3_SCOPE,\n ):\n type = self.__class__._get_type()\n if type == \"INTERFACE\":\n super().__init__(\n f\"{scope}__{InterfaceModel.INTERFACES_PRIMARY_KEY}\",\n name=name,\n updated_at=updated_at,\n plugin=plugin,\n scope=scope,\n )\n else:\n super().__init__(\n f\"{scope}__{InterfaceModel.ROUTERS_PRIMARY_KEY}\",\n name=name,\n updated_at=updated_at,\n plugin=plugin,\n scope=scope,\n )\n self.config_params = [] if config_params is None else config_params\n self.target_names = [] if target_names is None else target_names\n self.cmd_target_names = [] if cmd_target_names is None else cmd_target_names\n self.tlm_target_names = [] if tlm_target_names is None else tlm_target_names\n self.connect_on_startup = connect_on_startup\n self.auto_reconnect = auto_reconnect\n self.reconnect_delay = reconnect_delay\n self.disable_disconnect = disable_disconnect\n self.options = [] if options is None else options\n self.secret_options = [] if secret_options is None else secret_options\n self.protocols = [] if protocols is None else protocols\n self.log_stream = log_stream\n self.needs_dependencies = needs_dependencies\n self.cmd = cmd\n if self.cmd is None:\n microservice_name = f\"{self.scope}__{type}__{self.name}\"\n if len(self.config_params) == 0 or Path(config_params[0]).suffix == \".py\":\n work_dir = work_dir.replace(\"openc3/lib\", \"openc3/python\")\n self.cmd = [\n \"python\",\n f\"{type.lower()}_microservice.py\",\n microservice_name,\n ]\n else:\n raise RuntimeError(f\"Unknown file type {config_params[0]}\")\n self.work_dir = work_dir\n self.ports = [] if ports is None else ports\n self.env = {} if env is None else env\n self.container = container\n self.prefix = prefix\n self.secrets = [] if secrets is None else secrets", "smellKey": "S107", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def encode_plus(\n self,\n text: Union[TextInput, PreTokenizedInput, EncodedInput],\n text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n is_split_into_words: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Tokenize and prepare for the model a sequence or a pair of sequences.\n\n <Tip warning={true}>\n\n This method is deprecated, `__call__` should be used instead.\n\n </Tip>\n\n Args:\n text (`str`, `List[str]` or (for non-fast tokenizers) `List[int]`):\n The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the\n `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`\n method).\n text_pair (`str`, `List[str]` or `List[int]`, *optional*):\n Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using\n the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`\n method).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._encode_plus(\n text=text,\n text_pair=text_pair,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n split_special_tokens=kwargs.pop(\"split_special_tokens\", self.split_special_tokens),\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=32,\n patch_size=2,\n num_channels=3,\n embed_dim=16,\n depths=[1, 2, 1],\n num_heads=[2, 2, 4],\n window_size=2,\n mlp_ratio=2.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n use_absolute_embeddings=False,\n patch_norm=True,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n is_training=True,\n scope=None,\n use_labels=True,\n type_sequence_label_size=10,\n encoder_stride=8,\n out_features=[\"stage1\", \"stage2\"],\n out_indices=[1, 2],\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_heads = num_heads\n self.window_size = window_size\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.use_absolute_embeddings = use_absolute_embeddings\n self.patch_norm = patch_norm\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.is_training = is_training\n self.scope = scope\n self.use_labels = use_labels\n self.type_sequence_label_size = type_sequence_label_size\n self.encoder_stride = encoder_stride\n self.out_features = out_features\n self.out_indices = out_indices", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n num_channels=3,\n image_size=32,\n patch_size=16,\n use_labels=True,\n num_labels=3,\n is_training=True,\n hidden_size=4,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=8,\n out_features=[\"stage1\", \"stage2\"],\n apply_layernorm=False,\n reshape_hidden_states=False,\n neck_hidden_sizes=[2, 2],\n fusion_hidden_size=6,\n bottleneck_features=6,\n num_out_features=[6, 6, 6, 6],\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.patch_size = patch_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.out_features = out_features\n self.apply_layernorm = apply_layernorm\n self.reshape_hidden_states = reshape_hidden_states\n self.use_labels = use_labels\n self.num_labels = num_labels\n self.is_training = is_training\n self.neck_hidden_sizes = neck_hidden_sizes\n self.fusion_hidden_size = fusion_hidden_size\n self.bottleneck_features = bottleneck_features\n self.num_out_features = num_out_features\n # ZoeDepth's sequence length\n self.seq_length = (self.image_size // self.patch_size) ** 2 + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set\n `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`\n are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = transformer_outputs[0]\n\n # Set device for model parallelism\n if self.model_parallel:\n torch.cuda.set_device(self.transformer.first_device)\n hidden_states = hidden_states.to(self.lm_head.weight.device)\n\n lm_logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(lm_logits.device)\n # Shift so that tokens < n predict n\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=lm_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n cross_attentions=transformer_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=None,\n hidden_act=\"silu\",\n max_position_embeddings=2048,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n rope_theta=10000.0,\n rope_scaling=None,\n attention_bias=False,\n attention_dropout=0.0,\n embedding_multiplier=1.0,\n logits_scaling=1.0,\n residual_multiplier=1.0,\n attention_multiplier=1.0,\n num_local_experts=8,\n num_experts_per_tok=2,\n output_router_logits=False,\n router_aux_loss_coef=0.001,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n\n # for backward compatibility\n if num_key_value_heads is None:\n num_key_value_heads = num_attention_heads\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.rope_scaling = rope_scaling\n\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n\n self.embedding_multiplier = embedding_multiplier\n self.logits_scaling = logits_scaling\n self.residual_multiplier = residual_multiplier\n self.attention_multiplier = attention_multiplier\n\n self.num_local_experts = num_local_experts\n self.num_experts_per_tok = num_experts_per_tok\n self.output_router_logits = output_router_logits\n self.router_aux_loss_coef = router_aux_loss_coef\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )\n\n rope_config_validation(self)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=QuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, QuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = transformer_outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + transformer_outputs[1:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@classmethod\n def from_exception(\n cls,\n exc_type: Type[Any],\n exc_value: BaseException,\n traceback: Optional[TracebackType],\n *,\n width: Optional[int] = 100,\n extra_lines: int = 3,\n theme: Optional[str] = None,\n word_wrap: bool = False,\n show_locals: bool = False,\n locals_max_length: int = LOCALS_MAX_LENGTH,\n locals_max_string: int = LOCALS_MAX_STRING,\n locals_hide_dunder: bool = True,\n locals_hide_sunder: bool = False,\n indent_guides: bool = True,\n suppress: Iterable[Union[str, ModuleType]] = (),\n max_frames: int = 100,\n ) -> \"Traceback\":\n \"\"\"Create a traceback from exception info\n\n Args:\n exc_type (Type[BaseException]): Exception type.\n exc_value (BaseException): Exception value.\n traceback (TracebackType): Python Traceback object.\n width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.\n extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n theme (str, optional): Override pygments theme used in traceback.\n word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n show_locals (bool, optional): Enable display of local variables. Defaults to False.\n indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to 10.\n locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n\n Returns:\n Traceback: A Traceback instance that may be printed.\n \"\"\"\n rich_traceback = cls.extract(\n exc_type,\n exc_value,\n traceback,\n show_locals=show_locals,\n locals_max_length=locals_max_length,\n locals_max_string=locals_max_string,\n locals_hide_dunder=locals_hide_dunder,\n locals_hide_sunder=locals_hide_sunder,\n )\n\n return cls(\n rich_traceback,\n width=width,\n extra_lines=extra_lines,\n theme=theme,\n word_wrap=word_wrap,\n show_locals=show_locals,\n indent_guides=indent_guides,\n locals_max_length=locals_max_length,\n locals_max_string=locals_max_string,\n locals_hide_dunder=locals_hide_dunder,\n locals_hide_sunder=locals_hide_sunder,\n suppress=suppress,\n max_frames=max_frames,\n )", "smellKey": "S107", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=RetrievAugLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n doc_scores: Optional[torch.FloatTensor] = None,\n context_input_ids: Optional[torch.LongTensor] = None,\n context_attention_mask: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_retrieved: Optional[bool] = None,\n n_docs: Optional[int] = None,\n ) -> Union[Tuple[torch.Tensor], RetrievAugLMOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RagRetriever, RagModel\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/rag-token-base\")\n >>> retriever = RagRetriever.from_pretrained(\n ... \"facebook/rag-token-base\", index_name=\"exact\", use_dummy_dataset=True\n ... )\n >>> # initialize with RagRetriever to do everything in one forward call\n >>> model = RagModel.from_pretrained(\"facebook/rag-token-base\", retriever=retriever)\n\n >>> inputs = tokenizer(\"How many people live in Paris?\", return_tensors=\"pt\")\n >>> outputs = model(input_ids=inputs[\"input_ids\"])\n ```\"\"\"\n n_docs = n_docs if n_docs is not None else self.config.n_docs\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n output_retrieved = output_retrieved if output_retrieved is not None else self.config.output_retrieved\n\n # whether retriever has to be used\n has_to_retrieve = (\n self.retriever is not None\n and (context_input_ids is None or context_attention_mask is None or doc_scores is None)\n and encoder_outputs is None\n )\n # encoder_outputs are pre-computed during RAG-token generation\n if encoder_outputs is None:\n if has_to_retrieve:\n question_enc_outputs = self.question_encoder(\n input_ids, attention_mask=attention_mask, return_dict=True\n )\n question_encoder_last_hidden_state = question_enc_outputs[0] # hidden states of question encoder\n\n retriever_outputs = self.retriever(\n input_ids,\n question_encoder_last_hidden_state.cpu().detach().to(torch.float32).numpy(),\n prefix=self.generator.config.prefix,\n n_docs=n_docs,\n return_tensors=\"pt\",\n )\n if self.context_encoder_training:\n (\n context_input_ids,\n context_attention_mask,\n retrieved_doc_embeds,\n retrived_doc_input_ids,\n retrived_doc_attention_mask,\n retrieved_doc_ids,\n ) = (\n retriever_outputs[\"context_input_ids\"],\n retriever_outputs[\"context_attention_mask\"],\n retriever_outputs[\"retrieved_doc_embeds\"],\n retriever_outputs[\"tokenized_doc_ids\"],\n retriever_outputs[\"tokenized_doc_attention_mask\"],\n retriever_outputs[\"doc_ids\"],\n )\n\n context_input_ids = context_input_ids.to(input_ids)\n context_attention_mask = context_attention_mask.to(input_ids)\n\n retrived_doc_input_ids = retrived_doc_input_ids.to(input_ids)\n retrived_doc_attention_mask = retrived_doc_attention_mask.to(input_ids)\n retrieved_doc_embeds = self.ctx_encoder(\n retrived_doc_input_ids, attention_mask=retrived_doc_attention_mask, return_dict=True\n ).pooler_output\n retrieved_doc_embeds = retrieved_doc_embeds.view(\n -1, n_docs, question_encoder_last_hidden_state.shape[1]\n ) # reshaping\n\n # compute doc_scores involving ctx_encoder\n doc_scores = torch.bmm(\n question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)\n ).squeeze(1)\n\n else:\n context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (\n retriever_outputs[\"context_input_ids\"],\n retriever_outputs[\"context_attention_mask\"],\n retriever_outputs[\"retrieved_doc_embeds\"],\n retriever_outputs[\"doc_ids\"],\n )\n\n # set to correct device\n retrieved_doc_embeds = retrieved_doc_embeds.to(question_encoder_last_hidden_state)\n context_input_ids = context_input_ids.to(input_ids)\n context_attention_mask = context_attention_mask.to(input_ids)\n\n # compute doc_scores\n doc_scores = torch.bmm(\n question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)\n ).squeeze(1)\n else:\n assert context_input_ids is not None, (\n \"Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can\"\n \" set a retriever using the `set_retriever(...)` function.\"\n )\n assert context_attention_mask is not None, (\n \"Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you\"\n \" can set a retriever using the `set_retriever(...)` function.\"\n )\n assert doc_scores is not None, (\n \"Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a\"\n \" retriever using the `set_retriever(...)` function.\"\n )\n\n assert (\n doc_scores is not None\n ), \"Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function.\"\n\n assert (doc_scores.shape[1] % n_docs) == 0, (\n f\" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is\"\n f\" {context_input_ids.shape[0]}.\"\n )\n\n # Decoder input without context documents\n if decoder_input_ids is not None:\n decoder_input_ids = decoder_input_ids.repeat_interleave(n_docs, dim=0)\n\n if decoder_attention_mask is not None:\n decoder_attention_mask = decoder_attention_mask.repeat_interleave(n_docs, dim=0)\n\n gen_outputs = self.generator(\n input_ids=context_input_ids,\n attention_mask=context_attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n return_dict=True,\n )\n\n if not has_to_retrieve:\n question_encoder_last_hidden_state = None\n question_enc_hidden_states = None\n question_enc_attentions = None\n retrieved_doc_embeds = None\n retrieved_doc_ids = None\n else:\n question_enc_hidden_states = question_enc_outputs.hidden_states\n question_enc_attentions = question_enc_outputs.attentions\n\n if not has_to_retrieve or not output_retrieved:\n # don't output retrieved docs\n context_input_ids = (None,)\n context_attention_mask = None\n retrieved_doc_embeds = None\n retrieved_doc_ids = None\n\n return RetrievAugLMOutput(\n logits=gen_outputs.logits,\n doc_scores=doc_scores,\n past_key_values=gen_outputs.past_key_values,\n context_input_ids=context_input_ids,\n context_attention_mask=context_attention_mask,\n retrieved_doc_embeds=retrieved_doc_embeds,\n retrieved_doc_ids=retrieved_doc_ids,\n question_encoder_last_hidden_state=question_encoder_last_hidden_state,\n question_enc_hidden_states=question_enc_hidden_states,\n question_enc_attentions=question_enc_attentions,\n generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,\n generator_enc_hidden_states=gen_outputs.encoder_hidden_states,\n generator_enc_attentions=gen_outputs.encoder_attentions,\n generator_dec_hidden_states=gen_outputs.decoder_hidden_states,\n generator_dec_attentions=gen_outputs.decoder_attentions,\n generator_cross_attentions=gen_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"relu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n num_experts=4,\n encoder_sparse_step=2,\n decoder_sparse_step=1,\n expert_capacity=100,\n router_jitter_noise=0.0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.encoder_sparse_step = encoder_sparse_step\n self.decoder_sparse_step = decoder_sparse_step\n self.expert_capacity = expert_capacity\n self.router_jitter_noise = router_jitter_noise\n self.num_experts = num_experts", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=_EXPECTED_OUTPUT_SHAPE,\n )\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqModelOutput]:\n # different to other models, Bart automatically creates decoder_input_ids from\n # input_ids if no decoder_input_ids are provided\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n if input_ids is None:\n raise ValueError(\n \"If no `decoder_input_ids` or `decoder_inputs_embeds` are \"\n \"passed, `input_ids` cannot be `None`. Please pass either \"\n \"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.\"\n )\n\n decoder_input_ids = shift_tokens_right(\n input_ids, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=5,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=80,\n do_resize=True,\n size=None,\n do_center_crop=True,\n crop_size=None,\n do_normalize=True,\n image_mean=OPENAI_CLIP_MEAN,\n image_std=OPENAI_CLIP_STD,\n do_convert_rgb=True,\n ):\n size = size if size is not None else {\"shortest_edge\": 20}\n crop_size = crop_size if crop_size is not None else {\"height\": 18, \"width\": 18}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_center_crop = do_center_crop\n self.crop_size = crop_size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(M4T_MODEL_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n input_features: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n **kwargs,\n ) -> Union[Seq2SeqLMOutput, Tuple[torch.FloatTensor]]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n if input_ids is None and input_features is None and inputs_embeds is None and encoder_outputs is None:\n raise ValueError(\n \"`input_ids`,`input_features`, `inputs_embeds` and `encoder_outputs` are all empty. Make sure at least one of them is not.\"\n )\n elif input_features is not None:\n if input_ids is not None:\n logger.warning(\n \"`input_ids` is not `None` but `input_features` has been given.\"\n \"`input_features` will be used in priority through the `speech_encoder`. \"\n \"Make sure that `input_features` and `input_ids` are mutually exclusive.\"\n )\n\n if inputs_embeds is not None:\n logger.warning(\n \"`inputs_embeds` is not `None` but `input_features` has been given.\"\n \"`input_features` will be used in priority through `speech_encoder`. \"\n \"`inputs_embeds` will be ignored.\"\n )\n\n # if encoder_outputs is not None, it's probably used within a .generate method so no need to warn\n logger.warning(\n \"This calls the same method `forward` as `SeamlessM4TForTextToText` and `SeamlessM4TForSpeechToText`\"\n \"depending on the input modality. If you want to generate speech, use the `generate` method.\"\n )\n\n self.set_modality(\"speech\")\n\n encoder_outputs = self.speech_encoder(\n input_features=input_features,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n elif input_ids is not None or inputs_embeds is not None:\n # if encoder_outputs is not None, it's probably used within a .generate method so no need to warn\n logger.warning(\n \"This calls the same method `forward` as `SeamlessM4TForTextToText` and `SeamlessM4TForSpeechToText`\"\n \"depending on the input modality. If you want to generate speech, use the `generate` method.\"\n )\n self.set_modality(\"text\")\n encoder_outputs = self.text_encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n encoder_attention_mask = attention_mask\n # input modality = speech so new attention mask\n if self.current_modality == \"speech\" and attention_mask is not None:\n sub_sampled_lengths = self._compute_sub_sample_lengths_from_attention_mask(attention_mask).to(\n encoder_outputs[0].device\n )\n encoder_attention_mask = _compute_new_attention_mask(\n hidden_states=encoder_outputs[0], seq_lens=sub_sampled_lengths\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.text_decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n lm_logits = self.lm_head(decoder_outputs[0])\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n labels = labels.to(lm_logits.device)\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n outputs = decoder_outputs + encoder_outputs\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def analyze_member_access(\n name: str,\n typ: Type,\n context: Context,\n *,\n is_lvalue: bool,\n is_super: bool,\n is_operator: bool,\n msg: MessageBuilder,\n original_type: Type,\n chk: mypy.checker.TypeChecker,\n override_info: TypeInfo | None = None,\n in_literal_context: bool = False,\n self_type: Type | None = None,\n module_symbol_table: SymbolTable | None = None,\n no_deferral: bool = False,\n is_self: bool = False,\n) -> Type:\n \"\"\"Return the type of attribute 'name' of 'typ'.\n\n The actual implementation is in '_analyze_member_access' and this docstring\n also applies to it.\n\n This is a general operation that supports various different variations:\n\n 1. lvalue or non-lvalue access (setter or getter access)\n 2. supertype access when using super() (is_super == True and\n 'override_info' should refer to the supertype)\n\n 'original_type' is the most precise inferred or declared type of the base object\n that we have available. When looking for an attribute of 'typ', we may perform\n recursive calls targeting the fallback type, and 'typ' may become some supertype\n of 'original_type'. 'original_type' is always preserved as the 'typ' type used in\n the initial, non-recursive call. The 'self_type' is a component of 'original_type'\n to which generic self should be bound (a narrower type that has a fallback to instance).\n Currently this is used only for union types.\n\n 'module_symbol_table' is passed to this function if 'typ' is actually a module\n and we want to keep track of the available attributes of the module (since they\n are not available via the type object directly)\n \"\"\"\n mx = MemberContext(\n is_lvalue=is_lvalue,\n is_super=is_super,\n is_operator=is_operator,\n original_type=original_type,\n context=context,\n msg=msg,\n chk=chk,\n self_type=self_type,\n module_symbol_table=module_symbol_table,\n no_deferral=no_deferral,\n is_self=is_self,\n )\n result = _analyze_member_access(name, typ, mx, override_info)\n possible_literal = get_proper_type(result)\n if (\n in_literal_context\n and isinstance(possible_literal, Instance)\n and possible_literal.last_known_value is not None\n ):\n return possible_literal.last_known_value\n else:\n return result", "smellKey": "S107", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFIdeficsCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n past_key_values: Optional[List[tf.Tensor]] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n pixel_values: Optional[tf.Tensor] = None,\n image_encoder_embeddings: Optional[tf.Tensor] = None,\n perceiver_embeddings: Optional[tf.Tensor] = None,\n image_attention_mask: Optional[tf.Tensor] = None,\n labels: Optional[tf.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n interpolate_pos_encoding: Optional[bool] = False,\n return_dict: Optional[bool] = None,\n training=False,\n ) -> Union[TFIdeficsCausalLMOutputWithPast, Tuple[tf.Tensor]]:\n r\"\"\"\n Args:\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >> from transformers import AutoTokenizer, TFIdeficsForVisionText2Text\n\n >> model = TFIdeficsForVisionText2Text.from_pretrained(\"HuggingFaceM4/idefics-9b\")\n >> tokenizer = AutoTokenizer.from_pretrained(\"HuggingFaceM4/idefics-9b\")\n\n >> prompt = \"Hey, are you consciours? Can you talk to me?\"\n >> inputs = tokenizer(prompt, return_tensors=\"tf\")\n\n >> # Generate\n >> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you consciours? Can you talk to me?\\nI'm not consciours, but I can talk to you.\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n pixel_values=pixel_values,\n image_encoder_embeddings=image_encoder_embeddings,\n perceiver_embeddings=perceiver_embeddings,\n image_attention_mask=image_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n interpolate_pos_encoding=interpolate_pos_encoding,\n return_dict=return_dict,\n training=training,\n )\n\n hidden_states = outputs[0]\n logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n shift_attention_mask = attention_mask[..., 1:]\n shift_logits = logits[..., :-1, :][shift_attention_mask != 0]\n shift_labels = labels[..., 1:][shift_attention_mask != 0]\n else:\n shift_logits = logits[..., :-1, :]\n shift_labels = labels[..., 1:]\n # Flatten the tokens\n loss = self.hf_compute_loss(\n labels=tf.reshape(shift_labels, [-1]), logits=tf.reshape(shift_logits, [-1, shift_logits.shape[-1]])\n )\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return TFIdeficsCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=outputs.image_hidden_states,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def top_events_timeseries(\n timeseries_columns: list[str],\n selected_columns: list[str],\n user_query: str,\n snuba_params: SnubaParams,\n orderby: list[str],\n rollup: int,\n limit: int,\n referrer: str,\n organization: sentry.models.Organization,\n equations: list[str] | None = None,\n top_events: EventsResponse | None = None,\n allow_empty: bool = True,\n zerofill_results: bool = True,\n include_other: bool = False,\n functions_acl: list[str] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n):\n \"\"\"\n High-level API for doing arbitrary user timeseries queries for a limited number of top events\n\n Returns a dictionary of SnubaTSResult objects that have been zerofilled in\n case of gaps. Each value of the dictionary should match the result of a timeseries query\n\n timeseries_columns (Sequence[str]) List of public aliases to fetch for the timeseries query,\n usually matches the y-axis of the graph\n selected_columns (Sequence[str]) List of public aliases to fetch for the events query,\n this is to determine what the top events are\n user_query (str) Filter query string to create conditions from. needs to be user_query\n to not conflict with the function query\n params (Dict[str, str]) Filtering parameters with start, end, project_id, environment,\n orderby (Sequence[str]) The fields to order results by.\n rollup (int) The bucket width in seconds\n limit (int) The number of events to get timeseries for\n organization (Organization) Used to map group ids to short ids\n referrer (str|None) A referrer string to help locate the origin of this query.\n top_events (dict|None) A dictionary with a 'data' key containing a list of dictionaries that\n represent the top events matching the query. Useful when you have found\n the top events earlier and want to save a query.\n \"\"\"\n\n if top_events is None:\n top_events = query(\n selected_columns,\n query=user_query,\n snuba_params=snuba_params,\n equations=equations,\n orderby=orderby,\n limit=limit,\n referrer=referrer,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n include_equation_fields=True,\n skip_tag_resolution=True,\n )\n\n top_events_builder = TopProfileFunctionsMetricsQueryBuilder(\n Dataset.PerformanceMetrics,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=False,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n skip_tag_resolution=True,\n ),\n )\n if len(top_events[\"data\"]) == limit and include_other:\n other_events_builder = TopProfileFunctionsMetricsQueryBuilder(\n Dataset.PerformanceMetrics,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=True,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n )\n\n # TODO: use bulk_snuba_queries\n other_result = other_events_builder.run_query(referrer)\n result = top_events_builder.run_query(referrer)\n else:\n result = top_events_builder.run_query(referrer)\n other_result = {\"data\": []}\n if (\n not allow_empty\n and not len(result.get(\"data\", []))\n and not len(other_result.get(\"data\", []))\n ):\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, [\"time\"]\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n\n result = top_events_builder.process_results(result)\n\n translated_groupby = top_events_builder.translated_groupby\n\n results = (\n {discover.OTHER_KEY: {\"order\": limit, \"data\": other_result[\"data\"]}}\n if len(other_result.get(\"data\", []))\n else {}\n )\n # Using the top events add the order to the results\n for index, item in enumerate(top_events[\"data\"]):\n result_key = discover.create_result_key(item, translated_groupby, {})\n results[result_key] = {\"order\": index, \"data\": []}\n for row in result[\"data\"]:\n result_key = discover.create_result_key(row, translated_groupby, {})\n if result_key in results:\n results[result_key][\"data\"].append(row)\n else:\n logger.warning(\n \"profile_functions_metrics.top-events.timeseries.key-mismatch\",\n extra={\"result_key\": result_key, \"top_event_keys\": list(results.keys())},\n )\n snuba_ts_result: dict[str, SnubaTSResult] = {}\n for key, item in results.items():\n snuba_ts_result[key] = SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n item[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else item[\"data\"]\n ),\n \"order\": item[\"order\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n\n return snuba_ts_result", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=128112,\n max_position_embeddings=1024,\n encoder_layers=12,\n encoder_ffn_dim=4096,\n encoder_attention_heads=16,\n decoder_layers=12,\n decoder_ffn_dim=4096,\n decoder_attention_heads=16,\n encoder_layerdrop=0.05,\n decoder_layerdrop=0.05,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"relu\",\n d_model=1024,\n dropout=0.1,\n attention_dropout=0.1,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=2,\n scale_embedding=True,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_heads,\n embed_dim,\n kernel_size,\n padding_q,\n padding_kv,\n stride_q,\n stride_kv,\n qkv_projection_method,\n qkv_bias,\n attention_drop_rate,\n drop_rate,\n mlp_ratio,\n drop_path_rate,\n with_cls_token=True,\n ):\n super().__init__()\n self.attention = CvtAttention(\n num_heads,\n embed_dim,\n kernel_size,\n padding_q,\n padding_kv,\n stride_q,\n stride_kv,\n qkv_projection_method,\n qkv_bias,\n attention_drop_rate,\n drop_rate,\n with_cls_token,\n )\n\n self.intermediate = CvtIntermediate(embed_dim, mlp_ratio)\n self.output = CvtOutput(embed_dim, mlp_ratio, drop_rate)\n self.drop_path = CvtDropPath(drop_prob=drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()\n self.layernorm_before = nn.LayerNorm(embed_dim)\n self.layernorm_after = nn.LayerNorm(embed_dim)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n *,\n cron_pattern,\n delta_values,\n meter_offset,\n meter_type,\n name,\n net_consumption,\n parent_meter,\n periodically_resetting,\n source_entity,\n tariff_entity,\n tariff,\n unique_id,\n sensor_always_available,\n suggested_entity_id=None,\n device_info=None,\n ):\n \"\"\"Initialize the Utility Meter sensor.\"\"\"\n self._attr_unique_id = unique_id\n self._attr_device_info = device_info\n self.entity_id = suggested_entity_id\n self._parent_meter = parent_meter\n self._sensor_source_id = source_entity\n self._state = None\n self._last_period = Decimal(0)\n self._last_reset = dt_util.utcnow()\n self._last_valid_state = None\n self._collecting = None\n self._name = name\n self._input_device_class = None\n self._unit_of_measurement = None\n self._period = meter_type\n if meter_type is not None:\n # For backwards compatibility reasons we convert the period and offset into a cron pattern\n self._cron_pattern = PERIOD2CRON[meter_type].format(\n minute=meter_offset.seconds % 3600 // 60,\n hour=meter_offset.seconds // 3600,\n day=meter_offset.days + 1,\n )\n _LOGGER.debug(\"CRON pattern: %s\", self._cron_pattern)\n else:\n self._cron_pattern = cron_pattern\n self._sensor_always_available = sensor_always_available\n self._sensor_delta_values = delta_values\n self._sensor_net_consumption = net_consumption\n self._sensor_periodically_resetting = periodically_resetting\n self._tariff = tariff\n self._tariff_entity = tariff_entity\n self._next_reset = None", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n tie_word_embeddings=True,\n hidden_size=3712,\n attention_hidden_size=None,\n intermediate_size=14848,\n num_hidden_layers=76,\n num_attention_heads=16,\n attention_head_dim=None,\n num_key_value_heads=16,\n n_mamba_heads=2,\n hidden_act=\"gelu\",\n hidden_mamba_act=\"silu\",\n initializer_range=0.02,\n rms_norm_eps=1e-5,\n use_cache=True,\n num_logits_to_keep=1,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n max_position_embeddings=4096,\n attention_dropout=0.0,\n attn_layer_period=6,\n attn_layer_offset=4,\n use_mamba_kernels=True,\n mamba_d_state=16,\n mamba_d_conv=4,\n mamba_expand=2,\n mamba_dt_rank=\"auto\",\n time_step_min=0.001,\n time_step_max=0.1,\n time_step_floor=1e-4,\n mamba_conv_bias=True,\n mamba_proj_bias=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.tie_word_embeddings = tie_word_embeddings\n self.hidden_size = hidden_size\n if attention_hidden_size is None:\n self.attention_hidden_size = 2 * hidden_size\n else:\n self.attention_hidden_size = attention_hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n if attention_head_dim is None:\n self.attention_head_dim = 2 * self.hidden_size // self.num_attention_heads\n else:\n self.attention_head_dim = attention_head_dim\n self.max_position_embeddings = max_position_embeddings\n self.attention_dropout = attention_dropout\n\n self.num_key_value_heads = num_key_value_heads\n self.n_mamba_heads = n_mamba_heads\n self.hidden_act = hidden_act\n self.hidden_mamba_act = hidden_mamba_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n\n self.use_cache = use_cache\n self.num_logits_to_keep = num_logits_to_keep\n\n self.attn_layer_period = attn_layer_period\n self.attn_layer_offset = attn_layer_offset\n\n self.use_mamba_kernels = use_mamba_kernels\n self.mamba_d_state = mamba_d_state\n self.mamba_d_conv = mamba_d_conv\n self.mamba_expand = mamba_expand\n self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if mamba_dt_rank == \"auto\" else mamba_dt_rank\n self.time_step_min = time_step_min\n self.time_step_max = time_step_max\n self.time_step_floor = time_step_floor\n self.mamba_conv_bias = mamba_conv_bias\n self.mamba_proj_bias = mamba_proj_bias\n\n self.layers_block_type = self._layers_block_type(num_hidden_layers, attn_layer_period, attn_layer_offset)\n\n assert (\n self.mamba_expand * self.hidden_size\n ) % self.n_mamba_heads == 0, \"`intermediate_size` should be divisible by `n_mamba_heads`.\"\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@callback\n def _async_update_entity(\n self,\n entity_id: str,\n *,\n aliases: set[str] | UndefinedType = UNDEFINED,\n area_id: str | None | UndefinedType = UNDEFINED,\n categories: dict[str, str] | UndefinedType = UNDEFINED,\n capabilities: Mapping[str, Any] | None | UndefinedType = UNDEFINED,\n config_entry_id: str | None | UndefinedType = UNDEFINED,\n device_class: str | None | UndefinedType = UNDEFINED,\n device_id: str | None | UndefinedType = UNDEFINED,\n disabled_by: RegistryEntryDisabler | None | UndefinedType = UNDEFINED,\n entity_category: EntityCategory | None | UndefinedType = UNDEFINED,\n hidden_by: RegistryEntryHider | None | UndefinedType = UNDEFINED,\n icon: str | None | UndefinedType = UNDEFINED,\n has_entity_name: bool | UndefinedType = UNDEFINED,\n labels: set[str] | UndefinedType = UNDEFINED,\n name: str | None | UndefinedType = UNDEFINED,\n new_entity_id: str | UndefinedType = UNDEFINED,\n new_unique_id: str | UndefinedType = UNDEFINED,\n options: EntityOptionsType | UndefinedType = UNDEFINED,\n original_device_class: str | None | UndefinedType = UNDEFINED,\n original_icon: str | None | UndefinedType = UNDEFINED,\n original_name: str | None | UndefinedType = UNDEFINED,\n platform: str | None | UndefinedType = UNDEFINED,\n supported_features: int | UndefinedType = UNDEFINED,\n translation_key: str | None | UndefinedType = UNDEFINED,\n unit_of_measurement: str | None | UndefinedType = UNDEFINED,\n ) -> RegistryEntry:\n \"\"\"Private facing update properties method.\"\"\"\n old = self.entities[entity_id]\n\n new_values: dict[str, Any] = {} # Dict with new key/value pairs\n old_values: dict[str, Any] = {} # Dict with old key/value pairs\n\n for attr_name, value in (\n (\"aliases\", aliases),\n (\"area_id\", area_id),\n (\"categories\", categories),\n (\"capabilities\", capabilities),\n (\"config_entry_id\", config_entry_id),\n (\"device_class\", device_class),\n (\"device_id\", device_id),\n (\"disabled_by\", disabled_by),\n (\"entity_category\", entity_category),\n (\"hidden_by\", hidden_by),\n (\"icon\", icon),\n (\"has_entity_name\", has_entity_name),\n (\"labels\", labels),\n (\"name\", name),\n (\"options\", options),\n (\"original_device_class\", original_device_class),\n (\"original_icon\", original_icon),\n (\"original_name\", original_name),\n (\"platform\", platform),\n (\"supported_features\", supported_features),\n (\"translation_key\", translation_key),\n (\"unit_of_measurement\", unit_of_measurement),\n ):\n if value is not UNDEFINED and value != getattr(old, attr_name):\n new_values[attr_name] = value\n old_values[attr_name] = getattr(old, attr_name)\n\n # Only validate if data has changed\n if new_values or new_unique_id is not UNDEFINED:\n _validate_item(\n self.hass,\n old.domain,\n old.platform,\n disabled_by=disabled_by,\n entity_category=entity_category,\n hidden_by=hidden_by,\n unique_id=new_unique_id,\n )\n\n if new_entity_id is not UNDEFINED and new_entity_id != old.entity_id:\n if not self._entity_id_available(new_entity_id, None):\n raise ValueError(\"Entity with this ID is already registered\")\n\n if not valid_entity_id(new_entity_id):\n raise ValueError(\"Invalid entity ID\")\n\n if split_entity_id(new_entity_id)[0] != split_entity_id(entity_id)[0]:\n raise ValueError(\"New entity ID should be same domain\")\n\n self.entities.pop(entity_id)\n entity_id = new_values[\"entity_id\"] = new_entity_id\n old_values[\"entity_id\"] = old.entity_id\n\n if new_unique_id is not UNDEFINED:\n conflict_entity_id = self.async_get_entity_id(\n old.domain, old.platform, new_unique_id\n )\n if conflict_entity_id:\n raise ValueError(\n f\"Unique id '{new_unique_id}' is already in use by \"\n f\"'{conflict_entity_id}'\"\n )\n new_values[\"unique_id\"] = new_unique_id\n old_values[\"unique_id\"] = old.unique_id\n new_values[\"previous_unique_id\"] = old.unique_id\n\n if not new_values:\n return old\n\n new_values[\"modified_at\"] = utcnow()\n\n self.hass.verify_event_loop_thread(\"entity_registry.async_update_entity\")\n\n new = self.entities[entity_id] = attr.evolve(old, **new_values)\n\n self.async_schedule_save()\n\n data: _EventEntityRegistryUpdatedData_Update = {\n \"action\": \"update\",\n \"entity_id\": entity_id,\n \"changes\": old_values,\n }\n\n if old.entity_id != entity_id:\n data[\"old_entity_id\"] = old.entity_id\n\n self.hass.bus.async_fire_internal(EVENT_ENTITY_REGISTRY_UPDATED, data)\n\n return new", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: int = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_convert_rgb: bool = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after resizing. Shortest edge of the image is resized to size[\"shortest_edge\"], with\n the longest edge resized to keep the input aspect ratio.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size, param_name=\"size\", default_to_square=False)\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\", default_to_square=True)\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n\n validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if do_convert_rgb:\n images = [convert_to_rgb(image) for image in images]\n\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n all_images = []\n for image in images:\n if do_resize:\n image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n\n if do_center_crop:\n image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)\n\n if do_rescale:\n image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n\n if do_normalize:\n image = self.normalize(\n image=image, mean=image_mean, std=image_std, input_data_format=input_data_format\n )\n\n all_images.append(image)\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n for image in all_images\n ]\n\n data = {\"pixel_values\": images}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file=None,\n tokenizer_file=None,\n do_lower_case=False,\n remove_space=True,\n keep_accents=False,\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n unk_token=\"<unk>\",\n sep_token=\"<sep>\",\n pad_token=\"<pad>\",\n cls_token=\"<cls>\",\n mask_token=\"<mask>\",\n additional_special_tokens=[\"<eop>\", \"<eod>\"],\n **kwargs,\n ):\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n super().__init__(\n vocab_file=vocab_file,\n tokenizer_file=tokenizer_file,\n do_lower_case=do_lower_case,\n remove_space=remove_space,\n keep_accents=keep_accents,\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n additional_special_tokens=additional_special_tokens,\n **kwargs,\n )\n\n self._pad_token_type_id = 3\n self.do_lower_case = do_lower_case\n self.remove_space = remove_space\n self.keep_accents = keep_accents\n self.vocab_file = vocab_file", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def encode_plus_boxes(\n self,\n text: Union[TextInput, PreTokenizedInput],\n text_pair: Optional[PreTokenizedInput] = None,\n boxes: Optional[List[List[int]]] = None,\n word_labels: Optional[List[List[int]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n is_split_into_words: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Tokenize and prepare for the model a sequence or a pair of sequences.\n\n <Tip warning={true}>\n\n This method is deprecated, `__call__` should be used instead.\n\n </Tip>\n\n Args:\n text (`str`, `List[str]` or (for non-fast tokenizers) `List[int]`):\n The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the\n `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`\n method).\n text_pair (`str`, `List[str]` or `List[int]`, *optional*):\n Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using\n the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`\n method).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._encode_plus_boxes(\n text=text,\n text_pair=text_pair,\n boxes=boxes,\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n type_sequence_label_size=10,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n encoder_stride=2,\n attn_implementation=\"eager\",\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.scope = scope\n self.encoder_stride = encoder_stride\n self.attn_implementation = attn_implementation\n\n # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 2", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=49408,\n hidden_size=512,\n intermediate_size=2048,\n projection_dim=512,\n num_hidden_layers=12,\n num_attention_heads=8,\n max_position_embeddings=77,\n hidden_act=\"quick_gelu\",\n layer_norm_eps=1e-5,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n # This differs from `CLIPTokenizer`'s default and from openai/clip\n # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538\n pad_token_id=1,\n bos_token_id=49406,\n eos_token_id=49407,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.max_position_embeddings = max_position_embeddings\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.attention_dropout = attention_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_stream_processor(\n consumer_name: str,\n consumer_args: Sequence[str],\n topic: str | None,\n cluster: str | None,\n group_id: str,\n auto_offset_reset: str,\n strict_offset_reset: bool,\n join_timeout: float | None = None,\n max_poll_interval_ms: int | None = None,\n synchronize_commit_log_topic: str | None = None,\n synchronize_commit_group: str | None = None,\n healthcheck_file_path: str | None = None,\n enable_dlq: bool = True,\n enforce_schema: bool = False,\n group_instance_id: str | None = None,\n) -> StreamProcessor:\n from sentry.utils import kafka_config\n\n try:\n consumer_definition = KAFKA_CONSUMERS[consumer_name]\n except KeyError:\n raise click.ClickException(\n f\"No consumer named {consumer_name} in sentry.consumers.KAFKA_CONSUMERS. \"\n f\"Most likely there is another subcommand in 'sentry run' \"\n f\"responsible for this consumer\"\n )\n try:\n validate_consumer_definition(consumer_definition)\n except ValueError as e:\n raise click.ClickException(\n f\"Invalid consumer definition configured for {consumer_name}\"\n ) from e\n\n strategy_factory_cls = import_string(consumer_definition[\"strategy_factory\"])\n consumer_topic = consumer_definition[\"topic\"]\n\n topic_defn = get_topic_definition(consumer_topic)\n real_topic = topic_defn[\"real_topic_name\"]\n cluster_from_config = topic_defn[\"cluster\"]\n\n if topic is None:\n topic = real_topic\n\n if cluster is None:\n cluster = cluster_from_config\n\n cmd = click.Command(\n name=consumer_name, params=list(consumer_definition.get(\"click_options\") or ())\n )\n cmd_context = cmd.make_context(consumer_name, list(consumer_args))\n strategy_factory = cmd_context.invoke(\n strategy_factory_cls, **cmd_context.params, **consumer_definition.get(\"static_args\") or {}\n )\n\n def build_consumer_config(group_id: str):\n assert cluster is not None\n\n consumer_config = build_kafka_consumer_configuration(\n kafka_config.get_kafka_consumer_cluster_options(\n cluster,\n ),\n group_id=group_id,\n auto_offset_reset=auto_offset_reset,\n strict_offset_reset=strict_offset_reset,\n )\n\n if max_poll_interval_ms is not None:\n consumer_config[\"max.poll.interval.ms\"] = max_poll_interval_ms\n # HACK: If the max poll interval is less than 45 seconds, set the session timeout\n # to the same. (it's default is 45 seconds and it must be <= to max.poll.interval.ms)\n if max_poll_interval_ms < 45000:\n consumer_config[\"session.timeout.ms\"] = max_poll_interval_ms\n\n if group_instance_id is not None:\n consumer_config[\"group.instance.id\"] = group_instance_id\n\n return consumer_config\n\n consumer: Consumer = KafkaConsumer(build_consumer_config(group_id))\n\n if synchronize_commit_group is None:\n synchronize_commit_group = consumer_definition.get(\"synchronize_commit_group_default\")\n\n if synchronize_commit_log_topic is None:\n synchronize_commit_log_topic = consumer_definition.get(\n \"synchronize_commit_log_topic_default\"\n )\n\n if synchronize_commit_group or synchronize_commit_log_topic:\n if bool(synchronize_commit_log_topic) != bool(synchronize_commit_group):\n raise click.BadParameter(\n \"Both --synchronize_commit_group and --synchronize_commit_log_topic must be passed, or neither.\"\n )\n\n assert synchronize_commit_group is not None\n assert synchronize_commit_log_topic is not None\n\n commit_log_consumer = KafkaConsumer(\n build_consumer_config(f\"sentry-commit-log-{uuid.uuid1().hex}\")\n )\n\n from sentry.consumers.synchronized import SynchronizedConsumer\n\n consumer = SynchronizedConsumer(\n consumer=consumer,\n commit_log_consumer=commit_log_consumer,\n commit_log_topic=ArroyoTopic(synchronize_commit_log_topic),\n commit_log_groups={synchronize_commit_group},\n )\n elif consumer_definition.get(\"require_synchronization\"):\n click.BadParameter(\n \"--synchronize_commit_group and --synchronize_commit_log_topic are required arguments for this consumer\"\n )\n\n # Validate schema if enforce_schema is true or \"validate_schema\" is set\n validate_schema = enforce_schema or consumer_definition.get(\"validate_schema\") or False\n\n if validate_schema:\n strategy_factory = ValidateSchemaStrategyFactoryWrapper(\n consumer_topic.value, enforce_schema, strategy_factory\n )\n\n if healthcheck_file_path is not None:\n strategy_factory = HealthcheckStrategyFactoryWrapper(\n healthcheck_file_path, strategy_factory\n )\n\n if enable_dlq and consumer_definition.get(\"dlq_topic\"):\n try:\n dlq_topic = consumer_definition[\"dlq_topic\"]\n except KeyError as e:\n raise click.BadParameter(\n f\"Cannot enable DLQ for consumer: {consumer_name}, no DLQ topic has been defined for it\"\n ) from e\n try:\n dlq_topic_defn = get_topic_definition(dlq_topic)\n cluster_setting = dlq_topic_defn[\"cluster\"]\n except ValueError as e:\n raise click.BadParameter(\n f\"Cannot enable DLQ for consumer: {consumer_name}, DLQ topic {dlq_topic} is not configured in this environment\"\n ) from e\n\n producer_config = get_kafka_producer_cluster_options(cluster_setting)\n dlq_producer = KafkaProducer(producer_config)\n\n dlq_policy = DlqPolicy(\n KafkaDlqProducer(dlq_producer, ArroyoTopic(dlq_topic_defn[\"real_topic_name\"])),\n DlqLimit(\n max_invalid_ratio=consumer_definition.get(\"dlq_max_invalid_ratio\"),\n max_consecutive_count=consumer_definition.get(\"dlq_max_consecutive_count\"),\n ),\n None,\n )\n else:\n dlq_policy = None\n\n return StreamProcessor(\n consumer=consumer,\n topic=ArroyoTopic(topic),\n processor_factory=strategy_factory,\n commit_policy=ONCE_PER_SECOND,\n join_timeout=join_timeout,\n dlq_policy=dlq_policy,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LLAVA_NEXT_VIDEO_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=LlavaNextVideoCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n pixel_values: torch.FloatTensor = None,\n pixel_values_videos: torch.FloatTensor = None,\n image_sizes: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n vision_feature_layer: Optional[int] = None,\n vision_feature_select_strategy: Optional[str] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n cache_position: Optional[torch.LongTensor] = None,\n num_logits_to_keep: int = 0,\n ) -> Union[Tuple, LlavaNextVideoCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, image_size, image_size)):\n The tensors corresponding to the input videos. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`LlavaNextVideoVideoProcessor.__call__`] for details. [`LlavaProcessor`] uses\n [`LlavaNextVideoVideoProcessor`] for processing videos.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n num_logits_to_keep (`int`, *optional*):\n Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all\n `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that\n token can save memory, which becomes pretty significant for long sequences or large vocabulary size.\n\n Returns:\n\n Example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> import av\n >>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration\n\n >>> def read_video_pyav(container, indices):\n ... '''\n ... Decode the video with PyAV decoder.\n ... Args:\n ... container (`av.container.input.InputContainer`): PyAV container.\n ... indices (`List[int]`): List of frame indices to decode.\n ... Returns:\n ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).\n ... '''\n ... frames = []\n ... container.seek(0)\n ... start_index = indices[0]\n ... end_index = indices[-1]\n ... for i, frame in enumerate(container.decode(video=0)):\n ... if i > end_index:\n ... break\n ... if i >= start_index and i in indices:\n ... frames.append(frame)\n ... return np.stack([x.to_ndarray(format=\"rgb24\") for x in frames])\n\n >>> model = LlavaNextVideoForConditionalGeneration.from_pretrained(\"llava-hf/LLaVA-NeXT-Video-7B-hf\", device_map=\"auto\")\n >>> processor = AutoProcessor.from_pretrained(\"llava-hf/LLaVA-NeXT-Video-7B-hf\")\n\n >>> prompt = \"USER: <video>\\nWhy is this video funny? ASSISTANT:\"\n >>> video_path = hf_hub_download(repo_id=\"raushan-testing-hf/videos-test\", filename=\"sample_demo_1.mp4\", repo_type=\"dataset\")\n >>> container = av.open(video_path)\n\n >>> # sample uniformly 8 frames from the video (model was trained with 32 frames per video, but this video is short)\n >>> total_frames = container.streams.video[0].frames\n >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)\n >>> clip = read_video_pyav(container, indices)\n >>> inputs_video = processor(text=prompt, videos=clip, return_tensors=\"pt\").to(model.device)\n\n >>> # load an image to generate from an image\n >>> prompt = \"USER:<image>\\nWhat is shown in this image? ASSISTANT:\"\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> inputs_image = processor(text=prompt, images=image, return_tensors=\"pt\").to(model.device)\n\n >>> # Generate from video\n >>> generate_ids = model.generate(**inputs_video, max_length=50)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"USER:\\nWhy is this video funny? ASSISTANT: The humor in this video comes from the unexpected and endearing sight of a baby wearing glasses and (...)\"\n\n >>> # Generate from image\n >>> generate_ids = model.generate(**inputs_image, max_length=30)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"USER: \\nWhat's the content of the image? ASSISTANT: The image shows a red stop sign on a pole, with a traditional Chinese archway (...)\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n self.vision_feature_layer = (\n vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n )\n self.vision_feature_select_strategy = (\n vision_feature_select_strategy\n if vision_feature_select_strategy is not None\n else self.config.vision_feature_select_strategy\n )\n\n if (input_ids is None) ^ (inputs_embeds is not None):\n raise ValueError(\"You must specify exactly one of input_ids or inputs_embeds\")\n\n if (pixel_values is not None or pixel_values_videos is not None) and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one\"\n )\n\n legacy_processing = False\n if inputs_embeds is None:\n inputs_embeds = self.get_input_embeddings()(input_ids)\n\n # if the number of image/video tokens is more than image embeddings seq length, then prob we expanded it in processing\n # not very reliable, but we don't expect one to actually pass 500+ images for one prompt\n img_token_not_enough = (input_ids == self.config.image_token_index).sum(\n 1\n ).max() < self.config.image_seq_length\n video_token_not_enough = (input_ids == self.config.video_token_index).sum(\n 1\n ).max() < self.config.video_seq_length\n inputs_not_expanded = (img_token_not_enough and pixel_values is not None) or (\n video_token_not_enough and pixel_values_videos is not None\n )\n pixels_present = input_ids.shape[-1] == 1 and (pixel_values is not None or pixel_values_videos is not None)\n legacy_processing = inputs_not_expanded or pixels_present\n\n image_features = feature_lens = None\n if pixel_values is not None and pixel_values.size(0) > 0:\n image_features = self._get_image_features(pixel_values, image_sizes)\n image_features, feature_lens = self.pack_image_features(\n image_features,\n image_sizes,\n self.vision_feature_select_strategy,\n image_newline=self.image_newline,\n )\n\n video_features = video_feature_lens = None\n if pixel_values_videos is not None and pixel_values_videos.size(0) > 0:\n video_features = self._get_video_features(pixel_values_videos)\n video_features = [feature.flatten(0, 1) for feature in video_features]\n video_feature_lens = [feature.size(0) for feature in video_features]\n video_features = torch.cat(video_features, dim=0)\n video_feature_lens = torch.tensor(video_feature_lens, dtype=torch.long, device=video_features.device)\n\n if legacy_processing:\n logger.warning_once(\n \"Expanding inputs for image.video tokens in LLaVa-NeXT-Video should be done in processing. \"\n \"Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly \"\n \"with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. \"\n \"Using processors without these attributes in the config is deprecated and will throw an error in v4.47.\"\n )\n if input_ids.shape[1] != 1:\n iterator = (\n (image_features, feature_lens, self.config.image_token_index),\n (video_features, video_feature_lens, self.config.video_token_index),\n )\n for features, lens, special_token in iterator:\n if features is not None:\n (\n inputs_embeds,\n attention_mask,\n position_ids,\n labels,\n input_ids,\n ) = self._merge_input_ids_with_image_features(\n features,\n lens,\n inputs_embeds,\n input_ids,\n attention_mask,\n position_ids,\n labels=labels,\n image_token_index=special_token,\n )\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)\n else:\n # Retrieve the first layer to inspect the logits and mask out the hidden states that are set to 0\n first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]\n # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941\n batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)\n # Get the target length\n target_length = input_ids.shape[1]\n past_length = first_layer_past_key_value.shape[-1]\n extended_attention_mask = torch.ones(\n (attention_mask.shape[0], past_length),\n dtype=attention_mask.dtype,\n device=attention_mask.device,\n )\n # Filter out only the tokens that can be un-attended, this can happen\n # if one uses Llava + Fused modules where the cache on the\n # first iteration is already big enough, or if one passes custom cache\n valid_indices = non_attended_tokens < extended_attention_mask.size(-1)\n new_batch_index = batch_index[valid_indices]\n new_non_attended_tokens = non_attended_tokens[valid_indices]\n # Zero-out the places where we don't need to attend\n extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0\n attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)\n position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)[-target_length:]\n\n # TODO: @raushan retain only the new behavior after v4.47\n else:\n if image_features is not None:\n special_image_mask = (\n (input_ids == self.config.image_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)\n if video_features is not None:\n special_image_mask = (\n (input_ids == self.config.video_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, video_features)\n\n outputs = self.language_model(\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n cache_position=cache_position,\n num_logits_to_keep=num_logits_to_keep,\n )\n\n logits = outputs[0]\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n # we use the input attention mask to shift the logits and labels, because it is 2D.\n # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft\n shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)\n shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()\n shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()\n else:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(\n shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)\n )\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return LlavaNextVideoCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=image_features if pixel_values is not None else None,\n video_hidden_states=video_features if pixel_values_videos is not None else None,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_center_crop: Optional[bool] = None,\n crop_size: Optional[Dict[str, int]] = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, Iterable[float]]] = None,\n image_std: Optional[Union[float, Iterable[float]]] = None,\n return_tensors: Optional[TensorType] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> BatchFeature:\n \"\"\"\n Preprocess an image or batch of images to be used as input to a LeViT model.\n\n Args:\n images (`ImageInput`):\n Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging\n from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the output image after resizing. If size is a dict with keys \"width\" and \"height\", the image\n will be resized to (height, width). If size is a dict with key \"shortest_edge\", the shortest edge value\n `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value\n i.e, if height > width, then image will be rescaled to (size * height / width, size).\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the output image after center cropping. Crops images to (crop_size[\"height\"],\n crop_size[\"width\"]).\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image pixel values by `rescaling_factor` - typical to values between 0 and 1.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Factor to rescale the image pixel values by.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image pixel values by `image_mean` and `image_std`.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Mean to normalize the image pixel values by.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Standard deviation to normalize the image pixel values by.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`str` or `ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\")\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n if do_resize:\n images = [self.resize(image, size, resample, input_data_format=input_data_format) for image in images]\n\n if do_center_crop:\n images = [self.center_crop(image, crop_size, input_data_format=input_data_format) for image in images]\n\n if do_rescale:\n images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]\n\n if do_normalize:\n images = [\n self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images\n ]\n\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images\n ]\n\n data = {\"pixel_values\": images}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n do_lower_case=True,\n do_basic_tokenize=True,\n never_split=None,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n empty_token=\"[EMPTY]\",\n tokenize_chinese_chars=True,\n strip_accents=None,\n cell_trim_length: int = -1,\n max_column_id: int = None,\n max_row_id: int = None,\n strip_column_names: bool = False,\n update_answer_coordinates: bool = False,\n min_question_length=None,\n max_question_length=None,\n model_max_length: int = 512,\n additional_special_tokens: Optional[List[str]] = None,\n clean_up_tokenization_spaces=True,\n **kwargs,\n ):\n if not is_pandas_available():\n raise ImportError(\"Pandas is required for the TAPAS tokenizer.\")\n\n if additional_special_tokens is not None:\n if empty_token not in additional_special_tokens:\n additional_special_tokens.append(empty_token)\n else:\n additional_special_tokens = [empty_token]\n\n if not os.path.isfile(vocab_file):\n raise ValueError(\n f\"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained\"\n \" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\"\n )\n self.vocab = load_vocab(vocab_file)\n self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])\n self.do_basic_tokenize = do_basic_tokenize\n if do_basic_tokenize:\n self.basic_tokenizer = BasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n )\n self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))\n\n # Additional properties\n self.cell_trim_length = cell_trim_length\n self.max_column_id = (\n max_column_id\n if max_column_id is not None\n else model_max_length\n if model_max_length is not None\n else VERY_LARGE_INTEGER\n )\n self.max_row_id = (\n max_row_id\n if max_row_id is not None\n else model_max_length\n if model_max_length is not None\n else VERY_LARGE_INTEGER\n )\n self.strip_column_names = strip_column_names\n self.update_answer_coordinates = update_answer_coordinates\n self.min_question_length = min_question_length\n self.max_question_length = max_question_length\n\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=do_basic_tokenize,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n empty_token=empty_token,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n cell_trim_length=cell_trim_length,\n max_column_id=max_column_id,\n max_row_id=max_row_id,\n strip_column_names=strip_column_names,\n update_answer_coordinates=update_answer_coordinates,\n min_question_length=min_question_length,\n max_question_length=max_question_length,\n model_max_length=model_max_length,\n additional_special_tokens=additional_special_tokens,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def prepare_for_model(\n self,\n ids: List[int],\n pair_ids: Optional[List[int]] = None,\n entity_ids: Optional[List[int]] = None,\n pair_entity_ids: Optional[List[int]] = None,\n entity_token_spans: Optional[List[Tuple[int, int]]] = None,\n pair_entity_token_spans: Optional[List[Tuple[int, int]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n max_entity_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n prepend_batch_axis: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,\n entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing\n while taking into account the special tokens and manages a moving window (with user defined stride) for\n overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*\n or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an\n error.\n\n Args:\n ids (`List[int]`):\n Tokenized input ids of the first sequence.\n pair_ids (`List[int]`, *optional*):\n Tokenized input ids of the second sequence.\n entity_ids (`List[int]`, *optional*):\n Entity ids of the first sequence.\n pair_entity_ids (`List[int]`, *optional*):\n Entity ids of the second sequence.\n entity_token_spans (`List[Tuple[int, int]]`, *optional*):\n Entity spans of the first sequence.\n pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):\n Entity spans of the second sequence.\n max_entity_length (`int`, *optional*):\n The maximum length of the entity sequence.\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n # Compute lengths\n pair = bool(pair_ids is not None)\n len_ids = len(ids)\n len_pair_ids = len(pair_ids) if pair else 0\n\n if return_token_type_ids and not add_special_tokens:\n raise ValueError(\n \"Asking to return token_type_ids while setting add_special_tokens to False \"\n \"results in an undefined behavior. Please set add_special_tokens to True or \"\n \"set return_token_type_ids to None.\"\n )\n if (\n return_overflowing_tokens\n and truncation_strategy == TruncationStrategy.LONGEST_FIRST\n and pair_ids is not None\n ):\n raise ValueError(\n \"Not possible to return overflowing tokens for pair of sequences with the \"\n \"`longest_first`. Please select another truncation strategy than `longest_first`, \"\n \"for instance `only_second` or `only_first`.\"\n )\n\n # Load from model defaults\n if return_token_type_ids is None:\n return_token_type_ids = \"token_type_ids\" in self.model_input_names\n if return_attention_mask is None:\n return_attention_mask = \"attention_mask\" in self.model_input_names\n\n encoded_inputs = {}\n\n # Compute the total size of the returned word encodings\n total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)\n\n # Truncation: Handle max sequence length and max_entity_length\n overflowing_tokens = []\n if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:\n # truncate words up to max_length\n ids, pair_ids, overflowing_tokens = self.truncate_sequences(\n ids,\n pair_ids=pair_ids,\n num_tokens_to_remove=total_len - max_length,\n truncation_strategy=truncation_strategy,\n stride=stride,\n )\n\n if return_overflowing_tokens:\n encoded_inputs[\"overflowing_tokens\"] = overflowing_tokens\n encoded_inputs[\"num_truncated_tokens\"] = total_len - max_length\n\n # Add special tokens\n if add_special_tokens:\n sequence = self.build_inputs_with_special_tokens(ids, pair_ids)\n token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)\n entity_token_offset = 1 # 1 * <s> token\n pair_entity_token_offset = len(ids) + 3 # 1 * <s> token & 2 * <sep> tokens\n else:\n sequence = ids + pair_ids if pair else ids\n token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])\n entity_token_offset = 0\n pair_entity_token_offset = len(ids)\n\n # Build output dictionary\n encoded_inputs[\"input_ids\"] = sequence\n if return_token_type_ids:\n encoded_inputs[\"token_type_ids\"] = token_type_ids\n if return_special_tokens_mask:\n if add_special_tokens:\n encoded_inputs[\"special_tokens_mask\"] = self.get_special_tokens_mask(ids, pair_ids)\n else:\n encoded_inputs[\"special_tokens_mask\"] = [0] * len(sequence)\n\n # Set max entity length\n if not max_entity_length:\n max_entity_length = self.max_entity_length\n\n if entity_ids is not None:\n total_entity_len = 0\n num_invalid_entities = 0\n valid_entity_ids = [ent_id for ent_id, span in zip(entity_ids, entity_token_spans) if span[1] <= len(ids)]\n valid_entity_token_spans = [span for span in entity_token_spans if span[1] <= len(ids)]\n\n total_entity_len += len(valid_entity_ids)\n num_invalid_entities += len(entity_ids) - len(valid_entity_ids)\n\n valid_pair_entity_ids, valid_pair_entity_token_spans = None, None\n if pair_entity_ids is not None:\n valid_pair_entity_ids = [\n ent_id\n for ent_id, span in zip(pair_entity_ids, pair_entity_token_spans)\n if span[1] <= len(pair_ids)\n ]\n valid_pair_entity_token_spans = [span for span in pair_entity_token_spans if span[1] <= len(pair_ids)]\n total_entity_len += len(valid_pair_entity_ids)\n num_invalid_entities += len(pair_entity_ids) - len(valid_pair_entity_ids)\n\n if num_invalid_entities != 0:\n logger.warning(\n f\"{num_invalid_entities} entities are ignored because their entity spans are invalid due to the\"\n \" truncation of input tokens\"\n )\n\n if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and total_entity_len > max_entity_length:\n # truncate entities up to max_entity_length\n valid_entity_ids, valid_pair_entity_ids, overflowing_entities = self.truncate_sequences(\n valid_entity_ids,\n pair_ids=valid_pair_entity_ids,\n num_tokens_to_remove=total_entity_len - max_entity_length,\n truncation_strategy=truncation_strategy,\n stride=stride,\n )\n valid_entity_token_spans = valid_entity_token_spans[: len(valid_entity_ids)]\n if valid_pair_entity_token_spans is not None:\n valid_pair_entity_token_spans = valid_pair_entity_token_spans[: len(valid_pair_entity_ids)]\n\n if return_overflowing_tokens:\n encoded_inputs[\"overflowing_entities\"] = overflowing_entities\n encoded_inputs[\"num_truncated_entities\"] = total_entity_len - max_entity_length\n\n final_entity_ids = valid_entity_ids + valid_pair_entity_ids if valid_pair_entity_ids else valid_entity_ids\n encoded_inputs[\"entity_ids\"] = list(final_entity_ids)\n entity_position_ids = []\n entity_start_positions = []\n entity_end_positions = []\n for token_spans, offset in (\n (valid_entity_token_spans, entity_token_offset),\n (valid_pair_entity_token_spans, pair_entity_token_offset),\n ):\n if token_spans is not None:\n for start, end in token_spans:\n start += offset\n end += offset\n position_ids = list(range(start, end))[: self.max_mention_length]\n position_ids += [-1] * (self.max_mention_length - end + start)\n entity_position_ids.append(position_ids)\n entity_start_positions.append(start)\n entity_end_positions.append(end - 1)\n\n encoded_inputs[\"entity_position_ids\"] = entity_position_ids\n if self.task == \"entity_span_classification\":\n encoded_inputs[\"entity_start_positions\"] = entity_start_positions\n encoded_inputs[\"entity_end_positions\"] = entity_end_positions\n\n if return_token_type_ids:\n encoded_inputs[\"entity_token_type_ids\"] = [0] * len(encoded_inputs[\"entity_ids\"])\n\n # Check lengths\n self._eventual_warn_about_too_long_sequence(encoded_inputs[\"input_ids\"], max_length, verbose)\n\n # Padding\n if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:\n encoded_inputs = self.pad(\n encoded_inputs,\n max_length=max_length,\n max_entity_length=max_entity_length,\n padding=padding_strategy.value,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_attention_mask=return_attention_mask,\n )\n\n if return_length:\n encoded_inputs[\"length\"] = len(encoded_inputs[\"input_ids\"])\n\n batch_outputs = BatchEncoding(\n encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis\n )\n\n return batch_outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n num_channels=3,\n image_size=32,\n patch_size=16,\n use_labels=True,\n num_labels=3,\n is_training=True,\n hidden_size=4,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=8,\n out_features=[\"stage1\", \"stage2\"],\n apply_layernorm=False,\n reshape_hidden_states=False,\n neck_hidden_sizes=[2, 2],\n fusion_hidden_size=6,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.patch_size = patch_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.out_features = out_features\n self.apply_layernorm = apply_layernorm\n self.reshape_hidden_states = reshape_hidden_states\n self.use_labels = use_labels\n self.num_labels = num_labels\n self.is_training = is_training\n self.neck_hidden_sizes = neck_hidden_sizes\n self.fusion_hidden_size = fusion_hidden_size\n # DPT's sequence length\n self.seq_length = (self.image_size // self.patch_size) ** 2 + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Union[Tuple[torch.Tensor], BaseModelOutput]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Seq2SeqModelOutput:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, MarianModel\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"Helsinki-NLP/opus-mt-en-de\")\n >>> model = MarianModel.from_pretrained(\"Helsinki-NLP/opus-mt-en-de\")\n\n >>> inputs = tokenizer(\"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\")\n >>> decoder_inputs = tokenizer(\n ... \"<pad> Studien haben gezeigt dass es hilfreich ist einen Hund zu besitzen\",\n ... return_tensors=\"pt\",\n ... add_special_tokens=False,\n ... )\n >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)\n\n >>> last_hidden_states = outputs.last_hidden_state\n >>> list(last_hidden_states.shape)\n [1, 26, 512]\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __call__(\n self,\n images,\n text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,\n text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,\n boxes: Union[List[List[int]], List[List[List[int]]]] = None,\n word_labels: Optional[Union[List[int], List[List[int]]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n return_tensors: Optional[Union[str, TensorType]] = None,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n This method first forwards the `images` argument to [`~LayoutLMv3ImageProcessor.__call__`]. In case\n [`LayoutLMv3ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and\n bounding boxes along with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output,\n together with resized and normalized `pixel_values`. In case [`LayoutLMv3ImageProcessor`] was initialized with\n `apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along\n with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output, together with\n resized and normalized `pixel_values`.\n\n Please refer to the docstring of the above two methods for more information.\n \"\"\"\n # verify input\n if self.image_processor.apply_ocr and (boxes is not None):\n raise ValueError(\n \"You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.\"\n )\n\n if self.image_processor.apply_ocr and (word_labels is not None):\n raise ValueError(\n \"You cannot provide word labels if you initialized the image processor with apply_ocr set to True.\"\n )\n\n # first, apply the image processor\n features = self.image_processor(images=images, return_tensors=return_tensors)\n\n # second, apply the tokenizer\n if text is not None and self.image_processor.apply_ocr and text_pair is None:\n if isinstance(text, str):\n text = [text] # add batch dimension (as the image processor always adds a batch dimension)\n text_pair = features[\"words\"]\n\n encoded_inputs = self.tokenizer(\n text=text if text is not None else features[\"words\"],\n text_pair=text_pair if text_pair is not None else None,\n boxes=boxes if boxes is not None else features[\"boxes\"],\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n return_tensors=return_tensors,\n **kwargs,\n )\n\n # add pixel values\n images = features.pop(\"pixel_values\")\n if return_overflowing_tokens is True:\n images = self.get_overflowing_images(images, encoded_inputs[\"overflow_to_sample_mapping\"])\n encoded_inputs[\"pixel_values\"] = images\n\n return encoded_inputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n min_resolution=30,\n max_resolution=400,\n size=None,\n do_resize=True,\n do_normalize=True,\n image_mean=[0.5, 0.5, 0.5],\n image_std=[0.5, 0.5, 0.5],\n num_labels=10,\n do_reduce_labels=False,\n ignore_index=255,\n repo_path=\"shi-labs/oneformer_demo\",\n class_info_file=\"ade20k_panoptic.json\",\n num_text=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = {\"shortest_edge\": 32, \"longest_edge\": 1333} if size is None else size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.class_info_file = class_info_file\n self.num_text = num_text\n self.repo_path = repo_path\n\n # for the post_process_functions\n self.batch_size = 2\n self.num_queries = 10\n self.num_classes = 10\n self.height = 3\n self.width = 4\n self.num_labels = num_labels\n self.do_reduce_labels = do_reduce_labels\n self.ignore_index = ignore_index", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n past_key_values: Optional[List[tf.Tensor]] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n pixel_values: Optional[tf.Tensor] = None,\n image_encoder_embeddings: Optional[tf.Tensor] = None,\n perceiver_embeddings: Optional[tf.Tensor] = None,\n image_attention_mask: Optional[tf.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n interpolate_pos_encoding: Optional[bool] = False,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = None,\n ) -> Union[TFIdeficsBaseModelOutputWithPast, Tuple[tf.Tensor]]:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n pixel_values=pixel_values,\n image_encoder_embeddings=image_encoder_embeddings,\n perceiver_embeddings=perceiver_embeddings,\n image_attention_mask=image_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n interpolate_pos_encoding=interpolate_pos_encoding,\n return_dict=return_dict,\n training=training,\n )\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n seq_length=7,\n num_channels=3,\n ignore_index=-100,\n image_size=14,\n bos_token_id=0,\n eos_token_id=1,\n pad_token_id=2,\n vision_start_token_id=151652,\n image_token_id=151655,\n video_token_id=151656,\n hidden_act=\"silu\",\n hidden_size=32,\n vocab_size=152064,\n intermediate_size=37,\n max_position_embeddings=512,\n max_window_layers=3,\n model_type=\"qwen2_vl\",\n num_attention_heads=4,\n num_hidden_layers=4,\n num_key_value_heads=2,\n rope_theta=10000,\n tie_word_embeddings=True,\n is_training=True,\n vision_config={\n \"depth\": 2,\n \"embed_dim\": 32,\n \"hidden_act\": \"quick_gelu\",\n \"hidden_size\": 32,\n \"mlp_ratio\": 4,\n \"num_heads\": 4,\n \"patch_size\": 14,\n \"spatial_merge_size\": 1,\n \"temporal_patch_size\": 2,\n },\n rope_scaling={\"type\": \"mrope\", \"mrope_section\": [2, 1, 1]},\n ):\n self.parent = parent\n self.ignore_index = ignore_index\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.vision_start_token_id = vision_start_token_id\n self.image_token_id = image_token_id\n self.video_token_id = video_token_id\n self.hidden_act = hidden_act\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.max_position_embeddings = max_position_embeddings\n self.max_window_layers = max_window_layers\n self.model_type = model_type\n self.num_attention_heads = num_attention_heads\n self.num_hidden_layers = num_hidden_layers\n self.num_key_value_heads = num_key_value_heads\n self.rope_theta = rope_theta\n self.tie_word_embeddings = tie_word_embeddings\n self.vision_config = vision_config\n self.rope_scaling = rope_scaling\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.is_training = is_training\n self.vocab_size = vocab_size\n self.num_image_tokens = 32\n self.seq_length = seq_length + self.num_image_tokens", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n actions=None,\n env_actions=None,\n observations=None,\n rewards=None,\n disc_lines=None,\n times=None,\n params=None,\n meta=None,\n episode_times=None,\n observation_space=None,\n action_space=None,\n helper_action_env=None,\n attack_space=None,\n path_save=None,\n disc_lines_templ=None,\n attack_templ=None,\n attack=None,\n logger=None,\n name=\"EpisodeData\",\n get_dataframes=None,\n force_detail=False,\n other_rewards=[],\n legal=None,\n ambiguous=None,\n has_legal_ambiguous=False,\n _init_collections=False,\n ):\n self.parameters = None\n self.actions = CollectionWrapper(\n actions,\n action_space,\n \"actions\",\n check_legit=False,\n init_me=_init_collections,\n )\n\n self.observations = CollectionWrapper(\n observations, observation_space, \"observations\", init_me=_init_collections\n )\n\n self.env_actions = CollectionWrapper(\n env_actions,\n helper_action_env,\n \"env_actions\",\n check_legit=False,\n init_me=_init_collections,\n )\n\n self.attacks = CollectionWrapper(\n attack, attack_space, \"attacks\", init_me=_init_collections\n )\n\n self.meta = meta\n # gives a unique game over for everyone\n # TODO this needs testing!\n action_go = self.actions._game_over\n obs_go = self.observations._game_over\n env_go = self.env_actions._game_over\n # raise RuntimeError(\"Add the attaks game over too !\")\n real_go = action_go\n if self.meta is not None:\n # when initialized by the runner, meta is None\n if \"nb_timestep_played\" in self.meta:\n real_go = int(self.meta[\"nb_timestep_played\"])\n if real_go is None:\n real_go = action_go\n else:\n if action_go is not None:\n real_go = min(action_go, real_go)\n if real_go is None:\n real_go = obs_go\n else:\n if obs_go is not None:\n real_go = min(obs_go, real_go)\n if real_go is None:\n real_go = env_go\n else:\n if env_go is not None:\n real_go = min(env_go, real_go)\n if real_go is not None:\n # there is a real game over, i assign the proper value for each collection\n self.actions._game_over = real_go\n self.observations._game_over = real_go + 1\n self.env_actions._game_over = real_go\n\n self.other_rewards = other_rewards\n self.observation_space = observation_space\n self.attack_space = attack_space\n self.rewards = rewards\n self.disc_lines = disc_lines\n self.times = times\n self.params = params\n self.episode_times = episode_times\n self.name = name\n self.disc_lines_templ = disc_lines_templ\n\n self.attack_templ = attack_templ\n\n self.logger = logger\n self.serialize = False\n self.load_names = action_space.name_load\n self.n_loads = len(self.load_names)\n self.prod_names = action_space.name_gen\n self.n_prods = len(self.prod_names)\n self.line_names = action_space.name_line\n self.n_lines = len(self.line_names)\n self.name_sub = action_space.name_sub\n self.force_detail = force_detail\n\n self.has_legal_ambiguous = has_legal_ambiguous\n self.legal = copy.deepcopy(legal)\n self.ambiguous = copy.deepcopy(ambiguous)\n \n if path_save is not None:\n self.agent_path = os.path.abspath(path_save)\n self.episode_path = os.path.join(self.agent_path, name)\n self.serialize = True\n if not os.path.exists(self.agent_path):\n try:\n os.mkdir(self.agent_path)\n self.logger.info(\n 'Creating path \"{}\" to save the runner'.format(self.agent_path)\n )\n except FileExistsError:\n pass\n\n act_space_path = os.path.join(self.agent_path, EpisodeData.ACTION_SPACE)\n obs_space_path = os.path.join(self.agent_path, EpisodeData.OBS_SPACE)\n env_modif_space_path = os.path.join(\n self.agent_path, EpisodeData.ENV_MODIF_SPACE\n )\n attack_space_path = os.path.join(self.agent_path, EpisodeData.ATTACK_SPACE)\n\n if not os.path.exists(act_space_path):\n dict_action_space = action_space.cls_to_dict()\n with open(act_space_path, \"w\", encoding=\"utf8\") as f:\n json.dump(obj=dict_action_space, fp=f, indent=4, sort_keys=True)\n if not os.path.exists(obs_space_path):\n dict_observation_space = observation_space.cls_to_dict()\n with open(obs_space_path, \"w\", encoding=\"utf8\") as f:\n json.dump(\n obj=dict_observation_space, fp=f, indent=4, sort_keys=True\n )\n if not os.path.exists(env_modif_space_path):\n dict_helper_action_env = helper_action_env.cls_to_dict()\n with open(env_modif_space_path, \"w\", encoding=\"utf8\") as f:\n json.dump(\n obj=dict_helper_action_env, fp=f, indent=4, sort_keys=True\n )\n if not os.path.exists(attack_space_path):\n dict_attack_space = attack_space.cls_to_dict()\n with open(attack_space_path, \"w\", encoding=\"utf8\") as f:\n json.dump(obj=dict_attack_space, fp=f, indent=4, sort_keys=True)\n\n if not os.path.exists(self.episode_path):\n os.mkdir(self.episode_path)\n logger.info(\n 'Creating path \"{}\" to save the episode {}'.format(\n self.episode_path, self.name\n )\n )", "smellKey": "S107", "smellId": null, "repo": "Grid2op_grid2op", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLM_PROPHETNET_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=XLMProphetNetSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.Tensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, XLMProphetNetSeq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, XLMProphetNetModel\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"patrickvonplaten/xprophetnet-large-uncased-standalone\")\n >>> model = XLMProphetNetModel.from_pretrained(\"patrickvonplaten/xprophetnet-large-uncased-standalone\")\n\n >>> input_ids = tokenizer(\n ... \"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> decoder_input_ids = tokenizer(\"Studies show that\", return_tensors=\"pt\").input_ids # Batch size 1\n >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)\n\n >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states\n >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n use_cache=use_cache,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n return XLMProphetNetSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n last_hidden_state_ngram=decoder_outputs.last_hidden_state_ngram,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_ngram_hidden_states=decoder_outputs.hidden_states_ngram,\n decoder_attentions=decoder_outputs.attentions,\n decoder_ngram_attentions=decoder_outputs.ngram_attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=12,\n patch_embed_hidden_size=12,\n projection_dim=32,\n max_patches=64,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=1e-10,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_embed_hidden_size = patch_embed_hidden_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.max_patches = max_patches\n self.seq_length = self.max_patches\n self.patch_proj_dim = ((patch_size**2) * num_channels) + 2\n\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n # must be [== max_position_embeddings] AND [multiple of block_size (default = 32)] (?)\n seq_length=64,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=36,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n max_position_embeddings=64,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32000,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=None,\n hidden_act=\"silu\",\n max_position_embeddings=2048,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n rope_theta=10000.0,\n rope_scaling=None,\n attention_bias=False,\n attention_dropout=0.0,\n mlp_bias=False,\n embedding_multiplier=1.0,\n logits_scaling=1.0,\n residual_multiplier=1.0,\n attention_multiplier=1.0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n\n # for backward compatibility\n if num_key_value_heads is None:\n num_key_value_heads = num_attention_heads\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.rope_scaling = rope_scaling\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n self.mlp_bias = mlp_bias\n\n self.embedding_multiplier = embedding_multiplier\n self.logits_scaling = logits_scaling\n self.residual_multiplier = residual_multiplier\n self.attention_multiplier = attention_multiplier\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )\n\n rope_config_validation(self)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n encoder_seq_length=7,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n d_ff=37,\n relative_attention_num_buckets=8,\n dropout_rate=0.1,\n initializer_factor=0.002,\n eos_token_id=1,\n pad_token_id=0,\n decoder_start_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n # For common tests\n self.seq_length = self.encoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.d_ff = d_ff\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.dropout_rate = dropout_rate\n self.initializer_factor = initializer_factor\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.scope = None\n self.decoder_layers = 0", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@deprecate_kwarg(\"reduce_labels\", new_name=\"do_reduce_labels\", version=\"4.44.0\")\n @filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n segmentation_maps: Optional[ImageInput] = None,\n instance_id_to_semantic_id: Optional[Dict[int, int]] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n size_divisor: Optional[int] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n ignore_index: Optional[int] = None,\n do_reduce_labels: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> BatchFeature:\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False, max_size=self._max_size)\n size_divisor = size_divisor if size_divisor is not None else self.size_divisor\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n ignore_index = ignore_index if ignore_index is not None else self.ignore_index\n do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if segmentation_maps is not None and not valid_images(segmentation_maps):\n raise ValueError(\n \"Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n if not is_batched(images):\n images = [images]\n segmentation_maps = [segmentation_maps] if segmentation_maps is not None else None\n\n if segmentation_maps is not None and len(images) != len(segmentation_maps):\n raise ValueError(\"Images and segmentation maps must have the same length.\")\n\n images = [\n self._preprocess_image(\n image,\n do_resize=do_resize,\n size=size,\n size_divisor=size_divisor,\n resample=resample,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n\n if segmentation_maps is not None:\n segmentation_maps = [\n self._preprocess_mask(\n segmentation_map, do_resize, size, size_divisor, input_data_format=input_data_format\n )\n for segmentation_map in segmentation_maps\n ]\n encoded_inputs = self.encode_inputs(\n images,\n segmentation_maps,\n instance_id_to_semantic_id,\n ignore_index,\n do_reduce_labels,\n return_tensors,\n input_data_format=data_format,\n )\n return encoded_inputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFSeq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[TFSeq2SeqModelOutput, Tuple[tf.Tensor]]:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@bind_hass\ndef turn_on(\n hass: HomeAssistant,\n entity_id: str = ENTITY_MATCH_ALL,\n transition: float | None = None,\n brightness: int | None = None,\n brightness_pct: float | None = None,\n rgb_color: tuple[int, int, int] | None = None,\n rgbw_color: tuple[int, int, int, int] | None = None,\n rgbww_color: tuple[int, int, int, int, int] | None = None,\n xy_color: tuple[float, float] | None = None,\n hs_color: tuple[float, float] | None = None,\n color_temp: int | None = None,\n kelvin: int | None = None,\n profile: str | None = None,\n flash: str | None = None,\n effect: str | None = None,\n color_name: str | None = None,\n white: bool | None = None,\n) -> None:\n \"\"\"Turn all or specified light on.\"\"\"\n hass.add_job(\n async_turn_on,\n hass,\n entity_id,\n transition,\n brightness,\n brightness_pct,\n rgb_color,\n rgbw_color,\n rgbww_color,\n xy_color,\n hs_color,\n color_temp,\n kelvin,\n profile,\n flash,\n effect,\n color_name,\n white,\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "async def create_connection(\n self, protocol_factory, host=None, port=None,\n *, ssl=None, family=0, proto=0,\n flags=0, sock=None, local_addr=None,\n server_hostname=None,\n ssl_handshake_timeout=None,\n ssl_shutdown_timeout=None,\n happy_eyeballs_delay=None, interleave=None):\n raise NotImplementedError", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(\n self,\n backbone_config: Optional[Dict] = None,\n backbone: Optional[str] = None,\n use_pretrained_backbone: bool = False,\n use_timm_backbone: bool = False,\n backbone_kwargs: Optional[Dict] = None,\n ignore_value: int = 255,\n num_queries: int = 150,\n no_object_weight: int = 0.1,\n class_weight: float = 2.0,\n mask_weight: float = 5.0,\n dice_weight: float = 5.0,\n contrastive_weight: float = 0.5,\n contrastive_temperature: float = 0.07,\n train_num_points: int = 12544,\n oversample_ratio: float = 3.0,\n importance_sample_ratio: float = 0.75,\n init_std: float = 0.02,\n init_xavier_std: float = 1.0,\n layer_norm_eps: float = 1e-05,\n is_training: bool = False,\n use_auxiliary_loss: bool = True,\n output_auxiliary_logits: bool = True,\n strides: Optional[list] = [4, 8, 16, 32],\n task_seq_len: int = 77,\n text_encoder_width: int = 256,\n text_encoder_context_length: int = 77,\n text_encoder_num_layers: int = 6,\n text_encoder_vocab_size: int = 49408,\n text_encoder_proj_layers: int = 2,\n text_encoder_n_ctx: int = 16,\n conv_dim: int = 256,\n mask_dim: int = 256,\n hidden_dim: int = 256,\n encoder_feedforward_dim: int = 1024,\n norm: str = \"GN\",\n encoder_layers: int = 6,\n decoder_layers: int = 10,\n use_task_norm: bool = True,\n num_attention_heads: int = 8,\n dropout: float = 0.1,\n dim_feedforward: int = 2048,\n pre_norm: bool = False,\n enforce_input_proj: bool = False,\n query_dec_layers: int = 2,\n common_stride: int = 4,\n **kwargs,\n ):\n if backbone_config is None and backbone is None:\n logger.info(\"`backbone_config` is unset. Initializing the config with the default `Swin` backbone.\")\n backbone_config = CONFIG_MAPPING[\"swin\"](\n image_size=224,\n in_channels=3,\n patch_size=4,\n embed_dim=96,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n window_size=7,\n drop_path_rate=0.3,\n use_absolute_embeddings=False,\n out_features=[\"stage1\", \"stage2\", \"stage3\", \"stage4\"],\n )\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.get(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n self.backbone_config = backbone_config\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n self.ignore_value = ignore_value\n self.num_queries = num_queries\n self.no_object_weight = no_object_weight\n self.class_weight = class_weight\n self.mask_weight = mask_weight\n self.dice_weight = dice_weight\n self.contrastive_weight = contrastive_weight\n self.contrastive_temperature = contrastive_temperature\n self.train_num_points = train_num_points\n self.oversample_ratio = oversample_ratio\n self.importance_sample_ratio = importance_sample_ratio\n self.init_std = init_std\n self.init_xavier_std = init_xavier_std\n self.layer_norm_eps = layer_norm_eps\n self.is_training = is_training\n self.use_auxiliary_loss = use_auxiliary_loss\n self.output_auxiliary_logits = output_auxiliary_logits\n self.strides = strides\n self.task_seq_len = task_seq_len\n self.text_encoder_width = text_encoder_width\n self.text_encoder_context_length = text_encoder_context_length\n self.text_encoder_num_layers = text_encoder_num_layers\n self.text_encoder_vocab_size = text_encoder_vocab_size\n self.text_encoder_proj_layers = text_encoder_proj_layers\n self.text_encoder_n_ctx = text_encoder_n_ctx\n self.conv_dim = conv_dim\n self.mask_dim = mask_dim\n self.hidden_dim = hidden_dim\n self.encoder_feedforward_dim = encoder_feedforward_dim\n self.norm = norm\n self.encoder_layers = encoder_layers\n self.decoder_layers = decoder_layers\n self.use_task_norm = use_task_norm\n self.num_attention_heads = num_attention_heads\n self.dropout = dropout\n self.dim_feedforward = dim_feedforward\n self.pre_norm = pre_norm\n self.enforce_input_proj = enforce_input_proj\n self.query_dec_layers = query_dec_layers\n self.common_stride = common_stride\n self.num_hidden_layers = decoder_layers\n\n super().__init__(**kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=2,\n seq_length=7,\n is_training=False,\n use_input_mask=True,\n use_labels=True,\n vocab_size=50,\n hidden_size=128,\n projection_dim=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=32,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n task_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n past_key_values: Optional[List[torch.Tensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.ernie(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n task_type_ids=task_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def add_test_gemm(\n cls=None,\n cc=None,\n element=None,\n layouts=None,\n alignments=None,\n element_output=None,\n element_accumulator=None,\n cluster_shape=None,\n threadblock_shape=None,\n warp_count=None,\n stages=None,\n opclass=None,\n swizzle=None,\n kernel_schedule=None,\n epilogue_schedule=None,\n compilation_modes=['nvcc', 'nvrtc']):\n \"\"\"\n Create test-running functions with the given specification and set it as a method of ``cls``.\n\n :param cls: class to which the generated method will be added\n :type cls: type\n :param cc: compute capability to compile for\n :type cc: int\n :param element: data type of A and B operands\n :type element: cutlass.DataType.f16\n :param layouts: layouts of A, B, and C operands\n :type layouts: list or tuple\n :param alignments: alingments of A, B, and C operands\n :type alignments: list or tuple\n :param element_output: data type of the output element\n :type element_output: cutlass.DataType\n :param element_accumulator: data type used in accumulation\n :type element_accumulator: cutlass.DataType\n :param cluster_shape: dimensions of clusters\n :type cluster_shape: list or tuple\n :param threadblock_shape: dimensions of threadblock tiles\n :type threadblock_shape: list or tuple\n :param warp_count: warps to be launched per threadblock dimension\n :type warp_count: list or tuple\n :param stages: number of pipeline stages to use in the kernel\n :type stages: int\n :param opclass: class of operation being performed (e.g., SIMT, Tensor Core)\n :type opclass: cutlass.OpClass\n :param swizzle: threadblock swizzling functor\n :param kernel_schedule: kernel schedule to use\n :type kernel_schedule: cutlass.KernelScheduleType\n :param epilogue_schedule: epilogue schedule to use\n :type epilogue_schedule: cutlass.EpilogueScheduleType\n :param compilation_modes: list of compilers to used in testing the kernel (options: 'nvrtc', 'nvcc')\n :type compilation_modes: list\n \"\"\"\n\n for compilation_mode in compilation_modes:\n def run(self):\n \"\"\"\n Dynamically-generated function that constructs a GEMM operation and verifies it against\n multiple test cases.\n \"\"\"\n element_A = element\n element_B = element\n layout_A, layout_B, layout_C = layouts\n alignment_A, alignment_B, alignment_C = alignments\n\n plan = cutlass.op.Gemm(element_A=element_A, element_B=element_B,\n element_C=element_output, element_D=element_output,\n layout_A=layout_A, layout_B=layout_B, layout_C=layout_C,\n element_accumulator=element_accumulator,\n kernel_cc=cc)\n\n plan.opclass = opclass\n if swizzle is not None:\n plan.swizzling_functor = swizzle\n td = plan.tile_descriptions()[0]\n td.threadblock_shape = threadblock_shape\n td.stages = stages\n if warp_count is not None:\n td.warp_count = warp_count\n td.cluster_shape = cluster_shape\n op = plan.construct(tile_description=td, alignment_A=alignment_A, alignment_B=alignment_B, alignment_C=alignment_C)\n self.assertTrue(test_all_gemm(op, 'universal', compilation_mode=compilation_mode))\n\n element_epilogue = element_accumulator\n name = get_name(\n layouts=layouts, alignments=alignments, element_output=element_output, element_accumulator=element_accumulator,\n element_epilogue=element_epilogue, cluster_shape=cluster_shape, threadblock_shape=threadblock_shape,\n stages=stages, element_a=element, element_b=element, arch=cc, opclass=opclass,\n kernel_schedule=kernel_schedule, epilogue_schedule=epilogue_schedule, suffix=f'_{compilation_mode}')\n\n setattr(cls, name, run)", "smellKey": "S107", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def __init__(\n self,\n parent,\n d_model=16,\n batch_size=13,\n prediction_length=7,\n context_length=14,\n label_length=10,\n cardinality=19,\n embedding_dimension=5,\n num_time_features=4,\n is_training=True,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n lags_sequence=[1, 2, 3, 4, 5],\n moving_average=25,\n autocorrelation_factor=5,\n ):\n self.d_model = d_model\n self.parent = parent\n self.batch_size = batch_size\n self.prediction_length = prediction_length\n self.context_length = context_length\n self.cardinality = cardinality\n self.num_time_features = num_time_features\n self.lags_sequence = lags_sequence\n self.embedding_dimension = embedding_dimension\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n\n self.encoder_seq_length = context_length\n self.decoder_seq_length = prediction_length + label_length\n self.label_length = label_length\n\n self.moving_average = moving_average\n self.autocorrelation_factor = autocorrelation_factor", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n inputs_embeds: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n position_ids: tf.Tensor | None = None,\n encoder_hidden_states: tf.Tensor | None = None,\n encoder_attention_mask: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n ):\n r\"\"\"\n Args:\n input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you\n provide it.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the\n range `[0, config.max_position_embeddings - 1]`.\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention\n of the decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):\n Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values\n selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up\n decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those\n that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of\n all `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value\n in the config will be used instead.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail. This argument can be used only in eager mode, in graph mode the value in the config\n will be used instead.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used\n in eager mode, in graph mode the value will always be set to True.\n training (`bool`, *optional*, defaults to `False`):\n Whether or not to use the model in training mode (some modules like dropout modules have different\n behaviors between training and evaluation).\n \"\"\"\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = shape_list(input_ids)\n elif inputs_embeds is not None:\n input_shape = shape_list(inputs_embeds)[:-1]\n else:\n raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\n\n past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0\n\n # embed positions\n if position_ids is None:\n positions = self.embed_positions(input_shape, past_key_values_length)\n else:\n positions = self.embed_positions(input_shape, position_ids=position_ids)\n\n if inputs_embeds is None:\n check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)\n inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale\n\n hidden_states = inputs_embeds\n\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n if input_shape[-1] > 1:\n combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)\n else:\n combined_attention_mask = _expand_mask(\n tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]\n )\n\n if attention_mask is not None:\n combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])\n\n if encoder_hidden_states is not None and encoder_attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])\n\n hidden_states = self.dropout(hidden_states + positions, training=training)\n\n # decoder layers\n all_hidden_states = () if output_hidden_states else None\n all_self_attns = () if output_attentions else None\n all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None\n present_key_values = () if use_cache else None\n\n # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired\n for attn_name, attn_mask in [(\"head_mask\", head_mask), (\"cross_attn_head_mask\", cross_attn_head_mask)]:\n if attn_mask is not None:\n tf.debugging.assert_equal(\n shape_list(attn_mask)[0],\n len(self.layers),\n message=(\n f\"The {attn_name} should be specified for {len(self.layers)} layers, but it is for\"\n f\" {shape_list(attn_mask)[0]}.\"\n ),\n )\n\n for idx, decoder_layer in enumerate(self.layers):\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n dropout_probability = random.uniform(0, 1)\n\n if training and (dropout_probability < self.layerdrop):\n continue\n\n past_key_value = past_key_values[idx] if past_key_values is not None else None\n\n hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(\n hidden_states,\n attention_mask=combined_attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n layer_head_mask=head_mask[idx] if head_mask is not None else None,\n cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,\n past_key_value=past_key_value,\n )\n\n if use_cache:\n present_key_values += (present_key_value,)\n\n if output_attentions:\n all_self_attns += (layer_self_attn,)\n\n if encoder_hidden_states is not None:\n all_cross_attns += (layer_cross_attn,)\n\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n if not return_dict:\n return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns\n else:\n return TFBaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n past_key_values=present_key_values,\n hidden_states=all_hidden_states,\n attentions=all_self_attns,\n cross_attentions=all_cross_attns,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n num_questions=3,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n question_token_id=1,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.num_questions = num_questions\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.question_token_id = question_token_id\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(ROBERTA_PRELAYERNORM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFCausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: Optional[bool] = False,\n ) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,\n config.vocab_size - 1]`.\n \"\"\"\n outputs = self.roberta_prelayernorm(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n sequence_output = outputs[0]\n logits = self.lm_head(hidden_states=sequence_output, training=training)\n loss = None\n\n if labels is not None:\n # shift labels to the left and cut last logit token\n shifted_logits = logits[:, :-1]\n labels = labels[:, 1:]\n loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFCausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def attributes_ids_exist_in_states(\n attr1: int,\n attr2: int | None,\n attr3: int | None,\n attr4: int | None,\n attr5: int | None,\n attr6: int | None,\n attr7: int | None,\n attr8: int | None,\n attr9: int | None,\n attr10: int | None,\n attr11: int | None,\n attr12: int | None,\n attr13: int | None,\n attr14: int | None,\n attr15: int | None,\n attr16: int | None,\n attr17: int | None,\n attr18: int | None,\n attr19: int | None,\n attr20: int | None,\n attr21: int | None,\n attr22: int | None,\n attr23: int | None,\n attr24: int | None,\n attr25: int | None,\n attr26: int | None,\n attr27: int | None,\n attr28: int | None,\n attr29: int | None,\n attr30: int | None,\n attr31: int | None,\n attr32: int | None,\n attr33: int | None,\n attr34: int | None,\n attr35: int | None,\n attr36: int | None,\n attr37: int | None,\n attr38: int | None,\n attr39: int | None,\n attr40: int | None,\n attr41: int | None,\n attr42: int | None,\n attr43: int | None,\n attr44: int | None,\n attr45: int | None,\n attr46: int | None,\n attr47: int | None,\n attr48: int | None,\n attr49: int | None,\n attr50: int | None,\n attr51: int | None,\n attr52: int | None,\n attr53: int | None,\n attr54: int | None,\n attr55: int | None,\n attr56: int | None,\n attr57: int | None,\n attr58: int | None,\n attr59: int | None,\n attr60: int | None,\n attr61: int | None,\n attr62: int | None,\n attr63: int | None,\n attr64: int | None,\n attr65: int | None,\n attr66: int | None,\n attr67: int | None,\n attr68: int | None,\n attr69: int | None,\n attr70: int | None,\n attr71: int | None,\n attr72: int | None,\n attr73: int | None,\n attr74: int | None,\n attr75: int | None,\n attr76: int | None,\n attr77: int | None,\n attr78: int | None,\n attr79: int | None,\n attr80: int | None,\n attr81: int | None,\n attr82: int | None,\n attr83: int | None,\n attr84: int | None,\n attr85: int | None,\n attr86: int | None,\n attr87: int | None,\n attr88: int | None,\n attr89: int | None,\n attr90: int | None,\n attr91: int | None,\n attr92: int | None,\n attr93: int | None,\n attr94: int | None,\n attr95: int | None,\n attr96: int | None,\n attr97: int | None,\n attr98: int | None,\n attr99: int | None,\n attr100: int | None,\n) -> StatementLambdaElement:\n \"\"\"Generate the find attributes select only once.\n\n https://docs.sqlalchemy.org/en/14/core/connections.html#quick-guidelines-for-lambdas\n \"\"\"\n return lambda_stmt(\n lambda: union_all(\n _state_attrs_exist(attr1),\n _state_attrs_exist(attr2),\n _state_attrs_exist(attr3),\n _state_attrs_exist(attr4),\n _state_attrs_exist(attr5),\n _state_attrs_exist(attr6),\n _state_attrs_exist(attr7),\n _state_attrs_exist(attr8),\n _state_attrs_exist(attr9),\n _state_attrs_exist(attr10),\n _state_attrs_exist(attr11),\n _state_attrs_exist(attr12),\n _state_attrs_exist(attr13),\n _state_attrs_exist(attr14),\n _state_attrs_exist(attr15),\n _state_attrs_exist(attr16),\n _state_attrs_exist(attr17),\n _state_attrs_exist(attr18),\n _state_attrs_exist(attr19),\n _state_attrs_exist(attr20),\n _state_attrs_exist(attr21),\n _state_attrs_exist(attr22),\n _state_attrs_exist(attr23),\n _state_attrs_exist(attr24),\n _state_attrs_exist(attr25),\n _state_attrs_exist(attr26),\n _state_attrs_exist(attr27),\n _state_attrs_exist(attr28),\n _state_attrs_exist(attr29),\n _state_attrs_exist(attr30),\n _state_attrs_exist(attr31),\n _state_attrs_exist(attr32),\n _state_attrs_exist(attr33),\n _state_attrs_exist(attr34),\n _state_attrs_exist(attr35),\n _state_attrs_exist(attr36),\n _state_attrs_exist(attr37),\n _state_attrs_exist(attr38),\n _state_attrs_exist(attr39),\n _state_attrs_exist(attr40),\n _state_attrs_exist(attr41),\n _state_attrs_exist(attr42),\n _state_attrs_exist(attr43),\n _state_attrs_exist(attr44),\n _state_attrs_exist(attr45),\n _state_attrs_exist(attr46),\n _state_attrs_exist(attr47),\n _state_attrs_exist(attr48),\n _state_attrs_exist(attr49),\n _state_attrs_exist(attr50),\n _state_attrs_exist(attr51),\n _state_attrs_exist(attr52),\n _state_attrs_exist(attr53),\n _state_attrs_exist(attr54),\n _state_attrs_exist(attr55),\n _state_attrs_exist(attr56),\n _state_attrs_exist(attr57),\n _state_attrs_exist(attr58),\n _state_attrs_exist(attr59),\n _state_attrs_exist(attr60),\n _state_attrs_exist(attr61),\n _state_attrs_exist(attr62),\n _state_attrs_exist(attr63),\n _state_attrs_exist(attr64),\n _state_attrs_exist(attr65),\n _state_attrs_exist(attr66),\n _state_attrs_exist(attr67),\n _state_attrs_exist(attr68),\n _state_attrs_exist(attr69),\n _state_attrs_exist(attr70),\n _state_attrs_exist(attr71),\n _state_attrs_exist(attr72),\n _state_attrs_exist(attr73),\n _state_attrs_exist(attr74),\n _state_attrs_exist(attr75),\n _state_attrs_exist(attr76),\n _state_attrs_exist(attr77),\n _state_attrs_exist(attr78),\n _state_attrs_exist(attr79),\n _state_attrs_exist(attr80),\n _state_attrs_exist(attr81),\n _state_attrs_exist(attr82),\n _state_attrs_exist(attr83),\n _state_attrs_exist(attr84),\n _state_attrs_exist(attr85),\n _state_attrs_exist(attr86),\n _state_attrs_exist(attr87),\n _state_attrs_exist(attr88),\n _state_attrs_exist(attr89),\n _state_attrs_exist(attr90),\n _state_attrs_exist(attr91),\n _state_attrs_exist(attr92),\n _state_attrs_exist(attr93),\n _state_attrs_exist(attr94),\n _state_attrs_exist(attr95),\n _state_attrs_exist(attr96),\n _state_attrs_exist(attr97),\n _state_attrs_exist(attr98),\n _state_attrs_exist(attr99),\n _state_attrs_exist(attr100),\n )\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def get_data(\n self,\n model,\n keys,\n start,\n end,\n rollup=None,\n environment_ids=None,\n aggregation=\"count()\",\n group_on_model=True,\n group_on_time=False,\n conditions=None,\n use_cache=False,\n jitter_value=None,\n tenant_ids: dict[str, str | int] | None = None,\n referrer_suffix: str | None = None,\n ):\n if model in self.non_outcomes_snql_query_settings:\n # no way around having to explicitly map legacy condition format to SnQL since this function\n # is used everywhere that expects `conditions` to be legacy format\n parsed_conditions = []\n for cond in conditions or ():\n if not is_condition(cond):\n or_conditions = []\n for or_cond in cond:\n or_conditions.append(parse_condition(or_cond))\n\n if len(or_conditions) > 1:\n parsed_conditions.append(Or(or_conditions))\n else:\n parsed_conditions.extend(or_conditions)\n else:\n parsed_conditions.append(parse_condition(cond))\n\n return self.__get_data_snql(\n model,\n keys,\n start,\n end,\n rollup,\n environment_ids,\n \"count\" if aggregation == \"count()\" else aggregation,\n group_on_model,\n group_on_time,\n parsed_conditions,\n use_cache,\n jitter_value,\n manual_group_on_time=(\n model in (TSDBModel.group_generic, TSDBModel.users_affected_by_generic_group)\n ),\n is_grouprelease=(model == TSDBModel.frequent_releases_by_group),\n tenant_ids=tenant_ids,\n referrer_suffix=referrer_suffix,\n )\n else:\n return self.__get_data_legacy(\n model,\n keys,\n start,\n end,\n rollup,\n environment_ids,\n aggregation,\n group_on_model,\n group_on_time,\n conditions,\n use_cache,\n jitter_value,\n tenant_ids,\n referrer_suffix,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=XLNetForSequenceClassificationOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n mems: Optional[torch.Tensor] = None,\n perm_mask: Optional[torch.Tensor] = None,\n target_mapping: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n input_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n use_mems: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n **kwargs, # delete when `use_cache` is removed in XLNetModel\n ) -> Union[Tuple, XLNetForSequenceClassificationOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n mems=mems,\n perm_mask=perm_mask,\n target_mapping=target_mapping,\n token_type_ids=token_type_ids,\n input_mask=input_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_mems=use_mems,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n **kwargs,\n )\n output = transformer_outputs[0]\n\n output = self.sequence_summary(output)\n logits = self.logits_proj(output)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return XLNetForSequenceClassificationOutput(\n loss=loss,\n logits=logits,\n mems=transformer_outputs.mems,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n relative_attention=False,\n position_biased_input=True,\n pos_att_type=\"None\",\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.relative_attention = relative_attention\n self.position_biased_input = position_biased_input\n self.pos_att_type = pos_att_type\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_chart_releases_v3_get_without_preload_content(\n self,\n app_version_branch: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to the app's mainline branch if no other app version info is present\")] = None,\n app_version_commit: Optional[StrictStr] = None,\n app_version_exact: Optional[StrictStr] = None,\n app_version_follow_chart_release: Optional[StrictStr] = None,\n app_version_reference: Optional[StrictStr] = None,\n app_version_resolver: Annotated[Optional[StrictStr], Field(description=\"// When creating, will default to automatically reference any provided app version fields\")] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n chart_version_exact: Optional[StrictStr] = None,\n chart_version_follow_chart_release: Optional[StrictStr] = None,\n chart_version_reference: Optional[StrictStr] = None,\n chart_version_resolver: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to automatically reference any provided chart version\")] = None,\n cluster: Annotated[Optional[StrictStr], Field(description=\"When creating, will default the environment's default cluster, if provided. Either this or environment must be provided.\")] = None,\n created_at: Optional[datetime] = None,\n destination_type: Annotated[Optional[StrictStr], Field(description=\"Calculated field\")] = None,\n environment: Annotated[Optional[StrictStr], Field(description=\"Either this or cluster must be provided.\")] = None,\n helmfile_ref: Optional[StrictStr] = None,\n helmfile_ref_enabled: Optional[StrictBool] = None,\n id: Optional[StrictInt] = None,\n included_in_bulk_changesets: Optional[StrictBool] = None,\n name: Annotated[Optional[StrictStr], Field(description=\"When creating, will be calculated if left empty\")] = None,\n namespace: Annotated[Optional[StrictStr], Field(description=\"When creating, will default to the environment's default namespace, if provided\")] = None,\n pagerduty_integration: Optional[StrictStr] = None,\n port: Annotated[Optional[StrictInt], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n protocol: Annotated[Optional[StrictStr], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n resolved_at: Optional[datetime] = None,\n subdomain: Annotated[Optional[StrictStr], Field(description=\"When creating, will use the chart's default if left empty\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many ChartReleases are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned ChartReleases (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> RESTResponseType:\n \"\"\"List ChartReleases matching a filter\n\n List ChartReleases matching a filter.\n\n :param app_version_branch: When creating, will default to the app's mainline branch if no other app version info is present\n :type app_version_branch: str\n :param app_version_commit:\n :type app_version_commit: str\n :param app_version_exact:\n :type app_version_exact: str\n :param app_version_follow_chart_release:\n :type app_version_follow_chart_release: str\n :param app_version_reference:\n :type app_version_reference: str\n :param app_version_resolver: // When creating, will default to automatically reference any provided app version fields\n :type app_version_resolver: str\n :param chart: Required when creating\n :type chart: str\n :param chart_version_exact:\n :type chart_version_exact: str\n :param chart_version_follow_chart_release:\n :type chart_version_follow_chart_release: str\n :param chart_version_reference:\n :type chart_version_reference: str\n :param chart_version_resolver: When creating, will default to automatically reference any provided chart version\n :type chart_version_resolver: str\n :param cluster: When creating, will default the environment's default cluster, if provided. Either this or environment must be provided.\n :type cluster: str\n :param created_at:\n :type created_at: datetime\n :param destination_type: Calculated field\n :type destination_type: str\n :param environment: Either this or cluster must be provided.\n :type environment: str\n :param helmfile_ref:\n :type helmfile_ref: str\n :param helmfile_ref_enabled:\n :type helmfile_ref_enabled: bool\n :param id:\n :type id: int\n :param included_in_bulk_changesets:\n :type included_in_bulk_changesets: bool\n :param name: When creating, will be calculated if left empty\n :type name: str\n :param namespace: When creating, will default to the environment's default namespace, if provided\n :type namespace: str\n :param pagerduty_integration:\n :type pagerduty_integration: str\n :param port: When creating, will use the chart's default if left empty\n :type port: int\n :param protocol: When creating, will use the chart's default if left empty\n :type protocol: str\n :param resolved_at:\n :type resolved_at: datetime\n :param subdomain: When creating, will use the chart's default if left empty\n :type subdomain: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many ChartReleases are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned ChartReleases (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_chart_releases_v3_get_serialize(\n app_version_branch=app_version_branch,\n app_version_commit=app_version_commit,\n app_version_exact=app_version_exact,\n app_version_follow_chart_release=app_version_follow_chart_release,\n app_version_reference=app_version_reference,\n app_version_resolver=app_version_resolver,\n chart=chart,\n chart_version_exact=chart_version_exact,\n chart_version_follow_chart_release=chart_version_follow_chart_release,\n chart_version_reference=chart_version_reference,\n chart_version_resolver=chart_version_resolver,\n cluster=cluster,\n created_at=created_at,\n destination_type=destination_type,\n environment=environment,\n helmfile_ref=helmfile_ref,\n helmfile_ref_enabled=helmfile_ref_enabled,\n id=id,\n included_in_bulk_changesets=included_in_bulk_changesets,\n name=name,\n namespace=namespace,\n pagerduty_integration=pagerduty_integration,\n port=port,\n protocol=protocol,\n resolved_at=resolved_at,\n subdomain=subdomain,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartReleaseV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n return response_data.response", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n min_seq_length=400,\n max_seq_length=2000,\n feature_size=1,\n sampling_rate=24000,\n padding_value=0.0,\n do_normalize=True,\n num_mel_bins=100,\n hop_length=256,\n win_length=1024,\n win_function=\"hann_window\",\n filter_length=1024,\n max_length_s=10,\n fmin=0.0,\n fmax=12000,\n mel_floor=1e-9,\n center=False,\n compression_factor=1.0,\n compression_clip_val=1e-5,\n normalize_min=-11.512925148010254,\n normalize_max=2.3143386840820312,\n model_in_channels=64,\n pad_end_length=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.min_seq_length = min_seq_length\n self.max_seq_length = max_seq_length\n self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)\n\n self.feature_size = feature_size\n self.sampling_rate = sampling_rate\n self.padding_value = padding_value\n self.do_normalize = do_normalize\n self.num_mel_bins = num_mel_bins\n self.hop_length = hop_length\n self.win_length = win_length\n self.win_function = win_function\n self.filter_length = filter_length\n self.max_length_s = max_length_s\n self.fmin = fmin\n self.fmax = fmax\n self.mel_floor = mel_floor\n self.center = center\n self.compression_factor = compression_factor\n self.compression_clip_val = compression_clip_val\n self.normalize_min = normalize_min\n self.normalize_max = normalize_max\n self.model_in_channels = model_in_channels\n self.pad_end_length = pad_end_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50358,\n hidden_size=1024,\n num_hidden_layers=24,\n num_attention_heads=16,\n intermediate_size=4096,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n bos_token_id=2,\n eos_token_id=1,\n position_embedding_type=\"absolute\",\n use_cache=True,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n config: CvtConfig,\n num_heads: int,\n embed_dim: int,\n kernel_size: int,\n stride_q: int,\n stride_kv: int,\n padding_q: int,\n padding_kv: int,\n qkv_projection_method: str,\n qkv_bias: bool,\n attention_drop_rate: float,\n drop_rate: float,\n mlp_ratio: float,\n drop_path_rate: float,\n with_cls_token: bool = True,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.attention = TFCvtAttention(\n config,\n num_heads,\n embed_dim,\n kernel_size,\n stride_q,\n stride_kv,\n padding_q,\n padding_kv,\n qkv_projection_method,\n qkv_bias,\n attention_drop_rate,\n drop_rate,\n with_cls_token,\n name=\"attention\",\n )\n self.intermediate = TFCvtIntermediate(config, embed_dim, mlp_ratio, name=\"intermediate\")\n self.dense_output = TFCvtOutput(config, embed_dim, mlp_ratio, drop_rate, name=\"output\")\n # Using `layers.Activation` instead of `tf.identity` to better control `training` behaviour.\n self.drop_path = (\n TFCvtDropPath(drop_path_rate, name=\"drop_path\")\n if drop_path_rate > 0.0\n else keras.layers.Activation(\"linear\", name=\"drop_path\")\n )\n # Using the same default epsilon as PyTorch\n self.layernorm_before = keras.layers.LayerNormalization(epsilon=1e-5, name=\"layernorm_before\")\n self.layernorm_after = keras.layers.LayerNormalization(epsilon=1e-5, name=\"layernorm_after\")\n self.embed_dim = embed_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(MARIAN_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Union[Tuple[torch.Tensor], BaseModelOutput]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Seq2SeqLMOutput:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if use_cache:\n logger.warning(\"The `use_cache` argument is changed to `False` since `labels` is provided.\")\n use_cache = False\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.decoder_vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n activation_dropout: Optional[float] = 0.1,\n activation_function: Optional[Union[str, Callable]] = \"gelu\",\n vocab_size: Optional[int] = 30522,\n hidden_size: Optional[int] = 1024,\n encoder_ffn_dim: Optional[int] = 4096,\n num_encoder_layers: Optional[int] = 12,\n num_encoder_attention_heads: Optional[int] = 16,\n decoder_ffn_dim: Optional[int] = 4096,\n num_decoder_layers: Optional[int] = 12,\n num_decoder_attention_heads: Optional[int] = 16,\n attention_dropout: Optional[float] = 0.1,\n dropout: Optional[float] = 0.1,\n max_position_embeddings: Optional[int] = 512,\n init_std: Optional[float] = 0.02,\n is_encoder_decoder: Optional[bool] = True,\n add_cross_attention: Optional[bool] = True,\n decoder_start_token_id: Optional[int] = 0,\n ngram: Optional[int] = 2,\n num_buckets: Optional[int] = 32,\n relative_max_distance: Optional[int] = 128,\n disable_ngram_loss: Optional[bool] = False,\n eps: Optional[float] = 0.0,\n use_cache: Optional[bool] = True,\n pad_token_id: Optional[int] = 0,\n bos_token_id: Optional[int] = 1,\n eos_token_id: Optional[int] = 2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.encoder_ffn_dim = encoder_ffn_dim\n self.num_encoder_layers = num_encoder_layers\n self.num_encoder_attention_heads = num_encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.num_decoder_layers = num_decoder_layers\n self.num_decoder_attention_heads = num_decoder_attention_heads\n self.max_position_embeddings = max_position_embeddings\n self.init_std = init_std # Normal(0, this parameter)\n self.activation_function = activation_function\n\n # parameters for prophetnet\n self.ngram = ngram\n self.num_buckets = num_buckets\n self.relative_max_distance = relative_max_distance\n self.disable_ngram_loss = disable_ngram_loss\n self.eps = eps\n\n # 3 Types of Dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.dropout = dropout\n\n self.use_cache = use_cache\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n add_cross_attention=add_cross_attention,\n decoder_start_token_id=decoder_start_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n range_bbox=1000,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.range_bbox = range_bbox", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def prepare_for_model(\n self,\n raw_table: \"pd.DataFrame\",\n raw_query: Union[\n TextInput,\n PreTokenizedInput,\n EncodedInput,\n ],\n tokenized_table: Optional[TokenizedTable] = None,\n query_tokens: Optional[TokenizedTable] = None,\n answer_coordinates: Optional[List[Tuple]] = None,\n answer_text: Optional[List[TextInput]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TapasTruncationStrategy] = False,\n max_length: Optional[int] = None,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = True,\n return_attention_mask: Optional[bool] = True,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n prepend_batch_axis: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates\n sequences if overflowing while taking into account the special tokens.\n\n Args:\n raw_table (`pd.DataFrame`):\n The original table before any transformation (like tokenization) was applied to it.\n raw_query (`TextInput` or `PreTokenizedInput` or `EncodedInput`):\n The original query before any transformation (like tokenization) was applied to it.\n tokenized_table (`TokenizedTable`):\n The table after tokenization.\n query_tokens (`List[str]`):\n The query after tokenization.\n answer_coordinates (`List[Tuple]` or `List[List[Tuple]]`, *optional*):\n Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single\n list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row\n (not the column header row) has index 0. The first column has index 0.\n answer_text (`List[str]` or `List[List[str]]`, *optional*):\n Answer text of each table-question pair in the batch. The answer_text must be a single list of one or\n more strings. Each string must be the answer text of a corresponding answer coordinate.\n \"\"\"\n if isinstance(padding, bool):\n if padding and (max_length is not None or pad_to_multiple_of is not None):\n padding = PaddingStrategy.MAX_LENGTH\n else:\n padding = PaddingStrategy.DO_NOT_PAD\n elif not isinstance(padding, PaddingStrategy):\n padding = PaddingStrategy(padding)\n\n if isinstance(truncation, bool):\n if truncation:\n truncation = TapasTruncationStrategy.DROP_ROWS_TO_FIT\n else:\n truncation = TapasTruncationStrategy.DO_NOT_TRUNCATE\n elif not isinstance(truncation, TapasTruncationStrategy):\n truncation = TapasTruncationStrategy(truncation)\n\n encoded_inputs = {}\n\n is_part_of_batch = False\n prev_answer_coordinates, prev_answer_text = None, None\n if \"prev_answer_coordinates\" in kwargs and \"prev_answer_text\" in kwargs:\n is_part_of_batch = True\n prev_answer_coordinates = kwargs[\"prev_answer_coordinates\"]\n prev_answer_text = kwargs[\"prev_answer_text\"]\n\n num_rows = self._get_num_rows(raw_table, truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE)\n num_columns = self._get_num_columns(raw_table)\n _, _, num_tokens = self._get_table_boundaries(tokenized_table)\n\n if truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE:\n num_rows, num_tokens = self._get_truncated_table_rows(\n query_tokens, tokenized_table, num_rows, num_columns, max_length, truncation_strategy=truncation\n )\n table_data = list(self._get_table_values(tokenized_table, num_columns, num_rows, num_tokens))\n\n query_ids = self.convert_tokens_to_ids(query_tokens)\n table_ids = list(zip(*table_data))[0] if len(table_data) > 0 else list(zip(*table_data))\n table_ids = self.convert_tokens_to_ids(list(table_ids))\n\n if \"return_overflowing_tokens\" in kwargs and kwargs[\"return_overflowing_tokens\"]:\n raise ValueError(\"TAPAS does not return overflowing tokens as it works on tables.\")\n\n if add_special_tokens:\n input_ids = self.build_inputs_with_special_tokens(query_ids, table_ids)\n else:\n input_ids = query_ids + table_ids\n\n if max_length is not None and len(input_ids) > max_length:\n raise ValueError(\n \"Could not encode the query and table header given the maximum length. Encoding the query and table \"\n f\"header results in a length of {len(input_ids)} which is higher than the max_length of {max_length}\"\n )\n\n encoded_inputs[\"input_ids\"] = input_ids\n\n segment_ids = self.create_segment_token_type_ids_from_sequences(query_ids, table_data)\n column_ids = self.create_column_token_type_ids_from_sequences(query_ids, table_data)\n row_ids = self.create_row_token_type_ids_from_sequences(query_ids, table_data)\n if not is_part_of_batch or (prev_answer_coordinates is None and prev_answer_text is None):\n # simply set the prev_labels to zeros\n prev_labels = [0] * len(row_ids)\n else:\n prev_labels = self.get_answer_ids(\n column_ids, row_ids, table_data, prev_answer_text, prev_answer_coordinates\n )\n\n # FIRST: parse both the table and question in terms of numeric values\n\n raw_table = add_numeric_table_values(raw_table)\n raw_query = add_numeric_values_to_question(raw_query)\n\n # SECOND: add numeric-related features (and not parse them in these functions):\n\n column_ranks, inv_column_ranks = self._get_numeric_column_ranks(column_ids, row_ids, raw_table)\n numeric_relations = self._get_numeric_relations(raw_query, column_ids, row_ids, raw_table)\n\n # Load from model defaults\n if return_token_type_ids is None:\n return_token_type_ids = \"token_type_ids\" in self.model_input_names\n if return_attention_mask is None:\n return_attention_mask = \"attention_mask\" in self.model_input_names\n\n if return_attention_mask:\n attention_mask = self.create_attention_mask_from_sequences(query_ids, table_data)\n encoded_inputs[\"attention_mask\"] = attention_mask\n\n if answer_coordinates is not None and answer_text is not None:\n labels = self.get_answer_ids(column_ids, row_ids, table_data, answer_text, answer_coordinates)\n numeric_values = self._get_numeric_values(raw_table, column_ids, row_ids)\n numeric_values_scale = self._get_numeric_values_scale(raw_table, column_ids, row_ids)\n\n encoded_inputs[\"labels\"] = labels\n encoded_inputs[\"numeric_values\"] = numeric_values\n encoded_inputs[\"numeric_values_scale\"] = numeric_values_scale\n\n if return_token_type_ids:\n token_type_ids = [\n segment_ids,\n column_ids,\n row_ids,\n prev_labels,\n column_ranks,\n inv_column_ranks,\n numeric_relations,\n ]\n\n token_type_ids = [list(ids) for ids in list(zip(*token_type_ids))]\n encoded_inputs[\"token_type_ids\"] = token_type_ids\n\n if return_special_tokens_mask:\n if add_special_tokens:\n encoded_inputs[\"special_tokens_mask\"] = self.get_special_tokens_mask(query_ids, table_ids)\n else:\n encoded_inputs[\"special_tokens_mask\"] = [0] * len(input_ids)\n\n # Check lengths\n if max_length is None and len(encoded_inputs[\"input_ids\"]) > self.model_max_length and verbose:\n if not self.deprecation_warnings.get(\"sequence-length-is-longer-than-the-specified-maximum\", False):\n logger.warning(\n \"Token indices sequence length is longer than the specified maximum sequence length \"\n f\"for this model ({len(encoded_inputs['input_ids'])} > {self.model_max_length}). Running this \"\n \"sequence through the model will result in indexing errors.\"\n )\n self.deprecation_warnings[\"sequence-length-is-longer-than-the-specified-maximum\"] = True\n\n # Padding\n if padding != PaddingStrategy.DO_NOT_PAD or return_attention_mask:\n encoded_inputs = self.pad(\n encoded_inputs,\n max_length=max_length,\n padding=padding.value,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_attention_mask=return_attention_mask,\n )\n\n if return_length:\n encoded_inputs[\"length\"] = len(encoded_inputs[\"input_ids\"])\n\n batch_outputs = BatchEncoding(\n encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis\n )\n\n return batch_outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def data_ids_exist_in_events(\n id1: int,\n id2: int | None,\n id3: int | None,\n id4: int | None,\n id5: int | None,\n id6: int | None,\n id7: int | None,\n id8: int | None,\n id9: int | None,\n id10: int | None,\n id11: int | None,\n id12: int | None,\n id13: int | None,\n id14: int | None,\n id15: int | None,\n id16: int | None,\n id17: int | None,\n id18: int | None,\n id19: int | None,\n id20: int | None,\n id21: int | None,\n id22: int | None,\n id23: int | None,\n id24: int | None,\n id25: int | None,\n id26: int | None,\n id27: int | None,\n id28: int | None,\n id29: int | None,\n id30: int | None,\n id31: int | None,\n id32: int | None,\n id33: int | None,\n id34: int | None,\n id35: int | None,\n id36: int | None,\n id37: int | None,\n id38: int | None,\n id39: int | None,\n id40: int | None,\n id41: int | None,\n id42: int | None,\n id43: int | None,\n id44: int | None,\n id45: int | None,\n id46: int | None,\n id47: int | None,\n id48: int | None,\n id49: int | None,\n id50: int | None,\n id51: int | None,\n id52: int | None,\n id53: int | None,\n id54: int | None,\n id55: int | None,\n id56: int | None,\n id57: int | None,\n id58: int | None,\n id59: int | None,\n id60: int | None,\n id61: int | None,\n id62: int | None,\n id63: int | None,\n id64: int | None,\n id65: int | None,\n id66: int | None,\n id67: int | None,\n id68: int | None,\n id69: int | None,\n id70: int | None,\n id71: int | None,\n id72: int | None,\n id73: int | None,\n id74: int | None,\n id75: int | None,\n id76: int | None,\n id77: int | None,\n id78: int | None,\n id79: int | None,\n id80: int | None,\n id81: int | None,\n id82: int | None,\n id83: int | None,\n id84: int | None,\n id85: int | None,\n id86: int | None,\n id87: int | None,\n id88: int | None,\n id89: int | None,\n id90: int | None,\n id91: int | None,\n id92: int | None,\n id93: int | None,\n id94: int | None,\n id95: int | None,\n id96: int | None,\n id97: int | None,\n id98: int | None,\n id99: int | None,\n id100: int | None,\n) -> StatementLambdaElement:\n \"\"\"Generate the find event data select only once.\n\n https://docs.sqlalchemy.org/en/14/core/connections.html#quick-guidelines-for-lambdas\n \"\"\"\n return lambda_stmt(\n lambda: union_all(\n _event_data_id_exist(id1),\n _event_data_id_exist(id2),\n _event_data_id_exist(id3),\n _event_data_id_exist(id4),\n _event_data_id_exist(id5),\n _event_data_id_exist(id6),\n _event_data_id_exist(id7),\n _event_data_id_exist(id8),\n _event_data_id_exist(id9),\n _event_data_id_exist(id10),\n _event_data_id_exist(id11),\n _event_data_id_exist(id12),\n _event_data_id_exist(id13),\n _event_data_id_exist(id14),\n _event_data_id_exist(id15),\n _event_data_id_exist(id16),\n _event_data_id_exist(id17),\n _event_data_id_exist(id18),\n _event_data_id_exist(id19),\n _event_data_id_exist(id20),\n _event_data_id_exist(id21),\n _event_data_id_exist(id22),\n _event_data_id_exist(id23),\n _event_data_id_exist(id24),\n _event_data_id_exist(id25),\n _event_data_id_exist(id26),\n _event_data_id_exist(id27),\n _event_data_id_exist(id28),\n _event_data_id_exist(id29),\n _event_data_id_exist(id30),\n _event_data_id_exist(id31),\n _event_data_id_exist(id32),\n _event_data_id_exist(id33),\n _event_data_id_exist(id34),\n _event_data_id_exist(id35),\n _event_data_id_exist(id36),\n _event_data_id_exist(id37),\n _event_data_id_exist(id38),\n _event_data_id_exist(id39),\n _event_data_id_exist(id40),\n _event_data_id_exist(id41),\n _event_data_id_exist(id42),\n _event_data_id_exist(id43),\n _event_data_id_exist(id44),\n _event_data_id_exist(id45),\n _event_data_id_exist(id46),\n _event_data_id_exist(id47),\n _event_data_id_exist(id48),\n _event_data_id_exist(id49),\n _event_data_id_exist(id50),\n _event_data_id_exist(id51),\n _event_data_id_exist(id52),\n _event_data_id_exist(id53),\n _event_data_id_exist(id54),\n _event_data_id_exist(id55),\n _event_data_id_exist(id56),\n _event_data_id_exist(id57),\n _event_data_id_exist(id58),\n _event_data_id_exist(id59),\n _event_data_id_exist(id60),\n _event_data_id_exist(id61),\n _event_data_id_exist(id62),\n _event_data_id_exist(id63),\n _event_data_id_exist(id64),\n _event_data_id_exist(id65),\n _event_data_id_exist(id66),\n _event_data_id_exist(id67),\n _event_data_id_exist(id68),\n _event_data_id_exist(id69),\n _event_data_id_exist(id70),\n _event_data_id_exist(id71),\n _event_data_id_exist(id72),\n _event_data_id_exist(id73),\n _event_data_id_exist(id74),\n _event_data_id_exist(id75),\n _event_data_id_exist(id76),\n _event_data_id_exist(id77),\n _event_data_id_exist(id78),\n _event_data_id_exist(id79),\n _event_data_id_exist(id80),\n _event_data_id_exist(id81),\n _event_data_id_exist(id82),\n _event_data_id_exist(id83),\n _event_data_id_exist(id84),\n _event_data_id_exist(id85),\n _event_data_id_exist(id86),\n _event_data_id_exist(id87),\n _event_data_id_exist(id88),\n _event_data_id_exist(id89),\n _event_data_id_exist(id90),\n _event_data_id_exist(id91),\n _event_data_id_exist(id92),\n _event_data_id_exist(id93),\n _event_data_id_exist(id94),\n _event_data_id_exist(id95),\n _event_data_id_exist(id96),\n _event_data_id_exist(id97),\n _event_data_id_exist(id98),\n _event_data_id_exist(id99),\n _event_data_id_exist(id100),\n )\n )", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n collection: Collection[_DocumentType],\n filter: Optional[Mapping[str, Any]] = None,\n projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None,\n skip: int = 0,\n limit: int = 0,\n no_cursor_timeout: bool = False,\n cursor_type: int = CursorType.NON_TAILABLE,\n sort: Optional[_Sort] = None,\n allow_partial_results: bool = False,\n oplog_replay: bool = False,\n batch_size: int = 0,\n collation: Optional[_CollationIn] = None,\n hint: Optional[_Hint] = None,\n max_scan: Optional[int] = None,\n max_time_ms: Optional[int] = None,\n max: Optional[_Sort] = None,\n min: Optional[_Sort] = None,\n return_key: Optional[bool] = None,\n show_record_id: Optional[bool] = None,\n snapshot: Optional[bool] = None,\n comment: Optional[Any] = None,\n session: Optional[ClientSession] = None,\n allow_disk_use: Optional[bool] = None,\n let: Optional[bool] = None,\n ) -> None:\n \"\"\"Create a new cursor.\n\n Should not be called directly by application developers - see\n :meth:`~pymongo.collection.Collection.find` instead.\n\n .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.\n \"\"\"\n # Initialize all attributes used in __del__ before possibly raising\n # an error to avoid attribute errors during garbage collection.\n self.__collection: Collection[_DocumentType] = collection\n self.__id: Any = None\n self.__exhaust = False\n self.__sock_mgr: Any = None\n self.__killed = False\n self.__session: Optional[ClientSession]\n\n if session:\n self.__session = session\n self.__explicit_session = True\n else:\n self.__session = None\n self.__explicit_session = False\n\n spec: Mapping[str, Any] = filter or {}\n validate_is_mapping(\"filter\", spec)\n if not isinstance(skip, int):\n raise TypeError(\"skip must be an instance of int\")\n if not isinstance(limit, int):\n raise TypeError(\"limit must be an instance of int\")\n validate_boolean(\"no_cursor_timeout\", no_cursor_timeout)\n if no_cursor_timeout and not self.__explicit_session:\n warnings.warn(\n \"use an explicit session with no_cursor_timeout=True \"\n \"otherwise the cursor may still timeout after \"\n \"30 minutes, for more info see \"\n \"https://mongodb.com/docs/v4.4/reference/method/\"\n \"cursor.noCursorTimeout/\"\n \"#session-idle-timeout-overrides-nocursortimeout\",\n UserWarning,\n stacklevel=2,\n )\n if cursor_type not in (\n CursorType.NON_TAILABLE,\n CursorType.TAILABLE,\n CursorType.TAILABLE_AWAIT,\n CursorType.EXHAUST,\n ):\n raise ValueError(\"not a valid value for cursor_type\")\n validate_boolean(\"allow_partial_results\", allow_partial_results)\n validate_boolean(\"oplog_replay\", oplog_replay)\n if not isinstance(batch_size, int):\n raise TypeError(\"batch_size must be an integer\")\n if batch_size < 0:\n raise ValueError(\"batch_size must be >= 0\")\n # Only set if allow_disk_use is provided by the user, else None.\n if allow_disk_use is not None:\n allow_disk_use = validate_boolean(\"allow_disk_use\", allow_disk_use)\n\n if projection is not None:\n projection = helpers._fields_list_to_dict(projection, \"projection\")\n\n if let is not None:\n validate_is_document_type(\"let\", let)\n\n self.__let = let\n self.__spec = spec\n self.__has_filter = filter is not None\n self.__projection = projection\n self.__skip = skip\n self.__limit = limit\n self.__batch_size = batch_size\n self.__ordering = sort and helpers._index_document(sort) or None\n self.__max_scan = max_scan\n self.__explain = False\n self.__comment = comment\n self.__max_time_ms = max_time_ms\n self.__max_await_time_ms: Optional[int] = None\n self.__max: Optional[Union[dict[Any, Any], _Sort]] = max\n self.__min: Optional[Union[dict[Any, Any], _Sort]] = min\n self.__collation = validate_collation_or_none(collation)\n self.__return_key = return_key\n self.__show_record_id = show_record_id\n self.__allow_disk_use = allow_disk_use\n self.__snapshot = snapshot\n self.__hint: Union[str, dict[str, Any], None]\n self.__set_hint(hint)\n\n # Exhaust cursor support\n if cursor_type == CursorType.EXHAUST:\n if self.__collection.database.client.is_mongos:\n raise InvalidOperation(\"Exhaust cursors are not supported by mongos\")\n if limit:\n raise InvalidOperation(\"Can't use limit and exhaust together.\")\n self.__exhaust = True\n\n # This is ugly. People want to be able to do cursor[5:5] and\n # get an empty result set (old behavior was an\n # exception). It's hard to do that right, though, because the\n # server uses limit(0) to mean 'no limit'. So we set __empty\n # in that case and check for it when iterating. We also unset\n # it anytime we change __limit.\n self.__empty = False\n\n self.__data: deque = deque()\n self.__address: Optional[_Address] = None\n self.__retrieved = 0\n\n self.__codec_options = collection.codec_options\n # Read preference is set when the initial find is sent.\n self.__read_preference: Optional[_ServerMode] = None\n self.__read_concern = collection.read_concern\n\n self.__query_flags = cursor_type\n if no_cursor_timeout:\n self.__query_flags |= _QUERY_OPTIONS[\"no_timeout\"]\n if allow_partial_results:\n self.__query_flags |= _QUERY_OPTIONS[\"partial\"]\n if oplog_replay:\n self.__query_flags |= _QUERY_OPTIONS[\"oplog_replay\"]\n\n # The namespace to use for find/getMore commands.\n self.__dbname = collection.database.name\n self.__collname = collection.name", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=8194,\n max_position_embeddings=608,\n max_text_tokens=404,\n hidden_size=1024,\n num_hidden_layers=30,\n num_attention_heads=16,\n n_inner=None,\n num_mel_attn_blocks=6,\n activation_function=\"gelu_new\",\n resid_pdrop=0.1,\n embd_pdrop=0.1,\n attention_dropout=0.1,\n layer_norm_epsilon=1e-5,\n initializer_range=0.02,\n summary_type=\"cls_index\",\n summary_use_proj=True,\n summary_activation=None,\n summary_proj_to_labels=True,\n summary_first_dropout=0.1,\n use_cache=True,\n bos_token_id=8192,\n eos_token_id=8193,\n feature_size=80,\n use_attention_bias=True,\n initializer_factor=1.0,\n decoder_fixing_codes=[83, 45, 45, 248],\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.max_text_tokens = max_text_tokens\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.n_inner = n_inner\n self.num_mel_attn_blocks = num_mel_attn_blocks\n self.activation_function = activation_function\n self.resid_pdrop = resid_pdrop\n self.embd_pdrop = embd_pdrop\n self.attention_dropout = attention_dropout\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.summary_type = summary_type\n self.summary_use_proj = summary_use_proj\n self.summary_activation = summary_activation\n self.summary_first_dropout = summary_first_dropout\n self.summary_proj_to_labels = summary_proj_to_labels\n self.use_cache = use_cache\n self.feature_size = feature_size\n self.use_attention_bias = use_attention_bias\n self.initializer_factor = initializer_factor\n self.decoder_fixing_codes = decoder_fixing_codes\n\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n num_heads=8,\n n_groups=8,\n state_size=2,\n head_dim=8,\n conv_kernel=4,\n chunk_size=8,\n seq_length=7,\n is_training=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n hidden_act=\"silu\",\n hidden_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n num_labels=3,\n num_choices=4,\n scope=None,\n tie_word_embeddings=False,\n ):\n self.parent = parent\n self.num_heads = num_heads\n self.n_groups = n_groups\n self.head_dim = head_dim\n self.state_size = state_size\n self.conv_kernel = conv_kernel\n self.chunk_size = chunk_size\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1\n self.tie_word_embeddings = tie_word_embeddings", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, T5Model\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google-t5/t5-small\")\n >>> model = T5Model.from_pretrained(\"google-t5/t5-small\")\n\n >>> input_ids = tokenizer(\n ... \"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> decoder_input_ids = tokenizer(\"Studies show that\", return_tensors=\"pt\").input_ids # Batch size 1\n\n >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.\n >>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.\n >>> decoder_input_ids = model._shift_right(decoder_input_ids)\n\n >>> # forward pass\n >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)\n >>> last_hidden_states = outputs.last_hidden_state\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n # Set device for model parallelism\n if self.model_parallel:\n torch.cuda.set_device(self.decoder.first_device)\n hidden_states = hidden_states.to(self.decoder.first_device)\n if decoder_input_ids is not None:\n decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)\n if attention_mask is not None:\n attention_mask = attention_mask.to(self.decoder.first_device)\n if decoder_attention_mask is not None:\n decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=1024,\n is_training=False,\n hidden_size=16,\n feat_extract_norm=\"group\",\n feat_extract_dropout=0.0,\n feat_extract_activation=\"gelu\",\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n num_hidden_layers=2,\n num_attention_heads=2,\n hidden_dropout_prob=0.1, # this is most likely not correctly set yet\n intermediate_size=20,\n layer_norm_eps=1e-5,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n vocab_size=32,\n do_stable_layer_norm=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_dropout = feat_extract_dropout\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.intermediate_size = intermediate_size\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.scope = scope\n\n output_seq_length = self.seq_length\n for kernel, stride in zip(self.conv_kernel, self.conv_stride):\n output_seq_length = (output_seq_length - (kernel - 1)) / stride\n self.output_seq_length = int(math.ceil(output_seq_length))\n self.encoder_seq_length = self.output_seq_length", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def run_simple(\n hostname: str,\n port: int,\n application: WSGIApplication,\n use_reloader: bool = False,\n use_debugger: bool = False,\n use_evalex: bool = True,\n extra_files: t.Iterable[str] | None = None,\n exclude_patterns: t.Iterable[str] | None = None,\n reloader_interval: int = 1,\n reloader_type: str = \"auto\",\n threaded: bool = False,\n processes: int = 1,\n request_handler: type[WSGIRequestHandler] | None = None,\n static_files: dict[str, str | tuple[str, str]] | None = None,\n passthrough_errors: bool = False,\n ssl_context: _TSSLContextArg | None = None,\n) -> None:\n \"\"\"Start a development server for a WSGI application. Various\n optional features can be enabled.\n\n .. warning::\n\n Do not use the development server when deploying to production.\n It is intended for use only during local development. It is not\n designed to be particularly efficient, stable, or secure.\n\n :param hostname: The host to bind to, for example ``'localhost'``.\n Can be a domain, IPv4 or IPv6 address, or file path starting\n with ``unix://`` for a Unix socket.\n :param port: The port to bind to, for example ``8080``. Using ``0``\n tells the OS to pick a random free port.\n :param application: The WSGI application to run.\n :param use_reloader: Use a reloader process to restart the server\n process when files are changed.\n :param use_debugger: Use Werkzeug's debugger, which will show\n formatted tracebacks on unhandled exceptions.\n :param use_evalex: Make the debugger interactive. A Python terminal\n can be opened for any frame in the traceback. Some protection is\n provided by requiring a PIN, but this should never be enabled\n on a publicly visible server.\n :param extra_files: The reloader will watch these files for changes\n in addition to Python modules. For example, watch a\n configuration file.\n :param exclude_patterns: The reloader will ignore changes to any\n files matching these :mod:`fnmatch` patterns. For example,\n ignore cache files.\n :param reloader_interval: How often the reloader tries to check for\n changes.\n :param reloader_type: The reloader to use. The ``'stat'`` reloader\n is built in, but may require significant CPU to watch files. The\n ``'watchdog'`` reloader is much more efficient but requires\n installing the ``watchdog`` package first.\n :param threaded: Handle concurrent requests using threads. Cannot be\n used with ``processes``.\n :param processes: Handle concurrent requests using up to this number\n of processes. Cannot be used with ``threaded``.\n :param request_handler: Use a different\n :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass to\n handle requests.\n :param static_files: A dict mapping URL prefixes to directories to\n serve static files from using\n :class:`~werkzeug.middleware.SharedDataMiddleware`.\n :param passthrough_errors: Don't catch unhandled exceptions at the\n server level, let the server crash instead. If ``use_debugger``\n is enabled, the debugger will still catch such errors.\n :param ssl_context: Configure TLS to serve over HTTPS. Can be an\n :class:`ssl.SSLContext` object, a ``(cert_file, key_file)``\n tuple to create a typical context, or the string ``'adhoc'`` to\n generate a temporary self-signed certificate.\n\n .. versionchanged:: 2.1\n Instructions are shown for dealing with an \"address already in\n use\" error.\n\n .. versionchanged:: 2.1\n Running on ``0.0.0.0`` or ``::`` shows the loopback IP in\n addition to a real IP.\n\n .. versionchanged:: 2.1\n The command-line interface was removed.\n\n .. versionchanged:: 2.0\n Running on ``0.0.0.0`` or ``::`` shows a real IP address that\n was bound as well as a warning not to run the development server\n in production.\n\n .. versionchanged:: 2.0\n The ``exclude_patterns`` parameter was added.\n\n .. versionchanged:: 0.15\n Bind to a Unix socket by passing a ``hostname`` that starts with\n ``unix://``.\n\n .. versionchanged:: 0.10\n Improved the reloader and added support for changing the backend\n through the ``reloader_type`` parameter.\n\n .. versionchanged:: 0.9\n A command-line interface was added.\n\n .. versionchanged:: 0.8\n ``ssl_context`` can be a tuple of paths to the certificate and\n private key files.\n\n .. versionchanged:: 0.6\n The ``ssl_context`` parameter was added.\n\n .. versionchanged:: 0.5\n The ``static_files`` and ``passthrough_errors`` parameters were\n added.\n \"\"\"\n if not isinstance(port, int):\n raise TypeError(\"port must be an integer\")\n\n if static_files:\n from .middleware.shared_data import SharedDataMiddleware\n\n application = SharedDataMiddleware(application, static_files)\n\n if use_debugger:\n from .debug import DebuggedApplication\n\n application = DebuggedApplication(application, evalex=use_evalex)\n\n if not is_running_from_reloader():\n fd = None\n else:\n fd = int(os.environ[\"WERKZEUG_SERVER_FD\"])\n\n srv = make_server(\n hostname,\n port,\n application,\n threaded,\n processes,\n request_handler,\n passthrough_errors,\n ssl_context,\n fd=fd,\n )\n srv.socket.set_inheritable(True)\n os.environ[\"WERKZEUG_SERVER_FD\"] = str(srv.fileno())\n\n if not is_running_from_reloader():\n srv.log_startup()\n _log(\"info\", _ansi_style(\"Press CTRL+C to quit\", \"yellow\"))\n\n if use_reloader:\n from ._reloader import run_with_reloader\n\n try:\n run_with_reloader(\n srv.serve_forever,\n extra_files=extra_files,\n exclude_patterns=exclude_patterns,\n interval=reloader_interval,\n reloader_type=reloader_type,\n )\n finally:\n srv.server_close()\n else:\n srv.serve_forever()", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=XLNetForTokenClassificationOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n mems: Optional[torch.Tensor] = None,\n perm_mask: Optional[torch.Tensor] = None,\n target_mapping: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n input_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n use_mems: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n **kwargs, # delete when `use_cache` is removed in XLNetModel\n ) -> Union[Tuple, XLNetForTokenClassificationOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`\n where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n mems=mems,\n perm_mask=perm_mask,\n target_mapping=target_mapping,\n token_type_ids=token_type_ids,\n input_mask=input_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_mems=use_mems,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return XLNetForTokenClassificationOutput(\n loss=loss,\n logits=logits,\n mems=outputs.mems,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@classmethod\n def _handle_workers(cls, cache, taskqueue, ctx, Process, processes,\n pool, inqueue, outqueue, initializer, initargs,\n maxtasksperchild, wrap_exception, sentinels,\n change_notifier):\n thread = threading.current_thread()\n\n # Keep maintaining workers until the cache gets drained, unless the pool\n # is terminated.\n while thread._state == RUN or (cache and thread._state != TERMINATE):\n cls._maintain_pool(ctx, Process, processes, pool, inqueue,\n outqueue, initializer, initargs,\n maxtasksperchild, wrap_exception)\n\n current_sentinels = [*cls._get_worker_sentinels(pool), *sentinels]\n\n cls._wait_for_updates(current_sentinels, change_notifier)\n # send sentinel to stop workers\n taskqueue.put(None)\n util.debug('worker handler exiting')", "smellKey": "S107", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=32,\n is_training=True,\n is_decoder=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=32,\n attention_head_size=16,\n hidden_size=32,\n num_attention_heads=2,\n local_attn_chunk_length=4,\n local_num_chunks_before=1,\n local_num_chunks_after=0,\n num_buckets=None,\n num_hashes=1,\n lsh_attn_chunk_length=None,\n lsh_num_chunks_before=None,\n lsh_num_chunks_after=None,\n chunk_size_lm_head=0,\n chunk_size_feed_forward=0,\n feed_forward_size=32,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n local_attention_probs_dropout_prob=0.1,\n lsh_attention_probs_dropout_prob=None,\n max_position_embeddings=512,\n initializer_range=0.02,\n axial_norm_std=1.0,\n layer_norm_eps=1e-12,\n axial_pos_embds=True,\n axial_pos_shape=[4, 8],\n axial_pos_embds_dim=[16, 16],\n attn_layers=[\"local\", \"local\", \"local\", \"local\"],\n pad_token_id=0,\n eos_token_id=2,\n scope=None,\n hash_seed=0,\n num_labels=2,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.is_decoder = is_decoder\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.attention_head_size = attention_head_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_hidden_layers = len(attn_layers) if attn_layers is not None else 0\n self.local_attn_chunk_length = local_attn_chunk_length\n self.local_num_chunks_after = local_num_chunks_after\n self.local_num_chunks_before = local_num_chunks_before\n self.num_hashes = num_hashes\n self.num_buckets = tuple(num_buckets) if isinstance(num_buckets, list) else num_buckets\n self.lsh_attn_chunk_length = lsh_attn_chunk_length\n self.lsh_num_chunks_after = lsh_num_chunks_after\n self.lsh_num_chunks_before = lsh_num_chunks_before\n self.hidden_act = hidden_act\n self.feed_forward_size = feed_forward_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.local_attention_probs_dropout_prob = local_attention_probs_dropout_prob\n self.lsh_attention_probs_dropout_prob = lsh_attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.axial_pos_embds = axial_pos_embds\n self.axial_pos_shape = tuple(axial_pos_shape)\n self.axial_pos_embds_dim = tuple(axial_pos_embds_dim)\n self.axial_norm_std = axial_norm_std\n self.chunk_size_lm_head = chunk_size_lm_head\n self.chunk_size_feed_forward = chunk_size_feed_forward\n self.scope = scope\n self.attn_layers = attn_layers\n self.pad_token_id = pad_token_id\n self.hash_seed = hash_seed\n\n attn_chunk_length = local_attn_chunk_length if local_attn_chunk_length is not None else lsh_attn_chunk_length\n num_chunks_after = local_num_chunks_after if local_num_chunks_after is not None else lsh_num_chunks_after\n num_chunks_before = local_num_chunks_before if local_num_chunks_before is not None else lsh_num_chunks_before\n\n self.encoder_seq_length = seq_length // attn_chunk_length + (self.seq_length % attn_chunk_length != 0)\n self.key_length = (num_chunks_before + num_chunks_after + 1) * attn_chunk_length\n self.chunk_length = attn_chunk_length\n self.num_labels = num_labels", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @add_end_docstrings(M2M_100_GENERATION_EXAMPLE)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0])\n\n masked_lm_loss = None\n if labels is not None:\n # move labels to the correct device to enable PP\n labels = labels.to(lm_logits.device)\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LLAVA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=LlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n pixel_values: torch.FloatTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n vision_feature_layer: Optional[int] = None,\n vision_feature_select_strategy: Optional[str] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n cache_position: Optional[torch.LongTensor] = None,\n num_logits_to_keep: int = 0,\n ) -> Union[Tuple, LlavaCausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n num_logits_to_keep (`int`, *optional*):\n Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all\n `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that\n token can save memory, which becomes pretty significant for long sequences or large vocabulary size.\n\n\n Returns:\n\n Example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, LlavaForConditionalGeneration\n\n >>> model = LlavaForConditionalGeneration.from_pretrained(\"llava-hf/llava-1.5-7b-hf\")\n >>> processor = AutoProcessor.from_pretrained(\"llava-hf/llava-1.5-7b-hf\")\n\n >>> prompt = \"USER: <image>\\nWhat's the content of the image? ASSISTANT:\"\n >>> url = \"https://www.ilankelman.org/stopsigns/australia.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, text=prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(**inputs, max_new_tokens=15)\n >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"USER: \\nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n vision_feature_layer = (\n vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n )\n vision_feature_select_strategy = (\n vision_feature_select_strategy\n if vision_feature_select_strategy is not None\n else self.config.vision_feature_select_strategy\n )\n\n if (input_ids is None) ^ (inputs_embeds is not None):\n raise ValueError(\"You must specify exactly one of input_ids or inputs_embeds\")\n\n if pixel_values is not None and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one\"\n )\n\n legacy_processing = False\n if inputs_embeds is None:\n inputs_embeds = self.get_input_embeddings()(input_ids)\n\n # if the number of image tokens is more than image embeddings seq length, then prob we expanded it in processing\n # not very reliable, but we don't expect one to actually pass 500+ images for one prompt\n # In case we're in decoding stage, legacy behavior is checked by presence of pixel values even if use_cache=True\n legacy_processing = (\n (input_ids == self.config.image_token_index).sum(1).max() < self.config.image_seq_length\n ) or (input_ids.shape[-1] == 1 and pixel_values is not None)\n\n if pixel_values is not None:\n image_features = self.get_image_features(\n pixel_values=pixel_values,\n vision_feature_layer=vision_feature_layer,\n vision_feature_select_strategy=vision_feature_select_strategy,\n )\n\n if legacy_processing:\n logger.warning_once(\n \"Expanding inputs for image tokens in LLaVa should be done in processing. \"\n \"Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly \"\n \"with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. \"\n \"Using processors without these attributes in the config is deprecated and will throw an error in v4.47.\"\n )\n # prefill stage vs decoding stage (legacy behavior copied)\n if input_ids.shape[1] != 1:\n inputs_embeds, attention_mask, labels, position_ids = self._merge_input_ids_with_image_features(\n image_features, inputs_embeds, input_ids, attention_mask, labels\n )\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)\n else:\n # Retrieve the first layer to inspect the logits and mask out the hidden states\n # that are set to 0\n first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]\n\n # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941\n batch_index, non_attended_tokens = torch.where(first_layer_past_key_value.float().sum(-2) == 0)\n\n # Get the target length\n target_length = input_ids.shape[1]\n past_length = first_layer_past_key_value.shape[-1]\n\n extended_attention_mask = torch.ones(\n (attention_mask.shape[0], past_length),\n dtype=attention_mask.dtype,\n device=attention_mask.device,\n )\n\n # Filter out only the tokens that can be un-attended, this can happen\n # if one uses Llava + Fused modules where the cache on the\n # first iteration is already big enough, or if one passes custom cache\n valid_indices = non_attended_tokens < extended_attention_mask.size(-1)\n new_batch_index = batch_index[valid_indices]\n new_non_attended_tokens = non_attended_tokens[valid_indices]\n\n # Zero-out the places where we don't need to attend\n extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0\n\n attention_mask = torch.cat((extended_attention_mask, attention_mask[:, -target_length:]), dim=1)\n position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1\n cache_position = torch.arange(attention_mask.shape[1], device=attention_mask.device)[\n -target_length:\n ]\n\n # TODO: @raushan retain only the new behavior after v4.47\n else:\n special_image_mask = (\n (input_ids == self.config.image_token_index)\n .unsqueeze(-1)\n .expand_as(inputs_embeds)\n .to(inputs_embeds.device)\n )\n image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)\n inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)\n\n outputs = self.language_model(\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n cache_position=cache_position,\n num_logits_to_keep=num_logits_to_keep,\n )\n\n logits = outputs[0]\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n if attention_mask is not None:\n # we use the input attention mask to shift the logits and labels, because it is 2D.\n # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft\n shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)\n shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()\n shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()\n else:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(\n shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)\n )\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return LlavaCausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n image_hidden_states=image_features if pixel_values is not None else None,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout=0.1,\n activation_dropout=0.1,\n attention_dropout=0.1,\n feat_proj_dropout=0.0,\n final_dropout=0.1,\n layerdrop=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n feat_extract_norm=\"group\",\n feat_extract_activation=\"gelu\",\n conv_dim=(512, 512, 512, 512, 512, 512, 512),\n conv_stride=(5, 2, 2, 2, 2, 2, 2),\n conv_kernel=(10, 3, 3, 3, 3, 2, 2),\n conv_bias=False,\n num_conv_pos_embeddings=128,\n num_conv_pos_embedding_groups=16,\n num_buckets=320,\n max_bucket_distance=800,\n do_stable_layer_norm=False,\n apply_spec_augment=True,\n mask_time_prob=0.05,\n mask_time_length=10,\n mask_time_min_masks=2,\n mask_feature_prob=0.0,\n mask_feature_length=10,\n num_codevectors_per_group=320,\n num_codevector_groups=2,\n contrastive_logits_temperature=0.1,\n num_negatives=100,\n codevector_dim=256,\n proj_codevector_dim=256,\n diversity_loss_weight=0.1,\n ctc_loss_reduction=\"mean\",\n ctc_zero_infinity=False,\n use_weighted_layer_sum=False,\n classifier_proj_size=256,\n tdnn_dim=(512, 512, 512, 512, 1500),\n tdnn_kernel=(5, 3, 3, 1, 1),\n tdnn_dilation=(1, 2, 3, 1, 1),\n xvector_output_dim=512,\n num_ctc_classes=80,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n add_adapter=False,\n adapter_kernel_size=3,\n adapter_stride=2,\n num_adapter_layers=3,\n output_hidden_size=None,\n **kwargs,\n ):\n super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = list(conv_dim)\n self.conv_stride = list(conv_stride)\n self.conv_kernel = list(conv_kernel)\n self.conv_bias = conv_bias\n self.num_buckets = num_buckets\n self.max_bucket_distance = max_bucket_distance\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_feat_extract_layers = len(self.conv_dim)\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.feat_proj_dropout = feat_proj_dropout\n self.final_dropout = final_dropout\n self.layerdrop = layerdrop\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.num_ctc_classes = num_ctc_classes\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.use_weighted_layer_sum = use_weighted_layer_sum\n self.classifier_proj_size = classifier_proj_size\n\n if (\n (len(self.conv_stride) != self.num_feat_extract_layers)\n or (len(self.conv_kernel) != self.num_feat_extract_layers)\n or (len(self.conv_dim) != self.num_feat_extract_layers)\n ):\n raise ValueError(\n \"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==\"\n \" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =\"\n f\" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,\"\n f\" `len(config.conv_kernel) = {len(self.conv_kernel)}`.\"\n )\n\n # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779\n self.apply_spec_augment = apply_spec_augment\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.mask_time_min_masks = mask_time_min_masks\n self.mask_feature_prob = mask_feature_prob\n self.mask_feature_length = mask_feature_length\n\n # parameters for pretraining with codevector quantized representations\n self.num_codevectors_per_group = num_codevectors_per_group\n self.num_codevector_groups = num_codevector_groups\n self.contrastive_logits_temperature = contrastive_logits_temperature\n self.num_negatives = num_negatives\n self.codevector_dim = codevector_dim\n self.proj_codevector_dim = proj_codevector_dim\n self.diversity_loss_weight = diversity_loss_weight\n\n # ctc loss\n self.ctc_loss_reduction = ctc_loss_reduction\n self.ctc_zero_infinity = ctc_zero_infinity\n\n # adapter\n self.add_adapter = add_adapter\n self.adapter_kernel_size = adapter_kernel_size\n self.adapter_stride = adapter_stride\n self.num_adapter_layers = num_adapter_layers\n self.output_hidden_size = output_hidden_size or hidden_size\n\n # SequenceClassification-specific parameter. Feel free to ignore for other classes.\n self.classifier_proj_size = classifier_proj_size\n\n # XVector-specific parameters. Feel free to ignore for other classes.\n self.tdnn_dim = list(tdnn_dim)\n self.tdnn_kernel = list(tdnn_kernel)\n self.tdnn_dilation = list(tdnn_dilation)\n self.xvector_output_dim = xvector_output_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=RetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n context_input_ids: Optional[torch.LongTensor] = None,\n context_attention_mask: Optional[torch.LongTensor] = None,\n doc_scores: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_retrieved: Optional[bool] = None,\n do_marginalize: Optional[bool] = None,\n reduce_loss: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n n_docs: Optional[int] = None,\n **kwargs, # needs kwargs for generation\n ) -> RetrievAugLMMarginOutput:\n r\"\"\"\n do_marginalize (`bool`, *optional*):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*):\n Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`\n operation.\n kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):\n Legacy dictionary, which is required so that model can use *generate()* function.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RagRetriever, RagTokenForGeneration\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/rag-token-nq\")\n >>> retriever = RagRetriever.from_pretrained(\n ... \"facebook/rag-token-nq\", index_name=\"exact\", use_dummy_dataset=True\n ... )\n >>> # initialize with RagRetriever to do everything in one forward call\n >>> model = RagTokenForGeneration.from_pretrained(\"facebook/rag-token-nq\", retriever=retriever)\n\n >>> inputs = tokenizer(\"How many people live in Paris?\", return_tensors=\"pt\")\n >>> targets = tokenizer(text_target=\"In Paris, there are 10 million people.\", return_tensors=\"pt\")\n >>> input_ids = inputs[\"input_ids\"]\n >>> labels = targets[\"input_ids\"]\n >>> outputs = model(input_ids=input_ids, labels=labels)\n\n >>> # or use retriever separately\n >>> model = RagTokenForGeneration.from_pretrained(\"facebook/rag-token-nq\", use_dummy_dataset=True)\n >>> # 1. Encode\n >>> question_hidden_states = model.question_encoder(input_ids)[0]\n >>> # 2. Retrieve\n >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors=\"pt\")\n >>> doc_scores = torch.bmm(\n ... question_hidden_states.unsqueeze(1), docs_dict[\"retrieved_doc_embeds\"].float().transpose(1, 2)\n ... ).squeeze(1)\n >>> # 3. Forward to generator\n >>> outputs = model(\n ... context_input_ids=docs_dict[\"context_input_ids\"],\n ... context_attention_mask=docs_dict[\"context_attention_mask\"],\n ... doc_scores=doc_scores,\n ... decoder_input_ids=labels,\n ... )\n\n >>> # or directly generate\n >>> generated = model.generate(\n ... context_input_ids=docs_dict[\"context_input_ids\"],\n ... context_attention_mask=docs_dict[\"context_attention_mask\"],\n ... doc_scores=doc_scores,\n ... )\n >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)\n ```\"\"\"\n n_docs = n_docs if n_docs is not None else self.config.n_docs\n do_marginalize = do_marginalize if do_marginalize is not None else self.config.do_marginalize\n reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss\n\n if labels is not None:\n if decoder_input_ids is None:\n decoder_input_ids = labels\n use_cache = False\n\n outputs = self.rag(\n input_ids=input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n context_input_ids=context_input_ids,\n context_attention_mask=context_attention_mask,\n doc_scores=doc_scores,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_retrieved=output_retrieved,\n n_docs=n_docs,\n )\n\n loss = None\n logits = outputs.logits\n if labels is not None:\n assert decoder_input_ids is not None\n loss = self.get_nll(\n outputs.logits,\n outputs.doc_scores,\n labels,\n reduce_loss=reduce_loss,\n epsilon=self.config.label_smoothing,\n n_docs=n_docs,\n )\n\n if do_marginalize:\n logits = self.marginalize(logits, outputs.doc_scores, n_docs)\n\n return RetrievAugLMMarginOutput(\n loss=loss,\n logits=logits,\n doc_scores=outputs.doc_scores,\n past_key_values=outputs.past_key_values,\n context_input_ids=outputs.context_input_ids,\n context_attention_mask=outputs.context_attention_mask,\n retrieved_doc_embeds=outputs.retrieved_doc_embeds,\n retrieved_doc_ids=outputs.retrieved_doc_ids,\n question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,\n question_enc_hidden_states=outputs.question_enc_hidden_states,\n question_enc_attentions=outputs.question_enc_attentions,\n generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,\n generator_enc_hidden_states=outputs.generator_enc_hidden_states,\n generator_enc_attentions=outputs.generator_enc_attentions,\n generator_dec_hidden_states=outputs.generator_dec_hidden_states,\n generator_dec_attentions=outputs.generator_dec_attentions,\n generator_cross_attentions=outputs.generator_cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n exploration_id: str,\n title: str,\n category: str,\n objective: str,\n language_code: str,\n tags: List[str],\n ratings: Dict[str, int],\n scaled_average_rating: float,\n status: str,\n community_owned: bool,\n owner_ids: List[str],\n editor_ids: List[str],\n voice_artist_ids: List[str],\n viewer_ids: List[str],\n contributor_ids: List[str],\n contributors_summary: Dict[str, int],\n version: int,\n exploration_model_created_on: datetime.datetime,\n exploration_model_last_updated: datetime.datetime,\n first_published_msec: Optional[float],\n deleted: bool = False\n ) -> None:\n \"\"\"Initializes a ExplorationSummary domain object.\n\n Args:\n exploration_id: str. The exploration id.\n title: str. The exploration title.\n category: str. The exploration category.\n objective: str. The exploration objective.\n language_code: str. The code that represents the exploration\n language.\n tags: list(str). List of tags.\n ratings: dict. Dict whose keys are '1', '2', '3', '4', '5' and\n whose values are nonnegative integers representing frequency\n counts. Note that the keys need to be strings in order for this\n dict to be JSON-serializable.\n scaled_average_rating: float. The average rating.\n status: str. The status of the exploration.\n community_owned: bool. Whether the exploration is community-owned.\n owner_ids: list(str). List of the users ids who are the owners of\n this exploration.\n editor_ids: list(str). List of the users ids who have access to\n edit this exploration.\n voice_artist_ids: list(str). List of the users ids who have access\n to voiceover this exploration.\n viewer_ids: list(str). List of the users ids who have access to\n view this exploration.\n contributor_ids: list(str). List of the users ids of the user who\n have contributed to this exploration.\n contributors_summary: dict. A summary about contributors of current\n exploration. The keys are user ids and the values are the\n number of commits made by that user.\n version: int. The version of the exploration.\n exploration_model_created_on: datetime.datetime. Date and time when\n the exploration model is created.\n exploration_model_last_updated: datetime.datetime. Date and time\n when the exploration model was last updated.\n first_published_msec: float|None. Time in milliseconds since the\n Epoch, when the exploration was first published, or None if\n Exploration is not published yet.\n deleted: bool. Whether the exploration is marked as deleted.\n \"\"\"\n self.id = exploration_id\n self.title = title\n self.category = category\n self.objective = objective\n self.language_code = language_code\n self.tags = tags\n self.ratings = ratings\n self.scaled_average_rating = scaled_average_rating\n self.status = status\n self.community_owned = community_owned\n self.owner_ids = owner_ids\n self.editor_ids = editor_ids\n self.voice_artist_ids = voice_artist_ids\n self.viewer_ids = viewer_ids\n self.contributor_ids = contributor_ids\n self.contributors_summary = contributors_summary\n self.version = version\n self.exploration_model_created_on = exploration_model_created_on\n self.exploration_model_last_updated = exploration_model_last_updated\n self.first_published_msec = first_published_msec\n self.deleted = deleted", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n segmentation_maps: Optional[ImageInput] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n mask_size: Optional[Dict[str, int]] = None,\n resample: Optional[\"PILImageResampling\"] = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[Union[int, float]] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n pad_size: Optional[Dict[str, int]] = None,\n mask_pad_size: Optional[Dict[str, int]] = None,\n do_convert_rgb: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ):\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n segmentation_maps (`ImageInput`, *optional*):\n Segmentation map to preprocess.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Controls the size of the image after `resize`. The longest edge of the image is resized to\n `size[\"longest_edge\"]` whilst preserving the aspect ratio.\n mask_size (`Dict[str, int]`, *optional*, defaults to `self.mask_size`):\n Controls the size of the segmentation map after `resize`. The longest edge of the image is resized to\n `size[\"longest_edge\"]` whilst preserving the aspect ratio.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image pixel values by rescaling factor.\n rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to apply to the image pixel values.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to normalize the image by if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to normalize the image by if `do_normalize` is set to `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether to pad the image.\n pad_size (`Dict[str, int]`, *optional*, defaults to `self.pad_size`):\n Controls the size of the padding applied to the image. The image is padded to `pad_size[\"height\"]` and\n `pad_size[\"width\"]` if `do_pad` is set to `True`.\n mask_pad_size (`Dict[str, int]`, *optional*, defaults to `self.mask_pad_size`):\n Controls the size of the padding applied to the segmentation map. The image is padded to\n `mask_pad_size[\"height\"]` and `mask_pad_size[\"width\"]` if `do_pad` is set to `True`.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size\n mask_size = mask_size if mask_size is not None else self.mask_size\n mask_size = (\n get_size_dict(max_size=mask_size, default_to_square=False)\n if not isinstance(mask_size, dict)\n else mask_size\n )\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_pad = do_pad if do_pad is not None else self.do_pad\n pad_size = pad_size if pad_size is not None else self.pad_size\n pad_size = get_size_dict(pad_size, default_to_square=True)\n mask_pad_size = mask_pad_size if mask_pad_size is not None else self.mask_pad_size\n mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n if segmentation_maps is not None:\n segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)\n\n if not valid_images(segmentation_maps):\n raise ValueError(\n \"Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_pad=do_pad,\n size_divisibility=pad_size, # Here _preprocess needs do_pad and pad_size.\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n images, original_sizes, reshaped_input_sizes = zip(\n *(\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_pad=do_pad,\n pad_size=pad_size,\n do_convert_rgb=do_convert_rgb,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in images\n )\n )\n\n data = {\n \"pixel_values\": images,\n \"original_sizes\": original_sizes,\n \"reshaped_input_sizes\": reshaped_input_sizes,\n }\n\n if segmentation_maps is not None:\n segmentation_maps, original_mask_sizes = zip(\n *(\n self._preprocess_mask(\n segmentation_map=mask,\n do_resize=do_resize,\n mask_size=mask_size,\n do_pad=do_pad,\n mask_pad_size=mask_pad_size,\n input_data_format=input_data_format,\n )\n for mask in segmentation_maps\n )\n )\n\n # masks should start out the same size as input images\n assert all(\n original_im_size == original_mask_size\n for original_im_size, original_mask_size in zip(original_sizes, original_mask_sizes)\n ), \"Segmentation maps should be the same size as input images.\"\n\n data[\"labels\"] = segmentation_maps\n\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=58101,\n decoder_vocab_size=None,\n max_position_embeddings=1024,\n encoder_layers=12,\n encoder_ffn_dim=4096,\n encoder_attention_heads=16,\n decoder_layers=12,\n decoder_ffn_dim=4096,\n decoder_attention_heads=16,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=1024,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=58100,\n scale_embedding=False,\n pad_token_id=58100,\n eos_token_id=0,\n forced_eos_token_id=0,\n share_encoder_decoder_embeddings=True,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.decoder_vocab_size = decoder_vocab_size or vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n self.share_encoder_decoder_embeddings = share_encoder_decoder_embeddings\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n num_channels=3,\n image_size=32,\n patch_size=16,\n batch_size=13,\n text_seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n ):\n self.parent = parent\n self.num_channels = num_channels\n self.image_size = image_size\n self.patch_size = patch_size\n self.batch_size = batch_size\n self.text_seq_length = text_seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.scope = scope\n\n # make sure the BOS, EOS and PAD tokens are within the vocab\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1\n\n # for GIT, the sequence length is the sum of the text and patch tokens, + 1 due to the CLS token\n self.seq_length = self.text_seq_length + int((self.image_size / self.patch_size) ** 2) + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutputWithPastAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs: Any,\n ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n head_mask=head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n max_position_embeddings=512,\n encoder_layers=8,\n encoder_ffn_dim=2048,\n encoder_attention_heads=16,\n decoder_layers=8,\n decoder_ffn_dim=2048,\n decoder_attention_heads=16,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=512,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n decoder_start_token_id=1,\n scale_embedding=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n forced_eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=514,\n type_vocab_size=1,\n initializer_factor=1.0,\n layer_norm_eps=1e-12,\n projection_dim=512,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n position_embedding_type=\"absolute\",\n use_cache=True,\n projection_hidden_act=\"relu\",\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_factor = initializer_factor\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.projection_hidden_act = projection_hidden_act\n self.projection_dim = projection_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _call_one(\n self,\n text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],\n text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n is_split_into_words: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n split_special_tokens: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n # Input type checking for clearer error\n def _is_valid_text_input(t):\n if isinstance(t, str):\n # Strings are fine\n return True\n elif isinstance(t, (list, tuple)):\n # List are fine as long as they are...\n if len(t) == 0:\n # ... empty\n return True\n elif isinstance(t[0], str):\n # ... list of strings\n return True\n elif isinstance(t[0], (list, tuple)):\n # ... list with an empty list or with a list of strings\n return len(t[0]) == 0 or isinstance(t[0][0], str)\n else:\n return False\n else:\n return False\n\n if not _is_valid_text_input(text):\n raise ValueError(\n \"text input must be of type `str` (single example), `List[str]` (batch or single pretokenized example) \"\n \"or `List[List[str]]` (batch of pretokenized examples).\"\n )\n\n if text_pair is not None and not _is_valid_text_input(text_pair):\n raise ValueError(\n \"text input must be of type `str` (single example), `List[str]` (batch or single pretokenized example) \"\n \"or `List[List[str]]` (batch of pretokenized examples).\"\n )\n\n if is_split_into_words:\n is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))\n else:\n is_batched = isinstance(text, (list, tuple))\n\n if is_batched:\n if isinstance(text_pair, str):\n raise TypeError(\n \"when tokenizing batches of text, `text_pair` must be a list or tuple with the same length as\"\n \" `text`.\"\n )\n if text_pair is not None and len(text) != len(text_pair):\n raise ValueError(\n f\"batch length of `text`: {len(text)} does not match batch length of `text_pair`:\"\n f\" {len(text_pair)}.\"\n )\n batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text\n return self.batch_encode_plus(\n batch_text_or_text_pairs=batch_text_or_text_pairs,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n split_special_tokens=split_special_tokens,\n **kwargs,\n )\n else:\n return self.encode_plus(\n text=text,\n text_pair=text_pair,\n add_special_tokens=add_special_tokens,\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n split_special_tokens=split_special_tokens,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n projection_dim=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=100,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n size_divisor: Optional[int] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n do_center_crop: Optional[bool] = None,\n crop_size: Dict[str, int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Controls the size of the image after `resize`. The shortest edge of the image is resized to\n `size[\"shortest_edge\"]` whilst preserving the aspect ratio. If the longest edge of this resized image\n is > `int(size[\"shortest_edge\"] * (1333 / 800))`, then the image is resized again to make the longest\n edge equal to `int(size[\"shortest_edge\"] * (1333 / 800))`.\n size_divisor (`int`, *optional*, defaults to `self.size_divisor`):\n The image is resized to a size that is a multiple of this value.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to normalize the image by if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to normalize the image by if `do_normalize` is set to `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether to pad the image to the (max_height, max_width) in the batch. If `True`, a pixel mask is also\n created and returned.\n do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):\n Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the\n image is padded with 0's and then center cropped.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be\n padded with zeros and then cropped\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size_divisor = size_divisor if size_divisor is not None else self.size_divisor\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_pad = do_pad if do_pad is not None else self.do_pad\n do_center_crop if do_center_crop is not None else self.do_center_crop\n # For backwards compatibility. Initial version of this processor was cropping to the \"size\" argument, which\n # it should default to if crop_size is undefined.\n crop_size = (\n crop_size if crop_size is not None else (self.crop_size if self.crop_size is not None else self.size)\n )\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n\n if not is_batched(images):\n images = [images]\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n # Here, crop_size is used only if it is set, else size will be used.\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_pad=do_pad,\n size_divisibility=size_divisor,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if do_resize:\n images = [\n self.resize(\n image=image,\n size=size,\n size_divisor=size_divisor,\n resample=resample,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n\n if do_center_crop:\n images = [\n self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images\n ]\n\n if do_rescale:\n images = [\n self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_normalize:\n images = [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images\n ]\n\n if do_pad:\n encoded_outputs = self.pad(\n images, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=data_format\n )\n else:\n encoded_outputs = BatchFeature(data={\"pixel_values\": images}, tensor_type=return_tensors)\n\n return encoded_outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "async def assemble_spec( # pylint: disable=too-many-arguments # noqa: PLR0913\n *,\n app: FastAPI,\n service_key: ServiceKey,\n service_version: ServiceVersion,\n paths_mapping: PathMappingsLabel,\n compose_spec: ComposeSpecLabelDict | None,\n container_http_entry: str | None,\n dynamic_sidecar_network_name: str,\n swarm_network_name: str,\n service_resources: ServiceResourcesDict,\n has_quota_support: bool,\n simcore_service_labels: SimcoreServiceLabels,\n allow_internet_access: bool,\n product_name: ProductName,\n user_id: UserID,\n project_id: ProjectID,\n node_id: NodeID,\n simcore_user_agent: str,\n swarm_stack_name: str,\n) -> str:\n \"\"\"\n returns a docker-compose spec used by\n the dynamic-sidecar to start the service\n \"\"\"\n\n docker_registry_settings: RegistrySettings = (\n app.state.settings.DIRECTOR_V2_DOCKER_REGISTRY\n )\n\n docker_compose_version = (\n app.state.settings.DYNAMIC_SERVICES.DYNAMIC_SCHEDULER.DYNAMIC_SIDECAR_DOCKER_COMPOSE_VERSION\n )\n\n egress_proxy_settings: EgressProxySettings = (\n app.state.settings.DYNAMIC_SERVICES.DYNAMIC_SIDECAR_EGRESS_PROXY_SETTINGS\n )\n\n # when no compose yaml file was provided\n container_name: str | None = None\n if compose_spec is None:\n service_spec: ComposeSpecLabelDict = {\n \"version\": docker_compose_version,\n \"services\": {\n DEFAULT_SINGLE_SERVICE_NAME: {\n \"image\": f\"{docker_registry_settings.resolved_registry_url}/{service_key}:{service_version}\"\n }\n },\n }\n container_name = f\"{DEFAULT_SINGLE_SERVICE_NAME}\"\n else:\n service_spec = deepcopy(compose_spec)\n container_name = container_http_entry\n\n assert service_spec is not None # nosec\n assert container_name is not None # nosec\n\n _update_networking_configuration(\n service_spec=service_spec,\n target_http_entrypoint_container=container_name,\n dynamic_sidecar_network_name=dynamic_sidecar_network_name,\n swarm_network_name=swarm_network_name,\n )\n\n _update_paths_mappings(service_spec, paths_mapping)\n\n assigned_limits = _update_resource_limits_and_reservations(\n service_resources=service_resources, service_spec=service_spec\n )\n\n if not has_quota_support:\n _strip_service_quotas(service_spec)\n\n if not allow_internet_access:\n simcore_service_labels = await substitute_vendor_secrets_in_model(\n app=app,\n model=simcore_service_labels,\n safe=True,\n service_key=service_key,\n service_version=service_version,\n product_name=product_name,\n )\n simcore_service_labels = await resolve_and_substitute_session_variables_in_model(\n app=app,\n model=simcore_service_labels,\n # NOTE: at this point all OsparcIdentifiers have to be replaced\n # an error will be raised otherwise\n safe=False,\n user_id=user_id,\n product_name=product_name,\n project_id=project_id,\n node_id=node_id,\n )\n\n add_egress_configuration(\n service_spec=service_spec,\n simcore_service_labels=simcore_service_labels,\n egress_proxy_settings=egress_proxy_settings,\n )\n\n _update_container_labels(\n service_spec=service_spec,\n user_id=user_id,\n project_id=project_id,\n node_id=node_id,\n product_name=product_name,\n simcore_user_agent=simcore_user_agent,\n swarm_stack_name=swarm_stack_name,\n assigned_limits=assigned_limits,\n )\n\n # resolve service-spec\n service_spec = auto_inject_environments(service_spec)\n\n service_spec = await substitute_vendor_secrets_in_specs(\n app=app,\n specs=service_spec,\n safe=True,\n service_key=service_key,\n service_version=service_version,\n product_name=product_name,\n )\n service_spec = await resolve_and_substitute_session_variables_in_specs(\n app=app,\n specs=service_spec,\n user_id=user_id,\n safe=True,\n product_name=product_name,\n project_id=project_id,\n node_id=node_id,\n )\n\n stringified_service_spec: str = replace_env_vars_in_compose_spec(\n service_spec=service_spec,\n replace_simcore_registry=docker_registry_settings.resolved_registry_url,\n replace_service_version=service_version,\n )\n\n return stringified_service_spec", "smellKey": "S107", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=None,\n hidden_size=1024,\n num_hidden_layers=24,\n num_attention_heads=16,\n intermediate_size=4096,\n feature_projection_input_dim=160,\n hidden_act=\"swish\",\n hidden_dropout=0.0,\n activation_dropout=0.0,\n attention_dropout=0.0,\n feat_proj_dropout=0.0,\n final_dropout=0.1,\n layerdrop=0.1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n apply_spec_augment=True,\n mask_time_prob=0.05,\n mask_time_length=10,\n mask_time_min_masks=2,\n mask_feature_prob=0.0,\n mask_feature_length=10,\n mask_feature_min_masks=0,\n ctc_loss_reduction=\"sum\",\n ctc_zero_infinity=False,\n use_weighted_layer_sum=False,\n classifier_proj_size=768,\n tdnn_dim=(512, 512, 512, 512, 1500),\n tdnn_kernel=(5, 3, 3, 1, 1),\n tdnn_dilation=(1, 2, 3, 1, 1),\n xvector_output_dim=512,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n add_adapter=False,\n adapter_kernel_size=3,\n adapter_stride=2,\n num_adapter_layers=1,\n adapter_act=\"relu\",\n use_intermediate_ffn_before_adapter=False,\n output_hidden_size=None,\n position_embeddings_type=\"relative_key\",\n rotary_embedding_base=10000,\n max_source_positions=5000,\n left_max_position_embeddings=64,\n right_max_position_embeddings=8,\n conv_depthwise_kernel_size=31,\n conformer_conv_dropout=0.1,\n **kwargs,\n ):\n super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.num_attention_heads = num_attention_heads\n self.feature_projection_input_dim = feature_projection_input_dim\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.feat_proj_dropout = feat_proj_dropout\n self.final_dropout = final_dropout\n self.layerdrop = layerdrop\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.use_weighted_layer_sum = use_weighted_layer_sum\n self.max_source_positions = max_source_positions\n\n if position_embeddings_type is not None and position_embeddings_type not in [\n \"rotary\",\n \"relative\",\n \"relative_key\",\n ]:\n raise ValueError(\n \"\"\"\n `position_embeddings_type` is not valid. It must be one of the following values:\n `[\"rotary\", \"relative\", \"relative_key\"]` or left as `None`.\n \"\"\"\n )\n self.position_embeddings_type = position_embeddings_type\n self.rotary_embedding_base = rotary_embedding_base\n self.left_max_position_embeddings = left_max_position_embeddings\n self.right_max_position_embeddings = right_max_position_embeddings\n\n # Conformer-block related\n self.conv_depthwise_kernel_size = conv_depthwise_kernel_size\n self.conformer_conv_dropout = conformer_conv_dropout\n\n # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779\n self.apply_spec_augment = apply_spec_augment\n self.mask_time_prob = mask_time_prob\n self.mask_time_length = mask_time_length\n self.mask_time_min_masks = mask_time_min_masks\n self.mask_feature_prob = mask_feature_prob\n self.mask_feature_length = mask_feature_length\n self.mask_feature_min_masks = mask_feature_min_masks\n\n # ctc loss\n self.ctc_loss_reduction = ctc_loss_reduction\n self.ctc_zero_infinity = ctc_zero_infinity\n\n # adapter\n self.add_adapter = add_adapter\n self.adapter_kernel_size = adapter_kernel_size\n self.adapter_stride = adapter_stride\n self.num_adapter_layers = num_adapter_layers\n self.adapter_act = adapter_act\n self.output_hidden_size = output_hidden_size if output_hidden_size is not None else hidden_size\n if use_intermediate_ffn_before_adapter and not add_adapter:\n raise ValueError(\"`use_intermediate_ffn_before_adapter` is `True` but `add_adapter` is `False`.\")\n self.use_intermediate_ffn_before_adapter = use_intermediate_ffn_before_adapter\n\n # SequenceClassification-specific parameter. Feel free to ignore for other classes.\n self.classifier_proj_size = classifier_proj_size\n\n # XVector-specific parameters. Feel free to ignore for other classes.\n self.tdnn_dim = list(tdnn_dim)\n self.tdnn_kernel = list(tdnn_kernel)\n self.tdnn_dilation = list(tdnn_dilation)\n self.xvector_output_dim = xvector_output_dim", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def activation_key_present(\n name,\n description,\n base_channel=\"\",\n usage_limit=0,\n contact_method=\"default\",\n system_types=[],\n universal_default=False,\n child_channels=[],\n configuration_channels=[],\n packages=[],\n server_groups=[],\n configure_after_registration=False,\n org_admin_user=None,\n org_admin_password=None,\n):\n \"\"\"\n Ensure an Uyuni Activation Key is present.\n\n :param name: the Activation Key name\n :param description: the Activation description\n :param base_channel: base channel to be used\n :param usage_limit: activation key usage limit. Default value is 0, which means unlimited usage\n :param contact_method: contact method to be used. Can be one of: 'default', 'ssh-push' or 'ssh-push-tunnel'\n :param system_types: system types to be assigned.\n Can be one of: 'virtualization_host', 'container_build_host',\n 'monitoring_entitled', 'osimage_build_host', 'virtualization_host'\n :param universal_default: sets this activation key as organization universal default\n :param child_channels: list of child channels to be assigned\n :param configuration_channels: list of configuration channels to be assigned\n :param packages: list of packages which will be installed\n :param server_groups: list of server groups to assign the activation key with\n :param configure_after_registration: deploy configuration files to systems on registration\n :param org_admin_user: organization administrator username\n :param org_admin_password: organization administrator password\n\n :return: dict for Salt communication\n \"\"\"\n return UyuniActivationKeys().manage(\n name,\n description,\n base_channel=base_channel,\n usage_limit=usage_limit,\n contact_method=contact_method,\n system_types=system_types,\n universal_default=universal_default,\n child_channels=child_channels,\n configuration_channels=configuration_channels,\n packages=packages,\n server_groups=server_groups,\n configure_after_registration=configure_after_registration,\n org_admin_user=org_admin_user,\n org_admin_password=org_admin_password,\n )", "smellKey": "S107", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def preprocess(\n self,\n images: ImageInput,\n do_convert_rgb: Optional[bool] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: Optional[bool] = None,\n do_image_splitting: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n input_data_format: Optional[ChannelDimension] = None,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n ):\n \"\"\"\n Preprocess a batch of images.\n\n Args:\n images (`ImageInput`):\n A list of images to preprocess.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after resizing. Shortest edge of the image is resized to size[\"shortest_edge\"], with\n the longest edge resized to keep the input aspect ratio.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image.\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_pad (`bool`, *optional*, defaults to `self.do_pad`):\n Whether or not to pad the images to the largest height and width in the batch.\n do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):\n Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That\n strategy was first introduced in https://arxiv.org/abs/2311.06607.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n do_pad = do_pad if do_pad is not None else self.do_pad\n do_image_splitting = do_image_splitting if do_image_splitting is not None else self.do_image_splitting\n\n images_list = make_list_of_images(images)\n\n if not valid_images(images_list[0]):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if do_convert_rgb:\n images_list = [[convert_to_rgb(image) for image in images] for images in images_list]\n\n # All transformations expect numpy arrays.\n images_list = [[to_numpy_array(image) for image in images] for images in images_list]\n\n if is_scaled_image(images_list[0][0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images_list[0][0])\n\n if do_image_splitting:\n new_images_list = []\n for images in images_list:\n new_images = []\n for image in images:\n new_images.extend(self.split_image(image, input_data_format))\n new_images_list.append(new_images)\n images_list = new_images_list\n\n if do_resize:\n images_list = [\n [\n self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n if do_rescale:\n images_list = [\n [\n self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n if do_normalize:\n images_list = [\n [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n pixel_attention_mask = None\n if do_pad:\n images_list, pixel_attention_mask = self.pad(\n images_list, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=input_data_format\n )\n\n if data_format is not None:\n images_list = [\n [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n for image in images\n ]\n for images in images_list\n ]\n\n data = {\"pixel_values\": np.array(images_list) if do_pad else images_list} # Faster tensor conversion\n if pixel_attention_mask is not None:\n data[\"pixel_attention_mask\"] = np.array(pixel_attention_mask) if do_pad else pixel_attention_mask\n\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_attention_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n embedding_size=24,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_choices=4,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.embedding_size = embedding_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_choices = num_choices\n super().__init__()", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,\n formats=None, names=None, titles=None,\n byteorder=None, aligned=False,\n mask=nomask, hard_mask=False, fill_value=None, keep_mask=True,\n copy=False,\n **options):\n\n self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,\n strides=strides, formats=formats, names=names,\n titles=titles, byteorder=byteorder,\n aligned=aligned,)\n\n mdtype = ma.make_mask_descr(self.dtype)\n if mask is nomask or not np.size(mask):\n if not keep_mask:\n self._mask = tuple([False] * len(mdtype))\n else:\n mask = np.array(mask, copy=copy)\n if mask.shape != self.shape:\n (nd, nm) = (self.size, mask.size)\n if nm == 1:\n mask = np.resize(mask, self.shape)\n elif nm == nd:\n mask = np.reshape(mask, self.shape)\n else:\n msg = \"Mask and data not compatible: data size is %i, \" + \\\n \"mask size is %i.\"\n raise MAError(msg % (nd, nm))\n if not keep_mask:\n self.__setmask__(mask)\n self._sharedmask = True\n else:\n if mask.dtype == mdtype:\n _mask = mask\n else:\n _mask = np.array([tuple([m] * len(mdtype)) for m in mask],\n dtype=mdtype)\n self._mask = _mask\n return self", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n command: \"Command\",\n parent: t.Optional[\"Context\"] = None,\n info_name: t.Optional[str] = None,\n obj: t.Optional[t.Any] = None,\n auto_envvar_prefix: t.Optional[str] = None,\n default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,\n terminal_width: t.Optional[int] = None,\n max_content_width: t.Optional[int] = None,\n resilient_parsing: bool = False,\n allow_extra_args: t.Optional[bool] = None,\n allow_interspersed_args: t.Optional[bool] = None,\n ignore_unknown_options: t.Optional[bool] = None,\n help_option_names: t.Optional[t.List[str]] = None,\n token_normalize_func: t.Optional[t.Callable[[str], str]] = None,\n color: t.Optional[bool] = None,\n show_default: t.Optional[bool] = None,\n ) -> None:\n #: the parent context or `None` if none exists.\n self.parent = parent\n #: the :class:`Command` for this context.\n self.command = command\n #: the descriptive information name\n self.info_name = info_name\n #: Map of parameter names to their parsed values. Parameters\n #: with ``expose_value=False`` are not stored.\n self.params: t.Dict[str, t.Any] = {}\n #: the leftover arguments.\n self.args: t.List[str] = []\n #: protected arguments. These are arguments that are prepended\n #: to `args` when certain parsing scenarios are encountered but\n #: must be never propagated to another arguments. This is used\n #: to implement nested parsing.\n self.protected_args: t.List[str] = []\n #: the collected prefixes of the command's options.\n self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()\n\n if obj is None and parent is not None:\n obj = parent.obj\n\n #: the user object stored.\n self.obj: t.Any = obj\n self._meta: t.Dict[str, t.Any] = getattr(parent, \"meta\", {})\n\n #: A dictionary (-like object) with defaults for parameters.\n if (\n default_map is None\n and info_name is not None\n and parent is not None\n and parent.default_map is not None\n ):\n default_map = parent.default_map.get(info_name)\n\n self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map\n\n #: This flag indicates if a subcommand is going to be executed. A\n #: group callback can use this information to figure out if it's\n #: being executed directly or because the execution flow passes\n #: onwards to a subcommand. By default it's None, but it can be\n #: the name of the subcommand to execute.\n #:\n #: If chaining is enabled this will be set to ``'*'`` in case\n #: any commands are executed. It is however not possible to\n #: figure out which ones. If you require this knowledge you\n #: should use a :func:`result_callback`.\n self.invoked_subcommand: t.Optional[str] = None\n\n if terminal_width is None and parent is not None:\n terminal_width = parent.terminal_width\n\n #: The width of the terminal (None is autodetection).\n self.terminal_width: t.Optional[int] = terminal_width\n\n if max_content_width is None and parent is not None:\n max_content_width = parent.max_content_width\n\n #: The maximum width of formatted content (None implies a sensible\n #: default which is 80 for most things).\n self.max_content_width: t.Optional[int] = max_content_width\n\n if allow_extra_args is None:\n allow_extra_args = command.allow_extra_args\n\n #: Indicates if the context allows extra args or if it should\n #: fail on parsing.\n #:\n #: .. versionadded:: 3.0\n self.allow_extra_args = allow_extra_args\n\n if allow_interspersed_args is None:\n allow_interspersed_args = command.allow_interspersed_args\n\n #: Indicates if the context allows mixing of arguments and\n #: options or not.\n #:\n #: .. versionadded:: 3.0\n self.allow_interspersed_args: bool = allow_interspersed_args\n\n if ignore_unknown_options is None:\n ignore_unknown_options = command.ignore_unknown_options\n\n #: Instructs click to ignore options that a command does not\n #: understand and will store it on the context for later\n #: processing. This is primarily useful for situations where you\n #: want to call into external programs. Generally this pattern is\n #: strongly discouraged because it's not possibly to losslessly\n #: forward all arguments.\n #:\n #: .. versionadded:: 4.0\n self.ignore_unknown_options: bool = ignore_unknown_options\n\n if help_option_names is None:\n if parent is not None:\n help_option_names = parent.help_option_names\n else:\n help_option_names = [\"--help\"]\n\n #: The names for the help options.\n self.help_option_names: t.List[str] = help_option_names\n\n if token_normalize_func is None and parent is not None:\n token_normalize_func = parent.token_normalize_func\n\n #: An optional normalization function for tokens. This is\n #: options, choices, commands etc.\n self.token_normalize_func: t.Optional[\n t.Callable[[str], str]\n ] = token_normalize_func\n\n #: Indicates if resilient parsing is enabled. In that case Click\n #: will do its best to not cause any failures and default values\n #: will be ignored. Useful for completion.\n self.resilient_parsing: bool = resilient_parsing\n\n # If there is no envvar prefix yet, but the parent has one and\n # the command on this level has a name, we can expand the envvar\n # prefix automatically.\n if auto_envvar_prefix is None:\n if (\n parent is not None\n and parent.auto_envvar_prefix is not None\n and self.info_name is not None\n ):\n auto_envvar_prefix = (\n f\"{parent.auto_envvar_prefix}_{self.info_name.upper()}\"\n )\n else:\n auto_envvar_prefix = auto_envvar_prefix.upper()\n\n if auto_envvar_prefix is not None:\n auto_envvar_prefix = auto_envvar_prefix.replace(\"-\", \"_\")\n\n self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix\n\n if color is None and parent is not None:\n color = parent.color\n\n #: Controls if styling output is wanted or not.\n self.color: t.Optional[bool] = color\n\n if show_default is None and parent is not None:\n show_default = parent.show_default\n\n #: Show option default values when formatting help text.\n self.show_default: t.Optional[bool] = show_default\n\n self._close_callbacks: t.List[t.Callable[[], t.Any]] = []\n self._depth = 0\n self._parameter_source: t.Dict[str, ParameterSource] = {}\n self._exit_stack = ExitStack()", "smellKey": "S107", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"almanach/camembert-base\")\n >>> config = AutoConfig.from_pretrained(\"almanach/camembert-base\")\n >>> config.is_decoder = True\n >>> model = CamembertForCausalLM.from_pretrained(\"almanach/camembert-base\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.roberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(prediction_scores.device)\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n depths=[6, 3, 3],\n num_group_tokens=[64, 8, 0],\n num_output_groups=[64, 8, 8],\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.depths = depths\n self.num_hidden_layers = sum(depths)\n self.expected_num_hidden_layers = len(depths) + 1\n self.num_group_tokens = num_group_tokens\n self.num_output_groups = num_output_groups\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n num_patches = (image_size // patch_size) ** 2\n # no [CLS] token for GroupViT\n self.seq_length = num_patches", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n modality_type_vocab_size=2,\n add_multiple_images=False,\n num_images=-1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.scope = scope\n self.modality_type_vocab_size = modality_type_vocab_size\n self.add_multiple_images = add_multiple_images\n self.num_images = num_images\n # we set the expected sequence length (which is used in several tests)\n # this is equal to the seq length of the text tokens + number of image patches + 1 for the CLS token\n self.expected_seq_len = self.seq_length + (self.image_size // self.patch_size) ** 2 + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden_layers\n seq_length=60,\n is_training=True,\n use_labels=False,\n vocab_size=200,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n input_channels=1,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n max_source_positions=30,\n max_target_positions=40,\n bos_token_id=98,\n eos_token_id=98,\n pad_token_id=0,\n num_mel_bins=80,\n decoder_start_token_id=85,\n num_conv_layers=1,\n suppress_tokens=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.input_channels = input_channels\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.num_mel_bins = num_mel_bins\n self.max_position_embeddings = max_position_embeddings\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.num_conv_layers = num_conv_layers\n self.suppress_tokens = suppress_tokens", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def batch_encode_plus_boxes(\n self,\n batch_text_or_text_pairs: Union[\n List[TextInput],\n List[TextInputPair],\n List[PreTokenizedInput],\n ],\n is_pair: bool = None,\n boxes: Optional[List[List[List[int]]]] = None,\n word_labels: Optional[List[List[int]]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n is_split_into_words: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.\n\n <Tip warning={true}>\n\n This method is deprecated, `__call__` should be used instead.\n\n </Tip>\n\n Args:\n batch_text_or_text_pairs (`List[str]`, `List[Tuple[str, str]]`, `List[List[str]]`, `List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also `List[List[int]]`, `List[Tuple[List[int], List[int]]]`):\n Batch of sequences or pair of sequences to be encoded. This can be a list of\n string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see\n details in `encode_plus`).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._batch_encode_plus_boxes(\n batch_text_or_text_pairs=batch_text_or_text_pairs,\n is_pair=is_pair,\n boxes=boxes,\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n is_split_into_words=is_split_into_words,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n thread_id: str,\n entity_type: str,\n entity_id: str,\n state_name: Optional[str],\n original_author_id: str,\n status: str,\n subject: str,\n summary: str,\n has_suggestion: bool,\n message_count: int,\n created_on: datetime.datetime,\n last_updated: datetime.datetime,\n last_nonempty_message_text: Optional[str] = None,\n last_nonempty_message_author_id: Optional[str] = None\n ) -> None:\n \"\"\"Initializes a FeedbackThread object.\"\"\"\n\n self.id = thread_id\n self.entity_type = entity_type\n self.entity_id = entity_id\n self.state_name = state_name\n self.original_author_id = original_author_id\n self.status = status\n self.subject = subject\n self.summary = summary\n self.has_suggestion = has_suggestion\n self.message_count = message_count\n\n self.created_on = created_on\n self.last_updated = last_updated\n self.last_nonempty_message_text = last_nonempty_message_text\n self.last_nonempty_message_author_id = last_nonempty_message_author_id", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def encode_plus(\n self,\n text: Union[TextInput, PreTokenizedInput],\n text_pair: Optional[PreTokenizedInput] = None,\n boxes: Optional[List[List[int]]] = None,\n word_labels: Optional[List[int]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,\n `__call__` should be used instead.\n\n Args:\n text (`str`, `List[str]`, `List[List[str]]`):\n The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.\n text_pair (`List[str]` or `List[int]`, *optional*):\n Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a\n list of list of strings (words of a batch of examples).\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._encode_plus(\n text=text,\n boxes=boxes,\n text_pair=text_pair,\n word_labels=word_labels,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n stride=stride,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_overflowing_tokens=return_overflowing_tokens,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n backbone_config=None,\n backbone=None,\n use_pretrained_backbone=False,\n use_timm_backbone=False,\n backbone_kwargs=None,\n distance_loss_weight=1.0,\n duration_loss_weight=0.1,\n visual_prompter_type=\"framepad\",\n visual_prompter_apply=\"replace\",\n visual_prompt_size=96,\n max_img_size=448,\n num_frames=48,\n vocab_size=30522,\n hidden_size=768,\n intermediate_size=3072,\n num_hidden_layers=12,\n num_attention_heads=12,\n max_position_embeddings=512,\n max_grid_col_position_embeddings=100,\n max_grid_row_position_embeddings=100,\n hidden_dropout_prob=0.1,\n hidden_act=\"gelu\",\n layer_norm_eps=1e-12,\n initializer_range=0.02,\n attention_probs_dropout_prob=0.1,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if backbone_config is None and backbone is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\")\n backbone_config = CONFIG_MAPPING[\"resnet\"](out_features=[\"stage4\"])\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.get(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n self.backbone_config = backbone_config\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n self.distance_loss_weight = distance_loss_weight\n self.duration_loss_weight = duration_loss_weight\n self.visual_prompter_type = visual_prompter_type\n self.visual_prompter_apply = visual_prompter_apply\n self.visual_prompt_size = visual_prompt_size\n self.max_img_size = max_img_size\n self.num_frames = num_frames\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.max_position_embeddings = max_position_embeddings\n self.max_grid_col_position_embeddings = max_grid_col_position_embeddings\n self.max_grid_row_position_embeddings = max_grid_row_position_embeddings\n self.layer_norm_eps = layer_norm_eps\n self.hidden_dropout_prob = hidden_dropout_prob\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.attention_probs_dropout_prob = attention_probs_dropout_prob", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n qkv_bias=True,\n mask_token=True,\n vocab_size=99,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.qkv_bias = qkv_bias\n self.mask_token = mask_token\n self.vocab_size = vocab_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(LAYOUTLMV3_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFQuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n token_type_ids: tf.Tensor | None = None,\n position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n inputs_embeds: tf.Tensor | None = None,\n start_positions: tf.Tensor | None = None,\n end_positions: tf.Tensor | None = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n bbox: tf.Tensor | None = None,\n pixel_values: tf.Tensor | None = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n ) -> Union[\n TFQuestionAnsweringModelOutput,\n Tuple[tf.Tensor],\n Tuple[tf.Tensor, tf.Tensor],\n Tuple[tf.Tensor, tf.Tensor, tf.Tensor],\n Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor],\n ]:\n r\"\"\"\n start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoProcessor, TFAutoModelForQuestionAnswering\n >>> from datasets import load_dataset\n >>> import tensorflow as tf\n\n >>> processor = AutoProcessor.from_pretrained(\"microsoft/layoutlmv3-base\", apply_ocr=False)\n >>> model = TFAutoModelForQuestionAnswering.from_pretrained(\"microsoft/layoutlmv3-base\")\n\n >>> dataset = load_dataset(\"nielsr/funsd-layoutlmv3\", split=\"train\", trust_remote_code=True)\n >>> example = dataset[0]\n >>> image = example[\"image\"]\n >>> question = \"what's his name?\"\n >>> words = example[\"tokens\"]\n >>> boxes = example[\"bboxes\"]\n\n >>> encoding = processor(image, question, words, boxes=boxes, return_tensors=\"tf\")\n >>> start_positions = tf.convert_to_tensor([1])\n >>> end_positions = tf.convert_to_tensor([3])\n\n >>> outputs = model(**encoding, start_positions=start_positions, end_positions=end_positions)\n >>> loss = outputs.loss\n >>> start_scores = outputs.start_logits\n >>> end_scores = outputs.end_logits\n ```\"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.layoutlmv3(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n bbox=bbox,\n pixel_values=pixel_values,\n training=training,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output, training=training)\n start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)\n start_logits = tf.squeeze(input=start_logits, axis=-1)\n end_logits = tf.squeeze(input=end_logits, axis=-1)\n\n loss = None\n\n if start_positions is not None and end_positions is not None:\n labels = {\"start_position\": start_positions, \"end_position\": end_positions}\n loss = self.hf_compute_loss(labels, logits=(start_logits, end_logits))\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFQuestionAnsweringModelOutput(\n loss=loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def progressbar(\n iterable: t.Optional[t.Iterable[V]] = None,\n length: t.Optional[int] = None,\n label: t.Optional[str] = None,\n show_eta: bool = True,\n show_percent: t.Optional[bool] = None,\n show_pos: bool = False,\n item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,\n fill_char: str = \"#\",\n empty_char: str = \"-\",\n bar_template: str = \"%(label)s [%(bar)s] %(info)s\",\n info_sep: str = \" \",\n width: int = 36,\n file: t.Optional[t.TextIO] = None,\n color: t.Optional[bool] = None,\n update_min_steps: int = 1,\n) -> \"ProgressBar[V]\":\n \"\"\"This function creates an iterable context manager that can be used\n to iterate over something while showing a progress bar. It will\n either iterate over the `iterable` or `length` items (that are counted\n up). While iteration happens, this function will print a rendered\n progress bar to the given `file` (defaults to stdout) and will attempt\n to calculate remaining time and more. By default, this progress bar\n will not be rendered if the file is not a terminal.\n\n The context manager creates the progress bar. When the context\n manager is entered the progress bar is already created. With every\n iteration over the progress bar, the iterable passed to the bar is\n advanced and the bar is updated. When the context manager exits,\n a newline is printed and the progress bar is finalized on screen.\n\n Note: The progress bar is currently designed for use cases where the\n total progress can be expected to take at least several seconds.\n Because of this, the ProgressBar class object won't display\n progress that is considered too fast, and progress where the time\n between steps is less than a second.\n\n No printing must happen or the progress bar will be unintentionally\n destroyed.\n\n Example usage::\n\n with progressbar(items) as bar:\n for item in bar:\n do_something_with(item)\n\n Alternatively, if no iterable is specified, one can manually update the\n progress bar through the `update()` method instead of directly\n iterating over the progress bar. The update method accepts the number\n of steps to increment the bar with::\n\n with progressbar(length=chunks.total_bytes) as bar:\n for chunk in chunks:\n process_chunk(chunk)\n bar.update(chunks.bytes)\n\n The ``update()`` method also takes an optional value specifying the\n ``current_item`` at the new position. This is useful when used\n together with ``item_show_func`` to customize the output for each\n manual step::\n\n with click.progressbar(\n length=total_size,\n label='Unzipping archive',\n item_show_func=lambda a: a.filename\n ) as bar:\n for archive in zip_file:\n archive.extract()\n bar.update(archive.size, archive)\n\n :param iterable: an iterable to iterate over. If not provided the length\n is required.\n :param length: the number of items to iterate over. By default the\n progressbar will attempt to ask the iterator about its\n length, which might or might not work. If an iterable is\n also provided this parameter can be used to override the\n length. If an iterable is not provided the progress bar\n will iterate over a range of that length.\n :param label: the label to show next to the progress bar.\n :param show_eta: enables or disables the estimated time display. This is\n automatically disabled if the length cannot be\n determined.\n :param show_percent: enables or disables the percentage display. The\n default is `True` if the iterable has a length or\n `False` if not.\n :param show_pos: enables or disables the absolute position display. The\n default is `False`.\n :param item_show_func: A function called with the current item which\n can return a string to show next to the progress bar. If the\n function returns ``None`` nothing is shown. The current item can\n be ``None``, such as when entering and exiting the bar.\n :param fill_char: the character to use to show the filled part of the\n progress bar.\n :param empty_char: the character to use to show the non-filled part of\n the progress bar.\n :param bar_template: the format string to use as template for the bar.\n The parameters in it are ``label`` for the label,\n ``bar`` for the progress bar and ``info`` for the\n info section.\n :param info_sep: the separator between multiple info items (eta etc.)\n :param width: the width of the progress bar in characters, 0 means full\n terminal width\n :param file: The file to write to. If this is not a terminal then\n only the label is printed.\n :param color: controls if the terminal supports ANSI colors or not. The\n default is autodetection. This is only needed if ANSI\n codes are included anywhere in the progress bar output\n which is not the case by default.\n :param update_min_steps: Render only when this many updates have\n completed. This allows tuning for very fast iterators.\n\n .. versionchanged:: 8.0\n Output is shown even if execution time is less than 0.5 seconds.\n\n .. versionchanged:: 8.0\n ``item_show_func`` shows the current item, not the previous one.\n\n .. versionchanged:: 8.0\n Labels are echoed if the output is not a TTY. Reverts a change\n in 7.0 that removed all output.\n\n .. versionadded:: 8.0\n Added the ``update_min_steps`` parameter.\n\n .. versionchanged:: 4.0\n Added the ``color`` parameter. Added the ``update`` method to\n the object.\n\n .. versionadded:: 2.0\n \"\"\"\n from ._termui_impl import ProgressBar\n\n color = resolve_color_default(color)\n return ProgressBar(\n iterable=iterable,\n length=length,\n show_eta=show_eta,\n show_percent=show_percent,\n show_pos=show_pos,\n item_show_func=item_show_func,\n fill_char=fill_char,\n empty_char=empty_char,\n bar_template=bar_template,\n info_sep=info_sep,\n file=file,\n label=label,\n width=width,\n color=color,\n update_min_steps=update_min_steps,\n )", "smellKey": "S107", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _api_users_v3_get_serialize(\n self,\n created_at,\n deactivated_at,\n email,\n github_id,\n github_username,\n google_id,\n id,\n name,\n name_from,\n slack_id,\n slack_username,\n suitability_description,\n suitable,\n updated_at,\n limit,\n offset,\n include_deactivated,\n _request_auth,\n _content_type,\n _headers,\n _host_index,\n ) -> RequestSerialized:\n\n _host = None\n\n _collection_formats: Dict[str, str] = {\n }\n\n _path_params: Dict[str, str] = {}\n _query_params: List[Tuple[str, str]] = []\n _header_params: Dict[str, Optional[str]] = _headers or {}\n _form_params: List[Tuple[str, str]] = []\n _files: Dict[\n str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]\n ] = {}\n _body_params: Optional[bytes] = None\n\n # process the path parameters\n # process the query parameters\n if created_at is not None:\n if isinstance(created_at, datetime):\n _query_params.append(\n (\n 'createdAt',\n created_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('createdAt', created_at))\n \n if deactivated_at is not None:\n \n _query_params.append(('deactivatedAt', deactivated_at))\n \n if email is not None:\n \n _query_params.append(('email', email))\n \n if github_id is not None:\n \n _query_params.append(('githubID', github_id))\n \n if github_username is not None:\n \n _query_params.append(('githubUsername', github_username))\n \n if google_id is not None:\n \n _query_params.append(('googleID', google_id))\n \n if id is not None:\n \n _query_params.append(('id', id))\n \n if name is not None:\n \n _query_params.append(('name', name))\n \n if name_from is not None:\n \n _query_params.append(('nameFrom', name_from))\n \n if slack_id is not None:\n \n _query_params.append(('slackID', slack_id))\n \n if slack_username is not None:\n \n _query_params.append(('slackUsername', slack_username))\n \n if suitability_description is not None:\n \n _query_params.append(('suitabilityDescription', suitability_description))\n \n if suitable is not None:\n \n _query_params.append(('suitable', suitable))\n \n if updated_at is not None:\n if isinstance(updated_at, datetime):\n _query_params.append(\n (\n 'updatedAt',\n updated_at.strftime(\n self.api_client.configuration.datetime_format\n )\n )\n )\n else:\n _query_params.append(('updatedAt', updated_at))\n \n if limit is not None:\n \n _query_params.append(('limit', limit))\n \n if offset is not None:\n \n _query_params.append(('offset', offset))\n \n if include_deactivated is not None:\n \n _query_params.append(('include-deactivated', include_deactivated))\n \n # process the header parameters\n # process the form parameters\n # process the body parameter\n\n\n # set the HTTP header `Accept`\n if 'Accept' not in _header_params:\n _header_params['Accept'] = self.api_client.select_header_accept(\n [\n 'application/json'\n ]\n )\n\n\n # authentication setting\n _auth_settings: List[str] = [\n ]\n\n return self.api_client.param_serialize(\n method='GET',\n resource_path='/api/users/v3',\n path_params=_path_params,\n query_params=_query_params,\n header_params=_header_params,\n body=_body_params,\n post_params=_form_params,\n files=_files,\n auth_settings=_auth_settings,\n collection_formats=_collection_formats,\n _host=_host,\n _request_auth=_request_auth\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=64,\n num_channels=3,\n embed_dim=[16, 32, 48],\n num_heads=[1, 2, 3],\n depth=[1, 2, 10],\n patch_sizes=[7, 3, 3],\n patch_stride=[4, 2, 2],\n patch_padding=[2, 1, 1],\n stride_kv=[2, 2, 2],\n cls_token=[False, False, True],\n attention_drop_rate=[0.0, 0.0, 0.0],\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n is_training=True,\n use_labels=True,\n num_labels=2,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_sizes = patch_sizes\n self.patch_stride = patch_stride\n self.patch_padding = patch_padding\n self.is_training = is_training\n self.use_labels = use_labels\n self.num_labels = num_labels\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.stride_kv = stride_kv\n self.depth = depth\n self.cls_token = cls_token\n self.attention_drop_rate = attention_drop_rate\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n embedding_size=768,\n q_groups=4,\n k_groups=4,\n v_groups=4,\n post_attention_groups=1,\n intermediate_groups=4,\n output_groups=4,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.embedding_size = embedding_size\n self.q_groups = q_groups\n self.k_groups = k_groups\n self.v_groups = v_groups\n self.post_attention_groups = post_attention_groups\n self.intermediate_groups = intermediate_groups\n self.output_groups = output_groups", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n topic_id: str,\n name: str,\n canonical_name: str,\n language_code: str,\n description: str,\n version: int,\n canonical_story_count: int,\n additional_story_count: int,\n uncategorized_skill_count: int,\n subtopic_count: int,\n total_skill_count: int,\n total_published_node_count: int,\n thumbnail_filename: Optional[str],\n thumbnail_bg_color: Optional[str],\n url_fragment: str,\n published_story_exploration_mapping: Dict[str, List[str]],\n topic_model_created_on: datetime.datetime,\n topic_model_last_updated: datetime.datetime\n ) -> None:\n \"\"\"Constructs a TopicSummary domain object.\n\n Args:\n topic_id: str. The unique id of the topic.\n name: str. The name of the topic.\n canonical_name: str. The canonical name (lowercase) of the topic.\n language_code: str. The language code of the topic.\n description: str. The description of the topic.\n version: int. The version of the topic.\n canonical_story_count: int. The number of canonical stories present\n in the topic.\n additional_story_count: int. The number of additional stories\n present in the topic.\n uncategorized_skill_count: int. The number of uncategorized skills\n in the topic.\n subtopic_count: int. The number of subtopics in the topic.\n total_skill_count: int. The total number of skills in the topic\n (including those that are uncategorized).\n total_published_node_count: int. The total number of chapters\n that are published and associated with the stories of the topic.\n thumbnail_filename: str|None. The filename for the topic thumbnail,\n or None if no filename is provided.\n thumbnail_bg_color: str|None. The background color for the\n thumbnail, or None if no background color provided for\n the thumbnail.\n url_fragment: str. The url fragment of the topic.\n published_story_exploration_mapping: dict(str, list(str)). The\n mappings' keys are the ids of published stories owned by the\n topic and each key maps to a list of the story's linked\n exploration ids.\n topic_model_created_on: datetime.datetime. Date and time when\n the topic model is created.\n topic_model_last_updated: datetime.datetime. Date and time\n when the topic model was last updated.\n \"\"\"\n self.id = topic_id\n self.name = name\n self.description = description\n self.canonical_name = canonical_name\n self.language_code = language_code\n self.version = version\n self.canonical_story_count = canonical_story_count\n self.additional_story_count = additional_story_count\n self.uncategorized_skill_count = uncategorized_skill_count\n self.subtopic_count = subtopic_count\n self.total_skill_count = total_skill_count\n self.total_published_node_count = total_published_node_count\n self.thumbnail_filename = thumbnail_filename\n self.thumbnail_bg_color = thumbnail_bg_color\n self.topic_model_created_on = topic_model_created_on\n self.topic_model_last_updated = topic_model_last_updated\n self.url_fragment = url_fragment\n self.published_story_exploration_mapping = (\n published_story_exploration_mapping)", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@validate_call\n def api_app_versions_v3_get(\n self,\n app_version: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n authored_by: Optional[StrictStr] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n description: Annotated[Optional[StrictStr], Field(description=\"Generally the Git commit message\")] = None,\n git_branch: Optional[StrictStr] = None,\n git_commit: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n parent_app_version: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many AppVersions are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned AppVersions (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockAppVersionV3]:\n \"\"\"List AppVersions matching a filter\n\n List AppVersions matching a filter.\n\n :param app_version: Required when creating\n :type app_version: str\n :param authored_by:\n :type authored_by: str\n :param chart: Required when creating\n :type chart: str\n :param created_at:\n :type created_at: datetime\n :param description: Generally the Git commit message\n :type description: str\n :param git_branch:\n :type git_branch: str\n :param git_commit:\n :type git_commit: str\n :param id:\n :type id: int\n :param parent_app_version:\n :type parent_app_version: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many AppVersions are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned AppVersions (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_app_versions_v3_get_serialize(\n app_version=app_version,\n authored_by=authored_by,\n chart=chart,\n created_at=created_at,\n description=description,\n git_branch=git_branch,\n git_commit=git_commit,\n id=id,\n parent_app_version=parent_app_version,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockAppVersionV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=65536,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_key_value_heads=32,\n hidden_act=\"silu\",\n max_position_embeddings=4096,\n initializer_range=0.02,\n rms_norm_eps=1e-05,\n use_cache=True,\n pad_token_id=None,\n bos_token_id=1,\n eos_token_id=2,\n tie_word_embeddings=False,\n rope_theta=10000.0,\n rope_scaling=None,\n attention_bias=False,\n attention_dropout=0.0,\n model_parallel_size=1,\n swin_norm=False,\n vq_config=None,\n vocabulary_map=None,\n mlp_bias=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.mlp_bias = mlp_bias\n\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.rope_scaling = rope_scaling\n self._rope_scaling_validation()\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n self.model_parallel_size = model_parallel_size\n self.swin_norm = swin_norm\n\n if vq_config is None:\n vq_config = {}\n logger.info(\"vq_config is None. initializing the ChameleonVQConfig with default values.\")\n\n self.vq_config = ChameleonVQVAEConfig(**vq_config)\n\n self.vocabulary_map = vocabulary_map\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n embedding_size=128,\n hidden_size=256,\n num_hidden_layers=12,\n num_attention_heads=4,\n intermediate_size=1024,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n summary_type=\"first\",\n summary_use_proj=True,\n summary_activation=\"gelu\",\n summary_last_dropout=0.1,\n pad_token_id=0,\n position_embedding_type=\"absolute\",\n use_cache=True,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.embedding_size = embedding_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n\n self.summary_type = summary_type\n self.summary_use_proj = summary_use_proj\n self.summary_activation = summary_activation\n self.summary_last_dropout = summary_last_dropout\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=3, # need batch_size != num_hidden_layers\n seq_length=4,\n is_training=False, # for now training is not supported\n use_input_mask=True,\n use_labels=True,\n vocab_size=33,\n output_vocab_size=33,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=2,\n intermediate_size=15,\n dropout=0.1,\n window_size=256,\n initializer_range=0.02,\n n_codes_total=8, # for BarkFineModel\n n_codes_given=1, # for BarkFineModel\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.output_vocab_size = output_vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.window_size = window_size\n self.initializer_range = initializer_range\n self.bos_token_id = output_vocab_size - 1\n self.eos_token_id = output_vocab_size - 1\n self.pad_token_id = output_vocab_size - 1\n\n self.n_codes_total = n_codes_total\n self.n_codes_given = n_codes_given\n\n self.is_encoder_decoder = False", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n position_embedding_type=\"absolute\",\n use_cache=True,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.use_cache = use_cache\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n backbone_config=None,\n backbone=None,\n use_pretrained_backbone=False,\n use_timm_backbone=False,\n backbone_kwargs=None,\n hidden_size=512,\n initializer_range=0.02,\n pool_scales=[1, 2, 3, 6],\n use_auxiliary_head=True,\n auxiliary_loss_weight=0.4,\n auxiliary_in_channels=384,\n auxiliary_channels=256,\n auxiliary_num_convs=1,\n auxiliary_concat_input=False,\n loss_ignore_index=255,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if backbone_config is None and backbone is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\")\n backbone_config = CONFIG_MAPPING[\"resnet\"](out_features=[\"stage1\", \"stage2\", \"stage3\", \"stage4\"])\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.get(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n self.backbone_config = backbone_config\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.use_timm_backbone = use_timm_backbone\n self.backbone_kwargs = backbone_kwargs\n self.hidden_size = hidden_size\n self.initializer_range = initializer_range\n self.pool_scales = pool_scales\n self.use_auxiliary_head = use_auxiliary_head\n self.auxiliary_loss_weight = auxiliary_loss_weight\n self.auxiliary_in_channels = auxiliary_in_channels\n self.auxiliary_channels = auxiliary_channels\n self.auxiliary_num_convs = auxiliary_num_convs\n self.auxiliary_concat_input = auxiliary_concat_input\n self.loss_ignore_index = loss_ignore_index", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(SWITCH_TRANSFORMERS_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqMoEOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n output_router_logits: Optional[bool] = True,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqMoEOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,\n config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for\n labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, SwitchTransformersForConditionalGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/switch-base-8\")\n >>> model = SwitchTransformersForConditionalGeneration.from_pretrained(\"google/switch-base-8\")\n\n >>> # training\n >>> input_ids = tokenizer(\"The <extra_id_0> walks in <extra_id_1> park\", return_tensors=\"pt\").input_ids\n >>> labels = tokenizer(\"<extra_id_0> cute dog <extra_id_1> the <extra_id_2>\", return_tensors=\"pt\").input_ids\n >>> outputs = model(input_ids=input_ids, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> input_ids = tokenizer(\n ... \"summarize: studies have shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> outputs = model.generate(input_ids)\n >>> # . To, let\u2019s say you have a dog. To summarize:\n >>> # Since the model has been trained on MLM, this will output gibberish\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n # Convert encoder inputs in embeddings if needed\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_router_logits=output_router_logits,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, MoEModelOutput):\n encoder_outputs = MoEModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n router_probs=encoder_outputs[3] if len(encoder_outputs) > 3 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n output_router_logits=output_router_logits,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n if self.config.tie_word_embeddings:\n # Rescale output before projecting on vocab\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\n sequence_output = sequence_output * (self.model_dim**-0.5)\n\n lm_logits = self.lm_head(sequence_output)\n\n loss = None\n encoder_z_loss = None\n encoder_aux_loss = None\n decoder_z_loss = None\n decoder_aux_loss = None\n\n if output_router_logits:\n # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder\n if self.encoder.config.encoder_sparse_step > 1:\n encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_outputs[-1])\n encoder_z_loss = router_z_loss_func(encoder_router_logits)\n encoder_router_probs = nn.Softmax(dim=-1)(encoder_router_logits)\n encoder_aux_loss = load_balancing_loss_func(encoder_router_probs, encoder_expert_indexes)\n else:\n encoder_z_loss = 0\n encoder_aux_loss = 0\n\n if self.decoder.config.decoder_sparse_step > 1:\n decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_outputs[-1])\n decoder_z_loss = router_z_loss_func(decoder_router_logits)\n decoder_router_probs = nn.Softmax(dim=-1)(decoder_router_logits)\n decoder_aux_loss = load_balancing_loss_func(decoder_router_probs, decoder_expert_indexes)\n else:\n decoder_z_loss = 0\n decoder_aux_loss = 0\n\n if labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-100)\n # move labels to correct device to enable PP\n labels = labels.to(lm_logits.device)\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))\n\n if output_router_logits:\n z_loss = self.router_z_loss_coef * (encoder_z_loss + decoder_z_loss)\n aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)\n loss = loss + z_loss + aux_loss\n\n if not return_dict:\n output = (lm_logits,)\n if output_router_logits:\n output += (encoder_z_loss, encoder_aux_loss, decoder_z_loss, decoder_aux_loss)\n output += (*decoder_outputs[1:], *encoder_outputs)\n\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqMoEOutput(\n loss=loss,\n logits=lm_logits,\n encoder_z_loss=encoder_z_loss,\n encoder_aux_loss=encoder_aux_loss,\n decoder_z_loss=decoder_z_loss,\n decoder_aux_loss=decoder_aux_loss,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n decoder_router_logits=decoder_outputs.router_probs,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n encoder_router_logits=encoder_outputs.router_probs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=33201,\n d_model=1024,\n d_kv=64,\n d_ff=4096,\n num_layers=24,\n num_decoder_layers=None,\n num_heads=16,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n relative_bias_args=[{\"type\": \"1d\"}, {\"type\": \"horizontal\"}, {\"type\": \"vertical\"}],\n dropout_rate=0.1,\n layer_norm_epsilon=1e-6,\n initializer_factor=1.0,\n feed_forward_proj=\"relu\",\n is_encoder_decoder=True,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n max_2d_position_embeddings=1024,\n image_size=224,\n patch_size=16,\n num_channels=3,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.d_kv = d_kv\n self.d_ff = d_ff\n self.num_layers = num_layers\n self.num_decoder_layers = (\n num_decoder_layers if num_decoder_layers is not None else self.num_layers\n ) # default = symmetry\n self.num_heads = num_heads\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n self.dropout_rate = dropout_rate\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_factor = initializer_factor\n self.feed_forward_proj = feed_forward_proj\n self.use_cache = use_cache\n\n # UDOP attributes\n self.max_2d_position_embeddings = max_2d_position_embeddings\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n if not isinstance(relative_bias_args, list):\n raise TypeError(\"`relative_bias_args` should be a list of dictionaries.\")\n self.relative_bias_args = relative_bias_args\n\n act_info = self.feed_forward_proj.split(\"-\")\n self.dense_act_fn = act_info[-1]\n self.is_gated_act = act_info[0] == \"gated\"\n\n if len(act_info) > 1 and act_info[0] != \"gated\" or len(act_info) > 2:\n raise ValueError(\n f\"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.\"\n \"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. \"\n \"'gated-gelu' or 'relu'\"\n )\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n past_key_values: Optional[List[torch.Tensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n activation_dropout: Optional[float] = 0.1,\n activation_function: Optional[Union[str, Callable]] = \"gelu\",\n vocab_size: Optional[int] = 30522,\n hidden_size: Optional[int] = 1024,\n encoder_ffn_dim: Optional[int] = 4096,\n num_encoder_layers: Optional[int] = 12,\n num_encoder_attention_heads: Optional[int] = 16,\n decoder_ffn_dim: Optional[int] = 4096,\n num_decoder_layers: Optional[int] = 12,\n num_decoder_attention_heads: Optional[int] = 16,\n attention_dropout: Optional[float] = 0.1,\n dropout: Optional[float] = 0.1,\n max_position_embeddings: Optional[int] = 512,\n init_std: Optional[float] = 0.02,\n is_encoder_decoder: Optional[bool] = True,\n add_cross_attention: Optional[bool] = True,\n decoder_start_token_id: Optional[int] = 0,\n ngram: Optional[int] = 2,\n num_buckets: Optional[int] = 32,\n relative_max_distance: Optional[int] = 128,\n disable_ngram_loss: Optional[bool] = False,\n eps: Optional[float] = 0.0,\n use_cache: Optional[bool] = True,\n pad_token_id: Optional[int] = 0,\n bos_token_id: Optional[int] = 1,\n eos_token_id: Optional[int] = 2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.encoder_ffn_dim = encoder_ffn_dim\n self.num_encoder_layers = num_encoder_layers\n self.num_encoder_attention_heads = num_encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.num_decoder_layers = num_decoder_layers\n self.num_decoder_attention_heads = num_decoder_attention_heads\n self.max_position_embeddings = max_position_embeddings\n self.init_std = init_std # Normal(0, this parameter)\n self.activation_function = activation_function\n\n # parameters for xlmprophetnet\n self.ngram = ngram\n self.num_buckets = num_buckets\n self.relative_max_distance = relative_max_distance\n self.disable_ngram_loss = disable_ngram_loss\n self.eps = eps\n\n # 3 Types of Dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.dropout = dropout\n\n self.use_cache = use_cache\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n add_cross_attention=add_cross_attention,\n decoder_start_token_id=decoder_start_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _get_last_batch( # noqa: PLR0913\n self,\n datasource_name: Optional[str] = None,\n data_connector_name: Optional[str] = None,\n data_asset_name: Optional[str] = None,\n batch_request: Optional[BatchRequestBase] = None,\n batch_data: Optional[Any] = None,\n data_connector_query: Optional[dict] = None,\n batch_identifiers: Optional[dict] = None,\n limit: Optional[int] = None,\n index: Optional[Union[int, list, tuple, slice, str]] = None,\n custom_filter_function: Optional[Callable] = None,\n sampling_method: Optional[str] = None,\n sampling_kwargs: Optional[dict] = None,\n partitioner_method: Optional[str] = None,\n partitioner_kwargs: Optional[dict] = None,\n runtime_parameters: Optional[dict] = None,\n query: Optional[str] = None,\n path: Optional[str] = None,\n batch_filter_parameters: Optional[dict] = None,\n batch_spec_passthrough: Optional[dict] = None,\n batch_parameters: Optional[Union[dict, BatchParameters]] = None,\n **kwargs: Optional[dict],\n ) -> Batch:\n result = get_batch_request_from_acceptable_arguments(\n datasource_name=datasource_name,\n data_connector_name=data_connector_name,\n data_asset_name=data_asset_name,\n batch_request=batch_request,\n batch_data=batch_data,\n data_connector_query=data_connector_query,\n batch_identifiers=batch_identifiers,\n limit=limit,\n index=index,\n custom_filter_function=custom_filter_function,\n sampling_method=sampling_method,\n sampling_kwargs=sampling_kwargs,\n partitioner_method=partitioner_method,\n partitioner_kwargs=partitioner_kwargs,\n runtime_parameters=runtime_parameters,\n query=query,\n path=path,\n batch_filter_parameters=batch_filter_parameters,\n batch_spec_passthrough=batch_spec_passthrough,\n batch_parameters=batch_parameters,\n **kwargs,\n )\n datasource_name = result.datasource_name\n\n datasource = self.data_sources.all().get(datasource_name)\n if not datasource:\n raise gx_exceptions.DatasourceError(\n datasource_name,\n \"The given datasource could not be retrieved from the DataContext; \"\n \"please confirm that your configuration is accurate.\",\n )\n\n return datasource.get_batch(batch_request=result)", "smellKey": "S107", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def target_encode_plus(\n self,\n answer: str,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str] = None,\n max_length: Optional[int] = None,\n pad_to_multiple_of: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Prepare a answer string for the model.\n\n Args:\n answer `str`:\n Corresponding answer supervision to the queries for training the model.\n \"\"\"\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n return self._target_encode_plus(\n answer=answer,\n add_special_tokens=add_special_tokens,\n padding_strategy=padding_strategy,\n truncation_strategy=truncation_strategy,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n return_tensors=return_tensors,\n return_token_type_ids=return_token_type_ids,\n return_attention_mask=return_attention_mask,\n return_special_tokens_mask=return_special_tokens_mask,\n return_offsets_mapping=return_offsets_mapping,\n return_length=return_length,\n verbose=verbose,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hass: HomeAssistant,\n name: str,\n switch_entity_id: str,\n sensor_entity_id: str,\n min_humidity: float | None,\n max_humidity: float | None,\n target_humidity: float | None,\n device_class: HumidifierDeviceClass | None,\n min_cycle_duration: timedelta | None,\n dry_tolerance: float,\n wet_tolerance: float,\n keep_alive: timedelta | None,\n initial_state: bool | None,\n away_humidity: int | None,\n away_fixed: bool | None,\n sensor_stale_duration: timedelta | None,\n unique_id: str | None,\n ) -> None:\n \"\"\"Initialize the hygrostat.\"\"\"\n self._name = name\n self._switch_entity_id = switch_entity_id\n self._sensor_entity_id = sensor_entity_id\n self._attr_device_info = async_device_info_to_link_from_entity(\n hass,\n switch_entity_id,\n )\n self._device_class = device_class or HumidifierDeviceClass.HUMIDIFIER\n self._min_cycle_duration = min_cycle_duration\n self._dry_tolerance = dry_tolerance\n self._wet_tolerance = wet_tolerance\n self._keep_alive = keep_alive\n self._state = initial_state\n self._saved_target_humidity = away_humidity or target_humidity\n self._active = False\n self._cur_humidity: float | None = None\n self._humidity_lock = asyncio.Lock()\n self._min_humidity = min_humidity\n self._max_humidity = max_humidity\n self._target_humidity = target_humidity\n if away_humidity:\n self._attr_supported_features |= HumidifierEntityFeature.MODES\n self._away_humidity = away_humidity\n self._away_fixed = away_fixed\n self._sensor_stale_duration = sensor_stale_duration\n self._remove_stale_tracking: Callable[[], None] | None = None\n self._is_away = False\n self._attr_action = HumidifierAction.IDLE\n self._attr_unique_id = unique_id", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope\n\n # in ViT, the seq length equals the number of patches\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=1,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n position_embedding_type=\"absolute\",\n block_per_row=4,\n approx_mode=\"full\",\n initial_prior_first_n_blocks=0,\n initial_prior_diagonal_n_blocks=0,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.type_vocab_size = type_vocab_size\n self.layer_norm_eps = layer_norm_eps\n self.position_embedding_type = position_embedding_type\n self.block_per_row = block_per_row\n self.approx_mode = approx_mode\n self.initial_prior_first_n_blocks = initial_prior_first_n_blocks\n self.initial_prior_diagonal_n_blocks = initial_prior_diagonal_n_blocks", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\"initial_energy\", \"initial_cost\"), [(0, \"0.0\"), (None, \"unknown\")]\n)\n@pytest.mark.parametrize(\n (\"price_entity\", \"fixed_price\"), [(\"sensor.energy_price\", None), (None, 1)]\n)\n@pytest.mark.parametrize(\n (\"usage_sensor_entity_id\", \"cost_sensor_entity_id\", \"flow_type\"),\n [\n (\"sensor.energy_consumption\", \"sensor.energy_consumption_cost\", \"flow_from\"),\n (\n \"sensor.energy_production\",\n \"sensor.energy_production_compensation\",\n \"flow_to\",\n ),\n ],\n)\n@pytest.mark.parametrize(\"energy_state_class\", [\"total\", \"measurement\"])\nasync def test_cost_sensor_price_entity_total(\n frozen_time,\n setup_integration,\n hass: HomeAssistant,\n hass_storage: dict[str, Any],\n hass_ws_client: WebSocketGenerator,\n entity_registry: er.EntityRegistry,\n initial_energy,\n initial_cost,\n price_entity,\n fixed_price,\n usage_sensor_entity_id,\n cost_sensor_entity_id,\n flow_type,\n energy_state_class,\n) -> None:\n \"\"\"Test energy cost price from total type sensor entity.\"\"\"\n\n def _compile_statistics(_):\n with session_scope(hass=hass) as session:\n return compile_statistics(\n hass, session, now, now + timedelta(seconds=0.17)\n ).platform_stats\n\n energy_attributes = {\n ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR,\n ATTR_STATE_CLASS: energy_state_class,\n }\n\n energy_data = data.EnergyManager.default_preferences()\n energy_data[\"energy_sources\"].append(\n {\n \"type\": \"grid\",\n \"flow_from\": [\n {\n \"stat_energy_from\": \"sensor.energy_consumption\",\n \"stat_cost\": None,\n \"entity_energy_price\": price_entity,\n \"number_energy_price\": fixed_price,\n }\n ]\n if flow_type == \"flow_from\"\n else [],\n \"flow_to\": [\n {\n \"stat_energy_to\": \"sensor.energy_production\",\n \"stat_compensation\": None,\n \"entity_energy_price\": price_entity,\n \"number_energy_price\": fixed_price,\n }\n ]\n if flow_type == \"flow_to\"\n else [],\n \"cost_adjustment_day\": 0,\n }\n )\n\n hass_storage[data.STORAGE_KEY] = {\n \"version\": 1,\n \"data\": energy_data,\n }\n\n now = dt_util.utcnow()\n last_reset = dt_util.utc_from_timestamp(0).isoformat()\n last_reset_cost_sensor = now.isoformat()\n\n # Optionally initialize dependent entities\n if initial_energy is not None:\n hass.states.async_set(\n usage_sensor_entity_id,\n initial_energy,\n {**energy_attributes, \"last_reset\": last_reset},\n )\n hass.states.async_set(\"sensor.energy_price\", \"1\")\n\n await setup_integration(hass)\n\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == initial_cost\n assert state.attributes[ATTR_DEVICE_CLASS] == SensorDeviceClass.MONETARY\n if initial_cost != \"unknown\":\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == \"EUR\"\n\n # Optional late setup of dependent entities\n if initial_energy is None:\n hass.states.async_set(\n usage_sensor_entity_id,\n \"0\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"0.0\"\n assert state.attributes[ATTR_DEVICE_CLASS] == SensorDeviceClass.MONETARY\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == \"EUR\"\n\n entry = entity_registry.async_get(cost_sensor_entity_id)\n assert entry\n postfix = \"cost\" if flow_type == \"flow_from\" else \"compensation\"\n assert entry.unique_id == f\"{usage_sensor_entity_id}_grid_{postfix}\"\n assert entry.hidden_by is er.RegistryEntryHider.INTEGRATION\n\n # Energy use bumped to 10 kWh\n frozen_time.tick(TEST_TIME_ADVANCE_INTERVAL)\n hass.states.async_set(\n usage_sensor_entity_id,\n \"10\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"10.0\" # 0 EUR + (10-0) kWh * 1 EUR/kWh = 10 EUR\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n\n # Nothing happens when price changes\n if price_entity is not None:\n hass.states.async_set(price_entity, \"2\")\n await hass.async_block_till_done()\n else:\n energy_data = copy.deepcopy(energy_data)\n energy_data[\"energy_sources\"][0][flow_type][0][\"number_energy_price\"] = 2\n client = await hass_ws_client(hass)\n await client.send_json({\"id\": 5, \"type\": \"energy/save_prefs\", **energy_data})\n msg = await client.receive_json()\n assert msg[\"success\"]\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"10.0\" # 10 EUR + (10-10) kWh * 2 EUR/kWh = 10 EUR\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n\n # Additional consumption is using the new price\n frozen_time.tick(TEST_TIME_ADVANCE_INTERVAL)\n hass.states.async_set(\n usage_sensor_entity_id,\n \"14.5\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"19.0\" # 10 EUR + (14.5-10) kWh * 2 EUR/kWh = 19 EUR\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n\n # Check generated statistics\n await async_wait_recording_done(hass)\n all_statistics = await hass.loop.run_in_executor(None, _compile_statistics, hass)\n statistics = get_statistics_for_entity(all_statistics, cost_sensor_entity_id)\n assert statistics[\"stat\"][\"sum\"] == 19.0\n\n # Energy sensor has a small dip\n frozen_time.tick(TEST_TIME_ADVANCE_INTERVAL)\n hass.states.async_set(\n usage_sensor_entity_id,\n \"14\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"18.0\" # 19 EUR + (14-14.5) kWh * 2 EUR/kWh = 18 EUR\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n\n # Energy sensor is reset, with initial state at 4kWh, 0 kWh is used as zero-point\n frozen_time.tick(TEST_TIME_ADVANCE_INTERVAL)\n last_reset = dt_util.utcnow()\n hass.states.async_set(\n usage_sensor_entity_id,\n \"4\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"8.0\" # 0 EUR + (4-0) kWh * 2 EUR/kWh = 8 EUR\n assert state.attributes[ATTR_LAST_RESET] != last_reset_cost_sensor\n last_reset_cost_sensor = state.attributes[ATTR_LAST_RESET]\n\n # Energy use bumped to 10 kWh\n frozen_time.tick(TEST_TIME_ADVANCE_INTERVAL)\n hass.states.async_set(\n usage_sensor_entity_id,\n \"10\",\n {**energy_attributes, \"last_reset\": last_reset},\n )\n await hass.async_block_till_done()\n state = hass.states.get(cost_sensor_entity_id)\n assert state.state == \"20.0\" # 8 EUR + (10-4) kWh * 2 EUR/kWh = 20 EUR\n assert state.attributes[ATTR_LAST_RESET] == last_reset_cost_sensor\n\n # Check generated statistics\n await async_wait_recording_done(hass)\n all_statistics = await hass.loop.run_in_executor(None, _compile_statistics, hass)\n statistics = get_statistics_for_entity(all_statistics, cost_sensor_entity_id)\n assert statistics[\"stat\"][\"sum\"] == 38.0", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "def __init__(\n self,\n file_like=None,\n read_size=0,\n use_list=True,\n raw=False,\n timestamp=0,\n strict_map_key=True,\n object_hook=None,\n object_pairs_hook=None,\n list_hook=None,\n unicode_errors=None,\n max_buffer_size=100 * 1024 * 1024,\n ext_hook=ExtType,\n max_str_len=-1,\n max_bin_len=-1,\n max_array_len=-1,\n max_map_len=-1,\n max_ext_len=-1,\n ):\n if unicode_errors is None:\n unicode_errors = \"strict\"\n\n if file_like is None:\n self._feeding = True\n else:\n if not callable(file_like.read):\n raise TypeError(\"`file_like.read` must be callable\")\n self.file_like = file_like\n self._feeding = False\n\n #: array of bytes fed.\n self._buffer = bytearray()\n #: Which position we currently reads\n self._buff_i = 0\n\n # When Unpacker is used as an iterable, between the calls to next(),\n # the buffer is not \"consumed\" completely, for efficiency sake.\n # Instead, it is done sloppily. To make sure we raise BufferFull at\n # the correct moments, we have to keep track of how sloppy we were.\n # Furthermore, when the buffer is incomplete (that is: in the case\n # we raise an OutOfData) we need to rollback the buffer to the correct\n # state, which _buf_checkpoint records.\n self._buf_checkpoint = 0\n\n if not max_buffer_size:\n max_buffer_size = 2 ** 31 - 1\n if max_str_len == -1:\n max_str_len = max_buffer_size\n if max_bin_len == -1:\n max_bin_len = max_buffer_size\n if max_array_len == -1:\n max_array_len = max_buffer_size\n if max_map_len == -1:\n max_map_len = max_buffer_size // 2\n if max_ext_len == -1:\n max_ext_len = max_buffer_size\n\n self._max_buffer_size = max_buffer_size\n if read_size > self._max_buffer_size:\n raise ValueError(\"read_size must be smaller than max_buffer_size\")\n self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)\n self._raw = bool(raw)\n self._strict_map_key = bool(strict_map_key)\n self._unicode_errors = unicode_errors\n self._use_list = use_list\n if not (0 <= timestamp <= 3):\n raise ValueError(\"timestamp must be 0..3\")\n self._timestamp = timestamp\n self._list_hook = list_hook\n self._object_hook = object_hook\n self._object_pairs_hook = object_pairs_hook\n self._ext_hook = ext_hook\n self._max_str_len = max_str_len\n self._max_bin_len = max_bin_len\n self._max_array_len = max_array_len\n self._max_map_len = max_map_len\n self._max_ext_len = max_ext_len\n self._stream_offset = 0\n\n if list_hook is not None and not callable(list_hook):\n raise TypeError(\"`list_hook` is not callable\")\n if object_hook is not None and not callable(object_hook):\n raise TypeError(\"`object_hook` is not callable\")\n if object_pairs_hook is not None and not callable(object_pairs_hook):\n raise TypeError(\"`object_pairs_hook` is not callable\")\n if object_hook is not None and object_pairs_hook is not None:\n raise TypeError(\n \"object_pairs_hook and object_hook are mutually \" \"exclusive\"\n )\n if not callable(ext_hook):\n raise TypeError(\"`ext_hook` is not callable\")", "smellKey": "S107", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50000,\n embedding_size=None,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=1536,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n rotary_value=False,\n use_cache=True,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.embedding_size = hidden_size if embedding_size is None else embedding_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.rotary_value = rotary_value\n self.use_cache = use_cache", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n min_resolution=56,\n max_resolution=1024,\n min_pixels=56 * 56,\n max_pixels=28 * 28 * 1280,\n do_normalize=True,\n image_mean=OPENAI_CLIP_MEAN,\n image_std=OPENAI_CLIP_STD,\n do_resize=True,\n patch_size=14,\n temporal_patch_size=2,\n merge_size=2,\n do_convert_rgb=True,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.num_channels = num_channels\n self.image_mean = OPENAI_CLIP_MEAN\n self.image_std = OPENAI_CLIP_STD\n self.min_pixels = min_pixels\n self.max_pixels = max_pixels\n self.patch_size = patch_size\n self.temporal_patch_size = temporal_patch_size\n self.merge_size = merge_size\n self.do_resize = do_resize\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n vocab_size=300,\n hidden_size=28,\n num_attention_heads=2,\n num_labels=2,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n num_qa_labels=30,\n num_object_labels=16,\n num_attr_labels=4,\n num_visual_features=10,\n l_layers=2,\n x_layers=1,\n r_layers=1,\n visual_feat_dim=128,\n visual_pos_dim=4,\n visual_loss_normalizer=6.67,\n seq_length=20,\n batch_size=8,\n is_training=True,\n task_matched=True,\n task_mask_lm=True,\n task_obj_predict=True,\n task_qa=True,\n visual_obj_loss=True,\n visual_attr_loss=True,\n visual_feat_loss=True,\n use_token_type_ids=True,\n use_lang_mask=True,\n output_attentions=False,\n output_hidden_states=False,\n scope=None,\n ):\n self.parent = parent\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_labels = num_labels\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.pad_token_id = pad_token_id\n self.num_qa_labels = num_qa_labels\n self.num_object_labels = num_object_labels\n self.num_attr_labels = num_attr_labels\n self.l_layers = l_layers\n self.x_layers = x_layers\n self.r_layers = r_layers\n self.visual_feat_dim = visual_feat_dim\n self.visual_pos_dim = visual_pos_dim\n self.visual_loss_normalizer = visual_loss_normalizer\n self.seq_length = seq_length\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_lang_mask = use_lang_mask\n self.task_matched = task_matched\n self.task_mask_lm = task_mask_lm\n self.task_obj_predict = task_obj_predict\n self.task_qa = task_qa\n self.visual_obj_loss = visual_obj_loss\n self.visual_attr_loss = visual_attr_loss\n self.visual_feat_loss = visual_feat_loss\n self.num_visual_features = num_visual_features\n self.use_token_type_ids = use_token_type_ids\n self.output_attentions = output_attentions\n self.output_hidden_states = output_hidden_states\n self.scope = scope\n self.num_hidden_layers = {\"vision\": r_layers, \"cross_encoder\": x_layers, \"language\": l_layers}", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, cfg, pre_init=None, reset_halt_cmd=DEFAULT_OPENOCD_RESET_HALT_CMD,\n pre_load=None, load_cmd=None, verify_cmd=None, post_verify=None,\n do_verify=False, do_verify_only=False,\n tui=None, config=None, serial=None, use_elf=True,\n no_halt=False, no_init=False, no_targets=False,\n tcl_port=DEFAULT_OPENOCD_TCL_PORT,\n telnet_port=DEFAULT_OPENOCD_TELNET_PORT,\n gdb_port=DEFAULT_OPENOCD_GDB_PORT,\n gdb_init=None, no_load=False):\n super().__init__(cfg)\n\n support = path.join(cfg.board_dir, 'support')\n\n if not config:\n default = path.join(support, 'openocd.cfg')\n default2 = path.join(support, 'download_all.gdb')\n default3 = path.join(support, 'appli_dl_cmd.gdb')\n default4 = path.join(support, 'appli_debug_cmd.gdb')\n if path.exists(default):\n config = [default]\n gdb_commands = [default2]\n gdb_commands2 = [default3]\n gdb_commands_deb = [default4]\n self.openocd_config = config\n self.gdb_cmds = gdb_commands\n self.gdb_cmds2 = gdb_commands2\n self.gdb_cmds_deb = gdb_commands_deb\n\n search_args = []\n if path.exists(support):\n search_args.append('-s')\n search_args.append(support)\n\n if self.openocd_config is not None:\n for i in self.openocd_config:\n if path.exists(i) and not path.samefile(path.dirname(i), support):\n search_args.append('-s')\n search_args.append(path.dirname(i))\n\n if cfg.openocd_search is not None:\n for p in cfg.openocd_search:\n search_args.extend(['-s', p])\n self.openocd_cmd = [cfg.openocd or 'openocd'] + search_args\n # openocd doesn't cope with Windows path names, so convert\n # them to POSIX style just to be sure.\n self.elf_name = Path(cfg.elf_file).as_posix()\n self.pre_init = pre_init or []\n self.reset_halt_cmd = reset_halt_cmd\n self.pre_load = pre_load or []\n self.load_cmd = load_cmd\n self.verify_cmd = verify_cmd\n self.post_verify = post_verify or []\n self.do_verify = do_verify or False\n self.do_verify_only = do_verify_only or False\n self.tcl_port = tcl_port\n self.telnet_port = telnet_port\n self.gdb_port = gdb_port\n self.gdb_cmd = [cfg.gdb] if cfg.gdb else None\n self.tui_arg = ['-tui'] if tui else []\n self.halt_arg = [] if no_halt else ['-c halt']\n self.init_arg = [] if no_init else ['-c init']\n self.targets_arg = [] if no_targets else ['-c targets']\n self.serial = ['-c set _ZEPHYR_BOARD_SERIAL ' + serial] if serial else []\n self.use_elf = use_elf\n self.gdb_init = gdb_init\n self.load_arg = [] if no_load else ['-ex', 'load']", "smellKey": "S107", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def __init__(self, max_pool_size=MAX_POOL_SIZE,\n min_pool_size=MIN_POOL_SIZE,\n max_idle_time_seconds=MAX_IDLE_TIME_SEC, connect_timeout=None,\n socket_timeout=None, wait_queue_timeout=WAIT_QUEUE_TIMEOUT,\n wait_queue_multiple=None, ssl_context=None,\n ssl_match_hostname=True, socket_keepalive=True,\n event_listeners=None, appname=None, driver=None,\n compression_settings=None):\n\n self.__max_pool_size = max_pool_size\n self.__min_pool_size = min_pool_size\n self.__max_idle_time_seconds = max_idle_time_seconds\n self.__connect_timeout = connect_timeout\n self.__socket_timeout = socket_timeout\n self.__wait_queue_timeout = wait_queue_timeout\n self.__wait_queue_multiple = wait_queue_multiple\n self.__ssl_context = ssl_context\n self.__ssl_match_hostname = ssl_match_hostname\n self.__socket_keepalive = socket_keepalive\n self.__event_listeners = event_listeners\n self.__appname = appname\n self.__driver = driver\n self.__compression_settings = compression_settings\n self.__metadata = copy.deepcopy(_METADATA)\n if appname:\n self.__metadata['application'] = {'name': appname}\n\n # Combine the \"driver\" MongoClient option with PyMongo's info, like:\n # {\n # 'driver': {\n # 'name': 'PyMongo|MyDriver',\n # 'version': '3.7.0|1.2.3',\n # },\n # 'platform': 'CPython 3.6.0|MyPlatform'\n # }\n if driver:\n if driver.name:\n self.__metadata['driver']['name'] = \"%s|%s\" % (\n _METADATA['driver']['name'], driver.name)\n if driver.version:\n self.__metadata['driver']['version'] = \"%s|%s\" % (\n _METADATA['driver']['version'], driver.version)\n if driver.platform:\n self.__metadata['platform'] = \"%s|%s\" % (\n _METADATA['platform'], driver.platform)", "smellKey": "S107", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "def __init__(\n self,\n param_decls: t.Optional[t.Sequence[str]] = None,\n show_default: t.Union[bool, str, None] = None,\n prompt: t.Union[bool, str] = False,\n confirmation_prompt: t.Union[bool, str] = False,\n prompt_required: bool = True,\n hide_input: bool = False,\n is_flag: t.Optional[bool] = None,\n flag_value: t.Optional[t.Any] = None,\n multiple: bool = False,\n count: bool = False,\n allow_from_autoenv: bool = True,\n type: t.Optional[t.Union[types.ParamType, t.Any]] = None,\n help: t.Optional[str] = None,\n hidden: bool = False,\n show_choices: bool = True,\n show_envvar: bool = False,\n **attrs: t.Any,\n ) -> None:\n if help:\n help = inspect.cleandoc(help)\n\n default_is_missing = \"default\" not in attrs\n super().__init__(param_decls, type=type, multiple=multiple, **attrs)\n\n if prompt is True:\n if self.name is None:\n raise TypeError(\"'name' is required with 'prompt=True'.\")\n\n prompt_text: t.Optional[str] = self.name.replace(\"_\", \" \").capitalize()\n elif prompt is False:\n prompt_text = None\n else:\n prompt_text = prompt\n\n self.prompt = prompt_text\n self.confirmation_prompt = confirmation_prompt\n self.prompt_required = prompt_required\n self.hide_input = hide_input\n self.hidden = hidden\n\n # If prompt is enabled but not required, then the option can be\n # used as a flag to indicate using prompt or flag_value.\n self._flag_needs_value = self.prompt is not None and not self.prompt_required\n\n if is_flag is None:\n if flag_value is not None:\n # Implicitly a flag because flag_value was set.\n is_flag = True\n elif self._flag_needs_value:\n # Not a flag, but when used as a flag it shows a prompt.\n is_flag = False\n else:\n # Implicitly a flag because flag options were given.\n is_flag = bool(self.secondary_opts)\n elif is_flag is False and not self._flag_needs_value:\n # Not a flag, and prompt is not enabled, can be used as a\n # flag if flag_value is set.\n self._flag_needs_value = flag_value is not None\n\n self.default: t.Union[t.Any, t.Callable[[], t.Any]]\n\n if is_flag and default_is_missing and not self.required:\n if multiple:\n self.default = ()\n else:\n self.default = False\n\n if flag_value is None:\n flag_value = not self.default\n\n self.type: types.ParamType\n if is_flag and type is None:\n # Re-guess the type from the flag value instead of the\n # default.\n self.type = types.convert_type(None, flag_value)\n\n self.is_flag: bool = is_flag\n self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)\n self.flag_value: t.Any = flag_value\n\n # Counting\n self.count = count\n if count:\n if type is None:\n self.type = types.IntRange(min=0)\n if default_is_missing:\n self.default = 0\n\n self.allow_from_autoenv = allow_from_autoenv\n self.help = help\n self.show_default = show_default\n self.show_choices = show_choices\n self.show_envvar = show_envvar\n\n if __debug__:\n if self.nargs == -1:\n raise TypeError(\"nargs=-1 is not supported for options.\")\n\n if self.prompt and self.is_flag and not self.is_bool_flag:\n raise TypeError(\"'prompt' is not valid for non-boolean flag.\")\n\n if not self.is_bool_flag and self.secondary_opts:\n raise TypeError(\"Secondary flag is not valid for non-boolean flag.\")\n\n if self.is_bool_flag and self.hide_input and self.prompt is not None:\n raise TypeError(\n \"'prompt' with 'hide_input' is not valid for boolean flag.\"\n )\n\n if self.count:\n if self.multiple:\n raise TypeError(\"'count' is not valid with 'multiple'.\")\n\n if self.is_flag:\n raise TypeError(\"'count' is not valid with 'is_flag'.\")", "smellKey": "S107", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=36000,\n max_position_embeddings=1280,\n d_model=1024,\n d_ff=8192,\n d_ext=4096,\n d_spout=128,\n num_switch_layers=10,\n num_ext_layers=0,\n num_heads=16,\n num_experts=16,\n expert_capacity=128,\n dropout_rate=0.0,\n layer_norm_epsilon=1e-5,\n router_bias=False,\n router_jitter_noise=0.0,\n router_dtype=\"float32\",\n router_ignore_padding_tokens=False,\n output_hidden_states=False,\n output_attentions=False,\n initializer_factor=0.002,\n output_router_logits=False,\n use_cache=True,\n separator_token_id=35998,\n pad_token_id=35995,\n eos_token_id=35999,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.d_ff = d_ff\n self.d_ext = d_ext\n self.d_spout = d_spout\n self.num_switch_layers = num_switch_layers\n self.num_ext_layers = num_ext_layers\n self.num_layers = num_switch_layers + num_ext_layers\n self.num_heads = num_heads\n self.num_experts = num_experts\n self.expert_capacity = expert_capacity\n self.dropout_rate = dropout_rate\n self.layer_norm_epsilon = layer_norm_epsilon\n self.router_bias = router_bias\n self.router_jitter_noise = router_jitter_noise\n self.router_dtype = router_dtype\n self.router_ignore_padding_tokens = router_ignore_padding_tokens\n self.output_hidden_states = output_hidden_states\n self.output_attentions = output_attentions\n self.initializer_factor = initializer_factor\n self.output_router_logits = output_router_logits\n self.use_cache = use_cache\n\n super().__init__(\n separator_token_id=separator_token_id,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, XLMRobertaForCausalLM, AutoConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config = AutoConfig.from_pretrained(\"FacebookAI/roberta-base\")\n >>> config.is_decoder = True\n >>> model = XLMRobertaForCausalLM.from_pretrained(\"FacebookAI/roberta-base\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if labels is not None:\n use_cache = False\n\n outputs = self.roberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(prediction_scores.device)\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n do_resize: bool = True,\n size: Dict[str, int] = None,\n mask_size: Dict[str, int] = None,\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n do_rescale: bool = True,\n rescale_factor: Union[int, float] = 1 / 255,\n do_normalize: bool = True,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: bool = True,\n pad_size: int = None,\n mask_pad_size: int = None,\n do_convert_rgb: bool = True,\n **kwargs,\n ) -> None:\n super().__init__(**kwargs)\n size = size if size is not None else {\"longest_edge\": 1024}\n size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size\n\n pad_size = pad_size if pad_size is not None else {\"height\": 1024, \"width\": 1024}\n pad_size = get_size_dict(pad_size, default_to_square=True)\n\n mask_size = mask_size if mask_size is not None else {\"longest_edge\": 256}\n mask_size = (\n get_size_dict(max_size=mask_size, default_to_square=False)\n if not isinstance(mask_size, dict)\n else mask_size\n )\n\n mask_pad_size = mask_pad_size if mask_pad_size is not None else {\"height\": 256, \"width\": 256}\n mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)\n\n self.do_resize = do_resize\n self.size = size\n self.mask_size = mask_size\n self.resample = resample\n self.do_rescale = do_rescale\n self.rescale_factor = rescale_factor\n self.do_normalize = do_normalize\n self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN\n self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD\n self.do_pad = do_pad\n self.pad_size = pad_size\n self.mask_pad_size = mask_pad_size\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, BlenderbotSmallModel\n\n >>> model = BlenderbotSmallModel.from_pretrained(\"facebook/blenderbot_small-90M\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/blenderbot_small-90M\")\n\n >>> inputs = tokenizer(\"Studies have been shown that owning a dog is good for you\", return_tensors=\"pt\")\n >>> decoder_inputs = tokenizer(\"Studies show that\", return_tensors=\"pt\") # Batch size 1\n >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)\n\n >>> last_hidden_states = outputs.last_hidden_state\n >>> list(last_hidden_states.shape)\n [1, 3, 512]\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqTSModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n past_values: torch.Tensor,\n past_time_features: torch.Tensor,\n past_observed_mask: torch.Tensor,\n static_categorical_features: Optional[torch.Tensor] = None,\n static_real_features: Optional[torch.Tensor] = None,\n future_values: Optional[torch.Tensor] = None,\n future_time_features: Optional[torch.Tensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n output_hidden_states: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n use_cache: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Seq2SeqTSModelOutput, Tuple]:\n r\"\"\"\n Returns:\n\n Examples:\n\n ```python\n >>> from huggingface_hub import hf_hub_download\n >>> import torch\n >>> from transformers import TimeSeriesTransformerModel\n\n >>> file = hf_hub_download(\n ... repo_id=\"hf-internal-testing/tourism-monthly-batch\", filename=\"train-batch.pt\", repo_type=\"dataset\"\n ... )\n >>> batch = torch.load(file)\n\n >>> model = TimeSeriesTransformerModel.from_pretrained(\"huggingface/time-series-transformer-tourism-monthly\")\n\n >>> # during training, one provides both past and future values\n >>> # as well as possible additional features\n >>> outputs = model(\n ... past_values=batch[\"past_values\"],\n ... past_time_features=batch[\"past_time_features\"],\n ... past_observed_mask=batch[\"past_observed_mask\"],\n ... static_categorical_features=batch[\"static_categorical_features\"],\n ... static_real_features=batch[\"static_real_features\"],\n ... future_values=batch[\"future_values\"],\n ... future_time_features=batch[\"future_time_features\"],\n ... )\n\n >>> last_hidden_state = outputs.last_hidden_state\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_inputs, loc, scale, static_feat = self.create_network_inputs(\n past_values=past_values,\n past_time_features=past_time_features,\n past_observed_mask=past_observed_mask,\n static_categorical_features=static_categorical_features,\n static_real_features=static_real_features,\n future_values=future_values,\n future_time_features=future_time_features,\n )\n\n if encoder_outputs is None:\n enc_input = transformer_inputs[:, : self.config.context_length, ...]\n encoder_outputs = self.encoder(\n inputs_embeds=enc_input,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n dec_input = transformer_inputs[:, self.config.context_length :, ...]\n decoder_outputs = self.decoder(\n inputs_embeds=dec_input,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs + (loc, scale, static_feat)\n\n return Seq2SeqTSModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n loc=loc,\n scale=scale,\n static_features=static_feat,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_roles_v3_get(\n self,\n auto_assign_all_users: Annotated[Optional[StrictBool], Field(description=\"When true, Sherlock will automatically assign all users to this role who do not already have a role assignment\")] = None,\n can_be_glass_broken_by_role: Optional[StrictInt] = None,\n created_at: Optional[datetime] = None,\n default_glass_break_duration: Optional[StrictStr] = None,\n grants_broad_institute_group: Optional[StrictStr] = None,\n grants_dev_azure_account: Optional[StrictBool] = None,\n grants_dev_azure_directory_roles: Optional[StrictBool] = None,\n grants_dev_azure_group: Optional[StrictStr] = None,\n grants_dev_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_dev_firecloud_group: Optional[StrictStr] = None,\n grants_prod_azure_account: Optional[StrictBool] = None,\n grants_prod_azure_directory_roles: Optional[StrictBool] = None,\n grants_prod_azure_group: Optional[StrictStr] = None,\n grants_prod_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_prod_firecloud_group: Optional[StrictStr] = None,\n grants_qa_firecloud_folder_owner: Optional[StrictStr] = None,\n grants_qa_firecloud_group: Optional[StrictStr] = None,\n grants_sherlock_super_admin: Optional[StrictBool] = None,\n id: Optional[StrictInt] = None,\n name: Optional[StrictStr] = None,\n suspend_non_suitable_users: Annotated[Optional[StrictBool], Field(description=\"When true, the \\\"suspended\\\" field on role assignments will be computed by Sherlock based on suitability instead of being a mutable API field\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Roles are returned (default 0, no limit)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Roles (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> List[SherlockRoleV3]:\n \"\"\"List Roles matching a filter\n\n List Roles matching a filter.\n\n :param auto_assign_all_users: When true, Sherlock will automatically assign all users to this role who do not already have a role assignment\n :type auto_assign_all_users: bool\n :param can_be_glass_broken_by_role:\n :type can_be_glass_broken_by_role: int\n :param created_at:\n :type created_at: datetime\n :param default_glass_break_duration:\n :type default_glass_break_duration: str\n :param grants_broad_institute_group:\n :type grants_broad_institute_group: str\n :param grants_dev_azure_account:\n :type grants_dev_azure_account: bool\n :param grants_dev_azure_directory_roles:\n :type grants_dev_azure_directory_roles: bool\n :param grants_dev_azure_group:\n :type grants_dev_azure_group: str\n :param grants_dev_firecloud_folder_owner:\n :type grants_dev_firecloud_folder_owner: str\n :param grants_dev_firecloud_group:\n :type grants_dev_firecloud_group: str\n :param grants_prod_azure_account:\n :type grants_prod_azure_account: bool\n :param grants_prod_azure_directory_roles:\n :type grants_prod_azure_directory_roles: bool\n :param grants_prod_azure_group:\n :type grants_prod_azure_group: str\n :param grants_prod_firecloud_folder_owner:\n :type grants_prod_firecloud_folder_owner: str\n :param grants_prod_firecloud_group:\n :type grants_prod_firecloud_group: str\n :param grants_qa_firecloud_folder_owner:\n :type grants_qa_firecloud_folder_owner: str\n :param grants_qa_firecloud_group:\n :type grants_qa_firecloud_group: str\n :param grants_sherlock_super_admin:\n :type grants_sherlock_super_admin: bool\n :param id:\n :type id: int\n :param name:\n :type name: str\n :param suspend_non_suitable_users: When true, the \\\"suspended\\\" field on role assignments will be computed by Sherlock based on suitability instead of being a mutable API field\n :type suspend_non_suitable_users: bool\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many Roles are returned (default 0, no limit)\n :type limit: int\n :param offset: Control the offset for the returned Roles (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_roles_v3_get_serialize(\n auto_assign_all_users=auto_assign_all_users,\n can_be_glass_broken_by_role=can_be_glass_broken_by_role,\n created_at=created_at,\n default_glass_break_duration=default_glass_break_duration,\n grants_broad_institute_group=grants_broad_institute_group,\n grants_dev_azure_account=grants_dev_azure_account,\n grants_dev_azure_directory_roles=grants_dev_azure_directory_roles,\n grants_dev_azure_group=grants_dev_azure_group,\n grants_dev_firecloud_folder_owner=grants_dev_firecloud_folder_owner,\n grants_dev_firecloud_group=grants_dev_firecloud_group,\n grants_prod_azure_account=grants_prod_azure_account,\n grants_prod_azure_directory_roles=grants_prod_azure_directory_roles,\n grants_prod_azure_group=grants_prod_azure_group,\n grants_prod_firecloud_folder_owner=grants_prod_firecloud_folder_owner,\n grants_prod_firecloud_group=grants_prod_firecloud_group,\n grants_qa_firecloud_folder_owner=grants_qa_firecloud_folder_owner,\n grants_qa_firecloud_group=grants_qa_firecloud_group,\n grants_sherlock_super_admin=grants_sherlock_super_admin,\n id=id,\n name=name,\n suspend_non_suitable_users=suspend_non_suitable_users,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockRoleV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n ).data", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@validate_call\n def api_database_instances_v3_get_with_http_info(\n self,\n chart_release: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n default_database: Annotated[Optional[StrictStr], Field(description=\"When creating, defaults to the chart name\")] = None,\n google_project: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google'\")] = None,\n id: Optional[StrictInt] = None,\n instance_name: Annotated[Optional[StrictStr], Field(description=\"Required if platform is 'google' or 'azure'\")] = None,\n platform: Annotated[Optional[StrictStr], Field(description=\"'google', 'azure', or default 'kubernetes'\")] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many DatabaseInstances are returned (default 0, meaning all)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned DatabaseInstances (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockDatabaseInstanceV3]]:\n \"\"\"List DatabaseInstances matching a filter\n\n List DatabaseInstances matching a filter.\n\n :param chart_release: Required when creating\n :type chart_release: str\n :param created_at:\n :type created_at: datetime\n :param default_database: When creating, defaults to the chart name\n :type default_database: str\n :param google_project: Required if platform is 'google'\n :type google_project: str\n :param id:\n :type id: int\n :param instance_name: Required if platform is 'google' or 'azure'\n :type instance_name: str\n :param platform: 'google', 'azure', or default 'kubernetes'\n :type platform: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many DatabaseInstances are returned (default 0, meaning all)\n :type limit: int\n :param offset: Control the offset for the returned DatabaseInstances (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_database_instances_v3_get_serialize(\n chart_release=chart_release,\n created_at=created_at,\n default_database=default_database,\n google_project=google_project,\n id=id,\n instance_name=instance_name,\n platform=platform,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockDatabaseInstanceV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n projection_dim=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n bos_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = scope\n self.bos_token_id = bos_token_id", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@abstractmethod\n def query(\n self,\n projects: Sequence[Project],\n retention_window_start: datetime | None,\n group_queryset: BaseQuerySet,\n environments: Sequence[Environment] | None,\n sort_by: str,\n limit: int,\n cursor: Cursor | None,\n count_hits: bool,\n paginator_options: Mapping[str, Any] | None,\n search_filters: Sequence[SearchFilter] | None,\n date_from: datetime | None,\n date_to: datetime | None,\n max_hits: int | None = None,\n referrer: str | None = None,\n actor: Any | None = None,\n aggregate_kwargs: TrendsSortWeights | None = None,\n use_group_snuba_dataset: bool = False,\n ) -> CursorResult[Group]:\n \"\"\"This function runs your actual query and returns the results\n We usually return a paginator object, which contains the results and the number of hits\"\"\"\n raise NotImplementedError", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n *,\n data=None,\n disabled_by=None,\n domain=\"test\",\n entry_id=None,\n minor_version=1,\n options=None,\n pref_disable_new_entities=None,\n pref_disable_polling=None,\n reason=None,\n source=config_entries.SOURCE_USER,\n state=None,\n title=\"Mock Title\",\n unique_id=None,\n version=1,\n ) -> None:\n \"\"\"Initialize a mock config entry.\"\"\"\n kwargs = {\n \"data\": data or {},\n \"disabled_by\": disabled_by,\n \"domain\": domain,\n \"entry_id\": entry_id or ulid_util.ulid_now(),\n \"minor_version\": minor_version,\n \"options\": options or {},\n \"pref_disable_new_entities\": pref_disable_new_entities,\n \"pref_disable_polling\": pref_disable_polling,\n \"title\": title,\n \"unique_id\": unique_id,\n \"version\": version,\n }\n if source is not None:\n kwargs[\"source\"] = source\n if state is not None:\n kwargs[\"state\"] = state\n super().__init__(**kwargs)\n if reason is not None:\n object.__setattr__(self, \"reason\", reason)", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple, TFSeq2SeqModelOutput]:\n r\"\"\"\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, TFT5Model\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google-t5/t5-small\")\n >>> model = TFT5Model.from_pretrained(\"google-t5/t5-small\")\n\n >>> input_ids = tokenizer(\n ... \"Studies have been shown that owning a dog is good for you\", return_tensors=\"tf\"\n ... ).input_ids # Batch size 1\n >>> decoder_input_ids = tokenizer(\"Studies show that\", return_tensors=\"tf\").input_ids # Batch size 1\n\n >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.\n >>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.\n >>> decoder_input_ids = model._shift_right(decoder_input_ids)\n\n >>> # forward pass\n >>> outputs = model(input_ids, decoder_input_ids=decoder_input_ids)\n >>> last_hidden_states = outputs.last_hidden_state\n ```\"\"\"\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n warnings.warn(_HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids,\n attention_mask=attention_mask,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n past_key_values=None,\n use_cache=False,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n hidden_states = encoder_outputs[0]\n\n # Decode\n decoder_outputs = self.decoder(\n decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n head_mask=decoder_head_mask,\n encoder_head_mask=head_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n past = decoder_outputs[1] if use_cache else None\n\n if not return_dict:\n if past_key_values is not None:\n decoder_outputs = decoder_outputs[:1] + (past,) + decoder_outputs[2:]\n return decoder_outputs + encoder_outputs\n\n return TFSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=past,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BIGBIRD_PEGASUS_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=_EXPECTED_OUTPUT_SHAPE,\n )\n # Copied from transformers.models.bart.modeling_bart.BartModel.forward with Bart->BigBirdPegasus\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqModelOutput]:\n # different to other models, BigBirdPegasus automatically creates decoder_input_ids from\n # input_ids if no decoder_input_ids are provided\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n if input_ids is None:\n raise ValueError(\n \"If no `decoder_input_ids` or `decoder_inputs_embeds` are \"\n \"passed, `input_ids` cannot be `None`. Please pass either \"\n \"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.\"\n )\n\n decoder_input_ids = shift_tokens_right(\n input_ids, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, host='localhost', port=6379,\n db=0, password=None, socket_timeout=None,\n socket_connect_timeout=None,\n socket_keepalive=None, socket_keepalive_options=None,\n connection_pool=None, unix_socket_path=None,\n encoding='utf-8', encoding_errors='strict',\n charset=None, errors=None,\n decode_responses=False, retry_on_timeout=False,\n ssl=False, ssl_keyfile=None, ssl_certfile=None,\n ssl_cert_reqs='required', ssl_ca_certs=None,\n ssl_check_hostname=False,\n max_connections=None, single_connection_client=False,\n health_check_interval=0, client_name=None, username=None):\n if not connection_pool:\n if charset is not None:\n warnings.warn(DeprecationWarning(\n '\"charset\" is deprecated. Use \"encoding\" instead'))\n encoding = charset\n if errors is not None:\n warnings.warn(DeprecationWarning(\n '\"errors\" is deprecated. Use \"encoding_errors\" instead'))\n encoding_errors = errors\n\n kwargs = {\n 'db': db,\n 'username': username,\n 'password': password,\n 'socket_timeout': socket_timeout,\n 'encoding': encoding,\n 'encoding_errors': encoding_errors,\n 'decode_responses': decode_responses,\n 'retry_on_timeout': retry_on_timeout,\n 'max_connections': max_connections,\n 'health_check_interval': health_check_interval,\n 'client_name': client_name\n }\n # based on input, setup appropriate connection args\n if unix_socket_path is not None:\n kwargs.update({\n 'path': unix_socket_path,\n 'connection_class': UnixDomainSocketConnection\n })\n else:\n # TCP specific options\n kwargs.update({\n 'host': host,\n 'port': port,\n 'socket_connect_timeout': socket_connect_timeout,\n 'socket_keepalive': socket_keepalive,\n 'socket_keepalive_options': socket_keepalive_options,\n })\n\n if ssl:\n kwargs.update({\n 'connection_class': SSLConnection,\n 'ssl_keyfile': ssl_keyfile,\n 'ssl_certfile': ssl_certfile,\n 'ssl_cert_reqs': ssl_cert_reqs,\n 'ssl_ca_certs': ssl_ca_certs,\n 'ssl_check_hostname': ssl_check_hostname,\n })\n connection_pool = ConnectionPool(**kwargs)\n self.connection_pool = connection_pool\n self.connection = None\n if single_connection_client:\n self.connection = self.connection_pool.get_connection('_')\n\n self.response_callbacks = CaseInsensitiveDict(\n self.__class__.RESPONSE_CALLBACKS)", "smellKey": "S107", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "@validate_call\n def api_deploy_hooks_slack_v3_get_with_http_info(\n self,\n created_at: Optional[datetime] = None,\n id: Optional[StrictInt] = None,\n mention_people: Optional[StrictBool] = None,\n on_chart_release: Optional[StrictStr] = None,\n on_environment: Optional[StrictStr] = None,\n on_failure: Optional[StrictBool] = None,\n on_success: Optional[StrictBool] = None,\n slack_channel: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many SlackDeployHooks are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned SlackDeployHooks (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockSlackDeployHookV3]]:\n \"\"\"List SlackDeployHooks matching a filter\n\n List SlackDeployHooks matching a filter.\n\n :param created_at:\n :type created_at: datetime\n :param id:\n :type id: int\n :param mention_people:\n :type mention_people: bool\n :param on_chart_release:\n :type on_chart_release: str\n :param on_environment:\n :type on_environment: str\n :param on_failure:\n :type on_failure: bool\n :param on_success:\n :type on_success: bool\n :param slack_channel:\n :type slack_channel: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many SlackDeployHooks are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned SlackDeployHooks (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_deploy_hooks_slack_v3_get_serialize(\n created_at=created_at,\n id=id,\n mention_people=mention_people,\n on_chart_release=on_chart_release,\n on_environment=on_environment,\n on_failure=on_failure,\n on_success=on_success,\n slack_channel=slack_channel,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockSlackDeployHookV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(VISUAL_BERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n visual_embeds: Optional[torch.FloatTensor] = None,\n visual_attention_mask: Optional[torch.LongTensor] = None,\n visual_token_type_ids: Optional[torch.LongTensor] = None,\n image_text_alignment: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n region_to_phrase_position: Optional[torch.LongTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:\n r\"\"\"\n region_to_phrase_position (`torch.LongTensor` of shape `(batch_size, total_sequence_length)`, *optional*):\n The positions depicting the position of the image embedding corresponding to the textual tokens.\n\n labels (`torch.LongTensor` of shape `(batch_size, total_sequence_length, visual_sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. KLDivLoss is computed against these labels and the\n outputs from the attention layer.\n\n Returns:\n\n Example:\n\n ```python\n # Assumption: *get_visual_embeddings(image)* gets the visual embeddings of the image in the batch.\n from transformers import AutoTokenizer, VisualBertForRegionToPhraseAlignment\n import torch\n\n tokenizer = AutoTokenizer.from_pretrained(\"google-bert/bert-base-uncased\")\n model = VisualBertForRegionToPhraseAlignment.from_pretrained(\"uclanlp/visualbert-vqa-coco-pre\")\n\n text = \"Who is eating the apple?\"\n inputs = tokenizer(text, return_tensors=\"pt\")\n visual_embeds = get_visual_embeddings(image).unsqueeze(0)\n visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long)\n visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float)\n region_to_phrase_position = torch.ones((1, inputs[\"input_ids\"].shape[-1] + visual_embeds.shape[-2]))\n\n inputs.update(\n {\n \"region_to_phrase_position\": region_to_phrase_position,\n \"visual_embeds\": visual_embeds,\n \"visual_token_type_ids\": visual_token_type_ids,\n \"visual_attention_mask\": visual_attention_mask,\n }\n )\n\n labels = torch.ones(\n (1, inputs[\"input_ids\"].shape[-1] + visual_embeds.shape[-2], visual_embeds.shape[-2])\n ) # Batch size 1\n\n outputs = model(**inputs, labels=labels)\n loss = outputs.loss\n scores = outputs.logits\n ```\"\"\"\n if region_to_phrase_position is None:\n raise ValueError(\"`region_to_phrase_position` should not be None when using Flickr Model.\")\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.visual_bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n visual_embeds=visual_embeds,\n visual_attention_mask=visual_attention_mask,\n visual_token_type_ids=visual_token_type_ids,\n image_text_alignment=image_text_alignment,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n region_to_phrase_position_mask = (region_to_phrase_position != -1).long()\n\n # Make the -1 become 0\n region_to_phrase_position = region_to_phrase_position * region_to_phrase_position_mask\n\n # Selected_positions = batch x selected position x dim\n expanded_region_to_phrase_positions = region_to_phrase_position.unsqueeze(2).expand(\n region_to_phrase_position.size(0), region_to_phrase_position.size(1), sequence_output.size(2)\n )\n selected_positions = sequence_output.gather(1, expanded_region_to_phrase_positions)\n\n # Visual Features = batch x visual_feature_length x dim\n # This will need separate image and visual masks.\n visual_features = sequence_output[:, attention_mask.size(1) :]\n\n if visual_features.size(1) != visual_attention_mask.size(1):\n raise ValueError(\n f\"Visual features length :{visual_features.size(1)} should be the same\"\n f\" as visual attention mask length: {visual_attention_mask.size(1)}.\"\n )\n\n logits = self.attention(selected_positions, visual_features, visual_attention_mask)\n\n loss = None\n\n if labels is not None:\n # scores = batch x selected position x visual_feature\n # scores = selected_positions.bmm(visual_features.transpose(1,2))\n # label = batch x selected_postion x needed position\n loss_fct = KLDivLoss(reduction=\"batchmean\")\n log_softmax = LogSoftmax(dim=-1)\n scores = log_softmax(logits)\n labels = labels.contiguous()\n loss = loss_fct(scores, labels)\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=64,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_chart_versions_v3_get_without_preload_content(\n self,\n authored_by: Optional[StrictStr] = None,\n chart: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n chart_version: Annotated[Optional[StrictStr], Field(description=\"Required when creating\")] = None,\n created_at: Optional[datetime] = None,\n description: Annotated[Optional[StrictStr], Field(description=\"Generally the Git commit message\")] = None,\n id: Optional[StrictInt] = None,\n parent_chart_version: Optional[StrictStr] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many ChartVersions are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned ChartVersions (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> RESTResponseType:\n \"\"\"List ChartVersions matching a filter\n\n List ChartVersions matching a filter.\n\n :param authored_by:\n :type authored_by: str\n :param chart: Required when creating\n :type chart: str\n :param chart_version: Required when creating\n :type chart_version: str\n :param created_at:\n :type created_at: datetime\n :param description: Generally the Git commit message\n :type description: str\n :param id:\n :type id: int\n :param parent_chart_version:\n :type parent_chart_version: str\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many ChartVersions are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned ChartVersions (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_chart_versions_v3_get_serialize(\n authored_by=authored_by,\n chart=chart,\n chart_version=chart_version,\n created_at=created_at,\n description=description,\n id=id,\n parent_chart_version=parent_chart_version,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChartVersionV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n return response_data.response", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50005,\n max_position_embeddings=1024,\n encoder_layers=6,\n encoder_ffn_dim=3072,\n encoder_attention_heads=12,\n decoder_layers=6,\n decoder_ffn_dim=3072,\n decoder_attention_heads=12,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n use_cache=True,\n is_encoder_decoder=True,\n activation_function=\"gelu\",\n d_model=768,\n dropout=0.1,\n attention_dropout=0.1,\n activation_dropout=0.0,\n init_std=0.02,\n classifier_dropout=0.0,\n scale_embedding=True,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n forced_eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.classifier_dropout = classifier_dropout\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(REMBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.LongTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in\n `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are\n ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, RemBertForCausalLM, RemBertConfig\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/rembert\")\n >>> config = RemBertConfig.from_pretrained(\"google/rembert\")\n >>> config.is_decoder = True\n >>> model = RemBertForCausalLM.from_pretrained(\"google/rembert\", config=config)\n\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.rembert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n lm_loss = None\n if labels is not None:\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=lm_loss,\n logits=prediction_scores,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n src_vocab_size=99,\n tgt_vocab_size=99,\n langs=[\"ru\", \"en\"],\n batch_size=13,\n seq_length=7,\n is_training=False,\n use_labels=False,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"relu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n bos_token_id=0,\n pad_token_id=1,\n eos_token_id=2,\n ):\n self.parent = parent\n self.src_vocab_size = src_vocab_size\n self.tgt_vocab_size = tgt_vocab_size\n self.langs = langs\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.eos_token_id = eos_token_id\n torch.manual_seed(0)\n\n # hack needed for modeling_common tests - despite not really having this attribute in this model\n self.vocab_size = self.src_vocab_size", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFCausalLMOutputWithCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,\n config.vocab_size - 1]`.\n \"\"\"\n outputs = self.bert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n sequence_output = outputs[0]\n logits = self.mlm(sequence_output=sequence_output, training=training)\n loss = None\n\n if labels is not None:\n # shift labels to the left and cut last logit token\n shifted_logits = logits[:, :-1]\n labels = labels[:, 1:]\n loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFCausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@classmethod\n def create(\n cls,\n entity_id: str,\n platform: str,\n submitted_on: datetime.datetime,\n local_timezone_offset_hrs: int,\n report_type: str,\n category: str,\n platform_version: str,\n android_device_country_locale_code: Optional[str],\n android_sdk_version: Optional[int],\n android_device_model: Optional[str],\n entry_point: str,\n entry_point_topic_id: Optional[str],\n entry_point_story_id: Optional[str],\n entry_point_exploration_id: Optional[str],\n entry_point_subtopic_id: Optional[str],\n text_language_code: str,\n audio_language_code: str,\n android_report_info: Optional[ReportInfoDict],\n web_report_info: Optional[ReportInfoDict]\n ) -> str:\n \"\"\"Creates a new AppFeedbackReportModel instance and returns its ID.\n\n Args:\n entity_id: str. The ID used for this entity.\n platform: str. The platform the report is submitted on.\n submitted_on: datetime.datetime. The date and time the report was\n submitted, in the user's local time zone.\n local_timezone_offset_hrs: int. The hours offset from UTC of the\n user's local time zone.\n report_type: str. The type of report.\n category: str. The category the report is providing feedback on.\n platform_version: str. The version of Oppia that the report was\n submitted on.\n android_device_country_locale_code: str|None. The ISO-3166 code for\n the user's country locale or None if it's a web report.\n android_sdk_version: int|None. The SDK version running when on the\n device or None if it's a web report.\n android_device_model: str|None. The device model of the Android\n device, or None if it's a web report.\n entry_point: str. The entry point used to start the report.\n entry_point_topic_id: str|None. The current topic ID depending on\n the type of entry point used.\n entry_point_story_id: str|None. The current story ID depending on\n the type of entry point used.\n entry_point_exploration_id: str|None. The current exploration ID\n depending on the type of entry point used.\n entry_point_subtopic_id: int|None. The current subtopic ID depending\n on the type of entry point used.\n text_language_code: str. The ISO-639 language code for the text\n language set by the user on the Oppia app.\n audio_language_code: str. The language code for the audio language\n set by the user on the Oppia app, as defined by Oppia (not\n necessarily an ISO-639 code).\n android_report_info: dict|None. The information collected as part\n of the Android-specific feedback report.\n web_report_info: dict|None. The information collected as part of the\n web-specific feedback report.\n\n Returns:\n AppFeedbackReportModel. The newly created AppFeedbackReportModel\n instance.\n \"\"\"\n android_schema_version = None\n web_schema_version = None\n if platform == PLATFORM_CHOICE_ANDROID:\n android_schema_version = (\n feconf.CURRENT_ANDROID_REPORT_SCHEMA_VERSION)\n else:\n web_schema_version = (\n feconf.CURRENT_WEB_REPORT_SCHEMA_VERSION)\n report_entity = cls(\n id=entity_id, platform=platform, submitted_on=submitted_on,\n local_timezone_offset_hrs=local_timezone_offset_hrs,\n report_type=report_type, category=category,\n platform_version=platform_version,\n android_device_country_locale_code=(\n android_device_country_locale_code),\n android_sdk_version=android_sdk_version,\n android_device_model=android_device_model, entry_point=entry_point,\n entry_point_topic_id=entry_point_topic_id,\n entry_point_exploration_id=entry_point_exploration_id,\n entry_point_story_id=entry_point_story_id,\n entry_point_subtopic_id=entry_point_subtopic_id,\n text_language_code=text_language_code,\n audio_language_code=audio_language_code,\n android_report_info=android_report_info,\n android_report_info_schema_version=android_schema_version,\n web_report_info=web_report_info,\n web_report_info_schema_version=web_schema_version)\n report_entity.update_timestamps()\n report_entity.put()\n return entity_id", "smellKey": "S107", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(\n self,\n parent,\n hidden_size=36,\n intermediate_size=72,\n projection_dim=62,\n output_channels=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n num_channels=3,\n image_size=24,\n patch_size=2,\n hidden_act=\"gelu\",\n layer_norm_eps=1e-06,\n dropout=0.0,\n attention_dropout=0.0,\n initializer_range=0.02,\n initializer_factor=1.0,\n qkv_bias=True,\n mlp_ratio=4.0,\n use_abs_pos=True,\n use_rel_pos=True,\n rel_pos_zero_init=False,\n window_size=14,\n global_attn_indexes=[2, 5, 8, 11],\n num_pos_feats=16,\n mlp_dim=None,\n batch_size=2,\n ):\n self.parent = parent\n self.image_size = image_size\n self.patch_size = patch_size\n self.output_channels = output_channels\n self.num_channels = num_channels\n self.hidden_size = hidden_size\n self.projection_dim = projection_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.hidden_act = hidden_act\n self.layer_norm_eps = layer_norm_eps\n self.qkv_bias = qkv_bias\n self.mlp_ratio = mlp_ratio\n self.use_abs_pos = use_abs_pos\n self.use_rel_pos = use_rel_pos\n self.rel_pos_zero_init = rel_pos_zero_init\n self.window_size = window_size\n self.global_attn_indexes = global_attn_indexes\n self.num_pos_feats = num_pos_feats\n self.mlp_dim = mlp_dim\n self.batch_size = batch_size\n\n # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\n num_patches = (image_size // patch_size) ** 2\n self.seq_length = num_patches + 1\n\n self.prompt_encoder_tester = TFSamPromptEncoderTester()\n self.mask_decoder_tester = TFSamMaskDecoderTester()", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(BIGBIRD_PEGASUS_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Seq2SeqQuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n # Copied from transformers.models.bart.modeling_bart.BartForQuestionAnswering.forward\n def forward(\n self,\n input_ids: torch.Tensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n decoder_head_mask: Optional[torch.Tensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[List[torch.FloatTensor]] = None,\n start_positions: Optional[torch.LongTensor] = None,\n end_positions: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Seq2SeqQuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if start_positions is not None and end_positions is not None:\n use_cache = False\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (\n start_logits,\n end_logits,\n ) + outputs[1:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return Seq2SeqQuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=50265,\n max_position_embeddings=1024,\n encoder_layers=12,\n encoder_ffn_dim=4096,\n encoder_attention_heads=16,\n decoder_layers=12,\n decoder_ffn_dim=4096,\n decoder_attention_heads=16,\n encoder_layerdrop=0.0,\n decoder_layerdrop=0.0,\n activation_function=\"gelu\",\n d_model=1024,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n classifier_dropout=0.0,\n scale_embedding=False,\n use_cache=True,\n num_labels=3,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n is_encoder_decoder=True,\n decoder_start_token_id=2,\n forced_eos_token_id=2,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.encoder_layerdrop = encoder_layerdrop\n self.decoder_layerdrop = decoder_layerdrop\n self.classifier_dropout = classifier_dropout\n self.use_cache = use_cache\n self.num_hidden_layers = encoder_layers\n self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True\n\n super().__init__(\n num_labels=num_labels,\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n decoder_start_token_id=decoder_start_token_id,\n forced_eos_token_id=forced_eos_token_id,\n **kwargs,\n )\n\n # ensure backward compatibility for BART CNN models\n if self.forced_bos_token_id is None and kwargs.get(\"force_bos_token_to_be_generated\", False):\n self.forced_bos_token_id = self.bos_token_id\n warnings.warn(\n f\"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. \"\n \"The config can simply be saved and uploaded again to be fixed.\"\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, host=None,\n api_key=None, api_key_prefix=None,\n username=None, password=None,\n access_token=None,\n server_index=None, server_variables=None,\n server_operation_index=None, server_operation_variables=None,\n ignore_operation_servers=False,\n ssl_ca_cert=None,\n retries=None,\n *,\n debug: Optional[bool] = None\n ) -> None:\n \"\"\"Constructor\n \"\"\"\n self._base_path = \"https://sherlock.dsp-devops-prod.broadinstitute.org\" if host is None else host\n \"\"\"Default Base url\n \"\"\"\n self.server_index = 0 if server_index is None and host is None else server_index\n self.server_operation_index = server_operation_index or {}\n \"\"\"Default server index\n \"\"\"\n self.server_variables = server_variables or {}\n self.server_operation_variables = server_operation_variables or {}\n \"\"\"Default server variables\n \"\"\"\n self.ignore_operation_servers = ignore_operation_servers\n \"\"\"Ignore operation servers\n \"\"\"\n self.temp_folder_path = None\n \"\"\"Temp file folder for downloading files\n \"\"\"\n # Authentication Settings\n self.api_key = {}\n if api_key:\n self.api_key = api_key\n \"\"\"dict to store API key(s)\n \"\"\"\n self.api_key_prefix = {}\n if api_key_prefix:\n self.api_key_prefix = api_key_prefix\n \"\"\"dict to store API prefix (e.g. Bearer)\n \"\"\"\n self.refresh_api_key_hook = None\n \"\"\"function hook to refresh API key if expired\n \"\"\"\n self.username = username\n \"\"\"Username for HTTP basic authentication\n \"\"\"\n self.password = password\n \"\"\"Password for HTTP basic authentication\n \"\"\"\n self.access_token = access_token\n \"\"\"Access token\n \"\"\"\n self.logger = {}\n \"\"\"Logging Settings\n \"\"\"\n self.logger[\"package_logger\"] = logging.getLogger(\"sherlock_python_client\")\n self.logger[\"urllib3_logger\"] = logging.getLogger(\"urllib3\")\n self.logger_format = '%(asctime)s %(levelname)s %(message)s'\n \"\"\"Log format\n \"\"\"\n self.logger_stream_handler = None\n \"\"\"Log stream handler\n \"\"\"\n self.logger_file_handler: Optional[FileHandler] = None\n \"\"\"Log file handler\n \"\"\"\n self.logger_file = None\n \"\"\"Debug file location\n \"\"\"\n if debug is not None:\n self.debug = debug\n else:\n self.__debug = False\n \"\"\"Debug switch\n \"\"\"\n\n self.verify_ssl = True\n \"\"\"SSL/TLS verification\n Set this to false to skip verifying SSL certificate when calling API\n from https server.\n \"\"\"\n self.ssl_ca_cert = ssl_ca_cert\n \"\"\"Set this to customize the certificate file to verify the peer.\n \"\"\"\n self.cert_file = None\n \"\"\"client certificate file\n \"\"\"\n self.key_file = None\n \"\"\"client key file\n \"\"\"\n self.assert_hostname = None\n \"\"\"Set this to True/False to enable/disable SSL hostname verification.\n \"\"\"\n self.tls_server_name = None\n \"\"\"SSL/TLS Server Name Indication (SNI)\n Set this to the SNI value expected by the server.\n \"\"\"\n\n self.connection_pool_maxsize = multiprocessing.cpu_count() * 5\n \"\"\"urllib3 connection pool's maximum number of connections saved\n per pool. urllib3 uses 1 connection as default value, but this is\n not the best value when you are making a lot of possibly parallel\n requests to the same host, which is often the case here.\n cpu_count * 5 is used as default value to increase performance.\n \"\"\"\n\n self.proxy: Optional[str] = None\n \"\"\"Proxy URL\n \"\"\"\n self.proxy_headers = None\n \"\"\"Proxy headers\n \"\"\"\n self.safe_chars_for_path_param = ''\n \"\"\"Safe chars for path_param\n \"\"\"\n self.retries = retries\n \"\"\"Adding retries to override urllib3 default value 3\n \"\"\"\n # Enable client side validation\n self.client_side_validation = True\n\n self.socket_options = None\n \"\"\"Options to pass down to the underlying urllib3 socket\n \"\"\"\n\n self.datetime_format = \"%Y-%m-%dT%H:%M:%S.%f%z\"\n \"\"\"datetime format\n \"\"\"\n\n self.date_format = \"%Y-%m-%d\"\n \"\"\"date format\n \"\"\"", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_attention_mask=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=32,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.initializer_range = initializer_range", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n body=\"\",\n headers=None,\n status=0,\n version=0,\n reason=None,\n strict=0,\n preload_content=True,\n decode_content=True,\n original_response=None,\n pool=None,\n connection=None,\n msg=None,\n retries=None,\n enforce_content_length=False,\n request_method=None,\n request_url=None,\n auto_close=True,\n ):\n\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers)\n self.status = status\n self.version = version\n self.reason = reason\n self.strict = strict\n self.decode_content = decode_content\n self.retries = retries\n self.enforce_content_length = enforce_content_length\n self.auto_close = auto_close\n\n self._decoder = None\n self._body = None\n self._fp = None\n self._original_response = original_response\n self._fp_bytes_read = 0\n self.msg = msg\n self._request_url = request_url\n\n if body and isinstance(body, (six.string_types, bytes)):\n self._body = body\n\n self._pool = pool\n self._connection = connection\n\n if hasattr(body, \"read\"):\n self._fp = body\n\n # Are we using the chunked-style of transfer encoding?\n self.chunked = False\n self.chunk_left = None\n tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n # Don't incur the penalty of creating a list and then discarding it\n encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n if \"chunked\" in encodings:\n self.chunked = True\n\n # Determine length of response\n self.length_remaining = self._init_length(request_method)\n\n # If requested, preload the body.\n if preload_content and not self._body:\n self._body = self.read(decode_content=decode_content)", "smellKey": "S107", "smellId": null, "repo": "shenxianpeng_pip", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=32,\n num_channels=3,\n num_stages=4,\n hidden_sizes=[10, 20, 30, 40],\n depths=[2, 2, 3, 2],\n is_training=True,\n use_labels=True,\n intermediate_size=37,\n hidden_act=\"gelu\",\n type_sequence_label_size=10,\n initializer_range=0.02,\n num_labels=3,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.num_stages = num_stages\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.is_training = is_training\n self.use_labels = use_labels\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@pytest.mark.parametrize(\n (\n \"discovery_info\",\n \"entry_data\",\n \"old_addon_options\",\n \"new_addon_options\",\n \"disconnect_calls\",\n ),\n [\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 0,\n ),\n (\n {\"config\": ADDON_DISCOVERY_INFO},\n {\"use_addon\": True},\n {\n \"device\": \"/test\",\n \"network_key\": \"old123\",\n \"s0_legacy_key\": \"old123\",\n \"s2_access_control_key\": \"old456\",\n \"s2_authenticated_key\": \"old789\",\n \"s2_unauthenticated_key\": \"old987\",\n \"lr_s2_access_control_key\": \"old654\",\n \"lr_s2_authenticated_key\": \"old321\",\n },\n {\n \"usb_path\": \"/new\",\n \"s0_legacy_key\": \"new123\",\n \"s2_access_control_key\": \"new456\",\n \"s2_authenticated_key\": \"new789\",\n \"s2_unauthenticated_key\": \"new987\",\n \"lr_s2_access_control_key\": \"new654\",\n \"lr_s2_authenticated_key\": \"new321\",\n \"log_level\": \"info\",\n \"emulate_hardware\": False,\n },\n 1,\n ),\n ],\n)\nasync def test_options_addon_running(\n hass: HomeAssistant,\n client,\n supervisor,\n integration,\n addon_running,\n addon_options,\n set_addon_options,\n restart_addon,\n get_addon_discovery_info,\n discovery_info,\n entry_data,\n old_addon_options,\n new_addon_options,\n disconnect_calls,\n) -> None:\n \"\"\"Test options flow and add-on already running on Supervisor.\"\"\"\n addon_options.update(old_addon_options)\n entry = integration\n data = {**entry.data, **entry_data}\n hass.config_entries.async_update_entry(entry, data=data, unique_id=\"1234\")\n\n assert entry.data[\"url\"] == \"ws://test.org\"\n\n assert client.connect.call_count == 1\n assert client.disconnect.call_count == 0\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"on_supervisor\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"], {\"use_addon\": True}\n )\n\n assert result[\"type\"] is FlowResultType.FORM\n assert result[\"step_id\"] == \"configure_addon\"\n\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n new_addon_options,\n )\n\n new_addon_options[\"device\"] = new_addon_options.pop(\"usb_path\")\n assert set_addon_options.call_args == call(\n hass,\n \"core_zwave_js\",\n {\"options\": new_addon_options},\n )\n assert client.disconnect.call_count == disconnect_calls\n\n assert result[\"type\"] is FlowResultType.SHOW_PROGRESS\n assert result[\"step_id\"] == \"start_addon\"\n\n await hass.async_block_till_done()\n result = await hass.config_entries.options.async_configure(result[\"flow_id\"])\n await hass.async_block_till_done()\n\n assert restart_addon.call_args == call(hass, \"core_zwave_js\")\n\n assert result[\"type\"] is FlowResultType.CREATE_ENTRY\n assert entry.data[\"url\"] == \"ws://host1:3001\"\n assert entry.data[\"usb_path\"] == new_addon_options[\"device\"]\n assert entry.data[\"s0_legacy_key\"] == new_addon_options[\"s0_legacy_key\"]\n assert (\n entry.data[\"s2_access_control_key\"]\n == new_addon_options[\"s2_access_control_key\"]\n )\n assert (\n entry.data[\"s2_authenticated_key\"] == new_addon_options[\"s2_authenticated_key\"]\n )\n assert (\n entry.data[\"s2_unauthenticated_key\"]\n == new_addon_options[\"s2_unauthenticated_key\"]\n )\n assert (\n entry.data[\"lr_s2_access_control_key\"]\n == new_addon_options[\"lr_s2_access_control_key\"]\n )\n assert (\n entry.data[\"lr_s2_authenticated_key\"]\n == new_addon_options[\"lr_s2_authenticated_key\"]\n )\n assert entry.data[\"use_addon\"] is True\n assert entry.data[\"integration_created_addon\"] is False\n assert client.connect.call_count == 2\n assert client.disconnect.call_count == 1", "smellKey": "S107", "smellId": null, "repo": "phillis94_home-assistant-core", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(UDOP_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Tensor = None,\n attention_mask: Tensor = None,\n bbox: Dict[str, Any] = None,\n pixel_values: Optional[Tensor] = None,\n visual_bbox: Dict[str, Any] = None,\n decoder_input_ids: Optional[Tensor] = None,\n decoder_attention_mask: Optional[Tensor] = None,\n inputs_embeds: Optional[Tensor] = None,\n encoder_outputs: Optional[Tensor] = None,\n past_key_values: Optional[Tensor] = None,\n head_mask: Optional[Tensor] = None,\n decoder_inputs_embeds: Optional[Tensor] = None,\n decoder_head_mask: Optional[Tensor] = None,\n cross_attn_head_mask: Optional[Tensor] = None,\n use_cache=True,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Tuple[Tensor, ...]:\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoProcessor, AutoModel\n >>> from datasets import load_dataset\n >>> import torch\n\n >>> # load model and processor\n >>> # in this case, we already have performed OCR ourselves\n >>> # so we initialize the processor with `apply_ocr=False`\n >>> processor = AutoProcessor.from_pretrained(\"microsoft/udop-large\", apply_ocr=False)\n >>> model = AutoModel.from_pretrained(\"microsoft/udop-large\")\n\n >>> # load an example image, along with the words and coordinates\n >>> # which were extracted using an OCR engine\n >>> dataset = load_dataset(\"nielsr/funsd-layoutlmv3\", split=\"train\", trust_remote_code=True)\n >>> example = dataset[0]\n >>> image = example[\"image\"]\n >>> words = example[\"tokens\"]\n >>> boxes = example[\"bboxes\"]\n >>> inputs = processor(image, words, boxes=boxes, return_tensors=\"pt\")\n\n >>> decoder_input_ids = torch.tensor([[model.config.decoder_start_token_id]])\n\n >>> # forward pass\n >>> outputs = model(**inputs, decoder_input_ids=decoder_input_ids)\n >>> last_hidden_states = outputs.last_hidden_state\n >>> list(last_hidden_states.shape)\n [1, 1, 1024]\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n bbox=bbox,\n pixel_values=pixel_values,\n visual_bbox=visual_bbox,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = encoder_outputs[0]\n encoder_attention_mask = encoder_outputs.attention_mask if return_dict else encoder_outputs[1]\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n # we filter out the attention mask\n decoder_outputs = tuple(value for idx, value in enumerate(decoder_outputs) if idx != 1)\n encoder_outputs = tuple(value for idx, value in enumerate(encoder_outputs) if idx != 1)\n return decoder_outputs + encoder_outputs\n\n return Seq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=65024,\n hidden_size=4544,\n num_hidden_layers=32,\n num_attention_heads=71,\n num_ln_in_parallel_attn=None,\n layer_norm_epsilon=1e-5,\n initializer_range=0.02,\n use_cache=True,\n hidden_dropout=0.0,\n attention_dropout=0.0,\n num_kv_heads=None,\n alibi=False,\n new_decoder_architecture=False,\n multi_query=True,\n parallel_attn=True,\n bias=False,\n max_position_embeddings=2048,\n rope_theta=10000.0,\n rope_scaling=None,\n bos_token_id=11,\n eos_token_id=11,\n ffn_hidden_size=None,\n activation=\"gelu\",\n **kwargs,\n ):\n self.vocab_size = vocab_size\n # Backward compatibility with n_embed kwarg\n n_embed = kwargs.pop(\"n_embed\", None)\n self.hidden_size = hidden_size if n_embed is None else n_embed\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.use_cache = use_cache\n self.hidden_dropout = hidden_dropout\n self.attention_dropout = attention_dropout\n self.bos_token_id = bos_token_id\n self.eos_token_id = eos_token_id\n self.num_kv_heads = num_attention_heads if num_kv_heads is None else num_kv_heads\n self.alibi = alibi\n self.new_decoder_architecture = new_decoder_architecture\n self.multi_query = multi_query # Ignored when new_decoder_architecture is True\n self.parallel_attn = parallel_attn\n self.bias = bias\n self.num_ln_in_parallel_attn = num_ln_in_parallel_attn\n self.max_position_embeddings = max_position_embeddings\n self.rope_theta = rope_theta\n self.rope_scaling = rope_scaling\n self.activation = activation\n if ffn_hidden_size is None:\n self.ffn_hidden_size = hidden_size * 4\n else:\n self.ffn_hidden_size = ffn_hidden_size\n\n super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@staticmethod\n @custom_fwd\n def forward(\n ctx,\n xz,\n conv1d_weight,\n conv1d_bias,\n x_proj_weight,\n delta_proj_weight,\n out_proj_weight,\n out_proj_bias,\n A,\n B=None,\n C=None,\n D=None,\n delta_bias=None,\n B_proj_bias=None,\n C_proj_bias=None,\n delta_softplus=True,\n checkpoint_lvl=1,\n b_rms_weight=None,\n c_rms_weight=None,\n dt_rms_weight=None,\n b_c_dt_rms_eps=1e-6,\n ):\n \"\"\"\n xz: (batch, dim, seqlen)\n \"\"\"\n assert causal_conv1d_cuda is not None, \"causal_conv1d_cuda is not available. Please install causal-conv1d.\"\n assert checkpoint_lvl in [0, 1]\n L = xz.shape[-1]\n delta_rank = delta_proj_weight.shape[1]\n d_state = A.shape[-1] * (1 if not A.is_complex() else 2)\n if torch.is_autocast_enabled():\n x_proj_weight = x_proj_weight.to(dtype=torch.get_autocast_gpu_dtype())\n delta_proj_weight = delta_proj_weight.to(dtype=torch.get_autocast_gpu_dtype())\n out_proj_weight = out_proj_weight.to(dtype=torch.get_autocast_gpu_dtype())\n out_proj_bias = (\n out_proj_bias.to(dtype=torch.get_autocast_gpu_dtype()) if out_proj_bias is not None else None\n )\n if xz.stride(-1) != 1:\n xz = xz.contiguous()\n conv1d_weight = rearrange(conv1d_weight, \"d 1 w -> d w\")\n x, z = xz.chunk(2, dim=1)\n conv1d_bias = conv1d_bias.contiguous() if conv1d_bias is not None else None\n conv1d_out = causal_conv1d_cuda.causal_conv1d_fwd(x, conv1d_weight, conv1d_bias, None, None, None, True)\n # We're being very careful here about the layout, to avoid extra transposes.\n # We want delta to have d as the slowest moving dimension\n # and L as the fastest moving dimension, since those are what the ssm_scan kernel expects.\n x_dbl = F.linear(rearrange(conv1d_out, \"b d l -> (b l) d\"), x_proj_weight) # (bl d)\n delta = rearrange(delta_proj_weight @ x_dbl[:, :delta_rank].t(), \"d (b l) -> b d l\", l=L)\n ctx.is_variable_B = B is None\n ctx.is_variable_C = C is None\n ctx.B_proj_bias_is_None = B_proj_bias is None\n ctx.C_proj_bias_is_None = C_proj_bias is None\n if B is None: # variable B\n B = x_dbl[:, delta_rank : delta_rank + d_state] # (bl dstate)\n if B_proj_bias is not None:\n B = B + B_proj_bias.to(dtype=B.dtype)\n if not A.is_complex():\n # B = rearrange(B, \"(b l) dstate -> b dstate l\", l=L).contiguous()\n B = rearrange(B, \"(b l) dstate -> b 1 dstate l\", l=L).contiguous()\n else:\n B = rearrange(B, \"(b l) (dstate two) -> b 1 dstate (l two)\", l=L, two=2).contiguous()\n else:\n if B.stride(-1) != 1:\n B = B.contiguous()\n if C is None: # variable C\n C = x_dbl[:, -d_state:] # (bl dstate)\n if C_proj_bias is not None:\n C = C + C_proj_bias.to(dtype=C.dtype)\n if not A.is_complex():\n # C = rearrange(C, \"(b l) dstate -> b dstate l\", l=L).contiguous()\n C = rearrange(C, \"(b l) dstate -> b 1 dstate l\", l=L).contiguous()\n else:\n C = rearrange(C, \"(b l) (dstate two) -> b 1 dstate (l two)\", l=L, two=2).contiguous()\n else:\n if C.stride(-1) != 1:\n C = C.contiguous()\n if D is not None:\n D = D.contiguous()\n\n if b_rms_weight is not None:\n B = rearrange(B, \"b 1 dstate l -> (b l) dstate\", l=L).contiguous()\n B = rms_norm_forward(B, b_rms_weight, bias=None, eps=b_c_dt_rms_eps)\n B = rearrange(B, \"(b l) dstate -> b 1 dstate l\", l=L).contiguous()\n if c_rms_weight is not None:\n C = rearrange(C, \"b 1 dstate l -> (b l) dstate\", l=L).contiguous()\n C = rms_norm_forward(C, c_rms_weight, bias=None, eps=b_c_dt_rms_eps)\n C = rearrange(C, \"(b l) dstate -> b 1 dstate l\", l=L).contiguous()\n if dt_rms_weight is not None:\n delta = rearrange(delta, \"b d l -> (b l) d\", l=L).contiguous()\n delta = rms_norm_forward(delta, dt_rms_weight, bias=None, eps=b_c_dt_rms_eps)\n delta = rearrange(delta, \"(b l) d -> b d l\", l=L).contiguous()\n\n out, scan_intermediates, out_z = selective_scan_cuda.fwd(\n conv1d_out, delta, A, B, C, D, z, delta_bias, delta_softplus\n )\n ctx.delta_softplus = delta_softplus\n ctx.out_proj_bias_is_None = out_proj_bias is None\n ctx.checkpoint_lvl = checkpoint_lvl\n ctx.b_rms_weight = b_rms_weight\n ctx.c_rms_weight = c_rms_weight\n ctx.dt_rms_weight = dt_rms_weight\n ctx.b_c_dt_rms_eps = b_c_dt_rms_eps\n if checkpoint_lvl >= 1: # Will recompute conv1d_out and delta in the backward pass\n conv1d_out, delta = None, None\n ctx.save_for_backward(\n xz,\n conv1d_weight,\n conv1d_bias,\n x_dbl,\n x_proj_weight,\n delta_proj_weight,\n out_proj_weight,\n conv1d_out,\n delta,\n A,\n B,\n C,\n D,\n delta_bias,\n scan_intermediates,\n b_rms_weight,\n c_rms_weight,\n dt_rms_weight,\n out,\n )\n return F.linear(rearrange(out_z, \"b d l -> b l d\"), out_proj_weight, out_proj_bias)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(GPTSAN_JAPANESE_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.FloatTensor] = None,\n spout: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = False,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n output_router_logits: Optional[bool] = None,\n num_precontext: Optional[torch.LongTensor] = None,\n ) -> Union[MoEModelOutputWithPastAndCrossAttentions, Tuple[torch.FloatTensor]]:\n r\"\"\"\n num_precontext (`torch.LongTensor` of shape `(batch_size,1)`):\n length of `hybrid` input tokens in the input. Tokens up to this length refer to both front and back like\n BERT, tokens after that refer only to front like GPT. see also:\n https://github.com/tanreinama/GPTSAN/blob/main/report/model.md\n\n Returns:\n `MoEModelOutputWithPastAndCrossAttentions` or `tuple` if `return_dict` returns\n MoEModelOutputWithPastAndCrossAttentions insted of tuple\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n device = self.position_embeddings.weight.device\n if input_ids is None:\n input_ids = torch.zeros([1, 1]).int().to(device) # dummy for input_ids was None\n if inputs_embeds is not None:\n raise NotImplementedError(\n \"GPTSanJapaneseModel does not use `inputs_embeds`. Make sure to pass in `input_ids` instead.\"\n )\n num_pasts_contexts = 0\n num_batch = input_ids.shape[0]\n pasts_or_spout_value = None\n if past_key_values is not None:\n num_pasts_contexts = past_key_values[0][0].shape[2]\n elif self.config.d_spout and spout is not None:\n # `spout` is a special input vector specific to GPTSAN\n # This controls the output by projecting embedded information such as the class of sentences during learning.\n # It should passed instead of the first past_key_value.\n # See the original GPTSAN repository for details\n num_pasts_contexts += 1\n\n # If there is an attention_mask, increase first one for spout\n if self.config.d_spout and spout is not None and attention_mask is not None:\n attention_mask_with_spout = torch.ones(num_batch, attention_mask.shape[1] + 1, device=device)\n attention_mask_with_spout[:, 1:] -= 1 - attention_mask # 1st token should be spout\n attention_mask = attention_mask_with_spout # update attention_mask\n\n if num_precontext is not None:\n # `num_precontext` is the number of tokens that refer to each other in prefix-lm\n # created per batch, so dimension of num_precontext should be [batch, 1]\n if not (\n len(num_precontext.shape) == 2 and num_precontext.shape[1] == 1\n ): # num_precontext Should be [batch,1]\n raise ValueError(\"num_precontext should be [batch, 1] size.\")\n num_precontext = torch.reshape(num_precontext, [-1])\n else:\n num_precontext = torch.zeros([num_batch]).int().to(device)\n\n num_input_contexts = input_ids.shape[1]\n num_output_contexts = num_input_contexts + num_pasts_contexts\n\n hidden_states = self.embed_tokens(input_ids)\n\n if past_key_values is not None:\n pasts_or_spout_value = past_key_values\n elif self.config.d_spout and spout is not None:\n # Make vector from `spout` of GPTSAN to the same shape as past_key_values\n pasts_or_spout_value = self.spout(spout) # projecting `spout` vector\n pasts_or_spout_value = torch.reshape(\n pasts_or_spout_value,\n [\n num_batch,\n self.config.num_layers,\n 2,\n self.config.num_heads,\n num_pasts_contexts,\n self.config.d_model // self.config.num_heads,\n ],\n )\n pasts_or_spout_value = torch.split(pasts_or_spout_value, [1] * self.config.num_layers, dim=1)\n # make same shape as past_key_values\n pasts_or_spout_value = tuple(\n tuple([b.squeeze(1) for b in torch.split(a.squeeze(1), [1, 1], dim=1)]) for a in pasts_or_spout_value\n )\n else:\n pasts_or_spout_value = [None] * self.config.num_layers\n\n # Token position considering spout and pasts\n token_position = torch.arange(num_input_contexts).to(device) + num_pasts_contexts\n\n if attention_mask is None:\n attention_mask = torch.ones(num_batch, num_input_contexts, device=device)\n\n # positions for get position_embeddings\n gather_position = (\n (\n torch.zeros((num_batch, self.config.d_model, num_input_contexts)).to(device)\n + token_position.unsqueeze(0)\n )\n .transpose(1, 2)\n .long()\n )\n # When padding with padding_side=\"left\", zeros line up on the left side of attention_mask, so position_embeddings is shifted accordingly\n gather_position -= (1 - attention_mask).argmin(dim=-1).unsqueeze(1).unsqueeze(2)\n gather_position = torch.clip(gather_position, num_pasts_contexts, self.config.max_position_embeddings - 1)\n\n # attention_mask is applied per batch\n for i in range(num_batch):\n hidden_states[i] += torch.gather(self.position_embeddings.weight, dim=0, index=gather_position[i])\n\n # Create a mask to be used when making the prefix Input length of Prefix-LM variable\n causal_mask = (\n torch.tril(torch.ones((num_output_contexts, num_output_contexts), dtype=torch.uint8))\n .view(1, 1, num_output_contexts, num_output_contexts)\n .to(device)\n )\n prefix_lm_mask = causal_mask[:, :, -num_input_contexts:, :]\n if token_type_ids is not None:\n token_type_ids = token_type_ids.unsqueeze(1).unsqueeze(2)\n prefix_lm_mask = ((prefix_lm_mask + token_type_ids) > 0).float()\n # Marge prefix_lm_mask and attention_mask\n extended_attention_mask = prefix_lm_mask * attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Prepare head mask if needed\n if head_mask is not None:\n head_mask = self.get_head_mask(\n head_mask, self.config.num_switch_layers + self.config.num_ext_layers\n ) # n_layer x batch x n_heads x N x N\n\n # outputs\n present_key_value_states = () if self.config.use_cache or use_cache else None\n all_hidden_states = () if self.config.output_hidden_states or output_hidden_states else None\n all_attentions = () if self.config.output_attentions or output_attentions else None\n all_router_probs = () if self.config.output_router_logits or output_router_logits else None\n\n for layer, past in enumerate(pasts_or_spout_value):\n if layer == self.config.num_switch_layers:\n if self.config.num_ext_layers > 0:\n # extra_position_embeddings are extra position embeddings that are only created when extending the model with code from the original GPTSAN repository. Not used in the default model.\n # However, it is created when you create an additional layer and partially train only that location.\n # Therefore, convert_gptsan_tf_checkpoint_to_pytorch.py is used when converting and loading models created in the original GPTSAN repository.\n for i in range(num_batch):\n hidden_states[i] += torch.gather(\n self.extra_position_embeddings.weight, dim=0, index=gather_position[i]\n )\n\n output_router_tuple = (\n self.config.output_router_logits or output_router_logits\n ) and layer < self.config.num_switch_layers\n block_output = self.blocks[layer](\n hidden_states=hidden_states,\n past_key_value=past,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n use_cache=self.config.use_cache or use_cache,\n output_attentions=self.config.output_attentions or output_attentions,\n output_router_tuple=output_router_tuple,\n )\n\n outpos = 0\n hidden_states = block_output[outpos]\n if self.config.output_hidden_states or output_hidden_states:\n all_hidden_states += (hidden_states,)\n if self.config.use_cache or use_cache:\n outpos += 1\n present = block_output[outpos]\n present_key_value_states += (present,)\n if self.config.output_attentions or output_attentions:\n outpos += 1\n attention_probs = block_output[outpos]\n all_attentions += (attention_probs,)\n if output_router_tuple:\n outpos += 1\n router_tuple = block_output[outpos]\n all_router_probs.append(router_tuple[0])\n\n hidden_states = self.last_project(hidden_states)\n hidden_states = self.act(hidden_states)\n\n if self.config.output_hidden_states or output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(\n v\n for v in [\n hidden_states,\n present_key_value_states,\n all_hidden_states,\n all_attentions,\n all_router_probs,\n ]\n if v is not None\n )\n\n return MoEModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n past_key_values=present_key_value_states,\n hidden_states=all_hidden_states,\n attentions=all_attentions,\n router_probs=all_router_probs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def add_test(\n cls, \n cc, \n conv_kind,\n problem_sizes,\n element,\n element_accumulator,\n element_output,\n opclass,\n threadblock_shape,\n warp_count,\n instruction_shape,\n stages,\n iterator_algorithm=None,\n swizzle=None,\n split_k_mode=\"serial\",\n split_k_slices=1,\n activation = \"identity\"\n):\n \"\"\"Create a test-running function with the given specification\"\"\"\n test_name = get_name_conv2d(\n cc, conv_kind, element, element_accumulator,\n element_output, opclass, threadblock_shape, warp_count, instruction_shape, stages,\n iterator_algorithm, swizzle, split_k_mode, split_k_slices, activation)\n \n def run(self):\n # Create the plan\n plan = cutlass.Conv2d(\n kind=conv_kind,\n element=element,\n element_accumulator=element_accumulator,\n element_C=element_output,\n element_D=element_output\n )\n \n # Set the opclass\n plan.opclass = opclass\n # Set the tile description\n td = {\n \"threadblock_shape\": threadblock_shape,\n \"warp_count\": warp_count,\n \"stages\": stages,\n \"instruction_shape\": instruction_shape,\n }\n\n plan.tile_description = td\n # Set iterator algorithm\n if iterator_algorithm is not None:\n plan.iterator_algorithm = iterator_algorithm\n # Set swizzling functor\n if swizzle is not None:\n plan.swizzling_stride = swizzle\n \n if activation != \"identity\":\n if activation == \"leaky_relu\":\n plan.activation = (cutlass.epilogue.leaky_relu, 0.5)\n else:\n plan.activation = getattr(cutlass.epilogue, activation)\n \n conv2d_launcher = Conv2dLauncherFrontend(plan, 80, backend=\"numpy\")\n \n for ps in problem_sizes:\n if not validate_problem_size(ps, conv_kind, split_k_slices): continue\n \n self.assertTrue(\n conv2d_launcher.run(ps, split_k_mode, split_k_slices, 1.0, 0.5)\n )\n \n setattr(cls, test_name, run)\n \n return run", "smellKey": "S107", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=32,\n patch_size=1,\n num_channels=3,\n num_channels_out=1,\n embed_dim=16,\n depths=[1, 2, 1],\n num_heads=[2, 2, 4],\n window_size=2,\n mlp_ratio=2.0,\n qkv_bias=True,\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n drop_path_rate=0.1,\n hidden_act=\"gelu\",\n use_absolute_embeddings=False,\n patch_norm=True,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n is_training=True,\n scope=None,\n use_labels=False,\n upscale=2,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.num_channels_out = num_channels_out\n self.embed_dim = embed_dim\n self.depths = depths\n self.num_heads = num_heads\n self.window_size = window_size\n self.mlp_ratio = mlp_ratio\n self.qkv_bias = qkv_bias\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.hidden_act = hidden_act\n self.use_absolute_embeddings = use_absolute_embeddings\n self.patch_norm = patch_norm\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.is_training = is_training\n self.scope = scope\n self.use_labels = use_labels\n self.upscale = upscale\n\n # here we set some attributes to make tests pass\n self.num_hidden_layers = len(depths)\n self.hidden_size = embed_dim\n self.seq_length = (image_size // patch_size) ** 2", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n task_inputs: Optional[List[str]] = None,\n segmentation_maps: Optional[ImageInput] = None,\n instance_id_to_semantic_id: Optional[Dict[int, int]] = None,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n ignore_index: Optional[int] = None,\n do_reduce_labels: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> BatchFeature:\n if task_inputs is None:\n # Default value\n task_inputs = [\"panoptic\"]\n\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False, max_size=self._max_size)\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n ignore_index = ignore_index if ignore_index is not None else self.ignore_index\n do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n if segmentation_maps is not None and not valid_images(segmentation_maps):\n raise ValueError(\n \"Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n images = make_list_of_images(images)\n if segmentation_maps is not None:\n segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)\n\n if segmentation_maps is not None and len(images) != len(segmentation_maps):\n raise ValueError(\"Images and segmentation maps must have the same length.\")\n\n images = [\n self._preprocess_image(\n image,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n\n if segmentation_maps is not None:\n segmentation_maps = [\n self._preprocess_mask(segmentation_map, do_resize, size, input_data_format=input_data_format)\n for segmentation_map in segmentation_maps\n ]\n encoded_inputs = self.encode_inputs(\n images,\n task_inputs,\n segmentation_maps,\n instance_id_to_semantic_id,\n ignore_index,\n do_reduce_labels,\n return_tensors,\n input_data_format=data_format,\n )\n return encoded_inputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n encoder_hidden_states: np.ndarray | tf.Tensor | None = None,\n encoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[Tuple, TFBaseModelOutputWithPoolingAndCrossAttentions]:\n r\"\"\"\n encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n the model is configured as a decoder.\n encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)\n contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*, defaults to `True`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`). Set to `False` during training, `True` during generation\n \"\"\"\n outputs = self.roberta(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n use_timm_backbone=True,\n backbone_config=None,\n num_channels=3,\n num_queries=300,\n max_position_embeddings=1024,\n encoder_layers=6,\n encoder_ffn_dim=1024,\n encoder_attention_heads=8,\n decoder_layers=6,\n decoder_ffn_dim=1024,\n decoder_attention_heads=8,\n encoder_layerdrop=0.0,\n is_encoder_decoder=True,\n activation_function=\"relu\",\n d_model=256,\n dropout=0.1,\n attention_dropout=0.0,\n activation_dropout=0.0,\n init_std=0.02,\n init_xavier_std=1.0,\n return_intermediate=True,\n auxiliary_loss=False,\n position_embedding_type=\"sine\",\n backbone=\"resnet50\",\n use_pretrained_backbone=True,\n backbone_kwargs=None,\n dilation=False,\n num_feature_levels=4,\n encoder_n_points=4,\n decoder_n_points=4,\n two_stage=False,\n two_stage_num_proposals=300,\n with_box_refine=False,\n class_cost=1,\n bbox_cost=5,\n giou_cost=2,\n mask_loss_coefficient=1,\n dice_loss_coefficient=1,\n bbox_loss_coefficient=5,\n giou_loss_coefficient=2,\n eos_coefficient=0.1,\n focal_alpha=0.25,\n disable_custom_kernels=False,\n **kwargs,\n ):\n # We default to values which were previously hard-coded in the model. This enables configurability of the config\n # while keeping the default behavior the same.\n if use_timm_backbone and backbone_kwargs is None:\n backbone_kwargs = {}\n if dilation:\n backbone_kwargs[\"output_stride\"] = 16\n backbone_kwargs[\"out_indices\"] = [2, 3, 4] if num_feature_levels > 1 else [4]\n backbone_kwargs[\"in_chans\"] = num_channels\n # Backwards compatibility\n elif not use_timm_backbone and backbone in (None, \"resnet50\"):\n if backbone_config is None:\n logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\")\n backbone_config = CONFIG_MAPPING[\"resnet\"](out_features=[\"stage4\"])\n elif isinstance(backbone_config, dict):\n backbone_model_type = backbone_config.get(\"model_type\")\n config_class = CONFIG_MAPPING[backbone_model_type]\n backbone_config = config_class.from_dict(backbone_config)\n\n verify_backbone_config_arguments(\n use_timm_backbone=use_timm_backbone,\n use_pretrained_backbone=use_pretrained_backbone,\n backbone=backbone,\n backbone_config=backbone_config,\n backbone_kwargs=backbone_kwargs,\n )\n\n self.use_timm_backbone = use_timm_backbone\n self.backbone_config = backbone_config\n self.num_channels = num_channels\n self.num_queries = num_queries\n self.max_position_embeddings = max_position_embeddings\n self.d_model = d_model\n self.encoder_ffn_dim = encoder_ffn_dim\n self.encoder_layers = encoder_layers\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_layers = decoder_layers\n self.decoder_attention_heads = decoder_attention_heads\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.activation_dropout = activation_dropout\n self.activation_function = activation_function\n self.init_std = init_std\n self.init_xavier_std = init_xavier_std\n self.encoder_layerdrop = encoder_layerdrop\n self.auxiliary_loss = auxiliary_loss\n self.position_embedding_type = position_embedding_type\n self.backbone = backbone\n self.use_pretrained_backbone = use_pretrained_backbone\n self.backbone_kwargs = backbone_kwargs\n self.dilation = dilation\n # deformable attributes\n self.num_feature_levels = num_feature_levels\n self.encoder_n_points = encoder_n_points\n self.decoder_n_points = decoder_n_points\n self.two_stage = two_stage\n self.two_stage_num_proposals = two_stage_num_proposals\n self.with_box_refine = with_box_refine\n if two_stage is True and with_box_refine is False:\n raise ValueError(\"If two_stage is True, with_box_refine must be True.\")\n # Hungarian matcher\n self.class_cost = class_cost\n self.bbox_cost = bbox_cost\n self.giou_cost = giou_cost\n # Loss coefficients\n self.mask_loss_coefficient = mask_loss_coefficient\n self.dice_loss_coefficient = dice_loss_coefficient\n self.bbox_loss_coefficient = bbox_loss_coefficient\n self.giou_loss_coefficient = giou_loss_coefficient\n self.eos_coefficient = eos_coefficient\n self.focal_alpha = focal_alpha\n self.disable_custom_kernels = disable_custom_kernels\n super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_token_type_ids=False,\n use_input_mask=True,\n use_labels=True,\n use_mc_token_ids=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n num_labels=3,\n num_choices=4,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def open(\n file: Union[str, \"PathLike[str]\", bytes],\n mode: Union[Literal[\"rb\"], Literal[\"rt\"], Literal[\"r\"]] = \"r\",\n buffering: int = -1,\n encoding: Optional[str] = None,\n errors: Optional[str] = None,\n newline: Optional[str] = None,\n *,\n total: Optional[int] = None,\n description: str = \"Reading...\",\n auto_refresh: bool = True,\n console: Optional[Console] = None,\n transient: bool = False,\n get_time: Optional[Callable[[], float]] = None,\n refresh_per_second: float = 10,\n style: StyleType = \"bar.back\",\n complete_style: StyleType = \"bar.complete\",\n finished_style: StyleType = \"bar.finished\",\n pulse_style: StyleType = \"bar.pulse\",\n disable: bool = False,\n) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:\n \"\"\"Read bytes from a file while tracking progress.\n\n Args:\n path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.\n mode (str): The mode to use to open the file. Only supports \"r\", \"rb\" or \"rt\".\n buffering (int): The buffering strategy to use, see :func:`io.open`.\n encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.\n errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.\n newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`\n total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.\n description (str, optional): Description of task show next to progress bar. Defaults to \"Reading\".\n auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n transient: (bool, optional): Clear the progress on exit. Defaults to False.\n console (Console, optional): Console to write to. Default creates internal Console instance.\n refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.finished\".\n pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n disable (bool, optional): Disable display of progress.\n encoding (str, optional): The encoding to use when reading in text mode.\n\n Returns:\n ContextManager[BinaryIO]: A context manager yielding a progress reader.\n\n \"\"\"\n\n columns: List[\"ProgressColumn\"] = (\n [TextColumn(\"[progress.description]{task.description}\")] if description else []\n )\n columns.extend(\n (\n BarColumn(\n style=style,\n complete_style=complete_style,\n finished_style=finished_style,\n pulse_style=pulse_style,\n ),\n DownloadColumn(),\n TimeRemainingColumn(),\n )\n )\n progress = Progress(\n *columns,\n auto_refresh=auto_refresh,\n console=console,\n transient=transient,\n get_time=get_time,\n refresh_per_second=refresh_per_second or 10,\n disable=disable,\n )\n\n reader = progress.open(\n file,\n mode=mode,\n buffering=buffering,\n encoding=encoding,\n errors=errors,\n newline=newline,\n total=total,\n description=description,\n )\n return _ReadContext(progress, reader) # type: ignore[return-value, type-var]", "smellKey": "S107", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def __init__(\n self,\n *,\n pres_ex_id: Optional[str] = None,\n connection_id: Optional[str] = None,\n thread_id: Optional[str] = None,\n initiator: Optional[str] = None,\n role: Optional[str] = None,\n state: Optional[str] = None,\n pres_proposal: Union[V20PresProposal, Mapping] = None, # aries message\n pres_request: Union[V20PresRequest, Mapping] = None, # aries message\n pres: Union[V20Pres, Mapping] = None, # aries message\n verified: Optional[str] = None,\n verified_msgs: Optional[list] = None,\n auto_present: bool = False,\n auto_verify: bool = False,\n error_msg: Optional[str] = None,\n trace: bool = False, # backward compat: BaseRecord.FromStorage()\n by_format: Optional[Mapping] = None, # backward compat: BaseRecord.FromStorage()\n auto_remove: bool = False,\n **kwargs,\n ):\n \"\"\"Initialize a new PresExRecord.\"\"\"\n super().__init__(pres_ex_id, state, trace=trace, **kwargs)\n self.connection_id = connection_id\n self.thread_id = thread_id\n self.initiator = initiator\n self.role = role\n self.state = state\n self._pres_proposal = V20PresProposal.serde(pres_proposal)\n self._pres_request = V20PresRequest.serde(pres_request)\n self._pres = V20Pres.serde(pres)\n self.verified = verified\n self.verified_msgs = verified_msgs\n self.auto_present = auto_present\n self.auto_verify = auto_verify\n self.error_msg = error_msg\n self.auto_remove = auto_remove", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def __init__(\n self,\n image_config: Dict[str, Any] = None,\n text_config: Dict[str, Any] = None,\n multimodal_config: Dict[str, Any] = None,\n image_codebook_config: Dict[str, Any] = None,\n hidden_size: int = 768,\n layer_norm_eps: float = 1e-12,\n projection_dim: int = 768,\n init_codebook: bool = True,\n logit_scale_init_value: float = 2.6592,\n initializer_range: float = 0.02,\n ce_ignore_index: int = -100,\n mim_weight: float = 1.0,\n mlm_weight: float = 1.0,\n global_contrastive_weight: float = 1.0,\n itm_weight: float = 1.0,\n mmm_image_weight: float = 1.0,\n mmm_text_weight: float = 1.0,\n global_backprop_contrastive: bool = True,\n skip_unmasked_multimodal_encoder: bool = True,\n return_loss: bool = True,\n **kwargs,\n ):\n # If `_config_dict` exist, we use them for the backward compatibility.\n # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot\n # of confusion!).\n text_config_dict = kwargs.pop(\"text_config_dict\", None)\n image_config_dict = kwargs.pop(\"image_config_dict\", None)\n multimodal_config_dict = kwargs.pop(\"multimodal_config_dict\", None)\n image_codebook_config_dict = kwargs.pop(\"image_codebook_config_dict\", None)\n\n super().__init__(**kwargs)\n\n # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in\n # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most\n # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.\n if text_config_dict is not None:\n if text_config is None:\n text_config = {}\n\n # This is the complete result when using `text_config_dict`.\n _text_config_dict = FlavaTextConfig(**text_config_dict).to_dict()\n\n # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.\n for key, value in _text_config_dict.items():\n if key in text_config and value != text_config[key] and key not in [\"transformers_version\"]:\n # If specified in `text_config_dict`\n if key in text_config_dict:\n message = (\n f\"`{key}` is found in both `text_config_dict` and `text_config` but with different values. \"\n f'The value `text_config_dict[\"{key}\"]` will be used instead.'\n )\n # If inferred from default argument values (just to be super careful)\n else:\n message = (\n f\"`text_config_dict` is provided which will be used to initialize `FlavaTextConfig`. The \"\n f'value `text_config[\"{key}\"]` will be overridden.'\n )\n logger.info(message)\n\n # Update all values in `text_config` with the ones in `_text_config_dict`.\n text_config.update(_text_config_dict)\n\n if image_config_dict is not None:\n if image_config is None:\n image_config = {}\n\n # This is the complete result when using `image_config_dict`.\n _image_config_dict = FlavaImageConfig(**image_config_dict).to_dict()\n # convert keys to string instead of integer\n if \"id2label\" in _image_config_dict:\n _image_config_dict[\"id2label\"] = {\n str(key): value for key, value in _image_config_dict[\"id2label\"].items()\n }\n\n # Give a warning if the values exist in both `_image_config_dict` and `image_config` but being different.\n for key, value in _image_config_dict.items():\n if key in image_config and value != image_config[key] and key not in [\"transformers_version\"]:\n # If specified in `image_config_dict`\n if key in image_config_dict:\n message = (\n f\"`{key}` is found in both `image_config_dict` and `image_config` but with different \"\n f'values. The value `image_config_dict[\"{key}\"]` will be used instead.'\n )\n # If inferred from default argument values (just to be super careful)\n else:\n message = (\n f\"`image_config_dict` is provided which will be used to initialize `FlavaImageConfig`. \"\n f'The value `image_config[\"{key}\"]` will be overridden.'\n )\n logger.info(message)\n\n # Update all values in `image_config` with the ones in `_image_config_dict`.\n image_config.update(_image_config_dict)\n\n if multimodal_config_dict is not None:\n if multimodal_config is None:\n multimodal_config = {}\n\n # This is the complete result when using `multimodal_config_dict`.\n _multimodal_config_dict = FlavaMultimodalConfig(**multimodal_config_dict).to_dict()\n\n # Give a warning if the values exist in both `_multimodal_config_dict` and `multimodal_config` but being\n # different.\n for key, value in _multimodal_config_dict.items():\n if (\n key in multimodal_config\n and value != multimodal_config[key]\n and key not in [\"transformers_version\"]\n ):\n # If specified in `multimodal_config_dict`\n if key in multimodal_config_dict:\n message = (\n f\"`{key}` is found in both `multimodal_config_dict` and `multimodal_config` but with \"\n f'different values. The value `multimodal_config_dict[\"{key}\"]` will be used instead.'\n )\n # If inferred from default argument values (just to be super careful)\n else:\n message = (\n f\"`multimodal_config_dict` is provided which will be used to initialize \"\n f'`FlavaMultimodalConfig`. The value `multimodal_config[\"{key}\"]` will be overridden.'\n )\n logger.info(message)\n\n # Update all values in `multimodal_config` with the ones in `_multimodal_config_dict`.\n multimodal_config.update(_multimodal_config_dict)\n\n if image_codebook_config_dict is not None:\n if image_codebook_config is None:\n image_codebook_config = {}\n\n # This is the complete result when using `image_codebook_config_dict`.\n _image_codebook_config_dict = FlavaImageCodebookConfig(**image_codebook_config_dict).to_dict()\n\n # Give a warning if the values exist in both `_image_codebook_config_dict` and `image_codebook_config` but\n # being different.\n for key, value in _image_codebook_config_dict.items():\n if (\n key in image_codebook_config\n and value != image_codebook_config[key]\n and key not in [\"transformers_version\"]\n ):\n # If specified in `image_codebook_config_dict`\n if key in image_codebook_config_dict:\n message = (\n f\"`{key}` is found in both `image_codebook_config_dict` and `image_codebook_config` but \"\n f'with different values. The value `image_codebook_config_dict[\"{key}\"]` will be used '\n \"instead.\"\n )\n # If inferred from default argument values (just to be super careful)\n else:\n message = (\n f\"`image_codebook_config_dict` is provided which will be used to initialize \"\n f'`FlavaImageCodebookConfig`. The value `image_codebook_config[\"{key}\"]` will be overridden.'\n )\n logger.info(message)\n\n # Update all values in `image_codebook_config` with the ones in `_image_codebook_config_dict`.\n image_codebook_config.update(_image_codebook_config_dict)\n\n if image_config is None:\n image_config = {}\n logger.info(\"`image_config` is `None`. initializing the `FlavaImageConfig` with default values.\")\n\n if text_config is None:\n text_config = {}\n logger.info(\"`text_config` is `None`. Initializing the `FlavaTextConfig` with default values.\")\n\n if multimodal_config is None:\n multimodal_config = {}\n logger.info(\"`multimodal_config` is `None`. initializing the `FlavaMultimodalConfig` with default values.\")\n\n if image_codebook_config is None:\n image_codebook_config = {}\n logger.info(\n \"`image_codebook_config` is `None`. initializing the `FlavaImageCodebookConfig` with default values.\"\n )\n\n self.image_config = FlavaImageConfig(**image_config)\n self.text_config = FlavaTextConfig(**text_config)\n self.multimodal_config = FlavaMultimodalConfig(**multimodal_config)\n self.image_codebook_config = FlavaImageCodebookConfig(**image_codebook_config)\n self.projection_dim = projection_dim\n self.init_codebook = init_codebook\n\n self.hidden_size = hidden_size\n self.layer_norm_eps = layer_norm_eps\n self.initializer_range = initializer_range\n self.logit_scale_init_value = logit_scale_init_value\n self.initializer_factor = 1.0\n self.ce_ignore_index = ce_ignore_index\n self.mim_weight = mim_weight\n self.mlm_weight = mlm_weight\n self.global_contrastive_weight = global_contrastive_weight\n self.itm_weight = itm_weight\n self.mmm_image_weight = mmm_image_weight\n self.mmm_text_weight = mmm_text_weight\n self.global_backprop_contrastive = global_backprop_contrastive\n self.skip_unmasked_multimodal_encoder = skip_unmasked_multimodal_encoder\n self.return_loss = return_loss", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFSeq2SeqModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: tf.Tensor | None = None,\n attention_mask: tf.Tensor | None = None,\n decoder_input_ids: tf.Tensor | None = None,\n decoder_attention_mask: tf.Tensor | None = None,\n decoder_position_ids: tf.Tensor | None = None,\n head_mask: tf.Tensor | None = None,\n decoder_head_mask: tf.Tensor | None = None,\n cross_attn_head_mask: tf.Tensor | None = None,\n encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,\n past_key_values: List[tf.Tensor] | None = None,\n inputs_embeds: tf.Tensor | None = None,\n decoder_inputs_embeds: tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n encoder_outputs=encoder_outputs,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n return outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(WHISPER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n @unpack_inputs\n def call(\n self,\n input_features: TFModelInputType | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_position_ids: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n decoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]`\n or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is\n only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import AutoProcessor, TFWhisperForConditionalGeneration\n >>> from datasets import load_dataset\n\n >>> processor = AutoProcessor.from_pretrained(\"openai/whisper-tiny.en\")\n >>> model = TFWhisperForConditionalGeneration.from_pretrained(\"openai/whisper-tiny.en\")\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n >>> inputs = processor(ds[0][\"audio\"][\"array\"], return_tensors=\"tf\")\n >>> input_features = inputs.input_features\n\n >>> generated_ids = model.generate(input_features=input_features)\n\n >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\n >>> transcription\n ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_features,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n decoder_last_hidden_state = outputs[0]\n # Decoder and encoder embeddings are tied\n lm_logits = tf.matmul(decoder_last_hidden_state, self.get_output_embeddings().weights, transpose_b=True)\n\n loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFSeq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=5,\n max_window_layers=3,\n use_sliding_window=True,\n sliding_window=50,\n num_attention_heads=4,\n num_key_value_heads=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n expert_interval=1,\n moe_intermediate_size=12,\n shared_expert_intermediate_size=36,\n shared_expert_gate=True,\n num_experts_per_tok=2,\n num_experts=8,\n norm_topk_prob=False,\n output_router_logits=False,\n router_aux_loss_coef=0.001,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n bos_token_id=1,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.max_window_layers = max_window_layers\n self.use_sliding_window = use_sliding_window\n self.sliding_window = sliding_window\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.scope = scope\n self.expert_interval = expert_interval\n self.moe_intermediate_size = moe_intermediate_size\n self.shared_expert_intermediate_size = shared_expert_intermediate_size\n self.shared_expert_gate = shared_expert_gate\n self.num_experts_per_tok = num_experts_per_tok\n self.num_experts = num_experts\n self.norm_topk_prob = norm_topk_prob\n self.output_router_logits = output_router_logits\n self.router_aux_loss_coef = router_aux_loss_coef", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_features: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n decoder_input_ids: np.ndarray | tf.Tensor | None = None,\n decoder_attention_mask: np.ndarray | tf.Tensor | None = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n decoder_head_mask: np.ndarray | tf.Tensor | None = None,\n cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,\n encoder_outputs: np.ndarray | tf.Tensor | None = None,\n past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,\n decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,\n labels: np.ndarray | tf.Tensor | None = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n **kwargs,\n ) -> Union[Tuple, TFSeq2SeqLMOutput]:\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import Speech2TextProcessor, TFSpeech2TextForConditionalGeneration\n >>> from datasets import load_dataset\n >>> import soundfile as sf\n\n >>> model = TFSpeech2TextForConditionalGeneration.from_pretrained(\n ... \"facebook/s2t-small-librispeech-asr\", from_pt=True\n ... )\n >>> processor = Speech2TextProcessor.from_pretrained(\"facebook/s2t-small-librispeech-asr\")\n\n\n >>> def map_to_array(batch):\n ... speech, _ = sf.read(batch[\"file\"])\n ... batch[\"speech\"] = speech\n ... return batch\n\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> ds = ds.map(map_to_array)\n >>> ds.set_format(type=\"tf\")\n\n >>> input_features = processor(\n ... ds[\"speech\"][0], sampling_rate=16000, return_tensors=\"tf\"\n ... ).input_features # Batch size 1\n >>> generated_ids = model.generate(input_features)\n\n >>> transcription = processor.batch_decode(generated_ids)\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_features=input_features,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n lm_logits = self.lm_head(outputs[0])\n masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return TFSeq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size: int = 224,\n num_channels: int = 3,\n num_encoder_blocks: int = 4,\n depths: List[int] = [2, 2, 2, 2],\n sequence_reduction_ratios: List[int] = [8, 4, 2, 1],\n hidden_sizes: List[int] = [64, 128, 320, 512],\n patch_sizes: List[int] = [4, 2, 2, 2],\n strides: List[int] = [4, 2, 2, 2],\n num_attention_heads: List[int] = [1, 2, 5, 8],\n mlp_ratios: List[int] = [8, 8, 4, 4],\n hidden_act: Mapping[str, Callable] = \"gelu\",\n hidden_dropout_prob: float = 0.0,\n attention_probs_dropout_prob: float = 0.0,\n initializer_range: float = 0.02,\n drop_path_rate: float = 0.0,\n layer_norm_eps: float = 1e-6,\n qkv_bias: bool = True,\n num_labels: int = 1000,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.image_size = image_size\n self.num_channels = num_channels\n self.num_encoder_blocks = num_encoder_blocks\n self.depths = depths\n self.sequence_reduction_ratios = sequence_reduction_ratios\n self.hidden_sizes = hidden_sizes\n self.patch_sizes = patch_sizes\n self.strides = strides\n self.mlp_ratios = mlp_ratios\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.drop_path_rate = drop_path_rate\n self.layer_norm_eps = layer_norm_eps\n self.num_labels = num_labels\n self.qkv_bias = qkv_bias", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_changesets_v3_get_with_http_info(\n self,\n applied_at: Optional[datetime] = None,\n applied_by: Optional[StrictStr] = None,\n chart_release: Optional[StrictStr] = None,\n from_app_version_branch: Optional[StrictStr] = None,\n from_app_version_commit: Optional[StrictStr] = None,\n from_app_version_exact: Optional[StrictStr] = None,\n from_app_version_follow_chart_release: Optional[StrictStr] = None,\n from_app_version_reference: Optional[StrictStr] = None,\n from_app_version_resolver: Optional[StrictStr] = None,\n from_chart_version_exact: Optional[StrictStr] = None,\n from_chart_version_follow_chart_release: Optional[StrictStr] = None,\n from_chart_version_reference: Optional[StrictStr] = None,\n from_chart_version_resolver: Optional[StrictStr] = None,\n from_helmfile_ref: Optional[StrictStr] = None,\n from_helmfile_ref_enabled: Optional[StrictBool] = None,\n from_resolved_at: Optional[datetime] = None,\n planned_by: Optional[StrictStr] = None,\n superseded_at: Optional[datetime] = None,\n to_app_version_branch: Optional[StrictStr] = None,\n to_app_version_commit: Optional[StrictStr] = None,\n to_app_version_exact: Optional[StrictStr] = None,\n to_app_version_follow_chart_release: Optional[StrictStr] = None,\n to_app_version_reference: Optional[StrictStr] = None,\n to_app_version_resolver: Optional[StrictStr] = None,\n to_chart_version_exact: Optional[StrictStr] = None,\n to_chart_version_follow_chart_release: Optional[StrictStr] = None,\n to_chart_version_reference: Optional[StrictStr] = None,\n to_chart_version_resolver: Optional[StrictStr] = None,\n to_helmfile_ref: Optional[StrictStr] = None,\n to_helmfile_ref_enabled: Optional[StrictBool] = None,\n to_resolved_at: Optional[datetime] = None,\n id: Annotated[Optional[List[StrictInt]], Field(description=\"Get specific changesets by their IDs, can be passed multiple times and/or be comma-separated\")] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many Changesets are returned (default 100), ignored if specific IDs are passed\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned Changesets (default 0), ignored if specific IDs are passed\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> ApiResponse[List[SherlockChangesetV3]]:\n \"\"\"List Changesets matching a filter\n\n List Changesets matching a filter.\n\n :param applied_at:\n :type applied_at: datetime\n :param applied_by:\n :type applied_by: str\n :param chart_release:\n :type chart_release: str\n :param from_app_version_branch:\n :type from_app_version_branch: str\n :param from_app_version_commit:\n :type from_app_version_commit: str\n :param from_app_version_exact:\n :type from_app_version_exact: str\n :param from_app_version_follow_chart_release:\n :type from_app_version_follow_chart_release: str\n :param from_app_version_reference:\n :type from_app_version_reference: str\n :param from_app_version_resolver:\n :type from_app_version_resolver: str\n :param from_chart_version_exact:\n :type from_chart_version_exact: str\n :param from_chart_version_follow_chart_release:\n :type from_chart_version_follow_chart_release: str\n :param from_chart_version_reference:\n :type from_chart_version_reference: str\n :param from_chart_version_resolver:\n :type from_chart_version_resolver: str\n :param from_helmfile_ref:\n :type from_helmfile_ref: str\n :param from_helmfile_ref_enabled:\n :type from_helmfile_ref_enabled: bool\n :param from_resolved_at:\n :type from_resolved_at: datetime\n :param planned_by:\n :type planned_by: str\n :param superseded_at:\n :type superseded_at: datetime\n :param to_app_version_branch:\n :type to_app_version_branch: str\n :param to_app_version_commit:\n :type to_app_version_commit: str\n :param to_app_version_exact:\n :type to_app_version_exact: str\n :param to_app_version_follow_chart_release:\n :type to_app_version_follow_chart_release: str\n :param to_app_version_reference:\n :type to_app_version_reference: str\n :param to_app_version_resolver:\n :type to_app_version_resolver: str\n :param to_chart_version_exact:\n :type to_chart_version_exact: str\n :param to_chart_version_follow_chart_release:\n :type to_chart_version_follow_chart_release: str\n :param to_chart_version_reference:\n :type to_chart_version_reference: str\n :param to_chart_version_resolver:\n :type to_chart_version_resolver: str\n :param to_helmfile_ref:\n :type to_helmfile_ref: str\n :param to_helmfile_ref_enabled:\n :type to_helmfile_ref_enabled: bool\n :param to_resolved_at:\n :type to_resolved_at: datetime\n :param id: Get specific changesets by their IDs, can be passed multiple times and/or be comma-separated\n :type id: List[int]\n :param limit: Control how many Changesets are returned (default 100), ignored if specific IDs are passed\n :type limit: int\n :param offset: Control the offset for the returned Changesets (default 0), ignored if specific IDs are passed\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_changesets_v3_get_serialize(\n applied_at=applied_at,\n applied_by=applied_by,\n chart_release=chart_release,\n from_app_version_branch=from_app_version_branch,\n from_app_version_commit=from_app_version_commit,\n from_app_version_exact=from_app_version_exact,\n from_app_version_follow_chart_release=from_app_version_follow_chart_release,\n from_app_version_reference=from_app_version_reference,\n from_app_version_resolver=from_app_version_resolver,\n from_chart_version_exact=from_chart_version_exact,\n from_chart_version_follow_chart_release=from_chart_version_follow_chart_release,\n from_chart_version_reference=from_chart_version_reference,\n from_chart_version_resolver=from_chart_version_resolver,\n from_helmfile_ref=from_helmfile_ref,\n from_helmfile_ref_enabled=from_helmfile_ref_enabled,\n from_resolved_at=from_resolved_at,\n planned_by=planned_by,\n superseded_at=superseded_at,\n to_app_version_branch=to_app_version_branch,\n to_app_version_commit=to_app_version_commit,\n to_app_version_exact=to_app_version_exact,\n to_app_version_follow_chart_release=to_app_version_follow_chart_release,\n to_app_version_reference=to_app_version_reference,\n to_app_version_resolver=to_app_version_resolver,\n to_chart_version_exact=to_chart_version_exact,\n to_chart_version_follow_chart_release=to_chart_version_follow_chart_release,\n to_chart_version_reference=to_chart_version_reference,\n to_chart_version_resolver=to_chart_version_resolver,\n to_helmfile_ref=to_helmfile_ref,\n to_helmfile_ref_enabled=to_helmfile_ref_enabled,\n to_resolved_at=to_resolved_at,\n id=id,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockChangesetV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n response_data.read()\n return self.api_client.response_deserialize(\n response_data=response_data,\n response_types_map=_response_types_map,\n )", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(LONGT5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,\n config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for\n labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, LongT5ForConditionalGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"Stancld/longt5-tglobal-large-16384-pubmed-3k_steps\")\n >>> model = LongT5ForConditionalGeneration.from_pretrained(\n ... \"Stancld/longt5-tglobal-large-16384-pubmed-3k_steps\"\n ... )\n\n >>> # Let's try a very long input.\n >>> inputs = tokenizer(100 * \"studies have shown that owning a dog is good for you \", return_tensors=\"pt\")\n >>> input_ids = inputs.input_ids\n\n >>> outputs = model.generate(input_ids)\n >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))\n abstractthe aim of this article is to provide an overview of the literature on the role of dog\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n # Convert encoder inputs in embeddings if needed\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n if self.config.tie_word_embeddings:\n # Rescale output before projecting on vocab\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\n sequence_output = sequence_output * (self.model_dim**-0.5)\n\n lm_logits = self.lm_head(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-100)\n\n labels = labels.to(lm_logits.device)\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))\n # TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666\n\n if not return_dict:\n output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,\n config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for\n labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, T5ForConditionalGeneration\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google-t5/t5-small\")\n >>> model = T5ForConditionalGeneration.from_pretrained(\"google-t5/t5-small\")\n\n >>> # training\n >>> input_ids = tokenizer(\"The <extra_id_0> walks in <extra_id_1> park\", return_tensors=\"pt\").input_ids\n >>> labels = tokenizer(\"<extra_id_0> cute dog <extra_id_1> the <extra_id_2>\", return_tensors=\"pt\").input_ids\n >>> outputs = model(input_ids=input_ids, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> input_ids = tokenizer(\n ... \"summarize: studies have shown that owning a dog is good for you\", return_tensors=\"pt\"\n ... ).input_ids # Batch size 1\n >>> outputs = model.generate(input_ids)\n >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))\n >>> # studies have shown that owning a dog is good for you.\n ```\"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n # Convert encoder inputs in embeddings if needed\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if self.model_parallel:\n torch.cuda.set_device(self.decoder.first_device)\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n\n # Set device for model parallelism\n if self.model_parallel:\n torch.cuda.set_device(self.decoder.first_device)\n hidden_states = hidden_states.to(self.decoder.first_device)\n if decoder_input_ids is not None:\n decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)\n if attention_mask is not None:\n attention_mask = attention_mask.to(self.decoder.first_device)\n if decoder_attention_mask is not None:\n decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)\n\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n # Set device for model parallelism\n if self.model_parallel:\n torch.cuda.set_device(self.encoder.first_device)\n self.lm_head = self.lm_head.to(self.encoder.first_device)\n sequence_output = sequence_output.to(self.lm_head.weight.device)\n\n if self.config.tie_word_embeddings:\n # Rescale output before projecting on vocab\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\n sequence_output = sequence_output * (self.model_dim**-0.5)\n\n lm_logits = self.lm_head(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-100)\n # move labels to correct device to enable PP\n labels = labels.to(lm_logits.device)\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))\n # TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666\n\n if not return_dict:\n output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(ROC_BERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n input_shape_ids: Optional[torch.Tensor] = None,\n input_pronunciation_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Example:\n ```python\n >>> from transformers import AutoTokenizer, RoCBertForMaskedLM\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"weiweishi/roc-bert-base-zh\")\n >>> model = RoCBertForMaskedLM.from_pretrained(\"weiweishi/roc-bert-base-zh\")\n\n >>> inputs = tokenizer(\"\u6cd5\u56fd\u662f\u9996\u90fd[MASK].\", return_tensors=\"pt\")\n\n >>> with torch.no_grad():\n ... logits = model(**inputs).logits\n\n >>> # retrieve index of {mask}\n >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]\n\n >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)\n >>> tokenizer.decode(predicted_token_id)\n '.'\n ```\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.roc_bert(\n input_ids,\n input_shape_ids=input_shape_ids,\n input_pronunciation_ids=input_pronunciation_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss() # -100 index = padding token\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return MaskedLMOutput(\n loss=masked_lm_loss,\n logits=prediction_scores,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _preprocess_image(\n self,\n image: ImageInput,\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_map_pixels: bool = None,\n data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,\n input_data_format: Optional[ChannelDimension] = None,\n ) -> np.ndarray:\n \"\"\"Preprocesses a single image.\"\"\"\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n\n # All transformations expect numpy arrays.\n image = to_numpy_array(image)\n\n if is_scaled_image(image) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(image)\n\n if do_resize:\n image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n\n if do_center_crop:\n image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)\n\n if do_rescale:\n image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n\n if do_normalize:\n image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n\n if do_map_pixels:\n image = self.map_pixels(image)\n\n if data_format is not None:\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=8,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_center_crop=True,\n crop_size=None,\n do_normalize=True,\n image_mean=OPENAI_CLIP_MEAN,\n image_std=OPENAI_CLIP_STD,\n do_convert_rgb=True,\n ):\n size = size if size is not None else {\"shortest_edge\": 20}\n crop_size = crop_size if crop_size is not None else {\"height\": 18, \"width\": 18}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_center_crop = do_center_crop\n self.crop_size = crop_size\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std\n self.do_convert_rgb = do_convert_rgb", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file=None,\n tokenizer_file=None,\n do_lower_case=True,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n cls_token_box=[0, 0, 0, 0],\n sep_token_box=[1000, 1000, 1000, 1000],\n pad_token_box=[0, 0, 0, 0],\n pad_token_label=-100,\n only_label_first_subword=True,\n tokenize_chinese_chars=True,\n strip_accents=None,\n **kwargs,\n ):\n super().__init__(\n vocab_file,\n tokenizer_file=tokenizer_file,\n do_lower_case=do_lower_case,\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n cls_token_box=cls_token_box,\n sep_token_box=sep_token_box,\n pad_token_box=pad_token_box,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n tokenize_chinese_chars=tokenize_chinese_chars,\n strip_accents=strip_accents,\n **kwargs,\n )\n\n pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())\n if (\n pre_tok_state.get(\"lowercase\", do_lower_case) != do_lower_case\n or pre_tok_state.get(\"strip_accents\", strip_accents) != strip_accents\n ):\n pre_tok_class = getattr(normalizers, pre_tok_state.pop(\"type\"))\n pre_tok_state[\"lowercase\"] = do_lower_case\n pre_tok_state[\"strip_accents\"] = strip_accents\n self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)\n\n self.do_lower_case = do_lower_case\n\n # additional properties\n self.cls_token_box = cls_token_box\n self.sep_token_box = sep_token_box\n self.pad_token_box = pad_token_box\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n videos: Union[ImageInput, List[ImageInput], List[List[ImageInput]]],\n do_resize: bool = None,\n size: Dict[str, int] = None,\n resample: PILImageResampling = None,\n do_center_crop: bool = None,\n crop_size: Dict[str, int] = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_pad: bool = None,\n pad_size: Dict[str, int] = None,\n constant_values: Union[float, Iterable[float]] = None,\n pad_mode: PaddingMode = None,\n do_normalize: bool = None,\n do_flip_channel_order: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n videos (`ImageInput` or `List[ImageInput]` or `List[List[ImageInput]]`):\n Frames to preprocess.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after applying resize.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):\n Whether to centre crop the image.\n crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):\n Size of the image after applying the centre crop.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_pad (`bool`, *optional*, defaults to `True`):\n Whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess` method.\n pad_size (`Dict[str, int]`, *optional*, defaults to `{\"height\": 448, \"width\": 448}`):\n Size of the image after applying the padding. Can be overridden by the `pad_size` parameter in the\n `preprocess` method.\n constant_values (`Union[float, Iterable[float]]`, *optional*, defaults to 0):\n The fill value to use when padding the image.\n pad_mode (`PaddingMode`, *optional*, defaults to \"PaddingMode.CONSTANT\"):\n Use what kind of mode in padding.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):\n Whether to flip the channel order of the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the inferred channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n resample = resample if resample is not None else self.resample\n do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_pad = do_pad if do_pad is not None else self.do_pad\n pad_size = pad_size if pad_size is not None else self.pad_size\n constant_values = constant_values if constant_values is not None else self.constant_values\n pad_mode = pad_mode if pad_mode else self.pad_mode\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n do_flip_channel_order = (\n do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order\n )\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n crop_size = crop_size if crop_size is not None else self.crop_size\n crop_size = get_size_dict(crop_size, param_name=\"crop_size\")\n\n if not valid_images(videos):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n videos = make_batched(videos)\n\n videos = [\n np.array(\n [\n self._preprocess_image(\n image=img,\n do_resize=do_resize,\n size=size,\n resample=resample,\n do_center_crop=do_center_crop,\n crop_size=crop_size,\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_pad=do_pad,\n pad_size=pad_size,\n constant_values=constant_values,\n pad_mode=pad_mode,\n do_normalize=do_normalize,\n do_flip_channel_order=do_flip_channel_order,\n image_mean=image_mean,\n image_std=image_std,\n data_format=data_format,\n input_data_format=input_data_format,\n )\n for img in video\n ]\n )\n for video in videos\n ]\n\n data = {\"pixel_values\": videos}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=256000,\n hidden_size=3072,\n intermediate_size=24576,\n num_hidden_layers=28,\n num_attention_heads=16,\n num_key_value_heads=16,\n head_dim=256,\n hidden_act=\"gelu_pytorch_tanh\",\n hidden_activation=None,\n max_position_embeddings=8192,\n initializer_range=0.02,\n rms_norm_eps=1e-6,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n bos_token_id=2,\n tie_word_embeddings=True,\n rope_theta=10000.0,\n attention_bias=False,\n attention_dropout=0.0,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.max_position_embeddings = max_position_embeddings\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.head_dim = head_dim\n self.num_key_value_heads = num_key_value_heads\n self.hidden_act = hidden_act\n self.hidden_activation = hidden_activation\n self.initializer_range = initializer_range\n self.rms_norm_eps = rms_norm_eps\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.attention_bias = attention_bias\n self.attention_dropout = attention_dropout\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@unpack_inputs\n @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFTokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids: TFModelInputType | None = None,\n attention_mask: np.ndarray | tf.Tensor | None = None,\n langs: np.ndarray | tf.Tensor | None = None,\n token_type_ids: np.ndarray | tf.Tensor | None = None,\n position_ids: np.ndarray | tf.Tensor | None = None,\n lengths: np.ndarray | tf.Tensor | None = None,\n cache: Optional[Dict[str, tf.Tensor]] = None,\n head_mask: np.ndarray | tf.Tensor | None = None,\n inputs_embeds: np.ndarray | tf.Tensor | None = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: np.ndarray | tf.Tensor | None = None,\n training: bool = False,\n ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n \"\"\"\n transformer_outputs = self.transformer(\n input_ids=input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n sequence_output = transformer_outputs[0]\n\n sequence_output = self.dropout(sequence_output, training=training)\n logits = self.classifier(sequence_output)\n\n loss = None if labels is None else self.hf_compute_loss(labels, logits)\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFTokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n patch_embed_hidden_size=768,\n d_ff=2048,\n d_kv=64,\n num_hidden_layers=12,\n num_attention_heads=12,\n dense_act_fn=\"gelu_new\",\n layer_norm_eps=1e-6,\n dropout_rate=0.0,\n attention_dropout=0.0,\n initializer_range=1e-10,\n initializer_factor=1.0,\n seq_len=4096,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.patch_embed_hidden_size = patch_embed_hidden_size\n self.d_ff = d_ff\n self.dropout_rate = dropout_rate\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.initializer_range = initializer_range\n self.initializer_factor = initializer_factor\n self.attention_dropout = attention_dropout\n self.layer_norm_eps = layer_norm_eps\n self.dense_act_fn = dense_act_fn\n self.seq_len = seq_len\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n self.d_kv = d_kv", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def add_code_sample_docstrings(\n *docstr,\n processor_class=None,\n checkpoint=None,\n output_type=None,\n config_class=None,\n mask=\"[MASK]\",\n qa_target_start_index=14,\n qa_target_end_index=15,\n model_cls=None,\n modality=None,\n expected_output=None,\n expected_loss=None,\n real_checkpoint=None,\n revision=None,\n):\n def docstring_decorator(fn):\n # model_class defaults to function's class if not specified otherwise\n model_class = fn.__qualname__.split(\".\")[0] if model_cls is None else model_cls\n\n if model_class[:2] == \"TF\":\n sample_docstrings = TF_SAMPLE_DOCSTRINGS\n elif model_class[:4] == \"Flax\":\n sample_docstrings = FLAX_SAMPLE_DOCSTRINGS\n else:\n sample_docstrings = PT_SAMPLE_DOCSTRINGS\n\n # putting all kwargs for docstrings in a dict to be used\n # with the `.format(**doc_kwargs)`. Note that string might\n # be formatted with non-existing keys, which is fine.\n doc_kwargs = {\n \"model_class\": model_class,\n \"processor_class\": processor_class,\n \"checkpoint\": checkpoint,\n \"mask\": mask,\n \"qa_target_start_index\": qa_target_start_index,\n \"qa_target_end_index\": qa_target_end_index,\n \"expected_output\": expected_output,\n \"expected_loss\": expected_loss,\n \"real_checkpoint\": real_checkpoint,\n \"fake_checkpoint\": checkpoint,\n \"true\": \"{true}\", # For <Tip warning={true}> syntax that conflicts with formatting.\n }\n\n if (\"SequenceClassification\" in model_class or \"AudioClassification\" in model_class) and modality == \"audio\":\n code_sample = sample_docstrings[\"AudioClassification\"]\n elif \"SequenceClassification\" in model_class:\n code_sample = sample_docstrings[\"SequenceClassification\"]\n elif \"QuestionAnswering\" in model_class:\n code_sample = sample_docstrings[\"QuestionAnswering\"]\n elif \"TokenClassification\" in model_class:\n code_sample = sample_docstrings[\"TokenClassification\"]\n elif \"MultipleChoice\" in model_class:\n code_sample = sample_docstrings[\"MultipleChoice\"]\n elif \"MaskedLM\" in model_class or model_class in [\"FlaubertWithLMHeadModel\", \"XLMWithLMHeadModel\"]:\n code_sample = sample_docstrings[\"MaskedLM\"]\n elif \"LMHead\" in model_class or \"CausalLM\" in model_class:\n code_sample = sample_docstrings[\"LMHead\"]\n elif \"CTC\" in model_class:\n code_sample = sample_docstrings[\"CTC\"]\n elif \"AudioFrameClassification\" in model_class:\n code_sample = sample_docstrings[\"AudioFrameClassification\"]\n elif \"XVector\" in model_class and modality == \"audio\":\n code_sample = sample_docstrings[\"AudioXVector\"]\n elif \"Model\" in model_class and modality == \"audio\":\n code_sample = sample_docstrings[\"SpeechBaseModel\"]\n elif \"Model\" in model_class and modality == \"vision\":\n code_sample = sample_docstrings[\"VisionBaseModel\"]\n elif \"Model\" in model_class or \"Encoder\" in model_class:\n code_sample = sample_docstrings[\"BaseModel\"]\n elif \"ImageClassification\" in model_class:\n code_sample = sample_docstrings[\"ImageClassification\"]\n else:\n raise ValueError(f\"Docstring can't be built for model {model_class}\")\n\n code_sample = filter_outputs_from_example(\n code_sample, expected_output=expected_output, expected_loss=expected_loss\n )\n if real_checkpoint is not None:\n code_sample = FAKE_MODEL_DISCLAIMER + code_sample\n func_doc = (fn.__doc__ or \"\") + \"\".join(docstr)\n output_doc = \"\" if output_type is None else _prepare_output_docstrings(output_type, config_class)\n built_doc = code_sample.format(**doc_kwargs)\n if revision is not None:\n if re.match(r\"^refs/pr/\\\\d+\", revision):\n raise ValueError(\n f\"The provided revision '{revision}' is incorrect. It should point to\"\n \" a pull request reference on the hub like 'refs/pr/6'\"\n )\n built_doc = built_doc.replace(\n f'from_pretrained(\"{checkpoint}\")', f'from_pretrained(\"{checkpoint}\", revision=\"{revision}\")'\n )\n fn.__doc__ = func_doc + output_doc + built_doc\n return fn\n\n return docstring_decorator", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _get_batch_list_from_inputs( # noqa: PLR0913\n self,\n datasource_name: str | None,\n data_connector_name: str | None,\n data_asset_name: str | None,\n batch: Batch | None,\n batch_list: List[Batch] | None,\n batch_request: BatchRequestBase | FluentBatchRequest | None,\n batch_request_list: List[BatchRequestBase] | None,\n batch_data: Any,\n data_connector_query: Union[IDDict, dict] | None,\n batch_identifiers: dict | None,\n limit: int | None,\n index: int | list | tuple | slice | str | None,\n custom_filter_function: Callable | None,\n sampling_method: str | None,\n sampling_kwargs: dict | None,\n partitioner_method: str | None,\n partitioner_kwargs: dict | None,\n runtime_parameters: dict | None,\n query: str | None,\n path: str | None,\n batch_filter_parameters: dict | None,\n batch_spec_passthrough: dict | None,\n **kwargs,\n ) -> List[Batch]:\n if (\n sum(\n bool(x)\n for x in [\n batch is not None,\n batch_list is not None,\n batch_request is not None,\n batch_request_list is not None,\n ]\n )\n > 1\n ):\n raise ValueError( # noqa: TRY003\n \"No more than one of batch, batch_list, batch_request, or batch_request_list can be specified\" # noqa: E501\n )\n\n if batch_list:\n return batch_list\n\n if batch:\n return [batch]\n\n computed_batch_list: List[Batch] = []\n if not batch_request_list:\n # batch_request could actually be None here since we do explicit None checks in the\n # sum check above while here we do a truthy check.\n batch_request_list = [batch_request] # type: ignore[list-item]\n for batch_req in batch_request_list:\n computed_batch_list.append(\n self.get_last_batch(\n datasource_name=datasource_name,\n data_connector_name=data_connector_name,\n data_asset_name=data_asset_name,\n batch_request=batch_req,\n batch_data=batch_data,\n data_connector_query=data_connector_query,\n batch_identifiers=batch_identifiers,\n limit=limit,\n index=index,\n custom_filter_function=custom_filter_function,\n sampling_method=sampling_method,\n sampling_kwargs=sampling_kwargs,\n partitioner_method=partitioner_method,\n partitioner_kwargs=partitioner_kwargs,\n runtime_parameters=runtime_parameters,\n query=query,\n path=path,\n batch_filter_parameters=batch_filter_parameters,\n batch_spec_passthrough=batch_spec_passthrough,\n **kwargs,\n )\n )\n return computed_batch_list", "smellKey": "S107", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "@pytest.mark.parametrize(\n 'platform_name, filter_stages, sysbuild,' \\\n ' do_find_cache, west_flash_options, edt_exists,' \\\n ' parse_results, testsuite_filter,' \\\n ' expected_defconfig_path, expected_edt_pickle_path,' \\\n ' expected_defconfig, expected_cmakecache, expected_filter_data,' \\\n ' expected_edt,' \\\n ' expected_logs, expected_return',\n TESTDATA_3,\n ids=['unit testing', 'domain', 'kconfig', 'no cache',\n 'no west options', 'no edt',\n 'parse result', 'no parse result', 'no testsuite filter', 'parse err']\n)\ndef test_filterbuilder_parse_generated(\n caplog,\n mocked_jobserver,\n platform_name,\n filter_stages,\n sysbuild,\n do_find_cache,\n west_flash_options,\n edt_exists,\n parse_results,\n testsuite_filter,\n expected_defconfig_path,\n expected_edt_pickle_path,\n expected_defconfig,\n expected_cmakecache,\n expected_filter_data,\n expected_edt,\n expected_logs,\n expected_return\n):\n def mock_domains_from_file(*args, **kwargs):\n dom = mock.Mock()\n dom.build_dir = os.path.join('domain', 'build', 'dir')\n res = mock.Mock(get_default_domain=mock.Mock(return_value=dom))\n return res\n\n def mock_cmakecache_from_file(*args, **kwargs):\n if not do_find_cache:\n raise FileNotFoundError(errno.ENOENT, 'Cache not found')\n cache_elem = mock.Mock()\n cache_elem.name = 'dummy cache elem'\n cache_elem.value = 1\n cache = [cache_elem]\n return cache\n\n def mock_open(filepath, type, *args, **kwargs):\n if filepath == expected_defconfig_path:\n rd = 'I am not a proper line\\n' \\\n 'CONFIG_FOO=\"no\"'\n elif filepath == expected_edt_pickle_path:\n rd = b'dummy edt pickle contents'\n else:\n raise FileNotFoundError(errno.ENOENT,\n f'File {filepath} not mocked.')\n return mock.mock_open(read_data=rd)()\n\n def mock_parser(filter, filter_data, edt):\n assert filter_data == expected_filter_data\n if isinstance(parse_results, type) and \\\n issubclass(parse_results, Exception):\n raise parse_results\n return parse_results\n\n def mock_pickle(datafile):\n assert datafile.read() == expected_edt\n return mock.Mock()\n\n testsuite_mock = mock.Mock()\n testsuite_mock.name = 'dummy.testsuite.name'\n testsuite_mock.filter = testsuite_filter\n platform_mock = mock.Mock()\n platform_mock.name = platform_name\n platform_mock.arch = 'dummy arch'\n source_dir = os.path.join('source', 'dir')\n build_dir = os.path.join('build', 'dir')\n\n fb = FilterBuilder(testsuite_mock, platform_mock, source_dir, build_dir,\n mocked_jobserver)\n instance_mock = mock.Mock()\n instance_mock.sysbuild = 'sysbuild' if sysbuild else None\n fb.instance = instance_mock\n fb.env = mock.Mock()\n fb.env.options = mock.Mock()\n fb.env.options.west_flash = west_flash_options\n fb.env.options.device_testing = True\n\n environ_mock = {'env_dummy': True}\n\n with mock.patch('twisterlib.runner.Domains.from_file',\n mock_domains_from_file), \\\n mock.patch('twisterlib.runner.CMakeCache.from_file',\n mock_cmakecache_from_file), \\\n mock.patch('builtins.open', mock_open), \\\n mock.patch('expr_parser.parse', mock_parser), \\\n mock.patch('pickle.load', mock_pickle), \\\n mock.patch('os.path.exists', return_value=edt_exists), \\\n mock.patch('os.environ', environ_mock), \\\n pytest.raises(expected_return) if \\\n isinstance(parse_results, type) and \\\n issubclass(parse_results, Exception) else nullcontext() as err:\n result = fb.parse_generated(filter_stages)\n\n if err:\n assert True\n return\n\n assert all([log in caplog.text for log in expected_logs])\n\n assert fb.defconfig == expected_defconfig\n\n assert fb.cmake_cache == expected_cmakecache\n\n assert result == expected_return", "smellKey": "S107", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)\n def prepare_for_model(\n self,\n ids: List[int],\n pair_ids: Optional[List[int]] = None,\n add_special_tokens: bool = True,\n padding: Union[bool, str, PaddingStrategy] = False,\n truncation: Union[bool, str, TruncationStrategy] = None,\n max_length: Optional[int] = None,\n stride: int = 0,\n pad_to_multiple_of: Optional[int] = None,\n padding_side: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_token_type_ids: Optional[bool] = None,\n return_attention_mask: Optional[bool] = None,\n return_overflowing_tokens: bool = False,\n return_special_tokens_mask: bool = False,\n return_offsets_mapping: bool = False,\n return_length: bool = False,\n verbose: bool = True,\n prepend_batch_axis: bool = False,\n **kwargs,\n ) -> BatchEncoding:\n \"\"\"\n Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It\n adds special tokens, truncates sequences if overflowing while taking into account the special tokens and\n manages a moving window (with user defined stride) for overflowing tokens. Please Note, for *pair_ids*\n different than `None` and *truncation_strategy = longest_first* or `True`, it is not possible to return\n overflowing tokens. Such a combination of arguments will raise an error.\n\n Args:\n ids (`List[int]`):\n Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and\n `convert_tokens_to_ids` methods.\n pair_ids (`List[int]`, *optional*):\n Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`\n and `convert_tokens_to_ids` methods.\n \"\"\"\n\n # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'\n padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(\n padding=padding,\n truncation=truncation,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n verbose=verbose,\n **kwargs,\n )\n\n pair = bool(pair_ids is not None)\n len_ids = len(ids)\n len_pair_ids = len(pair_ids) if pair else 0\n\n if return_token_type_ids and not add_special_tokens:\n raise ValueError(\n \"Asking to return token_type_ids while setting add_special_tokens to False \"\n \"results in an undefined behavior. Please set add_special_tokens to True or \"\n \"set return_token_type_ids to None.\"\n )\n\n if (\n return_overflowing_tokens\n and truncation_strategy == TruncationStrategy.LONGEST_FIRST\n and pair_ids is not None\n ):\n raise ValueError(\n \"Not possible to return overflowing tokens for pair of sequences with the \"\n \"`longest_first`. Please select another truncation strategy than `longest_first`, \"\n \"for instance `only_second` or `only_first`.\"\n )\n\n # Load from model defaults\n if return_token_type_ids is None:\n return_token_type_ids = \"token_type_ids\" in self.model_input_names\n if return_attention_mask is None:\n return_attention_mask = \"attention_mask\" in self.model_input_names\n\n encoded_inputs = {}\n\n # Compute the total size of the returned encodings\n total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)\n\n # Truncation: Handle max sequence length\n overflowing_tokens = []\n if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:\n ids, pair_ids, overflowing_tokens = self.truncate_sequences(\n ids,\n pair_ids=pair_ids,\n num_tokens_to_remove=total_len - max_length,\n truncation_strategy=truncation_strategy,\n stride=stride,\n )\n\n if return_overflowing_tokens:\n encoded_inputs[\"overflowing_tokens\"] = overflowing_tokens\n encoded_inputs[\"num_truncated_tokens\"] = total_len - max_length\n\n # Add special tokens\n if add_special_tokens:\n sequence = self.build_inputs_with_special_tokens(ids, pair_ids)\n token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)\n else:\n sequence = ids + pair_ids if pair else ids\n token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])\n\n # Build output dictionary\n encoded_inputs[\"input_ids\"] = sequence\n if return_token_type_ids:\n encoded_inputs[\"token_type_ids\"] = token_type_ids\n if return_special_tokens_mask:\n if add_special_tokens:\n encoded_inputs[\"special_tokens_mask\"] = self.get_special_tokens_mask(ids, pair_ids)\n else:\n encoded_inputs[\"special_tokens_mask\"] = [0] * len(sequence)\n\n # Check lengths\n self._eventual_warn_about_too_long_sequence(encoded_inputs[\"input_ids\"], max_length, verbose)\n\n # Padding\n if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:\n encoded_inputs = self.pad(\n encoded_inputs,\n max_length=max_length,\n padding=padding_strategy.value,\n pad_to_multiple_of=pad_to_multiple_of,\n padding_side=padding_side,\n return_attention_mask=return_attention_mask,\n )\n\n if return_length:\n encoded_inputs[\"length\"] = len(encoded_inputs[\"input_ids\"])\n\n batch_outputs = BatchEncoding(\n encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis\n )\n\n return batch_outputs", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size: int = 128256,\n hidden_size: int = 4096,\n hidden_act: str = \"silu\",\n num_hidden_layers: int = 40,\n num_attention_heads: int = 32,\n num_key_value_heads: int = 8,\n intermediate_size: int = 14_336,\n rope_theta: float = 500_000,\n rope_scaling: Optional[Dict] = None,\n rms_norm_eps: float = 1e-5,\n max_position_embeddings: int = 131_072,\n initializer_range: float = 0.02,\n use_cache: bool = True,\n tie_word_embeddings: bool = False,\n cross_attention_layers: Optional[List[int]] = None,\n dropout: float = 0,\n bos_token_id: int = 128000,\n eos_token_id: int = 128001,\n pad_token_id: Optional[int] = 128004,\n **kwargs,\n ):\n if cross_attention_layers is None:\n cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38]\n\n self.vocab_size = vocab_size\n self.num_hidden_layers = num_hidden_layers\n self.cross_attention_layers = cross_attention_layers\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.initializer_range = initializer_range\n self.use_cache = use_cache\n self.rope_theta = rope_theta\n self.rms_norm_eps = rms_norm_eps\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.hidden_act = hidden_act\n self.rope_scaling = rope_scaling\n self.max_position_embeddings = max_position_embeddings\n rope_config_validation(self)\n\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n tie_word_embeddings=tie_word_embeddings,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_token_type_ids=True,\n use_input_mask=True,\n use_labels=True,\n use_mc_token_ids=True,\n vocab_size=256,\n hidden_size=32,\n rotary_dim=4,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_token_type_ids = use_token_type_ids\n self.use_input_mask = use_input_mask\n self.use_labels = use_labels\n self.use_mc_token_ids = use_mc_token_ids\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.rotary_dim = rotary_dim\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def generate(\n self,\n input_features: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,\n synced_gpus: bool = False,\n return_timestamps: Optional[bool] = None,\n task: Optional[str] = None,\n language: Optional[Union[str, List[str]]] = None,\n is_multilingual: Optional[bool] = None,\n prompt_ids: Optional[torch.Tensor] = None,\n prompt_condition_type: Optional[str] = None, # first-segment, all-segments\n condition_on_prev_tokens: Optional[bool] = None,\n temperature: Optional[Union[float, Tuple[float, ...]]] = None,\n compression_ratio_threshold: Optional[float] = None,\n logprob_threshold: Optional[float] = None,\n no_speech_threshold: Optional[float] = None,\n num_segment_frames: Optional[int] = None,\n attention_mask: Optional[torch.Tensor] = None,\n time_precision: float = 0.02,\n return_token_timestamps: Optional[bool] = None,\n return_segments: bool = False,\n return_dict_in_generate: Optional[bool] = None,\n **kwargs,\n ):\n \"\"\"\n Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.\n\n <Tip warning={true}>\n\n Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the\n model's default generation configuration. You can override any `generation_config` by passing the corresponding\n parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.\n\n For an overview of generation strategies and code examples, check out the [following\n guide](./generation_strategies).\n\n </Tip>\n\n Parameters:\n input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):\n Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by\n loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via\n the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the\n [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a\n tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] for details.\n generation_config (`~generation.GenerationConfig`, *optional*):\n The generation configuration to be used as base parametrization for the generation call. `**kwargs`\n passed to generate matching the attributes of `generation_config` will override them. If\n `generation_config` is not provided, the default will be used, which had the following loading\n priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model\n configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s\n default values, whose documentation should be checked to parameterize generation.\n logits_processor (`LogitsProcessorList`, *optional*):\n Custom logits processors that complement the default logits processors built from arguments and\n generation config. If a logit processor is passed that is already created with the arguments or a\n generation config an error is thrown. This feature is intended for advanced users.\n stopping_criteria (`StoppingCriteriaList`, *optional*):\n Custom stopping criteria that complement the default stopping criteria built from arguments and a\n generation config. If a stopping criteria is passed that is already created with the arguments or a\n generation config an error is thrown. This feature is intended for advanced users.\n prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):\n If provided, this function constraints the beam search to allowed tokens only at each step. If not\n provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and\n `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned\n on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful\n for constrained generation conditioned on the prefix, as described in [Autoregressive Entity\n Retrieval](https://arxiv.org/abs/2010.00904).\n synced_gpus (`bool`, *optional*, defaults to `False`):\n Whether to continue running the while loop until max_length (needed to avoid deadlocking with\n `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).\n return_timestamps (`bool`, *optional*):\n Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.\n task (`str`, *optional*):\n Task to use for generation, either \"translate\" or \"transcribe\". The `model.config.forced_decoder_ids`\n will be updated accordingly.\n language (`str` or list of `str`, *optional*):\n Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. For\n batched generation, a list of language tokens can be passed. You can find all the possible language\n tokens in the `model.generation_config.lang_to_id` dictionary.\n is_multilingual (`bool`, *optional*):\n Whether or not the model is multilingual.\n prompt_ids (`torch.Tensor`, *optional*):\n Rank-1 tensor of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is\n provided as a prompt to each chunk. This can be used to provide or \"prompt-engineer\" a context for\n transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words\n correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.\n prompt_condition_type (`str`, *optional*):\n Only relevant for long-form transcription. Condition type of `prompt_ids`. 'first-segment' means only the first segment is conditioned on `prompt_ids`. 'all-segments' means each segment is conditioned on `prompt_ids`. Make sure to enable `condition_on_prev_tokens` for 'all-segments'.\n Defaults to 'first-segment'. For short-term transcription only 'first-segment' is possible.\n condition_on_prev_tokens (`bool`, *optional*):\n Only relevant for long-form transcription. Whether to condition each segment on the previous segment.\n As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve\n performance.\n temperature (`float` or list of `float`, *optional*):\n The temperature to be used for generation. Passing a single `float` value and `do_sample=True` activates\n generation using sampling. For long-form transcription, temperature fallback can be activated by passing\n a list of float values such as (0.0, 0.2, 0.4, 0.6, 0.8, 1.0). As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve\n performance.\n compression_ratio_threshold (`float`, *optional*):\n Only relevant for long-form transcription. If defined, the zlib compression rate of each segment will be computed. If the compression rate of\n a segment is higher than `compression_ratio_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is\n repeated using a higher temperature. The intuition behind this feature is that segments with very high compression rates\n suffer from a lot of repetition. The unwanted repetition can be reduced by injecting more randomness by increasing the temperature. If `compression_ratio_threshold` is defined\n make sure that `temperature` is a list of values. A common value for `compression_ratio_threshold` is 1.35.\n As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve\n performance.\n logprob_threshold (`float`, *optional*):\n Only relevant for long-form transcription. If defined, the average log-probability of each segment will be computed. If the log-probability of\n a given segment is lower than `logprob_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is\n repeated using a higher temperature. The intuition behind this feature is that segments of low log-probability\n can be improved by injecting more randomness by increasing the temperature. If `logprob_threshold` is defined\n make sure that `temperature` is a list of values. A common value for `logprob_threshold` is -1.0.\n As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve\n performance.\n no_speech_threshold (`float`, *optional*):\n Only relevant for long-form transcription. If defined, the \"no-speech\" token combined with the `logprob_threshold`\n is used to determine whether a segment contains only silence. In this case, the transcription for this segment\n is skipped.\n As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve\n performance.\n num_segment_frames (`int`, *optional*):\n The number of frames a single segment is made of. If not defined, `num_segment_frames` defaults to the model's stride\n times the maximum input length.\n attention_mask (`torch.Tensor`, *optional*):\n `attention_mask` needs to be passed when doing long-form transcription using a batch size > 1.\n time_precision (`int`, *optional*, defaults to 0.02):\n The duration of output token in seconds. *E.g.* 0.02 means that a generated token on average accounts\n for 20 ms.\n return_token_timestamps (`bool`, *optional*):\n Whether to return token-level timestamps with the text. This can be used with or without the\n `return_timestamps` option. To get word-level timestamps, use the tokenizer to group the tokens into\n words.\n return_segments (`bool`, *optional*, defaults to `False`):\n Whether to additionally return a list of all segments. Note that this option can only be enabled\n when doing long-form transcription.\n return_dict_in_generate (`bool`, *optional*, defaults to `False`):\n Whether or not to return a [`~utils.ModelOutput`] instead of just returning the generated tokens.\n Note that when doing long-form transcription, `return_dict_in_generate` can only be enabled when\n `return_segments` is set True. In this case the generation outputs of each segment is added to each\n segment.\n kwargs (`Dict[str, Any]`, *optional*):\n Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be\n forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder\n specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.\n\n Return:\n [`~utils.ModelOutput`] or `torch.LongTensor` or `Dict[str, Any]`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`\n or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor` or a dict of segments when `return_segments=True`.\n\n If the passed input is > 30 seconds / > 3000 mel input features and `return_segments=True` then a dictionary of generated sequence ids, called `sequences` and a list of each generated segment is returned.\n\n else if the passed input is <= 30 seconds / >= 3000 mel input features, the possible [`~utils.ModelOutput`] types are:\n\n - [`~generation.GenerateEncoderDecoderOutput`],\n - [`~generation.GenerateBeamEncoderDecoderOutput`]\n\n else only the generated output sequence ids are returned.\n\n Example:\n\n - *Longform transcription*: To transcribe or translate audios longer than 30 seconds, process the audio files without truncation and pass all mel features at once to generate.\n\n ```python\n >>> import torch\n >>> from transformers import AutoProcessor, WhisperForConditionalGeneration\n >>> from datasets import load_dataset, Audio\n\n >>> processor = AutoProcessor.from_pretrained(\"openai/whisper-tiny.en\")\n >>> model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-tiny.en\")\n >>> model.cuda() # doctest: +IGNORE_RESULT\n\n >>> # load audios > 30 seconds\n >>> ds = load_dataset(\"distil-whisper/meanwhile\", \"default\")[\"test\"]\n >>> # resample to 16kHz\n >>> ds = ds.cast_column(\"audio\", Audio(sampling_rate=16000))\n >>> # take first 8 audios and retrieve array\n >>> audio = ds[:8][\"audio\"]\n >>> audio = [x[\"array\"] for x in audio]\n\n >>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio\n >>> inputs = processor(audio, return_tensors=\"pt\", truncation=False, padding=\"longest\", return_attention_mask=True, sampling_rate=16_000)\n >>> inputs = inputs.to(\"cuda\", torch.float32)\n\n >>> # transcribe audio to ids\n >>> generated_ids = model.generate(**inputs)\n\n >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)\n >>> transcription[0]\n \" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile.\"\n ```\n\n - *Shortform transcription*: If passed mel input features are < 30 seconds, the whole audio will be transcribed with a single call to generate.\n\n ```python\n >>> import torch\n >>> from transformers import AutoProcessor, WhisperForConditionalGeneration\n >>> from datasets import load_dataset\n\n >>> processor = AutoProcessor.from_pretrained(\"openai/whisper-tiny.en\")\n >>> model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-tiny.en\")\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n >>> inputs = processor(ds[0][\"audio\"][\"array\"], return_tensors=\"pt\")\n >>> input_features = inputs.input_features\n\n >>> generated_ids = model.generate(inputs=input_features)\n\n >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\n >>> transcription\n ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'\n ```\n\n \"\"\"\n # 0. deprecate old inputs\n if \"inputs\" in kwargs:\n input_features = kwargs.pop(\"inputs\")\n warnings.warn(\n \"The input name `inputs` is deprecated. Please make sure to use `input_features` instead.\",\n FutureWarning,\n )\n\n # 1. prepare generation config\n generation_config, kwargs = self._prepare_generation_config(generation_config, **kwargs)\n\n # 2. set global generate variables\n input_stride = self.model.encoder.conv1.stride[0] * self.model.encoder.conv2.stride[0]\n num_segment_frames = input_stride * self.config.max_source_positions\n batch_size, total_input_frames = self._retrieve_total_input_frames(\n input_features=input_features, input_stride=input_stride, kwargs=kwargs\n )\n is_shortform = total_input_frames <= num_segment_frames\n\n # 3. Make sure generation config is correctly set\n # Make sure the generation config is correctly set depending on whether timestamps are to be returned or not\n return_dict_in_generate = self._set_return_outputs(\n return_dict_in_generate=return_dict_in_generate,\n return_token_timestamps=return_token_timestamps,\n logprob_threshold=logprob_threshold,\n generation_config=generation_config,\n )\n timestamp_begin = self._set_return_timestamps(\n return_timestamps=return_timestamps, is_shortform=is_shortform, generation_config=generation_config\n )\n self._set_language_and_task(\n language=language, task=task, is_multilingual=is_multilingual, generation_config=generation_config\n )\n self._set_num_frames(\n return_token_timestamps=return_token_timestamps, generation_config=generation_config, kwargs=kwargs\n )\n self._set_thresholds_and_condition(\n generation_config=generation_config,\n logprob_threshold=logprob_threshold,\n compression_ratio_threshold=compression_ratio_threshold,\n no_speech_threshold=no_speech_threshold,\n condition_on_prev_tokens=condition_on_prev_tokens,\n )\n self._set_prompt_condition_type(\n generation_config=generation_config,\n prompt_condition_type=prompt_condition_type,\n )\n\n # pass self.config for backward compatibility\n init_tokens = self._retrieve_init_tokens(\n input_features,\n batch_size=batch_size,\n generation_config=generation_config,\n config=self.config,\n num_segment_frames=num_segment_frames,\n kwargs=kwargs,\n )\n # passing `decoder_input_ids` is deprecated - the only exception is for assisted generation\n # where the input ids are handled explicitly by the generate method\n self._check_decoder_input_ids(kwargs=kwargs)\n\n # 3. Retrieve logits processors\n device = kwargs[\"encoder_outputs\"][0].device if \"encoder_outputs\" in kwargs else input_features.device\n begin_index = init_tokens.shape[1]\n logits_processor = self._retrieve_logit_processors(\n generation_config=generation_config,\n logits_processor=logits_processor,\n begin_index=begin_index, # begin index is index of first generated decoder token\n num_beams=kwargs.get(\"num_beams\", 1),\n device=device,\n )\n\n # 4 Set and retrieve global generation variables\n self._set_condition_on_prev_tokens(\n condition_on_prev_tokens=condition_on_prev_tokens, generation_config=generation_config\n )\n\n temperatures = [temperature] if not isinstance(temperature, (list, tuple)) else temperature\n temperature = temperatures[0]\n\n max_frames, seek = self._retrieve_max_frames_and_seek(\n batch_size=batch_size,\n attention_mask=attention_mask,\n total_input_frames=total_input_frames,\n is_shortform=is_shortform,\n )\n\n # 5 Prepare running variables, list for generation\n num_return_sequences = generation_config.num_return_sequences\n (\n batch_idx_map,\n cur_bsz,\n input_features,\n seek,\n max_frames,\n init_tokens,\n do_condition_on_prev_tokens,\n ) = self._expand_variables_for_generation(\n input_features=input_features,\n seek=seek,\n max_frames=max_frames,\n init_tokens=init_tokens,\n batch_size=batch_size,\n condition_on_prev_tokens=condition_on_prev_tokens,\n generation_config=generation_config,\n )\n\n current_segments = self._prepare_segments(\n prompt_ids=prompt_ids,\n batch_size=cur_bsz,\n generation_config=generation_config,\n )\n\n # 6 Transcribe audio until we reach the end of all input audios\n while (seek < max_frames).any():\n # 6.1 NOTE: When in longform transcription mode and batch size > 1 we need to dynamically reduce the batch size during the loop\n # in case one audio finished earlier than another one. Thus, we need to keep a table of \"previous-index-2-current-index\" in order\n # to know which original audio is being decoded\n # Set updated index map, duration of previously decoded chunks and number of max frames of current decoding chunk\n input_features, cur_bsz, batch_idx_map = self._maybe_reduce_batch(\n input_features=input_features,\n seek=seek,\n max_frames=max_frames,\n cur_bsz=cur_bsz,\n batch_idx_map=batch_idx_map,\n )\n time_offset = seek * time_precision / input_stride\n seek_num_frames = (max_frames - seek).clamp(max=num_segment_frames)\n\n # 6.2 cut out next 30s segment from input features\n segment_input = self._get_input_segment(\n input_features=input_features,\n seek=seek,\n seek_num_frames=seek_num_frames,\n num_segment_frames=num_segment_frames,\n cur_bsz=cur_bsz,\n batch_idx_map=batch_idx_map,\n )\n\n # 6.3 prepare decoder input ids\n suppress_tokens = _get_attr_from_logit_processors(\n logits_processor, SuppressTokensLogitsProcessor, \"suppress_tokens\"\n )\n\n decoder_input_ids, kwargs = self._prepare_decoder_input_ids(\n cur_bsz=cur_bsz,\n init_tokens=init_tokens,\n current_segments=current_segments,\n batch_idx_map=batch_idx_map,\n do_condition_on_prev_tokens=do_condition_on_prev_tokens,\n prompt_ids=prompt_ids,\n generation_config=generation_config,\n config=self.config,\n device=init_tokens.device,\n suppress_tokens=suppress_tokens,\n kwargs=kwargs,\n )\n\n # 6.4 set max new tokens or max length\n self._set_max_new_tokens_and_length(\n config=self.config,\n decoder_input_ids=decoder_input_ids,\n generation_config=generation_config,\n )\n\n # 6.5 Set current `begin_index` for all logit processors\n if logits_processor is not None:\n for proc in logits_processor:\n if hasattr(proc, \"set_begin_index\"):\n proc.set_begin_index(decoder_input_ids.shape[-1])\n\n # 6.6 Run generate with fallback\n (\n seek_sequences,\n seek_outputs,\n should_skip,\n do_condition_on_prev_tokens,\n model_output_type,\n ) = self.generate_with_fallback(\n segment_input=segment_input,\n decoder_input_ids=decoder_input_ids,\n cur_bsz=cur_bsz,\n batch_idx_map=batch_idx_map,\n seek=seek,\n num_segment_frames=num_segment_frames,\n max_frames=max_frames,\n temperatures=temperatures,\n generation_config=generation_config,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n synced_gpus=synced_gpus,\n return_token_timestamps=return_token_timestamps,\n do_condition_on_prev_tokens=do_condition_on_prev_tokens,\n is_shortform=is_shortform,\n batch_size=batch_size,\n attention_mask=attention_mask,\n kwargs=kwargs,\n )\n\n # 6.7 In every generated sequence, split by timestamp tokens and extract segments\n for i, seek_sequence in enumerate(seek_sequences):\n prev_i = batch_idx_map[i]\n\n if should_skip[i]:\n seek[prev_i] += seek_num_frames[prev_i]\n continue\n\n segments, segment_offset = self._retrieve_segment(\n seek_sequence=seek_sequence,\n seek_outputs=seek_outputs,\n time_offset=time_offset,\n timestamp_begin=timestamp_begin,\n seek_num_frames=seek_num_frames,\n time_precision=time_precision,\n input_stride=input_stride,\n prev_idx=prev_i,\n idx=i,\n return_token_timestamps=return_token_timestamps,\n )\n\n current_segments[prev_i] += segments\n\n if is_shortform:\n seek[prev_i] += max_frames[i]\n else:\n seek[prev_i] += segment_offset\n\n # 7. Once all segments are added to the list of all segments, called `current_segments`, we extract the predicted\n # output tokens from the list of dicts. If we use batch size > 1, we make sure to pad the output\n final_segments = (\n [x[1:] for x in current_segments]\n if (prompt_ids is not None and generation_config.prompt_condition_type == \"first-segment\")\n else current_segments\n )\n\n sequences = _pad_to_max_length(\n final_segments, generation_config.pad_token_id, device=self.device, padding_side=\"right\"\n )\n\n # 8. If we return all segments, the predicted output sequences are put under `\"sequences\"`.\n if return_segments:\n return {\"sequences\": sequences, \"segments\": final_segments}\n\n if is_shortform:\n # add eos token:\n if generation_config.max_new_tokens is None and generation_config.max_length is None:\n eos_tokens = torch.full((sequences.shape[0], 1), generation_config.eos_token_id)\n sequences = torch.cat([sequences, eos_tokens], dim=-1)\n\n if return_token_timestamps:\n outputs = {}\n outputs[\"sequences\"] = sequences\n outputs[\"token_timestamps\"] = torch.stack([d[\"token_timestamps\"] for d in seek_outputs], dim=0)\n else:\n outputs = sequences\n\n if return_dict_in_generate and generation_config.return_dict_in_generate:\n dict_outputs = self._stack_split_outputs(seek_outputs, model_output_type, sequences.device, kwargs)\n\n if num_return_sequences > 1:\n if hasattr(dict_outputs, \"encoder_attentions\") and dict_outputs.encoder_attentions is not None:\n dict_outputs.encoder_attentions = tuple(\n dict_outputs.encoder_attentions[i][::num_return_sequences]\n for i in range(len(dict_outputs.encoder_attentions))\n )\n if (\n hasattr(dict_outputs, \"encoder_hidden_states\")\n and dict_outputs.encoder_hidden_states is not None\n ):\n dict_outputs.encoder_hidden_states = tuple(\n dict_outputs.encoder_hidden_states[i][::num_return_sequences]\n for i in range(len(dict_outputs.encoder_hidden_states))\n )\n if return_token_timestamps:\n dict_outputs[\"token_timestamps\"] = outputs[\"token_timestamps\"]\n return dict_outputs\n\n return outputs\n\n return sequences", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30000,\n embedding_size=128,\n hidden_size=4096,\n num_hidden_layers=12,\n num_hidden_groups=1,\n num_attention_heads=64,\n intermediate_size=16384,\n inner_group_num=1,\n hidden_act=\"gelu_new\",\n hidden_dropout_prob=0,\n attention_probs_dropout_prob=0,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n classifier_dropout_prob=0.1,\n position_embedding_type=\"absolute\",\n pad_token_id=0,\n bos_token_id=2,\n eos_token_id=3,\n **kwargs,\n ):\n super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)\n\n self.vocab_size = vocab_size\n self.embedding_size = embedding_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_hidden_groups = num_hidden_groups\n self.num_attention_heads = num_attention_heads\n self.inner_group_num = inner_group_num\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.classifier_dropout_prob = classifier_dropout_prob\n self.position_embedding_type = position_embedding_type", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n merges_file,\n do_lower_case=True,\n errors=\"replace\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n add_prefix_space=False,\n max_cell_length=15,\n **kwargs,\n ):\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token\n cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n with open(vocab_file, encoding=\"utf-8\") as vocab_handle:\n self.encoder = json.load(vocab_handle)\n self.decoder = {v: k for k, v in self.encoder.items()}\n self.errors = errors # how to handle errors in decoding\n self.byte_encoder = bytes_to_unicode()\n self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}\n with open(merges_file, encoding=\"utf-8\") as merges_handle:\n bpe_merges = merges_handle.read().split(\"\\n\")[1:-1]\n bpe_merges = [tuple(merge.split()) for merge in bpe_merges]\n self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))\n self.cache = {}\n self.add_prefix_space = add_prefix_space\n self.do_lower_case = do_lower_case\n\n # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions\n self.pat = re.compile(r\"\"\"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\"\"\")\n\n # additional properties\n\n super().__init__(\n vocab_file=vocab_file,\n merges_file=merges_file,\n do_lower_case=do_lower_case,\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n max_cell_length=max_cell_length,\n **kwargs,\n )\n\n self.max_cell_length = max_cell_length\n self.table_linearize = IndexedRowTableLinearize()", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n patch_size=16,\n num_channels=3,\n num_frames=8,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-6,\n qkv_bias=True,\n attention_type=\"divided_space_time\",\n drop_path_rate=0,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.num_frames = num_frames\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.qkv_bias = qkv_bias\n\n self.attention_type = attention_type\n self.drop_path_rate = drop_path_rate", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n num_channels=3,\n image_size=224,\n depth_multiplier=1.0,\n depth_divisible_by=8,\n min_depth=8,\n expand_ratio=6.0,\n output_stride=32,\n first_layer_is_expansion=True,\n finegrained_output=True,\n hidden_act=\"relu6\",\n tf_padding=True,\n classifier_dropout_prob=0.8,\n initializer_range=0.02,\n layer_norm_eps=0.001,\n semantic_loss_ignore_index=255,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n if depth_multiplier <= 0:\n raise ValueError(\"depth_multiplier must be greater than zero.\")\n\n self.num_channels = num_channels\n self.image_size = image_size\n self.depth_multiplier = depth_multiplier\n self.depth_divisible_by = depth_divisible_by\n self.min_depth = min_depth\n self.expand_ratio = expand_ratio\n self.output_stride = output_stride\n self.first_layer_is_expansion = first_layer_is_expansion\n self.finegrained_output = finegrained_output\n self.hidden_act = hidden_act\n self.tf_padding = tf_padding\n self.classifier_dropout_prob = classifier_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.semantic_loss_ignore_index = semantic_loss_ignore_index", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_file,\n merges_file,\n tags_dict,\n tokenizer_file=None,\n errors=\"replace\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n sep_token=\"</s>\",\n cls_token=\"<s>\",\n unk_token=\"<unk>\",\n pad_token=\"<pad>\",\n mask_token=\"<mask>\",\n add_prefix_space=False,\n max_depth=50,\n max_width=1000,\n pad_width=1001,\n pad_token_label=-100,\n only_label_first_subword=True,\n trim_offsets=False,\n **kwargs,\n ):\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token\n cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n super().__init__(\n vocab_file=vocab_file,\n merges_file=merges_file,\n tags_dict=tags_dict,\n tokenizer_file=tokenizer_file,\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n trim_offsets=trim_offsets,\n max_depth=max_depth,\n max_width=max_width,\n pad_width=pad_width,\n pad_token_label=pad_token_label,\n only_label_first_subword=only_label_first_subword,\n **kwargs,\n )\n if trim_offsets:\n # Not implemented yet, because we need to chain two post processors which is not possible yet\n # We need to wait for https://github.com/huggingface/tokenizers/pull/1005\n # With `trim_offsets=False` we don't need to do add `processors.ByteLevel(trim_offsets=False)`\n # because it's not doing anything\n raise NotImplementedError(\n \"`trim_offsets=True` is not implemented for MarkupLMTokenizerFast. Please set it to False.\"\n )\n\n self.tags_dict = tags_dict\n\n pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())\n if pre_tok_state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop(\"type\"))\n pre_tok_state[\"add_prefix_space\"] = add_prefix_space\n self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)\n\n self.add_prefix_space = add_prefix_space\n\n tokenizer_component = \"post_processor\"\n tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)\n if tokenizer_component_instance:\n state = json.loads(tokenizer_component_instance.__getstate__())\n\n # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`\n if \"sep\" in state:\n state[\"sep\"] = tuple(state[\"sep\"])\n if \"cls\" in state:\n state[\"cls\"] = tuple(state[\"cls\"])\n\n changes_to_apply = False\n\n if state.get(\"add_prefix_space\", add_prefix_space) != add_prefix_space:\n state[\"add_prefix_space\"] = add_prefix_space\n changes_to_apply = True\n\n if changes_to_apply:\n component_class = getattr(processors, state.pop(\"type\"))\n new_value = component_class(**state)\n setattr(self.backend_tokenizer, tokenizer_component, new_value)\n\n # additional properties\n self.max_depth = max_depth\n self.max_width = max_width\n self.pad_width = pad_width\n self.unk_tag_id = len(self.tags_dict)\n self.pad_tag_id = self.unk_tag_id + 1\n self.pad_xpath_tags_seq = [self.pad_tag_id] * self.max_depth\n self.pad_xpath_subs_seq = [self.pad_width] * self.max_depth\n self.pad_token_label = pad_token_label\n self.only_label_first_subword = only_label_first_subword", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=1,\n bos_token_id=0,\n eos_token_id=2,\n embedding_size=768,\n head_ratio=2,\n conv_kernel_size=9,\n num_groups=1,\n classifier_dropout=None,\n **kwargs,\n ):\n super().__init__(\n pad_token_id=pad_token_id,\n bos_token_id=bos_token_id,\n eos_token_id=eos_token_id,\n **kwargs,\n )\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.embedding_size = embedding_size\n self.head_ratio = head_ratio\n self.conv_kernel_size = conv_kernel_size\n self.num_groups = num_groups\n self.classifier_dropout = classifier_dropout", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n num_key_value_heads=2,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n pad_token_id=0,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.num_key_value_heads = num_key_value_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.pad_token_id = pad_token_id\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def full_text_generation(\n model,\n tokenizer,\n context=None,\n num_samples=1,\n device=\"cuda\",\n bag_of_words=None,\n discrim=None,\n class_label=None,\n length=100,\n stepsize=0.02,\n temperature=1.0,\n top_k=10,\n sample=False,\n num_iterations=3,\n grad_length=10000,\n horizon_length=1,\n window_length=0,\n decay=False,\n gamma=1.5,\n gm_scale=0.9,\n kl_scale=0.01,\n repetition_penalty=1.0,\n **kwargs,\n):\n classifier, class_id = get_classifier(discrim, class_label, device)\n\n bow_indices = []\n if bag_of_words:\n bow_indices = get_bag_of_words_indices(bag_of_words.split(\";\"), tokenizer)\n\n if bag_of_words and classifier:\n print(\"Both PPLM-BoW and PPLM-Discrim are on. This is not optimized.\")\n loss_type = PPLM_BOW_DISCRIM\n\n elif bag_of_words:\n loss_type = PPLM_BOW\n print(\"Using PPLM-BoW\")\n\n elif classifier is not None:\n loss_type = PPLM_DISCRIM\n print(\"Using PPLM-Discrim\")\n\n else:\n raise Exception(\"Specify either a bag of words or a discriminator\")\n\n unpert_gen_tok_text, _, _ = generate_text_pplm(\n model=model,\n tokenizer=tokenizer,\n context=context,\n device=device,\n length=length,\n sample=sample,\n perturb=False,\n repetition_penalty=repetition_penalty,\n )\n if device == \"cuda\":\n torch.cuda.empty_cache()\n\n pert_gen_tok_texts = []\n discrim_losses = []\n losses_in_time = []\n\n for i in range(num_samples):\n pert_gen_tok_text, discrim_loss, loss_in_time = generate_text_pplm(\n model=model,\n tokenizer=tokenizer,\n context=context,\n device=device,\n perturb=True,\n bow_indices=bow_indices,\n classifier=classifier,\n class_label=class_id,\n loss_type=loss_type,\n length=length,\n stepsize=stepsize,\n temperature=temperature,\n top_k=top_k,\n sample=sample,\n num_iterations=num_iterations,\n grad_length=grad_length,\n horizon_length=horizon_length,\n window_length=window_length,\n decay=decay,\n gamma=gamma,\n gm_scale=gm_scale,\n kl_scale=kl_scale,\n repetition_penalty=repetition_penalty,\n )\n pert_gen_tok_texts.append(pert_gen_tok_text)\n if classifier is not None:\n discrim_losses.append(discrim_loss.data.cpu().numpy())\n losses_in_time.append(loss_in_time)\n\n if device == \"cuda\":\n torch.cuda.empty_cache()\n\n return unpert_gen_tok_text, pert_gen_tok_texts, discrim_losses, losses_in_time", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n image_size=224,\n patch_size=4,\n num_channels=3,\n embed_dim=96,\n use_conv_embed=False,\n hidden_sizes=[192, 384, 768, 768],\n depths=[2, 2, 6, 2],\n focal_levels=[2, 2, 2, 2],\n focal_windows=[3, 3, 3, 3],\n hidden_act=\"gelu\",\n mlp_ratio=4.0,\n hidden_dropout_prob=0.0,\n drop_path_rate=0.1,\n use_layerscale=False,\n layerscale_value=1e-4,\n use_post_layernorm=False,\n use_post_layernorm_in_modulation=False,\n normalize_modulator=False,\n initializer_range=0.02,\n layer_norm_eps=1e-5,\n encoder_stride=32,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.embed_dim = embed_dim\n self.use_conv_embed = use_conv_embed\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.focal_levels = focal_levels\n self.focal_windows = focal_windows\n self.hidden_act = hidden_act\n self.mlp_ratio = mlp_ratio\n self.hidden_dropout_prob = hidden_dropout_prob\n self.drop_path_rate = drop_path_rate\n self.use_layerscale = use_layerscale\n self.layerscale_value = layerscale_value\n self.use_post_layernorm = use_post_layernorm\n self.use_post_layernorm_in_modulation = use_post_layernorm_in_modulation\n self.normalize_modulator = normalize_modulator\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.encoder_stride = encoder_stride\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(self.depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@validate_call\n def api_ci_runs_v3_get_without_preload_content(\n self,\n argo_workflows_name: Optional[StrictStr] = None,\n argo_workflows_namespace: Optional[StrictStr] = None,\n argo_workflows_template: Optional[StrictStr] = None,\n created_at: Optional[datetime] = None,\n github_actions_attempt_number: Optional[StrictInt] = None,\n github_actions_owner: Optional[StrictStr] = None,\n github_actions_repo: Optional[StrictStr] = None,\n github_actions_run_id: Optional[StrictInt] = None,\n github_actions_workflow_path: Optional[StrictStr] = None,\n id: Optional[StrictInt] = None,\n notify_slack_channels_upon_failure: Annotated[Optional[List[StrictStr]], Field(description=\"Slack channels to notify if this CiRun fails. This field is always appended to when mutated.\")] = None,\n notify_slack_channels_upon_retry: Annotated[Optional[List[StrictStr]], Field(description=\"Slack channels to notify if this CiRun is retried. This field is always appended to when mutated. It will de-dupe with the other notify fields.\")] = None,\n notify_slack_channels_upon_success: Annotated[Optional[List[StrictStr]], Field(description=\"Slack channels to notify if this CiRun succeeds. This field is always appended to when mutated.\")] = None,\n notify_slack_custom_icon: Annotated[Optional[StrictStr], Field(description=\"Icon to use for success or failure Slack notifications. Can be given either as a URL to an image or as a Slack emoji (using colon shortcodes, like :smiley:). An empty string is ignored to facilitate calling from GitHub Actions (where it's easier to pass an empty string than not send the field at all).\")] = None,\n platform: Optional[StrictStr] = None,\n resource_status: Annotated[Optional[StrictStr], Field(description=\"Available only when querying a CiRun via a CiIdentifier, indicates the status of the run for that resource\")] = None,\n started_at: Optional[StrictStr] = None,\n status: Optional[StrictStr] = None,\n terminal_at: Optional[StrictStr] = None,\n termination_hooks_dispatched_at: Optional[datetime] = None,\n updated_at: Optional[datetime] = None,\n limit: Annotated[Optional[StrictInt], Field(description=\"Control how many CiRuns are returned (default 100)\")] = None,\n offset: Annotated[Optional[StrictInt], Field(description=\"Control the offset for the returned CiRuns (default 0)\")] = None,\n _request_timeout: Union[\n None,\n Annotated[StrictFloat, Field(gt=0)],\n Tuple[\n Annotated[StrictFloat, Field(gt=0)],\n Annotated[StrictFloat, Field(gt=0)]\n ]\n ] = None,\n _request_auth: Optional[Dict[StrictStr, Any]] = None,\n _content_type: Optional[StrictStr] = None,\n _headers: Optional[Dict[StrictStr, Any]] = None,\n _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,\n ) -> RESTResponseType:\n \"\"\"List CiRuns matching a filter\n\n List CiRuns matching a filter. The CiRuns would have to re-queried directly to load any related resources. Results are ordered by start time, starting at most recent.\n\n :param argo_workflows_name:\n :type argo_workflows_name: str\n :param argo_workflows_namespace:\n :type argo_workflows_namespace: str\n :param argo_workflows_template:\n :type argo_workflows_template: str\n :param created_at:\n :type created_at: datetime\n :param github_actions_attempt_number:\n :type github_actions_attempt_number: int\n :param github_actions_owner:\n :type github_actions_owner: str\n :param github_actions_repo:\n :type github_actions_repo: str\n :param github_actions_run_id:\n :type github_actions_run_id: int\n :param github_actions_workflow_path:\n :type github_actions_workflow_path: str\n :param id:\n :type id: int\n :param notify_slack_channels_upon_failure: Slack channels to notify if this CiRun fails. This field is always appended to when mutated.\n :type notify_slack_channels_upon_failure: List[str]\n :param notify_slack_channels_upon_retry: Slack channels to notify if this CiRun is retried. This field is always appended to when mutated. It will de-dupe with the other notify fields.\n :type notify_slack_channels_upon_retry: List[str]\n :param notify_slack_channels_upon_success: Slack channels to notify if this CiRun succeeds. This field is always appended to when mutated.\n :type notify_slack_channels_upon_success: List[str]\n :param notify_slack_custom_icon: Icon to use for success or failure Slack notifications. Can be given either as a URL to an image or as a Slack emoji (using colon shortcodes, like :smiley:). An empty string is ignored to facilitate calling from GitHub Actions (where it's easier to pass an empty string than not send the field at all).\n :type notify_slack_custom_icon: str\n :param platform:\n :type platform: str\n :param resource_status: Available only when querying a CiRun via a CiIdentifier, indicates the status of the run for that resource\n :type resource_status: str\n :param started_at:\n :type started_at: str\n :param status:\n :type status: str\n :param terminal_at:\n :type terminal_at: str\n :param termination_hooks_dispatched_at:\n :type termination_hooks_dispatched_at: datetime\n :param updated_at:\n :type updated_at: datetime\n :param limit: Control how many CiRuns are returned (default 100)\n :type limit: int\n :param offset: Control the offset for the returned CiRuns (default 0)\n :type offset: int\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :type _request_timeout: int, tuple(int, int), optional\n :param _request_auth: set to override the auth_settings for an a single\n request; this effectively ignores the\n authentication in the spec for a single request.\n :type _request_auth: dict, optional\n :param _content_type: force content-type for the request.\n :type _content_type: str, Optional\n :param _headers: set to override the headers for a single\n request; this effectively ignores the headers\n in the spec for a single request.\n :type _headers: dict, optional\n :param _host_index: set to override the host_index for a single\n request; this effectively ignores the host_index\n in the spec for a single request.\n :type _host_index: int, optional\n :return: Returns the result object.\n \"\"\" # noqa: E501\n\n _param = self._api_ci_runs_v3_get_serialize(\n argo_workflows_name=argo_workflows_name,\n argo_workflows_namespace=argo_workflows_namespace,\n argo_workflows_template=argo_workflows_template,\n created_at=created_at,\n github_actions_attempt_number=github_actions_attempt_number,\n github_actions_owner=github_actions_owner,\n github_actions_repo=github_actions_repo,\n github_actions_run_id=github_actions_run_id,\n github_actions_workflow_path=github_actions_workflow_path,\n id=id,\n notify_slack_channels_upon_failure=notify_slack_channels_upon_failure,\n notify_slack_channels_upon_retry=notify_slack_channels_upon_retry,\n notify_slack_channels_upon_success=notify_slack_channels_upon_success,\n notify_slack_custom_icon=notify_slack_custom_icon,\n platform=platform,\n resource_status=resource_status,\n started_at=started_at,\n status=status,\n terminal_at=terminal_at,\n termination_hooks_dispatched_at=termination_hooks_dispatched_at,\n updated_at=updated_at,\n limit=limit,\n offset=offset,\n _request_auth=_request_auth,\n _content_type=_content_type,\n _headers=_headers,\n _host_index=_host_index\n )\n\n _response_types_map: Dict[str, Optional[str]] = {\n '200': \"List[SherlockCiRunV3]\",\n '400': \"ErrorsErrorResponse\",\n '403': \"ErrorsErrorResponse\",\n '404': \"ErrorsErrorResponse\",\n '407': \"ErrorsErrorResponse\",\n '409': \"ErrorsErrorResponse\",\n '500': \"ErrorsErrorResponse\",\n }\n response_data = self.api_client.call_api(\n *_param,\n _request_timeout=_request_timeout\n )\n return response_data.response", "smellKey": "S107", "smellId": null, "repo": "broadinstitute_sherlock", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_thumbnail=True,\n do_align_axis=False,\n do_pad=True,\n do_normalize=True,\n image_mean=[0.5, 0.5, 0.5],\n image_std=[0.5, 0.5, 0.5],\n ):\n super().__init__()\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size if size is not None else {\"height\": 18, \"width\": 20}\n self.do_thumbnail = do_thumbnail\n self.do_align_axis = do_align_axis\n self.do_pad = do_pad\n self.do_normalize = do_normalize\n self.image_mean = image_mean\n self.image_std = image_std", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n vocab_size=32128,\n d_model=768,\n d_kv=64,\n d_ff=2048,\n expert_capacity=64,\n num_layers=12,\n num_sparse_encoder_layers=3,\n num_decoder_layers=12,\n num_sparse_decoder_layers=3,\n num_heads=12,\n num_experts=8,\n router_bias=False,\n router_jitter_noise=0.01,\n router_dtype=\"float32\",\n router_ignore_padding_tokens=False,\n relative_attention_num_buckets=32,\n relative_attention_max_distance=128,\n dropout_rate=0.1,\n layer_norm_epsilon=1e-6,\n router_z_loss_coef=0.001,\n router_aux_loss_coef=0.001,\n initializer_factor=1.0,\n dense_act_fn=\"relu\",\n is_encoder_decoder=True,\n add_router_probs=False,\n use_cache=True,\n pad_token_id=0,\n eos_token_id=1,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.d_kv = d_kv\n self.d_ff = d_ff\n\n self.num_sparse_encoder_layers = num_sparse_encoder_layers\n\n self.num_layers = num_layers\n self.num_decoder_layers = (\n num_decoder_layers if num_decoder_layers is not None else self.num_layers\n ) # default = symmetry\n self.num_sparse_decoder_layers = num_sparse_decoder_layers\n\n # This tells us, each how many encoder layer we'll have to set a sparse layer.\n if self.num_sparse_encoder_layers > 0:\n self.encoder_sparse_step = self.num_layers // self.num_sparse_encoder_layers\n else:\n self.encoder_sparse_step = self.num_layers # HACK: this will create 0 sparse layers\n\n # This tells us, each how many encoder layer we'll have to set a sparse layer.\n if self.num_sparse_decoder_layers > 0:\n self.decoder_sparse_step = self.num_decoder_layers // self.num_sparse_decoder_layers\n else:\n self.decoder_sparse_step = self.num_decoder_layers # HACK: this will create 0 sparse layers\n\n self.num_heads = num_heads\n self.num_experts = num_experts\n self.expert_capacity = expert_capacity\n self.router_bias = router_bias\n self.router_jitter_noise = router_jitter_noise\n if router_dtype not in [\"float32\", \"float16\", \"bfloat16\"]:\n raise ValueError(f\"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}\")\n self.router_dtype = router_dtype\n\n self.router_ignore_padding_tokens = router_ignore_padding_tokens\n self.relative_attention_num_buckets = relative_attention_num_buckets\n self.relative_attention_max_distance = relative_attention_max_distance\n\n self.dropout_rate = dropout_rate\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_factor = initializer_factor\n self.use_cache = use_cache\n self.add_router_probs = add_router_probs\n\n self.router_z_loss_coef = router_z_loss_coef\n self.router_aux_loss_coef = router_aux_loss_coef\n self.dense_act_fn = dense_act_fn\n\n super().__init__(\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n is_encoder_decoder=is_encoder_decoder,\n **kwargs,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=10,\n num_channels=3,\n patch_size=2,\n num_frames=2,\n is_training=True,\n use_labels=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n num_labels=10,\n initializer_range=0.02,\n attention_type=\"divided_space_time\",\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.patch_size = patch_size\n self.num_frames = num_frames\n self.is_training = is_training\n self.use_labels = use_labels\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.attention_type = attention_type\n self.initializer_range = initializer_range\n self.scope = scope\n self.num_labels = num_labels\n\n # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token\n self.num_patches_per_frame = (image_size // patch_size) ** 2\n self.seq_length = (num_frames) * self.num_patches_per_frame + 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@add_start_docstrings_to_model_forward(IMAGEGPT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n attention_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n **kwargs: Any,\n ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set\n `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`\n are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoImageProcessor, ImageGPTForCausalImageModeling\n >>> import torch\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"openai/imagegpt-small\")\n >>> model = ImageGPTForCausalImageModeling.from_pretrained(\"openai/imagegpt-small\")\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n >>> model.to(device) # doctest: +IGNORE_RESULT\n\n >>> # unconditional generation of 8 images\n >>> batch_size = 4\n >>> context = torch.full((batch_size, 1), model.config.vocab_size - 1) # initialize with SOS token\n >>> context = context.to(device)\n >>> output = model.generate(\n ... input_ids=context, max_length=model.config.n_positions + 1, temperature=1.0, do_sample=True, top_k=40\n ... )\n\n >>> clusters = image_processor.clusters\n >>> height = image_processor.size[\"height\"]\n >>> width = image_processor.size[\"width\"]\n\n >>> samples = output[:, 1:].cpu().detach().numpy()\n >>> samples_img = [\n ... np.reshape(np.rint(127.5 * (clusters[s] + 1.0)), [height, width, 3]).astype(np.uint8) for s in samples\n ... ] # convert color cluster tokens back to pixels\n >>> f, axes = plt.subplots(1, batch_size, dpi=300)\n\n >>> for img, ax in zip(samples_img, axes): # doctest: +IGNORE_RESULT\n ... ax.axis(\"off\")\n ... ax.imshow(img)\n ```\"\"\"\n\n if \"pixel_values\" in kwargs:\n warnings.warn(\n \"The `pixel_values` argument is deprecated and will be removed in v4.47, use `input_ids` instead.\",\n FutureWarning,\n )\n\n if input_ids is not None:\n raise ValueError(\n \"You cannot pass both `pixel_values` and `input_ids`. Please make sure to only pass `input_ids`.\"\n )\n\n input_ids = kwargs.pop(\"pixel_values\")\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n transformer_outputs = self.transformer(\n input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutputWithCrossAttentions(\n loss=loss,\n logits=lm_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n cross_attentions=transformer_outputs.cross_attentions,\n )", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=14,\n seq_length=7,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=False,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.scope = None\n self.bos_token_id = vocab_size - 1\n self.eos_token_id = vocab_size - 1\n self.pad_token_id = vocab_size - 1", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n ident: str,\n http_port: int,\n admin_port: int,\n internal_host: str = None,\n external_host: str = None,\n genesis_data: str = None,\n genesis_txn_list: str = None,\n seed: str = None,\n label: str = None,\n color: str = None,\n prefix: str = None,\n tails_server_base_url: str = None,\n timing: bool = False,\n timing_log: str = None,\n postgres: bool = None,\n revocation: bool = False,\n multitenant: bool = False,\n mediation: bool = False,\n aip: int = 20,\n arg_file: str = None,\n endorser_role: str = None,\n extra_args=None,\n log_file: str = None,\n log_config: str = None,\n log_level: str = None,\n reuse_connections: bool = False,\n multi_use_invitations: bool = False,\n public_did_connections: bool = False,\n **params,\n ):\n self.ident = ident\n self.http_port = http_port\n self.admin_port = admin_port\n self.internal_host = internal_host or DEFAULT_INTERNAL_HOST\n self.external_host = external_host or DEFAULT_EXTERNAL_HOST\n self.genesis_data = genesis_data\n self.genesis_txn_list = genesis_txn_list\n self.label = label or ident\n self.color = color\n self.prefix = prefix\n self.timing = timing\n self.timing_log = timing_log\n self.postgres = DEFAULT_POSTGRES if postgres is None else postgres\n self.tails_server_base_url = tails_server_base_url\n self.revocation = revocation\n self.endorser_role = endorser_role\n self.endorser_did = None # set this later\n self.endorser_invite = None # set this later\n self.extra_args = extra_args\n self.trace_enabled = TRACE_ENABLED\n self.trace_target = TRACE_TARGET\n self.trace_tag = TRACE_TAG\n self.multitenant = multitenant\n self.external_webhook_target = WEBHOOK_TARGET\n self.mediation = mediation\n self.mediator_connection_id = None\n self.mediator_request_id = None\n self.aip = aip\n self.arg_file = arg_file\n self.log_file = log_file\n self.log_config = log_config\n self.log_level = log_level\n self.reuse_connections = reuse_connections\n self.multi_use_invitations = multi_use_invitations\n self.public_did_connections = public_did_connections\n\n self.admin_url = f\"http://{self.internal_host}:{admin_port}\"\n if AGENT_ENDPOINT:\n self.endpoint = AGENT_ENDPOINT\n elif RUN_MODE == \"pwd\":\n self.endpoint = f\"http://{self.external_host}\".replace(\n \"{PORT}\", str(http_port)\n )\n else:\n self.endpoint = f\"http://{self.external_host}:{http_port}\"\n\n self.webhook_port = None\n self.webhook_url = None\n self.webhook_site = None\n self.params = params\n self.proc = None\n self.client_session: ClientSession = ClientSession()\n self.thread_pool_executor = ThreadPoolExecutor(20)\n\n if self.endorser_role and self.endorser_role == \"author\":\n seed = None\n elif self.endorser_role and not seed:\n seed = \"random\"\n rand_name = token_hex(4)\n self.seed = token_hex(16) if seed == \"random\" else seed\n self.storage_type = params.get(\"storage_type\")\n self.wallet_type = params.get(\"wallet_type\") or \"askar\"\n self.wallet_name = (\n params.get(\"wallet_name\") or self.ident.lower().replace(\" \", \"\") + rand_name\n )\n self.wallet_key = params.get(\"wallet_key\") or self.ident + rand_name\n self.did = None\n self.wallet_stats = []\n\n # for multitenancy, storage_type and wallet_type are the same for all wallets\n if self.multitenant:\n self.agency_ident = self.ident\n self.agency_wallet_name = self.wallet_name\n self.agency_wallet_seed = self.seed\n self.agency_wallet_did = self.did\n self.agency_wallet_key = self.wallet_key\n\n self.multi_write_ledger_url = None\n if self.genesis_txn_list:\n updated_config_list = []\n with open(self.genesis_txn_list, \"r\") as stream:\n ledger_config_list = yaml.safe_load(stream)\n for config in ledger_config_list:\n if \"genesis_url\" in config and \"/$LEDGER_HOST:\" in config.get(\n \"genesis_url\"\n ):\n config[\"genesis_url\"] = config.get(\"genesis_url\").replace(\n \"$LEDGER_HOST\", str(self.external_host)\n )\n updated_config_list.append(config)\n if \"is_write\" in config and config[\"is_write\"]:\n self.multi_write_ledger_url = config[\"genesis_url\"].replace(\n \"/genesis\", \"\"\n )\n with open(self.genesis_txn_list, \"w\") as file:\n documents = yaml.dump(updated_config_list, file)", "smellKey": "S107", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@njit(cache=False, fastmath=True)\ndef compute_iLQR_coef(\n traj,\n inputs,\n A,\n B,\n Q_total,\n R_total,\n acc_lim_weights,\n acc_lim_center,\n steer_lim_weights,\n steer_lim_center,\n acc_rate_lim_weights,\n acc_rate_lim_center,\n steer_rate_lim_weights,\n steer_rate_lim_center,\n N,\n X_des,\n U_des,\n Sigma_x=None,\n dSigma_x=None,\n Sigma_y=None,\n dSigma_y=None,\n Sigma_v=None,\n dSigma_v=None,\n Sigma_theta=None,\n dSigma_theta=None,\n Sigma_acc=None,\n dSigma_acc=None,\n Sigma_steer=None,\n dSigma_steer=None,\n acc_input_index=acc_index,\n steer_input_index=steer_index,\n state_dim=actual_state_dim,\n):\n \"\"\"Perform the main part of iLQR.\n\n Performs a Riccati recursion and returns the coefficients needed for the final output.\n \"\"\"\n nx = A.shape[2]\n nu = B.shape[2]\n P = np.zeros((N + 1, nx, nx))\n w = np.zeros((N + 1, nx))\n H_inv_G = np.zeros((N, nu, nx))\n H_inv_g = np.zeros((N, nu))\n P[N][:6, :6] = Q_total[-1][:6, :6]\n P[N][acc_input_index, acc_input_index] = Q_total[-1][6, 6]\n P[N][steer_input_index, steer_input_index] = Q_total[-1][7, 7]\n\n P[N][acc_input_index, acc_input_index] += acc_lim_weights[N]\n P[N][steer_input_index, steer_input_index] += steer_lim_weights[N]\n\n Q_N_x = Q_total[-1] @ (traj[N] - X_des[N])\n\n w[N][:6] = Q_N_x[:6]\n w[N][acc_input_index] = Q_N_x[6]\n w[N][steer_input_index] = Q_N_x[7]\n\n w[N, acc_input_index] += acc_lim_weights[N] * (traj[N, acc_index] - acc_lim_center[N])\n w[N, steer_input_index] += steer_lim_weights[N] * (traj[N, acc_index + 1] - steer_lim_center[N])\n\n for i in range(N):\n j = N - i - 1\n Qj = Q_total[j]\n Rj = R_total[j]\n Aj = A[j]\n Pj1Aj = sparse_right_action_for_state_diff(\n P[j + 1], Aj[:state_dim], actual_state_dim=state_dim\n )\n G = sparse_left_action_for_input_diff(Pj1Aj, actual_state_dim=state_dim)\n\n H = (\n sparse_left_action_for_input_diff(\n sparse_right_action_for_input_diff(P[j + 1], actual_state_dim=state_dim),\n actual_state_dim=state_dim,\n )\n + Rj\n )\n H[0, 0] += acc_rate_lim_weights[j]\n H[1, 1] += steer_rate_lim_weights[j]\n\n g_ = vector_sparse_left_action_for_input_diff(w[j + 1], actual_state_dim=state_dim) + Rj @ (\n inputs[j] - U_des[j]\n )\n g_[0] += acc_rate_lim_weights[j] * (inputs[j, 0] - acc_rate_lim_center[j])\n g_[1] += steer_rate_lim_weights[j] * (inputs[j, 1] - steer_rate_lim_center[j])\n\n one_over_det = 1 / (H[0, 0] * H[1, 1] - H[1, 0] * H[1, 0])\n\n H_inv = one_over_det * np.array([[H[1, 1], -H[1, 0]], [-H[1, 0], H[0, 0]]])\n\n H_inv_G[j] = H_inv @ G\n H_inv_g[j] = H_inv @ g_\n\n P[j] = (\n sparse_left_action_for_state_diff(Aj[:state_dim], Pj1Aj, actual_state_dim=state_dim)\n - G.T @ H_inv_G[j]\n )\n P[j][:6, :6] += Qj[:6, :6]\n P[j][acc_input_index, acc_input_index] += Qj[6, 6]\n P[j][steer_input_index, steer_input_index] += Qj[7, 7]\n\n P[j][acc_input_index, acc_input_index] += acc_lim_weights[j]\n P[j][steer_input_index, steer_input_index] += steer_lim_weights[j]\n\n w[j] = (\n vector_sparse_left_action_for_state_diff(\n Aj[:state_dim], w[j + 1], actual_state_dim=state_dim\n )\n - H_inv_G[j].T @ g_\n )\n\n Q_j_x = Qj @ (traj[j] - X_des[j])\n w[j, :6] += Q_j_x[:6]\n w[j, acc_input_index] += Q_j_x[6]\n w[j, steer_input_index] += Q_j_x[7]\n\n w[j, acc_input_index] += acc_lim_weights[j] * (traj[j, acc_index] - acc_lim_center[j])\n w[j, steer_input_index] += steer_lim_weights[j] * (\n traj[j, acc_index + 1] - steer_lim_center[j]\n )\n P_noise = np.zeros((nx, nx))\n w_noise = np.zeros(nx)\n if Sigma_x is not None:\n sigma_x = Sigma_x[j]\n d_sigma_x = dSigma_x[j]\n vec_part = P[j][0, 0] * d_sigma_x\n P_noise += d_sigma_x.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_x * vec_part\n if Sigma_y is not None:\n sigma_y = Sigma_y[j]\n d_sigma_y = dSigma_y[j]\n vec_part = P[j][1, 1] * d_sigma_y\n P_noise += d_sigma_y.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_y * vec_part\n if Sigma_v is not None:\n sigma_v = Sigma_v[j]\n d_sigma_v = dSigma_v[j]\n vec_part = P[j][2, 2] * d_sigma_v\n P_noise += d_sigma_v.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_v * vec_part\n if Sigma_theta is not None:\n sigma_theta = Sigma_theta[j]\n d_sigma_theta = dSigma_theta[j]\n vec_part = P[j][3, 3] * d_sigma_theta\n P_noise += d_sigma_theta.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_theta * vec_part\n if Sigma_acc is not None:\n sigma_acc = Sigma_acc[j]\n d_sigma_acc = dSigma_acc[j]\n vec_part = P[j][4, 4] * d_sigma_acc\n P_noise += d_sigma_acc.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_acc * vec_part\n if Sigma_steer is not None:\n sigma_steer = Sigma_steer[j]\n d_sigma_steer = dSigma_steer[j]\n vec_part = P[j][5, 5] * d_sigma_steer\n P_noise += d_sigma_steer.reshape(-1, 1) @ vec_part.reshape(1, -1)\n w_noise += sigma_steer * vec_part\n\n P[j] += P_noise\n w[j] += w_noise\n return P, w, H_inv_G, H_inv_g", "smellKey": "S107", "smellId": null, "repo": "tier4_autoware.universe", "language": "python"} {"function": "def top_events_timeseries(\n timeseries_columns: list[str],\n selected_columns: list[str],\n user_query: str,\n snuba_params: SnubaParams,\n orderby: list[str],\n rollup: int,\n limit: int,\n organization: Organization,\n equations: list[str] | None = None,\n referrer: str | None = None,\n top_events: EventsResponse | None = None,\n allow_empty: bool = True,\n zerofill_results: bool = True,\n include_other: bool = False,\n functions_acl: list[str] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult | dict[str, Any]:\n metrics_compatible = False\n equations, _ = categorize_columns(selected_columns)\n if not equations:\n metrics_compatible = True\n\n if metrics_compatible:\n try:\n return metrics_top_events_timeseries(\n timeseries_columns,\n selected_columns,\n user_query,\n snuba_params,\n orderby,\n rollup,\n limit,\n organization,\n equations,\n referrer,\n top_events,\n allow_empty,\n zerofill_results,\n include_other,\n functions_acl,\n on_demand_metrics_enabled=on_demand_metrics_enabled,\n on_demand_metrics_type=on_demand_metrics_type,\n query_source=query_source,\n )\n # raise Invalid Queries since the same thing will happen with discover\n except InvalidSearchQuery:\n raise\n # any remaining errors mean we should try again with discover\n except IncompatibleMetricsQuery as error:\n sentry_sdk.set_tag(\"performance.mep_incompatible\", str(error))\n metrics_compatible = False\n\n # This isn't a query we can enhance with metrics\n if not metrics_compatible:\n sentry_sdk.set_tag(\"performance.dataset\", \"discover\")\n return discover.top_events_timeseries(\n timeseries_columns,\n selected_columns,\n user_query,\n snuba_params,\n orderby,\n rollup,\n limit,\n organization,\n equations,\n referrer,\n top_events,\n allow_empty,\n zerofill_results,\n include_other,\n functions_acl,\n query_source=query_source,\n )\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, [\"time\"]\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.0,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n image_size=224,\n patch_size=16,\n num_channels=3,\n use_mask_token=False,\n use_absolute_position_embeddings=False,\n use_relative_position_bias=False,\n use_shared_relative_position_bias=False,\n layer_scale_init_value=0.1,\n drop_path_rate=0.1,\n use_mean_pooling=True,\n out_indices=[3, 5, 7, 11],\n pool_scales=[1, 2, 3, 6],\n use_auxiliary_head=True,\n auxiliary_loss_weight=0.4,\n auxiliary_channels=256,\n auxiliary_num_convs=1,\n auxiliary_concat_input=False,\n semantic_loss_ignore_index=255,\n **kwargs,\n ):\n super().__init__(**kwargs)\n\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.use_mask_token = use_mask_token\n self.use_absolute_position_embeddings = use_absolute_position_embeddings\n self.use_relative_position_bias = use_relative_position_bias\n self.use_shared_relative_position_bias = use_shared_relative_position_bias\n self.layer_scale_init_value = layer_scale_init_value\n self.drop_path_rate = drop_path_rate\n self.use_mean_pooling = use_mean_pooling\n # decode head attributes (semantic segmentation)\n self.out_indices = out_indices\n self.pool_scales = pool_scales\n # auxiliary head attributes (semantic segmentation)\n self.use_auxiliary_head = use_auxiliary_head\n self.auxiliary_loss_weight = auxiliary_loss_weight\n self.auxiliary_channels = auxiliary_channels\n self.auxiliary_num_convs = auxiliary_num_convs\n self.auxiliary_concat_input = auxiliary_concat_input\n self.semantic_loss_ignore_index = semantic_loss_ignore_index", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n image_size=32,\n num_channels=3,\n kernel_sizes=[3, 3, 5],\n in_channels=[32, 16, 24],\n out_channels=[16, 24, 20],\n strides=[1, 1, 2],\n num_block_repeats=[1, 1, 2],\n expand_ratios=[1, 6, 6],\n is_training=True,\n use_labels=True,\n intermediate_size=37,\n hidden_act=\"gelu\",\n num_labels=10,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.num_channels = num_channels\n self.kernel_sizes = kernel_sizes\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.strides = strides\n self.num_block_repeats = num_block_repeats\n self.expand_ratios = expand_ratios\n self.is_training = is_training\n self.hidden_act = hidden_act\n self.num_labels = num_labels\n self.use_labels = use_labels", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self,\n featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n zca_whitening=False,\n zca_epsilon=1e-6,\n rotation_range=0.,\n width_shift_range=0.,\n height_shift_range=0.,\n shear_range=0.,\n zoom_range=0.,\n channel_shift_range=0.,\n fill_mode='nearest',\n cval=0.,\n horizontal_flip=False,\n vertical_flip=False,\n rescale=None,\n preprocessing_function=None,\n data_format=None,\n brighten_range=0):\n super(DriveDataGenerator, self).__init__(featurewise_center,\n samplewise_center,\n featurewise_std_normalization,\n samplewise_std_normalization,\n zca_whitening,\n zca_epsilon,\n rotation_range,\n width_shift_range,\n height_shift_range,\n shear_range,\n zoom_range,\n channel_shift_range,\n fill_mode,\n cval,\n horizontal_flip,\n vertical_flip,\n rescale,\n preprocessing_function,\n data_format)\n self.brighten_range = brighten_range", "smellKey": "S107", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "@click.command()\n@click.option(\n \"--reload/--no-reload\",\n default=True,\n help=\"Autoreloading of python files.\",\n)\n@click.option(\n \"--watchers/--no-watchers\",\n default=True,\n help=\"Watch static files and recompile on changes.\",\n)\n@click.option(\n \"--workers/--no-workers\",\n default=False,\n help=\"Run celery workers (excluding celerybeat).\",\n)\n@click.option(\n \"--celery-beat/--no-celery-beat\",\n default=False,\n help=\"Run celerybeat workers.\",\n)\n@click.option(\n \"--ingest/--no-ingest\",\n default=False,\n help=\"Run ingest services (including Relay).\",\n)\n@click.option(\n \"--occurrence-ingest/--no-occurrence-ingest\",\n default=False,\n help=\"Run ingest services for occurrences.\",\n)\n@click.option(\n \"--prefix/--no-prefix\",\n default=True,\n help=\"Show the service name prefix and timestamp\",\n)\n@click.option(\n \"--dev-consumer/--no-dev-consumer\",\n default=False,\n help=\"Fold multiple kafka consumers into one process using 'sentry run dev-consumer'.\",\n)\n@click.option(\n \"--pretty/--no-pretty\",\n default=False,\n help=\"Stylize various outputs from the devserver\",\n)\n@click.option(\n \"--environment\",\n default=\"development\",\n help=\"The environment name.\",\n)\n@click.option(\n \"--debug-server/--no-debug-server\",\n default=False,\n required=False,\n help=\"Start web server in same process\",\n)\n@click.option(\n \"--experimental-spa/--no-experimental-spa\",\n default=False,\n help=\"This enables running sentry with pure separation of the frontend and backend\",\n)\n@click.option(\n \"--client-hostname\",\n default=\"localhost\",\n help=\"The hostname that clients will use. Useful for ngrok workflows eg `--client-hostname=alice.ngrok.io`\",\n)\n@click.option(\n \"--ngrok\",\n default=None,\n required=False,\n help=(\n \"The hostname that you have ngrok forwarding to your devserver. \"\n \"This option will modify application settings to be compatible with ngrok forwarding. \"\n \"Expects a host name without protocol e.g `--ngrok=yourname.ngrok.app`. \"\n \"You will also need to run ngrok.\"\n ),\n)\n@click.option(\n \"--silo\",\n default=None,\n type=click.Choice([\"control\", \"region\"]),\n help=\"The silo mode to run this devserver instance in. Choices are control, region, none\",\n)\n@click.argument(\n \"bind\",\n default=None,\n metavar=\"ADDRESS\",\n envvar=\"SENTRY_DEVSERVER_BIND\",\n required=False,\n)\n@log_options() # needs this decorator to be typed\n@configuration # needs this decorator to be typed\ndef devserver(\n reload: bool,\n watchers: bool,\n workers: bool,\n celery_beat: bool,\n ingest: bool,\n occurrence_ingest: bool,\n experimental_spa: bool,\n prefix: bool,\n pretty: bool,\n environment: str,\n debug_server: bool,\n dev_consumer: bool,\n bind: str | None,\n client_hostname: str,\n ngrok: str | None,\n silo: str | None,\n) -> NoReturn:\n \"Starts a lightweight web server for development.\"\n if bind is None:\n bind = \"127.0.0.1:8000\"\n\n if \":\" in bind:\n host, port_s = bind.split(\":\", 1)\n port = int(port_s)\n else:\n raise SystemExit(f\"expected <host>:<port>, got {bind}\")\n\n # In a siloed environment we can't use localhost because cookies\n # cannot be shared across subdomains of localhost\n if silo and client_hostname == \"localhost\":\n click.echo(\n \"WARNING: You had a client_hostname of `localhost` but are using silo modes. \"\n \"Switching to dev.getsentry.net as the client hostname\"\n )\n client_hostname = \"dev.getsentry.net\"\n # We run webpack on the control server, not the regions.\n if silo == \"region\" and watchers:\n click.echo(\"WARNING: You have silo=region and webpack enabled. Disabling webpack.\")\n watchers = False\n\n import os\n\n os.environ[\"SENTRY_ENVIRONMENT\"] = environment\n # NODE_ENV *must* use production for any prod-like environment as third party libraries look\n # for this magic constant\n os.environ[\"NODE_ENV\"] = \"production\" if environment.startswith(\"prod\") else environment\n\n # Configure URL prefixes for customer-domains.\n client_host = f\"{client_hostname}:{port}\"\n os.environ[\"SENTRY_SYSTEM_URL_PREFIX\"] = f\"http://{client_host}\"\n os.environ[\"SENTRY_SYSTEM_BASE_HOSTNAME\"] = client_host\n os.environ[\"SENTRY_ORGANIZATION_BASE_HOSTNAME\"] = f\"{{slug}}.{client_host}\"\n os.environ[\"SENTRY_ORGANIZATION_URL_TEMPLATE\"] = \"http://{hostname}\"\n if ngrok:\n os.environ[\"SENTRY_DEVSERVER_NGROK\"] = ngrok\n\n from django.conf import settings\n\n from sentry.services.http import SentryHTTPServer\n\n uwsgi_overrides: dict[str, int | bool | str | None] = {\n \"protocol\": \"http\",\n \"uwsgi-socket\": None,\n \"http-keepalive\": True,\n # Make sure we reload really quickly for local dev in case it\n # doesn't want to shut down nicely on it's own, NO MERCY\n \"worker-reload-mercy\": 2,\n # We need stdin to support pdb in devserver\n \"honour-stdin\": True,\n # accept ridiculously large files\n \"limit-post\": 1 << 30,\n # do something with chunked\n \"http-chunked-input\": True,\n \"thunder-lock\": False,\n \"timeout\": 600,\n \"harakiri\": 600,\n \"workers\": 1 if debug_server else 2,\n }\n\n if reload:\n uwsgi_overrides[\"py-autoreload\"] = 1\n\n daemons: MutableSequence[tuple[str, Sequence[str]]] = []\n kafka_consumers: set[str] = set()\n\n if experimental_spa:\n os.environ[\"SENTRY_UI_DEV_ONLY\"] = \"1\"\n if not watchers:\n click.secho(\n \"Using experimental SPA mode without watchers enabled has no effect\",\n err=True,\n fg=\"yellow\",\n )\n\n # Configure ports based on options and environment vars\n # If present, webpack is given the 'bind' address as it proxies\n # requests to the server instances.\n # When we're running multiple servers control + region servers are offset\n # from webpack and each other.\n ports = {\n \"webpack\": port,\n \"server\": port + 1,\n \"region.server\": port + 10,\n }\n if not watchers:\n ports[\"server\"] = ports[\"webpack\"]\n ports.pop(\"webpack\")\n\n # Set ports to environment variables so that child processes can read them\n os.environ[\"SENTRY_BACKEND_PORT\"] = str(ports.get(\"server\"))\n if silo == \"region\":\n os.environ[\"SENTRY_BACKEND_PORT\"] = str(ports.get(\"region.server\"))\n\n server_port = os.environ[\"SENTRY_BACKEND_PORT\"]\n\n # We proxy all requests through webpacks devserver on the configured port.\n # The backend is served on port+1 and is proxied via the webpack\n # configuration.\n if watchers:\n daemons += settings.SENTRY_WATCHERS\n os.environ[\"FORCE_WEBPACK_DEV_SERVER\"] = \"1\"\n os.environ[\"SENTRY_WEBPACK_PROXY_HOST\"] = str(host)\n os.environ[\"SENTRY_WEBPACK_PROXY_PORT\"] = str(ports[\"webpack\"])\n\n # webpack and/or typescript is causing memory issues\n os.environ[\"NODE_OPTIONS\"] = (\n os.environ.get(\"NODE_OPTIONS\", \"\") + \" --max-old-space-size=4096\"\n ).lstrip()\n\n os.environ[\"SENTRY_USE_RELAY\"] = \"1\" if settings.SENTRY_USE_RELAY else \"\"\n\n if ingest and not workers:\n click.echo(\"--ingest was provided, implicitly enabling --workers\")\n workers = True\n\n if workers and not celery_beat:\n click.secho(\n \"If you want to run periodic tasks from celery (celerybeat), you need to also pass --celery-beat.\",\n fg=\"yellow\",\n )\n\n if celery_beat and silo != \"control\":\n daemons.append(_get_daemon(\"celery-beat\"))\n\n if workers and silo != \"control\":\n kafka_consumers.update(settings.DEVSERVER_START_KAFKA_CONSUMERS)\n\n if settings.CELERY_ALWAYS_EAGER:\n raise click.ClickException(\n \"Disable CELERY_ALWAYS_EAGER in your settings file to spawn workers.\"\n )\n\n daemons.append(_get_daemon(\"worker\"))\n\n from sentry import eventstream\n\n if eventstream.backend.requires_post_process_forwarder():\n kafka_consumers.add(\"post-process-forwarder-errors\")\n kafka_consumers.add(\"post-process-forwarder-transactions\")\n kafka_consumers.add(\"post-process-forwarder-issue-platform\")\n\n daemons.extend([_get_daemon(name) for name in settings.SENTRY_EXTRA_WORKERS])\n\n if settings.SENTRY_DEV_PROCESS_SUBSCRIPTIONS:\n kafka_consumers.update(_SUBSCRIPTION_RESULTS_CONSUMERS)\n\n if settings.SENTRY_USE_METRICS_DEV and settings.SENTRY_USE_RELAY:\n kafka_consumers.add(\"ingest-metrics\")\n kafka_consumers.add(\"ingest-generic-metrics\")\n kafka_consumers.add(\"billing-metrics-consumer\")\n\n if settings.SENTRY_USE_UPTIME:\n kafka_consumers.add(\"uptime-results\")\n kafka_consumers.add(\"uptime-configs\")\n\n if settings.SENTRY_USE_RELAY:\n daemons += [(\"relay\", [\"sentry\", \"devservices\", \"attach\", \"relay\"])]\n\n kafka_consumers.add(\"ingest-events\")\n kafka_consumers.add(\"ingest-attachments\")\n kafka_consumers.add(\"ingest-transactions\")\n kafka_consumers.add(\"ingest-monitors\")\n kafka_consumers.add(\"ingest-feedback-events\")\n\n kafka_consumers.add(\"monitors-clock-tick\")\n kafka_consumers.add(\"monitors-clock-tasks\")\n\n if settings.SENTRY_USE_PROFILING:\n kafka_consumers.add(\"ingest-profiles\")\n\n if settings.SENTRY_USE_SPANS_BUFFER:\n kafka_consumers.add(\"process-spans\")\n kafka_consumers.add(\"ingest-occurrences\")\n kafka_consumers.add(\"detect-performance-issues\")\n\n if occurrence_ingest:\n kafka_consumers.add(\"ingest-occurrences\")\n\n # Create all topics if the Kafka eventstream is selected\n if kafka_consumers:\n with get_docker_client() as docker:\n containers = {c.name for c in docker.containers.list(filters={\"status\": \"running\"})}\n if \"sentry_kafka\" not in containers:\n raise click.ClickException(\n f\"\"\"\nDevserver is configured to start some kafka consumers, but Kafka\ndon't seem to be running.\n\nThe following consumers were intended to be started: {kafka_consumers}\n\nMake sure you have:\n\n SENTRY_USE_RELAY = True\n\nor:\n\n SENTRY_EVENTSTREAM = \"sentry.eventstream.kafka.KafkaEventStream\"\n\nand run `sentry devservices up kafka`.\n\nAlternatively, run without --workers.\n\"\"\"\n )\n\n from sentry.conf.types.kafka_definition import Topic\n from sentry.utils.batching_kafka_consumer import create_topics\n from sentry.utils.kafka_config import get_topic_definition\n\n for topic in Topic:\n topic_defn = get_topic_definition(topic)\n create_topics(topic_defn[\"cluster\"], [topic_defn[\"real_topic_name\"]])\n\n if dev_consumer:\n daemons.append(\n (\"dev-consumer\", [\"sentry\", \"run\", \"dev-consumer\"] + list(kafka_consumers))\n )\n else:\n for name in kafka_consumers:\n daemons.append(\n (\n name,\n [\n \"sentry\",\n \"run\",\n \"consumer\",\n name,\n \"--consumer-group=sentry-consumer\",\n \"--auto-offset-reset=latest\",\n \"--no-strict-offset-reset\",\n ],\n )\n )\n\n # A better log-format for local dev when running through honcho,\n # but if there aren't any other daemons, we don't want to override.\n if daemons:\n uwsgi_overrides[\"log-format\"] = \"%(method) %(status) %(uri) %(proto) %(size)\"\n else:\n uwsgi_overrides[\"log-format\"] = \"[%(ltime)] %(method) %(status) %(uri) %(proto) %(size)\"\n\n # Prevent logging of requests to specified endpoints.\n #\n # TODO: According to the docs, the final `log-drain` value is evaluated as a regex (and indeed,\n # joining the options with `|` works), but no amount of escaping, not escaping, escaping the\n # escaping, using raw strings, or any combo thereof seems to actually work if you include a\n # regex pattern string in the list. Docs are here:\n # https://uwsgi-docs.readthedocs.io/en/latest/Options.html?highlight=log-format#log-drain\n if settings.DEVSERVER_REQUEST_LOG_EXCLUDES:\n filters = settings.DEVSERVER_REQUEST_LOG_EXCLUDES\n filter_pattern = \"|\".join(map(lambda s: re.escape(s), filters))\n uwsgi_overrides[\"log-drain\"] = filter_pattern\n\n server_port = os.environ[\"SENTRY_BACKEND_PORT\"]\n\n if silo == \"region\":\n os.environ[\"SENTRY_SILO_DEVSERVER\"] = \"1\"\n os.environ[\"SENTRY_SILO_MODE\"] = \"REGION\"\n os.environ[\"SENTRY_REGION\"] = \"us\"\n os.environ[\"SENTRY_REGION_SILO_PORT\"] = str(server_port)\n os.environ[\"SENTRY_CONTROL_SILO_PORT\"] = str(ports[\"server\"] + 1)\n os.environ[\"SENTRY_DEVSERVER_BIND\"] = f\"127.0.0.1:{server_port}\"\n os.environ[\"UWSGI_HTTP_SOCKET\"] = f\"127.0.0.1:{ports['region.server']}\"\n os.environ[\"UWSGI_WORKERS\"] = \"8\"\n os.environ[\"UWSGI_THREADS\"] = \"2\"\n\n server = SentryHTTPServer(\n host=host,\n port=int(server_port),\n extra_options=uwsgi_overrides,\n debug=debug_server,\n )\n\n # If we don't need any other daemons, just launch a normal uwsgi webserver\n # and avoid dealing with subprocesses\n if not daemons and not silo:\n server.run()\n\n import sys\n from subprocess import list2cmdline\n\n from honcho.manager import Manager\n\n os.environ[\"PYTHONUNBUFFERED\"] = \"true\"\n\n if debug_server:\n threading.Thread(target=server.run).start()\n else:\n # Make sure that the environment is prepared before honcho takes over\n # This sets all the appropriate uwsgi env vars, etc\n server.prepare_environment()\n\n if silo != \"control\":\n daemons += [_get_daemon(\"server\")]\n\n cwd = os.path.realpath(os.path.join(settings.PROJECT_ROOT, os.pardir, os.pardir))\n\n from sentry.runner.formatting import get_honcho_printer\n\n honcho_printer = get_honcho_printer(prefix=prefix, pretty=pretty)\n\n manager = Manager(honcho_printer)\n for name, cmd in daemons:\n quiet = bool(\n name not in (settings.DEVSERVER_LOGS_ALLOWLIST or ())\n and settings.DEVSERVER_LOGS_ALLOWLIST\n )\n manager.add_process(name, list2cmdline(cmd), quiet=quiet, cwd=cwd)\n\n if silo == \"control\":\n control_environ = {\n \"SENTRY_SILO_DEVSERVER\": \"1\",\n \"SENTRY_SILO_MODE\": \"CONTROL\",\n \"SENTRY_REGION\": \"\",\n \"SENTRY_CONTROL_SILO_PORT\": server_port,\n \"SENTRY_REGION_SILO_PORT\": str(ports[\"region.server\"]),\n \"SENTRY_DEVSERVER_BIND\": f\"127.0.0.1:{server_port}\",\n \"UWSGI_HTTP_SOCKET\": f\"127.0.0.1:{ports['server']}\",\n \"UWSGI_WORKERS\": \"8\",\n \"UWSGI_THREADS\": \"2\",\n }\n merged_env = os.environ.copy()\n merged_env.update(control_environ)\n control_services = [\"server\"]\n if workers:\n control_services.append(\"worker\")\n if celery_beat:\n control_services.append(\"celery-beat\")\n\n for service in control_services:\n name, cmd = _get_daemon(service)\n name = f\"control.{name}\"\n quiet = bool(\n name not in (settings.DEVSERVER_LOGS_ALLOWLIST or ())\n and settings.DEVSERVER_LOGS_ALLOWLIST\n )\n manager.add_process(name, list2cmdline(cmd), quiet=quiet, cwd=cwd, env=merged_env)\n\n manager.loop()\n sys.exit(manager.returncode)", "smellKey": "S107", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, string='unknown', required=False, readonly=False, domain=[], context={}, states=None, priority=0, change_default=False, size=None, ondelete=None, translate=False, select=False, manual=False, **args):\n \"\"\"\n\n The 'manual' keyword argument specifies if the field is a custom one.\n It corresponds to the 'state' column in ir_model_fields.\n\n \"\"\"\n # add parameters and default values\n args['copy'] = args.get('copy', True)\n args['string'] = string\n args['help'] = args.get('help', '')\n args['required'] = required\n args['readonly'] = readonly\n args['_domain'] = domain\n args['_context'] = context\n args['states'] = states\n args['priority'] = priority\n args['change_default'] = change_default\n args['size'] = size\n args['ondelete'] = ondelete.lower() if ondelete else None\n args['translate'] = translate\n args['select'] = select\n args['manual'] = manual\n args['write'] = args.get('write', False)\n args['read'] = args.get('read', False)\n args['selectable'] = args.get('selectable', True)\n args['group_operator'] = args.get('group_operator', None)\n args['groups'] = args.get('groups', None)\n args['deprecated'] = args.get('deprecated', None)\n args['_prefetch'] = args.get('_prefetch', True)\n\n self._args = EMPTY_DICT\n for key, val in args.iteritems():\n setattr(self, key, val)\n\n # prefetch only if _classic_write, not deprecated and not manual\n if not self._classic_write or self.deprecated or self.manual:\n self._prefetch = False", "smellKey": "S107", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=32,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n initializer_range=0.02,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n self.initializer_range = initializer_range", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(\n self,\n parent,\n batch_size=12,\n image_size=30,\n patch_size=2,\n num_channels=3,\n is_training=True,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n dropout=0.1,\n attention_dropout=0.1,\n initializer_range=0.02,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.image_size = image_size\n self.patch_size = patch_size\n self.num_channels = num_channels\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.dropout = dropout\n self.attention_dropout = attention_dropout\n self.initializer_range = initializer_range\n self.scope = scope", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@filter_out_non_signature_kwargs()\n def preprocess(\n self,\n images: ImageInput,\n do_resize: bool = None,\n size: int = None,\n keep_aspect_ratio: bool = None,\n ensure_multiple_of: int = None,\n resample: PILImageResampling = None,\n do_rescale: bool = None,\n rescale_factor: float = None,\n do_normalize: bool = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n do_pad: bool = None,\n size_divisor: int = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Size of the image after reszing. If `keep_aspect_ratio` is `True`, the image is resized to the largest\n possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is set, the image is\n resized to a size that is a multiple of this value.\n keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):\n Whether to keep the aspect ratio of the image. If False, the image will be resized to (size, size). If\n True, the image will be resized to keep the aspect ratio and the size will be the maximum possible.\n ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):\n Ensure that the image size is a multiple of this value.\n resample (`int`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only\n has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n size = size if size is not None else self.size\n size = get_size_dict(size)\n keep_aspect_ratio = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio\n ensure_multiple_of = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_pad = do_pad if do_pad is not None else self.do_pad\n size_divisor = size_divisor if size_divisor is not None else self.size_divisor\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_pad=do_pad,\n size_divisibility=size_divisor,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n if do_resize:\n images = [\n self.resize(\n image=image,\n size=size,\n resample=resample,\n keep_aspect_ratio=keep_aspect_ratio,\n ensure_multiple_of=ensure_multiple_of,\n input_data_format=input_data_format,\n )\n for image in images\n ]\n\n if do_rescale:\n images = [\n self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_normalize:\n images = [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_pad:\n images = [\n self.pad_image(image=image, size_divisor=size_divisor, input_data_format=input_data_format)\n for image in images\n ]\n\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images\n ]\n\n data = {\"pixel_values\": images}\n return BatchFeature(data=data, tensor_type=return_tensors)", "smellKey": "S107", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def func():\n try:\n try:\n raise Exception\n except Exception as e:\n raise\n x = \"Something\"\n y = \"Something\"\n except Exception:\n pass", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def bf_add_license(selected_bfaccount, selected_bfdataset, selected_license):\n \"\"\"\n Args:\n selected_bfaccount: name of selected Pennsieve account (string)\n selected_bfdataset: name of selected Pennsieve dataset (string)\n selected_license: name of selected license (string)\n Action:\n Add/change license for a selected dataset\n Return:\n Success message or error\n \"\"\"\n selected_dataset_id = get_dataset_id(selected_bfdataset)\n\n if not has_edit_permissions(get_access_token(), selected_dataset_id):\n abort(403, \"You do not have permission to edit this dataset.\")\n\n allowed_licenses_list = [\n \"Community Data License Agreement \u2013 Permissive\",\n \"Community Data License Agreement \u2013 Sharing\",\n \"Creative Commons Zero 1.0 Universal\",\n \"Creative Commons Attribution\",\n \"Creative Commons Attribution - ShareAlike\",\n \"Open Data Commons Open Database\",\n \"Open Data Commons Attribution\",\n \"Open Data Commons Public Domain Dedication and License\",\n \"Apache 2.0\",\n \"GNU General Public License v3.0\",\n \"GNU Lesser General Public License\",\n \"MIT\",\n \"Mozilla Public License 2.0\",\n ]\n if selected_license not in allowed_licenses_list:\n abort(403, \"Please select a valid license.\")\n jsonfile = {\"license\": selected_license}\n try: \n r = requests.put(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}\", json=jsonfile, headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n except Exception as e:\n raise Exception(e) from e\n return {\"message\": \"License added!\"}", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def _XMLTransform(source_pairs, outputs_zip):\n \"\"\"\n Apply module codes to input sources.\n \"\"\"\n with build_utils.TempDir() as temp_dir:\n path_info = resource_utils.ResourceInfoFile()\n for source, module in source_pairs:\n with codecs.open(source, 'r', 'utf-8') as f:\n xml_content = f.read()\n loaded_module = _ImportModuleByPath(module)\n\n if not xml_content or not loaded_module:\n continue\n\n root = ET.XML(xml_content)\n result = loaded_module._ProcessXML(root) # pylint: disable=protected-access\n output = ET.tostring(result,\n encoding='utf-8',\n xml_declaration=True)\n\n # Parse output path\n # For simplicity, we assume input path will always has java/res in\n # it\n if not (relpath := _UnderJavaRes(os.path.abspath(source))):\n raise Exception('input file %s is not under java/res' % source)\n\n # resource_overlay doesn't seem to work from\n # android_generated_resources\n relpath = _AddBravePrefix(relpath)\n output_filename = os.path.join(temp_dir, relpath)\n parent_dir = os.path.dirname(output_filename)\n build_utils.MakeDirectory(parent_dir)\n _ProcessFile(output_filename, output)\n path_info.AddMapping(relpath, source)\n\n path_info.Write(outputs_zip + '.info')\n zip_helpers.zip_directory(outputs_zip, temp_dir)", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def delete(self, *args, **kwargs):\n if self.is_default:\n raise Exception(\"You cannot delete the default organization.\")\n return super().delete(*args, **kwargs)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@staticmethod\n def getPerformanceStats(bridgeName):\n try:\n rxBytesPath = join(\"/sys/class/net/\", bridgeName, \"statistics/rx_bytes\")\n txBytesPath = join(\"/sys/class/net/\", bridgeName, \"statistics/tx_bytes\")\n if not exists(rxBytesPath): raise Exception(\"Cannot find %s\"%rxBytesPath)\n if not exists(txBytesPath): raise Exception(\"Cannot find %s\"%txBytesPath)\n rxBytes = long(doCmd(['cat', rxBytesPath])) / 1000\n txBytes = long(doCmd(['cat', txBytesPath])) / 1000\n sysPerf = successToMap(sys_perf_info())\n cpuUtil = float(100 - float(sysPerf['cpu_idle']) * 100)\n freeMemory = MtoBytes(long(sysPerf['mem_free']))\n xmInfo = successToMap(xen_get_xm_info())\n totalMemory = MtoBytes(long(xmInfo['total_memory']))\n rs = toGson({\"cpuUtil\":cpuUtil, \"totalMemory\":totalMemory, \"freeMemory\":freeMemory, \"rxBytes\":rxBytes, \"txBytes\":txBytes})\n logger.info(OvmHost.getPerformanceStats, rs)\n return rs\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmHost.getPerformanceStats, errmsg)\n raise XmlRpcFault(toErrCode(OvmHost, OvmHost.getPerformanceStats), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def advance(self, remainder, start=None):\n if self._current is None:\n raise Exception('advancing requires active source text')\n if remainder.strip():\n self._replace(remainder, start, fixnested=True)\n else:\n if self._nested:\n self._replace('', start, fixnested=True)\n #raise Exception('cannot advance while nesting')\n else:\n self._clear(start)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def delete_additional_story(self, story_id: str) -> None:\n \"\"\"Removes a story from the additional_story_references list.\n\n Args:\n story_id: str. The story id to remove from the list.\n\n Raises:\n Exception. The story ID is not present in the additional stories\n list of the topic.\n \"\"\"\n deleted = False\n for index, reference in enumerate(self.additional_story_references):\n if reference.story_id == story_id:\n del self.additional_story_references[index]\n deleted = True\n break\n if not deleted:\n raise Exception(\n 'The story_id %s is not present in the additional '\n 'story references list of the topic.' % story_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@staticmethod\n def destroy(poolUuid, path):\n try:\n OvmStoragePool()._getSrByNameLable(poolUuid)\n if not exists(path): raise Exception(\"Cannot find %s\"%path)\n dir = dirname(path)\n if exists(join(dir, 'vm.cfg')):\n # delete root disk\n vmNamePath = join(dir, 'vmName')\n if exists(vmNamePath):\n vmNameFd = open(vmNamePath, 'r')\n vmName = vmNameFd.readline()\n vmName = vmName.rstrip('\\n')\n link = join(dirname(dir), vmName)\n doCmd(['rm', '-rf', link])\n vmNameFd.close()\n else:\n logger.warning(OvmVolume.destroy, \"Can not find vmName file in %s\"%dir)\n doCmd(['rm','-rf', dir])\n else:\n doCmd(['rm', path])\n return SUCC()\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmVolume.destroy, errmsg)\n raise XmlRpcFault(toErrCode(OvmVolume, OvmVolume.destroy), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def _get_query(self) -> Q:\n \"\"\"\n Generates a query for all settings for a project, org, user, or team.\n\n Args:\n recipients: The recipients of the notification settings (user or team).\n projects_ids: The projects to get notification settings for.\n organization_id: The organization to get notification settings for.\n \"\"\"\n if not self.recipients:\n raise Exception(\"recipient, team_ids, or user_ids must be provided\")\n\n user_ids, team_ids = [], []\n for recipient in self.recipients:\n if recipient_is_user(recipient):\n user_ids.append(recipient.id)\n elif recipient_is_team(recipient):\n team_ids.append(recipient.id)\n\n if not user_ids and not team_ids:\n raise Exception(\"recipients must be either user or team\")\n\n project_settings = (\n Q(\n (Q(user_id__in=user_ids) | Q(team_id__in=team_ids)),\n scope_type=NotificationScopeEnum.PROJECT.value,\n scope_identifier__in=self.project_ids,\n )\n if self.project_ids\n else Q()\n )\n\n org_settings = (\n Q(\n (Q(user_id__in=user_ids) | Q(team_id__in=team_ids)),\n scope_type=NotificationScopeEnum.ORGANIZATION.value,\n scope_identifier=self.organization_id,\n )\n if self.organization_id\n else Q()\n )\n\n user_settings = (\n Q(\n Q(user_id__in=user_ids),\n scope_type=NotificationScopeEnum.USER.value,\n scope_identifier__in=user_ids,\n )\n if user_ids\n else Q()\n )\n\n team_settings = (\n Q(\n Q(team_id__in=team_ids),\n scope_type=NotificationScopeEnum.TEAM.value,\n scope_identifier__in=team_ids,\n )\n if team_ids\n else Q()\n )\n\n return project_settings | org_settings | user_settings | team_settings", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def getVmNameFromConfigureFile(cfgPath):\n fd = open(cfgPath)\n for i in fd.readlines():\n i = i.strip()\n if i.startswith('name'):\n (key, value) = i.split(\"=\", 1)\n value = value.strip().strip(\"'\")\n fd.close()\n return value\n fd.close()\n raise Exception('Cannot find vm name in %s'%cfgPath)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def read_pfm(file):\n \"\"\" Read a pfm file \"\"\"\n file = open(file, 'rb')\n\n color = None\n width = None\n height = None\n scale = None\n endian = None\n\n header = file.readline().rstrip()\n header = str(bytes.decode(header, encoding='utf-8'))\n if header == 'PF':\n color = True\n elif header == 'Pf':\n color = False\n else:\n raise Exception('Not a PFM file.')\n\n temp_str = str(bytes.decode(file.readline(), encoding='utf-8'))\n dim_match = re.match(r'^(\\d+)\\s(\\d+)\\s$', temp_str)\n if dim_match:\n width, height = map(int, dim_match.groups())\n else:\n raise Exception('Malformed PFM header.')\n\n scale = float(file.readline().rstrip())\n if scale < 0: # little-endian\n endian = '<'\n scale = -scale\n else:\n endian = '>' # big-endian\n\n data = np.fromfile(file, endian + 'f')\n shape = (height, width, 3) if color else (height, width)\n\n data = np.reshape(data, shape)\n # DEY: I don't know why this was there.\n file.close()\n \n return data, scale", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "def _compute_models_for_updating_exploration(\n committer_id: str,\n exploration: exp_domain.Exploration,\n commit_message: Optional[str],\n change_list: Sequence[exp_domain.ExplorationChange]\n) -> List[base_models.BaseModel]:\n \"\"\"Returns a list of updated models related to the exploration model to be\n put to the datastore. The caller should ensure that the Exploration is\n strictly valid before calling this function.\n\n If successful, increments the version number of the incoming exploration\n domain object by 1.\n\n Args:\n committer_id: str. The id of the user who made the commit.\n exploration: Exploration. The exploration to be saved.\n commit_message: str or None. A description of changes made to the state.\n For published explorations, this must be present; for unpublished\n explorations, it should be equal to None.\n change_list: list(ExplorationChange). A list of changes introduced in\n this commit.\n\n Raises:\n Exception. The versions of the given exploration and the currently\n stored exploration model do not match.\n\n Returns:\n list(BaseModel). A list of models to be put to the datastore.\n \"\"\"\n models_to_put: List[base_models.BaseModel] = []\n exploration_model = exp_models.ExplorationModel.get(exploration.id)\n\n if exploration.version > exploration_model.version:\n raise Exception(\n 'Unexpected error: trying to update version %s of exploration '\n 'from version %s. Please reload the page and try again.'\n % (exploration_model.version, exploration.version))\n\n if exploration.version < exploration_model.version:\n raise Exception(\n 'Trying to update version %s of exploration from version %s, '\n 'which is too old. Please reload the page and try again.'\n % (exploration_model.version, exploration.version))\n\n old_states = exp_fetchers.get_exploration_from_model(\n exploration_model).states\n old_metadata = exp_fetchers.get_exploration_from_model(\n exploration_model).get_metadata()\n\n exploration_model = populate_exp_model_fields(\n exploration_model, exploration)\n\n change_list_dict = [change.to_dict() for change in change_list]\n models_to_put.extend(\n exploration_model.get_models_to_put_values(\n committer_id,\n commit_message,\n change_list_dict,\n )\n )\n caching_services.delete_multi(\n caching_services.CACHE_NAMESPACE_EXPLORATION,\n None,\n [exploration.id]\n )\n exploration.version += 1\n\n exp_versions_diff = exp_domain.ExplorationVersionsDiff(change_list)\n\n # Update the version history data for each state and the exploration\n # metadata in the new version of the exploration.\n version_history_model = get_updated_version_history_model(\n exploration,\n change_list,\n committer_id,\n old_states,\n old_metadata\n )\n if version_history_model is not None:\n models_to_put.append(version_history_model)\n\n # Trigger statistics model update.\n new_exp_stats = stats_services.get_stats_for_new_exp_version(\n exploration.id, exploration.version, list(exploration.states.keys()),\n exp_versions_diff, revert_to_version=None)\n\n new_state_stats_mapping = stats_services.get_state_stats_mapping(\n new_exp_stats\n )\n\n new_exp_stats_instance_id = (\n stats_models.ExplorationStatsModel.get_entity_id(\n new_exp_stats.exp_id,\n new_exp_stats.exp_version\n )\n )\n models_to_put.append(\n stats_models.ExplorationStatsModel(\n id=new_exp_stats_instance_id,\n exp_id=new_exp_stats.exp_id,\n exp_version=new_exp_stats.exp_version,\n num_starts_v1=new_exp_stats.num_starts_v1,\n num_starts_v2=new_exp_stats.num_starts_v2,\n num_actual_starts_v1=new_exp_stats.num_actual_starts_v1,\n num_actual_starts_v2=new_exp_stats.num_actual_starts_v2,\n num_completions_v1=new_exp_stats.num_completions_v1,\n num_completions_v2=new_exp_stats.num_completions_v2,\n state_stats_mapping=new_state_stats_mapping\n )\n )\n\n if feconf.ENABLE_ML_CLASSIFIERS:\n trainable_states_dict = exploration.get_trainable_states_dict(\n old_states, exp_versions_diff)\n state_names_with_changed_answer_groups = trainable_states_dict[\n 'state_names_with_changed_answer_groups']\n state_names_with_unchanged_answer_groups = trainable_states_dict[\n 'state_names_with_unchanged_answer_groups']\n state_names_to_train_classifier = state_names_with_changed_answer_groups\n if state_names_with_unchanged_answer_groups:\n (\n state_names_without_classifier,\n state_training_jobs_mapping_models_to_put\n ) = (\n classifier_services\n .get_new_job_models_for_non_trainable_states(\n exploration, state_names_with_unchanged_answer_groups,\n exp_versions_diff\n )\n )\n state_names_to_train_classifier.extend(\n state_names_without_classifier)\n models_to_put.extend(state_training_jobs_mapping_models_to_put)\n if state_names_to_train_classifier:\n models_to_put.extend(\n classifier_services.get_new_job_models_for_trainable_states(\n exploration, state_names_to_train_classifier\n )\n )\n\n # Trigger exploration issues model updation.\n models_to_put.extend(\n stats_services.get_updated_exp_issues_models_for_new_exp_version(\n exploration,\n exp_versions_diff,\n None\n )\n )\n return models_to_put", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def create_platform_parameter(\n cls,\n name: ParamName,\n description: str,\n data_type: platform_parameter_domain.DataTypes,\n default: Optional[Union[bool, int, str, float]] = None\n ) -> platform_parameter_domain.PlatformParameter:\n \"\"\"Creates, registers and returns a platform parameter.\n\n Args:\n name: Enum(PARAMS). The name of the platform parameter.\n description: str. The description of the platform parameter.\n data_type: Enum(DataTypes). The data type of the platform\n parameter, must be one of the following: bool, number, string.\n default: Optional[Union[bool, int, str, float]]. The default value\n for the platform parameter.\n\n Returns:\n PlatformParameter. The created platform parameter.\n\n Raises:\n Exception. The data type is not supported.\n \"\"\"\n if data_type in cls.DEFAULT_VALUE_BY_TYPE_DICT:\n if not default:\n default = cls.DEFAULT_VALUE_BY_TYPE_DICT[data_type]\n else:\n allowed_data_types = [\n data_type_enum.value\n for data_type_enum in cls.DEFAULT_VALUE_BY_TYPE_DICT\n ]\n raise Exception(\n 'Unsupported data type \\'%s\\', must be one of'' %s.' % (\n data_type.value, allowed_data_types))\n\n param_dict: platform_parameter_domain.PlatformParameterDict = {\n 'name': name.value,\n 'description': description,\n 'data_type': data_type.value,\n 'rules': [],\n 'rule_schema_version': (\n feconf.CURRENT_PLATFORM_PARAMETER_RULE_SCHEMA_VERSION),\n 'default_value': default\n }\n return cls.init_platform_parameter_from_dict(param_dict)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def create(self):\n try:\n self._bucket = self._client.create_bucket(\n self.bucket,\n location=self._bucket_location\n )\n slogger.glob.info(\n 'Bucket {} has been created at {} region for {}'.format(\n self.name,\n self.bucket.location,\n self.bucket.user_project,\n ))\n except Exception as ex:\n msg = str(ex)\n slogger.glob.info(msg)\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@column_condition_partial(engine=PandasExecutionEngine)\n def _pandas(cls, column, country_iso_a3, polygon_points, **kwargs):\n # Check if the parameter are None\n if polygon_points is not None:\n polygon = Polygon(polygon_points)\n\n elif country_iso_a3 is not None:\n country_shapes = cls.world[[\"geometry\", \"iso_a3\"]]\n country_shapes = country_shapes[country_shapes[\"iso_a3\"] == country_iso_a3]\n country_shapes.reset_index(drop=True, inplace=True)\n\n if country_shapes.empty:\n raise Exception(\"This ISO country code is not supported.\") # noqa: TRY002, TRY003\n\n polygon = country_shapes[\"geometry\"][0]\n else:\n raise Exception(\"Specify country_iso_a3 or polygon_points\") # noqa: TRY002, TRY003\n\n points = geopandas.GeoSeries(column.apply(Point))\n\n return points.within(polygon)", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def _deassign_role(\n committer: user_domain.UserActionsInfo,\n removed_user_id: str,\n activity_id: str,\n activity_type: str\n) -> None:\n \"\"\"Deassigns given user from their current role in the activity.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user\n who is performing the action.\n removed_user_id: str. ID of the user who is being deassigned from\n the activity.\n activity_id: str. ID of the activity.\n activity_type: str. The type of activity. Possible values:\n constants.ACTIVITY_TYPE_EXPLORATION,\n constants.ACTIVITY_TYPE_COLLECTION.\n\n Raises:\n Exception. UnauthorizedUserException: Could not deassign role.\n Exception. This user does not have any role for the given activity.\n Exception. No activity_rights exists for the given activity id.\n Exception. Guest user is not allowed to deassign roles.\n \"\"\"\n committer_id = committer.user_id\n if committer_id is None:\n raise Exception(\n 'Guest user is not allowed to deassign roles.'\n )\n activity_rights = _get_activity_rights(activity_type, activity_id)\n\n if activity_rights is None:\n raise Exception(\n 'No activity_rights exists for the given activity_id: %s' %\n activity_id\n )\n\n if (\n activity_rights.is_voice_artist(removed_user_id) and\n activity_type == constants.ACTIVITY_TYPE_EXPLORATION\n ):\n user_can_deassign_role = check_can_manage_voice_artist_in_activity(\n committer, activity_rights)\n else:\n user_can_deassign_role = check_can_modify_core_activity_roles(\n committer, activity_rights)\n\n if not user_can_deassign_role:\n logging.error(\n 'User %s tried to remove user %s from an activity %s '\n 'but was refused permission.' % (\n committer_id, removed_user_id, activity_id))\n raise Exception(\n 'UnauthorizedUserException: Could not deassign role.')\n\n if activity_rights.is_owner(removed_user_id):\n old_role = rights_domain.ROLE_OWNER\n activity_rights.owner_ids.remove(removed_user_id)\n elif activity_rights.is_editor(removed_user_id):\n old_role = rights_domain.ROLE_EDITOR\n activity_rights.editor_ids.remove(removed_user_id)\n elif activity_rights.is_voice_artist(removed_user_id):\n old_role = rights_domain.ROLE_VOICE_ARTIST\n activity_rights.voice_artist_ids.remove(removed_user_id)\n elif activity_rights.is_viewer(removed_user_id):\n old_role = rights_domain.ROLE_VIEWER\n activity_rights.viewer_ids.remove(removed_user_id)\n else:\n raise Exception(\n 'This user does not have any role in %s with ID %s'\n % (activity_type, activity_id))\n\n assignee_username = user_services.get_usernames([removed_user_id])[0]\n if assignee_username is None:\n assignee_username = 'ANONYMOUS'\n commit_message = 'Remove %s from role %s for %s' % (\n assignee_username, old_role, activity_type)\n commit_cmds = [{\n 'cmd': rights_domain.CMD_REMOVE_ROLE,\n 'removed_user_id': removed_user_id,\n 'old_role': old_role,\n }]\n\n _save_activity_rights(\n committer_id,\n activity_rights,\n activity_type,\n commit_message,\n commit_cmds\n )\n _update_activity_summary(activity_type, activity_rights)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def default(self, obj):\n if not isinstance(obj, OvmHost): raise Exception(\"%s is not instance of OvmHost\"%type(obj))\n dct = {}\n safeDictSet(obj, dct, 'masterIp')\n safeDictSet(obj, dct, 'cpuNum')\n safeDictSet(obj, dct, 'cpuSpeed')\n safeDictSet(obj, dct, 'totalMemory')\n safeDictSet(obj, dct, 'freeMemory')\n safeDictSet(obj, dct, 'dom0Memory')\n safeDictSet(obj, dct, 'agentVersion')\n safeDictSet(obj, dct, 'name')\n safeDictSet(obj, dct, 'dom0KernelVersion')\n safeDictSet(obj, dct, 'hypervisorVersion')\n return dct", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "@acl_decorators.can_manage_contributors_role\n def post(self, category: str) -> None:\n \"\"\"Manages contributors' roles.\n\n Args:\n category: str. The role's category.\n\n Raises:\n Exception. The language_code cannot be None if the review category\n is translation.\n InvalidInputException. User already has rights to review\n translation.\n InvalidInputException. User already has rights to review question.\n InvalidInputException. User already has rights to submit question.\n \"\"\"\n assert self.normalized_payload is not None\n username = self.normalized_payload['username']\n user_id = user_services.get_user_id_from_username(username)\n\n if user_id is None:\n raise self.InvalidInputException('Invalid username: %s' % username)\n\n language_code = self.normalized_payload.get('language_code', None)\n\n if category == constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION:\n if language_code is None:\n raise Exception(\n 'The language_code cannot be None if the review category is'\n ' \\'translation\\''\n )\n if user_services.can_review_translation_suggestions(\n user_id, language_code=language_code):\n raise self.InvalidInputException(\n 'User %s already has rights to review translation in '\n 'language code %s' % (username, language_code))\n user_services.allow_user_to_review_translation_in_language(\n user_id, language_code)\n elif category == constants.CD_USER_RIGHTS_CATEGORY_REVIEW_QUESTION:\n if user_services.can_review_question_suggestions(user_id):\n raise self.InvalidInputException(\n 'User %s already has rights to review question.' % (\n username))\n user_services.allow_user_to_review_question(user_id)\n else:\n # The handler schema defines the possible values of 'category'.\n # If 'category' has a value other than those defined in the schema,\n # a Bad Request error will be thrown. Hence, 'category' must be\n # 'constants.CD_USER_RIGHTS_CATEGORY_SUBMIT_QUESTION' if this\n # branch is executed.\n assert category == (\n constants.CD_USER_RIGHTS_CATEGORY_SUBMIT_QUESTION)\n if user_services.can_submit_question_suggestions(user_id):\n raise self.InvalidInputException(\n 'User %s already has rights to submit question.' % (\n username))\n user_services.allow_user_to_submit_question(user_id)\n\n assert category in (\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION,\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_QUESTION,\n constants.CD_USER_RIGHTS_CATEGORY_SUBMIT_QUESTION,\n )\n email_manager.send_email_to_new_cd_user(\n user_id, category, language_code=language_code)\n self.render_json({})", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def load_projects(filename=None):\n if filename is None:\n return {}\n else:\n path = os.path.abspath(filename)\n\n if os.path.isfile(path):\n with open(path) as projects_fh:\n projects_dict = yaml.safe_load(projects_fh)\n return projects_dict\n else:\n msg = 'Unable to load projects file at %s' % path\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def visit_title_reference(self, node):\n raise Exception(node)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_dolphin", "language": "python"} {"function": "@classmethod\n def raises_exception(cls):\n try:\n super().setUpClass()\n except ImproperlyConfigured:\n # This raises ImproperlyConfigured(\"You're using the staticfiles\n # app without having set the required STATIC_URL setting.\")\n pass\n else:\n raise Exception(\"setUpClass() should have raised an exception.\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _match_version_flavor(\n self,\n op: str,\n flavor: str,\n client_version: str\n ) -> bool:\n \"\"\"Matches the client version flavor.\n\n Args:\n op: str. The operator for comparison, e.g. '=', '>'.\n flavor: str. The flavor to match, e.g. 'alpha', 'beta', 'test',\n 'release'.\n client_version: str. The version of the client, given in the form\n of '<version>-<hash>-<flavor>'. The hash and flavor of client\n version is optional, but if absent, no flavor filter will\n match to it.\n\n Returns:\n bool. True is the client_version matches the given flavor using\n the operator.\n\n Raises:\n Exception. Given operator is not supported.\n \"\"\"\n match = APP_VERSION_WITH_HASH_REGEXP.match(client_version)\n # Ruling out the possibility of None for mypy type checking.\n assert match is not None\n client_flavor = match.group(2)\n\n # An unspecified client flavor means no flavor-based filters should\n # match to it.\n if client_flavor is None:\n return False\n\n is_equal = flavor == client_flavor\n is_client_flavor_smaller = self._is_first_flavor_smaller(\n client_flavor, flavor)\n is_client_flavor_larger = self._is_first_flavor_smaller(\n flavor, client_flavor)\n\n if op == '=':\n return is_equal\n elif op == '<':\n return is_client_flavor_smaller\n elif op == '<=':\n return is_equal or is_client_flavor_smaller\n elif op == '>':\n return is_client_flavor_larger\n elif op == '>=':\n return is_equal or is_client_flavor_larger\n else:\n raise Exception(\n 'Unsupported comparison operator \\'%s\\' for %s filter, '\n 'expected one of %s.' % (\n op, self._type, self.SUPPORTED_OP_FOR_FILTERS[self._type]))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_log_destroyed_pending_task(self):\n Task = self.__class__.Task\n\n async def kill_me(loop):\n future = self.new_future(loop)\n await future\n # at this point, the only reference to kill_me() task is\n # the Task._wakeup() method in future._callbacks\n raise Exception(\"code never reached\")\n\n mock_handler = mock.Mock()\n self.loop.set_debug(True)\n self.loop.set_exception_handler(mock_handler)\n\n # schedule the task\n coro = kill_me(self.loop)\n task = asyncio.ensure_future(coro, loop=self.loop)\n\n self.assertEqual(self.all_tasks(loop=self.loop), {task})\n\n asyncio.set_event_loop(None)\n\n # execute the task so it waits for future\n self.loop._run_once()\n self.assertEqual(len(self.loop._ready), 0)\n\n coro = None\n source_traceback = task._source_traceback\n task = None\n\n # no more reference to kill_me() task: the task is destroyed by the GC\n support.gc_collect()\n\n self.assertEqual(self.all_tasks(loop=self.loop), set())\n\n mock_handler.assert_called_with(self.loop, {\n 'message': 'Task was destroyed but it is pending!',\n 'task': mock.ANY,\n 'source_traceback': source_traceback,\n })\n mock_handler.reset_mock()", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def validate_channel(channel):\n global config\n try:\n config.channel_names.index(channel)\n except Exception:\n raise Exception('Channel name \"' + channel + '\" is not valid!')", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "@staticmethod\n def start(poolPath, ip):\n pidFile = join(PID_DIR, \"heartbeat.pid\")\n\n def isLive():\n if exists(pidFile):\n f = open(pidFile)\n pid = f.read().strip()\n f.close()\n if isdir(\"/proc/%s\" % pid):\n return long(pid)\n return None\n\n def stopOldHeartBeat(pid):\n os.kill(pid, signal.SIGTERM)\n time.sleep(5)\n pid = isLive()\n if pid != None:\n logger.debug(OvmHaHeartBeat.start, \"SIGTERM cannot stop heartbeat process %s, will try SIGKILL\"%pid)\n os.kill(pid, signal.SIGKILL)\n time.sleep(5)\n pid = isLive()\n if pid != None:\n raise Exception(\"Cannot stop old heartbeat process %s, setup heart beat failed\"%pid)\n\n def heartBeat(hb):\n hb.run()\n\n def setupHeartBeat():\n hb = OvmHaHeartBeat(poolPath, ip)\n p = Process(target=heartBeat, args=(hb,))\n p.start()\n pid = p.pid\n if not isdir(PID_DIR):\n os.makedirs(PID_DIR)\n pidFd = open(pidFile, 'w')\n pidFd.write(str(pid))\n pidFd.close()\n logger.info(OvmHaHeartBeat.start, \"Set up heart beat successfully, pid is %s\" % pid)\n\n pid = isLive()\n if pid != None:\n stopOldHeartBeat(pid)\n\n setupHeartBeat()", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def update_interaction_customization_args(\n self,\n customization_args_mapping: Mapping[\n str, Mapping[str, UnionOfCustomizationArgsDictValues]\n ]\n ) -> None:\n \"\"\"Update the customization_args of InteractionInstance domain object.\n\n Args:\n customization_args_mapping: dict. The new customization_args to set.\n\n Raises:\n Exception. The customization arguments are not unique.\n \"\"\"\n # Here we use cast because for argument 'customization_args_mapping'\n # we have used Mapping type because we want to allow\n # 'update_interaction_customization_args' method to accept different\n # subtypes of customization_arg dictionaries, but the problem with\n # Mapping is that the Mapping does not allow to update(or set) values\n # because Mapping is a read-only type. To overcome this issue, we\n # narrowed down the type from Mapping to Dict by using cast so that\n # while updating or setting a new value MyPy will not throw any error.\n customization_args_dict = cast(\n CustomizationArgsDictType, customization_args_mapping\n )\n customization_args = (\n InteractionInstance.\n convert_customization_args_dict_to_customization_args(\n self.interaction.id,\n customization_args_dict)\n )\n for ca_name in customization_args:\n customization_args[ca_name].validate_subtitled_html()\n\n old_content_id_list = list(itertools.chain.from_iterable([\n self.interaction.customization_args[ca_name].get_content_ids()\n for ca_name in self.interaction.customization_args]))\n\n self.interaction.customization_args = customization_args\n new_content_id_list = list(itertools.chain.from_iterable([\n self.interaction.customization_args[ca_name].get_content_ids()\n for ca_name in self.interaction.customization_args]))\n\n if len(new_content_id_list) != len(set(new_content_id_list)):\n raise Exception(\n 'All customization argument content_ids should be unique. '\n 'Content ids received: %s' % new_content_id_list)\n\n self._update_content_ids_in_assets(\n old_content_id_list, new_content_id_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def prepare(self, sql, force=None):\n \"\"\"\n Prepares the current statement.\n\n Must be called prior to execute even if the underlying database driver\n does not support an explicit prepare before execution.\n \"\"\"\n if sql is None:\n # pylint: disable-next=broad-exception-raised\n raise Exception(\"XXX Unable to prepare None\")\n self.sql = sql\n self._real_cursor = self._prepare(force=force)", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def shutdown(self, kill_mode=\"random\"):\n conn = self._conn\n p = self._p\n self._nmobj = None\n self._nmiface = None\n self._conn = None\n self._p = None\n\n # The test stub service watches stdin and will do a proper\n # shutdown when it closes. That means, to send signals about\n # going away.\n # On the other hand, just killing it will cause the process\n # from dropping off the bus.\n if kill_mode == \"kill\":\n p.kill()\n elif kill_mode == \"stdin-close\":\n p.stdin.close()\n else:\n assert kill_mode == \"random\"\n ops = [p.stdin.close, p.kill]\n random.shuffle(ops)\n ops[0]()\n r = random.random()\n if r < 0.75:\n if r < 0.5:\n time.sleep(r * 0.2)\n ops[1]()\n\n if Util.popen_wait(p, 1) is None:\n raise Exception(\"Stub service did not exit in time\")\n p.stdin.close()\n if self._conn_get_main_object(conn) is not None:\n raise Exception(\n \"Stub service is not still here although it should shut down\"\n )", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "def get_learner_group_by_id(\n group_id: str, strict: bool = False\n) -> Optional[learner_group_domain.LearnerGroup]:\n \"\"\"Returns the learner group domain object given the learner group id.\n\n Args:\n group_id: str. The id of the learner group.\n strict: bool. Whether to fail noisily if no LearnerGroupModel with the\n given group_id exists in the datastore.\n\n Returns:\n LearnerGroup or None. The learner group domain object corresponding to\n the given id or None if no learner group exists for the given group id.\n\n Raises:\n Exception. No LearnerGroupModel found for the given group_id.\n \"\"\"\n learner_group_model = learner_group_models.LearnerGroupModel.get(\n group_id, strict=False)\n\n if not learner_group_model:\n if strict:\n raise Exception(\n 'No LearnerGroupModel found for the given group_id: %s' %\n group_id\n )\n return None\n\n return learner_group_services.get_learner_group_from_model(\n learner_group_model)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_run_presubmit_checks_when_branch_is_specified(self) -> None:\n specified_branch = 'develop'\n cmd_to_get_all_changed_file = [\n 'git', 'diff', '--cached', '--name-only', '--diff-filter=ACM',\n specified_branch]\n def mock_check_output(cmd: list[str], encoding: str = 'utf-8') -> str: # pylint: disable=unused-argument\n if cmd == self.cmd_to_check_current_branch:\n return self.current_branch\n elif cmd == self.cmd_to_match_current_branch_with_remote:\n return '1'\n elif cmd == cmd_to_get_all_changed_file:\n return self.changed_frontend_file\n else:\n raise Exception('Invalid cmd passed: %s' % cmd)\n\n swap_check_output = self.swap(\n subprocess, 'check_output', mock_check_output)\n with self.print_swap, swap_check_output, self.swap_run_lint_checks:\n with self.swap_backend_tests, self.swap_frontend_tests:\n run_presubmit_checks.main(args=['-b', specified_branch])\n\n for script in self.scripts_called:\n self.assertTrue(script)\n self.assertIn('Linting passed.', self.print_arr)\n self.assertIn(\n 'Comparing the current branch with %s' % specified_branch,\n self.print_arr)\n self.assertIn('Frontend tests passed.', self.print_arr)\n self.assertIn('Backend tests passed.', self.print_arr)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def _urlnorm(cls, uri: str) -> str:\n \"\"\"Normalize the URL to create a safe key for the cache\"\"\"\n (scheme, authority, path, query, fragment) = parse_uri(uri)\n if not scheme or not authority:\n raise Exception(\"Only absolute URIs are allowed. uri = %s\" % uri)\n\n scheme = scheme.lower()\n authority = authority.lower()\n\n if not path:\n path = \"/\"\n\n # Could do syntax based normalization of the URI before\n # computing the digest. See Section 6.2.2 of Std 66.\n request_uri = query and \"?\".join([path, query]) or path\n defrag_uri = scheme + \"://\" + authority + request_uri\n\n return defrag_uri", "smellKey": "S112", "smellId": null, "repo": "RaphaelBensoussan_MKdocsPerso", "language": "python"} {"function": "def mock_get_platform_parameter_value(\n parameter_name: str\n ) -> platform_parameter_domain.PlatformDataTypes:\n \"\"\"Mocks get_platform_parameter_value function to return the value of\n the platform parameter if the parameter is present in the\n platform_parameter_names list.\n\n Args:\n parameter_name: str. The name of the platform parameter whose\n value is required.\n\n Returns:\n PlatformDataTypes. The value of the platform parameter if the\n parameter is present in the platform_parameter_names list.\n\n Raises:\n Exception. The parameter_name is not present in the\n platform_parameter_names list.\n \"\"\"\n platform_parameter_name_value_dict = dict(\n (x.value, y) for x, y in platform_parameter_name_value_tuples\n )\n if parameter_name not in platform_parameter_name_value_dict:\n raise Exception(\n 'The value for the platform parameter %s was needed in this '\n 'test, but not specified in the set_platform_parameters '\n 'decorator. Please use this information in the decorator.'\n % parameter_name\n )\n return platform_parameter_name_value_dict[parameter_name]", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def get_new_id(cls, unused_entity_name: str = '') -> str:\n \"\"\"Gets a new id for an entity, based on its name.\n The returned id is guaranteed to be unique among all instances of this\n entity.\n\n Args:\n unused_entity_name: The name of the entity. Coerced to a utf-8\n encoded string. Defaults to ''.\n\n Returns:\n str. New unique id for this entity class.\n\n Raises:\n Exception. An ID cannot be generated within a reasonable number\n of attempts.\n \"\"\"\n for _ in range(base_models.MAX_RETRIES):\n new_id = 'uid_%s' % ''.join(\n random.choice(string.ascii_lowercase)\n for _ in range(feconf.USER_ID_RANDOM_PART_LENGTH))\n if (\n not cls.get_by_id(new_id) and\n not DeletedUserModel.get_by_id(new_id)\n ):\n return new_id\n\n raise Exception('New id generator is producing too many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_missing_override(self):\n class Color(Enum):\n red = 1\n green = 2\n blue = 3\n @classmethod\n def _missing_(cls, item):\n if item == 'three':\n return cls.blue\n elif item == 'bad return':\n # trigger internal error\n return 5\n elif item == 'error out':\n raise ZeroDivisionError\n else:\n # trigger not found\n return None\n self.assertIs(Color('three'), Color.blue)\n try:\n Color(7)\n except ValueError as exc:\n self.assertTrue(exc.__context__ is None)\n else:\n raise Exception('Exception not raised.')\n try:\n Color('bad return')\n except TypeError as exc:\n self.assertTrue(isinstance(exc.__context__, ValueError))\n else:\n raise Exception('Exception not raised.')\n try:\n Color('error out')\n except ZeroDivisionError as exc:\n self.assertTrue(isinstance(exc.__context__, ValueError))\n else:\n raise Exception('Exception not raised.')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@classmethod\n def get_platform_parameter(\n cls, name: str\n ) -> platform_parameter_domain.PlatformParameter:\n \"\"\"Returns the instance of the specified name of the platform\n parameter.\n\n Args:\n name: str. The name of the platform parameter.\n\n Returns:\n PlatformParameter. The instance of the specified platform\n parameter.\n\n Raises:\n Exception. The given name of the platform parameter doesn't exist.\n \"\"\"\n parameter_from_cache = cls.load_platform_parameter_from_memcache(\n name)\n if parameter_from_cache is not None:\n return parameter_from_cache\n\n parameter_from_storage = cls.load_platform_parameter_from_storage(name)\n if parameter_from_storage is not None:\n parameter = parameter_from_storage\n elif name in cls.parameter_registry:\n parameter = cls.parameter_registry[name]\n else:\n raise Exception('Platform parameter not found: %s.' % name)\n\n caching_services.set_multi(\n caching_services.CACHE_NAMESPACE_PLATFORM_PARAMETER, None,\n {\n name: parameter,\n })\n return parameter", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, key, rounds):\n self.state = c_buffer(_get_size(b'chacha_state'))\n self.counter = c_int(1)\n err = LTC.chacha_setup(byref(self.state), key, len(key), rounds)\n if err != CRYPT_OK:\n raise Exception('LTC.chacha_setup(), err = %d, \"%s\"' % (err, _err2str(err)))", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "def __init__(self, debug):\n self.debug = debug\n rhnLog.initLOG(DEFAULT_LOG_LOCATION + \"mgr-delete-patch.log\", self.debug)\n\n try:\n rhnSQL.initDB()\n except rhnSQL.SQLConnectError as e:\n # pylint: disable-next=consider-using-f-string\n log_error(\"Could not connect to the database. %s\" % e)\n # pylint: disable-next=raise-missing-from,broad-exception-raised,consider-using-f-string\n raise Exception(\"Could not connect to the database. %s\" % e)", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def apply_mux(self, pin, mux):\n if mux.pinmode == PinMode.ANALOG:\n self.pins_analog |= 1 << pin\n elif mux.pinmode == PinMode.DIGITAL_INPUT:\n self.pins_digital_input |= 1 << pin\n elif mux.pinmode == PinMode.PUSH_PULL_OUTPUT:\n self.pins_push_pull_output |= 1 << pin\n\n if mux.output_value:\n self.pins_high |= 1 << pin\n elif not mux.output_value:\n self.pins_low |= 1 << pin\n elif mux.output_value is None:\n pass\n else:\n raise Exception(\"unsupported output value\", mux.output_value)\n elif mux.pinmode is None:\n pass\n else:\n raise Exception(\"unsupported pinmode\", mux.pinmode)", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "@column_condition_partial(engine=PandasExecutionEngine)\n def _pandas(cls, column, **kwargs):\n shape = kwargs.get(\"shape\")\n shape_format = kwargs.get(\"shape_format\")\n column_shape_format = kwargs.get(\"column_shape_format\")\n\n # Check that shape is given and given in the correct format\n if shape is not None:\n try:\n if shape_format == \"wkt\":\n shape_ref = geos.from_wkt(shape)\n elif shape_format == \"wkb\":\n shape_ref = geos.from_wkb(shape)\n elif shape_format == \"geojson\":\n shape_ref = geos.from_geojson(shape)\n else:\n raise NotImplementedError( # noqa: TRY301\n \"Shape constructor method not implemented. Must be in WKT, WKB, or GeoJSON format.\"\n )\n except Exception:\n raise Exception(\"A valid reference shape was not given.\") # noqa: TRY002, TRY003\n else:\n raise Exception(\"A shape must be provided for this method.\") # noqa: TRY002, TRY003\n\n # Load the column into a pygeos Geometry vector from numpy array (Series not supported).\n if column_shape_format == \"wkt\":\n shape_test = geos.from_wkt(column.to_numpy(), on_invalid=\"ignore\")\n elif column_shape_format == \"wkb\":\n shape_test = geos.from_wkb(column.to_numpy(), on_invalid=\"ignore\")\n else:\n raise NotImplementedError(\"Column values shape format not implemented.\")\n\n # Allow for an array of reference shapes to be provided. Return a union of all the shapes in the array (Polygon or Multipolygon)\n shape_ref = geos.union_all(shape_ref)\n\n # Prepare the geometries\n geos.prepare(shape_ref)\n geos.prepare(shape_test)\n\n return pd.Series(geos.intersects(shape_ref, shape_test))", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def main():\n\n from optparse import OptionParser\n\n parser = OptionParser(\"usage: %prog [options] {configfile}\")\n parser.add_option(\"-s\", action=\"store\", type=\"string\", dest=\"section\",\n help=\"sets a specific section to be converted\")\n parser.add_option(\"-t\", action=\"store\", type=\"string\", dest=\"target\",\n help=\"specifies the target vm. Will search for TARGET.yaml\")\n parser.add_option(\"-o\", action=\"store\", type=\"string\", dest=\"outdir\",\n help=\"specifies the output directory for generated C++ code\")\n parser.add_option(\"-n\", action=\"store\", type=\"string\", dest=\"out_file\",\n help=\"specifcies the name of the output file, defaults to the prefix in the .ini file\")\n\n (opts, args) = parser.parse_args()\n\n # script directory\n workingdir = os.path.dirname(inspect.getfile(inspect.currentframe()))\n\n if len(args) == 0:\n parser.error('invalid number of arguments')\n\n userconfig = configparser.ConfigParser()\n userconfig_path = os.path.join(os.path.abspath(\n os.path.dirname(__file__)), \"../tojs\", 'userconf.ini')\n userconfig.read(userconfig_path)\n userconfig.set('DEFAULT', 'configdir', os.path.dirname(args[0]))\n # logger.info('Using userconfig \\n %s' % (userconfig.items('DEFAULT')))\n\n clang_lib_path = os.path.join(userconfig.get(\n 'DEFAULT', 'cxxgeneratordir'), 'libclang')\n cindex.Config.set_library_path(clang_lib_path)\n\n config = configparser.ConfigParser()\n config.read(args[0])\n\n if (0 == len(config.sections())):\n raise Exception(\"No sections defined in config file\")\n\n sections = []\n if opts.section:\n if (opts.section in config.sections()):\n sections = []\n sections.append(opts.section)\n else:\n raise Exception(\n \"Section %s not found in config file\" % opts.section)\n else:\n logger.info(\"processing all sections\")\n sections = config.sections()\n\n # find available targets\n targetdir = os.path.join(workingdir, \"targets\")\n targets = []\n if (os.path.isdir(targetdir)):\n targets = [entry for entry in os.listdir(targetdir)\n if (os.path.isdir(os.path.join(targetdir, entry)))]\n if 0 == len(targets):\n raise Exception(\"No targets defined\")\n\n if opts.target:\n if (opts.target in targets):\n targets = []\n targets.append(opts.target)\n\n if opts.outdir:\n outdir = opts.outdir\n else:\n outdir = os.path.join(workingdir, \"gen\")\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n for t in targets:\n # Fix for hidden '.svn', '.cvs' and '.git' etc. folders - these must be ignored or otherwise they will be interpreted as a target.\n if t == \".svn\" or t == \".cvs\" or t == \".git\" or t == \".gitignore\":\n continue\n\n logger.info(\".... Generating bindings for target\" + t)\n for s in sections:\n logger.info(\".... .... Processing section \" + s)\n gen_opts = {\n 'prefix': config.get(s, 'prefix'),\n 'headers': re.split('[\\s,]+', re.sub('[#;].*', '', (config.get(s, 'headers', raw=False, vars=dict(userconfig.items('DEFAULT')))))),\n 'replace_headers': config.get(s, 'replace_headers') if config.has_option(s, 'replace_headers') else None,\n 'classes': re.split('[\\s,]+', re.sub('[#;].*', '', config.get(s, 'classes'))),\n 'classes_need_extend': config.get(s, 'classes_need_extend').split(' ') if config.has_option(s, 'classes_need_extend') else [],\n 'clang_args': (config.get(s, 'extra_arguments', raw=False, vars=dict(userconfig.items('DEFAULT'))) or \"\").split(\" \"),\n 'target': os.path.join(workingdir, \"targets\", t),\n 'outdir': outdir,\n 'search_path': os.path.abspath(os.path.join(userconfig.get('DEFAULT', 'cocosdir'), 'cocos')),\n 'remove_prefix': config.get(s, 'remove_prefix'),\n 'target_ns': config.get(s, 'target_namespace'),\n 'cpp_ns': config.get(s, 'cpp_namespace').split(' ') if config.has_option(s, 'cpp_namespace') else None,\n 'classes_have_no_parents': config.get(s, 'classes_have_no_parents'),\n 'base_classes_to_skip': config.get(s, 'base_classes_to_skip'),\n 'getter_setter': config.get(s, 'getter_setter') if config.has_option(s, 'getter_setter') else \"\",\n 'abstract_classes': config.get(s, 'abstract_classes'),\n 'class_module_configs': config.get(s, 'class_module_configs') if config.has_option(s, 'class_module_configs') else {},\n 'method_module_configs': config.get(s, 'method_module_configs') if config.has_option(s, 'method_module_configs') else {},\n 'persistent_classes': config.get(s, 'persistent_classes') if config.has_option(s, 'persistent_classes') else None,\n 'classes_owned_by_cpp': config.get(s, 'classes_owned_by_cpp') if config.has_option(s, 'classes_owned_by_cpp') else None,\n 'skip': config.get(s, 'skip'),\n 'skip_public_fields': config.get(s, 'skip_public_fields') if config.has_option(s, 'skip_public_fields') else None,\n 'field': config.get(s, 'field') if config.has_option(s, 'field') else None,\n 'obtain_return_value': config.get(s, 'obtain_return_value') if config.has_option(s, 'obtain_return_value') else None,\n 'rename_functions': config.get(s, 'rename_functions'),\n 'rename_classes': config.get(s, 'rename_classes'),\n 'out_file': opts.out_file or config.get(s, 'prefix'),\n 'script_type': t,\n 'macro_judgement': config.get(s, 'macro_judgement') if config.has_option(s, 'macro_judgement') else None,\n 'hpp_headers': config.get(s, 'hpp_headers', raw=False, vars=dict(userconfig.items('DEFAULT'))).split(' ') if config.has_option(s, 'hpp_headers') else None,\n 'cpp_headers': config.get(s, 'cpp_headers', raw=False, vars=dict(userconfig.items('DEFAULT'))).split(' ') if config.has_option(s, 'cpp_headers') else None,\n 'win32_clang_flags': (config.get(s, 'win32_clang_flags', raw=False, vars=dict(userconfig.items('DEFAULT'))) or \"\").split(\" \") if config.has_option(s, 'win32_clang_flags') else None\n }\n generator = Generator(gen_opts)\n generator.generate_code()", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "@property\n def element_count(self):\n \"\"\"Retrieve the number of elements in this type.\n\n Returns an int.\n\n If the Type is not an array or vector, this raises.\n \"\"\"\n result = conf.lib.clang_getNumElements(self)\n if result < 0:\n raise Exception('Type does not have elements.')\n\n return result", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n urllib3_version = urllib3_version.split('.')\n assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.\n\n # Sometimes, urllib3 only reports its version as 16.1.\n if len(urllib3_version) == 2:\n urllib3_version.append('0')\n\n # Check urllib3 for compatibility.\n major, minor, patch = urllib3_version # noqa: F811\n major, minor, patch = int(major), int(minor), int(patch)\n # urllib3 >= 1.21.1, <= 1.26\n assert major == 1\n assert minor >= 21\n assert minor <= 26\n\n # Check charset_normalizer for compatibility.\n if chardet_version:\n major, minor, patch = chardet_version.split('.')[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # chardet_version >= 3.0.2, < 5.0.0\n assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)\n elif charset_normalizer_version:\n major, minor, patch = charset_normalizer_version.split('.')[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # charset_normalizer >= 2.0.0 < 3.0.0\n assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)\n else:\n raise Exception(\"You need either charset_normalizer or chardet installed\")", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def parse_size(s):\n m = re.match(r'(\\d+)(mb|kb|gb)?', s, re.IGNORECASE)\n if m is None:\n raise Exception(f'unrecognized size: {s}')\n size = int(m.group(1))\n if not m.group(2):\n pass\n elif m.group(2).lower() == 'kb':\n size *= 1024\n elif m.group(2).lower() == 'mb':\n size *= 1024 * 1024\n elif m.group(2).lower() == 'gb':\n size *= 1024 * 1024 * 1024\n return size", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_curl", "language": "python"} {"function": "def test_nested_exception_in_except(self):\n hit_else = False\n hit_finally = False\n hit_except = False\n hit_inner_except = False\n hit_inner_else = False\n\n try:\n try:\n raise Exception('inner exception')\n except:\n hit_inner_except = True\n raise Exception('outer exception')\n else:\n hit_inner_else = True\n except:\n hit_except = True\n else:\n hit_else = True\n finally:\n hit_finally = True\n\n self.assertTrue(hit_inner_except)\n self.assertFalse(hit_inner_else)\n self.assertFalse(hit_else)\n self.assertTrue(hit_finally)\n self.assertTrue(hit_except)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def pytorch(op, name: str, cc: int, jit: bool = False, sourcedir: str = \"\"):\n \"\"\"\n Generates source for building a PyTorch CUDA module that leverages the CUTLASS kernel\n specified by ``op``. If the ``jit`` parameter is set to true, the module is just-in-time\n compiled, loaded, and returned.\n\n The result of this method is files within ``sourcedir`` that can be used for building\n a PyTorch module.\n\n :param op: operation to emit in the module\n :param name: name of the module to generate\n :type name: str\n :param cc: compute capability of the device the module should target\n :type cc: int\n :param jit: whether the module should be just-in-time compiled\n :type jit: bool\n :param sourcedir: directory to which generated source files should be written\n :type sourcedir: str\n\n :return: loaded PyTorch module (if ``jit=True``) or None\n \"\"\"\n device_op = op.device_op()\n if isinstance(op, GemmOperationUniversal):\n return _pytorch_gemm(device_op, name, cc, jit, sourcedir)\n elif isinstance(op, GemmOperationGrouped):\n return _pytorch_grouped_gemm(device_op, name, cc, jit, sourcedir)\n elif isinstance(op, Conv2dOperation):\n return _pytorch_conv2d(device_op, name, cc, jit, sourcedir)\n else:\n raise Exception(\n f\"Operation type {type(op)} is not currently supported for PyTorch emission.\"\n )", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def _RaiseException():\n raise Exception(\"test exception\")", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_OpenUSD", "language": "python"} {"function": "def get_node_with_corresponding_exp_id(self, exp_id: str) -> StoryNode:\n \"\"\"Returns the node object which corresponds to a given exploration ids.\n\n Returns:\n StoryNode. The StoryNode object of the corresponding exploration id\n if exist.\n\n Raises:\n Exception. Unable to find the exploration in any node.\n \"\"\"\n for node in self.nodes:\n if node.exploration_id == exp_id:\n return node\n\n raise Exception('Unable to find the exploration id in any node: %s' % (\n exp_id))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "async def fetch_cred_def(\n self,\n cred_def_id: str,\n wallet_type=WALLET_TYPE_INDY,\n ):\n if wallet_type in [WALLET_TYPE_INDY, WALLET_TYPE_ASKAR]:\n cred_def_saved = await self.admin_GET(\n \"/credential-definitions/\" + cred_def_id\n )\n return cred_def_saved\n elif wallet_type == WALLET_TYPE_ANONCREDS:\n cred_def_saved = await self.admin_GET(\n \"/anoncreds/credential-definition/\" + cred_def_id\n )\n return cred_def_saved\n else:\n raise Exception(\"Invalid wallet_type: \" + str(wallet_type))", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _update_story_node(self, topic_story_list: Tuple[\n List[topic_models.TopicModel],\n List[story_models.StoryModel]]) -> result.Result[\n List[story_models.StoryModel],\n Tuple[str, Exception]\n ]:\n \"\"\"Populate the 5 new fields in each story node of the StoryModel\n instance, namely: status, planned_publication_date_msecs,\n last_modified_msecs, first_publication_date_msecs, unpublishing_reason.\n\n Args:\n topic_story_list: Tuple[List[TopicModel], List[StoryModel]]. The\n list of stories whose nodes have to be populated, grouped by\n their topics.\n\n Returns:\n Result(List[StoryModel], (str, Exception)). Result containing the\n list of updated StoryModel instances to be put.\n \"\"\"\n\n updated_story_model_list = []\n with datastore_services.get_ndb_context():\n try:\n topic_model = topic_story_list[0][0]\n story_model_list = topic_story_list[1]\n for story_model in story_model_list:\n nodes = story_model.story_contents['nodes']\n story_reference = next(\n story_ref for story_ref in (\n topic_model.canonical_story_references)\n if story_ref['story_id'] == story_model.id)\n for node in nodes:\n node['unpublishing_reason'] = None\n node['status'] = 'Draft'\n if story_reference['story_is_published']:\n node['status'] = 'Published'\n\n current_topic_version = topic_model.version\n story_published_on = None\n for version in range(current_topic_version, 0, -1):\n snapshot_id = topic_model.get_snapshot_id(\n topic_model.id, version)\n topic_metadata = (\n topic_models.TopicSnapshotMetadataModel.get(\n snapshot_id))\n for cmd in topic_metadata.commit_cmds:\n if (cmd['cmd'] == 'publish_story' and\n cmd['story_id'] == story_model.id):\n story_published_on = (\n utils.get_time_in_millisecs(\n topic_metadata.created_on))\n break\n if story_published_on is not None:\n break\n\n current_story_version = story_model.version\n node_created_on = None\n for version in range(current_story_version, 0, -1):\n snapshot_id = story_model.get_snapshot_id(\n story_model.id, version)\n story_metadata = (\n story_models.StorySnapshotMetadataModel.get(\n snapshot_id))\n for cmd in story_metadata.commit_cmds:\n if (cmd['cmd'] == 'update_story_node_property'\n and cmd['node_id'] == node['id'] and\n node.get('last_modified_msecs') is None):\n node['last_modified_msecs'] = (\n utils.get_time_in_millisecs(\n story_metadata.created_on))\n\n if (cmd['cmd'] == 'add_story_node' and\n cmd['node_id'] == node['id']):\n node_created_on = (\n utils.get_time_in_millisecs(\n story_metadata.created_on))\n break\n if node_created_on is not None:\n break\n\n if node_created_on is None:\n raise Exception(\n 'Node was not created.'\n )\n\n node_published_on = story_published_on if (\n story_published_on is not None and\n node_created_on is not None and\n story_published_on > node_created_on) else (\n node_created_on)\n node['first_publication_date_msecs'] = (\n node_published_on if node['status'] == 'Published'\n else None)\n node['planned_publication_date_msecs'] = (\n node['first_publication_date_msecs'])\n if node.get('last_modified_msecs') is None:\n node['last_modified_msecs'] = node_published_on\n\n updated_story_model_list.append(story_model)\n\n except Exception as e:\n logging.exception(e)\n return result.Err((story_model.id, e))\n return result.Ok(updated_story_model_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@property\n def stderr(self) -> List[str]:\n if self._proc:\n raise Exception('tcpdump still running')\n return open(self._stderrfile).readlines()", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_curl", "language": "python"} {"function": "@property\n def key_type(self):\n if isinstance(self._pkey, RSAPrivateKey):\n return f\"rsa{self._pkey.key_size}\"\n elif isinstance(self._pkey, EllipticCurvePrivateKey):\n return f\"{self._pkey.curve.name}\"\n else:\n raise Exception(f\"unknown key type: {self._pkey}\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_curl", "language": "python"} {"function": "@register.simple_tag\ndef go_boom():\n raise Exception(\"boom\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def upload_metadata_file(file_type, bfaccount, bfdataset, file_path, delete_after_upload):\n # check that the Pennsieve dataset is valid\n selected_dataset_id = get_dataset_id(bfdataset)\n\n # check that the user has permissions for uploading and modifying the dataset\n if not has_edit_permissions(get_access_token(), selected_dataset_id):\n abort(403, \"You do not have permissions to edit this dataset.\")\n headers = create_request_headers(get_access_token())\n # handle duplicates on Pennsieve: first, obtain the existing file ID\n r = requests.get(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}\", headers=headers)\n r.raise_for_status()\n ds_items = r.json()\n # go through the content in the dataset and find the file ID of the file to be uploaded\n for item in ds_items[\"children\"]:\n if item[\"content\"][\"name\"] == file_type:\n item_id = item[\"content\"][\"id\"]\n jsonfile = {\n \"things\": [item_id]\n }\n # then, delete it using Pennsieve method delete(id)\\vf = Pennsieve()\n r = requests.post(f\"{PENNSIEVE_URL}/data/delete\",json=jsonfile, headers=headers)\n r.raise_for_status()\n try:\n ps = connect_pennsieve_client(bfaccount)\n authenticate_user_with_client(ps, bfaccount)\n # create a new manifest for the metadata file\n ps.use_dataset(selected_dataset_id)\n manifest = ps.manifest.create(file_path)\n m_id = manifest.manifest_id\n except Exception as e:\n error_message = \"Could not create manifest file for this dataset\"\n abort(500, error_message)\n \n # upload the manifest file\n try: \n ps.manifest.upload(m_id)\n # create a subscriber function with ps attached so it can be used to unusbscribe\n subscriber_metadata_ps_client = partial(subscriber_metadata, ps)\n # subscribe for the upload to finish\n ps.subscribe(10, False, subscriber_metadata_ps_client)\n except Exception as e:\n namespace_logger.error(\"Error uploading dataset files\")\n namespace_logger.error(e)\n raise Exception(\"The Pennsieve Agent has encountered an issue while uploading. Please retry the upload. If this issue persists please follow this <a target='_blank' rel='noopener noreferrer' href='https://docs.sodaforsparc.io/docs/how-to/how-to-reinstall-the-pennsieve-agent'> guide</a> on performing a full reinstallation of the Pennsieve Agent to fix the problem.\")\n\n\n # before we can remove files we need to wait for all of the Agent's threads/subprocesses to finish\n # elsewise we get an error that the file is in use and therefore cannot be deleted\n time.sleep(5)\n\n # delete the local file that was created for the purpose of uploading to Pennsieve\n if delete_after_upload:\n os.remove(file_path)", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def find_alignment(self, shape: tuple, layout: cutlass.LayoutType) -> int:\n \"\"\"\n Returns the most preferable alignment for a given shape and layout\n\n :param shape: extent of each dimension of the tensor\n :type shape: tuple\n :param layout: layout of the tensor\n :type layout: cutlass.LayoutType\n\n :return: maximum alignment supported by the data type combination and tensor size\n :rtype: int\n \"\"\"\n # Determine the leading dimension of the shape\n if layout == cutlass.LayoutType.ColumnMajor:\n ld = shape[0]\n elif layout == cutlass.LayoutType.RowMajor:\n ld = shape[1]\n elif layout == cutlass.LayoutType.TensorNHWC:\n ld = shape[-1]\n else:\n raise Exception(f\"Unexpected or unsupported layout {layout}\")\n\n for alignment in sorted(list(self.kernels_by_alignment.keys()), reverse=True):\n if ld % alignment == 0:\n return alignment\n\n # Default to alignment of 1 if no others match\n return 1", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def main(arguments=None):\n raise Exception(\"Legacy arv-run removed.\")", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def get_topic_by_name(\n topic_name: str, strict: bool = False\n) -> Optional[topic_domain.Topic]:\n \"\"\"Returns a domain object representing a topic.\n\n Args:\n topic_name: str. The name of the topic.\n strict: bool. Whether to fail noisily if no Topic exists for\n the given topic name.\n\n Returns:\n Topic or None. The domain object representing a topic with the\n given id, or None if it does not exist.\n\n Raises:\n Exception. No Topic exists for the given topic name.\n \"\"\"\n topic_model: Optional[topic_models.TopicModel] = (\n topic_models.TopicModel.get_by_name(topic_name))\n if topic_model is None:\n if strict:\n raise Exception(\n 'No Topic exists for the given topic name: %s' % topic_name\n )\n return None\n\n return get_topic_from_model(topic_model)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, api_client,\n arvargs=None,\n keep_client=None,\n num_retries=4,\n thread_count=4,\n stdout=sys.stdout):\n\n if arvargs is None:\n arvargs = argparse.Namespace()\n arvargs.work_api = None\n arvargs.output_name = None\n arvargs.output_tags = None\n arvargs.thread_count = 1\n arvargs.collection_cache_size = None\n arvargs.git_info = True\n arvargs.submit = False\n arvargs.defer_downloads = False\n\n self.api = api_client\n self.processes = {}\n self.workflow_eval_lock = threading.Condition(threading.RLock())\n self.final_output = None\n self.final_status = None\n self.num_retries = num_retries\n self.uuid = None\n self.stop_polling = threading.Event()\n self.poll_api = None\n self.pipeline = None\n self.final_output_collection = None\n self.output_name = arvargs.output_name\n self.output_tags = arvargs.output_tags\n self.project_uuid = None\n self.intermediate_output_ttl = 0\n self.intermediate_output_collections = []\n self.trash_intermediate = False\n self.thread_count = arvargs.thread_count\n self.poll_interval = 12\n self.loadingContext = None\n self.should_estimate_cache_size = True\n self.fs_access = None\n self.secret_store = None\n self.stdout = stdout\n self.fast_submit = False\n self.git_info = arvargs.git_info\n self.debug = False\n\n if keep_client is not None:\n self.keep_client = keep_client\n else:\n self.keep_client = arvados.keep.KeepClient(api_client=self.api, num_retries=self.num_retries)\n\n if arvargs.collection_cache_size:\n collection_cache_size = arvargs.collection_cache_size*1024*1024\n self.should_estimate_cache_size = False\n else:\n collection_cache_size = 256*1024*1024\n\n self.collection_cache = CollectionCache(self.api, self.keep_client, self.num_retries,\n cap=collection_cache_size)\n\n self.fetcher_constructor = partial(CollectionFetcher,\n api_client=self.api,\n fs_access=CollectionFsAccess(\"\", collection_cache=self.collection_cache),\n num_retries=self.num_retries)\n\n self.work_api = None\n expected_api = [\"containers\"]\n for api in expected_api:\n try:\n methods = self.api._rootDesc.get('resources')[api]['methods']\n if ('httpMethod' in methods['create'] and\n (arvargs.work_api == api or arvargs.work_api is None)):\n self.work_api = api\n break\n except KeyError:\n pass\n\n if not self.work_api:\n if arvargs.work_api is None:\n raise Exception(\"No supported APIs\")\n else:\n raise Exception(\"Unsupported API '%s', expected one of %s\" % (arvargs.work_api, expected_api))\n\n if self.work_api == \"jobs\":\n logger.error(\"\"\"\n*******************************\nThe 'jobs' API is no longer supported.\n*******************************\"\"\")\n exit(1)\n\n self.loadingContext = ArvLoadingContext(vars(arvargs))\n self.loadingContext.fetcher_constructor = self.fetcher_constructor\n self.loadingContext.resolver = partial(collectionResolver, self.api, num_retries=self.num_retries)\n self.loadingContext.construct_tool_object = self.arv_make_tool\n\n # Add a custom logging handler to the root logger for runtime status reporting\n # if running inside a container\n if arvados_cwl.util.get_current_container(self.api, self.num_retries, logger):\n root_logger = logging.getLogger('')\n\n # Remove existing RuntimeStatusLoggingHandlers if they exist\n handlers = [h for h in root_logger.handlers if not isinstance(h, RuntimeStatusLoggingHandler)]\n root_logger.handlers = handlers\n\n handler = RuntimeStatusLoggingHandler(self.runtime_status_update)\n root_logger.addHandler(handler)\n\n self.toplevel_runtimeContext = ArvRuntimeContext(vars(arvargs))\n self.toplevel_runtimeContext.make_fs_access = partial(CollectionFsAccess,\n collection_cache=self.collection_cache)\n self.toplevel_runtimeContext.secret_store = ArvSecretStore()\n\n self.defer_downloads = arvargs.submit and arvargs.defer_downloads\n\n validate_cluster_target(self, self.toplevel_runtimeContext)", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def main():\n args = parse_args()\n # Attempt to making sure that we run this script from root of repo always\n if not os.path.exists(\".git\"):\n raise Exception(\"This needs to always be run from the root of repo\")\n # Check whether clang-tidy exists\n # print(args)\n if \"exe\" not in args and shutil.which(\"clang-tidy\") is not None:\n print(\"clang-tidy not found. Exiting...\")\n return\n all_files = get_all_commands(args.cdb)\n status = run_tidy_for_all_files(args, all_files)\n if not status:\n raise Exception(\"clang-tidy failed! Refer to the errors above.\")", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cudf", "language": "python"} {"function": "def __init__(self, value, props):\n self.pin = (value & 0x7, (value >> 3) & 0xFF)\n self.signal = Signal((value >> 22) & 0x7F)\n\n output_low = props[\"output-low\"].val\n output_high = props[\"output-high\"].val\n output_enable = props[\"output-enable\"].val or output_low or output_high\n\n input_enable = props[\"input-enable\"].val\n\n if output_enable and input_enable:\n raise Exception(\"can't enable both output and input\")\n if output_low and output_high:\n raise Exception(\"can't define output as both low and high\")\n\n if input_enable:\n self.pinmode = PinMode.DIGITAL_INPUT\n elif output_enable:\n self.pinmode = PinMode.PUSH_PULL_OUTPUT\n\n if output_low:\n self.output_value = True\n elif output_high:\n self.output_value = False\n else:\n self.output_value = None\n else:\n self.pinmode = None", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def __init__(self, cursor, generator, is_struct=False):\n # the cursor to the implementation\n self.cursor = cursor\n self.class_name = cursor.displayname\n self.is_ref_class = self.class_name == \"RefCount\"\n self.rename_destructor = generator.rename_destructor(self.class_name)\n self.parents = []\n self.fields = []\n self.public_fields = []\n self.methods = {}\n self.static_methods = {}\n # Key: function name, Value: list of NativeFunction\n self.dict_of_override_method_should_be_bound = {}\n self.generator = generator\n self.is_const_array = cursor.kind == cindex.TypeKind.CONSTANTARRAY\n self.is_abstract = self.class_name in generator.abstract_classes\n self.is_persistent = self.class_name in generator.persistent_classes\n self.is_class_owned_by_cpp = self.class_name in self.generator.classes_owned_by_cpp\n self.module_config = self.generator.class_module_configs[self.class_name] if self.class_name in self.generator.class_module_configs else {}\n # logger.info(\"class_name:\" + self.class_name + \", is_class_owned_by_cpp:\" + str(self.is_class_owned_by_cpp))\n self._current_visibility = cindex.AccessSpecifier.PRIVATE\n if is_struct:\n self._current_visibility = cindex.AccessSpecifier.PUBLIC\n # for generate lua api doc\n self.override_methods = {}\n self.has_constructor = False\n self.namespace_name = \"\"\n self.is_struct = is_struct\n self.getter_setter = []\n self.getter_list = []\n self.setter_list = []\n self.nested_classes = []\n\n registration_name = generator.get_class_or_rename_class(\n self.class_name)\n if generator.remove_prefix:\n self.target_class_name = re.sub(\n '^' + generator.remove_prefix, '', registration_name)\n else:\n self.target_class_name = registration_name\n self.namespaced_class_name = get_namespaced_class_name(cursor)\n self.namespace_name = get_namespace_name(cursor)\n self.parse()\n # signature_name\n # post parse\n\n def get_func_name(func):\n if isinstance(func, NativeOverloadedFunction):\n return func.implementations[0].func_name\n else:\n return func.func_name\n\n if self.class_name in generator.getter_setter:\n for field_name in iter(generator.getter_setter[self.class_name].keys()):\n field = generator.getter_setter[self.class_name][field_name]\n name_array ='{' +\", \".join(list(map(lambda x: \"\\\"%s\\\"\" % x, field[\"names\"]))) +'}'\n setter = self.find_method(field[\"setter\"])\n getter = self.find_method(field[\"getter\"])\n item = {\n \"name\": '\"'+field_name+'\"' if len(field[\"names\"]) == 1 else name_array,\n \"field_name\": field_name,\n \"names\": field[\"names\"],\n \"getter\": getter,\n \"setter\": setter,\n }\n if getter is None and setter is None:\n logger.info(\"gettter %s, setter %s\" % (field[\"getter\"], field[\"setter\"]))\n raise Exception(\"getter_setter for %s.%s both None\" % (\n self.class_name, field_name))\n if getter is not None:\n self.getter_list.append(get_func_name(getter))\n if isinstance(getter, NativeOverloadedFunction):\n old = getter\n # logger.error(\" old getter %s\" % old.__dict__)\n # logger.error(\" getter_list %s\\n setter_list: %s\", self.getter_list, self.setter_list)\n item[\"getter\"] = getter.implementations[0]\n item[\"getter\"].signature_name = \"js_%s_%s_%s\" % (self.generator.prefix, self.class_name, old.func_name)\n if setter is not None:\n self.setter_list.append(get_func_name(setter))\n self.getter_setter.append(item)", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "def handle_inc_nasm(state, l, ofp):\n m = re.search(r\"^\\s*\\%\\s*include\\s+([\\\"\\<])(.+?)([\\\"\\>])(.*)$\", l)\n if not m:\n return l\n q1, inc, q2, comment = m.groups()\n cf = parse_comment(state, l, comment)\n if q1 == '<' and q2 == '>':\n pass\n elif q1 == '\"' and q2 == '\"':\n pass\n else:\n raise Exception, \"syntax error: include line \" + l\n # info: nasm simply does concat the includes\n for prefix in opts.includes + [\"\"]:\n fn = prefix + inc\n if os.path.isfile(fn):\n add_dep(state, fn, False)\n handle_file(fn, ofp, state)\n return None\n return not_found(state, l, inc, cf.get(\"fatal\"))", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_upx", "language": "python"} {"function": "def mra2_attention(\n query,\n key,\n value,\n mask,\n num_blocks,\n approx_mode,\n block_size=32,\n initial_prior_first_n_blocks=0,\n initial_prior_diagonal_n_blocks=0,\n):\n \"\"\"\n Use Mra to approximate self-attention.\n \"\"\"\n if mra_cuda_kernel is None:\n return torch.zeros_like(query).requires_grad_()\n\n batch_size, num_head, seq_len, head_dim = query.size()\n meta_batch = batch_size * num_head\n\n if seq_len % block_size != 0:\n raise ValueError(\"sequence length must be divisible by the block_size.\")\n\n num_block_per_row = seq_len // block_size\n\n query = query.reshape(meta_batch, seq_len, head_dim)\n key = key.reshape(meta_batch, seq_len, head_dim)\n value = value.reshape(meta_batch, seq_len, head_dim)\n\n if mask is not None:\n query = query * mask[:, :, None]\n key = key * mask[:, :, None]\n value = value * mask[:, :, None]\n\n if approx_mode == \"full\":\n low_resolution_logit, token_count, low_resolution_logit_row_max, value_hat = get_low_resolution_logit(\n query, key, block_size, mask, value\n )\n elif approx_mode == \"sparse\":\n with torch.no_grad():\n low_resolution_logit, token_count, low_resolution_logit_row_max, _ = get_low_resolution_logit(\n query, key, block_size, mask\n )\n else:\n raise Exception('approx_mode must be \"full\" or \"sparse\"')\n\n with torch.no_grad():\n low_resolution_logit_normalized = low_resolution_logit - low_resolution_logit_row_max\n indices, high_resolution_mask = get_block_idxes(\n low_resolution_logit_normalized,\n num_blocks,\n approx_mode,\n initial_prior_first_n_blocks,\n initial_prior_diagonal_n_blocks,\n )\n\n high_resolution_logit = MraSampledDenseMatMul.operator_call(\n query, key, indices, block_size=block_size\n ) / math.sqrt(head_dim)\n max_vals, max_vals_scatter = sparse_max(high_resolution_logit, indices, num_block_per_row, num_block_per_row)\n high_resolution_logit = high_resolution_logit - max_vals_scatter\n if mask is not None:\n high_resolution_logit = high_resolution_logit - 1e4 * (1 - sparse_mask(mask, indices)[:, :, :, None])\n high_resolution_attn = torch.exp(high_resolution_logit)\n high_resolution_attn_out = MraSparseDenseMatMul.operator_call(\n high_resolution_attn, indices, value, num_block_per_row\n )\n high_resolution_normalizer = MraReduceSum.operator_call(\n high_resolution_attn, indices, num_block_per_row, num_block_per_row\n )\n\n if approx_mode == \"full\":\n low_resolution_attn = (\n torch.exp(low_resolution_logit - low_resolution_logit_row_max - 1e4 * high_resolution_mask)\n * token_count[:, None, :]\n )\n\n low_resolution_attn_out = (\n torch.matmul(low_resolution_attn, value_hat)[:, :, None, :]\n .repeat(1, 1, block_size, 1)\n .reshape(meta_batch, seq_len, head_dim)\n )\n low_resolution_normalizer = (\n low_resolution_attn.sum(dim=-1)[:, :, None].repeat(1, 1, block_size).reshape(meta_batch, seq_len)\n )\n\n log_correction = low_resolution_logit_row_max.repeat(1, 1, block_size).reshape(meta_batch, seq_len) - max_vals\n if mask is not None:\n log_correction = log_correction * mask\n\n low_resolution_corr = torch.exp(log_correction * (log_correction <= 0).float())\n low_resolution_attn_out = low_resolution_attn_out * low_resolution_corr[:, :, None]\n low_resolution_normalizer = low_resolution_normalizer * low_resolution_corr\n\n high_resolution_corr = torch.exp(-log_correction * (log_correction > 0).float())\n high_resolution_attn_out = high_resolution_attn_out * high_resolution_corr[:, :, None]\n high_resolution_normalizer = high_resolution_normalizer * high_resolution_corr\n\n context_layer = (high_resolution_attn_out + low_resolution_attn_out) / (\n high_resolution_normalizer[:, :, None] + low_resolution_normalizer[:, :, None] + 1e-6\n )\n\n elif approx_mode == \"sparse\":\n context_layer = high_resolution_attn_out / (high_resolution_normalizer[:, :, None] + 1e-6)\n else:\n raise Exception('config.approx_mode must be \"full\" or \"sparse\"')\n\n if mask is not None:\n context_layer = context_layer * mask[:, :, None]\n\n context_layer = context_layer.reshape(batch_size, num_head, seq_len, head_dim)\n\n return context_layer", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def validate_interval(\n interval: timedelta, error: Exception, date_range: timedelta, top_events: int\n) -> None:\n if interval.total_seconds() <= 0:\n raise error.__class__(\"Interval cannot result in a zero duration.\")\n\n # When top events are present, there can be up to 5x as many points\n max_rollup_points = MAX_ROLLUP_POINTS if top_events == 0 else MAX_ROLLUP_POINTS / top_events\n\n if date_range.total_seconds() / interval.total_seconds() > max_rollup_points:\n raise error", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def download_and_install_node() -> None:\n \"\"\"Download and install node to Oppia tools directory.\"\"\"\n outfile_name = 'node-download'\n\n if common.is_windows_os():\n if common.is_x64_architecture():\n architecture = 'x64'\n else:\n architecture = 'x86'\n\n extension = '.zip'\n node_file_name = 'node-v%s-win-%s' % (\n common.NODE_VERSION, architecture)\n url_to_retrieve = 'https://nodejs.org/dist/v%s/%s%s' % (\n common.NODE_VERSION, node_file_name, extension)\n common.url_retrieve(url_to_retrieve, outfile_name)\n subprocess.check_call(\n ['powershell.exe', '-c', 'expand-archive',\n outfile_name, '-DestinationPath',\n common.OPPIA_TOOLS_DIR])\n else:\n extension = '.tar.gz'\n if common.is_x64_architecture():\n if common.is_mac_os():\n node_file_name = 'node-v%s-darwin-x64' % (common.NODE_VERSION)\n elif common.is_linux_os():\n node_file_name = 'node-v%s-linux-x64' % (common.NODE_VERSION)\n # Oppia only suppports windows, mac and linux operating systems.\n else:\n raise Exception(\n 'System\\'s Operating System is not compatible.')\n else:\n node_file_name = 'node-v%s' % common.NODE_VERSION\n download_and_install_package(\n 'https://nodejs.org/dist/v%s/%s%s' % (\n common.NODE_VERSION, node_file_name, extension),\n outfile_name)\n os.rename(\n os.path.join(common.OPPIA_TOOLS_DIR, node_file_name),\n common.NODE_PATH)\n if node_file_name == 'node-v%s' % common.NODE_VERSION:\n with common.CD(common.NODE_PATH):\n subprocess.check_call(['./configure'])\n subprocess.check_call(['make'])", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_mark_for_rollback_on_error_in_transaction(self):\n with transaction.atomic(savepoint=False):\n # Swallow the intentional error raised.\n with self.assertRaisesMessage(Exception, \"Oops\"):\n # Wrap in `mark_for_rollback_on_error` to check if the\n # transaction is marked broken.\n with transaction.mark_for_rollback_on_error():\n # Ensure that we are still in a good state.\n self.assertFalse(transaction.get_rollback())\n\n raise Exception(\"Oops\")\n\n # mark_for_rollback_on_error marked the transaction as broken \u2026\n self.assertTrue(transaction.get_rollback())\n\n # \u2026 and further queries fail.\n msg = \"You can't execute queries until the end of the 'atomic' block.\"\n with self.assertRaisesMessage(transaction.TransactionManagementError, msg):\n Reporter.objects.create()\n\n # Transaction errors are reset at the end of an transaction, so this\n # should just work.\n Reporter.objects.create()", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_exp_issues(\n exp_id: str, exp_version: int, strict: bool = True\n) -> Optional[stats_domain.ExplorationIssues]:\n \"\"\"Retrieves the ExplorationIssues domain object.\n\n Args:\n exp_id: str. ID of the exploration.\n exp_version: int. Version of the exploration.\n strict: bool. Fails noisily if the model doesn't exist.\n\n Returns:\n ExplorationIssues|None. The domain object for exploration issues or None\n if the exp_id is invalid.\n\n Raises:\n Exception. No ExplorationIssues model found for the given exp_id.\n \"\"\"\n exp_issues_model = stats_models.ExplorationIssuesModel.get_model(\n exp_id, exp_version)\n if exp_issues_model is None:\n if not strict:\n return None\n raise Exception(\n 'No ExplorationIssues model found for the given exp_id: %s' %\n exp_id\n )\n\n return get_exp_issues_from_model(exp_issues_model)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def create(\n cls,\n user_id: str,\n language_code: str,\n topic_id: str,\n opportunity_id: str\n ) -> PinnedOpportunityModel:\n \"\"\"Creates a new PinnedOpportunityModel instance. Fails if the\n model already exists.\n\n Args:\n user_id: str. The ID of the user.\n language_code: str. The code of the language.\n topic_id: str. The ID of the topic.\n opportunity_id: str. The ID of the pinned opportunity.\n\n Returns:\n PinnedOpportunityModel. The created instance.\n\n Raises:\n Exception. There is already a pinned opportunity with\n the given id.\n \"\"\"\n instance_id = cls._generate_id(user_id, language_code, topic_id)\n if cls.get_by_id(instance_id):\n raise Exception(\n 'There is already a pinned opportunity with the given'\n ' id: %s' % instance_id)\n\n instance = cls(\n id=instance_id, user_id=user_id, language_code=language_code,\n topic_id=topic_id, opportunity_id=opportunity_id)\n instance.update_timestamps()\n instance.put()\n return instance", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def get_new_id(cls, unused_entity_name: str) -> str:\n \"\"\"Gets a new id for an entity, based on its name.\n\n The returned id is guaranteed to be unique among all instances of this\n entity.\n\n Args:\n unused_entity_name: The name of the entity. Coerced to a utf-8\n encoded string. Defaults to ''.\n\n Returns:\n str. New unique id for this entity class.\n\n Raises:\n Exception. An ID cannot be generated within a reasonable number\n of attempts.\n \"\"\"\n for _ in range(base_models.MAX_RETRIES):\n new_id = 'pid_%s' % ''.join(\n random.choice(string.ascii_lowercase)\n for _ in range(feconf.USER_ID_RANDOM_PART_LENGTH))\n\n if not cls.get_by_id(new_id):\n return new_id\n\n raise Exception('New id generator is producing too many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def install_mypy_prerequisites(install_globally: bool) -> Tuple[int, str]:\n \"\"\"Install mypy and type stubs from mypy_requirements.txt.\n\n Args:\n install_globally: bool. Whether mypy and its requirements are to be\n installed globally.\n\n Returns:\n tuple(int, str). The return code from installing prerequisites and the\n path of the mypy executable.\n\n Raises:\n Exception. No USER_BASE found for the user.\n \"\"\"\n # TODO(#13398): Change MyPy installation after Python3 migration. Now, we\n # install packages globally for CI. In CI, pip installation is not in a way\n # we expect.\n if install_globally:\n cmd = [\n PYTHON3_CMD, '-m', 'pip', 'install', '-r',\n MYPY_REQUIREMENTS_FILE_PATH\n ]\n else:\n cmd = [\n PYTHON3_CMD, '-m', 'pip', 'install', '-r',\n MYPY_REQUIREMENTS_FILE_PATH, '--target', MYPY_TOOLS_DIR,\n '--upgrade'\n ]\n process = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output = process.communicate()\n if b'can\\'t combine user with prefix' in output[1]:\n uextention_text = ['--user', '--prefix=', '--system']\n new_process = subprocess.Popen(\n cmd + uextention_text, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n new_process.communicate()\n if site.USER_BASE is None:\n raise Exception(\n 'No USER_BASE found for the user.'\n )\n _PATHS_TO_INSERT.append(os.path.join(site.USER_BASE, 'bin'))\n mypy_exec_path = os.path.join(site.USER_BASE, 'bin', 'mypy')\n return (new_process.returncode, mypy_exec_path)\n else:\n _PATHS_TO_INSERT.append(os.path.join(MYPY_TOOLS_DIR, 'bin'))\n mypy_exec_path = os.path.join(MYPY_TOOLS_DIR, 'bin', 'mypy')\n return (process.returncode, mypy_exec_path)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _run_action(cid, action, end, state):\n if action == 'use':\n if end == 'send':\n _channels.send(cid, b'spam', blocking=False)\n return state.incr()\n elif end == 'recv':\n if not state.pending:\n try:\n _channels.recv(cid)\n except _channels.ChannelEmptyError:\n return state\n else:\n raise Exception('expected ChannelEmptyError')\n else:\n recv_nowait(cid)\n return state.decr()\n else:\n raise ValueError(end)\n elif action == 'close':\n kwargs = {}\n if end in ('recv', 'send'):\n kwargs[end] = True\n _channels.close(cid, **kwargs)\n return state.close()\n elif action == 'force-close':\n kwargs = {\n 'force': True,\n }\n if end in ('recv', 'send'):\n kwargs[end] = True\n _channels.close(cid, **kwargs)\n return state.close(force=True)\n else:\n raise ValueError(action)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_blog_author_details(user_id: str) -> blog_domain.BlogAuthorDetails:\n \"\"\"Returns the blog author details for the given user id. If\n blogAuthorDetailsModel is not present, a new model with default values is\n created.\n\n Args:\n user_id: str. The user id of the blog author.\n\n Returns:\n BlogAuthorDetails. The blog author details for the given user ID.\n\n Raises:\n Exception. Unable to fetch blog author details for the given user ID.\n \"\"\"\n author_model = blog_models.BlogAuthorDetailsModel.get_by_author(user_id)\n\n if author_model is None:\n create_blog_author_details_model(user_id)\n author_model = blog_models.BlogAuthorDetailsModel.get_by_author(user_id)\n\n if author_model is None:\n raise Exception('Unable to fetch author details for the given user.')\n\n return blog_domain.BlogAuthorDetails(\n author_model.id,\n author_model.author_id,\n author_model.displayed_author_name,\n author_model.author_bio,\n author_model.last_updated\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@acl_decorators.can_access_learner_groups\n def get(self, username: str) -> None:\n \"\"\"Handles GET requests.\"\"\"\n assert self.normalized_request is not None\n story_ids = self.normalized_request['story_ids']\n user_id = user_services.get_user_id_from_username(username)\n if user_id is None:\n raise Exception(\n 'No learner user_id found for the given learner username: %s' %\n username\n )\n\n stories_chapters_progress = (\n story_fetchers.get_user_progress_in_story_chapters(\n user_id, story_ids))\n\n self.render_json(stories_chapters_progress)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _migrate_rubrics_to_latest_schema(\n versioned_rubrics: skill_domain.VersionedRubricDict\n) -> None:\n \"\"\"Holds the responsibility of performing a step-by-step, sequential update\n of the rubrics structure based on the schema version of the input\n rubrics dictionary. If the current rubrics schema changes, a\n new conversion function must be added and some code appended to this\n function to account for that new version.\n\n Args:\n versioned_rubrics: dict. A dict with two keys:\n - schema_version: int. The schema version for the rubrics dict.\n - rubrics: list(dict). The list of dicts comprising the skill\n rubrics.\n\n Raises:\n Exception. The schema version of rubrics is outside of what is supported\n at present.\n \"\"\"\n rubric_schema_version = versioned_rubrics['schema_version']\n if not (1 <= rubric_schema_version\n <= feconf.CURRENT_RUBRIC_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v1-v%d rubric schemas at '\n 'present.' % feconf.CURRENT_RUBRIC_SCHEMA_VERSION)\n\n while (rubric_schema_version <\n feconf.CURRENT_RUBRIC_SCHEMA_VERSION):\n skill_domain.Skill.update_rubrics_from_model(\n versioned_rubrics, rubric_schema_version)\n rubric_schema_version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, pkg_config_path, args):\n super(PkgConfigGTKDoc, self).__init__(args)\n\n pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')\n\n if not os.path.exists(pkg_config_path):\n raise Exception('Could not find pkg-config file at: %s'\n % pkg_config_path)\n\n self.cflags += \" \" + self._run_command([pkg_config,\n pkg_config_path,\n '--cflags'], print_output=False)\n self.ldflags += \" \" + self._run_command([pkg_config,\n pkg_config_path,\n '--libs'], print_output=False)\n self.version = self._run_command([pkg_config,\n pkg_config_path,\n '--modversion'], print_output=False)\n self.prefix = self._run_command([pkg_config,\n pkg_config_path,\n '--variable=prefix'], print_output=False)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_poppler", "language": "python"} {"function": "def func():\n try:\n try:\n raise Exception\n finally:\n y = \"Something\"\n except Exception:\n b = 23", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def _release_ownership_of_activity(\n committer: user_domain.UserActionsInfo,\n activity_id: str,\n activity_type: str\n) -> None:\n \"\"\"Releases ownership of the given activity to the community.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user who\n is performing the action.\n activity_id: str. ID of the activity.\n activity_type: str. The type of activity. Possible values:\n constants.ACTIVITY_TYPE_EXPLORATION,\n constants.ACTIVITY_TYPE_COLLECTION.\n\n Raises:\n Exception. The committer does not have release rights.\n Exception. The activity rights does not exist for the given activity_id.\n Exception. Guest user is not allowed to release ownership of activity.\n \"\"\"\n committer_id = committer.user_id\n if committer_id is None:\n raise Exception(\n 'Guest user is not allowed to release ownership of activity.'\n )\n activity_rights = _get_activity_rights(\n activity_type, activity_id, strict=True\n )\n\n if not check_can_release_ownership(committer, activity_rights):\n logging.error(\n 'User %s tried to release ownership of %s %s but was '\n 'refused permission.' % (committer_id, activity_type, activity_id))\n raise Exception(\n 'The ownership of this %s cannot be released.' % activity_type)\n\n activity_rights.community_owned = True\n activity_rights.owner_ids = []\n activity_rights.editor_ids = []\n activity_rights.viewer_ids = []\n activity_rights.voice_artist_ids = []\n commit_cmds = [{\n 'cmd': rights_domain.CMD_RELEASE_OWNERSHIP,\n }]\n\n _save_activity_rights(\n committer_id, activity_rights, activity_type,\n '%s ownership released to the community.' % activity_type, commit_cmds)\n _update_activity_summary(activity_type, activity_rights)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def verify_target_version_compatible_with_latest_release(\n target_version: str\n) -> None:\n \"\"\"Checks that the target version is consistent with the latest released\n version on GitHub.\n\n Args:\n target_version: str. The release version.\n\n Raises:\n Exception. Failed to fetch latest release info from GitHub.\n Exception. Could not parse version number of latest GitHub release.\n AssertionError. The previous and the current major version are not the\n same.\n AssertionError. The current patch version is not equal to previous patch\n version plus one.\n AssertionError. The current patch version is greater or equal to 10.\n AssertionError. The current minor version is not equal to previous\n minor version plus one.\n AssertionError. The current patch version is different than 0.\n \"\"\"\n response = utils.url_open(\n 'https://api.github.com/repos/oppia/oppia/releases/latest')\n if response.getcode() != 200:\n raise Exception(\n 'ERROR: Failed to fetch latest release info from GitHub.')\n\n data = json.load(response)\n latest_release_tag_name = data['tag_name']\n\n match_result = re.match(r'v(\\d)\\.(\\d)\\.(\\d)', latest_release_tag_name)\n if match_result is None:\n raise Exception(\n 'ERROR: Could not parse version number of latest GitHub release.')\n prev_major, prev_minor, prev_patch = match_result.group(1, 2, 3)\n\n match_result = re.match(r'(\\d)\\.(\\d)\\.(\\d)', target_version)\n if match_result is None:\n raise Exception(\n 'ERROR: Could not parse target version.'\n )\n curr_major, curr_minor, curr_patch = match_result.group(1, 2, 3)\n\n # This will need to be overridden if the major version changes.\n assert prev_major == curr_major, 'Unexpected major version change.'\n if prev_minor == curr_minor:\n assert int(curr_patch) == int(prev_patch) + 1, (\n 'The current patch version is not equal to previous patch '\n 'version plus one.')\n else:\n assert int(curr_minor) == int(prev_minor) + 1, (\n 'The current minor version is not equal to previous '\n 'minor version plus one.')\n assert int(curr_patch) == 0, (\n 'The current patch version is different than 0.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def setupSchemaPrisma(dbInfo):\n try:\n os.chdir(cwd+'/'+dbInfo['ProjectFolderName']+'/prisma')\n if (os.path.exists(os.getcwd()+\"/schema.prisma\") == True):\n f = open('schema.prisma', 'r')\n fileContent = f.read()\n f.close()\n updateContent = fileContent.replace(\n \"postgresql\", dbInfo['DatabaseProvider'])\n f = open('schema.prisma', 'w')\n f.write(updateContent)\n f.close()\n print(\"set up database provider\")\n except Exception as e:\n raise Exception('Unable to update Database Provider in schema.prisma')", "smellKey": "S112", "smellId": null, "repo": "REAN-Foundation_reancare-service", "language": "python"} {"function": "@pytest.fixture(scope=\"session\")\ndef regular_lonely_user(users):\n for user in users:\n if user[\"username\"] == \"lonely_user\":\n return user[\"username\"]\n raise Exception(\"Can't find the lonely user in the test DB\")", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def breakSpecialVarNameIntoBaseAndComponent(inSpecialVarName,\n inAddSeparatorFlag):\n\n twoDigitComponentFlag = False\n\n varNameLen = len(inSpecialVarName)\n if varNameLen < 2:\n errStr = ' in breakSpecialVarNameIntoBaseAndComponent representation bad color by vector component name (too short)\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n lastVarChar = inSpecialVarName[varNameLen - 1]\n if PhactoriDbg():\n myDebugPrint3(' lastVarChar: ' + str(lastVarChar) + '\\n')\n if lastVarChar == 'X' or lastVarChar == 'x':\n component = 0\n elif lastVarChar == 'Y' or lastVarChar == 'y':\n component = 1\n elif lastVarChar == 'Z' or lastVarChar == 'z':\n component = 2\n elif str(lastVarChar).isdigit():\n end2car = inSpecialVarName[varNameLen-2:varNameLen]\n if PhactoriDbg():\n myDebugPrint3(' end2car: ' + end2car + ' isdigit: ' + str(end2car.isdigit()) + '\\n')\n if end2car.isdigit():\n twoDigitComponentFlag = True\n component = int(end2car)\n else:\n component = int(str(lastVarChar))\n else:\n errStr = ' in breakSpecialVarNameIntoBaseAndComponent representation bad color by vector component name (does not end in X Y or Z or 1 or two character integer)\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n #baseVarName = inSpecialVarName[0:(varNameLen-2)] + GetSeparatorString()\n\n localinAddSeparatorFlag = inAddSeparatorFlag\n #for Sierra, as of 2022Aug09, we need inAddSeparatorFlag to default to\n #False but right here we need to strip the separator from the variable\n #base name\n #localinAddSeparatorFlag = True\n if localinAddSeparatorFlag:\n lenToGrab = varNameLen - 1 - len(GetSeparatorString())\n else:\n lenToGrab = varNameLen - 1\n if twoDigitComponentFlag:\n lenToGrab -= 1\n\n varNameWithoutSeparator = inSpecialVarName[0:lenToGrab]\n\n if inAddSeparatorFlag:\n baseVarName = varNameWithoutSeparator + GetSeparatorString()\n else:\n baseVarName = varNameWithoutSeparator\n\n return [baseVarName, component, varNameWithoutSeparator]", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _wait_until_task_is_created(username: str, rq_id: str) -> Dict[str, Any]:\n url = f\"requests/{rq_id}\"\n\n for _ in range(100):\n response = get_method(username, url)\n request_details = response.json()\n if request_details[\"status\"] in (\"finished\", \"failed\"):\n return request_details\n sleep(1)\n raise Exception(\"Cannot create task\")", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def create_messages(\n thread_ids: List[str],\n author_id: Optional[str],\n updated_status: Optional[str],\n updated_subject: Optional[str],\n text: str,\n received_via_email: bool = False,\n should_send_email: bool = True\n) -> List[feedback_domain.FeedbackMessage]:\n \"\"\"Creates a new message for each of the distinct threads in thread_ids and\n for each message, subscribes the author to the thread.\n\n Args:\n thread_ids: list(str). The thread ids to append the messages to.\n author_id: str|None. The id of the author who creates the messages, or\n None if the author is anonymous.\n updated_status: str|None. One of STATUS_CHOICES. Applied to each thread.\n Must be supplied if this is the first message of the threads.\n Otherwise, this property should only exist when the status\n changes.\n updated_subject: str|None. New thread subject. Applied to each thread.\n Must be supplied if this is the first message of the threads.\n Otherwise, this property should only exist when the subject changes.\n text: str. The text of the feedback message. This may be ''.\n received_via_email: bool. Whether the new message(s) are received via\n email or web.\n should_send_email: bool. Whether the new message(s) need to be added to\n the email buffer.\n\n Returns:\n list(FeedbackMessage). The domain objects representing the new messages\n added in the datastore.\n\n Raises:\n Exception. Thread_ids must be distinct.\n Exception. One or more GeneralFeedbackThreadModel entities not found.\n \"\"\"\n from core.domain import event_services\n\n # Check that the thread_ids are distinct.\n if len(set(thread_ids)) != len(thread_ids):\n raise Exception(\n 'Thread ids must be distinct when calling create_messsages.')\n\n # Get the threads at the outset, in order to check that there are models\n # corresponding to each of the thread_ids.\n thread_models_with_none = (\n feedback_models.GeneralFeedbackThreadModel.get_multi(\n thread_ids\n )\n )\n thread_models: List[feedback_models.GeneralFeedbackThreadModel] = []\n thread_ids_that_do_not_have_models = []\n for index, thread_model in enumerate(thread_models_with_none):\n if thread_model is None:\n thread_ids_that_do_not_have_models.append(thread_ids[index])\n else:\n thread_models.append(thread_model)\n if len(thread_ids_that_do_not_have_models) > 0:\n multiple_thread_models_are_missing = (\n len(thread_ids_that_do_not_have_models) > 1\n )\n raise Exception(\n 'Thread%s belonging to the GeneralFeedbackThreadModel class with '\n 'id%s:[%s] %s not found.' % (\n 's' if multiple_thread_models_are_missing else '',\n 's' if multiple_thread_models_are_missing else '',\n ' '.join(thread_ids_that_do_not_have_models),\n 'were' if multiple_thread_models_are_missing else 'was'\n )\n )\n\n # Get the corresponding message ids, which are required for message\n # creation.\n message_ids = (\n feedback_models.GeneralFeedbackMessageModel.get_message_counts(\n thread_ids)\n )\n\n # Create a list of FullyQualifiedMessageIdentifier objects so that each\n # (thread_id, message_id) pair is kept together.\n message_identifiers = []\n for thread_id, message_id in zip(thread_ids, message_ids):\n message_identifiers.append(\n feedback_domain.FullyQualifiedMessageIdentifier(\n thread_id, message_id))\n\n # Create the GeneralFeedbackMessageModel instances.\n message_models = feedback_models.GeneralFeedbackMessageModel.create_multi(\n message_identifiers)\n\n # Update the message instances.\n for index, message_model in enumerate(message_models):\n message_model.thread_id = thread_ids[index]\n message_model.message_id = message_ids[index]\n message_model.author_id = author_id\n message_model.text = text\n message_model.received_via_email = received_via_email\n # Get the corresponding thread in storage.\n thread_model = thread_models[index]\n if updated_status:\n message_model.updated_status = updated_status\n if message_model.message_id == 0:\n # New thread.\n if thread_model.entity_type == feconf.ENTITY_TYPE_EXPLORATION:\n event_services.FeedbackThreadCreatedEventHandler.record(\n thread_model.entity_id)\n else:\n # Thread status changed.\n if thread_model.entity_type == feconf.ENTITY_TYPE_EXPLORATION:\n (\n event_services\n .FeedbackThreadStatusChangedEventHandler\n .record(\n thread_model.entity_id, thread_model.status,\n updated_status)\n )\n if updated_subject:\n message_model.updated_subject = updated_subject\n feedback_models.GeneralFeedbackMessageModel.update_timestamps_multi(\n message_models)\n feedback_models.GeneralFeedbackMessageModel.put_multi(message_models)\n\n # Update the message data cache of the threads.\n for thread_model in thread_models:\n thread_model.message_count += 1\n if text:\n thread_model.last_nonempty_message_text = text\n thread_model.last_nonempty_message_author_id = author_id\n\n # We do a put() even if the status and subject are not updated, so that the\n # last_updated time of the threads reflects the last time a message was\n # added to it.\n old_statuses = [thread_model.status for thread_model in thread_models]\n new_statuses = old_statuses\n if updated_status or updated_subject:\n new_statuses = []\n for index, thread_model in enumerate(thread_models):\n # Can't be the first thread.\n if message_ids[index] != 0:\n if updated_status and (updated_status != thread_model.status):\n thread_model.status = updated_status\n if updated_subject and (\n updated_subject != thread_model.subject):\n thread_model.subject = updated_subject\n new_statuses.append(thread_model.status)\n feedback_models.GeneralFeedbackThreadModel.update_timestamps_multi(\n thread_models)\n feedback_models.GeneralFeedbackThreadModel.put_multi(thread_models)\n\n # For each thread, we do a put on the suggestion linked (if it exists) to\n # the thread, so that the last_updated time changes to show that there is\n # activity in the thread.\n thread_ids_that_have_linked_suggestions = []\n for thread_model in thread_models:\n if thread_model.has_suggestion:\n thread_ids_that_have_linked_suggestions.append(thread_model.id)\n general_suggestion_models = (\n suggestion_models.GeneralSuggestionModel.get_multi(\n thread_ids_that_have_linked_suggestions)\n )\n suggestion_models_to_update = []\n for suggestion_model in general_suggestion_models:\n # As the thread is created before the suggestion, for the first message\n # we need not update the suggestion.\n if suggestion_model:\n suggestion_models_to_update.append(suggestion_model)\n suggestion_models.GeneralSuggestionModel.update_timestamps_multi(\n suggestion_models_to_update)\n suggestion_models.GeneralSuggestionModel.put_multi(\n suggestion_models_to_update)\n\n server_can_send_emails = (\n platform_parameter_services.get_platform_parameter_value(\n platform_parameter_list.ParamName.SERVER_CAN_SEND_EMAILS.value\n )\n )\n # TODO(#12079): Figure out a better way to avoid sending feedback\n # thread emails for contributor dashboard suggestions.\n message_changed = (\n len(text) > 0 or old_statuses[index] != new_statuses[index]\n )\n if (\n server_can_send_emails and\n feconf.CAN_SEND_TRANSACTIONAL_EMAILS and\n author_id is not None and\n user_services.is_user_registered(author_id) and\n message_changed and\n should_send_email\n ):\n for index, thread_model in enumerate(thread_models):\n _add_message_to_email_buffer(\n author_id, thread_model.id, message_ids[index],\n len(text), old_statuses[index], new_statuses[index])\n\n if author_id:\n subscription_services.subscribe_to_threads(author_id, thread_ids)\n add_message_ids_to_read_by_list(author_id, message_identifiers)\n\n # Convert the GeneralFeedbackMessageModels into a list of FeedbackMessage\n # domain objects.\n feedback_messages = [\n _get_message_from_model(message_model) for message_model in\n message_models\n ]\n\n return feedback_messages", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _configure(self):\n autogen = os.path.join(self._srcdir, 'autogen.sh')\n cmd = [autogen, '--prefix=%s' % (self._prefix), '--enable-utils']\n\n # Disable frontends and tests\n cmd.extend(['--disable-poppler-glib',\n '--disable-poppler-qt4',\n '--disable-poppler-cpp',\n '--disable-gtk-test'])\n\n backends = self.config.backends\n if backends:\n # Disable backends. Text and ps can't be disabled.\n if 'cairo' not in backends:\n cmd.append('--disable-cairo-output')\n if 'splash' not in backends:\n cmd.append('--disable-splash-output')\n else:\n cmd.extend(['--enable-cairo-output',\n '--enable-splash-output'])\n\n p = subprocess.Popen(cmd, cwd=self._srcdir)\n status = p.wait()\n if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:\n raise Exception('Command %s returned non-zero exit status %d' % (str(cmd), status))", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_poppler", "language": "python"} {"function": "@classmethod\n def instance(cls, target_names=None, target_config_dir=None):\n \"\"\"Get the singleton instance of System\n\n Args:\n target_names [Array of target_names]\n target_config_dir Directory where target config folders are\n\n Returns:\n [System] The System singleton\n \"\"\"\n if System.instance_obj:\n return System.instance_obj\n if not target_names and not target_config_dir:\n raise Exception(\"System.instance parameters are required on first call\")\n\n with System.instance_mutex:\n System.instance_obj = cls(target_names, target_config_dir)\n return System.instance_obj", "smellKey": "S112", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def get(self, name):\n v = self._values.get(name, None)\n if name in self._values:\n return v\n if name == ENV_NM_TEST_CLIENT_BUILDDIR:\n v = os.environ.get(\n ENV_NM_TEST_CLIENT_BUILDDIR, PathConfiguration.top_srcdir()\n )\n if not os.path.isdir(v):\n raise Exception(\"Missing builddir. Set NM_TEST_CLIENT_BUILDDIR?\")\n elif name == ENV_NM_TEST_CLIENT_NMCLI_PATH:\n v = os.environ.get(ENV_NM_TEST_CLIENT_NMCLI_PATH, None)\n if v is None:\n try:\n v = os.path.abspath(\n self.get(ENV_NM_TEST_CLIENT_BUILDDIR) + \"/src/nmcli/nmcli\"\n )\n except:\n pass\n if not os.path.exists(v):\n raise Exception(\"Missing nmcli binary. Set NM_TEST_CLIENT_NMCLI_PATH?\")\n elif name == ENV_NM_TEST_CLIENT_CLOUD_SETUP_PATH:\n v = os.environ.get(ENV_NM_TEST_CLIENT_CLOUD_SETUP_PATH, None)\n if v is None:\n try:\n v = os.path.abspath(\n self.get(ENV_NM_TEST_CLIENT_BUILDDIR)\n + \"/src/nm-cloud-setup/nm-cloud-setup\"\n )\n except:\n pass\n if not os.path.exists(v):\n raise Exception(\n \"Missing nm-cloud-setup binary. Set NM_TEST_CLIENT_CLOUD_SETUP_PATH?\"\n )\n elif name == ENV_NM_TEST_CLIENT_CHECK_L10N:\n # if we test locales other than 'C', the output of nmcli depends on whether\n # nmcli can load the translations. Unfortunately, I cannot find a way to\n # make gettext use the po/*.gmo files from the build-dir.\n #\n # hence, such tests only work, if you also issue `make-install`\n #\n # Only by setting NM_TEST_CLIENT_CHECK_L10N=1, these tests are included\n # as well.\n v = Util.is_bool(os.environ.get(ENV_NM_TEST_CLIENT_CHECK_L10N, None))\n elif name == ENV_NM_TEST_REGENERATE:\n # in the \"regenerate\" mode, the tests will rewrite the files on disk against\n # which we assert. That is useful, if there are intentional changes and\n # we want to regenerate the expected output.\n v = Util.is_bool(os.environ.get(ENV_NM_TEST_REGENERATE, None))\n elif name == ENV_NM_TEST_WITH_LINENO:\n v = Util.is_bool(os.environ.get(ENV_NM_TEST_WITH_LINENO, None))\n elif name == ENV_NM_TEST_VALGRIND:\n if self.get(ENV_NM_TEST_REGENERATE):\n v = False\n else:\n v = os.environ.get(ENV_NM_TEST_VALGRIND, None)\n if v:\n v = Util.is_bool(v)\n else:\n v = Util.is_bool(os.environ.get(\"NMTST_USE_VALGRIND\", None))\n elif name in [\n ENV_NM_TEST_ASAN_OPTIONS,\n ENV_NM_TEST_LSAN_OPTIONS,\n ENV_NM_TEST_UBSAN_OPTIONS,\n ]:\n v = os.environ.get(name, None)\n if v is None:\n if name == ENV_NM_TEST_ASAN_OPTIONS:\n v = \"detect_leaks=1\"\n # v += ' fast_unwind_on_malloc=false'\n elif name == ENV_NM_TEST_LSAN_OPTIONS:\n v = \"\"\n elif name == ENV_NM_TEST_UBSAN_OPTIONS:\n v = \"print_stacktrace=1:halt_on_error=1\"\n else:\n assert False\n elif name == ENV_LIBTOOL:\n v = os.environ.get(name, None)\n if v is None:\n v = os.path.abspath(\n os.path.dirname(self.get(ENV_NM_TEST_CLIENT_NMCLI_PATH))\n + \"/../../libtool\"\n )\n if not os.path.isfile(v):\n v = None\n else:\n v = [v]\n elif not v:\n v = None\n else:\n v = shlex.split(v)\n else:\n raise Exception()\n self._values[name] = v\n return v", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "def _parse_unit(self, token_list: List[Token]) -> Node:\n \"\"\"Function representing the following production rule of the grammar:\n <unit> ::= <identifier> | <number> | '(' <expr> ')' |\n <function> '(' <expr> ')'\n\n Args:\n token_list: list(Token). A list containing token objects formed from\n the given math expression.\n\n Returns:\n Node. Root node of the generated parse tree.\n\n Raises:\n Exception. Invalid token.\n \"\"\"\n token = self._get_next_token(token_list)\n if token.category == _TOKEN_CATEGORY_IDENTIFIER:\n return IdentifierNode(token)\n\n if token.category == _TOKEN_CATEGORY_FUNCTION:\n if self._get_next_token_if_text_in(['('], token_list):\n parsed_child = self._parse_expr(token_list)\n next_token = self._get_next_token_if_text_in([')'], token_list)\n # Here, we are asserting that next_token is never going to be\n # None, because before reaching this line of code we are already\n # checking if token exists or not with method `_get_next_token`.\n assert next_token is not None\n return UnaryFunctionNode(next_token, parsed_child)\n\n if token.category == _TOKEN_CATEGORY_NUMBER:\n return NumberNode(token)\n\n if token.text == '(':\n parsed_expr = self._parse_expr(token_list)\n next_token = self._get_next_token_if_text_in([')'], token_list)\n return parsed_expr\n\n raise Exception('Invalid token: %s.' % token.text)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def assign_role(\n committer: user_domain.UserActionsInfo,\n assignee: user_domain.UserActionsInfo,\n new_role: str,\n topic_id: str\n) -> None:\n \"\"\"Assigns a new role to the user.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user\n who is performing the action.\n assignee: UserActionsInfo. UserActionsInfo object for the user\n whose role is being changed.\n new_role: str. The name of the new role. Possible values are:\n ROLE_MANAGER.\n topic_id: str. ID of the topic.\n\n Raises:\n Exception. The committer does not have rights to modify a role.\n Exception. The assignee is already a manager for the topic.\n Exception. The assignee doesn't have enough rights to become a manager.\n Exception. The role is invalid.\n Exception. Guest user is not allowed to assign roles to a user.\n Exception. The role of the Guest user cannot be changed.\n \"\"\"\n committer_id = committer.user_id\n if committer_id is None:\n raise Exception(\n 'Guest user is not allowed to assign roles to a user.'\n )\n topic_rights = topic_fetchers.get_topic_rights(topic_id)\n if (role_services.ACTION_MODIFY_CORE_ROLES_FOR_ANY_ACTIVITY not in\n committer.actions):\n logging.error(\n 'User %s tried to allow user %s to be a %s of topic %s '\n 'but was refused permission.' % (\n committer_id, assignee.user_id, new_role, topic_id))\n raise Exception(\n 'UnauthorizedUserException: Could not assign new role.')\n\n if assignee.user_id is None:\n raise Exception(\n 'Cannot change the role of the Guest user.'\n )\n assignee_username = user_services.get_username(assignee.user_id)\n if role_services.ACTION_EDIT_OWNED_TOPIC not in assignee.actions:\n raise Exception(\n 'The assignee doesn\\'t have enough rights to become a manager.')\n\n old_role = topic_domain.ROLE_NONE\n if topic_rights.is_manager(assignee.user_id):\n old_role = topic_domain.ROLE_MANAGER\n\n if new_role == topic_domain.ROLE_MANAGER:\n if topic_rights.is_manager(assignee.user_id):\n raise Exception('This user already is a manager for this topic')\n topic_rights.manager_ids.append(assignee.user_id)\n elif new_role == topic_domain.ROLE_NONE:\n if topic_rights.is_manager(assignee.user_id):\n topic_rights.manager_ids.remove(assignee.user_id)\n else:\n old_role = topic_domain.ROLE_NONE\n else:\n raise Exception('Invalid role: %s' % new_role)\n\n commit_message = rights_domain.ASSIGN_ROLE_COMMIT_MESSAGE_TEMPLATE % (\n assignee_username, old_role, new_role)\n commit_cmds = [topic_domain.TopicRightsChange({\n 'cmd': topic_domain.CMD_CHANGE_ROLE,\n 'assignee_id': assignee.user_id,\n 'old_role': old_role,\n 'new_role': new_role\n })]\n\n save_topic_rights(topic_rights, committer_id, commit_message, commit_cmds)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def cdBoot(vm, vmPath):\n isoMountPath = None\n try:\n cdrom = None\n for disk in vm.disks:\n if disk.isIso == True:\n cdrom = disk\n break\n if not cdrom: raise Exception(\"Cannot find Iso in disks\")\n\n isoOnSecStorage = dirname(cdrom.path)\n isoName = basename(cdrom.path)\n isoMountPath = OvmVm()._getIsoMountPath(vmPath)\n OvmStoragePool()._mount(isoOnSecStorage, isoMountPath)\n isoPath = join(isoMountPath, isoName)\n if not exists(isoPath):\n raise Exception(\"Cannot found iso %s at %s which mounts to %s\"%(isoName, isoOnSecStorage, isoMountPath))\n\n stdout = run_cmd(args=['file', isoPath])\n if not stdout.strip().endswith(\"(bootable)\"): raise Exception(\"ISO %s is not bootable\"%cdrom.path)\n\n #now alter cdrom to correct path\n cdrom.path = isoPath\n if len(vm.vifs) != 0:\n vif = vm.vifs[0]\n #ISO boot must be HVM\n vifCfg = ','.join([vif.mac, vif.bridge, 'ioemu'])\n else:\n vifCfg = ''\n\n rootDiskSize = os.path.getsize(vm.rootDisk.path)\n rooDiskCfg = ':'.join([join(vmPath, basename(vm.rootDisk.path)), str(BytesToG(rootDiskSize)), 'True'])\n disks = [rooDiskCfg]\n for d in vm.disks:\n if d.isIso: continue\n size = os.path.getsize(d.path)\n cfg = ':'.join([d.path, str(BytesToG(size)), 'True'])\n disks.append(cfg)\n disksCfg = ','.join(disks)\n server = successToMap(get_master_ip())['ip']\n\n raiseExceptionIfFail(install_vm_hvm(vmPath, BytesToM(vm.memory), vm.cpuNum, vifCfg, disksCfg, cdrom.path, vncpassword='', dedicated_server=server))\n rs = SUCC()\n return rs\n except Exception, e:\n if isoMountPath and OvmStoragePool()._isMounted(isoMountPath):\n doCmd(['umount', '-f', isoMountPath])\n errmsg = fmt_err_msg(e)\n raise Exception(errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "@cli.command()\n@click.pass_context\ndef unity(ctx):\n \"\"\" build just dynamic libs for use in unity project \"\"\"\n ctx.invoke(libs, clean=False, static=False, shared=True, skip_formatter=True, just_release=True)\n BUILDS = []\n\n click.echo('--- Copying libs and header into unity example')\n UNITY_PROJECT_PATH = os.path.join(SCRIPT_PATH, 'examples', 'button-clicker', 'Assets', 'Plugins')\n\n if sys.platform.startswith('win'):\n LIBRARY_NAME = 'discord-rpc.dll'\n BUILD_64_BASE_PATH = os.path.join(SCRIPT_PATH, 'builds', 'win64-dynamic', 'src', 'Release')\n UNITY_64_DLL_PATH = os.path.join(UNITY_PROJECT_PATH, 'x86_64')\n BUILDS.append({BUILD_64_BASE_PATH: UNITY_64_DLL_PATH})\n\n BUILD_32_BASE_PATH = os.path.join(SCRIPT_PATH, 'builds', 'win32-dynamic', 'src', 'Release')\n UNITY_32_DLL_PATH = os.path.join(UNITY_PROJECT_PATH, 'x86')\n BUILDS.append({BUILD_32_BASE_PATH: UNITY_32_DLL_PATH})\n\n elif sys.platform == 'darwin':\n LIBRARY_NAME = 'discord-rpc.bundle'\n BUILD_BASE_PATH = os.path.join(SCRIPT_PATH, 'builds', 'osx-dynamic', 'src')\n UNITY_DLL_PATH = UNITY_PROJECT_PATH\n os.rename(\n os.path.join(BUILD_BASE_PATH, 'libdiscord-rpc.dylib'), os.path.join(BUILD_BASE_PATH, 'discord-rpc.bundle'))\n\n BUILDS.append({BUILD_BASE_PATH: UNITY_DLL_PATH})\n\n elif sys.platform.startswith('linux'):\n LIBRARY_NAME = 'discord-rpc.so'\n BUILD_BASE_PATH = os.path.join(SCRIPT_PATH, 'builds', 'linux-dynamic', 'src')\n UNITY_DLL_PATH = os.path.join(UNITY_PROJECT_PATH, 'x86')\n os.rename(os.path.join(BUILD_BASE_PATH, 'libdiscord-rpc.so'), os.path.join(BUILD_BASE_PATH, 'discord-rpc.so'))\n\n BUILDS.append({BUILD_BASE_PATH: UNITY_DLL_PATH})\n\n else:\n raise Exception('Unsupported platform ' + sys.platform)\n\n for build in BUILDS:\n for i in build:\n mkdir_p(build[i])\n shutil.copy(os.path.join(i, LIBRARY_NAME), build[i])", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_dolphin", "language": "python"} {"function": "def copyToPrimary(secMountPoint, volumeFolderOnSecStorage, volumePath, primaryMountPath):\n srcPath = join(secMountPoint, volumeFolderOnSecStorage.lstrip(\"/\"), volumePath.lstrip(\"/\"))\n if not srcPath.endswith(\".raw\"): srcPath = srcPath + \".raw\"\n if not isfile(srcPath): raise Exception(\"Cannot find volume at %s\"%srcPath)\n if not exists(primaryMountPath): raise Exception(\"Primary storage(%s) seems to have gone\"%primaryMountPath)\n OvmStoragePool()._checkDirSizeForImage(primaryMountPath, srcPath)\n destPath = join(primaryMountPath, \"sharedDisk\")\n newName = get_uuid() + \".raw\"\n destName = join(destPath, newName)\n doCmd(['cp', srcPath, destName])\n return destName", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def get_node_index_by_story_id_and_node_id(\n story_id: str, node_id: str\n) -> int:\n \"\"\"Returns the index of the story node with the given story id\n and node id.\n\n Args:\n story_id: str. ID of the story.\n node_id: str. ID of the story node.\n\n Returns:\n int. The index of the corresponding node.\n\n Raises:\n Exception. The given story does not exist.\n \"\"\"\n story = get_story_by_id(story_id, strict=False)\n if story is None:\n raise Exception('Story with id %s does not exist.' % story_id)\n\n node_index = story.story_contents.get_node_index(node_id)\n return node_index", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def is_story_published_and_present_in_topic(story: story_domain.Story) -> bool:\n \"\"\"Returns whether a story is published. Raises an exception if the story\n is not present in the corresponding topic's story references.\n\n Args:\n story: Story. The story domain object.\n\n Returns:\n bool. Whether the supplied story is published.\n\n Raises:\n ValidationError. The story does not belong to any valid topic.\n Exception. The story does not belong to the expected topic.\n \"\"\"\n topic = topic_fetchers.get_topic_by_id(\n story.corresponding_topic_id, strict=False)\n if topic is None:\n raise utils.ValidationError(\n 'Expected story to only belong to a valid topic, but found no '\n 'topic with ID: %s' % story.corresponding_topic_id)\n\n story_is_published = False\n story_is_present_in_topic = False\n for story_reference in topic.get_all_story_references():\n if story_reference.story_id == story.id:\n story_is_present_in_topic = True\n story_is_published = story_reference.story_is_published\n\n if not story_is_present_in_topic:\n raise Exception(\n 'Expected story to belong to the topic %s, but it is '\n 'neither a part of the canonical stories or the additional '\n 'stories of the topic.' % story.corresponding_topic_id)\n\n return story_is_published", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def close(self):\n if self.__device is None:\n raise Exception(\"device not turned on\")\n ret = self._driver.SDF_CloseDevice(self.__device)\n if ret != 0:\n raise Exception(\"turn off device failed\")\n self.__device = None", "smellKey": "S112", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def save_new_exploration_from_yaml_and_assets(\n committer_id: str,\n yaml_content: str,\n exploration_id: str,\n assets_list: List[Tuple[str, bytes]],\n strip_voiceovers: bool = False\n) -> None:\n \"\"\"Saves a new exploration given its representation in YAML form and the\n list of assets associated with it.\n\n Args:\n committer_id: str. The id of the user who made the commit.\n yaml_content: str. The YAML representation of the exploration.\n exploration_id: str. The id of the exploration.\n assets_list: list(tuple(str, bytes)). A list of lists of assets, which\n contains asset's filename and content.\n strip_voiceovers: bool. Whether to strip away all audio voiceovers\n from the imported exploration.\n\n Raises:\n Exception. The yaml file is invalid due to a missing schema version.\n \"\"\"\n yaml_dict = utils.dict_from_yaml(yaml_content)\n if 'schema_version' not in yaml_dict:\n raise Exception('Invalid YAML file: missing schema version')\n\n # The assets are committed before the exploration is created because the\n # migrating to state schema version 25 involves adding dimensions to\n # images. So we need to have images in the datastore before we could\n # perform the migration.\n for (asset_filename, asset_content) in assets_list:\n fs = fs_services.GcsFileSystem(\n feconf.ENTITY_TYPE_EXPLORATION, exploration_id)\n fs.commit(asset_filename, asset_content)\n\n exploration = exp_domain.Exploration.from_yaml(exploration_id, yaml_content)\n\n # Check whether audio translations should be stripped.\n if strip_voiceovers:\n for state in exploration.states.values():\n state.recorded_voiceovers.strip_all_existing_voiceovers()\n\n create_commit_message = (\n 'New exploration created from YAML file with title \\'%s\\'.'\n % exploration.title)\n\n _create_exploration(\n committer_id, exploration, create_commit_message, [\n exp_domain.CreateNewExplorationCmd({\n 'cmd': exp_domain.CMD_CREATE_NEW,\n 'title': exploration.title,\n 'category': exploration.category,\n })])", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def raising_test(self):\n self._pre_setup.assert_called_once_with()\n raise Exception(\"debug() bubbles up exceptions before cleanup.\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_contributor_usernames(\n category: str, language_code: Optional[str] = None\n) -> Sequence[str]:\n \"\"\"Returns a list of usernames of users who has contribution rights of given\n category.\n\n Args:\n category: str. The review category to find the list of reviewers\n for.\n language_code: None|str. The language code for translation or voiceover\n review category.\n\n Returns:\n Sequence(str). A list of usernames.\n\n Raises:\n Exception. The language code is not of None for question review\n contribution.\n Exception. Invalid category.\n Exception. The language_code cannot be None if review category is\n 'translation' or 'voiceover'.\n \"\"\"\n user_ids = []\n if (\n category in (\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION,\n ) and language_code is None\n ):\n raise Exception(\n 'The language_code cannot be None if review category is'\n ' \\'translation\\' or \\'voiceover\\'.'\n )\n if category == constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION:\n # Ruling out the possibility of None for mypy type checking.\n assert language_code is not None\n user_ids = (\n user_models.UserContributionRightsModel\n .get_translation_reviewer_user_ids(language_code))\n elif category == constants.CD_USER_RIGHTS_CATEGORY_REVIEW_QUESTION:\n if language_code is not None:\n raise Exception('Expected language_code to be None, found: %s' % (\n language_code))\n user_ids = (\n user_models.UserContributionRightsModel\n .get_question_reviewer_user_ids())\n elif category == constants.CD_USER_RIGHTS_CATEGORY_SUBMIT_QUESTION:\n user_ids = (\n user_models.UserContributionRightsModel\n .get_question_submitter_user_ids())\n else:\n raise Exception('Invalid category: %s' % category)\n\n usernames = get_usernames(user_ids, strict=True)\n return usernames", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _parse_headers(self):\n header = os.path.join(os.path.dirname(__file__), \"batch_input.h\")\n df = io.open(header, \"w\", newline=\"\\n\")\n for h in self.headers:\n df.write(unicode(\"#include \\\"%s\\\"\\n\" % (os.path.relpath(h, os.path.dirname(header)))))\n # logger.info(\"write header %s\", h)\n df.close()\n logger.info(\">>> parse_header: \" + str(len(self.headers)))\n if not os.path.exists(header):\n logger.error(\"[error] header %s not found\" % header)\n # logger.info(\">>> arguments %s\" % self.clang_args)\n tu = self.index.parse(header, self.clang_args)\n if len(tu.diagnostics) > 0:\n self._pretty_print(tu.diagnostics)\n is_fatal = False\n for d in tu.diagnostics:\n if d.severity >= cindex.Diagnostic.Error:\n is_fatal = True\n if is_fatal:\n logger.error(\"*** Found errors - can not continue\")\n raise Exception(\"Fatal error in parsing headers\")\n self._deep_iterate(tu.cursor, 0, [])", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "def main() -> None:\n \"\"\"Checks that the CI config files and the test files have \n the same test suites.\n \"\"\"\n\n print(\n 'Checking all acceptance test suites are captured in CI '\n 'config files...'\n )\n acceptance_test_suites_from_config = (\n get_acceptance_test_suites_from_ci_config_file())\n acceptance_test_suites_from_directory = (\n get_acceptance_test_suites_from_acceptance_directory())\n acceptance_test_suites_difference = compute_test_suites_difference(\n acceptance_test_suites_from_config,\n acceptance_test_suites_from_directory\n )\n\n if len(acceptance_test_suites_difference) > 0:\n raise Exception(\n 'Acceptance test suites and CI test suites are not in sync. '\n 'The following suites are not in sync: %s. Please update the '\n 'CI config file for acceptance tests at core/tests/ci-test-'\n 'suite-configs/acceptance.json with the suites listed above.'\n % (json.dumps(acceptance_test_suites_difference))\n )\n print('Done!')\n\n print('Checking all e2e test modules are captured in wdio.conf.js...')\n webdriverio_test_suite_modules = (\n get_e2e_test_modules_from_webdriverio_directory())\n webdriverio_conf_test_modules = (\n get_e2e_test_modules_from_webdriverio_config_file())\n\n if not (\n sorted(\n webdriverio_test_suite_modules\n ) == sorted(webdriverio_conf_test_modules)\n ):\n raise Exception(\n 'One or more test module from webdriverio or webdriverio_desktop '\n 'directory is missing from wdio.conf.js. Please update wdio.conf.js'\n ' with the missing test modules.'\n )\n print('Done!')\n\n print('Checking all e2e test suites are captured in CI config files...')\n e2e_test_suites_from_config = (\n get_e2e_test_suites_from_ci_config_file())\n e2e_test_suites_from_directory = (\n get_e2e_test_suites_from_webdriverio_config_file())\n e2e_test_suites_difference = compute_test_suites_difference(\n e2e_test_suites_from_config, e2e_test_suites_from_directory)\n\n if len(e2e_test_suites_difference) > 0:\n raise Exception(\n 'E2E test suites and CI test suites are not in sync. The following '\n 'suites are not in sync: %s. Please update the CI config file for '\n 'e2e tests at core/tests/ci-test-suite-configs/e2e.json with the '\n 'suites listed above.' % (\n json.dumps(e2e_test_suites_difference))\n )\n print('Done!')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _convert_attrs(self, label: CommonData.Label, cvat_attrs: CommonData.Attribute):\n cvat_attrs = {a.name: a.value for a in cvat_attrs}\n\n dm_attr = dict()\n for _, a_desc in self.label_attrs[label]:\n a_name = a_desc['name']\n\n a_value = cvat_attrs.get(a_name, a_desc['default_value'])\n try:\n if a_desc['input_type'] == AttributeType.NUMBER:\n a_value = float(a_value)\n elif a_desc['input_type'] == AttributeType.CHECKBOX:\n a_value = (a_value.lower() == 'true')\n dm_attr[a_name] = a_value\n except Exception as e:\n raise Exception(\n \"Failed to convert attribute '%s'='%s': %s\" %\n (a_name, a_value, e))\n\n return dm_attr", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def update_question_skill_link_difficulty(\n question_id: str,\n skill_id: str,\n new_difficulty: float\n) -> None:\n \"\"\"Updates the difficulty value of question skill link.\n\n Args:\n question_id: str. ID of the question.\n skill_id: str. ID of the skill.\n new_difficulty: float. New difficulty value.\n\n Raises:\n Exception. Given question and skill are not linked.\n \"\"\"\n question_skill_link_id = (\n question_models.QuestionSkillLinkModel.get_model_id(\n question_id, skill_id))\n question_skill_link_model = question_models.QuestionSkillLinkModel.get(\n question_skill_link_id, strict=False)\n\n if question_skill_link_model is None:\n raise Exception('The given question and skill are not linked.')\n question_skill_link_model.skill_difficulty = new_difficulty\n question_skill_link_model.update_timestamps()\n question_skill_link_model.put()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@column_condition_partial(engine=PandasExecutionEngine)\n def _pandas(cls, column, **kwargs):\n column_shape_format = kwargs.get(\"column_shape_format\")\n place = kwargs.get(\"place\")\n geocoder = kwargs.get(\"geocoder\")\n geocoder_config = kwargs.get(\"geocoder_config\")\n\n if geocoder not in [\"nominatim\", \"pickpoint\", \"openmapquest\"]:\n raise NotImplementedError(\"The geocoder is not implemented for this method.\")\n\n # find the reference shape with the geocoder.\n if geocoder is not None:\n try:\n # Specify the default parameters for Nominatim and run query. User is responsible for config and query params otherwise.\n query_params = dict(exactly_one=True, geometry=\"wkt\")\n location = cls.geocode(geocoder, geocoder_config, place, query_params)\n except Exception:\n raise Exception( # noqa: TRY002, TRY003\n \"Geocoding configuration and query failed to produce a valid result.\"\n )\n else:\n raise Exception( # noqa: TRY002, TRY003\n \"A valid geocoder must be provided for this method. See GeoPy for reference.\"\n )\n\n # This method only works with the default Nominatim params and wkt.\n # TODO: Other geocoders and methods need to be implemented.\n # TODO: Add a conversion from lat-long to a CRS. (geopandas)\n if location is not None:\n shape_ref = geos.from_wkt(location.raw.get(\"geotext\"))\n else:\n raise Exception(\"Geocoding failed to return a result.\") # noqa: TRY002, TRY003\n\n # Load the column into a pygeos Geometry vector from numpy array (Series not supported).\n if column_shape_format == \"wkt\":\n shape_test = geos.from_wkt(column.to_numpy(), on_invalid=\"ignore\")\n elif column_shape_format == \"wkb\":\n shape_test = geos.from_wkb(column.to_numpy(), on_invalid=\"ignore\")\n else:\n raise NotImplementedError(\"Column values shape format not implemented.\")\n\n # Prepare the geometries\n geos.prepare(shape_ref)\n geos.prepare(shape_test)\n\n # Return whether the distance is below the tolerance.\n return pd.Series(geos.contains(shape_ref, shape_test))", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def check_execute():\n group = api.groups().create(body={\"group\": {\"name\": \"test-17004-project\", \"group_class\": \"project\"}}, ensure_unique_name=True).execute()\n try:\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n if len(contents[\"items\"]) != 0:\n raise Exception(\"Expected 0 items\")\n\n cmd = [\"arvados-cwl-runner\", \"--project-uuid\", group[\"uuid\"], \"17004-output-props.cwl\", \"--inp\", \"scripts/download_all_data.sh\"]\n print(\" \".join(cmd))\n subprocess.check_output(cmd)\n\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n\n found = False\n for c in contents[\"items\"]:\n if (c[\"kind\"] == \"arvados#collection\" and\n c[\"properties\"].get(\"type\") == \"output\" and\n c[\"properties\"].get(\"foo\") == \"bar\" and\n c[\"properties\"].get(\"baz\") == \"download_all_data.sh\"):\n found = True\n if not found:\n raise Exception(\"Didn't find collection with properties\")\n\n finally:\n api.groups().delete(uuid=group[\"uuid\"]).execute()", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def __init__(self, name):\n \"\"\"Initialize the DensityMechanism.\n\n Takes the name of a range mechanism; call via e.g. neuron.DensityMechanism('hh')\n \"\"\"\n self.__name = name\n self.__mt = h.MechanismType(0)\n self.__mt.select(-1)\n self.__mt.select(name)\n if self.__mt.selected() == -1:\n raise Exception(\"No DensityMechanism: \" + name)\n self.__has_nmodl = False\n self.__ast = None\n self.__ions = None\n try:\n import nmodl\n\n self.__has_nmodl = True\n except ModuleNotFoundError:\n pass", "smellKey": "S112", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def form_valid(self, form):\n from .type import WeniChatsType\n\n sector_uuid = form.cleaned_data[\"sector_uuid\"]\n\n project_auth = form.cleaned_data[\"project_auth\"]\n\n sectors_response = requests.get(\n url=WeniChatsType.base_url + \"/sectors/\",\n headers={\"Authorization\": \"Bearer \" + project_auth},\n )\n\n if sectors_response.status_code != 200:\n raise Exception(\n _(\n \"This ticketer integration with Weni Chats couldn't be created, check if all fields is correct and try again.\"\n )\n )\n\n current_sector = {}\n\n for sector in sectors_response.json()[\"results\"]:\n if sector[\"uuid\"] == sector_uuid:\n current_sector = sector\n\n if not current_sector:\n raise Exception(\n _(\"This ticketer integration with Weni Chats couldn't be created, the defined sector not exists.\")\n )\n\n config = {\n WeniChatsType.CONFIG_SECTOR_UUID: sector_uuid,\n WeniChatsType.CONFIG_PROJECT_AUTH: project_auth,\n }\n\n self.object = Ticketer(\n uuid=uuid4(),\n org=self.org,\n ticketer_type=WeniChatsType.slug,\n config=config,\n name=current_sector[\"name\"],\n created_by=self.request.user,\n modified_by=self.request.user,\n )\n\n self.object.save()\n return super().form_valid(form)", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "@classmethod\n def get_new_id(cls, entity_name: str) -> str:\n \"\"\"Gets a new id for an entity, based on its name.\n\n The returned id is guaranteed to be unique among all instances of this\n entity.\n\n Args:\n entity_name: The name of the entity. Coerced to a utf-8 encoded\n string.\n\n Returns:\n str. New unique id for this entity class.\n\n Raises:\n Exception. An ID cannot be generated within a reasonable number\n of attempts.\n \"\"\"\n for _ in range(MAX_RETRIES):\n new_id = utils.convert_to_hash(\n '%s%s' % (entity_name, utils.get_random_int(RAND_RANGE)),\n ID_LENGTH\n )\n if not cls.get_by_id(new_id):\n return new_id\n\n raise Exception('New id generator is producing too many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _send_headers(self, error=0, init_compressed_stream=1):\n log_debug(4, \"is_closed\", self._is_closed)\n if self._is_closed:\n # pylint: disable-next=broad-exception-raised\n raise Exception(\"Trying to write to a closed connection\")\n if self._headers_sent:\n return\n self._headers_sent = 1\n if self.compress_level:\n self.headers_out[\"Content-Encoding\"] = \"gzip\"\n # Send the headers\n if error:\n # No compression\n self.compress_level = 0\n self._raw_stream.content_type = \"text/xml\"\n for h, v in list(self.headers_out.items()):\n self._raw_stream.headers_out[h] = str(v)\n self._raw_stream.send_http_header()\n # If need be, start gzipping\n if self.compress_level and init_compressed_stream:\n # pylint: disable-next=consider-using-f-string\n log_debug(4, \"Compressing with factor %s\" % self.compress_level)\n self._compressed_stream = gzip.GzipFile(\n None, \"wb\", self.compress_level, self._raw_stream\n )", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def import_ps_metadata_files_skeleton(bfdataset, metadata_files):\n\n if not os.path.exists(path):\n os.makedirs(path)\n \n try: \n selected_dataset_id = get_dataset_id(bfdataset)\n except Exception as e:\n raise Exception(\"Please select a valid Pennsieve dataset.\") from e\n\n\n r = requests.get(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}\", headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n\n dataset = r.json()\n\n for child in dataset[\"children\"]:\n if child[\"content\"][\"packageType\"] != \"Collection\" and child[\"content\"][\"name\"] in METADATA_FILES:\n item_id = child[\"content\"][\"id\"]\n if child[\"content\"][\"name\"] in [\"README.txt\", \"CHANGES.txt\"]:\n # make a request to the zipit service directly\n url = returnFileURL(get_access_token(), item_id)\n r = requests.get(url)\n metadata_files[child[\"content\"][\"name\"]] = r.text\n else:\n dataframe = load_metadata_to_dataframe(item_id, \"xlsx\", get_access_token())\n metadata_json = dataframe.to_json()\n metadata_files[child[\"content\"][\"name\"]] = metadata_json\n\n # write the content name to a text file\n with open(os.path.join(path, \"metadata_files.txt\"), \"a\") as f:\n f.write(child[\"content\"][\"name\"] )\n\n return metadata_files", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def calculate_from_state_answers_dict(\n self, state_answers_dict: stats_domain.StateAnswersDict\n ) -> stats_domain.StateAnswersCalcOutput:\n \"\"\"Computes the number of occurrences of each answer, and returns a list\n of dicts; each dict has keys 'answer' and 'frequency'.\n\n This method is run from within the context of a MapReduce job.\n\n Args:\n state_answers_dict: dict. A dict containing state answers and\n exploration information such as:\n * exploration_id: id of the exploration.\n * exploration_version: Specific version of the exploration or\n VERSION_ALL is used if answers are aggregated across\n multiple versions.\n * state_name: Name of the state.\n * interaction_id: id of the interaction.\n * submitted_answer_list: A list of submitted answers.\n\n Returns:\n stats_domain.StateAnswersCalcOutput. A calculation output object\n containing the answers' frequencies.\n\n Raises:\n Exception. Linear interaction is not allowed for the calculation of\n answers' frequencies.\n \"\"\"\n interaction_id = state_answers_dict['interaction_id']\n if interaction_id in feconf.LINEAR_INTERACTION_IDS:\n raise Exception(\n 'Linear interaction \\'%s\\' is not allowed for the calculation '\n 'of answers\\' frequencies.' % interaction_id\n )\n answer_dicts = state_answers_dict['submitted_answer_list']\n answer_frequency_list = (\n _get_top_answers_by_frequency(d['answer'] for d in answer_dicts))\n return stats_domain.StateAnswersCalcOutput(\n state_answers_dict['exploration_id'],\n state_answers_dict['exploration_version'],\n state_answers_dict['state_name'],\n interaction_id,\n self.id,\n answer_frequency_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def reject_suggestions(\n suggestion_ids: List[str], reviewer_id: str, review_message: str\n) -> None:\n \"\"\"Rejects the suggestions with the given suggestion_ids.\n\n Args:\n suggestion_ids: list(str). The ids of the suggestions to be rejected.\n reviewer_id: str. The ID of the reviewer rejecting the suggestions.\n review_message: str. The message provided by the reviewer while\n rejecting the suggestions.\n\n Raises:\n Exception. One or more of the suggestions has already been handled.\n \"\"\"\n suggestions_with_none = get_suggestions_by_ids(suggestion_ids)\n suggestions = []\n\n for index, suggestion in enumerate(suggestions_with_none):\n if suggestion is None:\n raise Exception(\n 'You cannot reject the suggestion with id %s because it does '\n 'not exist.' % (suggestion_ids[index])\n )\n suggestions.append(suggestion)\n if suggestion.is_handled:\n raise Exception(\n 'The suggestion with id %s has already been accepted/'\n 'rejected.' % (suggestion.suggestion_id)\n )\n if not review_message:\n raise Exception('Review message cannot be empty.')\n\n for suggestion in suggestions:\n suggestion.set_suggestion_status_to_rejected()\n suggestion.set_final_reviewer_id(reviewer_id)\n\n _update_suggestions(suggestions, validate_suggestion=False)\n\n # Update the community contribution stats so that the number of suggestions\n # that are in review decreases, since these suggestions are no longer in\n # review.\n _update_suggestion_counts_in_community_contribution_stats(suggestions, -1)\n\n feedback_services.create_messages(\n suggestion_ids, reviewer_id, feedback_models.STATUS_CHOICES_IGNORED,\n None, review_message, should_send_email=False\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __getattr__(self, name):\n def fail(*args, **kwargs):\n raise Exception(\"OH NO\")\n\n return fail", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _parse_and_process_html_to_mdx( # noqa: C901\n self, html_file_path: pathlib.Path, html_file_contents: str\n ) -> str:\n \"\"\"Parse sphinx generated html and make changes suitable for use in docusaurus.\n\n Args:\n html_file_path: Path to the html file to process.\n html_file_contents: Contents of the html file to process.\n\n Returns:\n Content suitable for use in a docusaurus mdx file.\n \"\"\"\n from bs4 import (\n BeautifulSoup,\n ) # Importing here since it is not a library requirement\n\n soup = BeautifulSoup(html_file_contents, \"html.parser\")\n\n # Retrieve and remove the title (it will also be autogenerated by docusaurus)\n title = soup.find(\"h1\").extract() # type: ignore[union-attr]\n title_str = title.get_text(strip=True)\n title_str = title_str.replace(\"#\", \"\")\n\n apply_markdown_adjustments(soup, html_file_path, html_file_contents)\n\n sidebar_entry = self._get_sidebar_entry(html_file_path=html_file_path)\n\n # Add .py suffix to module titles\n if sidebar_entry.type == SidebarEntryType.MODULE:\n stem_path = pathlib.Path(\n self._get_mdx_file_path(sidebar_entry=sidebar_entry).stem\n )\n mdx_stripped_path = str(stem_path.with_suffix(\"\"))\n if mdx_stripped_path.lower() == title_str.lower():\n title_str = str(stem_path.with_suffix(\".py\"))\n\n # Add class=\"sphinx-api-doc\" to section tag to reference in css\n doc = soup.find(\"section\")\n doc[\"class\"] = \"sphinx-api-doc\" # type: ignore[index]\n\n # Change style to styles to avoid rendering errors\n tags_with_style = doc.find_all( # type: ignore[union-attr]\n \"col\",\n style=lambda value: value in value, # noqa: PLR0124\n )\n for tag in tags_with_style:\n style = tag[\"style\"]\n del tag[\"style\"]\n tag[\"styles\"] = style\n\n # Process documentation links\n external_refs = doc.find_all(class_=\"reference external\") # type: ignore[union-attr]\n for external_ref in external_refs:\n url = external_ref.string\n url_parts = urlparse(url)\n url_path = url_parts.path.strip(\"/\").split(\"/\")\n url_text = url_path[-1]\n\n formatted_text = url_text.replace(\"_\", \" \").title()\n\n external_ref.string = formatted_text\n\n # Process internal links\n # There are a couple things we need to do here:\n # - Use relative links. This solves two problems\n # - Ensure links continue to work even after cutting new docs versions\n # - Ensure links continue to work regardless of host url\n # - Remove fragments from links; docusaurus currently errors on these.\n internal_refs = doc.find_all(class_=\"reference internal\") # type: ignore[union-attr]\n for internal_ref in internal_refs:\n href = internal_ref[\"href\"]\n\n split_href = href.split(\"#\")\n href_path = pathlib.Path(split_href[0])\n\n if str(href_path) == \".\":\n # For self referential links, use the file path\n link_sidebar_entry = self._get_sidebar_entry(\n html_file_path=html_file_path\n )\n else:\n link_sidebar_entry = self._get_sidebar_entry(html_file_path=href_path)\n\n relative_link = self._relative_path_between_documents(\n sidebar_entry.mdx_relpath, link_sidebar_entry.mdx_relpath\n )\n without_extension = str(relative_link).replace(\".mdx\", \"\")\n if not without_extension.endswith(\"_class\"):\n raise Exception( # noqa: TRY002, TRY003\n f\"Expected class mdx file path to end with _class; this could indicate a method link that will break: {without_extension}\"\n )\n internal_ref[\"href\"] = str(without_extension)\n\n doc_str = str(doc)\n\n # Add front matter and handle code blocks\n code_block_exists = \"CodeBlock\" in doc_str\n doc_str = self._add_doc_front_matter(\n doc=doc_str, title=title_str, import_code_block=code_block_exists\n )\n if code_block_exists:\n doc_str = self._clean_up_code_blocks(doc_str)\n\n return doc_str", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def _run_command(self, args, env=None, cwd=None, print_output=True, ignore_warnings=False):\n if print_output:\n self.logger.debug(\"Running %s\", args[0])\n self.logger.debug(\"Full command args: %s\", str(args))\n\n process = subprocess.Popen(args, env=env, cwd=cwd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = [b.decode(\"utf-8\") for b in process.communicate()]\n\n if print_output:\n if stdout:\n if PY2:\n try:\n sys.stdout.write(stdout.encode(\"utf-8\"))\n except UnicodeDecodeError:\n sys.stdout.write(stdout)\n else:\n sys.stdout.write(stdout)\n if stderr:\n if PY2:\n try:\n sys.stderr.write(stderr.encode(\"utf-8\"))\n except UnicodeDecodeError:\n sys.stderr.write(stderr)\n else:\n sys.stderr.write(stderr)\n\n if process.returncode != 0:\n raise Exception('%s produced a non-zero return code %i'\n % (args[0], process.returncode))\n\n if not ignore_warnings and ('warning' in stderr or 'warning' in stdout):\n self.saw_warnings = True\n if not self._ask_yes_or_no_question('%s produced warnings, '\n 'try to continue?' % args[0]):\n raise Exception('%s step failed' % args[0])\n\n return stdout.strip()", "smellKey": "S112", "smellId": null, "repo": "tsdgeos_poppler_mirror", "language": "python"} {"function": "def _get_token(user_id: str, password: str, auth_svc: str) -> str:\n \"\"\"Given a user name and password, retrieve an auth token for that user.\"\"\"\n # This is bandaid helper function until we get a full\n # KBase python auth client released\n # note that currently globus usernames, and therefore kbase usernames,\n # cannot contain non-ascii characters. In python 2, quote doesn't handle\n # unicode, so if this changes this client will need to change.\n body = \"user_id=\" + quote(user_id) + \"&password=\" + quote(password) + \"&fields=token\"\n ret = requests.post(auth_svc, data=body, allow_redirects=True)\n status = ret.status_code\n if status >= 200 and status <= 299:\n tok = json.loads(ret.text)\n elif status == 403:\n err_msg = f\"Authentication failed: Bad user_id/password combination for user {user_id}\"\n raise Exception(err_msg)\n else:\n raise Exception(ret.text)\n return tok[\"token\"]", "smellKey": "S112", "smellId": null, "repo": "kbase_narrative", "language": "python"} {"function": "def get_gdb_version():\n try:\n stdout, stderr = run_gdb('--version')\n except OSError as exc:\n # This is what \"no gdb\" looks like. There may, however, be other\n # errors that manifest this way too.\n raise unittest.SkipTest(f\"Couldn't find gdb program on the path: {exc}\")\n\n # Regex to parse:\n # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\\n' -> 7.7\n # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\\n' -> 7.9\n # 'GNU gdb 6.1.1 [FreeBSD]\\n' -> 6.1\n # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\\n' -> 7.5\n # 'HP gdb 6.7 for HP Itanium (32 or 64 bit) and target HP-UX 11iv2 and 11iv3.\\n' -> 6.7\n match = re.search(r\"^(?:GNU|HP) gdb.*?\\b(\\d+)\\.(\\d+)\", stdout)\n if match is None:\n raise Exception(\"unable to parse gdb version: %r\" % stdout)\n version_text = stdout\n major = int(match.group(1))\n minor = int(match.group(2))\n version = (major, minor)\n return (version_text, version)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def set_network_quoted(self, id, field, value):\n res = self.request(\"SET_NETWORK \" + str(id) + \" \" + field + ' \"' + value + '\"')\n if \"FAIL\" in res:\n raise Exception(\"SET_NETWORK failed\")\n return None", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "def main():\n args = get_args()\n\n manifest_directory = os.path.abspath(args.output_dir)\n if not os.path.exists(manifest_directory):\n os.makedirs(manifest_directory)\n source = os.path.abspath(os.path.expanduser(args.source))\n\n sources = []\n if not os.path.isfile(source): # directory/pattern with images\n data_dir = None\n if os.path.isdir(source):\n data_dir = source\n for root, _, files in os.walk(source):\n sources.extend([os.path.join(root, f) for f in files if is_image(f)])\n else:\n items = source.lstrip('/').split('/')\n position = 0\n try:\n for item in items:\n if set(item) & {'*', '?', '[', ']'}:\n break\n position += 1\n else:\n raise Exception('Wrong positional argument')\n assert position != 0, 'Wrong pattern: there must be a common root'\n data_dir = source.split(items[position])[0]\n except Exception as ex:\n sys.exit(str(ex))\n sources = list(filter(is_image, glob(source, recursive=True)))\n\n sources = list(filter(lambda x: 'related_images{}'.format(os.sep) not in x, sources))\n\n # If the source is a glob expression, we need additional processing\n abs_root = source\n while abs_root and re.search(r'[*?\\[\\]]', abs_root):\n abs_root = os.path.split(abs_root)[0]\n\n related_images = detect_related_images(sources, abs_root)\n meta = { k: {'related_images': related_images[k] } for k in related_images }\n try:\n assert len(sources), 'A images was not found'\n manifest = ImageManifestManager(manifest_path=manifest_directory)\n manifest.link(sources=sources, meta=meta, sorting_method=args.sorting,\n use_image_hash=True, data_dir=data_dir)\n manifest.create(_tqdm=tqdm)\n except Exception as ex:\n sys.exit(str(ex))\n else: # video\n try:\n assert is_video(source), 'You can specify a video path or a directory/pattern with images'\n manifest = VideoManifestManager(manifest_path=manifest_directory)\n manifest.link(media_file=source, force=args.force)\n try:\n manifest.create(_tqdm=tqdm)\n except AssertionError as ex:\n if str(ex) == 'Too few keyframes':\n msg = 'NOTE: prepared manifest file contains too few key frames for smooth decoding.\\n' \\\n 'Use --force flag if you still want to prepare a manifest file.'\n print(msg)\n sys.exit(2)\n else:\n raise\n except Exception as ex:\n sys.exit(str(ex))\n\n print('The manifest file has been prepared')", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@pytest.fixture\ndef snafu() -> Any:\n class SNAFU:\n def __str__(self) -> str:\n raise Exception(\"snafu\")\n\n return SNAFU()", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def list_modules():\n names = set()\n\n list_builtin_modules(names)\n list_modules_setup_extensions(names)\n list_packages(names)\n list_python_modules(names)\n list_frozen(names)\n\n # Remove ignored packages and modules\n for name in list(names):\n package_name = name.split('.')[0]\n # package_name can be equal to name\n if package_name in IGNORE:\n names.discard(name)\n\n # Sanity checks\n for name in names:\n if \".\" in name:\n raise Exception(f\"sub-modules must not be listed: {name}\")\n if (\"test\" in name or \"xx\" in name) and name not in ALLOW_TEST_MODULES:\n raise Exception(f\"test modules must not be listed: {name}\")\n\n return names", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@classmethod\n def generate_new_classroom_id(cls) -> str:\n \"\"\"Generates a new classroom ID which is unique and is in the form of\n random hash of 12 chars.\n\n Returns:\n str. A classroom ID that is different from the IDs of all\n the existing classroom.\n\n Raises:\n Exception. There were too many collisions with existing classroom\n IDs when attempting to generate a new classroom ID.\n \"\"\"\n for _ in range(base_models.MAX_RETRIES):\n classroom_id = utils.convert_to_hash(\n str(utils.get_random_int(base_models.RAND_RANGE)),\n base_models.ID_LENGTH)\n if not cls.get_by_id(classroom_id):\n return classroom_id\n raise Exception(\n 'New classroom id generator is producing too many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def create_config_from_prompts(self, kwargs, parent=None):\n \"\"\"\n Create a launch configuration entry for this job, given prompts\n returns None if it can not be created\n \"\"\"\n JobLaunchConfig = self._meta.get_field('launch_config').related_model\n config = JobLaunchConfig(job=self)\n if parent is None:\n parent = getattr(self, self._get_parent_field_name())\n if parent is None:\n return\n valid_fields = list(parent.get_ask_mapping().keys())\n # Special cases allowed for workflows\n if hasattr(self, 'extra_vars'):\n valid_fields.extend(['survey_passwords', 'extra_vars'])\n else:\n kwargs.pop('survey_passwords', None)\n many_to_many_fields = []\n for field_name, value in kwargs.items():\n if field_name not in valid_fields:\n raise Exception('Unrecognized launch config field {}.'.format(field_name))\n field = None\n # may use extra_data as a proxy for extra_vars\n if field_name in config.SUBCLASS_FIELDS and field_name != 'extra_vars':\n field = config._meta.get_field(field_name)\n if isinstance(field, models.ManyToManyField):\n many_to_many_fields.append(field_name)\n continue\n if isinstance(field, (models.ForeignKey)) and (value is None):\n continue # the null value indicates not-provided for ForeignKey case\n setattr(config, field_name, value)\n config.save()\n\n for field_name in many_to_many_fields:\n prompted_items = kwargs.get(field_name, [])\n if not prompted_items:\n continue\n if field_name == 'instance_groups':\n # Here we are doing a loop to make sure we preserve order for this Ordered field\n # also do not merge IGs with parent, so this saves the literal list\n for item in prompted_items:\n getattr(config, field_name).add(item)\n else:\n # Assuming this field merges prompts with parent, save just the diff\n if field_name in [field.name for field in parent._meta.get_fields()]:\n prompted_items = set(prompted_items) - set(getattr(parent, field_name).all())\n if prompted_items:\n getattr(config, field_name).add(*prompted_items)\n\n return config", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def _save_topic(\n committer_id: str,\n topic: topic_domain.Topic,\n commit_message: Optional[str],\n change_list: Sequence[change_domain.BaseChange]\n) -> None:\n \"\"\"Validates a topic and commits it to persistent storage. If\n successful, increments the version number of the incoming topic domain\n object by 1.\n\n Args:\n committer_id: str. ID of the given committer.\n topic: Topic. The topic domain object to be saved.\n commit_message: str|None. The commit description message, for\n unpublished topics, it may be equal to None.\n change_list: list(TopicChange). List of changes applied to a topic.\n\n Raises:\n Exception. Received invalid change list.\n Exception. The topic model and the incoming topic domain\n object have different version numbers.\n \"\"\"\n if not change_list:\n raise Exception(\n 'Unexpected error: received an invalid change list when trying to '\n 'save topic %s: %s' % (topic.id, change_list))\n topic_rights = topic_fetchers.get_topic_rights(topic.id, strict=True)\n topic.validate(strict=topic_rights.topic_is_published)\n\n topic_model = topic_models.TopicModel.get(topic.id, strict=True)\n\n # Topic model cannot be None as topic is passed as parameter here and that\n # is only possible if a topic model with that topic id exists. Also this is\n # a private function and so it cannot be called independently with any\n # topic object.\n if topic.version > topic_model.version:\n raise Exception(\n 'Unexpected error: trying to update version %s of topic '\n 'from version %s. Please reload the page and try again.'\n % (topic_model.version, topic.version))\n if topic.version < topic_model.version:\n raise Exception(\n 'Trying to update version %s of topic from version %s, '\n 'which is too old. Please reload the page and try again.'\n % (topic_model.version, topic.version))\n\n topic_model_to_commit = populate_topic_model_fields(topic_model, topic)\n change_dicts = [change.to_dict() for change in change_list]\n topic_model_to_commit.commit(committer_id, commit_message, change_dicts)\n caching_services.delete_multi(\n caching_services.CACHE_NAMESPACE_TOPIC, None, [topic.id])\n topic.version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_requested_channels(self, data):\n if self.requested_channels > self.actual_channels:\n raise Exception(\"Cannot add channels, actual is {}, requested is {}\".format(\n self.actual_channels, self.requested_channels))\n\n if self.requested_channels < self.actual_channels:\n data = np.frombuffer(data, dtype=np.int16)\n channels = []\n # split into separate channels\n for i in range(self.actual_channels):\n channels += [data[i::self.actual_channels]]\n # drop the channels we don't want\n channels = channels[0:self.requested_channels]\n # zip the resulting channels back up.\n data = np.array(list(zip(*channels))).flatten()\n # convert back to packed bytes in PCM 16 format\n data = bytes(np.array(data, dtype=np.int16))\n\n return data", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "def test_exception_fetching_user(self):\n \"\"\"\n The error page can be rendered if the current user can't be retrieved\n (such as when the database is unavailable).\n \"\"\"\n\n class ExceptionUser:\n def __str__(self):\n raise Exception()\n\n request = self.rf.get(\"/test_view/\")\n request.user = ExceptionUser()\n\n try:\n raise ValueError(\"Oops\")\n except ValueError:\n exc_type, exc_value, tb = sys.exc_info()\n\n reporter = ExceptionReporter(request, exc_type, exc_value, tb)\n html = reporter.get_traceback_html()\n self.assertInHTML(\"<h1>ValueError at /test_view/</h1>\", html)\n self.assertIn('<pre class=\"exception_value\">Oops</pre>', html)\n self.assertIn('<h3 id=\"user-info\">USER</h3>', html)\n self.assertIn(\"<p>[unable to retrieve the current user]</p>\", html)\n\n text = reporter.get_traceback_text()\n self.assertIn(\"USER: [unable to retrieve the current user]\", text)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def dpp_bootstrap_gen(wpas, type=\"qrcode\", chan=None, mac=None, info=None,\n curve=None, key=None):\n cmd = \"DPP_BOOTSTRAP_GEN type=\" + type\n if chan:\n cmd += \" chan=\" + chan\n if mac:\n if mac is True:\n mac = own_addr(wpas)\n if mac is None:\n summary(\"Could not determine local MAC address for bootstrap info\")\n else:\n cmd += \" mac=\" + mac.replace(':', '')\n if info:\n cmd += \" info=\" + info\n if curve:\n cmd += \" curve=\" + curve\n if key:\n cmd += \" key=\" + key\n res = wpas.request(cmd)\n if \"FAIL\" in res:\n raise Exception(\"Failed to generate bootstrapping info\")\n return int(res)", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "def readfortrancode(ffile, dowithline=show, istop=1):\n \"\"\"\n Read fortran codes from files and\n 1) Get rid of comments, line continuations, and empty lines; lower cases.\n 2) Call dowithline(line) on every line.\n 3) Recursively call itself when statement \\\"include '<filename>'\\\" is met.\n \"\"\"\n global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77\n global beginpattern, quiet, verbose, dolowercase, include_paths\n\n if not istop:\n saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\\\n beginpattern, quiet, verbose, dolowercase\n if ffile == []:\n return\n localdolowercase = dolowercase\n # cont: set to True when the content of the last line read\n # indicates statement continuation\n cont = False\n finalline = ''\n ll = ''\n includeline = re.compile(\n r'\\s*include\\s*(\\'|\")(?P<name>[^\\'\"]*)(\\'|\")', re.I)\n cont1 = re.compile(r'(?P<line>.*)&\\s*\\Z')\n cont2 = re.compile(r'(\\s*&|)(?P<line>.*)')\n mline_mark = re.compile(r\".*?'''\")\n if istop:\n dowithline('', -1)\n ll, l1 = '', ''\n spacedigits = [' '] + [str(_m) for _m in range(10)]\n filepositiontext = ''\n fin = fileinput.FileInput(ffile, openhook=openhook)\n while True:\n try:\n l = fin.readline()\n except UnicodeDecodeError as msg:\n raise Exception(\n f'readfortrancode: reading {fin.filename()}#{fin.lineno()}'\n f' failed with\\n{msg}.\\nIt is likely that installing charset_normalizer'\n ' package will help f2py determine the input file encoding'\n ' correctly.')\n if not l:\n break\n if fin.isfirstline():\n filepositiontext = ''\n currentfilename = fin.filename()\n gotnextfile = 1\n l1 = l\n strictf77 = 0\n sourcecodeform = 'fix'\n ext = os.path.splitext(currentfilename)[1]\n if Path(currentfilename).suffix.lower() in COMMON_FIXED_EXTENSIONS and \\\n not (_has_f90_header(l) or _has_fix_header(l)):\n strictf77 = 1\n elif is_free_format(currentfilename) and not _has_fix_header(l):\n sourcecodeform = 'free'\n if strictf77:\n beginpattern = beginpattern77\n else:\n beginpattern = beginpattern90\n outmess('\\tReading file %s (format:%s%s)\\n'\n % (repr(currentfilename), sourcecodeform,\n strictf77 and ',strict' or ''))\n\n l = l.expandtabs().replace('\\xa0', ' ')\n # Get rid of newline characters\n while not l == '':\n if l[-1] not in \"\\n\\r\\f\":\n break\n l = l[:-1]\n if not strictf77:\n (l, rl) = split_by_unquoted(l, '!')\n l += ' '\n if rl[:5].lower() == '!f2py': # f2py directive\n l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!')\n if l.strip() == '': # Skip empty line\n if sourcecodeform == 'free':\n # In free form, a statement continues in the next line\n # that is not a comment line [3.3.2.4^1], lines with\n # blanks are comment lines [3.3.2.3^1]. Hence, the\n # line continuation flag must retain its state.\n pass\n else:\n # In fixed form, statement continuation is determined\n # by a non-blank character at the 6-th position. Empty\n # line indicates a start of a new statement\n # [3.3.3.3^1]. Hence, the line continuation flag must\n # be reset.\n cont = False\n continue\n if sourcecodeform == 'fix':\n if l[0] in ['*', 'c', '!', 'C', '#']:\n if l[1:5].lower() == 'f2py': # f2py directive\n l = ' ' + l[5:]\n else: # Skip comment line\n cont = False\n continue\n elif strictf77:\n if len(l) > 72:\n l = l[:72]\n if not (l[0] in spacedigits):\n raise Exception('readfortrancode: Found non-(space,digit) char '\n 'in the first column.\\n\\tAre you sure that '\n 'this code is in fix form?\\n\\tline=%s' % repr(l))\n\n if (not cont or strictf77) and (len(l) > 5 and not l[5] == ' '):\n # Continuation of a previous line\n ll = ll + l[6:]\n finalline = ''\n origfinalline = ''\n else:\n if not strictf77:\n # F90 continuation\n r = cont1.match(l)\n if r:\n l = r.group('line') # Continuation follows ..\n if cont:\n ll = ll + cont2.match(l).group('line')\n finalline = ''\n origfinalline = ''\n else:\n # clean up line beginning from possible digits.\n l = ' ' + l[5:]\n if localdolowercase:\n finalline = ll.lower()\n else:\n finalline = ll\n origfinalline = ll\n ll = l\n cont = (r is not None)\n else:\n # clean up line beginning from possible digits.\n l = ' ' + l[5:]\n if localdolowercase:\n finalline = ll.lower()\n else:\n finalline = ll\n origfinalline = ll\n ll = l\n\n elif sourcecodeform == 'free':\n if not cont and ext == '.pyf' and mline_mark.match(l):\n l = l + '\\n'\n while True:\n lc = fin.readline()\n if not lc:\n errmess(\n 'Unexpected end of file when reading multiline\\n')\n break\n l = l + lc\n if mline_mark.match(lc):\n break\n l = l.rstrip()\n r = cont1.match(l)\n if r:\n l = r.group('line') # Continuation follows ..\n if cont:\n ll = ll + cont2.match(l).group('line')\n finalline = ''\n origfinalline = ''\n else:\n if localdolowercase:\n finalline = ll.lower()\n else:\n finalline = ll\n origfinalline = ll\n ll = l\n cont = (r is not None)\n else:\n raise ValueError(\n \"Flag sourcecodeform must be either 'fix' or 'free': %s\" % repr(sourcecodeform))\n filepositiontext = 'Line #%d in %s:\"%s\"\\n\\t' % (\n fin.filelineno() - 1, currentfilename, l1)\n m = includeline.match(origfinalline)\n if m:\n fn = m.group('name')\n if os.path.isfile(fn):\n readfortrancode(fn, dowithline=dowithline, istop=0)\n else:\n include_dirs = [\n os.path.dirname(currentfilename)] + include_paths\n foundfile = 0\n for inc_dir in include_dirs:\n fn1 = os.path.join(inc_dir, fn)\n if os.path.isfile(fn1):\n foundfile = 1\n readfortrancode(fn1, dowithline=dowithline, istop=0)\n break\n if not foundfile:\n outmess('readfortrancode: could not find include file %s in %s. Ignoring.\\n' % (\n repr(fn), os.pathsep.join(include_dirs)))\n else:\n dowithline(finalline)\n l1 = ll\n if localdolowercase:\n finalline = ll.lower()\n else:\n finalline = ll\n origfinalline = ll\n filepositiontext = 'Line #%d in %s:\"%s\"\\n\\t' % (\n fin.filelineno() - 1, currentfilename, l1)\n m = includeline.match(origfinalline)\n if m:\n fn = m.group('name')\n if os.path.isfile(fn):\n readfortrancode(fn, dowithline=dowithline, istop=0)\n else:\n include_dirs = [os.path.dirname(currentfilename)] + include_paths\n foundfile = 0\n for inc_dir in include_dirs:\n fn1 = os.path.join(inc_dir, fn)\n if os.path.isfile(fn1):\n foundfile = 1\n readfortrancode(fn1, dowithline=dowithline, istop=0)\n break\n if not foundfile:\n outmess('readfortrancode: could not find include file %s in %s. Ignoring.\\n' % (\n repr(fn), os.pathsep.join(include_dirs)))\n else:\n dowithline(finalline)\n filepositiontext = ''\n fin.close()\n if istop:\n dowithline('', 1)\n else:\n gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\\\n beginpattern, quiet, verbose, dolowercase = saveglobals", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@acl_decorators.can_play_entity\n def put(self, entity_type: str, entity_id: str) -> None:\n \"\"\"\"Handles the PUT requests. Stores the answer details submitted\n by the learner.\n \"\"\"\n assert self.normalized_payload is not None\n if not constants.ENABLE_SOLICIT_ANSWER_DETAILS_FEATURE:\n raise self.NotFoundException\n\n interaction_id = self.normalized_payload['interaction_id']\n if entity_type == feconf.ENTITY_TYPE_EXPLORATION:\n state_name = self.normalized_payload.get('state_name')\n if state_name is None:\n raise Exception(\n 'The \\'state_name\\' must be provided when the entity_type '\n 'is %s.' % feconf.ENTITY_TYPE_EXPLORATION\n )\n state_reference = (\n stats_services.get_state_reference_for_exploration(\n entity_id, state_name))\n if interaction_id != exp_services.get_interaction_id_for_state(\n entity_id, state_name):\n raise utils.InvalidInputException(\n 'Interaction id given does not match with the '\n 'interaction id of the state')\n elif entity_type == feconf.ENTITY_TYPE_QUESTION:\n state_reference = (\n stats_services.get_state_reference_for_question(entity_id))\n if interaction_id != (\n question_services.get_interaction_id_for_question(\n entity_id)):\n raise utils.InvalidInputException(\n 'Interaction id given does not match with the '\n 'interaction id of the question')\n\n answer = self.normalized_payload['answer']\n answer_details = self.normalized_payload['answer_details']\n stats_services.record_learner_answer_info(\n entity_type, state_reference,\n interaction_id, answer, answer_details)\n self.render_json({})", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def forward(\n self,\n hidden_states: torch.Tensor,\n bbox_pos_emb: torch.Tensor,\n attention_mask: Optional[torch.FloatTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n output_attentions: Optional[bool] = False,\n ) -> Tuple[torch.Tensor]:\n # decoder uni-directional self-attention cached key/values tuple is at positions 1,2\n self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None\n self_attention_outputs = self.attention(\n hidden_states,\n bbox_pos_emb=bbox_pos_emb,\n attention_mask=attention_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n past_key_value=self_attn_past_key_value,\n )\n attention_output = self_attention_outputs[0]\n\n # if decoder, the last output is tuple of self-attn cache\n if self.is_decoder:\n outputs = self_attention_outputs[1:-1]\n present_key_value = self_attention_outputs[-1]\n else:\n outputs = self_attention_outputs[1:] # add self attentions if we output attention weights\n\n cross_attn_present_key_value = None\n if self.is_decoder and encoder_hidden_states is not None:\n if hasattr(self, \"crossattention\"):\n raise Exception(\n f\"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`\"\n )\n\n # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple\n cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None\n cross_attention_outputs = self.crossattention(\n attention_output,\n attention_mask,\n head_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n cross_attn_past_key_value,\n output_attentions,\n )\n attention_output = cross_attention_outputs[0]\n outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights\n\n # add cross-attn cache to positions 3,4 of present_key_value tuple\n cross_attn_present_key_value = cross_attention_outputs[-1]\n present_key_value = present_key_value + cross_attn_present_key_value\n\n layer_output = apply_chunking_to_forward(\n self.feed_forward_chunk,\n self.chunk_size_feed_forward,\n self.seq_len_dim,\n attention_output,\n )\n outputs = (layer_output,) + outputs\n\n # if decoder, return the attn key/values as the last output\n if self.is_decoder:\n outputs = outputs + (present_key_value,)\n\n return outputs", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_current_release_version_number(release_branch_name: str) -> str:\n \"\"\"Gets the release version given a release branch name.\n\n Args:\n release_branch_name: str. The name of release branch.\n\n Returns:\n str. The version of release.\n\n Raises:\n Exception. Invalid name of the release branch.\n \"\"\"\n release_match = re.match(RELEASE_BRANCH_REGEX, release_branch_name)\n release_maintenance_match = re.match(\n RELEASE_MAINTENANCE_BRANCH_REGEX, release_branch_name)\n hotfix_match = re.match(\n HOTFIX_BRANCH_REGEX, release_branch_name)\n if release_match:\n return release_match.group(1)\n elif release_maintenance_match:\n return release_maintenance_match.group(1)\n elif hotfix_match:\n return hotfix_match.group(1)\n else:\n raise Exception('Invalid branch name: %s.' % release_branch_name)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_success_response(self, *args, **params):\n \"\"\"\n Call `get_response` (see above) and assert the response's status code.\n\n :param params:\n * status_code: (Optional) Assert that the response's status code is\n a specific code. Omit to assert any successful status_code.\n :returns Response object\n \"\"\"\n status_code = params.pop(\"status_code\", None)\n\n if status_code and status_code >= 400:\n raise Exception(\"status_code must be < 400\")\n\n method = params.pop(\"method\", self.method).lower()\n\n response = self.get_response(*args, method=method, **params)\n\n if status_code:\n assert_status_code(response, status_code)\n elif method == \"get\":\n assert_status_code(response, status.HTTP_200_OK)\n # TODO(mgaeta): Add the other methods.\n # elif method == \"post\":\n # assert_status_code(response, status.HTTP_201_CREATED)\n elif method == \"put\":\n assert_status_code(response, status.HTTP_200_OK)\n elif method == \"delete\":\n assert_status_code(response, status.HTTP_204_NO_CONTENT)\n else:\n # TODO(mgaeta): Add other methods.\n assert_status_code(response, 200, 300)\n\n return response", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def create(\n cls, author_id: str\n ) -> AuthorBlogPostAggregatedReadingTimeModel:\n \"\"\"Creates a new AuthorBlogPostAggregatedReadingTimeModel entry.\n\n Args:\n author_id: str. User ID of the author.\n\n Returns:\n AuthorBlogPostAggregatedReadingTimeModel. The newly created\n AuthorBlogPostAggregatedReadingTimeModel instance.\n\n Raises:\n Exception. A reading time model with the given author ID exists\n already.\n \"\"\"\n if cls.get_by_id(author_id):\n raise Exception(\n 'A author blog post reading time model with the given author ID'\n ' exists already.')\n\n entity = cls(\n id=author_id,\n zero_to_one_min=0,\n one_to_two_min=0,\n two_to_three_min=0,\n three_to_four_min=0,\n four_to_five_min=0,\n five_to_six_min=0,\n six_to_seven_min=0,\n seven_to_eight_min=0,\n eight_to_nine_min=0,\n nine_to_ten_min=0,\n more_than_ten_min=0\n )\n entity.update_timestamps()\n entity.put()\n\n return entity", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_env_dict(env_var: str) -> dict[str, str]:\n \"\"\"\n Get an env variable and convert it into a python dictionary with keys and values as strings.\n Args:\n env_var (str): env var, example: SL_DB\n\n Syntax is: key1=value1;key2=value2\n Components separated by ;\n key and value separated by =\n \"\"\"\n value = os.getenv(env_var)\n if not value:\n return {}\n\n components = value.split(\";\")\n result = {}\n for component in components:\n if component == \"\":\n continue\n parts = component.split(\"=\")\n if len(parts) != 2:\n raise Exception(f\"Invalid config for env var {env_var}\")\n result[parts[0].strip()] = parts[1].strip()\n\n return result", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def test_does_not_decorate_message_with_non_beam_type(self) -> None:\n with self.assertRaisesRegex(Exception, 'Error coming through!'):\n with job_test_utils.decorate_beam_errors():\n raise Exception('Error coming through!')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def compute_models_to_commit(\n self,\n committer_id: str,\n commit_type: str,\n commit_message: Optional[str],\n commit_cmds: AllowedCommitCmdsListType,\n # We expect Mapping because we want to allow models that inherit\n # from BaseModel as the values, if we used Dict this wouldn't\n # be allowed.\n unused_additional_models: Mapping[str, BaseModel]\n ) -> ModelsToPutDict:\n \"\"\"Evaluates and executes commit. Main function for all commit types.\n\n Args:\n committer_id: str. The user_id of the user who committed the change.\n commit_type: str. Unique identifier of commit type. Possible values\n are in COMMIT_TYPE_CHOICES.\n commit_message: str|None. The commit description message, or None if\n draft (or unpublished) model is provided.\n commit_cmds: list(dict). A list of commands, describing changes\n made in this model, should give sufficient information to\n reconstruct the commit. Dict always contains:\n cmd: str. Unique command.\n And then additional arguments for that command. For example: {\n 'cmd': 'AUTO_revert_version_number',\n 'version_number': 4\n }\n unused_additional_models: dict(str, BaseModel). Additional models\n that are needed for the commit process.\n\n Returns:\n ModelsToPutDict. A dict of models that should be put into\n the datastore.\n\n Raises:\n Exception. No snapshot metadata class has been defined.\n Exception. No snapshot content class has been defined.\n Exception. The commit_cmds is not a list of dicts.\n \"\"\"\n if self.SNAPSHOT_METADATA_CLASS is None:\n raise Exception('No snapshot metadata class defined.')\n if self.SNAPSHOT_CONTENT_CLASS is None:\n raise Exception('No snapshot content class defined.')\n if not isinstance(commit_cmds, list):\n raise Exception(\n 'Expected commit_cmds to be a list of dicts, received %s'\n % commit_cmds)\n\n self.version += 1\n\n snapshot = self.compute_snapshot()\n snapshot_id = self.get_snapshot_id(self.id, self.version)\n\n snapshot_metadata_instance = self.SNAPSHOT_METADATA_CLASS.create(\n snapshot_id,\n committer_id,\n commit_type,\n commit_message,\n commit_cmds\n )\n snapshot_content_instance = self.SNAPSHOT_CONTENT_CLASS.create(\n snapshot_id, snapshot\n )\n\n return {\n 'snapshot_metadata_model': snapshot_metadata_instance,\n 'snapshot_content_model': snapshot_content_instance,\n 'versioned_model': self,\n }", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _init_curltest(self):\n if Httpd.MOD_CURLTEST is not None:\n return\n local_dir = os.path.dirname(inspect.getfile(Httpd))\n p = subprocess.run([self.env.apxs, '-c', 'mod_curltest.c'],\n capture_output=True,\n cwd=os.path.join(local_dir, 'mod_curltest'))\n rv = p.returncode\n if rv != 0:\n log.error(f\"compiling mod_curltest failed: {p.stderr}\")\n raise Exception(f\"compiling mod_curltest failed: {p.stderr}\")\n Httpd.MOD_CURLTEST = os.path.join(\n local_dir, 'mod_curltest/.libs/mod_curltest.so')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_curl", "language": "python"} {"function": "def _wrap_model(self, model, training=True, dataloader=None):\n if self.args.use_ipex:\n dtype = torch.bfloat16 if self.use_cpu_amp else torch.float32\n model = self.ipex_optimize_model(model, training, dtype=dtype)\n\n if is_sagemaker_mp_enabled():\n # Wrapping the base model twice in a DistributedModel will raise an error.\n if isinstance(self.model_wrapped, smp.model.DistributedModel):\n return self.model_wrapped\n return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps)\n\n # train/eval could be run multiple-times - if already wrapped, don't re-wrap it again\n if self.accelerator.unwrap_model(model) is not model:\n return model\n\n # Mixed precision training with apex (torch < 1.6)\n if self.use_apex and training:\n model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)\n\n # Multi-gpu training (should be after apex fp16 initialization) / 8bit models does not support DDP\n if self.args.n_gpu > 1 and not getattr(model, \"is_loaded_in_8bit\", False):\n model = nn.DataParallel(model)\n\n if self.args.jit_mode_eval:\n start_time = time.time()\n model = self.torch_jit_model_eval(model, dataloader, training)\n self.jit_compilation_time = round(time.time() - start_time, 4)\n\n # Note: in torch.distributed mode, there's no point in wrapping the model\n # inside a DistributedDataParallel as we'll be under `no_grad` anyways.\n if not training:\n return model\n\n # Distributed training (should be after apex fp16 initialization)\n # Distributed training using PyTorch FSDP\n if self.is_fsdp_xla_enabled:\n try:\n from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as FSDP\n from torch_xla.distributed.fsdp import checkpoint_module\n from torch_xla.distributed.fsdp.wrap import (\n size_based_auto_wrap_policy,\n transformer_auto_wrap_policy,\n )\n\n if self.is_fsdp_xla_v2_enabled:\n from torch_xla.experimental.spmd_fully_sharded_data_parallel import (\n SpmdFullyShardedDataParallel as FSDPv2,\n )\n except ImportError:\n raise ImportError(\"Missing XLA FSDP related module; please make sure to use torch-xla >= 2.0.\")\n auto_wrap_policy = None\n auto_wrapper_callable = None\n default_transformer_cls_names_to_wrap = getattr(model, \"_no_split_modules\", None)\n fsdp_transformer_layer_cls_to_wrap = self.args.fsdp_config.get(\n \"transformer_layer_cls_to_wrap\", default_transformer_cls_names_to_wrap\n )\n\n if self.args.fsdp_config[\"min_num_params\"] > 0:\n auto_wrap_policy = functools.partial(\n size_based_auto_wrap_policy, min_num_params=self.args.fsdp_config[\"min_num_params\"]\n )\n elif fsdp_transformer_layer_cls_to_wrap is not None:\n transformer_cls_to_wrap = set()\n for layer_class in fsdp_transformer_layer_cls_to_wrap:\n transformer_cls = get_module_class_from_name(model, layer_class)\n if transformer_cls is None:\n raise Exception(\"Could not find the transformer layer class to wrap in the model.\")\n else:\n transformer_cls_to_wrap.add(transformer_cls)\n\n auto_wrap_policy = functools.partial(\n transformer_auto_wrap_policy,\n # Transformer layer class to wrap\n transformer_layer_cls=transformer_cls_to_wrap,\n )\n fsdp_kwargs = self.args.xla_fsdp_config\n if self.args.fsdp_config[\"xla_fsdp_grad_ckpt\"]:\n if model.config.use_cache:\n logger.warning_once(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.\"\n )\n model.config.use_cache = False\n\n # Apply gradient checkpointing to auto-wrapped sub-modules if specified\n def auto_wrapper_callable(m, *args, **kwargs):\n target_cls = FSDP if not self.is_fsdp_xla_v2_enabled else FSDPv2\n return target_cls(checkpoint_module(m), *args, **kwargs)\n\n # Wrap the base model with an outer FSDP wrapper\n if self.is_fsdp_xla_v2_enabled:\n\n def shard_output(output, mesh):\n from .modeling_outputs import CausalLMOutputWithPast\n\n real_output = None\n if isinstance(output, torch.Tensor):\n real_output = output\n elif isinstance(output, tuple):\n real_output = output[0]\n elif isinstance(output, CausalLMOutputWithPast):\n real_output = output.logits\n\n if real_output is None:\n raise ValueError(\"Something went wrong, the output of the model shouldn't be `None`\")\n xs.mark_sharding(real_output, mesh, (\"fsdp\", None, None))\n\n self.model = model = FSDPv2(\n model,\n shard_output=shard_output,\n auto_wrap_policy=auto_wrap_policy,\n auto_wrapper_callable=auto_wrapper_callable,\n )\n else:\n self.model = model = FSDP(\n model,\n auto_wrap_policy=auto_wrap_policy,\n auto_wrapper_callable=auto_wrapper_callable,\n **fsdp_kwargs,\n )\n\n # Patch `xm.optimizer_step` should not reduce gradients in this case,\n # as FSDP does not need gradient reduction over sharded parameters.\n def patched_optimizer_step(optimizer, barrier=False, optimizer_args={}):\n loss = optimizer.step(**optimizer_args)\n if barrier:\n xm.mark_step()\n return loss\n\n xm.optimizer_step = patched_optimizer_step\n elif is_sagemaker_dp_enabled():\n model = nn.parallel.DistributedDataParallel(\n model, device_ids=[int(os.getenv(\"SMDATAPARALLEL_LOCAL_RANK\"))]\n )\n elif self.args.parallel_mode == ParallelMode.DISTRIBUTED:\n if is_torch_neuroncore_available():\n return model\n kwargs = {}\n if self.args.ddp_find_unused_parameters is not None:\n kwargs[\"find_unused_parameters\"] = self.args.ddp_find_unused_parameters\n elif isinstance(model, PreTrainedModel):\n # find_unused_parameters breaks checkpointing as per\n # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021\n kwargs[\"find_unused_parameters\"] = not model.is_gradient_checkpointing\n else:\n kwargs[\"find_unused_parameters\"] = True\n\n if self.args.ddp_bucket_cap_mb is not None:\n kwargs[\"bucket_cap_mb\"] = self.args.ddp_bucket_cap_mb\n\n if self.args.ddp_broadcast_buffers is not None:\n kwargs[\"broadcast_buffers\"] = self.args.ddp_broadcast_buffers\n\n self.accelerator.ddp_handler = DistributedDataParallelKwargs(**kwargs)\n\n return model", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def import_channels(channels, orgid=None, master=None):\n collection = ChannelCollection()\n batch = []\n org_map = None\n my_backend = diskImportLib.get_backend()\n if master:\n org_map = my_backend.lookupOrgMap(master)[\"master-id-to-local-id\"]\n for c in channels:\n try:\n timestamp = collection.get_channel_timestamp(c)\n except KeyError:\n # pylint: disable-next=consider-using-f-string\n raise_with_tb(Exception(\"Could not find channel %s\" % c), sys.exc_info()[2])\n c_obj = collection.get_channel(c, timestamp)\n if c_obj is None:\n # pylint: disable-next=broad-exception-raised,consider-using-f-string\n raise Exception(\"Channel not found in cache: %s\" % c)\n\n # Check to see if we're asked to sync to an orgid,\n # make sure the org from the export is not null org,\n # finally if the orgs differ so we might wanna use\n # requested org's channel-family.\n # TODO: Move these checks somewhere more appropriate\n if not orgid and c_obj[\"org_id\"] is not None:\n # If the src org is not present default to org 1\n orgid = DEFAULT_ORG\n if (\n orgid is not None\n and c_obj[\"org_id\"] is not None\n and c_obj[\"org_id\"] != orgid\n ):\n # If we know the master this is coming from and the master org\n # has been mapped to a local org, transform org_id to the local\n # org_id. Otherwise just put it in the default org.\n if (\n org_map\n and c_obj[\"org_id\"] in list(org_map.keys())\n and org_map[c_obj[\"org_id\"]]\n ):\n c_obj[\"org_id\"] = org_map[c_obj[\"org_id\"]]\n else:\n c_obj[\"org_id\"] = orgid\n if \"trust_list\" in c_obj:\n del c_obj[\"trust_list\"]\n for family in c_obj[\"families\"]:\n family[\"label\"] = \"private-channel-family-\" + str(c_obj[\"org_id\"])\n # If there's a trust list on the channel, transform the org ids to\n # the local ones\n if \"trust_list\" in c_obj and c_obj[\"trust_list\"]:\n trusts = []\n for trust in c_obj[\"trust_list\"]:\n if trust[\"org_trust_id\"] in org_map:\n trust[\"org_trust_id\"] = org_map[trust[\"org_trust_id\"]]\n trusts.append(trust)\n c_obj[\"trust_list\"] = trusts\n\n syncLib.log(\n 6,\n # pylint: disable-next=consider-using-f-string\n \"Syncing Channel %s to Org %s \" % (c_obj[\"label\"], c_obj[\"org_id\"]),\n )\n batch.append(c_obj)\n\n importer = channelImport.ChannelImport(batch, my_backend)\n # Don't commit just yet\n importer.will_commit = 0\n importer.run()\n return importer", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def create_suggestion(\n suggestion_type: str,\n target_type: str,\n target_id: str,\n target_version_at_submission: int,\n author_id: str,\n change_cmd: Mapping[str, change_domain.AcceptableChangeDictTypes],\n description: Optional[str]\n) -> suggestion_registry.BaseSuggestion:\n \"\"\"Creates a new SuggestionModel and the corresponding FeedbackThread.\n\n Args:\n suggestion_type: str. The type of the suggestion. This parameter should\n be one of the constants defined in storage/suggestion/gae_models.py.\n target_type: str. The target entity being edited. This parameter should\n be one of the constants defined in storage/suggestion/gae_models.py.\n target_id: str. The ID of the target entity being suggested to.\n target_version_at_submission: int. The version number of the target\n entity at the time of creation of the suggestion.\n author_id: str. The ID of the user who submitted the suggestion.\n change_cmd: dict. The details of the suggestion.\n description: str|None. The description of the changes provided by the\n author or None, if no description is provided.\n\n Returns:\n Suggestion. The newly created suggestion domain object.\n\n Raises:\n Exception. Invalid suggestion type.\n \"\"\"\n if description is None:\n description = DEFAULT_SUGGESTION_THREAD_SUBJECT\n thread_id = feedback_services.create_thread(\n target_type, target_id, author_id, description,\n DEFAULT_SUGGESTION_THREAD_INITIAL_MESSAGE, has_suggestion=True)\n\n status = suggestion_models.STATUS_IN_REVIEW\n\n if target_type == feconf.ENTITY_TYPE_EXPLORATION:\n exploration = exp_fetchers.get_exploration_by_id(target_id)\n if suggestion_type == feconf.SUGGESTION_TYPE_EDIT_STATE_CONTENT:\n score_category = ('%s%s%s' % (\n suggestion_models.SCORE_TYPE_CONTENT,\n suggestion_models.SCORE_CATEGORY_DELIMITER, exploration.category\n ))\n # Suggestions of this type do not have an associated language code,\n # since they are not queryable by language.\n language_code = None\n suggestion: AllowedSuggestionClasses = (\n suggestion_registry.SuggestionEditStateContent(\n thread_id, target_id, target_version_at_submission, status,\n author_id, None, change_cmd, score_category, language_code,\n False, datetime.datetime.utcnow(),\n datetime.datetime.utcnow()\n )\n )\n elif suggestion_type == feconf.SUGGESTION_TYPE_TRANSLATE_CONTENT:\n score_category = ('%s%s%s' % (\n suggestion_models.SCORE_TYPE_TRANSLATION,\n suggestion_models.SCORE_CATEGORY_DELIMITER, exploration.category)\n )\n # The language code of the translation, used for querying purposes.\n # Ruling out the possibility of any other type for mypy type checking.\n assert isinstance(change_cmd['language_code'], str)\n language_code = change_cmd['language_code']\n # Ruling out the possibility of any other type for mypy type checking.\n assert isinstance(change_cmd['state_name'], str)\n assert isinstance(change_cmd['content_id'], str)\n content_html = exploration.get_content_html(\n change_cmd['state_name'], change_cmd['content_id'])\n if content_html != change_cmd['content_html']:\n raise Exception(\n 'The Exploration content has changed since this translation '\n 'was submitted.')\n suggestion = suggestion_registry.SuggestionTranslateContent(\n thread_id, target_id, target_version_at_submission, status,\n author_id, None, change_cmd, score_category, language_code, False,\n datetime.datetime.utcnow(), datetime.datetime.utcnow())\n elif suggestion_type == feconf.SUGGESTION_TYPE_ADD_QUESTION:\n score_category = ('%s%s%s' % (\n suggestion_models.SCORE_TYPE_QUESTION,\n suggestion_models.SCORE_CATEGORY_DELIMITER, target_id)\n )\n # Ruling out the possibility of any other type for mypy type checking.\n assert isinstance(change_cmd['question_dict'], dict)\n # Here we use cast because we are narrowing down the type from\n # various Dict types that are present in AcceptableChangeDictTypes\n # to QuestionDict type.\n question_dict = cast(\n question_domain.QuestionDict,\n change_cmd['question_dict']\n )\n question_dict['language_code'] = (\n constants.DEFAULT_LANGUAGE_CODE)\n question_dict['question_state_data_schema_version'] = (\n feconf.CURRENT_STATE_SCHEMA_VERSION)\n # The language code of the question, used for querying purposes.\n add_question_language_code = constants.DEFAULT_LANGUAGE_CODE\n suggestion = suggestion_registry.SuggestionAddQuestion(\n thread_id, target_id, target_version_at_submission, status,\n author_id, None, change_cmd, score_category,\n add_question_language_code, False,\n datetime.datetime.utcnow(), datetime.datetime.utcnow()\n )\n else:\n raise Exception('Invalid suggestion type %s' % suggestion_type)\n suggestion.validate()\n\n suggestion_models.GeneralSuggestionModel.create(\n suggestion_type, target_type, target_id,\n target_version_at_submission, status, author_id,\n None, change_cmd, score_category, thread_id, suggestion.language_code)\n\n # Update the community contribution stats so that the number of suggestions\n # of this type that are in review increases by one.\n _update_suggestion_counts_in_community_contribution_stats([suggestion], 1)\n\n return get_suggestion_by_id(thread_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def build_entry(instance) -> BaseEntry:\n class_name = instance.__class__.__name__\n entry_class_name = f'{class_name}Entry'\n entry_class = getattr(current_module, entry_class_name, None)\n if not entry_class:\n raise Exception(f'Entry class {entry_class_name} is not found')\n return entry_class(instance)", "smellKey": "S112", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def test_nested_exception_in_finally_with_exception(self):\n hit_else = False\n hit_finally = False\n hit_except = False\n hit_inner_except = False\n hit_inner_else = False\n hit_inner_finally = False\n\n try:\n try:\n raise Exception('inner exception')\n except:\n hit_inner_except = True\n else:\n hit_inner_else = True\n finally:\n hit_inner_finally = True\n raise Exception('outer exception')\n except:\n hit_except = True\n else:\n hit_else = True\n finally:\n hit_finally = True\n\n\n self.assertTrue(hit_inner_except)\n self.assertFalse(hit_inner_else)\n self.assertTrue(hit_inner_finally)\n self.assertFalse(hit_else)\n self.assertTrue(hit_finally)\n self.assertTrue(hit_except)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def construct(self, tile_description: TileDescription = None,\n alignment_A: int = None,\n alignment_B: int = None,\n alignment_C: int = None) -> GemmOperationGrouped:\n \"\"\"\n Constructs a ``cutlass.backend.GemmOperationGrouped`` based on the input parameters and current\n kernel specification of the ``Gemm`` object.\n\n :param tile_description: tile description specifying shapes and operand types to use in the kernel\n :type tile_description: cutlass.backend.TileDescription\n :param alignment_A: alignment of operand A\n :type alignment_A: int\n :param alignment_B: alignment of operand B\n :type alignment_B: int\n :param alignment_C: alignment of operand C\n :type alignment_C: int\n\n :return: operation that was constructed\n :rtype: cutlass.backend.GemmOperationGrouped\n \"\"\"\n alignment_preference = max(self.possible_operations.alignments)\n alignment_A = check.alignment_or_default(alignment_A, alignment_preference)\n alignment_B = check.alignment_or_default(alignment_B, alignment_preference)\n alignment_C = check.alignment_or_default(alignment_C, alignment_preference)\n\n self.epilogue_functor = self._reset_epilogue_functor_alignment(alignment_C, self.epilogue_functor)\n\n tensor_A = TensorDescription(\n datatypes.binding_type(self._element_a),\n datatypes.binding_layout(self._layout_a),\n alignment_A\n )\n tensor_B = TensorDescription(\n datatypes.binding_type(self._element_b),\n datatypes.binding_layout(self._layout_b),\n alignment_B\n )\n tensor_C = TensorDescription(\n datatypes.binding_type(self._element_c),\n datatypes.binding_layout(self._layout_c),\n alignment_C\n )\n\n if tile_description is None:\n op = self.possible_operations.operations(alignment_A)[0]\n tile_description = datatypes.td_from_profiler_op(op)\n else:\n valid, err_str = self._valid_tile_description(tile_description)\n if not valid:\n raise Exception(f\"Invalid tile description. {err_str}\")\n self.tile_description = tile_description\n\n operation = GemmOperationGrouped(\n arch=self.current_cc,\n tile_description=tile_description,\n A=tensor_A, B=tensor_B, C=tensor_C,\n epilogue_functor=self.epilogue_functor,\n swizzling_functor=self._swizzling_functor,\n precompute_mode=SchedulerMode.Device)\n\n return operation", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def raiseExceptionIfFail(res):\n if \"success\" not in res and \"SUCC\" not in res: raise Exception(res)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def _getInterfaces(self, type):\n \"\"\"\n @param type : [\"pif\", \"bridge\", \"tap\"]\n @return : dictionary of Interface Objects\n get All Interfaces based on type\n \"\"\"\n devices = os.listdir('/sys/class/net')\n ifs = {}\n if type == \"pif\":\n devs = self.Parser.findall(Filter.Network.IFNAME_PIF, devices)\n for dev in set(devs):\n ifInst = OvmInterface()\n ifInst.name = dev\n ifs[dev] = ifInst\n\n elif type == \"vlan\":\n devs = self.Parser.findall(Filter.Network.IFNAME_VLAN, devices)\n for dev in set(devs):\n ifInst = OvmVlan()\n ifInst.name = dev\n (pif, vid) = dev.split('.')\n ifInst.pif = pif\n ifInst.vid = vid\n ifs[dev] = ifInst\n\n elif type == \"bridge\":\n devs = self.Parser.findall(Filter.Network.IFNAME_BRIDGE, devices)\n for dev in set(devs):\n ifInst = OvmBridge()\n ifInst.name = dev\n devs = os.listdir(join('/sys/class/net', dev, 'brif'))\n ifInst.interfaces = devs\n attches = self.Parser.findall(Filter.Network.IFNAME_PIF, devs) + self.Parser.findall(Filter.Network.IFNAME_VLAN, devs)\n if len(attches) > 1: raise Exception(\"Multiple PIF on bridge %s (%s)\"%(dev, attches))\n elif len(attches) == 0: ifInst.attach = \"null\"\n elif len(attches) == 1: ifInst.attach = attches[0]\n ifs[dev] = ifInst\n\n return ifs", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def test_with_exception_handler(self):\n exc_message = \"oh noooooo\"\n\n def broken_transformer(_data: ContextData) -> EvaluationContextDict:\n raise Exception(exc_message)\n\n context_builder = ContextBuilder[ContextData]().add_context_transformer(broken_transformer)\n\n with pytest.raises(Exception) as exc:\n context_builder.build(ContextData())\n\n assert exc.match(exc_message)\n\n # Ensure builder doesn't raise an exception\n context_builder.add_exception_handler(lambda _exc: None)\n context_builder.build(ContextData())\n\n with pytest.raises(Exception):\n context_builder.add_exception_handler(lambda _exc: None)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _validate_options(config: pytest.Config) -> None:\n if not config.option.build_dir:\n raise Exception('--build-dir has to be provided')\n if not os.path.isdir(config.option.build_dir):\n raise Exception(f'Provided --build-dir does not exist: {config.option.build_dir}')\n if not config.option.device_type:\n raise Exception('--device-type has to be provided')", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def run(boefje_meta: BoefjeMeta) -> list[tuple[set, bytes | str]]:\n input_ = boefje_meta.arguments[\"input\"]\n ip_port = input_[\"ip_port\"][\"port\"]\n address = input_[\"ip_port\"][\"address\"][\"address\"]\n\n if ip_address(address).version == 6:\n args = f\" --jsonfile tmp/output.json --server-preference -6 [{address}]:{ip_port}\"\n else:\n args = f\" --jsonfile tmp/output.json --server-preference {address}:{ip_port}\"\n\n timeout = getenv(\"TIMEOUT\", 30)\n\n environment_vars = {\"OPENSSL_TIMEOUT\": timeout, \"CONNECT_TIMEOUT\": timeout}\n\n client = docker.from_env()\n container = client.containers.run(SSL_TEST_IMAGE, args, detach=True, environment=environment_vars)\n\n try:\n container.wait(timeout=300)\n output = get_file_from_container(container, \"tmp/output.json\")\n except (APIError, RequestException) as e:\n logging.warning(\"DockerException occurred: %s\", e)\n container.stop()\n raise Exception(\"Error occurred (possibly a timeout) while running testssl.sh\")\n finally:\n container.remove()\n\n if not output:\n raise Exception(\"Couldn't get tmp/output.json from testsll container\")\n\n return [(set(), output)]", "smellKey": "S112", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def test_setslices_hardmask(self):\n # Tests setting slices w/ hardmask.\n base = self.base.copy()\n mbase = base.view(mrecarray)\n mbase.harden_mask()\n try:\n mbase[-2:] = (5, 5, 5)\n assert_equal(mbase.a._data, [1, 2, 3, 5, 5])\n assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 5, 5.5])\n assert_equal(mbase.c._data,\n [b'one', b'two', b'three', b'5', b'five'])\n assert_equal(mbase.a._mask, [0, 1, 0, 0, 1])\n assert_equal(mbase.b._mask, mbase.a._mask)\n assert_equal(mbase.b._mask, mbase.c._mask)\n except NotImplementedError:\n # OK, not implemented yet...\n pass\n except AssertionError:\n raise\n else:\n raise Exception(\"Flexible hard masks should be supported !\")\n # Not using a tuple should crash\n try:\n mbase[-2:] = 3\n except (NotImplementedError, TypeError):\n pass\n else:\n raise TypeError(\"Should have expected a readable buffer object!\")", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "async def test_info_endpoint_register_callback_exc(\n hass: HomeAssistant, hass_ws_client: WebSocketGenerator\n) -> None:\n \"\"\"Test that the info endpoint requires auth.\"\"\"\n\n async def mock_info(hass):\n raise Exception(\"TEST ERROR\")\n\n async_register_info(hass, \"lovelace\", mock_info)\n assert await async_setup_component(hass, \"system_health\", {})\n data = await gather_system_health_info(hass, hass_ws_client)\n\n assert len(data) == 1\n data = data[\"lovelace\"]\n assert data == {\"info\": {\"error\": {\"type\": \"failed\", \"error\": \"unknown\"}}}", "smellKey": "S112", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_cognito_userpool_access_token(email, password):\n \"\"\"\n Creates a temporary access token for utilizing the Pennsieve API. Utilizes email and password to authenticate with the Pennsieve Cognito Userpool \n which provides higher privileges than the API token and secret flow.\n \"\"\"\n \n\n try:\n response = requests.get(f\"{PENNSIEVE_URL}/authentication/cognito-config\")\n response.raise_for_status()\n cognito_app_client_id = response.json()[\"userPool\"][\"appClientId\"]\n cognito_region = response.json()[\"userPool\"][\"region\"]\n cognito_client = boto3.client(\n \"cognito-idp\",\n region_name=cognito_region,\n aws_access_key_id=\"\",\n aws_secret_access_key=\"\",\n )\n except Exception as e:\n raise Exception(e) from e\n\n try:\n login_response = cognito_client.initiate_auth(\n AuthFlow=\"USER_PASSWORD_AUTH\",\n AuthParameters={\"USERNAME\": email, \"PASSWORD\": password},\n ClientId=cognito_app_client_id,\n )\n except Exception as e:\n abort(400, \"Username or password was incorrect.\")\n\n try:\n access_token = login_response[\"AuthenticationResult\"][\"AccessToken\"]\n response = requests.get(\n f\"{PENNSIEVE_URL}/user\", headers={\"Authorization\": f\"Bearer {access_token}\"}\n )\n response.raise_for_status()\n except Exception as e:\n raise e\n\n return access_token", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def pipeline(\n task: str = None,\n model: Optional[Union[str, \"PreTrainedModel\", \"TFPreTrainedModel\"]] = None,\n config: Optional[Union[str, PretrainedConfig]] = None,\n tokenizer: Optional[Union[str, PreTrainedTokenizer, \"PreTrainedTokenizerFast\"]] = None,\n feature_extractor: Optional[Union[str, PreTrainedFeatureExtractor]] = None,\n image_processor: Optional[Union[str, BaseImageProcessor]] = None,\n processor: Optional[Union[str, ProcessorMixin]] = None,\n framework: Optional[str] = None,\n revision: Optional[str] = None,\n use_fast: bool = True,\n token: Optional[Union[str, bool]] = None,\n device: Optional[Union[int, str, \"torch.device\"]] = None,\n device_map=None,\n torch_dtype=None,\n trust_remote_code: Optional[bool] = None,\n model_kwargs: Dict[str, Any] = None,\n pipeline_class: Optional[Any] = None,\n **kwargs,\n) -> Pipeline:\n \"\"\"\n Utility factory method to build a [`Pipeline`].\n\n A pipeline consists of:\n\n - One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),\n [image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).\n - A [model](model) that generates predictions from the inputs.\n - Optional post-processing steps to refine the model's output, which can also be handled by processors.\n\n <Tip>\n While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,\n they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load\n required ones automatically. In case you want to provide these components explicitly, please refer to a\n specific pipeline in order to get more details regarding what components are required.\n </Tip>\n\n Args:\n task (`str`):\n The task defining which pipeline will be returned. Currently accepted tasks are:\n\n - `\"audio-classification\"`: will return a [`AudioClassificationPipeline`].\n - `\"automatic-speech-recognition\"`: will return a [`AutomaticSpeechRecognitionPipeline`].\n - `\"depth-estimation\"`: will return a [`DepthEstimationPipeline`].\n - `\"document-question-answering\"`: will return a [`DocumentQuestionAnsweringPipeline`].\n - `\"feature-extraction\"`: will return a [`FeatureExtractionPipeline`].\n - `\"fill-mask\"`: will return a [`FillMaskPipeline`]:.\n - `\"image-classification\"`: will return a [`ImageClassificationPipeline`].\n - `\"image-feature-extraction\"`: will return an [`ImageFeatureExtractionPipeline`].\n - `\"image-segmentation\"`: will return a [`ImageSegmentationPipeline`].\n - `\"image-to-image\"`: will return a [`ImageToImagePipeline`].\n - `\"image-to-text\"`: will return a [`ImageToTextPipeline`].\n - `\"mask-generation\"`: will return a [`MaskGenerationPipeline`].\n - `\"object-detection\"`: will return a [`ObjectDetectionPipeline`].\n - `\"question-answering\"`: will return a [`QuestionAnsweringPipeline`].\n - `\"summarization\"`: will return a [`SummarizationPipeline`].\n - `\"table-question-answering\"`: will return a [`TableQuestionAnsweringPipeline`].\n - `\"text2text-generation\"`: will return a [`Text2TextGenerationPipeline`].\n - `\"text-classification\"` (alias `\"sentiment-analysis\"` available): will return a\n [`TextClassificationPipeline`].\n - `\"text-generation\"`: will return a [`TextGenerationPipeline`]:.\n - `\"text-to-audio\"` (alias `\"text-to-speech\"` available): will return a [`TextToAudioPipeline`]:.\n - `\"token-classification\"` (alias `\"ner\"` available): will return a [`TokenClassificationPipeline`].\n - `\"translation\"`: will return a [`TranslationPipeline`].\n - `\"translation_xx_to_yy\"`: will return a [`TranslationPipeline`].\n - `\"video-classification\"`: will return a [`VideoClassificationPipeline`].\n - `\"visual-question-answering\"`: will return a [`VisualQuestionAnsweringPipeline`].\n - `\"zero-shot-classification\"`: will return a [`ZeroShotClassificationPipeline`].\n - `\"zero-shot-image-classification\"`: will return a [`ZeroShotImageClassificationPipeline`].\n - `\"zero-shot-audio-classification\"`: will return a [`ZeroShotAudioClassificationPipeline`].\n - `\"zero-shot-object-detection\"`: will return a [`ZeroShotObjectDetectionPipeline`].\n\n model (`str` or [`PreTrainedModel`] or [`TFPreTrainedModel`], *optional*):\n The model that will be used by the pipeline to make predictions. This can be a model identifier or an\n actual instance of a pretrained model inheriting from [`PreTrainedModel`] (for PyTorch) or\n [`TFPreTrainedModel`] (for TensorFlow).\n\n If not provided, the default for the `task` will be loaded.\n config (`str` or [`PretrainedConfig`], *optional*):\n The configuration that will be used by the pipeline to instantiate the model. This can be a model\n identifier or an actual pretrained model configuration inheriting from [`PretrainedConfig`].\n\n If not provided, the default configuration file for the requested model will be used. That means that if\n `model` is given, its default configuration will be used. However, if `model` is not supplied, this\n `task`'s default model's config is used instead.\n tokenizer (`str` or [`PreTrainedTokenizer`], *optional*):\n The tokenizer that will be used by the pipeline to encode data for the model. This can be a model\n identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`].\n\n If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model`\n is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string).\n However, if `config` is also not given or not a string, then the default tokenizer for the given `task`\n will be loaded.\n feature_extractor (`str` or [`PreTrainedFeatureExtractor`], *optional*):\n The feature extractor that will be used by the pipeline to encode data for the model. This can be a model\n identifier or an actual pretrained feature extractor inheriting from [`PreTrainedFeatureExtractor`].\n\n Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal\n models. Multi-modal models will also require a tokenizer to be passed.\n\n If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If\n `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it\n is a string). However, if `config` is also not given or not a string, then the default feature extractor\n for the given `task` will be loaded.\n image_processor (`str` or [`BaseImageProcessor`], *optional*):\n The image processor that will be used by the pipeline to preprocess images for the model. This can be a\n model identifier or an actual image processor inheriting from [`BaseImageProcessor`].\n\n Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal\n models will also require a tokenizer to be passed.\n\n If not provided, the default image processor for the given `model` will be loaded (if it is a string). If\n `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is\n a string).\n processor (`str` or [`ProcessorMixin`], *optional*):\n The processor that will be used by the pipeline to preprocess data for the model. This can be a model\n identifier or an actual processor inheriting from [`ProcessorMixin`].\n\n Processors are used for multi-modal models that require multi-modal inputs, for example, a model that\n requires both text and image inputs.\n\n If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model`\n is not specified or not a string, then the default processor for `config` is loaded (if it is a string).\n framework (`str`, *optional*):\n The framework to use, either `\"pt\"` for PyTorch or `\"tf\"` for TensorFlow. The specified framework must be\n installed.\n\n If no framework is specified, will default to the one currently installed. If no framework is specified and\n both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is\n provided.\n revision (`str`, *optional*, defaults to `\"main\"`):\n When passing a task name or a string model identifier: The specific model version to use. It can be a\n branch name, a tag name, or a commit id, since we use a git-based system for storing models and other\n artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n use_fast (`bool`, *optional*, defaults to `True`):\n Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]).\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated\n when running `huggingface-cli login` (stored in `~/.huggingface`).\n device (`int` or `str` or `torch.device`):\n Defines the device (*e.g.*, `\"cpu\"`, `\"cuda:1\"`, `\"mps\"`, or a GPU ordinal rank like `1`) on which this\n pipeline will be allocated.\n device_map (`str` or `Dict[str, Union[int, str, torch.device]`, *optional*):\n Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set\n `device_map=\"auto\"` to compute the most optimized `device_map` automatically (see\n [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)\n for more information).\n\n <Tip warning={true}>\n\n Do not use `device_map` AND `device` at the same time as they will conflict\n\n </Tip>\n\n torch_dtype (`str` or `torch.dtype`, *optional*):\n Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model\n (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`).\n trust_remote_code (`bool`, *optional*, defaults to `False`):\n Whether or not to allow for custom code defined on the Hub in their own modeling, configuration,\n tokenization or even pipeline files. This option should only be set to `True` for repositories you trust\n and in which you have read the code, as it will execute code present on the Hub on your local machine.\n model_kwargs (`Dict[str, Any]`, *optional*):\n Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,\n **model_kwargs)` function.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional keyword arguments passed along to the specific pipeline init (see the documentation for the\n corresponding pipeline class for possible values).\n\n Returns:\n [`Pipeline`]: A suitable pipeline for the task.\n\n Examples:\n\n ```python\n >>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer\n\n >>> # Sentiment analysis pipeline\n >>> analyzer = pipeline(\"sentiment-analysis\")\n\n >>> # Question answering pipeline, specifying the checkpoint identifier\n >>> oracle = pipeline(\n ... \"question-answering\", model=\"distilbert/distilbert-base-cased-distilled-squad\", tokenizer=\"google-bert/bert-base-cased\"\n ... )\n\n >>> # Named entity recognition pipeline, passing in a specific model and tokenizer\n >>> model = AutoModelForTokenClassification.from_pretrained(\"dbmdz/bert-large-cased-finetuned-conll03-english\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google-bert/bert-base-cased\")\n >>> recognizer = pipeline(\"ner\", model=model, tokenizer=tokenizer)\n ```\"\"\"\n if model_kwargs is None:\n model_kwargs = {}\n # Make sure we only pass use_auth_token once as a kwarg (it used to be possible to pass it in model_kwargs,\n # this is to keep BC).\n use_auth_token = model_kwargs.pop(\"use_auth_token\", None)\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\")\n token = use_auth_token\n\n code_revision = kwargs.pop(\"code_revision\", None)\n commit_hash = kwargs.pop(\"_commit_hash\", None)\n\n hub_kwargs = {\n \"revision\": revision,\n \"token\": token,\n \"trust_remote_code\": trust_remote_code,\n \"_commit_hash\": commit_hash,\n }\n\n if task is None and model is None:\n raise RuntimeError(\n \"Impossible to instantiate a pipeline without either a task or a model \"\n \"being specified. \"\n \"Please provide a task class or a model\"\n )\n\n if model is None and tokenizer is not None:\n raise RuntimeError(\n \"Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer\"\n \" may not be compatible with the default model. Please provide a PreTrainedModel class or a\"\n \" path/identifier to a pretrained model when providing tokenizer.\"\n )\n if model is None and feature_extractor is not None:\n raise RuntimeError(\n \"Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided\"\n \" feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class\"\n \" or a path/identifier to a pretrained model when providing feature_extractor.\"\n )\n if isinstance(model, Path):\n model = str(model)\n\n if commit_hash is None:\n pretrained_model_name_or_path = None\n if isinstance(config, str):\n pretrained_model_name_or_path = config\n elif config is None and isinstance(model, str):\n pretrained_model_name_or_path = model\n\n if not isinstance(config, PretrainedConfig) and pretrained_model_name_or_path is not None:\n # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible\n resolved_config_file = cached_file(\n pretrained_model_name_or_path,\n CONFIG_NAME,\n _raise_exceptions_for_gated_repo=False,\n _raise_exceptions_for_missing_entries=False,\n _raise_exceptions_for_connection_errors=False,\n cache_dir=model_kwargs.get(\"cache_dir\"),\n **hub_kwargs,\n )\n hub_kwargs[\"_commit_hash\"] = extract_commit_hash(resolved_config_file, commit_hash)\n else:\n hub_kwargs[\"_commit_hash\"] = getattr(config, \"_commit_hash\", None)\n\n # Config is the primordial information item.\n # Instantiate config if needed\n if isinstance(config, str):\n config = AutoConfig.from_pretrained(\n config, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs\n )\n hub_kwargs[\"_commit_hash\"] = config._commit_hash\n elif config is None and isinstance(model, str):\n # Check for an adapter file in the model path if PEFT is available\n if is_peft_available():\n # `find_adapter_config_file` doesn't accept `trust_remote_code`\n _hub_kwargs = {k: v for k, v in hub_kwargs.items() if k != \"trust_remote_code\"}\n maybe_adapter_path = find_adapter_config_file(\n model,\n token=hub_kwargs[\"token\"],\n revision=hub_kwargs[\"revision\"],\n _commit_hash=hub_kwargs[\"_commit_hash\"],\n )\n\n if maybe_adapter_path is not None:\n with open(maybe_adapter_path, \"r\", encoding=\"utf-8\") as f:\n adapter_config = json.load(f)\n model = adapter_config[\"base_model_name_or_path\"]\n\n config = AutoConfig.from_pretrained(\n model, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs\n )\n hub_kwargs[\"_commit_hash\"] = config._commit_hash\n\n custom_tasks = {}\n if config is not None and len(getattr(config, \"custom_pipelines\", {})) > 0:\n custom_tasks = config.custom_pipelines\n if task is None and trust_remote_code is not False:\n if len(custom_tasks) == 1:\n task = list(custom_tasks.keys())[0]\n else:\n raise RuntimeError(\n \"We can't infer the task automatically for this model as there are multiple tasks available. Pick \"\n f\"one in {', '.join(custom_tasks.keys())}\"\n )\n\n if task is None and model is not None:\n if not isinstance(model, str):\n raise RuntimeError(\n \"Inferring the task automatically requires to check the hub with a model_id defined as a `str`. \"\n f\"{model} is not a valid model_id.\"\n )\n task = get_task(model, token)\n\n # Retrieve the task\n if task in custom_tasks:\n normalized_task = task\n targeted_task, task_options = clean_custom_task(custom_tasks[task])\n if pipeline_class is None:\n if not trust_remote_code:\n raise ValueError(\n \"Loading this pipeline requires you to execute the code in the pipeline file in that\"\n \" repo on your local machine. Make sure you have read the code there to avoid malicious use, then\"\n \" set the option `trust_remote_code=True` to remove this error.\"\n )\n class_ref = targeted_task[\"impl\"]\n pipeline_class = get_class_from_dynamic_module(\n class_ref,\n model,\n code_revision=code_revision,\n **hub_kwargs,\n )\n else:\n normalized_task, targeted_task, task_options = check_task(task)\n if pipeline_class is None:\n pipeline_class = targeted_task[\"impl\"]\n\n # Use default model/config/tokenizer for the task if no model is provided\n if model is None:\n # At that point framework might still be undetermined\n model, default_revision = get_default_model_and_revision(targeted_task, framework, task_options)\n revision = revision if revision is not None else default_revision\n logger.warning(\n f\"No model was supplied, defaulted to {model} and revision\"\n f\" {revision} ({HUGGINGFACE_CO_RESOLVE_ENDPOINT}/{model}).\\n\"\n \"Using a pipeline without specifying a model name and revision in production is not recommended.\"\n )\n hub_kwargs[\"revision\"] = revision\n if config is None and isinstance(model, str):\n config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)\n hub_kwargs[\"_commit_hash\"] = config._commit_hash\n\n if device_map is not None:\n if \"device_map\" in model_kwargs:\n raise ValueError(\n 'You cannot use both `pipeline(... device_map=..., model_kwargs={\"device_map\":...})` as those'\n \" arguments might conflict, use only one.)\"\n )\n if device is not None:\n logger.warning(\n \"Both `device` and `device_map` are specified. `device` will override `device_map`. You\"\n \" will most likely encounter unexpected behavior. Please remove `device` and keep `device_map`.\"\n )\n model_kwargs[\"device_map\"] = device_map\n if torch_dtype is not None:\n if \"torch_dtype\" in model_kwargs:\n raise ValueError(\n 'You cannot use both `pipeline(... torch_dtype=..., model_kwargs={\"torch_dtype\":...})` as those'\n \" arguments might conflict, use only one.)\"\n )\n if isinstance(torch_dtype, str) and hasattr(torch, torch_dtype):\n torch_dtype = getattr(torch, torch_dtype)\n model_kwargs[\"torch_dtype\"] = torch_dtype\n\n model_name = model if isinstance(model, str) else None\n\n # Load the correct model if possible\n # Infer the framework from the model if not already defined\n if isinstance(model, str) or framework is None:\n model_classes = {\"tf\": targeted_task[\"tf\"], \"pt\": targeted_task[\"pt\"]}\n framework, model = infer_framework_load_model(\n model,\n model_classes=model_classes,\n config=config,\n framework=framework,\n task=task,\n **hub_kwargs,\n **model_kwargs,\n )\n\n model_config = model.config\n hub_kwargs[\"_commit_hash\"] = model.config._commit_hash\n\n load_tokenizer = type(model_config) in TOKENIZER_MAPPING or model_config.tokenizer_class is not None\n load_feature_extractor = type(model_config) in FEATURE_EXTRACTOR_MAPPING or feature_extractor is not None\n load_image_processor = type(model_config) in IMAGE_PROCESSOR_MAPPING or image_processor is not None\n load_processor = type(model_config) in PROCESSOR_MAPPING or processor is not None\n\n # Check that pipeline class required loading\n load_tokenizer = load_tokenizer and pipeline_class._load_tokenizer\n load_feature_extractor = load_feature_extractor and pipeline_class._load_feature_extractor\n load_image_processor = load_image_processor and pipeline_class._load_image_processor\n load_processor = load_processor and pipeline_class._load_processor\n\n # If `model` (instance of `PretrainedModel` instead of `str`) is passed (and/or same for config), while\n # `image_processor` or `feature_extractor` is `None`, the loading will fail. This happens particularly for some\n # vision tasks when calling `pipeline()` with `model` and only one of the `image_processor` and `feature_extractor`.\n # TODO: we need to make `NO_IMAGE_PROCESSOR_TASKS` and `NO_FEATURE_EXTRACTOR_TASKS` more robust to avoid such issue.\n # This block is only temporarily to make CI green.\n if load_image_processor and load_feature_extractor:\n load_feature_extractor = False\n\n if (\n tokenizer is None\n and not load_tokenizer\n and normalized_task not in NO_TOKENIZER_TASKS\n # Using class name to avoid importing the real class.\n and (\n model_config.__class__.__name__ in MULTI_MODEL_AUDIO_CONFIGS\n or model_config.__class__.__name__ in MULTI_MODEL_VISION_CONFIGS\n )\n ):\n # This is a special category of models, that are fusions of multiple models\n # so the model_config might not define a tokenizer, but it seems to be\n # necessary for the task, so we're force-trying to load it.\n load_tokenizer = True\n if (\n image_processor is None\n and not load_image_processor\n and normalized_task not in NO_IMAGE_PROCESSOR_TASKS\n # Using class name to avoid importing the real class.\n and model_config.__class__.__name__ in MULTI_MODEL_VISION_CONFIGS\n ):\n # This is a special category of models, that are fusions of multiple models\n # so the model_config might not define a tokenizer, but it seems to be\n # necessary for the task, so we're force-trying to load it.\n load_image_processor = True\n if (\n feature_extractor is None\n and not load_feature_extractor\n and normalized_task not in NO_FEATURE_EXTRACTOR_TASKS\n # Using class name to avoid importing the real class.\n and model_config.__class__.__name__ in MULTI_MODEL_AUDIO_CONFIGS\n ):\n # This is a special category of models, that are fusions of multiple models\n # so the model_config might not define a tokenizer, but it seems to be\n # necessary for the task, so we're force-trying to load it.\n load_feature_extractor = True\n\n if task in NO_TOKENIZER_TASKS:\n # These will never require a tokenizer.\n # the model on the other hand might have a tokenizer, but\n # the files could be missing from the hub, instead of failing\n # on such repos, we just force to not load it.\n load_tokenizer = False\n\n if task in NO_FEATURE_EXTRACTOR_TASKS:\n load_feature_extractor = False\n if task in NO_IMAGE_PROCESSOR_TASKS:\n load_image_processor = False\n\n if load_tokenizer:\n # Try to infer tokenizer from model or config name (if provided as str)\n if tokenizer is None:\n if isinstance(model_name, str):\n tokenizer = model_name\n elif isinstance(config, str):\n tokenizer = config\n else:\n # Impossible to guess what is the right tokenizer here\n raise Exception(\n \"Impossible to guess which tokenizer to use. \"\n \"Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer.\"\n )\n\n # Instantiate tokenizer if needed\n if isinstance(tokenizer, (str, tuple)):\n if isinstance(tokenizer, tuple):\n # For tuple we have (tokenizer name, {kwargs})\n use_fast = tokenizer[1].pop(\"use_fast\", use_fast)\n tokenizer_identifier = tokenizer[0]\n tokenizer_kwargs = tokenizer[1]\n else:\n tokenizer_identifier = tokenizer\n tokenizer_kwargs = model_kwargs.copy()\n tokenizer_kwargs.pop(\"torch_dtype\", None)\n\n tokenizer = AutoTokenizer.from_pretrained(\n tokenizer_identifier, use_fast=use_fast, _from_pipeline=task, **hub_kwargs, **tokenizer_kwargs\n )\n\n if load_image_processor:\n # Try to infer image processor from model or config name (if provided as str)\n if image_processor is None:\n if isinstance(model_name, str):\n image_processor = model_name\n elif isinstance(config, str):\n image_processor = config\n # Backward compatibility, as `feature_extractor` used to be the name\n # for `ImageProcessor`.\n elif feature_extractor is not None and isinstance(feature_extractor, BaseImageProcessor):\n image_processor = feature_extractor\n else:\n # Impossible to guess what is the right image_processor here\n raise Exception(\n \"Impossible to guess which image processor to use. \"\n \"Please provide a PreTrainedImageProcessor class or a path/identifier \"\n \"to a pretrained image processor.\"\n )\n\n # Instantiate image_processor if needed\n if isinstance(image_processor, (str, tuple)):\n image_processor = AutoImageProcessor.from_pretrained(\n image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs\n )\n\n if load_feature_extractor:\n # Try to infer feature extractor from model or config name (if provided as str)\n if feature_extractor is None:\n if isinstance(model_name, str):\n feature_extractor = model_name\n elif isinstance(config, str):\n feature_extractor = config\n else:\n # Impossible to guess what is the right feature_extractor here\n raise Exception(\n \"Impossible to guess which feature extractor to use. \"\n \"Please provide a PreTrainedFeatureExtractor class or a path/identifier \"\n \"to a pretrained feature extractor.\"\n )\n\n # Instantiate feature_extractor if needed\n if isinstance(feature_extractor, (str, tuple)):\n feature_extractor = AutoFeatureExtractor.from_pretrained(\n feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs\n )\n\n if (\n feature_extractor._processor_class\n and feature_extractor._processor_class.endswith(\"WithLM\")\n and isinstance(model_name, str)\n ):\n try:\n import kenlm # to trigger `ImportError` if not installed\n from pyctcdecode import BeamSearchDecoderCTC\n\n if os.path.isdir(model_name) or os.path.isfile(model_name):\n decoder = BeamSearchDecoderCTC.load_from_dir(model_name)\n else:\n language_model_glob = os.path.join(\n BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, \"*\"\n )\n alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME\n allow_patterns = [language_model_glob, alphabet_filename]\n decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns)\n\n kwargs[\"decoder\"] = decoder\n except ImportError as e:\n logger.warning(f\"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {e}\")\n if not is_kenlm_available():\n logger.warning(\"Try to install `kenlm`: `pip install kenlm\")\n\n if not is_pyctcdecode_available():\n logger.warning(\"Try to install `pyctcdecode`: `pip install pyctcdecode\")\n\n if load_processor:\n # Try to infer processor from model or config name (if provided as str)\n if processor is None:\n if isinstance(model_name, str):\n processor = model_name\n elif isinstance(config, str):\n processor = config\n else:\n # Impossible to guess what is the right processor here\n raise Exception(\n \"Impossible to guess which processor to use. \"\n \"Please provide a processor instance or a path/identifier \"\n \"to a processor.\"\n )\n\n # Instantiate processor if needed\n if isinstance(processor, (str, tuple)):\n processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)\n if not isinstance(processor, ProcessorMixin):\n raise TypeError(\n \"Processor was loaded, but it is not an instance of `ProcessorMixin`. \"\n f\"Got type `{type(processor)}` instead. Please check that you specified \"\n \"correct pipeline task for the model and model has processor implemented and saved.\"\n )\n\n if task == \"translation\" and model.config.task_specific_params:\n for key in model.config.task_specific_params:\n if key.startswith(\"translation\"):\n task = key\n warnings.warn(\n f'\"translation\" task was used, instead of \"translation_XX_to_YY\", defaulting to \"{task}\"',\n UserWarning,\n )\n break\n\n if tokenizer is not None:\n kwargs[\"tokenizer\"] = tokenizer\n\n if feature_extractor is not None:\n kwargs[\"feature_extractor\"] = feature_extractor\n\n if torch_dtype is not None:\n kwargs[\"torch_dtype\"] = torch_dtype\n\n if image_processor is not None:\n kwargs[\"image_processor\"] = image_processor\n\n if device is not None:\n kwargs[\"device\"] = device\n\n if processor is not None:\n kwargs[\"processor\"] = processor\n\n return pipeline_class(model=model, framework=framework, task=task, **kwargs)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "@classmethod\n def create(cls, author_id: str) -> AuthorBlogPostReadsAggregatedStatsModel:\n \"\"\"Creates a new AuthorBlogPostReadsAggregatedStatsModel entry.\n\n Args:\n author_id: str. User ID of author.\n\n Returns:\n AuthorBlogPostReadsAggregatedStatsModel. The newly created\n AuthorBlogPostReadsAggregatedStatsModel instance.\n\n Raises:\n Exception. A reads stats model with the given author ID exists\n already.\n \"\"\"\n if cls.get_by_id(author_id):\n raise Exception(\n 'A author blog post reads stats model with the given author ID'\n ' exists already.')\n\n entity = cls(\n id=author_id,\n reads_by_hour={},\n reads_by_date={},\n reads_by_month={}\n )\n entity.update_timestamps()\n entity.put()\n\n return entity", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def remove_uncategorized_skill_id(\n self, uncategorized_skill_id: str\n ) -> None:\n \"\"\"Updates the skill id list of a topic object.\n\n Args:\n uncategorized_skill_id: str. The skill id to be removed from the\n uncategorized_skill_ids list.\n\n Raises:\n Exception. The given skill id is not present in the\n uncategorized_skill_ids list.\n \"\"\"\n if uncategorized_skill_id not in self.uncategorized_skill_ids:\n raise Exception(\n 'The skill id %s is not present in the topic.'\n % uncategorized_skill_id)\n\n if uncategorized_skill_id in self.skill_ids_for_diagnostic_test:\n self.skill_ids_for_diagnostic_test.remove(uncategorized_skill_id)\n self.uncategorized_skill_ids.remove(uncategorized_skill_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_origin_manifest_id(dataset_id):\n global namespace_logger\n max_attempts = 3\n for _ in range(max_attempts):\n manifests = get_upload_manifests(dataset_id)\n if manifests and \"manifests\" in manifests and manifests[\"manifests\"]:\n # sort the manifests list by date_created timestamp field in descending order\n manifests[\"manifests\"].sort(key=lambda x: x[\"date_created\"], reverse=True)\n return manifests[\"manifests\"][0][\"id\"]\n time.sleep(5) # Wait for 5 seconds before the next attempt\n\n raise Exception(\"Did not get the origin manifest id in an expected amount of time.\")", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def delete_content_id_for_voiceover(self, content_id: str) -> None:\n \"\"\"Deletes a content id from the voiceovers_mapping dict.\n\n Args:\n content_id: str. The id representing a subtitled html.\n\n Raises:\n Exception. The content id isn't a string.\n Exception. The content id does not exist in the voiceovers_mapping\n dict.\n \"\"\"\n if not isinstance(content_id, str):\n raise Exception(\n 'Expected content_id to be a string, received %s' % content_id)\n if content_id not in self.voiceovers_mapping:\n raise Exception(\n 'The content_id %s does not exist.' % content_id)\n\n self.voiceovers_mapping.pop(content_id, None)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def add_additional_story(self, story_id: str) -> None:\n \"\"\"Adds a story to the additional_story_references list.\n\n Args:\n story_id: str. The story id to add to the list.\n\n Raises:\n Exception. The story ID is already present in the additional\n story references list of the topic.\n \"\"\"\n additional_story_ids = self.get_additional_story_ids()\n if story_id in additional_story_ids:\n raise Exception(\n 'The story_id %s is already present in the additional '\n 'story references list of the topic.' % story_id)\n self.additional_story_references.append(\n StoryReference.create_default_story_reference(story_id)\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def validate_metadata_directories() -> None:\n \"\"\"Validates that each library installed in the 'third_party/python_libs'\n has a corresponding metadata directory following the correct naming\n conventions detailed in PEP-427, PEP-376, and common Python guidelines.\n\n Raises:\n Exception. An installed library's metadata does not exist in the\n 'third_party/python_libs' directory in the format which we expect\n (following the PEP-427 and PEP-376 python guidelines).\n \"\"\"\n directory_contents = _get_third_party_python_libs_directory_contents()\n # Each python metadata directory name contains a python library name that\n # does not have uniform case. This is because we cannot guarantee the casing\n # of the directory names generated and there are no options that we can\n # provide to `pip install` to actually guarantee that a certain casing\n # format is used to create the directory names. The only official guidelines\n # for naming directories is that it must start with the string:\n # '<library_name>-<library-version>' but no casing guidelines are specified.\n # Therefore, in order to efficiently check if a python library's metadata\n # exists in a directory, we need to normalize the directory name. Otherwise,\n # we would need to check every permutation of the casing.\n normalized_directory_names = {\n normalize_directory_name(name)\n for name in os.listdir(common.THIRD_PARTY_PYTHON_LIBS_DIR)\n if os.path.isdir(os.path.join(common.THIRD_PARTY_PYTHON_LIBS_DIR, name))\n }\n for normalized_library_name, version_string in directory_contents.items():\n # Direct URL libraries are guaranteed to have metadata directories,\n # because that's how _get_third_party_python_libs_directory_contents\n # obtains the version_string being checked here.\n if version_string.startswith('git+'):\n continue\n # Possible names of the metadata directory installed when <library_name>\n # is installed.\n possible_normalized_directory_names = (\n _get_possible_normalized_metadata_directory_names(\n normalized_library_name, version_string))\n # If any of the possible metadata directory names show up in the\n # directory, that is confirmation that <library_name> was installed\n # correctly with the correct metadata.\n if not any(\n normalized_directory_name in normalized_directory_names\n for normalized_directory_name in\n possible_normalized_directory_names):\n raise Exception(\n 'The python library %s was installed without the correct '\n 'metadata folders which may indicate that the convention for '\n 'naming the metadata folders have changed. Please go to '\n '`scripts/install_python_prod_dependencies` and modify our '\n 'assumptions in the '\n '_get_possible_normalized_metadata_directory_names'\n ' function for what metadata directory names can be.' %\n normalized_library_name)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def catch_fails(self, object_):\n \"\"\"Catching 'object_' should raise a TypeError.\"\"\"\n try:\n try:\n raise Exception\n except object_:\n pass\n except TypeError:\n pass\n except Exception:\n self.fail(\"TypeError expected when catching %s\" % type(object_))\n\n try:\n try:\n raise Exception\n except (object_,):\n pass\n except TypeError:\n return\n except Exception:\n self.fail(\"TypeError expected when catching %s as specified in a \"\n \"tuple\" % type(object_))", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def _reset_options(self, cc: int):\n \"\"\"\n Resets the kernel options based on cc\n\n :param cc: compute capability to reset to\n :type cc: int\n \"\"\"\n if cc != self.current_cc:\n if cc not in _generator_ccs:\n raise Exception(f'Invalid CC for CUTLASS kernels: {cc}.')\n self.current_cc = cc\n self.options = option_registry.options_for_cc(self.current_cc, self.operation_kind)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def update_user_group(\n user_group_id: str,\n name: str,\n member_usernames: List[str]\n) -> None:\n \"\"\"Updates the user group.\n\n Args:\n user_group_id: str. The user group id.\n name: str. The new name of the user group if needs to\n be updated else old name of the user group.\n member_usernames: List[str]. The list of user usernames for\n the specified user group.\n\n Raises:\n Exception. The user group trying to update does not exist.\n \"\"\"\n user_group_model = user_models.UserGroupModel.get(\n user_group_id, strict=False)\n if user_group_model is None:\n raise Exception(f'User group {name} does not exist.')\n assert user_group_model is not None\n\n if len(member_usernames) > 0:\n _check_if_usernames_are_valid(name, member_usernames)\n\n user_group = user_domain.UserGroup(\n user_group_id, name, member_usernames\n )\n user_group.validate()\n\n user_ids = get_multi_user_ids_from_usernames(member_usernames)\n\n user_group_model.user_ids = user_ids\n user_group_model.name = name\n user_group_model.update_timestamps()\n user_group_model.put()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def process_tx(experiments, tx):\n exp_id = tx['experiment_id']\n # Block time is nanoseconds from the epoch - convert to seconds\n block_time = float(tx['block_time']) / (10**9)\n # Duration is also in nanoseconds - convert to seconds\n duration = float(tx['duration_ns']) / (10**9)\n connections = int(tx['connections'])\n rate = int(tx['rate'])\n\n if exp_id not in experiments:\n experiments[exp_id] = {\n 'connections': connections,\n 'rate': rate,\n 'block_time_min': block_time,\n # We keep track of the latency associated with the minimum block\n # time to estimate the start time of the experiment\n 'block_time_min_duration': duration,\n 'block_time_max': block_time,\n 'total_latencies': duration,\n 'tx_count': 1,\n }\n logging.info('Found experiment %s with rate=%d, connections=%d' %\n (exp_id, rate, connections))\n else:\n # Validation\n for field in ['connections', 'rate']:\n val = int(tx[field])\n if val != experiments[exp_id][field]:\n raise Exception(\n 'Found multiple distinct values for field '\n '\"%s\" for the same experiment (%s): %d and %d' %\n (field, exp_id, val, experiments[exp_id][field]))\n\n if block_time < experiments[exp_id]['block_time_min']:\n experiments[exp_id]['block_time_min'] = block_time\n experiments[exp_id]['block_time_min_duration'] = duration\n if block_time > experiments[exp_id]['block_time_max']:\n experiments[exp_id]['block_time_max'] = block_time\n\n experiments[exp_id]['total_latencies'] += duration\n experiments[exp_id]['tx_count'] += 1\n\n return experiments", "smellKey": "S112", "smellId": null, "repo": "0xPolygon_cometbft", "language": "python"} {"function": "def parse_args():\n parser = argparse.ArgumentParser(description='Transpile web-uis')\n parser.add_argument('-p', '--production',\n action='store_true',\n help='Uses production config')\n parser.add_argument('--entry',\n action='append',\n help='Entry points',\n required=True)\n parser.add_argument('--output_path', nargs=1)\n parser.add_argument('--root_gen_dir', nargs=1)\n parser.add_argument('--depfile_path', nargs=1)\n parser.add_argument('--grd_name', nargs=1)\n parser.add_argument('--resource_name', nargs=1)\n parser.add_argument('--public_asset_path', nargs='?')\n parser.add_argument('--webpack_alias',\n action='append',\n help='Webpack alias',\n required=False,\n default=[])\n parser.add_argument('--output_module', action='store_true')\n parser.add_argument(\n \"--resource_path_prefix\",\n nargs='?',\n help=\"The resource path prefix. Used in grit part files.\")\n parser.add_argument('--extra_modules',\n action='append',\n help='Extra paths to find modules',\n required=False,\n default=[])\n\n args = parser.parse_args()\n # validate args\n if (args.output_path is None or len(args.output_path) != 1 or\n len(args.output_path[0]) == 0):\n raise Exception(\" output_path argument was not specified correctly\")\n # args are valid\n return args", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def test_getfile_broken_repr(self):\n class ErrorRepr:\n def __repr__(self):\n raise Exception('xyz')\n er = ErrorRepr()\n with self.assertRaises(TypeError):\n inspect.getfile(er)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@staticmethod\n def createFromTemplate(poolUuid, templateUrl):\n try:\n if not exists(templateUrl):\n raise Exception(\"Cannot find template:%s\"%templateUrl)\n sr = OvmStoragePool()._getSrByNameLable(poolUuid)\n volDirUuid = get_uuid()\n volUuid = get_uuid()\n priStorageMountPoint = sr.mountpoint\n volDir = join(priStorageMountPoint, 'running_pool', volDirUuid)\n if exists(volDir):\n raise Exception(\"Volume dir %s already existed, can not override\"%volDir)\n os.makedirs(volDir)\n OvmStoragePool()._checkDirSizeForImage(volDir, templateUrl)\n volName = volUuid + '.raw'\n tgt = join(volDir, volName)\n cpVolCmd = ['cp', templateUrl, tgt]\n doCmd(cpVolCmd)\n volSize = os.path.getsize(tgt)\n vol = OvmVolume()\n vol.name = volName\n vol.path = tgt\n vol.size = volSize\n vol.uuid = volUuid\n vol.poolUuid = poolUuid\n rs = fromOvmVolume(vol)\n logger.debug(OvmVolume.createFromTemplate, rs)\n return rs\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmVolume.createFromTemplate, errmsg)\n raise XmlRpcFault(toErrCode(OvmVolume, OvmVolume.createFromTemplate), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def CreateParaviewItemsForImagesetC(inImageset):\n \"\"\"given a json block structure as discussed in the catalyst sierra\n insitu wiki, create the corresponding one imageset (view) based on\n a particular imageset block and the availa\"\"\"\n\n theCamera = inImageset.mCamera\n\n #we are setting this up, for now, so that you MUST have a camera at this\n #point--default should have been added and referenced earlier\n if theCamera == None:\n errStr = 'error! theCamera is None in \"\\\n \"CreateParaviewItemsForImagesetC\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n cameraLookDirectionAndFilenameAddonList = GetLookDirectionListFromCamera(theCamera)\n\n #counter = 0\n for oneItem in cameraLookDirectionAndFilenameAddonList:\n #print oneItem\n oneDirection = oneItem[0]\n oneDirectionFilenameAddon = oneItem[1]\n CreateParaViewRepresentationAndViewFromInfoC(inImageset, oneDirection,\n oneDirectionFilenameAddon)\n #counter = counter + 1", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def release(args):\n env = create_build_env()\n fmt_repo = env.fmt_repo\n\n branch = args.get('<branch>')\n if branch is None:\n branch = 'master'\n if not fmt_repo.update('-b', branch, fmt_repo_url):\n clean_checkout(fmt_repo, branch)\n\n # Convert changelog from RST to GitHub-flavored Markdown and get the\n # version.\n changelog = 'ChangeLog.rst'\n changelog_path = os.path.join(fmt_repo.dir, changelog)\n import rst2md\n changes, version = rst2md.convert(changelog_path)\n cmakelists = 'CMakeLists.txt'\n for line in fileinput.input(os.path.join(fmt_repo.dir, cmakelists),\n inplace=True):\n prefix = 'set(FMT_VERSION '\n if line.startswith(prefix):\n line = prefix + version + ')\\n'\n sys.stdout.write(line)\n\n # Update the version in the changelog.\n title_len = 0\n for line in fileinput.input(changelog_path, inplace=True):\n if line.startswith(version + ' - TBD'):\n line = version + ' - ' + datetime.date.today().isoformat()\n title_len = len(line)\n line += '\\n'\n elif title_len:\n line = '-' * title_len + '\\n'\n title_len = 0\n sys.stdout.write(line)\n\n # Add the version to the build script.\n script = os.path.join('doc', 'build.py')\n script_path = os.path.join(fmt_repo.dir, script)\n for line in fileinput.input(script_path, inplace=True):\n m = re.match(r'( *versions = )\\[(.+)\\]', line)\n if m:\n line = '{}[{}, \\'{}\\']\\n'.format(m.group(1), m.group(2), version)\n sys.stdout.write(line)\n\n fmt_repo.checkout('-B', 'release')\n fmt_repo.add(changelog, cmakelists, script)\n fmt_repo.commit('-m', 'Update version')\n\n # Build the docs and package.\n run = Runner(fmt_repo.dir)\n run('cmake', '.')\n run('make', 'doc', 'package_source')\n update_site(env)\n\n # Create a release on GitHub.\n fmt_repo.push('origin', 'release')\n auth_headers = {'Authorization': 'token ' + os.getenv('FMT_TOKEN')}\n r = requests.post('https://api.github.com/repos/fmtlib/fmt/releases',\n headers=auth_headers,\n data=json.dumps({'tag_name': version,\n 'target_commitish': 'release',\n 'body': changes, 'draft': True}))\n if r.status_code != 201:\n raise Exception('Failed to create a release ' + str(r))\n id = r.json()['id']\n uploads_url = 'https://uploads.github.com/repos/fmtlib/fmt/releases'\n package = 'fmt-{}.zip'.format(version)\n r = requests.post(\n '{}/{}/assets?name={}'.format(uploads_url, id, package),\n headers={'Content-Type': 'application/zip'} | auth_headers,\n data=open('build/fmt/' + package, 'rb'))\n if r.status_code != 201:\n raise Exception('Failed to upload an asset ' + str(r))", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_dolphin", "language": "python"} {"function": "def acquire(self, key: str, duration: int, routing_key: str | None = None) -> None:\n client = self.get_client(key, routing_key)\n full_key = self.prefix_key(key)\n if client.set(full_key, self.uuid, ex=duration, nx=True) is not True:\n raise Exception(f\"Could not set key: {full_key!r}\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@acl_decorators.get_decorator_for_accepting_suggestion(\n acl_decorators.can_edit_exploration)\n def put(self, target_id: str, suggestion_id: str) -> None:\n \"\"\"Handles PUT requests.\n\n Args:\n target_id: str. The ID of the suggestion target.\n suggestion_id: str. The ID of the suggestion.\n\n Raises:\n Exception. The 'commit_message' must be provided when the\n action is 'accept suggestion'.\n \"\"\"\n assert self.user_id is not None\n assert self.normalized_payload is not None\n if (\n suggestion_id.split('.')[0] !=\n feconf.ENTITY_TYPE_EXPLORATION):\n raise self.InvalidInputException(\n 'This handler allows actions only'\n ' on suggestions to explorations.')\n\n if suggestion_id.split('.')[1] != target_id:\n raise self.InvalidInputException(\n 'The exploration id provided does not match the exploration id '\n 'present as part of the suggestion_id')\n\n action = self.normalized_payload['action']\n suggestion = suggestion_services.get_suggestion_by_id(suggestion_id)\n\n if suggestion.author_id == self.user_id:\n raise self.UnauthorizedUserException(\n 'You cannot accept/reject your own suggestion.')\n\n if action == constants.ACTION_ACCEPT_SUGGESTION:\n commit_message = self.normalized_payload.get('commit_message')\n if commit_message is None:\n raise Exception(\n 'The \\'commit_message\\' must be provided when the '\n 'action is \\'accept suggestion\\'.'\n )\n suggestion_services.accept_suggestion(\n suggestion_id, self.user_id, commit_message,\n self.normalized_payload['review_message']\n )\n else:\n assert action == constants.ACTION_REJECT_SUGGESTION\n suggestion_services.reject_suggestion(\n suggestion_id, self.user_id,\n self.normalized_payload['review_message']\n )\n\n suggestion = suggestion_services.get_suggestion_by_id(suggestion_id)\n if suggestion.suggestion_type == (\n feconf.SUGGESTION_TYPE_TRANSLATE_CONTENT):\n suggestion_services.update_translation_review_stats(suggestion)\n\n self.render_json(self.values)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def main():\n args = parse_args()\n\n nmc = NM.Client.new()\n\n device = [d for d in nmc.get_devices() if d.get_iface() == args.device]\n if not device:\n raise Exception(f'Device \"{args.device}\" not found')\n if len(device) != 1:\n raise Exception(f'Not unique device \"{args.device}\" found')\n device = device[0]\n\n assert not args.stdin or args.mode == \"modify\"\n assert not args.preserve_external_ip or args.mode in [\"modify\", \"reapply\"]\n\n if args.mode == \"get\":\n connection, version_id = device_get_applied_connection(device)\n\n version_id_matches = args.version_id is None or args.version_id == version_id\n\n print(\n f'# Applied connection on \"{device.get_iface()}\": \"{connection.get_id()}\" ({connection.get_uuid()}, {connection.get_connection_type()})'\n )\n s = \"\" if version_id_matches else f\" (expected {args.version_id})\"\n print(f\"# version-id={version_id}{s}\")\n print(f\"#\")\n print(f\"{connection_to_kf(connection)}\")\n\n if not version_id_matches:\n eprint(\n f\"Applied version-id does not match (expects {args.version_id} but got {version_id})\"\n )\n sys.exit(1)\n sys.exit(0)\n\n if args.mode == \"reapply\":\n new_connection = None\n elif args.stdin:\n new_connection = connection_from_stdin()\n else:\n new_connection, _ = device_get_applied_connection(device)\n\n reapply_flags = 0\n if args.preserve_external_ip:\n reapply_flags = 1 # NM.DeviceReapplyFlags.PRESERVE_EXTERNAL_IP\n\n device_reapply(device, new_connection, args.version_id, reapply_flags)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "def pick_iterator (self, container):\n t = container.type.unqualified()\n if t.code == gdb.TYPE_CODE_PTR:\n t = t.target().unqualified()\n t = str(t)\n if t == \"GSList\":\n return self.slist_iterator\n if t == \"GList\":\n return self.list_iterator\n raise Exception(\"Invalid container type %s\"%(str(container.type)))", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "def main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--host\", help=\"Host to connect to\", required=True)\n parser.add_argument(\n \"--username\", help=\"Username to connect with\", default=\"root\"\n )\n parser.add_argument(\n \"--password\",\n help=\"Password for user in order to install certs over Redfish.\",\n default=\"0penBmc\",\n )\n args = parser.parse_args()\n host = args.host\n username = args.username\n password = args.password\n if username == \"root\" and password == \"0penBMC\":\n print(\n \"\"\"Note: Using default username 'root' and default password\n '0penBmc'. Use --username and --password flags to change these,\n respectively.\"\"\"\n )\n if \"//\" not in host:\n host = f\"https://{host}\"\n url = urllib.parse.urlparse(host, scheme=\"https\")\n\n serial = 1000\n certsDir = os.path.join(SCRIPT_DIR, \"certs\")\n print(f\"Writing certs to {certsDir}\")\n try:\n print(\"Making certs directory.\")\n os.mkdir(certsDir)\n except OSError as error:\n if error.errno == 17:\n print(\"certs directory already exists. Skipping...\")\n else:\n print(error)\n\n cacertFilename = os.path.join(certsDir, \"CA-cert.cer\")\n cakeyFilename = os.path.join(certsDir, \"CA-key.pem\")\n if os.path.exists(cacertFilename):\n with open(cacertFilename, \"rb\") as cacert_file:\n caCertDump = cacert_file.read()\n caCert = crypto.load_certificate(crypto.FILETYPE_PEM, caCertDump)\n with open(cakeyFilename, \"rb\") as cakey_file:\n caKeyDump = cakey_file.read()\n caKey = crypto.load_privatekey(crypto.FILETYPE_PEM, caKeyDump)\n else:\n\n caKey, caCert = generateCACert(serial)\n caKeyDump = crypto.dump_privatekey(crypto.FILETYPE_PEM, caKey)\n caCertDump = crypto.dump_certificate(crypto.FILETYPE_PEM, caCert)\n with open(cacertFilename, \"wb\") as f:\n f.write(caCertDump)\n print(\"CA cert generated.\")\n with open(cakeyFilename, \"wb\") as f:\n f.write(caKeyDump)\n print(\"CA key generated.\")\n serial += 1\n\n clientExtensions = [\n crypto.X509Extension(\n b\"keyUsage\",\n True,\n b\"\"\"digitalSignature,\n keyAgreement\"\"\",\n ),\n crypto.X509Extension(b\"extendedKeyUsage\", True, b\"clientAuth\"),\n ]\n\n redfishObject = redfish.redfish_client(\n base_url=\"https://\" + url.netloc,\n username=username,\n password=password,\n default_prefix=\"/redfish/v1\",\n )\n redfishObject.login(auth=\"session\")\n\n clientKey, clientCert = generateCert(\n username, clientExtensions, caKey, caCert, serial\n )\n\n clientKeyDump = crypto.dump_privatekey(crypto.FILETYPE_PEM, clientKey)\n with open(os.path.join(certsDir, \"client-key.pem\"), \"wb\") as f:\n f.write(clientKeyDump)\n print(\"Client key generated.\")\n serial += 1\n clientCertDump = crypto.dump_certificate(crypto.FILETYPE_PEM, clientCert)\n\n with open(os.path.join(certsDir, \"client-cert.pem\"), \"wb\") as f:\n f.write(clientCertDump)\n print(\"Client cert generated.\")\n\n san_list = [\n b\"DNS: localhost\",\n b\"IP: 127.0.0.1\",\n ]\n\n try:\n socket.inet_aton(url.hostname)\n san_list.append(b\"IP: \" + url.hostname.encode())\n except socket.error:\n san_list.append(b\"DNS: \" + url.hostname.encode())\n\n serverExtensions = [\n crypto.X509Extension(\n b\"keyUsage\",\n True,\n b\"digitalSignature, keyAgreement\",\n ),\n crypto.X509Extension(b\"extendedKeyUsage\", True, b\"serverAuth\"),\n crypto.X509Extension(b\"subjectAltName\", False, b\", \".join(san_list)),\n ]\n\n useCSR = True\n\n if useCSR:\n csr = generateCertCsr(\n redfishObject,\n url.hostname,\n serverExtensions,\n caKey,\n caCert,\n serial,\n )\n serverKey = None\n serverKeyDumpStr = \"\"\n else:\n csr = None\n serverKey, serverCert = generateCert(\n url.hostname, serverExtensions, caKey, caCert, serial, csr=csr\n )\n if serverKey is not None:\n serverKeyDump = crypto.dump_privatekey(crypto.FILETYPE_PEM, serverKey)\n with open(os.path.join(certsDir, \"server-key.pem\"), \"wb\") as f:\n f.write(serverKeyDump)\n print(\"Server key generated.\")\n serverKeyDumpStr = serverKeyDump.decode()\n serial += 1\n\n serverCertDump = crypto.dump_certificate(crypto.FILETYPE_PEM, serverCert)\n\n with open(os.path.join(certsDir, \"server-cert.pem\"), \"wb\") as f:\n f.write(serverCertDump)\n print(\"Server cert generated.\")\n\n serverCertDumpStr = serverCertDump.decode()\n\n print(\"Generating p12 cert file for browser authentication.\")\n pkcs12Cert = crypto.PKCS12()\n pkcs12Cert.set_certificate(clientCert)\n if clientKey:\n pkcs12Cert.set_privatekey(clientKey)\n pkcs12Cert.set_ca_certificates([caCert])\n pkcs12Cert.set_friendlyname(bytes(username, encoding=\"utf-8\"))\n with open(os.path.join(certsDir, \"client.p12\"), \"wb\") as f:\n f.write(pkcs12Cert.export())\n print(\"Client p12 cert file generated and stored in client.p12.\")\n print(\n \"Copy this file to a system with a browser and install the \"\n \"cert into the browser.\"\n )\n print(\n \"You will then be able to test redfish and webui \"\n \"authentication using this certificate.\"\n )\n print(\n \"Note: this p12 file was generated without a password, so it \"\n \"can be imported easily.\"\n )\n\n caCertJSON = {\n \"CertificateString\": caCertDump.decode(),\n \"CertificateType\": \"PEM\",\n }\n caCertPath = \"/redfish/v1/Managers/bmc/Truststore/Certificates\"\n replaceCertPath = \"/redfish/v1/CertificateService/Actions/\"\n replaceCertPath += \"CertificateService.ReplaceCertificate\"\n print(\"Attempting to install CA certificate to BMC.\")\n\n response = redfishObject.post(caCertPath, body=caCertJSON)\n if response.status == 500:\n print(\n \"An existing CA certificate is likely already installed.\"\n \" Replacing...\"\n )\n caCertJSON[\"CertificateUri\"] = {\n \"@odata.id\": caCertPath + \"/1\",\n }\n\n response = redfishObject.post(replaceCertPath, body=caCertJSON)\n if response.status == 200:\n print(\"Successfully replaced existing CA certificate.\")\n else:\n raise Exception(\n \"Could not install or replace CA certificate.\"\n \"Please check if a certificate is already installed. If a\"\n \"certificate is already installed, try performing a factory\"\n \"restore to clear such settings.\"\n )\n elif response.status == 200:\n print(\"Successfully installed CA certificate.\")\n else:\n raise Exception(\"Could not install certificate: \" + response.read)\n serverCertJSON = {\n \"CertificateString\": serverKeyDumpStr + serverCertDumpStr,\n \"CertificateUri\": {\n \"@odata.id\": \"/redfish/v1/Managers/bmc/NetworkProtocol/HTTPS/Certificates/1\",\n },\n \"CertificateType\": \"PEM\",\n }\n\n print(\"Replacing server certificate...\")\n response = redfishObject.post(replaceCertPath, body=serverCertJSON)\n if response.status == 200:\n print(\"Successfully replaced server certificate.\")\n else:\n raise Exception(\"Could not replace certificate: \" + response.read)\n tlsPatchJSON = {\"Oem\": {\"OpenBMC\": {\"AuthMethods\": {\"TLS\": True}}}}\n print(\"Ensuring TLS authentication is enabled.\")\n response = redfishObject.patch(\n \"/redfish/v1/AccountService\", body=tlsPatchJSON\n )\n if response.status == 200:\n print(\"Successfully enabled TLS authentication.\")\n else:\n raise Exception(\"Could not enable TLS auth: \" + response.read)\n redfishObject.logout()\n print(\"Testing redfish TLS authentication with generated certs.\")\n response = requests.get(\n f\"https://{url.netloc}/redfish/v1/SessionService/Sessions\",\n verify=os.path.join(certsDir, \"CA-cert.cer\"),\n cert=(\n os.path.join(certsDir, \"client-cert.pem\"),\n os.path.join(certsDir, \"client-key.pem\"),\n ),\n )\n response.raise_for_status()\n print(\"Redfish TLS authentication success!\")", "smellKey": "S112", "smellId": null, "repo": "edtanous_bmcweb", "language": "python"} {"function": "@opclass.setter\n def opclass(self, oc: cutlass.OpcodeClass):\n if isinstance(oc, str):\n oc = datatypes.getattr_enum(cutlass.OpcodeClass, oc)\n if oc in self.possible_op_classes:\n self.op_class = oc\n else:\n raise Exception(\n f'Unsupported operation class {oc} for CC {self.cc} and data type combination '\n f'({self._element_a}, {self._element_b}, {self._element_accumulator}) and '\n f'layout combination ({self._layout_a}, {self._layout_b}).')\n\n # Changing the op class changes the elements per access in the epilogue. Reset this.\n if self.op_class == cutlass.OpcodeClass.Simt:\n elements_per_access = 1\n else:\n elements_per_access = 128 // cutlass.DataTypeSize[self._element_c]\n\n if self.epilogue_functor is not None:\n self.epilogue_functor = self._reset_epilogue_functor_alignment(elements_per_access, self.epilogue_functor)\n\n # Changing the op class also changes the possible operations available. Reset these.\n self.possible_operations = self.options.operations(\n self.op_class, self._element_a, self._element_b,\n self._element_accumulator, self._layout_a, self._layout_b)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "@classmethod\n def create(\n cls,\n user_id: str,\n score_category: str,\n score: float,\n onboarding_email_sent: bool = False\n ) -> UserContributionProficiencyModel:\n \"\"\"Creates a new UserContributionProficiencyModel entry.\n\n Args:\n user_id: str. The ID of the user.\n score_category: str. The score category of the suggestion.\n score: float. The score of the user.\n onboarding_email_sent: bool. Whether the email to onboard the\n user as a reviewer has been sent.\n\n Returns:\n UserContributionProficiencyModel. The user proficiency model that\n was created.\n\n Raises:\n Exception. There is already an entry with the given id.\n \"\"\"\n instance_id = cls._get_instance_id(user_id, score_category)\n\n if cls.get_by_id(instance_id):\n raise Exception(\n 'There is already a UserContributionProficiencyModel entry with'\n ' the given id: %s' % instance_id\n )\n\n user_proficiency_model = cls(\n id=instance_id, user_id=user_id, score_category=score_category,\n score=score,\n onboarding_email_sent=onboarding_email_sent)\n user_proficiency_model.update_timestamps()\n user_proficiency_model.put()\n return user_proficiency_model", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def check_contents(group, wf_uuid):\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n if len(contents[\"items\"]) != 4:\n raise Exception(\"Expected 4 items in \"+group[\"uuid\"]+\" was \"+str(len(contents[\"items\"])))\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#workflow\" and c[\"uuid\"] == wf_uuid:\n found = True\n if not found:\n raise Exception(\"Couldn't find workflow in \"+group[\"uuid\"])\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"portable_data_hash\"] == \"d7514270f356df848477718d58308cc4+94\":\n found = True\n if not found:\n raise Exception(\"Couldn't find collection dependency\")\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"name\"].startswith(\"Docker image arvados jobs\"):\n found = True\n if not found:\n raise Exception(\"Couldn't find jobs image dependency\")\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and check_workflow_content(c[\"portable_data_hash\"]):\n found = True\n if not found:\n raise Exception(\"Couldn't find collection containing expected \"+expect_file)", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def _generate_dummy_skill_and_questions(self) -> None:\n \"\"\"Generate and loads the database with a skill and 15 questions\n linked to the skill.\n\n Raises:\n Exception. Cannot load new structures data in production mode.\n Exception. User does not have enough rights to generate data.\n \"\"\"\n assert self.user_id is not None\n if constants.DEV_MODE:\n if feconf.ROLE_ID_CURRICULUM_ADMIN not in self.user.roles:\n raise Exception(\n 'User does not have enough rights to generate data.')\n skill_id = skill_services.get_new_skill_id()\n skill_name = 'Dummy Skill %s' % str(random.getrandbits(32))\n skill = self._create_dummy_skill(\n skill_id, skill_name, '<p>Dummy Explanation 1</p>')\n skill_services.save_new_skill(self.user_id, skill)\n for i in range(15):\n question_id = question_services.get_new_question_id()\n question_name = 'Question number %s %s' % (str(i), skill_name)\n question = self._create_dummy_question(\n question_id, question_name, [skill_id])\n question_services.add_question(self.user_id, question)\n question_difficulty = list(\n constants.SKILL_DIFFICULTY_LABEL_TO_FLOAT.values())\n random_difficulty = random.choice(question_difficulty)\n question_services.create_new_question_skill_link(\n self.user_id, question_id, skill_id, random_difficulty)\n else:\n raise Exception('Cannot generate dummy skills in production.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def CalculateSmemUsagePerStage(operation):\n \"\"\"\n Returns the amount of shared memory in bytes consumed in a single stage of a kernel.\n\n :param op: operation for which the maximum stages should be computed. If stages are\n set via the `op.tile_description.stages` parameter, this setting is ignored\n in the present calculation\n :type op: cutlass.backend.Operation\n\n :return: number of bytes of shared memory consumed by a single stage\n :rtype: int\n \"\"\"\n m, n, k = operation.tile_description.threadblock_shape\n\n if operation.operation_kind == OperationKind.Gemm:\n stage_barrier_bytes = 32\n return (\n (DataTypeSize[operation.A.element] * m * k // 8)\n + (DataTypeSize[operation.B.element] * k * n // 8)\n + stage_barrier_bytes\n )\n else:\n raise Exception(\"Unsupported operation kind {}.\".format(operation.operation_kind))", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "@staticmethod\n def _get_cached_package_batch(chunk, sources=0):\n \"\"\"short-circuit the most common case\"\"\"\n if not chunk:\n return []\n short_package_collection = sync_handlers.ShortPackageCollection()\n if sources:\n package_collection = sync_handlers.SourcePackageCollection()\n else:\n package_collection = sync_handlers.PackageCollection()\n batch = []\n for pid in chunk:\n package = package_collection.get_package(pid)\n if (\n package is None\n or package[\"last_modified\"]\n != short_package_collection.get_package(pid)[\"last_modified\"]\n ):\n # not in the cache\n # pylint: disable-next=broad-exception-raised\n raise Exception(\n _(\n \"Package Not Found in Cache, Clear the Cache to \\\n Regenerate it.\"\n )\n )\n batch.append(package)\n return batch", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def get_composite_change_list(\n exp_id: str, from_version: int, to_version: int\n) -> List[exp_domain.ExplorationChange]:\n \"\"\"Returns a list of ExplorationChange domain objects consisting of\n changes from from_version to to_version in an exploration.\n\n Args:\n exp_id: str. The id of the exploration.\n from_version: int. The version of the exploration from where we\n want to start the change list.\n to_version: int. The version of the exploration till which we\n want are change list.\n\n Returns:\n list(ExplorationChange). List of ExplorationChange domain objects\n consisting of changes from from_version to to_version.\n\n Raises:\n Exception. From version is higher than to version.\n \"\"\"\n if from_version > to_version:\n raise Exception(\n 'Unexpected error: Trying to find change list from version %s '\n 'of exploration to version %s.'\n % (from_version, to_version))\n\n version_nums = list(range(from_version + 1, to_version + 1))\n snapshots_metadata = exp_models.ExplorationModel.get_snapshots_metadata(\n exp_id, version_nums, allow_deleted=False)\n\n composite_change_list_dict = []\n for snapshot in snapshots_metadata:\n composite_change_list_dict += snapshot['commit_cmds']\n\n composite_change_list = [\n exp_domain.ExplorationChange(change)\n for change in composite_change_list_dict]\n\n return composite_change_list", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, args):\n\n # Parameters specific to scanning.\n self.module_name = ''\n self.source_dirs = []\n self.headers = []\n self.ignored_files = []\n self.namespace = ''\n self.decorator = ''\n self.deprecation_guard = ''\n\n # Parameters specific to gtkdoc-scanobj.\n self.cflags = ''\n self.ldflags = ''\n self.library_path = ''\n\n # Parameters specific to generation.\n self.output_dir = ''\n self.doc_dir = ''\n self.main_sgml_file = ''\n\n # Parameters specific to gtkdoc-fixxref.\n self.cross_reference_deps = []\n\n self.interactive = False\n\n self.logger = logging.getLogger('gtkdoc')\n\n for key, value in iter(args.items()):\n setattr(self, key, value)\n\n if not getattr(self, 'output_dir'):\n raise Exception('output_dir not specified.')\n if not getattr(self, 'module_name'):\n raise Exception('module_name not specified.')\n if not getattr(self, 'source_dirs') and not getattr(self, 'headers'):\n raise Exception('Neither source_dirs nor headers specified.' % key)\n\n # Make all paths absolute in case we were passed relative paths, since\n # we change the current working directory when executing subcommands.\n self.output_dir = os.path.abspath(self.output_dir)\n self.source_dirs = [os.path.abspath(x) for x in self.source_dirs]\n self.headers = [os.path.abspath(x) for x in self.headers]\n if self.library_path:\n self.library_path = os.path.abspath(self.library_path)\n\n if not self.main_sgml_file:\n self.main_sgml_file = self.module_name + \"-docs.sgml\"", "smellKey": "S112", "smellId": null, "repo": "tsdgeos_poppler_mirror", "language": "python"} {"function": "def compile_test_ts_files() -> None:\n \"\"\"Compiles the test typescript files into a build directory.\"\"\"\n puppeteer_acceptance_tests_dir_path = os.path.join(\n common.CURR_DIR, 'core', 'tests', 'puppeteer-acceptance-tests')\n build_dir_path = os.path.join(\n puppeteer_acceptance_tests_dir_path,\n 'build',\n 'puppeteer-acceptance-tests'\n )\n\n if os.path.exists(build_dir_path):\n shutil.rmtree(build_dir_path)\n\n cmd = (\n './node_modules/typescript/bin/tsc -p %s' %\n './tsconfig.puppeteer-acceptance-tests.json')\n proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n\n _, encoded_stderr = proc.communicate()\n stderr = encoded_stderr.decode('utf-8')\n\n if stderr:\n raise Exception(stderr)\n\n shutil.copytree(\n os.path.join(puppeteer_acceptance_tests_dir_path, 'data'),\n os.path.join(build_dir_path, 'data'))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_multi(keys: List[Key]) -> List[Optional[TYPE_MODEL_SUBCLASS]]:\n \"\"\"Fetches models corresponding to a sequence of keys.\n\n Args:\n keys: list(str). The keys to look up.\n\n Returns:\n list(datastore_services.Model | None). List whose items are either a\n Model instance or None if the corresponding key wasn't found.\n\n Raises:\n Exception. If ndb.get_multi fails for MAX_GET_RETRIES.\n \"\"\"\n for unused_i in range(0, MAX_GET_RETRIES):\n try:\n return ndb.get_multi(keys)\n except Exception as e:\n logging.exception('Exception raised: %s', e)\n continue\n raise Exception('get_multi failed after %s retries' % MAX_GET_RETRIES)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def write_pfm(file, image, scale=1):\n \"\"\" Write a pfm file \"\"\"\n file = open(file, 'wb')\n\n color = None\n\n if image.dtype.name != 'float32':\n raise Exception('Image dtype must be float32.')\n\n if len(image.shape) == 3 and image.shape[2] == 3: # color image\n color = True\n elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # grayscale\n color = False\n else:\n raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')\n\n file.write('PF\\n'.encode('utf-8') if color else 'Pf\\n'.encode('utf-8'))\n temp_str = '%d %d\\n' % (image.shape[1], image.shape[0])\n file.write(temp_str.encode('utf-8'))\n\n endian = image.dtype.byteorder\n\n if endian == '<' or endian == '=' and sys.byteorder == 'little':\n scale = -scale\n\n temp_str = '%f\\n' % scale\n file.write(temp_str.encode('utf-8'))\n\n image.tofile(file)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "@acl_decorators.can_access_release_coordinator_page\n def put(self) -> None:\n \"\"\"Handles PUT requests.\"\"\"\n assert self.normalized_payload is not None\n action = self.normalized_payload.get('action')\n try:\n # The handler schema defines the possible values of 'action'.\n # If 'action' has a value other than those defined in the\n # schema, a Bad Request error will be thrown. Hence, 'action'\n # must be 'update_feature_flag' if this branch is\n # executed.\n assert action == 'update_feature_flag'\n feature_flag_name = self.normalized_payload.get('feature_flag_name')\n if feature_flag_name is None:\n raise Exception(\n 'The \\'feature_flag_name\\' must be provided when the action'\n ' is update_feature_flag.'\n )\n\n force_enable_for_all_users = self.normalized_payload.get(\n 'force_enable_for_all_users')\n # Ruling out the possibility of any other type for mypy\n # type checking.\n assert force_enable_for_all_users is not None\n rollout_percentage = self.normalized_payload.get(\n 'rollout_percentage')\n # Ruling out the possibility of any other type for mypy\n # type checking.\n assert rollout_percentage is not None\n user_group_ids = self.normalized_payload.get('user_group_ids')\n # Ruling out the possibility of any other type for mypy\n # type checking.\n assert user_group_ids is not None\n try:\n feature_services.update_feature_flag(\n feature_flag_name,\n force_enable_for_all_users,\n rollout_percentage,\n user_group_ids\n )\n except (\n utils.ValidationError,\n feature_services.FeatureFlagNotFoundException) as e:\n raise self.InvalidInputException(e)\n\n logging.info(\n '[RELEASE-COORDINATOR] %s updated feature %s with new values: '\n 'rollout_percentage - %d, force_enable_for_all_users - %s, '\n 'user_group_ids - %s.' % (\n self.user_id, feature_flag_name,\n rollout_percentage,\n force_enable_for_all_users,\n user_group_ids)\n )\n self.render_json(self.values)\n except Exception as e:\n logging.exception('[RELEASE-COORDINATOR] %s', e)\n self.render_json({'error': str(e)})\n raise e", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, transfer=0, encoding=0, connection=None, method=\"POST\"):\n # Assumes connection is an instance of HTTPConnection\n if connection:\n if not isinstance(connection, connections.HTTPConnection):\n # pylint: disable-next=broad-exception-raised\n raise Exception(\"Expected an HTTPConnection type object\")\n\n self.method = method\n\n # Store the connection\n self._connection = connection\n\n self.data = None\n self.headers = UserDictCase()\n self.encoding = 0\n self.transfer = 0\n self.transport_flags = {}\n # for authenticated proxies\n self.username = None\n self.password = None\n # Fields to keep the information about the server\n self._host = None\n self._handler = None\n self._http_type = None\n self._protocol = None\n # Initialize self.transfer and self.encoding\n self.set_transport_flags(transfer=transfer, encoding=encoding)\n\n # internal flags\n self.__processed = 0", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def _encode_plus(self, *args, **kwargs) -> BatchEncoding:\n is_split_into_words = kwargs.get(\"is_split_into_words\", False)\n\n if not (self.add_prefix_space or not is_split_into_words):\n raise Exception(\n f\"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with\"\n \" pretokenized inputs.\"\n )\n\n return super()._encode_plus(*args, **kwargs)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self,\n source_path,\n step=1,\n start=0,\n stop=None,\n dimension=DimensionType.DIM_2D,\n sorting_method=SortingMethod.LEXICOGRAPHICAL,\n extract_dir=None):\n if not source_path:\n raise Exception('No PDF found')\n\n self._pdf_source = source_path[0]\n\n _basename = os.path.splitext(os.path.basename(self._pdf_source))[0]\n _counter = itertools.count()\n def _make_name():\n for page_num in _counter:\n yield '{}{:09d}.jpeg'.format(_basename, page_num)\n\n from pdf2image import convert_from_path\n self._tmp_dir = extract_dir if extract_dir else os.path.dirname(source_path[0])\n os.makedirs(self._tmp_dir, exist_ok=True)\n\n # Avoid OOM: https://github.com/openvinotoolkit/cvat/issues/940\n paths = convert_from_path(self._pdf_source,\n last_page=stop, paths_only=True,\n output_folder=self._tmp_dir, fmt=\"jpeg\", output_file=_make_name())\n\n if not extract_dir:\n os.remove(source_path[0])\n\n super().__init__(\n source_path=paths,\n step=step,\n start=start,\n stop=stop,\n dimension=dimension,\n sorting_method=sorting_method,\n )", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@classmethod\n def generate_id(\n cls,\n platform: str,\n submitted_on_datetime: datetime.datetime\n ) -> str:\n \"\"\"Generates key for the instance of AppFeedbackReportModel class in the\n required format with the arguments provided.\n\n Args:\n platform: str. The platform the user is the report from.\n submitted_on_datetime: datetime.datetime. The datetime that the\n report was submitted on in UTC.\n\n Returns:\n str. The generated ID for this entity using platform,\n submitted_on_sec, and a random string, of the form\n '[platform].[submitted_on_msec].[random hash]'.\n\n Raises:\n Exception. If the id generator is producing too many collisions.\n \"\"\"\n submitted_datetime_in_msec = utils.get_time_in_millisecs(\n submitted_on_datetime)\n for _ in range(base_models.MAX_RETRIES):\n random_hash = utils.convert_to_hash(\n str(utils.get_random_int(base_models.RAND_RANGE)),\n base_models.ID_LENGTH)\n new_id = '%s.%s.%s' % (\n platform, int(submitted_datetime_in_msec), random_hash)\n if not cls.get_by_id(new_id):\n return new_id\n raise Exception(\n 'The id generator for AppFeedbackReportModel is producing too '\n 'many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _query_total_counts(self) -> tuple[float | int, float | int]:\n if self._cached_count is None:\n total_query = spans_indexed.SpansEAPQueryBuilder(\n dataset=self.builder.dataset,\n params={},\n snuba_params=self.builder.params,\n selected_columns=[\"count()\", \"count_weighted()\"],\n )\n total_results = total_query.run_query(Referrer.API_SPANS_TOTAL_COUNT_FIELD.value)\n results = total_query.process_results(total_results)\n if len(results[\"data\"]) != 1:\n raise Exception(\"Could not query population size\")\n self._cached_count = results[\"data\"][0][\"count\"]\n self._cached_count_weighted = results[\"data\"][0][\"count_weighted\"]\n return self._cached_count, self._cached_count_weighted", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@staticmethod\n def check_repo_path():\n if not all(os.path.isdir(d) for d in [\"include\", \"library\", \"tests\"]):\n raise Exception(\"Must be run from Mbed TLS root\")", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-mr", "language": "python"} {"function": "def validate(self) -> None:\n \"\"\"Method to validate the test object.\"\"\"\n if not isinstance(self.arg_a, str):\n raise Exception('Invalid type arg_a.')\n if not isinstance(self.arg_b, str):\n raise Exception('Invalid type arg_b.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def sendto(self, buf):\n ret = capi.nl_sendto(self._sock, buf, len(buf))\n if ret < 0:\n raise Exception('Failed to send')\n else:\n return ret", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l1", "language": "python"} {"function": "@staticmethod\n def _check_external_dependencies(terp):\n depends = terp.get('external_dependencies')\n if not depends:\n return\n for pydep in depends.get('python', []):\n try:\n importlib.import_module(pydep)\n except ImportError:\n raise ImportError('No module named %s' % (pydep,))\n\n for binary in depends.get('bin', []):\n try:\n tools.find_in_path(binary)\n except IOError:\n raise Exception('Unable to find %r in path' % (binary,))", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def get_updated_exp_issues_models_for_new_exp_version(\n exploration: exp_domain.Exploration,\n exp_versions_diff: Optional[exp_domain.ExplorationVersionsDiff],\n revert_to_version: Optional[int]\n) -> List[base_models.BaseModel]:\n \"\"\"Retrieves the ExplorationIssuesModel for the old exp_version and makes\n any required changes to the structure of the model.\n\n Note: This method does not perform put operations on the models. The caller\n of this method must do so.\n\n Args:\n exploration: Exploration. Domain object for the exploration.\n exp_versions_diff: ExplorationVersionsDiff|None. The domain object for\n the exploration versions difference, None if it is a revert.\n revert_to_version: int|None. If the change is a revert, the version.\n Otherwise, None.\n\n Raises:\n Exception. ExplorationVersionsDiff cannot be None when the change\n is not a revert.\n\n Returns:\n list(BaseModel). A list of model instances related to exploration\n issues that were updated.\n \"\"\"\n models_to_put: List[base_models.BaseModel] = []\n exp_issues = get_exp_issues(\n exploration.id, exploration.version - 1, strict=False\n )\n if exp_issues is None:\n instance_id = stats_models.ExplorationIssuesModel.get_entity_id(\n exploration.id,\n exploration.version - 1\n )\n models_to_put.append(\n stats_models.ExplorationIssuesModel(\n id=instance_id,\n exp_id=exploration.id,\n exp_version=exploration.version,\n unresolved_issues=[]\n )\n )\n return models_to_put\n\n if revert_to_version:\n old_exp_issues = get_exp_issues(exploration.id, revert_to_version)\n exp_issues.unresolved_issues = old_exp_issues.unresolved_issues\n exp_issues.exp_version = exploration.version + 1\n models_to_put.append(\n get_exp_issues_model_from_domain_object(exp_issues)\n )\n return models_to_put\n\n if exp_versions_diff is None:\n raise Exception(\n 'ExplorationVersionsDiff cannot be None when the change is'\n ' not a revert.'\n )\n\n deleted_state_names = exp_versions_diff.deleted_state_names\n old_to_new_state_names = exp_versions_diff.old_to_new_state_names\n\n playthrough_ids = list(itertools.chain.from_iterable(\n issue.playthrough_ids for issue in exp_issues.unresolved_issues))\n playthrough_models = get_playthrough_models_by_ids(\n playthrough_ids, strict=True\n )\n updated_playthrough_models = []\n\n for playthrough_model in playthrough_models:\n playthrough = get_playthrough_from_model(playthrough_model)\n\n if 'state_names' in playthrough.issue_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed issue customization arg types to List[str] type,\n # and here we are sure that the type is always going to be List[str]\n # because above 'if' condition forces 'state_names' issue\n # customization arg to have values of type List[str].\n state_names = cast(\n List[str],\n playthrough.issue_customization_args['state_names']['value']\n )\n playthrough.issue_customization_args['state_names']['value'] = [\n state_name if state_name not in old_to_new_state_names else\n old_to_new_state_names[state_name] for state_name in state_names\n ]\n\n if 'state_name' in playthrough.issue_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed issue customization arg types to str type, and\n # here we are sure that the type is always going to be str because\n # above 'if' condition forces 'state_name' issue customization arg\n # to have values of type str.\n state_name = cast(\n str,\n playthrough.issue_customization_args['state_name']['value']\n )\n playthrough.issue_customization_args['state_name']['value'] = (\n state_name if state_name not in old_to_new_state_names else\n old_to_new_state_names[state_name])\n\n for action in playthrough.actions:\n action_customization_args = action.action_customization_args\n\n if 'state_name' in action_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed action customization arg types to str type,\n # and here we are sure that the type is always going to be str\n # because above 'if' condition forces 'state_name' action\n # customization arg to have values of type str.\n state_name = cast(\n str, action_customization_args['state_name']['value']\n )\n action_customization_args['state_name']['value'] = (\n state_name if state_name not in old_to_new_state_names else\n old_to_new_state_names[state_name])\n\n if 'dest_state_name' in action_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed action customization arg types to str type,\n # and here we are sure that the type is always going to be str\n # because above 'if' condition forces 'dest_state_name' action\n # customization arg to have values of type str.\n dest_state_name = cast(\n str,\n action_customization_args['dest_state_name']['value']\n )\n action_customization_args['dest_state_name']['value'] = (\n dest_state_name\n if dest_state_name not in old_to_new_state_names else\n old_to_new_state_names[dest_state_name])\n\n playthrough_model.issue_customization_args = (\n playthrough.issue_customization_args)\n playthrough_model.actions = [\n action.to_dict() for action in playthrough.actions]\n updated_playthrough_models.append(playthrough_model)\n\n models_to_put.extend(updated_playthrough_models)\n\n for exp_issue in exp_issues.unresolved_issues:\n if 'state_names' in exp_issue.issue_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed issue customization arg types to List[str] type,\n # and here we are sure that the type is always going to be List[str]\n # because above 'if' condition forces 'state_names' issue\n # customization arg to have values of type List[str].\n state_names = cast(\n List[str],\n exp_issue.issue_customization_args['state_names']['value']\n )\n if any(name in deleted_state_names for name in state_names):\n exp_issue.is_valid = False\n\n exp_issue.issue_customization_args['state_names']['value'] = [\n state_name if state_name not in old_to_new_state_names else\n old_to_new_state_names[state_name]\n for state_name in state_names\n ]\n\n if 'state_name' in exp_issue.issue_customization_args:\n # Here we use cast because we need to narrow down the type from\n # various allowed issue customization arg types to str type, and\n # here we are sure that the type is always going to be str because\n # above 'if' condition forces 'state_name' issue customization arg\n # to have values of type str.\n state_name = cast(\n str,\n exp_issue.issue_customization_args['state_name']['value']\n )\n if state_name in deleted_state_names:\n exp_issue.is_valid = False\n\n exp_issue.issue_customization_args['state_name']['value'] = (\n state_name if state_name not in old_to_new_state_names else\n old_to_new_state_names[state_name])\n\n exp_issues.exp_version += 1\n models_to_put.append(get_exp_issues_model_from_domain_object(exp_issues))\n return models_to_put", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@pytest.fixture(scope=\"session\")\ndef admin_user(users):\n for user in users:\n if user[\"is_superuser\"] and user[\"is_active\"]:\n return user[\"username\"]\n raise Exception(\"Can't find any admin user in the test DB\")", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def __init__(self):\n self.tests_dir = TESTS_HTTPD_PATH\n self.gen_dir = os.path.join(self.tests_dir, 'gen')\n self.project_dir = os.path.dirname(os.path.dirname(self.tests_dir))\n self.build_dir = TOP_PATH\n self.config = DEF_CONFIG\n # check cur and its features\n self.curl = CURL\n if 'CURL' in os.environ:\n self.curl = os.environ['CURL']\n self.curl_props = {\n 'version': '',\n 'os': '',\n 'fullname': '',\n 'features': [],\n 'protocols': [],\n 'libs': [],\n 'lib_versions': [],\n }\n self.curl_is_debug = False\n self.curl_protos = []\n p = subprocess.run(args=[self.curl, '-V'],\n capture_output=True, text=True)\n if p.returncode != 0:\n assert False, f'{self.curl} -V failed with exit code: {p.returncode}'\n if p.stderr.startswith('WARNING:'):\n self.curl_is_debug = True\n for line in p.stdout.splitlines(keepends=False):\n if line.startswith('curl '):\n m = re.match(r'^curl (?P<version>\\S+) (?P<os>\\S+) (?P<libs>.*)$', line)\n if m:\n self.curl_props['fullname'] = m.group(0)\n self.curl_props['version'] = m.group('version')\n self.curl_props['os'] = m.group('os')\n self.curl_props['lib_versions'] = [\n lib.lower() for lib in m.group('libs').split(' ')\n ]\n self.curl_props['libs'] = [\n re.sub(r'/.*', '', lib) for lib in self.curl_props['lib_versions']\n ]\n if line.startswith('Features: '):\n self.curl_props['features'] = [\n feat.lower() for feat in line[10:].split(' ')\n ]\n if line.startswith('Protocols: '):\n self.curl_props['protocols'] = [\n prot.lower() for prot in line[11:].split(' ')\n ]\n\n self.ports = alloc_ports(port_specs={\n 'ftp': socket.SOCK_STREAM,\n 'ftps': socket.SOCK_STREAM,\n 'http': socket.SOCK_STREAM,\n 'https': socket.SOCK_STREAM,\n 'nghttpx_https': socket.SOCK_STREAM,\n 'proxy': socket.SOCK_STREAM,\n 'proxys': socket.SOCK_STREAM,\n 'h2proxys': socket.SOCK_STREAM,\n 'caddy': socket.SOCK_STREAM,\n 'caddys': socket.SOCK_STREAM,\n 'ws': socket.SOCK_STREAM,\n })\n self.httpd = self.config['httpd']['httpd']\n self.apachectl = self.config['httpd']['apachectl']\n self.apxs = self.config['httpd']['apxs']\n if len(self.apxs) == 0:\n self.apxs = None\n self._httpd_version = None\n\n self.examples_pem = {\n 'key': 'xxx',\n 'cert': 'xxx',\n }\n self.htdocs_dir = os.path.join(self.gen_dir, 'htdocs')\n self.tld = 'http.curl.se'\n self.domain1 = f\"one.{self.tld}\"\n self.domain1brotli = f\"brotli.one.{self.tld}\"\n self.domain2 = f\"two.{self.tld}\"\n self.ftp_domain = f\"ftp.{self.tld}\"\n self.proxy_domain = f\"proxy.{self.tld}\"\n self.cert_specs = [\n CertificateSpec(domains=[self.domain1, self.domain1brotli, 'localhost', '127.0.0.1'], key_type='rsa2048'),\n CertificateSpec(domains=[self.domain2], key_type='rsa2048'),\n CertificateSpec(domains=[self.ftp_domain], key_type='rsa2048'),\n CertificateSpec(domains=[self.proxy_domain, '127.0.0.1'], key_type='rsa2048'),\n CertificateSpec(name=\"clientsX\", sub_specs=[\n CertificateSpec(name=\"user1\", client=True),\n ]),\n ]\n\n self.nghttpx = self.config['nghttpx']['nghttpx']\n if len(self.nghttpx.strip()) == 0:\n self.nghttpx = None\n self._nghttpx_version = None\n self.nghttpx_with_h3 = False\n if self.nghttpx is not None:\n p = subprocess.run(args=[self.nghttpx, '-v'],\n capture_output=True, text=True)\n if p.returncode != 0:\n # not a working nghttpx\n self.nghttpx = None\n else:\n self._nghttpx_version = re.sub(r'^nghttpx\\s*', '', p.stdout.strip())\n self.nghttpx_with_h3 = re.match(r'.* nghttp3/.*', p.stdout.strip()) is not None\n log.debug(f'nghttpx -v: {p.stdout}')\n\n self.caddy = self.config['caddy']['caddy']\n self._caddy_version = None\n if len(self.caddy.strip()) == 0:\n self.caddy = None\n if self.caddy is not None:\n try:\n p = subprocess.run(args=[self.caddy, 'version'],\n capture_output=True, text=True)\n if p.returncode != 0:\n # not a working caddy\n self.caddy = None\n m = re.match(r'v?(\\d+\\.\\d+\\.\\d+).*', p.stdout)\n if m:\n self._caddy_version = m.group(1)\n else:\n raise f'Unable to determine cadd version from: {p.stdout}'\n # TODO: specify specific exceptions here\n except: # noqa: E722\n self.caddy = None\n\n self.vsftpd = self.config['vsftpd']['vsftpd']\n self._vsftpd_version = None\n if self.vsftpd is not None:\n try:\n with tempfile.TemporaryFile('w+') as tmp:\n p = subprocess.run(args=[self.vsftpd, '-v'],\n capture_output=True, text=True, stdin=tmp)\n if p.returncode != 0:\n # not a working vsftpd\n self.vsftpd = None\n if p.stderr:\n ver_text = p.stderr\n else:\n # Oddly, some versions of vsftpd write to stdin (!)\n # instead of stderr, which is odd but works. If there\n # is nothing on stderr, read the file on stdin and use\n # any data there instead.\n tmp.seek(0)\n ver_text = tmp.read()\n m = re.match(r'vsftpd: version (\\d+\\.\\d+\\.\\d+)', ver_text)\n if m:\n self._vsftpd_version = m.group(1)\n elif len(p.stderr) == 0:\n # vsftp does not use stdout or stderr for printing its version... -.-\n self._vsftpd_version = 'unknown'\n else:\n raise Exception(f'Unable to determine VsFTPD version from: {p.stderr}')\n except Exception:\n self.vsftpd = None\n\n self._tcpdump = shutil.which('tcpdump')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_curl", "language": "python"} {"function": "def enable_depot(depot, request):\n if depot.is_enabled:\n return f\"Le d\u00e9p\u00f4t {depot.name} est d\u00e9j\u00e0 activ\u00e9\"\n\n depot.is_enabled = True\n depot.save()\n\n # Get entity admin users\n entity = depot.entity\n try:\n admins = UserRights.objects.filter(entity=entity, role=UserRights.ADMIN)\n except Exception:\n raise Exception(\"Cette soci\u00e9t\u00e9 n'a pas d'admin actif\")\n\n send_email_to_admin_users(entity, depot, admins, request)\n\n return f\"Le d\u00e9p\u00f4t {depot.name} est activ\u00e9 et les administrateurs de {entity.name} ont \u00e9t\u00e9 notifi\u00e9s\"", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def install_package(\n pkg: str, python_executable: str = sys.executable, editable: bool = False\n) -> None:\n \"\"\"Install a package from test-data/packages/pkg/\"\"\"\n working_dir = os.path.join(package_path, pkg)\n with tempfile.TemporaryDirectory() as dir:\n install_cmd = [python_executable, \"-m\", \"pip\", \"install\"]\n if editable:\n install_cmd.append(\"-e\")\n install_cmd.append(\".\")\n\n # Note that newer versions of pip (21.3+) don't\n # follow this env variable, but this is for compatibility\n env = {\"PIP_BUILD\": dir}\n # Inherit environment for Windows\n env.update(os.environ)\n try:\n with filelock.FileLock(pip_lock, timeout=pip_timeout):\n proc = subprocess.run(install_cmd, cwd=working_dir, capture_output=True, env=env)\n except filelock.Timeout as err:\n raise Exception(f\"Failed to acquire {pip_lock}\") from err\n if proc.returncode != 0:\n raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def minimize(code):\n\n params = urllib.urlencode([\n ('js_code', code),\n ('compilation_level', 'SIMPLE_OPTIMIZATIONS'),\n ('output_format', 'text'),\n ('output_info', 'compiled_code'),\n ])\n \n t = time.time()\n # Always use the following value for the Content-type header.\n headers = { \"Content-type\": \"application/x-www-form-urlencoded\" }\n conn = httplib.HTTPConnection('closure-compiler.appspot.com')\n conn.request('POST', '/compile', params, headers)\n response = conn.getresponse()\n data = response.read()\n conn.close()\n if data.startswith(\"Error\"):\n raise Exception(data)\n print \"%.3f seconds to compile\" % (time.time() - t) \n return data", "smellKey": "S112", "smellId": null, "repo": "usdot-fhwa-stol_connectedvcs-tools", "language": "python"} {"function": "@pytest.mark.big\ndef test_graph_validate_with_exception(basic_datasource: PandasDatasource, mocker: MockerFixture):\n # noinspection PyUnusedLocal\n def mock_error(*args, **kwargs):\n raise Exception(\"Mock Error\") # noqa: TRY002\n\n df = pd.DataFrame({\"a\": [1, 5, 22, 3, 5, 10], \"b\": [1, 2, 3, 4, 5, None]})\n asset = basic_datasource.add_dataframe_asset(\"my_asset\")\n batch_definition = asset.add_batch_definition_whole_dataframe(\"my batch definition\")\n batch = batch_definition.get_batch(batch_parameters={\"dataframe\": df})\n\n expectation_configuration = ExpectationConfiguration(\n type=\"expect_column_value_z_scores_to_be_less_than\",\n kwargs={\n \"column\": \"b\",\n \"mostly\": 0.9,\n \"threshold\": 4,\n \"double_sided\": True,\n },\n )\n\n execution_engine = PandasExecutionEngine()\n validator = Validator(execution_engine=execution_engine, batches=[batch])\n\n # TODO: Convert this to actually mock an exception being thrown\n # graph = ValidationGraph(execution_engine=execution_engine)\n # graph.build_metric_dependency_graph = mock_error # type: ignore[method-assign]\n\n result = validator.graph_validate(configurations=[expectation_configuration])\n\n assert len(result) == 1\n assert result[0].expectation_config is not None", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def _verify_type_and_layout(self, tensor, ref_type, ref_layout, name):\n \"\"\"\n Verifies that ``tensor`` has data type ``ref_type`` and layout ``ref_layout``. An exception\n is raised if it does not.\n\n :param tensor: object representing a tensor passed in to verify, or ``None`` if no tensor was passed in\n :type tensor: numpy/cupy/torch array/tensor object\n :param ref_dtype: data type for the tensor that this object was initialized to\n :param name: identifier of the tensor to verify. Used in raising exceptions\n :type name: str\n \"\"\"\n dtype, _ = datatypes.get_datatype_and_layout(tensor)\n if dtype != ref_type:\n raise Exception(f'Tensor {name} with type and layout {dtype} '\n f'does not match the expected type of {ref_type}.')", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def test_merged_rollback_commit(self):\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with transaction.atomic():\n Reporter.objects.create(last_name=\"Tintin\")\n with transaction.atomic(savepoint=False):\n Reporter.objects.create(last_name=\"Haddock\")\n raise Exception(\"Oops, that's his first name\")\n self.assertSequenceEqual(Reporter.objects.all(), [])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def test_mempool_sync(self):\n \"\"\"\n Use sequence notification plus getrawmempool sequence results to \"sync mempool\"\n \"\"\"\n\n self.log.info(\"Testing 'mempool sync' usage of sequence notifier\")\n [seq] = self.setup_zmq_test([(\"sequence\", f\"tcp://127.0.0.1:{self.zmq_port_base}\")])\n\n # In-memory counter, should always start at 1\n next_mempool_seq = self.nodes[0].getrawmempool(mempool_sequence=True)[\"mempool_sequence\"]\n assert_equal(next_mempool_seq, 1)\n\n # Some transactions have been happening but we aren't consuming zmq notifications yet\n # or we lost a ZMQ message somehow and want to start over\n txs = []\n num_txs = 5\n for _ in range(num_txs):\n txs.append(self.wallet.send_self_transfer(from_node=self.nodes[1]))\n self.sync_all()\n\n # 1) Consume backlog until we get a mempool sequence number\n (hash_str, label, zmq_mem_seq) = seq.receive_sequence()\n while zmq_mem_seq is None:\n (hash_str, label, zmq_mem_seq) = seq.receive_sequence()\n\n assert label == \"A\" or label == \"R\"\n assert hash_str is not None\n\n # 2) We need to \"seed\" our view of the mempool\n mempool_snapshot = self.nodes[0].getrawmempool(mempool_sequence=True)\n mempool_view = set(mempool_snapshot[\"txids\"])\n get_raw_seq = mempool_snapshot[\"mempool_sequence\"]\n assert_equal(get_raw_seq, 6)\n # Snapshot may be too old compared to zmq message we read off latest\n while zmq_mem_seq >= get_raw_seq:\n sleep(2)\n mempool_snapshot = self.nodes[0].getrawmempool(mempool_sequence=True)\n mempool_view = set(mempool_snapshot[\"txids\"])\n get_raw_seq = mempool_snapshot[\"mempool_sequence\"]\n\n # Things continue to happen in the \"interim\" while waiting for snapshot results\n # We have node 0 do all these to avoid p2p races with RBF announcements\n for _ in range(num_txs):\n txs.append(self.wallet.send_self_transfer(from_node=self.nodes[0]))\n txs[-1]['tx'].vout[0].nValue -= 1000\n self.nodes[0].sendrawtransaction(txs[-1]['tx'].serialize().hex())\n self.sync_all()\n self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)\n final_txid = self.wallet.send_self_transfer(from_node=self.nodes[0])['txid']\n\n # 3) Consume ZMQ backlog until we get to \"now\" for the mempool snapshot\n while True:\n if zmq_mem_seq == get_raw_seq - 1:\n break\n (hash_str, label, mempool_sequence) = seq.receive_sequence()\n if mempool_sequence is not None:\n zmq_mem_seq = mempool_sequence\n if zmq_mem_seq > get_raw_seq:\n raise Exception(f\"We somehow jumped mempool sequence numbers! zmq_mem_seq: {zmq_mem_seq} > get_raw_seq: {get_raw_seq}\")\n\n # 4) Moving forward, we apply the delta to our local view\n # remaining txs(5) + 1 rbf(A+R) + 1 block connect + 1 final tx\n expected_sequence = get_raw_seq\n r_gap = 0\n for _ in range(num_txs + 2 + 1 + 1):\n (hash_str, label, mempool_sequence) = seq.receive_sequence()\n if mempool_sequence is not None:\n if mempool_sequence != expected_sequence:\n # Detected \"R\" gap, means this a conflict eviction, and mempool tx are being evicted before its\n # position in the incoming block message \"C\"\n if label == \"R\":\n assert mempool_sequence > expected_sequence\n r_gap += mempool_sequence - expected_sequence\n else:\n raise Exception(f\"WARNING: txhash has unexpected mempool sequence value: {mempool_sequence} vs expected {expected_sequence}\")\n if label == \"A\":\n assert hash_str not in mempool_view\n mempool_view.add(hash_str)\n expected_sequence = mempool_sequence + 1\n elif label == \"R\":\n assert hash_str in mempool_view\n mempool_view.remove(hash_str)\n expected_sequence = mempool_sequence + 1\n elif label == \"C\":\n # (Attempt to) remove all txids from known block connects\n block_txids = self.nodes[0].getblock(hash_str)[\"tx\"][1:]\n for txid in block_txids:\n if txid in mempool_view:\n expected_sequence += 1\n mempool_view.remove(txid)\n expected_sequence -= r_gap\n r_gap = 0\n elif label == \"D\":\n # Not useful for mempool tracking per se\n continue\n else:\n raise Exception(\"Unexpected ZMQ sequence label!\")\n\n assert_equal(self.nodes[0].getrawmempool(), [final_txid])\n assert_equal(self.nodes[0].getrawmempool(mempool_sequence=True)[\"mempool_sequence\"], expected_sequence)\n\n # 5) If you miss a zmq/mempool sequence number, go back to step (2)\n\n self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)", "smellKey": "S112", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def convert_tensorflow(nlp: Pipeline, opset: int, output: Path):\n \"\"\"\n Export a TensorFlow backed pipeline to ONNX Intermediate Representation (IR)\n\n Args:\n nlp: The pipeline to be exported\n opset: The actual version of the ONNX operator set to use\n output: Path where will be stored the generated ONNX model\n\n Notes: TensorFlow cannot export model bigger than 2GB due to internal constraint from TensorFlow\n\n \"\"\"\n if not is_tf_available():\n raise Exception(\"Cannot convert because TF is not installed. Please install tensorflow first.\")\n\n print(\"/!\\\\ Please note TensorFlow doesn't support exporting model > 2Gb /!\\\\\")\n\n try:\n import tensorflow as tf\n import tf2onnx\n from tf2onnx import __version__ as t2ov\n\n print(f\"Using framework TensorFlow: {tf.version.VERSION}, tf2onnx: {t2ov}\")\n\n # Build\n input_names, output_names, dynamic_axes, tokens = infer_shapes(nlp, \"tf\")\n\n # Forward\n nlp.model.predict(tokens.data)\n input_signature = [tf.TensorSpec.from_tensor(tensor, name=key) for key, tensor in tokens.items()]\n model_proto, _ = tf2onnx.convert.from_keras(\n nlp.model, input_signature, opset=opset, output_path=output.as_posix()\n )\n\n except ImportError as e:\n raise Exception(\n f\"Cannot import {e.name} required to convert TF model to ONNX. Please install {e.name} first. {e}\"\n )", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, config):\n super().__init__()\n self.chunk_size_feed_forward = config.chunk_size_feed_forward\n self.seq_len_dim = 1\n self.attention = BrosAttention(config)\n self.is_decoder = config.is_decoder\n self.add_cross_attention = config.add_cross_attention\n if self.add_cross_attention:\n if not self.is_decoder:\n raise Exception(f\"{self} should be used as a decoder model if cross attention is added\")\n self.crossattention = BrosAttention(config)\n self.intermediate = BrosIntermediate(config)\n self.output = BrosOutput(config)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def SetForCorrectColorByVariable(inImagesetInfo, inPhactoriOperation,\n inPvDataRepresentation, inPhactoriRepresentation,\n inInitializeColorLegendFlag):\n \"sets the color by variable to a scalar, vector component/magnitude, or\\n tensor component. Assumes we've already established we are doing this\\n instead of solid color or color by block\"\n\n if PhactoriDbg():\n myDebugPrint3(\"SetForCorrectColorByVariable entered\\n\")\n\n savedActiveSourceX = GetActiveSource()\n SetActiveSource(inPhactoriOperation.GetPvFilter())\n\n colorVarInfo = inPhactoriRepresentation.mColorVariableInfo\n\n if PhactoriDbg():\n myDebugPrint3(\"colorVarInfo.mVariableName: \" + \\\n str(colorVarInfo.mVariableName) + \"\\n\")\n\n if colorVarInfo.mVariableName == '':\n myVariableArrayType = gCellsString\n else:\n global gPipeAndViewsState\n #the correct behavior is probably to use the imageset's filter as the\n #filter to use to determine info about the variable, such as POINT or\n #cell; however prior work used the pipeline start default incoming\n #filter. We are using prior to get tests to pass for now, and\n #we are considering switching to 'correct.'\n useImagesetFilterToDetectVariableType = False\n if useImagesetFilterToDetectVariableType:\n paraViewSource = inPhactoriOperation.GetPvFilter()\n else:\n paraViewSource = \\\n gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()\n detectResult = colorVarInfo.DetectVariableType(\n paraViewSource, True, False)\n\n if detectResult == True:\n #variable type detected determine value for paraview\n if colorVarInfo.mVariableType == 'node':\n myVariableArrayType = gPointsString\n elif colorVarInfo.mVariableType == 'element':\n myVariableArrayType = gCellsString\n else:\n if PhactoriDbg():\n myDebugPrint3(errStr)\n errStr = 'CreateParaviewItemsForImagesetC error:\\n'\\\n 'image set ' + inImagesetInfo.mName + \\\n 'operation ' + inPhactoriOperation.mName + \\\n ' representation ' + inPhactoriRepresentation.mName + \\\n '\\ncolor variable name: ' + \\\n colorVarInfo.mVariableName +\\\n '\\nvariable should be node or element at this point and is not'\n raise Exception(errStr)\n else:\n #variable type not detected, deal with it\n errStr = 'CreateParaviewItemsForImagesetC error:\\n'\\\n 'image set ' + inImagesetInfo.mName + \\\n 'operation ' + inPhactoriOperation.mName + \\\n ' representation ' + inPhactoriRepresentation.mName + \\\n '\\ncolor variable name: ' + \\\n colorVarInfo.mVariableName +\\\n '\\nvariable is not point data or cell data, assuming cell'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n #current hack--if detection of variable type fails due to missing\n #variable; assume it is CELLS and let mpi stuff share info\n #and create odd color map otherwise\n myVariableArrayType = gCellsString\n\n if PhactoriDbg():\n myDebugPrint3(\"myVariableArrayType: \" + myVariableArrayType + \"\\n\")\n #(\"showColorLegend: \" + str(showColorLegend) + \"\\n\")\n\n colorVarName = colorVarInfo.mVariableName\n if colorVarName != '':\n if colorVarInfo.mVariableIsVectorComponent:\n if PhactoriDbg():\n myDebugPrint3(\"mVariableIsVectorComponent is true so we do\\n\"\n \"ColorByVariableComponentOrMagnitudeXX (component)\\n\")\n ColorByVariableComponentOrMagnitudeXX(\n inPvDataRepresentation, inPhactoriRepresentation, colorVarName,\n 'Component', colorVarInfo.mVariableComponent, myVariableArrayType,\n inPhactoriRepresentation.mColorMapSettings)\n elif colorVarInfo.mVariableIsVectorMagnitude:\n if PhactoriDbg():\n myDebugPrint3(\"mVariableIsVectorMagnitude is true so we do\\n\"\n \"ColorByVariableComponentOrMagnitudeXX (magnitude)\\n\")\n ColorByVariableComponentOrMagnitudeXX(\n inPvDataRepresentation, inPhactoriRepresentation, colorVarName,\n 'Magnitude', colorVarInfo.mVariableComponent, myVariableArrayType,\n inPhactoriRepresentation.mColorMapSettings)\n else:\n if PhactoriDbg():\n myDebugPrint3(\"not component or magnitude so we do \"\n \"ColorByVariableScalarXX\\n\")\n ColorByVariableScalarXX(inPvDataRepresentation, inPhactoriRepresentation,\n colorVarName, myVariableArrayType,\n inPhactoriRepresentation.mColorMapSettings)\n\n #if inInitializeColorLegendFlag:\n if True:\n if inPhactoriRepresentation.mUseFixedColorRange:\n fixedColorRange = inPhactoriRepresentation.mFixedColorRange\n SetMinimumMaximumColorValues(inPvDataRepresentation,\n fixedColorRange[0], fixedColorRange[1],\n inPhactoriOperation, inPhactoriRepresentation,\n colorVarName, myVariableArrayType)\n #else:\n # SetMinimumMaximumColorValues(inPvDataRepresentation,\n # -0.1, 0.1,\n # inPhactoriRepresentation, colorVarName, myVariableArrayType)\n else:\n if gParaViewCatalystVersionFlag <= 40100:\n inPvDataRepresentation.ColorArrayName = \"\"\n else:\n #if PhactoriDbg():\n # myDebugPrint3(\"using ColorBy() to set no color var 1\\n\")\n inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)\n SafeColorBy(inPvDataRepresentation, (gPointsString,''))\n inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)\n\n if PhactoriDbg():\n myDebugPrint3(\"SetForCorrectColorByVariable returning\\n\")\n\n #inPvDataRepresentation.RescaleTransferFunctionToDataRange(True)\n SetActiveSource(savedActiveSourceX)", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def binding_layout(layout):\n if layout in ShortLayoutTypeNames.keys():\n return layout\n elif layout == cutlass.LayoutType.RowMajor:\n return cutlass_bindings.RowMajor\n elif layout == cutlass.LayoutType.ColumnMajor:\n return cutlass_bindings.ColumnMajor\n elif layout == cutlass.LayoutType.TensorNHWC:\n return cutlass_bindings.TensorNHWC\n else:\n raise Exception(f\"No conversion available for layout {layout} to Python-bound CUTLASS layout.\")", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "@classmethod\n def import_models(cls, model_names: List[Names]) -> Tuple[ModuleType, ...]:\n \"\"\"Imports and returns the storage modules listed in model_names.\n\n Args:\n model_names: list(Names). List of storage module names.\n\n Returns:\n tuple(module). Tuple of storage modules.\n\n Raises:\n Exception. Invalid model name.\n \"\"\"\n returned_models: List[ModuleType] = []\n # There are a lot of ignore[no-redef] used here, since we import\n # gae_models from different folders multiple times. It is fine to use it\n # here since when we import modules using this function, we need to add\n # separate imports for mypy anyway.\n for name in model_names:\n if name == Names.ACTIVITY:\n from core.storage.activity import gae_models as activity_models\n returned_models.append(activity_models)\n elif name == Names.APP_FEEDBACK_REPORT:\n from core.storage.app_feedback_report import (\n gae_models as app_feedback_report_models)\n returned_models.append(app_feedback_report_models)\n elif name == Names.AUDIT:\n from core.storage.audit import gae_models as audit_models\n returned_models.append(audit_models)\n elif name == Names.AUTH:\n from core.storage.auth import gae_models as auth_models\n returned_models.append(auth_models)\n elif name == Names.BASE_MODEL:\n from core.storage.base_model import gae_models as base_model\n returned_models.append(base_model)\n elif name == Names.BEAM_JOB:\n from core.storage.beam_job import gae_models as beam_job_models\n returned_models.append(beam_job_models)\n elif name == Names.BLOG:\n from core.storage.blog import gae_models as blog_models\n returned_models.append(blog_models)\n elif name == Names.BLOG_STATISTICS:\n from core.storage.blog_statistics import (\n gae_models as blog_stats_models)\n returned_models.append(blog_stats_models)\n elif name == Names.CLASSIFIER:\n from core.storage.classifier import (\n gae_models as classifier_models)\n returned_models.append(classifier_models)\n elif name == Names.CLASSROOM:\n from core.storage.classroom import (\n gae_models as classroom_models)\n returned_models.append(classroom_models)\n elif name == Names.COLLECTION:\n from core.storage.collection import (\n gae_models as collection_models)\n returned_models.append(collection_models)\n elif name == Names.CONFIG:\n from core.storage.config import gae_models as config_models\n returned_models.append(config_models)\n elif name == Names.EMAIL:\n from core.storage.email import gae_models as email_models\n returned_models.append(email_models)\n elif name == Names.EXPLORATION:\n from core.storage.exploration import gae_models as exp_models\n returned_models.append(exp_models)\n elif name == Names.FEEDBACK:\n from core.storage.feedback import gae_models as feedback_models\n returned_models.append(feedback_models)\n elif name == Names.IMPROVEMENTS:\n from core.storage.improvements import (\n gae_models as improvements_models)\n returned_models.append(improvements_models)\n elif name == Names.JOB:\n from core.storage.job import gae_models as job_models\n returned_models.append(job_models)\n elif name == Names.LEARNER_GROUP:\n from core.storage.learner_group import (\n gae_models as learner_group_models)\n returned_models.append(learner_group_models)\n elif name == Names.OPPORTUNITY:\n from core.storage.opportunity import (\n gae_models as opportunity_models)\n returned_models.append(opportunity_models)\n elif name == Names.QUESTION:\n from core.storage.question import gae_models as question_models\n returned_models.append(question_models)\n elif name == Names.RECOMMENDATIONS:\n from core.storage.recommendations import (\n gae_models as recommendations_models)\n returned_models.append(recommendations_models)\n elif name == Names.SKILL:\n from core.storage.skill import gae_models as skill_models\n returned_models.append(skill_models)\n elif name == Names.STATISTICS:\n from core.storage.statistics import (\n gae_models as statistics_models)\n returned_models.append(statistics_models)\n elif name == Names.STORY:\n from core.storage.story import gae_models as story_models\n returned_models.append(story_models)\n elif name == Names.SUBTOPIC:\n from core.storage.subtopic import gae_models as subtopic_models\n returned_models.append(subtopic_models)\n elif name == Names.SUGGESTION:\n from core.storage.suggestion import (\n gae_models as suggestion_models)\n returned_models.append(suggestion_models)\n elif name == Names.TOPIC:\n from core.storage.topic import gae_models as topic_models\n returned_models.append(topic_models)\n elif name == Names.TRANSLATION:\n from core.storage.translation import (\n gae_models as translation_models)\n returned_models.append(translation_models)\n elif name == Names.USER:\n from core.storage.user import gae_models as user_models\n returned_models.append(user_models)\n elif name == Names.VOICEOVER:\n from core.storage.voiceover import (\n gae_models as voiceover_models)\n returned_models.append(voiceover_models)\n else:\n raise Exception('Invalid model name: %s' % name)\n\n return tuple(returned_models)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def accept_suggestion(\n suggestion_id: str,\n reviewer_id: str,\n commit_message: str,\n review_message: str\n) -> None:\n \"\"\"Accepts the suggestion with the given suggestion_id after validating it.\n\n Args:\n suggestion_id: str. The id of the suggestion to be accepted.\n reviewer_id: str. The ID of the reviewer accepting the suggestion.\n commit_message: str. The commit message.\n review_message: str. The message provided by the reviewer while\n accepting the suggestion.\n\n Raises:\n Exception. The suggestion is already handled.\n Exception. The suggestion is not valid.\n Exception. The commit message is empty.\n \"\"\"\n if not commit_message or not commit_message.strip():\n raise Exception('Commit message cannot be empty.')\n\n suggestion = get_suggestion_by_id(suggestion_id, strict=False)\n\n if suggestion is None:\n raise Exception(\n 'You cannot accept the suggestion with id %s because it does '\n 'not exist.' % (suggestion_id)\n )\n if suggestion.is_handled:\n raise Exception(\n 'The suggestion with id %s has already been accepted/'\n 'rejected.' % (suggestion_id)\n )\n suggestion.pre_accept_validate()\n html_string = ''.join(suggestion.get_all_html_content_strings())\n error_list = (\n html_validation_service.\n validate_math_tags_in_html_with_attribute_math_content(\n html_string))\n if len(error_list) > 0:\n raise Exception(\n 'Invalid math tags found in the suggestion with id %s.' % (\n suggestion.suggestion_id)\n )\n\n if suggestion.edited_by_reviewer:\n commit_message = '%s (with edits)' % commit_message\n\n suggestion.set_suggestion_status_to_accepted()\n suggestion.set_final_reviewer_id(reviewer_id)\n\n author_name = user_services.get_username(suggestion.author_id)\n commit_message = get_commit_message_for_suggestion(\n author_name, commit_message)\n suggestion.accept(commit_message)\n\n _update_suggestion(suggestion)\n\n # Update the community contribution stats so that the number of suggestions\n # of this type that are in review decreases by one, since this\n # suggestion is no longer in review.\n _update_suggestion_counts_in_community_contribution_stats([suggestion], -1)\n\n feedback_services.create_message(\n suggestion_id, reviewer_id, feedback_models.STATUS_CHOICES_FIXED,\n None, review_message, should_send_email=False)\n\n # When recording of scores is enabled, the author of the suggestion gets an\n # increase in their score for the suggestion category.\n if feconf.ENABLE_RECORDING_OF_SCORES:\n user_id = suggestion.author_id\n score_category = suggestion.score_category\n\n # Get user proficiency domain object.\n user_proficiency = _get_user_proficiency(user_id, score_category)\n\n # Increment the score of the author due to their suggestion being\n # accepted.\n user_proficiency.increment_score(\n suggestion_models.INCREMENT_SCORE_OF_AUTHOR_BY\n )\n\n # Emails are sent to onboard new reviewers. These new reviewers are\n # created when the score of the user passes the minimum score required\n # to review.\n if feconf.SEND_SUGGESTION_REVIEW_RELATED_EMAILS:\n if user_proficiency.can_user_review_category() and (\n not user_proficiency.onboarding_email_sent):\n email_manager.send_mail_to_onboard_new_reviewers(\n user_id, score_category\n )\n user_proficiency.mark_onboarding_email_as_sent()\n\n # Need to update the corresponding user proficiency model after we\n # updated the domain object.\n _update_user_proficiency(user_proficiency)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_change_cwd__non_existent_dir(self):\n \"\"\"Test passing a non-existent directory.\"\"\"\n original_cwd = os.getcwd()\n\n def call_change_cwd(path):\n with os_helper.change_cwd(path) as new_cwd:\n raise Exception(\"should not get here\")\n\n with os_helper.temp_dir() as parent_dir:\n non_existent_dir = os.path.join(parent_dir, 'does_not_exist')\n self.assertRaises(FileNotFoundError, call_change_cwd,\n non_existent_dir)\n\n self.assertEqual(os.getcwd(), original_cwd)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def default(self, obj):\n if not isinstance(obj, OvmBridge): raise Exception(\"%s is not instance of OvmBridge\"%type(obj))\n dct = {}\n safeDictSet(obj, dct, 'name')\n safeDictSet(obj, dct, 'attach')\n safeDictSet(obj, dct, 'interfaces')\n return dct", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "@acl_decorators.can_perform_tasks_in_taskqueue\n def post(self) -> None:\n \"\"\"Defers tasks for execution in the background.\n\n Raises:\n Exception. This request cannot defer tasks because it does not\n contain a function identifier attribute (fn_identifier).\n Deferred tasks must contain a function_identifier in the\n payload.\n \"\"\"\n # The request body has bytes type, thus we need to decode it first.\n payload = json.loads(self.request.body.decode('utf-8'))\n if 'fn_identifier' not in payload:\n raise Exception(\n 'This request cannot defer tasks because it does not contain a '\n 'function identifier attribute (fn_identifier). Deferred tasks '\n 'must contain a function_identifier in the payload.')\n if payload['fn_identifier'] not in self.DEFERRED_TASK_FUNCTIONS:\n raise Exception(\n 'The function id, %s, is not valid.' % payload['fn_identifier'])\n\n deferred_task_function = self.DEFERRED_TASK_FUNCTIONS[\n payload['fn_identifier']]\n deferred_task_function(*payload['args'], **payload['kwargs'])\n self.render_json({})", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def default(self, obj):\n if not isinstance(obj, OvmVolume): raise Exception(\"%s is not instance of OvmVolume\"%type(obj))\n dct = {}\n safeDictSet(obj, dct, 'name')\n safeDictSet(obj, dct, 'uuid')\n safeDictSet(obj, dct, 'poolUuid')\n safeDictSet(obj, dct, 'path')\n safeDictSet(obj, dct, 'size')\n return dct", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def validate_and_normalize_args(self) -> None:\n \"\"\"Validates schema for controller layer handler class arguments.\n\n Raises:\n InvalidInputException. Schema validation failed.\n NotImplementedError. Schema is not provided in handler class.\n \"\"\"\n handler_class_name = self.__class__.__name__\n request_method = self.request.environ['REQUEST_METHOD']\n\n # For HEAD requests, we use the schema of GET handler,\n # because HEAD returns just the handlers of the GET request.\n if request_method == 'HEAD':\n request_method = 'GET'\n\n url_path_args = self.request.route_kwargs\n\n if (\n handler_class_name in\n handler_schema_constants.HANDLER_CLASS_NAMES_WITH_NO_SCHEMA\n ):\n # TODO(#13155): Remove this clause once all the handlers have had\n # schema validation implemented.\n if self.URL_PATH_ARGS_SCHEMAS or self.HANDLER_ARGS_SCHEMAS:\n raise self.InternalErrorException(\n 'Remove handler class name from '\n 'HANDLER_CLASS_NAMES_WHICH_STILL_NEED_SCHEMAS')\n return\n\n handler_args = {}\n payload_arg_keys = []\n request_arg_keys = []\n for arg in self.request.arguments():\n if arg == 'csrf_token':\n # 'csrf_token' has been already validated in the\n # dispatch method.\n pass\n elif arg == 'source':\n source_url = self.request.get('source')\n regex_pattern = (\n r'http[s]?://(?:[a-zA-Z]|[0-9]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # pylint: disable=line-too-long\n )\n regex_verified_url = re.findall(regex_pattern, source_url)\n if not regex_verified_url:\n raise self.InvalidInputException(\n 'Not a valid source url.')\n elif arg == 'payload':\n payload_args = self.payload\n if payload_args is not None:\n payload_arg_keys = list(payload_args.keys())\n handler_args.update(payload_args)\n else:\n request_arg_keys.append(arg)\n handler_args[arg] = self.request.get(arg)\n\n # For html handlers, extra args are allowed (to accommodate\n # e.g. utm parameters which are not used by the backend but\n # needed for analytics).\n extra_args_are_allowed = (\n self.GET_HANDLER_ERROR_RETURN_TYPE == feconf.HANDLER_TYPE_HTML and\n request_method == 'GET')\n\n if self.URL_PATH_ARGS_SCHEMAS is None:\n raise NotImplementedError(\n 'Missing schema for url path args in %s handler class.' % (\n handler_class_name))\n\n schema_for_url_path_args = self.URL_PATH_ARGS_SCHEMAS\n self.request.route_kwargs, errors = (\n payload_validator.validate_arguments_against_schema(\n url_path_args, schema_for_url_path_args, extra_args_are_allowed)\n )\n\n if errors:\n raise self.InvalidInputException(\n 'At \\'%s\\' these errors are happening:\\n%s' % (\n self.request.uri, '\\n'.join(errors)\n )\n )\n\n # This check ensures that if a request method is not defined\n # in the handler class then schema validation will not raise\n # NotImplementedError for that corresponding request method.\n if request_method in ['GET', 'POST', 'PUT', 'DELETE'] and (\n getattr(self.__class__, request_method.lower()) ==\n getattr(BaseHandler, request_method.lower())):\n return\n\n try:\n if self.HANDLER_ARGS_SCHEMAS is None:\n raise Exception(\n 'No \\'HANDLER_ARGS_SCHEMAS\\' Found for the '\n 'handler class: %s' % handler_class_name\n )\n schema_for_request_method = self.HANDLER_ARGS_SCHEMAS[\n request_method]\n except Exception as e:\n raise NotImplementedError(\n 'Missing schema for %s method in %s handler class.' % (\n request_method, handler_class_name)) from e\n\n allow_string_to_bool_conversion = request_method in ['GET', 'DELETE']\n normalized_arg_values, errors = (\n payload_validator.validate_arguments_against_schema(\n handler_args, schema_for_request_method, extra_args_are_allowed,\n allow_string_to_bool_conversion)\n )\n\n normalized_payload = {\n arg: normalized_arg_values.get(arg) for arg in payload_arg_keys\n }\n normalized_request = {\n arg: normalized_arg_values.get(arg) for arg in request_arg_keys\n }\n\n # The following keys are absent in request/payload but present in\n # normalized_arg_values because these args are populated from their\n # default_value provided in the schema.\n keys_that_correspond_to_default_values = list(\n set(normalized_arg_values.keys()) -\n set(payload_arg_keys + request_arg_keys)\n )\n # Populate the payload/request with the default args before passing\n # execution onwards to the handler.\n for arg in keys_that_correspond_to_default_values:\n if request_method in ['GET', 'DELETE']:\n normalized_request[arg] = normalized_arg_values.get(arg)\n else:\n normalized_payload[arg] = normalized_arg_values.get(arg)\n\n # Here we use MyPy ignore because 'normalized_payload' is of\n # Dict[str, Any] type, whereas 'self.normalized_payload' is a Generic\n # type whose type can be decided while defining sub-classes. So, Due\n # to this mismatch in types MyPy throws an error. Thus, to silence the\n # error, we used type ignore here.\n self.normalized_payload = normalized_payload # type: ignore[assignment]\n # Here we use MyPy ignore because 'normalized_request' is of\n # Dict[str, Any] type, whereas 'self.normalized_request' is a Generic\n # type whose type can be decided while defining sub-classes. So, Due\n # to this mismatch in types MyPy throws an error. Thus, to silence the\n # error, we used type ignore here.\n self.normalized_request = normalized_request # type: ignore[assignment]\n\n # Here we use MyPy ignore because here we assigning RaiseErrorOnGet's\n # instance to a 'get' method, and according to MyPy assignment to a\n # method is not allowed.\n self.request.get = RaiseErrorOnGet( # type: ignore[assignment]\n 'Use self.normalized_request instead of self.request.').get\n self.payload = RaiseErrorOnGet(\n 'Use self.normalized_payload instead of self.payload.')\n\n if errors:\n raise self.InvalidInputException(\n 'At \\'%s\\' these errors are happening:\\n%s' % (\n self.request.uri, '\\n'.join(errors)\n )\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def delete(cls, obj_id):\n raise Exception(\"should use delete_alias(alias,user) instead\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def _save_skill(\n committer_id: str,\n skill: skill_domain.Skill,\n commit_message: str,\n change_list: List[skill_domain.SkillChange]\n) -> None:\n \"\"\"Validates a skill and commits it to persistent storage. If\n successful, increments the version number of the incoming skill domain\n object by 1.\n\n Args:\n committer_id: str. ID of the given committer.\n skill: Skill. The skill domain object to be saved.\n commit_message: str. The commit message.\n change_list: list(SkillChange). List of changes applied to a skill.\n\n Raises:\n Exception. The skill model and the incoming skill domain object have\n different version numbers.\n Exception. Received invalid change list.\n \"\"\"\n if not change_list:\n raise Exception(\n 'Unexpected error: received an invalid change list when trying to '\n 'save skill %s: %s' % (skill.id, change_list))\n skill.validate()\n\n # Skill model cannot be None as skill is passed as parameter here and that\n # is only possible if a skill model with that skill id exists.\n skill_model = skill_models.SkillModel.get(\n skill.id, strict=True)\n\n if skill.version > skill_model.version:\n raise Exception(\n 'Unexpected error: trying to update version %s of skill '\n 'from version %s. Please reload the page and try again.'\n % (skill_model.version, skill.version))\n\n if skill.version < skill_model.version:\n raise Exception(\n 'Trying to update version %s of skill from version %s, '\n 'which is too old. Please reload the page and try again.'\n % (skill_model.version, skill.version))\n\n skill_model = populate_skill_model_fields(skill_model, skill)\n change_dicts = [change.to_dict() for change in change_list]\n skill_model.commit(committer_id, commit_message, change_dicts)\n caching_services.delete_multi(\n caching_services.CACHE_NAMESPACE_SKILL, None, [skill.id])\n skill.version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def run_masscan(target_ip) -> bytes:\n \"\"\"Run Masscan in Docker.\"\"\"\n client = docker.from_env()\n\n # Scan according to arguments.\n port_range = os.getenv(\"PORTS\", \"53,80,443\")\n max_rate = os.getenv(\"MAX_RATE\", 100)\n logging.info(\"Starting container %s to run masscan...\", IMAGE)\n res = client.containers.run(\n image=IMAGE, command=f\"-p {port_range} --max-rate {max_rate} -oJ {FILE_PATH} {target_ip}\", detach=True\n )\n res.wait()\n logging.debug(res.logs())\n\n output = get_file_from_container(container=res, path=FILE_PATH)\n\n if not output:\n raise Exception(f\"Couldn't get {FILE_PATH} from masscan container\")\n\n # Do not crash the boefje if the output is known, instead log a warning.\n try:\n res.remove()\n except Exception as e:\n logging.warning(e)\n\n return output", "smellKey": "S112", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def paths_to_unmount(path, mnttype):\n paths = []\n for m in mountinfo():\n if m.path == path or m.path.startswith(path+\"/\"):\n paths.append(m.path)\n if not (m.is_fuse and (mnttype is None or\n mnttype == m.mnttype)):\n raise Exception(\n \"cannot unmount {}: mount type is {}\".format(\n path, m.mnttype))\n return paths", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def test_reuse_rollback_commit(self):\n atomic = transaction.atomic()\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with atomic:\n Reporter.objects.create(last_name=\"Tintin\")\n with atomic:\n Reporter.objects.create(last_name=\"Haddock\")\n raise Exception(\"Oops, that's his first name\")\n self.assertSequenceEqual(Reporter.objects.all(), [])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(\n self, operation: \"GemmOperation\", problem_size: \"cutlass_bindings.gemm.GemmCoord\",\n A: \"Tensor\", B: \"Tensor\", C: \"Tensor\", D: \"Tensor\",\n gemm_mode: \"cutlass_bindings.gemm.Mode\" = cutlass_bindings.gemm.Mode.Gemm, **kwargs):\n if gemm_mode not in [cutlass_bindings.gemm.Mode.Gemm, cutlass_bindings.gemm.Mode.Batched]:\n raise Exception(\"Unsupporged GEMM mode {}.\".format(gemm_mode))\n\n super().__init__(operation, problem_size, A, B, C, D, gemm_mode, **kwargs)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def commit(\n self,\n committer_id: str,\n commit_message: Optional[str],\n commit_cmds: AllowedCommitCmdsListType\n ) -> None:\n \"\"\"Saves a version snapshot and updates the model.\n\n Args:\n committer_id: str. The user_id of the user who committed the change.\n commit_message: str|None. The commit description message, or None if\n draft (or unpublished) model is provided.\n commit_cmds: list(dict). A list of commands, describing changes\n made in this model, should give sufficient information to\n reconstruct the commit. Dict always contains:\n cmd: str. Unique command.\n And then additional arguments for that command. For example:\n\n {'cmd': 'AUTO_revert_version_number'\n 'version_number': 4}\n\n Raises:\n Exception. This model instance has been already deleted.\n Exception. The commit_cmd is in invalid format.\n \"\"\"\n self._require_not_marked_deleted()\n\n for commit_cmd in commit_cmds:\n if not isinstance(commit_cmd, dict):\n raise Exception(\n 'Expected commit_cmds to be a list of dicts, received %s'\n % commit_cmds)\n if 'cmd' not in commit_cmd:\n raise Exception(\n 'Invalid commit_cmd: %s. Expected a \\'cmd\\' key.'\n % commit_cmd)\n if commit_cmd['cmd'].startswith(self._AUTOGENERATED_PREFIX):\n raise Exception(\n 'Invalid change list command: %s' % commit_cmd['cmd'])\n\n models_to_put = self.get_models_to_put_values(\n committer_id,\n commit_message,\n commit_cmds\n )\n BaseModel.update_timestamps_multi(models_to_put)\n BaseModel.put_multi_transactional(models_to_put)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_error_response(self, *args, **params):\n \"\"\"\n Call `get_response` (see above) and assert that the response's status\n code is an error code. Basically it's syntactic sugar.\n\n :param params:\n * status_code: (Optional) Assert that the response's status code is\n a specific error code. Omit to assert any error status_code.\n :returns Response object\n \"\"\"\n status_code = params.pop(\"status_code\", None)\n\n if status_code and status_code < 400:\n raise Exception(\"status_code must be >= 400 (an error status code)\")\n\n response = self.get_response(*args, **params)\n\n if status_code:\n assert_status_code(response, status_code)\n else:\n assert_status_code(response, 400, 600)\n\n return response", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_datatype_and_layout(tensor):\n if (numpy_available and isinstance(tensor, np.ndarray)) or (\n cupy_available and isinstance(tensor, cp.ndarray)\n ):\n return _tensor_from_numpy(tensor)\n elif torch_available and isinstance(tensor, torch.Tensor):\n return _tensor_from_torch(tensor)\n else:\n raise Exception(f\"Unable to convert tensor of type {type(tensor)} to Python-bound CUTLASS datatype and layout.\")", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def test_fileobj(self):\n # Test that __exit__() did not close the external file\n # object.\n with open(tmpname, \"wb\") as fobj:\n try:\n with tarfile.open(fileobj=fobj, mode=\"w\") as tar:\n raise Exception\n except:\n pass\n self.assertFalse(fobj.closed, \"external file object was closed\")\n self.assertTrue(tar.closed, \"context manager failed\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_human_readable_user_ids(\n user_ids: List[str], strict: bool = True\n) -> List[str]:\n \"\"\"Converts the given ids to usernames, or truncated email addresses.\n Requires all users to be known.\n\n Args:\n user_ids: list(str). The list of user_ids to get UserSettings domain\n objects for.\n strict: bool. Whether to fail noisily if no user with the given\n id exists in the datastore. Defaults to True.\n\n Returns:\n list(str). List of usernames corresponding to given user_ids. If\n username does not exist, the corresponding entry in the returned\n list is the user's truncated email address. If the user is scheduled to\n be deleted USER_IDENTIFICATION_FOR_USER_BEING_DELETED is returned.\n\n Raises:\n Exception. At least one of the user_ids does not correspond to a valid\n UserSettingsModel.\n \"\"\"\n users_settings = get_users_settings(user_ids, include_marked_deleted=True)\n usernames = []\n for ind, user_settings in enumerate(users_settings):\n if user_settings is None:\n if strict:\n logging.error('User id %s not known in list of user_ids %s' % (\n user_ids[ind], user_ids))\n raise Exception('User not found.')\n elif user_settings.deleted:\n usernames.append(LABEL_FOR_USER_BEING_DELETED)\n elif user_settings.username:\n usernames.append(user_settings.username)\n else:\n usernames.append(\n '[Awaiting user registration: %s]' %\n user_settings.truncated_email)\n return usernames", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def from_dict(cls, param_dict: PlatformParameterDict) -> PlatformParameter:\n \"\"\"Returns an PlatformParameter object from a dict.\n\n Args:\n param_dict: dict. A dict mapping of all fields of\n PlatformParameter object.\n\n Returns:\n PlatformParameter. The corresponding PlatformParameter domain\n object.\n\n Raises:\n Exception. Given schema version is not supported.\n \"\"\"\n if (param_dict['rule_schema_version'] !=\n feconf.CURRENT_PLATFORM_PARAMETER_RULE_SCHEMA_VERSION):\n # NOTE: When there's a new rule schema version, a new method with\n # name of the form '_convert_rule_v1_dict_to_v2_dict` should be\n # added to the class and called here to convert the rule dicts to\n # the latest schema.\n raise Exception(\n 'Current platform parameter rule schema version is v%s, '\n 'received v%s, and there\\'s no convert method from v%s to '\n 'v%s.' % (\n feconf.CURRENT_PLATFORM_PARAMETER_RULE_SCHEMA_VERSION,\n param_dict['rule_schema_version'],\n feconf.CURRENT_PLATFORM_PARAMETER_RULE_SCHEMA_VERSION,\n param_dict['rule_schema_version']))\n\n return cls(\n param_dict['name'],\n param_dict['description'],\n param_dict['data_type'],\n [\n PlatformParameterRule.from_dict(rule_dict)\n for rule_dict in param_dict['rules']],\n param_dict['rule_schema_version'],\n param_dict['default_value'],\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def destroy_cipher_key(self, key):\n ret = self._driver.SDF_DestroyKey(self._session, key)\n if ret != 0:\n raise Exception(\"destroy key failed\")", "smellKey": "S112", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def ogrinfo(data_source, num_features=10):\n \"\"\"\n Walk the available layers in the supplied `data_source`, displaying\n the fields for the first `num_features` features.\n \"\"\"\n\n # Checking the parameters.\n if isinstance(data_source, str):\n data_source = DataSource(data_source)\n elif isinstance(data_source, DataSource):\n pass\n else:\n raise Exception(\n \"Data source parameter must be a string or a DataSource object.\"\n )\n\n for i, layer in enumerate(data_source):\n print(\"data source : %s\" % data_source.name)\n print(\"==== layer %s\" % i)\n print(\" shape type: %s\" % GEO_CLASSES[layer.geom_type.num].__name__)\n print(\" # features: %s\" % len(layer))\n print(\" srs: %s\" % layer.srs)\n extent_tup = layer.extent.tuple\n print(\" extent: %s - %s\" % (extent_tup[0:2], extent_tup[2:4]))\n print(\"Displaying the first %s features ====\" % num_features)\n\n width = max(*map(len, layer.fields))\n fmt = \" %%%ss: %%s\" % width\n for j, feature in enumerate(layer[:num_features]):\n print(\"=== Feature %s\" % j)\n for fld_name in layer.fields:\n type_name = feature[fld_name].type_name\n output = fmt % (fld_name, type_name)\n val = feature.get(fld_name)\n if val:\n if isinstance(val, str):\n val_fmt = ' (\"%s\")'\n else:\n val_fmt = \" (%s)\"\n output += val_fmt % val\n else:\n output += \" (None)\"\n print(output)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _check_for_mandatory_pattern_in_file(\n self,\n pattern_list: List[MandatoryPatternsRegexpDict],\n filepath: str,\n failed: bool\n ) -> Tuple[bool, List[str]]:\n \"\"\"Checks for a given mandatory pattern in a file.\n\n Args:\n pattern_list: list(dict). The list of the mandatory patterns list to\n be checked for in the file.\n filepath: str. The path to the file to be linted.\n failed: bool. Status of failure of the check.\n\n Returns:\n Tuple[bool, List[str]]. The failure status of the check\n and error messages.\n\n Raises:\n Exception. Given file at filepath is not readable.\n \"\"\"\n # This boolean list keeps track of the regex matches\n # found in the file.\n pattern_found_list = []\n error_messages = []\n\n try:\n file_content = self.file_cache.readlines(filepath)\n except Exception as e:\n raise Exception('%s %s' % (filepath, e)) from e\n for index, regexp_to_check in enumerate(\n pattern_list):\n if (any(filepath.endswith(\n allowed_type) for allowed_type in (\n regexp_to_check['included_types'])) and (\n not any(\n filepath.endswith(\n pattern) for pattern in (\n regexp_to_check['excluded_files'] +\n regexp_to_check['excluded_dirs'])))):\n pattern_found_list.append(index)\n for line in file_content:\n if regexp_to_check['regexp'].search(line):\n pattern_found_list.pop()\n break\n if pattern_found_list:\n failed = True\n for pattern_found in pattern_found_list:\n error_message = ('%s --> %s' % (\n filepath,\n pattern_list[pattern_found]['message']))\n error_messages.append(error_message)\n\n return failed, error_messages", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_tensor_shape(tensor):\n if (numpy_available and isinstance(tensor, np.ndarray)) or (\n cupy_available and isinstance(tensor, cp.ndarray)\n ):\n return tensor.shape\n elif torch_available and isinstance(tensor, torch.Tensor):\n size = tensor.size()\n return (size[0], size[2], size[3], size[1])\n else:\n raise Exception(f\"Unable to convert tensor of type {type(tensor)} to Python-bound CUTLASS datatype and layout.\")", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def exp_rename(old_name, new_name):\n openerp.modules.registry.RegistryManager.delete(old_name)\n openerp.sql_db.close_db(old_name)\n\n db = openerp.sql_db.db_connect('postgres')\n with closing(db.cursor()) as cr:\n cr.autocommit(True) # avoid transaction block\n _drop_conn(cr, old_name)\n try:\n cr.execute('ALTER DATABASE \"%s\" RENAME TO \"%s\"' % (old_name, new_name))\n _logger.info('RENAME DB: %s -> %s', old_name, new_name)\n except Exception, e:\n _logger.info('RENAME DB: %s -> %s failed:\\n%s', old_name, new_name, e)\n raise Exception(\"Couldn't rename database %s to %s: %s\" % (old_name, new_name, e))\n\n old_fs = openerp.tools.config.filestore(old_name)\n new_fs = openerp.tools.config.filestore(new_name)\n if os.path.exists(old_fs) and not os.path.exists(new_fs):\n shutil.move(old_fs, new_fs)\n return True", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def _getVmPathFromPrimaryStorage(self, vmName):\n '''\n we don't have a database to store vm states, so there is no way to retrieve information of a vm\n when it was already stopped. The trick is to try to find the vm path in primary storage then we\n can read information from its configure file.\n '''\n mps = OvmStoragePool()._getAllMountPoints()\n vmPath = None\n for p in mps:\n vmPath = join(p, 'running_pool', vmName)\n if exists(vmPath): break\n if not vmPath:\n logger.error(self._getVmPathFromPrimaryStorage, \"Cannot find link for %s in any primary storage, the vm was really gone!\"%vmName)\n raise Exception(\"Cannot find link for %s in any primary storage, the vm was really gone!\"%vmName)\n return vmPath", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def __call__(self, x: Tensor):\n \"\"\"\n Transfer the weights of `self.src` to `self.dest` by performing a forward pass using `x` as input. Under the\n hood we tracked all the operations in both modules.\n \"\"\"\n dest_traced = Tracker(self.dest)(x).parametrized\n src_traced = Tracker(self.src)(x).parametrized\n\n src_traced = list(filter(lambda x: type(x) not in self.src_skip, src_traced))\n dest_traced = list(filter(lambda x: type(x) not in self.dest_skip, dest_traced))\n\n if len(dest_traced) != len(src_traced) and self.raise_if_mismatch:\n raise Exception(\n f\"Numbers of operations are different. Source module has {len(src_traced)} operations while\"\n f\" destination module has {len(dest_traced)}.\"\n )\n\n for dest_m, src_m in zip(dest_traced, src_traced):\n dest_m.load_state_dict(src_m.state_dict())\n if self.verbose == 1:\n print(f\"Transfered from={src_m} to={dest_m}\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_geometry_type(self, table_name, description):\n with self.connection.cursor() as cursor:\n # Querying the `geometry_columns` table to get additional metadata.\n cursor.execute(\n \"SELECT coord_dimension, srid, geometry_type \"\n \"FROM geometry_columns \"\n \"WHERE f_table_name=%s AND f_geometry_column=%s\",\n (table_name, description.name),\n )\n row = cursor.fetchone()\n if not row:\n raise Exception(\n 'Could not find a geometry column for \"%s\".\"%s\"'\n % (table_name, description.name)\n )\n\n # OGRGeomType does not require GDAL and makes it easy to convert\n # from OGC geom type name to Django field.\n ogr_type = row[2]\n if isinstance(ogr_type, int) and ogr_type > 1000:\n # SpatiaLite uses SFSQL 1.2 offsets 1000 (Z), 2000 (M), and\n # 3000 (ZM) to indicate the presence of higher dimensional\n # coordinates (M not yet supported by Django).\n ogr_type = ogr_type % 1000 + OGRGeomType.wkb25bit\n field_type = OGRGeomType(ogr_type).django\n\n # Getting any GeometryField keyword arguments that are not the default.\n dim = row[0]\n srid = row[1]\n field_params = {}\n if srid != 4326:\n field_params[\"srid\"] = srid\n if (isinstance(dim, str) and \"Z\" in dim) or dim == 3:\n field_params[\"dim\"] = 3\n return field_type, field_params", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def racetime_auto_record(race_data):\n url = RACETIME_URL + race_data['url']\n record_url = url + \"/monitor/record\"\n recorded = race_data.get('recorded', True)\n recordable = race_data.get('recordable', False)\n\n if recorded or not recordable:\n return\n\n async with aiohttp.ClientSession() as session:\n try:\n async with session.request(\n method='get',\n url=url,\n cookies={'sessionid': RACETIME_SESSION_TOKEN,\n 'csrftoken': RACETIME_CSRF_TOKEN},\n raise_for_status=True\n ) as resp:\n soup = BeautifulSoup(await resp.text(), features=\"html5lib\")\n except Exception as e:\n raise Exception(\"Unable to acquire CSRF token. Please contact Synack for help.\") from e\n\n csrftoken = soup.find('input', {'name': 'csrfmiddlewaretoken'})['value']\n data = {'csrfmiddlewaretoken': csrftoken}\n\n try:\n async with aiohttp.request(\n method='post',\n url=record_url,\n cookies={'sessionid': RACETIME_SESSION_TOKEN,\n 'csrftoken': RACETIME_CSRF_TOKEN},\n headers={'Origin': RACETIME_URL,\n 'Referer': url},\n data=data,\n raise_for_status=True\n ) as resp:\n pass\n except Exception:\n logging.exception(\"Unable to automatically record race. Skipping...\")", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "@patch(\"sentry.integrations.slack.unfurl.discover.client.get\")\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_saved_query_with_interval(self, mock_generate_chart, api_mock):\n query = {\n \"fields\": [\"title\", \"event.type\", \"project\", \"user.display\", \"timestamp\"],\n \"query\": \"\",\n \"yAxis\": \"count()\",\n \"interval\": \"10m\",\n \"statsPeriod\": \"24h\",\n }\n saved_query = DiscoverSavedQuery.objects.create(\n organization=self.organization,\n created_by_id=self.user.id,\n name=\"Test query\",\n query=query,\n version=2,\n )\n saved_query.set_projects([self.project.id])\n api_mock.return_value.data = query\n\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?id={saved_query.id}&statsPeriod=24h\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n\n assert len(mock_generate_chart.mock_calls) == 1\n assert len(api_mock.mock_calls) == 2\n\n assert \"interval\" in api_mock.call_args[1][\"params\"]\n assert api_mock.call_args[1][\"params\"][\"interval\"] == \"10m\"", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def convert_image_binary_to_data_url(\n content: bytes, file_type: str\n) -> str:\n \"\"\"Converts a PNG or WEBP image string (represented by 'content')\n to a data URL.\n\n Args:\n content: str. PNG or WEBP binary file content.\n file_type: str. Type of the binary data, webp or png.\n\n Returns:\n str. Data URL created from the binary content of the PNG or WEBP.\n\n Raises:\n Exception. The given binary string does not represent a PNG image.\n Exception. The given binary string does not represent a WEBP image.\n \"\"\"\n if imghdr.what(None, h=content) == file_type:\n return '%s%s' % (\n DATA_URL_FORMAT_PREFIX % file_type,\n urllib.parse.quote(base64.b64encode(content))\n )\n else:\n raise Exception(\n 'The given string does not represent a %s image.' % file_type)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def getDbDifferences(fromDbUrl, toDbUrl):\n try:\n print(\"DB Difference is=>\")\n cmd = 'npx prisma migrate diff --from-url {toDbUrl} --to-url {fromDbUrl} --script > ../migration.sql'.format(\n fromDbUrl=fromDbUrl, toDbUrl=toDbUrl);\n os.system(cmd)\n except Exception as e:\n raise Exception('Error in npx prisma migrate diff')", "smellKey": "S112", "smellId": null, "repo": "REAN-Foundation_reancare-service", "language": "python"} {"function": "def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def parse(self, de, mode=None):\n roots = ['openerp','data','odoo']\n if de.tag not in roots:\n raise Exception(\"Root xml tag must be <openerp>, <odoo> or <data>.\")\n for rec in de:\n if rec.tag in roots:\n self.parse(rec, mode)\n elif rec.tag in self._tags:\n try:\n self._tags[rec.tag](self.cr, rec, de, mode=mode)\n except Exception, e:\n self.cr.rollback()\n exc_info = sys.exc_info()\n raise ParseError, (misc.ustr(e), etree.tostring(rec).rstrip(), rec.getroottree().docinfo.URL, rec.sourceline), exc_info[2]\n return True", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def _reset_operations(self, reset_epilogue: bool = True):\n # Set the default op class\n datatype_comb = (self._element_a, self._element_b, self._element_accumulator)\n layout_comb = (self._layout_a, self._layout_b)\n \n self.possible_op_classes = self.options.supporting_opclasses(\n self._element_a, self._element_b, self._element_accumulator,\n self._layout_a, self._layout_b\n )\n \n if cutlass.OpcodeClass.TensorOp in self.possible_op_classes:\n self.opclass = cutlass.OpcodeClass.TensorOp\n elif cutlass.OpcodeClass.Simt in self.possible_op_classes:\n self.opclass = cutlass.OpcodeClass.Simt\n else:\n raise Exception(f'No kernel configuration found for supported data type and layout '\n f'combination {datatype_comb}x{layout_comb}')\n \n if reset_epilogue:\n self._reset_epilogue_functor_activation(epilogue.identity)\n \n self.alignment_pref_A = min(\n 128 // cutlass.DataTypeSize[self._element_a], max(self.possible_operations.alignments))\n self.alignment_pref_B = min(\n 128 // cutlass.DataTypeSize[self._element_b], max(self.possible_operations.alignments))\n self.alignment_pref_C = min(\n 128 // cutlass.DataTypeSize[self._element_c], max(self.possible_operations.alignments))", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def compile_protobuf_files(proto_files_paths: List[str]) -> None:\n \"\"\"Compiles protobuf files using buf.\n\n Raises:\n Exception. If there is any error in compiling the proto files.\n \"\"\"\n proto_env = os.environ.copy()\n proto_env['PATH'] += '%s%s/bin' % (os.pathsep, PROTOC_DIR)\n proto_env['PATH'] += '%s%s/bin' % (os.pathsep, PROTOC_GEN_TS_PATH)\n buf_path = os.path.join(\n BUF_DIR,\n BUF_DARWIN_FILES[0] if common.is_mac_os() else BUF_LINUX_FILES[0])\n for path in proto_files_paths:\n command = [\n buf_path, 'generate', path]\n process = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n env=proto_env)\n stdout, stderr = process.communicate()\n if process.returncode == 0:\n print(stdout)\n else:\n print(stderr)\n raise Exception('Error compiling proto files at %s' % path)\n\n # Since there is no simple configuration for imports when using protobuf to\n # generate Python files we need to manually fix the imports.\n # See: https://github.com/protocolbuffers/protobuf/issues/1491\n compiled_protobuf_dir = (\n pathlib.Path(os.path.join(common.CURR_DIR, 'proto_files')))\n for p in compiled_protobuf_dir.iterdir():\n if p.suffix == '.py':\n common.inplace_replace_file(\n p.absolute().as_posix(),\n r'^import (\\w*_pb2 as)', r'from proto_files import \\1')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def check_full_copies(overwrite: bool = False):\n \"\"\"\n Check the files that are full copies of others (as indicated in `FULL_COPIES`) are copy-consistent.\n\n Args:\n overwrite (`bool`, *optional*, defaults to `False`):\n Whether or not to overwrite the copies when they don't match.\n \"\"\"\n diffs = []\n for target, source in FULL_COPIES.items():\n with open(source, \"r\", encoding=\"utf-8\") as f:\n source_code = f.read()\n with open(target, \"r\", encoding=\"utf-8\") as f:\n target_code = f.read()\n if source_code != target_code:\n if overwrite:\n with open(target, \"w\", encoding=\"utf-8\") as f:\n print(f\"Replacing the content of {target} by the one of {source}.\")\n f.write(source_code)\n else:\n diffs.append(f\"- {target}: copy does not match {source}.\")\n\n if not overwrite and len(diffs) > 0:\n diff = \"\\n\".join(diffs)\n raise Exception(\n \"Found the following copy inconsistencies:\\n\"\n + diff\n + \"\\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.\"\n )", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def subscribe_to_creator(user_id: str, creator_id: str) -> None:\n \"\"\"Subscribes a user (learner) to a creator.\n\n WARNING: Callers of this function should ensure that the user_id and\n creator_id are valid.\n\n Args:\n user_id: str. The user ID of the new subscriber.\n creator_id: str. The user ID of the creator.\n\n Raises:\n Exception. The user ID of the new subscriber is same as the\n user ID of the creator.\n \"\"\"\n if user_id == creator_id:\n raise Exception('User %s is not allowed to self subscribe.' % user_id)\n subscribers_model_creator = user_models.UserSubscribersModel.get(\n creator_id, strict=False)\n subscriptions_model_user = user_models.UserSubscriptionsModel.get(\n user_id, strict=False)\n\n if not subscribers_model_creator:\n subscribers_model_creator = user_models.UserSubscribersModel(\n id=creator_id)\n\n if not subscriptions_model_user:\n subscriptions_model_user = user_models.UserSubscriptionsModel(\n id=user_id)\n\n if user_id not in subscribers_model_creator.subscriber_ids:\n subscribers_model_creator.subscriber_ids.append(user_id)\n subscriptions_model_user.creator_ids.append(creator_id)\n subscribers_model_creator.update_timestamps()\n subscribers_model_creator.put()\n subscriptions_model_user.update_timestamps()\n subscriptions_model_user.put()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_settings_for_user_by_projects(\n self,\n user: Recipient,\n type: NotificationSettingEnum | None = None,\n ) -> MutableMapping[\n int,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ]:\n \"\"\"\n Returns a mapping of project IDs to enabled notification settings for the given user\n with an optional type filter\n \"\"\"\n if not self.project_ids:\n raise Exception(\"Must specify project_ids\")\n\n result: MutableMapping[\n int,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ] = defaultdict(\n lambda: defaultdict(\n lambda: defaultdict(\n lambda: NotificationSettingsOptionEnum.DEFAULT\n ) # Use lambda to return the default enum value\n )\n )\n for project_id in self.project_ids:\n if not isinstance(project_id, int):\n raise Exception(\"project_ids must be a list of integers\")\n\n combined_settings = self.get_combined_settings(type=type, project_id=project_id)\n\n # take the settings for this user and apply it to the project\n result[project_id] = combined_settings[user]\n\n return result", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def test_try_except_else_finally(self):\n hit_except = False\n hit_else = False\n hit_finally = False\n\n try:\n raise Exception('nyaa!')\n except:\n hit_except = True\n else:\n hit_else = True\n finally:\n hit_finally = True\n\n self.assertTrue(hit_except)\n self.assertTrue(hit_finally)\n self.assertFalse(hit_else)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def apply_dynamic_factor(base_sample_rate: float, x: float) -> float:\n \"\"\"\n This function known as dynamic factor function is used during the rules generation in order to determine the factor\n for each rule based on the base_sample_rate of the project.\n\n The high-level idea is that we want to reduce the factor the bigger the base_sample_rate becomes, this is done\n because multiplication will exceed 1 very quickly in case we don't reduce the factor.\n \"\"\"\n if x == 0:\n raise Exception(\"A dynamic factor of 0 cannot be set.\")\n\n if base_sample_rate < 0.0 or base_sample_rate > 1.0:\n raise Exception(\n \"The dynamic factor function requires a sample rate in the interval [0.0, 1.0].\"\n )\n\n return float(x / x**base_sample_rate)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def test(self):\n \"\"\"\n Tests whether this constraint has been properly defined.\n \"\"\"\n counter = 0\n completed = False\n while not completed:\n if counter == 1:\n self.reset()\n advance = self.advance()\n if not self.does_advance(advance):\n raise Exception(\n \"Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.\"\n )\n\n stepped, completed, reset = self.update(advance)\n counter += 1\n\n if counter > 10000:\n raise Exception(\"update() does not fulfill the constraint.\")\n\n if self.remaining() != 0:\n raise Exception(\"Custom Constraint is not defined correctly.\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def parse_json(self, json_file):\n if json_file is None:\n return None\n try:\n data = json_file.read()\n try:\n tree = json.loads(str(data, \"utf-8\"))\n except Exception:\n tree = json.loads(data)\n except Exception:\n msg = \"Invalid format\"\n raise Exception(msg)\n\n return tree", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def __init__(self, tool_config):\n self.session = requests.Session()\n if tool_config.authentication_type == \"API\":\n self.api_token = tool_config.api_key\n self.org_token = tool_config.extras\n else:\n msg = f\"Cobalt.io Authentication type {tool_config.authentication_type} not supported\"\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def error(self, message):\n raise Exception(message)", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "@sensitive_variables(\"sauce\")\ndef sensitive_kwargs_function(sauce=None):\n # Do not just use plain strings for the variables' values in the code\n # so that the tests don't return false positives when the function's source\n # is displayed in the exception report.\n cooked_eggs = \"\".join([\"s\", \"c\", \"r\", \"a\", \"m\", \"b\", \"l\", \"e\", \"d\"]) # NOQA\n raise Exception", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def handle_present_proof_v2_0(self, message):\n state = message.get(\"state\")\n pres_ex_id = message[\"pres_ex_id\"]\n self.log(f\"Presentation: state = {state}, pres_ex_id = {pres_ex_id}\")\n\n print(f\"Presentation: state = {state}, pres_ex_id = {pres_ex_id}\")\n\n if state in [\"request-received\"]:\n # prover role\n log_status(\n \"#24 Query for credentials in the wallet that satisfy the proof request\"\n )\n if not message.get(\"by_format\"):\n # this should not happen, something hinky when running in IDE...\n self.log(f\"No 'by_format' in message: {message}\")\n else:\n pres_request_indy = (\n message[\"by_format\"].get(\"pres_request\", {}).get(\"indy\")\n )\n pres_request_dif = message[\"by_format\"].get(\"pres_request\", {}).get(\"dif\")\n request = {}\n\n if not pres_request_dif and not pres_request_indy:\n raise Exception(\"Invalid presentation request received\")\n\n if pres_request_indy:\n # include self-attested attributes (not included in credentials)\n creds_by_reft = {}\n revealed = {}\n self_attested = {}\n predicates = {}\n\n try:\n # select credentials to provide for the proof\n creds = await self.admin_GET(\n f\"/present-proof-2.0/records/{pres_ex_id}/credentials\"\n )\n # print(\">>> creds:\", creds)\n if creds:\n # select only indy credentials\n creds = [x for x in creds if \"cred_info\" in x]\n if \"timestamp\" in creds[0][\"cred_info\"][\"attrs\"]:\n sorted_creds = sorted(\n creds,\n key=lambda c: int(\n c[\"cred_info\"][\"attrs\"][\"timestamp\"]\n ),\n reverse=True,\n )\n else:\n sorted_creds = creds\n for row in sorted_creds:\n for referent in row[\"presentation_referents\"]:\n if referent not in creds_by_reft:\n creds_by_reft[referent] = row\n\n # submit the proof wit one unrevealed revealed attribute\n revealed_flag = False\n for referent in pres_request_indy[\"requested_attributes\"]:\n if referent in creds_by_reft:\n revealed[referent] = {\n \"cred_id\": creds_by_reft[referent][\"cred_info\"][\n \"referent\"\n ],\n \"revealed\": revealed_flag,\n }\n revealed_flag = True\n else:\n self_attested[referent] = \"my self-attested value\"\n\n for referent in pres_request_indy[\"requested_predicates\"]:\n if referent in creds_by_reft:\n predicates[referent] = {\n \"cred_id\": creds_by_reft[referent][\"cred_info\"][\n \"referent\"\n ]\n }\n\n log_status(\"#25 Generate the indy proof\")\n indy_request = {\n \"indy\": {\n \"requested_predicates\": predicates,\n \"requested_attributes\": revealed,\n \"self_attested_attributes\": self_attested,\n }\n }\n request.update(indy_request)\n except ClientError:\n pass\n\n if pres_request_dif:\n try:\n # select credentials to provide for the proof\n creds = await self.admin_GET(\n f\"/present-proof-2.0/records/{pres_ex_id}/credentials\"\n )\n\n if creds and 0 < len(creds):\n # select only dif credentials\n creds = [x for x in creds if \"issuanceDate\" in x]\n creds = sorted(\n creds,\n key=lambda c: c[\"issuanceDate\"],\n reverse=True,\n )\n records = creds\n else:\n records = []\n\n log_status(\"#25 Generate the dif proof\")\n dif_request = {\n \"dif\": {},\n }\n # specify the record id for each input_descriptor id:\n dif_request[\"dif\"][\"record_ids\"] = {}\n for input_descriptor in pres_request_dif[\n \"presentation_definition\"\n ][\"input_descriptors\"]:\n input_descriptor_schema_uri = []\n for element in input_descriptor[\"schema\"]:\n input_descriptor_schema_uri.append(element[\"uri\"])\n\n for record in records:\n if self.check_input_descriptor_record_id(\n input_descriptor_schema_uri, record\n ):\n record_id = record[\"record_id\"]\n dif_request[\"dif\"][\"record_ids\"][\n input_descriptor[\"id\"]\n ] = [\n record_id,\n ]\n break\n log_msg(\"presenting ld-presentation:\", dif_request)\n request.update(dif_request)\n\n # NOTE that the holder/prover can also/or specify constraints by including the whole proof request\n # and constraining the presented credentials by adding filters, for example:\n #\n # request = {\n # \"dif\": pres_request_dif,\n # }\n # request[\"dif\"][\"presentation_definition\"][\"input_descriptors\"][\"constraints\"][\"fields\"].append(\n # {\n # \"path\": [\n # \"$.id\"\n # ],\n # \"purpose\": \"Specify the id of the credential to present\",\n # \"filter\": {\n # \"const\": \"https://credential.example.com/residents/1234567890\"\n # }\n # }\n # )\n #\n # (NOTE the above assumes the credential contains an \"id\", which is an optional field)\n\n except ClientError:\n pass\n\n log_status(\"#26 Send the proof to X: \" + json.dumps(request))\n await self.admin_POST(\n f\"/present-proof-2.0/records/{pres_ex_id}/send-presentation\",\n request,\n )\n elif state == \"presentation-received\":\n # verifier role\n log_status(\"#27 Process the proof provided by X\")\n log_status(\"#28 Check if proof is valid\")\n proof = await self.admin_POST(\n f\"/present-proof-2.0/records/{pres_ex_id}/verify-presentation\"\n )\n self.log(\"Proof =\", proof[\"verified\"])\n self.last_proof_received = proof\n\n elif state == \"abandoned\":\n log_status(\"Presentation exchange abandoned\")\n self.log(\"Problem report message:\", message.get(\"error_msg\"))", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def get_queryset(self, raw_query=False):\n # Call the base implementation\n if not self.haystack:\n queryset = super().get_queryset()\n else:\n queryset = SearchQuerySet().models(self.model)\n\n # Optional tweak methods\n Mfields = None # noqa: N806\n MlimitQ = None # noqa: N806\n MsearchF = None # noqa: N806\n MsearchQ = None # noqa: N806\n if hasattr(self, \"__fields__\"):\n Mfields = self.__fields__ # noqa: N806\n if hasattr(self, \"__limitQ__\"):\n MlimitQ = self.__limitQ__ # noqa: N806\n if hasattr(self, \"__searchF__\"):\n MsearchF = self.__searchF__ # noqa: N806\n if hasattr(self, \"__searchQ__\"):\n MsearchQ = self.__searchQ__ # noqa: N806\n\n self._viewname = self.__module__\n\n # Link to our context and kwargs\n context = self.__context\n\n # Update kwargs if json key is present\n jsonquerytxt = self.request.GET.get(\n \"json\",\n self.request.POST.get(\"json\", None),\n )\n if jsonquerytxt is not None:\n # Decode json\n try:\n jsonquery = json.loads(jsonquerytxt)\n except json.JSONDecodeError:\n raise OSError(\n \"json argument in your GET/POST parameters is not a \"\n \"valid JSON string\",\n )\n\n # Set json context\n jsondata = self.set_context_json(jsonquery)\n\n # Get listid\n listid = jsondata.pop(\"listid\")\n # Get elementid\n elementid = jsondata.pop(\"elementid\")\n else:\n listid = None\n elementid = None\n jsondata = {}\n jsonquery = {}\n\n # Build info for GenModel methods\n MODELINF = MODELINFO( # noqa: N806\n self.model,\n self._appname,\n self._modelname,\n self._viewname,\n self.request,\n self.user,\n self.codenerix_request,\n self.codenerix_uuid,\n self.profile,\n jsonquery,\n Mfields,\n MlimitQ,\n MsearchF,\n MsearchQ,\n listid,\n elementid,\n self.__kwargs,\n )\n\n # Process the filter\n context[\"filters\"] = []\n context[\"filters_obj\"] = {}\n\n # Get field list\n fields = getattr(self, \"fields\", MODELINF.fields())\n\n # Save GET values\n context[\"get\"] = []\n context[\"getval\"] = {}\n for name in jsondata:\n struct = {}\n struct[\"name\"] = name\n if name == \"rowsperpage\":\n struct[\"value\"] = self.default_rows_per_page\n elif name == \"page\":\n struct[\"value\"] = 1\n elif name == \"pages_to_bring\":\n struct[\"value\"] = 1\n else:\n struct[\"value\"] = jsondata[name]\n context[\"get\"].append(struct)\n context[\"getval\"][name] = struct[\"value\"]\n\n # Filter on limits\n limits = MODELINF.limitQ()\n qobjects = None\n distinct = False\n for name in limits:\n if name == \"i_distinct\" or name == \"e_distinct\":\n distinct = True\n else:\n if qobjects:\n qobjects &= limits[name]\n else:\n qobjects = limits[name]\n\n if qobjects:\n queryset = queryset.filter(qobjects)\n\n if hasattr(self, \"annotations\"):\n if not self.haystack:\n # Prepare annotations\n if callable(self.annotations):\n anot = self.annotations(MODELINF)\n else:\n anot = self.annotations\n\n # Set annotations\n queryset = queryset.annotate(**anot)\n else:\n raise OSError(\"Haystack doesn't support annotate\")\n\n if distinct:\n queryset = queryset.distinct()\n\n # Filters on fields requested by the user request\n try:\n filters_get = jsondata.get(\"filters\", \"{}\")\n if isinstance(filters_get, dict):\n filters_by_struct = filters_get\n else:\n filters_by_struct = json.loads(str(filters_get))\n except Exception:\n filters_by_struct = []\n\n # Search filter button\n search_filter_button = jsondata.get(\"search_filter_button\", None)\n if search_filter_button is not None:\n self.search_filter_button = search_filter_button\n\n # Search text in all fields\n search = jsondata.get(\"search\", \"\").lower()\n # Remove extra spaces\n newlen = len(search)\n oldlen = 0\n while newlen != oldlen:\n oldlen = newlen\n search = search.replace(\" \", \" \")\n newlen = len(search)\n if len(search) > 0 and search[0] == \" \":\n search = search[1:]\n if len(search) > 0 and search[-1] == \" \":\n search = search[:-1]\n\n # Save in context\n context[\"search\"] = search\n datetimeQ = getattr(self, \"datetime_filter\", None) # noqa: N806\n if len(search) > 0:\n # Get ID\n tid = None\n if \"id:\" in search:\n tid = search.split(\":\")[1].split(\" \")[0]\n # Decide if it is what we expect\n try:\n tid = int(tid)\n except Exception:\n tid = None\n # Remove the token\n if tid:\n search = search.replace(\"id:%s\" % (tid), \"\")\n search = search.replace(\" \", \" \")\n\n # Get PK\n tpk = None\n if \"pk:\" in search:\n tpk = search.split(\":\")[1].split(\" \")[0]\n # Decide if it is what we expect\n try:\n tpk = int(tpk)\n except Exception:\n tpk = None\n # Remove the token\n if tpk:\n search = search.replace(\"pk:%s\" % (tpk), \"\")\n search = search.replace(\" \", \" \")\n\n # Spaces on front and behind\n search = search.strip()\n\n # Prepare searchs\n searchs = {}\n # Autofilter system\n if self.autofiltering:\n searchs.update(self.autoSearchQ(MODELINF, search))\n\n # Fields to search in from the MODELINF\n tmp_search = MODELINF.searchQ(search)\n if isinstance(tmp_search, dict):\n searchs.update(tmp_search)\n else:\n searchs[\"autoSearchQ\"] &= tmp_search\n qobjects = {}\n qobjectsCustom = {} # noqa: N806\n for name in searchs:\n # Extract the token\n qtoken = searchs[name]\n if qtoken == \"datetime\":\n if not datetimeQ:\n # If it is a datetime\n datetimeQ = name # noqa: N806\n continue\n elif (isinstance(qtoken, str)) or (isinstance(qtoken, list)):\n # Prepare query\n if isinstance(qtoken, tuple):\n (query, func) = qtoken\n else:\n\n def lambdax(x):\n return x\n\n func = lambdax\n query = qtoken\n\n # If it is a string\n if search:\n for word in search.split(\" \"):\n # If there is a word to process\n if len(word) > 0:\n # Build the key for the arguments and set the\n # word as a value for the Q search\n if word[0] == \"-\":\n # If negated request\n # key=\"-{}\".format(hashlib.md5(word[1:].encode()).hexdigest())\n qdict = {\n \"{}\".format(query): func(word[1:]),\n }\n qtokens_element = ~Q(**qdict)\n else:\n # If positive request\n # key=\"-{}\".format(hashlib.md5(word[1:].encode()).hexdigest())\n qdict = {\"{}\".format(query): func(word)}\n qtokens_element = Q(**qdict)\n\n # Safe the token\n if word in qobjects:\n qobjects[word].append(qtokens_element)\n else:\n qobjects[word] = [qtokens_element]\n else:\n if qobjectsCustom:\n qobjectsCustom |= searchs[name]\n else:\n qobjectsCustom = searchs[name] # noqa: N806\n\n # Build positive/negative\n qdata = None\n if search and qobjects:\n for word in search.split(\" \"):\n if word.split(\":\")[0] not in [\"id\", \"pk\"]:\n if word[0] == \"-\":\n negative = True\n else:\n negative = False\n qword = None\n for token in qobjects[word]:\n if qword:\n if negative:\n qword &= token\n else:\n qword |= token\n else:\n qword = token\n if qword:\n if qdata:\n qdata &= qword\n else:\n qdata = qword\n\n # Process ID/PK specific searches\n searchq_objects = Q()\n if tid:\n searchq_objects = searchq_objects & Q(id=tid)\n if tpk:\n searchq_objects = searchq_objects & Q(pk=tpk)\n # Add custom Q-objects\n if qobjectsCustom:\n searchq_objects = searchq_objects & qobjectsCustom\n # Add word by word search Q-objects\n if qdata:\n searchq_objects = searchq_objects & qdata\n queryset = queryset.filter(searchq_objects)\n\n # Prepare searchF\n listfilters = {}\n # Autofilter system\n if self.autofiltering:\n listfilters.update(self.autoSearchF(MODELINF))\n # List of filters from the MODELINF\n listfilters.update(MODELINF.searchF())\n\n # Process the search\n filters_struct = {}\n for key in filters_by_struct:\n # Get the value of the original filter\n value = filters_by_struct[key]\n # If there is something to filter, filter is not being\n # changed and filter is known by the class\n try:\n value = int(value)\n except ValueError:\n pass\n except TypeError:\n pass\n\n # ORIG if (key in listfilters) and ((value>0) or\n # (isinstance(value, list)):\n # V1 if (value and isinstance(value, int) and key in listfilters)\n # and ((value > 0) or (isinstance(value, list))):\n # V2 if (value and isinstance(value, int) and key in listfilters)\n # or ((value > 0) or (isinsance(value, list))):\n if value and key in listfilters:\n # Add the filter to the queryset\n rule = listfilters[key]\n # Get type\n typekind = rule[2]\n if isinstance(typekind, list):\n # Compatibility: set typekind and fv in the old fassion\n if isinstance(value, int):\n fv = typekind[value - 1][0]\n queryset = queryset.filter(rule[1](fv))\n typekind = \"select\"\n elif typekind == \"datetime\":\n # It has been already processed\n pass\n elif typekind == \"select\":\n # Get selected value from rule\n if isinstance(value, int):\n fv = rule[3][value - 1][0]\n queryset = queryset.filter(rule[1](fv))\n elif typekind in [\"multiselect\", \"multidynamicselect\"]:\n # Get selected values from rule\n if type(value) in (list, tuple) and len(value):\n qobjects = Q(rule[1](value[0]))\n for fvt in value[1:]:\n qobjects |= Q(rule[1](fvt))\n queryset = queryset.filter(qobjects)\n elif typekind in [\"daterange\", \"input\"]:\n # No arguments\n fv = value\n queryset = queryset.filter(rule[1](fv))\n elif typekind in [\n \"checkbox\",\n ]:\n fv = value\n queryset = queryset.filter(rule[1](fv))\n else:\n raise OSError(\n \"Wrong typekind '{}' for filter '{}'\".format(\n typekind,\n key,\n ),\n )\n # Save it in the struct as a valid filter\n filters_struct[key] = value\n\n # Rewrite filters_json updated\n filters_json = json.dumps(filters_struct, cls=DjangoJSONEncoder)\n\n # Build the clean get for filters\n get = context[\"get\"]\n filters_get = []\n for element in get:\n if element[\"name\"] not in [\"filters\"]:\n struct = {}\n struct[\"name\"] = element[\"name\"]\n struct[\"value\"] = element[\"value\"]\n filters_get.append(struct)\n\n # Add filter_json\n struct = {}\n struct[\"name\"] = \"filters\"\n struct[\"value\"] = filters_json\n filters_get.append(struct)\n context[\"filters_get\"] = filters_get\n\n # Get the list of filters allowed by this class\n filters = []\n for key in listfilters:\n typekind = listfilters[key][2]\n if isinstance(typekind, list) or isinstance(typekind, tuple):\n # Compatibility: set typekind and fv in the old fassion\n choice = [_(\"All\")]\n for value in typekind:\n choice.append(value[1])\n\n # Decide the choosen field\n if key in filters_struct.keys():\n value = int(filters_struct[key])\n else:\n value = 0\n typekind = \"select\"\n argument = choice\n elif typekind == \"select\":\n typevalue = listfilters[key][3]\n choice = [_(\"All\")]\n for value in typevalue:\n choice.append(value[1])\n\n # Decide the choosen field\n if key in filters_struct.keys():\n value = int(filters_struct[key])\n else:\n value = 0\n # Set choice as the command's argument\n argument = choice\n elif typekind in [\"multiselect\", \"multidynamicselect\"]:\n if typekind == \"multiselect\":\n typevalue = listfilters[key][3]\n choice = []\n for value in typevalue:\n choice.append({\"id\": value[0], \"label\": value[1]})\n else:\n choice = list(listfilters[key][3:])\n choice[1] = reverse_lazy(\n choice[1],\n kwargs={\"search\": \"a\"},\n )[:-1]\n\n # Decide the choosen field\n if key in filters_struct.keys():\n value = filters_struct[key]\n else:\n value = []\n\n # Set choice as the command's argument\n argument = choice\n elif typekind in [\"daterange\", \"input\"]:\n # Commands withouth arguments\n argument = None\n # Get the selected value\n if key in filters_struct.keys():\n value = filters_struct[key]\n else:\n value = None\n elif typekind in [\"checkbox\"]:\n # Commands withouth arguments\n argument = None\n # Get the selected value\n if key in filters_struct.keys():\n value = filters_struct[key]\n else:\n value = None\n else:\n raise OSError(\n \"Wrong typekind '{}' for filter '{}'\".format(\n typekind,\n key,\n ),\n )\n\n # Build filtertuple\n filtertuple = (key, listfilters[key][0], typekind, argument, value)\n # Save this filter in the corresponding list\n filters.append(filtertuple)\n\n # Save all filters\n context[\"filters\"] = filters\n\n # Datetime Q\n context[\"datetimeQ\"] = datetimeQ\n if datetimeQ:\n # Inicialization\n f = {}\n f[\"year\"] = (1900, 2100, False)\n f[\"month\"] = (1, 12, False)\n f[\"day\"] = (1, 31, False)\n f[\"hour\"] = (0, 23, False)\n f[\"minute\"] = (0, 59, False)\n f[\"second\"] = (0, 59, False)\n date_elements = [\n None,\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n ]\n # Get configuration of dates and set limits to the queryset\n for element in date_elements[1:]:\n value = jsondata.get(element, None)\n if value:\n f[element] = (int(value), int(value), True)\n if f[\"year\"][2] and f[\"month\"][2] and not f[\"day\"][2]:\n (g, lastday) = calendar.monthrange(f[\"year\"][1], f[\"month\"][1])\n f[\"day\"] = (f[\"day\"][0], lastday, f[\"day\"][2])\n # Limits\n date_min = datetime.datetime(\n f[\"year\"][0],\n f[\"month\"][0],\n f[\"day\"][0],\n f[\"hour\"][0],\n f[\"minute\"][0],\n f[\"second\"][0],\n )\n date_max = datetime.datetime(\n f[\"year\"][1],\n f[\"month\"][1],\n f[\"day\"][1],\n f[\"hour\"][1],\n f[\"minute\"][1],\n f[\"second\"][1],\n )\n qarg1 = {\"{}__gte\".format(datetimeQ): date_min}\n qarg2 = {\"{}__lte\".format(datetimeQ): date_max}\n qarg3 = {datetimeQ: None}\n queryset = queryset.filter((Q(**qarg1) & Q(**qarg2)) | Q(**qarg3))\n\n # Find actual deepness\n deepness_index = 0\n for element in date_elements[1:]:\n if f[element][2]:\n deepness_index += 1\n else:\n break\n\n # Get results from dates to set the new order\n exclusion = {}\n exclusion[datetimeQ] = None\n date_results = queryset.exclude(**exclusion).values_list(\n datetimeQ,\n flat=True,\n )\n # Remove empty results (usefull when the date is allowed to\n # be empty)\n if f[\"day\"][0] != f[\"day\"][1]:\n if f[\"month\"][0] == f[\"month\"][1]:\n date_results = date_results.datetimes(datetimeQ, \"day\")\n elif f[\"year\"][0] == f[\"year\"][1]:\n date_results = date_results.datetimes(datetimeQ, \"month\")\n else:\n date_results = date_results.datetimes(datetimeQ, \"year\")\n\n get = context[\"get\"]\n context[\"datefilter\"] = {}\n # Save the deepness\n if deepness_index + 1 == len(date_elements):\n context[\"datefilter\"][\"deepness\"] = None\n else:\n context[\"datefilter\"][\"deepness\"] = date_elements[\n deepness_index + 1\n ]\n context[\"datefilter\"][\"deepnessback\"] = []\n context[\"datefilter\"][\"deepnessinit\"] = []\n for element in get:\n if not element[\"name\"] in date_elements:\n struct = {}\n struct[\"name\"] = element[\"name\"]\n struct[\"value\"] = element[\"value\"]\n context[\"datefilter\"][\"deepnessinit\"].append(struct)\n context[\"datefilter\"][\"deepnessback\"].append(struct)\n elif (\n element[\"name\"] != date_elements[deepness_index]\n and f[element[\"name\"]][2]\n ):\n struct = {}\n struct[\"name\"] = element[\"name\"]\n struct[\"value\"] = element[\"value\"]\n context[\"datefilter\"][\"deepnessback\"].append(struct)\n # Build the list of elements\n context[\"datefilter\"][\"data\"] = []\n for element in date_results:\n # Save the data\n context[\"datefilter\"][\"data\"].append(\n element.timetuple()[deepness_index],\n )\n context[\"datefilter\"][\"data\"] = list(\n set(context[\"datefilter\"][\"data\"]),\n )\n context[\"datefilter\"][\"data\"].sort()\n\n # Prepare the rightnow result\n if self.json_worker:\n rightnow = {}\n for key in [\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n ]:\n rightnow[key] = (f[key][2] and f[key][0]) or None\n else:\n if f[\"month\"][2]:\n month = monthname(f[\"month\"][0])\n else:\n month = \"__\"\n if f[\"hour\"][2]:\n rightnow = format_lazy(\n grv(f, \"day\"),\n \"/\",\n month,\n \"/\",\n grv(f, \"year\"),\n \" \",\n grv(f, \"hour\"),\n \":\",\n grv(f, \"minute\"),\n \":\",\n grv(f, \"second\"),\n )\n else:\n rightnow = format_lazy(\n grv(f, \"day\"),\n \"/\",\n month,\n \"/\",\n grv(f, \"year\"),\n )\n context[\"datefilter\"][\"rightnow\"] = rightnow\n else:\n context[\"datefilter\"] = None\n\n # Distinct\n # queryset=queryset.distinct()\n\n # Ordering field autofill\n try:\n order_get = jsondata.get(\"ordering\", [])\n if isinstance(order_get, list):\n order_by_struct = order_get\n else:\n order_by_struct = json.loads(str(order_get))\n except Exception:\n order_by_struct = []\n order_by = []\n position = {}\n counter = 1\n\n # Build the columns structure and the fields list\n context[\"columns\"] = []\n self.__fields = []\n for value in fields:\n self.__fields.append(value[0])\n\n # Auto build rules\n self.__autorules = self.autorules()\n\n for order in order_by_struct:\n name = list(order.keys())[0]\n lbl = None\n # use __autofields for ordering by alias\n for field in self.__autorules:\n if \"{}:\".format(name) in field:\n name = field.split(\":\")[0]\n lbl = field.split(\":\")[1]\n break\n direction = order[name]\n\n if (\n lbl\n and not lbl.startswith(\"get_\")\n and not lbl.endswith(\"_display\")\n ):\n name = lbl\n\n if direction == \"asc\":\n order_by.append(\"%s\" % (remove_getdisplay(name)))\n elif direction == \"desc\":\n order_by.append(\"-%s\" % (remove_getdisplay(name)))\n position[name] = counter\n counter += 1\n\n if order_by:\n queryset = queryset.order_by(*order_by)\n else:\n if hasattr(self, \"default_ordering\"):\n if isinstance(self.default_ordering, list):\n queryset = queryset.order_by(*self.default_ordering)\n else:\n queryset = queryset.order_by(self.default_ordering)\n else:\n queryset = queryset.order_by(\"pk\")\n\n # Ordering field autofill\n sort = {}\n for value in fields:\n # Get values\n if value[0]:\n name = value[0].split(\":\")[0]\n order_key = name\n type_field = self.get_type_field(value[0].split(\":\")[-1])\n else:\n name = value[0]\n # not usable fields, example: fields.append((None,\n # _('Selector'))) in airportslist\n hash_key = hashlib.md5(\n value[1].encode(),\n usedforsecurity=False,\n ).hexdigest()\n order_key = \"#{}\".format(hash_key)\n type_field = None\n\n publicname = value[1]\n if len(value) > 2:\n size = value[2]\n else:\n size = None\n if len(value) > 3:\n align = value[3]\n else:\n align = None\n # filter column\n if len(value) > 4:\n filter_column = value[4]\n else:\n filter_column = None\n\n # Process ordering\n ordering = []\n found = False\n for order in order_by_struct:\n subname = list(order.keys())[0]\n direction = order[subname]\n if order_key == subname:\n if direction == \"desc\":\n direction = \"\"\n sort_class = \"headerSortUp\"\n elif direction == \"asc\":\n direction = \"desc\"\n sort_class = \"headerSortDown\"\n else:\n sort_class = \"\"\n direction = \"asc\"\n found = True\n if direction == \"asc\" or direction == \"desc\":\n ordering.append({subname: direction})\n\n if not found:\n ordering.append({order_key: \"asc\"})\n sort_class = \"\"\n # Save the ordering method\n sort[order_key] = {}\n sort[order_key][\"id\"] = name\n sort[order_key][\"name\"] = publicname\n sort[order_key][\"align\"] = align\n sort[order_key][\"type\"] = type_field\n\n if filter_column:\n sort[order_key][\"filter\"] = filter_column\n\n if jsonquery is None:\n sort[order_key][\"size\"] = size\n sort[order_key][\"class\"] = sort_class\n if order_key and order_key[0] != \"*\":\n sort[order_key][\"ordering\"] = json.dumps(\n ordering,\n cls=DjangoJSONEncoder,\n ).replace(\n '\"',\n '\\\\\"',\n )\n if order_key in position:\n sort[order_key][\"position\"] = position[order_key]\n\n # Save ordering in the context\n if jsonquery is not None:\n context[\"ordering\"] = order_by_struct\n\n # Build the columns structure and the fields list\n context[\"columns\"] = []\n for value in fields:\n field = value[0]\n if field:\n context[\"columns\"].append(sort[field.split(\":\")[0]])\n else:\n hash_key = hashlib.md5(\n value[1].encode(),\n usedforsecurity=False,\n ).hexdigest()\n field = \"#{}\".format(hash_key)\n # selector\n context[\"columns\"].append(sort[field])\n\n # Auto build rules\n # self.__autorules = self.autorules()\n\n # Columns\n self.__columns = [\"pk\"]\n # self.__columns = ['id']\n self.__foreignkeys = []\n for column in self.model._meta.fields:\n self.__columns.append(column.name)\n if column.is_relation:\n self.__foreignkeys.append(column.name)\n\n # Localfields\n self.__related_objects = []\n for f in self.model._meta.related_objects:\n self.__related_objects.append(f.name)\n\n # Model properties\n model_properties = self.__columns + self.__related_objects\n\n # === Queryset optimization ===\n # Get autorules ordered\n autorules_keys = sorted(self.__autorules.keys())\n #\n query_renamed = {}\n query_optimizer = []\n query_verifier = []\n query_select_related = []\n fields_related_model = []\n\n for rule in autorules_keys:\n found = False\n # name rule origin\n rule_org = rule\n # If rule is an alias\n rulesp = rule.split(\":\")\n if len(rulesp) == 2:\n (alias, rule) = rulesp\n else:\n alias = rule\n\n # If rule has a foreign key path (check first level attributes\n # only, nfrule = no foreign rule)\n nfrule = rule.split(\"__\")\n do_select_related = False\n model = self.model\n if len(nfrule) > 1:\n ruletmp = []\n field_related_model = []\n for n in nfrule:\n if model:\n for fi in model._meta.fields:\n if fi.name == n:\n found = True\n ruletmp.append(n)\n if fi.is_relation:\n model = fi.related_model\n field_related_model.append(fi.name)\n else:\n do_select_related = True\n model = None\n break\n if not found or model is None:\n break\n if field_related_model:\n fields_related_model.append(\"__\".join(field_related_model))\n\n if ruletmp != nfrule:\n do_select_related = False\n elif (\n nfrule[0] in [x.name for x in self.model._meta.fields]\n or nfrule[0] == \"pk\"\n ):\n found = True\n for fi in model._meta.fields:\n if fi.name == nfrule[0] and fi.is_relation:\n fields_related_model.append(nfrule[0])\n\n if not self.haystack and (\n do_select_related or rule in self.__foreignkeys\n ):\n # Compatibility with Django 1.10\n if \"__\" in rule:\n query_select_related.append(\n \"__\".join(rule.split(\"__\")[0:-1]),\n )\n else:\n query_select_related.append(rule)\n\n nfrule = nfrule[0]\n\n if nfrule in self.__columns:\n ############################\n # dejo comentada la restriccion, si se deja y hay una FK\n # \"nunca\" usaria .extra ni .value\n # no la elimino del todo por si hubiera algun fallo mas\n # adelante,\n # y se tuviera que parametrizarse de algun otro modo\n ############################\n\n # if nfrule not in self.__foreignkeys:\n if rule not in fields_related_model:\n # Save verifier name\n query_verifier.append(rule_org)\n\n # Save renamed field\n if alias != rule:\n query_renamed[alias] = F(rule)\n query_optimizer.append(alias)\n else:\n # Save final name\n query_optimizer.append(rule)\n\n if hasattr(self, \"annotations\"):\n # Prepare annotations\n if callable(self.annotations):\n anot = self.annotations(MODELINF)\n else:\n anot = self.annotations\n\n # Process annotations\n for xnfrule in anot.keys():\n found = True\n if xnfrule not in query_verifier:\n query_verifier.append(xnfrule)\n query_optimizer.append(xnfrule)\n\n if not found:\n query_renamed = {}\n query_optimizer = []\n query_verifier = []\n query_select_related = []\n break\n\n for rename in query_renamed.keys():\n if rename in model_properties:\n if rename in self.__foreignkeys:\n msg = (\n \"Invalid alias. The alias '{}' is a foreign key \"\n \" from model '{}' inside app '{}'\"\n )\n elif rename in self.__columns:\n msg = (\n \"Invalid alias. The alias '{}' is a columns \"\n \"from model '{}' inside app '{}'\"\n )\n elif rename in self.__related_objects:\n msg = (\n \"Invalid alias. The alias '{}' is a related \"\n \"object from model '{}' inside app '{}'\"\n )\n raise Exception(\n msg.format(rename, self._modelname, self._appname),\n )\n\n if found and query_select_related:\n queryset = queryset.select_related(*query_select_related)\n\n # If we got the query_optimizer to optimize everything, use it\n # use_extra = False\n query_verifier.sort()\n autorules_keys.sort()\n if found and query_verifier == autorules_keys:\n # use_extra = True\n if query_renamed:\n # queryset=queryset.extra(select=query_renamed).values(*query_optimizer)\n queryset = queryset.annotate(**query_renamed).values(\n *query_optimizer,\n )\n else:\n queryset = queryset.values(*query_optimizer)\n\n # Custom queryset\n if hasattr(self, \"custom_queryset\"):\n queryset = self.custom_queryset(queryset, MODELINF)\n\n # Internal Codenerix DEBUG for Querysets\n \"\"\"\n raise Exception(\"FOUND: {} -- __foreignkeys: {} -- __columns: {} -- autorules_keys: {} -- \\\n query_select_related: {} -- query_renamed: {} -- query_optimizer: {} | use_extra: {}| -- \\\n query: {} -- meta.fields: {} -- fields_related_model: {} -- query_verifier: {}\\\n -- ??? {} == {}\".format(\n found,\n self.__foreignkeys, self.__columns, autorules_keys,\n query_select_related, query_renamed, query_optimizer,use_extra,\n queryset.query,\n [x.name for x in self.model._meta.fields],\n fields_related_model, query_verifier,\n query_verifier.sort(),autorules_keys.sort()\n ))\n #\"\"\" # noqa: E501\n\n # Check if the user requested to return a raw queryset\n if raw_query:\n return queryset\n else:\n # Check the total count of registers + rows per page\n total_rows_per_page = jsondata.get(\n \"rowsperpage\",\n self.default_rows_per_page,\n )\n pages_to_bring = jsondata.get(\"pages_to_bring\", 1)\n if self.export:\n # Bring all pages overriding any other action\n total_rows_per_page = queryset.count()\n elif total_rows_per_page is None:\n # Bring default pages\n total_rows_per_page = self.default_rows_per_page\n elif total_rows_per_page == \"All\":\n # Bring all pages\n total_rows_per_page = queryset.count()\n paginator = Paginator(queryset, total_rows_per_page)\n total_registers = paginator.count\n\n # Rows per page\n if total_rows_per_page:\n try:\n total_rows_per_page = int(total_rows_per_page)\n except Exception:\n total_rows_per_page = \"All\"\n else:\n total_rows_per_page = self.default_rows_per_page\n if total_rows_per_page == \"All\":\n page_number = 1\n total_rows_per_page = total_registers\n total_rows_per_page_out = _(\"All\")\n total_pages = 1\n else:\n total_rows_per_page = int(\n total_rows_per_page,\n ) # By default 10 rows per page\n total_rows_per_page_out = total_rows_per_page\n total_pages = int(total_registers / total_rows_per_page)\n if total_registers % total_rows_per_page:\n total_pages += 1\n page_number = jsondata.get(\n \"page\",\n 1,\n ) # If no page specified use first page\n if page_number == \"last\":\n page_number = total_pages\n else:\n try:\n page_number = int(page_number)\n except Exception:\n page_number = 1\n if page_number < 1:\n page_number = 1\n if page_number > total_pages:\n page_number = total_pages\n\n # Build the list of page counters allowed\n choice = {}\n c = self.default_rows_per_page\n chk = 1\n while total_registers >= c:\n choice[c] = c\n if chk == 1:\n # From 5 to 10\n c = c * 2\n # Next level\n chk = 2\n elif chk == 2:\n # From 10 to 25 (10*2+10/2)\n c = c * 2 + int(c / 2)\n # Next level\n chk = 3\n elif chk == 3:\n # From 25 to 50\n c *= 2\n chk = 1\n # Don't give a too long choice\n if c > 2000:\n break\n\n # Add all choice in any case\n if settings.ALL_PAGESALLOWED:\n choice[\"All\"] = _(\"All\")\n\n # Save the pagination in the structure\n context[\"rowsperpageallowed\"] = choice\n context[\"rowsperpage\"] = total_rows_per_page_out\n context[\"pages_to_bring\"] = pages_to_bring\n context[\"pagenumber\"] = page_number\n\n # Get the full number of registers and save it to context\n context[\"total_registers\"] = total_registers\n if total_rows_per_page == \"All\":\n # Remove total_rows_per_page if is all\n total_rows_per_page = None\n context[\"page_before\"] = None\n context[\"page_after\"] = None\n context[\"start_register\"] = 1\n context[\"showing_registers\"] = total_registers\n else:\n # Page before\n if page_number <= 1:\n context[\"page_before\"] = None\n else:\n context[\"page_before\"] = page_number - 1\n # Page after\n if page_number >= total_pages:\n context[\"page_after\"] = None\n else:\n context[\"page_after\"] = page_number + 1\n # Starting on register number\n context[\"start_register\"] = (\n page_number - 1\n ) * total_rows_per_page + 1\n context[\"showing_registers\"] = total_rows_per_page\n\n # Calculate end\n context[\"end_register\"] = min(\n context[\"start_register\"] + context[\"showing_registers\"] - 1,\n total_registers,\n )\n\n # Add pagination\n regs = []\n if paginator.count:\n desired_page_number = page_number\n try:\n range_pages_to_bring = xrange(pages_to_bring)\n except NameError:\n range_pages_to_bring = range(pages_to_bring)\n for p in range_pages_to_bring:\n try:\n regs += paginator.page(desired_page_number)\n desired_page_number += 1\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n regs += paginator.page(1)\n desired_page_number = 2\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver\n # last page of results.\n if pages_to_bring == 1:\n regs += paginator.page(paginator.num_pages)\n # Leave bucle\n break\n\n # Fill pages\n if total_registers:\n context[\"pages\"] = pages(paginator, page_number)\n try:\n range_fill = xrange(pages_to_bring - 1)\n except NameError:\n range_fill = range(pages_to_bring - 1)\n for p in range_fill:\n page_number += 1\n context[\"pages\"] += pages(paginator, page_number)\n else:\n context[\"pages\"] = []\n\n # Return queryset\n return regs", "smellKey": "S112", "smellId": null, "repo": "codenerix_django-codenerix", "language": "python"} {"function": "def add_user_role(user_id: str, role: str) -> None:\n \"\"\"Updates the roles of the user with given user_id.\n\n Args:\n user_id: str. The unique ID of the user whose role is to be updated.\n role: str. The role to be assigned to user with given id.\n\n Raises:\n Exception. The given role does not exist.\n \"\"\"\n user_settings = get_user_settings(user_id, strict=True)\n if feconf.ROLE_ID_MOBILE_LEARNER in user_settings.roles:\n raise Exception('The role of a Mobile Learner cannot be changed.')\n if role in feconf.ALLOWED_DEFAULT_USER_ROLES_ON_REGISTRATION:\n raise Exception('Adding a %s role is not allowed.' % role)\n if role in user_settings.roles:\n raise Exception('The user already has this role.')\n user_settings.roles.append(role)\n role_services.log_role_query(\n user_id, feconf.ROLE_ACTION_ADD, role=role,\n username=user_settings.username)\n\n save_user_settings(user_settings)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def send_email_to_new_cd_user(\n recipient_id: str,\n category: str,\n language_code: Optional[str] = None\n) -> None:\n \"\"\"Sends an email to user who is assigned rights to either\n review or submit contributions.\n\n Args:\n recipient_id: str. The ID of the user.\n category: str. The category in which user can review or submit\n contributions.\n language_code: None|str. The language code for a language if\n the category is 'translation' else None.\n\n Raises:\n Exception. The contribution category is not valid.\n Exception. The language_code cannot be None if the\n category is 'translation'.\n \"\"\"\n if category not in NEW_CD_USER_EMAIL_DATA:\n raise Exception('Invalid category: %s' % category)\n\n category_data = NEW_CD_USER_EMAIL_DATA[category]\n email_subject = 'You have been invited to %s Oppia %s' % (\n category_data['task'],\n category_data['category'])\n\n if category in [\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION,\n ]:\n if language_code is None:\n raise Exception(\n 'The language_code cannot be None if the review category is'\n ' \\'translation\\''\n )\n language_description = utils.get_supported_audio_language_description(\n language_code).capitalize()\n category_description = (\n category_data['description_template'] %\n language_description)\n rights_message = (\n category_data['rights_message_template'] %\n (language_description))\n else:\n category_description = (\n category_data['description'])\n rights_message = (\n category_data['rights_message'])\n\n server_can_send_emails = (\n platform_parameter_services.get_platform_parameter_value(\n platform_parameter_list.ParamName.SERVER_CAN_SEND_EMAILS.value\n )\n )\n if not server_can_send_emails:\n logging.error('This app cannot send emails to users.')\n return\n\n email_body_template = '%s %s %s %s'\n recipient_username = user_services.get_username(recipient_id)\n if category in [\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_TRANSLATION,\n constants.CD_USER_RIGHTS_CATEGORY_REVIEW_QUESTION\n ]:\n to_review = category_data['to_review']\n email_body_template = (\n 'Hi %s,<br><br>'\n 'This is to let you know that the Oppia team has added you as a '\n 'reviewer for %s. This allows you to %s.<br><br>'\n 'You can check the %s waiting for review in the '\n '<a href=\"https://www.oppia.org/contributor-dashboard\">'\n 'Contributor Dashboard</a>.<br><br>'\n 'Thanks, and happy contributing!<br><br>'\n 'Best wishes,<br>'\n 'The Oppia Community')\n email_body = email_body_template % (\n recipient_username, category_description,\n rights_message, to_review)\n\n elif category in [\n constants.CD_USER_RIGHTS_CATEGORY_SUBMIT_QUESTION\n ]:\n email_body_template = (\n 'Hi %s,<br><br>'\n 'This is to let you know that the Oppia team has added you as a '\n 'contributor to %s for use in lessons.<br><br>'\n 'You can now start to submit %s in the '\n '<a href=\"https://www.oppia.org/contributor-dashboard\">'\n 'Contributor Dashboard</a>.<br><br>'\n 'Thanks, and happy contributing!<br><br>'\n 'Best wishes,<br>'\n 'The Oppia Community')\n email_body = email_body_template % (\n recipient_username, rights_message,\n category_description)\n\n can_user_receive_email = user_services.get_email_preferences(\n recipient_id).can_receive_email_updates\n\n # Send email only if recipient wants to receive.\n if can_user_receive_email:\n noreply_email_address = (\n platform_parameter_services.get_platform_parameter_value(\n platform_parameter_list.ParamName.NOREPLY_EMAIL_ADDRESS.value))\n assert isinstance(noreply_email_address, str)\n _send_email(\n recipient_id, feconf.SYSTEM_COMMITTER_ID,\n feconf.EMAIL_INTENT_ONBOARD_CD_USER, email_subject, email_body,\n noreply_email_address)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_done_callback_raises(self):\n with support.captured_stderr() as stderr:\n raising_was_called = False\n fn_was_called = False\n\n def raising_fn(callback_future):\n nonlocal raising_was_called\n raising_was_called = True\n raise Exception('doh!')\n\n def fn(callback_future):\n nonlocal fn_was_called\n fn_was_called = True\n\n f = Future()\n f.add_done_callback(raising_fn)\n f.add_done_callback(fn)\n f.set_result(5)\n self.assertTrue(raising_was_called)\n self.assertTrue(fn_was_called)\n self.assertIn('Exception: doh!', stderr.getvalue())", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_object_role(self, role, by_name=False):\n \"\"\"Lookup and return a related object role by its role field or name.\n\n Args:\n ----\n role (str): The role's `role_field` or name\n by_name (bool): Whether to retrieve the role by its name field (default: False)\n\n Examples:\n --------\n >>> # get the description of the Use role for an inventory\n >>> inventory = v2.inventory.create()\n >>> use_role_1 = inventory.get_object_role('use_role')\n >>> use_role_2 = inventory.get_object_role('use', True)\n >>> use_role_1.description\n u'Can use the inventory in a job template'\n >>> use_role_1.json == use_role_2.json\n True\n\n \"\"\"\n if by_name:\n for obj_role in self.related.object_roles.get().results:\n if obj_role.name.lower() == role.lower():\n return obj_role\n\n raise Exception(\"Role '{0}' not found for {1.endpoint}\".format(role, self))\n\n object_roles = self.get_related('object_roles', role_field=role)\n if not object_roles.count == 1:\n raise Exception(\"No role with role_field '{0}' found.\".format(role))\n return object_roles.results[0]", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def __init__(self, cc: int = None, kernel_cc: int = None, operation_kind = cutlass.OperationKind.Gemm):\n \"\"\"\n :param cc: compute capability of device for which kernels should be compiled. For example, if running on H100, this should be set to 90\n :type cc: int\n :param kernel_cc: compute capability of kernels to generate. For example, if running on SM90, but desiring to use a CUTLASS 2.x-style Ampere kernel, this should be set to 80\n :type kernel_cc: int\n \"\"\"\n self.operation_kind = operation_kind\n self.cc = cc if cc is not None else device_cc()\n self.specified_kernel_cc = kernel_cc is not None\n self.current_cc = kernel_cc if kernel_cc is not None else self._find_closest_cc(self.cc)\n self.tile_description = None\n\n self.options = option_registry.options_for_cc(self.current_cc, operation_kind)\n\n if self.options is None:\n raise Exception(f\"Invalid or unsupported compute capability: {self.current_cc}\")\n \n # Default activation function: identity\n self._activation = epilogue.identity", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def main(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Runs the script to setup GAE.\"\"\"\n unused_parsed_args = _PARSER.parse_args(args=args)\n\n sys.path.append('.')\n sys.path.append(common.GOOGLE_APP_ENGINE_SDK_HOME)\n\n # Delete old *.pyc files.\n for directory, _, files in os.walk('.'):\n for file_name in files:\n if file_name.endswith('.pyc'):\n filepath = os.path.join(directory, file_name)\n os.remove(filepath)\n\n print(\n 'Checking whether google-cloud-sdk is installed in %s'\n % common.GOOGLE_CLOUD_SDK_HOME)\n if not os.path.exists(common.GOOGLE_CLOUD_SDK_HOME):\n print('Downloading Google Cloud SDK (this may take a little while)...')\n os.makedirs(common.GOOGLE_CLOUD_SDK_HOME)\n try:\n # If the google cloud version is updated here, the corresponding\n # lines (GAE_DIR and GCLOUD_PATH) in assets/release_constants.json\n # should also be updated.\n common.url_retrieve(\n 'https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/'\n 'google-cloud-sdk-364.0.0-linux-x86_64.tar.gz',\n 'gcloud-sdk.tar.gz')\n except Exception as e:\n print('Error downloading Google Cloud SDK. Exiting.')\n raise Exception('Error downloading Google Cloud SDK.') from e\n print('Download complete. Installing Google Cloud SDK...')\n tar = tarfile.open(name='gcloud-sdk.tar.gz')\n tar.extractall(\n path=os.path.join(\n common.OPPIA_TOOLS_DIR, 'google-cloud-sdk-364.0.0/'))\n tar.close()\n\n os.remove('gcloud-sdk.tar.gz')\n\n # This command installs specific google cloud components for the google\n # cloud sdk to prevent the need for developers to install it themselves when\n # the app engine development server starts up. The --quiet parameter\n # specifically tells the gcloud program to autofill all prompts with default\n # values. In this case, that means accepting all installations of gcloud\n # packages.\n subprocess.run(\n [\n common.GCLOUD_PATH, 'components', 'install', 'beta',\n 'cloud-datastore-emulator', 'app-engine-python',\n 'app-engine-python-extras', '--quiet',\n ],\n check=True,\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_users_settings(\n user_ids: Sequence[Optional[str]],\n strict: bool = False,\n include_marked_deleted: bool = False\n) -> Sequence[Optional[user_domain.UserSettings]]:\n \"\"\"Gets domain objects representing the settings for the given user_ids.\n\n Args:\n user_ids: list(str). The list of user_ids to get UserSettings\n domain objects for.\n strict: bool. Whether to fail noisily if one or more user IDs don't\n exist in the datastore. Defaults to False.\n include_marked_deleted: bool. Whether to included users that are being\n deleted. This should be used only for retrieving the usernames.\n\n Returns:\n list(UserSettings|None). The UserSettings domain objects corresponding\n to the given user ids. If the given user_id does not exist, the\n corresponding entry in the returned list is None.\n\n Raises:\n Exception. When strict mode is enabled and some user is not found.\n \"\"\"\n user_settings_models = user_models.UserSettingsModel.get_multi(\n user_ids, include_deleted=include_marked_deleted)\n\n if strict:\n for user_id, user_settings_model in zip(user_ids, user_settings_models):\n if user_settings_model is None:\n raise Exception('User with ID \\'%s\\' not found.' % user_id)\n result: List[Optional[user_domain.UserSettings]] = []\n system_email_address = (\n platform_parameter_services.get_platform_parameter_value(\n platform_parameter_list.ParamName.SYSTEM_EMAIL_ADDRESS.value))\n assert isinstance(system_email_address, str)\n for i, model in enumerate(user_settings_models):\n if user_ids[i] == feconf.SYSTEM_COMMITTER_ID:\n result.append(user_domain.UserSettings(\n user_id=feconf.SYSTEM_COMMITTER_ID,\n email=system_email_address,\n roles=[\n feconf.ROLE_ID_FULL_USER,\n feconf.ROLE_ID_CURRICULUM_ADMIN,\n feconf.ROLE_ID_MODERATOR,\n feconf.ROLE_ID_VOICEOVER_ADMIN\n ],\n banned=False,\n username='admin',\n has_viewed_lesson_info_modal_once=False,\n last_agreed_to_terms=datetime.datetime.utcnow()\n ))\n else:\n if model is not None and model.deleted:\n model.username = USERNAME_FOR_USER_BEING_DELETED\n result.append(\n _get_user_settings_from_model(model)\n if model is not None else None\n )\n return result", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "async def generate_league_playoff(majors, area, bosses):\n if majors not in ['FullTraditional', 'FullRandom', 'Major', 'Chozo']:\n raise Exception(\"Invalid major setting. Must be FullTraditional, FullRandom, Major, or Chozo.\")\n\n if area not in ['Off', 'Light', 'Full']:\n raise Exception(\"Invalid area setting. Must be Off, Light, or Full.\")\n\n if bosses not in ['Off', 'On']:\n raise Exception(\"Invalid bosses setting. Must be Off, or On.\")\n\n settings = {\n \"majorsSplit\": \"Full\" if majors in ['FullTraditional', 'FullRandom'] else majors,\n\n # these are both set at same time\n \"areaRandomization\": \"off\" if area == \"Off\" else \"on\",\n \"areaLayout\": \"off\" if area == \"Off\" else \"on\",\n\n # requires area rando on\n \"lightAreaRandomization\": \"on\" if area == \"Light\" else \"off\",\n\n # boss rando\n \"bossRandomization\": \"off\" if bosses == \"Off\" else \"on\",\n }\n if majors == \"FullRandom\":\n settings['startLocation'] = 'random'\n settings['startLocationMultiSelect'] = [\n 'Gauntlet Top',\n 'Green Brinstar Elevator',\n 'Big Pink,Etecoons Supers',\n 'Wrecked Ship Main',\n 'Firefleas Top',\n 'Business Center',\n 'Bubble Mountain',\n 'Mama Turtle'\n ]\n\n seed = await SuperMetroidVariaDiscord.create(\n settings_preset=\"Season_Races\",\n skills_preset=\"Season_Races\",\n settings_dict=settings,\n race=True\n )\n return seed", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "def pytest_configure(config):\n \"\"\"\n Generate frontend assets before running any acceptance tests\n\n TODO: There is a bug if you run `py.test` with `-f` -- the built\n assets will trigger another `py.test` run.\n \"\"\"\n\n # Do not build in CI because tests are run w/ `make test-acceptance` which builds assets\n # Can also skip with the env var `SKIP_ACCEPTANCE_UI_BUILD`\n # `CI` is a default env var in GHA (https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables)\n if os.environ.get(\"CI\") or os.environ.get(\"SKIP_ACCEPTANCE_UI_BUILD\"):\n return\n\n try:\n with open(\"./.webpack.meta\") as f:\n data = json.load(f)\n\n # If built within last hour, do not build again\n last_built = int(time.time()) - data[\"built\"]\n\n if last_built <= 3600:\n print( # noqa: S002\n f\"\"\"\n###################\n#\n# Frontend assets last built {last_built} seconds ago, skipping rebuilds for another {3600 - last_built} seconds.\n# Delete the file: `.webpack.meta` to rebuild.\n#\n###################\n \"\"\",\n file=sys.stderr,\n )\n return\n except OSError:\n pass\n except Exception:\n pass\n\n print( # noqa: S002\n \"\"\"\n###################\n#\n# Running webpack to compile frontend assets - this will take awhile\n#\n###################\n \"\"\"\n )\n\n try:\n status = subprocess.call(\n [\"yarn\", \"build-acceptance\"],\n env={\"PATH\": os.environ[\"PATH\"], \"NODE_OPTIONS\": \"--max-old-space-size=4096\"},\n )\n\n if status != 0:\n raise Exception(\n \"Unable to run `webpack` -- make sure your development environment is setup correctly: https://docs.sentry.io/development/contribute/environment/#macos---nodejs\"\n )\n except OSError:\n raise Exception(\n \"Unable to run `yarn` -- make sure your development environment is setup correctly: https://docs.sentry.io/development/contribute/environment/#macos---nodejs\"\n )", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _match_version_expression(\n self,\n op: str,\n value: str,\n client_version: Optional[str]\n ) -> bool:\n \"\"\"Tries to match the version expression against the client version.\n\n Args:\n op: str. The operator for comparison, e.g. '=', '>'.\n value: str. The version for comparison, e.g. '1.0.1'.\n client_version: str|None. The client version, e.g. '1.0.1-3aebf3h'.\n\n Returns:\n bool. True if the expression matches the version.\n\n Raises:\n Exception. Given operator is not supported.\n \"\"\"\n if client_version is None:\n return False\n\n match = APP_VERSION_WITH_HASH_REGEXP.match(client_version)\n # Ruling out the possibility of None for mypy type checking.\n assert match is not None\n client_version_without_hash = match.group(1)\n\n is_equal = value == client_version_without_hash\n is_client_version_smaller = self._is_first_version_smaller(\n client_version_without_hash, value)\n is_client_version_larger = self._is_first_version_smaller(\n value, client_version_without_hash\n )\n if op == '=':\n return is_equal\n elif op == '<':\n return is_client_version_smaller\n elif op == '<=':\n return is_equal or is_client_version_smaller\n elif op == '>':\n return is_client_version_larger\n elif op == '>=':\n return is_equal or is_client_version_larger\n else:\n raise Exception(\n 'Unsupported comparison operator \\'%s\\' for %s filter, '\n 'expected one of %s.' % (\n op, self._type, self.SUPPORTED_OP_FOR_FILTERS[self._type]))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _set_granule_values(\n self,\n quota: Quota,\n values: list[int | None],\n window_end: int | None = None,\n ) -> None:\n \"\"\"\n Set the usage in each granule of the given quota, for the time window ending at the given\n time.\n\n If no ending time is given, the current time is used.\n\n The list of values should be ordered from oldest to newest and must contain the same number\n of elements as the window has granules. To only change some of the values, pass `None` in\n the spot of any value which should remain unchanged. (For example, in a two-granule window,\n to only change the older granule, pass `[3, None]`.)\n \"\"\"\n window_duration = quota.window_seconds\n granule_duration = quota.granularity_seconds\n num_granules = window_duration // granule_duration\n\n if len(values) != num_granules:\n raise Exception(\n f\"Exactly {num_granules} granule values must be provided. \"\n + \"To leave an existing value as is, include `None` in its spot.\"\n )\n\n now = int(time.time())\n window_end_time = window_end or now\n\n previous_values = self._clear_quota(quota, window_end_time)\n\n for i, granule_end_time, value in zip(\n range(num_granules), self._get_granule_end_times(quota, window_end_time), values\n ):\n # When we cleared the quota above, we set each granule's value to 0, so here \"adding\"\n # usage is actually setting usage\n if value is not None:\n self._add_quota_usage(quota, value, granule_end_time)\n else:\n self._add_quota_usage(quota, previous_values[i], granule_end_time)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def add_uncategorized_skill_id(\n self, new_uncategorized_skill_id: str\n ) -> None:\n \"\"\"Updates the skill id list of a topic object.\n\n Args:\n new_uncategorized_skill_id: str. The new skill id to add to\n uncategorized_skill_ids list.\n\n Raises:\n Exception. The given skill id is already present in a subtopic.\n \"\"\"\n for subtopic in self.subtopics:\n if new_uncategorized_skill_id in subtopic.skill_ids:\n raise Exception(\n 'The skill id %s already exists in subtopic with id %s.'\n % (new_uncategorized_skill_id, subtopic.id))\n\n if new_uncategorized_skill_id in self.uncategorized_skill_ids:\n raise Exception(\n 'The skill id %s is already an uncategorized skill.'\n % new_uncategorized_skill_id)\n\n self.uncategorized_skill_ids.append(new_uncategorized_skill_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, data=None):\n\t\tself._keys = []\n\t\tdict.__init__(self)\n\t\tif data:\n\t\t\t# we were provided a regular dict\n\t\t\tif isinstance(data, dict):\n\t\t\t\tself.append_from_dict(data)\n\n\t\t\t# we were provided a tuple list\n\t\t\telif type(data) == list:\n\t\t\t\tself.append_from_plist(data)\n\n\t\t\t# we were provided invalid input\n\t\t\telse:\n\t\t\t\traise Exception(\"expected a dict or a tuple list\")", "smellKey": "S112", "smellId": null, "repo": "uajithkumar_audacity", "language": "python"} {"function": "def _get_satisfactory_metric(project: Project) -> str:\n \"\"\"It returns the statisfactory response time threshold for the project and\n the associated metric (\"transaction.duration\" or \"measurements.lcp\").\"\"\"\n\n result = ProjectTransactionThreshold.filter(\n organization_id=project.organization.id,\n project_ids=[project.id],\n order_by=[],\n value_list=[\"metric\"],\n )\n\n if len(result) == 0:\n metric = TransactionMetric.DURATION.value\n else:\n metric = result[0][0]\n\n if metric == TransactionMetric.DURATION.value:\n metric_field = \"transaction.duration\"\n elif metric == TransactionMetric.LCP.value:\n # We assume it's lcp since the enumerator contains only two possibilities.\n metric_field = \"measurements.lcp\"\n else:\n raise Exception(\"Invalid metric for project transaction threshold\")\n\n return metric_field", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def load_credentials(filename=None):\n if filename is None:\n path = os.path.join(os.getcwd(), 'credentials.yaml')\n else:\n path = os.path.abspath(filename)\n\n if os.path.isfile(path):\n with open(path) as credentials_fh:\n credentials_dict = yaml.safe_load(credentials_fh)\n return credentials_dict\n else:\n msg = 'Unable to load credentials file at %s' % path\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def migrate_state_schema(\n versioned_question_state: question_domain.VersionedQuestionStateDict\n) -> Optional[int]:\n \"\"\"Holds the responsibility of performing a step-by-step, sequential update\n of the state structure based on the schema version of the input\n state dictionary. If the current State schema changes, a new\n conversion function must be added and some code appended to this function\n to account for that new version.\n\n Args:\n versioned_question_state: dict. A dict with two keys:\n state_schema_version: int. the state schema version for the\n question.\n state: The State domain object representing the question\n state data.\n\n Returns:\n int. The next content id index for generating content id.\n\n Raises:\n Exception. The given state_schema_version is invalid.\n \"\"\"\n state_schema_version = versioned_question_state[\n 'state_schema_version']\n if state_schema_version is None or state_schema_version < 1:\n state_schema_version = 0\n\n if not (25 <= state_schema_version\n <= feconf.CURRENT_STATE_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v25-v%d state schemas at present.' %\n feconf.CURRENT_STATE_SCHEMA_VERSION)\n\n next_content_id_index = None\n while state_schema_version < feconf.CURRENT_STATE_SCHEMA_VERSION:\n if state_schema_version == 54:\n # State conversion function from 54 to 55 removes\n # next_content_id_index from the state level, hence this \"if\" case\n # populates the next_content_id_index from the old state, which will\n # be used for introducing next_content_id_index into\n # question level.\n next_content_id_index = (\n question_domain.Question.update_state_from_model(\n versioned_question_state, state_schema_version)\n )\n else:\n question_domain.Question.update_state_from_model(\n versioned_question_state, state_schema_version)\n state_schema_version += 1\n\n return next_content_id_index", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_translation_review_stats_models(\n stats_ids: List[str], strict: bool = True\n) -> Sequence[Optional[suggestion_models.TranslationReviewStatsModel]]:\n \"\"\"Finds translation review stats by the IDs.\n\n Args:\n stats_ids: list(str). The IDs of the stats.\n strict: bool. Whether to fail noisily if no stat with given ids exists.\n\n Returns:\n list(TranslationReviewStatsModel|None). The corresponding translation\n review stats for the given IDs.\n\n Raises:\n Exception. The stats models do not exist for the given IDs.\n \"\"\"\n stats_models = (\n suggestion_models.TranslationReviewStatsModel.get_multi(\n list(stats_ids)))\n\n if not strict:\n return stats_models\n\n for index, model in enumerate(stats_models):\n if model is None:\n raise Exception(\n 'The stats models do not exist for the stats_id %s.' % (\n stats_ids[index])\n )\n\n return stats_models", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,\n wiz_data=None, wiz_buttons=None,\n context=None, our_module=None):\n \"\"\"Take an ir.action.act_window and follow it until a report is produced\n\n :param action_id: the integer id of an action, or a reference to xml id\n of the act_window (can search [our_module.]+xml_id\n :param active_model, active_ids: call the action as if it had been launched\n from that model+ids (tree/form view action)\n :param wiz_data: a dictionary of values to use in the wizard, if needed.\n They will override (or complete) the default values of the\n wizard form.\n :param wiz_buttons: a list of button names, or button icon strings, which\n should be preferred to press during the wizard.\n Eg. 'OK' or 'gtk-print'\n :param our_module: the name of the calling module (string), like 'account'\n \"\"\"\n if not our_module and isinstance(action_id, basestring):\n if '.' in action_id:\n our_module = action_id.split('.', 1)[0]\n\n if context is None:\n context = {}\n else:\n context = context.copy() # keep it local\n # TODO context fill-up\n\n registry = openerp.registry(cr.dbname)\n\n def log_test(msg, *args):\n _test_logger.info(\" - \" + msg, *args)\n\n datas = {}\n if active_model:\n datas['model'] = active_model\n if active_ids:\n datas['ids'] = active_ids\n\n if not wiz_buttons:\n wiz_buttons = []\n\n if isinstance(action_id, basestring):\n if '.' in action_id:\n act_module, act_xmlid = action_id.split('.', 1)\n else:\n if not our_module:\n raise ValueError('You cannot only specify action_id \"%s\" without a module name' % action_id)\n act_module = our_module\n act_xmlid = action_id\n act_model, act_id = registry['ir.model.data'].get_object_reference(cr, uid, act_module, act_xmlid)\n else:\n assert isinstance(action_id, (long, int))\n act_model = 'ir.action.act_window' # assume that\n act_id = action_id\n act_xmlid = '<%s>' % act_id\n\n def _exec_action(action, datas, context):\n # taken from client/modules/action/main.py:84 _exec_action()\n if isinstance(action, bool) or 'type' not in action:\n return\n # Updating the context : Adding the context of action in order to use it on Views called from buttons\n if datas.get('id',False):\n context.update( {'active_id': datas.get('id',False), 'active_ids': datas.get('ids',[]), 'active_model': datas.get('model',False)})\n context1 = action.get('context', {})\n if isinstance(context1, basestring):\n context1 = safe_eval(context1, context.copy())\n context.update(context1)\n if action['type'] in ['ir.actions.act_window', 'ir.actions.submenu']:\n for key in ('res_id', 'res_model', 'view_type', 'view_mode',\n 'limit', 'auto_refresh', 'search_view', 'auto_search', 'search_view_id'):\n datas[key] = action.get(key, datas.get(key, None))\n\n view_id = False\n if action.get('views', []):\n if isinstance(action['views'],list):\n view_id = action['views'][0][0]\n datas['view_mode']= action['views'][0][1]\n else:\n if action.get('view_id', False):\n view_id = action['view_id'][0]\n elif action.get('view_id', False):\n view_id = action['view_id'][0]\n\n assert datas['res_model'], \"Cannot use the view without a model\"\n # Here, we have a view that we need to emulate\n log_test(\"will emulate a %s view: %s#%s\",\n action['view_type'], datas['res_model'], view_id or '?')\n\n view_res = registry[datas['res_model']].fields_view_get(cr, uid, view_id, action['view_type'], context)\n assert view_res and view_res.get('arch'), \"Did not return any arch for the view\"\n view_data = {}\n if view_res.get('fields',{}).keys():\n view_data = registry[datas['res_model']].default_get(cr, uid, view_res['fields'].keys(), context)\n if datas.get('form'):\n view_data.update(datas.get('form'))\n if wiz_data:\n view_data.update(wiz_data)\n _logger.debug(\"View data is: %r\", view_data)\n\n for fk, field in view_res.get('fields',{}).items():\n # Default fields returns list of int, while at create()\n # we need to send a [(6,0,[int,..])]\n if field['type'] in ('one2many', 'many2many') \\\n and view_data.get(fk, False) \\\n and isinstance(view_data[fk], list) \\\n and not isinstance(view_data[fk][0], tuple) :\n view_data[fk] = [(6, 0, view_data[fk])]\n\n action_name = action.get('name')\n try:\n from xml.dom import minidom\n cancel_found = False\n buttons = []\n dom_doc = minidom.parseString(view_res['arch'])\n if not action_name:\n action_name = dom_doc.documentElement.getAttribute('name')\n\n for button in dom_doc.getElementsByTagName('button'):\n button_weight = 0\n if button.getAttribute('special') == 'cancel':\n cancel_found = True\n continue\n if button.getAttribute('icon') == 'gtk-cancel':\n cancel_found = True\n continue\n if button.getAttribute('default_focus') == '1':\n button_weight += 20\n if button.getAttribute('string') in wiz_buttons:\n button_weight += 30\n elif button.getAttribute('icon') in wiz_buttons:\n button_weight += 10\n string = button.getAttribute('string') or '?%s' % len(buttons)\n\n buttons.append( { 'name': button.getAttribute('name'),\n 'string': string,\n 'type': button.getAttribute('type'),\n 'weight': button_weight,\n })\n except Exception, e:\n _logger.warning(\"Cannot resolve the view arch and locate the buttons!\", exc_info=True)\n raise AssertionError(e.args[0])\n\n if not datas['res_id']:\n # it is probably an orm_memory object, we need to create\n # an instance\n datas['res_id'] = registry[datas['res_model']].create(cr, uid, view_data, context)\n\n if not buttons:\n raise AssertionError(\"view form doesn't have any buttons to press!\")\n\n buttons.sort(key=lambda b: b['weight'])\n _logger.debug('Buttons are: %s', ', '.join([ '%s: %d' % (b['string'], b['weight']) for b in buttons]))\n\n res = None\n while buttons and not res:\n b = buttons.pop()\n log_test(\"in the \\\"%s\\\" form, I will press the \\\"%s\\\" button.\", action_name, b['string'])\n if not b['type']:\n log_test(\"the \\\"%s\\\" button has no type, cannot use it\", b['string'])\n continue\n if b['type'] == 'object':\n #there we are! press the button!\n fn = getattr(registry[datas['res_model']], b['name'])\n if not fn:\n _logger.error(\"The %s model doesn't have a %s attribute!\", datas['res_model'], b['name'])\n continue\n res = fn(cr, uid, [datas['res_id'],], context)\n break\n else:\n _logger.warning(\"in the \\\"%s\\\" form, the \\\"%s\\\" button has unknown type %s\",\n action_name, b['string'], b['type'])\n return res\n\n elif action['type']=='ir.actions.report.xml':\n if 'window' in datas:\n del datas['window']\n if not datas:\n datas = action.get('datas')\n if not datas:\n datas = action.get('data')\n datas = datas.copy()\n ids = datas.get('ids')\n if 'ids' in datas:\n del datas['ids']\n res = try_report(cr, uid, 'report.'+action['report_name'], ids, datas, context, our_module=our_module)\n return res\n else:\n raise Exception(\"Cannot handle action of type %s\" % act_model)\n\n log_test(\"will be using %s action %s #%d\", act_model, act_xmlid, act_id)\n action = registry[act_model].read(cr, uid, [act_id], context=context)[0]\n assert action, \"Could not read action %s[%s]\" %(act_model, act_id)\n loop = 0\n while action:\n loop += 1\n # This part tries to emulate the loop of the Gtk client\n if loop > 100:\n _logger.info(\"Passed %d loops, giving up\", loop)\n raise Exception(\"Too many loops at action\")\n log_test(\"it is an %s action at loop #%d\", action.get('type', 'unknown'), loop)\n result = _exec_action(action, datas, context)\n if not isinstance(result, dict):\n break\n datas = result.get('datas', {})\n if datas:\n del result['datas']\n action = result\n\n return True", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "@classmethod\n def shortname(cls, params):\n cls.build_naming_info()\n assert cls.PREFIX is not None\n name = [copy.copy(cls.PREFIX)]\n\n for k, v in params.items():\n if k not in cls.DEFAULTS:\n raise Exception(f\"You should provide a default value for the param name {k} with value {v}\")\n if v == cls.DEFAULTS[k]:\n # The default value is not added to the name\n continue\n\n key = cls.NAMING_INFO[\"short_param\"][k]\n\n if isinstance(v, bool):\n v = 1 if v else 0\n\n sep = \"\" if isinstance(v, (int, float)) else \"-\"\n e = f\"{key}{sep}{v}\"\n name.append(e)\n\n return \"_\".join(name)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def GetCurrentGeometricPoint(self, inParaViewSource, ioViewBounds,\n inUpdateInputPipelineFlag):\n \"returns the current absolute xyz of this point, calculating relative\\n position or element or node position if necessary; if it obtains\\n its view bounds during operation it returns them, otherwise it\\n returns None\\n \"\n if inUpdateInputPipelineFlag:\n UpdatePipelineWithCurrentTimeArgument(inParaViewSource)\n if PhactoriDbg(100):\n myDebugPrint3(\"GetCurrentGeometricPoint entered\\n\", 100)\n\n #import pdb\n #pdb.set_trace()\n\n #self.PrintSelf()\n if self.mPointType == 'absolute':\n #focal point is exact point in coordinate system of data\n returnXyz = list(self.mXyz)\n elif self.mPointType == 'datasize relative':\n #focal point is offset from center of data bounding box, with offset\n #relative in size to the size of the overall bounding box\n relativeXyz = self.mXyz\n myViewBounds = ioViewBounds[0]\n if myViewBounds == None:\n myViewBounds = GetGlobalDataBoundsParallel(inParaViewSource)\n ioViewBounds[0] = myViewBounds\n #old style: use maximum bounding box dimension to define\n #relative space\n #maxDim = GetMaximumDimensionFromBounds(myViewBounds)\n #returnXyz = [ (myViewBounds[1] + myViewBounds[0]) * 0.5 + \\\n # maxDim * relativeXyz[0], \\\n # (myViewBounds[3] + myViewBounds[2]) * 0.5 + \\\n # maxDim * relativeXyz[1], \\\n # (myViewBounds[5] + myViewBounds[4]) * 0.5 + \\\n # maxDim * relativeXyz[2] ]\n\n #new style: do relative in each dimension\n returnXyz = [0.0,0.0,0.0]\n returnXyz[0] = myViewBounds[0] + (myViewBounds[1] - myViewBounds[0]) * \\\n (relativeXyz[0] + 0.5)\n returnXyz[1] = myViewBounds[2] + (myViewBounds[3] - myViewBounds[2]) * \\\n (relativeXyz[1] + 0.5)\n returnXyz[2] = myViewBounds[4] + (myViewBounds[5] - myViewBounds[4]) * \\\n (relativeXyz[2] + 0.5)\n elif self.mPointType == 'node':\n nodeId = self.mElementOrNodeId\n returnXyz = [0.0, 0.0, 0.0]\n GetXyzForNodeOrElementParallel(inParaViewSource, True, nodeId, returnXyz)\n elif self.mPointType == 'element':\n elementId = self.mElementOrNodeId\n returnXyz = [0.0, 0.0, 0.0]\n GetXyzForNodeOrElementParallel(inParaViewSource, False, elementId, returnXyz)\n elif self.mPointType == 'min variable':\n returnXyz = [0.0, 0.0, 0.0]\n if self.mInputNameToUseForMinMaxVariable == None:\n pvFilter = inParaViewSource\n else:\n if self.mInputPvSourceToUseForMinMaxVariable == None:\n global gPipeAndViewsState\n operationBlock = gPipeAndViewsState.mOperationBlocks[\n self.mInputNameToUseForMinMaxVariable]\n pvFilter = operationBlock.GetPvFilter()\n self.mInputPvSourceToUseForMinMaxVariable = pvFilter\n else:\n pvFilter = self.mInputPvSourceToUseForMinMaxVariable\n if(pvFilter == None):\n #no pvFilter for min/max yet, just use 0,0,0\n returnXyz = [0.0, 0.0, 0.0]\n else:\n UpdatePipelineWithCurrentTimeArgument(pvFilter)\n GetXyzForMinOrMaxVariable(pvFilter, True,\n self.mReferenceVariableInfo, returnXyz)\n elif self.mPointType == 'max variable':\n returnXyz = [0.0, 0.0, 0.0]\n if self.mInputNameToUseForMinMaxVariable == None:\n pvFilter = inParaViewSource\n if PhactoriDbg():\n myDebugPrint3(\"max var point has no source, using incoming\\n\")\n else:\n if PhactoriDbg():\n myDebugPrint3(\"max var point has source, using instead\\n\")\n if self.mInputPvSourceToUseForMinMaxVariable == None:\n if PhactoriDbg():\n myDebugPrint3(\"not previously found, must locate\\n\")\n #global gPipeAndViewsState\n operationBlock = gPipeAndViewsState.mOperationBlocks[\n self.mInputNameToUseForMinMaxVariable]\n pvFilter = operationBlock.GetPvFilter()\n self.mInputPvSourceToUseForMinMaxVariable = pvFilter\n else:\n if PhactoriDbg():\n myDebugPrint3(\"previously found.\\n\")\n pvFilter = self.mInputPvSourceToUseForMinMaxVariable\n if PhactoriDbg():\n myDebugPrint3(\"incoming: \" + str(inParaViewSource) + \"\\n\"\n \"using: \" + str(pvFilter) + \"\\n\")\n if(pvFilter == None):\n #no pvFilter for min/max yet, just use 0,0,0\n returnXyz = [0.0, 0.0, 0.0]\n else:\n UpdatePipelineWithCurrentTimeArgument(pvFilter)\n GetXyzForMinOrMaxVariable(pvFilter, False,\n self.mReferenceVariableInfo, returnXyz)\n else:\n errStr = 'GetCurrentGeometricPoint error! bad mPointType\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n \n if PhactoriDbg(100):\n myDebugPrint3(\"GetCurrentGeometricPoint returning: \" + \\\n str(returnXyz) + \"\\n\", 100)\n\n return returnXyz", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def assign_new_role(self, user_id: str, new_role: str) -> str:\n \"\"\"Assigns new role to user and removes previous role if present.\n\n Args:\n user_id: str. The ID of the user.\n new_role: str. The role of the user.\n\n Returns:\n str. The previous role of the user.\n\n Raises:\n Exception. If previous role is assigned again.\n \"\"\"\n old_role = ROLE_NONE\n if new_role == ROLE_VIEWER:\n if self.status != ACTIVITY_STATUS_PRIVATE:\n raise Exception(\n 'Public explorations can be viewed by anyone.')\n\n for role, user_ids in zip(\n [ROLE_OWNER, ROLE_EDITOR, ROLE_VIEWER, ROLE_VOICE_ARTIST],\n [self.owner_ids, self.editor_ids, self.viewer_ids,\n self.voice_artist_ids]):\n if user_id in user_ids:\n user_ids.remove(user_id)\n old_role = role\n\n if new_role == role and old_role != new_role:\n user_ids.append(user_id)\n\n if old_role == new_role:\n if old_role == ROLE_OWNER:\n raise Exception(\n 'This user already owns this exploration.')\n\n if old_role == ROLE_EDITOR:\n raise Exception(\n 'This user already can edit this exploration.')\n\n if old_role == ROLE_VOICE_ARTIST:\n raise Exception(\n 'This user already can voiceover this exploration.')\n\n if old_role == ROLE_VIEWER:\n raise Exception(\n 'This user already can view this exploration.')\n\n return old_role", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_group(innergroup, all_groups):\n try:\n return [\n g\n for g in all_groups\n if g.get_compounddef()[0].get_id() == innergroup.get_refid()\n ][0]\n except IndexError as e:\n raise Exception(f\"Unexpected group {innergroup.get_refid()}\") from e", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def get_demo_exploration_components(\n demo_path: str\n) -> Tuple[str, List[Tuple[str, bytes]]]:\n \"\"\"Gets the content of `demo_path` in the sample explorations folder.\n\n Args:\n demo_path: str. The file or folder path for the content of an\n exploration in SAMPLE_EXPLORATIONS_DIR. E.g.: 'adventure.yaml' or\n 'tar/'.\n\n Returns:\n tuple. A 2-tuple, the first element of which is a yaml string, and the\n second element of which is a list of (filepath, content) 2-tuples. The\n filepath does not include the assets/ prefix.\n\n Raises:\n Exception. The path of the file is unrecognized or does not exist.\n \"\"\"\n demo_filepath = os.path.join(feconf.SAMPLE_EXPLORATIONS_DIR, demo_path)\n\n if demo_filepath.endswith('yaml'):\n file_contents = utils.get_file_contents(demo_filepath)\n return file_contents, []\n elif os.path.isdir(demo_filepath):\n return utils.get_exploration_components_from_dir(demo_filepath)\n else:\n raise Exception('Unrecognized file path: %s' % demo_path)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def ParseUsd(usdFilePath):\n sdfLayer = Sdf.Layer.FindOrOpen(usdFilePath)\n stage = Usd.Stage.Open(sdfLayer)\n classes = []\n\n hasInvalidFields = False\n # Node that we do not want to auto promote the stage to use literal\n # identifier if all any of the layers (this or sublayers) defined it. But we\n # just care of the sdfLayer of the schema being generated, and hence only\n # query the presence of useLiteralIdentifier on the sdfLayer metadata.\n useLiteralIdentifier = _UseLiteralIdentifierForLayer(sdfLayer)\n\n # PARSE CLASSES\n for sdfPrim in sdfLayer.rootPrims:\n if sdfPrim.specifier != Sdf.SpecifierClass:\n continue\n\n if not _ValidateFields(sdfPrim):\n hasInvalidFields = True\n\n usdPrim = stage.GetPrimAtPath(sdfPrim.path)\n classInfo = ClassInfo(usdPrim, sdfPrim, useLiteralIdentifier)\n\n # make sure that if we have a multiple-apply schema with a property\n # namespace prefix that the prim actually has some properties\n if classInfo.apiSchemaType == MULTIPLE_APPLY:\n if classInfo.propertyNamespacePrefix and \\\n len(sdfPrim.properties) == 0:\n raise _GetSchemaDefException(\n \"Multiple-apply schemas that have the \"\n \"propertyNamespacePrefix metadata fields must have at \"\n \"least one property\", sdfPrim.path)\n if not classInfo.propertyNamespacePrefix and \\\n not len(sdfPrim.properties) == 0:\n raise _GetSchemaDefException(\n \"Multiple-apply schemas that do not\"\n \"have a propertyNamespacePrefix metadata field must \"\n \"have zero properties\", sdfPrim.path)\n\n # Templatize all the included API schema names for this multiple\n # apply API (see _MakeMultipleApplySchemaNameTemplate for the\n # explanation as to why).\n classInfo.allAppliedAPISchemas = [\n _MakeMultipleApplySchemaNameTemplate(s) \n for s in classInfo.allAppliedAPISchemas]\n classInfo.apiSchemasMetadata.prependedItems = [\n _MakeMultipleApplySchemaNameTemplate(s) \n for s in classInfo.apiSchemasMetadata.prependedItems]\n\n classes.append(classInfo)\n #\n # We don't want to use the composed property names here because we only\n # want the local properties declared directly on the class, which the\n # \"properties\" metadata field provides.\n #\n attrApiNames = []\n relApiNames = []\n for sdfProp in sdfPrim.properties:\n\n if not _ValidateFields(sdfProp):\n hasInvalidFields = True\n\n # Attribute\n if isinstance(sdfProp, Sdf.AttributeSpec):\n attrInfo = AttrInfo(sdfProp, classInfo)\n\n # Assert unique attribute names\n if (attrInfo.apiName != ''):\n if attrInfo.name in classInfo.attrs:\n raise Exception(\n 'Schema Attribute names must be unique, '\n 'irrespective of namespacing. '\n 'Duplicate name encountered: %s.%s' %\n (classInfo.usdPrimTypeName, attrInfo.name))\n elif attrInfo.apiName in attrApiNames:\n raise Exception(\n 'Schema Attribute API names must be unique. '\n 'Duplicate apiName encountered: %s.%s' %\n (classInfo.usdPrimTypeName, attrInfo.apiName))\n else:\n attrApiNames.append(attrInfo.apiName)\n classInfo.attrs[attrInfo.name] = attrInfo\n classInfo.attrOrder.append(attrInfo.name)\n\n # Relationship\n else:\n relInfo = RelInfo(sdfProp, classInfo)\n\n # Assert unique relationship names\n if (relInfo.apiName != ''):\n if relInfo.name in classInfo.rels: \n raise Exception(\n 'Schema Relationship names must be unique, '\n 'irrespective of namespacing. '\n 'Duplicate name encountered: %s.%s' %\n (classInfo.usdPrimTypeName, relInfo.name))\n elif relInfo.apiName in relApiNames:\n raise Exception(\n 'Schema Relationship API names must be unique. '\n 'Duplicate apiName encountered: %s.%s' %\n (classInfo.usdPrimTypeName, relInfo.apiName))\n else:\n relApiNames.append(relInfo.apiName)\n classInfo.rels[relInfo.name] = relInfo\n classInfo.relOrder.append(relInfo.name)\n\n # Get all the API schema override properties declared for this class as\n # they need to appear in the generatedSchema. This includes any \n # inherited override properties base class schemas. The properties are\n # also properly prefixed with the namespace template for multiple apply\n # schemas.\n classInfo.apiSchemaOverridePropertyNames = \\\n _GetAPISchemaOverridePropertyNames(\n usdPrim, classInfo.propertyNamespacePrefix)\n \n for classInfo in classes:\n # If this is an applied API schema that does not inherit from \n # UsdAPISchemaBase directly, ensure that the parent class is also \n # an applied API Schema.\n if classInfo.isApi and classInfo.parentCppClassName!='UsdAPISchemaBase':\n parentClassInfo = GetClassInfo(classes, classInfo.parentCppClassName)\n if parentClassInfo:\n if parentClassInfo.isAppliedAPISchema != \\\n classInfo.isAppliedAPISchema:\n raise Exception(\"API schema '%s' inherits from incompatible \"\n \"base API schema '%s'. Both must be either applied API \"\n \"schemas or non-applied API schemas.\" %\n (classInfo.cppClassName, parentClassInfo.cppClassName))\n if parentClassInfo.isMultipleApply != \\\n classInfo.isMultipleApply:\n raise Exception(\"API schema '%s' inherits from incompatible \"\n \"base API schema '%s'. Both must be either single-apply \"\n \"or multiple-apply.\" % (classInfo.cppClassName,\n parentClassInfo.cppClassName))\n else:\n parentClassTfType = Tf.Type.FindByName(\n classInfo.parentCppClassName)\n if parentClassTfType and parentClassTfType != Tf.Type.Unknown:\n if classInfo.isAppliedAPISchema != \\\n Usd.SchemaRegistry().IsAppliedAPISchema(parentClassTfType):\n raise Exception(\"API schema '%s' inherits from \"\n \"incompatible base API schema '%s'. Both must be \"\n \"either applied API schemas or non-applied API \"\n \" schemas.\" % (classInfo.cppClassName,\n parentClassInfo.cppClassName))\n if classInfo.isMultipleApply != \\\n Usd.SchemaRegistry().IsMultipleApplyAPISchema(\n parentClassTfType):\n raise Exception(\"API schema '%s' inherits from \"\n \"incompatible base API schema '%s'. Both must be either\" \n \" single-apply or multiple-apply.\" % \n (classInfo.cppClassName, parentClassInfo.cppClassName))\n \n if hasInvalidFields:\n raise Exception('Invalid fields specified in schema.')\n\n return (_GetLibName(sdfLayer),\n _GetLibPath(sdfLayer),\n _GetLibPrefix(sdfLayer),\n _GetTokensPrefix(sdfLayer),\n _GetUseExportAPI(sdfLayer),\n _GetLibTokens(sdfLayer),\n _SkipCodeGenForSchemaLib(stage),\n classes)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_OpenUSD", "language": "python"} {"function": "def __init__(self, username: str, password: str):\n if not username:\n raise Exception(\"UpcloudClient username must be set\")\n if not password:\n raise Exception(\"UpcloudClient password must be set\")\n\n client = requests.Session()\n encoded_auth = base64.b64encode(\n f\"{username}:{password}\".encode(\"utf-8\")\n ).decode(\"utf-8\")\n client.headers = {\"Authorization\": f\"Basic {encoded_auth}\"}\n self.__client = client", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def check_objects_being_equally_in_main_init():\n \"\"\"\n Check if a (TensorFlow or Flax) object is in the main __init__ iif its counterpart in PyTorch is.\n \"\"\"\n attrs = dir(transformers)\n\n failures = []\n for attr in attrs:\n obj = getattr(transformers, attr)\n if not hasattr(obj, \"__module__\") or \"models.deprecated\" in obj.__module__:\n continue\n\n module_path = obj.__module__\n module_name = module_path.split(\".\")[-1]\n module_dir = \".\".join(module_path.split(\".\")[:-1])\n if (\n module_name.startswith(\"modeling_\")\n and not module_name.startswith(\"modeling_tf_\")\n and not module_name.startswith(\"modeling_flax_\")\n ):\n parent_module = sys.modules[module_dir]\n\n frameworks = []\n if is_tf_available():\n frameworks.append(\"TF\")\n if is_flax_available():\n frameworks.append(\"Flax\")\n\n for framework in frameworks:\n other_module_path = module_path.replace(\"modeling_\", f\"modeling_{framework.lower()}_\")\n if os.path.isfile(\"src/\" + other_module_path.replace(\".\", \"/\") + \".py\"):\n other_module_name = module_name.replace(\"modeling_\", f\"modeling_{framework.lower()}_\")\n other_module = getattr(parent_module, other_module_name)\n if hasattr(other_module, f\"{framework}{attr}\"):\n if not hasattr(transformers, f\"{framework}{attr}\"):\n if f\"{framework}{attr}\" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK:\n failures.append(f\"{framework}{attr}\")\n if hasattr(other_module, f\"{framework}_{attr}\"):\n if not hasattr(transformers, f\"{framework}_{attr}\"):\n if f\"{framework}_{attr}\" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK:\n failures.append(f\"{framework}_{attr}\")\n if len(failures) > 0:\n raise Exception(f\"There were {len(failures)} failures:\\n\" + \"\\n\".join(failures))", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def update_translation_suggestion(\n suggestion_id: str, translation_html: str\n) -> None:\n \"\"\"Updates the translation_html of a suggestion with the given\n suggestion_id.\n\n Args:\n suggestion_id: str. The id of the suggestion to be updated.\n translation_html: str. The new translation_html string.\n\n Raises:\n Exception. Expected SuggestionTranslateContent suggestion but found\n different suggestion.\n \"\"\"\n suggestion = get_suggestion_by_id(suggestion_id)\n if not isinstance(\n suggestion, suggestion_registry.SuggestionTranslateContent\n ):\n raise Exception(\n 'Expected SuggestionTranslateContent suggestion but found: %s.'\n % type(suggestion).__name__\n )\n suggestion.change_cmd.translation_html = (\n html_cleaner.clean(translation_html)\n if isinstance(translation_html, str)\n else translation_html\n )\n suggestion.edited_by_reviewer = True\n suggestion.pre_update_validate(suggestion.change_cmd)\n _update_suggestion(suggestion)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def update_interaction_confirmed_unclassified_answers(\n self, confirmed_unclassified_answers: List[AnswerGroup]\n ) -> None:\n \"\"\"Update the confirmed_unclassified_answers of IteractionInstance\n domain object.\n\n Args:\n confirmed_unclassified_answers: list(AnswerGroup). The new list of\n answers which have been confirmed to be associated with the\n default outcome.\n\n Raises:\n Exception. Given answers is not of type list.\n \"\"\"\n if not isinstance(confirmed_unclassified_answers, list):\n raise Exception(\n 'Expected confirmed_unclassified_answers to be a list,'\n ' received %s' % confirmed_unclassified_answers)\n self.interaction.confirmed_unclassified_answers = (\n confirmed_unclassified_answers)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __conform__(self, proto):\n \"\"\"Does the given protocol conform to what Psycopg2 expects?\"\"\"\n from psycopg2.extensions import ISQLQuote\n\n if proto == ISQLQuote:\n return self\n else:\n raise Exception(\n \"Error implementing psycopg2 protocol. Is psycopg2 installed?\"\n )", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _add(self, count: str):\n if count not in self.count_prefixes:\n raise Exception(\"Requires a valid key param.\")\n\n now = datetime.now().strftime(\"%Y-%m-%d\")\n buffer_key = f\"{self.integration_key}:{now}\"\n\n pipe = self.client.pipeline()\n pipe.hincrby(buffer_key, count + \"_count\", 1)\n pipe.expire(buffer_key, self.key_expiration_seconds)\n pipe.execute()", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def main(args):\n extra_args = None\n if DEMO_EXTRA_AGENT_ARGS:\n extra_args = json.loads(DEMO_EXTRA_AGENT_ARGS)\n print(\"Got extra args:\", extra_args)\n faber_agent = await create_agent_with_args(\n args,\n ident=\"faber\",\n extra_args=extra_args,\n )\n\n try:\n log_status(\n \"#1 Provision an agent and wallet, get back configuration details\"\n + (\n f\" (Wallet type: {faber_agent.wallet_type})\"\n if faber_agent.wallet_type\n else \"\"\n )\n )\n agent = FaberAgent(\n \"faber.agent\",\n faber_agent.start_port,\n faber_agent.start_port + 1,\n genesis_data=faber_agent.genesis_txns,\n genesis_txn_list=faber_agent.genesis_txn_list,\n no_auto=faber_agent.no_auto,\n tails_server_base_url=faber_agent.tails_server_base_url,\n revocation=faber_agent.revocation,\n timing=faber_agent.show_timing,\n multitenant=faber_agent.multitenant,\n mediation=faber_agent.mediation,\n wallet_type=faber_agent.wallet_type,\n seed=faber_agent.seed,\n aip=faber_agent.aip,\n endorser_role=faber_agent.endorser_role,\n anoncreds_legacy_revocation=faber_agent.anoncreds_legacy_revocation,\n log_file=faber_agent.log_file,\n log_config=faber_agent.log_config,\n log_level=faber_agent.log_level,\n reuse_connections=faber_agent.reuse_connections,\n multi_use_invitations=faber_agent.multi_use_invitations,\n public_did_connections=faber_agent.public_did_connections,\n extra_args=extra_args,\n )\n\n faber_schema_name = \"degree schema\"\n faber_schema_attrs = [\n \"name\",\n \"date\",\n \"degree\",\n \"birthdate_dateint\",\n \"timestamp\",\n ]\n if faber_agent.cred_type in [CRED_FORMAT_INDY, CRED_FORMAT_VC_DI]:\n faber_agent.public_did = True\n await faber_agent.initialize(\n the_agent=agent,\n schema_name=faber_schema_name,\n schema_attrs=faber_schema_attrs,\n create_endorser_agent=(\n (faber_agent.endorser_role == \"author\")\n if faber_agent.endorser_role\n else False\n ),\n )\n elif faber_agent.cred_type in [\n CRED_FORMAT_JSON_LD,\n ]:\n faber_agent.public_did = True\n await faber_agent.initialize(the_agent=agent)\n else:\n raise Exception(\"Invalid credential type:\" + faber_agent.cred_type)\n\n # generate an invitation for Alice\n await faber_agent.generate_invitation(\n display_qr=True,\n reuse_connections=faber_agent.reuse_connections,\n multi_use_invitations=faber_agent.multi_use_invitations,\n public_did_connections=faber_agent.public_did_connections,\n wait=True,\n )\n\n exchange_tracing = False\n options = \" (1) Issue Credential\\n\"\n if faber_agent.cred_type in [\n CRED_FORMAT_INDY,\n CRED_FORMAT_VC_DI,\n ]:\n options += \" (1a) Set Credential Type (%CRED_TYPE%)\\n\"\n options += (\n \" (2) Send Proof Request\\n\"\n \" (2a) Send *Connectionless* Proof Request (requires a Mobile client)\\n\"\n \" (3) Send Message\\n\"\n \" (4) Create New Invitation\\n\"\n )\n if faber_agent.revocation:\n options += (\n \" (5) Revoke Credential\\n\"\n \" (6) Publish Revocations\\n\"\n \" (7) Rotate Revocation Registry\\n\"\n \" (8) List Revocation Registries\\n\"\n )\n if faber_agent.endorser_role and faber_agent.endorser_role == \"author\":\n options += \" (D) Set Endorser's DID\\n\"\n if faber_agent.multitenant:\n options += \" (W) Create and/or Enable Wallet\\n\"\n options += \" (U) Upgrade wallet to anoncreds \\n\"\n options += \" (T) Toggle tracing on credential/proof exchange\\n\"\n options += \" (X) Exit?\\n[1/2/3/4/{}{}T/X] \".format(\n \"5/6/7/8/\" if faber_agent.revocation else \"\",\n \"W/\" if faber_agent.multitenant else \"\",\n )\n\n upgraded_to_anoncreds = False\n async for option in prompt_loop(\n options.replace(\"%CRED_TYPE%\", faber_agent.cred_type)\n ):\n if option is not None:\n option = option.strip()\n\n # Anoncreds has different endpoints for revocation\n is_anoncreds = False\n if (\n faber_agent.agent.__dict__[\"wallet_type\"] == \"askar-anoncreds\"\n or upgraded_to_anoncreds\n ):\n is_anoncreds = True\n\n if option is None or option in \"xX\":\n break\n\n elif option in \"dD\" and faber_agent.endorser_role:\n endorser_did = await prompt(\"Enter Endorser's DID: \")\n await faber_agent.agent.admin_POST(\n f\"/transactions/{faber_agent.agent.connection_id}/set-endorser-info\",\n params={\"endorser_did\": endorser_did},\n )\n\n elif option in \"wW\" and faber_agent.multitenant:\n target_wallet_name = await prompt(\"Enter wallet name: \")\n include_subwallet_webhook = await prompt(\n \"(Y/N) Create sub-wallet webhook target: \"\n )\n if include_subwallet_webhook.lower() == \"y\":\n created = await faber_agent.agent.register_or_switch_wallet(\n target_wallet_name,\n webhook_port=faber_agent.agent.get_new_webhook_port(),\n public_did=True,\n mediator_agent=faber_agent.mediator_agent,\n endorser_agent=faber_agent.endorser_agent,\n taa_accept=faber_agent.taa_accept,\n )\n else:\n created = await faber_agent.agent.register_or_switch_wallet(\n target_wallet_name,\n public_did=True,\n mediator_agent=faber_agent.mediator_agent,\n endorser_agent=faber_agent.endorser_agent,\n cred_type=faber_agent.cred_type,\n taa_accept=faber_agent.taa_accept,\n )\n # create a schema and cred def for the new wallet\n # TODO check first in case we are switching between existing wallets\n if created:\n # TODO this fails because the new wallet doesn't get a public DID\n await faber_agent.create_schema_and_cred_def(\n schema_name=faber_schema_name,\n schema_attrs=faber_schema_attrs,\n )\n\n elif option in \"tT\":\n exchange_tracing = not exchange_tracing\n log_msg(\n \">>> Credential/Proof Exchange Tracing is {}\".format(\n \"ON\" if exchange_tracing else \"OFF\"\n )\n )\n\n elif option == \"1a\":\n new_cred_type = await prompt(\n \"Enter credential type ({}, {}): \".format(\n CRED_FORMAT_INDY,\n CRED_FORMAT_VC_DI,\n )\n )\n if new_cred_type in [\n CRED_FORMAT_INDY,\n CRED_FORMAT_VC_DI,\n ]:\n faber_agent.set_cred_type(new_cred_type)\n else:\n log_msg(\"Not a valid credential type.\")\n\n elif option == \"1\":\n log_status(\"#13 Issue credential offer to X\")\n\n if faber_agent.aip == 10:\n offer_request = faber_agent.agent.generate_credential_offer(\n faber_agent.aip, None, faber_agent.cred_def_id, exchange_tracing\n )\n await faber_agent.agent.admin_POST(\n \"/issue-credential/send-offer\", offer_request\n )\n\n elif faber_agent.aip == 20:\n if faber_agent.cred_type == CRED_FORMAT_INDY:\n offer_request = faber_agent.agent.generate_credential_offer(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.cred_def_id,\n exchange_tracing,\n )\n\n elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:\n offer_request = faber_agent.agent.generate_credential_offer(\n faber_agent.aip,\n faber_agent.cred_type,\n None,\n exchange_tracing,\n )\n\n elif faber_agent.cred_type == CRED_FORMAT_VC_DI:\n offer_request = faber_agent.agent.generate_credential_offer(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.cred_def_id,\n exchange_tracing,\n )\n\n else:\n raise Exception(\n f\"Error invalid credential type: {faber_agent.cred_type}\"\n )\n\n await faber_agent.agent.admin_POST(\n \"/issue-credential-2.0/send-offer\", offer_request\n )\n\n else:\n raise Exception(f\"Error invalid AIP level: {faber_agent.aip}\")\n\n elif option == \"2\":\n log_status(\"#20 Request proof of degree from alice\")\n if faber_agent.aip == 10:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n )\n )\n await faber_agent.agent.admin_POST(\n \"/present-proof/send-request\", proof_request_web_request\n )\n pass\n\n elif faber_agent.aip == 20:\n if faber_agent.cred_type == CRED_FORMAT_INDY:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n )\n )\n\n elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n )\n )\n\n elif faber_agent.cred_type == CRED_FORMAT_VC_DI:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n )\n )\n\n else:\n raise Exception(\n \"Error invalid credential type:\" + faber_agent.cred_type\n )\n\n await agent.admin_POST(\n \"/present-proof-2.0/send-request\", proof_request_web_request\n )\n\n else:\n raise Exception(f\"Error invalid AIP level: {faber_agent.aip}\")\n\n elif option == \"2a\":\n log_status(\"#20 Request * Connectionless * proof of degree from alice\")\n if faber_agent.aip == 10:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n connectionless=True,\n )\n )\n proof_request = await faber_agent.agent.admin_POST(\n \"/present-proof/create-request\", proof_request_web_request\n )\n pres_req_id = proof_request[\"presentation_exchange_id\"]\n url = (\n os.getenv(\"WEBHOOK_TARGET\")\n or (\n \"http://\"\n + os.getenv(\"DOCKERHOST\").replace(\n \"{PORT}\", str(faber_agent.agent.admin_port + 1)\n )\n + \"/webhooks\"\n )\n ) + f\"/pres_req/{pres_req_id}/\"\n log_msg(f\"Proof request url: {url}\")\n qr = QRCode(border=1)\n qr.add_data(url)\n log_msg(\n \"Scan the following QR code to accept the proof request from a mobile agent.\"\n )\n qr.print_ascii(invert=True)\n\n elif faber_agent.aip == 20:\n if faber_agent.cred_type == CRED_FORMAT_INDY:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n connectionless=True,\n )\n )\n elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n connectionless=True,\n )\n )\n\n elif faber_agent.cred_type == CRED_FORMAT_VC_DI:\n proof_request_web_request = (\n faber_agent.agent.generate_proof_request_web_request(\n faber_agent.aip,\n faber_agent.cred_type,\n faber_agent.revocation,\n exchange_tracing,\n connectionless=True,\n )\n )\n else:\n raise Exception(\n \"Error invalid credential type:\" + faber_agent.cred_type\n )\n\n proof_request = await faber_agent.agent.admin_POST(\n \"/present-proof-2.0/create-request\", proof_request_web_request\n )\n pres_req_id = proof_request[\"pres_ex_id\"]\n url = (\n \"http://\"\n + os.getenv(\"DOCKERHOST\").replace(\n \"{PORT}\", str(faber_agent.agent.admin_port + 1)\n )\n + \"/webhooks/pres_req/\"\n + pres_req_id\n + \"/\"\n )\n log_msg(f\"Proof request url: {url}\")\n qr = QRCode(border=1)\n qr.add_data(url)\n log_msg(\n \"Scan the following QR code to accept the proof request from a mobile agent.\"\n )\n qr.print_ascii(invert=True)\n else:\n raise Exception(f\"Error invalid AIP level: {faber_agent.aip}\")\n\n elif option == \"3\":\n msg = await prompt(\"Enter message: \")\n await faber_agent.agent.admin_POST(\n f\"/connections/{faber_agent.agent.connection_id}/send-message\",\n {\"content\": msg},\n )\n\n elif option == \"4\":\n log_msg(\n \"Creating a new invitation, please receive \"\n \"and accept this invitation using Alice agent\"\n )\n await faber_agent.generate_invitation(\n display_qr=True,\n reuse_connections=faber_agent.reuse_connections,\n multi_use_invitations=faber_agent.multi_use_invitations,\n public_did_connections=faber_agent.public_did_connections,\n wait=True,\n )\n\n elif option == \"5\" and faber_agent.revocation:\n rev_reg_id = (await prompt(\"Enter revocation registry ID: \")).strip()\n cred_rev_id = (await prompt(\"Enter credential revocation ID: \")).strip()\n publish = (\n await prompt(\"Publish now? [Y/N]: \", default=\"N\")\n ).strip() in \"yY\"\n\n try:\n endpoint = (\n \"/anoncreds/revocation/revoke\"\n if is_anoncreds\n else \"/revocation/revoke\"\n )\n await faber_agent.agent.admin_POST(\n endpoint,\n {\n \"rev_reg_id\": rev_reg_id,\n \"cred_rev_id\": cred_rev_id,\n \"publish\": publish,\n \"connection_id\": faber_agent.agent.connection_id,\n # leave out thread_id, let aca-py generate\n # \"thread_id\": \"12345678-4444-4444-4444-123456789012\",\n \"comment\": \"Revocation reason goes here ...\",\n },\n )\n except ClientError:\n pass\n\n elif option == \"6\" and faber_agent.revocation:\n try:\n endpoint = (\n \"/anoncreds/revocation/publish-revocations\"\n if is_anoncreds\n else \"/revocation/publish-revocations\"\n )\n resp = await faber_agent.agent.admin_POST(endpoint, {})\n faber_agent.agent.log(\n \"Published revocations for {} revocation registr{} {}\".format(\n len(resp[\"rrid2crid\"]),\n \"y\" if len(resp[\"rrid2crid\"]) == 1 else \"ies\",\n json.dumps(list(resp[\"rrid2crid\"]), indent=4),\n )\n )\n except ClientError:\n pass\n elif option == \"7\" and faber_agent.revocation:\n try:\n endpoint = (\n f\"/anoncreds/revocation/active-registry/{faber_agent.cred_def_id}/rotate\"\n if is_anoncreds\n else f\"/revocation/active-registry/{faber_agent.cred_def_id}/rotate\"\n )\n resp = await faber_agent.agent.admin_POST(\n endpoint,\n {},\n )\n faber_agent.agent.log(\n \"Rotated registries for {}. Decommissioned Registries: {}\".format(\n faber_agent.cred_def_id,\n json.dumps(list(resp[\"rev_reg_ids\"]), indent=4),\n )\n )\n except ClientError:\n pass\n elif option == \"8\" and faber_agent.revocation:\n if is_anoncreds:\n endpoint = \"/anoncreds/revocation/registries\"\n states = [\n \"finished\",\n \"failed\",\n \"action\",\n \"wait\",\n \"decommissioned\",\n \"full\",\n ]\n default_state = \"finished\"\n else:\n endpoint = \"/revocation/registries/created\"\n states = [\n \"init\",\n \"generated\",\n \"posted\",\n \"active\",\n \"full\",\n \"decommissioned\",\n ]\n default_state = \"active\"\n state = (\n await prompt(\n f\"Filter by state: {states}: \",\n default=default_state,\n )\n ).strip()\n if state not in states:\n state = \"active\"\n try:\n resp = await faber_agent.agent.admin_GET(\n endpoint,\n params={\"state\": state},\n )\n faber_agent.agent.log(\n \"Registries (state = '{}'): {}\".format(\n state,\n json.dumps(list(resp[\"rev_reg_ids\"]), indent=4),\n )\n )\n except ClientError:\n pass\n elif option in \"uU\" and faber_agent.multitenant:\n log_status(\"Upgrading wallet to anoncreds. Wait a couple seconds...\")\n await faber_agent.agent.admin_POST(\n \"/anoncreds/wallet/upgrade\",\n params={\"wallet_name\": faber_agent.agent.wallet_name},\n )\n upgraded_to_anoncreds = True\n await asyncio.sleep(2.0)\n\n if faber_agent.show_timing:\n timing = await faber_agent.agent.fetch_timing()\n if timing:\n for line in faber_agent.agent.format_timing(timing):\n log_msg(line)\n\n finally:\n terminated = await faber_agent.terminate()\n\n await asyncio.sleep(0.1)\n\n if not terminated:\n os._exit(1)", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def connect_port(self, port_index, data):\n \"\"\"Connect a port to a data location.\n\n This may be called regardless of whether the plugin is activated,\n activation and deactivation does not destroy port connections.\n \"\"\"\n import numpy\n\n if data is None:\n self.get_descriptor().connect_port(\n self.get_handle(), port_index, data\n )\n elif type(data) == numpy.ndarray:\n self.get_descriptor().connect_port(\n self.get_handle(),\n port_index,\n data.ctypes.data_as(POINTER(c_float)),\n )\n else:\n raise Exception(\"Unsupported data type\")", "smellKey": "S112", "smellId": null, "repo": "uajithkumar_audacity", "language": "python"} {"function": "def create_string_from_largest_unit_in_timedelta(\n timedelta_obj: datetime.timedelta\n) -> str:\n \"\"\"Given the timedelta object, find the largest nonzero time unit and\n return that value, along with the time unit, as a human readable string.\n The returned string is not localized.\n\n Args:\n timedelta_obj: datetime.timedelta. A datetime timedelta object. Datetime\n timedelta objects are created when you subtract two datetime\n objects.\n\n Returns:\n str. A human readable string representing the value of the largest\n nonzero time unit, along with the time units. If the largest time unit\n is seconds, 1 minute is returned. The value is represented as an integer\n in the string.\n\n Raises:\n Exception. If the provided timedelta is not positive.\n \"\"\"\n total_seconds = timedelta_obj.total_seconds()\n if total_seconds <= 0:\n raise Exception(\n 'Expected a positive timedelta, received: %s.' % total_seconds)\n if timedelta_obj.days != 0:\n return '%s day%s' % (\n int(timedelta_obj.days), 's' if timedelta_obj.days > 1 else '')\n else:\n number_of_hours, remainder = divmod(total_seconds, SECONDS_IN_HOUR)\n number_of_minutes, _ = divmod(remainder, SECONDS_IN_MINUTE)\n if number_of_hours != 0:\n return '%s hour%s' % (\n int(number_of_hours), 's' if number_of_hours > 1 else '')\n elif number_of_minutes > 1:\n return '%s minutes' % int(number_of_minutes)\n # Round any seconds up to one minute.\n else:\n return '1 minute'", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@staticmethod\n def _set_call_to_action(channel, payload):\n # register for get_started events\n url = \"https://graph.facebook.com/v14.0/%s/thread_settings\" % channel.address\n body = {\"setting_type\": \"call_to_actions\", \"thread_state\": \"new_thread\", \"call_to_actions\": []}\n\n # if we have a payload, set it, otherwise, clear it\n if payload:\n body[\"call_to_actions\"].append({\"payload\": payload})\n\n access_token = channel.config[Channel.CONFIG_AUTH_TOKEN]\n\n response = requests.post(\n url, json=body, params={\"access_token\": access_token}, headers={\"Content-Type\": \"application/json\"}\n )\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Unable to update call to action: %s\" % response.text)", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def check_public_method_exists(documented_methods_map):\n \"\"\"Check that all explicitly documented public methods are defined in the corresponding class.\"\"\"\n failures = []\n for obj, methods in documented_methods_map.items():\n # Let's ensure there is no repetition\n if len(set(methods)) != len(methods):\n failures.append(f\"Error in the documentation of {obj}: there are repeated documented methods.\")\n\n # Navigates into the object, given the full import path\n nested_path = obj.split(\".\")\n submodule = transformers\n if len(nested_path) > 1:\n nested_submodules = nested_path[:-1]\n for submodule_name in nested_submodules:\n if submodule_name == \"transformers\":\n continue\n\n try:\n submodule = getattr(submodule, submodule_name)\n except AttributeError:\n failures.append(f\"Could not parse {submodule_name}. Are the required dependencies installed?\")\n continue\n\n class_name = nested_path[-1]\n\n try:\n obj_class = getattr(submodule, class_name)\n except AttributeError:\n failures.append(f\"Could not parse {submodule_name}. Are the required dependencies installed?\")\n continue\n\n # Checks that all explicitly documented methods are defined in the class\n for method in methods:\n if method == \"all\": # Special keyword to document all public methods\n continue\n try:\n if not hasattr(obj_class, method):\n failures.append(\n \"The following public method is explicitly documented but not defined in the corresponding \"\n f\"class. class: {obj}, method: {method}. If the method is defined, this error can be due to \"\n f\"lacking dependencies.\"\n )\n except ImportError:\n pass\n\n if len(failures) > 0:\n raise Exception(\"\\n\".join(failures))", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, stanza: str) -> None:\n \"\"\"Initialize the object which provides relevant data of a lcov\n stanza in order to calculate any decrease in frontend test coverage.\n\n Args:\n stanza: list(str). Contains all the lines from a lcov stanza.\n\n Raises:\n Exception. The file_path is empty.\n Exception. Total lines number is not found.\n Exception. Covered lines number is not found.\n \"\"\"\n\n match = re.search('SF:(.+)\\n', stanza)\n if match is None:\n raise Exception(\n 'The test path is empty or null. '\n 'It\\'s not possible to diff the test coverage correctly.')\n _, file_name = os.path.split(match.group(1))\n self.file_name = file_name\n self.file_path = match.group(1)\n\n match = re.search(r'LF:(\\d+)\\n', stanza)\n if match is None:\n raise Exception(\n 'It wasn\\'t possible to get the total lines of {} file.'\n 'It\\'s not possible to diff the test coverage correctly.'\n .format(file_name))\n self.total_lines = int(match.group(1))\n\n match = re.search(r'LH:(\\d+)\\n', stanza)\n if match is None:\n raise Exception(\n 'It wasn\\'t possible to get the covered lines of {} file.'\n 'It\\'s not possible to diff the test coverage correctly.'\n .format(file_name))\n self.covered_lines = int(match.group(1))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def classify_class_attrs(cls):\n \"\"\"Return list of attribute-descriptor tuples.\n\n For each name in dir(cls), the return list contains a 4-tuple\n with these elements:\n\n 0. The name (a string).\n\n 1. The kind of attribute this is, one of these strings:\n 'class method' created via classmethod()\n 'static method' created via staticmethod()\n 'property' created via property()\n 'method' any other flavor of method or descriptor\n 'data' not a method\n\n 2. The class which defined this attribute (a class).\n\n 3. The object as obtained by calling getattr; if this fails, or if the\n resulting object does not live anywhere in the class' mro (including\n metaclasses) then the object is looked up in the defining class's\n dict (found by walking the mro).\n\n If one of the items in dir(cls) is stored in the metaclass it will now\n be discovered and not have None be listed as the class in which it was\n defined. Any items whose home class cannot be discovered are skipped.\n \"\"\"\n\n mro = getmro(cls)\n metamro = getmro(type(cls)) # for attributes stored in the metaclass\n metamro = tuple(cls for cls in metamro if cls not in (type, object))\n class_bases = (cls,) + mro\n all_bases = class_bases + metamro\n names = dir(cls)\n # :dd any DynamicClassAttributes to the list of names;\n # this may result in duplicate entries if, for example, a virtual\n # attribute with the same name as a DynamicClassAttribute exists.\n for base in mro:\n for k, v in base.__dict__.items():\n if isinstance(v, types.DynamicClassAttribute) and v.fget is not None:\n names.append(k)\n result = []\n processed = set()\n\n for name in names:\n # Get the object associated with the name, and where it was defined.\n # Normal objects will be looked up with both getattr and directly in\n # its class' dict (in case getattr fails [bug #1785], and also to look\n # for a docstring).\n # For DynamicClassAttributes on the second pass we only look in the\n # class's dict.\n #\n # Getting an obj from the __dict__ sometimes reveals more than\n # using getattr. Static and class methods are dramatic examples.\n homecls = None\n get_obj = None\n dict_obj = None\n if name not in processed:\n try:\n if name == '__dict__':\n raise Exception(\"__dict__ is special, don't want the proxy\")\n get_obj = getattr(cls, name)\n except Exception:\n pass\n else:\n homecls = getattr(get_obj, \"__objclass__\", homecls)\n if homecls not in class_bases:\n # if the resulting object does not live somewhere in the\n # mro, drop it and search the mro manually\n homecls = None\n last_cls = None\n # first look in the classes\n for srch_cls in class_bases:\n srch_obj = getattr(srch_cls, name, None)\n if srch_obj is get_obj:\n last_cls = srch_cls\n # then check the metaclasses\n for srch_cls in metamro:\n try:\n srch_obj = srch_cls.__getattr__(cls, name)\n except AttributeError:\n continue\n if srch_obj is get_obj:\n last_cls = srch_cls\n if last_cls is not None:\n homecls = last_cls\n for base in all_bases:\n if name in base.__dict__:\n dict_obj = base.__dict__[name]\n if homecls not in metamro:\n homecls = base\n break\n if homecls is None:\n # unable to locate the attribute anywhere, most likely due to\n # buggy custom __dir__; discard and move on\n continue\n obj = get_obj if get_obj is not None else dict_obj\n # Classify the object or its descriptor.\n if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):\n kind = \"static method\"\n obj = dict_obj\n elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):\n kind = \"class method\"\n obj = dict_obj\n elif isinstance(dict_obj, property):\n kind = \"property\"\n obj = dict_obj\n elif isroutine(obj):\n kind = \"method\"\n else:\n kind = \"data\"\n result.append(Attribute(name, kind, homecls, obj))\n processed.add(name)\n return result", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def enable_entity(entity, request):\n # get entity admin\n try:\n right_request = UserRightsRequests.objects.get(entity=entity, role=UserRightsRequests.ADMIN, status=\"PENDING\")\n except Exception:\n raise Exception(\"Cette soci\u00e9t\u00e9 n'a pas de demande d'inscription en attente\")\n\n admin_user = right_request.user\n # valid admin rights request\n right_request.status = \"ACCEPTED\"\n right_request.save()\n\n # create user right\n UserRights.objects.create(\n entity=right_request.entity,\n user=right_request.user,\n role=right_request.role,\n expiration_date=right_request.expiration_date,\n )\n\n entity.is_enabled = True\n entity.save()\n\n # send email to user\n subject = \"Demande d'inscription de soci\u00e9t\u00e9 valid\u00e9e\"\n subject = subject if CarbureEnv.is_prod else \"TEST \" + subject\n recipient_list = [admin_user.email] if CarbureEnv.is_prod else [\"carbure@beta.gouv.fr\"]\n text_message = f\"\"\"\n Bonjour,\n\n Votre demande d'inscription pour la soci\u00e9t\u00e9 {entity.name} a \u00e9t\u00e9 valid\u00e9e par l'administration.\n Vous pouvez d\u00e9sormais acc\u00e9der \u00e0 la soci\u00e9t\u00e9 dans votre espace en tant qu'administrateur : {CarbureEnv.get_base_url()}/account\n\n Pour plus d'information veuillez consulter notre guide d'utilisation : https://carbure-1.gitbook.io/faq/affichage/traduction\n\n Bien cordialement,\n L'\u00e9quipe CarbuRe\n \"\"\" # noqa: E501\n\n send_mail(\n request=request,\n subject=subject,\n message=text_message,\n from_email=settings.DEFAULT_FROM_EMAIL,\n recipient_list=recipient_list,\n )", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "async def detect_process(self, headers=None):\n async def fetch_status(url: str, timeout: float, headers=None):\n code = None\n text = None\n start = default_timer()\n async with ClientSession(timeout=ClientTimeout(total=3.0)) as session:\n while default_timer() - start < timeout:\n try:\n async with session.get(url, headers=headers) as resp:\n code = resp.status\n if code == 200:\n text = await resp.text()\n break\n except (ClientError, asyncio.TimeoutError):\n pass\n await asyncio.sleep(0.5)\n return code, text\n\n status_url = self.admin_url + \"/status\"\n status_code, status_text = await fetch_status(\n status_url, START_TIMEOUT, headers=headers\n )\n\n if not status_text:\n raise Exception(\n f\"Timed out waiting for agent process to start (status={status_code}). \"\n + f\"Admin URL: {status_url}\"\n )\n ok = False\n try:\n status = json.loads(status_text)\n ok = isinstance(status, dict) and \"version\" in status\n except json.JSONDecodeError:\n pass\n if not ok:\n raise Exception(\n f\"Unexpected response from agent process. Admin URL: {status_url}\"\n )", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def CreateParaviewItemsForImagesetC(inImageset):\n \"given a json block structure as discussed in the catalyst sierra\\n insitu wiki, create the corresponding one imageset (view) based on\\n a particular imageset block and the availa\"\n\n theCamera = inImageset.mCamera\n\n #we are setting this up, for now, so that you MUST have a camera at this\n #point--default should have been added and referenced earlier\n if theCamera == None:\n errStr = 'error! theCamera is None in \"\\\n \"CreateParaviewItemsForImagesetC\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n cameraLookDirectionAndFilenameAddonList = GetLookDirectionListFromCamera(theCamera)\n\n #counter = 0\n for oneItem in cameraLookDirectionAndFilenameAddonList:\n #print oneItem\n oneDirection = oneItem[0]\n oneDirectionFilenameAddon = oneItem[1]\n CreateParaViewRepresentationAndViewFromInfoC(inImageset, oneDirection,\n oneDirectionFilenameAddon)\n #counter = counter + 1", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _manage_acl(self, node, method, acl=None, user=None):\n url = self.shock_url + \"/node/\" + node + \"/acl\"\n if acl and user:\n url += \"/\" + acl + \"?users=\" + urllib.quote(user)\n try:\n if method == \"get\":\n req = requests.get(url, headers=self.auth_header)\n elif method == \"put\":\n req = requests.put(url, headers=self.auth_header)\n elif method == \"delete\":\n req = requests.delete(url, headers=self.auth_header)\n except Exception as ex:\n message = self.template.format(type(ex).__name__, ex.args)\n raise Exception(f\"Unable to connect to Shock server {url}\\n{message}\") from ex\n if not (req.ok and req.text):\n raise Exception(f\"Unable to connect to Shock server {url}\\n{req.raise_for_status()}\")\n rj = req.json()\n if not (\n rj and isinstance(rj, dict) and all(key in rj for key in [\"status\", \"data\", \"error\"])\n ):\n raise Exception(\"Return data not valid Shock format\")\n if rj[\"error\"]:\n raise Exception(f\"Shock error {rj['status']} : {rj['error'][0]}\")\n return rj[\"data\"]", "smellKey": "S112", "smellId": null, "repo": "kbase_narrative", "language": "python"} {"function": "def filter_forward(items, *, markpublic=False):\n if markpublic:\n public = set()\n actual = []\n for item in items:\n if is_public_api(item):\n public.add(item.id)\n elif not _match.is_forward_decl(item):\n actual.append(item)\n else:\n # non-public duplicate!\n # XXX\n raise Exception(item)\n for item in actual:\n _info.set_flag(item, 'is_public', item.id in public)\n yield item\n else:\n for item in items:\n if _match.is_forward_decl(item):\n continue\n yield item", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def _get_activity_rights(\n activity_type: str, activity_id: str, strict: bool = False\n) -> Optional[rights_domain.ActivityRights]:\n \"\"\"Retrieves the rights object for the given activity\n based on its type.\n\n Args:\n activity_type: str. The type of activity. Possible values:\n constants.ACTIVITY_TYPE_EXPLORATION,\n constants.ACTIVITY_TYPE_COLLECTION.\n activity_id: str. ID of the activity.\n strict: bool. Whether to fail noisily if the activity_rights\n doesn't exist for the given activity_id.\n\n Returns:\n ActivityRights|None. The rights object associated with the given\n activity, or None if no rights object exists.\n\n Raises:\n Exception. The activity_type provided is unknown.\n \"\"\"\n if activity_type == constants.ACTIVITY_TYPE_EXPLORATION:\n activity_rights = get_exploration_rights(activity_id, strict=strict)\n elif activity_type == constants.ACTIVITY_TYPE_COLLECTION:\n activity_rights = get_collection_rights(activity_id, strict=strict)\n else:\n raise Exception(\n 'Cannot get activity rights for unknown activity type: %s' % (\n activity_type))\n return activity_rights", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def generate_new_thread_id(cls, entity_type: str, entity_id: str) -> str:\n \"\"\"Generates a new thread ID which is unique.\n\n Args:\n entity_type: str. The type of the entity.\n entity_id: str. The ID of the entity.\n\n Returns:\n str. A thread ID that is different from the IDs of all\n the existing threads within the given entity.\n\n Raises:\n Exception. There were too many collisions with existing thread IDs\n when attempting to generate a new thread ID.\n \"\"\"\n for _ in range(_MAX_RETRIES):\n thread_id = (\n '%s.%s.%s%s' % (\n entity_type,\n entity_id,\n utils.base64_from_int(\n int(utils.get_current_time_in_millisecs())),\n utils.base64_from_int(utils.get_random_int(_RAND_RANGE))\n )\n )\n if not cls.get_by_id(thread_id):\n return thread_id\n raise Exception(\n 'New thread id generator is producing too many collisions.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_user_information(token):\n \"\"\"\n Get a user's information from Pennsieve.\n \"\"\"\n\n\n headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {token}\",\n }\n\n try:\n r = requests.get(f\"{PENNSIEVE_URL}/user\", headers=headers) \n r.raise_for_status() \n return r.json()\n except Exception as e:\n raise Exception(e) from e", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def deassign_user_from_all_topics(\n committer: user_domain.UserActionsInfo, user_id: str\n) -> None:\n \"\"\"Deassigns given user from all topics assigned to them.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user\n who is performing the action.\n user_id: str. The ID of the user.\n\n Raises:\n Exception. The committer does not have rights to modify a role.\n Exception. Guest users are not allowed to deassing users from\n all topics.\n \"\"\"\n topic_rights_list = topic_fetchers.get_topic_rights_with_user(user_id)\n if committer.user_id is None:\n raise Exception(\n 'Guest users are not allowed to deassing users from all topics.'\n )\n for topic_rights in topic_rights_list:\n topic_rights.manager_ids.remove(user_id)\n commit_cmds = [topic_domain.TopicRightsChange({\n 'cmd': topic_domain.CMD_REMOVE_MANAGER_ROLE,\n 'removed_user_id': user_id\n })]\n save_topic_rights(\n topic_rights, committer.user_id,\n 'Removed all assigned topics from %s' % (\n user_services.get_username(user_id)\n ),\n commit_cmds\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@staticmethod\n def downloadTemplate(uuid, secPath):\n secMountPoint = None\n try:\n logger.debug(OvmStoragePool.downloadTemplate, \"download %s to pool %s\"%(secPath, uuid))\n try:\n tmpUuid = get_uuid()\n secMountPoint = join(\"/var/cloud/\", tmpUuid)\n if not exists(secMountPoint):\n os.makedirs(secMountPoint)\n\n templateFile = None\n if secPath.endswith(\"raw\"):\n secPathDir = os.path.dirname(secPath)\n templateFile = os.path.basename(secPath)\n else:\n secPathDir = secPath\n\n # mount as read-only\n mountCmd = ['mount.nfs', secPathDir, secMountPoint, '-r']\n doCmd(mountCmd)\n\n if not templateFile:\n for f in os.listdir(secMountPoint):\n if isfile(join(secMountPoint, f)) and f.endswith('raw'):\n templateFile = f\n break\n\n if not templateFile:\n raise Exception(\"Can not find raw template in secondary storage\")\n templateSecPath = join(secMountPoint, templateFile)\n\n sr = OvmStoragePool()._getSrByNameLable(uuid)\n priStorageMountPoint = sr.mountpoint\n # Although mgmt server will check the size, we check again for safety\n OvmStoragePool()._checkDirSizeForImage(priStorageMountPoint, templateSecPath)\n seedDir = join(priStorageMountPoint, 'seed_pool', tmpUuid)\n if exists(seedDir):\n raise Exception(\"%s already here, cannot override existing template\" % seedDir)\n os.makedirs(seedDir)\n\n tgt = join(seedDir, templateFile)\n cpTemplateCmd = ['cp', templateSecPath, tgt]\n logger.info(OvmStoragePool.downloadTemplate, \" \".join(cpTemplateCmd))\n doCmd(cpTemplateCmd)\n templateSize = os.path.getsize(tgt)\n logger.info(OvmStoragePool.downloadTemplate, \"primary_storage_download success:installPath:%s, templateSize:%s\"%(tgt,templateSize))\n rs = toGson({\"installPath\":tgt, \"templateSize\":templateSize})\n return rs\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmStoragePool.downloadTemplate, errmsg)\n raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.downloadTemplate), errmsg)\n finally:\n if exists(secMountPoint):\n try:\n OvmStoragePool()._umount(secMountPoint)\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmStoragePool.downloadTemplate, 'unmount secondary storage at %s failed, %s'%(secMountPoint, errmsg))", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "@staticmethod\n def __class_getitem__(datatype):\n \"\"\"\n Returns the number of bytes in size the data type is. Raises an exception if the data type\n is either less than a full byte or a non-integer number of bytes in size.\n\n :param datatype: data type to query\n\n :return: number of bytes the data type occupies\n :rtype: int\n \"\"\"\n bits = DataTypeSize[datatype]\n if bits < 8:\n raise Exception(\n \"Data type {} is less than one byte in size.\".format(datatype)\n )\n elif bits % 8 != 0:\n raise Exception(\n \"Data type {} is not an integer number of bytes.\".format(datatype)\n )\n return bits // 8", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def test_no_eof(self):\n # __exit__() must not write end-of-archive blocks if an\n # exception was raised.\n try:\n with tarfile.open(tmpname, \"w\") as tar:\n raise Exception\n except:\n pass\n self.assertEqual(os.path.getsize(tmpname), 0,\n \"context manager wrote an end-of-archive block\")\n self.assertTrue(tar.closed, \"context manager failed\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_supported_audio_language_description(language_code: str) -> str:\n \"\"\"Returns the language description for the given language code.\n\n Args:\n language_code: str. The language code for which the description is\n required.\n\n Returns:\n str. The language description for the given language code.\n\n Raises:\n Exception. If the given language code is unsupported.\n \"\"\"\n for language in constants.SUPPORTED_AUDIO_LANGUAGES:\n if language['id'] == language_code:\n description: str = language['description']\n return description\n raise Exception('Unsupported audio language code: %s' % language_code)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def publish_story(\n topic_id: str,\n story_id: str,\n committer_id: str\n) -> None:\n \"\"\"Marks the given story as published.\n\n Args:\n topic_id: str. The id of the topic.\n story_id: str. The id of the given story.\n committer_id: str. ID of the committer.\n\n Raises:\n Exception. The given story does not exist.\n Exception. The story is already published.\n Exception. The user does not have enough rights to publish the story.\n \"\"\"\n def _are_nodes_valid_for_publishing(\n story_nodes: List[story_domain.StoryNode]\n ) -> None:\n \"\"\"Validates the story nodes before publishing.\n\n Args:\n story_nodes: list(dict(str, *)). The list of story nodes dicts.\n\n Raises:\n Exception. The exploration id is invalid or corresponds to an\n exploration which isn't published yet.\n \"\"\"\n exploration_id_list = []\n for node in story_nodes:\n assert node.exploration_id is not None\n exploration_id_list.append(node.exploration_id)\n story_services.validate_explorations_for_story(\n exploration_id_list, True)\n\n topic = topic_fetchers.get_topic_by_id(topic_id, strict=True)\n user = user_services.get_user_actions_info(committer_id)\n if role_services.ACTION_CHANGE_STORY_STATUS not in user.actions:\n raise Exception(\n 'The user does not have enough rights to publish the story.')\n\n story = story_fetchers.get_story_by_id(story_id, strict=False)\n if story is None:\n raise Exception('A story with the given ID doesn\\'t exist')\n for node in story.story_contents.nodes:\n if node.id == story.story_contents.initial_node_id:\n _are_nodes_valid_for_publishing([node])\n\n serial_chapter_curriculum_admin_view_feature_is_enabled = (\n feature_flag_services.is_feature_flag_enabled(\n feature_flag_list.FeatureNames\n .SERIAL_CHAPTER_LAUNCH_CURRICULUM_ADMIN_VIEW.value,\n None)\n )\n if not serial_chapter_curriculum_admin_view_feature_is_enabled:\n chapters_change_list = []\n for node in story.story_contents.nodes:\n chapters_change_list.append(story_domain.StoryChange({\n 'cmd': story_domain.CMD_UPDATE_STORY_NODE_PROPERTY,\n 'node_id': node.id,\n 'property_name': (\n story_domain.STORY_NODE_PROPERTY_STATUS),\n 'old_value': node.status,\n 'new_value': constants.STORY_NODE_STATUS_PUBLISHED\n }))\n\n if chapters_change_list:\n update_story_and_topic_summary(\n committer_id, story_id, chapters_change_list,\n 'Published the story.', topic.id)\n\n topic.publish_story(story_id)\n change_list = [topic_domain.TopicChange({\n 'cmd': topic_domain.CMD_PUBLISH_STORY,\n 'story_id': story_id\n })]\n _save_topic(\n committer_id, topic, 'Published story with id %s' % story_id,\n change_list)\n generate_topic_summary(topic.id)\n # Create exploration opportunities corresponding to the story and linked\n # explorations.\n linked_exp_ids = story.story_contents.get_all_linked_exp_ids()\n opportunity_services.add_new_exploration_opportunities(\n story_id, linked_exp_ids)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def update_subtopic_thumbnail_filename(\n topic: topic_domain.Topic,\n subtopic_id: int,\n new_thumbnail_filename: str\n) -> None:\n \"\"\"Updates the thumbnail filename and file size in a subtopic.\n\n Args:\n topic: topic_domain.Topic. The topic domain object containing\n the subtopic whose thumbnail is to be updated.\n subtopic_id: int. The id of the subtopic to edit.\n new_thumbnail_filename: str. The new thumbnail filename for the\n subtopic.\n\n Raises:\n Exception. The thumbnail does not exist for expected topic in\n the filesystem.\n \"\"\"\n fs = fs_services.GcsFileSystem(feconf.ENTITY_TYPE_TOPIC, topic.id)\n filepath = '%s/%s' % (\n constants.ASSET_TYPE_THUMBNAIL, new_thumbnail_filename)\n if fs.isfile(filepath):\n thumbnail_size_in_bytes = len(fs.get(filepath))\n topic.update_subtopic_thumbnail_filename_and_size(\n subtopic_id, new_thumbnail_filename, thumbnail_size_in_bytes)\n else:\n raise Exception(\n 'The thumbnail %s for subtopic with topic_id %s does not exist'\n ' in the filesystem.' % (new_thumbnail_filename, topic.id))", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(\n self,\n operation: \"Conv2dOperation\",\n seed: int = 2080,\n interleaved=False,\n verification=True,\n profiling=False,\n warmup_iterations=500,\n iterations=500,\n compilation_mode=\"nvcc\",\n **kwargs,\n ) -> None:\n self.enable_cached_results = True\n self.interleaved = interleaved\n\n # create the reduction kernel\n self.reduction_operation = ReductionOperation(\n shape=cutlass_bindings.MatrixCoord(4, 32 * operation.C.alignment),\n C=operation.C,\n element_accumulator=operation.tile_description.math_instruction.element_accumulator,\n element_compute=operation.epilogue_functor.element_epilogue,\n epilogue_functor=operation.epilogue_functor,\n count=operation.C.alignment,\n )\n\n #: verify the output result\n self.verification = verification\n #: profile the kernel's runtime\n self.profiling = profiling\n\n self.timer = GpuTimer()\n\n self.warmup_iterations = warmup_iterations\n self.iterations = iterations\n\n if \"sleep\" in kwargs.keys():\n self.sleep_time = kwargs[\"sleep\"]\n else:\n self.sleep_time = 0\n\n #\n # Compile the operator\n #\n\n if compilation_mode == \"nvcc\":\n compiler.nvcc()\n elif compilation_mode == \"nvrtc\":\n compiler.nvrtc()\n else:\n raise Exception(f\"Unexpected compilation mode {compilation_mode}\")\n\n compiler.add_module([operation, self.reduction_operation])\n\n self.operation = operation\n\n self.dtype_A = Conv2dLauncher.numpy_type(operation.A.element)\n self.layout_A = operation.A.layout\n self.dtype_B = Conv2dLauncher.numpy_type(operation.B.element)\n self.layout_B = operation.B.layout\n self.dtype_C = Conv2dLauncher.numpy_type(operation.C.element)\n self.layout_C = operation.C.layout\n self.dtype_D = Conv2dLauncher.numpy_type(operation.C.element)\n self.layout_D = operation.C.layout\n\n accumulator_size = DataTypeSize[\n operation.tile_description.math_instruction.element_accumulator\n ]\n element_size = DataTypeSize[operation.A.element]\n\n if element_size <= 8:\n self.randomization_max = 1\n elif element_size == 16:\n if accumulator_size <= 16:\n self.randomization_max = 2\n else:\n self.randomization_max = 4\n else:\n self.randomization_max = 7\n\n # Seed\n self.seed = seed\n\n self.conv_kind = operation.conv_kind\n\n #\n # Get the host reference function\n #\n\n self.element_compute = operation.epilogue_functor.element_epilogue\n\n self.host_conv2d = cutlass_bindings.test.conv.host.conv2d\n\n self.timer = GpuTimer()", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def testError(self):\n raise Exception('error')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@staticmethod\n def detachOrAttachIso(vmName, iso, isAttach):\n try:\n if vmName in OvmHost.getAllVms():\n scope = 'both'\n vmPath = OvmHost()._vmNameToPath(vmName)\n else:\n scope = 'cfg'\n vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)\n\n vmType = OvmVm()._getVmTypeFromConfigFile(vmPath)\n if vmType != 'HVM':\n raise Exception(\"Only HVM supports attaching/detaching ISO\")\n\n if not isAttach:\n iso = ''\n else:\n isoName = basename(iso)\n isoMountPoint = OvmVm()._getIsoMountPath(vmPath)\n isoOnSecStorage = dirname(iso)\n OvmStoragePool()._mount(isoOnSecStorage, isoMountPoint)\n iso = join(isoMountPoint, isoName)\n\n exceptionIfNoSuccess(xen_change_vm_cdrom(vmPath, iso, scope))\n return SUCC()\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmVm.detachOrAttachIso, errmsg)\n raise XmlRpcFault(toErrCode(OvmVm, OvmVm.detachOrAttachIso), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def create_test_suites(\n test_target: Optional[str] = None\n) -> List[unittest.TestSuite]:\n \"\"\"Creates test suites. If test_target is None, runs all tests.\n\n Args:\n test_target: str. The name of the test script.\n Default to None if not specified.\n\n Returns:\n list. A list of tests within the test script.\n\n Raises:\n Exception. The delimeter in the test_target should be a dot (.)\n \"\"\"\n\n if test_target and '/' in test_target:\n raise Exception('The delimiter in test_target should be a dot (.)')\n\n loader = unittest.TestLoader()\n master_test_suite = (\n loader.loadTestsFromName(test_target)\n if test_target else\n loader.discover(\n CURR_DIR,\n pattern='[^core/tests/data]*_test.py',\n top_level_dir=CURR_DIR\n )\n )\n return [master_test_suite]", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@column_condition_partial(engine=PandasExecutionEngine)\n def _pandas(cls, column, **kwargs): # noqa: C901 - 24\n column_shape_format = kwargs.get(\"column_shape_format\")\n place = kwargs.get(\"place\")\n geocoder = kwargs.get(\"geocoder\")\n geocoder_config = kwargs.get(\"geocoder_config\")\n min_value = kwargs.get(\"min_value\")\n max_value = kwargs.get(\"max_value\")\n strict_min = kwargs.get(\"strict_min\")\n strict_max = kwargs.get(\"strict_max\")\n units = kwargs.get(\"units\")\n\n if min_value is None and max_value is None:\n raise ValueError(\"min_value and max_value cannot both be None\") # noqa: TRY003\n if min_value is not None and max_value is not None and min_value > max_value:\n raise ValueError(\"min_value cannot be greater than max_value\") # noqa: TRY003\n\n if geocoder not in [\"nominatim\", \"pickpoint\", \"openmapquest\"]:\n raise NotImplementedError(\"The geocoder is not implemented for this method.\")\n\n # find the reference shape with the geocoder.\n if geocoder is not None:\n try:\n # Specify the default parameters for Nominatim and run query. User is responsible for config and query params otherwise.\n query_params = dict(exactly_one=True, geometry=\"wkt\")\n location = cls.geocode(geocoder, geocoder_config, place, query_params)\n except Exception:\n raise Exception( # noqa: TRY002, TRY003\n \"Geocoding configuration and query failed to produce a valid result.\"\n )\n else:\n raise Exception( # noqa: TRY002, TRY003\n \"A valid geocoder must be provided for this method. See GeoPy for reference.\"\n )\n\n # Load the column into a pygeos Geometry vector from numpy array (Series not supported).\n if column_shape_format == \"wkt\":\n shape_test = geos.from_wkt(column.to_numpy(), on_invalid=\"ignore\")\n elif column_shape_format == \"wkb\":\n shape_test = geos.from_wkb(column.to_numpy(), on_invalid=\"ignore\")\n elif column_shape_format == \"lonlat\":\n shape_df = pd.DataFrame(column.to_list(), columns=(\"lon\", \"lat\"))\n shape_test = geos.points(shape_df.lon, y=shape_df.lat)\n elif column_shape_format == \"latlon\":\n shape_df = pd.DataFrame(column.to_list(), columns=(\"lat\", \"lon\"))\n shape_test = geos.points(shape_df.lon, y=shape_df.lat)\n else:\n raise NotImplementedError(\"Column values shape format not implemented.\")\n\n # verify that all shapes are points and if not, convert to centroid point.\n points_test = pd.Series(shape_test)\n if not points_test.apply(lambda x: geos.get_type_id(x) == 0).all():\n points_test = points_test.map(geos.centroid)\n\n # convert the geos point to a geopy point.\n points_test = points_test.apply(lambda x: lonlat(geos.get_x(x), geos.get_y(x)))\n\n if location is None:\n raise Exception(\"Geocoding failed to return a result.\") # noqa: TRY002, TRY003\n else:\n point_ref = lonlat(location.longitude, location.latitude)\n\n # calculate the distance between the points using geopy\n if units in [\"km\", \"kilometers\", \"kilometres\", \"kilometer\", \"kilometre\"]:\n column_dist = points_test.apply(lambda p: distance(p, point_ref).km)\n elif units in [\"m\", \"meters\", \"metres\", \"meter\", \"metre\"]:\n column_dist = points_test.apply(lambda p: distance(p, point_ref).m)\n elif units in [\"mi\", \"miles\", \"mile\"]:\n column_dist = points_test.apply(lambda p: distance(p, point_ref).mi)\n elif units in [\"ft\", \"feet\", \"foot\"]:\n column_dist = points_test.apply(lambda p: distance(p, point_ref).ft)\n else:\n raise NotImplementedError(\n \"Unit conversion has not yet been implemented. Please use one of km, m, mi, ft\"\n )\n\n # Evaluate the between statement (from column_values_between.py)\n if min_value is None:\n if strict_max:\n return column_dist < max_value\n else:\n return column_dist <= max_value\n\n elif max_value is None:\n if strict_min:\n return min_value < column_dist\n else:\n return min_value <= column_dist\n\n else:\n if strict_min and strict_max:\n return (min_value < column_dist) & (column_dist < max_value)\n elif strict_min:\n return (min_value < column_dist) & (column_dist <= max_value)\n elif strict_max:\n return (min_value <= column_dist) & (column_dist < max_value)\n else:\n return (min_value <= column_dist) & (column_dist <= max_value)", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "@staticmethod\n def variant_from_dbus(val):\n if isinstance(val, (dbus.String, str)):\n return GLib.Variant(\"s\", str(val))\n if isinstance(val, dbus.UInt32):\n return GLib.Variant(\"u\", int(val))\n if isinstance(val, dbus.UInt64):\n return GLib.Variant(\"t\", int(val))\n if isinstance(val, dbus.Int32):\n return GLib.Variant(\"i\", int(val))\n if isinstance(val, dbus.Boolean):\n return GLib.Variant(\"b\", bool(val))\n if isinstance(val, dbus.Byte):\n return GLib.Variant(\"y\", int(val))\n if isinstance(val, dbus.Array):\n try:\n if val.signature == \"s\":\n return GLib.Variant(\"as\", [str(x) for x in val])\n if val.signature == \"b\":\n return GLib.Variant(\"ab\", [bool(x) for x in val])\n if val.signature == \"y\":\n return GLib.Variant(\"ay\", [int(x) for x in val])\n if val.signature == \"u\":\n return GLib.Variant(\"au\", [int(x) for x in val])\n if val.signature == \"ay\":\n return GLib.Variant(\"aay\", [Util.variant_from_dbus(x) for x in val])\n if val.signature == \"au\":\n return GLib.Variant(\"aau\", [Util.variant_from_dbus(x) for x in val])\n if val.signature == \"a{sv}\":\n return GLib.Variant(\n \"aa{sv}\",\n [\n collections.OrderedDict(\n [\n (str(k), Util.variant_from_dbus(v))\n for k, v in addr.items()\n ]\n )\n for addr in val\n ],\n )\n if val.signature == \"(ayuay)\":\n return GLib.Variant(\n \"a(ayuay)\", [Util.variant_from_dbus(x) for x in val]\n )\n if val.signature == \"(ayuayu)\":\n return GLib.Variant(\n \"a(ayuayu)\", [Util.variant_from_dbus(x) for x in val]\n )\n except Exception as e:\n raise Exception(\n \"Cannot convert array element to type '%s': %s\" % (val.signature, e)\n )\n if isinstance(val, dbus.Dictionary):\n if val.signature == \"ss\":\n return GLib.Variant(\n \"a{ss}\",\n collections.OrderedDict([(str(k), str(v)) for k, v in val.items()]),\n )\n if val.signature == \"sv\":\n return GLib.Variant(\n \"a{sv}\",\n collections.OrderedDict(\n [(str(k), Util.variant_from_dbus(v)) for k, v in val.items()]\n ),\n )\n if val.signature == \"sa{sv}\" or val.signature == \"sa{ss}\":\n c = collections.OrderedDict(\n [\n (\n str(key1),\n collections.OrderedDict(\n [\n (str(key2), Util.variant_from_dbus(arr2))\n for key2, arr2 in arr1.items()\n ]\n ),\n )\n for key1, arr1 in val.items()\n ]\n )\n return GLib.Variant(\"a{sa{sv}}\", c)\n\n raise Exception(\"Unsupported type for value '%s'\" % (repr(val)))", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "def convert_extent(self, clob):\n if clob:\n # Generally, Oracle returns a polygon for the extent -- however,\n # it can return a single point if there's only one Point in the\n # table.\n ext_geom = GEOSGeometry(memoryview(clob.read()))\n gtype = str(ext_geom.geom_type)\n if gtype == \"Polygon\":\n # Construct the 4-tuple from the coordinates in the polygon.\n shell = ext_geom.shell\n ll, ur = shell[0][:2], shell[2][:2]\n elif gtype == \"Point\":\n ll = ext_geom.coords[:2]\n ur = ll\n else:\n raise Exception(\n \"Unexpected geometry type returned for extent: %s\" % gtype\n )\n xmin, ymin = ll\n xmax, ymax = ur\n return (xmin, ymin, xmax, ymax)\n else:\n return None", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_user(self) -> Optional[UserInformation]:\n info = self.__get(\"/simple_login/v1/subscription\")[\"Subscription\"]\n if not info[\"IsAllowed\"]:\n LOG.debug(\"Account is not allowed to log into SL\")\n return None\n\n plan_value = info[\"Plan\"]\n if plan_value == PLAN_FREE:\n plan = SLPlan(type=SLPlanType.Free, expiration=None)\n elif plan_value == PLAN_PREMIUM:\n plan = SLPlan(\n type=SLPlanType.Premium,\n expiration=Arrow.fromtimestamp(info[\"PlanExpiration\"], tzinfo=\"utc\"),\n )\n else:\n raise Exception(f\"Invalid value for plan: {plan_value}\")\n\n return UserInformation(\n email=info.get(\"Email\"),\n name=info.get(\"DisplayName\"),\n id=info.get(\"UserID\"),\n plan=plan,\n )", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "async def register_schema_and_creddef(\n self,\n schema_name,\n version,\n schema_attrs,\n support_revocation: bool = False,\n revocation_registry_size: int = None,\n tag=None,\n wallet_type=WALLET_TYPE_INDY,\n ):\n if wallet_type in [WALLET_TYPE_INDY, WALLET_TYPE_ASKAR]:\n return await self.register_schema_and_creddef_indy(\n schema_name,\n version,\n schema_attrs,\n support_revocation=support_revocation,\n revocation_registry_size=revocation_registry_size,\n tag=tag,\n )\n elif wallet_type == WALLET_TYPE_ANONCREDS:\n return await self.register_schema_and_creddef_anoncreds(\n schema_name,\n version,\n schema_attrs,\n support_revocation=support_revocation,\n revocation_registry_size=revocation_registry_size,\n tag=tag,\n )\n else:\n raise Exception(\"Invalid wallet_type: \" + str(wallet_type))", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_rollback(self):\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with transaction.atomic():\n Reporter.objects.create(first_name=\"Haddock\")\n raise Exception(\"Oops, that's his last name\")\n self.assertSequenceEqual(Reporter.objects.all(), [])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def resubmit_rejected_suggestion(\n suggestion_id: str,\n summary_message: str,\n author_id: str,\n change_cmd: change_domain.BaseChange\n) -> None:\n \"\"\"Resubmit a rejected suggestion with the given suggestion_id.\n\n Args:\n suggestion_id: str. The id of the rejected suggestion.\n summary_message: str. The message provided by the author to\n summarize new suggestion.\n author_id: str. The ID of the author creating the suggestion.\n change_cmd: BaseChange. The new change to apply to the suggestion.\n\n Raises:\n Exception. The summary message is empty.\n Exception. The suggestion has not been handled yet.\n Exception. The suggestion has already been accepted.\n \"\"\"\n suggestion = get_suggestion_by_id(suggestion_id)\n if not summary_message:\n raise Exception('Summary message cannot be empty.')\n if not suggestion.is_handled:\n raise Exception(\n 'The suggestion with id %s is not yet handled.' % (suggestion_id)\n )\n if suggestion.status == suggestion_models.STATUS_ACCEPTED:\n raise Exception(\n 'The suggestion with id %s was accepted. '\n 'Only rejected suggestions can be resubmitted.' % (suggestion_id)\n )\n\n suggestion.pre_update_validate(change_cmd)\n suggestion.change_cmd = change_cmd\n suggestion.set_suggestion_status_to_in_review()\n _update_suggestion(suggestion)\n\n # Update the community contribution stats so that the number of suggestions\n # of this type that are in review increases by one, since this suggestion is\n # now back in review.\n _update_suggestion_counts_in_community_contribution_stats([suggestion], 1)\n\n feedback_services.create_message(\n suggestion_id, author_id, feedback_models.STATUS_CHOICES_OPEN,\n None, summary_message)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def generic_inlineformset_factory(\n model,\n form=ModelForm,\n formset=BaseGenericInlineFormSet,\n ct_field=\"content_type\",\n fk_field=\"object_id\",\n fields=None,\n exclude=None,\n extra=3,\n can_order=False,\n can_delete=True,\n max_num=None,\n formfield_callback=None,\n validate_max=False,\n for_concrete_model=True,\n min_num=None,\n validate_min=False,\n absolute_max=None,\n can_delete_extra=True,\n):\n \"\"\"\n Return a ``GenericInlineFormSet`` for the given kwargs.\n\n You must provide ``ct_field`` and ``fk_field`` if they are different from\n the defaults ``content_type`` and ``object_id`` respectively.\n \"\"\"\n opts = model._meta\n # if there is no field called `ct_field` let the exception propagate\n ct_field = opts.get_field(ct_field)\n if (\n not isinstance(ct_field, models.ForeignKey)\n or ct_field.remote_field.model != ContentType\n ):\n raise Exception(\"fk_name '%s' is not a ForeignKey to ContentType\" % ct_field)\n fk_field = opts.get_field(fk_field) # let the exception propagate\n exclude = [*(exclude or []), ct_field.name, fk_field.name]\n FormSet = modelformset_factory(\n model,\n form=form,\n formfield_callback=formfield_callback,\n formset=formset,\n extra=extra,\n can_delete=can_delete,\n can_order=can_order,\n fields=fields,\n exclude=exclude,\n max_num=max_num,\n validate_max=validate_max,\n min_num=min_num,\n validate_min=validate_min,\n absolute_max=absolute_max,\n can_delete_extra=can_delete_extra,\n )\n FormSet.ct_field = ct_field\n FormSet.ct_fk_field = fk_field\n FormSet.for_concrete_model = for_concrete_model\n return FormSet", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"start\": 1652817000,\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_unfurl_discover_without_project_ids(\n self, mock_generate_chart, mock_get_event_stats_data\n ):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?dataset=errors&field=title&field=event.type&field=project&field=user.display&field=timestamp&name=All+Events&query=&sort=-timestamp&statsPeriod=24h\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count()\"\n assert len(chart_data[\"stats\"][\"data\"]) == INTERVALS_PER_DAY\n\n assert len(mock_get_event_stats_data.mock_calls) == 1\n dataset = mock_get_event_stats_data.mock_calls[0][2][\"dataset\"]\n assert dataset == errors", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def default(self, obj):\n if not isinstance(obj, OvmDisk): raise Exception(\"%s is not instance of OvmDisk\"%type(obj))\n dct = {}\n safeDictSet(obj, dct, 'path')\n safeDictSet(obj, dct, 'type')\n return dct", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def equal(a, b):\n assert type(a) == type(b)\n if type(a) in (float, int):\n match = math.isclose(a, b, rel_tol=tol)\n if not match:\n print(a, b, \"diff\", abs(a - b) / max(abs(a), abs(b)), \">\", tol)\n return match\n elif type(a) == str:\n match = a == b\n if not match:\n print(\"strdiff\", a, b)\n return match\n elif type(a) == list:\n # List comprehension avoids short-circuit, so the \"diff\"\n # message just above is printed for all elements\n return all([equal(aa, bb) for aa, bb in zip(a, b)])\n elif type(a) == dict:\n assert a.keys() == b.keys()\n return all([equal(a[k], b[k]) for k in a.keys()])\n raise Exception(\n \"Don't know how to compare objects of type \" + str(type(a))\n )", "smellKey": "S112", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def __repr__(self):\n raise Exception(\"This should be caught by Repr.repr_instance\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def _create_user_in_mailchimp_db(\n client: mailchimp3.MailChimp,\n # Here we use type Any because the value can be a list (for Tags) or dict\n # (for merge_fields).\n subscribed_mailchimp_data: Dict[str, Any]\n) -> bool:\n \"\"\"Creates a new user in the mailchimp database and handles the case where\n the user was permanently deleted from the database.\n\n Args:\n client: mailchimp3.MailChimp. A mailchimp instance with the API key and\n username initialized.\n subscribed_mailchimp_data: dict. Post body with required fields for a\n new user. The required fields are email_address, status and tags.\n Any relevant merge_fields are optional.\n\n Returns:\n bool. Whether the user was successfully added to the db. (This will be\n False if the user was permanently deleted earlier and therefore cannot\n be added back.)\n\n Raises:\n Exception. Any error (other than the one mentioned below) raised by the\n mailchimp API.\n \"\"\"\n try:\n client.lists.members.create(\n feconf.MAILCHIMP_AUDIENCE_ID, subscribed_mailchimp_data)\n except mailchimpclient.MailChimpError as error:\n error_message = ast.literal_eval(str(error))\n # This is the specific error message returned for the case where the\n # user was permanently deleted from the Mailchimp database earlier.\n # This was found by experimenting with the MailChimp API. Note that the\n # error reference\n # (https://mailchimp.com/developer/marketing/docs/errors/) is not\n # comprehensive, since, under status 400, they only list a subset of the\n # common error titles.\n if error_message['title'] == 'Forgotten Email Not Subscribed':\n return False\n raise Exception(error_message['detail']) from error\n return True", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def check_same_WFJT(self, obj, sub_obj):\n if type(obj) != self.model or type(sub_obj) != self.model:\n raise Exception('Attaching workflow nodes only allowed for other nodes')\n if obj.workflow_job_template != sub_obj.workflow_job_template:\n return False\n return True", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "async def async_scan_devices(self, now: datetime | None = None) -> None:\n \"\"\"Scan for new devices and return a list of found device ids.\"\"\"\n\n if self.hass.is_stopping:\n _ha_is_stopping(\"scan devices\")\n return\n\n _LOGGER.debug(\"Checking host info for FRITZ!Box device %s\", self.host)\n (\n self._update_available,\n self._latest_firmware,\n self._release_url,\n ) = await self._async_update_device_info()\n\n _LOGGER.debug(\"Checking devices for FRITZ!Box device %s\", self.host)\n _default_consider_home = DEFAULT_CONSIDER_HOME.total_seconds()\n if self._options:\n consider_home = self._options.get(\n CONF_CONSIDER_HOME, _default_consider_home\n )\n else:\n consider_home = _default_consider_home\n\n new_device = False\n hosts = await self._async_update_hosts_info()\n\n if not self.fritz_status.device_has_mesh_support or (\n self._options\n and self._options.get(CONF_OLD_DISCOVERY, DEFAULT_CONF_OLD_DISCOVERY)\n ):\n _LOGGER.debug(\n \"Using old hosts discovery method. (Mesh not supported or user option)\"\n )\n self.mesh_role = MeshRoles.NONE\n for mac, info in hosts.items():\n if self.manage_device_info(info, mac, consider_home):\n new_device = True\n await self.async_send_signal_device_update(new_device)\n return\n\n try:\n if not (\n topology := await self.hass.async_add_executor_job(\n self.fritz_hosts.get_mesh_topology\n )\n ):\n # pylint: disable-next=broad-exception-raised\n raise Exception(\"Mesh supported but empty topology reported\")\n except FritzActionError:\n self.mesh_role = MeshRoles.SLAVE\n # Avoid duplicating device trackers\n return\n\n mesh_intf = {}\n # first get all meshed devices\n for node in topology.get(\"nodes\", []):\n if not node[\"is_meshed\"]:\n continue\n\n for interf in node[\"node_interfaces\"]:\n int_mac = interf[\"mac_address\"]\n mesh_intf[interf[\"uid\"]] = Interface(\n device=node[\"device_name\"],\n mac=int_mac,\n op_mode=interf.get(\"op_mode\", \"\"),\n ssid=interf.get(\"ssid\", \"\"),\n type=interf[\"type\"],\n )\n if dr.format_mac(int_mac) == self.mac:\n self.mesh_role = MeshRoles(node[\"mesh_role\"])\n\n # second get all client devices\n for node in topology.get(\"nodes\", []):\n if node[\"is_meshed\"]:\n continue\n\n for interf in node[\"node_interfaces\"]:\n dev_mac = interf[\"mac_address\"]\n\n if dev_mac not in hosts:\n continue\n\n dev_info: Device = hosts[dev_mac]\n\n for link in interf[\"node_links\"]:\n intf = mesh_intf.get(link[\"node_interface_1_uid\"])\n if intf is not None:\n if intf[\"op_mode\"] == \"AP_GUEST\":\n dev_info.wan_access = None\n\n dev_info.connected_to = intf[\"device\"]\n dev_info.connection_type = intf[\"type\"]\n dev_info.ssid = intf.get(\"ssid\")\n\n if self.manage_device_info(dev_info, dev_mac, consider_home):\n new_device = True\n\n await self.async_send_signal_device_update(new_device)", "smellKey": "S112", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"default,first,capable-hagfish,None\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n \"default,second,capable-hagfish,None\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_unfurl_discover_short_url(self, mock_generate_chart, _):\n query = {\n \"fields\": [\"message\", \"event.type\", \"project\", \"user.display\", \"count_unique(user)\"],\n \"query\": \"message:[first,second]\",\n \"yAxis\": \"count_unique(user)\",\n \"display\": \"top5\",\n \"topEvents\": 2,\n }\n saved_query = DiscoverSavedQuery.objects.create(\n organization=self.organization,\n created_by_id=self.user.id,\n name=\"Test query\",\n query=query,\n version=2,\n )\n saved_query.set_projects([self.project.id])\n\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?id={saved_query.id}&statsPeriod=24h&project={self.project.id}\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n\n # Line chart expected since yAxis is count_unique(user)\n assert mock_generate_chart.call_args[0][0] == ChartType.SLACK_DISCOVER_TOP5_PERIOD_LINE\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count_unique(user)\"\n # 2 + 1 cause of Other\n assert len(chart_data[\"stats\"].keys()) == 2\n first_key = list(chart_data[\"stats\"].keys())[0]\n assert len(chart_data[\"stats\"][first_key][\"data\"]) == INTERVALS_PER_DAY", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def mock_subprocess_run(cmd: List[str], **_: str) -> MockProcessOutput:\n if cmd == self.coverage_combine_cmd:\n return MockProcessOutput()\n elif cmd == self.coverage_check_cmd:\n return failed_process_output\n else:\n raise Exception(\n 'Invalid command passed to subprocess.run() method')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def run_prefork_process(cmd, kwargs, cargs):\n\t\"\"\"\n\tDelegates process execution to a pre-forked process instance.\n\t\"\"\"\n\tif not 'env' in kwargs:\n\t\tkwargs['env'] = dict(os.environ)\n\ttry:\n\t\tobj = base64.b64encode(cPickle.dumps([cmd, kwargs, cargs]))\n\texcept (TypeError, AttributeError):\n\t\treturn run_regular_process(cmd, kwargs, cargs)\n\n\tproc = get_process()\n\tif not proc:\n\t\treturn run_regular_process(cmd, kwargs, cargs)\n\n\tproc.stdin.write(obj)\n\tproc.stdin.write('\\n'.encode())\n\tproc.stdin.flush()\n\tobj = proc.stdout.readline()\n\tif not obj:\n\t\traise OSError('Preforked sub-process %r died' % proc.pid)\n\n\tprocess_pool.append(proc)\n\tlst = cPickle.loads(base64.b64decode(obj))\n\t# Jython wrapper failures (bash/execvp)\n\tassert len(lst) == 5\n\tret, out, err, ex, trace = lst\n\tif ex:\n\t\tif ex == 'OSError':\n\t\t\traise OSError(trace)\n\t\telif ex == 'ValueError':\n\t\t\traise ValueError(trace)\n\t\telif ex == 'TimeoutExpired':\n\t\t\texc = TimeoutExpired(cmd, timeout=cargs['timeout'], output=out)\n\t\t\texc.stderr = err\n\t\t\traise exc\n\t\telse:\n\t\t\traise Exception(trace)\n\treturn ret, out, err", "smellKey": "S112", "smellId": null, "repo": "uajithkumar_audacity", "language": "python"} {"function": "def _lookup_report(self, cr, name):\n \"\"\"\n Look up a report definition.\n \"\"\"\n opj = os.path.join\n\n # First lookup in the deprecated place, because if the report definition\n # has not been updated, it is more likely the correct definition is there.\n # Only reports with custom parser sepcified in Python are still there.\n if 'report.' + name in openerp.report.interface.report_int._reports:\n new_report = openerp.report.interface.report_int._reports['report.' + name]\n else:\n cr.execute(\"SELECT * FROM ir_act_report_xml WHERE report_name=%s\", (name,))\n r = cr.dictfetchone()\n if r:\n if r['report_type'] in ['qweb-pdf', 'qweb-html']:\n return r['report_name']\n elif r['report_rml'] or r['report_rml_content_data']:\n if r['parser']:\n kwargs = { 'parser': operator.attrgetter(r['parser'])(openerp.addons) }\n else:\n kwargs = {}\n new_report = report_sxw('report.'+r['report_name'], r['model'],\n opj('addons',r['report_rml'] or '/'), header=r['header'], register=False, **kwargs)\n elif r['report_xsl'] and r['report_xml']:\n new_report = report_rml('report.'+r['report_name'], r['model'],\n opj('addons',r['report_xml']),\n r['report_xsl'] and opj('addons',r['report_xsl']), register=False)\n else:\n raise Exception, \"Unhandled report type: %s\" % r\n else:\n raise Exception, \"Required report does not exist: %s\" % name\n\n return new_report", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "@classmethod\n def get_next_corp_num(cls, con, corp_type: str) -> str:\n \"\"\"Retrieve the next available corporation number and advance by one.\"\"\"\n try:\n cursor = con.cursor()\n cursor.execute(\n \"\"\"\n SELECT id_num\n FROM system_id\n WHERE id_typ_cd = :corp_type\n FOR UPDATE\n \"\"\",\n corp_type=corp_type\n )\n corp_num = cursor.fetchone()\n\n if corp_num:\n cursor.execute(\n \"\"\"\n UPDATE system_id\n SET id_num = :new_num\n WHERE id_typ_cd = :corp_type\n \"\"\",\n new_num=corp_num[0]+1,\n corp_type=corp_type\n )\n\n return '%07d' % corp_num\n except Exception as err:\n current_app.logger.error('Error looking up corp_num')\n raise err", "smellKey": "S112", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "async def test_platform_setup_with_error(\n hass: HomeAssistant,\n caplog: pytest.LogCaptureFixture,\n mock_provider: MockProvider,\n) -> None:\n \"\"\"Test platform setup with an error during setup.\"\"\"\n\n class BadPlatform(MockTTS):\n \"\"\"A mock TTS platform with a setup error.\"\"\"\n\n async def async_get_engine(\n self,\n hass: HomeAssistant,\n config: ConfigType,\n discovery_info: DiscoveryInfoType | None = None,\n ) -> Provider:\n \"\"\"Raise exception during platform setup.\"\"\"\n raise Exception(\"Setup error\") # pylint: disable=broad-exception-raised\n\n mock_integration(hass, MockModule(domain=\"bad_tts\"))\n mock_platform(hass, \"bad_tts.tts\", BadPlatform(mock_provider))\n\n await async_load_platform(\n hass,\n \"tts\",\n \"bad_tts\",\n {},\n hass_config={\"tts\": [{\"platform\": \"bad_tts\"}]},\n )\n await hass.async_block_till_done()\n\n assert \"Error setting up platform: bad_tts\" in caplog.text", "smellKey": "S112", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "@property\n def allows_field(self):\n if self._allows_field is None:\n try:\n return self.name[len('ask_') : -len('_on_launch')]\n except AttributeError:\n # self.name will be set by the model metaclass, not this field\n raise Exception('Corresponding allows_field cannot be accessed until model is initialized.')\n return self._allows_field", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def __run_cmd(self, cmd):\n p = subprocess.Popen(cmd, cwd=self.srcdir, stdout=subprocess.PIPE)\n stdout, stderr = p.communicate()\n if stdout:\n sys.stdout.write(stdout)\n\n status = p.returncode\n if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:\n raise Exception('Command %s returned non-zero exit status %d' % (str(cmd), status))\n\n return stdout", "smellKey": "S112", "smellId": null, "repo": "tsdgeos_poppler_mirror", "language": "python"} {"function": "def message(self, domain: str) -> str:\n if self == CannotUseDomainReason.InvalidDomain:\n return \"This is not a valid domain\"\n elif self == CannotUseDomainReason.BuiltinDomain:\n return \"A custom domain cannot be a built-in domain.\"\n elif self == CannotUseDomainReason.DomainAlreadyUsed:\n return f\"{domain} already used\"\n elif self == CannotUseDomainReason.DomainPartOfUserEmail:\n return \"You cannot add a domain that you are currently using for your personal email. Please change your personal email to your real email\"\n elif self == CannotUseDomainReason.DomainUserInMailbox:\n return f\"{domain} already used in a SimpleLogin mailbox\"\n else:\n raise Exception(\"Invalid CannotUseDomainReason\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def _Worker():\n while True:\n binary = q.get()\n\n try:\n if options.verbose:\n with print_lock:\n print(\"Generating symbols for {0}\".format(binary))\n\n if sys.platform == 'darwin':\n binary = GetDSYMBundle(options, binary)\n elif sys.platform == 'linux2':\n binary = GetSymbolPath(options, binary)\n\n dump_syms_bin = options.dump_syms_bin\n if not os.access(dump_syms_bin, os.X_OK):\n raise Exception(f'Cannot find dump_syms: {dump_syms_bin}')\n\n syms = GetCommandOutput([dump_syms_bin, '-d', '-m', binary])\n module_line = re.match(\"MODULE [^ ]+ [^ ]+ ([0-9A-F]+) (.*)\\n\",\n syms)\n output_path = os.path.join(options.symbols_dir,\n module_line.group(2),\n module_line.group(1))\n mkdir_p(output_path)\n symbol_file = \"%s.sym\" % module_line.group(2)\n f = open(os.path.join(output_path, symbol_file), 'w')\n f.write(syms)\n f.close()\n except Exception as inst:\n with print_lock:\n print(f'Symbol failure {binary} {type(inst)} {inst}')\n finally:\n q.task_done()", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def http_to_keep(api, project_uuid, url,\n utcnow=datetime.datetime.utcnow, varying_url_params=\"\",\n prefer_cached_downloads=False):\n \"\"\"Download a file over HTTP and upload it to keep, with HTTP headers as metadata.\n\n Before downloading the URL, checks to see if the URL already\n exists in Keep and applies HTTP caching policy, the\n varying_url_params and prefer_cached_downloads flags in order to\n decide whether to use the version in Keep or re-download it.\n \"\"\"\n\n etags = {}\n cache_result = check_cached_url(api, project_uuid, url, etags,\n utcnow, varying_url_params,\n prefer_cached_downloads)\n\n if cache_result[0] is not None:\n return cache_result\n\n clean_url = cache_result[3]\n now = cache_result[4]\n\n properties = {}\n headers = {}\n if etags:\n headers['If-None-Match'] = ', '.join([_etag_quote(k) for k,v in etags.items()])\n logger.debug(\"Sending GET request with headers %s\", headers)\n\n logger.info(\"Beginning download of %s\", url)\n\n curldownloader = _Downloader(api)\n\n req = curldownloader.download(url, headers)\n\n c = curldownloader.collection\n\n if req.status_code not in (200, 304):\n raise Exception(\"Failed to download '%s' got status %s \" % (url, req.status_code))\n\n if curldownloader.target is not None:\n curldownloader.target.close()\n\n _remember_headers(clean_url, properties, req.headers, now)\n\n if req.status_code == 304 and \"Etag\" in req.headers and req.headers[\"Etag\"] in etags:\n item = etags[req.headers[\"Etag\"]]\n item[\"properties\"].update(properties)\n api.collections().update(uuid=item[\"uuid\"], body={\"collection\":{\"properties\": item[\"properties\"]}}).execute()\n cr = arvados.collection.CollectionReader(item[\"portable_data_hash\"], api_client=api)\n return (item[\"portable_data_hash\"], list(cr.keys())[0], item[\"uuid\"], clean_url, now)\n\n logger.info(\"Download complete\")\n\n collectionname = \"Downloaded from %s\" % urllib.parse.quote(clean_url, safe='')\n\n # max length - space to add a timestamp used by ensure_unique_name\n max_name_len = 254 - 28\n\n if len(collectionname) > max_name_len:\n over = len(collectionname) - max_name_len\n split = int(max_name_len/2)\n collectionname = collectionname[0:split] + \"\u2026\" + collectionname[split+over:]\n\n c.save_new(name=collectionname, owner_uuid=project_uuid, ensure_unique_name=True)\n\n api.collections().update(uuid=c.manifest_locator(), body={\"collection\":{\"properties\": properties}}).execute()\n\n return (c.portable_data_hash(), curldownloader.name, c.manifest_locator(), clean_url, now)", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def execute_action(self):\n form = self.form\n channel = self.object\n\n auth_token = form.data[\"user_access_token\"]\n fb_user_id = form.data[\"fb_user_id\"]\n\n page_id = channel.address\n\n app_id = settings.FACEBOOK_APPLICATION_ID\n app_secret = settings.FACEBOOK_APPLICATION_SECRET\n\n # get user long lived access token\n url = \"https://graph.facebook.com/oauth/access_token\"\n params = {\n \"grant_type\": \"fb_exchange_token\",\n \"client_id\": app_id,\n \"client_secret\": app_secret,\n \"fb_exchange_token\": auth_token,\n }\n\n response = requests.get(url, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to get a user long lived token\")\n\n long_lived_auth_token = response.json().get(\"access_token\", \"\")\n\n if long_lived_auth_token == \"\": # pragma: no cover\n raise Exception(\"Empty user access token!\")\n\n url = f\"https://graph.facebook.com/v7.0/{fb_user_id}/accounts\"\n params = {\"access_token\": long_lived_auth_token}\n\n response = requests.get(url, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to get a page long lived token\")\n\n response_json = response.json()\n\n page_access_token = \"\"\n for elt in response_json[\"data\"]:\n if elt[\"id\"] == str(page_id):\n page_access_token = elt[\"access_token\"]\n name = elt[\"name\"]\n break\n\n if page_access_token == \"\": # pragma: no cover\n raise Exception(\"Empty page access token!\")\n\n url = f\"https://graph.facebook.com/v7.0/{page_id}/subscribed_apps\"\n params = {\"access_token\": page_access_token}\n data = {\n \"subscribed_fields\": \"messages,message_deliveries,messaging_optins,messaging_optouts,messaging_postbacks,message_reads,messaging_referrals,messaging_handovers\"\n }\n\n response = requests.post(url, data=data, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to subscribe to app for webhook events\")\n\n channel.config[Channel.CONFIG_AUTH_TOKEN] = page_access_token\n channel.config[Channel.CONFIG_PAGE_NAME] = name\n channel.save(update_fields=[\"config\"])", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def GetOperationReferredByJsonCrossPipe(self, inOperationNameKey, inJsonDict):\n \"\"\"same as GetOperationReferredByJson(); however, if the operation is not\n in our self.mOperationBlocks, then we will also search all the other\n pipe and views state instances for the operation. If we find it, we\n will return it along with the pipe we found it in\"\"\"\n if inOperationNameKey in inJsonDict:\n nameOfOperationToUse = inJsonDict[inOperationNameKey]\n if nameOfOperationToUse in self.mOperationBlocks:\n #this operation is in our own operation blocks; return it and None\n #to follow the normal course of (non cross-pipe) operation\n returnOperation = self.mOperationBlocks[nameOfOperationToUse]\n returnPipe = None\n else:\n returnOperation = None\n returnPipe = None\n for onePipeKey, onePipe in gPhactoriPipeRootMap.items():\n if nameOfOperationToUse in onePipe.mOperationBlocks:\n #we found the operation in another pipe; return that and the other\n #pipe\n returnOperation = onePipe.mOperationBlocks[nameOfOperationToUse]\n returnPipe = onePipe\n break\n if returnOperation == None:\n #operation not found anywhere: this is fatal\n errStr = \" in GetOperationReferredByJsonCrossPipe \" +\\\n \"operation with name \" +\\\n str(nameOfOperationToUse) + \" does not exist in any pipe\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n else:\n #this code path requires an operation name, no implied default allowed\n errStr = \" in GetOperationReferredByJsonCrossPipe \" +\\\n \"requires specific operation name; no implied default allowed\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n return returnOperation, returnPipe", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def test_process_response_fails_open(self):\n request = self.factory.get(\"/\")\n bad_response = sentinel.response\n assert self.middleware.process_response(request, bad_response) is bad_response\n\n class BadRequest(HttpRequest):\n def __getattr__(self, attr):\n raise Exception(\"nope\")\n\n bad_request = BadRequest()\n assert self.middleware.process_response(bad_request, bad_response) is bad_response", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_displayable_question_skill_link_details(\n question_count: int, skill_ids: List[str], offset: int\n) -> Tuple[\n List[Optional[question_domain.QuestionSummary]],\n List[question_domain.MergedQuestionSkillLink]\n]:\n \"\"\"Returns the list of question summaries and corresponding skill\n descriptions linked to all the skills given by skill_ids.\n\n Args:\n question_count: int. The number of questions to fetch.\n skill_ids: list(str). The ids of skills for which the linked questions\n are to be retrieved.\n offset: int. Number of query results to skip.\n\n Raises:\n Exception. Querying linked question summaries for more than 3 skills at\n a time is not supported currently.\n\n Returns:\n list(QuestionSummary), list(MergedQuestionSkillLink).\n The list of questions linked to the given skill ids, the list of\n MergedQuestionSkillLink objects, keyed by question ID.\n \"\"\"\n if len(skill_ids) == 0:\n return [], []\n\n if len(skill_ids) > 3:\n raise Exception(\n 'Querying linked question summaries for more than 3 skills at a '\n 'time is not supported currently.')\n question_skill_link_models = (\n question_models.QuestionSkillLinkModel.\n get_question_skill_links_by_skill_ids(\n question_count, skill_ids, offset))\n\n # Deduplicate question_ids and group skill_descriptions that are linked to\n # the same question.\n question_ids = []\n grouped_skill_ids = []\n grouped_difficulties = []\n for question_skill_link in question_skill_link_models:\n if question_skill_link.question_id not in question_ids:\n question_ids.append(question_skill_link.question_id)\n grouped_skill_ids.append([question_skill_link.skill_id])\n grouped_difficulties.append([question_skill_link.skill_difficulty])\n else:\n grouped_skill_ids[-1].append(question_skill_link.skill_id)\n grouped_difficulties[-1].append(\n question_skill_link.skill_difficulty)\n\n merged_question_skill_links = []\n for ind, skill_ids_list in enumerate(grouped_skill_ids):\n skills = skill_models.SkillModel.get_multi(skill_ids_list)\n merged_question_skill_links.append(\n question_domain.MergedQuestionSkillLink(\n question_ids[ind], skill_ids_list,\n [skill.description if skill else None for skill in skills],\n grouped_difficulties[ind]))\n\n question_summaries = get_question_summaries_by_ids(question_ids)\n return (question_summaries, merged_question_skill_links)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def GetLookDirectionListFromCamera(inCamera):\n if inCamera.mType == 'multicamera8':\n directionsList = [ [[-1.0, 0.0, 0.0], 'x1.'],\n [[ 1.0, 0.0, 0.0], 'x2.'],\n [[ 0.0, -1.0, 0.0], 'y1.'],\n [[ 0.0, 1.0, 0.0], 'y2.'],\n [[ 0.0, 0.0, -1.0], 'z1.'],\n [[ 0.0, 0.0, 1.0], 'z2.'],\n [[-1.0, -1.0, -1.0], 'xyz1.'],\n [[ 1.0, 1.0, 1.0], 'xyz2.'] ]\n elif inCamera.mType == 'camera':\n directionsList = [[inCamera.mLookDirection, '']]\n else:\n errStr = 'error! GetLookDirectionListFromCamera has illegal camera type\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n return directionsList", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "@staticmethod\n def con_hash_to_connection(con_hash, do_verify=False, do_normalize=False):\n x_con = []\n for v_setting_name, v_setting in list(con_hash.items()):\n if isinstance(v_setting_name, (dbus.String, str)):\n v_setting_name = str(v_setting_name)\n else:\n raise Exception(\n \"Expected string dict, but got '%s' key\" % (v_setting_name)\n )\n x_setting = []\n for v_property_name, v_value in list(v_setting.items()):\n if isinstance(v_property_name, (dbus.String, str)):\n v_property_name = str(v_property_name)\n else:\n raise Exception(\n \"Expected string dict, but got '%s' subkey under %s (%s)\"\n % (v_property_name, v_setting_name, repr(con_hash))\n )\n try:\n v = Util.variant_from_dbus(v_value)\n except Exception as e:\n raise Exception(\n \"Unsupported value %s.%s = %s (%s)\"\n % (v_setting_name, v_property_name, v_value, str(e))\n )\n x_setting.append((v_property_name, v))\n\n x_con.append((v_setting_name, collections.OrderedDict(x_setting)))\n\n x_con = GLib.Variant(\"a{sa{sv}}\", collections.OrderedDict(x_con))\n\n assert GLib.Variant.equal(x_con, Util.variant_from_dbus(con_hash))\n\n try:\n con = NM.SimpleConnection.new_from_dbus(x_con)\n except:\n if do_verify:\n raise\n return None\n\n if do_normalize:\n try:\n con.normalize()\n except:\n if do_verify:\n raise\n\n if do_verify:\n con.verify()\n\n return con", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_networkmanager", "language": "python"} {"function": "def claim_number(self, user, phone_number, country, role):\n auth_id = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_ID, None)\n auth_token = self.request.session.get(Channel.CONFIG_PLIVO_AUTH_TOKEN, None)\n\n org = user.get_org()\n\n plivo_uuid = generate_uuid()\n callback_domain = org.get_brand_domain()\n app_name = \"%s/%s\" % (callback_domain.lower(), plivo_uuid)\n\n message_url = f\"https://{callback_domain}{reverse('courier.pl', args=[plivo_uuid, 'receive'])}\"\n answer_url = f\"{settings.STORAGE_URL}/plivo_voice_unavailable.xml\"\n\n headers = http_headers(extra={\"Content-Type\": \"application/json\"})\n create_app_url = \"https://api.plivo.com/v1/Account/%s/Application/\" % auth_id\n\n response = requests.post(\n create_app_url,\n json=dict(app_name=app_name, answer_url=answer_url, message_url=message_url),\n headers=headers,\n auth=(auth_id, auth_token),\n )\n\n if response.status_code in [201, 200, 202]:\n plivo_app_id = response.json()[\"app_id\"]\n else: # pragma: no cover\n plivo_app_id = None\n\n plivo_config = {\n Channel.CONFIG_PLIVO_AUTH_ID: auth_id,\n Channel.CONFIG_PLIVO_AUTH_TOKEN: auth_token,\n Channel.CONFIG_PLIVO_APP_ID: plivo_app_id,\n Channel.CONFIG_CALLBACK_DOMAIN: org.get_brand_domain(),\n }\n\n plivo_number = phone_number.strip(\"+ \").replace(\" \", \"\")\n response = requests.get(\n \"https://api.plivo.com/v1/Account/%s/Number/%s/\" % (auth_id, plivo_number),\n headers=headers,\n auth=(auth_id, auth_token),\n )\n\n if response.status_code != 200:\n response = requests.post(\n \"https://api.plivo.com/v1/Account/%s/PhoneNumber/%s/\" % (auth_id, plivo_number),\n headers=headers,\n auth=(auth_id, auth_token),\n )\n\n if response.status_code != 201: # pragma: no cover\n raise Exception(\n _(\"There was a problem claiming that number, please check the balance on your account.\")\n )\n\n response = requests.get(\n \"https://api.plivo.com/v1/Account/%s/Number/%s/\" % (auth_id, plivo_number),\n headers=headers,\n auth=(auth_id, auth_token),\n )\n\n if response.status_code == 200:\n response = requests.post(\n \"https://api.plivo.com/v1/Account/%s/Number/%s/\" % (auth_id, plivo_number),\n json=dict(app_id=plivo_app_id),\n headers=headers,\n auth=(auth_id, auth_token),\n )\n\n if response.status_code != 202: # pragma: no cover\n raise Exception(_(\"There was a problem updating that number, please try again.\"))\n\n phone_number = \"+\" + plivo_number\n phone = phonenumbers.format_number(\n phonenumbers.parse(phone_number, None), phonenumbers.PhoneNumberFormat.NATIONAL\n )\n\n channel = Channel.create(\n org, user, country, \"PL\", name=phone, address=phone_number, config=plivo_config, uuid=plivo_uuid\n )\n\n return channel", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def test_validate_exploration_throws_an_exception(self) -> None:\n observed_log_messages = []\n\n def _mock_logging_function(msg: str) -> None:\n \"\"\"Mocks logging.exception().\"\"\"\n observed_log_messages.append(msg)\n\n def _mock_validate_function(\n _exploration: exp_domain.Exploration, _strict: bool\n ) -> None:\n \"\"\"Mocks logging.exception().\"\"\"\n raise Exception('Error in exploration')\n\n logging_swap = self.swap(logging, 'exception', _mock_logging_function)\n validate_fn_swap = self.swap(\n exp_services, 'validate_exploration_for_story',\n _mock_validate_function)\n with logging_swap, validate_fn_swap:\n self.save_new_valid_exploration(\n 'exp_id_1', self.user_id_a, title='title',\n category='Algebra')\n self.publish_exploration(self.user_id_a, 'exp_id_1')\n\n with self.assertRaisesRegex(\n Exception, 'Error in exploration'):\n story_services.validate_explorations_for_story(\n ['exp_id_1'], False)\n self.assertItemsEqual(\n observed_log_messages, [\n 'Exploration validation failed for exploration with '\n 'ID: exp_id_1. Error: Error in exploration'])", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def check_copies(overwrite: bool = False, file: str = None):\n \"\"\"\n Check every file is copy-consistent with the original. Also check the model list in the main README and other\n READMEs are consistent.\n\n Args:\n overwrite (`bool`, *optional*, defaults to `False`):\n Whether or not to overwrite the copies when they don't match.\n file (`bool`, *optional*):\n The path to a specific file to check and/or fix.\n \"\"\"\n buffer = {}\n\n if file is None:\n all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, \"**/*.py\"), recursive=True)\n all_test_files = glob.glob(os.path.join(MODEL_TEST_PATH, \"**/*.py\"), recursive=True)\n all_files = list(all_files) + list(all_test_files)\n else:\n all_files = [file]\n\n diffs = []\n for filename in all_files:\n new_diffs = is_copy_consistent(filename, overwrite, buffer)\n diffs += [f\"- {filename}: copy does not match {d[0]} at line {d[1]}\" for d in new_diffs]\n if not overwrite and len(diffs) > 0:\n diff = \"\\n\".join(diffs)\n raise Exception(\n \"Found the following copy inconsistencies:\\n\"\n + diff\n + \"\\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.\"\n )", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_learner_collection_dict_by_id(\n collection_id: str,\n user: user_domain.UserActionsInfo,\n strict: bool = True,\n allow_invalid_explorations: bool = False,\n version: Optional[int] = None\n) -> LearnerCollectionDict:\n \"\"\"Gets a dictionary representation of a collection given by the provided\n collection ID. This dict includes user-specific playthrough information.\n\n Args:\n collection_id: str. The id of the collection.\n user: UserActionsInfo. Object having user_id, role and actions for\n given user.\n strict: bool. Whether to fail noisily if no collection with the given\n id exists in the datastore.\n allow_invalid_explorations: bool. Whether to also return explorations\n that are invalid, such as deleted/private explorations.\n version: int or None. The version number of the collection to be\n retrieved. If it is None, the latest version will be retrieved.\n\n Returns:\n dict. A dictionary that contains extra information along with the dict\n returned by collection_domain.Collection.to_dict() which includes useful\n data for the collection learner view. The information includes progress\n in the collection, information about explorations referenced within the\n collection, and a slightly nicer data structure for frontend work.\n\n Raises:\n ValidationError. If the collection retrieved using the given\n ID references non-existent explorations.\n Exception. No collection exists for the given collection id.\n \"\"\"\n collection = collection_services.get_collection_by_id(\n collection_id, strict=strict, version=version)\n\n if collection is None:\n raise Exception(\n 'No collection exists for the given collection id.'\n )\n exp_ids = collection.exploration_ids\n exp_summary_dicts = get_displayable_exp_summary_dicts_matching_ids(\n exp_ids, user=user)\n exp_summaries_dict_map = {\n exp_summary_dict['id']: exp_summary_dict\n for exp_summary_dict in exp_summary_dicts\n }\n\n next_exploration_id = None\n completed_exp_ids = []\n if user.user_id:\n completed_exp_ids = (\n collection_services.get_valid_completed_exploration_ids(\n user.user_id, collection))\n next_exploration_id = collection.get_next_exploration_id(\n completed_exp_ids)\n else:\n # If the user is not logged in or they have not completed any of\n # the explorations yet within the context of this collection,\n # recommend the initial exploration.\n next_exploration_id = collection.first_exploration_id\n completed_exp_ids = []\n\n # Here we use cast because the return type of 'to_dict' method\n # is CollectionDict but here we need a different dictionary\n # that contains 'playthrough_dict' key. So, we have defined a\n # LearnerCollectionDict which is inherited from CollectionDict\n # and assigned it to collection_dict. So, due to this difference\n # in types, MyPy throws an error. Thus to avoid the error,\n # we used cast here.\n collection_dict: LearnerCollectionDict = cast(\n LearnerCollectionDict, collection.to_dict()\n )\n # Here we use MyPy ignore because the expression has type List[\n # CollectionNodeDict] but here we need a list of those dictionaries\n # that can contain both 'exploration_summary' key and CollectionNodeDict's\n # key. So, we have defined LearnerCollectionNodeDict and assigned\n # its list type to the collection_dict['nodes']. So, due to this\n # difference in types, MyPy throws an error. Thus, to avoid the error,\n # we used ignore here.\n collection_dict['nodes'] = [\n node.to_dict() for node in collection.nodes] # type: ignore[misc]\n\n collection_dict['playthrough_dict'] = {\n 'next_exploration_id': next_exploration_id,\n 'completed_exploration_ids': completed_exp_ids\n }\n collection_dict['version'] = collection.version\n collection_is_public = rights_manager.is_collection_public(collection_id)\n\n # Insert an 'exploration' dict into each collection node, where the\n # dict includes meta information about the exploration (ID and title).\n for collection_node in collection_dict['nodes']:\n exploration_id = collection_node['exploration_id']\n summary_dict = exp_summaries_dict_map.get(exploration_id)\n if not allow_invalid_explorations:\n if not summary_dict:\n raise utils.ValidationError(\n 'Expected collection to only reference valid '\n 'explorations, but found an exploration with ID: %s (was '\n 'the exploration deleted or is it a private exploration '\n 'that you do not have edit access to?)'\n % exploration_id)\n if collection_is_public and rights_manager.is_exploration_private(\n exploration_id):\n raise utils.ValidationError(\n 'Cannot reference a private exploration within a public '\n 'collection, exploration ID: %s' % exploration_id)\n\n if summary_dict:\n collection_node['exploration_summary'] = summary_dict\n else:\n collection_node['exploration_summary'] = None\n\n return collection_dict", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_engagement_or_product(\n self,\n user: Dojo_User,\n engagement_id: Optional[int] = None,\n product_id: Optional[int] = None,\n ) -> Tuple[Engagement, Product, Product | Engagement]:\n \"\"\"Using the path parameters, either fetch the product or engagement\"\"\"\n engagement = product = engagement_or_product = None\n # Get the product if supplied\n # Get the engagement if supplied\n if engagement_id is not None:\n engagement = get_object_or_404(Engagement, id=engagement_id)\n engagement_or_product = engagement\n elif product_id is not None:\n product = get_object_or_404(Product, id=product_id)\n engagement_or_product = product\n else:\n msg = \"Either Engagement or Product has to be provided\"\n raise Exception(msg)\n # Ensure the supplied user has access to import to the engagement or product\n user_has_permission_or_403(user, engagement_or_product, Permissions.Import_Scan_Result)\n\n return engagement, product, engagement_or_product", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def rearrange_subtopic(self, from_index: int, to_index: int) -> None:\n \"\"\"Rearranges the subtopic in the topic.\n\n Args:\n from_index: int. The index of subtopic to move.\n to_index: int. The index at which to insert the moved subtopic.\n\n Raises:\n Exception. Invalid input.\n \"\"\"\n if from_index == to_index:\n raise Exception(\n 'Expected from_index and to_index values to be different.')\n\n if from_index >= len(self.subtopics) or from_index < 0:\n raise Exception('Expected from_index value to be with-in bounds.')\n\n if to_index >= len(self.subtopics) or to_index < 0:\n raise Exception('Expected to_index value to be with-in bounds.')\n\n skill_to_move = copy.deepcopy(\n self.subtopics[from_index])\n del self.subtopics[from_index]\n self.subtopics.insert(to_index, skill_to_move)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_arguments_from_server_type(server_type, port):\n this_path = os.path.dirname(os.path.abspath(__file__))\n certs_path = os.path.join(this_path, \"..\", \"credentials\")\n\n args = [\"openssl\", \"s_server\"]\n if server_type == \"1.2-rsa\":\n args.extend([\"-cert\", \"{}/rsa.crt\".format(certs_path),\n \"-key\", \"{}/rsa-priv.key\".format(certs_path),\n \"-certform\", \"PEM\",\n \"-tls1_2\",\n \"-cipher\", \"AES128-SHA256,AES256-SHA256\"])\n elif server_type == \"1.2-ec\":\n args.extend([\"-cert\", \"{}/ec.crt\".format(certs_path),\n \"-key\", \"{}/ec-priv.key\".format(certs_path),\n \"-certform\", \"PEM\",\n \"-tls1_2\",\n \"-cipher\", \"ECDHE-ECDSA-AES128-SHA256\"])\n elif server_type == \"1.3-ephemeral\":\n args.extend([\"-cert\", \"{}/ec.crt\".format(certs_path),\n \"-key\", \"{}/ec-priv.key\".format(certs_path),\n \"-certform\", \"PEM\",\n \"-tls1_3\",\n \"-ciphersuites\", \"TLS_AES_128_GCM_SHA256\",\n \"-num_tickets\", \"0\"])\n elif server_type == \"1.3-ephemeral-tickets\":\n args.extend([\"-cert\", \"{}/ec.crt\".format(certs_path),\n \"-key\", \"{}/ec-priv.key\".format(certs_path),\n \"-certform\", \"PEM\",\n \"-tls1_3\",\n \"-ciphersuites\", \"TLS_AES_128_GCM_SHA256\"])\n elif server_type == \"1.3-psk-tickets\":\n args.extend([\"-tls1_3\",\n \"-ciphersuites\", \"TLS_AES_128_GCM_SHA256\",\n \"-psk_identity\", \"PSK_identity\", \"-psk\", \"0102030405\",\n \"-allow_no_dhe_kex\", \"-nocert\"])\n else:\n raise Exception(\"Wrong server type\")\n\n args.extend([\"-serverpref\", \"-state\", \"-debug\", \"-status_verbose\", \"-rev\",\n \"-accept\", \"{}\".format(port)])\n return args", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def put_target_file(path: str, io_or_string: io.IOBase | str, scope: str = OPENC3_SCOPE):\n \"\"\"Get a handle to write a target file\n\n Args:\n path (str) Path to a file in a target directory\n io_or_string (io | str) IO object or str object\n scope (str) Optional, defaults to env.OPENC3_SCOPE\n \"\"\"\n if \"..\" in path:\n raise Exception(f\"Disallowed path modifier '..' found in {path}\")\n\n upload_path = f\"{scope}/targets_modified/{path}\"\n\n if os.getenv(\"OPENC3_LOCAL_MODE\") and openc3.script.OPENC3_IN_CLUSTER:\n LocalMode.put_target_file(upload_path, io_or_string, scope=scope)\n if hasattr(io_or_string, \"read\"): # not str or bytes\n io_or_string.seek(0)\n\n endpoint = f\"/openc3-api/storage/upload/{upload_path}\"\n result = _get_presigned_request(endpoint, scope=scope)\n print(f\"Writing {upload_path}\")\n\n # Try to put the file\n try:\n uri = _get_uri(result[\"url\"])\n with requests.Session() as s:\n if hasattr(io_or_string, \"read\"):\n # TODO: Better way to get io size?\n io_or_string.seek(0, 2) # Jump to end\n length = io_or_string.tell()\n io_or_string.seek(0)\n io_or_string = io_or_string.read()\n else: # str or bytes\n length = len(io_or_string)\n result = s.put(\n uri,\n data=io_or_string,\n headers={\"Content-Length\": str(length)},\n )\n return result.content\n except Exception as error:\n raise Exception(f\"Failed to write {upload_path} due to {repr(error)}\") from error", "smellKey": "S112", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def send_messages(self, messages):\n sent_messages = 0\n for m in messages:\n payload = {\"text\": m.subject}\n for opt, optval in {'rocketchat_icon_url': 'icon_url', 'rocketchat_username': 'username'}.items():\n optvalue = getattr(self, opt)\n if optvalue is not None:\n payload[optval] = optvalue.strip()\n\n r = requests.post(\n \"{}\".format(m.recipients()[0]), data=json.dumps(payload), headers=get_awx_http_client_headers(), verify=(not self.rocketchat_no_verify_ssl)\n )\n\n if r.status_code >= 400:\n logger.error(smart_str(_(\"Error sending notification rocket.chat: {}\").format(r.status_code)))\n if not self.fail_silently:\n raise Exception(smart_str(_(\"Error sending notification rocket.chat: {}\").format(r.status_code)))\n sent_messages += 1\n return sent_messages", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def save_as_chunk(self, images, chunk_path):\n first_frame, images = self._peek_first_frame(images)\n if not first_frame:\n raise Exception('no images to save')\n\n input_w = first_frame[0].width\n input_h = first_frame[0].height\n\n downscale_factor = 1\n while input_h / downscale_factor >= 1080:\n downscale_factor *= 2\n\n output_h = input_h // downscale_factor\n output_w = input_w // downscale_factor\n\n with av.open(chunk_path, 'w', format=self.FORMAT) as output_container:\n output_v_stream = self._add_video_stream(\n container=output_container,\n w=output_w,\n h=output_h,\n rate=self._output_fps,\n options=self._codec_opts,\n )\n\n with closing(output_v_stream):\n self._encode_images(images, output_container, output_v_stream)\n\n return [(input_w, input_h)]", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "async def agency_admin_GET(\n self, path, text=False, params=None, headers=None\n ) -> ClientResponse:\n if not self.multitenant:\n raise Exception(\"Error can't call agency admin unless in multitenant mode\")\n try:\n EVENT_LOGGER.debug(\"Controller GET %s request to Agent\", path)\n if not headers:\n headers = {}\n response = await self.admin_request(\n \"GET\", path, None, text, params, headers=headers\n )\n EVENT_LOGGER.debug(\n \"Response from GET %s received: \\n%s\",\n path,\n repr_json(response),\n )\n return response\n except ClientError as e:\n self.log(f\"Error during GET {path}: {str(e)}\")\n raise", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def test_unhandled_exception(self):\n async def handle_echo(reader, writer):\n raise Exception('test')\n messages = self._basetest_unhandled_exceptions(handle_echo)\n self.assertEqual(messages[0]['message'],\n 'Unhandled exception in client_connected_cb')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_action_from_state() -> Action:\n oauth_action = session[SESSION_ACTION_KEY]\n if oauth_action == Action.Login.value:\n return Action.Login\n elif oauth_action == Action.Link.value:\n return Action.Link\n raise Exception(f\"Unknown action in state: {oauth_action}\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def get_hotspot_rule(self, rule_id):\n \"\"\"\n Get detailed information about a hotspot\n :param rule_id:\n :return:\n \"\"\"\n rule = self.rules_cache.get(rule_id)\n if not rule:\n response = self.session.get(\n url=f\"{self.sonar_api_url}/hotspots/show\",\n params={\"hotspot\": rule_id},\n headers=self.default_headers,\n )\n if not response.ok:\n msg = (\n f\"Unable to get the hotspot rule {rule_id} \"\n f\"due to {response.status_code} - {response.content}\"\n )\n raise Exception(msg)\n\n rule = response.json()[\"rule\"]\n self.rules_cache.update({rule_id: rule})\n return rule", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def _deleteVlan(self, name):\n if name not in self.vlans.keys():\n raise Exception(\"No vlan device %s found\"%name)\n\n vlan = self.vlans[name]\n self.bringDown(vlan.name)\n doCmd(['vconfig', 'rem', vlan.name])\n logger.debug(self._deleteVlan, \"Delete vlan %s successfully\"%vlan.name)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def error_once(frame, event, arg):\n nonlocal raised\n if not raised:\n raised = True\n raise Exception\n return error", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def enable_bit(self, bit, pins):\n if len(pins) != len(bit.signals):\n raise Exception(\n f\"pins({pins}) and signals({bit.signals}) must be the same length\"\n )\n\n for pin in pins:\n if pin < self.first_configurable:\n raise Exception(\n \"can't enable crossbar pin anymore\", pin, self.first_configurable\n )\n\n self.portbanks[pin[0]].unskip(pin[1])\n\n self.first_configurable = (pin[0], pin[1] + 1)\n\n self.value |= 1 << bit.bit", "smellKey": "S112", "smellId": null, "repo": "wkhadgar_zephyr", "language": "python"} {"function": "def check_all_models_are_auto_configured():\n \"\"\"Check all models are each in an auto class.\"\"\"\n # This is where we need to check we have all backends or the check is incomplete.\n check_missing_backends()\n modules = get_model_modules()\n all_auto_models = get_all_auto_configured_models()\n failures = []\n for module in modules:\n new_failures = check_models_are_auto_configured(module, all_auto_models)\n if new_failures is not None:\n failures += new_failures\n if len(failures) > 0:\n raise Exception(f\"There were {len(failures)} failures:\\n\" + \"\\n\".join(failures))", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, radius = 2, altitude = 10, speed = 2, iterations = 1, center = [1,0], snapshots = None):\n self.radius = radius\n self.altitude = altitude\n self.speed = speed\n self.iterations = iterations\n self.snapshots = snapshots\n self.snapshot_delta = None\n self.next_snapshot = None\n self.z = None\n self.snapshot_index = 0\n self.takeoff = False # whether we did a take off\n\n if self.snapshots is not None and self.snapshots > 0:\n self.snapshot_delta = 360 / self.snapshots\n\n if self.iterations <= 0:\n self.iterations = 1\n\n if len(center) != 2:\n raise Exception(\"Expecting '[x,y]' for the center direction vector\")\n \n # center is just a direction vector, so normalize it to compute the actual cx,cy locations.\n cx = float(center[0])\n cy = float(center[1])\n length = math.sqrt((cx*cx) + (cy*cy))\n cx /= length\n cy /= length\n cx *= self.radius\n cy *= self.radius\n\n self.client = airsim.MultirotorClient()\n self.client.confirmConnection()\n self.client.enableApiControl(True)\n\n self.home = self.client.getMultirotorState().kinematics_estimated.position\n # check that our home position is stable\n start = time.time()\n count = 0\n while count < 100:\n pos = self.client.getMultirotorState().kinematics_estimated.position\n if abs(pos.z_val - self.home.z_val) > 1: \n count = 0\n self.home = pos\n if time.time() - start > 10:\n print(\"Drone position is drifting, we are waiting for it to settle down...\")\n start = time\n else:\n count += 1\n\n self.center = pos\n self.center.x_val += cx\n self.center.y_val += cy", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "@classmethod\n def get_suggestions_waiting_too_long_for_review(\n cls\n ) -> Sequence[GeneralSuggestionModel]:\n \"\"\"Returns a list of suggestions that have been waiting for a review\n longer than SUGGESTION_REVIEW_WAIT_TIME_THRESHOLD_IN_DAYS days on the\n Contributor Dashboard. MAX_NUMBER_OF_SUGGESTIONS_TO_EMAIL_ADMIN\n suggestions are returned, sorted in descending order by their review\n wait time.\n\n Returns:\n list(GeneralSuggestionModel). A list of suggestions, sorted in\n descending order by their review wait time.\n\n Raises:\n Exception. If there are no suggestion types offered on the\n Contributor Dashboard.\n \"\"\"\n if not feconf.CONTRIBUTOR_DASHBOARD_SUGGESTION_TYPES:\n raise Exception(\n 'Expected the suggestion types offered on the Contributor '\n 'Dashboard to be nonempty.')\n threshold_time = (\n datetime.datetime.utcnow() - datetime.timedelta(\n days=SUGGESTION_REVIEW_WAIT_TIME_THRESHOLD_IN_DAYS))\n return cls.get_all().filter(datastore_services.all_of(\n cls.status == STATUS_IN_REVIEW,\n cls.last_updated < threshold_time,\n cls.suggestion_type.IN(\n feconf.CONTRIBUTOR_DASHBOARD_SUGGESTION_TYPES)\n )).order(\n cls.last_updated\n ).fetch(MAX_NUMBER_OF_SUGGESTIONS_TO_EMAIL_ADMIN)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_bpo_42057(self):\n for i in range(10):\n try:\n raise Exception\n except Exception or Exception:\n pass", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def convert_xmod_checkpoint_to_pytorch(\n xmod_checkpoint_path: str, pytorch_dump_folder_path: str, classification_head: bool\n):\n data_dir = Path(\"data_bin\")\n xmod = FairseqXmodModel.from_pretrained(\n model_name_or_path=str(Path(xmod_checkpoint_path).parent),\n checkpoint_file=Path(xmod_checkpoint_path).name,\n _name=\"xmod_base\",\n arch=\"xmod_base\",\n task=\"multilingual_masked_lm\",\n data_name_or_path=str(data_dir),\n bpe=\"sentencepiece\",\n sentencepiece_model=str(Path(xmod_checkpoint_path).parent / \"sentencepiece.bpe.model\"),\n src_dict=str(data_dir / \"dict.txt\"),\n )\n xmod.eval() # disable dropout\n print(xmod)\n\n xmod_sent_encoder = xmod.model.encoder.sentence_encoder\n config = XmodConfig(\n vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings,\n hidden_size=xmod.cfg.model.encoder_embed_dim,\n num_hidden_layers=xmod.cfg.model.encoder_layers,\n num_attention_heads=xmod.cfg.model.encoder_attention_heads,\n intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim,\n max_position_embeddings=514,\n type_vocab_size=1,\n layer_norm_eps=1e-5, # PyTorch default used in fairseq\n pre_norm=xmod.cfg.model.encoder_normalize_before,\n adapter_reduction_factor=getattr(xmod.cfg.model, \"bottleneck\", 2),\n adapter_layer_norm=xmod.cfg.model.adapter_layer_norm,\n adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm,\n ln_before_adapter=xmod.cfg.model.ln_before_adapter,\n languages=xmod.cfg.model.languages,\n )\n if classification_head:\n config.num_labels = xmod.model.classification_heads[\"mnli\"].out_proj.weight.shape[0]\n\n print(\"Our X-MOD config:\", config)\n\n model = XmodForSequenceClassification(config) if classification_head else XmodForMaskedLM(config)\n model.eval()\n\n # Now let's copy all the weights.\n # Embeddings\n model.roberta.embeddings.word_embeddings.weight = xmod_sent_encoder.embed_tokens.weight\n model.roberta.embeddings.position_embeddings.weight = xmod_sent_encoder.embed_positions.weight\n model.roberta.embeddings.token_type_embeddings.weight.data = torch.zeros_like(\n model.roberta.embeddings.token_type_embeddings.weight\n ) # just zero them out b/c xmod doesn't use them.\n\n model.roberta.embeddings.LayerNorm.weight = xmod_sent_encoder.layernorm_embedding.weight\n model.roberta.embeddings.LayerNorm.bias = xmod_sent_encoder.layernorm_embedding.bias\n\n for i in range(config.num_hidden_layers):\n # Encoder: start of layer\n layer = model.roberta.encoder.layer[i]\n xmod_layer = xmod_sent_encoder.layers[i]\n\n # self attention\n self_attn = layer.attention.self\n if not (\n xmod_layer.self_attn.k_proj.weight.data.shape\n == xmod_layer.self_attn.q_proj.weight.data.shape\n == xmod_layer.self_attn.v_proj.weight.data.shape\n == torch.Size((config.hidden_size, config.hidden_size))\n ):\n raise AssertionError(\"Dimensions of self-attention weights do not match.\")\n\n self_attn.query.weight.data = xmod_layer.self_attn.q_proj.weight\n self_attn.query.bias.data = xmod_layer.self_attn.q_proj.bias\n self_attn.key.weight.data = xmod_layer.self_attn.k_proj.weight\n self_attn.key.bias.data = xmod_layer.self_attn.k_proj.bias\n self_attn.value.weight.data = xmod_layer.self_attn.v_proj.weight\n self_attn.value.bias.data = xmod_layer.self_attn.v_proj.bias\n\n # self-attention output\n self_output = layer.attention.output\n if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:\n raise AssertionError(\"Dimensions of self-attention output weights do not match.\")\n self_output.dense.weight = xmod_layer.self_attn.out_proj.weight\n self_output.dense.bias = xmod_layer.self_attn.out_proj.bias\n self_output.LayerNorm.weight = xmod_layer.self_attn_layer_norm.weight\n self_output.LayerNorm.bias = xmod_layer.self_attn_layer_norm.bias\n\n # intermediate\n intermediate = layer.intermediate\n if intermediate.dense.weight.shape != xmod_layer.fc1.weight.shape:\n raise AssertionError(\"Dimensions of intermediate weights do not match.\")\n intermediate.dense.weight = xmod_layer.fc1.weight\n intermediate.dense.bias = xmod_layer.fc1.bias\n\n # output\n bert_output = layer.output\n if bert_output.dense.weight.shape != xmod_layer.fc2.weight.shape:\n raise AssertionError(\"Dimensions of feed-forward weights do not match.\")\n bert_output.dense.weight = xmod_layer.fc2.weight\n bert_output.dense.bias = xmod_layer.fc2.bias\n bert_output.LayerNorm.weight = xmod_layer.final_layer_norm.weight\n bert_output.LayerNorm.bias = xmod_layer.final_layer_norm.bias\n if bert_output.adapter_layer_norm is not None:\n bert_output.adapter_layer_norm.weight = xmod_layer.adapter_layer_norm.weight\n bert_output.adapter_layer_norm.bias = xmod_layer.adapter_layer_norm.bias\n\n if sorted(bert_output.adapter_modules.keys()) != sorted(xmod_layer.adapter_modules.keys()):\n raise AssertionError(\"Lists of language adapters do not match.\")\n for lang_code, adapter in xmod_layer.adapter_modules.items():\n to_adapter = bert_output.adapter_modules[lang_code]\n from_adapter = xmod_layer.adapter_modules[lang_code]\n to_adapter.dense1.weight = from_adapter.fc1.weight\n to_adapter.dense1.bias = from_adapter.fc1.bias\n to_adapter.dense2.weight = from_adapter.fc2.weight\n to_adapter.dense2.bias = from_adapter.fc2.bias\n\n # end of layer\n\n if xmod_sent_encoder.layer_norm is not None:\n model.roberta.encoder.LayerNorm.weight = xmod_sent_encoder.layer_norm.weight\n model.roberta.encoder.LayerNorm.bias = xmod_sent_encoder.layer_norm.bias\n\n if classification_head:\n model.classifier.dense.weight = xmod.model.classification_heads[\"mnli\"].dense.weight\n model.classifier.dense.bias = xmod.model.classification_heads[\"mnli\"].dense.bias\n model.classifier.out_proj.weight = xmod.model.classification_heads[\"mnli\"].out_proj.weight\n model.classifier.out_proj.bias = xmod.model.classification_heads[\"mnli\"].out_proj.bias\n else:\n # LM Head\n model.lm_head.dense.weight = xmod.model.encoder.lm_head.dense.weight\n model.lm_head.dense.bias = xmod.model.encoder.lm_head.dense.bias\n model.lm_head.layer_norm.weight = xmod.model.encoder.lm_head.layer_norm.weight\n model.lm_head.layer_norm.bias = xmod.model.encoder.lm_head.layer_norm.bias\n model.lm_head.decoder.weight = xmod.model.encoder.lm_head.weight\n model.lm_head.decoder.bias = xmod.model.encoder.lm_head.bias\n\n # Let's check that we get the same results.\n input_ids = xmod.encode(SAMPLE_TEXT).unsqueeze(0) # batch of size 1\n model.roberta.set_default_language(SAMPLE_LANGUAGE)\n\n our_output = model(input_ids)[0]\n if classification_head:\n their_output = xmod.model.classification_heads[\"mnli\"](xmod.extract_features(input_ids))\n else:\n their_output = xmod.model(input_ids, lang_id=[SAMPLE_LANGUAGE])[0]\n print(our_output.shape, their_output.shape)\n max_absolute_diff = torch.max(torch.abs(our_output - their_output)).item()\n print(f\"max_absolute_diff = {max_absolute_diff}\") # ~ 1e-7\n success = torch.allclose(our_output, their_output, atol=1e-3)\n print(\"Do both models output the same tensors?\", \"\ud83d\udd25\" if success else \"\ud83d\udca9\")\n if not success:\n raise Exception(\"Something went wRoNg\")\n\n Path(pytorch_dump_folder_path).mkdir(parents=True, exist_ok=True)\n print(f\"Saving model to {pytorch_dump_folder_path}\")\n model.save_pretrained(pytorch_dump_folder_path)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, *args, **kwargs):\n if \"request\" in kwargs:\n self.request = kwargs.get(\"request\")\n if \"user_id\" in kwargs:\n self.user_id = kwargs.get(\"user_id\")\n\n if \"host\" in kwargs:\n self.host = kwargs.get(\"host\")\n\n if \"findings\" in kwargs:\n self.findings = kwargs.get(\"findings\")\n else:\n msg = \"Need to instantiate with finding queryset.\"\n raise Exception(msg)\n\n if \"finding_notes\" in kwargs:\n self.finding_notes = kwargs.get(\"finding_notes\")\n else:\n self.finding_notes = False\n\n if \"finding_images\" in kwargs:\n self.finding_images = kwargs.get(\"finding_images\")\n else:\n self.finding_images = False\n\n super().__init__(*args, **kwargs)\n\n self.title = \"Finding List\"\n if hasattr(self.findings, \"form\"):\n self.form = self.findings.form\n else:\n self.form = None\n self.multiple = \"true\"\n self.widget_class = \"finding-list\"\n self.extra_help = \"You can use this form to filter findings and select only the ones to be included in the \" \\\n \"report.\"\n self.title_words = get_words_for_field(Finding, \"title\")\n self.component_words = get_words_for_field(Finding, \"component_name\")\n\n if self.request is not None:\n self.paged_findings = get_page_items(self.request, self.findings.qs, 25)\n else:\n self.paged_findings = self.findings", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def get_folder_by_name(self, folder_name):\n for folder in self.get_folders():\n a_folder_name = folder.get_name()\n if folder_name == a_folder_name:\n return folder\n if folder_name == 'false':\n return Folder(self.xml)\n else:\n raise Exception(\"Dataset no encontrado\")", "smellKey": "S112", "smellId": null, "repo": "poblaciones_poblaciones", "language": "python"} {"function": "def get_multiple_versioned_exp_interaction_ids_mapping_by_version(\n exp_id: str,\n version_numbers: List[int]\n) -> List[exp_domain.VersionedExplorationInteractionIdsMapping]:\n \"\"\"Returns a list of VersionedExplorationInteractionIdsMapping domain\n objects corresponding to the specified versions.\n\n Args:\n exp_id: str. ID of the exploration.\n version_numbers: list(int). List of version numbers.\n\n Returns:\n list(VersionedExplorationInteractionIdsMapping). List of Exploration\n domain objects.\n\n Raises:\n Exception. One or more of the given versions of the exploration could\n not be converted to the latest schema version.\n \"\"\"\n versioned_exp_interaction_ids_mapping = []\n exploration_models = exp_models.ExplorationModel.get_multi_versions(\n exp_id, version_numbers)\n for index, exploration_model in enumerate(exploration_models):\n if (exploration_model.states_schema_version !=\n feconf.CURRENT_STATE_SCHEMA_VERSION):\n raise Exception(\n 'Exploration(id=%s, version=%s, states_schema_version=%s) '\n 'does not match the latest schema version %s' % (\n exp_id,\n version_numbers[index],\n exploration_model.states_schema_version,\n feconf.CURRENT_STATE_SCHEMA_VERSION\n ))\n states_to_interaction_id_mapping = {}\n for state_name in exploration_model.states:\n states_to_interaction_id_mapping[state_name] = (\n exploration_model.states[state_name]['interaction']['id'])\n versioned_exp_interaction_ids_mapping.append(\n exp_domain.VersionedExplorationInteractionIdsMapping(\n exploration_model.version,\n states_to_interaction_id_mapping))\n\n return versioned_exp_interaction_ids_mapping", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def func():\n try:\n try:\n 3\n except:\n 5\n else:\n 7\n raise Exception\n finally:\n 10\n except:\n 12\n finally:\n 14", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def test_decorator_syntax_rollback(self):\n @transaction.atomic\n def make_reporter():\n Reporter.objects.create(first_name=\"Haddock\")\n raise Exception(\"Oops, that's his last name\")\n\n with self.assertRaisesMessage(Exception, \"Oops\"):\n make_reporter()\n self.assertSequenceEqual(Reporter.objects.all(), [])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _load_dummy_blog_post(self, blog_post_title: str) -> None:\n \"\"\"Loads the database with a blog post.\n\n Raises:\n Exception. Cannot load new blog post in production mode.\n \"\"\"\n assert self.user_id is not None\n if not constants.DEV_MODE:\n raise Exception('Cannot load new blog post in production mode.')\n\n blog_post = blog_services.create_new_blog_post(self.user_id)\n fs = fs_services.GcsFileSystem('blog_post', blog_post.id)\n with open(\n './assets/images/general/learner1.png', 'rb'\n ) as thumbnail:\n fs.commit(\n 'thumbnail/blog_thumbnail.png',\n thumbnail.read(),\n 'image/png'\n )\n with open(\n './assets/images/subjects/Art.svg', 'rb'\n ) as image:\n fs.commit(\n 'image/blog_post_image_height_326_width_490.svg',\n image.read(),\n 'image/svg+xml'\n )\n\n if blog_post_title == EDUCATION_BLOG_POST_TITLE:\n blog_services.update_blog_post(blog_post.id, {\n 'title':\n '%s-%s' % (EDUCATION_BLOG_POST_TITLE, blog_post.id),\n 'thumbnail_filename': 'blog_thumbnail.png',\n 'content': EDUCATION_BLOG_POST_CONTENT,\n 'tags': ['Community']\n })\n elif blog_post_title == FORMATTING_BLOG_POST_TITLE:\n blog_services.update_blog_post(blog_post.id, {\n 'title':\n '%s-%s' % (FORMATTING_BLOG_POST_TITLE, blog_post.id),\n 'content': FORMATTING_BLOG_POST_CONTENT,\n 'tags': ['Learners', 'Languages'],\n 'thumbnail_filename': 'blog_thumbnail.png'\n })\n else:\n # The handler schema defines the possible values of\n # 'blog_post_title'. If 'blog_post_title' has a value other than\n # those defined in the schema, a Bad Request error will be thrown.\n # Hence, 'blog_post_title' must be 'ARABIC_BLOG_POST_TITLE' if\n # this branch is executed.\n assert blog_post_title == ARABIC_BLOG_POST_TITLE\n blog_services.update_blog_post(blog_post.id, {\n 'title':\n '%s-%s' % (ARABIC_BLOG_POST_TITLE, blog_post.id),\n 'content': ARABIC_BLOG_POST_CONTENT,\n 'tags': [\n 'Learners',\n 'Volunteer',\n 'New features',\n 'Community',\n 'Languages'\n ],\n 'thumbnail_filename': 'blog_thumbnail.png'\n })\n blog_services.publish_blog_post(blog_post.id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_richcompare_crash(self):\n # gh-4613\n import operator as op\n\n # dummy class where __array__ throws exception\n class Foo:\n __array_priority__ = 1002\n\n def __array__(self, *args, **kwargs):\n raise Exception()\n\n rhs = Foo()\n lhs = np.array(1)\n for f in [op.lt, op.le, op.gt, op.ge]:\n assert_raises(TypeError, f, lhs, rhs)\n assert_(not op.eq(lhs, rhs))\n assert_(op.ne(lhs, rhs))", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@region_silo_function\ndef build_action_response(\n registered_factory: ActionHandlerFactory,\n integration: RpcIntegration | None = None,\n organization: Organization | None = None,\n sentry_app_installation: RpcSentryAppInstallation | None = None,\n) -> Mapping[str, Any]:\n \"\"\"\n Build the \"available action\" objects for the API. Each one can have different fields.\n\n :param registered_factory: One of the registered AlertRuleTriggerAction factories.\n :param integration: Optional. The Integration if this action uses a one.\n :param organization: Optional. If this is a PagerDuty/Opsgenie action, we need the organization to look up services/teams.\n :param sentry_app: Optional. The SentryApp if this action uses a one.\n :return: The available action object.\n \"\"\"\n action_response: dict[str, Any] = {\n \"type\": registered_factory.slug,\n \"allowedTargetTypes\": [\n ACTION_TARGET_TYPE_TO_STRING.get(target_type)\n for target_type in registered_factory.supported_target_types\n ],\n }\n\n if integration:\n action_response[\"integrationName\"] = integration.name\n action_response[\"integrationId\"] = integration.id\n\n if registered_factory.service_type == AlertRuleTriggerAction.Type.PAGERDUTY:\n if organization is None:\n raise Exception(\"Organization is required for PAGERDUTY actions\")\n action_response[\"options\"] = [\n {\"value\": id, \"label\": service_name}\n for id, service_name in get_pagerduty_services(organization.id, integration.id)\n ]\n elif registered_factory.service_type == AlertRuleTriggerAction.Type.OPSGENIE:\n if organization is None:\n raise Exception(\"Organization is required for OPSGENIE actions\")\n action_response[\"options\"] = [\n {\"value\": id, \"label\": team}\n for id, team in get_opsgenie_teams(organization.id, integration.id)\n ]\n\n elif sentry_app_installation:\n action_response[\"sentryAppName\"] = sentry_app_installation.sentry_app.name\n action_response[\"sentryAppId\"] = sentry_app_installation.sentry_app.id\n action_response[\"sentryAppInstallationUuid\"] = sentry_app_installation.uuid\n action_response[\"status\"] = sentry_app_installation.sentry_app.status\n\n # Sentry Apps can be alertable but not have an Alert Rule UI Component\n component = app_service.prepare_sentry_app_components(\n installation_id=sentry_app_installation.id, component_type=\"alert-rule-action\"\n )\n if component:\n action_response[\"settings\"] = component.app_schema.get(\"settings\", {})\n\n return action_response", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _dist_info_files(whl_zip):\n \"\"\"Identify the .dist-info folder inside a wheel ZipFile.\"\"\"\n res = []\n for path in whl_zip.namelist():\n m = re.match(r'[^/\\\\]+-[^/\\\\]+\\.dist-info/', path)\n if m:\n res.append(path)\n if res:\n return res\n raise Exception(\"No .dist-info folder found in wheel\")", "smellKey": "S112", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def test_exception_cleanup_names2(self):\n # Make sure the cleanup doesn't break if the variable is explicitly deleted.\n try:\n raise Exception()\n except Exception as e:\n self.assertIsInstance(e, Exception)\n del e\n self.assertNotIn('e', locals())\n with self.assertRaises(UnboundLocalError):\n e", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def apply_change_list(\n exploration_id: str, change_list: Sequence[exp_domain.ExplorationChange]\n) -> exp_domain.Exploration:\n \"\"\"Applies a changelist to a pristine exploration and returns the result.\n\n Each entry in change_list is a dict that represents an ExplorationChange\n object.\n\n Args:\n exploration_id: str. The id of the exploration to which the change list\n is to be applied.\n change_list: list(ExplorationChange). The list of changes to apply.\n\n Returns:\n Exploration. The exploration domain object that results from applying\n the given changelist to the existing version of the exploration.\n\n Raises:\n Exception. Any entries in the changelist are invalid.\n Exception. Solution cannot exist with None interaction id.\n \"\"\"\n exploration = exp_fetchers.get_exploration_by_id(exploration_id)\n try:\n to_param_domain = param_domain.ParamChange.from_dict\n for change in change_list:\n if change.cmd == exp_domain.CMD_ADD_STATE:\n # Here we use cast because we are narrowing down the type from\n # ExplorationChange to a specific change command.\n add_state_cmd = cast(\n exp_domain.AddExplorationStateCmd,\n change\n )\n exploration.add_state(\n add_state_cmd.state_name,\n add_state_cmd.content_id_for_state_content,\n add_state_cmd.content_id_for_default_outcome\n )\n elif change.cmd == exp_domain.CMD_RENAME_STATE:\n # Here we use cast because we are narrowing down the type from\n # ExplorationChange to a specific change command.\n rename_state_cmd = cast(\n exp_domain.RenameExplorationStateCmd,\n change\n )\n exploration.rename_state(\n rename_state_cmd.old_state_name,\n rename_state_cmd.new_state_name\n )\n elif change.cmd == exp_domain.CMD_DELETE_STATE:\n # Here we use cast because we are narrowing down the type from\n # ExplorationChange to a specific change command.\n delete_state_cmd = cast(\n exp_domain.DeleteExplorationStateCmd,\n change\n )\n exploration.delete_state(delete_state_cmd.state_name)\n elif change.cmd == exp_domain.CMD_EDIT_STATE_PROPERTY:\n state: state_domain.State = exploration.states[\n change.state_name]\n if (change.property_name ==\n exp_domain.STATE_PROPERTY_PARAM_CHANGES):\n # Here we use cast because this 'if' condition forces\n # change to have type EditExpStatePropertyParamChangesCmd.\n edit_param_changes_cmd = cast(\n exp_domain.EditExpStatePropertyParamChangesCmd,\n change\n )\n state.update_param_changes(list(map(\n to_param_domain, edit_param_changes_cmd.new_value\n )))\n elif change.property_name == exp_domain.STATE_PROPERTY_CONTENT:\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExpStatePropertyContentCmd.\n edit_content_cmd = cast(\n exp_domain.EditExpStatePropertyContentCmd,\n change\n )\n content = (\n state_domain.SubtitledHtml.from_dict(\n edit_content_cmd.new_value\n )\n )\n content.validate()\n state.update_content(content)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_ID):\n state.update_interaction_id(change.new_value)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_LINKED_SKILL_ID):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyLinkedSkillIdCmd.\n edit_linked_skill_id_cmd = cast(\n exp_domain.EditExpStatePropertyLinkedSkillIdCmd,\n change\n )\n state.update_linked_skill_id(\n edit_linked_skill_id_cmd.new_value\n )\n elif (change.property_name ==\n exp_domain.\n STATE_PROPERTY_INAPPLICABLE_SKILL_MISCONCEPTION_IDS):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInapplicableSkillMisconceptionIdsCmd.\n edit_inapplicable_skill_misconception_ids = cast(\n exp_domain.\n EditExpStatePropertyInapplicableSkillMisconceptionIdsCmd, # pylint: disable=line-too-long\n change\n )\n state.update_inapplicable_skill_misconception_ids(\n edit_inapplicable_skill_misconception_ids.new_value\n )\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_CUST_ARGS):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInteractionCustArgsCmd.\n edit_interaction_cust_arg_cmd = cast(\n exp_domain.EditExpStatePropertyInteractionCustArgsCmd,\n change\n )\n state.update_interaction_customization_args(\n edit_interaction_cust_arg_cmd.new_value)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_HANDLERS):\n raise utils.InvalidInputException(\n 'Editing interaction handlers is no longer supported')\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_ANSWER_GROUPS):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInteractionAnswerGroupsCmd.\n edit_interaction_answer_group_cmd = cast(\n exp_domain.EditExpStatePropertyInteractionAnswerGroupsCmd, # pylint: disable=line-too-long\n change\n )\n answer_groups = (\n edit_interaction_answer_group_cmd.new_value\n )\n new_answer_groups = [\n state_domain.AnswerGroup.from_dict(answer_group)\n for answer_group in answer_groups\n ]\n state.update_interaction_answer_groups(new_answer_groups)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_DEFAULT_OUTCOME):\n new_outcome = None\n if change.new_value:\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInteractionDefaultOutcomeCmd.\n edit_interaction_default_outcome_cmd = cast(\n exp_domain.EditExpStatePropertyInteractionDefaultOutcomeCmd, # pylint: disable=line-too-long\n change\n )\n new_outcome = state_domain.Outcome.from_dict(\n edit_interaction_default_outcome_cmd.new_value\n )\n state.update_interaction_default_outcome(new_outcome)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_UNCLASSIFIED_ANSWERS):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyUnclassifiedAnswersCmd.\n edit_unclassified_answers_cmd = cast(\n exp_domain.EditExpStatePropertyUnclassifiedAnswersCmd,\n change\n )\n state.update_interaction_confirmed_unclassified_answers(\n edit_unclassified_answers_cmd.new_value)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_HINTS):\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInteractionHintsCmd.\n edit_state_interaction_hints_cmd = cast(\n exp_domain.EditExpStatePropertyInteractionHintsCmd,\n change\n )\n hint_dicts = (\n edit_state_interaction_hints_cmd.new_value\n )\n if not isinstance(hint_dicts, list):\n raise Exception(\n 'Expected hints_list to be a list,'\n ' received %s' % hint_dicts)\n new_hints_list = [\n state_domain.Hint.from_dict(hint_dict)\n for hint_dict in hint_dicts\n ]\n state.update_interaction_hints(new_hints_list)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_INTERACTION_SOLUTION):\n new_solution = None\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyInteractionSolutionCmd.\n edit_interaction_solution_cmd = cast(\n exp_domain.EditExpStatePropertyInteractionSolutionCmd,\n change\n )\n if edit_interaction_solution_cmd.new_value is not None:\n if state.interaction.id is None:\n raise Exception(\n 'solution cannot exist with None '\n 'interaction id.'\n )\n new_solution = state_domain.Solution.from_dict(\n state.interaction.id,\n edit_interaction_solution_cmd.new_value\n )\n state.update_interaction_solution(new_solution)\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_SOLICIT_ANSWER_DETAILS):\n if not isinstance(change.new_value, bool):\n raise Exception(\n 'Expected solicit_answer_details to be a ' +\n 'bool, received %s' % change.new_value)\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertySolicitAnswerDetailsCmd.\n edit_solicit_answer_details_cmd = cast(\n exp_domain.EditExpStatePropertySolicitAnswerDetailsCmd,\n change\n )\n state.update_solicit_answer_details(\n edit_solicit_answer_details_cmd.new_value\n )\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_CARD_IS_CHECKPOINT):\n if not isinstance(change.new_value, bool):\n raise Exception(\n 'Expected card_is_checkpoint to be a ' +\n 'bool, received %s' % change.new_value)\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyCardIsCheckpointCmd.\n edit_card_is_checkpoint_cmd = cast(\n exp_domain.EditExpStatePropertyCardIsCheckpointCmd,\n change\n )\n state.update_card_is_checkpoint(\n edit_card_is_checkpoint_cmd.new_value\n )\n elif (change.property_name ==\n exp_domain.STATE_PROPERTY_RECORDED_VOICEOVERS):\n if not isinstance(change.new_value, dict):\n raise Exception(\n 'Expected recorded_voiceovers to be a dict, '\n 'received %s' % change.new_value)\n # Explicitly convert the duration_secs value from\n # int to float. Reason for this is the data from\n # the frontend will be able to match the backend\n # state model for Voiceover properly. Also js\n # treats any number that can be float and int as\n # int (no explicit types). For example,\n # 10.000 is not 10.000 it is 10.\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExpStatePropertyRecordedVoiceoversCmd.\n edit_recorded_voiceovers_cmd = cast(\n exp_domain.EditExpStatePropertyRecordedVoiceoversCmd,\n change\n )\n new_voiceovers_mapping = (\n edit_recorded_voiceovers_cmd.new_value[\n 'voiceovers_mapping'\n ]\n )\n language_codes_to_audio_metadata = (\n new_voiceovers_mapping.values())\n for language_codes in language_codes_to_audio_metadata:\n for audio_metadata in language_codes.values():\n audio_metadata['duration_secs'] = (\n float(audio_metadata['duration_secs'])\n )\n recorded_voiceovers = (\n state_domain.RecordedVoiceovers.from_dict(\n change.new_value))\n state.update_recorded_voiceovers(recorded_voiceovers)\n elif change.cmd == exp_domain.CMD_EDIT_EXPLORATION_PROPERTY:\n if change.property_name == 'title':\n # Here we use cast because this 'if' condition forces\n # change to have type EditExplorationPropertyTitleCmd.\n edit_title_cmd = cast(\n exp_domain.EditExplorationPropertyTitleCmd,\n change\n )\n exploration.update_title(edit_title_cmd.new_value)\n elif change.property_name == 'category':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyCategoryCmd.\n edit_category_cmd = cast(\n exp_domain.EditExplorationPropertyCategoryCmd,\n change\n )\n exploration.update_category(edit_category_cmd.new_value)\n elif change.property_name == 'objective':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyObjectiveCmd.\n edit_objective_cmd = cast(\n exp_domain.EditExplorationPropertyObjectiveCmd,\n change\n )\n exploration.update_objective(edit_objective_cmd.new_value)\n elif change.property_name == 'language_code':\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExplorationPropertyLanguageCodeCmd.\n edit_language_code_cmd = cast(\n exp_domain.EditExplorationPropertyLanguageCodeCmd,\n change\n )\n exploration.update_language_code(\n edit_language_code_cmd.new_value\n )\n elif change.property_name == 'tags':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyTagsCmd.\n edit_tags_cmd = cast(\n exp_domain.EditExplorationPropertyTagsCmd,\n change\n )\n exploration.update_tags(edit_tags_cmd.new_value)\n elif change.property_name == 'blurb':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyBlurbCmd.\n edit_blurb_cmd = cast(\n exp_domain.EditExplorationPropertyBlurbCmd,\n change\n )\n exploration.update_blurb(edit_blurb_cmd.new_value)\n elif change.property_name == 'author_notes':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyAuthorNotesCmd.\n edit_author_notes_cmd = cast(\n exp_domain.EditExplorationPropertyAuthorNotesCmd,\n change\n )\n exploration.update_author_notes(\n edit_author_notes_cmd.new_value\n )\n elif change.property_name == 'param_specs':\n # Here we use cast because this 'elif' condition forces\n # change to have type EditExplorationPropertyParamSpecsCmd.\n edit_param_specs_cmd = cast(\n exp_domain.EditExplorationPropertyParamSpecsCmd,\n change\n )\n exploration.update_param_specs(\n edit_param_specs_cmd.new_value\n )\n elif change.property_name == 'param_changes':\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExplorationPropertyParamChangesCmd.\n edit_exp_param_changes_cmd = cast(\n exp_domain.EditExplorationPropertyParamChangesCmd,\n change\n )\n exploration.update_param_changes(\n list(\n map(\n to_param_domain,\n edit_exp_param_changes_cmd.new_value\n )\n )\n )\n elif change.property_name == 'init_state_name':\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExplorationPropertyInitStateNameCmd.\n edit_init_state_name_cmd = cast(\n exp_domain.EditExplorationPropertyInitStateNameCmd,\n change\n )\n exploration.update_init_state_name(\n edit_init_state_name_cmd.new_value\n )\n elif change.property_name == 'auto_tts_enabled':\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExplorationPropertyAutoTtsEnabledCmd.\n edit_auto_tts_enabled_cmd = cast(\n exp_domain.EditExplorationPropertyAutoTtsEnabledCmd,\n change\n )\n exploration.update_auto_tts_enabled(\n edit_auto_tts_enabled_cmd.new_value\n )\n elif change.property_name == 'next_content_id_index':\n # Here we use cast because this 'elif'\n # condition forces change to have type\n # EditExplorationPropertyNextContentIdIndexCmd.\n cmd = cast(\n exp_domain.EditExplorationPropertyNextContentIdIndexCmd,\n change\n )\n next_content_id_index = max(\n cmd.new_value, exploration.next_content_id_index)\n exploration.update_next_content_id_index(\n next_content_id_index)\n elif (change.cmd ==\n exp_domain.CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION):\n # Loading the exploration model from the datastore into an\n # Exploration domain object automatically converts it to use\n # the latest states schema version. As a result, simply\n # resaving the exploration is sufficient to apply the states\n # schema update. Thus, no action is needed here other than\n # to make sure that the version that the user is trying to\n # migrate to is the latest version.\n # Here we use cast because we are narrowing down the type from\n # ExplorationChange to a specific change command.\n migrate_states_schema_cmd = cast(\n exp_domain.MigrateStatesSchemaToLatestVersionCmd,\n change\n )\n target_version_is_current_state_schema_version = (\n migrate_states_schema_cmd.to_version ==\n str(feconf.CURRENT_STATE_SCHEMA_VERSION)\n )\n if not target_version_is_current_state_schema_version:\n raise Exception(\n 'Expected to migrate to the latest state schema '\n 'version %s, received %s' % (\n feconf.CURRENT_STATE_SCHEMA_VERSION,\n migrate_states_schema_cmd.to_version))\n return exploration\n\n except Exception as e:\n logging.error(\n '%s %s %s %s' % (\n e.__class__.__name__, e, exploration_id,\n pprint.pformat(change_list))\n )\n raise e", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def trace_error(self, level: str, error: Exception):\n self.bot.logger.name = f\"discord.{level}\"\n self.bot.logger.error(msg=type(error).__name__, exc_info=error)\n\n raise error", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "def mock_load_template(\n filename: str,\n template_is_aot_compiled: bool = False\n) -> str:\n \"\"\"Mock for load_template function. This mock is required for backend tests\n since we do not have webpack compilation before backend tests. The folder to\n search templates is webpack_bundles which is generated after webpack\n compilation. Since this folder will be missing, load_template function will\n return an error. So, we use a mock for load_template which returns the html\n file from the source directory instead.\n\n Args:\n filename: str. The name of the file for which template is to be\n returned.\n template_is_aot_compiled: bool. False by default. Use\n True when the template is compiled by angular AoT compiler.\n\n Returns:\n str. The contents of the given file.\n\n Raises:\n Exception. No file exists for the given file name.\n \"\"\"\n filepath = get_filepath_from_filename(\n filename, os.path.join('core', 'templates', 'pages'))\n if template_is_aot_compiled:\n filepath = get_filepath_from_filename(\n filename, 'src')\n if filepath is None:\n raise Exception(\n 'No file exists for the given file name.'\n )\n with utils.open_file(filepath, 'r') as f:\n return f.read()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def compile_all_ts_files() -> None:\n \"\"\"Compiles all project typescript files into\n COMPILED_TYPESCRIPT_TMP_PATH. Previously, we only compiled\n the TS files that were needed, but when a relative import was used, the\n linter would crash with a FileNotFound exception before being able to\n run. For more details, please see issue #9458.\n \"\"\"\n cmd = ('./node_modules/typescript/bin/tsc -p %s -outDir %s') % (\n './tsconfig-lint.json', COMPILED_TYPESCRIPT_TMP_PATH)\n proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n\n _, encoded_stderr = proc.communicate()\n stderr = encoded_stderr.decode('utf-8')\n\n if stderr:\n raise Exception(stderr)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_profiles_per_rule_by_id(rule_id, project_root_abspath, env_yaml, product_yaml):\n relevant_benchmarks = get_relevant_benchmarks(env_yaml, product_yaml)\n rules = find_existing_rules(project_root_abspath, relevant_benchmarks)\n if rule_id not in rules and \"ALL_RULES\" not in rule_id:\n raise Exception(\"Rule ID: {} not found!\".format(rule_id))\n if \"ALL_RULES\" not in rule_id:\n rules = {rule_id}\n return get_minimal_profiles_by_id(rules, {})", "smellKey": "S112", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def operations(self, alignment: int):\n \"\"\"\n Returns operations satisfying the alignment constraint indicated by `alignment`\n\n :param alignment: alignment constraint of operations to return\n :type alignment: int\n\n :return: list of operations\n :rtype: list\n \"\"\"\n if alignment not in self.kernels_by_alignment:\n raise Exception(\n f\"No operations of alignment {alignment} found for data type and layout \"\n f\"combination {self.datatype_comb} {self.layout_comb}\"\n )\n return self.kernels_by_alignment[alignment]", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"count()\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n \"count_unique(user)\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_unfurl_discover_multi_y_axis(self, mock_generate_chart, _):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?field=title&field=event.type&field=project&field=user.display&field=timestamp&name=All+Events&project={self.project.id}&query=&sort=-timestamp&statsPeriod=24h&yAxis=count_unique%28user%29&yAxis=count%28%29\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature([\"organizations:discover-basic\"]):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n chart_data = mock_generate_chart.call_args[0][1]\n\n assert len(chart_data[\"stats\"][\"count()\"][\"data\"]) == INTERVALS_PER_DAY\n assert len(chart_data[\"stats\"][\"count_unique(user)\"][\"data\"]) == INTERVALS_PER_DAY", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def IssueErrorOrWarningThroughSierraIO(datadescription, outString, isErrorFlag):\n if PhactoriDbg():\n myDebugPrint3(\"IssueErrorOrWarningThroughSierraIO entered\")\n\n if datadescription == None:\n errStr = \"IssueErrorOrWarningThroughSierraIO no datadescription\\n\" + \\\n outString\n raise Exception(errStr)\n return\n\n fd = datadescription.GetUserData()\n\n if fd == None:\n errStr = \"IssueErrorOrWarningThroughSierraIO, no user data\\n\" + \\\n outString\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n return\n\n #numArrays = fd.GetNumberOfArrays()\n #myDebugPrint3(\"abstract arrays: number of arrays: \" + str(numArrays) + \"\\n\")\n #for ii in range(numArrays):\n # myDebugPrint3(\"array \" + str(ii) + \":\\n\")\n # oneArray = fd.GetAbstractArray(ii)\n # myDebugPrint3(\"name: \" + oneArray.GetName() + \"\\n\")\n\n errorCodeArray = fd.GetAbstractArray(\"catalyst_sierra_error_codes\")\n errorMessageArray = fd.GetAbstractArray(\"catalyst_sierra_error_messages\")\n\n if errorCodeArray == None or errorMessageArray == None:\n if PhactoriDbg(999):\n myDebugPrint3(\"IssueErrorOrWarningThroughSierraIO::\\n\"\n \"catalyst_sierra_error_codes and/or catalyst_sierra_error_messages\\n\"\n \"were missing from UserData. Item follows:\\n\" + outString, 999)\n else:\n if isErrorFlag:\n errorCode = 0\n else:\n errorCode = 1\n errorCodeArray.InsertNextValue(errorCode)\n errorMessageArray.InsertNextValue(outString)\n\n if PhactoriDbg():\n myDebugPrint3(\"IssueErrorOrWarningThroughSierraIO reached end\")", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def populateFromElements(self, obj, elements):\n # Populates obj with `elements' as subelements\n keys = list(obj.keys())\n keys_len = len(keys)\n for element in elements:\n if _is_string(element):\n if keys_len != 1:\n if not element.strip():\n # White space around an element - skip\n continue\n # Ambiguity: don't know which attribute to initialize\n # pylint: disable-next=broad-exception-raised,consider-using-f-string\n raise Exception(\"Ambiguity %s\" % keys)\n # Init the only attribute we know of\n obj[keys[0]] = element\n continue\n name = element.name\n if name not in obj and name not in self.tagMap:\n # Unsupported key\n continue\n if name in self.tagMap:\n # Have to map this element\n name = self.tagMap[name]\n value = _normalizeSubelements(\n obj.attributeTypes.get(name), element.subelements\n )\n obj[name] = value", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def _load_configs() -> dict[str, list[Rule]]:\n if not CONFIGS_DIR.exists():\n logger.error(\n \"Failed to load Fingerprinting Configs, invalid _config_dir: %s\",\n CONFIGS_DIR,\n )\n if settings.DEBUG:\n raise Exception(\n f\"Failed to load Fingerprinting Configs, invalid _config_dir: '{CONFIGS_DIR}'\"\n )\n\n configs: dict[str, list[Rule]] = {}\n\n for config_file_path in sorted(CONFIGS_DIR.glob(\"**/*.txt\")):\n config_name = config_file_path.parent.name\n configs.setdefault(config_name, [])\n\n try:\n with open(config_file_path) as config_file:\n str_conf = config_file.read().rstrip()\n configs[config_name].extend(\n BuiltInFingerprintingRules.from_config_string(str_conf).rules\n )\n except InvalidFingerprintingConfig:\n logger.exception(\n \"Fingerprinting Config %s Invalid\",\n config_file_path,\n )\n if settings.DEBUG:\n raise\n except Exception:\n logger.exception(\n \"Failed to load Fingerprinting Config %s\",\n config_file_path,\n )\n if settings.DEBUG:\n raise\n\n return configs", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def neurondemo(extra, input):\n input = extra + input\n stdout, stderr = run(\"neurondemo -nobanner\", input)\n stdout = stdout.splitlines()\n stderr = stderr.splitlines()\n if len(stderr) != 0:\n for line in stderr:\n print(\"stderr:\", line.strip())\n raise Exception(\"Unexpected stderr\")\n begin_index = stdout.index(\"ZZZbegin\")\n end_index = stdout.index(\"ZZZend\")\n prefix = stdout[:begin_index]\n suffix = stdout[end_index + 1 :]\n if len(prefix):\n print(\"stdout prefix, excluded from comparison:\")\n for line in prefix:\n print(\"stdout:\", line.strip())\n if len(suffix):\n print(\"stdout suffix, excluded from comparison:\")\n for line in suffix:\n print(\"stdout:\", line.strip())\n return stdout[begin_index + 1 : end_index]", "smellKey": "S112", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def _migrate_subtopics_to_latest_schema(\n versioned_subtopics: topic_domain.VersionedSubtopicsDict, topic_id: str\n) -> None:\n \"\"\"Holds the responsibility of performing a step-by-step, sequential update\n of the subtopics structure based on the schema version of the input\n subtopics dictionary. If the current subtopics schema changes, a\n new conversion function must be added and some code appended to this\n function to account for that new version.\n\n Args:\n versioned_subtopics: dict. A dict with two keys:\n - schema_version: int. The schema version for the subtopics dict.\n - subtopics: list(dict). The list of dicts comprising the topic's\n subtopics.\n topic_id: str. The id of the topic to which the subtopics are part of.\n\n Raises:\n Exception. The schema version of subtopics is outside of what\n is supported at present.\n \"\"\"\n subtopic_schema_version = versioned_subtopics['schema_version']\n if not (1 <= subtopic_schema_version\n <= feconf.CURRENT_SUBTOPIC_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v1-v%d subtopic schemas at '\n 'present.' % feconf.CURRENT_SUBTOPIC_SCHEMA_VERSION)\n\n while (subtopic_schema_version <\n feconf.CURRENT_SUBTOPIC_SCHEMA_VERSION):\n topic_domain.Topic.update_subtopics_from_model(\n versioned_subtopics, subtopic_schema_version, topic_id)\n subtopic_schema_version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _normalizeSubelements(objtype, subelements):\n # pylint: disable=R0911\n # Deal with simple cases first\n if objtype is None:\n # Don't know how to handle it\n return _stringify(subelements)\n\n if not subelements:\n # No subelements available\n if isinstance(objtype, usix.ListType):\n # Expect a list of things - return the empty list\n return []\n # Expected a scalar type\n return None\n\n # We do have subelements\n # Extract all the non-string subelements\n _s = []\n _strings_only = 1\n for subel in subelements:\n if _is_string(subel) and not subel.strip():\n # Ignore it for now\n continue\n _s.append(subel)\n if not _is_string(subel):\n _strings_only = 0\n\n if _strings_only:\n # Multiple strings - contactenate into one\n subelements = [\"\".join(subelements)]\n else:\n # Ignore whitespaces around elements\n subelements = _s\n\n if not isinstance(objtype, usix.ListType):\n if len(subelements) > 1:\n # pylint: disable-next=broad-exception-raised\n raise Exception(\"Expected a scalar, got back a list\")\n subelement = subelements[0]\n # NULL?\n if isinstance(subelement, Node):\n if subelement.name == \"rhn-null\":\n return None\n # pylint: disable-next=broad-exception-raised\n raise Exception(\n # pylint: disable-next=consider-using-f-string\n \"Expected a scalar, got back an element '%s'\"\n % subelement.name\n )\n\n if objtype is usix.StringType:\n return _stringify(subelement)\n\n if objtype is usix.IntType:\n if subelement == \"\":\n # Treat it as NULL\n return None\n return int(subelement)\n\n if objtype is importLib.DateType:\n return _normalizeDateType(subelement)\n # pylint: disable-next=broad-exception-raised,consider-using-f-string\n raise Exception(\"Unhandled type %s for subelement %s\" % (objtype, subelement))\n\n # Expecting a list of things\n expectedType = objtype[0]\n if expectedType is usix.StringType:\n # List of strings\n return list(map(_stringify, subelements))\n\n if expectedType is usix.IntType:\n # list of ints\n return list(map(int, subelements))\n\n if expectedType is importLib.DateType:\n return list(map(_normalizeDateType, subelements))\n\n # A subelement\n result = []\n for subelement in subelements:\n item = _createItem(subelement)\n if item is None:\n # Item processor not found\n continue\n if not isinstance(item, expectedType):\n # pylint: disable-next=broad-exception-raised\n raise Exception(\n # pylint: disable-next=consider-using-f-string\n \"Expected type %s, got back %s %s\"\n % (expectedType, type(item), item)\n )\n result.append(item)\n\n return result", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def update_analytics_constants_based_on_config(\n release_analytics_constants_path: str,\n analytics_constants_config_path: str\n) -> None:\n \"\"\"Updates the GA4 and UA IDs in the analytics constants JSON file.\n\n Args:\n release_analytics_constants_path: str. The path to constants file.\n analytics_constants_config_path: str. The path to constants config file.\n\n Raises:\n Exception. No GA_ANALYTICS_ID key found.\n Exception. No SITE_NAME_FOR_ANALYTICS key found.\n Exception. No CAN_SEND_ANALYTICS_EVENTS key found.\n \"\"\"\n with utils.open_file(analytics_constants_config_path, 'r') as config_file:\n config_file_contents = config_file.read()\n ga_analytics_searched_key = re.search(\n r'\"GA_ANALYTICS_ID\": \"(.*)\"', config_file_contents)\n if ga_analytics_searched_key is None:\n raise Exception(\n 'Error: No GA_ANALYTICS_ID key found.'\n )\n ga_analytics_id = ga_analytics_searched_key.group(1)\n site_name_for_analytics_searched_key = re.search(\n r'\"SITE_NAME_FOR_ANALYTICS\": \"(.*)\"', config_file_contents)\n if site_name_for_analytics_searched_key is None:\n raise Exception(\n 'Error: No SITE_NAME_FOR_ANALYTICS key found.'\n )\n site_name_for_analytics = site_name_for_analytics_searched_key.group(1)\n can_send_analytics_events_searched_key = re.search(\n r'\"CAN_SEND_ANALYTICS_EVENTS\": (true|false)',\n config_file_contents)\n if can_send_analytics_events_searched_key is None:\n raise Exception(\n 'Error: No CAN_SEND_ANALYTICS_EVENTS key found.'\n )\n can_send_analytics_events = can_send_analytics_events_searched_key.group(1)\n common.inplace_replace_file(\n release_analytics_constants_path,\n '\"GA_ANALYTICS_ID\": \"\"',\n '\"GA_ANALYTICS_ID\": \"%s\"' % ga_analytics_id)\n common.inplace_replace_file(\n release_analytics_constants_path,\n '\"SITE_NAME_FOR_ANALYTICS\": \"\"',\n '\"SITE_NAME_FOR_ANALYTICS\": \"%s\"' % site_name_for_analytics)\n common.inplace_replace_file(\n release_analytics_constants_path,\n '\"CAN_SEND_ANALYTICS_EVENTS\": false',\n '\"CAN_SEND_ANALYTICS_EVENTS\": %s' % can_send_analytics_events)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_maintenance_failure_recovery(self):\n backend = RedisBackend()\n\n record_1 = Record(\"record:1\", self.notification, time.time())\n backend.add(\"timeline\", record_1)\n\n try:\n with backend.digest(\"timeline\", 0) as records:\n raise Exception(\"This causes the digest to not be closed.\")\n except Exception:\n pass\n\n # Maintenance should move the timeline back to the waiting state, ...\n backend.maintenance(time.time())\n\n # ...and you can't send a digest in the waiting state.\n with pytest.raises(InvalidState):\n with backend.digest(\"timeline\", 0) as records:\n pass\n\n record_2 = Record(\"record:2\", self.notification, time.time())\n backend.add(\"timeline\", record_2)\n\n # The schedule should now contain the timeline.\n assert {entry.key for entry in backend.schedule(time.time())} == {\"timeline\"}\n\n # The existing and new record should be there because the timeline\n # contents were merged back into the digest.\n with backend.digest(\"timeline\", 0) as records:\n assert {record.key for record in records} == {\"record:1\", \"record:2\"}", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@tile_description.setter\n def tile_description(\n self, td=None):\n \"\"\"\n Set the tile description\n \n :param td: tile description\n :type td: cutlass.backend.TileDescription, or a dict with keys\n {\n \"threadblock_shape\": [int, int, int],\n \"warp_count\": [int, int, int],\n \"stages\": int,\n \"instruction_shape\": [int, int, int] (optional),\n \"cluster_shape\": [int, int, int] (optional)\n }\n \"\"\"\n if td is None:\n return\n if isinstance(td, dict):\n if self._tile_description is None:\n alignment = list(self.possible_operations.kernels_by_alignment.keys())[0]\n op = self.possible_operations.operations(alignment)[0]\n self._tile_description = datatypes.td_from_profiler_op(op)\n if \"cluster_shape\" in td.keys():\n if td[\"cluster_shape\"] != [1, 1, 1]:\n cutlass.logger.warning(\"Conv2d currently only support 'cluster_shape'=[1, 1, 1]'.\")\n td[\"cluster_shape\"] = [1, 1, 1] \n td = self._tile_description.clone_and_update(td)\n\n valid, msg = self._valid_tile_description(td)\n if valid:\n self._tile_description = td\n else:\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def main():\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n parser.add_argument(\n \"file\", type=Path, metavar='FILE', nargs='?',\n default=DEFAULT_MANIFEST_PATH,\n help=f\"file with the stable abi manifest (default: {DEFAULT_MANIFEST_PATH})\",\n )\n parser.add_argument(\n \"--generate\", action='store_true',\n help=\"generate file(s), rather than just checking them\",\n )\n parser.add_argument(\n \"--generate-all\", action='store_true',\n help=\"as --generate, but generate all file(s) using default filenames.\"\n + \" (unlike --all, does not run any extra checks)\",\n )\n parser.add_argument(\n \"-a\", \"--all\", action='store_true',\n help=\"run all available checks using default filenames\",\n )\n parser.add_argument(\n \"-l\", \"--list\", action='store_true',\n help=\"list available generators and their default filenames; then exit\",\n )\n parser.add_argument(\n \"--dump\", action='store_true',\n help=\"dump the manifest contents (used for debugging the parser)\",\n )\n\n actions_group = parser.add_argument_group('actions')\n for gen in generators:\n actions_group.add_argument(\n gen.arg_name, dest=gen.var_name,\n type=str, nargs=\"?\", default=MISSING,\n metavar='FILENAME',\n help=gen.__doc__,\n )\n actions_group.add_argument(\n '--unixy-check', action='store_true',\n help=do_unixy_check.__doc__,\n )\n args = parser.parse_args()\n\n base_path = args.file.parent.parent\n\n if args.list:\n for gen in generators:\n print(f'{gen.arg_name}: {(base_path / gen.default_path).resolve()}')\n sys.exit(0)\n\n run_all_generators = args.generate_all\n\n if args.generate_all:\n args.generate = True\n\n if args.all:\n run_all_generators = True\n if UNIXY:\n args.unixy_check = True\n\n try:\n file = args.file.open('rb')\n except FileNotFoundError as err:\n if args.file.suffix == '.txt':\n # Provide a better error message\n suggestion = args.file.with_suffix('.toml')\n raise FileNotFoundError(\n f'{args.file} not found. Did you mean {suggestion} ?') from err\n raise\n with file:\n manifest = parse_manifest(file)\n\n check_private_names(manifest)\n\n # Remember results of all actions (as booleans).\n # At the end we'll check that at least one action was run,\n # and also fail if any are false.\n results = {}\n\n if args.dump:\n for line in manifest.dump():\n print(line)\n results['dump'] = check_dump(manifest, args.file)\n\n for gen in generators:\n filename = getattr(args, gen.var_name)\n if filename is None or (run_all_generators and filename is MISSING):\n filename = base_path / gen.default_path\n elif filename is MISSING:\n continue\n\n results[gen.var_name] = generate_or_check(manifest, args, filename, gen)\n\n if args.unixy_check:\n results['unixy_check'] = do_unixy_check(manifest, args)\n\n if not results:\n if args.generate:\n parser.error('No file specified. Use --generate-all to regenerate '\n + 'all files, or --help for usage.')\n parser.error('No check specified. Use --all to check all files, '\n + 'or --help for usage.')\n\n failed_results = [name for name, result in results.items() if not result]\n\n if failed_results:\n raise Exception(f\"\"\"\n These checks related to the stable ABI did not succeed:\n {', '.join(failed_results)}\n\n If you see diffs in the output, files derived from the stable\n ABI manifest the were not regenerated.\n Run `make regen-limited-abi` to fix this.\n\n Otherwise, see the error(s) above.\n\n The stable ABI manifest is at: {args.file}\n Note that there is a process to follow when modifying it.\n\n You can read more about the limited API and its contracts at:\n\n https://docs.python.org/3/c-api/stable.html\n\n And in PEP 384:\n\n https://peps.python.org/pep-0384/\n \"\"\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def load_graph_from_args(\n pipeline_name: str, framework: str, model: str, tokenizer: Optional[str] = None, **models_kwargs\n) -> Pipeline:\n \"\"\"\n Convert the set of arguments provided through the CLI to an actual pipeline reference (tokenizer + model\n\n Args:\n pipeline_name: The kind of pipeline to use (ner, question-answering, etc.)\n framework: The actual model to convert the pipeline from (\"pt\" or \"tf\")\n model: The model name which will be loaded by the pipeline\n tokenizer: The tokenizer name which will be loaded by the pipeline, default to the model's value\n\n Returns: Pipeline object\n\n \"\"\"\n # If no tokenizer provided\n if tokenizer is None:\n tokenizer = model\n\n # Check the wanted framework is available\n if framework == \"pt\" and not is_torch_available():\n raise Exception(\"Cannot convert because PyTorch is not installed. Please install torch first.\")\n if framework == \"tf\" and not is_tf_available():\n raise Exception(\"Cannot convert because TF is not installed. Please install tensorflow first.\")\n\n print(f\"Loading pipeline (model: {model}, tokenizer: {tokenizer})\")\n\n # Allocate tokenizer and model\n return pipeline(pipeline_name, model=model, tokenizer=tokenizer, framework=framework, model_kwargs=models_kwargs)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def __init__(self, tool_config):\n self.session = requests.Session()\n if tool_config.authentication_type == \"API\":\n self.api_token = tool_config.api_key\n self.session.headers.update(\n {\"Authorization\": f\"Token {self.api_token}\"},\n )\n self.session.headers.update(self.default_headers)\n else:\n msg = f\"bugcrowd Authentication type {tool_config.authentication_type} not supported\"\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def get_organization_id(organization_members: Sequence[OrganizationMember]) -> int:\n \"\"\"Ensure all organization_members have the same organization ID and then return that ID.\"\"\"\n organization_ids = {\n organization_member.organization_id for organization_member in organization_members\n }\n if len(organization_ids) != 1:\n raise Exception(\"Cannot determine organization\")\n return int(organization_ids.pop())", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def update_interaction_solution(\n self, solution: Optional[Solution]\n ) -> None:\n \"\"\"Update the solution of interaction.\n\n Args:\n solution: Solution|None. Object of class Solution.\n\n Raises:\n Exception. The 'solution' is not a domain object.\n \"\"\"\n old_content_id_list = []\n new_content_id_list = []\n if self.interaction.solution:\n old_content_id_list.append(\n self.interaction.solution.explanation.content_id)\n\n if solution is not None:\n if not isinstance(solution, Solution):\n raise Exception(\n 'Expected solution to be a Solution object,received %s'\n % solution)\n self.interaction.solution = solution\n new_content_id_list.append(\n self.interaction.solution.explanation.content_id)\n else:\n self.interaction.solution = None\n\n self._update_content_ids_in_assets(\n old_content_id_list, new_content_id_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_unfurl_discover_html_escaped(self, mock_generate_chart, _):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?field=title&amp;field=event.type&amp;field=project&amp;field=user.display&amp;field=timestamp&amp;name=All+Events&amp;project={self.project.id}&amp;query=&amp;sort=-timestamp&amp;statsPeriod=24h\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature([\"organizations:discover-basic\"]):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count()\"\n assert len(chart_data[\"stats\"][\"data\"]) == INTERVALS_PER_DAY", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def test_override_update(self):\n OrderedDict = self.OrderedDict\n # Verify that subclasses can override update() without breaking __init__()\n class MyOD(OrderedDict):\n def update(self, *args, **kwds):\n raise Exception()\n items = [('a', 1), ('c', 3), ('b', 2)]\n self.assertEqual(list(MyOD(items).items()), items)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "@sensitive_variables()\n@sensitive_post_parameters()\ndef custom_exception_reporter_filter_view(request):\n # Do not just use plain strings for the variables' values in the code\n # so that the tests don't return false positives when the function's source\n # is displayed in the exception report.\n cooked_eggs = \"\".join([\"s\", \"c\", \"r\", \"a\", \"m\", \"b\", \"l\", \"e\", \"d\"]) # NOQA\n sauce = \"\".join( # NOQA\n [\"w\", \"o\", \"r\", \"c\", \"e\", \"s\", \"t\", \"e\", \"r\", \"s\", \"h\", \"i\", \"r\", \"e\"]\n )\n request.exception_reporter_filter = UnsafeExceptionReporterFilter()\n try:\n raise Exception\n except Exception:\n exc_info = sys.exc_info()\n send_log(request, exc_info)\n return technical_500_response(request, *exc_info)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@unittest.skipUnless(hasattr(signal, 'pthread_kill'),\n 'need signal.pthread_kill()')\n @threading_helper.requires_working_threading()\n def test_pthread_kill_main_thread(self):\n # Test that a signal can be sent to the main thread with pthread_kill()\n # before any other thread has been created (see issue #12392).\n code = \"\"\"if True:\n import threading\n import signal\n import sys\n\n def handler(signum, frame):\n sys.exit(3)\n\n signal.signal(signal.SIGUSR1, handler)\n signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)\n sys.exit(2)\n \"\"\"\n\n with spawn_python('-c', code) as process:\n stdout, stderr = process.communicate()\n exitcode = process.wait()\n if exitcode != 3:\n raise Exception(\"Child error (exit code %s): %s\" %\n (exitcode, stdout))", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def __exit__(self, *_):\n while time.time() < self.timeout:\n if self.page_has_loaded():\n return True\n time.sleep(0.2)\n msg = f\"Timeout waiting for {self.timeout}s\"\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def _get_uri(url):\n if openc3.script.OPENC3_IN_CLUSTER:\n match OPENC3_CLOUD:\n case \"local\":\n bucket_url = os.environ.get(\"OPENC3_BUCKET_URL\", \"http://openc3-minio:9000\")\n return f\"{bucket_url}{url}\"\n case \"aws\":\n return f\"https://s3.{os.getenv('AWS_REGION')}.amazonaws.com{url}\"\n case \"gcp\":\n return f\"https://storage.googleapis.com{url}\"\n # when 'azure'\n case _:\n raise Exception(f\"Unknown cloud {OPENC3_CLOUD}\")\n else:\n return f\"{openc3.script.API_SERVER.generate_url()}{url}\"", "smellKey": "S112", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def _verify_scalar(self, scalar, ref_scalar, ref_dtype, name):\n \"\"\"\n Verifies the following properties:\n 1) Either ``scalar`` or ``ref_scakar`` must be set (i.e., not ``None``)\n 2) If ``scalar`` is not ``None``, its datatype must match matches the current version\n set by the plan (i.e., those in ``ref_dtype``)\n\n If either of these properties does not hold, an exception is raised. If these properties hold and\n ``scalar`` is not ``None``, ``scalar`` is returned. Otherwise, ``ref_scalar`` is returned.\n\n :param scalar: object representing a tensor passed in to verify, or ``None`` if no tensor was passed in\n :type scalar: numpy/cupy/torch scalar\n :param ref_scalar: object representing a tensor passed in on construction of this object, or ``None`` if no tensor was passed in\n :type ref_scalar: numpy/cupy/torch scalar\n :param ref_dtype: data type for the scalar that this object was initialized to\n :param name: identifier of the scalar to verify. Used in raising exceptions\n :type name: str\n\n :return: valid scalar to use\n :rtype: numpy/cupy/torch scalar\n \"\"\"\n if scalar is None:\n if ref_scalar is None:\n raise Exception(f\"Scalar {name} must be set.\")\n return ref_scalar\n if hasattr(scalar, \"dtype\"):\n dtype = datatypes.library_type(scalar.dtype)\n if dtype != ref_dtype:\n raise Exception(\n f\"Tensor {name} with type {dtype} does not match expected type {ref_dtype}.\"\n )\n return scalar", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def add_from_file(self, f):\n \"\"\"\n Loads a pre-existing dictionary from a text file and adds its symbols to this instance.\n \"\"\"\n if isinstance(f, str):\n try:\n with open(f, \"r\", encoding=\"utf-8\") as fd:\n self.add_from_file(fd)\n except FileNotFoundError as fnfe:\n raise fnfe\n except UnicodeError:\n raise Exception(f\"Incorrect encoding detected in {f}, please rebuild the dataset\")\n return\n\n lines = f.readlines()\n for lineTmp in lines:\n line = lineTmp.strip()\n idx = line.rfind(\" \")\n if idx == -1:\n raise ValueError(\"Incorrect dictionary format, expected '<token> <cnt>'\")\n word = line[:idx]\n self.encoder[word] = len(self.encoder)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def parse(this, s):\n if this._parse(byref(this), s) is None:\n raise Exception(\"Parse failure\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_pulseaudio", "language": "python"} {"function": "def send_email_to_recipients(\n sender_email: str,\n recipient_emails: List[str],\n subject: str,\n plaintext_body: str,\n html_body: str,\n bcc: Optional[List[str]] = None,\n reply_to: Optional[str] = None,\n recipient_variables: Optional[\n Dict[str, Dict[str, Union[str, float]]]] = None\n) -> bool:\n \"\"\"Send POST HTTP request to mailgun api. This method is adopted from\n the requests library's post method.\n\n Args:\n sender_email: str. The email address of the sender. This should be in\n the form 'SENDER_NAME <SENDER_EMAIL_ADDRESS>' or\n 'SENDER_EMAIL_ADDRESS'. Must be utf-8.\n recipient_emails: list(str). The email addresses of the recipients.\n Must be utf-8.\n subject: str. The subject line of the email, Must be utf-8.\n plaintext_body: str. The plaintext body of the email. Must be utf-8.\n html_body: str. The HTML body of the email. Must fit in a datastore\n entity. Must be utf-8.\n bcc: list(str)|None. Optional argument. List of bcc emails.\n reply_to: str|None. Optional argument. Reply address formatted like\n \u201creply+<reply_id>@<incoming_email_domain_name>\n reply_id is the unique id of the sender.\n recipient_variables: dict|None. Optional argument. If batch sending\n requires differentiating each email based on the recipient, we\n assign a unique id to each recipient, including info relevant to\n that recipient so that we can reference it when composing the\n email like so:\n recipient_variables =\n {\"bob@example.com\": {\"first\":\"Bob\", \"id\":1},\n \"alice@example.com\": {\"first\":\"Alice\", \"id\":2}}\n subject = 'Hey, %recipient.first%\u2019\n More info about this format at:\n https://documentation.mailgun.com/en/\n latest/user_manual.html#batch-sending.\n\n Raises:\n Exception. The mailgun api key is not stored in\n feconf.MAILGUN_API_KEY.\n Exception. The mailgun domain name is not stored in\n feconf.MAILGUN_DOMAIN_NAME.\n\n Returns:\n bool. Whether the emails are sent successfully.\n \"\"\"\n mailgun_api_key: Optional[str] = secrets_services.get_secret(\n 'MAILGUN_API_KEY')\n if mailgun_api_key is None:\n raise Exception('Mailgun API key is not available.')\n\n if not feconf.MAILGUN_DOMAIN_NAME:\n raise Exception('Mailgun domain name is not set.')\n\n # To send bulk emails we pass list of recipients in 'to' paarameter of\n # post data. Maximum limit of recipients per request is 1000.\n # For more detail check following link:\n # https://documentation.mailgun.com/user_manual.html#batch-sending\n recipient_email_lists = [\n recipient_emails[i:i + 1000]\n for i in range(0, len(recipient_emails), 1000)]\n for email_list in recipient_email_lists:\n data = {\n 'from': sender_email,\n 'subject': subject.encode('utf-8'),\n 'text': plaintext_body.encode('utf-8'),\n 'html': html_body.encode('utf-8'),\n 'to': email_list[0] if len(email_list) == 1 else email_list\n }\n\n if bcc:\n data['bcc'] = bcc[0] if len(bcc) == 1 else bcc\n\n if reply_to:\n data['h:Reply-To'] = reply_to\n\n # 'recipient-variable' in post data forces mailgun to send individual\n # email to each recipient (This is intended to be a workaround for\n # sending individual emails).\n data['recipient_variables'] = recipient_variables or {}\n\n # The b64encode accepts and returns bytes, so we first need to encode\n # the MAILGUN_API_KEY to bytes, then decode the returned bytes back\n # to string.\n base64_mailgun_api_key = base64.b64encode(\n b'api:%b' % mailgun_api_key.encode('utf-8')\n ).strip().decode('utf-8')\n auth_str = 'Basic %s' % base64_mailgun_api_key\n header = {'Authorization': auth_str}\n server = 'https://api.mailgun.net/v3/%s/messages' % (\n feconf.MAILGUN_DOMAIN_NAME\n )\n # The 'ascii' is used here, because only ASCII char are allowed in url,\n # also the docs recommend this approach:\n # https://docs.python.org/3.7/library/urllib.request.html#urllib-examples\n encoded_url = urllib.parse.urlencode(data).encode('ascii')\n req = urllib.request.Request(server, encoded_url, header)\n resp = utils.url_open(req)\n # The function url_open returns a file_like object that can be queried\n # for the status code of the url query. If it is not 200, the mail query\n # failed so we return False (this function did not complete\n # successfully).\n if resp.getcode() != 200:\n return False\n return True", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def verify_target_branch_does_not_already_exist(\n remote_alias: str, new_branch_name: str\n) -> None:\n \"\"\"Checks that the new release branch doesn't already exist locally or\n remotely.\n\n Args:\n remote_alias: str. The alias that points to the remote oppia\n repository. Example: When calling git remote -v, you get:\n upstream https://github.com/oppia/oppia.git (fetch),\n where 'upstream' is the alias that points to the remote oppia\n repository.\n new_branch_name: str. The name of the new branch to cut.\n\n Raises:\n Exception. The target branch name already exists locally.\n Exception. The target branch name already exists on the remote\n oppia repository.\n \"\"\"\n\n git_branch_output = subprocess.check_output(\n ['git', 'branch'], encoding='utf-8'\n ).split('\\n')\n if new_branch_name in git_branch_output:\n raise Exception(\n 'ERROR: The target branch name already exists locally. '\n 'Run \"git branch -D %s\" to delete it.' % new_branch_name)\n git_ls_remote_output = subprocess.check_output(\n ['git', 'ls-remote', '--heads', remote_alias], encoding='utf-8'\n ).split('\\n')\n remote_branch_ref = 'refs/heads/%s' % new_branch_name\n if remote_branch_ref in git_ls_remote_output:\n raise Exception(\n 'ERROR: The target branch name already exists on the remote repo.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_response_without_checking_for_errors(\n self,\n url: str,\n expected_status_int_list: List[int],\n http_method: Optional[str] = 'GET',\n params: Optional[Dict[str, str]] = None\n ) -> webtest.TestResponse:\n \"\"\"Get a response, transformed to a Python object and checks for a list\n of status codes.\n\n Args:\n url: str. The URL to fetch the response.\n expected_status_int_list: list(int). A list of integer status code\n to expect.\n http_method: str. The http method by which the request is to be \n sent.\n params: dict. A dictionary that will be encoded into a query string.\n\n Returns:\n webtest.TestResponse. The test response.\n\n Raises:\n Exception. If the http method is not one of GET, POST, PUT or\n DELETE, then this exception is raised.\n \"\"\"\n if params is not None:\n self.assertIsInstance(\n params, dict,\n msg='Expected params to be a dict, received %s' % params)\n\n # This swap is required to ensure that the templates are fetched from\n # source directory instead of webpack_bundles since webpack_bundles is\n # only produced after webpack compilation which is not performed during\n # backend tests.\n with self.swap(base, 'load_template', mock_load_template):\n\n if http_method == 'GET':\n response = self.testapp.get(\n url, params=params, expect_errors=True\n )\n\n if http_method == 'POST':\n response = self.testapp.post(\n url, params=params, expect_errors=True\n )\n elif http_method == 'PUT':\n response = self.testapp.put(\n url, params=params, expect_errors=True\n )\n elif http_method == 'DELETE':\n response = self.testapp.delete(\n url, params=params, expect_errors=True\n )\n elif http_method != 'GET':\n raise Exception('Invalid http method %s' % http_method)\n\n self.assertIn(response.status_int, expected_status_int_list)\n\n return response", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def validate_explorations_for_story(\n exp_ids: List[str], strict: bool\n) -> List[str]:\n \"\"\"Validates the explorations in the given story and checks whether they\n are compatible with the mobile app and ready for publishing.\n\n Args:\n exp_ids: list(str). The exp IDs to validate.\n strict: bool. Whether to raise an Exception when a validation error\n is encountered. If not, a list of the error messages are\n returned. strict should be True when this is called before\n saving the story and False when this function is called from the\n frontend.\n\n Returns:\n list(str). The various validation error messages (if strict is\n False).\n\n Raises:\n ValidationError. Expected story to only reference valid explorations.\n ValidationError. Exploration with ID is not public. Please publish\n explorations before adding them to a story.\n ValidationError. All explorations in a story should be of the same\n category.\n Exception. Exploration validation failed for given exploration IDs.\n \"\"\"\n validation_error_messages = []\n\n # Strict = False, since the existence of explorations is checked below.\n exps_dict = (\n exp_fetchers.get_multiple_explorations_by_id(exp_ids, strict=False))\n\n exp_rights = (\n rights_manager.get_multiple_exploration_rights_by_ids(exp_ids))\n\n exp_rights_dict = {}\n\n for rights in exp_rights:\n if rights is not None:\n exp_rights_dict[rights.id] = rights.status\n\n for exp_id in exp_ids:\n if exp_id not in exps_dict:\n error_string = (\n 'Expected story to only reference valid explorations, but found'\n ' a reference to an invalid exploration with ID: %s'\n % exp_id)\n if strict:\n raise utils.ValidationError(error_string)\n validation_error_messages.append(error_string)\n else:\n if exp_rights_dict[exp_id] != constants.ACTIVITY_STATUS_PUBLIC:\n error_string = (\n 'Exploration with ID %s is not public. Please publish '\n 'explorations before adding them to a story.'\n % exp_id)\n if strict:\n raise utils.ValidationError(error_string)\n validation_error_messages.append(error_string)\n\n if exps_dict:\n for exp_id, exp in exps_dict.items():\n if exp.category not in constants.ALL_CATEGORIES:\n error_string = (\n 'All explorations in a story should be of a '\n 'default category. The exploration with ID %s has'\n ' an invalid category %s.' % (exp_id, exp.category))\n if strict:\n raise utils.ValidationError(error_string)\n validation_error_messages.append(error_string)\n\n if exps_dict:\n for exp_id in exp_ids:\n if exp_id in exps_dict:\n sample_exp_id = exp_id\n break\n common_exp_category = exps_dict[sample_exp_id].category\n for exp_id, exp in exps_dict.items():\n if exp.category != common_exp_category:\n error_string = (\n 'All explorations in a story should be of the '\n 'same category. The explorations with ID %s and %s have'\n ' different categories.' % (sample_exp_id, exp_id))\n if strict:\n raise utils.ValidationError(error_string)\n validation_error_messages.append(error_string)\n try:\n validation_error_messages.extend(\n exp_services.validate_exploration_for_story(exp, strict))\n except Exception as e:\n logging.exception(\n 'Exploration validation failed for exploration with ID: '\n '%s. Error: %s' % (exp_id, e))\n raise Exception(e) from e\n\n return validation_error_messages", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_exc_info():\n try:\n loop = Exception(\"Loop\")\n loop.__cause__ = loop\n loop.__context__ = loop\n raise loop\n except Exception:\n return sys.exc_info()", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_all_actions(roles: List[str]) -> List[str]:\n \"\"\"Returns a list of all actions that can be performed by the given role.\n\n Args:\n roles: list(str). A list of strings defining the user roles.\n\n Returns:\n list(str). A list of actions accessible to the role.\n\n Raises:\n Exception. The given role does not exist.\n \"\"\"\n role_actions = set()\n for role in roles:\n if role not in _ROLE_ACTIONS:\n raise Exception('Role %s does not exist.' % role)\n\n role_actions |= set(_ROLE_ACTIONS[role])\n\n return list(role_actions)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@sensitive_variables(\"sauce\")\n@sensitive_post_parameters(\"bacon-key\", \"sausage-key\")\ndef sensitive_view(request):\n # Do not just use plain strings for the variables' values in the code\n # so that the tests don't return false positives when the function's source\n # is displayed in the exception report.\n cooked_eggs = \"\".join([\"s\", \"c\", \"r\", \"a\", \"m\", \"b\", \"l\", \"e\", \"d\"]) # NOQA\n sauce = \"\".join( # NOQA\n [\"w\", \"o\", \"r\", \"c\", \"e\", \"s\", \"t\", \"e\", \"r\", \"s\", \"h\", \"i\", \"r\", \"e\"]\n )\n try:\n raise Exception\n except Exception:\n exc_info = sys.exc_info()\n send_log(request, exc_info)\n return technical_500_response(request, *exc_info)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def populate_test_data(tournament: models.AsyncTournament, participant_count: int = 1):\n \"\"\"\n Populates a tournament with test data for each permalink.\n Will use fake Discord User IDs for the racers that'll be in the range of 1 to 100000, which is smaller than a real ID.\n This should only be ran in a local testing environment.\n \"\"\"\n\n # only run this in a local testing environment\n if not config.DEBUG:\n raise Exception(\"This function should only be ran in a local testing environment.\")\n\n await tournament.fetch_related(\"permalink_pools\")\n\n # create specified number of fake users\n offset = random.randint(1, 1000) * 1000\n for i in range(1, participant_count + 1):\n # create a fake user, set a test_user flag to true so we can delete them later if needed\n user = await models.Users.create(\n discord_id=i + offset,\n display_name=f\"Test User {i + offset}\",\n test_user=True\n )\n # iterate through each pool in the tournament, using our existing algorithm to pick a permalink\n for pool in tournament.permalink_pools:\n permalink = await get_eligible_permalink_from_pool(pool, user)\n await models.AsyncTournamentRace.create(\n tournament=tournament,\n thread_id=random.randint(1, 10000000000000),\n user=user,\n thread_open_time=discord.utils.utcnow(),\n permalink=permalink,\n status=\"finished\",\n start_time=discord.utils.utcnow(),\n end_time=discord.utils.utcnow() + timedelta(seconds=random.randint(3600000, 7200000) / 1000),\n )", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "def __load_driver(self, path):\n # check driver status\n if self._driver is not None:\n raise Exception(\"already load driver\")\n # load driver\n self._driver = cdll.LoadLibrary(path)", "smellKey": "S112", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def add_target(self, target_name, target_config_dir):\n parser = ConfigParser()\n folder_name = f\"{target_config_dir}/{target_name}\"\n if not os.path.exists(folder_name):\n raise parser.error(f\"Target folder must exist '{folder_name}'.\")\n\n target = Target(target_name, target_config_dir)\n System.targets[target.name] = target\n errors = [] # Store all errors processing the cmd_tlm files\n try:\n for cmd_tlm_file in target.cmd_tlm_files:\n self.packet_config.process_file(cmd_tlm_file, target.name)\n except Exception as error:\n trace = \"\".join(traceback.TracebackException.from_exception(error).format())\n errors.append(f\"Error processing {target_name}:\\n{trace}\")\n if len(errors) != 0:\n raise Exception(\"\\n\".join(errors))", "smellKey": "S112", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def nested_simplify(obj, decimals=3):\n \"\"\"\n Simplifies an object by rounding float numbers, and downcasting tensors/numpy arrays to get simple equality test\n within tests.\n \"\"\"\n import numpy as np\n\n if isinstance(obj, list):\n return [nested_simplify(item, decimals) for item in obj]\n if isinstance(obj, tuple):\n return tuple([nested_simplify(item, decimals) for item in obj])\n elif isinstance(obj, np.ndarray):\n return nested_simplify(obj.tolist())\n elif isinstance(obj, Mapping):\n return {nested_simplify(k, decimals): nested_simplify(v, decimals) for k, v in obj.items()}\n elif isinstance(obj, (str, int, np.int64)):\n return obj\n elif obj is None:\n return obj\n elif is_torch_available() and isinstance(obj, torch.Tensor):\n return nested_simplify(obj.tolist(), decimals)\n elif is_tf_available() and tf.is_tensor(obj):\n return nested_simplify(obj.numpy().tolist())\n elif isinstance(obj, float):\n return round(obj, decimals)\n elif isinstance(obj, (np.int32, np.float32, np.float16)):\n return nested_simplify(obj.item(), decimals)\n else:\n raise Exception(f\"Not supported: {type(obj)}\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def main():\n if not authToken or authToken == \"\":\n raise Exception(\"Please set META_DUMPER_AUTH_HEADER\")\n # Upload the index.json.\n with scoped_cwd(ELECTRON_DIR):\n safe_mkdir(OUT_DIR)\n index_json = os.path.relpath(os.path.join(OUT_DIR, 'index.json'))\n\n new_content = get_content()\n\n with open(index_json, \"wb\") as f:\n f.write(new_content)\n\n store_artifact(OUT_DIR, 'headers/dist', [index_json])", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_electron", "language": "python"} {"function": "async def run(self):\n self.stats_mgr = RelayWebsocketStatsManager(self.local_hostname)\n self.stats_mgr.start()\n\n database_conf = deepcopy(settings.DATABASES['default'])\n database_conf['OPTIONS'] = deepcopy(database_conf.get('OPTIONS', {}))\n\n for k, v in settings.LISTENER_DATABASES.get('default', {}).items():\n if k != 'OPTIONS':\n database_conf[k] = v\n for k, v in settings.LISTENER_DATABASES.get('default', {}).get('OPTIONS', {}).items():\n database_conf['OPTIONS'][k] = v\n\n if 'PASSWORD' in database_conf:\n database_conf['OPTIONS']['password'] = database_conf.pop('PASSWORD')\n\n async_conn = await psycopg.AsyncConnection.connect(\n dbname=database_conf['NAME'],\n host=database_conf['HOST'],\n user=database_conf['USER'],\n port=database_conf['PORT'],\n **database_conf.get(\"OPTIONS\", {}),\n )\n\n await async_conn.set_autocommit(True)\n on_ws_heartbeat_task = asyncio.get_running_loop().create_task(\n self.on_ws_heartbeat(async_conn),\n name=\"WebSocketRelayManager.on_ws_heartbeat\",\n )\n\n # Establishes a websocket connection to /websocket/relay on all API servers\n while True:\n if on_ws_heartbeat_task.done():\n raise Exception(\"on_ws_heartbeat_task has exited\")\n\n future_remote_hosts = self.known_hosts.keys()\n current_remote_hosts = self.relay_connections.keys()\n deleted_remote_hosts = set(current_remote_hosts) - set(future_remote_hosts)\n new_remote_hosts = set(future_remote_hosts) - set(current_remote_hosts)\n\n # This loop handles if we get an advertisement from a host we already know about but\n # the advertisement has a different IP than we are currently connected to.\n for hostname, address in self.known_hosts.items():\n if hostname not in self.relay_connections:\n # We've picked up a new hostname that we don't know about yet.\n continue\n\n if address != self.relay_connections[hostname].remote_host:\n deleted_remote_hosts.add(hostname)\n new_remote_hosts.add(hostname)\n\n # Delete any hosts with closed connections\n for hostname, relay_conn in self.relay_connections.items():\n if not relay_conn.connected:\n deleted_remote_hosts.add(hostname)\n\n if deleted_remote_hosts:\n logger.info(f\"Removing {deleted_remote_hosts} from websocket broadcast list\")\n await asyncio.gather(*[self.cleanup_offline_host(h) for h in deleted_remote_hosts])\n\n if new_remote_hosts:\n logger.info(f\"Adding {new_remote_hosts} to websocket broadcast list\")\n\n for h in new_remote_hosts:\n stats = self.stats_mgr.new_remote_host_stats(h)\n relay_connection = WebsocketRelayConnection(name=self.local_hostname, stats=stats, remote_host=self.known_hosts[h])\n relay_connection.start()\n self.relay_connections[h] = relay_connection\n\n await asyncio.sleep(settings.BROADCAST_WEBSOCKET_NEW_INSTANCE_POLL_RATE_SECONDS)", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def test_load_cert_chain(self):\n ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n # Combined key and cert in a single file\n ctx.load_cert_chain(CERTFILE, keyfile=None)\n ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE)\n self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE)\n with self.assertRaises(OSError) as cm:\n ctx.load_cert_chain(NONEXISTINGCERT)\n self.assertEqual(cm.exception.errno, errno.ENOENT)\n with self.assertRaisesRegex(ssl.SSLError, \"PEM (lib|routines)\"):\n ctx.load_cert_chain(BADCERT)\n with self.assertRaisesRegex(ssl.SSLError, \"PEM (lib|routines)\"):\n ctx.load_cert_chain(EMPTYCERT)\n # Separate key and cert\n ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n ctx.load_cert_chain(ONLYCERT, ONLYKEY)\n ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)\n ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)\n with self.assertRaisesRegex(ssl.SSLError, \"PEM (lib|routines)\"):\n ctx.load_cert_chain(ONLYCERT)\n with self.assertRaisesRegex(ssl.SSLError, \"PEM (lib|routines)\"):\n ctx.load_cert_chain(ONLYKEY)\n with self.assertRaisesRegex(ssl.SSLError, \"PEM (lib|routines)\"):\n ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)\n # Mismatching key and cert\n ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n # Allow for flexible libssl error messages.\n regex = re.compile(r\"\"\"(\n key values mismatch # OpenSSL\n |\n KEY_VALUES_MISMATCH # AWS-LC\n )\"\"\", re.X)\n with self.assertRaisesRegex(ssl.SSLError, regex):\n ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY)\n # Password protected key and cert\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD)\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode())\n ctx.load_cert_chain(CERTFILE_PROTECTED,\n password=bytearray(KEY_PASSWORD.encode()))\n ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD)\n ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode())\n ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED,\n bytearray(KEY_PASSWORD.encode()))\n with self.assertRaisesRegex(TypeError, \"should be a string\"):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=True)\n with self.assertRaises(ssl.SSLError):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=\"badpass\")\n with self.assertRaisesRegex(ValueError, \"cannot be longer\"):\n # openssl has a fixed limit on the password buffer.\n # PEM_BUFSIZE is generally set to 1kb.\n # Return a string larger than this.\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400)\n # Password callback\n def getpass_unicode():\n return KEY_PASSWORD\n def getpass_bytes():\n return KEY_PASSWORD.encode()\n def getpass_bytearray():\n return bytearray(KEY_PASSWORD.encode())\n def getpass_badpass():\n return \"badpass\"\n def getpass_huge():\n return b'a' * (1024 * 1024)\n def getpass_bad_type():\n return 9\n def getpass_exception():\n raise Exception('getpass error')\n class GetPassCallable:\n def __call__(self):\n return KEY_PASSWORD\n def getpass(self):\n return KEY_PASSWORD\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode)\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes)\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray)\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable())\n ctx.load_cert_chain(CERTFILE_PROTECTED,\n password=GetPassCallable().getpass)\n with self.assertRaises(ssl.SSLError):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass)\n with self.assertRaisesRegex(ValueError, \"cannot be longer\"):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge)\n with self.assertRaisesRegex(TypeError, \"must return a string\"):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type)\n with self.assertRaisesRegex(Exception, \"getpass error\"):\n ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception)\n # Make sure the password function isn't called if it isn't needed\n ctx.load_cert_chain(CERTFILE, password=getpass_exception)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def ParseOneCameraBlockC(ioCameraBlock, ioCameraBlockJson, inPipeAndViewsState):\n #parse camera type\n if 'camera type' not in ioCameraBlockJson:\n errStr = 'error! camera block with name ' + str(ioCameraBlock.mName) + \\\n ' has no camera type key in ParseCameraBlocksC\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n cameraType = ioCameraBlockJson['camera type']\n\n if cameraType != 'camera' and cameraType != 'multicamera8':\n errStr = 'camera type entry is not recognized in camera ' + ioCameraBlock.mName + ' ParseCameraBlocksC\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n ioCameraBlock.mType = cameraType\n\n #check for camera at node|element displaced settings\n ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \\\n ioCameraBlockJson, \"camera at \", \" displaced\", True)\n if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting == False:\n #check for camera at settings (not displaced) if there weren't displaced ones\n ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \\\n ioCameraBlockJson, \"camera at \", \"\", False)\n if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting:\n ioCameraBlock.mUseCameraAtPointFlag = True\n else:\n ioCameraBlock.mUseCameraAtPointFlag = False\n\n if PhactoriDbg():\n myDebugPrint3(\"camera parsing look at point:\\n\")\n ioCameraBlock.mLookAtPointInfo.UserPointInfoParseParametersFromJson(ioCameraBlockJson,\n \"look at \", \"\")\n\n #parse look at distance\n if 'look at relative distance' in ioCameraBlockJson:\n ioCameraBlock.mLookAtDistanceType = 'datasize relative'\n ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at relative distance']\n #if 'camera at point' was specified, look at distance should not\n #be specified\n elif 'look at absolute distance' in ioCameraBlockJson:\n ioCameraBlock.mLookAtDistanceType = 'absolute'\n ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at absolute distance']\n #if 'camera at point' was specified, look at distance should not\n #be specified\n else:\n ioCameraBlock.mLookAtDistanceType = 'datasize relative'\n ioCameraBlock.mLookAtDistance = 1.0\n\n #parse look direction (single camera, not multicamera8)\n if ioCameraBlock.mType == 'camera':\n ioCameraBlock.mLookDirection = [-1.0, -1.0, -1.0]\n if 'look direction' in ioCameraBlockJson:\n ioCameraBlock.mLookDirection = ioCameraBlockJson['look direction']\n ioCameraBlock.mLookDirectionSpecifiedFlag = True\n else:\n ioCameraBlock.mLookDirectionSpecifiedFlag = False\n \n #get text to add to each image created with this camera, if any\n if \"image name addon\" in ioCameraBlockJson:\n ioCameraBlock.mFilenameAddon = ioCameraBlockJson[\"image name addon\"]\n\n #camera field of view (for default use current value which was set at\n #creation time--see class definition for default\n ioCameraBlock.mViewAngle = getParameterFromBlock(ioCameraBlockJson,\n 'camera fov', ioCameraBlock.mViewAngle)\n\n #up vector for the view (for default use current value which was set at\n #creation time--see class definition for default)\n ioCameraBlock.mViewUpVector = getParameterFromBlock(ioCameraBlockJson,\n 'up vector', ioCameraBlock.mViewUpVector)\n\n #parse off-axis projection info\n ioCameraBlock.mOffAxisProjectionInfo.ParseParametersFromJson(\n ioCameraBlockJson)\n\n #parse parallel projection info\n perspectiveOrParallel = getParameterFromBlock(ioCameraBlockJson,\n 'projection type', 'perspective')\n if perspectiveOrParallel == 'parallel':\n ioCameraBlock.mUseParallelProjection = True\n if PhactoriDbg(100):\n myDebugPrint3(\"projection type is now parallel\\n\", 100)\n if 'absolute parallel scale' in ioCameraBlockJson:\n ioCameraBlock.mParallelScaleAbsoluteOrRelative = 0\n ioCameraBlock.mParallelScale = \\\n ioCameraBlockJson['absolute parallel scale']\n if PhactoriDbg(100):\n myDebugPrint3(\"absolute parallel scale: \" + \\\n str(ioCameraBlock.mParallelScale) + \"\\n\", 100)\n elif 'relative parallel scale' in ioCameraBlockJson:\n ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1\n ioCameraBlock.mParallelScale = \\\n ioCameraBlockJson['relative parallel scale']\n if PhactoriDbg(100):\n myDebugPrint3(\"relative parallel scale: \" + \\\n str(ioCameraBlock.mParallelScale) + \"\\n\", 100)\n else:\n ioCameraBlock.mParallelScale = 1.0\n ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1\n if PhactoriDbg(100):\n myDebugPrint3(\"default relative parallel scale: \" + \\\n str(ioCameraBlock.mParallelScale) + \"\\n\", 100)\n\n #parse locking setup\n ioCameraBlock.LockAfterNCalls = getParameterFromBlock(ioCameraBlockJson,\n 'lock camera call count', -1)\n if \"lockingcamera\" in ioCameraBlock.mName:\n ioCameraBlock.LockAfterNCalls = 1", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def assign_coordinator(\n committer: user_domain.UserActionsInfo,\n assignee: user_domain.UserActionsInfo,\n language_id: str\n) -> None:\n \"\"\"Assigns a new role to the user.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user\n who is performing the action.\n assignee: UserActionsInfo. UserActionsInfo object for the user\n whose role is being changed.\n language_id: str. ID of the language.\n\n Raises:\n Exception. The committer does not have rights to modify a role.\n Exception. The assignee is already coordinator for this language.\n Exception. Guest user is not allowed to assign roles to a user.\n Exception. The role of the Guest user cannot be changed.\n \"\"\"\n committer_id = committer.user_id\n if committer_id is None:\n raise Exception(\n 'Guest user is not allowed to assign roles to a user.'\n )\n\n if (\n role_services.ACTION_MODIFY_CORE_ROLES_FOR_ANY_ACTIVITY not in\n committer.actions\n ):\n logging.error(\n 'User %s tried to allow user %s to be a coordinator of language %s '\n 'but was refused permission.' % (\n committer_id, assignee.user_id, language_id))\n raise Exception(\n 'UnauthorizedUserException: Could not assign new role.')\n\n if assignee.user_id is None:\n raise Exception(\n 'Cannot change the role of the Guest user.'\n )\n\n language_rights = suggestion_models.TranslationCoordinatorsModel.get(\n language_id, strict=False)\n\n if language_rights is None:\n model = suggestion_models.TranslationCoordinatorsModel(\n id=language_id,\n coordinator_ids=[assignee.user_id],\n coordinators_count=1\n )\n model.update_timestamps()\n model.put()\n else:\n if assignee.user_id in language_rights.coordinator_ids:\n raise Exception(\n 'This user already is a coordinator for this language.'\n )\n\n language_rights.coordinator_ids.append(assignee.user_id)\n language_rights.coordinators_count += 1\n\n suggestion_models.TranslationCoordinatorsModel.update_timestamps(\n language_rights,\n update_last_updated_time=True)\n suggestion_models.TranslationCoordinatorsModel.put(\n language_rights)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _migrate_to_latest_action_schema(\n learner_action_dict: stats_domain.LearnerActionDict\n) -> None:\n \"\"\"Holds the responsibility of performing a step-by-step sequential update\n of an learner action dict based on its schema version. If the current action\n schema version changes (stats_models.CURRENT_ACTION_SCHEMA_VERSION), a new\n conversion function must be added and some code appended to this function to\n account for that new version.\n\n Args:\n learner_action_dict: dict. Dict representing the learner action.\n\n Raises:\n Exception. The action_schema_version is invalid.\n \"\"\"\n action_schema_version = learner_action_dict['schema_version']\n if action_schema_version is None or action_schema_version < 1:\n action_schema_version = 0\n\n if not (0 <= action_schema_version\n <= stats_models.CURRENT_ACTION_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v1-v%d and unversioned action schemas '\n 'at present.' %\n stats_models.CURRENT_ACTION_SCHEMA_VERSION)\n\n while action_schema_version < stats_models.CURRENT_ACTION_SCHEMA_VERSION:\n stats_domain.LearnerAction.update_learner_action_from_model(\n learner_action_dict)\n action_schema_version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def split_by_type(\n activity_references: List[activity_domain.ActivityReference]\n) -> Tuple[List[str], List[str]]:\n \"\"\"Given a list of activity references, returns two lists: the first list\n contains the exploration ids, and the second contains the collection ids.\n The elements in each of the returned lists are in the same order as those\n in the input list.\n\n Args:\n activity_references: list(ActivityReference). The domain object\n containing exploration ids and collection ids.\n\n Returns:\n tuple(list(str), list(str)). A 2-tuple whose first element is a list of\n all exploration ids represented in the input list, and whose second\n element is a list of all collection ids represented in the input list.\n\n Raises:\n Exception. The activity reference type is invalid.\n \"\"\"\n exploration_ids, collection_ids = [], []\n for activity_reference in activity_references:\n if activity_reference.type == constants.ACTIVITY_TYPE_EXPLORATION:\n exploration_ids.append(activity_reference.id)\n elif activity_reference.type == constants.ACTIVITY_TYPE_COLLECTION:\n collection_ids.append(activity_reference.id)\n else:\n raise Exception(\n 'Invalid activity reference: (%s, %s)' %\n (activity_reference.type, activity_reference.id))\n\n return exploration_ids, collection_ids", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_file_name(job_id):\n #print(f\"Fetching job id {job_id}\")\n url = f\"http://192.168.56.159/api/v2/jobs/{job_id}/stdout/?format=json\"\n\n try:\n response_job = requests.get(url, headers=HEADERS)\n content = response_job.json()[\"content\"]\n\n index = content.index(\"\\\"dest\\\"\")\n start = content.index(\"\\\"\", index + 6) + 1\n end = content.index(\"\\\"\", start)\n\n path = content[start:end]\n file_name = path.split(\"/\")[-1]\n if file_name == \"\":\n raise Exception(\"File name empty!\")\n return file_name\n except:\n return \"Not Present\"", "smellKey": "S112", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "def parameters(self: \"Job\") -> dict[str, Any]:\n \"\"\"Returns the parameters used to start the job. Job tries to use its params field, but\n if that's None, then it makes a call to EE2.\n\n If no exception is raised, this only returns the list of parameters, NOT the whole\n object fetched from ee2.check_job\n \"\"\"\n if self.params is None:\n try:\n state = self.query_ee2_states([self.job_id], init=True)\n self.update_state(state[self.job_id])\n except Exception as e:\n raise Exception(f\"Unable to fetch parameters for job {self.job_id} - {e}\") from e\n\n return self.params", "smellKey": "S112", "smellId": null, "repo": "kbase_narrative", "language": "python"} {"function": "def main(argv):\n try: assert 0\n except AssertionError: pass\n else: raise Exception(\"fatal error - assertions not enabled\")\n shortopts, longopts = \"qv\", [\n \"bfdname=\", \"dry-run\", \"elfosabi=\", \"quiet\", \"verbose\"\n ]\n xopts, args = getopt.gnu_getopt(argv[1:], shortopts, longopts)\n for opt, optarg in xopts:\n if 0: pass\n elif opt in [\"-q\", \"--quiet\"]: opts.verbose = opts.verbose - 1\n elif opt in [\"-v\", \"--verbose\"]: opts.verbose = opts.verbose + 1\n elif opt in [\"--dry-run\"]: opts.dry_run = opts.dry_run + 1\n elif opt in [\"--bfdname\"]: opts.bfdname = optarg.lower()\n elif opt in [\"--elfosabi\"]: opts.elfosabi = optarg.lower()\n else: assert 0, (\"getopt problem:\", opt, optarg, xopts, args)\n # process arguments\n if not args:\n raise Exception, \"error: no arguments given\"\n for arg in args:\n do_file(arg)\n return 0", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_upx", "language": "python"} {"function": "@staticmethod\n def getBridgeDetails(name):\n try:\n network = OvmNetwork()\n if name not in network.bridges.keys():\n raise Exception(\"No bridge %s found\"%name)\n bridge = network.bridges[name]\n rs = fromOvmBridge(bridge)\n logger.debug(OvmNetwork.getBridgeDetails, rs)\n return rs\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmNetwork.getBridgeDetails, errmsg)\n raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.getBridgeDetails), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def __call__(self, x: Tensor):\n \"\"\"\n Transfer the weights of `self.src` to `self.dest` by performing a forward pass using `x` as input. Under the\n hood we tracked all the operations in both modules.\n \"\"\"\n dest_traced = Tracker(self.dest)(x).parametrized\n src_traced = Tracker(self.src)(x).parametrized\n\n src_traced = list(filter(lambda x: type(x) not in self.src_skip, src_traced))\n dest_traced = list(filter(lambda x: type(x) not in self.dest_skip, dest_traced))\n\n if len(dest_traced) != len(src_traced):\n raise Exception(\n f\"Numbers of operations are different. Source module has {len(src_traced)} operations while\"\n f\" destination module has {len(dest_traced)}.\"\n )\n\n for dest_m, src_m in zip(dest_traced, src_traced):\n dest_m.load_state_dict(src_m.state_dict())\n if self.verbose == 1:\n print(f\"Transfered from={src_m} to={dest_m}\")", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def recursive_merge_binaries(src0, src1, dst):\n \"\"\"\n Merges two build trees together for different architectures into a single\n universal binary.\n\n The rules for merging are:\n\n 1) Files that exist in either src tree are copied into the dst tree\n 2) Files that exist in both trees and are identical are copied over\n unmodified\n 3) Files that exist in both trees and are non-identical are lipo'd\n 4) Symlinks are created in the destination tree to mirror the hierarchy in\n the source trees\n \"\"\"\n\n # Check that all files present in the folder are of the same type and that\n # links link to the same relative location\n for newpath0 in glob.glob(src0+\"/*\"):\n filename = os.path.basename(newpath0)\n newpath1 = os.path.join(src1, filename)\n if not os.path.exists(newpath1):\n continue\n\n if os.path.islink(newpath0) and os.path.islink(newpath1):\n if os.path.relpath(newpath0, src0) == os.path.relpath(newpath1, src1):\n continue\n\n if os.path.isdir(newpath0) and os.path.isdir(newpath1):\n continue\n\n # isfile() can be true for links so check that both are not links\n # before checking if they are both files\n if (not os.path.islink(newpath0)) and (not os.path.islink(newpath1)):\n if os.path.isfile(newpath0) and os.path.isfile(newpath1):\n continue\n\n raise Exception(f\"{newpath0} and {newpath1} cannot be \" +\n \"merged into a universal binary because they are of \" +\n \"incompatible types. Perhaps the installed libraries\" +\n \" are from different versions for each architecture\")\n\n for newpath0 in glob.glob(src0+\"/*\"):\n filename = os.path.basename(newpath0)\n newpath1 = os.path.join(src1, filename)\n new_dst_path = os.path.join(dst, filename)\n if os.path.islink(newpath0):\n # Symlinks will be fixed after files are resolved\n continue\n\n if not os.path.exists(newpath1):\n if os.path.isdir(newpath0):\n shutil.copytree(newpath0, new_dst_path)\n else:\n shutil.copy(newpath0, new_dst_path)\n\n continue\n\n if os.path.isdir(newpath1):\n os.mkdir(new_dst_path)\n recursive_merge_binaries(newpath0, newpath1, new_dst_path)\n continue\n\n if filecmp.cmp(newpath0, newpath1):\n shutil.copy(newpath0, new_dst_path)\n else:\n lipo(newpath0, newpath1, new_dst_path)\n\n # Loop over files in src1 and copy missing things over to dst\n for newpath1 in glob.glob(src1+\"/*\"):\n filename = os.path.basename(newpath1)\n newpath0 = os.path.join(src0, filename)\n new_dst_path = os.path.join(dst, filename)\n if (not os.path.exists(newpath0)) and (not os.path.islink(newpath1)):\n if os.path.isdir(newpath1):\n shutil.copytree(newpath1, new_dst_path)\n else:\n shutil.copy(newpath1, new_dst_path)\n\n # Fix up symlinks for path0\n for newpath0 in glob.glob(src0+\"/*\"):\n filename = os.path.basename(newpath0)\n new_dst_path = os.path.join(dst, filename)\n if os.path.islink(newpath0):\n relative_path = os.path.relpath(os.path.realpath(newpath0), src0)\n os.symlink(relative_path, new_dst_path)\n # Fix up symlinks for path1\n for newpath1 in glob.glob(src1+\"/*\"):\n filename = os.path.basename(newpath1)\n new_dst_path = os.path.join(dst, filename)\n newpath0 = os.path.join(src0, filename)\n if os.path.islink(newpath1) and not os.path.exists(newpath0):\n relative_path = os.path.relpath(os.path.realpath(newpath1), src1)\n os.symlink(relative_path, new_dst_path)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_dolphin", "language": "python"} {"function": "def validate_referrer(referrer: str | None) -> None:\n if not referrer:\n return\n\n if referrer in VALUES:\n return\n\n for suffix in VALID_SUFFIXES:\n if referrer.removesuffix(f\".{suffix}\") in VALUES:\n return\n\n error_message = f\"referrer {referrer} is not part of Referrer Enum\"\n\n try:\n raise Exception(error_message)\n except Exception:\n metrics.incr(\"snql.sdk.api.new_referrers\", tags={\"referrer\": referrer})\n logger.warning(error_message, exc_info=True)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def HandleOperationShortcuts2(inBlockName, inJson, ioOperationBlocks, inCount):\n if PhactoriDbg(100):\n myDebugPrint3('HandleOperationShortcuts entered2\\n', 100)\n\n lastShortcutOperationName = None\n\n opSuffix = str(inCount)\n\n if \"threshold\" in inJson:\n stuff = inJson[\"threshold\"]\n if len(stuff) != 4:\n errStr = 'HandleOperationShortcuts2 threshold shortcut bad stuff, not 4 items\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n #stuff should have 4 items \n #[scalar|vector magnitude|vector component|tensor\n #component, component<variable name>, namekeep between|keep above|keep\n #below, [<val1>, <val2>]]\n newOperationJson = {}\n newOperationJson[\"type\"] = \"threshold\"\n varkey = \"variable \" + stuff[0]\n newOperationJson[varkey] = stuff[1]\n thresholdValues = stuff[3]\n if stuff[2] == \"keep between\":\n newOperationJson[\"keep between\"] = thresholdValues\n elif stuff[2] == \"keep below\":\n newOperationJson[\"keep below\"] = thresholdValues[0]\n elif stuff[2] == \"keep above\":\n newOperationJson[\"keep above\"] = thresholdValues[0]\n else:\n errStr = 'HandleOperationShortcuts2 bad stuff[2], not keep above|below|between\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n \n if PhactoriDbg():\n myDebugPrint3('got threshold operation shortcut ' + str(newOperationJson) + '\\n')\n if lastShortcutOperationName != None:\n newOperationJson[\"input\"] = lastShortcutOperationName\n lastShortcutOperationName = \"thresholdshortcutoperation\" + opSuffix\n ioOperationBlocks[lastShortcutOperationName] = newOperationJson\n\n\n if \"boxclip\" in inJson:\n stuff = inJson[\"boxclip\"]\n if len(stuff) != 3:\n errStr = 'HandleOperationShortcuts2 boxclip shortcut bad stuff, not 3 items\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n center = stuff[0]\n extents = stuff[1]\n insideOrOutside = stuff[2]\n\n newOperationJson = {}\n newOperationJson[\"type\"] = \"boxclip\"\n newOperationJson[\"center at absolute point\"] = center\n newOperationJson[\"absolute extents\"] = extents\n if insideOrOutside == \"keep inside box\":\n newOperationJson[\"keep inside box\"] = True\n elif insideOrOutside == \"keep outside box\":\n newOperationJson[\"keep inside box\"] = False\n else:\n newOperationJson[\"keep inside box\"] = True\n\n if PhactoriDbg():\n myDebugPrint3('got boxclip operation shortcut ' + str(newOperationJson) + '\\n')\n if lastShortcutOperationName != None:\n newOperationJson[\"input\"] = lastShortcutOperationName\n lastShortcutOperationName = \"boxclipshortcutoperation\" + opSuffix\n ioOperationBlocks[lastShortcutOperationName] = newOperationJson\n\n if \"clip\" in inJson:\n stuff = inJson[\"clip\"]\n if len(stuff) != 2:\n errStr = 'HandleOperationShortcuts2 clip shortcut bad stuff, not 2 items\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n pointOnPlane = stuff[0]\n planeNormal = stuff[1]\n if PhactoriDbg():\n myDebugPrint3('got clip operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\\n')\n newOperationJson = {\"type\":\"clip\", \"absolute point on plane\":pointOnPlane, \"plane normal\":planeNormal}\n if lastShortcutOperationName != None:\n newOperationJson[\"input\"] = lastShortcutOperationName\n lastShortcutOperationName = \"clipshortcutoperation\" + opSuffix\n ioOperationBlocks[lastShortcutOperationName] = newOperationJson\n\n if \"contour\" in inJson:\n stuff = inJson[\"contour\"]\n if len(stuff) != 4:\n errStr = 'HandleOperationShortcuts2 contour shortcut bad stuff, not 4 items\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n variableInfo = stuff[0]\n variableName = stuff[1]\n valueListOrSequence = stuff[2]\n contourValues = stuff[3]\n newOperationJson = {}\n newOperationJson[\"type\"] = \"contour\"\n varkey = \"variable \" + variableInfo\n newOperationJson[varkey] = variableName\n if (valueListOrSequence.lower()==\"value list\"):\n newOperationJson[\"contour value\"] = contourValues\n elif (valueListOrSequence.lower()==\"value sequence\"):\n newOperationJson[\"contour value sequence\"]=contourValues\n else:\n errStr = \"\"\"error! contour shortcut did not contain 'value list' or 'value sequence' in\n HandleOperationShortcuts2\\n\"\"\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n if lastShortcutOperationName != None:\n newOperationJson[\"input\"] = lastShortcutOperationName\n lastShortcutOperationName = \"contourshortcutoperation\" + opSuffix\n ioOperationBlocks[lastShortcutOperationName] = newOperationJson\n\n if \"slice\" in inJson:\n stuff = inJson[\"slice\"]\n if len(stuff) != 2:\n errStr = 'HandleOperationShortcuts2 slice shortcut bad stuff, not 2 items\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n pointOnPlane = stuff[0]\n planeNormal = stuff[1]\n if PhactoriDbg():\n myDebugPrint3('got slice operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\\n')\n newOperationJson = {\"type\":\"slice\", \"absolute point on plane\":pointOnPlane, \"plane normal\":planeNormal}\n if lastShortcutOperationName != None:\n newOperationJson[\"input\"] = lastShortcutOperationName\n lastShortcutOperationName = \"sliceshortcutoperation\" + opSuffix\n ioOperationBlocks[lastShortcutOperationName] = newOperationJson\n\n if lastShortcutOperationName != None:\n inJson[\"operation\"] = lastShortcutOperationName\n if PhactoriDbg(100):\n myDebugPrint3('HandleOperationShortcuts returning\\n', 100)", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _get_and_verify_conv_problem_size(self, A, B, C, stride, padding, dilation):\n if self.conv_kind == cutlass_bindings.conv.Operator.fprop:\n input = A\n weight = B\n output = C\n output_tensor = \"C\"\n elif self.conv_kind == cutlass_bindings.conv.Operator.dgrad:\n output = A\n weight = B\n input = C\n output_tensor = \"A\"\n elif self.conv_kind == cutlass_bindings.conv.Operator.wgrad:\n output = A\n input = B\n weight = C\n output_tensor = \"A\"\n else:\n raise Exception(f\"Convolution kind {self.conv_kind} is not supported\")\n\n N_, H_, W_, C_ = datatypes.get_tensor_shape(input)\n K_, R_, S_, _ = datatypes.get_tensor_shape(weight)\n _, P_, Q_, _ = datatypes.get_tensor_shape(output)\n \n problem_size = cutlass_bindings.conv.Conv2dProblemSize(\n cutlass_bindings.Tensor4DCoord(N_, H_, W_, C_),\n cutlass_bindings.Tensor4DCoord(K_, R_, S_, C_),\n cutlass_bindings.Tensor4DCoord(padding[0], padding[0], padding[1], padding[1]),\n cutlass_bindings.MatrixCoord(stride[0], stride[1]),\n cutlass_bindings.MatrixCoord(dilation[0], dilation[1]),\n cutlass_bindings.conv.Mode.cross_correlation,\n 1, 1\n )\n \n if P_ != problem_size.P or Q_ != problem_size.Q:\n raise Exception(\n f\"Tensor {output_tensor} size should be ({N_}, {problem_size.P}, {problem_size.Q}, {K_}), got ({N_}, {P_}, {Q_}, {K_})\")\n \n return problem_size", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def get_content_type(self, obj=None, id=None, using=None, model=None):\n if obj is not None:\n return ContentType.objects.db_manager(obj._state.db).get_for_model(\n obj, for_concrete_model=self.for_concrete_model\n )\n elif id is not None:\n return ContentType.objects.db_manager(using).get_for_id(id)\n elif model is not None:\n return ContentType.objects.db_manager(using).get_for_model(\n model, for_concrete_model=self.for_concrete_model\n )\n else:\n # This should never happen. I love comments like this, don't you?\n raise Exception(\"Impossible arguments to GFK.get_content_type!\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ParseParametersFromJson(self, inJson):\n\n self.mBypassFlag = getParameterFromBlock(inJson, 'bypass flag',\n self.mBypassFlag)\n if self.mBypassFlag == True:\n #this operation is bypassed: don't do other parsing\n return\n\n foundVariableFlag = self.mVariableInfo.\\\n ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')\n\n if foundVariableFlag == False:\n errStr = \"error! inJson has no variable info in\\n PhactoriContourOperation.ParseParametersFromJson\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n if 'contour value' in inJson:\n self.mContourValue = inJson['contour value']\n elif 'contour value sequence' in inJson:\n seqCntrl = inJson['contour value sequence']\n rStart = seqCntrl[0]\n rStep = seqCntrl[1]\n rEnd = seqCntrl[2]\n self.mContourValue = []\n rVal = rStart\n if rEnd > rStart:\n if rStep <= 0.0:\n errStr = \"error! bad contour value sequence in\\n PhactoriContourOperation.ParseParametersFromJson\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n while rVal < rEnd:\n self.mContourValue.append(rVal)\n rVal += rStep\n else:\n if rStep >= 0.0:\n errStr = \"error! bad contour value sequence in\\n PhactoriContourOperation.ParseParametersFromJson\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n while rVal > rEnd:\n self.mContourValue.append(rVal)\n rVal += rStep\n else:\n errStr = \"error! inJson has no 'contour value' or 'contour value sequence' key in\\n PhactoriContourOperation.ParseParametersFromJson\\n\"\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def validate_email_dashboard_data(\n data: Dict[str, Optional[Union[bool, int]]]\n) -> Dict[str, Optional[Union[bool, int]]]:\n \"\"\"Validates email dashboard data.\n\n Args:\n data: dict. Data that needs to be validated.\n\n Returns:\n dict. Returns the dict after validation.\n\n Raises:\n Exception. The key in 'data' is not one of the allowed keys.\n \"\"\"\n predicates = constants.EMAIL_DASHBOARD_PREDICATE_DEFINITION\n possible_keys = [predicate['backend_attr'] for predicate in predicates]\n\n for key, value in data.items():\n if value is None:\n continue\n if key not in possible_keys:\n # Raise exception if key is not one of the allowed keys.\n raise Exception('400 Invalid input for query.')\n # The method returns a dict containing fields of email dashboard\n # query params. This dict represents the UserQueryParams class, which is a\n # namedtuple. Hence the fields of the dict are being validated as a part of\n # schema validation before saving new user queries in the handler.\n return data", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@classmethod\n def create_default_context(cls, *args, **kwargs):\n raise Exception(\"no ssl support\") # pylint: disable=broad-exception-raised", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def deassign_user_from_all_languages(\n committer: user_domain.UserActionsInfo, user_id: str\n) -> None:\n \"\"\"Deassigns given user from all languages assigned to them.\n\n Args:\n committer: UserActionsInfo. UserActionsInfo object for the user\n who is performing the action.\n user_id: str. The ID of the user.\n\n Raises:\n Exception. Guest users are not allowed to deassign users from\n all languages.\n \"\"\"\n translation_rights_list = get_translation_rights_with_user(user_id)\n if committer.user_id is None:\n raise Exception(\n 'Guest users are not allowed to deassign users from all languages.'\n )\n\n for translation_rights in translation_rights_list:\n translation_rights.coordinator_ids.remove(user_id)\n translation_rights.coordinators_count -= 1\n language_rights = suggestion_models.TranslationCoordinatorsModel(\n id=translation_rights.language_id,\n coordinator_ids=translation_rights.coordinator_ids,\n coordinators_count=translation_rights.coordinators_count)\n suggestion_models.TranslationCoordinatorsModel.update_timestamps(\n language_rights,\n update_last_updated_time=True)\n suggestion_models.TranslationCoordinatorsModel.put(\n language_rights)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def server_error(request):\n raise Exception(\"Error in view\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _migrate_collection_contents_to_latest_schema(\n versioned_collection_contents: collection_domain.VersionedCollectionDict\n) -> None:\n \"\"\"Holds the responsibility of performing a step-by-step, sequential update\n of the collection structure based on the schema version of the input\n collection dictionary. This is very similar to the exploration migration\n process seen in exp_services. If any of the current collection schemas\n change, a new conversion function must be added and some code appended to\n this function to account for that new version.\n\n Args:\n versioned_collection_contents: dict. A dict with two keys:\n - schema_version: int. The schema version for the collection.\n - collection_contents: dict. The dict comprising the collection\n contents.\n\n Raises:\n Exception. The schema version of the collection is outside of what is\n supported at present.\n \"\"\"\n collection_schema_version = versioned_collection_contents['schema_version']\n if not (1 <= collection_schema_version\n <= feconf.CURRENT_COLLECTION_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v1-v%d collection schemas at '\n 'present.' % feconf.CURRENT_COLLECTION_SCHEMA_VERSION)\n\n while (collection_schema_version <\n feconf.CURRENT_COLLECTION_SCHEMA_VERSION):\n collection_domain.Collection.update_collection_contents_from_model(\n versioned_collection_contents, collection_schema_version)\n collection_schema_version += 1", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "async def create_agent_with_args(args, ident: str = None, extra_args: list = None):\n if (\"did_exchange\" in args and args.did_exchange) and args.mediation:\n raise Exception(\n \"DID-Exchange connection protocol is not (yet) compatible with mediation\"\n )\n\n check_requires(args)\n\n if \"revocation\" in args and args.revocation:\n tails_server_base_url = args.tails_server_base_url or os.getenv(\n \"PUBLIC_TAILS_URL\"\n )\n else:\n tails_server_base_url = None\n\n arg_file = args.arg_file or os.getenv(\"ACAPY_ARG_FILE\")\n arg_file_dict = {}\n if arg_file:\n with open(arg_file) as f:\n arg_file_dict = yaml.safe_load(f)\n if args.log_file or args.log_file == \"\":\n log_file = args.log_file\n else:\n log_file = os.getenv(\"ACAPY_LOG_FILE\")\n log_config = args.log_config or os.getenv(\"ACAPY_LOG_CONFIG\")\n log_level = args.log_level\n # if we don't have a tails server url then guess it\n if (\"revocation\" in args and args.revocation) and not tails_server_base_url:\n # assume we're running in docker\n tails_server_base_url = (\n \"http://\" + (os.getenv(\"DOCKERHOST\") or \"host.docker.internal\") + \":6543\"\n )\n\n if (\"revocation\" in args and args.revocation) and not tails_server_base_url:\n raise Exception(\n \"If revocation is enabled, --tails-server-base-url must be provided\"\n )\n\n multi_ledger_config_path = None\n genesis = None\n if \"multi_ledger\" in args and args.multi_ledger:\n multi_ledger_config_path = \"./demo/multi_ledger_config.yml\"\n else:\n genesis = await default_genesis_txns()\n if not genesis and not multi_ledger_config_path:\n print(\"Error retrieving ledger genesis transactions\")\n sys.exit(1)\n\n agent_ident = ident if ident else (args.ident if \"ident\" in args else \"Aries\")\n\n if \"aip\" in args:\n aip = int(args.aip)\n if aip not in [\n 10,\n 20,\n ]:\n raise Exception(\"Invalid value for aip, should be 10 or 20\")\n else:\n aip = 20\n\n if \"cred_type\" in args and args.cred_type not in [\n CRED_FORMAT_INDY,\n CRED_FORMAT_VC_DI,\n ]:\n public_did = None\n aip = 20\n elif \"cred_type\" in args and args.cred_type in [\n CRED_FORMAT_INDY,\n CRED_FORMAT_VC_DI,\n ]:\n public_did = True\n else:\n public_did = args.public_did if \"public_did\" in args else None\n\n cred_type = args.cred_type if \"cred_type\" in args else None\n log_msg(\n f\"Initializing demo agent {agent_ident} with AIP {aip} and credential type {cred_type}\"\n )\n\n reuse_connections = \"reuse_connections\" in args and args.reuse_connections\n # if reuse_connections and aip != 20:\n # raise Exception(\"Can only specify `--reuse-connections` with AIP 2.0\")\n multi_use_invitations = \"multi_use_invitations\" in args and args.multi_use_invitations\n if multi_use_invitations and aip != 20:\n raise Exception(\"Can only specify `--multi-use-invitations` with AIP 2.0\")\n public_did_connections = (\n \"public_did_connections\" in args and args.public_did_connections\n )\n if public_did_connections and aip != 20:\n raise Exception(\"Can only specify `--public-did-connections` with AIP 2.0\")\n\n anoncreds_legacy_revocation = None\n if \"anoncreds_legacy_revocation\" in args and args.anoncreds_legacy_revocation:\n anoncreds_legacy_revocation = args.anoncreds_legacy_revocation\n\n emit_did_peer_2 = \"emit_did_peer_2\" in args and args.emit_did_peer_2\n emit_did_peer_4 = \"emit_did_peer_4\" in args and args.emit_did_peer_4\n\n agent = AgentContainer(\n genesis_txns=genesis,\n genesis_txn_list=multi_ledger_config_path,\n ident=agent_ident + \".agent\",\n start_port=args.port,\n no_auto=args.no_auto,\n revocation=args.revocation if \"revocation\" in args else False,\n tails_server_base_url=tails_server_base_url,\n show_timing=args.timing,\n multitenant=args.multitenant,\n mediation=args.mediation,\n cred_type=cred_type,\n use_did_exchange=(aip == 20) if (\"aip\" in args) else args.did_exchange,\n wallet_type=arg_file_dict.get(\"wallet-type\") or args.wallet_type,\n public_did=public_did,\n seed=\"random\" if public_did else None,\n arg_file=arg_file,\n aip=aip,\n endorser_role=args.endorser_role,\n reuse_connections=reuse_connections,\n multi_use_invitations=multi_use_invitations,\n public_did_connections=public_did_connections,\n emit_did_peer_2=emit_did_peer_2,\n emit_did_peer_4=emit_did_peer_4,\n taa_accept=args.taa_accept,\n anoncreds_legacy_revocation=anoncreds_legacy_revocation,\n log_file=log_file,\n log_config=log_config,\n log_level=log_level,\n extra_args=extra_args,\n )\n\n return agent", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def generate_reply_email(contact_email: str, alias: Alias) -> str:\n \"\"\"\n generate a reply_email (aka reverse-alias), make sure it isn't used by any contact\n \"\"\"\n # shorten email to avoid exceeding the 64 characters\n # from https://tools.ietf.org/html/rfc5321#section-4.5.3\n # \"The maximum total length of a user name or other local-part is 64\n # octets.\"\n\n include_sender_in_reverse_alias = False\n\n user = alias.user\n # user has set this option explicitly\n if user.include_sender_in_reverse_alias is not None:\n include_sender_in_reverse_alias = user.include_sender_in_reverse_alias\n\n if include_sender_in_reverse_alias and contact_email:\n # make sure contact_email can be ascii-encoded\n contact_email = convert_to_id(contact_email)\n contact_email = sanitize_email(contact_email)\n contact_email = contact_email[:45]\n # use _ instead of . to avoid AC_FROM_MANY_DOTS SpamAssassin rule\n contact_email = contact_email.replace(\"@\", \"_at_\")\n contact_email = contact_email.replace(\".\", \"_\")\n contact_email = convert_to_alphanumeric(contact_email)\n\n reply_domain = config.EMAIL_DOMAIN\n alias_domain = get_email_domain_part(alias.email)\n sl_domain = SLDomain.get_by(domain=alias_domain)\n if sl_domain and sl_domain.use_as_reverse_alias:\n reply_domain = alias_domain\n\n # not use while to avoid infinite loop\n for _ in range(1000):\n if include_sender_in_reverse_alias and contact_email:\n random_length = random.randint(5, 10)\n reply_email = (\n # do not use the ra+ anymore\n # f\"ra+{contact_email}+{random_string(random_length)}@{config.EMAIL_DOMAIN}\"\n f\"{contact_email}_{random_string(random_length)}@{reply_domain}\"\n )\n else:\n random_length = random.randint(20, 50)\n # do not use the ra+ anymore\n # reply_email = f\"ra+{random_string(random_length)}@{config.EMAIL_DOMAIN}\"\n reply_email = f\"{random_string(random_length)}@{reply_domain}\"\n\n if available_sl_email(reply_email):\n return reply_email\n\n raise Exception(\"Cannot generate reply email\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "@staticmethod\n def getVmStats(vmName):\n def getVcpuNumAndUtils():\n try:\n session = session_login()\n refs = session.xenapi.VM.get_by_name_label(vmName)\n if len(refs) == 0:\n raise Exception(\"No ref for %s found in xenapi VM objects\"%vmName)\n vm = XenAPIObject('VM', session, refs[0])\n VM_metrics = XenAPIObject(\"VM_metrics\", session, vm.get_metrics())\n items = VM_metrics.get_VCPUs_utilisation().items()\n nvCpus = len(items)\n if nvCpus == 0:\n raise Exception(\"vm %s has 0 vcpus !!!\"%vmName)\n\n xmInfo = successToMap(xen_get_xm_info())\n nCpus = int(xmInfo['nr_cpus'])\n totalUtils = 0.0\n # CPU utlization of VM = (total cpu utilization of each vcpu) / number of physical cpu\n for num, util in items:\n totalUtils += float(util)\n avgUtils = float(totalUtils/nCpus) * 100\n return (nvCpus, avgUtils)\n finally:\n session_logout()\n\n\n try:\n try:\n OvmHost()._getDomainIdByName(vmName)\n vmPath = OvmHost()._vmNameToPath(vmName)\n (nvcpus, avgUtils) = getVcpuNumAndUtils()\n vifs = successToMap(xen_get_vifs(vmPath))\n rxBytes = 0\n txBytes = 0\n vifs = OvmVm()._getVifs(vmName)\n for vif in vifs:\n rxp = join('/sys/class/net', vif.name, 'statistics/rx_bytes')\n txp = join(\"/sys/class/net/\", vif.name, \"statistics/tx_bytes\")\n if not exists(rxp): raise Exception('can not find %s'%rxp)\n if not exists(txp): raise Exception('can not find %s'%txp)\n rxBytes += long(doCmd(['cat', rxp])) / 1000\n txBytes += long(doCmd(['cat', txp])) / 1000\n except NoVmFoundException, e:\n vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)\n nvcpus = int(successToMap(xen_get_vcpus(vmPath))['vcpus'])\n avgUtils = 0\n rxBytes = 0\n txBytes = 0\n\n rs = toGson({\"cpuNum\":nvcpus, \"cpuUtil\":avgUtils, \"rxBytes\":rxBytes, \"txBytes\":txBytes})\n logger.debug(OvmVm.getVmStats, rs)\n return rs\n except Exception, e:\n errmsg = fmt_err_msg(e)\n logger.error(OvmVm.getVmStats, errmsg)\n raise XmlRpcFault(toErrCode(OvmVm, OvmVm.getVmStats), errmsg)", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def test_raises_exception_with_context(self):\n try:\n raise Exception(2)\n except Exception as e:\n try:\n raise Exception(1) from e\n except Exception:\n exc_info = sys.exc_info()\n\n with mock.patch(\"django.utils.autoreload._exception\", exc_info):\n with self.assertRaises(Exception) as cm:\n autoreload.raise_last_exception()\n self.assertEqual(cm.exception.args[0], 1)\n self.assertEqual(cm.exception.__cause__.args[0], 2)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_topic_id_to_topic_name_dict(topic_ids: List[str]) -> Dict[str, str]:\n \"\"\"Returns a dict with topic ID as key and topic name as value, for all\n given topic IDs.\n\n Args:\n topic_ids: List(str). A list of topic IDs.\n\n Raises:\n Exception. The topic models for some of the given topic IDs do not\n exist.\n\n Returns:\n dict(str, str). A dict with topic ID as key and topic name as value.\n \"\"\"\n topic_id_to_topic_name = {}\n topics = topic_fetchers.get_topics_by_ids(topic_ids)\n\n for topic in topics:\n if topic is None:\n continue\n topic_id_to_topic_name[topic.id] = topic.name\n\n correct_topic_ids = list(topic_id_to_topic_name.keys())\n # The topic IDs for which topic models do not exist are referred to as\n # incorrect topic IDs.\n incorrect_topic_ids = [\n topic_id for topic_id in topic_ids if topic_id not in correct_topic_ids\n ]\n if incorrect_topic_ids:\n error_msg = (\n 'No corresponding topic models exist for these topic IDs: %s.'\n % (', '.join(incorrect_topic_ids))\n )\n raise Exception(error_msg)\n return topic_id_to_topic_name", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def delete_demo(exploration_id: str) -> None:\n \"\"\"Deletes a single demo exploration.\n\n Args:\n exploration_id: str. The id of the exploration to be deleted.\n\n Raises:\n Exception. The exploration id is invalid.\n \"\"\"\n if not exp_domain.Exploration.is_demo_exploration_id(exploration_id):\n raise Exception('Invalid demo exploration id %s' % exploration_id)\n\n exploration = exp_fetchers.get_exploration_by_id(\n exploration_id, strict=False)\n if not exploration:\n logging.info(\n 'Exploration with id %s was not deleted, because it '\n 'does not exist.' % exploration_id)\n else:\n delete_exploration(\n feconf.SYSTEM_COMMITTER_ID, exploration_id, force_deletion=True)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_sample(self):\n raise Exception(\"test\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_combined_settings(\n self,\n type: NotificationSettingEnum | None = None,\n actor_type: ActorType | None = None,\n project_id: int | None = None,\n ) -> MutableMapping[\n Recipient,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ]:\n \"\"\"\n Returns the co-leaved settings between the setting options and setting providers\n It is as nested as _get_layered_setting_providers by applying the value from the options\n to the provider map.\n \"\"\"\n if self.type and type != self.type:\n raise Exception(\"Type mismatch: the provided type differs from the controller type\")\n\n kwargs: MutableMapping[str, str] = {}\n if type:\n kwargs[\"type\"] = type.value\n\n types_to_search = [type] if type else list(NotificationSettingEnum)\n\n setting_options_map = self._get_layered_setting_options(project_id=project_id, **kwargs)\n setting_providers_map = self._get_layered_setting_providers(project_id=project_id, **kwargs)\n\n result: MutableMapping[\n Recipient,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ] = defaultdict(\n lambda: defaultdict(\n lambda: defaultdict(\n lambda: NotificationSettingsOptionEnum.DEFAULT\n ) # Use lambda to return the default enum value\n )\n )\n for recipient, recipient_options_map in setting_options_map.items():\n # check actor type against recipient type\n if actor_type:\n if actor_type == ActorType.USER and recipient_is_team(recipient):\n continue\n if actor_type == ActorType.TEAM and recipient_is_user(recipient):\n continue\n\n for type in types_to_search:\n option_value = recipient_options_map[type]\n if option_value == NotificationSettingsOptionEnum.NEVER:\n continue\n\n provider_options_map = setting_providers_map[recipient][type]\n for provider, provider_value in provider_options_map.items():\n if provider_value == NotificationSettingsOptionEnum.NEVER:\n continue\n # use the option value here as it has more specific information\n result[recipient][type][provider] = option_value\n\n return result", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def exp_report_get(db, uid, report_id):\n if report_id in self_reports:\n if self_reports[report_id]['uid'] == uid:\n return _check_report(report_id)\n else:\n raise Exception, 'AccessDenied'\n else:\n raise Exception, 'ReportNotFound'", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def send(self, method, path, **kw):\n if 'headers' not in kw:\n kw['headers'] = dict()\n headers = kw['headers']\n headers['Authorization'] = self._authorization\n headers['Accept'] = 'application/vnd.github+json'\n headers['X-GitHub-Api-Version'] = '2022-11-28'\n\n # Switch to a different domain for the releases uploading API.\n if self._releases_upload_api_pattern.match(path):\n url = '%s%s' % (GITHUB_UPLOAD_ASSET_URL, path)\n else:\n url = '%s%s' % (GITHUB_URL, path)\n # Data are sent in JSON format.\n if 'data' in kw:\n kw['data'] = json.dumps(kw['data']).encode('utf-8')\n\n try:\n kw['method'] = method.upper()\n params = kw.pop('params', None)\n if params:\n url += '?' + urllib.parse.urlencode(params)\n request = urllib.request.Request(url, **kw)\n with urllib.request.urlopen(request) as response:\n r = json.loads(response.read())\n except ValueError:\n # Returned response may be empty in some cases\n r = {}\n if 'message' in r:\n raise Exception(json.dumps(r, indent=2, separators=(',', ': ')))\n return r", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def process_file(self, filename: str):\n \"\"\"Parses the target configuration file\n Args:\n filename (str) The target configuration file to parse\n \"\"\"\n Logger.info(f\"Processing python target definition in file '{filename}'\")\n parser = ConfigParser(\"https://docs.openc3.com/docs/configuration/target\")\n for keyword, parameters in parser.parse_file(filename):\n match keyword:\n case \"LANGUAGE\":\n usage = f\"{keyword} <ruby | python>\"\n parser.verify_num_parameters(1, 1, usage)\n self.language = parameters[0].lower()\n case \"REQUIRE\":\n usage = f\"{keyword} <FILENAME>\"\n parser.verify_num_parameters(1, 1, usage)\n # TODO:\n # filename = f\"{self.dir}/lib/{parameters[0]}\"\n # try:\n # # Require absolute path to file in target lib folder. Prevents name\n # # conflicts at the require step\n # # OpenC3.require_file(filename, False)\n\n # except LoadError:\n # begin\n # # If we couldn't load at the target/lib level check everywhere\n # OpenC3.disable_warnings do\n # filename = parameters[0]\n # OpenC3.require_file(parameters[0])\n\n # rescue Exception => err\n # raise parser.error(err)\n\n # rescue Exception => err\n # raise parser.error(err)\n\n # This code resolves any relative paths to absolute before putting into the self.requires array\n # unless Pathname.new(filename).absolute?\n # $:.each do |search_path|\n # test_filename = os.path.join(search_path, filename).gsub(\"\\\\\", \"/\")\n # if os.path.exists(test_filename)\n # filename = test_filename\n # break\n # self.requires << filename\n\n case \"IGNORE_PARAMETER\" | \"IGNORE_ITEM\":\n usage = f\"{keyword} <{keyword.split('_')[1]} NAME>\"\n parser.verify_num_parameters(1, 1, usage)\n if \"PARAMETER\" in keyword:\n self.ignored_parameters.append(parameters[0].upper())\n if \"ITEM\" in keyword:\n self.ignored_items.append(parameters[0].upper())\n\n case \"COMMANDS\" | \"TELEMETRY\":\n usage = f\"{keyword} <FILENAME>\"\n parser.verify_num_parameters(1, 1, usage)\n filename = pathlib.Path(self.dir, \"cmd_tlm\", parameters[0])\n if not filename.exists():\n raise parser.error(f\"{filename} not found\")\n self.cmd_tlm_files.append(filename)\n\n case \"CMD_UNIQUE_ID_MODE\":\n usage = keyword\n parser.verify_num_parameters(0, 0, usage)\n self.cmd_unique_id_mode = True\n\n case \"TLM_UNIQUE_ID_MODE\":\n usage = keyword\n parser.verify_num_parameters(0, 0, usage)\n self.tlm_unique_id_mode = True\n\n case _:\n # blank lines will have a None keyword and should not raise an exception\n if keyword:\n raise Exception(parser.error(f\"Unknown keyword '{keyword}'\"))", "smellKey": "S112", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def normalize_against_schema(\n obj: Any,\n schema: Dict[str, Any],\n apply_custom_validators: bool = True,\n global_validators: Optional[List[Dict[str, Any]]] = None\n) -> Any:\n \"\"\"Validate the given object using the schema, normalizing if necessary.\n\n Args:\n obj: *. The object to validate and normalize.\n schema: dict(str, *). The schema to validate and normalize the value\n against.\n apply_custom_validators: bool. Whether to validate the normalized\n object using the validators defined in the schema.\n global_validators: list(dict). List of additional validators that will\n verify all the values in the schema.\n\n Returns:\n *. The normalized object.\n\n Raises:\n Exception. The object fails to validate against the schema.\n AssertionError. The validation for schema validators fails.\n \"\"\"\n # Here we use type Any because 'normalized_obj' can be of type int, str,\n # Dict, List and other types too.\n normalized_obj: Any = None\n\n if schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_WEAK_MULTIPLE:\n for i in schema[SCHEMA_KEY_OPTIONS]:\n if isinstance(obj, ALL_SCHEMAS[i]):\n normalized_obj = obj\n break\n if normalized_obj is None:\n raise Exception(\n 'Type of %s is not present in options' % obj)\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_BOOL:\n assert isinstance(obj, bool), ('Expected bool, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_CUSTOM:\n # Importing this at the top of the file causes a circular dependency.\n # TODO(sll): Either get rid of custom objects or find a way to merge\n # them into the schema framework -- probably the latter.\n from core.domain import object_registry\n obj_class = object_registry.Registry.get_object_class_by_type(\n schema[SCHEMA_KEY_OBJ_TYPE])\n if not apply_custom_validators:\n normalized_obj = normalize_against_schema(\n obj, obj_class.get_schema(), apply_custom_validators=False)\n else:\n normalized_obj = obj_class.normalize(obj)\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_DICT:\n assert isinstance(obj, dict), ('Expected dict, received %s' % obj)\n expected_dict_keys = [\n p[SCHEMA_KEY_NAME] for p in schema[SCHEMA_KEY_PROPERTIES]]\n\n missing_keys = list(sorted(set(expected_dict_keys) - set(obj.keys())))\n extra_keys = list(sorted(set(obj.keys()) - set(expected_dict_keys)))\n\n assert set(obj.keys()) == set(expected_dict_keys), (\n 'Missing keys: %s, Extra keys: %s' % (missing_keys, extra_keys))\n\n normalized_obj = {}\n for prop in schema[SCHEMA_KEY_PROPERTIES]:\n key = prop[SCHEMA_KEY_NAME]\n normalized_obj[key] = normalize_against_schema(\n obj[key],\n prop[SCHEMA_KEY_SCHEMA],\n global_validators=global_validators\n )\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_DICT_WITH_VARIABLE_NO_OF_KEYS:\n assert isinstance(obj, dict), ('Expected dict, received %s' % obj)\n normalized_obj = {}\n for key, value in obj.items():\n normalized_key = normalize_against_schema(\n key, schema[SCHEMA_KEY_KEYS][SCHEMA_KEY_SCHEMA],\n global_validators=global_validators\n )\n normalized_obj[normalized_key] = normalize_against_schema(\n value, schema[SCHEMA_KEY_VALUES][SCHEMA_KEY_SCHEMA],\n global_validators=global_validators\n )\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_FLOAT:\n if isinstance(obj, bool):\n raise Exception('Expected float, received %s' % obj)\n try:\n obj = float(obj)\n except Exception as e:\n raise Exception('Could not convert %s to float: %s' % (\n type(obj).__name__, obj)) from e\n assert isinstance(obj, numbers.Real), (\n 'Expected float, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_INT:\n try:\n obj = int(obj)\n except Exception as e:\n raise Exception('Could not convert %s to int: %s' % (\n type(obj).__name__, obj)) from e\n assert isinstance(obj, numbers.Integral), (\n 'Expected int, received %s' % obj)\n assert isinstance(obj, int), ('Expected int, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_HTML:\n # TODO(#14028): Use just one type.\n assert isinstance(obj, (str, bytes)), (\n 'Expected unicode HTML string, received %s' % obj)\n if isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n else:\n obj = str(obj)\n assert isinstance(obj, str), (\n 'Expected unicode, received %s' % obj)\n normalized_obj = html_cleaner.clean(obj)\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_LIST:\n assert isinstance(obj, list), ('Expected list, received %s' % obj)\n item_schema = schema[SCHEMA_KEY_ITEMS]\n if SCHEMA_KEY_LEN in schema:\n assert len(obj) == schema[SCHEMA_KEY_LEN], (\n 'Expected length of %s got %s' % (\n schema[SCHEMA_KEY_LEN], len(obj)))\n normalized_obj = [\n normalize_against_schema(\n item,\n item_schema,\n global_validators=global_validators\n ) for item in obj\n ]\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_BASESTRING:\n # TODO(#14028): Use just one type.\n assert isinstance(obj, (str, bytes)), (\n 'Expected string, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_UNICODE:\n # TODO(#14028): Use just one type.\n assert isinstance(obj, (str, bytes)), (\n 'Expected unicode string, received %s' % obj)\n if isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n else:\n obj = str(obj)\n assert isinstance(obj, str), (\n 'Expected unicode, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_UNICODE_OR_NONE:\n # TODO(#14028): Use just one type.\n assert obj is None or isinstance(obj, (str, bytes)), (\n 'Expected unicode string or None, received %s' % obj)\n if obj is not None:\n if isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n else:\n obj = str(obj)\n assert isinstance(obj, str), (\n 'Expected unicode, received %s' % obj)\n normalized_obj = obj\n elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_OBJECT_DICT:\n # The schema type 'object_dict' accepts either of the keys\n # 'object_class' or 'validation_method'.\n # 'object_class' key is the most commonly used case, when the object is\n # initialized from_dict() method and the validation is done from\n # validate() method.\n # 'validation_method' key is used for some rare cases like if they have\n # validate_dict method instead of validate method, or if they need some\n # extra flags like for strict validation. The methods are written in the\n # domain_objects_validator file.\n\n if SCHEMA_KEY_OBJECT_CLASS in schema:\n validate_class = schema[SCHEMA_KEY_OBJECT_CLASS]\n domain_object = validate_class.from_dict(obj)\n domain_object.validate()\n normalized_obj = domain_object\n else:\n validation_method = schema[SCHEMA_KEY_VALIDATION_METHOD]\n normalized_obj = validation_method(obj)\n\n return normalized_obj\n else:\n raise Exception('Invalid schema type: %s' % schema[SCHEMA_KEY_TYPE])\n\n if SCHEMA_KEY_CHOICES in schema:\n assert normalized_obj in schema[SCHEMA_KEY_CHOICES], (\n 'Received %s which is not in the allowed range of choices: %s' %\n (normalized_obj, schema[SCHEMA_KEY_CHOICES]))\n\n # When type normalization is finished, apply the post-normalizers in the\n # given order.\n if SCHEMA_KEY_POST_NORMALIZERS in schema:\n for normalizer in schema[SCHEMA_KEY_POST_NORMALIZERS]:\n kwargs = dict(normalizer)\n del kwargs['id']\n normalized_obj = Normalizers.get(normalizer['id'])(\n normalized_obj, **kwargs)\n\n # Validate the normalized object.\n if apply_custom_validators:\n if SCHEMA_KEY_VALIDATORS in schema:\n for validator in schema[SCHEMA_KEY_VALIDATORS]:\n kwargs = dict(validator)\n expect_invalid_default_value = False\n if 'expect_invalid_default_value' in kwargs:\n expect_invalid_default_value = kwargs[\n 'expect_invalid_default_value']\n del kwargs['expect_invalid_default_value']\n del kwargs['id']\n validator_func = get_validator(validator['id'])\n if (\n not validator_func(normalized_obj, **kwargs) and\n not expect_invalid_default_value\n ):\n raise AssertionError(\n 'Validation failed: %s (%s) for object %s' % (\n validator['id'], kwargs, normalized_obj)\n )\n\n if global_validators is not None:\n for validator in global_validators:\n kwargs = dict(validator)\n del kwargs['id']\n assert get_validator(\n validator['id'])(normalized_obj, **kwargs), (\n 'Validation failed: %s (%s) for object %s' % (\n validator['id'], kwargs, normalized_obj))\n\n return normalized_obj", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def convert_esm_checkpoint_to_pytorch(\n model: str, pytorch_dump_folder_path: str, classification_head: bool, push_to_repo: str, auth_token: str\n):\n \"\"\"\n Copy/paste/tweak esm's weights to our BERT structure.\n \"\"\"\n if model.startswith(\"esmfold\"):\n esm = MODEL_MAPPING[model]()\n else:\n esm, alphabet = MODEL_MAPPING[model]()\n esm.eval() # disable dropout\n\n if model.startswith(\"esmfold\"):\n embed_dim = esm.esm.embed_dim\n num_layers = esm.esm.num_layers\n num_attention_heads = esm.esm.attention_heads\n intermediate_size = 4 * embed_dim\n token_dropout = esm.esm.token_dropout\n emb_layer_norm_before = False # This code path does not exist in ESM-2\n position_embedding_type = \"rotary\"\n is_folding_model = True\n esmfold_config = EsmFoldConfig()\n for key, val in esm.cfg.items():\n if hasattr(esmfold_config, key) and key != \"trunk\":\n setattr(esmfold_config, key, val)\n for key, val in esm.cfg.trunk.items():\n if hasattr(esmfold_config.trunk, key) and key != \"structure_module\":\n setattr(esmfold_config.trunk, key, val)\n for key, val in esm.cfg.trunk.structure_module.items():\n if hasattr(esmfold_config.trunk.structure_module, key):\n setattr(esmfold_config.trunk.structure_module, key, val)\n elif hasattr(esm, \"args\"):\n # Indicates an ESM-1b or ESM-1v model\n embed_dim = esm.args.embed_dim\n num_layers = esm.args.layers\n num_attention_heads = esm.args.attention_heads\n intermediate_size = esm.args.ffn_embed_dim\n token_dropout = esm.args.token_dropout\n emb_layer_norm_before = True if esm.emb_layer_norm_before else False\n position_embedding_type = \"absolute\"\n is_folding_model = False\n esmfold_config = None\n else:\n # Indicates an ESM-2 model\n embed_dim = esm.embed_dim\n num_layers = esm.num_layers\n num_attention_heads = esm.attention_heads\n intermediate_size = 4 * embed_dim # This is hardcoded in ESM-2\n token_dropout = esm.token_dropout\n emb_layer_norm_before = False # This code path does not exist in ESM-2\n position_embedding_type = \"rotary\"\n is_folding_model = False\n esmfold_config = None\n\n if is_folding_model:\n alphabet = esm.esm.alphabet\n vocab_list = tuple(alphabet.all_toks)\n mask_token_id = alphabet.mask_idx\n pad_token_id = alphabet.padding_idx\n\n if is_folding_model:\n original_esm_model = esm.esm\n else:\n original_esm_model = esm\n\n config = EsmConfig(\n vocab_size=original_esm_model.embed_tokens.num_embeddings,\n mask_token_id=mask_token_id,\n hidden_size=embed_dim,\n num_hidden_layers=num_layers,\n num_attention_heads=num_attention_heads,\n intermediate_size=intermediate_size,\n max_position_embeddings=1026,\n layer_norm_eps=1e-5, # PyTorch default used in fairseq\n attention_probs_dropout_prob=0.0,\n hidden_dropout_prob=0.0,\n pad_token_id=pad_token_id,\n emb_layer_norm_before=emb_layer_norm_before,\n token_dropout=token_dropout,\n position_embedding_type=position_embedding_type,\n is_folding_model=is_folding_model,\n esmfold_config=esmfold_config,\n vocab_list=vocab_list,\n )\n if classification_head:\n config.num_labels = esm.classification_heads[\"mnli\"].out_proj.weight.shape[0]\n print(\"Our ESM config:\", config)\n\n if model.startswith(\"esmfold\"):\n model_class = EsmForProteinFolding\n elif classification_head:\n model_class = EsmForSequenceClassification\n else:\n model_class = EsmForMaskedLM\n model = model_class(config)\n model.eval()\n\n # Now let's copy all the weights.\n # Embeddings\n model.esm.embeddings.word_embeddings.weight = original_esm_model.embed_tokens.weight\n if position_embedding_type == \"absolute\":\n model.esm.embeddings.position_embeddings.weight = original_esm_model.embed_positions.weight\n\n if config.emb_layer_norm_before:\n model.esm.embeddings.layer_norm.weight = original_esm_model.emb_layer_norm_before.weight\n model.esm.embeddings.layer_norm.bias = original_esm_model.emb_layer_norm_before.bias\n\n model.esm.encoder.emb_layer_norm_after.weight = original_esm_model.emb_layer_norm_after.weight\n model.esm.encoder.emb_layer_norm_after.bias = original_esm_model.emb_layer_norm_after.bias\n\n for i in range(config.num_hidden_layers):\n # Encoder: start of layer\n layer: EsmLayer = model.esm.encoder.layer[i]\n # esm_layer: TransformerSentenceEncoderLayer = original_esm_model.layers[i]\n esm_layer = original_esm_model.layers[i]\n\n # self attention\n self_attn: EsmSelfAttention = layer.attention.self\n assert (\n esm_layer.self_attn.k_proj.weight.data.shape\n == esm_layer.self_attn.q_proj.weight.data.shape\n == esm_layer.self_attn.v_proj.weight.data.shape\n == torch.Size((config.hidden_size, config.hidden_size))\n )\n\n self_attn.query.weight.data = esm_layer.self_attn.q_proj.weight\n self_attn.query.bias.data = esm_layer.self_attn.q_proj.bias\n self_attn.key.weight.data = esm_layer.self_attn.k_proj.weight\n self_attn.key.bias.data = esm_layer.self_attn.k_proj.bias\n self_attn.value.weight.data = esm_layer.self_attn.v_proj.weight\n self_attn.value.bias.data = esm_layer.self_attn.v_proj.bias\n\n if getattr(esm_layer.self_attn, \"rot_emb\", None) is not None:\n # Matt: Although inv_freq is not a trainable weight, it is computed at model init and cached.\n # During the training of ESM-2 the model was converted to float16 precision, which also converts\n # the inv_freq tensor, and the loss of precision remains even if the model is loaded later as float32.\n # If we recompute inv_freq without this loss of precision then we will get subtly different rotary\n # embeddings, which are enough to cause significant discrepancies in model outputs. To avoid this,\n # we make sure the new model copies the data from the old inv_freq.\n self_attn.rotary_embeddings.inv_freq.data = esm_layer.self_attn.rot_emb.inv_freq\n\n # LayerNorm changes for pre-activation\n layer.attention.LayerNorm.weight = esm_layer.self_attn_layer_norm.weight\n layer.attention.LayerNorm.bias = esm_layer.self_attn_layer_norm.bias\n layer.LayerNorm.weight = esm_layer.final_layer_norm.weight\n layer.LayerNorm.bias = esm_layer.final_layer_norm.bias\n\n # self-attention output\n self_output: EsmSelfOutput = layer.attention.output\n assert self_output.dense.weight.shape == esm_layer.self_attn.out_proj.weight.shape\n self_output.dense.weight = esm_layer.self_attn.out_proj.weight\n self_output.dense.bias = esm_layer.self_attn.out_proj.bias\n\n # intermediate\n intermediate: EsmIntermediate = layer.intermediate\n assert intermediate.dense.weight.shape == esm_layer.fc1.weight.shape\n intermediate.dense.weight = esm_layer.fc1.weight\n intermediate.dense.bias = esm_layer.fc1.bias\n\n # output\n bert_output: EsmOutput = layer.output\n assert bert_output.dense.weight.shape == esm_layer.fc2.weight.shape\n bert_output.dense.weight = esm_layer.fc2.weight\n bert_output.dense.bias = esm_layer.fc2.bias\n # end of layer\n\n if is_folding_model:\n model.esm_s_combine.data = esm.esm_s_combine.data\n model.af2_to_esm.data = esm.af2_to_esm.data\n transfer_and_check_weights(esm.embedding, model.embedding)\n transfer_and_check_weights(esm.esm_s_mlp, model.esm_s_mlp)\n transfer_and_check_weights(esm.trunk, model.trunk)\n transfer_and_check_weights(esm.distogram_head, model.distogram_head)\n transfer_and_check_weights(esm.ptm_head, model.ptm_head)\n transfer_and_check_weights(esm.lm_head, model.lm_head)\n transfer_and_check_weights(esm.lddt_head, model.lddt_head)\n\n elif classification_head:\n model.classifier.dense.weight = esm.esm.classification_heads[\"mnli\"].dense.weight\n model.classifier.dense.bias = esm.classification_heads[\"mnli\"].dense.bias\n model.classifier.out_proj.weight = esm.classification_heads[\"mnli\"].out_proj.weight\n model.classifier.out_proj.bias = esm.classification_heads[\"mnli\"].out_proj.bias\n else:\n # LM Head\n model.lm_head.dense.weight = esm.lm_head.dense.weight\n model.lm_head.dense.bias = esm.lm_head.dense.bias\n model.lm_head.layer_norm.weight = esm.lm_head.layer_norm.weight\n model.lm_head.layer_norm.bias = esm.lm_head.layer_norm.bias\n model.lm_head.decoder.weight = esm.lm_head.weight\n model.lm_head.bias = esm.lm_head.bias\n\n # Contact prediction head\n transfer_and_check_weights(esm.contact_head, model.esm.contact_head)\n\n # Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)\n if is_folding_model:\n # Folding models aren't trained on masked inputs and don't like mask tokens.\n sample_data = SAMPLE_DATA[:2]\n else:\n sample_data = SAMPLE_DATA\n\n if is_folding_model:\n hf_tokenizer = get_esmfold_tokenizer()\n hf_tokens = hf_tokenizer(\n [row[1] for row in sample_data], return_tensors=\"pt\", padding=True, add_special_tokens=False\n )\n esmfold_aas, esmfold_mask, _, _, _ = esmfold_encode_sequences([row[1] for row in sample_data])\n success = torch.all(hf_tokens[\"input_ids\"] == esmfold_aas) and torch.all(\n hf_tokens[\"attention_mask\"] == esmfold_mask\n )\n else:\n # Let's check that we get the same results.\n batch_converter = alphabet.get_batch_converter()\n batch_labels, batch_strs, batch_tokens = batch_converter(sample_data)\n # Prepare tokenizer and make sure it matches\n with TemporaryDirectory() as tempdir:\n vocab = \"\\n\".join(alphabet.all_toks)\n vocab_file = Path(tempdir) / \"vocab.txt\"\n vocab_file.write_text(vocab)\n hf_tokenizer = EsmTokenizer(vocab_file=str(vocab_file))\n\n hf_tokens = hf_tokenizer([row[1] for row in sample_data], return_tensors=\"pt\", padding=True)\n success = torch.all(hf_tokens[\"input_ids\"] == batch_tokens)\n\n print(\"Do both models tokenizers output the same tokens?\", \"\ud83d\udd25\" if success else \"\ud83d\udca9\")\n if not success:\n raise Exception(\"Tokenization does not match!\")\n\n with torch.no_grad():\n if is_folding_model:\n # Let's test the model in parts\n # ESMFold always converts the ESM stem to float16, which requires float16 ops\n # that don't exist on CPU. Therefore, to test it we need to run it on GPU. However,\n # ESMFold is what we in the community call a \"big boy\" and so we desperately avoid putting both the\n # original and the converted model on the GPU at the same time.\n their_output = esm.cuda().infer([row[1] for row in sample_data])\n our_output = model.cuda()(\n input_ids=hf_tokens[\"input_ids\"].cuda(), attention_mask=hf_tokens[\"attention_mask\"].cuda()\n )\n else:\n our_output = model(**hf_tokens, output_hidden_states=True)\n our_output = our_output[\"logits\"]\n if classification_head:\n their_output = esm.model.classification_heads[\"mnli\"](esm.extract_features(batch_tokens))\n else:\n their_output = esm(hf_tokens[\"input_ids\"], repr_layers=list(range(999)))\n their_output = their_output[\"logits\"]\n\n if is_folding_model:\n max_absolute_diff = torch.max(torch.abs(our_output[\"positions\"] - their_output[\"positions\"])).item()\n success = torch.allclose(our_output[\"positions\"], their_output[\"positions\"], atol=1e-5)\n else:\n max_absolute_diff = torch.max(torch.abs(our_output - their_output)).item()\n success = torch.allclose(our_output, their_output, atol=1e-5)\n\n print(f\"max_absolute_diff = {max_absolute_diff}\") # ~ 1e-5\n print(\"Do both models output the same tensors?\", \"\ud83d\udd25\" if success else \"\ud83d\udca9\")\n\n if not success:\n raise Exception(\"Something went wRoNg\")\n\n if not is_folding_model:\n # Let's check contact prediction too\n our_output = model.predict_contacts(hf_tokens[\"input_ids\"], hf_tokens[\"attention_mask\"])\n their_output = esm.predict_contacts(hf_tokens[\"input_ids\"])\n max_absolute_diff = torch.max(torch.abs(our_output - their_output)).item()\n success = torch.allclose(our_output, their_output, atol=1e-5)\n\n print(\"Contact prediction testing:\")\n print(f\"max_absolute_diff = {max_absolute_diff}\") # ~ 1e-5\n print(\"Do both models output the same tensors?\", \"\ud83d\udd25\" if success else \"\ud83d\udca9\")\n\n if not success:\n raise Exception(\"Something went wRoNg\")\n\n pathlib.Path(pytorch_dump_folder_path).mkdir(parents=True, exist_ok=True)\n print(f\"Saving model to {pytorch_dump_folder_path}\")\n model.save_pretrained(pytorch_dump_folder_path)\n\n del esm # Free up some memory before continuing\n\n print(f\"Saving tokenizer to {pytorch_dump_folder_path}\")\n hf_tokenizer.save_pretrained(pytorch_dump_folder_path)\n\n if push_to_repo:\n model.push_to_hub(repo_id=push_to_repo, token_token=auth_token)\n hf_tokenizer.push_to_hub(repo_id=push_to_repo, token_token=auth_token)", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def search(self, markup):\n #print 'looking for %s in %s' % (self, markup)\n found = None\n # If given a list of items, scan it for a text element that\n # matches. \n if isList(markup) and not isinstance(markup, Tag):\n for element in markup:\n if isinstance(element, NavigableString) \\\n and self.search(element):\n found = element\n break\n # If it's a Tag, make sure its name or attributes match.\n # Don't bother with Tags if we're searching for text.\n elif isinstance(markup, Tag):\n if not self.text:\n found = self.searchTag(markup)\n # If it's text, make sure the text matches.\n elif isinstance(markup, NavigableString) or \\\n isString(markup):\n if self._matches(markup, self.text):\n found = markup\n else:\n raise Exception, \"I don't know how to match against a %s\" \\\n % markup.__class__\n return found", "smellKey": "S112", "smellId": null, "repo": "usdot-fhwa-stol_connectedvcs-tools", "language": "python"} {"function": "def update_translation_review_stats(\n suggestion: suggestion_registry.BaseSuggestion\n) -> None:\n \"\"\"Creates/updates TranslationReviewStatsModel\n TranslationReviewerTotalContributionStatsModel model for given translation\n reviewer when a translation is reviewed.\n\n Args:\n suggestion: Suggestion. The suggestion domain object that is being\n reviewed.\n\n Raises:\n Exception. The final_reviewer_id of the suggestion should not be None.\n \"\"\"\n content_word_count = 0\n if suggestion.final_reviewer_id is None:\n raise Exception(\n 'The final_reviewer_id in the suggestion should not be None.'\n )\n exp_opportunity = (\n opportunity_services.get_exploration_opportunity_summary_by_id(\n suggestion.target_id))\n # We can confirm that exp_opportunity will not be None since there should\n # be an assigned opportunity for a given translation. Hence we can rule out\n # the possibility of None for mypy type checking.\n assert exp_opportunity is not None\n topic_id = exp_opportunity.topic_id\n suggestion_is_accepted = (\n suggestion.status == suggestion_models.STATUS_ACCEPTED\n )\n\n if isinstance(suggestion.change_cmd.translation_html, list):\n for content in suggestion.change_cmd.translation_html:\n content_plain_text = html_cleaner.strip_html_tags(content)\n content_word_count += len(content_plain_text.split())\n else:\n content_plain_text = html_cleaner.strip_html_tags(\n suggestion.change_cmd.translation_html)\n content_word_count = len(content_plain_text.split())\n\n translation_review_stat_model = (\n # This function is called when reviewing a translation and hence\n # final_reviewer_id should not be None when the suggestion is\n # up-to-date.\n suggestion_models.TranslationReviewStatsModel.get(\n suggestion.change_cmd.language_code, suggestion.final_reviewer_id,\n topic_id\n ))\n\n translation_reviewer_total_stat_model = (\n suggestion_models.TranslationReviewerTotalContributionStatsModel.get(\n suggestion.change_cmd.language_code, suggestion.final_reviewer_id\n ))\n\n if translation_reviewer_total_stat_model is None:\n # This function is called when reviewing a translation and hence\n # final_reviewer_id should not be None when the suggestion is\n # up-to-date.\n accepted_translations_count = 0\n accepted_translations_with_reviewer_edits_count = 0\n rejected_translation_count = 0\n accepted_translation_word_count = 0\n if suggestion_is_accepted:\n accepted_translations_count += 1\n accepted_translation_word_count = content_word_count\n else:\n rejected_translation_count += 1\n if suggestion_is_accepted and suggestion.edited_by_reviewer:\n accepted_translations_with_reviewer_edits_count += 1\n suggestion_models.TranslationReviewerTotalContributionStatsModel.create(\n language_code=suggestion.change_cmd.language_code,\n contributor_id=suggestion.final_reviewer_id,\n topic_ids_with_translation_reviews=[topic_id],\n reviewed_translations_count=1,\n accepted_translations_count=accepted_translations_count,\n accepted_translations_with_reviewer_edits_count=(\n accepted_translations_with_reviewer_edits_count),\n accepted_translation_word_count=accepted_translation_word_count,\n rejected_translations_count=rejected_translation_count,\n first_contribution_date=suggestion.last_updated.date(),\n last_contribution_date=suggestion.last_updated.date()\n )\n else:\n translation_reviewer_total_stat = (\n contribution_stats_services\n .get_translation_reviewer_total_stats_from_model(\n translation_reviewer_total_stat_model))\n\n if topic_id not in (\n translation_reviewer_total_stat\n .topic_ids_with_translation_reviews):\n (\n translation_reviewer_total_stat\n .topic_ids_with_translation_reviews\n ).append(topic_id)\n\n increment_translation_reviewer_total_stats(\n translation_reviewer_total_stat, content_word_count,\n suggestion.last_updated, suggestion_is_accepted,\n suggestion.edited_by_reviewer\n )\n _update_translation_reviewer_total_stats_models(\n translation_reviewer_total_stat)\n\n if translation_review_stat_model is None:\n # This function is called when reviewing a translation and hence\n # final_reviewer_id should not be None when the suggestion is\n # up-to-date.\n accepted_translations_count = 0\n accepted_translations_with_reviewer_edits_count = 0\n accepted_translation_word_count = 0\n if suggestion_is_accepted:\n accepted_translations_count += 1\n accepted_translation_word_count = content_word_count\n if suggestion_is_accepted and suggestion.edited_by_reviewer:\n accepted_translations_with_reviewer_edits_count += 1\n suggestion_models.TranslationReviewStatsModel.create(\n language_code=suggestion.change_cmd.language_code,\n reviewer_user_id=suggestion.final_reviewer_id,\n topic_id=topic_id,\n reviewed_translations_count=1,\n reviewed_translation_word_count=content_word_count,\n accepted_translations_count=accepted_translations_count,\n accepted_translations_with_reviewer_edits_count=(\n accepted_translations_with_reviewer_edits_count),\n accepted_translation_word_count=accepted_translation_word_count,\n first_contribution_date=suggestion.last_updated.date(),\n last_contribution_date=suggestion.last_updated.date()\n )\n else:\n translation_review_stat = (\n _create_translation_review_stats_from_model(\n translation_review_stat_model))\n\n increment_translation_review_stats(\n translation_review_stat, content_word_count,\n suggestion.last_updated, suggestion_is_accepted,\n suggestion.edited_by_reviewer\n )\n _update_translation_review_stats_models([translation_review_stat])\n\n update_translation_contribution_stats_at_review(suggestion)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_credential(self, system: str, username: str) -> None:\n self._call_count += 1\n raise Exception(\"This keyring is broken!\")", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "@classmethod\n def _migrate_to_latest_yaml_version(\n cls, yaml_content: str\n ) -> CollectionDict:\n \"\"\"Return the YAML content of the collection in the latest schema\n format.\n\n Args:\n yaml_content: str. The YAML representation of the collection.\n\n Returns:\n Dict. The dictionary representation of the collection in which\n the latest YAML representation of the collection and latest\n schema format is used.\n\n Raises:\n InvalidInputException. The 'yaml_content' or the schema version\n is not specified.\n Exception. The collection schema version is not valid.\n \"\"\"\n try:\n # Here we use cast because here we are narrowing down the type from\n # Dict[str, Any] to CollectionDict.\n collection_dict = cast(\n CollectionDict, utils.dict_from_yaml(yaml_content)\n )\n except utils.InvalidInputException as e:\n raise utils.InvalidInputException(\n 'Please ensure that you are uploading a YAML text file, not '\n 'a zip file. The YAML parser returned the following error: %s'\n % e)\n\n collection_schema_version = collection_dict.get('schema_version')\n if collection_schema_version is None:\n raise utils.InvalidInputException(\n 'Invalid YAML file: no schema version specified.')\n if not (1 <= collection_schema_version\n <= feconf.CURRENT_COLLECTION_SCHEMA_VERSION):\n raise Exception(\n 'Sorry, we can only process v1 to v%s collection YAML files at '\n 'present.' % feconf.CURRENT_COLLECTION_SCHEMA_VERSION)\n\n while (collection_schema_version <\n feconf.CURRENT_COLLECTION_SCHEMA_VERSION):\n conversion_fn = getattr(\n cls, '_convert_v%s_dict_to_v%s_dict' % (\n collection_schema_version, collection_schema_version + 1))\n collection_dict = conversion_fn(collection_dict)\n collection_schema_version += 1\n\n return collection_dict", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@patch(\"sentry.integrations.slack.unfurl.discover.client.get\")\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_bar_chart_interval_with_absolute_date(self, mock_generate_chart, api_mock):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?display=bar&end=2022-09-16T23%3A59%3A59&field=title&field=event.type&field=project&field=user.display&field=timestamp&name=All+Events&query=&sort=-timestamp&start=2022-09-09T00%3A00%3A00&utc=true&yAxis=count%28%29\"\n\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n\n assert len(mock_generate_chart.mock_calls) == 1\n assert len(api_mock.mock_calls) == 1\n\n assert \"interval\" in api_mock.call_args[1][\"params\"]\n assert api_mock.call_args[1][\"params\"][\"interval\"] == \"1h\"", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def create_branch(channel, top_level_base, remote_base, local_branch, args):\n global config\n\n if is_nightly(channel):\n return local_branch\n\n channel_branch = local_branch + '_' + remote_base\n\n if is_sha(top_level_base):\n compare_from = top_level_base\n else:\n compare_from = 'origin/' + top_level_base\n\n with scoped_cwd(BRAVE_CORE_ROOT):\n # get SHA for all commits (in order)\n sha_list = execute([\n 'git', 'log', compare_from + '..HEAD', '--pretty=format:%h',\n '--reverse'\n ])\n sha_list = sha_list.split('\\n')\n if len(sha_list) == 0:\n raise Exception('No changes detected!')\n try:\n # check if branch exists already\n try:\n branch_sha = execute(\n ['git', 'rev-parse', '-q', '--verify', channel_branch])\n except Exception:\n branch_sha = ''\n\n if len(branch_sha) > 0:\n # branch exists; reset it\n print('(' + channel + ') branch \"' + channel_branch +\n '\" exists; resetting to origin/' + remote_base)\n execute(['git', 'checkout', channel_branch])\n execute(['git', 'reset', '--hard', 'origin/' + remote_base])\n else:\n # create the branch\n print('(' + channel + ') creating \"' + channel_branch +\n '\" from ' + remote_base)\n execute(['git', 'checkout', remote_base])\n execute(['git', 'pull', 'origin', remote_base])\n execute(['git', 'checkout', '-b', channel_branch])\n\n # TODO: handle errors thrown by cherry-pick\n for sha in sha_list:\n output = execute(['git', 'cherry-pick', sha]).split('\\n')\n print('- picked ' + sha + ' (' + output[0] + ')')\n\n # squash all commits into one\n # NOTE: master is not squashed. This only runs for uplifts.\n execute(['git', 'reset', '--soft', remote_base])\n squash_message = 'Squash of commits from branch \"' + \\\n str(local_branch) + '\" to ' + channel\n if int(config.master_pr_number) > 0:\n squash_message = 'Uplift of #' + \\\n str(config.master_pr_number) + ' (squashed) to ' + channel\n if args.gpgsign:\n cmdline = ['git', 'commit', '-S', '-m', squash_message]\n else:\n cmdline = ['git', 'commit', '-m', squash_message]\n execute(cmdline)\n squash_hash = execute(['git', 'log', '--pretty=\"%h\"', '-n1'])\n print('- squashed all commits into ' + squash_hash +\n ' with message: \"' + squash_message + '\"')\n\n finally:\n # switch back to original branch\n execute(['git', 'checkout', local_branch])\n execute(['git', 'reset', '--hard', sha_list[-1]])\n\n config.branches_to_push.append(channel_branch)\n\n return channel_branch", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def _AddToken(tokenDict, classTokenSet, tokenId, val, desc, \n useLiteralIdentifier=False):\n \"\"\"tokenId must be an identifier\"\"\"\n\n cppReservedKeywords = [\n \"alignas\", \"alignof\", \"and\", \"and_eq\", \"asm\", \"atomic_cancel\",\n \"atomic_commit\", \"atomic_noexcept\", \"auto\", \"bitand\", \"bitor\", \"bool\",\n \"break\", \"case\", \"catch\", \"char\", \"char8_t\", \"char16_t\", \"char32_t\",\n \"class\", \"compl\", \"concept\", \"const\", \"consteval\", \"constexpr\",\n \"constinit\", \"const_cast\", \"continue\", \"co_await\", \"co_return\",\n \"co_yield\", \"decltype\", \"default\", \"delete\", \"do\", \"double\",\n \"dynamic_cast\", \"else\", \"enum\", \"explicit\", \"export\", \"extern\", \"false\",\n \"float\", \"for\", \"friend\", \"goto\", \"if\", \"inline\", \"int\", \"long\",\n \"mutable\", \"namespace\", \"new\", \"noexcept\", \"not\", \"not_eq\", \"nullptr\",\n \"operator\", \"or\", \"or_eq\", \"private\", \"protected\", \"public\", \"reflexpr\",\n \"register\", \"reinterpret_cast\", \"requires\", \"return\", \"short\", \"signed\",\n \"sizeof\", \"static\", \"static_assert\", \"static_cast\", \"struct\", \"switch\",\n \"synchronized\", \"template\", \"this\", \"thread_local\", \"throw\", \"true\",\n \"try\", \"typedef\", \"typeid\", \"typename\", \"union\", \"unsigned\", \"using\",\n \"virtual\", \"void\", \"volatile\", \"wchar_t\", \"while\", \"xor\", \"xor_eq\",\n ]\n pythonReservedKeywords = keyword.kwlist\n # If token is a reserved word in either language, append with underscore.\n # 'interface' is not a reserved word but is a macro on Windows when using\n # COM so we treat it as reserved.\n # None is a reserved word for python3 \n reserved = set(cppReservedKeywords + keyword.kwlist + [\n 'interface',\n 'None',\n ])\n \n if not Tf.IsValidIdentifier(tokenId):\n tokenId = _MakeValidToken(tokenId, useLiteralIdentifier)\n elif not useLiteralIdentifier:\n # if not using literal identifier we always camelCase our valid\n # identifiers as per convention.\n tokenId = _CamelCase(tokenId)\n \n # After conversion to camelCase, check if the token is reserved.\n if tokenId in reserved:\n tokenId = tokenId + '_'\n\n if tokenId in tokenDict:\n token = tokenDict[tokenId]\n\n # Assert one-to-one mapping of token.id -> token.value\n if token.value != val:\n raise Exception(\n 'Token identifiers must map to exactly one token value. '\n 'One-to-Many mapping encountered: %s maps to \\\"%s\\\" and \\\"%s\\\"'\n % (token.id, token.value, val))\n \n # Update Description\n tokenDict[tokenId] = token._replace(\n desc=token.desc + ', ' + desc)\n \n else:\n tokenDict[tokenId] = Token(tokenId, val, desc)\n\n if classTokenSet is not None:\n classTokenSet.add(tokenId)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_OpenUSD", "language": "python"} {"function": "def _createVlan(self, vlan):\n \"\"\"\n @param jsonString : parameter from client side\n @return : succ xxxxx\n ex. jsonString => {vid:100, pif:eth0}\n ex. return =>\n \"\"\"\n\n #Pre-condition\n #check Physical Interface Name\n if vlan.pif not in self.pifs.keys():\n msg = \"Physical Interface(%s) does not exist\" % vlan.pif\n logger.debug(self._createVlan, msg)\n raise Exception(msg)\n\n #Pre-condition\n #check Vlan Interface Name\n ifName = \"%s.%s\" % (vlan.pif, vlan.vid)\n if ifName in self.vlans.keys():\n msg = \"Vlan Interface(%s) already exist, return it\" % ifName\n logger.debug(self._createVlan, msg)\n return self.vlans[ifName]\n\n doCmd(['vconfig', 'add', vlan.pif, vlan.vid])\n self.bringUP(ifName)\n logger.debug(self._createVlan, \"Create vlan %s successfully\"%ifName)\n return self.vlans[ifName]", "smellKey": "S112", "smellId": null, "repo": "BTIGIT03_apache_cloudstack", "language": "python"} {"function": "def process_scan(\n self,\n auto_create_manager: AutoCreateContextManager,\n data: dict,\n context: dict,\n ) -> None:\n \"\"\"\n Process the scan with all of the supplied data fully massaged\n into the format we are expecting\n\n Raises exceptions in the event of an error\n \"\"\"\n statistics_before, statistics_delta = None, None\n try:\n if test := context.get(\"test\"):\n statistics_before = test.statistics\n context[\"test\"], _, _, _, _, _, test_import = self.get_reimporter(\n **context,\n ).process_scan(\n context.pop(\"scan\", None),\n )\n if test_import:\n statistics_delta = test_import.statistics\n elif context.get(\"auto_create_context\"):\n # Attempt to create an engagement\n logger.debug(\"reimport for non-existing test, using import to create new test\")\n context[\"engagement\"] = auto_create_manager.get_or_create_engagement(**context)\n context[\"test\"], _, _, _, _, _, _ = self.get_importer(\n **context,\n ).process_scan(\n context.pop(\"scan\", None),\n )\n else:\n msg = \"A test could not be found!\"\n raise NotFound(msg)\n # Update the response body with some new data\n if test := context.get(\"test\"):\n data[\"test\"] = test\n data[\"test_id\"] = test.id\n data[\"engagement_id\"] = test.engagement.id\n data[\"product_id\"] = test.engagement.product.id\n data[\"product_type_id\"] = test.engagement.product.prod_type.id\n data[\"statistics\"] = {}\n if statistics_before:\n data[\"statistics\"][\"before\"] = statistics_before\n if statistics_delta:\n data[\"statistics\"][\"delta\"] = statistics_delta\n data[\"statistics\"][\"after\"] = test.statistics\n # convert to exception otherwise django rest framework will swallow them as 400 error\n # exceptions are already logged in the importer\n except SyntaxError as se:\n raise Exception(se)\n except ValueError as ve:\n raise Exception(ve)", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def finish_pipeline(self) -> HttpResponseBase:\n data = self.fetch_state()\n\n # The state data may have expired, in which case the state data will\n # simply be None.\n if not data:\n return self.error(ERR_INVALID_IDENTITY)\n\n try:\n identity = self.provider.build_identity(data)\n except IdentityNotValid as error:\n return self.error(str(error) or ERR_INVALID_IDENTITY)\n\n if self.state.flow == self.FLOW_LOGIN:\n # create identity and authenticate the user\n response = self._finish_login_pipeline(identity)\n elif self.state.flow == self.FLOW_SETUP_PROVIDER:\n # Configuring the SSO Auth provider\n response = self._finish_setup_pipeline(identity)\n else:\n raise Exception(f\"Unrecognized flow value: {self.state.flow}\")\n\n return response", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def test_suite_debug_propagates_exceptions(self):\n class Module(object):\n @staticmethod\n def setUpModule():\n if phase == 0:\n raise Exception('setUpModule')\n @staticmethod\n def tearDownModule():\n if phase == 1:\n raise Exception('tearDownModule')\n\n class Test(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n if phase == 2:\n raise Exception('setUpClass')\n @classmethod\n def tearDownClass(cls):\n if phase == 3:\n raise Exception('tearDownClass')\n def test_something(self):\n if phase == 4:\n raise Exception('test_something')\n\n Test.__module__ = 'Module'\n sys.modules['Module'] = Module\n\n messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something')\n for phase, msg in enumerate(messages):\n _suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test)\n suite = unittest.TestSuite([_suite])\n with self.assertRaisesRegex(Exception, msg):\n suite.debug()", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def check_danger_keywords(self):\n lines = self.job.playbook.check_dangerous_keywords()\n if len(lines) > 0:\n for line in lines:\n print('\\033[31mThe {} line of the file \\'{}\\' contains the '\n 'dangerous keyword \\'{}\\'\\033[0m'.format(line['line'], line['file'], line['keyword']))\n raise Exception(\"Playbook contains dangerous keywords\")", "smellKey": "S112", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def test_merged_rollback_rollback(self):\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with transaction.atomic():\n Reporter.objects.create(last_name=\"Tintin\")\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with transaction.atomic(savepoint=False):\n Reporter.objects.create(first_name=\"Haddock\")\n raise Exception(\"Oops, that's his last name\")\n raise Exception(\"Oops, that's his first name\")\n self.assertSequenceEqual(Reporter.objects.all(), [])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def compute_lot_quantity(biofuel, data):\n volume = None\n weight = None\n lhv_amount = None\n\n # normalize the given data in the form of a (quantity, unit) couple\n if data.get(\"quantity\") is not None and data.get(\"unit\") is not None:\n quantity = round(float(data.get(\"quantity\")), 2)\n unit = data.get(\"unit\", CarbureUnit.LITER).lower()\n elif data.get(\"volume\") is not None:\n quantity = round(float(data.get(\"volume\")), 2)\n unit = CarbureUnit.LITER\n elif data.get(\"weight\") is not None:\n quantity = round(float(data.get(\"weight\")), 2)\n unit = CarbureUnit.KILOGRAM\n elif data.get(\"lhv_amount\") is not None:\n quantity = round(float(data.get(\"lhv_amount\")), 2)\n unit = CarbureUnit.LHV\n else:\n raise Exception(\"No quantity was specified\")\n\n # compute the different quantity values based on the previous config\n if unit == CarbureUnit.LITER:\n volume = quantity\n weight = round(volume * biofuel.masse_volumique, 2)\n lhv_amount = round(volume * biofuel.pci_litre, 2)\n elif unit == CarbureUnit.KILOGRAM:\n weight = quantity\n volume = round(weight / biofuel.masse_volumique, 2)\n lhv_amount = round(volume * biofuel.pci_litre, 2)\n elif unit == CarbureUnit.LHV:\n lhv_amount = quantity\n volume = round(lhv_amount / biofuel.pci_litre, 2)\n weight = round(volume * biofuel.masse_volumique, 2)\n\n return {\"volume\": volume, \"weight\": weight, \"lhv_amount\": lhv_amount}", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "@classmethod\n def _urlnorm(cls, uri):\n \"\"\"Normalize the URL to create a safe key for the cache\"\"\"\n (scheme, authority, path, query, fragment) = parse_uri(uri)\n if not scheme or not authority:\n raise Exception(\"Only absolute URIs are allowed. uri = %s\" % uri)\n\n scheme = scheme.lower()\n authority = authority.lower()\n\n if not path:\n path = \"/\"\n\n # Could do syntax based normalization of the URI before\n # computing the digest. See Section 6.2.2 of Std 66.\n request_uri = query and \"?\".join([path, query]) or path\n defrag_uri = scheme + \"://\" + authority + request_uri\n\n return defrag_uri", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "def clean(self):\n try:\n auth_token = self.cleaned_data[\"user_access_token\"]\n name = self.cleaned_data[\"page_name\"]\n page_id = self.cleaned_data[\"page_id\"]\n fb_user_id = self.cleaned_data[\"fb_user_id\"]\n\n app_id = settings.FACEBOOK_APPLICATION_ID\n app_secret = settings.FACEBOOK_APPLICATION_SECRET\n\n # get user long lived access token\n url = \"https://graph.facebook.com/oauth/access_token\"\n params = {\n \"grant_type\": \"fb_exchange_token\",\n \"client_id\": app_id,\n \"client_secret\": app_secret,\n \"fb_exchange_token\": auth_token,\n }\n\n response = requests.get(url, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to get a user long lived token\")\n\n long_lived_auth_token = response.json().get(\"access_token\", \"\")\n\n if long_lived_auth_token == \"\": # pragma: no cover\n raise Exception(\"Empty user access token!\")\n\n url = f\"https://graph.facebook.com/v7.0/{fb_user_id}/accounts\"\n params = {\"access_token\": long_lived_auth_token}\n\n response = requests.get(url, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to get a page long lived token\")\n\n response_json = response.json()\n\n page_access_token = \"\"\n for elt in response_json[\"data\"]:\n if elt[\"id\"] == str(page_id):\n page_access_token = elt[\"access_token\"]\n name = elt[\"name\"]\n break\n\n if page_access_token == \"\": # pragma: no cover\n raise Exception(\"Empty page access token!\")\n\n url = f\"https://graph.facebook.com/v7.0/{page_id}/subscribed_apps\"\n params = {\"access_token\": page_access_token}\n data = {\n \"subscribed_fields\": \"messages,message_deliveries,messaging_optins,messaging_optouts,messaging_postbacks,message_reads,messaging_referrals,messaging_handovers\"\n }\n\n response = requests.post(url, data=data, params=params)\n\n if response.status_code != 200: # pragma: no cover\n raise Exception(\"Failed to subscribe to app for webhook events\")\n\n self.cleaned_data[\"page_access_token\"] = page_access_token\n self.cleaned_data[\"name\"] = name\n\n except Exception:\n raise forms.ValidationError(_(\"Sorry your Facebook channel could not be connected. Please try again\"))\n\n return self.cleaned_data", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "@functools.wraps(handler)\n def test_can_view_reviewable_suggestions(\n self: _SelfBaseHandlerType,\n target_type: str,\n suggestion_type: str,\n **kwargs: Any\n ) -> _GenericHandlerFunctionReturnType:\n \"\"\"Checks whether the user can view reviewable suggestions.\n\n Args:\n target_type: str. The entity type of the target of the suggestion.\n suggestion_type: str. The type of the suggestion.\n **kwargs: *. Keyword arguments.\n\n Returns:\n *. The return value of the decorated function.\n\n Raises:\n NotFoundException. The given page cannot be found.\n Exception. User is not allowed to review translation suggestions.\n Exception. User is not allowed to review question suggestions.\n \"\"\"\n if not self.user_id:\n raise base.UserFacingExceptions.NotLoggedInException\n if suggestion_type == (\n feconf.SUGGESTION_TYPE_TRANSLATE_CONTENT):\n if user_services.can_review_translation_suggestions(self.user_id):\n return handler(self, target_type, suggestion_type, **kwargs)\n else:\n raise Exception(\n 'User with user_id: %s is not allowed to review '\n 'translation suggestions.' % self.user_id\n )\n elif suggestion_type == (\n feconf.SUGGESTION_TYPE_ADD_QUESTION):\n if user_services.can_review_question_suggestions(self.user_id):\n return handler(self, target_type, suggestion_type, **kwargs)\n else:\n raise Exception(\n 'User with user_id: %s is not allowed to review question '\n 'suggestions.' % self.user_id\n )\n else:\n raise self.NotFoundException", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@sensitive_variables(\"sauce\")\n@sensitive_post_parameters(\"bacon-key\", \"sausage-key\")\nasync def async_sensitive_view(request):\n # Do not just use plain strings for the variables' values in the code so\n # that the tests don't return false positives when the function's source is\n # displayed in the exception report.\n cooked_eggs = \"\".join([\"s\", \"c\", \"r\", \"a\", \"m\", \"b\", \"l\", \"e\", \"d\"]) # NOQA\n sauce = \"\".join( # NOQA\n [\"w\", \"o\", \"r\", \"c\", \"e\", \"s\", \"t\", \"e\", \"r\", \"s\", \"h\", \"i\", \"r\", \"e\"]\n )\n try:\n raise Exception\n except Exception:\n exc_info = sys.exc_info()\n send_log(request, exc_info)\n return technical_500_response(request, *exc_info)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def publish_story(self, story_id: str) -> None:\n \"\"\"Marks story with the given id as published.\n\n Raises:\n Exception. Story with given id doesn't exist in the topic.\n \"\"\"\n for story_reference in self.canonical_story_references:\n if story_reference.story_id == story_id:\n story_reference.story_is_published = True\n return\n\n for story_reference in self.additional_story_references:\n if story_reference.story_id == story_id:\n story_reference.story_is_published = True\n return\n raise Exception('Story with given id doesn\\'t exist in the topic')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def main(args: Optional[List[str]] = None) -> None:\n \"\"\"Runs the script to setup Oppia.\"\"\"\n unused_parsed_args = _PARSER.parse_args(args=args)\n test_python_version()\n\n # The second option allows this script to also be run from deployment\n # folders.\n if not os.getcwd().endswith(('oppia', 'deploy-')):\n print('')\n print('WARNING This script should be run from the oppia/ root folder.')\n print('')\n raise Exception('Invalid root directory.')\n\n # Set COMMON_DIR to the absolute path of the directory above OPPIA_DIR. This\n # is necessary becaue COMMON_DIR (or subsequent variables which refer to it)\n # may use it in a situation where relative paths won't work as expected(such\n # as $PYTHONPATH).\n create_directory(common.OPPIA_TOOLS_DIR)\n create_directory(common.THIRD_PARTY_DIR)\n common.create_readme(\n common.THIRD_PARTY_DIR,\n 'This folder contains third party libraries used in Oppia codebase.\\n'\n 'You can regenerate this folder by deleting it and then running '\n 'the start.py script.\\n')\n create_directory(common.NODE_MODULES_PATH)\n common.create_readme(\n common.NODE_MODULES_PATH,\n 'This folder contains node utilities used in Oppia codebase.\\n'\n 'You can regenerate this folder by deleting it and then running '\n 'the start.py script.\\n')\n\n # Download and install node.js.\n print('Checking if node.js is installed in %s' % common.OPPIA_TOOLS_DIR)\n if not os.path.exists(common.NODE_PATH):\n print('Installing Node.js')\n download_and_install_node()\n # Change ownership of node_modules.\n # Note: on some machines, these commands seem to take quite a long time.\n if not common.is_windows_os():\n common.recursive_chown(common.NODE_MODULES_PATH, os.getuid(), -1)\n common.recursive_chmod(common.NODE_MODULES_PATH, 0o744)\n\n # Download and install yarn.\n print('Checking if yarn is installed in %s' % common.OPPIA_TOOLS_DIR)\n if not os.path.exists(common.YARN_PATH):\n print('Removing package-lock.json')\n clean.delete_file('package-lock.json')\n common.print_each_string_after_two_new_lines([\n 'Installing yarn',\n 'WARNING: Please note that Oppia uses Yarn to manage node packages',\n 'do *NOT* use npm. For more information on how to use yarn,',\n 'visit https://yarnpkg.com/en/docs/usage.'])\n\n # NB: Update .yarnrc if the yarn version below is changed.\n yarn_file_name = 'yarn-v%s.tar.gz' % common.YARN_VERSION\n download_and_install_package(\n 'https://github.com/yarnpkg/yarn/releases/download/v%s/%s'\n % (common.YARN_VERSION, yarn_file_name), yarn_file_name)\n\n print('Environment setup completed.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def authenticate(self, server, login, password, db=''):\n print(\"Authenticating on server '%s' ...\" % server)\n\n # Fixate session with a given db if any\n self.session.get(server + '/web/login', params=dict(db=db))\n\n args = dict(login=login, password=password, db=db)\n res = self.session.post(server + '/base_import_module/login', args)\n if res.status_code == 404:\n raise Exception(\"The server '%s' does not have the 'base_import_module' installed.\" % server)\n elif res.status_code != 200:\n raise Exception(res.text)\n\n return res.headers.get('x-csrf-token')", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def get_user_id_from_email(\n self, email: str, strict: bool = True\n ) -> Optional[str]:\n \"\"\"Gets the user ID corresponding to the given email.\n\n Args:\n email: str. A valid email stored in the App Engine database.\n strict: bool. Whether to fail noisily if no user ID corresponding\n to the given email exists in the datastore.\n\n Returns:\n str|None. ID of the user possessing the given email, or None if\n the user does not exist.\n\n Raises:\n Exception. No user_id found for the given email address.\n \"\"\"\n user_settings = user_services.get_user_settings_by_auth_id(\n self.get_auth_id_from_email(email))\n if user_settings is None:\n if not strict:\n return None\n raise Exception(\n 'No user_id found for the given email address: %s' % email\n )\n\n return user_settings.user_id", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def try_infer_format_from_ext(path: str):\n if not path:\n return \"pipe\"\n\n for ext in PipelineDataFormat.SUPPORTED_FORMATS:\n if path.endswith(ext):\n return ext\n\n raise Exception(\n f\"Unable to determine file format from file extension {path}. \"\n f\"Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}\"\n )", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def _get_constant(name):\n constant = c_int(0)\n rc = LTC.crypt_get_constant(bytes(name), byref(constant))\n if rc != 0:\n raise Exception('LTC.crypt_get_constant(%s) rc = %d' % (name, rc))\n return constant.value", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "def parse_config(self) -> None:\n if not hasattr(self, \"config\") or self.config is None:\n raise Exception(\"Setup failed, dataset config was not loaded\")\n self.field_alias_converter = self.config.field_alias_converter\n self.function_converter = self.config.function_converter\n self.search_filter_converter = self.config.search_filter_converter\n self.orderby_converter = self.config.orderby_converter", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def add_oval_definition_to_cpe_oval(root, unlinked_oval_file_path, oval_def_id):\n oval_cpe_root = get_cpe_oval_root(root)\n if oval_cpe_root is None:\n raise Exception(\"CPE OVAL is missing in base DS!\")\n\n oval_document = get_linked_cpe_oval_document(unlinked_oval_file_path)\n\n references_to_keep = oval_document.get_all_references_of_definition(oval_def_id)\n oval_document.keep_referenced_components(references_to_keep)\n\n add_oval_components_to_oval_xml(\n oval_cpe_root, \"definitions\", oval_document.definitions\n )\n add_oval_components_to_oval_xml(oval_cpe_root, \"tests\", oval_document.tests)\n add_oval_components_to_oval_xml(oval_cpe_root, \"objects\", oval_document.objects)\n add_oval_components_to_oval_xml(oval_cpe_root, \"states\", oval_document.states)\n add_oval_components_to_oval_xml(oval_cpe_root, \"variables\", oval_document.variables)", "smellKey": "S112", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def read_pfm(file):\n \"\"\" Read a pfm file \"\"\"\n file = open(file, 'rb')\n\n color = None\n width = None\n height = None\n scale = None\n endian = None\n\n header = file.readline().rstrip()\n header = str(bytes.decode(header, encoding='utf-8'))\n if header == 'PF':\n color = True\n elif header == 'Pf':\n color = False\n else:\n raise Exception('Not a PFM file.')\n\n pattern = r'^(\\d+)\\s(\\d+)\\s$'\n temp_str = str(bytes.decode(file.readline(), encoding='utf-8'))\n dim_match = re.match(pattern, temp_str)\n if dim_match:\n width, height = map(int, dim_match.groups())\n else:\n temp_str += str(bytes.decode(file.readline(), encoding='utf-8'))\n dim_match = re.match(pattern, temp_str)\n if dim_match:\n width, height = map(int, dim_match.groups())\n else:\n raise Exception('Malformed PFM header: width, height cannot be found')\n\n scale = float(file.readline().rstrip())\n if scale < 0: # little-endian\n endian = '<'\n scale = -scale\n else:\n endian = '>' # big-endian\n\n data = np.fromfile(file, endian + 'f')\n shape = (height, width, 3) if color else (height, width)\n\n data = np.reshape(data, shape)\n # DEY: I don't know why this was there.\n file.close()\n \n return data, scale", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_AirSim", "language": "python"} {"function": "def get_formsets_with_inlines(self, request, obj=None):\n if request.is_add_view and obj is not None:\n raise Exception(\n \"'obj' passed to get_formsets_with_inlines wasn't None during add_view\"\n )\n if not request.is_add_view and obj is None:\n raise Exception(\n \"'obj' passed to get_formsets_with_inlines was None during change_view\"\n )\n return super().get_formsets_with_inlines(request, obj)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ParseVariableNameAndVectorOrTensorComponent(self, inJson, inBaseString):\n \"take a base string such as 'y axis variable ' or 'variable ', use it\\n to construct keys to define a scalar variable, vector component, vector\\n magnitude, or tensor component, and see if the json has those keys.\\n If the json has a key, use it to grab the variable name and setup.\\n Also look to see if the type of the variable is specifically defined\\n (node or element) or needs to be detected\\n \"\n variableFoundFlag = False\n self.mVariableIsVectorComponent = False\n self.mVariableIsVectorMagnitude = False\n\n if 'add separator to vector variable name' in inJson:\n self.mAddSeparatorToVectorVariableName = \\\n inJson['add separator to vector variable name']\n\n variableFoundFlag = self.CheckAndParseScalarVariable1(inJson, inBaseString)\n if not variableFoundFlag:\n variableFoundFlag = self.CheckAndParseVectorVariable1(inJson, inBaseString)\n if variableFoundFlag:\n #it is now apparent variable is intended to be used, not ignored\n self.mVariableIntendedForUseFlag = True\n if 'variable type' in inJson:\n variableType = inJson['variable type']\n self.mVariableType = variableType\n if variableType != 'element' \\\n and variableType != 'node' \\\n and variableType != 'global' \\\n and variableType != 'detect':\n errStr = 'error! inJson has variable type is neither node nor '\\\n 'element nor detect nor global in ParseVariableNameAndVectorOrTensorComponent\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n if variableType == 'detect':\n self.mVariableType = 'element'\n self.mVariableTypeNeedsDetection = True\n self.mVariableTypeWasDetected = False\n elif variableType == 'element':\n self.mVariableType = 'element'\n self.mVariableTypeNeedsDetection = False\n self.mVariableTypeWasDetected = True\n elif variableType == 'node':\n self.mVariableType = 'node'\n self.mVariableTypeNeedsDetection = False\n self.mVariableTypeWasDetected = True\n elif variableType == 'global':\n self.mVariableType = 'global'\n self.mVariableTypeNeedsDetection = False\n self.mVariableTypeWasDetected = True\n else:\n self.mVariableType = 'element'\n self.mVariableTypeNeedsDetection = True\n self.mVariableTypeWasDetected = False\n else:\n self.mVariableType = None\n\n if PhactoriDbg():\n str1 = \"ParseVariableNameAndVectorOrTensorComponent:\\n\"\n str2 = \"inBaseString:\\n\" + str(inBaseString) + \"\\n\"\n str3 = \"inJson:\\n\" + str(inJson) + \"\\n\"\n str4 = \"instance state after parsing:\\n\" + self.SelfToStr()\n myDebugPrint3(str1 + str2 + str3 + str4)\n return variableFoundFlag", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def parseImpl(self, *args):\n raise Exception(\n \"use of `...` expression without following SkipTo target expression\"\n )", "smellKey": "S112", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@test_utils.set_platform_parameters(\n [\n (platform_parameter_list.ParamName.SERVER_CAN_SEND_EMAILS, True),\n (\n platform_parameter_list.ParamName.SYSTEM_EMAIL_ADDRESS,\n 'system@example.com'\n )\n ]\n )\n def test_get_and_set_user_email_preferences_with_error(self) -> None:\n auth_id = 'someUser'\n username = 'username'\n user_email = 'user@example.com'\n\n user_id = user_services.create_new_user(auth_id, user_email).user_id\n user_services.set_username(user_id, username)\n\n def _mock_add_or_update_user_status(\n _email: str, _can_receive_updates: bool\n ) -> None:\n \"\"\"Mocks bulk_email_services.add_or_update_user_status().\n\n Raises:\n Exception. Mock exception - server error.\n \"\"\"\n raise Exception('Server error')\n\n with self.swap(\n bulk_email_services, 'add_or_update_user_status',\n _mock_add_or_update_user_status):\n try:\n user_services.update_email_preferences(\n user_id, False,\n feconf.DEFAULT_EDITOR_ROLE_EMAIL_PREFERENCE,\n feconf.DEFAULT_FEEDBACK_MESSAGE_EMAIL_PREFERENCE,\n feconf.DEFAULT_SUBSCRIPTION_EMAIL_PREFERENCE)\n except Exception:\n email_preferences = user_services.get_email_preferences(user_id)\n # 'can_receive_email_updates' should not be updated in this\n # case. Note that the default value is True.\n self.assertTrue(email_preferences.can_receive_email_updates)\n\n user_services.update_email_preferences(\n user_id, True,\n feconf.DEFAULT_EDITOR_ROLE_EMAIL_PREFERENCE,\n feconf.DEFAULT_FEEDBACK_MESSAGE_EMAIL_PREFERENCE,\n feconf.DEFAULT_SUBSCRIPTION_EMAIL_PREFERENCE)\n email_preferences = user_services.get_email_preferences(user_id)\n self.assertTrue(email_preferences.can_receive_email_updates)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def cmake_get_available_generators():\n \"\"\"Returns list of generators available in current CMake executable.\"\"\"\n result = run_process_and_capture_output(f'{CMAKE} --help')\n\n if result[0] != 0:\n raise Exception(f'cmake --help failed, exit code: {result[0]}\\n{result[1]}')\n\n help_text = result[1].splitlines()\n generators_start_index = help_text.index('Generators') + 3\n generators_text = help_text[generators_start_index::]\n\n generators = []\n for gen in generators_text:\n gen = gen.split('=')[0].strip().replace('* ', '')\n\n if gen and gen[0] != '=':\n generators.append(gen)\n\n return generators", "smellKey": "S112", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "def extract_flags(binary_path):\n ret = {}\n data = subprocess.run([binary_path, \"--help-xml\"], stdout=subprocess.PIPE).stdout.decode(\"utf-8\")\n # If something is printed out before the help output, it will break the the\n # XML parsing -> filter out if something is not XML line because something\n # can be logged before gflags output (e.g. during the global objects init).\n # This gets called during memgraph build phase to generate default config\n # file later installed under /etc/memgraph/memgraph.conf\n # NOTE: Don't use \\n in the gflags description strings.\n # NOTE: Check here if gflags version changes because of the XML format.\n data = \"\\n\".join([line for line in data.split(\"\\n\") if line.startswith(\"<\")])\n root = ET.fromstring(data)\n for child in root:\n if child.tag == \"usage\" and child.text.lower().count(\"warning\"):\n raise Exception(\"You should set the usage message!\")\n if child.tag == \"flag\":\n flag = {}\n for elem in child:\n flag[elem.tag] = elem.text if elem.text is not None else \"\"\n flag[\"override\"] = False\n ret[flag[\"name\"]] = flag\n return ret", "smellKey": "S112", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def clean_target_dir(target_dir):\n try:\n if os.path.exists(target_dir):\n shutil.rmtree(target_dir)\n except Exception as e:\n raise Exception(\"Error removing previous webpack target dir\") from e", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def regenerate_opportunities_related_to_topic(\n topic_id: str, delete_existing_opportunities: bool = False\n) -> int:\n \"\"\"Regenerates opportunity models which belongs to a given topic.\n\n Args:\n topic_id: str. The ID of the topic.\n delete_existing_opportunities: bool. Whether to delete all the existing\n opportunities related to the given topic.\n\n Returns:\n int. The number of opportunity models created.\n\n Raises:\n Exception. Failure to regenerate opportunities for given topic.\n \"\"\"\n if delete_existing_opportunities:\n exp_opportunity_models = (\n opportunity_models.ExplorationOpportunitySummaryModel.get_by_topic(\n topic_id))\n opportunity_models.ExplorationOpportunitySummaryModel.delete_multi(\n list(exp_opportunity_models))\n\n topic = topic_fetchers.get_topic_by_id(topic_id)\n story_ids = topic.get_canonical_story_ids()\n stories = story_fetchers.get_stories_by_ids(story_ids)\n exp_ids = []\n non_existing_story_ids = []\n\n for index, story in enumerate(stories):\n if story is None:\n non_existing_story_ids.append(story_ids[index])\n else:\n exp_ids += story.story_contents.get_all_linked_exp_ids()\n\n exp_ids_to_exp = exp_fetchers.get_multiple_explorations_by_id(\n exp_ids, strict=False)\n non_existing_exp_ids = set(exp_ids) - set(exp_ids_to_exp.keys())\n\n if len(non_existing_exp_ids) > 0 or len(non_existing_story_ids) > 0:\n raise Exception(\n 'Failed to regenerate opportunities for topic id: %s, '\n 'missing_exp_with_ids: %s, missing_story_with_ids: %s' % (\n topic_id, list(non_existing_exp_ids), non_existing_story_ids))\n\n exploration_opportunity_summary_list = []\n for story in stories:\n # Ruling out the possibility of None for mypy type checking, because\n # above we are already validating that story is not None.\n assert story is not None\n for exp_id in story.story_contents.get_all_linked_exp_ids():\n exploration_opportunity_summary_list.append(\n create_exp_opportunity_summary(\n topic, story, exp_ids_to_exp[exp_id]))\n\n _save_multi_exploration_opportunity_summary(\n exploration_opportunity_summary_list)\n return len(exploration_opportunity_summary_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def revert_m2m_for_related_files(apps, schema_editor):\n RelatedFile = apps.get_model(\"engine\", \"RelatedFile\")\n\n if top_related_file_uses := (\n RelatedFile.objects\n .annotate(images_count=models.aggregates.Count(\n \"images\",\n filter=models.Q(images__is_placeholder=False)\n ))\n .order_by(\"-images_count\")\n .filter(images_count__gt=1)\n .values_list(\"id\", \"images_count\")[:10]\n ):\n raise Exception(\n \"Can't run backward migration: \"\n \"there are RelatedFile objects with more than 1 related Image. \"\n \"Top RelatedFile uses: {}\".format(\n \", \".join(f\"\\n\\tid = {id}: {count}\" for id, count in top_related_file_uses)\n )\n )\n\n ThroughModel = RelatedFile.images.through\n\n (\n RelatedFile.objects\n .annotate(images_count=models.aggregates.Count(\n \"images\",\n filter=models.Q(images__is_placeholder=False)\n ))\n .filter(images_count__gt=0)\n .update(\n primary_image_id=models.Subquery(\n ThroughModel.objects\n .filter(relatedfile_id=models.OuterRef(\"id\"))\n .values_list(\"image_id\", flat=True)[:1]\n )\n )\n )", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def _GetLibMetadata(layer):\n \"\"\" Return a dictionary of library-specific data found in layer.\"\"\"\n \n globalPrim = layer.GetPrimAtPath('/GLOBAL')\n if not globalPrim:\n raise Exception(\"Code generation requires a \\\"/GLOBAL\\\" prim with \"\n \"customData to define at least libraryName. GLOBAL prim not found.\")\n \n if not globalPrim.customData:\n raise Exception(\"customData is either empty or not defined on /GLOBAL \"\n \"prim. At least \\\"libraryName\\\" entries in customData are required \"\n \"for code generation.\")\n \n # Return a copy of customData to avoid accessing an invalid map proxy during\n # template rendering.\n return dict(globalPrim.customData)", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_OpenUSD", "language": "python"} {"function": "def run(self):\n self.filenames = set()\n if self.arguments[0] == 'lexers':\n out = self.document_lexers()\n elif self.arguments[0] == 'formatters':\n out = self.document_formatters()\n elif self.arguments[0] == 'filters':\n out = self.document_filters()\n elif self.arguments[0] == 'lexers_overview':\n out = self.document_lexers_overview()\n else:\n raise Exception('invalid argument for \"pygmentsdoc\" directive')\n node = nodes.compound()\n vl = ViewList(out.split('\\n'), source='')\n nested_parse_with_titles(self.state, vl, node)\n for fn in self.filenames:\n self.state.document.settings.record_dependencies.add(fn)\n return node.children", "smellKey": "S112", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def next(self):\n trans_type = name = res_id = source = trad = None\n if self.extra_lines:\n trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0)\n if not res_id:\n res_id = '0'\n else:\n comments = []\n targets = []\n line = None\n fuzzy = False\n while not line:\n if 0 == len(self.lines):\n raise StopIteration()\n line = self.lines.pop(0).strip()\n while line.startswith('#'):\n if line.startswith('#~ '):\n break\n if line.startswith('#.'):\n line = line[2:].strip()\n if not line.startswith('module:'):\n comments.append(line)\n elif line.startswith('#:'):\n # Process the `reference` comments. Each line can specify\n # multiple targets (e.g. model, view, code, selection,\n # ...). For each target, we will return an additional\n # entry.\n for lpart in line[2:].strip().split(' '):\n trans_info = lpart.strip().split(':',2)\n if trans_info and len(trans_info) == 2:\n # looks like the translation trans_type is missing, which is not\n # unexpected because it is not a GetText standard. Default: 'code'\n trans_info[:0] = ['code']\n if trans_info and len(trans_info) == 3:\n # this is a ref line holding the destination info (model, field, record)\n targets.append(trans_info)\n elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'):\n fuzzy = True\n line = self.lines.pop(0).strip()\n if not self.lines:\n raise StopIteration()\n while not line:\n # allow empty lines between comments and msgid\n line = self.lines.pop(0).strip()\n if line.startswith('#~ '):\n while line.startswith('#~ ') or not line.strip():\n if 0 == len(self.lines):\n raise StopIteration()\n line = self.lines.pop(0)\n # This has been a deprecated entry, don't return anything\n return self.next()\n\n if not line.startswith('msgid'):\n raise Exception(\"malformed file: bad line: %s\" % line)\n source = unquote(line[6:])\n line = self.lines.pop(0).strip()\n if not source and self.first:\n self.first = False\n # if the source is \"\" and it's the first msgid, it's the special\n # msgstr with the informations about the traduction and the\n # traductor; we skip it\n self.extra_lines = []\n while line:\n line = self.lines.pop(0).strip()\n return self.next()\n\n while not line.startswith('msgstr'):\n if not line:\n raise Exception('malformed file at %d'% self.cur_line())\n source += unquote(line)\n line = self.lines.pop(0).strip()\n\n trad = unquote(line[7:])\n line = self.lines.pop(0).strip()\n while line:\n trad += unquote(line)\n line = self.lines.pop(0).strip()\n\n if targets and not fuzzy:\n # Use the first target for the current entry (returned at the\n # end of this next() call), and keep the others to generate\n # additional entries (returned the next next() calls).\n trans_type, name, res_id = targets.pop(0)\n for t, n, r in targets:\n if t == trans_type == 'code': continue\n self.extra_lines.append((t, n, r, source, trad, comments))\n\n if name is None:\n if not fuzzy:\n self.warn('Missing \"#:\" formated comment at line %d for the following source:\\n\\t%s',\n self.cur_line(), source[:30])\n return self.next()\n return trans_type, name, res_id, source, trad, '\\n'.join(comments)", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def library_to_binding(inp: cutlass.DataType):\n if not has_binding_type(inp):\n raise Exception(f\"No available conversion from library type {inp} to Python-bound CUTLASS type\")\n return library_to_binding_dict[inp]", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "@classmethod\n def get_question_skill_links_based_on_difficulty_equidistributed_by_skill(\n cls,\n total_question_count: int,\n skill_ids: List[str],\n difficulty_requested: float\n ) -> List[QuestionSkillLinkModel]:\n \"\"\"Fetches the list of constant number of random QuestionSkillLinkModels\n linked to the skills, sorted by the absolute value of the difference\n between skill difficulty and the requested difficulty.\n\n Args:\n total_question_count: int. The number of questions expected.\n skill_ids: list(str). The ids of skills for which the linked\n question ids are to be retrieved.\n difficulty_requested: float. The skill difficulty of the questions\n requested to be fetched.\n\n Returns:\n list(QuestionSkillLinkModel). A list of random\n QuestionSkillLinkModels corresponding to given skill_ids, with\n total_question_count/len(skill_ids) number of questions for\n each skill. If not evenly divisible, it will be rounded up.\n If not enough questions for a skill, just return all questions\n it links to.\n\n Raises:\n Exception. The number of skill IDs exceeds 20.\n \"\"\"\n if len(skill_ids) > feconf.MAX_NUMBER_OF_SKILL_IDS:\n raise Exception('Please keep the number of skill IDs below 20.')\n\n if (not skill_ids) or (total_question_count == 0):\n return []\n\n question_count_per_skill = int(\n math.ceil(float(total_question_count) / float(len(skill_ids))))\n\n question_skill_link_mapping = {}\n\n # For fetching the questions randomly we have used a random offset.\n # But this is a temporary solution since this method scales linearly.\n # Other alternative methods were:\n # 1) Using a random id in question id filter\n # 2) Adding an additional column that can be filtered upon.\n # But these methods are not viable because google datastore limits\n # each query to have at most one inequality filter. So we can't filter\n # on both question_id and difficulty. Please see\n # https://github.com/oppia/oppia/pull/9061#issuecomment-629765809\n # for more details.\n\n def get_offset(query: datastore_services.Query) -> int:\n \"\"\"Helper function to get the offset.\"\"\"\n question_count = query.count()\n if question_count > 2 * question_count_per_skill:\n return utils.get_random_int(\n question_count - (question_count_per_skill * 2))\n return 0\n\n for skill_id in skill_ids:\n query = cls.query(cls.skill_id == skill_id)\n\n equal_questions_query = query.filter(\n cls.skill_difficulty == difficulty_requested)\n\n # We fetch more questions here in order to try and ensure that the\n # eventual number of returned questions is sufficient to meet the\n # number requested, even after deduplication.\n new_question_skill_link_models: List[QuestionSkillLinkModel] = list(\n equal_questions_query.fetch(\n limit=question_count_per_skill * 2,\n offset=get_offset(equal_questions_query)\n )\n )\n for model in new_question_skill_link_models:\n if model.question_id in question_skill_link_mapping:\n new_question_skill_link_models.remove(model)\n\n if len(new_question_skill_link_models) >= question_count_per_skill:\n new_question_skill_link_models = random.sample(\n new_question_skill_link_models, question_count_per_skill)\n else:\n # Fetch QuestionSkillLinkModels with difficulty smaller than\n # requested difficulty.\n easier_questions_query = query.filter(\n cls.skill_difficulty < difficulty_requested)\n easier_question_skill_link_models: List[\n QuestionSkillLinkModel\n ] = list(\n easier_questions_query.fetch(\n limit=question_count_per_skill * 2,\n offset=get_offset(easier_questions_query)\n )\n )\n for model in easier_question_skill_link_models:\n if model.question_id in question_skill_link_mapping:\n easier_question_skill_link_models.remove(model)\n question_extra_count = (\n len(new_question_skill_link_models) +\n len(easier_question_skill_link_models) -\n question_count_per_skill)\n if question_extra_count >= 0:\n easier_question_skill_link_models = random.sample(\n easier_question_skill_link_models,\n question_count_per_skill -\n len(new_question_skill_link_models)\n )\n new_question_skill_link_models.extend(\n easier_question_skill_link_models)\n else:\n # Fetch QuestionSkillLinkModels with difficulty larger than\n # requested difficulty.\n new_question_skill_link_models.extend(\n easier_question_skill_link_models)\n harder_questions_query = query.filter(\n cls.skill_difficulty > difficulty_requested)\n harder_question_skill_link_models: List[\n QuestionSkillLinkModel\n ] = list(\n harder_questions_query.fetch(\n limit=question_count_per_skill * 2,\n offset=get_offset(harder_questions_query)\n )\n )\n for model in harder_question_skill_link_models:\n if model.question_id in question_skill_link_mapping:\n harder_question_skill_link_models.remove(model)\n question_extra_count = (\n len(new_question_skill_link_models) +\n len(harder_question_skill_link_models) -\n question_count_per_skill)\n if question_extra_count >= 0:\n harder_question_skill_link_models = (\n random.sample(\n harder_question_skill_link_models,\n question_count_per_skill -\n len(new_question_skill_link_models)\n ))\n new_question_skill_link_models.extend(\n harder_question_skill_link_models)\n\n new_question_skill_link_models = (\n new_question_skill_link_models[:question_count_per_skill])\n\n for model in new_question_skill_link_models:\n if model.question_id not in question_skill_link_mapping:\n question_skill_link_mapping[model.question_id] = model\n\n return list(question_skill_link_mapping.values())", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@acl_decorators.can_play_exploration\n def get(self, exploration_id: str) -> None:\n \"\"\"Handles GET request.\"\"\"\n assert self.normalized_request is not None\n story_url_fragment = self.normalized_request['story_url_fragment']\n story = story_fetchers.get_story_by_url_fragment(story_url_fragment)\n if story is None:\n raise self.InvalidInputException\n if not story.has_exploration(exploration_id):\n raise self.InvalidInputException\n prerequisite_skill_ids = story.get_prerequisite_skill_ids_for_exp_id(\n exploration_id\n )\n if prerequisite_skill_ids is None:\n raise Exception(\n 'No prerequisite skill_ids found for the exploration with '\n 'exploration_id: %s' % exploration_id\n )\n pretest_questions = (\n question_services.get_questions_by_skill_ids(\n feconf.NUM_PRETEST_QUESTIONS,\n prerequisite_skill_ids,\n True)\n )\n question_dicts = [question.to_dict() for question in pretest_questions]\n\n self.values.update({\n 'pretest_question_dicts': question_dicts,\n })\n self.render_json(self.values)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def unpublish_topic(topic_id: str, committer_id: str) -> None:\n \"\"\"Marks the given topic as unpublished.\n\n Args:\n topic_id: str. The id of the given topic.\n committer_id: str. ID of the committer.\n\n Raises:\n Exception. The given topic does not exist.\n Exception. The topic is already unpublished.\n Exception. The user does not have enough rights to unpublish the topic.\n \"\"\"\n topic_rights = topic_fetchers.get_topic_rights(topic_id, strict=False)\n if topic_rights is None:\n raise Exception('The given topic does not exist')\n user = user_services.get_user_actions_info(committer_id)\n if role_services.ACTION_CHANGE_TOPIC_STATUS not in user.actions:\n raise Exception(\n 'The user does not have enough rights to unpublish the topic.')\n\n if not topic_rights.topic_is_published:\n raise Exception('The topic is already unpublished.')\n topic_rights.topic_is_published = False\n commit_cmds = [topic_domain.TopicRightsChange({\n 'cmd': topic_domain.CMD_UNPUBLISH_TOPIC\n })]\n save_topic_rights(\n topic_rights, committer_id, 'Unpublished the topic', commit_cmds)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def migrate_state_training_jobs(\n state_training_jobs_mapping: classifier_domain.StateTrainingJobsMapping\n) -> None:\n \"\"\"Migrate exploration training jobs to latest version of algorithm_id\n and algorithm_version.\n\n This function lazily migrates an older classifier training job and\n trains new classifiers. Specifically, if training job exploration mapping of\n an <exploration, version, state> triplet is missing job_id for some\n algorithm_id, or if the job_id exists but it has been trained on a now\n obsolete algorithm, we re-submit the jobs.\n\n The function goes through existing training job exploration mapping and\n identifies three different types of algorithm IDs.\n 1. algorithm_ids_to_upgrade: Those which exist but needs to be\n upgraded a new algorithm (because existing one has been deprecated)\n by re-submitting the training job.\n 2. algorithm_ids_to_add: Those which doesn't exist and needs to be added\n by submitting a new training job.\n 3. algorithm_ids_to_remove: Those which needs to be removed since these\n algorithms are no longer supported.\n\n Once all three types of algorithm IDs are filtered, the function performs\n specific tasks tailored to each of them. We call this a lazy migration\n because it happens only when there is a query to retrieve a trained model\n for given <exploration, version, state> and algorithm_id.\n\n Args:\n state_training_jobs_mapping: StateTrainingJobsMapping. Domain\n object containing exploration to training job id mapping. This\n mapping is used to figure out jobs that need to be re-submitted,\n added or removed.\n\n Raises:\n Exception. Interaction id does not exist for the state.\n \"\"\"\n exp_id = state_training_jobs_mapping.exp_id\n exp_version = state_training_jobs_mapping.exp_version\n state_name = state_training_jobs_mapping.state_name\n\n exploration = exp_fetchers.get_exploration_by_id(\n exp_id, version=exp_version)\n interaction_id = exploration.states[state_name].interaction.id\n\n if interaction_id is None:\n raise Exception(\n 'Interaction id does not exist for the state having state_name: %s'\n % state_name\n )\n algorithm_id = feconf.INTERACTION_CLASSIFIER_MAPPING[\n interaction_id]['algorithm_id']\n algorithm_version = feconf.INTERACTION_CLASSIFIER_MAPPING[\n interaction_id]['algorithm_version']\n\n algorithm_id_to_algorithm_version = {\n algorithm_id: algorithm_version\n }\n\n # The list below contains only one element because as of now we only\n # support a single algorithm id per interaction type. However once the\n # support for multiple algorithm ids (see issue #10217) is added, the list\n # of possible algorithm ids can be retrieved from\n # feconf.INTERACTION_CLASSIFIER_MAPPING.\n possible_algorithm_ids = [algorithm_id]\n\n algorithm_ids_to_add = set(possible_algorithm_ids).difference(\n set(state_training_jobs_mapping.algorithm_ids_to_job_ids.keys()))\n\n algorithm_ids_to_remove = set(\n state_training_jobs_mapping.algorithm_ids_to_job_ids.keys()).difference(\n set(possible_algorithm_ids))\n\n algorithm_ids_to_upgrade = set(possible_algorithm_ids).intersection(\n set(state_training_jobs_mapping.algorithm_ids_to_job_ids.keys()))\n\n if len(algorithm_ids_to_add) > 0:\n job_dicts: List[JobInfoDict] = []\n\n for algorithm_id in algorithm_ids_to_add:\n next_scheduled_check_time = datetime.datetime.utcnow()\n training_data = exploration.states[state_name].get_training_data()\n\n classifier_domain.ClassifierTrainingJob(\n 'job_id_dummy', algorithm_id, interaction_id, exp_id,\n exp_version, next_scheduled_check_time, state_name,\n feconf.TRAINING_JOB_STATUS_NEW, training_data,\n algorithm_version).validate()\n\n job_dicts.append({\n 'algorithm_id': algorithm_id,\n 'interaction_id': interaction_id,\n 'exp_id': exp_id,\n 'exp_version': exp_version,\n 'next_scheduled_check_time': next_scheduled_check_time,\n 'state_name': state_name,\n 'training_data': training_data,\n 'status': feconf.TRAINING_JOB_STATUS_NEW,\n 'algorithm_version': algorithm_version\n })\n\n job_ids = classifier_models.ClassifierTrainingJobModel.create_multi(\n job_dicts)\n\n for algorithm_id, job_id in zip(algorithm_ids_to_add, job_ids):\n state_training_jobs_mapping.algorithm_ids_to_job_ids[\n algorithm_id] = job_id\n\n if algorithm_ids_to_upgrade:\n for algorithm_id in algorithm_ids_to_upgrade:\n classifier_training_job = (\n classifier_models.ClassifierTrainingJobModel.get_by_id(\n state_training_jobs_mapping.algorithm_ids_to_job_ids[\n algorithm_id]))\n classifier_training_job.algorithm_version = (\n algorithm_id_to_algorithm_version[algorithm_id])\n classifier_training_job.next_scheduled_check_time = (\n datetime.datetime.utcnow())\n classifier_training_job.status = feconf.TRAINING_JOB_STATUS_NEW\n classifier_training_job.update_timestamps()\n classifier_training_job.put()\n\n if algorithm_ids_to_remove:\n for algorithm_id in algorithm_ids_to_remove:\n delete_classifier_training_job(\n state_training_jobs_mapping.algorithm_ids_to_job_ids[\n algorithm_id])\n state_training_jobs_mapping.algorithm_ids_to_job_ids.pop(\n algorithm_id)\n\n state_training_jobs_mapping_model = (\n classifier_models.StateTrainingJobsMappingModel.get_model(\n exp_id, exp_version, state_name))\n state_training_jobs_mapping.validate()\n # Ruling out the possibility of None for mypy type checking.\n assert state_training_jobs_mapping_model is not None\n state_training_jobs_mapping_model.algorithm_ids_to_job_ids = (\n state_training_jobs_mapping.algorithm_ids_to_job_ids)\n state_training_jobs_mapping_model.update_timestamps()\n state_training_jobs_mapping_model.put()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_assets(self):\n \"\"\"Returns all org assets\"\"\"\n response = self.session.get(\n url=f\"{self.cobalt_api_url}/assets?limit=1000\",\n headers=self.get_headers(),\n )\n\n if response.ok:\n return response.json().get(\"data\")\n msg = (\n \"Unable to get assets due to {} - {}\".format(\n response.status_code, response.content.decode(\"utf-8\"),\n )\n )\n raise Exception(msg)", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def save_as_chunk(\n self, images: Iterator[FrameDescriptor], chunk_path: str\n ) -> Sequence[Tuple[int, int]]:\n first_frame, images = self._peek_first_frame(images)\n if not first_frame:\n raise Exception('no images to save')\n\n input_w = first_frame[0].width\n input_h = first_frame[0].height\n\n with av.open(chunk_path, 'w', format=self.FORMAT) as output_container:\n output_v_stream = self._add_video_stream(\n container=output_container,\n w=input_w,\n h=input_h,\n rate=self._output_fps,\n options=self._codec_opts,\n )\n\n with closing(output_v_stream):\n self._encode_images(images, output_container, output_v_stream)\n\n return [(input_w, input_h)]", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@patch(\"generate_test_code.parse_until_pattern\")\n def test_begin_header(self, parse_until_pattern_mock):\n \"\"\"\n Test that begin header is checked and parse_until_pattern() is called.\n :return:\n \"\"\"\n def stop(*_unused):\n \"\"\"Stop when parse_until_pattern is called.\"\"\"\n raise Exception\n parse_until_pattern_mock.side_effect = stop\n data = '''/* BEGIN_HEADER */\n#include \"mbedtls/ecp.h\"\n\n#define ECP_PF_UNKNOWN -1\n/* END_HEADER */\n'''\n stream = StringIOWrapper('test_suite_ut.function', data)\n self.assertRaises(Exception, parse_functions, stream)\n parse_until_pattern_mock.assert_called_with(stream, END_HEADER_REGEX)\n self.assertEqual(stream.line_no, 1)", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-mr", "language": "python"} {"function": "def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n urllib3_version = urllib3_version.split(\".\")\n assert urllib3_version != [\"dev\"] # Verify urllib3 isn't installed from git.\n\n # Sometimes, urllib3 only reports its version as 16.1.\n if len(urllib3_version) == 2:\n urllib3_version.append(\"0\")\n\n # Check urllib3 for compatibility.\n major, minor, patch = urllib3_version # noqa: F811\n major, minor, patch = int(major), int(minor), int(patch)\n # urllib3 >= 1.21.1\n assert major >= 1\n if major == 1:\n assert minor >= 21\n\n # Check charset_normalizer for compatibility.\n if chardet_version:\n major, minor, patch = chardet_version.split(\".\")[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # chardet_version >= 3.0.2, < 6.0.0\n assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)\n elif charset_normalizer_version:\n major, minor, patch = charset_normalizer_version.split(\".\")[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # charset_normalizer >= 2.0.0 < 4.0.0\n assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)\n else:\n raise Exception(\"You need either charset_normalizer or chardet installed\")", "smellKey": "S112", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def generate_contributor_certificate_data(\n username: str,\n suggestion_type: str,\n language_code: Optional[str],\n from_date: datetime.datetime,\n to_date: datetime.datetime\n) -> Optional[suggestion_registry.ContributorCertificateInfoDict]:\n \"\"\"Returns data to generate the certificate.\n\n Args:\n username: str. The username of the contributor.\n language_code: str|None. The language for which the contributions should\n be considered.\n suggestion_type: str. The type of suggestion that the certificate\n needs to generate.\n from_date: datetime.datetime. The start of the date range for which the\n contributions were created.\n to_date: datetime.datetime. The end of the date range for which the\n contributions were created.\n\n Returns:\n ContributorCertificateInfoDict|None. Data to generate the certificate,\n or None if no data is found.\n\n Raises:\n Exception. The suggestion type is invalid.\n Exception. There is no user for the given username.\n \"\"\"\n user_id = user_services.get_user_id_from_username(username)\n if user_id is None:\n raise Exception('There is no user for the given username.')\n\n if suggestion_type == feconf.SUGGESTION_TYPE_TRANSLATE_CONTENT:\n # For the suggestion_type translate_content, there should be a\n # corresponding language_code.\n assert isinstance(language_code, str)\n data = _generate_translation_contributor_certificate_data(\n language_code, from_date, to_date, user_id)\n\n elif suggestion_type == feconf.SUGGESTION_TYPE_ADD_QUESTION:\n data = _generate_question_contributor_certificate_data(\n from_date, to_date, user_id)\n\n else:\n raise Exception('The suggestion type is invalid.')\n\n return data.to_dict() if data is not None else None", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def calculate_from_state_answers_dict(\n self, state_answers_dict: stats_domain.StateAnswersDict\n ) -> stats_domain.StateAnswersCalcOutput:\n \"\"\"Computes the number of occurrences of each individual answer across\n all given answer sets, keeping only the top 10. Returns a list of dicts;\n each dict has keys 'answer' and 'frequency'.\n\n This method is run from within the context of a MapReduce job.\n\n Args:\n state_answers_dict: dict. A dict containing state answers and\n exploration information such as:\n * exploration_id: id of the exploration.\n * exploration_version: Specific version of the exploration or\n VERSION_ALL is used if answers are aggragated across\n multiple versions.\n * state_name: Name of the state.\n * interaction_id: id of the interaction.\n * submitted_answer_list: A list of submitted answers.\n\n Returns:\n stats_domain.StateAnswersCalcOutput. A calculation output object\n containing the commonly submitted answers, by frequency.\n\n Raises:\n Exception. Linear interaction is not allowed for the calculation of\n commonly submitted answers' frequencies.\n Exception. To calculate commonly submitted answers\\' frequencies,\n answers must be provided in an iterable form, like:\n SetOfUnicodeString.\n \"\"\"\n interaction_id = state_answers_dict['interaction_id']\n if interaction_id in feconf.LINEAR_INTERACTION_IDS:\n raise Exception(\n 'Linear interaction \\'%s\\' is not allowed for the calculation '\n 'of commonly submitted answers\\' frequencies.' % interaction_id\n )\n answer_dicts = state_answers_dict['submitted_answer_list']\n answer_list = []\n for answer_dict in answer_dicts:\n if not isinstance(answer_dict['answer'], collections.abc.Iterable):\n raise Exception(\n 'To calculate commonly submitted answers\\' frequencies, '\n 'answers must be provided in an iterable form, like: '\n 'SetOfUnicodeString.'\n )\n answer_list.append(answer_dict['answer'])\n answer_frequency_list = _get_top_answers_by_frequency(\n itertools.chain.from_iterable(answer_list),\n limit=10)\n return stats_domain.StateAnswersCalcOutput(\n state_answers_dict['exploration_id'],\n state_answers_dict['exploration_version'],\n state_answers_dict['state_name'],\n state_answers_dict['interaction_id'],\n self.id,\n answer_frequency_list)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def load_existing_DD_file(import_type, filepath, item_id=None, token=None):\n\n ### the following block of code converts .xlsx file into .csv for better performance from Pandas.\n ### Currently pandas' read_excel is super slow - could take minutes.\n # open given workbook\n # and store in excel object\n\n # bf is the old signifier for pennsieve\n if import_type == \"bf\":\n try:\n DD_df = load_metadata_to_dataframe(item_id, \"excel\", token, column_check, 0)\n except Exception as e:\n namespace_logger.info(e)\n raise Exception from e (\n \"SODA cannot read this dataset_description.xlsx file. If you are trying to retrieve a dataset_description.xlsx file from Pennsieve, please make sure you are signed in with your Pennsieve account on SODA.\"\n )\n\n else:\n excel = load_workbook(filepath)\n sheet = excel.active\n # writer object is created\n with tempfile.NamedTemporaryFile(mode=\"w\", newline=\"\", delete=False) as tf:\n col = csv.writer(tf)\n # writing the data in csv file\n for r in sheet.rows:\n col.writerow([cell.value for cell in r])\n\n DD_df = pd.DataFrame(\n pd.read_csv(tf.name, encoding=\"ISO-8859-1\", usecols=column_check, header=0)\n )\n\n # drop emtpy rows, convert values to strings, and remove white spaces\n DD_df = DD_df.dropna(axis=0, how=\"all\")\n DD_df = DD_df.replace(np.nan, \"\", regex=True)\n DD_df = DD_df.applymap(str)\n DD_df = DD_df.applymap(str.strip)\n\n basicInfoHeaders = [\n \"Type\",\n \"Title\",\n \"Subtitle\",\n \"Keywords\",\n \"Number of subjects\",\n \"Number of samples\",\n ]\n studyInfoHeaders = [\n \"Study purpose\",\n \"Study data collection\",\n \"Study primary conclusion\",\n \"Study organ system\",\n \"Study approach\",\n \"Study technique\",\n \"Study collection title\",\n ]\n contributorInfoHeaders = [\n \"Contributor name\",\n \"Contributor ORCiD\",\n \"Contributor affiliation\",\n \"Contributor role\",\n ]\n awardInfoHeaders = [\"Funding\", \"Acknowledgments\"]\n relatedInfoHeaders = [\n \"Identifier description\",\n \"Relation type\",\n \"Identifier\",\n \"Identifier type\",\n ]\n\n header_list = list(\n itertools.chain(\n basicInfoHeaders,\n studyInfoHeaders,\n contributorInfoHeaders,\n awardInfoHeaders,\n relatedInfoHeaders,\n )\n )\n\n # check if Metadata Element a.k.a Header column exists\n for key in [\"Metadata element\", \"Description\", \"Example\", \"Value\"]:\n if key not in DD_df:\n abort(400, \n \"The imported file is not in the correct format. Please refer to the new SPARC Dataset Structure (SDS) 2.0.0 <a target='_blank' rel='noopener noreferrer' href='https://github.com/SciCrunch/sparc-curation/blob/master/resources/DatasetTemplate/dataset_description.xlsx'>template</a> of the dataset_description.\"\n )\n\n if \"Metadata element\" not in DD_df:\n abort(400, \n \"The imported file is not in the correct format. Please refer to the new SPARC Dataset Structure (SDS) 2.0.0 <a target='_blank' rel='noopener noreferrer' href='https://github.com/SciCrunch/sparc-curation/blob/master/resources/DatasetTemplate/dataset_description.xlsx'>template</a> of the dataset_description.\"\n )\n\n else:\n for header_name in header_list:\n if header_name not in set(DD_df[\"Metadata element\"]):\n abort(400, \n \"The imported file is not in the correct format. Please refer to the new SPARC Dataset Structure (SDS) 2.0.0 <a target='_blank' rel='noopener noreferrer' href='https://github.com/SciCrunch/sparc-curation/blob/master/resources/DatasetTemplate/dataset_description.xlsx'>template</a> of the dataset_description.\"\n )\n\n if non_empty_1st_value := checkEmptyColumn(DD_df[\"Value\"]):\n abort(400, \n \"At least 1 value is required to import an existing dataset_description file\"\n )\n\n # drop Description and Examples columns\n DD_df = DD_df.drop(columns=[\"Description\", \"Example\"])\n\n ## convert DD_df to array of arrays (a matrix)\n DD_matrix = DD_df.to_numpy().tolist()\n\n # divide DD_df into UI sections (Basic Info + Participant Info, Study Info, Contributor Info, Related Info)\n basicInfoSection = []\n studyInfoSection = []\n conInfoSection = []\n awardInfoSection = []\n relatedInfoSection = []\n\n for array in DD_matrix:\n if array[0] in basicInfoHeaders:\n basicInfoSection.append(array)\n if array[0] in studyInfoHeaders:\n studyInfoSection.append(array)\n if array[0] in contributorInfoHeaders:\n conInfoSection.append(array)\n if array[0] in awardInfoHeaders:\n awardInfoSection.append(array)\n if array[0] in relatedInfoHeaders:\n relatedInfoSection.append(array)\n\n return {\n \"Basic information\": basicInfoSection,\n \"Study information\": studyInfoSection,\n \"Contributor information\": transposeMatrix(conInfoSection),\n \"Award information\": awardInfoSection,\n \"Related information\": transposeMatrix(relatedInfoSection),\n }", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def main(args: Optional[List[str]] = None) -> None:\n \"\"\"Installs all the third party libraries.\"\"\"\n if common.is_windows_os():\n # The redis cli is not compatible with Windows machines.\n raise Exception(\n 'The redis command line interface will not be installed because '\n 'your machine is on the Windows operating system.')\n unused_parsed_args = _PARSER.parse_args(args=args)\n install_python_prod_dependencies.main()\n install_dependencies_json_packages.download_all_dependencies(\n DEPENDENCIES_FILE_PATH)\n install_redis_cli()\n install_elasticsearch_dev_server()", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __export_xml_id(self):\n \"\"\" Return a valid xml_id for the record ``self``. \"\"\"\n if not self._is_an_ordinary_table():\n raise Exception(\n \"You can not export the column ID of model %s, because the \"\n \"table %s is not an ordinary table.\"\n % (self._name, self._table))\n ir_model_data = self.sudo().env['ir.model.data']\n data = ir_model_data.search([('model', '=', self._name), ('res_id', '=', self.id)])\n if data:\n if data[0].module:\n return '%s.%s' % (data[0].module, data[0].name)\n else:\n return data[0].name\n else:\n postfix = 0\n name = '%s_%s' % (self._table, self.id)\n while ir_model_data.search([('module', '=', '__export__'), ('name', '=', name)]):\n postfix += 1\n name = '%s_%s_%s' % (self._table, self.id, postfix)\n ir_model_data.create({\n 'model': self._name,\n 'res_id': self.id,\n 'module': '__export__',\n 'name': name,\n })\n return '__export__.' + name", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def send_historical_data_to_seer(\n alert_rule: AlertRule,\n project: Project,\n snuba_query: SnubaQuery | None = None,\n event_types: list[SnubaQueryEventType.EventType] | None = None,\n) -> AlertRuleStatus:\n \"\"\"\n Get 28 days of historical data and pass it to Seer to be used for prediction anomalies on the alert.\n \"\"\"\n if not snuba_query:\n snuba_query = SnubaQuery.objects.get(id=alert_rule.snuba_query_id)\n window_min = int(snuba_query.time_window / 60)\n dataset = get_dataset_from_label(snuba_query.dataset)\n query_columns = get_query_columns([snuba_query.aggregate], window_min)\n event_types = get_event_types(snuba_query, event_types)\n if not alert_rule.organization:\n raise ValidationError(\"Alert rule doesn't belong to an organization\")\n\n historical_data = fetch_historical_data(\n organization=alert_rule.organization,\n snuba_query=snuba_query,\n query_columns=query_columns,\n project=project,\n event_types=event_types,\n )\n\n if not historical_data:\n raise ValidationError(\"No historical data available.\")\n\n formatted_data = format_historical_data(\n data=historical_data,\n query_columns=query_columns,\n dataset=dataset,\n organization=project.organization,\n )\n if not formatted_data:\n raise ValidationError(\"Unable to get historical data for this alert.\")\n\n if (\n not alert_rule.sensitivity\n or not alert_rule.seasonality\n or alert_rule.threshold_type is None\n or alert_rule.organization is None\n ):\n # this won't happen because we've already gone through the serializer, but mypy insists\n raise ValidationError(\"Missing expected configuration for a dynamic alert.\")\n\n anomaly_detection_config = AnomalyDetectionConfig(\n time_period=window_min,\n sensitivity=alert_rule.sensitivity,\n direction=translate_direction(alert_rule.threshold_type),\n expected_seasonality=alert_rule.seasonality,\n )\n alert = AlertInSeer(id=alert_rule.id)\n body = StoreDataRequest(\n organization_id=alert_rule.organization.id,\n project_id=project.id,\n alert=alert,\n config=anomaly_detection_config,\n timeseries=formatted_data,\n )\n logger.info(\n \"Sending data to Seer's store data endpoint\",\n extra={\n \"ad_config\": anomaly_detection_config,\n \"alert\": alert_rule.id,\n \"dataset\": snuba_query.dataset,\n \"aggregate\": snuba_query.aggregate,\n \"meta\": json.dumps(historical_data.data.get(\"meta\", {}).get(\"fields\", {})),\n },\n )\n try:\n response = make_signed_seer_api_request(\n connection_pool=seer_anomaly_detection_connection_pool,\n path=SEER_ANOMALY_DETECTION_STORE_DATA_URL,\n body=json.dumps(body).encode(\"utf-8\"),\n )\n # See SEER_ANOMALY_DETECTION_TIMEOUT in sentry.conf.server.py\n except (TimeoutError, MaxRetryError):\n logger.warning(\n \"Timeout error when hitting Seer store data endpoint\",\n extra={\n \"rule_id\": alert_rule.id,\n \"project_id\": project.id,\n },\n )\n raise TimeoutError\n\n if response.status > 400:\n logger.error(\n \"Error when hitting Seer store data endpoint\",\n extra={\"response_code\": response.status},\n )\n raise Exception(\"Error when hitting Seer store data endpoint\")\n\n try:\n decoded_data = response.data.decode(\"utf-8\")\n except AttributeError:\n data_format_error_string = \"Seer store data response data is malformed\"\n logger.exception(\n data_format_error_string,\n extra={\n \"ad_config\": anomaly_detection_config,\n \"alert\": alert_rule.id,\n \"response_data\": response.data,\n \"response_code\": response.status,\n },\n )\n raise AttributeError(data_format_error_string)\n\n try:\n results: StoreDataResponse = json.loads(decoded_data)\n except JSONDecodeError:\n parse_error_string = \"Failed to parse Seer store data response\"\n logger.exception(\n parse_error_string,\n extra={\n \"ad_config\": anomaly_detection_config,\n \"alert\": alert_rule.id,\n \"response_data\": response.data,\n \"response_code\": response.status,\n \"dataset\": snuba_query.dataset,\n \"meta\": json.dumps(historical_data.data.get(\"meta\", {}).get(\"fields\", {})),\n },\n )\n raise ParseError(parse_error_string)\n\n if not results.get(\"success\"):\n message = results.get(\"message\", \"\")\n logger.error(\n \"Error when hitting Seer store data endpoint\",\n extra={\n \"rule_id\": alert_rule.id,\n \"project_id\": project.id,\n \"error_message\": message,\n },\n )\n raise Exception(message)\n\n data_start_index, data_end_index = _get_start_and_end_indices(formatted_data)\n if data_start_index == -1:\n return AlertRuleStatus.NOT_ENOUGH_DATA\n\n data_start_time = datetime.fromtimestamp(formatted_data[data_start_index][\"timestamp\"])\n data_end_time = datetime.fromtimestamp(formatted_data[data_end_index][\"timestamp\"])\n if data_end_time - data_start_time < timedelta(days=MIN_DAYS):\n return AlertRuleStatus.NOT_ENOUGH_DATA\n return AlertRuleStatus.PENDING", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, ifname):\n self.ifname = ifname\n self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))\n if \"PONG\" not in self.ctrl.request(\"PING\"):\n raise Exception(\"Failed to connect to eapol_test (%s)\" % ifname)\n self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))\n self.mon.attach()", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "@classmethod\n def create(\n cls,\n entity_type: str,\n entity_id: str,\n entity_version: int,\n task_type: str,\n target_type: str,\n target_id: str,\n issue_description: Optional[str] = None,\n status: str = constants.TASK_STATUS_OBSOLETE,\n resolver_id: Optional[str] = None,\n resolved_on: Optional[datetime.datetime] = None\n ) -> str:\n \"\"\"Creates a new task entry and puts it in storage.\n\n Args:\n entity_type: str. The type of entity a task entry refers to.\n entity_id: str. The ID of the entity a task entry refers to.\n entity_version: int. The version of the entity a task entry refers\n to.\n task_type: str. The type of task a task entry tracks.\n target_type: str. The type of sub-entity a task entry refers to.\n target_id: str. The ID of the sub-entity a task entry refers to.\n issue_description: str. Sentence generated by Oppia to describe why\n the task was created.\n status: str. Tracks the state/progress of a task entry.\n resolver_id: str. ID of the user who closed the task, if any.\n resolved_on: datetime. The date and time at which a task was closed\n or deprecated.\n\n Returns:\n str. The ID of the new task.\n\n Raises:\n Exception. A task corresponding to the provided identifier values\n (entity_type, entity_id, entity_version, task_type, target_type,\n target_id) already exists in storage.\n \"\"\"\n task_id = cls.generate_task_id(\n entity_type, entity_id, entity_version, task_type, target_type,\n target_id)\n if cls.get_by_id(task_id) is not None:\n raise Exception('Task id %s already exists' % task_id)\n composite_entity_id = cls.generate_composite_entity_id(\n entity_type, entity_id, entity_version)\n task_entry = cls(\n id=task_id,\n composite_entity_id=composite_entity_id,\n entity_type=entity_type,\n entity_id=entity_id,\n entity_version=entity_version,\n task_type=task_type,\n target_type=target_type,\n target_id=target_id,\n issue_description=issue_description,\n status=status,\n resolver_id=resolver_id,\n resolved_on=resolved_on)\n task_entry.update_timestamps()\n task_entry.put()\n return task_id", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def do_file(fn):\n odata = None\n if opts.dry_run:\n fp = open(fn, \"rb\")\n else:\n fp = open(fn, \"r+b\")\n fp.seek(0, 0)\n idata = fp.read()\n if idata[:4] != \"\\x7f\\x45\\x4c\\x46\":\n raise Exception, \"%s is not %s\" % (fn, \"ELF\")\n if idata[4:7] == \"\\x01\\x01\\x01\":\n # ELF32 LE\n eh, idata = idata[:52], idata[52:]\n e_shnum, e_shstrndx = struct.unpack(\"<HH\", eh[48:52])\n assert e_shstrndx + 3 == e_shnum\n ##eh = eh[:48] + struct.pack(\"<HH\", e_shnum - 3, e_shstrndx)\n elif idata[4:7] == \"\\x01\\x02\\x01\":\n # ELF32 BE\n eh, idata = idata[:52], idata[52:]\n e_shnum, e_shstrndx = struct.unpack(\">HH\", eh[48:52])\n assert e_shstrndx + 3 == e_shnum\n elif idata[4:7] == \"\\x02\\x01\\x01\":\n # ELF64 LE\n eh, idata = idata[:64], idata[64:]\n e_shnum, e_shstrndx = struct.unpack(\"<HH\", eh[60:64])\n assert e_shstrndx + 3 == e_shnum\n elif idata[4:7] == \"\\x02\\x02\\x01\":\n # ELF64 BE\n eh, idata = idata[:64], idata[64:]\n e_shnum, e_shstrndx = struct.unpack(\">HH\", eh[60:64])\n assert e_shstrndx + 3 == e_shnum\n else:\n raise Exception, \"%s is not %s\" % (fn, \"ELF\")\n\n odata = None\n pos = idata.find(\"\\0.symtab\\0.strtab\\0.shstrtab\\0\")\n if opts.with_dump:\n eh, odata = strip_with_dump(opts.with_dump, eh, idata)\n # Other compilers can intermix the contents of .rela sections\n # with PROGBITS sections. This happens on powerpc64le and arm64.\n # The general solution probably requires a C++ program\n # that combines \"objcopy -R\", \"objdump -htr\", and xstrip.\n if re.search(r\"^powerpc64\", os.path.basename(fn)):\n assert pos >= len(odata), (\"unexpected strip_with_dump\", pos, len(odata))\n elif re.search(r\"^arm64-\", os.path.basename(fn)):\n assert pos >= len(odata), (\"unexpected strip_with_dump\", pos, len(odata))\n else:\n assert pos == len(odata), (\"unexpected strip_with_dump\", pos, len(odata))\n else:\n if pos >= 0:\n odata = idata[:pos]\n\n if eh and odata and not opts.dry_run:\n fp.seek(0, 0)\n fp.write(eh[:-4]) # all but e_shnum, e_shstrndx\n fp.write(struct.pack(\"I\", 0)) # clear e_shnum, e_shstrndx\n fp.write(odata)\n fp.truncate()\n fp.close()", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_upx", "language": "python"} {"function": "@sensitive_variables(\"sauce\")\n def method(self, request):\n # Do not just use plain strings for the variables' values in the code\n # so that the tests don't return false positives when the function's\n # source is displayed in the exception report.\n cooked_eggs = \"\".join([\"s\", \"c\", \"r\", \"a\", \"m\", \"b\", \"l\", \"e\", \"d\"]) # NOQA\n sauce = \"\".join( # NOQA\n [\"w\", \"o\", \"r\", \"c\", \"e\", \"s\", \"t\", \"e\", \"r\", \"s\", \"h\", \"i\", \"r\", \"e\"]\n )\n try:\n raise Exception\n except Exception:\n exc_info = sys.exc_info()\n send_log(request, exc_info)\n return technical_500_response(request, *exc_info)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@classmethod\n def setUpTestData(cls):\n raise Exception", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __call__(self, graph, *args, **kwargs):\n yvec = h.Vector()\n xvec = h.Vector()\n self._data.to_vector(yvec, xvec)\n if isinstance(graph, hoc.HocObject):\n return yvec.line(graph, xvec, *args)\n str_type_graph = str(type(graph))\n if str_type_graph == \"<class 'plotly.graph_objs._figure.Figure'>\":\n # plotly figure\n import plotly.graph_objects as go\n\n kwargs.setdefault(\"mode\", \"lines\")\n return graph.add_trace(go.Scatter(x=xvec, y=yvec, *args, **kwargs))\n if str_type_graph == \"<class 'plotnine.ggplot.ggplot'>\":\n # ggplot object\n import plotnine as p9\n import pandas as pd\n\n return graph + p9.geom_line(\n *args,\n data=pd.DataFrame({\"x\": xvec, \"y\": yvec}),\n mapping=p9.aes(x=\"x\", y=\"y\"),\n **kwargs,\n )\n str_graph = str(graph)\n if str_graph.startswith(\"<module 'plotly' from \"):\n # plotly module\n import plotly.graph_objects as go\n\n fig = go.Figure()\n kwargs.setdefault(\"mode\", \"lines\")\n return fig.add_trace(go.Scatter(x=xvec, y=yvec, *args, **kwargs))\n if str_graph.startswith(\"<module 'plotnine' from \"):\n # plotnine module (contains ggplot)\n import plotnine as p9\n import pandas as pd\n\n return p9.geom_line(\n *args,\n data=pd.DataFrame({\"x\": xvec, \"y\": yvec}),\n mapping=p9.aes(x=\"x\", y=\"y\"),\n **kwargs,\n )\n if hasattr(graph, \"plot\"):\n # works with e.g. pyplot or a matplotlib axis\n return graph.plot(xvec, yvec, *args, **kwargs)\n if hasattr(graph, \"line\"):\n # works with e.g. bokeh\n return graph.line(xvec, yvec, *args, **kwargs)\n if str_type_graph == \"<class 'matplotlib.figure.Figure'>\":\n raise Exception(\"plot to a matplotlib axis not a matplotlib figure\")\n raise Exception(\"Unable to plot to graphs of type {}\".format(type(graph)))", "smellKey": "S112", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def parse_output(a, fmt):\n \"\"\"Parse the output according to specified format.\n\n Raise an error if the output can't be parsed.\"\"\"\n if fmt == 'json': # json: compare parsed data\n return json.loads(a)\n elif fmt == 'hex': # hex: parse and compare binary data\n return bytes.fromhex(a.strip())\n else:\n raise NotImplementedError(\"Don't know how to compare %s\" % fmt)", "smellKey": "S112", "smellId": null, "repo": "aureleoules_bitcoin", "language": "python"} {"function": "def validate(self, value: int) -> None:\n if value >> self.length != 0:\n raise Exception(f\"{self.name} exceed max bit value of {self.length}\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def TestForTruth(self, ioPipeAndViewsState):\n \"\"\"returns true if this criteria indicates we should render a frame, false\n otherwise\"\"\"\n\n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriImagesetOnOffFilterCriteria::TestForTruth entered\", 100)\n\n if self.mFrameTagCounter == ioPipeAndViewsState.mFrameTagCounter:\n if PhactoriDbg(100):\n myDebugPrint3(\n \"additional call, same mFrameTagCounter, just return value\", 100)\n return self.mReturnValAtCurrentFrameTagCounter\n self.mFrameTagCounter = ioPipeAndViewsState.mFrameTagCounter\n\n #if this has been triggered, it remains true no matter what variables do.\n #if there is a limit to the number of frames this trigger is true, it\n #will be false after that many frames no matter what\n #if self.mHasBeenTriggered:\n # if self.mNumberOfFramesAfterTrigger < 0:\n # #no frame limit; always true now\n # return True\n # else:\n # countSoFar = ioPipeAndViewsState.mFrameTagCounter - \\\n # self.mCallbackTagAtFirstTrigger\n # if PhactoriDbg(100):\n # myDebugPrint3(\n # \"mFrameTagCounter: \" + \\\n # str(ioPipeAndViewsState.mFrameTagCounter) + \"\\n\"\n # \"mCallbackTagAtFirstTrigger: \" + \\\n # str(self.mCallbackTagAtFirstTrigger) + \"\\n\"\n # \"countSoFar: \" + str(countSoFar) + \"\\n\"\n # \"mNumberOfFramesAfterTrigger: \" + \\\n # str(self.mNumberOfFramesAfterTrigger) + \"\\n\",\n # 100)\n # if countSoFar >= self.mNumberOfFramesAfterTrigger:\n # #reached frame limit\n # return False\n # else:\n # #haven't reached frame limit, still true\n # return True\n\n if self.mInputOperation == None:\n if self.mInputOperationName == None:\n self.mInputOperation = ioPipeAndViewsState.mIncomingDefaultOperation\n else:\n if self.mInputOperationName not in ioPipeAndViewsState.mOperationBlocks:\n errStr = 'error! in PhactoriImagesetOnOffFilterCriteria::TestForTruth calls for nonexistent input operation with name ' + str(self.mInputOperationName) + '\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n else:\n self.mInputOperation = \\\n ioPipeAndViewsState.mOperationBlocks[self.mInputOperationName]\n\n theParaViewFilter = self.mInputOperation.GetPvFilter()\n UpdatePipelineWithCurrentTimeArgument(theParaViewFilter)\n\n ###find min/max/avg/sum/count\n inputcsData = theParaViewFilter.GetClientSideObject().\\\n GetOutputDataObject(0)\n if inputcsData == None:\n if PhactoriDbg(100):\n myDebugPrint3('inputcsData is None, returning false', 100)\n self.mReturnValAtCurrentFrameTagCounter = False\n return False\n\n if PhactoriDbg():\n myDebugPrint3('finding min/max data for this processor at this timestep\\n')\n DataMinMax = [0.0, 0.0, False]\n DataSumCnt = [0.0, 0]\n\n FindMinMaxSumCntFromData(inputcsData, self.mVariableInfo, None, \n DataMinMax, DataSumCnt, None, None)\n\n #just return false if there is no min/max found\n #if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):\n if (DataSumCnt[1] == 0):\n if PhactoriDbg(100):\n myDebugPrint3('no data value for min/max found, returning', 100)\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriImagesetOnOffFilterCriteria returning false\",\n 100)\n self.mReturnValAtCurrentFrameTagCounter = False\n return False\n\n if self.mFunctionType == \"maximum\":\n mTestValue = DataMinMax[1]\n if PhactoriDbg():\n myDebugPrint3(\"test is against max, \" + str(mTestValue) + \"\\n\")\n elif self.mFunctionType == \"minimum\":\n mTestValue = DataMinMax[0]\n if PhactoriDbg():\n myDebugPrint3(\"test is against min, \" + str(mTestValue) + \"\\n\")\n elif self.mFunctionType == \"mean\":\n mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])\n if PhactoriDbg():\n myDebugPrint3(\"test is against mean, \" + str(mTestValue) + \"\\n\")\n elif self.mFunctionType == \"sum\":\n mTestValue = DataSumCnt[0]\n if PhactoriDbg():\n myDebugPrint3(\"test is against sum, \" + str(mTestValue) + \"\\n\")\n elif self.mFunctionType == \"count\":\n mTestValue = DataSumCnt[1]\n if PhactoriDbg():\n myDebugPrint3(\"test is against count, \" + str(mTestValue) + \"\\n\")\n else:\n myDebugPrint3AndException(\"PhactoriOnOffCriteria::TestForTruth\"\n \"bad mFunctionType: \" + str(self.mFunctionType) + \"\\n\")\n\n #let each threshold see if this value crossed from the previous value,\n #and update its internal frame count as appropriate\n for oneThrsld in self.mThresholdList:\n oneThrsld.ObservePotentialCrossingValue(mTestValue)\n\n #if any threshold was just triggered or was triggered and is within\n #the frame count limit, issue a 'True'\n for oneThrsld in self.mThresholdList:\n if oneThrsld.CurrentlyTriggered():\n self.mReturnValAtCurrentFrameTagCounter = True\n return True\n\n self.mReturnValAtCurrentFrameTagCounter = False\n return False\n\n #if self.mFunctionType == \"maximum\":\n # #possible issue, but probably not; if min/max is 0.0 we assume no\n # #data existed\n # #DataMinMax[2] == False: don't use this, it's not mpi shared\n # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):\n # if PhactoriDbg(100):\n # myDebugPrint3('no data value for max found, returning', 100)\n # if PhactoriDbg(\n # 100):\n # myDebugPrint3(\"PhactoriImagesetOnOffFilterCriteria returning false\",\n # 100)\n # return False\n # else:\n # mTestValue = DataMinMax[1]\n # if PhactoriDbg():\n # myDebugPrint3(\"test is against max, \" + str(mTestValue) + \"\\n\")\n #elif self.mFunctionType == \"minimum\":\n # #possible issue, but probably not; if min/max is 0.0 we assume no\n # #data existed\n # #DataMinMax[2] == False: don't use this, it's not mpi shared\n # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):\n # if PhactoriDbg(100):\n # myDebugPrint3('no data value for min found, returning', 100)\n # if PhactoriDbg(\n # 100):\n # myDebugPrint3(\"PhactoriImagesetOnOffFilterCriteria returning false\",\n # 100)\n # return False\n # else:\n # mTestValue = DataMinMax[0]\n # if PhactoriDbg():\n # myDebugPrint3(\"test is against min, \" + str(mTestValue) + \"\\n\")\n #elif self.mFunctionType == \"mean\":\n # if DataSumCnt[1] == 0:\n # if PhactoriDbg(100):\n # myDebugPrint3('no data values for mean found, returning false', 100)\n # return False\n # else:\n # mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])\n # if PhactoriDbg():\n # myDebugPrint3(\"test is against mean, \" + str(mTestValue) + \"\\n\")\n #elif self.mFunctionType == \"sum\":\n # mTestValue = DataSumCnt[0]\n # if PhactoriDbg():\n # myDebugPrint3(\"test is against sum, \" + str(mTestValue) + \"\\n\")\n #elif self.mFunctionType == \"count\":\n # mTestValue = DataSumCnt[1]\n # if PhactoriDbg():\n # myDebugPrint3(\"test is against count, \" + str(mTestValue) + \"\\n\")\n\n #if PhactoriDbg():\n # myDebugPrint3(\"test range: \" + str(self.mRange) + \"\\n\")\n #if mTestValue < self.mRange[0]:\n # if PhactoriDbg(100):\n # myDebugPrint3('below range, returning false', 100)\n # return False\n #if mTestValue > self.mRange[1]:\n # if PhactoriDbg(100):\n # myDebugPrint3('above range, returning false', 100)\n # return False\n\n #if PhactoriDbg(100):\n # myDebugPrint3('in range, returning true', 100)\n\n #if PhactoriDbg(100):\n # myDebugPrint3(\"cp 6000\")\n\n\n #self.mHasBeenTriggered = True\n #self.mCallbackTagAtFirstTrigger = ioPipeAndViewsState.mFrameTagCounter\n #return True", "smellKey": "S112", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def release(name, version, dist_name=None):\n if dist_name is None:\n dist_name = name.lower()\n\n dist = '%s-%s.tar.bz2' % (dist_name or name.lower(), version)\n try:\n os.remove(dist)\n os.remove(dist + '.sig')\n except Exception:\n pass\n\n status = subprocess.check_output('git status --porcelain', shell=True)\n if status:\n Logs.error('error: git working copy is dirty\\n' + status)\n raise Exception('git working copy is dirty')\n\n head = subprocess.check_output('git show -s --oneline', shell=True)\n head_summary = head[8:].strip().lower()\n expected_summary = '%s %s' % (name.lower(), version)\n if head_summary != expected_summary:\n raise Exception('latest commit \"%s\" does not match \"%s\"' % (\n head_summary, expected_summary))\n\n run_script(['./waf configure --docs',\n './waf',\n './waf distcheck',\n './waf posts',\n 'gpg -b %s' % dist,\n 'git tag -s v%s -m \"%s %s\"' % (version, name, version)])", "smellKey": "S112", "smellId": null, "repo": "uajithkumar_audacity", "language": "python"} {"function": "def validate_platform_params_values_for_blog_admin(\n new_platform_parameter_values: Mapping[\n str, platform_parameter_domain.PlatformDataTypes]\n) -> Mapping[str, platform_parameter_domain.PlatformDataTypes]:\n \"\"\"Validates new platform parameter values.\n\n Args:\n new_platform_parameter_values: dict. Data that needs to be validated.\n\n Returns:\n dict(str, PlatformDataTypes). Returns the dict after validation.\n\n Raises:\n Exception. The name of the platform parameter is not of type string.\n Exception. The value of the platform parameter is not of valid type.\n Exception. The max_number_of_tags_assigned_to_blog_post platform\n parameter has incoming value less than or equal to 0.\n \"\"\"\n for name, value in new_platform_parameter_values.items():\n if not isinstance(name, str):\n raise Exception(\n 'Platform parameter name should be a string, received'\n ': %s' % name)\n\n if not isinstance(value, (bool, float, int, str)):\n raise Exception(\n 'The value of %s platform parameter is not of valid type, '\n 'it should be one of %s.' % (\n name, str(platform_parameter_domain.PlatformDataTypes))\n )\n\n parameter = platform_parameter_registry.Registry.get_platform_parameter(\n name)\n\n if not (\n (isinstance(value, bool) and parameter.data_type == 'bool') or\n (isinstance(value, str) and parameter.data_type == 'string') or\n (isinstance(value, float) and parameter.data_type == 'number') or\n (isinstance(value, int) and parameter.data_type == 'number')\n ):\n raise Exception(\n 'The value of platform parameter %s is of type \\'%s\\', '\n 'expected it to be of type \\'%s\\'' % (\n name, value, parameter.data_type)\n )\n\n if (\n name ==\n platform_parameter_list.ParamName.\n MAX_NUMBER_OF_TAGS_ASSIGNED_TO_BLOG_POST.value\n ):\n assert isinstance(value, int)\n if value <= 0:\n raise Exception(\n 'The value of %s should be greater than 0, it is %s.' % (\n name, value)\n )\n # The new_platform_parameter_values do not represent a domain class directly\n # and in the handler these dict values are used to set platform parameters\n # individually. Hence conversion of dicts to domain objects is not required\n # for new_platform_parameter_values.\n return new_platform_parameter_values", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def get_topics_by_ids(\n topic_ids: List[str], strict: bool = False\n) -> Sequence[Optional[topic_domain.Topic]]:\n \"\"\"Returns a list of topics matching the IDs provided.\n\n Args:\n topic_ids: list(str). List of IDs to get topics for.\n strict: bool. Whether to fail noisily if no topic model exists\n with a given ID exists in the datastore.\n\n Returns:\n list(Topic|None). The list of topics corresponding to given ids\n (with None in place of topic ids corresponding to deleted topics).\n\n Raises:\n Exception. No topic model exists for the given topic_id.\n \"\"\"\n all_topic_models: List[Optional[topic_models.TopicModel]] = (\n topic_models.TopicModel.get_multi(topic_ids)\n )\n topics: List[Optional[topic_domain.Topic]] = []\n for index, topic_model in enumerate(all_topic_models):\n if topic_model is None:\n if strict:\n raise Exception(\n 'No topic model exists for the topic_id: %s'\n % topic_ids[index]\n )\n topics.append(topic_model)\n if topic_model is not None:\n topics.append(get_topic_from_model(topic_model))\n return topics", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def test_failure_in_test_execution_throws_error(self) -> None:\n with self.swap_install_third_party_libs:\n from scripts import run_backend_tests\n\n def mock_execute_tasks(*_: str) -> None:\n raise Exception('XYZ error occured.')\n self.swap_execute_task = self.swap(\n concurrent_task_utils, 'execute_tasks', mock_execute_tasks)\n swap_check_results = self.swap(\n run_backend_tests, 'check_test_results',\n lambda *unused_args, **unused_kwargs: (100, 0, 0, {}))\n\n with self.swap_execute_task, self.swap_redis_server, swap_check_results:\n with self.swap_cloud_datastore_emulator, self.assertRaisesRegex(\n Exception, 'Task execution failed.'\n ):\n run_backend_tests.main(args=[])", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _get_next_token(self, token_list: List[Token]) -> Token:\n \"\"\"Function to retrieve the token at the next position and then\n increment the _next_token_index.\n\n Args:\n token_list: list(Token). A list containing token objects formed from\n the given math expression.\n\n Returns:\n Token. Token at the next position.\n\n Raises:\n Exception. Invalid syntax: Unexpected end of expression.\n \"\"\"\n if self._next_token_index < len(token_list):\n token = token_list[self._next_token_index]\n self._next_token_index += 1\n return token\n\n raise Exception('Invalid syntax: Unexpected end of expression.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def check_all_models_are_tested():\n \"\"\"Check all models are properly tested.\"\"\"\n modules = get_model_modules()\n test_files = get_model_test_files()\n failures = []\n for module in modules:\n # Matches a module to its test file.\n test_file = [file for file in test_files if f\"test_{module.__name__.split('.')[-1]}.py\" in file]\n if len(test_file) == 0:\n failures.append(f\"{module.__name__} does not have its corresponding test file {test_file}.\")\n elif len(test_file) > 1:\n failures.append(f\"{module.__name__} has several test files: {test_file}.\")\n else:\n test_file = test_file[0]\n new_failures = check_models_are_tested(module, test_file)\n if new_failures is not None:\n failures += new_failures\n if len(failures) > 0:\n raise Exception(f\"There were {len(failures)} failures:\\n\" + \"\\n\".join(failures))", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def convert_csv_import(cr, module, fname, csvcontent, idref=None, mode='init',\n noupdate=False):\n '''Import csv file :\n quote: \"\n delimiter: ,\n encoding: utf-8'''\n if not idref:\n idref={}\n model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]\n #remove folder path from model\n head, model = os.path.split(model)\n\n input = cStringIO.StringIO(csvcontent) #FIXME\n reader = csv.reader(input, quotechar='\"', delimiter=',')\n fields = reader.next()\n fname_partial = \"\"\n if config.get('import_partial'):\n fname_partial = module + '/'+ fname\n if not os.path.isfile(config.get('import_partial')):\n pickle.dump({}, file(config.get('import_partial'),'w+'))\n else:\n data = pickle.load(file(config.get('import_partial')))\n if fname_partial in data:\n if not data[fname_partial]:\n return\n else:\n for i in range(data[fname_partial]):\n reader.next()\n\n if not (mode == 'init' or 'id' in fields):\n _logger.error(\"Import specification does not contain 'id' and we are in init mode, Cannot continue.\")\n return\n\n uid = 1\n datas = []\n for line in reader:\n if not (line and any(line)):\n continue\n try:\n datas.append(map(misc.ustr, line))\n except:\n _logger.error(\"Cannot import the line: %s\", line)\n\n registry = openerp.registry(cr.dbname)\n result, rows, warning_msg, dummy = registry[model].import_data(cr, uid, fields, datas,mode, module, noupdate, filename=fname_partial)\n if result < 0:\n # Report failed import and abort module install\n raise Exception(_('Module loading %s failed: file %s could not be processed:\\n %s') % (module, fname, warning_msg))\n if config.get('import_partial'):\n data = pickle.load(file(config.get('import_partial')))\n data[fname_partial] = 0\n pickle.dump(data, file(config.get('import_partial'),'wb'))\n cr.commit()", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def send_auto_complete(self, msg):\n if not isinstance(msg, Message):\n raise Exception('must provide Message instance')\n ret = capi.nl_send_auto_complete(self._sock, msg._msg)\n if ret < 0:\n raise Exception('send_auto_complete failed: ret=%d' % ret)\n return ret", "smellKey": "S112", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l1", "language": "python"} {"function": "def download_image_from_url(remote_url, timeout=2.5):\n \"\"\"Download an image file from a remote URL.\n\n This is a potentially dangerous operation, so we must perform some checks:\n - The remote URL is available\n - The Content-Length is provided, and is not too large\n - The file is a valid image file\n\n Arguments:\n remote_url: The remote URL to retrieve image\n max_size: Maximum allowed image size (default = 1MB)\n timeout: Connection timeout in seconds (default = 5)\n\n Returns:\n An in-memory PIL image file, if the download was successful\n\n Raises:\n requests.exceptions.ConnectionError: Connection could not be established\n requests.exceptions.Timeout: Connection timed out\n requests.exceptions.HTTPError: Server responded with invalid response code\n ValueError: Server responded with invalid 'Content-Length' value\n TypeError: Response is not a valid image\n \"\"\"\n # Check that the provided URL at least looks valid\n validator = URLValidator()\n validator(remote_url)\n\n # Calculate maximum allowable image size (in bytes)\n max_size = (\n int(get_global_setting('INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE')) * 1024 * 1024\n )\n\n # Add user specified user-agent to request (if specified)\n user_agent = get_global_setting('INVENTREE_DOWNLOAD_FROM_URL_USER_AGENT')\n\n headers = {'User-Agent': user_agent} if user_agent else None\n\n try:\n response = requests.get(\n remote_url,\n timeout=timeout,\n allow_redirects=True,\n stream=True,\n headers=headers,\n )\n # Throw an error if anything goes wrong\n response.raise_for_status()\n except requests.exceptions.ConnectionError as exc:\n raise Exception(_('Connection error') + f': {exc!s}')\n except requests.exceptions.Timeout as exc:\n raise exc\n except requests.exceptions.HTTPError:\n raise requests.exceptions.HTTPError(\n _('Server responded with invalid status code') + f': {response.status_code}'\n )\n except Exception as exc:\n raise Exception(_('Exception occurred') + f': {exc!s}')\n\n if response.status_code != 200:\n raise Exception(\n _('Server responded with invalid status code') + f': {response.status_code}'\n )\n\n try:\n content_length = int(response.headers.get('Content-Length', 0))\n except ValueError:\n raise ValueError(_('Server responded with invalid Content-Length value'))\n\n if content_length > max_size:\n raise ValueError(_('Image size is too large'))\n\n # Download the file, ensuring we do not exceed the reported size\n file = io.BytesIO()\n\n dl_size = 0\n chunk_size = 64 * 1024\n\n for chunk in response.iter_content(chunk_size=chunk_size):\n dl_size += len(chunk)\n\n if dl_size > max_size:\n raise ValueError(_('Image download exceeded maximum size'))\n\n file.write(chunk)\n\n if dl_size == 0:\n raise ValueError(_('Remote server returned empty response'))\n\n # Now, attempt to convert the downloaded data to a valid image file\n # img.verify() will throw an exception if the image is not valid\n try:\n img = Image.open(file).convert()\n img.verify()\n except Exception:\n raise TypeError(_('Supplied URL is not a valid image file'))\n\n return img", "smellKey": "S112", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "@Gemm.swizzling_functor.setter\n def swizzling_functor(self, swizzling_functor):\n \"\"\"\n Sets the swizzling functor to the type specified by `swizzling_functor`\n \"\"\"\n raise Exception('Grouped GEMM does not currently support different swizzling functors')", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_cutlass", "language": "python"} {"function": "def install_elasticsearch_dev_server() -> None:\n \"\"\"This installs a local ElasticSearch server to the oppia_tools\n directory to be used by development servers and backend tests.\n \"\"\"\n try:\n subprocess.call(\n ['%s/bin/elasticsearch' % common.ES_PATH, '--version'],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n # Set the minimum heap size to 100 MB and maximum to 500 MB.\n env={'ES_JAVA_OPTS': '-Xms100m -Xmx500m'}\n )\n print('ElasticSearch is already installed.')\n return\n except OSError:\n print('Installing ElasticSearch...')\n\n if common.is_mac_os() or common.is_linux_os():\n file_ext = 'tar.gz'\n def download_and_extract(*args: str) -> None:\n \"\"\"This downloads and extracts the elasticsearch files.\"\"\"\n download_and_untar_files(*args)\n elif common.is_windows_os():\n file_ext = 'zip'\n def download_and_extract(*args: str) -> None:\n \"\"\"This downloads and extracts the elasticsearch files.\"\"\"\n download_and_unzip_files(*args)\n else:\n raise Exception('Unrecognized or unsupported operating system.')\n\n download_and_extract(\n 'https://artifacts.elastic.co/downloads/elasticsearch/' +\n 'elasticsearch-%s-%s-x86_64.%s' % (\n common.ELASTICSEARCH_VERSION,\n common.OS_NAME.lower(),\n file_ext\n ),\n TARGET_DOWNLOAD_DIRS['oppiaTools'],\n 'elasticsearch-%s' % common.ELASTICSEARCH_VERSION,\n 'elasticsearch-%s' % common.ELASTICSEARCH_VERSION\n )\n print('ElasticSearch installed successfully.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _download_data(urls, upload_dir):\n job = rq.get_current_job()\n local_files = {}\n\n with make_requests_session() as session:\n for url in urls:\n name = os.path.basename(urlrequest.url2pathname(urlparse.urlparse(url).path))\n if name in local_files:\n raise Exception(\"filename collision: {}\".format(name))\n _validate_scheme(url)\n slogger.glob.info(\"Downloading: {}\".format(url))\n job.meta['status'] = '{} is being downloaded..'.format(url)\n job.save_meta()\n\n response = session.get(url, stream=True, proxies=PROXIES_FOR_UNTRUSTED_URLS)\n if response.status_code == 200:\n response.raw.decode_content = True\n with open(os.path.join(upload_dir, name), 'wb') as output_file:\n shutil.copyfileobj(response.raw, output_file)\n else:\n error_message = f\"Failed to download {response.url}\"\n if url != response.url:\n error_message += f\" (redirected from {url})\"\n\n if response.status_code == 407:\n error_message += \"; likely attempt to access internal host\"\n elif response.status_code:\n error_message += f\"; HTTP error {response.status_code}\"\n\n raise Exception(error_message)\n\n local_files[name] = True\n\n return list(local_files.keys())", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def add_srs_entry(\n srs, auth_name=\"EPSG\", auth_srid=None, ref_sys_name=None, database=None\n):\n \"\"\"\n Take a GDAL SpatialReference system and add its information to the\n `spatial_ref_sys` table of the spatial backend. Doing this enables\n database-level spatial transformations for the backend. Thus, this utility\n is useful for adding spatial reference systems not included by default with\n the backend:\n\n >>> from django.contrib.gis.utils import add_srs_entry\n >>> add_srs_entry(3857)\n\n Keyword Arguments:\n auth_name:\n This keyword may be customized with the value of the `auth_name` field.\n Defaults to 'EPSG'.\n\n auth_srid:\n This keyword may be customized with the value of the `auth_srid` field.\n Defaults to the SRID determined by GDAL.\n\n ref_sys_name:\n For SpatiaLite users only, sets the value of the `ref_sys_name` field.\n Defaults to the name determined by GDAL.\n\n database:\n The name of the database connection to use; the default is the value\n of `django.db.DEFAULT_DB_ALIAS` (at the time of this writing, its value\n is 'default').\n \"\"\"\n database = database or DEFAULT_DB_ALIAS\n connection = connections[database]\n\n if not hasattr(connection.ops, \"spatial_version\"):\n raise Exception(\"The `add_srs_entry` utility only works with spatial backends.\")\n if not connection.features.supports_add_srs_entry:\n raise Exception(\"This utility does not support your database backend.\")\n SpatialRefSys = connection.ops.spatial_ref_sys()\n\n # If argument is not a `SpatialReference` instance, use it as parameter\n # to construct a `SpatialReference` instance.\n if not isinstance(srs, SpatialReference):\n srs = SpatialReference(srs)\n\n if srs.srid is None:\n raise Exception(\n \"Spatial reference requires an SRID to be \"\n \"compatible with the spatial backend.\"\n )\n\n # Initializing the keyword arguments dictionary for both PostGIS\n # and SpatiaLite.\n kwargs = {\n \"srid\": srs.srid,\n \"auth_name\": auth_name,\n \"auth_srid\": auth_srid or srs.srid,\n \"proj4text\": srs.proj4,\n }\n # Backend-specific fields for the SpatialRefSys model.\n srs_field_names = {f.name for f in SpatialRefSys._meta.get_fields()}\n if \"srtext\" in srs_field_names:\n kwargs[\"srtext\"] = srs.wkt\n if \"ref_sys_name\" in srs_field_names:\n # SpatiaLite specific\n kwargs[\"ref_sys_name\"] = ref_sys_name or srs.name\n\n # Creating the spatial_ref_sys model.\n try:\n # Try getting via SRID only, because using all kwargs may\n # differ from exact wkt/proj in database.\n SpatialRefSys.objects.using(database).get(srid=srs.srid)\n except SpatialRefSys.DoesNotExist:\n SpatialRefSys.objects.using(database).create(**kwargs)", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __call__(self, req):\n # NOTE: all imports done here due to required initialization of\n # of the configuration module before all others.\n # Initialization is dependent on RHNComponentType in the\n # req object.\n\n if self.__init:\n from .apacheHandler import getComponentType\n # We cannot trust the config files to tell us if we are in the\n # broker or in the redirect because we try to always pass\n # upstream all requests\n componentType = getComponentType(req)\n initCFG(componentType)\n initLOG(CFG.LOG_FILE, CFG.DEBUG, f\"wsgi_{componentType}\")\n log_debug(2, 'New request, component %s' % (componentType, ))\n\n # Instantiate the handlers\n if HandlerWrap.svrHandlers is None:\n HandlerWrap.svrHandlers = self.get_handler_factory(req)()\n\n if self.__init:\n # Set the component type\n HandlerWrap.svrHandlers.set_component(componentType)\n\n try:\n log_setreq(req)\n if hasattr(HandlerWrap.svrHandlers, self.__name):\n f = getattr(HandlerWrap.svrHandlers, self.__name)\n ret = f(req)\n else:\n raise Exception(\"Class has no attribute %s\" % self.__name)\n # pylint: disable=W0702\n except:\n Traceback(self.__name, req, extra=\"Unhandled exception type\",\n severity=\"unhandled\")\n return apache.HTTP_INTERNAL_SERVER_ERROR\n else:\n return ret", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def conduct(self):\n\t\tmplsbuffer = bytearray(\"MPLS0200\")\n\n\t\tmplsbuffer += '\\x00\\x00\\x00\\x3a' # playlist_start_address #Position of PlayList, from beginning of file\n\n\t\tmplsbuffer += zeros[0:4] # playlist_mark_start_address Position of PlayListMark, from beginning of file\n\t\tmplsbuffer += zeros[0:4] # extension_data_start_address= bytearray(4)\n\t\tmplsbuffer += zeros[0:20] # reserved\n\n\t\tAppInfoPlayList = bytearray() # length of AppInfoPlayList (4 bytes)\n\n\t\tAppInfoPlayList += '\\x00' # reserved 1 byte\n\t\tAppInfoPlayList += '\\x01' # playlist_playback_type\n\t\tAppInfoPlayList += zeros[0:2] # reserved 2 bytes\n\t\tAppInfoPlayList += zeros[0:8] # UO_mask_table\n\n\t\tAppInfoPlayList += '\\x40\\x00' # playlist_random_access_flag, audio_mix_app_flag, lossless_may_bypass_mixer_flag, 13 bit reserved_for_word_align\n\n\t\tmplsbuffer += bytearray(struct.pack('>L', len(AppInfoPlayList)))\n\t\tmplsbuffer += AppInfoPlayList\n\n\t\tPlayList = bytearray()\t\t#length of PlayList (4 bytes)\n\n\t\tPlayList += zeros[0:2]\t\t#reserved 2 bytes\n\n\t\tnum_of_playitems = 1\n\t\tPlayList += struct.pack('>H', num_of_playitems)\n\n\t\tnum_of_subpaths = 0\n\t\tPlayList += struct.pack('>H', num_of_subpaths)\n\n\t\tnum_primary_video = len(self.title.VideoStreams)\n\n\t\tif num_primary_video == 0:\n\t\t\tself.error_text = \"Title %05d has no valid video streams!\" % self.mpls_num\n\t\t\traise Exception(self.error_text)\n\n\t\tnum_primary_audio = len(self.title.AudioStreams)\n\n\t\tnum_pg = 0\t\t\t# (presentation graphics, subtitle)\n\t\tnum_ig = 0\t\t\t# (interactive graphics)\n\t\tnum_secondary_audio = 0\n\t\tnum_secondary_video = 0\n\t\tnum_PIP_PG = 0\n\n\t\tfor item_i in list(range(num_of_playitems)):\n\t\t\tPlayItem = bytearray()\n\t\t\tclip_no = \"%05d\" % self.mpls_num\n\t\t\tPlayItem += bytearray(clip_no)\n\t\t\tPlayItem += \"M2TS\"\n\t\t\tPlayItem += '\\x00\\x01'\t\t\t# reserved 11 bits & 1 bit is_multi_angle & connection_condition\n\t\t\tPlayItem += '\\x00'\t\t\t# stc_id\n\t\t\tPlayItem += self.title.InTime\t\t# start time (in 45khz ticks)\n\t\t\tPlayItem += self.title.OutTime\t\t# end time (in 45khz ticks)\n\t\t\tPlayItem += zeros[0:8]\t\t\t# UO_mask_table\n\t\t\tPlayItem += '\\x00'\t\t\t# random_access_flag (uppermost bit, 0=permit) & reserved 7 bits\n\t\t\tPlayItem += '\\x01\\x00\\x02'\t\t# still_mode & still_time (in s)\n\n\t\t\tStnTable = bytearray() # len 4 bytes\n\t\t\tStnTable += zeros[0:2] # reserved\n\t\t\tStnTable += struct.pack('B', num_primary_video)\n\t\t\tStnTable += struct.pack('B', num_primary_audio)\n\t\t\tStnTable += struct.pack('B', num_pg)\n\t\t\tStnTable += struct.pack('B', num_ig)\n\t\t\tStnTable += struct.pack('B', num_secondary_audio)\n\t\t\tStnTable += struct.pack('B', num_secondary_video)\n\t\t\tStnTable += struct.pack('B', num_PIP_PG)\n\t\t\tStnTable += zeros[0:5] # reserved\n\n\t\t\tfor vid in self.title.VideoStreams:\n\t\t\t\tprint(\"adding vid\", vid, type(vid))\n\t\t\t\tVideoEntry = bytearray(1) # len\n\t\t\t\tVideoEntry += '\\x01'\t\t# type 01 = elementary stream of the clip used by the PlayItem\n\n\t\t\t\tVideoEntry += vid.pid\t\t# stream_pid\n\t\t\t\tVideoEntry += zeros[0:6] # reserved\n\t\t\t\tVideoEntry[0] = struct.pack('B', len(VideoEntry) - 1)\n\n\t\t\t\tVideoAttr = bytearray(1) # len\n\t\t\t\tVideoAttr += vid.streamType # Video type\n\t\t\t\tVideoAttr += vid.formatByte # Format & Framerate\n\t\t\t\tVideoAttr += zeros[0:3]\t\t# reserved\n\t\t\t\tVideoAttr[0] = struct.pack('B', len(VideoAttr) - 1)\n\n\t\t\t\tStnTable += VideoEntry\n\t\t\t\tStnTable += VideoAttr\n\n\t\t\tfor aud in self.title.AudioStreams:\n\t\t\t\tAudioEntry = bytearray(1) # len\n\t\t\t\tAudioEntry += '\\x01'\t\t# type 01 = elementary stream of the clip used by the PlayItem\n\t\t\t\tAudioEntry += aud.pid\t\t# stream_pid\n\t\t\t\tAudioEntry += zeros[0:6] # reserved\n\t\t\t\tAudioEntry[0] = struct.pack('B', len(AudioEntry) - 1)\n\n\t\t\t\tAudioAttr = bytearray(1) # len\n\t\t\t\tAudioAttr += aud.streamType # stream_coding_type\n\t\t\t\tAudioAttr += aud.formatByte # Audio Format & Samplerate\n\t\t\t\tAudioAttr += aud.languageCode # Audio Language Code\n\t\t\t\tAudioAttr[0] = struct.pack('B', len(AudioAttr) - 1)\n\n\t\t\t\tStnTable += AudioEntry\n\t\t\t\tStnTable += AudioAttr\n\n\t\t\tPlayItem += struct.pack('>H', len(StnTable))\n\t\t\tPlayItem += StnTable\n\n\t\t\tPlayList += struct.pack('>H', len(PlayItem))\n\t\t\tPlayList += PlayItem\n\n\t\tmplsbuffer += struct.pack('>L', len(PlayList))\n\t\tmplsbuffer += PlayList\n\n\t\tPlayListMarkStartAdress = bytearray(struct.pack('>L', len(mplsbuffer)))\n\t\tmplsbuffer[0x0C:0x10] = PlayListMarkStartAdress\n\n\t\tif len(self.title.entrypoints) == 0:\n\t\t\tprint(\"no entry points found for this title!\")\n\t\t\tself.title.entrypoints.append(0)\n\n\t\t#playlist mark list [(id, type, timestamp, skip duration)]\n\t\t#! implement cutlist / skip marks\n\t\tmarkslist = [(0, 1, self.title.entrypoints[0][1] / 2, 0)]\n\t\tmark_id = 1\n\t\ttry:\n\t\t\tfor chapter_pts in self.title.chaptermarks:\n\t\t\t\tif (chapter_pts):\n\t\t\t\t\tep_pts = self.title.getEPforOffsetPTS(chapter_pts)\n\t\t\t\t\tif (ep_pts > markslist[0][2]):\n\t\t\t\t\t\tmarkslist.append((mark_id, 1, ep_pts, 0))\n\t\t\t\t\t\tmark_id += 1\n\t\texcept AttributeError:\n\t\t\tprint(\"title has no chaptermarks\")\n\t\tprint(\"**** final markslist\", markslist)\n\n\t\tnum_marks = len(markslist)\n\t\tPlayListMark = bytearray()\t\t\t# len 4 bytes\n\t\tPlayListMark += struct.pack('>H', num_marks)\n\t\tfor mark_id, mark_type, mark_ts, skip_dur in markslist:\n\t\t\tMarkEntry = bytearray()\n\t\t\tMarkEntry += struct.pack('B', mark_id) # mark_id\n\t\t\tMarkEntry += struct.pack('B', mark_type) # mark_type 00=resume, 01=bookmark, 02=skip mark\n\t\t\tMarkEntry += struct.pack('>H', item_i) # play_item_ref (number of PlayItem that the mark is for\n\t\t\tMarkEntry += struct.pack('>L', mark_ts) # (in 45khz time ticks)\n\t\t\tMarkEntry += '\\xFF\\xFF'\t\t\t# entry_ES_PID\n\t\t\tMarkEntry += struct.pack('>L', skip_dur) # for skip marks: skip duration\n\t\t\tPlayListMark += MarkEntry\n\n\t\tmplsbuffer += struct.pack('>L', len(PlayListMark))\n\t\tmplsbuffer += PlayListMark\n\n\t\tf = open(self.job.workspace + \"BDMV/PLAYLIST/%05d.mpls\" % self.mpls_num, 'w')\n\t\tf.write(buffer(mplsbuffer))\n\t\tf.close()\n\t\tf = open(self.job.workspace + \"BDMV/BACKUP/PLAYLIST/%05d.mpls\" % self.mpls_num, 'w')\n\t\tf.write(buffer(mplsbuffer))\n\t\tf.close()", "smellKey": "S112", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _load_dummy_new_structures_data(self) -> None:\n \"\"\"Loads the database with two topics (one of which is empty), a story\n and three skills in the topic (two of them in a subtopic) and a question\n attached to each skill.\n\n Raises:\n Exception. Cannot load new structures data in production mode.\n Exception. User does not have enough rights to generate data.\n \"\"\"\n assert self.user_id is not None\n if constants.DEV_MODE:\n if feconf.ROLE_ID_CURRICULUM_ADMIN not in self.user.roles:\n raise Exception(\n 'User does not have enough rights to generate data.')\n topic_id_1 = topic_fetchers.get_new_topic_id()\n story_id = story_services.get_new_story_id()\n\n skill_id_1 = skill_services.get_new_skill_id()\n skill_id_2 = skill_services.get_new_skill_id()\n skill_id_3 = skill_services.get_new_skill_id()\n\n question_id_1 = question_services.get_new_question_id()\n question_id_2 = question_services.get_new_question_id()\n question_id_3 = question_services.get_new_question_id()\n question_id_4 = question_services.get_new_question_id()\n question_id_5 = question_services.get_new_question_id()\n\n skill_1 = self._create_dummy_skill(\n skill_id_1, 'Dummy Skill 1', '<p>Dummy Explanation 1</p>')\n skill_2 = self._create_dummy_skill(\n skill_id_2, 'Dummy Skill 2', '<p>Dummy Explanation 2</p>')\n skill_3 = self._create_dummy_skill(\n skill_id_3, 'Dummy Skill 3', '<p>Dummy Explanation 3</p>')\n\n question_1 = self._create_dummy_question(\n question_id_1, 'Question 1', [skill_id_1])\n question_2 = self._create_dummy_question(\n question_id_2, 'Question 2', [skill_id_2])\n question_3 = self._create_dummy_question(\n question_id_3, 'Question 3', [skill_id_3])\n question_4 = self._create_dummy_question(\n question_id_4, 'Question 4', [skill_id_1])\n question_5 = self._create_dummy_question(\n question_id_5, 'Question 5', [skill_id_1])\n question_services.add_question(self.user_id, question_1)\n question_services.add_question(self.user_id, question_2)\n question_services.add_question(self.user_id, question_3)\n question_services.add_question(self.user_id, question_4)\n question_services.add_question(self.user_id, question_5)\n\n question_services.create_new_question_skill_link(\n self.user_id, question_id_1, skill_id_1, 0.3)\n question_services.create_new_question_skill_link(\n self.user_id, question_id_4, skill_id_1, 0.3)\n question_services.create_new_question_skill_link(\n self.user_id, question_id_5, skill_id_1, 0.3)\n question_services.create_new_question_skill_link(\n self.user_id, question_id_2, skill_id_2, 0.5)\n question_services.create_new_question_skill_link(\n self.user_id, question_id_3, skill_id_3, 0.7)\n\n topic_1 = topic_domain.Topic.create_default_topic(\n topic_id_1, 'Dummy Topic 1', 'dummy-topic-one', 'description',\n 'fragm')\n\n topic_1.update_meta_tag_content('dummy-meta')\n raw_image = b''\n with open(\n 'core/tests/data/thumbnail.svg', 'rt',\n encoding='utf-8') as svg_file:\n svg_file_content = svg_file.read()\n raw_image = svg_file_content.encode('ascii')\n fs_services.save_original_and_compressed_versions_of_image(\n 'thumbnail.svg', feconf.ENTITY_TYPE_TOPIC, topic_id_1,\n raw_image, 'thumbnail', False)\n topic_services.update_thumbnail_filename(topic_1, 'thumbnail.svg')\n topic_1.update_thumbnail_bg_color('#C6DCDA')\n topic_1.add_canonical_story(story_id)\n topic_1.add_uncategorized_skill_id(skill_id_1)\n topic_1.add_uncategorized_skill_id(skill_id_2)\n topic_1.add_uncategorized_skill_id(skill_id_3)\n topic_1.update_skill_ids_for_diagnostic_test([skill_id_1])\n topic_1.add_subtopic(1, 'Dummy Subtopic Title', 'dummysubtopic')\n topic_services.update_subtopic_thumbnail_filename(\n topic_1, 1, 'thumbnail.svg')\n topic_1.update_subtopic_thumbnail_bg_color(\n 1, constants.ALLOWED_THUMBNAIL_BG_COLORS['subtopic'][0])\n topic_1.move_skill_id_to_subtopic(None, 1, skill_id_2)\n topic_1.move_skill_id_to_subtopic(None, 1, skill_id_3)\n\n subtopic_page = (\n subtopic_page_domain.SubtopicPage.create_default_subtopic_page(\n 1, topic_id_1))\n # These explorations were chosen since they pass the validations\n # for published stories.\n self._reload_exploration('6')\n self._reload_exploration('25')\n self._reload_exploration('13')\n\n story = story_domain.Story.create_default_story(\n story_id, 'Help Jaime win the Arcade', 'Description',\n topic_id_1, 'help-jamie-win-arcade')\n\n story_node_dicts = [{\n 'exp_id': '6',\n 'title': 'What are the place values?',\n 'description': 'Jaime learns the place value of each digit '\n 'in a big number.'\n }, {\n 'exp_id': '25',\n 'title': 'Finding the value of a number',\n 'description': 'Jaime understands the value of his '\n 'arcade score.'\n }, {\n 'exp_id': '13',\n 'title': 'Comparing Numbers',\n 'description': 'Jaime learns if a number is smaller or '\n 'greater than another number.'\n }]\n\n def generate_dummy_story_nodes(\n node_id: int, exp_id: str, title: str, description: str\n ) -> None:\n \"\"\"Generates and connects sequential story nodes.\n\n Args:\n node_id: int. The node id.\n exp_id: str. The exploration id.\n title: str. The title of the story node.\n description: str. The description of the story node.\n \"\"\"\n assert self.user_id is not None\n story.add_node(\n '%s%d' % (story_domain.NODE_ID_PREFIX, node_id),\n title)\n story.update_node_description(\n '%s%d' % (story_domain.NODE_ID_PREFIX, node_id),\n description)\n story.update_node_exploration_id(\n '%s%d' % (story_domain.NODE_ID_PREFIX, node_id), exp_id)\n\n if node_id != len(story_node_dicts):\n story.update_node_destination_node_ids(\n '%s%d' % (story_domain.NODE_ID_PREFIX, node_id),\n ['%s%d' % (story_domain.NODE_ID_PREFIX, node_id + 1)])\n\n exp_services.update_exploration(\n self.user_id, exp_id, [exp_domain.ExplorationChange({\n 'cmd': exp_domain.CMD_EDIT_EXPLORATION_PROPERTY,\n 'property_name': 'category',\n 'new_value': 'Astronomy'\n })], 'Change category')\n\n for i, story_node_dict in enumerate(story_node_dicts):\n generate_dummy_story_nodes(i + 1, **story_node_dict)\n\n skill_services.save_new_skill(self.user_id, skill_1)\n skill_services.save_new_skill(self.user_id, skill_2)\n skill_services.save_new_skill(self.user_id, skill_3)\n story_services.save_new_story(self.user_id, story)\n topic_services.save_new_topic(self.user_id, topic_1)\n subtopic_page_services.save_subtopic_page(\n self.user_id, subtopic_page, 'Added subtopic',\n [topic_domain.TopicChange({\n 'cmd': topic_domain.CMD_ADD_SUBTOPIC,\n 'subtopic_id': 1,\n 'title': 'Dummy Subtopic Title',\n 'url_fragment': 'dummy-fragment'\n })]\n )\n\n # Generates translation opportunities for the Contributor Dashboard.\n exp_ids_in_story = story.story_contents.get_all_linked_exp_ids()\n opportunity_services.add_new_exploration_opportunities(\n story_id, exp_ids_in_story)\n\n topic_services.publish_story(topic_id_1, story_id, self.user_id)\n topic_services.publish_topic(topic_id_1, self.user_id)\n else:\n raise Exception('Cannot load new structures data in production.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def callback(self, error: Any, message: Any, committable: Mapping[Partition, int]) -> None:\n if message and error is None:\n self.__produced_message_offsets.update(committable)\n if error is not None:\n raise Exception(error.str())", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def create(cls, blog_post_id: str) -> BlogPostReadingTimeModel:\n \"\"\"Creates a new BlogPostReadingTimeModel entry.\n\n Args:\n blog_post_id: str. Blog Post ID of the newly-published blog post for\n which the stats model has to be created.\n\n Returns:\n BlogPostReadingTimeModel. The newly created BlogPostReadingTimeModel\n instance.\n\n Raises:\n Exception. A reading time model with the given blog post ID exists\n already.\n \"\"\"\n if cls.get_by_id(blog_post_id):\n raise Exception(\n 'A blog post reading time model with the given blog post ID'\n 'exists already.')\n entity = cls(\n id=blog_post_id,\n zero_to_one_min=0,\n one_to_two_min=0,\n two_to_three_min=0,\n three_to_four_min=0,\n four_to_five_min=0,\n five_to_six_min=0,\n six_to_seven_min=0,\n seven_to_eight_min=0,\n eight_to_nine_min=0,\n nine_to_ten_min=0,\n more_than_ten_min=0\n )\n entity.update_timestamps()\n entity.put()\n\n return entity", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def claim_number(self, user, phone_number, country, role):\n org = user.get_org()\n\n client = org.get_twilio_client()\n twilio_phones = client.api.incoming_phone_numbers.stream(phone_number=phone_number)\n channel_uuid = uuid4()\n\n # create new TwiML app\n callback_domain = org.get_brand_domain()\n\n twilio_phone = next(twilio_phones, None)\n if not twilio_phone:\n raise Exception(_(\"Only existing Twilio WhatsApp number are supported\"))\n\n phone = phonenumbers.format_number(\n phonenumbers.parse(phone_number, None), phonenumbers.PhoneNumberFormat.NATIONAL\n )\n\n number_sid = twilio_phone.sid\n\n org_config = org.config\n config = {\n Channel.CONFIG_NUMBER_SID: number_sid,\n Channel.CONFIG_ACCOUNT_SID: org_config[Org.CONFIG_TWILIO_SID],\n Channel.CONFIG_AUTH_TOKEN: org_config[Org.CONFIG_TWILIO_TOKEN],\n Channel.CONFIG_CALLBACK_DOMAIN: callback_domain,\n }\n\n role = Channel.ROLE_SEND + Channel.ROLE_RECEIVE\n\n channel = Channel.create(\n org,\n user,\n country,\n self.channel_type,\n name=phone,\n address=phone_number,\n role=role,\n config=config,\n uuid=channel_uuid,\n schemes=[URN.WHATSAPP_SCHEME],\n )\n\n return channel", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def sync_logged_in_learner_checkpoint_progress_with_current_exp_version(\n user_id: str, exploration_id: str, strict: bool = False\n) -> Optional[user_domain.ExplorationUserData]:\n \"\"\"Synchronizes the most recently reached checkpoint and the furthest\n reached checkpoint with the latest exploration.\n\n Args:\n user_id: str. The Id of the user.\n exploration_id: str. The Id of the exploration.\n strict: bool. Whether to fail noisily if no ExplorationUserDataModel\n with the given user_id exists in the datastore.\n\n Returns:\n ExplorationUserData. The domain object corresponding to the given user\n and exploration.\n\n Raises:\n Exception. No ExplorationUserDataModel found for the given user and\n exploration ids.\n \"\"\"\n exp_user_model = user_models.ExplorationUserDataModel.get(\n user_id, exploration_id)\n\n if exp_user_model is None:\n if strict:\n raise Exception(\n 'No ExplorationUserDataModel found for the given user and '\n 'exploration ids: %s, %s' % (user_id, exploration_id)\n )\n return None\n\n latest_exploration = exp_fetchers.get_exploration_by_id(exploration_id)\n most_recently_interacted_exploration = (\n exp_fetchers.get_exploration_by_id(\n exploration_id,\n strict=True,\n version=exp_user_model.most_recently_reached_checkpoint_exp_version\n ))\n furthest_reached_exploration = (\n exp_fetchers.get_exploration_by_id(\n exploration_id,\n strict=True,\n version=exp_user_model.furthest_reached_checkpoint_exp_version\n ))\n\n most_recently_reached_checkpoint_in_current_exploration = (\n get_most_distant_reached_checkpoint_in_current_exploration(\n get_checkpoints_in_order(\n latest_exploration.init_state_name,\n latest_exploration.states),\n get_checkpoints_in_order(\n most_recently_interacted_exploration.init_state_name,\n most_recently_interacted_exploration.states),\n exp_user_model.most_recently_reached_checkpoint_state_name\n )\n )\n\n furthest_reached_checkpoint_in_current_exploration = (\n get_most_distant_reached_checkpoint_in_current_exploration(\n get_checkpoints_in_order(\n latest_exploration.init_state_name,\n latest_exploration.states),\n get_checkpoints_in_order(\n furthest_reached_exploration.init_state_name,\n furthest_reached_exploration.states),\n exp_user_model.furthest_reached_checkpoint_state_name\n )\n )\n\n # If the most recently reached checkpoint doesn't exist in current\n # exploration.\n if (\n most_recently_reached_checkpoint_in_current_exploration !=\n exp_user_model.most_recently_reached_checkpoint_state_name\n ):\n exp_user_model.most_recently_reached_checkpoint_state_name = (\n most_recently_reached_checkpoint_in_current_exploration)\n exp_user_model.most_recently_reached_checkpoint_exp_version = (\n latest_exploration.version)\n exp_user_model.update_timestamps()\n exp_user_model.put()\n\n # If the furthest reached checkpoint doesn't exist in current\n # exploration.\n if (\n furthest_reached_checkpoint_in_current_exploration !=\n exp_user_model.furthest_reached_checkpoint_state_name\n ):\n exp_user_model.furthest_reached_checkpoint_state_name = (\n furthest_reached_checkpoint_in_current_exploration)\n exp_user_model.furthest_reached_checkpoint_exp_version = (\n latest_exploration.version)\n exp_user_model.update_timestamps()\n exp_user_model.put()\n\n return exp_fetchers.get_exploration_user_data(user_id, exploration_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def session_start(\n session,\n cvat_root_dir=CVAT_ROOT_DIR,\n cvat_db_dir=CVAT_DB_DIR,\n extra_dc_files=None,\n waiting_time=300,\n):\n stop = session.config.getoption(\"--stop-services\")\n start = session.config.getoption(\"--start-services\")\n rebuild = session.config.getoption(\"--rebuild\")\n cleanup = session.config.getoption(\"--cleanup\")\n dumpdb = session.config.getoption(\"--dumpdb\")\n\n if session.config.getoption(\"--collect-only\"):\n if any((stop, start, rebuild, cleanup, dumpdb)):\n raise Exception(\n \"\"\"--collect-only is not compatible with any of the other options:\n --stop-services --start-services --rebuild --cleanup --dumpdb\"\"\"\n )\n return # don't need to start the services to collect tests\n\n platform = session.config.getoption(\"--platform\")\n\n if platform == \"kube\" and any((stop, start, rebuild, cleanup, dumpdb)):\n raise Exception(\n \"\"\"--platform=kube is not compatible with any of the other options\n --stop-services --start-services --rebuild --cleanup --dumpdb\"\"\"\n )\n\n if platform == \"local\":\n local_start(\n start,\n stop,\n dumpdb,\n cleanup,\n rebuild,\n cvat_root_dir,\n cvat_db_dir,\n extra_dc_files,\n waiting_time,\n )\n\n elif platform == \"kube\":\n kube_start(cvat_db_dir)", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def ps_add_permission(\n selected_bfaccount, selected_bfdataset, selected_user, selected_role\n):\n \"\"\"\n Function to add/remove permission for a user to a selected dataset\n\n Args:\n selected_bfaccount: name of selected Pennsieve account (string)\n selected_bfdataset: name of selected Pennsieve dataset (string)\n selected_user: name (first name -- last name) of selected Pennsieve user (string)\n selected_role: desired role ('manager', 'viewer', 'editor', 'remove current permissions') (string)\n Return:\n success or error message (string)\n \"\"\"\n selected_user_id = selected_user\n user_present = False\n error = \"\"\n\n selected_dataset_id = get_dataset_id(selected_bfdataset)\n\n try:\n c = 0\n organization_id = get_user_information(get_access_token())[\"preferredOrganization\"]\n r = requests.get(f\"{PENNSIEVE_URL}/organizations/{str(organization_id)}/members\", headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n list_users = r.json()\n for i in range(len(list_users)):\n selected_user = list_users[i][\"firstName\"] + \" \" + list_users[i][\"lastName\"]\n if selected_user_id == list_users[i][\"id\"]:\n user_present = True\n break\n if user_present == False:\n error = f\"{error}Please select a valid user<br>\"\n c += 1\n except Exception as e:\n raise e\n if selected_role not in [\n \"manager\",\n \"viewer\",\n \"editor\",\n \"owner\",\n \"remove current permissions\",\n ]:\n error = f\"{error}Please select a valid role<br>\"\n c += 1\n\n if c > 0:\n abort(400, error)\n\n try:\n # check that currently logged in user is a manager or a owner of the selected dataset (only manager and owner can change dataset permission)\n r = requests.get(f\"{PENNSIEVE_URL}/user\", headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n current_user = r.json()\n first_name_current_user = current_user[\"firstName\"]\n last_name_current_user = current_user[\"lastName\"]\n\n r = requests.get(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}/collaborators/users\", headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n list_dataset_permission = r.json()\n c = 0\n for i in range(len(list_dataset_permission)):\n first_name = list_dataset_permission[i][\"firstName\"]\n last_name = list_dataset_permission[i][\"lastName\"]\n role = list_dataset_permission[i][\"role\"]\n user_id = list_dataset_permission[i][\"id\"]\n if (\n first_name == first_name_current_user\n and last_name == last_name_current_user\n ):\n if role not in [\"owner\", \"manager\"]:\n abort(403, \"You must be dataset owner or manager to change its permissions\")\n elif selected_role == \"owner\" and role != \"owner\":\n abort(403,\"You must be dataset owner to change the ownership\")\n else:\n c += 1\n # check if selected user is owner, dataset permission cannot be changed for owner\n if user_id == selected_user_id and role == \"owner\":\n abort(400, \"Owner's permission cannot be changed\")\n\n if c == 0:\n abort(403,\"You must be dataset owner or manager to change its permissions\")\n\n if selected_role == \"remove current permissions\":\n try:\n jsonfile = {\"id\": selected_user_id}\n r = requests.delete(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}/collaborators/users\", json=jsonfile, headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n except Exception as e:\n raise Exception(e) from e\n return {\"message\": f\"Permission removed for {selected_user}\"}\n elif selected_role == \"owner\":\n # check if currently logged in user is owner of selected dataset (only owner can change owner)\n # change owner\n jsonfile = {\"id\": selected_user_id}\n r = requests.put(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}/collaborators/owner\", json=jsonfile, headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n return {\"message\": \"Permission \" + \"'\" + selected_role + \"' \" + \" added for \" + selected_user}\n else:\n jsonfile = {\"id\": selected_user_id, \"role\": selected_role}\n r = requests.put(f\"{PENNSIEVE_URL}/datasets/{selected_dataset_id}/collaborators/users\", json=jsonfile, headers=create_request_headers(get_access_token()))\n r.raise_for_status()\n return {\"message\": \"Permission \" + \"'\" + selected_role + \"' \" + \" added for \" + selected_user}\n except Exception as e:\n raise e", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "async def fetch_schemas(\n self,\n wallet_type=WALLET_TYPE_INDY,\n ):\n if wallet_type in [WALLET_TYPE_INDY, WALLET_TYPE_ASKAR]:\n schemas_saved = await self.admin_GET(\"/schemas/created\")\n return schemas_saved\n elif wallet_type == WALLET_TYPE_ANONCREDS:\n schemas_saved = await self.admin_GET(\"/anoncreds/schemas\")\n return schemas_saved\n else:\n raise Exception(\"Invalid wallet_type: \" + str(wallet_type))", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def replace_block(lines, start_marker, end_marker, replacements, file):\n start_pos = find_marker(lines, start_marker, file)\n end_pos = find_marker(lines, end_marker, file)\n if end_pos <= start_pos:\n raise Exception(f\"End marker {end_marker!r} \"\n f\"occurs before start marker {start_marker!r} \"\n f\"in file {file}\")\n replacements = [line.rstrip() + '\\n' for line in replacements]\n return lines[:start_pos + 1] + replacements + lines[end_pos:]", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def run_unittest(test_mod):\n loader = unittest.TestLoader()\n tests = loader.loadTestsFromModule(test_mod)\n for error in loader.errors:\n print(error, file=sys.stderr)\n if loader.errors:\n raise Exception(\"errors while loading tests\")\n _filter_suite(tests, match_test)\n return _run_suite(tests)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def test_reuse_commit_rollback(self):\n atomic = transaction.atomic()\n with atomic:\n reporter = Reporter.objects.create(first_name=\"Tintin\")\n with self.assertRaisesMessage(Exception, \"Oops\"):\n with atomic:\n Reporter.objects.create(first_name=\"Haddock\")\n raise Exception(\"Oops, that's his last name\")\n self.assertSequenceEqual(Reporter.objects.all(), [reporter])", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def rf(module_name, module_params, request_user):\n def new_request(self, method, url, **kwargs):\n kwargs_copy = kwargs.copy()\n if 'data' in kwargs:\n if isinstance(kwargs['data'], dict):\n kwargs_copy['data'] = kwargs['data']\n elif kwargs['data'] is None:\n pass\n elif isinstance(kwargs['data'], str):\n kwargs_copy['data'] = json.loads(kwargs['data'])\n else:\n raise RuntimeError('Expected data to be dict or str, got {0}, data: {1}'.format(type(kwargs['data']), kwargs['data']))\n if 'params' in kwargs and method == 'GET':\n # query params for GET are handled a bit differently by\n # tower-cli and python requests as opposed to REST framework APIRequestFactory\n if not kwargs_copy.get('data'):\n kwargs_copy['data'] = {}\n if isinstance(kwargs['params'], dict):\n kwargs_copy['data'].update(kwargs['params'])\n elif isinstance(kwargs['params'], list):\n for k, v in kwargs['params']:\n kwargs_copy['data'][k] = v\n\n # make request\n with transaction.atomic():\n rf = _request(method.lower())\n django_response = rf(url, user=request_user, expect=None, **kwargs_copy)\n\n # requests library response object is different from the Django response, but they are the same concept\n # this converts the Django response object into a requests response object for consumption\n resp = Response()\n py_data = django_response.data\n sanitize_dict(py_data)\n resp._content = bytes(json.dumps(django_response.data), encoding='utf8')\n resp.status_code = django_response.status_code\n resp.headers = dict(django_response.headers)\n\n if request.config.getoption('verbose') > 0:\n logger.info('%s %s by %s, code:%s', method, '/api/' + url.split('/api/')[1], request_user.username, resp.status_code)\n\n resp.request = PreparedRequest()\n resp.request.prepare(method=method, url=url)\n return resp\n\n def new_open(self, method, url, **kwargs):\n r = new_request(self, method, url, **kwargs)\n m = mock.MagicMock(read=mock.MagicMock(return_value=r._content), status=r.status_code, getheader=mock.MagicMock(side_effect=r.headers.get))\n return m\n\n stdout_buffer = io.StringIO()\n # Requies specific PYTHONPATH, see docs\n # Note that a proper Ansiballz explosion of the modules will have an import path like:\n # ansible_collections.awx.awx.plugins.modules.{}\n # We should consider supporting that in the future\n resource_module = collection_import('plugins.modules.{0}'.format(module_name))\n\n if not isinstance(module_params, dict):\n raise RuntimeError('Module params must be dict, got {0}'.format(type(module_params)))\n\n # Ansible params can be passed as an invocation argument or over stdin\n # this short circuits within the AnsibleModule interface\n def mock_load_params(self):\n self.params = module_params\n\n if getattr(resource_module, 'ControllerAWXKitModule', None):\n resource_class = resource_module.ControllerAWXKitModule\n elif getattr(resource_module, 'ControllerAPIModule', None):\n resource_class = resource_module.ControllerAPIModule\n else:\n raise RuntimeError(\"The module has neither a ControllerAWXKitModule or a ControllerAPIModule\")\n\n with mock.patch.object(resource_class, '_load_params', new=mock_load_params):\n # Call the test utility (like a mock server) instead of issuing HTTP requests\n with mock.patch('ansible.module_utils.urls.Request.open', new=new_open):\n if HAS_TOWER_CLI:\n tower_cli_mgr = mock.patch('tower_cli.api.Session.request', new=new_request)\n elif HAS_AWX_KIT:\n tower_cli_mgr = mock.patch('awxkit.api.client.requests.Session.request', new=new_request)\n else:\n tower_cli_mgr = suppress()\n with tower_cli_mgr:\n try:\n # Ansible modules return data to the mothership over stdout\n with redirect_stdout(stdout_buffer):\n resource_module.main()\n except SystemExit:\n pass # A system exit indicates successful execution\n except Exception:\n # dump the stdout back to console for debugging\n print(stdout_buffer.getvalue())\n raise\n\n module_stdout = stdout_buffer.getvalue().strip()\n try:\n result = json.loads(module_stdout)\n except Exception as e:\n raise_from(Exception('Module did not write valid JSON, error: {0}, stdout:\\n{1}'.format(str(e), module_stdout)), e)\n # A module exception should never be a test expectation\n if 'exception' in result:\n if \"ModuleNotFoundError: No module named 'tower_cli'\" in result['exception']:\n pytest.skip('The tower-cli library is needed to run this test, module no longer supported.')\n raise Exception('Module encountered error:\\n{0}'.format(result['exception']))\n return result", "smellKey": "S112", "smellId": null, "repo": "ansible_awx", "language": "python"} {"function": "def download_font_file(url: str, name: str):\n with open(name, 'wb') as f:\n response = requests.get(url, headers=headers)\n if not response.ok:\n raise Exception(f\"Oh no! (response was {response.status_code})\")\n f.write(response.content)", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "@property\n def element_type(self):\n \"\"\"Retrieve the Type of elements within this Type.\n\n If accessed on a type that is not an array, complex, or vector type, an\n exception will be raised.\n \"\"\"\n result = conf.lib.clang_getElementType(self)\n if result.kind == TypeKind.INVALID:\n raise Exception('Element type not available on this type.')\n\n return result", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "def unpublish_blog_post(blog_post_id: str) -> None:\n \"\"\"Marks the given blog post as unpublished or draft.\n\n Args:\n blog_post_id: str. The ID of the given blog post.\n\n Raises:\n Exception. The given blog post does not exist.\n \"\"\"\n blog_post_rights = get_blog_post_rights(blog_post_id, strict=False)\n if blog_post_rights is None:\n raise Exception('The given blog post does not exist')\n\n blog_post = get_blog_post_by_id(blog_post_id, strict=True)\n blog_post.published_on = None\n _save_blog_post(blog_post)\n\n blog_post_summary = get_blog_post_summary_by_id(blog_post_id, strict=True)\n blog_post_summary.published_on = None\n _save_blog_post_summary(blog_post_summary)\n\n blog_post_rights.blog_post_is_published = False\n save_blog_post_rights(blog_post_rights)\n\n search_services.delete_blog_post_summary_from_search_index(\n blog_post_id)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def __init__(self, obj, rel=None, id1=None, id2=None, string='unknown', limit=None, **args):\n \"\"\"\n \"\"\"\n args['_prefetch'] = args.get('_prefetch', False)\n _column.__init__(self, string=string, **args)\n self._obj = obj\n if rel and '.' in rel:\n raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\\\n 'You used %s, which is not a valid SQL table name.')% (string,rel))\n self._rel = rel\n self._id1 = id1\n self._id2 = id2\n self._limit = limit\n self._auto_join = False", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def set(self, *args, **kwargs):\n raise Exception(\"Faked exception saving to cache\")", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(self, binaries, output_dir=None, verbosity=Verbosity.CHATTY,\n disabled_tests_policy=DisabledTestsPolicy.DISABLE):\n # Don't run anything twice.\n binaries = set(binaries)\n\n # First check that all names are present in the config.\n for binary_name in binaries:\n if binary_name not in self.tests:\n raise Exception(\"binary {0} not found in config '{1}'\".format(\n binary_name, self.config_path))\n\n # Respect the \"platform\" setting.\n for binary_name in binaries:\n if not self.__platform_supports(binary_name):\n raise Exception(\n \"binary {0} cannot be run on {1}, check the config\".format(\n binary_name, Platform.get_current()))\n\n suite_returncode = sum(\n [self.__run(binary, output_dir, verbosity, disabled_tests_policy)\n for binary in binaries])\n return suite_returncode", "smellKey": "S112", "smellId": null, "repo": "abbas-sabra-sonarsource_electron", "language": "python"} {"function": "def get_client(self) -> VstsApiClient:\n base_url = self.instance\n if SiloMode.get_current_mode() != SiloMode.REGION:\n if self.default_identity is None:\n self.default_identity = self.get_default_identity()\n self._check_domain_name(self.default_identity)\n\n if self.org_integration is None:\n raise Exception(\"self.org_integration is not defined\")\n if self.org_integration.default_auth_id is None:\n raise Exception(\"self.org_integration.default_auth_id is not defined\")\n return VstsApiClient(\n base_url=base_url,\n oauth_redirect_url=VstsIntegrationProvider.oauth_redirect_url,\n org_integration_id=self.org_integration.id,\n identity_id=self.org_integration.default_auth_id,\n )", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _fix_erratum_oval_info(self, erratum):\n \"\"\"\n manipulate oval package info to populate in the\n appropriate fields in the db tables.\n\n \"\"\"\n # pylint: disable-next=import-outside-toplevel\n import os\n\n if \"oval_info\" not in erratum:\n return\n\n for oval_file in erratum[\"oval_info\"]:\n if has_suffix(oval_file[\"filename\"], \".xml\"):\n eft = oval_file[\"file_type\"] = \"OVAL\"\n if eft not in self.file_types:\n # pylint: disable-next=broad-exception-raised,consider-using-f-string\n raise Exception(\"Unknown file type %s\" % eft)\n oval_file[\"type\"] = self.file_types[eft]\n\n # XXX: stubs incase we need to associate them to channels/packages\n oval_file[\"channel_list\"] = []\n oval_file[\"channels\"] = []\n oval_file[\"package_id\"] = None\n\n if not os.path.isfile(oval_file[\"filename\"]):\n # Don't bother to copy the package\n raise rhnFault(\n 47,\n # pylint: disable-next=consider-using-f-string\n \"Oval file %s not found on the server. \" % oval_file[\"filename\"],\n explain=0,\n )\n\n # add the oval info into the files field to get\n # populated into db\n erratum[\"files\"].append(oval_file)", "smellKey": "S112", "smellId": null, "repo": "uyuni-project_uyuni", "language": "python"} {"function": "def writeto(self, off, size, num_retries=0):\n raise Exception(\"Not writable\")", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def _run_pip_command(cmd_parts: List[str]) -> None:\n \"\"\"Run pip command with some flags and configs. If it fails try to rerun it\n with additional flags and else raise an exception.\n\n Args:\n cmd_parts: list(str). List of cmd parts to be run with pip.\n\n Raises:\n Exception. Error installing package.\n \"\"\"\n # The call to python -m is used to ensure that Python and Pip versions are\n # compatible.\n command = [sys.executable, '-m', 'pip'] + cmd_parts\n process = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n encoding='utf-8')\n stdout, stderr = process.communicate()\n if process.returncode == 0:\n print(stdout)\n elif 'can\\'t combine user with prefix' in stderr:\n print('Trying by setting --user and --prefix flags.')\n subprocess.check_call(\n command + ['--user', '--prefix=', '--system'])\n else:\n print(stderr)\n print('Refer to https://github.com/oppia/oppia/wiki/Troubleshooting')\n raise Exception('Error installing package')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def update_question_review_stats(\n suggestion: suggestion_registry.BaseSuggestion\n) -> None:\n \"\"\"Creates/updates QuestionReviewStatsModel and\n QuestionReviewerTotalContributionStatsModel model for given question\n reviewer when a question is reviewed.\n\n Args:\n suggestion: Suggestion. The suggestion domain object that is being\n reviewed.\n\n Raises:\n Exception. The final_reviewer_id of the suggestion should not be None.\n \"\"\"\n if suggestion.final_reviewer_id is None:\n raise Exception(\n 'The final_reviewer_id in the suggestion should not be None.'\n )\n suggestion_is_accepted = (\n suggestion.status == suggestion_models.STATUS_ACCEPTED\n )\n\n for topic in skill_services.get_all_topic_assignments_for_skill(\n suggestion.target_id):\n question_review_stat_model = (\n # This function is called when reviewing a question suggestion and\n # hence final_reviewer_id should not be None when the suggestion is\n # up-to-date.\n suggestion_models.QuestionReviewStatsModel.get(\n suggestion.final_reviewer_id, topic.topic_id\n ))\n\n if question_review_stat_model is None:\n # This function is called when reviewing a question suggestion and\n # hence final_reviewer_id should not be None when the suggestion is\n # up-to-date.\n accepted_questions_count = 0\n accepted_questions_with_reviewer_edits_count = 0\n if suggestion_is_accepted:\n accepted_questions_count += 1\n if suggestion_is_accepted and suggestion.edited_by_reviewer:\n accepted_questions_with_reviewer_edits_count += 1\n suggestion_models.QuestionReviewStatsModel.create(\n reviewer_user_id=suggestion.final_reviewer_id,\n topic_id=topic.topic_id,\n reviewed_questions_count=1,\n accepted_questions_count=accepted_questions_count,\n accepted_questions_with_reviewer_edits_count=(\n accepted_questions_with_reviewer_edits_count),\n first_contribution_date=suggestion.last_updated.date(),\n last_contribution_date=suggestion.last_updated.date()\n )\n continue\n\n question_review_stat = (\n _create_question_review_stats_from_model(\n question_review_stat_model))\n\n increment_question_review_stats(\n question_review_stat, suggestion.last_updated,\n suggestion_is_accepted,\n suggestion.edited_by_reviewer)\n _update_question_review_stats_models([question_review_stat])\n\n for topic in skill_services.get_all_topic_assignments_for_skill(\n suggestion.target_id):\n question_reviewer_total_stat_model = (\n suggestion_models.QuestionReviewerTotalContributionStatsModel\n .get_by_id(\n suggestion.final_reviewer_id\n ))\n\n if question_reviewer_total_stat_model is None:\n accepted_questions_count = 0\n accepted_questions_with_reviewer_edits_count = 0\n rejected_questions_count = 0\n if suggestion_is_accepted:\n accepted_questions_count += 1\n else:\n rejected_questions_count += 1\n if suggestion_is_accepted and suggestion.edited_by_reviewer:\n accepted_questions_with_reviewer_edits_count += 1\n suggestion_models.QuestionReviewerTotalContributionStatsModel.create( # pylint: disable=line-too-long\n contributor_id=suggestion.final_reviewer_id,\n topic_ids_with_question_reviews=[topic.topic_id],\n reviewed_questions_count=1,\n accepted_questions_count=accepted_questions_count,\n accepted_questions_with_reviewer_edits_count=(\n accepted_questions_with_reviewer_edits_count),\n rejected_questions_count=rejected_questions_count,\n first_contribution_date=suggestion.last_updated.date(),\n last_contribution_date=suggestion.last_updated.date()\n )\n continue\n\n question_reviewer_total_stat = (\n contribution_stats_services\n .get_question_reviewer_total_stats_from_model(\n question_reviewer_total_stat_model))\n\n if topic.topic_id not in (\n question_reviewer_total_stat\n .topic_ids_with_question_reviews):\n (\n question_reviewer_total_stat\n .topic_ids_with_question_reviews\n ).append(topic.topic_id)\n\n increment_question_reviewer_total_stats(\n question_reviewer_total_stat, suggestion.last_updated,\n suggestion_is_accepted,\n suggestion.edited_by_reviewer)\n _update_question_reviewer_total_stats_models(\n question_reviewer_total_stat)\n\n update_question_contribution_stats_at_review(suggestion)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@racetime_blueprint.route('/api/racetime/cmd', methods=['POST'])\nasync def bot_command():\n data = await request.get_json()\n\n category = data['category']\n room = data['room']\n cmd = data['cmd']\n auth_key = request.args['auth_key']\n\n access = await models.AuthorizationKeyPermissions.get_or_none(auth_key__key=auth_key, type='racetimecmd',\n subtype=category)\n if access is None:\n return abort(403)\n\n racetime_bot = racetimebot.racetime_bots.get(category)\n if not racetime_bot:\n raise Exception(\"Invalid game category\")\n\n racetime_handler = racetime_bot.handlers.get(f\"{category}/{room}\").handler\n\n fake_data = {\n 'message': {\n 'id': 'FAKE',\n 'user': {\n 'id': 'FAKE',\n 'full_name': 'API-submitted command',\n 'name': 'API-submitted command',\n 'discriminator': None,\n 'url': None,\n 'avatar': None,\n 'flair': None,\n 'twitch_name': None,\n 'twitch_display_name': None,\n 'twitch_channel': None,\n 'can_moderate': True,\n },\n 'bot': False,\n 'posted_at': datetime.datetime.utcnow().isoformat(),\n 'message': cmd,\n 'message_plain': cmd,\n 'highlight': False,\n 'is_bot': False,\n 'is_monitor': True,\n 'is_system': False,\n 'delay': 0\n },\n 'type': 'message.chat',\n 'date': datetime.datetime.utcnow().isoformat(),\n }\n\n await racetime_handler.send_message(f\"Executing command from API request: {cmd}\")\n await racetime_handler.chat_message(fake_data)\n\n return jsonify({'success': True})", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"data\": [\n (i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(int(INTERVALS_PER_DAY / 6))\n ],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"start\": 1652817000,\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_unfurl_discover_previous_period(self, mock_generate_chart, _):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?display=previous&field=title&field=event.type&field=project&field=user.display&field=timestamp&name=All+Events&project={self.project.id}&query=&sort=-timestamp&statsPeriod=24h\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature([\"organizations:discover-basic\"]):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n assert mock_generate_chart.call_args[0][0] == ChartType.SLACK_DISCOVER_PREVIOUS_PERIOD\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count()\"\n assert len(chart_data[\"stats\"][\"data\"]) == 48", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, *args, **kwargs):\n \"\"\"Specify a reaction spanning multiple regions to be added to the system.\n\n Use this for, for example, pumps and channels, or interactions between\n species living in a volume (e.g. the cytosol) and species on a\n membrane (e.g. the plasma membrane).\n\n For each species/state/parameter, you must specify what region you are\n referring to, as it could be present in multiple regions. You must\n also specify a `membrane` or a `border` (these are treated as synonyms)\n that separates the regions involved in your reaction. This is necessary\n because the default behavior is to scale the reaction rate by the\n border area, as would be expected if one of the species involved is a\n pump that is binding to a species in the volume. If this is not the\n desired behavior, pass the keyword argument `scale_by_area=False`.\n\n Pass in `membrane_flux=True` if the reaction produces a current across\n the plasma membrane that should affect the membrane potential.\n\n Unlike Reaction objects, the base units for the rates are in terms of\n molecules per square micron per ms.\n\n .. seealso::\n\n :class:`neuron.rxd.Reaction`\n \"\"\"\n\n # parse the arguments shared with rxd.Reaction\n (\n scheme,\n rate_f,\n rate_b,\n regions,\n custom_dynamics,\n mass_action,\n ) = get_scheme_rate1_rate2_regions_custom_dynamics_mass_action(args, kwargs)\n # additional keyword arguments\n membrane_flux = kwargs.get(\"membrane_flux\", False)\n membrane = kwargs.get(\"membrane\")\n border = kwargs.get(\"border\")\n scale_by_area = kwargs.get(\"scale_by_area\", True)\n\n if border is not None and membrane is not None:\n raise Exception(\"cannot specify both border and membrane; they are synoyms\")\n if border is not None:\n membrane = border\n\n # TODO: verify schemes use weakrefs\n self._scheme = scheme\n self._scale_by_area = scale_by_area\n self._original_rate_f = rate_f\n self._original_rate_b = rate_b\n\n for ar in [scheme, rate_f, rate_b]:\n try:\n if ar._voltage_dependent:\n self._voltage_dependent = True\n break\n except AttributeError:\n pass\n else:\n self._voltage_dependent = False\n\n if custom_dynamics is not None and mass_action is not None:\n raise RxDException(\"Cannot specify both custom_dynamics and mass_action.\")\n elif custom_dynamics is None and mass_action is None:\n custom_dynamics = False\n elif custom_dynamics is None and mass_action is not None:\n custom_dynamics = not mass_action\n self._custom_dynamics = custom_dynamics\n self._trans_membrane = True\n if membrane_flux not in (True, False):\n raise RxDException(\"membrane_flux must be either True or False\")\n if membrane is None:\n raise RxDException(\"MultiCompartmentReaction requires a membrane parameter\")\n if membrane_flux and species._has_3d:\n raise RxDException(\"membrane_flux not supported except in 1D\")\n self._membrane_flux = membrane_flux\n if not isinstance(scheme, rxdmath._Reaction):\n raise RxDException(\"%r not a recognized reaction scheme\" % self._scheme)\n self._dir = scheme._dir\n if not membrane._geometry.is_area():\n raise RxDException(\"must specify a membrane not a volume for the boundary\")\n self._regions = [membrane]\n rxd._register_reaction(self)\n\n # initialize self if the rest of rxd is already initialized\n if initializer.is_initialized():\n self._do_init()\n self._update_indices()", "smellKey": "S112", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "@pytest.mark.no_fail_on_log_exception\nasync def test_callback_exception_gets_logged(\n hass: HomeAssistant, caplog: pytest.LogCaptureFixture\n) -> None:\n \"\"\"Test exception raised by signal handler.\"\"\"\n\n @callback\n def bad_handler(*args):\n \"\"\"Record calls.\"\"\"\n raise Exception(\"This is a bad message callback\")\n\n # wrap in partial to test message logging.\n async_dispatcher_connect(hass, \"test\", partial(bad_handler))\n async_dispatcher_send(hass, \"test\", \"bad\")\n\n assert (\n f\"Exception in functools.partial({bad_handler}) when dispatching 'test': ('bad',)\"\n in caplog.text\n )", "smellKey": "S112", "smellId": null, "repo": "denis-troller_home-assistant-core", "language": "python"} {"function": "def get_newrelic_license() -> str:\n nr_file = os.environ.get(_NR_CONFIG_FILE_LOCATION_VAR, None)\n if nr_file is None:\n raise Exception(f\"{_NR_CONFIG_FILE_LOCATION_VAR} not defined\")\n\n config = configparser.ConfigParser()\n config.read(nr_file)\n return config[\"newrelic\"][\"license_key\"]", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def load_network(self, model):\n device = ort.get_device()\n cuda = True if device == 'GPU' else False\n try:\n providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n so = ort.SessionOptions()\n so.log_severity_level = 3\n\n self.model = ort.InferenceSession(model, providers=providers, sess_options=so)\n self.output_details = [i.name for i in self.model.get_outputs()]\n self.input_details = [i.name for i in self.model.get_inputs()]\n\n self.is_inititated = True\n except Exception as e:\n raise Exception(f\"Cannot load model {model}: {e}\")", "smellKey": "S112", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def clean(self):\n # first check that our phone number looks sane\n country = self.cleaned_data[\"country\"]\n normalized = URN.normalize_number(self.cleaned_data[\"number\"], country)\n if not URN.validate(URN.from_parts(URN.TEL_SCHEME, normalized), country):\n raise forms.ValidationError(_(\"Please enter a valid phone number\"))\n self.cleaned_data[\"number\"] = normalized\n\n try:\n resp = requests.post(\n self.cleaned_data[\"base_url\"] + \"/v1/users/login\",\n auth=(self.cleaned_data[\"username\"], self.cleaned_data[\"password\"]),\n )\n\n if resp.status_code != 200:\n raise Exception(\"Received non-200 response: %d\", resp.status_code)\n\n self.cleaned_data[\"auth_token\"] = resp.json()[\"users\"][0][\"token\"]\n\n except Exception:\n raise forms.ValidationError(\n _(\"Unable to check WhatsApp enterprise account, please check username and password\")\n )\n\n # check we can access their facebook templates\n from .type import TEMPLATE_LIST_URL\n\n if self.cleaned_data[\"facebook_template_list_domain\"] != \"graph.facebook.com\":\n response = requests.get(\n TEMPLATE_LIST_URL\n % (self.cleaned_data[\"facebook_template_list_domain\"], self.cleaned_data[\"facebook_business_id\"]),\n params=dict(access_token=self.cleaned_data[\"facebook_access_token\"]),\n )\n\n if response.status_code != 200:\n raise forms.ValidationError(\n _(\n \"Unable to access Facebook templates, please check user id and access token and make sure \"\n + \"the whatsapp_business_management permission is enabled\"\n )\n )\n return self.cleaned_data", "smellKey": "S112", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "@staticmethod\n def _convert_platform_names(rule, product_cpes):\n if not Rule._has_platforms_to_convert(rule, product_cpes):\n return\n # parse platform definition and get CPEAL platform\n for platform in rule.platforms:\n try:\n cpe_platform = Platform.from_text(platform, product_cpes)\n except Exception as e:\n msg = \"Unable to process platforms in rule '%s': %s\" % (\n rule.id_, str(e))\n raise Exception(msg)\n cpe_platform = add_platform_if_not_defined(\n cpe_platform, product_cpes)\n rule.cpe_platform_names.add(cpe_platform.id_)", "smellKey": "S112", "smellId": null, "repo": "Mab879_content", "language": "python"} {"function": "def get(self, request):\n try:\n raise Exception\n except Exception:\n return technical_500_response(request, *sys.exc_info())", "smellKey": "S112", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def resolve_match(self):\n error_entity = Entity(self.dataset.value, alias=self.dataset.value, sample=self.sample_rate)\n if len(self.entities) == 1:\n self.match = error_entity\n elif len(self.entities) == 2:\n group_entity = Entity(\"group_attributes\", alias=\"ga\")\n self.match = Join([Relationship(error_entity, \"attributes\", group_entity)])\n else:\n raise Exception(\"Unexpected number of entities\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def compute_summary_of_skill(\n skill: skill_domain.Skill\n) -> skill_domain.SkillSummary:\n \"\"\"Create a SkillSummary domain object for a given Skill domain\n object and return it.\n\n Args:\n skill: Skill. The skill object, for which the summary is to be computed.\n\n Returns:\n SkillSummary. The computed summary for the given skill.\n\n Raises:\n Exception. No data available for when the skill was last_updated.\n Exception. No data available for when the skill was created.\n \"\"\"\n skill_model_misconception_count = len(skill.misconceptions)\n skill_model_worked_examples_count = len(\n skill.skill_contents.worked_examples)\n\n if skill.created_on is None:\n raise Exception(\n 'No data available for when the skill was created.'\n )\n\n if skill.last_updated is None:\n raise Exception(\n 'No data available for when the skill was last_updated.'\n )\n skill_summary = skill_domain.SkillSummary(\n skill.id, skill.description, skill.language_code,\n skill.version, skill_model_misconception_count,\n skill_model_worked_examples_count,\n skill.created_on, skill.last_updated\n )\n\n return skill_summary", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"default,first\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n \"default,second\": {\n \"data\": [(i * INTERVAL_COUNT, [{\"count\": 0}]) for i in range(INTERVALS_PER_DAY)],\n \"end\": 1652903400,\n \"isMetricsData\": False,\n \"order\": 1,\n \"start\": 1652817000,\n },\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_top_events_url_param(self, mock_generate_chart, _):\n url = f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/?field=message&field=event.type&field=count()&name=All+Events&query=message:[first,second]&sort=-count&statsPeriod=24h&display=top5&topEvents=2\"\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n\n assert mock_generate_chart.call_args[0][0] == ChartType.SLACK_DISCOVER_TOP5_PERIOD\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count()\"\n assert len(chart_data[\"stats\"].keys()) == 2\n first_key = list(chart_data[\"stats\"].keys())[0]\n assert len(chart_data[\"stats\"][first_key][\"data\"]) == INTERVALS_PER_DAY", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _reload_collection(self, collection_id: str) -> None:\n \"\"\"Reloads the collection in dev_mode corresponding to the given\n collection id.\n\n Args:\n collection_id: str. The collection id.\n\n Raises:\n Exception. Cannot reload a collection in production.\n \"\"\"\n assert self.user_id is not None\n if constants.DEV_MODE:\n logging.info(\n '[ADMIN] %s reloaded collection %s' %\n (self.user_id, collection_id))\n collection_services.load_demo(collection_id)\n rights_manager.release_ownership_of_collection(\n user_services.get_system_user(), collection_id)\n else:\n raise Exception('Cannot reload a collection in production.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "@require_safetensors\n def test_can_use_safetensors(self):\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n for model_class in self.all_model_classes:\n model_tied = model_class(config)\n with tempfile.TemporaryDirectory() as d:\n try:\n model_tied.save_pretrained(d, safe_serialization=True)\n except Exception as e:\n raise Exception(f\"Class {model_class.__name__} cannot be saved using safetensors: {e}\")\n\n model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True)\n # Checking the state dicts are correct\n reloaded_state = model_reloaded.state_dict()\n for k, v in model_tied.state_dict().items():\n self.assertIn(k, reloaded_state, f\"Key {k} is missing from reloaded\")\n torch.testing.assert_close(\n v, reloaded_state[k], msg=lambda x: f\"{model_class.__name__}: Tensor {k}: {x}\"\n )\n # Checking there was no complain of missing weights\n self.assertEqual(infos[\"missing_keys\"], [])\n\n # Checking the tensor sharing are correct\n ptrs = defaultdict(list)\n for k, v in model_tied.state_dict().items():\n ptrs[v.data_ptr()].append(k)\n\n shared_ptrs = {k: v for k, v in ptrs.items() if len(v) > 1}\n\n for _, shared_names in shared_ptrs.items():\n reloaded_ptrs = {reloaded_state[k].data_ptr() for k in shared_names}\n self.assertEqual(\n len(reloaded_ptrs),\n 1,\n f\"The shared pointers are incorrect, found different pointers for keys {shared_names}\",\n )", "smellKey": "S112", "smellId": null, "repo": "catherinemabato_Myactivity", "language": "python"} {"function": "def get_playthrough_models_by_ids(\n playthrough_ids: List[str], strict: bool = False\n) -> Sequence[Optional[stats_models.PlaythroughModel]]:\n \"\"\"Returns a list of playthrough models matching the IDs provided.\n\n Args:\n playthrough_ids: list(str). List of IDs to get playthrough models for.\n strict: bool. Whether to fail noisily if no playthrough model exists\n with a given ID exists in the datastore.\n\n Returns:\n list(PlaythroughModel|None). The list of playthrough models\n corresponding to given ids. If a PlaythroughModel does not exist,\n the corresponding returned list element is None.\n\n Raises:\n Exception. No PlaythroughModel exists for the given playthrough_id.\n \"\"\"\n\n playthrough_models = (\n stats_models.PlaythroughModel.get_multi(playthrough_ids))\n\n if strict:\n for index, playthrough_model in enumerate(playthrough_models):\n if playthrough_model is None:\n raise Exception(\n 'No PlaythroughModel exists for the playthrough_id: %s'\n % playthrough_ids[index]\n )\n\n return playthrough_models", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def subscribe_projects(\n self,\n projects: Iterable[Project],\n monitor_type: AlertRuleMonitorTypeInt = AlertRuleMonitorTypeInt.CONTINUOUS,\n query_extra: str | None = None,\n activation_condition: AlertRuleActivationConditionType | None = None,\n activator: str | None = None,\n ) -> list[QuerySubscription]:\n \"\"\"\n Subscribes a list of projects to the alert rule instance\n :return: The list of created subscriptions\n \"\"\"\n\n logger.info(\n \"Subscribing projects to alert rule\",\n extra={\n \"alert_rule.monitor_type\": self.monitor_type,\n \"conditional_monitor_type\": monitor_type,\n \"query_extra\": query_extra,\n },\n )\n # NOTE: AlertRuleMonitorTypeInt.ACTIVATED will be conditionally subscribed given activation triggers\n # On activated subscription, additional query parameters will be added to the constructed query in Snuba\n created_subscriptions = []\n if self.monitor_type == monitor_type:\n # NOTE: QuerySubscriptions hold reference to Projects which should match the AlertRule's project reference\n created_subscriptions = bulk_create_snuba_subscriptions(\n projects,\n INCIDENTS_SNUBA_SUBSCRIPTION_TYPE,\n self.snuba_query,\n query_extra=query_extra,\n )\n if self.monitor_type == AlertRuleMonitorTypeInt.ACTIVATED:\n # NOTE: Activated Alert Rules are conditionally subscribed\n # Meaning at time of subscription, the rule must have been activated\n if not activator or activation_condition is None:\n raise Exception(\n \"Alert activations require an activation condition and activator reference\"\n )\n\n for subscription in created_subscriptions:\n AlertRuleActivations.objects.create(\n alert_rule=self,\n query_subscription=subscription,\n condition_type=activation_condition.value,\n activator=activator,\n )\n\n return created_subscriptions", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def find_first_broken_version(args):\n global tag_names\n\n print('bisecting: total of ' + str(len(tag_names)) +\n ' versions in search set')\n\n left_index = 0\n right_index = len(tag_names) - 1\n\n if left_index >= right_index:\n raise Exception('[ERROR] Not enough versions to perform search')\n\n if args.good:\n left_index = get_nearest_index(args.good, 0, left_index)\n if left_index == 0:\n args.good = None\n else:\n print('- starting at ' + tag_names[left_index])\n\n if args.bad:\n right_index = get_nearest_index(args.bad, -1, right_index)\n if right_index == len(tag_names) - 1:\n args.bad = None\n else:\n print('- ending at ' + tag_names[right_index])\n\n if args.good or args.bad:\n print('- search set narrowed down to ' + str(right_index - left_index) +\n ' versions using provided good/bad version(s)')\n\n attempt_number = 1\n\n # left should be working\n if not args.good:\n left_tag = tag_names[left_index]\n result = test_version(args, attempt_number, left_tag)\n attempt_number = attempt_number + 1\n if result is False:\n raise Exception('[ERROR] Version \"' + left_tag +\n '\" is expected to work but doesn\\'t')\n\n # right should be NOT working\n if not args.bad:\n right_tag = tag_names[right_index]\n result = test_version(args, attempt_number, right_tag)\n attempt_number = attempt_number + 1\n if result is True:\n raise Exception('[ERROR] Version \"' + right_tag +\n '\" is expected to fail but doesn\\'t')\n\n # perform search\n works_from = left_index\n fails_at = right_index\n while (fails_at - works_from) > 1:\n test_index = int(math.floor((left_index + right_index) / 2))\n test_tag = tag_names[test_index]\n\n if args.verbose:\n print('\\n[DEBUG]' + '\\nworks_from=' + tag_names[works_from] + ' (' +\n str(works_from) + ')' + '\\nfails_at=' + tag_names[fails_at] +\n ' (' + str(fails_at) + ')' + '\\nleft_index=' +\n tag_names[left_index] + ' (' + str(left_index) + ')' +\n '\\nright_index=' + tag_names[right_index] + ' (' +\n str(right_index) + ')' + '\\ntest_index=' +\n tag_names[test_index] + ' (' + str(test_index) + ')' +\n '\\ngap=' + str(fails_at - works_from))\n\n result = test_version(args, attempt_number, test_tag)\n\n if left_index == right_index:\n if result:\n return tag_names[fails_at], attempt_number\n return test_tag, attempt_number\n\n if result:\n works_from = max(test_index, works_from)\n left_index = test_index + 1\n else:\n fails_at = min(test_index, fails_at)\n right_index = test_index - 1\n\n attempt_number = attempt_number + 1\n\n return tag_names[test_index], attempt_number", "smellKey": "S112", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def statfile(prefix, fn, fnPattern=\"$(file %s/%s)\", dirPattern=\"$(dir %s/%s/)\", raiseOSError=False):\n absfn = os.path.abspath(fn)\n try:\n st = os.stat(absfn)\n sp = os.path.split(absfn)\n (pdh, branch) = is_in_collection(sp[0], sp[1])\n if pdh:\n if stat.S_ISREG(st.st_mode):\n return ArvFile(prefix, fnPattern % (pdh, branch))\n elif stat.S_ISDIR(st.st_mode):\n return ArvFile(prefix, dirPattern % (pdh, branch))\n else:\n raise Exception(\"%s is not a regular file or directory\" % absfn)\n else:\n # trim leading '/' for path prefix test later\n return UploadFile(prefix, absfn[1:])\n except OSError as e:\n if e.errno == errno.ENOENT and not raiseOSError:\n pass\n else:\n raise\n\n return prefix+fn", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def get_filter_values(applications, filter):\n if not filter:\n raise Exception(\"No filter was specified\")\n\n if filter == \"cpo\":\n column = \"cpo__name\"\n elif filter == \"quarter\":\n column = \"quarter\"\n else: # raise an error for unknown filters\n raise Exception(\"Filter '%s' does not exist for tickets\" % filter)\n\n values = applications.values_list(column, flat=True).distinct()\n return [v for v in values if v]", "smellKey": "S112", "smellId": null, "repo": "MTES-MCT_carbure", "language": "python"} {"function": "def check_execute():\n group = api.groups().create(body={\"group\": {\"name\": \"test-19070-project-3\", \"group_class\": \"project\"}}, ensure_unique_name=True).execute()\n try:\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n if len(contents[\"items\"]) != 0:\n raise Exception(\"Expected 0 items\")\n\n # Execute workflow, shouldn't copy anything.\n cmd = [\"arvados-cwl-runner\", \"--disable-git\", \"--project-uuid\", group[\"uuid\"], \"19070-copy-deps.cwl\"]\n print(\" \".join(cmd))\n wf_uuid = subprocess.check_output(cmd)\n wf_uuid = wf_uuid.decode(\"utf-8\").strip()\n\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n # container request\n # final output collection\n # container log\n # step output collection\n # container request log\n if len(contents[\"items\"]) != 5:\n raise Exception(\"Expected 5 items\")\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"portable_data_hash\"] == \"d7514270f356df848477718d58308cc4+94\":\n found = True\n if found:\n raise Exception(\"Didn't expect to find collection dependency\")\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"name\"].startswith(\"Docker image arvados jobs\"):\n found = True\n if found:\n raise Exception(\"Didn't expect to find jobs image dependency\")\n\n # Execute workflow with --copy-deps\n cmd = [\"arvados-cwl-runner\", \"--disable-git\", \"--project-uuid\", group[\"uuid\"], \"--copy-deps\", \"19070-copy-deps.cwl\"]\n print(\" \".join(cmd))\n wf_uuid = subprocess.check_output(cmd)\n wf_uuid = wf_uuid.decode(\"utf-8\").strip()\n\n contents = api.groups().contents(uuid=group[\"uuid\"]).execute()\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"portable_data_hash\"] == \"d7514270f356df848477718d58308cc4+94\":\n found = True\n if not found:\n raise Exception(\"Couldn't find collection dependency\")\n\n found = False\n for c in contents[\"items\"]:\n if c[\"kind\"] == \"arvados#collection\" and c[\"name\"].startswith(\"Docker image arvados jobs\"):\n found = True\n if not found:\n raise Exception(\"Couldn't find jobs image dependency\")\n\n finally:\n api.groups().delete(uuid=group[\"uuid\"]).execute()", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "@patch(\n \"sentry.api.bases.organization_events.OrganizationEventsV2EndpointBase.get_event_stats_data\",\n return_value={\n \"default,second\": {\n \"data\": [(1212121, [{\"count\": 15}]), (1652659200, [{\"count\": 12}])],\n \"order\": 0,\n \"isMetricsData\": False,\n \"start\": 1652572800,\n \"end\": 1652659201,\n },\n \"default,first\": {\n \"data\": [(1652572800, [{\"count\": 15}]), (1652659200, [{\"count\": 11}])],\n \"order\": 1,\n \"isMetricsData\": False,\n \"start\": 1652572800,\n \"end\": 1652659201,\n },\n },\n )\n @patch(\"sentry.charts.backend.generate_chart\", return_value=\"chart-url\")\n def test_top_daily_events_renders_bar_chart(self, mock_generate_chart, _):\n url = (\n f\"https://sentry.io/organizations/{self.organization.slug}/discover/results/\"\n \"?field=message\"\n \"&field=event.type\"\n \"&field=count()\"\n \"&name=All+Events\"\n \"&query=message:[first,second]\"\n \"&sort=-count\"\n \"&statsPeriod=24h\"\n \"&display=dailytop5\"\n \"&topEvents=2\"\n )\n link_type, args = match_link(url)\n\n if not args or not link_type:\n raise Exception(\"Missing link_type/args\")\n\n links = [\n UnfurlableUrl(url=url, args=args),\n ]\n\n with self.feature(\n [\n \"organizations:discover\",\n \"organizations:discover-basic\",\n ]\n ):\n unfurls = link_handlers[link_type].fn(self.request, self.integration, links, self.user)\n\n assert (\n unfurls[url]\n == SlackDiscoverMessageBuilder(\n title=args[\"query\"].get(\"name\"), chart_url=\"chart-url\"\n ).build()\n )\n assert len(mock_generate_chart.mock_calls) == 1\n\n assert mock_generate_chart.call_args[0][0] == ChartType.SLACK_DISCOVER_TOP5_DAILY\n chart_data = mock_generate_chart.call_args[0][1]\n assert chart_data[\"seriesName\"] == \"count()\"\n assert len(chart_data[\"stats\"].keys()) == 2\n first_key = list(chart_data[\"stats\"].keys())[0]\n # Two buckets\n assert len(chart_data[\"stats\"][first_key][\"data\"]) == 2", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def add_translatable_field(\n self,\n content_id: str,\n content_type: ContentType,\n content_format: TranslatableContentFormat,\n content_value: feconf.ContentValueType,\n interaction_id: Optional[str] = None,\n rule_type: Optional[str] = None\n ) -> None:\n \"\"\"Adds translatable field parameter to\n 'content_id_to_translatable_content' dict.\n\n Args:\n content_id: str. The id of the corresponding translatable content\n value.\n content_type: TranslatableContentFormat. The type of the\n corresponding content value.\n content_format: TranslatableContentFormat. The format of the\n content.\n content_value: ContentValueType. The content value which can be\n translated.\n interaction_id: str|None. The ID of the interaction in which the\n content is used.\n rule_type: str|None. The rule type of the answer group in which the\n content is used.\n\n Raises:\n Exception. The content_id_to_translatable_content dict already\n contains the content_id.\n \"\"\"\n if content_id in self.content_id_to_translatable_content:\n raise Exception(\n 'Content_id %s already exists in the '\n 'TranslatableContentsCollection.' % content_id)\n\n self.content_id_to_translatable_content[content_id] = (\n TranslatableContent(\n content_id,\n content_type,\n content_format,\n content_value,\n interaction_id,\n rule_type)\n )", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def testSubTestMixed(self):\n with self.subTest('success', a=1):\n pass\n with self.subTest('skip', b=2):\n self.skipTest('skip')\n with self.subTest('fail', c=3):\n self.fail('fail')\n with self.subTest('error', d=4):\n raise Exception('error')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def upgrade_pip(python_executable: str) -> None:\n \"\"\"Install pip>=21.3.1. Required for editable installs with PEP 660.\"\"\"\n if (\n sys.version_info >= (3, 11)\n or (3, 10, 3) <= sys.version_info < (3, 11)\n or (3, 9, 11) <= sys.version_info < (3, 10)\n or (3, 8, 13) <= sys.version_info < (3, 9)\n ):\n # Skip for more recent Python releases which come with pip>=21.3.1\n # out of the box - for performance reasons.\n return\n\n install_cmd = [python_executable, \"-m\", \"pip\", \"install\", \"pip>=21.3.1\"]\n try:\n with filelock.FileLock(pip_lock, timeout=pip_timeout):\n proc = subprocess.run(install_cmd, capture_output=True, env=os.environ)\n except filelock.Timeout as err:\n raise Exception(f\"Failed to acquire {pip_lock}\") from err\n if proc.returncode != 0:\n raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))", "smellKey": "S112", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@api.model\n def set_multi(self, name, model, values):\n \"\"\" Assign the property field `name` for the records of model `model`\n with `values` (dictionary mapping record ids to their value).\n \"\"\"\n def clean(value):\n return value.id if isinstance(value, models.BaseModel) else value\n\n if not values:\n return\n\n domain = self._get_domain(name, model)\n if domain is None:\n raise Exception()\n\n # retrieve the default value for the field\n default_value = clean(self.get(name, model))\n\n # retrieve the properties corresponding to the given record ids\n self._cr.execute(\"SELECT id FROM ir_model_fields WHERE name=%s AND model=%s\", (name, model))\n field_id = self._cr.fetchone()[0]\n company_id = self.env.context.get('force_company') or self.env['res.company']._company_default_get(model, field_id).id\n refs = {('%s,%s' % (model, id)): id for id in values}\n props = self.search([\n ('fields_id', '=', field_id),\n ('company_id', '=', company_id),\n ('res_id', 'in', list(refs)),\n ])\n\n # modify existing properties\n for prop in props:\n id = refs.pop(prop.res_id)\n value = clean(values[id])\n if value == default_value:\n prop.unlink()\n elif value != clean(prop.get_by_record(prop)):\n prop.write({'value': value})\n\n # create new properties for records that do not have one yet\n for ref, id in refs.iteritems():\n value = clean(values[id])\n if value != default_value:\n self.create({\n 'fields_id': field_id,\n 'company_id': company_id,\n 'res_id': ref,\n 'name': name,\n 'value': value,\n 'type': self.env[model]._fields[name].type,\n })", "smellKey": "S112", "smellId": null, "repo": "bunheng168_odoo", "language": "python"} {"function": "def call_func_failure():\n raise Exception('spam!')", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def rebase_installed_docs(self):\n if not os.path.isdir(self.output_dir):\n raise Exception(\"Tried to rebase documentation before generating it.\")\n html_dir = os.path.join(self.virtual_root + self.prefix, 'share', 'gtk-doc', 'html', self.module_name)\n if not os.path.isdir(html_dir):\n return\n args = ['gtkdoc-rebase',\n '--relative',\n '--html-dir=%s' % html_dir]\n args.extend(['--other-dir=%s' % extra_dir for extra_dir in self.cross_reference_deps])\n if self.virtual_root:\n args.extend(['--dest-dir=%s' % self.virtual_root])\n self._run_command(args, cwd=self.output_dir)", "smellKey": "S112", "smellId": null, "repo": "tsdgeos_poppler_mirror", "language": "python"} {"function": "async def create_schema_and_cred_def(\n self,\n schema_name: str,\n schema_attrs: list,\n version: str = None,\n ):\n if not self.public_did:\n raise Exception(\"Can't create a schema/cred def without a public DID :-(\")\n if self.cred_type in [CRED_FORMAT_INDY, CRED_FORMAT_VC_DI]:\n # need to redister schema and cred def on the ledger\n self.cred_def_id = await self.agent.create_schema_and_cred_def(\n schema_name,\n schema_attrs,\n self.revocation,\n version=version,\n wallet_type=self.agent.wallet_type,\n )\n return self.cred_def_id\n elif self.cred_type == CRED_FORMAT_JSON_LD:\n # TODO no schema/cred def required\n pass\n return None\n else:\n raise Exception(\"Invalid credential type:\" + self.cred_type)", "smellKey": "S112", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@contextmanager\n def swap_to_region_by_name(self, region_name: str):\n \"\"\"Swap to the specified region when entering region mode.\"\"\"\n\n region = self.get_by_name(region_name)\n if region is None:\n raise Exception(\"specified swap region not found\")\n with override_settings(SENTRY_REGION=region.name):\n yield", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def final(self, *, force=False):\n try:\n return self._final\n except AttributeError:\n if not self._closed:\n if not force:\n raise Exception('no final results available yet')\n else:\n return CapturedResults.Proxy(self)\n self._final = CapturedResults(\n self._unpack_stdout(),\n self._unpack_stderr(),\n self._unpack_exc(),\n )\n return self._final", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def create_progression_spoiler(seed):\n if not seed.data['spoiler']['meta'].get('spoilers') in ['on', 'generate']:\n return None\n\n spoiler = seed.data['spoiler']\n\n if spoiler['meta'].get('shuffle', 'none') != 'none':\n raise Exception(\"Entrance randomizer is not yet supported.\")\n\n progression_spoiler = OrderedDict()\n\n for region in REGIONLIST:\n progression_for_region = [loc for loc, item in mw_filter(\n spoiler[region]).items() if item in PROGRESSION_ITEMS]\n if progression_for_region:\n progression_spoiler[region] = progression_for_region\n\n progression_spoiler['meta'] = spoiler['meta']\n progression_spoiler['meta']['hash'] = seed.hash\n progression_spoiler['meta']['permalink'] = seed.url\n\n return progression_spoiler", "smellKey": "S112", "smellId": null, "repo": "tcprescott_sahasrahbot", "language": "python"} {"function": "def enqueue_contributor_ranking_notification_email_task(\n contributor_user_id: str, contribution_type: str,\n contribution_sub_type: str, language_code: str, rank_name: str,\n) -> None:\n \"\"\"Adds a 'send feedback email' (instant) task into the task queue.\n\n Args:\n contributor_user_id: str. The ID of the contributor.\n contribution_type: str. The type of the contribution i.e.\n translation or question.\n contribution_sub_type: str. The sub type of the contribution\n i.e. submissions/acceptances/reviews/edits.\n language_code: str. The language code of the suggestion.\n rank_name: str. The name of the rank that the contributor achieved.\n\n Raises:\n Exception. The contribution type must be offered on the Contributor\n Dashboard.\n Exception. The contribution subtype must be offered on the Contributor\n Dashboard.\n \"\"\"\n # contributor_user_id is alrerady validated in the controller layer.\n # TODO(#16062): Rank name should be valid to send notification emails.\n if language_code not in [language['id'] for language in (\n constants.SUPPORTED_AUDIO_LANGUAGES)]:\n raise Exception(\n 'Not supported language code: %s' % language_code)\n if contribution_type not in [\n feconf.CONTRIBUTION_TYPE_TRANSLATION,\n feconf.CONTRIBUTION_TYPE_QUESTION\n ]:\n raise Exception(\n 'Invalid contribution type: %s' % contribution_type)\n if contribution_sub_type not in [\n feconf.CONTRIBUTION_SUBTYPE_ACCEPTANCE,\n feconf.CONTRIBUTION_SUBTYPE_REVIEW,\n feconf.CONTRIBUTION_SUBTYPE_EDIT,\n ]:\n raise Exception(\n 'Invalid contribution subtype: %s' % contribution_sub_type)\n\n payload = {\n 'contributor_user_id': contributor_user_id,\n 'contribution_type': contribution_type,\n 'contribution_sub_type': contribution_sub_type,\n 'language_code': language_code,\n 'rank_name': rank_name,\n }\n\n taskqueue_services.enqueue_task(\n feconf.TASK_URL_CONTRIBUTOR_DASHBOARD_ACHIEVEMENT_NOTIFICATION_EMAILS,\n payload, 0)", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def set_duplicate(new_finding, existing_finding):\n deduplicationLogger.debug(f\"new_finding.status(): {new_finding.id} {new_finding.status()}\")\n deduplicationLogger.debug(f\"existing_finding.status(): {existing_finding.id} {existing_finding.status()}\")\n if existing_finding.duplicate:\n deduplicationLogger.debug(\"existing finding: %s:%s:duplicate=%s;duplicate_finding=%s\", existing_finding.id, existing_finding.title, existing_finding.duplicate, existing_finding.duplicate_finding.id if existing_finding.duplicate_finding else \"None\")\n msg = \"Existing finding is a duplicate\"\n raise Exception(msg)\n if existing_finding.id == new_finding.id:\n msg = \"Can not add duplicate to itself\"\n raise Exception(msg)\n if is_duplicate_reopen(new_finding, existing_finding):\n msg = \"Found a regression. Ignore this so that a new duplicate chain can be made\"\n raise Exception(msg)\n if new_finding.duplicate and finding_mitigated(existing_finding):\n msg = \"Skip this finding as we do not want to attach a new duplicate to a mitigated finding\"\n raise Exception(msg)\n\n deduplicationLogger.debug(\"Setting new finding \" + str(new_finding.id) + \" as a duplicate of existing finding \" + str(existing_finding.id))\n new_finding.duplicate = True\n new_finding.active = False\n new_finding.verified = False\n new_finding.duplicate_finding = existing_finding\n\n # Make sure transitive duplication is flattened\n # if A -> B and B is made a duplicate of C here, aferwards:\n # A -> C and B -> C should be true\n for find in new_finding.original_finding.all().order_by(\"-id\"):\n new_finding.original_finding.remove(find)\n set_duplicate(find, existing_finding)\n existing_finding.found_by.add(new_finding.test.test_type)\n logger.debug(\"saving new finding: %d\", new_finding.id)\n super(Finding, new_finding).save()\n logger.debug(\"saving existing finding: %d\", existing_finding.id)\n super(Finding, existing_finding).save()", "smellKey": "S112", "smellId": null, "repo": "SonarQude-Saas_django-DefectDojo", "language": "python"} {"function": "def __init__(self, parent_inode, inodes, enable_write, filters):\n \"\"\"parent_inode is the integer inode number\"\"\"\n\n super(Directory, self).__init__()\n\n self.inode = None\n if not isinstance(parent_inode, int):\n raise Exception(\"parent_inode should be an int\")\n self.parent_inode = parent_inode\n self.inodes = inodes\n self._entries = {}\n self._mtime = time.time()\n self._enable_write = enable_write\n self._filters = filters or []", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def test_nested_else_mixed2(self):\n hit_else = False\n hit_finally = False\n hit_except = False\n hit_inner_except = False\n hit_inner_else = False\n\n try:\n try:\n pass\n except:\n hit_inner_except = True\n else:\n hit_inner_else = True\n\n raise Exception('outer exception')\n except* BaseException:\n hit_except = True\n else:\n hit_else = True\n finally:\n hit_finally = True\n\n self.assertFalse(hit_inner_except)\n self.assertTrue(hit_inner_else)\n self.assertFalse(hit_else)\n self.assertTrue(hit_finally)\n self.assertTrue(hit_except)", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def get_local_region() -> Region:\n \"\"\"Get the region in which this server instance is running.\n\n Return the monolith region if this server instance is in monolith mode.\n Otherwise, it must be a region silo; raise RegionContextError otherwise.\n \"\"\"\n\n if SiloMode.get_current_mode() == SiloMode.MONOLITH:\n return get_region_by_name(settings.SENTRY_MONOLITH_REGION)\n\n if SiloMode.get_current_mode() != SiloMode.REGION:\n raise RegionContextError(\"Not a region silo\")\n\n # In our threaded acceptance tests, we need to override the region of the current\n # context when passing through test rpc calls, but we can't rely on settings because\n # django settings are not thread safe :'(\n # We use this thread local instead which is managed by the SiloMode context managers\n single_process_region = SingleProcessSiloModeState.get_region()\n if single_process_region is not None:\n return single_process_region\n\n if not settings.SENTRY_REGION:\n if in_test_environment():\n return get_region_by_name(settings.SENTRY_MONOLITH_REGION)\n else:\n raise Exception(\"SENTRY_REGION must be set when server is in REGION silo mode\")\n return get_region_by_name(settings.SENTRY_REGION)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@staticmethod\n def set_library_path(path):\n \"\"\"Set the path in which to search for libclang\"\"\"\n if Config.loaded:\n raise Exception(\"library path must be set before before using \" \\\n \"any other functionalities in libclang.\")\n\n Config.library_path = fspath(path)", "smellKey": "S112", "smellId": null, "repo": "AbbasNS_cocos-engine", "language": "python"} {"function": "@auth_bp.route(\"/proton/callback\")\ndef proton_callback():\n if SESSION_STATE_KEY not in session or SESSION_STATE_KEY not in session:\n flash(\"Invalid state, please retry\", \"error\")\n return redirect(url_for(\"auth.login\"))\n if PROTON_CLIENT_ID is None or PROTON_CLIENT_SECRET is None:\n return redirect(url_for(\"auth.login\"))\n\n # user clicks on cancel\n if \"error\" in request.args:\n flash(\"Please use another sign in method then\", \"warning\")\n return redirect(\"/\")\n\n proton = OAuth2Session(\n PROTON_CLIENT_ID,\n state=session[SESSION_STATE_KEY],\n redirect_uri=_redirect_uri,\n )\n\n def check_status_code(response: requests.Response) -> requests.Response:\n if response.status_code != 200:\n raise Exception(\n f\"Bad Proton API response [status={response.status_code}]: {response.json()}\"\n )\n return response\n\n proton.register_compliance_hook(\"access_token_response\", check_status_code)\n\n headers = None\n if PROTON_EXTRA_HEADER_NAME and PROTON_EXTRA_HEADER_VALUE:\n headers = {PROTON_EXTRA_HEADER_NAME: PROTON_EXTRA_HEADER_VALUE}\n\n try:\n token = proton.fetch_token(\n _token_url,\n client_secret=PROTON_CLIENT_SECRET,\n authorization_response=request.url,\n verify=PROTON_VALIDATE_CERTS,\n method=\"GET\",\n include_client_id=True,\n headers=headers,\n )\n except Exception as e:\n LOG.warning(f\"Error fetching Proton token: {e}\")\n flash(\"There was an error in the login process\", \"error\")\n return redirect(url_for(\"auth.login\"))\n\n credentials = convert_access_token(token[\"access_token\"])\n action = get_action_from_state()\n\n proton_client = HttpProtonClient(\n PROTON_BASE_URL, credentials, get_remote_address(), verify=PROTON_VALIDATE_CERTS\n )\n handler = ProtonCallbackHandler(proton_client)\n proton_partner = get_proton_partner()\n\n next_url = session.get(\"oauth_next\")\n if action == Action.Login:\n res = handler.handle_login(proton_partner)\n elif action == Action.Link:\n res = handler.handle_link(current_user, proton_partner)\n else:\n raise Exception(f\"Unknown Action: {action.name}\")\n\n if res.flash_message is not None:\n flash(res.flash_message, res.flash_category)\n\n oauth_scheme = session.get(\"oauth_scheme\")\n if session.get(\"oauth_mode\", \"session\") == \"apikey\":\n apikey = get_api_key_for_user(res.user)\n scheme = oauth_scheme or DEFAULT_SCHEME\n return redirect(f\"{scheme}:///login?apikey={apikey}\")\n\n if res.redirect_to_login:\n return redirect(url_for(\"auth.login\"))\n\n if next_url and next_url[0] == \"/\" and oauth_scheme:\n next_url = f\"{oauth_scheme}://{next_url}\"\n\n redirect_url = next_url or res.redirect\n return after_login(res.user, redirect_url, login_from_proton=True)", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def mock_set_constants_to_default(self) -> None:\n \"\"\"Change constants file in the test could lead to other\n tests fail. Mock set_constants_to_default method in your test\n will suppress this exception.\n \"\"\"\n raise Exception('Please mock this method in the test.')", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _get_seedlist(self):\n \"\"\"Poll SRV records for a seedlist.\n\n Returns a list of ServerDescriptions.\n \"\"\"\n try:\n seedlist, ttl = _SrvResolver(self._fqdn).get_hosts_and_min_ttl()\n if len(seedlist) == 0:\n # As per the spec: this should be treated as a failure.\n raise Exception\n except Exception:\n # As per the spec, upon encountering an error:\n # - An error must not be raised\n # - SRV records must be rescanned every heartbeatFrequencyMS\n # - Topology must be left unchanged\n self.request_check()\n return None\n else:\n self._executor.update_interval(\n max(ttl, common.MIN_SRV_RESCAN_INTERVAL))\n return seedlist", "smellKey": "S112", "smellId": null, "repo": "python-ops-org_python-ops", "language": "python"} {"function": "def get_upstream_git_repository_remote_name() -> str:\n \"\"\"Get the remote name of the upstream repository.\n\n Returns:\n Optional[bytes]. The remote name of the upstream repository.\n\n Raises:\n ValueError. Subprocess failed to start.\n Exception. Upstream not set.\n \"\"\"\n remote_name = ''\n remote_num = 0\n remotes = get_git_remotes()\n for remote in remotes:\n remote_url = get_remote_url(remote)\n if remote_url.endswith('oppia/oppia.git\\n'):\n remote_num += 1\n remote_name = remote\n\n if not remote_num:\n raise Exception(\n 'Error: Please set the git \\'upstream\\' repository.\\n'\n 'To do that follow these steps:\\n'\n '1. Run the command \\'git remote -v\\'\\n'\n '2a. If \\'upstream\\' is listed in the command output, then run the '\n 'command \\'git remote set-url upstream '\n 'https://github.com/oppia/oppia.git\\'\\n'\n '2b. If \\'upstream\\' is not listed in the command output, then run '\n 'the command \\'git remote add upstream '\n 'https://github.com/oppia/oppia.git\\'\\n'\n )\n\n if remote_num > 1:\n raise Exception(\n 'Error: Please keep only one remote branch for oppia:develop.\\n'\n 'To do that follow these steps:\\n'\n '1. Run the command \\'git remote -v\\'\\n'\n '2. This command will list the remote references. There will be '\n 'multiple remotes with the main oppia github reopsitory url, but we'\n ' want to make sure that there is only one main \\'upstream\\' remote'\n ' that uses the url https://github.com/oppia/oppia.git. Please use '\n 'the command, \\'git remote remove <remote_name>\\' on all remotes '\n 'that have the url https://github.com/oppia/oppia.git except for '\n 'the main \\'upstream\\' remote.\\n'\n )\n\n return remote_name", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def _iter_filenames(filenames, process, relroot):\n if process is None:\n yield from fsutil.process_filenames(filenames, relroot=relroot)\n return\n\n onempty = Exception('no filenames provided')\n items = process(filenames, relroot=relroot)\n items, peeked = iterutil.peek_and_iter(items)\n if not items:\n raise onempty\n if isinstance(peeked, str):\n if relroot and relroot is not fsutil.USE_CWD:\n relroot = os.path.abspath(relroot)\n check = (lambda: True)\n for filename, ismany in iterutil.iter_many(items, onempty):\n relfile = fsutil.format_filename(filename, relroot, fixroot=False)\n yield filename, relfile, check, ismany\n elif len(peeked) == 4:\n yield from items\n else:\n raise NotImplementedError", "smellKey": "S112", "smellId": null, "repo": "codacy-open-source-projects-scans_cpython", "language": "python"} {"function": "def add_dkim_signature(msg: Message, email_domain: str):\n if config.RSPAMD_SIGN_DKIM:\n LOG.d(\"DKIM signature will be added by rspamd\")\n msg[headers.SL_WANT_SIGNING] = \"yes\"\n return\n\n for dkim_headers in headers.DKIM_HEADERS:\n try:\n add_dkim_signature_with_header(msg, email_domain, dkim_headers)\n return\n except dkim.DKIMException:\n LOG.w(\"DKIM fail with %s\", dkim_headers, exc_info=True)\n # try with another headers\n continue\n\n # To investigate why some emails can't be DKIM signed. todo: remove\n if config.TEMP_DIR:\n file_name = str(uuid.uuid4()) + \".eml\"\n with open(os.path.join(config.TEMP_DIR, file_name), \"wb\") as f:\n f.write(msg.as_bytes())\n\n LOG.w(\"email saved to %s\", file_name)\n\n raise Exception(\"Cannot create DKIM signature\")", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def get_interaction_id_for_question(question_id: str) -> Optional[str]:\n \"\"\"Returns the interaction id for the given question.\n\n Args:\n question_id: str. ID of the question.\n\n Returns:\n str. The ID of the interaction of the question.\n\n Raises:\n Exception. The question does not exists of the ID question_id.\n \"\"\"\n question = get_question_by_id(question_id, strict=False)\n if question is None:\n raise Exception('No questions exists with the given question id.')\n return question.question_state_data.interaction.id", "smellKey": "S112", "smellId": null, "repo": "gutoslv_oppia", "language": "python"} {"function": "def handle_unsubscribe_from_request(\n self, user: User, unsub_request: str\n ) -> Optional[UnsubscribeData]:\n unsub_data = UnsubscribeEncoder.decode_subject(unsub_request)\n if not unsub_data:\n LOG.w(\"Wrong request %s\", unsub_request)\n return None\n if unsub_data.action == UnsubscribeAction.DisableAlias:\n response_code = self._disable_alias(unsub_data.data, user)\n elif unsub_data.action == UnsubscribeAction.DisableContact:\n response_code = self._disable_contact(unsub_data.data, user)\n elif unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter:\n response_code = self._unsubscribe_user_from_newsletter(\n unsub_data.data, user\n )\n elif unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto:\n response_code = self._unsubscribe_original_behaviour(unsub_data.data, user)\n else:\n raise Exception(f\"Unknown unsubscribe action {unsub_data.action}\")\n if response_code == status.E202:\n return unsub_data\n return None", "smellKey": "S112", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def get_rootDesc():\n global _rootDesc\n if not _rootDesc:\n try:\n _rootDesc = arvados.api('v1')._rootDesc\n except ValueError:\n raise Exception(\"Test requires an running API server to fetch discovery document\")\n return _rootDesc", "smellKey": "S112", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def run(self, test, **kwargs):\n if type(test) == list and 'name' not in kwargs:\n import pipes\n kwargs['name'] = ' '.join(map(pipes.quote, test))\n\n if Options.options.test_filter and 'name' in kwargs:\n import re\n found = False\n for scope in self.tst.stack:\n if re.search(Options.options.test_filter, scope.name):\n found = True\n break\n\n if (not found and\n not re.search(Options.options.test_filter, self.name) and\n not re.search(Options.options.test_filter, kwargs['name'])):\n return True\n\n if callable(test):\n output = self._run_callable(test, **kwargs)\n elif type(test) == list:\n output = self._run_command(test, **kwargs)\n else:\n raise Exception(\"Unknown test type\")\n\n if not output:\n self.tst.log_bad('FAILED', kwargs['name'])\n\n return self.tst.test_result(output)", "smellKey": "S112", "smellId": null, "repo": "uajithkumar_audacity", "language": "python"} {"function": "def bf_submit_dataset(accountname, bfdataset, pathdataset):\n \"\"\"\n Associated with 'Submit dataset' button in 'Submit new dataset' section\n Uploads the specified folder to the specified dataset on Pennsieve account\n\n Input:\n accountname: account in which the dataset needs to be created (string)\n bfdataset: name of the dataset on Pennsieve (string)\n pathdataset: path of dataset on local machine (string)\n Action:\n Uploads dataset on Pennsieve account\n \"\"\"\n global submitdataprogress\n global submitdatastatus\n global total_file_size\n global uploaded_file_size\n global submitprintstatus\n global start_time_bf_upload\n global bf\n global myds\n global start_submit\n global initial_bfdataset_size_submit\n global completed_files\n global did_upload\n global did_fail\n global upload_folder_count\n global namespace_logger\n global files_uploaded\n global total_files_to_upload\n global total_bytes_uploaded\n\n files_uploaded = 0\n total_files_to_upload = 0\n submitdataprogress = \" \"\n submitdatastatus = \" \"\n uploaded_file_size = 0\n submitprintstatus = \" \"\n start_time_bf_upload = 0\n initial_bfdataset_size_submit = 0\n start_submit = 0\n did_upload = False\n did_fail = False\n upload_folder_count = 0\n bytes_uploaded_per_file = {}\n total_bytes_uploaded = {\"value\": 0}\n\n def monitor_subscriber_progress(events_dict):\n \"\"\"\n Monitors the progress of a subscriber and unsubscribes once the upload finishes. \n \"\"\"\n\n total_dataset_files = total_files_to_upload\n global files_uploaded\n global total_bytes_uploaded\n\n if events_dict[\"type\"] == 1: # upload status: file_id, total, current, worker_id\n file_id = events_dict[\"upload_status\"].file_id\n total_bytes_to_upload = events_dict[\"upload_status\"].total\n current_bytes_uploaded = events_dict[\"upload_status\"].current\n\n\n \n # get the previous bytes uploaded for the given file id - use 0 if no bytes have been uploaded for this file id yet\n previous_bytes_uploaded = bytes_uploaded_per_file.get(file_id, 0)\n\n # update the file id's current total bytes uploaded value \n bytes_uploaded_per_file[file_id] = current_bytes_uploaded\n\n # calculate the additional amount of bytes that have just been uploaded for the given file id\n total_bytes_uploaded[\"value\"] += current_bytes_uploaded - previous_bytes_uploaded\n\n\n\n # check if the given file has finished uploading\n if current_bytes_uploaded == total_bytes_to_upload and file_id != \"\":\n files_uploaded += 1\n\n\n # check if the upload has finished\n if files_uploaded == total_dataset_files:\n # unsubscribe from the agent's upload messages since the upload has finished\n ps.unsubscribe(10)\n\n\n # check if the local dataset folder exists\n if not isdir(pathdataset):\n submitdatastatus = \"Done\"\n error_message = (\n f\"{error_message} Please select a valid local dataset folder<br>\"\n )\n did_fail = True\n did_upload = False\n abort(400, error_message)\n\n total_file_size = 1\n \n\n # initialize the Pennsieve client \n try:\n ps = Pennsieve(profile_name=accountname)\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n error_message = \"Please select a valid Pennsieve account\"\n abort(400, e)\n\n\n # select the user\n try:\n ps.user.switch(accountname)\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n error_message = \"Please select a valid Pennsieve account\"\n abort(400, error_message)\n\n selected_dataset_id = get_dataset_id(bfdataset)\n\n # reauthenticate the user\n try:\n ps.user.reauthenticate()\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n error_message = \"Could not reauthenticate this user\"\n abort(401, error_message)\n\n # select the dataset \n try:\n ps.use_dataset(selected_dataset_id)\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n error_message = \"Please select a valid Pennsieve dataset\"\n\n # get the dataset size before starting the upload\n total_file_size, invalid_dataset_messages, total_files_to_upload = get_dataset_size(pathdataset)\n\n namespace_logger.info(f\"Size of the dataset: {total_file_size} bytes\")\n\n if invalid_dataset_messages != \"\":\n submitdatastatus = \"Done\"\n invalid_dataset_messages = (\n invalid_dataset_messages\n + \"<br>Please remove invalid files/folders from your dataset before uploading. If you have hidden files present please remove them before upload. You can find more details <a target='_blank' rel='noopener noreferrer' href='https://docs.sodaforsparc.io/docs/common-errors/issues-regarding-hidden-files-or-folders'>here </a> on how to fix this issue.\"\n )\n did_fail = True\n did_upload = False\n abort(400, invalid_dataset_messages)\n\n if not has_edit_permissions(get_access_token(), selected_dataset_id):\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n abort(403, \"You don't have permissions for uploading to this Pennsieve dataset\")\n\n\n # create the manifest file for the dataset\n try:\n manifest_data = ps.manifest.create(pathdataset, os.path.basename(pathdataset))\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n did_upload = False\n error_message = \"Could not create manifest file for this dataset\"\n abort(500, e)\n \n\n # upload the dataset\n try:\n submitprintstatus = \"Uploading\"\n start_time_bf_upload = time.time()\n start_submit = 1\n manifest_id = manifest_data.manifest_id\n try: \n ps.manifest.upload(manifest_id)\n ps.subscribe(10, False, monitor_subscriber_progress)\n except Exception as e:\n namespace_logger.error(\"Error uploading dataset files\")\n namespace_logger.error(e)\n raise Exception(\"The Pennsieve Agent has encountered an issue while uploading. Please retry the upload. If this issue persists please follow this <a target='_blank' rel='noopener noreferrer' href='https://docs.sodaforsparc.io/docs/how-to/how-to-reinstall-the-pennsieve-agent'> guide</a> on performing a full reinstallation of the Pennsieve Agent to fix the problem.\")\n\n submitdatastatus = \"Done\"\n except Exception as e:\n submitdatastatus = \"Done\"\n did_fail = True\n raise e\n\n return \"Done\"", "smellKey": "S112", "smellId": null, "repo": "fairdataihub_SODA-for-SPARC", "language": "python"} {"function": "def _new_conn(self):\n # Performs the NTLM handshake that secures the connection. The socket\n # must be kept open while requests are performed.\n self.num_connections += 1\n log.debug(\n \"Starting NTLM HTTPS connection no. %d: https://%s%s\",\n self.num_connections,\n self.host,\n self.authurl,\n )\n\n headers = {\"Connection\": \"Keep-Alive\"}\n req_header = \"Authorization\"\n resp_header = \"www-authenticate\"\n\n conn = HTTPSConnection(host=self.host, port=self.port)\n\n # Send negotiation message\n headers[req_header] = \"NTLM %s\" % ntlm.create_NTLM_NEGOTIATE_MESSAGE(\n self.rawuser\n )\n log.debug(\"Request headers: %s\", headers)\n conn.request(\"GET\", self.authurl, None, headers)\n res = conn.getresponse()\n reshdr = dict(res.getheaders())\n log.debug(\"Response status: %s %s\", res.status, res.reason)\n log.debug(\"Response headers: %s\", reshdr)\n log.debug(\"Response data: %s [...]\", res.read(100))\n\n # Remove the reference to the socket, so that it can not be closed by\n # the response object (we want to keep the socket open)\n res.fp = None\n\n # Server should respond with a challenge message\n auth_header_values = reshdr[resp_header].split(\", \")\n auth_header_value = None\n for s in auth_header_values:\n if s[:5] == \"NTLM \":\n auth_header_value = s[5:]\n if auth_header_value is None:\n raise Exception(\n \"Unexpected %s response header: %s\" % (resp_header, reshdr[resp_header])\n )\n\n # Send authentication message\n ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(\n auth_header_value\n )\n auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(\n ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags\n )\n headers[req_header] = \"NTLM %s\" % auth_msg\n log.debug(\"Request headers: %s\", headers)\n conn.request(\"GET\", self.authurl, None, headers)\n res = conn.getresponse()\n log.debug(\"Response status: %s %s\", res.status, res.reason)\n log.debug(\"Response headers: %s\", dict(res.getheaders()))\n log.debug(\"Response data: %s [...]\", res.read()[:100])\n if res.status != 200:\n if res.status == 401:\n raise Exception(\"Server rejected request: wrong username or password\")\n raise Exception(\"Wrong server response: %s %s\" % (res.status, res.reason))\n\n res.fp = None\n log.debug(\"Connection established\")\n return conn", "smellKey": "S112", "smellId": null, "repo": "isuruherath0_Diabetic_Retinopathy_Reccomendation_Service", "language": "python"} {"function": "@column_condition_partial(engine=PandasExecutionEngine)\n def _pandas(cls, column, **kwargs): # noqa: C901 - too complex\n shape = kwargs.get(\"shape\")\n shape_format = kwargs.get(\"shape_format\")\n column_shape_format = kwargs.get(\"column_shape_format\")\n properly = kwargs.get(\"properly\")\n\n # Check that shape is given and given in the correct format\n if shape is not None:\n try:\n if shape_format == \"wkt\":\n shape_ref = geos.from_wkt(shape)\n elif shape_format == \"wkb\":\n shape_ref = geos.from_wkb(shape)\n elif shape_format == \"geojson\":\n shape_ref = geos.from_geojson(shape)\n else:\n raise NotImplementedError( # noqa: TRY301\n \"Shape constructor method not implemented. Must be in WKT, WKB, or GeoJSON format.\"\n )\n except Exception:\n raise Exception(\"A valid reference shape was not given.\") # noqa: TRY002, TRY003\n else:\n raise Exception(\"A shape must be provided for this method.\") # noqa: TRY002, TRY003\n\n # Load the column into a pygeos Geometry vector from numpy array (Series not supported).\n if column_shape_format == \"wkt\":\n shape_test = geos.from_wkt(column.to_numpy(), on_invalid=\"ignore\")\n elif column_shape_format == \"wkb\":\n shape_test = geos.from_wkb(column.to_numpy(), on_invalid=\"ignore\")\n else:\n raise NotImplementedError(\"Column values shape format not implemented.\")\n\n # Allow for an array of reference shapes to be provided. Return a union of all the shapes in the array (Polygon or Multipolygon)\n shape_ref = geos.union_all(shape_ref)\n\n # Prepare the geometries\n geos.prepare(shape_ref)\n geos.prepare(shape_test)\n\n if properly:\n return pd.Series(geos.contains_properly(shape_ref, shape_test))\n else:\n return pd.Series(geos.contains(shape_ref, shape_test))", "smellKey": "S112", "smellId": null, "repo": "Chinissi_Repository2", "language": "python"} {"function": "def formfield(self, **kwargs):\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def compute_title(self, metadata):\n return None", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def run_procs(\n repo: str,\n reporoot: str,\n venv_path: str,\n _procs: tuple[tuple[str, tuple[str, ...], dict[str, str]], ...],\n verbose: bool = False,\n) -> bool:\n procs: list[tuple[str, tuple[str, ...], subprocess.Popen[bytes]]] = []\n\n stdout = subprocess.PIPE if not verbose else None\n stderr = subprocess.STDOUT if not verbose else None\n\n for name, cmd, extra_env in _procs:\n print(f\"\u23f3 {name}\")\n if constants.DEBUG:\n proc.xtrace(cmd)\n env = {\n **constants.user_environ,\n **proc.base_env,\n \"VIRTUAL_ENV\": venv_path,\n \"PATH\": f\"{venv_path}/bin:{reporoot}/.devenv/bin:{proc.base_path}\",\n }\n if extra_env:\n env = {**env, **extra_env}\n procs.append(\n (\n name,\n cmd,\n subprocess.Popen(\n cmd,\n stdout=stdout,\n stderr=stderr,\n env=env,\n cwd=reporoot,\n ),\n )\n )\n\n all_good = True\n for name, final_cmd, p in procs:\n out, _ = p.communicate()\n if p.returncode != 0:\n all_good = False\n out_str = f\"Output:\\n{out.decode()}\" if not verbose else \"\"\n print(\n f\"\"\"\n\u274c {name}\n\nfailed command (code {p.returncode}):\n {shlex.join(final_cmd)}\n\n{out_str}\n\n\"\"\"\n )\n else:\n print(f\"\u2705 {name}\")\n\n return all_good", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def handle_DATA(self, server, session, envelope: Envelope):\n msg = email.message_from_bytes(envelope.original_content)\n try:\n ret = self._handle(envelope, msg)\n return ret\n\n # happen if reverse-alias is used during the forward phase\n # as in this case, a new reverse-alias needs to be created for this reverse-alias -> chaos\n except CannotCreateContactForReverseAlias as e:\n LOG.w(\n \"Probably due to reverse-alias used in the forward phase, \"\n \"error:%s mail_from:%s, rcpt_tos:%s, header_from:%s, header_to:%s\",\n e,\n envelope.mail_from,\n envelope.rcpt_tos,\n msg[headers.FROM],\n msg[headers.TO],\n )\n return status.E524\n except (VERPReply, VERPForward, VERPTransactional) as e:\n LOG.w(\n \"email handling fail with error:%s \"\n \"mail_from:%s, rcpt_tos:%s, header_from:%s, header_to:%s\",\n e,\n envelope.mail_from,\n envelope.rcpt_tos,\n msg[headers.FROM],\n msg[headers.TO],\n )\n return status.E213\n except Exception as e:\n LOG.e(\n \"email handling fail with error:%s \"\n \"mail_from:%s, rcpt_tos:%s, header_from:%s, header_to:%s, saved to %s\",\n e,\n envelope.mail_from,\n envelope.rcpt_tos,\n msg[headers.FROM],\n msg[headers.TO],\n save_envelope_for_debugging(\n envelope, file_name_prefix=e.__class__.__name__\n ), # todo: remove\n )\n return status.E404", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def process_view(self, request, view_func, view_args, view_kwargs):\n if request.user.is_authenticated:\n return None\n\n if not getattr(view_func, \"login_required\", True):\n return None\n\n return self.handle_no_permission(request, view_func)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_api_context(self, is_public=False, platform=None):\n return self.to_json()", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def set_default_inbound_filters(\n project,\n organization,\n filters=(\n \"browser-extensions\",\n \"legacy-browsers\",\n \"web-crawlers\",\n \"filtered-transaction\",\n ),\n):\n\n browser_subfilters = [\n \"ie\",\n \"firefox\",\n \"chrome\",\n \"safari\",\n \"opera\",\n \"opera_mini\",\n \"android\",\n \"edge\",\n ]\n\n for filter_id in filters:\n state: dict[str, bool | list[str]] = {}\n if filter_id == \"legacy-browsers\":\n state[\"subfilters\"] = browser_subfilters\n else:\n state[\"active\"] = True\n\n inbound_filters.set_filter_state(filter_id, project, state)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def absolute_kwargs_view(request, arg1=1, arg2=2):\n return HttpResponse()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def visit_NSRef(self, node: nodes.NSRef, **kwargs: t.Any) -> None:\n self.symbols.load(node.name)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def cleanup_resources(self, force: bool = False) -> list[str]:\n \"\"\"\n Delete all extracted resource files and directories, returning a list\n of the file and directory names that could not be successfully removed.\n This function does not have any concurrency protection, so it should\n generally only be called when the extraction path is a temporary\n directory exclusive to a single process. This method is not\n automatically called; you must call it explicitly or register it as an\n ``atexit`` function if you wish to ensure cleanup of a temporary\n directory used for extractions.\n \"\"\"\n # XXX\n return []", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def plugin(version: str) -> type[OverloadedMethodPlugin]:\n return OverloadedMethodPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_email_template(self, notification) -> tuple: # pragma: no cover\n \"\"\"\n For types that support sending as email, this should return subject and template name\n \"\"\"\n return (\"\", \"\")", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def allow_relation(self, obj1, obj2, **hints):\n return self._db_for_model(obj1) == self._db_for_model(obj2)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def is_latest_analysis_completed(self, case_id: str):\n return True", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def get_latest_file(\n self, bundle: str, tags: list | None = None, version: int | None = None\n ) -> File | None:\n if tags.intersection(self._missing_tags):\n return None\n return self._files[0]", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\" and ownership != \"None\":\n return False\n if context == \"organization\" and membership is None:\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def make_account_vars(self, host, asset, account, automation, protocol, platform, gateway, path_dir):\n from accounts.const import AutomationTypes\n if not account:\n host['error'] = _(\"No account available\")\n return host\n\n port = protocol.port if protocol else 22\n host['ansible_host'] = asset.address\n host['ansible_port'] = port\n\n su_from = account.su_from\n if platform.su_enabled and su_from:\n su_from_auth = account.get_ansible_become_auth()\n host.update(su_from_auth)\n host.update(self.make_custom_become_ansible_vars(account, su_from_auth, path_dir))\n elif platform.su_enabled and not su_from and \\\n self.task_type in (AutomationTypes.change_secret, AutomationTypes.push_account):\n host.update(self.make_account_ansible_vars(account, path_dir))\n host['ansible_become'] = True\n host['ansible_become_user'] = 'root'\n host['ansible_become_password'] = account.escape_jinja2_syntax(account.secret)\n else:\n host.update(self.make_account_ansible_vars(account, path_dir))\n\n if platform.is_huawei():\n host['ansible_connection'] = 'network_cli'\n host['ansible_network_os'] = 'ce'\n\n if gateway:\n ansible_connection = host.get('ansible_connection', 'ssh')\n if ansible_connection in ('local', 'winrm', 'rdp'):\n host['jms_gateway'] = {\n 'address': gateway.address, 'port': gateway.port,\n 'username': gateway.username, 'secret': gateway.password,\n 'private_key_path': gateway.get_private_key_path(path_dir)\n }\n host['jms_asset']['port'] = port\n else:\n ansible_ssh_common_args = self.make_proxy_command(gateway, path_dir)\n host['jms_asset'].update(ansible_ssh_common_args)\n host.update(ansible_ssh_common_args)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def run(input_ooi: Hostname, additional_oois: list[Finding | Website], config: dict[str, Any]) -> Iterator[OOI]:\n # only websites have to comply with the internetnl rules\n websites = [websites for websites in additional_oois if isinstance(websites, Website)]\n if not websites:\n return\n\n finding_ids = [finding.finding_type.tokenized.id for finding in additional_oois if isinstance(finding, Finding)]\n\n result = \"\"\n internetnl_findings = {\n \"KAT-WEBSERVER-NO-IPV6\": \"This webserver does not have an IPv6 address\",\n \"KAT-NAMESERVER-NO-TWO-IPV6\": \"This webserver does not have at least two nameservers with an IPv6 address\",\n \"KAT-NO-DNSSEC\": \"This webserver is not DNSSEC signed\",\n \"KAT-INVALID-DNSSEC\": \"The DNSSEC signature of this webserver is not valid\",\n \"KAT-NO-HSTS\": \"This website has at least one webpage with a missing Strict-Transport-Policy header\",\n \"KAT-NO-CSP\": \"This website has at least one webpage with a missing Content-Security-Policy header\",\n \"KAT-NO-X-FRAME-OPTIONS\": \"This website has at least one webpage with a missing X-Frame-Options header\",\n \"KAT-NO-X-CONTENT-TYPE-OPTIONS\": (\n \"This website has at least one webpage with a missing X-Content-Type-Options header\"\n ),\n \"KAT-CSP-VULNERABILITIES\": \"This website has at least one webpage with a mis-configured CSP header\",\n \"KAT-HSTS-VULNERABILITIES\": \"This website has at least one webpage with a mis-configured HSTS header\",\n \"KAT-NO-CERTIFICATE\": \"This website does not have an SSL certificate\",\n \"KAT-HTTPS-NOT-AVAILABLE\": \"HTTPS is not available for this website\",\n \"KAT-SSL-CERT-HOSTNAME-MISMATCH\": \"The SSL certificate of this website does not match the hostname\",\n \"KAT-HTTPS-REDIRECT\": \"This website has at least one HTTP URL that does not redirect to HTTPS\",\n }\n\n for finding, description in internetnl_findings.items():\n if finding in finding_ids:\n result += f\"{description}\\n\"\n\n if result:\n ft = KATFindingType(id=\"KAT-INTERNETNL\")\n yield ft\n f = Finding(\n finding_type=ft.reference,\n ooi=input_ooi.reference,\n description=f\"This hostname has at least one website with the following finding(s): {result}\",\n )\n yield f", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def get_usage_pieces(self, ctx: Context) -> t.List[str]:\n return []", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def open(self, filename):\n\t\treturn None", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_function_signature_hook(\n self, fullname: str\n ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n \"\"\"Adjust the signature of a function.\n\n This method is called before type checking a function call. Plugin\n may infer a better type for the function.\n\n from lib import Class, do_stuff\n\n do_stuff(42)\n Class()\n\n This method will be called with 'lib.do_stuff' and then with 'lib.Class'.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def empty_response(request):\n return HttpResponse()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ensure_sso_groups(sender, sociallogin: SocialLogin, **kwargs):\n \"\"\"Sync groups from IdP each time a SSO user logs on.\n\n This event listener is registered in the apps ready method.\n \"\"\"\n if not get_global_setting('LOGIN_ENABLE_SSO_GROUP_SYNC'):\n return\n\n group_key = get_global_setting('SSO_GROUP_KEY')\n group_map = json.loads(get_global_setting('SSO_GROUP_MAP'))\n # map SSO groups to InvenTree groups\n group_names = []\n for sso_group in sociallogin.account.extra_data.get(group_key, []):\n if mapped_name := group_map.get(sso_group):\n group_names.append(mapped_name)\n\n # ensure user has groups\n user = sociallogin.account.user\n for group_name in group_names:\n try:\n user.groups.get(name=group_name)\n except Group.DoesNotExist:\n # user not in group yet\n try:\n group = Group.objects.get(name=group_name)\n except Group.DoesNotExist:\n logger.info(f'Creating group {group_name} as it did not exist')\n group = Group(name=group_name)\n group.save()\n logger.info(f'Adding group {group_name} to user {user}')\n user.groups.add(group)\n\n # remove groups not listed by SSO if not disabled\n if get_global_setting('SSO_REMOVE_GROUPS'):\n for group in user.groups.all():\n if not group.name in group_names:\n logger.info(f'Removing group {group.name} from {user}')\n user.groups.remove(group)", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def _alter_column_comment_sql(self, model, new_field, new_type, new_db_comment):\n return (\n self.sql_alter_column_comment\n % {\n \"table\": self.quote_name(model._meta.db_table),\n \"column\": self.quote_name(new_field.column),\n \"comment\": self._comment_sql(new_db_comment),\n },\n [],\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def can_createdir(self, item):\n\t\treturn True", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_bundle_deliverables_type(self, case_id: str) -> str | None:\n return None", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields):\n return \"\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def validate(self, value, model_instance):\n \"\"\"\n Validate value and raise ValidationError if necessary. Subclasses\n should override this to provide validation logic.\n \"\"\"\n if not self.editable:\n # Skip validation for non-editable fields.\n return\n\n if self.choices is not None and value not in self.empty_values:\n for option_key, option_value in self.choices:\n if isinstance(option_value, (list, tuple)):\n # This is an optgroup, so look inside the group for\n # options.\n for optgroup_key, optgroup_value in option_value:\n if value == optgroup_key:\n return\n elif value == option_key:\n return\n raise exceptions.ValidationError(\n self.error_messages[\"invalid_choice\"],\n code=\"invalid_choice\",\n params={\"value\": value},\n )\n\n if value is None and not self.null:\n raise exceptions.ValidationError(self.error_messages[\"null\"], code=\"null\")\n\n if not self.blank and value in self.empty_values:\n raise exceptions.ValidationError(self.error_messages[\"blank\"], code=\"blank\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def feed_extra_kwargs(self, obj):\n \"\"\"\n Return an extra keyword arguments dictionary that is used when\n initializing the feed generator.\n \"\"\"\n return {}", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:\n \"\"\"Dump the macro definition for the def created by macro_body.\"\"\"\n arg_tuple = \", \".join(repr(x.name) for x in macro_ref.node.args)\n name = getattr(macro_ref.node, \"name\", None)\n if len(macro_ref.node.args) == 1:\n arg_tuple += \",\"\n self.write(\n f\"Macro(environment, macro, {name!r}, ({arg_tuple}),\"\n f\" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},\"\n f\" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)\"\n )", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def ask_string(question, blank_or_default=False, password=False):\n answer = \"\"\n default = None\n if blank_or_default is not True and blank_or_default is not False:\n question += f\" (default = {blank_or_default})\"\n default = str(blank_or_default)\n allow_blank = True\n else:\n allow_blank = blank_or_default\n while len(answer) == 0:\n print(question + \" \")\n answer = input()\n if allow_blank:\n break\n if len(answer) == 0 and default:\n answer = default\n return answer", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def filescan(**kwargs):\n\tfrom Components.Scanner import Scanner, ScanPath\n\treturn [\n\t\tScanner(mimetypes=[\"video/mpeg\", \"video/MP2T\", \"video/x-msvideo\", \"video/mkv\"],\n\t\t\tpaths_to_scan=[\n\t\t\t\t\tScanPath(path=\"\", with_subdirs=False),\n\t\t\t\t\tScanPath(path=\"PRIVATE/AVCHD/BDMV/STREAM\", with_subdirs=False),\n\t\t\t\t],\n\t\t\tname=\"Movie\",\n\t\t\tdescription=_(\"Watch movies...\"),\n\t\t\topenfnc=movielist_open,\n\t\t),\n\t\tScanner(mimetypes=[\"video/x-vcd\"],\n\t\t\tpaths_to_scan=[\n\t\t\t\t\tScanPath(path=\"mpegav\", with_subdirs=False),\n\t\t\t\t\tScanPath(path=\"MPEGAV\", with_subdirs=False),\n\t\t\t\t],\n\t\t\tname=\"Video CD\",\n\t\t\tdescription=_(\"View video CD...\"),\n\t\t\topenfnc=filescan_open,\n\t\t),\n\t\tScanner(mimetypes=[\"audio/mpeg\", \"audio/x-wav\", \"application/ogg\", \"audio/x-flac\"],\n\t\t\tpaths_to_scan=[\n\t\t\t\t\tScanPath(path=\"\", with_subdirs=False),\n\t\t\t\t],\n\t\t\tname=\"Music\",\n\t\t\tdescription=_(\"Play music...\"),\n\t\t\topenfnc=filescan_open,\n\t\t),\n\t\tScanner(mimetypes=[\"audio/x-cda\"],\n\t\t\tpaths_to_scan=[\n\t\t\t\t\tScanPath(path=\"\", with_subdirs=False),\n\t\t\t\t],\n\t\t\tname=\"Audio-CD\",\n\t\t\tdescription=_(\"Play audio-CD...\"),\n\t\t\topenfnc=audioCD_open,\n\t\t),\n\t\t]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_data(scope, context, ownership, privilege, membership):\n data = {\n \"scope\": scope,\n \"auth\": {\n \"user\": {\"id\": random.randrange(0, 100), \"privilege\": privilege},\n \"organization\": {\n \"id\": random.randrange(100, 200),\n \"owner\": {\"id\": random.randrange(200, 300)},\n \"user\": {\"role\": membership},\n }\n if context == \"organization\"\n else None,\n },\n }\n\n user_id = data[\"auth\"][\"user\"][\"id\"]\n if context == \"organization\":\n if data[\"auth\"][\"organization\"][\"user\"][\"role\"] == \"owner\":\n data[\"auth\"][\"organization\"][\"owner\"][\"id\"] = user_id\n\n return data", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def check_errcode(result, func, cargs, cpl=False):\n \"\"\"\n Check the error code returned (c_int).\n \"\"\"\n check_err(result, cpl=cpl)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def write(self, project: Project, rules: RuleSet) -> None:\n self._rules = rules", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def notify_disable(\n organization: RpcOrganization | Organization,\n integration_name: str,\n redis_key: str,\n integration_slug: str | None = None,\n webhook_url: str | None = None,\n project: str | None = None,\n):\n\n integration_link = get_url(\n organization,\n get_provider_type(redis_key),\n integration_slug if \"sentry-app\" in redis_key and integration_slug else integration_name,\n )\n\n referrer = (\n \"?referrer=disabled-sentry-app\"\n if \"sentry-app\" in redis_key\n else \"?referrer=disabled-integration\"\n )\n\n for user in organization.get_owners():\n\n msg = MessageBuilder(\n subject=(\n get_sentry_app_subject(integration_name.title())\n if \"sentry-app\" in redis_key\n else get_subject(integration_name.title())\n ),\n context={\n \"integration_name\": integration_name.title(),\n \"integration_link\": f\"{integration_link}{referrer}\",\n \"webhook_url\": webhook_url if \"sentry-app\" in redis_key and webhook_url else \"\",\n \"dashboard_link\": (\n f\"{integration_link}dashboard/{referrer}\" if \"sentry-app\" in redis_key else \"\"\n ),\n },\n html_template=(\n \"sentry/integrations/sentry-app-notify-disable.html\"\n if \"sentry-app\" in redis_key and integration_slug\n else \"sentry/integrations/notify-disable.html\"\n ),\n template=(\n \"sentry/integrations/sentry-app-notify-disable.txt\"\n if \"sentry-app\" in redis_key and integration_slug\n else \"sentry/integrations/notify-disable.txt\"\n ),\n )\n msg.send_async([user.email])\n\n analytics.record(\n \"integration.disabled.notified\",\n organization_id=organization.id,\n provider=(\n integration_slug if integration_slug and \"sentry-app\" in redis_key else integration_name\n ), # integration_name is the provider for first party integrations\n integration_type=(\"sentry_app\" if \"sentry-app\" in redis_key else \"first-party\"),\n integration_id=redis_key[redis_key.find(\":\") + 1 :],\n user_id=organization.default_owner_id,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def find_module(self, fullname, path=None):\n if fullname in self.known_modules:\n return self\n return None", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_db_converters(self, expression):\n \"\"\"\n Return a list of functions needed to convert field data.\n\n Some field types on some backends do not provide data in the correct\n format, this is the hook for converter functions.\n \"\"\"\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:\n cp_value = ord(label[pos])\n\n if cp_value == 0x00b7:\n if 0 < pos < len(label)-1:\n if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c:\n return True\n return False\n\n elif cp_value == 0x0375:\n if pos < len(label)-1 and len(label) > 1:\n return _is_script(label[pos + 1], 'Greek')\n return False\n\n elif cp_value == 0x05f3 or cp_value == 0x05f4:\n if pos > 0:\n return _is_script(label[pos - 1], 'Hebrew')\n return False\n\n elif cp_value == 0x30fb:\n for cp in label:\n if cp == '\\u30fb':\n continue\n if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'):\n return True\n return False\n\n elif 0x660 <= cp_value <= 0x669:\n for cp in label:\n if 0x6f0 <= ord(cp) <= 0x06f9:\n return False\n return True\n\n elif 0x6f0 <= cp_value <= 0x6f9:\n for cp in label:\n if 0x660 <= ord(cp) <= 0x0669:\n return False\n return True\n\n return False", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def after_scenario(context, step):\n print(\">>> after_scenario activated\")\n\n # shut down any agents that were started for the scenario\n if \"active_agents\" in context:\n print(\">>> shutting down active agents ...\")\n for agent_name in context.active_agents.keys():\n print(\" shutting down:\", agent_name)\n agent = context.active_agents[agent_name][\"agent\"]\n if agent:\n terminated = aries_container_terminate(agent)\n print(\" terminated:\", terminated)", "smellKey": "S1172", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _repr_mimebundle_(\n self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any\n ) -> Dict[str, str]:\n data = {\"text/plain\": self.text, \"text/html\": self.html}\n if include:\n data = {k: v for (k, v) in data.items() if k in include}\n if exclude:\n data = {k: v for (k, v) in data.items() if k not in exclude}\n return data", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [PluginDescriptor(name=_(\"%s Setup\") % cur_skin, description=_(\"Personalize your Skin\"), where=PluginDescriptor.WHERE_MENU, icon=\"plugin.png\", fnc=menu)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def DoUpdateDueToChangeInData(self, inIncomingPvFilter,\n outOutgoingPvFilter):\n #default behavior is to do nothing on new data\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriOperationSpecifics::\"\n \"DoUpdateDueToChangeInData executed\\n\")\n return False", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:\n for child in node.body:\n self.sym_visitor.visit(child)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def compile_full_name_template(*args, **kwargs):\n \"\"\"Recompile the template for rendering the 'full_name' attribute of a Part.\n\n This function is called whenever the 'PART_NAME_FORMAT' setting is changed.\n \"\"\"\n global _part_full_name_template\n global _part_full_name_template_string\n\n template_string = get_global_setting('PART_NAME_FORMAT', cache=True)\n\n # Skip if the template string has not changed\n if (\n template_string == _part_full_name_template_string\n and _part_full_name_template is not None\n ):\n return _part_full_name_template\n\n # Cache the template string\n _part_full_name_template_string = template_string\n\n env = Environment(\n autoescape=select_autoescape(default_for_string=False, default=False),\n variable_start_string='{{',\n variable_end_string='}}',\n )\n\n # Compile the template\n try:\n _part_full_name_template = env.from_string(template_string)\n except Exception:\n _part_full_name_template = None\n\n return _part_full_name_template", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def cancelCB(self, value):\n\t\tself.keySave()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def group_categories_from_search_filters(\n search_filters: Sequence[SearchFilter], organization: Organization, actor: User | RpcUser\n) -> set[int]:\n group_categories = group_categories_from(search_filters)\n\n if not group_categories:\n group_categories = set(get_search_strategies().keys())\n # if we're not searching for feedbacks, then hide them by default\n group_categories.discard(GroupCategory.FEEDBACK.value)\n\n if not features.has(\"organizations:performance-issues-search\", organization):\n group_categories.discard(GroupCategory.PERFORMANCE.value)\n\n return group_categories", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def close(self, **kwargs):\n self.closed = True", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def as_sql(self, compiler, connection):\n return compiler.compile(self.resolved_condition)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def server_error(request: HttpRequest, *args, **kwargs) -> JsonResponse: # noqa: ARG001\n data = {\n \"code\": HTTP_500_INTERNAL_SERVER_ERROR,\n \"level\": \"error\",\n \"desc\": \"Server Error (500)\",\n }\n return JsonResponse(data=data, status=HTTP_500_INTERNAL_SERVER_ERROR)", "smellKey": "S1172", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def get_language_from_path(request):\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def err_handler(error_class, error_number, message):\n logger.error(\"GDAL_ERROR %d: %s\", error_number, message)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def volumes3d(\n self,\n source,\n dx=0.25,\n xlo=None,\n xhi=None,\n ylo=None,\n yhi=None,\n zlo=None,\n zhi=None,\n n_soma_step=100,\n ):\n # mesh, surface_areas, volumes, triangles = geometry3d.voxelize2(source, dx=dx)\n # volumes._values *= self._area_per_vol # volume on 2D boundaries is actually the area; the amount of space for holding things\n # surface_areas._values *= 0\n # return mesh, surface_areas, volumes, triangles\n internal_voxels, surface_voxels, mesh_grid = geometry3d.voxelize2(source, dx=dx)\n area_per_vol = self._area_per_vol\n for key in internal_voxels:\n internal_voxels[key][0] *= area_per_vol\n for key in surface_voxels:\n surface_voxels[key][0] *= area_per_vol\n return internal_voxels, surface_voxels, mesh_grid", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def mass_mail_sending_view(request):\n m1 = mail.EmailMessage(\n \"First Test message\",\n \"This is the first test email\",\n \"from@example.com\",\n [\"first@example.com\", \"second@example.com\"],\n )\n m2 = mail.EmailMessage(\n \"Second Test message\",\n \"This is the second test email\",\n \"from@example.com\",\n [\"second@example.com\", \"third@example.com\"],\n )\n\n c = mail.get_connection()\n c.send_messages([m1, m2])\n\n return HttpResponse(\"Mail sent\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def event_handler(self, data, **kwargs):\n event = data.get(\"event\", None)\n if not event:\n return\n\n pid = data.get(\"pid\", None)\n if pid:\n self.write_pid(pid)\n\n event_data = data.get(\"event_data\", {})\n host = event_data.get(\"remote_addr\", \"\")\n task = event_data.get(\"task\", \"\")\n res = event_data.get(\"res\", {})\n handler = getattr(self, event, self.on_any)\n handler(event_data, host=host, task=task, res=res)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def run(\n input_ooi: X509Certificate, additional_oois: list[Website | SubjectAlternativeNameHostname], config: dict\n) -> Iterator[OOI]:\n websites = [website for website in additional_oois if isinstance(website, Website)]\n subject_alternative_name_hostnames = [\n subject_alternative_name.hostname.tokenized.name.rstrip(\".\")\n for subject_alternative_name in additional_oois\n if isinstance(subject_alternative_name, SubjectAlternativeNameHostname)\n ]\n\n subject_alternative_name_qualifiers = [\n subject_alternative_name.name.rstrip(\".\")\n for subject_alternative_name in additional_oois\n if isinstance(subject_alternative_name, SubjectAlternativeNameQualifier)\n ]\n\n for website in websites:\n hostname = website.hostname.tokenized.name.rstrip(\".\")\n\n if hostname in subject_alternative_name_hostnames:\n return\n\n if hostname_in_qualifiers(hostname, subject_alternative_name_qualifiers):\n return\n\n ft = KATFindingType(id=\"KAT-SSL-CERT-HOSTNAME-MISMATCH\")\n yield Finding(\n ooi=website.reference,\n finding_type=ft.reference,\n description=f\"The hostname {website.hostname} does not match the subject of the certificate\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def get_object(self, request, *args, **kwargs):\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def setdefault(self, key, default):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def resetSortOrder(self, key=None):\n\t\tconfig.usage.menu_sort_weight.value = {\"mainmenu\": {\"submenu\": {}}}\n\t\tconfig.usage.menu_sort_weight.save()\n\t\tself.closeRecursive()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_location(self, metadata):\n return None", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def insert(self, pos, value):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def wait_check(*args, type=\"CONVERTED\", scope=OPENC3_SCOPE):\n \"\"\"Wait for the converted value of a telmetry item against a condition or for a timeout\n and then check against the condition\n Supports two signatures:\n wait_check(target_name, packet_name, item_name, comparison_to_eval, timeout, polling_rate)\n or\n wait_check('target_name packet_name item_name > 1', timeout, polling_rate)\"\"\"\n (\n target_name,\n packet_name,\n item_name,\n comparison_to_eval,\n timeout,\n polling_rate,\n ) = _wait_check_process_args(args)\n start_time = time.time()\n success, value = _openc3_script_wait_value(\n target_name,\n packet_name,\n item_name,\n type,\n comparison_to_eval,\n timeout,\n polling_rate,\n )\n if isinstance(value, str):\n value = f\"'{value}'\" # Show user the check against a quoted string\n time_diff = time.time() - start_time\n check_str = f\"CHECK: {_upcase(target_name, packet_name, item_name)}\"\n if comparison_to_eval:\n check_str += f\" {comparison_to_eval}\"\n with_value_str = f\"with value == {value} after waiting {time_diff:.3f} seconds\"\n if success:\n print(f\"{check_str} success {with_value_str}\")\n else:\n message = f\"{check_str} failed {with_value_str}\"\n if openc3.script.DISCONNECT:\n print(f\"ERROR: {message}\")\n else:\n raise CheckError(message)\n return time_diff", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def render_to_response(self, context, **response_kwargs):\n menu = [item for item in self.derive_menu() if item is not None]\n return JsonResponse({\"results\": menu})", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def can_bookmarks(self, item):\n\t\treturn True", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_method_signature_hook(\n self, fullname: str\n ) -> Callable[[MethodSigContext], FunctionLike] | None:\n \"\"\"Adjust the signature of a method.\n\n This method is called before type checking a method call. Plugin\n may infer a better type for the method. The hook is also called for special\n Python dunder methods except __init__ and __new__ (use get_function_hook to customize\n class instantiation). This function is called with the method full name using\n the class where it was _defined_. For example, in this code:\n\n from lib import Special\n\n class Base:\n def method(self, arg: Any) -> Any:\n ...\n class Derived(Base):\n ...\n\n var: Derived\n var.method(42)\n\n x: Special\n y = x[0]\n\n this method is called with '__main__.Base.method', and then with\n 'lib.Special.__getitem__'.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def apply_hooks_to_class(\n self: SemanticAnalyzer,\n module: str,\n info: TypeInfo,\n options: Options,\n file_node: MypyFile,\n errors: Errors,\n) -> bool:\n # TODO: Move more class-related hooks here?\n defn = info.defn\n ok = True\n for decorator in defn.decorators:\n with self.file_context(file_node, options, info):\n hook = None\n\n decorator_name = self.get_fullname_for_hook(decorator)\n if decorator_name:\n hook = self.plugin.get_class_decorator_hook_2(decorator_name)\n # Special case: if the decorator is itself decorated with\n # typing.dataclass_transform, apply the hook for the dataclasses plugin\n # TODO: remove special casing here\n if hook is None and find_dataclass_transform_spec(decorator):\n hook = dataclasses_plugin.dataclass_class_maker_callback\n\n if hook:\n ok = ok and hook(ClassDefContext(defn, decorator, self))\n\n # Check if the class definition itself triggers a dataclass transform (via a parent class/\n # metaclass)\n spec = find_dataclass_transform_spec(info)\n if spec is not None:\n with self.file_context(file_node, options, info):\n # We can't use the normal hook because reason = defn, and ClassDefContext only accepts\n # an Expression for reason\n ok = ok and dataclasses_plugin.DataclassTransformer(defn, defn, spec, self).transform()\n\n return ok", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_api_meta(self, meta, is_public=False, platform=None):\n return meta", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def top_events_timeseries(\n timeseries_columns,\n selected_columns,\n user_query,\n snuba_params,\n orderby,\n rollup,\n limit,\n organization,\n equations=None,\n referrer=None,\n top_events=None,\n allow_empty=True,\n zerofill_results=True,\n include_other=False,\n functions_acl=None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n query_source: QuerySource | None = None,\n):\n \"\"\"\n High-level API for doing arbitrary user timeseries queries for a limited number of top events\n\n this API should match that of sentry.snuba.discover.top_events_timeseries\n \"\"\"\n\n if top_events is None:\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"top_events.fetch_events\"):\n top_events = query(\n selected_columns,\n query=user_query,\n snuba_params=snuba_params,\n equations=equations,\n orderby=orderby,\n limit=limit,\n referrer=referrer,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n include_equation_fields=True,\n skip_tag_resolution=True,\n query_source=query_source,\n )\n\n top_events_builder = TopEventsSpanIndexedQueryBuilder(\n Dataset.SpansIndexed,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=False,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n equations=equations,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n skip_tag_resolution=True,\n ),\n )\n if len(top_events[\"data\"]) == limit and include_other:\n other_events_builder = TopEventsSpanIndexedQueryBuilder(\n Dataset.SpansIndexed,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=True,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n equations=equations,\n )\n result, other_result = bulk_snuba_queries(\n [top_events_builder.get_snql_query(), other_events_builder.get_snql_query()],\n referrer=referrer,\n query_source=query_source,\n )\n else:\n result = top_events_builder.run_query(referrer)\n other_result = {\"data\": []}\n if (\n not allow_empty\n and not len(result.get(\"data\", []))\n and not len(other_result.get(\"data\", []))\n ):\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, \"time\"\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"top_events.transform_results\") as span:\n span.set_data(\"result_count\", len(result.get(\"data\", [])))\n result = top_events_builder.process_results(result)\n\n issues = {}\n translated_groupby = top_events_builder.translated_groupby\n\n results = (\n {discover.OTHER_KEY: {\"order\": limit, \"data\": other_result[\"data\"]}}\n if len(other_result.get(\"data\", []))\n else {}\n )\n # Using the top events add the order to the results\n for index, item in enumerate(top_events[\"data\"]):\n result_key = discover.create_result_key(item, translated_groupby, issues)\n results[result_key] = {\"order\": index, \"data\": []}\n for row in result[\"data\"]:\n result_key = discover.create_result_key(row, translated_groupby, issues)\n if result_key in results:\n results[result_key][\"data\"].append(row)\n else:\n logger.warning(\n \"spans_indexed.top-events.timeseries.key-mismatch\",\n extra={\"result_key\": result_key, \"top_event_keys\": list(results.keys())},\n )\n for key, item in results.items():\n results[key] = SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n item[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n \"time\",\n )\n if zerofill_results\n else item[\"data\"]\n ),\n \"order\": item[\"order\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n\n return results", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def emit_tuple_cast(\n self,\n src: str,\n dest: str,\n typ: RTuple,\n declare_dest: bool,\n error: ErrorHandler,\n src_type: RType | None,\n ) -> None:\n \"\"\"Emit cast to a tuple type.\n\n The arguments are similar to emit_cast.\n \"\"\"\n if declare_dest:\n self.emit_line(f\"PyObject *{dest};\")\n # This reuse of the variable is super dodgy. We don't even\n # care about the values except to check whether they are\n # invalid.\n out_label = self.new_label()\n self.emit_lines(\n \"if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{\".format(\n r=src, size=len(typ.types)\n ),\n f\"{dest} = NULL;\",\n f\"goto {out_label};\",\n \"}\",\n )\n for i, item in enumerate(typ.types):\n # Since we did the checks above this should never fail\n self.emit_cast(\n f\"PyTuple_GET_ITEM({src}, {i})\",\n dest,\n item,\n declare_dest=False,\n raise_exception=False,\n optional=False,\n )\n self.emit_line(f\"if ({dest} == NULL) goto {out_label};\")\n\n self.emit_line(f\"{dest} = {src};\")\n self.emit_label(out_label)", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_xframe_options_value(self, request, response):\n \"\"\"\n Get the value to set for the X_FRAME_OPTIONS header. Use the value from\n the X_FRAME_OPTIONS setting, or 'DENY' if not set.\n\n This method can be overridden if needed, allowing it to vary based on\n the request or response.\n \"\"\"\n return getattr(settings, \"X_FRAME_OPTIONS\", \"DENY\").upper()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_field(self, field, **kwargs):\n errors = []\n # Backends may implement a check_field_type() method.\n if (\n hasattr(self, \"check_field_type\")\n and\n # Ignore any related fields.\n not getattr(field, \"remote_field\", None)\n ):\n # Ignore fields with unsupported features.\n db_supports_all_required_features = all(\n getattr(self.connection.features, feature, False)\n for feature in field.model._meta.required_db_features\n )\n if db_supports_all_required_features:\n field_type = field.db_type(self.connection)\n # Ignore non-concrete fields.\n if field_type is not None:\n errors.extend(self.check_field_type(field, field_type))\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def record_transaction_name(project: Project, event_data: Mapping[str, Any], **kwargs: Any) -> None:\n if transaction_name := _should_store_transaction_name(event_data):\n safe_execute(\n _record_sample,\n ClustererNamespace.TRANSACTIONS,\n project,\n transaction_name,\n )\n if in_random_rollout(\"txnames.bump-lifetime-sample-rate\"):\n safe_execute(_bump_rule_lifetime, project, event_data)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def check_models_permissions(app_configs=None, **kwargs):\n if app_configs is None:\n models = apps.get_models()\n else:\n models = chain.from_iterable(\n app_config.get_models() for app_config in app_configs\n )\n\n Permission = apps.get_model(\"auth\", \"Permission\")\n permission_name_max_length = Permission._meta.get_field(\"name\").max_length\n permission_codename_max_length = Permission._meta.get_field(\"codename\").max_length\n errors = []\n\n for model in models:\n opts = model._meta\n builtin_permissions = dict(_get_builtin_permissions(opts))\n # Check builtin permission name length.\n max_builtin_permission_name_length = (\n max(len(name) for name in builtin_permissions.values())\n if builtin_permissions\n else 0\n )\n if max_builtin_permission_name_length > permission_name_max_length:\n verbose_name_max_length = permission_name_max_length - (\n max_builtin_permission_name_length - len(opts.verbose_name_raw)\n )\n errors.append(\n checks.Error(\n \"The verbose_name of model '%s' must be at most %d \"\n \"characters for its builtin permission names to be at \"\n \"most %d characters.\"\n % (opts.label, verbose_name_max_length, permission_name_max_length),\n obj=model,\n id=\"auth.E007\",\n )\n )\n # Check builtin permission codename length.\n max_builtin_permission_codename_length = (\n max(len(codename) for codename in builtin_permissions.keys())\n if builtin_permissions\n else 0\n )\n if max_builtin_permission_codename_length > permission_codename_max_length:\n model_name_max_length = permission_codename_max_length - (\n max_builtin_permission_codename_length - len(opts.model_name)\n )\n errors.append(\n checks.Error(\n \"The name of model '%s' must be at most %d characters \"\n \"for its builtin permission codenames to be at most %d \"\n \"characters.\"\n % (\n opts.label,\n model_name_max_length,\n permission_codename_max_length,\n ),\n obj=model,\n id=\"auth.E011\",\n )\n )\n codenames = set()\n for codename, name in opts.permissions:\n # Check custom permission name length.\n if len(name) > permission_name_max_length:\n errors.append(\n checks.Error(\n \"The permission named '%s' of model '%s' is longer \"\n \"than %d characters.\"\n % (\n name,\n opts.label,\n permission_name_max_length,\n ),\n obj=model,\n id=\"auth.E008\",\n )\n )\n # Check custom permission codename length.\n if len(codename) > permission_codename_max_length:\n errors.append(\n checks.Error(\n \"The permission codenamed '%s' of model '%s' is \"\n \"longer than %d characters.\"\n % (\n codename,\n opts.label,\n permission_codename_max_length,\n ),\n obj=model,\n id=\"auth.E012\",\n )\n )\n # Check custom permissions codename clashing.\n if codename in builtin_permissions:\n errors.append(\n checks.Error(\n \"The permission codenamed '%s' clashes with a builtin \"\n \"permission for model '%s'.\" % (codename, opts.label),\n obj=model,\n id=\"auth.E005\",\n )\n )\n elif codename in codenames:\n errors.append(\n checks.Error(\n \"The permission codenamed '%s' is duplicated for \"\n \"model '%s'.\" % (codename, opts.label),\n obj=model,\n id=\"auth.E006\",\n )\n )\n codenames.add(codename)\n\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_cli(request: HttpRequest) -> HttpResponse:\n metrics.incr(\"cli.download_script\")\n return HttpResponse(SCRIPT, content_type=\"text/plain\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def poplist(self, key):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def regular(request):\n return HttpResponse(b\"regular content\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def visit_EnvironmentAttribute(\n self, node: nodes.EnvironmentAttribute, frame: Frame\n ) -> None:\n self.write(\"environment.\" + node.name)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "async def _load_did_document(self, did: str, options: dict):\n # Resolver expects plain did without path, query, etc...\n # DIDUrl throws error if it contains no path, query etc...\n # This makes sure we get a plain did\n did = DIDUrl.parse(did).did if DIDUrl.is_valid(did) else did\n\n did_document = await self.resolver.resolve(self.profile, did)\n\n document = {\n \"contentType\": \"application/ld+json\",\n \"contextUrl\": None,\n \"documentUrl\": did,\n \"document\": did_document,\n }\n\n return document", "smellKey": "S1172", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def SET_DEFAULT(collector, field, sub_objs, using):\n collector.add_field_update(field, field.get_default(), sub_objs)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def parse_navigation_property(\n root, curr_entitytype, element, path, top_collections, found_top, xml_map\n):\n if element.tag != (EDM + \"NavigationProperty\"):\n return\n\n # We don't want to actually parse this property if it's just an excerpt\n for annotation in element.findall(EDM + \"Annotation\"):\n term = annotation.get(\"Term\")\n if term == \"Redfish.ExcerptCopy\":\n return\n\n # We don't want to aggregate JsonSchemas as well as anything under\n # AccountService or SessionService\n nav_name = element.get(\"Name\")\n if nav_name in [\"JsonSchemas\", \"AccountService\", \"SessionService\"]:\n return\n\n nav_type = element.get(\"Type\")\n if \"Collection\" in nav_type:\n # Type is either Collection(<Namespace>.<TypeName>) or\n # Collection(<NamespaceName>.<NamespaceVersion>.<TypeName>)\n if nav_type.startswith(\"Collection\"):\n qualified_name = nav_type.split(\"(\")[1].split(\")\")[0]\n # Do we need to parse this file or another file?\n qualified_name_split = qualified_name.split(\".\")\n if len(qualified_name_split) == 3:\n typename = qualified_name_split[2]\n else:\n typename = qualified_name_split[1]\n file_key = qualified_name_split[0]\n\n # If we contain a collection array then we don't want to add the\n # name to the path if we're a collection schema\n if nav_name != \"Members\":\n path += \"/\" + nav_name\n if path in seen_paths:\n return\n seen_paths.add(path)\n\n # Did we find the top level collection in the current path or\n # did we previously find it?\n if not found_top:\n top_collections.add(path)\n found_top = True\n\n member_id = typename + \"Id\"\n prev_count = path.count(member_id)\n if prev_count:\n new_path = path + \"/{\" + member_id + str(prev_count + 1) + \"}\"\n else:\n new_path = path + \"/{\" + member_id + \"}\"\n\n # type is \"<Namespace>.<TypeName>\", both should end with \"Collection\"\n else:\n # Escape if we've found a circular dependency like SubProcessors\n if path.count(nav_name) >= 2:\n return\n\n nav_type_split = nav_type.split(\".\")\n if (len(nav_type_split) != 2) and (\n nav_type_split[0] != nav_type_split[1]\n ):\n # We ended up with something like Resource.ResourceCollection\n return\n file_key = nav_type_split[0]\n typename = nav_type_split[1]\n new_path = path + \"/\" + nav_name\n\n # Did we find the top level collection in the current path or did we\n # previously find it?\n if not found_top:\n top_collections.add(new_path)\n found_top = True\n\n # NavigationProperty is not for a collection\n else:\n # Bail if we've found a circular dependency like MetricReport\n if path.count(nav_name):\n return\n\n new_path = path + \"/\" + nav_name\n nav_type_split = nav_type.split(\".\")\n file_key = nav_type_split[0]\n typename = nav_type_split[1]\n\n # We need to specially handle certain URIs since the Name attribute from the\n # schema is not used as part of the path\n # TODO: Expand this section to add special handling across the entirety of\n # the Redfish tree\n new_path2 = \"\"\n if new_path == \"/redfish/v1/Tasks\":\n new_path2 = \"/redfish/v1/TaskService\"\n\n # If we had to apply special handling then we need to remove the initial\n # version of the URI if it was previously added\n if new_path2 != \"\":\n if new_path in seen_paths:\n seen_paths.remove(new_path)\n new_path = new_path2\n\n # No need to parse the new URI if we've already done so\n if new_path in seen_paths:\n return\n seen_paths.add(new_path)\n\n # We can stop parsing if we've found a top level collection\n # TODO: Don't return here when we want to walk the entire tree instead\n if found_top:\n return\n\n # If the namespace of the NavigationProperty's Type is not in our xml map\n # then that means it inherits from elsewhere in the current file\n if file_key in xml_map:\n parse_node(\n typename, new_path, top_collections, found_top, xml_map[file_key]\n )\n else:\n parse_root(\n root, typename, new_path, top_collections, found_top, xml_map\n )", "smellKey": "S1172", "smellId": null, "repo": "edtanous_bmcweb", "language": "python"} {"function": "def serialize(\n self, obj: Any, attrs: Mapping[Any, Any], user: Any, **kwargs: Any\n ) -> Mapping[str, Any]:\n \"\"\"\n Convert an arbitrary python object `obj` to an object that only contains primitives.\n\n :param obj: An item from `item_list` that was passed to `get_attrs`.\n :param attrs: The object in `get_attrs` that corresponds to `obj`.\n :param user: The user who will be viewing the objects.\n :param kwargs: Any\n :returns A serialized version of `obj`.\n \"\"\"\n return {}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def normalize(\n self, value: str, params: ParamsType, combinator: Combinator | None\n ) -> NormalizedArg:\n return value", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def generate_serial_number(part=None, quantity=1, **kwargs) -> str:\n \"\"\"Generate a default 'serial number' for a new StockItem.\"\"\"\n quantity = quantity or 1\n\n if part is None:\n # Cannot generate a serial number without a part\n return None\n\n try:\n quantity = int(quantity)\n except Exception:\n raise ValidationError({'quantity': 'Invalid quantity value'})\n\n if quantity < 1:\n raise ValidationError({'quantity': 'Quantity must be greater than zero'})\n\n # If we are here, no plugins were available to generate a serial number\n # In this case, we will generate a simple serial number based on the provided part\n sn = part.get_latest_serial_number()\n\n serials = []\n\n # Generate the required quantity of serial numbers\n # Note that this call gets passed through to the plugin system\n while quantity > 0:\n sn = InvenTree.helpers.increment_serial_number(sn, part=part)\n\n # Exit if an empty or duplicated serial is generated\n if not sn or sn in serials:\n break\n\n serials.append(sn)\n quantity -= 1\n\n return ','.join(serials)", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def fly_configure_view(\n request: HttpRequest, org: RpcOrganization, auth_provider: RpcAuthProvider\n) -> DeferredResponse:\n return DeferredResponse(\"sentry_auth_fly/configure.html\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def query(\n selected_columns: list[str],\n query: str,\n snuba_params: SnubaParams,\n equations: list[str] | None = None,\n orderby: list[str] | None = None,\n offset: int | None = None,\n limit: int = 50,\n referrer: str | None = None,\n auto_fields: bool = False,\n auto_aggregations: bool = False,\n include_equation_fields: bool = False,\n allow_metric_aggregates: bool = False,\n use_aggregate_conditions: bool = False,\n conditions: list[Condition] | None = None,\n functions_acl: list[str] | None = None,\n transform_alias_to_input_format: bool = False,\n sample: float | None = None,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n skip_tag_resolution: bool = False,\n extra_columns: list[Column] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n fallback_to_transactions: bool = False,\n query_source: QuerySource | None = None,\n enable_rpc: bool | None = False,\n):\n builder = SpansEAPQueryBuilder(\n Dataset.EventsAnalyticsPlatform,\n {},\n snuba_params=snuba_params,\n query=query,\n selected_columns=selected_columns,\n equations=equations,\n orderby=orderby,\n limit=limit,\n offset=offset,\n sample_rate=sample,\n config=QueryBuilderConfig(\n has_metrics=has_metrics,\n transform_alias_to_input_format=transform_alias_to_input_format,\n skip_tag_resolution=skip_tag_resolution,\n equation_config={\"auto_add\": include_equation_fields},\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n functions_acl=functions_acl,\n ),\n )\n\n result = builder.process_results(\n builder.run_query(referrer=referrer, query_source=query_source)\n )\n return result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def plugin(version: str) -> type[Plugin2]:\n return Plugin2", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def db_for_write(self, model, **hints):\n return self._db_for_model(model)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def handle_delete(scope, instance, store_in_deletion_cache=False, **kwargs):\n deletion_cache = get_cache()\n if store_in_deletion_cache:\n deletion_cache.set(\n instance.__class__,\n instance.id,\n {\n \"oid\": organization_id(instance),\n \"oslug\": organization_slug(instance),\n \"pid\": project_id(instance),\n \"tid\": task_id(instance),\n \"jid\": job_id(instance),\n },\n )\n return\n\n instance_meta_info = deletion_cache.pop(instance.__class__, instance.id)\n if instance_meta_info:\n oid = instance_meta_info[\"oid\"]\n oslug = instance_meta_info[\"oslug\"]\n pid = instance_meta_info[\"pid\"]\n tid = instance_meta_info[\"tid\"]\n jid = instance_meta_info[\"jid\"]\n else:\n oid = organization_id(instance)\n oslug = organization_slug(instance)\n pid = project_id(instance)\n tid = task_id(instance)\n jid = job_id(instance)\n\n uid = user_id(instance)\n uname = user_name(instance)\n uemail = user_email(instance)\n\n record_server_event(\n scope=scope,\n request_id=request_id(),\n on_commit=True,\n obj_id=getattr(instance, 'id', None),\n obj_name=_get_object_name(instance),\n org_id=oid,\n org_slug=oslug,\n project_id=pid,\n task_id=tid,\n job_id=jid,\n user_id=uid,\n user_name=uname,\n user_email=uemail,\n )", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def handles_frame(self, frame, stacktrace_info):\n \"\"\"Returns true if this processor can handle this frame. This is the\n earliest check and operates on a raw frame and stacktrace info. If\n this returns `True` a processable frame is created.\n \"\"\"\n return False", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def add_attribute_to_class(\n api: SemanticAnalyzerPluginInterface,\n cls: ClassDef,\n name: str,\n typ: Type,\n final: bool = False,\n no_serialize: bool = False,\n override_allow_incompatible: bool = False,\n fullname: str | None = None,\n is_classvar: bool = False,\n overwrite_existing: bool = False,\n) -> Var:\n \"\"\"\n Adds a new attribute to a class definition.\n This currently only generates the symbol table entry and no corresponding AssignmentStatement\n \"\"\"\n info = cls.info\n\n # NOTE: we would like the plugin generated node to dominate, but we still\n # need to keep any existing definitions so they get semantically analyzed.\n if name in info.names and not overwrite_existing:\n # Get a nice unique name instead.\n r_name = get_unique_redefinition_name(name, info.names)\n info.names[r_name] = info.names[name]\n\n node = Var(name, typ)\n node.info = info\n node.is_final = final\n node.is_classvar = is_classvar\n if name in ALLOW_INCOMPATIBLE_OVERRIDE:\n node.allow_incompatible_override = True\n else:\n node.allow_incompatible_override = override_allow_incompatible\n\n if fullname:\n node._fullname = fullname\n else:\n node._fullname = info.fullname + \".\" + name\n\n info.names[name] = SymbolTableNode(\n MDEF, node, plugin_generated=True, no_serialize=no_serialize\n )\n return node", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_import_exclude_fields(self, **kwargs) -> list:\n \"\"\"Return the list of field names which are excluded during data import.\"\"\"\n return self.import_exclude_fields", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def _file_dialog(title, message, filter=None):\n answer = \"\"\n while len(answer) == 0:\n print(f\"{title}\\n{message}\\n<Type file name>:\")\n answer = input()\n return answer", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs):\n \"\"\"Load extra data from provider and store it on current UserSocialAuth\n extra_data field.\n \"\"\"\n social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid, user)\n if social_user:\n extra_data = backend.extra_data(user, uid, response, details)\n if kwargs.get(\"original_email\") and \"email\" not in extra_data:\n extra_data[\"email\"] = kwargs.get(\"original_email\")\n if extra_data and social_user.extra_data != extra_data:\n if social_user.extra_data:\n social_user.extra_data.update(extra_data)\n else:\n social_user.extra_data = extra_data\n social_user.save()\n return {\"social_user\": social_user}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def bind_f(\n instance: LocalProxy[t.Any], obj: t.Any\n ) -> t.Callable[..., t.Any]:\n return f.__get__(obj, type(obj)) # type: ignore", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_pk_value_on_save(self, instance):\n \"\"\"\n Hook to generate new PK values on save. This method is called when\n saving instances with no primary key value set. If this method returns\n something else than None, then the returned value is used when saving\n the new instance.\n \"\"\"\n if self.default:\n return self.get_default()\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def readServicesFromBouquet(self, sBouquetSelection, formatstring): # This method gives back a list of services for a given bouquet.\n\t\tserviceHandler = eServiceCenter.getInstance()\n\t\troot = eServiceReference(sBouquetSelection)\n\t\tserviceList = serviceHandler.list(root)\n\t\tif serviceList is not None:\n\t\t\treturn serviceList.getContent(\"CN\", True) # (ServiceCompareString, Name)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def end(self, arg=None):\n return self._start + len(self._text)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def query(\n selected_columns: list[str],\n query: str,\n snuba_params: SnubaParams,\n equations: list[str] | None = None,\n orderby: list[str] | None = None,\n offset: int | None = None,\n limit: int = 50,\n referrer: str | None = None,\n auto_fields: bool = False,\n auto_aggregations: bool = False,\n include_equation_fields: bool = False,\n allow_metric_aggregates: bool = False,\n use_aggregate_conditions: bool = False,\n conditions: list[Condition] | None = None,\n functions_acl: list[str] | None = None,\n transform_alias_to_input_format: bool = False,\n sample: float | None = None,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n skip_tag_resolution: bool = False,\n extra_columns: list[Column] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n fallback_to_transactions: bool = False,\n query_source: QuerySource | None = None,\n) -> EventsResponse:\n return discover.query(\n selected_columns,\n query,\n snuba_params=snuba_params,\n equations=equations,\n orderby=orderby,\n offset=offset,\n limit=limit,\n referrer=referrer,\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n include_equation_fields=include_equation_fields,\n allow_metric_aggregates=allow_metric_aggregates,\n use_aggregate_conditions=use_aggregate_conditions,\n conditions=conditions,\n functions_acl=functions_acl,\n transform_alias_to_input_format=transform_alias_to_input_format,\n sample=sample,\n has_metrics=has_metrics,\n use_metrics_layer=use_metrics_layer,\n skip_tag_resolution=skip_tag_resolution,\n extra_columns=extra_columns,\n on_demand_metrics_enabled=on_demand_metrics_enabled,\n on_demand_metrics_type=on_demand_metrics_type,\n dataset=Dataset.Transactions,\n fallback_to_transactions=fallback_to_transactions,\n query_source=query_source,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def run(boefje_meta: BoefjeMeta) -> list[tuple[set, bytes | str]]:\n return [(set(), repr(dict(environ)).encode())]", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def exit_signal_handler(sigcode, frame):\n logger.error(str(u\"Caught signal {}, exiting.\").format(sigcode))\n sys.exit(-sigcode)", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def increment_serial_number(\n self, serial: str, part: part.models.Part = None, **kwargs\n ) -> str:\n \"\"\"Return the next sequential serial based on the provided value.\n\n A plugin which implements this method can either return:\n\n - A string which represents the \"next\" serial number in the sequence\n - None (null value) if the next value could not be determined\n\n Arguments:\n serial: Current serial value (string)\n part: The Part instance for which this serial number is being incremented\n\n Returns:\n The next serial number in the sequence (string), or None\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:\n \"\"\"Customize behaviour of the type analyzer for given full names.\n\n This method is called during the semantic analysis pass whenever mypy sees an\n unbound type. For example, while analysing this code:\n\n from lib import Special, Other\n\n var: Special\n def func(x: Other[int]) -> None:\n ...\n\n this method will be called with 'lib.Special', and then with 'lib.Other'.\n The callback returned by plugin must return an analyzed type,\n i.e. an instance of `mypy.types.Type`.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def shell_complete(\n self, ctx: \"Context\", param: \"Parameter\", incomplete: str\n ) -> t.List[\"CompletionItem\"]:\n \"\"\"Return a list of\n :class:`~click.shell_completion.CompletionItem` objects for the\n incomplete value. Most types do not provide completions, but\n some do, and this allows custom types to provide custom\n completions as well.\n\n :param ctx: Invocation context for this command.\n :param param: The parameter that is requesting completion.\n :param incomplete: Value being completed. May be empty.\n\n .. versionadded:: 8.0\n \"\"\"\n return []", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def social_auth_user(backend, uid, user, *args, **kwargs):\n \"\"\"\n Return UserSocialAuth details.\n \"\"\"\n social_user = UserSocialAuth.get_social_auth(backend.name, uid, user)\n return {\"social_user\": social_user, \"user\": user, \"new_association\": False}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def try_enroll(self, enrollment_data, response_data, device_name=None, state=None):\n data = orjson.loads(response_data)\n client_data = ClientData(websafe_decode(data[\"response\"][\"clientDataJSON\"]))\n att_obj = base.AttestationObject(websafe_decode(data[\"response\"][\"attestationObject\"]))\n binding = self.webauthn_registration_server.register_complete(state, client_data, att_obj)\n devices = self.config.setdefault(\"devices\", [])\n devices.append(\n {\"name\": device_name or \"Security Key\", \"ts\": int(time()), \"binding\": binding}\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def query(\n selected_columns,\n query,\n snuba_params,\n equations=None,\n orderby=None,\n offset=None,\n limit=50,\n referrer=None,\n auto_fields=False,\n auto_aggregations=False,\n include_equation_fields=False,\n allow_metric_aggregates=False,\n use_aggregate_conditions=False,\n conditions=None,\n functions_acl=None,\n transform_alias_to_input_format=False,\n sample=None,\n has_metrics=False,\n use_metrics_layer=False,\n skip_tag_resolution=False,\n on_demand_metrics_enabled=False,\n on_demand_metrics_type: MetricSpecType | None = None,\n fallback_to_transactions=False,\n query_source: QuerySource | None = None,\n) -> EventsResponse:\n if not selected_columns:\n raise InvalidSearchQuery(\"No columns selected\")\n\n builder = ErrorsQueryBuilder(\n Dataset.Events,\n params={},\n snuba_params=snuba_params,\n query=query,\n selected_columns=selected_columns,\n equations=equations,\n orderby=orderby,\n limit=limit,\n offset=offset,\n sample_rate=sample,\n config=QueryBuilderConfig(\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n functions_acl=functions_acl,\n equation_config={\"auto_add\": include_equation_fields},\n has_metrics=has_metrics,\n transform_alias_to_input_format=transform_alias_to_input_format,\n skip_tag_resolution=skip_tag_resolution,\n parser_config_overrides=PARSER_CONFIG_OVERRIDES,\n ),\n )\n if conditions is not None:\n builder.add_conditions(conditions)\n result = builder.process_results(builder.run_query(referrer, query_source=query_source))\n result[\"meta\"][\"tips\"] = transform_tips(builder.tips)\n return result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def Plugins(path, **kwargs):\n\treturn PluginDescriptor(name=\"Backup/Restore\", description=\"Backup and Restore your Settings\", icon=\"backup.png\", where=PluginDescriptor.WHERE_PLUGINMENU, fnc=BackupMain)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def references_field(self, model_name, name, app_label):\n \"\"\"\n Return True if there is a chance this operation references the given\n field name, with an app label for accuracy.\n\n Used for optimization. If in doubt, return True.\n \"\"\"\n return self.references_model(model_name, app_label)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_org_redirect_url(request: HttpRequest, active_organization: RpcOrganization | None) -> str:\n from sentry import features\n\n # TODO(dcramer): deal with case when the user cannot create orgs\n if active_organization:\n return Organization.get_url(active_organization.slug)\n if not features.has(\"organizations:create\"):\n return \"/auth/login/\"\n return \"/organizations/new/\"", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def search(self, **kwargs):\n return []", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:\n \"\"\"Writes the epilog into the formatter if it exists.\"\"\"\n if self.epilog:\n epilog = inspect.cleandoc(self.epilog)\n formatter.write_paragraph()\n\n with formatter.indentation():\n formatter.write_text(epilog)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_export_only_fields(self, **kwargs) -> list:\n \"\"\"Return the list of field names which are only used during data export.\"\"\"\n return self.export_only_fields", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def redirect_view_factory(target, redirect=HTTPMovedPermanently, **kw):\n def redirect_view(request):\n redirect_to = target.format(_request=request, **request.matchdict)\n\n # Check to see if any of the characters that we can't represent in a\n # header exist in our target, if so we'll raise a BadRequest\n if set(redirect_to) & {\"\\n\", \"\\r\"}:\n raise HTTPBadRequest(\"URL may not contain control characters\")\n\n return redirect(redirect_to)\n\n return redirect_view", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def get_description(\n self,\n environ: WSGIEnvironment | None = None,\n scope: dict[str, t.Any] | None = None,\n ) -> str:\n \"\"\"Get the description.\"\"\"\n if self.description is None:\n description = \"\"\n else:\n description = self.description\n\n description = escape(description).replace(\"\\n\", Markup(\"<br>\"))\n return f\"<p>{description}</p>\"", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def plugin(version: str) -> type[DummyPlugin]:\n return DummyPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def run(\n ip_address: IPAddress, additional_oois: list[IPPort | ResolvedHostname], config: dict[str, Any]\n) -> Iterator[OOI]:\n hostnames = [resolved.hostname for resolved in additional_oois if isinstance(resolved, ResolvedHostname)]\n ip_ports = [ip_port for ip_port in additional_oois if isinstance(ip_port, IPPort)]\n\n for ip_port in ip_ports:\n if ip_port.port == 443:\n for hostname in hostnames:\n yield URL(\n network=Network(name=hostname.tokenized.network.name).reference,\n raw=f\"https://{hostname.tokenized.name}/\",\n )\n if ip_port.port == 80:\n for hostname in hostnames:\n yield URL(\n network=Network(name=hostname.tokenized.network.name).reference,\n raw=f\"http://{hostname.tokenized.name}/\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def form_view(request):\n class Form(forms.Form):\n number = forms.FloatField()\n\n template = Template(\"<html>{{ form }}</html>\")\n context = Context({\"form\": Form()})\n return HttpResponse(template.render(context))", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def send_msg(self, users, message, subject=None):\n accounts, __, __ = self.get_accounts(users)\n if not accounts:\n return\n return self.client.send_text(accounts, message)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def check_cached_url(api, project_uuid, url, etags,\n utcnow=datetime.datetime.utcnow,\n varying_url_params=\"\",\n prefer_cached_downloads=False):\n\n logger.info(\"Checking Keep for %s\", url)\n\n varying_params = [s.strip() for s in varying_url_params.split(\",\")]\n\n parsed = urllib.parse.urlparse(url)\n query = [q for q in urllib.parse.parse_qsl(parsed.query)\n if q[0] not in varying_params]\n\n clean_url = urllib.parse.urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params,\n urllib.parse.urlencode(query, safe=\"/\"), parsed.fragment))\n\n r1 = api.collections().list(filters=[[\"properties\", \"exists\", url]]).execute()\n\n if clean_url == url:\n items = r1[\"items\"]\n else:\n r2 = api.collections().list(filters=[[\"properties\", \"exists\", clean_url]]).execute()\n items = r1[\"items\"] + r2[\"items\"]\n\n now = utcnow()\n\n curldownloader = _Downloader(api)\n\n for item in items:\n properties = item[\"properties\"]\n\n if clean_url in properties:\n cache_url = clean_url\n elif url in properties:\n cache_url = url\n else:\n raise Exception(\"Shouldn't happen, got an API result for %s that doesn't have the URL in properties\" % item[\"uuid\"])\n\n if prefer_cached_downloads or _fresh_cache(cache_url, properties, now):\n # HTTP caching rules say we should use the cache\n cr = arvados.collection.CollectionReader(item[\"portable_data_hash\"], api_client=api)\n return (item[\"portable_data_hash\"], next(iter(cr.keys())), item[\"uuid\"], clean_url, now)\n\n if not _changed(cache_url, clean_url, properties, now, curldownloader):\n # Etag didn't change, same content, just update headers\n api.collections().update(uuid=item[\"uuid\"], body={\"collection\":{\"properties\": properties}}).execute()\n cr = arvados.collection.CollectionReader(item[\"portable_data_hash\"], api_client=api)\n return (item[\"portable_data_hash\"], next(iter(cr.keys())), item[\"uuid\"], clean_url, now)\n\n for etagstr in (\"Etag\", \"ETag\"):\n if etagstr in properties[cache_url] and len(properties[cache_url][etagstr]) > 2:\n etags[properties[cache_url][etagstr]] = item\n\n logger.debug(\"Found ETag values %s\", etags)\n\n return (None, None, None, clean_url, now)", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def h_descrypt(phrase, rounds, salt):\n expected = DES_CRYPT.using(\n salt=salt, truncate_error=False\n ).hash(phrase)\n setting = expected[:2]\n yield (phrase, setting, expected)", "smellKey": "S1172", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l4", "language": "python"} {"function": "def media(request):\n \"\"\"\n Add media-related context variables to the context.\n \"\"\"\n return {\"MEDIA_URL\": settings.MEDIA_URL}", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def gen_property_setter_ir(\n builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool\n) -> FuncIR:\n \"\"\"Generate an implicit trivial property setter for an attribute.\n\n These are used if an attribute can also be accessed as a property.\n \"\"\"\n name = func_decl.name\n builder.enter(name)\n self_reg = builder.add_argument(\"self\", func_decl.sig.args[0].type)\n value_reg = builder.add_argument(\"value\", func_decl.sig.args[1].type)\n assert name.startswith(PROPSET_PREFIX)\n attr_name = name[len(PROPSET_PREFIX) :]\n if not is_trait:\n builder.add(SetAttr(self_reg, attr_name, value_reg, -1))\n builder.add(Return(builder.none()))\n args, _, blocks, ret_type, fn_info = builder.leave()\n return FuncIR(func_decl, args, blocks)", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def plugin(version: str) -> type[FullyQualifiedTestPlugin]:\n return FullyQualifiedTestPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_projects_list(self, cached: bool = True):\n return self._get_stub_data(\"project_list_response.json\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def has_scope(self, scope: str) -> bool:\n return True", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def select_address_family(host: str, port: int) -> socket.AddressFamily:\n \"\"\"Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on\n the host and port.\"\"\"\n if host.startswith(\"unix://\"):\n return socket.AF_UNIX\n elif \":\" in host and hasattr(socket, \"AF_INET6\"):\n return socket.AF_INET6\n return socket.AF_INET", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def moveServiceFiles(serviceref, dest, name=None, allowCopy=True):\n\tmoveList = createMoveList(serviceref, dest)\n\ttry:\n\t\t# print(\"[MovieSelection] Moving in background.\")\n\t\tmoveList.reverse() # Start with the smaller files, do the big one later.\n\t\tif name is None:\n\t\t\tname = split(moveList[-1][0])[1]\n\t\tmoveFiles(moveList, name)\n\texcept OSError as err:\n\t\tprint(\"[MovieSelection] Error %d: Failed move! (%s)\" % (err.errno, err.strerror))\n\t\traise # Throw exception.", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def add_commit(self, *args, **kwargs):\n \"\"\"Wrap method in Housekeeper Store\"\"\"\n return True", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def tablespace_sql(self, tablespace, inline=False):\n \"\"\"\n Return the SQL that will be used in a query to define the tablespace.\n\n Return '' if the backend doesn't support tablespaces.\n\n If `inline` is True, append the SQL to a row; otherwise append it to\n the entire CREATE TABLE or CREATE INDEX statement.\n \"\"\"\n return \"\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def subscribe(self, f: Filter, last_log_id: Optional[int]=None) -> None:\n \"\"\"Subscribe to another set of events from the server\n\n Arguments:\n\n * f: arvados.events.Filter | None --- One filter to subscribe to.\n\n * last_log_id: Optional[int] --- Ignored; this argument exists for\n API compatibility with `EventClient.subscribe`.\n \"\"\"\n self.on_event({'status': 200})\n self.filters.append(f)", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str | None = None,\n zerofill_results: bool = True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n allow_metric_aggregates=False,\n has_metrics=False,\n use_metrics_layer=False,\n on_demand_metrics_enabled=False,\n on_demand_metrics_type: MetricSpecType | None = None,\n query_source: QuerySource | None = None,\n):\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n\n This function operates on the public event schema and\n virtual fields/aggregate functions for selected columns and\n conditions are supported through this function.\n\n This function is intended to only get timeseries based\n results and thus requires the `rollup` parameter.\n\n Returns a SnubaTSResult object that has been zerofilled in\n case of gaps.\n\n selected_columns (Sequence[str]) List of public aliases to fetch.\n query (str) Filter query string to create conditions from.\n params (Dict[str, str]) Filtering parameters with start, end, project_id, environment,\n rollup (int) The bucket width in seconds\n referrer (str|None) A referrer string to help locate the origin of this query.\n comparison_delta: A timedelta used to convert this into a comparison query. We make a second\n query time-shifted back by comparison_delta, and compare the results to get the % change for each\n time bucket. Requires that we only pass\n allow_metric_aggregates (bool) Ignored here, only used in metric enhanced performance\n \"\"\"\n\n with sentry_sdk.start_span(op=\"issueplatform\", name=\"timeseries.filter_transform\"):\n equations, columns = categorize_columns(selected_columns)\n base_builder = IssuePlatformTimeseriesQueryBuilder(\n Dataset.IssuePlatform,\n {},\n rollup,\n snuba_params=snuba_params,\n query=query,\n selected_columns=columns,\n equations=equations,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n has_metrics=has_metrics,\n ),\n )\n query_list = [base_builder]\n if comparison_delta:\n if len(base_builder.aggregates) != 1:\n raise InvalidSearchQuery(\"Only one column can be selected for comparison queries\")\n comp_query_params = snuba_params.copy()\n comp_query_params.start -= comparison_delta\n comp_query_params.end -= comparison_delta\n comparison_builder = IssuePlatformTimeseriesQueryBuilder(\n Dataset.IssuePlatform,\n {},\n rollup,\n snuba_params=comp_query_params,\n query=query,\n selected_columns=columns,\n equations=equations,\n )\n query_list.append(comparison_builder)\n\n query_results = bulk_snuba_queries(\n [query.get_snql_query() for query in query_list], referrer, query_source=query_source\n )\n\n with sentry_sdk.start_span(op=\"issueplatform\", name=\"timeseries.transform_results\"):\n results = []\n for snql_query, result in zip(query_list, query_results):\n results.append(\n {\n \"data\": (\n zerofill(\n result[\"data\"],\n snql_query.params.start,\n snql_query.params.end,\n rollup,\n \"time\",\n )\n if zerofill_results\n else result[\"data\"]\n ),\n \"meta\": result[\"meta\"],\n }\n )\n\n if len(results) == 2 and comparison_delta:\n col_name = base_builder.aggregates[0].alias\n # If we have two sets of results then we're doing a comparison queries. Divide the primary\n # results by the comparison results.\n for result, cmp_result in zip(results[0][\"data\"], results[1][\"data\"]):\n cmp_result_val = cmp_result.get(col_name, 0)\n result[\"comparisonCount\"] = cmp_result_val\n\n result = results[0]\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"meta\": {\n \"fields\": {\n value[\"name\"]: get_json_meta_type(\n value[\"name\"], value.get(\"type\"), base_builder\n )\n for value in result[\"meta\"]\n }\n },\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_lhs(self, compiler, connection, lhs=None):\n lhs = lhs or self.lhs\n if hasattr(lhs, \"resolve_expression\"):\n lhs = lhs.resolve_expression(compiler.query)\n sql, params = compiler.compile(lhs)\n if isinstance(lhs, Lookup):\n # Wrapped in parentheses to respect operator precedence.\n sql = f\"({sql})\"\n return sql, params", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def make_message(self, profile: Profile, parsed_msg: dict) -> BaseMessage:\n \"\"\"Deserialize a message dict into the appropriate message instance.\n\n Given a dict describing a message, this method\n returns an instance of the related message class.\n\n Args:\n parsed_msg: The parsed message\n profile: Profile\n\n Returns:\n An instance of the corresponding message class for this message\n\n Raises:\n MessageParseError: If the message doesn't specify @type\n MessageParseError: If there is no message class registered to handle\n the given type\n\n \"\"\"\n if not isinstance(parsed_msg, dict):\n raise MessageParseError(\"Expected a JSON object\")\n message_type = parsed_msg.get(\"@type\")\n\n if not message_type:\n raise MessageParseError(\"Message does not contain '@type' parameter\")\n\n if message_type.startswith(\"did:sov\"):\n warnings.warn(\n \"Received a core DIDComm protocol with the deprecated \"\n \"`did:sov:BzCbsNYhMrjHiqZDTUASHg;spec` prefix. The sending party should \"\n \"be notified that support for receiving such messages will be removed in \"\n \"a future release. Use https://didcomm.org/ instead.\",\n DeprecationWarning,\n )\n self.logger.warning(\n \"Received a core DIDComm protocol with the deprecated \"\n \"`did:sov:BzCbsNYhMrjHiqZDTUASHg;spec` prefix. The sending party should \"\n \"be notified that support for receiving such messages will be removed in \"\n \"a future release. Use https://didcomm.org/ instead.\",\n )\n\n registry: ProtocolRegistry = self.profile.inject(ProtocolRegistry)\n try:\n message_cls = registry.resolve_message_class(message_type)\n if isinstance(message_cls, DeferLoad):\n message_cls = message_cls.resolved\n except ProtocolMinorVersionNotSupported as e:\n raise MessageParseError(f\"Problem parsing message type. {e}\")\n\n if not message_cls:\n raise MessageParseError(f\"Unrecognized message type {message_type}\")\n\n try:\n instance = message_cls.deserialize(parsed_msg)\n except BaseModelError as e:\n if \"/problem-report\" in message_type:\n raise ProblemReportParseError(\"Error parsing problem report message\")\n raise MessageParseError(f\"Error deserializing message: {e}\") from e\n\n return instance", "smellKey": "S1172", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def visit_ExtensionAttribute(\n self, node: nodes.ExtensionAttribute, frame: Frame\n ) -> None:\n self.write(f\"environment.extensions[{node.identifier!r}].{node.name}\")", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_profiles_with_function(\n organization_id: int,\n project_id: int,\n function_fingerprint: int,\n snuba_params: SnubaParams,\n query: str,\n) -> ProfileIds:\n conditions = [query, f\"fingerprint:{function_fingerprint}\"]\n\n result = functions.query(\n selected_columns=[\"timestamp\", \"unique_examples()\"],\n query=\" \".join(cond for cond in conditions if cond),\n snuba_params=snuba_params,\n limit=100,\n orderby=[\"-timestamp\"],\n referrer=Referrer.API_PROFILING_FUNCTION_SCOPED_FLAMEGRAPH.value,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n transform_alias_to_input_format=True,\n )\n\n def extract_profile_ids() -> list[str]:\n max_profiles = options.get(\"profiling.flamegraph.profile-set.size\")\n profile_ids = []\n\n for i in range(5):\n for row in result[\"data\"]:\n examples = row[\"unique_examples()\"]\n if i < len(examples):\n profile_ids.append(examples[i])\n\n if len(profile_ids) >= max_profiles:\n return profile_ids\n\n return profile_ids\n\n return {\"profile_ids\": extract_profile_ids()}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def plugin(version: str) -> type[MethodSigPlugin]:\n return MethodSigPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def remove_group_from_inbox(group, action=None, user=None, referrer=None):\n try:\n group_inbox = GroupInbox.objects.get(group=group)\n group_inbox.delete()\n\n if action is GroupInboxRemoveAction.MARK_REVIEWED and user is not None:\n Activity.objects.create(\n project_id=group_inbox.group.project_id,\n group_id=group_inbox.group_id,\n type=ActivityType.MARK_REVIEWED.value,\n user_id=user.id,\n )\n record_group_history(group, GroupHistoryStatus.REVIEWED, actor=user)\n except GroupInbox.DoesNotExist:\n pass", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def translation_file_changed(sender, file_path, **kwargs):\n \"\"\"Clear the internal translations cache if a .mo file is modified.\"\"\"\n if file_path.suffix == \".mo\":\n import gettext\n\n from django.utils.translation import trans_real\n\n gettext._translations = {}\n trans_real._translations = {}\n trans_real._default = None\n trans_real._active = Local()\n return True", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_with_pagination(\n self,\n path: str,\n gen_params: Callable[..., Any],\n get_results: Callable[..., Any],\n *args: Any,\n **kwargs: Any,\n ) -> Sequence[BaseApiResponse]:\n page_size = self.page_size\n offset = 0\n output = []\n\n for i in range(self.page_number_limit):\n resp = self.get(path, params=gen_params(i, page_size))\n results = get_results(resp)\n num_results = len(results)\n\n output += results\n offset += num_results\n # if the number is lower than our page_size, we can quit\n if num_results < page_size:\n return output\n return output", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def ask_rename_model(self, old_model_state, new_model_state):\n \"\"\"Was this model really renamed?\"\"\"\n return self.defaults.get(\"ask_rename_model\", False)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def parse_file(\n self,\n filename,\n yield_non_keyword_lines=False,\n remove_quotes_arg=True,\n run_erb=True,\n variables={},\n ):\n if filename and not os.path.exists(filename):\n raise ConfigParser.Error(self, f\"Configuration file {filename} does not exist.\")\n\n self.filename = filename\n with open(filename, \"r\") as file:\n # Loop through each line of the data\n yield from self.parse_loop(\n file,\n yield_non_keyword_lines,\n remove_quotes_arg,\n os.path.getsize(file.name),\n ConfigParser.PARSING_REGEX,\n )", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [\n\t\tPluginDescriptor(name=_(\"Enable Quad PiP\"), description=\"Quad Picture in Picture\", where=[PluginDescriptor.WHERE_EXTENSIONSMENU], fnc=main),\n\t\tPluginDescriptor(where=[PluginDescriptor.WHERE_AUTOSTART], fnc=autoStart)\n\t\t]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def compression_tween_factory(handler, registry):\n def compression_tween(request):\n response = handler(request)\n\n # We use a response callback here so that it happens after all of the\n # other response callbacks are called. This is important because\n # otherwise we won't be able to check Vary headers and such that are\n # set by response callbacks.\n request.add_response_callback(_compressor)\n\n return response\n\n return compression_tween", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def flash(self, **kwargs):\n '''Download program to flash over CANopen'''\n self.ensure_output('bin')\n self.logger.info('Using Node ID %d, program number %d',\n self.downloader.node_id,\n self.downloader.program_number)\n\n self.downloader.connect()\n status = self.downloader.flash_status()\n if status == 0:\n self.downloader.swid()\n else:\n self.logger.warning('Flash status 0x{:02x}, '\n 'skipping software identification'.format(status))\n\n self.downloader.enter_pre_operational()\n\n if self.confirm_only:\n self.downloader.zephyr_confirm_program()\n self.downloader.disconnect()\n return\n\n if self.bin_file is None:\n raise ValueError('Cannot download program; bin_file is missing')\n\n self.downloader.stop_program()\n self.downloader.clear_program()\n self.downloader.download(self.bin_file)\n\n status = self.downloader.flash_status()\n if status != 0:\n raise ValueError('Program download failed: '\n 'flash status 0x{:02x}'.format(status))\n\n self.downloader.start_program()\n self.downloader.wait_for_bootup(self.timeout)\n self.downloader.swid()\n\n if self.confirm:\n self.downloader.enter_pre_operational()\n self.downloader.zephyr_confirm_program()\n\n self.downloader.disconnect()", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def get_resource_string(self, manager, resource_name):\n return self._get(self._fn(self.module_path, resource_name))", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_monitor_checkin_attachment(\n self, request: Request, project, monitor, checkin\n ) -> Response:\n if checkin.attachment_id:\n return self.download(checkin.attachment_id)\n else:\n return Response({\"detail\": \"Check-in has no attachment\"}, status=404)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def write_byte(\n self, value: int, bit_length: int = 8, logical_name: str = \"\", **kwargs\n ) -> None:\n self.write_signed_byte(value, 8, logical_name, **kwargs)", "smellKey": "S1172", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def with_parameter(request, parameter):\n return HttpResponse(\"ok\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def languages(request):\n context = {\"languages\": [code for code, _ in settings.LANGUAGES]}\n return context", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def postWidgetCreate(self, instance):\n\t\tprint(self)\n\t\tprint(self.GUI_WIDGET)\n\t\tself.instance.setValue(self.__value)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def as_sql(self, connection, lookup, template_params, sql_params):\n sql_template = self.sql_template or lookup.sql_template or self.default_template\n template_params.update({\"op\": self.op, \"func\": self.func})\n return sql_template % template_params, sql_params", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def update_user_details(backend, details, response, user=None, is_new=False, *args, **kwargs):\n \"\"\"Update user details using data from provider.\"\"\"\n if user is None:\n return\n\n changed = False # flag to track changes\n\n for name, value in details.items():\n # do not update username, it was already generated, do not update\n # configured fields if user already existed\n if not _ignore_field(name, is_new):\n if hasattr(user, name) and value and value != getattr(user, name, None):\n setattr(user, name, value)\n changed = True\n\n if changed and hasattr(user, \"save\"):\n user.save()", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def google_configure_view(\n request: HttpRequest, organization: RpcOrganization, auth_provider: RpcAuthProvider\n) -> DeferredResponse:\n config = auth_provider.config\n if config.get(\"domain\"):\n domains: list[str] | None\n domains = [config[\"domain\"]]\n else:\n domains = config.get(\"domains\")\n return DeferredResponse(\"sentry_auth_google/configure.html\", {\"domains\": domains or []})", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def empty_view(request, *args, **kwargs):\n return HttpResponse()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def resolve_expression(\n self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False\n ):\n return query.resolve_ref(self.name, allow_joins, reuse, summarize)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def process_response(self, request, response, spider):\n # Called with the response returned from the downloader.\n\n # Must either;\n # - return a Response object\n # - return a Request object\n # - or raise IgnoreRequest\n return response", "smellKey": "S1172", "smellId": null, "repo": "MTES-MCT_monitorfish", "language": "python"} {"function": "def include(self, *args, **kwargs):\n \"\"\"Call the include version function to import related assets.\"\"\"\n self._file_included = True", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def _collate_sql(self, collation, old_collation=None, table_name=None):\n return \"COLLATE \" + self.quote_name(collation) if collation else \"\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def build(self, notification_uuid: str | None = None) -> dict[str, object]:\n return self._build(\n self.content,\n self.embeds,\n self.components,\n self.flags,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def save_user(self, request, user, form, commit=True):\n \"\"\"Check if a default group is set in settings.\"\"\"\n # Create the user\n user = super().save_user(request, user, form)\n\n # Check if a default group is set in settings\n start_group = get_global_setting('SIGNUP_GROUP')\n if (\n start_group and user.groups.count() == 0\n ): # check that no group has been added through SSO group sync\n try:\n group = Group.objects.get(id=start_group)\n user.groups.add(group)\n except Group.DoesNotExist:\n logger.exception(\n 'The setting `SIGNUP_GROUP` contains an non existent group',\n start_group,\n )\n user.save()\n return user", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def from_arguments_root(\n context_owner: CoreObjectDescriptor, # noqa: ARG001\n context: VarsContextSection,\n parsed_arguments: Any,\n) -> tuple[CoreObjectDescriptor, ...]:\n if not isinstance(parsed_arguments, BaseTypedArguments):\n return ()\n\n return (_from_target_description(target_description=parsed_arguments, context=context),)", "smellKey": "S1172", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def get_meta_context(self, meta, is_public=False, platform=None):\n if not meta:\n return\n\n return {\n \"filename\": meta.get(\"filename\"),\n \"absPath\": meta.get(\"abs_path\"),\n \"module\": meta.get(\"module\"),\n \"package\": meta.get(\"package\"),\n \"platform\": meta.get(\"platform\"),\n \"instructionAddr\": meta.get(\"instruction_addr\"),\n \"symbolAddr\": meta.get(\"symbol_addr\"),\n \"function\": meta.get(\"function\"),\n \"symbol\": meta.get(\"symbol\"),\n \"context\": get_context(\n lineno=meta.get(\"lineno\"),\n context_line=meta.get(\"context_line\"),\n pre_context=meta.get(\"pre_context\"),\n post_context=meta.get(\"post_context\"),\n ),\n \"lineNo\": meta.get(\"lineno\"),\n \"colNo\": meta.get(\"colno\"),\n \"inApp\": meta.get(\"in_app\"),\n \"trust\": meta.get(\"trust\"),\n \"errors\": meta.get(\"errors\"),\n \"lock\": meta.get(\"lock\"),\n \"sourceLink\": meta.get(\"source_link\"),\n }", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def default_lib_path(\n data_dir: str, pyversion: tuple[int, int], custom_typeshed_dir: str | None\n) -> list[str]:\n \"\"\"Return default standard library search paths. Guaranteed to be normalised.\"\"\"\n\n data_dir = os.path.abspath(data_dir)\n path: list[str] = []\n\n if custom_typeshed_dir:\n custom_typeshed_dir = os.path.abspath(custom_typeshed_dir)\n typeshed_dir = os.path.join(custom_typeshed_dir, \"stdlib\")\n mypy_extensions_dir = os.path.join(custom_typeshed_dir, \"stubs\", \"mypy-extensions\")\n versions_file = os.path.join(typeshed_dir, \"VERSIONS\")\n if not os.path.isdir(typeshed_dir) or not os.path.isfile(versions_file):\n print(\n \"error: --custom-typeshed-dir does not point to a valid typeshed ({})\".format(\n custom_typeshed_dir\n )\n )\n sys.exit(2)\n else:\n auto = os.path.join(data_dir, \"stubs-auto\")\n if os.path.isdir(auto):\n data_dir = auto\n typeshed_dir = os.path.join(data_dir, \"typeshed\", \"stdlib\")\n mypy_extensions_dir = os.path.join(data_dir, \"typeshed\", \"stubs\", \"mypy-extensions\")\n path.append(typeshed_dir)\n\n # Get mypy-extensions stubs from typeshed, since we treat it as an\n # \"internal\" library, similar to typing and typing-extensions.\n path.append(mypy_extensions_dir)\n\n # Add fallback path that can be used if we have a broken installation.\n if sys.platform != \"win32\":\n path.append(\"/usr/local/lib/mypy\")\n if not path:\n print(\n \"Could not resolve typeshed subdirectories. Your mypy install is broken.\\n\"\n \"Python executable is located at {}.\\nMypy located at {}\".format(\n sys.executable, data_dir\n ),\n file=sys.stderr,\n )\n sys.exit(1)\n return path", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def plugin(version: str) -> type[FunctionSigPlugin]:\n return FunctionSigPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def handler404(request, *args, **argv):\n if request.content_type.find('application/json') > -1:\n response = JsonResponse({'error': 'Not found'}, status=404)\n else:\n response = render(request, '404.html', status=404)\n return response", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def prompt(\n string,\n text_color=None,\n background_color=None,\n font_size=None,\n font_family=None,\n details=None,\n):\n print(f\"{string}: \")\n if details:\n print(f\"Details: {details}\\n\")\n return input()", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def atomic_traffic(client, server, iters, gid_idx, port, new_send=False,\n send_op=None, receiver_val=1, sender_val=2, swap=0,\n client_wr=1, server_wr=1, **kwargs):\n \"\"\"\n Runs atomic traffic between two sides.\n :param client: Client side, clients base class is BaseTraffic\n :param server: Server side, servers base class is BaseTraffic\n :param iters: Number of traffic iterations\n :param gid_idx: Local gid index\n :param port: IB port\n :param new_send: If True use new post send API.\n :param send_op: The send_wr opcode.\n :param receiver_val: The requested value on the reciver MR.\n :param sender_val: The requested value on the sender SendWR.\n :param client_wr: Number of WR the client will post before polling all of them\n :param server_wr: Number of WR the server will post before polling all of them\n :param kwargs: General arguments (shared with other traffic functions).\n \"\"\"\n send_element_idx = 1 if new_send else 0\n if is_datagram_qp(client):\n ah_client = get_global_ah(client, gid_idx, port)\n ah_server = get_global_ah(server, gid_idx, port)\n else:\n ah_client = None\n ah_server = None\n\n for _ in range(iters):\n client.mr.write(int.to_bytes(sender_val, 1, byteorder='big') * 8, 8)\n server.mr.write(int.to_bytes(receiver_val, 1, byteorder='big') * 8, 8)\n for _ in range(client_wr):\n c_send_wr = get_atomic_send_elements(client,\n send_op,\n cmp_add=sender_val,\n swap=swap)[send_element_idx]\n if isinstance(server, XRCResources):\n c_send_wr.set_qp_type_xrc(server.srq.get_srq_num())\n send(client, c_send_wr, send_op, new_send, ah=ah_client,\n cmp_add=sender_val, swap=swap)\n poll_cq(client.cq, count=client_wr)\n validate_atomic(send_op, server, client,\n receiver_val=receiver_val + sender_val * (client_wr - 1),\n send_cmp_add=sender_val, send_swp=swap)\n server.mr.write(int.to_bytes(sender_val, 1, byteorder='big') * 8, 8)\n client.mr.write(int.to_bytes(receiver_val, 1, byteorder='big') * 8, 8)\n for _ in range(server_wr):\n s_send_wr = get_atomic_send_elements(server,\n send_op,\n cmp_add=sender_val,\n swap=swap)[send_element_idx]\n if isinstance(client, XRCResources):\n s_send_wr.set_qp_type_xrc(client.srq.get_srq_num())\n send(server, s_send_wr, send_op, new_send, ah=ah_server,\n cmp_add=sender_val, swap=swap)\n poll_cq(server.cq, count=server_wr)\n validate_atomic(send_op, client, server,\n receiver_val=receiver_val + sender_val * (server_wr - 1),\n send_cmp_add=sender_val, send_swp=swap)", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_rdma-core", "language": "python"} {"function": "def user_data(self, access_token, *args, **kwargs):\n \"\"\"Loads user data from service. Implement in subclass\"\"\"\n return {}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def computeLiteWeightCells(weights_):\n\treturn (3, 4, 5)", "smellKey": "S1172", "smellId": null, "repo": "openMSX_openMSX", "language": "python"} {"function": "def RESOURCES(scope):\n return [None]", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def debounce_update_release_health_data(organization, project_ids: list[int]):\n \"\"\"This causes a flush of snuba health data to the postgres tables once\n per minute for the given projects.\n \"\"\"\n # Figure out which projects need to get updates from the snuba.\n should_update = {}\n cache_keys = [\"debounce-health:%d\" % id for id in project_ids]\n cache_data = cache.get_many(cache_keys)\n for project_id, cache_key in zip(project_ids, cache_keys):\n if cache_data.get(cache_key) is None:\n should_update[project_id] = cache_key\n\n if not should_update:\n return\n\n projects = {p.id: p for p in Project.objects.get_many_from_cache(should_update.keys())}\n\n # This gives us updates for all release-projects which have seen new\n # health data over the last days. It will miss releases where the last\n # date is longer than what `get_changed_project_release_model_adoptions`\n # considers recent.\n project_releases = release_health.backend.get_changed_project_release_model_adoptions(\n should_update.keys()\n )\n\n # Check which we already have rows for.\n existing = set(\n ReleaseProject.objects.filter(\n project_id__in=[x[0] for x in project_releases],\n release__version__in=[x[1] for x in project_releases],\n ).values_list(\"project_id\", \"release__version\")\n )\n to_upsert = []\n for key in project_releases:\n if key not in existing:\n to_upsert.append(key)\n\n if to_upsert:\n dates = release_health.backend.get_oldest_health_data_for_releases(to_upsert)\n\n for project_id, version in to_upsert:\n project = projects.get(project_id)\n if project is None:\n # should not happen\n continue\n\n # Ignore versions that were saved with an empty string before validation was added\n if not Release.is_valid_version(version):\n continue\n\n # We might have never observed the release. This for instance can\n # happen if the release only had health data so far. For these cases\n # we want to create the release the first time we observed it on the\n # health side.\n release = Release.get_or_create(\n project=project, version=version, date_added=dates.get((project_id, version))\n )\n\n # Make sure that the release knows about this project. Like we had before\n # the project might not have been associated with this release yet.\n release.add_project(project)\n\n # Debounce updates for a minute\n cache.set_many(dict(zip(should_update.values(), [True] * len(should_update))), 60)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def query(\n selected_columns: list[str],\n query: str,\n referrer: str,\n snuba_params: SnubaParams | None = None,\n equations: list[str] | None = None,\n orderby: list[str] | None = None,\n offset: int | None = None,\n limit: int = 50,\n auto_fields: bool = False,\n auto_aggregations: bool = False,\n include_equation_fields: bool = False,\n allow_metric_aggregates: bool = False,\n use_aggregate_conditions: bool = False,\n conditions: list[Condition] | None = None,\n functions_acl: list[str] | None = None,\n transform_alias_to_input_format: bool = False,\n sample: float | None = None,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n skip_tag_resolution: bool = False,\n extra_columns: list[Column] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n fallback_to_transactions: bool = False,\n query_source: QuerySource | None = None,\n):\n builder = ProfileFunctionsMetricsQueryBuilder(\n dataset=Dataset.PerformanceMetrics,\n params={},\n snuba_params=snuba_params,\n query=query,\n selected_columns=selected_columns,\n equations=equations,\n orderby=orderby,\n limit=limit,\n offset=offset,\n sample_rate=sample,\n config=QueryBuilderConfig(\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n functions_acl=functions_acl,\n equation_config={\"auto_add\": include_equation_fields},\n has_metrics=has_metrics,\n use_metrics_layer=use_metrics_layer,\n transform_alias_to_input_format=transform_alias_to_input_format,\n skip_tag_resolution=skip_tag_resolution,\n ),\n )\n\n result = builder.process_results(builder.run_query(referrer, query_source=query_source))\n return result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def nesting_exception_view(request):\n \"\"\"\n A view that uses a nested client to call another view and then raises an\n exception.\n \"\"\"\n client = Client()\n client.get(\"/get_view/\")\n raise Exception(\"exception message\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def apply_modifiers(org, user, contacts, modifiers: list):\n \"\"\"\n Approximates mailroom applying modifiers but doesn't do dynamic group re-evaluation.\n \"\"\"\n\n for mod in modifiers:\n fields = dict()\n clear_groups = False\n\n if mod.type == \"name\":\n fields = dict(name=mod.name)\n\n if mod.type == \"language\":\n fields = dict(language=mod.language)\n\n if mod.type == \"field\":\n for c in contacts:\n update_field_locally(user, c, mod.field.key, mod.value, label=mod.field.name)\n\n elif mod.type == \"status\":\n if mod.status == \"blocked\":\n fields = dict(status=Contact.STATUS_BLOCKED)\n clear_groups = True\n elif mod.status == \"stopped\":\n fields = dict(status=Contact.STATUS_STOPPED)\n clear_groups = True\n elif mod.status == \"archived\":\n fields = dict(status=Contact.STATUS_ARCHIVED)\n clear_groups = True\n else:\n fields = dict(status=Contact.STATUS_ACTIVE)\n\n elif mod.type == \"groups\":\n add = mod.modification == \"add\"\n for contact in contacts:\n update_groups_locally(contact, [g.uuid for g in mod.groups], add=add)\n\n elif mod.type == \"urns\":\n assert len(contacts) == 1, \"should never be trying to bulk update contact URNs\"\n assert mod.modification == \"set\", \"should only be setting URNs from here\"\n\n update_urns_locally(contacts[0], mod.urns)\n\n contacts.update(modified_by=user, modified_on=timezone.now(), **fields)\n if clear_groups:\n for c in contacts:\n for g in c.user_groups.all():\n g.contacts.remove(c)", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):\n \"\"\"\n This view generates KML for the given app label, model, and field name.\n\n The field name must be that of a geographic field.\n \"\"\"\n placemarks = []\n try:\n klass = apps.get_model(label, model)\n except LookupError:\n raise Http404(\n 'You must supply a valid app label and module name. Got \"%s.%s\"'\n % (label, model)\n )\n\n if field_name:\n try:\n field = klass._meta.get_field(field_name)\n if not isinstance(field, GeometryField):\n raise FieldDoesNotExist\n except FieldDoesNotExist:\n raise Http404(\"Invalid geometry field.\")\n\n connection = connections[using]\n\n if connection.features.has_AsKML_function:\n # Database will take care of transformation.\n placemarks = klass._default_manager.using(using).annotate(kml=AsKML(field_name))\n else:\n # If the database offers no KML method, we use the `kml`\n # attribute of the lazy geometry instead.\n placemarks = []\n if connection.features.has_Transform_function:\n qs = klass._default_manager.using(using).annotate(\n **{\"%s_4326\" % field_name: Transform(field_name, 4326)}\n )\n field_name += \"_4326\"\n else:\n qs = klass._default_manager.using(using).all()\n for mod in qs:\n mod.kml = getattr(mod, field_name).kml\n placemarks.append(mod)\n\n # Getting the render function and rendering to the correct.\n if compress:\n render = render_to_kmz\n else:\n render = render_to_kml\n return render(\"gis/kml/placemarks.kml\", {\"places\": placemarks})", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def WriteOutImagesTest(datadescription, coprocessor):\n global gPipeAndViewsState\n return gPipeAndViewsState.mImagesetOnOffFilter.TestDrawImagesThisCallback(gPipeAndViewsState)", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def post_form_view(request):\n \"\"\"Return a POST form (without a token).\"\"\"\n return HttpResponse(\n content=\"\"\"\n<html>\n<body><h1>\\u00a1Unicode!<form method=\"post\"><input type=\"text\"></form></body>\n</html>\n\"\"\"\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_envelope(result, func, cargs, offset=-1):\n \"Check a function that returns an OGR Envelope by reference.\"\n return ptr_byref(cargs, offset)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def process(business: Business, filing_rec: Filing, filing: Dict):\n # pylint: disable=too-many-locals; 1 extra\n \"\"\"Process the incoming transition filing.\"\"\"\n # Extract the filing information for transition application\n if not (transition_filing := filing.get('transition')): # pylint: disable=superfluous-parens;\n raise QueueException(f'legal_filing:transition data missing from {filing_rec.id}')\n if not business:\n raise QueueException(f'Business does not exist: legal_filing:transitionApplication {filing_rec.id}')\n\n # Initial insert of the business record\n business.restriction_ind = transition_filing.get('hasProvisions')\n\n if offices := transition_filing['offices']:\n update_offices(business, offices)\n\n if parties := transition_filing.get('parties'):\n update_parties(business, parties)\n\n if share_structure := transition_filing['shareStructure']:\n shares.update_share_structure(business, share_structure)\n\n if name_translations := transition_filing.get('nameTranslations'):\n aliases.update_aliases(business, name_translations)\n\n return filing_rec", "smellKey": "S1172", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "def run(boefje_meta: BoefjeMeta) -> list[tuple[set, bytes | str]]:\n with open(FINDING_TYPE_PATH) as json_file:\n data = json.load(json_file)\n return [(set(), json.dumps(data))]", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]\n return s if n == 1 else p", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "async def process_exception(self, request, exception):\n return HttpResponse(\"Exception caught\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _sset_dict(key, ob, state):\n ob.clear()\n ob.update(state)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def rate_limited(mail_from: str, rcpt_tos: [str]) -> bool:\n # todo: re-enable rate limiting\n return False\n\n for rcpt_to in rcpt_tos:\n if is_reverse_alias(rcpt_to):\n if rate_limited_reply_phase(rcpt_to):\n return True\n else:\n # Forward phase\n address = rcpt_to # alias@SL\n if rate_limited_forward_phase(address):\n return True\n\n return False", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def from_context(\n context_owner: CoreObjectDescriptor,\n context: VarsContextSection, # noqa: ARG001\n parsed_arguments: Any, # noqa: ARG001\n) -> tuple[CoreObjectDescriptor, ...]:\n return (context_owner,)", "smellKey": "S1172", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def _repr_mimebundle_(\n self: \"ConsoleRenderable\",\n include: Sequence[str],\n exclude: Sequence[str],\n **kwargs: Any,\n ) -> Dict[str, str]:\n console = get_console()\n segments = list(console.render(self, console.options))\n html = _render_segments(segments)\n text = console._render_buffer(segments)\n data = {\"text/plain\": text, \"text/html\": html}\n if include:\n data = {k: v for (k, v) in data.items() if k in include}\n if exclude:\n data = {k: v for (k, v) in data.items() if k not in exclude}\n return data", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def get_file_from_version(self, version: Version, tags: Set[str]):\n if tags.intersection(self._missing_tags):\n return None\n return self._files[0]", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:\n self.write(node.name)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def _is_recursionerror(e):\n return True", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [PluginDescriptor(where=PluginDescriptor.WHERE_FILESCAN, needsRestart=False, fnc=filescan),\n\t\tPluginDescriptor(name=_(\"DVDPlayer\"), description=_(\"Play DVDs\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=menu)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def switchToTV(self, *val):\n\t\tif self.msgVisible:\n\t\t\tif self.msgBox:\n\t\t\t\tself.msgBox.close() # ... MsgBoxClosed -> switchToTV again..\n\t\t\t\treturn\n\t\t\tself.avswitch.setInput(\"encoder\")\n\t\t\tself.msgVisible = False\n\t\tif self.notificationVisible:\n\t\t\tself.avswitch.setInput(\"encoder\")\n\t\t\tself.notificationVisible = False\n\t\t\tfor notification in Tools.Notifications.current_notifications:\n\t\t\t\ttry:\n\t\t\t\t\tif notification[1].msgBoxID == \"scart_msgbox\":\n\t\t\t\t\t\tnotification[1].close()\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"other notification is open. try another one.\")", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def fetch_returned_insert_columns(self, cursor, returning_params):\n \"\"\"\n Given a cursor object that has just performed an INSERT...RETURNING\n statement into a table, return the newly created data.\n \"\"\"\n return cursor.fetchone()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:\n \"\"\"The sandboxed environment will call this method to check if the\n attribute of an object is safe to access. Per default all attributes\n starting with an underscore are considered private as well as the\n special attributes of internal python objects as returned by the\n :func:`is_internal_attribute` function.\n \"\"\"\n return not (attr.startswith(\"_\") or is_internal_attribute(obj, attr))", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def update_last_login(sender, user, **kwargs):\n \"\"\"\n A signal receiver which updates the last_login date for\n the user logging in.\n \"\"\"\n user.last_login = timezone.now()\n user.save(update_fields=[\"last_login\"])", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def process_item(self, item, spider):\n return item", "smellKey": "S1172", "smellId": null, "repo": "MTES-MCT_monitorfish", "language": "python"} {"function": "def check_middleware(app_configs, **kwargs):\n errors = []\n\n login_required_index = _subclass_index(\n \"django.contrib.auth.middleware.LoginRequiredMiddleware\",\n settings.MIDDLEWARE,\n )\n\n if login_required_index != -1:\n auth_index = _subclass_index(\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n settings.MIDDLEWARE,\n )\n if auth_index == -1 or auth_index > login_required_index:\n errors.append(\n checks.Error(\n \"In order to use django.contrib.auth.middleware.\"\n \"LoginRequiredMiddleware, django.contrib.auth.middleware.\"\n \"AuthenticationMiddleware must be defined before it in MIDDLEWARE.\",\n id=\"auth.E013\",\n )\n )\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\" and ownership != \"None\":\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def publisher_url(self, claims: SignedClaims | None = None) -> str:\n return self.publisher_base_url", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def model_view(request):\n people = Person.objects.all()\n return HttpResponse(\"\\n\".join(person.name for person in people))", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _detect_transaction_change_points(\n transactions: list[tuple[int, str | int]], start: datetime, *args, **kwargs\n) -> None:\n if not options.get(\"statistical_detectors.enable\"):\n return\n\n EndpointRegressionDetector.configure_tags()\n\n projects_by_id = {\n project.id: project\n for project in get_detector_enabled_projects(\n [project_id for project_id, _ in transactions],\n )\n }\n\n transaction_pairs: list[tuple[Project, int | str]] = [\n (projects_by_id[item[0]], item[1]) for item in transactions if item[0] in projects_by_id\n ]\n\n regressions = EndpointRegressionDetector.detect_regressions(\n transaction_pairs, start, \"p95(transaction.duration)\", TIMESERIES_PER_BATCH\n )\n regressions = EndpointRegressionDetector.save_regressions_with_versions(regressions)\n\n breakpoint_count = 0\n\n for regression in regressions:\n breakpoint_count += 1\n send_regression_to_platform(regression)\n\n metrics.incr(\n \"statistical_detectors.breakpoint.emitted\",\n amount=breakpoint_count,\n tags={\"source\": \"transaction\", \"kind\": \"endpoint\"},\n sample_rate=1.0,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def update(\n self, verified=None, subscribed=None, subscribed_date=None, unsubscribed_date=None, **kwargs\n ):\n if verified is not None:\n self.verified = verified\n if subscribed is not None:\n self.subscribed = subscribed\n if subscribed_date is not None:\n self.subscribed_date = subscribed_date\n elif subscribed:\n self.subscribed_date = timezone.now()\n if unsubscribed_date is not None:\n self.unsubscribed_date = unsubscribed_date\n elif subscribed is False:\n self.unsubscribed_date = timezone.now()", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_owner_details(group_list: list[Group], user: Any) -> dict[int, list[OwnersSerialized]]:\n group_ids = [g.id for g in group_list]\n group_owners = GroupOwner.objects.filter(group__in=group_ids).exclude(\n user_id__isnull=True, team_id__isnull=True\n )\n owner_details = defaultdict(list)\n for go in group_owners:\n owner_details[go.group_id].append(\n OwnersSerialized(\n type=GROUP_OWNER_TYPE[GroupOwnerType(go.type)],\n owner=go.owner().identifier,\n date_added=go.date_added,\n ),\n )\n\n return owner_details", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def query_transactions_timeseries(\n transactions: list[tuple[Project, int | str]],\n start: datetime,\n agg_function: str,\n) -> Generator[tuple[int, int | str, SnubaTSResult]]:\n end = start.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)\n days_to_query = options.get(\"statistical_detectors.query.transactions.timeseries_days\")\n start = end - timedelta(days=days_to_query)\n use_case_id = UseCaseID.TRANSACTIONS\n interval = 3600 # 1 hour\n\n project_objects = {p for p, _ in transactions}\n project_ids = [project.id for project in project_objects]\n org_ids = list({project.organization_id for project in project_objects})\n # The only tag available on DURATION_LIGHT is `transaction`: as long as\n # we don't filter on any other tags, DURATION_LIGHT's lower cardinality\n # will be faster to query.\n duration_metric_id = indexer.resolve(\n use_case_id, org_ids[0], str(TransactionMRI.DURATION_LIGHT.value)\n )\n transaction_name_metric_id = indexer.resolve(\n use_case_id,\n org_ids[0],\n \"transaction\",\n )\n\n transactions_condition = None\n if len(transactions) == 1:\n project, transaction_name = transactions[0]\n transactions_condition = BooleanCondition(\n BooleanOp.AND,\n [\n Condition(Column(\"project_id\"), Op.EQ, project.id),\n Condition(Column(\"transaction\"), Op.EQ, transaction_name),\n ],\n )\n else:\n transactions_condition = BooleanCondition(\n BooleanOp.OR,\n [\n BooleanCondition(\n BooleanOp.AND,\n [\n Condition(Column(\"project_id\"), Op.EQ, project.id),\n Condition(Column(\"transaction\"), Op.EQ, transaction_name),\n ],\n )\n for project, transaction_name in transactions\n ],\n )\n\n query = Query(\n match=Entity(EntityKey.GenericMetricsDistributions.value),\n select=[\n Column(\"project_id\"),\n Function(\n \"arrayElement\",\n (\n CurriedFunction(\n \"quantilesIf\",\n [0.95],\n (\n Column(\"value\"),\n Function(\"equals\", (Column(\"metric_id\"), duration_metric_id)),\n ),\n ),\n 1,\n ),\n \"p95_transaction_duration\",\n ),\n Function(\n \"transform\",\n (\n Column(f\"tags_raw[{transaction_name_metric_id}]\"),\n Function(\"array\", (\"\",)),\n Function(\"array\", (\"<< unparameterized >>\",)),\n ),\n \"transaction\",\n ),\n ],\n groupby=[\n Column(\"transaction\"),\n Column(\"project_id\"),\n Function(\n \"toStartOfInterval\",\n (Column(\"timestamp\"), Function(\"toIntervalSecond\", (3600,)), \"Universal\"),\n \"time\",\n ),\n ],\n where=[\n Condition(Column(\"org_id\"), Op.IN, list(org_ids)),\n Condition(Column(\"project_id\"), Op.IN, list(project_ids)),\n Condition(Column(\"timestamp\"), Op.GTE, start),\n Condition(Column(\"timestamp\"), Op.LT, end),\n Condition(Column(\"metric_id\"), Op.EQ, duration_metric_id),\n transactions_condition,\n ],\n orderby=[\n OrderBy(Column(\"project_id\"), Direction.ASC),\n OrderBy(Column(\"transaction\"), Direction.ASC),\n OrderBy(\n Function(\n \"toStartOfInterval\",\n (Column(\"timestamp\"), Function(\"toIntervalSecond\", (3600,)), \"Universal\"),\n \"time\",\n ),\n Direction.ASC,\n ),\n ],\n granularity=Granularity(interval),\n limit=Limit(10000),\n )\n request = Request(\n dataset=Dataset.PerformanceMetrics.value,\n app_id=\"statistical_detectors\",\n query=query,\n tenant_ids={\n \"referrer\": Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value,\n \"cross_org_query\": 1,\n \"use_case_id\": use_case_id.value,\n },\n )\n data = raw_snql_query(\n request, referrer=Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value\n )[\"data\"]\n\n results = {}\n for index, datapoint in enumerate(data or []):\n key = (datapoint[\"project_id\"], datapoint[\"transaction\"])\n if key not in results:\n results[key] = {\n \"data\": [datapoint],\n }\n else:\n data = results[key][\"data\"]\n data.append(datapoint)\n\n for key, item in results.items():\n project_id, transaction_name = key\n formatted_result = SnubaTSResult(\n {\n \"data\": zerofill(\n item[\"data\"],\n start,\n end,\n interval,\n [\"time\"],\n ),\n \"project\": project_id,\n },\n start,\n end,\n interval,\n )\n yield project_id, transaction_name, formatted_result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def remove(self, item):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def create_contenttypes(\n app_config,\n verbosity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n \"\"\"\n Create content types for models in the given app.\n \"\"\"\n if not app_config.models_module:\n return\n\n app_label = app_config.label\n try:\n app_config = apps.get_app_config(app_label)\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n except LookupError:\n return\n\n content_types, app_models = get_contenttypes_and_models(\n app_config, using, ContentType\n )\n\n if not app_models:\n return\n\n cts = [\n ContentType(\n app_label=app_label,\n model=model_name,\n )\n for (model_name, model) in app_models.items()\n if model_name not in content_types\n ]\n ContentType.objects.using(using).bulk_create(cts)\n if verbosity >= 2:\n for ct in cts:\n print(\"Adding content type '%s | %s'\" % (ct.app_label, ct.model))", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _sleep(self, driver: webdriver.Chrome, target: str):\n try:\n sleep_time = int(target)\n except Exception as e:\n # at least sleep 1 second\n sleep_time = 1\n time.sleep(sleep_time)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def metadata_isdir(self, name: str) -> bool:\n return False", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def wait_check(*args, type=\"CONVERTED\", scope=OPENC3_SCOPE):\n \"\"\"Wait for the converted value of a telmetry item against a condition or for a timeout\n and then check against the condition\n Supports two signatures:\n wait_check(target_name, packet_name, item_name, comparison_to_eval, timeout, polling_rate)\n or\n wait_check('target_name packet_name item_name > 1', timeout, polling_rate)\"\"\"\n (\n target_name,\n packet_name,\n item_name,\n comparison_to_eval,\n timeout,\n polling_rate,\n ) = _wait_check_process_args(args)\n start_time = time.time()\n success, value = _openc3_script_wait_value(\n target_name,\n packet_name,\n item_name,\n type,\n comparison_to_eval,\n timeout,\n polling_rate,\n )\n if isinstance(value, str):\n value = f\"'{value}'\" # Show user the check against a quoted string\n time_diff = time.time() - start_time\n check_str = f\"CHECK: {_upcase(target_name, packet_name, item_name)}\"\n if comparison_to_eval:\n check_str += f\" {comparison_to_eval}\"\n with_value_str = f\"with value == {value} after waiting {time_diff:.3f} seconds\"\n if success:\n print(f\"{check_str} success {with_value_str}\")\n else:\n message = f\"{check_str} failed {with_value_str}\"\n raise CheckError(message)\n return time_diff", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def load_ipython_extension(ip: Any) -> None: # pragma: no cover\n # prevent circular import\n from pip._vendor.rich.pretty import install\n from pip._vendor.rich.traceback import install as tr_install\n\n install()\n tr_install()", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def npgettext(c: str, s: str, p: str, n: int) -> str:\n return s if n == 1 else p", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def optgroups(self, name, value, attr=None):\n \"\"\"Return selected options based on the ModelChoiceIterator.\"\"\"\n default = (None, [], 0)\n groups = [default]\n has_selected = False\n selected_choices = {\n str(v) for v in value if str(v) not in self.choices.field.empty_values\n }\n if not self.is_required and not self.allow_multiple_selected:\n default[1].append(self.create_option(name, \"\", \"\", False, 0))\n remote_model_opts = self.field.remote_field.model._meta\n to_field_name = getattr(\n self.field.remote_field, \"field_name\", remote_model_opts.pk.attname\n )\n to_field_name = remote_model_opts.get_field(to_field_name).attname\n choices = (\n (getattr(obj, to_field_name), self.choices.field.label_from_instance(obj))\n for obj in self.choices.queryset.using(self.db).filter(\n **{\"%s__in\" % to_field_name: selected_choices}\n )\n )\n for option_value, option_label in choices:\n selected = str(option_value) in value and (\n has_selected is False or self.allow_multiple_selected\n )\n has_selected |= selected\n index = len(default[1])\n subgroup = default[1]\n subgroup.append(\n self.create_option(\n name, option_value, option_label, selected_choices, index\n )\n )\n return groups", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def analyses(self, *args, **kwargs) -> list:\n return self.analyses_response", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def lookup_cast(self, lookup_type, internal_type=None):\n \"\"\"\n Return the string to use in a query when performing lookups\n (\"contains\", \"like\", etc.). It should contain a '%s' placeholder for\n the column being searched against.\n \"\"\"\n return \"%s\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def validate(self, password, user=None):\n digest = sha1(password.encode(\"utf-8\")).hexdigest().upper()\n prefix = digest[:5]\n suffix = digest[5:]\n\n url = f\"https://api.pwnedpasswords.com/range/{prefix}\"\n headers = {\n \"User-Agent\": \"Sentry @ {}\".format(options.get(\"system.url-prefix\")),\n }\n\n try:\n r = requests.get(url, headers=headers, timeout=self.timeout)\n except Exception as e:\n logger.warning(\n \"Unable to fetch PwnedPasswords API\",\n extra={\n \"exception\": str(e),\n \"prefix\": prefix,\n },\n )\n return\n\n for line in r.text.split(\"\\n\"):\n if \":\" not in line:\n continue\n\n breached_suffix, occurrences = line.rstrip().split(\":\")\n if breached_suffix == suffix:\n if int(occurrences) >= self.threshold:\n raise ValidationError(\n f\"This password has previously appeared in data breaches {occurrences} times.\"\n )\n break", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def Plugins(**kwargs):\n\tfrom Tools.StbHardware import getFPVersion\n\n\tversion = getFPVersion()\n\tnewversion = getUpgradeVersion() or 0\n\tlist = []\n\tif version is not None and version < newversion:\n\t\tlist.append(PluginDescriptor(name=_(\"FP Upgrade\"), where=PluginDescriptor.WHERE_WIZARD, needsRestart=True, fnc=(8, FPUpgrade)))\n\n\ttry:\n\t\tmsg = open(\"/proc/stb/message\").read()\n\t\tlist.append(PluginDescriptor(name=_(\"System Message Check\"), where=PluginDescriptor.WHERE_WIZARD, needsRestart=True, fnc=(9, SystemMessage, msg)))\n\texcept:\n\t\tpass\n\n\treturn list", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def create_owner(organization: Organization, user: User, role: str | None = None) -> None:\n create_member(organization, user, roles.get_top_dog().id)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def remember(self, request, userid, **kw):\n # This is a NO-OP because our Macaroon header policy doesn't allow\n # the ability for authentication to \"remember\" the user id. This\n # assumes it has been configured in clients somewhere out of band.\n return []", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def top_events_timeseries(\n timeseries_columns: list[str],\n selected_columns: list[str],\n user_query: str,\n snuba_params: SnubaParams,\n orderby: list[str],\n rollup: int,\n limit: int,\n organization: Organization,\n equations: list[str] | None = None,\n referrer: str | None = None,\n top_events: EventsResponse | None = None,\n allow_empty: bool = True,\n zerofill_results: bool = True,\n include_other: bool = False,\n functions_acl: list[str] | None = None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n query_source: QuerySource | None = None,\n):\n \"\"\"\n High-level API for doing arbitrary user timeseries queries for a limited number of top events\n\n this API should match that of sentry.snuba.discover.top_events_timeseries\n \"\"\"\n if top_events is None:\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"top_events.fetch_events\"):\n top_events = query(\n selected_columns,\n query=user_query,\n snuba_params=snuba_params,\n equations=equations,\n orderby=orderby,\n limit=limit,\n referrer=referrer,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n include_equation_fields=True,\n skip_tag_resolution=True,\n query_source=query_source,\n )\n\n top_events_builder = TopEventsSpanEAPQueryBuilder(\n Dataset.EventsAnalyticsPlatform,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=False,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n equations=equations,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n skip_tag_resolution=True,\n ),\n )\n if len(top_events[\"data\"]) == limit and include_other:\n other_events_builder = TopEventsSpanEAPQueryBuilder(\n Dataset.EventsAnalyticsPlatform,\n {},\n rollup,\n top_events[\"data\"],\n snuba_params=snuba_params,\n other=True,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n equations=equations,\n )\n result, other_result = bulk_snuba_queries(\n [top_events_builder.get_snql_query(), other_events_builder.get_snql_query()],\n referrer=referrer,\n query_source=query_source,\n )\n else:\n result = top_events_builder.run_query(referrer)\n other_result = {\"data\": []}\n if (\n not allow_empty\n and not len(result.get(\"data\", []))\n and not len(other_result.get(\"data\", []))\n ):\n return SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n [], snuba_params.start_date, snuba_params.end_date, rollup, [\"time\"]\n )\n if zerofill_results\n else []\n ),\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"top_events.transform_results\") as span:\n span.set_data(\"result_count\", len(result.get(\"data\", [])))\n result = top_events_builder.process_results(result)\n\n issues: Mapping[int, str | None] = {}\n translated_groupby = top_events_builder.translated_groupby\n\n results = (\n {discover.OTHER_KEY: {\"order\": limit, \"data\": other_result[\"data\"]}}\n if len(other_result.get(\"data\", []))\n else {}\n )\n # Using the top events add the order to the results\n for index, item in enumerate(top_events[\"data\"]):\n result_key = discover.create_result_key(item, translated_groupby, issues)\n results[result_key] = {\"order\": index, \"data\": []}\n for row in result[\"data\"]:\n result_key = discover.create_result_key(row, translated_groupby, issues)\n if result_key in results:\n results[result_key][\"data\"].append(row)\n else:\n logger.warning(\n \"spans_indexed.top-events.timeseries.key-mismatch\",\n extra={\"result_key\": result_key, \"top_event_keys\": list(results.keys())},\n )\n top_events_results: dict[str, SnubaTSResult] = {}\n for key, result_item in results.items():\n top_events_results[key] = SnubaTSResult(\n {\n \"data\": (\n discover.zerofill(\n result_item[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else result_item[\"data\"]\n ),\n \"order\": result_item[\"order\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )\n\n return top_events_results", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_exception(self, request, exception):\n log.append(\"process-exception\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def jwt_identifier_exists(self, jti: str) -> bool:\n \"\"\"\n The NullOIDCPublisherService does not provide a mechanism to store used tokens\n before their expiration.\n \"\"\"\n return False", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def create_new_procedures(apps, schema_editor):\n h.run_sql_files([\n '0122_index_custom_text.sql',\n '0122_index_facilities.sql',\n '0122_index_facilities_by.sql',\n ])", "smellKey": "S1172", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def get_language_from_request(request, check_path=False):\n return settings.LANGUAGE_CODE", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def Plugins(**kwargs):\n\tdescr = _(\"Burn to medium\")\n\treturn [PluginDescriptor(name=_(\"DVD Burn\"), description=descr, where=PluginDescriptor.WHERE_MOVIELIST, needsRestart=True, fnc=main_add, icon=\"dvdburn.png\"),\n\t\tPluginDescriptor(name=_(\"DVD Burn\"), description=descr, where=PluginDescriptor.WHERE_PLUGINMENU, needsRestart=True, fnc=main, icon=\"dvdburn.png\")]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def SetUpOneParaViewRepresentationAndViewC(inCameraC, inLookDirection,\n inImagesetInfo,\n inColorSettingsX,\n inMeshRenderControl,\n inShowDataCubeAxes, inShowDataCubeAxesInfo, inShowOrientationAxes,\n inFixedColorRange,\n inIsPlotFlag,\n inViewBounds = None,\n inRepresentationFilenameAddon = \"\",\n inLookDirectionFilenameAddon = \"\",\n inPhactoriRepresentation = None):\n\n global gRenderingEnabled\n if gRenderingEnabled == False:\n if PhactoriDbg():\n myDebugPrint3(\"SetUpOneParaViewRepresentationAndViewC returning with noop because rendering is disabled\\n\")\n return\n\n inImageSettings = inImagesetInfo.mImageSettings\n lclImageSize = inImageSettings.mImageSize\n lclImageFormat = inImageSettings.mImageFormat\n inImageBasename = inImageSettings.mImageBasename\n inImageBasedirectory = inImageSettings.mImageBasedirectory\n inNumCounterDigits = inImageSettings.mNumCounterDigits\n\n #myDebugPrint3('inCameraC: ' + str(inCameraC) + '\\n')\n #myDebugPrint3('inLookDirection: ' + str(inLookDirection) + '\\n')\n #myDebugPrint3('inImageBasename: ' + str(inImageBasename) + '\\n')\n #myDebugPrint3('inImageBasedirectory: ' + str(inImageBasedirectory) + '\\n')\n #myDebugPrint3('inNumCounterDigits: ' + str(inNumCounterDigits) + '\\n')\n #myDebugPrint3('lclImageFormat: ' + str(lclImageFormat) + '\\n')\n #myDebugPrint3('lclImageSize: ' + str(lclImageSize) + '\\n')\n #myDebugPrint3('inMeshRenderControl: ' + str(inMeshRenderControl) + '\\n')\n #myDebugPrint3('inShowDataCubeAxes: ' + str(inShowDataCubeAxes) + '\\n')\n #myDebugPrint3('inShowOrientationAxes: ' + str(inShowOrientationAxes) + '\\n')\n #myDebugPrint3('inViewBounds: ' + str(inViewBounds) + '\\n')\n #myDebugPrint3('inRepresentationFilenameAddon: ' + str(inRepresentationFilenameAddon) + '\\n')\n #myDebugPrint3('inLookDirectionFilenameAddon: ' + str(inLookDirectionFilenameAddon) + '\\n')\n\n\n #need to handle absolute and error\n\n nameSuffix = inRepresentationFilenameAddon + inCameraC.mFilenameAddon + inLookDirectionFilenameAddon\n\n if inImageBasedirectory == None:\n fileBaseName = inImageBasename + nameSuffix\n elif inImageBasedirectory == \"\":\n fileBaseName = inImageBasename + nameSuffix\n else:\n import os\n fileBaseName = inImageBasedirectory + os.sep + inImageBasename + nameSuffix\n\n AddRenderView(inPhactoriImagesetInfo = inImagesetInfo,\n inColorSettings = inColorSettingsX,\n ImageBaseFileName = fileBaseName, ImageType = lclImageFormat,\n ImageOverwriteFlag = False,\n PixelSizeX = lclImageSize[0], PixelSizeY = lclImageSize[1],\n numCounterDigits = inNumCounterDigits,\n inIsPlotFlag = inIsPlotFlag)\n\n if inIsPlotFlag == False:\n SetParaViewRepresentationCameraParams(inImagesetInfo.mSharedPvRenderView2,\n inCameraC, inLookDirection, inImageSettings, GetActiveSource())\n SetForCorrectColorBy(inImagesetInfo,\n inImagesetInfo.GetInputPhactoriOperation(),\n inImagesetInfo.mPvDataRepresentation2, inPhactoriRepresentation, True)\n\n inImagesetInfo.mPvDataRepresentation2.Representation = inMeshRenderControl\n if(inShowOrientationAxes):\n inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 1\n else:\n inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 0\n\n UpdateRepresentationColorBy(inImagesetInfo)\n #if inShowColorLegend:\n # if PhactoriDbg():\n # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend on\\n')\n # ShowDataColorLegendXX(inImagesetInfo, 'on',\n # inColorLegendPositionAndSize, inColorSettingsX)\n #else:\n # if PhactoriDbg():\n # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend off\\n')\n # ShowDataColorLegendXX(inImagesetInfo, 'off',\n # inColorLegendPositionAndSize, inColorSettingsX)\n\n if inShowDataCubeAxes:\n ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'on', inShowDataCubeAxesInfo)\n else:\n ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'off')", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def db_for_read(self, model, instance=None, **hints):\n if instance:\n return instance._state.db or \"other\"\n return \"other\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def meta_tags(self, request: Request, **kwargs):\n return {}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def run(input_ooi: Network, additional_oois: list, config: dict[str, Any]) -> Iterator[OOI]:\n network = input_ooi\n\n with (Path(__file__).parent / \"question_schema.json\").open() as f:\n schema = json.load(f)\n\n yield Question(ooi=network.reference, schema_id=schema[\"$id\"], json_schema=json.dumps(schema))", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def lookup_member_var_or_accessor(info: TypeInfo, name: str, is_lvalue: bool) -> SymbolNode | None:\n \"\"\"Find the attribute/accessor node that refers to a member of a type.\"\"\"\n # TODO handle lvalues\n node = info.get(name)\n if node:\n return node.node\n else:\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def last_executed_query(self, cursor, sql, params):\n # https://www.psycopg.org/docs/cursor.html#cursor.query\n # The query attribute is a Psycopg extension to the DB API 2.0.\n if cursor.query is not None:\n return cursor.query.decode()\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def db_type(self, connection: BaseDatabaseWrapper) -> str:\n return \"text\"", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def associate_by_email(details, user=None, *args, **kwargs):\n \"\"\"Return user entry with same email address as one returned on details.\"\"\"\n if user:\n return None\n\n email = details.get(\"email\")\n\n if email:\n # Try to associate accounts registered with the same email address,\n # only if it's a single object. AuthException is raised if multiple\n # objects are returned.\n try:\n return {\"user\": UserSocialAuth.get_user_by_email(email=email)}\n except MultipleObjectsReturned:\n raise AuthException(kwargs[\"backend\"], \"Not unique email address.\")\n except ObjectDoesNotExist:\n pass", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def update(self, **kwargs):\n return True", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def create(self, **kwargs):\n return MockTwilioClient.MockApplication(\"temba.io/1234\")", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def from_db_value(self, value, expression, connection, context=None):\n if value is None:\n return value\n return self.json_decode(value)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def lookupEventTime(self, ref, query):\n\t\treturn None", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def update(self, select=None):\n was_selected = self.selected()\n self.ell.remove_all()\n self.names, self.mapping = get_sectionlists()\n self.names = [\"No Sections\", \"All Sections\"] + self.names\n for name in self.names:\n self._append(name)\n # restore selection if possible\n if was_selected is None:\n self.ell.select(-1)\n else:\n self.select(was_selected)", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def get_field_type(self, connection, table_name, row):\n \"\"\"\n Given the database connection, the table name, and the cursor row\n description, this routine will return the given field type name, as\n well as any additional keyword parameters and notes for the field.\n \"\"\"\n field_params = {}\n field_notes = []\n\n try:\n field_type = connection.introspection.get_field_type(row.type_code, row)\n except KeyError:\n field_type = \"TextField\"\n field_notes.append(\"This field type is a guess.\")\n\n # Add max_length for all CharFields.\n if field_type == \"CharField\" and row.display_size:\n if (size := int(row.display_size)) and size > 0:\n field_params[\"max_length\"] = size\n\n if field_type in {\"CharField\", \"TextField\"} and row.collation:\n field_params[\"db_collation\"] = row.collation\n\n if field_type == \"DecimalField\":\n if row.precision is None or row.scale is None:\n field_notes.append(\n \"max_digits and decimal_places have been guessed, as this \"\n \"database handles decimal fields as float\"\n )\n field_params[\"max_digits\"] = (\n row.precision if row.precision is not None else 10\n )\n field_params[\"decimal_places\"] = (\n row.scale if row.scale is not None else 5\n )\n else:\n field_params[\"max_digits\"] = row.precision\n field_params[\"decimal_places\"] = row.scale\n\n return field_type, field_params, field_notes", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def process_view(self, *args, **kwargs):\n def stream():\n yield reverse(\"inner\")\n\n return StreamingHttpResponse(stream())", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _set_instance_attribute(self, name, content):\n setattr(self.instance, self.field.attname, name)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def getInfoString(self, serviceref, w):\n\t\treturn ''", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_repository_data(self, organization, config):\n \"\"\"\n Gets the necessary repository data through the integration's API\n \"\"\"\n return config", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_customize_class_mro_hook(\n self, fullname: str\n ) -> Callable[[ClassDefContext], None] | None:\n \"\"\"Customize MRO for given classes.\n\n The plugin can modify the class MRO _in place_. This method is called\n with the class full name before its body was semantically analyzed.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def setlistdefault(self, key, default_list=None):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def _loads_v1(\n self,\n request: PreparedRequest,\n data: bytes,\n body_file: IO[bytes] | None = None,\n ) -> HTTPResponse | None:\n # The \"v1\" pickled cache format. This is no longer supported\n # for security reasons, so we treat it as a miss.\n return None", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_user_detail(self, user_id, **kwargs):\n # https://open.dingtalk.com/document/orgapp/query-user-details\n data = self._request.post(\n URL.GET_USER_INFO_BY_USER_ID, json={'userid': user_id}, with_token=True\n )\n data = data['result']\n data['user_id'] = user_id\n info = flatten_dict(data)\n default_detail = self.default_user_detail(data, user_id)\n detail = map_attributes(default_detail, info, self.attributes)\n return detail", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def resolve_expression_parameter(self, compiler, connection, sql, param):\n params = [param]\n if hasattr(param, \"resolve_expression\"):\n param = param.resolve_expression(compiler.query)\n if hasattr(param, \"as_sql\"):\n sql, params = compiler.compile(param)\n return sql, params", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "async def process_view(self, request, view_func, view_args, view_kwargs):\n return HttpResponse(\"Processed view %s\" % view_func.__name__)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def headers(self, **kwargs):\n return {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Token {self.secret}\",\n }", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def oauth_request(self, token, url, extra_params=None, method=\"GET\"):\n \"\"\"Generate OAuth request, setups callback url\"\"\"\n return self.request(url, auth=self.oauth_auth(token))", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn getPlugins()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def extra_data(self, user, uid, response, details):\n \"\"\"Return default blank user extra data\"\"\"\n return {}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def allow_migrate(self, db, app_label, model_name=None, **hints):\n \"\"\"\n The Tribble model should be the only one to appear in the 'other' db.\n \"\"\"\n if model_name == \"tribble\":\n return db == \"other\"\n elif db != \"default\":\n return False", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def django_db_all(func=None, *, transaction=None, reset_sequences=None, **kwargs):\n \"\"\"Pytest decorator for resetting all databases\"\"\"\n\n if func is not None:\n return pytest.mark.django_db(\n transaction=transaction, reset_sequences=reset_sequences, databases=\"__all__\"\n )(func)\n\n def decorator(function):\n return pytest.mark.django_db(\n transaction=transaction, reset_sequences=reset_sequences, databases=\"__all__\"\n )(function)\n\n return decorator", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def read(self, bytes):\n s = self.source.readline()\n self.lineno += 1\n return s", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "async def async_get_view(request):\n return HttpResponse(b\"GET content.\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def delete_file(file_blob_model, path, checksum, **kwargs):\n from sentry.models.files.utils import get_storage\n\n # check that the fileblob with *this* path exists, as its possible\n # that a concurrent re-upload added the same chunk once again, with a\n # different path that time\n if not file_blob_model.objects.filter(checksum=checksum, path=path).exists():\n get_storage().delete(path)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def as_sql(self, compiler=None, connection=None):\n sqls = [\"(%s)\" % sql for sql in self.sqls]\n return \" AND \".join(sqls), list(self.params or ())", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def referrer_policy_tween_factory(handler, registry):\n def referrer_policy_tween(request):\n response = handler(request)\n\n response.headers[\"Referrer-Policy\"] = \"origin-when-cross-origin\"\n\n return response\n\n return referrer_policy_tween", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def _detect_function_change_points(\n functions_list: list[tuple[int, int]], start: datetime, *args, **kwargs\n) -> None:\n if not options.get(\"statistical_detectors.enable\"):\n return\n\n FunctionRegressionDetector.configure_tags()\n\n projects_by_id = {\n project.id: project\n for project in get_detector_enabled_projects(\n [project_id for project_id, _ in functions_list],\n )\n }\n\n function_pairs: list[tuple[Project, int | str]] = [\n (projects_by_id[item[0]], item[1]) for item in functions_list if item[0] in projects_by_id\n ]\n\n regressions = FunctionRegressionDetector.detect_regressions(\n function_pairs, start, \"p95()\", TIMESERIES_PER_BATCH\n )\n regressions = FunctionRegressionDetector.save_regressions_with_versions(regressions)\n\n breakpoint_count = 0\n emitted_count = 0\n\n for regression_chunk in chunked(regressions, 100):\n breakpoint_count += len(regression_chunk)\n emitted_count += emit_function_regression_issue(projects_by_id, regression_chunk, start)\n\n metrics.incr(\n \"statistical_detectors.breakpoint.detected\",\n amount=breakpoint_count,\n tags={\"source\": \"profile\", \"kind\": \"function\"},\n sample_rate=1.0,\n )\n\n metrics.incr(\n \"statistical_detectors.breakpoint.emitted\",\n amount=emitted_count,\n tags={\"source\": \"profile\", \"kind\": \"function\"},\n sample_rate=1.0,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def evaluate(self, evaluator, qn, connection):\n return self.mask, []", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_latest_analysis_status(self, *args, **kwargs) -> None:\n return None", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def forget(self, request, **kw):\n # No-op.\n return []", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def restartGUI(self, ret=None):\n\t\tself.session.open(Console, title=_(\"Your %s %s will Restart...\") % getBoxDisplayName(), cmdlist=[\"killall -9 enigma2\"], showScripts=False)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def activate(x):\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def set_on_delete(collector, field, sub_objs, using):\n collector.add_field_update(field, value, sub_objs)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def migrate_export_to_version_11_2(exported_json, org, same_site=True):\n \"\"\"\n Migrates base_language in flow exports from iso639-2 to iso639-3\n \"\"\"\n country_code = org.default_country_code\n\n migrated_flows = []\n for sub_flow in exported_json.get(\"flows\", []):\n flow = _base_migrate_to_version_11_2(sub_flow, country_code=country_code)\n migrated_flows.append(flow)\n\n exported_json[\"flows\"] = migrated_flows\n\n return exported_json", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def _should_update_cache(self, request, response):\n return hasattr(request, \"_cache_update_cache\") and request._cache_update_cache", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def validate_config(self, organization, config, actor=None):\n return config", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_issue(self, issue_key):\n return self._get_stub_data(\"get_issue_response.json\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def handler500(request, *args, **argv):\n if request.content_type.find('application/json') > -1:\n response = JsonResponse({'error': 'Server internal error'}, status=500)\n else:\n response = render(request, '500.html', status=500)\n return response", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn PluginDescriptor(name=_(\"Video enhancement setup\"), description=_(\"Advanced video enhancement setup\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=startSetup)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def createCryptoNameCaid(self, info):\n\t\tcaidName = \"FTA\"\n\t\tif int(self.currentCAID, 16):\n\t\t\ttry:\n\t\t\t\tfor caidData in getCaidData():\n\t\t\t\t\tif int(caidData[0], 16) <= int(self.currentCAID, 16) <= int(caidData[1], 16):\n\t\t\t\t\t\tcaidName = caidData[2]\n\t\t\t\t\t\tbreak\n\t\t\t\tcaidName = f\"{caidName}:{int(self.currentCAID, 16):04X}\"\n\t\t\texcept Exception:\n\t\t\t\tcaidName = \"\"\n\t\treturn caidName", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def build_activity_context(\n activity: IncidentActivity, user: RpcUser, activity_user: RpcUser | None = None\n) -> dict[str, Any]:\n if activity_user is None:\n activity_user = user_service.get_user(user_id=activity.user_id)\n\n if activity.type == IncidentActivityType.COMMENT.value:\n action = \"left a comment\"\n else:\n action = \"changed status from {} to {}\".format(\n INCIDENT_STATUS[IncidentStatus(int(activity.previous_value))],\n INCIDENT_STATUS[IncidentStatus(int(activity.value))],\n )\n incident = activity.incident\n\n action = f\"{action} on alert {incident.title} (#{incident.identifier})\"\n\n return {\n \"user_name\": activity_user.name if activity_user else \"Sentry\",\n \"action\": action,\n \"link\": absolute_uri(\n reverse(\n \"sentry-metric-alert\",\n kwargs={\n \"organization_slug\": incident.organization.slug,\n \"incident_id\": incident.identifier,\n },\n )\n )\n + \"?\"\n + urlencode({\"referrer\": \"incident_activity_email\"}),\n \"comment\": activity.comment,\n }", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def top_events_timeseries(\n timeseries_columns,\n selected_columns,\n user_query,\n snuba_params,\n orderby,\n rollup,\n limit,\n organization,\n equations=None,\n referrer=None,\n top_events=None,\n allow_empty=True,\n zerofill_results=True,\n include_other=False,\n functions_acl=None,\n result_key_order=None,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n query_source: QuerySource | None = None,\n):\n assert not include_other, \"Other is not supported\" # TODO: support other\n\n if top_events is None:\n with sentry_sdk.start_span(op=\"discover.discover\", name=\"top_events.fetch_events\"):\n top_events = query(\n selected_columns,\n query=user_query,\n snuba_params=snuba_params,\n equations=equations,\n orderby=orderby,\n limit=limit,\n referrer=referrer,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n query_source=query_source,\n )\n\n top_functions_builder = ProfileTopFunctionsTimeseriesQueryBuilder(\n dataset=Dataset.Functions,\n params={},\n snuba_params=snuba_params,\n interval=rollup,\n top_events=top_events[\"data\"],\n other=False,\n query=user_query,\n selected_columns=selected_columns,\n timeseries_columns=timeseries_columns,\n equations=equations,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n skip_tag_resolution=True,\n ),\n )\n\n if len(top_events[\"data\"]) == limit and include_other:\n assert False, \"Other is not supported\" # TODO: support other\n\n result = top_functions_builder.run_query(referrer=referrer, query_source=query_source)\n\n return format_top_events_timeseries_results(\n result,\n top_functions_builder,\n snuba_params,\n rollup,\n top_events=top_events,\n allow_empty=allow_empty,\n zerofill_results=zerofill_results,\n result_key_order=result_key_order,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def transifex_upload_string_l10n(self, resource_name,\n string_name, # pylint: disable=unused-argument\n string_hash, lang_code, translated_value,\n missing_only): # pylint: disable=unused-argument\n \"\"\"Uploads the localized string in the given language for the string\n with the given hash.\"\"\"\n url_part = (f'project/{self.project_name}/resource/{resource_name}'\n f'/translation/{lang_code}/string/{string_hash}/')\n url = base_url + url_part\n payload = {\n 'translation': translated_value,\n # Assume Chromium provided strings are reviewed and proofread\n 'reviewed': True,\n 'proofread': True,\n 'user': 'bbondy'\n }\n headers = {'Content-Type': 'application/json'}\n r = requests.put(url, json=payload, auth=self.get_auth(),\n headers=headers)\n assert r.status_code >= 200 and r.status_code <= 299, \\\n f'Aborting. Status code {r.status_code}: {r.content}'", "smellKey": "S1172", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def get_auth_url(self, user, **kwargs):\n if self.auth_provider is None:\n return\n\n return reverse(\"socialauth_associate\", args=[self.auth_provider])", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def on_runner_success(self, runner, cb):\n summary = cb.summary\n for state, hosts in summary.items():\n for host in hosts:\n result = cb.host_results.get(host)\n if state == 'ok':\n self.on_host_success(host, result.get('ok', ''))\n elif state == 'skipped':\n pass\n else:\n error = hosts.get(host)\n self.on_host_error(\n host, error,\n result.get('failures', '')\n or result.get('dark', '')\n )", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str | None = None,\n zerofill_results: bool = True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n allow_metric_aggregates: bool = False,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n\n This function operates on the public event schema and\n virtual fields/aggregate functions for selected columns and\n conditions are supported through this function.\n\n This function is intended to only get timeseries based\n results and thus requires the `rollup` parameter.\n\n Returns a SnubaTSResult object that has been zerofilled in\n case of gaps.\n\n selected_columns - List of public aliases to fetch.\n query - Filter query string to create conditions from.\n snuba_params - Filtering parameters with start, end, project_id, environment,\n rollup - The bucket width in seconds\n referrer - A referrer string to help locate the origin of this query.\n comparison_delta - A timedelta used to convert this into a comparison query. We make a second\n query time-shifted back by comparison_delta, and compare the results to get the % change for each\n time bucket. Requires that we only pass\n allow_metric_aggregates - Ignored here, only used in metric enhanced performance\n \"\"\"\n assert dataset in [\n Dataset.Discover,\n Dataset.Transactions,\n ], \"A dataset is required to query discover\"\n\n with sentry_sdk.start_span(op=\"discover.discover\", name=\"timeseries.filter_transform\"):\n equations, columns = categorize_columns(selected_columns)\n base_builder = TimeseriesQueryBuilder(\n dataset,\n params={},\n interval=rollup,\n snuba_params=snuba_params,\n query=query,\n selected_columns=columns,\n equations=equations,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n has_metrics=has_metrics,\n ),\n )\n query_list = [base_builder]\n if comparison_delta:\n if len(base_builder.aggregates) != 1:\n raise InvalidSearchQuery(\"Only one column can be selected for comparison queries\")\n comp_query_params = snuba_params.copy()\n assert comp_query_params.start is not None, \"start is required\"\n assert comp_query_params.end is not None, \"end is required\"\n comp_query_params.start -= comparison_delta\n comp_query_params.end -= comparison_delta\n comparison_builder = TimeseriesQueryBuilder(\n dataset,\n params={},\n interval=rollup,\n snuba_params=comp_query_params,\n query=query,\n selected_columns=columns,\n equations=equations,\n )\n query_list.append(comparison_builder)\n\n query_results = bulk_snuba_queries(\n [query.get_snql_query() for query in query_list], referrer, query_source=query_source\n )\n\n with sentry_sdk.start_span(op=\"discover.discover\", name=\"timeseries.transform_results\"):\n results = []\n for snql_query, snuba_result in zip(query_list, query_results):\n results.append(\n {\n \"data\": (\n zerofill(\n snuba_result[\"data\"],\n # Start and end are asserted to exist earlier in the function\n cast(datetime, snql_query.params.start),\n cast(datetime, snql_query.params.end),\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else snuba_result[\"data\"]\n ),\n \"meta\": snuba_result[\"meta\"],\n }\n )\n\n if len(results) == 2 and comparison_delta:\n col_name = base_builder.aggregates[0].alias\n # If we have two sets of results then we're doing a comparison queries. Divide the primary\n # results by the comparison results.\n for row, compared_row in zip(results[0][\"data\"], results[1][\"data\"]):\n compared_value = compared_row.get(col_name, 0)\n row[\"comparisonCount\"] = compared_value\n\n result = results[0]\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"meta\": {\n \"fields\": {\n value[\"name\"]: get_json_meta_type(\n value[\"name\"], value.get(\"type\"), base_builder\n )\n for value in result[\"meta\"]\n }\n },\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def redirect(request):\n return HttpResponseRedirect(\"/\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def conditional_http_tween_factory(handler, registry):\n def conditional_http_tween(request):\n response = handler(request)\n\n # If the Last-Modified header has been set, we want to enable the\n # conditional response processing.\n if response.last_modified is not None:\n response.conditional_response = True\n\n streaming = not isinstance(response.app_iter, collections.abc.Sequence)\n\n # We want to only enable the conditional machinery if either we\n # were given an explicit ETag header by the view or we have a\n # buffered response and can generate the ETag header ourself.\n if response.etag is not None:\n response.conditional_response = True\n # We can only reasonably implement automatic ETags on 200 responses\n # to GET or HEAD requests. The subtles of doing it in other cases\n # are too hard to get right.\n elif request.method in {\"GET\", \"HEAD\"} and response.status_code == 200:\n # If we have a streaming response, but it's small enough, we'll\n # just go ahead and buffer it in memory so that we can generate a\n # ETag for it.\n if (\n streaming\n and response.content_length is not None\n and response.content_length <= BUFFER_MAX\n ):\n response.body\n streaming = False\n\n # Anything that has survived as a streaming response at this point\n # and doesn't have an ETag header already, we'll go ahead and give\n # it one.\n if not streaming:\n response.conditional_response = True\n response.md5_etag()\n\n return response\n\n return conditional_http_tween", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def upload_dependencies(arvrunner, name, document_loader,\n workflowobj, uri, runtimeContext,\n include_primary=True, discovered_secondaryfiles=None,\n cache=None):\n \"\"\"Upload the dependencies of the workflowobj document to Keep.\n\n Returns a pathmapper object mapping local paths to keep references. Also\n does an in-place update of references in \"workflowobj\".\n\n Use scandeps to find $schemas, File and Directory\n fields that represent external references.\n\n If workflowobj has an \"id\" field, this will reload the document to ensure\n it is scanning the raw document prior to preprocessing.\n \"\"\"\n\n scanobj = workflowobj\n metadata = scanobj\n\n with Perf(metrics, \"scandeps\"):\n sc_result = scandeps(uri, scanobj,\n set(),\n set((\"location\",)),\n None, urljoin=document_loader.fetcher.urljoin,\n nestdirs=False)\n optional_deps = scandeps(uri, scanobj,\n set(),\n set((\"$schemas\",)),\n None, urljoin=document_loader.fetcher.urljoin,\n nestdirs=False)\n\n if sc_result is None:\n sc_result = []\n\n if optional_deps is None:\n optional_deps = []\n\n if optional_deps:\n sc_result.extend(optional_deps)\n\n sc = []\n uuids = {}\n\n def collect_uuids(obj):\n loc = obj.get(\"location\", \"\")\n sp = loc.split(\":\")\n if sp[0] == \"keep\":\n # Collect collection uuids that need to be resolved to\n # portable data hashes\n gp = collection_uuid_pattern.match(loc)\n if gp:\n uuids[gp.groups()[0]] = obj\n if collectionUUID in obj:\n uuids[obj[collectionUUID]] = obj\n\n def collect_uploads(obj):\n loc = obj.get(\"location\", \"\")\n sp = loc.split(\":\")\n if len(sp) < 1:\n return\n if sp[0] in (\"file\", \"http\", \"https\"):\n # Record local files than need to be uploaded,\n # don't include file literals, keep references, etc.\n sc.append(obj)\n collect_uuids(obj)\n\n with Perf(metrics, \"collect uuids\"):\n visit_class(workflowobj, (\"File\", \"Directory\"), collect_uuids)\n\n with Perf(metrics, \"collect uploads\"):\n visit_class(sc_result, (\"File\", \"Directory\"), collect_uploads)\n\n # Resolve any collection uuids we found to portable data hashes\n # and assign them to uuid_map\n uuid_map = {}\n fetch_uuids = list(uuids.keys())\n with Perf(metrics, \"fetch_uuids\"):\n while fetch_uuids:\n # For a large number of fetch_uuids, API server may limit\n # response size, so keep fetching from API server has nothing\n # more to give us.\n lookups = arvrunner.api.collections().list(\n filters=[[\"uuid\", \"in\", fetch_uuids]],\n count=\"none\",\n select=[\"uuid\", \"portable_data_hash\"]).execute(\n num_retries=arvrunner.num_retries)\n\n if not lookups[\"items\"]:\n break\n\n for l in lookups[\"items\"]:\n uuid_map[l[\"uuid\"]] = l[\"portable_data_hash\"]\n\n fetch_uuids = [u for u in fetch_uuids if u not in uuid_map]\n\n normalizeFilesDirs(sc)\n\n if \"id\" in workflowobj:\n defrg, _ = urllib.parse.urldefrag(workflowobj[\"id\"])\n if include_primary:\n # make sure it's included\n sc.append({\"class\": \"File\", \"location\": defrg})\n else:\n # make sure it's excluded\n sc = [d for d in sc if d.get(\"location\") != defrg]\n\n def visit_default(obj):\n def defaults_are_optional(f):\n if \"location\" not in f and \"path\" in f:\n f[\"location\"] = f[\"path\"]\n del f[\"path\"]\n normalizeFilesDirs(f)\n optional_deps.append(f)\n visit_class(obj[\"default\"], (\"File\", \"Directory\"), defaults_are_optional)\n\n find_defaults(workflowobj, visit_default)\n\n discovered = {}\n def discover_default_secondary_files(obj):\n builder_job_order = {}\n for t in obj[\"inputs\"]:\n builder_job_order[shortname(t[\"id\"])] = t[\"default\"] if \"default\" in t else None\n # Need to create a builder object to evaluate expressions.\n builder = make_builder(builder_job_order,\n obj.get(\"hints\", []),\n obj.get(\"requirements\", []),\n ArvRuntimeContext(),\n metadata)\n discover_secondary_files(arvrunner.fs_access,\n builder,\n obj[\"inputs\"],\n builder_job_order,\n discovered)\n\n copied, _ = document_loader.resolve_all(copy.deepcopy(cmap(workflowobj)), base_url=uri, checklinks=False)\n visit_class(copied, (\"CommandLineTool\", \"Workflow\"), discover_default_secondary_files)\n\n for d in list(discovered):\n # Only interested in discovered secondaryFiles which are local\n # files that need to be uploaded.\n if d.startswith(\"file:\"):\n sc.extend(discovered[d])\n else:\n del discovered[d]\n\n with Perf(metrics, \"mapper\"):\n mapper = ArvPathMapper(arvrunner, sc, \"\",\n \"keep:%s\",\n \"keep:%s/%s\",\n name=name,\n single_collection=True,\n optional_deps=optional_deps)\n\n for k, v in uuid_map.items():\n mapper._pathmap[\"keep:\"+k] = MapperEnt(v, \"\", \"\", False)\n\n keeprefs = set()\n def addkeepref(k):\n if k.startswith(\"keep:\"):\n keeprefs.add(collection_pdh_pattern.match(k).group(1))\n\n\n def collectloc(p):\n loc = p.get(\"location\")\n if loc and (not loc.startswith(\"_:\")) and (not loc.startswith(\"keep:\")):\n addkeepref(p[\"location\"])\n return\n\n if not loc:\n return\n\n if collectionUUID in p:\n uuid = p[collectionUUID]\n if uuid not in uuid_map:\n raise SourceLine(p, collectionUUID, validate.ValidationException).makeError(\n \"Collection uuid %s not found\" % uuid)\n gp = collection_pdh_pattern.match(loc)\n if gp and uuid_map[uuid] != gp.groups()[0]:\n # This file entry has both collectionUUID and a PDH\n # location. If the PDH doesn't match the one returned\n # the API server, raise an error.\n raise SourceLine(p, \"location\", validate.ValidationException).makeError(\n \"Expected collection uuid %s to be %s but API server reported %s\" % (\n uuid, gp.groups()[0], uuid_map[p[collectionUUID]]))\n\n gp = collection_uuid_pattern.match(loc)\n if not gp:\n # Not a uuid pattern (must be a pdh pattern)\n addkeepref(p[\"location\"])\n return\n\n uuid = gp.groups()[0]\n if uuid not in uuid_map:\n raise SourceLine(p, \"location\", validate.ValidationException).makeError(\n \"Collection uuid %s not found\" % uuid)\n\n with Perf(metrics, \"collectloc\"):\n visit_class(workflowobj, (\"File\", \"Directory\"), collectloc)\n visit_class(discovered, (\"File\", \"Directory\"), collectloc)\n\n if discovered_secondaryfiles is not None:\n for d in discovered:\n discovered_secondaryfiles[mapper.mapper(d).resolved] = discovered[d]\n\n if runtimeContext.copy_deps:\n # Find referenced collections and copy them into the\n # destination project, for easy sharing.\n already_present = list(arvados.util.keyset_list_all(arvrunner.api.collections().list,\n filters=[[\"portable_data_hash\", \"in\", list(keeprefs)],\n [\"owner_uuid\", \"=\", runtimeContext.project_uuid]],\n select=[\"uuid\", \"portable_data_hash\", \"created_at\"]))\n\n keeprefs = keeprefs - set(a[\"portable_data_hash\"] for a in already_present)\n for kr in keeprefs:\n col = arvrunner.api.collections().list(filters=[[\"portable_data_hash\", \"=\", kr]],\n order=\"created_at desc\",\n select=[\"name\", \"description\", \"properties\", \"portable_data_hash\", \"manifest_text\", \"storage_classes_desired\", \"trash_at\"],\n limit=1).execute()\n if len(col[\"items\"]) == 0:\n logger.warning(\"Cannot find collection with portable data hash %s\", kr)\n continue\n col = col[\"items\"][0]\n col[\"name\"] = arvados.util.trim_name(col[\"name\"])\n try:\n arvrunner.api.collections().create(body={\"collection\": {\n \"owner_uuid\": runtimeContext.project_uuid,\n \"name\": col[\"name\"],\n \"description\": col[\"description\"],\n \"properties\": col[\"properties\"],\n \"portable_data_hash\": col[\"portable_data_hash\"],\n \"manifest_text\": col[\"manifest_text\"],\n \"storage_classes_desired\": col[\"storage_classes_desired\"],\n \"trash_at\": col[\"trash_at\"]\n }}, ensure_unique_name=True).execute()\n except Exception as e:\n logger.warning(\"Unable to copy collection to destination: %s\", e)\n\n if \"$schemas\" in workflowobj:\n sch = CommentedSeq()\n for s in workflowobj[\"$schemas\"]:\n if s in mapper:\n sch.append(mapper.mapper(s).resolved)\n workflowobj[\"$schemas\"] = sch\n\n return mapper", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def filter_delete_queryset(self, queryset, request):\n \"\"\"Provide custom filtering for the queryset *before* it is deleted.\n\n The default implementation does nothing, just returns the queryset.\n \"\"\"\n return queryset", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def _check_unique(self, **kwargs):\n if self.unique:\n return [\n checks.Error(\n \"ManyToManyFields cannot be unique.\",\n obj=self,\n id=\"fields.E330\",\n )\n ]\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def activity_created_receiver(instance, created, **kwargs) -> None:\n \"\"\"\n If an activity is created for an issue, this will trigger, and we can kick off an async process\n \"\"\"\n log_params = {\"activity_id\": instance.id, \"activity_object_created\": created}\n _default_logger.debug(\"receiver for activity event\", extra=log_params)\n if not created:\n _default_logger.debug(\"instance is not created, skipping post processing\", extra=log_params)\n return\n\n transaction.on_commit(\n lambda: send_activity_notifications_to_slack_threads.apply_async(\n kwargs={\"activity_id\": instance.id}\n ),\n using=router.db_for_read(Activity),\n )\n\n metrics.incr(\n _TASK_QUEUED_METRIC,\n sample_rate=1.0,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def calculate_hits(\n self,\n group_ids: Sequence[int],\n too_many_candidates: bool,\n sort_field: str,\n projects: Sequence[Project],\n retention_window_start: datetime | None,\n group_queryset: Query,\n environments: Sequence[Environment] | None,\n sort_by: str,\n limit: int,\n cursor: Cursor | None,\n count_hits: bool,\n paginator_options: Mapping[str, Any],\n search_filters: Sequence[SearchFilter] | None,\n start: datetime,\n end: datetime,\n actor: Any | None = None,\n ) -> int | None:\n \"\"\"\n This method should return an integer representing the number of hits (results) of your search.\n It will return 0 if hits were calculated and there are none.\n It will return None if hits were not calculated.\n \"\"\"\n if count_hits is False:\n return None\n elif too_many_candidates or cursor is not None:\n # If we had too many candidates to reasonably pass down to snuba,\n # or if we have a cursor that bisects the overall result set (such\n # that our query only sees results on one side of the cursor) then\n # we need an alternative way to figure out the total hits that this\n # query has.\n\n # To do this, we get a sample of groups matching the snuba side of\n # the query, and see how many of those pass the post-filter in\n # postgres. This should give us an estimate of the total number of\n # snuba matches that will be overall matches, which we can use to\n # get an estimate for X-Hits.\n\n # The sampling is not simple random sampling. It will return *all*\n # matching groups if there are less than N groups matching the\n # query, or it will return a random, deterministic subset of N of\n # the groups if there are more than N overall matches. This means\n # that the \"estimate\" is actually an accurate result when there are\n # less than N matching groups.\n\n # The number of samples required to achieve a certain error bound\n # with a certain confidence interval can be calculated from a\n # rearrangement of the normal approximation (Wald) confidence\n # interval formula:\n #\n # https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval\n #\n # Effectively if we want the estimate to be within +/- 10% of the\n # real value with 95% confidence, we would need (1.96^2 * p*(1-p))\n # / 0.1^2 samples. With a starting assumption of p=0.5 (this\n # requires the most samples) we would need 96 samples to achieve\n # +/-10% @ 95% confidence.\n\n sample_size = options.get(\"snuba.search.hits-sample-size\")\n kwargs = dict(\n start=start,\n end=end,\n project_ids=[p.id for p in projects],\n environment_ids=environments and [environment.id for environment in environments],\n organization=projects[0].organization,\n sort_field=sort_field,\n limit=sample_size,\n offset=0,\n get_sample=True,\n search_filters=search_filters,\n actor=actor,\n )\n if not too_many_candidates:\n kwargs[\"group_ids\"] = group_ids\n\n snuba_groups, snuba_total = self.snuba_search(**kwargs)\n snuba_count = len(snuba_groups)\n if snuba_count == 0:\n # Maybe check for 0 hits and return EMPTY_RESULT in ::query? self.empty_result\n return 0\n else:\n filtered_count = group_queryset.filter(\n id__in=[gid for gid, _ in snuba_groups]\n ).count()\n\n hit_ratio = filtered_count / float(snuba_count)\n hits = int(hit_ratio * snuba_total)\n return hits\n return None", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def pgettext(c: str, s: str) -> str: # type: ignore[misc]\n return s", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _get_wheel_metadata_from_wheel(\n whl_basename, metadata_directory, config_settings):\n \"\"\"Extract the metadata from a wheel.\n\n Fallback for when the build backend does not\n define the 'get_wheel_metadata' hook.\n \"\"\"\n from zipfile import ZipFile\n with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):\n pass # Touch marker file\n\n whl_file = os.path.join(metadata_directory, whl_basename)\n with ZipFile(whl_file) as zipf:\n dist_info = _dist_info_files(zipf)\n zipf.extractall(path=metadata_directory, members=dist_info)\n return dist_info[0].split('/')[0]", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def check_password(self, password, *, tags=None):\n # This service allows *every* password as a non-breached password. It will never\n # tell a user their password isn't good enough.\n return False", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def process(business: Business, filing_submission: Filing, filing: Dict):\n \"\"\"Render the Alteration onto the model objects.\"\"\"\n # Alter the corp type, if any\n with suppress(IndexError, KeyError, TypeError):\n business_json = dpath.util.get(filing, '/alteration/business')\n business_info.set_corp_type(business, business_json)\n\n # update court order, if any is present\n with suppress(IndexError, KeyError, TypeError):\n court_order_json = dpath.util.get(filing, '/alteration/courtOrder')\n filings.update_filing_court_order(filing_submission, court_order_json)\n\n # update name translations, if any\n with suppress(IndexError, KeyError, TypeError):\n alias_json = dpath.util.get(filing, '/alteration/nameTranslations')\n aliases.update_aliases(business, alias_json)\n\n # update share structure and resolutions, if any\n with suppress(IndexError, KeyError, TypeError):\n share_structure = dpath.util.get(filing, '/alteration/shareStructure')\n shares.update_share_structure(business, share_structure)", "smellKey": "S1172", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "def translate(self, *args, **kwargs):\n self._fail()", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def get_username(\n details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs\n):\n \"\"\"Return an username for new user. Return current user username\n if user was given.\n \"\"\"\n if user:\n return {\"username\": UserSocialAuth.user_username(user)}\n\n email_as_username = setting(\"SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL\", False)\n uuid_length = setting(\"SOCIAL_AUTH_UUID_LENGTH\", 16)\n do_slugify = setting(\"SOCIAL_AUTH_SLUGIFY_USERNAMES\", False)\n\n if email_as_username and details.get(\"email\"):\n username = details[\"email\"]\n elif details.get(\"username\"):\n username = str(details[\"username\"])\n else:\n username = uuid4().hex\n\n max_length = UserSocialAuth.username_max_length()\n short_username = username[: max_length - uuid_length]\n final_username = UserSocialAuth.clean_username(username[:max_length])\n if do_slugify:\n final_username = slugify(final_username)\n\n # Generate a unique username for current user using username\n # as base but adding a unique hash at the end. Original\n # username is cut to avoid any field max_length.\n while user_exists(username=final_username):\n username = short_username + uuid4().hex[:uuid_length]\n username = username[:max_length]\n final_username = UserSocialAuth.clean_username(username)\n if do_slugify:\n final_username = slugify(final_username)\n return {\"username\": final_username}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_session_count(\n self, project_id: int, environment_id: int, start: datetime, end: datetime\n ) -> int:\n cache_key = f\"r.c.spc:{project_id}-{environment_id}\"\n session_count_last_hour = cache.get(cache_key)\n if session_count_last_hour is None:\n with options_override({\"consistent\": False}):\n session_count_last_hour = release_health.backend.get_project_sessions_count(\n project_id=project_id,\n environment_id=environment_id,\n rollup=60,\n start=end - timedelta(minutes=60),\n end=end,\n )\n\n cache.set(cache_key, session_count_last_hour, 600)\n return session_count_last_hour", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def main(args, stdout, stderr, api_client=None, logger=None):\n args = parse_args(args)\n\n if api_client is None:\n api_client = arvados.api('v1', num_retries=args.retries)\n\n if logger is None:\n logger = logging.getLogger('arvados.arv-ls')\n\n try:\n r = re.search(r'^(.*?)(/.*)?$', args.locator)\n collection = r.group(1)\n get_prefix = r.group(2)\n\n cr = arvados.CollectionReader(collection, api_client=api_client,\n num_retries=args.retries)\n if get_prefix:\n if get_prefix[-1] == '/':\n get_prefix = get_prefix[:-1]\n stream_name = '.' + get_prefix\n reader = cr.find(stream_name)\n if not (isinstance(reader, arvados.CollectionReader) or\n isinstance(reader, arvados.collection.Subcollection)):\n logger.error(\"'{}' is not a subdirectory\".format(get_prefix))\n return 1\n else:\n stream_name = '.'\n reader = cr\n except (arvados.errors.ApiError,\n arvados.errors.ArgumentError,\n arvados.errors.NotFoundError) as error:\n logger.error(\"error fetching collection: {}\".format(error))\n return 1\n\n formatters = []\n if args.s:\n formatters.append(size_formatter)\n formatters.append(name_formatter)\n\n for f in files_in_collection(reader, stream_name):\n print(*(info_func(f) for info_func in formatters), file=stdout)\n\n return 0", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def from_objects(\n context_owner: CoreObjectDescriptor, # noqa: ARG001\n context: VarsContextSection,\n parsed_arguments: Any,\n) -> tuple[CoreObjectDescriptor, ...]:\n if not isinstance(parsed_arguments, BaseArgumentsWithTypedObjects):\n return ()\n\n return tuple(\n _from_target_description(target_description=target_description, context=context)\n for target_description in parsed_arguments.objects\n )", "smellKey": "S1172", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def process_view(self, request, view_func, view_args, view_kwargs):\n log.append(\"processed view %s\" % view_func.__name__)\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def index_view(request):\n \"\"\"Target for no_trailing_slash_external_redirect with follow=True.\"\"\"\n return HttpResponse(\"Hello world\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def query(\n selected_columns,\n query,\n snuba_params,\n equations=None,\n orderby=None,\n offset=None,\n limit=50,\n referrer=None,\n auto_fields=False,\n auto_aggregations=False,\n include_equation_fields=False,\n allow_metric_aggregates=False,\n use_aggregate_conditions=False,\n conditions=None,\n functions_acl=None,\n transform_alias_to_input_format=False,\n sample=None,\n has_metrics=False,\n use_metrics_layer=False,\n skip_tag_resolution=False,\n on_demand_metrics_enabled=False,\n on_demand_metrics_type: MetricSpecType | None = None,\n fallback_to_transactions=False,\n query_source: QuerySource | None = None,\n) -> EventsResponse:\n \"\"\"\n High-level API for doing arbitrary user queries against events.\n\n This function operates on the Discover public event schema and\n virtual fields/aggregate functions for selected columns and\n conditions are supported through this function.\n\n The resulting list will have all internal field names mapped\n back into their public schema names.\n\n selected_columns (Sequence[str]) List of public aliases to fetch.\n query (str) Filter query string to create conditions from.\n params (Dict[str, str]) Filtering parameters with start, end, project_id, environment\n equations (Sequence[str]) List of equations to calculate for the query\n orderby (None|str|Sequence[str]) The field to order results by.\n offset (None|int) The record offset to read.\n limit (int) The number of records to fetch.\n referrer (str|None) A referrer string to help locate the origin of this query.\n auto_fields (bool) Set to true to have project + eventid fields automatically added.\n auto_aggregations (bool) Whether aggregates should be added automatically if they're used\n in conditions, and there's at least one aggregate already.\n include_equation_fields (bool) Whether fields should be added automatically if they're used in\n equations\n allow_metric_aggregates (bool) Ignored here, only used in metric enhanced performance\n use_aggregate_conditions (bool) Set to true if aggregates conditions should be used at all.\n conditions (Sequence[Condition]) List of conditions that are passed directly to snuba without\n any additional processing.\n transform_alias_to_input_format (bool) Whether aggregate columns should be returned in the originally\n requested function format.\n sample (float) The sample rate to run the query with\n \"\"\"\n if not selected_columns:\n raise InvalidSearchQuery(\"No columns selected\")\n\n builder = DiscoverQueryBuilder(\n Dataset.IssuePlatform,\n {},\n snuba_params=snuba_params,\n query=query,\n selected_columns=selected_columns,\n equations=equations,\n orderby=orderby,\n limit=limit,\n offset=offset,\n sample_rate=sample,\n config=QueryBuilderConfig(\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n functions_acl=functions_acl,\n equation_config={\"auto_add\": include_equation_fields},\n has_metrics=has_metrics,\n transform_alias_to_input_format=transform_alias_to_input_format,\n skip_tag_resolution=skip_tag_resolution,\n ),\n )\n if conditions is not None:\n builder.add_conditions(conditions)\n result = builder.process_results(builder.run_query(referrer, query_source=query_source))\n result[\"meta\"][\"tips\"] = transform_tips(builder.tips)\n return result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _script_response_error(response, message, scope=OPENC3_SCOPE):\n if response:\n raise RuntimeError(f\"{message} ({response.status_code}): {response.text}\")\n else:\n raise RuntimeError(f\"{message}: No Response\")", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [PluginDescriptor(name=\"DiSEqC Tester\", description=_(\"Test DiSEqC settings\"), where=PluginDescriptor.WHERE_PLUGINMENU, needsRestart=False, fnc=DiseqcTesterMain),\n\t\t\tPluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, needsRestart=False, fnc=autostart)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _gather_logs(item, report, driver, summary, extra):\n try:\n types = driver.log_types\n except Exception as e:\n # note that some drivers may not implement log types\n summary.append(f\"WARNING: Failed to gather log types: {e}\")\n return\n for name in types:\n try:\n log = driver.get_log(name)\n except Exception as e:\n summary.append(f\"WARNING: Failed to gather {name} log: {e}\")\n return\n pytest_html = item.config.pluginmanager.getplugin(\"html\")\n if pytest_html is not None:\n extra.append(pytest_html.extras.text(format_log(log), \"%s Log\" % name.title()))", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def check_pointer(result, func, cargs):\n \"Make sure the result pointer is valid.\"\n if isinstance(result, int):\n result = c_void_p(result)\n if result:\n return result\n else:\n raise GDALException('Invalid pointer returned from \"%s\"' % func.__name__)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def read_text(\n package: Package,\n resource: Resource,\n encoding: str = 'utf-8',\n errors: str = 'strict'\n ) -> str:\n with open(where(), encoding=encoding) as data:\n return data.read()", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def Plugins(**kwargs):\n\tif YoutubeDL:\n\t\treturn [PluginDescriptor(name=\"YTDLWrapper\", description=\"YTDLWrapper\", where=PluginDescriptor.WHERE_PLAYSERVICE, needsRestart=False, fnc=playService)]\n\telse:\n\t\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _execute_create_test_db(self, cursor, parameters, keepdb=False):\n cursor.execute(\"CREATE DATABASE %(dbname)s %(suffix)s\" % parameters)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get(self, key, secret_store=None, scope=None):\n return self.local_secrets[key]", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:\n \"\"\"Writes the help text to the formatter if it exists.\"\"\"\n if self.help is not None:\n # truncate the help text to the first form feed\n text = inspect.cleandoc(self.help).partition(\"\\f\")[0]\n else:\n text = \"\"\n\n if self.deprecated:\n text = _(\"(Deprecated) {text}\").format(text=text)\n\n if text:\n formatter.write_paragraph()\n\n with formatter.indentation():\n formatter.write_text(text)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def process_resource_change(instance, **kwargs):\n from sentry.integrations.github.integration import GitHubIntegration\n from sentry.integrations.gitlab.integration import GitlabIntegration\n from sentry.tasks.codeowners import code_owners_auto_sync\n\n def _spawn_task():\n filepaths = set(GitHubIntegration.codeowners_locations) | set(\n GitlabIntegration.codeowners_locations\n )\n\n # CODEOWNERS file added or modified, trigger auto-sync\n if instance.filename in filepaths and instance.type in [\"A\", \"M\"]:\n # Trigger the task after 5min to make sure all records in the transactions has been saved.\n code_owners_auto_sync.apply_async(\n kwargs={\"commit_id\": instance.commit_id}, countdown=60 * 5\n )\n\n transaction.on_commit(_spawn_task, router.db_for_write(CommitFileChange))", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def run(resource: HTTPResource, additional_oois: list[HTTPHeader], config: dict[str, Any]) -> Iterator[OOI]:\n if not additional_oois:\n return\n\n header_keys = [header.key.lower() for header in additional_oois]\n headers = {header.key.lower(): header.value for header in additional_oois}\n\n if \"location\" in header_keys:\n return\n\n if \"strict-transport-security\" not in header_keys and resource.reference.tokenized.web_url.scheme != \"http\":\n ft = KATFindingType(id=\"KAT-NO-HSTS\")\n yield ft\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header strict-transport-security is missing or not configured correctly.\",\n )\n yield finding\n\n if \"content-security-policy\" not in header_keys and is_xss_capable(headers.get(\"content-type\", \"\")):\n ft = KATFindingType(id=\"KAT-NO-CSP\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header content-security-policy is missing or not configured correctly.\",\n )\n yield ft\n yield finding\n\n if \"x-frame-options\" not in header_keys:\n ft = KATFindingType(id=\"KAT-NO-X-FRAME-OPTIONS\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header x-frame-options is missing or not configured correctly.\",\n )\n yield ft\n yield finding\n\n if \"permissions-policy\" not in header_keys:\n ft = KATFindingType(id=\"KAT-NO-PERMISSIONS-POLICY\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header permissions-policy is missing or not configured correctly.\",\n )\n yield ft\n yield finding\n\n if \"referrer-policy\" not in header_keys:\n ft = KATFindingType(id=\"KAT-NO-REFERRER-POLICY\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header referrer-policy is missing or not configured correctly.\",\n )\n yield ft\n yield finding\n\n if \"x-content-type-options\" not in header_keys:\n ft = KATFindingType(id=\"KAT-NO-X-CONTENT-TYPE-OPTIONS\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=\"Header x-content-type-options is missing or not configured correctly.\",\n )\n yield ft\n yield finding\n\n deprecated_headers = set(header_keys) & DEPRECATED_HEADER\n if deprecated_headers:\n ft = KATFindingType(id=\"KAT-NONSTANDARD-HEADERS\")\n finding = Finding(\n finding_type=ft.reference,\n ooi=resource.reference,\n description=f\"Nonstandard headers are used. Avoid using the following headers: \"\n f\"{' '.join(deprecated_headers)}\",\n )\n yield ft\n yield finding", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def visit_Name(\n self, node: nodes.Name, store_as_param: bool = False, **kwargs: t.Any\n ) -> None:\n \"\"\"All assignments to names go through this function.\"\"\"\n if store_as_param or node.ctx == \"param\":\n self.symbols.declare_parameter(node.name)\n elif node.ctx == \"store\":\n self.symbols.store(node.name)\n elif node.ctx == \"load\":\n self.symbols.load(node.name)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def quickMenuEntryComponent(itemIndex, pngname, name, description, longDescription=None, width=540):\n\t\t\ticon = LoadPixmap(resolveFilename(SCOPE_SKIN, f\"icons/{pngname}.png\"))\n\t\t\tif icon is None:\n\t\t\t\ticon = LoadPixmap(resolveFilename(SCOPE_SKIN, \"icons/default.png\"))\n\t\t\treturn (name, description, icon, itemIndex, longDescription)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def ls_owned_files(self, codeowners):\n \"\"\"Returns an OrderedDict mapping git patterns from the CODEOWNERS file\n to the corresponding list of files found on the filesystem. It\n unfortunately does not seem possible to invoke git and re-use\n how 'git ignore' and/or 'git attributes' already implement this,\n we must re-invent it.\n \"\"\"\n\n # TODO: filter out files not in \"git ls-files\" (e.g.,\n # twister-out) _if_ the overhead isn't too high for a clean tree.\n #\n # pathlib.match() doesn't support **, so it looks like we can't\n # recursively glob the output of ls-files directly, only real\n # files :-(\n\n pattern2files = collections.OrderedDict()\n top_path = Path(GIT_TOP)\n\n with open(codeowners, \"r\") as codeo:\n for lineno, line in enumerate(codeo, start=1):\n\n if line.startswith(\"#\") or not line.strip():\n continue\n\n match = re.match(r\"^([^\\s,]+)\\s+[^\\s]+\", line)\n if not match:\n self.add_failure(\n \"Invalid CODEOWNERS line %d\\n\\t%s\" %\n (lineno, line))\n continue\n\n git_patrn = match.group(1)\n glob = self.git_pattern_to_glob(git_patrn)\n files = []\n for abs_path in top_path.glob(glob):\n # comparing strings is much faster later\n files.append(str(abs_path.relative_to(top_path)))\n\n if not files:\n self.add_failure(\"Path '{}' not found in the tree but is listed in \"\n \"CODEOWNERS\".format(git_patrn))\n\n pattern2files[git_patrn] = files\n\n return pattern2files", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def read_item(self, item, value_type=\"RAW\", buffer=None):\n if not buffer:\n buffer = self._buffer\n if not buffer:\n buffer = self.allocate_buffer_if_needed()\n return self.accessor.read_item(item, buffer)", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def get_dataset_from_category(category: int, organization: Organization) -> Dataset:\n if category == GroupCategory.ERROR.value:\n return Dataset.Events\n return Dataset.IssuePlatform", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_start_options(flags: list[str], allow_sources: bool) -> Options:\n _, options = mypy.main.process_options(\n [\"-i\"] + flags, require_targets=False, server_options=True\n )\n if options.report_dirs:\n print(\"dmypy: Ignoring report generation settings. Start/restart cannot generate reports.\")\n if options.junit_xml:\n print(\n \"dmypy: Ignoring report generation settings. \"\n \"Start/restart does not support --junit-xml. Pass it to check/recheck instead\"\n )\n options.junit_xml = None\n if not options.incremental:\n sys.exit(\"dmypy: start/restart should not disable incremental mode\")\n if options.follow_imports not in (\"skip\", \"error\", \"normal\"):\n sys.exit(\"dmypy: follow-imports=silent not supported\")\n return options", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def check(self, **kwargs):\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(hostname: Hostname, additional_oois: list[Finding | DNSNSRecord], config: dict[str, Any]) -> Iterator[OOI]:\n no_ipv6_findings = [\n finding\n for finding in additional_oois\n if isinstance(finding, Finding) and finding.finding_type.tokenized.id == \"KAT-NAMESERVER-NO-IPV6\"\n ]\n\n dns_ns_records = [dns_ns_record for dns_ns_record in additional_oois if isinstance(dns_ns_record, DNSNSRecord)]\n\n if len(dns_ns_records) - len(no_ipv6_findings) < 2 and dns_ns_records:\n finding_type = KATFindingType(id=\"KAT-NAMESERVER-NO-TWO-IPV6\")\n yield finding_type\n yield Finding(\n finding_type=finding_type.reference,\n ooi=hostname.reference,\n description=\"This hostname has less than two nameservers with an IPv6 address.\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def EpgCacheSaveCheck(session=None, **kwargs):\n\tglobal epgcachesavecheckpoller\n\tepgcachesavecheckpoller = EpgCacheSaveCheckPoller()\n\tif config.epg.cachesavesched.value:\n\t\tepgcachesavecheckpoller.start()\n\telse:\n\t\tepgcachesavecheckpoller.stop()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def alter_db_table_comment(self, model, old_db_table_comment, new_db_table_comment):\n if self.sql_alter_table_comment and self.connection.features.supports_comments:\n self.execute(\n self.sql_alter_table_comment\n % {\n \"table\": self.quote_name(model._meta.db_table),\n \"comment\": self.quote_value(new_db_table_comment or \"\"),\n }\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def updateService(self, result=None, retval=None, extra_args=None):\n\t\timport process\n\t\tp = process.ProcessList()\n\t\tsabnzbd_processpy = str(p.named('SABnzbd.py')).strip('[]')\n\t\tsabnzbd_processpyc = str(p.named('SABnzbd.pyc')).strip('[]')\n\t\tself['labrun'].hide()\n\t\tself['labstop'].hide()\n\t\tself['labactive'].setText(_(\"Disabled\"))\n\t\tself.my_sabnzbd_active = False\n\t\tself.my_sabnzbd_run = False\n\t\tif fileExists('/etc/rc2.d/S20sabnzbd'):\n\t\t\tself['labactive'].setText(_(\"Enabled\"))\n\t\t\tself['labactive'].show()\n\t\t\tself.my_sabnzbd_active = True\n\t\tif sabnzbd_processpy or sabnzbd_processpyc:\n\t\t\tself.my_sabnzbd_run = True\n\t\tif self.my_sabnzbd_run:\n\t\t\tself['labstop'].hide()\n\t\t\tself['labactive'].show()\n\t\t\tself['labrun'].show()\n\t\t\tself['key_green'].setText(_(\"Stop\"))\n\t\t\tstatus_summary = self['lab2'].text + ' ' + self['labrun'].text\n\t\telse:\n\t\t\tself['labrun'].hide()\n\t\t\tself['labstop'].show()\n\t\t\tself['labactive'].show()\n\t\t\tself['key_green'].setText(_(\"Start\"))\n\t\t\tstatus_summary = self['lab2'].text + ' ' + self['labstop'].text\n\t\ttitle = _(\"SABnzbd Settings\")\n\t\tautostartstatus_summary = self['lab1'].text + ' ' + self['labactive'].text\n\n\t\tfor cb in self.onChangedEntry:\n\t\t\tcb(title, status_summary, autostartstatus_summary)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _factory(\n self,\n *,\n decode_responses: bool,\n is_redis_cluster: bool = False,\n readonly_mode: bool = False,\n hosts: list[dict[Any, Any]] | dict[Any, Any] | None = None,\n client_args: dict[str, Any] | None = None,\n **config: Any,\n ) -> RedisCluster[bytes] | StrictRedis[bytes] | RedisCluster[str] | StrictRedis[str]:\n # StrictRedisCluster expects a list of { host, port } dicts. Coerce the\n # configuration into the correct format if necessary.\n if not hosts:\n hosts = []\n hosts_list = list(hosts.values()) if isinstance(hosts, dict) else hosts\n\n # support for scaling reads using the readonly mode\n # https://redis.io/docs/reference/cluster-spec/#scaling-reads-using-replica-nodes\n\n if not client_args:\n client_args = {}\n\n client_args = {**_REDIS_DEFAULT_CLIENT_ARGS, **client_args}\n\n # Redis cluster does not wait to attempt to connect. We'd prefer to not\n # make TCP connections on boot. Wrap the client in a lazy proxy object.\n def cluster_factory() -> RedisCluster[\n bytes\n ] | StrictRedis[bytes] | RedisCluster[str] | StrictRedis[str]:\n if is_redis_cluster:\n return RetryingRedisCluster(\n # Intentionally copy hosts here because redis-cluster-py\n # mutates the inner dicts and this closure can be run\n # concurrently, as SimpleLazyObject is not threadsafe. This\n # is likely triggered by RetryingRedisCluster running\n # reset() after startup\n #\n # https://github.com/Grokzen/redis-py-cluster/blob/73f27edf7ceb4a408b3008ef7d82dac570ab9c6a/rediscluster/nodemanager.py#L385\n startup_nodes=deepcopy(hosts_list),\n decode_responses=decode_responses,\n skip_full_coverage_check=True,\n max_connections=16,\n max_connections_per_node=True,\n readonly_mode=readonly_mode,\n **client_args,\n )\n else:\n assert len(hosts_list) > 0, \"Hosts should have at least 1 entry\"\n host = dict(hosts_list[0])\n host[\"decode_responses\"] = decode_responses\n return FailoverRedis(**host, **client_args)\n\n # losing some type safety: SimpleLazyObject acts like the underlying type\n return SimpleLazyObject(cluster_factory) # type: ignore[return-value]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def load(fp: IO[str] | IO[bytes], **kwargs: NoReturn) -> Any:\n return loads(fp.read())", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def check_str_arg(result, func, cargs):\n \"\"\"\n This is for the OSRGet[Angular|Linear]Units functions, which\n require that the returned string pointer not be freed. This\n returns both the double and string values.\n \"\"\"\n dbl = result\n ptr = cargs[-1]._obj\n return dbl, ptr.value.decode()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def query(\n selected_columns: list[str],\n query: str | None,\n snuba_params: SnubaParams,\n equations: list[str] | None = None,\n orderby: list[str] | None = None,\n offset: int = 0,\n limit: int = 50,\n referrer: str = \"\",\n auto_fields: bool = False,\n auto_aggregations: bool = False,\n use_aggregate_conditions: bool = False,\n allow_metric_aggregates: bool = False,\n transform_alias_to_input_format: bool = False,\n has_metrics: bool = False,\n functions_acl: list[str] | None = None,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n fallback_to_transactions=False,\n query_source: QuerySource | None = None,\n) -> Any:\n if not selected_columns:\n raise InvalidSearchQuery(\"No columns selected\")\n\n builder = ProfilesQueryBuilder(\n dataset=Dataset.Profiles,\n params={},\n query=query,\n snuba_params=snuba_params,\n selected_columns=selected_columns,\n orderby=orderby,\n limit=limit,\n offset=offset,\n config=QueryBuilderConfig(\n auto_fields=auto_fields,\n auto_aggregations=auto_aggregations,\n use_aggregate_conditions=use_aggregate_conditions,\n transform_alias_to_input_format=transform_alias_to_input_format,\n functions_acl=functions_acl,\n ),\n )\n result = builder.process_results(builder.run_query(referrer, query_source=query_source))\n result[\"meta\"][\"tips\"] = transform_tips(builder.tips)\n return result", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def generate_constructor_for_class(\n cl: ClassIR,\n fn: FuncDecl,\n init_fn: FuncIR | None,\n setup_name: str,\n vtable_name: str,\n emitter: Emitter,\n) -> None:\n \"\"\"Generate a native function that allocates and initializes an instance of a class.\"\"\"\n emitter.emit_line(f\"{native_function_header(fn, emitter)}\")\n emitter.emit_line(\"{\")\n emitter.emit_line(f\"PyObject *self = {setup_name}({emitter.type_struct_name(cl)});\")\n emitter.emit_line(\"if (self == NULL)\")\n emitter.emit_line(\" return NULL;\")\n args = \", \".join([\"self\"] + [REG_PREFIX + arg.name for arg in fn.sig.args])\n if init_fn is not None:\n emitter.emit_line(\n \"char res = {}{}{}({});\".format(\n emitter.get_group_prefix(init_fn.decl),\n NATIVE_PREFIX,\n init_fn.cname(emitter.names),\n args,\n )\n )\n emitter.emit_line(\"if (res == 2) {\")\n emitter.emit_line(\"Py_DECREF(self);\")\n emitter.emit_line(\"return NULL;\")\n emitter.emit_line(\"}\")\n\n # If there is a nontrivial ctor that we didn't define, invoke it via tp_init\n elif len(fn.sig.args) > 1:\n emitter.emit_line(f\"int res = {emitter.type_struct_name(cl)}->tp_init({args});\")\n\n emitter.emit_line(\"if (res < 0) {\")\n emitter.emit_line(\"Py_DECREF(self);\")\n emitter.emit_line(\"return NULL;\")\n emitter.emit_line(\"}\")\n\n emitter.emit_line(\"return self;\")\n emitter.emit_line(\"}\")", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def render_to_html(self, label: LabelTemplate, instance, request, **kwargs):\n \"\"\"Render this label to HTML format.\n\n Arguments:\n label: The LabelTemplate object to render against\n instance: The model instance to render\n request: The HTTP request object which triggered this print job\n \"\"\"\n try:\n return label.render_as_string(instance, request)\n except Exception:\n log_error('label.render_to_html')\n raise ValidationError(_('Error rendering label to HTML'))", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def get_pons(self, case_id: str) -> list[str]:\n \"\"\"Return list of panel of normals used for analysis.\"\"\"\n return []", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def run(boefje_meta: BoefjeMeta) -> list[tuple[set, bytes | str]]:\n return [(set(), b\"dummy-data\")]", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def Plugins(**kwargs):\n\tif YoutubeDL:\n\t\treturn [PluginDescriptor(name=\"YTDLPWrapper\", description=\"YTDLPWrapper\", where=PluginDescriptor.WHERE_PLAYSERVICE, needsRestart=False, fnc=playService)]\n\telse:\n\t\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def process_exception(self, request, exception):\n return HttpResponse(\"Exception caught\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get(self, key, **kwargs):\n return self.__lookup[key]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_view(self, request, view_func, view_args, view_kwargs):\n template = engines[\"django\"].from_string(\n \"Processed view {{ view }}{% for m in mw %}\\n{{ m }}{% endfor %}\"\n )\n return TemplateResponse(\n request,\n template,\n {\"mw\": [self.__class__.__name__], \"view\": view_func.__name__},\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(input_ooi: FindingType, additional_oois: list, config: dict[str, Any]) -> Iterator[OOI]:\n value_set = False\n if not input_ooi.risk_severity:\n input_ooi.risk_severity = RiskLevelSeverity.PENDING\n value_set = True\n if not input_ooi.risk_score:\n input_ooi.risk_score = 0\n value_set = True\n if value_set:\n yield input_ooi", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def close(self, delete: bool = False) -> None:\n if self.closed:\n return\n self._f.close()\n os.replace(self._tmp_filename, self._real_filename)\n self.closed = True", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_assignee_email(\n integration: RpcIntegration | Integration,\n assignee: Mapping[str, str],\n) -> str | None:\n \"\"\"Get email from `assignee`.\"\"\"\n return assignee.get(\"emailAddress\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def render_to_pdf(self, label: LabelTemplate, instance, request, **kwargs):\n \"\"\"Render this label to PDF format.\n\n Arguments:\n label: The LabelTemplate object to render against\n instance: The model instance to render\n request: The HTTP request object which triggered this print job\n \"\"\"\n try:\n return label.render(instance, request)\n except Exception:\n log_error('label.render_to_pdf')\n raise ValidationError(_('Error rendering label to PDF'))", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def references_index(self, table, index):\n \"\"\"\n Return whether or not this instance references the specified index.\n \"\"\"\n return False", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _get_desktop_browser_performance_profiles(organization: Organization) -> list[dict[str, Any]]:\n return [\n {\n \"name\": \"Chrome\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.30,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.15,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": True,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Chrome\",\n },\n },\n {\n \"name\": \"Firefox\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.30,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": True, # Only available on Firefox 122 and beyond\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.0,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": False,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Firefox\",\n },\n },\n {\n \"name\": \"Safari\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.0,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": False,\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.0,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": False,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Safari\",\n },\n },\n {\n \"name\": \"Edge\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.30,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.15,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": True,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Edge\",\n },\n },\n {\n \"name\": \"Opera\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.30,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.15,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": True,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Opera\",\n },\n },\n {\n \"name\": \"Chrome INP\",\n \"scoreComponents\": [\n {\n \"measurement\": \"inp\",\n \"weight\": 1.0,\n \"p10\": 200.0,\n \"p50\": 500.0,\n \"optional\": False,\n },\n ],\n \"condition\": {\n \"op\": \"or\",\n \"inner\": [\n {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Chrome\",\n },\n {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Google Chrome\",\n },\n ],\n },\n },\n {\n \"name\": \"Edge INP\",\n \"scoreComponents\": [\n {\n \"measurement\": \"inp\",\n \"weight\": 1.0,\n \"p10\": 200.0,\n \"p50\": 500.0,\n \"optional\": False,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Edge\",\n },\n },\n {\n \"name\": \"Opera INP\",\n \"scoreComponents\": [\n {\n \"measurement\": \"inp\",\n \"weight\": 1.0,\n \"p10\": 200.0,\n \"p50\": 500.0,\n \"optional\": False,\n },\n ],\n \"condition\": {\n \"op\": \"eq\",\n \"name\": \"event.contexts.browser.name\",\n \"value\": \"Opera\",\n },\n },\n ]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _get_windows_console_stream(\n f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]\n ) -> t.Optional[t.TextIO]:\n return None", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def execute_cmd(cmd, filename, lineno, stdout_log=False, debug=False):\n '''\n Executes a command, checks for segfaults and returns the command exit\n code.\n\n :param cmd: string with the command to be executed\n :param filename: name of the file tested (used for print_error purposes)\n :param lineno: line number being tested (used for print_error purposes)\n :param stdout_log: redirect stdout to this file instead of global log_file\n :param debug: temporarily set these debug flags\n '''\n global log_file\n print(\"command: {}\".format(cmd), file=log_file)\n if debug_option:\n print(cmd)\n\n if debug:\n debug_old = nftables.get_debug()\n nftables.set_debug(debug)\n\n ret, out, err = nftables.cmd(cmd)\n\n if not stdout_log:\n stdout_log = log_file\n\n stdout_log.write(out)\n stdout_log.flush()\n log_file.write(err)\n log_file.flush()\n\n if debug:\n nftables.set_debug(debug_old)\n\n return ret", "smellKey": "S1172", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-mr", "language": "python"} {"function": "def post_process(self, paths, dry_run=False, **options):\n \"\"\"\n Post process the given dictionary of files (called from collectstatic).\n\n Processing is actually two separate operations:\n\n 1. renaming files to include a hash of their content for cache-busting,\n and copying those files to the target storage.\n 2. adjusting files which contain references to other files so they\n refer to the cache-busting filenames.\n\n If either of these are performed on a file, then that file is considered\n post-processed.\n \"\"\"\n # don't even dare to process the files if we're in dry run mode\n if dry_run:\n return\n\n # where to store the new paths\n hashed_files = {}\n\n # build a list of adjustable files\n adjustable_paths = [\n path for path in paths if matches_patterns(path, self._patterns)\n ]\n\n # Adjustable files to yield at end, keyed by the original path.\n processed_adjustable_paths = {}\n\n # Do a single pass first. Post-process all files once, yielding not\n # adjustable files and exceptions, and collecting adjustable files.\n for name, hashed_name, processed, _ in self._post_process(\n paths, adjustable_paths, hashed_files\n ):\n if name not in adjustable_paths or isinstance(processed, Exception):\n yield name, hashed_name, processed\n else:\n processed_adjustable_paths[name] = (name, hashed_name, processed)\n\n paths = {path: paths[path] for path in adjustable_paths}\n unresolved_paths = []\n for i in range(self.max_post_process_passes):\n unresolved_paths = []\n for name, hashed_name, processed, subst in self._post_process(\n paths, adjustable_paths, hashed_files\n ):\n # Overwrite since hashed_name may be newer.\n processed_adjustable_paths[name] = (name, hashed_name, processed)\n if subst:\n unresolved_paths.append(name)\n\n if not unresolved_paths:\n break\n\n if unresolved_paths:\n problem_paths = \", \".join(sorted(unresolved_paths))\n yield problem_paths, None, RuntimeError(\"Max post-process passes exceeded.\")\n\n # Store the processed paths\n self.hashed_files.update(hashed_files)\n\n # Yield adjustable files with final, hashed name.\n yield from processed_adjustable_paths.values()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def create_organization_join_request(organization, email, ip_address=None):\n with outbox_context(flush=False):\n om = OrganizationMember.objects.filter(\n Q(email__iexact=email)\n | Q(user_is_active=True, user_email__iexact=email, user_id__isnull=False),\n organization=organization,\n ).first()\n if om:\n return\n\n try:\n om = OrganizationMember.objects.create(\n organization_id=organization.id,\n role=organization.default_role,\n email=email,\n invite_status=InviteStatus.REQUESTED_TO_JOIN.value,\n )\n except IntegrityError:\n pass\n\n return om", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:\n self.writeline(\"continue\", node)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def on_host_error(self, host, error, result):\n if settings.DEBUG_DEV:\n print('host error: {} -> {}'.format(host, error))", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def run(input_ooi: HTTPHeader, additional_oois: list, config: dict[str, Any]) -> Iterator[OOI]:\n header = input_ooi\n if header.key.lower() != \"server\":\n return\n\n if \"Apache/2.4.49\" in header.value or \"Apache/2.4.50\" in header.value:\n finding_type = CVEFindingType(id=\"CVE-2021-41773\")\n yield finding_type\n yield Finding(finding_type=finding_type.reference, ooi=header.reference, description=\"Bad apache version\")", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [PluginDescriptor(name=\"SocketMMI\", description=_(\"Python frontend for /tmp/mmi.socket\"), where=PluginDescriptor.WHERE_MENU, needsRestart=True, fnc=menu),\n\t\tPluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, needsRestart=True, fnc=sessionstart),\n\t\tPluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, needsRestart=True, fnc=autostart)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def remember(self, request, userid, **kw):\n # No-op.\n return []", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def _not_modified(request, response=None):\n new_response = HttpResponseNotModified()\n if response:\n # Preserve the headers required by RFC 9110 Section 15.4.5, as well as\n # Last-Modified.\n for header in (\n \"Cache-Control\",\n \"Content-Location\",\n \"Date\",\n \"ETag\",\n \"Expires\",\n \"Last-Modified\",\n \"Vary\",\n ):\n if header in response:\n new_response.headers[header] = response.headers[header]\n\n # Preserve cookies as per the cookie specification: \"If a proxy server\n # receives a response which contains a Set-cookie header, it should\n # propagate the Set-cookie header to the client, regardless of whether\n # the response was 304 (Not Modified) or 200 (OK).\n # https://curl.haxx.se/rfc/cookie_spec.html\n new_response.cookies = response.cookies\n return new_response", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def allow_relation(self, obj1, obj2, **hints):\n \"Allow any relation if a model in Auth is involved\"\n return obj1._meta.app_label == \"auth\" or obj2._meta.app_label == \"auth\" or None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n network = Network(name=raw.decode())\n\n yield network", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def run(input_ooi: Hostname, additional_oois: list[DMARCTXTRecord | NXDOMAIN], config: dict[str, Any]) -> Iterator[OOI]:\n dmarc_records = [ooi for ooi in additional_oois if isinstance(ooi, DMARCTXTRecord)]\n nxdomains = (ooi for ooi in additional_oois if isinstance(ooi, NXDOMAIN))\n\n if any(nxdomains):\n return\n\n # only report finding when there is no DMARC record\n if (\n not tldextract.extract(input_ooi.name).subdomain\n and tldextract.extract(input_ooi.name).domain\n and not dmarc_records\n ):\n ft = KATFindingType(id=\"KAT-NO-DMARC\")\n yield ft\n yield Finding(\n ooi=input_ooi.reference, finding_type=ft.reference, description=\"This hostname does not have a DMARC record\"\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def write_interface_base(self, data, extra=None):\n self.written_raw_data_time = datetime.now(timezone.utc)\n self.written_raw_data = data\n self.bytes_written += len(data)\n if self.stream_log_pair:\n self.stream_log_pair.write_log.write(data)", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def get_paginate_by(self, queryset):\n \"\"\"\n Get the number of items to paginate by, or ``None`` for no pagination.\n \"\"\"\n return self.paginate_by", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def extend(self, *args, **kwargs):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def file_response(request):\n f1 = BytesIO(b\"test1\")\n f2 = BytesIO(b\"test2\")\n response = FileResponse(f1)\n response._resource_closers.append(f2.close)\n FILE_RESPONSE_HOLDER[\"response\"] = response\n FILE_RESPONSE_HOLDER[\"buffers\"] = (f1, f2)\n return response", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def segments(self, node):\n self.in_cablegroup_ = False\n self.points_ = []\n self.cables_ = []\n self.cable_ = None\n self.id = -1\n self.cid = -1\n self.pid = -1\n self.nprox = 0\n self.cableid2index_ = {}\n self.ptid2pt_ = {}\n self.cablegroups_ = []\n self.groupname2index_ = {}", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [PluginDescriptor(where=[PluginDescriptor.WHERE_AUTOSTART, PluginDescriptor.WHERE_SESSIONSTART], fnc=sessionstart), PluginDescriptor(name=\"FRQ Setup\", description=\"Set CPU speed settings\", where=PluginDescriptor.WHERE_MENU, fnc=main)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def http404_error_handler(\n request: Request, # pylint: disable=unused-argument\n error: CustomResourceUsageTrackerError,\n) -> JSONResponse:\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": f\"{error.msg_template}\"},\n )", "smellKey": "S1172", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def query_facet_performance_key_histogram(\n snuba_params: SnubaParams,\n top_tags: list[Any],\n tag_key: str,\n num_buckets_per_key: int,\n limit: int,\n referrer: str,\n aggregate_column: str,\n filter_query: str | None = None,\n) -> dict:\n precision = 0\n\n tag_values = [x[\"tags_value\"] for x in top_tags]\n\n results = discover.histogram_query(\n fields=[aggregate_column],\n user_query=filter_query,\n snuba_params=snuba_params,\n num_buckets=num_buckets_per_key,\n precision=precision,\n group_by=[\"tags_value\", \"tags_key\"],\n extra_conditions=[\n Condition(Column(\"tags_key\"), Op.EQ, tag_key),\n Condition(Column(\"tags_value\"), Op.IN, tag_values),\n ],\n histogram_rows=limit,\n referrer=\"api.organization-events-facets-performance-histogram\",\n normalize_results=False,\n )\n return results", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def inode_op(self, inodes, locked_ops):\n return True", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def write_serializable(self, value, logical_name=\"\") -> None:\n value.serialize(self)", "smellKey": "S1172", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def migrate_to_version_11_4(json_flow, flow=None):\n \"\"\"\n Replaces @flow.foo.text with @step.value for non-waiting rulesets, to bring old world functionality inline with the\n new engine, where @run.results.foo.input is always the router operand.\n \"\"\"\n # figure out which rulesets aren't waits\n rule_sets = json_flow.get(\"rule_sets\", [])\n non_waiting = {Flow.label_to_slug(r[\"label\"]) for r in rule_sets if not r[\"ruleset_type\"].startswith(\"wait_\")}\n\n # make a regex that matches a context reference to the .text on any result from these\n replace_pattern = r\"flow\\.(\" + \"|\".join(non_waiting) + r\")\\.text\"\n replace_regex = regex.compile(replace_pattern, flags=regex.UNICODE | regex.IGNORECASE | regex.MULTILINE)\n replace_with = \"step.value\"\n\n # for every action in this flow, replace such references with @step.text\n for actionset in json_flow.get(\"action_sets\", []):\n for action in actionset.get(\"actions\", []):\n if action[\"type\"] in [\"reply\", \"send\", \"say\", \"email\"]:\n msg = action[\"msg\"]\n if isinstance(msg, str):\n action[\"msg\"] = replace_regex.sub(replace_with, msg)\n else:\n for lang, text in msg.items():\n msg[lang] = replace_regex.sub(replace_with, text or \"\")\n\n return json_flow", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def stored_claims(self, claims=None):\n return {}", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def h_md5crypt(phrase, rounds, salt):\n expected = MD5_CRYPT.using(\n salt=salt\n ).hash(phrase)\n setting = expected[:expected.rfind('$')]\n yield (phrase, setting, expected)", "smellKey": "S1172", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l4", "language": "python"} {"function": "def csrf_failure(request, reason=\"\"):\n from django.shortcuts import reverse\n login_url = reverse('authentication:login') + '?csrf_failure=1&admin=1'\n return redirect(login_url)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def last_insert_id(self, cursor, table_name, pk_name):\n \"\"\"\n Given a cursor object that has just performed an INSERT statement into\n a table that has an auto-incrementing ID, return the newly created ID.\n\n `pk_name` is the name of the primary-key column.\n \"\"\"\n return cursor.lastrowid", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _process_token(cls, token):\n \"\"\"Preprocess the token component of a token definition.\"\"\"\n assert type(token) is _TokenType or callable(token), \\\n 'token type must be simple type or callable, not %r' % (token,)\n return token", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [\n\t\tPluginDescriptor(name=_(\"Media scanner\"), description=_(\"Scan files...\"), where=PluginDescriptor.WHERE_PLUGINMENU, icon=\"MediaScanner.png\", needsRestart=True, fnc=main),\n#\t\tPluginDescriptor(where = PluginDescriptor.WHERE_MENU, fnc=menuHook),\n\t\tPluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, needsRestart=True, fnc=sessionstart),\n\t\tPluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, needsRestart=True, fnc=autostart)\n\t\t]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def setup_databases(\n verbosity,\n interactive,\n *,\n time_keeper=None,\n keepdb=False,\n debug_sql=False,\n parallel=0,\n aliases=None,\n serialized_aliases=None,\n **kwargs,\n):\n \"\"\"Create the test databases.\"\"\"\n if time_keeper is None:\n time_keeper = NullTimeKeeper()\n\n test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases)\n\n old_names = []\n\n for db_name, aliases in test_databases.values():\n first_alias = None\n for alias in aliases:\n connection = connections[alias]\n old_names.append((connection, db_name, first_alias is None))\n\n # Actually create the database for the first connection\n if first_alias is None:\n first_alias = alias\n with time_keeper.timed(\" Creating '%s'\" % alias):\n serialize_alias = (\n serialized_aliases is None or alias in serialized_aliases\n )\n connection.creation.create_test_db(\n verbosity=verbosity,\n autoclobber=not interactive,\n keepdb=keepdb,\n serialize=serialize_alias,\n )\n if parallel > 1:\n for index in range(parallel):\n with time_keeper.timed(\" Cloning '%s'\" % alias):\n connection.creation.clone_test_db(\n suffix=str(index + 1),\n verbosity=verbosity,\n keepdb=keepdb,\n )\n # Configure all other connections as mirrors of the first one\n else:\n connections[alias].creation.set_as_test_mirror(\n connections[first_alias].settings_dict\n )\n\n # Configure the test mirrors.\n for alias, mirror_alias in mirrored_aliases.items():\n connections[alias].creation.set_as_test_mirror(\n connections[mirror_alias].settings_dict\n )\n\n if debug_sql:\n for alias in connections:\n connections[alias].force_debug_cursor = True\n\n return old_names", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def clear(self, *identifiers):\n return None", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def closePinCorrect(self, *args):\n\t\tself.setTries(3)\n\t\tself.close(True)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_workflow_metrics(self, metric_id: str) -> dict:\n \"\"\"Get nf-core workflow metrics constants.\"\"\"\n return {}", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def add_send_to_generator_class(\n builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> None:\n \"\"\"Generates the 'send' method for a generator class.\"\"\"\n with builder.enter_method(fn_info.generator_class.ir, \"send\", object_rprimitive, fn_info):\n arg = builder.add_argument(\"arg\", object_rprimitive)\n none_reg = builder.none_object()\n # Call the helper function with error flags set to Py_None, and return that result.\n result = builder.add(\n Call(\n fn_decl,\n [builder.self(), none_reg, none_reg, none_reg, builder.read(arg)],\n fn_info.fitem.line,\n )\n )\n builder.add(Return(result))", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def add_commit(self, *args, **kwargs) -> None:\n return None", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def run(url: URL, additional_oois: list, config: dict[str, Any]) -> Iterator[OOI]:\n if url.raw.scheme == \"http\" or url.raw.scheme == \"https\":\n port = url.raw.port\n if port is None:\n if url.raw.scheme == \"https\":\n port = 443\n elif url.raw.scheme == \"http\":\n port = 80\n\n path = url.raw.path if url.raw.path is not None else \"/\"\n\n default_args = {\"network\": url.network, \"scheme\": WebScheme(url.raw.scheme), \"port\": port, \"path\": path}\n try:\n addr = ip_address(url.raw.host)\n except ValueError:\n hostname = Hostname(network=url.network, name=url.raw.host)\n hostname_url = HostnameHTTPURL(netloc=hostname.reference, **default_args)\n original_url = URL(network=url.network, raw=url.raw, web_url=hostname_url.reference)\n yield hostname\n yield hostname_url\n yield original_url\n else:\n if isinstance(addr, IPv4Address):\n ip = IPAddressV4(network=url.network, address=addr)\n ip_url = IPAddressHTTPURL(netloc=ip.reference, **default_args)\n original_url = URL(network=url.network, raw=url.raw, web_url=ip_url.reference)\n yield ip\n yield ip_url\n yield original_url\n else:\n ip = IPAddressV6(network=url.network, address=addr)\n ip_url = IPAddressHTTPURL(netloc=ip.reference, **default_args)\n original_url = URL(network=url.network, raw=url.raw, web_url=ip_url.reference)\n yield ip\n yield ip_url\n yield original_url", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def get_log_kwargs(self, record, logger):\n kwargs = {k: v for k, v in vars(record).items() if k not in throwaways and v is not None}\n kwargs.update({\"level\": record.levelno, \"event\": record.msg})\n\n if record.args:\n # record.args inside of LogRecord.__init__ gets unrolled\n # if it's the shape `({},)`, a single item dictionary.\n # so we need to check for this, and re-wrap it because\n # down the line of structlog, it's expected to be this\n # original shape.\n if isinstance(record.args, (tuple, list)):\n kwargs[\"positional_args\"] = record.args\n else:\n kwargs[\"positional_args\"] = (record.args,)\n\n return kwargs", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_transitions(self, issue_key):\n return self._get_stub_data(\"transition_response.json\")[\"transitions\"]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def update_catalogs(resources=None, languages=None):\n \"\"\"\n Update the en/LC_MESSAGES/django.po (main and contrib) files with\n new/updated translatable strings.\n \"\"\"\n settings.configure()\n django.setup()\n if resources is not None:\n print(\"`update_catalogs` will always process all resources.\")\n contrib_dirs = _get_locale_dirs(None, include_core=False)\n\n os.chdir(os.path.join(os.getcwd(), \"django\"))\n print(\"Updating en catalogs for Django and contrib apps...\")\n call_command(\"makemessages\", locale=[\"en\"])\n print(\"Updating en JS catalogs for Django and contrib apps...\")\n call_command(\"makemessages\", locale=[\"en\"], domain=\"djangojs\")\n\n # Output changed stats\n _check_diff(\"core\", os.path.join(os.getcwd(), \"conf\", \"locale\"))\n for name, dir_ in contrib_dirs:\n _check_diff(name, dir_)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(input_ooi: TLSCipher, additional_oois, config) -> Iterator[OOI]:\n # Get the highest severity and all reasons for the cipher suite\n highest_severity, all_reasons = get_highest_severity_and_all_reasons(input_ooi.suites)\n\n # If no severity is found, return an empty list\n if not highest_severity:\n return\n\n if highest_severity in SEVERITY_TO_ID:\n ft = KATFindingType(id=SEVERITY_TO_ID[highest_severity])\n yield ft\n yield Finding(\n finding_type=ft.reference,\n ooi=input_ooi.reference,\n description=f\"One or more of the cipher suites should not be used because:\\n{all_reasons}\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def runner_on_failed(self, event_data, host=None, task=None, res=None, **kwargs):\n detail = {\n \"action\": event_data.get(\"task_action\", \"\"),\n \"res\": res,\n \"rc\": res.get(\"rc\", 0),\n \"stdout\": res.get(\"stdout\", \"\"),\n \"stderr\": \";\".join([res.get(\"stderr\", \"\"), res.get(\"msg\", \"\")]).strip(\";\"),\n }\n ignore_errors = event_data.get(\"ignore_errors\", False)\n error_key = \"ignored\" if ignore_errors else \"failures\"\n self.result[error_key][host][task] = detail", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def migrate_to_version_11_8(json_flow, flow=None):\n \"\"\"\n Fixes duplicate rule UUIDs\n \"\"\"\n seen_uuids = set()\n\n for rs in json_flow.get(\"rule_sets\", []):\n for rule in rs.get(\"rules\"):\n if rule.get(\"uuid\") in seen_uuids or not rule.get(\"uuid\"):\n rule[\"uuid\"] = str(uuid4())\n seen_uuids.add(rule[\"uuid\"])\n\n return json_flow", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def db_for_write(self, model, **hints):\n \"Point all operations on auth models to 'other'\"\n if model._meta.app_label == \"auth\":\n return \"other\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_keys_for_row(self, row):\n return [(\"session.status\", key) for key in [\"healthy\", \"abnormal\", \"crashed\", \"errored\"]]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def pre_save(self, model_instance, add):\n \"\"\"Return field's value just before saving.\"\"\"\n return getattr(model_instance, self.attname)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def flash(self, **kwargs) -> None:\n self.require(str(self._cli))\n\n # prepare base command\n cmd = [str(self._cli)]\n\n connect_opts = f\"port={self._port}\"\n if self._frequency:\n connect_opts += f\" freq={self._frequency}\"\n if self._reset_mode:\n reset_mode = STM32CubeProgrammerBinaryRunner._RESET_MODES[self._reset_mode]\n connect_opts += f\" reset={reset_mode}\"\n if self._conn_modifiers:\n connect_opts += f\" {self._conn_modifiers}\"\n\n cmd += [\"--connect\", connect_opts]\n cmd += self._tool_opt\n\n # erase first if requested\n if self._erase:\n self.check_call(cmd + [\"--erase\", \"all\"])\n\n # flash image and run application\n dl_file = self.cfg.elf_file if self._use_elf else self.cfg.hex_file\n if dl_file is None:\n raise RuntimeError(f'cannot flash; no download file was specified')\n elif not os.path.isfile(dl_file):\n raise RuntimeError(f'download file {dl_file} does not exist')\n self.check_call(cmd + [\"--download\", dl_file, \"--start\"])", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def get_price(\n instance,\n quantity,\n moq=True,\n multiples=True,\n currency=None,\n break_name: str = 'price_breaks',\n):\n \"\"\"Calculate the price based on quantity price breaks.\n\n - Don't forget to add in flat-fee cost (base_cost field)\n - If MOQ (minimum order quantity) is required, bump quantity\n - If order multiples are to be observed, then we need to calculate based on that, too\n \"\"\"\n from common.currency import currency_code_default\n\n if hasattr(instance, break_name):\n price_breaks = getattr(instance, break_name).all()\n else:\n price_breaks = []\n\n # No price break information available?\n if len(price_breaks) == 0:\n return None\n\n # Check if quantity is fraction and disable multiples\n multiples = quantity % 1 == 0\n\n # Order multiples\n if multiples:\n quantity = int(math.ceil(quantity / instance.multiple) * instance.multiple)\n\n pb_found = False\n pb_quantity = -1\n pb_cost = 0.0\n\n if currency is None:\n # Default currency selection\n currency = currency_code_default()\n\n pb_min = None\n for pb in price_breaks:\n # Store smallest price break\n if not pb_min:\n pb_min = pb\n\n # Ignore this pricebreak (quantity is too high)\n if pb.quantity > quantity:\n continue\n\n pb_found = True\n\n # If this price-break quantity is the largest so far, use it!\n if pb.quantity > pb_quantity:\n pb_quantity = pb.quantity\n\n # Convert everything to the selected currency\n pb_cost = pb.convert_to(currency)\n\n # Use smallest price break\n if not pb_found and pb_min:\n # Update price break information\n pb_quantity = pb_min.quantity\n pb_cost = pb_min.convert_to(currency)\n # Trigger cost calculation using smallest price break\n pb_found = True\n\n # Convert quantity to decimal.Decimal format\n quantity = decimal.Decimal(f'{quantity}')\n\n if pb_found:\n cost = pb_cost * quantity\n return InvenTree.helpers.normalize(cost + instance.base_cost)\n return None", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def migrate_export_to_version_11_0(json_export, org, same_site=True):\n \"\"\"\n Introduces the concept of format_location and format_date. This migration\n wraps all references to rulesets or contact fields which are locations or dates and\n wraps them appropriately\n \"\"\"\n replacements = [\n [r\"@date([^0-9a-zA-Z\\.]|\\.[^0-9a-zA-Z\\.]|$|\\.$)\", r\"@(format_date(date))\\1\"],\n [r\"@date\\.now\", r\"@(format_date(date.now))\"],\n ]\n\n # get all contact fields that are date or location for this org\n fields = ContactField.user_fields.filter(org=org, is_active=True, value_type__in=[\"D\", \"S\", \"I\", \"W\"]).only(\n \"id\", \"value_type\", \"key\"\n )\n\n for cf in fields:\n format_function = \"format_date\" if cf.value_type == \"D\" else \"format_location\"\n replacements.append(\n [\n r\"@contact\\.%s([^0-9a-zA-Z\\.]|\\.[^0-9a-zA-Z\\.]|$|\\.$)\" % cf.key,\n r\"@(%s(contact.%s))\\1\" % (format_function, cf.key),\n ]\n )\n\n for flow in json_export.get(\"flows\", []):\n # figure out which rulesets are date or location\n for rs in flow.get(\"rule_sets\", []):\n rs_type = None\n for rule in rs.get(\"rules\", []):\n test = rule.get(\"test\", {}).get(\"type\")\n if not test: # pragma: no cover\n continue\n elif test == \"true\":\n continue\n elif not rs_type:\n rs_type = test\n elif rs_type and test != rs_type:\n rs_type = \"none\"\n\n if rs[\"label\"] is None:\n continue\n\n key = Flow.label_to_slug(rs[\"label\"])\n\n # any reference to this result value's time property needs wrapped in format_date\n replacements.append([r\"@flow\\.%s\\.time\" % key, r\"@(format_date(flow.%s.time))\" % key])\n\n # how we wrap the actual result value depends on its type\n if rs_type in [\"date\", \"date_before\", \"date_after\", \"date_equal\"]:\n format_function = \"format_date\"\n elif rs_type in [\"state\", \"district\", \"ward\"]:\n format_function = \"format_location\"\n else: # pragma: no cover\n continue\n\n replacements.append(\n [\n r\"@flow\\.%s([^0-9a-zA-Z\\.]|\\.[^0-9a-zA-Z\\.]|$|\\.$)\" % key,\n r\"@(%s(flow.%s))\\1\" % (format_function, key),\n ]\n )\n\n # for every action in this flow, look for replies, sends or says that use these fields and wrap them\n for actionset in flow.get(\"action_sets\", []):\n for action in actionset.get(\"actions\", []):\n if action[\"type\"] in [\"reply\", \"send\", \"say\"]:\n msg = action[\"msg\"]\n for lang, text in msg.items():\n # some single message flows erroneously ended up with dicts inside dicts\n if isinstance(text, dict):\n text = next(iter(text.values()))\n\n migrated_text = text\n if isinstance(migrated_text, str):\n for pattern, replacement in replacements:\n migrated_text = regex.sub(\n pattern, replacement, migrated_text, flags=regex.UNICODE | regex.MULTILINE\n )\n\n msg[lang] = migrated_text\n\n return json_export", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def dt_node_has_prop(kconf, _, label, prop):\n \"\"\"\n This function takes a 'label' and looks for an EDT node for that label. If\n it finds an EDT node, it will look to see if that node has a property\n by the name of 'prop'. If the 'prop' exists it will return \"y\" otherwise\n we return \"n\".\n \"\"\"\n\n if doc_mode or edt is None:\n return \"n\"\n\n try:\n node = edt.label2node.get(label)\n except edtlib.EDTError:\n return \"n\"\n\n if node is None:\n return \"n\"\n\n if prop in node.props:\n return \"y\"\n\n return \"n\"", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def check_namedtuple_classdef(\n self, defn: ClassDef, is_stub_file: bool\n ) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None:\n \"\"\"Parse and validate fields in named tuple class definition.\n\n Return a four tuple:\n * field names\n * field types\n * field default values\n * valid statements\n or None, if any of the types are not ready.\n \"\"\"\n if len(defn.base_type_exprs) > 1:\n self.fail(\"NamedTuple should be a single base\", defn)\n items: list[str] = []\n types: list[Type] = []\n default_items: dict[str, Expression] = {}\n statements: list[Statement] = []\n for stmt in defn.defs.body:\n statements.append(stmt)\n if not isinstance(stmt, AssignmentStmt):\n # Still allow pass or ... (for empty namedtuples).\n if isinstance(stmt, PassStmt) or (\n isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n ):\n continue\n # Also allow methods, including decorated ones.\n if isinstance(stmt, (Decorator, FuncBase)):\n continue\n # And docstrings.\n if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):\n continue\n statements.pop()\n defn.removed_statements.append(stmt)\n self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):\n # An assignment, but an invalid one.\n statements.pop()\n defn.removed_statements.append(stmt)\n self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n else:\n # Append name and type in this case...\n name = stmt.lvalues[0].name\n items.append(name)\n if stmt.type is None:\n types.append(AnyType(TypeOfAny.unannotated))\n else:\n # We never allow recursive types at function scope. Although it is\n # possible to support this for named tuples, it is still tricky, and\n # it would be inconsistent with type aliases.\n analyzed = self.api.anal_type(\n stmt.type,\n allow_placeholder=not self.api.is_func_scope(),\n prohibit_self_type=\"NamedTuple item type\",\n )\n if analyzed is None:\n # Something is incomplete. We need to defer this named tuple.\n return None\n types.append(analyzed)\n # ...despite possible minor failures that allow further analyzis.\n if name.startswith(\"_\"):\n self.fail(\n f\"NamedTuple field name cannot start with an underscore: {name}\", stmt\n )\n if stmt.type is None or hasattr(stmt, \"new_syntax\") and not stmt.new_syntax:\n self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n elif isinstance(stmt.rvalue, TempNode):\n # x: int assigns rvalue to TempNode(AnyType())\n if default_items:\n self.fail(\n \"Non-default NamedTuple fields cannot follow default fields\", stmt\n )\n else:\n default_items[name] = stmt.rvalue\n if defn.keywords:\n for_function = ' for \"__init_subclass__\" of \"NamedTuple\"'\n for key in defn.keywords:\n self.msg.unexpected_keyword_argument_for_function(for_function, key, defn)\n return items, types, default_items, statements", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def inclusion_tag(self, filename, func=None, takes_context=None, name=None):\n \"\"\"\n Register a callable as an inclusion tag:\n\n @register.inclusion_tag('results.html')\n def show_results(poll):\n choices = poll.choice_set.all()\n return {'choices': choices}\n \"\"\"\n\n def dec(func):\n (\n params,\n varargs,\n varkw,\n defaults,\n kwonly,\n kwonly_defaults,\n _,\n ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n\n @wraps(func)\n def compile_func(parser, token):\n bits = token.split_contents()[1:]\n args, kwargs = parse_bits(\n parser,\n bits,\n params,\n varargs,\n varkw,\n defaults,\n kwonly,\n kwonly_defaults,\n takes_context,\n function_name,\n )\n return InclusionNode(\n func,\n takes_context,\n args,\n kwargs,\n filename,\n )\n\n self.tag(function_name, compile_func)\n return func\n\n return dec", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def register_type_handlers(connection, **kwargs):\n if connection.vendor != \"postgresql\" or connection.alias == NO_DB_ALIAS:\n return\n\n oids, array_oids = get_hstore_oids(connection.alias)\n for oid, array_oid in zip(oids, array_oids):\n ti = TypeInfo(\"hstore\", oid, array_oid)\n hstore.register_hstore(ti, connection.connection)\n\n _, citext_oids = get_citext_oids(connection.alias)\n for array_oid in citext_oids:\n ti = TypeInfo(\"citext\", 0, array_oid)\n ti.register(connection.connection)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_obj(model, req, error=None): # noqa: ARG001\n kwargs = req if isinstance(req, dict) else {\"id\": req}\n return model.obj.get(**kwargs)", "smellKey": "S1172", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def plugin(version: str) -> type[ClassMethodPlugin]:\n return ClassMethodPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def timeseries_query(\n selected_columns: list[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str,\n zerofill_results: bool = True,\n allow_metric_aggregates=True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n has_metrics: bool = True,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n groupby: Column | None = None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n\n metrics_query = TimeseriesProfileFunctionsMetricsQueryBuilder(\n {},\n rollup,\n snuba_params=snuba_params,\n dataset=Dataset.PerformanceMetrics,\n query=query,\n selected_columns=selected_columns,\n groupby=groupby,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n allow_metric_aggregates=allow_metric_aggregates,\n use_metrics_layer=use_metrics_layer,\n ),\n )\n result = metrics_query.run_query(referrer, query_source=query_source)\n\n result = metrics_query.process_results(result)\n result[\"data\"] = (\n discover.zerofill(\n result[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else result[\"data\"]\n )\n\n result[\"meta\"][\"isMetricsData\"] = True\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"isMetricsData\": True,\n \"meta\": result[\"meta\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_scheme(\n dist_name: str,\n user: bool = False,\n home: typing.Optional[str] = None,\n root: typing.Optional[str] = None,\n isolated: bool = False,\n prefix: typing.Optional[str] = None,\n) -> Scheme:\n \"\"\"\n Get the \"scheme\" corresponding to the input parameters.\n\n :param dist_name: the name of the package to retrieve the scheme for, used\n in the headers scheme path\n :param user: indicates to use the \"user\" scheme\n :param home: indicates to use the \"home\" scheme\n :param root: root under which other directories are re-based\n :param isolated: ignored, but kept for distutils compatibility (where\n this controls whether the user-site pydistutils.cfg is honored)\n :param prefix: indicates to use the \"prefix\" scheme and provides the\n base directory for the same\n \"\"\"\n if user and prefix:\n raise InvalidSchemeCombination(\"--user\", \"--prefix\")\n if home and prefix:\n raise InvalidSchemeCombination(\"--home\", \"--prefix\")\n\n if home is not None:\n scheme_name = _infer_home()\n elif user:\n scheme_name = _infer_user()\n else:\n scheme_name = _infer_prefix()\n\n # Special case: When installing into a custom prefix, use posix_prefix\n # instead of osx_framework_library. See _should_use_osx_framework_prefix()\n # docstring for details.\n if prefix is not None and scheme_name == \"osx_framework_library\":\n scheme_name = \"posix_prefix\"\n\n if home is not None:\n variables = {k: home for k in _HOME_KEYS}\n elif prefix is not None:\n variables = {k: prefix for k in _HOME_KEYS}\n else:\n variables = {}\n\n paths = sysconfig.get_paths(scheme=scheme_name, vars=variables)\n\n # Logic here is very arbitrary, we're doing it for compatibility, don't ask.\n # 1. Pip historically uses a special header path in virtual environments.\n # 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We\n # only do the same when not running in a virtual environment because\n # pip's historical header path logic (see point 1) did not do this.\n if running_under_virtualenv():\n if user:\n base = variables.get(\"userbase\", sys.prefix)\n else:\n base = variables.get(\"base\", sys.prefix)\n python_xy = f\"python{get_major_minor_version()}\"\n paths[\"include\"] = os.path.join(base, \"include\", \"site\", python_xy)\n elif not dist_name:\n dist_name = \"UNKNOWN\"\n\n scheme = Scheme(\n platlib=paths[\"platlib\"],\n purelib=paths[\"purelib\"],\n headers=os.path.join(paths[\"include\"], dist_name),\n scripts=paths[\"scripts\"],\n data=paths[\"data\"],\n )\n if root is not None:\n for key in SCHEME_KEYS:\n value = change_root(root, getattr(scheme, key))\n setattr(scheme, key, value)\n return scheme", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def store_exc_info(self, **kwargs):\n \"\"\"Store exceptions when they are generated by a view.\"\"\"\n self.exc_info = sys.exc_info()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_storages(app_configs=None, **kwargs):\n \"\"\"Ensure staticfiles is defined in STORAGES setting.\"\"\"\n errors = []\n if STATICFILES_STORAGE_ALIAS not in settings.STORAGES:\n errors.append(E005)\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _check_decimal_places_and_max_digits(self, **kwargs):\n if int(self.decimal_places) > int(self.max_digits):\n return [\n checks.Error(\n \"'max_digits' must be greater or equal to 'decimal_places'.\",\n obj=self,\n id=\"fields.E134\",\n )\n ]\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn PluginDescriptor(name=_(\"Wireless LAN\"), description=_(\"Connect to a wireless network\"), where=PluginDescriptor.WHERE_NETWORKSETUP, needsRestart=False, fnc={\"ifaceSupported\": callFunction, \"configStrings\": configStrings, \"WlanPluginEntry\": lambda x: _(\"Wireless network configuration...\")})", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def handle_annotations_change(instance, annotations, action, **kwargs):\n def filter_data(data):\n filtered_data = {\n \"id\": data[\"id\"],\n \"frame\": data[\"frame\"],\n \"attributes\": data[\"attributes\"],\n }\n if label_id := data.get(\"label_id\"):\n filtered_data[\"label_id\"] = label_id\n\n return filtered_data\n\n def filter_track(track):\n filtered_data = filter_data(track)\n filtered_data[\"shapes\"] = [filter_data(s) for s in track[\"shapes\"]]\n return filtered_data\n\n oid = organization_id(instance)\n oslug = organization_slug(instance)\n pid = project_id(instance)\n tid = task_id(instance)\n jid = job_id(instance)\n uid = user_id(instance)\n uname = user_name(instance)\n uemail = user_email(instance)\n\n tags = [filter_data(tag) for tag in annotations.get(\"tags\", [])]\n if tags:\n record_server_event(\n scope=event_scope(action, \"tags\"),\n request_id=request_id(),\n on_commit=True,\n count=len(tags),\n org_id=oid,\n org_slug=oslug,\n project_id=pid,\n task_id=tid,\n job_id=jid,\n user_id=uid,\n user_name=uname,\n user_email=uemail,\n payload={\"tags\": tags},\n )\n\n shapes_by_type = {shape_type[0]: [] for shape_type in ShapeType.choices()}\n for shape in annotations.get(\"shapes\", []):\n shapes_by_type[shape[\"type\"]].append(filter_data(shape))\n\n scope = event_scope(action, \"shapes\")\n for shape_type, shapes in shapes_by_type.items():\n if shapes:\n record_server_event(\n scope=scope,\n request_id=request_id(),\n on_commit=True,\n obj_name=shape_type,\n count=len(shapes),\n org_id=oid,\n org_slug=oslug,\n project_id=pid,\n task_id=tid,\n job_id=jid,\n user_id=uid,\n user_name=uname,\n user_email=uemail,\n payload={\"shapes\": shapes},\n )\n\n tracks_by_type = {shape_type[0]: [] for shape_type in ShapeType.choices()}\n for track in annotations.get(\"tracks\", []):\n filtered_track = filter_track(track)\n tracks_by_type[track[\"shapes\"][0][\"type\"]].append(filtered_track)\n\n scope = event_scope(action, \"tracks\")\n for track_type, tracks in tracks_by_type.items():\n if tracks:\n record_server_event(\n scope=scope,\n request_id=request_id(),\n on_commit=True,\n obj_name=track_type,\n count=len(tracks),\n org_id=oid,\n org_slug=oslug,\n project_id=pid,\n task_id=tid,\n job_id=jid,\n user_id=uid,\n user_name=uname,\n user_email=uemail,\n payload={\"tracks\": tracks},\n )", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def destroy(self, request, *args, **kwargs):\n \"\"\"Custom destroy method to pass kwargs.\"\"\"\n instance = self.get_object()\n self.perform_destroy(instance, **kwargs)\n return Response(status=status.HTTP_204_NO_CONTENT)", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n data = json.loads(raw)\n\n for log in data:\n yield from parse_log(log)", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def getTextBoundarySize(instance, font, targetSize, text, nowrap=False):\n\treturn eLabel.calculateTextSize(font, text, targetSize, nowrap)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_available_auths(self, user, organization, integrations, social_auths, **kwargs):\n if self.auth_provider is None:\n return []\n\n social_auths_by_id = {usa.id: usa for usa in social_auths}\n linked_social_auths = set()\n\n auths = []\n for i in integrations:\n associated_auth = i.default_auth_id and social_auths_by_id[i.default_auth_id]\n if associated_auth:\n linked_social_auths.add(associated_auth.id)\n auths.append(\n {\n \"defaultAuthId\": i.default_auth_id,\n \"user\": associated_auth and {\"email\": associated_auth.user.email},\n \"externalId\": i.external_id,\n \"integrationId\": str(i.id),\n \"linked\": True,\n }\n )\n auths.extend(\n [\n {\n \"defaultAuthId\": sa.id,\n \"user\": {\"email\": sa.user.email},\n \"externalId\": sa.uid,\n \"integrationId\": None,\n \"linked\": False,\n }\n for sa in social_auths\n if sa.id not in linked_social_auths\n ]\n )\n return auths", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource, same_org):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\" and ownership != \"None\":\n return False\n if context == \"sandbox\" and same_org is False:\n return False\n if scope.startswith(\"create\") and ownership in [\"owner\", \"assignee\"]:\n return False\n if scope in [\"create\", \"import:backup\"] and ownership != \"None\":\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def run(\n hostname: Hostname, additional_oois: list[DNSCNAMERecord | ResolvedHostname], config: dict[str, Any]\n) -> Iterator[OOI]:\n cname_records = [ooi for ooi in additional_oois if isinstance(ooi, DNSCNAMERecord)]\n resolved_hostnames = [ooi for ooi in additional_oois if isinstance(ooi, ResolvedHostname)]\n\n for cname_record in cname_records:\n for resolved_hostname in resolved_hostnames:\n yield ResolvedHostname(hostname=cname_record.hostname, address=resolved_hostname.address)\n # Also the non-fqdn variant\n yield ResolvedHostname(\n hostname=Hostname(\n name=cname_record.hostname.tokenized.name,\n network=Network(name=cname_record.hostname.tokenized.network.name).reference,\n ).reference,\n address=resolved_hostname.address,\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def get_constrained_date_range(\n params,\n allowed_resolution: AllowedResolution = AllowedResolution.one_hour,\n max_points=MAX_POINTS,\n restrict_date_range=True,\n) -> tuple[datetime, datetime, int]:\n interval = parse_stats_period(params.get(\"interval\", \"1h\"))\n interval = int(3600 if interval is None else interval.total_seconds())\n\n smallest_interval, interval_str = allowed_resolution.value\n if interval % smallest_interval != 0 or interval < smallest_interval:\n raise InvalidParams(\n f\"The interval has to be a multiple of the minimum interval of {interval_str}.\"\n )\n\n if interval > ONE_DAY:\n raise InvalidParams(\"The interval has to be less than one day.\")\n\n if ONE_DAY % interval != 0:\n raise InvalidParams(\"The interval should divide one day without a remainder.\")\n\n start, end = get_date_range_from_params(params)\n now = get_now()\n\n if start > now:\n start = now\n\n adjusted_start, adjusted_end, _num_intervals = to_intervals(start, end, interval)\n\n date_range = adjusted_end - adjusted_start\n\n if date_range.total_seconds() / interval > max_points:\n raise InvalidParams(\n \"Your interval and date range would create too many results. \"\n \"Use a larger interval, or a smaller date range.\"\n )\n\n return adjusted_start, adjusted_end, interval", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_swagger_view(version='v1'):\n from ..urls import api_v1\n from django.urls import path, include\n api_v1_patterns = [\n path('api/v1/', include(api_v1))\n ]\n patterns = api_v1_patterns\n schema_view = get_schema_view(\n api_info,\n patterns=patterns,\n permission_classes=(permissions.IsAuthenticated,),\n )\n return schema_view", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def run(input_ooi: Hostname, additional_oois: list[DNSCAARecord | NXDOMAIN], config: dict[str, Any]) -> Iterator[OOI]:\n caa_records = [ooi for ooi in additional_oois if isinstance(ooi, DNSCAARecord)]\n nxdomains = (ooi for ooi in additional_oois if isinstance(ooi, NXDOMAIN))\n\n if any(nxdomains):\n return\n # only report finding when there is no SPF record\n if (\n not tldextract.extract(input_ooi.name).subdomain\n and tldextract.extract(input_ooi.name).domain\n and not caa_records\n ):\n ft = KATFindingType(id=\"KAT-NO-CAA\")\n yield ft\n yield Finding(\n ooi=input_ooi.reference, finding_type=ft.reference, description=\"This hostname does not have a CAA record\"\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def Plugins(**kwargs):\n\tif Streamlink:\n\t\treturn [PluginDescriptor(name=WRAPPER, description=\"StreamlinkWrapper\", where=PluginDescriptor.WHERE_PLAYSERVICE, needsRestart=False, fnc=playService)]\n\telse:\n\t\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def inbox_search(\n projects: Sequence[Project],\n environments: Sequence[Environment] | None = None,\n limit: int = 100,\n cursor: Cursor | None = None,\n count_hits: bool = False,\n search_filters: Sequence[SearchFilter] | None = None,\n date_from: datetime | None = None,\n date_to: datetime | None = None,\n max_hits: int | None = None,\n actor: Any | None = None,\n) -> CursorResult:\n now: datetime = timezone.now()\n end: datetime | None = None\n end_params: list[datetime] = [\n _f for _f in [date_to, get_search_filter(search_filters, \"date\", \"<\")] if _f\n ]\n if end_params:\n end = min(end_params)\n\n end = end if end else now + ALLOWED_FUTURE_DELTA\n\n # We only want to search back a week at most, since that's the oldest inbox rows\n # can be.\n earliest_date = now - timedelta(days=7)\n start_params = [date_from, earliest_date, get_search_filter(search_filters, \"date\", \">\")]\n start = max(_f for _f in start_params if _f)\n end = max([earliest_date, end])\n\n if start >= end:\n return Paginator(Group.objects.none()).get_result()\n\n # Make sure search terms are valid\n invalid_search_terms = (\n [str(sf) for sf in search_filters if sf.key.name not in allowed_inbox_search_terms]\n if search_filters\n else []\n )\n if invalid_search_terms:\n raise InvalidSearchQuery(f\"Invalid search terms for 'inbox' search: {invalid_search_terms}\")\n\n # Make sure this is an inbox search\n if not get_search_filter(search_filters, \"for_review\", \"=\"):\n raise InvalidSearchQuery(\"Sort key 'inbox' only supported for inbox search\")\n\n if get_search_filter(\n search_filters, \"status\", \"=\"\n ) != GroupStatus.UNRESOLVED and get_search_filter(search_filters, \"status\", \"IN\") != [\n GroupStatus.UNRESOLVED\n ]:\n raise InvalidSearchQuery(\"Inbox search only works for 'unresolved' status\")\n\n # We just filter on `GroupInbox.date_added` here, and don't filter by date\n # on the group. This keeps the query simpler and faster in some edge cases,\n # and date_added is a good enough proxy when we're using this sort.\n qs = GroupInbox.objects.filter(\n date_added__gte=start,\n date_added__lte=end,\n project__in=projects,\n ).using_replica()\n\n if environments is not None:\n environment_ids: list[int] = [environment.id for environment in environments]\n qs = qs.filter(\n group_id__in=GroupEnvironment.objects.filter(environment_id__in=environment_ids)\n .values_list(\"group_id\", flat=True)\n .distinct()\n )\n\n owner_search = get_search_filter(search_filters, \"assigned_or_suggested\", \"IN\")\n if owner_search:\n qs = qs.filter(\n assigned_or_suggested_filter(owner_search, projects, field_filter=\"group_id\")\n )\n\n paginator = DateTimePaginator(qs.order_by(\"date_added\"), \"-date_added\")\n results = paginator.get_result(limit, cursor, count_hits=count_hits, max_hits=max_hits)\n\n # We want to return groups from the endpoint, but have the cursor be related to the\n # GroupInbox rows. So we paginate on the GroupInbox results queryset, then fetch\n # the group_ids out and use them to get the actual groups.\n group_qs = Group.objects.filter(\n id__in=[r.group_id for r in results.results],\n project__in=projects,\n status=GroupStatus.UNRESOLVED,\n )\n groups: Mapping[int, Group] = {g.id: g for g in group_qs}\n results.results = [groups[r.group_id] for r in results.results if r.group_id in groups]\n return results", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _get_default_browser_performance_profiles(organization: Organization) -> list[dict[str, Any]]:\n return [\n {\n \"name\": \"Default\",\n \"scoreComponents\": [\n {\n \"measurement\": \"fcp\",\n \"weight\": 0.15,\n \"p10\": 900.0,\n \"p50\": 1600.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"lcp\",\n \"weight\": 0.30,\n \"p10\": 1200.0,\n \"p50\": 2400.0,\n \"optional\": True,\n },\n {\n \"measurement\": \"cls\",\n \"weight\": 0.15,\n \"p10\": 0.1,\n \"p50\": 0.25,\n \"optional\": True,\n },\n {\n \"measurement\": \"ttfb\",\n \"weight\": 0.10,\n \"p10\": 200.0,\n \"p50\": 400.0,\n \"optional\": True,\n },\n ],\n \"condition\": {\n \"op\": \"and\",\n \"inner\": [],\n },\n },\n {\n \"name\": \"Default INP\",\n \"scoreComponents\": [\n {\n \"measurement\": \"inp\",\n \"weight\": 1.0,\n \"p10\": 200.0,\n \"p50\": 500.0,\n \"optional\": False,\n },\n ],\n \"condition\": {\n \"op\": \"and\",\n \"inner\": [],\n },\n },\n ]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def plugin(version: str) -> type[AttrPlugin]:\n return AttrPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _infer_dataclass_attr_init_type(\n self, sym: SymbolTableNode, name: str, context: Context\n ) -> Type | None:\n \"\"\"Infer __init__ argument type for an attribute.\n\n In particular, possibly use the signature of __set__.\n \"\"\"\n default = sym.type\n if sym.implicit:\n return default\n t = get_proper_type(sym.type)\n\n # Perform a simple-minded inference from the signature of __set__, if present.\n # We can't use mypy.checkmember here, since this plugin runs before type checking.\n # We only support some basic scanerios here, which is hopefully sufficient for\n # the vast majority of use cases.\n if not isinstance(t, Instance):\n return default\n setter = t.type.get(\"__set__\")\n if setter:\n if isinstance(setter.node, FuncDef):\n super_info = t.type.get_containing_type_info(\"__set__\")\n assert super_info\n if setter.type:\n setter_type = get_proper_type(\n map_type_from_supertype(setter.type, t.type, super_info)\n )\n else:\n return AnyType(TypeOfAny.unannotated)\n if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [\n ARG_POS,\n ARG_POS,\n ARG_POS,\n ]:\n return expand_type_by_instance(setter_type.arg_types[2], t)\n else:\n self._api.fail(\n f'Unsupported signature for \"__set__\" in \"{t.type.name}\"', context\n )\n else:\n self._api.fail(f'Unsupported \"__set__\" in \"{t.type.name}\"', context)\n\n return default", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def process_template_response(self, request, response):\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(boefje_meta: BoefjeMeta) -> list[tuple[set, bytes | str]]:\n response = requests.get(\n \"https://raw.githubusercontent.com/RetireJS/retire.js/v3/repository/jsrepository.json\", timeout=30\n )\n\n return [(set(), response.content)]", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def process_view(self, request, view_func, view_args, view_kwargs):\n return HttpResponse(\"Processed view %s\" % view_func.__name__)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def scan(self, barcode_data):\n \"\"\"Scan a barcode against this plugin.\n\n This method is explicitly called from the /scan/ API endpoint,\n and thus it is expected that any barcode which matches this barcode will return a result.\n\n If this plugin finds a match against the provided barcode, it should return a dict object\n with the intended result.\n\n Default return value is None\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def get_geom_placeholder(self, f, value, compiler):\n \"\"\"\n Return the placeholder for the given geometry field with the given\n value. Depending on the spatial backend, the placeholder may contain a\n stored procedure call to the transformation function of the spatial\n backend.\n \"\"\"\n\n def transform_value(value, field):\n return value is not None and value.srid != field.srid\n\n if hasattr(value, \"as_sql\"):\n return (\n \"%s(%%s, %s)\" % (self.spatial_function_name(\"Transform\"), f.srid)\n if transform_value(value.output_field, f)\n else \"%s\"\n )\n if transform_value(value, f):\n # Add Transform() to the SQL placeholder.\n return \"%s(%s(%%s,%s), %s)\" % (\n self.spatial_function_name(\"Transform\"),\n self.from_text,\n value.srid,\n f.srid,\n )\n elif self.connection.features.has_spatialrefsys_table:\n return \"%s(%%s,%s)\" % (self.from_text, f.srid)\n else:\n # For backwards compatibility on MySQL (#27464).\n return \"%s(%%s)\" % self.from_text", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def primitive_call(desc: CFunctionDescription, args: list[Value], line: int) -> CallC:\n return CallC(\n desc.c_function_name,\n [],\n desc.return_type,\n desc.steals,\n desc.is_borrowed,\n desc.error_kind,\n line,\n )", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def cache(\n self,\n keys,\n request,\n response,\n *,\n seconds=None,\n stale_while_revalidate=None,\n stale_if_error=None,\n ):\n existing_keys = set(response.headers.get(\"Surrogate-Key\", \"\").split())\n\n response.headers[\"Surrogate-Key\"] = \" \".join(sorted(set(keys) | existing_keys))\n\n values = []\n\n if seconds is not None:\n values.append(f\"max-age={seconds}\")\n\n if stale_while_revalidate is not None:\n values.append(f\"stale-while-revalidate={stale_while_revalidate}\")\n\n if stale_if_error is not None:\n values.append(f\"stale-if-error={stale_if_error}\")\n\n if values:\n response.headers[\"Surrogate-Control\"] = \", \".join(values)", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def process_exception(self, request, exception):\n if settings.DEBUG:\n traceback.print_exc()\n\n return None", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def create_issue(self, raw_form_data):\n return {\"key\": \"APP-123\"}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def getAudioCodec(self, info):\n\t\tdescription_str = _(\"unknown\")\n\t\tif self.getAudio():\n\t\t\tlanguages = self.getLanguage()\n\t\t\tdescription = self.audio_info.getDescription() or \"\"\n\t\t\tdescription_str = description.split(\" \")\n\t\t\tif len(description_str) and description_str[0] in languages:\n\t\t\t\treturn languages\n\t\t\tif description.lower() in languages.lower():\n\t\t\t\tlanguages = \"\"\n\t\t\tdescription_str = description + \" \" + languages\n\t\treturn description_str", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def __build_url(self, *args, gerais:bool, ano:int, tipo_emenda:Optional[TIPOS_EMENDAS]=None, )->str:\n \n endpoint = self.__build_endpoint(gerais=gerais, tipo_emenda=tipo_emenda)\n\n #neste caso n\u00e3o tem ano\n if not gerais and tipo_emenda == 'especiais':\n return endpoint\n \n return endpoint + f'/{ano}'", "smellKey": "S1172", "smellId": null, "repo": "AppCivico_smae", "language": "python"} {"function": "def process_view(self, *args, **kwargs):\n def stream():\n yield reverse(\"outer\")\n\n return StreamingHttpResponse(stream())", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def mock_extract_side_effect(\n db_name: str,\n query_filepath: Union[Path, str],\n dtypes: Union[None, dict] = None,\n parse_dates: Union[list, dict, None] = None,\n params: Union[dict, None] = None,\n backend: str = \"pandas\",\n geom_col: str = \"geom\",\n crs: Union[int, None] = None,\n):\n @patch(\"src.read_query.pd\")\n @patch(\"src.read_query.create_engine\")\n def mock_extract_side_effect_(\n db_name,\n query_filepath,\n dtypes,\n parse_dates,\n params,\n mock_create_engine,\n mock_pd,\n ):\n def read_sql_mock(query, engine, **kwargs):\n return query\n\n mock_pd.read_sql.side_effect = read_sql_mock\n\n return extract(\n db_name=db_name,\n query_filepath=query_filepath,\n dtypes=None,\n parse_dates=parse_dates,\n params=params,\n )\n\n return mock_extract_side_effect_(\n db_name, query_filepath, dtypes, parse_dates, params\n )", "smellKey": "S1172", "smellId": null, "repo": "MTES-MCT_monitorfish", "language": "python"} {"function": "async def app(scope, receive, send):\n assert scope['type'] == 'http'\n\n await send({\n 'type': 'http.response.start',\n 'status': 200,\n 'headers': [\n [b'content-type', b'text/plain'],\n ],\n })\n await send({\n 'type': 'http.response.body',\n 'body': b'Hello, Integration Test!',\n })", "smellKey": "S1172", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def send_issue_unresolved_webhook_helper(\n group: Group,\n project: Project,\n user: User | RpcUser | None = None,\n data: Mapping[str, Any] | None = None,\n **kwargs,\n) -> None:\n organization = project.organization\n if features.has(\"organizations:webhooks-unresolved\", organization):\n send_workflow_webhooks(\n organization=organization,\n issue=group,\n user=user,\n event=\"issue.unresolved\",\n data=data,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def getPlayingref(self, ref):\n\t\tplayingref = None\n\t\tif NavigationInstance.instance:\n\t\t\tplayingref = NavigationInstance.instance.getCurrentlyPlayingServiceReference()\n\t\tif not playingref:\n\t\t\tplayingref = eServiceReference()\n\t\treturn playingref", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n results = json.loads(raw)\n\n internet = Network(name=\"internet\")\n yield internet\n\n for _, subdomain in results[\"subdomains\"].items():\n hostname = subdomain[\"url\"].rstrip(\".\")\n registered_domain = tldextract.extract(hostname).registered_domain\n\n registered_domain_ooi = Hostname(name=registered_domain, network=internet.reference)\n yield registered_domain_ooi\n hostname_ooi = Hostname(\n name=hostname, network=internet.reference, registered_domain=registered_domain_ooi.reference\n )\n yield hostname_ooi\n\n resolved_ip = subdomain[\"ip\"]\n if isinstance(ip_address(resolved_ip), IPv4Address):\n resolved_ip_ooi = IPAddressV4(network=internet.reference, address=resolved_ip)\n else:\n resolved_ip_ooi = IPAddressV6(network=internet.reference, address=resolved_ip)\n yield resolved_ip_ooi\n\n resolved_hostname_ooi = ResolvedHostname(hostname=hostname_ooi.reference, address=resolved_ip_ooi.reference)\n yield resolved_hostname_ooi", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource, same_org):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\" and ownership != \"None\":\n return False\n if context == \"sandbox\" and same_org is False:\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def include_file(self, *args, **kwargs):\n \"\"\"Call the include version function to import related assets.\"\"\"\n self._file_included = True", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def build_message(\n self, context: dict[str, Any], status: TriggerStatus, user_id: int\n ) -> MessageBuilder:\n display = self.status_display[status]\n\n return MessageBuilder(\n subject=\"[{}] {} - {}\".format(\n context[\"status\"], context[\"incident_name\"], self.project.slug\n ),\n template=\"sentry/emails/incidents/trigger.txt\",\n html_template=\"sentry/emails/incidents/trigger.html\",\n type=f\"incident.alert_rule_{display.lower()}\",\n context=context,\n headers={\"X-SMTPAPI\": orjson.dumps({\"category\": \"metric_alert_email\"}).decode()},\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def sort(self, key=None, reverse=False):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def AutoLogManager(session=None, **kwargs):\n\tglobal debuglogcheckpoller\n\tdebuglogcheckpoller = LogManagerPoller()\n\tdebuglogcheckpoller.start()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params: SnubaParams,\n rollup: int,\n referrer: str,\n zerofill_results: bool = True,\n allow_metric_aggregates=True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n has_metrics: bool = True,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n equations, columns = categorize_columns(selected_columns)\n\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"TimeseriesSpanIndexedQueryBuilder\"):\n query = TimeseriesSpanIndexedQueryBuilder(\n Dataset.SpansIndexed,\n {},\n rollup,\n snuba_params=snuba_params,\n query=query,\n selected_columns=columns,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n ),\n )\n result = query.run_query(referrer, query_source=query_source)\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"query.transform_results\"):\n result = query.process_results(result)\n result[\"data\"] = (\n discover.zerofill(\n result[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n \"time\",\n )\n if zerofill_results\n else result[\"data\"]\n )\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"meta\": result[\"meta\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def ask_rename(self, model_name, old_name, new_name, field_instance):\n \"\"\"Was this field really renamed?\"\"\"\n return self.defaults.get(\"ask_rename\", False)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def create_project_rule(\n self,\n project=None,\n action_match=None,\n condition_match=None,\n comparison_interval=None,\n *args,\n **kwargs,\n ) -> Rule:\n if project is None:\n project = self.project\n return Factories.create_project_rule(\n project=project,\n action_data=action_match,\n condition_data=condition_match,\n *args,\n **kwargs,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def insert_statement(self, on_conflict=None):\n return \"INSERT INTO\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def Plugins(path, **kwargs):\n\treturn [PluginDescriptor(name=_(\"Ipkg\"), where=PluginDescriptor.WHERE_FILESCAN, needsRestart=False, fnc=filescan)]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def activate_all(session):\n\tcihelper.load_ci_assignment()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_db_converters(self, connection):\n if hasattr(self, \"from_db_value\"):\n return [self.from_db_value]\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def enable_single_lambda(lambda_client, function, sentry_project_dsn, retries_left=3):\n # find the latest layer for this function\n layer_arn = get_latest_layer_for_function(function)\n\n name = function[\"FunctionName\"]\n runtime = function[\"Runtime\"]\n # update the env variables\n env_variables = function.get(\"Environment\", {}).get(\"Variables\", {})\n\n # Check if the sentry sdk layer already exists\n layers = get_function_layer_arns(function)\n sentry_layer_index = get_index_of_sentry_layer(layers, layer_arn)\n\n updated_handler = None\n\n sentry_env_variables = {\n \"SENTRY_DSN\": sentry_project_dsn,\n \"SENTRY_TRACES_SAMPLE_RATE\": \"1.0\",\n }\n\n if runtime.startswith(\"nodejs\"):\n # note the env variables would be different for non-Node runtimes\n version = get_option_value(function, OPTION_VERSION)\n try:\n parsed_version = int(version)\n except Exception:\n sentry_sdk.capture_message(\"Invariant: Unable to parse AWS lambda version\")\n parsed_version = None\n\n if (\n # Lambda layer version 235 was the latest version using `@sentry/serverless` before we switched to `@sentry/aws-serverless`\n parsed_version is not None\n and parsed_version <= 235\n ):\n env_variables.update(\n {\n \"NODE_OPTIONS\": \"-r @sentry/serverless/dist/awslambda-auto\",\n **sentry_env_variables,\n }\n )\n else:\n env_variables.update(\n {\n \"NODE_OPTIONS\": \"-r @sentry/aws-serverless/awslambda-auto\",\n **sentry_env_variables,\n }\n )\n\n elif runtime.startswith(\"python\"):\n # Check if we are trying to re-enable an already enabled python, and if\n # are we should not override the env variable \"SENTRY_INITIAL_HANDLER\"\n # because that would be problematic as we would lose the handler value.\n if sentry_layer_index > -1:\n env_variables.update(sentry_env_variables)\n else:\n env_variables.update(\n {\"SENTRY_INITIAL_HANDLER\": function[\"Handler\"], **sentry_env_variables}\n )\n updated_handler = \"sentry_sdk.integrations.init_serverless_sdk.sentry_lambda_handler\"\n\n # Check if the sentry layer exists and update it or insert new layer to end\n if sentry_layer_index > -1:\n layers[sentry_layer_index] = layer_arn\n else:\n layers.append(layer_arn)\n\n lambda_kwargs = {\n \"FunctionName\": name,\n \"Layers\": layers,\n \"Environment\": {\"Variables\": env_variables},\n }\n if updated_handler:\n lambda_kwargs.update({\"Handler\": updated_handler})\n\n return update_lambda_with_retries(lambda_client, **lambda_kwargs)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def can_tags(self, item):\n\t\treturn self.tags", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def perform_special_format_checks(\n self,\n spec: ConversionSpecifier,\n call: CallExpr,\n repl: Expression,\n actual_type: Type,\n expected_type: Type,\n ) -> None:\n # TODO: try refactoring to combine this logic with % formatting.\n if spec.conv_type == \"c\":\n if isinstance(repl, (StrExpr, BytesExpr)) and len(repl.value) != 1:\n self.msg.requires_int_or_char(call, format_call=True)\n c_typ = get_proper_type(self.chk.lookup_type(repl))\n if isinstance(c_typ, Instance) and c_typ.last_known_value:\n c_typ = c_typ.last_known_value\n if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str):\n if len(c_typ.value) != 1:\n self.msg.requires_int_or_char(call, format_call=True)\n if (not spec.conv_type or spec.conv_type == \"s\") and not spec.conversion:\n if has_type_component(actual_type, \"builtins.bytes\") and not custom_special_method(\n actual_type, \"__str__\"\n ):\n self.msg.fail(\n 'If x = b\\'abc\\' then f\"{x}\" or \"{}\".format(x) produces \"b\\'abc\\'\", '\n 'not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). '\n \"Otherwise, decode the bytes\",\n call,\n code=codes.STR_BYTES_PY3,\n )\n if spec.flags:\n numeric_types = UnionType(\n [self.named_type(\"builtins.int\"), self.named_type(\"builtins.float\")]\n )\n if (\n spec.conv_type\n and spec.conv_type not in NUMERIC_TYPES_NEW\n or not spec.conv_type\n and not is_subtype(actual_type, numeric_types)\n and not custom_special_method(actual_type, \"__format__\")\n ):\n self.msg.fail(\n \"Numeric flags are only allowed for numeric types\",\n call,\n code=codes.STRING_FORMATTING,\n )", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def register_type_handlers(connection, **kwargs):\n if connection.vendor != \"postgresql\" or connection.alias == NO_DB_ALIAS:\n return\n\n oids, array_oids = get_hstore_oids(connection.alias)\n # Don't register handlers when hstore is not available on the database.\n #\n # If someone tries to create an hstore field it will error there. This is\n # necessary as someone may be using PSQL without extensions installed but\n # be using other features of contrib.postgres.\n #\n # This is also needed in order to create the connection in order to install\n # the hstore extension.\n if oids:\n register_hstore(\n connection.connection, globally=True, oid=oids, array_oid=array_oids\n )\n\n oids, citext_oids = get_citext_oids(connection.alias)\n # Don't register handlers when citext is not available on the database.\n #\n # The same comments in the above call to register_hstore() also apply here.\n if oids:\n array_type = psycopg2.extensions.new_array_type(\n citext_oids, \"citext[]\", psycopg2.STRING\n )\n psycopg2.extensions.register_type(array_type, None)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(nameserver_record: DNSNSRecord, additional_oois, config: dict[str, str]) -> Iterator[OOI]:\n \"\"\"Checks to see if a domain has a specific set of dns servers which would indicate domain registrant verification.\n https://support.dnsimple.com/articles/icann-domain-validation/\n \"\"\"\n if nameserver_record.name_server_hostname.tokenized.name.rstrip(\".\").upper() in INDICATORS:\n finding_type = KATFindingType(id=\"KAT-DOMAIN-OWNERSHIP-PENDING\")\n yield finding_type\n yield Finding(\n finding_type=finding_type.reference,\n ooi=nameserver_record.hostname,\n description=\"This domain requires ownership verification and is currently pending.\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def _alter_many_to_many(self, model, old_field, new_field, strict):\n \"\"\"Alter M2Ms to repoint their to= endpoints.\"\"\"\n # Rename the through table\n if (\n old_field.remote_field.through._meta.db_table\n != new_field.remote_field.through._meta.db_table\n ):\n self.alter_db_table(\n old_field.remote_field.through,\n old_field.remote_field.through._meta.db_table,\n new_field.remote_field.through._meta.db_table,\n )\n # Repoint the FK to the other side\n self.alter_field(\n new_field.remote_field.through,\n # The field that points to the target model is needed, so we can\n # tell alter_field to change it - this is m2m_reverse_field_name()\n # (as opposed to m2m_field_name(), which points to our model).\n old_field.remote_field.through._meta.get_field(\n old_field.m2m_reverse_field_name()\n ),\n new_field.remote_field.through._meta.get_field(\n new_field.m2m_reverse_field_name()\n ),\n )\n self.alter_field(\n new_field.remote_field.through,\n # for self-referential models we need to alter field from the other end too\n old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),\n new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_single_conversion(field,schema,argnum=0,classname='?'):\n name = field.name\n return template_convert_single.format(name=name,argnum=argnum,classname=classname,full_type=field.fullspec)", "smellKey": "S1172", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "def _check_allowing_files_or_folders(self, **kwargs):\n if not self.allow_files and not self.allow_folders:\n return [\n checks.Error(\n \"FilePathFields must have either 'allow_files' or 'allow_folders' \"\n \"set to True.\",\n obj=self,\n id=\"fields.E140\",\n )\n ]\n return []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def converter(value, expression, connection):\n if value is not None:\n return create_decimal(value)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def emit_union_cast(\n self,\n src: str,\n dest: str,\n typ: RUnion,\n declare_dest: bool,\n error: ErrorHandler,\n optional: bool,\n src_type: RType | None,\n raise_exception: bool,\n ) -> None:\n \"\"\"Emit cast to a union type.\n\n The arguments are similar to emit_cast.\n \"\"\"\n if declare_dest:\n self.emit_line(f\"PyObject *{dest};\")\n good_label = self.new_label()\n if optional:\n self.emit_line(f\"if ({src} == NULL) {{\")\n self.emit_line(f\"{dest} = {self.c_error_value(typ)};\")\n self.emit_line(f\"goto {good_label};\")\n self.emit_line(\"}\")\n for item in typ.items:\n self.emit_cast(\n src,\n dest,\n item,\n declare_dest=False,\n raise_exception=False,\n optional=False,\n likely=False,\n )\n self.emit_line(f\"if ({dest} != NULL) goto {good_label};\")\n # Handle cast failure.\n self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n self.emit_label(good_label)", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def setlistdefault(self, key, default):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def send_sms(body: str, to: str, from_: str | None = None) -> bool:\n account = options.get(\"sms.twilio-account\")\n if not account:\n raise RuntimeError(\"SMS backend is not configured.\")\n if account[:2] != \"AC\":\n account = \"AC\" + account\n url = \"https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json\" % quote(account)\n\n phone_number = phone_number_as_e164(to)\n\n rv = requests.post(\n url,\n auth=(account, options.get(\"sms.twilio-token\")),\n data={\"To\": phone_number, \"From\": options.get(\"sms.twilio-number\"), \"Body\": body},\n )\n if not rv.ok:\n logging.error(\n \"Failed to send text message to %s: (%s) %s\", phone_number, rv.status_code, rv.content\n )\n return False\n return True", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_handler(self, *args, **options):\n \"\"\"Return the default WSGI handler for the runner.\"\"\"\n return get_internal_wsgi_application()", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def visit_DerivedContextReference(\n self, node: nodes.DerivedContextReference, frame: Frame\n ) -> None:\n self.write(self.derive_context(frame))", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def method_saving_308_redirect_query_string_view(request):\n return HttpResponseRedirect(\"/post_view/?hello=world\", status=308)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def after_change_currency(setting) -> None:\n \"\"\"Callback function when base currency is changed.\n\n - Update exchange rates\n - Recalculate prices for all parts\n \"\"\"\n import InvenTree.ready\n import InvenTree.tasks\n\n if InvenTree.ready.isImportingData():\n return\n\n if not InvenTree.ready.canAppAccessDatabase():\n return\n\n from part import tasks as part_tasks\n\n # Immediately update exchange rates\n InvenTree.tasks.update_exchange_rates(force=True)\n\n # Offload update of part prices to a background task\n InvenTree.tasks.offload_task(part_tasks.check_missing_pricing, force_async=True)", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data, context=self.get_serializer_context())\n\n if serializer.is_valid():\n result = serializer.save()\n if isinstance(result, BulkActionFailure):\n return Response(result.as_json(), status.HTTP_200_OK)\n else:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def get_data(scope, context, ownership, privilege, membership, resource, same_org):\n data = {\n \"scope\": scope,\n \"auth\": {\n \"user\": {\"id\": random.randrange(0, 100), \"privilege\": privilege},\n \"organization\": {\n \"id\": random.randrange(100, 200),\n \"owner\": {\"id\": random.randrange(200, 300)},\n \"user\": {\"role\": membership},\n }\n if context == \"organization\"\n else None,\n },\n \"resource\": resource,\n }\n\n user_id = data[\"auth\"][\"user\"][\"id\"]\n if context == \"organization\":\n if data[\"auth\"][\"organization\"][\"user\"][\"role\"] == \"owner\":\n data[\"auth\"][\"organization\"][\"owner\"][\"id\"] = user_id\n\n return data", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def get_lims_naming_metadata(self, sample: Sample) -> str | None:\n return None", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def send_msg(self, users, message, subject=None):\n accounts, __, __ = self.get_accounts(users)\n print('lark', message)\n if not accounts:\n return\n return self.client.send_text(accounts, message)", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def functools_total_ordering_maker_callback(\n ctx: mypy.plugin.ClassDefContext, auto_attribs_default: bool = False\n) -> bool:\n \"\"\"Add dunder methods to classes decorated with functools.total_ordering.\"\"\"\n comparison_methods = _analyze_class(ctx)\n if not comparison_methods:\n ctx.api.fail(\n 'No ordering operation defined when using \"functools.total_ordering\": < > <= >=',\n ctx.reason,\n )\n return True\n\n # prefer __lt__ to __le__ to __gt__ to __ge__\n root = max(comparison_methods, key=lambda k: (comparison_methods[k] is None, k))\n root_method = comparison_methods[root]\n if not root_method:\n # None of the defined comparison methods can be analysed\n return True\n\n other_type = _find_other_type(root_method)\n bool_type = ctx.api.named_type(\"builtins.bool\")\n ret_type: Type = bool_type\n if root_method.type.ret_type != ctx.api.named_type(\"builtins.bool\"):\n proper_ret_type = get_proper_type(root_method.type.ret_type)\n if not (\n isinstance(proper_ret_type, UnboundType)\n and proper_ret_type.name.split(\".\")[-1] == \"bool\"\n ):\n ret_type = AnyType(TypeOfAny.implementation_artifact)\n for additional_op in _ORDERING_METHODS:\n # Either the method is not implemented\n # or has an unknown signature that we can now extrapolate.\n if not comparison_methods.get(additional_op):\n args = [Argument(Var(\"other\", other_type), other_type, None, ARG_POS)]\n add_method_to_class(ctx.api, ctx.cls, additional_op, args, ret_type)\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def exception_in_render(request):\n class CustomHttpResponse(HttpResponse):\n def render(self):\n raise Exception(\"Exception in HttpResponse.render()\")\n\n return CustomHttpResponse(\"Error\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run_tests(self, test_labels, **kwargs):\n \"\"\"\n Run the unit tests for all the test labels in the provided list.\n\n Test labels should be dotted Python paths to test modules, test\n classes, or test methods.\n\n Return the number of tests that failed.\n \"\"\"\n self.setup_test_environment()\n suite = self.build_suite(test_labels)\n databases = self.get_databases(suite)\n suite.serialized_aliases = set(\n alias for alias, serialize in databases.items() if serialize\n )\n suite.used_aliases = set(databases)\n with self.time_keeper.timed(\"Total database setup\"):\n old_config = self.setup_databases(\n aliases=databases,\n serialized_aliases=suite.serialized_aliases,\n )\n run_failed = False\n try:\n self.run_checks(databases)\n result = self.run_suite(suite)\n except Exception:\n run_failed = True\n raise\n finally:\n try:\n with self.time_keeper.timed(\"Total database teardown\"):\n self.teardown_databases(old_config)\n self.teardown_test_environment()\n except Exception:\n # Silence teardown exceptions if an exception was raised during\n # runs to avoid shadowing it.\n if not run_failed:\n raise\n self.time_keeper.print_results()\n return self.suite_result(suite, result)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def main(session, **kwargs):\n\tfrom Screens import DVD\n\tsession.open(DVD.DVDPlayer)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def json_response_view(request):\n return JsonResponse(\n {\n \"a\": [1, 2, 3],\n \"foo\": {\"bar\": \"baz\"},\n # Make sure datetime and Decimal objects would be serialized properly\n \"timestamp\": datetime.datetime(2013, 5, 19, 20),\n \"value\": decimal.Decimal(\"3.14\"),\n }\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(hostname: Hostname, additional_oois: list[HostnameHTTPURL | Website], config: dict[str, Any]) -> Iterator[OOI]:\n hostname_http_urls = [\n hostname_http_url for hostname_http_url in additional_oois if isinstance(hostname_http_url, HostnameHTTPURL)\n ]\n websites = [website for website in additional_oois if isinstance(website, Website)]\n\n # HTTPResource is cartesian product of HostnameHTTPURL and Websites\n for hostname_http_url in hostname_http_urls:\n for website in websites:\n # only create resource if ports are the same and schemes are the same\n if (\n int(website.ip_service.tokenized.ip_port.port) == hostname_http_url.port\n and website.ip_service.tokenized.service.name == hostname_http_url.scheme.value\n ):\n yield HTTPResource(website=website.reference, web_url=hostname_http_url.reference)", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def options(self, request, *args, **kwargs):\n \"\"\"Handle responding to requests for the OPTIONS HTTP verb.\"\"\"\n response = HttpResponse()\n response.headers[\"Allow\"] = \", \".join(self._allowed_methods())\n response.headers[\"Content-Length\"] = \"0\"\n\n if self.view_is_async:\n\n async def func():\n return response\n\n return func()\n else:\n return response", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def Plugins(**kwargs):\n\treturn [\n\t\tPluginDescriptor(name=_(\"Media Player\"), description=_(\"Play back media files\"), where=PluginDescriptor.WHERE_PLUGINMENU, icon=\"MediaPlayer.png\", needsRestart=False, fnc=main),\n\t\t#PluginDescriptor(name = _(\"Media Player\"), where = PluginDescriptor.WHERE_FILESCAN, needsRestart = False, fnc = filescan),\n\t\tPluginDescriptor(name=_(\"Media Player\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=audiocdscan),\n\t\tPluginDescriptor(name=_(\"Media Player\"), description=_(\"Play back media files\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=menu)\n\t]", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def parse_terminated_string_bytes(read_buffer: ReadBuffer, string_length) -> str:\n terminate: bool = False\n byte_list: bytearray = bytearray()\n while not terminate:\n if len(byte_list) == 16:\n break\n next_byte: int = read_buffer.read_byte()\n if next_byte == 0x00 or len(byte_list) == 16:\n terminate = True\n else:\n byte_list.append(next_byte)\n length = len(byte_list)\n for _ in range(1, 16 - length):\n read_buffer.read_byte()\n result: str = byte_list.decode(\"UTF-8\")\n return result", "smellKey": "S1172", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def suite_result(self, suite, result, **kwargs):\n return (\n len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses)\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def metadata_listdir(self, name: str) -> List[str]:\n return []", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def when_ready(server):\n open(\"/tmp/app-initialized\", \"w\").close()", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def references_model(self, name, app_label):\n \"\"\"\n Return True if there is a chance this operation references the given\n model name (as a string), with an app label for accuracy.\n\n Used for optimization. If in doubt, return True;\n returning a false positive will merely make the optimizer a little\n less efficient, while returning a false negative may result in an\n unusable optimized migration.\n \"\"\"\n return True", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def distinct_sql(self, fields, params):\n \"\"\"\n Return an SQL DISTINCT clause which removes duplicate rows from the\n result set. If any fields are given, only check the given fields for\n duplicates.\n \"\"\"\n if fields:\n raise NotSupportedError(\n \"DISTINCT ON fields is not supported by this database backend\"\n )\n else:\n return [\"DISTINCT\"], []", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ask_not_null_alteration(self, field_name, model_name):\n \"\"\"Changing a NULL field to NOT NULL.\"\"\"\n # None means quit\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def pull_request_url(self, repo, pull_request):\n \"\"\"\n Generate a URL to a pull request on the repository provider.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def segments_end(self, node):\n if debug:\n print(\"\\nEnd of segments element\")\n ic = 0\n ip = 0\n for cab in self.cables_:\n ic += 1\n for i in range(cab.first_, cab.first_ + cab.pcnt_):\n pt = self.points_[i]\n print(ip, pt.id_, pt.pid_, pt.x_, pt.y_, pt.z_, pt.d_)\n ip += 1\n print(\"ncable=\", ic, \" npoint=\", ip, \" nprox=\", self.nprox, \"\\n\")\n\n return", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def struct_name(self, names: NameGenerator) -> str:\n return f\"{exported_name(self.fullname)}Object\"", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def django_orm_maxlength_truncate(backend, details, user=None, is_new=False, *args, **kwargs):\n \"\"\"Truncate any value in details that corresponds with a field in the user\n model. Add this entry to the pipeline before update_user_details\"\"\"\n if user is None:\n return\n out = {}\n names = get_all_field_names(user)\n for name, value in details.items():\n if name in names and not _ignore_field(name, is_new):\n max_length = user._meta.get_field(name).max_length\n try:\n if max_length and len(value) > max_length:\n value = value[:max_length]\n except TypeError:\n pass\n out[name] = value\n return {\"details\": out}", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def allow_migrate(self, db, app_label, **hints):\n return True", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_minus_one(result, func, cargs):\n \"Error checking on routines that should not return -1.\"\n if result == -1:\n raise GEOSException(\n 'Error encountered in GEOS C function \"%s\".' % func.__name__\n )\n else:\n return result", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def firebase_credentials(request):\n return {\n \"firebase_api_key\": settings.FIREBASE_API_KEY,\n \"firebase_auth_domain\": settings.FIREBASE_AUTH_DOMAIN,\n \"firebase_project_id\": settings.FIREBASE_PROJECT_ID,\n \"firebase_storage_bucket\": settings.FIREBASE_STORAGE_BUCKET,\n \"firebase_messaging_sender_id\": settings.FIREBASE_MESSAGING_SENDER_ID,\n \"firebase_app_id\": settings.FIREBASE_APP_ID,\n \"firebase_measurement_id\": settings.FIREBASE_MEASUREMENT_ID,\n }", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def lock(f, flags):\n # File is not locked\n return False", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_resource_filename(self, manager: ResourceManager, resource_name: str):\n return self._fn(self.module_path, resource_name)", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def dispatch(self, request: Request, organization, **kwargs):\n if self.needs_auth(request.user):\n # TODO(dcramer): this should be a 401\n return Response(\n {\n \"error_type\": \"auth\",\n \"auth_url\": reverse(\"socialauth_associate\", args=[self.auth_provider]),\n },\n status=400,\n )\n\n try:\n fields = self.get_config()\n except Exception as e:\n return self.handle_api_error(e)\n\n if request.method == \"GET\":\n return Response(fields)\n\n validator = ConfigValidator(fields, request.data)\n if not validator.is_valid():\n return Response({\"error_type\": \"validation\", \"errors\": validator.errors}, status=400)\n\n try:\n config = self.validate_config(organization, validator.result, actor=request.user)\n except Exception as e:\n return self.handle_api_error(e)\n\n try:\n result = self.create_repository(\n organization=organization, data=config, actor=request.user\n )\n except PluginError as e:\n logger.exception(\"repo.create-error\")\n return Response({\"errors\": {\"__all__\": str(e)}}, status=400)\n\n try:\n with transaction.atomic(router.db_for_write(Repository)):\n repo = Repository.objects.create(\n organization_id=organization.id,\n name=result[\"name\"],\n external_id=result.get(\"external_id\"),\n url=result.get(\"url\"),\n config=result.get(\"config\") or {},\n provider=self.id,\n )\n except IntegrityError:\n # Try to delete webhook we just created\n try:\n repo = Repository(\n organization_id=organization.id,\n name=result[\"name\"],\n external_id=result.get(\"external_id\"),\n url=result.get(\"url\"),\n config=result.get(\"config\") or {},\n provider=self.id,\n )\n self.delete_repository(repo, actor=request.user)\n except PluginError:\n pass\n return Response(\n {\"errors\": {\"__all__\": \"A repository with that name already exists\"}}, status=400\n )\n else:\n repo_linked.send_robust(repo=repo, user=request.user, sender=self.__class__)\n\n return Response(serialize(repo, request.user), status=201)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def updateState(self, slot):\n\t\tself.createSetup()", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _get_webauthn_user_public_key_credential_descriptors(user, *, rp_id):\n \"\"\"\n Returns a webauthn.WebAuthnUser instance corresponding\n to the given user model, with properties suitable for\n usage within the webauthn API.\n \"\"\"\n return [\n PublicKeyCredentialDescriptor(id=base64url_to_bytes(credential.credential_id))\n for credential in user.webauthn\n ]", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def addNotifier(self, notifier, initial_call=True, immediate_feedback=True, extra_args=None, call_on_save_or_cancel=None): # TODO: camelCase the variables!\n\t\tif not callable(notifier):\n\t\t\traise TypeError(\"[Config] Error: Notifiers must be callable!\")\n\t\textraArgs = extra_args # This can be removed when all calling code is updated.\n\t\tif extraArgs is not None:\n\t\t\tself.extraArgs.append((notifier, extraArgs))\n\t\tif immediate_feedback:\n\t\t\tself.immediateNotifiers.append(notifier)\n\t\telse:\n\t\t\tself.finalNotifiers.append(notifier)\n\t\t# CHECKME:\n\t\t# Do we want to call the notifier:\n\t\t# - At all when adding it? (Yes, though optional - initial_call)\n\t\t# - When the default is active? (Yes)\n\t\t# - When no value *yet* has been set, because no config has\n\t\t# ever been read though that's not so easy to detect as\n\t\t# the entry could just be new. (Currently Yes)\n\t\tif initial_call:\n\t\t\tif extraArgs:\n\t\t\t\tnotifier(self, extraArgs)\n\t\t\telse:\n\t\t\t\tnotifier(self)", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def validate(self, password, user=None):\n if password.lower().strip() in self.passwords:\n raise ValidationError(\n self.get_error_message(),\n code=\"password_too_common\",\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def process_keystroke(self, key, mod):\n\n # process arrow keys if an object is selected\n if self.currently_selected:\n up = 0\n strafe = 0\n\n if key == pygame.K_UP:\n up = 1\n if key == pygame.K_DOWN:\n up = -1\n if key == pygame.K_LEFT:\n strafe = -1\n if key == pygame.K_RIGHT:\n strafe = 1\n\n self.move_selected_node(up, strafe)\n\n if key == pygame.K_f:\n pygame.display.toggle_fullscreen()\n\n if key == pygame.K_TAB:\n self.cycle_cameras()\n\n if key in [pygame.K_ESCAPE, pygame.K_q]:\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "def raises404(request):\n resolver = get_resolver(None)\n resolver.resolve(\"/not-in-urls\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def CreateParaViewFilter2(self, inInputOperation, ioPipeAndViewsState):\n return self.CreateParaViewFilter(inInputOperation)", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def create_default_site(\n app_config,\n verbosity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n try:\n Site = apps.get_model(\"sites\", \"Site\")\n except LookupError:\n return\n\n if not router.allow_migrate_model(using, Site):\n return\n\n if not Site.objects.using(using).exists():\n # The default settings set SITE_ID = 1, and some tests in Django's test\n # suite rely on this value. However, if database sequences are reused\n # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that\n # the next id will be 1, so we coerce it. See #15573 and #16353. This\n # can also crop up outside of tests - see #15346.\n if verbosity >= 2:\n print(\"Creating example.com Site object\")\n Site(\n pk=getattr(settings, \"SITE_ID\", 1), domain=\"example.com\", name=\"example.com\"\n ).save(using=using)\n\n # We set an explicit pk instead of relying on auto-incrementation,\n # so we need to reset the database sequence. See #17415.\n sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site])\n if sequence_sql:\n if verbosity >= 2:\n print(\"Resetting sequence\")\n with connections[using].cursor() as cursor:\n for command in sequence_sql:\n cursor.execute(command)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def can_movieoff(self, item):\n\t\treturn True", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def ask_merge(self, app_label):\n \"\"\"Should these migrations really be merged?\"\"\"\n return self.defaults.get(\"ask_merge\", False)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def maybe_clean_local_cache(self, **kwargs):\n # Periodically force an expire on the local cache.\n # This cleanup is purely to keep memory low and garbage collect\n # old values. It's not required to run to keep things consistent.\n # Internally, if an option is fetched and it's expired, it gets\n # evicted immediately. This is purely for options that haven't\n # been fetched since they've expired.\n if not self._local_cache:\n return\n if random() < 0.25:\n self.clean_local_cache()", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def last_sent(self, to, subject):\n # We don't store previously sent emails, so nothing to comapre against\n return None", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def get_redis_client(db=0):\n client = cache.client.get_client()\n assert isinstance(client, redis.Redis)\n return client", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def convert_durationfield_value(self, value, expression, connection):\n if value is not None:\n return datetime.timedelta(0, 0, value)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def Plugins(**kwargs):\n\tlist = []\n\n\tif max_fcc > 0:\n\t\tlist.append(\n\t\t\tPluginDescriptor(name=\"FCCSupport\",\n\t\t\tdescription=\"Fast Channel Change support\",\n\t\t\twhere=[PluginDescriptor.WHERE_SESSIONSTART],\n\t\t\tfnc=FCCSupportInit))\n\n\t\tlist.append(\n\t\t\tPluginDescriptor(name=\"FCCExtensionMenu\",\n\t\t\tdescription=\"Fast Channel Change menu\",\n\t\t\twhere=[PluginDescriptor.WHERE_EXTENSIONSINGLE],\n\t\t\tfnc=addExtentions))\n\n\t\tlist.append(\n\t\t\tPluginDescriptor(name=\"FCCSetup\",\n\t\t\tdescription=_(\"Fast Channel Change Setup\"),\n\t\t\twhere=[PluginDescriptor.WHERE_MENU],\n\t\t\tneedsRestart=False,\n\t\t\tfnc=main))\n\n\treturn list", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def inject_rename_contenttypes_operations(\n plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs\n):\n \"\"\"\n Insert a `RenameContentType` operation after every planned `RenameModel`\n operation.\n \"\"\"\n if plan is None:\n return\n\n # Determine whether or not the ContentType model is available.\n try:\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n except LookupError:\n available = False\n else:\n if not router.allow_migrate_model(using, ContentType):\n return\n available = True\n\n for migration, backward in plan:\n if (migration.app_label, migration.name) == (\"contenttypes\", \"0001_initial\"):\n # There's no point in going forward if the initial contenttypes\n # migration is unapplied as the ContentType model will be\n # unavailable from this point.\n if backward:\n break\n else:\n available = True\n continue\n # The ContentType model is not available yet.\n if not available:\n continue\n inserts = []\n for index, operation in enumerate(migration.operations):\n if isinstance(operation, migrations.RenameModel):\n operation = RenameContentType(\n migration.app_label,\n operation.old_name_lower,\n operation.new_name_lower,\n )\n inserts.append((index + 1, operation))\n for inserted, (index, operation) in enumerate(inserts):\n migration.operations.insert(inserted + index, operation)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _to_config_structure(self, version: int):\n return ACTIONS.index(self.key) | (ACTION_FLAGS[self.flag, self.range] << ACTION_BITSIZE)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _resolve_cpm(\n self,\n args: Mapping[str, str | Column | SelectType | int | float],\n alias: str | None,\n extra_condition: Function | None = None,\n ) -> SelectType:\n assert (\n self.builder.params.end is not None and self.builder.params.start is not None\n ), f\"params.end: {self.builder.params.end} - params.start: {self.builder.params.start}\"\n interval = (self.builder.params.end - self.builder.params.start).total_seconds()\n\n base_condition = Function(\n \"equals\",\n [\n Column(\"metric_id\"),\n self.resolve_metric(\"function.duration\"),\n ],\n )\n if extra_condition:\n condition = Function(\"and\", [base_condition, extra_condition])\n else:\n condition = base_condition\n\n return Function(\n \"divide\",\n [\n Function(\n \"countIf\",\n [\n Column(\"value\"),\n condition,\n ],\n ),\n Function(\"divide\", [interval, 60]),\n ],\n alias,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def download_segment(segment: RecordingSegmentStorageMeta, span: Any) -> bytes:\n results = _download_segment(segment)\n return results[1] if results is not None else b\"[]\"", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def receive_problem_report(\n self,\n problem_report: OOBProblemReport,\n receipt: MessageReceipt,\n conn_record: ConnRecord,\n ) -> None:\n \"\"\"Receive and process a ProblemReport message from the inviter to invitee.\n\n Process a `ProblemReport` message by updating the OobRecord\n state to `not_accepted`.\n\n Args:\n problem_report: The `OOBProblemReport` to process\n receipt: The message receipt\n conn_record: The connection record associated with the OOB record\n\n Returns:\n None\n\n Raises:\n OutOfBandManagerError: if there is an error in processing the\n HandshakeReuseAccept message\n\n \"\"\"\n invi_msg_id = problem_report._thread.pthid\n thread_reuse_msg_id = problem_report._thread.thid\n try:\n async with self.profile.session() as session:\n oob_record = await OobRecord.retrieve_by_tag_filter(\n session,\n {\"invi_msg_id\": invi_msg_id, \"reuse_msg_id\": thread_reuse_msg_id},\n )\n oob_record.state = OobRecord.STATE_NOT_ACCEPTED\n await oob_record.save(session)\n except Exception as e:\n raise OutOfBandManagerError(\n (\n \"Error processing problem report message \"\n f\"for OOB invitation {invi_msg_id}, {e}\"\n )\n )", "smellKey": "S1172", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def run(input_ooi: HTTPHeader, additional_oois: list, config: dict[str, Any]) -> Iterator[OOI]:\n network = Network(name=\"internet\")\n\n if input_ooi.key.lower() == \"location\":\n if is_url(input_ooi.value):\n u = URL(raw=input_ooi.value, network=network.reference)\n else:\n # url is not a url but a relative path\n http_url = input_ooi.reference.tokenized.resource.web_url\n # allow for ipaddress http urls\n netloc = http_url.netloc.name if \"name\" in http_url.netloc.root else http_url.netloc.address\n original_url = f\"{http_url.scheme}://{netloc}{http_url.path}\"\n u = URL(raw=urljoin(original_url, input_ooi.value), network=network.reference)\n yield u\n http_header_url = HTTPHeaderURL(header=input_ooi.reference, url=u.reference)\n yield http_header_url\n\n if input_ooi.key.lower() == \"content-security-policy\":\n urls_and_hostname = re.findall(r\"(?:(?:https?|ftp):\\/\\/)?[\\w/\\-?=%.]+\\.[\\w/\\-&?=%.]+\", input_ooi.value)\n\n for url_or_hostname in urls_and_hostname:\n try:\n u = URL(raw=url_or_hostname, network=network.reference)\n yield u\n http_header_url = HTTPHeaderURL(header=input_ooi.reference, url=u.reference)\n yield http_header_url\n # some hostnames get classified as urls by the regex here, they need to be parsed by another bit\n except ValidationError:\n name = url_or_hostname if url_or_hostname[0] != \".\" else url_or_hostname[1:]\n h = Hostname(name=name, network=network.reference)\n yield h\n http_header_hostname = HTTPHeaderHostname(header=input_ooi.reference, hostname=h.reference)\n yield http_header_hostname", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def visit_Break(self, node: nodes.Break, frame: Frame) -> None:\n self.writeline(\"break\", node)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def make_data(self, data):\n return []", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def runner_on_unreachable(\n self, event_data, host=None, task=None, res=None, **kwargs\n ):\n detail = {\n \"action\": event_data.get(\"task_action\", \"\"),\n \"res\": res,\n \"rc\": 255,\n \"stderr\": \";\".join([res.get(\"stderr\", \"\"), res.get(\"msg\", \"\")]).strip(\";\"),\n }\n self.result[\"dark\"][host][task] = detail", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def run(hostname: Hostname, additional_oois: list[DNSAAAARecord | DNSARecord], config: dict[str, Any]) -> Iterator[OOI]:\n dns_ns_records = [dns_ns_record for dns_ns_record in additional_oois if isinstance(dns_ns_record, DNSNSRecord)]\n dns_aaaa_records = [\n dns_aaaa_record for dns_aaaa_record in additional_oois if isinstance(dns_aaaa_record, DNSAAAARecord)\n ]\n\n if dns_aaaa_records:\n return\n\n for dns_ns_record in dns_ns_records:\n finding_type = KATFindingType(id=\"KAT-NAMESERVER-NO-IPV6\")\n yield finding_type\n yield Finding(\n finding_type=finding_type.reference,\n ooi=dns_ns_record.reference,\n description=\"This nameserver has no IPv6 address\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def add_throw_to_generator_class(\n builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> None:\n \"\"\"Generates the 'throw' method for a generator class.\"\"\"\n with builder.enter_method(fn_info.generator_class.ir, \"throw\", object_rprimitive, fn_info):\n typ = builder.add_argument(\"type\", object_rprimitive)\n val = builder.add_argument(\"value\", object_rprimitive, ARG_OPT)\n tb = builder.add_argument(\"traceback\", object_rprimitive, ARG_OPT)\n\n # Because the value and traceback arguments are optional and hence\n # can be NULL if not passed in, we have to assign them Py_None if\n # they are not passed in.\n none_reg = builder.none_object()\n builder.assign_if_null(val, lambda: none_reg, builder.fn_info.fitem.line)\n builder.assign_if_null(tb, lambda: none_reg, builder.fn_info.fitem.line)\n\n # Call the helper function using the arguments passed in, and return that result.\n result = builder.add(\n Call(\n fn_decl,\n [builder.self(), builder.read(typ), builder.read(val), builder.read(tb), none_reg],\n fn_info.fitem.line,\n )\n )\n builder.add(Return(result))", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def db_for_write(self, model, **hints):\n return DEFAULT_DB_ALIAS", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def add_next_to_generator_class(\n builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> None:\n \"\"\"Generates the '__next__' method for a generator class.\"\"\"\n with builder.enter_method(fn_info.generator_class.ir, \"__next__\", object_rprimitive, fn_info):\n none_reg = builder.none_object()\n # Call the helper function with error flags set to Py_None, and return that result.\n result = builder.add(\n Call(\n fn_decl,\n [builder.self(), none_reg, none_reg, none_reg, none_reg],\n fn_info.fitem.line,\n )\n )\n builder.add(Return(result))", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def Plugins(**kwargs):\n\tif nimmanager.hasNimType(\"DVB-S\"):\n\t\treturn [\n\t\t\tPluginDescriptor(name=_(\"Programmlisten-Updater V\") + \"1.3\", description=_(\"Programmlisten-Updater from DXAndy\"), icon=\"plugin.png\", where=PluginDescriptor.WHERE_PLUGINMENU, fnc=main),\n\t\t\tPluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, fnc=sessionstart),\n\t\t\tPluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, fnc=autoStart)\n\t\t]\n\telse:\n\t\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:\n session_finish(session)", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def inode_op(self, inodes, locked_ops):\n llfuse.invalidate_inode(self.inode)\n return True", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def URLValidator(value: str, **kwargs: object) -> str:\n if not value.startswith((\"http://\", \"https://\")):\n raise PluginError(\"Not a valid URL.\")\n if not is_valid_url(value):\n raise PluginError(\"Not a valid URL.\")\n return value", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def binary_placeholder_sql(self, value):\n \"\"\"\n Some backends require special syntax to insert binary content (MySQL\n for example uses '_binary %s').\n \"\"\"\n return \"%s\"", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _alter_column_database_default_sql(\n self, model, old_field, new_field, drop=False\n ):\n \"\"\"\n Hook to specialize column database default alteration.\n\n Return a (sql, params) fragment to add or drop (depending on the drop\n argument) a default to new_field's column.\n \"\"\"\n if drop:\n sql = self.sql_alter_column_no_default\n default_sql = \"\"\n params = []\n else:\n sql = self.sql_alter_column_default\n default_sql, params = self.db_default_sql(new_field)\n\n new_db_params = new_field.db_parameters(connection=self.connection)\n return (\n sql\n % {\n \"column\": self.quote_name(new_field.column),\n \"type\": new_db_params[\"type\"],\n \"default\": default_sql,\n },\n params,\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def allow_relation(self, obj1, obj2, **hints):\n return obj1._state.db in (\"default\", \"other\") and obj2._state.db in (\n \"default\",\n \"other\",\n )", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def generateCertCsr(\n redfishObject, commonName, extensions, caKey, caCert, serial\n):\n\n try:\n socket.inet_aton(commonName)\n commonName = \"IP: \" + commonName\n except socket.error:\n commonName = \"DNS: \" + commonName\n\n CSRRequest = {\n \"CommonName\": commonName,\n \"City\": \"San Fransisco\",\n \"Country\": \"US\",\n \"Organization\": \"\",\n \"OrganizationalUnit\": \"\",\n \"State\": \"CA\",\n \"CertificateCollection\": {\n \"@odata.id\": \"/redfish/v1/Managers/bmc/NetworkProtocol/HTTPS/Certificates\",\n },\n \"AlternativeNames\": [\n commonName,\n \"DNS: localhost\",\n \"IP: 127.0.0.1\",\n ],\n }\n\n response = redfishObject.post(\n \"/redfish/v1/CertificateService/Actions/CertificateService.GenerateCSR\",\n body=CSRRequest,\n )\n\n if response.status != 200:\n raise Exception(\"Failed to create CSR\")\n\n csrString = response.dict[\"CSRString\"]\n\n return crypto.load_certificate_request(crypto.FILETYPE_PEM, csrString)", "smellKey": "S1172", "smellId": null, "repo": "edtanous_bmcweb", "language": "python"} {"function": "def analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> Type:\n if name == \"__bool__\":\n literal_false = LiteralType(False, fallback=mx.named_type(\"builtins.bool\"))\n return CallableType(\n arg_types=[],\n arg_kinds=[],\n arg_names=[],\n ret_type=literal_false,\n fallback=mx.named_type(\"builtins.function\"),\n )\n else:\n return _analyze_member_access(name, mx.named_type(\"builtins.object\"), mx)", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def authorize(\n permission=None,\n target_name=None,\n packet_name=None,\n interface_name=None,\n router_name=None,\n manual=False,\n scope=None,\n):\n if not scope:\n raise AuthError(\"Scope is required\")", "smellKey": "S1172", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def run(input_ooi: IPAddress, additional_oois: list[IPPort | Website], config: dict[str, Any]) -> Iterator[OOI]:\n websites = [website for website in additional_oois if isinstance(website, Website)]\n\n open_ports = [port.port for port in additional_oois if isinstance(port, IPPort)]\n if 80 in open_ports and 443 not in open_ports:\n ft = KATFindingType(id=\"KAT-HTTPS-NOT-AVAILABLE\")\n for website in websites:\n yield Finding(\n ooi=website.reference,\n finding_type=ft.reference,\n description=\"HTTP port is open, but HTTPS port is not open\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def load_span_serialized_performance_issues(self, light: bool) -> None:\n \"\"\"Rewriting load_performance_issues from scratch so the logic is more independent\"\"\"\n memoized_groups = {}\n for event_span in self.event[\"occurrence_spans\"]:\n unique_spans: set[str] = set()\n start: float | None = None\n end: float | None = None\n suspect_spans: list[str] = []\n problem = event_span[\"problem\"]\n offender_span_ids = problem.evidence_data.get(\"offender_span_ids\", [])\n for group_id in self.event[\"occurrence_to_issue_id\"][problem.id]:\n if group_id not in memoized_groups:\n memoized_groups[group_id] = Group.objects.get(\n id=group_id, project=self.event[\"project.id\"]\n )\n group = memoized_groups[group_id]\n if event_span.get(\"span_id\") in offender_span_ids:\n start_timestamp = float(event_span[\"precise.start_ts\"])\n if start is None:\n start = start_timestamp\n else:\n start = min(start, start_timestamp)\n end_timestamp = float(event_span[\"precise.finish_ts\"])\n if end is None:\n end = end_timestamp\n else:\n end = max(end, end_timestamp)\n suspect_spans.append(event_span[\"span_id\"])\n\n parent_span_ids = problem.evidence_data.get(\"parent_span_ids\")\n if parent_span_ids is not None:\n unique_spans = unique_spans.union(parent_span_ids)\n\n # Logic for qualified_short_id is copied from property on the Group model\n # to prevent an N+1 query from accessing project.slug everytime\n qualified_short_id = None\n project_slug = self.event[\"project\"]\n if group.short_id is not None:\n qualified_short_id = f\"{project_slug.upper()}-{base32_encode(group.short_id)}\"\n\n self.performance_issues.append(\n {\n \"event_id\": self.event[\"id\"],\n \"issue_id\": group_id,\n \"issue_short_id\": qualified_short_id,\n \"span\": list(unique_spans),\n \"suspect_spans\": suspect_spans,\n \"project_id\": self.event[\"project.id\"],\n \"project_slug\": self.event[\"project\"],\n \"title\": group.title,\n \"level\": constants.LOG_LEVELS[group.level],\n \"culprit\": group.culprit,\n \"type\": group.type,\n \"start\": start,\n \"end\": end,\n }\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def migrate_to_version_10_2(json_flow, flow=None):\n \"\"\"\n Fixes malformed single message flows that have a base language but a message action that isn't localized\n \"\"\"\n # this is a case that can only arise from malformed revisions\n base_language = json_flow[\"base_language\"]\n if not base_language: # pragma: no cover\n base_language = \"base\"\n json_flow[\"base_language\"] = base_language\n\n def update_action(action):\n if action[\"type\"] == \"reply\":\n if not isinstance(action[\"msg\"], dict):\n action[\"msg\"] = {base_language: action[\"msg\"]}\n return action\n\n return map_actions(json_flow, update_action)", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def check_model_name_lengths(app_configs=None, **kwargs):\n if app_configs is None:\n models = apps.get_models()\n else:\n models = chain.from_iterable(\n app_config.get_models() for app_config in app_configs\n )\n errors = []\n for model in models:\n if len(model._meta.model_name) > 100:\n errors.append(\n Error(\n \"Model names must be at most 100 characters (got %d).\"\n % (len(model._meta.model_name),),\n obj=model,\n id=\"contenttypes.E005\",\n )\n )\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_issue_types(self, project_id):\n return self._get_stub_data(\"issue_types_response.json\")", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def forget(self, request, **kw):\n # This is a NO-OP because our Macaroon header policy doesn't allow\n # the ability for authentication to \"forget\" the user id. This\n # assumes it has been configured in clients somewhere out of band.\n return []", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def _CreatePipeline(coprocessor, datadescription):\n class Pipeline:\n dummyItem = \"blah\"\n #global cp_views, cp_writers\n\n #print \"CreatePipeline startup\"\n #print \"cp_views len is \" + str(len(cp_views))\n\n #rigid_body_impact_6_ff_e = coprocessor.CreateProducer( datadescription, \"input\" )\n\n #SetUpCoProcessor(coprocessor)\n #SetCpViewsAndCpWriters(cp_views, cp_writers)\n\n#QQQQQ->we want to do this and CreateProducer once for each output results block,\n#reuse same coprocesor instance (?), then have LocalWriteImages3 only do the images for a given output results bloxk:q\n\n #PhactoriScript.CreatePipeline(datadescription)\n \n return Pipeline()", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def flash(self, **kwargs):\n if self.hex_name is not None and os.path.isfile(self.hex_name):\n fname = self.hex_name\n elif self.bin_name is not None and os.path.isfile(self.bin_name):\n self.logger.warning(\n 'hex file ({}) does not exist; falling back on .bin ({}). '.\n format(self.hex_name, self.bin_name) +\n 'Consider enabling CONFIG_BUILD_OUTPUT_HEX.')\n fname = self.bin_name\n else:\n raise ValueError(\n 'Cannot flash; no hex ({}) or bin ({}) files found. '.format(\n self.hex_name, self.bin_name))\n\n erase_method = 'chip' if self.erase else 'sector'\n\n cmd = ([self.pyocd] +\n ['flash'] +\n self.pyocd_config_args +\n ['-e', erase_method] +\n self.flash_addr_args +\n self.daparg_args +\n self.target_args +\n self.board_args +\n self.frequency_args +\n self.tool_opt_args +\n self.flash_extra +\n [fname])\n\n self.logger.info('Flashing file: {}'.format(fname))\n self.check_call(cmd)", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def _3_2_generate_django_models(ctx):\n models = subprocess.check_output([sys.executable, str(DJANGO_DIR / '..' / '_django_model_generator.py')], timeout=30)\n (DJANGO_DIR / 'models.py').write_bytes(models)", "smellKey": "S1172", "smellId": null, "repo": "open-condo-software_condo", "language": "python"} {"function": "def dispatch(self, request: Request, organization, **kwargs):\n try:\n config = self.get_repository_data(organization, request.data)\n except Exception as e:\n return self.handle_api_error(e)\n\n try:\n result, repo = self.create_repository(repo_config=config, organization=organization)\n except RepoExistsError:\n metrics.incr(\"sentry.integration_repo_provider.repo_exists\")\n raise\n except Exception as e:\n return self.handle_api_error(e)\n\n repo_linked.send_robust(repo=repo, user=request.user, sender=self.__class__)\n\n analytics.record(\n \"integration.repo.added\",\n provider=self.id,\n id=result.get(\"integration_id\"),\n organization_id=organization.id,\n )\n return Response(\n repository_service.serialize_repository(\n organization_id=organization.id,\n id=repo.id,\n as_user=(\n serialize_rpc_user(request.user)\n if isinstance(request.user, User)\n else request.user\n ),\n ),\n status=201,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:\n for child in node.iter_child_nodes(exclude=(\"call\",)):\n self.sym_visitor.visit(child)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_function_index(column_expr, depth=0):\n \"\"\"\n If column_expr list contains a function, returns the index of its function name\n within column_expr (and assumption is that index + 1 is the list of arguments),\n otherwise None.\n\n A function expression is of the form:\n [func, [arg1, arg2]] => func(arg1, arg2)\n If a string argument is followed by list arg, the pair of them is assumed\n to be a nested function call, with extra args to the outer function afterward.\n [func1, [func2, [arg1, arg2], arg3]] => func1(func2(arg1, arg2), arg3)\n Although at the top level, there is no outer function call, and the optional\n 3rd argument is interpreted as an alias for the entire expression.\n [func, [arg1], alias] => function(arg1) AS alias\n You can also have a function part of an argument list:\n [func1, [arg1, func2, [arg2, arg3]]] => func1(arg1, func2(arg2, arg3))\n \"\"\"\n index = None\n if isinstance(column_expr, (tuple, list)):\n i = 0\n while i < len(column_expr) - 1:\n # The assumption here is that a list that follows a string means\n # the string is a function name\n if isinstance(column_expr[i], str) and isinstance(column_expr[i + 1], (tuple, list)):\n assert column_expr[i] in SAFE_FUNCTIONS or SAFE_FUNCTION_RE.match(\n column_expr[i]\n ), column_expr[i]\n index = i\n break\n else:\n i = i + 1\n\n return index\n else:\n return None", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def loads(value: str | bytes, use_rapid_json: bool = False, **kwargs: NoReturn) -> Any:\n if use_rapid_json is True:\n return rapidjson.loads(value)\n else:\n return _default_decoder.decode(value)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def pluralize(self, *args, **kwargs):\n self._fail()", "smellKey": "S1172", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def watch_for_translation_changes(sender, **kwargs):\n \"\"\"Register file watchers for .mo files in potential locale paths.\"\"\"\n from django.conf import settings\n\n if settings.USE_I18N:\n directories = [Path(\"locale\")]\n directories.extend(\n Path(config.path) / \"locale\"\n for config in apps.get_app_configs()\n if not is_django_module(config.module)\n )\n directories.extend(Path(p) for p in settings.LOCALE_PATHS)\n for path in directories:\n sender.watch_dir(path, \"**/*.mo\")", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def UseMpiToGetGlobalCellPointsClosestV5(inInputFilter, inLocalCellPointList, inLocalDistSqrdList):\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest entered\\n\", 100)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"inLocalCellPointList:\\n\" + str(inLocalCellPointList) + \"\\ninLocalDistSqrdList:\\n\" + str(inLocalDistSqrdList) + \"\\n\")\n pidWithDataList, globalDistSqrdList = GetPidWithLeastValueListV5(inLocalDistSqrdList)\n if PhactoriDbg(100):\n myDebugPrint3(\"pidWithDataList:\\n\" + str(pidWithDataList) + \"\\nglobalDistSqrdList:\\n\" + str(globalDistSqrdList) + \"\\n\")\n\n #convert cell point list to array of doubles and ints, use mpi reduce to share\n #the values, then convert back to cell point list\n serializeFloatArray = []\n serializeIntArray = []\n\n #convert cell point list to array of doubles\n cellPointFloatArray = []\n myPid = SmartGetLocalProcessId()\n for ii, oneCellPoint in enumerate(inLocalCellPointList):\n if pidWithDataList[ii] == myPid:\n cellPointFloatArray.append(oneCellPoint[0])\n cellPointFloatArray.append(oneCellPoint[1])\n cellPointFloatArray.append(oneCellPoint[2])\n else:\n cellPointFloatArray.append(0.0)\n cellPointFloatArray.append(0.0)\n cellPointFloatArray.append(0.0)\n\n #use mpi reduce to spread array correctly\n globalCellPointFloatArray = UseReduceOnFloatList(cellPointFloatArray, 2)\n\n #now create return global cell point list from arrays\n numCells = len(inLocalCellPointList)\n returnGlobalCellPointList = []\n for ii in range(0,numCells):\n myndx = ii*3\n oneCellPoint = [globalCellPointFloatArray[myndx],\n globalCellPointFloatArray[myndx+1],\n globalCellPointFloatArray[myndx+2]]\n returnGlobalCellPointList.append(oneCellPoint)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"returnGlobalCellPointList:\\n\" + str(returnGlobalCellPointList) + \"\\n\")\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest returning\\n\", 100)\n return returnGlobalCellPointList, globalDistSqrdList", "smellKey": "S1172", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def Plugins(**kwargs):\n\tfrom os import path\n\tif path.exists(\"/proc/stb/vmpeg/0/clip_left\"):\n\t\tfrom Plugins.Plugin import PluginDescriptor\n\t\treturn [PluginDescriptor(name=\"Video clipping setup\", description=\"\", where=PluginDescriptor.WHERE_SESSIONSTART, fnc=startup),\n\t\t\t\t\tPluginDescriptor(name=_(\"Video clipping\"), description=_(\"clip overscan / letterbox borders\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=startMain)]\n\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def check_finders(app_configs=None, **kwargs):\n \"\"\"Check all registered staticfiles finders.\"\"\"\n errors = []\n for finder in get_finders():\n try:\n finder_errors = finder.check()\n except NotImplementedError:\n pass\n else:\n errors.extend(finder_errors)\n return errors", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\":\n return not ownership == \"self\"\n if context == \"sandbox\" and resource[\"membership\"][\"role\"] is not None:\n return False\n if context == \"organization\" and membership is None:\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def _on_step_closed(self, step):\n self._send_processed_mail_to_applicant()", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def plugin(version: str) -> type[CallableInstancePlugin]:\n return CallableInstancePlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n yield 3", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def to_email_html(self, event, **kwargs):\n body = self.to_string(event)\n if not body:\n return \"\"\n return f\"<pre>{escape(body)}</pre>\"", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def async_streaming(request):\n async def async_streaming_generator():\n yield b\"streaming\"\n yield b\" \"\n yield b\"content\"\n\n return StreamingHttpResponse(async_streaming_generator())", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def plugin(version: str) -> type[CustomErrorCodePlugin]:\n return CustomErrorCodePlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:\n \"\"\"\n Return true if the commit hash checked out at dest matches\n the revision in url.\n\n Always return False, if the VCS does not support immutable commit\n hashes.\n\n This method does not check if there are local uncommitted changes\n in dest after checkout, as pip currently has no use case for that.\n \"\"\"\n return False", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource, same_org):\n if context == \"sandbox\" and membership:\n return False\n if scope == \"list\" and ownership != \"None\":\n return False\n if context == \"sandbox\" and not same_org:\n return False\n if scope.startswith(\"create\") and ownership != \"None\":\n return False\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def process_view(self, request, view_func, view_args, view_kwargs):\n \"\"\"\n If the request method is HEAD and either the IP is internal or the\n user is a logged-in staff member, return a response with an x-view\n header indicating the view function. This is used to lookup the view\n function for an arbitrary page.\n \"\"\"\n if not hasattr(request, \"user\"):\n raise ImproperlyConfigured(\n \"The XView middleware requires authentication middleware to \"\n \"be installed. Edit your MIDDLEWARE setting to insert \"\n \"'django.contrib.auth.middleware.AuthenticationMiddleware'.\"\n )\n if request.method == \"HEAD\" and (\n request.META.get(\"REMOTE_ADDR\") in settings.INTERNAL_IPS\n or (request.user.is_active and request.user.is_staff)\n ):\n response = HttpResponse()\n response.headers[\"X-View\"] = get_view_name(view_func)\n return response", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(\n ip_address: IPAddressV4, additional_oois: list[IPService | ResolvedHostname], config: dict[str, Any]\n) -> Iterator[OOI]:\n def is_service_http(ip_service: IPService) -> bool:\n return \"http\" in ip_service.service.tokenized.name.lower().strip()\n\n hostnames = [resolved.hostname for resolved in additional_oois if isinstance(resolved, ResolvedHostname)]\n services = [ip_service for ip_service in additional_oois if isinstance(ip_service, IPService)]\n http_services = filter(is_service_http, services)\n\n # website is cartesian product of hostname and http services\n for http_service in http_services:\n for hostname in hostnames:\n yield Website(hostname=hostname, ip_service=http_service.reference)", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def config(request):\n return {\n \"COMPONENTS_DEV_MODE\": getattr(settings, \"COMPONENTS_DEV_MODE\", False),\n \"EDITOR_DEV_MODE\": getattr(settings, \"EDITOR_DEV_MODE\", False),\n }", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def Plugins(**kwargs):\n\tif config.usage.setup_level.index >= 2 and os_path.exists(\"/proc/stb/vmpeg/0/pep_apply\"):\n\t\treturn PluginDescriptor(name=_(\"Video enhancement setup\"), description=_(\"Advanced video enhancement setup\"), where=PluginDescriptor.WHERE_MENU, needsRestart=False, fnc=startSetup)\n\treturn []", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def drop_new_procedures(apps, schema_editor):\n h.run_sql_files([\n '0121_index_facilities.sql',\n '0121_index_facilities_by.sql',\n ])\n h.drop_function('index_custom_text(text)')", "smellKey": "S1172", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def visit_Macro(self, node: nodes.Macro, **kwargs: t.Any) -> None:\n self.symbols.store(node.name)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_relocation_storage(config=None) -> Storage:\n from sentry import options as options_store\n\n backend = options_store.get(\"filestore.relocation-backend\")\n relocation = options_store.get(\"filestore.relocation-options\")\n\n try:\n backend = settings.SENTRY_FILESTORE_ALIASES[backend]\n except KeyError:\n pass\n\n storage = import_string(backend)\n return storage(**relocation)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_latest_serial_number(self, part, **kwargs):\n \"\"\"Return the 'latest' serial number for a given Part instance.\n\n A plugin which implements this method can either return:\n - A string which represents the \"latest\" serial number\n - None (null value) if the latest value could not be determined\n\n Arguments:\n part: The Part instance for which the latest serial number is being requested\n\n Returns:\n The latest serial number (string), or None\n \"\"\"\n # Default implementation returns None\n return None", "smellKey": "S1172", "smellId": null, "repo": "inventree_InvenTree", "language": "python"} {"function": "def plugin(version: str) -> type[AddOverrideMethodPlugin]:\n return AddOverrideMethodPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def Plugins(path, **kwargs):\n\tplugin = [\n\t\tPluginDescriptor(name=PROGRAM_NAME, description=f\"{PROGRAM_DESCRIPTION} ({PROGRAM_VERSION})\", where=PluginDescriptor.WHERE_PLUGINMENU, icon=\"FileCommander.png\", fnc=startFromPluginMenu),\n\t\t# PluginDescriptor(name=PROGRAM_NAME, where=PluginDescriptor.WHERE_FILESCAN, fnc=startFromFilescan) # Buggy!!!\n\t]\n\tif config.plugins.FileCommander.addToExtensionMenu.value:\n\t\tplugin.append(PluginDescriptor(name=PROGRAM_NAME, description=PROGRAM_DESCRIPTION, where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=startFromPluginMenu))\n\tif config.plugins.FileCommander.addToMainMenu.value:\n\t\tplugin.append(PluginDescriptor(name=PROGRAM_NAME, description=PROGRAM_DESCRIPTION, where=PluginDescriptor.WHERE_MENU, fnc=startFromMainMenu))\n\treturn plugin", "smellKey": "S1172", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_rxd_vars(secs):\n # TODO: filter by sections present\n result = []\n if have_rxd:\n for sp in species._all_species:\n sp = sp()\n if sp is not None and sp.name is not None:\n regions = sp._regions\n if hasattr(regions, \"__len__\"):\n regions = list(regions)\n else:\n regions = list([regions])\n result += [\n {\n \"type\": \"NEURONRXD\",\n \"name\": \"%s[%s]\" % (sp.name, r._name),\n \"species\": sp.name,\n \"region\": r._name,\n }\n for r in regions\n if r._name is not None\n ]\n return result", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def method_saving_307_redirect_query_string_view(request):\n return HttpResponseRedirect(\"/post_view/?hello=world\", status=307)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def spec_axial_resistance(self, node):\n self.biomechs_.append(BioMech(\"Ra\"))", "smellKey": "S1172", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def add(self, _key, _value, **kwargs):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def create_user(sender, user=None, ldap_user=None, **kwargs):\n user_groups = []\n for role in settings.IAM_ROLES:\n db_group = Group.objects.get(name=role)\n\n for ldap_group in settings.DJANGO_AUTH_LDAP_GROUPS[role]:\n if ldap_group.lower() in ldap_user.group_dns:\n user_groups.append(db_group)\n if role == settings.IAM_ADMIN_ROLE:\n user.is_staff = user.is_superuser = True\n break\n\n # It is important to save the user before adding groups. Please read\n # https://django-auth-ldap.readthedocs.io/en/latest/users.html#populating-users\n # The user instance will be saved automatically after the signal handler\n # is run.\n user.save()\n user.groups.set(user_groups)", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def serialize(data, projects):\n # filter out SDKs with empty sdk.name or sdk.version\n nonempty_sdks = [sdk for sdk in data if sdk[\"sdk.name\"] != \"\" and sdk[\"sdk.version\"] != \"\"]\n\n # Build datastructure of the latest version of each SDK in use for each\n # project we have events for.\n latest_sdks = chain.from_iterable(\n [\n {\n \"projectId\": str(project_id),\n \"sdkName\": sdk_name,\n \"sdkVersion\": max((s[\"sdk.version\"] for s in sdks), key=version.parse),\n }\n for sdk_name, sdks in groupby(sorted(sdks_used, key=by_sdk_name), key=by_sdk_name)\n ]\n for project_id, sdks_used in groupby(nonempty_sdks, key=by_project_id)\n )\n\n # Determine suggested upgrades for each project\n index_state = SdkIndexState()\n\n updates_list = [\n dict(\n **latest,\n suggestions=list(\n get_suggested_updates(\n # TODO: In the future it would be nice to also add\n # the integrations and modules the SDK is using.\n # However this isn't currently available in the\n # discover dataset from snuba.\n SdkSetupState(latest[\"sdkName\"], latest[\"sdkVersion\"], (), ()),\n index_state,\n ignore_patch_version=True,\n )\n ),\n )\n for latest in latest_sdks\n ]\n\n # Filter out SDKs that have no update suggestions\n return [update for update in updates_list if len(update[\"suggestions\"]) > 0]", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def is_valid(scope, context, ownership, privilege, membership, resource, same_org):\n if context == \"sandbox\" and membership:\n return False\n if context == \"sandbox\" and same_org:\n return False\n\n\n return True", "smellKey": "S1172", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def default_urlconf(request):\n \"\"\"Create an empty URLconf 404 error response.\"\"\"\n with builtin_template_path(\"default_urlconf.html\").open(encoding=\"utf-8\") as fh:\n t = DEBUG_ENGINE.from_string(fh.read())\n c = Context(\n {\n \"version\": get_docs_version(),\n }\n )\n\n return HttpResponse(t.render(c))", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def run(input_ooi: Hostname, additional_oois: list[DKIMExists | NXDOMAIN], config: dict[str, Any]) -> Iterator[OOI]:\n dkim_exists = [ooi for ooi in additional_oois if isinstance(ooi, DKIMExists)]\n nxdomains = (ooi for ooi in additional_oois if isinstance(ooi, NXDOMAIN))\n\n if any(nxdomains):\n return\n\n # only report finding when there is no DKIM record\n if (\n not tldextract.extract(input_ooi.name).subdomain\n and tldextract.extract(input_ooi.name).domain\n and not dkim_exists\n ):\n ft = KATFindingType(id=\"KAT-NO-DKIM\")\n yield ft\n yield Finding(\n ooi=input_ooi.reference,\n finding_type=ft.reference,\n description=\"This hostname does not support DKIM records\",\n )", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def store_custom_metric(\n self,\n name: str,\n tags: dict[str, str],\n value: int | float | dict[str, int | float],\n type: str | None = None,\n org_id: int | None = None,\n project_id: int | None = None,\n days_before_now: int = 0,\n hours_before_now: int = 0,\n minutes_before_now: int = 0,\n seconds_before_now: int = 0,\n aggregation_option: AggregationOption | None = None,\n ):\n self._store_metric(\n mri=name,\n tags=tags,\n value=value,\n org_id=org_id,\n project_id=project_id,\n days_before_now=days_before_now,\n hours_before_now=hours_before_now,\n minutes_before_now=minutes_before_now,\n seconds_before_now=seconds_before_now,\n aggregation_option=aggregation_option,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def write_manual(self, logical_name: str = \"\", write_function=None, **kwargs):\n if isinstance(write_function, types.FunctionType):\n return write_function()", "smellKey": "S1172", "smellId": null, "repo": "apache_plc4x", "language": "python"} {"function": "def timeseries_query(\n selected_columns: Sequence[str],\n query: str,\n snuba_params,\n rollup: int,\n referrer: str | None = None,\n zerofill_results: bool = True,\n comparison_delta: timedelta | None = None,\n functions_acl: list[str] | None = None,\n allow_metric_aggregates: bool = False,\n has_metrics: bool = False,\n use_metrics_layer: bool = False,\n on_demand_metrics_enabled: bool = False,\n on_demand_metrics_type: MetricSpecType | None = None,\n dataset: Dataset = Dataset.Discover,\n query_source: QuerySource | None = None,\n) -> SnubaTSResult:\n \"\"\"\n High-level API for doing arbitrary user timeseries queries against events.\n this API should match that of sentry.snuba.discover.timeseries_query\n \"\"\"\n equations, columns = categorize_columns(selected_columns)\n\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"TimeseriesSpanIndexedQueryBuilder\"):\n querybuilder = TimeseriesSpanEAPIndexedQueryBuilder(\n Dataset.EventsAnalyticsPlatform,\n {},\n rollup,\n snuba_params=snuba_params,\n query=query,\n selected_columns=columns,\n config=QueryBuilderConfig(\n functions_acl=functions_acl,\n ),\n )\n result = querybuilder.run_query(referrer, query_source=query_source)\n with sentry_sdk.start_span(op=\"spans_indexed\", name=\"query.transform_results\"):\n result = querybuilder.process_results(result)\n result[\"data\"] = (\n discover.zerofill(\n result[\"data\"],\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n [\"time\"],\n )\n if zerofill_results\n else result[\"data\"]\n )\n\n return SnubaTSResult(\n {\n \"data\": result[\"data\"],\n \"meta\": result[\"meta\"],\n },\n snuba_params.start_date,\n snuba_params.end_date,\n rollup,\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_resource_filename(self, manager, resource_name):\n return self._fn(self.module_path, resource_name)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def evaluate_marker(text, extra=None):\n \"\"\"\n Evaluate a PEP 508 environment marker.\n Return a boolean indicating the marker result in this environment.\n Raise SyntaxError if marker is invalid.\n\n This implementation uses the 'pyparsing' module.\n \"\"\"\n try:\n marker = packaging.markers.Marker(text)\n return marker.evaluate()\n except packaging.markers.InvalidMarker as e:\n raise SyntaxError(e) from e", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def last_version(self, *args, **kwargs):\n \"\"\"Gets the latest version of a bundle.\"\"\"\n if self._last_version is False:\n return None\n if len(args) > 0:\n bundle = self.bundle(args[0])\n if bundle:\n return bundle.versions[-1]\n return self._version_obj", "smellKey": "S1172", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def process_template_response(self, request, response):\n response.context_data[\"mw\"].append(self.__class__.__name__)\n return response", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _validate_app_names(self, loader, app_names):\n has_bad_names = False\n for app_name in app_names:\n try:\n apps.get_app_config(app_name)\n except LookupError as err:\n self.stderr.write(str(err))\n has_bad_names = True\n if has_bad_names:\n sys.exit(2)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def visit_For(\n self, node: nodes.For, for_branch: str = \"body\", **kwargs: t.Any\n ) -> None:\n if for_branch == \"body\":\n self.sym_visitor.visit(node.target, store_as_param=True)\n branch = node.body\n elif for_branch == \"else\":\n branch = node.else_\n elif for_branch == \"test\":\n self.sym_visitor.visit(node.target, store_as_param=True)\n if node.test is not None:\n self.sym_visitor.visit(node.test)\n return\n else:\n raise RuntimeError(\"Unknown for branch\")\n\n if branch:\n for item in branch:\n self.sym_visitor.visit(item)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _ignore_error(error):\n return None", "smellKey": "S1172", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def hotjar(request):\n return {\n \"hotjar_id\": settings.HOTJAR_ID,\n }", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def _match_compatible(self, version, constraint, prefix):\n if version < constraint:\n return False\n m = self.numeric_re.match(str(constraint))\n if not m:\n logger.warning('Cannot compute compatible match for version %s '\n ' and constraint %s', version, constraint)\n return True\n s = m.groups()[0]\n if '.' in s:\n s = s.rsplit('.', 1)[0]\n return _match_prefix(version, s)", "smellKey": "S1172", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def create_alert_rule_trigger_action(\n self,\n alert_rule_trigger=None,\n target_identifier=None,\n triggered_for_incident=None,\n *args,\n **kwargs,\n ):\n if not alert_rule_trigger:\n alert_rule_trigger = self.create_alert_rule_trigger()\n\n if not target_identifier:\n target_identifier = str(self.user.id)\n\n if triggered_for_incident is not None:\n Factories.create_incident_trigger(triggered_for_incident, alert_rule_trigger)\n\n return Factories.create_alert_rule_trigger_action(\n alert_rule_trigger, target_identifier=target_identifier, **kwargs\n )", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def start_group_reprocessing(\n project_id: int,\n group_id: int,\n remaining_events: str,\n max_events: int | None = None,\n acting_user_id: int | None = None,\n) -> int:\n from django.db import transaction\n\n with transaction.atomic(router.db_for_write(models.Group)):\n group = models.Group.objects.get(id=group_id)\n original_status = group.status\n original_substatus = group.substatus\n if original_status == models.GroupStatus.REPROCESSING:\n # This is supposed to be a rather unlikely UI race when two people\n # click reprocessing in the UI at the same time.\n #\n # During reprocessing the button is greyed out.\n raise RuntimeError(\"Cannot reprocess group that is currently being reprocessed\")\n\n original_short_id = group.short_id\n group.status = models.GroupStatus.REPROCESSING\n group.substatus = None\n # satisfy unique constraint of (project_id, short_id)\n # we manually tested that multiple groups with (project_id=1,\n # short_id=null) can exist in postgres\n group.short_id = None\n group.save()\n\n # Create a duplicate row that has the same attributes by nulling out\n # the primary key and saving\n group.pk = group.id = None # type: ignore[assignment] # XXX: intentional resetting pk\n new_group = group # rename variable just to avoid confusion\n del group\n new_group.status = original_status\n new_group.substatus = original_substatus\n new_group.short_id = original_short_id\n\n # this will be incremented by either the events that are\n # reprocessed, or handle_remaining_events\n #\n # XXX(markus): times_seen etc are unlikely to be correct ootb,\n # especially if handle_remaining_events is used a lot.\n new_group.times_seen = 0\n\n new_group.save()\n\n # This migrates all models that are associated with a group but not\n # directly with an event, i.e. everything but event attachments and user\n # reports. Those other updates are run per-event (in\n # post-process-forwarder) to not cause too much load on pg.\n for model in GROUP_MODELS_TO_MIGRATE:\n model.objects.filter(group_id=group_id).update(group_id=new_group.id)\n\n # Get event counts of issue (for all environments etc). This was copypasted\n # and simplified from groupserializer.\n event_count = sync_count = snuba.aliased_query(\n aggregations=[[\"count()\", \"\", \"times_seen\"]], # select\n dataset=Dataset.Events, # from\n conditions=[[\"group_id\", \"=\", group_id], [\"project_id\", \"=\", project_id]], # where\n referrer=\"reprocessing2.start_group_reprocessing\",\n )[\"data\"][0][\"times_seen\"]\n\n sentry_sdk.set_extra(\"event_count\", event_count)\n\n if max_events is not None:\n event_count = min(max_events, event_count)\n\n # Create activity on *old* group as that will serve the landing page for our\n # reprocessing status\n #\n # Later the activity is migrated to the new group where it is used to serve\n # the success message.\n new_activity = models.Activity.objects.create(\n type=ActivityType.REPROCESS.value,\n project=new_group.project,\n ident=str(group_id),\n group_id=group_id,\n user_id=acting_user_id,\n data={\"eventCount\": event_count, \"oldGroupId\": group_id, \"newGroupId\": new_group.id},\n )\n\n # New Activity Timestamp\n date_created = new_activity.datetime\n\n reprocessing_store.start_reprocessing(group_id, date_created, sync_count, event_count)\n\n return new_group.id", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _process_regex(cls, regex, rflags, state):\n \"\"\"Preprocess the regular expression component of a token definition.\"\"\"\n if isinstance(regex, Future):\n regex = regex.get()\n return re.compile(regex, rflags).match", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _index_columns(self, table, columns, col_suffixes, opclasses):\n return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _clear_cached_properties(self, setting, **kwargs):\n \"\"\"Reset setting based property values.\"\"\"\n if setting == \"MEDIA_ROOT\":\n self.__dict__.pop(\"base_location\", None)\n self.__dict__.pop(\"location\", None)\n elif setting == \"MEDIA_URL\":\n self.__dict__.pop(\"base_url\", None)\n elif setting == \"FILE_UPLOAD_PERMISSIONS\":\n self.__dict__.pop(\"file_permissions_mode\", None)\n elif setting == \"FILE_UPLOAD_DIRECTORY_PERMISSIONS\":\n self.__dict__.pop(\"directory_permissions_mode\", None)", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def debug_debugserver(self, command, **kwargs):\n # Per comments in the shell script, the NIOSII GDB server\n # doesn't exit gracefully, so it's better to explicitly search\n # for an unused port. The script picks a random value in\n # between 1024 and 49151, but we'll start with the\n # \"traditional\" 3333 choice.\n gdb_start = 3333\n nh = NetworkPortHelper()\n gdb_port = nh.get_unused_ports([gdb_start])[0]\n\n server_cmd = (['nios2-gdb-server',\n '--tcpport', str(gdb_port),\n '--stop', '--reset-target'])\n self.require(server_cmd[0])\n\n if command == 'debugserver':\n self.print_gdbserver_message(gdb_port)\n self.check_call(server_cmd)\n else:\n if self.elf_name is None:\n raise ValueError('Cannot debug; elf is missing')\n if self.gdb_cmd is None:\n raise ValueError('Cannot debug; no gdb specified')\n\n gdb_cmd = (self.gdb_cmd +\n self.tui_arg +\n [self.elf_name,\n '-ex', 'target remote :{}'.format(gdb_port)])\n self.require(gdb_cmd[0])\n\n self.print_gdbserver_message(gdb_port)\n self.run_server_and_client(server_cmd, gdb_cmd)", "smellKey": "S1172", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def playbook_on_stats(self, event_data, **kwargs):\n error_func = (\n lambda err, task_detail: err\n + f\"{task_detail[0]}: {task_detail[1]['stderr']};\"\n )\n for tp in [\"dark\", \"failures\"]:\n for host, tasks in self.result[tp].items():\n error = reduce(error_func, tasks.items(), \"\").strip(\";\")\n self.summary[tp][host] = error\n failures = list(self.result[\"failures\"].keys())\n dark_or_failures = list(self.result[\"dark\"].keys()) + failures\n\n for host, tasks in self.result.get(\"ignored\", {}).items():\n ignore_errors = reduce(error_func, tasks.items(), \"\").strip(\";\")\n if host in failures:\n self.summary[\"failures\"][host] += ignore_errors\n\n self.summary[\"ok\"] = list(set(self.result[\"ok\"].keys()) - set(dark_or_failures))\n self.summary[\"skipped\"] = list(\n set(self.result[\"skipped\"].keys()) - set(dark_or_failures)\n )", "smellKey": "S1172", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def _field_db_check(self, field, field_db_params):\n # Always check constraints with the same mocked column name to avoid\n # recreating constrains when the column is renamed.\n check_constraints = self.connection.data_type_check_constraints\n data = field.db_type_parameters(self.connection)\n data[\"column\"] = \"__column_name__\"\n try:\n return check_constraints[field.get_internal_type()] % data\n except KeyError:\n return None", "smellKey": "S1172", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def is_asset_ready(self, asset): # pragma: no cover\n return True", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n yield {\"I\": \"write\", \"bad\": \"normalizers\"}", "smellKey": "S1172", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def db_for_read(self, model, **hints):\n return self._db_for_model(model)", "smellKey": "S1172", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def plugin(version: str) -> type[DynPlugin]:\n return DynPlugin", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def prepare_auth(self, auth, url=\"\"):\n \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n # If no Auth is explicitly provided, extract it from the URL first.\n if auth is None:\n url_auth = get_auth_from_url(self.url)\n auth = url_auth if any(url_auth) else None\n\n if auth:\n if isinstance(auth, tuple) and len(auth) == 2:\n # special-case basic HTTP auth\n auth = HTTPBasicAuth(*auth)\n\n # Allow auth to make its changes.\n r = auth(self)\n\n # Update self to reflect the auth changes.\n self.__dict__.update(r.__dict__)\n\n # Recompute Content-Length\n self.prepare_content_length(self.body)", "smellKey": "S1172", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def create(self, *args, **kwargs):\n phone_number = kwargs[\"phone_number\"]\n return MockTwilioClient.MockPhoneNumber(phone_number)", "smellKey": "S1172", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def pop(self, key, default=None):\n is_immutable(self)", "smellKey": "S1172", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n \"\"\"Adjust the return type of a function call.\n\n This method is called after type checking a call. Plugin may adjust the return\n type inferred by mypy, and/or emit some error messages. Note, this hook is also\n called for class instantiation calls, so that in this example:\n\n from lib import Class, do_stuff\n\n do_stuff(42)\n Class()\n\n This method will be called with 'lib.do_stuff' and then with 'lib.Class'.\n \"\"\"\n return None", "smellKey": "S1172", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def prepare_body(self, data, files, json=None):\n \"\"\"Prepares the given HTTP body data.\"\"\"\n\n # Check if file, fo, generator, iterator.\n # If not, run through normal process.\n\n # Nottin' on you.\n body = None\n content_type = None\n\n if not data and json is not None:\n # urllib3 requires a bytes-like body. Python 2's json.dumps\n # provides this natively, but Python 3 gives a Unicode string.\n content_type = \"application/json\"\n\n try:\n body = complexjson.dumps(json, allow_nan=False)\n except ValueError as ve:\n raise InvalidJSONError(ve, request=self)\n\n if not isinstance(body, bytes):\n body = body.encode(\"utf-8\")\n\n is_stream = all(\n [\n hasattr(data, \"__iter__\"),\n not isinstance(data, (basestring, list, tuple, Mapping)),\n ]\n )\n\n if is_stream:\n try:\n length = super_len(data)\n except (TypeError, AttributeError, UnsupportedOperation):\n length = None\n\n body = data\n\n if getattr(body, \"tell\", None) is not None:\n # Record the current file position before reading.\n # This will allow us to rewind a file in the event\n # of a redirect.\n try:\n self._body_position = body.tell()\n except OSError:\n # This differentiates from None, allowing us to catch\n # a failed `tell()` later when trying to rewind the body\n self._body_position = object()\n\n if files:\n raise NotImplementedError(\n \"Streamed bodies and files are mutually exclusive.\"\n )\n\n if length:\n self.headers[\"Content-Length\"] = builtin_str(length)\n else:\n self.headers[\"Transfer-Encoding\"] = \"chunked\"\n else:\n # Multi-part file uploads.\n if files:\n (body, content_type) = self._encode_files(files, data)\n else:\n if data:\n body = self._encode_params(data)\n if isinstance(data, basestring) or hasattr(data, \"read\"):\n content_type = None\n else:\n content_type = \"application/x-www-form-urlencoded\"\n\n self.prepare_content_length(body)\n\n # Add content-type if it wasn't explicitly provided.\n if content_type and (\"content-type\" not in self.headers):\n self.headers[\"Content-Type\"] = content_type\n\n self.body = body", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def loadSkin(filename, scope=SCOPE_SKINS, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID):\n\tglobal windowStyles, resolutions\n\tfilename = resolveFilename(scope, filename)\n\tprint(f\"[Skin] Loading skin file '{filename}'.\")\n\tdomSkin = fileReadXML(filename, source=MODULE_NAME)\n\tif domSkin is not None:\n\t\t# For loadSingleSkinData colors, bordersets etc. are applied one after\n\t\t# the other in order of ascending priority.\n\t\tloadSingleSkinData(desktop, screenID, domSkin, filename, scope=scope)\n\t\tresolution = resolutions.get(screenID, (0, 0, 0))\n\t\tprint(f\"[Skin] Skin resolution is {resolution[0]}x{resolution[1]} and color depth is {resolution[2]} bits.\")\n\t\tfor element in domSkin:\n\t\t\tif element.tag == \"screen\": # Process all screen elements.\n\t\t\t\tname = element.attrib.get(\"name\")\n\t\t\t\tif name: # Without a name, it's useless!\n\t\t\t\t\tscrnID = element.attrib.get(\"id\")\n\t\t\t\t\tif scrnID is None or scrnID == screenID: # If there is a screen ID is it for this display.\n\t\t\t\t\t\tres = element.attrib.get(\"resolution\", f\"{resolution[0]},{resolution[1]}\")\n\t\t\t\t\t\tif res != \"0,0\":\n\t\t\t\t\t\t\telement.attrib[\"resolution\"] = res\n\t\t\t\t\t\tif config.crash.debugScreens.value:\n\t\t\t\t\t\t\tres = [parseInteger(x.strip()) for x in res.split(\",\")]\n\t\t\t\t\t\t\tprint(f\"[Skin] Loading screen '{name}'{f\", resolution {res[0]}x{res[1]},\" if len(res) == 2 and res[0] and res[1] else \"\"} from '{filename}'. (scope={scope})\")\n\t\t\t\t\t\tdomScreens[name] = (element, f\"{dirname(filename)}/\")\n\t\t\telif element.tag == \"windowstyle\": # Process the windowstyle element.\n\t\t\t\tscrnID = element.attrib.get(\"id\")\n\t\t\t\tif scrnID is not None: # Without an scrnID, it is useless!\n\t\t\t\t\tscrnID = parseInteger(scrnID)\n\t\t\t\t\tdomStyle = ElementTree(Element(\"skin\"))\n\t\t\t\t\tdomStyle.getroot().append(element)\n\t\t\t\t\twindowStyles[scrnID] = (desktop, screenID, domStyle.getroot(), filename, scope)\n\t\t\t\t\tif config.crash.debugScreens.value:\n\t\t\t\t\t\tprint(f\"[Skin] This skin has a windowstyle for screen ID='{scrnID}'.\")\n\t\t\t# Element is not a screen or windowstyle element so no need for it any longer.\n\t\tprint(f\"[Skin] Loading skin file '{filename}' complete.\")\n\t\tif runCallbacks:\n\t\t\tfor method in callbacks:\n\t\t\t\tif method:\n\t\t\t\t\tmethod()\n\t\treturn True\n\treturn False", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def generate_proof_request_web_request(\n self, aip, cred_type, revocation, exchange_tracing, connectionless=False\n ):\n age = 18\n d = datetime.date.today()\n birth_date = datetime.date(d.year - age, d.month, d.day)\n birth_date_format = \"%Y%m%d\"\n if aip == 10:\n req_attrs = [\n {\n \"name\": \"name\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n },\n {\n \"name\": \"date\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n },\n ]\n if revocation:\n req_attrs.append(\n {\n \"name\": \"degree\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n \"non_revoked\": {\"to\": int(time.time() - 1)},\n },\n )\n else:\n req_attrs.append(\n {\n \"name\": \"degree\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n }\n )\n if SELF_ATTESTED:\n # test self-attested claims\n req_attrs.append(\n {\"name\": \"self_attested_thing\"},\n )\n req_preds = [\n # test zero-knowledge proofs\n {\n \"name\": \"birthdate_dateint\",\n \"p_type\": \"<=\",\n \"p_value\": int(birth_date.strftime(birth_date_format)),\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n }\n ]\n indy_proof_request = {\n \"name\": \"Proof of Education\",\n \"version\": \"1.0\",\n \"requested_attributes\": {\n f\"0_{req_attr['name']}_uuid\": req_attr for req_attr in req_attrs\n },\n \"requested_predicates\": {\n f\"0_{req_pred['name']}_GE_uuid\": req_pred for req_pred in req_preds\n },\n }\n\n if revocation:\n indy_proof_request[\"non_revoked\"] = {\"to\": int(time.time())}\n\n proof_request_web_request = {\n \"proof_request\": indy_proof_request,\n \"trace\": exchange_tracing,\n }\n if not connectionless:\n proof_request_web_request[\"connection_id\"] = self.connection_id\n return proof_request_web_request\n\n elif aip == 20:\n if cred_type == CRED_FORMAT_INDY:\n req_attrs = [\n {\n \"name\": \"name\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n },\n {\n \"name\": \"date\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n },\n ]\n if revocation:\n req_attrs.append(\n {\n \"name\": \"degree\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n \"non_revoked\": {\"to\": int(time.time() - 1)},\n },\n )\n else:\n req_attrs.append(\n {\n \"name\": \"degree\",\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n }\n )\n if SELF_ATTESTED:\n # test self-attested claims\n req_attrs.append(\n {\"name\": \"self_attested_thing\"},\n )\n req_preds = [\n # test zero-knowledge proofs\n {\n \"name\": \"birthdate_dateint\",\n \"p_type\": \"<=\",\n \"p_value\": int(birth_date.strftime(birth_date_format)),\n \"restrictions\": [{\"schema_name\": \"degree schema\"}],\n }\n ]\n indy_proof_request = {\n \"name\": \"Proof of Education\",\n \"version\": \"1.0\",\n \"requested_attributes\": {\n f\"0_{req_attr['name']}_uuid\": req_attr for req_attr in req_attrs\n },\n \"requested_predicates\": {\n f\"0_{req_pred['name']}_GE_uuid\": req_pred\n for req_pred in req_preds\n },\n }\n\n if revocation:\n indy_proof_request[\"non_revoked\"] = {\"to\": int(time.time())}\n\n proof_request_web_request = {\n \"presentation_request\": {\"indy\": indy_proof_request},\n \"trace\": exchange_tracing,\n }\n if not connectionless:\n proof_request_web_request[\"connection_id\"] = self.connection_id\n return proof_request_web_request\n\n elif cred_type == CRED_FORMAT_VC_DI:\n proof_request_web_request = {\n \"comment\": \"Test proof request for VC-DI format\",\n \"presentation_request\": {\n \"dif\": {\n \"options\": {\n \"challenge\": \"3fa85f64-5717-4562-b3fc-2c963f66afa7\",\n \"domain\": \"4jt78h47fh47\",\n },\n \"presentation_definition\": {\n \"id\": \"5591656f-5b5d-40f8-ab5c-9041c8e3a6a0\",\n \"name\": \"Age Verification\",\n \"purpose\": \"We need to verify your age before entering a bar\",\n \"input_descriptors\": [\n {\n \"id\": \"age-verification\",\n \"name\": \"A specific type of VC + Issuer\",\n \"purpose\": \"We want a VC of this type generated by this issuer\",\n \"schema\": [\n {\n \"uri\": \"https://www.w3.org/2018/credentials#VerifiableCredential\"\n }\n ],\n \"constraints\": {\n \"statuses\": {\n \"active\": {\"directive\": \"disallowed\"}\n },\n \"limit_disclosure\": \"required\",\n \"fields\": [\n {\n \"path\": [\"$.issuer\"],\n \"filter\": {\n \"type\": \"string\",\n \"const\": self.did,\n },\n },\n {\"path\": [\"$.credentialSubject.name\"]},\n {\"path\": [\"$.credentialSubject.degree\"]},\n {\n \"path\": [\n \"$.credentialSubject.birthdate_dateint\"\n ],\n \"predicate\": \"preferred\",\n \"filter\": {\n \"type\": \"number\",\n \"maximum\": int(\n birth_date.strftime(\n birth_date_format\n )\n ),\n },\n },\n ],\n },\n }\n ],\n \"format\": {\n \"di_vc\": {\n \"proof_type\": [\"DataIntegrityProof\"],\n \"cryptosuite\": [\n \"anoncreds-2023\",\n \"eddsa-rdfc-2022\",\n ],\n }\n },\n },\n },\n },\n }\n\n if revocation:\n proof_request_web_request[\"presentation_request\"][\"dif\"][\n \"presentation_definition\"\n ][\"input_descriptors\"][0][\"constraints\"][\"statuses\"][\"active\"][\n \"directive\"\n ] = \"required\"\n if not connectionless:\n proof_request_web_request[\"connection_id\"] = self.connection_id\n return proof_request_web_request\n\n elif cred_type == CRED_FORMAT_JSON_LD:\n proof_request_web_request = {\n \"comment\": \"test proof request for json-ld\",\n \"presentation_request\": {\n \"dif\": {\n \"options\": {\n \"challenge\": \"3fa85f64-5717-4562-b3fc-2c963f66afa7\",\n \"domain\": \"4jt78h47fh47\",\n },\n \"presentation_definition\": {\n \"id\": \"32f54163-7166-48f1-93d8-ff217bdb0654\",\n \"format\": {\"ldp_vp\": {\"proof_type\": [SIG_TYPE_BLS]}},\n \"input_descriptors\": [\n {\n \"id\": \"citizenship_input_1\",\n \"name\": \"EU Driver's License\",\n \"schema\": [\n {\n \"uri\": \"https://www.w3.org/2018/credentials#VerifiableCredential\"\n },\n {\n \"uri\": \"https://w3id.org/citizenship#PermanentResident\"\n },\n ],\n \"constraints\": {\n \"limit_disclosure\": \"required\",\n \"is_holder\": [\n {\n \"directive\": \"required\",\n \"field_id\": [\n \"1f44d55f-f161-4938-a659-f8026467f126\"\n ],\n }\n ],\n \"fields\": [\n {\n \"id\": \"1f44d55f-f161-4938-a659-f8026467f126\",\n \"path\": [\n \"$.credentialSubject.familyName\"\n ],\n \"purpose\": \"The claim must be from one of the specified person\",\n \"filter\": {\"const\": \"SMITH\"},\n },\n {\n \"path\": [\n \"$.credentialSubject.givenName\"\n ],\n \"purpose\": \"The claim must be from one of the specified person\",\n },\n ],\n },\n }\n ],\n },\n }\n },\n }\n if not connectionless:\n proof_request_web_request[\"connection_id\"] = self.connection_id\n return proof_request_web_request\n\n else:\n raise Exception(f\"Error invalid credential type: {self.cred_type}\")\n\n else:\n raise Exception(f\"Error invalid AIP level: {self.aip}\")", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def timesince(d, now=None, reversed=False, time_strings=None, depth=2):\n \"\"\"\n Take two datetime objects and return the time between d and now as a nicely\n formatted string, e.g. \"10 minutes\". If d occurs after now, return\n \"0 minutes\".\n\n Units used are years, months, weeks, days, hours, and minutes.\n Seconds and microseconds are ignored.\n\n The algorithm takes into account the varying duration of years and months.\n There is exactly \"1 year, 1 month\" between 2013/02/10 and 2014/03/10,\n but also between 2007/08/10 and 2008/09/10 despite the delta being 393 days\n in the former case and 397 in the latter.\n\n Up to `depth` adjacent units will be displayed. For example,\n \"2 weeks, 3 days\" and \"1 year, 3 months\" are possible outputs, but\n \"2 weeks, 3 hours\" and \"1 year, 5 days\" are not.\n\n `time_strings` is an optional dict of strings to replace the default\n TIME_STRINGS dict.\n\n `depth` is an optional integer to control the number of adjacent time\n units returned.\n\n Originally adapted from\n https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since\n Modified to improve results for years and months.\n \"\"\"\n if time_strings is None:\n time_strings = TIME_STRINGS\n if depth <= 0:\n raise ValueError(\"depth must be greater than 0.\")\n # Convert datetime.date to datetime.datetime for comparison.\n if not isinstance(d, datetime.datetime):\n d = datetime.datetime(d.year, d.month, d.day)\n if now and not isinstance(now, datetime.datetime):\n now = datetime.datetime(now.year, now.month, now.day)\n\n # Compared datetimes must be in the same time zone.\n if not now:\n now = datetime.datetime.now(d.tzinfo if is_aware(d) else None)\n elif is_aware(now) and is_aware(d):\n now = now.astimezone(d.tzinfo)\n\n if reversed:\n d, now = now, d\n delta = now - d\n\n # Ignore microseconds.\n since = delta.days * 24 * 60 * 60 + delta.seconds\n if since <= 0:\n # d is in the future compared to now, stop processing.\n return avoid_wrapping(time_strings[\"minute\"] % {\"num\": 0})\n\n # Get years and months.\n total_months = (now.year - d.year) * 12 + (now.month - d.month)\n if d.day > now.day or (d.day == now.day and d.time() > now.time()):\n total_months -= 1\n years, months = divmod(total_months, 12)\n\n # Calculate the remaining time.\n # Create a \"pivot\" datetime shifted from d by years and months, then use\n # that to determine the other parts.\n if years or months:\n pivot_year = d.year + years\n pivot_month = d.month + months\n if pivot_month > 12:\n pivot_month -= 12\n pivot_year += 1\n pivot = datetime.datetime(\n pivot_year,\n pivot_month,\n min(MONTHS_DAYS[pivot_month - 1], d.day),\n d.hour,\n d.minute,\n d.second,\n tzinfo=d.tzinfo,\n )\n else:\n pivot = d\n remaining_time = (now - pivot).total_seconds()\n partials = [years, months]\n for chunk in TIME_CHUNKS:\n count = int(remaining_time // chunk)\n partials.append(count)\n remaining_time -= chunk * count\n\n # Find the first non-zero part (if any) and then build the result, until\n # depth.\n i = 0\n for i, value in enumerate(partials):\n if value != 0:\n break\n else:\n return avoid_wrapping(time_strings[\"minute\"] % {\"num\": 0})\n\n result = []\n current_depth = 0\n while i < len(TIME_STRINGS_KEYS) and current_depth < depth:\n value = partials[i]\n if value == 0:\n break\n name = TIME_STRINGS_KEYS[i]\n result.append(avoid_wrapping(time_strings[name] % {\"num\": value}))\n current_depth += 1\n i += 1\n\n return gettext(\", \").join(result)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _finish_pipeline(self, data):\n if \"expect_exists\" in data:\n self.integration = Integration.objects.get(\n provider=self.provider.integration_key, external_id=data[\"external_id\"]\n )\n else:\n self.integration = ensure_integration(self.provider.integration_key, data)\n\n # Does this integration provide a user identity for the user setting up\n # the integration?\n identity = data.get(\"user_identity\")\n identity_model = None\n if identity:\n # Some identity providers may not be directly associated to the\n # external integration. Integrations may specify the external_id to\n # be used for the idp.\n idp_external_id = data.get(\"idp_external_id\", data[\"external_id\"])\n idp_config = data.get(\"idp_config\", {})\n\n # Create identity provider for this integration if necessary\n idp, created = IdentityProvider.objects.get_or_create(\n external_id=idp_external_id, type=identity[\"type\"], defaults={\"config\": idp_config}\n )\n if not created:\n idp.update(config=idp_config)\n\n identity_data = {\n \"status\": IdentityStatus.VALID,\n \"scopes\": identity[\"scopes\"],\n \"data\": identity[\"data\"],\n \"date_verified\": timezone.now(),\n }\n\n try:\n identity_model = Identity.objects.link_identity(\n user=self.request.user,\n idp=idp,\n external_id=identity[\"external_id\"],\n should_reattach=False,\n defaults=identity_data,\n )\n except IntegrityError:\n # If the external_id is already used for a different user then throw an error\n # otherwise we have the same user with a new external id\n # and we update the identity with the new external_id and identity data\n try:\n matched_identity = Identity.objects.get(\n idp=idp, external_id=identity[\"external_id\"]\n )\n except Identity.DoesNotExist:\n # The user is linked to a different external_id. It's ok to relink\n # here because they'll still be able to log in with the new external_id.\n identity_model = Identity.objects.update_external_id_and_defaults(\n idp, identity[\"external_id\"], self.request.user, identity_data\n )\n else:\n self.get_logger().info(\n \"finish_pipeline.identity_linked_different_user\",\n extra={\n \"idp_id\": idp.id,\n \"external_id\": identity[\"external_id\"],\n \"object_id\": matched_identity.id,\n \"user_id\": self.request.user.id,\n \"type\": identity[\"type\"],\n },\n )\n # if we don't need a default identity, we don't have to throw an error\n if self.provider.needs_default_identity:\n # The external_id is linked to a different user.\n proper_name = idp.get_provider().name\n return self._dialog_response(\n {\n \"error\": _(\n \"The provided %(proper_name)s account is linked to a different Sentry user. \"\n \"To continue linking the current Sentry user, please use a different %(proper_name)s account.\"\n )\n % ({\"proper_name\": proper_name})\n },\n False,\n )\n\n default_auth_id = None\n if self.provider.needs_default_identity:\n if not (identity and identity_model):\n raise NotImplementedError(\"Integration requires an identity\")\n default_auth_id = identity_model.id\n if self.provider.is_region_restricted and is_violating_region_restriction(\n organization_id=self.organization.id, integration_id=self.integration.id\n ):\n return self._dialog_response(\n {\n \"error\": _(\n \"This integration has already been installed on another Sentry organization \"\n \"which resides in a different region. Installation could not be completed.\"\n )\n },\n False,\n )\n\n org_integration = self.integration.add_organization(\n self.organization, self.request.user, default_auth_id=default_auth_id\n )\n\n extra = data.get(\"post_install_data\", {})\n # If a particular provider has a redirect for a successful install, use that instead of the generic success\n redirect_url_format = extra.get(\"redirect_url_format\", None)\n if redirect_url_format is not None:\n return self._get_redirect_response(redirect_url_format=redirect_url_format)\n return self._dialog_success(org_integration)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(\n self,\n local: ContextVar[T] | Local | LocalStack[T] | t.Callable[[], T],\n name: str | None = None,\n *,\n unbound_message: str | None = None,\n ) -> None:\n if name is None:\n get_name = _identity\n else:\n get_name = attrgetter(name) # type: ignore[assignment]\n\n if unbound_message is None:\n unbound_message = \"object is not bound\"\n\n if isinstance(local, Local):\n if name is None:\n raise TypeError(\"'name' is required when proxying a 'Local' object.\")\n\n def _get_current_object() -> T:\n try:\n return get_name(local) # type: ignore[return-value]\n except AttributeError:\n raise RuntimeError(unbound_message) from None\n\n elif isinstance(local, LocalStack):\n\n def _get_current_object() -> T:\n obj = local.top\n\n if obj is None:\n raise RuntimeError(unbound_message)\n\n return get_name(obj)\n\n elif isinstance(local, ContextVar):\n\n def _get_current_object() -> T:\n try:\n obj = local.get()\n except LookupError:\n raise RuntimeError(unbound_message) from None\n\n return get_name(obj)\n\n elif callable(local):\n\n def _get_current_object() -> T:\n return get_name(local())\n\n else:\n raise TypeError(f\"Don't know how to proxy '{type(local)}'.\")\n\n object.__setattr__(self, \"_LocalProxy__wrapped\", local)\n object.__setattr__(self, \"_get_current_object\", _get_current_object)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def run_tidy(task_queue, lock, timeout, exit_status, running_processes):\n watchdog = None\n while True:\n command = task_queue.get()\n with lock:\n should_run = exit_status[\"status\"] == 0\n if not should_run:\n task_queue.task_done()\n continue\n\n proc = None\n try:\n proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n with lock:\n running_processes.add(proc)\n\n if timeout is not None:\n watchdog = threading.Timer(timeout, proc.kill)\n watchdog.start()\n\n stdout, stderr = proc.communicate()\n return_code = proc.returncode\n\n with lock:\n sys.stdout.write(stdout.decode(\"utf-8\") + \"\\n\")\n sys.stdout.flush()\n if stderr:\n sys.stderr.write(stderr.decode(\"utf-8\") + \"\\n\")\n sys.stderr.flush()\n if return_code != 0:\n exit_status[\"status\"] = 1\n for p in running_processes:\n if p != proc:\n p.terminate()\n except Exception as e:\n with lock:\n sys.stderr.write(\"Failed: \" + str(e) + \": \".join(command) + \"\\n\")\n exit_status[\"status\"] = 1\n finally:\n with lock:\n if not (timeout is None or watchdog is None):\n if not watchdog.is_alive():\n sys.stderr.write(\"Terminated by timeout: \" + \" \".join(command) + \"\\n\")\n watchdog.cancel()\n if proc is not None:\n running_processes.remove(proc)\n task_queue.task_done()", "smellKey": "S3776", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def recursive_render(self, node, shader, mode=BASE, with_normals=True):\n \"\"\" Main recursive rendering method.\n \"\"\"\n\n normals = with_normals\n\n if mode == COLORS:\n normals = False\n\n\n if not hasattr(node, \"selected\"):\n node.selected = False\n\n m = get_world_transform(self.scene, node)\n\n # HELPERS mode\n ###\n if mode == HELPERS:\n # if node.type == ENTITY:\n self.render_axis(m,\n label=node.name if node != self.scene.rootnode else None,\n selected=node.selected if hasattr(node, \"selected\") else False)\n\n if node.type == CAMERA:\n self.render_camera(node, m)\n\n for child in node.children:\n self.recursive_render(child, shader, mode)\n\n return\n\n # Mesh rendering modes\n ###\n if node.type == MESH:\n\n for mesh in node.meshes:\n\n stride = 24 # 6 * 4 bytes\n\n if node.selected and mode == SILHOUETTE:\n glUniform4f(shader.u_materialDiffuse, 1.0, 0.0, 0.0, 1.0)\n glUniformMatrix4fv(shader.u_modelViewMatrix, 1, GL_TRUE,\n numpy.dot(self.view_matrix, m))\n\n else:\n if mode == COLORS:\n colorid = self.node2colorid[node.name]\n r, g, b = self.get_rgb_from_colorid(colorid)\n glUniform4f(shader.u_materialDiffuse, r / 255.0, g / 255.0, b / 255.0, 1.0)\n elif mode == SILHOUETTE:\n glUniform4f(shader.u_materialDiffuse, .0, .0, .0, 1.0)\n else:\n if node.selected:\n diffuse = (1.0, 0.0, 0.0, 1.0) # selected nodes in red\n else:\n diffuse = mesh.material.properties[\"diffuse\"]\n if len(diffuse) == 3: # RGB instead of expected RGBA\n diffuse.append(1.0)\n glUniform4f(shader.u_materialDiffuse, *diffuse)\n # if ambient:\n # glUniform4f( shader.Material_ambient, *mat[\"ambient\"] )\n\n if mode == BASE: # not in COLORS or SILHOUETTE\n normal_matrix = linalg.inv(numpy.dot(self.view_matrix, m)[0:3, 0:3]).transpose()\n glUniformMatrix3fv(shader.u_normalMatrix, 1, GL_TRUE, normal_matrix)\n\n glUniformMatrix4fv(shader.u_modelMatrix, 1, GL_TRUE, m)\n\n vbo = mesh.gl[\"vbo\"]\n vbo.bind()\n\n glEnableVertexAttribArray(shader.a_vertex)\n if normals:\n glEnableVertexAttribArray(shader.a_normal)\n\n glVertexAttribPointer(\n shader.a_vertex,\n 3, GL_FLOAT, False, stride, vbo\n )\n\n if normals:\n glVertexAttribPointer(\n shader.a_normal,\n 3, GL_FLOAT, False, stride, vbo + 12\n )\n\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl[\"faces\"])\n glDrawElements(GL_TRIANGLES, mesh.gl[\"nbfaces\"] * 3, GL_UNSIGNED_INT, None)\n\n vbo.unbind()\n glDisableVertexAttribArray(shader.a_vertex)\n\n if normals:\n glDisableVertexAttribArray(shader.a_normal)\n\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)\n\n for child in node.children:\n self.recursive_render(child, shader, mode)", "smellKey": "S3776", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "def layoutFinished(self):\n\t\tdef getInitPath(path):\n\t\t\tdirectory = None # None means the device list.\n\t\t\tselect = None\n\t\t\tif not path.startswith(\"/\"): # This should be a selection on device list.\n\t\t\t\tselect = f\"/{path}\"\n\t\t\telif path.endswith(\"/\") and isdir(path):\n\t\t\t\tdirectory = normpath(path)\n\t\t\telif isfile(path) or isdir(path):\n\t\t\t\tselect = path if isfile(path) else pathjoin(path, \"\")\n\t\t\t\tdirectory = dirname(path)\n\t\t\telse:\n\t\t\t\tdirectory = dirname(normpath(path)) # Try parent, probably file is removed.\n\t\t\t\tif not isdir(directory):\n\t\t\t\t\tdirectory = dirname(directory) # Try one more parent, for dir is removed.\n\t\t\t\t\tif not isdir(directory):\n\t\t\t\t\t\tdirectory = None\n\t\t\treturn (directory, select)\n\n\t\tself[\"headleft\"].enableAutoNavigation(False) # Override listbox navigation.\n\t\tself[\"headright\"].enableAutoNavigation(False) # Override listbox navigation.\n\t\tself[\"listleft\"].enableAutoNavigation(False) # Override listbox navigation.\n\t\tself[\"listright\"].enableAutoNavigation(False) # Override listbox navigation.\n\t\tif self.leftActive:\n\t\t\tself.keyGoLeftColumn()\n\t\telse:\n\t\t\tself.keyGoRightColumn()\n\t\tself[\"listleft\"].changeDir(*getInitPath(config.plugins.FileCommander.pathLeft.value))\n\t\tself[\"listright\"].changeDir(*getInitPath(config.plugins.FileCommander.pathRight.value))\n\t\tself.updateHeading(self.targetColumn)\n\t\tself.updateSort()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def replace_enclosed_string(\n s: str, start: str, end: str, replacement: str | Callable[[str, int], str] | None = None\n) -> str:\n if start not in s:\n return s\n\n depth = 0\n\n rv = []\n pair_start = None\n for idx, char in enumerate(s):\n if char == start:\n if depth == 0:\n pair_start = idx\n depth += 1\n elif char == end:\n depth -= 1\n if depth == 0:\n if isinstance(replacement, str):\n rv.append(replacement)\n elif replacement is not None:\n assert pair_start is not None\n rv.append(replacement(s[pair_start + 1 : idx], pair_start))\n elif depth == 0:\n rv.append(char)\n\n return \"\".join(rv)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def stripUnchangedMsgstrs(poEntry):\n if prefs['stripUnchangedMsgstrs']:\n percentCleared = 0\n if len(poEntry.msgid_plural) > 0:\n try:\n # this script version will only handle an entry with one singular\n # (msgstr_plural[0]) and one plural msgstr_plural[1] entry\n if (poEntry.msgid == poEntry.msgstr_plural[0]):\n poEntry.msgstr_plural[0] = \"\"\n percentCleared = 50\n if (poEntry.msgid_plural == poEntry.msgstr_plural[1]):\n poEntry.msgstr_plural[1] = \"\"\n percentCleared += 50\n except:\n pass # let's just pretend that didn't happen >_<\n elif poEntry.msgid == poEntry.msgstr:\n poEntry.msgstr = \"\"\n percentCleared = 100\n # remove leftover fuzzy flag\n if (\"fuzzy\" in poEntry.flags) and (percentCleared == 100):\n poEntry.flags = [f for f in poEntry.flags if f != 'fuzzy']\n percentCleared = None", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def filter_by_query_params(self, params):\n \"\"\"\n Create a Facility queryset filtered by a list of request query params.\n\n Arguments:\n self (queryset) -- A queryset on the Facility model\n params (dict) -- Request query parameters whose potential choices are\n enumerated in `api.constants.FacilitiesQueryParams`.\n\n Returns:\n A queryset on the Facility model\n \"\"\"\n\n id = params.get(FacilitiesQueryParams.ID, None)\n\n free_text_query = params.get(FacilitiesQueryParams.Q, None)\n\n name = params.get(FacilitiesQueryParams.NAME, None)\n\n contributors = params.getlist(FacilitiesQueryParams.CONTRIBUTORS)\n\n lists = params.getlist(FacilitiesQueryParams.LISTS)\n\n contributor_types = params \\\n .getlist(FacilitiesQueryParams.CONTRIBUTOR_TYPES)\n\n countries = params.getlist(FacilitiesQueryParams.COUNTRIES)\n\n combine_contributors = params.get(\n FacilitiesQueryParams.COMBINE_CONTRIBUTORS, '')\n\n boundary = params.get(\n FacilitiesQueryParams.BOUNDARY, None\n )\n\n embed = params.get(\n FacilitiesQueryParams.EMBED, None\n )\n\n parent_companies = params.getlist(FacilitiesQueryParams.PARENT_COMPANY)\n\n facility_types = params.getlist(FacilitiesQueryParams.FACILITY_TYPE)\n\n processing_types = params.getlist(\n FacilitiesQueryParams.PROCESSING_TYPE\n )\n\n product_types = params.getlist(FacilitiesQueryParams.PRODUCT_TYPE)\n\n number_of_workers = params.getlist(\n FacilitiesQueryParams.NUMBER_OF_WORKERS\n )\n\n native_language_name = params.get(\n FacilitiesQueryParams.NATIVE_LANGUAGE_NAME, None\n )\n\n sectors = params.getlist(FacilitiesQueryParams.SECTOR)\n\n from .facility_index import FacilityIndex\n facilities_qs = FacilityIndex.objects.all()\n\n if id is None and string_matches_os_id_format(free_text_query):\n id = free_text_query\n free_text_query = None\n\n if id is not None:\n from .facility_alias import FacilityAlias\n\n try:\n id = FacilityAlias.objects.get(pk=id).facility_id\n except FacilityAlias.DoesNotExist:\n pass\n\n facilities_qs = facilities_qs.filter(id=id)\n\n if free_text_query is not None:\n name_filter = Q(name__unaccent__icontains=free_text_query)\n if embed is not None:\n custom_text = (\n format_custom_text(contributors[0], free_text_query)\n if contributors\n else free_text_query)\n custom_text_search_filter = Q(\n custom_text_search__unaccent__contains=custom_text\n )\n\n facilities_qs = facilities_qs \\\n .filter(name_filter |\n Q(id=free_text_query) |\n custom_text_search_filter)\n else:\n facilities_qs = facilities_qs \\\n .filter(name_filter | Q(id=free_text_query))\n\n # `name` is deprecated in favor of `q`. We keep `name` available for\n # backward compatibility.\n if name is not None:\n name_filter = Q(name__unaccent__icontains=name)\n facilities_qs = facilities_qs.filter(name_filter | Q(id=name))\n\n if countries is not None and len(countries):\n facilities_qs = facilities_qs \\\n .filter(country_code__in=countries)\n\n if len(contributor_types):\n facilities_qs = facilities_qs \\\n .filter(contrib_types__overlap=contributor_types)\n\n if len(contributors):\n if combine_contributors.upper() == 'AND':\n facilities_qs = facilities_qs.filter(\n contributors_id__contains=contributors\n )\n else:\n facilities_qs = facilities_qs.filter(\n contributors_id__overlap=contributors\n )\n\n if len(lists):\n facilities_qs = facilities_qs.filter(lists__overlap=lists)\n\n if boundary is not None:\n facilities_qs = facilities_qs.filter(\n location__within=GEOSGeometry(boundary)\n )\n\n if len(parent_companies):\n parent_company_id = []\n parent_company_name = []\n for parent_company in parent_companies:\n if parent_company.isnumeric():\n parent_company_id.append(parent_company)\n else:\n parent_company_name.append(parent_company)\n if len(parent_company_id) or len(parent_company_name):\n facilities_qs = facilities_qs.filter(\n Q(parent_company_id__overlap=parent_company_id) |\n Q(parent_company_name__overlap=parent_company_name)\n )\n\n if len(facility_types):\n standard_facility_types = []\n for facility_type in facility_types:\n standard_type = get_facility_and_processing_type(\n facility_type, ['Apparel']\n )\n if standard_type[0] is not None:\n standard_facility_types.append(standard_type[2])\n facilities_qs = facilities_qs.filter(\n facility_type__overlap=standard_facility_types\n )\n\n if len(processing_types):\n standard_processing_types = []\n for processing_type in processing_types:\n standard_type = get_facility_and_processing_type(\n processing_type, ['Apparel']\n )\n if standard_type[0] is not None:\n standard_processing_types.append(standard_type[3])\n facilities_qs = facilities_qs.filter(\n processing_type__overlap=standard_processing_types\n )\n\n if len(product_types):\n clean_product_types = []\n for product_type in product_types:\n clean_product_types.append(clean(product_type))\n facilities_qs = facilities_qs.filter(\n product_type__overlap=clean_product_types\n )\n\n if len(number_of_workers):\n facilities_qs = facilities_qs.filter(\n number_of_workers__overlap=number_of_workers\n )\n\n if native_language_name is not None:\n unidecode_name = unidecode(native_language_name)\n facilities_qs = facilities_qs.filter(\n native_language_name__icontains=unidecode_name\n )\n\n if len(sectors):\n facilities_qs = facilities_qs.filter(\n sector__overlap=sectors\n )\n\n facility_ids = facilities_qs.values_list('id', flat=True)\n\n from .facility import Facility\n facilities_qs = Facility.objects.filter(id__in=facility_ids)\n\n return facilities_qs", "smellKey": "S3776", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def ParseMarkerSettingsFromJson(self, inJsn):\n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriMarkerBlock::ParseMarkerSettingsFromJson entered\\n\", 100)\n\n if 'input' in inJsn:\n self.mInputOperationName = inJsn['input']\n else:\n noticeStr = \\\n 'notice! inJsn has no input key, using default pipeline input\\n'\n self.mInputOperationName = None\n if PhactoriDbg():\n myDebugPrint3(noticeStr)\n\n if \"color\" in inJsn:\n self.mColor = inJsn[\"color\"]\n if len(self.mColor) != 3:\n myDebugPrint3AndException(\n \"'color' item was not three element list\")\n if \"relative size\" in inJsn:\n myDebugPrint3AndException(\n \"PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\\n\"\n \"'relative size' not yet implemented\")\n if \"absolute size\" in inJsn:\n self.mSize = inJsn[\"absolute size\"]\n if \"orientation\" in inJsn:\n self.mOrientation= inJsn[\"orientation\"]\n if \"resolution\" in inJsn:\n self.mResolution = inJsn[\"resolution\"]\n if \"shape\" in inJsn:\n self.mShape = inJsn[\"shape\"]\n if self.mShape == \"sphere\":\n if PhactoriDbg(100):\n myDebugPrint3(\"shape is sphere\\n\", 100)\n elif self.mShape == \"box\":\n if PhactoriDbg(100):\n myDebugPrint3(\"shape is box\\n\", 100)\n elif self.mShape == \"cone\":\n if PhactoriDbg(100):\n myDebugPrint3(\"shape is cone\\n\", 100)\n elif self.mShape == \"arrow\":\n if PhactoriDbg(100):\n myDebugPrint3(\"shape is arrow\\n\", 100)\n else:\n myDebugPrint3AndException(\n \"PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\\n\"\n \"'shape' must be 'sphere' or 'box' or 'cone' or 'arrow'\\n\"\n \"got: \" + str(self.mShape) + \"\\n\")\n\n #get point location for marker settings, e.g. marker at max variable point\n self.mLocationPoint.UserPointInfoParseParametersFromJson(inJsn,\n \"marker at \", \"\")\n\n if self.mLocationPoint.mParsingDetectedAtLeastOneSetting == False:\n myDebugPrint3AndException(\n \"PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\\n\"\n \"must have 'marker at ... point' parameters\")\n\n if PhactoriDbg(100):\n myDebugPrint3(self.SelfToStr())\n myDebugPrint3(\n \"PhactoriMarkerBlock::ParseMarkerSettingsFromJson returning\\n\", 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def hideSlot(self, data, retVal, extraArgs): # Part of emptySlot().\n\t\tif retVal:\n\t\t\tprint(f\"[MultiBoot] hideSlot Error {retVal}: Unable to mount slot '{self.slotCode}' ({self.device})!\")\n\t\t\tself.callback(2)\n\t\telse:\n\t\t\trootDir = self.bootSlots[self.slotCode].get(\"rootsubdir\")\n\t\t\timageDir = pathjoin(self.tempDir, rootDir) if rootDir else self.tempDir\n\t\t\tif self.bootSlots[self.slotCode].get(\"ubi\", False) or fileHas(\"/proc/cmdline\", \"kexec=1\"):\n\t\t\t\ttry:\n\t\t\t\t\tif isfile(pathjoin(imageDir, \"usr/bin/enigma2\")):\n\t\t\t\t\t\tself.console.ePopen([REMOVE, REMOVE, \"-rf\", imageDir])\n\t\t\t\t\tmkdir(imageDir)\n\t\t\t\texcept OSError as err:\n\t\t\t\t\tprint(f\"[MultiBoot] hideSlot Error {err.errno}: Unable to wipe all files in slot '{self.slotCode}' ({self.device})! ({err.strerror})\")\n\t\t\telse:\n\t\t\t\tenigmaFile = \"\" # This is in case the first pathjoin fails.\n\t\t\t\ttry:\n\t\t\t\t\tenigmaFile = pathjoin(imageDir, \"usr/bin/enigma2\")\n\t\t\t\t\tif isfile(enigmaFile):\n\t\t\t\t\t\trename(enigmaFile, f\"{enigmaFile}x.bin\")\n\t\t\t\t\tenigmaFile = pathjoin(imageDir, \"usr/lib/enigma.info\")\n\t\t\t\t\tif isfile(enigmaFile):\n\t\t\t\t\t\trename(enigmaFile, f\"{enigmaFile}x\")\n\t\t\t\t\tenigmaFile = pathjoin(imageDir, \"etc\")\n\t\t\t\t\tif isdir(enigmaFile):\n\t\t\t\t\t\trename(enigmaFile, f\"{enigmaFile}x\")\n\t\t\t\texcept OSError as err:\n\t\t\t\t\tprint(f\"[MultiBoot] hideSlot Error {err.errno}: Unable to hide item '{enigmaFile}' in slot '{self.slotCode}' ({self.device})! ({err.strerror})\")\n\t\t\tself.console.ePopen([UMOUNT, UMOUNT, self.tempDir], self.cleanUpSlot)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def traverse(\n _object: Any,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n) -> Node:\n \"\"\"Traverse object and generate a tree.\n\n Args:\n _object (Any): Object to be traversed.\n max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to None.\n max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n Defaults to None.\n max_depth (int, optional): Maximum depth of data structures, or None for no maximum.\n Defaults to None.\n\n Returns:\n Node: The root of a tree structure which can be used to render a pretty repr.\n \"\"\"\n\n def to_repr(obj: Any) -> str:\n \"\"\"Get repr string for an object, but catch errors.\"\"\"\n if (\n max_string is not None\n and _safe_isinstance(obj, (bytes, str))\n and len(obj) > max_string\n ):\n truncated = len(obj) - max_string\n obj_repr = f\"{obj[:max_string]!r}+{truncated}\"\n else:\n try:\n obj_repr = repr(obj)\n except Exception as error:\n obj_repr = f\"<repr-error {str(error)!r}>\"\n return obj_repr\n\n visited_ids: Set[int] = set()\n push_visited = visited_ids.add\n pop_visited = visited_ids.remove\n\n def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:\n \"\"\"Walk the object depth first.\"\"\"\n\n obj_id = id(obj)\n if obj_id in visited_ids:\n # Recursion detected\n return Node(value_repr=\"...\")\n\n obj_type = type(obj)\n children: List[Node]\n reached_max_depth = max_depth is not None and depth >= max_depth\n\n def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:\n for arg in rich_args:\n if _safe_isinstance(arg, tuple):\n if len(arg) == 3:\n key, child, default = arg\n if default == child:\n continue\n yield key, child\n elif len(arg) == 2:\n key, child = arg\n yield key, child\n elif len(arg) == 1:\n yield arg[0]\n else:\n yield arg\n\n try:\n fake_attributes = hasattr(\n obj, \"awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492\"\n )\n except Exception:\n fake_attributes = False\n\n rich_repr_result: Optional[RichReprResult] = None\n if not fake_attributes:\n try:\n if hasattr(obj, \"__rich_repr__\") and not isclass(obj):\n rich_repr_result = obj.__rich_repr__()\n except Exception:\n pass\n\n if rich_repr_result is not None:\n push_visited(obj_id)\n angular = getattr(obj.__rich_repr__, \"angular\", False)\n args = list(iter_rich_args(rich_repr_result))\n class_name = obj.__class__.__name__\n\n if args:\n children = []\n append = children.append\n\n if reached_max_depth:\n if angular:\n node = Node(value_repr=f\"<{class_name}...>\")\n else:\n node = Node(value_repr=f\"{class_name}(...)\")\n else:\n if angular:\n node = Node(\n open_brace=f\"<{class_name} \",\n close_brace=\">\",\n children=children,\n last=root,\n separator=\" \",\n )\n else:\n node = Node(\n open_brace=f\"{class_name}(\",\n close_brace=\")\",\n children=children,\n last=root,\n )\n for last, arg in loop_last(args):\n if _safe_isinstance(arg, tuple):\n key, child = arg\n child_node = _traverse(child, depth=depth + 1)\n child_node.last = last\n child_node.key_repr = key\n child_node.key_separator = \"=\"\n append(child_node)\n else:\n child_node = _traverse(arg, depth=depth + 1)\n child_node.last = last\n append(child_node)\n else:\n node = Node(\n value_repr=f\"<{class_name}>\" if angular else f\"{class_name}()\",\n children=[],\n last=root,\n )\n pop_visited(obj_id)\n elif _is_attr_object(obj) and not fake_attributes:\n push_visited(obj_id)\n children = []\n append = children.append\n\n attr_fields = _get_attr_fields(obj)\n if attr_fields:\n if reached_max_depth:\n node = Node(value_repr=f\"{obj.__class__.__name__}(...)\")\n else:\n node = Node(\n open_brace=f\"{obj.__class__.__name__}(\",\n close_brace=\")\",\n children=children,\n last=root,\n )\n\n def iter_attrs() -> Iterable[\n Tuple[str, Any, Optional[Callable[[Any], str]]]\n ]:\n \"\"\"Iterate over attr fields and values.\"\"\"\n for attr in attr_fields:\n if attr.repr:\n try:\n value = getattr(obj, attr.name)\n except Exception as error:\n # Can happen, albeit rarely\n yield (attr.name, error, None)\n else:\n yield (\n attr.name,\n value,\n attr.repr if callable(attr.repr) else None,\n )\n\n for last, (name, value, repr_callable) in loop_last(iter_attrs()):\n if repr_callable:\n child_node = Node(value_repr=str(repr_callable(value)))\n else:\n child_node = _traverse(value, depth=depth + 1)\n child_node.last = last\n child_node.key_repr = name\n child_node.key_separator = \"=\"\n append(child_node)\n else:\n node = Node(\n value_repr=f\"{obj.__class__.__name__}()\", children=[], last=root\n )\n pop_visited(obj_id)\n elif (\n is_dataclass(obj)\n and not _safe_isinstance(obj, type)\n and not fake_attributes\n and _is_dataclass_repr(obj)\n ):\n push_visited(obj_id)\n children = []\n append = children.append\n if reached_max_depth:\n node = Node(value_repr=f\"{obj.__class__.__name__}(...)\")\n else:\n node = Node(\n open_brace=f\"{obj.__class__.__name__}(\",\n close_brace=\")\",\n children=children,\n last=root,\n empty=f\"{obj.__class__.__name__}()\",\n )\n\n for last, field in loop_last(\n field for field in fields(obj) if field.repr\n ):\n child_node = _traverse(getattr(obj, field.name), depth=depth + 1)\n child_node.key_repr = field.name\n child_node.last = last\n child_node.key_separator = \"=\"\n append(child_node)\n\n pop_visited(obj_id)\n elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):\n push_visited(obj_id)\n class_name = obj.__class__.__name__\n if reached_max_depth:\n # If we've reached the max depth, we still show the class name, but not its contents\n node = Node(\n value_repr=f\"{class_name}(...)\",\n )\n else:\n children = []\n append = children.append\n node = Node(\n open_brace=f\"{class_name}(\",\n close_brace=\")\",\n children=children,\n empty=f\"{class_name}()\",\n )\n for last, (key, value) in loop_last(obj._asdict().items()):\n child_node = _traverse(value, depth=depth + 1)\n child_node.key_repr = key\n child_node.last = last\n child_node.key_separator = \"=\"\n append(child_node)\n pop_visited(obj_id)\n elif _safe_isinstance(obj, _CONTAINERS):\n for container_type in _CONTAINERS:\n if _safe_isinstance(obj, container_type):\n obj_type = container_type\n break\n\n push_visited(obj_id)\n\n open_brace, close_brace, empty = _BRACES[obj_type](obj)\n\n if reached_max_depth:\n node = Node(value_repr=f\"{open_brace}...{close_brace}\")\n elif obj_type.__repr__ != type(obj).__repr__:\n node = Node(value_repr=to_repr(obj), last=root)\n elif obj:\n children = []\n node = Node(\n open_brace=open_brace,\n close_brace=close_brace,\n children=children,\n last=root,\n )\n append = children.append\n num_items = len(obj)\n last_item_index = num_items - 1\n\n if _safe_isinstance(obj, _MAPPING_CONTAINERS):\n iter_items = iter(obj.items())\n if max_length is not None:\n iter_items = islice(iter_items, max_length)\n for index, (key, child) in enumerate(iter_items):\n child_node = _traverse(child, depth=depth + 1)\n child_node.key_repr = to_repr(key)\n child_node.last = index == last_item_index\n append(child_node)\n else:\n iter_values = iter(obj)\n if max_length is not None:\n iter_values = islice(iter_values, max_length)\n for index, child in enumerate(iter_values):\n child_node = _traverse(child, depth=depth + 1)\n child_node.last = index == last_item_index\n append(child_node)\n if max_length is not None and num_items > max_length:\n append(Node(value_repr=f\"... +{num_items - max_length}\", last=True))\n else:\n node = Node(empty=empty, children=[], last=root)\n\n pop_visited(obj_id)\n else:\n node = Node(value_repr=to_repr(obj), last=root)\n node.is_tuple = _safe_isinstance(obj, tuple)\n node.is_namedtuple = _is_namedtuple(obj)\n return node\n\n node = _traverse(_object, root=True)\n return node", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@lru_cache(maxsize=1)\ndef dependencies() -> dict[NormalizedModelName, ModelRelations]:\n \"\"\"\n Produce a dictionary mapping model type definitions to a `ModelDeps` describing their\n dependencies.\n \"\"\"\n\n from django.apps import apps\n\n from sentry.db.models.base import ModelSiloLimit\n from sentry.db.models.fields.bounded import (\n BoundedBigIntegerField,\n BoundedIntegerField,\n BoundedPositiveIntegerField,\n )\n from sentry.db.models.fields.foreignkey import FlexibleForeignKey\n from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey\n from sentry.db.models.fields.onetoone import OneToOneCascadeDeletes\n\n # Process the list of models, and get the list of dependencies.\n model_dependencies_dict: dict[NormalizedModelName, ModelRelations] = {}\n app_configs = apps.get_app_configs()\n models_from_names = {\n get_model_name(model): model\n for app_config in app_configs\n for model in app_config.get_models()\n }\n\n for app_config in app_configs:\n if app_config.label in EXCLUDED_APPS:\n continue\n\n model_iterator = app_config.get_models()\n\n for model in model_iterator:\n # Ignore some native Django models, since other models don't reference them and we don't\n # really use them for business logic.\n #\n # Also, exclude `getsentry`, since data in those tables should never be backed up or\n # checked.\n if model._meta.app_label in {\"sessions\", \"sites\", \"test\", \"getsentry\"}:\n continue\n\n foreign_keys: dict[str, ForeignField] = dict()\n uniques: set[frozenset[str]] = {\n frozenset(combo) for combo in model._meta.unique_together\n }\n for constraint in model._meta.constraints:\n if isinstance(constraint, UniqueConstraint):\n uniques.add(frozenset(constraint.fields))\n\n # Now add a dependency for any FK relation visible to Django.\n for field in model._meta.get_fields():\n is_nullable = getattr(field, \"null\", False)\n if field.name != \"id\" and getattr(field, \"unique\", False):\n uniques.add(frozenset({field.name}))\n\n rel_model = getattr(field.remote_field, \"model\", None)\n if rel_model is not None and rel_model != model:\n if isinstance(field, FlexibleForeignKey):\n foreign_keys[field.name] = ForeignField(\n model=rel_model,\n kind=ForeignFieldKind.FlexibleForeignKey,\n nullable=is_nullable,\n )\n elif isinstance(field, ForeignKey):\n foreign_keys[field.name] = ForeignField(\n model=rel_model,\n kind=ForeignFieldKind.DefaultForeignKey,\n nullable=is_nullable,\n )\n elif isinstance(field, HybridCloudForeignKey):\n rel_model = models_from_names[NormalizedModelName(field.foreign_model_name)]\n foreign_keys[field.name] = ForeignField(\n model=rel_model,\n kind=ForeignFieldKind.HybridCloudForeignKey,\n nullable=is_nullable,\n )\n\n # Get all simple O2O relations as well.\n one_to_one_fields = [\n field for field in model._meta.get_fields() if isinstance(field, OneToOneField)\n ]\n for field in one_to_one_fields:\n is_nullable = getattr(field, \"null\", False)\n if getattr(field, \"unique\", False):\n uniques.add(frozenset({field.name}))\n\n rel_model = getattr(field.remote_field, \"model\", None)\n if rel_model is not None and rel_model != model:\n if isinstance(field, OneToOneCascadeDeletes):\n foreign_keys[field.name] = ForeignField(\n model=rel_model,\n kind=ForeignFieldKind.OneToOneCascadeDeletes,\n nullable=is_nullable,\n )\n elif isinstance(field, OneToOneField):\n foreign_keys[field.name] = ForeignField(\n model=rel_model,\n kind=ForeignFieldKind.DefaultOneToOneField,\n nullable=is_nullable,\n )\n else:\n raise RuntimeError(\"Unknown one to kind\")\n\n # Use some heuristics to grab numeric-only unlinked dependencies.\n simple_integer_fields = [\n field\n for field in model._meta.get_fields()\n if isinstance(field, BoundedIntegerField)\n or isinstance(field, BoundedBigIntegerField)\n or isinstance(field, BoundedPositiveIntegerField)\n ]\n for field in simple_integer_fields:\n is_nullable = getattr(field, \"null\", False)\n if getattr(field, \"unique\", False):\n uniques.add(frozenset({field.name}))\n\n # \"actor_id\", when used as a simple integer field rather than a `ForeignKey` into an\n # `Actor`, refers to a unified but loosely specified means by which to index into a\n # either a `Team` or `User`, before this pattern was formalized by the official\n # `Actor` model. Because of this, we avoid assuming that it is a dependency into\n # `Actor` and just ignore it.\n if field.name.endswith(\"_id\") and field.name != \"actor_id\":\n candidate = NormalizedModelName(\"sentry.\" + field.name[:-3].replace(\"_\", \"\"))\n if candidate and candidate in models_from_names:\n foreign_keys[field.name] = ForeignField(\n model=models_from_names[candidate],\n kind=ForeignFieldKind.ImplicitForeignKey,\n nullable=is_nullable,\n )\n\n model_dependencies_dict[get_model_name(model)] = ModelRelations(\n dangling=None,\n foreign_keys=foreign_keys,\n model=model,\n # We'll fill this in after the entire dictionary is populated.\n relocation_dependencies=set(),\n relocation_scope=getattr(model, \"__relocation_scope__\", RelocationScope.Excluded),\n silos=list(\n getattr(model._meta, \"silo_limit\", ModelSiloLimit(SiloMode.MONOLITH)).modes\n ),\n table_name=model._meta.db_table,\n # Sort the constituent sets alphabetically, so that we get consistent JSON output.\n uniques=sorted(uniques, key=lambda u: \":\".join(sorted(u))),\n )\n\n # Get a flat list of \"root\" models, then mark all of them as non-dangling.\n relocation_root_models: list[NormalizedModelName] = []\n for root_models in RelocationRootModels:\n relocation_root_models.extend(root_models.value)\n for model_name in relocation_root_models:\n model_dependencies_dict[model_name].dangling = False\n\n # TODO(getsentry/team-ospo#190): In practice, we can treat `AlertRule`'s dependency on\n # `Organization` as non-nullable, so mark it is non-dangling. This is a hack - we should figure\n # out a more rigorous way to deduce this.\n model_dependencies_dict[NormalizedModelName(\"sentry.alertrule\")].dangling = False\n\n # TODO(getsentry/team-ospo#190): The same is basically true for the remaining models in this\n # list: the schema defines all of their foreign keys as nullable, but since these models have no\n # other models referencing them (ie, they are leaves on our dependency graph), we know that at\n # least one of those nullable relations will be present on every model.\n model_dependencies_dict[NormalizedModelName(\"sentry.savedsearch\")].dangling = False\n model_dependencies_dict[NormalizedModelName(\"sentry.servicehook\")].dangling = False\n model_dependencies_dict[NormalizedModelName(\"sentry.snubaqueryeventtype\")].dangling = False\n model_dependencies_dict[NormalizedModelName(\"sentry.rulesnooze\")].dangling = False\n\n # Now that all `ModelRelations` have been added to the `model_dependencies_dict`, we can circle\n # back and figure out which ones are actually dangling. We do this by marking all of the root\n # models non-dangling, then traversing from every other model to a (possible) root model\n # recursively. At this point there should be no circular reference chains, so if we encounter\n # them, fail immediately.\n def resolve_dangling(seen: set[NormalizedModelName], model_name: NormalizedModelName) -> bool:\n model_relations = model_dependencies_dict[model_name]\n model_name = get_model_name(model_relations.model)\n if model_name in seen:\n raise RuntimeError(\n f\"Circular dependency: {model_name} cannot transitively reference itself\"\n )\n if model_relations.relocation_scope == RelocationScope.Excluded:\n model_relations.dangling = False\n return model_relations.dangling\n if model_relations.dangling is not None:\n return model_relations.dangling\n\n # TODO(getsentry/team-ospo#190): Maybe make it so that `Global` models are never \"dangling\",\n # since we want to export 100% of models in `ExportScope.Global` anyway?\n\n seen.add(model_name)\n\n # If we are able to successfully over all of the foreign keys without encountering a\n # dangling reference, we know that this model is dangling as well.\n model_relations.dangling = True\n for ff in model_relations.foreign_keys.values():\n if not ff.nullable:\n foreign_model_name = get_model_name(ff.model)\n if not resolve_dangling(seen, foreign_model_name):\n # We only need one non-dangling reference to mark this model as non-dangling as\n # well.\n model_relations.dangling = False\n break\n\n seen.remove(model_name)\n return model_relations.dangling\n\n for model_name, model_relations in model_dependencies_dict.items():\n resolve_dangling(set(), model_name)\n model_relations.relocation_dependencies = {\n model_dependencies_dict[NormalizedModelName(rd)].model\n for rd in getattr(model_relations.model, \"__relocation_dependencies__\", set())\n }\n\n return model_dependencies_dict", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@track_slo_response(\"workflow\")\n def get(self, request: Request, organization) -> Response:\n \"\"\"\n List an Organization's Issues\n `````````````````````````````\n\n Return a list of issues (groups) bound to an organization. All parameters are\n supplied as query string parameters.\n\n A default query of ``is:unresolved issue.priority:[high,medium]`` is applied.\n To return results with other statuses send a new query value\n (i.e. ``?query=`` for all results).\n\n The ``groupStatsPeriod`` parameter can be used to select the timeline\n stats which should be present. Possible values are: '' (disable),\n '24h', '14d'\n\n The ``statsPeriod`` parameter can be used to select a date window starting\n from now. Ex. ``14d``.\n\n The ``start`` and ``end`` parameters can be used to select an absolute\n date period to fetch issues from.\n\n :qparam string statsPeriod: an optional stat period (can be one of\n ``\"24h\"``, ``\"14d\"``, and ``\"\"``).\n :qparam string groupStatsPeriod: an optional stat period (can be one of\n ``\"24h\"``, ``\"14d\"``, and ``\"\"``).\n :qparam string start: Beginning date. You must also provide ``end``.\n :qparam string end: End date. You must also provide ``start``.\n :qparam bool shortIdLookup: if this is set to true then short IDs are\n looked up by this function as well. This\n can cause the return value of the function\n to return an event issue of a different\n project which is why this is an opt-in.\n Set to `1` to enable.\n :qparam querystring query: an optional Sentry structured search\n query. If not provided an implied\n ``\"is:unresolved issue.priority:[high,medium]\"`` is assumed.)\n :qparam bool savedSearch: if this is set to False, then we are making the request without\n a saved search and will look for the default search from this endpoint.\n :qparam string searchId: if passed in, this is the selected search\n :pparam string organization_id_or_slug: the id or slug of the organization the\n issues belong to.\n :auth: required\n :qparam list expand: an optional list of strings to opt in to additional data. Supports `inbox`\n :qparam list collapse: an optional list of strings to opt out of certain pieces of data. Supports `stats`, `lifetime`, `base`, `unhandled`\n \"\"\"\n stats_period = request.GET.get(\"groupStatsPeriod\")\n try:\n start, end = get_date_range_from_stats_period(request.GET)\n except InvalidParams as e:\n raise ParseError(detail=str(e))\n\n expand = request.GET.getlist(\"expand\", [])\n collapse = request.GET.getlist(\"collapse\", [])\n if stats_period not in (None, \"\", \"24h\", \"14d\", \"auto\"):\n return Response({\"detail\": ERR_INVALID_STATS_PERIOD}, status=400)\n stats_period, stats_period_start, stats_period_end = calculate_stats_period(\n stats_period, start, end\n )\n\n environments = self.get_environments(request, organization)\n\n projects = self.get_projects(request, organization)\n project_ids = [p.id for p in projects]\n\n if not projects:\n return Response([])\n\n is_fetching_replay_data = request.headers.get(\"X-Sentry-Replay-Request\") == \"1\"\n if (\n len(projects) > 1\n and not features.has(\"organizations:global-views\", organization, actor=request.user)\n and not is_fetching_replay_data\n ):\n return Response(\n {\"detail\": \"You do not have the multi project stream feature enabled\"}, status=400\n )\n\n serializer = functools.partial(\n StreamGroupSerializerSnuba,\n environment_ids=[env.id for env in environments],\n stats_period=stats_period,\n stats_period_start=stats_period_start,\n stats_period_end=stats_period_end,\n expand=expand,\n collapse=collapse,\n project_ids=project_ids,\n organization_id=organization.id,\n )\n\n # we ignore date range for both short id and event ids\n query = request.GET.get(\"query\", \"\").strip()\n\n # record analytics for search query\n if request.user:\n analytics.record(\n \"issue_search.endpoint_queried\",\n user_id=request.user.id,\n organization_id=organization.id,\n project_ids=\",\".join(map(str, project_ids)),\n full_query_params=\",\".join(f\"{key}={value}\" for key, value in request.GET.items()),\n query=query,\n )\n\n if query:\n # check to see if we've got an event ID\n event_id = normalize_event_id(query)\n if event_id:\n # For a direct hit lookup we want to use any passed project ids\n # (we've already checked permissions on these) plus any other\n # projects that the user is a member of. This gives us a better\n # chance of returning the correct result, even if the wrong\n # project is selected.\n direct_hit_projects = (\n set(project_ids) | request.access.project_ids_with_team_membership\n )\n groups = list(\n Group.objects.filter_by_event_id(\n direct_hit_projects,\n event_id,\n tenant_ids={\"organization_id\": organization.id},\n )\n )\n if len(groups) == 1:\n serialized_groups = serialize(\n groups, request.user, serializer(), request=request\n )\n if event_id:\n serialized_groups[0][\"matchingEventId\"] = event_id\n response = Response(serialized_groups)\n response[\"X-Sentry-Direct-Hit\"] = \"1\"\n return response\n\n if groups:\n return Response(serialize(groups, request.user, serializer(), request=request))\n\n group = get_by_short_id(organization.id, request.GET.get(\"shortIdLookup\") or \"0\", query)\n if group is not None:\n # check all projects user has access to\n if request.access.has_project_access(group.project):\n response = Response(\n serialize([group], request.user, serializer(), request=request)\n )\n response[\"X-Sentry-Direct-Hit\"] = \"1\"\n return response\n\n # If group ids specified, just ignore any query components\n try:\n group_ids = set(map(int, request.GET.getlist(\"group\")))\n except ValueError:\n return Response({\"detail\": \"Group ids must be integers\"}, status=400)\n\n if group_ids:\n groups = list(Group.objects.filter(id__in=group_ids, project_id__in=project_ids))\n if any(g for g in groups if not request.access.has_project_access(g.project)):\n raise PermissionDenied\n return Response(serialize(groups, request.user, serializer(), request=request))\n\n try:\n cursor_result, query_kwargs = self._search(\n request,\n organization,\n projects,\n environments,\n {\"count_hits\": True, \"date_to\": end, \"date_from\": start},\n )\n except (ValidationError, discover.InvalidSearchQuery) as exc:\n return Response({\"detail\": str(exc)}, status=400)\n\n results = list(cursor_result)\n\n context = serialize(\n results,\n request.user,\n serializer(\n start=start,\n end=end,\n search_filters=(\n query_kwargs[\"search_filters\"] if \"search_filters\" in query_kwargs else None\n ),\n organization_id=organization.id,\n ),\n request=request,\n )\n\n # HACK: remove auto resolved entries\n # TODO: We should try to integrate this into the search backend, since\n # this can cause us to arbitrarily return fewer results than requested.\n status = [\n search_filter\n for search_filter in query_kwargs.get(\"search_filters\", [])\n if search_filter.key.name == \"status\" and search_filter.operator in EQUALITY_OPERATORS\n ]\n if status and (GroupStatus.UNRESOLVED in status[0].value.raw_value):\n status_labels = {QUERY_STATUS_LOOKUP[s] for s in status[0].value.raw_value}\n context = [r for r in context if \"status\" not in r or r[\"status\"] in status_labels]\n\n response = Response(context)\n\n self.add_cursor_headers(request, response, cursor_result)\n\n # TODO(jess): add metrics that are similar to project endpoint here\n return response", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def and_conditional_maps(m1: TypeMap, m2: TypeMap, use_meet: bool = False) -> TypeMap:\n \"\"\"Calculate what information we can learn from the truth of (e1 and e2)\n in terms of the information that we can learn from the truth of e1 and\n the truth of e2.\n \"\"\"\n\n if m1 is None or m2 is None:\n # One of the conditions can never be true.\n return None\n # Both conditions can be true; combine the information. Anything\n # we learn from either conditions' truth is valid. If the same\n # expression's type is refined by both conditions, we somewhat\n # arbitrarily give precedence to m2 unless m1 value is Any.\n # In the future, we could use an intersection type or meet_types().\n result = m2.copy()\n m2_keys = {literal_hash(n2) for n2 in m2}\n for n1 in m1:\n if literal_hash(n1) not in m2_keys or isinstance(get_proper_type(m1[n1]), AnyType):\n result[n1] = m1[n1]\n if use_meet:\n # For now, meet common keys only if specifically requested.\n # This is currently used for tuple types narrowing, where having\n # a precise result is important.\n for n1 in m1:\n for n2 in m2:\n if literal_hash(n1) == literal_hash(n2):\n result[n1] = meet_types(m1[n1], m2[n2])\n return result", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@classmethod\n def _slice_track(cls, track_, start, stop, dimension):\n def filter_track_shapes(shapes):\n shapes = [s for s in shapes if cls._is_shape_inside(s, start, stop)]\n\n # remove leading outside shapes as they are not necessary\n drop_count = 0\n for s in shapes:\n if s['outside']:\n drop_count += 1\n else:\n break\n\n return shapes[drop_count:]\n\n track = deepcopy(track_)\n segment_shapes = filter_track_shapes(deepcopy(track['shapes']))\n\n track[\"elements\"] = [\n cls._slice_track(element, start, stop, dimension)\n for element in track.get('elements', [])\n ]\n\n if len(segment_shapes) < len(track['shapes']):\n interpolated_shapes = TrackManager.get_interpolated_shapes(\n track, start, stop + 1, dimension)\n scoped_shapes = filter_track_shapes(interpolated_shapes)\n\n if scoped_shapes:\n last_key = max(shape['frame'] for shape in track['shapes'])\n if not scoped_shapes[0]['keyframe']:\n segment_shapes.insert(0, scoped_shapes[0])\n if last_key >= stop and scoped_shapes[-1]['points'] != segment_shapes[-1]['points']:\n segment_shapes.append(scoped_shapes[-1])\n elif scoped_shapes[-1]['keyframe'] and \\\n scoped_shapes[-1]['outside']:\n segment_shapes.append(scoped_shapes[-1])\n elif stop + 1 < len(interpolated_shapes) and \\\n interpolated_shapes[stop + 1]['outside']:\n segment_shapes.append(interpolated_shapes[stop + 1])\n\n for shape in segment_shapes:\n shape.pop('keyframe', None)\n\n track['shapes'] = segment_shapes\n if 0 < len(segment_shapes):\n track['frame'] = track['shapes'][0]['frame']\n return track", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def holds_bad_pickle_object(value, memo=None):\n if memo is None:\n memo = {}\n\n value_id = id(value)\n if value_id in memo:\n return\n memo[value_id] = value\n\n if isinstance(value, (tuple, list)):\n for item in value:\n bad_object = holds_bad_pickle_object(item)\n if bad_object is not None:\n return bad_object\n elif isinstance(value, dict):\n for item in value.values():\n bad_object = holds_bad_pickle_object(item)\n if bad_object is not None:\n return bad_object\n\n if isinstance(value, models.Model):\n return (\n value,\n \"django database models are large and likely to be stale when your task is run. \"\n \"Instead pass primary key values to the task and load records from the database within your task.\",\n )\n if type(value).__module__.startswith((\"sentry.\", \"getsentry.\")):\n return value, \"do not pickle custom classes\"\n\n return None", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, contexts=None, actions=None, prio=0, parentScreen=None):\n\t\tself.contexts = contexts or []\n\t\tself.actions = actions or {}\n\t\tself.prio = prio\n\t\tself.actionMapInstance = eActionMap.getInstance()\n\t\tself.bound = False\n\t\tself.execActive = False\n\t\tself.enabled = True\n\t\tself.legacyBound = False\n\t\tself.parentScreen = parentScreen.__class__.__name__ if parentScreen and [x for x in parentScreen.__class__.__mro__ if x.__name__ == \"Screen\"] else \"N/A\"\n\t\tundefinedAction = list(self.actions.keys())\n\t\tleftActionDefined = \"left\" in undefinedAction\n\t\trightActionDefined = \"right\" in undefinedAction\n\t\tleftAction = None\n\t\trightAction = None\n\t\tfor action in undefinedAction[:]:\n\t\t\tfor context in self.contexts:\n\t\t\t\tif context == \"NavigationActions\":\n\t\t\t\t\tif action == \"pageUp\" and not leftActionDefined:\n\t\t\t\t\t\tleftAction = self.actions[action]\n\t\t\t\t\tif action == \"pageDown\" and not rightActionDefined:\n\t\t\t\t\t\trightAction = self.actions[action]\n\t\t\t\tif queryKeyBinding(context, action):\n\t\t\t\t\tundefinedAction.remove(action)\n\t\t\t\t\tbreak\n\t\tif leftAction and rightAction and config.misc.actionLeftRightToPageUpPageDown.value:\n\t\t\tif config.crash.debugActionMaps.value:\n\t\t\t\tprint(\"[ActionMap] DEBUG: Creating legacy navigation action map.\")\n\t\t\t\tprint(leftAction)\n\t\t\t\tprint(rightAction)\n\t\t\tself.legacyActions = {\n\t\t\t\t\"left\": leftAction,\n\t\t\t\t\"right\": rightAction\n\t\t\t}\n\t\telse:\n\t\t\tself.legacyActions = {}\n\t\tif undefinedAction:\n\t\t\tcontext = \"', '\".join(sorted(self.contexts))\n\t\t\tcontextPlural = \"s\" if len(self.contexts) > 1 else \"\"\n\t\t\taction = \"', '\".join(sorted(undefinedAction))\n\t\t\tactionPlural = \"s\" if len(undefinedAction) > 1 else \"\"\n\t\t\tprint(f\"[ActionMap] Map context{contextPlural} '{context}': Undefined action{actionPlural} '{action}'.\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def UpdatePipeAndViewsStateFromUserA(inPipeAndViewsState, inFileName):\n \"given a PhactoriPipeAndViewsState instance which has been previously\\n parsed, paraview items created, etc. (and presumably used to create\\n rendered images at least once), read in the json state from the\\n specified file, and update the inPipeAndViewsState accordingly.\\n Only do the update if the PhactoriUpdateTrigger.txt file has a new\\n value since the last check. Only read the file on processor zero,\\n and use mpi to share the update with all other processors.\"\n if PhactoriDbg():\n myDebugPrint3(\"UpdatePipeAndViewsStateFromUserA entered\\n\")\n if SmartGetLocalProcessId() != 0:\n if PhactoriDbg():\n myDebugPrint3(\"UpdatePipeAndViewsStateFromUserA returning, not process 0\\n\")\n return\n try:\n inFile = open(inFileName, 'rb')\n userUpdateJson = json.load(inFile)\n inFile.close()\n userUpdateJson = convertJsonUnicodeToStrings(userUpdateJson)\n\n if 'representation blocks' in userUpdateJson:\n representationBlocks = userUpdateJson['representation blocks']\n #could add logic to detect no change\n for repName, repJson in representationBlocks.items():\n onePhactoriRep = inPipeAndViewsState.mRepresentationBlocks[repName]\n if PhactoriDbg():\n myDebugPrint3(\"representation name: \" + str(repName) + \\\n \"\\nrepresentation json: \" + str(repJson) + \"\\n\")\n if onePhactoriRep != None:\n ParseOneRepresentationBlockC(onePhactoriRep, repJson,\n inPipeAndViewsState)\n if PhactoriDbg():\n myDebugPrint3(\"new color by variable: \" +\n onePhactoriRep.mColorVariableInfo.SelfToStr() + \"\\n\")\n\n if 'camera blocks' in userUpdateJson:\n cameraBlocks = userUpdateJson['camera blocks']\n for cameraName, cameraJson in cameraBlocks.items():\n onePhactoriCamera = inPipeAndViewsState.mCameraBlocks[cameraName]\n if PhactoriDbg():\n myDebugPrint3(\"camera name: \" + str(cameraName) + \\\n \"\\ncamera json: \" + str(cameraJson) + \"\\n\")\n if onePhactoriCamera != None:\n if PhactoriDbg():\n myDebugPrint3(\"updating camera named: \" + str(cameraName) + \"\\n\")\n ParseOneCameraBlockC(onePhactoriCamera, cameraJson,\n inPipeAndViewsState)\n if PhactoriDbg():\n myDebugPrint3(\"new look direction: \" + \\\n str(onePhactoriCamera.mLookDirection) + \"\\n\")\n\n except:\n if PhactoriDbg():\n myDebugPrint3(\"error trying to get and use json from file\\n\")\n if PhactoriDbg():\n myDebugPrint3(\"UpdatePipeAndViewsStateFromUserA returning\\n\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def platform_tags(linux: str, arch: str) -> Iterator[str]:\n if not _have_compatible_abi(arch):\n return\n # Oldest glibc to be supported regardless of architecture is (2, 17).\n too_old_glibc2 = _GLibCVersion(2, 16)\n if arch in {\"x86_64\", \"i686\"}:\n # On x86/i686 also oldest glibc to be supported is (2, 5).\n too_old_glibc2 = _GLibCVersion(2, 4)\n current_glibc = _GLibCVersion(*_get_glibc_version())\n glibc_max_list = [current_glibc]\n # We can assume compatibility across glibc major versions.\n # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n #\n # Build a list of maximum glibc versions so that we can\n # output the canonical list of all glibc from current_glibc\n # down to too_old_glibc2, including all intermediary versions.\n for glibc_major in range(current_glibc.major - 1, 1, -1):\n glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n for glibc_max in glibc_max_list:\n if glibc_max.major == too_old_glibc2.major:\n min_minor = too_old_glibc2.minor\n else:\n # For other glibc major versions oldest supported is (x, 0).\n min_minor = -1\n for glibc_minor in range(glibc_max.minor, min_minor, -1):\n glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n tag = \"manylinux_{}_{}\".format(*glibc_version)\n if _is_compatible(tag, arch, glibc_version):\n yield linux.replace(\"linux\", tag)\n # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n if glibc_version in _LEGACY_MANYLINUX_MAP:\n legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]\n if _is_compatible(legacy_tag, arch, glibc_version):\n yield linux.replace(\"linux\", legacy_tag)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get(self, request, *args, **kwargs):\n data = {}\n\n query_params = self.request.query_params\n\n caches = OrgResourceStatisticsCache(self.org)\n\n _all = query_params.get('all')\n\n if _all or query_params.get('total_count') or query_params.get('total_count_users'):\n data.update({\n 'total_count_users': caches.users_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_assets'):\n data.update({\n 'total_count_assets': caches.assets_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_users_this_week'):\n data.update({\n 'total_count_users_this_week': caches.new_users_amount_this_week,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_assets_this_week'):\n data.update({\n 'total_count_assets_this_week': caches.new_assets_amount_this_week,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_login_users'):\n data.update({\n 'total_count_login_users': self.user_login_amount\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_today_active_assets'):\n data.update({\n 'total_count_today_active_assets': caches.total_count_today_active_assets,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_online_users'):\n data.update({\n 'total_count_online_users': caches.total_count_online_users,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_online_sessions'):\n data.update({\n 'total_count_online_sessions': caches.total_count_online_sessions,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_today_failed_sessions'):\n data.update({\n 'total_count_today_failed_sessions': caches.total_count_today_failed_sessions,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_user_login_logs'):\n data.update({\n 'total_count_user_login_logs': self.user_login_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_user_login_success_logs'):\n data.update({\n 'total_count_user_login_success_logs': self.user_login_success_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_operate_logs'):\n data.update({\n 'total_count_operate_logs': self.operate_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_change_password_logs'):\n data.update({\n 'total_count_change_password_logs': self.change_password_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_commands'):\n data.update({\n 'total_count_commands': self.commands_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_commands_danger'):\n data.update({\n 'total_count_commands_danger': self.commands_danger_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_history_sessions'):\n data.update({\n 'total_count_history_sessions': self.sessions_amount - self.online_sessions_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_ftp_logs'):\n data.update({\n 'total_count_ftp_logs': self.ftp_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_job_logs'):\n data.update({\n 'total_count_job_logs': self.job_logs_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_job_logs_running'):\n data.update({\n 'total_count_job_logs_running': self.job_logs_running_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_job_logs_failed'):\n data.update({\n 'total_count_job_logs_failed': self.job_logs_failed_amount,\n })\n\n if _all or query_params.get('total_count') or query_params.get('total_count_type_to_assets_amount'):\n data.update({\n 'total_count_type_to_assets_amount': self.get_type_to_assets,\n })\n\n if _all or query_params.get('session_dates_metrics'):\n data.update({\n 'dates_metrics_date': self.get_dates_metrics_date(),\n 'dates_metrics_total_count_session': self.get_dates_metrics_total_count_sessions(),\n })\n\n if _all or query_params.get('dates_metrics'):\n user_data, asset_data = self.get_dates_metrics_total_count_active_users_and_assets()\n login_data = self.get_dates_metrics_total_count_login()\n data.update({\n 'dates_metrics_date': self.get_dates_metrics_date(),\n 'dates_metrics_total_count_login': login_data,\n 'dates_metrics_total_count_active_users': user_data,\n 'dates_metrics_total_count_active_assets': asset_data,\n })\n\n if _all or query_params.get('dates_login_times_top10_assets'):\n data.update({\n 'dates_login_times_top10_assets': self.get_dates_login_times_assets(),\n })\n\n if _all or query_params.get('dates_login_times_top10_users'):\n data.update({\n 'dates_login_times_top10_users': self.get_dates_login_times_users(),\n })\n\n if _all or query_params.get('dates_login_record_top10_sessions'):\n data.update({\n 'dates_login_record_top10_sessions': self.get_dates_login_record_sessions()\n })\n\n return JsonResponse(data, status=200)", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def writeHash(hashFile, topdir, extensions):\n\tdef isMatch(fileName, extensions):\n\t\tbase, ext = os.path.splitext(fileName)\n\t\tif extensions:\n\t\t\tfor extension in extensions:\n\t\t\t\tif ext == extension or ext == \".\" + extension:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\twith open(hashFile, \"w\") as fout:\n\t\tchecksums = {}\n\t\tfor root, dirs, files in os.walk(topdir):\n\t\t\tfor fileName in files:\n\t\t\t\tfull_path = os.path.join(root, fileName)\n\t\t\t\tif isMatch(fileName, extensions):\n\t\t\t\t\tchecksum = getSha256(full_path)\n\t\t\t\t\tif checksum not in checksums:\n\t\t\t\t\t\tchecksums[checksum] = []\n\t\t\t\t\tchecksums[checksum].append(full_path)\n\t\t\t\t\t\n\t\tfor key, valueList in checksums.items():\n\t\t\tfor value in valueList:\n\t\t\t\tfout.write(key + \"\\t\" + value + \"\\n\")\n\t\t\t\tprint (key + \"\\t\" + value)", "smellKey": "S3776", "smellId": null, "repo": "sakura-editor_sakura", "language": "python"} {"function": "def get_default_function_sig(self, func: object, ctx: FunctionContext) -> FunctionSig:\n argspec = None\n if not self.is_c_module:\n # Get the full argument specification of the function\n try:\n argspec = inspect.getfullargspec(func)\n except TypeError:\n # some callables cannot be inspected, e.g. functools.partial\n pass\n if argspec is None:\n if ctx.class_info is not None:\n # method:\n return FunctionSig(\n name=ctx.name,\n args=infer_c_method_args(ctx.name, ctx.class_info.self_var),\n ret_type=infer_method_ret_type(ctx.name),\n )\n else:\n # function:\n return FunctionSig(\n name=ctx.name,\n args=[ArgSig(name=\"*args\"), ArgSig(name=\"**kwargs\")],\n ret_type=None,\n )\n\n # Extract the function arguments, defaults, and varargs\n args = argspec.args\n defaults = argspec.defaults\n varargs = argspec.varargs\n kwargs = argspec.varkw\n annotations = argspec.annotations\n kwonlyargs = argspec.kwonlyargs\n kwonlydefaults = argspec.kwonlydefaults\n\n def get_annotation(key: str) -> str | None:\n if key not in annotations:\n return None\n argtype = annotations[key]\n if argtype is None:\n return \"None\"\n if not isinstance(argtype, str):\n return self.get_type_fullname(argtype)\n return argtype\n\n arglist: list[ArgSig] = []\n\n # Add the arguments to the signature\n def add_args(\n args: list[str], get_default_value: Callable[[int, str], object | None]\n ) -> None:\n for i, arg in enumerate(args):\n # Check if the argument has a default value\n default_value = get_default_value(i, arg)\n if default_value is not None:\n if arg in annotations:\n argtype = annotations[arg]\n else:\n argtype = self.get_type_annotation(default_value)\n if argtype == \"None\":\n # None is not a useful annotation, but we can infer that the arg\n # is optional\n incomplete = self.add_name(\"_typeshed.Incomplete\")\n argtype = f\"{incomplete} | None\"\n\n arglist.append(ArgSig(arg, argtype, default=True))\n else:\n arglist.append(ArgSig(arg, get_annotation(arg), default=False))\n\n def get_pos_default(i: int, _arg: str) -> Any | None:\n if defaults and i >= len(args) - len(defaults):\n return defaults[i - (len(args) - len(defaults))]\n else:\n return None\n\n add_args(args, get_pos_default)\n\n # Add *args if present\n if varargs:\n arglist.append(ArgSig(f\"*{varargs}\", get_annotation(varargs)))\n # if we have keyword only args, then wee need to add \"*\"\n elif kwonlyargs:\n arglist.append(ArgSig(\"*\"))\n\n def get_kw_default(_i: int, arg: str) -> Any | None:\n if kwonlydefaults:\n return kwonlydefaults.get(arg)\n else:\n return None\n\n add_args(kwonlyargs, get_kw_default)\n\n # Add **kwargs if present\n if kwargs:\n arglist.append(ArgSig(f\"**{kwargs}\", get_annotation(kwargs)))\n\n # add types for known special methods\n if ctx.class_info is not None and all(\n arg.type is None and arg.default is False for arg in arglist\n ):\n new_args = infer_method_arg_types(\n ctx.name, ctx.class_info.self_var, [arg.name for arg in arglist if arg.name]\n )\n if new_args is not None:\n arglist = new_args\n\n ret_type = get_annotation(\"return\") or infer_method_ret_type(ctx.name)\n return FunctionSig(ctx.name, arglist, ret_type)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def p2p_handover_client(llc):\n message = nfc.ndef.HandoverRequestMessage(version=\"1.2\")\n message.nonce = random.randint(0, 0xffff)\n\n global include_p2p_req\n if include_p2p_req:\n data = wpas_get_handover_req()\n if (data == None):\n summary(\"Could not get handover request carrier record from wpa_supplicant\")\n return\n print(\"Handover request carrier record from wpa_supplicant: \" + data.encode(\"hex\"))\n datamsg = nfc.ndef.Message(data)\n message.add_carrier(datamsg[0], \"active\", datamsg[1:])\n\n global include_wps_req\n if include_wps_req:\n print(\"Handover request (pre-WPS):\")\n try:\n print(message.pretty())\n except Exception as e:\n print(e)\n\n data = wpas_get_handover_req_wps()\n if data:\n print(\"Add WPS request in addition to P2P\")\n datamsg = nfc.ndef.Message(data)\n message.add_carrier(datamsg[0], \"active\", datamsg[1:])\n\n print(\"Handover request:\")\n try:\n print(message.pretty())\n except Exception as e:\n print(e)\n print(str(message).encode(\"hex\"))\n\n client = nfc.handover.HandoverClient(llc)\n try:\n summary(\"Trying to initiate NFC connection handover\")\n client.connect()\n summary(\"Connected for handover\")\n except nfc.llcp.ConnectRefused:\n summary(\"Handover connection refused\")\n client.close()\n return\n except Exception as e:\n summary(\"Other exception: \" + str(e))\n client.close()\n return\n\n summary(\"Sending handover request\")\n\n if not client.send(message):\n summary(\"Failed to send handover request\")\n client.close()\n return\n\n summary(\"Receiving handover response\")\n message = client._recv()\n if message is None:\n summary(\"No response received\")\n client.close()\n return\n if message.type != \"urn:nfc:wkt:Hs\":\n summary(\"Response was not Hs - received: \" + message.type)\n client.close()\n return\n\n print(\"Received message\")\n try:\n print(message.pretty())\n except Exception as e:\n print(e)\n print(str(message).encode(\"hex\"))\n message = nfc.ndef.HandoverSelectMessage(message)\n summary(\"Handover select received\")\n try:\n print(message.pretty())\n except Exception as e:\n print(e)\n\n for carrier in message.carriers:\n print(\"Remote carrier type: \" + carrier.type)\n if carrier.type == \"application/vnd.wfa.p2p\":\n print(\"P2P carrier type match - send to wpa_supplicant\")\n if \"OK\" in wpas_report_handover(data, carrier.record, \"INIT\"):\n success_report(\"P2P handover reported successfully (initiator)\")\n else:\n summary(\"P2P handover report rejected\")\n break\n\n print(\"Remove peer\")\n client.close()\n print(\"Done with handover\")\n global only_one\n if only_one:\n print(\"only_one -> stop loop\")\n global continue_loop\n continue_loop = False\n\n global no_wait\n if no_wait:\n print(\"Trying to exit..\")\n global terminate_now\n terminate_now = True", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "def generate_mock_columns(connection, table_name, should_mock_column_nulls,\n should_use_random_test_data):\n auto_increment_column_names = get_auto_increment_column_names(\n connection, table_name)\n\n mock_columns = []\n\n table_info = get_table_info(connection, table_name)\n for column_name, column_type, column_notnull, column_pk in zip(\n column_names(table_info), column_types(table_info),\n column_notnulls(table_info), column_pks(table_info)):\n if column_name in auto_increment_column_names:\n # Do not mock auto-increment columns.\n continue\n\n mock_column = None\n\n if column_pk == 1:\n # Always mock the column if the column is a primary key.\n mock_column = (\n generate_mock_column_with_random_test_data(\n connection, table_name, column_name, column_type)\n if is_column_unique(connection, table_name, column_name)\n or should_use_random_test_data else\n generate_mock_column_with_fixed_test_data(column_type))\n elif column_notnull == 1:\n # Always mock the column if the column has a NOT NULL constraint.\n mock_column = (\n generate_mock_column_with_random_test_data(\n connection, table_name, column_name, column_type)\n if is_column_unique(connection, table_name, column_name)\n or should_use_random_test_data else\n generate_mock_column_with_fixed_test_data(column_type))\n else:\n # Only mock the column if we should mock NULL columns.\n if should_mock_column_nulls:\n mock_column = (\n generate_mock_column_with_random_test_data(\n connection, table_name, column_name, column_type)\n if should_use_random_test_data else\n generate_mock_column_with_fixed_test_data(column_type))\n\n mock_columns.append(mock_column)\n\n return mock_columns", "smellKey": "S3776", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def getButtonSetupFunctions():\n\ttextSetup = _(\"Setup\")\n\ttextEPG = _(\"EPG\")\n\ttextInfoBar = _(\"InfoBar\")\n\ttextScanning = _(\"Scanning\")\n\ttextPower = _(\"Power\")\n\ttextPlugins = _(\"Plugins\")\n\tButtonSetupFunctions = []\n\ttwinPlugins = []\n\ttwinPaths = {}\n\tpluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO)\n\tpluginlist.sort(key=lambda p: p.name)\n\tfor plugin in pluginlist:\n\t\tif plugin.name not in twinPlugins and plugin.path and \"selectedevent\" not in plugin.__call__.__code__.co_varnames:\n\t\t\tif plugin.path[plugin.path.rfind(\"Plugins\"):] in twinPaths:\n\t\t\t\ttwinPaths[plugin.path[plugin.path.rfind(\"Plugins\"):]] += 1\n\t\t\telse:\n\t\t\t\ttwinPaths[plugin.path[plugin.path.rfind(\"Plugins\"):]] = 1\n\t\t\tButtonSetupFunctions.append((plugin.name, f\"{plugin.path[plugin.path.rfind('Plugins'):]}/{str(twinPaths[plugin.path[plugin.path.rfind('Plugins'):]])}\", textEPG))\n\t\t\ttwinPlugins.append(plugin.name)\n\tpluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO, PluginDescriptor.WHERE_BUTTONSETUP])\n\tpluginlist.sort(key=lambda p: p.name)\n\tfor plugin in pluginlist:\n\t\tif plugin.name not in twinPlugins and plugin.path:\n\t\t\tif plugin.path[plugin.path.rfind(\"Plugins\"):] in twinPaths:\n\t\t\t\ttwinPaths[plugin.path[plugin.path.rfind(\"Plugins\"):]] += 1\n\t\t\telse:\n\t\t\t\ttwinPaths[plugin.path[plugin.path.rfind(\"Plugins\"):]] = 1\n\t\t\tButtonSetupFunctions.append((plugin.name, f\"{plugin.path[plugin.path.rfind('Plugins'):]}/{str(twinPaths[plugin.path[plugin.path.rfind('Plugins'):]])}\", textPlugins))\n\t\t\ttwinPlugins.append(plugin.name)\n\tButtonSetupFunctions.append((_(\"Show vertical Program Guide\"), \"Infobar/openVerticalEPG\", textEPG))\n\tButtonSetupFunctions.append((_(\"Show graphical multi EPG\"), \"Infobar/openGraphEPG\", textEPG))\n\tButtonSetupFunctions.append((_(\"Main Menu\"), \"Infobar/showMainMenu\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show help\"), \"Infobar/showHelp\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show extension selection\"), \"Infobar/showExtensionSelection\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Zap down\"), \"Infobar/zapDown\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Zap up\"), \"Infobar/zapUp\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Volume down\"), \"Infobar/volumeDown\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Volume up\"), \"Infobar/volumeUp\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show InfoBar\"), \"Infobar/toggleShow\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show service list\"), \"Infobar/openServiceList\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show favorites list\"), \"Infobar/openBouquets\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show satellites list\"), \"Infobar/openSatellites\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"History back\"), \"Infobar/historyBack\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"History next\"), \"Infobar/historyNext\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show eventinfo plugins\"), \"Infobar/showEventInfoPlugins\", textEPG))\n\tButtonSetupFunctions.append((_(\"Show event details\"), \"Infobar/openEventView\", textEPG))\n\tButtonSetupFunctions.append((_(\"Show single service EPG\"), \"Infobar/openSingleServiceEPG\", textEPG))\n\tButtonSetupFunctions.append((_(\"Show multi channel EPG\"), \"Infobar/openMultiServiceEPG\", textEPG))\n\tButtonSetupFunctions.append((_(\"Show Audioselection\"), \"Infobar/audioSelection\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Enable digital downmix\"), \"Infobar/audioDownmixOn\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Disable digital downmix\"), \"Infobar/audioDownmixOff\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Switch to Radio mode\"), \"Infobar/showRadio\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Switch to TV mode\"), \"Infobar/showTv\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show servicelist or movies\"), \"Infobar/showServiceListOrMovies\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show movies\"), \"Infobar/showMovies\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Instant record\"), \"Infobar/instantRecord\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Start instant recording\"), \"Infobar/startInstantRecording\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Start recording current event\"), \"Infobar/startRecordingCurrentEvent\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Activate time shift End\"), \"Infobar/activateTimeshiftEnd\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Activate time shift end and pause\"), \"Infobar/activateTimeshiftEndAndPause\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Start time shift\"), \"Infobar/startTimeshift\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Stop time shift\"), \"Infobar/stopTimeshift\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Start teletext\"), \"Infobar/startTeletext\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show subservices\"), \"Infobar/openSubservices\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show subservice selection\"), \"Infobar/hotkeySubserviceSelection\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show subtitle selection\"), \"Infobar/subtitleSelection\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Show subtitle quick menu\"), \"Infobar/subtitleQuickMenu\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Letterbox zoom\"), \"Infobar/vmodeSelection\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Seekbar\"), \"Infobar/seekFwdVod\", textInfoBar))\n\tif BoxInfo.getItem(\"PIPAvailable\"):\n\t\tButtonSetupFunctions.append((_(\"Show PiP\"), \"Infobar/showPiP\", textInfoBar))\n\t\tButtonSetupFunctions.append((_(\"Swap PiP\"), \"Infobar/swapPiP\", textInfoBar))\n\t\tButtonSetupFunctions.append((_(\"Move PiP\"), \"Infobar/movePiP\", textInfoBar))\n\t\tButtonSetupFunctions.append((_(\"Toggle PiPzap\"), \"Infobar/togglePipzap\", textInfoBar))\n\t\tButtonSetupFunctions.append((_(\"Cycle PiP(zap)\"), \"Infobar/activePiP\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Activate HbbTV (RED button)\"), \"Infobar/activateRedButton\", textInfoBar))\n\tif BoxInfo.getItem(\"hdmihdin\") or BoxInfo.getItem(\"hdmifhdin\"):\n\t\tButtonSetupFunctions.append((_(\"Toggle HDMI-In full screen\"), \"Infobar/HDMIInFull\", textInfoBar))\n\t\tButtonSetupFunctions.append((_(\"Toggle HDMI-In PiP\"), \"Infobar/HDMIInPiP\", textInfoBar))\n\tif BoxInfo.getItem(\"LcdLiveTV\"):\n\t\tButtonSetupFunctions.append((_(\"Toggle LCD LiveTV\"), \"Infobar/ToggleLCDLiveTV\", textInfoBar))\n\tif BoxInfo.getItem(\"canMultiBoot\"):\n\t\tButtonSetupFunctions.append((_(\"MultiBoot Manager\"), \"Module/Screens.MultiBootManager/MultiBootManager\", textInfoBar))\n\tButtonSetupFunctions.append((_(\"Hotkey Settings\"), \"Module/Screens.ButtonSetup/ButtonSetup\", textSetup))\n\tButtonSetupFunctions.append((_(\"Software Update\"), \"Module/Screens.SoftwareUpdate/SoftwareUpdate\", textSetup))\n\tif BoxInfo.getItem(\"ci\"):\n\t\tButtonSetupFunctions.append((_(\"CI (Common Interface) Setup\"), \"Module/Screens.Ci/CiSelection\", textSetup))\n\tif BoxInfo.getItem(\"SoftCam\"):\n\t\tButtonSetupFunctions.append((_(\"Softcam Setup\"), \"Module/Screens.SoftcamSetup/SoftcamSetup\", textSetup))\n\tButtonSetupFunctions.append((_(\"Videosetup\"), \"Module/Screens.VideoMode/VideoSetup\", textSetup))\n\tButtonSetupFunctions.append((_(\"Tuner Configuration\"), \"Module/Screens.Satconfig/NimSelection\", textScanning))\n\tButtonSetupFunctions.append((_(\"Manual Scan\"), \"Module/Screens.ScanSetup/ScanSetup\", textScanning))\n\tButtonSetupFunctions.append((_(\"Automatic Scan\"), \"Module/Screens.ScanSetup/ScanSimple\", textScanning))\n\tfor plugin in plugins.getPluginsForMenu(\"scan\"):\n\t\tButtonSetupFunctions.append((plugin[0], \"MenuPlugin/scan/\" + plugin[2], textScanning))\n\tButtonSetupFunctions.append((_(\"Network Settings\"), \"Module/Screens.NetworkSetup/NetworkAdapterSelection\", textSetup))\n\tButtonSetupFunctions.append((_(\"Network menu\"), \"Infobar/showNetworkMenu\", textSetup))\n\tButtonSetupFunctions.append((_(\"Plugin Browser\"), \"Module/Screens.PluginBrowser/PluginBrowser\", textSetup))\n\tButtonSetupFunctions.append((_(\"Channel Info\"), \"Module/Screens.Information/ServiceInformation\", textSetup))\n\tButtonSetupFunctions.append((_(\"SkinSelection\"), \"Module/Screens.SkinSelection/SkinSelection\", textSetup))\n\tButtonSetupFunctions.append((_(\"RecordTimer\"), \"Module/Screens.Timers/RecordTimerOverview\", textSetup))\n\tButtonSetupFunctions.append((_(\"Open AutoTimer\"), \"Infobar/showAutoTimerList\", textSetup))\n\tfor plugin in plugins.getPluginsForMenu(\"system\"):\n\t\tif plugin[2]:\n\t\t\tButtonSetupFunctions.append((plugin[0], \"MenuPlugin/system/\" + plugin[2], textSetup))\n\tButtonSetupFunctions.append((_(\"Standby\"), \"Module/Screens.Standby/Standby\", textPower))\n\tButtonSetupFunctions.append((_(\"Restart\"), \"Module/Screens.Standby/TryQuitMainloop/2\", textPower))\n\tButtonSetupFunctions.append((_(\"Restart enigma\"), \"Module/Screens.Standby/TryQuitMainloop/3\", textPower))\n\tButtonSetupFunctions.append((_(\"Deep Standby\"), \"Module/Screens.Standby/TryQuitMainloop/1\", textPower))\n\tButtonSetupFunctions.append((_(\"SleepTimer\"), \"Module/Screens.SleepTimer/SleepTimer\", textPower))\n\tButtonSetupFunctions.append((_(\"PowerTimer\"), \"Module/Screens.Timers/PowerTimerOverview\", textPower))\n\tButtonSetupFunctions.append((_(\"Usage Setup\"), \"Setup/Usage\", textSetup))\n\tButtonSetupFunctions.append((_(\"User interface settings\"), \"Setup/UserInterface\", textSetup))\n\tButtonSetupFunctions.append((_(\"Recording Setup\"), \"Setup/Recording\", textSetup))\n\tButtonSetupFunctions.append((_(\"Harddisk Setup\"), \"Setup/HardDisk\", textSetup))\n\tButtonSetupFunctions.append((_(\"Mount Manager\"), \"Module/Screens.MountManager/HddMount\", textSetup))\n\tButtonSetupFunctions.append((_(\"Subtitles Settings\"), \"Setup/Subtitle\", textSetup))\n\tButtonSetupFunctions.append((_(\"Language\"), \"Module/Screens.LocaleSelection/LocaleSelection\", textSetup))\n\tif BoxInfo.getItem(\"SoftCam\"):\n\t\tButtonSetupFunctions.append((_(\"Oscam Information\"), \"Module/Screens.OScamInfo/OSCamInfo\", textPlugins))\n\t\tButtonSetupFunctions.append((_(\"CCcamInfo Mainmenu\"), \"Module/Screens.CCcamInfo/CCcamInfoMain\", textPlugins))\n\tButtonSetupFunctions.append((_(\"Movieplayer\"), \"Infobar/showMoviePlayer\", textPlugins))\n\tif isdir(\"/etc/ppanels\"):\n\t\tfor file in [x for x in listdir(\"/etc/ppanels\") if x.endswith(\".xml\")]:\n\t\t\tfile = file[:-4]\n\t\t\tButtonSetupFunctions.append((f\"{_('PPanel')} {file}\", f\"PPanel/{file}\", \"PPanels\"))\n\tif isdir(\"/usr/script\"):\n\t\tfor file in [x for x in listdir(\"/usr/script\") if x.endswith(\".sh\")]:\n\t\t\tfile = file[:-3]\n\t\t\tButtonSetupFunctions.append((f\"{_('Shellscript')} {file}\", f\"Shellscript/{file}\", \"Shellscripts\"))\n\tButtonSetupFunctions.append((_(\"ScriptRunner\"), \"Module/Screens.ScriptRunner/ScriptRunner\", textPlugins))\n\tButtonSetupFunctions.append((_(\"QuickMenu\"), \"Module/Screens.QuickMenu/QuickMenu\", textPlugins))\n\tif isPluginInstalled(\"Kodi\"):\n\t\tButtonSetupFunctions.append((_(\"Kodi MediaCenter\"), \"Kodi/\", textPlugins))\n\tif isPluginInstalled(\"BluetoothSetup\"):\n\t\tButtonSetupFunctions.append((_(\"Bluetooth Setup\"), \"Bluetooth/\", textPlugins))\n\tif isPluginInstalled(\"Chromium\"):\n\t\tButtonSetupFunctions.append((_(\"Youtube TV\"), \"YoutubeTV/\", textPlugins))\n\tButtonSetupFunctions.append((_(\"Reload Skin\"), \"ReloadSkin/\", textSetup))\n\treturn ButtonSetupFunctions", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@staticmethod\n def CollectDataOnSampledCellsInBlock(recursionObject, inInputCsData, inParameters):\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock entered 1\\n\")\n\n inParameters.leafVisitCount += 1\n\n if inParameters.GeometricallySampledCellsByRecursionLeaf == None:\n #no cells collected for sampling on this process\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 1\\n\")\n return\n\n if inParameters.leafVisitCount not in inParameters.GeometricallySampledCellsByRecursionLeaf:\n #no cells collected for sampling on this block on this process\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 2\\n\")\n return\n\n numCells = inInputCsData.GetNumberOfCells()\n numPoints = inInputCsData.GetNumberOfPoints()\n if (numCells == 0) or (numPoints == 0):\n #no cells here\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 3\\n\")\n return\n\n cellData = inInputCsData.GetCellData()\n if cellData == None:\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 4\\n\")\n return\n\n testDataCellArray = None\n testDataCellArray = cellData.GetArray(inParameters.dataArrayNames[0])\n\n if testDataCellArray == None:\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 5\\n\")\n return\n\n outputCellArrays = []\n dataArrayNumCmpnts = 0\n if cellData != None:\n for oneDataArrayName in inParameters.dataArrayNames:\n oneCellDataArray = cellData.GetArray(oneDataArrayName)\n outputCellArrays.append(oneCellDataArray)\n if oneCellDataArray != None:\n dataArrayNumCmpnts += oneCellDataArray.GetNumberOfComponents()\n if PhactoriDbg(100):\n myDebugPrint3(\"inParameters.dataArrayNames: \" + str(inParameters.dataArrayNames) + \"\\n\")\n for oneCellDataArray in outputCellArrays:\n if oneCellDataArray == None:\n myDebugPrint3(\"None\\n\")\n else:\n myDebugPrint3(str(oneCellDataArray.GetNumberOfTuples()) + \"\\n\")\n \n if dataArrayNumCmpnts != 0:\n defaultTuple = []\n for ii in range(0, dataArrayNumCmpnts):\n defaultTuple.append(-1.0)\n else:\n dataArrayNumCmpnts = -1\n defaultTuple = []\n\n myPid = SmartGetLocalProcessId()\n\n sampleCellList = inParameters.GeometricallySampledCellsByRecursionLeaf[inParameters.leafVisitCount]\n if PhactoriDbg(100):\n myDebugPrint3(\"num cells, leaf: \" + str(len(sampleCellList)) + \", \" + str(inParameters.leafVisitCount) + \"\\n\")\n for oneSampleCell in sampleCellList:\n #thisCellDataTuple = outputCellArray.GetTuple(oneSampleCell.index)\n if dataArrayNumCmpnts == 0:\n thisCellDataTuple = defaultTuple\n else:\n thisCellDataTuple = []\n for oneCellDataArray in outputCellArrays:\n if oneCellDataArray != None:\n dataTupleSub1 = oneCellDataArray.GetTuple(oneSampleCell.index)\n thisCellDataTuple.extend(dataTupleSub1)\n tupleCount = min(len(thisCellDataTuple), len(oneSampleCell.dataTuple))\n if PhactoriDbg(100):\n myDebugPrint3(str(oneSampleCell.index) + \", \" + str(thisCellDataTuple) + \", \" + str(tupleCount) + \"\\n\")\n for ii in range(0, tupleCount):\n oneSampleCell.dataTuple[ii] = thisCellDataTuple[ii]\n\n if PhactoriDbg(100):\n myDebugPrint3(\"CollectDataOnSampledCellsInBlock returning 6\\n\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def __init__(self, obj, subscript):\n super().__init__(obj.name)\n self.obj = obj\n if isinstance(subscript, int):\n if subscript < 0:\n raise ValueError(\"Negative indexing is not supported.\")\n self.start = subscript + 1\n self.length = 1\n elif isinstance(subscript, slice):\n if (subscript.start is not None and subscript.start < 0) or (\n subscript.stop is not None and subscript.stop < 0\n ):\n raise ValueError(\"Negative indexing is not supported.\")\n if subscript.step is not None:\n raise ValueError(\"Step argument is not supported.\")\n if subscript.stop and subscript.start and subscript.stop < subscript.start:\n raise ValueError(\"Slice stop must be greater than slice start.\")\n self.start = 1 if subscript.start is None else subscript.start + 1\n if subscript.stop is None:\n self.length = None\n else:\n self.length = subscript.stop - (subscript.start or 0)\n else:\n raise TypeError(\"Argument to slice must be either int or slice instance.\")", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@classmethod\n def split_lines(cls, segments: Iterable[\"Segment\"]) -> Iterable[List[\"Segment\"]]:\n \"\"\"Split a sequence of segments in to a list of lines.\n\n Args:\n segments (Iterable[Segment]): Segments potentially containing line feeds.\n\n Yields:\n Iterable[List[Segment]]: Iterable of segment lists, one per line.\n \"\"\"\n line: List[Segment] = []\n append = line.append\n\n for segment in segments:\n if \"\\n\" in segment.text and not segment.control:\n text, style, _ = segment\n while text:\n _text, new_line, text = text.partition(\"\\n\")\n if _text:\n append(cls(_text, style))\n if new_line:\n yield line\n line = []\n append = line.append\n else:\n append(segment)\n if line:\n yield line", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _create_mac(self):\n font_map = {}\n for font_dir in (os.path.join(os.getenv(\"HOME\"), 'Library/Fonts/'),\n '/Library/Fonts/', '/System/Library/Fonts/'):\n font_map.update(\n (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))\n for f in os.listdir(font_dir)\n if f.lower().endswith(('ttf', 'ttc')))\n\n for name in STYLES['NORMAL']:\n path = self._get_mac_font_path(font_map, self.font_name, name)\n if path is not None:\n self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)\n break\n else:\n raise FontNotFound('No usable fonts named: \"%s\"' %\n self.font_name)\n for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):\n for stylename in STYLES[style]:\n path = self._get_mac_font_path(font_map, self.font_name, stylename)\n if path is not None:\n self.fonts[style] = ImageFont.truetype(path, self.font_size)\n break\n else:\n if style == 'BOLDITALIC':\n self.fonts[style] = self.fonts['BOLD']\n else:\n self.fonts[style] = self.fonts['NORMAL']", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _text_report_agg_gen(self, aggformat):\n by_single_task = \"\"\n if len(self.tasks) > 1:\n by_single_task = \" by a single task\"\n\n metrics = [\n ('Elapsed time',\n self.elapsed_time(),\n None,\n ''),\n\n ('Estimated cost',\n '${:.3f}'.format(self.cost),\n None,\n '') if self.cost > 0 else None,\n\n ('Assigned instance type',\n self.node_info.get('ProviderType'),\n None,\n '') if self.node_info.get('ProviderType') else None,\n\n ('Instance hourly price',\n '${:.3f}'.format(self.node_info.get('Price')),\n None,\n '') if self.node_info.get('Price') else None,\n\n ('Max CPU usage in a single interval',\n self.stats_max['cpu']['user+sys__rate'],\n lambda x: x * 100,\n '%'),\n\n ('Overall CPU usage',\n float(self.job_tot['cpu']['user+sys']) /\n self.job_tot['time']['elapsed']\n if self.job_tot['time']['elapsed'] > 0 else 0,\n lambda x: x * 100,\n '%'),\n\n ('Requested CPU cores',\n self.existing_constraints.get(self._map_runtime_constraint('vcpus')),\n None,\n '') if self.existing_constraints.get(self._map_runtime_constraint('vcpus')) else None,\n\n ('Instance VCPUs',\n self.node_info.get('VCPUs'),\n None,\n '') if self.node_info.get('VCPUs') else None,\n\n ('Max memory used{}'.format(by_single_task),\n self.stats_max['mem']['rss'],\n lambda x: x / 2**20,\n 'MB'),\n\n ('Requested RAM',\n self.existing_constraints.get(self._map_runtime_constraint('ram')),\n lambda x: x / 2**20,\n 'MB') if self.existing_constraints.get(self._map_runtime_constraint('ram')) else None,\n\n ('Maximum RAM request for this instance type',\n (self.node_info.get('RAM') - self.arv_config.get('Containers', {}).get('ReserveExtraRAM', 0))*.95,\n lambda x: x / 2**20,\n 'MB') if self.node_info.get('RAM') else None,\n\n ('Max network traffic{}'.format(by_single_task),\n self.stats_max['net:eth0']['tx+rx'] +\n self.stats_max['net:keep0']['tx+rx'],\n lambda x: x / 1e9,\n 'GB'),\n\n ('Max network speed in a single interval',\n self.stats_max['net:eth0']['tx+rx__rate'] +\n self.stats_max['net:keep0']['tx+rx__rate'],\n lambda x: x / 1e6,\n 'MB/s'),\n\n ('Keep cache miss rate',\n (float(self.job_tot['keepcache']['miss']) /\n float(self.job_tot['keepcalls']['get']))\n if self.job_tot['keepcalls']['get'] > 0 else 0,\n lambda x: x * 100.0,\n '%'),\n\n ('Keep cache utilization',\n (float(self.job_tot['blkio:0:0']['read']) /\n float(self.job_tot['net:keep0']['rx']))\n if self.job_tot['net:keep0']['rx'] > 0 else 0,\n lambda x: x * 100.0,\n '%'),\n\n ('Temp disk utilization',\n (float(self.job_tot['statfs']['used']) /\n float(self.job_tot['statfs']['total']))\n if self.job_tot['statfs']['total'] > 0 else 0,\n lambda x: x * 100.0,\n '%'),\n ]\n\n if len(self.tasks) > 1:\n metrics.insert(0, ('Number of tasks',\n len(self.tasks),\n None,\n ''))\n for args in metrics:\n if args is None:\n continue\n format_string, val, transform, suffix = args\n if val == float('-Inf'):\n continue\n if transform:\n val = transform(val)\n yield aggformat((format_string, self._format(val), suffix))", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def changed(self, what):\n\t\tdef setTemplate():\n\t\t\tdef scaleTemplate(template, itemWidth, itemHeight):\n\t\t\t\tscaleFactorVertical = self.scale[1][0] / self.scale[1][1]\n\t\t\t\tscaleFactorHorizontal = self.scale[0][0] / self.scale[0][1]\n\t\t\t\titemWidth = int(itemWidth * scaleFactorHorizontal)\n\t\t\t\titemHeight = int(itemHeight * scaleFactorVertical)\n\t\t\t\tscaledTemplate = []\n\t\t\t\tfonts = []\n\t\t\t\tfor font in self.template[\"fonts\"]:\n\t\t\t\t\tfonts.append(gFont(font.family, int(font.pointSize * scaleFactorVertical)))\n\t\t\t\tfor content in template:\n\t\t\t\t\telements = list(content)\n\t\t\t\t\telements[1] = int(elements[1] * scaleFactorVertical)\n\t\t\t\t\telements[2] = int(elements[2] * scaleFactorHorizontal)\n\t\t\t\t\telements[3] = int(elements[3] * scaleFactorVertical)\n\t\t\t\t\telements[4] = int(elements[4] * scaleFactorHorizontal)\n\t\t\t\t\tscaledTemplate.append(tuple(elements))\n\t\t\t\treturn scaledTemplate, itemWidth, itemHeight, fonts\n\n\t\t\tif self.source:\n\t\t\t\tstyle = self.source.style\n\t\t\t\tif style == self.activeStyle:\n\t\t\t\t\treturn\n\t\t\t\ttemplates = self.template.get(\"templates\") # If skin defined \"templates\", that means that it defines multiple styles in a dictionary but template should still be a default.\n\t\t\t\ttemplate = self.template.get(\"template\")\n\t\t\t\tif \"itemHeight\" in self.template:\n\t\t\t\t\titemHeight = self.template[\"itemHeight\"]\n\t\t\t\t\titemWidth = itemHeight\n\t\t\t\tif \"itemWidth\" in self.template:\n\t\t\t\t\titemWidth = self.template[\"itemWidth\"]\n\t\t\t\tif \"itemSize\" in self.template:\n\t\t\t\t\titemWidth = self.template[\"itemSize\"]\n\t\t\t\t\titemHeight = itemWidth\n\t\t\t\tselectionEnabled = self.template.get(\"selectionEnabled\", None)\n\t\t\t\tscrollbarMode = self.template.get(\"scrollbarMode\", None)\n\t\t\t\tif templates and style and style in templates: # If we have a custom style defined in the source, and different templates in the skin, look the template up.\n\t\t\t\t\ttemplate = templates[style][1]\n\t\t\t\t\tif isinstance(templates[style][0], tuple):\n\t\t\t\t\t\titemWidth = templates[style][0][0]\n\t\t\t\t\t\titemHeight = templates[style][0][1]\n\t\t\t\t\telse:\n\t\t\t\t\t\titemWidth = templates[style][0]\n\t\t\t\t\t\titemHeight = itemWidth\n\t\t\t\t\tif len(templates[style]) > 2:\n\t\t\t\t\t\tselectionEnabled = templates[style][2]\n\t\t\t\t\tif len(templates[style]) > 3:\n\t\t\t\t\t\tscrollbarMode = templates[style][3]\n\t\t\t\tif self.scale:\n\t\t\t\t\ttemplate, itemWidth, itemHeight, fonts = scaleTemplate(template, itemWidth, itemHeight)\n\t\t\t\t\tfor index, font in enumerate(fonts):\n\t\t\t\t\t\tself.content.setFont(index, font)\n\t\t\t\tself.content.setTemplate(template)\n\t\t\t\tself.content.setItemWidth(int(itemWidth))\n\t\t\t\tself.content.setItemHeight(int(itemHeight))\n\t\t\t\tif selectionEnabled is not None:\n\t\t\t\t\tself.selectionEnabled = selectionEnabled\n\t\t\t\tif scrollbarMode is not None:\n\t\t\t\t\tself.scrollbarMode = scrollbarMode\n\t\t\t\tself.activeStyle = style\n\n\t\tif not self.content:\n\t\t\tself.content = eListboxPythonMultiContent()\n\t\t\tfor index, font in enumerate(self.template[\"fonts\"]): # Setup fonts (also given by source).\n\t\t\t\tself.content.setFont(index, font)\n\t\tif what[0] == self.CHANGED_SPECIFIC and what[1] == \"style\" and self.scale is not None: # If only template changed, don't reload list.\n\t\t\tpass\n\t\telif self.source:\n\t\t\tif self.scale is None and self.downstream_elements:\n\t\t\t\tlistBoxRenderer = self.downstream_elements[0]\n\t\t\t\tif str(listBoxRenderer.__class__.__name__) == \"Listbox\":\n\t\t\t\t\tif hasattr(listBoxRenderer, \"scale\"):\n\t\t\t\t\t\tscale = listBoxRenderer.scale\n\t\t\t\t\t\tif scale and (scale[0][0] != scale[0][1] or scale[1][0] != scale[1][1]):\n\t\t\t\t\t\t\tself.scale = scale\n\t\t\t\t\t\t\tself.activeStyle = None\n\t\t\ttry:\n\t\t\t\tcontentList = []\n\t\t\t\tsourceList = self.source.list\n\t\t\t\tfor item in range(len(sourceList)):\n\t\t\t\t\tif not isinstance(sourceList[item], (list, tuple)):\n\t\t\t\t\t\tcontentList.append((sourceList[item],))\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontentList.append(sourceList[item])\n\t\t\texcept Exception as error:\n\t\t\t\tprint(f\"[TemplatedMultiContent] Error: {error}.\")\n\t\t\t\tcontentList = self.source.list\n\t\t\tself.content.setList(contentList)\n\t\tsetTemplate()\n\t\tself.downstream_elements.changed(what)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def parse_config_file(\n options: Options,\n set_strict_flags: Callable[[], None],\n filename: str | None,\n stdout: TextIO | None = None,\n stderr: TextIO | None = None,\n) -> None:\n \"\"\"Parse a config file into an Options object.\n\n Errors are written to stderr but are not fatal.\n\n If filename is None, fall back to default config files.\n \"\"\"\n stdout = stdout or sys.stdout\n stderr = stderr or sys.stderr\n\n if filename is not None:\n config_files: tuple[str, ...] = (filename,)\n else:\n config_files_iter: Iterable[str] = map(os.path.expanduser, defaults.CONFIG_FILES)\n config_files = tuple(config_files_iter)\n\n config_parser = configparser.RawConfigParser()\n\n for config_file in config_files:\n if not os.path.exists(config_file):\n continue\n try:\n if is_toml(config_file):\n with open(config_file, \"rb\") as f:\n toml_data = tomllib.load(f)\n # Filter down to just mypy relevant toml keys\n toml_data = toml_data.get(\"tool\", {})\n if \"mypy\" not in toml_data:\n continue\n toml_data = {\"mypy\": toml_data[\"mypy\"]}\n parser: MutableMapping[str, Any] = destructure_overrides(toml_data)\n config_types = toml_config_types\n else:\n config_parser.read(config_file)\n parser = config_parser\n config_types = ini_config_types\n except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err:\n print(f\"{config_file}: {err}\", file=stderr)\n else:\n if config_file in defaults.SHARED_CONFIG_FILES and \"mypy\" not in parser:\n continue\n file_read = config_file\n options.config_file = file_read\n break\n else:\n return\n\n os.environ[\"MYPY_CONFIG_FILE_DIR\"] = os.path.dirname(os.path.abspath(config_file))\n\n if \"mypy\" not in parser:\n if filename or file_read not in defaults.SHARED_CONFIG_FILES:\n print(f\"{file_read}: No [mypy] section in config file\", file=stderr)\n else:\n section = parser[\"mypy\"]\n prefix = f\"{file_read}: [mypy]: \"\n updates, report_dirs = parse_section(\n prefix, options, set_strict_flags, section, config_types, stderr\n )\n for k, v in updates.items():\n setattr(options, k, v)\n options.report_dirs.update(report_dirs)\n\n for name, section in parser.items():\n if name.startswith(\"mypy-\"):\n prefix = get_prefix(file_read, name)\n updates, report_dirs = parse_section(\n prefix, options, set_strict_flags, section, config_types, stderr\n )\n if report_dirs:\n print(\n prefix,\n \"Per-module sections should not specify reports ({})\".format(\n \", \".join(s + \"_report\" for s in sorted(report_dirs))\n ),\n file=stderr,\n )\n if set(updates) - PER_MODULE_OPTIONS:\n print(\n prefix,\n \"Per-module sections should only specify per-module flags ({})\".format(\n \", \".join(sorted(set(updates) - PER_MODULE_OPTIONS))\n ),\n file=stderr,\n )\n updates = {k: v for k, v in updates.items() if k in PER_MODULE_OPTIONS}\n\n globs = name[5:]\n for glob in globs.split(\",\"):\n # For backwards compatibility, replace (back)slashes with dots.\n glob = glob.replace(os.sep, \".\")\n if os.altsep:\n glob = glob.replace(os.altsep, \".\")\n\n if any(c in glob for c in \"?[]!\") or any(\n \"*\" in x and x != \"*\" for x in glob.split(\".\")\n ):\n print(\n prefix,\n \"Patterns must be fully-qualified module names, optionally \"\n \"with '*' in some components (e.g spam.*.eggs.*)\",\n file=stderr,\n )\n else:\n options.per_module_options[glob] = updates", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def post_process(self, interface_prefix, cns, cns_upper, cns_lower, containing_iface):\n if len(self.doc_string) == 0:\n self.doc_string = utils.lookup_docs(self.annotations)\n if len(self.since) == 0:\n self.since = utils.lookup_since(self.annotations)\n if len(self.since) == 0:\n self.since = containing_iface.since\n\n name = self.name\n overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.C.Name')\n if utils.is_ugly_case(overridden_name):\n self.name_lower = overridden_name.lower()\n else:\n if overridden_name:\n name = overridden_name\n self.name_lower = utils.camel_case_to_uscore(name).lower().replace('-', '_')\n self.name_hyphen = self.name_lower.replace('_', '-')\n\n arg_count = 0\n for a in self.in_args:\n a.post_process(interface_prefix, cns, cns_upper, cns_lower, arg_count)\n arg_count += 1\n if self.h_type_implies_unix_fd and 'h' in a.signature:\n self.unix_fd = True\n\n for a in self.out_args:\n a.post_process(interface_prefix, cns, cns_upper, cns_lower, arg_count)\n arg_count += 1\n if self.h_type_implies_unix_fd and 'h' in a.signature:\n self.unix_fd = True\n\n if utils.lookup_annotation(self.annotations, 'org.freedesktop.DBus.Deprecated') == 'true':\n self.deprecated = True\n\n if utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.C.UnixFD'):\n self.unix_fd = True\n\n for a in self.annotations:\n a.post_process(interface_prefix, cns, cns_upper, cns_lower, self)", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "def add_error(self, field, error):\n \"\"\"\n Update the content of `self._errors`.\n\n The `field` argument is the name of the field to which the errors\n should be added. If it's None, treat the errors as NON_FIELD_ERRORS.\n\n The `error` argument can be a single error, a list of errors, or a\n dictionary that maps field names to lists of errors. An \"error\" can be\n either a simple string or an instance of ValidationError with its\n message attribute set and a \"list or dictionary\" can be an actual\n `list` or `dict` or an instance of ValidationError with its\n `error_list` or `error_dict` attribute set.\n\n If `error` is a dictionary, the `field` argument *must* be None and\n errors will be added to the fields that correspond to the keys of the\n dictionary.\n \"\"\"\n if not isinstance(error, ValidationError):\n # Normalize to ValidationError and let its constructor\n # do the hard work of making sense of the input.\n error = ValidationError(error)\n\n if hasattr(error, \"error_dict\"):\n if field is not None:\n raise TypeError(\n \"The argument `field` must be `None` when the `error` \"\n \"argument contains errors for multiple fields.\"\n )\n else:\n error = error.error_dict\n else:\n error = {field or NON_FIELD_ERRORS: error.error_list}\n\n for field, error_list in error.items():\n if field not in self.errors:\n if field != NON_FIELD_ERRORS and field not in self.fields:\n raise ValueError(\n \"'%s' has no field named '%s'.\"\n % (self.__class__.__name__, field)\n )\n if field == NON_FIELD_ERRORS:\n self._errors[field] = self.error_class(\n error_class=\"nonfield\", renderer=self.renderer\n )\n else:\n self._errors[field] = self.error_class(renderer=self.renderer)\n self._errors[field].extend(error_list)\n if field in self.cleaned_data:\n del self.cleaned_data[field]", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ExportOperationData(self, datadescription):\n \"\"\"this will be called once per callback (before WriteImages) to allow the\n operation to export any desired data which is not an image. The child\n class should override this method if it wants so do something.\n For PhactoriIntersectNodeNormalsWithSurface we will output information\n about the nearest and furthest intersections\"\"\"\n \n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData \"\n \"entered\\n\", 100)\n\n UpdatePipelineWithCurrentTimeArgument(\n self.mPhactoriOperationBlockOwner.mParaViewFilter)\n self.RunCalculationToCastRays(gPipeAndViewsState)\n UpdatePipelineWithCurrentTimeArgument(\n self.mPhactoriOperationBlockOwner.mParaViewFilter)\n\n if self.mPointNormalRayIntersectDistanceArray == None:\n if PhactoriDbg(100):\n myDebugPrint3(\"no data values, returning\\n\")\n return\n\n numpts = self.mPointNormalRayIntersectDistanceArray.GetNumberOfValues()\n maxval = -1.0\n minval = -1.0\n minval2 = -1.0\n if numpts > 0:\n vv = self.mPointNormalRayIntersectDistanceArray.GetValue(0)\n maxval = vv\n minval = vv\n if vv >= -0.5:\n minval2 = vv\n for ii in range(1, numpts):\n vv = self.mPointNormalRayIntersectDistanceArray.GetValue(ii)\n if vv > maxval:\n maxval = vv\n if vv < minval:\n minval = vv\n if vv >= -0.5:\n if (minval2 < -0.5) or (vv < minval2):\n minval2 = vv\n\n fname = \"RayIntersectionMinMax_\" + \\\n self.mPhactoriOperationBlockOwner.mName + \"_process_\" + \\\n str(SmartGetLocalProcessId()) + \".txt\"\n try:\n ff = open(fname, \"a+b\")\n ff.write(\"minimum, maximum, nonnegative minimum\\n\")\n ff.write(str(minval) + \", \" + str(maxval) + \", \" + str(minval2) + \"\\n\")\n except:\n myDebugPrint3AndException(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData\\n\"\n \"Error writing file: \" + str(fname) + \"\\n\")\n\n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData \"\n \"returning\\n\", 100)\n return", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def __getattribute__(self, key):\n common = object.__getattribute__(self, 'common_keys')\n mapped = object.__getattribute__(self, 'mapped_keys')\n if key in mapped:\n lk, maker = mapped[key]\n if self._legacy:\n if lk is None:\n result = None if maker is None else maker()\n else:\n result = self._legacy.get(lk)\n else:\n value = None if maker is None else maker()\n if key not in ('commands', 'exports', 'modules', 'namespaces',\n 'classifiers'):\n result = self._data.get(key, value)\n else:\n # special cases for PEP 459\n sentinel = object()\n result = sentinel\n d = self._data.get('extensions')\n if d:\n if key == 'commands':\n result = d.get('python.commands', value)\n elif key == 'classifiers':\n d = d.get('python.details')\n if d:\n result = d.get(key, value)\n else:\n d = d.get('python.exports')\n if not d:\n d = self._data.get('python.exports')\n if d:\n result = d.get(key, value)\n if result is sentinel:\n result = value\n elif key not in common:\n result = object.__getattribute__(self, key)\n elif self._legacy:\n result = self._legacy.get(key)\n else:\n result = self._data.get(key)\n return result", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def write_pot_file(potfile, msgs):\n \"\"\"\n Write the `potfile` with the `msgs` contents, making sure its format is\n valid.\n \"\"\"\n pot_lines = msgs.splitlines()\n if os.path.exists(potfile):\n # Strip the header\n lines = dropwhile(len, pot_lines)\n else:\n lines = []\n found, header_read = False, False\n for line in pot_lines:\n if not found and not header_read:\n if \"charset=CHARSET\" in line:\n found = True\n line = line.replace(\"charset=CHARSET\", \"charset=UTF-8\")\n if not line and not found:\n header_read = True\n lines.append(line)\n msgs = \"\\n\".join(lines)\n # Force newlines of POT files to '\\n' to work around\n # https://savannah.gnu.org/bugs/index.php?52395\n with open(potfile, \"a\", encoding=\"utf-8\", newline=\"\\n\") as fp:\n fp.write(msgs)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def close(self) -> ResultDict:\n \"\"\"\n Stop analyzing the current document and come up with a final\n prediction.\n\n :returns: The ``result`` attribute, a ``dict`` with the keys\n `encoding`, `confidence`, and `language`.\n \"\"\"\n # Don't bother with checks if we're already done\n if self.done:\n return self.result\n self.done = True\n\n if not self._got_data:\n self.logger.debug(\"no data received!\")\n\n # Default to ASCII if it is all we've seen so far\n elif self._input_state == InputState.PURE_ASCII:\n self.result = {\"encoding\": \"ascii\", \"confidence\": 1.0, \"language\": \"\"}\n\n # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD\n elif self._input_state == InputState.HIGH_BYTE:\n prober_confidence = None\n max_prober_confidence = 0.0\n max_prober = None\n for prober in self._charset_probers:\n if not prober:\n continue\n prober_confidence = prober.get_confidence()\n if prober_confidence > max_prober_confidence:\n max_prober_confidence = prober_confidence\n max_prober = prober\n if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD):\n charset_name = max_prober.charset_name\n assert charset_name is not None\n lower_charset_name = charset_name.lower()\n confidence = max_prober.get_confidence()\n # Use Windows encoding name instead of ISO-8859 if we saw any\n # extra Windows-specific bytes\n if lower_charset_name.startswith(\"iso-8859\"):\n if self._has_win_bytes:\n charset_name = self.ISO_WIN_MAP.get(\n lower_charset_name, charset_name\n )\n # Rename legacy encodings with superset encodings if asked\n if self.should_rename_legacy:\n charset_name = self.LEGACY_MAP.get(\n (charset_name or \"\").lower(), charset_name\n )\n self.result = {\n \"encoding\": charset_name,\n \"confidence\": confidence,\n \"language\": max_prober.language,\n }\n\n # Log all prober confidences if none met MINIMUM_THRESHOLD\n if self.logger.getEffectiveLevel() <= logging.DEBUG:\n if self.result[\"encoding\"] is None:\n self.logger.debug(\"no probers hit minimum threshold\")\n for group_prober in self._charset_probers:\n if not group_prober:\n continue\n if isinstance(group_prober, CharSetGroupProber):\n for prober in group_prober.probers:\n self.logger.debug(\n \"%s %s confidence = %s\",\n prober.charset_name,\n prober.language,\n prober.get_confidence(),\n )\n else:\n self.logger.debug(\n \"%s %s confidence = %s\",\n group_prober.charset_name,\n group_prober.language,\n group_prober.get_confidence(),\n )\n return self.result", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def getCPUInfoString():\n\tcpuCount = 0\n\tcpuSpeedStr = \"-\"\n\tcpuSpeedMhz = _getCPUSpeedMhz()\n\tprocessor = \"\"\n\tlines = fileReadLines(\"/proc/cpuinfo\", source=MODULE_NAME)\n\tif lines:\n\t\tfor line in lines:\n\t\t\tline = [x.strip() for x in line.strip().split(\":\", 1)]\n\t\t\tif not processor and line[0] in (\"system type\", \"model name\", \"Processor\"):\n\t\t\t\tprocessor = line[1].split()[0]\n\t\t\telif not cpuSpeedMhz and line[0] == \"cpu MHz\":\n\t\t\t\tcpuSpeedMhz = float(line[1])\n\t\t\telif line[0] == \"processor\":\n\t\t\t\tcpuCount += 1\n\t\tif processor.startswith(\"ARM\") and isfile(\"/proc/stb/info/chipset\"):\n\t\t\tprocessor = \"%s (%s)\" % (fileReadLine(\"/proc/stb/info/chipset\", \"\", source=MODULE_NAME).upper(), processor)\n\t\tif not cpuSpeedMhz:\n\t\t\tcpuSpeed = fileReadLine(\"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq\", source=MODULE_NAME)\n\t\t\tif cpuSpeed:\n\t\t\t\tcpuSpeedMhz = int(cpuSpeed) / 1000\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tcpuSpeedMhz = int(int(hexlify(open(\"/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency\", \"rb\").read()), 16) / 100000000) * 100\n\t\t\t\texcept:\n\t\t\t\t\tcpuSpeedMhz = 1500\n\n\t\ttemperature = None\n\t\tif isfile(\"/proc/stb/fp/temp_sensor_avs\"):\n\t\t\ttemperature = fileReadLine(\"/proc/stb/fp/temp_sensor_avs\", source=MODULE_NAME)\n\t\telif isfile(\"/proc/stb/power/avs\"):\n\t\t\ttemperature = fileReadLine(\"/proc/stb/power/avs\", source=MODULE_NAME)\n#\t\telif isfile(\"/proc/stb/fp/temp_sensor\"):\n#\t\t\ttemperature = fileReadLine(\"/proc/stb/fp/temp_sensor\", source=MODULE_NAME)\n#\t\telif isfile(\"/proc/stb/sensors/temp0/value\"):\n#\t\t\ttemperature = fileReadLine(\"/proc/stb/sensors/temp0/value\", source=MODULE_NAME)\n#\t\telif isfile(\"/proc/stb/sensors/temp/value\"):\n#\t\t\ttemperature = fileReadLine(\"/proc/stb/sensors/temp/value\", source=MODULE_NAME)\n\t\telif isfile(\"/sys/devices/virtual/thermal/thermal_zone0/temp\"):\n\t\t\ttemperature = fileReadLine(\"/sys/devices/virtual/thermal/thermal_zone0/temp\", source=MODULE_NAME)\n\t\t\tif temperature:\n\t\t\t\ttemperature = int(temperature) / 1000\n\t\telif isfile(\"/sys/class/thermal/thermal_zone0/temp\"):\n\t\t\ttemperature = fileReadLine(\"/sys/class/thermal/thermal_zone0/temp\", source=MODULE_NAME)\n\t\t\tif temperature:\n\t\t\t\ttemperature = int(temperature) / 1000\n\t\telif isfile(\"/proc/hisi/msp/pm_cpu\"):\n\t\t\tlines = fileReadLines(\"/proc/hisi/msp/pm_cpu\", source=MODULE_NAME)\n\t\t\tif lines:\n\t\t\t\tfor line in lines:\n\t\t\t\t\tif \"temperature = \" in line:\n\t\t\t\t\t\ttemperature = int(line.split(\"temperature = \")[1].split()[0])\n\n\t\tif cpuSpeedMhz and cpuSpeedMhz >= 1000:\n\t\t\tcpuSpeedStr = _(\"%s GHz\") % format_string(\"%.1f\", cpuSpeedMhz / 1000)\n\t\telse:\n\t\t\tcpuSpeedStr = _(\"%d MHz\") % int(cpuSpeedMhz)\n\n\t\tif temperature:\n\t\t\tdegree = \"\\u00B0\"\n\t\t\tif not isinstance(degree, str):\n\t\t\t\tdegree = degree.encode(\"UTF-8\", errors=\"ignore\")\n\t\t\tif isinstance(temperature, float):\n\t\t\t\ttemperature = format_string(\"%.1f\", temperature)\n\t\t\telse:\n\t\t\t\ttemperature = str(temperature)\n\t\t\treturn (processor, cpuSpeedStr, ngettext(\"%d core\", \"%d cores\", cpuCount) % cpuCount, \"%s%s C\" % (temperature, degree))\n\t\t\t#return (\"%s %s MHz (%s) %s%sC\") % (processor, cpuSpeed, ngettext(\"%d core\", \"%d cores\", cpuCount) % cpuCount, temperature, degree)\n\t\treturn (processor, cpuSpeedStr, ngettext(\"%d core\", \"%d cores\", cpuCount) % cpuCount, \"\")\n\t\t#return (\"%s %s MHz (%s)\") % (processor, cpuSpeed, ngettext(\"%d core\", \"%d cores\", cpuCount) % cpuCount)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def doActivityTimer(self):\n\t\tif self.isSeekable():\n\t\t\tself.activity += 16\n\t\t\thdd = 1\n\t\t\tif self.activity >= 100:\n\t\t\t\tself.activity = 0\n\t\t\tBoxInfo.setMutableItem(\"SeekStatePlay\", True)\n\t\t\tif exists(\"/proc/stb/lcd/symbol_hdd\"):\n\t\t\t\tif config.lcd.hdd.value:\n\t\t\t\t\tfile = open(\"/proc/stb/lcd/symbol_hdd\", \"w\")\n\t\t\t\t\tfile.write(\"%d\" % int(hdd))\n\t\t\t\t\tfile.close()\n\t\t\tif exists(\"/proc/stb/lcd/symbol_hddprogress\"):\n\t\t\t\tif config.lcd.hdd.value:\n\t\t\t\t\tfile = open(\"/proc/stb/lcd/symbol_hddprogress\", \"w\")\n\t\t\t\t\tfile.write(\"%d\" % int(self.activity))\n\t\t\t\t\tfile.close()\n\t\telse:\n\t\t\tself.activityTimer.stop()\n\t\t\tself.activity = 0\n\t\t\thdd = 0\n\t\t\tself.seekAction = 0\n\t\tBoxInfo.setMutableItem(\"SeekStatePlay\", True)\n\t\tif exists(\"/proc/stb/lcd/symbol_hdd\"):\n\t\t\tif config.lcd.hdd.value:\n\t\t\t\tfile = open(\"/proc/stb/lcd/symbol_hdd\", \"w\")\n\t\t\t\tfile.write(\"%d\" % int(hdd))\n\t\t\t\tfile.close()\n\t\tif exists(\"/proc/stb/lcd/symbol_hddprogress\"):\n\t\t\tif config.lcd.hdd.value:\n\t\t\t\tfile = open(\"/proc/stb/lcd/symbol_hddprogress\", \"w\")\n\t\t\t\tfile.write(\"%d\" % int(self.activity))\n\t\t\t\tfile.close()\n\t\tif self.LastseekAction:\n\t\t\tself.DoSeekAction()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def list(\n self,\n request: fastapi.Request,\n scheduler_id: str | None = None,\n task_type: str | None = None,\n status: str | None = None,\n offset: int = 0,\n limit: int = 10,\n min_created_at: datetime.datetime | None = None,\n max_created_at: datetime.datetime | None = None,\n input_ooi: str | None = None, # FIXME: deprecated\n plugin_id: str | None = None, # FIXME: deprecated\n filters: storage.filters.FilterRequest | None = None,\n ) -> Any:\n if (min_created_at is not None and max_created_at is not None) and min_created_at > max_created_at:\n raise fastapi.HTTPException(\n status_code=fastapi.status.HTTP_400_BAD_REQUEST, detail=\"min_date must be less than max_date\"\n )\n\n # FIXME: deprecated; backwards compatibility for rocky that uses the\n # input_ooi and plugin_id parameters.\n f_req = filters or storage.filters.FilterRequest(filters={})\n if input_ooi is not None:\n if task_type == \"boefje\":\n f_ooi = {\n \"and\": [storage.filters.Filter(column=\"data\", field=\"input_ooi\", operator=\"eq\", value=input_ooi)]\n }\n elif task_type == \"normalizer\":\n f_ooi = {\n \"and\": [\n storage.filters.Filter(\n column=\"data\", field=\"raw_data__boefje_meta__input_ooi\", operator=\"eq\", value=input_ooi\n )\n ]\n }\n else:\n f_ooi = {\n \"or\": [\n storage.filters.Filter(column=\"data\", field=\"input_ooi\", operator=\"eq\", value=input_ooi),\n storage.filters.Filter(\n column=\"data\", field=\"raw_data__boefje_meta__input_ooi\", operator=\"eq\", value=input_ooi\n ),\n ]\n }\n\n f_req.filters.update(f_ooi) # type: ignore\n\n if plugin_id is not None:\n if task_type == \"boefje\":\n f_plugin = {\n \"and\": [storage.filters.Filter(column=\"data\", field=\"boefje__id\", operator=\"eq\", value=plugin_id)]\n }\n elif task_type == \"normalizer\":\n f_plugin = {\n \"and\": [\n storage.filters.Filter(column=\"data\", field=\"normalizer__id\", operator=\"eq\", value=plugin_id)\n ]\n }\n else:\n f_plugin = {\n \"or\": [\n storage.filters.Filter(column=\"data\", field=\"boefje__id\", operator=\"eq\", value=plugin_id),\n storage.filters.Filter(column=\"data\", field=\"normalizer__id\", operator=\"eq\", value=plugin_id),\n ]\n }\n\n f_req.filters.update(f_plugin) # type: ignore\n\n try:\n results, count = self.ctx.datastores.task_store.get_tasks(\n scheduler_id=scheduler_id,\n task_type=task_type,\n status=status,\n offset=offset,\n limit=limit,\n min_created_at=min_created_at,\n max_created_at=max_created_at,\n filters=f_req,\n )\n except storage.filters.errors.FilterError as exc:\n raise fastapi.HTTPException(\n status_code=fastapi.status.HTTP_400_BAD_REQUEST, detail=f\"invalid filter(s) [exception: {exc}]\"\n ) from exc\n except storage.errors.StorageError as exc:\n self.logger.exception(exc)\n raise fastapi.HTTPException(\n status_code=fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=f\"error occurred while accessing the database [exception: {exc}]\",\n ) from exc\n except Exception as exc:\n self.logger.exception(exc)\n raise fastapi.HTTPException(\n status_code=fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR, detail=\"failed to get tasks\"\n ) from exc\n\n return utils.paginate(request, results, count, offset, limit)", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def gen_func_item(\n builder: IRBuilder,\n fitem: FuncItem,\n name: str,\n sig: FuncSignature,\n cdef: ClassDef | None = None,\n) -> tuple[FuncIR, Value | None]:\n \"\"\"Generate and return the FuncIR for a given FuncDef.\n\n If the given FuncItem is a nested function, then we generate a\n callable class representing the function and use that instead of\n the actual function. if the given FuncItem contains a nested\n function, then we generate an environment class so that inner\n nested functions can access the environment of the given FuncDef.\n\n Consider the following nested function:\n\n def a() -> None:\n def b() -> None:\n def c() -> None:\n return None\n return None\n return None\n\n The classes generated would look something like the following.\n\n has pointer to +-------+\n +--------------------------> | a_env |\n | +-------+\n | ^\n | | has pointer to\n +-------+ associated with +-------+\n | b_obj | -------------------> | b_env |\n +-------+ +-------+\n ^\n |\n +-------+ has pointer to |\n | c_obj | --------------------------+\n +-------+\n \"\"\"\n\n # TODO: do something about abstract methods.\n\n func_reg: Value | None = None\n\n # We treat lambdas as always being nested because we always generate\n # a class for lambdas, no matter where they are. (It would probably also\n # work to special case toplevel lambdas and generate a non-class function.)\n is_nested = fitem in builder.nested_fitems or isinstance(fitem, LambdaExpr)\n contains_nested = fitem in builder.encapsulating_funcs.keys()\n is_decorated = fitem in builder.fdefs_to_decorators\n is_singledispatch = fitem in builder.singledispatch_impls\n in_non_ext = False\n add_nested_funcs_to_env = has_nested_func_self_reference(builder, fitem)\n class_name = None\n if cdef:\n ir = builder.mapper.type_to_ir[cdef.info]\n in_non_ext = not ir.is_ext_class\n class_name = cdef.name\n\n if is_singledispatch:\n func_name = singledispatch_main_func_name(name)\n else:\n func_name = name\n builder.enter(\n FuncInfo(\n fitem=fitem,\n name=func_name,\n class_name=class_name,\n namespace=gen_func_ns(builder),\n is_nested=is_nested,\n contains_nested=contains_nested,\n is_decorated=is_decorated,\n in_non_ext=in_non_ext,\n add_nested_funcs_to_env=add_nested_funcs_to_env,\n )\n )\n\n # Functions that contain nested functions need an environment class to store variables that\n # are free in their nested functions. Generator functions need an environment class to\n # store a variable denoting the next instruction to be executed when the __next__ function\n # is called, along with all the variables inside the function itself.\n if builder.fn_info.contains_nested or builder.fn_info.is_generator:\n setup_env_class(builder)\n\n if builder.fn_info.is_nested or builder.fn_info.in_non_ext:\n setup_callable_class(builder)\n\n if builder.fn_info.is_generator:\n # Do a first-pass and generate a function that just returns a generator object.\n gen_generator_func(builder)\n args, _, blocks, ret_type, fn_info = builder.leave()\n func_ir, func_reg = gen_func_ir(\n builder, args, blocks, sig, fn_info, cdef, is_singledispatch\n )\n\n # Re-enter the FuncItem and visit the body of the function this time.\n builder.enter(fn_info)\n setup_env_for_generator_class(builder)\n load_outer_envs(builder, builder.fn_info.generator_class)\n top_level = builder.top_level_fn_info()\n if (\n builder.fn_info.is_nested\n and isinstance(fitem, FuncDef)\n and top_level\n and top_level.add_nested_funcs_to_env\n ):\n setup_func_for_recursive_call(builder, fitem, builder.fn_info.generator_class)\n create_switch_for_generator_class(builder)\n add_raise_exception_blocks_to_generator_class(builder, fitem.line)\n else:\n load_env_registers(builder)\n gen_arg_defaults(builder)\n\n if builder.fn_info.contains_nested and not builder.fn_info.is_generator:\n finalize_env_class(builder)\n\n builder.ret_types[-1] = sig.ret_type\n\n # Add all variables and functions that are declared/defined within this\n # function and are referenced in functions nested within this one to this\n # function's environment class so the nested functions can reference\n # them even if they are declared after the nested function's definition.\n # Note that this is done before visiting the body of this function.\n\n env_for_func: FuncInfo | ImplicitClass = builder.fn_info\n if builder.fn_info.is_generator:\n env_for_func = builder.fn_info.generator_class\n elif builder.fn_info.is_nested or builder.fn_info.in_non_ext:\n env_for_func = builder.fn_info.callable_class\n\n if builder.fn_info.fitem in builder.free_variables:\n # Sort the variables to keep things deterministic\n for var in sorted(builder.free_variables[builder.fn_info.fitem], key=lambda x: x.name):\n if isinstance(var, Var):\n rtype = builder.type_to_rtype(var.type)\n builder.add_var_to_env_class(var, rtype, env_for_func, reassign=False)\n\n if builder.fn_info.fitem in builder.encapsulating_funcs:\n for nested_fn in builder.encapsulating_funcs[builder.fn_info.fitem]:\n if isinstance(nested_fn, FuncDef):\n # The return type is 'object' instead of an RInstance of the\n # callable class because differently defined functions with\n # the same name and signature across conditional blocks\n # will generate different callable classes, so the callable\n # class that gets instantiated must be generic.\n builder.add_var_to_env_class(\n nested_fn, object_rprimitive, env_for_func, reassign=False\n )\n\n builder.accept(fitem.body)\n builder.maybe_add_implicit_return()\n\n if builder.fn_info.is_generator:\n populate_switch_for_generator_class(builder)\n\n # Hang on to the local symbol table for a while, since we use it\n # to calculate argument defaults below.\n symtable = builder.symtables[-1]\n\n args, _, blocks, ret_type, fn_info = builder.leave()\n\n if fn_info.is_generator:\n add_methods_to_generator_class(builder, fn_info, sig, args, blocks, fitem.is_coroutine)\n else:\n func_ir, func_reg = gen_func_ir(\n builder, args, blocks, sig, fn_info, cdef, is_singledispatch\n )\n\n # Evaluate argument defaults in the surrounding scope, since we\n # calculate them *once* when the function definition is evaluated.\n calculate_arg_defaults(builder, fn_info, func_reg, symtable)\n\n if is_singledispatch:\n # add the generated main singledispatch function\n builder.functions.append(func_ir)\n # create the dispatch function\n assert isinstance(fitem, FuncDef)\n return gen_dispatch_func_ir(builder, fitem, fn_info.name, name, sig)\n\n return func_ir, func_reg", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def migrate_to_version_11_6(json_flow, flow=None):\n \"\"\"\n Versions before 11.6 maintained uuid mismatches on imported flows. This updates\n the flow definition with accurate group uuids\n \"\"\"\n\n # this migration only matters for existing flows\n if not flow:\n return json_flow\n\n # only look up group once per flow migration\n uuid_map = {}\n\n def remap_group(group):\n if type(group) is dict:\n # we haven't been mapped yet (also, non-uuid groups can't be mapped)\n if \"uuid\" not in group or group[\"uuid\"] not in uuid_map and group.get(\"name\"):\n group_instance = ContactGroup.get_user_group_by_name(flow.org, group[\"name\"])\n if group_instance:\n # map group references that started with a uuid\n if \"uuid\" in group:\n uuid_map[group[\"uuid\"]] = group_instance.uuid\n group[\"uuid\"] = group_instance.uuid\n\n # we were already mapped\n elif group[\"uuid\"] in uuid_map:\n group[\"uuid\"] = uuid_map[group[\"uuid\"]]\n\n for actionset in json_flow.get(\"action_sets\", []):\n for action in actionset[\"actions\"]:\n for group in action.get(\"groups\", []):\n remap_group(group)\n\n for ruleset in json_flow.get(\"rule_sets\", []):\n for rule in ruleset.get(\"rules\", []):\n if rule[\"test\"][\"type\"] == \"in_group\":\n group = rule[\"test\"][\"test\"]\n remap_group(group)\n\n return json_flow", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def cpython_tags(\n python_version: Optional[PythonVersion] = None,\n abis: Optional[Iterable[str]] = None,\n platforms: Optional[Iterable[str]] = None,\n *,\n warn: bool = False,\n) -> Iterator[Tag]:\n \"\"\"\n Yields the tags for a CPython interpreter.\n\n The tags consist of:\n - cp<python_version>-<abi>-<platform>\n - cp<python_version>-abi3-<platform>\n - cp<python_version>-none-<platform>\n - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.\n\n If python_version only specifies a major version then user-provided ABIs and\n the 'none' ABItag will be used.\n\n If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n their normal position and not at the beginning.\n \"\"\"\n if not python_version:\n python_version = sys.version_info[:2]\n\n interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n if abis is None:\n if len(python_version) > 1:\n abis = _cpython_abis(python_version, warn)\n else:\n abis = []\n abis = list(abis)\n # 'abi3' and 'none' are explicitly handled later.\n for explicit_abi in (\"abi3\", \"none\"):\n try:\n abis.remove(explicit_abi)\n except ValueError:\n pass\n\n platforms = list(platforms or platform_tags())\n for abi in abis:\n for platform_ in platforms:\n yield Tag(interpreter, abi, platform_)\n if _abi3_applies(python_version):\n yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n if _abi3_applies(python_version):\n for minor_version in range(python_version[1] - 1, 1, -1):\n for platform_ in platforms:\n interpreter = \"cp{version}\".format(\n version=_version_nodot((python_version[0], minor_version))\n )\n yield Tag(interpreter, \"abi3\", platform_)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def __init__(self, session, parentMenu):\n\t\tself.session = session\n\t\tself.parentMenu = parentMenu\n\t\tScreen.__init__(self, session, enableHelp=True)\n\t\tself.menuList = []\n\t\tself[\"menu\"] = List(self.menuList)\n\t\tself[\"menu\"].onSelectionChanged.append(self.selectionChanged)\n\t\tself[\"menuimage\"] = Pixmap()\n\t\tself[\"description\"] = StaticText()\n\t\tself[\"key_menu\"] = StaticText(_(\"MENU\"))\n\t\tself[\"key_red\"] = StaticText(_(\"Exit\"))\n\t\tself[\"key_green\"] = StaticText()\n\t\tself[\"key_yellow\"] = StaticText()\n\t\tself[\"key_blue\"] = StaticText()\n\t\tmenuImageLibrary = resolveFilename(SCOPE_GUISKIN, \"mainmenu\")\n\t\tself.menuImageLibrary = menuImageLibrary if isdir(menuImageLibrary) else None\n\t\tself.showNumericHelp = False\n\t\tself.sortMode = False\n\t\tself.selectedEntry = None\n\t\tself.subMenuSort = None\n\t\tself.createMenuList()\n\t\tProtectedScreen.__init__(self) # ProtectedScreen needs self.menuID\n\t\t# For the skin: first try a menu_<menuID>, then Menu.\n\t\tself.skinName = []\n\t\tif self.menuID is not None:\n\t\t\tif config.usage.menuType.value == \"horzanim\" and findSkinScreen(\"Animmain\"):\n\t\t\t\tself.skinName.append(\"Animmain\")\n\t\t\telif config.usage.menuType.value == \"horzicon\" and findSkinScreen(\"Iconmain\"):\n\t\t\t\tself.skinName.append(\"Iconmain\")\n\t\t\telse:\n\t\t\t\tself.skinName.append(f\"Menu{self.menuID}\")\n\t\t\t\tself.skinName.append(f\"menu_{self.menuID}\")\n\t\tself.skinName.append(\"Menu\")\n\t\tif config.usage.menuType.value == \"horzanim\" and findSkinScreen(\"Animmain\"):\n\t\t\tself.onShown.append(self.openTestA)\n\t\telif config.usage.menuType.value == \"horzicon\" and findSkinScreen(\"Iconmain\"):\n\t\t\tself.onShown.append(self.openTestB)\n\t\tself[\"menuActions\"] = HelpableNumberActionMap(self, [\"OkCancelActions\", \"MenuActions\", \"ColorActions\", \"NumberActions\", \"TextActions\"], {\n\t\t\t\"ok\": (self.okbuttonClick, _(\"Select the current menu item\")),\n\t\t\t\"cancel\": (self.closeNonRecursive, _(\"Exit menu\")),\n\t\t\t\"close\": (self.closeRecursive, _(\"Exit all menus\")),\n\t\t\t\"menu\": (self.keySetupMenu, _(\"Change OSD Settings\")),\n\t\t\t\"red\": (self.closeNonRecursive, _(\"Exit menu\")),\n\t\t\t\"1\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"2\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"3\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"4\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"5\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"6\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"7\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"8\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"9\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"0\": (self.keyNumberGlobal, _(\"Direct menu item selection\")),\n\t\t\t\"textlong\": (self.keyText, _(\"Switch to 720p video\"))\n\t\t}, prio=0, description=_(\"Menu Common Actions\"))\n\t\tself[\"navigationActions\"] = HelpableActionMap(self, [\"NavigationActions\"], {\n\t\t\t\"top\": (self.keyTop, _(\"Move to first line / screen\")),\n\t\t\t\"pageUp\": (self.keyPageUp, _(\"Move up a screen\")),\n\t\t\t\"up\": (self.keyUp, _(\"Move up a line\")),\n\t\t\t# \"first\": (self.keyFirst, _(\"Jump to first item in list or the start of text\")),\n\t\t\t# \"last\": (self.keyLast, _(\"Jump to last item in list or the end of text\")),\n\t\t\t\"down\": (self.keyDown, _(\"Move down a line\")),\n\t\t\t\"pageDown\": (self.keyPageDown, _(\"Move down a screen\")),\n\t\t\t\"bottom\": (self.keyBottom, _(\"Move to last line / screen\"))\n\t\t}, prio=-1, description=_(\"Menu Navigation Actions\"))\n\t\tif config.usage.menuSortOrder.value == \"user\":\n\t\t\tself[\"editActions\"] = HelpableActionMap(self, [\"ColorActions\"], {\n\t\t\t\t\"green\": (self.keyGreen, _(\"Toggle item move mode on/off\")),\n\t\t\t\t\"yellow\": (self.keyYellow, _(\"Toggle hide/show of the current item\")),\n\t\t\t\t\"blue\": (self.toggleSortMode, _(\"Toggle item edit mode on/off\"))\n\t\t\t}, prio=0, description=_(\"Menu Edit Actions\"))\n\t\ttitle = parentMenu.get(\"title\", \"\") or None\n\t\ttitle = title and _(title)\n\t\tif title is None:\n\t\t\ttitle = _(parentMenu.get(\"text\", \"\"))\n\t\tself.setTitle(title)\n\t\tself.number = 0\n\t\tself.nextNumberTimer = eTimer()\n\t\tself.nextNumberTimer.callback.append(self.okbuttonClick)\n\t\tif len(self.menuList) == 1: # Does this menu have only one item, if so just run that item.\n\t\t\tself.onExecBegin.append(self.singleItemMenu)\n\t\tself.onLayoutFinish.append(self.layoutFinished)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def check_argument_types(\n self,\n arg_types: list[Type],\n arg_kinds: list[ArgKind],\n args: list[Expression],\n callee: CallableType,\n formal_to_actual: list[list[int]],\n context: Context,\n check_arg: ArgChecker | None = None,\n object_type: Type | None = None,\n ) -> None:\n \"\"\"Check argument types against a callable type.\n\n Report errors if the argument types are not compatible.\n\n The check_call docstring describes some of the arguments.\n \"\"\"\n check_arg = check_arg or self.check_arg\n # Keep track of consumed tuple *arg items.\n mapper = ArgTypeExpander(self.argument_infer_context())\n for i, actuals in enumerate(formal_to_actual):\n orig_callee_arg_type = get_proper_type(callee.arg_types[i])\n\n # Checking the case that we have more than one item but the first argument\n # is an unpack, so this would be something like:\n # [Tuple[Unpack[Ts]], int]\n #\n # In this case we have to check everything together, we do this by re-unifying\n # the suffices to the tuple, e.g. a single actual like\n # Tuple[Unpack[Ts], int]\n expanded_tuple = False\n actual_kinds = [arg_kinds[a] for a in actuals]\n if len(actuals) > 1:\n p_actual_type = get_proper_type(arg_types[actuals[0]])\n if (\n isinstance(p_actual_type, TupleType)\n and len(p_actual_type.items) == 1\n and isinstance(p_actual_type.items[0], UnpackType)\n and actual_kinds == [nodes.ARG_STAR] + [nodes.ARG_POS] * (len(actuals) - 1)\n ):\n actual_types = [p_actual_type.items[0]] + [arg_types[a] for a in actuals[1:]]\n if isinstance(orig_callee_arg_type, UnpackType):\n p_callee_type = get_proper_type(orig_callee_arg_type.type)\n if isinstance(p_callee_type, TupleType):\n assert p_callee_type.items\n callee_arg_types = p_callee_type.items\n callee_arg_kinds = [nodes.ARG_STAR] + [nodes.ARG_POS] * (\n len(p_callee_type.items) - 1\n )\n expanded_tuple = True\n\n if not expanded_tuple:\n actual_types = [arg_types[a] for a in actuals]\n if isinstance(orig_callee_arg_type, UnpackType):\n unpacked_type = get_proper_type(orig_callee_arg_type.type)\n if isinstance(unpacked_type, TupleType):\n inner_unpack_index = find_unpack_in_list(unpacked_type.items)\n if inner_unpack_index is None:\n callee_arg_types = unpacked_type.items\n callee_arg_kinds = [ARG_POS] * len(actuals)\n else:\n inner_unpack = unpacked_type.items[inner_unpack_index]\n assert isinstance(inner_unpack, UnpackType)\n inner_unpacked_type = get_proper_type(inner_unpack.type)\n if isinstance(inner_unpacked_type, TypeVarTupleType):\n # This branch mimics the expanded_tuple case above but for\n # the case where caller passed a single * unpacked tuple argument.\n callee_arg_types = unpacked_type.items\n callee_arg_kinds = [\n ARG_POS if i != inner_unpack_index else ARG_STAR\n for i in range(len(unpacked_type.items))\n ]\n else:\n # We assume heterogeneous tuples are desugared earlier.\n assert isinstance(inner_unpacked_type, Instance)\n assert inner_unpacked_type.type.fullname == \"builtins.tuple\"\n callee_arg_types = (\n unpacked_type.items[:inner_unpack_index]\n + [inner_unpacked_type.args[0]]\n * (len(actuals) - len(unpacked_type.items) + 1)\n + unpacked_type.items[inner_unpack_index + 1 :]\n )\n callee_arg_kinds = [ARG_POS] * len(actuals)\n elif isinstance(unpacked_type, TypeVarTupleType):\n callee_arg_types = [orig_callee_arg_type]\n callee_arg_kinds = [ARG_STAR]\n else:\n assert isinstance(unpacked_type, Instance)\n assert unpacked_type.type.fullname == \"builtins.tuple\"\n callee_arg_types = [unpacked_type.args[0]] * len(actuals)\n callee_arg_kinds = [ARG_POS] * len(actuals)\n else:\n callee_arg_types = [orig_callee_arg_type] * len(actuals)\n callee_arg_kinds = [callee.arg_kinds[i]] * len(actuals)\n\n assert len(actual_types) == len(actuals) == len(actual_kinds)\n\n if len(callee_arg_types) != len(actual_types):\n if len(actual_types) > len(callee_arg_types):\n self.chk.msg.too_many_arguments(callee, context)\n else:\n self.chk.msg.too_few_arguments(callee, context, None)\n continue\n\n assert len(callee_arg_types) == len(actual_types)\n assert len(callee_arg_types) == len(callee_arg_kinds)\n for actual, actual_type, actual_kind, callee_arg_type, callee_arg_kind in zip(\n actuals, actual_types, actual_kinds, callee_arg_types, callee_arg_kinds\n ):\n if actual_type is None:\n continue # Some kind of error was already reported.\n # Check that a *arg is valid as varargs.\n if actual_kind == nodes.ARG_STAR and not self.is_valid_var_arg(actual_type):\n self.msg.invalid_var_arg(actual_type, context)\n if actual_kind == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(\n actual_type\n ):\n is_mapping = is_subtype(\n actual_type, self.chk.named_type(\"_typeshed.SupportsKeysAndGetItem\")\n )\n self.msg.invalid_keyword_var_arg(actual_type, is_mapping, context)\n expanded_actual = mapper.expand_actual_type(\n actual_type,\n actual_kind,\n callee.arg_names[i],\n callee_arg_kind,\n allow_unpack=isinstance(callee_arg_type, UnpackType),\n )\n check_arg(\n expanded_actual,\n actual_type,\n actual_kind,\n callee_arg_type,\n actual + 1,\n i + 1,\n callee,\n object_type,\n args[actual],\n context,\n )", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@property\n def size(self) -> ConsoleDimensions:\n \"\"\"Get the size of the console.\n\n Returns:\n ConsoleDimensions: A named tuple containing the dimensions.\n \"\"\"\n\n if self._width is not None and self._height is not None:\n return ConsoleDimensions(self._width - self.legacy_windows, self._height)\n\n if self.is_dumb_terminal:\n return ConsoleDimensions(80, 25)\n\n width: Optional[int] = None\n height: Optional[int] = None\n\n if WINDOWS: # pragma: no cover\n try:\n width, height = os.get_terminal_size()\n except (AttributeError, ValueError, OSError): # Probably not a terminal\n pass\n else:\n for file_descriptor in _STD_STREAMS:\n try:\n width, height = os.get_terminal_size(file_descriptor)\n except (AttributeError, ValueError, OSError):\n pass\n else:\n break\n\n columns = self._environ.get(\"COLUMNS\")\n if columns is not None and columns.isdigit():\n width = int(columns)\n lines = self._environ.get(\"LINES\")\n if lines is not None and lines.isdigit():\n height = int(lines)\n\n # get_terminal_size can report 0, 0 if run from pseudo-terminal\n width = width or 80\n height = height or 25\n return ConsoleDimensions(\n width - self.legacy_windows if self._width is None else self._width,\n height if self._height is None else self._height,\n )", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def report_error_to_rollbar(\n request=None,\n message=None,\n auth=None,\n file=None,\n extra_data=None,\n exception=None):\n ROLLBAR = getattr(settings, 'ROLLBAR', {})\n if ROLLBAR:\n data = extra_data or {}\n contributor_id_msg = ''\n is_api_user_msg = ''\n if request:\n data['fingerprint'] = data['user_id'] = \\\n getattr(request.user, 'id', None)\n data['contributor_id'] = getattr(getattr(\n request.user, 'contributor', None), 'id', None)\n data['is_api_user'] = getattr(request.user, 'has_groups', False)\n if data[\"contributor_id\"]:\n contributor_id_msg = (\n f' (contributor id {data[\"contributor_id\"]})'\n )\n if data['is_api_user']:\n is_api_user_msg = 'API '\n if file:\n data['file_name'] = file.name\n if auth:\n data['auth'] = auth\n if message:\n rollbar.report_message(message, level='error', extra_data=data)\n elif exception:\n modified_message = (\n f\"{is_api_user_msg}User error{contributor_id_msg}: {exception}\"\n )\n data['fingerprint'] = (\n str(data['fingerprint']) + '-' + str(modified_message)\n )\n new_exception = Exception(modified_message)\n rollbar.report_exc_info(\n (type(new_exception), new_exception, sys.exc_info()[2]),\n extra_data=data\n )\n else:\n rollbar.report_exc_info(sys.exc_info(), extra_data=data)", "smellKey": "S3776", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def validate_and_remap(self, shapes: List[models.LabeledShapeRequest], ds_frame: int) -> None:\n new_shapes = []\n\n for shape in shapes:\n if hasattr(shape, \"id\"):\n raise BadFunctionError(\"function output shape with preset id\")\n\n if hasattr(shape, \"source\"):\n raise BadFunctionError(\"function output shape with preset source\")\n shape.source = \"auto\"\n\n if shape.frame != 0:\n raise BadFunctionError(\n f\"function output shape with unexpected frame number ({shape.frame})\"\n )\n\n shape.frame = ds_frame\n\n try:\n mapped_label = self._label_mapping[shape.label_id]\n except KeyError:\n raise BadFunctionError(\n f\"function output shape with unknown label ID ({shape.label_id})\"\n )\n\n if not mapped_label:\n continue\n\n shape.label_id = mapped_label.id\n\n if getattr(shape, \"attributes\", None):\n raise BadFunctionError(\n \"function output shape with attributes, which is not yet supported\"\n )\n\n new_shapes.append(shape)\n\n if shape.type.value == \"skeleton\":\n new_elements = []\n seen_sl_ids = set()\n\n for element in shape.elements:\n if hasattr(element, \"id\"):\n raise BadFunctionError(\"function output shape element with preset id\")\n\n if hasattr(element, \"source\"):\n raise BadFunctionError(\"function output shape element with preset source\")\n element.source = \"auto\"\n\n if element.frame != 0:\n raise BadFunctionError(\n f\"function output shape element with unexpected frame number ({element.frame})\"\n )\n\n element.frame = ds_frame\n\n if element.type.value != \"points\":\n raise BadFunctionError(\n f\"function output skeleton with element type other than 'points' ({element.type.value})\"\n )\n\n try:\n mapped_sl_id = mapped_label.sublabel_mapping[element.label_id]\n except KeyError:\n raise BadFunctionError(\n f\"function output shape with unknown sublabel ID ({element.label_id})\"\n )\n\n if not mapped_sl_id:\n continue\n\n if mapped_sl_id in seen_sl_ids:\n raise BadFunctionError(\n \"function output skeleton with multiple elements with same sublabel\"\n )\n\n element.label_id = mapped_sl_id\n\n seen_sl_ids.add(mapped_sl_id)\n\n new_elements.append(element)\n\n if len(new_elements) != mapped_label.expected_num_elements:\n # new_elements could only be shorter than expected,\n # because the reverse would imply that there are more distinct sublabel IDs\n # than are actually defined in the dataset.\n assert len(new_elements) < mapped_label.expected_num_elements\n\n raise BadFunctionError(\n f\"function output skeleton with fewer elements than expected ({len(new_elements)} vs {mapped_label.expected_num_elements})\"\n )\n\n shape.elements[:] = new_elements\n else:\n if getattr(shape, \"elements\", None):\n raise BadFunctionError(\"function output non-skeleton shape with elements\")\n\n shapes[:] = new_shapes", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def get_feed(self, obj, request):\n \"\"\"\n Return a feedgenerator.DefaultFeed object, fully populated, for\n this feed. Raise FeedDoesNotExist for invalid parameters.\n \"\"\"\n current_site = get_current_site(request)\n\n link = self._get_dynamic_attr(\"link\", obj)\n link = add_domain(current_site.domain, link, request.is_secure())\n\n feed = self.feed_type(\n title=self._get_dynamic_attr(\"title\", obj),\n subtitle=self._get_dynamic_attr(\"subtitle\", obj),\n link=link,\n description=self._get_dynamic_attr(\"description\", obj),\n language=self.language or get_language(),\n feed_url=add_domain(\n current_site.domain,\n self._get_dynamic_attr(\"feed_url\", obj) or request.path,\n request.is_secure(),\n ),\n author_name=self._get_dynamic_attr(\"author_name\", obj),\n author_link=self._get_dynamic_attr(\"author_link\", obj),\n author_email=self._get_dynamic_attr(\"author_email\", obj),\n categories=self._get_dynamic_attr(\"categories\", obj),\n feed_copyright=self._get_dynamic_attr(\"feed_copyright\", obj),\n feed_guid=self._get_dynamic_attr(\"feed_guid\", obj),\n ttl=self._get_dynamic_attr(\"ttl\", obj),\n stylesheets=self._get_dynamic_attr(\"stylesheets\", obj),\n **self.feed_extra_kwargs(obj),\n )\n\n title_tmp = None\n if self.title_template is not None:\n try:\n title_tmp = loader.get_template(self.title_template)\n except TemplateDoesNotExist:\n pass\n\n description_tmp = None\n if self.description_template is not None:\n try:\n description_tmp = loader.get_template(self.description_template)\n except TemplateDoesNotExist:\n pass\n\n for item in self._get_dynamic_attr(\"items\", obj):\n context = self.get_context_data(\n item=item, site=current_site, obj=obj, request=request\n )\n if title_tmp is not None:\n title = title_tmp.render(context, request)\n else:\n title = self._get_dynamic_attr(\"item_title\", item)\n if description_tmp is not None:\n description = description_tmp.render(context, request)\n else:\n description = self._get_dynamic_attr(\"item_description\", item)\n link = add_domain(\n current_site.domain,\n self._get_dynamic_attr(\"item_link\", item),\n request.is_secure(),\n )\n enclosures = self._get_dynamic_attr(\"item_enclosures\", item)\n author_name = self._get_dynamic_attr(\"item_author_name\", item)\n if author_name is not None:\n author_email = self._get_dynamic_attr(\"item_author_email\", item)\n author_link = self._get_dynamic_attr(\"item_author_link\", item)\n else:\n author_email = author_link = None\n\n tz = get_default_timezone()\n\n pubdate = self._get_dynamic_attr(\"item_pubdate\", item)\n if pubdate and is_naive(pubdate):\n pubdate = make_aware(pubdate, tz)\n\n updateddate = self._get_dynamic_attr(\"item_updateddate\", item)\n if updateddate and is_naive(updateddate):\n updateddate = make_aware(updateddate, tz)\n\n feed.add_item(\n title=title,\n link=link,\n description=description,\n unique_id=self._get_dynamic_attr(\"item_guid\", item, link),\n unique_id_is_permalink=self._get_dynamic_attr(\n \"item_guid_is_permalink\", item\n ),\n enclosures=enclosures,\n pubdate=pubdate,\n updateddate=updateddate,\n author_name=author_name,\n author_email=author_email,\n author_link=author_link,\n comments=self._get_dynamic_attr(\"item_comments\", item),\n categories=self._get_dynamic_attr(\"item_categories\", item),\n item_copyright=self._get_dynamic_attr(\"item_copyright\", item),\n **self.item_extra_kwargs(item),\n )\n return feed", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(self, args):\n\t\tConverter.__init__(self, args)\n\t\targs = [x.strip() for x in args.split(\",\")]\n\t\tself.argError = False\n\t\tself.checkSourceBoolean = False\n\t\tself.checkInvertSourceBoolean = False\n\t\tself.invert = False\n\t\tself.ignore = False\n\t\tself.configKey = None\n\t\tself.configValue = None\n\t\tif len(args) < 2:\n\t\t\tself.argError = True\n\t\telse:\n\t\t\tif \"config.\" in args[0]:\n\t\t\t\tself.configKey = args[0]\n\t\t\t\tself.configValue = args[1]\n\n\t\t\t\tdef checkArg(arg):\n\t\t\t\t\tif arg == \"Invert\":\n\t\t\t\t\t\tself.invert = True\n\t\t\t\t\telif arg == \"Ignore\":\n\t\t\t\t\t\tself.ignore = True\n\t\t\t\t\telif arg == \"CheckSourceBoolean\":\n\t\t\t\t\t\tself.checkSourceBoolean = True\n\t\t\t\t\telif arg == \"CheckInvertSourceBoolean\":\n\t\t\t\t\t\tself.checkInvertSourceBoolean = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.argError = True\n\n\t\t\t\tif len(args) > 2:\n\t\t\t\t\tcheckArg(args[2])\n\t\t\t\tif len(args) > 3:\n\t\t\t\t\tcheckArg(args[3])\n\t\t\t\tif len(args) > 4:\n\t\t\t\t\tcheckArg(args[4])\n\t\t\telse:\n\t\t\t\tself.argError = True\n\t\tif self.argError:\n\t\t\tprint(\"[ConfigEntryTest] Converter got incorrect arguments '%s'! The arg[0] must start with 'config.', arg[1] is the compare string, arg[2] - arg[4] are optional arguments and must be 'Invert', 'Ignore', 'CheckSourceBoolean' or 'CheckInvertSourceBoolean'.\" % str(args))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def PriestMemorizeSelectPress():\n\tglobal PriestMemorizeWindow, Learnable, PriestMemorizeTextArea, PriestMemorizeDoneButton, PriestMemorizePointsLeft\n\n\tPriestMemorized = GemRB.GetVar (\"PriestMemorized\")\n\tSpellMask = GemRB.GetVar (\"SpellMask\")\n\tSpell = abs(PriestMemorized - SpellMask)\n\n\ti = -1\n\twhile (Spell > 0):\n\t\ti = i + 1\n\t\tSpell = Spell >> 1\n\n\tSpell=GemRB.GetSpell (Learnable[i])\n\tPriestMemorizeTextArea.SetText (Spell[\"SpellDesc\"])\n\n\tif SpellMask < PriestMemorized:\n\t\tPriestMemorizePointsLeft = PriestMemorizePointsLeft + 1\n\t\tfor i in range (len(Learnable)):\n\t\t\tSpellButton = PriestMemorizeWindow.GetControl (i + 2)\n\t\t\tif (((1 << i) & SpellMask) == 0):\n\t\t\t\tSpellButton.SetState (IE_GUI_BUTTON_ENABLED)\n\t\tPriestMemorizeDoneButton.SetState (IE_GUI_BUTTON_DISABLED)\n\telse:\n\t\tPriestMemorizePointsLeft = PriestMemorizePointsLeft - 1\n\t\tif PriestMemorizePointsLeft == 0:\n\t\t\tfor i in range (len(Learnable)):\n\t\t\t\tSpellButton = PriestMemorizeWindow.GetControl (i + 2)\n\t\t\t\tif ((1 << i) & SpellMask) == 0:\n\t\t\t\t\tSpellButton.SetState (IE_GUI_BUTTON_DISABLED)\n\t\t\tPriestMemorizeDoneButton.SetState (IE_GUI_BUTTON_ENABLED)\n\n\tPointsLeftLabel = PriestMemorizeWindow.GetControl (0x1000001b)\n\tPointsLeftLabel.SetText (str(PriestMemorizePointsLeft))\n\tGemRB.SetVar (\"PriestMemorized\", SpellMask)\n\treturn", "smellKey": "S3776", "smellId": null, "repo": "gemrb_gemrb", "language": "python"} {"function": "def validate_instance(t: Instance, fail: MsgCallback, empty_tuple_index: bool) -> bool:\n \"\"\"Check if this is a well-formed instance with respect to argument count/positions.\"\"\"\n # TODO: combine logic with instantiate_type_alias().\n if any(unknown_unpack(a) for a in t.args):\n # This type is not ready to be validated, because of unknown total count.\n # TODO: is it OK to fill with TypeOfAny.from_error instead of special form?\n return False\n if t.type.has_type_var_tuple_type:\n min_tv_count = sum(\n not tv.has_default() and not isinstance(tv, TypeVarTupleType)\n for tv in t.type.defn.type_vars\n )\n correct = len(t.args) >= min_tv_count\n if any(\n isinstance(a, UnpackType) and isinstance(get_proper_type(a.type), Instance)\n for a in t.args\n ):\n correct = True\n if not t.args:\n if not (empty_tuple_index and len(t.type.type_vars) == 1):\n # The Any arguments should be set by the caller.\n if empty_tuple_index and min_tv_count:\n fail(\n f\"At least {min_tv_count} type argument(s) expected, none given\",\n t,\n code=codes.TYPE_ARG,\n )\n return False\n elif not correct:\n fail(\n f\"Bad number of arguments, expected: at least {min_tv_count}, given: {len(t.args)}\",\n t,\n code=codes.TYPE_ARG,\n )\n return False\n else:\n # We also need to check if we are not performing a type variable tuple split.\n unpack = find_unpack_in_list(t.args)\n if unpack is not None:\n unpack_arg = t.args[unpack]\n assert isinstance(unpack_arg, UnpackType)\n if isinstance(unpack_arg.type, TypeVarTupleType):\n assert t.type.type_var_tuple_prefix is not None\n assert t.type.type_var_tuple_suffix is not None\n exp_prefix = t.type.type_var_tuple_prefix\n act_prefix = unpack\n exp_suffix = t.type.type_var_tuple_suffix\n act_suffix = len(t.args) - unpack - 1\n if act_prefix < exp_prefix or act_suffix < exp_suffix:\n fail(\"TypeVarTuple cannot be split\", t, code=codes.TYPE_ARG)\n return False\n elif any(isinstance(a, UnpackType) for a in t.args):\n # A variadic unpack in fixed size instance (fixed unpacks must be flattened by the caller)\n fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)\n t.args = ()\n return False\n elif len(t.args) != len(t.type.type_vars):\n # Invalid number of type parameters.\n arg_count = len(t.args)\n min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)\n max_tv_count = len(t.type.type_vars)\n if arg_count and (arg_count < min_tv_count or arg_count > max_tv_count):\n fail(\n wrong_type_arg_count(min_tv_count, max_tv_count, str(arg_count), t.type.name),\n t,\n code=codes.TYPE_ARG,\n )\n t.invalid = True\n return False\n return True", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def resolve_top_event_conditions(\n self, top_events: list[dict[str, Any]], other: bool\n ) -> WhereType | None:\n \"\"\"Given a list of top events construct the conditions\"\"\"\n conditions = []\n for field in self.fields:\n # If we have a project field, we need to limit results by project so we don't hit the result limit\n if field in [\"project\", \"project.id\", \"project.name\"] and top_events:\n # Iterate through the existing conditions to find the project one\n # the project condition is a requirement of queries so there should always be one\n project_condition = [\n condition\n for condition in self.where\n if isinstance(condition, Condition)\n and condition.lhs == self.column(\"project_id\")\n ][0]\n self.where.remove(project_condition)\n if field in [\"project\", \"project.name\"]:\n projects = list(\n {self.params.project_slug_map[event[field]] for event in top_events}\n )\n else:\n projects = list({event[\"project.id\"] for event in top_events})\n\n if other:\n projects = list(set(self.params.project_ids) - set(projects))\n\n # if there are no more projects, we search on project id 0 to guarantee no results\n if not projects:\n projects = [0]\n\n self.where.append(Condition(self.column(\"project_id\"), Op.IN, projects))\n continue\n\n resolved_field = self.resolve_column(self.prefixed_to_tag_map.get(field, field))\n\n values: set[Any] = set()\n for event in top_events:\n if field in event:\n alias = field\n elif self.is_column_function(resolved_field) and resolved_field.alias in event:\n alias = resolved_field.alias\n else:\n continue\n\n # Note that because orderby shouldn't be an array field its not included in the values\n if isinstance(event.get(alias), list):\n continue\n else:\n values.add(event.get(alias))\n values_list = list(values)\n\n if values_list:\n if field == \"timestamp\" or field.startswith(\"timestamp.to_\"):\n if not other:\n # timestamp fields needs special handling, creating a big OR instead\n function, operator = Or, Op.EQ\n else:\n # Needs to be a big AND when negated\n function, operator = And, Op.NEQ\n if len(values_list) > 1:\n conditions.append(\n function(\n conditions=[\n Condition(resolved_field, operator, value)\n for value in sorted(values_list)\n ]\n )\n )\n else:\n conditions.append(Condition(resolved_field, operator, values_list[0]))\n elif None in values_list:\n # one of the values was null, but we can't do an in with null values, so split into two conditions\n non_none_values = [value for value in values_list if value is not None]\n null_condition = Condition(\n Function(\"isNull\", [resolved_field]), Op.EQ if not other else Op.NEQ, 1\n )\n if non_none_values:\n non_none_condition = Condition(\n resolved_field, Op.IN if not other else Op.NOT_IN, non_none_values\n )\n if not other:\n conditions.append(Or(conditions=[null_condition, non_none_condition]))\n else:\n conditions.append(And(conditions=[null_condition, non_none_condition]))\n else:\n conditions.append(null_condition)\n else:\n conditions.append(\n Condition(resolved_field, Op.IN if not other else Op.NOT_IN, values_list)\n )\n if len(conditions) > 1:\n final_function = And if not other else Or\n final_condition = final_function(conditions=conditions)\n elif len(conditions) == 1:\n final_condition = conditions[0]\n else:\n final_condition = None\n return final_condition", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@cached\n\tdef getText(self):\n\t\tif hasattr(self.source, 'text'):\n\t\t\tif 'nozero' in self.type:\n\t\t\t\treturn self.source.text.rjust(4)\n\t\t\telse:\n\t\t\t\treturn self.source.text.zfill(4)\n\t\tif self.showclock == 0:\n\t\t\tif self.delay:\n\t\t\t\tself.poll_interval = self.delay\n\t\t\t\tself.showclock = 1\n\t\t\tif self.num:\n\t\t\t\treturn self.num\n\t\telse:\n\t\t\tif self.showclock == 1:\n\t\t\t\tif 'noblink' in self.type:\n\t\t\t\t\tself.poll_interval = self.delay\n\t\t\t\telse:\n\t\t\t\t\tself.poll_interval = 1000\n\t\t\t\t\tself.showclock = 3\n\t\t\t\tclockformat = self.hour + '%02M'\n\t\t\telif self.showclock == 2:\n\t\t\t\tself.showclock = 3\n\t\t\t\tclockformat = self.hour + '%02M'\n\t\t\telse:\n\t\t\t\tself.showclock = 2\n\t\t\t\tclockformat = self.hour + ':%02M'\n\t\t\tif self.loop != -1:\n\t\t\t\tself.loop -= 1000\n\t\t\t\tif self.loop <= 0:\n\t\t\t\t\tself.loop = self.delay\n\t\t\t\t\tself.showclock = 0\n\t\t\treturn datetime.today().strftime(clockformat)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def turn_ptt(options):\n if options.limerfe_index is not None:\n limerfe_url = f\"{base_url}/featureset/feature/{options.limerfe_index}/actions\"\n if options.transmit:\n limerfe_payload_rx = {\n \"featureType\": \"LimeRFE\",\n \"LimeRFEActions\": {\n \"setRx\": 0\n }\n }\n r = requests.post(url=limerfe_url, json=limerfe_payload_rx) # switch off Rx\n print(f\"LimeRFE switch off Rx {r.status_code}\")\n else:\n limerfe_payload_tx = {\n \"featureType\": \"LimeRFE\",\n \"LimeRFEActions\": {\n \"setTx\": 0\n }\n }\n r = requests.post(url=limerfe_url, json=limerfe_payload_tx) # switch off Tx\n print(f\"LimeRFE switch off Tx {r.status_code}\")\n time.sleep(0.2)\n\n ptt_payload = {\n \"featureType\": \"SimplePTT\",\n \"SimplePTTActions\": {\n \"ptt\": 1 if options.transmit else 0\n }\n }\n ptt_url = f\"{base_url}/featureset/feature/{options.ptt_index}/actions\"\n r = requests.post(url=ptt_url, json=ptt_payload)\n print(f\"SimplePTT post action {r.status_code}\")\n\n if options.limerfe_index is not None:\n time.sleep(0.2)\n limerfe_url = f\"{base_url}/featureset/feature/{options.limerfe_index}/actions\"\n if options.transmit:\n limerfe_payload_tx = {\n \"featureType\": \"LimeRFE\",\n \"LimeRFEActions\": {\n \"setTx\": 1\n }\n }\n r = requests.post(url=limerfe_url, json=limerfe_payload_tx) # switch on Tx\n print(f\"LimeRFE switch on Tx {r.status_code}\")\n else:\n limerfe_payload_rx = {\n \"featureType\": \"LimeRFE\",\n \"LimeRFEActions\": {\n \"setRx\": 1\n }\n }\n for i in range(5):\n r = requests.post(url=limerfe_url, json=limerfe_payload_rx) # switch on Rx\n print(f\"LimeRFE switch on Rx {r.status_code}\")\n if r.status_code // 100 == 2:\n break\n time.sleep(0.5)", "smellKey": "S3776", "smellId": null, "repo": "f4exb_sdrangel", "language": "python"} {"function": "def MinMaxTestAndSet(self, inTestXyz):\n if self.mAllInitialized:\n if inTestXyz < self.mAllMin:\n self.mAllMin = inTestXyz\n else:\n if inTestXyz > self.mAllMax:\n self.mAllMax = inTestXyz\n else:\n self.mAllMin = inTestXyz\n self.mAllMax = inTestXyz\n self.mAllInitialized = True\n if self.mThisCbInitialized:\n if inTestXyz < self.mThisCbMin:\n self.mThisCbMin = inTestXyz\n else:\n if inTestXyz > self.mThisCbMax:\n self.mThisCbMax = inTestXyz\n else:\n self.mThisCbMin = inTestXyz\n self.mThisCbMax = inTestXyz\n self.mThisCbInitialized = True", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _map(prefix, child, parent, child_spec, spec_len_fn, require_controller):\n # Common code for mapping through <prefix>-map properties, e.g.\n # interrupt-map and gpio-map.\n #\n # prefix:\n # The prefix, e.g. \"interrupt\" or \"gpio\"\n #\n # child:\n # The \"sender\", e.g. the node with 'interrupts = <...>'\n #\n # parent:\n # The \"receiver\", e.g. a node with 'interrupt-map = <...>' or\n # 'interrupt-controller' (no mapping)\n #\n # child_spec:\n # The data associated with the interrupt/GPIO/etc., as a 'bytes' object,\n # e.g. <1 2> for 'foo-gpios = <&gpio1 1 2>'.\n #\n # spec_len_fn:\n # Function called on a parent specified in a *-map property to get the\n # length of the parent specifier (data after phandle in *-map), in cells\n #\n # require_controller:\n # If True, the final controller node after mapping is required to have\n # to have a <prefix>-controller property.\n\n map_prop = parent.props.get(prefix + \"-map\")\n if not map_prop:\n if require_controller and prefix + \"-controller\" not in parent.props:\n _err(\"expected '{}-controller' property on {!r} \"\n \"(referenced by {!r})\".format(prefix, parent, child))\n\n # No mapping\n return (parent, child_spec)\n\n masked_child_spec = _mask(prefix, child, parent, child_spec)\n\n raw = map_prop.value\n while raw:\n if len(raw) < len(child_spec):\n _err(\"bad value for {!r}, missing/truncated child data\"\n .format(map_prop))\n child_spec_entry = raw[:len(child_spec)]\n raw = raw[len(child_spec):]\n\n if len(raw) < 4:\n _err(\"bad value for {!r}, missing/truncated phandle\"\n .format(map_prop))\n phandle = to_num(raw[:4])\n raw = raw[4:]\n\n # Parent specified in *-map\n map_parent = parent.dt.phandle2node.get(phandle)\n if not map_parent:\n _err(\"bad phandle ({}) in {!r}\".format(phandle, map_prop))\n\n map_parent_spec_len = 4*spec_len_fn(map_parent)\n if len(raw) < map_parent_spec_len:\n _err(\"bad value for {!r}, missing/truncated parent data\"\n .format(map_prop))\n parent_spec = raw[:map_parent_spec_len]\n raw = raw[map_parent_spec_len:]\n\n # Got one *-map row. Check if it matches the child data.\n if child_spec_entry == masked_child_spec:\n # Handle *-map-pass-thru\n parent_spec = _pass_thru(\n prefix, child, parent, child_spec, parent_spec)\n\n # Found match. Recursively map and return it.\n return _map(prefix, parent, map_parent, parent_spec, spec_len_fn,\n require_controller)\n\n _err(\"child specifier for {!r} ({}) does not appear in {!r}\"\n .format(child, child_spec, map_prop))", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def insert_on(self, path, loc=None, replace=False): # noqa: C901\n \"\"\"Ensure self.location is on path\n\n If replace=False (default):\n - If location is already in path anywhere, do nothing.\n - Else:\n - If it's an egg and its parent directory is on path,\n insert just ahead of the parent.\n - Else: add to the end of path.\n If replace=True:\n - If location is already on path anywhere (not eggs)\n or higher priority than its parent (eggs)\n do nothing.\n - Else:\n - If it's an egg and its parent directory is on path,\n insert just ahead of the parent,\n removing any lower-priority entries.\n - Else: add it to the front of path.\n \"\"\"\n\n loc = loc or self.location\n if not loc:\n return\n\n nloc = _normalize_cached(loc)\n bdir = os.path.dirname(nloc)\n npath = [(p and _normalize_cached(p) or p) for p in path]\n\n for p, item in enumerate(npath):\n if item == nloc:\n if replace:\n break\n else:\n # don't modify path (even removing duplicates) if\n # found and not replace\n return\n elif item == bdir and self.precedence == EGG_DIST:\n # if it's an .egg, give it precedence over its directory\n # UNLESS it's already been added to sys.path and replace=False\n if (not replace) and nloc in npath[p:]:\n return\n if path is sys.path:\n self.check_version_conflict()\n path.insert(p, loc)\n npath.insert(p, nloc)\n break\n else:\n if path is sys.path:\n self.check_version_conflict()\n if replace:\n path.insert(0, loc)\n else:\n path.append(loc)\n return\n\n # p is the spot where we found or inserted loc; now remove duplicates\n while True:\n try:\n np = npath.index(nloc, p + 1)\n except ValueError:\n break\n else:\n del npath[np], path[np]\n # ha!\n p = np\n\n return", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def integrator_properties():\n s = h.Section()\n s.insert(\"pas\")\n s.e_pas = 0\n s.g_pas = 0.001\n cv.active(1)\n vvec = h.Vector()\n tvec = h.Vector()\n vvec.record(s(0.5)._ref_v, sec=s)\n tvec.record(h._ref_t, sec=s)\n\n # rtol and atol\n def run1(key):\n h.finitialize(0.001)\n cv.solve(2)\n chk(key + \" tvec\", tvec, tol=5e-10)\n chk(key + \" vvec\", vvec, tol=1e-9)\n\n cv.rtol(1e-3)\n cv.atol(0)\n run1(\"rtol=%g atol=%g\" % (cv.rtol(), cv.atol()))\n cv.rtol(0)\n cv.atol(1e-3)\n run1(\"rtol=%g atol=%g\" % (cv.rtol(), cv.atol()))\n del s\n\n net = Net(2)\n vvec.record(net.cells[0].soma(0.5)._ref_v, sec=net.cells[0].soma)\n tvec.record(h._ref_t, sec=net.cells[0].soma)\n\n # stiff\n def run2(key):\n h.finitialize(-65)\n cv.solve(2)\n # Note the very large tolerance, this seems relatively unstable with the\n # NVIDIA compilers\n chk(key + \" tvec size\", tvec.size(), tol=0.25)\n\n cv.use_local_dt(1)\n cv.stiff(0)\n run2(\"stiff=0 lvardt\")\n cv.stiff(2)\n cv.use_local_dt(0)\n for stiff in range(3):\n cv.stiff(stiff)\n run2(\"stiff=%d\" % (cv.stiff(),))\n\n # maxorder, minstep, maxstep\n for lvardt in [1, 0]:\n cv.use_local_dt(lvardt)\n for maxorder in [2, 5]:\n cv.maxorder(maxorder)\n assert cv.maxorder() == maxorder\n h.finitialize(-65)\n while h.t < 2.0:\n cv.solve()\n order = cv.order(0) if lvardt else cv.order()\n assert order <= maxorder\n for minstep in [0.0001, 0.0]:\n cv.minstep(minstep)\n assert cv.minstep() == minstep\n for maxstep in [0.5, 1e9]:\n cv.maxstep(maxstep)\n assert cv.maxstep() == maxstep\n\n # jacobian\n for jac in [2, 1, 0]: # end up as default\n cv.jacobian(jac)\n run2(\"jacobian \" + str(cv.jacobian()))\n\n # selfqueue remove\n cv.active(0)\n cv.queue_mode(True, True)\n pc.set_maxstep(10)\n h.finitialize(-65)\n pc.psolve(2)\n cv.queue_mode(False, False) # or later cv.store_events will abort(0)", "smellKey": "S3776", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def get_fingerprint_value(var, data):\n if var == \"transaction\":\n return data.get(\"transaction\") or \"<no-transaction>\"\n elif var == \"message\":\n message = (\n get_path(data, \"logentry\", \"formatted\")\n or get_path(data, \"logentry\", \"message\")\n or get_path(data, \"exception\", \"values\", -1, \"value\")\n )\n return message or \"<no-message>\"\n elif var in (\"type\", \"error.type\"):\n ty = get_path(data, \"exception\", \"values\", -1, \"type\")\n return ty or \"<no-type>\"\n elif var in (\"value\", \"error.value\"):\n value = get_path(data, \"exception\", \"values\", -1, \"value\")\n return value or \"<no-value>\"\n elif var in (\"function\", \"stack.function\"):\n frame = get_crash_frame_from_event_data(data)\n func = frame.get(\"function\") if frame else None\n return func or \"<no-function>\"\n elif var in (\"path\", \"stack.abs_path\"):\n frame = get_crash_frame_from_event_data(data)\n func = frame.get(\"abs_path\") or frame.get(\"filename\") if frame else None\n return func or \"<no-abs-path>\"\n elif var == \"stack.filename\":\n frame = get_crash_frame_from_event_data(data)\n func = frame.get(\"filename\") or frame.get(\"abs_path\") if frame else None\n return func or \"<no-filename>\"\n elif var in (\"module\", \"stack.module\"):\n frame = get_crash_frame_from_event_data(data)\n mod = frame.get(\"module\") if frame else None\n return mod or \"<no-module>\"\n elif var in (\"package\", \"stack.package\"):\n frame = get_crash_frame_from_event_data(data)\n pkg = frame.get(\"package\") if frame else None\n if pkg:\n pkg = pkg.rsplit(\"/\", 1)[-1].rsplit(\"\\\\\", 1)[-1]\n return pkg or \"<no-package>\"\n elif var == \"level\":\n return data.get(\"level\") or \"<no-level>\"\n elif var == \"logger\":\n return data.get(\"logger\") or \"<no-logger>\"\n elif var.startswith(\"tags.\"):\n tag = var[5:]\n for t, value in data.get(\"tags\") or ():\n if t == tag:\n return value\n return \"<no-value-for-tag-%s>\" % tag", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def keySave(self):\n\t\tself.installPackages = []\n\t\tself.removePackages = []\n\t\tself.cmdList = []\n\t\tfor item in self[\"config\"].list:\n\t\t\tif len(item) > 1 and item[1].isChanged():\n\t\t\t\tdaemon = item[3]\n\t\t\t\tif item[1].value == 2: # remove\n\t\t\t\t\tself.removePackages.append(daemon[\"package\"])\n\t\t\t\telif item[1].value == 3: # install\n\t\t\t\t\tself.installPackages.append(daemon[\"package\"])\n\t\t\t\telif item[1].value == 0: # autostart on\n\t\t\t\t\tautostartprio = daemon[\"autostartprio\"]\n\t\t\t\t\tcmd = f\"defaults {autostartprio}\" if autostartprio else \"defaults\"\n\t\t\t\t\tautostartservice = daemon[\"autostartservice\"]\n\t\t\t\t\tself.cmdList.append(f\"update-rc.d -f {autostartservice} {cmd}\")\n\t\t\t\telif item[1].value == 1: # autostart off\n\t\t\t\t\tautostartservice = daemon[\"autostartservice\"]\n\t\t\t\t\tself.cmdList.append(f\"update-rc.d -f {autostartservice} remove\")\n\t\t\titem[1].cancel()\n\n\t\tif self.removePackages:\n\t\t\tself.showProgress(_(\"Removing Service\"))\n\t\t\targs = {\n\t\t\t\t\"arguments\": self.removePackages,\n\t\t\t\t\"options\": {\"remove\": [\"--force-remove\", \"--autoremove\"]}\n\t\t\t}\n\t\t\tself.opkgComponent.runCommand(self.opkgComponent.CMD_REMOVE, args)\n\t\telif self.installPackages:\n\t\t\tself.opkgCallback(self.opkgComponent.EVENT_REMOVE_DONE, \"\")\n\t\telif self.cmdList:\n\t\t\tself.opkgCallback(self.opkgComponent.EVENT_INSTALL_DONE, \"\")\n\t\telse:\n\t\t\tSetup.keySave(self)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@skipUnlessDBFeature(\"supports_dwithin_lookup\")\n def test_dwithin(self):\n \"\"\"\n Test the `dwithin` lookup type.\n \"\"\"\n # Distances -- all should be equal (except for the\n # degree/meter pair in au_cities, that's somewhat\n # approximate).\n tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]\n au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]\n\n # Expected cities for Australia and Texas.\n tx_cities = [\"Downtown Houston\", \"Southside Place\"]\n au_cities = [\"Mittagong\", \"Shellharbour\", \"Thirroul\", \"Wollongong\"]\n\n # Performing distance queries on two projected coordinate systems one\n # with units in meters and the other in units of U.S. survey feet.\n for dist in tx_dists:\n if isinstance(dist, tuple):\n dist1, dist2 = dist\n else:\n dist1 = dist2 = dist\n qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))\n qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))\n for qs in qs1, qs2:\n with self.subTest(dist=dist, qs=qs):\n self.assertEqual(tx_cities, self.get_names(qs))\n\n # With a complex geometry expression\n self.assertFalse(\n SouthTexasCity.objects.exclude(point__dwithin=(Union(\"point\", \"point\"), 0))\n )\n\n # Now performing the `dwithin` queries on a geodetic coordinate system.\n for dist in au_dists:\n with self.subTest(dist=dist):\n type_error = isinstance(dist, D) and not connection.ops.oracle\n if isinstance(dist, tuple):\n if connection.ops.oracle or connection.ops.spatialite:\n # Result in meters\n dist = dist[1]\n else:\n # Result in units of the field\n dist = dist[0]\n\n # Creating the query set.\n qs = AustraliaCity.objects.order_by(\"name\")\n if type_error:\n # A ValueError should be raised on PostGIS when trying to\n # pass Distance objects into a DWithin query using a\n # geodetic field.\n with self.assertRaises(ValueError):\n AustraliaCity.objects.filter(\n point__dwithin=(self.au_pnt, dist)\n ).count()\n else:\n self.assertEqual(\n au_cities,\n self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))),\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@classmethod\n def add_filing(cls, con, filing: Filing) -> int:\n \"\"\"Add new filing to COLIN tables.\"\"\"\n try:\n if filing.filing_type not in ['annualReport', 'changeOfAddress', 'changeOfDirectors',\n 'incorporationApplication', 'alteration', 'transition', 'correction']:\n raise InvalidFilingTypeException(filing_type=filing.filing_type)\n\n legal_type = filing.business.corp_type\n corp_num = filing.business.corp_num\n\n filing.user_id = Filing.USERS[legal_type]\n business = filing.business.as_dict()\n cursor = con.cursor()\n # create new event record, return event ID\n filing.event_id = cls._get_event_id(cursor=cursor, corp_num=corp_num)\n # create new filing user\n cls._insert_filing_user(cursor=cursor, filing=filing)\n\n # annualReportDate and annualGeneralMeetingDate will be available in annualReport\n ar_date = filing.body.get('annualReportDate', None)\n agm_date = filing.body.get('annualGeneralMeetingDate', None)\n # create new filing\n cls._insert_filing(cursor=cursor, filing=filing, ar_date=ar_date, agm_date=agm_date)\n\n if filing.filing_type == 'correction':\n cls._process_correction(cursor, business, filing, corp_num)\n else:\n ar_text = cls._process_ar(cursor, filing, corp_num, ar_date, agm_date)\n dir_text = cls._process_directors(cursor, filing, business, corp_num)\n office_text = cls._process_office(cursor=cursor, filing=filing)\n\n if parties := filing.body.get('parties', []):\n for party in parties:\n cls._create_party_roles(cursor=cursor,\n party=party,\n business=business,\n event_id=filing.event_id)\n # add shares if not coop\n cls._process_share_structure(cursor, filing, corp_num)\n if filing.body.get('nameRequest'):\n cls._create_corp_name(cursor, filing, corp_num)\n\n # add name translations\n cls._process_name_translations(cursor, filing, corp_num)\n\n # alter corp type\n if alter_corp_type := filing.body.get('business', {}).get('legalType'):\n Business.update_corp_type(cursor=cursor, corp_num=corp_num, corp_type=alter_corp_type)\n\n if filing.body.get('provisionsRemoved'):\n provisions = Business.get_corp_restriction(cursor=cursor, event_id=None, corp_num=corp_num)\n if provisions and provisions['restriction_ind'] == 'Y':\n Business.end_current_corp_restriction(\n cursor=cursor, event_id=filing.event_id, corp_num=corp_num)\n\n if filing.body.get('hasProvisions'):\n provisions = Business.get_corp_restriction(cursor=cursor, event_id=None, corp_num=corp_num)\n if provisions and provisions['restriction_ind'] == 'N':\n Business.end_current_corp_restriction(\n cursor=cursor, event_id=filing.event_id, corp_num=corp_num)\n Business.create_corp_restriction(\n cursor=cursor, event_id=filing.event_id, corp_num=corp_num, provisions=True)\n elif not provisions:\n Business.create_corp_restriction(\n cursor=cursor, event_id=filing.event_id, corp_num=corp_num, provisions=True)\n ledger_text = f'{ar_text}{dir_text}{office_text}'.replace(' ', '')\n if ledger_text != '':\n cls._insert_ledger_text(cursor, filing, ledger_text)\n\n # update corporation record\n is_annual_report = filing.filing_type == 'annualReport'\n Business.update_corporation(\n cursor=cursor, corp_num=corp_num, date=agm_date, annual_report=is_annual_report)\n\n # Freeze entity for Alteration\n if filing.filing_type == 'alteration':\n Business.update_corp_frozen_type(cursor, corp_num, Business.CorpFrozenTypes.COMPANY_FROZEN.value)\n\n return filing.event_id\n\n except Exception as err:\n # something went wrong, roll it all back\n current_app.logger.error(err.with_traceback(None))\n raise err", "smellKey": "S3776", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "def _handle_breadcrumb(\n event: dict[str, Any],\n project: Project,\n replay_id: str,\n replay_event: dict[str, Any] | None,\n should_report_rage_click_issue=False,\n should_report_hydration_error_issue=False,\n) -> ReplayActionsEventPayloadClick | None:\n\n click = None\n\n payload = event[\"data\"].get(\"payload\", {})\n if not isinstance(payload, dict):\n return None\n\n category = payload.get(\"category\")\n if category == \"ui.slowClickDetected\":\n is_timeout_reason = payload[\"data\"].get(\"endReason\") == \"timeout\"\n is_target_tagname = payload[\"data\"].get(\"node\", {}).get(\"tagName\") in (\n \"a\",\n \"button\",\n \"input\",\n )\n timeout = payload[\"data\"].get(\"timeAfterClickMs\", 0) or payload[\"data\"].get(\n \"timeafterclickms\", 0\n )\n if is_timeout_reason and is_target_tagname and timeout >= 7000:\n is_rage = (\n payload[\"data\"].get(\"clickCount\", 0) or payload[\"data\"].get(\"clickcount\", 0)\n ) >= 5\n click = create_click_event(\n payload, replay_id, is_dead=True, is_rage=is_rage, project_id=project.id\n )\n if click is not None:\n if is_rage:\n metrics.incr(\"replay.rage_click_detected\")\n if should_report_rage_click_issue:\n if replay_event is not None:\n report_rage_click_issue_with_replay_event(\n project.id,\n replay_id,\n payload[\"timestamp\"],\n payload[\"message\"],\n payload[\"data\"][\"url\"],\n payload[\"data\"][\"node\"],\n payload[\"data\"][\"node\"][\"attributes\"].get(\"data-sentry-component\"),\n replay_event,\n )\n # Log the event for tracking.\n log = event[\"data\"].get(\"payload\", {}).copy()\n log[\"project_id\"] = project.id\n log[\"replay_id\"] = replay_id\n log[\"dom_tree\"] = log.pop(\"message\")\n\n return click\n\n elif category == \"ui.click\":\n click = create_click_event(\n payload, replay_id, is_dead=False, is_rage=False, project_id=project.id\n )\n if click is not None:\n return click\n\n elif category == \"replay.hydrate-error\":\n metrics.incr(\"replay.hydration_error_breadcrumb\")\n if replay_event is not None and should_report_hydration_error_issue:\n report_hydration_error_issue_with_replay_event(\n project.id,\n replay_id,\n payload[\"timestamp\"],\n payload.get(\"data\", {}).get(\"url\"),\n replay_event,\n )\n\n return None", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _verify_peercerts_impl(\n ssl_context: ssl.SSLContext,\n cert_chain: list[bytes],\n server_hostname: str | None = None,\n) -> None:\n certs = None\n policies = None\n trust = None\n cf_error = None\n try:\n if server_hostname is not None:\n cf_str_hostname = None\n try:\n cf_str_hostname = _bytes_to_cf_string(server_hostname.encode(\"ascii\"))\n ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)\n finally:\n if cf_str_hostname:\n CoreFoundation.CFRelease(cf_str_hostname)\n else:\n ssl_policy = Security.SecPolicyCreateSSL(True, None)\n\n policies = ssl_policy\n if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n # Add explicit policy requiring positive revocation checks\n policies = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n CoreFoundation.CFArrayAppendValue(policies, ssl_policy)\n CoreFoundation.CFRelease(ssl_policy)\n revocation_policy = Security.SecPolicyCreateRevocation(\n kSecRevocationUseAnyAvailableMethod\n | kSecRevocationRequirePositiveResponse\n )\n CoreFoundation.CFArrayAppendValue(policies, revocation_policy)\n CoreFoundation.CFRelease(revocation_policy)\n elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n raise NotImplementedError(\"VERIFY_CRL_CHECK_LEAF not implemented for macOS\")\n\n certs = None\n try:\n certs = _der_certs_to_cf_cert_array(cert_chain)\n\n # Now that we have certificates loaded and a SecPolicy\n # we can finally create a SecTrust object!\n trust = Security.SecTrustRef()\n Security.SecTrustCreateWithCertificates(\n certs, policies, ctypes.byref(trust)\n )\n\n finally:\n # The certs are now being held by SecTrust so we can\n # release our handles for the array.\n if certs:\n CoreFoundation.CFRelease(certs)\n\n # If there are additional trust anchors to load we need to transform\n # the list of DER-encoded certificates into a CFArray.\n ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(\n binary_form=True\n )\n if ctx_ca_certs_der:\n ctx_ca_certs = None\n try:\n ctx_ca_certs = _der_certs_to_cf_cert_array(ctx_ca_certs_der)\n Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)\n finally:\n if ctx_ca_certs:\n CoreFoundation.CFRelease(ctx_ca_certs)\n\n # We always want system certificates.\n Security.SecTrustSetAnchorCertificatesOnly(trust, False)\n\n cf_error = CoreFoundation.CFErrorRef()\n sec_trust_eval_result = Security.SecTrustEvaluateWithError(\n trust, ctypes.byref(cf_error)\n )\n # sec_trust_eval_result is a bool (0 or 1)\n # where 1 means that the certs are trusted.\n if sec_trust_eval_result == 1:\n is_trusted = True\n elif sec_trust_eval_result == 0:\n is_trusted = False\n else:\n raise ssl.SSLError(\n f\"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}\"\n )\n\n cf_error_code = 0\n if not is_trusted:\n cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)\n\n # If the error is a known failure that we're\n # explicitly okay with from SSLContext configuration\n # we can set is_trusted accordingly.\n if ssl_context.verify_mode != ssl.CERT_REQUIRED and (\n cf_error_code == CFConst.errSecNotTrusted\n or cf_error_code == CFConst.errSecCertificateExpired\n ):\n is_trusted = True\n elif (\n not ssl_context.check_hostname\n and cf_error_code == CFConst.errSecHostNameMismatch\n ):\n is_trusted = True\n\n # If we're still not trusted then we start to\n # construct and raise the SSLCertVerificationError.\n if not is_trusted:\n cf_error_string_ref = None\n try:\n cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)\n\n # Can this ever return 'None' if there's a CFError?\n cf_error_message = (\n _cf_string_ref_to_str(cf_error_string_ref)\n or \"Certificate verification failed\"\n )\n\n # TODO: Not sure if we need the SecTrustResultType for anything?\n # We only care whether or not it's a success or failure for now.\n sec_trust_result_type = Security.SecTrustResultType()\n Security.SecTrustGetTrustResult(\n trust, ctypes.byref(sec_trust_result_type)\n )\n\n err = ssl.SSLCertVerificationError(cf_error_message)\n err.verify_message = cf_error_message\n err.verify_code = cf_error_code\n raise err\n finally:\n if cf_error_string_ref:\n CoreFoundation.CFRelease(cf_error_string_ref)\n\n finally:\n if policies:\n CoreFoundation.CFRelease(policies)\n if trust:\n CoreFoundation.CFRelease(trust)", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def handle_comment(self, data):\n comment_state = DBusXMLParser.COMMENT_STATE_BEGIN;\n lines = data.split('\\n')\n symbol = ''\n body = ''\n in_para = False\n params = {}\n for line in lines:\n orig_line = line\n line = line.lstrip()\n if comment_state == DBusXMLParser.COMMENT_STATE_BEGIN:\n if len(line) > 0:\n colon_index = line.find(': ')\n if colon_index == -1:\n if line.endswith(':'):\n symbol = line[0:len(line)-1]\n comment_state = DBusXMLParser.COMMENT_STATE_PARAMS\n else:\n comment_state = DBusXMLParser.COMMENT_STATE_SKIP\n else:\n symbol = line[0:colon_index]\n rest_of_line = line[colon_index+2:].strip()\n if len(rest_of_line) > 0:\n body += '<para>' + rest_of_line + '</para>'\n comment_state = DBusXMLParser.COMMENT_STATE_PARAMS\n elif comment_state == DBusXMLParser.COMMENT_STATE_PARAMS:\n if line.startswith('@'):\n colon_index = line.find(': ')\n if colon_index == -1:\n comment_state = DBusXMLParser.COMMENT_STATE_BODY\n if not in_para:\n body += '<para>'\n in_para = True\n body += orig_line + '\\n'\n else:\n param = line[1:colon_index]\n docs = line[colon_index + 2:]\n params[param] = docs\n else:\n comment_state = DBusXMLParser.COMMENT_STATE_BODY\n if len(line) > 0:\n if not in_para:\n body += '<para>'\n in_para = True\n body += orig_line + '\\n'\n elif comment_state == DBusXMLParser.COMMENT_STATE_BODY:\n if len(line) > 0:\n if not in_para:\n body += '<para>'\n in_para = True\n body += orig_line + '\\n'\n else:\n if in_para:\n body += '</para>'\n in_para = False\n if in_para:\n body += '</para>'\n\n if symbol != '':\n self.doc_comment_last_symbol = symbol\n self.doc_comment_params = params\n self.doc_comment_body = body", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "def dump_cookie(\n key: str,\n value: str = \"\",\n max_age: timedelta | int | None = None,\n expires: str | datetime | int | float | None = None,\n path: str | None = \"/\",\n domain: str | None = None,\n secure: bool = False,\n httponly: bool = False,\n sync_expires: bool = True,\n max_size: int = 4093,\n samesite: str | None = None,\n) -> str:\n \"\"\"Create a Set-Cookie header without the ``Set-Cookie`` prefix.\n\n The return value is usually restricted to ascii as the vast majority\n of values are properly escaped, but that is no guarantee. It's\n tunneled through latin1 as required by :pep:`3333`.\n\n The return value is not ASCII safe if the key contains unicode\n characters. This is technically against the specification but\n happens in the wild. It's strongly recommended to not use\n non-ASCII values for the keys.\n\n :param max_age: should be a number of seconds, or `None` (default) if\n the cookie should last only as long as the client's\n browser session. Additionally `timedelta` objects\n are accepted, too.\n :param expires: should be a `datetime` object or unix timestamp.\n :param path: limits the cookie to a given path, per default it will\n span the whole domain.\n :param domain: Use this if you want to set a cross-domain cookie. For\n example, ``domain=\"example.com\"`` will set a cookie\n that is readable by the domain ``www.example.com``,\n ``foo.example.com`` etc. Otherwise, a cookie will only\n be readable by the domain that set it.\n :param secure: The cookie will only be available via HTTPS\n :param httponly: disallow JavaScript to access the cookie. This is an\n extension to the cookie standard and probably not\n supported by all browsers.\n :param charset: the encoding for string values.\n :param sync_expires: automatically set expires if max_age is defined\n but expires not.\n :param max_size: Warn if the final header value exceeds this size. The\n default, 4093, should be safely `supported by most browsers\n <cookie_>`_. Set to 0 to disable this check.\n :param samesite: Limits the scope of the cookie such that it will\n only be attached to requests if those requests are same-site.\n\n .. _`cookie`: http://browsercookielimits.squawky.net/\n\n .. versionchanged:: 3.0\n Passing bytes, and the ``charset`` parameter, were removed.\n\n .. versionchanged:: 2.3.3\n The ``path`` parameter is ``/`` by default.\n\n .. versionchanged:: 2.3.1\n The value allows more characters without quoting.\n\n .. versionchanged:: 2.3\n ``localhost`` and other names without a dot are allowed for the domain. A\n leading dot is ignored.\n\n .. versionchanged:: 2.3\n The ``path`` parameter is ``None`` by default.\n\n .. versionchanged:: 1.0.0\n The string ``'None'`` is accepted for ``samesite``.\n \"\"\"\n if path is not None:\n # safe = https://url.spec.whatwg.org/#url-path-segment-string\n # as well as percent for things that are already quoted\n # excluding semicolon since it's part of the header syntax\n path = quote(path, safe=\"%!$&'()*+,/:=@\")\n\n if domain:\n domain = domain.partition(\":\")[0].lstrip(\".\").encode(\"idna\").decode(\"ascii\")\n\n if isinstance(max_age, timedelta):\n max_age = int(max_age.total_seconds())\n\n if expires is not None:\n if not isinstance(expires, str):\n expires = http_date(expires)\n elif max_age is not None and sync_expires:\n expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)\n\n if samesite is not None:\n samesite = samesite.title()\n\n if samesite not in {\"Strict\", \"Lax\", \"None\"}:\n raise ValueError(\"SameSite must be 'Strict', 'Lax', or 'None'.\")\n\n # Quote value if it contains characters not allowed by RFC 6265. Slash-escape with\n # three octal digits, which matches http.cookies, although the RFC suggests base64.\n if not _cookie_no_quote_re.fullmatch(value):\n # Work with bytes here, since a UTF-8 character could be multiple bytes.\n value = _cookie_slash_re.sub(\n lambda m: _cookie_slash_map[m.group()], value.encode()\n ).decode(\"ascii\")\n value = f'\"{value}\"'\n\n # Send a non-ASCII key as mojibake. Everything else should already be ASCII.\n # TODO Remove encoding dance, it seems like clients accept UTF-8 keys\n buf = [f\"{key.encode().decode('latin1')}={value}\"]\n\n for k, v in (\n (\"Domain\", domain),\n (\"Expires\", expires),\n (\"Max-Age\", max_age),\n (\"Secure\", secure),\n (\"HttpOnly\", httponly),\n (\"Path\", path),\n (\"SameSite\", samesite),\n ):\n if v is None or v is False:\n continue\n\n if v is True:\n buf.append(k)\n continue\n\n buf.append(f\"{k}={v}\")\n\n rv = \"; \".join(buf)\n\n # Warn if the final value of the cookie is larger than the limit. If the cookie is\n # too large, then it may be silently ignored by the browser, which can be quite hard\n # to debug.\n cookie_size = len(rv)\n\n if max_size and cookie_size > max_size:\n value_size = len(value)\n warnings.warn(\n f\"The '{key}' cookie is too large: the value was {value_size} bytes but the\"\n f\" header required {cookie_size - value_size} extra bytes. The final size\"\n f\" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may\"\n \" silently ignore cookies larger than this.\",\n stacklevel=2,\n )\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def convert_json_class(object_):\n if isinstance(object_, dict):\n try:\n json_class = object_[\"json_class\"]\n raw = object_[\"raw\"]\n if json_class == \"Float\":\n if raw == \"Infinity\":\n return float(\"inf\")\n elif raw == \"-Infinity\":\n return float(\"-inf\")\n elif raw == \"NaN\":\n return float(\"nan\")\n return raw\n return bytearray(raw)\n except Exception:\n for key, value in object_.items():\n object_[key] = convert_json_class(value)\n return object_\n elif isinstance(object_, (tuple, list)):\n object_ = list(object_)\n index = 0\n for value in object_:\n object_[index] = convert_json_class(value)\n index += 1\n return object_\n else:\n return object_", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n results = json.loads(raw)\n pk_ooi = Reference.from_str(input_ooi[\"primary_key\"])\n network = Network(name=\"internet\").reference\n\n # Structure based on https://docs.binaryedge.io/modules/<accepted_modules_name>/\n accepted_modules = (\"webv2\", \" web-enrich\") # http/https: deprecated, so not implemented.\n for scan in results[\"results\"]:\n module = scan[\"origin\"][\"type\"]\n if module not in accepted_modules:\n continue\n\n port_nr = int(scan[\"target\"][\"port\"])\n protocol = scan[\"target\"][\"protocol\"]\n ip = scan[\"target\"][\"ip\"]\n\n if input_ooi[\"object_type\"] in [\"IPAddressV4\", \"IPAddressV6\"]:\n ip_ref = pk_ooi\n else:\n ipvx = ipaddress.ip_address(ip)\n if ipvx.version == 4:\n ip_ooi = IPAddressV4(address=ip, network=network)\n else:\n ip_ooi = IPAddressV6(address=ip, network=network)\n yield ip_ooi\n ip_ref = ip_ooi.reference\n\n ip_port_ooi = IPPort(address=ip_ref, protocol=Protocol(protocol), port=port_nr, state=PortState(\"open\"))\n yield ip_port_ooi\n\n if module == \"webv2\":\n response = scan.get(\"result\", {}).get(\"data\", {}).get(\"response\", {})\n # (potential) TODO:\n # * url [string]\n # * protocol_version [int]\n # * redirects [list]\n # * headers.headers [object]\n # * plugin (name+version) of {wordpress,joomla}\n\n for app in response.get(\"apps\", {}):\n if \"cpe\" in app:\n software_ooi = Software(name=get_name_from_cpe(app[\"cpe\"]), cpe=app[\"cpe\"])\n yield software_ooi\n yield SoftwareInstance(ooi=ip_port_ooi.reference, software=software_ooi.reference)\n else:\n software_name = app[\"name\"]\n if \"version\" in app:\n software_ooi = Software(name=software_name, version=app[\"version\"])\n yield software_ooi\n yield SoftwareInstance(ooi=ip_port_ooi.reference, software=software_ooi.reference)\n else:\n software_ooi = Software(name=software_name)\n yield software_ooi\n yield SoftwareInstance(ooi=ip_port_ooi.reference, software=software_ooi.reference)\n elif module == \"web-enrich\":\n # (potential) TODO:\n # * http_version [string]\n # * headers [object]\n # * redirects [list]\n # * url [string]\n\n data = scan.get(\"result\", {}).get(\"data\", {})\n for potential_software in data:\n # Check all values for 'cpe'\n if isinstance(potential_software, dict) and \"cpe\" in potential_software:\n software_ooi = Software(\n name=get_name_from_cpe(potential_software[\"cpe\"]), cpe=potential_software[\"cpe\"]\n )\n yield software_ooi\n yield SoftwareInstance(ooi=ip_port_ooi.reference, software=software_ooi.reference)\n\n key_software = {\n \"secrets\": \"AWS Secrets\",\n \"f5_bigip_loadbalancer\": \"F5 BigIP Loadblancer\",\n \"f5_bigip\": \"F5 BigIP\",\n \"citrix_netscaler\": \"Citrix NetScaler\",\n }\n for ks_key, ks_software in key_software.items():\n if ks_key in data:\n software_ooi = Software(name=ks_software)\n yield software_ooi\n yield SoftwareInstance(ooi=ip_port_ooi.reference, software=software_ooi.reference)", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def check_assigned_sym_values(kconf):\n # Verifies that the values assigned to symbols \"took\" (matches the value\n # the symbols actually got), printing warnings otherwise. Choice symbols\n # are checked separately, in check_assigned_choice_values().\n\n for sym in kconf.unique_defined_syms:\n if sym.choice:\n continue\n\n user_value = sym.user_value\n if user_value is None:\n continue\n\n # Tristate values are represented as 0, 1, 2. Having them as \"n\", \"m\",\n # \"y\" is more convenient here, so convert.\n if sym.type in (BOOL, TRISTATE):\n user_value = TRI_TO_STR[user_value]\n\n if user_value != sym.str_value:\n msg = f\"{sym.name_and_loc} was assigned the value '{user_value}'\" \\\n f\" but got the value '{sym.str_value}'. \"\n\n # List any unsatisfied 'depends on' dependencies in the warning\n mdeps = missing_deps(sym)\n if mdeps:\n expr_strs = []\n for expr in mdeps:\n estr = expr_str(expr)\n if isinstance(expr, tuple):\n # Add () around dependencies that aren't plain symbols.\n # Gives '(FOO || BAR) (=n)' instead of\n # 'FOO || BAR (=n)', which might be clearer.\n estr = f\"({estr})\"\n expr_strs.append(f\"{estr} \"\n f\"(={TRI_TO_STR[expr_value(expr)]})\")\n\n msg += \"Check these unsatisfied dependencies: \" + \\\n \", \".join(expr_strs) + \". \"\n\n warn(msg + SYM_INFO_HINT.format(sym))", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def backfill_outboxes_for(\n silo_mode: SiloMode,\n scheduled_count: int = 0,\n max_batch_rate: int = OUTBOX_BACKFILLS_PER_MINUTE,\n force_synchronous: bool = False,\n) -> bool:\n # Maintain a steady state of outbox processing by subtracting any regularly scheduled rows\n # from an expected rate.\n remaining_to_backfill = max_batch_rate - scheduled_count\n backfilled = 0\n\n if remaining_to_backfill > 0:\n for app, app_models in apps.all_models.items():\n for model in app_models.values():\n if not hasattr(model._meta, \"silo_limit\"):\n continue\n\n # Only process models local this operational mode.\n if (\n silo_mode is not SiloMode.MONOLITH\n and silo_mode not in model._meta.silo_limit.modes\n ):\n continue\n\n # If we find some backfill work to perform, do it.\n batch = process_outbox_backfill_batch(\n model, batch_size=remaining_to_backfill, force_synchronous=force_synchronous\n )\n if batch is None:\n continue\n\n remaining_to_backfill -= batch.count\n backfilled += batch.count\n if remaining_to_backfill <= 0:\n break\n\n metrics.incr(\n \"backfill_outboxes.backfilled\",\n amount=backfilled,\n tags=dict(silo_mode=silo_mode.name, force_synchronous=force_synchronous),\n skip_internal=True,\n sample_rate=1.0,\n )\n return backfilled > 0", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def channelSelected(self):\n\t\tref = self.getCurrentSelection()\n\t\ttry:\n\t\t\tdoClose = not config.usage.servicelistpreview_mode.value or ref == self.session.nav.getCurrentlyPlayingServiceOrGroup()\n\t\texcept Exception:\n\t\t\tdoClose = False\n\t\tif self.startServiceRef is None and not doClose:\n\t\t\tself.startServiceRef = self.session.nav.getCurrentlyPlayingServiceOrGroup()\n\t\tref = self.getCurrentSelection()\n\t\tif self.movemode and (self.isBasePathEqual(self.bouquet_root) or \"userbouquet.\" in ref.toString()):\n\t\t\tself.toggleMoveMarked()\n\t\telif (ref.flags & eServiceReference.flagDirectory) == eServiceReference.flagDirectory:\n\t\t\tif self.isSubservices(ref):\n\t\t\t\tself.enterSubservices()\n\t\t\telif parentalControl.isServicePlayable(ref, self.bouquetParentalControlCallback, self.session):\n\t\t\t\tself.enterPath(ref)\n\t\t\t\tself.gotoCurrentServiceOrProvider(ref)\n\t\telif self.bouquet_mark_edit != EDIT_OFF:\n\t\t\tif not (self.bouquet_mark_edit == EDIT_ALTERNATIVES and ref.flags & eServiceReference.isGroup):\n\t\t\t\tself.doMark()\n\t\telif not (ref.flags & eServiceReference.isMarker or ref.type == -1):\n\t\t\troot = self.getRoot()\n\t\t\tif not root or not (root.flags & eServiceReference.isGroup):\n\t\t\t\tself.zap(enable_pipzap=doClose, preview_zap=not doClose)\n\t\t\t\tself.asciiOff()\n\t\t\t\tif doClose:\n\t\t\t\t\tif self.dopipzap:\n\t\t\t\t\t\tself.zapBack()\n\t\t\t\t\tself.startServiceRef = None\n\t\t\t\t\tself.startRoot = None\n\t\t\t\t\tself.correctChannelNumber()\n\t\t\t\t\tself.movemode and self.toggleMoveMode()\n\t\t\t\t\tself.editMode = False\n\t\t\t\t\tself.protectContextMenu = True\n\t\t\t\t\tself[\"key_green\"].setText(_(\"Reception Lists\"))\n\t\t\t\t\tself.close(ref)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def set_fields_default_value(self):\n if not hasattr(self, \"Meta\"):\n return\n if not hasattr(self.Meta, \"model\"):\n return\n model = self.Meta.model\n\n for name, serializer_field in self.fields.items():\n if serializer_field.default != empty or serializer_field.required:\n continue\n model_field = getattr(model, name, None)\n if model_field is None:\n continue\n if (\n not hasattr(model_field, \"field\")\n or not hasattr(model_field.field, \"default\")\n or model_field.field.default == NOT_PROVIDED\n ):\n continue\n if name == \"id\":\n continue\n default = model_field.field.default\n\n if callable(default):\n default = default()\n if default == \"\":\n continue\n # print(f\"Set default value: {name}: {default}\")\n serializer_field.default = default", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def flush_boefje_cache(self) -> None:\n \"\"\"boefje.consumes -> plugin type boefje\"\"\"\n self.logger.debug(\"Flushing the katalogus boefje type cache for organisations\")\n\n with self.boefje_cache_lock:\n # First, we reset the cache, to make sure we won't get any ExpiredError\n self.boefje_cache.expiration_enabled = False\n self.boefje_cache.reset()\n\n orgs = self.get_organisations()\n for org in orgs:\n self.boefje_cache[org.id] = {}\n\n for plugin in self.get_plugins_by_organisation(org.id):\n if plugin.type != \"boefje\":\n continue\n\n if plugin.enabled is False:\n continue\n\n if not plugin.consumes:\n continue\n\n # NOTE: backwards compatibility, when it is a boefje the\n # consumes field is a string field.\n if isinstance(plugin.consumes, str):\n self.boefje_cache[org.id].setdefault(plugin.consumes, []).append(plugin)\n continue\n\n for type_ in plugin.consumes:\n self.boefje_cache[org.id].setdefault(type_, []).append(plugin)\n\n self.boefje_cache.expiration_enabled = True\n\n self.logger.debug(\"Flushed the katalogus boefje type cache for organisations\")", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "@staticmethod\n def get_interpolated_shapes(\n track, start_frame, end_frame, dimension, *,\n included_frames: Optional[Sequence[int]] = None,\n include_outside: bool = False,\n ):\n def copy_shape(source, frame, points=None, rotation=None):\n copied = source.copy()\n copied[\"attributes\"] = faster_deepcopy(source[\"attributes\"])\n\n copied[\"keyframe\"] = False\n copied[\"frame\"] = frame\n if rotation is not None:\n copied[\"rotation\"] = rotation\n\n if points is None:\n points = copied[\"points\"]\n\n if isinstance(points, np.ndarray):\n points = points.tolist()\n else:\n points = points.copy()\n\n if points is not None:\n copied[\"points\"] = points\n\n return copied\n\n def find_angle_diff(right_angle, left_angle):\n angle_diff = right_angle - left_angle\n angle_diff = ((angle_diff + 180) % 360) - 180\n if abs(angle_diff) >= 180:\n # if the main arc is bigger than 180, go another arc\n # to find it, just subtract absolute value from 360 and inverse sign\n angle_diff = 360 - abs(angle_diff) * -1 if angle_diff > 0 else 1\n\n return angle_diff\n\n def simple_interpolation(shape0, shape1):\n shapes = []\n distance = shape1[\"frame\"] - shape0[\"frame\"]\n diff = np.subtract(shape1[\"points\"], shape0[\"points\"])\n\n for frame in range(shape0[\"frame\"] + 1, shape1[\"frame\"]):\n offset = (frame - shape0[\"frame\"]) / distance\n rotation = (shape0[\"rotation\"] + find_angle_diff(\n shape1[\"rotation\"], shape0[\"rotation\"],\n ) * offset + 360) % 360\n points = shape0[\"points\"] + diff * offset\n\n if included_frames is None or frame in included_frames:\n shapes.append(copy_shape(shape0, frame, points, rotation))\n\n return shapes\n\n def simple_3d_interpolation(shape0, shape1):\n result = simple_interpolation(shape0, shape1)\n angles = (shape0[\"points\"][3:6] + shape1[\"points\"][3:6])\n distance = shape1[\"frame\"] - shape0[\"frame\"]\n\n for shape in result:\n offset = (shape[\"frame\"] - shape0[\"frame\"]) / distance\n for i, angle0 in enumerate(angles):\n if i < 3:\n angle1 = angles[i + 3]\n angle0 = (angle0 if angle0 >= 0 else angle0 + math.pi * 2) * 180 / math.pi\n angle1 = (angle1 if angle1 >= 0 else angle1 + math.pi * 2) * 180 / math.pi\n angle = angle0 + find_angle_diff(angle1, angle0) * offset * math.pi / 180\n shape[\"points\"][i + 3] = angle if angle <= math.pi else angle - math.pi * 2\n\n return result\n\n def points_interpolation(shape0, shape1):\n if len(shape0[\"points\"]) == 2 and len(shape1[\"points\"]) == 2:\n return simple_interpolation(shape0, shape1)\n else:\n shapes = []\n for frame in range(shape0[\"frame\"] + 1, shape1[\"frame\"]):\n if included_frames is None or frame in included_frames:\n shapes.append(copy_shape(shape0, frame))\n\n return shapes\n\n def interpolate_position(left_position, right_position, offset):\n def to_array(points):\n return np.asarray(\n list(map(lambda point: [point[\"x\"], point[\"y\"]], points))\n ).flatten()\n\n def to_points(array):\n return list(map(\n lambda point: {\"x\": point[0], \"y\": point[1]}, np.asarray(array).reshape(-1, 2)\n ))\n\n def curve_length(points):\n length = 0\n for i in range(1, len(points)):\n dx = points[i][\"x\"] - points[i - 1][\"x\"]\n dy = points[i][\"y\"] - points[i - 1][\"y\"]\n length += np.sqrt(dx ** 2 + dy ** 2)\n return length\n\n def curve_to_offset_vec(points, length):\n offset_vector = [0]\n accumulated_length = 0\n for i in range(1, len(points)):\n dx = points[i][\"x\"] - points[i - 1][\"x\"]\n dy = points[i][\"y\"] - points[i - 1][\"y\"]\n accumulated_length += np.sqrt(dx ** 2 + dy ** 2)\n offset_vector.append(accumulated_length / length)\n\n return offset_vector\n\n def find_nearest_pair(value, curve):\n minimum = [0, abs(value - curve[0])]\n for i in range(1, len(curve)):\n distance = abs(value - curve[i])\n if distance < minimum[1]:\n minimum = [i, distance]\n\n return minimum[0]\n\n def match_left_right(left_curve, right_curve):\n matching = {}\n for i, left_curve_item in enumerate(left_curve):\n matching[i] = [find_nearest_pair(left_curve_item, right_curve)]\n return matching\n\n def match_right_left(left_curve, right_curve, left_right_matching):\n matched_right_points = list(chain.from_iterable(left_right_matching.values()))\n unmatched_right_points = filter(lambda x: x not in matched_right_points, range(len(right_curve)))\n updated_matching = faster_deepcopy(left_right_matching)\n\n for right_point in unmatched_right_points:\n left_point = find_nearest_pair(right_curve[right_point], left_curve)\n updated_matching[left_point].append(right_point)\n\n for key, value in updated_matching.items():\n updated_matching[key] = sorted(value)\n\n return updated_matching\n\n def reduce_interpolation(interpolated_points, matching, left_points, right_points):\n def average_point(points):\n sumX = 0\n sumY = 0\n for point in points:\n sumX += point[\"x\"]\n sumY += point[\"y\"]\n\n return {\n \"x\": sumX / len(points),\n \"y\": sumY / len(points)\n }\n\n def compute_distance(point1, point2):\n return np.sqrt(\n ((point1[\"x\"] - point2[\"x\"])) ** 2\n + ((point1[\"y\"] - point2[\"y\"]) ** 2)\n )\n\n def minimize_segment(base_length, N, start_interpolated, stop_interpolated):\n threshold = base_length / (2 * N)\n minimized = [interpolated_points[start_interpolated]]\n latest_pushed = start_interpolated\n for i in range(start_interpolated + 1, stop_interpolated):\n distance = compute_distance(\n interpolated_points[latest_pushed], interpolated_points[i]\n )\n\n if distance >= threshold:\n minimized.append(interpolated_points[i])\n latest_pushed = i\n\n minimized.append(interpolated_points[stop_interpolated])\n\n if len(minimized) == 2:\n distance = compute_distance(\n interpolated_points[start_interpolated],\n interpolated_points[stop_interpolated]\n )\n\n if distance < threshold:\n return [average_point(minimized)]\n\n return minimized\n\n reduced = []\n interpolated_indexes = {}\n accumulated = 0\n for i in range(len(left_points)):\n interpolated_indexes[i] = []\n for _ in range(len(matching[i])):\n interpolated_indexes[i].append(accumulated)\n accumulated += 1\n\n def left_segment(start, stop):\n start_interpolated = interpolated_indexes[start][0]\n stop_interpolated = interpolated_indexes[stop][0]\n\n if start_interpolated == stop_interpolated:\n reduced.append(interpolated_points[start_interpolated])\n return\n\n base_length = curve_length(left_points[start: stop + 1])\n N = stop - start + 1\n\n reduced.extend(\n minimize_segment(base_length, N, start_interpolated, stop_interpolated)\n )\n\n\n def right_segment(left_point):\n start = matching[left_point][0]\n stop = matching[left_point][-1]\n start_interpolated = interpolated_indexes[left_point][0]\n stop_interpolated = interpolated_indexes[left_point][-1]\n base_length = curve_length(right_points[start: stop + 1])\n N = stop - start + 1\n\n reduced.extend(\n minimize_segment(base_length, N, start_interpolated, stop_interpolated)\n )\n\n previous_opened = None\n for i in range(len(left_points)):\n if len(matching[i]) == 1:\n if previous_opened is not None:\n if matching[i][0] == matching[previous_opened][0]:\n continue\n else:\n start = previous_opened\n stop = i - 1\n left_segment(start, stop)\n previous_opened = i\n else:\n previous_opened = i\n else:\n if previous_opened is not None:\n start = previous_opened\n stop = i - 1\n left_segment(start, stop)\n previous_opened = None\n\n right_segment(i)\n\n if previous_opened is not None:\n left_segment(previous_opened, len(left_points) - 1)\n\n return reduced\n\n left_points = to_points(left_position[\"points\"])\n right_points = to_points(right_position[\"points\"])\n left_offset_vec = curve_to_offset_vec(left_points, curve_length(left_points))\n right_offset_vec = curve_to_offset_vec(right_points, curve_length(right_points))\n\n matching = match_left_right(left_offset_vec, right_offset_vec)\n completed_matching = match_right_left(\n left_offset_vec, right_offset_vec, matching\n )\n\n interpolated_points = []\n for left_point_index, left_point in enumerate(left_points):\n for right_point_index in completed_matching[left_point_index]:\n right_point = right_points[right_point_index]\n interpolated_points.append({\n \"x\": left_point[\"x\"] + (right_point[\"x\"] - left_point[\"x\"]) * offset,\n \"y\": left_point[\"y\"] + (right_point[\"y\"] - left_point[\"y\"]) * offset\n })\n\n reducedPoints = reduce_interpolation(\n interpolated_points,\n completed_matching,\n left_points,\n right_points\n )\n\n return to_array(reducedPoints).tolist()\n\n def polyshape_interpolation(shape0, shape1):\n shapes = []\n is_polygon = shape0[\"type\"] == ShapeType.POLYGON\n if is_polygon:\n # Make the polygon closed for computations\n shape0 = shape0.copy()\n shape1 = shape1.copy()\n shape0[\"points\"] = shape0[\"points\"] + shape0[\"points\"][:2]\n shape1[\"points\"] = shape1[\"points\"] + shape1[\"points\"][:2]\n\n distance = shape1[\"frame\"] - shape0[\"frame\"]\n for frame in range(shape0[\"frame\"] + 1, shape1[\"frame\"]):\n offset = (frame - shape0[\"frame\"]) / distance\n points = interpolate_position(shape0, shape1, offset)\n\n if included_frames is None or frame in included_frames:\n shapes.append(copy_shape(shape0, frame, points))\n\n if is_polygon:\n # Remove the extra point added\n shape0[\"points\"] = shape0[\"points\"][:-2]\n shape1[\"points\"] = shape1[\"points\"][:-2]\n for shape in shapes:\n shape[\"points\"] = shape[\"points\"][:-2]\n\n return shapes\n\n def interpolate(shape0, shape1):\n is_same_type = shape0[\"type\"] == shape1[\"type\"]\n is_rectangle = shape0[\"type\"] == ShapeType.RECTANGLE\n is_ellipse = shape0[\"type\"] == ShapeType.ELLIPSE\n is_cuboid = shape0[\"type\"] == ShapeType.CUBOID\n is_polygon = shape0[\"type\"] == ShapeType.POLYGON\n is_polyline = shape0[\"type\"] == ShapeType.POLYLINE\n is_points = shape0[\"type\"] == ShapeType.POINTS\n is_skeleton = shape0[\"type\"] == ShapeType.SKELETON\n\n if not is_same_type:\n raise NotImplementedError()\n\n shapes = []\n if dimension == DimensionType.DIM_3D:\n shapes = simple_3d_interpolation(shape0, shape1)\n if is_rectangle or is_cuboid or is_ellipse or is_skeleton:\n shapes = simple_interpolation(shape0, shape1)\n elif is_points:\n shapes = points_interpolation(shape0, shape1)\n elif is_polygon or is_polyline:\n shapes = polyshape_interpolation(shape0, shape1)\n else:\n raise NotImplementedError()\n\n return shapes\n\n def propagate(shape, end_frame, *, included_frames=None):\n return [\n copy_shape(shape, i)\n for i in range(shape[\"frame\"] + 1, end_frame)\n if included_frames is None or i in included_frames\n ]\n\n shapes = []\n prev_shape = None\n for shape in sorted(track[\"shapes\"], key=lambda shape: shape[\"frame\"]):\n curr_frame = shape[\"frame\"]\n if prev_shape and end_frame <= curr_frame:\n # If we exceed the end_frame and there was a previous shape,\n # we still need to interpolate up to the next keyframe,\n # but keep the results only up to the end_frame:\n # vvvvvvv\n # ---- | ------- | ----- | ----->\n # prev end cur kf\n interpolated = interpolate(prev_shape, shape)\n interpolated.append(shape)\n\n for shape in sorted(interpolated, key=lambda shape: shape[\"frame\"]):\n if shape[\"frame\"] < end_frame:\n shapes.append(shape)\n else:\n break\n\n # Update the last added shape\n shape[\"keyframe\"] = True\n prev_shape = shape\n\n break # The track finishes here\n\n if prev_shape:\n assert curr_frame > prev_shape[\"frame\"], f\"{curr_frame} > {prev_shape['frame']}. Track id: {track['id']}\" # Catch invalid tracks\n\n # Propagate attributes\n for attr in prev_shape[\"attributes\"]:\n if attr[\"spec_id\"] not in map(lambda el: el[\"spec_id\"], shape[\"attributes\"]):\n shape[\"attributes\"].append(faster_deepcopy(attr))\n\n if not prev_shape[\"outside\"] or include_outside:\n shapes.extend(interpolate(prev_shape, shape))\n\n shape[\"keyframe\"] = True\n shapes.append(shape)\n prev_shape = shape\n\n if prev_shape and (not prev_shape[\"outside\"] or include_outside):\n # When the latest keyframe of a track is less than the end_frame\n # and it is not outside, need to propagate\n shapes.extend(propagate(prev_shape, end_frame, included_frames=included_frames))\n\n shapes = [\n shape for shape in shapes\n\n # After interpolation there can be a finishing frame\n # outside of the task boundaries. Filter it out to avoid errors.\n # https://github.com/openvinotoolkit/cvat/issues/2827\n if track[\"frame\"] <= shape[\"frame\"] < end_frame\n\n # Exclude outside shapes.\n # Keyframes should be included regardless the outside value\n # If really needed, they can be excluded on the later stages,\n # but here they represent a finishing shape in a visible sequence\n if shape[\"keyframe\"] or not shape[\"outside\"] or include_outside\n\n if included_frames is None or shape[\"frame\"] in included_frames\n ]\n\n return shapes", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def test_primitives_included_in_header(self) -> None:\n base_dir = os.path.join(os.path.dirname(__file__), \"..\", \"lib-rt\")\n with open(os.path.join(base_dir, \"CPy.h\")) as f:\n header = f.read()\n with open(os.path.join(base_dir, \"pythonsupport.h\")) as f:\n header += f.read()\n\n def check_name(name: str) -> None:\n if name.startswith(\"CPy\"):\n assert re.search(\n rf\"\\b{name}\\b\", header\n ), f'\"{name}\" is used in mypyc.primitives but not declared in CPy.h'\n\n for old_values in [\n registry.method_call_ops.values(),\n registry.function_ops.values(),\n registry.unary_ops.values(),\n ]:\n for old_ops in old_values:\n if isinstance(old_ops, CFunctionDescription):\n old_ops = [old_ops]\n for old_op in old_ops:\n check_name(old_op.c_function_name)\n\n for values in [registry.binary_ops.values()]:\n for ops in values:\n if isinstance(ops, PrimitiveDescription):\n ops = [ops]\n for op in ops:\n if op.c_function_name is not None:\n check_name(op.c_function_name)\n\n primitives_path = os.path.join(os.path.dirname(__file__), \"..\", \"primitives\")\n for fnam in glob.glob(f\"{primitives_path}/*.py\"):\n with open(fnam) as f:\n content = f.read()\n for name in re.findall(r'c_function_name=[\"\\'](CPy[A-Z_a-z0-9]+)', content):\n check_name(name)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def copyFile(self):\n\t\tif self.filelist.getServiceRef().type == 4098: # playlist\n\t\t\tServiceRef = self.filelist.getServiceRef()\n\t\t\textension = ServiceRef.getPath()[ServiceRef.getPath().rfind('.') + 1:]\n\t\t\tif extension in self.playlistparsers:\n\t\t\t\tplaylist = self.playlistparsers[extension]()\n\t\t\t\tlist = playlist.open(ServiceRef.getPath())\n\t\t\t\tfor x in list:\n\t\t\t\t\tself.playlist.addFile(x.ref)\n\t\t\tself.playlist.updateList()\n\t\t# check if MerlinMusicPlayer is installed and merlinmp3player.so is running\n\t\t# so we need the right id to play now the mp3-file\n\t\telif self.filelist.getServiceRef().type == 4116:\n\t\t\tif self.filelist.getSelection() is not None:\n\t\t\t\tinst = self.filelist.getSelection()[0]\n\t\t\t\tif isinstance(inst, eServiceReference):\n\t\t\t\t\tpath = inst.getPath()\n\t\t\t\t\tservice = eServiceReference(4097, 0, path)\n\t\t\t\t\tself.playlist.addFile(service)\n\t\t\t\t\tself.playlist.updateList()\n\t\t\t\t\tif len(self.playlist) == 1:\n\t\t\t\t\t\tself.changeEntry(0)\n\t\telse:\n\t\t\tself.playlist.addFile(self.filelist.getServiceRef())\n\t\t\tself.playlist.updateList()\n\t\t\tif len(self.playlist) == 1:\n\t\t\t\tself.changeEntry(0)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def collect_nodes(self, expression: RefExpr) -> list[FuncBase | SymbolNode]:\n \"\"\"Collect nodes that can be referred to by an expression.\n\n Note: it can be more than one for example in case of a union attribute.\n \"\"\"\n node: FuncBase | SymbolNode | None = expression.node\n nodes: list[FuncBase | SymbolNode]\n if node is None:\n # Tricky case: instance attribute\n if isinstance(expression, MemberExpr) and expression.kind is None:\n base_type = self.fg_manager.manager.all_types.get(expression.expr)\n if base_type is None:\n return []\n\n # Now we use the base type to figure out where the attribute is defined.\n base_type = get_proper_type(base_type)\n instances = get_instance_fallback(base_type)\n nodes = []\n for instance in instances:\n node = find_node(expression.name, instance.type)\n if node:\n nodes.append(node)\n if not nodes:\n # Try checking class namespace if attribute is on a class object.\n if isinstance(base_type, FunctionLike) and base_type.is_type_obj():\n instances = get_instance_fallback(\n fill_typevars_with_any(base_type.type_object())\n )\n for instance in instances:\n node = find_node(expression.name, instance.type)\n if node:\n nodes.append(node)\n else:\n # Still no luck, give up.\n return []\n else:\n return []\n else:\n # Easy case: a module-level definition\n nodes = [node]\n return nodes", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@cached\n\tdef getText(self):\n\t\tseek = self.getSeek()\n\t\tif seek is None:\n\t\t\treturn \"\"\n\t\tif self.type in (self.TYPE_SUMMARY, self.TYPE_ENDTIME):\n\t\t\tsVal = self.position / 90000\n\t\t\teVal = (self.length / 90000) - sVal\n\t\t\tif self.type == self.TYPE_SUMMARY:\n\t\t\t\treturn \"%02d:%02d +%2dm\" % (sVal / 60, sVal % 60, eVal / 60)\n\t\t\telse:\n\t\t\t\tif self.showNoSeconds or self.showNoSeconds2:\n\t\t\t\t\treturn strftime(\"%H:%M\", localtime(getTime() + eVal))\n\t\t\t\telse:\n\t\t\t\t\treturn strftime(\"%H:%M:%S\", localtime(getTime() + eVal))\n\n\t\tlVal = self.length\n\t\tpVal = self.position\n\t\trVal = self.length - self.position # Remaining\n\n\t\tif lVal < 0:\n\t\t\treturn \"\"\n\n\t\tif not self.detailed:\n\t\t\tlVal /= 90000\n\t\t\tpVal /= 90000\n\t\t\trVal /= 90000\n\n\t\tif lVal == 0 and pVal > 0: # Set position to 0 if length = 0 and pos > 0\n\t\t\tpVal = 0\n\n\t\tif self.negate:\n\t\t\tlVal = -lVal\n\t\t\tpVal = -pVal\n\t\t\trVal = -rVal\n\n\t\tif lVal >= 0:\n\t\t\tsign_l = \"\"\n\t\telse:\n\t\t\tlVal = -lVal\n\t\t\tsign_l = \"-\"\n\n\t\tif pVal >= 0:\n\t\t\tsign_p = \"\"\n\t\telse:\n\t\t\tpVal = -pVal\n\t\t\tsign_p = \"-\"\n\n\t\tif rVal >= 0:\n\t\t\tsign_r = \"\"\n\t\telse:\n\t\t\trVal = -rVal\n\t\t\tsign_r = \"-\"\n\n\t\tif self.type < self.TYPE_VFD_LENGTH:\n\t\t\tif config.usage.elapsed_time_positive_osd.value:\n\t\t\t\tsign_p = \"+\"\n\t\t\t\tsign_r = \"-\"\n\t\t\t\tsign_l = \"\"\n\t\t\telse:\n\t\t\t\tsign_p = \"-\"\n\t\t\t\tsign_r = \"+\"\n\t\t\t\tsign_l = \"\"\n\n\t\t\tif config.usage.swap_media_time_display_on_osd.value == \"1\": # Mins\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (lVal / 60)) % (lVal / 60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d \" % (pVal / 60) + sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d \" % (rVal / 60) + sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"2\": # Mins Secs\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 60, lVal % 60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (pVal / 60, pVal % 60) + sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (rVal / 60, rVal % 60) + sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"3\": # Hours Mins\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (pVal / 3600, pVal % 3600 / 60) + sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (rVal / 3600, rVal % 3600 / 60) + sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"4\": # Hours Mins Secs\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (lVal / 3600, lVal % 3600 / 60, lVal % 60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d \" % (pVal / 3600, pVal % 3600 / 60, pVal % 60) + sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d \" % (rVal / 3600, rVal % 3600 / 60, rVal % 60) + sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"5\": # Percentage\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%% \" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100) + sign_r + \"%d%%\" % ((float(rVal + 0.0) / float(lVal + 0.0)) * 100 + 1)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%% \" % ((float(rVal + 0.0) / float(lVal + 0.0)) * 100 + 1) + sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t# test = 0\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Elapsed & Remaining\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\n\t\t\telse: # Skin Setting\n\t\t\t\tif not self.detailed:\n\t\t\t\t\tif not self.vfd:\n\t\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\t\tif self.showNoSeconds or self.showNoSeconds2:\n\t\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (lVal / 3600, lVal % 3600 / 60, lVal % 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (lVal / 60)) % (lVal / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING and self.OnlyMinute:\n\t\t\t\t\t\t\t\t\treturn ngettext(\"%d\", \"%d\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\t\t\telif self.showNoSeconds2:\n\t\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (lVal / 60)) % (lVal / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING and self.OnlyMinute:\n\t\t\t\t\t\t\t\t\tif config.usage.elapsed_time_positive_vfd.value:\n\t\t\t\t\t\t\t\t\t\tmyRestMinuten = \"%+6d\" % (rVal / 60)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tmyRestMinuten = \"%+6d\" % (rVal / 60 * -1)\n\t\t\t\t\t\t\t\t\tif (rVal / 60) == 0:\n\t\t\t\t\t\t\t\t\t\tmyRestMinuten = \" \"\n\t\t\t\t\t\t\t\t\ttime = getTime()\n\t\t\t\t\t\t\t\t\tt = localtime(time)\n\t\t\t\t\t\t\t\t\td = _(\"%-H:%M\")\n\t\t\t\t\t\t\t\t\treturn strftime(d, t) + myRestMinuten\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 60, lVal % 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\tf = rVal / 60\n\t\t\t\t\t\tif f < 60:\n\t\t\t\t\t\t\tsVal = rVal % 60\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tf /= 60\n\t\t\t\t\t\t\tsVal = rVal % 3600 / 60\n\t\t\t\t\t\treturn \"%2d:%02d\" % (f, sVal)\n\t\t\t\telse:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d:%03d\" % ((lVal / 3600 / 90000), (lVal / 90000) % 3600 / 60, (lVal / 90000) % 60, (lVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d:%03d\" % ((rVal / 3600 / 90000), (rVal / 90000) % 3600 / 60, (rVal / 90000) % 60, (rVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d:%03d\" % ((pVal / 3600 / 90000), (pVal / 90000) % 3600 / 60, (pVal / 90000) % 60, (pVal % 90000) / 90)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%03d\" % ((lVal / 60 / 90000), (lVal / 90000) % 60, (lVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%03d\" % ((pVal / 60 / 90000), (pVal / 90000) % 60, (pVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%03d\" % ((rVal / 60 / 90000), (rVal / 90000) % 60, (rVal % 90000) / 90)\n\t\telse:\n\t\t\tif config.usage.elapsed_time_positive_vfd.value:\n\t\t\t\tsign_p = \"+\"\n\t\t\t\tsign_r = \"-\"\n\t\t\telse:\n\t\t\t\tsign_p = \"-\"\n\t\t\t\tsign_r = \"+\"\n\t\t\tif config.usage.swap_media_time_display_on_vfd.value == \"1\": # Mins\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (lVal / 60)) % (lVal / 60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d \" % (pVal / 60) + sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d \" % (rVal / 60) + sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"2\": # Mins Secs\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 60, lVal % 60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (pVal / 60, pVal % 60) + sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (rVal / 60, rVal % 60) + sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"3\": # Hours Mins\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (pVal / 3600, pVal % 3600 / 60) + sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (rVal / 3600, rVal % 3600 / 60) + sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"4\": # Hours Mins Secs\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (lVal / 3600, lVal % 3600 / 60, lVal % 60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d \" % (pVal / 3600, pVal % 3600 / 60, pVal % 60) + sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d \" % (rVal / 3600, rVal % 3600 / 60, rVal % 60) + sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"5\": # Percentage\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%% \" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100) + sign_r + \"%d%%\" % ((float(rVal + 0.0) / float(lVal + 0.0)) * 100 + 1)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%% \" % ((float(rVal + 0.0) / float(lVal + 0.0)) * 100 + 1) + sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\t# test = 0\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Elapsed & Remaining\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(pVal + 0.0) / float(lVal + 0.0)) * 100)\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\treturn \"\"\n\n\t\t\telse: # Skin Setting\n\t\t\t\tif not self.detailed:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 3600, pVal % 3600 / 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 3600, rVal % 3600 / 60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (lVal / 3600, lVal % 3600 / 60, lVal % 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (pVal / 3600, pVal % 3600 / 60, pVal % 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (rVal / 3600, rVal % 3600 / 60, rVal % 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (lVal / 60)) % (lVal / 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (pVal / 60)) % (pVal / 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (rVal / 60)) % (rVal / 60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (lVal / 60, lVal % 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (pVal / 60, pVal % 60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (rVal / 60, rVal % 60)\n\t\t\t\telse:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d:%03d\" % ((lVal / 3600 / 90000), (lVal / 90000) % 3600 / 60, (lVal / 90000) % 60, (lVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d:%03d\" % ((rVal / 3600 / 90000), (rVal / 90000) % 3600 / 60, (rVal / 90000) % 60, (rVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d:%03d\" % ((pVal / 3600 / 90000), (pVal / 90000) % 3600 / 60, (pVal / 90000) % 60, (pVal % 90000) / 90)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%03d\" % ((lVal / 60 / 90000), (lVal / 90000) % 60, (lVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%03d\" % ((pVal / 60 / 90000), (pVal / 90000) % 60, (pVal % 90000) / 90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%03d\" % ((rVal / 60 / 90000), (rVal / 90000) % 60, (rVal % 90000) / 90)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def changeBouquet(self, direction):\n\t\tif not self.pathChangeDisabled:\n\t\t\tif len(self.servicePath) > 1:\n\t\t\t\tref = serviceRefAppendPath(self.service_types_ref, \" FROM SATELLITES ORDER BY satellitePosition\")\n\t\t\t\tif self.isBasePathEqual(ref):\n\t\t\t\t\tself.showSatellites()\n\t\t\t\telse:\n\t\t\t\t\tself.pathUp()\n\t\t\t\tif direction < 0:\n\t\t\t\t\tself.servicelist.goLineUp()\n\t\t\t\telse:\n\t\t\t\t\tself.servicelist.goLineDown()\n\t\t\t\tref = self.getCurrentSelection()\n\t\t\t\tself.enterPath(ref)\n\t\t\t\tprev = None\n\t\t\t\troot = self.getRoot()\n\t\t\t\tfor path in self.history:\n\t\t\t\t\tif len(path) > 2 and path[1] == root:\n\t\t\t\t\t\tprev = path[2]\n\t\t\t\tif prev is not None:\n\t\t\t\t\tself.setCurrentSelection(prev)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _normalize_host(host, scheme):\n if host:\n if isinstance(host, six.binary_type):\n host = six.ensure_str(host)\n\n if scheme in NORMALIZABLE_SCHEMES:\n is_ipv6 = IPV6_ADDRZ_RE.match(host)\n if is_ipv6:\n # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as\n # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID\n # separator as necessary to return a valid RFC 4007 scoped IP.\n match = ZONE_ID_RE.search(host)\n if match:\n start, end = match.span(1)\n zone_id = host[start:end]\n\n if zone_id.startswith(\"%25\") and zone_id != \"%25\":\n zone_id = zone_id[3:]\n else:\n zone_id = zone_id[1:]\n zone_id = \"%\" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS)\n return host[:start].lower() + zone_id + host[end:]\n else:\n return host.lower()\n elif not IPV4_RE.match(host):\n return six.ensure_str(\n b\".\".join([_idna_encode(label) for label in host.split(\".\")])\n )\n return host", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def __init__(self, session):\n\t\tScreen.__init__(self, session)\n\t\tScreen.setTitle(self, _(\"Automatic Scan\"))\n\n\t\tself[\"key_red\"] = StaticText(_(\"Close\"))\n\t\tself[\"key_green\"] = StaticText(_(\"Scan\"))\n\n\t\tself[\"actions\"] = ActionMap([\"SetupActions\", \"MenuActions\", \"ColorActions\"],\n\t\t{\n\t\t\t\"ok\": self.keyGo,\n\t\t\t\"save\": self.keyGo,\n\t\t\t\"cancel\": self.keyCancel,\n\t\t\t\"menu\": self.doCloseRecursive,\n\t\t\t\"red\": self.keyCancel,\n\t\t\t\"green\": self.keyGo,\n\t\t}, -2)\n\n\t\tself.session.postScanService = session.nav.getCurrentlyPlayingServiceOrGroup()\n\n\t\tself.list = []\n\t\ttlist = []\n\n\t\tknown_networks = []\n\t\tnims_to_scan = set()\n\t\tself.finished_cb = None\n\n\t\t#collect networks\n\t\tnetworks = {}\n\t\tfor nim in nimmanager.nim_slots:\n\n\t\t\tif nim.canBeCompatible(\"DVB-S\") and nim.config.dvbs.configMode.value != \"nothing\":\n\t\t\t\tnew_network = nimmanager.getSatListForNim(nim.slot)\n\t\t\t\tknown = networks.get(\"DVB-S\", set())\n\t\t\t\tknown2 = networks.get(\"DVB-S2\", set())\n\t\t\t\tfor x in new_network:\n\t\t\t\t\tnims_to_scan.add(nim)\n\t\t\t\t\tif nim.canBeCompatible(\"DVB-S2\"):\n\t\t\t\t\t\tknown2.add(x)\n\t\t\t\t\telse:\n\t\t\t\t\t\tknown.add(x)\n\t\t\t\tnetworks.update({\"DVB-S2\": known2})\n\t\t\t\tnetworks.update({\"DVB-S\": known})\n\n\t\t\tif nim.canBeCompatible(\"DVB-T\") and nim.config.dvbt.configMode.value != \"nothing\":\n\t\t\t\tnew_network = [nimmanager.getTerrestrialDescription(nim.slot)]\n\t\t\t\tknown = networks.get(\"DVB-T\", set())\n\t\t\t\tknown2 = networks.get(\"DVB-T2\", set())\n\t\t\t\tfor x in new_network:\n\t\t\t\t\tnims_to_scan.add(nim)\n\t\t\t\t\tif nim.canBeCompatible(\"DVB-T2\"):\n\t\t\t\t\t\tknown2.add(x)\n\t\t\t\t\telse:\n\t\t\t\t\t\tknown.add(x)\n\t\t\t\tnetworks.update({\"DVB-T2\": known2})\n\t\t\t\tnetworks.update({\"DVB-T\": known})\n\n\t\t\tif nim.canBeCompatible(\"DVB-C\") and nim.config.dvbc.configMode.value != \"nothing\":\n\t\t\t\tnew_network = [nimmanager.getCableDescription(nim.slot)]\n\t\t\t\tknown = networks.get(\"DVB-C\", set())\n\t\t\t\tknown2 = networks.get(\"DVB-C2\", set())\n\t\t\t\tfor x in new_network:\n\t\t\t\t\tnims_to_scan.add(nim)\n\t\t\t\t\tif nim.canBeCompatible(\"DVB-C2\"):\n\t\t\t\t\t\tknown2.add(x)\n\t\t\t\t\telse:\n\t\t\t\t\t\tknown.add(x)\n\t\t\t\tnetworks.update({\"DVB-C2\": known2})\n\t\t\t\tnetworks.update({\"DVB-C\": known})\n\n\t\t\tif nim.canBeCompatible(\"ATSC\") and nim.config.atsc.configMode.value != \"nothing\":\n\t\t\t\tnew_network = [nimmanager.getATSCDescription(nim.slot)]\n\t\t\t\tknown = networks.get(\"ATSC\", set())\n\t\t\t\tfor x in new_network:\n\t\t\t\t\tnims_to_scan.add(nim)\n\t\t\t\t\tknown.add(x)\n\t\t\t\tnetworks.update({\"ATSC\": known})\n\n#\t\t\tif not nim.empty and not (nim.canBeCompatible(\"DVB-S\") or nim.canBeCompatible(\"DVB-C\") or nim.canBeCompatible(\"DVB-S\")):\n#\t\t\t\tprint\"unsupported nim type %s\" % nim.type\n#\t\t\t\tnetworks += [nim.type]\n\n\t\tknown = networks.get(\"DVB-S\", set()) - networks.get(\"DVB-S2\", set())\n\t\tnetworks.update({\"DVB-S\": known})\n\t\tknown = networks.get(\"DVB-T\", set()) - networks.get(\"DVB-T2\", set())\n\t\tnetworks.update({\"DVB-T\": known})\n\t\tknown = networks.get(\"DVB-C\", set()) - networks.get(\"DVB-C2\", set())\n\t\tnetworks.update({\"DVB-C\": known})\n\t\tknown = networks.get(\"ATSC\", set())\n\t\tnetworks.update({\"ATSC\": known})\n\n\t\t# we save the config elements to use them on keyGo\n\t\tself.nim_enable = []\n\n\t\tif len(nims_to_scan):\n\t\t\tself.scan_networkScan = ConfigYesNo(default=True)\n\t\t\tself.scan_clearallservices = ConfigSelection(default=\"yes\", choices=[(\"no\", _(\"No\")), (\"yes\", _(\"Yes\")), (\"yes_hold_feeds\", _(\"yes (keep feeds)\"))])\n\t\t\tself.list.append(getConfigListEntry(_(\"Network scan\"), self.scan_networkScan))\n\t\t\tself.list.append(getConfigListEntry(_(\"Clear before scan\"), self.scan_clearallservices))\n\n\t\t\t#assign nims\n\t\t\ttag_dvbc_default = tag_dvbt_default = tag_dvbs_default = tag_atsc_default = True\n\t\t\tfor item in networks.items():\n\t\t\t\treq_type = item[0]\n\t\t\t\tfor req_network in item[1]:\n\t\t\t\t\tfor nim in nimmanager.nim_slots:\n\t\t\t\t\t\ttag_dvbc = tag_dvbt = tag_dvbs = tag_atsc = False\n\t\t\t\t\t\tif not nim.canBeCompatible(req_type):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tif req_type in (\"DVB-S\", \"DVB-S2\") and nim.config.dvbs.configMode.value != \"nothing\" and not tag_dvbs:\n\t\t\t\t\t\t\tif req_network in nimmanager.getSatListForNim(nim.slot):\n\t\t\t\t\t\t\t\ttag_dvbs = True\n\t\t\t\t\t\t\t\tnimconfig = ConfigYesNo(default=tag_dvbs_default)\n\t\t\t\t\t\t\t\tif tag_dvbs_default is True:\n\t\t\t\t\t\t\t\t\ttag_dvbs_default = False\n\t\t\t\t\t\t\t\tnimconfig.nim_index = nim.slot\n\t\t\t\t\t\t\t\tnimconfig.network = req_network\n\t\t\t\t\t\t\t\tnimconfig.nim_type = \"DVB-S\"\n\t\t\t\t\t\t\t\tself.nim_enable.append(nimconfig)\n\t\t\t\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Scan \") + nim.slot_name + \" (DVB-S) \" + req_network[1], nimconfig))\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif req_type in (\"DVB-C\", \"DVB-C2\") and nim.config.dvbc.configMode.value != \"nothing\" and not tag_dvbc:\n\t\t\t\t\t\t\tif req_network in nimmanager.getCableDescription(nim.slot):\n\t\t\t\t\t\t\t\ttag_dvbc = True\n\t\t\t\t\t\t\t\tnimconfig = ConfigYesNo(default=tag_dvbc_default)\n\t\t\t\t\t\t\t\tif tag_dvbc_default is True:\n\t\t\t\t\t\t\t\t\ttag_dvbc_default = False\n\t\t\t\t\t\t\t\tnimconfig.nim_index = nim.slot\n\t\t\t\t\t\t\t\tnimconfig.network = req_network\n\t\t\t\t\t\t\t\tnimconfig.nim_type = \"DVB-C\"\n\t\t\t\t\t\t\t\tself.nim_enable.append(nimconfig)\n\t\t\t\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Scan \") + nim.slot_name + \" (DVB-C) \" + req_network[:45], nimconfig))\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif req_type in (\"DVB-T\", \"DVB-T2\") and nim.config.dvbt.configMode.value != \"nothing\" and not tag_dvbt:\n\t\t\t\t\t\t\tif req_network in nimmanager.getTerrestrialDescription(nim.slot):\n\t\t\t\t\t\t\t\ttag_dvbt = True\n\t\t\t\t\t\t\t\tnimconfig = ConfigYesNo(default=tag_dvbt_default)\n\t\t\t\t\t\t\t\tif tag_dvbt_default is True:\n\t\t\t\t\t\t\t\t\ttag_dvbt_default = False\n\t\t\t\t\t\t\t\tnimconfig.nim_index = nim.slot\n\t\t\t\t\t\t\t\tnimconfig.network = req_network\n\t\t\t\t\t\t\t\tnimconfig.nim_type = \"DVB-T\"\n\t\t\t\t\t\t\t\tself.nim_enable.append(nimconfig)\n\t\t\t\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Scan \") + nim.slot_name + \" (DVB-T) \" + req_network[:45], nimconfig))\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif req_type in (\"ATSC\") and nim.config.atsc.configMode.value != \"nothing\" and not tag_atsc:\n\t\t\t\t\t\t\tif req_network in nimmanager.getATSCDescription(nim.slot):\n\t\t\t\t\t\t\t\ttag_atsc = True\n\t\t\t\t\t\t\t\tnimconfig = ConfigYesNo(default=tag_atsc_default)\n\t\t\t\t\t\t\t\tif tag_atsc_default is True:\n\t\t\t\t\t\t\t\t\ttag_atsc_default = False\n\t\t\t\t\t\t\t\tnimconfig.nim_index = nim.slot\n\t\t\t\t\t\t\t\tnimconfig.network = req_network\n\t\t\t\t\t\t\t\tnimconfig.nim_type = \"ATSC\"\n\t\t\t\t\t\t\t\tself.nim_enable.append(nimconfig)\n\t\t\t\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Scan \") + nim.slot_name + \" (ATSC) \" + req_network[:45], nimconfig))\n\t\t\t\t\t\t\t\tbreak\n\t\tself.list.sort()\n\t\tConfigListScreen.__init__(self, self.list)\n\t\tself[\"header\"] = Label(_(\"Automatic Scan\"))\n\t\tself[\"footer\"] = Label(_(\"Press OK to scan\"))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def compatible_platforms(provided, required):\n \"\"\"Can code for the `provided` platform run on the `required` platform?\n\n Returns true if either platform is ``None``, or the platforms are equal.\n\n XXX Needs compatibility checks for Linux and other unixy OSes.\n \"\"\"\n if provided is None or required is None or provided == required:\n # easy case\n return True\n\n # macOS special cases\n reqMac = macosVersionString.match(required)\n if reqMac:\n provMac = macosVersionString.match(provided)\n\n # is this a Mac package?\n if not provMac:\n # this is backwards compatibility for packages built before\n # setuptools 0.6. All packages built after this point will\n # use the new macOS designation.\n provDarwin = darwinVersionString.match(provided)\n if provDarwin:\n dversion = int(provDarwin.group(1))\n macosversion = \"%s.%s\" % (reqMac.group(1), reqMac.group(2))\n if (\n dversion == 7\n and macosversion >= \"10.3\"\n or dversion == 8\n and macosversion >= \"10.4\"\n ):\n return True\n # egg isn't macOS or legacy darwin\n return False\n\n # are they the same major version and machine type?\n if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):\n return False\n\n # is the required OS major update >= the provided one?\n if int(provMac.group(2)) > int(reqMac.group(2)):\n return False\n\n return True\n\n # XXX Linux and other platforms' special cases should go here\n return False", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def get_search_results(self, request, queryset, search_term):\n \"\"\"\n Return a tuple containing a queryset to implement the search\n and a boolean indicating if the results may contain duplicates.\n \"\"\"\n\n # Apply keyword searches.\n def construct_search(field_name):\n if field_name.startswith(\"^\"):\n return \"%s__istartswith\" % field_name.removeprefix(\"^\")\n elif field_name.startswith(\"=\"):\n return \"%s__iexact\" % field_name.removeprefix(\"=\")\n elif field_name.startswith(\"@\"):\n return \"%s__search\" % field_name.removeprefix(\"@\")\n # Use field_name if it includes a lookup.\n opts = queryset.model._meta\n lookup_fields = field_name.split(LOOKUP_SEP)\n # Go through the fields, following all relations.\n prev_field = None\n for path_part in lookup_fields:\n if path_part == \"pk\":\n path_part = opts.pk.name\n try:\n field = opts.get_field(path_part)\n except FieldDoesNotExist:\n # Use valid query lookups.\n if prev_field and prev_field.get_lookup(path_part):\n return field_name\n else:\n prev_field = field\n if hasattr(field, \"path_infos\"):\n # Update opts to follow the relation.\n opts = field.path_infos[-1].to_opts\n # Otherwise, use the field with icontains.\n return \"%s__icontains\" % field_name\n\n may_have_duplicates = False\n search_fields = self.get_search_fields(request)\n if search_fields and search_term:\n orm_lookups = [\n construct_search(str(search_field)) for search_field in search_fields\n ]\n term_queries = []\n for bit in smart_split(search_term):\n if bit.startswith(('\"', \"'\")) and bit[0] == bit[-1]:\n bit = unescape_string_literal(bit)\n or_queries = models.Q.create(\n [(orm_lookup, bit) for orm_lookup in orm_lookups],\n connector=models.Q.OR,\n )\n term_queries.append(or_queries)\n queryset = queryset.filter(models.Q.create(term_queries))\n may_have_duplicates |= any(\n lookup_spawns_duplicates(self.opts, search_spec)\n for search_spec in orm_lookups\n )\n return queryset, may_have_duplicates", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def guess_lexer_for_filename(_fn, _text, **options):\n \"\"\"\n As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames`\n or `alias_filenames` that matches `filename` are taken into consideration.\n\n :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can\n handle the content.\n \"\"\"\n fn = basename(_fn)\n primary = {}\n matching_lexers = set()\n for lexer in _iter_lexerclasses():\n for filename in lexer.filenames:\n if _fn_matches(fn, filename):\n matching_lexers.add(lexer)\n primary[lexer] = True\n for filename in lexer.alias_filenames:\n if _fn_matches(fn, filename):\n matching_lexers.add(lexer)\n primary[lexer] = False\n if not matching_lexers:\n raise ClassNotFound('no lexer for filename %r found' % fn)\n if len(matching_lexers) == 1:\n return matching_lexers.pop()(**options)\n result = []\n for lexer in matching_lexers:\n rv = lexer.analyse_text(_text)\n if rv == 1.0:\n return lexer(**options)\n result.append((rv, lexer))\n\n def type_sort(t):\n # sort by:\n # - analyse score\n # - is primary filename pattern?\n # - priority\n # - last resort: class name\n return (t[0], primary[t[1]], t[1].priority, t[1].__name__)\n result.sort(key=type_sort)\n\n return result[-1][1](**options)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _check_dump_content(self, content, task, jobs, data, format_name):\n def etree_to_dict(t):\n d = {t.tag: {} if t.attrib else None}\n children = list(t)\n if children:\n dd = defaultdict(list)\n for dc in map(etree_to_dict, children):\n for k, v in dc.items():\n dd[k].append(v)\n d = {t.tag: {k: v[0] if len(v) == 1 else v\n for k, v in dd.items()}}\n if t.attrib:\n d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())\n if t.text:\n text = t.text.strip()\n if not (children or t.attrib):\n d[t.tag] = text\n return d\n\n if format_name in {\"CVAT for video 1.1\", \"CVAT for images 1.1\"}:\n with tempfile.TemporaryDirectory() as tmp_dir:\n zipfile.ZipFile(content).extractall(tmp_dir)\n xmls = glob(os.path.join(tmp_dir, '**', '*.xml'), recursive=True)\n self.assertTrue(xmls)\n for xml in xmls:\n xmlroot = ET.parse(xml).getroot()\n self.assertEqual(xmlroot.tag, \"annotations\")\n tags = xmlroot.findall(\"./meta\")\n self.assertEqual(len(tags), 1)\n meta = etree_to_dict(tags[0])[\"meta\"]\n self.assertEqual(meta[\"task\"][\"name\"], task[\"name\"])\n elif format_name == \"PASCAL VOC 1.1\":\n self.assertTrue(zipfile.is_zipfile(content))\n elif format_name in [\"YOLO 1.1\", \"YOLOv8 Detection 1.0\", \"YOLOv8 Segmentation 1.0\", \"YOLOv8 Oriented Bounding Boxes 1.0\", \"YOLOv8 Pose 1.0\"]:\n self.assertTrue(zipfile.is_zipfile(content))\n elif format_name in ['Kitti Raw Format 1.0','Sly Point Cloud Format 1.0']:\n self.assertTrue(zipfile.is_zipfile(content))\n elif format_name in [\"COCO 1.0\", \"COCO Keypoints 1.0\"]:\n with tempfile.TemporaryDirectory() as tmp_dir:\n zipfile.ZipFile(content).extractall(tmp_dir)\n jsons = glob(os.path.join(tmp_dir, '**', '*.json'), recursive=True)\n self.assertTrue(jsons)\n for json in jsons:\n coco = coco_loader.COCO(json)\n self.assertTrue(coco.getAnnIds())\n elif format_name == \"Segmentation mask 1.1\":\n self.assertTrue(zipfile.is_zipfile(content))", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def _merge_full_response(data, response):\n data[\"platform\"] = \"native\"\n # Specifically for Unreal events: Do not overwrite the level as it has already been set in Relay when merging the context.\n if response.get(\"crashed\") is not None and data.get(\"level\") is None:\n data[\"level\"] = \"fatal\" if response[\"crashed\"] else \"info\"\n\n if response.get(\"system_info\"):\n _merge_system_info(data, response[\"system_info\"])\n\n os = get_os_from_event(data)\n\n images: list[dict[str, Any]] = []\n set_path(data, \"debug_meta\", \"images\", value=images)\n\n for complete_image in response[\"modules\"]:\n image: dict[str, Any] = {}\n _merge_image(image, complete_image, os, data)\n images.append(image)\n\n # Extract the crash reason and infos\n data_exception = get_path(data, \"exception\", \"values\", 0)\n if response.get(\"assertion\"):\n data_exception[\"value\"] = \"Assertion Error: {}\".format(response[\"assertion\"])\n elif response.get(\"crash_details\"):\n data_exception[\"value\"] = response[\"crash_details\"]\n elif response.get(\"crash_reason\"):\n data_exception[\"value\"] = \"Fatal Error: {}\".format(response[\"crash_reason\"])\n else:\n # We're merging a full response, so there was no initial payload\n # submitted. Assuming that this still contains the placeholder, remove\n # it rather than showing a default value.\n data_exception.pop(\"value\", None)\n\n if response.get(\"crash_reason\"):\n data_exception[\"type\"] = response[\"crash_reason\"]\n\n data_threads: list[dict[str, Any]] = []\n if response[\"stacktraces\"]:\n data[\"threads\"] = {\"values\": data_threads}\n else:\n error = SymbolicationFailed(\n message=\"minidump has no thread list\", type=EventError.NATIVE_SYMBOLICATOR_FAILED\n )\n write_error(error, data)\n\n for complete_stacktrace in response[\"stacktraces\"]:\n is_requesting = complete_stacktrace.get(\"is_requesting\")\n thread_id = complete_stacktrace.get(\"thread_id\")\n thread_name = complete_stacktrace.get(\"thread_name\")\n\n data_thread = {\"id\": thread_id}\n if thread_name:\n data_thread[\"name\"] = thread_name\n\n if is_requesting:\n if response.get(\"crashed\"):\n data_thread[\"crashed\"] = True\n else:\n data_thread[\"current\"] = True\n data_threads.append(data_thread)\n\n if is_requesting:\n data_exception[\"thread_id\"] = thread_id\n data_stacktrace = data_exception.setdefault(\"stacktrace\", {})\n data_stacktrace[\"frames\"] = []\n else:\n data_thread[\"stacktrace\"] = data_stacktrace = {\"frames\": []}\n\n if complete_stacktrace.get(\"registers\"):\n data_stacktrace[\"registers\"] = complete_stacktrace[\"registers\"]\n\n for complete_frame in reversed(complete_stacktrace[\"frames\"]):\n new_frame: dict[str, Any] = {}\n _merge_frame(new_frame, complete_frame)\n data_stacktrace[\"frames\"].append(new_frame)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def resolve_condition(cond: list, column_resolver: Callable[[Any], Any]) -> list:\n \"\"\"\n When conditions have been parsed by the api.event_search module\n we can end up with conditions that are not valid on the current dataset\n due to how api.event_search checks for valid field names without\n being aware of the dataset.\n\n We have the dataset context here, so we need to re-scope conditions to the\n current dataset.\n\n cond (tuple) Condition to resolve aliases in.\n column_resolver (Function[string]) Function to resolve column names for the\n current dataset.\n \"\"\"\n index = get_function_index(cond)\n\n def _passthrough_arg(arg):\n if isinstance(arg, str):\n return f\"'{arg}'\"\n elif isinstance(arg, datetime):\n return f\"'{arg.isoformat()}'\"\n else:\n return arg\n\n # IN/NOT IN conditions are detected as a function but aren't really.\n if index is not None and cond[index] not in (\"IN\", \"NOT IN\"):\n if cond[index] in FUNCTION_TO_OPERATOR:\n func_args = cond[index + 1]\n for i, arg in enumerate(func_args):\n if i == 0:\n if isinstance(arg, list):\n func_args[i] = resolve_condition(arg, column_resolver)\n else:\n func_args[i] = column_resolver(arg)\n else:\n func_args[i] = _passthrough_arg(arg)\n\n cond[index + 1] = func_args\n return cond\n\n func_args = cond[index + 1]\n for i, arg in enumerate(func_args):\n # Nested function\n try:\n if isinstance(arg, list):\n func_args[i] = resolve_condition(arg, column_resolver)\n else:\n func_args[i] = column_resolver(arg)\n except AttributeError:\n func_args[i] = _passthrough_arg(arg)\n cond[index + 1] = func_args\n return cond\n\n # No function name found\n if isinstance(cond, (list, tuple)) and len(cond):\n # Condition is [col, operator, value]\n if isinstance(cond[0], str) and len(cond) == 3:\n cond[0] = column_resolver(cond[0])\n return cond\n if isinstance(cond[0], list):\n if get_function_index(cond[0]) is not None:\n cond[0] = resolve_condition(cond[0], column_resolver)\n return cond\n else:\n # Nested conditions\n return [resolve_condition(item, column_resolver) for item in cond]\n raise ValueError(\"Unexpected condition format %s\" % cond)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_result(self, results):\n # If we were passed an array we concat it to the results global\n if isinstance(results, list):\n self.results.append(results)\n # A single result is appended and then turned into an array\n else:\n self.results.append(results)\n results = [results]\n\n # Process all the results (may be just one)\n for result in results:\n self.puts(f\"{result.group}:{result.script}:{result.result}\")\n if result.message:\n for line in result.message.split(\"\\n\"):\n if re.search(r\"\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F\\x7F-\\xFF\", line):\n line = line.rstrip(\"\\n\")\n line = remove_quotes(repr(line))\n self._report.append(\" \" + line.strip())\n\n if result.exceptions:\n self._report.append(\" Exceptions:\")\n for _, error in enumerate(result.exceptions):\n self._report.append(\"\".join(traceback.format_exception(error)))", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def parse_call_args(self) -> t.Tuple:\n token = self.stream.expect(\"lparen\")\n args = []\n kwargs = []\n dyn_args = None\n dyn_kwargs = None\n require_comma = False\n\n def ensure(expr: bool) -> None:\n if not expr:\n self.fail(\"invalid syntax for function call expression\", token.lineno)\n\n while self.stream.current.type != \"rparen\":\n if require_comma:\n self.stream.expect(\"comma\")\n\n # support for trailing comma\n if self.stream.current.type == \"rparen\":\n break\n\n if self.stream.current.type == \"mul\":\n ensure(dyn_args is None and dyn_kwargs is None)\n next(self.stream)\n dyn_args = self.parse_expression()\n elif self.stream.current.type == \"pow\":\n ensure(dyn_kwargs is None)\n next(self.stream)\n dyn_kwargs = self.parse_expression()\n else:\n if (\n self.stream.current.type == \"name\"\n and self.stream.look().type == \"assign\"\n ):\n # Parsing a kwarg\n ensure(dyn_kwargs is None)\n key = self.stream.current.value\n self.stream.skip(2)\n value = self.parse_expression()\n kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))\n else:\n # Parsing an arg\n ensure(dyn_args is None and dyn_kwargs is None and not kwargs)\n args.append(self.parse_expression())\n\n require_comma = True\n\n self.stream.expect(\"rparen\")\n return args, kwargs, dyn_args, dyn_kwargs", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def buildInterfaceList(self, device, description, type, isinputdevice=True):\n\t\tdivpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_GUISKIN, \"div-h.png\"))\n\t\tactivepng = None\n\t\tdevicepng = None\n\t\tenabled = inputDevices.getDeviceAttribute(device, \"enabled\")\n\t\tif type == \"remote\":\n\t\t\tif config.misc.rcused.value == 0:\n\t\t\t\tif enabled:\n\t\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_rcnew-configured.png\"))\n\t\t\t\telse:\n\t\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_rcnew.png\"))\n\t\t\telse:\n\t\t\t\tif enabled:\n\t\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_rcold-configured.png\"))\n\t\t\t\telse:\n\t\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_rcold.png\"))\n\t\telif type == \"keyboard\":\n\t\t\tif enabled:\n\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_keyboard-configured.png\"))\n\t\t\telse:\n\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_keyboard.png\"))\n\t\telif type == \"mouse\":\n\t\t\tif enabled:\n\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_mouse-configured.png\"))\n\t\t\telse:\n\t\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_mouse.png\"))\n\t\telif isinputdevice:\n\t\t\tdevicepng = LoadPixmap(resolveFilename(SCOPE_GUISKIN, \"icons/input_rcnew.png\"))\n\t\treturn device, description, devicepng, divpng", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def updateSubPagePixmaps(self):\n\t\tservice = self.session.nav.getCurrentService()\n\t\tdecoder = service and service.rdsDecoder()\n\t\tif not decoder: # this should never happen\n\t\t\tprint(\"NO RDS DECODER in showRassPage\")\n\t\telse:\n\t\t\tmask = decoder.getRassInteractiveMask()\n\t\t\tpage = 1\n\t\t\twhile page < 10:\n\t\t\t\tsubpage_cnt = self.countAvailSubpages(page, mask)\n\t\t\t\tsubpage = self.subpage[page]\n\t\t\t\tif subpage_cnt > 0:\n\t\t\t\t\tif subpage.instance:\n\t\t\t\t\t\tpng = self.subpage_png[subpage_cnt]\n\t\t\t\t\t\tif png:\n\t\t\t\t\t\t\tsubpage.instance.setPixmap(png)\n\t\t\t\t\t\t\tsubpage.show()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"rass png missing\")\n\t\t\t\telse:\n\t\t\t\t\tsubpage.hide()\n\t\t\t\tpage += 1", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _detect_auto_attribs(ctx: mypy.plugin.ClassDefContext) -> bool:\n \"\"\"Return whether auto_attribs should be enabled or disabled.\n\n It's disabled if there are any unannotated attribs()\n \"\"\"\n for stmt in ctx.cls.defs.body:\n if isinstance(stmt, AssignmentStmt):\n for lvalue in stmt.lvalues:\n lvalues, rvalues = _parse_assignments(lvalue, stmt)\n\n if len(lvalues) != len(rvalues):\n # This means we have some assignment that isn't 1 to 1.\n # It can't be an attrib.\n continue\n\n for lhs, rvalue in zip(lvalues, rvalues):\n # Check if the right hand side is a call to an attribute maker.\n if (\n isinstance(rvalue, CallExpr)\n and isinstance(rvalue.callee, RefExpr)\n and rvalue.callee.fullname in attr_attrib_makers\n and not stmt.new_syntax\n ):\n # This means we have an attrib without an annotation and so\n # we can't do auto_attribs=True\n return False\n return True", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def visit_nonlocal_decl(self, d: NonlocalDecl) -> None:\n self.statement = d\n if self.is_module_scope():\n self.fail(\"nonlocal declaration not allowed at module level\", d)\n else:\n for name in d.names:\n for table, scope_type in zip(\n reversed(self.locals[:-1]), reversed(self.scope_stack[:-1])\n ):\n if table is not None and name in table:\n if scope_type == SCOPE_ANNOTATION:\n self.fail(\n f'nonlocal binding not allowed for type parameter \"{name}\"', d\n )\n break\n else:\n self.fail(f'No binding for nonlocal \"{name}\" found', d)\n\n if self.locals[-1] is not None and name in self.locals[-1]:\n self.fail(\n 'Name \"{}\" is already defined in local '\n \"scope before nonlocal declaration\".format(name),\n d,\n )\n\n if name in self.global_decls[-1]:\n self.fail(f'Name \"{name}\" is nonlocal and global', d)\n self.nonlocal_decls[-1].add(name)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def __init__(\n self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance\n ):\n self._tokdict: Dict[str, _ParseResultsWithOffset]\n self._modal = modal\n if name is not None and name != \"\":\n if isinstance(name, int):\n name = str(name)\n if not modal:\n self._all_names = {name}\n self._name = name\n if toklist not in self._null_values:\n if isinstance(toklist, (str_type, type)):\n toklist = [toklist]\n if asList:\n if isinstance(toklist, ParseResults):\n self[name] = _ParseResultsWithOffset(\n ParseResults(toklist._toklist), 0\n )\n else:\n self[name] = _ParseResultsWithOffset(\n ParseResults(toklist[0]), 0\n )\n self[name]._name = name\n else:\n try:\n self[name] = toklist[0]\n except (KeyError, TypeError, IndexError):\n if toklist is not self:\n self[name] = toklist\n else:\n self._name = name", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def simplevolume(flist, distances, voxel, g):\n \"\"\"estimate the volume by the fraction of interior points\"\"\"\n res = options.ics_partial_volume_resolution\n distance_threshold = options.ics_distance_threshold\n\n sx, sy, sz = g[\"dx\"] / res, g[\"dy\"] / res, g[\"dz\"] / res\n\n res1 = res + 1\n\n # count up the interior points on the boundary\n if res == 1:\n count = sum(1 if d <= distance_threshold else 0 for d in distances)\n\n else:\n vi, vj, vk = voxel\n startx, starty, startz = (\n g[\"xlo\"] + vi * g[\"dx\"],\n g[\"ylo\"] + vj * g[\"dy\"],\n g[\"zlo\"] + vk * g[\"dz\"],\n )\n\n count = 0\n for i in range(res1):\n vx = startx + i * sx\n for j in range(res1):\n vy = starty + j * sy\n for k in range(res1):\n vz = startz + k * sz\n if any(f.distance(vx, vy, vz) <= distance_threshold for f in flist):\n count += 1\n volume = count * g[\"dx\"] * g[\"dy\"] * g[\"dz\"] / (res1**3)\n return volume", "smellKey": "S3776", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def calcMoving(self):\n\t\tif self.txtext == \"\" or self.type == NONE or self.test_label is None:\n\t\t\treturn False\n\t\tself.test_label.setText(self.txtext)\n\t\ttext_size = self.test_label.calculateSize()\n\t\ttext_width = text_size.width()\n\t\ttext_height = text_size.height()\n\n#\t\tself.type =\t\t0 - NONE; 1 - RUNNING; 2 - SWIMMING; 3 - AUTO(???)\n#\t\tself.direction =\t0 - LEFT; 1 - RIGHT; 2 - TOP; 3 - BOTTOM\n#\t\tself.halign =\t\t0 - LEFT; 1 - RIGHT; 2 -CENTER; 3 - BLOCK\n\n\t\tif self.direction in (LEFT, RIGHT):\n\t\t\tif self.type == RUNNING:\t\t# scroll_type == RUNNING\n\t\t\t\tif not self.mAlways and text_width <= self.W:\n\t\t\t\t\treturn False\n\n\t\t\t\tself.A = self.X - text_width - self.soffset[0] - abs(self.mStep)\n\t\t\t\tself.B = self.W - self.soffset[0] + abs(self.mStep)\n\t\t\t\tif self.direction == LEFT:\t\t# direction == LEFT:\n\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\tself.mStop = self.X\n\t\t\t\t\tself.P = self.B\n\t\t\t\telse:\t\t\t\t\t# direction == RIGHT (arabic):\n\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\tself.mStop = self.B - text_width + self.soffset[0] - self.mStep\n\t\t\t\t\tself.P = self.A\n\n\t\t\t\tif self.mStartPoint is not None:\n\t\t\t\t\tif self.direction == LEFT:\n\t\t\t\t\t\t#self.P = min(self.B, max(self.A, self.mStartPoint))\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.W, self.mStartPoint))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.B, self.mStartPoint - text_width + self.soffset[0]))\n\n\t\t\telif self.type == SWIMMING: # scroll_type == SWIMMING\n\t\t\t\tif not self.mAlways and text_width <= self.W:\n\t\t\t\t\treturn False\n\t\t\t\tif text_width < self.W:\n\t\t\t\t\tif self.halign == LEFT:\n\t\t\t\t\t\tself.A = self.X + 1\n\t\t\t\t\t\tself.B = self.W - text_width - 1\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\telif self.halign == RIGHT:\n\t\t\t\t\t\tself.A = self.X + 1\n\t\t\t\t\t\tself.B = self.W - text_width - 1\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telse: # self.halign == CENTER or self.halign == BLOCK:\n\t\t\t\t\t\tself.A = self.X + 1\n\t\t\t\t\t\tself.B = self.W - text_width - 1\n\t\t\t\t\t\tself.P = int(self.B / 2)\n\t\t\t\t\t\tself.mStep = (self.direction == RIGHT) and abs(self.mStep) or -abs(self.mStep)\n\t\t\t\telif text_width > self.W:\n\t\t\t\t\tif self.halign == LEFT:\n\t\t\t\t\t\tself.A = self.W - text_width\n\t\t\t\t\t\tself.B = self.X\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telif self.halign == RIGHT:\n\t\t\t\t\t\tself.A = self.W - text_width\n\t\t\t\t\t\tself.B = self.X\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\telse: # self.halign == CENTER or self.halign == BLOCK:\n\t\t\t\t\t\tself.A = self.W - text_width\n\t\t\t\t\t\tself.B = self.X\n\t\t\t\t\t\tself.P = int(self.A / 2)\n\t\t\t\t\t\tself.mStep = (self.direction == RIGHT) and abs(self.mStep) or -abs(self.mStep)\n\t\t\t\telse: # if text_width == self.W\n\t\t\t\t\treturn False\n\t\t\telse:\t\t\t\t\t# scroll_type == NONE\n\t\t\t\treturn False\n\t\telif self.direction in (TOP, BOTTOM):\n\t\t\tif self.type == RUNNING:\t\t# scroll_type == RUNNING\n\t\t\t\tif not self.mAlways and text_height <= self.H:\n\t\t\t\t\treturn False\n\n\t\t\t\tself.A = self.Y - text_height - self.soffset[1] - abs(self.mStep) - 9\n\t\t\t\tself.B = self.H - self.soffset[1] + abs(self.mStep)\n\t\t\t\tif self.direction == TOP:\t\t# direction == TOP:\n\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\tself.mStop = self.Y\n\t\t\t\t\tself.P = self.B\n\t\t\t\telse:\t\t\t\t\t# direction == BOTTOM (arabic):\n\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\tself.mStop = self.B - text_height + self.soffset[1] - self.mStep - 9\n\t\t\t\t\tself.P = self.A\n\n\t\t\t\tif self.mStartPoint is not None:\n\t\t\t\t\tif self.direction == TOP:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.H, self.mStartPoint))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.B, self.mStartPoint - text_height + self.soffset[1] - 9))\n\n\t\t\telif self.type == SWIMMING: # scroll_type == SWIMMING\n\t\t\t\tif not self.mAlways and text_height <= self.H:\n\t\t\t\t\treturn False\n\t\t\t\tif text_height < self.H:\n\t\t\t\t\tif self.direction == TOP: # direction == TOP\n\t\t\t\t\t\tself.A = self.Y\n\t\t\t\t\t\tself.B = self.H - text_height\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telse:\t\t\t\t# direction == BOTTOM (arabic)\n\t\t\t\t\t\tself.A = self.Y\n\t\t\t\t\t\tself.B = self.H - text_height\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\telif text_height > self.H:\n\t\t\t\t\tif self.direction == TOP: # direction == TOP\n\t\t\t\t\t\tself.A = self.H - text_height - 8 # \" - 8\" added by vlamo (25.12.2010 17:59)\n\t\t\t\t\t\tself.B = self.Y\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telse:\t\t\t\t# direction == BOTTOM (arabic)\n\t\t\t\t\t\tself.A = self.H - text_height - 8 # \" - 8\" added by vlamo (25.12.2010 17:59)\n\t\t\t\t\t\tself.B = self.Y\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\telse: # if text_height == self.H\n\t\t\t\t\treturn False\n\t\t\telse:\t\t\t\t\t# scroll_type == NONE\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\n\t\tif self.mStartDelay:\n\t\t\tif self.direction in (LEFT, RIGHT):\n\t\t\t\tself.drawText(self.P, self.Y)\n\t\t\telse: # if self.direction in (TOP,BOTTOM)\n\t\t\t\tself.drawText(self.X, self.P)\n\t\tself.mCount = self.mRepeat\n\t\tself.mTimer.start(self.mStartDelay, True)\n\t\treturn True", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@csrf_exempt\n @allow_cors_options\n def dispatch(self, request: Request, *args, **kwargs) -> Response:\n \"\"\"\n Identical to rest framework's dispatch except we add the ability\n to convert arguments (for common URL params).\n \"\"\"\n with sentry_sdk.start_span(op=\"base.dispatch.setup\", name=type(self).__name__):\n self.args = args\n self.kwargs = kwargs\n request = self.initialize_request(request, *args, **kwargs)\n self.load_json_body(request)\n self.request = request\n self.headers = self.default_response_headers # deprecate?\n\n # Tags that will ultimately flow into the metrics backend at the end of\n # the request (happens via middleware/stats.py).\n request._metric_tags = {}\n\n start_time = time.time()\n\n origin = request.META.get(\"HTTP_ORIGIN\", \"null\")\n # A \"null\" value should be treated as no Origin for us.\n # See RFC6454 for more information on this behavior.\n if origin == \"null\":\n origin = None\n\n try:\n with sentry_sdk.start_span(op=\"base.dispatch.request\", name=type(self).__name__):\n if origin:\n if request.auth:\n allowed_origins = request.auth.get_allowed_origins()\n else:\n allowed_origins = None\n if not is_valid_origin(origin, allowed=allowed_origins):\n response = Response(f\"Invalid origin: {origin}\", status=400)\n self.response = self.finalize_response(request, response, *args, **kwargs)\n return self.response\n\n if request.auth:\n update_token_access_record(request.auth)\n\n self.initial(request, *args, **kwargs)\n\n # Get the appropriate handler method\n method = request.method.lower()\n if method in self.http_method_names and hasattr(self, method):\n handler = getattr(self, method)\n\n # Only convert args when using defined handlers\n (args, kwargs) = self.convert_args(request, *args, **kwargs)\n self.args = args\n self.kwargs = kwargs\n else:\n handler = self.http_method_not_allowed\n\n if getattr(request, \"access\", None) is None:\n # setup default access\n request.access = access.from_request(request)\n\n with sentry_sdk.start_span(\n op=\"base.dispatch.execute\",\n name=\".\".join(\n getattr(part, \"__name__\", None) or str(part) for part in (type(self), handler)\n ),\n ) as span:\n response = handler(request, *args, **kwargs)\n\n except Exception as exc:\n response = self.handle_exception(request, exc)\n\n if origin:\n self.add_cors_headers(request, response)\n\n self.response = self.finalize_response(request, response, *args, **kwargs)\n\n if settings.SENTRY_API_RESPONSE_DELAY:\n duration = time.time() - start_time\n\n if duration < (settings.SENTRY_API_RESPONSE_DELAY / 1000.0):\n with sentry_sdk.start_span(\n op=\"base.dispatch.sleep\",\n name=type(self).__name__,\n ) as span:\n span.set_data(\"SENTRY_API_RESPONSE_DELAY\", settings.SENTRY_API_RESPONSE_DELAY)\n time.sleep(settings.SENTRY_API_RESPONSE_DELAY / 1000.0 - duration)\n\n # Only enforced in dev environment\n if settings.ENFORCE_PAGINATION:\n if request.method.lower() == \"get\":\n status = getattr(self.response, \"status_code\", 0)\n # Response can either be Response or HttpResponse, check if\n # it's value is an array and that it was an OK response\n if (\n 200 <= status < 300\n and hasattr(self.response, \"data\")\n and isinstance(self.response.data, list)\n ):\n # if not paginated and not in settings.SENTRY_API_PAGINATION_ALLOWLIST, raise error\n if (\n handler.__self__.__class__.__name__\n not in settings.SENTRY_API_PAGINATION_ALLOWLIST\n and not self.has_pagination(self.response)\n ):\n raise MissingPaginationError(handler.__func__.__qualname__)\n return self.response", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def IntersectWithOneRay(self, inIndex, inRayStart, inRayDirection,\n ioRaycastOperation, inPointOrCellData):\n \"\"\"this is not used, but we are leaving it in as a reference for how to\n do a ray/triangle intersection directly\"\"\"\n if PhactoriDbg():\n myDebugPrint3(\n \"ray: \" + str(inIndex) + \" \" + str(inRayStart) + \" \" + \\\n str(inRayDirection) + \" \" + str(inPointOrCellData) + \"\\n\")\n\n ptA = [0.0,0.0,0.0]\n ptB = [0.0,0.0,0.0]\n ptC = [0.0,0.0,0.0]\n hitPoint = [0.0, 0.0, 0.0, 0.0]\n saveHit = [0.0, 0.0, 0.0, -1.0]\n #if PhactoriDbg():\n # myDebugPrint3(\n # \"self.Triangles.GetNumberOfValues() \" + str(self.Triangles.GetNumberOfValues()) + \"\\n\")\n # myDebugPrint3(\n # \"self.PointXyzs.GetNumberOfValues() \" + str(self.PointXyzs.GetNumberOfValues()) + \"\\n\")\n hitCount = 0\n for ii in range(0, self.numTriangles):\n ndx = ii * 3\n ptndxA = self.Triangles.GetValue(ndx)\n ptndxB = self.Triangles.GetValue(ndx+1)\n ptndxC = self.Triangles.GetValue(ndx+2)\n #if PhactoriDbg():\n # myDebugPrint3(\"ptndxABC: \" + str(ptndxA) + \" \" + str(ptndxB) + \" \" + str(ptndxC) + \"\\n\");\n ptndxA *= 3\n ptA[0] = self.PointXyzs.GetValue(ptndxA)\n ptA[1] = self.PointXyzs.GetValue(ptndxA+1)\n ptA[2] = self.PointXyzs.GetValue(ptndxA+2)\n ptndxB *= 3\n ptB[0] = self.PointXyzs.GetValue(ptndxB)\n ptB[1] = self.PointXyzs.GetValue(ptndxB+1)\n ptB[2] = self.PointXyzs.GetValue(ptndxB+2)\n ptndxC *= 3\n ptC[0] = self.PointXyzs.GetValue(ptndxC)\n ptC[1] = self.PointXyzs.GetValue(ptndxC+1)\n ptC[2] = self.PointXyzs.GetValue(ptndxC+2)\n #if PhactoriDbg():\n # myDebugPrint3(\"try \" + str(ii) + \" \" + str(ptA) + \"\\n\")\n hitFlag = self.IntersectRayTriangle(\n inRayStart, inRayDirection, ptA, ptB, ptC, hitPoint)\n if hitFlag:\n hitCount += 1\n if PhactoriDbg():\n myDebugPrint3(\"Hit \" + str(hitCount) + \"! \" + str(hitPoint) + \"\\n\")\n vvx = vecFromAToB(inRayStart, hitPoint)\n vvxdist = math.sqrt(vecDotProduct(vvx,vvx))\n myDebugPrint3(\"calculated distance: \" + str(vvxdist) + \"\\n\")\n if ioRaycastOperation.mCreateIntersectionSegmentGroup:\n #onelinesource = Line()\n #onelinesource.Point1 = inRayStart\n #onelinesource.Point2 = [hitPoint[0], hitPoint[1], hitPoint[2]]\n #ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)\n if (saveHit[3] < 0.0) or (hitPoint[3] < saveHit[3]):\n saveHit[0] = hitPoint[0]\n saveHit[1] = hitPoint[1]\n saveHit[2] = hitPoint[2]\n saveHit[3] = hitPoint[3]\n else:\n if inPointOrCellData <= 0:\n oldvv = ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\\\n GetValue(inIndex)\n newvv = hitPoint[3]\n if (oldvv < 0.0) or (newvv < oldvv): \n ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\\\n SetValue(inIndex, hitPoint[3])\n else:\n oldvv = ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\\\n GetValue(inIndex)\n newvv = hitPoint[3]\n if (oldvv < 0.0) or (newvv < oldvv): \n ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\\\n SetValue(inIndex, hitPoint[3])\n\n if ioRaycastOperation.mCreateIntersectionSegmentGroup:\n if saveHit[3] >= 0.0:\n onelinesource = Line()\n onelinesource.Point1 = inRayStart\n onelinesource.Point2 = [saveHit[0], saveHit[1], saveHit[2]]\n ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def parse_color_setting(config_string):\n \"\"\"Parse a DJANGO_COLORS environment variable to produce the system palette\n\n The general form of a palette definition is:\n\n \"palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option\"\n\n where:\n palette is a named palette; one of 'light', 'dark', or 'nocolor'.\n role is a named style used by Django\n fg is a foreground color.\n bg is a background color.\n option is a display options.\n\n Specifying a named palette is the same as manually specifying the individual\n definitions for each role. Any individual definitions following the palette\n definition will augment the base palette definition.\n\n Valid roles:\n 'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype',\n 'sql_keyword', 'sql_table', 'http_info', 'http_success',\n 'http_redirect', 'http_not_modified', 'http_bad_request',\n 'http_not_found', 'http_server_error', 'migrate_heading',\n 'migrate_label'\n\n Valid colors:\n 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'\n\n Valid options:\n 'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset'\n \"\"\"\n if not config_string:\n return PALETTES[DEFAULT_PALETTE]\n\n # Split the color configuration into parts\n parts = config_string.lower().split(\";\")\n palette = PALETTES[NOCOLOR_PALETTE].copy()\n for part in parts:\n if part in PALETTES:\n # A default palette has been specified\n palette.update(PALETTES[part])\n elif \"=\" in part:\n # Process a palette defining string\n definition = {}\n\n # Break the definition into the role,\n # plus the list of specific instructions.\n # The role must be in upper case\n role, instructions = part.split(\"=\")\n role = role.upper()\n\n styles = instructions.split(\",\")\n styles.reverse()\n\n # The first instruction can contain a slash\n # to break apart fg/bg.\n colors = styles.pop().split(\"/\")\n colors.reverse()\n fg = colors.pop()\n if fg in color_names:\n definition[\"fg\"] = fg\n if colors and colors[-1] in color_names:\n definition[\"bg\"] = colors[-1]\n\n # All remaining instructions are options\n opts = tuple(s for s in styles if s in opt_dict)\n if opts:\n definition[\"opts\"] = opts\n\n # The nocolor palette has all available roles.\n # Use that palette as the basis for determining\n # if the role is valid.\n if role in PALETTES[NOCOLOR_PALETTE] and definition:\n palette[role] = definition\n\n # If there are no colors specified, return the empty palette.\n if palette == PALETTES[NOCOLOR_PALETTE]:\n return None\n return palette", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _verify_signature(\n stub: Signature[nodes.Argument], runtime: Signature[inspect.Parameter], function_name: str\n) -> Iterator[str]:\n # Check positional arguments match up\n for stub_arg, runtime_arg in zip(stub.pos, runtime.pos):\n yield from _verify_arg_name(stub_arg, runtime_arg, function_name)\n yield from _verify_arg_default_value(stub_arg, runtime_arg)\n if (\n runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY\n and not stub_arg.pos_only\n and not stub_arg.variable.name.startswith(\"__\")\n and stub_arg.variable.name.strip(\"_\") != \"self\"\n and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods\n ):\n yield (\n f'stub argument \"{stub_arg.variable.name}\" should be positional-only '\n f'(add \"/\", e.g. \"{runtime_arg.name}, /\")'\n )\n if (\n runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY\n and (stub_arg.pos_only or stub_arg.variable.name.startswith(\"__\"))\n and stub_arg.variable.name.strip(\"_\") != \"self\"\n and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods\n ):\n yield (\n f'stub argument \"{stub_arg.variable.name}\" should be positional or keyword '\n '(remove \"/\")'\n )\n\n # Check unmatched positional args\n if len(stub.pos) > len(runtime.pos):\n # There are cases where the stub exhaustively lists out the extra parameters the function\n # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the\n # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes\n # *args, since runtime logic may prevent arbitrary arguments from actually being accepted.\n if runtime.varpos is None:\n for stub_arg in stub.pos[len(runtime.pos) :]:\n # If the variable is in runtime.kwonly, it's just mislabelled as not a\n # keyword-only argument\n if stub_arg.variable.name not in runtime.kwonly:\n msg = f'runtime does not have argument \"{stub_arg.variable.name}\"'\n if runtime.varkw is not None:\n msg += \". Maybe you forgot to make it keyword-only in the stub?\"\n yield msg\n else:\n yield f'stub argument \"{stub_arg.variable.name}\" is not keyword-only'\n if stub.varpos is not None:\n yield f'runtime does not have *args argument \"{stub.varpos.variable.name}\"'\n elif len(stub.pos) < len(runtime.pos):\n for runtime_arg in runtime.pos[len(stub.pos) :]:\n if runtime_arg.name not in stub.kwonly:\n if not _is_private_parameter(runtime_arg):\n yield f'stub does not have argument \"{runtime_arg.name}\"'\n else:\n yield f'runtime argument \"{runtime_arg.name}\" is not keyword-only'\n\n # Checks involving *args\n if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None:\n if stub.varpos is None and runtime.varpos is not None:\n yield f'stub does not have *args argument \"{runtime.varpos.name}\"'\n if stub.varpos is not None and runtime.varpos is None:\n yield f'runtime does not have *args argument \"{stub.varpos.variable.name}\"'\n\n # Check keyword-only args\n for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)):\n stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg]\n yield from _verify_arg_name(stub_arg, runtime_arg, function_name)\n yield from _verify_arg_default_value(stub_arg, runtime_arg)\n\n # Check unmatched keyword-only args\n if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)):\n # There are cases where the stub exhaustively lists out the extra parameters the function\n # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't\n # exhaustively listed out params), we don't check whether the runtime has all of the stub's\n # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic\n # may prevent arbitrary keyword arguments from actually being accepted.\n for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)):\n if arg in {runtime_arg.name for runtime_arg in runtime.pos}:\n # Don't report this if we've reported it before\n if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}:\n yield f'runtime argument \"{arg}\" is not keyword-only'\n else:\n yield f'runtime does not have argument \"{arg}\"'\n for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)):\n if arg in {stub_arg.variable.name for stub_arg in stub.pos}:\n # Don't report this if we've reported it before\n if not (\n runtime.varpos is None\n and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]}\n ):\n yield f'stub argument \"{arg}\" is not keyword-only'\n else:\n if not _is_private_parameter(runtime.kwonly[arg]):\n yield f'stub does not have argument \"{arg}\"'\n\n # Checks involving **kwargs\n if stub.varkw is None and runtime.varkw is not None:\n # As mentioned above, don't enforce that the stub takes **kwargs.\n # Also check against positional parameters, to avoid a nitpicky message when an argument\n # isn't marked as keyword-only\n stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos}\n # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful\n if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names):\n yield f'stub does not have **kwargs argument \"{runtime.varkw.name}\"'\n if stub.varkw is not None and runtime.varkw is None:\n yield f'runtime does not have **kwargs argument \"{stub.varkw.variable.name}\"'", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def AxisCrossesExtent(self, myExtent, whichAxis):\n # i -> 0\n # j -> 1\n # k -> 2\n # ij -> 3\n # ik -> 4\n # jk -> 5\n if whichAxis < 3:\n if whichAxis != 0:\n if self.ijk[0] < myExtent[0]:\n return False\n if self.ijk[0] >= myExtent[1]:\n return False\n if whichAxis != 1:\n if self.ijk[1] < myExtent[2]:\n return False\n if self.ijk[1] >= myExtent[3]:\n return False\n if whichAxis != 2:\n if self.ijk[2] < myExtent[4]:\n return False\n if self.ijk[2] >= myExtent[5]:\n return False\n else:\n if whichAxis == 3:\n if self.ijk[2] < myExtent[4]:\n return False\n if self.ijk[2] >= myExtent[5]:\n return False\n if whichAxis == 4:\n if self.ijk[1] < myExtent[2]:\n return False\n if self.ijk[1] >= myExtent[3]:\n return False\n if whichAxis == 5:\n if self.ijk[0] < myExtent[0]:\n return False\n if self.ijk[0] >= myExtent[1]:\n return False\n return True", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def GetImageFilename(self, datadescription, inImageSettings,\n inOneLookDirectionFilenameAddon, inRepresentationFilenameAddon,\n inCameraFilenameAddon):\n \"\"\"given the imageset and the look direction filename addon, figure out the\n filename for the image. Due to prior implementation, we return two\n values, a temporary name based only on the callback count, and the\n entire name we intend to have so that all processes can agree on the\n file name when it is generated and then process zero can move the image\n filename to it's final correct value. If we return a None as the\n second value, this indicates the callback count temporary name is also\n the final name so no operating system move needs to happen\"\"\"\n\n inImageBasename = inImageSettings.mImageBasename\n inImageBasedirectory = inImageSettings.mImageBasedirectory\n inNumCounterDigits = inImageSettings.mNumCounterDigits\n inImageFormat = inImageSettings.mImageFormat\n \n timestep = datadescription.GetTimeStep()\n\n lastImagesetName = \"\"\n\n unusedFilenameFound = False\n extraCount = 0\n import os\n\n while unusedFilenameFound == False:\n imageBasename = inImageBasename\n imageBasedirectory = inImageBasedirectory\n nameSuffix = inRepresentationFilenameAddon + \\\n inCameraFilenameAddon + inOneLookDirectionFilenameAddon\n\n if imageBasedirectory == None:\n fileBaseName = imageBasename + nameSuffix\n elif imageBasedirectory == \"\":\n fileBaseName = imageBasename + nameSuffix\n else:\n import os\n fileBaseName = imageBasedirectory + os.sep + imageBasename + \\\n nameSuffix\n\n fname = fileBaseName\n\n fname += \"%t.\" + inImageFormat\n\n extraString = GetExtraFileString()\n if extraString != '':\n fname = fname.replace(\"%t\", extraString + \"-%t\")\n timestepString = str(timestep + extraCount)\n while len(timestepString) < inNumCounterDigits:\n timestepString = \"0\" + timestepString\n myDebugPrint2(\"image fname: \" + fname + \"\\ndigit count: \" + str(inNumCounterDigits) + \"\\ntimestepString: \" + timestepString + \"\\n\")\n \n rplstr1 = None\n if self.mUseDateTime:\n ttnow = gPipeAndViewsState.mCallbackDateTime\n if self.mUseMicrosecondsWithDateTime == False:\n ttnow = ttnow.replace(microsecond=0)\n rplstr1 = str(ttnow.isoformat('-'))\n if self.mConvertDateTimeToInteger:\n import re\n rplstr1 = re.sub('[-:.]', '', rplstr1)\n\n if self.mUseSimulationTime:\n global gSharedRenderView\n simtm = gSharedRenderView.ViewTime\n simtmstr = self.mSimulationTimeFormat % simtm\n if rplstr1 == None:\n rplstr1 = simtmstr\n else:\n rplstr1 = rplstr1 + \"_\" + simtmstr\n\n if self.mUseCallbackCount:\n #if rplstr1 is None, we just fall through and use the default\n #behavior; otherwise we need to add to the string\n if rplstr1 != None:\n rplstr1 = timestepString + \"_\" + rplstr1\n\n if rplstr1 != None:\n fnameRR = fname.replace(\"%t\", rplstr1)\n else:\n fnameRR = None\n \n fname = fname.replace(\"%t\", timestepString)\n\n myDebugPrint2(\"fname after replace: ->\" + fname + \"<-\\n\")\n #if os.path.exists(fname):\n if False: #don't do os.path.exists; it's maybe slow\n #myDebugPrint2(\" filename in use, try to find another\\n\")\n #unusedFilenameFound = False\n unusedFilenameFound = True\n extraCount += 1\n else:\n #myDebugPrint2(\" filename is not in use, use it\\n\")\n unusedFilenameFound = True\n\n if self.mUseRemeshRestartTag == False:\n if fnameRR != None:\n import re\n #print \"removing, e.g. -s0004-\"\n #print \"before:\", fnameRR\n fnameRR = re.sub('-s[0123456789]*-', '', fnameRR)\n #print \"after:\", fnameRR\n\n return fname, fnameRR", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def fast_dict_type(self, e: DictExpr) -> Type | None:\n \"\"\"\n Fast path to determine the type of a dict literal,\n based on the list of entries. This mostly impacts large\n module-level constant definitions.\n\n Limitations:\n - no active type context\n - only supported star expressions are other dict instances\n - the joined types of all keys and values must be Instance or Tuple types\n \"\"\"\n ctx = self.type_context[-1]\n if ctx:\n return None\n rt = self.resolved_type.get(e, None)\n if rt is not None:\n return rt if isinstance(rt, Instance) else None\n keys: list[Type] = []\n values: list[Type] = []\n stargs: tuple[Type, Type] | None = None\n for key, value in e.items:\n if key is None:\n st = get_proper_type(self.accept(value))\n if (\n isinstance(st, Instance)\n and st.type.fullname == \"builtins.dict\"\n and len(st.args) == 2\n ):\n stargs = (st.args[0], st.args[1])\n else:\n self.resolved_type[e] = NoneType()\n return None\n else:\n keys.append(self.accept(key))\n values.append(self.accept(value))\n kt = join.join_type_list(keys)\n vt = join.join_type_list(values)\n if not (allow_fast_container_literal(kt) and allow_fast_container_literal(vt)):\n self.resolved_type[e] = NoneType()\n return None\n if stargs and (stargs[0] != kt or stargs[1] != vt):\n self.resolved_type[e] = NoneType()\n return None\n dt = self.chk.named_generic_type(\"builtins.dict\", [kt, vt])\n self.resolved_type[e] = dt\n return dt", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def add_service_pubkeys(\n self, service: dict, tags: Union[Sequence[str], str]\n ) -> List[PublicKey]:\n \"\"\"Add public keys specified in service. Return public keys so discovered.\n\n Args:\n service: service from DID document\n tags: potential tags marking public keys of type of interest\n (the standard is still coalescing)\n\n Raises:\n ValueError: for public key reference not present in DID document.\n\n Returns: list of public keys from the document service specification\n\n \"\"\"\n\n rv = []\n for tag in [tags] if isinstance(tags, str) else list(tags):\n for svc_key in service.get(tag, {}):\n canon_key = canon_ref(self.did, svc_key)\n pubkey = None\n\n if \"#\" in svc_key:\n if canon_key in self.pubkey:\n pubkey = self.pubkey[canon_key]\n else: # service key refers to another DID doc\n LOGGER.debug(\n \"DID document %s has no public key %s\", self.did, svc_key\n )\n raise ValueError(\n \"DID document {} has no public key {}\".format(\n self.did, svc_key\n )\n )\n else:\n for existing_pubkey in self.pubkey.values():\n if existing_pubkey.value == svc_key:\n pubkey = existing_pubkey\n break\n else:\n pubkey = PublicKey(\n self.did,\n ident=svc_key[-9:-1], # industrial-grade uniqueness\n value=svc_key,\n )\n self._pubkey[pubkey.id] = pubkey\n\n if (\n pubkey and pubkey not in rv\n ): # perverse case: could specify same key multiple ways; append once\n rv.append(pubkey)\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@dashboard_bp.route(\"/account_setting\", methods=[\"GET\", \"POST\"])\n@login_required\n@sudo_required\n@limiter.limit(\"5/minute\", methods=[\"POST\"])\ndef account_setting():\n change_email_form = ChangeEmailForm()\n csrf_form = CSRFValidationForm()\n\n email_change = EmailChange.get_by(user_id=current_user.id)\n if email_change:\n pending_email = email_change.new_email\n else:\n pending_email = None\n\n if request.method == \"POST\":\n if not csrf_form.validate():\n flash(\"Invalid request\", \"warning\")\n return redirect(url_for(\"dashboard.setting\"))\n if request.form.get(\"form-name\") == \"update-email\":\n if change_email_form.validate():\n # whether user can proceed with the email update\n new_email_valid = True\n new_email = canonicalize_email(change_email_form.email.data)\n if new_email != current_user.email and not pending_email:\n # check if this email is not already used\n if personal_email_already_used(new_email) or Alias.get_by(\n email=new_email\n ):\n flash(f\"Email {new_email} already used\", \"error\")\n new_email_valid = False\n elif not email_can_be_used_as_mailbox(new_email):\n flash(\n \"You cannot use this email address as your personal inbox.\",\n \"error\",\n )\n new_email_valid = False\n # a pending email change with the same email exists from another user\n elif EmailChange.get_by(new_email=new_email):\n other_email_change: EmailChange = EmailChange.get_by(\n new_email=new_email\n )\n LOG.w(\n \"Another user has a pending %s with the same email address. Current user:%s\",\n other_email_change,\n current_user,\n )\n\n if other_email_change.is_expired():\n LOG.d(\n \"delete the expired email change %s\", other_email_change\n )\n EmailChange.delete(other_email_change.id)\n Session.commit()\n else:\n flash(\n \"You cannot use this email address as your personal inbox.\",\n \"error\",\n )\n new_email_valid = False\n\n if new_email_valid:\n email_change = EmailChange.create(\n user_id=current_user.id,\n code=random_string(\n 60\n ), # todo: make sure the code is unique\n new_email=new_email,\n )\n Session.commit()\n send_change_email_confirmation(current_user, email_change)\n flash(\n \"A confirmation email is on the way, please check your inbox\",\n \"success\",\n )\n return redirect(url_for(\"dashboard.account_setting\"))\n elif request.form.get(\"form-name\") == \"change-password\":\n flash(\n \"You are going to receive an email containing instructions to change your password\",\n \"success\",\n )\n send_reset_password_email(current_user)\n return redirect(url_for(\"dashboard.account_setting\"))\n elif request.form.get(\"form-name\") == \"send-full-user-report\":\n if ExportUserDataJob(current_user).store_job_in_db():\n flash(\n \"You will receive your SimpleLogin data via email shortly\",\n \"success\",\n )\n else:\n flash(\"An export of your data is currently in progress\", \"error\")\n\n partner_sub = None\n partner_name = None\n\n return render_template(\n \"dashboard/account_setting.html\",\n csrf_form=csrf_form,\n PlanEnum=PlanEnum,\n SenderFormatEnum=SenderFormatEnum,\n BlockBehaviourEnum=BlockBehaviourEnum,\n change_email_form=change_email_form,\n pending_email=pending_email,\n AliasGeneratorEnum=AliasGeneratorEnum,\n UnsubscribeBehaviourEnum=UnsubscribeBehaviourEnum,\n partner_sub=partner_sub,\n partner_name=partner_name,\n FIRST_ALIAS_DOMAIN=FIRST_ALIAS_DOMAIN,\n ALIAS_RAND_SUFFIX_LENGTH=ALIAS_RANDOM_SUFFIX_LENGTH,\n connect_with_proton=CONNECT_WITH_PROTON,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def search_library():\n '''\n Loads the assimp library.\n Throws exception AssimpError if no library_path is found\n\n Returns: tuple, (load from filename function,\n load from memory function,\n export to filename function,\n export to blob function,\n release function,\n dll)\n '''\n #this path\n folder = os.path.dirname(__file__)\n\n # silence 'DLL not found' message boxes on win\n try:\n ctypes.windll.kernel32.SetErrorMode(0x8007)\n except AttributeError:\n pass\n\n candidates = []\n # test every file\n for curfolder in [folder]+additional_dirs:\n if os.path.isdir(curfolder):\n for filename in os.listdir(curfolder):\n # our minimum requirement for candidates is that\n # they should contain 'assimp' somewhere in\n # their name \n if filename.lower().find('assimp')==-1 : \n continue\n is_out=1\n for et in ext_whitelist:\n if et in filename.lower():\n is_out=0\n break\n if is_out:\n continue\n \n library_path = os.path.join(curfolder, filename)\n logger.debug('Try ' + library_path)\n try:\n dll = ctypes.cdll.LoadLibrary(library_path)\n except Exception as e:\n logger.warning(str(e))\n # OK, this except is evil. But different OSs will throw different\n # errors. So just ignore any errors.\n continue\n # see if the functions we need are in the dll\n loaded = try_load_functions(library_path, dll)\n if loaded: candidates.append(loaded)\n\n if not candidates:\n # no library found\n raise AssimpError(\"assimp library not found\")\n else:\n # get the newest library_path\n candidates = map(lambda x: (os.lstat(x[0])[-2], x), candidates)\n res = max(candidates, key=operator.itemgetter(0))[1]\n logger.debug('Using assimp library located at ' + res[0])\n\n # XXX: if there are 1000 dll/so files containing 'assimp'\n # in their name, do we have all of them in our address\n # space now until gc kicks in?\n\n # XXX: take version postfix of the .so on linux?\n return res[1:]", "smellKey": "S3776", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "def _yield_distributions(self):\n \"\"\"\n Yield .dist-info and/or .egg(-info) distributions.\n \"\"\"\n # We need to check if we've seen some resources already, because on\n # some Linux systems (e.g. some Debian/Ubuntu variants) there are\n # symlinks which alias other files in the environment.\n seen = set()\n for path in self.path:\n finder = resources.finder_for_path(path)\n if finder is None:\n continue\n r = finder.find('')\n if not r or not r.is_container:\n continue\n rset = sorted(r.resources)\n for entry in rset:\n r = finder.find(entry)\n if not r or r.path in seen:\n continue\n try:\n if self._include_dist and entry.endswith(DISTINFO_EXT):\n possible_filenames = [\n METADATA_FILENAME, WHEEL_METADATA_FILENAME,\n LEGACY_METADATA_FILENAME\n ]\n for metadata_filename in possible_filenames:\n metadata_path = posixpath.join(\n entry, metadata_filename)\n pydist = finder.find(metadata_path)\n if pydist:\n break\n else:\n continue\n\n with contextlib.closing(pydist.as_stream()) as stream:\n metadata = Metadata(fileobj=stream,\n scheme='legacy')\n logger.debug('Found %s', r.path)\n seen.add(r.path)\n yield new_dist_class(r.path,\n metadata=metadata,\n env=self)\n elif self._include_egg and entry.endswith(\n ('.egg-info', '.egg')):\n logger.debug('Found %s', r.path)\n seen.add(r.path)\n yield old_dist_class(r.path, self)\n except Exception as e:\n msg = 'Unable to read distribution at %s, perhaps due to bad metadata: %s'\n logger.warning(msg, r.path, e)\n import warnings\n warnings.warn(msg % (r.path, e), stacklevel=2)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def createCryptoBar(self, info):\n\t\tdata = []\n\t\tavailableCAIDs = info.getInfoObject(iServiceInformation.sCAIDs)\n\t\tfor caidData in getCaidData():\n\t\t\tif int(caidData[0], 16) <= int(self.currentCAID, 16) <= int(caidData[1], 16):\n\t\t\t\tcolor = self.infoColors[0]\n\t\t\telse:\n\t\t\t\tcolor = self.infoColors[2]\n\t\t\t\ttry:\n\t\t\t\t\tfor caid in availableCAIDs:\n\t\t\t\t\t\tif int(caidData[0], 16) <= caid <= int(caidData[1], 16):\n\t\t\t\t\t\t\tcolor = self.infoColors[1]\n\t\t\t\texcept Exception:\n\t\t\t\t\tpass\n\t\t\tif color != self.infoColors[2] or caidData[4]:\n\t\t\t\tdata.append(f\"{color}{caidData[3]}\")\n\t\treturn f\"{' '.join(data)}{self.infoColors[3]}\"", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_users_for_authors(organization_id, authors, user=None) -> Mapping[str, Author]:\n \"\"\"\n Returns a dictionary of author_id => user, if a Sentry\n user object exists for that email. If there is no matching\n Sentry user, a {user, email} dict representation of that\n author is returned.\n e.g.\n {\n '<author-id-1>': serialized(<User id=1, ...>),\n '<author-id-2>': {'email': 'not-a-user@example.com', 'name': 'dunno'},\n '<author-id-3>': serialized(<User id=3, ...>),\n ...\n }\n \"\"\"\n results = {}\n\n fetched = cache.get_many(\n [_user_to_author_cache_key(organization_id, author) for author in authors]\n )\n if fetched:\n missed = []\n for author in authors:\n fetched_user = fetched.get(_user_to_author_cache_key(organization_id, author))\n if fetched_user is None:\n missed.append(author)\n else:\n results[str(author.id)] = fetched_user\n else:\n missed = authors\n\n if missed:\n if isinstance(user, AnonymousUser):\n user = None\n\n # Filter users based on the emails provided in the commits\n # and that belong to the organization associated with the release\n users: Sequence[UserSerializerResponse] = user_service.serialize_many(\n filter={\n \"emails\": [a.email for a in missed],\n \"organization_id\": organization_id,\n \"is_active\": True,\n },\n as_user=serialize_generic_user(user),\n )\n # Figure out which email address matches to a user\n users_by_email = {}\n for email in [a.email for a in missed]:\n # force emails to lower case so we can do case insensitive matching\n lower_email = email.lower()\n if lower_email not in users_by_email:\n for u in users:\n for match in u[\"emails\"]:\n if (\n match[\"email\"].lower() == lower_email\n and lower_email not in users_by_email\n ):\n users_by_email[lower_email] = u\n\n to_cache = {}\n for author in missed:\n results[str(author.id)] = users_by_email.get(\n author.email.lower(), {\"name\": author.name, \"email\": author.email}\n )\n to_cache[_user_to_author_cache_key(organization_id, author)] = results[str(author.id)]\n cache.set_many(to_cache)\n\n metrics.incr(\"sentry.release.get_users_for_authors.missed\", amount=len(missed))\n metrics.incr(\"sentry.release.get_users_for_authors.total\", amount=len(results))\n return results", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def check_op_sources_valid(fn: FuncIR) -> list[FnError]:\n errors = []\n valid_ops: set[Op] = set()\n valid_registers: set[Register] = set()\n\n for block in fn.blocks:\n valid_ops.update(block.ops)\n\n for op in block.ops:\n if isinstance(op, BaseAssign):\n valid_registers.add(op.dest)\n elif isinstance(op, LoadAddress) and isinstance(op.src, Register):\n valid_registers.add(op.src)\n\n valid_registers.update(fn.arg_regs)\n\n for block in fn.blocks:\n for op in block.ops:\n for source in op.sources():\n if isinstance(source, Integer):\n pass\n elif isinstance(source, Op):\n if source not in valid_ops:\n errors.append(\n FnError(\n source=op,\n desc=f\"Invalid op reference to op of type {type(source).__name__}\",\n )\n )\n elif isinstance(source, Register):\n if source not in valid_registers:\n errors.append(\n FnError(\n source=op, desc=f\"Invalid op reference to register {source.name!r}\"\n )\n )\n\n return errors", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type:\n sym = self.lookup_qualified(t.name, t)\n if sym is not None:\n node = sym.node\n if isinstance(node, PlaceholderNode):\n if node.becomes_typeinfo:\n # Reference to placeholder type.\n if self.api.final_iteration:\n self.cannot_resolve_type(t)\n return AnyType(TypeOfAny.from_error)\n elif self.allow_placeholder:\n self.api.defer()\n else:\n self.api.record_incomplete_ref()\n # Always allow ParamSpec for placeholders, if they are actually not valid,\n # they will be reported later, after we resolve placeholders.\n return PlaceholderType(\n node.fullname,\n self.anal_array(\n t.args,\n allow_param_spec=True,\n allow_param_spec_literals=True,\n allow_unpack=True,\n ),\n t.line,\n )\n else:\n if self.api.final_iteration:\n self.cannot_resolve_type(t)\n return AnyType(TypeOfAny.from_error)\n else:\n # Reference to an unknown placeholder node.\n self.api.record_incomplete_ref()\n return AnyType(TypeOfAny.special_form)\n if node is None:\n self.fail(f\"Internal error (node is None, kind={sym.kind})\", t)\n return AnyType(TypeOfAny.special_form)\n fullname = node.fullname\n hook = self.plugin.get_type_analyze_hook(fullname)\n if hook is not None:\n return hook(AnalyzeTypeContext(t, t, self))\n if (\n fullname in get_nongen_builtins(self.options.python_version)\n and t.args\n and not self.always_allow_new_syntax\n ):\n self.fail(\n no_subscript_builtin_alias(fullname, propose_alt=not self.defining_alias), t\n )\n tvar_def = self.tvar_scope.get_binding(sym)\n if isinstance(sym.node, ParamSpecExpr):\n if tvar_def is None:\n if self.allow_unbound_tvars:\n return t\n if self.defining_alias and self.not_declared_in_type_params(t.name):\n msg = f'ParamSpec \"{t.name}\" is not included in type_params'\n else:\n msg = f'ParamSpec \"{t.name}\" is unbound'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n assert isinstance(tvar_def, ParamSpecType)\n if len(t.args) > 0:\n self.fail(\n f'ParamSpec \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n )\n # Change the line number\n return ParamSpecType(\n tvar_def.name,\n tvar_def.fullname,\n tvar_def.id,\n tvar_def.flavor,\n tvar_def.upper_bound,\n tvar_def.default,\n line=t.line,\n column=t.column,\n )\n if (\n isinstance(sym.node, TypeVarExpr)\n and self.defining_alias\n and not defining_literal\n and (tvar_def is None or tvar_def not in self.allowed_alias_tvars)\n ):\n if self.not_declared_in_type_params(t.name):\n if self.python_3_12_type_alias:\n msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n f'\"{t.name}\"'\n )\n else:\n msg = f'Type variable \"{t.name}\" is not included in type_params'\n else:\n msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:\n assert isinstance(tvar_def, TypeVarType)\n if len(t.args) > 0:\n self.fail(\n f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n )\n # Change the line number\n return tvar_def.copy_modified(line=t.line, column=t.column)\n if isinstance(sym.node, TypeVarTupleExpr) and (\n tvar_def is not None\n and self.defining_alias\n and tvar_def not in self.allowed_alias_tvars\n ):\n if self.not_declared_in_type_params(t.name):\n msg = f'Type variable \"{t.name}\" is not included in type_params'\n else:\n msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n if isinstance(sym.node, TypeVarTupleExpr):\n if tvar_def is None:\n if self.allow_unbound_tvars:\n return t\n if self.defining_alias and self.not_declared_in_type_params(t.name):\n if self.python_3_12_type_alias:\n msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n f'\"{t.name}\"'\n )\n else:\n msg = f'TypeVarTuple \"{t.name}\" is not included in type_params'\n else:\n msg = f'TypeVarTuple \"{t.name}\" is unbound'\n self.fail(msg, t, code=codes.VALID_TYPE)\n return AnyType(TypeOfAny.from_error)\n assert isinstance(tvar_def, TypeVarTupleType)\n if not self.allow_type_var_tuple:\n self.fail(\n f'TypeVarTuple \"{t.name}\" is only valid with an unpack',\n t,\n code=codes.VALID_TYPE,\n )\n return AnyType(TypeOfAny.from_error)\n if len(t.args) > 0:\n self.fail(\n f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n )\n\n # Change the line number\n return TypeVarTupleType(\n tvar_def.name,\n tvar_def.fullname,\n tvar_def.id,\n tvar_def.upper_bound,\n sym.node.tuple_fallback,\n tvar_def.default,\n line=t.line,\n column=t.column,\n )\n special = self.try_analyze_special_unbound_type(t, fullname)\n if special is not None:\n return special\n if isinstance(node, TypeAlias):\n self.aliases_used.add(fullname)\n an_args = self.anal_array(\n t.args,\n allow_param_spec=True,\n allow_param_spec_literals=node.has_param_spec_type,\n allow_unpack=True, # Fixed length unpacks can be used for non-variadic aliases.\n )\n if node.has_param_spec_type and len(node.alias_tvars) == 1:\n an_args = self.pack_paramspec_args(an_args)\n\n disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub\n res = instantiate_type_alias(\n node,\n an_args,\n self.fail,\n node.no_args,\n t,\n self.options,\n unexpanded_type=t,\n disallow_any=disallow_any,\n empty_tuple_index=t.empty_tuple_index,\n )\n # The only case where instantiate_type_alias() can return an incorrect instance is\n # when it is top-level instance, so no need to recurse.\n if (\n isinstance(res, ProperType)\n and isinstance(res, Instance)\n and not (self.defining_alias and self.nesting_level == 0)\n and not validate_instance(res, self.fail, t.empty_tuple_index)\n ):\n fix_instance(\n res,\n self.fail,\n self.note,\n disallow_any=disallow_any,\n options=self.options,\n use_generic_error=True,\n unexpanded_type=t,\n )\n if node.eager:\n res = get_proper_type(res)\n return res\n elif isinstance(node, TypeInfo):\n return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index)\n elif node.fullname in TYPE_ALIAS_NAMES:\n return AnyType(TypeOfAny.special_form)\n # Concatenate is an operator, no need for a proper type\n elif node.fullname in (\"typing_extensions.Concatenate\", \"typing.Concatenate\"):\n # We check the return type further up the stack for valid use locations\n return self.apply_concatenate_operator(t)\n else:\n return self.analyze_unbound_type_without_type_info(t, sym, defining_literal)\n else: # sym is None\n return AnyType(TypeOfAny.special_form)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@swagger_auto_schema(auto_schema=None, methods=['POST'])\n @action(detail=True, methods=['POST'],\n permission_classes=(IsRegisteredAndConfirmed,))\n @transaction.atomic\n def claim(self, request, pk=None):\n if not switch_is_active('claim_a_facility'):\n raise NotFound()\n\n try:\n facility = Facility.objects.get(pk=pk)\n contributor = request.user.contributor\n\n contact_person = request.data.get('your_name')\n job_title = request.data.get('your_title')\n website = request.data.get('your_business_website')\n business_website = request.data.get('business_website')\n linkedin_profile = request.data.get('business_linkedin_profile')\n sectors = request.data.getlist('sectors')\n number_of_workers = request.data.get('number_of_workers')\n local_language_name = request.data.get('local_language_name')\n files = request.FILES.getlist('files')\n\n for file in files:\n extension = file.name.split('.')[-1].lower()\n if f\".{extension}\" not in ALLOWED_ATTACHMENT_EXTENSIONS:\n raise ValidationError(\n f'{file.name} could not be uploaded because \\\n it is not in a supported format.',\n )\n\n if file.size > MAX_ATTACHMENT_SIZE_IN_BYTES:\n mb = MAX_ATTACHMENT_SIZE_IN_BYTES / (1024*1024)\n raise ValidationError(\n '{} exceeds the maximum size of \\\n {:.1f}MB.'.format(file.name, mb)\n )\n\n if (len(files) > MAX_ATTACHMENT_AMOUNT):\n raise ValidationError(\n f'{file.name} could not be uploaded because there is a maximum of \\\n {MAX_ATTACHMENT_AMOUNT} attachments and you have \\\n already uploaded {MAX_ATTACHMENT_AMOUNT} attachments.'\n )\n\n user_has_pending_claims = (\n FacilityClaim\n .objects\n .filter(status=FacilityClaimStatuses.PENDING)\n .filter(facility=facility)\n .filter(contributor=contributor)\n .count() > 0\n )\n\n if user_has_pending_claims:\n raise BadRequestException(\n 'User already has a pending claim on this facility'\n )\n\n facility_claim = (\n FacilityClaim\n .objects\n .create(\n facility=facility,\n contributor=contributor,\n contact_person=contact_person,\n job_title=job_title,\n website=website,\n facility_website=business_website,\n linkedin_profile=linkedin_profile,\n )\n )\n\n if len(sectors) > 0:\n setattr(facility_claim, 'sector', sectors)\n\n try:\n workers_count = number_of_workers\n\n if len(workers_count) == 0:\n workers_count = None\n elif not validate_workers_count(workers_count):\n workers_count = None\n\n except (ValueError, TypeError):\n workers_count = None\n\n facility_claim.facility_workers_count = workers_count\n\n facility_claim.\\\n facility_name_native_language = local_language_name\n\n facility_claim.save()\n\n for file in files:\n timestamp = datetime.now().strftime('%Y%m%d%H%M%S')\n milliseconds = datetime.now().strftime('%f')[:-3]\n timestamp_ms = f'{timestamp}{milliseconds}'\n file_name, file_extension = os.path.splitext(file.name)\n file.name = (\n f'{slugify(file_name, allow_unicode=True)}-'\n f'{contributor.name}-{timestamp_ms}{file_extension}'\n )\n FacilityClaimAttachments.objects.create(\n claim=facility_claim,\n file_name=f'{slugify(file_name)}.{file_extension}',\n claim_attachment=file\n )\n\n send_claim_facility_confirmation_email(request, facility_claim)\n Facility.update_facility_updated_at_field(facility.id)\n\n approved = (\n FacilityClaim\n .objects\n .filter(status=FacilityClaimStatuses.APPROVED)\n .filter(contributor=contributor)\n .values_list('facility__id', flat=True)\n )\n pending = (\n FacilityClaim\n .objects\n .filter(status=FacilityClaimStatuses.PENDING)\n .filter(contributor=contributor)\n .values_list('facility__id', flat=True)\n )\n return Response({\n 'pending': pending,\n 'approved': approved,\n })\n except Facility.DoesNotExist as exc:\n raise NotFound() from exc\n except Contributor.DoesNotExist as exc:\n raise NotFound() from exc", "smellKey": "S3776", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "async def main(\n start_port: int,\n threads: int = 20,\n action: str = None,\n show_timing: bool = False,\n multitenant: bool = False,\n mediation: bool = False,\n multi_ledger: bool = False,\n use_did_exchange: bool = False,\n revocation: bool = False,\n tails_server_base_url: str = None,\n issue_count: int = 300,\n batch_size: int = 30,\n wallet_type: str = None,\n arg_file: str = None,\n log_file: str = None,\n log_config: str = None,\n log_level: str = None,\n cred_type: str = None,\n):\n if multi_ledger:\n genesis = None\n multi_ledger_config_path = \"./demo/multi_ledger_config.yml\"\n else:\n genesis = await default_genesis_txns()\n multi_ledger_config_path = None\n if not genesis:\n print(\"Error retrieving ledger genesis transactions\")\n sys.exit(1)\n\n alice = None\n faber = None\n alice_mediator_agent = None\n faber_mediator_agent = None\n run_timer = log_timer(\"Total runtime:\")\n run_timer.start()\n\n try:\n alice = AliceAgent(\n start_port,\n genesis_data=genesis,\n genesis_txn_list=multi_ledger_config_path,\n timing=show_timing,\n multitenant=multitenant,\n mediation=mediation,\n wallet_type=wallet_type,\n arg_file=arg_file,\n log_file=log_file,\n log_config=log_config,\n log_level=log_level,\n )\n await alice.listen_webhooks(start_port + 2)\n\n faber = FaberAgent(\n start_port + 3,\n genesis_data=genesis,\n genesis_txn_list=multi_ledger_config_path,\n timing=show_timing,\n tails_server_base_url=tails_server_base_url,\n multitenant=multitenant,\n mediation=mediation,\n wallet_type=wallet_type,\n arg_file=arg_file,\n log_file=log_file,\n log_config=log_config,\n log_level=log_level,\n cred_type=cred_type,\n )\n await faber.listen_webhooks(start_port + 5)\n await faber.register_did()\n\n with log_timer(\"Startup duration:\"):\n await alice.start_process()\n await faber.start_process()\n\n if mediation:\n alice_mediator_agent = await start_mediator_agent(\n start_port + 8, genesis, multi_ledger_config_path\n )\n if not alice_mediator_agent:\n raise Exception(\"Mediator agent returns None :-(\")\n faber_mediator_agent = await start_mediator_agent(\n start_port + 11, genesis, multi_ledger_config_path\n )\n if not faber_mediator_agent:\n raise Exception(\"Mediator agent returns None :-(\")\n else:\n alice_mediator_agent = None\n faber_mediator_agent = None\n\n with log_timer(\"Connect duration:\"):\n if multitenant:\n # create an initial managed sub-wallet (also mediated)\n await alice.register_or_switch_wallet(\n \"Alice.initial\",\n webhook_port=None,\n mediator_agent=alice_mediator_agent,\n )\n await faber.register_or_switch_wallet(\n \"Faber.initial\",\n public_did=True,\n webhook_port=None,\n mediator_agent=faber_mediator_agent,\n )\n elif mediation:\n # we need to pre-connect the agent(s) to their mediator (use the same\n # mediator for both)\n if not await connect_wallet_to_mediator(alice, alice_mediator_agent):\n log_msg(\"Mediation setup FAILED :-(\")\n raise Exception(\"Mediation setup FAILED :-(\")\n if not await connect_wallet_to_mediator(faber, faber_mediator_agent):\n log_msg(\"Mediation setup FAILED :-(\")\n raise Exception(\"Mediation setup FAILED :-(\")\n\n invite = await faber.get_invite(use_did_exchange)\n await alice.receive_invite(invite[\"invitation\"])\n await asyncio.wait_for(faber.detect_connection(), 30)\n\n if action != \"ping\":\n with log_timer(\"Publish duration:\"):\n await faber.publish_defs(revocation)\n # cache the credential definition\n await alice.fetch_credential_definition(faber.credential_definition_id)\n\n if show_timing:\n await alice.reset_timing()\n await faber.reset_timing()\n if mediation:\n await alice_mediator_agent.reset_timing()\n await faber_mediator_agent.reset_timing()\n\n semaphore = asyncio.Semaphore(threads)\n\n def done_propose(fut: asyncio.Task):\n semaphore.release()\n alice.check_task_exception(fut)\n\n def done_send(fut: asyncio.Task):\n semaphore.release()\n faber.check_task_exception(fut)\n\n def test_cred(index: int) -> dict:\n return {\n \"name\": \"Alice Smith\",\n \"date\": f\"{2020+index}-05-28\",\n \"degree\": \"Maths\",\n \"age\": \"24\",\n }\n\n async def propose_credential(index: int):\n await semaphore.acquire()\n comment = f\"propose test credential {index}\"\n attributes = test_cred(index)\n asyncio.ensure_future(\n alice.propose_credential(\n attributes, faber.credential_definition_id, comment, not revocation\n )\n ).add_done_callback(done_propose)\n\n async def send_credential(index: int):\n await semaphore.acquire()\n comment = f\"issue test credential {index}\"\n attributes = test_cred(index)\n asyncio.ensure_future(\n faber.send_credential(attributes, comment, not revocation)\n ).add_done_callback(done_send)\n\n async def check_received_creds(agent, issue_count, pb):\n reported = 0\n iter_pb = iter(pb) if pb else None\n while True:\n pending, total = await agent.check_received_creds()\n complete = total - pending\n if reported == complete:\n await asyncio.wait_for(agent.update_creds(), 45)\n continue\n if iter_pb and complete > reported:\n try:\n while next(iter_pb) < complete:\n pass\n except StopIteration:\n iter_pb = None\n reported = complete\n if reported == issue_count:\n break\n\n async def send_ping(index: int):\n await semaphore.acquire()\n asyncio.ensure_future(faber.send_ping(str(index))).add_done_callback(\n done_send\n )\n\n async def check_received_pings(agent, issue_count, pb):\n reported = 0\n iter_pb = iter(pb) if pb else None\n while True:\n pings = await agent.check_received_pings()\n complete = sum(len(tids) for tids in pings.values())\n if complete == reported:\n await asyncio.wait_for(agent.update_pings(), 30)\n continue\n if iter_pb and complete > reported:\n try:\n while next(iter_pb) < complete:\n pass\n except StopIteration:\n iter_pb = None\n reported = complete\n if reported >= issue_count:\n break\n\n if action == \"ping\":\n recv_timer = faber.log_timer(f\"Completed {issue_count} ping exchanges in\")\n batch_timer = faber.log_timer(f\"Started {batch_size} ping exchanges in\")\n else:\n recv_timer = faber.log_timer(\n f\"Completed {issue_count} credential exchanges in\"\n )\n batch_timer = faber.log_timer(f\"Started {batch_size} credential exchanges in\")\n recv_timer.start()\n batch_timer.start()\n\n with progress() as pb:\n receive_task = None\n try:\n if action == \"ping\":\n issue_pg = pb(range(issue_count), label=\"Sending pings\")\n receive_pg = pb(range(issue_count), label=\"Responding pings\")\n check_received = check_received_pings\n send = send_ping\n completed = f\"Done sending {issue_count} pings in\"\n else:\n issue_pg = pb(range(issue_count), label=\"Issuing credentials\")\n receive_pg = pb(range(issue_count), label=\"Receiving credentials\")\n check_received = check_received_creds\n if action == \"propose\":\n send = propose_credential\n else:\n send = send_credential\n completed = f\"Done starting {issue_count} credential exchanges in\"\n\n issue_task = asyncio.ensure_future(\n check_received(faber, issue_count, issue_pg)\n )\n issue_task.add_done_callback(faber.check_task_exception)\n receive_task = asyncio.ensure_future(\n check_received(alice, issue_count, receive_pg)\n )\n receive_task.add_done_callback(alice.check_task_exception)\n with faber.log_timer(completed):\n for idx in range(0, issue_count):\n await send(idx + 1)\n if not (idx + 1) % batch_size and idx < issue_count - 1:\n batch_timer.reset()\n\n await issue_task\n await receive_task\n except KeyboardInterrupt:\n if receive_task:\n receive_task.cancel()\n print(\"Cancelled\")\n\n recv_timer.stop()\n avg = recv_timer.duration / issue_count\n item_short = \"ping\" if action == \"ping\" else \"cred\"\n item_long = \"ping exchange\" if action == \"ping\" else \"credential\"\n faber.log(f\"Average time per {item_long}: {avg:.2f}s ({1/avg:.2f}/s)\")\n\n if alice.postgres:\n await alice.collect_postgres_stats(f\"{issue_count} {item_short}s\")\n for line in alice.format_postgres_stats():\n alice.log(line)\n if faber.postgres:\n await faber.collect_postgres_stats(f\"{issue_count} {item_short}s\")\n for line in faber.format_postgres_stats():\n faber.log(line)\n\n if revocation and faber.revocations:\n (rev_reg_id, cred_rev_id) = next(iter(faber.revocations))\n print(\n f\"Revoking and publishing cred rev id {cred_rev_id} \"\n f\"from rev reg id {rev_reg_id}\"\n )\n\n if show_timing:\n timing = await alice.fetch_timing()\n if timing:\n for line in alice.format_timing(timing):\n alice.log(line)\n\n timing = await faber.fetch_timing()\n if timing:\n for line in faber.format_timing(timing):\n faber.log(line)\n if mediation:\n timing = await alice_mediator_agent.fetch_timing()\n if timing:\n for line in alice_mediator_agent.format_timing(timing):\n alice_mediator_agent.log(line)\n timing = await faber_mediator_agent.fetch_timing()\n if timing:\n for line in faber_mediator_agent.format_timing(timing):\n faber_mediator_agent.log(line)\n\n finally:\n terminated = True\n try:\n if alice:\n await alice.terminate()\n except Exception:\n LOGGER.exception(\"Error terminating agent:\")\n terminated = False\n try:\n if faber:\n await faber.terminate()\n except Exception:\n LOGGER.exception(\"Error terminating agent:\")\n terminated = False\n try:\n if alice_mediator_agent:\n await alice_mediator_agent.terminate()\n if faber_mediator_agent:\n await faber_mediator_agent.terminate()\n except Exception:\n LOGGER.exception(\"Error terminating agent:\")\n terminated = False\n\n run_timer.stop()\n await asyncio.sleep(0.1)\n\n if not terminated:\n os._exit(1)", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def PlotValMinMaxTrkCParseJson(self, inJson, inKeyPrefix):\n if PhactoriDbg(100):\n myDebugPrint3(\"PlotValMinMaxTrkCParseJson entered, key prefix is ->\" + inKeyPrefix + \"<-\\n\", 100)\n #self.mParseHadKeys = False\n keyCurrentDataRange = inKeyPrefix + 'use current data range'\n keyCumulativeDataRange = inKeyPrefix + 'use cumulative data range'\n keyRange = inKeyPrefix + 'range'\n keyMinimumRange = inKeyPrefix + 'minimum range'\n keyMaximumRange = inKeyPrefix + 'maximum range'\n\n if keyCurrentDataRange in inJson:\n self.mUseCumulativeRange = False\n elif keyCumulativeDataRange in inJson:\n self.mUseCumulativeRange = True\n\n if keyRange in inJson:\n range = inJson[keyRange]\n ff0 = float(range[0])\n ff1 = float(range[1])\n range = [ff0, ff1]\n if PhactoriDbg():\n myDebugPrint3(\"PlotValMinMaxTrkCParseJson got range \" + str(range) + \"\\n\")\n self.mLowestBot = range[0]\n self.mUseLowestBot = True\n self.mHighestBot = range[0]\n self.mUseHighestBot = True\n self.mLowestTop = range[1]\n self.mUseLowestTop = True\n self.mHighestTop = range[1]\n self.mUseHighestTop = True\n else:\n if keyMinimumRange in inJson:\n range = inJson[keyMinimumRange]\n ff0 = float(range[0])\n ff1 = float(range[1])\n range = [ff0, ff1]\n if PhactoriDbg():\n myDebugPrint3(\"PlotValMinMaxTrkCParseJson got minimum range \" + str(range) + \"\\n\")\n self.mHighestBot = range[0]\n self.mUseHighestBot = True\n self.mLowestTop = range[1]\n self.mUseLowestTop = True\n if keyMaximumRange in inJson:\n range = inJson[keyMaximumRange]\n ff0 = float(range[0])\n ff1 = float(range[1])\n range = [ff0, ff1]\n if PhactoriDbg():\n myDebugPrint3(\"PlotValMinMaxTrkCParseJson got maximum range \" + str(range) + \"\\n\")\n self.mLowestBot = range[0]\n self.mUseLowestBot = True\n self.mHighestTop = range[1]\n self.mUseHighestTop = True\n\n if PhactoriDbg():\n myDebugPrint3(self.SelfToStr())", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def main():\n argument_spec = mongodb_common_argument_spec()\n argument_spec.update(\n database=dict(required=True, aliases=['db']),\n name=dict(required=True, aliases=['user']),\n password=dict(aliases=['pass'], no_log=True),\n replica_set=dict(default=None),\n roles=dict(default=None, type='list', elements='raw'),\n state=dict(default='present', choices=['absent', 'present']),\n update_password=dict(default=\"always\", choices=[\"always\", \"on_create\"], no_log=False),\n create_for_localhost_exception=dict(default=None, type='path'),\n )\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True,\n )\n login_user = module.params['login_user']\n\n # Certs don't have a password but we want this module behaviour\n if module.params['login_database'] == '$external':\n module.params['update_password'] = 'on_create'\n\n if not pymongo_found:\n module.fail_json(msg=missing_required_lib('pymongo'),\n exception=PYMONGO_IMP_ERR)\n\n create_for_localhost_exception = module.params['create_for_localhost_exception']\n b_create_for_localhost_exception = (\n to_bytes(create_for_localhost_exception, errors='surrogate_or_strict')\n if create_for_localhost_exception is not None else None\n )\n\n db_name = module.params['database']\n user = module.params['name']\n password = module.params['password']\n roles = module.params['roles'] or []\n state = module.params['state']\n update_password = module.params['update_password']\n\n try:\n directConnection = False\n if module.params['replica_set'] is None:\n directConnection = True\n client = get_mongodb_client(module, directConnection=directConnection)\n client = mongo_auth(module, client, directConnection=directConnection)\n except Exception as e:\n module.fail_json(msg='Unable to connect to database: %s' % to_native(e))\n\n if state == 'present':\n if password is None and update_password == 'always':\n module.fail_json(msg='password parameter required when adding a user unless update_password is set to on_create')\n\n if login_user is None and create_for_localhost_exception is not None:\n if os.path.exists(b_create_for_localhost_exception):\n try:\n client.close()\n except Exception:\n pass\n module.exit_json(changed=False, user=user, skipped=True, msg=\"The path in create_for_localhost_exception exists.\")\n\n try:\n if update_password != 'always':\n uinfo = user_find(client, user, db_name)\n if uinfo:\n password = None\n if not check_if_roles_changed(uinfo, roles, db_name):\n module.exit_json(changed=False, user=user)\n\n if module.check_mode:\n module.exit_json(changed=True, user=user)\n user_add(module, client, db_name, user, password, roles)\n except Exception as e:\n module.fail_json(msg='Unable to add or update user: %s' % to_native(e), exception=traceback.format_exc())\n finally:\n try:\n client.close()\n except Exception:\n pass\n # Here we can check password change if mongo provide a query for that : https://jira.mongodb.org/browse/SERVER-22848\n # newuinfo = user_find(client, user, db_name)\n # if uinfo['role'] == newuinfo['role'] and CheckPasswordHere:\n # module.exit_json(changed=False, user=user)\n\n if login_user is None and create_for_localhost_exception is not None:\n # localhost exception applied.\n try:\n # touch the file\n open(b_create_for_localhost_exception, 'wb').close()\n except Exception as e:\n module.fail_json(\n changed=True,\n msg='Added user but unable to touch create_for_localhost_exception file %s: %s' % (create_for_localhost_exception, to_native(e)),\n exception=traceback.format_exc()\n )\n\n elif state == 'absent':\n try:\n user_remove(module, client, db_name, user)\n except Exception as e:\n module.fail_json(msg='Unable to remove user: %s' % to_native(e), exception=traceback.format_exc())\n finally:\n try:\n client.close()\n except Exception:\n pass\n module.exit_json(changed=True, user=user)", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def __rich_console__(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> \"RenderResult\":\n\n stack: List[Iterator[Tuple[bool, Tree]]] = []\n pop = stack.pop\n push = stack.append\n new_line = Segment.line()\n\n get_style = console.get_style\n null_style = Style.null()\n guide_style = get_style(self.guide_style, default=\"\") or null_style\n SPACE, CONTINUE, FORK, END = range(4)\n\n ASCII_GUIDES = (\" \", \"| \", \"+-- \", \"`-- \")\n TREE_GUIDES = [\n (\" \", \"\u2502 \", \"\u251c\u2500\u2500 \", \"\u2514\u2500\u2500 \"),\n (\" \", \"\u2503 \", \"\u2523\u2501\u2501 \", \"\u2517\u2501\u2501 \"),\n (\" \", \"\u2551 \", \"\u2560\u2550\u2550 \", \"\u255a\u2550\u2550 \"),\n ]\n _Segment = Segment\n\n def make_guide(index: int, style: Style) -> Segment:\n \"\"\"Make a Segment for a level of the guide lines.\"\"\"\n if options.ascii_only:\n line = ASCII_GUIDES[index]\n else:\n guide = 1 if style.bold else (2 if style.underline2 else 0)\n line = TREE_GUIDES[0 if options.legacy_windows else guide][index]\n return _Segment(line, style)\n\n levels: List[Segment] = [make_guide(CONTINUE, guide_style)]\n push(iter(loop_last([self])))\n\n guide_style_stack = StyleStack(get_style(self.guide_style))\n style_stack = StyleStack(get_style(self.style))\n remove_guide_styles = Style(bold=False, underline2=False)\n\n depth = 0\n\n while stack:\n stack_node = pop()\n try:\n last, node = next(stack_node)\n except StopIteration:\n levels.pop()\n if levels:\n guide_style = levels[-1].style or null_style\n levels[-1] = make_guide(FORK, guide_style)\n guide_style_stack.pop()\n style_stack.pop()\n continue\n push(stack_node)\n if last:\n levels[-1] = make_guide(END, levels[-1].style or null_style)\n\n guide_style = guide_style_stack.current + get_style(node.guide_style)\n style = style_stack.current + get_style(node.style)\n prefix = levels[(2 if self.hide_root else 1) :]\n renderable_lines = console.render_lines(\n Styled(node.label, style),\n options.update(\n width=options.max_width\n - sum(level.cell_length for level in prefix),\n highlight=self.highlight,\n height=None,\n ),\n pad=options.justify is not None,\n )\n\n if not (depth == 0 and self.hide_root):\n for first, line in loop_first(renderable_lines):\n if prefix:\n yield from _Segment.apply_style(\n prefix,\n style.background_style,\n post_style=remove_guide_styles,\n )\n yield from line\n yield new_line\n if first and prefix:\n prefix[-1] = make_guide(\n SPACE if last else CONTINUE, prefix[-1].style or null_style\n )\n\n if node.expanded and node.children:\n levels[-1] = make_guide(\n SPACE if last else CONTINUE, levels[-1].style or null_style\n )\n levels.append(\n make_guide(END if len(node.children) == 1 else FORK, guide_style)\n )\n style_stack.push(get_style(node.style))\n guide_style_stack.push(get_style(node.guide_style))\n push(iter(loop_last(node.children)))\n depth += 1", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def run_case_once(\n self,\n testcase: DataDrivenTestCase,\n operations: list[FileOperation] | None = None,\n incremental_step: int = 0,\n ) -> None:\n if operations is None:\n operations = []\n original_program_text = \"\\n\".join(testcase.input)\n module_data = self.parse_module(original_program_text, incremental_step)\n\n # Unload already loaded plugins, they may be updated.\n for file, _ in testcase.files:\n module = module_from_path(file)\n if module.endswith(\"_plugin\") and module in sys.modules:\n del sys.modules[module]\n if incremental_step == 0 or incremental_step == 1:\n # In run 1, copy program text to program file.\n for module_name, program_path, program_text in module_data:\n if module_name == \"__main__\":\n with open(program_path, \"w\", encoding=\"utf8\") as f:\n f.write(program_text)\n break\n elif incremental_step > 1:\n # In runs 2+, copy *.[num] files to * files.\n perform_file_operations(operations)\n\n # Parse options after moving files (in case mypy.ini is being moved).\n options = parse_options(original_program_text, testcase, incremental_step)\n options.use_builtins_fixtures = True\n options.show_traceback = True\n\n # Enable some options automatically based on test file name.\n if \"columns\" in testcase.file:\n options.show_column_numbers = True\n if \"errorcodes\" in testcase.file:\n options.hide_error_codes = False\n if \"abstract\" not in testcase.file:\n options.allow_empty_bodies = not testcase.name.endswith(\"_no_empty\")\n if \"lowercase\" not in testcase.file:\n options.force_uppercase_builtins = True\n if \"union-error\" not in testcase.file:\n options.force_union_syntax = True\n\n if incremental_step and options.incremental:\n # Don't overwrite # flags: --no-incremental in incremental test cases\n options.incremental = True\n else:\n options.incremental = False\n # Don't waste time writing cache unless we are specifically looking for it\n if not testcase.writescache:\n options.cache_dir = os.devnull\n\n sources = []\n for module_name, program_path, program_text in module_data:\n # Always set to none so we're forced to reread the module in incremental mode\n sources.append(\n BuildSource(program_path, module_name, None if incremental_step else program_text)\n )\n\n plugin_dir = os.path.join(test_data_prefix, \"plugins\")\n sys.path.insert(0, plugin_dir)\n\n res = None\n try:\n res = build.build(sources=sources, options=options, alt_lib_path=test_temp_dir)\n a = res.errors\n except CompileError as e:\n a = e.messages\n finally:\n assert sys.path[0] == plugin_dir\n del sys.path[0]\n\n if testcase.normalize_output:\n a = normalize_error_messages(a)\n\n # Make sure error messages match\n if incremental_step < 2:\n if incremental_step == 1:\n msg = \"Unexpected type checker output in incremental, run 1 ({}, line {})\"\n else:\n assert incremental_step == 0\n msg = \"Unexpected type checker output ({}, line {})\"\n self._sort_output_if_needed(testcase, a)\n output = testcase.output\n else:\n msg = (\n f\"Unexpected type checker output in incremental, run {incremental_step}\"\n + \" ({}, line {})\"\n )\n output = testcase.output2.get(incremental_step, [])\n\n if output != a and testcase.config.getoption(\"--update-data\", False):\n update_testcase_output(testcase, a, incremental_step=incremental_step)\n\n assert_string_arrays_equal(output, a, msg.format(testcase.file, testcase.line))\n\n if res:\n if options.cache_dir != os.devnull:\n self.verify_cache(module_data, res.errors, res.manager, res.graph)\n\n name = \"targets\"\n if incremental_step:\n name += str(incremental_step + 1)\n expected = testcase.expected_fine_grained_targets.get(incremental_step + 1)\n actual = [\n target\n for module, target in res.manager.processed_targets\n if module in testcase.test_modules\n ]\n if expected is not None:\n assert_target_equivalence(name, expected, actual)\n if incremental_step > 1:\n suffix = \"\" if incremental_step == 2 else str(incremental_step - 1)\n expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)\n if expected_rechecked is not None:\n assert_module_equivalence(\n \"rechecked\" + suffix, expected_rechecked, res.manager.rechecked_modules\n )\n expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)\n if expected_stale is not None:\n assert_module_equivalence(\n \"stale\" + suffix, expected_stale, res.manager.stale_modules\n )\n\n if testcase.output_files:\n check_test_output_files(testcase, incremental_step, strip_prefix=\"tmp/\")", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@cached\n\tdef getBoolean(self):\n\t\tservice = self.source.service\n\t\tinfo = service and service.info()\n\t\tif not info:\n\t\t\treturn False\n\t\tif self.type == self.AUDIOTRACKS_AVAILABLE:\n\t\t\taudio = service.audioTracks()\n\t\t\tif audio:\n\t\t\t\tif audio.getNumberOfTracks() > 1:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\telif self.type == self.SUBTITLES_AVAILABLE:\n\t\t\tsubtitle = service and service.subtitle()\n\t\t\tif subtitle:\n\t\t\t\tsubtitle_list = subtitle.getSubtitleList()\n\t\t\t\tif subtitle_list:\n\t\t\t\t\tif len(subtitle_list) > 0:\n\t\t\t\t\t\treturn True\n\t\t\treturn False", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_tokendefs(cls):\n \"\"\"\n Merge tokens from superclasses in MRO order, returning a single tokendef\n dictionary.\n\n Any state that is not defined by a subclass will be inherited\n automatically. States that *are* defined by subclasses will, by\n default, override that state in the superclass. If a subclass wishes to\n inherit definitions from a superclass, it can use the special value\n \"inherit\", which will cause the superclass' state definition to be\n included at that point in the state.\n \"\"\"\n tokens = {}\n inheritable = {}\n for c in cls.__mro__:\n toks = c.__dict__.get('tokens', {})\n\n for state, items in toks.items():\n curitems = tokens.get(state)\n if curitems is None:\n # N.b. because this is assigned by reference, sufficiently\n # deep hierarchies are processed incrementally (e.g. for\n # A(B), B(C), C(RegexLexer), B will be premodified so X(B)\n # will not see any inherits in B).\n tokens[state] = items\n try:\n inherit_ndx = items.index(inherit)\n except ValueError:\n continue\n inheritable[state] = inherit_ndx\n continue\n\n inherit_ndx = inheritable.pop(state, None)\n if inherit_ndx is None:\n continue\n\n # Replace the \"inherit\" value with the items\n curitems[inherit_ndx:inherit_ndx+1] = items\n try:\n # N.b. this is the index in items (that is, the superclass\n # copy), so offset required when storing below.\n new_inh_ndx = items.index(inherit)\n except ValueError:\n pass\n else:\n inheritable[state] = inherit_ndx + new_inh_ndx\n\n return tokens", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def SetUpViewAndRepresentationBeforeWriteImage(self, inLookDirection,\n inLookDirectionIndex):\n \"Since it turns out to be much more memory efficient to reuse a single\\n render view rather than having one per image, this routine is called\\n immediately before WriteImage in order to set the\\n camera, background color, image size, etc. up appropriately for the\\n WriteImage call\"\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriImagesetBlock:\" \\\n \"SetUpViewAndRepresentationBeforeWriteImage entered \" + \\\n str(self.mName) + \"\\n\", 100)\n self.mPvDataRepresentation2.Visibility = 1\n\n pvRenderView = self.mSharedPvRenderView2\n pvDataRep = self.mPvDataRepresentation2\n\n #image size\n #pvRenderView.ViewSize = self.mImageSettings.mImageSize\n pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),\n int(self.mImageSettings.mImageSize[1])]\n\n #background color, text color, etc.\n\n theColorSettings = self.mRepresentation.mColorSettings\n\n theColorSettings.SetParaviewRvRepColors(pvRenderView, pvDataRep)\n\n phactoriRep = self.mRepresentation\n #orientation axis on or off for this 3d mesh\n if phactoriRep.mOrientationAxesFlag:\n pvRenderView.OrientationAxesVisibility = 1\n else:\n pvRenderView.OrientationAxesVisibility = 0\n\n #time annotation invisible (for 3d plot)\n timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings\n if timeAnnStngs.mVisible:\n global gPipeAndViewsState\n if gPipeAndViewsState.mTimeAnnotationPv != None:\n gPipeAndViewsState.mTimeAnnotationPv.\\\n mParaViewRepresentation.Visibility = 1\n\n #cube axes\n if phactoriRep.mDataCubeAxesFlag:\n ShowCubeAxesXX(pvRenderView, 'on', phactoriRep.mDataCubeAxesInfo)\n\n #edges/surface/wireframe\n #self.mPvDataRepresentation2.Representation = \\\n # phactoriRep.mMeshRenderControl\n self.mPvDataRepresentation2.SetRepresentationType(\n phactoriRep.mMeshRenderControl)\n\n if phactoriRep.mDoingVolumeRendering:\n if phactoriRep.mScalarOpacityUnitDistance < 0.0:\n phactoriRep.CalculateDefaultScalarOpacityUnitDistance(self.mOperation)\n if phactoriRep.mScalarOpacityUnitDistance != \\\n self.mPvDataRepresentation2.ScalarOpacityUnitDistance:\n self.mPvDataRepresentation2.ScalarOpacityUnitDistance = \\\n phactoriRep.mScalarOpacityUnitDistance\n\n #size of points\n self.mPvDataRepresentation2.PointSize = phactoriRep.mPointSize\n\n #color legend\n for oneColorLegendRepRef in self.mColorLegendRepRefs:\n if oneColorLegendRepRef != None:\n oneColorLegendRepRef.Visibility = 1\n\n #color by variable or solid color or color by block\n if inLookDirectionIndex == 0:\n #on multicamera 8 setups, we only do this on first (index 0)\n SetForCorrectColorBy(self, self.mOperation,\n self.mPvDataRepresentation2, phactoriRep, False)\n else:\n #for some reason, solid color doesn't stick between camera angles;\n #redo if it is solid color\n if phactoriRep.mColorBySolidColorFlag == True:\n SetForCorrectColorBy(self, self.mOperation,\n self.mPvDataRepresentation2, phactoriRep, False)\n\n #markers for this imageset made visible\n for oneMarker in self.mVisibleMarkers:\n oneMarker.UpdateAndMakeVisible()\n\n for oneTextAnnotation in self.mTextAnnotations:\n oneTextAnnotation.UpdateAndMakeVisible()\n\n #do extra visible operations/representations\n ii = 1\n while ii < len(self.mVisibleReps):\n oneVisOp = self.mVisibleOps[ii]\n oneVisRep = self.mVisibleReps[ii]\n oneVisPvDataRep = self.mVisiblePvDataReps[ii]\n if PhactoriDbg(100):\n myDebugPrint3(\"add extra visiblity \" + str(ii) + \" rep:\\n\" + \\\n str(oneVisPvDataRep))\n ii += 1\n\n oneVisPvDataRep.Visibility = 1\n #theColorSettings = self.mRepresentation.mColorSettings\n #theColorSettings.SetParaviewRvRepColors(pvRenderView, oneVisPvDataRep)\n\n #edges/surface/wireframe\n oneVisPvDataRep.SetRepresentationType(oneVisRep.mMeshRenderControl)\n\n if oneVisRep.mDoingVolumeRendering:\n if oneVisRep.mScalarOpacityUnitDistance < 0.0:\n oneVisRep.CalculateDefaultScalarOpacityUnitDistance(oneVisOp)\n if oneVisRep.mScalarOpacityUnitDistance != \\\n oneVisPvDataRep.ScalarOpacityUnitDistance:\n oneVisPvDataRep.ScalarOpacityUnitDistance = \\\n oneVisRep.mScalarOpacityUnitDistance\n\n\n #color legend\n #if self.mColorLegendRepRef != None:\n # self.mColorLegendRepRef.Visibility = 1\n\n #color by variable or solid color or color by block\n if inLookDirectionIndex == 0:\n #on multicamera 8 setups, we only do this on first (index 0)\n SetForCorrectColorBy(self, oneVisOp,\n oneVisPvDataRep, oneVisRep, False)\n else:\n #for some reason, solid color doesn't stick between camera angles;\n #redo if it is solid color\n if phactoriRep.mColorBySolidColorFlag == True:\n #SetForCorrectColorBy(self, self.mPvDataRepresentation2,\n # phactoriRep, False)\n SetForCorrectColorBy(self, oneVisOp,\n oneVisPvDataRep, oneVisRep, False)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"start setting camera parameters for imageset: \" + \\\n self.mName + \"\\n\", 100)\n SetParaViewRepresentationCameraParams(\n pvRenderView,\n self.mCamera,\n inLookDirection,\n self.mImageSettings,\n self.mOperation.GetPvFilter())\n if PhactoriDbg(100):\n myDebugPrint3(\"done setting camera parameters for imageset: \" + \\\n self.mName + \"\\n\", 100)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetUpViewAndRepresentationBeforeWriteImage returning\\n\",\n 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def forward_email_to_mailbox(\n alias,\n msg: Message,\n contact: Contact,\n envelope,\n mailbox,\n user,\n reply_to_contact: Optional[Contact],\n) -> (bool, str):\n LOG.d(\"Forward %s -> %s -> %s\", contact, alias, mailbox)\n\n if mailbox.disabled:\n LOG.d(\"%s disabled, do not forward\")\n if should_ignore_bounce(envelope.mail_from):\n return True, status.E207\n else:\n return False, status.E518\n\n # sanity check: make sure mailbox is not actually an alias\n if get_email_domain_part(alias.email) == get_email_domain_part(mailbox.email):\n LOG.w(\n \"Mailbox has the same domain as alias. %s -> %s -> %s\",\n contact,\n alias,\n mailbox,\n )\n mailbox_url = f\"{URL}/dashboard/mailbox/{mailbox.id}/\"\n send_email_with_rate_control(\n user,\n ALERT_MAILBOX_IS_ALIAS,\n user.email,\n f\"Your mailbox {mailbox.email} and alias {alias.email} use the same domain\",\n render(\n \"transactional/mailbox-invalid.txt.jinja2\",\n user=mailbox.user,\n mailbox=mailbox,\n mailbox_url=mailbox_url,\n alias=alias,\n ),\n render(\n \"transactional/mailbox-invalid.html\",\n user=mailbox.user,\n mailbox=mailbox,\n mailbox_url=mailbox_url,\n alias=alias,\n ),\n max_nb_alert=1,\n )\n\n # retry later\n # so when user fixes the mailbox, the email can be delivered\n return False, status.E405\n\n email_log = EmailLog.create(\n contact_id=contact.id,\n user_id=contact.user_id,\n mailbox_id=mailbox.id,\n alias_id=contact.alias_id,\n message_id=str(msg[headers.MESSAGE_ID]),\n commit=True,\n )\n LOG.d(\"Create %s for %s, %s, %s\", email_log, contact, user, mailbox)\n\n if ENABLE_SPAM_ASSASSIN:\n # Spam check\n spam_status = \"\"\n is_spam = False\n\n if SPAMASSASSIN_HOST:\n start = time.time()\n spam_score, spam_report = get_spam_score(msg, email_log)\n LOG.d(\n \"%s -> %s - spam score:%s in %s seconds. Spam report %s\",\n contact,\n alias,\n spam_score,\n time.time() - start,\n spam_report,\n )\n email_log.spam_score = spam_score\n Session.commit()\n\n if (user.max_spam_score and spam_score > user.max_spam_score) or (\n not user.max_spam_score and spam_score > MAX_SPAM_SCORE\n ):\n is_spam = True\n # only set the spam report for spam\n email_log.spam_report = spam_report\n else:\n is_spam, spam_status = get_spam_info(msg, max_score=user.max_spam_score)\n\n if is_spam:\n LOG.w(\n \"Email detected as spam. %s -> %s. Spam Score: %s, Spam Report: %s\",\n contact,\n alias,\n email_log.spam_score,\n email_log.spam_report,\n )\n email_log.is_spam = True\n email_log.spam_status = spam_status\n Session.commit()\n\n handle_spam(contact, alias, msg, user, mailbox, email_log)\n return False, status.E519\n\n if contact.invalid_email:\n LOG.d(\"add noreply information %s %s\", alias, mailbox)\n msg = add_header(\n msg,\n f\"\"\"Email sent to {alias.email} from an invalid address and cannot be replied\"\"\",\n f\"\"\"Email sent to {alias.email} from an invalid address and cannot be replied\"\"\",\n )\n\n headers_to_keep = [\n headers.FROM,\n headers.TO,\n headers.CC,\n headers.SUBJECT,\n headers.DATE,\n # do not delete original message id\n headers.MESSAGE_ID,\n # References and In-Reply-To are used for keeping the email thread\n headers.REFERENCES,\n headers.IN_REPLY_TO,\n headers.SL_QUEUE_ID,\n headers.LIST_UNSUBSCRIBE,\n headers.LIST_UNSUBSCRIBE_POST,\n ] + headers.MIME_HEADERS\n if user.include_header_email_header:\n headers_to_keep.append(headers.AUTHENTICATION_RESULTS)\n delete_all_headers_except(msg, headers_to_keep)\n\n if mailbox.generic_subject:\n LOG.d(\"Use a generic subject for %s\", mailbox)\n orig_subject = msg[headers.SUBJECT]\n orig_subject = get_header_unicode(orig_subject)\n add_or_replace_header(msg, \"Subject\", mailbox.generic_subject)\n sender = msg[headers.FROM]\n sender = get_header_unicode(sender)\n msg = add_header(\n msg,\n f\"\"\"Forwarded by SimpleLogin to {alias.email} from \"{sender}\" with \"{orig_subject}\" as subject\"\"\",\n f\"\"\"Forwarded by SimpleLogin to {alias.email} from \"{sender}\" with <b>{orig_subject}</b> as subject\"\"\",\n )\n\n # create PGP email if needed\n if mailbox.pgp_enabled() and user.is_premium() and not alias.disable_pgp:\n LOG.d(\"Encrypt message using mailbox %s\", mailbox)\n\n try:\n msg = prepare_pgp_message(\n msg, mailbox.pgp_finger_print, mailbox.pgp_public_key, can_sign=True\n )\n except PGPException:\n LOG.w(\n \"Cannot encrypt message %s -> %s. %s %s\", contact, alias, mailbox, user\n )\n msg = add_header(\n msg,\n f\"\"\"PGP encryption fails with {mailbox.email}'s PGP key\"\"\",\n )\n\n # add custom header\n add_or_replace_header(msg, headers.SL_DIRECTION, \"Forward\")\n\n msg[headers.SL_EMAIL_LOG_ID] = str(email_log.id)\n if user.include_header_email_header:\n msg[headers.SL_ENVELOPE_FROM] = envelope.mail_from\n if contact.name:\n original_from = f\"{contact.name} <{contact.website_email}>\"\n else:\n original_from = contact.website_email\n msg[headers.SL_ORIGINAL_FROM] = original_from\n # when an alias isn't in the To: header, there's no way for users to know what alias has received the email\n msg[headers.SL_ENVELOPE_TO] = alias.email\n\n if not msg[headers.DATE]:\n LOG.w(\"missing date header, create one\")\n msg[headers.DATE] = formatdate()\n\n replace_sl_message_id_by_original_message_id(msg)\n\n # change the from_header so the email comes from a reverse-alias\n # replace the email part in from: header\n old_from_header = msg[headers.FROM]\n new_from_header = contact.new_addr()\n add_or_replace_header(msg, \"From\", new_from_header)\n LOG.d(\"From header, new:%s, old:%s\", new_from_header, old_from_header)\n\n if reply_to_contact:\n reply_to_header = msg[headers.REPLY_TO]\n new_reply_to_header = reply_to_contact.new_addr()\n add_or_replace_header(msg, \"Reply-To\", new_reply_to_header)\n LOG.d(\"Reply-To header, new:%s, old:%s\", new_reply_to_header, reply_to_header)\n\n # replace CC & To emails by reverse-alias for all emails that are not alias\n try:\n replace_header_when_forward(msg, alias, headers.CC)\n replace_header_when_forward(msg, alias, headers.TO)\n except CannotCreateContactForReverseAlias:\n LOG.d(\"CannotCreateContactForReverseAlias error, delete %s\", email_log)\n EmailLog.delete(email_log.id)\n Session.commit()\n raise\n\n # add alias to To: header if it isn't included in To and Cc header\n add_alias_to_header_if_needed(msg, alias)\n\n # add List-Unsubscribe header\n msg = UnsubscribeGenerator().add_header_to_message(alias, contact, msg)\n\n add_dkim_signature(msg, EMAIL_DOMAIN)\n\n LOG.d(\n \"Forward mail from %s to %s, mail_options:%s, rcpt_options:%s \",\n contact.website_email,\n mailbox.email,\n envelope.mail_options,\n envelope.rcpt_options,\n )\n\n contact_domain = get_email_domain_part(contact.reply_email)\n try:\n sl_sendmail(\n # use a different envelope sender for each forward (aka VERP)\n generate_verp_email(VerpType.bounce_forward, email_log.id, contact_domain),\n mailbox.email,\n msg,\n envelope.mail_options,\n envelope.rcpt_options,\n is_forward=True,\n )\n except (SMTPServerDisconnected, SMTPRecipientsRefused, TimeoutError):\n LOG.w(\n \"Postfix error during forward phase %s -> %s -> %s\",\n contact,\n alias,\n mailbox,\n exc_info=True,\n )\n if should_ignore_bounce(envelope.mail_from):\n return True, status.E207\n else:\n EmailLog.delete(email_log.id, commit=True)\n # so Postfix can retry\n return False, status.E407\n else:\n Session.commit()\n return True, status.E200", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def collect_root_requirements(\n self, root_ireqs: List[InstallRequirement]\n ) -> CollectedRootRequirements:\n collected = CollectedRootRequirements([], {}, {})\n for i, ireq in enumerate(root_ireqs):\n if ireq.constraint:\n # Ensure we only accept valid constraints\n problem = check_invalid_constraint_type(ireq)\n if problem:\n raise InstallationError(problem)\n if not ireq.match_markers():\n continue\n assert ireq.name, \"Constraint must be named\"\n name = canonicalize_name(ireq.name)\n if name in collected.constraints:\n collected.constraints[name] &= ireq\n else:\n collected.constraints[name] = Constraint.from_ireq(ireq)\n else:\n reqs = list(\n self._make_requirements_from_install_req(\n ireq,\n requested_extras=(),\n )\n )\n if not reqs:\n continue\n template = reqs[0]\n if ireq.user_supplied and template.name not in collected.user_requested:\n collected.user_requested[template.name] = i\n collected.requirements.extend(reqs)\n # Put requirements with extras at the end of the root requires. This does not\n # affect resolvelib's picking preference but it does affect its initial criteria\n # population: by putting extras at the end we enable the candidate finder to\n # present resolvelib with a smaller set of candidates to resolvelib, already\n # taking into account any non-transient constraints on the associated base. This\n # means resolvelib will have fewer candidates to visit and reject.\n # Python's list sort is stable, meaning relative order is kept for objects with\n # the same key.\n collected.requirements.sort(key=lambda r: r.name != r.project_name)\n return collected", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def init_roles() -> str:\n role_data = get_role_spec(data=ROLE_SPEC, schema=ROLE_SCHEMA)\n for role in role_data[\"roles\"]:\n if \"child\" not in role:\n continue\n\n break_flag = False\n for child_name in role[\"child\"]:\n for child_role in role_data[\"roles\"]:\n if child_role[\"name\"] == child_name:\n break_flag = True\n\n break\n\n if not break_flag:\n raise_adcm_ex(\"INVALID_ROLE_SPEC\", f'child role \"{child_name}\" is absent')\n\n role_migration = RoleMigration.objects.last()\n if role_migration is None:\n role_migration = RoleMigration(version=0)\n\n if role_data[\"version\"] > role_migration.version:\n with transaction.atomic():\n upgrade(data=role_data)\n role_migration.version = role_data[\"version\"]\n role_migration.save()\n\n for bundle in Bundle.objects.exclude(name=\"ADCM\"):\n prepare_action_roles(bundle=bundle)\n logger.info('Prepare roles for \"%s\" bundle.', bundle.name)\n\n for policy in Policy.objects.all():\n policy.apply()\n\n logger.info(\"Roles are upgraded to version %s\", role_migration.version)\n msg = f\"Roles are upgraded to version {role_migration.version}\"\n else:\n msg = f\"Roles are already at version {role_migration.version}\"\n\n return msg", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def runImageBackup(self, answer):\n\t\tdef consoleCallback(result=None):\n\t\t\tprint(\"[ImageBackup] Image backup completed.\")\n\t\t\tself.close()\n\n\t\tlabel, slotCode, target, recovery = answer if answer else (None, None, None, None)\n\t\tif slotCode:\n\t\t\tshutdownOK = config.usage.shutdownOK.value\n\t\t\tconfig.usage.shutdownOK.setValue(True)\n\t\t\tconfig.usage.shutdownOK.save()\n\t\t\tconfigfile.save()\n\t\t\t# Make sure that the image backup target exists.\n\t\t\ttarget = join(target, \"images\")\n\t\t\tif not exists(target):\n\t\t\t\ttry:\n\t\t\t\t\tmakedirs(target)\n\t\t\t\texcept OSError as err:\n\t\t\t\t\tprint(f\"[ImageBackup] Error {err.errno}: Can't create backup directory '{target}'! ({err.strerror})\")\n\t\t\t\t\tself.session.open(MessageBox, f\"{_(\"Error\")} {err.errno}: {_(\"Can't create backup directory!\")} ({err.strerror})\", MessageBox.TYPE_ERROR, timeout=10, windowTitle=self.getTitle())\n\t\t\t\t\treturn\n\t\t\t# Get information about image to be backed up.\n\t\t\tif BoxInfo.getItem(\"canRecovery\"):\n\t\t\t\temmcing = BoxInfo.getItem(\"canRecovery\")[0]\n\t\t\t\tmtdBoot = BoxInfo.getItem(\"canRecovery\")[1]\n\t\t\telse:\n\t\t\t\temmcing = \"None\"\n\t\t\t\tmtdBoot = \"None\"\n\t\t\thasMultiBootMDT = False\n\t\t\trootfsSubDir = None\n\t\t\tif MultiBoot.canMultiBoot():\n\t\t\t\tbootSlots = MultiBoot.getBootSlots()\n\t\t\t\thasMultiBootMDT = bootSlots[slotCode].get(\"ubi\", False)\n\t\t\t\trootfsSubDir = bootSlots[slotCode].get(\"rootsubdir\")\n\t\t\t\tif BoxInfo.getItem(\"HasKexecMultiboot\") and slotCode == \"R\":\n\t\t\t\t\tmtdKernel = bootSlots[slotCode][\"kernel\"]\n\t\t\t\t\trootfsSubDir = None\n\t\t\t\telse:\n\t\t\t\t\tmtdKernel = bootSlots[slotCode][\"kernel\"].split(\"/\")[2]\n\t\t\t\tmtdRootFs = bootSlots[slotCode][\"device\"] if hasMultiBootMDT else bootSlots[slotCode][\"device\"].split(\"/\")[2]\n\t\t\telse:\n\t\t\t\tmtdKernel = BoxInfo.getItem(\"mtdkernel\")\n\t\t\t\tmtdRootFs = BoxInfo.getItem(\"mtdrootfs\")\n\t\t\tisNotCurrent = MultiBoot.getCurrentSlotCode() != slotCode\n\t\t\t# Start creating the image backup script.\n\t\t\tprint(f\"[ImageBackup] Bulding shell script '{self.runScript}' to perform the image backup.\")\n\t\t\tcmdLines = []\n\t\t\tcmdLines.append(f\"#!{self.shellCmd}\")\n\t\t\tcmdLines.append(f\"StartTime=`{self.dateCmd} -u +\\\"%s\\\"`\")\n\t\t\t# Display the starting message to the user.\n\t\t\tlines = []\n\t\t\tlines.append(_(\"Backup tool for %s %s\") % getBoxDisplayName())\n\t\t\tlines.append(self.separator)\n\t\t\tlines.append(\"\")\n\t\t\tlines.append(_(\"A backup is now being created.\"))\n\t\t\tlines.append(_(\"Please be patient.\"))\n\t\t\tlines.append(_(\"The backup can take up to about 15 minutes to complete.\"))\n\t\t\tlines.append(self.separator)\n\t\t\tlines.append(\"\")\n\t\t\tlines.append(_(\"Backup Mode: USB Recovery\") if recovery else _(\"Backup Mode: Flash Online\"))\n\t\t\tlines.append(self.separator)\n\t\t\tlines.append(\"\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{\"\\n\".join(lines)}\\\"\")\n\t\t\t# Create working directories.\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create working directories.\\\"\")\n\t\t\tworkDir = f\"{join(target, \"ib\", \"\")}\" # NOTE: workDir will always have a trailing \"/\".\n\t\t\tcmdLines.append(f\"{self.removeCmd} -rf {workDir}\")\n\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {workDir}\")\n\t\t\tmountPoint = \"/tmp/ib/RootSubdir/\" if rootfsSubDir else \"/tmp/ib/root/\" # NOTE: mountPoint will always have a trailing \"/\".\n\t\t\tbackupRoot = mountPoint # NOTE: backupRoot will always have a trailing \"/\".\n\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {mountPoint}\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Mount root file system.\\\"\") # Mount the root file system.\n\t\t\tif MultiBoot.canMultiBoot():\n\t\t\t\tmountArgs = f\"/dev/{mtdRootFs} {mountPoint}\"\n\t\t\t\tif rootfsSubDir:\n\t\t\t\t\tif hasMultiBootMDT:\n\t\t\t\t\t\tmountArgs = f\"-t ubifs {mtdRootFs} {mountPoint}\"\n\t\t\t\t\tbackupRoot = f\"{join(backupRoot, rootfsSubDir, \"\")}\" # NOTE: backupRoot will always have a trailing \"/\".\n\t\t\telse:\n\t\t\t\tmountArgs = f\"--bind / {mountPoint}\"\n\t\t\tcmdLines.append(f\"{self.mountCmd} {mountArgs}\")\n\t\t\t# Extract some image information.\n\t\t\tcmdLines.append(f\"if [ -f {backupRoot}usr/lib/enigma.info ]; then\")\n\t\t\tcmdLines.append(f\"\\tDistro=`{self.grepCmd} \\\"^distro=\\\" {backupRoot}usr/lib/enigma.info | {self.sedCmd} -En \\\"s/^\\\\w+=(['\\\\\\\"]?)(.*?)\\\\1$/\\\\2/p\\\"`\")\n\t\t\tcmdLines.append(f\"\\tDisplayDistro=`{self.grepCmd} \\\"^displaydistro=\\\" {backupRoot}usr/lib/enigma.info | {self.sedCmd} -En \\\"s/^\\\\w+=(['\\\\\\\"]?)(.*?)\\\\1$/\\\\2/p\\\"`\")\n\t\t\tcmdLines.append(f\"\\tImageVersion=`{self.grepCmd} \\\"^imageversion=\\\" {backupRoot}usr/lib/enigma.info | {self.sedCmd} -En \\\"s/^\\\\w+=(['\\\\\\\"]?)(.*?)\\\\1$/\\\\2/p\\\"`\")\n\t\t\tcmdLines.append(f\"elif [ -f {backupRoot}etc/image-version ]; then\")\n\t\t\tcmdLines.append(f\"\\tDistro=`{self.grepCmd} \\\"^distro=\\\" {backupRoot}etc/image-version | {self.cutCmd} -d\\\"=\\\" -f2`\")\n\t\t\tcmdLines.append(\"\\tif [ \\\"$Distro\\\" == \\\"\\\" ]; then\")\n\t\t\tcmdLines.append(f\"\\t\\tDisplayDistro=`{self.grepCmd} \\\"^creator=\\\" {backupRoot}etc/image-version | {self.cutCmd} -d\\\"=\\\" -f2`\")\n\t\t\tcmdLines.append(f\"\\t\\tDistro=`{self.echoCmd} \\\"$DisplayDistro\\\" | {self.cutCmd} -d\\\" \\\" -f1`\")\n\t\t\tcmdLines.append(f\"\\t\\tVersion=`{self.grepCmd} \\\"^version=\\\" {backupRoot}etc/image-version | {self.cutCmd} -d\\\"=\\\" -f2`\")\n\t\t\tcmdLines.append(f\"\\t\\tImageVersion=`{self.echoCmd} \\\"${{Version:0:3}}\\\" | {self.sedCmd} -En \\\"s/^0*(\\\\d*)/\\\\1/p\\\"`.${{Version:3:1}}.${{Version:4:2}}\")\n\t\t\tcmdLines.append(\"\\telse\")\n\t\t\tcmdLines.append(f\"\\t\\tDisplayDistro=`{self.grepCmd} \\\"^creator=\\\" {backupRoot}etc/image-version | {self.cutCmd} -d\\\"=\\\" -f2`\")\n\t\t\tcmdLines.append(f\"\\t\\tImageVersion=`{self.grepCmd} \\\"^imageversion=\\\" {backupRoot}etc/image-version | {self.cutCmd} -d\\\"=\\\" -f2`\")\n\t\t\tcmdLines.append(\"\\tfi\")\n\t\t\tcmdLines.append(f\"elif [ -f {backupRoot}etc/issue ]; then\")\n\t\t\tcmdLines.append(f\"\\tData=`{self.sedCmd} -n 2p {backupRoot}etc/issue`\")\n\t\t\tcmdLines.append(f\"\\tDistro=`{self.echoCmd} $Data | {self.cutCmd} -d\\\" \\\" -f1`\")\n\t\t\tcmdLines.append(f\"\\tDisplayDistro=`{self.sedCmd} -n 1p {backupRoot}etc/issue | {self.cutCmd} -d\\\" \\\" -f3`\")\n\t\t\tcmdLines.append(f\"\\tImageVersion=`{self.echoCmd} $Data | {self.cutCmd} -d\\\" \\\" -f2`\")\n\t\t\tcmdLines.append(\"else\")\n\t\t\tcmdLines.append(\"\\tDistro=Unknown\")\n\t\t\tcmdLines.append(\"\\tDisplayDistro=Unknown\")\n\t\t\tcmdLines.append(\"\\tImageVersion=Unknown\")\n\t\t\tcmdLines.append(\"fi\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Image version $DisplayDistro $ImageVersion.\\\"\")\n\t\t\t# Build the \"imageversion\" inventory file.\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"[Image Version]\\\" > /tmp/imageversion\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"distro=$Distro\\\" >> /tmp/imageversion\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"displaydistro=$DisplayDistro\\\" >> /tmp/imageversion\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"imageversion=$ImageVersion.\\\" >> /tmp/imageversion\")\n\t\t\tif not recovery:\n\t\t\t\tinfoPath = \"/\"\n\t\t\t\tif MultiBoot.canMultiBoot() and isNotCurrent:\n\t\t\t\t\tinfoPath = backupRoot\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} >> /tmp/imageversion\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"[Enigma2 Settings]\\\" >> /tmp/imageversion\")\n\t\t\t\tcmdLines.append(f\"{self.catCmd} {infoPath}etc/enigma2/settings >> /tmp/imageversion\")\n\t\t\tif not isNotCurrent:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} >> /tmp/imageversion\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"[Installed Plugins]\\\" >> /tmp/imageversion\")\n\t\t\t\tcmdLines.append(f\"{self.opkgCmd} list-installed | {self.grepCmd} \\\"enigma2-plugin-*\\\" >> /tmp/imageversion\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} 3 > /proc/sys/vm/drop_caches\") # Clear memory caches.\n\t\t\t# Create the root file system image.\n\t\t\timageFs = BoxInfo.getItem(\"imagefs\").strip().split()\n\t\t\tmkubifsArgs = BoxInfo.getItem(\"mkubifs\")\n\t\t\tbackupRootNoSlash = backupRoot[:-1]\n\t\t\tif \"jffs2\" in imageFs:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create root journaling flash file system.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.mkfsJffs2} --root={backupRootNoSlash} --faketime --output={workDir}root.jffs2 {mkubifsArgs}\")\n\t\t\telif \"ubi\" in imageFs:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create root UBI file system.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} > {workDir}root.ubi\")\n\t\t\t\tcmdLines.append(f\"{self.mkfsUbiCmd} -r {backupRootNoSlash} -o {workDir}root.ubi {mkubifsArgs}\")\n\t\t\t\tlines = []\n\t\t\t\tlines.append(\"[ubifs]\")\n\t\t\t\tlines.append(\"mode=ubi\")\n\t\t\t\tlines.append(f\"image={workDir}root.ubi\")\n\t\t\t\tlines.append(\"vol_id=0\")\n\t\t\t\tlines.append(\"vol_type=dynamic\")\n\t\t\t\tlines.append(\"vol_name=rootfs\")\n\t\t\t\tlines.append(\"vol_flags=autoresize\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} '{\"\\n\".join(lines)}' > {workDir}ubinize.cfg\")\n\t\t\t\tcmdLines.append(f\"{self.ubiCmd} -o {workDir}root.ubifs {BoxInfo.getItem(\"ubinize\")} {workDir}ubinize.cfg\")\n\t\t\telif not recovery:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create tar file of root file system.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.touchCmd} {workDir}rootfs.tar\") # Uncomment this line and comment out the line below to enable a fast backup debugging mode.\n\t\t\t\tcmdLines.append(f\"{self.tarCmd} -cf {workDir}rootfs.tar -C {backupRootNoSlash} --exclude ./boot/kernel.img --exclude ./var/nmbd --exclude ./.resizerootfs --exclude ./.resize-rootfs --exclude ./.resize-linuxrootfs --exclude ./.resize-userdata --exclude ./var/lib/samba/private/msg.sock --exclude ./var/lib/samba/msg.sock/* --exclude ./run/avahi-daemon/socket --exclude ./run/chrony/chronyd.sock --exclude ./run/udev/control .\")\n\t\t\t\tcmdLines.append(f\"{self.syncCmd}\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Compress root file system tar file. (This takes the most time!)\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.bzip2Cmd} {workDir}rootfs.tar\")\n\t\t\tcmdLines.append(f\"{self.syncCmd}\")\n\t\t\t# Create other image backup components.\n\t\t\tboxName = BoxInfo.getItem(\"BoxName\")\n\t\t\tif boxName in (\"gbquad4k\", \"gbquad4kpro\", \"gbue4k\", \"gbx34k\"):\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create boot dump.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p1 of={workDir}boot.bin\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create rescue dump.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p3 of={workDir}rescue.bin\")\n\t\t\tdisplayNames = [\"fast boot\", \"boot arguments\", \"base parameters\", \"PQ parameters\", \"logo\"]\n\t\t\tmodel = BoxInfo.getItem(\"model\")\n\t\t\tif model in (\"h9\", \"i55plus\"):\n\t\t\t\tfor index, value in enumerate([\"fastboot\", \"bootargs\", \"baseparam\", \"pq_param\", \"logo\"]):\n\t\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[index]} dump.\\\"\")\n\t\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mtd{index} of={workDir}{value}.bin\")\n\t\t\tif emmcing == self.usbBin and recovery:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[0]} dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p1 of={workDir}fastboot.bin\")\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/fastboot.bin {workDir}\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[1]} dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p2 of={workDir}bootargs.bin\")\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {workDir}\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create boot image dump.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p3 of={workDir}boot.img\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[2]} dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {workDir}baseparam.img\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p4 of={workDir}baseparam.img\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[3]} dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {workDir}pq_param.bin\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p5 of={workDir}pq_param.bin\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create {displayNames[4]} dump.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p6 of={workDir}logo.img\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create device information dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {workDir}deviceinfo.bin\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p7 of={workDir}deviceinfo.bin\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create application loader dump.\\\"\")\n\t\t\t\t# cmdLines.append(f\"{self.ddCmd} if=/dev/mmcblk0p10 of={workDir}apploader.bin\")\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/apploader.bin {workDir}\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create root file system dump.\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/zero of={workDir}rootfs.ext4 seek=$(((`{self.duCmd} -sb \\\"{backupRoot}\\\" | cut -f1` / 1024) + 200000)) count=60 bs=1024\")\n\t\t\t\tcmdLines.append(f\"{self.mkfsExt4} -F -i 4096 {workDir}rootfs.ext4\")\n\t\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {workDir}userdata\")\n\t\t\t\tcmdLines.append(f\"{self.mountCmd} {workDir}rootfs.ext4 {workDir}userdata\")\n\t\t\t\tfor rootIndex in range(1, 5):\n\t\t\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {workDir}userdata/linuxrootfs{rootIndex}\")\n\t\t\t\tcmdLines.append(f\"{self.rsyncCmd} -aAX {backupRoot} {workDir}userdata/linuxrootfs1\")\n\t\t\t\tcmdLines.append(f\"{self.unmountCmd} {workDir}userdata\")\n\t\t\t# Create the kernel dump.\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create kernel dump.\\\"\")\n\t\t\tkernelFile = BoxInfo.getItem(\"kernelfile\")\n\t\t\tif MultiBoot.canMultiBoot() or mtdKernel.startswith(\"mmcblk0\") or model in (\"h8\", \"hzero\"):\n\t\t\t\tif BoxInfo.getItem(\"HasKexecMultiboot\") or BoxInfo.getItem(\"HasGPT\"):\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} /{mtdKernel} {workDir}{kernelFile}\")\n\t\t\t\telse:\n\t\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdKernel} of={workDir}{kernelFile}\")\n\t\t\telse:\n\t\t\t\tcmdLines.append(f\"{self.nandDumpCmd} -a -f {workDir}vmlinux.gz {join(\"/dev\", mtdKernel)}\")\n\t\t\tif emmcing == \"disk.img\" and recovery:\n\t\t\t\tblockSize = 512 # These values are all assumed to be integers!\n\t\t\t\tblockSectors = 2\n\t\t\t\timageRoorFSAlignment = 1024\n\t\t\t\tbootPartitionSize = 3072\n\t\t\t\tkernelPartitionSize = 8192\n\t\t\t\trootFSPartitionSize = 1048576\n\t\t\t\temmcImageSize = 3817472\n\t\t\t\tkernelPartitionOffset = imageRoorFSAlignment + bootPartitionSize\n\t\t\t\trootFSPartitionOffset = kernelPartitionOffset + kernelPartitionSize\n\t\t\t\tsecondKernelPartitionOffset = rootFSPartitionOffset + rootFSPartitionSize\n\t\t\t\tthirdKernelPartitionOffset = secondKernelPartitionOffset + kernelPartitionSize\n\t\t\t\tfourthKernelPartitionOffset = thirdKernelPartitionOffset + kernelPartitionSize\n\t\t\t\temmcImage = f\"{workDir}{emmcing}\"\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{_(\"Create recovery image backup '%s'.\") % emmcing}\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/zero of={emmcImage} bs={blockSize} count=0 seek={emmcImageSize * blockSectors}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} mklabel gpt\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart boot fat16 {imageRoorFSAlignment} {imageRoorFSAlignment + bootPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart linuxkernel {kernelPartitionOffset} {kernelPartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart linuxrootfs ext4 {rootFSPartitionOffset} {rootFSPartitionOffset + rootFSPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart linuxkernel2 {secondKernelPartitionOffset} {secondKernelPartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart linuxkernel3 {thirdKernelPartitionOffset} {thirdKernelPartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart linuxkernel4 {fourthKernelPartitionOffset} {fourthKernelPartitionOffset + kernelPartitionSize}\")\n\t\t\t\tlines = fileReadLines(\"/proc/swaps\", default=[], source=MODULE_NAME)\n\t\t\t\tmmcblk0p7Found = False\n\t\t\t\tfor line in lines:\n\t\t\t\t\tif \"mmcblk0p7\" in line:\n\t\t\t\t\t\tmmcblk0p7Found = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif mmcblk0p7Found:\n\t\t\t\t\tswapPartitionSize = 262144\n\t\t\t\t\tswapPartitionOffset = fourthKernelPartitionOffset + kernelPartitionSize\n\t\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart swap linux-swap {swapPartitionOffset} {swapPartitionOffset + swapPartitionSize}\")\n\t\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart userdata ext4 {swapPartitionOffset + swapPartitionSize} 100%\")\n\t\t\t\telse:\n\t\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart userdata ext4 {fourthKernelPartitionOffset + kernelPartitionSize} 100%\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdBoot} of={emmcImage} seek={imageRoorFSAlignment * blockSectors}\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdKernel} of={emmcImage} seek={kernelPartitionOffset * blockSectors}\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdRootFs} of={emmcImage} seek={rootFSPartitionOffset * blockSectors}\")\n\t\t\telif emmcing == \"emmc.img\" and recovery: # BOOTDD_VOLUME_ID = \"boot\".\n\t\t\t\tblockSectors = 2 # These values are all assumed to be integers!\n\t\t\t\timageRoorFSAlignment = 1024\n\t\t\t\tbootPartitionSize = 3072\n\t\t\t\tkernelPartitionSize = 8192\n\t\t\t\trootFSPartitionSize = 1898496\n\t\t\t\temmcImageSize = 7634944\n\t\t\t\tel1PartitionOffset = imageRoorFSAlignment + bootPartitionSize\n\t\t\t\trootFSPartitionOffset = el1PartitionOffset + kernelPartitionSize\n\t\t\t\tkernel2PartitionOffset = rootFSPartitionOffset + rootFSPartitionSize\n\t\t\t\trootFS2PartitionOffset = kernel2PartitionOffset + kernelPartitionSize\n\t\t\t\tkernel3PartitionOffset = rootFS2PartitionOffset + rootFSPartitionSize\n\t\t\t\trootFS3PartitionOffset = kernel3PartitionOffset + kernelPartitionSize\n\t\t\t\tkernel4PartitionOffset = rootFS3PartitionOffset + rootFSPartitionSize\n\t\t\t\trootFS4PartitionOffset = kernel4PartitionOffset + kernelPartitionSize\n\t\t\t\temmcImage = f\"{workDir}{emmcing}\"\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{_(\"Create recovery image backup '%s'.\") % emmcing}\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/zero of={emmcImage} bs=1 count=0 seek={emmcImageSize * imageRoorFSAlignment}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} mklabel gpt\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart boot fat16 {imageRoorFSAlignment} {imageRoorFSAlignment + bootPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} set 1 boot on\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart kernel1 {el1PartitionOffset} {el1PartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart rootfs1 ext4 {rootFSPartitionOffset} {rootFSPartitionOffset + rootFSPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart kernel2 {kernel2PartitionOffset} {kernel2PartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart rootfs2 ext4 {rootFS2PartitionOffset} {rootFS2PartitionOffset + rootFSPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart kernel3 {kernel3PartitionOffset} {kernel3PartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart rootfs3 ext4 {rootFS3PartitionOffset} {rootFS3PartitionOffset + rootFSPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart kernel4 {kernel4PartitionOffset} {kernel4PartitionOffset + kernelPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.partedCmd} -s {emmcImage} unit KiB mkpart rootfs4 ext4 {rootFS4PartitionOffset} {rootFS4PartitionOffset + rootFSPartitionSize}\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdBoot} of={emmcImage} seek={imageRoorFSAlignment * blockSectors}\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdKernel} of={emmcImage} seek={el1PartitionOffset * blockSectors}\")\n\t\t\t\tcmdLines.append(f\"{self.ddCmd} if=/dev/{mtdRootFs} of={emmcImage} seek={rootFSPartitionOffset * blockSectors} \")\n\t\t\telif emmcing == self.usbBin and recovery:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{_(\"Create recovery image backup '%s'.\") % emmcing}\\\"\")\n\t\t\t\tlines = []\n\t\t\t\tlines.append(\"<?xml version=\\\"1.0\\\" encoding=\\\"GB2312\\\" ?>\")\n\t\t\t\tlines.append(\"<Partition_Info>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"fastboot\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"0\\\" Length=\\\"1M\\\" SelectFile=\\\"fastboot.bin\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"bootargs\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"1M\\\" Length=\\\"1M\\\" SelectFile=\\\"bootargs.bin\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"bootoptions\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"2M\\\" Length=\\\"1M\\\" SelectFile=\\\"boot.img\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"baseparam\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"3M\\\" Length=\\\"3M\\\" SelectFile=\\\"baseparam.img\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"pqparam\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"6M\\\" Length=\\\"4M\\\" SelectFile=\\\"pq_param.bin\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"logo\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"10M\\\" Length=\\\"4M\\\" SelectFile=\\\"logo.img\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"deviceinfo\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"14M\\\" Length=\\\"4M\\\" SelectFile=\\\"deviceinfo.bin\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"loader\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"26M\\\" Length=\\\"32M\\\" SelectFile=\\\"apploader.bin\\\"/>\")\n\t\t\t\tlines.append(\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"linuxkernel1\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"none\\\" Start=\\\"66M\\\" Length=\\\"16M\\\" SelectFile=\\\"kernel.bin\\\"/>\")\n\t\t\t\tlines.append(f\"\\t<Part Sel=\\\"1\\\" PartitionName=\\\"userdata\\\" FlashType=\\\"emmc\\\" FileSystem=\\\"ext3/4\\\" Start=\\\"130M\\\" Length=\\\"{\"3580\" if model == \"sf8008m\" else \"7000\"}M\\\" SelectFile=\\\"rootfs.ext4\\\"/>\")\n\t\t\t\tlines.append(\"</Partition_Info>\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} '{\"\\n\".join(lines)}' > {workDir}emmc_partitions.xml\")\n\t\t\t\tcmdLines.append(f\"{self.mkupdateCmd} -s 00000003-00000001-01010101 -f {workDir}emmc_partitions.xml -d {workDir}{emmcing}\")\n\t\t\tcmdLines.append(f\"{self.syncCmd}\")\n\t\t\t# Assemble the image backup.\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{_(\"Assembling the image backup files.\")}\\\"\")\n\t\t\tmainDestinationRoot = f\"{join(target, f\"build_{boxName}\", \"\")}\" # NOTE: mainDestinationRoot will always have a trailing \"/\".\n\t\t\tmainDestination = f\"{join(target, f\"build_{boxName}\", BoxInfo.getItem(\"imagedir\"), \"\")}\" # NOTE: mainDestination will always have a trailing \"/\".\n\t\t\tcheckFiles = []\n\t\t\tif emmcing == self.usbBin and recovery:\n\t\t\t\tcmdLines.append(f\"{self.removeCmd} -rf {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} /tmp/imageversion {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(f\"if [ -f {backupRoot}usr/lib/enigma.info ]; then\")\n\t\t\t\tcmdLines.append(f\"\\t{self.copyCmd} {backupRoot}usr/lib/enigma.info {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(\"fi\")\n\t\t\t\tcmdLines.append(f\"if [ -f {backupRoot}usr/lib/enigma.conf ]; then\")\n\t\t\t\tcmdLines.append(f\"\\t{self.copyCmd} {backupRoot}usr/lib/enigma.conf {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(\"fi\")\n\t\t\telse:\n\t\t\t\tcmdLines.append(f\"{self.removeCmd} -rf {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.makeDirCmd} -p {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} /tmp/imageversion {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"if [ -f {backupRoot}usr/lib/enigma.info ]; then\")\n\t\t\t\tcmdLines.append(f\"\\t{self.copyCmd} {backupRoot}usr/lib/enigma.info {mainDestination}\")\n\t\t\t\tcmdLines.append(\"fi\")\n\t\t\t\tcmdLines.append(f\"if [ -f {backupRoot}usr/lib/enigma.conf ]; then\")\n\t\t\t\tcmdLines.append(f\"\\t{self.copyCmd} {backupRoot}usr/lib/enigma.conf {mainDestination}\")\n\t\t\t\tcmdLines.append(\"fi\")\n\t\t\t\tcmdLines.append(f\"if [ -f {backupRoot}etc/image-version ]; then\")\n\t\t\t\tcmdLines.append(f\"\\t{self.copyCmd} {backupRoot}etc/image-version {mainDestination}\")\n\t\t\t\tcmdLines.append(\"fi\")\n\t\t\t\tif not recovery:\n\t\t\t\t\tif model in (\"dm800se\", \"dm500hd\", \"dreamone\", \"dreamtwo\"):\n\t\t\t\t\t\tcmdLines.append(f\"{self.touchCmd} {mainDestination}{kernelFile}\")\n\t\t\t\t\telif MultiBoot.canMultiBoot() or mtdKernel.startswith(\"mmcblk0\") or model in (\"h8\", \"hzero\"):\n\t\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}{kernelFile} {mainDestination}\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}vmlinux.gz {mainDestination}{kernelFile}\")\n\t\t\t\t\trootFile = BoxInfo.getItem(\"rootfile\")\n\t\t\t\t\tif rootFile in (\"rootfs.tar.bz2\", \"rootfs-two.tar.bz2\", \"rootfs-one.tar.bz2\"):\n\t\t\t\t\t\tif model in (\"dreamone\", \"dreamtwo\"):\n\t\t\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}rootfs.tar.bz2 {mainDestination}{rootFile}\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}{rootFile} {mainDestination}\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}root.ubifs {mainDestination}{rootFile}\")\n\t\t\t\t\tcheckFiles.append(f\"{mainDestination}{kernelFile}\")\n\t\t\t\t\tcheckFiles.append(f\"{mainDestination}{rootFile}\")\n\t\t\tif recovery:\n\t\t\t\tif emmcing == self.usbBin:\n\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}{emmcing} {mainDestinationRoot}\")\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/fastboot.bin {mainDestinationRoot}\")\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {mainDestinationRoot}\")\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/apploader.bin {mainDestinationRoot}\")\n\t\t\t\t\tcheckFiles.append(f\"{mainDestinationRoot}{emmcing}\")\n\t\t\t\telse:\n\t\t\t\t\tcheckFiles.append(f\"{mainDestination}{emmcing}\")\n\t\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}{emmcing} {mainDestination}\")\n\t\t\t\tif emmcing == \"emmc.img\":\n\t\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Rename this file to 'force' to force an update without confirmation.\\\" > {mainDestination}noforce\")\n\t\t\telif boxName in (\"vuultimo4k\", \"vusolo4k\", \"vuduo2\", \"vusolo2\", \"vusolo\", \"vuduo\", \"vuultimo\", \"vuuno\"):\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"This file forces a reboot after the update.\\\" > {mainDestination}reboot.update\")\n\t\t\telif boxName in (\"vuzero\", \"vusolose\", \"vuuno4k\", \"vuzero4k\"):\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"This file forces the update.\\\" > {mainDestination}force.update\")\n\t\t\telif boxName in (\"viperslim\", \"evoslimse\", \"evoslimt2c\", \"novaip\", \"zgemmai55\", \"sf98\", \"xpeedlxpro\", \"evoslim\", \"vipert2c\"):\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"This file forces the update.\\\" > {mainDestination}force\")\n\t\t\telif rootfsSubDir:\n\t\t\t\tlines = []\n\t\t\t\tlines.append(f\"Rename the 'unforce_{model}.txt' to 'force_{model}.txt' and move it to the root of your usb-stick.\")\n\t\t\t\tlines.append(\"When you enter the recovery menu then it will force to install the image in the linux1 selection.\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{\"\\n\".join(lines)}\\\" > {mainDestination}force_{model}_READ.ME\")\n\t\t\telse:\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Rename this file to 'force' to force an update without confirmation.\\\" > {mainDestination}noforce\")\n\t\t\tif boxName in (\"gbquad4k\", \"gbquad4kpro\", \"gbue4k\", \"gbx34k\"):\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}boot.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}rescue.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/gpt.bin {mainDestination}\")\n\t\t\tif model in (\"h9\", \"i55plus\"):\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}fastboot.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}pq_param.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}bootargs.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}baseparam.bin {mainDestination}\")\n\t\t\t\tcmdLines.append(f\"{self.moveCmd} {workDir}logo.bin {mainDestination}\")\n\t\t\tif boxName in (\"gbquad\", \"gbquadplus\", \"gb800ue\", \"gb800ueplus\", \"gbultraue\", \"gbultraueh\", \"twinboxlcd\", \"twinboxlcdci\", \"singleboxlcd\", \"sf208\", \"sf228\"):\n\t\t\t\tlcdWaitKey = \"/usr/share/lcdwaitkey.bin\"\n\t\t\t\tif isfile(lcdWaitKey):\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} {lcdWaitKey} {mainDestination}\")\n\t\t\t\tlcdWarning = \"/usr/share/lcdwarning.bin\"\n\t\t\t\tif isfile(lcdWarning):\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} {lcdWarning} {mainDestination}\")\n\t\t\tif boxName in (\"e4hdultra\", \"protek4k\"):\n\t\t\t\tlcdWarning = \"/usr/share/lcdflashing.bmp\"\n\t\t\t\tif isfile(lcdWarning):\n\t\t\t\t\tcmdLines.append(f\"{self.copyCmd} {lcdWarning} {mainDestination}\")\n\t\t\tif boxName == \"gb800solo\":\n\t\t\t\tlines = []\n\t\t\t\tlines.append(\"flash -noheader usbdisk0:gigablue/solo/kernel.bin flash0.kernel\")\n\t\t\t\tlines.append(\"flash -noheader usbdisk0:gigablue/solo/rootfs.bin flash0.rootfs\")\n\t\t\t\tlines.append(\"setenv -p STARTUP \\\"boot -z -elf flash0.kernel: 'rootfstype=jffs2 bmem=106M@150M root=/dev/mtdblock6 rw '\\\"\")\n\t\t\t\tcmdLines.append(f\"{self.echoCmd} '{\"\\n\".join(lines)}' > {mainDestinationRoot}burn.bat\")\n\t\t\tif model in (\"h9\", \"i55plus\"):\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/fastboot.bin {mainDestinationRoot}\")\n\t\t\t\tcmdLines.append(f\"{self.copyCmd} -f /usr/share/bootargs.bin {mainDestinationRoot}\")\n\t\t\tname = \"recovery_emmc\" if BoxInfo.getItem(\"canRecovery\") and recovery else \"usb\"\n\t\t\tcmdLines.append(f\"{self.echoCmd} 3 > /proc/sys/vm/drop_caches\") # Clear memory caches.\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"Create backup image zip file.\\\"\")\n\t\t\tcmdLines.append(f\"ZipName=$Distro-$ImageVersion-{boxName}-backup-`{self.dateCmd} +\\\"%Y%m%d_%H%M\\\"`_{name}.zip\")\n\t\t\tcmdLines.append(f\"{self.zipCmd} a -r -bt -bd -bso0 {target}/$ZipName {join(mainDestinationRoot, \"*\")}\")\n\t\t\tcmdLines.append(self.syncCmd)\n\t\t\tcheckFiles = \"\\\" -a \\\"\".join(checkFiles)\n\t\t\tcmdLines.append(f\"if [ -r \\\"{checkFiles}\\\" ]; then\")\n\t\t\tif MultiBoot.canMultiBoot() and not recovery and rootfsSubDir is None:\n\t\t\t\tlines = []\n\t\t\t\tlines.append(self.separator)\n\t\t\t\tlines.append(\"\")\n\t\t\t\tlines.append(f\"{_(\"Multiboot Image created:\")} $ZipName\")\n\t\t\t\tlines.append(self.separator)\n\t\t\t\tlines.append(\"\")\n\t\t\t\tlines.append(_(\"To restore the image use 'OnlineFlash' option in the 'SoftwareManager' menu.\"))\n\t\t\t\tcmdLines.append(f\"\\t{self.echoCmd} \\\"{\"\\n\".join(lines)}\\\"\")\n\t\t\telse:\n\t\t\t\tlines = []\n\t\t\t\tlines.append(self.separator)\n\t\t\t\tlines.append(\"\")\n\t\t\t\tlines.append(f\"{_(\"Image created:\")} $ZipName\")\n\t\t\t\tlines.append(self.separator)\n\t\t\t\tlines.append(\"\")\n\t\t\t\tlines.append(_(\"To restore the image check the manual or documentation for the receiver.\"))\n\t\t\t\tcmdLines.append(f\"\\t{self.echoCmd} \\\"{\"\\n\".join(lines)}\\\"\")\n\t\t\tcmdLines.append(\"else\")\n\t\t\tlines = []\n\t\t\tlines.append(f\"{_(\"Image creation failed!\")}\")\n\t\t\tlines.append(f\"{_(\"Possible causes could be:\")}\")\n\t\t\tlines.append(f\"{_(\"- Wrong backup destination.\")}\")\n\t\t\tlines.append(f\"{_(\"- No space left on backup device.\")}\")\n\t\t\tlines.append(f\"{_(\"- No write permission on backup device.\")}\")\n\t\t\tcmdLines.append(f\"\\t{self.echoCmd} \\\"{\"\\n\".join(lines)}\\\"\")\n\t\t\tcmdLines.append(\"fi\")\n\t\t\tcmdLines.append(f\"{self.removeCmd} -rf {join(target, f\"build_{boxName}\")}\")\n\t\t\tcmdLines.append(f\"{self.unmountCmd} {mountPoint}\") # Unmount the root file system.\n\t\t\tcmdLines.append(f\"{self.removeDirCmd} {mountPoint}\")\n\t\t\tcmdLines.append(f\"{self.removeDirCmd} /tmp/ib/\")\n\t\t\tcmdLines.append(f\"{self.removeCmd} -rf {workDir}\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} 3 > /proc/sys/vm/drop_caches\") # Clear memory caches.\n\t\t\tcmdLines.append(f\"{self.syncCmd}\")\n\t\t\tcmdLines.append(f\"{self.echoCmd}\")\n\t\t\tcmdLines.append(f\"EndTime=`{self.dateCmd} -u +\\\"%s\\\"`\")\n\t\t\tcmdLines.append(f\"RunTime=`{self.dateCmd} -u -d@\\\"$(($EndTime - $StartTime))\\\" +\\\"%H:%M:%S\\\"`\")\n\t\t\tcmdLines.append(f\"{self.echoCmd} \\\"{_(\"Time taken for the backup:\")} $RunTime\\\"\")\n\t\t\tfileWriteLines(self.runScript, cmdLines, source=MODULE_NAME)\n\t\t\tchmod(self.runScript, 0o755)\n\t\t\tprint(\"[ImageBackup] Running the shell script.\")\n\t\t\tself.session.openWithCallback(consoleCallback, Console, title=_(\"Image Backup To %s\") % target, cmdlist=[self.runScript], closeOnSuccess=False, showScripts=False)\n\t\t\tconfig.usage.shutdownOK.setValue(shutdownOK)\n\t\t\tconfig.usage.shutdownOK.save()\n\t\t\tconfigfile.save()\n\t\telse:\n\t\t\tself.close()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def make_api_ref(infiles):\n macros = []\n enums = []\n types = []\n functions = []\n for infile in infiles:\n while True:\n line = infile.readline()\n if not line:\n break\n elif line == '/**\\n':\n line = infile.readline()\n doctype = line.split()[1]\n if doctype == '@function':\n functions.append(process_function('function', infile))\n elif doctype == '@functypedef':\n types.append(process_function('type', infile))\n elif doctype == '@struct' or doctype == '@union':\n types.append(process_struct(infile))\n elif doctype == '@enum':\n enums.append(process_enum(infile))\n elif doctype == '@macro':\n macros.append(process_macro(infile))\n return macros, enums, types, functions\n\n alldocs = [('Macros', macros),\n ('Enums', enums),\n ('Types (structs, unions and typedefs)', types),\n ('Functions', functions)]", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-mr", "language": "python"} {"function": "def finishedAdd(self, answer):\n\t\t# print(\"finished add\")\n\t\tif not isinstance(answer, bool) and answer[0]:\n\t\t\tentry = answer[1]\n\t\t\tsimulTimerList = self.session.nav.RecordTimer.record(entry)\n\t\t\tif simulTimerList is not None:\n\t\t\t\tfor x in simulTimerList:\n\t\t\t\t\tif x.setAutoincreaseEnd(entry):\n\t\t\t\t\t\tself.session.nav.RecordTimer.timeChanged(x)\n\t\t\t\tsimulTimerList = self.session.nav.RecordTimer.record(entry)\n\t\t\t\tif simulTimerList is not None:\n\t\t\t\t\tif not entry.repeated and not config.recording.margin_before.value and not config.recording.margin_after.value and len(simulTimerList) > 1:\n\t\t\t\t\t\tchange_time = False\n\t\t\t\t\t\tconflict_begin = simulTimerList[1].begin\n\t\t\t\t\t\tconflict_end = simulTimerList[1].end\n\t\t\t\t\t\tif conflict_begin == entry.end:\n\t\t\t\t\t\t\tentry.end -= 30\n\t\t\t\t\t\t\tchange_time = True\n\t\t\t\t\t\telif entry.begin == conflict_end:\n\t\t\t\t\t\t\tentry.begin += 30\n\t\t\t\t\t\t\tchange_time = True\n\t\t\t\t\t\tif change_time:\n\t\t\t\t\t\t\tsimulTimerList = self.session.nav.RecordTimer.record(entry)\n\t\t\t\t\tif simulTimerList is not None:\n\t\t\t\t\t\tself.session.openWithCallback(self.finishSanityCorrection, TimerSanityConflict, simulTimerList)\n\t\t\tself[\"key_green\"].setText(_(\"Remove timer\"))\n\t\t\tself.key_green_choice = self.REMOVE_TIMER\n\t\telse:\n\t\t\tself[\"key_green\"].setText(_(\"Add Timer\"))\n\t\t\tself.key_green_choice = self.ADD_TIMER\n\t\t\t# print(\"Timeredit aborted\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@transaction.atomic\n def update(self, instance: models.Task, validated_data: dict[str, Any]) -> models.Task:\n validation_layout = getattr(instance.data, 'validation_layout', None)\n if not validation_layout:\n raise serializers.ValidationError(\"Validation is not configured in the task\")\n\n if 'disabled_frames' in validated_data:\n requested_disabled_frames = validated_data['disabled_frames']\n unknown_requested_disabled_frames = (\n set(requested_disabled_frames).difference(validation_layout.frames)\n )\n if unknown_requested_disabled_frames:\n raise serializers.ValidationError(\n \"Unknown frames requested for exclusion from the validation set {}\".format(\n format_list(tuple(map(str, sorted(unknown_requested_disabled_frames))))\n )\n )\n\n gt_job_meta_serializer = JobDataMetaWriteSerializer(instance.gt_job, {\n \"deleted_frames\": requested_disabled_frames\n })\n gt_job_meta_serializer.is_valid(raise_exception=True)\n gt_job_meta_serializer.save()\n\n frame_selection_method = validated_data.get('frame_selection_method')\n if frame_selection_method and not (\n validation_layout and\n instance.data.validation_layout.mode == models.ValidationMode.GT_POOL\n ):\n raise serializers.ValidationError(\n \"Honeypots can only be modified if the task \"\n f\"validation mode is '{models.ValidationMode.GT_POOL}'\"\n )\n\n if frame_selection_method == models.JobFrameSelectionMethod.MANUAL:\n requested_honeypot_real_frames = validated_data['honeypot_real_frames']\n\n task_honeypot_abs_frames = (\n instance.data.images\n .filter(is_placeholder=True)\n .order_by('frame')\n .values_list('frame', flat=True)\n )\n\n task_honeypot_frames_count = len(task_honeypot_abs_frames)\n if task_honeypot_frames_count != len(requested_honeypot_real_frames):\n raise serializers.ValidationError(\n \"Invalid size of 'honeypot_real_frames' array, \"\n f\"expected {task_honeypot_frames_count}\"\n )\n\n if frame_selection_method:\n for db_job in (\n models.Job.objects.select_related(\"segment\")\n .filter(segment__task_id=instance.id, type=models.JobType.ANNOTATION)\n .order_by(\"segment__start_frame\")\n .all()\n ):\n job_serializer_params = {\n 'frame_selection_method': frame_selection_method\n }\n\n if frame_selection_method == models.JobFrameSelectionMethod.MANUAL:\n segment_frame_set = db_job.segment.frame_set\n job_serializer_params['honeypot_real_frames'] = [\n requested_frame\n for abs_frame, requested_frame in zip(\n task_honeypot_abs_frames, requested_honeypot_real_frames\n )\n if abs_frame in segment_frame_set\n ]\n\n job_validation_layout_serializer = JobValidationLayoutWriteSerializer(\n db_job, job_serializer_params\n )\n job_validation_layout_serializer.is_valid(raise_exception=True)\n job_validation_layout_serializer.save()\n\n return instance", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "@staticmethod\n def with_line_numbers(\n s: str,\n start_line: typing.Optional[int] = None,\n end_line: typing.Optional[int] = None,\n expand_tabs: bool = True,\n eol_mark: str = \"|\",\n mark_spaces: typing.Optional[str] = None,\n mark_control: typing.Optional[str] = None,\n ) -> str:\n \"\"\"\n Helpful method for debugging a parser - prints a string with line and column numbers.\n (Line and column numbers are 1-based.)\n\n :param s: tuple(bool, str - string to be printed with line and column numbers\n :param start_line: int - (optional) starting line number in s to print (default=1)\n :param end_line: int - (optional) ending line number in s to print (default=len(s))\n :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default\n :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default=\"|\")\n :param mark_spaces: str - (optional) special character to display in place of spaces\n :param mark_control: str - (optional) convert non-printing control characters to a placeholding\n character; valid values:\n - \"unicode\" - replaces control chars with Unicode symbols, such as \"\u240d\" and \"\u240a\"\n - any single character string - replace control characters with given string\n - None (default) - string is displayed as-is\n\n :return: str - input string with leading line numbers and column number headers\n \"\"\"\n if expand_tabs:\n s = s.expandtabs()\n if mark_control is not None:\n mark_control = typing.cast(str, mark_control)\n if mark_control == \"unicode\":\n transtable_map = {\n c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))\n }\n transtable_map[127] = 0x2421\n tbl = str.maketrans(transtable_map)\n eol_mark = \"\"\n else:\n ord_mark_control = ord(mark_control)\n tbl = str.maketrans(\n {c: ord_mark_control for c in list(range(0, 32)) + [127]}\n )\n s = s.translate(tbl)\n if mark_spaces is not None and mark_spaces != \" \":\n if mark_spaces == \"unicode\":\n tbl = str.maketrans({9: 0x2409, 32: 0x2423})\n s = s.translate(tbl)\n else:\n s = s.replace(\" \", mark_spaces)\n if start_line is None:\n start_line = 1\n if end_line is None:\n end_line = len(s)\n end_line = min(end_line, len(s))\n start_line = min(max(1, start_line), end_line)\n\n if mark_control != \"unicode\":\n s_lines = s.splitlines()[start_line - 1 : end_line]\n else:\n s_lines = [line + \"\u240a\" for line in s.split(\"\u240a\")[start_line - 1 : end_line]]\n if not s_lines:\n return \"\"\n\n lineno_width = len(str(end_line))\n max_line_len = max(len(line) for line in s_lines)\n lead = \" \" * (lineno_width + 1)\n if max_line_len >= 99:\n header0 = (\n lead\n + \"\".join(\n f\"{' ' * 99}{(i + 1) % 100}\"\n for i in range(max(max_line_len // 100, 1))\n )\n + \"\\n\"\n )\n else:\n header0 = \"\"\n header1 = (\n header0\n + lead\n + \"\".join(f\" {(i + 1) % 10}\" for i in range(-(-max_line_len // 10)))\n + \"\\n\"\n )\n header2 = lead + \"1234567890\" * (-(-max_line_len // 10)) + \"\\n\"\n return (\n header1\n + header2\n + \"\\n\".join(\n f\"{i:{lineno_width}d}:{line}{eol_mark}\"\n for i, line in enumerate(s_lines, start=start_line)\n )\n + \"\\n\"\n )", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def format_unencoded(self, tokensource, outfile):\n self._write_lineno(outfile)\n\n for ttype, value in tokensource:\n color = self.colorscheme.get(ttype)\n while color is None:\n ttype = ttype[:-1]\n color = self.colorscheme.get(ttype)\n if color:\n color = color[self.darkbg]\n spl = value.split('\\n')\n for line in spl[:-1]:\n if line:\n outfile.write(ircformat(color, line))\n outfile.write('\\n')\n self._write_lineno(outfile)\n if spl[-1]:\n outfile.write(ircformat(color, spl[-1]))\n else:\n outfile.write(value)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def showServiceInformation(self):\n\t\tdef formatHex(value):\n\t\t\treturn f\"0x{value:04X} ({value})\" if value and isinstance(value, int) else \"\"\n\n\t\tdef getServiceInfoValue(item):\n\t\t\tif self.serviceInfo:\n\t\t\t\tvalue = self.serviceInfo.getInfo(item)\n\t\t\t\tif value == -2:\n\t\t\t\t\tvalue = self.serviceInfo.getInfoString(item)\n\t\t\t\telif value == -1:\n\t\t\t\t\tvalue = _(\"N/A\")\n\t\t\telse:\n\t\t\t\tvalue = \"\"\n\t\t\treturn value\n\n\t\tdef getNamespace(value):\n\t\t\tif isinstance(value, str):\n\t\t\t\tnamespace = f\"{_('N/A')} - {_('N/A')}\"\n\t\t\telse:\n\t\t\t\tnamespace = f\"{value & 0xFFFFFFFF:08X}\"\n\t\t\t\tif namespace.startswith(\"EEEE\"):\n\t\t\t\t\tnamespace = f\"{namespace} - DVB-T\"\n\t\t\t\telif namespace.startswith(\"FFFF\"):\n\t\t\t\t\tnamespace = f\"{namespace} - DVB-C\"\n\t\t\t\telse:\n\t\t\t\t\tposition = int(namespace[:4], 16)\n\t\t\t\t\tif position > 1800:\n\t\t\t\t\t\tposition = 3600 - position\n\t\t\t\t\t\talignment = _(\"W\")\n\t\t\t\t\telse:\n\t\t\t\t\t\talignment = _(\"E\")\n\t\t\t\t\tnamespace = f\"{namespace} - {float(position) / 10.0}\\u00B0{alignment}\"\n\t\t\treturn namespace\n\n\t\tdef getSubtitleList(): # IanSav: If we know the current subtitle then we should flag it as \"(Current)\".\n\t\t\tsubtitleTypes = { # This should be in SystemInfo maybe as a BoxInfo variable.\n\t\t\t\t0: _(\"Unknown\"),\n\t\t\t\t1: _(\"Embedded\"),\n\t\t\t\t2: _(\"SSA file\"),\n\t\t\t\t3: _(\"ASS file\"),\n\t\t\t\t4: _(\"SRT file\"),\n\t\t\t\t5: _(\"VOB file\"),\n\t\t\t\t6: _(\"PGS file\")\n\t\t\t}\n\t\t\tsubtitleSelected = self.service and self.service.subtitle().getCachedSubtitle()\n\t\t\tif subtitleSelected:\n\t\t\t\tsubtitleSelected = subtitleSelected[:3]\n\t\t\tsubtitle = self.service and self.service.subtitle()\n\t\t\tsubList = subtitle and subtitle.getSubtitleList() or []\n\t\t\tfor subtitle in subList:\n\t\t\t\tprint(subtitle)\n\t\t\t\tindent = \"P1F0\" if subtitle[:3] == subtitleSelected else \"P1\"\n\t\t\t\tsubtitleLang = subtitle[4]\n\t\t\t\tif subtitle[0] == 0: # DVB PID.\n\t\t\t\t\tinfo.append(formatLine(indent, _(\"DVB Subtitles PID & Language\"), f\"{formatHex(subtitle[1])} - {subtitleLang}\"))\n\t\t\t\telif subtitle[0] == 1: # Teletext.\n\t\t\t\t\tinfo.append(formatLine(indent, _(\"TXT Subtitles page & Language\"), f\"0x0{subtitle[3] or 8:X}{subtitle[2]:02X} - {subtitleLang}\"))\n\t\t\t\telif subtitle[0] == 2: # File.\n\t\t\t\t\tsubtitleDesc = subtitleTypes.get(subtitle[2], f\"{_('Unknown')}: {subtitle[2]}\")\n\t\t\t\t\tinfo.append(formatLine(indent, _(\"Other Subtitles & Language\"), f\"{subtitle[1] + 1} - {subtitleDesc} - {subtitleLang}\"))\n\n\t\tinfo = []\n\t\tinfo.append(formatLine(\"H\", _(\"Service and PID information for '%s'\") % self.serviceName))\n\t\tinfo.append(\"\")\n\t\tif self.serviceInfo:\n\t\t\tfrom Components.Converter.PliExtraInfo import codec_data # This should be in SystemInfo maybe as a BoxInfo variable.\n\t\t\tvideoData = []\n\t\t\tvideoData.append(codec_data.get(self.serviceInfo.getInfo(iServiceInformation.sVideoType), _(\"N/A\")))\n\t\t\twidth = self.serviceInfo.getInfo(iServiceInformation.sVideoWidth)\n\t\t\theight = self.serviceInfo.getInfo(iServiceInformation.sVideoHeight)\n\t\t\tif width > 0 and height > 0:\n\t\t\t\tvideoData.append(f\"{width}x{height}\")\n\t\t\t\tvideoData.append(f\"{(self.serviceInfo.getInfo(iServiceInformation.sFrameRate) + 500) // 1000}{('i', 'p', '')[self.serviceInfo.getInfo(iServiceInformation.sProgressive)]}\")\n\t\t\t\tvideoData.append(f\"[{'4:3' if getServiceInfoValue(iServiceInformation.sAspect) in (1, 2, 5, 6, 9, 0xA, 0xD, 0xE) else '16:9'}]\") # This should be in SystemInfo maybe as a BoxInfo variable.\n\t\t\tgamma = (\"SDR\", \"HDR\", \"HDR10\", \"HLG\", \"\")[self.serviceInfo.getInfo(iServiceInformation.sGamma)] # This should be in SystemInfo maybe as a BoxInfo variable.\n\t\t\tif gamma:\n\t\t\t\tvideoData.append(gamma)\n\t\t\tvideoData = \" - \".join(videoData)\n\t\telse:\n\t\t\tvideoData = _(\"Unknown\")\n\t\tif \"%3a//\" in self.serviceReference and self.serviceReferenceType not in (1, 257, 4098, 4114): # IPTV 4097 5001, no PIDs shown.\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Video Codec, Size & Format\"), videoData))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Service reference\"), \":\".join(self.serviceReference.split(\":\")[:9])))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"URL\"), self.serviceReference.split(\":\")[10].replace(\"%3a\", \":\")))\n\t\t\tgetSubtitleList() # IanSav: This wasn't activated to be used!\n\t\telse:\n\t\t\tif \":/\" in self.serviceReference: # mp4 videos, DVB-S-T recording.\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Video Codec, Size & Format\"), videoData))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Service reference\"), \":\".join(self.serviceReference.split(\":\")[:9])))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Filename\"), self.serviceReference.split(\":\")[10]))\n\t\t\telse: # fallback, movistartv, live DVB-S-T.\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Provider\"), getServiceInfoValue(iServiceInformation.sProvider)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Video Codec, Size & Format\"), videoData))\n\t\t\t\tif \"%3a//\" in self.serviceReference: # fallback, movistartv.\n\t\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Service reference\"), \":\".join(self.serviceReference.split(\":\")[:9])))\n\t\t\t\t\tinfo.append(formatLine(\"P1\", _(\"URL\"), self.serviceReference.split(\":\")[10].replace(\"%3a\", \":\")))\n\t\t\t\telse: # Live DVB-S-T\n\t\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Service reference\"), self.serviceReference))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Namespace & Orbital position\"), getNamespace(getServiceInfoValue(iServiceInformation.sNamespace))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Service ID (SID)\"), formatHex(getServiceInfoValue(iServiceInformation.sSID))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Transport Stream ID (TSID)\"), formatHex(getServiceInfoValue(iServiceInformation.sTSID))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Original Network ID (ONID)\"), formatHex(getServiceInfoValue(iServiceInformation.sONID))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Video PID\"), formatHex(getServiceInfoValue(iServiceInformation.sVideoPID))))\n\t\t\taudio = self.service and self.service.audioTracks()\n\t\t\tnumberOfTracks = audio and audio.getNumberOfTracks()\n\t\t\tif numberOfTracks:\n\t\t\t\tfor index in range(numberOfTracks):\n\t\t\t\t\taudioPID = audio.getTrackInfo(index).getPID()\n\t\t\t\t\taudioDesc = audio.getTrackInfo(index).getDescription()\n\t\t\t\t\taudioLang = audio.getTrackInfo(index).getLanguage() or _(\"Undefined\")\n\t\t\t\t\taudioPIDValue = _(\"N/A\") if getServiceInfoValue(iServiceInformation.sAudioPID) == \"N/A\" else formatHex(audioPID)\n\t\t\t\t\tindent = \"P1F0\" if numberOfTracks > 1 and audio.getCurrentTrack() == index else \"P1\"\n\t\t\t\t\tinfo.append(formatLine(indent, _(\"Audio PID%s, Codec & Language\") % (f\" {index + 1}\" if numberOfTracks > 1 else \"\"), f\"{audioPIDValue} - {audioDesc} - {audioLang}\"))\n\t\t\telse:\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Audio PID\"), _(\"N/A\")))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"PCR PID\"), formatHex(getServiceInfoValue(iServiceInformation.sPCRPID))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"PMT PID\"), formatHex(getServiceInfoValue(iServiceInformation.sPMTPID))))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"TXT PID\"), formatHex(getServiceInfoValue(iServiceInformation.sTXTPID))))\n\t\t\tgetSubtitleList()\n\t\treturn info", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def write(self, packet):\n if not self.connected():\n raise RuntimeError(f\"Interface not connected for write {self.name}\")\n if not self.write_allowed:\n raise RuntimeError(f\"Interface not writable {self.name}\")\n\n with self._write():\n self.write_count += 1\n\n # Potentially modify packet\n for protocol in self.write_protocols:\n packet = protocol.write_packet(packet)\n if packet == \"DISCONNECT\":\n Logger.info(\n f\"{self.name}: Protocol {protocol.__class__.__name__} write_packet requested disconnect\"\n )\n self.disconnect()\n return\n if packet == \"STOP\":\n return\n\n data, extra = self.convert_packet_to_data(packet)\n\n # Potentially modify packet data\n for protocol in self.write_protocols:\n data, extra = protocol.write_data(data, extra)\n if data == \"DISCONNECT\":\n Logger.info(f\"{self.name}: Protocol {protocol.__class__.__name__} write_data requested disconnect\")\n self.disconnect()\n return\n if data == \"STOP\":\n return\n\n # Actually write out data if not handled by protocol:\n self.write_interface(data, extra)\n\n # Potentially block and wait for response\n for protocol in self.write_protocols:\n packet, data, extra = protocol.post_write_interface(packet, data, extra)\n if packet == \"DISCONNECT\":\n Logger.info(\n f\"{self.name}: Protocol {protocol.__class__.__name__} post_write_packet requested disconnect\"\n )\n self.disconnect()\n return\n if packet == \"STOP\":\n return\n return None", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "@extend_schema(\n operation_id=\"Retrieve an Organization's Release\",\n parameters=[\n GlobalParams.ORG_ID_OR_SLUG,\n ReleaseParams.VERSION,\n ReleaseParams.PROJECT_ID,\n ReleaseParams.HEALTH,\n ReleaseParams.ADOPTION_STAGES,\n ReleaseParams.SUMMARY_STATS_PERIOD,\n ReleaseParams.HEALTH_STATS_PERIOD,\n ReleaseParams.SORT,\n ReleaseParams.STATUS_FILTER,\n VisibilityParams.QUERY,\n ],\n responses={\n 200: inline_sentry_response_serializer(\"OrgReleaseResponse\", ReleaseSerializerResponse),\n 401: RESPONSE_UNAUTHORIZED,\n 403: RESPONSE_FORBIDDEN,\n 404: RESPONSE_NOT_FOUND,\n },\n examples=OrganizationExamples.RELEASE_DETAILS,\n )\n def get(self, request: Request, organization, version) -> Response:\n \"\"\"\n\n Return details on an individual release.\n \"\"\"\n # Dictionary responsible for storing selected project meta data\n current_project_meta = {}\n project_id = request.GET.get(\"project\")\n with_health = request.GET.get(\"health\") == \"1\"\n with_adoption_stages = request.GET.get(\"adoptionStages\") == \"1\"\n summary_stats_period = request.GET.get(\"summaryStatsPeriod\") or \"14d\"\n health_stats_period = request.GET.get(\"healthStatsPeriod\") or (\"24h\" if with_health else \"\")\n sort = request.GET.get(\"sort\") or \"date\"\n status_filter = request.GET.get(\"status\", \"open\")\n query = request.GET.get(\"query\")\n\n if summary_stats_period not in STATS_PERIODS:\n raise ParseError(detail=get_stats_period_detail(\"summaryStatsPeriod\", STATS_PERIODS))\n if health_stats_period and health_stats_period not in STATS_PERIODS:\n raise ParseError(detail=get_stats_period_detail(\"healthStatsPeriod\", STATS_PERIODS))\n\n try:\n release = Release.objects.get(organization_id=organization.id, version=version)\n except Release.DoesNotExist:\n raise ResourceDoesNotExist\n\n if not self.has_release_permission(request, organization, release):\n raise ResourceDoesNotExist\n\n if with_health and project_id:\n try:\n project = Project.objects.get_from_cache(id=int(project_id))\n except (ValueError, Project.DoesNotExist):\n raise ParseError(detail=\"Invalid project\")\n release._for_project_id = project.id\n\n if project_id:\n # Add sessions time bound to current project meta data\n environments = set(request.GET.getlist(\"environment\")) or None\n current_project_meta.update(\n {\n **release_health.backend.get_release_sessions_time_bounds(\n project_id=int(project_id),\n release=release.version,\n org_id=organization.id,\n environments=environments,\n )\n }\n )\n\n # Get prev and next release to current release\n try:\n filter_params = self.get_filter_params(request, organization)\n current_project_meta.update(\n {\n **self.get_adjacent_releases_to_current_release(\n org=organization,\n release=release,\n filter_params=filter_params,\n stats_period=summary_stats_period,\n sort=sort,\n status_filter=status_filter,\n query=query,\n ),\n **self.get_first_and_last_releases(\n org=organization,\n environment=filter_params.get(\"environment\"),\n project_id=[project_id],\n sort=sort,\n ),\n }\n )\n except InvalidSortException:\n return Response({\"detail\": \"invalid sort\"}, status=400)\n\n return Response(\n serialize(\n release,\n request.user,\n with_health_data=with_health,\n with_adoption_stages=with_adoption_stages,\n summary_stats_period=summary_stats_period,\n health_stats_period=health_stats_period,\n current_project_meta=current_project_meta,\n )\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def validate_no_cross_silo_deletions(\n exemptions: set[tuple[type[Model], type[Model]]], app_name: str | None = None\n) -> None:\n from sentry import deletions\n from sentry.deletions.base import BaseDeletionTask\n\n for model_class in iter_models(app_name):\n if not hasattr(model_class._meta, \"silo_limit\"):\n continue\n deletion_task: BaseDeletionTask = deletions.get(model=model_class, query={})\n for relation in deletion_task.get_child_relations(model_class()):\n to_model = relation.params[\"model\"]\n if (model_class, to_model) in exemptions or (to_model, model_class) in exemptions:\n continue\n for mode in _model_silo_limit(model_class).modes:\n if mode not in _model_silo_limit(to_model).modes:\n raise ValueError(\n f\"Deletions for {model_class!r} cascade to {to_model!r}, but does not belong to the same silo mode. Please remove this relation from get_child_relations in deletions configuration\"\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _alter_field(\n self,\n model,\n old_field,\n new_field,\n old_type,\n new_type,\n old_db_params,\n new_db_params,\n strict=False,\n ):\n \"\"\"Perform a \"physical\" (non-ManyToMany) field update.\"\"\"\n # Drop any FK constraints, we'll remake them later\n fks_dropped = set()\n if (\n self.connection.features.supports_foreign_keys\n and old_field.remote_field\n and old_field.db_constraint\n and self._field_should_be_altered(\n old_field,\n new_field,\n ignore={\"db_comment\"},\n )\n ):\n fk_names = self._constraint_names(\n model, [old_field.column], foreign_key=True\n )\n if strict and len(fk_names) != 1:\n raise ValueError(\n \"Found wrong number (%s) of foreign key constraints for %s.%s\"\n % (\n len(fk_names),\n model._meta.db_table,\n old_field.column,\n )\n )\n for fk_name in fk_names:\n fks_dropped.add((old_field.column,))\n self.execute(self._delete_fk_sql(model, fk_name))\n # Has unique been removed?\n if old_field.unique and (\n not new_field.unique or self._field_became_primary_key(old_field, new_field)\n ):\n # Find the unique constraint for this field\n meta_constraint_names = {\n constraint.name for constraint in model._meta.constraints\n }\n constraint_names = self._constraint_names(\n model,\n [old_field.column],\n unique=True,\n primary_key=False,\n exclude=meta_constraint_names,\n )\n if strict and len(constraint_names) != 1:\n raise ValueError(\n \"Found wrong number (%s) of unique constraints for %s.%s\"\n % (\n len(constraint_names),\n model._meta.db_table,\n old_field.column,\n )\n )\n for constraint_name in constraint_names:\n self.execute(self._delete_unique_sql(model, constraint_name))\n # Drop incoming FK constraints if the field is a primary key or unique,\n # which might be a to_field target, and things are going to change.\n old_collation = old_db_params.get(\"collation\")\n new_collation = new_db_params.get(\"collation\")\n drop_foreign_keys = (\n self.connection.features.supports_foreign_keys\n and (\n (old_field.primary_key and new_field.primary_key)\n or (old_field.unique and new_field.unique)\n )\n and ((old_type != new_type) or (old_collation != new_collation))\n )\n if drop_foreign_keys:\n # '_meta.related_field' also contains M2M reverse fields, these\n # will be filtered out\n for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):\n rel_fk_names = self._constraint_names(\n new_rel.related_model, [new_rel.field.column], foreign_key=True\n )\n for fk_name in rel_fk_names:\n self.execute(self._delete_fk_sql(new_rel.related_model, fk_name))\n # Removed an index? (no strict check, as multiple indexes are possible)\n # Remove indexes if db_index switched to False or a unique constraint\n # will now be used in lieu of an index. The following lines from the\n # truth table show all True cases; the rest are False:\n #\n # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique\n # ------------------------------------------------------------------------------\n # True | False | False | False\n # True | False | False | True\n # True | False | True | True\n if (\n old_field.db_index\n and not old_field.unique\n and (not new_field.db_index or new_field.unique)\n ):\n # Find the index for this field\n meta_index_names = {index.name for index in model._meta.indexes}\n # Retrieve only BTREE indexes since this is what's created with\n # db_index=True.\n index_names = self._constraint_names(\n model,\n [old_field.column],\n index=True,\n type_=Index.suffix,\n exclude=meta_index_names,\n )\n for index_name in index_names:\n # The only way to check if an index was created with\n # db_index=True or with Index(['field'], name='foo')\n # is to look at its name (refs #28053).\n self.execute(self._delete_index_sql(model, index_name))\n # Change check constraints?\n old_db_check = self._field_db_check(old_field, old_db_params)\n new_db_check = self._field_db_check(new_field, new_db_params)\n if old_db_check != new_db_check and old_db_check:\n meta_constraint_names = {\n constraint.name for constraint in model._meta.constraints\n }\n constraint_names = self._constraint_names(\n model,\n [old_field.column],\n check=True,\n exclude=meta_constraint_names,\n )\n if strict and len(constraint_names) != 1:\n raise ValueError(\n \"Found wrong number (%s) of check constraints for %s.%s\"\n % (\n len(constraint_names),\n model._meta.db_table,\n old_field.column,\n )\n )\n for constraint_name in constraint_names:\n self.execute(self._delete_check_sql(model, constraint_name))\n # Have they renamed the column?\n if old_field.column != new_field.column:\n self.execute(\n self._rename_field_sql(\n model._meta.db_table, old_field, new_field, new_type\n )\n )\n # Rename all references to the renamed column.\n for sql in self.deferred_sql:\n if isinstance(sql, Statement):\n sql.rename_column_references(\n model._meta.db_table, old_field.column, new_field.column\n )\n # Next, start accumulating actions to do\n actions = []\n null_actions = []\n post_actions = []\n # Type suffix change? (e.g. auto increment).\n old_type_suffix = old_field.db_type_suffix(connection=self.connection)\n new_type_suffix = new_field.db_type_suffix(connection=self.connection)\n # Type, collation, or comment change?\n if (\n old_type != new_type\n or old_type_suffix != new_type_suffix\n or old_collation != new_collation\n or (\n self.connection.features.supports_comments\n and old_field.db_comment != new_field.db_comment\n )\n ):\n fragment, other_actions = self._alter_column_type_sql(\n model, old_field, new_field, new_type, old_collation, new_collation\n )\n actions.append(fragment)\n post_actions.extend(other_actions)\n\n if new_field.db_default is not NOT_PROVIDED:\n if (\n old_field.db_default is NOT_PROVIDED\n or new_field.db_default != old_field.db_default\n ):\n actions.append(\n self._alter_column_database_default_sql(model, old_field, new_field)\n )\n elif old_field.db_default is not NOT_PROVIDED:\n actions.append(\n self._alter_column_database_default_sql(\n model, old_field, new_field, drop=True\n )\n )\n # When changing a column NULL constraint to NOT NULL with a given\n # default value, we need to perform 4 steps:\n # 1. Add a default for new incoming writes\n # 2. Update existing NULL rows with new default\n # 3. Replace NULL constraint with NOT NULL\n # 4. Drop the default again.\n # Default change?\n needs_database_default = False\n if (\n old_field.null\n and not new_field.null\n and new_field.db_default is NOT_PROVIDED\n ):\n old_default = self.effective_default(old_field)\n new_default = self.effective_default(new_field)\n if (\n not self.skip_default_on_alter(new_field)\n and old_default != new_default\n and new_default is not None\n ):\n needs_database_default = True\n actions.append(\n self._alter_column_default_sql(model, old_field, new_field)\n )\n # Nullability change?\n if old_field.null != new_field.null:\n fragment = self._alter_column_null_sql(model, old_field, new_field)\n if fragment:\n null_actions.append(fragment)\n # Only if we have a default and there is a change from NULL to NOT NULL\n four_way_default_alteration = (\n new_field.has_default() or new_field.db_default is not NOT_PROVIDED\n ) and (old_field.null and not new_field.null)\n if actions or null_actions:\n if not four_way_default_alteration:\n # If we don't have to do a 4-way default alteration we can\n # directly run a (NOT) NULL alteration\n actions += null_actions\n # Combine actions together if we can (e.g. postgres)\n if self.connection.features.supports_combined_alters and actions:\n sql, params = tuple(zip(*actions))\n actions = [(\", \".join(sql), sum(params, []))]\n # Apply those actions\n for sql, params in actions:\n self.execute(\n self.sql_alter_column\n % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": sql,\n },\n params,\n )\n if four_way_default_alteration:\n if new_field.db_default is NOT_PROVIDED:\n default_sql = \"%s\"\n params = [new_default]\n else:\n default_sql, params = self.db_default_sql(new_field)\n # Update existing rows with default value\n self.execute(\n self.sql_update_with_default\n % {\n \"table\": self.quote_name(model._meta.db_table),\n \"column\": self.quote_name(new_field.column),\n \"default\": default_sql,\n },\n params,\n )\n # Since we didn't run a NOT NULL change before we need to do it\n # now\n for sql, params in null_actions:\n self.execute(\n self.sql_alter_column\n % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": sql,\n },\n params,\n )\n if post_actions:\n for sql, params in post_actions:\n self.execute(sql, params)\n # If primary_key changed to False, delete the primary key constraint.\n if old_field.primary_key and not new_field.primary_key:\n self._delete_primary_key(model, strict)\n # Added a unique?\n if self._unique_should_be_added(old_field, new_field):\n self.execute(self._create_unique_sql(model, [new_field]))\n # Added an index? Add an index if db_index switched to True or a unique\n # constraint will no longer be used in lieu of an index. The following\n # lines from the truth table show all True cases; the rest are False:\n #\n # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique\n # ------------------------------------------------------------------------------\n # False | False | True | False\n # False | True | True | False\n # True | True | True | False\n if (\n (not old_field.db_index or old_field.unique)\n and new_field.db_index\n and not new_field.unique\n ):\n self.execute(self._create_index_sql(model, fields=[new_field]))\n # Type alteration on primary key? Then we need to alter the column\n # referring to us.\n rels_to_update = []\n if drop_foreign_keys:\n rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))\n # Changed to become primary key?\n if self._field_became_primary_key(old_field, new_field):\n # Make the new one\n self.execute(self._create_primary_key_sql(model, new_field))\n # Update all referencing columns\n rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))\n # Handle our type alters on the other end of rels from the PK stuff above\n for old_rel, new_rel in rels_to_update:\n rel_db_params = new_rel.field.db_parameters(connection=self.connection)\n rel_type = rel_db_params[\"type\"]\n rel_collation = rel_db_params.get(\"collation\")\n old_rel_db_params = old_rel.field.db_parameters(connection=self.connection)\n old_rel_collation = old_rel_db_params.get(\"collation\")\n fragment, other_actions = self._alter_column_type_sql(\n new_rel.related_model,\n old_rel.field,\n new_rel.field,\n rel_type,\n old_rel_collation,\n rel_collation,\n )\n self.execute(\n self.sql_alter_column\n % {\n \"table\": self.quote_name(new_rel.related_model._meta.db_table),\n \"changes\": fragment[0],\n },\n fragment[1],\n )\n for sql, params in other_actions:\n self.execute(sql, params)\n # Does it have a foreign key?\n if (\n self.connection.features.supports_foreign_keys\n and new_field.remote_field\n and (\n fks_dropped or not old_field.remote_field or not old_field.db_constraint\n )\n and new_field.db_constraint\n ):\n self.execute(\n self._create_fk_sql(model, new_field, \"_fk_%(to_table)s_%(to_column)s\")\n )\n # Rebuild FKs that pointed to us if we previously had to drop them\n if drop_foreign_keys:\n for _, rel in rels_to_update:\n if rel.field.db_constraint:\n self.execute(\n self._create_fk_sql(rel.related_model, rel.field, \"_fk\")\n )\n # Does it have check constraints we need to add?\n if old_db_check != new_db_check and new_db_check:\n constraint_name = self._create_index_name(\n model._meta.db_table, [new_field.column], suffix=\"_check\"\n )\n self.execute(\n self._create_check_sql(model, constraint_name, new_db_params[\"check\"])\n )\n # Drop the default if we need to\n # (Django usually does not use in-database defaults)\n if needs_database_default:\n changes_sql, params = self._alter_column_default_sql(\n model, old_field, new_field, drop=True\n )\n sql = self.sql_alter_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": changes_sql,\n }\n self.execute(sql, params)\n # Reset connection if required\n if self.connection.features.connection_persists_old_columns:\n self.connection.close()", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def handle_bounce(envelope, email_log: EmailLog, msg: Message) -> str:\n \"\"\"\n Return SMTP status, e.g. \"500 Error\"\n \"\"\"\n\n if not email_log:\n LOG.w(\"No such email log\")\n return status.E512\n\n contact: Contact = email_log.contact\n alias = contact.alias\n LOG.d(\n \"handle bounce for %s, phase=%s, contact=%s, alias=%s\",\n email_log,\n email_log.get_phase(),\n contact,\n alias,\n )\n if not email_log.user.is_active():\n LOG.d(f\"User {email_log.user} is not active\")\n return status.E510\n\n if email_log.is_reply:\n content_type = msg.get_content_type().lower()\n\n if content_type != \"multipart/report\" or envelope.mail_from != \"<>\":\n # forward the email again to the alias\n LOG.i(\n \"Handle auto reply %s %s\",\n content_type,\n envelope.mail_from,\n )\n\n contact: Contact = email_log.contact\n alias = contact.alias\n\n email_log.auto_replied = True\n Session.commit()\n\n # replace the BOUNCE_EMAIL by alias in To field\n add_or_replace_header(msg, \"To\", alias.email)\n envelope.rcpt_tos = [alias.email]\n\n # same as handle()\n # result of all deliveries\n # each element is a couple of whether the delivery is successful and the smtp status\n res: [(bool, str)] = []\n\n for is_delivered, smtp_status in handle_forward(envelope, msg, alias.email):\n res.append((is_delivered, smtp_status))\n\n for is_success, smtp_status in res:\n # Consider all deliveries successful if 1 delivery is successful\n if is_success:\n return smtp_status\n\n # Failed delivery for all, return the first failure\n return res[0][1]\n\n handle_bounce_reply_phase(envelope, msg, email_log)\n return status.E212\n else: # forward phase\n handle_bounce_forward_phase(msg, email_log)\n return status.E211", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def _visit_formula(self, formula: Formula) -> tuple[UnitMetadata, QueryExpression]:\n last_metadata: WithUnit | None = None\n future_units = []\n\n has_all_timeseries_params = True\n has_all_futures = True\n\n parameters = []\n for index, parameter in enumerate(formula.parameters):\n if not isinstance(parameter, Timeseries):\n has_all_timeseries_params = False\n\n unit_metadata, query_expression = self.visit(parameter)\n if isinstance(unit_metadata, WithNoUnit):\n return unit_metadata, formula\n elif isinstance(unit_metadata, WithFutureUnit):\n future_units.append((index, query_expression))\n parameters.append(query_expression)\n elif isinstance(unit_metadata, WithUnit):\n has_all_futures = False\n if (\n last_metadata is not None\n and unit_metadata.unit_family != last_metadata.unit_family\n ):\n return WithNoUnit(), formula\n\n last_metadata = unit_metadata\n parameters.append(query_expression)\n\n # If we have only future unit types, we know that the formula will be a future itself.\n # TODO: we might want to execute in-memory the formulas with all scalars to avoid making bigger queries.\n if has_all_futures:\n return WithFutureUnit(), formula\n\n # If we have no metadata here, it means that all parameters of the formula can't be normalized.\n if last_metadata is None:\n return WithNoUnit(), formula\n\n has_coefficient_operators = formula.function_name in COEFFICIENT_OPERATORS\n\n # If we have all timeseries as parameters of a formula and the function belongs to `*` or `/` we will\n # not perform any normalization.\n if has_coefficient_operators and has_all_timeseries_params:\n return WithNoUnit(), formula\n\n # We convert all scalars in the formula using the last seen scaling factor. Since we are always working with\n # two operands, this means that if we found at least one numeric scalar, the scaling factor will belong to the\n # other operand.\n # It's important to note that we are not doing any scalar normalization if we have a coefficient operator, since\n # we don't want to scale both operands.\n # Example:\n # a * 2 with a scaling factor of 1000 must become a * 1000 * 2 and not a * 1000 * 2 * 1000\n if not has_coefficient_operators and future_units and last_metadata.unit is not None:\n for index, future_unit in future_units:\n parameters[index] = self._normalize_future_units(last_metadata.unit, future_unit)\n\n # We want to find the reference unit of the unit family in the formula.\n formula_reference_unit = get_reference_unit_for_unit_family(last_metadata.unit_family)\n if formula_reference_unit is None:\n return WithNoUnit(), formula\n\n # The new formula unit is the reference unit, since we know that all of its operands have been converted to\n # the reference unit at this point.\n return WithUnit(\n unit_family=last_metadata.unit_family,\n reference_unit=formula_reference_unit.name,\n unit=formula_reference_unit,\n from_formula=True,\n ), formula.set_parameters(parameters)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def checkInterface(self, iface):\n\t\tself.stopScan()\n\t\tif self.Adapterlist is None:\n\t\t\tself.Adapterlist = iNetwork.getAdapterList()\n\t\tif self.NextStep != 'end':\n\t\t\tif len(self.Adapterlist) == 0:\n\t\t\t\t#Reset Network to defaults if network broken\n\t\t\t\tiNetwork.resetNetworkConfig('lan', self.resetNetworkConfigCB)\n\t\t\t\tself.resetRef = self.session.openWithCallback(self.resetNetworkConfigFinished, MessageBox, _(\"Please wait while we prepare your network interfaces...\"), type=MessageBox.TYPE_INFO, enable_input=False)\n\t\t\tif iface in iNetwork.getInstalledAdapters():\n\t\t\t\tif iface in iNetwork.configuredNetworkAdapters and len(iNetwork.configuredNetworkAdapters) == 1:\n\t\t\t\t\tif iNetwork.getAdapterAttribute(iface, 'up') is True:\n\t\t\t\t\t\tself.isInterfaceUp = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.isInterfaceUp = False\n\t\t\t\t\tself.currStep = self.getStepWithID(self.NextStep)\n\t\t\t\t\tself.afterAsyncCode()\n\t\t\t\telse:\n\t\t\t\t\tself.isInterfaceUp = iNetwork.checkforInterface(iface)\n\t\t\t\t\tself.currStep = self.getStepWithID(self.NextStep)\n\t\t\t\t\tself.afterAsyncCode()\n\t\telse:\n\t\t\tself.resetNetworkConfigFinished(False)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def normalize(pattern):\n r\"\"\"\n Given a reg-exp pattern, normalize it to an iterable of forms that\n suffice for reverse matching. This does the following:\n\n (1) For any repeating sections, keeps the minimum number of occurrences\n permitted (this means zero for optional groups).\n (2) If an optional group includes parameters, include one occurrence of\n that group (along with the zero occurrence case from step (1)).\n (3) Select the first (essentially an arbitrary) element from any character\n class. Select an arbitrary character for any unordered class (e.g. '.'\n or '\\w') in the pattern.\n (4) Ignore look-ahead and look-behind assertions.\n (5) Raise an error on any disjunctive ('|') constructs.\n\n Django's URLs for forward resolving are either all positional arguments or\n all keyword arguments. That is assumed here, as well. Although reverse\n resolving can be done using positional args when keyword args are\n specified, the two cannot be mixed in the same reverse() call.\n \"\"\"\n # Do a linear scan to work out the special features of this pattern. The\n # idea is that we scan once here and collect all the information we need to\n # make future decisions.\n result = []\n non_capturing_groups = []\n consume_next = True\n pattern_iter = next_char(iter(pattern))\n num_args = 0\n\n # A \"while\" loop is used here because later on we need to be able to peek\n # at the next character and possibly go around without consuming another\n # one at the top of the loop.\n try:\n ch, escaped = next(pattern_iter)\n except StopIteration:\n return [(\"\", [])]\n\n try:\n while True:\n if escaped:\n result.append(ch)\n elif ch == \".\":\n # Replace \"any character\" with an arbitrary representative.\n result.append(\".\")\n elif ch == \"|\":\n # FIXME: One day we'll should do this, but not in 1.0.\n raise NotImplementedError(\"Awaiting Implementation\")\n elif ch == \"^\":\n pass\n elif ch == \"$\":\n break\n elif ch == \")\":\n # This can only be the end of a non-capturing group, since all\n # other unescaped parentheses are handled by the grouping\n # section later (and the full group is handled there).\n #\n # We regroup everything inside the capturing group so that it\n # can be quantified, if necessary.\n start = non_capturing_groups.pop()\n inner = NonCapture(result[start:])\n result = result[:start] + [inner]\n elif ch == \"[\":\n # Replace ranges with the first character in the range.\n ch, escaped = next(pattern_iter)\n result.append(ch)\n ch, escaped = next(pattern_iter)\n while escaped or ch != \"]\":\n ch, escaped = next(pattern_iter)\n elif ch == \"(\":\n # Some kind of group.\n ch, escaped = next(pattern_iter)\n if ch != \"?\" or escaped:\n # A positional group\n name = \"_%d\" % num_args\n num_args += 1\n result.append(Group(((\"%%(%s)s\" % name), name)))\n walk_to_end(ch, pattern_iter)\n else:\n ch, escaped = next(pattern_iter)\n if ch in \"!=<\":\n # All of these are ignorable. Walk to the end of the\n # group.\n walk_to_end(ch, pattern_iter)\n elif ch == \":\":\n # Non-capturing group\n non_capturing_groups.append(len(result))\n elif ch != \"P\":\n # Anything else, other than a named group, is something\n # we cannot reverse.\n raise ValueError(\"Non-reversible reg-exp portion: '(?%s'\" % ch)\n else:\n ch, escaped = next(pattern_iter)\n if ch not in (\"<\", \"=\"):\n raise ValueError(\n \"Non-reversible reg-exp portion: '(?P%s'\" % ch\n )\n # We are in a named capturing group. Extra the name and\n # then skip to the end.\n if ch == \"<\":\n terminal_char = \">\"\n # We are in a named backreference.\n else:\n terminal_char = \")\"\n name = []\n ch, escaped = next(pattern_iter)\n while ch != terminal_char:\n name.append(ch)\n ch, escaped = next(pattern_iter)\n param = \"\".join(name)\n # Named backreferences have already consumed the\n # parenthesis.\n if terminal_char != \")\":\n result.append(Group(((\"%%(%s)s\" % param), param)))\n walk_to_end(ch, pattern_iter)\n else:\n result.append(Group(((\"%%(%s)s\" % param), None)))\n elif ch in \"*?+{\":\n # Quantifiers affect the previous item in the result list.\n count, ch = get_quantifier(ch, pattern_iter)\n if ch:\n # We had to look ahead, but it wasn't need to compute the\n # quantifier, so use this character next time around the\n # main loop.\n consume_next = False\n\n if count == 0:\n if contains(result[-1], Group):\n # If we are quantifying a capturing group (or\n # something containing such a group) and the minimum is\n # zero, we must also handle the case of one occurrence\n # being present. All the quantifiers (except {0,0},\n # which we conveniently ignore) that have a 0 minimum\n # also allow a single occurrence.\n result[-1] = Choice([None, result[-1]])\n else:\n result.pop()\n elif count > 1:\n result.extend([result[-1]] * (count - 1))\n else:\n # Anything else is a literal.\n result.append(ch)\n\n if consume_next:\n ch, escaped = next(pattern_iter)\n consume_next = True\n except StopIteration:\n pass\n except NotImplementedError:\n # A case of using the disjunctive form. No results for you!\n return [(\"\", [])]\n\n return list(zip(*flatten_result(result)))", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def main(arguments=None):\n if arguments is None:\n arguments = sys.argv[1:]\n\n args, since, to = parse_arguments(arguments)\n\n arv = arvados.api()\n\n prefix = ''\n suffix = \"\\n\"\n if args.csv:\n prefix = '# '\n suffix = ''\n print(\"%sUser activity on %s between %s and %s%s\" % (prefix, arv.config()[\"ClusterID\"],\n since.isoformat(sep=\" \", timespec=\"minutes\"),\n to.isoformat(sep=\" \", timespec=\"minutes\"), suffix))\n\n events = arvados.util.keyset_list_all(arv.logs().list, filters=[[\"created_at\", \">=\", since.isoformat()],[\"created_at\", \"<\", to.isoformat()]])\n\n users = {}\n owners = {}\n\n for e in events:\n owner = getowner(arv, e[\"object_owner_uuid\"], owners)\n users.setdefault(owner, [])\n event_at = ciso8601.parse_datetime(e[\"event_at\"]).astimezone().isoformat(sep=\" \", timespec=\"minutes\")\n loguuid = e[\"uuid\"]\n\n if e[\"event_type\"] == \"create\" and e[\"object_uuid\"][6:11] == \"tpzed\":\n users.setdefault(e[\"object_uuid\"], [])\n users[e[\"object_uuid\"]].append([loguuid, event_at, \"User account created\"])\n\n elif e[\"event_type\"] == \"update\" and e[\"object_uuid\"][6:11] == \"tpzed\":\n pass\n\n elif e[\"event_type\"] == \"create\" and e[\"object_uuid\"][6:11] == \"xvhdp\":\n if e[\"properties\"][\"new_attributes\"][\"requesting_container_uuid\"] is None:\n users[owner].append([loguuid, event_at, \"Ran container %s\" % (getname(e[\"properties\"][\"new_attributes\"]))])\n\n elif e[\"event_type\"] == \"update\" and e[\"object_uuid\"][6:11] == \"xvhdp\":\n pass\n\n elif e[\"event_type\"] == \"create\" and e[\"object_uuid\"][6:11] == \"j7d0g\":\n users[owner].append([loguuid, event_at,\"Created project %s\" % (getname(e[\"properties\"][\"new_attributes\"]))])\n\n elif e[\"event_type\"] == \"delete\" and e[\"object_uuid\"][6:11] == \"j7d0g\":\n users[owner].append([loguuid, event_at,\"Deleted project %s\" % (getname(e[\"properties\"][\"old_attributes\"]))])\n\n elif e[\"event_type\"] == \"update\" and e[\"object_uuid\"][6:11] == \"j7d0g\":\n users[owner].append([loguuid, event_at,\"Updated project %s\" % (getname(e[\"properties\"][\"new_attributes\"]))])\n\n elif e[\"event_type\"] in (\"create\", \"update\") and e[\"object_uuid\"][6:11] == \"gj3su\":\n # Don't log token activity, it is too noisy (bug #19179)\n pass\n\n # We want to report when a user goes through the login\n # process, but controller doesn't do that yet, so revisit\n # this when #19388 is done.\n\n elif e[\"event_type\"] == \"create\" and e[\"object_uuid\"][6:11] == \"o0j2j\":\n if e[\"properties\"][\"new_attributes\"][\"link_class\"] == \"tag\":\n users[owner].append([event_at,\"Tagged %s\" % (e[\"properties\"][\"new_attributes\"][\"head_uuid\"])])\n elif e[\"properties\"][\"new_attributes\"][\"link_class\"] == \"permission\":\n users[owner].append([loguuid, event_at,\"Shared %s with %s\" % (e[\"properties\"][\"new_attributes\"][\"tail_uuid\"], e[\"properties\"][\"new_attributes\"][\"head_uuid\"])])\n else:\n users[owner].append([loguuid, event_at,\"%s %s %s\" % (e[\"event_type\"], e[\"object_kind\"], e[\"object_uuid\"])])\n\n elif e[\"event_type\"] == \"delete\" and e[\"object_uuid\"][6:11] == \"o0j2j\":\n if e[\"properties\"][\"old_attributes\"][\"link_class\"] == \"tag\":\n users[owner].append([loguuid, event_at,\"Untagged %s\" % (e[\"properties\"][\"old_attributes\"][\"head_uuid\"])])\n elif e[\"properties\"][\"old_attributes\"][\"link_class\"] == \"permission\":\n users[owner].append([loguuid, event_at,\"Unshared %s with %s\" % (e[\"properties\"][\"old_attributes\"][\"tail_uuid\"], e[\"properties\"][\"old_attributes\"][\"head_uuid\"])])\n else:\n users[owner].append([loguuid, event_at,\"%s %s %s\" % (e[\"event_type\"], e[\"object_kind\"], e[\"object_uuid\"])])\n\n elif e[\"event_type\"] == \"create\" and e[\"object_uuid\"][6:11] == \"4zz18\":\n if e[\"properties\"][\"new_attributes\"][\"properties\"].get(\"type\") in (\"log\", \"output\", \"intermediate\"):\n pass\n else:\n users[owner].append([loguuid, event_at,\"Created collection %s\" % (getname(e[\"properties\"][\"new_attributes\"]))])\n\n elif e[\"event_type\"] == \"update\" and e[\"object_uuid\"][6:11] == \"4zz18\":\n users[owner].append([loguuid, event_at,\"Updated collection %s\" % (getname(e[\"properties\"][\"new_attributes\"]))])\n\n elif e[\"event_type\"] == \"delete\" and e[\"object_uuid\"][6:11] == \"4zz18\":\n if e[\"properties\"][\"old_attributes\"][\"properties\"].get(\"type\") in (\"log\", \"output\", \"intermediate\"):\n pass\n else:\n users[owner].append([loguuid, event_at, \"Deleted collection %s\" % (getname(e[\"properties\"][\"old_attributes\"]))])\n\n elif e[\"event_type\"] == \"file_download\":\n users.setdefault(e[\"object_uuid\"], [])\n users[e[\"object_uuid\"]].append([loguuid, event_at, \"Downloaded file \\\"%s\\\" from \\\"%s\\\" (%s) (%s)\" % (\n e[\"properties\"].get(\"collection_file_path\") or e[\"properties\"].get(\"reqPath\"),\n getCollectionName(arv, e[\"properties\"].get(\"collection_uuid\"), e[\"properties\"].get(\"portable_data_hash\")),\n e[\"properties\"].get(\"collection_uuid\"),\n e[\"properties\"].get(\"portable_data_hash\"))])\n\n elif e[\"event_type\"] == \"file_upload\":\n users.setdefault(e[\"object_uuid\"], [])\n users[e[\"object_uuid\"]].append([loguuid, event_at, \"Uploaded file \\\"%s\\\" to \\\"%s\\\" (%s)\" % (\n e[\"properties\"].get(\"collection_file_path\") or e[\"properties\"].get(\"reqPath\"),\n getCollectionName(arv, e[\"properties\"].get(\"collection_uuid\"), e[\"properties\"].get(\"portable_data_hash\")),\n e[\"properties\"].get(\"collection_uuid\"))])\n\n else:\n users[owner].append([loguuid, event_at, \"%s %s %s\" % (e[\"event_type\"], e[\"object_kind\"], e[\"object_uuid\"])])\n\n if args.csv:\n csvwriter = csv.writer(sys.stdout, dialect='unix')\n\n for k,v in users.items():\n # Skip system user\n if k is None or k.endswith(\"-tpzed-000000000000000\"):\n continue\n\n # Skip users with no activity to report\n if not v:\n continue\n\n if not args.csv:\n print(getuserinfo(arv, k))\n for ev in v:\n # Remove the log entry uuid, this report is intended for human consumption\n ev.pop(0)\n print(\" %s\" % ' '.join(ev))\n print(\"\")\n else:\n user = getuserinfocsv(arv, k)\n for ev in v:\n ev = user + ev\n csvwriter.writerow(ev)", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def getNextPowerManagerTime(self, getNextStbPowerOn=False, getNextTimerTyp=False):\n\t\tglobal DSsave, RSsave, RBsave, aeDSsave\n\t\tnextRecTime = self.getNextPowerManagerTimeOld(getNextStbPowerOn)\n\t\tfakeTime = int(time()) + 300\n\t\tif getNextStbPowerOn:\n\t\t\tif config.timeshift.isRecording.value:\n\t\t\t\tif 0 < nextRecTime[0][0] < fakeTime:\n\t\t\t\t\treturn nextRecTime[0][0], int(nextRecTime[0][1] == 2 or nextRecTime[0][2] == 2)\n\t\t\t\telse:\n\t\t\t\t\treturn fakeTime, 0\n\t\t\telse:\n\t\t\t\treturn nextRecTime[0][0], int(nextRecTime[0][1] == 2 or nextRecTime[0][2] == 2)\n\t\telif getNextTimerTyp: # Check entries and plausibility of shift state (manual canceled timer has shift/save state not reset).\n\t\t\ttt = []\n\t\t\tae = []\n\t\t\tnow = int(time())\n\t\t\tif DEBUG:\n\t\t\t\tprint(\"[PowerTimer] +++++++++++++++\")\n\t\t\tfor entry in nextRecTime:\n\t\t\t\tif entry[0] < now + 900:\n\t\t\t\t\ttt.append(entry[1])\n\t\t\t\tif entry[0] < now + 900:\n\t\t\t\t\tae.append(entry[2])\n\t\t\t\tif DEBUG:\n\t\t\t\t\tprint(f\"[PowerTimer] {ctime(entry[0])} {str(entry)}.\")\n\t\t\tif TIMERTYPE.RESTART not in tt:\n\t\t\t\tRSsave = False\n\t\t\tif TIMERTYPE.REBOOT not in tt:\n\t\t\t\tRBsave = False\n\t\t\tif TIMERTYPE.DEEPSTANDBY not in tt:\n\t\t\t\tDSsave = False\n\t\t\tif AFTEREVENT.DEEPSTANDBY not in ae:\n\t\t\t\taeDSsave = False\n\t\t\tif DEBUG:\n\t\t\t\tprint(f\"[PowerTimer] RSsave={RSsave}, RBsave={RBsave}, DSsave={DSsave}, aeDSsave={aeDSsave}, wasTimerWakeup={wasTimerWakeup}\")\n\t\t\tif DEBUG:\n\t\t\t\tprint(\"[PowerTimer] +++++++++++++++\")\n\t\t\tif config.timeshift.isRecording.value:\n\t\t\t\tif 0 < nextRecTime[0][0] < fakeTime:\n\t\t\t\t\treturn nextRecTime\n\t\t\t\telse:\n\t\t\t\t\tnextRecTime.append((fakeTime, None, None, None))\n\t\t\t\t\tnextRecTime.sort()\n\t\t\t\t\treturn nextRecTime\n\t\t\telse:\n\t\t\t\treturn nextRecTime\n\t\telse:\n\t\t\tif config.timeshift.isRecording.value:\n\t\t\t\tif 0 < nextRecTime[0][0] < fakeTime:\n\t\t\t\t\treturn nextRecTime[0][0]\n\t\t\t\telse:\n\t\t\t\t\treturn fakeTime\n\t\t\telse:\n\t\t\t\treturn nextRecTime[0][0]", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@lru_cache(maxsize=1024)\n def downgrade(self, system: ColorSystem) -> \"Color\":\n \"\"\"Downgrade a color system to a system with fewer colors.\"\"\"\n\n if self.type in (ColorType.DEFAULT, system):\n return self\n # Convert to 8-bit color from truecolor color\n if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:\n assert self.triplet is not None\n _h, l, s = rgb_to_hls(*self.triplet.normalized)\n # If saturation is under 15% assume it is grayscale\n if s < 0.15:\n gray = round(l * 25.0)\n if gray == 0:\n color_number = 16\n elif gray == 25:\n color_number = 231\n else:\n color_number = 231 + gray\n return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n red, green, blue = self.triplet\n six_red = red / 95 if red < 95 else 1 + (red - 95) / 40\n six_green = green / 95 if green < 95 else 1 + (green - 95) / 40\n six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40\n\n color_number = (\n 16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue)\n )\n return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n # Convert to standard from truecolor or 8-bit\n elif system == ColorSystem.STANDARD:\n if self.system == ColorSystem.TRUECOLOR:\n assert self.triplet is not None\n triplet = self.triplet\n else: # self.system == ColorSystem.EIGHT_BIT\n assert self.number is not None\n triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n color_number = STANDARD_PALETTE.match(triplet)\n return Color(self.name, ColorType.STANDARD, number=color_number)\n\n elif system == ColorSystem.WINDOWS:\n if self.system == ColorSystem.TRUECOLOR:\n assert self.triplet is not None\n triplet = self.triplet\n else: # self.system == ColorSystem.EIGHT_BIT\n assert self.number is not None\n if self.number < 16:\n return Color(self.name, ColorType.WINDOWS, number=self.number)\n triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n color_number = WINDOWS_PALETTE.match(triplet)\n return Color(self.name, ColorType.WINDOWS, number=color_number)\n\n return self", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def _set_value(\n self,\n item: ocio.Look,\n column_desc: ColumnDesc,\n value: Any,\n index: QtCore.QModelIndex,\n ) -> None:\n config = ocio.GetCurrentConfig()\n new_item = copy.deepcopy(item)\n prev_item_name = item.getName()\n\n # Update parameters\n if column_desc == self.NAME:\n new_item.setName(value)\n elif column_desc == self.PROCESS_SPACE:\n new_item.setProcessSpace(value)\n elif column_desc == self.DESCRIPTION:\n new_item.setDescription(value)\n\n # Update transforms\n if column_desc == self.TRANSFORM:\n new_item.setTransform(value)\n elif column_desc == self.INVERSE_TRANSFORM:\n new_item.setInverseTransform(value)\n\n # Preserve item order when replacing item due to name change, which requires\n # removing the old item to add the new.\n if column_desc == self.NAME:\n items = [\n copy.deepcopy(other_item) for other_item in config.getLooks()\n ]\n config.clearLooks()\n for other_look in items:\n if other_look.getName() == prev_item_name:\n config.addLook(new_item)\n self.item_renamed.emit(new_item.getName(), prev_item_name)\n else:\n config.addLook(other_look)\n\n # Item order is preserved for all other changes\n else:\n config.addLook(new_item)\n\n # Broadcast transform or name changes to subscribers\n if column_desc in (self.NAME, self.TRANSFORM, self.INVERSE_TRANSFORM):\n item_name = new_item.getName()\n self._update_tf_subscribers(\n item_name,\n prev_item_name if prev_item_name != item_name else None,\n )", "smellKey": "S3776", "smellId": null, "repo": "AcademySoftwareFoundation_OpenColorIO", "language": "python"} {"function": "@pytest.mark.parametrize('test_case', TEST_CASES)\n@patch('runners.canopen_program.CANopenProgramDownloader')\ndef test_canopen_program_create(cpd, test_case, runner_config):\n '''Test CANopen runner created from command line parameters.'''\n node_id, context, program_number, confirm, confirm_only, timeout = test_case\n\n args = ['--node-id', str(node_id)]\n if context is not None:\n args.extend(['--can-context', context])\n if program_number:\n args.extend(['--program-number', str(program_number)])\n if not confirm:\n args.append('--no-confirm')\n if confirm_only:\n args.append('--confirm-only')\n if timeout:\n args.extend(['--timeout', str(timeout)])\n\n mock = cpd.return_value\n mock.flash_status.return_value = 0\n mock.swid.return_value = 0\n\n parser = argparse.ArgumentParser()\n CANopenBinaryRunner.add_parser(parser)\n arg_namespace = parser.parse_args(args)\n runner = CANopenBinaryRunner.create(runner_config, arg_namespace)\n with patch('os.path.isfile', side_effect=os_path_isfile_patch):\n runner.run('flash')\n\n cpd.assert_called_once()\n if context:\n assert cpd.call_args == call(node_id=node_id,\n can_context=context,\n logger=runner.logger,\n program_number=program_number)\n else:\n assert cpd.call_args == call(node_id=node_id,\n can_context=TEST_DEF_CONTEXT,\n logger=runner.logger,\n program_number=program_number)\n\n mock.connect.assert_called_once()\n\n if confirm_only:\n mock.flash_status.assert_called_once()\n mock.swid.assert_called_once()\n mock.enter_pre_operational.assert_called_once()\n mock.zephyr_confirm_program.assert_called_once()\n mock.clear_program.assert_not_called()\n mock.stop_program.assert_not_called()\n mock.download.assert_not_called()\n mock.start_program.assert_not_called()\n mock.wait_for_bootup.assert_not_called()\n else:\n mock.enter_pre_operational.assert_called()\n mock.flash_status.assert_called()\n mock.swid.assert_called()\n mock.stop_program.assert_called_once()\n mock.clear_program.assert_called_once()\n mock.download.assert_called_once_with(RC_KERNEL_BIN)\n mock.start_program.assert_called_once()\n mock.wait_for_bootup.assert_called_once_with(timeout)\n if confirm:\n mock.zephyr_confirm_program.assert_called_once()\n else:\n mock.zephyr_confirm_program.assert_not_called()\n\n mock.disconnect.assert_called_once()", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def urlopen(self, method, url, redirect=True, **kw):\n \"\"\"\n Same as :meth:`urllib3.HTTPConnectionPool.urlopen`\n with custom cross-host redirect logic and only sends the request-uri\n portion of the ``url``.\n\n The given ``url`` parameter must be absolute, such that an appropriate\n :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.\n \"\"\"\n u = parse_url(url)\n self._validate_proxy_scheme_url_selection(u.scheme)\n\n conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)\n\n kw[\"assert_same_host\"] = False\n kw[\"redirect\"] = False\n\n if \"headers\" not in kw:\n kw[\"headers\"] = self.headers.copy()\n\n if self._proxy_requires_url_absolute_form(u):\n response = conn.urlopen(method, url, **kw)\n else:\n response = conn.urlopen(method, u.request_uri, **kw)\n\n redirect_location = redirect and response.get_redirect_location()\n if not redirect_location:\n return response\n\n # Support relative URLs for redirecting.\n redirect_location = urljoin(url, redirect_location)\n\n # RFC 7231, Section 6.4.4\n if response.status == 303:\n method = \"GET\"\n\n retries = kw.get(\"retries\")\n if not isinstance(retries, Retry):\n retries = Retry.from_int(retries, redirect=redirect)\n\n # Strip headers marked as unsafe to forward to the redirected location.\n # Check remove_headers_on_redirect to avoid a potential network call within\n # conn.is_same_host() which may use socket.gethostbyname() in the future.\n if retries.remove_headers_on_redirect and not conn.is_same_host(\n redirect_location\n ):\n headers = list(six.iterkeys(kw[\"headers\"]))\n for header in headers:\n if header.lower() in retries.remove_headers_on_redirect:\n kw[\"headers\"].pop(header, None)\n\n try:\n retries = retries.increment(method, url, response=response, _pool=conn)\n except MaxRetryError:\n if retries.raise_on_redirect:\n response.drain_conn()\n raise\n return response\n\n kw[\"retries\"] = retries\n kw[\"redirect\"] = redirect\n\n log.info(\"Redirecting %s -> %s\", url, redirect_location)\n\n response.drain_conn()\n return self.urlopen(method, redirect_location, **kw)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "async def handle(self, context: RequestContext, responder: BaseResponder):\n \"\"\"Message handler logic for credential requests.\n\n Args:\n context: request context\n responder: responder callback\n\n \"\"\"\n r_time = get_timer()\n profile = context.profile\n self._logger.debug(\"CredentialRequestHandler called with context %s\", context)\n assert isinstance(context.message, CredentialRequest)\n self._logger.info(\n \"Received credential request message: %s\",\n context.message.serialize(as_string=True),\n )\n\n # If connection is present it must be ready for use\n if context.connection_record and not context.connection_ready:\n raise HandlerException(\"Connection used for credential request not ready\")\n\n # Find associated oob record. If the credential offer was created as an oob\n # attachment the presentation exchange record won't have a connection id (yet)\n oob_processor = context.inject(OobMessageProcessor)\n oob_record = await oob_processor.find_oob_record_for_inbound_message(context)\n\n # Either connection or oob context must be present\n if not context.connection_record and not oob_record:\n raise HandlerException(\n \"No connection or associated connectionless exchange found for credential\"\n \" request\"\n )\n\n credential_manager = CredentialManager(profile)\n try:\n cred_ex_record = await credential_manager.receive_request(\n context.message, context.connection_record, oob_record\n ) # mgr only finds, saves record: on exception, saving state null is hopeless\n except StorageNotFoundError:\n # issue a problem report...\n cred_ex_record = None\n thread_id = context.message._thread_id\n await responder.send_reply(\n problem_report_for_record(\n None,\n ProblemReportReason.RECORD_NOT_FOUND.value,\n thread_id=thread_id,\n )\n )\n r_time = trace_event(\n context.settings,\n context.message,\n outcome=\"CredentialRequestHandler.handle.END\",\n perf_counter=r_time,\n )\n\n # If auto_issue is enabled, respond immediately\n if cred_ex_record and cred_ex_record.auto_issue:\n if (\n cred_ex_record.credential_proposal_dict\n and cred_ex_record.credential_proposal_dict.credential_proposal\n ):\n credential_issue_message = None\n try:\n (\n cred_ex_record,\n credential_issue_message,\n ) = await credential_manager.issue_credential(\n cred_ex_record=cred_ex_record,\n comment=context.message.comment,\n )\n await responder.send_reply(credential_issue_message)\n except (\n BaseModelError,\n CredentialManagerError,\n IndyIssuerError,\n LedgerError,\n StorageError,\n ) as err:\n self._logger.exception(\"Error responding to credential request\")\n if cred_ex_record:\n async with profile.session() as session:\n await cred_ex_record.save_error_state(\n session,\n reason=err.roll_up, # us: be specific\n )\n await responder.send_reply( # them: be vague\n problem_report_for_record(\n cred_ex_record,\n ProblemReportReason.ISSUANCE_ABANDONED.value,\n )\n )\n\n trace_event(\n context.settings,\n credential_issue_message,\n outcome=\"CredentialRequestHandler.issue.END\",\n perf_counter=r_time,\n )\n else:\n self._logger.warning(\n \"Operation set for auto-issue but credential exchange record \"\n f\"{cred_ex_record.credential_exchange_id} \"\n \"has no attribute values\"\n )", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def confPath(self):\n\t\towebif, oport, opath, ipcompiled, conffile = False, None, None, False, \"\"\n\t\tfor file in [\"/tmp/.ncam/ncam.version\", \"/tmp/.oscam/oscam.version\"]: # Find and parse running oscam\n\t\t\tif exists(file):\n\t\t\t\twith open(file) as data:\n\t\t\t\t\tconffile = file.split('/')[-1].replace(\"version\", \"conf\")\n\t\t\t\t\tfor i in data:\n\t\t\t\t\t\tif \"web interface support:\" in i.lower():\n\t\t\t\t\t\t\towebif = {\"no\": False, \"yes\": True}.get(i.split(\":\")[1].strip(), False)\n\t\t\t\t\t\telif \"webifport:\" in i.lower():\n\t\t\t\t\t\t\toport = i.split(\":\")[1].strip()\n\t\t\t\t\t\t\tif oport == \"0\":\n\t\t\t\t\t\t\t\toport = None\n\t\t\t\t\t\telif \"configdir:\" in i.lower():\n\t\t\t\t\t\t\topath = i.split(\":\")[1].strip()\n\t\t\t\t\t\telif \"ipv6 support:\" in i.lower():\n\t\t\t\t\t\t\tipcompiled = {\"no\": False, \"yes\": True}.get(i.split(\":\")[1].strip())\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\t\treturn owebif, oport, opath, ipcompiled, conffile", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_protected_operations() -> list[re.Pattern]:\n from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey\n from sentry.hybridcloud.outbox.base import ReplicatedControlModel, ReplicatedRegionModel\n\n if len(_protected_operations):\n return _protected_operations\n\n # Protect Foreign Keys using hybrid cloud models from being deleted without using the\n # privileged user. Deletion should only occur when the developer is actively aware\n # of the need to generate outboxes.\n seen_models: MutableSet[type] = set()\n for app_config in apps.get_app_configs():\n for model in iter_models(app_config.name):\n for field in model._meta.fields:\n if not isinstance(field, HybridCloudForeignKey):\n continue\n fk_model = field.foreign_model\n if fk_model is None or fk_model in seen_models:\n continue\n seen_models.add(fk_model)\n _protected_operations.append(protected_table(fk_model._meta.db_table, \"delete\"))\n if issubclass(model, ReplicatedControlModel) or issubclass(\n model, ReplicatedRegionModel\n ):\n _protected_operations.append(protected_table(model._meta.db_table, \"insert\"))\n _protected_operations.append(protected_table(model._meta.db_table, \"update\"))\n _protected_operations.append(protected_table(model._meta.db_table, \"delete\"))\n\n # Protect inserts/updates that require outbox messages.\n _protected_operations.extend(\n [\n protected_table(\"sentry_user\", \"insert\"),\n protected_table(\"sentry_user\", \"update\"),\n protected_table(\"sentry_user\", \"delete\"),\n protected_table(\"sentry_organizationmember\", \"insert\"),\n protected_table(\"sentry_organizationmember\", \"update\"),\n protected_table(\"sentry_organizationmember\", \"delete\"),\n protected_table(\"sentry_organizationmembermapping\", \"insert\"),\n ]\n )\n\n return _protected_operations", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def read(cls, bit_offset, bit_size, data_type, buffer, endianness):\n given_bit_offset = bit_offset\n given_bit_size = bit_size\n\n bit_offset = cls.check_bit_offset_and_size(\"read\", given_bit_offset, given_bit_size, data_type, buffer)\n\n # If passed a negative bit size with strings or blocks\n # recalculate based on the buffer length\n if (bit_size <= 0) and ((data_type == \"STRING\") or (data_type == \"BLOCK\")):\n bit_size = (len(buffer) * 8) - bit_offset + bit_size\n if bit_size == 0:\n return \"\"\n elif bit_size < 0:\n cls.raise_buffer_error(\"read\", buffer, data_type, given_bit_offset, given_bit_size)\n\n result, lower_bound, upper_bound = cls.check_bounds_and_buffer_size(\n bit_offset, bit_size, len(buffer), endianness, data_type\n )\n if not result:\n cls.raise_buffer_error(\"read\", buffer, data_type, given_bit_offset, given_bit_size)\n\n if data_type in [\"STRING\", \"BLOCK\"]:\n #######################################\n # Handle 'STRING' and 'BLOCK' data types\n #######################################\n\n if cls.byte_aligned(bit_offset):\n if data_type == \"STRING\":\n try:\n buffer = buffer[lower_bound : (upper_bound + 1)]\n try:\n return buffer[: buffer.index(BinaryAccessor.ZERO_STRING)].decode(encoding=\"utf-8\")\n except ValueError:\n return buffer.decode(encoding=\"utf-8\")\n # If this 'STRING' contains binary buffer.decode will fail\n # Instead of blowing up return the original buffer\n except UnicodeDecodeError:\n return buffer\n else: # BLOCK\n return buffer[lower_bound : upper_bound + 1]\n\n else:\n raise AttributeError(f\"bit_offset {given_bit_offset} is not byte aligned for data_type {data_type}\")\n\n elif data_type in [\"INT\", \"UINT\"]:\n ###################################\n # Handle 'INT' and 'UINT' data types\n ###################################\n\n if cls.byte_aligned(bit_offset) and cls.even_bit_size(bit_size):\n # if data_type == \"INT\":\n ###########################################################\n # Handle byte-aligned 8, 16, 32, and 64 bit 'INT'\n ###########################################################\n const = getattr(BinaryAccessor, f\"STRUCT_{data_type}_{bit_size}\")\n endian = getattr(BinaryAccessor, f\"STRUCT_{endianness}\")\n format = \"%s%s\" % (endian, const)\n return struct.unpack(\n format,\n buffer[lower_bound : upper_bound + 1],\n )[0]\n\n else:\n ##########################\n # Handle 'INT' and 'UINT' Bitfields\n ##########################\n\n # Extract Data for Bitfield\n if endianness == \"LITTLE_ENDIAN\":\n # Bitoffset always refers to the most significant bit of a bitfield\n num_bytes = math.floor((((bit_offset % 8) + bit_size - 1) / 8) + 1)\n upper_bound = math.floor(bit_offset / 8)\n lower_bound = upper_bound - num_bytes + 1\n\n if lower_bound < 0:\n raise AttributeError(\n f\"LITTLE_ENDIAN bitfield with bit_offset {given_bit_offset} and bit_size {given_bit_size} is invalid\"\n )\n temp_lower = lower_bound - 1 if lower_bound > 0 else lower_bound\n temp_data = buffer[upper_bound : temp_lower or None : -1]\n else:\n temp_data = buffer[lower_bound : upper_bound + 1]\n\n # Determine temp upper bound\n temp_upper = upper_bound - lower_bound\n\n # Handle Bitfield\n start_bits = bit_offset % 8\n start_mask = ~(0xFF << (8 - start_bits))\n total_bits = (temp_upper + 1) * 8\n right_shift = total_bits - start_bits - bit_size\n\n # Mask off unwanted bits at beginning\n temp = temp_data[0] & start_mask\n\n if upper_bound > lower_bound:\n # Combine bytes into a FixNum\n for temp_value in temp_data[1 : (temp_upper + 1)]:\n temp = temp << 8\n temp = temp + temp_value\n\n # Shift off unwanted bits at end\n temp = temp >> right_shift\n if data_type == \"INT\":\n # Convert to negative if necessary\n if (bit_size > 1) and (temp & (1 << (bit_size - 1))):\n temp = -((1 << bit_size) - temp)\n return temp\n\n elif data_type == \"FLOAT\":\n ##########################\n # Handle 'FLOAT' data type\n ##########################\n\n if cls.byte_aligned(bit_offset):\n if bit_size in [32, 64]:\n const = getattr(BinaryAccessor, f\"STRUCT_{data_type}_{bit_size}\")\n endian = getattr(BinaryAccessor, f\"STRUCT_{endianness}\")\n format = \"%s%s\" % (endian, const)\n return struct.unpack(\n format,\n buffer[lower_bound : upper_bound + 1],\n )[0]\n else:\n raise AttributeError(f\"bit_size is {given_bit_size} but must be 32 or 64 for data_type {data_type}\")\n else:\n raise AttributeError(f\"bit_offset {given_bit_offset} is not byte aligned for data_type {data_type}\")\n\n else:\n ############################\n # Handle Unknown data types\n ############################\n raise AttributeError(f\"data_type {data_type} is not recognized\")", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def install_given_reqs(\n requirements: List[InstallRequirement],\n global_options: Sequence[str],\n root: Optional[str],\n home: Optional[str],\n prefix: Optional[str],\n warn_script_location: bool,\n use_user_site: bool,\n pycompile: bool,\n) -> List[InstallationResult]:\n \"\"\"\n Install everything in the given list.\n\n (to be called after having downloaded and unpacked the packages)\n \"\"\"\n to_install = collections.OrderedDict(_validate_requirements(requirements))\n\n if to_install:\n logger.info(\n \"Installing collected packages: %s\",\n \", \".join(to_install.keys()),\n )\n\n installed = []\n\n with indent_log():\n for req_name, requirement in to_install.items():\n if requirement.should_reinstall:\n logger.info(\"Attempting uninstall: %s\", req_name)\n with indent_log():\n uninstalled_pathset = requirement.uninstall(auto_confirm=True)\n else:\n uninstalled_pathset = None\n\n try:\n requirement.install(\n global_options,\n root=root,\n home=home,\n prefix=prefix,\n warn_script_location=warn_script_location,\n use_user_site=use_user_site,\n pycompile=pycompile,\n )\n except Exception:\n # if install did not succeed, rollback previous uninstall\n if uninstalled_pathset and not requirement.install_succeeded:\n uninstalled_pathset.rollback()\n raise\n else:\n if uninstalled_pathset and requirement.install_succeeded:\n uninstalled_pathset.commit()\n\n installed.append(InstallationResult(req_name))\n\n return installed", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def parseCoordinate(value, parent, size=0, font=None, scale=(1, 1)):\n\tdef scaleNumbers(coordinate, scale):\n\t\tinNumber = False\n\t\tchars = []\n\t\tdigits = []\n\t\tfor char in list(f\"{coordinate} \"):\n\t\t\tif char.isdigit():\n\t\t\t\tinNumber = True\n\t\t\t\tdigits.append(char)\n\t\t\telif inNumber:\n\t\t\t\tinNumber = False\n\t\t\t\tchars.append(str(int(int(\"\".join(digits)) * scale[0] / scale[1])))\n\t\t\t\tdigits = []\n\t\t\t\tchars.append(char)\n\t\t\telse:\n\t\t\t\tchars.append(char)\n\t\treturn \"\".join(chars).strip()\n\n\tvalue = value.strip()\n\ttry:\n\t\tresult = int(int(value) * scale[0] / scale[1]) # For speed try a simple number first.\n\texcept ValueError:\n\t\tif value == \"center\": # For speed as this can be common case.\n\t\t\treturn max(int((parent - size) // 2) if size else 0, 0)\n\t\telif value == \"*\":\n\t\t\treturn None\n\t\tif font is None:\n\t\t\tfont = \"Body\"\n\t\t\tif \"w\" in value or \"h\" in value:\n\t\t\t\tprint(f\"[Skin] Warning: Coordinate 'w' and/or 'h' used but font is None, '{font}' font ('{fonts[font][0]}', width={fonts[font][3]}, height={fonts[font][2]}) assumed!\")\n\t\tval = scaleNumbers(value, scale)\n\t\tif \"center\" in val:\n\t\t\tval = val.replace(\"center\", str((parent - size) / 2.0))\n\t\tif \"e\" in val:\n\t\t\tval = val.replace(\"e\", str(parent))\n\t\tif \"c\" in val:\n\t\t\tval = val.replace(\"c\", str(parent / 2.0))\n\t\tif \"%\" in val:\n\t\t\tval = val.replace(\"%\", f\"*{parent / 100.0}\")\n\t\tif \"w\" in val:\n\t\t\tval = val.replace(\"w\", f\"*{fonts[font][3]}\")\n\t\tif \"h\" in val:\n\t\t\tval = val.replace(\"h\", f\"*{fonts[font][2]}\")\n\t\tif \"f\" in val:\n\t\t\tval = val.replace(\"f\", f\"{getSkinFactor()}\")\n\t\ttry:\n\t\t\tresult = int(val) # For speed try a simple number first.\n\t\texcept ValueError:\n\t\t\ttry:\n\t\t\t\tresult = int(eval(val))\n\t\t\texcept Exception as err:\n\t\t\t\tprint(f\"[Skin] Error ({type(err).__name__} - {err}): Coordinate '{value}', calculated to '{val}', can't be evaluated!\")\n\t\t\t\tresult = 0\n\t# print(f\"[Skin] parseCoordinate DEBUG: value='{value}', parent='{parent}', size={size}, font='{font}', scale='{scale}', result='{result}'.\")\n\treturn 0 if result < 0 else result", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@instrumented_task(\n name=\"sentry.tasks.unmerge\",\n queue=\"unmerge\",\n silo_mode=SiloMode.REGION,\n)\ndef unmerge(*posargs, **kwargs):\n args = UnmergeArgsBase.parse_arguments(*posargs, **kwargs)\n\n source = Group.objects.get(project_id=args.project_id, id=args.source_id)\n\n caches = get_caches()\n\n project = caches[\"Project\"](args.project_id)\n\n # On the first iteration of this loop, we clear out all of the\n # denormalizations from the source group so that we can have a clean slate\n # for the new, repaired data.\n if isinstance(args, InitialUnmergeArgs):\n locked_primary_hashes = lock_hashes(\n args.project_id, args.source_id, args.replacement.primary_hashes_to_lock\n )\n truncate_denormalizations(project, source)\n last_event = None\n else:\n last_event = args.last_event\n locked_primary_hashes = args.locked_primary_hashes\n\n last_event, events = celery_run_batch_query(\n filter=eventstore.Filter(project_ids=[args.project_id], group_ids=[source.id]),\n batch_size=args.batch_size,\n state=last_event,\n referrer=\"unmerge\",\n tenant_ids={\"organization_id\": source.project.organization_id},\n )\n # Log info related to this unmerge\n logger.info(\n \"unmerge.check\",\n extra={\n \"source_id\": source.id,\n \"num_events\": len(events),\n },\n )\n\n # If there are no more events to process, we're done with the migration.\n if not events:\n unlock_hashes(args.project_id, locked_primary_hashes)\n for unmerge_key, (group_id, eventstream_state) in args.destinations.items():\n logger.warning(\n \"Unmerge complete (eventstream state: %s)\",\n eventstream_state,\n extra={\"source_id\": source.id},\n )\n if eventstream_state:\n args.replacement.stop_snuba_replacement(eventstream_state)\n return\n\n source_events = []\n destination_events: dict[str, list[BaseEvent]] = {}\n\n for event in events:\n key = args.replacement.get_unmerge_key(event, locked_primary_hashes)\n if key is not None:\n destination_events.setdefault(key, []).append(event)\n else:\n source_events.append(event)\n\n source_fields_reset = isinstance(args, SuccessiveUnmergeArgs) and args.source_fields_reset\n\n if source_events:\n if not source_fields_reset:\n source.update(**get_group_creation_attributes(caches, source, source_events))\n source_fields_reset = True\n else:\n source.update(**get_group_backfill_attributes(caches, source, source_events))\n\n destinations = dict(args.destinations)\n # Log info related to this unmerge\n logger.info(\n \"unmerge.destinations\",\n extra={\n \"source_id\": source.id,\n \"source_events\": len(source_events),\n \"destination_events\": len(destination_events),\n \"source_fields_reset\": source_fields_reset,\n },\n )\n\n # XXX: This is only actually able to create a destination group and migrate\n # the group hashes if there are events that can be migrated. How do we\n # handle this if there aren't any events? We can't create a group (there\n # isn't any data to derive the aggregates from), so we'd have to mark the\n # hash as in limbo somehow...?)\n\n for unmerge_key, _destination_events in destination_events.items():\n destination_id, eventstream_state = destinations.get(unmerge_key) or (None, None)\n (destination_id, eventstream_state) = migrate_events(\n source,\n caches,\n project,\n args,\n _destination_events,\n locked_primary_hashes,\n destination_id,\n eventstream_state,\n )\n destinations[unmerge_key] = destination_id, eventstream_state\n\n repair_denormalizations(caches, project, events)\n\n new_args = SuccessiveUnmergeArgs(\n project_id=args.project_id,\n source_id=args.source_id,\n replacement=args.replacement,\n actor_id=args.actor_id,\n batch_size=args.batch_size,\n last_event=last_event,\n destinations=destinations,\n locked_primary_hashes=locked_primary_hashes,\n source_fields_reset=source_fields_reset,\n )\n\n unmerge.delay(**new_args.dump_arguments())", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def _parse(cls, path):\n context = ElementTree.iterparse(path, events=(\"start\", \"end\"))\n context = iter(context)\n\n categories, tasks_info, attribute_types = cls._parse_meta(context)\n\n items = OrderedDict()\n\n track = None\n track_shapes = None\n track_elements = None\n shape = None\n shape_element = None\n tag = None\n attributes = None\n element_attributes = None\n image = None\n subset = None\n for ev, el in context:\n if ev == 'start':\n if el.tag == 'track':\n frame_size = tasks_info[int(el.attrib.get('task_id'))]['frame_size'] \\\n if el.attrib.get('task_id') else tuple(tasks_info.values())[0]['frame_size']\n track = {\n 'id': el.attrib['id'],\n 'label': el.attrib.get('label'),\n 'group': int(el.attrib.get('group_id', 0)),\n 'height': frame_size[0],\n 'width': frame_size[1],\n }\n subset = el.attrib.get('subset')\n track_shapes = {}\n elif el.tag == 'image':\n image = {\n 'name': el.attrib.get('name'),\n 'frame': el.attrib['id'],\n 'width': el.attrib.get('width'),\n 'height': el.attrib.get('height'),\n }\n subset = el.attrib.get('subset')\n elif el.tag in cls._SUPPORTED_SHAPES and (track or image):\n if shape and shape['type'] == 'skeleton':\n element_attributes = {}\n shape_element = {\n 'type': 'rectangle' if el.tag == 'box' else el.tag,\n 'attributes': element_attributes,\n }\n if track:\n shape_element.update(track)\n else:\n shape_element.update(image)\n else:\n attributes = {}\n shape = {\n 'type': 'rectangle' if el.tag == 'box' else el.tag,\n 'attributes': attributes,\n }\n shape['elements'] = []\n if track:\n shape.update(track)\n shape['track_id'] = int(track['id'])\n shape['frame'] = el.attrib['frame']\n track_elements = []\n if image:\n shape.update(image)\n elif el.tag == 'tag' and image:\n attributes = {}\n tag = {\n 'frame': image['frame'],\n 'attributes': attributes,\n 'group': int(el.attrib.get('group_id', 0)),\n 'label': el.attrib['label'],\n }\n subset = el.attrib.get('subset')\n elif ev == 'end':\n if el.tag == 'attribute' and element_attributes is not None and shape_element is not None:\n attr_value = el.text or ''\n attr_type = attribute_types.get(el.attrib['name'])\n if el.text in ['true', 'false']:\n attr_value = attr_value == 'true'\n elif attr_type is not None and attr_type != 'text':\n try:\n attr_value = float(attr_value)\n except ValueError:\n pass\n element_attributes[el.attrib['name']] = attr_value\n\n if el.tag == 'attribute' and attributes is not None and shape_element is None:\n attr_value = el.text or ''\n attr_type = attribute_types.get(el.attrib['name'])\n if el.text in ['true', 'false']:\n attr_value = attr_value == 'true'\n elif attr_type is not None and attr_type != 'text':\n try:\n attr_value = float(attr_value)\n except ValueError:\n pass\n attributes[el.attrib['name']] = attr_value\n\n elif el.tag in cls._SUPPORTED_SHAPES and shape[\"type\"] == \"skeleton\" and el.tag != \"skeleton\":\n shape_element['label'] = el.attrib.get('label')\n shape_element['group'] = int(el.attrib.get('group_id', 0))\n\n shape_element['type'] = el.tag\n shape_element['z_order'] = int(el.attrib.get('z_order', 0))\n\n if el.tag == 'box':\n shape_element['points'] = list(map(float, [\n el.attrib['xtl'], el.attrib['ytl'],\n el.attrib['xbr'], el.attrib['ybr'],\n ]))\n else:\n shape_element['points'] = []\n for pair in el.attrib['points'].split(';'):\n shape_element['points'].extend(map(float, pair.split(',')))\n\n if el.tag == 'points' and el.attrib.get('occluded') == '1':\n shape_element['visibility'] = [Points.Visibility.hidden] * (len(shape_element['points']) // 2)\n else:\n shape_element['occluded'] = (el.attrib.get('occluded') == '1')\n\n if el.tag == 'points' and el.attrib.get('outside') == '1':\n shape_element['visibility'] = [Points.Visibility.absent] * (len(shape_element['points']) // 2)\n else:\n shape_element['outside'] = (el.attrib.get('outside') == '1')\n\n if track:\n shape_element['keyframe'] = (el.attrib.get('keyframe') == '1')\n if shape_element['keyframe']:\n track_elements.append(shape_element)\n else:\n shape['elements'].append(shape_element)\n shape_element = None\n\n elif el.tag in cls._SUPPORTED_SHAPES:\n if track is not None:\n shape['frame'] = el.attrib['frame']\n shape['outside'] = (el.attrib.get('outside') == '1')\n shape['keyframe'] = (el.attrib.get('keyframe') == '1')\n if image is not None:\n shape['label'] = el.attrib.get('label')\n shape['group'] = int(el.attrib.get('group_id', 0))\n\n shape['type'] = el.tag\n shape['occluded'] = (el.attrib.get('occluded') == '1')\n shape['z_order'] = int(el.attrib.get('z_order', 0))\n shape['rotation'] = float(el.attrib.get('rotation', 0))\n\n if el.tag == 'box':\n shape['points'] = list(map(float, [\n el.attrib['xtl'], el.attrib['ytl'],\n el.attrib['xbr'], el.attrib['ybr'],\n ]))\n elif el.tag == 'skeleton':\n shape['points'] = []\n else:\n shape['points'] = []\n for pair in el.attrib['points'].split(';'):\n shape['points'].extend(map(float, pair.split(',')))\n\n if track:\n if shape[\"type\"] == \"skeleton\" and track_elements:\n shape[\"keyframe\"] = True\n track_shapes[shape['frame']] = shape\n track_shapes[shape['frame']]['elements'] = track_elements\n track_elements = None\n elif shape[\"type\"] != \"skeleton\":\n track_shapes[shape['frame']] = shape\n else:\n frame_desc = items.get((subset, shape['frame']), {'annotations': []})\n frame_desc['annotations'].append(\n cls._parse_shape_ann(shape, categories))\n items[(subset, shape['frame'])] = frame_desc\n\n shape = None\n\n elif el.tag == 'tag':\n frame_desc = items.get((subset, tag['frame']), {'annotations': []})\n frame_desc['annotations'].append(\n cls._parse_tag_ann(tag, categories))\n items[(subset, tag['frame'])] = frame_desc\n tag = None\n elif el.tag == 'track':\n for track_shape in track_shapes.values():\n frame_desc = items.get((subset, track_shape['frame']), {'annotations': []})\n frame_desc['annotations'].append(\n cls._parse_shape_ann(track_shape, categories))\n items[(subset, track_shape['frame'])] = frame_desc\n track = None\n elif el.tag == 'image':\n frame_desc = items.get((subset, image['frame']), {'annotations': []})\n frame_desc.update({\n 'name': image.get('name'),\n 'height': image.get('height'),\n 'width': image.get('width'),\n 'subset': subset,\n })\n items[(subset, image['frame'])] = frame_desc\n image = None\n el.clear()\n\n return items, categories", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def ParseAvsFromJson(self, inJsn):\n self.mVisible = getParameterFromBlock(inJsn, 'show time annotation',\n self.mVisible)\n\n #global gTestTimeNotation\n #if gTestTimeNotation == 0:\n # self.mVisible = True\n # gTestTimeNotation = 1\n #else:\n # self.mVisible = False\n # gTestTimeNotation = 0\n\n if 'time annotation position' in inJsn:\n windowPosSize = inJsn['time annotation position']\n winPos = windowPosSize[0]\n winSize = windowPosSize[1]\n self.SetSizeScale(winSize)\n global gParaViewCatalystVersionFlag\n if gParaViewCatalystVersionFlag < 51000:\n if winPos == 'top left':\n self.SetWindowLocation('UpperLeftCorner')\n elif winPos == 'top right':\n self.SetWindowLocation('UpperRightCorner')\n elif winPos == 'top':\n self.SetWindowLocation('UpperCenter')\n elif winPos == 'bottom left':\n self.SetWindowLocation('LowerLeftCorner')\n elif winPos == 'bottom right':\n self.SetWindowLocation('LowerRightCorner')\n elif winPos == 'bottom':\n self.SetWindowLocation('LowerCenter')\n else:\n if PhactoriDbg():\n myDebugPrint3(\"bad time annotation position, using upper left\\n\")\n self.SetWindowLocation('UpperLeftCorner')\n else: #gParaViewCatalystVersionFlag >= 51000\n if winPos == 'top left':\n self.SetWindowLocation('Upper Left Corner')\n elif winPos == 'top right':\n self.SetWindowLocation('Upper Right Corner')\n elif winPos == 'top':\n self.SetWindowLocation('Upper Center')\n elif winPos == 'bottom left':\n self.SetWindowLocation('Lower Left Corner')\n elif winPos == 'bottom right':\n self.SetWindowLocation('Lower Right Corner')\n elif winPos == 'bottom':\n self.SetWindowLocation('Lower Center')\n else:\n if PhactoriDbg():\n myDebugPrint3(\"bad time annotation position, using upper left\\n\")\n self.SetWindowLocation('UpperLeftCorner')\n\n if 'time format string' in inJsn:\n self.mTimeFormatString = inJsn['time format string']", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def pre_validate_solutions(\n solutions: list[Type | None],\n original_vars: Sequence[TypeVarLikeType],\n constraints: list[Constraint],\n) -> list[Type | None]:\n \"\"\"Check is each solution satisfies the upper bound of the corresponding type variable.\n\n If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and\n if yes, use it instead as a fallback solution.\n \"\"\"\n new_solutions: list[Type | None] = []\n for t, s in zip(original_vars, solutions):\n if is_callable_protocol(t.upper_bound):\n # This is really ad-hoc, but a proper fix would be much more complex,\n # and otherwise this may cause crash in a relatively common scenario.\n new_solutions.append(s)\n continue\n if s is not None and not is_subtype(s, t.upper_bound):\n bound_satisfies_all = True\n for c in constraints:\n if c.op == SUBTYPE_OF and not is_subtype(t.upper_bound, c.target):\n bound_satisfies_all = False\n break\n if c.op == SUPERTYPE_OF and not is_subtype(c.target, t.upper_bound):\n bound_satisfies_all = False\n break\n if bound_satisfies_all:\n new_solutions.append(t.upper_bound)\n continue\n new_solutions.append(s)\n return new_solutions", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def cfg_convert(self, value):\n \"\"\"Default converter for the cfg:// protocol.\"\"\"\n rest = value\n m = self.WORD_PATTERN.match(rest)\n if m is None:\n raise ValueError(\"Unable to convert %r\" % value)\n else:\n rest = rest[m.end():]\n d = self.config[m.groups()[0]]\n while rest:\n m = self.DOT_PATTERN.match(rest)\n if m:\n d = d[m.groups()[0]]\n else:\n m = self.INDEX_PATTERN.match(rest)\n if m:\n idx = m.groups()[0]\n if not self.DIGIT_PATTERN.match(idx):\n d = d[idx]\n else:\n try:\n n = int(\n idx\n ) # try as number first (most likely)\n d = d[n]\n except TypeError:\n d = d[idx]\n if m:\n rest = rest[m.end():]\n else:\n raise ValueError('Unable to convert '\n '%r at %r' % (value, rest))\n # rest should be empty\n return d", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def _validate_data(counter, manifest_files=None):\n unique_entries = 0\n multiple_entries = 0\n for media_type, media_config in MEDIA_TYPES.items():\n if counter[media_type]:\n if media_config['unique']:\n unique_entries += len(counter[media_type])\n else:\n multiple_entries += len(counter[media_type])\n\n if manifest_files and media_type not in ('video', 'image', 'zip', 'archive'):\n raise Exception(\n 'File with meta information can only be uploaded with video/images/archives'\n )\n\n if unique_entries == 1 and multiple_entries > 0 or unique_entries > 1:\n unique_types = ', '.join([k for k, v in MEDIA_TYPES.items() if v['unique']])\n multiply_types = ', '.join([k for k, v in MEDIA_TYPES.items() if not v['unique']])\n count = ', '.join(['{} {}(s)'.format(len(v), k) for k, v in counter.items()])\n raise ValueError('Only one {} or many {} can be used simultaneously, \\\n but {} found.'.format(unique_types, multiply_types, count))\n\n if unique_entries == 0 and multiple_entries == 0:\n raise ValueError('No media data found')\n\n task_modes = [MEDIA_TYPES[media_type]['mode'] for media_type, media_files in counter.items() if media_files]\n\n if not all(mode == task_modes[0] for mode in task_modes):\n raise Exception('Could not combine different task modes for data')\n\n return counter, task_modes[0]", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def load_data(\n platform,\n default=None,\n sample_name=None,\n timestamp=None,\n start_timestamp=None,\n trace=None,\n span_id=None,\n spans=None,\n trace_context=None,\n fingerprint=None,\n event_id=None,\n metrics_summary=None,\n):\n # NOTE: Before editing this data, make sure you understand the context\n # in which its being used. It is NOT only used for local development and\n # has production consequences.\n # * bin/load-mocks to generate fake data for local testing\n # * When a new project is created, a fake event is generated as a \"starter\"\n # event so it's not an empty project.\n # * When a user clicks Test Configuration from notification plugin settings page,\n # a fake event is generated to go through the pipeline.\n data = None\n language = None\n platform_data = INTEGRATION_ID_TO_PLATFORM_DATA.get(platform)\n\n if platform_data is not None and platform_data[\"type\"] != \"language\":\n language = platform_data[\"language\"]\n\n samples_root = os.path.join(DATA_ROOT, \"samples\")\n\n # this loop will try to load the specified platform first, but if we do not\n # have a specific sample for it, we then move on to the `language`, then the `default`.\n # The `default` is set to `javascript` in ./src/sentry/api/endpoints/project_create_sample.py\n # on the `ProjectCreateSampleEndpoint`\n for sample in (platform, language, default):\n if not sample:\n continue\n\n # Verify the requested path is valid and disallow path traversal attempts\n json_file = f\"{sample}.json\"\n\n expected_commonpath = os.path.realpath(\n samples_root\n ) # .realpath() ensures symlinks are handled\n json_path = os.path.join(samples_root, json_file)\n json_real_path = os.path.realpath(json_path)\n\n if expected_commonpath != os.path.commonpath([expected_commonpath, json_real_path]):\n raise SuspiciousFileOperation(\"potential path traversal attack detected\")\n\n # the requested `sample` does not exist, so continue through to the next iteration\n if not os.path.exists(json_path):\n continue\n\n if not os.path.isfile(json_path):\n raise IsADirectoryError(\"expected file but found a directory instead\")\n\n if not sample_name:\n try:\n sample_name = INTEGRATION_ID_TO_PLATFORM_DATA[platform][\"name\"]\n except KeyError:\n pass\n\n # XXX: At this point, it's assumed that `json_path` was safely found\n # within `samples_root` due to the checks above and cannot traverse\n # into paths.\n with open(json_path) as fp:\n data = json.load(fp)\n break\n\n if data is None:\n return\n\n if platform in (\"csp\", \"hkpk\", \"expectct\", \"expectstaple\"):\n return data\n\n # Generate a timestamp in the present.\n if timestamp is None:\n timestamp = datetime.utcnow() - timedelta(minutes=1)\n timestamp = timestamp - timedelta(microseconds=timestamp.microsecond % 1000)\n timestamp = timestamp.replace(tzinfo=timezone.utc)\n data.setdefault(\"timestamp\", timestamp.timestamp())\n\n if data.get(\"type\") == \"transaction\":\n if start_timestamp is None:\n start_timestamp = timestamp - timedelta(seconds=3)\n else:\n start_timestamp = start_timestamp.replace(tzinfo=timezone.utc)\n data[\"start_timestamp\"] = start_timestamp.timestamp()\n\n if metrics_summary is not None:\n data[\"_metrics_summary\"] = metrics_summary\n\n if trace is None:\n trace = uuid4().hex\n if span_id is None:\n span_id = uuid4().hex[:16]\n\n for tag in data[\"tags\"]:\n if tag[0] == \"trace\":\n tag[1] = trace\n elif tag[0] == \"trace.span\":\n tag[1] = span_id\n data[\"contexts\"][\"trace\"][\"trace_id\"] = trace\n data[\"contexts\"][\"trace\"][\"span_id\"] = span_id\n if trace_context is not None:\n data[\"contexts\"][\"trace\"].update(trace_context)\n if spans:\n data[\"spans\"] = spans\n\n for span in data.get(\"spans\", []):\n # Use data to generate span timestamps consistently and based\n # on event timestamp\n duration = span.get(\"data\", {}).get(\"duration\", 10.0)\n offset = span.get(\"data\", {}).get(\"offset\", 0)\n\n # Span doesn't have a parent, make it the transaction\n if span.get(\"parent_span_id\") is None:\n span[\"parent_span_id\"] = span_id\n if span.get(\"span_id\") is None:\n span[\"span_id\"] = uuid4().hex[:16]\n\n span_start = data[\"start_timestamp\"] + offset\n span[\"trace_id\"] = trace\n span.setdefault(\"start_timestamp\", span_start)\n span.setdefault(\"timestamp\", span_start + duration)\n\n measurements = data.get(\"measurements\")\n\n if measurements:\n measurement_markers = {}\n for key, entry in measurements.items():\n if key in [\n \"fp\",\n \"fcp\",\n \"lcp\",\n \"fid\",\n \"time_to_initial_display\",\n \"time_to_full_display\",\n ]:\n measurement_markers[f\"mark.{key}\"] = {\n \"unit\": \"none\",\n \"value\": round(data[\"start_timestamp\"] + entry[\"value\"] / 1000, 3),\n }\n measurements.update(measurement_markers)\n\n if fingerprint is not None:\n for f in fingerprint:\n f_data = f.split(\"-\", 1)\n if len(f_data) < 2:\n raise ValueError(\n \"Invalid performance fingerprint data. Format must be 'group_type-fingerprint'.\"\n )\n\n data[\"fingerprint\"] = fingerprint\n\n if event_id is not None:\n data[\"event_id\"] = event_id\n\n data[\"platform\"] = platform\n data.setdefault(\n \"logentry\", {\"formatted\": f\"This is an example {sample_name or platform} exception\"}\n )\n data.setdefault(\n \"user\",\n generate_user(ip_address=\"127.0.0.1\", username=\"sentry\", id=1, email=\"sentry@example.com\"),\n )\n data.setdefault(\n \"extra\",\n {\n \"session\": {\"foo\": \"bar\"},\n \"results\": [1, 2, 3, 4, 5],\n \"emptyList\": [],\n \"emptyMap\": {},\n \"length\": 10837790,\n \"unauthorized\": False,\n \"url\": \"http://example.org/foo/bar/\",\n },\n )\n data.setdefault(\"modules\", {\"my.package\": \"1.0.0\"})\n data.setdefault(\n \"request\",\n {\n \"cookies\": \"foo=bar;biz=baz\",\n \"url\": \"http://example.com/foo\",\n \"headers\": {\n \"Referer\": \"http://example.com\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36\",\n },\n \"env\": {\"ENV\": \"prod\"},\n \"query_string\": \"foo=bar\",\n \"data\": '{\"hello\": \"world\"}',\n \"method\": \"GET\",\n },\n )\n\n return data", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def process_hotspots(scanned_hotspots):\n global CONFIG\n global UNSERVED_FREQUENCIES\n if len(scanned_hotspots) > OPTIONS.hotspots_noise:\n return\n # calculate frequency for each hotspot and create list of valid hotspots\n hotspots = []\n for hotspot in scanned_hotspots:\n width = hotspot['end'] - hotspot['begin']\n fc = hotspot['begin'] + width/2\n if not freq_in_ranges_check(fc):\n continue\n hotspot['fc'] = fc\n hotspot['begin'] = fc - (width/2) # re-center around fc\n hotspot['end'] = fc + (width/2)\n hotspots.append(hotspot)\n # calculate hotspot distances for each used channel and reuse the channel for the closest hotspot\n channels = CONFIG['channel_info']\n used_channels = [channel for channel in channels if channel['usage'] == 1]\n consolidated_distances = []\n for channel in used_channels: # loop on used channels\n distances = [[abs(channel['frequency'] - get_hotspot_frequency(channel, hotspot)), hotspot] for hotspot in hotspots]\n distances = sorted(distances, key=operator.itemgetter(0))\n if distances:\n consolidated_distances.append([distances[0][0], channel, distances[0][1]]) # [distance, channel, hotspot]\n consolidated_distances = sorted(consolidated_distances, key=operator.itemgetter(0)) # get (channel, hotspot) pair with shortest distance first\n # reallocate used channels on their closest hotspot\n for distance in consolidated_distances:\n channel = distance[1]\n hotspot = distance[2]\n if hotspot in hotspots: # hotspot is not processed yet\n channel_frequency = get_hotspot_frequency(channel, hotspot)\n channel['usage'] = 2 # mark channel used on this pass\n if channel['frequency'] != channel_frequency: # optimization: do not move to same frequency\n channel['frequency'] = channel_frequency\n channel_index = channel['index']\n set_channel_frequency(channel)\n log_with_timestamp(f'Moved channel {channel_index} to frequency {channel_frequency} Hz')\n hotspots.remove(hotspot) # done with this hotspot\n # for remaining hotspots we need to allocate new channels\n for hotspot in hotspots:\n channel = allocate_channel()\n if channel:\n channel_index = channel['index']\n channel_frequency = get_hotspot_frequency(channel, hotspot)\n channel['usage'] = 2 # mark channel used on this pass\n channel['frequency'] = channel_frequency\n set_channel_frequency(channel)\n log_with_timestamp(f'Allocated channel {channel_index} on frequency {channel_frequency} Hz')\n else:\n fc = hotspot['fc']\n if fc not in UNSERVED_FREQUENCIES:\n UNSERVED_FREQUENCIES.append(fc)\n log_with_timestamp(f'All channels allocated. Cannot process signal at {fc} Hz')\n # cleanup\n for channel in CONFIG['channel_info']:\n if channel['usage'] == 1: # channel unused on this pass\n channel['usage'] = 0 # release it\n channel_index = channel['index']\n fc = channel['frequency']\n set_channel_mute(channel)\n UNSERVED_FREQUENCIES.clear() # at least one channel is able to serve next time\n log_with_timestamp(f'Released channel {channel_index} on frequency {fc} Hz')\n elif channel['usage'] == 2: # channel used on this pass\n channel['usage'] = 1 # reset usage for next pass", "smellKey": "S3776", "smellId": null, "repo": "f4exb_sdrangel", "language": "python"} {"function": "def get_attrs(\n self, item_list: Sequence[Team], user: User, **kwargs: Any\n ) -> MutableMapping[Team, MutableMapping[str, Any]]:\n request = env.request\n org_ids: set[int] = {t.organization_id for t in item_list}\n\n assert len(org_ids) == 1, \"Cross organization query for teams\"\n\n optimization = (\n maybe_singular_rpc_access_org_context(self.access, org_ids) if self.access else None\n )\n roles_by_org = get_org_roles(org_ids, user, optimization=optimization)\n\n member_totals = get_member_totals(item_list, user)\n team_memberships = _get_team_memberships(item_list, user, optimization=optimization)\n access_requests = get_access_requests(item_list, user)\n\n is_superuser = request and is_active_superuser(request) and request.user == user\n result: MutableMapping[Team, MutableMapping[str, Any]] = {}\n organization = Organization.objects.get_from_cache(id=list(org_ids)[0])\n\n for team in item_list:\n is_member = team.id in team_memberships\n org_role = roles_by_org.get(team.organization_id)\n team_role_id, team_role_scopes = team_memberships.get(team.id), set()\n\n has_access = bool(\n is_member\n or is_superuser\n or organization.flags.allow_joinleave\n or (org_role and roles.get(org_role).is_global)\n )\n\n if has_access:\n effective_team_role = (\n team_roles.get(team_role_id) if team_role_id else team_roles.get_default()\n )\n\n if is_superuser:\n org_role = organization_roles.get_top_dog().id\n\n if org_role:\n minimum_team_role = roles.get_minimum_team_role(org_role)\n if minimum_team_role.priority > effective_team_role.priority:\n effective_team_role = minimum_team_role\n\n team_role_scopes = effective_team_role.scopes\n team_role_id = effective_team_role.id\n\n result[team] = {\n \"pending_request\": team.id in access_requests,\n \"is_member\": is_member,\n \"team_role\": team_role_id if is_member else None,\n \"access\": team_role_scopes,\n \"has_access\": has_access,\n \"member_count\": member_totals.get(team.id, 0),\n }\n\n if self._expand(\"projects\"):\n project_teams = ProjectTeam.objects.get_for_teams_with_org_cache(item_list)\n projects = [pt.project for pt in project_teams]\n\n projects_by_id = {\n project.id: data for project, data in zip(projects, serialize(projects, user))\n }\n\n project_map = defaultdict(list)\n for project_team in project_teams:\n project_map[project_team.team_id].append(projects_by_id[project_team.project_id])\n\n for team in item_list:\n result[team][\"projects\"] = project_map[team.id]\n\n if self._expand(\"externalTeams\"):\n external_actors = list(\n ExternalActor.objects.filter(team_id__in={team.id for team in item_list})\n )\n\n external_teams_map = defaultdict(list)\n serialized_list = serialize(external_actors, user, key=\"team\")\n for serialized in serialized_list:\n external_teams_map[serialized[\"teamId\"]].append(serialized)\n\n for team in item_list:\n result[team][\"externalTeams\"] = external_teams_map[str(team.id)]\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def delete(self):\n # sort instance collections\n for model, instances in self.data.items():\n self.data[model] = sorted(instances, key=attrgetter(\"pk\"))\n\n # if possible, bring the models in an order suitable for databases that\n # don't support transactions or cannot defer constraint checks until the\n # end of a transaction.\n self.sort()\n # number of objects deleted for each model label\n deleted_counter = Counter()\n\n # Optimize for the case with a single obj and no dependencies\n if len(self.data) == 1 and len(instances) == 1:\n instance = list(instances)[0]\n if self.can_fast_delete(instance):\n with transaction.mark_for_rollback_on_error(self.using):\n count = sql.DeleteQuery(model).delete_batch(\n [instance.pk], self.using\n )\n setattr(instance, model._meta.pk.attname, None)\n return count, {model._meta.label: count}\n\n with transaction.atomic(using=self.using, savepoint=False):\n # send pre_delete signals\n for model, obj in self.instances_with_model():\n if not model._meta.auto_created:\n signals.pre_delete.send(\n sender=model,\n instance=obj,\n using=self.using,\n origin=self.origin,\n )\n\n # fast deletes\n for qs in self.fast_deletes:\n count = qs._raw_delete(using=self.using)\n if count:\n deleted_counter[qs.model._meta.label] += count\n\n # update fields\n for (field, value), instances_list in self.field_updates.items():\n updates = []\n objs = []\n for instances in instances_list:\n if (\n isinstance(instances, models.QuerySet)\n and instances._result_cache is None\n ):\n updates.append(instances)\n else:\n objs.extend(instances)\n if updates:\n combined_updates = reduce(or_, updates)\n combined_updates.update(**{field.name: value})\n if objs:\n model = objs[0].__class__\n query = sql.UpdateQuery(model)\n query.update_batch(\n list({obj.pk for obj in objs}), {field.name: value}, self.using\n )\n\n # reverse instance collections\n for instances in self.data.values():\n instances.reverse()\n\n # delete instances\n for model, instances in self.data.items():\n query = sql.DeleteQuery(model)\n pk_list = [obj.pk for obj in instances]\n count = query.delete_batch(pk_list, self.using)\n if count:\n deleted_counter[model._meta.label] += count\n\n if not model._meta.auto_created:\n for obj in instances:\n signals.post_delete.send(\n sender=model,\n instance=obj,\n using=self.using,\n origin=self.origin,\n )\n\n for model, instances in self.data.items():\n for instance in instances:\n setattr(instance, model._meta.pk.attname, None)\n return sum(deleted_counter.values()), dict(deleted_counter)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def unary_op(self, value: Value, expr_op: str, line: int) -> Value:\n typ = value.type\n if is_bool_rprimitive(typ) or is_bit_rprimitive(typ):\n if expr_op == \"not\":\n return self.unary_not(value, line)\n if expr_op == \"+\":\n return value\n if is_fixed_width_rtype(typ):\n if expr_op == \"-\":\n # Translate to '0 - x'\n return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)\n elif expr_op == \"~\":\n if typ.is_signed:\n # Translate to 'x ^ -1'\n return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line)\n else:\n # Translate to 'x ^ 0xff...'\n mask = (1 << (typ.size * 8)) - 1\n return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line)\n elif expr_op == \"+\":\n return value\n if is_float_rprimitive(typ):\n if expr_op == \"-\":\n return self.add(FloatNeg(value, line))\n elif expr_op == \"+\":\n return value\n\n if isinstance(value, Integer):\n # TODO: Overflow? Unsigned?\n num = value.value\n if is_short_int_rprimitive(typ):\n num >>= 1\n return Integer(-num, typ, value.line)\n if is_tagged(typ) and expr_op == \"+\":\n return value\n if isinstance(value, Float):\n return Float(-value.value, value.line)\n if isinstance(typ, RInstance):\n if expr_op == \"-\":\n method = \"__neg__\"\n elif expr_op == \"+\":\n method = \"__pos__\"\n elif expr_op == \"~\":\n method = \"__invert__\"\n else:\n method = \"\"\n if method and typ.class_ir.has_method(method):\n return self.gen_method_call(value, method, [], None, line)\n call_c_ops_candidates = unary_ops.get(expr_op, [])\n target = self.matching_call_c(call_c_ops_candidates, [value], line)\n assert target, \"Unsupported unary operation: %s\" % expr_op\n return target", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def makeChanServMap(self, channels):\n res = defaultdict(list)\n name_map = dict((n.upper(), t) for n, t in self.getScanChanNameMap().items())\n\n ice_services = set()\n for channel in channels:\n channel_id = int(channel[\"id\"])\n triplets = []\n if \"dvb_triplets\" in channel:\n triplets = channel[\"dvb_triplets\"]\n elif \"dvbt_info\" in channel:\n triplets = channel[\"dvbt_info\"]\n for triplet in triplets:\n t = (int(triplet[\"original_network_id\"]),\n int(triplet[\"transport_stream_id\"]),\n int(triplet[\"service_id\"]))\n res[channel_id].append(t)\n ice_services.add(t)\n\n names = [channel[\"name\"].strip().upper()]\n if \"name_short\" in channel:\n name = channel[\"name_short\"].strip().upper()\n if name not in names:\n names.append(name)\n for n in channel.get(\"known_names\", []):\n name = n.strip().upper()\n if name not in names:\n names.append(name)\n\n for triplets in (name_map[n] for n in names if n in name_map):\n for triplet in (t for t in triplets if t not in res[channel_id]):\n res[channel_id].append(triplet)\n ice_services.add(triplet)\n self.channel_service_map = res\n self.service_set = ice_services\n return res", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def parse_tuple(\n self,\n simplified: bool = False,\n with_condexpr: bool = True,\n extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,\n explicit_parentheses: bool = False,\n ) -> t.Union[nodes.Tuple, nodes.Expr]:\n \"\"\"Works like `parse_expression` but if multiple expressions are\n delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.\n This method could also return a regular expression instead of a tuple\n if no commas where found.\n\n The default parsing mode is a full tuple. If `simplified` is `True`\n only names and literals are parsed. The `no_condexpr` parameter is\n forwarded to :meth:`parse_expression`.\n\n Because tuples do not require delimiters and may end in a bogus comma\n an extra hint is needed that marks the end of a tuple. For example\n for loops support tuples between `for` and `in`. In that case the\n `extra_end_rules` is set to ``['name:in']``.\n\n `explicit_parentheses` is true if the parsing was triggered by an\n expression in parentheses. This is used to figure out if an empty\n tuple is a valid expression or not.\n \"\"\"\n lineno = self.stream.current.lineno\n if simplified:\n parse = self.parse_primary\n elif with_condexpr:\n parse = self.parse_expression\n else:\n\n def parse() -> nodes.Expr:\n return self.parse_expression(with_condexpr=False)\n\n args: t.List[nodes.Expr] = []\n is_tuple = False\n\n while True:\n if args:\n self.stream.expect(\"comma\")\n if self.is_tuple_end(extra_end_rules):\n break\n args.append(parse())\n if self.stream.current.type == \"comma\":\n is_tuple = True\n else:\n break\n lineno = self.stream.current.lineno\n\n if not is_tuple:\n if args:\n return args[0]\n\n # if we don't have explicit parentheses, an empty tuple is\n # not a valid expression. This would mean nothing (literally\n # nothing) in the spot of an expression would be an empty\n # tuple.\n if not explicit_parentheses:\n self.fail(\n \"Expected an expression,\"\n f\" got {describe_token(self.stream.current)!r}\"\n )\n\n return nodes.Tuple(args, \"load\", lineno=lineno)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def _changeform_view(self, request, object_id, form_url, extra_context):\n to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))\n if to_field and not self.to_field_allowed(request, to_field):\n raise DisallowedModelAdminToField(\n \"The field %s cannot be referenced.\" % to_field\n )\n\n if request.method == \"POST\" and \"_saveasnew\" in request.POST:\n object_id = None\n\n add = object_id is None\n\n if add:\n if not self.has_add_permission(request):\n raise PermissionDenied\n obj = None\n\n else:\n obj = self.get_object(request, unquote(object_id), to_field)\n\n if request.method == \"POST\":\n if not self.has_change_permission(request, obj):\n raise PermissionDenied\n else:\n if not self.has_view_or_change_permission(request, obj):\n raise PermissionDenied\n\n if obj is None:\n return self._get_obj_does_not_exist_redirect(\n request, self.opts, object_id\n )\n\n fieldsets = self.get_fieldsets(request, obj)\n ModelForm = self.get_form(\n request, obj, change=not add, fields=flatten_fieldsets(fieldsets)\n )\n if request.method == \"POST\":\n form = ModelForm(request.POST, request.FILES, instance=obj)\n formsets, inline_instances = self._create_formsets(\n request,\n form.instance,\n change=not add,\n )\n form_validated = form.is_valid()\n if form_validated:\n new_object = self.save_form(request, form, change=not add)\n else:\n new_object = form.instance\n if all_valid(formsets) and form_validated:\n self.save_model(request, new_object, form, not add)\n self.save_related(request, form, formsets, not add)\n change_message = self.construct_change_message(\n request, form, formsets, add\n )\n if add:\n self.log_addition(request, new_object, change_message)\n return self.response_add(request, new_object)\n else:\n self.log_change(request, new_object, change_message)\n return self.response_change(request, new_object)\n else:\n form_validated = False\n else:\n if add:\n initial = self.get_changeform_initial_data(request)\n form = ModelForm(initial=initial)\n formsets, inline_instances = self._create_formsets(\n request, form.instance, change=False\n )\n else:\n form = ModelForm(instance=obj)\n formsets, inline_instances = self._create_formsets(\n request, obj, change=True\n )\n\n if not add and not self.has_change_permission(request, obj):\n readonly_fields = flatten_fieldsets(fieldsets)\n else:\n readonly_fields = self.get_readonly_fields(request, obj)\n admin_form = helpers.AdminForm(\n form,\n list(fieldsets),\n # Clear prepopulated fields on a view-only form to avoid a crash.\n (\n self.get_prepopulated_fields(request, obj)\n if add or self.has_change_permission(request, obj)\n else {}\n ),\n readonly_fields,\n model_admin=self,\n )\n media = self.media + admin_form.media\n\n inline_formsets = self.get_inline_formsets(\n request, formsets, inline_instances, obj\n )\n for inline_formset in inline_formsets:\n media += inline_formset.media\n\n if add:\n title = _(\"Add %s\")\n elif self.has_change_permission(request, obj):\n title = _(\"Change %s\")\n else:\n title = _(\"View %s\")\n context = {\n **self.admin_site.each_context(request),\n \"title\": title % self.opts.verbose_name,\n \"subtitle\": str(obj) if obj else None,\n \"adminform\": admin_form,\n \"object_id\": object_id,\n \"original\": obj,\n \"is_popup\": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,\n \"to_field\": to_field,\n \"media\": media,\n \"inline_admin_formsets\": inline_formsets,\n \"errors\": helpers.AdminErrorList(form, formsets),\n \"preserved_filters\": self.get_preserved_filters(request),\n }\n\n # Hide the \"Save\" and \"Save and continue\" buttons if \"Save as New\" was\n # previously chosen to prevent the interface from getting confusing.\n if (\n request.method == \"POST\"\n and not form_validated\n and \"_saveasnew\" in request.POST\n ):\n context[\"show_save\"] = False\n context[\"show_save_and_continue\"] = False\n # Use the change template instead of the add template.\n add = False\n\n context.update(extra_context or {})\n\n return self.render_change_form(\n request, context, add=add, change=not add, obj=obj, form_url=form_url\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_event_payload_properties(self, event):\n props = {\n \"event_id\": event.event_id,\n \"issue_id\": event.group_id,\n \"project_id\": event.project.slug,\n \"transaction\": event.get_tag(\"transaction\") or \"\",\n \"release\": event.get_tag(\"sentry:release\") or \"\",\n \"environment\": event.get_tag(\"environment\") or \"\",\n \"type\": event.get_event_type(),\n }\n props[\"tags\"] = [\n [k.format(tagstore.backend.get_standardized_key(k)), v] for k, v in event.tags\n ]\n for key, value in event.interfaces.items():\n if key == \"request\":\n headers = value.headers\n if not isinstance(headers, dict):\n headers = dict(headers or ())\n\n props.update(\n {\n \"request_url\": value.url,\n \"request_method\": value.method,\n \"request_referer\": headers.get(\"Referer\", \"\"),\n }\n )\n elif key == \"exception\":\n exc = value.values[0]\n props.update({\"exception_type\": exc.type, \"exception_value\": exc.value})\n elif key == \"logentry\":\n props.update({\"message\": value.formatted or value.message})\n elif key in (\"csp\", \"expectct\", \"expectstable\", \"hpkp\"):\n props.update(\n {\n \"{}_{}\".format(key.rsplit(\".\", 1)[-1].lower(), k): v\n for k, v in value.to_json().items()\n }\n )\n elif key == \"user\":\n user_payload = {}\n if value.id:\n user_payload[\"user_id\"] = value.id\n if value.email:\n user_payload[\"user_email_hash\"] = md5_text(value.email).hexdigest()\n if value.ip_address:\n user_payload[\"user_ip_trunc\"] = anonymize_ip(value.ip_address)\n if user_payload:\n props.update(user_payload)\n return props", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _make_ansi_codes(self, color_system: ColorSystem) -> str:\n \"\"\"Generate ANSI codes for this style.\n\n Args:\n color_system (ColorSystem): Color system.\n\n Returns:\n str: String containing codes.\n \"\"\"\n\n if self._ansi is None:\n sgr: List[str] = []\n append = sgr.append\n _style_map = self._style_map\n attributes = self._attributes & self._set_attributes\n if attributes:\n if attributes & 1:\n append(_style_map[0])\n if attributes & 2:\n append(_style_map[1])\n if attributes & 4:\n append(_style_map[2])\n if attributes & 8:\n append(_style_map[3])\n if attributes & 0b0000111110000:\n for bit in range(4, 9):\n if attributes & (1 << bit):\n append(_style_map[bit])\n if attributes & 0b1111000000000:\n for bit in range(9, 13):\n if attributes & (1 << bit):\n append(_style_map[bit])\n if self._color is not None:\n sgr.extend(self._color.downgrade(color_system).get_ansi_codes())\n if self._bgcolor is not None:\n sgr.extend(\n self._bgcolor.downgrade(color_system).get_ansi_codes(\n foreground=False\n )\n )\n self._ansi = \";\".join(sgr)\n return self._ansi", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def add_type_promotion(\n info: TypeInfo, module_names: SymbolTable, options: Options, builtin_names: SymbolTable\n) -> None:\n \"\"\"Setup extra, ad-hoc subtyping relationships between classes (promotion).\n\n This includes things like 'int' being compatible with 'float'.\n \"\"\"\n defn = info.defn\n promote_targets: list[ProperType] = []\n for decorator in defn.decorators:\n if isinstance(decorator, CallExpr):\n analyzed = decorator.analyzed\n if isinstance(analyzed, PromoteExpr):\n # _promote class decorator (undocumented feature).\n promote_targets.append(analyzed.type)\n if not promote_targets:\n if defn.fullname in TYPE_PROMOTIONS:\n target_sym = module_names.get(TYPE_PROMOTIONS[defn.fullname])\n if defn.fullname == \"builtins.bytearray\" and options.disable_bytearray_promotion:\n target_sym = None\n elif defn.fullname == \"builtins.memoryview\" and options.disable_memoryview_promotion:\n target_sym = None\n # With test stubs, the target may not exist.\n if target_sym:\n target_info = target_sym.node\n assert isinstance(target_info, TypeInfo)\n promote_targets.append(Instance(target_info, []))\n # Special case the promotions between 'int' and native integer types.\n # These have promotions going both ways, such as from 'int' to 'i64'\n # and 'i64' to 'int', for convenience.\n if defn.fullname in MYPYC_NATIVE_INT_NAMES:\n int_sym = builtin_names[\"int\"]\n assert isinstance(int_sym.node, TypeInfo)\n int_sym.node._promote.append(Instance(defn.info, []))\n defn.info.alt_promote = Instance(int_sym.node, [])\n if promote_targets:\n defn.info._promote.extend(promote_targets)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def finish_packet(self):\n self.finish_item()\n if self.current_packet:\n warnings = self.current_packet.check_bit_offsets()\n if len(warnings) > 0:\n self.warnings += warnings\n if self.current_cmd_or_tlm == PacketConfig.COMMAND:\n PacketParser.check_item_data_types(self.current_packet)\n self.commands[self.current_packet.target_name][self.current_packet.packet_name] = self.current_packet\n if not self.current_packet.virtual:\n hash = self.cmd_id_value_hash.get(self.current_packet.target_name)\n if not hash:\n hash = {}\n self.cmd_id_value_hash[self.current_packet.target_name] = hash\n self.update_id_value_hash(hash)\n else:\n self.telemetry[self.current_packet.target_name][self.current_packet.packet_name] = self.current_packet\n if not self.current_packet.virtual:\n hash = self.tlm_id_value_hash.get(self.current_packet.target_name)\n if not hash:\n hash = {}\n self.tlm_id_value_hash[self.current_packet.target_name] = hash\n self.update_id_value_hash(hash)\n\n self.current_packet = None\n self.current_item = None", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def format_message(self) -> str:\n if self.param_hint is not None:\n param_hint: t.Optional[str] = self.param_hint\n elif self.param is not None:\n param_hint = self.param.get_error_hint(self.ctx) # type: ignore\n else:\n param_hint = None\n\n param_hint = _join_param_hints(param_hint)\n param_hint = f\" {param_hint}\" if param_hint else \"\"\n\n param_type = self.param_type\n if param_type is None and self.param is not None:\n param_type = self.param.param_type_name\n\n msg = self.message\n if self.param is not None:\n msg_extra = self.param.type.get_missing_message(self.param)\n if msg_extra:\n if msg:\n msg += f\". {msg_extra}\"\n else:\n msg = msg_extra\n\n msg = f\" {msg}\" if msg else \"\"\n\n # Translate param_type for known types.\n if param_type == \"argument\":\n missing = _(\"Missing argument\")\n elif param_type == \"option\":\n missing = _(\"Missing option\")\n elif param_type == \"parameter\":\n missing = _(\"Missing parameter\")\n else:\n missing = _(\"Missing {param_type}\").format(param_type=param_type)\n\n return f\"{missing}{param_hint}.{msg}\"", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None:\n # Copy the items because we may mutate symtab.\n for key, value in list(symtab.items()):\n cross_ref = value.cross_ref\n if cross_ref is not None: # Fix up cross-reference.\n value.cross_ref = None\n if cross_ref in self.modules:\n value.node = self.modules[cross_ref]\n else:\n stnode = lookup_fully_qualified(\n cross_ref, self.modules, raise_on_missing=not self.allow_missing\n )\n if stnode is not None:\n if stnode is value:\n # The node seems to refer to itself, which can mean that\n # the target is a deleted submodule of the current module,\n # and thus lookup falls back to the symbol table of the parent\n # package. Here's how this may happen:\n #\n # pkg/__init__.py:\n # from pkg import sub\n #\n # Now if pkg.sub is deleted, the pkg.sub symbol table entry\n # appears to refer to itself. Replace the entry with a\n # placeholder to avoid a crash. We can't delete the entry,\n # as it would stop dependency propagation.\n value.node = Var(key + \"@deleted\")\n else:\n assert stnode.node is not None, (table_fullname + \".\" + key, cross_ref)\n value.node = stnode.node\n elif not self.allow_missing:\n assert False, f\"Could not find cross-ref {cross_ref}\"\n else:\n # We have a missing crossref in allow missing mode, need to put something\n value.node = missing_info(self.modules)\n else:\n if isinstance(value.node, TypeInfo):\n # TypeInfo has no accept(). TODO: Add it?\n self.visit_type_info(value.node)\n elif value.node is not None:\n value.node.accept(self)\n else:\n assert False, f\"Unexpected empty node {key!r}: {value}\"", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def check_requirements(\n self, reqs: Iterable[str]\n ) -> Tuple[Set[Tuple[str, str]], Set[str]]:\n \"\"\"Return 2 sets:\n - conflicting requirements: set of (installed, wanted) reqs tuples\n - missing requirements: set of reqs\n \"\"\"\n missing = set()\n conflicting = set()\n if reqs:\n env = (\n get_environment(self._lib_dirs)\n if hasattr(self, \"_lib_dirs\")\n else get_default_environment()\n )\n for req_str in reqs:\n req = Requirement(req_str)\n # We're explicitly evaluating with an empty extra value, since build\n # environments are not provided any mechanism to select specific extras.\n if req.marker is not None and not req.marker.evaluate({\"extra\": \"\"}):\n continue\n dist = env.get_distribution(req.name)\n if not dist:\n missing.add(req_str)\n continue\n if isinstance(dist.version, Version):\n installed_req_str = f\"{req.name}=={dist.version}\"\n else:\n installed_req_str = f\"{req.name}==={dist.version}\"\n if not req.specifier.contains(dist.version, prereleases=True):\n conflicting.add((installed_req_str, req_str))\n # FIXME: Consider direct URL?\n return conflicting, missing", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def has_any_project_scope(self, project: Project, scopes: Collection[str]) -> bool:\n \"\"\"\n Represent if a user should have access with any one of the given scopes to\n information for the given project.\n\n For performance's sake, prefer this over multiple calls to `has_project_scope`.\n \"\"\"\n if not self.has_project_access(project):\n return False\n if any(self.has_scope(scope) for scope in scopes):\n return True\n\n if self.rpc_user_organization_context.member and features.has(\n \"organizations:team-roles\", self.rpc_user_organization_context.organization\n ):\n with sentry_sdk.start_span(op=\"check_access_for_all_project_teams\") as span:\n project_teams_id = set(project.teams.values_list(\"id\", flat=True))\n orgmember_teams = self.rpc_user_organization_context.member.member_teams\n span.set_tag(\"organization\", self.rpc_user_organization_context.organization.id)\n span.set_tag(\n \"organization.slug\", self.rpc_user_organization_context.organization.slug\n )\n span.set_data(\"membership_count\", len(orgmember_teams))\n\n for member_team in orgmember_teams:\n if not member_team.role:\n continue\n if member_team.team_id not in project_teams_id:\n continue\n\n team_scopes = member_team.role.scopes\n if self.scopes_upper_bound:\n team_scopes = team_scopes & self.scopes_upper_bound\n\n for scope in scopes:\n if scope in team_scopes:\n metrics.incr(\n \"team_roles.pass_by_project_scope\",\n tags={\"team_role\": f\"{member_team.role.id}\", \"scope\": scope},\n )\n return True\n return False", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _match_segments(\n a_segms,\n b_segms,\n distance=dm.ops.segment_iou,\n dist_thresh=1.0,\n label_matcher=lambda a, b: a.label == b.label,\n):\n assert callable(distance), distance\n assert callable(label_matcher), label_matcher\n\n max_anns = max(len(a_segms), len(b_segms))\n distances = np.array(\n [\n [\n 1 - distance(a, b) if a is not None and b is not None else 1\n for b, _ in itertools.zip_longest(b_segms, range(max_anns), fillvalue=None)\n ]\n for a, _ in itertools.zip_longest(a_segms, range(max_anns), fillvalue=None)\n ]\n )\n distances[~np.isfinite(distances)] = 1\n distances[distances > 1 - dist_thresh] = 1\n\n if a_segms and b_segms:\n a_matches, b_matches = linear_sum_assignment(distances)\n else:\n a_matches = []\n b_matches = []\n\n # matches: boxes we succeeded to match completely\n # mispred: boxes we succeeded to match, having label mismatch\n matches = []\n mispred = []\n # *_umatched: boxes of (*) we failed to match\n a_unmatched = []\n b_unmatched = []\n\n for a_idx, b_idx in zip(a_matches, b_matches):\n dist = distances[a_idx, b_idx]\n if dist > 1 - dist_thresh or dist == 1:\n if a_idx < len(a_segms):\n a_unmatched.append(a_segms[a_idx])\n if b_idx < len(b_segms):\n b_unmatched.append(b_segms[b_idx])\n else:\n a_ann = a_segms[a_idx]\n b_ann = b_segms[b_idx]\n if label_matcher(a_ann, b_ann):\n matches.append((a_ann, b_ann))\n else:\n mispred.append((a_ann, b_ann))\n\n if not len(a_matches) and not len(b_matches):\n a_unmatched = list(a_segms)\n b_unmatched = list(b_segms)\n\n return matches, mispred, a_unmatched, b_unmatched", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def summary(self):\n self.printer.printout_ln()\n\n if self._n_run:\n if self._exited_early:\n self.printer.printout_ln(\"Testing exited early\")\n self.printer.printout_ln()\n self.printer.printout_ln(\"%d tests passed (%.2f%%)\" % (\n self._n_passed, (self._n_passed * 100) / self._n_run))\n self.printer.printout_ln()\n\n def result_tests(test_dict):\n if not test_dict:\n return 0, None\n\n n_tests = 0\n tests = \"\"\n for backend in test_dict:\n backend_docs = test_dict[backend]\n n_tests += len(backend_docs)\n tests += \"\\n\".join([\" %s (%s)\" % (doc_path, backend) for doc_path in backend_docs])\n tests += \"\\n\"\n\n return n_tests, tests\n\n def backends_summary(test_dict, n_tests):\n percs = []\n for backend in test_dict:\n n_docs = len(test_dict[backend])\n percs.append(\"%d %s (%.2f%%)\" % (n_docs, backend,\n n_docs * 100 / n_tests))\n return \", \".join(percs)\n\n test_results = [(self._failed, \"unexpected failures\"),\n (self._crashed, \"unexpected crashes\"),\n (self._failed_status_error, \"unexpected failures (test program returned with an exit error status)\"),\n (self._stderr, \"tests have stderr output\"),\n (self._did_not_crash, \"expected to crash, but didn't crash\"),\n (self._did_not_fail_status_error, \"expected to fail to run, but didn't fail\")]\n\n for test_dict, test_msg in test_results:\n n_tests, tests = result_tests(test_dict)\n if n_tests == 0:\n continue\n\n self.printer.printout_ln(\"%d %s (%.2f%%) [%s]\" % (\n n_tests, test_msg, n_tests * 100 / self._n_run,\n backends_summary(test_dict, n_tests)))\n self.printer.printout_ln(tests)\n self.printer.printout_ln()\n else:\n self.printer.printout_ln(\"No tests run\")\n\n if self._skipped:\n self.printer.printout_ln(\"%d tests skipped\" % len(self._skipped))\n self.printer.printout_ln(\"\\n\".join([\" %s\" % skipped for skipped in self._skipped]))\n self.printer.printout_ln()\n\n if self._new:\n self.printer.printout_ln(\"%d new documents\" % len(self._new))\n self.printer.printout_ln(\"\\n\".join([\" %s\" % new for new in self._new]))\n self.printer.printout_ln(\"Use create-refs command to add reference results for them\")\n self.printer.printout_ln()", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_poppler", "language": "python"} {"function": "def find_fixed_callable_return(expr: Expression) -> CallableType | None:\n \"\"\"Return the return type, if expression refers to a callable that returns a callable.\n\n But only do this if the return type has no type variables. Return None otherwise.\n This approximates things a lot as this is supposed to be called before type checking\n when full type information is not available yet.\n \"\"\"\n if isinstance(expr, RefExpr):\n if isinstance(expr.node, FuncDef):\n typ = expr.node.type\n if typ:\n if isinstance(typ, CallableType) and has_no_typevars(typ.ret_type):\n ret_type = get_proper_type(typ.ret_type)\n if isinstance(ret_type, CallableType):\n return ret_type\n elif isinstance(expr, CallExpr):\n t = find_fixed_callable_return(expr.callee)\n if t:\n ret_type = get_proper_type(t.ret_type)\n if isinstance(ret_type, CallableType):\n return ret_type\n return None", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@extend_schema(\n operation_id=\"List an Organization's Replays\",\n parameters=[GlobalParams.ORG_ID_OR_SLUG, ReplayValidator],\n responses={\n 200: inline_sentry_response_serializer(\"ListReplays\", list[ReplayDetailsResponse]),\n 400: RESPONSE_BAD_REQUEST,\n 403: RESPONSE_FORBIDDEN,\n },\n examples=ReplayExamples.GET_REPLAYS,\n )\n @handled_snuba_exceptions\n def get(self, request: Request, organization: Organization) -> Response:\n \"\"\"\n Return a list of replays belonging to an organization.\n \"\"\"\n\n if not features.has(\"organizations:session-replay\", organization, actor=request.user):\n return Response(status=404)\n try:\n filter_params = self.get_filter_params(request, organization)\n except NoProjects:\n return Response({\"data\": []}, status=200)\n\n result = ReplayValidator(data=request.GET)\n if not result.is_valid():\n raise ParseError(result.errors)\n\n for key, value in result.validated_data.items():\n if key not in filter_params:\n filter_params[key] = value # type: ignore[literal-required]\n\n # We allow the requester to make their own decision about where to source the data.\n # Because this is a stateless, isolated interaction its okay for the user to decide where\n # to source the data. At worst they receive an exception and stop manually specifying the\n # header. This allows us to quickly test and compare multiple data sources without\n # interacting with a feature flagging system.\n preferred_source = request.headers.get(\"X-Preferred-Data-Source\")\n if preferred_source not in (\"scalar\", \"aggregated\", \"materialized-view\"):\n # If the feature flag has been enabled we'll default to the materialized-view data\n # source if none was provided. This would be the common path for users using the\n # Javascript web application.\n if features.has(\"organizations:session-replay-materialized-view\", organization):\n preferred_source = \"materialized-view\"\n else:\n preferred_source = \"scalar\"\n\n preferred_source = cast(PREFERRED_SOURCE, preferred_source)\n\n headers = {}\n\n def data_fn(offset: int, limit: int):\n try:\n search_filters = parse_search_query(\n request.query_params.get(\"query\", \"\"), config=replay_url_parser_config\n )\n except InvalidSearchQuery as e:\n raise ParseError(str(e))\n\n # Sort must be optional string.\n sort = filter_params.get(\"sort\")\n if not isinstance(sort, str):\n sort = None\n\n start = filter_params[\"start\"]\n end = filter_params[\"end\"]\n if start is None or end is None:\n # It's not possible to reach this point but the type hint is wrong so I have\n # to do this for completeness sake.\n return Response({\"detail\": \"Missing start or end period.\"}, status=400)\n\n response = query_replays_collection_paginated(\n project_ids=filter_params[\"project_id\"],\n start=start,\n end=end,\n environment=filter_params.get(\"environment\") or [],\n sort=sort,\n fields=request.query_params.getlist(\"field\"),\n limit=limit,\n offset=offset,\n search_filters=search_filters,\n preferred_source=preferred_source,\n organization=organization,\n actor=request.user,\n )\n\n # We set the data-source header so we can figure out which query is giving\n # incorrect or slow results.\n headers[\"X-Data-Source\"] = response.source\n\n return response\n\n response = self.paginate(\n request=request,\n paginator=ReplayPaginator(data_fn=data_fn),\n on_results=lambda results: {\n \"data\": process_raw_response(\n results,\n fields=request.query_params.getlist(\"field\"),\n )\n },\n )\n\n for header, value in headers.items():\n response[header] = value\n\n return response", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def somethingConnected(self, slotid=-1):\n\t\tif slotid == -1:\n\t\t\tconnected = False\n\t\t\tfor id in list(range(self.getSlotCount())):\n\t\t\t\tif self.somethingConnected(id):\n\t\t\t\t\tconnected = True\n\t\t\treturn connected\n\t\telse:\n\t\t\tres = False\n\t\t\tif self.nim_slots[slotid].canBeCompatible(\"DVB-S\"):\n\t\t\t\tnim = config.Nims[slotid].dvbs\n\t\t\t\tconfigMode = nim.configMode.value\n\t\t\t\tres = res or (configMode != \"nothing\")\n\t\t\tif self.nim_slots[slotid].canBeCompatible(\"DVB-T\"):\n\t\t\t\tnim = config.Nims[slotid].dvbt\n\t\t\t\tconfigMode = nim.configMode.value\n\t\t\t\tres = res or (configMode != \"nothing\")\n\t\t\tif self.nim_slots[slotid].canBeCompatible(\"DVB-C\"):\n\t\t\t\tnim = config.Nims[slotid].dvbc\n\t\t\t\tconfigMode = nim.configMode.value\n\t\t\t\tres = res or (configMode != \"nothing\")\n\t\t\tif self.nim_slots[slotid].canBeCompatible(\"ATSC\"):\n\t\t\t\tnim = config.Nims[slotid].atsc\n\t\t\t\tconfigMode = nim.configMode.value\n\t\t\t\tres = res or (configMode != \"nothing\")\n\t\t\treturn res", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:\n # Final letter analysis for logical-visual decision.\n # Look for evidence that the received buffer is either logical Hebrew\n # or visual Hebrew.\n # The following cases are checked:\n # 1) A word longer than 1 letter, ending with a final letter. This is\n # an indication that the text is laid out \"naturally\" since the\n # final letter really appears at the end. +1 for logical score.\n # 2) A word longer than 1 letter, ending with a Non-Final letter. In\n # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi,\n # should not end with the Non-Final form of that letter. Exceptions\n # to this rule are mentioned above in isNonFinal(). This is an\n # indication that the text is laid out backwards. +1 for visual\n # score\n # 3) A word longer than 1 letter, starting with a final letter. Final\n # letters should not appear at the beginning of a word. This is an\n # indication that the text is laid out backwards. +1 for visual\n # score.\n #\n # The visual score and logical score are accumulated throughout the\n # text and are finally checked against each other in GetCharSetName().\n # No checking for final letters in the middle of words is done since\n # that case is not an indication for either Logical or Visual text.\n #\n # We automatically filter out all 7-bit characters (replace them with\n # spaces) so the word boundary detection works properly. [MAP]\n\n if self.state == ProbingState.NOT_ME:\n # Both model probers say it's not them. No reason to continue.\n return ProbingState.NOT_ME\n\n byte_str = self.filter_high_byte_only(byte_str)\n\n for cur in byte_str:\n if cur == self.SPACE:\n # We stand on a space - a word just ended\n if self._before_prev != self.SPACE:\n # next-to-last char was not a space so self._prev is not a\n # 1 letter word\n if self.is_final(self._prev):\n # case (1) [-2:not space][-1:final letter][cur:space]\n self._final_char_logical_score += 1\n elif self.is_non_final(self._prev):\n # case (2) [-2:not space][-1:Non-Final letter][\n # cur:space]\n self._final_char_visual_score += 1\n else:\n # Not standing on a space\n if (\n (self._before_prev == self.SPACE)\n and (self.is_final(self._prev))\n and (cur != self.SPACE)\n ):\n # case (3) [-2:space][-1:final letter][cur:not space]\n self._final_char_visual_score += 1\n self._before_prev = self._prev\n self._prev = cur\n\n # Forever detecting, till the end or until both model probers return\n # ProbingState.NOT_ME (handled above)\n return ProbingState.DETECTING", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def fileReadXML(filename, default=None, source=DEFAULT_MODULE_NAME, debug=False):\n\tdom = None\n\ttry:\n\t\twith open(filename) as fd: # This open gets around a possible file handle leak in Python's XML parser.\n\t\t\ttry:\n\t\t\t\tdom = parse(fd).getroot()\n\t\t\t\tmsg = \"Read\"\n\t\t\texcept ParseError as err:\n\t\t\t\tfd.seek(0)\n\t\t\t\tcontent = fd.readlines()\n\t\t\t\tline, column = err.position\n\t\t\t\tprint(f\"[{source}] XML Parse Error: '{err}' in '{filename}'!\")\n\t\t\t\tdata = content[line - 1].replace(\"\\t\", \" \").rstrip()\n\t\t\t\tprint(f\"[{source}] XML Parse Error: '{data}'\")\n\t\t\t\tprint(f\"[{source}] XML Parse Error: '{'-' * column}^{' ' * (len(data) - column - 1)}'\")\n\t\t\texcept Exception as err:\n\t\t\t\tprint(f\"[{source}] Error: Unable to parse data in '{filename}' - '{err}'!\")\n\texcept OSError as err:\n\t\tif err.errno == ENOENT: # ENOENT - No such file or directory.\n\t\t\tprint(f\"[{source}] Warning: File '{filename}' does not exist!\")\n\t\telse:\n\t\t\tprint(\"[%s] Error %d: Opening file '%s'! (%s)\" % (source, err.errno, filename, err.strerror))\n\texcept Exception as err:\n\t\tprint(f\"[{source}] Error: Unexpected error opening/parsing file '{filename}'! ({err})\")\n\t\tprint_exc()\n\tif dom is None:\n\t\tif default and isinstance(default, str):\n\t\t\tdom = fromstring(default)\n\t\t\tmsg = \"Default (XML)\"\n\t\telif default and isinstance(default, Element):\n\t\t\tdom = default\n\t\t\tmsg = \"Default (DOM)\"\n\t\telse:\n\t\t\tmsg = \"Failed to read\"\n\tif debug or forceDebug:\n\t\tprint(f\"[{source}] Line {getframe(1).f_lineno}: {msg} from XML file '{filename}'.\")\n\treturn dom", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@staticmethod\n def explain_exception(exc, depth=16):\n \"\"\"\n Method to take an exception and translate the Python internal traceback into a list\n of the pyparsing expressions that caused the exception to be raised.\n\n Parameters:\n\n - exc - exception raised during parsing (need not be a ParseException, in support\n of Python exceptions that might be raised in a parse action)\n - depth (default=16) - number of levels back in the stack trace to list expression\n and function names; if None, the full stack trace names will be listed; if 0, only\n the failing input line, marker, and exception string will be shown\n\n Returns a multi-line string listing the ParserElements and/or function names in the\n exception's stack trace.\n \"\"\"\n import inspect\n from .core import ParserElement\n\n if depth is None:\n depth = sys.getrecursionlimit()\n ret = []\n if isinstance(exc, ParseBaseException):\n ret.append(exc.line)\n ret.append(\" \" * (exc.column - 1) + \"^\")\n ret.append(f\"{type(exc).__name__}: {exc}\")\n\n if depth > 0:\n callers = inspect.getinnerframes(exc.__traceback__, context=depth)\n seen = set()\n for i, ff in enumerate(callers[-depth:]):\n frm = ff[0]\n\n f_self = frm.f_locals.get(\"self\", None)\n if isinstance(f_self, ParserElement):\n if not frm.f_code.co_name.startswith(\n (\"parseImpl\", \"_parseNoCache\")\n ):\n continue\n if id(f_self) in seen:\n continue\n seen.add(id(f_self))\n\n self_type = type(f_self)\n ret.append(\n f\"{self_type.__module__}.{self_type.__name__} - {f_self}\"\n )\n\n elif f_self is not None:\n self_type = type(f_self)\n ret.append(f\"{self_type.__module__}.{self_type.__name__}\")\n\n else:\n code = frm.f_code\n if code.co_name in (\"wrapper\", \"<module>\"):\n continue\n\n ret.append(code.co_name)\n\n depth -= 1\n if not depth:\n break\n\n return \"\\n\".join(ret)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def __init__(self, settings_module):\n # update this dict from global settings (but only for ALL_CAPS settings)\n for setting in dir(global_settings):\n if setting.isupper():\n setattr(self, setting, getattr(global_settings, setting))\n\n # store the settings module in case someone later cares\n self.SETTINGS_MODULE = settings_module\n\n mod = importlib.import_module(self.SETTINGS_MODULE)\n\n tuple_settings = (\n \"ALLOWED_HOSTS\",\n \"INSTALLED_APPS\",\n \"TEMPLATE_DIRS\",\n \"LOCALE_PATHS\",\n \"SECRET_KEY_FALLBACKS\",\n )\n self._explicit_settings = set()\n for setting in dir(mod):\n if setting.isupper():\n setting_value = getattr(mod, setting)\n\n if setting in tuple_settings and not isinstance(\n setting_value, (list, tuple)\n ):\n raise ImproperlyConfigured(\n \"The %s setting must be a list or a tuple.\" % setting\n )\n setattr(self, setting, setting_value)\n self._explicit_settings.add(setting)\n\n if self.is_overridden(\"FORMS_URLFIELD_ASSUME_HTTPS\"):\n warnings.warn(\n FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG,\n RemovedInDjango60Warning,\n )\n\n if hasattr(time, \"tzset\") and self.TIME_ZONE:\n # When we can, attempt to validate the timezone. If we can't find\n # this file, no check happens and it's harmless.\n zoneinfo_root = Path(\"/usr/share/zoneinfo\")\n zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split(\"/\"))\n if zoneinfo_root.exists() and not zone_info_file.exists():\n raise ValueError(\"Incorrect timezone setting: %s\" % self.TIME_ZONE)\n # Move the time zone info into os.environ. See ticket #2315 for why\n # we don't do this unconditionally (breaks Windows).\n os.environ[\"TZ\"] = self.TIME_ZONE\n time.tzset()", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_event_by_id(\n self,\n project_id: int,\n event_id: str,\n group_id: int | None = None,\n tenant_ids=None,\n occurrence_id: str | None = None,\n *,\n skip_transaction_groupevent: bool = False,\n ) -> Event | GroupEvent | None:\n \"\"\"\n Get an event given a project ID and event ID\n Returns None if an event cannot be found\n\n skip_transaction_groupevent: Temporary hack parameter to skip converting a transaction\n event into a `GroupEvent`. Used as part of `post_process_group`.\n \"\"\"\n\n event_id = normalize_event_id(event_id)\n\n if not event_id:\n return None\n\n event = Event(project_id=project_id, event_id=event_id)\n\n # Return None if there was no data in nodestore\n if len(event.data) == 0:\n return None\n\n if group_id is not None and (\n event.get_event_type() == \"error\"\n or (event.get_event_type() == \"transaction\" and skip_transaction_groupevent)\n ):\n event.group_id = group_id\n elif occurrence_id is not None and group_id is not None:\n event.group_id = group_id\n\n event._snuba_data = {\n \"event_id\": event_id,\n \"group_id\": group_id,\n \"project_id\": project_id,\n \"timestamp\": event.timestamp,\n \"occurrence_id\": occurrence_id,\n }\n\n elif event.get_event_type() != \"transaction\" or group_id:\n # Load group_id from Snuba if not a transaction\n raw_query_kwargs = {}\n if event.datetime > timezone.now() - timedelta(hours=1):\n # XXX: This is a hack to bust the snuba cache. We want to avoid the case where\n # we cache an empty result, since this can result in us failing to fetch new events\n # in some cases.\n raw_query_kwargs[\"conditions\"] = [\n [\"timestamp\", \">\", datetime.fromtimestamp(random.randint(0, 1000000000))]\n ]\n dataset = (\n Dataset.IssuePlatform\n if event.get_event_type() in (\"transaction\", \"generic\")\n else Dataset.Events\n )\n try:\n tenant_ids = tenant_ids or {\"organization_id\": event.project.organization_id}\n filter_keys = {\"project_id\": [project_id], \"event_id\": [event_id]}\n if group_id:\n filter_keys[\"group_id\"] = [group_id]\n result = snuba.raw_query(\n dataset=dataset,\n selected_columns=self.__get_columns(dataset),\n start=event.datetime,\n end=event.datetime + timedelta(seconds=1),\n filter_keys=filter_keys,\n limit=1,\n referrer=\"eventstore.backend.get_event_by_id_nodestore\",\n tenant_ids=tenant_ids,\n **raw_query_kwargs,\n )\n except snuba.QueryOutsideRetentionError:\n # this can happen due to races. We silently want to hide\n # this from callers.\n return None\n\n # Return None if the event from Nodestore was not yet written to Snuba\n if len(result[\"data\"]) != 1:\n logger.warning(\n \"eventstore.missing-snuba-event\",\n extra={\n \"project_id\": project_id,\n \"event_id\": event_id,\n \"group_id\": group_id,\n \"event_datetime\": event.datetime,\n \"event_timestamp\": event.timestamp,\n \"nodestore_insert\": event.data.get(\"nodestore_insert\"),\n \"received\": event.data.get(\"received\"),\n \"len_data\": len(result[\"data\"]),\n },\n )\n return None\n\n event.group_id = result[\"data\"][0][\"group_id\"]\n # Inject the snuba data here to make sure any snuba columns are available\n event._snuba_data = result[\"data\"][0]\n\n # Set passed group_id if not a transaction\n if event.get_event_type() == \"transaction\" and not skip_transaction_groupevent and group_id:\n logger.warning(\"eventstore.passed-group-id-for-transaction\")\n return event.for_group(Group.objects.get(id=group_id))\n\n return event", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def ObservePotentialCrossingValue(self, mTestValue):\n if PhactoriDbg(100):\n if self.mObserveCallCount != 0:\n if PhactoriDbg(100):\n myDebugPrint3(\"ObservePotentialCrossingValue:\\n\" +\n str(mTestValue) + \" <> \" + str(self.mThresholdValue) + \" <> \" + \\\n str(self.mLastTestValue) + \"\\n\", 100)\n else:\n if PhactoriDbg(100):\n myDebugPrint3(\"ObservePotentialCrossingValue:\\n\" +\n str(mTestValue) + \" <> \" + str(self.mThresholdValue) + \" <> \" + \\\n str(\"first call\") + \"\\n\", 100)\n\n if self.mObserveCallCount != 0:\n if((self.mLastTestValue <= self.mThresholdValue) and \\\n (mTestValue >= self.mThresholdValue)) or \\\n ((self.mLastTestValue >= self.mThresholdValue) and \\\n (mTestValue <= self.mThresholdValue)):\n #the test value crosses the threshold from the last test value\n self.mCrossingsSoFar += 1\n self.mCountAtLastCrossing = self.mObserveCallCount\n if PhactoriDbg(100):\n myDebugPrint3(\"crossing occurred: \" + str(self.mCrossingsSoFar) + \\\n \", \" + str(self.mCountAtLastCrossing) + \"\\n\")\n if(self.mCrossingsSoFar <= self.mMaxTriggers):\n self.mCountAtLastTrigger = self.mObserveCallCount\n if PhactoriDbg(100):\n myDebugPrint3(\"self.mCountAtLastTrigger changed to \" +\n str(self.mCountAtLastTrigger) + \"\\n\")\n else:\n if PhactoriDbg(100):\n myDebugPrint3(\"no trigger due to self.mMaxTriggers\")\n\n self.mCurrentlyTriggered = False\n if self.mCrossingsSoFar != 0:\n if (self.mFramesAfterTrigger <= 0) or \\\n (self.mObserveCallCount - self.mCountAtLastTrigger) < \\\n self.mFramesAfterTrigger:\n self.mCurrentlyTriggered = True\n\n if PhactoriDbg(100):\n myDebugPrint3(\"self.mCurrentlyTriggered now \" + \\\n str(self.mCurrentlyTriggered) + \"\\n\")\n\n self.mLastTestValue = mTestValue\n self.mObserveCallCount += 1\n return", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def post_process(self, interface_prefix, c_namespace):\n if len(self.doc_string) == 0:\n self.doc_string = utils.lookup_docs(self.annotations)\n if len(self.doc_string_brief) == 0:\n self.doc_string_brief = utils.lookup_brief_docs(self.annotations)\n if len(self.since) == 0:\n self.since = utils.lookup_since(self.annotations)\n\n if len(c_namespace) > 0:\n if utils.is_ugly_case(c_namespace):\n cns = c_namespace.replace('_', '')\n cns_upper = c_namespace.upper() + '_'\n cns_lower = c_namespace.lower() + '_'\n else:\n cns = c_namespace\n cns_upper = utils.camel_case_to_uscore(c_namespace).upper() + '_'\n cns_lower = utils.camel_case_to_uscore(c_namespace).lower() + '_'\n else:\n cns = ''\n cns_upper = ''\n cns_lower = ''\n\n overridden_name = utils.lookup_annotation(self.annotations, 'org.gtk.GDBus.C.Name')\n if utils.is_ugly_case(overridden_name):\n name = overridden_name.replace('_', '')\n name_with_ns = cns + name\n self.name_without_prefix = name\n self.camel_name = name_with_ns\n self.ns_upper = cns_upper\n self.name_lower = cns_lower + overridden_name.lower()\n self.name_upper = overridden_name.upper()\n\n #print_error('handle Ugly_Case \"{}\"'.format(overridden_name))\n else:\n if overridden_name:\n name = overridden_name\n else:\n name = self.name\n if name.startswith(interface_prefix):\n name = name[len(interface_prefix):]\n self.name_without_prefix = name\n name = utils.strip_dots(name)\n name_with_ns = utils.strip_dots(cns + '.' + name)\n self.camel_name = name_with_ns\n self.ns_upper = cns_upper\n self.name_lower = cns_lower + utils.camel_case_to_uscore(name)\n self.name_upper = utils.camel_case_to_uscore(name).upper()\n\n self.name_hyphen = self.name_upper.lower().replace('_', '-')\n\n if utils.lookup_annotation(self.annotations, 'org.freedesktop.DBus.Deprecated') == 'true':\n self.deprecated = True\n\n for m in self.methods:\n m.post_process(interface_prefix, cns, cns_upper, cns_lower, self)\n\n for s in self.signals:\n s.post_process(interface_prefix, cns, cns_upper, cns_lower, self)\n\n for p in self.properties:\n p.post_process(interface_prefix, cns, cns_upper, cns_lower, self)\n\n for a in self.annotations:\n a.post_process(interface_prefix, cns, cns_upper, cns_lower, self)", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "@api_bp.route(\"/alias/random/new\", methods=[\"POST\"])\n@limiter.limit(ALIAS_LIMIT)\n@require_api_auth\n@parallel_limiter.lock(name=\"alias_creation\")\ndef new_random_alias():\n \"\"\"\n Create a new random alias\n Input:\n (Optional) note\n Output:\n 201 if success\n\n \"\"\"\n user = g.user\n if not user.can_create_new_alias():\n LOG.d(\"user %s cannot create new random alias\", user)\n return (\n jsonify(\n error=f\"You have reached the limitation of a free account with the maximum of \"\n f\"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases\"\n ),\n 400,\n )\n\n note = None\n data = request.get_json(silent=True)\n if data:\n note = data.get(\"note\")\n\n alias = None\n\n # custom alias suggestion and suffix\n hostname = request.args.get(\"hostname\")\n if hostname and user.include_website_in_one_click_alias:\n LOG.d(\"Use %s to create new alias\", hostname)\n # keep only the domain name of hostname, ignore TLD and subdomain\n # for ex www.groupon.com -> groupon\n ext = tldextract.extract(hostname)\n prefix_suggestion = ext.domain\n prefix_suggestion = convert_to_id(prefix_suggestion)\n\n suffixes = get_alias_suffixes(user)\n # use the first suffix\n suggested_alias = prefix_suggestion + suffixes[0].suffix\n\n alias = Alias.get_by(email=suggested_alias)\n\n # cannot use this alias as it belongs to another user\n if alias and not alias.user_id == user.id:\n LOG.d(\"%s belongs to another user\", alias)\n alias = None\n elif alias and alias.user_id == user.id:\n # make sure alias was created for this website\n if AliasUsedOn.get_by(\n alias_id=alias.id, hostname=hostname, user_id=alias.user_id\n ):\n LOG.d(\"Use existing alias %s\", alias)\n else:\n LOG.d(\"%s wasn't created for this website %s\", alias, hostname)\n alias = None\n elif not alias:\n LOG.d(\"create new alias %s\", suggested_alias)\n try:\n alias = Alias.create(\n user_id=user.id,\n email=suggested_alias,\n note=note,\n mailbox_id=user.default_mailbox_id,\n commit=True,\n )\n except AliasInTrashError:\n LOG.i(\"Alias %s is in trash\", suggested_alias)\n alias = None\n\n if not alias:\n scheme = user.alias_generator\n mode = request.args.get(\"mode\")\n if mode:\n if mode == \"word\":\n scheme = AliasGeneratorEnum.word.value\n elif mode == \"uuid\":\n scheme = AliasGeneratorEnum.uuid.value\n else:\n return jsonify(error=f\"{mode} must be either word or uuid\"), 400\n\n alias = Alias.create_new_random(user=user, scheme=scheme, note=note)\n Session.commit()\n\n if hostname and not AliasUsedOn.get_by(alias_id=alias.id, hostname=hostname):\n AliasUsedOn.create(\n alias_id=alias.id, hostname=hostname, user_id=alias.user_id, commit=True\n )\n\n return (\n jsonify(alias=alias.email, **serialize_alias_info_v2(get_alias_info_v2(alias))),\n 201,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]) -> None:\n \"\"\"Remove dummy alias definitions such as List = TypeAlias(object) from typing.\n\n They will be replaced with real aliases when corresponding targets are ready.\n \"\"\"\n\n # This is all pretty unfortunate. typeshed now has a\n # sys.version_info check for OrderedDict, and we shouldn't\n # take it out, because it is correct and a typechecker should\n # use that as a source of truth. But instead we rummage\n # through IfStmts to remove the info first. (I tried to\n # remove this whole machinery and ran into issues with the\n # builtins/typing import cycle.)\n def helper(defs: list[Statement]) -> None:\n for stmt in defs.copy():\n if isinstance(stmt, IfStmt):\n for body in stmt.body:\n helper(body.body)\n if stmt.else_body:\n helper(stmt.else_body.body)\n if (\n isinstance(stmt, AssignmentStmt)\n and len(stmt.lvalues) == 1\n and isinstance(stmt.lvalues[0], NameExpr)\n ):\n # Assignment to a simple name, remove it if it is a dummy alias.\n if f\"{file_node.fullname}.{stmt.lvalues[0].name}\" in aliases:\n defs.remove(stmt)\n\n helper(file_node.defs)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _format_lines(self, tokensource):\n \"\"\"\n Just format the tokens, without any wrapping tags.\n Yield individual lines.\n \"\"\"\n nocls = self.noclasses\n lsep = self.lineseparator\n tagsfile = self.tagsfile\n\n lspan = ''\n line = []\n for ttype, value in tokensource:\n try:\n cspan = self.span_element_openers[ttype]\n except KeyError:\n title = ' title=\"{}\"'.format('.'.join(ttype)) if self.debug_token_types else ''\n if nocls:\n css_style = self._get_css_inline_styles(ttype)\n if css_style:\n css_style = self.class2style[css_style][0]\n cspan = f'<span style=\"{css_style}\"{title}>'\n else:\n cspan = ''\n else:\n css_class = self._get_css_classes(ttype)\n if css_class:\n cspan = f'<span class=\"{css_class}\"{title}>'\n else:\n cspan = ''\n self.span_element_openers[ttype] = cspan\n\n parts = self._translate_parts(value)\n\n if tagsfile and ttype in Token.Name:\n filename, linenumber = self._lookup_ctag(value)\n if linenumber:\n base, filename = os.path.split(filename)\n if base:\n base += '/'\n filename, extension = os.path.splitext(filename)\n url = self.tagurlformat % {'path': base, 'fname': filename,\n 'fext': extension}\n parts[0] = \"<a href=\\\"%s#%s-%d\\\">%s\" % \\\n (url, self.lineanchors, linenumber, parts[0])\n parts[-1] = parts[-1] + \"</a>\"\n\n # for all but the last line\n for part in parts[:-1]:\n if line:\n # Also check for part being non-empty, so we avoid creating\n # empty <span> tags\n if lspan != cspan and part:\n line.extend(((lspan and '</span>'), cspan, part,\n (cspan and '</span>'), lsep))\n else: # both are the same, or the current part was empty\n line.extend((part, (lspan and '</span>'), lsep))\n yield 1, ''.join(line)\n line = []\n elif part:\n yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))\n else:\n yield 1, lsep\n # for the last line\n if line and parts[-1]:\n if lspan != cspan:\n line.extend(((lspan and '</span>'), cspan, parts[-1]))\n lspan = cspan\n else:\n line.append(parts[-1])\n elif parts[-1]:\n line = [cspan, parts[-1]]\n lspan = cspan\n # else we neither have to open a new span nor set lspan\n\n if line:\n line.extend(((lspan and '</span>'), lsep))\n yield 1, ''.join(line)", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def _get_layered_setting_options(\n self,\n project_id: int | None = None,\n **kwargs,\n ) -> MutableMapping[\n Recipient, MutableMapping[NotificationSettingEnum, NotificationSettingsOptionEnum]\n ]:\n \"\"\"\n Returns a mapping of the most specific notification setting options for the given recipients and scopes.\n Note that this includes default settings for any notification types that are not set.\n\n Args:\n setting_type: If specified, only return settings of this type.\n \"\"\"\n if self.project_ids and len(list(self.project_ids)) > 1 and not project_id:\n raise Exception(\"Must specify project_id if controller has more than 1 projects\")\n\n most_specific_setting_options: MutableMapping[\n Recipient, MutableMapping[NotificationSettingEnum, NotificationSettingsOptionEnum]\n ] = defaultdict(\n lambda: defaultdict(\n lambda: NotificationSettingsOptionEnum.DEFAULT\n ) # Use lambda to return the default enum value\n )\n\n for recipient in self.recipients:\n # get the settings for this user/team\n filter_kwargs = kwargs.copy()\n if recipient_is_user(recipient):\n filter_kwargs[\"user_id\"] = recipient.id\n elif recipient_is_team(recipient):\n filter_kwargs[\"team_id\"] = recipient.id\n local_settings = self._filter_options(**filter_kwargs)\n local_settings.sort(key=sort_settings_by_scope)\n most_specific_recipient_options = most_specific_setting_options[recipient]\n\n for setting in local_settings:\n # if we have a project_id, make sure the setting is for that project since\n # the controller can be scoped for multiple projects\n if (\n project_id is not None\n and setting.scope_type == NotificationScopeEnum.PROJECT.value\n ):\n if setting.scope_identifier != project_id:\n continue\n\n # sort the settings by scope type, with the most specific scope last so we override with the most specific value\n most_specific_recipient_options[\n NotificationSettingEnum(setting.type)\n ] = NotificationSettingsOptionEnum(setting.value)\n\n # if we have no settings for this user/team, use the defaults\n for type, default in get_type_defaults().items():\n if type not in most_specific_recipient_options:\n most_specific_recipient_options[type] = default\n return most_specific_setting_options", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@shared_task(track_started=True, name=\"resolve_twitter_ids_task\")\ndef resolve_twitter_ids():\n r = get_redis_connection()\n # TODO: we can't use our non-overlapping task decorator as it creates a loop in the celery resolver when registering\n if r.get(\"resolve_twitter_ids_task\"): # pragma: no cover\n return\n\n with r.lock(\"resolve_twitter_ids_task\", 1800):\n # look up all 'twitter' URNs, limiting to 30k since that's the most our API would allow anyways\n twitter_urns = ContactURN.objects.filter(\n scheme=URN.TWITTER_SCHEME, contact__status=Contact.STATUS_ACTIVE\n ).exclude(contact=None)\n twitter_urns = twitter_urns[:30000].only(\"id\", \"org\", \"contact\", \"path\")\n api_key = settings.TWITTER_API_KEY\n api_secret = settings.TWITTER_API_SECRET\n client = Twython(api_key, api_secret)\n\n updated = 0\n print(\"found %d twitter urns to resolve\" % len(twitter_urns))\n\n # contacts we will stop\n stop_contacts = []\n\n # we try to look these up 100 at a time\n for urn_batch in chunk_list(twitter_urns, 100):\n screen_names = [u.path for u in urn_batch]\n screen_map = {u.path: u for u in urn_batch}\n\n # try to fetch our users by screen name\n try:\n resp = client.lookup_user(screen_name=\",\".join(screen_names))\n\n for twitter_user in resp:\n screen_name = twitter_user[\"screen_name\"].lower()\n twitter_id = twitter_user[\"id\"]\n\n if screen_name in screen_map and twitter_user[\"id\"]:\n twitterid_urn = URN.normalize(URN.from_twitterid(twitter_id, screen_name))\n old_urn = screen_map[screen_name]\n\n # create our new contact URN\n new_urn = ContactURN.get_or_create(old_urn.org, old_urn.contact, twitterid_urn, priority=50)\n\n # if our new URN already existed for another contact and it is newer\n # than our old contact, reassign it to the old contact\n if (\n new_urn.contact != old_urn.contact\n and new_urn.contact.created_on > old_urn.contact.created_on\n ):\n new_urn.contact = old_urn.contact\n new_urn.save(update_fields=[\"contact\"])\n\n # get rid of our old URN\n ContactURN.objects.filter(id=old_urn.id).update(contact=None)\n del screen_map[screen_name]\n updated += 1\n\n except Exception as e:\n # if this wasn't an exception caused by not finding any of the users, then break\n if str(e).find(\"No user matches\") < 0:\n # exit, we'll try again later\n print(\"exiting resolve_twitter_ids due to exception: %s\" % e)\n break\n\n # add all remaining contacts to the contacts we will stop\n for contact in screen_map.values():\n stop_contacts.append(contact)\n\n # stop all the contacts we couldn't resolve that have only a twitter URN\n stopped = 0\n for contact_urn in stop_contacts:\n contact = contact_urn.contact\n if len(contact.urns.all()) == 1:\n contact.stop(contact.created_by)\n stopped += 1\n\n if len(twitter_urns) > 0:\n print(\"updated %d twitter urns, %d stopped\" % (updated, len(stop_contacts)))", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def mediainfoCB(self, mediuminfo, retval, extra_args):\n\t\tif isinstance(mediuminfo, bytes):\n\t\t\tmediuminfo = mediuminfo.decode()\n\t\tformatted_capacity = 0\n\t\tread_capacity = 0\n\t\tcapacity = 0\n\t\tused = 0\n\t\tinfotext = \"\"\n\t\tmediatype = \"\"\n\t\tfor line in mediuminfo.splitlines():\n\t\t\tif line.find(\"Mounted Media:\") > -1:\n\t\t\t\tmediatype = line.rsplit(',', 1)[1][1:]\n\t\t\t\tif mediatype.find(\"RW\") > 0 or mediatype.find(\"RAM\") > 0 or mediatype.find(\"RE\"):\n\t\t\t\t\tself.formattable = True\n\t\t\t\telse:\n\t\t\t\t\tself.formattable = False\n\t\t\telif line.find(\"Legacy lead-out at:\") > -1:\n\t\t\t\tused = int(line.rsplit('=', 1)[1]) / 1048576.0\n\t\t\t\tprint(\"[dvd+rw-mediainfo] lead out used =\", used)\n\t\t\telif line.find(\"formatted:\") > -1:\n\t\t\t\tformatted_capacity = int(line.rsplit('=', 1)[1]) / 1048576.0\n\t\t\t\tprint(\"[dvd+rw-mediainfo] formatted capacity =\", formatted_capacity)\n\t\t\telif formatted_capacity == 0 and line.find(\"READ CAPACITY:\") > -1:\n\t\t\t\tread_capacity = int(line.rsplit('=', 1)[1]) / 1048576.0\n\t\t\t\tprint(\"[dvd+rw-mediainfo] READ CAPACITY =\", read_capacity)\n\t\tfor line in mediuminfo.splitlines():\n\t\t\tif line.find(\"Free Blocks:\") > -1:\n\t\t\t\ttry:\n\t\t\t\t\tsize = eval(line[14:].replace(\"KB\", \"*1024\"))\n\t\t\t\texcept:\n\t\t\t\t\tsize = 0\n\t\t\t\tif size > 0:\n\t\t\t\t\tcapacity = size / 1048576\n\t\t\t\t\tif used:\n\t\t\t\t\t\tused = capacity - used\n\t\t\t\t\tprint(\"[dvd+rw-mediainfo] free blocks capacity=%d, used=%d\" % (capacity, used))\n\t\t\telif line.find(\"Disc status:\") > -1:\n\t\t\t\tif line.find(\"blank\") > -1:\n\t\t\t\t\tprint(\"[dvd+rw-mediainfo] Disc status blank capacity=%d, used=0\" % (capacity))\n\t\t\t\t\tcapacity = used\n\t\t\t\t\tused = 0\n\t\t\t\telif line.find(\"complete\") > -1 and formatted_capacity == 0:\n\t\t\t\t\tprint(\"[dvd+rw-mediainfo] Disc status complete capacity=0, used=%d\" % (capacity))\n\t\t\t\t\tused = read_capacity\n\t\t\t\t\tcapacity = 1\n\t\t\t\telse:\n\t\t\t\t\tcapacity = formatted_capacity\n\t\t\tinfotext += line + '\\n'\n\t\tif capacity and used > capacity:\n\t\t\tused = read_capacity or capacity\n\t\t\tcapacity = formatted_capacity or capacity\n\t\tprint(\"capacity\", capacity, \"used\", used, \"read_capacity\", read_capacity, \"formatted_capacity\", formatted_capacity)\n\t\tself[\"details\"].setText(infotext)\n\t\tif self.formattable:\n\t\t\tself[\"key_yellow\"].text = _(\"Format\")\n\t\telse:\n\t\t\tself[\"key_yellow\"].text = \"\"\n\t\tpercent = 100 * used / (capacity or 1)\n\t\tif capacity > 9900:\n\t\t\tself[\"space_label\"].text = \"%d / %d MB\" % (used, capacity) + \" (%.2f%% \" % percent + _(\"BLUDISC RECORDABLE\") + \")\"\n\t\t\tself[\"space_bar\"].value = int(percent)\n\t\telif capacity > 4600 and capacity < 9900:\n\t\t\tself[\"space_label\"].text = \"%d / %d MB\" % (used, capacity) + \" (%.2f%% \" % percent + _(\"of a DUAL layer medium used.\") + \")\"\n\t\t\tself[\"space_bar\"].value = int(percent)\n\t\telif capacity > 1:\n\t\t\tself[\"space_label\"].text = \"%d / %d MB\" % (used, capacity) + \" (%.2f%% \" % percent + _(\"of a SINGLE layer medium used.\") + \")\"\n\t\t\tself[\"space_bar\"].value = int(percent)\n\t\telif capacity == 1 and used > 0:\n\t\t\tself[\"space_label\"].text = \"%d MB \" % (used) + _(\"on READ ONLY medium.\")\n\t\t\tself[\"space_bar\"].value = int(percent)\n\t\telse:\n\t\t\tself[\"space_label\"].text = _(\"Medium is not a writeable DVD!\")\n\t\t\tself[\"space_bar\"].value = 0\n\t\tfree = capacity - used\n\t\tif free < 2:\n\t\t\tfree = 0\n\t\tself[\"info\"].text = \"Media-Type:\\t\\t%s\\nFree capacity:\\t\\t%d MB\" % (mediatype or \"NO DVD\", free)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def search_credentials(\n self,\n contexts: Sequence[str] = None,\n types: Sequence[str] = None,\n schema_ids: Optional[str] = None,\n issuer_id: Optional[str] = None,\n subject_ids: Optional[str] = None,\n proof_types: Sequence[str] = None,\n given_id: Optional[str] = None,\n tag_query: Optional[Mapping] = None,\n pd_uri_list: Sequence[str] = None,\n ) -> \"VCRecordSearch\":\n \"\"\"Start a new VC record search.\n\n Args:\n contexts (Sequence[str], optional): An inclusive list of JSON-LD contexts\n to match.\n types (Sequence[str], optional): An inclusive list of JSON-LD types to\n match.\n schema_ids (str, optional): An inclusive list of credential schema\n identifiers.\n issuer_id (str, optional): The ID of the credential issuer.\n subject_ids (str, optional): The IDs of credential subjects all of which\n to match.\n proof_types (Sequence[str], optional): The signature suite types used for\n the proof objects.\n given_id (str, optional): The given id of the credential.\n tag_query (Mapping, optional): A tag filter clause.\n pd_uri_list (Sequence[str], optional): A list of presentation definition\n URIs.\n\n Returns:\n VCRecordSearch: An instance of VCRecordSearch representing the search\n query.\n\n \"\"\"\n query = {}\n if contexts:\n for ctx_val in contexts:\n query[f\"ctxt:{ctx_val}\"] = \"1\"\n if types:\n for type_val in types:\n query[f\"type:{type_val}\"] = \"1\"\n if schema_ids:\n for schema_val in schema_ids:\n query[f\"schm:{schema_val}\"] = \"1\"\n if subject_ids:\n for subject_id in subject_ids:\n query[f\"subj:{subject_id}\"] = \"1\"\n if proof_types:\n for proof_type in proof_types:\n query[f\"ptyp:{proof_type}\"] = \"1\"\n if issuer_id:\n query[\"issuer_id\"] = issuer_id\n if given_id:\n query[\"given_id\"] = given_id\n if tag_query:\n query.update(tag_query)\n if pd_uri_list:\n query.update(self.build_type_or_schema_query(pd_uri_list))\n search = self._store.search_records(VC_CRED_RECORD_TYPE, query)\n return InMemoryVCRecordSearch(search)", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _get_layered_setting_providers(\n self,\n project_id: int | None = None,\n **kwargs,\n ) -> MutableMapping[\n Recipient,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ]:\n \"\"\"\n Returns a mapping of the most specific notification setting providers for the given recipients and scopes.\n Note that this includes default settings for any notification types that are not set.\n \"\"\"\n if self.project_ids and len(list(self.project_ids)) > 2 and not project_id:\n raise Exception(\"Must specify project_id if controller has more than 2 projects\")\n\n # Now, define your variable using the outermost defaultdict\n most_specific_setting_providers: MutableMapping[\n Recipient,\n MutableMapping[\n NotificationSettingEnum,\n MutableMapping[str, NotificationSettingsOptionEnum],\n ],\n ] = defaultdict(\n lambda: defaultdict(\n lambda: defaultdict(\n lambda: NotificationSettingsOptionEnum.DEFAULT\n ) # Use lambda to return the default enum value\n )\n )\n\n if self.organization_id is not None:\n org_mapping = OrganizationMapping.objects.filter(\n organization_id=self.organization_id\n ).first()\n org = serialize_organization_mapping(org_mapping) if org_mapping is not None else None\n else:\n org = None\n has_team_workflow = org and features.has(\"organizations:team-workflow-notifications\", org)\n\n for recipient in self.recipients:\n # get the settings for this user/team\n filter_kwargs = kwargs.copy()\n if recipient_is_user(recipient):\n filter_kwargs[\"user_id\"] = recipient.id\n elif recipient_is_team(recipient):\n filter_kwargs[\"team_id\"] = recipient.id\n\n local_settings = self._filter_providers(**filter_kwargs)\n local_settings.sort(key=sort_settings_by_scope)\n\n most_specific_recipient_providers = most_specific_setting_providers[recipient]\n for setting in local_settings:\n # if we have a project_id, make sure the setting is for that project since\n # the controller can be scoped for multiple projects\n if (\n project_id is not None\n and setting.scope_type == NotificationScopeEnum.PROJECT.value\n ):\n if setting.scope_identifier != project_id:\n continue\n # sort the settings by scope type, with the most specific scope last so we override with the most specific value\n most_specific_recipient_providers[NotificationSettingEnum(setting.type)][\n ExternalProviderEnum(setting.provider).value\n ] = NotificationSettingsOptionEnum(setting.value)\n\n # if we have no settings for this user, use the defaults\n for type in NotificationSettingEnum:\n for provider_str in PERSONAL_NOTIFICATION_PROVIDERS:\n provider = ExternalProviderEnum(provider_str)\n if provider_str not in most_specific_recipient_providers[type]:\n # TODO(jangjodi): Remove this once the flag is removed\n if recipient_is_team(recipient) and (not has_team_workflow):\n most_specific_recipient_providers[type][\n provider_str\n ] = NotificationSettingsOptionEnum.NEVER\n else:\n most_specific_recipient_providers[type][\n provider_str\n ] = get_default_for_provider(type, provider)\n\n return most_specific_setting_providers", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def prefetch_related_objects(model_instances, *related_lookups):\n \"\"\"\n Populate prefetched object caches for a list of model instances based on\n the lookups/Prefetch instances given.\n \"\"\"\n if not model_instances:\n return # nothing to do\n\n # We need to be able to dynamically add to the list of prefetch_related\n # lookups that we look up (see below). So we need some book keeping to\n # ensure we don't do duplicate work.\n done_queries = {} # dictionary of things like 'foo__bar': [results]\n\n auto_lookups = set() # we add to this as we go through.\n followed_descriptors = set() # recursion protection\n\n all_lookups = normalize_prefetch_lookups(reversed(related_lookups))\n while all_lookups:\n lookup = all_lookups.pop()\n if lookup.prefetch_to in done_queries:\n if lookup.queryset is not None:\n raise ValueError(\n \"'%s' lookup was already seen with a different queryset. \"\n \"You may need to adjust the ordering of your lookups.\"\n % lookup.prefetch_to\n )\n\n continue\n\n # Top level, the list of objects to decorate is the result cache\n # from the primary QuerySet. It won't be for deeper levels.\n obj_list = model_instances\n\n through_attrs = lookup.prefetch_through.split(LOOKUP_SEP)\n for level, through_attr in enumerate(through_attrs):\n # Prepare main instances\n if not obj_list:\n break\n\n prefetch_to = lookup.get_current_prefetch_to(level)\n if prefetch_to in done_queries:\n # Skip any prefetching, and any object preparation\n obj_list = done_queries[prefetch_to]\n continue\n\n # Prepare objects:\n good_objects = True\n for obj in obj_list:\n # Since prefetching can re-use instances, it is possible to have\n # the same instance multiple times in obj_list, so obj might\n # already be prepared.\n if not hasattr(obj, \"_prefetched_objects_cache\"):\n try:\n obj._prefetched_objects_cache = {}\n except (AttributeError, TypeError):\n # Must be an immutable object from\n # values_list(flat=True), for example (TypeError) or\n # a QuerySet subclass that isn't returning Model\n # instances (AttributeError), either in Django or a 3rd\n # party. prefetch_related() doesn't make sense, so quit.\n good_objects = False\n break\n if not good_objects:\n break\n\n # Descend down tree\n\n # We assume that objects retrieved are homogeneous (which is the premise\n # of prefetch_related), so what applies to first object applies to all.\n first_obj = obj_list[0]\n to_attr = lookup.get_current_to_attr(level)[0]\n prefetcher, descriptor, attr_found, is_fetched = get_prefetcher(\n first_obj, through_attr, to_attr\n )\n\n if not attr_found:\n raise AttributeError(\n \"Cannot find '%s' on %s object, '%s' is an invalid \"\n \"parameter to prefetch_related()\"\n % (\n through_attr,\n first_obj.__class__.__name__,\n lookup.prefetch_through,\n )\n )\n\n if level == len(through_attrs) - 1 and prefetcher is None:\n # Last one, this *must* resolve to something that supports\n # prefetching, otherwise there is no point adding it and the\n # developer asking for it has made a mistake.\n raise ValueError(\n \"'%s' does not resolve to an item that supports \"\n \"prefetching - this is an invalid parameter to \"\n \"prefetch_related().\" % lookup.prefetch_through\n )\n\n obj_to_fetch = None\n if prefetcher is not None:\n obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)]\n\n if obj_to_fetch:\n obj_list, additional_lookups = prefetch_one_level(\n obj_to_fetch,\n prefetcher,\n lookup,\n level,\n )\n # We need to ensure we don't keep adding lookups from the\n # same relationships to stop infinite recursion. So, if we\n # are already on an automatically added lookup, don't add\n # the new lookups from relationships we've seen already.\n if not (\n prefetch_to in done_queries\n and lookup in auto_lookups\n and descriptor in followed_descriptors\n ):\n done_queries[prefetch_to] = obj_list\n new_lookups = normalize_prefetch_lookups(\n reversed(additional_lookups), prefetch_to\n )\n auto_lookups.update(new_lookups)\n all_lookups.extend(new_lookups)\n followed_descriptors.add(descriptor)\n else:\n # Either a singly related object that has already been fetched\n # (e.g. via select_related), or hopefully some other property\n # that doesn't support prefetching but needs to be traversed.\n\n # We replace the current list of parent objects with the list\n # of related objects, filtering out empty or missing values so\n # that we can continue with nullable or reverse relations.\n new_obj_list = []\n for obj in obj_list:\n if through_attr in getattr(obj, \"_prefetched_objects_cache\", ()):\n # If related objects have been prefetched, use the\n # cache rather than the object's through_attr.\n new_obj = list(obj._prefetched_objects_cache.get(through_attr))\n else:\n try:\n new_obj = getattr(obj, through_attr)\n except exceptions.ObjectDoesNotExist:\n continue\n if new_obj is None:\n continue\n # We special-case `list` rather than something more generic\n # like `Iterable` because we don't want to accidentally match\n # user models that define __iter__.\n if isinstance(new_obj, list):\n new_obj_list.extend(new_obj)\n else:\n new_obj_list.append(new_obj)\n obj_list = new_obj_list", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def createConfig(self):\n\t\tself.InterfaceEntry = None\n\t\tself.dhcpEntry = None\n\t\tself.gatewayEntry = None\n\t\tself.DNSConfigEntry = None\n\t\tself.hiddenSSID = None\n\t\tself.wlanSSID = None\n\t\tself.encryption = None\n\t\tself.encryptionType = None\n\t\tself.encryptionKey = None\n\t\tself.encryptionlist = None\n\t\tself.weplist = None\n\t\tself.wsconfig = None\n\t\tself.default = None\n\t\tself.primaryDNSEntry = None\n\t\tself.secondaryDNSEntry = None\n\t\tself.onlyWakeOnWiFi = False\n\t\tself.WakeOnWiFiEntry = False\n\t\tself.ipTypeEntry = None\n\t\tif iNetwork.isWirelessInterface(self.iface):\n\t\t\tdriver = iNetwork.detectWlanModule(self.iface)\n\t\t\tif driver in (\"brcm-wl\", ):\n\t\t\t\tfrom Plugins.SystemPlugins.WirelessLan.Wlan import brcmWLConfig\n\t\t\t\tself.ws = brcmWLConfig()\n\t\t\telse:\n\t\t\t\tfrom Plugins.SystemPlugins.WirelessLan.Wlan import wpaSupplicant\n\t\t\t\tself.ws = wpaSupplicant()\n\t\t\tself.encryptionlist = []\n\t\t\tself.encryptionlist.append((\"Unencrypted\", _(\"Unencrypted\")))\n\t\t\tself.encryptionlist.append((\"WEP\", _(\"WEP\")))\n\t\t\tself.encryptionlist.append((\"WPA\", _(\"WPA\")))\n\t\t\tif not exists(f\"/tmp/bcm/{self.iface}\"):\n\t\t\t\tself.encryptionlist.append((\"WPA/WPA2\", _(\"WPA or WPA2\")))\n\t\t\tself.encryptionlist.append((\"WPA2\", _(\"WPA2\")))\n\t\t\tself.weplist = []\n\t\t\tself.weplist.append(\"ASCII\")\n\t\t\tself.weplist.append(\"HEX\")\n\t\t\tself.wsconfig = self.ws.loadConfig(self.iface)\n\t\t\tif self.essid is None:\n\t\t\t\tself.essid = self.wsconfig[\"ssid\"]\n\t\t\tif iNetwork.canWakeOnWiFi(self.iface):\n\t\t\t\tiface_file = \"/etc/network/interfaces\"\n\t\t\t\tdefault_v = False\n\t\t\t\tif exists(iface_file):\n\t\t\t\t\twith open(iface_file) as f:\n\t\t\t\t\t\toutput = f.read()\n\t\t\t\t\tsearch_str = f\"#only WakeOnWiFi {self.iface}\"\n\t\t\t\t\tif output.find(search_str) >= 0:\n\t\t\t\t\t\tdefault_v = True\n\t\t\t\tself.onlyWakeOnWiFi = NoSave(ConfigYesNo(default=default_v))\n\t\t\tconfig.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default=self.wsconfig[\"hiddenessid\"]))\n\t\t\tconfig.plugins.wlan.essid = NoSave(ConfigText(default=self.essid, visible_width=50, fixed_size=False))\n\t\t\tconfig.plugins.wlan.encryption = NoSave(ConfigSelection(self.encryptionlist, default=self.wsconfig[\"encryption\"]))\n\t\t\tconfig.plugins.wlan.wepkeytype = NoSave(ConfigSelection(self.weplist, default=self.wsconfig[\"wepkeytype\"]))\n\t\t\tconfig.plugins.wlan.psk = NoSave(ConfigPassword(default=self.wsconfig[\"key\"], visible_width=50, fixed_size=False))\n\t\tself.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, \"up\") or False))\n\t\tself.dhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, \"dhcp\") or False))\n\t\tself.ipConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, \"ip\")) or [0, 0, 0, 0])\n\t\tself.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, \"netmask\") or [255, 0, 0, 0]))\n\t\tif iNetwork.getAdapterAttribute(self.iface, \"gateway\"):\n\t\t\tself.dhcpdefault = True\n\t\telse:\n\t\t\tself.dhcpdefault = False\n\t\tself.hasGatewayConfigEntry = NoSave(ConfigYesNo(default=self.dhcpdefault or False))\n\t\tself.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, \"gateway\") or [0, 0, 0, 0]))\n\t\tnameserver = (iNetwork.getNameserverList() + [[0, 0, 0, 0]] * 2)[0:2]\n\t\tself.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))\n\t\tself.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))\n\t\tself.ipTypeConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, \"ipv6\") or False))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def fine_grained_increment_follow_imports(\n self, sources: list[BuildSource], explicit_export_types: bool = False\n ) -> list[str]:\n \"\"\"Like fine_grained_increment, but follow imports.\"\"\"\n t0 = time.time()\n\n # TODO: Support file events\n\n assert self.fine_grained_manager is not None\n fine_grained_manager = self.fine_grained_manager\n graph = fine_grained_manager.graph\n manager = fine_grained_manager.manager\n\n orig_modules = list(graph.keys())\n\n self.update_sources(sources)\n changed_paths = self.fswatcher.find_changed()\n manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir)\n\n t1 = time.time()\n manager.log(f\"fine-grained increment: find_changed: {t1 - t0:.3f}s\")\n\n seen = {source.module for source in sources}\n\n # Find changed modules reachable from roots (or in roots) already in graph.\n changed, new_files = self.find_reachable_changed_modules(\n sources, graph, seen, changed_paths\n )\n if explicit_export_types:\n # Same as in fine_grained_increment().\n add_all_sources_to_changed(sources, changed)\n sources.extend(new_files)\n\n # Process changes directly reachable from roots.\n messages = fine_grained_manager.update(changed, [], followed=True)\n\n # Follow deps from changed modules (still within graph).\n worklist = changed.copy()\n while worklist:\n module = worklist.pop()\n if module[0] not in graph:\n continue\n sources2 = self.direct_imports(module, graph)\n # Filter anything already seen before. This prevents\n # infinite looping if there are any self edges. (Self\n # edges are maybe a bug, but...)\n sources2 = [source for source in sources2 if source.module not in seen]\n changed, new_files = self.find_reachable_changed_modules(\n sources2, graph, seen, changed_paths\n )\n self.update_sources(new_files)\n messages = fine_grained_manager.update(changed, [], followed=True)\n worklist.extend(changed)\n\n t2 = time.time()\n\n def refresh_file(module: str, path: str) -> list[str]:\n return fine_grained_manager.update([(module, path)], [], followed=True)\n\n for module_id, state in list(graph.items()):\n new_messages = refresh_suppressed_submodules(\n module_id, state.path, fine_grained_manager.deps, graph, self.fscache, refresh_file\n )\n if new_messages is not None:\n messages = new_messages\n\n t3 = time.time()\n\n # There may be new files that became available, currently treated as\n # suppressed imports. Process them.\n while True:\n new_unsuppressed = self.find_added_suppressed(graph, seen, manager.search_paths)\n if not new_unsuppressed:\n break\n new_files = [BuildSource(mod[1], mod[0], followed=True) for mod in new_unsuppressed]\n sources.extend(new_files)\n self.update_sources(new_files)\n messages = fine_grained_manager.update(new_unsuppressed, [], followed=True)\n\n for module_id, path in new_unsuppressed:\n new_messages = refresh_suppressed_submodules(\n module_id, path, fine_grained_manager.deps, graph, self.fscache, refresh_file\n )\n if new_messages is not None:\n messages = new_messages\n\n t4 = time.time()\n\n # Find all original modules in graph that were not reached -- they are deleted.\n to_delete = []\n for module_id in orig_modules:\n if module_id not in graph:\n continue\n if module_id not in seen:\n module_path = graph[module_id].path\n assert module_path is not None\n to_delete.append((module_id, module_path))\n if to_delete:\n messages = fine_grained_manager.update([], to_delete)\n\n fix_module_deps(graph)\n\n self.previous_sources = find_all_sources_in_build(graph)\n self.update_sources(self.previous_sources)\n\n # Store current file state as side effect\n self.fswatcher.find_changed()\n\n t5 = time.time()\n\n manager.log(f\"fine-grained increment: update: {t5 - t1:.3f}s\")\n manager.add_stats(\n find_changes_time=t1 - t0,\n fg_update_time=t2 - t1,\n refresh_suppressed_time=t3 - t2,\n find_added_supressed_time=t4 - t3,\n cleanup_time=t5 - t4,\n )\n\n return messages", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def __setattr__(self, key, value):\n self._validate_value(key, value)\n common = object.__getattribute__(self, 'common_keys')\n mapped = object.__getattribute__(self, 'mapped_keys')\n if key in mapped:\n lk, _ = mapped[key]\n if self._legacy:\n if lk is None:\n raise NotImplementedError\n self._legacy[lk] = value\n elif key not in ('commands', 'exports', 'modules', 'namespaces',\n 'classifiers'):\n self._data[key] = value\n else:\n # special cases for PEP 459\n d = self._data.setdefault('extensions', {})\n if key == 'commands':\n d['python.commands'] = value\n elif key == 'classifiers':\n d = d.setdefault('python.details', {})\n d[key] = value\n else:\n d = d.setdefault('python.exports', {})\n d[key] = value\n elif key not in common:\n object.__setattr__(self, key, value)\n else:\n if key == 'keywords':\n if isinstance(value, string_types):\n value = value.strip()\n if value:\n value = value.split()\n else:\n value = []\n if self._legacy:\n self._legacy[key] = value\n else:\n self._data[key] = value", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _write_variable_int(self, item, value, buffer):\n # QUIC encoding is currently assumed for individual variable sized integers\n # see https://datatracker.ietf.org/doc/html/rfc9000#name-variable-length-integer-enc\n\n # Calculate current bit size so we can preserve bytes after the item\n length_item_value = self.packet.read(item.variable_bit_size[\"length_item_name\"], \"CONVERTED\")\n match length_item_value:\n case 0:\n current_bit_size = 6\n case 1:\n current_bit_size = 14\n case 2:\n current_bit_size = 30\n case 3:\n current_bit_size = 62\n case _:\n raise AttributeError(\n f\"Value {item.variable_bit_size['length_item_name']} has unknown QUIC bit size encoding: {length_item_value}\"\n )\n\n if item.data_type == \"UINT\":\n if value <= 63:\n # Length = 0, value up to 6-bits\n new_bit_size = 6\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 0)\n elif value <= 16383:\n # Length = 1, value up to 14-bits\n new_bit_size = 14\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 1)\n elif value <= 1073741823:\n # Length = 2, value up to 30-bits\n new_bit_size = 30\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 2)\n else:\n # Length = 3, value up to 62-bits\n new_bit_size = 62\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 3)\n else:\n if value <= 31 and value >= -32:\n # Length = 0, value up to 6-bits\n new_bit_size = 6\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 0)\n elif value <= 8191 and value >= -8192:\n # Length = 1, value up to 14-bits\n new_bit_size = 14\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 1)\n elif value <= 536870911 and value >= -536870912:\n # Length = 2, value up to 30-bits\n new_bit_size = 30\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 2)\n else:\n # Length = 3, value up to 62-bits\n new_bit_size = 62\n item.bit_size = new_bit_size\n self.packet.write(item.variable_bit_size[\"length_item_name\"], 3)\n\n # Later items need their bit_offset adjusted by the change in this item\n adjustment = new_bit_size - current_bit_size\n adjust_bytes = int(adjustment / 8)\n item_offset = int(item.bit_offset / 8)\n if adjust_bytes > 0:\n original_length = len(buffer)\n # Add extra bytes because we're adjusting larger\n buffer += BinaryAccessor.ZERO_STRING * adjust_bytes\n # We added bytes to the end so now we have to shift the buffer over\n # We copy from the original offset with the original length\n # to the new shifted offset all the way to the end of the buffer\n buffer[(item_offset + adjust_bytes) :] = buffer[item_offset:original_length]\n elif adjust_bytes < 0:\n # Remove extra bytes because we're adjusting smaller\n del buffer[item_offset + 1 : item_offset + 1 - adjust_bytes]\n\n return adjustment", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def ValidateSampleList1(self, sampleList):\n if len(sampleList) < 1:\n myDebugPrint3AndException(\n \"PhactoriStructuredGridSampler:ValidateSampleList1\\n\" \\\n \"list of samples must have at least one entry\\n\")\n\n for oneSample in sampleList:\n sampleBlockName = oneSample[0]\n sampleBlockType = oneSample[1]\n validType = False\n if sampleBlockType == \"imax\":\n validType = True\n if sampleBlockType == \"imin\":\n validType = True\n if sampleBlockType == \"jmax\":\n validType = True\n if sampleBlockType == \"jmin\":\n validType = True\n if sampleBlockType == \"kmax\":\n validType = True\n if sampleBlockType == \"kmin\":\n validType = True\n if validType != True:\n myDebugPrint3AndException(\n \"PhactoriStructuredGridSampler:ValidateSampleList1\\n\" \\\n \"invalid sample type: \" + str(sampleBlockType) + \"\\n\" \\\n \"must be 'imin' 'imax' 'jmin' 'jmax' 'kmin' or 'kmax'\\n\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def finished(self, gotoStep=None, *args, **kwargs):\n\t\tprint(\"[Wizard] Running finished() code.\")\n\t\tcurrStep = self.currStep\n\t\tif self.updateValues not in self.onShown:\n\t\t\tself.onShown.append(self.updateValues)\n\t\tif self.showConfig:\n\t\t\tif self.wizard[currStep][\"config\"][\"type\"] == \"dynamic\":\n\t\t\t\teval(\"self.%s\" % self.wizard[currStep][\"config\"][\"evaluation\"])()\n\t\tif self.showList:\n\t\t\tif len(self.wizard[currStep][\"evaluatedList\"]) > 0:\n\t\t\t\t# print(\"[Wizard] current: '%s'.\" % self[\"list\"].current)\n\t\t\t\tnextStep = self[\"list\"].current[1]\n\t\t\t\tif \"listEvaluation\" in self.wizard[currStep]:\n\t\t\t\t\texec(\"self.%s('%s')\" % (self.wizard[self.currStep][\"listEvaluation\"], nextStep))\n\t\t\t\telse:\n\t\t\t\t\tself.currStep = self.findStepByName(nextStep)\n\t\t# printNow = True\n\t\tif (currStep == self.numSteps and self.wizard[currStep][\"nextStep\"] is None) or self.wizard[currStep][\"name\"] == \"end\": # wizard finished\n\t\t\t# print(\"[Wizard] wizard finished\")\n\t\t\tself.markDone()\n\t\t\tself.exit()\n\t\telse:\n\t\t\tself.codeAfter = True\n\t\t\tself.runCode(self.wizard[currStep][\"codeAfter\"])\n\t\t\tself.prevStep = currStep\n\t\t\tself.gotoStep = gotoStep\n\t\t\tif not self.runCode(self.wizard[currStep][\"codeAfterAsync\"]):\n\t\t\t\tself.afterAsyncCode()\n\t\t\telse:\n\t\t\t\tif self.updateValues in self.onShown:\n\t\t\t\t\tself.onShown.remove(self.updateValues)\n\t\t# if printNow:\n\t\t# \tprint(\"[Wizard] Now: '%s'.\" % self.currStep)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def removeAlternativeServices(self):\n\t\tcur_service = ServiceReference(self.getCurrentSelection())\n\t\tend = self.atEnd()\n\t\troot = self.getRoot()\n\t\tcur_root = root and ServiceReference(root)\n\t\tlist = cur_service.list()\n\t\tfirst_in_alternative = list and list.getNext()\n\t\tif first_in_alternative:\n\t\t\tedit_root = cur_root and cur_root.list().startEdit()\n\t\t\tif edit_root:\n\t\t\t\tif not edit_root.addService(first_in_alternative, cur_service.ref):\n\t\t\t\t\tself.servicelist.addService(first_in_alternative, True)\n\t\t\t\t\tif cur_service.ref.toString() == self.lastservice.value:\n\t\t\t\t\t\tself.saveChannel(first_in_alternative)\n\t\t\t\t\tif self.startServiceRef and cur_service.ref == self.startServiceRef:\n\t\t\t\t\t\tself.startServiceRef = first_in_alternative\n\t\t\t\telse:\n\t\t\t\t\tprint(\"[ChannelSelection] Couldn't add first alternative service to current root!\")\n\t\t\telse:\n\t\t\t\tprint(\"[ChannelSelection] Couldn't edit current root!\")\n\t\telse:\n\t\t\tprint(\"[ChannelSelection] Remove empty alternative list!\")\n\t\tself.removeBouquet()\n\t\tif not end:\n\t\t\tself.servicelist.goLineUp()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def apply_dynamic_class_hook(self, s: AssignmentStmt) -> None:\n if not isinstance(s.rvalue, CallExpr):\n return\n fname = \"\"\n call = s.rvalue\n while True:\n if isinstance(call.callee, RefExpr):\n fname = call.callee.fullname\n # check if method call\n if not fname and isinstance(call.callee, MemberExpr):\n callee_expr = call.callee.expr\n if isinstance(callee_expr, RefExpr) and callee_expr.fullname:\n method_name = call.callee.name\n fname = callee_expr.fullname + \".\" + method_name\n elif (\n isinstance(callee_expr, IndexExpr)\n and isinstance(callee_expr.base, RefExpr)\n and isinstance(callee_expr.analyzed, TypeApplication)\n ):\n method_name = call.callee.name\n fname = callee_expr.base.fullname + \".\" + method_name\n elif isinstance(callee_expr, CallExpr):\n # check if chain call\n call = callee_expr\n continue\n break\n if not fname:\n return\n hook = self.plugin.get_dynamic_class_hook(fname)\n if not hook:\n return\n for lval in s.lvalues:\n if not isinstance(lval, NameExpr):\n continue\n hook(DynamicClassDefContext(call, lval.name, self))", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "async def return_presentation(\n self,\n pres_ex_record: Union[V10PresentationExchange, V20PresExRecord],\n requested_credentials: Optional[dict] = None,\n ) -> dict:\n \"\"\"Return Indy proof request as dict.\"\"\"\n # Get all credentials for this presentation\n holder = self._profile.inject(IndyHolder)\n credentials = {}\n requested_credentials = requested_credentials or {}\n\n # extract credential ids and non_revoked\n requested_referents = {}\n if isinstance(pres_ex_record, V20PresExRecord):\n proof_request = pres_ex_record.pres_request.attachment(\n V20PresFormat.Format.INDY\n )\n elif isinstance(pres_ex_record, V10PresentationExchange):\n proof_request = pres_ex_record._presentation_request.ser\n non_revoc_intervals = indy_proof_req2non_revoc_intervals(proof_request)\n attr_creds = requested_credentials.get(\"requested_attributes\", {})\n req_attrs = proof_request.get(\"requested_attributes\", {})\n for reft in attr_creds:\n requested_referents[reft] = {\"cred_id\": attr_creds[reft][\"cred_id\"]}\n if reft in req_attrs and reft in non_revoc_intervals:\n requested_referents[reft][\"non_revoked\"] = non_revoc_intervals[reft]\n pred_creds = requested_credentials.get(\"requested_predicates\", {})\n req_preds = proof_request.get(\"requested_predicates\", {})\n for reft in pred_creds:\n requested_referents[reft] = {\"cred_id\": pred_creds[reft][\"cred_id\"]}\n if reft in req_preds and reft in non_revoc_intervals:\n requested_referents[reft][\"non_revoked\"] = non_revoc_intervals[reft]\n # extract mapping of presentation referents to credential ids\n for reft in requested_referents:\n credential_id = requested_referents[reft][\"cred_id\"]\n if credential_id not in credentials:\n credentials[credential_id] = json.loads(\n await holder.get_credential(credential_id)\n )\n # remove any timestamps that cannot correspond to non-revoc intervals\n for r in (\"requested_attributes\", \"requested_predicates\"):\n for reft, req_item in requested_credentials.get(r, {}).items():\n if not credentials[req_item[\"cred_id\"]].get(\n \"rev_reg_id\"\n ) and req_item.pop(\"timestamp\", None):\n LOGGER.info(\n f\"Removed superfluous timestamp from requested_credentials {r} \"\n f\"{reft} for non-revocable credential {req_item['cred_id']}\"\n )\n # Get all schemas, credential definitions, and revocation registries in use\n schemas = {}\n cred_defs = {}\n revocation_registries = {}\n\n for credential in credentials.values():\n schema_id = credential[\"schema_id\"]\n multitenant_mgr = self._profile.inject_or(BaseMultitenantManager)\n if multitenant_mgr:\n ledger_exec_inst = IndyLedgerRequestsExecutor(self._profile)\n else:\n ledger_exec_inst = self._profile.inject(IndyLedgerRequestsExecutor)\n ledger = (\n await ledger_exec_inst.get_ledger_for_identifier(\n schema_id,\n txn_record_type=GET_SCHEMA,\n )\n )[1]\n async with ledger:\n if schema_id not in schemas:\n schemas[schema_id] = await ledger.get_schema(schema_id)\n cred_def_id = credential[\"cred_def_id\"]\n if cred_def_id not in cred_defs:\n cred_defs[cred_def_id] = await ledger.get_credential_definition(\n cred_def_id\n )\n if credential.get(\"rev_reg_id\"):\n revocation_registry_id = credential[\"rev_reg_id\"]\n if revocation_registry_id not in revocation_registries:\n revocation_registries[revocation_registry_id] = (\n RevocationRegistry.from_definition(\n await ledger.get_revoc_reg_def(revocation_registry_id),\n True,\n )\n )\n # Get delta with non-revocation interval defined in \"non_revoked\"\n # of the presentation request or attributes\n epoch_now = int(time.time())\n revoc_reg_deltas = {}\n for precis in requested_referents.values(): # cred_id, non-revoc interval\n credential_id = precis[\"cred_id\"]\n if not credentials[credential_id].get(\"rev_reg_id\"):\n continue\n if \"timestamp\" in precis:\n continue\n rev_reg_id = credentials[credential_id][\"rev_reg_id\"]\n multitenant_mgr = self._profile.inject_or(BaseMultitenantManager)\n if multitenant_mgr:\n ledger_exec_inst = IndyLedgerRequestsExecutor(self._profile)\n else:\n ledger_exec_inst = self._profile.inject(IndyLedgerRequestsExecutor)\n ledger = (\n await ledger_exec_inst.get_ledger_for_identifier(\n rev_reg_id,\n txn_record_type=GET_REVOC_REG_DELTA,\n )\n )[1]\n async with ledger:\n reft_non_revoc_interval = precis.get(\"non_revoked\")\n if reft_non_revoc_interval:\n key = (\n f\"{rev_reg_id}_\"\n f\"{reft_non_revoc_interval.get('from', 0)}_\"\n f\"{reft_non_revoc_interval.get('to', epoch_now)}\"\n )\n if key not in revoc_reg_deltas:\n (delta, delta_timestamp) = await ledger.get_revoc_reg_delta(\n rev_reg_id,\n reft_non_revoc_interval.get(\"from\", 0),\n reft_non_revoc_interval.get(\"to\", epoch_now),\n )\n revoc_reg_deltas[key] = (\n rev_reg_id,\n credential_id,\n delta,\n delta_timestamp,\n )\n for stamp_me in requested_referents.values():\n # often one cred satisfies many requested attrs/preds\n if stamp_me[\"cred_id\"] == credential_id:\n stamp_me[\"timestamp\"] = revoc_reg_deltas[key][3]\n # Get revocation states to prove non-revoked\n revocation_states = {}\n for (\n rev_reg_id,\n credential_id,\n delta,\n delta_timestamp,\n ) in revoc_reg_deltas.values():\n if rev_reg_id not in revocation_states:\n revocation_states[rev_reg_id] = {}\n rev_reg = revocation_registries[rev_reg_id]\n tails_local_path = await rev_reg.get_or_fetch_local_tails_path()\n try:\n revocation_states[rev_reg_id][delta_timestamp] = json.loads(\n await holder.create_revocation_state(\n credentials[credential_id][\"cred_rev_id\"],\n rev_reg.reg_def,\n delta,\n delta_timestamp,\n tails_local_path,\n )\n )\n except IndyHolderError as e:\n LOGGER.error(\n f\"Failed to create revocation state: {e.error_code}, {e.message}\"\n )\n raise e\n for referent, precis in requested_referents.items():\n if \"timestamp\" not in precis:\n continue\n if referent in requested_credentials[\"requested_attributes\"]:\n requested_credentials[\"requested_attributes\"][referent][\"timestamp\"] = (\n precis[\"timestamp\"]\n )\n if referent in requested_credentials[\"requested_predicates\"]:\n requested_credentials[\"requested_predicates\"][referent][\"timestamp\"] = (\n precis[\"timestamp\"]\n )\n indy_proof_json = await holder.create_presentation(\n proof_request,\n requested_credentials,\n schemas,\n cred_defs,\n revocation_states,\n )\n indy_proof = json.loads(indy_proof_json)\n return indy_proof", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def post(self, request, *args, **kwargs):\n import stripe\n from temba.orgs.models import Org, TopUp\n\n # stripe delivers a JSON payload\n stripe_data = json.loads(request.body)\n\n # but we can't trust just any response, so lets go look up this event\n stripe.api_key = get_stripe_credentials()[1]\n event = stripe.Event.retrieve(stripe_data[\"id\"])\n\n if not event:\n return HttpResponse(\"Ignored, no event\")\n\n if not event.livemode:\n return HttpResponse(\"Ignored, test event\")\n\n # we only care about invoices being paid or failing\n if event.type == \"charge.succeeded\" or event.type == \"charge.failed\":\n charge = event.data.object\n charge_date = datetime.fromtimestamp(charge.created)\n description = charge.description\n amount = \"$%s\" % (Decimal(charge.amount) / Decimal(100)).quantize(Decimal(\".01\"))\n\n # look up our customer\n customer = stripe.Customer.retrieve(charge.customer)\n\n # and our org\n org = Org.objects.filter(stripe_customer=customer.id).first()\n if not org:\n return HttpResponse(\"Ignored, no org for customer\")\n\n # look up the topup that matches this charge\n topup = TopUp.objects.filter(stripe_charge=charge.id).first()\n if topup and event.type == \"charge.failed\":\n topup.rollback()\n topup.save()\n\n # we know this org, trigger an event for a payment succeeding\n if org.administrators.all():\n if event.type == \"charge_succeeded\":\n track = \"temba.charge_succeeded\"\n else:\n track = \"temba.charge_failed\"\n\n context = dict(\n description=description,\n invoice_id=charge.id,\n invoice_date=charge_date.strftime(\"%b %e, %Y\"),\n amount=amount,\n org=org.name,\n )\n\n if getattr(charge, \"card\", None):\n context[\"cc_last4\"] = charge.card.last4\n context[\"cc_type\"] = charge.card.type\n context[\"cc_name\"] = charge.card.name\n\n else:\n context[\"cc_type\"] = \"bitcoin\"\n context[\"cc_name\"] = charge.source.bitcoin.address\n\n admin = org.administrators.all().first()\n\n analytics.track(admin, track, context)\n return HttpResponse(\"Event '%s': %s\" % (track, context))\n\n # empty response, 200 lets Stripe know we handled it\n return HttpResponse(\"Ignored, uninteresting event\")", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def function (self):\n instances = []\n signals = []\n\n for frame in self.frames:\n name = frame_name(frame)\n if name == \"signal_emit_unlocked_R\":\n self.read_object (frame, \"instance\", instances)\n node = self.read_var (frame, \"node\")\n if node:\n signal = node[\"name\"].string()\n signal = self.get_detailed_signal_from_frame(frame, signal)\n self.append(signals, signal)\n\n if name == \"g_signal_emitv\":\n instance_and_params = self.read_var (frame, \"instance_and_params\")\n if instance_and_params:\n instance = instance_and_params[0][\"v_pointer\"].cast (gdb.Type(\"GObject\").pointer())\n self.append (instances, instance)\n id = self.read_var (frame, \"signal_id\")\n signal = get_signal_name (id)\n if signal:\n signal = self.get_detailed_signal_from_frame(frame, signal)\n self.append (signals, signal)\n\n if name == \"g_signal_emit_valist\" or name == \"g_signal_emit\":\n self.read_object (frame, \"instance\", instances)\n id = self.read_var (frame, \"signal_id\")\n signal = get_signal_name (id)\n if signal:\n signal = self.get_detailed_signal_from_frame(frame, signal)\n self.append (signals, signal)\n\n if name == \"g_signal_emit_by_name\":\n self.read_object (frame, \"instance\", instances)\n self.read_var (frame, \"detailed_signal\", signals)\n break\n\n instance = self.or_join_array (instances)\n signal = self.or_join_array (signals)\n\n return \"<emit signal %s on instance %s>\" % (signal, instance)", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-dk", "language": "python"} {"function": "@classmethod\n def check_alerts(cls):\n from temba.channels.types.android import AndroidType\n from temba.msgs.models import Msg\n\n thirty_minutes_ago = timezone.now() - timedelta(minutes=30)\n\n # end any alerts that no longer seem valid\n for alert in Alert.objects.filter(alert_type=cls.TYPE_DISCONNECTED, ended_on=None):\n # if we've seen the channel since this alert went out, then clear the alert\n if alert.channel.last_seen > alert.created_on:\n alert.ended_on = alert.channel.last_seen\n alert.save()\n alert.send_resolved()\n\n for channel in (\n Channel.objects.filter(channel_type=AndroidType.code, is_active=True)\n .exclude(org=None)\n .exclude(last_seen__gte=thirty_minutes_ago)\n ):\n # have we already sent an alert for this channel\n if not Alert.objects.filter(channel=channel, alert_type=cls.TYPE_DISCONNECTED, ended_on=None):\n cls.create_and_send(channel, cls.TYPE_DISCONNECTED)\n\n day_ago = timezone.now() - timedelta(days=1)\n six_hours_ago = timezone.now() - timedelta(hours=6)\n\n # end any sms alerts that are open and no longer seem valid\n for alert in Alert.objects.filter(alert_type=cls.TYPE_SMS, ended_on=None).distinct(\"channel_id\"):\n # are there still queued messages?\n\n if (\n not Msg.objects.filter(\n status__in=[\"Q\", \"P\"], channel_id=alert.channel_id, created_on__lte=thirty_minutes_ago\n )\n .exclude(created_on__lte=day_ago)\n .exists()\n ):\n Alert.objects.filter(alert_type=cls.TYPE_SMS, ended_on=None, channel_id=alert.channel_id).update(\n ended_on=timezone.now()\n )\n\n # now look for channels that have many unsent messages\n queued_messages = (\n Msg.objects.filter(status__in=[\"Q\", \"P\"])\n .order_by(\"channel\", \"created_on\")\n .exclude(created_on__gte=thirty_minutes_ago)\n .exclude(created_on__lte=day_ago)\n .exclude(channel=None)\n .values(\"channel\")\n .annotate(latest_queued=Max(\"created_on\"))\n )\n sent_messages = (\n Msg.objects.filter(status__in=[\"S\", \"D\"])\n .exclude(created_on__lte=day_ago)\n .exclude(channel=None)\n .order_by(\"channel\", \"sent_on\")\n .values(\"channel\")\n .annotate(latest_sent=Max(\"sent_on\"))\n )\n\n channels = dict()\n for queued in queued_messages:\n if queued[\"channel\"]:\n channels[queued[\"channel\"]] = dict(queued=queued[\"latest_queued\"], sent=None)\n\n for sent in sent_messages:\n existing = channels.get(sent[\"channel\"], dict(queued=None))\n existing[\"sent\"] = sent[\"latest_sent\"]\n\n for channel_id, value in channels.items():\n # we haven't sent any messages in the past six hours\n if not value[\"sent\"] or value[\"sent\"] < six_hours_ago:\n channel = Channel.objects.get(pk=channel_id)\n\n # never alert on channels that have no org\n if channel.org is None: # pragma: no cover\n continue\n\n # if we haven't sent an alert in the past six ours\n if not Alert.objects.filter(channel=channel).filter(Q(created_on__gt=six_hours_ago)).exists():\n cls.create_and_send(channel, cls.TYPE_SMS)", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def check_simple_assignment(\n self,\n lvalue_type: Type | None,\n rvalue: Expression,\n context: Context,\n msg: ErrorMessage = message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,\n lvalue_name: str = \"variable\",\n rvalue_name: str = \"expression\",\n *,\n notes: list[str] | None = None,\n ) -> Type:\n if self.is_stub and isinstance(rvalue, EllipsisExpr):\n # '...' is always a valid initializer in a stub.\n return AnyType(TypeOfAny.special_form)\n else:\n always_allow_any = lvalue_type is not None and not isinstance(\n get_proper_type(lvalue_type), AnyType\n )\n rvalue_type = self.expr_checker.accept(\n rvalue, lvalue_type, always_allow_any=always_allow_any\n )\n if (\n isinstance(get_proper_type(lvalue_type), UnionType)\n # Skip literal types, as they have special logic (for better errors).\n and not isinstance(get_proper_type(rvalue_type), LiteralType)\n and not self.simple_rvalue(rvalue)\n ):\n # Try re-inferring r.h.s. in empty context, and use that if it\n # results in a narrower type. We don't do this always because this\n # may cause some perf impact, plus we want to partially preserve\n # the old behavior. This helps with various practical examples, see\n # e.g. testOptionalTypeNarrowedByGenericCall.\n with self.msg.filter_errors() as local_errors, self.local_type_map() as type_map:\n alt_rvalue_type = self.expr_checker.accept(\n rvalue, None, always_allow_any=always_allow_any\n )\n if (\n not local_errors.has_new_errors()\n # Skip Any type, since it is special cased in binder.\n and not isinstance(get_proper_type(alt_rvalue_type), AnyType)\n and is_valid_inferred_type(alt_rvalue_type)\n and is_proper_subtype(alt_rvalue_type, rvalue_type)\n ):\n rvalue_type = alt_rvalue_type\n self.store_types(type_map)\n if isinstance(rvalue_type, DeletedType):\n self.msg.deleted_as_rvalue(rvalue_type, context)\n if isinstance(lvalue_type, DeletedType):\n self.msg.deleted_as_lvalue(lvalue_type, context)\n elif lvalue_type:\n self.check_subtype(\n # Preserve original aliases for error messages when possible.\n rvalue_type,\n lvalue_type,\n context,\n msg,\n f\"{rvalue_name} has type\",\n f\"{lvalue_name} has type\",\n notes=notes,\n )\n return rvalue_type", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def playService(self, ref, checkParentalControl=True, forceRestart=False, adjust=True, ignoreStreamRelay=False):\n\t\toldref = self.currentlyPlayingServiceOrGroup\n\t\tif ref and oldref and ref == oldref and not forceRestart:\n\t\t\tprint(\"[Navigation] Ignore request to play already running service. (1)\")\n\t\t\treturn 1\n\t\tprint(f\"[Navigation] Playing ref '{ref and ref.toString()}'.\")\n\t\tif exists(\"/proc/stb/lcd/symbol_signal\"):\n\t\t\tsignal = \"1\" if config.lcd.mode.value and ref and \"0:0:0:0:0:0:0:0:0\" not in ref.toString() else \"0\"\n\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_signal\", signal, source=MODULE_NAME)\n\t\tif ref is None:\n\t\t\tself.stopService()\n\t\t\treturn 0\n\t\tfrom Components.ServiceEventTracker import InfoBarCount\n\t\tInfoBarInstance = InfoBarCount == 1 and InfoBar.instance\n\t\tisStreamRelay = False\n\t\tif not checkParentalControl or parentalControl.isServicePlayable(ref, boundFunction(self.playService, checkParentalControl=False, forceRestart=forceRestart, adjust=adjust)):\n\t\t\tif ref.flags & eServiceReference.isGroup:\n\t\t\t\toldref = self.currentlyPlayingServiceReference or eServiceReference()\n\t\t\t\tplayref = getBestPlayableServiceReference(ref, oldref)\n\t\t\t\tif not ignoreStreamRelay:\n\t\t\t\t\tplayref, isStreamRelay = streamrelay.streamrelayChecker(playref)\n\t\t\t\tif not isStreamRelay:\n\t\t\t\t\tplayref, wrappererror = self.serviceHook(playref)\n\t\t\t\t\tif wrappererror:\n\t\t\t\t\t\treturn 1\n\t\t\t\tprint(f\"[Navigation] Playref is '{str(playref)}'.\")\n\t\t\t\tif playref and oldref and playref == oldref and not forceRestart:\n\t\t\t\t\tprint(\"[Navigation] Ignore request to play already running service. (2)\")\n\t\t\t\t\treturn 1\n\t\t\t\tif not playref:\n\t\t\t\t\talternativeref = getBestPlayableServiceReference(ref, eServiceReference(), True)\n\t\t\t\t\tself.stopService()\n\t\t\t\t\tif alternativeref and self.pnav:\n\t\t\t\t\t\tself.currentlyPlayingServiceReference = alternativeref\n\t\t\t\t\t\tself.currentlyPlayingServiceOrGroup = ref\n\t\t\t\t\t\tif self.pnav.playService(alternativeref):\n\t\t\t\t\t\t\tprint(f\"[Navigation] Failed to start '{alternativeref.toString()}'.\")\n\t\t\t\t\t\t\tself.currentlyPlayingServiceReference = None\n\t\t\t\t\t\t\tself.currentlyPlayingServiceOrGroup = None\n\t\t\t\t\t\t\tif oldref and (\"://\" in oldref.getPath() or streamrelay.checkService(oldref)):\n\t\t\t\t\t\t\t\tprint(\"[Navigation] Streaming was active, try again.\") # Use timer to give the stream server the time to deallocate the tuner.\n\t\t\t\t\t\t\t\tself.retryServicePlayTimer = eTimer()\n\t\t\t\t\t\t\t\tself.retryServicePlayTimer.callback.append(boundFunction(self.playService, ref, checkParentalControl, forceRestart, adjust))\n\t\t\t\t\t\t\t\tself.retryServicePlayTimer.start(500, True)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(f\"[Navigation] Alternative ref as simulate is '{alternativeref.toString()}'.\")\n\t\t\t\t\treturn 0\n\t\t\t\telif checkParentalControl and not parentalControl.isServicePlayable(playref, boundFunction(self.playService, checkParentalControl=False)):\n\t\t\t\t\tif self.currentlyPlayingServiceOrGroup and InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent(self.currentlyPlayingServiceOrGroup, adjust):\n\t\t\t\t\t\tself.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent()\n\t\t\t\t\treturn 1\n\t\t\telse:\n\t\t\t\tplayref = ref\n\t\t\tif self.pnav:\n\t\t\t\tif not BoxInfo.getItem(\"FCCactive\"):\n\t\t\t\t\tself.pnav.stopService()\n\t\t\t\telse:\n\t\t\t\t\tself.skipServiceReferenceReset = True\n\t\t\t\tself.currentlyPlayingServiceReference = playref\n\t\t\t\tif not ignoreStreamRelay:\n\t\t\t\t\tplayref, isStreamRelay = streamrelay.streamrelayChecker(playref)\n\t\t\t\tif not isStreamRelay:\n\t\t\t\t\tplayref, wrappererror = self.serviceHook(playref)\n\t\t\t\t\tif wrappererror:\n\t\t\t\t\t\tif oldref:\n\t\t\t\t\t\t\tself.playService(oldref, checkParentalControl=False, forceRestart=True, ignoreStreamRelay=True)\n\t\t\t\t\t\treturn 1\n\t\t\t\tprint(f\"[Navigation] Playref is '{playref.toString()}'.\")\n\t\t\t\tself.currentlyPlayingServiceOrGroup = ref\n\t\t\t\tif InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent(ref, adjust):\n\t\t\t\t\tself.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent()\n\t\t\t\t# self.skipServiceReferenceReset = True\n\t\t\t\tif (config.misc.softcam_streamrelay_delay.value and self.isCurrentServiceStreamRelay) or (self.firstStart and isStreamRelay):\n\t\t\t\t\tself.skipServiceReferenceReset = False\n\t\t\t\t\tself.isCurrentServiceStreamRelay = False\n\t\t\t\t\tself.currentlyPlayingServiceReference = None\n\t\t\t\t\tself.currentlyPlayingServiceOrGroup = None\n\t\t\t\t\tprint(\"[Navigation] Stream relay was active, delay the zap till tuner is freed.\")\n\t\t\t\t\tself.retryServicePlayTimer = eTimer()\n\t\t\t\t\tself.retryServicePlayTimer.callback.append(boundFunction(self.playService, ref, checkParentalControl, forceRestart, adjust))\n\t\t\t\t\tdelay = 2000 if self.firstStart else config.misc.softcam_streamrelay_delay.value\n\t\t\t\t\tself.firstStart = False\n\t\t\t\t\tself.retryServicePlayTimer.start(delay, True)\n\t\t\t\t\treturn 0\n\t\t\t\telif self.pnav.playService(playref):\n\t\t\t\t\tprint(f\"[Navigation] Failed to start '{playref.toString()}'.\")\n\t\t\t\t\tself.currentlyPlayingServiceReference = None\n\t\t\t\t\tself.currentlyPlayingServiceOrGroup = None\n\t\t\t\t\tif oldref and (\"://\" in oldref.getPath() or streamrelay.checkService(oldref)):\n\t\t\t\t\t\tprint(\"[Navigation] Streaming was active, try again.\") # Use timer to give the stream server the time to deallocate the tuner.\n\t\t\t\t\t\tself.retryServicePlayTimer = eTimer()\n\t\t\t\t\t\tself.retryServicePlayTimer.callback.append(boundFunction(self.playService, ref, checkParentalControl, forceRestart, adjust))\n\t\t\t\t\t\tself.retryServicePlayTimer.start(500, True)\n\t\t\t\tself.skipServiceReferenceReset = False\n\t\t\t\tif isStreamRelay and not self.isCurrentServiceStreamRelay:\n\t\t\t\t\tself.isCurrentServiceStreamRelay = True\n\t\t\t\treturn 0\n\t\telif oldref and InfoBarInstance and InfoBarInstance.servicelist.servicelist.setCurrent(oldref, adjust):\n\t\t\tself.currentlyPlayingServiceOrGroup = InfoBarInstance.servicelist.servicelist.getCurrent()\n\t\treturn 1", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def doBackup(self):\n\t\tself.shutdownOKOld = config.usage.shutdownOK.value\n\t\tconfig.usage.shutdownOK.setValue(True)\n\t\tconfig.usage.shutdownOK.save()\n\t\tconfigfile.save()\n\t\ttry:\n\t\t\tif config.plugins.softwaremanager.epgcache.value:\n\t\t\t\teEPGCache.getInstance().save()\n\t\texcept Exception:\n\t\t\tpass\n\t\ttry:\n\t\t\tbackupFile = getBackupFilename()\n\t\t\tif exists(self.backuppath) is False:\n\t\t\t\tmakedirs(self.backuppath)\n\t\t\tfullbackupFilename = join(self.backuppath, backupFile)\n\t\t\tif not hasattr(config.plugins, \"configurationbackup\"):\n\t\t\t\tInitConfig()\n\t\t\tbackupDirs = \" \".join(f.strip(\"/\") for f in config.plugins.configurationbackup.backupdirs_default.value)\n\t\t\tfor f in config.plugins.configurationbackup.backupdirs.value:\n\t\t\t\tif f.strip(\"/\") not in backupDirs:\n\t\t\t\t\tbackupDirs += f\" {f.strip('/')}\"\n\t\t\tfor file in (\"installed-list.txt\", \"changed-configfiles.txt\", \"passwd.txt\", \"groups.txt\"):\n\t\t\t\tif f\"tmp/{file}\" not in backupDirs:\n\t\t\t\t\tbackupDirs += f\" tmp/{file}\"\n\n\t\t\tShellCompatibleFunctions.backupUserDB()\n\t\t\tpkgs = ShellCompatibleFunctions.listpkg(type=\"user\")\n\t\t\tfileWriteLines(\"/tmp/installed-list.txt\", pkgs)\n\t\t\tif exists(\"/usr/lib/package.lst\"):\n\t\t\t\tpkgs = ShellCompatibleFunctions.listpkg(type=\"installed\")\n\t\t\t\twith open(\"/usr/lib/package.lst\") as fd:\n\t\t\t\t\tinstalled = set(line.split()[0] for line in pkgs)\n\t\t\t\t\tpreinstalled = set(line.split()[0] for line in fd)\n\t\t\t\t\tremoved = preinstalled - installed\n\t\t\t\t\tremoved = [package for package in removed if package.startswith(\"enigma2-plugin-\") or package.startswith(\"enigma2-locale-\")]\n\t\t\t\t\tif removed:\n\t\t\t\t\t\tfileWriteLines(\"/tmp/removed-list.txt\", removed)\n\t\t\t\t\t\tbackupDirs += \" tmp/removed-list.txt\"\n\t\t\ttarCmd = f\"tar -C / -czvf {fullbackupFilename}\"\n\t\t\tfor f in config.plugins.configurationbackup.backupdirs_exclude.value:\n\t\t\t\ttarCmd += f\" --exclude {f.strip('/')}\"\n\t\t\tfor f in BLACKLISTED:\n\t\t\t\ttarCmd += f\" --exclude {f.strip('/')}\"\n\t\t\ttarCmd += f\" {backupDirs}\"\n\t\t\tcmdList = [\"opkg list-changed-conffiles > /tmp/changed-configfiles.txt\", tarCmd]\n\t\t\tif exists(fullbackupFilename):\n\t\t\t\tdt = str(date.fromtimestamp(stat(fullbackupFilename).st_ctime))\n\t\t\t\tnewFilename = join(self.backuppath, f\"{dt}-{backupFile}\")\n\t\t\t\tif exists(newFilename):\n\t\t\t\t\tremove(newFilename)\n\t\t\t\trename(fullbackupFilename, newFilename)\n\t\t\tself.session.openWithCallback(self.backupFinishedCB, Console, title=self.screenTitle, cmdlist=cmdList, closeOnSuccess=self.closeOnSuccess, showScripts=False)\n\t\texcept OSError:\n\t\t\tself.session.openWithCallback(self.backupErrorCB, MessageBox, _(\"Sorry, your backup destination is not writeable.\\nPlease select a different one.\"), MessageBox.TYPE_INFO, timeout=10)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@view_config(\n route_name=\"admin.user.account_recovery.initiate\",\n renderer=\"admin/users/account_recovery/initiate.html\",\n permission=Permissions.AdminUsersAccountRecoveryWrite,\n has_translations=True,\n uses_session=True,\n require_csrf=True,\n context=User,\n require_methods=False,\n)\ndef user_recover_account_initiate(user, request):\n if user.active_account_recoveries:\n request.session.flash(\n \"Only one account recovery may be in process for each user.\", queue=\"error\"\n )\n\n return HTTPSeeOther(\n request.route_path(\"admin.user.detail\", username=user.username)\n )\n\n repo_urls = _get_related_urls(user)\n\n if request.method == \"POST\":\n\n support_issue_link = request.POST.get(\"support_issue_link\")\n project_name = request.POST.get(\"project_name\")\n\n if not support_issue_link:\n request.session.flash(\n \"Provide a link to the pypi/support issue\", queue=\"error\"\n )\n elif not support_issue_link.startswith(\n \"https://github.com/pypi/support/issues/\"\n ):\n request.session.flash(\n \"The pypi/support issue link is invalid\", queue=\"error\"\n )\n elif repo_urls and not project_name:\n request.session.flash(\"Select a project for verification\", queue=\"error\")\n else:\n token = token_urlsafe().replace(\"-\", \"\").replace(\"_\", \"\")[:16]\n override_to_email = (\n request.POST.get(\"override_to_email\")\n if request.POST.get(\"override_to_email\") != \"\"\n else None\n )\n\n if override_to_email is not None:\n user_service = request.find_service(IUserService, context=None)\n _user = user_service.get_user_by_email(override_to_email)\n if _user is None:\n user_and_email = (\n user,\n user_service.add_email(\n user.id, override_to_email, ratelimit=False\n ),\n )\n elif _user != user:\n request.session.flash(\n \"Email address already associated with a user\", queue=\"error\"\n )\n return HTTPSeeOther(\n request.route_path(\n \"admin.user.account_recovery.initiate\",\n username=user.username,\n )\n )\n else:\n user_and_email = (\n user,\n request.db.query(Email)\n .filter(Email.email == override_to_email)\n .one(),\n )\n else:\n user_and_email = (user, user.primary_email)\n\n # Store an event\n observation = user.record_observation(\n request=request,\n kind=ObservationKind.AccountRecovery,\n actor=request.user,\n summary=\"Account Recovery\",\n payload={\n \"initiated\": str(datetime.datetime.now(datetime.UTC)),\n \"completed\": None,\n \"token\": token,\n \"project_name\": project_name,\n \"repos\": sorted(list(repo_urls.get(project_name, []))),\n \"support_issue_link\": support_issue_link,\n \"override_to_email\": override_to_email,\n },\n )\n observation.additional = {\"status\": \"initiated\"}\n\n # Send the email\n send_account_recovery_initiated_email(\n request,\n user_and_email,\n project_name=project_name,\n support_issue_link=support_issue_link,\n token=token,\n )\n\n request.session.flash(\n f\"Initiatied account recovery for {user.username!r}\", queue=\"success\"\n )\n\n return HTTPSeeOther(\n request.route_path(\"admin.user.detail\", username=user.username)\n )\n\n return HTTPSeeOther(\n request.route_path(\n \"admin.user.account_recovery.initiate\", username=user.username\n )\n )\n\n return {\n \"user\": user,\n \"repo_urls\": repo_urls,\n }", "smellKey": "S3776", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "@instrumented_task(\n name=\"sentry.tasks.summaries.weekly_reports.prepare_organization_report\",\n queue=\"reports.prepare\",\n max_retries=5,\n acks_late=True,\n silo_mode=SiloMode.REGION,\n)\n@retry\ndef prepare_organization_report(\n timestamp: float,\n duration: int,\n organization_id: int,\n batch_id: uuid.UUID,\n dry_run: bool = False,\n target_user: User | None = None,\n email_override: str | None = None,\n):\n if target_user and not hasattr(target_user, \"id\"):\n logger.error(\n \"Target user must have an ID\",\n extra={\n \"batch_id\": str(batch_id),\n \"organization\": organization_id,\n \"target_user\": target_user,\n \"email_override\": email_override,\n },\n )\n return\n organization = Organization.objects.get(id=organization_id)\n set_tag(\"org.slug\", organization.slug)\n set_tag(\"org.id\", organization_id)\n ctx = OrganizationReportContext(timestamp, duration, organization)\n\n # Run organization passes\n with sentry_sdk.start_span(op=\"weekly_reports.user_project_ownership\"):\n user_project_ownership(ctx)\n with sentry_sdk.start_span(op=\"weekly_reports.project_event_counts_for_organization\"):\n event_counts = project_event_counts_for_organization(\n start=ctx.start, end=ctx.end, ctx=ctx, referrer=Referrer.REPORTS_OUTCOMES.value\n )\n for data in event_counts:\n project_id = data[\"project_id\"]\n # Project no longer in organization, but events still exist\n if project_id not in ctx.projects_context_map:\n continue\n project_ctx = cast(ProjectContext, ctx.projects_context_map[project_id])\n total = data[\"total\"]\n timestamp = int(parse_snuba_datetime(data[\"time\"]).timestamp())\n if data[\"category\"] == DataCategory.TRANSACTION:\n # Transaction outcome\n if data[\"outcome\"] == Outcome.RATE_LIMITED or data[\"outcome\"] == Outcome.FILTERED:\n project_ctx.dropped_transaction_count += total\n else:\n project_ctx.accepted_transaction_count += total\n project_ctx.transaction_count_by_day[timestamp] = total\n elif data[\"category\"] == DataCategory.REPLAY:\n # Replay outcome\n if data[\"outcome\"] == Outcome.RATE_LIMITED or data[\"outcome\"] == Outcome.FILTERED:\n project_ctx.dropped_replay_count += total\n else:\n project_ctx.accepted_replay_count += total\n project_ctx.replay_count_by_day[timestamp] = total\n else:\n # Error outcome\n if data[\"outcome\"] == Outcome.RATE_LIMITED or data[\"outcome\"] == Outcome.FILTERED:\n project_ctx.dropped_error_count += total\n else:\n project_ctx.accepted_error_count += total\n project_ctx.error_count_by_day[timestamp] = (\n project_ctx.error_count_by_day.get(timestamp, 0) + total\n )\n\n with sentry_sdk.start_span(op=\"weekly_reports.organization_project_issue_substatus_summaries\"):\n organization_project_issue_substatus_summaries(ctx)\n\n with sentry_sdk.start_span(op=\"weekly_reports.project_passes\"):\n # Run project passes\n for project in organization.project_set.all():\n key_errors = project_key_errors(\n ctx, project, referrer=Referrer.REPORTS_KEY_ERRORS.value\n )\n if project.id not in ctx.projects_context_map:\n continue\n\n project_ctx = cast(ProjectContext, ctx.projects_context_map[project.id])\n if key_errors:\n project_ctx.key_errors_by_id = [\n (e[\"events.group_id\"], e[\"count()\"]) for e in key_errors\n ]\n\n if ctx.organization.slug == \"sentry\":\n logger.info(\n \"project_key_errors.results\",\n extra={\n \"batch_id\": str(batch_id),\n \"project_id\": project.id,\n \"num_key_errors\": len(key_errors),\n },\n )\n key_transactions_this_week = project_key_transactions_this_week(ctx, project)\n if key_transactions_this_week:\n project_ctx.key_transactions = [\n (i[\"transaction_name\"], i[\"count\"], i[\"p95\"])\n for i in key_transactions_this_week\n ]\n query_result = project_key_transactions_last_week(\n ctx, project, key_transactions_this_week\n )\n # Join this week with last week\n last_week_data = {\n i[\"transaction_name\"]: (i[\"count\"], i[\"p95\"]) for i in query_result[\"data\"]\n }\n\n project_ctx.key_transactions = [\n (i[\"transaction_name\"], i[\"count\"], i[\"p95\"])\n + last_week_data.get(i[\"transaction_name\"], (0, 0))\n for i in key_transactions_this_week\n ]\n\n key_performance_issues = project_key_performance_issues(\n ctx, project, referrer=Referrer.REPORTS_KEY_PERFORMANCE_ISSUES.value\n )\n if key_performance_issues:\n ctx.projects_context_map[project.id].key_performance_issues = key_performance_issues\n\n with sentry_sdk.start_span(op=\"weekly_reports.fetch_key_error_groups\"):\n fetch_key_error_groups(ctx)\n with sentry_sdk.start_span(op=\"weekly_reports.fetch_key_performance_issue_groups\"):\n fetch_key_performance_issue_groups(ctx)\n\n with sentry_sdk.start_span(op=\"weekly_reports.check_if_ctx_is_empty\"):\n report_is_available = not check_if_ctx_is_empty(ctx)\n set_tag(\"report.available\", report_is_available)\n\n if not report_is_available:\n logger.info(\n \"prepare_organization_report.skipping_empty\",\n extra={\"batch_id\": str(batch_id), \"organization\": organization_id},\n )\n return\n\n # Finally, deliver the reports\n batch = OrganizationReportBatch(ctx, batch_id, dry_run, target_user, email_override)\n with sentry_sdk.start_span(op=\"weekly_reports.deliver_reports\"):\n logger.info(\n \"weekly_reports.deliver_reports\",\n extra={\"batch_id\": str(batch_id), \"organization\": organization_id},\n )\n batch.deliver_reports()", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def createConfig(self):\n\t\tself.service = self.session.nav.getCurrentService()\n\t\tself.feinfo = None\n\t\tself.networkid = 0\n\t\tfrontendData = None\n\t\tif self.service is not None:\n\t\t\tself.feinfo = self.service.frontendInfo()\n\t\t\tfrontendData = self.feinfo and self.feinfo.getAll(True)\n\t\tdel self.feinfo\n\t\tdel self.service\n\t\tself.updateSatList()\n\t\tdefaultSat = {\n\t\t\t\"orbpos\": 192,\n\t\t\t\"system\": eDVBFrontendParametersSatellite.System_DVB_S,\n\t\t\t\"frequency\": 11836,\n\t\t\t\"inversion\": eDVBFrontendParametersSatellite.Inversion_Unknown,\n\t\t\t\"symbolrate\": 27500,\n\t\t\t\"polarization\": eDVBFrontendParametersSatellite.Polarisation_Horizontal,\n\t\t\t\"fec\": eDVBFrontendParametersSatellite.FEC_Auto,\n\t\t\t\"fec_s2\": eDVBFrontendParametersSatellite.FEC_9_10,\n\t\t\t\"modulation\": eDVBFrontendParametersSatellite.Modulation_QPSK,\n\t\t\t\"is_id\": eDVBFrontendParametersSatellite.No_Stream_Id_Filter,\n\t\t\t\"pls_mode\": eDVBFrontendParametersSatellite.PLS_Gold,\n\t\t\t\"pls_code\": eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,\n\t\t\t\"t2mi_plp_id\": eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,\n\t\t\t\"t2mi_pid\": eDVBFrontendParametersSatellite.T2MI_Default_Pid}\n\t\tdefaultCab = {\n\t\t\t\"frequency\": 466000,\n\t\t\t\"inversion\": eDVBFrontendParametersCable.Inversion_Unknown,\n\t\t\t\"modulation\": eDVBFrontendParametersCable.Modulation_QAM64,\n\t\t\t\"fec\": eDVBFrontendParametersCable.FEC_Auto,\n\t\t\t\"symbolrate\": 6900,\n\t\t\t\"system\": eDVBFrontendParametersCable.System_DVB_C_ANNEX_A}\n\t\tdefaultTer = {\n\t\t\t\"frequency\": 474000,\n\t\t\t\"inversion\": eDVBFrontendParametersTerrestrial.Inversion_Unknown,\n\t\t\t\"bandwidth\": 8000000,\n\t\t\t\"fechigh\": eDVBFrontendParametersTerrestrial.FEC_Auto,\n\t\t\t\"feclow\": eDVBFrontendParametersTerrestrial.FEC_Auto,\n\t\t\t\"modulation\": eDVBFrontendParametersTerrestrial.Modulation_Auto,\n\t\t\t\"transmission_mode\": eDVBFrontendParametersTerrestrial.TransmissionMode_Auto,\n\t\t\t\"guard_interval\": eDVBFrontendParametersTerrestrial.GuardInterval_Auto,\n\t\t\t\"hierarchy\": eDVBFrontendParametersTerrestrial.Hierarchy_Auto,\n\t\t\t\"system\": eDVBFrontendParametersTerrestrial.System_DVB_T,\n\t\t\t\"plp_id\": 0}\n\t\tdefaultATSC = {\n\t\t\t\"frequency\": 474000,\n\t\t\t\"inversion\": eDVBFrontendParametersATSC.Inversion_Unknown,\n\t\t\t\"modulation\": eDVBFrontendParametersATSC.Modulation_Auto,\n\t\t\t\"system\": eDVBFrontendParametersATSC.System_ATSC}\n\n\t\tif frontendData is not None:\n\t\t\tttype = frontendData.get(\"tuner_type\", \"UNKNOWN\")\n\t\t\tif ttype == \"DVB-S\":\n\t\t\t\tdefaultSat[\"system\"] = frontendData.get(\"system\", eDVBFrontendParametersSatellite.System_DVB_S)\n\t\t\t\tdefaultSat[\"frequency\"] = frontendData.get(\"frequency\", 0) // 1000\n\t\t\t\tdefaultSat[\"inversion\"] = frontendData.get(\"inversion\", eDVBFrontendParametersSatellite.Inversion_Unknown)\n\t\t\t\tdefaultSat[\"symbolrate\"] = frontendData.get(\"symbol_rate\", 0) // 1000\n\t\t\t\tdefaultSat[\"polarization\"] = frontendData.get(\"polarization\", eDVBFrontendParametersSatellite.Polarisation_Horizontal)\n\t\t\t\tif defaultSat[\"system\"] == eDVBFrontendParametersSatellite.System_DVB_S2:\n\t\t\t\t\tdefaultSat[\"fec_s2\"] = frontendData.get(\"fec_inner\", eDVBFrontendParametersSatellite.FEC_Auto)\n\t\t\t\t\tdefaultSat[\"rolloff\"] = frontendData.get(\"rolloff\", eDVBFrontendParametersSatellite.RollOff_alpha_0_35)\n\t\t\t\t\tdefaultSat[\"pilot\"] = frontendData.get(\"pilot\", eDVBFrontendParametersSatellite.Pilot_Unknown)\n\t\t\t\t\tdefaultSat[\"is_id\"] = frontendData.get(\"is_id\", defaultSat[\"is_id\"])\n\t\t\t\t\tdefaultSat[\"pls_mode\"] = frontendData.get(\"pls_mode\", defaultSat[\"pls_mode\"])\n\t\t\t\t\tdefaultSat[\"pls_code\"] = frontendData.get(\"pls_code\", defaultSat[\"pls_code\"])\n\t\t\t\t\tdefaultSat[\"t2mi_plp_id\"] = frontendData.get(\"t2mi_plp_id\", defaultSat[\"t2mi_plp_id\"])\n\t\t\t\t\tdefaultSat[\"t2mi_pid\"] = frontendData.get(\"t2mi_pid\", defaultSat[\"t2mi_pid\"])\n\t\t\t\telse:\n\t\t\t\t\tdefaultSat[\"fec\"] = frontendData.get(\"fec_inner\", eDVBFrontendParametersSatellite.FEC_Auto)\n\t\t\t\tdefaultSat[\"modulation\"] = frontendData.get(\"modulation\", eDVBFrontendParametersSatellite.Modulation_QPSK)\n\t\t\t\tdefaultSat[\"orbpos\"] = frontendData.get(\"orbital_position\", 0)\n\t\t\telif ttype == \"DVB-C\":\n\t\t\t\tdefaultCab[\"frequency\"] = frontendData.get(\"frequency\", 0)\n\t\t\t\tdefaultCab[\"symbolrate\"] = frontendData.get(\"symbol_rate\", 0) // 1000\n\t\t\t\tdefaultCab[\"inversion\"] = frontendData.get(\"inversion\", eDVBFrontendParametersCable.Inversion_Unknown)\n\t\t\t\tdefaultCab[\"fec\"] = frontendData.get(\"fec_inner\", eDVBFrontendParametersCable.FEC_Auto)\n\t\t\t\tdefaultCab[\"modulation\"] = frontendData.get(\"modulation\", eDVBFrontendParametersCable.Modulation_QAM16)\n\t\t\t\tdefaultCab[\"system\"] = frontendData.get(\"system\", eDVBFrontendParametersCable.System_DVB_C_ANNEX_A)\n\t\t\telif ttype == \"DVB-T\":\n\t\t\t\tdefaultTer[\"frequency\"] = frontendData.get(\"frequency\", 47400000) // 1000\n\t\t\t\tdefaultTer[\"inversion\"] = frontendData.get(\"inversion\", eDVBFrontendParametersTerrestrial.Inversion_Unknown)\n\t\t\t\tdefaultTer[\"bandwidth\"] = frontendData.get(\"bandwidth\", 8000000)\n\t\t\t\tdefaultTer[\"fechigh\"] = frontendData.get(\"code_rate_hp\", eDVBFrontendParametersTerrestrial.FEC_Auto)\n\t\t\t\tdefaultTer[\"feclow\"] = frontendData.get(\"code_rate_lp\", eDVBFrontendParametersTerrestrial.FEC_Auto)\n\t\t\t\tdefaultTer[\"modulation\"] = frontendData.get(\"constellation\", eDVBFrontendParametersTerrestrial.Modulation_Auto)\n\t\t\t\tdefaultTer[\"transmission_mode\"] = frontendData.get(\"transmission_mode\", eDVBFrontendParametersTerrestrial.TransmissionMode_Auto)\n\t\t\t\tdefaultTer[\"guard_interval\"] = frontendData.get(\"guard_interval\", eDVBFrontendParametersTerrestrial.GuardInterval_Auto)\n\t\t\t\tdefaultTer[\"hierarchy\"] = frontendData.get(\"hierarchy_information\", eDVBFrontendParametersTerrestrial.Hierarchy_Auto)\n\t\t\t\tdefaultTer[\"system\"] = frontendData.get(\"system\", eDVBFrontendParametersTerrestrial.System_DVB_T)\n\t\t\t\tdefaultTer[\"plp_id\"] = frontendData.get(\"plp_id\", 0)\n\t\t\telif ttype == \"ATSC\":\n\t\t\t\tdefaultATSC[\"frequency\"] = frontendData.get(\"frequency\", 47400000) // 1000\n\t\t\t\tdefaultATSC[\"inversion\"] = frontendData.get(\"inversion\", eDVBFrontendParametersATSC.Inversion_Unknown)\n\t\t\t\tdefaultATSC[\"modulation\"] = frontendData.get(\"modulation\", eDVBFrontendParametersATSC.Modulation_Auto)\n\t\t\t\tdefaultATSC[\"system\"] = frontendData.get(\"system\", eDVBFrontendParametersATSC.System_ATSC)\n\n\t\tself.scan_sat = ConfigSubsection()\n\t\tself.scan_cab = ConfigSubsection()\n\t\tself.scan_ter = ConfigSubsection()\n\t\tself.scan_ats = ConfigSubsection()\n\n\t\tnim_list = []\n\t\t# collect all nims which are *not* set to \"nothing\"\n\t\tfor n in nimmanager.nim_slots:\n\t\t\tdvbs = (n.canBeCompatible(\"DVB-S\") and (n.config.dvbs.configMode.value != \"nothing\" and True or False))\n\t\t\tdvbc = (n.canBeCompatible(\"DVB-C\") and (n.config.dvbc.configMode.value != \"nothing\" and True or False))\n\t\t\tdvbt = (n.canBeCompatible(\"DVB-T\") and (n.config.dvbt.configMode.value != \"nothing\" and True or False))\n\t\t\tatsc = (n.canBeCompatible(\"ATSC\") and (n.config.atsc.configMode.value != \"nothing\" and True or False))\n\n\t\t\tif (dvbc or dvbt or atsc):\n\t\t\t\tnim_list.append((str(n.slot), n.friendly_full_description))\n\t\t\telif dvbs:\n\t\t\t\tif n.canBeCompatible(\"DVB-S\") and len(nimmanager.getSatListForNim(n.slot)) < 1: # empty setup\n\t\t\t\t\tcontinue\n\t\t\t\tif n.canBeCompatible(\"DVB-S\") and n.config.dvbs.configMode.value in (\"loopthrough\", \"satposdepends\"):\n\t\t\t\t\troot_id = nimmanager.sec.getRoot(n.slot_id, int(n.config.dvbs.connectedTo.value))\n\t\t\t\t\tif n.type == nimmanager.nim_slots[root_id].type: # check if connected from a DVB-S to DVB-S2 Nim or vice versa\n\t\t\t\t\t\tcontinue\n\t\t\t\tnim_list.append((str(n.slot), n.friendly_full_description))\n\n\t\tself.scan_nims = ConfigSelection(choices=nim_list)\n\t\tif frontendData is not None and len(nim_list) > 0:\n\t\t\tself.scan_nims.setValue(str(frontendData.get(\"tuner_number\", nim_list[0][0])))\n\n\t\tfor slot in nimmanager.nim_slots:\n\t\t\tif slot.canBeCompatible(\"DVB-T\"):\n\t\t\t\tself.ter_tnumber = slot.slot\n\t\tif self.ter_tnumber is not None:\n\t\t\tself.ter_channel_input = supportedChannels(self.ter_tnumber)\n\n\t\t# status\n\t\tself.scan_snr = ConfigSlider()\n\t\tself.scan_snr.enabled = False\n\t\tself.scan_agc = ConfigSlider()\n\t\tself.scan_agc.enabled = False\n\t\tself.scan_ber = ConfigSlider()\n\t\tself.scan_ber.enabled = False\n\n\t\t# sat\n\t\tself.scan_sat.system = ConfigSelection(default=defaultSat[\"system\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.System_DVB_S, _(\"DVB-S\")),\n\t\t\t(eDVBFrontendParametersSatellite.System_DVB_S2, _(\"DVB-S2\"))])\n\t\tself.scan_sat.frequency = ConfigInteger(default=defaultSat[\"frequency\"], limits=(1, 99999))\n\t\tself.scan_sat.inversion = ConfigSelection(default=defaultSat[\"inversion\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.Inversion_Off, _(\"Off\")),\n\t\t\t(eDVBFrontendParametersSatellite.Inversion_On, _(\"On\")),\n\t\t\t(eDVBFrontendParametersSatellite.Inversion_Unknown, _(\"Auto\"))])\n\t\tself.scan_sat.symbolrate = ConfigInteger(default=defaultSat[\"symbolrate\"], limits=(1, 99999))\n\t\tself.scan_sat.polarization = ConfigSelection(default=defaultSat[\"polarization\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.Polarisation_Horizontal, _(\"Horizontal\")),\n\t\t\t(eDVBFrontendParametersSatellite.Polarisation_Vertical, _(\"Vertical\")),\n\t\t\t(eDVBFrontendParametersSatellite.Polarisation_CircularLeft, _(\"Circular left\")),\n\t\t\t(eDVBFrontendParametersSatellite.Polarisation_CircularRight, _(\"Circular right\"))])\n\t\tself.scan_sat.fec = ConfigSelection(default=defaultSat[\"fec\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.FEC_Auto, _(\"Auto\")),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_1_2, \"1/2\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_2_3, \"2/3\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_3_4, \"3/4\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_5_6, \"5/6\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_7_8, \"7/8\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_None, _(\"None\"))])\n\t\tself.scan_sat.fec_s2 = ConfigSelection(default=defaultSat[\"fec_s2\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.FEC_Auto, _(\"Auto\")),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_1_2, \"1/2\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_2_3, \"2/3\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_3_4, \"3/4\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_3_5, \"3/5\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_4_5, \"4/5\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_5_6, \"5/6\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_6_7, \"6/7\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_7_8, \"7/8\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_8_9, \"8/9\"),\n\t\t\t(eDVBFrontendParametersSatellite.FEC_9_10, \"9/10\")])\n\t\tself.scan_sat.modulation = ConfigSelection(default=defaultSat[\"modulation\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.Modulation_QPSK, \"QPSK\"),\n\t\t\t(eDVBFrontendParametersSatellite.Modulation_8PSK, \"8PSK\"),\n\t\t\t(eDVBFrontendParametersSatellite.Modulation_16APSK, \"16APSK\"),\n\t\t\t(eDVBFrontendParametersSatellite.Modulation_32APSK, \"32APSK\")])\n\t\tself.scan_sat.rolloff = ConfigSelection(default=defaultSat.get(\"rolloff\", eDVBFrontendParametersSatellite.RollOff_alpha_0_35), choices=[\n\t\t\t(eDVBFrontendParametersSatellite.RollOff_alpha_0_35, \"0.35\"),\n\t\t\t(eDVBFrontendParametersSatellite.RollOff_alpha_0_25, \"0.25\"),\n\t\t\t(eDVBFrontendParametersSatellite.RollOff_alpha_0_20, \"0.20\"),\n\t\t\t(eDVBFrontendParametersSatellite.RollOff_auto, _(\"Auto\"))])\n\t\tself.scan_sat.pilot = ConfigSelection(default=defaultSat.get(\"pilot\", eDVBFrontendParametersSatellite.Pilot_Unknown), choices=[\n\t\t\t(eDVBFrontendParametersSatellite.Pilot_Off, _(\"Off\")),\n\t\t\t(eDVBFrontendParametersSatellite.Pilot_On, _(\"On\")),\n\t\t\t(eDVBFrontendParametersSatellite.Pilot_Unknown, _(\"Auto\"))])\n\t\tself.scan_sat.is_id = ConfigInteger(default=defaultSat[\"is_id\"], limits=(eDVBFrontendParametersSatellite.No_Stream_Id_Filter, 255))\n\t\tself.scan_sat.is_id_bool = ConfigSelection(default=defaultSat[\"is_id\"] != eDVBFrontendParametersSatellite.No_Stream_Id_Filter, choices=[(True, _(\"Multistream\")), (False, _(\"Ordinary\"))])\n\t\tself.scan_sat.pls_mode = ConfigSelection(default=defaultSat[\"pls_mode\"], choices=[\n\t\t\t(eDVBFrontendParametersSatellite.PLS_Root, _(\"Root\")),\n\t\t\t(eDVBFrontendParametersSatellite.PLS_Gold, _(\"Gold\")),\n\t\t\t(eDVBFrontendParametersSatellite.PLS_Combo, _(\"Combo\"))])\n\t\tself.scan_sat.pls_code = ConfigInteger(default=defaultSat.get(\"pls_code\"), limits=(0, 262142))\n\t\tself.scan_sat.t2mi_plp_id = ConfigInteger(default=defaultSat[\"t2mi_plp_id\"], limits=(eDVBFrontendParametersSatellite.No_T2MI_PLP_Id, 255))\n\t\tself.scan_sat.t2mi_pid = ConfigInteger(default=defaultSat[\"t2mi_pid\"] if self.scan_sat.t2mi_plp_id.value != eDVBFrontendParametersSatellite.No_T2MI_PLP_Id else eDVBFrontendParametersSatellite.T2MI_Default_Pid, limits=(0, 8191))\n\t\tself.scan_sat.t2mi_plp_id_bool = ConfigSelection(default=defaultSat[\"t2mi_plp_id\"] != eDVBFrontendParametersSatellite.No_T2MI_PLP_Id, choices=[(True, _(\"Enabled\")), (False, _(\"Disabled\"))])\n\n\t\tself.is_id_memory = self.scan_sat.is_id.value # used to prevent is_id value being lost when self.scan_sat.is_id_bool state changes\n\t\tself.pls_mode_memory = self.scan_sat.pls_mode.value\n\t\tself.pls_code_memory = self.scan_sat.pls_code.value\n\t\tself.t2mi_plp_id_memory = self.scan_sat.t2mi_plp_id.value\n\t\tself.t2mi_pid_memory = self.scan_sat.t2mi_pid.value\n\n\t\t# cable\n\t\tself.scan_cab.frequency = ConfigFloat(default=[defaultCab[\"frequency\"] // 1000, defaultCab[\"frequency\"] % 1000], limits=[(50, 999), (0, 999)])\n\t\tself.scan_cab.inversion = ConfigSelection(default=defaultCab[\"inversion\"], choices=[\n\t\t\t(eDVBFrontendParametersCable.Inversion_Off, _(\"Off\")),\n\t\t\t(eDVBFrontendParametersCable.Inversion_On, _(\"On\")),\n\t\t\t(eDVBFrontendParametersCable.Inversion_Unknown, _(\"Auto\"))])\n\t\tself.scan_cab.modulation = ConfigSelection(default=defaultCab[\"modulation\"], choices=[\n\t\t\t(eDVBFrontendParametersCable.Modulation_QAM16, \"16-QAM\"),\n\t\t\t(eDVBFrontendParametersCable.Modulation_QAM32, \"32-QAM\"),\n\t\t\t(eDVBFrontendParametersCable.Modulation_QAM64, \"64-QAM\"),\n\t\t\t(eDVBFrontendParametersCable.Modulation_QAM128, \"128-QAM\"),\n\t\t\t(eDVBFrontendParametersCable.Modulation_QAM256, \"256-QAM\")])\n\t\tself.scan_cab.fec = ConfigSelection(default=defaultCab[\"fec\"], choices=[\n\t\t\t(eDVBFrontendParametersCable.FEC_Auto, _(\"Auto\")),\n\t\t\t(eDVBFrontendParametersCable.FEC_1_2, \"1/2\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_2_3, \"2/3\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_3_4, \"3/4\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_3_5, \"3/5\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_4_5, \"4/5\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_5_6, \"5/6\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_6_7, \"6/7\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_7_8, \"7/8\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_8_9, \"8/9\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_9_10, \"9/10\"),\n\t\t\t(eDVBFrontendParametersCable.FEC_None, _(\"None\"))])\n\t\tself.scan_cab.symbolrate = ConfigInteger(default=defaultCab[\"symbolrate\"], limits=(1, 99999))\n\t\tself.scan_cab.system = ConfigSelection(default=defaultCab[\"system\"], choices=[\n\t\t\t(eDVBFrontendParametersCable.System_DVB_C_ANNEX_A, _(\"DVB-C\")),\n\t\t\t(eDVBFrontendParametersCable.System_DVB_C_ANNEX_C, _(\"DVB-C ANNEX C\"))])\n\n\t\t# terrestial\n\t\tself.scan_ter.frequency = ConfigFloat(default=[defaultTer[\"frequency\"] // 1000, defaultTer[\"frequency\"] % 1000], limits=[(50, 999), (0, 999)])\n\t\tself.scan_ter.channel = ConfigInteger(default=21, limits=(1, 99))\n\t\tself.scan_ter.inversion = ConfigSelection(default=defaultTer[\"inversion\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.Inversion_Off, _(\"Off\")),\n\t\t\t(eDVBFrontendParametersTerrestrial.Inversion_On, _(\"On\")),\n\t\t\t(eDVBFrontendParametersTerrestrial.Inversion_Unknown, _(\"Auto\"))])\n\t\t# WORKAROUND: we can't use BW-auto\n\t\tself.scan_ter.bandwidth = ConfigSelection(default=defaultTer[\"bandwidth\"], choices=[\n\t\t\t(1712000, \"1.712MHz\"),\n\t\t\t(5000000, \"5MHz\"),\n\t\t\t(6000000, \"6MHz\"),\n\t\t\t(7000000, \"7MHz\"),\n\t\t\t(8000000, \"8MHz\"),\n\t\t\t(10000000, \"10MHz\")\n\t\t\t])\n\t\t#, (eDVBFrontendParametersTerrestrial.Bandwidth_Auto, _(\"Auto\"))))\n\t\tself.scan_ter.fechigh = ConfigSelection(default=defaultTer[\"fechigh\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_1_2, \"1/2\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_2_3, \"2/3\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_3_4, \"3/4\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_3_5, \"3/5\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_4_5, \"4/5\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_5_6, \"5/6\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_6_7, \"6/7\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_7_8, \"7/8\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_8_9, \"8/9\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.feclow = ConfigSelection(default=defaultTer[\"feclow\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_1_2, \"1/2\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_2_3, \"2/3\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_3_4, \"3/4\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_3_5, \"3/5\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_4_5, \"4/5\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_5_6, \"5/6\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_6_7, \"6/7\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_7_8, \"7/8\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_8_9, \"8/9\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.FEC_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.modulation = ConfigSelection(default=defaultTer[\"modulation\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.Modulation_QPSK, \"QPSK\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Modulation_QAM16, \"QAM16\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Modulation_QAM64, \"QAM64\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Modulation_QAM256, \"QAM256\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Modulation_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.transmission = ConfigSelection(default=defaultTer[\"transmission_mode\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_1k, \"1K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_2k, \"2K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_4k, \"4K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_8k, \"8K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_16k, \"16K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_32k, \"32K\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.TransmissionMode_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.guard = ConfigSelection(default=defaultTer[\"guard_interval\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_1_32, \"1/32\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_1_16, \"1/16\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_1_8, \"1/8\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_1_4, \"1/4\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_1_128, \"1/128\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_19_128, \"19/128\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_19_256, \"19/256\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.GuardInterval_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.hierarchy = ConfigSelection(default=defaultTer[\"hierarchy\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.Hierarchy_None, _(\"None\")),\n\t\t\t(eDVBFrontendParametersTerrestrial.Hierarchy_1, \"1\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Hierarchy_2, \"2\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Hierarchy_4, \"4\"),\n\t\t\t(eDVBFrontendParametersTerrestrial.Hierarchy_Auto, _(\"Auto\"))])\n\t\tself.scan_ter.system = ConfigSelection(default=defaultTer[\"system\"], choices=[\n\t\t\t(eDVBFrontendParametersTerrestrial.System_DVB_T_T2, _(\"Auto\")),\n\t\t\t(eDVBFrontendParametersTerrestrial.System_DVB_T, _(\"DVB-T\")),\n\t\t\t(eDVBFrontendParametersTerrestrial.System_DVB_T2, _(\"DVB-T2\"))])\n\t\tself.scan_ter.plp_id = ConfigInteger(default=defaultTer[\"plp_id\"], limits=(0, 255))\n\n\t\t# ATSC\n\t\tself.scan_ats.frequency = ConfigFloat(default=[defaultATSC[\"frequency\"] // 1000, defaultATSC[\"frequency\"] % 1000], limits=[(50, 999), (0, 999)])\n\t\tself.scan_ats.inversion = ConfigSelection(default=defaultATSC[\"inversion\"], choices=[\n\t\t\t(eDVBFrontendParametersATSC.Inversion_Off, _(\"Off\")),\n\t\t\t(eDVBFrontendParametersATSC.Inversion_On, _(\"On\")),\n\t\t\t(eDVBFrontendParametersATSC.Inversion_Unknown, _(\"Auto\"))])\n\t\tself.scan_ats.modulation = ConfigSelection(default=defaultATSC[\"modulation\"], choices=[\n\t\t\t(eDVBFrontendParametersATSC.Modulation_Auto, _(\"Auto\")),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_QAM16, \"QAM16\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_QAM32, \"QAM32\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_QAM64, \"QAM64\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_QAM128, \"QAM128\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_QAM256, \"QAM256\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_VSB_8, \"8VSB\"),\n\t\t\t(eDVBFrontendParametersATSC.Modulation_VSB_16, \"16VSB\")])\n\t\tself.scan_ats.system = ConfigSelection(default=defaultATSC[\"system\"], choices=[\n\t\t\t(eDVBFrontendParametersATSC.System_ATSC, _(\"ATSC\")),\n\t\t\t(eDVBFrontendParametersATSC.System_DVB_C_ANNEX_B, _(\"DVB-C ANNEX B\"))])\n\n\t\tself.scan_scansat = {}\n\t\tfor sat in nimmanager.satList:\n\t\t\t#print sat[1]\n\t\t\tself.scan_scansat[sat[0]] = ConfigYesNo(default=False)\n\n\t\tself.scan_satselection = []\n\t\tfor slot in nimmanager.nim_slots:\n\t\t\tif slot.canBeCompatible(\"DVB-S\"):\n\t\t\t\tself.scan_satselection.append(getConfigSatlist(defaultSat[\"orbpos\"], self.satList[slot.slot]))\n\t\t\telse:\n\t\t\t\tself.scan_satselection.append(None)\n\n\t\tself.terrestrial_nims_regions = []\n\t\tfor slot in nimmanager.nim_slots:\n\t\t\tif slot.canBeCompatible(\"DVB-T\"):\n\t\t\t\tself.terrestrial_nims_regions.append(self.getTerrestrialRegionsList(slot.slot))\n\t\t\telse:\n\t\t\t\tself.terrestrial_nims_regions.append(None)\n\n\t\tif frontendData is not None and ttype == \"DVB-S\" and self.predefinedTranspondersList(defaultSat[\"orbpos\"]) is not None:\n\t\t\tdefaultSatSearchType = \"predefined_transponder\"\n\t\telse:\n\t\t\tdefaultSatSearchType = \"single_transponder\"\n\t\tif frontendData is not None and ttype == \"DVB-T\" and self.predefinedTerrTranspondersList() is not None:\n\t\t\tdefaultTerrSearchType = \"predefined_transponder\"\n\t\telse:\n\t\t\tdefaultTerrSearchType = \"single_transponder\"\n\n\t\tif frontendData is not None and ttype == \"DVB-C\" and self.predefinedCabTranspondersList() is not None:\n\t\t\tdefaultCabSearchType = \"predefined_transponder\"\n\t\telse:\n\t\t\tdefaultCabSearchType = \"single_transponder\"\n\n\t\tif frontendData is not None and ttype == \"ATSC\" and self.predefinedATSCTranspondersList() is not None:\n\t\t\tdefaultATSCSearchType = \"predefined_transponder\"\n\t\telse:\n\t\t\tdefaultATSCSearchType = \"single_transponder\"\n\n\t\tself.scan_type = ConfigSelection(default=defaultSatSearchType, choices=[(\"single_transponder\", _(\"User defined transponder\")), (\"predefined_transponder\", _(\"Predefined transponder\")), (\"single_satellite\", _(\"Single satellite\")), (\"multisat\", _(\"Multisat\")), (\"multisat_yes\", _(\"Multisat all select\"))])\n\t\tself.scan_typecable = ConfigSelection(default=defaultCabSearchType, choices=[(\"single_transponder\", _(\"User defined transponder\")), (\"predefined_transponder\", _(\"Predefined transponder\")), (\"complete\", _(\"Complete\"))])\n\t\tself.last_scan_typecable = \"single_transponder\"\n\t\tself.cable_toggle = {\"single_transponder\": \"complete\", \"complete\": \"single_transponder\"}\n\t\tself.scan_typeterrestrial = ConfigSelection(default=defaultTerrSearchType, choices=[(\"single_transponder\", _(\"User defined transponder\")), (\"predefined_transponder\", _(\"Predefined transponder\")), (\"complete\", _(\"Complete\"))])\n\t\tself.scan_typeatsc = ConfigSelection(default=defaultATSCSearchType, choices=[(\"single_transponder\", _(\"User defined transponder\")), (\"predefined_transponder\", _(\"Predefined transponder\")), (\"complete\", _(\"Complete\"))])\n\t\tself.scan_input_as = ConfigSelection(default=\"channel\", choices=[(\"frequency\", _(\"Frequency\")), (\"channel\", _(\"Channel\"))])\n\t\tself.scan_clearallservices = ConfigSelection(default=\"no\", choices=[(\"no\", _(\"No\")), (\"yes\", _(\"Yes\")), (\"yes_hold_feeds\", _(\"yes (keep feeds)\"))])\n\t\tself.scan_onlyfree = ConfigYesNo(default=False)\n\t\tself.scan_networkScan = ConfigYesNo(default=False)\n\n\t\tfor x in (\n\t\t\tself.scan_sat.frequency,\n\t\t\tself.scan_sat.inversion,\n\t\t\tself.scan_sat.symbolrate,\n\t\t\tself.scan_sat.polarization,\n\t\t\tself.scan_sat.fec,\n\t\t\tself.scan_sat.pilot,\n\t\t\tself.scan_sat.fec_s2,\n\t\t\tself.scan_sat.fec,\n\t\t\tself.scan_sat.modulation,\n\t\t\tself.scan_sat.rolloff,\n\t\t\tself.scan_sat.system,\n\t\t\tself.preDefTransponders,\n\n\t\t\tself.scan_ter.channel,\n\t\t\tself.scan_ter.frequency,\n\t\t\tself.scan_ter.inversion,\n\t\t\tself.scan_ter.bandwidth,\n\t\t\tself.scan_ter.fechigh,\n\t\t\tself.scan_ter.feclow,\n\t\t\tself.scan_ter.modulation,\n\t\t\tself.scan_ter.transmission,\n\t\t\tself.scan_ter.guard,\n\t\t\tself.scan_ter.hierarchy,\n\t\t\tself.scan_ter.plp_id,\n\t\t\tself.scan_ter.system,\n\t\t\tself.scan_typeterrestrial,\n\t\t\tself.TerrestrialRegion,\n\t\t\tself.TerrestrialTransponders,\n\n\t\t\tself.scan_cab.frequency,\n\t\t\tself.scan_cab.inversion,\n\t\t\tself.scan_cab.symbolrate,\n\t\t\tself.scan_cab.modulation,\n\t\t\tself.scan_cab.fec,\n\t\t\tself.CableTransponders,\n\n\t\t\tself.scan_ats.frequency,\n\t\t\tself.scan_ats.inversion,\n\t\t\tself.scan_ats.modulation,\n\t\t\tself.scan_ats.system,\n\t\t\tself.ATSCTransponders\n\t\t\t):\n\t\t\tif x is not None:\n\t\t\t\tx.addNotifier(self.TriggeredByConfigElement, initial_call=False)\n\t\treturn True", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def UseMPIToCreateSharedPointList(inGlobalNodeIds, inPointXyzs):\n \"\"\"used during finding nearest point (and distance) between one set of points\n and others. The idea is that we have a fairly small set of points from one\n data source (e.g. one block of a multiblock or a decimated set of points)\n which we share to all processors (using mpi broadcast), and then each\n processor finds the nearest point and distance from all of it's points\n to the shared set, and then we use mpi reduce to find which is the\n closest and where it is. This function takes the portion of the shared\n points which are local to this processor (obtained via\n PhactoriOperationBlock.MakeListOfAllPoints1()) and does mpi broadcasting\n to share with all the other processors and also to construct the whole\n list of shared points locally\n returns a vtkIntArray and vtkDoubleArray, where the int array is the list\n of all the global node ids and the double array is all the geometric\n pointx (stored x1y1z1x2y2z2...)\n inGlobalNodeIds is vtkIntArray\n inPointXyzs is vtkDoubleArray\"\"\"\n mypid = SmartGetLocalProcessId()\n\n pm = paraview.servermanager.vtkProcessModule.GetProcessModule()\n globalController = pm.GetGlobalController()\n #gLocalProcessId = globalController.GetLocalProcessId()\n numproc = globalController.GetNumberOfProcesses()\n if PhactoriDbg(100):\n myDebugPrint3(\"mypid: \" + str(mypid) + \" numproc: \" + str(numproc) + \"\\n\")\n\n #first let everyone know how many points are in each process\n\n numptsInEachProc = vtk.vtkIntArray()\n numptsInEachProc.SetNumberOfValues(numproc)\n for ii in range(0,numproc):\n numptsInEachProc.SetValue(ii, 0)\n numptsInEachProc.SetValue(mypid, inGlobalNodeIds.GetNumberOfValues())\n #if PhactoriDbg(100):\n # myDebugPrint3(\"numptsInEachProc before AllReduce:\\n\")\n # for ii in range(0,numproc):\n # myDebugPrint3(str(ii) + \": \" + str(numptsInEachProc.GetValue(ii)) + \"\\n\")\n\n glbNumptsInEachProc = vtk.vtkIntArray()\n glbNumptsInEachProc.SetNumberOfValues(numproc)\n\n globalController.AllReduce(numptsInEachProc, glbNumptsInEachProc, 0)\n #if PhactoriDbg(100):\n # myDebugPrint3(\"numptsInEachProc after AllReduce:\\n\" + str(glbNumptsInEachProc) + \"\\n\")\n # for ii in range(0,numproc):\n # myDebugPrint3(str(ii) + \": \" + str(glbNumptsInEachProc.GetValue(ii)) + \"\\n\")\n\n #now go through and create the shared points list\n #first the node ids\n glbNodeIdList = vtk.vtkIntArray()\n shareIdList = vtk.vtkIntArray()\n for ii in range(0,numproc):\n numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)\n #if PhactoriDbg(100):\n # myDebugPrint3(\"doing broadcast for process \" + str(ii) + \": numpts: \" + str(numPtsFromProcii) + \"\\n\")\n if ii == mypid:\n #if PhactoriDbg(100):\n #myDebugPrint3(\"I am this process, broadcasting to everyone\\n\")\n if(numPtsFromProcii > 0):\n globalController.Broadcast(inGlobalNodeIds, ii)\n for jj in range(0,numPtsFromProcii):\n glbNodeIdList.InsertNextValue(inGlobalNodeIds.GetValue(jj))\n else:\n #if PhactoriDbg(100):\n # myDebugPrint3(\"I am not this process, receiving broadcast from this process: \" + str(numPtsFromProcii) + \"\\n\")\n if(numPtsFromProcii > 0):\n shareIdList.SetNumberOfValues(numPtsFromProcii)\n #if PhactoriDbg(100):\n # myDebugPrint3(\"returned from broadcast call 2\\n\")\n globalController.Broadcast(shareIdList, ii)\n for jj in range(0,numPtsFromProcii):\n glbNodeIdList.InsertNextValue(shareIdList.GetValue(jj))\n #if PhactoriDbg(100):\n # myDebugPrint3(\"glbNodeIdList after broadcasts:\\n\")\n # for ii in range(0, glbNodeIdList.GetNumberOfValues()):\n # myDebugPrint3(str(ii) + \": \" + str(glbNodeIdList.GetValue(ii)) + \"\\n\")\n\n #now the xyz geometry values for the nodes\n glbXyzList = vtk.vtkDoubleArray()\n shareXyzList = vtk.vtkDoubleArray()\n for ii in range(0,numproc):\n numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)\n #if PhactoriDbg(100):\n # myDebugPrint3(\"doing broadcast for process \" + str(ii) + \": numpts: \" + str(numPtsFromProcii) + \"\\n\")\n if ii == mypid:\n #if PhactoriDbg(100):\n #myDebugPrint3(\"I am this process, broadcasting to everyone\\n\")\n if(numPtsFromProcii > 0):\n globalController.Broadcast(inPointXyzs, ii)\n for jj in range(0,numPtsFromProcii*3):\n glbXyzList.InsertNextValue(inPointXyzs.GetValue(jj))\n else:\n #if PhactoriDbg(100):\n # myDebugPrint3(\"I am not this process, receiving broadcast from this process: \" + str(numPtsFromProcii) + \"\\n\")\n if(numPtsFromProcii > 0):\n shareXyzList.SetNumberOfValues(numPtsFromProcii*3)\n #if PhactoriDbg(100):\n # myDebugPrint3(\"returned from broadcast call 2\\n\")\n globalController.Broadcast(shareXyzList, ii)\n for jj in range(0,numPtsFromProcii*3):\n glbXyzList.InsertNextValue(shareXyzList.GetValue(jj))\n #if PhactoriDbg(100):\n # myDebugPrint3(\"glbNodeIdList after broadcasts:\\n\")\n # for ii in range(0, glbXyzList.GetNumberOfValues()):\n # myDebugPrint3(str(ii) + \": \" + str(glbXyzList.GetValue(ii)) + \"\\n\")\n\n return glbNodeIdList, glbXyzList", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def install(\n *,\n console: Optional[Console] = None,\n width: Optional[int] = 100,\n extra_lines: int = 3,\n theme: Optional[str] = None,\n word_wrap: bool = False,\n show_locals: bool = False,\n locals_max_length: int = LOCALS_MAX_LENGTH,\n locals_max_string: int = LOCALS_MAX_STRING,\n locals_hide_dunder: bool = True,\n locals_hide_sunder: Optional[bool] = None,\n indent_guides: bool = True,\n suppress: Iterable[Union[str, ModuleType]] = (),\n max_frames: int = 100,\n) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:\n \"\"\"Install a rich traceback handler.\n\n Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.\n\n\n Args:\n console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.\n width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.\n extra_lines (int, optional): Extra lines of code. Defaults to 3.\n theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick\n a theme appropriate for the platform.\n word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n show_locals (bool, optional): Enable display of local variables. Defaults to False.\n locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to 10.\n locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.\n locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.\n indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n\n Returns:\n Callable: The previous exception handler that was replaced.\n\n \"\"\"\n traceback_console = Console(stderr=True) if console is None else console\n\n locals_hide_sunder = (\n True\n if (traceback_console.is_jupyter and locals_hide_sunder is None)\n else locals_hide_sunder\n )\n\n def excepthook(\n type_: Type[BaseException],\n value: BaseException,\n traceback: Optional[TracebackType],\n ) -> None:\n traceback_console.print(\n Traceback.from_exception(\n type_,\n value,\n traceback,\n width=width,\n extra_lines=extra_lines,\n theme=theme,\n word_wrap=word_wrap,\n show_locals=show_locals,\n locals_max_length=locals_max_length,\n locals_max_string=locals_max_string,\n locals_hide_dunder=locals_hide_dunder,\n locals_hide_sunder=bool(locals_hide_sunder),\n indent_guides=indent_guides,\n suppress=suppress,\n max_frames=max_frames,\n )\n )\n\n def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover\n tb_data = {} # store information about showtraceback call\n default_showtraceback = ip.showtraceback # keep reference of default traceback\n\n def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:\n \"\"\"wrap the default ip.showtraceback to store info for ip._showtraceback\"\"\"\n nonlocal tb_data\n tb_data = kwargs\n default_showtraceback(*args, **kwargs)\n\n def ipy_display_traceback(\n *args: Any, is_syntax: bool = False, **kwargs: Any\n ) -> None:\n \"\"\"Internally called traceback from ip._showtraceback\"\"\"\n nonlocal tb_data\n exc_tuple = ip._get_exc_info()\n\n # do not display trace on syntax error\n tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]\n\n # determine correct tb_offset\n compiled = tb_data.get(\"running_compiled_code\", False)\n tb_offset = tb_data.get(\"tb_offset\", 1 if compiled else 0)\n # remove ipython internal frames from trace with tb_offset\n for _ in range(tb_offset):\n if tb is None:\n break\n tb = tb.tb_next\n\n excepthook(exc_tuple[0], exc_tuple[1], tb)\n tb_data = {} # clear data upon usage\n\n # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work\n # this is also what the ipython docs recommends to modify when subclassing InteractiveShell\n ip._showtraceback = ipy_display_traceback\n # add wrapper to capture tb_data\n ip.showtraceback = ipy_show_traceback\n ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(\n *args, is_syntax=True, **kwargs\n )\n\n try: # pragma: no cover\n # if within ipython, use customized traceback\n ip = get_ipython() # type: ignore[name-defined]\n ipy_excepthook_closure(ip)\n return sys.excepthook\n except Exception:\n # otherwise use default system hook\n old_excepthook = sys.excepthook\n sys.excepthook = excepthook\n return old_excepthook", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def ParseParametersFromJson(self, inJson):\n #if \"filename\" in inJson:\n # self.JsonListFileName = inJson['filename']\n #else:\n # myDebugPrint3AndException(\n # \"PhactoriGeometricCellSampler1:ParseParametersFromJson\\n\"\n # \"Error: must have 'filename' key\\n\")\n\n keyval1 = \"sampling geometry bounding box\"\n if keyval1 in inJson:\n newBB = inJson[keyval1]\n self.CheckBoundingBox(newBB, keyval1,\n \"PhactoriGeometricCellSampler1:ParseParametersFromJson\")\n self.SamplingGeometryBoundingBox = newBB\n\n keyval4 = \"projection axis\"\n if keyval4 in inJson:\n val4 = inJson[keyval4]\n if val4 == \"none\":\n self.ProjectionAxis = -1\n elif val4 == \"x\":\n self.ProjectionAxis = 0\n elif val4 == \"y\":\n self.ProjectionAxis = 1\n elif val4 == \"z\":\n self.ProjectionAxis = 2\n elif int(val4) == 1:\n self.ProjectionAxis = 0\n elif int(val4) == 2:\n self.ProjectionAxis = 1\n elif int(val4) == 3:\n self.ProjectionAxis = 2\n\n keyval5 = \"do programmable filter\"\n if keyval5 in inJson:\n self.DoProgrammableFilterToAddMaskVariable = inJson[keyval5]\n\n self.GeometricSampledCellOutputFilePathManager.ParseOutputFileNameControl(\n inJson, \"geometric sampled cell output file \")\n\n self.DataControlledSampledCellOutputFilePathManager.ParseOutputFileNameControl(\n inJson, \"data controlled sampled cell output file \")\n\n keyval7e = \"export geometric sampled cell data as json file\"\n if keyval7e in inJson:\n self.WriteOutGeometricallySampledCellData = inJson[keyval7e]\n\n keyval7f = \"export data controlled sampled cell data as json file\"\n if keyval7f in inJson:\n self.WriteOutDataControlledSampledCellData = inJson[keyval7f]\n\n keyval8 = \"cell data array names\"\n if keyval8 in inJson:\n self.CellDataArrayNames = inJson[keyval8]\n\n keyval9 = \"cell data array tuple size\"\n if keyval9 in inJson:\n self.CellDataArrayTupleSize = inJson[keyval9]\n\n keyval10 = \"programmable filter output cell variable name\"\n if keyval10 in inJson:\n self.ProgrammableFilterOutputCellVariableName = inJson[keyval10]\n\n keyval11 = \"data controlled sampling method\"\n if keyval11 in inJson:\n self.DataControlledSamplingMethod = inJson[keyval11]\n if self.DataControlledSamplingMethod == \"cells within distance of min/max highest data value cell\":\n keyval11b = \"data controlled distance\"\n if keyval11b not in inJson:\n myDebugPrint3AndException(\"must have 'data controlled distance'\\n\")\n self.DataControlledDistance = inJson[keyval11b]\n elif self.DataControlledSamplingMethod == \"cells with ratio of min/max data value\":\n keyval11b = \"data controlled ratio of min/max\"\n if keyval11b in inJson:\n self.DataControlledRatio = inJson[keyval11b]\n if (self.DataControlledRatio < 0.0) or (self.DataControlledRatio > 1.0):\n myDebugPrint3AndException(\"'data controlled ratio of min/max must be in range [0.0, 1.0]\\n\")\n if PhactoriDbg(100):\n myDebugPrint3(\"self.DataControlledRatio set to \" + str(self.DataControlledRatio) + \"\\n\", 100)\n keyval11c = \"data controlled ratio basis\"\n if keyval11c in inJson:\n self.DataControlledRatioBasis = inJson[keyval11c]\n if (self.DataControlledRatioBasis != \"ratio is from zero to data maximum\") and \\\n (self.DataControlledRatioBasis != \"ratio is from data minimum to data maximum\"):\n myDebugPrint3(\"bad 'data controlled ratio basis'\\n\"\n \"must be one of:\\n\"\n \"'ratio is from zero to data maximum'\\n\"\n \"'ratio is from data minimum to data maximum'\\n\")\n keyval11d = \"collect cells relative to ratio\"\n if keyval11d in inJson:\n self.DataControlledRatioGreaterOrLess = inJson[keyval11d]\n if (self.DataControlledRatioGreaterOrLess != \"cells greater/equal\") and \\\n (self.DataControlledRatioGreaterOrLess != \"cells less/equal\"):\n myDebugPrint3(\"bad 'collect cells relative to ratio'\\n\"\n \"must be one of:\\n\"\n \"'cells greater/equal'\\n\"\n \"'cells less/equal'\\n\")\n elif self.DataControlledSamplingMethod == \"cells within bounding box around min/max highest data value cell\":\n keyval11b = \"data controlled bounding box\"\n if keyval11b in inJson:\n self.DataControlledBoundingBox = inJson[keyval11b]\n self.CheckBoundingBox(self.DataControlledBoundingBox, keyval11b,\n \"PhactoriGeometricCellSampler1:ParseParametersFromJson\")\n else:\n myDebugPrint3AndException(\"bad 'data controlled sampling method'\\n\")\n if PhactoriDbg(100):\n myDebugPrint3(\"self.DataControlledSamplingMethod set to \" + \\\n str(self.DataControlledSamplingMethod) + \"\\n\", 100)\n\n keyval11c = \"data controlled sampling use min or max\"\n if keyval11c in inJson:\n if inJson[keyval11c] == \"max\":\n self.DataControlledUseMinOrMax = \"max\"\n else:\n self.DataControlledUseMinOrMax = \"min\"", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def call_subprocess(\n cmd: Union[List[str], CommandArgs],\n show_stdout: bool = False,\n cwd: Optional[str] = None,\n on_returncode: 'Literal[\"raise\", \"warn\", \"ignore\"]' = \"raise\",\n extra_ok_returncodes: Optional[Iterable[int]] = None,\n extra_environ: Optional[Mapping[str, Any]] = None,\n unset_environ: Optional[Iterable[str]] = None,\n spinner: Optional[SpinnerInterface] = None,\n log_failed_cmd: Optional[bool] = True,\n stdout_only: Optional[bool] = False,\n *,\n command_desc: str,\n) -> str:\n \"\"\"\n Args:\n show_stdout: if true, use INFO to log the subprocess's stderr and\n stdout streams. Otherwise, use DEBUG. Defaults to False.\n extra_ok_returncodes: an iterable of integer return codes that are\n acceptable, in addition to 0. Defaults to None, which means [].\n unset_environ: an iterable of environment variable names to unset\n prior to calling subprocess.Popen().\n log_failed_cmd: if false, failed commands are not logged, only raised.\n stdout_only: if true, return only stdout, else return both. When true,\n logging of both stdout and stderr occurs when the subprocess has\n terminated, else logging occurs as subprocess output is produced.\n \"\"\"\n if extra_ok_returncodes is None:\n extra_ok_returncodes = []\n if unset_environ is None:\n unset_environ = []\n # Most places in pip use show_stdout=False. What this means is--\n #\n # - We connect the child's output (combined stderr and stdout) to a\n # single pipe, which we read.\n # - We log this output to stderr at DEBUG level as it is received.\n # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't\n # requested), then we show a spinner so the user can still see the\n # subprocess is in progress.\n # - If the subprocess exits with an error, we log the output to stderr\n # at ERROR level if it hasn't already been displayed to the console\n # (e.g. if --verbose logging wasn't enabled). This way we don't log\n # the output to the console twice.\n #\n # If show_stdout=True, then the above is still done, but with DEBUG\n # replaced by INFO.\n if show_stdout:\n # Then log the subprocess output at INFO level.\n log_subprocess: Callable[..., None] = subprocess_logger.info\n used_level = logging.INFO\n else:\n # Then log the subprocess output using VERBOSE. This also ensures\n # it will be logged to the log file (aka user_log), if enabled.\n log_subprocess = subprocess_logger.verbose\n used_level = VERBOSE\n\n # Whether the subprocess will be visible in the console.\n showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level\n\n # Only use the spinner if we're not showing the subprocess output\n # and we have a spinner.\n use_spinner = not showing_subprocess and spinner is not None\n\n log_subprocess(\"Running command %s\", command_desc)\n env = os.environ.copy()\n if extra_environ:\n env.update(extra_environ)\n for name in unset_environ:\n env.pop(name, None)\n try:\n proc = subprocess.Popen(\n # Convert HiddenText objects to the underlying str.\n reveal_command_args(cmd),\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,\n cwd=cwd,\n env=env,\n errors=\"backslashreplace\",\n )\n except Exception as exc:\n if log_failed_cmd:\n subprocess_logger.critical(\n \"Error %s while executing command %s\",\n exc,\n command_desc,\n )\n raise\n all_output = []\n if not stdout_only:\n assert proc.stdout\n assert proc.stdin\n proc.stdin.close()\n # In this mode, stdout and stderr are in the same pipe.\n while True:\n line: str = proc.stdout.readline()\n if not line:\n break\n line = line.rstrip()\n all_output.append(line + \"\\n\")\n\n # Show the line immediately.\n log_subprocess(line)\n # Update the spinner.\n if use_spinner:\n assert spinner\n spinner.spin()\n try:\n proc.wait()\n finally:\n if proc.stdout:\n proc.stdout.close()\n output = \"\".join(all_output)\n else:\n # In this mode, stdout and stderr are in different pipes.\n # We must use communicate() which is the only safe way to read both.\n out, err = proc.communicate()\n # log line by line to preserve pip log indenting\n for out_line in out.splitlines():\n log_subprocess(out_line)\n all_output.append(out)\n for err_line in err.splitlines():\n log_subprocess(err_line)\n all_output.append(err)\n output = out\n\n proc_had_error = proc.returncode and proc.returncode not in extra_ok_returncodes\n if use_spinner:\n assert spinner\n if proc_had_error:\n spinner.finish(\"error\")\n else:\n spinner.finish(\"done\")\n if proc_had_error:\n if on_returncode == \"raise\":\n error = InstallationSubprocessError(\n command_description=command_desc,\n exit_code=proc.returncode,\n output_lines=all_output if not showing_subprocess else None,\n )\n if log_failed_cmd:\n subprocess_logger.error(\"%s\", error, extra={\"rich\": True})\n subprocess_logger.verbose(\n \"[bold magenta]full command[/]: [blue]%s[/]\",\n escape(format_command_args(cmd)),\n extra={\"markup\": True},\n )\n subprocess_logger.verbose(\n \"[bold magenta]cwd[/]: %s\",\n escape(cwd or \"[inherit]\"),\n extra={\"markup\": True},\n )\n\n raise error\n elif on_returncode == \"warn\":\n subprocess_logger.warning(\n 'Command \"%s\" had error code %s in %s',\n command_desc,\n proc.returncode,\n cwd,\n )\n elif on_returncode == \"ignore\":\n pass\n else:\n raise ValueError(f\"Invalid value: on_returncode={on_returncode!r}\")\n return output", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def test_api_v2_tasks_annotations_dump_and_upload_with_datumaro(self):\n test_name = self._testMethodName\n # get formats\n dump_formats = dm.views.get_export_formats()\n include_images_params = (False, True)\n for dump_format, include_images in itertools.product(dump_formats, include_images_params):\n if dump_format.ENABLED:\n dump_format_name = dump_format.DISPLAY_NAME\n with self.subTest(dump_format_name):\n if dump_format_name in [\n \"MOT 1.1\",\n \"CamVid 1.0\", # issue #2840 and changed points values\n \"MOTS PNG 1.0\", # changed points values\n \"Segmentation mask 1.1\", # changed points values\n \"ICDAR Segmentation 1.0\", # changed points values\n \"Open Images V6 1.0\", # changed points values\n 'Kitti Raw Format 1.0',\n 'Sly Point Cloud Format 1.0',\n 'KITTI 1.0', # changed points values\n 'Cityscapes 1.0', # changed points value\n 'Datumaro 3D 1.0'\n ]:\n self.skipTest(\"Format is fail\")\n\n # create task\n images = self._generate_task_images(3)\n if dump_format_name in [\n \"Market-1501 1.0\", \"Cityscapes 1.0\",\n \"ICDAR Localization 1.0\", \"ICDAR Recognition 1.0\",\n \"ICDAR Segmentation 1.0\", \"COCO Keypoints 1.0\",\n \"YOLOv8 Pose 1.0\",\n ]:\n task = self._create_task(tasks[dump_format_name], images)\n else:\n task = self._create_task(tasks[\"main\"], images)\n\n # create annotations\n if dump_format_name in DEFAULT_ATTRIBUTES_FORMATS + [\n \"MOT 1.1\", \"LFW 1.0\",\n \"Open Images V6 1.0\", \"Datumaro 1.0\", \"KITTI 1.0\",\n ]:\n self._create_annotations(task, dump_format_name, \"default\")\n else:\n self._create_annotations(task, dump_format_name, \"random\")\n\n task_id = task[\"id\"]\n data_from_task_before_upload = self._get_data_from_task(task_id, include_images)\n\n # dump annotations\n url = self._generate_url_dump_tasks_annotations(task_id)\n with TestDir() as test_dir:\n file_zip_name = osp.join(test_dir, f'{test_name}_{dump_format_name}.zip')\n data = {\n \"format\": dump_format_name,\n }\n self._download_file(url, data, self.admin, file_zip_name)\n self._check_downloaded_file(file_zip_name)\n\n # remove annotations\n self._remove_annotations(url, self.admin)\n\n # upload annotations\n if dump_format_name in [\"CVAT for images 1.1\", \"CVAT for video 1.1\"]:\n upload_format_name = \"CVAT 1.1\"\n else:\n upload_format_name = dump_format_name\n url = self._generate_url_upload_tasks_annotations(task_id, upload_format_name)\n with open(file_zip_name, 'rb') as binary_file:\n self._upload_file(url, binary_file, self.admin)\n\n # equals annotations\n data_from_task_after_upload = self._get_data_from_task(task_id, include_images)\n compare_datasets(data_from_task_before_upload, data_from_task_after_upload)", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def getDriverInstalledDate():\n\n\tdef extractDate(value):\n\t\tmatch = search('[0-9]{8}', value)\n\t\tif match:\n\t\t\treturn match[0]\n\t\telse:\n\t\t\treturn value\n\n\tfilenames = glob(\"/var/lib/opkg/info/*dvb-modules*.control\")\n\tif filenames:\n\t\tlines = fileReadLines(filenames[0], source=MODULE_NAME)\n\t\tif lines:\n\t\t\tfor line in lines:\n\t\t\t\tif line[0:8] == \"Version:\":\n\t\t\t\t\treturn extractDate(line)\n\tfilenames = glob(\"/var/lib/opkg/info/*dvb-proxy*.control\")\n\tif filenames:\n\t\tlines = fileReadLines(filenames[0], source=MODULE_NAME)\n\t\tif lines:\n\t\t\tfor line in lines:\n\t\t\t\tif line[0:8] == \"Version:\":\n\t\t\t\t\treturn extractDate(line)\n\tfilenames = glob(\"/var/lib/opkg/info/*platform-util*.control\")\n\tif filenames:\n\t\tlines = fileReadLines(filenames[0], source=MODULE_NAME)\n\t\tif lines:\n\t\t\tfor line in lines:\n\t\t\t\tif line[0:8] == \"Version:\":\n\t\t\t\t\treturn extractDate(line)\n\treturn _(\"Unknown\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def applySkin(self, desktop, screen):\n\t\tif self.skinAttributes is not None:\n\t\t\tforegroundColor = None\n\t\t\tbackgroundColor = None\n\t\t\tattribs = []\n\t\t\tfor (attrib, value) in self.skinAttributes:\n\t\t\t\tif attrib == \"foregroundColors\":\n\t\t\t\t\tcolors = value.split(',')\n\t\t\t\t\tfor color in colors:\n\t\t\t\t\t\tself.foreColors.append(parseColor(color))\n\t\t\t\t\tif not foregroundColor:\n\t\t\t\t\t\tforegroundColor = colors[0]\n\t\t\t\telif attrib == \"backgroundColors\":\n\t\t\t\t\tcolors = value.split(',')\n\t\t\t\t\tfor color in colors:\n\t\t\t\t\t\tself.backColors.append(parseColor(color))\n\t\t\t\t\tif not backgroundColor:\n\t\t\t\t\t\tbackgroundColor = colors[0]\n\t\t\t\telif attrib == \"backgroundColor\":\n\t\t\t\t\tbackgroundColor = value\n\t\t\t\telif attrib == \"foregroundColor\":\n\t\t\t\t\tforegroundColor = value\n\t\t\t\telse:\n\t\t\t\t\tattribs.append((attrib, value))\n\t\t\tif foregroundColor:\n\t\t\t\tattribs.append((\"foregroundColor\", foregroundColor))\n\t\t\tif backgroundColor:\n\t\t\t\tattribs.append((\"backgroundColor\", backgroundColor))\n\t\t\tself.skinAttributes = attribs\n\t\treturn GUIComponent.applySkin(self, desktop, screen)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def createItems(self):\n\t\tguiDirectory, guiSkin = split(config.skin.primary_skin.value)\n\t\tguiSkin = guiSkin if guiSkin else \"skin.xml\"\n\t\tchoices = []\n\t\tfor directory in [x for x in listdir(self.guiRoot) if isdir(join(self.guiRoot, x))]:\n\t\t\tpath = join(directory, \"skin.xml\")\n\t\t\tif exists(join(self.guiRoot, path)):\n\t\t\t\tlabel = _(\"< Default >\") if directory == \"skin_default\" else directory\n\t\t\t\tif directory == \"MetrixHD\":\n\t\t\t\t\tif isfile(join(self.guiRoot, directory, \"skin.MySkin.xml\")):\n\t\t\t\t\t\tguiSkin = \"skin.MySkin.xml\"\n\t\t\t\t\tpath = join(directory, guiSkin)\n\t\t\t\tchoices.append((path, label))\n\t\tconfig.skin.guiSkin = NoSave(ConfigSelection(default=config.skin.primary_skin.value, choices=choices))\n\t\tlcdDirectory, lcdSkin = split(config.skin.display_skin.value)\n\t\tlcdSkin = lcdSkin if lcdSkin else \"skin_display.xml\"\n\t\tchoices = []\n\t\tif exists(self.lcdRoot):\n\t\t\tfor skin in self.DISPLAY_SKINS.keys():\n\t\t\t\tpath = join(self.lcdRoot, skin)\n\t\t\t\tif exists(path):\n\t\t\t\t\tchoices.append((skin, self.DISPLAY_SKINS[skin]))\n\t\t\tfor directory in [x for x in listdir(self.lcdRoot) if isdir(join(self.lcdRoot, x))]:\n\t\t\t\tpath = join(directory, \"skin_display.xml\")\n\t\t\t\tif exists(join(self.lcdRoot, path)):\n\t\t\t\t\tchoices.append((path, directory))\n\t\telse:\n\t\t\tchoices.append((config.skin.display_skin.value, \"\"))\n\t\tconfig.skin.lcdSkin = NoSave(ConfigSelection(default=config.skin.display_skin.value, choices=choices))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def split_blocks_at_uninits(\n blocks: list[BasicBlock], pre_must_defined: AnalysisDict[Value]\n) -> list[BasicBlock]:\n new_blocks: list[BasicBlock] = []\n\n init_registers = []\n init_registers_set = set()\n bitmap_registers: list[Register] = [] # Init status bitmaps\n bitmap_backed: list[Register] = [] # These use bitmaps to track init status\n\n # First split blocks on ops that may raise.\n for block in blocks:\n ops = block.ops\n block.ops = []\n cur_block = block\n new_blocks.append(cur_block)\n\n for i, op in enumerate(ops):\n defined = pre_must_defined[block, i]\n for src in op.unique_sources():\n # If a register operand is not guaranteed to be\n # initialized is an operand to something other than a\n # check that it is defined, insert a check.\n\n # Note that for register operand in a LoadAddress op,\n # we should be able to use it without initialization\n # as we may need to use its address to update itself\n if (\n isinstance(src, Register)\n and src not in defined\n and not (isinstance(op, Branch) and op.op == Branch.IS_ERROR)\n and not isinstance(op, LoadAddress)\n ):\n new_block, error_block = BasicBlock(), BasicBlock()\n new_block.error_handler = error_block.error_handler = cur_block.error_handler\n new_blocks += [error_block, new_block]\n\n if src not in init_registers_set:\n init_registers.append(src)\n init_registers_set.add(src)\n\n if not src.type.error_overlap:\n cur_block.ops.append(\n Branch(\n src,\n true_label=error_block,\n false_label=new_block,\n op=Branch.IS_ERROR,\n line=op.line,\n )\n )\n else:\n # We need to use bitmap for this one.\n check_for_uninit_using_bitmap(\n cur_block.ops,\n src,\n bitmap_registers,\n bitmap_backed,\n error_block,\n new_block,\n op.line,\n )\n\n raise_std = RaiseStandardError(\n RaiseStandardError.UNBOUND_LOCAL_ERROR,\n f'local variable \"{src.name}\" referenced before assignment',\n op.line,\n )\n error_block.ops.append(raise_std)\n error_block.ops.append(Unreachable())\n cur_block = new_block\n cur_block.ops.append(op)\n\n if bitmap_backed:\n update_register_assignments_to_set_bitmap(new_blocks, bitmap_registers, bitmap_backed)\n\n if init_registers:\n new_ops: list[Op] = []\n for reg in init_registers:\n err = LoadErrorValue(reg.type, undefines=True)\n new_ops.append(err)\n new_ops.append(Assign(reg, err))\n for reg in bitmap_registers:\n new_ops.append(Assign(reg, Integer(0, bitmap_rprimitive)))\n new_blocks[0].ops[0:0] = new_ops\n\n return new_blocks", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@property\n def strong_connections(self):\n # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm\n index_counter = [0]\n stack = []\n lowlinks = {}\n index = {}\n result = []\n\n graph = self._succs\n\n def strongconnect(node):\n # set the depth index for this node to the smallest unused index\n index[node] = index_counter[0]\n lowlinks[node] = index_counter[0]\n index_counter[0] += 1\n stack.append(node)\n\n # Consider successors\n try:\n successors = graph[node]\n except Exception:\n successors = []\n for successor in successors:\n if successor not in lowlinks:\n # Successor has not yet been visited\n strongconnect(successor)\n lowlinks[node] = min(lowlinks[node], lowlinks[successor])\n elif successor in stack:\n # the successor is in the stack and hence in the current\n # strongly connected component (SCC)\n lowlinks[node] = min(lowlinks[node], index[successor])\n\n # If `node` is a root node, pop the stack and generate an SCC\n if lowlinks[node] == index[node]:\n connected_component = []\n\n while True:\n successor = stack.pop()\n connected_component.append(successor)\n if successor == node:\n break\n component = tuple(connected_component)\n # storing the result\n result.append(component)\n\n for node in graph:\n if node not in lowlinks:\n strongconnect(node)\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def merge(self, items, fn, same, new_entry):\n \"\"\"Helper method for updating the contents of the directory.\n\n Takes a list describing the new contents of the directory, reuse\n entries that are the same in both the old and new lists, create new\n entries, and delete old entries missing from the new list.\n\n Arguments:\n * items: Iterable --- New directory contents\n\n * fn: Callable --- Takes an entry in 'items' and return the desired file or\n directory name, or None if this entry should be skipped\n\n * same: Callable --- Compare an existing entry (a File or Directory\n object) with an entry in the items list to determine whether to keep\n the existing entry.\n\n * new_entry: Callable --- Create a new directory entry (File or Directory\n object) from an entry in the items list.\n\n \"\"\"\n\n oldentries = self._entries\n self._entries = {}\n changed = False\n for i in items:\n name = self.sanitize_filename(fn(i))\n if not name:\n continue\n if name in oldentries:\n ent = oldentries[name]\n if same(ent, i) and ent.parent_inode == self.inode:\n # move existing directory entry over\n self._entries[name] = ent\n del oldentries[name]\n self.inodes.inode_cache.touch(ent)\n\n for i in items:\n name = self.sanitize_filename(fn(i))\n if not name:\n continue\n if name not in self._entries:\n # create new directory entry\n ent = new_entry(i)\n if ent is not None:\n self._entries[name] = self.inodes.add_entry(ent)\n # need to invalidate this just in case there was a\n # previous entry that couldn't be moved over or a\n # lookup that returned file not found and cached\n # a negative result\n self.inodes.invalidate_entry(self, name)\n changed = True\n _logger.debug(\"Added entry '%s' as inode %i to parent inode %i\", name, ent.inode, self.inode)\n\n # delete any other directory entries that were not in found in 'items'\n for name, ent in oldentries.items():\n _logger.debug(\"Detaching entry '%s' from parent_inode %i\", name, self.inode)\n self.inodes.invalidate_entry(self, name)\n self.inodes.del_entry(ent)\n changed = True\n\n if changed:\n self._mtime = time.time()\n self.inodes.inode_cache.update_cache_size(self)\n\n self.fresh()", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]:\n \"\"\"Uses mypy to construct stub objects for the given modules.\n\n This sets global state that ``get_stub`` can access.\n\n Returns all modules we might want to check. If ``find_submodules`` is False, this is equal\n to ``modules``.\n\n :param modules: List of modules to build stubs for.\n :param options: Mypy options for finding and building stubs.\n :param find_submodules: Whether to attempt to find submodules of the given modules as well.\n\n \"\"\"\n data_dir = mypy.build.default_data_dir()\n search_path = mypy.modulefinder.compute_search_paths([], options, data_dir)\n find_module_cache = mypy.modulefinder.FindModuleCache(\n search_path, fscache=None, options=options\n )\n\n all_modules = []\n sources = []\n for module in modules:\n all_modules.append(module)\n if not find_submodules:\n module_path = find_module_cache.find_module(module)\n if not isinstance(module_path, str):\n # test_module will yield an error later when it can't find stubs\n continue\n sources.append(mypy.modulefinder.BuildSource(module_path, module, None))\n else:\n found_sources = find_module_cache.find_modules_recursive(module)\n sources.extend(found_sources)\n # find submodules via mypy\n all_modules.extend(s.module for s in found_sources if s.module not in all_modules)\n # find submodules via pkgutil\n try:\n runtime = silent_import_module(module)\n all_modules.extend(\n m.name\n for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + \".\")\n if m.name not in all_modules\n )\n except KeyboardInterrupt:\n raise\n except BaseException:\n pass\n\n if sources:\n try:\n res = mypy.build.build(sources=sources, options=options)\n except mypy.errors.CompileError as e:\n raise StubtestFailure(f\"failed mypy compile:\\n{e}\") from e\n if res.errors:\n raise StubtestFailure(\"mypy build errors:\\n\" + \"\\n\".join(res.errors))\n\n global _all_stubs\n _all_stubs = res.files\n\n return all_modules", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def SetCameraLookAtPointAndLookDirection(inParaViewRenderView, \\\n inLookDirection, \\\n inImageSettings, \\\n inFocalPoint = None, \\\n inEyeToFocalPointDistance = None, \\\n inEyePositionFactor = 1.0, \\\n inViewUp=[0.0,1.0,0.0], \\\n inCameraViewAngle = 30.0, \\\n inViewBounds = None,\n inPhactoriCamera = None):\n \"\"\"Set up camera with position, look at point, and positioning factor\n\n Sets the current camera view by looking at a focal point (inFocalPoint)\n along a specified vector (inLookDirection). The distance from the focal\n point is set using twice the largest of the data bounding box dimensions\n multiplied by inEyePositionFactor. To see the whole of the data,\n inEyePositionFactor can be about 1.0, although trying different values\n will give you different filling of the screen and 'zooming' into the focal\n point, while values greater than 1.0 can be used to zoom out, possibly to\n bring the entire dataset into the image. If inEyeToFocalPointDistance is\n something other than None, this distance will be used instead of the\n bounding box of the data. If inFocalPoint is None, then\n the center of the data bounds will be used as a focal point. inViewBounds\n allows calling routine to pass along data bounds or other viewing bounds\n which are used to calculate the viewing distance from the focal point\n and the focal point if they are not supplied. If inEyeToFocalPointDistance\n is not None and inFocalPoint is not None, than inViewBounds will not\n be used and the global data bounds will not be obtained.\n example: SetCameraLookAtPointAndLookDirection([5.0, 4.0, 3.0],\n [1.0, 1.0, 1.0], 1.5, [0.0, 1.0, 0.0])\n \"\"\"\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetCameraLookAtPointAndLookDirection entered\\n\", 100);\n\n #check for look view up same as look direction\n #need to do better check here\n if CheckForParallelVector(inLookDirection, inViewUp):\n inViewUp = [0.0, 0.0, 1.0]\n if CheckForParallelVector(inLookDirection, inViewUp):\n inViewUp = [0.0, 1.0, 0.0]\n\n #find maximum data dimension, then multiply by inEyePositionFactor\n if(inFocalPoint == None):\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n inFocalPoint = [ (inViewBounds[1] + inViewBounds[0]) * 0.5, \\\n (inViewBounds[3] + inViewBounds[2]) * 0.5, \\\n (inViewBounds[5] + inViewBounds[4]) * 0.5 ]\n\n if inEyeToFocalPointDistance != None:\n eyeToFocalPointDistance = inEyeToFocalPointDistance\n else:\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n #eyeToFocalPointDistance = GetMaximumDimensionFromBounds(inViewBounds)\n #eyeToFocalPointDistance *= inEyePositionFactor\n eyeToFocalPointDistance = CalcRelativeCameraDistance2(inFocalPoint,\n inLookDirection, inViewUp, inCameraViewAngle, inImageSettings,\n inViewBounds)\n eyeToFocalPointDistance *= inEyePositionFactor\n\n\n if PhactoriDbg():\n myDebugPrint3(\" eyeToFocalPointDistance: \" + str(eyeToFocalPointDistance) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inFocalPoint: \" + str(inFocalPoint) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inLookDirection: \" + str(inLookDirection) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inEyePositionFactor: \" + str(inEyePositionFactor) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inViewUp: \" + str(inViewUp) + \"\\n\")\n\n #find eye position based on focal point, distance to eye point, and look direction\n xx = inLookDirection[0]\n yy = inLookDirection[1]\n zz = inLookDirection[2]\n lookDirectionMagnitude = math.sqrt(xx*xx + yy*yy + zz*zz)\n #lookDirectionMagnitude = 1.0\n if PhactoriDbg():\n myDebugPrint3(\" lookDirectionMagnitude: \" + str(lookDirectionMagnitude) + \"\\n\")\n xx = xx / lookDirectionMagnitude\n yy = yy / lookDirectionMagnitude\n zz = zz / lookDirectionMagnitude\n eyePosition = [inFocalPoint[0] - xx * eyeToFocalPointDistance, \\\n inFocalPoint[1] - yy * eyeToFocalPointDistance, \\\n inFocalPoint[2] - zz * eyeToFocalPointDistance]\n if PhactoriDbg():\n myDebugPrint3(\" eyePosition: \" + str(eyePosition) + \"\\n\")\n\n\n useNewClippingCalc = True\n if useNewClippingCalc:\n eyeToFocalPointDist = vecDistance(eyePosition, inFocalPoint)\n clippingRange = [0.01 * eyeToFocalPointDist, 100.0 * eyeToFocalPointDist]\n else:\n clippingRange = [0.01 * lookDirectionMagnitude, 100.0 * lookDirectionMagnitude]\n\n localUseParallelProjection = False\n localParallelScale = 1.0\n if inPhactoriCamera != None:\n if inPhactoriCamera.mUseParallelProjection:\n localUseParallelProjection = True\n if inPhactoriCamera.mParallelScaleAbsoluteOrRelative == 0:\n localParallelScale = inPhactoriCamera.mParallelScale\n if PhactoriDbg():\n myDebugPrint3(\"absolute parallel scale: \" + \\\n str(localParallelScale) + \"\\n\")\n else:\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n #for relative case, we are using the diagonal of the\n #bounding box to determine the parallel scale; other algorithms might\n #be to use the longest bounding box side, or determine all bounding\n #box corner positions from camera position and use the greatest\n #vertical or horizontal extent of those points\n dimx = inViewBounds[1] - inViewBounds[0]\n dimy = inViewBounds[3] - inViewBounds[2]\n dimz = inViewBounds[5] - inViewBounds[4]\n maxbbdim = math.sqrt(dimx*dimx + dimy*dimy + dimz*dimz)\n localParallelScale = maxbbdim * 0.5 * 1.05\n localParallelScale *= inPhactoriCamera.mParallelScale\n if PhactoriDbg():\n myDebugPrint3(\"relative parallel scale: \" + \\\n str(localParallelScale) + \"\\n\")\n\n SetCameraViewExplicitly(inParaViewRenderView, eyePosition, inFocalPoint,\n clippingRange, inViewUp, inCameraViewAngle, inViewBounds,\n inPhactoriCamera, localUseParallelProjection, localParallelScale)\n\n if inPhactoriCamera != None:\n inPhactoriCamera.HandleLockingOption(eyePosition, inFocalPoint)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetCameraLookAtPointAndLookDirection returning\\n\", 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def setupChannel(deviceset_url, options):\n i = 0\n\n settings = callAPI(deviceset_url + \"/channel\", \"POST\", None, {\"channelType\": options.channel_id, \"direction\": 0}, \"Create demod\")\n if settings is None:\n exit(-1)\n\n settings = callAPI(deviceset_url + \"/channel/%d/settings\" % i, \"GET\", None, None, \"Get demod settings\")\n if settings is None:\n exit(-1)\n\n if options.channel_id == \"NFMDemod\":\n settings[\"NFMDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"NFMDemodSettings\"][\"afBandwidth\"] = options.af_bw * 1000\n settings[\"NFMDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"NFMDemodSettings\"][\"volume\"] = options.volume\n settings[\"NFMDemodSettings\"][\"squelch\"] = options.squelch_db # deci-Bels\n settings[\"NFMDemodSettings\"][\"squelchGate\"] = options.squelch_gate // 10 # 10's of ms\n settings[\"NFMDemodSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"BFMDemod\":\n settings[\"BFMDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"BFMDemodSettings\"][\"afBandwidth\"] = options.af_bw * 1000\n settings[\"BFMDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"BFMDemodSettings\"][\"volume\"] = options.volume\n settings[\"BFMDemodSettings\"][\"squelch\"] = options.squelch_db # dB\n settings[\"BFMDemodSettings\"][\"audioStereo\"] = 1 if options.stereo else 0\n settings[\"BFMDemodSettings\"][\"lsbStereo\"] = 1 if options.lsb_stereo else 0\n settings[\"BFMDemodSettings\"][\"rdsActive\"] = 1 if options.rds else 0\n settings[\"BFMDemodSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"WFMDemod\":\n settings[\"WFMDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"WFMDemodSettings\"][\"afBandwidth\"] = options.af_bw * 1000\n settings[\"WFMDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"WFMDemodSettings\"][\"volume\"] = options.volume\n settings[\"WFMDemodSettings\"][\"squelch\"] = options.squelch_db # dB\n settings[\"WFMDemodSettings\"][\"audioMute\"] = 0\n settings[\"WFMDemodSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"AMDemod\":\n settings[\"AMDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"AMDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"AMDemodSettings\"][\"volume\"] = options.volume\n settings[\"AMDemodSettings\"][\"squelch\"] = options.squelch_db\n settings[\"AMDemodSettings\"][\"title\"] = \"Channel %d\" % i\n settings[\"AMDemodSettings\"][\"bandpassEnable\"] = 1 # bandpass filter\n elif options.channel_id == \"SSBDemod\":\n settings[\"SSBDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"SSBDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"SSBDemodSettings\"][\"lowCutoff\"] = -300 if options.rf_bw < 0 else 300\n settings[\"SSBDemodSettings\"][\"audioBinaural\"] = 1\n settings[\"SSBDemodSettings\"][\"audioFlipChannels\"] = 0\n settings[\"SSBDemodSettings\"][\"dsb\"] = 0\n settings[\"SSBDemodSettings\"][\"audioMute\"] = 0\n settings[\"SSBDemodSettings\"][\"agc\"] = 1\n settings[\"SSBDemodSettings\"][\"agcClamping\"] = 0\n settings[\"SSBDemodSettings\"][\"agcTimeLog2\"] = 8\n settings[\"SSBDemodSettings\"][\"agcPowerThreshold\"] = options.squelch_db\n settings[\"SSBDemodSettings\"][\"agcThresholdGate\"] = 4\n settings[\"SSBDemodSettings\"][\"volume\"] = options.volume\n settings[\"SSBDemodSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"DSDDemod\":\n settings[\"DSDDemodSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"DSDDemodSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"DSDDemodSettings\"][\"volume\"] = options.volume\n settings[\"DSDDemodSettings\"][\"squelch\"] = options.squelch_db\n settings[\"DSDDemodSettings\"][\"baudRate\"] = options.baud_rate\n settings[\"DSDDemodSettings\"][\"fmDeviation\"] = options.fm_deviation\n settings[\"DSDDemodSettings\"][\"enableCosineFiltering\"] = 1\n settings[\"DSDDemodSettings\"][\"pllLock\"] = 1\n settings[\"DSDDemodSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"UDPSink\":\n settings[\"UDPSinkSettings\"][\"inputFrequencyOffset\"] = options.channel_freq\n settings[\"UDPSinkSettings\"][\"rfBandwidth\"] = options.rf_bw\n settings[\"UDPSinkSettings\"][\"volume\"] = options.volume\n settings[\"UDPSinkSettings\"][\"squelchDB\"] = options.squelch_db\n settings[\"UDPSinkSettings\"][\"channelMute\"] = 0\n settings[\"UDPSinkSettings\"][\"title\"] = \"Channel %d\" % i\n elif options.channel_id == \"RemoteSink\":\n settings[\"RemoteSinkSettings\"][\"title\"] = \"Channel %d\" % i\n if options.remote_address:\n settings[\"RemoteSinkSettings\"][\"dataAddress\"] = options.remote_address\n if options.remote_port:\n settings[\"RemoteSinkSettings\"][\"dataPort\"] = options.remote_port\n if options.remote_fec:\n settings[\"RemoteSinkSettings\"][\"nbFECBlocks\"] = options.remote_fec\n\n r = callAPI(deviceset_url + \"/channel/%d/settings\" % i, \"PATCH\", None, settings, \"Change demod\")\n if r is None:\n exit(-1)", "smellKey": "S3776", "smellId": null, "repo": "f4exb_sdrangel", "language": "python"} {"function": "def read(self):\n result = {}\n\n if os.path.exists(self.filename):\n repository = self.url or self.DEFAULT_REPOSITORY\n\n config = configparser.RawConfigParser()\n config.read(self.filename)\n sections = config.sections()\n if 'distutils' in sections:\n # let's get the list of servers\n index_servers = config.get('distutils', 'index-servers')\n _servers = [\n server.strip() for server in index_servers.split('\\n')\n if server.strip() != ''\n ]\n if _servers == []:\n # nothing set, let's try to get the default pypi\n if 'pypi' in sections:\n _servers = ['pypi']\n else:\n for server in _servers:\n result = {'server': server}\n result['username'] = config.get(server, 'username')\n\n # optional params\n for key, default in (('repository',\n self.DEFAULT_REPOSITORY),\n ('realm', self.DEFAULT_REALM),\n ('password', None)):\n if config.has_option(server, key):\n result[key] = config.get(server, key)\n else:\n result[key] = default\n\n # work around people having \"repository\" for the \"pypi\"\n # section of their config set to the HTTP (rather than\n # HTTPS) URL\n if (server == 'pypi' and repository\n in (self.DEFAULT_REPOSITORY, 'pypi')):\n result['repository'] = self.DEFAULT_REPOSITORY\n elif (result['server'] != repository\n and result['repository'] != repository):\n result = {}\n elif 'server-login' in sections:\n # old format\n server = 'server-login'\n if config.has_option(server, 'repository'):\n repository = config.get(server, 'repository')\n else:\n repository = self.DEFAULT_REPOSITORY\n result = {\n 'username': config.get(server, 'username'),\n 'password': config.get(server, 'password'),\n 'repository': repository,\n 'server': server,\n 'realm': self.DEFAULT_REALM\n }\n return result", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _copy_script(self, script, filenames):\n adjust = False\n script = os.path.join(self.source_dir, convert_path(script))\n outname = os.path.join(self.target_dir, os.path.basename(script))\n if not self.force and not self._fileop.newer(script, outname):\n logger.debug('not copying %s (up-to-date)', script)\n return\n\n # Always open the file, but ignore failures in dry-run mode --\n # that way, we'll get accurate feedback if we can read the\n # script.\n try:\n f = open(script, 'rb')\n except IOError: # pragma: no cover\n if not self.dry_run:\n raise\n f = None\n else:\n first_line = f.readline()\n if not first_line: # pragma: no cover\n logger.warning('%s is an empty file (skipping)', script)\n return\n\n match = FIRST_LINE_RE.match(first_line.replace(b'\\r\\n', b'\\n'))\n if match:\n adjust = True\n post_interp = match.group(1) or b''\n\n if not adjust:\n if f:\n f.close()\n self._fileop.copy_file(script, outname)\n if self.set_mode:\n self._fileop.set_executable_mode([outname])\n filenames.append(outname)\n else:\n logger.info('copying and adjusting %s -> %s', script,\n self.target_dir)\n if not self._fileop.dry_run:\n encoding, lines = detect_encoding(f.readline)\n f.seek(0)\n shebang = self._get_shebang(encoding, post_interp)\n if b'pythonw' in first_line: # pragma: no cover\n ext = 'pyw'\n else:\n ext = 'py'\n n = os.path.basename(outname)\n self._write_script([n], shebang, f.read(), filenames, ext)\n if f:\n f.close()", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def msg_handler(m, a):\n\ttry:\n\t\te, attr = genl.py_genlmsg_parse(nl.nlmsg_hdr(m), 0,\n\t\t\t\t\t\tnl80211.NL80211_ATTR_MAX, None)\n\t\tif nl80211.NL80211_ATTR_WIPHY in attr:\n\t\t\tthiswiphy = nl.nla_get_u32(attr[nl80211.NL80211_ATTR_WIPHY])\n\t\t\tprint(\"phy#%d\" % thiswiphy)\n\t\tif nl80211.NL80211_ATTR_IFNAME in attr:\n\t\t\tprint(\"\\tinterface %s\" % nl.nla_get_string(attr[nl80211.NL80211_ATTR_IFNAME]));\n\t\tif nl80211.NL80211_ATTR_IFINDEX in attr:\n\t\t\tprint(\"\\tifindex %d\" % nl.nla_get_u32(attr[nl80211.NL80211_ATTR_IFINDEX]))\n\t\tif nl80211.NL80211_ATTR_WDEV in attr:\n\t\t\tprint(\"\\twdev 0x%lx\" % nl.nla_get_u64(attr[nl80211.NL80211_ATTR_WDEV]))\n\t\tif nl80211.NL80211_ATTR_MAC in attr:\n\t\t\tprint(\"\\tmac %02x:%02x:%02x:%02x:%02x:%02x\" % tuple(nl.nla_data(attr[nl80211.NL80211_ATTR_MAC])))\n\t\tif nl80211.NL80211_ATTR_SSID in attr:\n\t\t\tprint(\"\\tssid \", nl.nla_data(attr[nl80211.NL80211_ATTR_SSID]))\n\t\tif nl80211.NL80211_ATTR_IFTYPE in attr:\n\t\t\tiftype = nl.nla_get_u32(attr[nl80211.NL80211_ATTR_IFTYPE])\n\t\t\tprint(\"\\ttype %s\" % nl80211.nl80211_iftype2str[iftype])\n\t\tif nl80211.NL80211_ATTR_WIPHY_FREQ in attr:\n\t\t\tfreq = nl.nla_get_u32(attr[nl80211.NL80211_ATTR_WIPHY_FREQ])\n\n\t\t\tsys.stdout.write(\"\\tfreq %d MHz\" % freq);\n\n\t\t\tif nl80211.NL80211_ATTR_CHANNEL_WIDTH in attr:\n\t\t\t\tchanw = nl.nla_get_u32(attr[nl80211.NL80211_ATTR_CHANNEL_WIDTH])\n\t\t\t\tsys.stdout.write(\", width: %s\" % nl80211.nl80211_chan_width2str[chanw])\n\t\t\t\tif nl80211.NL80211_ATTR_CENTER_FREQ1 in attr:\n\t\t\t\t\tsys.stdout.write(\", center1: %d MHz\" %\n\t\t\t\t\t\tnl.nla_get_u32(attr[nl80211.NL80211_ATTR_CENTER_FREQ1]))\n\t\t\t\tif nl80211.NL80211_ATTR_CENTER_FREQ2 in attr:\n\t\t\t\t\tsys.stdout.write(\", center2: %d MHz\" %\n\t\t\t\t\t\tnl.nla_get_u32(attr[nl80211.NL80211_ATTR_CENTER_FREQ2]))\n\t\t\telif nl80211.NL80211_ATTR_WIPHY_CHANNEL_TYPE in attr:\n\t\t\t\tchannel_type = nl.nla_get_u32(attr[nl80211.NL80211_ATTR_WIPHY_CHANNEL_TYPE])\n\t\t\t\tsys.stdout.write(\" %s\" % nl80211.nl80211_channel_type2str(channel_type));\n\n\t\t\tsys.stdout.write(\"\\n\");\n\t\treturn nl.NL_SKIP;\n\texcept Exception as e:\n\t\t(t,v,tb) = sys.exc_info()\n\t\tprint v.message\n\t\ttraceback.print_tb(tb)", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l1", "language": "python"} {"function": "def upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"boefje_config\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"settings\", sa.String(length=512), nullable=False, server_default=\"{}\"),\n sa.Column(\"enabled\", sa.Boolean(), nullable=False, server_default=\"false\"),\n sa.Column(\"boefje_id\", sa.Integer(), nullable=False),\n sa.Column(\"organisation_pk\", sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint([\"boefje_id\"], [\"boefje.id\"], ondelete=\"CASCADE\"),\n sa.ForeignKeyConstraint([\"organisation_pk\"], [\"organisation.pk\"], ondelete=\"CASCADE\"),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"organisation_pk\", \"boefje_id\", name=\"unique_boefje_config_per_organisation_per_boefje\"),\n )\n op.create_table(\n \"normalizer_config\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"enabled\", sa.Boolean(), server_default=\"false\", nullable=False),\n sa.Column(\"normalizer_id\", sa.Integer(), nullable=False),\n sa.Column(\"organisation_pk\", sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint([\"normalizer_id\"], [\"normalizer.id\"], ondelete=\"CASCADE\"),\n sa.ForeignKeyConstraint([\"organisation_pk\"], [\"organisation.pk\"], ondelete=\"CASCADE\"),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\n \"organisation_pk\", \"normalizer_id\", name=\"unique_normalizer_config_per_organisation_per_normalizer\"\n ),\n )\n\n op.add_column(\"boefje\", sa.Column(\"static\", sa.Boolean(), server_default=\"false\", nullable=False))\n op.add_column(\"normalizer\", sa.Column(\"static\", sa.Boolean(), server_default=\"false\", nullable=False))\n\n register_adapter(dict, Json)\n\n local_plugins = {plugin.id: plugin for plugin in get_local_repository().get_all()}\n connection = op.get_bind()\n\n # Get unique plugin_ids from the settings table for boefjes that do not exist yet in the database\n query = \"\"\"\n SELECT DISTINCT s.plugin_id FROM settings s left join boefje b on b.plugin_id = s.plugin_id\n where b.plugin_id IS NULL\n \"\"\" # noqa: S608\n\n to_insert: list[Boefje] = []\n\n for plugin_id_output in connection.execute(query).fetchall():\n plugin_id = plugin_id_output[0]\n if plugin_id not in local_plugins:\n raise ValueError(f\"Invalid plugin id found: {plugin_id}\")\n\n # Since settings are boefje-only at this moment\n if local_plugins[plugin_id].type != \"boefje\":\n raise ValueError(f\"Settings for normalizer or bit found: {plugin_id}. Remove these entries first.\")\n\n res = connection.execute(f\"SELECT id FROM boefje where plugin_id = '{plugin_id}'\") # noqa: S608\n if res.fetchone() is not None:\n continue # The Boefje already exists\n\n if local_plugins[plugin_id].type == \"boefje\":\n to_insert.append(local_plugins[plugin_id])\n\n entries = [\n (\n boefje.id,\n boefje.name,\n boefje.description,\n str(boefje.scan_level),\n list(boefje.consumes),\n list(boefje.produces),\n [\"TEST_KEY\"],\n boefje.oci_image,\n boefje.oci_arguments,\n boefje.version,\n )\n for boefje in to_insert\n ]\n query = \"\"\"INSERT INTO boefje (plugin_id, name, description, scan_level, consumes, produces, environment_keys,\n oci_image, oci_arguments, version) values %s\"\"\"\n\n with connection.begin():\n cursor = connection.connection.cursor()\n execute_values(cursor, query, entries)\n\n to_insert = []\n\n query = \"\"\"\n SELECT DISTINCT p.plugin_id FROM plugin_state p left join boefje b on b.plugin_id = p.plugin_id\n where b.plugin_id IS NULL\n \"\"\"\n\n for plugin_id_output in connection.execute(query).fetchall():\n plugin_id = plugin_id_output[0]\n if plugin_id not in local_plugins:\n logger.warning(\"Unknown plugin id found: %s. You might have to re-enable the plugin!\", plugin_id)\n continue\n\n res = connection.execute(f\"SELECT id FROM boefje where plugin_id = '{plugin_id}'\") # noqa: S608\n if res.fetchone() is not None:\n continue # The Boefje already exists\n\n if local_plugins[plugin_id].type == \"boefje\":\n to_insert.append(local_plugins[plugin_id])\n\n entries = [\n (\n boefje.id,\n boefje.name,\n boefje.description,\n str(boefje.scan_level),\n list(boefje.consumes),\n list(boefje.produces),\n [\"TEST_KEY\"],\n boefje.oci_image,\n boefje.oci_arguments,\n boefje.version,\n )\n for boefje in to_insert\n ]\n query = \"\"\"INSERT INTO boefje (plugin_id, name, description, scan_level, consumes, produces, environment_keys,\n oci_image, oci_arguments, version) values %s\"\"\" # noqa: S608\n\n with connection.begin():\n cursor = connection.connection.cursor()\n execute_values(cursor, query, entries)\n\n normalizers_to_insert: list[Normalizer] = []\n query = \"\"\"\n SELECT DISTINCT p.plugin_id FROM plugin_state p left join normalizer n on n.plugin_id = p.plugin_id\n where n.plugin_id IS NULL\n \"\"\" # noqa: S608\n\n for plugin_id_output in connection.execute(query).fetchall():\n plugin_id = plugin_id_output[0]\n if plugin_id not in local_plugins:\n logger.warning(\"Unknown plugin id found: %s. You might have to re-enable the plugin!\", plugin_id)\n continue\n\n res = connection.execute(f\"SELECT id FROM normalizer where plugin_id = '{plugin_id}'\") # noqa: S608\n if res.fetchone() is not None:\n continue # The Normalizer already exists\n\n if local_plugins[plugin_id].type == \"normalizer\":\n normalizers_to_insert.append(local_plugins[plugin_id])\n\n normalizer_entries = [\n (\n normalizer.id,\n normalizer.name,\n normalizer.description,\n normalizer.consumes,\n normalizer.produces,\n [\"TEST_KEY\"],\n normalizer.version,\n )\n for normalizer in normalizers_to_insert\n ]\n query = \"\"\"INSERT INTO normalizer (plugin_id, name, description, consumes, produces, environment_keys, version)\n values %s\"\"\" # noqa: S608\n\n with connection.begin():\n cursor = connection.connection.cursor()\n execute_values(cursor, query, normalizer_entries)\n\n with connection.begin():\n connection.execute(\"\"\"\n INSERT INTO boefje_config (settings, boefje_id, organisation_pk)\n SELECT s.values, b.id, s.organisation_pk from settings s\n join boefje b on s.plugin_id = b.plugin_id\n \"\"\") # Add boefjes and set the settings for boefjes\n\n with connection.begin():\n connection.execute(\"\"\"\n INSERT INTO boefje_config (enabled, boefje_id, organisation_pk)\n SELECT p.enabled, b.id, p.organisation_pk FROM plugin_state p\n JOIN boefje b ON p.plugin_id = b.plugin_id\n LEFT JOIN boefje_config bc ON bc.boefje_id = b.id WHERE bc.boefje_id IS NULL\n \"\"\") # Add boefjes and set the enabled field for boefjes that to not exist yet\n connection.execute(\"\"\"\n UPDATE boefje_config bc SET enabled = p.enabled from plugin_state p\n JOIN boefje b ON p.plugin_id = b.plugin_id\n where b.id = bc.boefje_id and p.organisation_pk = bc.organisation_pk\n \"\"\") # Set the enabled field for boefjes\n connection.execute(\"\"\"\n UPDATE normalizer_config nc SET enabled = p.enabled from plugin_state p\n JOIN normalizer n ON p.plugin_id = n.plugin_id\n where n.id = nc.normalizer_id and p.organisation_pk = nc.organisation_pk\n \"\"\") # Set the enabled field for normalizers\n\n op.drop_table(\"settings\")\n op.drop_table(\"plugin_state\")\n # ### end Alembic commands ###", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def _pep_440_key(s):\n s = s.strip()\n m = PEP440_VERSION_RE.match(s)\n if not m:\n raise UnsupportedVersionError('Not a valid version: %s' % s)\n groups = m.groups()\n nums = tuple(int(v) for v in groups[1].split('.'))\n while len(nums) > 1 and nums[-1] == 0:\n nums = nums[:-1]\n\n if not groups[0]:\n epoch = 0\n else:\n epoch = int(groups[0][:-1])\n pre = groups[4:6]\n post = groups[7:9]\n dev = groups[10:12]\n local = groups[13]\n if pre == (None, None):\n pre = ()\n else:\n if pre[1] is None:\n pre = pre[0], 0\n else:\n pre = pre[0], int(pre[1])\n if post == (None, None):\n post = ()\n else:\n if post[1] is None:\n post = post[0], 0\n else:\n post = post[0], int(post[1])\n if dev == (None, None):\n dev = ()\n else:\n if dev[1] is None:\n dev = dev[0], 0\n else:\n dev = dev[0], int(dev[1])\n if local is None:\n local = ()\n else:\n parts = []\n for part in local.split('.'):\n # to ensure that numeric compares as > lexicographic, avoid\n # comparing them directly, but encode a tuple which ensures\n # correct sorting\n if part.isdigit():\n part = (1, int(part))\n else:\n part = (0, part)\n parts.append(part)\n local = tuple(parts)\n if not pre:\n # either before pre-release, or final release and after\n if not post and dev:\n # before pre-release\n pre = ('a', -1) # to sort before a0\n else:\n pre = ('z',) # to sort after all pre-releases\n # now look at the state of post and dev.\n if not post:\n post = ('_',) # sort before 'a'\n if not dev:\n dev = ('final',)\n\n return epoch, nums, pre, post, dev, local", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:\n \"\"\"Find the most appropriate :class:`ParamType` for the given Python\n type. If the type isn't provided, it can be inferred from a default\n value.\n \"\"\"\n guessed_type = False\n\n if ty is None and default is not None:\n if isinstance(default, (tuple, list)):\n # If the default is empty, ty will remain None and will\n # return STRING.\n if default:\n item = default[0]\n\n # A tuple of tuples needs to detect the inner types.\n # Can't call convert recursively because that would\n # incorrectly unwind the tuple to a single type.\n if isinstance(item, (tuple, list)):\n ty = tuple(map(type, item))\n else:\n ty = type(item)\n else:\n ty = type(default)\n\n guessed_type = True\n\n if isinstance(ty, tuple):\n return Tuple(ty)\n\n if isinstance(ty, ParamType):\n return ty\n\n if ty is str or ty is None:\n return STRING\n\n if ty is int:\n return INT\n\n if ty is float:\n return FLOAT\n\n if ty is bool:\n return BOOL\n\n if guessed_type:\n return STRING\n\n if __debug__:\n try:\n if issubclass(ty, ParamType):\n raise AssertionError(\n f\"Attempted to use an uninstantiated parameter type ({ty}).\"\n )\n except TypeError:\n # ty is an instance (correct), so issubclass fails.\n pass\n\n return FuncParamType(ty)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@contextmanager\ndef Feature(names: str | Sequence[str] | dict[str, bool]) -> Generator[None]:\n \"\"\"\n Control whether a feature is enabled.\n\n A single feature may be conveniently enabled with\n\n >>> with Feature('feature-1'):\n >>> # Executes with feature-1 enabled\n\n More advanced enabling / disabling can be done using a dict\n\n >>> with Feature({'feature-1': True, 'feature-2': False}):\n >>> # Executes with feature-1 enabled and feature-2 disabled\n\n The following two invocations are equivalent:\n\n >>> with Feature(['feature-1', 'feature-2']):\n >>> # execute with both features enabled\n >>> with Feature({'feature-1': True, 'feature-2': True}):\n >>> # execute with both features enabled\n\n You can enable features for specific organizations:\n\n >>> with Feature({'feature-1': ['org-slug', 'albertos-apples']}):\n >>> # execute with feature-1 enabled for any organizations whose slug matches either \"org-slug\" or \"albertos-apples\"\n \"\"\"\n if isinstance(names, str):\n names = {names: True}\n\n elif not isinstance(names, Mapping):\n names = {k: True for k in names}\n\n default_features = sentry.features.has\n default_batch_has = sentry.features.batch_has\n\n def resolve_feature_name_value_for_org(organization, feature_name_value):\n if isinstance(feature_name_value, list):\n return organization.slug in feature_name_value\n return feature_name_value\n\n def features_override(name, *args, **kwargs):\n if name in names:\n try:\n feature = features.get(name, None)\n except FeatureNotRegistered:\n raise ValueError(\"Unregistered feature flag: %s\", repr(name))\n\n if isinstance(feature, OrganizationFeature):\n org = args[0] if len(args) > 0 else kwargs.get(\"organization\", None)\n if not isinstance(\n org,\n (\n Organization,\n RpcOrganizationSummary,\n RpcOrganization,\n RpcUserOrganizationContext,\n ),\n ):\n raise ValueError(\"Must provide organization to check feature\")\n return resolve_feature_name_value_for_org(org, names[name])\n\n if isinstance(feature, ProjectFeature):\n project = args[0] if len(args) > 0 else kwargs.get(\"project\", None)\n if not isinstance(project, Project):\n raise ValueError(\"Must provide project to check feature\")\n\n return names[name]\n else:\n try:\n default_value = default_features(name, *args, **kwargs)\n except FeatureNotRegistered:\n logger.info(\"Unregistered flag defaulting to False: %s\", repr(name))\n return False\n\n if default_value:\n logger.info(\"Flag defaulting to %s: %s\", default_value, repr(name))\n return default_value\n\n def batch_features_override(\n _feature_names: Sequence[str], projects=None, organization=None, *args, **kwargs\n ):\n feature_results = {name: names[name] for name in _feature_names if name in names}\n default_feature_names = [name for name in _feature_names if name not in names]\n default_feature_results: dict[str, dict[str, bool | None]] = {}\n if default_feature_names:\n defaults = default_batch_has(\n default_feature_names, projects=projects, organization=organization, **kwargs\n )\n if defaults:\n default_feature_results.update(defaults)\n\n if projects:\n results = {}\n for project in projects:\n result_key = f\"project:{project.id}\"\n proj_results = {**feature_results, **default_feature_results[result_key]}\n results[result_key] = {\n name: val for name, val in proj_results.items() if name.startswith(\"project\")\n }\n return results\n elif organization:\n result_key = f\"organization:{organization.id}\"\n results_for_org = {**feature_results, **default_feature_results[result_key]}\n results_for_org = {\n name: resolve_feature_name_value_for_org(organization, val)\n for name, val in results_for_org.items()\n if name.startswith(\"organization\")\n }\n return {result_key: results_for_org}\n\n with patch(\"sentry.features.has\") as features_has:\n features_has.side_effect = features_override\n with patch(\"sentry.features.batch_has\") as features_batch_has:\n features_batch_has.side_effect = batch_features_override\n yield", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def calcMoving(self):\n\t\tself.X = self.Y = 0\n\t\tif not (self.txtflags & RT_WRAP):\n\t\t\tself.txtext = self.txtext.replace(\"\\xe0\\x8a\", \" \").replace(chr(0x8A), \" \").replace(\"\\n\", \" \").replace(\"\\r\", \" \")\n\n\t\tself.scroll_label.setText(self.txtext)\n\n\t\tif self.txtext == \"\" or \\\n\t\t\tself.type == NONE or \\\n\t\t\tself.scroll_label is None:\n\t\t\treturn False\n\n\t\tif self.direction in (LEFT, RIGHT) or not (self.txtflags & RT_WRAP):\n\t\t\tself.scroll_label.resize(eSize(self.txfont.pointSize * len(self.txtext), self.H)) # stupid workaround, have no better idea right now...\n\n\t\ttext_size = self.scroll_label.calculateSize()\n\t\ttext_width = text_size.width()\n\t\ttext_height = text_size.height()\n\n\t\tif self.direction in (LEFT, RIGHT) or not (self.txtflags & RT_WRAP):\n\t\t\ttext_width += 10\n\n\t\tself.mStop = None\n\t\t# text height correction if necessary:\n\t\tif self.lineHeight and self.direction in (TOP, BOTTOM):\n\t\t\ttext_height = max(text_height, (text_height + self.lineHeight - 1) / self.lineHeight * self.lineHeight)\n\n\n#\t\tself.type =\t\t0 - NONE; 1 - RUNNING; 2 - SWIMMING; 3 - AUTO(???)\n#\t\tself.direction =\t0 - LEFT; 1 - RIGHT; 2 - TOP; 3 - BOTTOM\n#\t\tself.halign =\t\t0 - LEFT; 1 - RIGHT; 2 - CENTER; 3 - BLOCK\n\n\t\tif self.direction in (LEFT, RIGHT):\n\t\t\tif not self.mAlways and text_width <= self.W:\n\t\t\t\treturn False\n\t\t\tif self.type == RUNNING:\n\t\t\t\tself.A = self.X - text_width - self.soffset[0] - abs(self.mStep)\n\t\t\t\tself.B = self.W - self.soffset[0] + abs(self.mStep)\n\t\t\t\tif self.direction == LEFT:\n\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\tself.mStop = self.X\n\t\t\t\t\tself.P = self.B\n\t\t\t\telse:\n\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\tself.mStop = self.B - text_width + self.soffset[0] - self.mStep\n\t\t\t\t\tself.P = self.A\n\t\t\t\tif self.mStartPoint is not None:\n\t\t\t\t\tif self.direction == LEFT:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.W, self.mStartPoint))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.B, self.mStartPoint - text_width + self.soffset[0]))\n\t\t\telif self.type == SWIMMING:\n\t\t\t\tif text_width < self.W:\n\t\t\t\t\tself.A = self.X + 1\t\t\t# incomprehensible indent \"+ 1\" ???\n\t\t\t\t\tself.B = self.W - text_width - 1 # incomprehensible indent \"- 1\" ???\n\t\t\t\t\tif self.halign == LEFT:\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\telif self.halign == RIGHT:\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telse: # if self.halign in (CENTER, BLOCK):\n\t\t\t\t\t\tself.P = int(self.B / 2)\n\t\t\t\t\t\tself.mStep = (self.direction == RIGHT) and abs(self.mStep) or -abs(self.mStep)\n\t\t\t\telse:\n\t\t\t\t\tif text_width == self.W:\n\t\t\t\t\t\ttext_width += max(2, text_width / 20)\n\t\t\t\t\tself.A = self.W - text_width\n\t\t\t\t\tself.B = self.X\n\t\t\t\t\tif self.halign == LEFT:\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telif self.halign == RIGHT:\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\telse: # if self.halign in (CENTER, BLOCK):\n\t\t\t\t\t\tself.P = int(self.A / 2)\n\t\t\t\t\t\tself.mStep = (self.direction == RIGHT) and abs(self.mStep) or -abs(self.mStep)\n\t\t\telse:\n\t\t\t\treturn False\n\t\telif self.direction in (TOP, BOTTOM):\n\t\t\tif not self.mAlways and text_height <= self.H:\n\t\t\t\treturn False\n\t\t\tif self.type == RUNNING:\n\t\t\t\tself.A = self.Y - text_height - self.soffset[1] - abs(self.mStep)\n\t\t\t\tself.B = self.H - self.soffset[1] + abs(self.mStep)\n\t\t\t\tif self.direction == TOP:\n\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\tself.mStop = self.Y\n\t\t\t\t\tself.P = self.B\n\t\t\t\telse:\n\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\tself.mStop = self.B - text_height + self.soffset[1] - self.mStep\n\t\t\t\t\tself.P = self.A\n\t\t\t\tif self.mStartPoint is not None:\n\t\t\t\t\tif self.direction == TOP:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.H, self.mStartPoint))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.mStop = self.P = max(self.A, min(self.B, self.mStartPoint - text_height + self.soffset[1]))\n\t\t\telif self.type == SWIMMING:\n\t\t\t\tif text_height < self.H:\n\t\t\t\t\tself.A = self.Y\n\t\t\t\t\tself.B = self.H - text_height\n\t\t\t\t\tif self.direction == TOP:\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\telse:\n\t\t\t\t\tif text_height == self.H:\n\t\t\t\t\t\ttext_height += max(2, text_height / 40)\n\t\t\t\t\tself.A = self.H - text_height\n\t\t\t\t\tself.B = self.Y\n\t\t\t\t\tif self.direction == TOP:\n\t\t\t\t\t\tself.P = self.B\n\t\t\t\t\t\tself.mStep = -abs(self.mStep)\n\t\t\t\t\t\tself.mStop = self.B\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.P = self.A\n\t\t\t\t\t\tself.mStep = abs(self.mStep)\n\t\t\t\t\t\tself.mStop = self.A\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\n\t\tself.xW = max(self.W, text_width)\n\t\tself.xH = max(self.H, text_height)\n\n\t\tself.scroll_label.resize(eSize(self.xW, self.xH))\n\n\t\tif self.mStartDelay:\n\t\t\tif self.direction in (LEFT, RIGHT):\n\t\t\t\tself.moveLabel(self.P, self.Y)\n\t\t\telse: # if self.direction in (TOP,BOTTOM):\n\t\t\t\tself.moveLabel(self.X, self.P)\n\n\t\tself.mCount = self.mRepeat\n\t\tself.mTimer.start(self.mStartDelay, True)\n\t\treturn True", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def infer_variance(info: TypeInfo, i: int) -> bool:\n \"\"\"Infer the variance of the ith type variable of a generic class.\n\n Return True if successful. This can fail if some inferred types aren't ready.\n \"\"\"\n object_type = Instance(info.mro[-1], [])\n\n for variance in COVARIANT, CONTRAVARIANT, INVARIANT:\n tv = info.defn.type_vars[i]\n assert isinstance(tv, TypeVarType)\n if tv.variance != VARIANCE_NOT_READY:\n continue\n tv.variance = variance\n co = True\n contra = True\n tvar = info.defn.type_vars[i]\n self_type = fill_typevars(info)\n for member in all_non_object_members(info):\n # __mypy-replace is an implementation detail of the dataclass plugin\n if member in (\"__init__\", \"__new__\", \"__mypy-replace\"):\n continue\n\n if isinstance(self_type, TupleType):\n self_type = mypy.typeops.tuple_fallback(self_type)\n flags = get_member_flags(member, self_type)\n settable = IS_SETTABLE in flags\n\n node = info[member].node\n if isinstance(node, Var):\n if node.type is None:\n tv.variance = VARIANCE_NOT_READY\n return False\n if has_underscore_prefix(member):\n # Special case to avoid false positives (and to pass conformance tests)\n settable = False\n\n typ = find_member(member, self_type, self_type)\n if typ:\n # It's okay for a method in a generic class with a contravariant type\n # variable to return a generic instance of the class, if it doesn't involve\n # variance (i.e. values of type variables are propagated). Our normal rules\n # would disallow this. Replace such return types with 'Any' to allow this.\n #\n # This could probably be more lenient (e.g. allow self type be nested, don't\n # require all type arguments to be identical to self_type), but this will\n # hopefully cover the vast majority of such cases, including Self.\n typ = erase_return_self_types(typ, self_type)\n\n typ2 = expand_type(typ, {tvar.id: object_type})\n if not is_subtype(typ, typ2):\n co = False\n if not is_subtype(typ2, typ):\n contra = False\n if settable:\n co = False\n\n # Infer variance from base classes, in case they have explicit variances\n for base in info.bases:\n base2 = expand_type(base, {tvar.id: object_type})\n if not is_subtype(base, base2):\n co = False\n if not is_subtype(base2, base):\n contra = False\n\n if co:\n v = COVARIANT\n elif contra:\n v = CONTRAVARIANT\n else:\n v = INVARIANT\n if v == variance:\n break\n tv.variance = VARIANCE_NOT_READY\n return True", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n \"\"\"Given a command, mode, and a PATH string, return the path which\n conforms to the given mode on the PATH, or None if there is no such\n file.\n\n `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result\n of os.environ.get(\"PATH\"), or can be overridden with a custom search\n path.\n\n \"\"\"\n\n # Check that a given file can be accessed with the correct mode.\n # Additionally check that `file` is not a directory, as on Windows\n # directories pass the os.access check.\n def _access_check(fn, mode):\n return (os.path.exists(fn) and os.access(fn, mode)\n and not os.path.isdir(fn))\n\n # If we're given a path with a directory part, look it up directly rather\n # than referring to PATH directories. This includes checking relative to the\n # current directory, e.g. ./script\n if os.path.dirname(cmd):\n if _access_check(cmd, mode):\n return cmd\n return None\n\n if path is None:\n path = os.environ.get(\"PATH\", os.defpath)\n if not path:\n return None\n path = path.split(os.pathsep)\n\n if sys.platform == \"win32\":\n # The current directory takes precedence on Windows.\n if os.curdir not in path:\n path.insert(0, os.curdir)\n\n # PATHEXT is necessary to check on Windows.\n pathext = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n # See if the given file matches any of the expected path extensions.\n # This will allow us to short circuit when given \"python.exe\".\n # If it does match, only test that one, otherwise we have to try\n # others.\n if any(cmd.lower().endswith(ext.lower()) for ext in pathext):\n files = [cmd]\n else:\n files = [cmd + ext for ext in pathext]\n else:\n # On other platforms you don't have things like PATHEXT to tell you\n # what file suffixes are executable, so just pass on cmd as-is.\n files = [cmd]\n\n seen = set()\n for dir in path:\n normdir = os.path.normcase(dir)\n if normdir not in seen:\n seen.add(normdir)\n for thefile in files:\n name = os.path.join(dir, thefile)\n if _access_check(name, mode):\n return name\n return None", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _assemble_workbook(\n self,\n sheets_entries: Generator[tuple[str, Any], None, None],\n template_data: BaseModel | None,\n ) -> Workbook:\n workbook = Workbook()\n\n sheet_data: BaseXLSXSheet\n for _, sheet_data in sheets_entries:\n sheet_name = sheet_data.name\n\n xls_sheet = workbook.create_sheet(sheet_name)\n\n single_cells_cell_styles: dict[str, BaseXLSXCellData] = {}\n\n all_cells: list[tuple[str, BaseXLSXCellData]] = []\n data_cells = sheet_data.assemble_data_for_template(template_data)\n\n if data_cells:\n all_cells.extend(data_cells)\n if sheet_data.cell_styles:\n all_cells.extend(sheet_data.cell_styles)\n\n for cell_address, entry in all_cells:\n if \":\" in cell_address:\n # ranges like A1:B4 will be flattened into single cell entries\n _parse_multiple_cell_ranges(\n single_cells_cell_styles=single_cells_cell_styles,\n xls_sheet=xls_sheet,\n entry=entry,\n cell_address=cell_address,\n )\n else:\n _update_entry_in_cell(\n target=single_cells_cell_styles,\n address=cell_address,\n new_entry=entry,\n )\n\n # finally apply data from cell cell_styles to xls cells\n for cell_address, entry in single_cells_cell_styles.items():\n _update_cell(xls_sheet[cell_address], entry)\n\n # apply column widths\n for column, width in sheet_data.column_dimensions.items():\n xls_sheet.column_dimensions[column].width = width\n\n # apply cell merging\n for to_merge in sheet_data.cell_merge:\n xls_sheet.merge_cells(to_merge)\n\n # store for future usage\n self._sheets_by_name[sheet_data] = xls_sheet\n\n # remove the default sheet\n sheet_to_remove = workbook.get_sheet_by_name(workbook.get_sheet_names()[0])\n workbook.remove(sheet_to_remove)\n\n return workbook", "smellKey": "S3776", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "@cached\n\tdef getText(self):\n\t\tseek = self.getSeek()\n\t\tif seek is None:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\tlVal = self.length\n\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\tlVal = self.position\n\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\tlVal = self.length - self.position\n\t\t\telif self.type == self.TYPE_ENDTIME:\n\t\t\t\tlVal = (self.length - self.position) / 90000\n\t\t\t\ttVal = time()\n\t\t\t\ttVal = localtime(tVal + lVal)\n\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\treturn \"%02d:%02d\" % (tVal.tm_hour, tVal.tm_min)\n\t\t\t\telse:\n\t\t\t\t\treturn \"%02d:%02d:%02d\" % (tVal.tm_hour, tVal.tm_min, tVal.tm_sec)\n\n\t\t\tif not self.detailed:\n\t\t\t\tlVal /= 90000\n\n\t\t\tif self.negate:\n\t\t\t\tlVal = -lVal\n\n\t\t\tif lVal > 0:\n\t\t\t\tsign = \"\"\n\t\t\telse:\n\t\t\t\tlVal = -lVal\n\t\t\t\tsign = \"-\"\n\n\t\t\tif not self.detailed:\n\t\t\t\tif self.showHours:\n\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\treturn sign + \"%d:%02d\" % (lVal / 3600, lVal % 3600 / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign + \"%d:%02d:%02d\" % (lVal / 3600, lVal % 3600 / 60, lVal % 60)\n\t\t\t\telse:\n\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\treturn sign + \"%d\" % (lVal / 60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign + \"%d:%02d\" % (lVal / 60, lVal % 60)\n\t\t\telse:\n\t\t\t\tif self.showHours:\n\t\t\t\t\treturn sign + \"%d:%02d:%02d:%03d\" % ((lVal / 3600 / 90000), (lVal / 90000) % 3600 / 60, (lVal / 90000) % 60, (lVal % 90000) / 90)\n\t\t\t\telse:\n\t\t\t\t\treturn sign + \"%d:%02d:%03d\" % ((lVal / 60 / 90000), (lVal / 90000) % 60, (lVal % 90000) / 90)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def render_on_html(infile):\n expr = None\n gid = 1\n log = \"\"\n dot = \"\"\n indot = 0\n logs = []\n\n for line in infile:\n if line.startswith(\"machine codes for filter:\"):\n expr = line[len(\"machine codes for filter:\"):].strip()\n break\n elif line.startswith(\"digraph BPF {\"):\n indot = 1\n dot = line\n elif indot:\n dot += line\n if line.startswith(\"}\"):\n indot = 2\n else:\n log += line\n\n if indot == 2:\n try:\n p = subprocess.Popen(['dot', '-Tsvg'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n except OSError as ose:\n print \"Failed to run 'dot':\", ose\n print \"(Is Graphviz installed?)\"\n exit(1)\n\n svg = p.communicate(dot)[0]\n with file(\"expr1_g%03d.svg\" % (gid), \"wt\") as f:\n f.write(svg)\n\n logs.append(log)\n gid += 1\n log = \"\"\n dot = \"\"\n indot = 0\n\n if indot != 0:\n #unterminated dot graph for expression\n return False\n if expr is None:\n # BPF parser encounter error(s)\n return False\n write_html(expr, gid - 1, logs)\n return True", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l1", "language": "python"} {"function": "def get_ordering(self, request, queryset):\n \"\"\"\n Return the list of ordering fields for the change list.\n First check the get_ordering() method in model admin, then check\n the object's default ordering. Then, any manually-specified ordering\n from the query string overrides anything. Finally, a deterministic\n order is guaranteed by calling _get_deterministic_ordering() with the\n constructed ordering.\n \"\"\"\n params = self.params\n ordering = list(\n self.model_admin.get_ordering(request) or self._get_default_ordering()\n )\n if params.get(ORDER_VAR):\n # Clear ordering and used params\n ordering = []\n order_params = params[ORDER_VAR].split(\".\")\n for p in order_params:\n try:\n none, pfx, idx = p.rpartition(\"-\")\n field_name = self.list_display[int(idx)]\n order_field = self.get_ordering_field(field_name)\n if not order_field:\n continue # No 'admin_order_field', skip it\n if isinstance(order_field, OrderBy):\n if pfx == \"-\":\n order_field = order_field.copy()\n order_field.reverse_ordering()\n ordering.append(order_field)\n elif hasattr(order_field, \"resolve_expression\"):\n # order_field is an expression.\n ordering.append(\n order_field.desc() if pfx == \"-\" else order_field.asc()\n )\n # reverse order if order_field has already \"-\" as prefix\n elif pfx == \"-\" and order_field.startswith(pfx):\n ordering.append(order_field.removeprefix(pfx))\n else:\n ordering.append(pfx + order_field)\n except (IndexError, ValueError):\n continue # Invalid ordering specified, skip it.\n\n # Add the given query's ordering fields, if any.\n ordering.extend(queryset.query.order_by)\n\n return self._get_deterministic_ordering(ordering)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def fixed_width_int_op(\n self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int\n ) -> Value:\n \"\"\"Generate a binary op using Python fixed-width integer semantics.\n\n These may differ in overflow/rounding behavior from native/C ops.\n\n Args:\n type: Either int64_rprimitive or int32_rprimitive\n op: IntOp.* constant (e.g. IntOp.ADD)\n \"\"\"\n lhs = self.coerce(lhs, type, line)\n rhs = self.coerce(rhs, type, line)\n if op == IntOp.DIV:\n if isinstance(rhs, Integer) and rhs.value not in (-1, 0):\n if not type.is_signed:\n return self.int_op(type, lhs, rhs, IntOp.DIV, line)\n else:\n # Inline simple division by a constant, so that C\n # compilers can optimize more\n return self.inline_fixed_width_divide(type, lhs, rhs, line)\n if is_int64_rprimitive(type):\n prim = int64_divide_op\n elif is_int32_rprimitive(type):\n prim = int32_divide_op\n elif is_int16_rprimitive(type):\n prim = int16_divide_op\n elif is_uint8_rprimitive(type):\n self.check_for_zero_division(rhs, type, line)\n return self.int_op(type, lhs, rhs, op, line)\n else:\n assert False, type\n return self.call_c(prim, [lhs, rhs], line)\n if op == IntOp.MOD:\n if isinstance(rhs, Integer) and rhs.value not in (-1, 0):\n if not type.is_signed:\n return self.int_op(type, lhs, rhs, IntOp.MOD, line)\n else:\n # Inline simple % by a constant, so that C\n # compilers can optimize more\n return self.inline_fixed_width_mod(type, lhs, rhs, line)\n if is_int64_rprimitive(type):\n prim = int64_mod_op\n elif is_int32_rprimitive(type):\n prim = int32_mod_op\n elif is_int16_rprimitive(type):\n prim = int16_mod_op\n elif is_uint8_rprimitive(type):\n self.check_for_zero_division(rhs, type, line)\n return self.int_op(type, lhs, rhs, op, line)\n else:\n assert False, type\n return self.call_c(prim, [lhs, rhs], line)\n return self.int_op(type, lhs, rhs, op, line)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def dangerous_comparison(\n self,\n left: Type,\n right: Type,\n *,\n original_container: Type | None = None,\n seen_types: set[tuple[Type, Type]] | None = None,\n prefer_literal: bool = True,\n ) -> bool:\n \"\"\"Check for dangerous non-overlapping comparisons like 42 == 'no'.\n\n The original_container is the original container type for 'in' checks\n (and None for equality checks).\n\n Rules:\n * X and None are overlapping even in strict-optional mode. This is to allow\n 'assert x is not None' for x defined as 'x = None # type: str' in class body\n (otherwise mypy itself would have couple dozen errors because of this).\n * Optional[X] and Optional[Y] are non-overlapping if X and Y are\n non-overlapping, although technically None is overlap, it is most\n likely an error.\n * Any overlaps with everything, i.e. always safe.\n * Special case: b'abc' in b'cde' is safe.\n \"\"\"\n if not self.chk.options.strict_equality:\n return False\n\n if seen_types is None:\n seen_types = set()\n if (left, right) in seen_types:\n return False\n seen_types.add((left, right))\n\n left, right = get_proper_types((left, right))\n\n # We suppress the error if there is a custom __eq__() method on either\n # side. User defined (or even standard library) classes can define this\n # to return True for comparisons between non-overlapping types.\n if custom_special_method(left, \"__eq__\") or custom_special_method(right, \"__eq__\"):\n return False\n\n if prefer_literal:\n # Also flag non-overlapping literals in situations like:\n # x: Literal['a', 'b']\n # if x == 'c':\n # ...\n left = try_getting_literal(left)\n right = try_getting_literal(right)\n\n if self.chk.binder.is_unreachable_warning_suppressed():\n # We are inside a function that contains type variables with value restrictions in\n # its signature. In this case we just suppress all strict-equality checks to avoid\n # false positives for code like:\n #\n # T = TypeVar('T', str, int)\n # def f(x: T) -> T:\n # if x == 0:\n # ...\n # return x\n #\n # TODO: find a way of disabling the check only for types resulted from the expansion.\n return False\n if isinstance(left, NoneType) or isinstance(right, NoneType):\n return False\n if isinstance(left, UnionType) and isinstance(right, UnionType):\n left = remove_optional(left)\n right = remove_optional(right)\n left, right = get_proper_types((left, right))\n if (\n original_container\n and has_bytes_component(original_container)\n and has_bytes_component(left)\n ):\n # We need to special case bytes and bytearray, because 97 in b'abc', b'a' in b'abc',\n # b'a' in bytearray(b'abc') etc. all return True (and we want to show the error only\n # if the check can _never_ be True).\n return False\n if isinstance(left, Instance) and isinstance(right, Instance):\n # Special case some builtin implementations of AbstractSet.\n left_name = left.type.fullname\n right_name = right.type.fullname\n if (\n left_name in OVERLAPPING_TYPES_ALLOWLIST\n and right_name in OVERLAPPING_TYPES_ALLOWLIST\n ):\n abstract_set = self.chk.lookup_typeinfo(\"typing.AbstractSet\")\n left = map_instance_to_supertype(left, abstract_set)\n right = map_instance_to_supertype(right, abstract_set)\n return self.dangerous_comparison(\n left.args[0], right.args[0], seen_types=seen_types\n )\n elif left.type.has_base(\"typing.Mapping\") and right.type.has_base(\"typing.Mapping\"):\n # Similar to above: Mapping ignores the classes, it just compares items.\n abstract_map = self.chk.lookup_typeinfo(\"typing.Mapping\")\n left = map_instance_to_supertype(left, abstract_map)\n right = map_instance_to_supertype(right, abstract_map)\n return self.dangerous_comparison(\n left.args[0], right.args[0], seen_types=seen_types\n ) or self.dangerous_comparison(left.args[1], right.args[1], seen_types=seen_types)\n elif left_name in (\"builtins.list\", \"builtins.tuple\") and right_name == left_name:\n return self.dangerous_comparison(\n left.args[0], right.args[0], seen_types=seen_types\n )\n elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in (\n OVERLAPPING_BYTES_ALLOWLIST\n ):\n return False\n if isinstance(left, LiteralType) and isinstance(right, LiteralType):\n if isinstance(left.value, bool) and isinstance(right.value, bool):\n # Comparing different booleans is not dangerous.\n return False\n return not is_overlapping_types(left, right, ignore_promotions=False)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _is_typing_same(type1_, type2_):\n \"\"\"Convert typing annotation to a _mgp.CypherType instance.\"\"\"\n simple_types = {\n typing.Any: 1,\n object: 2,\n list: 3,\n Any: 4,\n bool: 5,\n str: 6,\n int: 7,\n float: 8,\n Number: 9,\n Map: 10,\n Vertex: 11,\n Edge: 12,\n Path: 13,\n Date: 14,\n LocalTime: 15,\n LocalDateTime: 16,\n Duration: 17,\n }\n try:\n return simple_types[type1_] == simple_types[type2_]\n except KeyError:\n pass\n\n if sys.version_info < (3, 8):\n # skip type checks\n return True\n\n complex_type1 = typing.get_origin(type1_)\n type_args1 = typing.get_args(type2_)\n\n complex_type2 = typing.get_origin(type1_)\n type_args2 = typing.get_args(type2_)\n\n if complex_type2 != complex_type1:\n raise UnequalTypesError(type1_, type2_)\n\n if complex_type1 == typing.Union:\n contains_none_arg1 = type(None) in type_args1\n contains_none_arg2 = type(None) in type_args2\n\n if contains_none_arg1 != contains_none_arg2:\n raise UnequalTypesError(type1_, type2_)\n\n if contains_none_arg1:\n types1 = tuple(t for t in type_args1 if t is not type(None)) # noqa E721\n types2 = tuple(t for t in type_args2 if t is not type(None)) # noqa E721\n if len(types1) != len(types2):\n raise UnequalTypesError(types1, types2)\n if len(types1) == 1:\n (type_arg1,) = types1\n (type_arg2,) = types2\n else:\n type_arg1 = typing.Union.__getitem__(types1)\n type_arg2 = typing.Union.__getitem__(types2)\n return _is_typing_same(type_arg1, type_arg2)\n elif complex_type1 == list:\n (type_arg1,) = type_args1\n (type_arg2,) = type_args2\n return _is_typing_same(type_arg1, type_arg2)\n # skip type checks\n return True", "smellKey": "S3776", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def __run_configlog_rotation(self):\n try:\n configlog_days_delta = self.config[\"config\"][\"config_rotation_in_db\"]\n if configlog_days_delta <= 0:\n return\n\n threshold_date = timezone.now() - timedelta(days=configlog_days_delta)\n self.__log(f\"ConfigLog rotation started. Threshold date: {threshold_date}\", \"info\")\n\n exclude_pks = set()\n target_configlogs = ConfigLog.objects.filter(date__lte=threshold_date)\n for config_log in target_configlogs:\n for cl_pk in (config_log.obj_ref.current, config_log.obj_ref.previous):\n exclude_pks.add(cl_pk)\n\n for group_config in GroupConfig.objects.order_by(\"id\"):\n if group_config.config:\n exclude_pks.add(group_config.config.previous)\n exclude_pks.add(group_config.config.current)\n\n target_configlogs = target_configlogs.exclude(pk__in=exclude_pks)\n target_configlog_ids = {i[0] for i in target_configlogs.values_list(\"id\")}\n target_objectconfig_ids = {\n cl.obj_ref.id for cl in target_configlogs if not self.__has_related_records(cl.obj_ref)\n }\n if target_configlog_ids or target_objectconfig_ids:\n make_audit_log(\"config\", AuditLogOperationResult.SUCCESS, \"launched\")\n\n with transaction.atomic():\n ConfigLog.objects.filter(id__in=target_configlog_ids).delete()\n ObjectConfig.objects.filter(id__in=target_objectconfig_ids).delete()\n if target_configlog_ids or target_objectconfig_ids:\n make_audit_log(\"config\", AuditLogOperationResult.SUCCESS, \"completed\")\n\n self.__log(\n f\"Deleted {len(target_configlog_ids)} ConfigLogs and \" f\"{len(target_objectconfig_ids)} ObjectConfigs\",\n \"info\",\n )\n\n except Exception as e: # noqa: BLE001\n make_audit_log(\"config\", AuditLogOperationResult.FAIL, \"completed\")\n self.__log(\"Error in ConfigLog rotation\", \"warning\")\n self.__log(e, \"exception\")", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def __getitem__(self, k):\n \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n if not isinstance(k, (int, slice)):\n raise TypeError(\n \"QuerySet indices must be integers or slices, not %s.\"\n % type(k).__name__\n )\n if (isinstance(k, int) and k < 0) or (\n isinstance(k, slice)\n and (\n (k.start is not None and k.start < 0)\n or (k.stop is not None and k.stop < 0)\n )\n ):\n raise ValueError(\"Negative indexing is not supported.\")\n\n if self._result_cache is not None:\n return self._result_cache[k]\n\n if isinstance(k, slice):\n qs = self._chain()\n if k.start is not None:\n start = int(k.start)\n else:\n start = None\n if k.stop is not None:\n stop = int(k.stop)\n else:\n stop = None\n qs.query.set_limits(start, stop)\n return list(qs)[:: k.step] if k.step else qs\n\n qs = self._chain()\n qs.query.set_limits(k, k + 1)\n qs._fetch_all()\n return qs._result_cache[0]", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _backfill_alert_rule_projects(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:\n QuerySubscriptions = apps.get_model(\"sentry\", \"QuerySubscription\")\n AlertRuleProjects = apps.get_model(\"sentry\", \"AlertRuleProjects\")\n\n # use RangeQuerySetWrapper to avoid loading all subscriptions into memory\n for subscription in RangeQuerySetWrapper(QuerySubscriptions.objects.all()):\n\n snuba_query = subscription.snuba_query\n if not snuba_query:\n logger.warning(\n \"QuerySubscription found with no snuba_query\",\n extra={\"query_subscription_id\": subscription.id},\n )\n continue\n\n alert_rule_set = list(snuba_query.alertrule_set.all())\n if not len(alert_rule_set):\n logger.warning(\n \"QuerySubscription + SnubaQuery found with no alert_rule\",\n extra={\n \"query_subscription_id\": subscription.id,\n \"snuba_query_id\": snuba_query.id,\n },\n )\n continue\n elif len(alert_rule_set) > 1:\n logger.warning(\n \"QuerySubscription + SnubaQuery found with multiple alert_rules\",\n extra={\n \"query_subscription_id\": subscription.id,\n \"snuba_query_id\": snuba_query.id,\n \"alert_rule_ids\": [alert_rule.id for alert_rule in alert_rule_set],\n },\n )\n\n # Default to the first alert rule\n alert_rule = alert_rule_set[0]\n\n existing_alert_rule_projects = list(AlertRuleProjects.objects.filter(alert_rule=alert_rule))\n should_create_new = True\n\n if len(existing_alert_rule_projects) > 0:\n for arp in existing_alert_rule_projects:\n if arp.project_id != subscription.project_id:\n logger.warning(\n \"AlertRuleProject found with different project than subscription\",\n extra={\n \"alert_rule_id\": alert_rule.id,\n \"subscription_id\": subscription.id,\n \"subscription_project\": subscription.project_id,\n \"alert_rule_project\": arp.project_id,\n },\n )\n arp.delete()\n else:\n should_create_new = False\n\n if should_create_new:\n AlertRuleProjects.objects.create(\n alert_rule=alert_rule,\n project=subscription.project,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def postParse(self, instring, loc, tokenlist):\n for i, tok in enumerate(tokenlist):\n if len(tok) == 0:\n continue\n\n ikey = tok[0]\n if isinstance(ikey, int):\n ikey = str(ikey).strip()\n\n if len(tok) == 1:\n tokenlist[ikey] = _ParseResultsWithOffset(\"\", i)\n\n elif len(tok) == 2 and not isinstance(tok[1], ParseResults):\n tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)\n\n else:\n try:\n dictvalue = tok.copy() # ParseResults(i)\n except Exception:\n exc = TypeError(\n \"could not extract dict values from parsed results\"\n \" - Dict expression must contain Grouped expressions\"\n )\n raise exc from None\n\n del dictvalue[0]\n\n if len(dictvalue) != 1 or (\n isinstance(dictvalue, ParseResults) and dictvalue.haskeys()\n ):\n tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)\n else:\n tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)\n\n if self._asPythonDict:\n return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()\n else:\n return [tokenlist] if self.resultsName else tokenlist", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def updateHeading(self, column):\n\t\tdef buildHeadingData(column): # Numbers in trailing comments are the template text indexes.\n\t\t\tsort = column.getSortBy().split(\",\")\n\t\t\tsortDirs, reverseDirs = (int(x) for x in sort[0].split(\".\"))\n\t\t\tsortFiles, reverseFiles = (int(x) for x in sort[1].split(\".\"))\n\t\t\tsortText = f\"[D]{('n', 'd', 's')[sortDirs]}{('+', '-')[reverseDirs]}[F]{('n', 'd', 's')[sortFiles]}{('+', '-')[reverseFiles]}\" # (name|date|size)(normal|reverse)\n\t\t\tpath = column.getPath()\n\t\t\tcurrentDirectory = column.getCurrentDirectory()\n\t\t\tcurrentDirectory = normpath(currentDirectory) if currentDirectory else \"\"\n\t\t\tsplitCurrentParent = _(\"Current: %s\\nParent: %s\") % (currentDirectory, dirname(currentDirectory)) if column.getIsSpecialFolder() else path # 25\n\t\t\tif path:\n\t\t\t\tpath = normpath(path)\n\t\t\t\ttry:\n\t\t\t\t\tpathStat = lstat(path)\n\t\t\t\t\tsymbolicMode = filemode(pathStat.st_mode)\n\t\t\t\t\toctalMode = f\"{S_IMODE(pathStat.st_mode):04o}\"\n\t\t\t\t\tmodes = (\n\t\t\t\t\t\toctalMode, # 0\n\t\t\t\t\t\tsymbolicMode, # 1\n\t\t\t\t\t\tf\"{octalMode} ({symbolicMode})\" # 2\n\t\t\t\t\t)\n\t\t\t\t\tsize = pathStat.st_size\n\t\t\t\t\tformattedSize = \"{:n}\".format(size)\n\t\t\t\t\tnumberScaler = NumberScaler()\n\t\t\t\t\tscaledSizes = [numberScaler.scale(size, style=x, maxNumLen=3, decimals=3) for x in (None, \"Si\", \"Iec\")]\n\t\t\t\t\tif S_ISCHR(pathStat.st_mode) or S_ISBLK(pathStat.st_mode):\n\t\t\t\t\t\tsizes = (\"\", \"\", \"\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tsizes = (\n\t\t\t\t\t\t\tformattedSize, # 10\n\t\t\t\t\t\t\tscaledSizes[0], # 11\n\t\t\t\t\t\t\tf\"{formattedSize} ({scaledSizes[0]})\" # 12\n\t\t\t\t\t\t)\n\t\t\t\t\tdata = modes + (\n\t\t\t\t\t\tf\"{pathStat.st_ino}\", # 3\n\t\t\t\t\t\tf\"{(pathStat.st_dev >> 8) & 0xff}, {pathStat.st_dev & 0xff}\", # 4\n\t\t\t\t\t\tf\"{pathStat.st_nlink}\", # 5\n\t\t\t\t\t\tf\"{pathStat.st_uid}\", # 6\n\t\t\t\t\t\tself.username(pathStat.st_uid), # 7\n\t\t\t\t\t\tf\"{pathStat.st_gid}\", # 8\n\t\t\t\t\t\tself.groupname(pathStat.st_gid) # 9\n\t\t\t\t\t) + sizes + (\n\t\t\t\t\t\tself.formatTime(pathStat.st_mtime), # 13\n\t\t\t\t\t\tself.formatTime(pathStat.st_atime), # 14\n\t\t\t\t\t\tself.formatTime(pathStat.st_ctime), # 15\n\t\t\t\t\t\tsortText, # 16\n\t\t\t\t\t\tpath, # 17\n\t\t\t\t\t\tdirname(path), # 18\n\t\t\t\t\t\tbasename(path), # 19\n\t\t\t\t\t\tscaledSizes[1], # 20\n\t\t\t\t\t\tf\"{formattedSize} ({scaledSizes[1]})\", # 21\n\t\t\t\t\t\tscaledSizes[2], # 22\n\t\t\t\t\t\tf\"{formattedSize} ({scaledSizes[2]})\", # 23\n\t\t\t\t\t\tcurrentDirectory, # 24\n\t\t\t\t\t\tsplitCurrentParent, # 25\n\t\t\t\t\t\tcurrentDirectory if column.getIsSpecialFolder() else f\"{currentDirectory}/\\u2026/{basename(path)}\" # 26\n\t\t\t\t\t)\n\t\t\t\texcept OSError:\n\t\t\t\t\tdata = (\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", sortText, path, dirname(path), basename(path), \"\", \"\", \"\", \"\", currentDirectory, splitCurrentParent, currentDirectory)\n\t\t\telse:\n\t\t\t\tdata = (\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", sortText, STORAGE_DEVICES_NAME, STORAGE_DEVICES_NAME, STORAGE_DEVICES_NAME, \"\", \"\", \"\", \"\", currentDirectory, \"\", currentDirectory)\n\t\t\treturn [data]\n\n\t\tself.updateTitle()\n\t\theadColumn = self[\"headleft\"] if column == self[\"listleft\"] else self[\"headright\"]\n\t\theadColumn.updateList(buildHeadingData(column))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "async def create_request(\n self,\n conn_rec: ConnRecord,\n my_label: Optional[str] = None,\n my_endpoint: Optional[str] = None,\n mediation_id: Optional[str] = None,\n goal_code: Optional[str] = None,\n goal: Optional[str] = None,\n use_did_method: Optional[str] = None,\n ) -> DIDXRequest:\n \"\"\"Create a new connection request for a previously-received invitation.\n\n Args:\n conn_rec: The `ConnRecord` representing the invitation to accept\n my_label: My label for request\n my_endpoint: My endpoint\n mediation_id: The record id for mediation that contains routing_keys and\n service endpoint\n goal_code: Optional self-attested code for sharing intent of connection\n goal: Optional self-attested string for sharing intent of connection\n use_did_method: The DID method to use for the connection\n Returns:\n A new `DIDXRequest` message to send to the other agent\n\n \"\"\"\n if use_did_method and use_did_method not in self.SUPPORTED_USE_DID_METHODS:\n raise DIDXManagerError(\n f\"Unsupported use_did_method: {use_did_method}. Supported methods: \"\n f\"{self.SUPPORTED_USE_DID_METHODS}\"\n )\n\n # Mediation Support\n mediation_records = await self._route_manager.mediation_records_for_connection(\n self.profile,\n conn_rec,\n mediation_id,\n or_default=True,\n )\n\n if my_endpoint:\n my_endpoints = [my_endpoint]\n else:\n my_endpoints = []\n default_endpoint = self.profile.settings.get(\"default_endpoint\")\n if default_endpoint:\n my_endpoints.append(default_endpoint)\n my_endpoints.extend(self.profile.settings.get(\"additional_endpoints\", []))\n\n if not my_label:\n my_label = self.profile.settings.get(\"default_label\")\n assert my_label\n\n did_url = None\n if conn_rec.their_public_did is not None:\n try:\n services = await self.resolve_didcomm_services(conn_rec.their_public_did)\n except BaseConnectionManagerError as e:\n raise DIDXManagerError(\n \"Failed to resolve DIDComm services from \"\n f\"{conn_rec.their_public_did}: {e}\"\n ) from e\n if services:\n did_url = services[0].id\n\n pthid = conn_rec.invitation_msg_id or did_url\n\n if conn_rec.connection_protocol == DIDEX_1_0:\n did, attach = await self._legacy_did_with_attached_doc(\n conn_rec, my_endpoints, mediation_records\n )\n else:\n if conn_rec.accept == ConnRecord.ACCEPT_AUTO or use_did_method is None:\n # If we're auto accepting or engaging in 1.1 without setting a\n # use_did_method, default to did:peer:4\n use_did_method = \"did:peer:4\"\n try:\n did, attach = await self._qualified_did_with_fallback(\n conn_rec,\n my_endpoints,\n mediation_records,\n use_did_method,\n )\n except LegacyHandlingFallback:\n did, attach = await self._legacy_did_with_attached_doc(\n conn_rec, my_endpoints, mediation_records\n )\n\n request = DIDXRequest(\n label=my_label,\n did=did,\n did_doc_attach=attach,\n goal=goal,\n goal_code=goal_code,\n )\n\n if conn_rec.connection_protocol == DIDEX_1_0:\n request.assign_version(\"1.0\")\n\n request.assign_thread_id(thid=request._id, pthid=pthid)\n\n # Update connection state\n conn_rec.request_id = request._id\n conn_rec.state = ConnRecord.State.REQUEST.rfc160\n async with self.profile.session() as session:\n await conn_rec.save(session, reason=\"Created connection request\")\n\n # Idempotent; if routing has already been set up, no action taken\n await self._route_manager.route_connection_as_invitee(\n self.profile, conn_rec, mediation_records\n )\n\n return request", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _register_batch_proc(\n func: typing.Callable[..., Record], initializer: typing.Callable, cleanup: typing.Callable, is_write: bool\n):\n raise_if_does_not_meet_requirements(func)\n register_func = _mgp.Module.add_batch_write_procedure if is_write else _mgp.Module.add_batch_read_procedure\n func_sig = inspect.signature(func)\n func_params = tuple(func_sig.parameters.values())\n\n initializer_sig = inspect.signature(initializer)\n initializer_params = tuple(initializer_sig.parameters.values())\n\n assert (\n func_params and initializer_params or not func_params and not initializer_params\n ), \"Both function params and initializer params must exist or not exist\"\n\n assert len(func_params) == len(initializer_params), \"Number of params must be same\"\n\n assert initializer_sig.return_annotation is initializer_sig.empty, \"Initializer can't return anything\"\n\n if func_params and func_params[0].annotation is ProcCtx:\n assert (\n initializer_params and initializer_params[0].annotation is ProcCtx\n ), \"Initializer must have mgp.ProcCtx as first parameter\"\n\n @wraps(func)\n def wrapper_func(graph, args):\n return func(ProcCtx(graph), *args)\n\n @wraps(initializer)\n def wrapper_initializer(graph, args):\n return initializer(ProcCtx(graph), *args)\n\n func_params = func_params[1:]\n initializer_params = initializer_params[1:]\n mgp_proc = register_func(_mgp._MODULE, wrapper_func, wrapper_initializer, cleanup)\n else:\n\n @wraps(func)\n def wrapper_func(graph, args):\n return func(*args)\n\n @wraps(initializer)\n def wrapper_initializer(graph, args):\n return initializer(*args)\n\n mgp_proc = register_func(_mgp._MODULE, wrapper_func, wrapper_initializer, cleanup)\n\n for func_param, initializer_param in zip(func_params, initializer_params):\n func_param_name = func_param.name\n func_param_type_ = func_param.annotation\n if func_param_type_ is func_param.empty:\n func_param_type_ = object\n initializer_param_type_ = initializer_param.annotation\n if initializer_param.annotation is initializer_param.empty:\n initializer_param_type_ = object\n\n assert _is_typing_same(\n func_param_type_, initializer_param_type_\n ), \"Types of initializer and function must be same\"\n\n func_cypher_type = _typing_to_cypher_type(func_param_type_)\n if func_param.default is func_param.empty:\n mgp_proc.add_arg(func_param_name, func_cypher_type)\n else:\n mgp_proc.add_opt_arg(func_param_name, func_cypher_type, func_param.default)\n if func_sig.return_annotation is not func_sig.empty:\n record = func_sig.return_annotation\n if not isinstance(record, Record):\n raise TypeError(\"Expected '{}' to return 'mgp.Record', got '{}'\".format(func.__name__, type(record)))\n for name, type_ in record.fields.items():\n if isinstance(type_, Deprecated):\n cypher_type = _typing_to_cypher_type(type_.field_type)\n mgp_proc.add_deprecated_result(name, cypher_type)\n else:\n mgp_proc.add_result(name, _typing_to_cypher_type(type_))\n return func", "smellKey": "S3776", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def __init__(\n self,\n param_decls: t.Optional[t.Sequence[str]] = None,\n type: t.Optional[t.Union[types.ParamType, t.Any]] = None,\n required: bool = False,\n default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,\n callback: t.Optional[t.Callable[[Context, \"Parameter\", t.Any], t.Any]] = None,\n nargs: t.Optional[int] = None,\n multiple: bool = False,\n metavar: t.Optional[str] = None,\n expose_value: bool = True,\n is_eager: bool = False,\n envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,\n shell_complete: t.Optional[\n t.Callable[\n [Context, \"Parameter\", str],\n t.Union[t.List[\"CompletionItem\"], t.List[str]],\n ]\n ] = None,\n ) -> None:\n self.name: t.Optional[str]\n self.opts: t.List[str]\n self.secondary_opts: t.List[str]\n self.name, self.opts, self.secondary_opts = self._parse_decls(\n param_decls or (), expose_value\n )\n self.type: types.ParamType = types.convert_type(type, default)\n\n # Default nargs to what the type tells us if we have that\n # information available.\n if nargs is None:\n if self.type.is_composite:\n nargs = self.type.arity\n else:\n nargs = 1\n\n self.required = required\n self.callback = callback\n self.nargs = nargs\n self.multiple = multiple\n self.expose_value = expose_value\n self.default = default\n self.is_eager = is_eager\n self.metavar = metavar\n self.envvar = envvar\n self._custom_shell_complete = shell_complete\n\n if __debug__:\n if self.type.is_composite and nargs != self.type.arity:\n raise ValueError(\n f\"'nargs' must be {self.type.arity} (or None) for\"\n f\" type {self.type!r}, but it was {nargs}.\"\n )\n\n # Skip no default or callable default.\n check_default = default if not callable(default) else None\n\n if check_default is not None:\n if multiple:\n try:\n # Only check the first value against nargs.\n check_default = next(_check_iter(check_default), None)\n except TypeError:\n raise ValueError(\n \"'default' must be a list when 'multiple' is true.\"\n ) from None\n\n # Can be None for multiple with empty default.\n if nargs != 1 and check_default is not None:\n try:\n _check_iter(check_default)\n except TypeError:\n if multiple:\n message = (\n \"'default' must be a list of lists when 'multiple' is\"\n \" true and 'nargs' != 1.\"\n )\n else:\n message = \"'default' must be a list when 'nargs' != 1.\"\n\n raise ValueError(message) from None\n\n if nargs > 1 and len(check_default) != nargs:\n subject = \"item length\" if multiple else \"length\"\n raise ValueError(\n f\"'default' {subject} must match nargs={nargs}.\"\n )", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def user_add(\n module, oracle_client, username, password, auth_type,\n default_tablespace, temporary_tablespace\n):\n username = username.upper()\n extend_sql = None\n user = user_find(oracle_client, username)\n auth_type = auth_type.lower()\n identified_suffix_map = {\n 'external': 'identified externally ',\n 'global': 'identified globally ',\n 'password': 'identified by \"%s\" ',\n }\n if user:\n user_sql = \"alter user %s \" % username\n user_sql += identified_suffix_map.get(auth_type, 'no authentication ') % password\n\n if default_tablespace and default_tablespace.lower() != user['default_tablespace'].lower():\n user_sql += 'default tablespace %s quota unlimited on %s ' % (default_tablespace, default_tablespace)\n if temporary_tablespace and temporary_tablespace.lower() != user['temporary_tablespace'].lower():\n user_sql += 'temporary tablespace %s ' % temporary_tablespace\n else:\n user_sql = \"create user %s \" % username\n user_sql += identified_suffix_map.get(auth_type, 'no authentication ') % password\n if default_tablespace:\n user_sql += 'default tablespace %s quota unlimited on %s ' % (default_tablespace, default_tablespace)\n if temporary_tablespace:\n user_sql += 'temporary tablespace %s ' % temporary_tablespace\n extend_sql = 'grant connect to %s' % username\n\n rtn, err = oracle_client.execute(user_sql)\n if err:\n module.fail_json(msg='Cannot add/edit user %s: %s' % (username, err), changed=False)\n else:\n if extend_sql:\n oracle_client.execute(extend_sql)\n module.exit_json(msg='User %s has been created.' % username, changed=True, name=username)", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def _parseNoCache(\n self, instring, loc, doActions=True, callPreParse=True\n ) -> Tuple[int, ParseResults]:\n TRY, MATCH, FAIL = 0, 1, 2\n debugging = self.debug # and doActions)\n len_instring = len(instring)\n\n if debugging or self.failAction:\n # print(\"Match {} at loc {}({}, {})\".format(self, loc, lineno(loc, instring), col(loc, instring)))\n try:\n if callPreParse and self.callPreparse:\n pre_loc = self.preParse(instring, loc)\n else:\n pre_loc = loc\n tokens_start = pre_loc\n if self.debugActions.debug_try:\n self.debugActions.debug_try(instring, tokens_start, self, False)\n if self.mayIndexError or pre_loc >= len_instring:\n try:\n loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n except IndexError:\n raise ParseException(instring, len_instring, self.errmsg, self)\n else:\n loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n except Exception as err:\n # print(\"Exception raised:\", err)\n if self.debugActions.debug_fail:\n self.debugActions.debug_fail(\n instring, tokens_start, self, err, False\n )\n if self.failAction:\n self.failAction(instring, tokens_start, self, err)\n raise\n else:\n if callPreParse and self.callPreparse:\n pre_loc = self.preParse(instring, loc)\n else:\n pre_loc = loc\n tokens_start = pre_loc\n if self.mayIndexError or pre_loc >= len_instring:\n try:\n loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n except IndexError:\n raise ParseException(instring, len_instring, self.errmsg, self)\n else:\n loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n\n tokens = self.postParse(instring, loc, tokens)\n\n ret_tokens = ParseResults(\n tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults\n )\n if self.parseAction and (doActions or self.callDuringTry):\n if debugging:\n try:\n for fn in self.parseAction:\n try:\n tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type]\n except IndexError as parse_action_exc:\n exc = ParseException(\"exception raised in parse action\")\n raise exc from parse_action_exc\n\n if tokens is not None and tokens is not ret_tokens:\n ret_tokens = ParseResults(\n tokens,\n self.resultsName,\n asList=self.saveAsList\n and isinstance(tokens, (ParseResults, list)),\n modal=self.modalResults,\n )\n except Exception as err:\n # print \"Exception raised in user parse action:\", err\n if self.debugActions.debug_fail:\n self.debugActions.debug_fail(\n instring, tokens_start, self, err, False\n )\n raise\n else:\n for fn in self.parseAction:\n try:\n tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type]\n except IndexError as parse_action_exc:\n exc = ParseException(\"exception raised in parse action\")\n raise exc from parse_action_exc\n\n if tokens is not None and tokens is not ret_tokens:\n ret_tokens = ParseResults(\n tokens,\n self.resultsName,\n asList=self.saveAsList\n and isinstance(tokens, (ParseResults, list)),\n modal=self.modalResults,\n )\n if debugging:\n # print(\"Matched\", self, \"->\", ret_tokens.as_list())\n if self.debugActions.debug_match:\n self.debugActions.debug_match(\n instring, tokens_start, loc, self, ret_tokens, False\n )\n\n return loc, ret_tokens", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _check_buffer(self) -> None:\n \"\"\"Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)\n Rendering is supported on Windows, Unix and Jupyter environments. For\n legacy Windows consoles, the win32 API is called directly.\n This method will also record what it renders if recording is enabled via Console.record.\n \"\"\"\n if self.quiet:\n del self._buffer[:]\n return\n with self._lock:\n if self.record:\n with self._record_buffer_lock:\n self._record_buffer.extend(self._buffer[:])\n\n if self._buffer_index == 0:\n if self.is_jupyter: # pragma: no cover\n from .jupyter import display\n\n display(self._buffer, self._render_buffer(self._buffer[:]))\n del self._buffer[:]\n else:\n if WINDOWS:\n use_legacy_windows_render = False\n if self.legacy_windows:\n fileno = get_fileno(self.file)\n if fileno is not None:\n use_legacy_windows_render = (\n fileno in _STD_STREAMS_OUTPUT\n )\n\n if use_legacy_windows_render:\n from pip._vendor.rich._win32_console import LegacyWindowsTerm\n from pip._vendor.rich._windows_renderer import legacy_windows_render\n\n buffer = self._buffer[:]\n if self.no_color and self._color_system:\n buffer = list(Segment.remove_color(buffer))\n\n legacy_windows_render(buffer, LegacyWindowsTerm(self.file))\n else:\n # Either a non-std stream on legacy Windows, or modern Windows.\n text = self._render_buffer(self._buffer[:])\n # https://bugs.python.org/issue37871\n # https://github.com/python/cpython/issues/82052\n # We need to avoid writing more than 32Kb in a single write, due to the above bug\n write = self.file.write\n # Worse case scenario, every character is 4 bytes of utf-8\n MAX_WRITE = 32 * 1024 // 4\n try:\n if len(text) <= MAX_WRITE:\n write(text)\n else:\n batch: List[str] = []\n batch_append = batch.append\n size = 0\n for line in text.splitlines(True):\n if size + len(line) > MAX_WRITE and batch:\n write(\"\".join(batch))\n batch.clear()\n size = 0\n batch_append(line)\n size += len(line)\n if batch:\n write(\"\".join(batch))\n batch.clear()\n except UnicodeEncodeError as error:\n error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n raise\n else:\n text = self._render_buffer(self._buffer[:])\n try:\n self.file.write(text)\n except UnicodeEncodeError as error:\n error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n raise\n\n self.file.flush()\n del self._buffer[:]", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]:\n \"\"\"\n Return a cached response if it exists in the cache, otherwise\n return False.\n \"\"\"\n assert request.url is not None\n cache_url = self.cache_url(request.url)\n logger.debug('Looking up \"%s\" in the cache', cache_url)\n cc = self.parse_cache_control(request.headers)\n\n # Bail out if the request insists on fresh data\n if \"no-cache\" in cc:\n logger.debug('Request header has \"no-cache\", cache bypassed')\n return False\n\n if \"max-age\" in cc and cc[\"max-age\"] == 0:\n logger.debug('Request header has \"max_age\" as 0, cache bypassed')\n return False\n\n # Check whether we can load the response from the cache:\n resp = self._load_from_cache(request)\n if not resp:\n return False\n\n # If we have a cached permanent redirect, return it immediately. We\n # don't need to test our response for other headers b/c it is\n # intrinsically \"cacheable\" as it is Permanent.\n #\n # See:\n # https://tools.ietf.org/html/rfc7231#section-6.4.2\n #\n # Client can try to refresh the value by repeating the request\n # with cache busting headers as usual (ie no-cache).\n if int(resp.status) in PERMANENT_REDIRECT_STATUSES:\n msg = (\n \"Returning cached permanent redirect response \"\n \"(ignoring date and etag information)\"\n )\n logger.debug(msg)\n return resp\n\n headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)\n if not headers or \"date\" not in headers:\n if \"etag\" not in headers:\n # Without date or etag, the cached response can never be used\n # and should be deleted.\n logger.debug(\"Purging cached response: no date or etag\")\n self.cache.delete(cache_url)\n logger.debug(\"Ignoring cached response: no date\")\n return False\n\n now = time.time()\n time_tuple = parsedate_tz(headers[\"date\"])\n assert time_tuple is not None\n date = calendar.timegm(time_tuple[:6])\n current_age = max(0, now - date)\n logger.debug(\"Current age based on date: %i\", current_age)\n\n # TODO: There is an assumption that the result will be a\n # urllib3 response object. This may not be best since we\n # could probably avoid instantiating or constructing the\n # response until we know we need it.\n resp_cc = self.parse_cache_control(headers)\n\n # determine freshness\n freshness_lifetime = 0\n\n # Check the max-age pragma in the cache control header\n max_age = resp_cc.get(\"max-age\")\n if max_age is not None:\n freshness_lifetime = max_age\n logger.debug(\"Freshness lifetime from max-age: %i\", freshness_lifetime)\n\n # If there isn't a max-age, check for an expires header\n elif \"expires\" in headers:\n expires = parsedate_tz(headers[\"expires\"])\n if expires is not None:\n expire_time = calendar.timegm(expires[:6]) - date\n freshness_lifetime = max(0, expire_time)\n logger.debug(\"Freshness lifetime from expires: %i\", freshness_lifetime)\n\n # Determine if we are setting freshness limit in the\n # request. Note, this overrides what was in the response.\n max_age = cc.get(\"max-age\")\n if max_age is not None:\n freshness_lifetime = max_age\n logger.debug(\n \"Freshness lifetime from request max-age: %i\", freshness_lifetime\n )\n\n min_fresh = cc.get(\"min-fresh\")\n if min_fresh is not None:\n # adjust our current age by our min fresh\n current_age += min_fresh\n logger.debug(\"Adjusted current age from min-fresh: %i\", current_age)\n\n # Return entry if it is fresh enough\n if freshness_lifetime > current_age:\n logger.debug('The response is \"fresh\", returning cached response')\n logger.debug(\"%i > %i\", freshness_lifetime, current_age)\n return resp\n\n # we're not fresh. If we don't have an Etag, clear it out\n if \"etag\" not in headers:\n logger.debug('The cached response is \"stale\" with no etag, purging')\n self.cache.delete(cache_url)\n\n # return the original handler\n return False", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def check_method_override_for_base_with_name(\n self, defn: FuncDef | OverloadedFuncDef | Decorator, name: str, base: TypeInfo\n ) -> bool:\n \"\"\"Check if overriding an attribute `name` of `base` with `defn` is valid.\n\n Return True if the supertype node was not analysed yet, and `defn` was deferred.\n \"\"\"\n base_attr = base.names.get(name)\n if base_attr:\n # The name of the method is defined in the base class.\n\n # Point errors at the 'def' line (important for backward compatibility\n # of type ignores).\n if not isinstance(defn, Decorator):\n context = defn\n else:\n context = defn.func\n\n # Construct the type of the overriding method.\n # TODO: this logic is much less complete than similar one in checkmember.py\n if isinstance(defn, (FuncDef, OverloadedFuncDef)):\n typ: Type = self.function_type(defn)\n override_class_or_static = defn.is_class or defn.is_static\n override_class = defn.is_class\n else:\n assert defn.var.is_ready\n assert defn.var.type is not None\n typ = defn.var.type\n override_class_or_static = defn.func.is_class or defn.func.is_static\n override_class = defn.func.is_class\n typ = get_proper_type(typ)\n if isinstance(typ, FunctionLike) and not is_static(context):\n typ = bind_self(typ, self.scope.active_self_type(), is_classmethod=override_class)\n # Map the overridden method type to subtype context so that\n # it can be checked for compatibility.\n original_type = get_proper_type(base_attr.type)\n original_node = base_attr.node\n # `original_type` can be partial if (e.g.) it is originally an\n # instance variable from an `__init__` block that becomes deferred.\n if original_type is None or isinstance(original_type, PartialType):\n if self.pass_num < self.last_pass:\n # If there are passes left, defer this node until next pass,\n # otherwise try reconstructing the method type from available information.\n self.defer_node(defn, defn.info)\n return True\n elif isinstance(original_node, (FuncDef, OverloadedFuncDef)):\n original_type = self.function_type(original_node)\n elif isinstance(original_node, Decorator):\n original_type = self.function_type(original_node.func)\n elif isinstance(original_node, Var):\n # Super type can define method as an attribute.\n # See https://github.com/python/mypy/issues/10134\n\n # We also check that sometimes `original_node.type` is None.\n # This is the case when we use something like `__hash__ = None`.\n if original_node.type is not None:\n original_type = get_proper_type(original_node.type)\n else:\n original_type = NoneType()\n else:\n # Will always fail to typecheck below, since we know the node is a method\n original_type = NoneType()\n if isinstance(original_node, (FuncDef, OverloadedFuncDef)):\n original_class_or_static = original_node.is_class or original_node.is_static\n elif isinstance(original_node, Decorator):\n fdef = original_node.func\n original_class_or_static = fdef.is_class or fdef.is_static\n else:\n original_class_or_static = False # a variable can't be class or static\n\n if isinstance(original_type, FunctionLike):\n original_type = self.bind_and_map_method(base_attr, original_type, defn.info, base)\n if original_node and is_property(original_node):\n original_type = get_property_type(original_type)\n\n if is_property(defn):\n inner: FunctionLike | None\n if isinstance(typ, FunctionLike):\n inner = typ\n else:\n inner = self.extract_callable_type(typ, context)\n if inner is not None:\n typ = inner\n typ = get_property_type(typ)\n if (\n isinstance(original_node, Var)\n and not original_node.is_final\n and (not original_node.is_property or original_node.is_settable_property)\n and isinstance(defn, Decorator)\n ):\n # We only give an error where no other similar errors will be given.\n if not isinstance(original_type, AnyType):\n self.msg.fail(\n \"Cannot override writeable attribute with read-only property\",\n # Give an error on function line to match old behaviour.\n defn.func,\n code=codes.OVERRIDE,\n )\n\n if isinstance(original_type, AnyType) or isinstance(typ, AnyType):\n pass\n elif isinstance(original_type, FunctionLike) and isinstance(typ, FunctionLike):\n # Check that the types are compatible.\n self.check_override(\n typ,\n original_type,\n defn.name,\n name,\n base.name,\n original_class_or_static,\n override_class_or_static,\n context,\n )\n elif is_equivalent(original_type, typ):\n # Assume invariance for a non-callable attribute here. Note\n # that this doesn't affect read-only properties which can have\n # covariant overrides.\n pass\n elif (\n original_node\n and not self.is_writable_attribute(original_node)\n and is_subtype(typ, original_type)\n ):\n # If the attribute is read-only, allow covariance\n pass\n else:\n self.msg.signature_incompatible_with_supertype(\n defn.name, name, base.name, context, original=original_type, override=typ\n )\n return False", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_letter_avatar(\n display_name: str | None,\n identifier: str | int,\n size: int | None = None,\n use_svg: bool | None = True,\n initials: str | None = None,\n rounded: bool | None = False,\n) -> SafeString:\n display_name = (display_name or \"\").strip() or \"?\"\n names = display_name.split(\" \")\n initials = initials or \"{}{}\".format(names[0][0], names[-1][0] if len(names) > 1 else \"\")\n initials = escape(initials.upper())\n color = get_letter_avatar_color(identifier)\n if use_svg:\n size_attrs = f'height=\"{size}\" width=\"{size}\"' if size else \"\"\n return format_html(\n '<svg viewBox=\"0 0 120 120\" xmlns=\"http://www.w3.org/2000/svg\" {size_attrs}>'\n '<rect x=\"0\" y=\"0\" width=\"120\" height=\"120\" rx=\"15\" ry=\"15\" fill={color}></rect>'\n '<text x=\"50%\" y=\"50%\" font-size=\"65\" dominant-baseline=\"central\" text-anchor=\"middle\" fill=\"#FFFFFF\">'\n \"{initials}\"\n \"</text>\"\n \"</svg>\",\n color=color,\n initials=initials,\n size_attrs=size_attrs,\n )\n else:\n size_attrs = f\"height:{size}px;width:{size}px;\" if size else \"\"\n font_size = \"font-size:%spx;\" % (size / 2) if size else \"\"\n line_height = \"line-height:%spx;\" % size if size else \"\"\n span_class = \" rounded\" if rounded else \"\"\n return format_html(\n '<span class=\"html-avatar{span_class}\" '\n 'style=\"background-color:{color};{size_attrs}{font_size}{line_height}\">'\n \"{initials}</span>\",\n color=color,\n initials=initials,\n size_attrs=size_attrs,\n font_size=font_size,\n line_height=line_height,\n span_class=span_class,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def get_attrs(self, item_list, user, **kwargs):\n from sentry.sentry_apps.services.app import app_service\n\n prefetch_related_objects(item_list, \"project\")\n\n environments = Environment.objects.in_bulk(\n [_f for _f in [i.environment_id for i in item_list] if _f]\n )\n\n result = {i: {\"environment\": environments.get(i.environment_id)} for i in item_list}\n ras = list(\n RuleActivity.objects.filter(\n rule__in=item_list, type=RuleActivityType.CREATED.value\n ).select_related(\"rule\")\n )\n\n users = {\n u.id: u\n for u in user_service.get_many_by_id(\n ids=[ra.user_id for ra in ras if ra.user_id is not None]\n )\n }\n\n for rule_activity in ras:\n u = users.get(rule_activity.user_id)\n if u:\n creator = {\n \"id\": u.id,\n \"name\": u.get_display_name(),\n \"email\": u.email,\n }\n else:\n creator = None\n\n result[rule_activity.rule].update({\"created_by\": creator})\n\n rules = {item.id: item for item in item_list}\n\n sentry_app_installations_by_uuid: Mapping[str, RpcSentryAppComponentContext] = {}\n if self.prepare_component_fields:\n sentry_app_uuids = [\n sentry_app_uuid\n for sentry_app_uuid in (\n action.get(\"sentryAppInstallationUuid\")\n for rule in rules.values()\n for action in rule.data.get(\"actions\", [])\n )\n if sentry_app_uuid is not None\n ]\n install_contexts = app_service.get_component_contexts(\n filter={\"uuids\": sentry_app_uuids}, component_type=\"alert-rule-action\"\n )\n sentry_app_installations_by_uuid = {\n install_context.installation.uuid: install_context\n for install_context in install_contexts\n }\n\n for rule in rules.values():\n actor = rule.owner\n if actor:\n result[rule][\"owner\"] = actor.identifier\n\n errors = []\n for action in rule.data.get(\"actions\", []):\n install_context = sentry_app_installations_by_uuid.get(\n str(action.get(\"sentryAppInstallationUuid\"))\n )\n if install_context:\n rpc_install = install_context.installation\n rpc_component = install_context.component\n rpc_app = rpc_install.sentry_app\n\n component = prepare_ui_component(\n rpc_install,\n rpc_component,\n self.project_slug,\n action.get(\"settings\"),\n )\n if component is None:\n errors.append({\"detail\": f\"Could not fetch details from {rpc_app.name}\"})\n action[\"disabled\"] = True\n continue\n\n action[\"formFields\"] = component.app_schema.get(\"settings\", {})\n\n if len(errors):\n result[rule][\"errors\"] = errors\n\n if \"lastTriggered\" in self.expand:\n last_triggered_lookup = {\n rfh[\"rule_id\"]: rfh[\"date_added\"]\n for rfh in RuleFireHistory.objects.filter(rule__in=item_list)\n .values(\"rule_id\")\n .annotate(date_added=Max(\"date_added\"))\n }\n for rule in item_list:\n result[rule][\"last_triggered\"] = last_triggered_lookup.get(rule.id, None)\n\n neglected_rule_lookup = {\n nr[\"rule_id\"]: nr[\"disable_date\"]\n for nr in NeglectedRule.objects.filter(\n rule__in=item_list,\n opted_out=False,\n sent_initial_email_date__isnull=False,\n ).values(\"rule_id\", \"disable_date\")\n }\n for rule in item_list:\n disable_date = neglected_rule_lookup.get(rule.id, None)\n if disable_date:\n result[rule][\"disable_date\"] = disable_date\n\n rule_snooze_lookup = {\n snooze[\"rule_id\"]: {\"user_id\": snooze[\"user_id\"], \"owner_id\": snooze[\"owner_id\"]}\n for snooze in RuleSnooze.objects.filter(\n Q(user_id=user.id) | Q(user_id=None),\n rule__in=[item.id for item in item_list],\n ).values(\"rule_id\", \"user_id\", \"owner_id\")\n }\n\n for rule in item_list:\n snooze = rule_snooze_lookup.get(rule.id, None)\n if snooze:\n result[rule][\"snooze\"] = snooze\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@extend_schema(\n operation_id=\"List an Organization's Projects\",\n parameters=[GlobalParams.ORG_ID_OR_SLUG, CursorQueryParam],\n request=None,\n responses={\n 200: inline_sentry_response_serializer(\n \"OrganizationProjectResponseDict\", list[OrganizationProjectResponse]\n ),\n 401: RESPONSE_UNAUTHORIZED,\n 403: RESPONSE_FORBIDDEN,\n 404: RESPONSE_NOT_FOUND,\n },\n examples=OrganizationExamples.LIST_PROJECTS,\n )\n def get(self, request: Request, organization) -> Response:\n \"\"\"\n Return a list of projects bound to a organization.\n \"\"\"\n stats_period = request.GET.get(\"statsPeriod\")\n collapse = request.GET.getlist(\"collapse\", [])\n if stats_period not in (None, \"\", \"1h\", \"24h\", \"7d\", \"14d\", \"30d\"):\n return Response(\n {\"error\": {\"params\": {\"stats_period\": {\"message\": ERR_INVALID_STATS_PERIOD}}}},\n status=400,\n )\n elif not stats_period:\n # disable stats\n stats_period = None\n\n datasetName = request.GET.get(\"dataset\", \"discover\")\n dataset = get_dataset(datasetName)\n\n if request.auth and not request.user.is_authenticated:\n # TODO: remove this, no longer supported probably\n if hasattr(request.auth, \"project\"):\n queryset = Project.objects.filter(id=request.auth.project.id)\n elif request.auth.organization_id is not None:\n org = request.auth.organization_id\n team_list = list(Team.objects.filter(organization_id=org))\n queryset = Project.objects.filter(teams__in=team_list)\n else:\n return Response(\n {\"detail\": \"Current access does not point to \" \"organization.\"}, status=400\n )\n else:\n queryset = Project.objects.filter(organization=organization)\n\n order_by = [\"slug\"]\n\n if request.user.is_authenticated:\n queryset = queryset.extra(\n select={\n \"is_bookmarked\": \"\"\"exists (\n select *\n from sentry_projectbookmark spb\n where spb.project_id = sentry_project.id and spb.user_id = %s\n )\"\"\"\n },\n select_params=(request.user.id,),\n )\n order_by.insert(0, \"-is_bookmarked\")\n\n query = request.GET.get(\"query\")\n if query:\n tokens = tokenize_query(query)\n for key, value in tokens.items():\n if key == \"query\":\n value = \" \".join(value)\n queryset = queryset.filter(Q(name__icontains=value) | Q(slug__icontains=value))\n elif key == \"id\":\n if all(v.isdigit() for v in value):\n queryset = queryset.filter(id__in=value)\n else:\n return Response(\n {\n \"error\": {\n \"params\": {\n \"stats_period\": {\n \"message\": \"All 'id' values must be integers.\"\n }\n }\n }\n },\n status=400,\n )\n elif key == \"slug\":\n queryset = queryset.filter(slug__in=value)\n elif key == \"team\":\n team_list = list(Team.objects.filter(organization=organization, slug__in=value))\n queryset = queryset.filter(teams__in=team_list)\n elif key == \"!team\":\n team_list = list(Team.objects.filter(organization=organization, slug__in=value))\n queryset = queryset.exclude(teams__in=team_list)\n elif key == \"is_member\":\n queryset = queryset.filter(teams__organizationmember__user_id=request.user.id)\n else:\n queryset = queryset.none()\n\n queryset = queryset.filter(status=ObjectStatus.ACTIVE).distinct()\n\n # TODO(davidenwang): remove this after frontend requires only paginated projects\n get_all_projects = request.GET.get(\"all_projects\") == \"1\"\n\n if get_all_projects:\n queryset = queryset.order_by(\"slug\").select_related(\"organization\")\n return Response(\n serialize(\n list(queryset),\n request.user,\n ProjectSummarySerializer(collapse=collapse, dataset=dataset),\n )\n )\n else:\n expand = set()\n if request.GET.get(\"transactionStats\"):\n expand.add(\"transaction_stats\")\n if request.GET.get(\"sessionStats\"):\n expand.add(\"session_stats\")\n\n expand_context = {\"options\": request.GET.getlist(\"options\") or []}\n if expand_context:\n expand.add(\"options\")\n\n def serialize_on_result(result):\n environment_id = self._get_environment_id_from_request(request, organization.id)\n serializer = ProjectSummarySerializer(\n environment_id=environment_id,\n stats_period=stats_period,\n expand=expand,\n expand_context=expand_context,\n collapse=collapse,\n dataset=dataset,\n )\n return serialize(result, request.user, serializer)\n\n return self.paginate(\n request=request,\n queryset=queryset,\n order_by=order_by,\n on_results=serialize_on_result,\n paginator_cls=OffsetPaginator,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@method_decorator(never_cache)\n def handle(self, request, channel, resource_id):\n if request.subdomain is not None:\n return self.redirect(reverse(\"sentry-auth-organization\", args=[request.subdomain]))\n\n config_data = request.GET.get(\"config_data\", \"\")\n\n if not config_data:\n # NOTE: This provider_config may differ per provider\n # Allow providers to supply their own config_data, otherwise\n # construct one with the resource_id (NOT the sentry org id)\n provider = CHANNEL_PROVIDER_MAP[channel]\n config_data = provider.build_config(resource={\"id\": resource_id})\n\n # Checking for duplicate orgs\n auth_provider_model = AuthProvider.objects.filter(provider=channel, config=config_data)\n\n if not auth_provider_model.exists() or len(auth_provider_model) > 1:\n return self.redirect(reverse(\"sentry-login\"))\n\n organization_id = auth_provider_model[0].organization_id\n try:\n slug = OrganizationMapping.objects.get(organization_id=organization_id).slug\n except OrganizationMapping.DoesNotExist:\n return self.redirect(reverse(\"sentry-login\"))\n\n next_uri = self.get_next_uri(request)\n # If user has an active session within the same organization skip login\n if request.user.is_authenticated:\n if self.active_organization is not None:\n if self.active_organization.organization.id == organization_id:\n if is_valid_redirect(next_uri, allowed_hosts=(request.get_host())):\n return self.redirect(next_uri)\n return self.redirect(Organization.get_url(slug=slug))\n\n # If user doesn't have active session within the same organization redirect to login for the\n # organization in the url\n org_auth_url = reverse(\"sentry-auth-organization\", args=[slug])\n redirect_url = (\n org_auth_url + \"?next=\" + next_uri\n if is_valid_redirect(next_uri, allowed_hosts=(request.get_host()))\n else org_auth_url\n )\n return self.redirect(redirect_url)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def put(self, request: Request, app_id) -> Response:\n try:\n instance = ApiApplication.objects.get(\n owner_id=request.user.id, client_id=app_id, status=ApiApplicationStatus.active\n )\n except ApiApplication.DoesNotExist:\n raise ResourceDoesNotExist\n\n serializer = ApiApplicationSerializer(data=request.data, partial=True)\n\n if serializer.is_valid():\n result = serializer.validated_data\n kwargs = {}\n if \"name\" in result:\n kwargs[\"name\"] = result[\"name\"]\n if \"allowedOrigins\" in result:\n kwargs[\"allowed_origins\"] = \"\\n\".join(result[\"allowedOrigins\"])\n if \"redirectUris\" in result:\n kwargs[\"redirect_uris\"] = \"\\n\".join(result[\"redirectUris\"])\n if \"homepageUrl\" in result:\n kwargs[\"homepage_url\"] = result[\"homepageUrl\"]\n if \"privacyUrl\" in result:\n kwargs[\"privacy_url\"] = result[\"privacyUrl\"]\n if \"termsUrl\" in result:\n kwargs[\"terms_url\"] = result[\"termsUrl\"]\n if kwargs:\n instance.update(**kwargs)\n return Response(serialize(instance, request.user), status=200)\n return Response(serializer.errors, status=400)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def upgrade():\n op.add_column(\"user\", Column(\"order_portal_login\", mysql.BOOLEAN, default=False))\n\n op.add_column(\n \"customer\",\n Column(\"delivery_contact_id\", mysql.INTEGER(display_width=11), autoincrement=False),\n )\n op.add_column(\n \"customer\",\n Column(\"invoice_contact_id\", mysql.INTEGER(display_width=11), autoincrement=False),\n )\n op.add_column(\n \"customer\",\n Column(\"primary_contact_id\", mysql.INTEGER(display_width=11), autoincrement=False),\n )\n\n bind = op.get_bind()\n session = orm.Session(bind=bind)\n\n count = 0\n # replace email addresses on customers with connection between customer and user using users email\n for customer in session.query(Customer):\n if customer.delivery_contact_email:\n user = session.query(User).filter(User.email == customer.delivery_contact_email).first()\n if user:\n customer.delivery_contact_id = user.id\n print(\n f\"connecting user {user.id} directly to customer {customer.id} as delivery_contact\"\n )\n count += 1\n else:\n print(\n f\"WARNING: could not find any user with email {customer.delivery_contact_email} to connect customer {customer.id} as delivery_contact\"\n )\n\n if customer.invoice_contact_email:\n user = session.query(User).filter(User.email == customer.invoice_contact_email).first()\n if user:\n customer.invoice_contact_id = user.id\n print(\n f\"connecting user {user.id} directly to customer {customer.id} as invoice_contact\"\n )\n count += 1\n else:\n print(\n f\"WARNING: could not find any user with email {customer.invoice_contact_email} to connect customer {customer.id} as invoice_contact\"\n )\n\n if customer.primary_contact_email:\n user = session.query(User).filter(User.email == customer.primary_contact_email).first()\n if user:\n customer.primary_contact_id = user.id\n print(\n f\"connecting user {user.id} directly to customer {customer.id} as primary_contact\"\n )\n count += 1\n else:\n print(\n f\"WARNING: could not find any user with email {customer.primary_contact_email} to connect customer {customer.id} as primary_contact\"\n )\n\n session.commit()\n print(f\"Changed {count} connections\")\n\n count = 0\n for user in session.query(User):\n user.order_portal_login = True\n count += 1\n session.commit()\n print(f\"Added {count} order portal logins\")\n\n op.create_foreign_key(\n \"delivery_contact_ibfk_1\",\n \"customer\",\n \"user\",\n [\"delivery_contact_id\"],\n [\"id\"],\n )\n op.create_foreign_key(\n \"invoice_contact_ibfk_1\",\n \"customer\",\n \"user\",\n [\"invoice_contact_id\"],\n [\"id\"],\n )\n op.create_foreign_key(\n \"primary_contact_ibfk_1\",\n \"customer\",\n \"user\",\n [\"primary_contact_id\"],\n [\"id\"],\n )\n\n op.drop_column(\"customer\", \"delivery_contact_email\")\n op.drop_column(\"customer\", \"invoice_contact_email\")\n op.drop_column(\"customer\", \"primary_contact_email\")\n op.drop_column(\"customer\", \"delivery_contact_name\")\n op.drop_column(\"customer\", \"invoice_contact_name\")\n op.drop_column(\"customer\", \"primary_contact_name\")", "smellKey": "S3776", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def DoCoProcessingSub(datadescription):\n \"Callback to do co-processing for current timestep\"\n\n global gDoCoProcessingCount\n myDebugPrint3(\"PhactoriDriver.DoCoProcessingSub entered: \" + str(gDoCoProcessingCount)+ \"\\n\");\n\n gDoCoProcessingCount += 1\n\n\n fd = datadescription.GetUserData()\n \n if GetBypassUserDataFlag() == False:\n if fd == None:\n myDebugPrint2(\"no user data, returning {}\\n\")\n returnViewMapC = {}\n return returnViewMapC\n \n global coprocessor\n global gFirstTimeInDoCoProcessing\n global gSkipCountdown\n\n if gFirstTimeInDoCoProcessing == True:\n myDebugPrint2(\"DoCoProcessing doing gFirstTimeInDoCoProcessing\\n\")\n myDebugPrint2(\" skip countdown is \" + str(gSkipCountdown) + \"\\n\")\n if gSkipCountdown > 0:\n return\n coprocessor = CreateCoProcessor()\n coprocessor.SetInitialUpdateFrequences(datadescription)\n coprocessor.EnableLiveVisualization(False)\n gFirstTimeInDoCoProcessing = False\n else:\n coprocessor.SetInitialUpdateFrequences(datadescription)\n\n #import pdb\n #pdb.set_trace()\n\n InitializePerPipeRoot(datadescription, coprocessor)\n\n \"Callback to do co-processing for current timestep\"\n timestep = datadescription.GetTimeStep()\n\n myDebugPrint(\"timestep is: \" + str(timestep) + \"\\n\");\n\n SmartGetLocalProcessId()\n\n # Load the Pipeline if not created yet\n #if not pipeline:\n # myDebugPrint(\"PhactoriDriver.DoCoProcessing creating pipeline\\n\");\n # pipeline = CreatePipeline(datadescription)\n #else:\n # myDebugPrint(\"PhactoriDriver.DoCoProcessing updating pipeline\\n\");\n # # update to the new input and time\n # UpdateProducers(datadescription)\n # PerFrameUpdate(datadescription)\n\n\n # Update the coprocessor by providing it the newly generated simulation data.\n # If the pipeline hasn't been setup yet, this will setup the pipeline.\n coprocessor.UpdateProducers(datadescription)\n\n PerFrameUpdate(datadescription)\n\n # check for simulation-data-based i/o filtering--skip image creation\n # and writing if criteria has been set up to determine whether to\n # create images, such as 'maximum of variable X above 80.0'\n result = WriteOutImagesTest(datadescription, coprocessor)\n if result == False:\n #don't write images\n return\n\n # Write output data, if appropriate.\n #coprocessor.WriteData(datadescription);\n\n # Write output data\n #WriteAllData(datadescription, cp_writers, timestep);\n\n # Write image capture (Last arg: rescale lookup table)\n #myDebugPrint(\"PhactoriDriver.DoCoProcessing writing images\\n\");\n #LocalWriteAllImages(datadescription, cp_views, timestep, False)\n #WriteAllImages(datadescription, cp_views, timestep, False)\n\n # Live Visualization\n #if (len(cp_views) == 0) and live_visu_active:\n # DoLiveInsitu(timestep, pv_host, pv_port)\n\n # Write output data, if appropriate.\n coprocessor.WriteData(datadescription)\n\n coprocessor.LocalExportOperationsData3(datadescription)\n \n # Write image capture (Last arg: rescale lookup table), if appropriate.\n coprocessor.LocalWriteImages3(datadescription,\n rescale_lookuptable=False)\n\n #test and allow for looping when doing user vis interaction while\n #pausing simulation\n continueWriteAndInteractionCheckLoop = True\n while continueWriteAndInteractionCheckLoop:\n interactionTestResult = \\\n DoUserInteractionWithSimulationPausedIfEnabled()\n if interactionTestResult == 0:\n #looping interaction is not or is no longer on; allow simulation to\n #continue\n continueWriteAndInteractionCheckLoop = False\n elif interactionTestResult == 1:\n #looping interaction is on, but there were no changes to the vis\n #(i.e. no trigger was given to update vis). Therefore do not write\n #images, but continue looping and waiting for vis change trigger\n continueWriteAndInteractionCheckLoop = True\n elif interactionTestResult == 2:\n #there was a vis change triggered; update the images for the new\n #vis, write out the images, and continue looping\n continueWriteAndInteractionCheckLoop = True\n imagesNeedWriting = True\n if imagesNeedWriting:\n UpdateAllImagesetViewsWhichMayChangeWithData()\n coprocessor.LocalExportOperationsData3(datadescription)\n coprocessor.LocalWriteImages3(datadescription,\n rescale_lookuptable=False)\n\n #coprocessor.WriteImages(datadescription, rescale_lookuptable=True)\n\n # Live Visualization, if enabled.\n coprocessor.DoLiveVisualization(datadescription, \"localhost\", 22222)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def check_boolean_op(self, e: OpExpr, context: Context) -> Type:\n \"\"\"Type check a boolean operation ('and' or 'or').\"\"\"\n\n # A boolean operation can evaluate to either of the operands.\n\n # We use the current type context to guide the type inference of of\n # the left operand. We also use the left operand type to guide the type\n # inference of the right operand so that expressions such as\n # '[1] or []' are inferred correctly.\n ctx = self.type_context[-1]\n left_type = self.accept(e.left, ctx)\n expanded_left_type = try_expanding_sum_type_to_union(\n self.accept(e.left, ctx), \"builtins.bool\"\n )\n\n assert e.op in (\"and\", \"or\") # Checked by visit_op_expr\n\n if e.right_always:\n left_map: mypy.checker.TypeMap = None\n right_map: mypy.checker.TypeMap = {}\n elif e.right_unreachable:\n left_map, right_map = {}, None\n elif e.op == \"and\":\n right_map, left_map = self.chk.find_isinstance_check(e.left)\n elif e.op == \"or\":\n left_map, right_map = self.chk.find_isinstance_check(e.left)\n\n # If left_map is None then we know mypy considers the left expression\n # to be redundant.\n if (\n codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes\n and left_map is None\n # don't report an error if it's intentional\n and not e.right_always\n ):\n self.msg.redundant_left_operand(e.op, e.left)\n\n if (\n self.chk.should_report_unreachable_issues()\n and right_map is None\n # don't report an error if it's intentional\n and not e.right_unreachable\n ):\n self.msg.unreachable_right_operand(e.op, e.right)\n\n # If right_map is None then we know mypy considers the right branch\n # to be unreachable and therefore any errors found in the right branch\n # should be suppressed.\n with self.msg.filter_errors(filter_errors=right_map is None):\n right_type = self.analyze_cond_branch(right_map, e.right, expanded_left_type)\n\n if left_map is None and right_map is None:\n return UninhabitedType()\n\n if right_map is None:\n # The boolean expression is statically known to be the left value\n assert left_map is not None\n return left_type\n if left_map is None:\n # The boolean expression is statically known to be the right value\n assert right_map is not None\n return right_type\n\n if e.op == \"and\":\n restricted_left_type = false_only(expanded_left_type)\n result_is_left = not expanded_left_type.can_be_true\n elif e.op == \"or\":\n restricted_left_type = true_only(expanded_left_type)\n result_is_left = not expanded_left_type.can_be_false\n\n if isinstance(restricted_left_type, UninhabitedType):\n # The left operand can never be the result\n return right_type\n elif result_is_left:\n # The left operand is always the result\n return left_type\n else:\n return make_simplified_union([restricted_left_type, right_type])", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def transfer_to(self, organization):\n from sentry.deletions.models.scheduleddeletion import RegionScheduledDeletion\n from sentry.incidents.models.alert_rule import AlertRule\n from sentry.integrations.models.external_issue import ExternalIssue\n from sentry.models.environment import Environment, EnvironmentProject\n from sentry.models.projectteam import ProjectTeam\n from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment\n from sentry.models.releases.release_project import ReleaseProject\n from sentry.models.rule import Rule\n from sentry.monitors.models import Monitor\n\n old_org_id = self.organization_id\n org_changed = old_org_id != organization.id\n\n self.organization = organization\n\n try:\n with transaction.atomic(router.db_for_write(Project)):\n self.update(organization=organization)\n except IntegrityError:\n slugify_instance(self, self.name, organization=organization, max_length=50)\n self.update(slug=self.slug, organization=organization)\n\n # Both environments and releases are bound at an organization level.\n # Due to this, when you transfer a project into another org, we have to\n # handle this behavior somehow. We really only have two options here:\n # * Copy over all releases/environments into the new org and handle de-duping\n # * Delete the bindings and let them reform with new data.\n # We're generally choosing to just delete the bindings since new data\n # flowing in will recreate links correctly. The tradeoff is that\n # historical data is lost, but this is a compromise we're willing to\n # take and a side effect of allowing this feature. There are exceptions\n # to this however, such as rules, which should maintain their\n # configuration when moved across organizations.\n if org_changed:\n for model in ReleaseProject, ReleaseProjectEnvironment, EnvironmentProject:\n model.objects.filter(project_id=self.id).delete()\n # this is getting really gross, but make sure there aren't lingering associations\n # with old orgs or teams\n ProjectTeam.objects.filter(project=self, team__organization_id=old_org_id).delete()\n\n rules_by_environment_id = defaultdict(set)\n for rule_id, environment_id in Rule.objects.filter(\n project_id=self.id, environment_id__isnull=False\n ).values_list(\"id\", \"environment_id\"):\n assert environment_id is not None\n rules_by_environment_id[environment_id].add(rule_id)\n\n environment_names = dict(\n Environment.objects.filter(organization_id=old_org_id).values_list(\"id\", \"name\")\n )\n\n for environment_id, rule_ids in rules_by_environment_id.items():\n Rule.objects.filter(id__in=rule_ids).update(\n environment_id=Environment.get_or_create(self, environment_names[environment_id]).id\n )\n\n # Manually move over organization id's for Monitors\n monitors = Monitor.objects.filter(organization_id=old_org_id, project_id=self.id)\n new_monitors = set(\n Monitor.objects.filter(organization_id=organization.id).values_list(\"slug\", flat=True)\n )\n for monitor in monitors:\n if monitor.slug in new_monitors:\n RegionScheduledDeletion.schedule(monitor, days=0)\n else:\n for monitor_env_id, env_id in MonitorEnvironment.objects.filter(\n monitor_id=monitor.id, status=MonitorStatus.ACTIVE\n ).values_list(\"id\", \"environment_id\"):\n MonitorEnvironment.objects.filter(id=monitor_env_id).update(\n environment_id=Environment.get_or_create(\n self, name=environment_names.get(env_id, None)\n ).id\n )\n monitor.update(organization_id=organization.id)\n\n # Remove alert owners not in new org\n alert_rules = AlertRule.objects.fetch_for_project(self).filter(\n Q(user_id__isnull=False) | Q(team_id__isnull=False)\n )\n for alert_rule in alert_rules:\n is_member = False\n if alert_rule.user_id:\n is_member = organization.member_set.filter(user_id=alert_rule.user_id).exists()\n if alert_rule.team_id:\n is_member = Team.objects.filter(\n organization_id=organization.id, id=alert_rule.team_id\n ).exists()\n if not is_member:\n alert_rule.update(team_id=None, user_id=None)\n rule_models = Rule.objects.filter(\n Q(owner_team_id__isnull=False) | Q(owner_user_id__isnull=False), project=self\n )\n for rule_model in rule_models:\n is_member = False\n if rule_model.owner_user_id:\n is_member = organization.member_set.filter(\n user_id=rule_model.owner_user_id\n ).exists()\n if rule_model.owner_team_id:\n is_member = Team.objects.filter(\n organization_id=organization.id, id=rule_model.owner_team_id\n ).exists()\n if not is_member:\n rule_model.update(owner_user_id=None, owner_team_id=None)\n\n # [Rule, AlertRule(SnubaQuery->Environment)]\n # id -> name\n environment_names_with_alerts = {\n **environment_names,\n **{\n env_id: env_name\n for env_id, env_name in AlertRule.objects.fetch_for_project(self).values_list(\n \"snuba_query__environment__id\", \"snuba_query__environment__name\"\n )\n },\n }\n\n # conditionally create a new environment associated to the new Org -> Project -> AlertRule -> SnubaQuery\n # this should take care of any potentially dead references from SnubaQuery -> Environment when deleting\n # the old org\n # alertrule -> snuba_query -> environment_id\n for snuba_id, environment_id in AlertRule.objects.fetch_for_project(self).values_list(\n \"snuba_query_id\", \"snuba_query__environment__id\"\n ):\n SnubaQuery.objects.filter(id=snuba_id).update(\n environment_id=Environment.get_or_create(\n self, name=environment_names_with_alerts.get(environment_id, None)\n ).id\n )\n\n AlertRule.objects.fetch_for_project(self).update(organization=organization)\n\n # Manually move over external issues to the new org\n linked_groups = GroupLink.objects.filter(project_id=self.id).values_list(\n \"linked_id\", flat=True\n )\n\n for external_issues in chunked(\n RangeQuerySetWrapper(\n ExternalIssue.objects.filter(organization_id=old_org_id, id__in=linked_groups),\n step=1000,\n ),\n 1000,\n ):\n for ei in external_issues:\n ei.organization_id = organization.id\n ExternalIssue.objects.bulk_update(external_issues, [\"organization_id\"])", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, path, fname2path, raw=None,\n require_compatible=True, require_description=True):\n \"\"\"\n Binding constructor.\n\n path:\n Path to binding YAML file. May be None.\n\n fname2path:\n Map from include files to their absolute paths. Must\n not be None, but may be empty.\n\n raw:\n Optional raw content in the binding.\n This does not have to have any \"include:\" lines resolved.\n May be left out, in which case 'path' is opened and read.\n This can be used to resolve child bindings, for example.\n\n require_compatible:\n If True, it is an error if the binding does not contain a\n \"compatible:\" line. If False, a missing \"compatible:\" is\n not an error. Either way, \"compatible:\" must be a string\n if it is present in the binding.\n\n require_description:\n If True, it is an error if the binding does not contain a\n \"description:\" line. If False, a missing \"description:\" is\n not an error. Either way, \"description:\" must be a string\n if it is present in the binding.\n \"\"\"\n self.path = path\n self._fname2path = fname2path\n\n if raw is None:\n with open(path, encoding=\"utf-8\") as f:\n raw = yaml.load(f, Loader=_BindingLoader)\n\n # Merge any included files into self.raw. This also pulls in\n # inherited child binding definitions, so it has to be done\n # before initializing those.\n self.raw = self._merge_includes(raw, self.path)\n\n # Recursively initialize any child bindings. These don't\n # require a 'compatible' or 'description' to be well defined,\n # but they must be dicts.\n if \"child-binding\" in raw:\n if not isinstance(raw[\"child-binding\"], dict):\n _err(f\"malformed 'child-binding:' in {self.path}, \"\n \"expected a binding (dictionary with keys/values)\")\n self.child_binding = Binding(path, fname2path,\n raw=raw[\"child-binding\"],\n require_compatible=False,\n require_description=False)\n else:\n self.child_binding = None\n\n # Make sure this is a well defined object.\n self._check(require_compatible, require_description)\n\n # Initialize look up tables.\n self.prop2specs = OrderedDict()\n for prop_name in self.raw.get(\"properties\", {}).keys():\n self.prop2specs[prop_name] = PropertySpec(prop_name, self)\n self.specifier2cells = OrderedDict()\n for key, val in self.raw.items():\n if key.endswith(\"-cells\"):\n self.specifier2cells[key[:-len(\"-cells\")]] = val", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def check_dangerous_keywords(self):\n result = []\n for root, dirs, files in os.walk(self.work_dir):\n for f in files:\n try:\n if str(f).endswith('.yml') or str(f).endswith('.yaml'):\n lines = self.search_keywords(os.path.join(root, f))\n if len(lines) > 0:\n for line in lines:\n result.append({'file': f, 'line': line[0], 'keyword': line[1]})\n # \u9047\u5230\u65e0\u6cd5\u8bfb\u53d6\u7684\u6587\u4ef6\uff0c\u8df3\u8fc7\n except UnicodeEncodeError:\n continue\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def _openc3_script_wait(\n target_name,\n packet_name,\n item_name,\n value_type,\n timeout,\n polling_rate,\n exp_to_eval,\n scope,\n):\n value = None\n end_time = time.time() + timeout\n if exp_to_eval and not exp_to_eval.isascii():\n raise RuntimeError(\"ERROR: Invalid comparison to non-ascii value\")\n\n try:\n while True:\n work_start = time.time()\n value = getattr(openc3.script.API_SERVER, \"tlm\")(\n target_name, packet_name, item_name, type=value_type, scope=scope\n )\n try:\n if eval(exp_to_eval):\n return True, value\n # We get TypeError when trying to eval None >= 0 (for example)\n # In this case we just continue and see if eventually we get a good value from tlm()\n except TypeError:\n pass\n if time.time() >= end_time:\n break\n\n delta = time.time() - work_start\n sleep_time = polling_rate - delta\n end_delta = end_time - time.time()\n if end_delta < sleep_time:\n sleep_time = end_delta\n if sleep_time < 0:\n sleep_time = 0\n canceled = openc3_script_sleep(sleep_time)\n\n if canceled:\n value = getattr(openc3.script.API_SERVER, \"tlm\")(\n target_name, packet_name, item_name, type=value_type, scope=scope\n )\n try:\n if eval(exp_to_eval):\n return True, value\n else:\n return False, value\n # We get TypeError when trying to eval None >= 0 (for example)\n except TypeError:\n return False, value\n\n except NameError as error:\n parts = error.args[0].split(\"'\")\n new_error = NameError(f\"Uninitialized constant {parts[1]}. Did you mean '{parts[1]}' as a string?\")\n raise new_error from error\n\n return False, value", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def CreateViewSetFromPhactoriViewMapC(inViewMapC):\n \"\"\"Create data pipeline, cameras, representations, and views from data struct\n\n Given a dict which is a json format structure with syntax as discussed in\n the sierra catalyst paraview insitu wiki, create the corresponding data\n pipeline, representations, views, etc. The basic idea is that from the\n incoming datastructure, we will parse out 6 (currently) sets of blocks:\n operations, cameras, representations, imagesets, scatter plots, and plots\n over time. From these, we will construct ParaView/Catalyst data structures\n to do the data management and rendering. See the class\n PhactoriPipeAndViewsState and the lower level related classes for more\n explaination.\n \"\"\"\n\n if PhactoriDbg(100):\n myDebugPrint3('CreateViewSetFromPhactoriViewMapC entered\\n', 100)\n if PhactoriDbg():\n myDebugPrint3(str(inViewMapC) + \"\\n\")\n global gPipeAndViewsState\n gPipeAndViewsState.mJsonDescription = inViewMapC\n \n #get pointers to the various block types (currently 6, camera,\n #representation, operation, imageset, plot over time, and scatter plot)\n\n #check for 'experimental blocks' and handle them appropriately if they\n #are there (e.g. use them to create other blocks)\n PreprocessExperimentalBlocks(inViewMapC)\n\n cameraBlocks = {}\n representationBlocks = {}\n imagesetBlocks = {}\n operationBlocks = {}\n scatterplotBlocks = {}\n timeplotBlocks = {}\n criteriaBlocks = {}\n markerBlocks = {}\n textannotationBlocks = {}\n if 'camera blocks' in inViewMapC:\n cameraBlocks = inViewMapC['camera blocks']\n if 'representation blocks' in inViewMapC:\n representationBlocks = inViewMapC['representation blocks']\n if 'imageset blocks' in inViewMapC:\n imagesetBlocks = inViewMapC['imageset blocks']\n if 'operation blocks' in inViewMapC:\n operationBlocks = inViewMapC['operation blocks']\n if 'scatter plot blocks' in inViewMapC:\n scatterplotBlocks = inViewMapC['scatter plot blocks']\n if 'plot over time blocks' in inViewMapC:\n timeplotBlocks = inViewMapC['plot over time blocks']\n if 'onoff criteria blocks' in inViewMapC:\n criteriaBlocks = inViewMapC['onoff criteria blocks']\n if 'visual marker blocks' in inViewMapC:\n markerBlocks = inViewMapC['visual marker blocks']\n if 'text annotation blocks' in inViewMapC:\n textannotationBlocks = inViewMapC['text annotation blocks']\n if PhactoriDbg():\n myDebugPrint3(\" cameraBlocks:\\n\")\n myDebugPrint3(\" \" + str(cameraBlocks) + \"\\n\")\n myDebugPrint3(\" representationBlocks:\\n\")\n myDebugPrint3(\" \" + str(representationBlocks) + \"\\n\")\n myDebugPrint3(\" imagesetBlocks:\\n\")\n myDebugPrint3(\" \" + str(imagesetBlocks) + \"\\n\")\n myDebugPrint3(\" operationBlocks:\\n\")\n myDebugPrint3(\" \" + str(operationBlocks) + \"\\n\")\n myDebugPrint3(\" scatterplotBlocks:\\n\")\n myDebugPrint3(\" \" + str(scatterplotBlocks) + \"\\n\")\n myDebugPrint3(\" timeplotBlocks:\\n\")\n myDebugPrint3(\" \" + str(timeplotBlocks) + \"\\n\")\n myDebugPrint3(\" onoff criteria blocks:\\n\")\n myDebugPrint3(\" \" + str(criteriaBlocks) + \"\\n\")\n myDebugPrint3(\" visual marker blocks:\\n\")\n myDebugPrint3(\" \" + str(markerBlocks) + \"\\n\")\n myDebugPrint3(\" text annotation blocks:\\n\")\n myDebugPrint3(\" \" + str(textannotationBlocks) + \"\\n\")\n\n #go through imageset json, and locate operation shortcuts. If found, create\n #json defintion of operations and add them to the structure for later\n #creation, and add reference to the new operations in the imageblock json\n HandleOperationShortcuts(imagesetBlocks, operationBlocks)\n\n #do pipeline stuff\n gPipeAndViewsState.mIncomingDefaultOperation.mParaViewFilter = GetActiveSource()\n\n global gEnableTemporaryExtractBlockTest\n if gEnableTemporaryExtractBlockTest:\n #hack to test extract block filter\n if gExtractBlockAOperationName in operationBlocks:\n global gExtractBlockAList\n theBlock = operationBlocks[gExtractBlockAOperationName]\n theBlock['type'] = 'extractblock'\n theBlock['include blocks'] = gExtractBlockAList\n if gExtractBlockBOperationName in operationBlocks:\n global gExtractBlockBList\n theBlock = operationBlocks[gExtractBlockBOperationName]\n theBlock['type'] = 'extractblock'\n theBlock['include blocks'] = gExtractBlockBList\n\n #to test imagesets with multiple operations visible\n if gEnableTemporaryMultiOpViewTest:\n if gMultiOpViewTestImagesetName in imagesetBlocks:\n theBlock = imagesetBlocks[\"multioptestimageset\"]\n theBlock[\"operation2\"] = gMultiOpViewTestOp2Name\n theBlock[\"representation2\"] = gMultiOpViewTestRep2Name\n\n global gEnableTemporaryOffAxisProjectionTest\n if gEnableTemporaryOffAxisProjectionTest:\n global gOaptCameraNameList\n\n #go through cameras and set up stereo ones\n for oneOaptCameraName in gOaptCameraNameList:\n if oneOaptCameraName in cameraBlocks:\n global gOaptPhysicalSettingsForCamera\n physicalSettingsForCamera = \\\n gOaptPhysicalSettingsForCamera[oneOaptCameraName]\n theBlock = cameraBlocks[oneOaptCameraName]\n theBlock['use off axis projection'] = True\n for key, value in physicalSettingsForCamera.items():\n theBlock[key] = value\n theBlock['which eye'] = 'left'\n #copy this camera to another to use for right eye\n rightCameraName = oneOaptCameraName + \"Right\"\n rightCameraBlock = {}\n for key, value in theBlock.items():\n rightCameraBlock[key] = value\n rightCameraBlock['which eye'] = 'right'\n cameraBlocks[rightCameraName] = rightCameraBlock\n if PhactoriDbg():\n myDebugPrint3(\"new camera block for right eye:\\n\"\n + str(rightCameraBlock) + \"\\n\")\n\n #go through imageset blocks and add extras for stereo\n blocksToReplicateForRightEye = []\n for imagesetName, oneImagesetBlock in imagesetBlocks.items():\n if 'camera' in oneImagesetBlock:\n if oneImagesetBlock['camera'] in gOaptCameraNameList:\n blocksToReplicateForRightEye.append(\n [imagesetName, oneImagesetBlock])\n if PhactoriDbg():\n myDebugPrint3(\"blocksToReplicateForRightEye:\\n\"\n + str(blocksToReplicateForRightEye) + \"\\n\")\n for iterItem in blocksToReplicateForRightEye:\n oneImagesetName = iterItem[0]\n oneImagesetBlock = iterItem[1]\n newImagesetBlock = {}\n for key, value in oneImagesetBlock.items():\n newImagesetBlock[key] = value\n rightCameraName = oneImagesetBlock['camera'] + \"Right\"\n newImagesetBlock['camera'] = rightCameraName\n imagesetBaseName = str(oneImagesetBlock['image basename'])\n oneImagesetBlock['image basename'] = imagesetBaseName + \"left.\"\n newImagesetBlock['image basename'] = imagesetBaseName + \"right.\"\n if PhactoriDbg():\n myDebugPrint3(\"new imageset block for right eye:\\n\"\n + str(newImagesetBlock) + \"\\n\")\n imagesetBlocks[oneImagesetName + \"Right\"] = newImagesetBlock\n\n #swap out operations from input deck for testing operations which aren't\n #available through the input deck syntax yet\n global gEnableSubstituteOperationTesting\n if gEnableSubstituteOperationTesting:\n global gSubstituteOperationTestingList\n global gSubstituteOperationTestingMap\n for oneOpName in gSubstituteOperationTestingList:\n if oneOpName in operationBlocks:\n if PhactoriDbg():\n myDebugPrint3(\"substituting operation named: \" + oneOpName + \"\\n\")\n oneOpBlock = operationBlocks[oneOpName]\n subOpBlock = gSubstituteOperationTestingMap[oneOpName]\n if 'input' in oneOpBlock:\n subOpBlock['input'] = oneOpBlock['input']\n operationBlocks[oneOpName] = subOpBlock\n\n #swap out imagesets from input deck for testing imagesets which aren't\n #available through the input deck syntax yet\n global gEnableSubstituteImagesetTesting\n if gEnableSubstituteImagesetTesting:\n global gSubstituteImagesetTestingList\n global gSubstituteImagesetTestingMap\n for oneIsName in gSubstituteImagesetTestingList:\n if oneIsName in imagesetBlocks:\n oneIsBlock = imagesetBlocks[oneIsName]\n subIsBlock = gSubstituteImagesetTestingMap[oneIsName]\n for key, value in subIsBlock.items():\n oneIsBlock[key] = value\n\n MakeFiltersFromViewMapOperationsC(gPipeAndViewsState, operationBlocks)\n if PhactoriDbg():\n myDebugPrint3(' gPipeAndViewsState.mOperationBlocks: ' + \\\n str(gPipeAndViewsState.mOperationBlocks) + '\\n')\n\n #parse scatter plot blocks\n\n #special case; check for 'all variables' in a scatter plot and contruct all\n #plot json blocks if necessary\n TestForAndConstructAllScatterPlots(scatterplotBlocks)\n\n #ParseScatterPlotBlocksC(gPipeAndViewsState, scatterplotBlocks)\n #ParseBlocksC(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,\n # PhactoriScatterPlotBlock, ParseOneScatterPlotBlockC,\n # gPipeAndViewsState)\n ParseBlocksC2(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,\n PhactoriScatterPlotBlock, gPipeAndViewsState)\n\n #special case; check for 'all variables' in a plot over time and contruct all\n #plot json blocks if necessary\n TestForAndConstructAllPlotsOverTime(timeplotBlocks)\n\n #parse time plot blocks\n ParseBlocksC(gPipeAndViewsState.mPlotOverTimeBlocks, timeplotBlocks,\n PhactoriPlotOverTimeBlock, ParseOnePlotOverTimeBlockC,\n gPipeAndViewsState)\n\n #create producers for plots\n CreateScatterPlotProducersC(gPipeAndViewsState)\n CreatePlotOverTimeProducersC(gPipeAndViewsState)\n\n #parse camera blocks\n #ParseCameraBlocksC(gPipeAndViewsState, cameraBlocks)\n ParseBlocksC(gPipeAndViewsState.mCameraBlocks, cameraBlocks,\n PhactoriCameraBlock, ParseOneCameraBlockC,\n gPipeAndViewsState)\n\n #parse representation blocks\n #ParseRepresentationBlocksC(gPipeAndViewsState, representationBlocks)\n ParseBlocksC(gPipeAndViewsState.mRepresentationBlocks, representationBlocks,\n PhactoriRepresentationBlock, ParseOneRepresentationBlockC,\n gPipeAndViewsState)\n\n #parse imageset onoff criteria blocks\n ParseBlocksC(gPipeAndViewsState.mImagesetOnOffCriteriaBlocks, criteriaBlocks,\n PhactoriImagesetOnOffFilterCriteria, ParseOneCriteriaBlockC,\n gPipeAndViewsState)\n\n #parse visual marker blocks\n numMarkerBlocks = ParseBlocksC(\n gPipeAndViewsState.mMarkerBlocks,\n markerBlocks, PhactoriMarkerBlock,\n ParseOneMarkerBlockC, gPipeAndViewsState)\n\n #parse text annotation blocks\n numTextAnnotationBlocks = ParseBlocksC(\n gPipeAndViewsState.mTextAnnotationBlocks,\n textannotationBlocks, PhactoriTextAnnotationBlock,\n ParseOneTextAnnotationBlockC, gPipeAndViewsState)\n\n #construct marker paraview items (e.g. sphere or box source and the\n #corresponding representation\n #this is now done the first time the marker is made visible\n #for oneMarkerName, oneMarkerBlock in \\\n # gPipeAndViewsState.mMarkerBlocks.iteritems():\n # oneMarkerBlock.CreateParaViewItems()\n\n #parse imageset blocks\n #ParseImagesetBlocksC(gPipeAndViewsState, imagesetBlocks)\n numImagesetBlocks = ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,\n PhactoriImagesetBlock, ParseOneImagesetBlockC,\n gPipeAndViewsState)\n\n #if there are no imageset blocks, create default and parse parameters in\n #wrappint imagesetBlock json as if they were from an imageset block\n if numImagesetBlocks == 0:\n if PhactoriDbg():\n myDebugPrint3(\" no imagesets, creating a default imageset\\n\")\n imagesetBlocks['defaultimageset'] = {}\n ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,\n PhactoriImagesetBlock, ParseOneImagesetBlockC,\n gPipeAndViewsState)\n\n\n# if 'camera' not in ioImagesetBlockJson:\n# #we have to construct and use a default camera, including parsing\n# #commands in the imageset for the camera\n# myDebugPrint3(\" ParseOneImagesetBlockC: for imageset \" + \\\n# ioImagesetBlock.mName + \\\n# \" there is no camera, so we must add and reference default\\n\")\n# if 'camera type' not in ioImagesetBlockJson:\n# ioImagesetBlockJson['camera type'] = 'multicamera8'\n# defaultCameraName = ioImagesetBlock.mName + '_default_camera'\n# defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}\n# ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,\n# defaultCameraBlockAndWrapper,\n# PhactoriCameraBlock,\n# ParseOneCameraBlockC,\n# ioPipeAndViewsState)\n# ioImagesetBlockJson['camera'] = defaultCameraName\n# #myDebugPrint3( \"done adding camera, here it is:\\n\")\n# #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()\n\n\n #loop through imageset blocks and create a viz for each--i.e. create a\n #ParaView/Catalyst Representation and View for each imageset block, and\n #have it render info from some stage of the above pipeline\n\n for imagesetName, imagesetInstance in gPipeAndViewsState.mImagesetBlocks.items():\n CreateParaviewItemsForImagesetC(imagesetInstance)\n\n CreateScatterPlotViewsC(gPipeAndViewsState)\n CreatePlotOverTimeViewsC(gPipeAndViewsState)\n\n if gPipeAndViewsState.mInteractionEnabled == True:\n SaveJsonSettingsToFile(gPipeAndViewsState, \"PhactoriJsonSettings.txt\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def lookup_fully_qualified(\n name: str, modules: dict[str, MypyFile], *, raise_on_missing: bool = False\n) -> SymbolTableNode | None:\n \"\"\"Find a symbol using it fully qualified name.\n\n The algorithm has two steps: first we try splitting the name on '.' to find\n the module, then iteratively look for each next chunk after a '.' (e.g. for\n nested classes).\n\n This function should *not* be used to find a module. Those should be looked\n in the modules dictionary.\n \"\"\"\n head = name\n rest = []\n # 1. Find a module tree in modules dictionary.\n while True:\n if \".\" not in head:\n if raise_on_missing:\n assert \".\" in head, f\"Cannot find module for {name}\"\n return None\n head, tail = head.rsplit(\".\", maxsplit=1)\n rest.append(tail)\n mod = modules.get(head)\n if mod is not None:\n break\n names = mod.names\n # 2. Find the symbol in the module tree.\n if not rest:\n # Looks like a module, don't use this to avoid confusions.\n if raise_on_missing:\n assert rest, f\"Cannot find {name}, got a module symbol\"\n return None\n while True:\n key = rest.pop()\n if key not in names:\n if raise_on_missing:\n assert key in names, f\"Cannot find component {key!r} for {name!r}\"\n return None\n stnode = names[key]\n if not rest:\n return stnode\n node = stnode.node\n # In fine-grained mode, could be a cross-reference to a deleted module\n # or a Var made up for a missing module.\n if not isinstance(node, TypeInfo):\n if raise_on_missing:\n assert node, f\"Cannot find {name}\"\n return None\n names = node.names", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def CreateDirectoryFromProcessZero(inDirname):\n if SmartGetLocalProcessId() != 0:\n if PhactoriDbg():\n myDebugPrint3('CreateDirectoryFromProcessZero, not process 0\\n')\n return\n\n if inDirname == '':\n if PhactoriDbg():\n myDebugPrint3('CreateDirectoryFromProcessZero, no directory to create\\n')\n return\n\n #test for directory existence, try to create if not existing\n import os\n if PhactoriDbg():\n myDebugPrint3('find or create directory: ' + str(inDirname) + '\\n')\n if os.path.exists(inDirname):\n if os.path.isdir(inDirname) != True:\n errStr = \\\n ' path to base directory exists and is not a directory\\n' + \\\n ' (' + str(inDirname) + ')\\n'\n myDebugPrint3AndException(errStr)\n else:\n if PhactoriDbg():\n myDebugPrint3('inDirname found and is directory\\n')\n else:\n if PhactoriDbg():\n myDebugPrint3(str(inDirname) + ' to be created\\n')\n try:\n os.makedirs(inDirname)\n except:\n errStr = \\\n ' failed (1) to create directory\\n' + \\\n ' (' + str(inDirname) + ')\\n'\n myDebugPrint3AndException(errStr)\n if os.path.exists(inDirname) != True:\n errStr = \\\n ' failed (2) to create directory\\n' + \\\n ' (' + str(inDirname) + ')\\n'\n myDebugPrint3AndException(errStr)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def get_user_actions(\n project: Project,\n replay_id: str,\n events: list[dict[str, Any]],\n replay_event: dict[str, Any] | None,\n) -> list[ReplayActionsEventPayloadClick]:\n \"\"\"Return a list of ReplayActionsEventPayloadClick types.\n\n The node object is a partially destructured HTML element with an additional RRWeb\n identifier included. Node objects are not recursive and truncate their children. Text is\n extracted and stored on the textContent key.\n\n For example, the follow DOM element:\n\n <div id=\"a\" class=\"b c\">Hello<span>, </span>world!</div>\n\n Would be destructured as:\n\n {\n \"id\": 217,\n \"tagName\": \"div\",\n \"attributes\": {\"id\": \"a\", \"class\": \"b c\"},\n \"textContent\": \"Helloworld!\"\n }\n \"\"\"\n # Feature flag and project option queries\n should_report_rage = _should_report_rage_click_issue(project)\n should_report_hydration = _should_report_hydration_error_issue(project)\n\n result: list[ReplayActionsEventPayloadClick] = []\n for event in _iter_custom_events(events):\n if len(result) == 20:\n break\n\n tag = event.get(\"data\", {}).get(\"tag\")\n\n if tag == \"breadcrumb\":\n click = _handle_breadcrumb(\n event,\n project,\n replay_id,\n replay_event,\n should_report_rage_click_issue=should_report_rage,\n should_report_hydration_error_issue=should_report_hydration,\n )\n if click is not None:\n result.append(click)\n # look for request / response breadcrumbs and report metrics on them\n if tag == \"performanceSpan\":\n _handle_resource_metric_event(event)\n # log the SDK options sent from the SDK 1/500 times\n if tag == \"options\" and random.randint(0, 499) < 1:\n _handle_options_logging_event(project.id, replay_id, event)\n # log large dom mutation breadcrumb events 1/100 times\n\n payload = event.get(\"data\", {}).get(\"payload\", {})\n if (\n isinstance(payload, dict)\n and tag == \"breadcrumb\"\n and payload.get(\"category\") == \"replay.mutations\"\n and random.randint(0, 500) < 1\n ):\n _handle_mutations_event(project.id, replay_id, event)\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def initInternational(self):\n\t\tprint(\"[International] Initializing locales/languages.\")\n\t\tself.availablePackages = self.getAvailablePackages(update=True)\n\t\tself.installedPackages = self.getInstalledPackages(update=True)\n\t\tself.installedDirectories = self.getInstalledDirectories(update=True)\n\t\tif len(self.installedDirectories) != len(self.installedPackages):\n\t\t\tprint(\"[International] Warning: Count of installed locale/language packages and locale/language directory entries do not match!\")\n\t\tself.packageLocales = {}\n\t\tfor package in self.installedPackages:\n\t\t\tlocales = self.packageToLocales(package)\n\t\t\tpackageLocales = []\n\t\t\tfor locale in locales:\n\t\t\t\tif locale not in packageLocales:\n\t\t\t\t\tpackageLocales.append(locale)\n\t\t\t\tif locale not in self.localeList:\n\t\t\t\t\tself.localeList.append(locale)\n\t\t\tself.packageLocales[package] = packageLocales\n\t\t\tlanguage = self.splitPackage(package)[0]\n\t\t\tif language not in self.languageList:\n\t\t\t\tself.languageList.append(language)\n\t\t\tcount = len(packageLocales)\n\t\t\tif self.debugMode:\n\t\t\t\tprint(f\"[International] Package '{package}' supports {count} locale{'' if count == 1 else 's'} '{\"', '\".join(packageLocales)}'.\")\n\t\tself.localeList.sort()\n\t\tself.languageList.sort()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def __init__(\n self,\n request,\n model,\n list_display,\n list_display_links,\n list_filter,\n date_hierarchy,\n search_fields,\n list_select_related,\n list_per_page,\n list_max_show_all,\n list_editable,\n model_admin,\n sortable_by,\n search_help_text,\n ):\n self.model = model\n self.opts = model._meta\n self.lookup_opts = self.opts\n self.root_queryset = model_admin.get_queryset(request)\n self.list_display = list_display\n self.list_display_links = list_display_links\n self.list_filter = list_filter\n self.has_filters = None\n self.has_active_filters = None\n self.clear_all_filters_qs = None\n self.date_hierarchy = date_hierarchy\n self.search_fields = search_fields\n self.list_select_related = list_select_related\n self.list_per_page = list_per_page\n self.list_max_show_all = list_max_show_all\n self.model_admin = model_admin\n self.preserved_filters = model_admin.get_preserved_filters(request)\n self.sortable_by = sortable_by\n self.search_help_text = search_help_text\n\n # Get search parameters from the query string.\n _search_form = self.search_form_class(request.GET)\n if not _search_form.is_valid():\n for error in _search_form.errors.values():\n messages.error(request, \", \".join(error))\n self.query = _search_form.cleaned_data.get(SEARCH_VAR) or \"\"\n try:\n self.page_num = int(request.GET.get(PAGE_VAR, 1))\n except ValueError:\n self.page_num = 1\n self.show_all = ALL_VAR in request.GET\n self.is_popup = IS_POPUP_VAR in request.GET\n self.add_facets = model_admin.show_facets is ShowFacets.ALWAYS or (\n model_admin.show_facets is ShowFacets.ALLOW and IS_FACETS_VAR in request.GET\n )\n self.is_facets_optional = model_admin.show_facets is ShowFacets.ALLOW\n to_field = request.GET.get(TO_FIELD_VAR)\n if to_field and not model_admin.to_field_allowed(request, to_field):\n raise DisallowedModelAdminToField(\n \"The field %s cannot be referenced.\" % to_field\n )\n self.to_field = to_field\n self.params = dict(request.GET.items())\n self.filter_params = dict(request.GET.lists())\n if PAGE_VAR in self.params:\n del self.params[PAGE_VAR]\n del self.filter_params[PAGE_VAR]\n if ERROR_FLAG in self.params:\n del self.params[ERROR_FLAG]\n del self.filter_params[ERROR_FLAG]\n self.remove_facet_link = self.get_query_string(remove=[IS_FACETS_VAR])\n self.add_facet_link = self.get_query_string({IS_FACETS_VAR: True})\n\n if self.is_popup:\n self.list_editable = ()\n else:\n self.list_editable = list_editable\n self.queryset = self.get_queryset(request)\n self.get_results(request)\n if self.is_popup:\n title = gettext(\"Select %s\")\n elif self.model_admin.has_change_permission(request):\n title = gettext(\"Select %s to change\")\n else:\n title = gettext(\"Select %s to view\")\n self.title = title % self.opts.verbose_name\n self.pk_attname = self.lookup_opts.pk.attname", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def pipeline(self, pipeline, request, *args, **kwargs):\n \"\"\"Pipeline\"\"\"\n out = kwargs.copy()\n\n if \"pipeline_index\" in kwargs:\n base_index = int(kwargs[\"pipeline_index\"])\n else:\n base_index = 0\n\n for idx, name in enumerate(pipeline):\n out[\"pipeline_index\"] = base_index + idx\n mod_name, func_name = name.rsplit(\".\", 1)\n mod = __import__(mod_name, {}, {}, [func_name])\n func = getattr(mod, func_name)\n\n try:\n result: dict[str, Any] = {}\n if func_name == \"save_status_to_session\":\n result = func(request, *args, **out) or {}\n else:\n result = func(*args, **out) or {}\n except StopPipeline:\n # Clean partial pipeline on stop\n if \"request\" in kwargs:\n clean_partial_pipeline(kwargs[\"request\"])\n break\n\n if isinstance(result, dict):\n out.update(result)\n else:\n return result\n\n # clean the partial pipeline at the end of the process\n if \"request\" in kwargs:\n clean_partial_pipeline(kwargs[\"request\"])\n return out", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _get_decorator_optional_bool_argument(\n ctx: mypy.plugin.ClassDefContext, name: str, default: bool | None = None\n) -> bool | None:\n \"\"\"Return the Optional[bool] argument for the decorator.\n\n This handles both @decorator(...) and @decorator.\n \"\"\"\n if isinstance(ctx.reason, CallExpr):\n attr_value = _get_argument(ctx.reason, name)\n if attr_value:\n if isinstance(attr_value, NameExpr):\n if attr_value.fullname == \"builtins.True\":\n return True\n if attr_value.fullname == \"builtins.False\":\n return False\n if attr_value.fullname == \"builtins.None\":\n return None\n ctx.api.fail(\n f'\"{name}\" argument must be a True, False, or None literal',\n ctx.reason,\n code=LITERAL_REQ,\n )\n return default\n return default\n else:\n return default", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def check_return_stmt(self, s: ReturnStmt) -> None:\n defn = self.scope.top_function()\n if defn is not None:\n if defn.is_generator:\n return_type = self.get_generator_return_type(\n self.return_types[-1], defn.is_coroutine\n )\n elif defn.is_coroutine:\n return_type = self.get_coroutine_return_type(self.return_types[-1])\n else:\n return_type = self.return_types[-1]\n return_type = get_proper_type(return_type)\n\n is_lambda = isinstance(self.scope.top_function(), LambdaExpr)\n if isinstance(return_type, UninhabitedType):\n # Avoid extra error messages for failed inference in lambdas\n if not is_lambda and not return_type.ambiguous:\n self.fail(message_registry.NO_RETURN_EXPECTED, s)\n return\n\n if s.expr:\n declared_none_return = isinstance(return_type, NoneType)\n declared_any_return = isinstance(return_type, AnyType)\n\n # This controls whether or not we allow a function call that\n # returns None as the expression of this return statement.\n # E.g. `return f()` for some `f` that returns None. We allow\n # this only if we're in a lambda or in a function that returns\n # `None` or `Any`.\n allow_none_func_call = is_lambda or declared_none_return or declared_any_return\n\n # Return with a value.\n typ = get_proper_type(\n self.expr_checker.accept(\n s.expr, return_type, allow_none_return=allow_none_func_call\n )\n )\n # Treat NotImplemented as having type Any, consistent with its\n # definition in typeshed prior to python/typeshed#4222.\n if (\n isinstance(typ, Instance)\n and typ.type.fullname == \"builtins._NotImplementedType\"\n ):\n typ = AnyType(TypeOfAny.special_form)\n\n if defn.is_async_generator:\n self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s)\n return\n # Returning a value of type Any is always fine.\n if isinstance(typ, AnyType):\n # (Unless you asked to be warned in that case, and the\n # function is not declared to return Any)\n if (\n self.options.warn_return_any\n and not self.current_node_deferred\n and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)\n and not (\n defn.name in BINARY_MAGIC_METHODS\n and is_literal_not_implemented(s.expr)\n )\n and not (\n isinstance(return_type, Instance)\n and return_type.type.fullname == \"builtins.object\"\n )\n and not is_lambda\n ):\n self.msg.incorrectly_returning_any(return_type, s)\n return\n\n # Disallow return expressions in functions declared to return\n # None, subject to two exceptions below.\n if declared_none_return:\n # Lambdas are allowed to have None returns.\n # Functions returning a value of type None are allowed to have a None return.\n if is_lambda or isinstance(typ, NoneType):\n return\n self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s)\n else:\n self.check_subtype(\n subtype_label=\"got\",\n subtype=typ,\n supertype_label=\"expected\",\n supertype=return_type,\n context=s.expr,\n outer_context=s,\n msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE,\n )\n else:\n # Empty returns are valid in Generators with Any typed returns, but not in\n # coroutines.\n if (\n defn.is_generator\n and not defn.is_coroutine\n and isinstance(return_type, AnyType)\n ):\n return\n\n if isinstance(return_type, (NoneType, AnyType)):\n return\n\n if self.in_checked_function():\n self.fail(message_registry.RETURN_VALUE_EXPECTED, s)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def user_entry_to_dict(self, entry):\n user = {}\n attr_map = self.config.attr_map.items()\n for attr, mapping in attr_map:\n if not hasattr(entry, mapping):\n continue\n value = getattr(entry, mapping).value or ''\n if attr == 'is_active':\n if mapping.lower() == 'useraccountcontrol' and value:\n value = int(value) & LDAP_AD_ACCOUNT_DISABLE != LDAP_AD_ACCOUNT_DISABLE\n else:\n value = is_true(value)\n\n if attr == 'groups' and mapping.lower() == 'memberof':\n # AD: {'groups': 'memberOf'}\n if isinstance(value, str) and value:\n value = [value]\n if not isinstance(value, list):\n value = []\n user[attr] = value.strip() if isinstance(value, str) else value\n user['status'] = ImportStatus.pending\n return user", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def _unpack(self, execute=EX_CONSTRUCT):\n typ, n, obj = self._read_header()\n\n if execute == EX_READ_ARRAY_HEADER:\n if typ != TYPE_ARRAY:\n raise ValueError(\"Expected array\")\n return n\n if execute == EX_READ_MAP_HEADER:\n if typ != TYPE_MAP:\n raise ValueError(\"Expected map\")\n return n\n # TODO should we eliminate the recursion?\n if typ == TYPE_ARRAY:\n if execute == EX_SKIP:\n for i in xrange(n):\n # TODO check whether we need to call `list_hook`\n self._unpack(EX_SKIP)\n return\n ret = newlist_hint(n)\n for i in xrange(n):\n ret.append(self._unpack(EX_CONSTRUCT))\n if self._list_hook is not None:\n ret = self._list_hook(ret)\n # TODO is the interaction between `list_hook` and `use_list` ok?\n return ret if self._use_list else tuple(ret)\n if typ == TYPE_MAP:\n if execute == EX_SKIP:\n for i in xrange(n):\n # TODO check whether we need to call hooks\n self._unpack(EX_SKIP)\n self._unpack(EX_SKIP)\n return\n if self._object_pairs_hook is not None:\n ret = self._object_pairs_hook(\n (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT))\n for _ in xrange(n)\n )\n else:\n ret = {}\n for _ in xrange(n):\n key = self._unpack(EX_CONSTRUCT)\n if self._strict_map_key and type(key) not in (unicode, bytes):\n raise ValueError(\n \"%s is not allowed for map key\" % str(type(key))\n )\n if not PY2 and type(key) is str:\n key = sys.intern(key)\n ret[key] = self._unpack(EX_CONSTRUCT)\n if self._object_hook is not None:\n ret = self._object_hook(ret)\n return ret\n if execute == EX_SKIP:\n return\n if typ == TYPE_RAW:\n if self._raw:\n obj = bytes(obj)\n else:\n obj = obj.decode(\"utf_8\", self._unicode_errors)\n return obj\n if typ == TYPE_BIN:\n return bytes(obj)\n if typ == TYPE_EXT:\n if n == -1: # timestamp\n ts = Timestamp.from_bytes(bytes(obj))\n if self._timestamp == 1:\n return ts.to_unix()\n elif self._timestamp == 2:\n return ts.to_unix_nano()\n elif self._timestamp == 3:\n return ts.to_datetime()\n else:\n return ts\n else:\n return self._ext_hook(n, bytes(obj))\n assert typ == TYPE_IMMEDIATE\n return obj", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def flatten_rvalues(self, rvalues: list[Expression]) -> list[Expression]:\n \"\"\"Flatten expression list by expanding those * items that have tuple type.\n\n For each regular type item in the tuple type use a TempNode(), for an Unpack\n item use a corresponding StarExpr(TempNode()).\n \"\"\"\n new_rvalues = []\n for rv in rvalues:\n if not isinstance(rv, StarExpr):\n new_rvalues.append(rv)\n continue\n typ = get_proper_type(self.expr_checker.accept(rv.expr))\n if not isinstance(typ, TupleType):\n new_rvalues.append(rv)\n continue\n for t in typ.items:\n if not isinstance(t, UnpackType):\n new_rvalues.append(TempNode(t))\n else:\n unpacked = get_proper_type(t.type)\n if isinstance(unpacked, TypeVarTupleType):\n fallback = unpacked.upper_bound\n else:\n assert (\n isinstance(unpacked, Instance)\n and unpacked.type.fullname == \"builtins.tuple\"\n )\n fallback = unpacked\n new_rvalues.append(StarExpr(TempNode(fallback)))\n return new_rvalues", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def main():\n args = parse_args()\n\n infile = open(args.infile, \"r\")\n if not infile:\n print(f\"ERROR: Cannot open input file: {args.infile}, exiting...\")\n sys.exit(1)\n\n outfile = open(args.outfile, \"wb\")\n if not outfile:\n print(f\"ERROR: Cannot open output file for write: {args.outfile}, exiting...\")\n sys.exit(1)\n\n print(f\"Input file {args.infile}\")\n print(f\"Output file {args.outfile}\")\n\n has_begin = False\n has_end = False\n has_error = False\n go_parse_line = False\n bytes_written = 0\n for line in infile.readlines():\n if line.find(COREDUMP_BEGIN_STR) >= 0:\n # Found \"BEGIN#\" - beginning of log\n has_begin = True\n go_parse_line = True\n continue\n\n if line.find(COREDUMP_END_STR) >= 0:\n # Found \"END#\" - end of log\n has_end = True\n go_parse_line = False\n break\n\n if line.find(COREDUMP_ERROR_STR) >= 0:\n # Error was encountered during dumping:\n # log is not usable\n has_error = True\n go_parse_line = False\n break\n\n if not go_parse_line:\n continue\n\n prefix_idx = line.find(COREDUMP_PREFIX_STR)\n\n if prefix_idx < 0:\n continue\n\n prefix_idx += len(COREDUMP_PREFIX_STR)\n hex_str = line[prefix_idx:].strip()\n\n binary_data = binascii.unhexlify(hex_str)\n outfile.write(binary_data)\n bytes_written += len(binary_data)\n\n if not has_begin:\n print(\"ERROR: Beginning of log not found!\")\n elif not has_end:\n print(\"WARN: End of log not found! Is log complete?\")\n elif has_error:\n print(\"ERROR: log has error.\")\n else:\n print(f\"Bytes written {bytes_written}\")\n\n infile.close()\n outfile.close()", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def __contains__(self, k):\n if k in self._entries:\n return True\n\n if not portable_data_hash_pattern.match(k) and (self.pdh_only or not uuid_pattern.match(k)):\n return False\n\n try:\n e = None\n\n if group_uuid_pattern.match(k):\n project = self.api.groups().list(\n filters=[\n ['group_class', 'in', ['project','filter']],\n [\"uuid\", \"=\", k],\n *self._filters_for('groups', qualified=False),\n ],\n ).execute(num_retries=self.num_retries)\n if project[u'items_available'] == 0:\n return False\n e = self.inodes.add_entry(ProjectDirectory(\n self.inode,\n self.inodes,\n self.api,\n self.num_retries,\n self._enable_write,\n self._filters,\n project[u'items'][0],\n storage_classes=self.storage_classes,\n ))\n else:\n e = self.inodes.add_entry(CollectionDirectory(\n self.inode,\n self.inodes,\n self.api,\n self.num_retries,\n self._enable_write,\n self._filters,\n k,\n ))\n\n if e.update():\n if k not in self._entries:\n self._entries[k] = e\n else:\n self.inodes.del_entry(e)\n return True\n else:\n self.inodes.invalidate_entry(self, k)\n self.inodes.del_entry(e)\n return False\n except Exception as ex:\n _logger.exception(\"arv-mount lookup '%s':\", k)\n if e is not None:\n self.inodes.del_entry(e)\n return False", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def get_tokens(self, text, unfiltered=False):\n \"\"\"\n This method is the basic interface of a lexer. It is called by\n the `highlight()` function. It must process the text and return an\n iterable of ``(tokentype, value)`` pairs from `text`.\n\n Normally, you don't need to override this method. The default\n implementation processes the options recognized by all lexers\n (`stripnl`, `stripall` and so on), and then yields all tokens\n from `get_tokens_unprocessed()`, with the ``index`` dropped.\n\n If `unfiltered` is set to `True`, the filtering mechanism is\n bypassed even if filters are defined.\n \"\"\"\n if not isinstance(text, str):\n if self.encoding == 'guess':\n text, _ = guess_decode(text)\n elif self.encoding == 'chardet':\n try:\n from pip._vendor import chardet\n except ImportError as e:\n raise ImportError('To enable chardet encoding guessing, '\n 'please install the chardet library '\n 'from http://chardet.feedparser.org/') from e\n # check for BOM first\n decoded = None\n for bom, encoding in _encoding_map:\n if text.startswith(bom):\n decoded = text[len(bom):].decode(encoding, 'replace')\n break\n # no BOM found, so use chardet\n if decoded is None:\n enc = chardet.detect(text[:1024]) # Guess using first 1KB\n decoded = text.decode(enc.get('encoding') or 'utf-8',\n 'replace')\n text = decoded\n else:\n text = text.decode(self.encoding)\n if text.startswith('\\ufeff'):\n text = text[len('\\ufeff'):]\n else:\n if text.startswith('\\ufeff'):\n text = text[len('\\ufeff'):]\n\n # text now *is* a unicode string\n text = text.replace('\\r\\n', '\\n')\n text = text.replace('\\r', '\\n')\n if self.stripall:\n text = text.strip()\n elif self.stripnl:\n text = text.strip('\\n')\n if self.tabsize > 0:\n text = text.expandtabs(self.tabsize)\n if self.ensurenl and not text.endswith('\\n'):\n text += '\\n'\n\n def streamer():\n for _, t, v in self.get_tokens_unprocessed(text):\n yield t, v\n stream = streamer()\n if not unfiltered:\n stream = apply_filters(stream, self.filters, self)\n return stream", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def make_environ(self) -> WSGIEnvironment:\n request_url = urlsplit(self.path)\n url_scheme = \"http\" if self.server.ssl_context is None else \"https\"\n\n if not self.client_address:\n self.client_address = (\"<local>\", 0)\n elif isinstance(self.client_address, str):\n self.client_address = (self.client_address, 0)\n\n # If there was no scheme but the path started with two slashes,\n # the first segment may have been incorrectly parsed as the\n # netloc, prepend it to the path again.\n if not request_url.scheme and request_url.netloc:\n path_info = f\"/{request_url.netloc}{request_url.path}\"\n else:\n path_info = request_url.path\n\n path_info = unquote(path_info)\n\n environ: WSGIEnvironment = {\n \"wsgi.version\": (1, 0),\n \"wsgi.url_scheme\": url_scheme,\n \"wsgi.input\": self.rfile,\n \"wsgi.errors\": sys.stderr,\n \"wsgi.multithread\": self.server.multithread,\n \"wsgi.multiprocess\": self.server.multiprocess,\n \"wsgi.run_once\": False,\n \"werkzeug.socket\": self.connection,\n \"SERVER_SOFTWARE\": self.server_version,\n \"REQUEST_METHOD\": self.command,\n \"SCRIPT_NAME\": \"\",\n \"PATH_INFO\": _wsgi_encoding_dance(path_info),\n \"QUERY_STRING\": _wsgi_encoding_dance(request_url.query),\n # Non-standard, added by mod_wsgi, uWSGI\n \"REQUEST_URI\": _wsgi_encoding_dance(self.path),\n # Non-standard, added by gunicorn\n \"RAW_URI\": _wsgi_encoding_dance(self.path),\n \"REMOTE_ADDR\": self.address_string(),\n \"REMOTE_PORT\": self.port_integer(),\n \"SERVER_NAME\": self.server.server_address[0],\n \"SERVER_PORT\": str(self.server.server_address[1]),\n \"SERVER_PROTOCOL\": self.request_version,\n }\n\n for key, value in self.headers.items():\n if \"_\" in key:\n continue\n\n key = key.upper().replace(\"-\", \"_\")\n value = value.replace(\"\\r\\n\", \"\")\n if key not in (\"CONTENT_TYPE\", \"CONTENT_LENGTH\"):\n key = f\"HTTP_{key}\"\n if key in environ:\n value = f\"{environ[key]},{value}\"\n environ[key] = value\n\n if environ.get(\"HTTP_TRANSFER_ENCODING\", \"\").strip().lower() == \"chunked\":\n environ[\"wsgi.input_terminated\"] = True\n environ[\"wsgi.input\"] = DechunkedInput(environ[\"wsgi.input\"])\n\n # Per RFC 2616, if the URL is absolute, use that as the host.\n # We're using \"has a scheme\" to indicate an absolute URL.\n if request_url.scheme and request_url.netloc:\n environ[\"HTTP_HOST\"] = request_url.netloc\n\n try:\n # binary_form=False gives nicer information, but wouldn't be compatible with\n # what Nginx or Apache could return.\n peer_cert = self.connection.getpeercert(binary_form=True)\n if peer_cert is not None:\n # Nginx and Apache use PEM format.\n environ[\"SSL_CLIENT_CERT\"] = ssl.DER_cert_to_PEM_cert(peer_cert)\n except ValueError:\n # SSL handshake hasn't finished.\n self.server.log(\"error\", \"Cannot fetch SSL peer certificate info\")\n except AttributeError:\n # Not using TLS, the socket will not have getpeercert().\n pass\n\n return environ", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def startPreview(self):\n\t\tif self.nextInBackground is not None:\n\t\t\tcurrent = self.nextInBackground\n\t\t\tself.nextInBackground = None\n\t\telse:\n\t\t\tcurrent = self.getCurrent()\n\t\tplayInBackground = self.list.playInBackground\n\t\tplayInForeground = self.list.playInForeground\n\t\tif playInBackground:\n\t\t\tself.list.playInBackground = None\n\t\t\tfrom Screens.InfoBar import MoviePlayer\n\t\t\tMoviePlayerInstance = MoviePlayer.instance\n\t\t\tif MoviePlayerInstance is not None:\n\t\t\t\tfrom Screens.InfoBarGenerics import setResumePoint\n\t\t\t\tsetResumePoint(MoviePlayer.instance.session)\n\t\t\tself.session.nav.stopService()\n\t\t\tif playInBackground != current:\n\t\t\t\tself.callLater(self.preview) # Come back to play the new one.\n\t\telif playInForeground:\n\t\t\tself.playingInForeground = playInForeground\n\t\t\tself.list.playInForeground = None\n\t\t\tfrom Screens.InfoBar import MoviePlayer\n\t\t\tMoviePlayerInstance = MoviePlayer.instance\n\t\t\tif MoviePlayerInstance is not None:\n\t\t\t\tfrom Screens.InfoBarGenerics import setResumePoint\n\t\t\t\tsetResumePoint(MoviePlayer.instance.session)\n\t\t\tself.session.nav.stopService()\n\t\t\tif playInForeground != current:\n\t\t\t\tself.callLater(self.preview)\n\t\telse:\n\t\t\tself.list.playInBackground = current\n\t\t\tif current.type == 4116: # Check if MerlinMusicPlayer is installed and merlinmp3player.so is running so we need the right id to play now the mp3-file.\n\t\t\t\tpath = current.getPath()\n\t\t\t\tservice = eServiceReference(4097, 0, path)\n\t\t\t\tself.session.nav.playService(service)\n\t\t\telse:\n\t\t\t\tself.session.nav.playService(current)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@track_slo_response(\"workflow\")\n def get(self, request: Request, project) -> Response:\n \"\"\"\n List a Project's Issues\n ```````````````````````\n\n Return a list of issues (groups) bound to a project. All parameters are\n supplied as query string parameters.\n\n A default query of ``is:unresolved`` is applied. To return results\n with other statuses send an new query value (i.e. ``?query=`` for all\n results).\n\n The ``statsPeriod`` parameter can be used to select the timeline\n stats which should be present. Possible values are: ``\"\"`` (disable),\n ``\"24h\"``, ``\"14d\"``\n\n :qparam string statsPeriod: an optional stat period (can be one of\n ``\"24h\"``, ``\"14d\"``, and ``\"\"``).\n :qparam bool shortIdLookup: if this is set to true then short IDs are\n looked up by this function as well. This\n can cause the return value of the function\n to return an event issue of a different\n project which is why this is an opt-in.\n Set to `1` to enable.\n :qparam querystring query: an optional Sentry structured search\n query. If not provided an implied\n ``\"is:unresolved\"`` is assumed.)\n :qparam string environment: this restricts the issues to ones containing\n events from this environment\n :qparam list hashes: hashes of groups to return, overrides 'query' parameter, only returning list of groups found from hashes. The maximum number of hashes that can be sent is 100. If more are sent, only the first 100 will be used.\n :pparam string organization_id_or_slug: the id or slug of the organization the\n issues belong to.\n :pparam string project_id_or_slug: the id or slug of the project the issues\n belong to.\n :auth: required\n \"\"\"\n stats_period = request.GET.get(\"statsPeriod\")\n if stats_period not in (None, \"\", \"24h\", \"14d\"):\n return Response({\"detail\": ERR_INVALID_STATS_PERIOD}, status=400)\n elif stats_period is None:\n # default\n stats_period = \"24h\"\n elif stats_period == \"\":\n # disable stats\n stats_period = None\n\n serializer = functools.partial(\n StreamGroupSerializer,\n environment_func=self._get_environment_func(request, project.organization_id),\n stats_period=stats_period,\n )\n\n hashes = request.GET.getlist(\"hashes\", [])\n query = request.GET.get(\"query\", \"\").strip()\n\n if hashes:\n if query:\n return Response({\"detail\": ERR_HASHES_AND_OTHER_QUERY}, status=400)\n\n # limit to 100 hashes\n hashes = hashes[:100]\n groups_from_hashes = GroupHash.objects.filter(\n hash__in=hashes, project=project\n ).values_list(\"group_id\", flat=True)\n groups = list(Group.objects.filter(id__in=groups_from_hashes))\n\n serialized_groups = serialize(\n groups,\n request.user,\n serializer(),\n )\n return Response(serialized_groups)\n\n if query:\n matching_group = None\n matching_event = None\n event_id = normalize_event_id(query)\n if event_id:\n # check to see if we've got an event ID\n try:\n matching_group = Group.objects.from_event_id(project, event_id)\n except Group.DoesNotExist:\n pass\n else:\n matching_event = eventstore.backend.get_event_by_id(project.id, event_id)\n elif matching_group is None:\n matching_group = get_by_short_id(\n project.organization_id, request.GET.get(\"shortIdLookup\", \"0\"), query\n )\n if matching_group is not None and matching_group.project_id != project.id:\n matching_group = None\n\n if matching_group is not None:\n matching_event_environment = None\n\n try:\n matching_event_environment = (\n matching_event.get_environment().name if matching_event else None\n )\n except Environment.DoesNotExist:\n pass\n\n serialized_groups = serialize(\n [matching_group],\n request.user,\n serializer(),\n )\n matching_event_id = getattr(matching_event, \"event_id\", None)\n if matching_event_id:\n serialized_groups[0][\"matchingEventId\"] = getattr(\n matching_event, \"event_id\", None\n )\n if matching_event_environment:\n serialized_groups[0][\"matchingEventEnvironment\"] = matching_event_environment\n\n response = Response(serialized_groups)\n\n response[\"X-Sentry-Direct-Hit\"] = \"1\"\n return response\n\n try:\n cursor_result, query_kwargs = prep_search(self, request, project, {\"count_hits\": True})\n except ValidationError as exc:\n return Response({\"detail\": str(exc)}, status=400)\n\n results = list(cursor_result)\n\n context = serialize(results, request.user, serializer())\n\n # HACK: remove auto resolved entries\n # TODO: We should try to integrate this into the search backend, since\n # this can cause us to arbitrarily return fewer results than requested.\n status = [\n search_filter\n for search_filter in query_kwargs.get(\"search_filters\", [])\n if search_filter.key.name == \"status\" and search_filter.operator in EQUALITY_OPERATORS\n ]\n if status and (GroupStatus.UNRESOLVED in status[0].value.raw_value):\n status_labels = {QUERY_STATUS_LOOKUP[s] for s in status[0].value.raw_value}\n context = [r for r in context if \"status\" not in r or r[\"status\"] in status_labels]\n\n response = Response(context)\n\n self.add_cursor_headers(request, response, cursor_result)\n\n if results and query:\n advanced_search.send(project=project, sender=request.user)\n analytics.record(\n \"project_issue.searched\",\n user_id=request.user.id,\n organization_id=project.organization_id,\n project_id=project.id,\n query=query,\n )\n\n return response", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def _check_indexes(cls, databases):\n \"\"\"Check fields, names, and conditions of indexes.\"\"\"\n errors = []\n references = set()\n for index in cls._meta.indexes:\n # Index name can't start with an underscore or a number, restricted\n # for cross-database compatibility with Oracle.\n if index.name[0] == \"_\" or index.name[0].isdigit():\n errors.append(\n checks.Error(\n \"The index name '%s' cannot start with an underscore \"\n \"or a number.\" % index.name,\n obj=cls,\n id=\"models.E033\",\n ),\n )\n if len(index.name) > index.max_name_length:\n errors.append(\n checks.Error(\n \"The index name '%s' cannot be longer than %d \"\n \"characters.\" % (index.name, index.max_name_length),\n obj=cls,\n id=\"models.E034\",\n ),\n )\n if index.contains_expressions:\n for expression in index.expressions:\n references.update(\n ref[0] for ref in cls._get_expr_references(expression)\n )\n for db in databases:\n if not router.allow_migrate_model(db, cls):\n continue\n connection = connections[db]\n if not (\n connection.features.supports_partial_indexes\n or \"supports_partial_indexes\" in cls._meta.required_db_features\n ) and any(index.condition is not None for index in cls._meta.indexes):\n errors.append(\n checks.Warning(\n \"%s does not support indexes with conditions.\"\n % connection.display_name,\n hint=(\n \"Conditions will be ignored. Silence this warning \"\n \"if you don't care about it.\"\n ),\n obj=cls,\n id=\"models.W037\",\n )\n )\n if not (\n connection.features.supports_covering_indexes\n or \"supports_covering_indexes\" in cls._meta.required_db_features\n ) and any(index.include for index in cls._meta.indexes):\n errors.append(\n checks.Warning(\n \"%s does not support indexes with non-key columns.\"\n % connection.display_name,\n hint=(\n \"Non-key columns will be ignored. Silence this \"\n \"warning if you don't care about it.\"\n ),\n obj=cls,\n id=\"models.W040\",\n )\n )\n if not (\n connection.features.supports_expression_indexes\n or \"supports_expression_indexes\" in cls._meta.required_db_features\n ) and any(index.contains_expressions for index in cls._meta.indexes):\n errors.append(\n checks.Warning(\n \"%s does not support indexes on expressions.\"\n % connection.display_name,\n hint=(\n \"An index won't be created. Silence this warning \"\n \"if you don't care about it.\"\n ),\n obj=cls,\n id=\"models.W043\",\n )\n )\n fields = [\n field for index in cls._meta.indexes for field, _ in index.fields_orders\n ]\n fields += [include for index in cls._meta.indexes for include in index.include]\n fields += references\n errors.extend(cls._check_local_fields(fields, \"indexes\"))\n return errors", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def main():\n parser = argparse.ArgumentParser(\n description=\"Run clang-tidy against changed files, and \" \"output diagnostics only for modified \" \"lines.\"\n )\n parser.add_argument(\"-clang-tidy-binary\", metavar=\"PATH\", default=\"clang-tidy\", help=\"path to clang-tidy binary\")\n parser.add_argument(\"-p\", metavar=\"NUM\", default=0, help=\"strip the smallest prefix containing P slashes\")\n parser.add_argument(\n \"-regex\",\n metavar=\"PATTERN\",\n default=None,\n help=\"custom pattern selecting file paths to check \" \"(case sensitive, overrides -iregex)\",\n )\n parser.add_argument(\n \"-iregex\",\n metavar=\"PATTERN\",\n default=r\".*\\.(cpp|cc|c\\+\\+|cxx|c|cl|h|hpp|m|mm|inc)\",\n help=\"custom pattern selecting file paths to check \" \"(case insensitive, overridden by -regex)\",\n )\n parser.add_argument(\"-j\", type=int, default=1, help=\"number of tidy instances to be run in parallel.\")\n parser.add_argument(\"-timeout\", type=int, default=None, help=\"timeout per each file in seconds.\")\n parser.add_argument(\"-fix\", action=\"store_true\", default=False, help=\"apply suggested fixes\")\n parser.add_argument(\"-checks\", help=\"checks filter, when not specified, use clang-tidy \" \"default\", default=\"\")\n parser.add_argument(\"-path\", dest=\"build_path\", help=\"Path used to read a compile command database.\")\n if yaml:\n parser.add_argument(\n \"-export-fixes\",\n metavar=\"FILE\",\n dest=\"export_fixes\",\n help=\"Create a yaml file to store suggested fixes in, \"\n \"which can be applied with clang-apply-replacements.\",\n )\n parser.add_argument(\n \"-extra-arg\",\n dest=\"extra_arg\",\n action=\"append\",\n default=[],\n help=\"Additional argument to append to the compiler \" \"command line.\",\n )\n parser.add_argument(\n \"-extra-arg-before\",\n dest=\"extra_arg_before\",\n action=\"append\",\n default=[],\n help=\"Additional argument to prepend to the compiler \" \"command line.\",\n )\n parser.add_argument(\"-quiet\", action=\"store_true\", default=False, help=\"Run clang-tidy in quiet mode\")\n clang_tidy_args = []\n argv = sys.argv[1:]\n if \"--\" in argv:\n clang_tidy_args.extend(argv[argv.index(\"--\") :])\n argv = argv[: argv.index(\"--\")]\n\n args = parser.parse_args(argv)\n\n # Extract changed lines for each file.\n filename = None\n lines_by_file = {}\n for line in sys.stdin:\n match = re.search('^\\+\\+\\+\\ \"?(.*?/){%s}([^ \\t\\n\"]*)' % args.p, line)\n if match:\n filename = match.group(2)\n if filename is None:\n continue\n\n if args.regex is not None:\n if not re.match(\"^%s$\" % args.regex, filename):\n continue\n else:\n if not re.match(\"^%s$\" % args.iregex, filename, re.IGNORECASE):\n continue\n\n match = re.search(\"^@@.*\\+(\\d+)(,(\\d+))?\", line)\n if match:\n start_line = int(match.group(1))\n line_count = 1\n if match.group(3):\n line_count = int(match.group(3))\n if line_count == 0:\n continue\n end_line = start_line + line_count - 1\n lines_by_file.setdefault(filename, []).append([start_line, end_line])\n\n if not any(lines_by_file):\n print(\"No relevant changes found.\")\n sys.exit(0)\n\n max_task_count = args.j\n if max_task_count == 0:\n max_task_count = multiprocessing.cpu_count()\n max_task_count = min(len(lines_by_file), max_task_count)\n\n tmpdir = None\n if yaml and args.export_fixes:\n tmpdir = tempfile.mkdtemp()\n\n # Tasks for clang-tidy.\n task_queue = queue.Queue(max_task_count)\n # A lock for console output.\n lock = threading.Lock()\n running_processes = set()\n\n exit_status = {\"status\": 0}\n\n # Run a pool of clang-tidy workers.\n start_workers(max_task_count, run_tidy, task_queue, lock, args.timeout, exit_status, running_processes)\n\n # Form the common args list.\n common_clang_tidy_args = []\n if args.fix:\n common_clang_tidy_args.append(\"-fix\")\n if args.checks != \"\":\n common_clang_tidy_args.append(\"-checks=\" + args.checks)\n if args.quiet:\n common_clang_tidy_args.append(\"-quiet\")\n if args.build_path is not None:\n common_clang_tidy_args.append(\"-p=%s\" % args.build_path)\n for arg in args.extra_arg:\n common_clang_tidy_args.append(\"-extra-arg=%s\" % arg)\n for arg in args.extra_arg_before:\n common_clang_tidy_args.append(\"-extra-arg-before=%s\" % arg)\n for name in lines_by_file:\n line_filter_json = json.dumps([{\"name\": name, \"lines\": lines_by_file[name]}], separators=(\",\", \":\"))\n\n # Run clang-tidy on files containing changes.\n command = [args.clang_tidy_binary]\n command.append(\"-line-filter=\" + line_filter_json)\n if yaml and args.export_fixes:\n # Get a temporary file. We immediately close the handle so clang-tidy can\n # overwrite it.\n (handle, tmp_name) = tempfile.mkstemp(suffix=\".yaml\", dir=tmpdir)\n os.close(handle)\n command.append(\"-export-fixes=\" + tmp_name)\n command.extend(common_clang_tidy_args)\n command.append(name)\n command.extend(clang_tidy_args)\n task_queue.put(command)\n\n # Wait for all threads to be done.\n task_queue.join()\n\n if exit_status[\"status\"] != 0:\n sys.exit(exit_status[\"status\"])\n\n if yaml and args.export_fixes:\n print(\"Writing fixes to \" + args.export_fixes + \" ...\")\n try:\n merge_replacement_files(tmpdir, args.export_fixes)\n except:\n sys.stderr.write(\"Error exporting fixes.\\n\")\n traceback.print_exc()\n\n if tmpdir:\n shutil.rmtree(tmpdir)", "smellKey": "S3776", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def process_file(f, options):\n with open(f) as ff:\n lines_in = [line.rstrip() for line in ff]\n lines_out = []\n cr = analyze(f)\n header = False\n header_start = 0\n for iline, line in enumerate(lines_in):\n if line.startswith(\"////////\"):\n header= True\n header_start = iline\n break\n if header:\n lines_out = lines_in[:header_start+1]\n else:\n lines_out = [\"///////////////////////////////////////////////////////////////////////////////////////\"]\n width = len(lines_out[header_start]) - 6\n for name, mail, years in cr:\n if name == \"Hexameron\":\n lines_out.append(\"// {0:{1}} //\".format(\"Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany\", width))\n lines_out.append(\"// {0:{1}} //\".format(\"written by Christian Daniel\", width))\n else:\n cr_string = f\"Copyright (C) {pretty_years(years)} {name} <{mail}>\"\n lines_out.append(f\"// {cr_string:{width}} //\")\n if not header:\n for hline in get_header_lines():\n lines_out.append(\"// {0:{1}} //\".format(hline, width))\n lines_out.append(lines_out[0])\n elif not options.remove_original:\n lines_out.append(\"\")\n in_header = header\n header_stop = len(lines_out)\n iread = header_start+1 if header else 0\n for iline, line in enumerate(lines_in[iread:]):\n if in_header and options.remove_original and remove_line(line):\n continue\n if line.startswith(\"////////\"):\n in_header = False\n header_stop += iline\n lines_out.append(line)\n if options.dry_run:\n for line_out in lines_out[header_start:header_stop]:\n print(line_out)\n else:\n with open(f, \"w\") as ff:\n for line in lines_out:\n ff.write(f\"{line}\\n\")", "smellKey": "S3776", "smellId": null, "repo": "f4exb_sdrangel", "language": "python"} {"function": "def setMode(self, mode):\n\t\tself.mode = mode\n\t\tif mode == self.MODE_SERVICES: # Mode all is not supported in legacy mode\n\t\t\tself.mode = self.MODE_OTHER\n\t\tself.setItemsPerPage()\n\t\tself.l.setItemHeight(self.ItemHeight)\n\t\tself.l.setVisualMode(eListboxServiceContent.visModeComplex)\n\t\tself.l.setServicePiconDownsize(int(config.usage.servicelist_picon_downsize.value))\n\t\tself.l.setServicePiconRatio(int(config.usage.servicelist_picon_ratio.value))\n\n\t\ttwoLines = config.usage.servicelist_twolines.value\n\t\tself.l.setShowTwoLines(twoLines)\n\n\t\tif config.usage.service_icon_enable.value:\n\t\t\tself.l.setGetPiconNameFunc(getPiconName)\n\t\telse:\n\t\t\tself.l.setGetPiconNameFunc(None)\n\n\t\trowWidth = self.instance.size().width() - self.listMarginRight\n\n\t\tif mode != self.MODE_BOUQUETS or not config.usage.show_channel_numbers_in_servicelist.value:\n\t\t\tchannelNumberWidth = 0\n\t\t\tchannelNumberSpace = self.listMarginLeft\n\t\telse:\n\t\t\tchannelNumberWidth = config.usage.alternative_number_mode.value and getTextBoundarySize(self.instance, self.ServiceNumberFont, self.instance.size(), \"0\" * int(config.usage.maxchannelnumlen.value)).width() or getTextBoundarySize(self.instance, self.ServiceNumberFont, self.instance.size(), \"00000\").width()\n\t\t\tchannelNumberSpace = self.fieldMargins + self.listMarginLeft\n\n\t\tnumberHeight = self.ItemHeight // 2 if twoLines and config.usage.servicelist_servicenumber_valign.value == \"1\" else self.ItemHeight\n\t\tself.l.setElementPosition(self.l.celServiceNumber, eRect(self.listMarginLeft, 0, channelNumberWidth, numberHeight))\n\n\t\t#progress view modes for two lines\n\t\t# 0 - single, centered\n\t\t# 10 - single, upper line\n\t\t# 1 - dual, bar upper line, value lower line\n\t\t# 2 - dual, value upper line, bar lower line\n\t\t# 11 - dual, bar and value upper line\n\t\t# 12 - dual, value and bar upper line\n\t\tif twoLines:\n\t\t\tviewMode, viewType = (config.usage.servicelist_eventprogress_valign.value + config.usage.servicelist_eventprogress_view_mode.value).split('_')\n\t\t\tviewMode = int(viewMode)\n\t\telse:\n\t\t\tviewType = config.usage.show_event_progress_in_servicelist.value\n\t\t\tviewMode = 0\n\n\t\tself.l.setProgressViewMode(viewMode)\n\n\t\tminuteUnit = _(\"min\")\n\t\tself.l.setProgressUnit(minuteUnit if \"mins\" in viewType else \"%\")\n\n\t\tprogressHeight = self.ItemHeight // 2 if viewMode else self.ItemHeight\n\t\tprogressTextWidth = getTextBoundarySize(self.instance, self.ProgressInfoFont, self.instance.size(), \"+000 %s\" % minuteUnit).width() if \"mins\" in viewType else getTextBoundarySize(self.instance, self.ProgressInfoFont, self.instance.size(), \"100 %\").width()\n\t\tself.l.setProgressTextWidth(progressTextWidth)\n\n\t\tif \"bar\" in viewType:\n\t\t\tif viewMode and viewMode < 10:\n\t\t\t\tprogressWidth = max(self.progressBarWidth, progressTextWidth)\n\t\t\telif viewMode > 10:\n\t\t\t\tprogressWidth = self.progressBarWidth + progressTextWidth + self.itemsDistances\n\t\t\telse:\n\t\t\t\tprogressWidth = self.progressBarWidth\n\t\telse:\n\t\t\tprogressWidth = progressTextWidth\n\n\t\tif \"left\" in viewType:\n\t\t\tself.l.setElementPosition(self.l.celServiceEventProgressbar, eRect(channelNumberWidth + channelNumberSpace, 0, progressWidth, progressHeight))\n\t\t\tself.l.setElementPosition(self.l.celServiceName, eRect(channelNumberWidth + channelNumberSpace + progressWidth + self.fieldMargins, 0, rowWidth - (channelNumberWidth + channelNumberSpace + progressWidth + self.fieldMargins), self.ItemHeight))\n\t\telif \"right\" in viewType:\n\t\t\tself.l.setElementPosition(self.l.celServiceEventProgressbar, eRect(rowWidth - progressWidth, 0, progressWidth, progressHeight))\n\t\t\tself.l.setElementPosition(self.l.celServiceName, eRect(channelNumberWidth + channelNumberSpace, 0, rowWidth - (channelNumberWidth + channelNumberSpace + progressWidth + self.fieldMargins), self.ItemHeight))\n\t\telse:\n\t\t\tself.l.setElementPosition(self.l.celServiceEventProgressbar, eRect(0, 0, 0, 0))\n\t\t\tself.l.setElementPosition(self.l.celServiceName, eRect(channelNumberWidth + channelNumberSpace, 0, rowWidth - (channelNumberWidth + channelNumberSpace), self.ItemHeight))\n\t\tif \"perc\" in viewType or \"mins\" in viewType:\n\t\t\tself.l.setElementFont(self.l.celServiceEventProgressbar, self.ProgressInfoFont)\n\n\t\tself.l.setElementFont(self.l.celServiceName, self.ServiceNameFont)\n\t\tself.l.setElementFont(self.l.celServiceNumber, self.ServiceNumberFont)\n\t\tself.l.setElementFont(self.l.celServiceInfo, self.ServiceInfoFont)\n\n\t\tself.l.setHideNumberMarker(config.usage.hide_number_markers.value)\n\t\tself.l.setServiceTypeIconMode(int(config.usage.servicetype_icon_mode.value))\n\t\tself.l.setCryptoIconMode(int(config.usage.crypto_icon_mode.value))\n\t\tself.l.setRecordIndicatorMode(int(config.usage.record_indicator_mode.value))\n\t\tself.l.setColumnWidth(-1 if twoLines else int(config.usage.servicelist_column.value))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _get_altered_foo_together_operations(self, option_name):\n for app_label, model_name in sorted(self.kept_model_keys):\n old_model_name = self.renamed_models.get(\n (app_label, model_name), model_name\n )\n old_model_state = self.from_state.models[app_label, old_model_name]\n new_model_state = self.to_state.models[app_label, model_name]\n\n # We run the old version through the field renames to account for those\n old_value = old_model_state.options.get(option_name)\n old_value = (\n {\n tuple(\n self.renamed_fields.get((app_label, model_name, n), n)\n for n in unique\n )\n for unique in old_value\n }\n if old_value\n else set()\n )\n\n new_value = new_model_state.options.get(option_name)\n new_value = set(new_value) if new_value else set()\n\n if old_value != new_value:\n dependencies = []\n for foo_togethers in new_value:\n for field_name in foo_togethers:\n field = new_model_state.get_field(field_name)\n if field.remote_field and field.remote_field.model:\n dependencies.extend(\n self._get_dependencies_for_foreign_key(\n app_label,\n model_name,\n field,\n self.to_state,\n )\n )\n yield (\n old_value,\n new_value,\n app_label,\n model_name,\n dependencies,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def resolve(\n self, root_reqs: List[InstallRequirement], check_supported_wheels: bool\n ) -> RequirementSet:\n collected = self.factory.collect_root_requirements(root_reqs)\n provider = PipProvider(\n factory=self.factory,\n constraints=collected.constraints,\n ignore_dependencies=self.ignore_dependencies,\n upgrade_strategy=self.upgrade_strategy,\n user_requested=collected.user_requested,\n )\n if \"PIP_RESOLVER_DEBUG\" in os.environ:\n reporter: BaseReporter = PipDebuggingReporter()\n else:\n reporter = PipReporter()\n resolver: RLResolver[Requirement, Candidate, str] = RLResolver(\n provider,\n reporter,\n )\n\n try:\n limit_how_complex_resolution_can_be = 200000\n result = self._result = resolver.resolve(\n collected.requirements, max_rounds=limit_how_complex_resolution_can_be\n )\n\n except ResolutionImpossible as e:\n error = self.factory.get_installation_error(\n cast(\"ResolutionImpossible[Requirement, Candidate]\", e),\n collected.constraints,\n )\n raise error from e\n\n req_set = RequirementSet(check_supported_wheels=check_supported_wheels)\n # process candidates with extras last to ensure their base equivalent is\n # already in the req_set if appropriate.\n # Python's sort is stable so using a binary key function keeps relative order\n # within both subsets.\n for candidate in sorted(\n result.mapping.values(), key=lambda c: c.name != c.project_name\n ):\n ireq = candidate.get_install_requirement()\n if ireq is None:\n if candidate.name != candidate.project_name:\n # extend existing req's extras\n with contextlib.suppress(KeyError):\n req = req_set.get_requirement(candidate.project_name)\n req_set.add_named_requirement(\n install_req_extend_extras(\n req, get_requirement(candidate.name).extras\n )\n )\n continue\n\n # Check if there is already an installation under the same name,\n # and set a flag for later stages to uninstall it, if needed.\n installed_dist = self.factory.get_dist_to_uninstall(candidate)\n if installed_dist is None:\n # There is no existing installation -- nothing to uninstall.\n ireq.should_reinstall = False\n elif self.factory.force_reinstall:\n # The --force-reinstall flag is set -- reinstall.\n ireq.should_reinstall = True\n elif installed_dist.version != candidate.version:\n # The installation is different in version -- reinstall.\n ireq.should_reinstall = True\n elif candidate.is_editable or installed_dist.editable:\n # The incoming distribution is editable, or different in\n # editable-ness to installation -- reinstall.\n ireq.should_reinstall = True\n elif candidate.source_link and candidate.source_link.is_file:\n # The incoming distribution is under file://\n if candidate.source_link.is_wheel:\n # is a local wheel -- do nothing.\n logger.info(\n \"%s is already installed with the same version as the \"\n \"provided wheel. Use --force-reinstall to force an \"\n \"installation of the wheel.\",\n ireq.name,\n )\n continue\n\n # is a local sdist or path -- reinstall\n ireq.should_reinstall = True\n else:\n continue\n\n link = candidate.source_link\n if link and link.is_yanked:\n # The reason can contain non-ASCII characters, Unicode\n # is required for Python 2.\n msg = (\n \"The candidate selected for download or install is a \"\n \"yanked version: {name!r} candidate (version {version} \"\n \"at {link})\\nReason for being yanked: {reason}\"\n ).format(\n name=candidate.name,\n version=candidate.version,\n link=link,\n reason=link.yanked_reason or \"<none given>\",\n )\n logger.warning(msg)\n\n req_set.add_named_requirement(ireq)\n\n reqs = req_set.all_requirements\n self.factory.preparer.prepare_linked_requirements_more(reqs)\n for req in reqs:\n req.prepared = True\n req.needs_more_preparation = False\n return req_set", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def CalculateColorMapRGBPointsWithSubranges(inBaseRgbPoints,\n inMinimum, inMaximum, inSubrangeMin, inSubrangeMax, inSubrangeColor):\n \"creates the rgb values for color map with highlighed subranges\"\n\n if PhactoriDbg(100):\n myDebugPrint3(\"CalculateColorMapRGBPointsWithSubranges entered \\n\"\n \" min, max: \" + str(inMinimum) + \", \" + str(inMaximum) + \"\\n\"\n \"subrange min, max: \" + str(inSubrangeMin) + \", \" + \\\n str(inSubrangeMax) + \"\\n\"\n \"subrange color: \" + str(inSubrangeColor) + \"\\n\", 100)\n\n #find where subrange fits in overallrange\n allRange = inMaximum - inMinimum\n minHlRatio = (inSubrangeMin - inMinimum)/allRange\n maxHlRatio = (inSubrangeMax - inMinimum)/allRange\n\n #test for case where whole subrange is above or below overall range\n if minHlRatio >= 1.0 or maxHlRatio <= 0.0:\n if PhactoriDbg(100):\n myDebugPrint3(\"subrange is above or below overall range, returning\\n\"\n \"CalculateColorMapRGBPointsWithSubranges returing \\n\", 100)\n return inBaseRgbPoints\n\n if minHlRatio < 0.0:\n minHlRatio = 0.0\n if maxHlRatio > 1.0:\n maxHlRatio = 1.0\n if maxHlRatio - minHlRatio < 0.004:\n #very narrow subrange; use narrow bands but might color odd\n #issue warning?\n ratDelta = maxHlRatio - minHlRatio\n bandStep = ratDelta * 0.25\n else:\n bandStep = 0.001\n\n #construct the no-subrange color map, with extra items to track the\n #outer range colors while changing the inner subrange colors\n xrgbPoints = inBaseRgbPoints\n #xrgbPoints = [0.0, 0.23137254902, 0.298039215686, 0.752941176471,\n # 0.5, 0.865, 0.865, 0.865,\n # 1.0, 0.705882352941, 0.0156862745098, 0.149019607843]\n if PhactoriDbg(100):\n myDebugPrint3(\"inBaseRgbPoints:\\n\" + str(inBaseRgbPoints) + \"\\n\", 100)\n\n #find the 4 points for the subrange\n subrangePt1 = helpFindNewRgbPoint(xrgbPoints, minHlRatio)\n subrangePt2 = [minHlRatio + bandStep,\n inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]\n subrangePt3 = [maxHlRatio - bandStep,\n inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]\n subrangePt4 = helpFindNewRgbPoint(xrgbPoints, maxHlRatio)\n\n #construct the map with the subrange\n xrgbIndex = 0\n myRgbPoints = []\n\n #first do points from original color map which are below subrange\n while (xrgbIndex < len(xrgbPoints)) and xrgbPoints[xrgbIndex] < subrangePt1[0]:\n myRgbPoints.append(xrgbPoints[xrgbIndex+0])\n myRgbPoints.append(xrgbPoints[xrgbIndex+1])\n myRgbPoints.append(xrgbPoints[xrgbIndex+2])\n myRgbPoints.append(xrgbPoints[xrgbIndex+3])\n xrgbIndex += 4\n\n #add in subrange points, accounting for bottom/top cases\n if subrangePt1[0] > xrgbPoints[0]:\n for nn in subrangePt1:\n myRgbPoints.append(nn)\n for nn in subrangePt2:\n myRgbPoints.append(nn)\n else:\n #special case, bottom of subrange is bottom of whole range\n subrangePt2[0] = subrangePt1[0]\n for nn in subrangePt2:\n myRgbPoints.append(nn)\n\n numXrgbPoints = int(len(xrgbPoints) / 4)\n if subrangePt4[0] < xrgbPoints[(numXrgbPoints-1) * 4]:\n for nn in subrangePt3:\n myRgbPoints.append(nn)\n for nn in subrangePt4:\n myRgbPoints.append(nn)\n else:\n #special case, top of subrange is top of whole range\n subrangePt3[0] = subrangePt4[0]\n for nn in subrangePt3:\n myRgbPoints.append(nn)\n\n #add in points from original color map after subrange, skipping any points\n #which were subsumed in subrange\n while subrangePt4[0] >= xrgbPoints[xrgbIndex]:\n xrgbIndex += 4\n if xrgbIndex >= len(xrgbPoints):\n break\n\n while xrgbIndex < len(xrgbPoints):\n myRgbPoints.append(xrgbPoints[xrgbIndex+0])\n myRgbPoints.append(xrgbPoints[xrgbIndex+1])\n myRgbPoints.append(xrgbPoints[xrgbIndex+2])\n myRgbPoints.append(xrgbPoints[xrgbIndex+3])\n xrgbIndex += 4\n\n if PhactoriDbg(100):\n myDebugPrint3('subrange: [' + \\\n str(inSubrangeMin) + ', ' + \\\n str(inSubrangeMax) + ']\\n' + \\\n 'subrange ratio: [' + \\\n str(minHlRatio) + ', ' + \\\n str(maxHlRatio) + ']\\n' + \\\n 'myRGBPoints: \\n' + str(myRgbPoints) + '\\n')\n\n if PhactoriDbg(100):\n myDebugPrint3(\"CalculateColorMapRGBPointsWithSubranges returing \\n\", 100)\n\n return myRgbPoints", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def create_renamed_fields(self):\n \"\"\"Work out renamed fields.\"\"\"\n self.renamed_operations = []\n old_field_keys = self.old_field_keys.copy()\n for app_label, model_name, field_name in sorted(\n self.new_field_keys - old_field_keys\n ):\n old_model_name = self.renamed_models.get(\n (app_label, model_name), model_name\n )\n old_model_state = self.from_state.models[app_label, old_model_name]\n new_model_state = self.to_state.models[app_label, model_name]\n field = new_model_state.get_field(field_name)\n # Scan to see if this is actually a rename!\n field_dec = self.deep_deconstruct(field)\n for rem_app_label, rem_model_name, rem_field_name in sorted(\n old_field_keys - self.new_field_keys\n ):\n if rem_app_label == app_label and rem_model_name == model_name:\n old_field = old_model_state.get_field(rem_field_name)\n old_field_dec = self.deep_deconstruct(old_field)\n if (\n field.remote_field\n and field.remote_field.model\n and \"to\" in old_field_dec[2]\n ):\n old_rel_to = old_field_dec[2][\"to\"]\n if old_rel_to in self.renamed_models_rel:\n old_field_dec[2][\"to\"] = self.renamed_models_rel[old_rel_to]\n old_field.set_attributes_from_name(rem_field_name)\n old_db_column = old_field.get_attname_column()[1]\n if old_field_dec == field_dec or (\n # Was the field renamed and db_column equal to the\n # old field's column added?\n old_field_dec[0:2] == field_dec[0:2]\n and dict(old_field_dec[2], db_column=old_db_column)\n == field_dec[2]\n ):\n if self.questioner.ask_rename(\n model_name, rem_field_name, field_name, field\n ):\n self.renamed_operations.append(\n (\n rem_app_label,\n rem_model_name,\n old_field.db_column,\n rem_field_name,\n app_label,\n model_name,\n field,\n field_name,\n )\n )\n old_field_keys.remove(\n (rem_app_label, rem_model_name, rem_field_name)\n )\n old_field_keys.add((app_label, model_name, field_name))\n self.renamed_fields[app_label, model_name, field_name] = (\n rem_field_name\n )\n break", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def main(argv):\n global opt_dryrun\n\n try:\n (opts, args) = getopt.getopt(\n argv[1:],\n \"hdBw:D:b:\",\n [\n \"help\",\n \"dry-run\",\n \"show-blacklist\",\n \"whitelist=\",\n \"download-dir=\",\n \"build-dir=\",\n ],\n )\n except getopt.GetoptError as e:\n usage()\n return 1\n\n directory = \"dl/\"\n builddir = \"build_dir/\"\n\n for (o, v) in opts:\n if o in (\"-h\", \"--help\"):\n usage()\n return 0\n if o in (\"-d\", \"--dry-run\"):\n opt_dryrun = True\n if o in (\"-w\", \"--whitelist\"):\n for i in range(0, len(blacklist)):\n (name, regex) = blacklist[i]\n if name == v:\n del blacklist[i]\n break\n else:\n print(\"Whitelist error: Item\", v, \"is not in blacklist\")\n return 1\n if o in (\"-B\", \"--show-blacklist\"):\n for (name, regex) in blacklist:\n sep = \"\\t\\t\"\n if len(name) >= 8:\n sep = \"\\t\"\n print(\"%s%s(%s)\" % (name, sep, regex.pattern))\n return 0\n if o in (\"-D\", \"--download-dir\"):\n directory = v\n if o in (\"-b\", \"--build-dir\"):\n builddir = v\n\n if args:\n directory = args[0]\n\n if not os.path.exists(directory):\n print(\"Can't find download directory\", directory)\n return 1\n\n if not os.path.exists(builddir):\n print(\"Can't find build directory\", builddir)\n return 1\n\n # Create a directory listing and parse the file names.\n entries = []\n for filename in os.listdir(directory):\n if filename == \".\" or filename == \"..\":\n continue\n for (name, regex) in blacklist:\n if regex.match(filename):\n if opt_dryrun:\n print(filename, \"is blacklisted\")\n break\n else:\n try:\n entries.append(Entry(directory, builddir, filename))\n except EntryParseError as e:\n pass\n\n # Create a map of programs\n progmap = {}\n for entry in entries:\n if entry.progname in progmap.keys():\n progmap[entry.progname].append(entry)\n else:\n progmap[entry.progname] = [\n entry,\n ]\n\n # Traverse the program map and delete everything but the last version\n for prog in progmap:\n lastVersion = None\n versions = progmap[prog]\n for version in versions:\n if lastVersion:\n if os.path.isdir(lastVersion.getPath()) and not os.path.isdir(version.getPath()):\n continue\n if lastVersion is None or version >= lastVersion:\n lastVersion = version\n if lastVersion:\n for version in versions:\n if version is not lastVersion:\n version.deleteFile()\n if builddir:\n version.deleteBuildDir()\n if opt_dryrun:\n print(\"Keeping\", lastVersion.getPath())\n\n return 0", "smellKey": "S3776", "smellId": null, "repo": "physicszq_openwrt", "language": "python"} {"function": "def provides_distribution(self, name, version=None):\n \"\"\"\n Iterates over all distributions to find which distributions provide *name*.\n If a *version* is provided, it will be used to filter the results.\n\n This function only returns the first result found, since no more than\n one values are expected. If the directory is not found, returns ``None``.\n\n :parameter version: a version specifier that indicates the version\n required, conforming to the format in ``PEP-345``\n\n :type name: string\n :type version: string\n \"\"\"\n matcher = None\n if version is not None:\n try:\n matcher = self._scheme.matcher('%s (%s)' % (name, version))\n except ValueError:\n raise DistlibException('invalid name or version: %r, %r' %\n (name, version))\n\n for dist in self.get_distributions():\n # We hit a problem on Travis where enum34 was installed and doesn't\n # have a provides attribute ...\n if not hasattr(dist, 'provides'):\n logger.debug('No \"provides\": %s', dist)\n else:\n provided = dist.provides\n\n for p in provided:\n p_name, p_ver = parse_name_and_version(p)\n if matcher is None:\n if p_name == name:\n yield dist\n break\n else:\n if p_name == name and matcher.match(p_ver):\n yield dist\n break", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "@transaction.atomic\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.owner_id = validated_data.get('owner_id', instance.owner_id)\n instance.bug_tracker = validated_data.get('bug_tracker', instance.bug_tracker)\n instance.subset = validated_data.get('subset', instance.subset)\n labels = validated_data.get('label_set', [])\n\n if (\n \"assignee_id\" in validated_data and\n validated_data[\"assignee_id\"] != instance.assignee_id\n ):\n instance.assignee_id = validated_data.pop('assignee_id')\n instance.assignee_updated_date = timezone.now()\n\n if instance.project_id is None:\n LabelSerializer.update_labels(labels, parent_instance=instance)\n\n validated_project_id = validated_data.get('project_id')\n if validated_project_id is not None and validated_project_id != instance.project_id:\n project = models.Project.objects.get(id=validated_project_id)\n if project.tasks.count() and project.tasks.first().dimension != instance.dimension:\n raise serializers.ValidationError(f'Dimension ({instance.dimension}) of the task must be the same as other tasks in project ({project.tasks.first().dimension})')\n\n if instance.project_id is None:\n label_set = instance.label_set.all()\n else:\n label_set = instance.project.label_set.all()\n\n for old_label in label_set:\n new_label_for_name = list(filter(lambda x: x.get('id', None) == old_label.id, labels))\n if len(new_label_for_name):\n old_label.name = new_label_for_name[0].get('name', old_label.name)\n try:\n if old_label.parent:\n new_label = project.label_set.filter(name=old_label.name, parent__name=old_label.parent.name).first()\n else:\n new_label = project.label_set.filter(name=old_label.name).first()\n except ValueError:\n raise serializers.ValidationError(f'Target project does not have label with name \"{old_label.name}\"')\n\n for old_attr in old_label.attributespec_set.all():\n new_attr = new_label.attributespec_set.filter(name=old_attr.name,\n values=old_attr.values,\n input_type=old_attr.input_type).first()\n if new_attr is None:\n raise serializers.ValidationError('Target project does not have ' \\\n f'\"{old_label.name}\" label with \"{old_attr.name}\" attribute')\n\n for (model, model_name) in (\n (models.LabeledTrackAttributeVal, 'track'),\n (models.LabeledShapeAttributeVal, 'shape'),\n (models.LabeledImageAttributeVal, 'image'),\n (models.TrackedShapeAttributeVal, 'shape__track')\n ):\n model.objects.filter(**{\n f'{model_name}__job__segment__task': instance,\n f'{model_name}__label': old_label,\n 'spec': old_attr\n }).update(spec=new_attr)\n\n for model in (models.LabeledTrack, models.LabeledShape, models.LabeledImage):\n model.objects.filter(job__segment__task=instance, label=old_label).update(\n label=new_label\n )\n\n if instance.project_id is None:\n instance.label_set.all().delete()\n\n instance.project = project\n\n # update source and target storages\n _update_related_storages(instance, validated_data)\n\n instance.save()\n\n if 'label_set' in validated_data and not instance.project_id:\n self.update_child_objects_on_labels_update(instance)\n\n return instance", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:\n \"\"\"Visit named imports.\"\"\"\n self.newline(node)\n self.write(\"included_template = \")\n self._import_common(node, frame)\n var_names = []\n discarded_names = []\n for name in node.names:\n if isinstance(name, tuple):\n name, alias = name\n else:\n alias = name\n self.writeline(\n f\"{frame.symbols.ref(alias)} =\"\n f\" getattr(included_template, {name!r}, missing)\"\n )\n self.writeline(f\"if {frame.symbols.ref(alias)} is missing:\")\n self.indent()\n message = (\n \"the template {included_template.__name__!r}\"\n f\" (imported on {self.position(node)})\"\n f\" does not export the requested name {name!r}\"\n )\n self.writeline(\n f\"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})\"\n )\n self.outdent()\n if frame.toplevel:\n var_names.append(alias)\n if not alias.startswith(\"_\"):\n discarded_names.append(alias)\n\n if var_names:\n if len(var_names) == 1:\n name = var_names[0]\n self.writeline(f\"context.vars[{name!r}] = {frame.symbols.ref(name)}\")\n else:\n names_kv = \", \".join(\n f\"{name!r}: {frame.symbols.ref(name)}\" for name in var_names\n )\n self.writeline(f\"context.vars.update({{{names_kv}}})\")\n if discarded_names:\n if len(discarded_names) == 1:\n self.writeline(f\"context.exported_vars.discard({discarded_names[0]!r})\")\n else:\n names_str = \", \".join(map(repr, discarded_names))\n self.writeline(\n f\"context.exported_vars.difference_update(({names_str}))\"\n )", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@register.tag(\"blocktranslate\")\n@register.tag(\"blocktrans\")\ndef do_block_translate(parser, token):\n \"\"\"\n Translate a block of text with parameters.\n\n Usage::\n\n {% blocktranslate with bar=foo|filter boo=baz|filter %}\n This is {{ bar }} and {{ boo }}.\n {% endblocktranslate %}\n\n Additionally, this supports pluralization::\n\n {% blocktranslate count count=var|length %}\n There is {{ count }} object.\n {% plural %}\n There are {{ count }} objects.\n {% endblocktranslate %}\n\n This is much like ngettext, only in template syntax.\n\n The \"var as value\" legacy format is still supported::\n\n {% blocktranslate with foo|filter as bar and baz|filter as boo %}\n {% blocktranslate count var|length as count %}\n\n The translated string can be stored in a variable using `asvar`::\n\n {% blocktranslate with bar=foo|filter boo=baz|filter asvar var %}\n This is {{ bar }} and {{ boo }}.\n {% endblocktranslate %}\n {{ var }}\n\n Contextual translations are supported::\n\n {% blocktranslate with bar=foo|filter context \"greeting\" %}\n This is {{ bar }}.\n {% endblocktranslate %}\n\n This is equivalent to calling pgettext/npgettext instead of\n (u)gettext/(u)ngettext.\n \"\"\"\n bits = token.split_contents()\n\n options = {}\n remaining_bits = bits[1:]\n asvar = None\n while remaining_bits:\n option = remaining_bits.pop(0)\n if option in options:\n raise TemplateSyntaxError(\n \"The %r option was specified more than once.\" % option\n )\n if option == \"with\":\n value = token_kwargs(remaining_bits, parser, support_legacy=True)\n if not value:\n raise TemplateSyntaxError(\n '\"with\" in %r tag needs at least one keyword argument.' % bits[0]\n )\n elif option == \"count\":\n value = token_kwargs(remaining_bits, parser, support_legacy=True)\n if len(value) != 1:\n raise TemplateSyntaxError(\n '\"count\" in %r tag expected exactly '\n \"one keyword argument.\" % bits[0]\n )\n elif option == \"context\":\n try:\n value = remaining_bits.pop(0)\n value = parser.compile_filter(value)\n except Exception:\n raise TemplateSyntaxError(\n '\"context\" in %r tag expected exactly one argument.' % bits[0]\n )\n elif option == \"trimmed\":\n value = True\n elif option == \"asvar\":\n try:\n value = remaining_bits.pop(0)\n except IndexError:\n raise TemplateSyntaxError(\n \"No argument provided to the '%s' tag for the asvar option.\"\n % bits[0]\n )\n asvar = value\n else:\n raise TemplateSyntaxError(\n \"Unknown argument for %r tag: %r.\" % (bits[0], option)\n )\n options[option] = value\n\n if \"count\" in options:\n countervar, counter = next(iter(options[\"count\"].items()))\n else:\n countervar, counter = None, None\n if \"context\" in options:\n message_context = options[\"context\"]\n else:\n message_context = None\n extra_context = options.get(\"with\", {})\n\n trimmed = options.get(\"trimmed\", False)\n\n singular = []\n plural = []\n while parser.tokens:\n token = parser.next_token()\n if token.token_type in (TokenType.VAR, TokenType.TEXT):\n singular.append(token)\n else:\n break\n if countervar and counter:\n if token.contents.strip() != \"plural\":\n raise TemplateSyntaxError(\n \"%r doesn't allow other block tags inside it\" % bits[0]\n )\n while parser.tokens:\n token = parser.next_token()\n if token.token_type in (TokenType.VAR, TokenType.TEXT):\n plural.append(token)\n else:\n break\n end_tag_name = \"end%s\" % bits[0]\n if token.contents.strip() != end_tag_name:\n raise TemplateSyntaxError(\n \"%r doesn't allow other block tags (seen %r) inside it\"\n % (bits[0], token.contents)\n )\n\n return BlockTranslateNode(\n extra_context,\n singular,\n plural,\n countervar,\n counter,\n message_context,\n trimmed=trimmed,\n asvar=asvar,\n tag_name=bits[0],\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def collectAttributes(skinAttributes, node, context, skinPath=None, ignore=(), filenames=frozenset((\"pixmap\", \"pointer\", \"seekPointer\", \"seek_pointer\", \"backgroundPixmap\", \"selectionPixmap\", \"sliderPixmap\", \"scrollbarBackgroundPixmap\", \"scrollbarForegroundPixmap\", \"scrollbarbackgroundPixmap\", \"scrollbarBackgroundPicture\", \"scrollbarSliderPicture\"))):\n\tsize = None\n\tpos = None\n\tfont = None\n\tselectionZoom = None\n\tselectionZoomSize = None\n\tfor attrib, value in node.items(): # Walk all attributes.\n\t\tif attrib not in ignore:\n\t\t\tnewValue = value\n\t\t\tif attrib in filenames:\n\t\t\t\t# DEBUG: Why does a SCOPE_LCDSKIN image replace the GUI image?!?!?!\n\t\t\t\tpngFile = resolveFilename(SCOPE_GUISKIN, value, path_prefix=skinPath)\n\t\t\t\tif isfile(pngFile):\n\t\t\t\t\tnewValue = pngFile\n\t\t\t\telse:\n\t\t\t\t\tlcdFile = resolveFilename(SCOPE_LCDSKIN, value, path_prefix=skinPath)\n\t\t\t\t\tnewValue = lcdFile if isfile(lcdFile) else pngFile\n\t\t\t# Bit of a hack this, really. When a window has a flag (e.g. wfNoBorder)\n\t\t\t# it needs to be set at least before the size is set, in order for the\n\t\t\t# window dimensions to be calculated correctly in all situations.\n\t\t\t# If wfNoBorder is applied after the size has been set, the window will\n\t\t\t# fail to clear the title area. Similar situation for a scrollbar in a\n\t\t\t# listbox; when the scrollbar setting is applied after the size, a scrollbar\n\t\t\t# will not be shown until the selection moves for the first time.\n\t\t\tmatch attrib:\n\t\t\t\tcase \"size\":\n\t\t\t\t\tsize = newValue\n\t\t\t\tcase \"position\":\n\t\t\t\t\tpos = newValue\n\t\t\t\tcase \"font\":\n\t\t\t\t\tfont = newValue\n\t\t\t\t\tskinAttributes.append((attrib, newValue))\n\t\t\t\tcase \"selectionZoom\":\n\t\t\t\t\tselectionZoom = newValue\n\t\t\t\tcase \"selectionZoomSize\":\n\t\t\t\t\tselectionZoomSize = newValue\n\t\t\t\tcase _:\n\t\t\t\t\tskinAttributes.append((attrib, newValue))\n\n\tif selectionZoom is not None: # The \"selectionZoom\" attribute must be after the item size attributes.\n\t\tskinAttributes.append((\"selectionZoom\", selectionZoom))\n\tif selectionZoomSize is not None: # The \"selectionZoomSize\" attribute must be after the item size attributes.\n\t\tskinAttributes.append((\"selectionZoomSize\", selectionZoomSize))\n\tif pos is not None: # The \"position\" attribute must be after the all other attributes.\n\t\tpos, size = context.parse(pos, size, font)\n\t\tskinAttributes.append((\"position\", pos))\n\tif size is not None: # The \"size\" attribute must be after the \"position\" attribute.\n\t\tskinAttributes.append((\"size\", size))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def ParseParametersFromJson(self, inJson):\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriPlaneOpBase.ParseParametersFromJson entered\\n\", 100)\n\n if \"plane specification\" in inJson:\n if inJson[\"plane specification\"] == \"point and normal\":\n self.mUseThreePointsOnPlane = False\n elif inJson[\"plane specification\"] == \"three points\":\n self.mUseThreePointsOnPlane = True\n else:\n myDebugPrint3AndException(\n \"PhactoriPlaneOpBase.ParseParametersFromJson:\\n\"\n \"'plane specification' must be 'point and normal' or \"\n \"'three points'\\n\")\n\n if self.mUseThreePointsOnPlane:\n if PhactoriDbg():\n myDebugPrint3(\"using three points on plane instead of plane/normal:\\n\")\n self.mPtOnPlaneInfoA = PhactoriUserPointInfo()\n self.mPtOnPlaneInfoA.mXyz = [0.0, 0.0, 0.0]\n self.mPtOnPlaneInfoB = PhactoriUserPointInfo()\n self.mPtOnPlaneInfoB.mXyz = [0.0, 1.0, 0.0]\n self.mPtOnPlaneInfoC = PhactoriUserPointInfo()\n self.mPtOnPlaneInfoC.mXyz = [0.0, 0.0, 1.0]\n self.mPtOnPlaneInfoA.UserPointInfoParseParametersFromJson(\n inJson, \"\", \" on plane A\")\n self.mPtOnPlaneInfoB.UserPointInfoParseParametersFromJson(\n inJson, \"\", \" on plane B\")\n self.mPtOnPlaneInfoC.UserPointInfoParseParametersFromJson(\n inJson, \"\", \" on plane C\")\n else:\n if PhactoriDbg():\n myDebugPrint3(\n \"using point/normal: PhactoriPlaneOpBase parsing point onplane:\\n\")\n self.mPtOnPlaneInfo.UserPointInfoParseParametersFromJson(\n inJson, \"\", \" on plane\")\n\n if 'plane normal' in inJson:\n self.mPlaneNormal = inJson['plane normal']\n self.mPlaneNormal = vecNormalize(self.mPlaneNormal)\n else:\n self.mPlaneNormal = [0.0, 1.0, 0.0]\n\n if gParaViewCatalystVersionFlag < 50502:\n if 'side to keep' in inJson:\n whichSide = inJson['side to keep']\n if whichSide == 'positive':\n self.mInsideOut = 0\n elif whichSide == 'negative':\n self.mInsideOut = 1\n else:\n if PhactoriDbg():\n myDebugPrint3('ParseParametersFromJson warning: side to keep \\\n should be positive or negative, but is not, using positive\\n')\n else:\n self.mInsideOut = 0\n else:\n if 'side to keep' in inJson:\n whichSide = inJson['side to keep']\n if whichSide == 'positive':\n self.mInvert = 0\n elif whichSide == 'negative':\n self.mInvert = 1\n else:\n if PhactoriDbg():\n myDebugPrint3('ParseParametersFromJson warning: side to keep \\\n should be positive or negative, but is not, using positive\\n')\n else:\n self.mInvert = 0\n\n if 'cut type' in inJson:\n cutType = inJson['cut type']\n self.mCrinkleSetting = 0\n if cutType == 'smooth':\n self.mCrinkleSetting = 0\n elif cutType == 'crinkle':\n self.mCrinkleSetting = 1\n else:\n if PhactoriDbg():\n myDebugPrint3('ParseParametersFromJson warning: cut type \\\n should be smooth or crinkle, but is not, using smooth\\n')\n self.mCrinkleSetting = 0\n else:\n self.mCrinkleSetting = 0 #debatable default", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _register_proc(func: typing.Callable[..., Record], is_write: bool):\n raise_if_does_not_meet_requirements(func)\n register_func = _mgp.Module.add_write_procedure if is_write else _mgp.Module.add_read_procedure\n sig = inspect.signature(func)\n params = tuple(sig.parameters.values())\n if params and params[0].annotation is ProcCtx:\n\n @wraps(func)\n def wrapper(graph, args):\n return func(ProcCtx(graph), *args)\n\n params = params[1:]\n mgp_proc = register_func(_mgp._MODULE, wrapper)\n else:\n\n @wraps(func)\n def wrapper(graph, args):\n return func(*args)\n\n mgp_proc = register_func(_mgp._MODULE, wrapper)\n for param in params:\n name = param.name\n type_ = param.annotation\n if type_ is param.empty:\n type_ = object\n cypher_type = _typing_to_cypher_type(type_)\n if param.default is param.empty:\n mgp_proc.add_arg(name, cypher_type)\n else:\n mgp_proc.add_opt_arg(name, cypher_type, param.default)\n if sig.return_annotation is not sig.empty:\n record = sig.return_annotation\n if not isinstance(record, Record):\n raise TypeError(\"Expected '{}' to return 'mgp.Record', got '{}'\".format(func.__name__, type(record)))\n for name, type_ in record.fields.items():\n if isinstance(type_, Deprecated):\n cypher_type = _typing_to_cypher_type(type_.field_type)\n mgp_proc.add_deprecated_result(name, cypher_type)\n else:\n mgp_proc.add_result(name, _typing_to_cypher_type(type_))\n return func", "smellKey": "S3776", "smellId": null, "repo": "memgraph_memgraph", "language": "python"} {"function": "def _find_no_duplicates(self, name, domain=None, path=None):\n \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n used elsewhere in Requests.\n\n :param name: a string containing name of cookie\n :param domain: (optional) string containing domain of cookie\n :param path: (optional) string containing path of cookie\n :raises KeyError: if cookie is not found\n :raises CookieConflictError: if there are multiple cookies\n that match name and optionally domain and path\n :return: cookie.value\n \"\"\"\n toReturn = None\n for cookie in iter(self):\n if cookie.name == name:\n if domain is None or cookie.domain == domain:\n if path is None or cookie.path == path:\n if toReturn is not None:\n # if there are multiple cookies that meet passed in criteria\n raise CookieConflictError(\n f\"There are multiple cookies with name, {name!r}\"\n )\n # we will eventually return this as long as no cookie conflict\n toReturn = cookie.value\n\n if toReturn:\n return toReturn\n raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def createConfig(self):\n\t\tdays = {}\n\t\tfor day in DAY_LIST:\n\t\t\tdays[day] = False\n\t\tif self.timer.repeated: # Timer repeated.\n\t\t\ttype = \"repeated\"\n\t\t\tweekday = \"Mon\"\n\t\t\tif self.timer.repeated == 31: # Mon-Fri.\n\t\t\t\trepeated = \"weekdays\"\n\t\t\telif self.timer.repeated == 127: # Daily.\n\t\t\t\trepeated = \"daily\"\n\t\t\telse:\n\t\t\t\tflags = self.timer.repeated\n\t\t\t\trepeated = \"user\"\n\t\t\t\tcount = 0\n\t\t\t\tfor day in DAY_LIST:\n\t\t\t\t\tif flags == 1: # Weekly.\n\t\t\t\t\t\tweekday = day\n\t\t\t\t\tif flags & 1 == 1: # Set user defined days.\n\t\t\t\t\t\tdays[day] = True\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tdays[day] = False\n\t\t\t\t\tflags >>= 1\n\t\t\t\tif count == 1:\n\t\t\t\t\trepeated = \"weekly\"\n\t\telse: # Timer once.\n\t\t\ttype = \"once\"\n\t\t\trepeated = None\n\t\t\tweekday = DAY_LIST[int(strftime(\"%u\", localtime(self.timer.begin))) - 1]\n\t\t\tdays[weekday] = True\n\t\tself.timerName = ConfigText(default=self.timer.name.replace(\"\\x86\", \"\").replace(\"\\x87\", \"\"), visible_width=50, fixed_size=False)\n\t\tself.timerDescription = ConfigText(default=self.timer.description.replace(\"\\x8a\", \" \").replace(\"\\n\", \" \"), visible_width=50, fixed_size=False)\n\t\tself.timerType = ConfigSelection(default=RECORDTIMER_TYPES.get(self.timer.justplay + 2 * self.timer.always_zap, \"record\"), choices=[\n\t\t\t(RECORDTIMER_TYPES.get(RECORD_TIMERTYPE.RECORD), RECORDTIMER_TYPE_NAMES.get(RECORD_TIMERTYPE.RECORD)),\n\t\t\t(RECORDTIMER_TYPES.get(RECORD_TIMERTYPE.ZAP), RECORDTIMER_TYPE_NAMES.get(RECORD_TIMERTYPE.ZAP)),\n\t\t\t(RECORDTIMER_TYPES.get(RECORD_TIMERTYPE.ZAP_RECORD), RECORDTIMER_TYPE_NAMES.get(RECORD_TIMERTYPE.ZAP_RECORD))\n\t\t])\n\t\tself.timerRepeat = ConfigSelection(default=type, choices=REPEAT_CHOICES)\n\t\tself.timerRepeatPeriod = ConfigSelection(default=repeated, choices=REPEAT_OPTIONS)\n\t\tself.timerRepeatStartDate = ConfigDateTime(default=self.timer.repeatedbegindate, formatstring=config.usage.date.daylong.value, increment=86400)\n\t\tself.timerWeekday = ConfigSelection(default=weekday, choices=DAY_NAMES)\n\t\tself.timerDay = ConfigSubDict()\n\t\tfor day in DAY_LIST:\n\t\t\tself.timerDay[day] = ConfigYesNo(default=days[day])\n\t\tself.timerRename = ConfigYesNo(default=self.timer.rename_repeat != 0)\n\t\t# self.timerStartDate = ConfigDateTime(default=self.timer.begin, formatstring=config.usage.date.daylong.value, increment=86400)\n\t\tself.timerStartDate = ConfigDateTime(default=self.timer.eventBegin, formatstring=config.usage.date.daylong.value, increment=86400)\n\t\t# self.timerStartTime = ConfigClock(default=self.timer.begin)\n\t\tself.timerStartTime = ConfigClock(default=self.timer.eventBegin)\n\t\tmarginChoices = [(x, ngettext(\"%d Minute\", \"%d Minutes\", x) % x) for x in range(121)]\n\t\tself.timerMarginBefore = ConfigSelection(default=self.timer.marginBefore // 60, choices=marginChoices)\n\t\t# print(\"[Timers] DEBUG: default=%d, value=%d, margin=%d.\" % (self.timerMarginBefore.value, self.timerMarginBefore.default, self.timer.marginBefore // 60))\n\t\t# self.timerHasEndTime = ConfigYesNo(default=self.timer.end > self.timer.begin + 3 and self.timer.justplay != 0)\n\t\tself.timerHasEndTime = ConfigYesNo(default=self.timer.hasEndTime)\n\t\t# self.timerEndTime = ConfigClock(default=self.timer.end)\n\t\tself.timerEndTime = ConfigClock(default=self.timer.eventEnd)\n\t\tself.timerMarginAfter = ConfigSelection(default=self.timer.marginAfter // 60, choices=marginChoices)\n\t\tserviceName = self.getServiceName(self.timer.service_ref)\n\t\tself.timerService = ConfigSelection([(serviceName, serviceName)])\n\t\tself.timerServiceReference = self.timer.service_ref\n\t\tif self.timer.record_ecm and self.timer.descramble:\n\t\t\trecordingType = \"descrambled+ecm\"\n\t\telif self.timer.record_ecm:\n\t\t\trecordingType = \"scrambled+ecm\"\n\t\telif self.timer.descramble:\n\t\t\trecordingType = \"normal\"\n\t\tself.timerRecordingType = ConfigSelection(default=recordingType, choices=[\n\t\t\t(\"normal\", _(\"Normal\")),\n\t\t\t(\"descrambled+ecm\", _(\"Unscramble and record ECM\")),\n\t\t\t(\"scrambled+ecm\", _(\"Don't unscramble, record ECM\"))\n\t\t])\n\t\tdefault, locations = self.getLocationInfo()\n\t\tif default not in locations:\n\t\t\tlocations.append(default)\n\t\tself.timerLocation = ConfigSelection(default=default, choices=locations)\n\n\t\tself.tags = self.timer.tags[:]\n\t\tif not self.tags: # If no tags found, make name of event default tag set.\n\t\t\ttagName = self.timer.name.strip()\n\t\t\tif tagName:\n\t\t\t\ttagName = \"%s%s\" % (tagName[0].upper(), tagName[1:].replace(\" \", \"_\"))\n\t\t\t\tself.tags.append(tagName)\n\t\tself.timerTags = ConfigSelection(choices=[not self.tags and \"None\" or \" \".join(self.tags)])\n\t\tself.timerAfterEvent = ConfigSelection(default=RECORDTIMER_AFTER_EVENTS.get(self.timer.afterEvent, \"auto\"), choices=[\n\t\t\t(RECORDTIMER_AFTER_EVENTS.get(RECORD_AFTEREVENT.NONE), RECORDTIMER_AFTER_EVENT_NAMES.get(RECORD_AFTEREVENT.NONE)),\n\t\t\t(RECORDTIMER_AFTER_EVENTS.get(RECORD_AFTEREVENT.STANDBY), RECORDTIMER_AFTER_EVENT_NAMES.get(RECORD_AFTEREVENT.STANDBY)),\n\t\t\t(RECORDTIMER_AFTER_EVENTS.get(RECORD_AFTEREVENT.DEEPSTANDBY), RECORDTIMER_AFTER_EVENT_NAMES.get(RECORD_AFTEREVENT.DEEPSTANDBY)),\n\t\t\t(RECORDTIMER_AFTER_EVENTS.get(RECORD_AFTEREVENT.AUTO), RECORDTIMER_AFTER_EVENT_NAMES.get(RECORD_AFTEREVENT.AUTO))\n\t\t])\n\t\tself.timerFallback = ConfigYesNo(default=self.timer.external_prev or self.newEntry and config.usage.remote_fallback_external_timer.value and config.usage.remote_fallback.value and config.usage.remote_fallback_external_timer_default.value)\n\n\t\tfor callback in onRecordTimerCreate:\n\t\t\tcallback(self)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def assertRunTestResults(\n self, run_tests_report, expected_parse_results=None, msg=None\n ):\n \"\"\"\n Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of\n list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped\n with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.\n Finally, asserts that the overall ``runTests()`` success value is ``True``.\n\n :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests\n :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]\n \"\"\"\n run_test_success, run_test_results = run_tests_report\n\n if expected_parse_results is not None:\n merged = [\n (*rpt, expected)\n for rpt, expected in zip(run_test_results, expected_parse_results)\n ]\n for test_string, result, expected in merged:\n # expected should be a tuple containing a list and/or a dict or an exception,\n # and optional failure message string\n # an empty tuple will skip any result validation\n fail_msg = next(\n (exp for exp in expected if isinstance(exp, str)), None\n )\n expected_exception = next(\n (\n exp\n for exp in expected\n if isinstance(exp, type) and issubclass(exp, Exception)\n ),\n None,\n )\n if expected_exception is not None:\n with self.assertRaises(\n expected_exception=expected_exception, msg=fail_msg or msg\n ):\n if isinstance(result, Exception):\n raise result\n else:\n expected_list = next(\n (exp for exp in expected if isinstance(exp, list)), None\n )\n expected_dict = next(\n (exp for exp in expected if isinstance(exp, dict)), None\n )\n if (expected_list, expected_dict) != (None, None):\n self.assertParseResultsEquals(\n result,\n expected_list=expected_list,\n expected_dict=expected_dict,\n msg=fail_msg or msg,\n )\n else:\n # warning here maybe?\n print(f\"no validation for {test_string!r}\")\n\n # do this last, in case some specific test results can be reported instead\n self.assertTrue(\n run_test_success, msg=msg if msg is not None else \"failed runTests\"\n )", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def setEvent(self, event):\n\t\tif event is None:\n\t\t\treturn\n\t\tself.event = event\n\t\ttry:\n\t\t\tname = event.getEventName()\n\t\t\tself[\"channel\"].setText(name)\n\t\texcept Exception:\n\t\t\tpass\n\t\tdescription = event.getShortDescription()\n\t\textended = event.getExtendedDescription()\n\t\tif description and extended:\n\t\t\tdescription += \"\\n\"\n\t\telif description and not extended:\n\t\t\textended = description\n\t\tif description == extended:\n\t\t\ttext = description\n\t\telse:\n\t\t\ttext = description + extended\n\t\tself.setTitle(event.getEventName())\n\t\tself[\"epg_description\"].setText(text)\n\t\tself[\"FullDescription\"].setText(extended)\n\t\tserviceref = self.currentService\n\t\teventid = self.event.getEventId()\n\t\trefstr = serviceref.ref.toString()\n\t\tisRecordEvent = False\n\t\tfor timer in self.session.nav.RecordTimer.timer_list:\n\t\t\tif timer.eit == eventid and timer.service_ref.ref.toString() == refstr:\n\t\t\t\tisRecordEvent = True\n\t\t\t\tbreak\n\t\tif isRecordEvent and self.key_green_choice != self.REMOVE_TIMER:\n\t\t\tself[\"key_green\"].setText(_(\"Remove timer\"))\n\t\t\tself.key_green_choice = self.REMOVE_TIMER\n\t\telif not isRecordEvent and self.key_green_choice != self.ADD_TIMER:\n\t\t\tself[\"key_green\"].setText(_(\"Add Timer\"))\n\t\t\tself.key_green_choice = self.ADD_TIMER", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _wrap_tablelinenos(self, inner):\n dummyoutfile = StringIO()\n lncount = 0\n for t, line in inner:\n if t:\n lncount += 1\n dummyoutfile.write(line)\n\n fl = self.linenostart\n mw = len(str(lncount + fl - 1))\n sp = self.linenospecial\n st = self.linenostep\n anchor_name = self.lineanchors or self.linespans\n aln = self.anchorlinenos\n nocls = self.noclasses\n\n lines = []\n\n for i in range(fl, fl+lncount):\n print_line = i % st == 0\n special_line = sp and i % sp == 0\n\n if print_line:\n line = '%*d' % (mw, i)\n if aln:\n line = '<a href=\"#%s-%d\">%s</a>' % (anchor_name, i, line)\n else:\n line = ' ' * mw\n\n if nocls:\n if special_line:\n style = ' style=\"%s\"' % self._linenos_special_style\n else:\n style = ' style=\"%s\"' % self._linenos_style\n else:\n if special_line:\n style = ' class=\"special\"'\n else:\n style = ' class=\"normal\"'\n\n if style:\n line = '<span%s>%s</span>' % (style, line)\n\n lines.append(line)\n\n ls = '\\n'.join(lines)\n\n # If a filename was specified, we can't put it into the code table as it\n # would misalign the line numbers. Hence we emit a separate row for it.\n filename_tr = \"\"\n if self.filename:\n filename_tr = (\n '<tr><th colspan=\"2\" class=\"filename\">'\n '<span class=\"filename\">' + self.filename + '</span>'\n '</th></tr>')\n\n # in case you wonder about the seemingly redundant <div> here: since the\n # content in the other cell also is wrapped in a div, some browsers in\n # some configurations seem to mess up the formatting...\n yield 0, (f'<table class=\"{self.cssclass}table\">' + filename_tr +\n '<tr><td class=\"linenos\"><div class=\"linenodiv\"><pre>' +\n ls + '</pre></div></td><td class=\"code\">')\n yield 0, '<div>'\n yield 0, dummyoutfile.getvalue()\n yield 0, '</div>'\n yield 0, '</td></tr></table>'", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def iterator(self, resource_name):\n resource = self.find(resource_name)\n if resource is not None:\n todo = [resource]\n while todo:\n resource = todo.pop(0)\n yield resource\n if resource.is_container:\n rname = resource.name\n for name in resource.resources:\n if not rname:\n new_name = name\n else:\n new_name = '/'.join([rname, name])\n child = self.find(new_name)\n if child.is_container:\n todo.append(child)\n else:\n yield child", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def del_key_in_dict(orig_dict, keys):\n \"\"\"Remove keys from dictionaires.\"\"\"\n modified_dict = {}\n for key, value in orig_dict.items():\n if key not in keys:\n if isinstance(value, MutableMapping): # or\n modified_dict[key] = del_key_in_dict(value, keys)\n elif isinstance(value, MutableSequence):\n if rv := scan_list(value, keys):\n modified_dict[key] = rv\n else:\n modified_dict[key] = value # or copy.deepcopy(value) if a copy is desired for non-dicts.\n return modified_dict", "smellKey": "S3776", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "def _init_tokens():\n # Builds a (<token 1>)|(<token 2>)|... regex and assigns the index of each\n # capturing group to a corresponding _T_<TOKEN> variable. This makes the\n # token type appear in match.lastindex after a match.\n\n global _token_re\n global _T_NUM\n global _T_PROPNODENAME\n global _T_MISC\n global _T_BYTE\n global _T_BAD\n\n # Each pattern must have exactly one capturing group, which can capture any\n # part of the pattern. This makes match.lastindex match the token type.\n # _Token.val is based on the captured string.\n token_spec = ((\"_T_INCLUDE\", r'(/include/\\s*\"(?:[^\\\\\"]|\\\\.)*\")'),\n (\"_T_LINE\", # #line directive\n r'^#(?:line)?[ \\t]+([0-9]+[ \\t]+\"(?:[^\\\\\"]|\\\\.)*\")(?:[ \\t]+[0-9]+)?'),\n (\"_T_STRING\", r'\"((?:[^\\\\\"]|\\\\.)*)\"'),\n (\"_T_DTS_V1\", r\"(/dts-v1/)\"),\n (\"_T_PLUGIN\", r\"(/plugin/)\"),\n (\"_T_MEMRESERVE\", r\"(/memreserve/)\"),\n (\"_T_BITS\", r\"(/bits/)\"),\n (\"_T_DEL_PROP\", r\"(/delete-property/)\"),\n (\"_T_DEL_NODE\", r\"(/delete-node/)\"),\n (\"_T_OMIT_IF_NO_REF\", r\"(/omit-if-no-ref/)\"),\n (\"_T_LABEL\", r\"([a-zA-Z_][a-zA-Z0-9_]*):\"),\n (\"_T_CHAR_LITERAL\", r\"'((?:[^\\\\']|\\\\.)*)'\"),\n (\"_T_REF\",\n r\"&([a-zA-Z_][a-zA-Z0-9_]*|{[a-zA-Z0-9,._+*#?@/-]*})\"),\n (\"_T_INCBIN\", r\"(/incbin/)\"),\n # Whitespace, C comments, and C++ comments\n (\"_T_SKIP\", r\"(\\s+|(?:/\\*(?:.|\\n)*?\\*/)|//.*$)\"),\n # Return a token for end-of-file so that the parsing code can\n # always assume that there are more tokens when looking\n # ahead. This simplifies things.\n (\"_T_EOF\", r\"(\\Z)\"))\n\n # MULTILINE is needed for C++ comments and #line directives\n _token_re = re.compile(\"|\".join(spec[1] for spec in token_spec),\n re.MULTILINE | re.ASCII)\n\n for i, spec in enumerate(token_spec, 1):\n globals()[spec[0]] = i\n\n # pylint: disable=undefined-loop-variable\n _T_NUM = i + 1\n _T_PROPNODENAME = i + 2\n _T_MISC = i + 3\n _T_BYTE = i + 4\n _T_BAD = i + 5", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def updateAdvanced(self, sec, slotid):\n\t\tadvanced = config.Nims[slotid].dvbs.advanced\n\t\ttry:\n\t\t\tif advanced.unicableconnected is not None:\n\t\t\t\tif advanced.unicableconnected.value:\n\t\t\t\t\tadvanced.unicableconnectedTo.save_forced = True\n\t\t\t\t\tself.linkNIMs(sec, slotid, int(advanced.unicableconnectedTo.value))\n\t\t\t\t\tconnto = self.getRoot(slotid, int(advanced.unicableconnectedTo.value))\n\t\t\t\t\tif connto not in self.linked:\n\t\t\t\t\t\tself.linked[connto] = []\n\t\t\t\t\tself.linked[connto].append(slotid)\n\t\t\t\telse:\n\t\t\t\t\tadvanced.unicableconnectedTo.save_forced = False\n\t\texcept:\n\t\t\tpass\n\n\t\tlnbSat = {}\n\t\tfor x in list(range(1, 71)):\n\t\t\tlnbSat[x] = []\n\n\t\t#wildcard for all satellites ( for rotor )\n\t\tfor x in list(range(3601, 3605)):\n\t\t\tlnb = int(advanced.sat[x].lnb.value)\n\t\t\tif lnb != 0:\n\t\t\t\tfor x in self.NimManager.satList:\n\t\t\t\t\tprint(\"[NimManager] add %s to %s\" % (x[0], lnb))\n\t\t\t\t\tlnbSat[lnb].append(x[0])\n\n\t\t#wildcard for user satellites ( for rotor )\n\t\tfor x in list(range(3605, 3607)):\n\t\t\tlnb = int(advanced.sat[x].lnb.value)\n\t\t\tif lnb != 0:\n\t\t\t\tfor user_sat in self.NimManager.satList:\n\t\t\t\t\tif str(user_sat[0]) in advanced.sat[x].userSatellitesList.value:\n\t\t\t\t\t\tprint(\"[NimManager] add %s to %s\" % (user_sat[0], lnb))\n\t\t\t\t\t\tlnbSat[lnb].append(user_sat[0])\n\n\t\tfor x in self.NimManager.satList:\n\t\t\tlnb = int(advanced.sat[x[0]].lnb.value)\n\t\t\tif lnb != 0:\n\t\t\t\tprint(\"[NimManager] add %s to %s\" % (x[0], lnb))\n\t\t\t\tlnbSat[lnb].append(x[0])\n\n\t\tfor x in list(range(1, 71)):\n\t\t\tif len(lnbSat[x]) > 0:\n\t\t\t\tcurrLnb = advanced.lnb[x]\n\t\t\t\tif sec.addLNB():\n\t\t\t\t\tprint(\"[NimManager] No space left on m_lnbs (max No. 144 LNBs exceeded)\")\n\t\t\t\t\treturn\n\n\t\t\t\tposnum = 1\n\t\t\t\t#default if LNB movable\n\t\t\t\tif x <= maxFixedLnbPositions:\n\t\t\t\t\tposnum = x\n\t\t\t\t\tsec.setLNBSatCRpositionnumber(x) # LNB has fixed Position\n\t\t\t\telse:\n\t\t\t\t\tsec.setLNBSatCRpositionnumber(0) # or not (movable LNB)\n\n\t\t\t\ttunermask = 1 << slotid\n\t\t\t\tif slotid in self.equal:\n\t\t\t\t\tfor slot in self.equal[slotid]:\n\t\t\t\t\t\ttunermask |= (1 << slot)\n\t\t\t\tif slotid in self.linked:\n\t\t\t\t\tfor slot in self.linked[slotid]:\n\t\t\t\t\t\ttunermask |= (1 << slot)\n\t\t\t\tif currLnb.lof.value != \"unicable\":\n\t\t\t\t\tsec.setLNBSatCR(-1)\n\t\t\t\t\tsec.setLNBSatCRTuningAlgo(0)\n\t\t\t\t\tsec.setLNBBootupTime(0)\n\t\t\t\tif currLnb.lof.value == \"universal_lnb\":\n\t\t\t\t\tsec.setLNBLOFL(9750000)\n\t\t\t\t\tsec.setLNBLOFH(10600000)\n\t\t\t\t\tsec.setLNBThreshold(11700000)\n\t\t\t\telif currLnb.lof.value == \"unicable\":\n\t\t\t\t\tdef setupUnicable(configManufacturer, ProductDict):\n\t\t\t\t\t\tmanufacturer_name = configManufacturer.value\n\t\t\t\t\t\tmanufacturer = ProductDict[manufacturer_name]\n\t\t\t\t\t\tproduct_name = manufacturer.product.value\n\t\t\t\t\t\tif product_name == \"None\" and manufacturer.product.saved_value != \"None\":\n\t\t\t\t\t\t\tproduct_name = manufacturer.product.value = manufacturer.product.saved_value\n\t\t\t\t\t\tmanufacturer_scr = manufacturer.scr\n\t\t\t\t\t\tmanufacturer_positions_value = manufacturer.positions[product_name][0].value\n\t\t\t\t\t\tposition_idx = (posnum - 1) % manufacturer_positions_value\n\t\t\t\t\t\tif product_name in manufacturer_scr:\n\t\t\t\t\t\t\tdiction = manufacturer.diction[product_name].value\n\t\t\t\t\t\t\tpositionsoffset = manufacturer.positionsoffset[product_name][0].value\n\t\t\t\t\t\t\tif diction != \"EN50607\" or ((posnum <= (positionsoffset + manufacturer_positions_value) and (posnum > positionsoffset) and x <= maxFixedLnbPositions)): # for every allowed position\n\t\t\t\t\t\t\t\tsec.setLNBSatCRformat(diction == \"EN50607\" and 1 or 0)\n\t\t\t\t\t\t\t\tsec.setLNBSatCR(manufacturer_scr[product_name].index)\n\t\t\t\t\t\t\t\tsec.setLNBSatCRvco(manufacturer.vco[product_name][manufacturer_scr[product_name].index].value * 1000)\n\t\t\t\t\t\t\t\tsec.setLNBSatCRpositions(manufacturer_positions_value)\n\t\t\t\t\t\t\t\tsec.setLNBLOFL(manufacturer.lofl[product_name][position_idx].value * 1000)\n\t\t\t\t\t\t\t\tsec.setLNBLOFH(manufacturer.lofh[product_name][position_idx].value * 1000)\n\t\t\t\t\t\t\t\tsec.setLNBThreshold(manufacturer.loft[product_name][position_idx].value * 1000)\n\t\t\t\t\t\t\t\tsec.setLNBSatCRTuningAlgo([\"traditional\", \"reliable\", \"traditional_retune\", \"reliable_retune\"].index(currLnb.unicableTuningAlgo.value))\n\t\t\t\t\t\t\t\tsec.setLNBBootupTime(manufacturer.bootuptime[product_name][0].value)\n\t\t\t\t\t\t\t\tconfigManufacturer.save_forced = True\n\t\t\t\t\t\t\t\tmanufacturer.product.save_forced = True\n\t\t\t\t\t\t\t\tmanufacturer.vco[product_name][manufacturer_scr[product_name].index].save_forced = True\n\t\t\t\t\t\t\telse: # positionnumber out of range\n\t\t\t\t\t\t\t\tprint(\"[NimManager] positionnumber out of range\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"[NimManager] no product in list\")\n\n\t\t\t\t\tif currLnb.unicable.value == \"unicable_user\":\n#TODO satpositions for satcruser\n\t\t\t\t\t\tif currLnb.dictionuser.value == \"EN50607\":\n\t\t\t\t\t\t\tsec.setLNBSatCRformat(1)\n\t\t\t\t\t\t\tsec.setLNBSatCR(currLnb.satcruserEN50607.index)\n\t\t\t\t\t\t\tsec.setLNBSatCRvco(currLnb.satcrvcouserEN50607[currLnb.satcruserEN50607.index].value * 1000)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsec.setLNBSatCRformat(0)\n\t\t\t\t\t\t\tsec.setLNBSatCR(currLnb.satcruserEN50494.index)\n\t\t\t\t\t\t\tsec.setLNBSatCRvco(currLnb.satcrvcouserEN50494[currLnb.satcruserEN50494.index].value * 1000)\n\n\t\t\t\t\t\tsec.setLNBLOFL(currLnb.lofl.value * 1000)\n\t\t\t\t\t\tsec.setLNBLOFH(currLnb.lofh.value * 1000)\n\t\t\t\t\t\tsec.setLNBThreshold(currLnb.threshold.value * 1000)\n\t\t\t\t\t\tsec.setLNBSatCRpositions(64)\n\t\t\t\t\t\tsec.setLNBBootupTime(currLnb.bootuptimeuser.value)\n\t\t\t\t\telif currLnb.unicable.value == \"unicable_matrix\":\n\t\t\t\t\t\tself.reconstructUnicableDate(currLnb.unicableMatrixManufacturer, currLnb.unicableMatrix, currLnb)\n\t\t\t\t\t\tsetupUnicable(currLnb.unicableMatrixManufacturer, currLnb.unicableMatrix)\n\t\t\t\t\telif currLnb.unicable.value == \"unicable_lnb\":\n\t\t\t\t\t\tself.reconstructUnicableDate(currLnb.unicableLnbManufacturer, currLnb.unicableLnb, currLnb)\n\t\t\t\t\t\tsetupUnicable(currLnb.unicableLnbManufacturer, currLnb.unicableLnb)\n\t\t\t\telif currLnb.lof.value == \"c_band\":\n\t\t\t\t\tsec.setLNBLOFL(5150000)\n\t\t\t\t\tsec.setLNBLOFH(5150000)\n\t\t\t\t\tsec.setLNBThreshold(5150000)\n\t\t\t\telif currLnb.lof.value == \"user_defined\":\n\t\t\t\t\tsec.setLNBLOFL(currLnb.lofl.value * 1000)\n\t\t\t\t\tsec.setLNBLOFH(currLnb.lofh.value * 1000)\n\t\t\t\t\tsec.setLNBThreshold(currLnb.threshold.value * 1000)\n\t\t\t\telif currLnb.lof.value == \"circular_lnb\":\n\t\t\t\t\tsec.setLNBLOFL(10750000)\n\t\t\t\t\tsec.setLNBLOFH(10750000)\n\t\t\t\t\tsec.setLNBThreshold(10750000)\n\t\t\t\telif currLnb.lof.value == \"ka_sat\":\n\t\t\t\t\tsec.setLNBLOFL(21200000)\n\t\t\t\t\tsec.setLNBLOFH(21200000)\n\t\t\t\t\tsec.setLNBThreshold(21200000)\n\n\t\t\t\tif currLnb.increased_voltage.value:\n\t\t\t\t\tsec.setLNBIncreasedVoltage(True)\n\t\t\t\telse:\n\t\t\t\t\tsec.setLNBIncreasedVoltage(False)\n\n\t\t\t\tdm = currLnb.diseqcMode.value\n\t\t\t\tif dm == \"none\":\n\t\t\t\t\tsec.setDiSEqCMode(diseqcParam.NONE)\n\t\t\t\telif dm == \"1_0\":\n\t\t\t\t\tsec.setDiSEqCMode(diseqcParam.V1_0)\n\t\t\t\telif dm == \"1_1\":\n\t\t\t\t\tsec.setDiSEqCMode(diseqcParam.V1_1)\n\t\t\t\telif dm == \"1_2\":\n\t\t\t\t\tsec.setDiSEqCMode(diseqcParam.V1_2)\n\n\t\t\t\t\tif slotid in self.satposdepends:\n\t\t\t\t\t\tfor slot in self.satposdepends[slotid]:\n\t\t\t\t\t\t\ttunermask |= (1 << slot)\n\n\t\t\t\tif dm != \"none\":\n\t\t\t\t\tif currLnb.toneburst.value == \"none\":\n\t\t\t\t\t\tsec.setToneburst(diseqcParam.NO)\n\t\t\t\t\telif currLnb.toneburst.value == \"A\":\n\t\t\t\t\t\tsec.setToneburst(diseqcParam.A)\n\t\t\t\t\telif currLnb.toneburst.value == \"B\":\n\t\t\t\t\t\tsec.setToneburst(diseqcParam.B)\n\n\t\t\t\t\t# Committed Diseqc Command\n\t\t\t\t\tcdc = currLnb.commitedDiseqcCommand.value\n\n\t\t\t\t\tc = {\"none\": diseqcParam.SENDNO,\n\t\t\t\t\t\t\"AA\": diseqcParam.AA,\n\t\t\t\t\t\t\"AB\": diseqcParam.AB,\n\t\t\t\t\t\t\"BA\": diseqcParam.BA,\n\t\t\t\t\t\t\"BB\": diseqcParam.BB}\n\n\t\t\t\t\tif cdc in c:\n\t\t\t\t\t\tsec.setCommittedCommand(c[cdc])\n\t\t\t\t\telse:\n\t\t\t\t\t\tsec.setCommittedCommand(int(cdc))\n\n\t\t\t\t\tsec.setFastDiSEqC(currLnb.fastDiseqc.value)\n\n\t\t\t\t\tsec.setSeqRepeat(currLnb.sequenceRepeat.value)\n\n\t\t\t\t\tif currLnb.diseqcMode.value == \"1_0\":\n\t\t\t\t\t\tcurrCO = currLnb.commandOrder1_0.value\n\t\t\t\t\t\tsec.setRepeats(0)\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurrCO = currLnb.commandOrder.value\n\n\t\t\t\t\t\tudc = int(currLnb.uncommittedDiseqcCommand.value)\n\t\t\t\t\t\tif udc > 0:\n\t\t\t\t\t\t\tsec.setUncommittedCommand(0xF0 | (udc - 1))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsec.setUncommittedCommand(0) # SENDNO\n\n\t\t\t\t\t\tsec.setRepeats({\"none\": 0, \"one\": 1, \"two\": 2, \"three\": 3}[currLnb.diseqcRepeats.value])\n\n\t\t\t\t\t# setCommandOrder = False\n\n\t\t\t\t\t# 0 \"committed, toneburst\",\n\t\t\t\t\t# 1 \"toneburst, committed\",\n\t\t\t\t\t# 2 \"committed, uncommitted, toneburst\",\n\t\t\t\t\t# 3 \"toneburst, committed, uncommitted\",\n\t\t\t\t\t# 4 \"uncommitted, committed, toneburst\"\n\t\t\t\t\t# 5 \"toneburst, uncommitted, commmitted\"\n\t\t\t\t\torder_map = {\"ct\": 0, \"tc\": 1, \"cut\": 2, \"tcu\": 3, \"uct\": 4, \"tuc\": 5}\n\t\t\t\t\tsec.setCommandOrder(order_map[currCO])\n\n\t\t\t\tif dm == \"1_2\":\n\t\t\t\t\tlatitude = currLnb.latitude.float\n\t\t\t\t\tsec.setLatitude(latitude)\n\t\t\t\t\tlongitude = currLnb.longitude.float\n\t\t\t\t\tsec.setLongitude(longitude)\n\t\t\t\t\tif currLnb.latitudeOrientation.value == \"north\":\n\t\t\t\t\t\tsec.setLaDirection(rotorParam.NORTH)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsec.setLaDirection(rotorParam.SOUTH)\n\t\t\t\t\tif currLnb.longitudeOrientation.value == \"east\":\n\t\t\t\t\t\tsec.setLoDirection(rotorParam.EAST)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsec.setLoDirection(rotorParam.WEST)\n\n\t\t\t\t\tif currLnb.powerMeasurement.value:\n\t\t\t\t\t\tsec.setUseInputpower(True)\n\t\t\t\t\t\tsec.setInputpowerDelta(currLnb.powerThreshold.value)\n\t\t\t\t\t\tturn_speed_dict = {\"fast\": rotorParam.FAST, \"slow\": rotorParam.SLOW}\n\t\t\t\t\t\tif currLnb.turningSpeed.value in turn_speed_dict:\n\t\t\t\t\t\t\tturning_speed = turn_speed_dict[currLnb.turningSpeed.value]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbeg_time = localtime(currLnb.fastTurningBegin.value)\n\t\t\t\t\t\t\tend_time = localtime(currLnb.fastTurningEnd.value)\n\t\t\t\t\t\t\tturning_speed = ((beg_time.tm_hour + 1) * 60 + beg_time.tm_min + 1) << 16\n\t\t\t\t\t\t\tturning_speed |= (end_time.tm_hour + 1) * 60 + end_time.tm_min + 1\n\t\t\t\t\t\tsec.setRotorTurningSpeed(turning_speed)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsec.setUseInputpower(False)\n\n\t\t\t\tsec.setLNBSlotMask(tunermask)\n\n\t\t\t\tsec.setLNBPrio(int(currLnb.prio.value))\n\n\t\t\t\t# finally add the orbital positions\n\t\t\t\tfor y in lnbSat[x]:\n\t\t\t\t\tself.addSatellite(sec, y)\n\t\t\t\t\tif x > maxFixedLnbPositions:\n\t\t\t\t\t\tsatpos = x > maxFixedLnbPositions and (3606 - (70 - x)) or y\n\t\t\t\t\telse:\n\t\t\t\t\t\tsatpos = y\n\t\t\t\t\tcurrSat = advanced.sat[satpos]\n\t\t\t\t\tif currSat.voltage.value == \"polarization\":\n\t\t\t\t\t\tif config.Nims[slotid].dvbs.diseqc13V.value:\n\t\t\t\t\t\t\tsec.setVoltageMode(switchParam.HV_13)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsec.setVoltageMode(switchParam.HV)\n\t\t\t\t\telif currSat.voltage.value == \"13V\":\n\t\t\t\t\t\t# noinspection PyProtectedMember\n\t\t\t\t\t\tsec.setVoltageMode(switchParam._14V)\n\t\t\t\t\telif currSat.voltage.value == \"18V\":\n\t\t\t\t\t\t# noinspection PyProtectedMember\n\t\t\t\t\t\tsec.setVoltageMode(switchParam._18V)\n\n\t\t\t\t\tif currSat.tonemode.value == \"band\":\n\t\t\t\t\t\tsec.setToneMode(switchParam.HILO)\n\t\t\t\t\telif currSat.tonemode.value == \"on\":\n\t\t\t\t\t\tsec.setToneMode(switchParam.ON)\n\t\t\t\t\telif currSat.tonemode.value == \"off\":\n\t\t\t\t\t\tsec.setToneMode(switchParam.OFF)\n\t\t\t\t\tif not currSat.usals.value and x <= maxFixedLnbPositions:\n\t\t\t\t\t\tsec.setRotorPosNum(currSat.rotorposition.value)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsec.setRotorPosNum(0) # USALS", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _order_by_pairs(self):\n if self.query.extra_order_by:\n ordering = self.query.extra_order_by\n elif not self.query.default_ordering:\n ordering = self.query.order_by\n elif self.query.order_by:\n ordering = self.query.order_by\n elif (meta := self.query.get_meta()) and meta.ordering:\n ordering = meta.ordering\n self._meta_ordering = ordering\n else:\n ordering = []\n if self.query.standard_ordering:\n default_order, _ = ORDER_DIR[\"ASC\"]\n else:\n default_order, _ = ORDER_DIR[\"DESC\"]\n\n selected_exprs = {}\n # Avoid computing `selected_exprs` if there is no `ordering` as it's\n # relatively expensive.\n if ordering and (select := self.select):\n for ordinal, (expr, _, alias) in enumerate(select, start=1):\n pos_expr = PositionRef(ordinal, alias, expr)\n if alias:\n selected_exprs[alias] = pos_expr\n selected_exprs[expr] = pos_expr\n\n for field in ordering:\n if hasattr(field, \"resolve_expression\"):\n if isinstance(field, Value):\n # output_field must be resolved for constants.\n field = Cast(field, field.output_field)\n if not isinstance(field, OrderBy):\n field = field.asc()\n if not self.query.standard_ordering:\n field = field.copy()\n field.reverse_ordering()\n select_ref = selected_exprs.get(field.expression)\n if select_ref or (\n isinstance(field.expression, F)\n and (select_ref := selected_exprs.get(field.expression.name))\n ):\n # Emulation of NULLS (FIRST|LAST) cannot be combined with\n # the usage of ordering by position.\n if (\n field.nulls_first is None and field.nulls_last is None\n ) or self.connection.features.supports_order_by_nulls_modifier:\n field = field.copy()\n field.expression = select_ref\n # Alias collisions are not possible when dealing with\n # combined queries so fallback to it if emulation of NULLS\n # handling is required.\n elif self.query.combinator:\n field = field.copy()\n field.expression = Ref(select_ref.refs, select_ref.source)\n yield field, select_ref is not None\n continue\n if field == \"?\": # random\n yield OrderBy(Random()), False\n continue\n\n col, order = get_order_dir(field, default_order)\n descending = order == \"DESC\"\n\n if select_ref := selected_exprs.get(col):\n # Reference to expression in SELECT clause\n yield (\n OrderBy(\n select_ref,\n descending=descending,\n ),\n True,\n )\n continue\n\n if expr := self.query.annotations.get(col):\n ref = col\n transforms = []\n else:\n ref, *transforms = col.split(LOOKUP_SEP)\n expr = self.query.annotations.get(ref)\n if expr:\n if self.query.combinator and self.select:\n if transforms:\n raise NotImplementedError(\n \"Ordering combined queries by transforms is not \"\n \"implemented.\"\n )\n # Don't use the resolved annotation because other\n # combined queries might define it differently.\n expr = F(ref)\n if transforms:\n for name in transforms:\n expr = self.query.try_transform(expr, name)\n if isinstance(expr, Value):\n # output_field must be resolved for constants.\n expr = Cast(expr, expr.output_field)\n yield OrderBy(expr, descending=descending), False\n continue\n\n if \".\" in field:\n # This came in through an extra(order_by=...) addition. Pass it\n # on verbatim.\n table, col = col.split(\".\", 1)\n yield (\n OrderBy(\n RawSQL(\n \"%s.%s\" % (self.quote_name_unless_alias(table), col), []\n ),\n descending=descending,\n ),\n False,\n )\n continue\n\n if self.query.extra and col in self.query.extra:\n if col in self.query.extra_select:\n yield (\n OrderBy(\n Ref(col, RawSQL(*self.query.extra[col])),\n descending=descending,\n ),\n True,\n )\n else:\n yield (\n OrderBy(RawSQL(*self.query.extra[col]), descending=descending),\n False,\n )\n else:\n if self.query.combinator and self.select:\n # Don't use the first model's field because other\n # combinated queries might define it differently.\n yield OrderBy(F(col), descending=descending), False\n else:\n # 'col' is of the form 'field' or 'field1__field2' or\n # '-field1__field2__field', etc.\n yield from self.find_ordering_name(\n field,\n self.query.get_meta(),\n default_order=default_order,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def to_shapes(self, end_frame: int, *,\n included_frames: Optional[Sequence[int]] = None,\n include_outside: bool = False,\n use_server_track_ids: bool = False\n ) -> list:\n shapes = []\n for idx, track in enumerate(self.objects):\n track_id = track[\"id\"] if use_server_track_ids else idx\n track_shapes = {}\n\n for shape in TrackManager.get_interpolated_shapes(\n track,\n 0,\n end_frame,\n self.dimension,\n include_outside=include_outside,\n included_frames=included_frames,\n ):\n shape[\"label_id\"] = track[\"label_id\"]\n shape[\"group\"] = track[\"group\"]\n shape[\"track_id\"] = track_id\n shape[\"source\"] = track[\"source\"]\n shape[\"attributes\"] += track[\"attributes\"]\n shape[\"elements\"] = []\n\n track_shapes[shape[\"frame\"]] = shape\n\n if not track_shapes:\n # This track has no elements on the included frames\n continue\n\n if track.get(\"elements\"):\n track_elements = TrackManager(track[\"elements\"], dimension=self.dimension)\n element_included_frames = set(track_shapes.keys())\n if included_frames is not None:\n element_included_frames = element_included_frames.intersection(included_frames)\n element_shapes = track_elements.to_shapes(end_frame,\n included_frames=element_included_frames,\n include_outside=True, # elements are controlled by the parent shape\n use_server_track_ids=use_server_track_ids\n )\n\n for shape in element_shapes:\n track_shapes[shape[\"frame\"]][\"elements\"].append(shape)\n\n # The whole shape can be filtered out, if all its elements are outside,\n # and outside shapes are not requested.\n if not include_outside:\n track_shapes = {\n frame_number: shape for frame_number, shape in track_shapes.items()\n if not shape[\"elements\"]\n or not all(elem[\"outside\"] for elem in shape[\"elements\"])\n }\n\n shapes.extend(track_shapes.values())\n return shapes", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def find_app_by_string(module, app_name):\n \"\"\"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n \"\"\"\n from . import Flask\n\n # Parse app_name as a single expression to determine if it's a valid\n # attribute name or function call.\n try:\n expr = ast.parse(app_name.strip(), mode=\"eval\").body\n except SyntaxError:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n ) from None\n\n if isinstance(expr, ast.Name):\n name = expr.id\n args = []\n kwargs = {}\n elif isinstance(expr, ast.Call):\n # Ensure the function name is an attribute name only.\n if not isinstance(expr.func, ast.Name):\n raise NoAppException(\n f\"Function reference must be a simple name: {app_name!r}.\"\n )\n\n name = expr.func.id\n\n # Parse the positional and keyword arguments as literals.\n try:\n args = [ast.literal_eval(arg) for arg in expr.args]\n kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}\n except ValueError:\n # literal_eval gives cryptic error messages, show a generic\n # message with the full expression instead.\n raise NoAppException(\n f\"Failed to parse arguments as literal values: {app_name!r}.\"\n ) from None\n else:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n try:\n attr = getattr(module, name)\n except AttributeError as e:\n raise NoAppException(\n f\"Failed to find attribute {name!r} in {module.__name__!r}.\"\n ) from e\n\n # If the attribute is a function, call it with any args and kwargs\n # to get the real application.\n if inspect.isfunction(attr):\n try:\n app = attr(*args, **kwargs)\n except TypeError as e:\n if not _called_with_wrong_args(attr):\n raise\n\n raise NoAppException(\n f\"The factory {app_name!r} in module\"\n f\" {module.__name__!r} could not be called with the\"\n \" specified arguments.\"\n ) from e\n else:\n app = attr\n\n if isinstance(app, Flask):\n return app\n\n raise NoAppException(\n \"A valid Flask application was not obtained from\"\n f\" '{module.__name__}:{app_name}'.\"\n )", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def update_status(group: Group, status_change: StatusChangeMessageData) -> None:\n new_status = status_change[\"new_status\"]\n new_substatus = status_change[\"new_substatus\"]\n\n if group.status == new_status and group.substatus == new_substatus:\n return\n\n log_extra = {\n \"project_id\": status_change[\"project_id\"],\n \"fingerprint\": status_change[\"fingerprint\"],\n \"new_status\": new_status,\n \"new_substatus\": new_substatus,\n }\n\n # Validate the provided status and substatus - we only allow setting a substatus for unresolved or ignored groups.\n if new_status in [GroupStatus.UNRESOLVED, GroupStatus.IGNORED]:\n if new_substatus is None:\n logger.error(\n \"group.update_status.missing_substatus\",\n extra={**log_extra},\n )\n return\n else:\n if new_substatus is not None:\n logger.error(\n \"group.update_status.unexpected_substatus\",\n extra={**log_extra},\n )\n return\n\n if new_status == GroupStatus.RESOLVED:\n Group.objects.update_group_status(\n groups=[group],\n status=new_status,\n substatus=new_substatus,\n activity_type=ActivityType.SET_RESOLVED,\n )\n elif new_status == GroupStatus.IGNORED:\n # The IGNORED status supports 3 substatuses. For UNTIL_ESCALATING and\n # UNTIL_CONDITION_MET, we expect the caller to monitor the conditions/escalating\n # logic and call the API with the new status when the conditions change.\n if new_substatus not in IGNORED_SUBSTATUS_CHOICES:\n logger.error(\n \"group.update_status.invalid_substatus\",\n extra={**log_extra},\n )\n return\n\n Group.objects.update_group_status(\n groups=[group],\n status=new_status,\n substatus=new_substatus,\n activity_type=ActivityType.SET_IGNORED,\n )\n elif new_status == GroupStatus.UNRESOLVED and new_substatus == GroupSubStatus.ESCALATING:\n manage_issue_states(group=group, group_inbox_reason=GroupInboxReason.ESCALATING)\n elif new_status == GroupStatus.UNRESOLVED:\n activity_type = None\n if new_substatus == GroupSubStatus.REGRESSED:\n activity_type = ActivityType.SET_REGRESSION\n elif new_substatus == GroupSubStatus.ONGOING:\n if group.substatus == GroupSubStatus.ESCALATING:\n # If the group was previously escalating, update the priority via AUTO_SET_ONGOING\n activity_type = ActivityType.AUTO_SET_ONGOING\n else:\n activity_type = ActivityType.SET_UNRESOLVED\n\n # We don't support setting the UNRESOLVED status with substatus NEW as it\n # is automatically set on creation. All other issues should be set to ONGOING.\n if activity_type is None:\n logger.error(\n \"group.update_status.invalid_substatus\",\n extra={**log_extra},\n )\n return\n\n Group.objects.update_group_status(\n groups=[group],\n status=new_status,\n substatus=new_substatus,\n activity_type=activity_type,\n from_substatus=group.substatus,\n )\n else:\n logger.error(\n \"group.update_status.unsupported_status\",\n extra={**log_extra},\n )\n raise NotImplementedError(\n f\"Unsupported status: {status_change['new_status']} {status_change['new_substatus']}\"\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _resolve_dist(\n self, req, best, replace_conflicting, env, installer, required_by, to_activate\n ):\n dist = best.get(req.key)\n if dist is None:\n # Find the best distribution and add it to the map\n dist = self.by_key.get(req.key)\n if dist is None or (dist not in req and replace_conflicting):\n ws = self\n if env is None:\n if dist is None:\n env = Environment(self.entries)\n else:\n # Use an empty environment and workingset to avoid\n # any further conflicts with the conflicting\n # distribution\n env = Environment([])\n ws = WorkingSet([])\n dist = best[req.key] = env.best_match(\n req, ws, installer, replace_conflicting=replace_conflicting\n )\n if dist is None:\n requirers = required_by.get(req, None)\n raise DistributionNotFound(req, requirers)\n to_activate.append(dist)\n if dist not in req:\n # Oops, the \"best\" so far conflicts with a dependency\n dependent_req = required_by[req]\n raise VersionConflict(dist, req).with_context(dependent_req)\n return dist", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def setMode(self, value):\n\t\tif exists(\"/proc/stb/lcd/show_symbols\"):\n\t\t\tprint(\"[Lcd] setLCDMode='%s'.\" % value)\n\t\t\tfileWriteLine(\"/proc/stb/lcd/show_symbols\", value)\n\t\tif value == \"0\":\n\t\t\tBoxInfo.setItem(\"SeekStatePlay\", False)\n\t\t\tBoxInfo.setItem(\"StatePlayPause\", False)\n\t\t\tif exists(\"/proc/stb/lcd/symbol_hdd\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_hdd\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_hddprogress\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_hddprogress\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_network\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_network\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_signal\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_signal\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_timeshift\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_timeshift\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_tv\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_tv\", \"0\")\n\t\t\tif exists(\"/proc/stb/lcd/symbol_usb\"):\n\t\t\t\tfileWriteLine(\"/proc/stb/lcd/symbol_usb\", \"0\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def keySave(self, result=None):\n\t\tfor callback in onPowerTimerSave:\n\t\t\tcallback(self)\n\t\tif not self.timerSetEndTime.value:\n\t\t\tself.timerEndTime.value = self.timerStartTime.value\n\t\tnow = int(time())\n\t\tself.timer.resetRepeated()\n\t\tself.timer.timerType = POWERTIMER_VALUES.get(self.timerType.value, POWER_TIMERTYPE.WAKEUP)\n\t\tself.timer.afterEvent = POWERTIMER_AFTER_VALUES.get(self.timerAfterEvent.value, POWER_AFTEREVENT.NONE)\n\t\tif self.timerRepeat.value == \"once\":\n\t\t\tdate = self.timerRepeatStartDate.value\n\t\t\tstartTime = self.timerStartTime.value\n\t\t\tbegin = self.getTimeStamp(date, startTime)\n\t\t\tendTime = self.timerEndTime.value\n\t\t\tend = self.getTimeStamp(date, endTime)\n\t\t\tif end < begin: # If end is less than start then add 1 day to the end time.\n\t\t\t\tend += 86400\n\t\t\tself.timer.begin = begin\n\t\t\tself.timer.end = end\n\t\tif self.timerType.value in (\"autostandby\", \"autodeepstandby\"):\n\t\t\tself.timer.begin = now + 10\n\t\t\tself.timer.end = self.timer.begin\n\t\t\tself.timer.autosleepinstandbyonly = self.timerActiveInStandby.value\n\t\t\tself.timer.autosleepdelay = self.timerSleepDelay.value\n\t\t\tself.timer.autosleeprepeat = self.timerAutoSleepRepeat.value\n\t\t\tif self.timerRepeat.value == \"repeated\": # Ensure that the timer repeated is cleared if we have an \"autosleeprepeat\".\n\t\t\t\tself.timer.resetRepeated()\n\t\t\t\tself.timerRepeat.value = \"once\" # Stop it being set again.\n\t\t\tself.timer.autosleepwindow = self.timerSleepWindow.value\n\t\t\tif self.timerSleepWindow.value:\n\t\t\t\tself.timer.autosleepbegin = self.getTimeStamp(now, self.timerSleepStart.value)\n\t\t\t\tself.timer.autosleepend = self.getTimeStamp(now, self.timerSleepEnd.value)\n\t\tif self.timerRepeat.value == \"repeated\":\n\t\t\tif self.timerRepeatPeriod.value == \"daily\":\n\t\t\t\tfor day in (0, 1, 2, 3, 4, 5, 6):\n\t\t\t\t\tself.timer.setRepeated(day)\n\t\t\telif self.timerRepeatPeriod.value == \"weekly\":\n\t\t\t\tself.timer.setRepeated(self.timerWeekday.index)\n\t\t\telif self.timerRepeatPeriod.value == \"weekdays\":\n\t\t\t\tfor day in (0, 1, 2, 3, 4):\n\t\t\t\t\tself.timer.setRepeated(day)\n\t\t\telif self.timerRepeatPeriod.value == \"weekends\":\n\t\t\t\tfor day in (5, 6):\n\t\t\t\t\tself.timer.setRepeated(day)\n\t\t\telif self.timerRepeatPeriod.value == \"user\":\n\t\t\t\tfor day in (0, 1, 2, 3, 4, 5, 6):\n\t\t\t\t\tif self.timerDay[DAY_LIST[day]].value:\n\t\t\t\t\t\tself.timer.setRepeated(day)\n\t\t\tself.timer.repeatedbegindate = self.getTimeStamp(self.timerRepeatStartDate.value, self.timerStartTime.value)\n\t\t\tif self.timer.repeated:\n\t\t\t\tself.timer.begin = self.getTimeStamp(self.timerRepeatStartDate.value, self.timerStartTime.value)\n\t\t\t\tself.timer.end = self.getTimeStamp(self.timerRepeatStartDate.value, self.timerEndTime.value)\n\t\t\telse:\n\t\t\t\tself.timer.begin = self.getTimeStamp(now, self.timerStartTime.value)\n\t\t\t\tself.timer.end = self.getTimeStamp(now, self.timerEndTime.value)\n\t\t\tif self.timer.end < self.timer.begin: # If end is less than start then add 1 day to the end time.\n\t\t\t\tself.timer.end += 86400\n\t\tself.timer.nettraffic = self.timerNetTraffic.value\n\t\tself.timer.trafficlimit = self.timerNetTrafficLimit.value\n\t\tself.timer.netip = self.timerNetIP.value\n\t\tipAdresses = []\n\t\tfor i in range(self.timerNetIPCount.value):\n\t\t\tipAdresses.append(\".\".join(\"%d\" % d for d in self.timerIPAddress[i].value))\n\t\tself.timer.ipadress = \",\".join(ipAdresses)\n\n\t\tself.session.nav.PowerTimer.saveTimers()\n\t\tfor notifier in self.onSave:\n\t\t\tnotifier()\n\t\tself.close((True, self.timer))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def filter_ooi_tree_item(ooi_node, show_types, hide_types, self_excluded_from_filter=False):\n def include_type(ooi_type):\n # hiding type takes precedence over showing type\n if hide_types and ooi_type in hide_types:\n return False\n\n if show_types:\n return ooi_type in show_types\n\n return True\n\n children = []\n\n if \"children\" in ooi_node:\n for child_ooi_node in ooi_node.get(\"children\", []):\n children.extend(filter_ooi_tree_item(child_ooi_node, show_types, hide_types))\n\n # no duplicates\n child_ids = set()\n ooi_node[\"children\"] = []\n for child in children:\n if child.get(\"id\") not in child_ids and child.get(\"id\") != ooi_node[\"id\"]:\n child_ids.add(child.get(\"id\"))\n ooi_node[\"children\"].append(child)\n\n if not self_excluded_from_filter and not include_type(ooi_node[\"ooi_type\"]):\n return children\n\n return [ooi_node]", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def _create_win(self):\n lookuperror = None\n keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts'),\n (_winreg.HKEY_CURRENT_USER, r'Software\\Microsoft\\Windows\\CurrentVersion\\Fonts'),\n (_winreg.HKEY_LOCAL_MACHINE, r'Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts'),\n (_winreg.HKEY_LOCAL_MACHINE, r'Software\\Microsoft\\Windows\\CurrentVersion\\Fonts') ]\n for keyname in keynames:\n try:\n key = _winreg.OpenKey(*keyname)\n try:\n path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)\n self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)\n for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):\n path = self._lookup_win(key, self.font_name, STYLES[style])\n if path:\n self.fonts[style] = ImageFont.truetype(path, self.font_size)\n else:\n if style == 'BOLDITALIC':\n self.fonts[style] = self.fonts['BOLD']\n else:\n self.fonts[style] = self.fonts['NORMAL']\n return\n except FontNotFound as err:\n lookuperror = err\n finally:\n _winreg.CloseKey(key)\n except OSError:\n pass\n else:\n # If we get here, we checked all registry keys and had no luck\n # We can be in one of two situations now:\n # * All key lookups failed. In this case lookuperror is None and we\n # will raise a generic error\n # * At least one lookup failed with a FontNotFound error. In this\n # case, we will raise that as a more specific error\n if lookuperror:\n raise lookuperror\n raise FontNotFound('Can\\'t open Windows font registry key')", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def update_local_templates(channel, templates_data, unique=False):\n channel_namespace = channel.config.get(\"fb_namespace\", \"\")\n # run through all our templates making sure they are present in our DB\n seen = []\n for template in templates_data:\n template_status = template[\"status\"]\n\n template_status = template_status.upper()\n # if this is a status we don't know about\n if template_status not in STATUS_MAPPING:\n continue\n\n status = STATUS_MAPPING[template_status]\n\n content_parts = []\n\n all_supported = True\n for component in template[\"components\"]:\n if component[\"type\"] not in [\"HEADER\", \"BODY\", \"FOOTER\"]:\n continue\n\n if \"text\" not in component:\n continue\n\n if component[\"type\"] in [\"HEADER\", \"FOOTER\"] and _calculate_variable_count(component[\"text\"]):\n all_supported = False\n\n content_parts.append(component[\"text\"])\n\n if not content_parts or not all_supported:\n continue\n\n content = \"\\n\\n\".join(content_parts)\n variable_count = _calculate_variable_count(content)\n\n language, country = LANGUAGE_MAPPING.get(template[\"language\"], (None, None))\n\n # its a (non fatal) error if we see a language we don't know\n if language is None:\n status = TemplateTranslation.STATUS_UNSUPPORTED_LANGUAGE\n language = template[\"language\"]\n\n missing_external_id = f\"{template['language']}/{template['name']}\"\n translation = TemplateTranslation.get_or_create(\n channel=channel,\n name=template[\"name\"],\n language=language,\n country=country,\n content=content,\n variable_count=variable_count,\n status=status,\n external_id=template.get(\"id\", missing_external_id),\n namespace=template.get(\"namespace\", channel_namespace),\n category=template[\"category\"],\n )\n\n for component in template[\"components\"]:\n if component[\"type\"] == \"HEADER\":\n TemplateHeader.objects.get_or_create(\n translation=translation, type=component.get(\"format\"), text=component.get(\"text\", None)\n )\n\n if component[\"type\"] == \"BUTTONS\":\n for button in component.get(\"buttons\"):\n TemplateButton.objects.get_or_create(\n translation=translation,\n type=button.get(\"type\"),\n url=button.get(\"url\", None),\n text=button.get(\"text\", None),\n phone_number=button.get(\"phone_number\", None),\n )\n\n seen.append(translation)\n\n if not unique:\n # trim any translations we didn't see\n TemplateTranslation.trim(channel, seen)\n Template.trim(channel)", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n \"\"\"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n A dictionary that will be jsonify'd before being returned.\n\n ``list``\n A list that will be jsonify'd before being returned.\n\n ``generator`` or ``iterator``\n A generator that returns ``str`` or ``bytes`` to be\n streamed as the response.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n ``headers`` is a dictionary or a list of ``(key, value)``\n tuples. If ``body`` is a :attr:`response_class` instance,\n ``status`` overwrites the exiting value and ``headers`` are\n extended.\n\n :attr:`response_class`\n The object is returned unchanged.\n\n other :class:`~werkzeug.wrappers.Response` class\n The object is coerced to :attr:`response_class`.\n\n :func:`callable`\n The function is called as a WSGI application. The result is\n used to create a response object.\n\n .. versionchanged:: 2.2\n A generator will be converted to a streaming response.\n A list will be converted to a JSON response.\n\n .. versionchanged:: 1.1\n A dict will be converted to a JSON response.\n\n .. versionchanged:: 0.9\n Previously a tuple was interpreted as the arguments for the\n response object.\n \"\"\"\n\n status = headers = None\n\n # unpack tuple returns\n if isinstance(rv, tuple):\n len_rv = len(rv)\n\n # a 3-tuple is unpacked directly\n if len_rv == 3:\n rv, status, headers = rv # type: ignore[misc]\n # decide if a 2-tuple has status or headers\n elif len_rv == 2:\n if isinstance(rv[1], (Headers, dict, tuple, list)):\n rv, headers = rv\n else:\n rv, status = rv # type: ignore[assignment,misc]\n # other sized tuples are not allowed\n else:\n raise TypeError(\n \"The view function did not return a valid response tuple.\"\n \" The tuple must have the form (body, status, headers),\"\n \" (body, status), or (body, headers).\"\n )\n\n # the body must not be None\n if rv is None:\n raise TypeError(\n f\"The view function for {request.endpoint!r} did not\"\n \" return a valid response. The function either returned\"\n \" None or ended without a return statement.\"\n )\n\n # make sure the body is an instance of the response class\n if not isinstance(rv, self.response_class):\n if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):\n # let the response class set the status and headers instead of\n # waiting to do it manually, so that the class can handle any\n # special logic\n rv = self.response_class(\n rv,\n status=status,\n headers=headers, # type: ignore[arg-type]\n )\n status = headers = None\n elif isinstance(rv, (dict, list)):\n rv = self.json.response(rv)\n elif isinstance(rv, BaseResponse) or callable(rv):\n # evaluate a WSGI callable, or coerce a different response\n # class to the correct type\n try:\n rv = self.response_class.force_type(\n rv, # type: ignore[arg-type]\n request.environ,\n )\n except TypeError as e:\n raise TypeError(\n f\"{e}\\nThe view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, list, tuple with headers or status,\"\n \" Response instance, or WSGI callable, but it\"\n f\" was a {type(rv).__name__}.\"\n ).with_traceback(sys.exc_info()[2]) from None\n else:\n raise TypeError(\n \"The view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, list, tuple with headers or status,\"\n \" Response instance, or WSGI callable, but it was a\"\n f\" {type(rv).__name__}.\"\n )\n\n rv = t.cast(Response, rv)\n # prefer the status if it was provided\n if status is not None:\n if isinstance(status, (str, bytes, bytearray)):\n rv.status = status\n else:\n rv.status_code = status\n\n # extend existing headers with provided headers\n if headers:\n rv.headers.update(headers) # type: ignore[arg-type]\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,\n inTestPoint, inFov = 30.0):\n \"\"\"finds point X which is along the inNormCameraDir vector starting from\n point inFocalPoint, such that inTestPoint is visible. This is\n accomplished by taking a parametric value ss to move the camera position\n out from the focal point (along the inNormCameraDir vector) and finding\n the parametric value such that the angle between the vector from the\n camera position to the focal point and the camera position to inTestPoint\n is equal to (or greater than) the camera field of view. The parametric\n value is returned. We use the law of sines. assumes inNormCameraDir\n is normalized and pointing in the direction from inFocalPoint towards\n where we want to place the camera (the opposite of the look direction)\"\"\"\n\n #angle between camera-to-focal point vector and camera-to-testpoint vector\n #is equal to half the camera fOV. Call this angle AA. \n #The side opposite this angle has length equal to the distance between\n #the focal point and the test point. Call this distance aa. We also\n #know the angle between the focal point-to-camera vector and the focal\n #point-to-testpoint vector (because both vectors point in a fixed direction).\n #call this angle BB. The remaining angle is CC, and CC = 180 - (AA + BB).\n #thus the length of the parametric side is determined by the law of sines,\n #cc/sin(CC) = aa/sin(AA) (cc is the length of interest),\n #so cc = aa * sin(CC) / sin(AA)\n #\n\n #need to set to 1/2 fov\n if PhactoriDbg(100):\n myDebugPrint3(\"CalcRelativeCameraDistance2_AA entered\\n\");\n if PhactoriDbg(100):\n myDebugPrint3(\"inTestPoint: \" + str(inTestPoint) + \"\\n\");\n angleAA = math.radians(inFov * 0.5)\n if PhactoriDbg(100):\n myDebugPrint3(\"angleAA: \" + str(math.degrees(angleAA)) + \"\\n\");\n\n focalToTestVec = [inTestPoint[0] - inFocalPoint[0],\n inTestPoint[1] - inFocalPoint[1],\n inTestPoint[2] - inFocalPoint[2]]\n aa = vecMagnitude(focalToTestVec)\n if aa == 0.0:\n return 0.0\n focalToTestVec[0] /= aa\n focalToTestVec[1] /= aa\n focalToTestVec[2] /= aa\n if PhactoriDbg(100):\n myDebugPrint3(\"inNormCameraDir: \" + str(inNormCameraDir) + \"\\n\");\n if PhactoriDbg(100):\n myDebugPrint3(\"focalToTestVec: \" + str(focalToTestVec) + \"\\n\");\n cosAngleBB = vecDotProduct(inNormCameraDir, focalToTestVec)\n if PhactoriDbg(100):\n myDebugPrint3(\"cosAngleBB: \" + str(cosAngleBB) + \"\\n\");\n if cosAngleBB >= 1.0:\n #camera-to-test-point in line with camera-to-focal-point\n #and already in camera view\n if PhactoriDbg(100):\n myDebugPrint3(\"cosAngleBB >= 1.0 cc is 0.0\\n\");\n cc = 0.0\n return cc\n elif cosAngleBB <= -1.0:\n #camera-to-test-point in line with camera-to-focal-point\n #with camera needing movement back to test point\n if PhactoriDbg(100):\n myDebugPrint3(\"cosAngleBB <= -1.0, cc is camera to test point dist\\n\");\n cc = aa\n return cc\n angleBB = math.acos(cosAngleBB)\n if PhactoriDbg(100):\n myDebugPrint3(\"angleBB: \" + str(math.degrees(angleBB)) + \"\\n\");\n angleCC = math.pi - (angleAA + angleBB)\n if PhactoriDbg(100):\n myDebugPrint3(\"angleCC: \" + str(math.degrees(angleCC)) + \"\\n\");\n cc = aa * math.sin(angleCC) / math.sin(angleAA)\n if PhactoriDbg(100):\n myDebugPrint3(\"cc: \" + str(cc) + \"\\n\");\n if PhactoriDbg(100):\n myDebugPrint3(\"CalcRelativeCameraDistance2_AA returning\\n\");\n return cc", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "@classmethod\n def _auto_mappings(cls, org: Org, headers: list[str]) -> list:\n \"\"\"\n Automatic mappings for the given list of headers - users can customize these later\n \"\"\"\n\n fields_by_key = {}\n fields_by_label = {}\n for f in org.contactfields(manager=\"user_fields\").filter(is_active=True):\n fields_by_key[f.key] = f\n fields_by_label[f.label.lower()] = f\n\n mappings = []\n\n for header in headers:\n header_prefix, header_name = cls._parse_header(header)\n mapping = ContactImport.MAPPING_IGNORE\n\n if header_prefix == \"\":\n attribute = header_name.lower()\n attribute = attribute.removeprefix(\"contact \") # header \"Contact UUID\" -> uuid etc\n\n if attribute in (\"uuid\", \"name\", \"language\"):\n mapping = {\"type\": \"attribute\", \"name\": attribute}\n elif header_prefix == \"urn\" and header_name:\n mapping = {\"type\": \"scheme\", \"scheme\": header_name.lower()}\n elif header_prefix == \"field\" and header_name:\n field_key = ContactField.make_key(header_name)\n\n # try to match by field label, then by key\n field = fields_by_label.get(header_name.lower())\n if not field:\n field = fields_by_key.get(field_key)\n\n if field:\n mapping = {\"type\": \"field\", \"key\": field.key, \"name\": field.label}\n else:\n # can be created or selected in next step\n mapping = {\"type\": \"new_field\", \"key\": field_key, \"name\": header_name, \"value_type\": \"T\"}\n\n mappings.append({\"header\": header, \"mapping\": mapping})\n\n cls._validate_mappings(mappings)\n return mappings", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def get_path(data: PathSearchable, *path, should_log=False, **kwargs):\n \"\"\"\n Safely resolves data from a recursive data structure. A value is only\n returned if the full path exists, otherwise ``None`` is returned.\n\n If the ``default`` argument is specified, it is returned instead of ``None``.\n\n If the ``filter`` argument is specified and the value is a list, it is\n filtered with the given callback. Alternatively, pass ``True`` as filter to\n only filter ``None`` values.\n \"\"\"\n logger = logging.getLogger(__name__)\n default = kwargs.pop(\"default\", None)\n f: bool | None = kwargs.pop(\"filter\", None)\n for k in kwargs:\n raise TypeError(\"get_path() got an undefined keyword argument '%s'\" % k)\n\n logger_data = {}\n if should_log:\n logger_data = {\n \"path_searchable\": json.dumps(data),\n \"path_arg\": json.dumps(path),\n }\n\n for p in path:\n if isinstance(data, Mapping) and p in data:\n data = data[p]\n elif isinstance(data, (list, tuple)) and isinstance(p, int) and -len(data) <= p < len(data):\n data = data[p]\n else:\n if should_log:\n logger_data[\"invalid_path\"] = json.dumps(p)\n logger.info(\"sentry.safe.get_path.invalid_path_section\", extra=logger_data)\n return default\n\n if should_log:\n if data is None:\n logger.info(\"sentry.safe.get_path.iterated_path_is_none\", extra=logger_data)\n else:\n logger_data[\"iterated_path\"] = json.dumps(data)\n\n if f and data and isinstance(data, (list, tuple)):\n data = list(filter((lambda x: x is not None) if f is True else f, data))\n if should_log and len(data) == 0 and \"iterated_path\" in logger_data:\n logger.info(\"sentry.safe.get_path.filtered_path_is_none\", extra=logger_data)\n\n return data if data is not None else default", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _get_metrics_query_from_on_demand_spec(\n self,\n spec: OnDemandMetricSpec,\n require_time_range: bool = True,\n groupby: Sequence[MetricGroupByField] | None = None,\n orderby: Sequence[MetricOrderByField] | None = None,\n # Where normally isn't accepted for on-demand since it should only encoded into the metric\n # but in the case of top events, etc. there is need for another where condition dynamically for top N groups.\n additional_where: Sequence[Condition] | None = None,\n ) -> DeprecatingMetricsQuery:\n if self.params.organization is None:\n raise InvalidSearchQuery(\"An on demand metrics query requires an organization\")\n\n if len(self.selected_columns) == 0:\n raise InvalidSearchQuery(\n \"An on demand metrics query requires at least one selected column\"\n )\n\n max_limit = None\n if isinstance(self, TopMetricsQueryBuilder):\n limit = self.limit or Limit(1)\n # Top N events passes a limit of 10000 by default. That's also the upper bound for metrics layer, so\n # we need to reduce the interval.\n intervals_len = get_num_intervals(\n start=self.start,\n end=self.end,\n granularity=self.granularity,\n interval=self.interval,\n )\n if intervals_len > 0:\n limit = Limit(int(limit.limit / intervals_len))\n max_limit = 10_000\n include_series = True\n interval = self.interval\n elif isinstance(self, TimeseriesMetricQueryBuilder):\n limit = Limit(1)\n include_series = True\n interval = self.interval\n elif isinstance(self, AlertMetricsQueryBuilder):\n limit = self.limit or Limit(1)\n include_series = False\n interval = None\n else:\n limit = self.limit or Limit(1)\n include_series = False\n interval = None\n\n # Since the query builder is very convoluted, we first try to get the start and end from the validated\n # parameters but in case it's none it can be that the `skip_time_conditions` was True, thus in that case we\n # try to see if start and end were supplied directly in the constructor.\n start = self.start or self.params.start\n end = self.end or self.params.end\n\n # The time range can be required or not, since the query generated by the builder can either be used to execute\n # the query on its own (requiring a time range) or it can be used to get the snql code necessary to create a\n # query subscription from the outside.\n if require_time_range and (start is None or end is None):\n raise InvalidSearchQuery(\n \"The on demand metric query requires a time range to be executed\"\n )\n\n where = [\n Condition(\n lhs=Column(QUERY_HASH_KEY),\n op=Op.EQ,\n rhs=spec.query_hash,\n ),\n ]\n\n if spec.spec_type == MetricSpecType.DYNAMIC_QUERY and spec.environment:\n where.append(Condition(lhs=Column(\"environment\"), op=Op.EQ, rhs=spec.environment))\n\n if additional_where:\n where.extend(additional_where)\n\n return DeprecatingMetricsQuery(\n select=[self.convert_spec_to_metric_field(spec)],\n where=where,\n limit=limit,\n max_limit=max_limit,\n offset=self.offset,\n granularity=self.granularity,\n interval=interval,\n is_alerts_query=True,\n org_id=self.params.organization.id,\n project_ids=[p.id for p in self.params.projects],\n include_series=include_series,\n orderby=orderby,\n groupby=groupby,\n start=start,\n end=end,\n skip_orderby_validation=True,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@pre_load\n def extract_info(self, data, **kwargs):\n \"\"\"Support deserialization of statuses according to DIF spec.\"\"\"\n if \"statuses\" in data:\n if \"active\" in data.get(\"statuses\"):\n if \"directive\" in data.get(\"statuses\").get(\"active\"):\n data[\"status_active\"] = data[\"statuses\"][\"active\"][\"directive\"]\n if \"suspended\" in data.get(\"statuses\"):\n if \"directive\" in data.get(\"statuses\").get(\"suspended\"):\n data[\"status_suspended\"] = data[\"statuses\"][\"suspended\"][\"directive\"]\n if \"revoked\" in data.get(\"statuses\"):\n if \"directive\" in data.get(\"statuses\").get(\"revoked\"):\n data[\"status_revoked\"] = data[\"statuses\"][\"revoked\"][\"directive\"]\n return data", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def add_error_info(self, info: ErrorInfo) -> None:\n file, lines = info.origin\n # process the stack of ErrorWatchers before modifying any internal state\n # in case we need to filter out the error entirely\n # NB: we need to do this both here and in _add_error_info, otherwise we\n # might incorrectly update the sets of ignored or only_once messages\n if self._filter_error(file, info):\n return\n if not info.blocker: # Blockers cannot be ignored\n if file in self.ignored_lines:\n # Check each line in this context for \"type: ignore\" comments.\n # line == end_line for most nodes, so we only loop once.\n for scope_line in lines:\n if self.is_ignored_error(scope_line, info, self.ignored_lines[file]):\n # Annotation requests us to ignore all errors on this line.\n self.used_ignored_lines[file][scope_line].append(\n (info.code or codes.MISC).code\n )\n return\n if file in self.ignored_files:\n return\n if info.only_once:\n if info.message in self.only_once_messages:\n return\n self.only_once_messages.add(info.message)\n if (\n self.seen_import_error\n and info.code not in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND)\n and self.has_many_errors()\n ):\n # Missing stubs can easily cause thousands of errors about\n # Any types, especially when upgrading to mypy 0.900,\n # which no longer bundles third-party library stubs. Avoid\n # showing too many errors to make it easier to see\n # import-related errors.\n info.hidden = True\n self.report_hidden_errors(info)\n self._add_error_info(file, info)\n ignored_codes = self.ignored_lines.get(file, {}).get(info.line, [])\n if ignored_codes and info.code:\n # Something is ignored on the line, but not this error, so maybe the error\n # code is incorrect.\n msg = f'Error code \"{info.code.code}\" not covered by \"type: ignore\" comment'\n if info.code in original_error_codes:\n # If there seems to be a \"type: ignore\" with a stale error\n # code, report a more specific note.\n old_code = original_error_codes[info.code].code\n if old_code in ignored_codes:\n msg = (\n f'Error code changed to {info.code.code}; \"type: ignore\" comment '\n + \"may be out of date\"\n )\n note = ErrorInfo(\n import_ctx=info.import_ctx,\n file=info.file,\n module=info.module,\n typ=info.type,\n function_or_member=info.function_or_member,\n line=info.line,\n column=info.column,\n end_line=info.end_line,\n end_column=info.end_column,\n severity=\"note\",\n message=msg,\n code=None,\n blocker=False,\n only_once=False,\n allow_dups=False,\n )\n self._add_error_info(file, note)\n if (\n self.options.show_error_code_links\n and not self.options.hide_error_codes\n and info.code is not None\n and info.code not in HIDE_LINK_CODES\n and info.code.code in mypy_error_codes\n ):\n message = f\"See {BASE_RTD_URL}-{info.code.code} for more info\"\n if message in self.only_once_messages:\n return\n self.only_once_messages.add(message)\n info = ErrorInfo(\n import_ctx=info.import_ctx,\n file=info.file,\n module=info.module,\n typ=info.type,\n function_or_member=info.function_or_member,\n line=info.line,\n column=info.column,\n end_line=info.end_line,\n end_column=info.end_column,\n severity=\"note\",\n message=message,\n code=info.code,\n blocker=False,\n only_once=True,\n allow_dups=False,\n priority=20,\n )\n self._add_error_info(file, info)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get(self, request: Request, project: Project) -> Response:\n \"\"\"\n List a Project's Debug Information Files\n ````````````````````````````````````````\n\n Retrieve a list of debug information files for a given project.\n\n :pparam string organization_id_or_slug: the id or slug of the organization the\n file belongs to.\n :pparam string project_id_or_slug: the id or slug of the project to list the\n DIFs of.\n :qparam string query: If set, this parameter is used to locate DIFs with.\n :qparam string id: If set, the specified DIF will be sent in the response.\n :qparam string file_formats: If set, only DIFs with these formats will be returned.\n :auth: required\n \"\"\"\n download_requested = request.GET.get(\"id\") is not None\n if download_requested and has_download_permission(request, project):\n return self.download(request.GET.get(\"id\"), project)\n elif download_requested:\n return Response(status=403)\n\n code_id = request.GET.get(\"code_id\")\n debug_id = request.GET.get(\"debug_id\")\n query = request.GET.get(\"query\")\n file_formats = request.GET.getlist(\"file_formats\")\n\n # If this query contains a debug identifier, normalize it to allow for\n # more lenient queries (e.g. supporting Breakpad ids). Use the index to\n # speed up such queries.\n if query and len(query) <= 45 and not debug_id:\n try:\n debug_id = normalize_debug_id(query.strip())\n except SymbolicError:\n pass\n\n if debug_id:\n # If a debug ID is specified, do not consider the stored code\n # identifier and strictly filter by debug identifier. Often there\n # are mismatches in the code identifier in PEs.\n q = Q(debug_id__exact=debug_id)\n elif code_id:\n q = Q(code_id__exact=code_id)\n elif query:\n q = (\n Q(object_name__icontains=query)\n | Q(debug_id__icontains=query)\n | Q(code_id__icontains=query)\n | Q(cpu_name__icontains=query)\n | Q(file__headers__icontains=query)\n )\n\n known_file_format = DIF_MIMETYPES.get(query)\n if known_file_format:\n q |= Q(file__headers__icontains=known_file_format)\n else:\n q = Q()\n\n if file_formats:\n file_format_q = Q()\n for file_format in file_formats:\n known_file_format = DIF_MIMETYPES.get(file_format)\n if known_file_format:\n file_format_q |= Q(file__headers__icontains=known_file_format)\n q &= file_format_q\n\n q &= Q(project_id=project.id)\n queryset = ProjectDebugFile.objects.filter(q).select_related(\"file\")\n\n def on_results(difs: Sequence[ProjectDebugFile]):\n # NOTE: we are only refreshing files if there is direct query for specific files\n if debug_id and not query and not file_formats:\n maybe_renew_debug_files(q, difs)\n\n return serialize(difs, request.user)\n\n return self.paginate(\n request=request,\n queryset=queryset,\n order_by=\"-id\",\n paginator_cls=OffsetPaginator,\n default_per_page=20,\n on_results=on_results,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def as_string(self):\n \"\"\"Return a string of the file contents.\"\"\"\n items = {\n \"replaces_str\": \"\",\n \"initial_str\": \"\",\n }\n\n imports = set()\n\n # Deconstruct operations\n operations = []\n for operation in self.migration.operations:\n operation_string, operation_imports = OperationWriter(operation).serialize()\n imports.update(operation_imports)\n operations.append(operation_string)\n items[\"operations\"] = \"\\n\".join(operations) + \"\\n\" if operations else \"\"\n\n # Format dependencies and write out swappable dependencies right\n dependencies = []\n for dependency in self.migration.dependencies:\n if dependency[0] == \"__setting__\":\n dependencies.append(\n \" migrations.swappable_dependency(settings.%s),\"\n % dependency[1]\n )\n imports.add(\"from django.conf import settings\")\n else:\n dependencies.append(\" %s,\" % self.serialize(dependency)[0])\n items[\"dependencies\"] = (\n \"\\n\".join(sorted(dependencies)) + \"\\n\" if dependencies else \"\"\n )\n\n # Format imports nicely, swapping imports of functions from migration files\n # for comments\n migration_imports = set()\n for line in list(imports):\n if re.match(r\"^import (.*)\\.\\d+[^\\s]*$\", line):\n migration_imports.add(line.split(\"import\")[1].strip())\n imports.remove(line)\n self.needs_manual_porting = True\n\n # django.db.migrations is always used, but models import may not be.\n # If models import exists, merge it with migrations import.\n if \"from django.db import models\" in imports:\n imports.discard(\"from django.db import models\")\n imports.add(\"from django.db import migrations, models\")\n else:\n imports.add(\"from django.db import migrations\")\n\n # Sort imports by the package / module to be imported (the part after\n # \"from\" in \"from ... import ...\" or after \"import\" in \"import ...\").\n # First group the \"import\" statements, then \"from ... import ...\".\n sorted_imports = sorted(\n imports, key=lambda i: (i.split()[0] == \"from\", i.split()[1])\n )\n items[\"imports\"] = \"\\n\".join(sorted_imports) + \"\\n\" if imports else \"\"\n if migration_imports:\n items[\"imports\"] += (\n \"\\n\\n# Functions from the following migrations need manual \"\n \"copying.\\n# Move them and any dependencies into this file, \"\n \"then update the\\n# RunPython operations to refer to the local \"\n \"versions:\\n# %s\"\n ) % \"\\n# \".join(sorted(migration_imports))\n # If there's a replaces, make a string for it\n if self.migration.replaces:\n items[\"replaces_str\"] = (\n \"\\n replaces = %s\\n\" % self.serialize(self.migration.replaces)[0]\n )\n # Hinting that goes into comment\n if self.include_header:\n items[\"migration_header\"] = MIGRATION_HEADER_TEMPLATE % {\n \"version\": get_version(),\n \"timestamp\": now().strftime(\"%Y-%m-%d %H:%M\"),\n }\n else:\n items[\"migration_header\"] = \"\"\n\n if self.migration.initial:\n items[\"initial_str\"] = \"\\n initial = True\\n\"\n\n return MIGRATION_TEMPLATE % items", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_prefetch_querysets(self, instances, querysets=None):\n custom_queryset_dict = {}\n if querysets is not None:\n for queryset in querysets:\n ct_id = self.get_content_type(\n model=queryset.query.model, using=queryset.db\n ).pk\n if ct_id in custom_queryset_dict:\n raise ValueError(\n \"Only one queryset is allowed for each content type.\"\n )\n custom_queryset_dict[ct_id] = queryset\n\n # For efficiency, group the instances by content type and then do one\n # query per model\n fk_dict = defaultdict(set)\n # We need one instance for each group in order to get the right db:\n instance_dict = {}\n ct_attname = self.model._meta.get_field(self.ct_field).attname\n for instance in instances:\n # We avoid looking for values if either ct_id or fkey value is None\n ct_id = getattr(instance, ct_attname)\n if ct_id is not None:\n fk_val = getattr(instance, self.fk_field)\n if fk_val is not None:\n fk_dict[ct_id].add(fk_val)\n instance_dict[ct_id] = instance\n\n ret_val = []\n for ct_id, fkeys in fk_dict.items():\n if ct_id in custom_queryset_dict:\n # Return values from the custom queryset, if provided.\n ret_val.extend(custom_queryset_dict[ct_id].filter(pk__in=fkeys))\n else:\n instance = instance_dict[ct_id]\n ct = self.get_content_type(id=ct_id, using=instance._state.db)\n ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))\n\n # For doing the join in Python, we have to match both the FK val and the\n # content type, so we use a callable that returns a (fk, class) pair.\n def gfk_key(obj):\n ct_id = getattr(obj, ct_attname)\n if ct_id is None:\n return None\n else:\n model = self.get_content_type(\n id=ct_id, using=obj._state.db\n ).model_class()\n return (\n model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),\n model,\n )\n\n return (\n ret_val,\n lambda obj: (obj.pk, obj.__class__),\n gfk_key,\n True,\n self.name,\n False,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def prevService(self):\n\t\tif self.type == EPG_TYPE_ENHANCED or self.type == EPG_TYPE_INFOBAR:\n\t\t\tself.CurrBouquet = self.servicelist.getCurrentSelection()\n\t\t\tself.CurrService = self.servicelist.getRoot()\n\t\t\tself[\"list\"].instance.moveSelectionTo(0)\n\t\t\tif self.servicelist.inBouquet():\n\t\t\t\tprev = self.servicelist.getCurrentSelection()\n\t\t\t\tif prev:\n\t\t\t\t\tprev = prev.toString()\n\t\t\t\t\twhile True:\n\t\t\t\t\t\tif config.usage.quickzap_bouquet_change.value:\n\t\t\t\t\t\t\tif self.servicelist.atBegin():\n\t\t\t\t\t\t\t\tself.servicelist.prevBouquet()\n\t\t\t\t\t\tself.servicelist.moveUp()\n\t\t\t\t\t\tcur = self.servicelist.getCurrentSelection()\n\t\t\t\t\t\tif not cur or (not (cur.flags & 64)) or cur.toString() == prev:\n\t\t\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tself.servicelist.moveUp()\n\t\t\tif self.isPlayable():\n\t\t\t\tself.onCreate()\n\t\t\t\tif not self[\"list\"].getCurrent()[1] and config.epgselection.overjump.value:\n\t\t\t\t\tself.prevService()\n\t\t\telse:\n\t\t\t\tself.prevService()\n\t\telif self.type == EPG_TYPE_GRAPH or self.type == EPG_TYPE_INFOBARGRAPH:\n\t\t\tself.updEvent(-24)\n\t\telif self.serviceChangeCB:\n\t\t\tself.serviceChangeCB(-1, self)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@view_config(\n route_name=\"accounts.login\",\n renderer=\"accounts/login.html\",\n uses_session=True,\n require_csrf=True,\n require_methods=False,\n has_translations=True,\n)\ndef login(request, redirect_field_name=REDIRECT_FIELD_NAME, _form_class=LoginForm):\n # TODO: Logging in should reset request.user\n if request.user is not None:\n return HTTPSeeOther(request.route_path(\"manage.projects\"))\n\n user_service = request.find_service(IUserService, context=None)\n breach_service = request.find_service(IPasswordBreachedService, context=None)\n\n redirect_to = request.POST.get(\n redirect_field_name, request.GET.get(redirect_field_name)\n )\n\n form = _form_class(\n request.POST,\n request=request,\n user_service=user_service,\n breach_service=breach_service,\n check_password_metrics_tags=[\"method:auth\", \"auth_method:login_form\"],\n )\n\n if request.method == \"POST\":\n if form.validate():\n # Get the user id for the given username.\n username = form.username.data\n userid = user_service.find_userid(username)\n\n # If the user has enabled two-factor authentication and they do not have\n # a valid saved device.\n two_factor_required = user_service.has_two_factor(userid) and (\n not _check_remember_device_token(request, userid)\n )\n if two_factor_required:\n two_factor_data = {\"userid\": userid}\n if redirect_to:\n two_factor_data[\"redirect_to\"] = redirect_to\n\n token_service = request.find_service(ITokenService, name=\"two_factor\")\n token = token_service.dumps(two_factor_data)\n\n # Stuff our token in the query and redirect to two-factor page.\n resp = HTTPSeeOther(\n request.route_path(\"accounts.two-factor\", _query=token)\n )\n return resp\n else:\n # If the user-originating redirection url is not safe, then\n # redirect to the index instead.\n if not redirect_to or not is_safe_url(\n url=redirect_to, host=request.host\n ):\n redirect_to = request.route_path(\"manage.projects\")\n\n # Actually perform the login routine for our user.\n headers = _login_user(request, userid)\n\n # Now that we're logged in we'll want to redirect the user to\n # either where they were trying to go originally, or to the default\n # view.\n resp = HTTPSeeOther(redirect_to, headers=dict(headers))\n\n # We'll use this cookie so that client side javascript can\n # Determine the actual user ID (not username, user ID). This is\n # *not* a security sensitive context and it *MUST* not be used\n # where security matters.\n #\n # We'll also hash this value just to avoid leaking the actual User\n # IDs here, even though it really shouldn't matter.\n resp.set_cookie(\n USER_ID_INSECURE_COOKIE,\n hashlib.blake2b(\n str(userid).encode(\"ascii\"), person=b\"warehouse.userid\"\n )\n .hexdigest()\n .lower(),\n )\n\n return resp\n\n return {\n \"form\": form,\n \"redirect\": {\"field\": REDIRECT_FIELD_NAME, \"data\": redirect_to},\n }", "smellKey": "S3776", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "@extend_schema(\n operation_id=\"Get Debug Information Related to Source Maps for a Given Event\",\n parameters=[\n GlobalParams.ORG_ID_OR_SLUG,\n GlobalParams.PROJECT_ID_OR_SLUG,\n EventParams.EVENT_ID,\n ],\n request=None,\n responses={\n 200: inline_sentry_response_serializer(\"SourceMapDebug\", SourceMapDebugResponse),\n 401: RESPONSE_UNAUTHORIZED,\n 403: RESPONSE_FORBIDDEN,\n 404: RESPONSE_NOT_FOUND,\n },\n )\n def get(self, request: Request, project: Project, event_id: str) -> Response:\n \"\"\"\n Return a list of source map errors for a given event.\n \"\"\"\n\n event = eventstore.backend.get_event_by_id(project.id, event_id)\n if event is None:\n raise NotFound(detail=\"Event not found\")\n\n event_data = event.data\n\n release = None\n if event.release is not None:\n try:\n release = Release.objects.get(\n organization=project.organization, version=event.release\n )\n except Release.DoesNotExist:\n pass\n\n # get general information about what has been uploaded\n project_has_some_artifact_bundle = ArtifactBundle.objects.filter(\n projectartifactbundle__project_id=project.id,\n ).exists()\n has_uploaded_release_bundle_with_release = False\n has_uploaded_artifact_bundle_with_release = False\n if release is not None:\n has_uploaded_release_bundle_with_release = ReleaseFile.objects.filter(\n release_id=release.id\n ).exists()\n has_uploaded_artifact_bundle_with_release = ReleaseArtifactBundle.objects.filter(\n organization_id=project.organization_id, release_name=release.version\n ).exists()\n has_uploaded_some_artifact_with_a_debug_id = DebugIdArtifactBundle.objects.filter(\n organization_id=project.organization_id,\n artifact_bundle__projectartifactbundle__project_id=project.id,\n ).exists()\n\n debug_images = get_path(event_data, \"debug_meta\", \"images\")\n debug_images = debug_images if debug_images is not None else []\n\n # get information about which debug ids on the event have uploaded artifacts\n debug_ids = [\n debug_image[\"debug_id\"]\n for debug_image in debug_images\n if debug_image[\"type\"] == \"sourcemap\"\n ][0:100]\n debug_id_artifact_bundles = DebugIdArtifactBundle.objects.filter(\n artifact_bundle__projectartifactbundle__project_id=project.id,\n debug_id__in=debug_ids,\n )\n debug_ids_with_uploaded_source_file = set()\n debug_ids_with_uploaded_source_map = set()\n for debug_id_artifact_bundle in debug_id_artifact_bundles:\n if (\n SourceFileType(debug_id_artifact_bundle.source_file_type) == SourceFileType.SOURCE\n or SourceFileType(debug_id_artifact_bundle.source_file_type)\n == SourceFileType.MINIFIED_SOURCE\n ):\n debug_ids_with_uploaded_source_file.add(str(debug_id_artifact_bundle.debug_id))\n elif (\n SourceFileType(debug_id_artifact_bundle.source_file_type)\n == SourceFileType.SOURCE_MAP\n ):\n debug_ids_with_uploaded_source_map.add(str(debug_id_artifact_bundle.debug_id))\n\n # Get all abs paths and query for their existence so that we can match release artifacts\n release_process_abs_path_data = {}\n if release is not None:\n abs_paths = get_abs_paths_in_event(event_data)\n for abs_path in abs_paths:\n path_data = ReleaseLookupData(abs_path, project, release, event).to_dict()\n release_process_abs_path_data[abs_path] = path_data\n\n # Get a map that maps from abs_path to scraping data\n scraping_attempt_map = get_scraping_attempt_map(event_data)\n\n # build information about individual exceptions and their stack traces\n processed_exceptions = []\n exception_values = get_path(event_data, \"exception\", \"values\")\n if exception_values is not None:\n for exception_value in exception_values:\n processed_frames = []\n frames = get_path(exception_value, \"raw_stacktrace\", \"frames\")\n stacktrace_frames = get_path(exception_value, \"stacktrace\", \"frames\")\n if frames is not None:\n for frame_index, frame in enumerate(frames):\n abs_path = get_path(frame, \"abs_path\")\n debug_id = next(\n (\n debug_image[\"debug_id\"]\n for debug_image in debug_images\n if debug_image[\"type\"] == \"sourcemap\"\n and abs_path == debug_image[\"code_file\"]\n ),\n None,\n )\n processed_frames.append(\n {\n \"debug_id_process\": {\n \"debug_id\": debug_id,\n \"uploaded_source_file_with_correct_debug_id\": debug_id\n in debug_ids_with_uploaded_source_file,\n \"uploaded_source_map_with_correct_debug_id\": debug_id\n in debug_ids_with_uploaded_source_map,\n },\n \"release_process\": release_process_abs_path_data.get(abs_path),\n \"scraping_process\": get_scraping_data_for_frame(\n scraping_attempt_map, frame, frame_index, stacktrace_frames\n ),\n }\n )\n processed_exceptions.append({\"frames\": processed_frames})\n\n sdk_debug_id_support, min_debug_id_sdk_version = get_sdk_debug_id_support(event_data)\n\n return Response(\n {\n \"dist\": event.dist,\n \"release\": event.release,\n \"exceptions\": processed_exceptions,\n \"has_debug_ids\": event_has_debug_ids(event_data),\n \"sdk_version\": get_path(event_data, \"sdk\", \"version\"),\n \"project_has_some_artifact_bundle\": project_has_some_artifact_bundle,\n \"release_has_some_artifact\": has_uploaded_release_bundle_with_release\n or has_uploaded_artifact_bundle_with_release,\n \"has_uploaded_some_artifact_with_a_debug_id\": has_uploaded_some_artifact_with_a_debug_id,\n \"sdk_debug_id_support\": sdk_debug_id_support,\n \"min_debug_id_sdk_version\": min_debug_id_sdk_version,\n \"has_scraping_data\": event_data.get(\"scraping_attempts\") is not None,\n }\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def ParseParametersFromJson(self, inJson):\n if PhactoriDbg(100):\n myDebugPrint3(\n 'PhactoriCylinderClipOperation.ParseParametersFromJson entered\\n', 100)\n self.mCenterPtInfo.UserPointInfoParseParametersFromJson(\n inJson, \"center at \", \"\")\n\n absRadiusKey = 'absolute radius'\n relRadiusKey = 'relative radius'\n if absRadiusKey in inJson:\n self.mRadius = inJson[absRadiusKey]\n self.mRadiusRelAbsFlag = False\n elif relRadiusKey in inJson:\n self.mRadius = inJson[relRadiusKey]\n self.mRadiusRelAbsFlag = True\n else:\n self.mRadius = 0.5\n self.mRadiusRelAbsFlag = True\n\n axisKey = 'axis'\n if axisKey in inJson:\n self.mAxis = inJson[axisKey]\n\n if 'keep inside cylinder' in inJson:\n self.mKeepInside = inJson['keep inside cylinder']\n else:\n self.mKeepInside = True\n\n if 'cut type' in inJson:\n cutType = inJson['cut type']\n self.mCrinkleSetting = 0\n if cutType == 'smooth':\n self.mCrinkleSetting = 0\n elif cutType == 'crinkle':\n self.mCrinkleSetting = 1\n else:\n if PhactoriDbg():\n myDebugPrint3('ParseParametersFromJson warning: cut type \\\n should be smooth or crinkle, but is not, using smooth\\n')\n self.mCrinkleSetting = 0\n else:\n self.mCrinkleSetting = 0 #debatable default\n\n #self.PrintSelf()\n if PhactoriDbg(100):\n myDebugPrint3(\n 'PhactoriCylinderClipOperation.ParseParametersFromJson returning\\n',\n 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def generate_property_stub(\n self,\n name: str,\n raw_obj: object,\n obj: object,\n static_properties: list[str],\n rw_properties: list[str],\n ro_properties: list[str],\n class_info: ClassInfo | None = None,\n ) -> None:\n \"\"\"Generate property stub using introspection of 'obj'.\n\n Try to infer type from docstring, append resulting lines to 'output'.\n\n raw_obj : object before evaluation of descriptor (if any)\n obj : object after evaluation of descriptor\n \"\"\"\n\n docstring = getattr(raw_obj, \"__doc__\", None)\n fget = getattr(raw_obj, \"fget\", None)\n if fget:\n alt_docstr = getattr(fget, \"__doc__\", None)\n if alt_docstr and docstring:\n docstring += \"\\n\" + alt_docstr\n elif alt_docstr:\n docstring = alt_docstr\n\n ctx = FunctionContext(\n self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info\n )\n\n if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):\n return\n\n self.record_name(ctx.name)\n static = self.is_static_property(raw_obj)\n readonly = self.is_property_readonly(raw_obj)\n if static:\n ret_type: str | None = self.strip_or_import(self.get_type_annotation(obj))\n else:\n default_sig = self.get_default_function_sig(raw_obj, ctx)\n ret_type = default_sig.ret_type\n\n inferred_type = self.get_property_type(ret_type, self.sig_generators, ctx)\n if inferred_type is not None:\n inferred_type = self.strip_or_import(inferred_type)\n\n if static:\n classvar = self.add_name(\"typing.ClassVar\")\n trailing_comment = \" # read-only\" if readonly else \"\"\n if inferred_type is None:\n inferred_type = self.add_name(\"_typeshed.Incomplete\")\n\n static_properties.append(\n f\"{self._indent}{name}: {classvar}[{inferred_type}] = ...{trailing_comment}\"\n )\n else: # regular property\n if readonly:\n ro_properties.append(f\"{self._indent}@property\")\n sig = FunctionSig(name, [ArgSig(\"self\")], inferred_type)\n ro_properties.append(sig.format_sig(indent=self._indent))\n else:\n if inferred_type is None:\n inferred_type = self.add_name(\"_typeshed.Incomplete\")\n\n rw_properties.append(f\"{self._indent}{name}: {inferred_type}\")", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def run(self):\n # Re-run on the current document if this directive's source changes.\n self.state.document.settings.env.note_dependency(__file__)\n\n # Parse directive options. Don't use os.path.sep or os.path.join here!\n # That would break if building the docs on Windows.\n tool = self.options.get('tool', 'west').lower()\n app = self.options.get('app', None)\n zephyr_app = self.options.get('zephyr-app', None)\n cd_into = 'cd-into' in self.options\n generator = self.options.get('generator', 'ninja').lower()\n host_os = self.options.get('host-os', 'all').lower()\n board = self.options.get('board', None)\n shield = self.options.get('shield', None)\n conf = self.options.get('conf', None)\n gen_args = self.options.get('gen-args', None)\n build_args = self.options.get('build-args', None)\n build_dir_append = self.options.get('build-dir', '').strip('/')\n goals = self.options.get('goals').split()\n skip_config = 'maybe-skip-config' in self.options\n compact = 'compact' in self.options\n\n if tool not in self.TOOLS:\n raise self.error('Unknown tool {}; choose from: {}'.format(\n tool, self.TOOLS))\n\n if app and zephyr_app:\n raise self.error('Both app and zephyr-app options were given.')\n\n if generator not in self.GENERATORS:\n raise self.error('Unknown generator {}; choose from: {}'.format(\n generator, self.GENERATORS))\n\n if host_os not in self.HOST_OS:\n raise self.error('Unknown host-os {}; choose from: {}'.format(\n host_os, self.HOST_OS))\n\n if compact and skip_config:\n raise self.error('Both compact and maybe-skip-config options were given.')\n\n app = app or zephyr_app\n in_tree = self.IN_TREE_STR if zephyr_app else None\n # Allow build directories which are nested.\n build_dir = ('build' + '/' + build_dir_append).rstrip('/')\n\n # Create host_os array\n host_os = [host_os] if host_os != \"all\" else [v for v in self.HOST_OS\n if v != 'all']\n # Create tools array\n tools = [tool] if tool != \"all\" else [v for v in self.TOOLS\n if v != 'all']\n # Build the command content as a list, then convert to string.\n content = []\n tool_comment = None\n if len(tools) > 1:\n tool_comment = 'Using {}:'\n\n run_config = {\n 'host_os': host_os,\n 'app': app,\n 'in_tree': in_tree,\n 'cd_into': cd_into,\n 'board': board,\n 'shield': shield,\n 'conf': conf,\n 'gen_args': gen_args,\n 'build_args': build_args,\n 'build_dir': build_dir,\n 'goals': goals,\n 'compact': compact,\n 'skip_config': skip_config,\n 'generator': generator\n }\n\n if 'west' in tools:\n w = self._generate_west(**run_config)\n if tool_comment:\n paragraph = nodes.paragraph()\n paragraph += nodes.Text(tool_comment.format('west'))\n content.append(paragraph)\n content.append(self._lit_block(w))\n else:\n content.extend(w)\n\n if 'cmake' in tools:\n c = self._generate_cmake(**run_config)\n if tool_comment:\n paragraph = nodes.paragraph()\n paragraph += nodes.Text(tool_comment.format(\n 'CMake and {}'.format(generator)))\n content.append(paragraph)\n content.append(self._lit_block(c))\n else:\n content.extend(c)\n\n if not tool_comment:\n content = [self._lit_block(content)]\n\n return content", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def __rich_console__(\n self, console: Console, options: ConsoleOptions\n ) -> RenderResult:\n render_str = console.render_str\n renderables = [\n render_str(renderable) if isinstance(renderable, str) else renderable\n for renderable in self.renderables\n ]\n if not renderables:\n return\n _top, right, _bottom, left = Padding.unpack(self.padding)\n width_padding = max(left, right)\n max_width = options.max_width\n widths: Dict[int, int] = defaultdict(int)\n column_count = len(renderables)\n\n get_measurement = Measurement.get\n renderable_widths = [\n get_measurement(console, options, renderable).maximum\n for renderable in renderables\n ]\n if self.equal:\n renderable_widths = [max(renderable_widths)] * len(renderable_widths)\n\n def iter_renderables(\n column_count: int,\n ) -> Iterable[Tuple[int, Optional[RenderableType]]]:\n item_count = len(renderables)\n if self.column_first:\n width_renderables = list(zip(renderable_widths, renderables))\n\n column_lengths: List[int] = [item_count // column_count] * column_count\n for col_no in range(item_count % column_count):\n column_lengths[col_no] += 1\n\n row_count = (item_count + column_count - 1) // column_count\n cells = [[-1] * column_count for _ in range(row_count)]\n row = col = 0\n for index in range(item_count):\n cells[row][col] = index\n column_lengths[col] -= 1\n if column_lengths[col]:\n row += 1\n else:\n col += 1\n row = 0\n for index in chain.from_iterable(cells):\n if index == -1:\n break\n yield width_renderables[index]\n else:\n yield from zip(renderable_widths, renderables)\n # Pad odd elements with spaces\n if item_count % column_count:\n for _ in range(column_count - (item_count % column_count)):\n yield 0, None\n\n table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False)\n table.expand = self.expand\n table.title = self.title\n\n if self.width is not None:\n column_count = (max_width) // (self.width + width_padding)\n for _ in range(column_count):\n table.add_column(width=self.width)\n else:\n while column_count > 1:\n widths.clear()\n column_no = 0\n for renderable_width, _ in iter_renderables(column_count):\n widths[column_no] = max(widths[column_no], renderable_width)\n total_width = sum(widths.values()) + width_padding * (\n len(widths) - 1\n )\n if total_width > max_width:\n column_count = len(widths) - 1\n break\n else:\n column_no = (column_no + 1) % column_count\n else:\n break\n\n get_renderable = itemgetter(1)\n _renderables = [\n get_renderable(_renderable)\n for _renderable in iter_renderables(column_count)\n ]\n if self.equal:\n _renderables = [\n None\n if renderable is None\n else Constrain(renderable, renderable_widths[0])\n for renderable in _renderables\n ]\n if self.align:\n align = self.align\n _Align = Align\n _renderables = [\n None if renderable is None else _Align(renderable, align)\n for renderable in _renderables\n ]\n\n right_to_left = self.right_to_left\n add_row = table.add_row\n for start in range(0, len(_renderables), column_count):\n row = _renderables[start : start + column_count]\n if right_to_left:\n row = row[::-1]\n add_row(*row)\n yield table", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _build_session(\n self,\n options: Values,\n retries: Optional[int] = None,\n timeout: Optional[int] = None,\n fallback_to_certifi: bool = False,\n ) -> PipSession:\n cache_dir = options.cache_dir\n assert not cache_dir or os.path.isabs(cache_dir)\n\n if \"truststore\" in options.features_enabled:\n try:\n ssl_context = _create_truststore_ssl_context()\n except Exception:\n if not fallback_to_certifi:\n raise\n ssl_context = None\n else:\n ssl_context = None\n\n session = PipSession(\n cache=os.path.join(cache_dir, \"http-v2\") if cache_dir else None,\n retries=retries if retries is not None else options.retries,\n trusted_hosts=options.trusted_hosts,\n index_urls=self._get_index_urls(options),\n ssl_context=ssl_context,\n )\n\n # Handle custom ca-bundles from the user\n if options.cert:\n session.verify = options.cert\n\n # Handle SSL client certificate\n if options.client_cert:\n session.cert = options.client_cert\n\n # Handle timeouts\n if options.timeout or timeout:\n session.timeout = timeout if timeout is not None else options.timeout\n\n # Handle configured proxies\n if options.proxy:\n session.proxies = {\n \"http\": options.proxy,\n \"https\": options.proxy,\n }\n\n # Determine if we can prompt the user for authentication or not\n session.auth.prompting = not options.no_input\n session.auth.keyring_provider = options.keyring_provider\n\n return session", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def handle_sync_pattern(self):\n if self.sync_pattern and self.sync_state == \"SEARCHING\":\n while True:\n # Make sure we have some data to look for a sync word in\n if len(self.data) < len(self.sync_pattern):\n return \"STOP\"\n\n # Find the beginning of the sync pattern\n try:\n sync_index = self.data.index(self.sync_pattern[0])\n # Make sure we have enough data for the whole sync pattern past this index\n if len(self.data) < (sync_index + len(self.sync_pattern)):\n return \"STOP\"\n\n # Check for the rest of the sync pattern\n found = True\n index = sync_index\n for byte in self.sync_pattern:\n if self.data[index] != byte:\n found = False\n break\n index += 1\n\n if found:\n if sync_index != 0:\n self.log_discard(sync_index, True)\n # Delete Data Before Sync Pattern\n self.data = self.data[sync_index:]\n self.sync_state = \"FOUND\"\n return None\n\n else: # not found\n self.log_discard(sync_index, False)\n # Delete Data Before and including first character of suspected sync Pattern\n self.data = self.data[(sync_index + 1) :]\n continue\n\n except ValueError: # sync_index = None\n self.log_discard(len(self.data), False)\n self.data = b\"\"\n return \"STOP\"\n return None", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def parse_queries(captured_queries: list[dict[str, Any]]) -> dict[str, int]:\n write_ops = [\"INSERT\", \"UPDATE\", \"DELETE\"]\n\n real_queries: dict[str, int] = {}\n\n for query in captured_queries:\n raw_sql = query[\"sql\"]\n parsed = sqlparse.parse(raw_sql)\n for token_index, token in enumerate(parsed[0].tokens):\n if token.ttype is DML:\n if token.value.upper() in write_ops:\n for t in parsed[0].tokens[token_index + 1 :]:\n if isinstance(t, sqlparse.sql.Identifier):\n table_name = t.get_real_name()\n if real_queries.get(table_name) is None:\n real_queries[table_name] = 0\n real_queries[table_name] += 1\n break\n\n return real_queries", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def UserPointInfoParseParametersFromJson(self, inJson, inKeyPrefix, inKeySuffix,\n inDisplacementFlag = False):\n self.mParseHadKeys = False\n keyAbsolute = inKeyPrefix + \"absolute point\" + inKeySuffix\n keyRelative = inKeyPrefix + \"relative point\" + inKeySuffix\n keyNode = inKeyPrefix + \"node\" + inKeySuffix\n keyElement = inKeyPrefix + \"element\" + inKeySuffix\n keyMaxVar = inKeyPrefix + \"max variable point\" + inKeySuffix\n keyMinVar = inKeyPrefix + \"min variable point\" + inKeySuffix\n keyDataPt = inKeyPrefix + \"data point\" + inKeySuffix\n\n if keyAbsolute in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n self.mPointType = \"absolute\"\n self.mXyz = inJson[keyAbsolute]\n self.mMayChangeWithData = False\n elif keyRelative in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n self.mPointType = \"datasize relative\"\n self.mXyz = inJson[keyRelative]\n self.mMayChangeWithData = True\n elif keyNode in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson node found\\n\")\n self.mPointType = \"node\"\n self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyNode)\n self.mMayChangeWithData = True\n if PhactoriDbg():\n myDebugPrint3(\" node id is \" + str(self.mElementOrNodeId) + \"\\n\")\n elif keyElement in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson element found\\n\")\n self.mPointType = \"element\"\n self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyElement)\n self.mMayChangeWithData = True\n if PhactoriDbg():\n myDebugPrint3(\" element id is \" + str(self.mElementOrNodeId) + \"\\n\")\n elif keyMinVar in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n self.mPointType = \"min variable\"\n #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):\n self.mReferenceVariableInfo = PhactoriVariableInfo()\n self.mReferenceVariableInfo.\\\n ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')\n self.mMayChangeWithData = True\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson \"\n \"min variable found\\n\"\n \"var info: \" + self.mReferenceVariableInfo.SelfToStr() + \"\\n\")\n varSourceKey = inKeyPrefix + \"input for min variable point\" + inKeySuffix\n if varSourceKey in inJson:\n self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]\n myDebugPrint3(\"input name for min variable point: \" + \\\n self.mInputNameToUseForMinMaxVariable + \"\\n\")\n varDispKey = \\\n inKeyPrefix + \"displacement for min variable point\" + inKeySuffix\n if varDispKey in inJson:\n self.mDisplacement = inJson[varDispKey]\n myDebugPrint3(\"displacement for min variable point: \" + \\\n str(self.mDisplacement) + \"\\n\")\n elif keyDataPt in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson: \"\n \"parsing data point\")\n params = inJson[keyDataPt]\n if inDisplacementFlag:\n #better have 7 items\n if len(params) != 7:\n myDebugPrint3AndException(\n \"PhactoriUserPointInfo.ParseParametersFromJson:\\n\"\n \"data point displaced expected 7 parameters\")\n else:\n #better have 4 items\n if len(params) != 4:\n myDebugPrint3AndException(\n \"PhactoriUserPointInfo.ParseParametersFromJson:\\n\"\n \"data point expected 4 parameters\")\n param0 = params[0].lower()\n if param0 == \"min\":\n self.mPointType = \"min variable\"\n if param0 == \"max\":\n self.mPointType = \"max variable\"\n if param0 == \"center\":\n myDebugPrint3AndException(\n \"PhactoriUserPointInfo.ParseParametersFromJson:\\n\"\n \"data point 'center' not yet implemented\")\n self.mReferenceVariableInfo = PhactoriVariableInfo()\n tempJson = {}\n tempJson[params[1].lower()] = params[2]\n if PhactoriDbg():\n print(\"tempJson: \" + str(tempJson))\n self.mReferenceVariableInfo.\\\n ParseVariableNameAndVectorOrTensorComponent(tempJson, '')\n self.mMayChangeWithData = True\n if PhactoriDbg():\n myDebugPrint3(\"variable found\\n\"\n \"var info: \" + self.mReferenceVariableInfo.SelfToStr() + \"\\n\")\n if params[3] != \"default\":\n self.mInputNameToUseForMinMaxVariable = params[3]\n if PhactoriDbg():\n myDebugPrint3(\"name of input operation: \" +\n self.mInputNameToUseForMinMaxVariable + \"\\n\")\n if inDisplacementFlag:\n self.mHasDisplacedInfoFlag = True\n self.mDisplacement[0] = params[4]\n self.mDisplacement[1] = params[5]\n self.mDisplacement[2] = params[6]\n\n else:\n if PhactoriDbg():\n myDebugPrint3(\"using default input operation\\n\")\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson: \"\n \"done parsing data point\")\n elif keyMaxVar in inJson:\n self.mParsingDetectedAtLeastOneSetting = True\n self.mPointType = \"max variable\"\n #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):\n self.mReferenceVariableInfo = PhactoriVariableInfo()\n self.mReferenceVariableInfo.\\\n ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')\n self.mMayChangeWithData = True\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriUserPointInfo.ParseParametersFromJson \"\n \"max variable found\\n\"\n \"var info: \" + self.mReferenceVariableInfo.SelfToStr() + \"\\n\")\n varSourceKey = inKeyPrefix + \"input for max variable point\" + inKeySuffix\n if varSourceKey in inJson:\n self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]\n myDebugPrint3(\"input name for max variable point: \" + \\\n self.mInputNameToUseForMinMaxVariable + \"\\n\")\n varDispKey = \\\n inKeyPrefix + \"displacement for max variable point\" + inKeySuffix\n if varDispKey in inJson:\n self.mDisplacement = inJson[varDispKey]\n myDebugPrint3(\"displacement for max variable point: \" + \\\n str(self.mDisplacement) + \"\\n\")\n else:\n self.mParsingDetectedAtLeastOneSetting = False\n if PhactoriDbg():\n myDebugPrint3(\" no PhactoriUserPointInfo parse keys, using default\\n\")\n\n #myDebugPrint3(\"PhactoriUserPoint Parsed from json:\\n\")\n #self.PrintSelf()", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def program_start(self):\n\t\tself.demux = -1\n\n\t\tif self.dont_restart_program:\n\t\t\treturn\n\n\t\tself.rec_ref = self.timer.service_ref and self.timer.service_ref.ref\n\t\tif self.rec_ref and self.rec_ref.flags & eServiceReference.isGroup:\n\t\t\tself.rec_ref = getBestPlayableServiceReference(self.rec_ref, eServiceReference())\n\n\t\t# recordService (Simulation) ggf. starten\n\t\tif self.timer.state == TimerEntry.StateWaiting:\n\t\t\tif self.simulate_recordService is None:\n\t\t\t\tif self.rec_ref:\n\t\t\t\t\tself.simulate_recordService = NavigationInstance.instance.recordService(self.rec_ref, True)\n\t\t\t\t\tif self.simulate_recordService:\n\t\t\t\t\t\tres = self.simulate_recordService.start()\n\t\t\t\t\t\tself.timer.log(0, \"[VPS] start recordService (simulation) \" + str(res))\n\t\t\t\t\t\tif res != 0 and res != -1:\n\t\t\t\t\t\t\t# Fehler aufgetreten (kein Tuner frei?)\n\t\t\t\t\t\t\tNavigationInstance.instance.stopRecordService(self.simulate_recordService)\n\t\t\t\t\t\t\tself.simulate_recordService = None\n\n\t\t\t\t\t\t\t# in einer Minute ggf. nochmal versuchen\n\t\t\t\t\t\t\tif 60 < self.nextExecution:\n\t\t\t\t\t\t\t\tself.nextExecution = 60\n\n\t\t\t\t\t\t\t# Bei Overwrite versuchen ohne Fragen auf Sender zu schalten\n\t\t\t\t\t\t\tif self.timer.vpsplugin_overwrite is True:\n\t\t\t\t\t\t\t\tcur_ref = NavigationInstance.instance.getCurrentlyPlayingServiceReference()\n\t\t\t\t\t\t\t\tif cur_ref and not cur_ref.getPath() and self.rec_ref.toCompareString() != cur_ref.toCompareString():\n\t\t\t\t\t\t\t\t\tself.timer.log(9, \"[VPS-Plugin] zap without asking (simulation)\")\n\t\t\t\t\t\t\t\t\tNotifications.AddNotification(MessageBox, _(\"In order to record a timer, the TV was switched to the recording service!\\n\"), type=MessageBox.TYPE_INFO, timeout=20)\n\t\t\t\t\t\t\t\t\tNavigationInstance.instance.playService(self.rec_ref)\n\t\t\t\t\t\t\t\t\tif 3 < self.nextExecution:\n\t\t\t\t\t\t\t\t\t\tself.nextExecution = 3\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# ansonsten versuchen auf dem aktuellen Transponder/Kanal nach Infos zu suchen\n\t\t\t\t\t\t\t\tif not self.program_try_search_running:\n\t\t\t\t\t\t\t\t\tself.program_do_start(1)\n\t\t\t\t\t\telse: # Simulation hat geklappt\n\t\t\t\t\t\t\tif 1 < self.nextExecution:\n\t\t\t\t\t\t\t\tself.nextExecution = 1\n\t\t\telse: # Simulation l\u00e4uft schon\n\t\t\t\t# hole Demux\n\t\t\t\tstream = self.simulate_recordService.stream()\n\t\t\t\tif stream:\n\t\t\t\t\tstreamdata = stream.getStreamingData()\n\t\t\t\t\tif (streamdata and ('demux' in streamdata)):\n\t\t\t\t\t\tself.demux = streamdata['demux']\n\n\t\t\t\tif self.demux == -1:\n\t\t\t\t\t# ist noch nicht soweit(?), in einer Sekunde erneut versuchen\n\t\t\t\t\tif 1 < self.nextExecution:\n\t\t\t\t\t\tself.nextExecution = 1\n\t\t\t\telse:\n\t\t\t\t\tself.program_do_start(0)\n\n\t\telif self.timer.state == TimerEntry.StatePrepared or self.timer.state == TimerEntry.StateRunning:\n\t\t\tstream = self.timer.record_service.stream()\n\t\t\tif stream:\n\t\t\t\tstreamdata = stream.getStreamingData()\n\t\t\t\tif (streamdata and ('demux' in streamdata)):\n\t\t\t\t\tself.demux = streamdata['demux']\n\t\t\tif self.demux != -1:\n\t\t\t\tself.program_do_start(0)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def do_flag_elimination(fn: FuncIR, options: CompilerOptions) -> None:\n # Find registers that are used exactly once as source, and in a branch.\n counts: dict[Register, int] = {}\n branches: dict[Register, Branch] = {}\n labels: dict[Register, BasicBlock] = {}\n for block in fn.blocks:\n for i, op in enumerate(block.ops):\n for src in op.sources():\n if isinstance(src, Register):\n counts[src] = counts.get(src, 0) + 1\n if i == 0 and isinstance(op, Branch) and isinstance(op.value, Register):\n branches[op.value] = op\n labels[op.value] = block\n\n # Based on these we can find the candidate registers.\n candidates: set[Register] = {\n r for r in branches if counts.get(r, 0) == 1 and r not in fn.arg_regs\n }\n\n # Remove candidates with invalid assignments.\n for block in fn.blocks:\n for i, op in enumerate(block.ops):\n if isinstance(op, Assign) and op.dest in candidates:\n next_op = block.ops[i + 1]\n if not (isinstance(next_op, Goto) and next_op.label is labels[op.dest]):\n # Not right\n candidates.remove(op.dest)\n\n builder = LowLevelIRBuilder(None, options)\n transform = FlagEliminationTransform(\n builder, {x: y for x, y in branches.items() if x in candidates}\n )\n transform.transform_blocks(fn.blocks)\n fn.blocks = builder.blocks", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@pytest.mark.slow\ndef test_migration(\n octopoes_api_connector: OctopoesAPIConnector,\n bytes_client: BytesAPIClient,\n organisation_storage: SQLOrganisationStorage,\n valid_time,\n):\n octopoes_api_connector.session._timeout.connect = 60\n octopoes_api_connector.session._timeout.read = 60\n\n iterations = 30\n cache_path = Path(BASE_DIR.parent / \".ci\" / f\".cache_{iterations}.json\")\n hostname_range = range(0, iterations)\n\n if cache_path.exists():\n export = json.load(cache_path.open())\n exported = json.dumps(export)\n else:\n for x in hostname_range:\n seed_system(\n octopoes_api_connector,\n valid_time,\n test_hostname=f\"{x}.com\",\n test_ip=f\"192.0.{x % 7}.{x % 13}\",\n test_ipv6=f\"{x % 7}e4d:64a2:cb49:bd48:a1ba:def3:d15d:{x % 5}230\",\n method=\"kat_nmap_normalize\" if x % 3 == 0 else \"kat_dns_normalize\", # 30% of the origins need Bytes\n )\n\n export = []\n\n # Drop the source method field to test the migration\n for tx in octopoes_api_connector.export_all():\n if \"txOps\" in tx:\n ops = []\n for tx_op in tx[\"txOps\"]:\n if \"source_method\" in tx_op[1]:\n del tx_op[1][\"source_method\"]\n\n ops.append(tx_op)\n\n tx[\"txOps\"] = ops\n\n export.append(tx)\n\n exported = json.dumps(export)\n cache_path.write_text(exported)\n\n octopoes_api_connector.import_new(exported)\n\n raw = b\"1234567890\"\n bytes_client.login()\n\n for method in [\"kat_nmap_normalize\", \"kat_dns_normalize\"]:\n for origin in octopoes_api_connector.list_origins(\n valid_time, method=method, origin_type=OriginType.OBSERVATION\n ):\n boefje_id = \"boefje_\" + method\n\n if \"3.com\" in origin.source: # create one udp scan\n boefje_id = \"boefje_udp\"\n\n boefje_meta = get_boefje_meta(uuid.uuid4(), boefje_id=boefje_id)\n bytes_client.save_boefje_meta(boefje_meta)\n raw_data_id = bytes_client.save_raw(boefje_meta.id, raw)\n\n normalizer_meta = get_normalizer_meta(boefje_meta, raw_data_id)\n normalizer_meta.id = origin.task_id\n normalizer_meta.normalizer.id = method\n\n bytes_client.save_normalizer_meta(normalizer_meta)\n\n total_oois = octopoes_api_connector.list_objects(set(), valid_time).count\n total_processed, total_failed = upgrade(organisation_storage, valid_time)\n\n assert total_processed == len(hostname_range)\n assert total_failed == 0\n\n observation = octopoes_api_connector.list_origins(\n valid_time, source=Reference.from_str(\"Hostname|test|0.com\"), origin_type=OriginType.OBSERVATION\n )[0]\n assert observation.method == \"kat_nmap_normalize\"\n assert observation.source_method == \"boefje_kat_nmap_normalize\"\n\n observation = octopoes_api_connector.list_origins(\n valid_time, source=Reference.from_str(\"Hostname|test|1.com\"), origin_type=OriginType.OBSERVATION\n )[0]\n assert observation.method == \"kat_dns_normalize\"\n assert observation.source_method == \"dns-records\" # the logic has found the right boefje id\n\n observation = octopoes_api_connector.list_origins(\n valid_time, source=Reference.from_str(\"Hostname|test|3.com\"), origin_type=OriginType.OBSERVATION\n )[0]\n assert observation.method == \"kat_nmap_normalize\"\n assert observation.source_method == \"boefje_udp\"\n\n assert octopoes_api_connector.list_objects(set(), valid_time).count == total_oois", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def main():\n try:\n options = getInputOptions()\n global base_url\n base_url = \"http://%s/sdrangel\" % options.address\n r = requests.get(url=base_url + \"/devicesets\")\n if r.status_code / 100 == 2:\n rj = r.json()\n deviceSets = rj.get(\"deviceSets\", None)\n if deviceSets is not None:\n if len(deviceSets) > 1:\n if options.transmit:\n if deviceSets[options.deviceset_index][\"samplingDevice\"][\"direction\"] == 0 and deviceSets[options.deviceset_index + 1][\"samplingDevice\"][\"direction\"] == 1:\n stopDevice(options.deviceset_index)\n time.sleep(1)\n startDevice(options.deviceset_index + 1)\n setFocus(options.deviceset_index + 1)\n else:\n print(\"Incorrect configuration expecting Rx%d and Tx%d\" % (options.deviceset_index, options.deviceset_index + 1))\n else:\n if deviceSets[options.deviceset_index - 1][\"samplingDevice\"][\"direction\"] == 0 and deviceSets[options.deviceset_index][\"samplingDevice\"][\"direction\"] == 1:\n stopDevice(options.deviceset_index)\n time.sleep(1)\n startDevice(options.deviceset_index - 1)\n setFocus(options.deviceset_index - 1)\n else:\n print(\"Incorrect configuration expecting Rx%d and Tx%d\" % (options.deviceset_index - 1, options.deviceset_index))\n else:\n print(\"Need at least a Rx and a Tx device set\")\n else:\n print(\"Cannot get device sets configuration\")\n else:\n print(\"Error getting device sets configuration\")\n\n except Exception as ex:\n tb = traceback.format_exc()\n print >> sys.stderr, tb", "smellKey": "S3776", "smellId": null, "repo": "f4exb_sdrangel", "language": "python"} {"function": "def prepare_url(self, url, params):\n \"\"\"Prepares the given HTTP URL.\"\"\"\n #: Accept objects that have string representations.\n #: We're unable to blindly call unicode/str functions\n #: as this will include the bytestring indicator (b'')\n #: on python 3.x.\n #: https://github.com/psf/requests/pull/2238\n if isinstance(url, bytes):\n url = url.decode(\"utf8\")\n else:\n url = str(url)\n\n # Remove leading whitespaces from url\n url = url.lstrip()\n\n # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n # `data` etc to work around exceptions from `url_parse`, which\n # handles RFC 3986 only.\n if \":\" in url and not url.lower().startswith(\"http\"):\n self.url = url\n return\n\n # Support for unicode domain names and paths.\n try:\n scheme, auth, host, port, path, query, fragment = parse_url(url)\n except LocationParseError as e:\n raise InvalidURL(*e.args)\n\n if not scheme:\n raise MissingSchema(\n f\"Invalid URL {url!r}: No scheme supplied. \"\n f\"Perhaps you meant https://{url}?\"\n )\n\n if not host:\n raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n # In general, we want to try IDNA encoding the hostname if the string contains\n # non-ASCII characters. This allows users to automatically get the correct IDNA\n # behaviour. For strings containing only ASCII characters, we need to also verify\n # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n if not unicode_is_ascii(host):\n try:\n host = self._get_idna_encoded_host(host)\n except UnicodeError:\n raise InvalidURL(\"URL has an invalid label.\")\n elif host.startswith((\"*\", \".\")):\n raise InvalidURL(\"URL has an invalid label.\")\n\n # Carefully reconstruct the network location\n netloc = auth or \"\"\n if netloc:\n netloc += \"@\"\n netloc += host\n if port:\n netloc += f\":{port}\"\n\n # Bare domains aren't valid URLs.\n if not path:\n path = \"/\"\n\n if isinstance(params, (str, bytes)):\n params = to_native_string(params)\n\n enc_params = self._encode_params(params)\n if enc_params:\n if query:\n query = f\"{query}&{enc_params}\"\n else:\n query = enc_params\n\n url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))\n self.url = url", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def GetNextStruct(filep):\n global CPP_DIRECT\n global LINE_COUNT\n\n got_struct = False\n have_c_comment = False\n\n data = \"\"\n\n while True:\n line = filep.readline()\n if not line:\n break\n\n LINE_COUNT += 1\n line = line[:-1]\n\n if not have_c_comment and C_COMMENT_START_RE.search(line):\n if C_MULTILINE_COMMENT_SUB_RE.search(line):\n line = C_MULTILINE_COMMENT_SUB_RE.sub(\"\", line)\n else:\n line = C_COMMENT_START_SUB_RE.sub(\"\", line)\n have_c_comment = True\n\n if have_c_comment:\n if not C_COMMENT_END_RE.search(line):\n continue\n have_c_comment = False\n line = C_COMMENT_END_SUB_RE.sub(\"\", line)\n\n line = NormalizeLine(line)\n\n if not line:\n continue\n\n if not got_struct:\n if INCLUDE_RE.match(line):\n CPP_DIRECT.append(line)\n elif CPP_CONDITIONAL_BLOCK_RE.match(line):\n CPP_DIRECT.append(line)\n elif PREPROCESSOR_DEF_RE.match(line):\n HEADER_DIRECT.append(line)\n elif not STRUCT_DEF_RE.match(line):\n raise RpcGenError(\"Missing struct on line %d: %s\" % (LINE_COUNT, line))\n else:\n got_struct = True\n data += line\n continue\n\n # We are inside the struct\n tokens = line.split(\"}\")\n if len(tokens) == 1:\n data += \" \" + line\n continue\n\n if tokens[1]:\n raise RpcGenError(\"Trailing garbage after struct on line %d\" % LINE_COUNT)\n\n # We found the end of the struct\n data += \" %s}\" % tokens[0]\n break\n\n # Remove any comments, that might be in there\n data = re.sub(r\"/\\*.*\\*/\", \"\", data)\n\n return data", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-l3", "language": "python"} {"function": "def get_combinator_sql(self, combinator, all):\n features = self.connection.features\n compilers = [\n query.get_compiler(self.using, self.connection, self.elide_empty)\n for query in self.query.combined_queries\n ]\n if not features.supports_slicing_ordering_in_compound:\n for compiler in compilers:\n if compiler.query.is_sliced:\n raise DatabaseError(\n \"LIMIT/OFFSET not allowed in subqueries of compound statements.\"\n )\n if compiler.get_order_by():\n raise DatabaseError(\n \"ORDER BY not allowed in subqueries of compound statements.\"\n )\n parts = []\n empty_compiler = None\n for compiler in compilers:\n try:\n parts.append(self._get_combinator_part_sql(compiler))\n except EmptyResultSet:\n # Omit the empty queryset with UNION and with DIFFERENCE if the\n # first queryset is nonempty.\n if combinator == \"union\" or (combinator == \"difference\" and parts):\n empty_compiler = compiler\n continue\n raise\n if not parts:\n raise EmptyResultSet\n elif len(parts) == 1 and combinator == \"union\" and self.query.is_sliced:\n # A sliced union cannot be composed of a single component because\n # in the event the later is also sliced it might result in invalid\n # SQL due to the usage of multiple LIMIT clauses. Prevent that from\n # happening by always including an empty resultset query to force\n # the creation of an union.\n empty_compiler.elide_empty = False\n parts.append(self._get_combinator_part_sql(empty_compiler))\n combinator_sql = self.connection.ops.set_operators[combinator]\n if all and combinator == \"union\":\n combinator_sql += \" ALL\"\n braces = \"{}\"\n if not self.query.subquery and features.supports_slicing_ordering_in_compound:\n braces = \"({})\"\n sql_parts, args_parts = zip(\n *((braces.format(sql), args) for sql, args in parts)\n )\n result = [\" {} \".format(combinator_sql).join(sql_parts)]\n params = []\n for part in args_parts:\n params.extend(part)\n return result, params", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _calculate_column_widths(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> List[int]:\n \"\"\"Calculate the widths of each column, including padding, not including borders.\"\"\"\n max_width = options.max_width\n columns = self.columns\n width_ranges = [\n self._measure_column(console, options, column) for column in columns\n ]\n widths = [_range.maximum or 1 for _range in width_ranges]\n get_padding_width = self._get_padding_width\n extra_width = self._extra_width\n if self.expand:\n ratios = [col.ratio or 0 for col in columns if col.flexible]\n if any(ratios):\n fixed_widths = [\n 0 if column.flexible else _range.maximum\n for _range, column in zip(width_ranges, columns)\n ]\n flex_minimum = [\n (column.width or 1) + get_padding_width(column._index)\n for column in columns\n if column.flexible\n ]\n flexible_width = max_width - sum(fixed_widths)\n flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum)\n iter_flex_widths = iter(flex_widths)\n for index, column in enumerate(columns):\n if column.flexible:\n widths[index] = fixed_widths[index] + next(iter_flex_widths)\n table_width = sum(widths)\n\n if table_width > max_width:\n widths = self._collapse_widths(\n widths,\n [(column.width is None and not column.no_wrap) for column in columns],\n max_width,\n )\n table_width = sum(widths)\n # last resort, reduce columns evenly\n if table_width > max_width:\n excess_width = table_width - max_width\n widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths)\n table_width = sum(widths)\n\n width_ranges = [\n self._measure_column(console, options.update_width(width), column)\n for width, column in zip(widths, columns)\n ]\n widths = [_range.maximum or 0 for _range in width_ranges]\n\n if (table_width < max_width and self.expand) or (\n self.min_width is not None and table_width < (self.min_width - extra_width)\n ):\n _max_width = (\n max_width\n if self.min_width is None\n else min(self.min_width - extra_width, max_width)\n )\n pad_widths = ratio_distribute(_max_width - table_width, widths)\n widths = [_width + pad for _width, pad in zip(widths, pad_widths)]\n\n return widths", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def tryPrepare(self):\n\t\tif self.justplay:\n\t\t\treturn True\n\t\telse:\n\t\t\tif not self.calculateFilename():\n\t\t\t\tself.do_backoff()\n\t\t\t\tself.start_prepare = int(time()) + self.backoff\n\t\t\t\treturn False\n\t\t\trecordingReference = self.service_ref and self.service_ref.ref\n\t\t\tif recordingReference and recordingReference.flags & eServiceReference.isGroup:\n\t\t\t\trecordingReference = getBestPlayableServiceReference(recordingReference, eServiceReference())\n\t\t\t\tif not recordingReference:\n\t\t\t\t\tself.log(1, \"The 'get best playable service for group... record' call failed!\")\n\t\t\t\t\treturn False\n\t\t\tself.setRecordingPreferredTuner()\n\t\t\tself.record_service = recordingReference and NavigationInstance.instance.recordService(recordingReference, False, pNavigation.isRealRecording)\n\t\t\tif not self.record_service:\n\t\t\t\tself.log(1, \"The 'record service' call failed!\")\n\t\t\t\tself.setRecordingPreferredTuner(setdefault=True)\n\t\t\t\treturn False\n\t\t\tname = self.name\n\t\t\tdescription = self.description\n\t\t\tif self.repeated:\n\t\t\t\tepgCache = eEPGCache.getInstance()\n\t\t\t\tqueryTime = self.begin + (self.end - self.begin) // 2\n\t\t\t\tevent = epgCache.lookupEventTime(recordingReference, queryTime)\n\t\t\t\tif event:\n\t\t\t\t\tif self.rename_repeat:\n\t\t\t\t\t\teventDescription = event.getShortDescription()\n\t\t\t\t\t\tif not eventDescription:\n\t\t\t\t\t\t\teventDescription = event.getExtendedDescription()\n\t\t\t\t\t\tif eventDescription and eventDescription != description:\n\t\t\t\t\t\t\tdescription = eventDescription\n\t\t\t\t\t\teventName = event.getEventName()\n\t\t\t\t\t\tif eventName and eventName != name:\n\t\t\t\t\t\t\tname = eventName\n\t\t\t\t\t\t\tif not self.calculateFilename(eventName):\n\t\t\t\t\t\t\t\tself.do_backoff()\n\t\t\t\t\t\t\t\tself.start_prepare = int(time()) + self.backoff\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\t\teventId = event.getEventId()\n\t\t\t\telse:\n\t\t\t\t\teventId = -1\n\t\t\telse:\n\t\t\t\teventId = self.eit\n\t\t\t\tif eventId is None:\n\t\t\t\t\teventId = -1\n\t\t\tprepareResult = self.record_service.prepare(f\"{self.Filename}{self.record_service.getFilenameExtension()}\", self.begin, self.end, eventId, name.replace(\"\\n\", \" \"), description.replace(\"\\n\", \" \"), \" \".join(self.tags), bool(self.descramble), bool(self.record_ecm))\n\t\t\tif prepareResult:\n\t\t\t\tif prepareResult == -255:\n\t\t\t\t\tself.log(4, \"Failed to write meta information!\")\n\t\t\t\telse:\n\t\t\t\t\tself.log(2, f\"The 'prepare' call failed with error {prepareResult}!\")\n\t\t\t\t# We must calculate only start time before stopRecordService call because in Screens/Standby.py TryQuitMainloop\n\t\t\t\t# tries to get the next start time in evEnd event handler.\n\t\t\t\tself.do_backoff()\n\t\t\t\tself.start_prepare = int(time()) + self.backoff\n\t\t\t\tNavigationInstance.instance.stopRecordService(self.record_service)\n\t\t\t\tself.record_service = None\n\t\t\t\tself.setRecordingPreferredTuner(setdefault=True)\n\t\t\t\treturn False\n\t\t\treturn True", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def find_sometimes_defined_attributes(\n blocks: list[BasicBlock],\n self_reg: Register,\n maybe_defined: AnalysisResult[str],\n dirty: AnalysisResult[None],\n) -> set[str]:\n \"\"\"Find attributes that are sometimes initialized in some basic blocks.\"\"\"\n attrs: set[str] = set()\n for block in blocks:\n for i, op in enumerate(block.ops):\n # Only look at possibly defined attributes at exits.\n if dirty.after[block, i]:\n if not dirty.before[block, i]:\n attrs = attrs | maybe_defined.after[block, i]\n break\n if isinstance(op, ControlOp):\n for target in op.targets():\n if not dirty.after[block, i] and dirty.before[target, 0]:\n attrs = attrs | maybe_defined.after[target, 0]\n return attrs", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@instrumented_task(\n name=\"sentry.tasks.update_user_reports\",\n queue=\"update\",\n silo_mode=SiloMode.REGION,\n)\ndef update_user_reports(**kwargs: Any) -> None:\n now = timezone.now()\n start = kwargs.get(\"start\", now - timedelta(days=1))\n end = kwargs.get(\"end\", now + timedelta(minutes=5)) # +5 minutes just to catch clock skew\n\n # The event query time range is [start - event_lookback, end].\n event_lookback = kwargs.get(\"event_lookback\", timedelta(days=1))\n\n # Filter for user reports where there was no event associated with them at\n # ingestion time\n user_reports = UserReport.objects.filter(\n group_id__isnull=True,\n environment_id__isnull=True,\n date_added__gte=start,\n date_added__lte=end,\n )\n\n # We do one query per project, just to avoid the small case that two projects have the same event ID\n project_map: dict[int, Any] = {}\n for r in user_reports:\n project_map.setdefault(r.project_id, []).append(r)\n\n # Logging values\n total_reports = len(user_reports)\n updated_reports = 0\n samples = None\n\n MAX_EVENTS = kwargs.get(\n \"max_events\",\n 2000, # the default max_query_size is 256 KiB, which we're hitting with 5000 events, so keeping it safe at 2000\n )\n for project_id, reports in project_map.items():\n project = Project.objects.get(id=project_id)\n event_ids = [r.event_id for r in reports]\n report_by_event = {r.event_id: r for r in reports}\n events = []\n\n event_start = start - event_lookback\n if retention := quotas.backend.get_event_retention(organization=project.organization):\n event_start = max(event_start, now - timedelta(days=retention))\n\n for event_id_chunk in chunked(event_ids, MAX_EVENTS):\n snuba_filter = eventstore.Filter(\n project_ids=[project_id],\n event_ids=event_id_chunk,\n start=event_start,\n end=end,\n )\n try:\n events_chunk = eventstore.backend.get_events(\n filter=snuba_filter, referrer=\"tasks.update_user_reports\"\n )\n events.extend(events_chunk)\n except Exception:\n sentry_sdk.set_tag(\"update_user_reports.eventstore_query_failed\", True)\n logger.exception(\n \"update_user_reports.eventstore_query_failed\",\n extra={\"project_id\": project_id, \"start\": start, \"end\": end},\n ) # will also send exc to Sentry\n metrics.incr(\"tasks.update_user_reports.eventstore_query_failed\")\n\n for event in events:\n report = report_by_event.get(event.event_id)\n if report:\n if not is_in_feedback_denylist(project.organization):\n logger.info(\n \"update_user_reports.shim_to_feedback\",\n extra={\"report_id\": report.id, \"event_id\": event.event_id},\n )\n metrics.incr(\"tasks.update_user_reports.shim_to_feedback\")\n shim_to_feedback(\n {\n \"name\": report.name,\n \"email\": report.email,\n \"comments\": report.comments,\n \"event_id\": report.event_id,\n \"level\": \"error\",\n },\n event,\n project,\n FeedbackCreationSource.UPDATE_USER_REPORTS_TASK,\n )\n report.update(group_id=event.group_id, environment_id=event.get_environment().id)\n updated_reports += 1\n\n if not samples and len(reports) <= 10:\n samples = {\n \"project_id\": project_id,\n \"event_ids\": event_ids,\n \"reports_event_ids\": {r.id: r.event_id for r in reports},\n }\n\n logger.info(\n \"update_user_reports.records_updated\",\n extra={\n \"reports_to_update\": total_reports,\n \"updated_reports\": updated_reports,\n \"samples\": samples,\n },\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def autofocus(self):\n\n\t\tdef move(x):\n\t\t\tif x > 0:\n\t\t\t\tself.diseqccommand(\"moveEast\", (-x) & 0xFF)\n\t\t\telif x < 0:\n\t\t\t\tself.diseqccommand(\"moveWest\", x & 0xFF)\n\t\t\tif x != 0:\n\t\t\t\ttime = int(abs(x) * self.tuningstepsize / turningspeed + 2 * self.TURNING_START_STOP_DELAY)\n\t\t\t\tsleep(time * self.MAX_LOW_RATE_ADAPTER_COUNT)\n\n\t\tdef reportlevels(pos, level, lock):\n\t\t\tprint(\"Signal quality [%2d] : %6.2f\" % (pos, level), file=log)\n\t\t\tprint(\"Lock ratio [%2d] : %6.2f\" % (pos, lock), file=log)\n\n\t\tdef optimise(readings):\n\t\t\txi = list(readings.keys())\n\t\t\tyi = [x_y1[0] for x_y1 in list(readings.values())]\n\t\t\tx0 = int(round(sum(map(mul, xi, yi)) / sum(yi)))\n\t\t\txm = xi[yi.index(max(yi))]\n\t\t\treturn x0, xm\n\n\t\tdef toGeoposEx(x):\n\t\t\tif x < 0:\n\t\t\t\treturn _(\"west\")\n\t\t\telse:\n\t\t\t\treturn _(\"east\")\n\n\t\tself.logMsg(_(\"Auto focus commencing ...\"))\n\t\tturningspeed = self.getTurningspeed()\n\t\tmeasurements = {}\n\t\tmaxsteps = max(min(round(self.MAX_FOCUS_ANGLE / self.tuningstepsize), 0x1F), 3)\n\t\tself.measure()\n\t\tprint(\"Initial signal quality: %6.2f\" % self.snr_percentage, file=log)\n\t\tprint(\"Initial lock ratio : %6.2f\" % self.lock_count, file=log)\n\t\tif self.lock_count < 1 - self.LOCK_LIMIT:\n\t\t\tmsg = _(\"There is no signal to lock on !\")\n\t\t\tself.printMsg(msg)\n\t\t\tself.statusMsg(\"\")\n\t\t\tself.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout=5)\n\t\t\treturn\n\t\tprint(\"Signal OK, proceeding\", file=log)\n\t\tx = 0\n\t\tdirection = 1\n\t\tif self.randomBool():\n\t\t\tdirection = -direction\n\t\tmeasurements[x] = (self.snr_percentage, self.lock_count)\n\t\tnsteps = 0\n\t\twhile nsteps < maxsteps:\n\t\t\tx += direction\n\t\t\tself.statusMsg((_(\"Moving\") + \" \" + toGeoposEx(direction) + \" %2d\") % abs(x), blinking=True)\n\t\t\tmove(direction) \t\t# one step\n\t\t\tself.measure()\n\t\t\tmeasurements[x] = (self.snr_percentage, self.lock_count)\n\t\t\treportlevels(x, self.snr_percentage, self.lock_count)\n\t\t\tif self.lock_count < self.LOCK_LIMIT:\n\t\t\t\tbreak\n\t\t\tnsteps += 1\n\t\telse:\n\t\t\tmsg = _(\"Cannot determine %s limit ..., aborting !\") % toGeoposEx(direction)\n\t\t\tself.printMsg(msg)\n\t\t\tself.statusMsg(\"\")\n\t\t\tself.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout=5)\n\t\t\treturn\n\t\tdirection = -direction\n\t\tself.statusMsg(_(\"Moving\") + \" \" + toGeoposEx(direction) + \" 0\", blinking=True)\n\t\tmove(-x)\n\t\tif not self.sync():\n\t\t\tmsg = _(\"Sync failure moving back to origin !\")\n\t\t\tself.printMsg(msg)\n\t\t\tself.statusMsg(\"\")\n\t\t\tself.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout=5)\n\t\t\treturn\n\t\tx = 0\n\t\tnsteps = 0\n\t\twhile nsteps < maxsteps:\n\t\t\tx += direction\n\t\t\tself.statusMsg((_(\"Moving\") + \" \" + toGeoposEx(direction) + \" %2d\") % abs(x), blinking=True)\n\t\t\tmove(direction) \t\t# one step\n\t\t\tself.measure()\n\t\t\tmeasurements[x] = (self.snr_percentage, self.lock_count)\n\t\t\treportlevels(x, self.snr_percentage, self.lock_count)\n\t\t\tif self.lock_count < self.LOCK_LIMIT:\n\t\t\t\tbreak\n\t\t\tnsteps += 1\n\t\telse:\n\t\t\tmsg = _(\"Cannot determine %s limit ..., aborting !\") % toGeoposEx(direction)\n\t\t\tself.printMsg(msg)\n\t\t\tself.statusMsg(\"\")\n\t\t\tself.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout=5)\n\t\t\treturn\n\t\t(x0, xm) = optimise(measurements)\n\t\tprint(\"Weighted position : %2d\" % x0, file=log)\n\t\tprint(\"Strongest position : %2d\" % xm, file=log)\n\t\tself.logMsg((_(\"Final position at index\") + \" %2d (%5.1f\" + chr(176) + \")\") % (x0, x0 * self.tuningstepsize), timeout=6)\n\t\tmove(x0 - x)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def handle_exception(\n self,\n request: Request,\n exc: Exception,\n handler_context: MutableMapping[str, Any] | None = None,\n scope: Scope | None = None,\n ) -> Response:\n handler_context = handler_context or {}\n scope = scope or Scope()\n\n if isinstance(exc, (AtlassianConnectValidationError, JiraTokenError)):\n return self.respond(status=status.HTTP_409_CONFLICT)\n\n # Atlassian has an automated tool which tests to make sure integrations with Jira\n # (like ours) pass certain security requirements, which leads them to probe certain\n # of our endpoints to make sure we're not accepting insecure GET requests. Not\n # actionable on our part and therefore not worth sending to Sentry.\n if isinstance(\n exc, MethodNotAllowed\n ) and \"github.com/atlassian-labs/connect-security-req-tester\" in request.headers.get(\n \"User-Agent\", \"\"\n ):\n logger.info(\n \"Atlassian Connect Security Request Tester tried disallowed method\",\n extra={\"path\": request.path, \"method\": request.method},\n )\n return self.respond(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n # Handle and clean up known errors, and flag unknown ones by logging an exception\n if isinstance(exc, ApiError):\n # Pull off \"com.atlassian.jira.issue:sentry.io.jira:sentry-issues-glance:status\"\n # and the like - what we really care about is which Jira API endpoint we were\n # trying to hit\n jira_api_endpoint = (\n exc.path.split(\"com.atlassian.jira\")[0] if exc.path else \"[unknown endpoint]\"\n )\n\n scope.set_tag(\"jira.host\", exc.host)\n scope.set_tag(\"jira.endpoint\", jira_api_endpoint)\n\n # If the error message is a big mess of html or xml, move it to `handler_context`\n # so we can see it if we need it, but also can replace the error message\n # with a much more helpful one\n if \"doctype html\" in exc.text.lower() or \"<html\" in exc.text.lower():\n handler_context[\"html_response\"] = exc.text\n elif \"<?xml\" in exc.text.lower():\n handler_context[\"xml_response\"] = exc.text\n\n if handler_context.get(\"html_response\") or handler_context.get(\"xml_response\"):\n if exc.code == 401:\n exc.text = f\"Unauthorized request to {jira_api_endpoint}\"\n elif exc.code == 429:\n exc.text = f\"Rate limit hit when requesting {jira_api_endpoint}\"\n # TODO: The two 500s might be better as metrics rather than ending up as events\n # in Sentry\n elif exc.code == 502:\n exc.text = f\"Bad gateway when connecting to {jira_api_endpoint}\"\n elif exc.code == 504:\n exc.text = f\"Gateway timeout when connecting to {jira_api_endpoint}\"\n else: # generic ApiError\n exc.text = f\"Unknown error when requesting {jira_api_endpoint}\"\n logger.error(\"Unclear JIRA exception\")\n\n # OperationalErrors are errors talking to our postgres DB\n elif isinstance(exc, OperationalError):\n pass # No processing needed and these are known errors\n else:\n logger.error(\"Unclear JIRA exception\")\n\n # This will log the error locally, capture the exception and send it to Sentry, and create a\n # generic 500/Internal Error response\n return super().handle_exception(request, exc, handler_context, scope)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def displayInformation(self):\n\t\tdef formatNumber(number):\n\t\t\tnumber = number.strip()\n\t\t\tvalue, units = number.split(maxsplit=1) if \" \" in number else (number, None)\n\t\t\tif \".\" in value:\n\t\t\t\tformat = \"%.3f\"\n\t\t\t\tvalue = float(value)\n\t\t\telse:\n\t\t\t\tformat = \"%d\"\n\t\t\t\tvalue = int(value)\n\t\t\treturn f\"{format_string(format, value, grouping=True)} {units}\" if units else format_string(format, value, grouping=True)\n\n\t\tinfo = []\n\t\tinfo.append(formatLine(\"H\", _(\"Memory information for %s %s\") % getBoxDisplayName()))\n\t\tinfo.append(\"\")\n\t\tmemInfo = fileReadLines(\"/proc/meminfo\", source=MODULE_NAME)\n\t\tinfo.append(formatLine(\"S\", _(\"RAM (Summary)\")))\n\t\tif self.extraSpacing:\n\t\t\tinfo.append(\"\")\n\t\tfor line in memInfo:\n\t\t\tkey, value = (x for x in line.split(maxsplit=1))\n\t\t\tif key == \"MemTotal:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Total memory\"), formatNumber(value)))\n\t\t\telif key == \"MemFree:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Free memory\"), formatNumber(value)))\n\t\t\telif key == \"Buffers:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Buffers\"), formatNumber(value)))\n\t\t\telif key == \"Cached:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Cached\"), formatNumber(value)))\n\t\t\telif key == \"SwapTotal:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Total swap\"), formatNumber(value)))\n\t\t\telif key == \"SwapFree:\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Free swap\"), formatNumber(value)))\n\t\tinfo.append(\"\")\n\t\tinfo.append(formatLine(\"S\", _(\"FLASH\")))\n\t\tif self.extraSpacing:\n\t\t\tinfo.append(\"\")\n\t\tstat = statvfs(\"/\")\n\t\tdiskSize = stat.f_blocks * stat.f_frsize\n\t\tdiskFree = stat.f_bfree * stat.f_frsize\n\t\tdiskUsed = diskSize - diskFree\n\t\tinfo.append(formatLine(\"P1\", _(\"Total flash\"), f\"{scaleNumber(diskSize)} ({scaleNumber(diskSize, 'Iec')})\"))\n\t\tinfo.append(formatLine(\"P1\", _(\"Used flash\"), f\"{scaleNumber(diskUsed)} ({scaleNumber(diskUsed, 'Iec')})\"))\n\t\tinfo.append(formatLine(\"P1\", _(\"Free flash\"), f\"{scaleNumber(diskFree)} ({scaleNumber(diskFree, 'Iec')})\"))\n\t\tinfo.append(\"\")\n\t\tinfo.append(formatLine(\"S\", _(\"RAM (Details)\")))\n\t\tif self.extraSpacing:\n\t\t\tinfo.append(\"\")\n\t\tfor line in memInfo:\n\t\t\tkey, value = (x for x in line.split(maxsplit=1))\n\t\t\tinfo.append(formatLine(\"P1\", key[:-1], formatNumber(value)))\n\t\tinfo.append(\"\")\n\t\tinfo.append(formatLine(\"M1\", _(\"The detailed information is intended for developers only.\")))\n\t\tinfo.append(formatLine(\"M1\", _(\"Please don't panic if you see values that look suspicious.\")))\n\t\tself[\"information\"].setText(\"\\n\".join(info))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def __iter__(self):\n if self.min_value is not None:\n cur_value = self.min_value\n else:\n cur_value = None\n\n num = 0\n limit = self.limit\n\n queryset = self.queryset\n if self.desc:\n queryset = queryset.order_by(\"-%s\" % self.order_by)\n else:\n queryset = queryset.order_by(self.order_by)\n\n # we implement basic cursor pagination for columns that are not unique\n last_object_pk: int | None = None\n has_results = True\n while has_results:\n if limit and num >= limit:\n break\n\n start = num\n\n if cur_value is None:\n results = queryset\n elif self.desc:\n results = queryset.filter(**{\"%s__lte\" % self.order_by: cur_value})\n else:\n results = queryset.filter(**{\"%s__gte\" % self.order_by: cur_value})\n\n results = list(results[0 : self.step])\n\n for cb in self.callbacks:\n cb(results)\n\n for result in results:\n pk = self.result_value_getter(result) if self.result_value_getter else result.pk\n if last_object_pk is not None and pk == last_object_pk:\n continue\n\n # Need to bind value before yielding, because the caller\n # may mutate the value and we're left with a bad value.\n # This is commonly the case if iterating over and\n # deleting, because a Model.delete() mutates the `id`\n # to `None` causing the loop to exit early.\n num += 1\n last_object_pk = pk\n cur_value = (\n self.result_value_getter(result)\n if self.result_value_getter\n else getattr(result, self.order_by)\n )\n\n yield result\n\n if cur_value is None:\n break\n\n has_results = num > start", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def updateSize(self):\n\t\tsize = self.project.size / (1024 * 1024)\n\t\tMAX_DL = self.project.MAX_DL - 100\n\t\tMAX_SL = self.project.MAX_SL - 100\n\t\tMAX_BD = self.project.MAX_BD - 200\n\t\tself[\"space_bar_bludisc\"].value = 100 * size / (MAX_BD)\n\n\t\tif self.project.settings.authormode.value == \"bdmv\":\n\t\t\tpercent = 100 * size / float(MAX_BD)\n\t\t\tself[\"space_label\"].text = \"%d MB (%.2f%%)\" % (size, percent)\n\n\t\t\tif size > MAX_BD:\n\t\t\t\tself[\"medium_label\"].setText(_(\"Exceeds Blu-ray disc medium!\"))\n\t\t\t\tself[\"medium_label\"].setForegroundColorNum(2)\n\t\t\t\tif self.previous_size < MAX_BD:\n\t\t\t\t\tself.session.open(MessageBox, text=_(\"Exceeds Blu-ray disc medium!\"), type=MessageBox.TYPE_ERROR)\n\t\t\telif size < MAX_BD:\n\t\t\t\tself[\"medium_label\"].setText(_(\"Required medium type:\") + \" \" + _(\"BLUDISC RECORDABLE\") + \", %d MB \" % (MAX_BD - size) + _(\"free\"))\n\t\t\t\tself[\"medium_label\"].setForegroundColorNum(1)\n\t\telse:\n\t\t\tif size > MAX_DL:\n\t\t\t\tpercent = 100 * size / float(MAX_DL)\n\t\t\t\tself[\"space_label\"].text = \"%d MB (%.2f%%)\" % (size, percent)\n\t\t\t\tself[\"medium_label\"].setText(_(\"Exceeds dual layer medium!\"))\n\t\t\t\tself[\"medium_label\"].setForegroundColorNum(2)\n\t\t\t\tif self.previous_size < MAX_DL:\n\t\t\t\t\tself.session.open(MessageBox, text=_(\"Exceeds dual layer medium!\"), type=MessageBox.TYPE_ERROR)\n\t\t\telif size > MAX_SL:\n\t\t\t\tpercent = 100 * size / float(MAX_DL)\n\t\t\t\tself[\"space_label\"].text = \"%d MB (%.2f%%)\" % (size, percent)\n\t\t\t\tself[\"medium_label\"].setText(_(\"Required medium type:\") + \" \" + _(\"DUAL LAYER DVD\") + \", %d MB \" % (MAX_DL - size) + _(\"free\"))\n\t\t\t\tself[\"medium_label\"].setForegroundColorNum(1)\n\t\t\t\tif self.previous_size < MAX_SL:\n\t\t\t\t\tself.session.open(MessageBox, text=_(\"Your collection exceeds the size of a single layer medium, you will need a blank dual layer DVD!\"), timeout=10, type=MessageBox.TYPE_INFO)\n\t\t\telif size < MAX_SL:\n\t\t\t\tpercent = 100 * size / float(MAX_SL)\n\t\t\t\tself[\"space_label\"].text = \"%d MB (%.2f%%)\" % (size, percent)\n\t\t\t\tself[\"medium_label\"].setText(_(\"Required medium type:\") + \" \" + _(\"SINGLE LAYER DVD\") + \", %d MB \" % (MAX_SL - size) + _(\"free\"))\n\t\t\t\tself[\"medium_label\"].setForegroundColorNum(0)\n\t\tself.previous_size = size", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def getSatelliteName(self, ref):\n\t\tif isinstance(ref, eServiceReference):\n\t\t\torbpos = ref.getUnsignedData(4) >> 16\n\t\t\tif orbpos == 0xFFFF: # Cable\n\t\t\t\treturn _(\"Cable\")\n\t\t\telif orbpos == 0xEEEE: # Terrestrial\n\t\t\t\treturn _(\"Terrestrial\")\n\t\t\telse: # Satellite\n\t\t\t\torbpos = ref.getData(4) >> 16\n\t\t\t\tif orbpos < 0:\n\t\t\t\t\torbpos += 3600\n\t\t\t\ttry:\n\t\t\t\t\tfrom Components.NimManager import nimmanager\n\t\t\t\t\treturn str(nimmanager.getSatDescription(orbpos))\n\t\t\t\texcept Exception:\n\t\t\t\t\tdir = ref.flags & (eServiceReference.isDirectory | eServiceReference.isMarker)\n\t\t\t\t\tif not dir:\n\t\t\t\t\t\trefString = ref.toString().lower()\n\t\t\t\t\t\tif refString.startswith(\"-1\"):\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\t\telif refString.startswith(\"1:134:\"):\n\t\t\t\t\t\t\treturn _(\"Alternative\")\n\t\t\t\t\t\telif refString.startswith(\"4097:\"):\n\t\t\t\t\t\t\treturn _(\"Internet\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treturn orbpos > 1800 and f\"{(3600 - orbpos) // 10}.{(3600 - orbpos) % 10}\u00b0W\" or f\"{orbpos // 10}.{orbpos % 10}\u00b0E\"\n\t\treturn \"\"", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def check_version(version1: str, version2: str) -> VersionCheck:\n \"\"\"\n Checks first string in regard to second string\n Output: VersionCheck.{SMALLER,SMALLER_EQUAL,EQUAL,GREATER_EQUAL,GREATER,UNKNOWN}\n \"\"\"\n\n # Split the version until first dot\n version1_split = version1.split(\".\", 1)\n version2_split = version2.split(\".\", 1)\n\n # Check versions until first dot\n v1 = version1_split[0]\n v2 = version2_split[0]\n if v1 != v2 and v1.isnumeric() and v2.isnumeric():\n if int(v1) < int(v2):\n return VersionCheck.SMALLER\n elif int(v1) > int(v2):\n return VersionCheck.GREATER_EQUAL\n elif v1 != v2:\n # Check for packages, because we cannot compare those on name only (can start with version)\n pack1 = re.split(\"[+-]\", v1)\n pack2 = re.split(\"[+-]\", v2)\n if pack1[0].isnumeric() and pack2[0].isnumeric():\n # Has a package-name, but it starts with version-numbers # https://snyk.io/vuln/debian%3A12%3Awordpress\n first_part_check = check_version(pack1[0], pack2[0])\n if first_part_check != VersionCheck.EQUAL:\n return first_part_check\n else:\n # Version is the same, but package different.. impossible to compare\n return VersionCheck.UNKNOWN\n elif (len(pack1) > 1 or len(pack2) > 1) and v1 != v2:\n # They have different packages, impossible to compare\n return VersionCheck.UNKNOWN\n else:\n # The same package name or no packages at all but versionname is non-numeric\n if v1 < v2:\n return VersionCheck.SMALLER\n elif v2 > v1:\n return VersionCheck.GREATER\n\n # Check part after the first dot\n if len(version1_split) == 1 and len(version2_split) == 1:\n # This was the last part\n return VersionCheck.EQUAL\n elif len(version1_split) == 1:\n # version 1 < version 1.1\n return VersionCheck.SMALLER\n elif len(version2_split) == 1:\n # version 1 > version 1.1\n return VersionCheck.GREATER\n else:\n # Compare next part of version\n return check_version(version1_split[1], version2_split[1])", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def format(self, fmt: str, *args: Any) -> str:\n \"\"\"Helper for formatting strings.\n\n These format sequences are supported in fmt:\n\n %s: arbitrary object converted to string using str()\n %r: name of IR value/register\n %d: int\n %f: float\n %l: BasicBlock (formatted as label 'Ln')\n %t: RType\n \"\"\"\n result = []\n i = 0\n arglist = list(args)\n while i < len(fmt):\n n = fmt.find(\"%\", i)\n if n < 0:\n n = len(fmt)\n result.append(fmt[i:n])\n if n < len(fmt):\n typespec = fmt[n + 1]\n arg = arglist.pop(0)\n if typespec == \"r\":\n # Register/value\n assert isinstance(arg, Value)\n if isinstance(arg, Integer):\n result.append(str(arg.value))\n elif isinstance(arg, Float):\n result.append(repr(arg.value))\n else:\n result.append(self.names[arg])\n elif typespec == \"d\":\n # Integer\n result.append(\"%d\" % arg)\n elif typespec == \"f\":\n # Float\n result.append(\"%f\" % arg)\n elif typespec == \"l\":\n # Basic block (label)\n assert isinstance(arg, BasicBlock)\n result.append(\"L%s\" % arg.label)\n elif typespec == \"t\":\n # RType\n assert isinstance(arg, RType)\n result.append(arg.name)\n elif typespec == \"s\":\n # String\n result.append(str(arg))\n else:\n raise ValueError(f\"Invalid format sequence %{typespec}\")\n i = n + 2\n else:\n i = n\n return \"\".join(result)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def selectCamProvider(self):\n\t\tdef selectCamProvidercallback(answer):\n\t\t\tif answer:\n\t\t\t\tautocam.selectCams(services, answer)\n\t\t\tself.close()\n\n\t\tservice = self.csel.getCurrentSelection()\n\t\tif service:\n\t\t\tname = service.getName()\n\t\t\tservices = self.csel.getRefsforProvider()\n\t\t\tif services:\n\t\t\t\tfrom Screens.InfoBarGenerics import autocam\n\t\t\t\tcams = BoxInfo.getItem(\"Softcams\")\n\t\t\t\tif len(cams) > 2 and \"None\" in cams:\n\t\t\t\t\tchoiceList = []\n\t\t\t\t\tcurrentcam = BoxInfo.getItem(\"CurrentSoftcam\")\n\t\t\t\t\tdefaultcam = config.misc.autocamDefault.value\n\t\t\t\t\tfor idx, cam in enumerate(cams):\n\t\t\t\t\t\tdesc = cam\n\t\t\t\t\t\tif cam == currentcam:\n\t\t\t\t\t\t\tdesc = f\"{desc} ({_('Current')})\"\n\t\t\t\t\t\tif cam == defaultcam:\n\t\t\t\t\t\t\tdesc = f\"{desc} ({_('Default')})\"\n\t\t\t\t\t\tif cam == \"None\":\n\t\t\t\t\t\t\tdesc = _(\"Remove\")\n\t\t\t\t\t\tchoiceList.append((desc, cam))\n\t\t\t\t\tif choiceList:\n\t\t\t\t\t\tmessage = _(\"Select the Softcam for '%s'\" % name)\n\t\t\t\t\t\tself.session.openWithCallback(selectCamProvidercallback, MessageBox, message, list=choiceList)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def handle(self, include_pattern, org_ids, org_limits, num_requests, results_file, results_html, *args, **options):\n self.client = Client()\n started = datetime.utcnow()\n\n prev_times = self.load_previous_times(results_file)\n\n if not prev_times:\n self.stdout.write(self.style.WARNING(\"No previous results found for change calculation\"))\n\n # gather which orgs will be tested\n if org_ids:\n test_orgs = list(Org.objects.filter(id__in=org_ids.split(\",\")).order_by(\"id\"))\n else:\n test_orgs = [Org.objects.first(), Org.objects.last()]\n\n # gather org specific maximum time limits\n if org_limits:\n org_allowed_maximums = [int(l) for l in org_limits.split(\",\")]\n if len(org_allowed_maximums) != len(test_orgs):\n raise CommandError(\"%d time limits provided for %d orgs\" % (len(org_limits), len(test_orgs)))\n else:\n org_allowed_maximums = [DEFAULT_ALLOWED_MAXIMUM] * len(test_orgs)\n\n test_urls = [u for u in TEST_URLS if not include_pattern or fnmatch.fnmatch(u, include_pattern)]\n\n results = []\n\n for o, org in enumerate(test_orgs):\n org.allowed_max = org_allowed_maximums[o]\n\n # look for previous times for this org\n prev_org_times = prev_times.get(org.id, {})\n\n results.append(self.test_org(org, test_urls, num_requests, prev_org_times))\n\n self.save_results(results_file, started, results)\n\n if results_html:\n self.save_html_results(results_html, results)\n\n # exit with no-zero code if any test for any org failed\n for result in results:\n for test in result[\"tests\"]:\n if not test.is_pass():\n sys.exit(1)", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def ParseOperationAndRepresentationPair(self, ioPipeAndViewsState, ioJson,\n inOperationKey, inSkipIfOperationKeyNotPresent,\n inRepresentationKey, inRepresentationKeyRequired,\n inAllowPairFromAnotherSource):\n \"parse out the operation and associated representation from the\\n given json; also optionally throw exception if representation\\n is not given. Used to get multiple visible operation/representation\\n pairs\"\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriImagesetBlock::\"\n \"ParseOperationAndRepresentationPair entered\\n\")\n myDebugPrint3(\n \"inOperationKey: \" + str(inOperationKey) + \"\\n\"\n \"inRepresentationKey: \" + str(inRepresentationKey) + \"\\n\"\n \"incoming json:\\n\" + str(ioJson) + \"\\n\")\n \n\n if inOperationKey not in ioJson:\n if inSkipIfOperationKeyNotPresent:\n return\n\n if inRepresentationKeyRequired == False and \\\n inRepresentationKey not in ioJson:\n #we have to construct and use a default representation, including parsing\n #commands in the imageset for the representation\n if PhactoriDbg():\n myDebugPrint3(\" ParseOperationAndRepresentationPair: for imageset \" + \\\n self.mName + \\\n \" there is no representation, \" +\n \"so we must add and reference default\\n\")\n defaultRepName = self.mName + '_default_representation'\n defaultRepBlockAndWrapper = {defaultRepName: ioJson}\n ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,\n defaultRepBlockAndWrapper,\n PhactoriRepresentationBlock,\n ParseOneRepresentationBlockC,\n ioPipeAndViewsState)\n ioJson[inRepresentationKey] = defaultRepName\n\n pipeForPair = None\n if inAllowPairFromAnotherSource:\n anotherVisOperation, pipeForPair = ioPipeAndViewsState. \\\n GetOperationReferredByJsonCrossPipe(inOperationKey, ioJson)\n else:\n anotherVisOperation = ioPipeAndViewsState.GetOperationReferredByJson(\n inOperationKey, ioJson)\n\n self.mVisibleOps.append(anotherVisOperation)\n\n anotherVisRepresentation = None\n if inRepresentationKey in ioJson:\n pipeForRepresentation = ioPipeAndViewsState\n if pipeForPair != None:\n pipeForRepresentation = pipeForPair\n representationName = ioJson[inRepresentationKey]\n if representationName not in pipeForRepresentation.mRepresentationBlocks:\n errStr = \"ParseOperationAndRepresentationPair::exeception/error\\n\" + \\\n \" imageset (\" + str(self.mName) + \\\n \") calls for representation (\" + \\\n str(representationName) + \") which does not exist\\n\"\n myDebugPrint3AndException(errStr)\n else:\n anotherVisRepresentation = \\\n pipeForRepresentation.mRepresentationBlocks[representationName]\n\n if anotherVisRepresentation == None:\n #at this point we should have a representation--if we don't it\n #was required to be set but not set\n myDebugPrint3AndException(\\\n \"PhactoriImagesetBlock::ParseOperationAndRepresentationPair\\n\"\n \"Exception/Error: operation missing required corresponding\\n\"\n \"repesentation.\\noperation key: \" + inOperationKey + \"\\n\"\n \"missing representation key: \" + inRepresentationKey + \"\\n\")\n\n self.mVisibleReps.append(anotherVisRepresentation)\n self.mVisiblePvDataReps.append(None)\n self.mColorLegendRepRefs.append(None)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def parse_options_header(value: str | None) -> tuple[str, dict[str, str]]:\n \"\"\"Parse a header that consists of a value with ``key=value`` parameters separated\n by semicolons ``;``. For example, the ``Content-Type`` header.\n\n .. code-block:: python\n\n parse_options_header(\"text/html; charset=UTF-8\")\n ('text/html', {'charset': 'UTF-8'})\n\n parse_options_header(\"\")\n (\"\", {})\n\n This is the reverse of :func:`dump_options_header`.\n\n This parses valid parameter parts as described in\n `RFC 9110 <https://httpwg.org/specs/rfc9110.html#parameter>`__. Invalid parts are\n skipped.\n\n This handles continuations and charsets as described in\n `RFC 2231 <https://www.rfc-editor.org/rfc/rfc2231#section-3>`__, although not as\n strictly as the RFC. Only ASCII, UTF-8, and ISO-8859-1 charsets are accepted,\n otherwise the value remains quoted.\n\n Clients may not be consistent in how they handle a quote character within a quoted\n value. The `HTML Standard <https://html.spec.whatwg.org/#multipart-form-data>`__\n replaces it with ``%22`` in multipart form data.\n `RFC 9110 <https://httpwg.org/specs/rfc9110.html#quoted.strings>`__ uses backslash\n escapes in HTTP headers. Both are decoded to the ``\"`` character.\n\n Clients may not be consistent in how they handle non-ASCII characters. HTML\n documents must declare ``<meta charset=UTF-8>``, otherwise browsers may replace with\n HTML character references, which can be decoded using :func:`html.unescape`.\n\n :param value: The header value to parse.\n :return: ``(value, options)``, where ``options`` is a dict\n\n .. versionchanged:: 2.3\n Invalid parts, such as keys with no value, quoted keys, and incorrectly quoted\n values, are discarded instead of treating as ``None``.\n\n .. versionchanged:: 2.3\n Only ASCII, UTF-8, and ISO-8859-1 are accepted for charset values.\n\n .. versionchanged:: 2.3\n Escaped quotes in quoted values, like ``%22`` and ``\\\\\"``, are handled.\n\n .. versionchanged:: 2.2\n Option names are always converted to lowercase.\n\n .. versionchanged:: 2.2\n The ``multiple`` parameter was removed.\n\n .. versionchanged:: 0.15\n :rfc:`2231` parameter continuations are handled.\n\n .. versionadded:: 0.5\n \"\"\"\n if value is None:\n return \"\", {}\n\n value, _, rest = value.partition(\";\")\n value = value.strip()\n rest = rest.strip()\n\n if not value or not rest:\n # empty (invalid) value, or value without options\n return value, {}\n\n rest = f\";{rest}\"\n options: dict[str, str] = {}\n encoding: str | None = None\n continued_encoding: str | None = None\n\n for pk, pv in _parameter_re.findall(rest):\n if not pk:\n # empty or invalid part\n continue\n\n pk = pk.lower()\n\n if pk[-1] == \"*\":\n # key*=charset''value becomes key=value, where value is percent encoded\n pk = pk[:-1]\n match = _charset_value_re.match(pv)\n\n if match:\n # If there is a valid charset marker in the value, split it off.\n encoding, pv = match.groups()\n # This might be the empty string, handled next.\n encoding = encoding.lower()\n\n # No charset marker, or marker with empty charset value.\n if not encoding:\n encoding = continued_encoding\n\n # A safe list of encodings. Modern clients should only send ASCII or UTF-8.\n # This list will not be extended further. An invalid encoding will leave the\n # value quoted.\n if encoding in {\"ascii\", \"us-ascii\", \"utf-8\", \"iso-8859-1\"}:\n # Continuation parts don't require their own charset marker. This is\n # looser than the RFC, it will persist across different keys and allows\n # changing the charset during a continuation. But this implementation is\n # much simpler than tracking the full state.\n continued_encoding = encoding\n # invalid bytes are replaced during unquoting\n pv = unquote(pv, encoding=encoding)\n\n # Remove quotes. At this point the value cannot be empty or a single quote.\n if pv[0] == pv[-1] == '\"':\n # HTTP headers use slash, multipart form data uses percent\n pv = pv[1:-1].replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"').replace(\"%22\", '\"')\n\n match = _continuation_re.search(pk)\n\n if match:\n # key*0=a; key*1=b becomes key=ab\n pk = pk[: match.start()]\n options[pk] = options.get(pk, \"\") + pv\n else:\n options[pk] = pv\n\n return value, options", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def serialize(self, obj, attrs, user, **kwargs) -> RuleSerializerResponse:\n environment = attrs[\"environment\"]\n all_conditions = [\n dict(list(o.items()) + [(\"name\", generate_rule_label(obj.project, obj, o))])\n for o in obj.data.get(\"conditions\", [])\n ]\n\n actions = []\n for action in obj.data.get(\"actions\", []):\n try:\n actions.append(\n dict(\n list(action.items())\n + [(\"name\", generate_rule_label(obj.project, obj, action))]\n )\n )\n except serializers.ValidationError:\n # Integrations can be deleted and we don't want to fail to load the rule\n pass\n\n d = {\n # XXX(dcramer): we currently serialize unsaved rule objects\n # as part of the rule editor\n \"id\": str(obj.id) if obj.id else None,\n # conditions pertain to criteria that can trigger an alert\n \"conditions\": list(filter(lambda condition: not _is_filter(condition), all_conditions)),\n # filters are not new conditions but are the subset of conditions that pertain to event attributes\n \"filters\": list(filter(lambda condition: _is_filter(condition), all_conditions)),\n \"actions\": actions,\n \"actionMatch\": obj.data.get(\"action_match\") or Rule.DEFAULT_CONDITION_MATCH,\n \"filterMatch\": obj.data.get(\"filter_match\") or Rule.DEFAULT_FILTER_MATCH,\n \"frequency\": obj.data.get(\"frequency\") or Rule.DEFAULT_FREQUENCY,\n \"name\": obj.label,\n \"dateCreated\": obj.date_added,\n \"owner\": attrs.get(\"owner\", None),\n \"createdBy\": attrs.get(\"created_by\", None),\n \"environment\": environment.name if environment is not None else None,\n \"projects\": [obj.project.slug],\n \"status\": \"active\" if obj.status == ObjectStatus.ACTIVE else \"disabled\",\n }\n if \"last_triggered\" in attrs:\n d[\"lastTriggered\"] = attrs[\"last_triggered\"]\n\n if \"errors\" in attrs:\n d[\"errors\"] = attrs[\"errors\"]\n\n if \"snooze\" in attrs:\n snooze = attrs[\"snooze\"]\n d[\"snooze\"] = True\n created_by = None\n if user.id == snooze.get(\"owner_id\"):\n created_by = \"You\"\n elif owner_id := snooze.get(\"owner_id\"):\n creator = user_service.get_user(owner_id)\n if creator:\n created_by = creator.get_display_name()\n\n if created_by is not None:\n d[\"snoozeCreatedBy\"] = created_by\n d[\"snoozeForEveryone\"] = snooze.get(\"user_id\") is None\n else:\n d[\"snooze\"] = False\n\n if \"disable_date\" in attrs:\n d[\"disableReason\"] = \"noisy\"\n d[\"disableDate\"] = attrs[\"disable_date\"]\n\n return d", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def readSlotInfo(self, path): # Part of analyzeSlot() within getSlotImageList().\n\t\tinfo = {}\n\t\tlines = fileReadLines(path, source=MODULE_NAME)\n\t\tif lines:\n\t\t\tif self.checkChecksum(lines):\n\t\t\t\tprint(\"[MultiBoot] WARNING: Enigma information file found but checksum is incorrect!\")\n\t\t\tfor line in lines:\n\t\t\t\tif line.startswith(\"#\") or line.strip() == \"\":\n\t\t\t\t\tcontinue\n\t\t\t\tif \"=\" in line:\n\t\t\t\t\titem, value = (x.strip() for x in line.split(\"=\", 1))\n\t\t\t\t\tif item:\n\t\t\t\t\t\tinfo[item] = self.processValue(value)\n\t\tlines = fileReadLines(path.replace(\".info\", \".conf\"), source=MODULE_NAME)\n\t\tif lines:\n\t\t\tfor line in lines:\n\t\t\t\tif line.startswith(\"#\") or line.strip() == \"\":\n\t\t\t\t\tcontinue\n\t\t\t\tif \"=\" in line:\n\t\t\t\t\titem, value = (x.strip() for x in line.split(\"=\", 1))\n\t\t\t\t\tif item:\n\t\t\t\t\t\tif item in info:\n\t\t\t\t\t\t\tprint(f\"[MultiBoot] Note: Enigma information value '{item}' with value '{info[item]}' being overridden to '{value}'.\")\n\t\t\t\t\t\tinfo[item] = self.processValue(value)\n\t\treturn info", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_contributor_fields(self, facility):\n request = self.context.get('request') \\\n if self.context is not None else []\n if request is None or request.query_params is None:\n return []\n\n embed = request.query_params.get('embed')\n contributor_id = request.query_params.get('contributor', None)\n if not embed == '1' or contributor_id is None:\n return []\n\n contributor_data_json = None\n if len(facility.custom_field_info) > 0:\n for custom_field_info in facility.custom_field_info:\n if custom_field_info['contributor_id'] == int(contributor_id):\n contributor_data_json = custom_field_info\n break\n\n if contributor_data_json is not None:\n try:\n contributor_fields = []\n embed_fields = contributor_data_json['embed_field']\n embed_display_fields = contributor_data_json[\n 'embed_display_field'\n ]\n # If there are any configured fields to apply\n if (len(embed_fields) > 0\n and len(embed_display_fields) == len(embed_fields)):\n for index in range(0, len(embed_fields)):\n contributor_fields.append({\n 'label': embed_display_fields[index],\n 'value': None,\n 'column_name': embed_fields[index]\n })\n\n source_type = contributor_data_json['source_type']\n raw_data = contributor_data_json['raw_data']\n if source_type == 'SINGLE':\n data = parse_raw_data(raw_data)\n for f in contributor_fields:\n value = data.get(f['column_name'], None)\n if value is not None:\n f['value'] = value\n else:\n f['value'] = None\n else:\n list_header = contributor_data_json['list_header']\n data_values = get_csv_values(raw_data)\n list_fields = get_csv_values(list_header)\n for f in contributor_fields:\n if f['column_name'] in list_fields:\n index = list_fields.index(f['column_name'])\n if 0 <= index < len(data_values):\n value = data_values[index]\n f['value'] = value\n else:\n f['value'] = None\n else:\n f['value'] = None\n\n return [\n {\n 'value': format_numeric(f['value']),\n 'label': f['label'],\n 'fieldName': f['column_name'],\n }\n for f in contributor_fields\n ]\n except Exception:\n return []\n else:\n fields = []\n contributor = Contributor.objects.get(id=contributor_id)\n if contributor.embed_config is not None:\n config = contributor.embed_config\n # If there are any configured fields, they override the\n # defaults set above\n if EmbedField.objects.filter(embed_config=config).count() > 0:\n fields = EmbedField.objects.filter(\n embed_config=config, visible=True).order_by('order')\n\n return [\n {\n 'label': f.display_name,\n 'value': None,\n 'column_name': f.column_name\n }\n for f in fields\n ]\n else:\n return []\n else:\n return []", "smellKey": "S3776", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def validate_patch(self, to_check: any, _filter: Filter) -> bool:\n \"\"\"Apply filter on match_value.\n\n Utility function used in applying filtering to a cred\n by triggering checks according to filter specification\n\n Args:\n to_check: value to check, extracted from match\n _filter: Filter\n Return:\n bool\n\n \"\"\"\n return_val = False\n if _filter._type:\n if self.check_filter_only_type_enforced(_filter):\n if _filter._type == \"number\":\n if isinstance(to_check, (int, float)):\n return True\n elif _filter._type == \"string\":\n if isinstance(to_check, str):\n if _filter.fmt == \"date\" or _filter.fmt == \"date-time\":\n try:\n to_compare_date = self.string_to_timezone_aware_datetime(\n to_check\n )\n if isinstance(to_compare_date, datetime):\n return True\n except (ParserError, TypeError):\n return False\n else:\n return True\n else:\n if _filter._type == \"number\":\n return_val = self.process_numeric_val(to_check, _filter)\n elif _filter._type == \"string\":\n return_val = self.process_string_val(to_check, _filter)\n else:\n if _filter.enums:\n return_val = self.enum_check(val=to_check, _filter=_filter)\n if _filter.const:\n return_val = self.const_check(val=to_check, _filter=_filter)\n\n if _filter._not:\n return not return_val\n return return_val", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def SetUpViewAndRepresentationBeforeWriteImage(self, inLookDirection,\n inLookDirectionIndex):\n \"\"\"Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n immediately before WriteImage in order to set the\n camera, background color, image size, etc. up appropriately for the\n WriteImage call\"\"\"\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriImagesetBlock:\" \\\n \"SetUpViewAndRepresentationBeforeWriteImage entered \" + \\\n str(self.mName) + \"\\n\", 100)\n self.mPvDataRepresentation2.Visibility = 1\n\n pvRenderView = self.mSharedPvRenderView2\n pvDataRep = self.mPvDataRepresentation2\n\n #image size\n #pvRenderView.ViewSize = self.mImageSettings.mImageSize\n pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),\n int(self.mImageSettings.mImageSize[1])]\n\n #background color, text color, etc.\n\n theColorSettings = self.mRepresentation.mColorSettings\n\n theColorSettings.SetParaviewRvRepColors(pvRenderView, pvDataRep)\n\n phactoriRep = self.mRepresentation\n #orientation axis on or off for this 3d mesh\n if phactoriRep.mOrientationAxesFlag:\n pvRenderView.OrientationAxesVisibility = 1\n else:\n pvRenderView.OrientationAxesVisibility = 0\n\n #time annotation invisible (for 3d plot)\n timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings\n if timeAnnStngs.mVisible:\n global gPipeAndViewsState\n if gPipeAndViewsState.mTimeAnnotationPv != None:\n gPipeAndViewsState.mTimeAnnotationPv.\\\n mParaViewRepresentation.Visibility = 1\n\n #cube axes\n if phactoriRep.mDataCubeAxesFlag:\n ShowCubeAxesXX(pvRenderView, 'on', phactoriRep.mDataCubeAxesInfo)\n\n #edges/surface/wireframe\n #self.mPvDataRepresentation2.Representation = \\\n # phactoriRep.mMeshRenderControl\n self.mPvDataRepresentation2.SetRepresentationType(\n phactoriRep.mMeshRenderControl)\n\n if phactoriRep.mDoingVolumeRendering:\n if phactoriRep.mScalarOpacityUnitDistance < 0.0:\n phactoriRep.CalculateDefaultScalarOpacityUnitDistance(self.mOperation)\n if phactoriRep.mScalarOpacityUnitDistance != \\\n self.mPvDataRepresentation2.ScalarOpacityUnitDistance:\n self.mPvDataRepresentation2.ScalarOpacityUnitDistance = \\\n phactoriRep.mScalarOpacityUnitDistance\n\n #size of points\n self.mPvDataRepresentation2.PointSize = phactoriRep.mPointSize\n\n #color legend\n for oneColorLegendRepRef in self.mColorLegendRepRefs:\n if oneColorLegendRepRef != None:\n oneColorLegendRepRef.Visibility = 1\n\n #color by variable or solid color or color by block\n if inLookDirectionIndex == 0:\n #on multicamera 8 setups, we only do this on first (index 0)\n SetForCorrectColorBy(self, self.mOperation,\n self.mPvDataRepresentation2, phactoriRep, False)\n else:\n #for some reason, solid color doesn't stick between camera angles;\n #redo if it is solid color\n if phactoriRep.mColorBySolidColorFlag == True:\n SetForCorrectColorBy(self, self.mOperation,\n self.mPvDataRepresentation2, phactoriRep, False)\n\n #markers for this imageset made visible\n for oneMarker in self.mVisibleMarkers:\n oneMarker.UpdateAndMakeVisible()\n\n for oneTextAnnotation in self.mTextAnnotations:\n oneTextAnnotation.UpdateAndMakeVisible()\n\n #do extra visible operations/representations\n ii = 1\n while ii < len(self.mVisibleReps):\n oneVisOp = self.mVisibleOps[ii]\n oneVisRep = self.mVisibleReps[ii]\n oneVisPvDataRep = self.mVisiblePvDataReps[ii]\n if PhactoriDbg(100):\n myDebugPrint3(\"add extra visiblity \" + str(ii) + \" rep:\\n\" + \\\n str(oneVisPvDataRep))\n ii += 1\n\n oneVisPvDataRep.Visibility = 1\n #theColorSettings = self.mRepresentation.mColorSettings\n #theColorSettings.SetParaviewRvRepColors(pvRenderView, oneVisPvDataRep)\n\n #edges/surface/wireframe\n oneVisPvDataRep.SetRepresentationType(oneVisRep.mMeshRenderControl)\n\n if oneVisRep.mDoingVolumeRendering:\n if oneVisRep.mScalarOpacityUnitDistance < 0.0:\n oneVisRep.CalculateDefaultScalarOpacityUnitDistance(oneVisOp)\n if oneVisRep.mScalarOpacityUnitDistance != \\\n oneVisPvDataRep.ScalarOpacityUnitDistance:\n oneVisPvDataRep.ScalarOpacityUnitDistance = \\\n oneVisRep.mScalarOpacityUnitDistance\n\n\n #color legend\n #if self.mColorLegendRepRef != None:\n # self.mColorLegendRepRef.Visibility = 1\n\n #color by variable or solid color or color by block\n if inLookDirectionIndex == 0:\n #on multicamera 8 setups, we only do this on first (index 0)\n SetForCorrectColorBy(self, oneVisOp,\n oneVisPvDataRep, oneVisRep, False)\n else:\n #for some reason, solid color doesn't stick between camera angles;\n #redo if it is solid color\n if phactoriRep.mColorBySolidColorFlag == True:\n #SetForCorrectColorBy(self, self.mPvDataRepresentation2,\n # phactoriRep, False)\n SetForCorrectColorBy(self, oneVisOp,\n oneVisPvDataRep, oneVisRep, False)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"start setting camera parameters for imageset: \" + \\\n self.mName + \"\\n\", 100)\n SetParaViewRepresentationCameraParams(\n pvRenderView,\n self.mCamera,\n inLookDirection,\n self.mImageSettings,\n self.mOperation.GetPvFilter())\n if PhactoriDbg(100):\n myDebugPrint3(\"done setting camera parameters for imageset: \" + \\\n self.mName + \"\\n\", 100)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetUpViewAndRepresentationBeforeWriteImage returning\\n\",\n 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def find_module_via_source_set(self, id: str) -> ModuleSearchResult | None:\n \"\"\"Fast path to find modules by looking through the input sources\n\n This is only used when --fast-module-lookup is passed on the command line.\"\"\"\n if not self.source_set:\n return None\n\n p = self.source_set.source_modules.get(id, None)\n if p and self.fscache.isfile(p):\n # We need to make sure we still have __init__.py all the way up\n # otherwise we might have false positives compared to slow path\n # in case of deletion of init files, which is covered by some tests.\n # TODO: are there some combination of flags in which this check should be skipped?\n d = os.path.dirname(p)\n for _ in range(id.count(\".\")):\n if not any(\n self.fscache.isfile(os_path_join(d, \"__init__\" + x)) for x in PYTHON_EXTENSIONS\n ):\n return None\n d = os.path.dirname(d)\n return p\n\n idx = id.rfind(\".\")\n if idx != -1:\n # When we're looking for foo.bar.baz and can't find a matching module\n # in the source set, look up for a foo.bar module.\n parent = self.find_module_via_source_set(id[:idx])\n if parent is None or not isinstance(parent, str):\n return None\n\n basename, ext = os.path.splitext(parent)\n if not any(parent.endswith(\"__init__\" + x) for x in PYTHON_EXTENSIONS) and (\n ext in PYTHON_EXTENSIONS and not self.fscache.isdir(basename)\n ):\n # If we do find such a *module* (and crucially, we don't want a package,\n # hence the filtering out of __init__ files, and checking for the presence\n # of a folder with a matching name), then we can be pretty confident that\n # 'baz' will either be a top-level variable in foo.bar, or will not exist.\n #\n # Either way, spelunking in other search paths for another 'foo.bar.baz'\n # module should be avoided because:\n # 1. in the unlikely event that one were found, it's highly likely that\n # it would be unrelated to the source being typechecked and therefore\n # more likely to lead to erroneous results\n # 2. as described in _find_module, in some cases the search itself could\n # potentially waste significant amounts of time\n return ModuleNotFoundReason.NOT_FOUND\n return None", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def create_contacts(self, orgs, locations, num_contacts):\n \"\"\"\n Creates test and regular contacts for this database. Returns tuples of org, contact id and the preferred urn\n id to avoid trying to hold all contact and URN objects in memory.\n \"\"\"\n group_counts = defaultdict(int)\n\n self._log(self.style.SUCCESS(\"OK\") + \"\\n\")\n self._log(\"Creating %d regular contacts...\\n\" % num_contacts)\n\n # disable table triggers to speed up insertion and in the case of contact group m2m, avoid having an unsquashed\n # count row for every contact\n with DisableTriggersOn(Contact, ContactURN, ContactGroup.contacts.through):\n names = [(\"%s %s\" % (c1, c2)).strip() for c2 in CONTACT_NAMES[1] for c1 in CONTACT_NAMES[0]]\n names = [n if n else None for n in names]\n\n batch_num = 1\n for index_batch in chunk_list(range(num_contacts), self.batch_size):\n batch = []\n\n # generate flat representations and contact objects for this batch\n for c_index in index_batch: # pragma: no cover\n org = self.random_org(orgs)\n name = self.random_choice(names)\n location = self.random_choice(locations) if self.probability(CONTACT_HAS_FIELD_PROB) else None\n created_on = self.timeline_date(c_index / num_contacts)\n\n status = Contact.STATUS_ACTIVE\n if self.probability(CONTACT_IS_STOPPED_PROB):\n status = Contact.STATUS_STOPPED\n elif self.probability(CONTACT_IS_BLOCKED_PROB):\n status = Contact.STATUS_BLOCKED\n\n c = {\n \"org\": org,\n \"user\": org.cache[\"users\"][0],\n \"name\": name,\n \"groups\": [],\n \"tel\": \"+2507%08d\" % c_index if self.probability(CONTACT_HAS_TEL_PROB) else None,\n \"twitter\": \"%s%d\" % (name.replace(\" \", \"_\").lower() if name else \"tweep\", c_index)\n if self.probability(CONTACT_HAS_TWITTER_PROB)\n else None,\n \"gender\": self.random_choice((\"M\", \"F\")) if self.probability(CONTACT_HAS_FIELD_PROB) else None,\n \"age\": self.random.randint(16, 80) if self.probability(CONTACT_HAS_FIELD_PROB) else None,\n \"joined\": self.random_date() if self.probability(CONTACT_HAS_FIELD_PROB) else None,\n \"ward\": location[0] if location else None,\n \"district\": location[1] if location else None,\n \"state\": location[2] if location else None,\n \"language\": self.random_choice(CONTACT_LANGS),\n \"status\": status,\n \"is_active\": self.probability(1 - CONTACT_IS_DELETED_PROB),\n \"created_on\": created_on,\n \"modified_on\": self.random_date(created_on, self.db_ends_on),\n \"fields_as_json\": {},\n }\n\n if c[\"gender\"] is not None:\n c[\"fields_as_json\"][str(org.cache[\"fields\"][\"gender\"].uuid)] = {\"text\": str(c[\"gender\"])}\n if c[\"age\"] is not None:\n c[\"fields_as_json\"][str(org.cache[\"fields\"][\"age\"].uuid)] = {\n \"text\": str(c[\"age\"]),\n \"number\": str(c[\"age\"]),\n }\n if c[\"joined\"] is not None:\n c[\"fields_as_json\"][str(org.cache[\"fields\"][\"joined\"].uuid)] = {\n \"text\": org.format_datetime(c[\"joined\"], show_time=False),\n \"datetime\": timezone.localtime(c[\"joined\"], org.timezone).isoformat(),\n }\n\n if location:\n c[\"fields_as_json\"].update(\n {\n str(org.cache[\"fields\"][\"ward\"].uuid): {\n \"text\": str(c[\"ward\"].path.split(\" > \")[-1]),\n \"ward\": c[\"ward\"].path,\n \"district\": c[\"district\"].path,\n \"state\": c[\"state\"].path,\n },\n str(org.cache[\"fields\"][\"district\"].uuid): {\n \"text\": str(c[\"district\"].path.split(\" > \")[-1]),\n \"district\": c[\"district\"].path,\n \"state\": c[\"state\"].path,\n },\n str(org.cache[\"fields\"][\"state\"].uuid): {\n \"text\": str(c[\"state\"].path.split(\" > \")[-1]),\n \"state\": c[\"state\"].path,\n },\n }\n )\n\n # work out which groups this contact belongs to\n if c[\"is_active\"]:\n if c[\"status\"] == Contact.STATUS_ACTIVE:\n c[\"groups\"].append(org.cache[\"system_groups\"][ContactGroup.TYPE_ACTIVE])\n\n # let each user group decide if it is taking this contact\n for g in org.cache[\"groups\"]:\n if g.member(c) if callable(g.member) else self.probability(g.member):\n c[\"groups\"].append(g)\n\n elif c[\"status\"] == Contact.STATUS_BLOCKED:\n c[\"groups\"].append(org.cache[\"system_groups\"][ContactGroup.TYPE_BLOCKED])\n elif c[\"status\"] == Contact.STATUS_STOPPED:\n c[\"groups\"].append(org.cache[\"system_groups\"][ContactGroup.TYPE_STOPPED])\n\n # track changes to group counts\n for g in c[\"groups\"]:\n group_counts[g] += 1\n\n batch.append(c)\n\n self._create_contact_batch(batch)\n self._log(\" > Created batch %d of %d\\n\" % (batch_num, max(num_contacts // self.batch_size, 1)))\n batch_num += 1\n\n # create group count records manually\n counts = []\n for group, count in group_counts.items():\n counts.append(ContactGroupCount(group=group, count=count, is_squashed=True))\n group.count = count\n ContactGroupCount.objects.bulk_create(counts)", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:\n if self.hidden:\n return None\n\n any_prefix_is_slash = False\n\n def _write_opts(opts: t.Sequence[str]) -> str:\n nonlocal any_prefix_is_slash\n\n rv, any_slashes = join_options(opts)\n\n if any_slashes:\n any_prefix_is_slash = True\n\n if not self.is_flag and not self.count:\n rv += f\" {self.make_metavar()}\"\n\n return rv\n\n rv = [_write_opts(self.opts)]\n\n if self.secondary_opts:\n rv.append(_write_opts(self.secondary_opts))\n\n help = self.help or \"\"\n extra = []\n\n if self.show_envvar:\n envvar = self.envvar\n\n if envvar is None:\n if (\n self.allow_from_autoenv\n and ctx.auto_envvar_prefix is not None\n and self.name is not None\n ):\n envvar = f\"{ctx.auto_envvar_prefix}_{self.name.upper()}\"\n\n if envvar is not None:\n var_str = (\n envvar\n if isinstance(envvar, str)\n else \", \".join(str(d) for d in envvar)\n )\n extra.append(_(\"env var: {var}\").format(var=var_str))\n\n # Temporarily enable resilient parsing to avoid type casting\n # failing for the default. Might be possible to extend this to\n # help formatting in general.\n resilient = ctx.resilient_parsing\n ctx.resilient_parsing = True\n\n try:\n default_value = self.get_default(ctx, call=False)\n finally:\n ctx.resilient_parsing = resilient\n\n show_default = False\n show_default_is_str = False\n\n if self.show_default is not None:\n if isinstance(self.show_default, str):\n show_default_is_str = show_default = True\n else:\n show_default = self.show_default\n elif ctx.show_default is not None:\n show_default = ctx.show_default\n\n if show_default_is_str or (show_default and (default_value is not None)):\n if show_default_is_str:\n default_string = f\"({self.show_default})\"\n elif isinstance(default_value, (list, tuple)):\n default_string = \", \".join(str(d) for d in default_value)\n elif inspect.isfunction(default_value):\n default_string = _(\"(dynamic)\")\n elif self.is_bool_flag and self.secondary_opts:\n # For boolean flags that have distinct True/False opts,\n # use the opt without prefix instead of the value.\n default_string = split_opt(\n (self.opts if self.default else self.secondary_opts)[0]\n )[1]\n elif self.is_bool_flag and not self.secondary_opts and not default_value:\n default_string = \"\"\n else:\n default_string = str(default_value)\n\n if default_string:\n extra.append(_(\"default: {default}\").format(default=default_string))\n\n if (\n isinstance(self.type, types._NumberRangeBase)\n # skip count with default range type\n and not (self.count and self.type.min == 0 and self.type.max is None)\n ):\n range_str = self.type._describe_range()\n\n if range_str:\n extra.append(range_str)\n\n if self.required:\n extra.append(_(\"required\"))\n\n if extra:\n extra_str = \"; \".join(extra)\n help = f\"{help} [{extra_str}]\" if help else f\"[{extra_str}]\"\n\n return (\"; \" if any_prefix_is_slash else \" / \").join(rv), help", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@register.filter(is_safe=True, needs_autoescape=True)\ndef unordered_list(value, autoescape=True):\n \"\"\"\n Recursively take a self-nested list and return an HTML unordered list --\n WITHOUT opening and closing <ul> tags.\n\n Assume the list is in the proper format. For example, if ``var`` contains:\n ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then\n ``{{ var|unordered_list }}`` returns::\n\n <li>States\n <ul>\n <li>Kansas\n <ul>\n <li>Lawrence</li>\n <li>Topeka</li>\n </ul>\n </li>\n <li>Illinois</li>\n </ul>\n </li>\n \"\"\"\n if autoescape:\n escaper = conditional_escape\n else:\n\n def escaper(x):\n return x\n\n def walk_items(item_list):\n item_iterator = iter(item_list)\n try:\n item = next(item_iterator)\n while True:\n try:\n next_item = next(item_iterator)\n except StopIteration:\n yield item, None\n break\n if isinstance(next_item, (list, tuple, types.GeneratorType)):\n try:\n iter(next_item)\n except TypeError:\n pass\n else:\n yield item, next_item\n item = next(item_iterator)\n continue\n yield item, None\n item = next_item\n except StopIteration:\n pass\n\n def list_formatter(item_list, tabs=1):\n indent = \"\\t\" * tabs\n output = []\n for item, children in walk_items(item_list):\n sublist = \"\"\n if children:\n sublist = \"\\n%s<ul>\\n%s\\n%s</ul>\\n%s\" % (\n indent,\n list_formatter(children, tabs + 1),\n indent,\n indent,\n )\n output.append(\"%s<li>%s%s</li>\" % (indent, escaper(item), sublist))\n return \"\\n\".join(output)\n\n return mark_safe(list_formatter(value))", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def addToHistory(self, ref):\n\t\tif not self.isSubservices():\n\t\t\tif self.delhistpoint is not None:\n\t\t\t\tx = self.delhistpoint\n\t\t\t\twhile x <= len(self.history) - 1:\n\t\t\t\t\tdel self.history[x]\n\t\t\tself.delhistpoint = None\n\t\t\tif self.servicePath is not None:\n\t\t\t\ttmp = self.servicePath[:]\n\t\t\t\ttmp.append(ref)\n\t\t\t\tself.history.append(tmp)\n\t\t\t\thlen = len(self.history)\n\t\t\t\tx = 0\n\t\t\t\twhile x < hlen - 1:\n\t\t\t\t\tif self.history[x][-1] == ref:\n\t\t\t\t\t\tdel self.history[x]\n\t\t\t\t\t\thlen -= 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tx += 1\n\t\t\t\tif hlen > HISTORY_SIZE:\n\t\t\t\t\tdel self.history[0]\n\t\t\t\t\thlen -= 1\n\t\t\t\tself.history_pos = hlen - 1", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def check_mapping_str_interpolation(\n self,\n specifiers: list[ConversionSpecifier],\n replacements: Expression,\n expr: FormatStringExpr,\n ) -> None:\n \"\"\"Check % string interpolation with names specifiers '%(name)s' % {'name': 'John'}.\"\"\"\n if isinstance(replacements, DictExpr) and all(\n isinstance(k, (StrExpr, BytesExpr)) for k, v in replacements.items\n ):\n mapping: dict[str, Type] = {}\n for k, v in replacements.items:\n if isinstance(expr, BytesExpr):\n # Special case: for bytes formatting keys must be bytes.\n if not isinstance(k, BytesExpr):\n self.msg.fail(\n \"Dictionary keys in bytes formatting must be bytes, not strings\",\n expr,\n code=codes.STRING_FORMATTING,\n )\n key_str = cast(FormatStringExpr, k).value\n mapping[key_str] = self.accept(v)\n\n for specifier in specifiers:\n if specifier.conv_type == \"%\":\n # %% is allowed in mappings, no checking is required\n continue\n assert specifier.key is not None\n if specifier.key not in mapping:\n self.msg.key_not_in_mapping(specifier.key, replacements)\n return\n rep_type = mapping[specifier.key]\n assert specifier.conv_type is not None\n expected_type = self.conversion_type(specifier.conv_type, replacements, expr)\n if expected_type is None:\n return\n self.chk.check_subtype(\n rep_type,\n expected_type,\n replacements,\n message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,\n \"expression has type\",\n f\"placeholder with key '{specifier.key}' has type\",\n code=codes.STRING_FORMATTING,\n )\n if specifier.conv_type == \"s\":\n self.check_s_special_cases(expr, rep_type, expr)\n else:\n rep_type = self.accept(replacements)\n dict_type = self.build_dict_type(expr)\n self.chk.check_subtype(\n rep_type,\n dict_type,\n replacements,\n message_registry.FORMAT_REQUIRES_MAPPING,\n \"expression has type\",\n \"expected type for mapping is\",\n code=codes.STRING_FORMATTING,\n )", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def is_secure_origin(self, location: Link) -> bool:\n # Determine if this url used a secure transport mechanism\n parsed = urllib.parse.urlparse(str(location))\n origin_protocol, origin_host, origin_port = (\n parsed.scheme,\n parsed.hostname,\n parsed.port,\n )\n\n # The protocol to use to see if the protocol matches.\n # Don't count the repository type as part of the protocol: in\n # cases such as \"git+ssh\", only use \"ssh\". (I.e., Only verify against\n # the last scheme.)\n origin_protocol = origin_protocol.rsplit(\"+\", 1)[-1]\n\n # Determine if our origin is a secure origin by looking through our\n # hardcoded list of secure origins, as well as any additional ones\n # configured on this PackageFinder instance.\n for secure_origin in self.iter_secure_origins():\n secure_protocol, secure_host, secure_port = secure_origin\n if origin_protocol != secure_protocol and secure_protocol != \"*\":\n continue\n\n try:\n addr = ipaddress.ip_address(origin_host or \"\")\n network = ipaddress.ip_network(secure_host)\n except ValueError:\n # We don't have both a valid address or a valid network, so\n # we'll check this origin against hostnames.\n if (\n origin_host\n and origin_host.lower() != secure_host.lower()\n and secure_host != \"*\"\n ):\n continue\n else:\n # We have a valid address and network, so see if the address\n # is contained within the network.\n if addr not in network:\n continue\n\n # Check to see if the port matches.\n if (\n origin_port != secure_port\n and secure_port != \"*\"\n and secure_port is not None\n ):\n continue\n\n # If we've gotten here, then this origin matches the current\n # secure origin and we should return True\n return True\n\n # If we've gotten to this point, then the origin isn't secure and we\n # will not accept it as a valid location to search. We will however\n # log a warning that we are ignoring it.\n logger.warning(\n \"The repository located at %s is not a trusted or secure host and \"\n \"is being ignored. If this repository is available via HTTPS we \"\n \"recommend you use HTTPS instead, otherwise you may silence \"\n \"this warning and allow it anyway with '--trusted-host %s'.\",\n origin_host,\n origin_host,\n )\n\n return False", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def analyze_type_application_args(self, expr: IndexExpr) -> list[Type] | None:\n \"\"\"Analyze type arguments (index) in a type application.\n\n Return None if anything was incomplete.\n \"\"\"\n index = expr.index\n tag = self.track_incomplete_refs()\n self.analyze_type_expr(index)\n if self.found_incomplete_ref(tag):\n return None\n if self.basic_type_applications:\n # Postpone the rest until we have more information (for r.h.s. of an assignment)\n return None\n types: list[Type] = []\n if isinstance(index, TupleExpr):\n items = index.items\n is_tuple = isinstance(expr.base, RefExpr) and expr.base.fullname == \"builtins.tuple\"\n if is_tuple and len(items) == 2 and isinstance(items[-1], EllipsisExpr):\n items = items[:-1]\n else:\n items = [index]\n\n # TODO: this needs a clean-up.\n # Probably always allow Parameters literals, and validate in semanal_typeargs.py\n base = expr.base\n if isinstance(base, RefExpr) and isinstance(base.node, TypeAlias):\n allow_unpack = base.node.tvar_tuple_index is not None\n alias = base.node\n if any(isinstance(t, ParamSpecType) for t in alias.alias_tvars):\n has_param_spec = True\n num_args = len(alias.alias_tvars)\n else:\n has_param_spec = False\n num_args = -1\n elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo):\n allow_unpack = (\n base.node.has_type_var_tuple_type or base.node.fullname == \"builtins.tuple\"\n )\n has_param_spec = base.node.has_param_spec_type\n num_args = len(base.node.type_vars)\n else:\n allow_unpack = False\n has_param_spec = False\n num_args = -1\n\n for item in items:\n try:\n typearg = self.expr_to_unanalyzed_type(item, allow_unpack=True)\n except TypeTranslationError:\n self.fail(\"Type expected within [...]\", expr)\n return None\n analyzed = self.anal_type(\n typearg,\n # The type application may appear in base class expression,\n # where type variables are not bound yet. Or when accepting\n # r.h.s. of type alias before we figured out it is a type alias.\n allow_unbound_tvars=self.allow_unbound_tvars,\n allow_placeholder=True,\n allow_param_spec_literals=has_param_spec,\n allow_unpack=allow_unpack,\n )\n if analyzed is None:\n return None\n types.append(analyzed)\n\n if has_param_spec and num_args == 1 and types:\n first_arg = get_proper_type(types[0])\n single_any = len(types) == 1 and isinstance(first_arg, AnyType)\n if not (single_any or any(isinstance(t, (Parameters, ParamSpecType)) for t in types)):\n types = [Parameters(types, [ARG_POS] * len(types), [None] * len(types))]\n\n return types", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def to_config(self, cmd_or_tlm, default_endianness):\n config = \"\"\n if self.description:\n description = self.description.replace('\"', \"'\")\n else:\n description = \"\"\n if cmd_or_tlm == \"TELEMETRY\":\n if self.array_size is not None:\n config += f' ARRAY_ITEM {quote_if_necessary(self.name)} {self.bit_offset} {self.bit_size} {self.data_type} {self.array_size} \"{description}\"'\n elif self.id_value:\n id_value = self.id_value\n if self.data_type == \"BLOCK\" or self.data_type == \"STRING\":\n if not self.id_value.isascii():\n id_value = \"0x\" + simple_formatted(self.id_value)\n else:\n id_value = f'\"{self.id_value}\"'\n config += f' ID_ITEM {quote_if_necessary(self.name)} {self.bit_offset} {self.bit_size} {self.data_type} {id_value} \"{description}\"'\n else:\n config += f' ITEM {quote_if_necessary(self.name)} {self.bit_offset} {self.bit_size} {self.data_type} \"{description}\"'\n else: # 'COMMAND'\n if self.array_size is not None:\n config += f' ARRAY_PARAMETER {quote_if_necessary(self.name)} {self.bit_offset} {self.bit_size} {self.data_type} {self.array_size} \"{description}\"'\n else:\n config += self.parameter_config()\n if self.endianness != default_endianness and self.data_type != \"STRING\" and self.data_type != \"BLOCK\":\n config += \" {self.endianness}\"\n config += \"\\n\"\n\n if self.required:\n config += \" REQUIRED\\n\"\n if self.format_string:\n config += f\" FORMAT_STRING {quote_if_necessary(self.format_string)}\\n\"\n if self.units:\n config += f\" UNITS {quote_if_necessary(self.units_full)} {quote_if_necessary(self.units)}\\n\"\n if self.overflow != \"ERROR\":\n config += f\" OVERFLOW {self.overflow}\\n\"\n\n if self.states:\n for state_name, state_value in self.states.items():\n config += f\" STATE {quote_if_necessary(state_name)} {quote_if_necessary(str(state_value))}\"\n if self.hazardous and self.hazardous[state_name]:\n config += f\" HAZARDOUS {quote_if_necessary(self.hazardous[state_name])}\"\n if self.messages_disabled and self.messages_disabled[state_name]:\n config += \" DISABLE_MESSAGES\"\n if self.state_colors and self.state_colors[state_name]:\n config += f\" {self.state_colors[state_name]}\"\n config += \"\\n\"\n\n if self.read_conversion:\n config += self.read_conversion.to_config(\"READ\")\n if self.write_conversion:\n config += self.write_conversion.to_config(\"WRITE\")\n\n if self.limits:\n if self.limits.values:\n for limits_set, limits_values in self.limits.values.items():\n config += f\" LIMITS {limits_set} {self.limits.persistence_setting} {'ENABLED' if self.limits.enabled else 'DISABLED'} {limits_values[0]} {limits_values[1]} {limits_values[2]} {limits_values[3]}\"\n if len(limits_values) > 4:\n config += f\" {limits_values[4]} {limits_values[5]}\\n\"\n else:\n config += \"\\n\"\n if self.limits.response:\n config += self.limits.response.to_config\n\n if self.meta:\n for key, values in self.meta.items():\n vals = \" \".join([quote_if_necessary(x) for x in values])\n config += f\" META {quote_if_necessary(key)} {vals}\\n\"\n\n return config", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def find_targets_recursive(\n manager: BuildManager,\n graph: Graph,\n triggers: set[str],\n deps: dict[str, set[str]],\n up_to_date_modules: set[str],\n) -> tuple[dict[str, set[FineGrainedDeferredNode]], set[str], set[TypeInfo]]:\n \"\"\"Find names of all targets that need to reprocessed, given some triggers.\n\n Returns: A tuple containing a:\n * Dictionary from module id to a set of stale targets.\n * A set of module ids for unparsed modules with stale targets.\n \"\"\"\n result: dict[str, set[FineGrainedDeferredNode]] = {}\n worklist = triggers\n processed: set[str] = set()\n stale_protos: set[TypeInfo] = set()\n unloaded_files: set[str] = set()\n\n # Find AST nodes corresponding to each target.\n #\n # TODO: Don't rely on a set, since the items are in an unpredictable order.\n while worklist:\n processed |= worklist\n current = worklist\n worklist = set()\n for target in current:\n if target.startswith(\"<\"):\n module_id = module_prefix(graph, trigger_to_target(target))\n if module_id:\n ensure_deps_loaded(module_id, deps, graph)\n\n worklist |= deps.get(target, set()) - processed\n else:\n module_id = module_prefix(graph, target)\n if module_id is None:\n # Deleted module.\n continue\n if module_id in up_to_date_modules:\n # Already processed.\n continue\n if (\n module_id not in manager.modules\n or manager.modules[module_id].is_cache_skeleton\n ):\n # We haven't actually parsed and checked the module, so we don't have\n # access to the actual nodes.\n # Add it to the queue of files that need to be processed fully.\n unloaded_files.add(module_id)\n continue\n\n if module_id not in result:\n result[module_id] = set()\n manager.log_fine_grained(f\"process: {target}\")\n deferred, stale_proto = lookup_target(manager, target)\n if stale_proto:\n stale_protos.add(stale_proto)\n result[module_id].update(deferred)\n\n return result, unloaded_files, stale_protos", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@strategy(\n ids=[\"frame:v1\"],\n interface=Frame,\n)\ndef frame(\n interface: Frame, event: Event, context: GroupingContext, **meta: Any\n) -> ReturnedVariants:\n frame = interface\n platform = frame.platform or event.platform\n\n # Safari throws [native code] frames in for calls like ``forEach``\n # whereas Chrome ignores these. Let's remove it from the hashing algo\n # so that they're more likely to group together\n filename_component = get_filename_component(\n frame.abs_path, frame.filename, platform, allow_file_origin=context[\"javascript_fuzzing\"]\n )\n\n # if we have a module we use that for grouping. This will always\n # take precedence over the filename if it contributes\n module_component = get_module_component(frame.abs_path, frame.module, platform, context)\n if module_component.contributes and filename_component.contributes:\n filename_component.update(contributes=False, hint=\"module takes precedence\")\n\n context_line_component = None\n\n # If we are allowed to use the contextline we add it now.\n if platform in context[\"contextline_platforms\"]:\n context_line_component = get_contextline_component(\n frame,\n platform,\n function=frame.function,\n context=context,\n )\n\n context_line_available = bool(context_line_component and context_line_component.contributes)\n\n function_component = get_function_component(\n context=context,\n function=frame.function,\n raw_function=frame.raw_function,\n platform=platform,\n sourcemap_used=frame.data and frame.data.get(\"sourcemap\") is not None,\n context_line_available=context_line_available,\n )\n\n values = [module_component, filename_component, function_component]\n if context_line_component is not None:\n values.append(context_line_component)\n\n rv = GroupingComponent(id=\"frame\", values=values)\n\n # if we are in javascript fuzzing mode we want to disregard some\n # frames consistently. These force common bad stacktraces together\n # to have a common hash at the cost of maybe skipping over frames that\n # would otherwise be useful.\n if context[\"javascript_fuzzing\"] and get_behavior_family_for_platform(platform) == \"javascript\":\n func = frame.raw_function or frame.function\n if func:\n func = func.rsplit(\".\", 1)[-1]\n # special case empty functions not to have a hint\n if not func:\n function_component.update(contributes=False)\n elif func in (\n \"?\",\n \"<anonymous function>\",\n \"<anonymous>\",\n \"Anonymous function\",\n ) or func.endswith(\"/<\"):\n function_component.update(contributes=False, hint=\"ignored unknown function name\")\n if (func == \"eval\") or frame.abs_path in (\n \"[native code]\",\n \"native code\",\n \"eval code\",\n \"<anonymous>\",\n ):\n rv.update(contributes=False, hint=\"ignored low quality javascript frame\")\n\n if context[\"is_recursion\"]:\n rv.update(contributes=False, hint=\"ignored due to recursion\")\n\n return {context[\"variant\"]: rv}", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def check_config(data_file, schema_file, print_ok=True):\n rules = ruyaml.round_trip_load(\n open(schema_file, encoding=settings.ENCODING_UTF_8), # noqa: SIM115\n )\n try:\n data = ruyaml.round_trip_load(\n open(data_file, encoding=settings.ENCODING_UTF_8), # noqa: SIM115\n version=\"1.1\",\n )\n except FileNotFoundError as e:\n print(e)\n\n return 1\n except ruyaml.constructor.DuplicateKeyError as e:\n print(f'Config file \"{data_file}\" Duplicate Keys Error:')\n print(f\"{e.context}\\n{e.context_mark}\\n{e.problem}\\n{e.problem_mark}\")\n\n return 1\n except (ruyaml.parser.ParserError, ruyaml.scanner.ScannerError, NotImplementedError) as e:\n print(f'Config file \"{data_file}\" YAML Parser Error:')\n print(f\"{e}\")\n\n return 1\n\n try:\n cm.checker.check(data, rules)\n if print_ok:\n print(f'Config file \"{data_file}\" is OK')\n\n return 0\n except cm.checker.DataError as e:\n print(f'File \"{data_file}\", error: {e}')\n\n return 1\n except cm.checker.SchemaError as e:\n print(f'File \"{schema_file}\" error: {e}')\n\n return 1\n except cm.checker.FormatError as e:\n print(f'Data File \"{data_file}\" Errors:')\n print(f\"\\tline {e.line}: {e.message}\")\n if e.errors:\n for error in e.errors:\n if \"Input data for\" in error.message:\n continue\n\n print(f\"\\tline {error.line}: {error.message}\")\n\n print(f'Schema File \"{schema_file}\" line {rules[e.rule].lc.line}, Rule: \"{e.rule}\"')\n\n return 1", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def getMulti(self, selected):\n\t\tif selected:\n\t\t\tstart = 0\n\t\t\tfor index, value in enumerate(self.value):\n\t\t\t\tif index == self.item:\n\t\t\t\t\tbreak\n\t\t\t\tstart += len(value) + 1\n\t\t\tend = start + len(value)\n\t\t\tvalue = \" \".join(self.value)\n\t\t\tif self.visibleWidth and len(value) > self.visibleWidth:\n\t\t\t\tif start + 1 < self.visibleWidth / 2:\n\t\t\t\t\toffset = 0\n\t\t\t\telse:\n\t\t\t\t\toffset = min(start + 1 - self.visibleWidth / 2, len(value) - self.visibleWidth)\n\t\t\t\treturn (\"mtext\", value[offset:offset + self.visibleWidth], list(range(start - offset, end - offset)))\n\t\t\telse:\n\t\t\t\treturn (\"mtext\", value, list(range(start, end)))\n\t\telse:\n\t\t\tvalue = \" \".join(self.value)\n\t\t\treturn (\"text\", value[0:self.visibleWidth] if self.visibleWidth and len(value) > self.visibleWidth else value)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@sensitive_post_parameters_m\n def user_change_password(self, request, id, form_url=\"\"):\n user = self.get_object(request, unquote(id))\n if not self.has_change_permission(request, user):\n raise PermissionDenied\n if user is None:\n raise Http404(\n _(\"%(name)s object with primary key %(key)r does not exist.\")\n % {\n \"name\": self.opts.verbose_name,\n \"key\": escape(id),\n }\n )\n if request.method == \"POST\":\n form = self.change_password_form(user, request.POST)\n if form.is_valid():\n # If disabling password-based authentication was requested\n # (via the form field `usable_password`), the submit action\n # must be \"unset-password\". This check is most relevant when\n # the admin user has two submit buttons available (for example\n # when Javascript is disabled).\n valid_submission = (\n form.cleaned_data[\"set_usable_password\"]\n or \"unset-password\" in request.POST\n )\n if not valid_submission:\n msg = gettext(\"Conflicting form data submitted. Please try again.\")\n messages.error(request, msg)\n return HttpResponseRedirect(request.get_full_path())\n\n user = form.save()\n change_message = self.construct_change_message(request, form, None)\n self.log_change(request, user, change_message)\n if user.has_usable_password():\n msg = gettext(\"Password changed successfully.\")\n else:\n msg = gettext(\"Password-based authentication was disabled.\")\n messages.success(request, msg)\n update_session_auth_hash(request, form.user)\n return HttpResponseRedirect(\n reverse(\n \"%s:%s_%s_change\"\n % (\n self.admin_site.name,\n user._meta.app_label,\n user._meta.model_name,\n ),\n args=(user.pk,),\n )\n )\n else:\n form = self.change_password_form(user)\n\n fieldsets = [(None, {\"fields\": list(form.base_fields)})]\n admin_form = admin.helpers.AdminForm(form, fieldsets, {})\n\n if user.has_usable_password():\n title = _(\"Change password: %s\")\n else:\n title = _(\"Set password: %s\")\n context = {\n \"title\": title % escape(user.get_username()),\n \"adminForm\": admin_form,\n \"form_url\": form_url,\n \"form\": form,\n \"is_popup\": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),\n \"is_popup_var\": IS_POPUP_VAR,\n \"add\": True,\n \"change\": False,\n \"has_delete_permission\": False,\n \"has_change_permission\": True,\n \"has_absolute_url\": False,\n \"opts\": self.opts,\n \"original\": user,\n \"save_as\": False,\n \"show_save\": True,\n **self.admin_site.each_context(request),\n }\n\n request.current_app = self.admin_site.name\n\n return TemplateResponse(\n request,\n self.change_user_password_template\n or \"admin/auth/user/change_password.html\",\n context,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def find_cache_meta(id: str, path: str, manager: BuildManager) -> CacheMeta | None:\n \"\"\"Find cache data for a module.\n\n Args:\n id: module ID\n path: module path\n manager: the build manager (for pyversion, log/trace, and build options)\n\n Returns:\n A CacheMeta instance if the cache data was found and appears\n valid; otherwise None.\n \"\"\"\n # TODO: May need to take more build options into account\n meta_json, data_json, _ = get_cache_names(id, path, manager.options)\n manager.trace(f\"Looking for {id} at {meta_json}\")\n t0 = time.time()\n meta = _load_json_file(\n meta_json, manager, log_success=f\"Meta {id} \", log_error=f\"Could not load cache for {id}: \"\n )\n t1 = time.time()\n if meta is None:\n return None\n if not isinstance(meta, dict):\n manager.log(f\"Could not load cache for {id}: meta cache is not a dict: {repr(meta)}\")\n return None\n m = cache_meta_from_dict(meta, data_json)\n t2 = time.time()\n manager.add_stats(\n load_meta_time=t2 - t0, load_meta_load_time=t1 - t0, load_meta_from_dict_time=t2 - t1\n )\n\n # Don't check for path match, that is dealt with in validate_meta().\n #\n # TODO: these `type: ignore`s wouldn't be necessary\n # if the type annotations for CacheMeta were more accurate\n # (all of these attributes can be `None`)\n if (\n m.id != id\n or m.mtime is None # type: ignore[redundant-expr]\n or m.size is None # type: ignore[redundant-expr]\n or m.dependencies is None # type: ignore[redundant-expr]\n or m.data_mtime is None\n ):\n manager.log(f\"Metadata abandoned for {id}: attributes are missing\")\n return None\n\n # Ignore cache if generated by an older mypy version.\n if (\n (m.version_id != manager.version_id and not manager.options.skip_version_check)\n or m.options is None\n or len(m.dependencies) + len(m.suppressed) != len(m.dep_prios)\n or len(m.dependencies) + len(m.suppressed) != len(m.dep_lines)\n ):\n manager.log(f\"Metadata abandoned for {id}: new attributes are missing\")\n return None\n\n # Ignore cache if (relevant) options aren't the same.\n # Note that it's fine to mutilate cached_options since it's only used here.\n cached_options = m.options\n current_options = manager.options.clone_for_module(id).select_options_affecting_cache()\n if manager.options.skip_version_check:\n # When we're lax about version we're also lax about platform.\n cached_options[\"platform\"] = current_options[\"platform\"]\n if \"debug_cache\" in cached_options:\n # Older versions included debug_cache, but it's silly to compare it.\n del cached_options[\"debug_cache\"]\n if cached_options != current_options:\n manager.log(f\"Metadata abandoned for {id}: options differ\")\n if manager.options.verbosity >= 2:\n for key in sorted(set(cached_options) | set(current_options)):\n if cached_options.get(key) != current_options.get(key):\n manager.trace(\n \" {}: {} != {}\".format(\n key, cached_options.get(key), current_options.get(key)\n )\n )\n return None\n if manager.old_plugins_snapshot and manager.plugins_snapshot:\n # Check if plugins are still the same.\n if manager.plugins_snapshot != manager.old_plugins_snapshot:\n manager.log(f\"Metadata abandoned for {id}: plugins differ\")\n return None\n # So that plugins can return data with tuples in it without\n # things silently always invalidating modules, we round-trip\n # the config data. This isn't beautiful.\n plugin_data = json_loads(\n json_dumps(manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=True)))\n )\n if m.plugin_data != plugin_data:\n manager.log(f\"Metadata abandoned for {id}: plugin configuration differs\")\n return None\n\n manager.add_stats(fresh_metas=1)\n return m", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def get_gear_links(self):\n links = []\n\n if self.object.status == Contact.STATUS_ACTIVE:\n if self.has_org_perm(\"msgs.broadcast_send\"):\n links.append(\n dict(\n id=\"send-message\",\n title=_(\"Send Message\"),\n style=\"button-primary\",\n href=f\"{reverse('msgs.broadcast_send')}?c={self.object.uuid}\",\n modax=_(\"Send Message\"),\n )\n )\n\n if self.has_org_perm(\"contacts.contact_start\"):\n links.append(\n dict(\n id=\"start-flow\",\n title=_(\"Start In Flow\"),\n href=f\"{reverse('contacts.contact_start', args=[self.object.id])}\",\n modax=_(\"Start In Flow\"),\n )\n )\n\n if self.has_org_perm(\"contacts.contact_update\"):\n links.append(\n dict(\n id=\"edit-contact\",\n title=_(\"Edit\"),\n modax=_(\"Edit Contact\"),\n href=f\"{reverse('contacts.contact_update', args=[self.object.pk])}\",\n )\n )\n\n links.append(\n dict(\n id=\"update-custom-fields\",\n title=_(\"Custom Fields\"),\n modax=_(\"Custom Fields\"),\n href=f\"{reverse('contacts.contact_update_fields', args=[self.object.pk])}\",\n )\n )\n\n if self.object.status != Contact.STATUS_ACTIVE and self.has_org_perm(\"contacts.contact_restore\"):\n links.append(\n dict(\n title=_(\"Activate\"),\n style=\"button-primary\",\n js_class=\"posterize\",\n href=reverse(\"contacts.contact_restore\", args=(self.object.pk,)),\n )\n )\n\n if self.object.status != Contact.STATUS_BLOCKED and self.has_org_perm(\"contacts.contact_block\"):\n links.append(\n dict(\n title=_(\"Block\"),\n style=\"button-primary\",\n js_class=\"posterize\",\n href=reverse(\"contacts.contact_block\", args=(self.object.pk,)),\n )\n )\n\n if self.object.status != Contact.STATUS_ARCHIVED and self.has_org_perm(\"contacts.contact_archive\"):\n links.append(\n dict(\n title=_(\"Archive\"),\n style=\"btn-primary\",\n js_class=\"posterize\",\n href=reverse(\"contacts.contact_archive\", args=(self.object.pk,)),\n )\n )\n\n user = self.get_user()\n if user.is_superuser or user.is_staff:\n links.append(\n dict(\n title=_(\"Service\"),\n posterize=True,\n href=f'{reverse(\"orgs.org_service\")}?organization={self.object.org_id}&redirect_url={reverse(\"contacts.contact_read\", args=[self.get_object().uuid])}',\n )\n )\n\n return links", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "def keySelect(self):\n\t\tif self.pluginList:\n\t\t\tcurrentPlugin = self.pluginList[self.currentList.getSelectedIndex()][0]\n\t\t\tif self.sortMode:\n\t\t\t\tselect = (self.selectedPlugin is None or self.selectedPlugin != currentPlugin)\n\t\t\t\tif not select:\n\t\t\t\t\tself.selectedPlugin = None\n\t\t\t\tfor index, plugin in enumerate(self.pluginList):\n\t\t\t\t\tif currentPlugin == plugin[0]:\n\t\t\t\t\t\tself.pluginList.pop(index)\n\t\t\t\t\t\tself.pluginList.insert(index, (plugin[0], plugin[0].name, plugin[0].description, plugin[0].icon or self.pluginIcon))\n\t\t\t\t\t\tself.selectedPlugin = currentPlugin if select else None\n\t\t\t\t\t\tbreak\n\t\t\t\tif self.selectedPlugin:\n\t\t\t\t\tself[\"key_green\"].setText(_(\"Move Mode Off\"))\n\t\t\t\t\tself.currentList.master.master.instance.setBackgroundColorSelected(self.moveBackgroundColor)\n\t\t\t\t\tif self.moveFontColor:\n\t\t\t\t\t\tself.currentList.master.master.instance.setForegroundColorSelected(self.moveFontColor)\n\t\t\t\telse:\n\t\t\t\t\tself[\"key_green\"].setText(_(\"Move Mode On\"))\n\t\t\t\t\tself.currentList.master.master.instance.clearBackgroundColorSelected()\n\t\t\t\t\tif self.moveFontColor:\n\t\t\t\t\t\tself.currentList.master.master.instance.clearForegroundColorSelected()\n\t\t\t\tself.currentList.updateList(self.pluginList)\n\t\t\telse:\n\t\t\t\tcurrentPlugin(session=self.session)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def set_secondary(fsaccess, builder, inputschema, secondaryspec, primary, discovered):\n if isinstance(inputschema, Sequence) and not isinstance(inputschema, basestring):\n # union type, collect all possible secondaryFiles\n for i in inputschema:\n set_secondary(fsaccess, builder, i, secondaryspec, primary, discovered)\n return\n\n if inputschema == \"File\":\n inputschema = {\"type\": \"File\"}\n\n if isinstance(inputschema, basestring):\n sd = search_schemadef(inputschema, reversed(builder.hints+builder.requirements))\n if sd:\n inputschema = sd\n else:\n return\n\n if \"secondaryFiles\" in inputschema:\n # set secondaryFiles, may be inherited by compound types.\n secondaryspec = inputschema[\"secondaryFiles\"]\n\n if (isinstance(inputschema[\"type\"], (Mapping, Sequence)) and\n not isinstance(inputschema[\"type\"], basestring)):\n # compound type (union, array, record)\n set_secondary(fsaccess, builder, inputschema[\"type\"], secondaryspec, primary, discovered)\n\n elif (inputschema[\"type\"] == \"record\" and\n isinstance(primary, Mapping)):\n #\n # record type, find secondary files associated with fields.\n #\n for f in inputschema[\"fields\"]:\n p = primary.get(shortname(f[\"name\"]))\n if p:\n set_secondary(fsaccess, builder, f, secondaryspec, p, discovered)\n\n elif (inputschema[\"type\"] == \"array\" and\n isinstance(primary, Sequence)):\n #\n # array type, find secondary files of elements\n #\n for p in primary:\n set_secondary(fsaccess, builder, {\"type\": inputschema[\"items\"]}, secondaryspec, p, discovered)\n\n elif (inputschema[\"type\"] == \"File\" and\n isinstance(primary, Mapping) and\n primary.get(\"class\") == \"File\"):\n\n if \"secondaryFiles\" in primary or not secondaryspec:\n # Nothing to do.\n return\n\n #\n # Found a file, check for secondaryFiles\n #\n specs = []\n primary[\"secondaryFiles\"] = secondaryspec\n for i, sf in enumerate(aslist(secondaryspec)):\n if builder.cwlVersion == \"v1.0\":\n pattern = sf\n else:\n pattern = sf[\"pattern\"]\n if pattern is None:\n continue\n if isinstance(pattern, list):\n specs.extend(pattern)\n elif isinstance(pattern, dict):\n specs.append(pattern)\n elif isinstance(pattern, str):\n if builder.cwlVersion == \"v1.0\":\n specs.append({\"pattern\": pattern, \"required\": True})\n else:\n specs.append({\"pattern\": pattern, \"required\": sf.get(\"required\")})\n else:\n raise SourceLine(primary[\"secondaryFiles\"], i, validate.ValidationException).makeError(\n \"Expression must return list, object, string or null\")\n\n found = []\n for i, sf in enumerate(specs):\n if isinstance(sf, dict):\n if sf.get(\"class\") == \"File\":\n pattern = None\n if sf.get(\"location\") is None:\n raise SourceLine(primary[\"secondaryFiles\"], i, validate.ValidationException).makeError(\n \"File object is missing 'location': %s\" % sf)\n sfpath = sf[\"location\"]\n required = True\n else:\n pattern = sf[\"pattern\"]\n required = sf.get(\"required\")\n elif isinstance(sf, str):\n pattern = sf\n required = True\n else:\n raise SourceLine(primary[\"secondaryFiles\"], i, validate.ValidationException).makeError(\n \"Expression must return list, object, string or null\")\n\n if pattern is not None:\n if \"${\" in pattern or \"$(\" in pattern:\n sfname = builder.do_eval(pattern, context=primary)\n else:\n sfname = substitute(primary[\"basename\"], pattern)\n\n if sfname is None:\n continue\n\n if isinstance(sfname, str):\n p_location = primary[\"location\"]\n if \"/\" in p_location:\n sfpath = (\n p_location[0 : p_location.rindex(\"/\") + 1]\n + sfname\n )\n\n required = builder.do_eval(required, context=primary)\n\n if isinstance(sfname, list) or isinstance(sfname, dict):\n each = aslist(sfname)\n for e in each:\n if required and not fsaccess.exists(e.get(\"location\")):\n raise SourceLine(primary[\"secondaryFiles\"], i, validate.ValidationException).makeError(\n \"Required secondary file '%s' does not exist\" % e.get(\"location\"))\n found.extend(each)\n\n if isinstance(sfname, str):\n if fsaccess.exists(sfpath):\n if pattern is not None:\n found.append({\"location\": sfpath, \"class\": \"File\"})\n else:\n found.append(sf)\n elif required:\n raise SourceLine(primary[\"secondaryFiles\"], i, validate.ValidationException).makeError(\n \"Required secondary file '%s' does not exist\" % sfpath)\n\n primary[\"secondaryFiles\"] = cmap(found)\n if discovered is not None:\n discovered[primary[\"location\"]] = primary[\"secondaryFiles\"]\n elif inputschema[\"type\"] not in primitive_types_set and inputschema[\"type\"] not in (\"File\", \"Directory\"):\n set_secondary(fsaccess, builder, inputschema[\"type\"], secondaryspec, primary, discovered)", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def keyBlueConfirm(self, confirmed):\n\t\tif not confirmed:\n\t\t\tprint(\"not confirmed\")\n\t\telse:\n\t\t\tif self.contrastEntry is not None:\n\t\t\t\tconfig.pep.contrast.setValue(128)\n\t\t\tif self.saturationEntry is not None:\n\t\t\t\tconfig.pep.saturation.setValue(128)\n\t\t\tif self.hueEntry is not None:\n\t\t\t\tconfig.pep.hue.setValue(128)\n\t\t\tif self.brightnessEntry is not None:\n\t\t\t\tconfig.pep.brightness.setValue(128)\n\t\t\tif self.block_noise_reductionEntry is not None:\n\t\t\t\tconfig.pep.block_noise_reduction.setValue(0)\n\t\t\tif self.mosquito_noise_reductionEntry is not None:\n\t\t\t\tconfig.pep.mosquito_noise_reduction.setValue(0)\n\t\t\tif self.digital_contour_removalEntry is not None:\n\t\t\t\tconfig.pep.digital_contour_removal.setValue(0)\n\t\t\tif self.scaler_sharpnessEntry is not None:\n\t\t\t\tconfig.av.scaler_sharpness.setValue(13)\n\t\t\tif self.scaler_vertical_dejaggingEntry is not None:\n\t\t\t\tconfig.pep.scaler_vertical_dejagging.setValue(False)\n\t\t\tif self.smoothEntry is not None:\n\t\t\t\tconfig.pep.smooth.setValue(False)\n\t\t\tif self.splitEntry is not None:\n\t\t\t\tconfig.pep.split.setValue('off')\n\t\t\tif self.sharpnessEntry is not None:\n\t\t\t\tconfig.pep.sharpness.setValue(0)\n\t\t\tif self.auto_fleshEntry is not None:\n\t\t\t\tconfig.pep.auto_flesh.setValue(0)\n\t\t\tif self.green_boostEntry is not None:\n\t\t\t\tconfig.pep.green_boost.setValue(0)\n\t\t\tif self.blue_boostEntry is not None:\n\t\t\t\tconfig.pep.blue_boost.setValue(0)\n\t\t\tif self.dynamic_contrastEntry is not None:\n\t\t\t\tconfig.pep.dynamic_contrast.setValue(0)\n\t\t\tif self.color_spaceEntry is not None:\n\t\t\t\tfile = open(\"/proc/stb/video/hdmi_colorspace_choices\")\n\t\t\t\tmodes = file.readline().split()\n\t\t\t\tfile.close()\n\t\t\t\tconfig.pep.color_space.setValue(modes[0])\n\t\t\tself.keySave()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def generate_data(self, input_ooi: str, valid_time: datetime) -> dict[str, Any]:\n ref = Reference.from_str(input_ooi)\n records_tree = self.octopoes_api_connector.get_tree(ref, valid_time, depth=1, types={DNSRecord}).store\n findings_tree = self.octopoes_api_connector.get_tree(ref, valid_time, depth=3, types={Finding}).store\n\n findings = []\n finding_types: dict[str, dict] = {}\n records = []\n security = {\"spf\": True, \"dkim\": True, \"dmarc\": True, \"dnssec\": True, \"caa\": True}\n\n for ooi_type, ooi in findings_tree.items():\n if isinstance(ooi, Finding):\n for check in [\"caa\", \"dkim\", \"dmarc\", \"dnssec\", \"spf\"]:\n if \"NO-%s\" % check.upper() in ooi.finding_type.tokenized.id:\n security[check] = False\n if ooi.finding_type.tokenized.id == \"KAT-INVALID-SPF\":\n security[\"spf\"] = False\n if ooi.finding_type.tokenized.id in (\n \"KAT-INVALID-SPF\",\n \"KAT-NAMESERVER-NO-IPV6\",\n \"KAT-NAMESERVER-NO-TWO-IPV6\",\n ):\n findings.append(ooi)\n for ooi_type, ooi in records_tree.items():\n if isinstance(ooi, DNSRecord):\n records.append(\n {\n \"type\": ooi.dns_record_type,\n \"ttl\": round(ooi.ttl / 60) if ooi.ttl else \"\",\n \"name\": ooi.hostname.tokenized.name,\n \"content\": ooi.value,\n }\n )\n\n for finding in findings:\n try:\n finding_type = self.octopoes_api_connector.get(Reference.from_str(finding.finding_type), valid_time)\n\n if finding_type.id in finding_types:\n finding_types[finding_type.id][\"occurrences\"].append(finding)\n else:\n finding_types[finding_type.id] = {\"finding_type\": finding_type, \"occurrences\": [finding]}\n\n except ObjectNotFoundException:\n logger.error(\"No Finding Type found for Finding '%s' on date %s.\", finding, str(valid_time))\n\n finding_types_sorted = sorted(\n finding_types.values(), key=lambda x: x[\"finding_type\"].risk_score or 0, reverse=True\n )\n\n records = sorted(records, key=lambda x: x[\"type\"])\n\n return {\"input_ooi\": input_ooi, \"records\": records, \"security\": security, \"finding_types\": finding_types_sorted}", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def get_task_download_archive_file_handler(task: TaskLog) -> io.BytesIO:\n jobs = JobLog.objects.filter(task=task)\n\n if task.action and task.action.type == ActionType.JOB:\n task_dir_name_suffix = str_remove_non_alnum(value=task.action.display_name) or str_remove_non_alnum(\n value=task.action.name,\n )\n else:\n task_dir_name_suffix = None\n\n file_handler = io.BytesIO()\n with tarfile.open(fileobj=file_handler, mode=\"w:gz\") as tar_file:\n for job in jobs:\n if task_dir_name_suffix is None:\n dir_name_suffix = str_remove_non_alnum(value=job.display_name or \"\") or str_remove_non_alnum(\n value=job.name\n )\n else:\n dir_name_suffix = task_dir_name_suffix\n\n directory = Path(settings.RUN_DIR, str(job.pk))\n if directory.is_dir():\n files = [item for item in Path(settings.RUN_DIR, str(job.pk)).iterdir() if item.is_file()]\n for log_file in files:\n tarinfo = tarfile.TarInfo(f'{f\"{job.pk}-{dir_name_suffix}\".strip(\"-\")}/{log_file.name}')\n tarinfo.size = log_file.stat().st_size\n tar_file.addfile(tarinfo=tarinfo, fileobj=io.BytesIO(log_file.read_bytes()))\n else:\n log_storages = LogStorage.objects.filter(job=job, type__in={\"stdout\", \"stderr\"})\n for log_storage in log_storages:\n tarinfo = tarfile.TarInfo(\n f'{f\"{job.pk}-{dir_name_suffix}\".strip(\"-\")}' f\"/{log_storage.name}-{log_storage.type}.txt\",\n )\n # using `or \"\"` here to avoid passing None to `bytes`\n body = io.BytesIO(bytes(log_storage.body or \"\", settings.ENCODING_UTF_8))\n tarinfo.size = body.getbuffer().nbytes\n tar_file.addfile(tarinfo=tarinfo, fileobj=body)\n\n return file_handler", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "@extend_schema(\n operation_id=\"Update an Inbound Data Filter\",\n parameters=[\n GlobalParams.ORG_ID_OR_SLUG,\n GlobalParams.PROJECT_ID_OR_SLUG,\n ProjectParams.FILTER_ID,\n ],\n request=_LegacyBrowserFilterSerializer,\n responses={\n 204: RESPONSE_NO_CONTENT,\n 400: RESPONSE_BAD_REQUEST,\n 403: RESPONSE_FORBIDDEN,\n 404: RESPONSE_NOT_FOUND,\n },\n examples=None,\n )\n def put(self, request: Request, project, filter_id) -> Response:\n \"\"\"\n Update various inbound data filters for a project.\n \"\"\"\n for flt in inbound_filters.get_all_filter_specs():\n if flt.id == filter_id:\n current_filter = flt\n break\n else:\n raise ResourceDoesNotExist # could not find filter with the requested id\n\n serializer = current_filter.serializer_cls(data=request.data, partial=True)\n\n if not serializer.is_valid():\n return Response(serializer.errors, status=400)\n\n current_state = inbound_filters.get_filter_state(filter_id, project)\n if isinstance(current_state, list):\n current_state = set(current_state)\n\n new_state = inbound_filters.set_filter_state(filter_id, project, serializer.validated_data)\n if isinstance(new_state, list):\n new_state = set(new_state)\n audit_log_state = audit_log.get_event_id(\"PROJECT_ENABLE\")\n\n returned_state = None\n if filter_id == \"legacy-browsers\":\n if isinstance(current_state, bool) or isinstance(new_state, bool):\n returned_state = new_state\n if not new_state:\n audit_log_state = audit_log.get_event_id(\"PROJECT_DISABLE\")\n\n elif current_state - new_state:\n returned_state = current_state - new_state\n audit_log_state = audit_log.get_event_id(\"PROJECT_DISABLE\")\n\n elif new_state - current_state:\n returned_state = new_state - current_state\n\n elif new_state == current_state:\n returned_state = new_state\n\n if filter_id in (\n FilterStatKeys.BROWSER_EXTENSION,\n FilterStatKeys.LOCALHOST,\n FilterStatKeys.WEB_CRAWLER,\n FilterStatKeys.HEALTH_CHECK,\n ):\n returned_state = filter_id\n removed = current_state - new_state\n\n if removed == 1:\n audit_log_state = audit_log.get_event_id(\"PROJECT_DISABLE\")\n\n if isinstance(returned_state, Iterable) and not isinstance(returned_state, str):\n returned_state = list(returned_state)\n self.create_audit_entry(\n request=request,\n organization=project.organization,\n target_object=project.id,\n event=audit_log_state,\n data={\"state\": returned_state, \"slug\": project.slug},\n )\n\n return Response(status=204)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@sentry_sdk.tracing.trace\ndef process_stacktraces(\n data: MutableMapping[str, Any], make_processors=None, set_raw_stacktrace: bool = True\n) -> MutableMapping[str, Any] | None:\n infos = find_stacktraces_in_data(data, include_empty_exceptions=True)\n if make_processors is None:\n processors = get_processors_for_stacktraces(data, infos)\n else:\n processors = make_processors(data, infos)\n\n # Early out if we have no processors. We don't want to record a timer\n # in that case.\n if not processors:\n return None\n\n changed = False\n\n # Build a new processing task\n processing_task = get_stacktrace_processing_task(infos, processors)\n try:\n # Preprocess step\n for processor in processing_task.iter_processors():\n with sentry_sdk.start_span(\n op=\"stacktraces.processing.process_stacktraces.preprocess_step\"\n ) as span:\n span.set_data(\"processor\", processor.__class__.__name__)\n if processor.preprocess_step(processing_task):\n changed = True\n span.set_data(\"data_changed\", True)\n\n # Process all stacktraces\n for stacktrace_info, processable_frames in processing_task.iter_processable_stacktraces():\n # Let the stacktrace processors touch the exception\n if stacktrace_info.is_exception and stacktrace_info.container:\n for processor in processing_task.iter_processors():\n with sentry_sdk.start_span(\n op=\"stacktraces.processing.process_stacktraces.process_exception\"\n ) as span:\n span.set_data(\"processor\", processor.__class__.__name__)\n if processor.process_exception(stacktrace_info.container):\n changed = True\n span.set_data(\"data_changed\", True)\n\n # If the stacktrace is empty we skip it for processing\n if not stacktrace_info.stacktrace:\n continue\n with sentry_sdk.start_span(\n op=\"stacktraces.processing.process_stacktraces.process_single_stacktrace\"\n ) as span:\n new_frames, new_raw_frames, errors = process_single_stacktrace(\n processing_task, stacktrace_info, processable_frames\n )\n if new_frames is not None:\n stacktrace_info.stacktrace[\"frames\"] = new_frames\n changed = True\n span.set_data(\"data_changed\", True)\n if (\n set_raw_stacktrace\n and new_raw_frames is not None\n and stacktrace_info.container is not None\n ):\n stacktrace_info.container[\"raw_stacktrace\"] = dict(\n stacktrace_info.stacktrace, frames=new_raw_frames\n )\n changed = True\n if errors:\n data.setdefault(\"errors\", []).extend(dedup_errors(errors))\n data.setdefault(\"_metrics\", {})[\"flag.processing.error\"] = True\n changed = True\n\n except Exception:\n logger.exception(\"stacktraces.processing.crash\")\n data.setdefault(\"_metrics\", {})[\"flag.processing.fatal\"] = True\n data.setdefault(\"_metrics\", {})[\"flag.processing.error\"] = True\n changed = True\n finally:\n for processor in processors:\n processor.close()\n processing_task.close()\n\n if changed:\n return data\n else:\n return None", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _generate_frame_annotation_conflicts(\n self, frame_id: str, frame_results, *, gt_item: dm.DatasetItem, ds_item: dm.DatasetItem\n ) -> List[AnnotationConflict]:\n conflicts = []\n\n matches, mismatches, gt_unmatched, ds_unmatched, _ = frame_results[\"all_ann_types\"]\n (\n shape_matches,\n shape_mismatches,\n shape_gt_unmatched,\n shape_ds_unmatched,\n shape_pairwise_distances,\n ) = frame_results[\"all_shape_ann_types\"]\n\n def _get_similarity(gt_ann: dm.Annotation, ds_ann: dm.Annotation) -> Optional[float]:\n return self.comparator.get_distance(shape_pairwise_distances, gt_ann, ds_ann)\n\n _matched_shapes = set(\n id(shape)\n for shape_pair in itertools.chain(shape_matches, shape_mismatches)\n for shape in shape_pair\n )\n\n def _find_closest_unmatched_shape(shape: dm.Annotation):\n this_shape_id = id(shape)\n\n this_shape_distances = []\n\n for (gt_shape_id, ds_shape_id), dist in shape_pairwise_distances.items():\n if gt_shape_id == this_shape_id:\n other_shape_id = ds_shape_id\n elif ds_shape_id == this_shape_id:\n other_shape_id = gt_shape_id\n else:\n continue\n\n this_shape_distances.append((other_shape_id, dist))\n\n matched_ann, distance = max(this_shape_distances, key=lambda v: v[1], default=(None, 0))\n return matched_ann, distance\n\n for gt_ann, ds_ann in itertools.chain(matches, mismatches):\n similarity = _get_similarity(gt_ann, ds_ann)\n if similarity and similarity < self.settings.low_overlap_threshold:\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.LOW_OVERLAP,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n self._dm_ann_to_ann_id(gt_ann, self._gt_dataset),\n ],\n )\n )\n\n for unmatched_ann in gt_unmatched:\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.MISSING_ANNOTATION,\n annotation_ids=[self._dm_ann_to_ann_id(unmatched_ann, self._gt_dataset)],\n )\n )\n\n for unmatched_ann in ds_unmatched:\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.EXTRA_ANNOTATION,\n annotation_ids=[self._dm_ann_to_ann_id(unmatched_ann, self._ds_dataset)],\n )\n )\n\n for gt_ann, ds_ann in mismatches:\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.MISMATCHING_LABEL,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n self._dm_ann_to_ann_id(gt_ann, self._gt_dataset),\n ],\n )\n )\n\n resulting_distances = [\n _get_similarity(shape_gt_ann, shape_ds_ann)\n for shape_gt_ann, shape_ds_ann in itertools.chain(shape_matches, shape_mismatches)\n ]\n\n for shape_unmatched_ann in itertools.chain(shape_gt_unmatched, shape_ds_unmatched):\n shape_matched_ann_id, similarity = _find_closest_unmatched_shape(shape_unmatched_ann)\n if shape_matched_ann_id is not None:\n _matched_shapes.add(shape_matched_ann_id)\n resulting_distances.append(similarity)\n\n resulting_distances = [\n sim if sim is not None and (sim >= 0) else 0 for sim in resulting_distances\n ]\n\n mean_iou = np.mean(resulting_distances) if resulting_distances else 0\n\n if (\n self.settings.compare_line_orientation\n and dm.AnnotationType.polyline in self.comparator.included_ann_types\n ):\n # Check line directions\n line_matcher = _LineMatcher(\n torso_r=self.settings.line_thickness,\n oriented=True,\n scale=np.prod(gt_item.image.size),\n )\n\n for gt_ann, ds_ann in itertools.chain(matches, mismatches):\n if gt_ann.type != ds_ann.type or gt_ann.type != dm.AnnotationType.polyline:\n continue\n\n non_oriented_distance = _get_similarity(gt_ann, ds_ann)\n oriented_distance = line_matcher.distance(gt_ann, ds_ann)\n\n # need to filter computation errors from line approximation\n # and (almost) orientation-independent cases\n if (\n non_oriented_distance - oriented_distance\n > self.settings.line_orientation_threshold\n ):\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.MISMATCHING_DIRECTION,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n self._dm_ann_to_ann_id(gt_ann, self._gt_dataset),\n ],\n )\n )\n\n if self.settings.check_covered_annotations:\n ds_covered_anns = self.comparator.find_covered(ds_item)\n\n for ds_ann in ds_covered_anns:\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.COVERED_ANNOTATION,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n ],\n )\n )\n\n if self.settings.compare_attributes:\n for gt_ann, ds_ann in matches:\n attribute_results = self.comparator.match_attrs(gt_ann, ds_ann)\n if any(attribute_results[1:]):\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.MISMATCHING_ATTRIBUTES,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n self._dm_ann_to_ann_id(gt_ann, self._gt_dataset),\n ],\n )\n )\n\n if self.settings.compare_groups:\n gt_groups, gt_group_map = self.comparator.find_groups(gt_item)\n ds_groups, ds_group_map = self.comparator.find_groups(ds_item)\n shape_matched_objects = shape_matches + shape_mismatches\n ds_to_gt_groups = self.comparator.match_groups(\n gt_groups, ds_groups, shape_matched_objects\n )\n\n for gt_ann, ds_ann in shape_matched_objects:\n gt_group = gt_groups.get(gt_group_map[id(gt_ann)], [gt_ann])\n ds_group = ds_groups.get(ds_group_map[id(ds_ann)], [ds_ann])\n ds_gt_group = ds_to_gt_groups.get(ds_group_map[id(ds_ann)], None)\n\n if (\n # Check ungrouped objects\n (len(gt_group) == 1 and len(ds_group) != 1)\n or\n # Check grouped objects\n ds_gt_group != gt_group_map[id(gt_ann)]\n ):\n conflicts.append(\n AnnotationConflict(\n frame_id=frame_id,\n type=AnnotationConflictType.MISMATCHING_GROUPS,\n annotation_ids=[\n self._dm_ann_to_ann_id(ds_ann, self._ds_dataset),\n self._dm_ann_to_ann_id(gt_ann, self._gt_dataset),\n ],\n )\n )\n\n valid_shapes_count = len(shape_matches) + len(shape_mismatches)\n missing_shapes_count = len(shape_gt_unmatched)\n extra_shapes_count = len(shape_ds_unmatched)\n total_shapes_count = (\n len(shape_matches)\n + len(shape_mismatches)\n + len(shape_gt_unmatched)\n + len(shape_ds_unmatched)\n )\n ds_shapes_count = len(shape_matches) + len(shape_mismatches) + len(shape_ds_unmatched)\n gt_shapes_count = len(shape_matches) + len(shape_mismatches) + len(shape_gt_unmatched)\n\n valid_labels_count = len(matches)\n invalid_labels_count = len(mismatches)\n total_labels_count = valid_labels_count + invalid_labels_count\n\n confusion_matrix_labels, confusion_matrix, label_id_map = self._make_zero_confusion_matrix()\n for gt_ann, ds_ann in itertools.chain(\n # fully matched annotations - shape, label, attributes\n matches,\n mismatches,\n zip(itertools.repeat(None), ds_unmatched),\n zip(gt_unmatched, itertools.repeat(None)),\n ):\n ds_label_idx = label_id_map[ds_ann.label] if ds_ann else self._UNMATCHED_IDX\n gt_label_idx = label_id_map[gt_ann.label] if gt_ann else self._UNMATCHED_IDX\n confusion_matrix[ds_label_idx, gt_label_idx] += 1\n\n self._frame_results[frame_id] = ComparisonReportFrameSummary(\n annotations=self._generate_annotations_summary(\n confusion_matrix, confusion_matrix_labels\n ),\n annotation_components=ComparisonReportAnnotationComponentsSummary(\n shape=ComparisonReportAnnotationShapeSummary(\n valid_count=valid_shapes_count,\n missing_count=missing_shapes_count,\n extra_count=extra_shapes_count,\n total_count=total_shapes_count,\n ds_count=ds_shapes_count,\n gt_count=gt_shapes_count,\n mean_iou=mean_iou,\n ),\n label=ComparisonReportAnnotationLabelSummary(\n valid_count=valid_labels_count,\n invalid_count=invalid_labels_count,\n total_count=total_labels_count,\n ),\n ),\n conflicts=conflicts,\n )\n\n return conflicts", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def __init__(self, data=None, **kwargs):\n super().__init__(data=data, **kwargs)\n\n initial = kwargs.get(\"initial\") or {}\n for key, value in self.data.items():\n initial[key.lstrip(self.prefix or \"\")] = value\n\n has_credentials = all(initial.get(k) for k in (\"host\", \"key\"))\n client = None\n if has_credentials:\n client = RedmineClient(initial[\"host\"], initial[\"key\"])\n try:\n projects = client.get_projects()\n except Exception:\n has_credentials = False\n else:\n project_choices = [\n (p[\"id\"], \"{} ({})\".format(p[\"name\"], p[\"identifier\"]))\n for p in projects[\"projects\"]\n ]\n set_field_choices(self.fields[\"project_id\"], project_choices)\n\n if client is not None and has_credentials:\n try:\n trackers = client.get_trackers()\n except Exception:\n del self.fields[\"tracker_id\"]\n else:\n tracker_choices = [(p[\"id\"], p[\"name\"]) for p in trackers[\"trackers\"]]\n set_field_choices(self.fields[\"tracker_id\"], tracker_choices)\n\n try:\n priorities = client.get_priorities()\n except Exception:\n del self.fields[\"default_priority\"]\n else:\n tracker_choices = [(p[\"id\"], p[\"name\"]) for p in priorities[\"issue_priorities\"]]\n set_field_choices(self.fields[\"default_priority\"], tracker_choices)\n\n if not has_credentials:\n del self.fields[\"project_id\"]\n del self.fields[\"tracker_id\"]\n del self.fields[\"default_priority\"]", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def register_or_switch_wallet(\n self,\n target_wallet_name,\n public_did=False,\n webhook_port: int = None,\n mediator_agent=None,\n cred_type: str = CRED_FORMAT_INDY,\n endorser_agent=None,\n taa_accept=False,\n ):\n if webhook_port is not None:\n await self.listen_webhooks(webhook_port)\n self.log(f\"Register or switch to wallet {target_wallet_name}\")\n if target_wallet_name == self.agency_wallet_name:\n self.ident = self.agency_ident\n self.wallet_name = self.agency_wallet_name\n self.seed = self.agency_wallet_seed\n self.did = self.agency_wallet_did\n self.wallet_key = self.agency_wallet_key\n\n wallet_params = await self.get_id_and_token(self.wallet_name)\n self.managed_wallet_params[\"wallet_id\"] = wallet_params[\"id\"]\n self.managed_wallet_params[\"token\"] = wallet_params[\"token\"]\n\n if taa_accept:\n await self.taa_accept()\n\n self.log(f\"Switching to AGENCY wallet {target_wallet_name}\")\n return False\n\n # check if wallet exists already\n wallets = await self.agency_admin_GET(\"/multitenancy/wallets\")\n for wallet in wallets[\"results\"]:\n if wallet[\"settings\"][\"wallet.name\"] == target_wallet_name:\n # if so set local agent attributes\n self.wallet_name = target_wallet_name\n # assume wallet key is wallet name\n self.wallet_key = target_wallet_name\n self.ident = target_wallet_name\n # we can't recover the seed so let's set it to None and see what happens\n self.seed = None\n\n wallet_params = await self.get_id_and_token(self.wallet_name)\n self.managed_wallet_params[\"wallet_id\"] = wallet_params[\"id\"]\n self.managed_wallet_params[\"token\"] = wallet_params[\"token\"]\n\n if taa_accept:\n await self.taa_accept()\n\n self.log(f\"Switching to EXISTING wallet {target_wallet_name}\")\n return False\n\n # if not then create it\n wallet_params = {\n \"wallet_key\": target_wallet_name,\n \"wallet_name\": target_wallet_name,\n \"wallet_type\": self.wallet_type,\n \"label\": target_wallet_name,\n \"wallet_webhook_urls\": [self.webhook_url],\n \"wallet_dispatch_type\": \"both\",\n }\n self.wallet_name = target_wallet_name\n self.wallet_key = target_wallet_name\n self.ident = target_wallet_name\n new_wallet = await self.agency_admin_POST(\"/multitenancy/wallet\", wallet_params)\n self.log(\"New wallet params:\", new_wallet)\n self.managed_wallet_params = new_wallet\n\n # if endorser, endorse the wallet ledger operations\n if endorser_agent:\n self.log(\"Connect sub-wallet to endorser ...\")\n if not await connect_wallet_to_endorser(self, endorser_agent):\n raise Exception(\"Endorser setup FAILED :-(\")\n # if mediation, mediate the wallet connections\n if mediator_agent:\n if not await connect_wallet_to_mediator(self, mediator_agent):\n log_msg(\"Mediation setup FAILED :-(\")\n raise Exception(\"Mediation setup FAILED :-(\")\n if taa_accept:\n await self.taa_accept()\n\n if public_did:\n if cred_type == CRED_FORMAT_INDY:\n # assign public did\n new_did = await self.admin_POST(\"/wallet/did/create\")\n self.did = new_did[\"result\"][\"did\"]\n await self.register_did(\n did=new_did[\"result\"][\"did\"],\n verkey=new_did[\"result\"][\"verkey\"],\n )\n if self.endorser_role and self.endorser_role == \"author\":\n if endorser_agent:\n await self.admin_POST(\"/wallet/did/public?did=\" + self.did)\n await asyncio.sleep(3.0)\n else:\n await self.admin_POST(\"/wallet/did/public?did=\" + self.did)\n await asyncio.sleep(3.0)\n elif cred_type == CRED_FORMAT_VC_DI:\n # assign public did\n new_did = await self.admin_POST(\"/wallet/did/create\")\n self.did = new_did[\"result\"][\"did\"]\n await self.register_did(\n did=new_did[\"result\"][\"did\"],\n verkey=new_did[\"result\"][\"verkey\"],\n cred_type=CRED_FORMAT_VC_DI,\n )\n if self.endorser_role and self.endorser_role == \"author\":\n if endorser_agent:\n await self.admin_POST(\"/wallet/did/public?did=\" + self.did)\n await asyncio.sleep(3.0)\n else:\n await self.admin_POST(\"/wallet/did/public?did=\" + self.did)\n await asyncio.sleep(3.0)\n elif cred_type == CRED_FORMAT_JSON_LD:\n # create did of appropriate type\n data = {\"method\": DID_METHOD_KEY, \"options\": {\"key_type\": KEY_TYPE_BLS}}\n new_did = await self.admin_POST(\"/wallet/did/create\", data=data)\n self.did = new_did[\"result\"][\"did\"]\n\n # did:key is not registered as a public did\n else:\n # todo ignore for now\n pass\n\n self.log(f\"Created NEW wallet {target_wallet_name}\")\n return True", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _best_version(fields):\n \"\"\"Detect the best version depending on the fields used.\"\"\"\n def _has_marker(keys, markers):\n return any(marker in keys for marker in markers)\n\n keys = [key for key, value in fields.items() if value not in ([], 'UNKNOWN', None)]\n possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.1', '2.2'] # 2.0 removed\n\n # first let's try to see if a field is not part of one of the version\n for key in keys:\n if key not in _241_FIELDS and '1.0' in possible_versions:\n possible_versions.remove('1.0')\n logger.debug('Removed 1.0 due to %s', key)\n if key not in _314_FIELDS and '1.1' in possible_versions:\n possible_versions.remove('1.1')\n logger.debug('Removed 1.1 due to %s', key)\n if key not in _345_FIELDS and '1.2' in possible_versions:\n possible_versions.remove('1.2')\n logger.debug('Removed 1.2 due to %s', key)\n if key not in _566_FIELDS and '1.3' in possible_versions:\n possible_versions.remove('1.3')\n logger.debug('Removed 1.3 due to %s', key)\n if key not in _566_FIELDS and '2.1' in possible_versions:\n if key != 'Description': # In 2.1, description allowed after headers\n possible_versions.remove('2.1')\n logger.debug('Removed 2.1 due to %s', key)\n if key not in _643_FIELDS and '2.2' in possible_versions:\n possible_versions.remove('2.2')\n logger.debug('Removed 2.2 due to %s', key)\n # if key not in _426_FIELDS and '2.0' in possible_versions:\n # possible_versions.remove('2.0')\n # logger.debug('Removed 2.0 due to %s', key)\n\n # possible_version contains qualified versions\n if len(possible_versions) == 1:\n return possible_versions[0] # found !\n elif len(possible_versions) == 0:\n logger.debug('Out of options - unknown metadata set: %s', fields)\n raise MetadataConflictError('Unknown metadata set')\n\n # let's see if one unique marker is found\n is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)\n is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)\n is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)\n # is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)\n is_2_2 = '2.2' in possible_versions and _has_marker(keys, _643_MARKERS)\n if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_2) > 1:\n raise MetadataConflictError('You used incompatible 1.1/1.2/2.1/2.2 fields')\n\n # we have the choice, 1.0, or 1.2, 2.1 or 2.2\n # - 1.0 has a broken Summary field but works with all tools\n # - 1.1 is to avoid\n # - 1.2 fixes Summary but has little adoption\n # - 2.1 adds more features\n # - 2.2 is the latest\n if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_2:\n # we couldn't find any specific marker\n if PKG_INFO_PREFERRED_VERSION in possible_versions:\n return PKG_INFO_PREFERRED_VERSION\n if is_1_1:\n return '1.1'\n if is_1_2:\n return '1.2'\n if is_2_1:\n return '2.1'\n # if is_2_2:\n # return '2.2'\n\n return '2.2'", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def handle_ignored(\n group_ids: Sequence[Group],\n group_list: Sequence[Group],\n status_details: dict[str, Any],\n acting_user: User | None,\n user: User | RpcUser,\n) -> IgnoredStatusDetails:\n \"\"\"\n Handle issues that are ignored and create a snooze for them.\n\n Evaluate ignored issues according to the statusDetails and create a snooze as needed.\n\n Returns: a dict with the statusDetails for ignore conditions.\n \"\"\"\n metrics.incr(\"group.ignored\", skip_internal=True)\n for group in group_ids:\n remove_group_from_inbox(group, action=GroupInboxRemoveAction.IGNORED, user=acting_user)\n\n new_status_details: IgnoredStatusDetails = {}\n ignore_duration = (\n status_details.pop(\"ignoreDuration\", None) or status_details.pop(\"snoozeDuration\", None)\n ) or None\n ignore_count = status_details.pop(\"ignoreCount\", None) or None\n ignore_window = status_details.pop(\"ignoreWindow\", None) or None\n ignore_user_count = status_details.pop(\"ignoreUserCount\", None) or None\n ignore_user_window = status_details.pop(\"ignoreUserWindow\", None) or None\n if ignore_duration or ignore_count or ignore_user_count:\n if ignore_duration:\n ignore_until = timezone.now() + timedelta(minutes=ignore_duration)\n else:\n ignore_until = None\n for group in group_list:\n state = {}\n if ignore_count and not ignore_window:\n state[\"times_seen\"] = group.times_seen\n if ignore_user_count and not ignore_user_window:\n state[\"users_seen\"] = group.count_users_seen(\n referrer=Referrer.TAGSTORE_GET_GROUPS_USER_COUNTS_IGNORED.value\n )\n GroupSnooze.objects.create_or_update(\n group=group,\n values={\n \"until\": ignore_until,\n \"count\": ignore_count,\n \"window\": ignore_window,\n \"user_count\": ignore_user_count,\n \"user_window\": ignore_user_window,\n \"state\": state,\n \"actor_id\": user.id if user.is_authenticated else None,\n },\n )\n\n Group.objects.filter(id=group.id, status=GroupStatus.UNRESOLVED).update(\n substatus=GroupSubStatus.UNTIL_CONDITION_MET, status=GroupStatus.IGNORED\n )\n with in_test_hide_transaction_boundary():\n serialized_user = user_service.serialize_many(\n filter=dict(user_ids=[user.id]), as_user=serialize_generic_user(user)\n )\n new_status_details = IgnoredStatusDetails(\n ignoreCount=ignore_count,\n ignoreUntil=ignore_until,\n ignoreUserCount=ignore_user_count,\n ignoreUserWindow=ignore_user_window,\n ignoreWindow=ignore_window,\n actor=serialized_user[0] if serialized_user else None,\n )\n else:\n GroupSnooze.objects.filter(group__in=group_ids).delete()\n\n return new_status_details", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n @lru_cache(maxsize=1024)\n def parse(cls, color: str) -> \"Color\":\n \"\"\"Parse a color definition.\"\"\"\n original_color = color\n color = color.lower().strip()\n\n if color == \"default\":\n return cls(color, type=ColorType.DEFAULT)\n\n color_number = ANSI_COLOR_NAMES.get(color)\n if color_number is not None:\n return cls(\n color,\n type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),\n number=color_number,\n )\n\n color_match = RE_COLOR.match(color)\n if color_match is None:\n raise ColorParseError(f\"{original_color!r} is not a valid color\")\n\n color_24, color_8, color_rgb = color_match.groups()\n if color_24:\n triplet = ColorTriplet(\n int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)\n )\n return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n elif color_8:\n number = int(color_8)\n if number > 255:\n raise ColorParseError(f\"color number must be <= 255 in {color!r}\")\n return cls(\n color,\n type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n number=number,\n )\n\n else: # color_rgb:\n components = color_rgb.split(\",\")\n if len(components) != 3:\n raise ColorParseError(\n f\"expected three components in {original_color!r}\"\n )\n red, green, blue = components\n triplet = ColorTriplet(int(red), int(green), int(blue))\n if not all(component <= 255 for component in triplet):\n raise ColorParseError(\n f\"color components must be <= 255 in {original_color!r}\"\n )\n return cls(color, ColorType.TRUECOLOR, triplet=triplet)", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n\n dev_mode = getattr(settings, \"EDITOR_DEV_MODE\", False)\n prefix = \"/dev\" if dev_mode else settings.STATIC_URL\n\n # get our list of assets to incude\n scripts = []\n styles = []\n\n if dev_mode: # pragma: no cover\n response = requests.get(\"http://localhost:3000/manifest.json\")\n data = response.json()\n else:\n with open(\"node_modules/@weni/flow-editor/build/manifest.json\") as json_file:\n data = json.load(json_file)\n\n for key, filedata in data.items():\n # tack on our prefix for dev mode\n filename = prefix + \"./\" + filedata[\"file\"]\n\n # ignore precache manifest\n if key.startswith(\"precache-manifest\") or key.startswith(\"service-worker\"):\n continue\n\n # css files\n if key.endswith(\".css\") and filename.endswith(\".css\"):\n styles.append(filename)\n\n # javascript\n if key.endswith(\".js\") or key.endswith(\".jsx\") and filename.endswith(\".js\"):\n scripts.append(filename)\n\n flow = self.object\n\n context[\"scripts\"] = scripts\n context[\"styles\"] = styles\n context[\"migrate\"] = \"migrate\" in self.request.GET\n\n if flow.is_archived or not (\n flow.is_mutable or self.request.user.email.endswith(settings.MUTABLE_EDITOR_DOMAINS)\n ):\n context[\"mutable\"] = False\n context[\"can_start\"] = False\n context[\"can_simulate\"] = False\n else:\n context[\"mutable\"] = self.has_org_perm(\"flows.flow_update\") and not self.request.user.is_superuser\n context[\"can_start\"] = flow.flow_type != Flow.TYPE_VOICE or flow.org.supports_ivr()\n context[\"can_simulate\"] = True\n\n context[\"dev_mode\"] = dev_mode\n context[\"is_starting\"] = flow.is_starting()\n context[\"feature_filters\"] = json.dumps(self.get_features(flow.org))\n return context", "smellKey": "S3776", "smellId": null, "repo": "weni-ai_flows", "language": "python"} {"function": "@lru_cache(maxsize=1)\ndef _android_folder() -> str | None: # noqa: C901, PLR0912\n \"\"\":return: base folder for the Android OS or None if it cannot be found\"\"\"\n result: str | None = None\n # type checker isn't happy with our \"import android\", just don't do this when type checking see\n # https://stackoverflow.com/a/61394121\n if not TYPE_CHECKING:\n try:\n # First try to get a path to android app using python4android (if available)...\n from android import mActivity # noqa: PLC0415\n\n context = cast(\"android.content.Context\", mActivity.getApplicationContext()) # noqa: F821\n result = context.getFilesDir().getParentFile().getAbsolutePath()\n except Exception: # noqa: BLE001\n result = None\n if result is None:\n try:\n # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful\n # result...\n from jnius import autoclass # noqa: PLC0415\n\n context = autoclass(\"android.content.Context\")\n result = context.getFilesDir().getParentFile().getAbsolutePath()\n except Exception: # noqa: BLE001\n result = None\n if result is None:\n # and if that fails, too, find an android folder looking at path on the sys.path\n # warning: only works for apps installed under /data, not adopted storage etc.\n pattern = re.compile(r\"/data/(data|user/\\d+)/(.+)/files\")\n for path in sys.path:\n if pattern.match(path):\n result = path.split(\"/files\")[0]\n break\n else:\n result = None\n if result is None:\n # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into\n # account\n pattern = re.compile(r\"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\\d+)/(.+)/files\")\n for path in sys.path:\n if pattern.match(path):\n result = path.split(\"/files\")[0]\n break\n else:\n result = None\n return result", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def arvados_job_spec(self, runtimeContext, git_info):\n \"\"\"Create an Arvados container request for this workflow.\n\n The returned dict can be used to create a container passed as\n the +body+ argument to container_requests().create().\n \"\"\"\n\n adjustDirObjs(self.job_order, trim_listing)\n visit_class(self.job_order, (\"File\", \"Directory\"), trim_anonymous_location)\n visit_class(self.job_order, (\"File\", \"Directory\"), remove_redundant_fields)\n\n secret_mounts = {}\n for param in sorted(self.job_order.keys()):\n if self.secret_store.has_secret(self.job_order[param]):\n mnt = \"/secrets/s%d\" % len(secret_mounts)\n secret_mounts[mnt] = {\n \"kind\": \"text\",\n \"content\": self.secret_store.retrieve(self.job_order[param])\n }\n self.job_order[param] = {\"$include\": mnt}\n\n container_image = arvados_jobs_image(self.arvrunner, self.jobs_image, runtimeContext)\n\n workflow_runner_req, _ = self.embedded_tool.get_requirement(\"http://arvados.org/cwl#WorkflowRunnerResources\")\n if workflow_runner_req and workflow_runner_req.get(\"acrContainerImage\"):\n container_image = workflow_runner_req.get(\"acrContainerImage\")\n\n container_req = {\n \"name\": self.name,\n \"output_path\": \"/var/spool/cwl\",\n \"cwd\": \"/var/spool/cwl\",\n \"priority\": self.priority,\n \"state\": \"Committed\",\n \"container_image\": container_image,\n \"mounts\": {\n \"/var/lib/cwl/cwl.input.json\": {\n \"kind\": \"json\",\n \"content\": self.job_order\n },\n \"stdout\": {\n \"kind\": \"file\",\n \"path\": \"/var/spool/cwl/cwl.output.json\"\n },\n \"/var/spool/cwl\": {\n \"kind\": \"collection\",\n \"writable\": True\n }\n },\n \"secret_mounts\": secret_mounts,\n \"runtime_constraints\": {\n \"vcpus\": math.ceil(self.submit_runner_cores),\n \"ram\": 1024*1024 * (math.ceil(self.submit_runner_ram) + math.ceil(self.collection_cache_size)),\n \"API\": True\n },\n \"use_existing\": self.reuse_runner,\n \"properties\": {}\n }\n\n if self.embedded_tool.tool.get(\"id\", \"\").startswith(\"keep:\"):\n sp = self.embedded_tool.tool[\"id\"].split('/')\n workflowcollection = sp[0][5:]\n workflowname = \"/\".join(sp[1:])\n workflowpath = \"/var/lib/cwl/workflow/%s\" % workflowname\n container_req[\"mounts\"][\"/var/lib/cwl/workflow\"] = {\n \"kind\": \"collection\",\n \"portable_data_hash\": \"%s\" % workflowcollection\n }\n elif self.embedded_tool.tool.get(\"id\", \"\").startswith(\"arvwf:\"):\n uuid, frg = urllib.parse.urldefrag(self.embedded_tool.tool[\"id\"])\n workflowpath = \"/var/lib/cwl/workflow.json#\" + frg\n packedtxt = self.loadingContext.loader.fetch_text(uuid)\n yaml = ruamel.yaml.YAML(typ='safe', pure=True)\n packed = yaml.load(packedtxt)\n container_req[\"mounts\"][\"/var/lib/cwl/workflow.json\"] = {\n \"kind\": \"json\",\n \"content\": packed\n }\n container_req[\"properties\"][\"template_uuid\"] = self.embedded_tool.tool[\"id\"][6:33]\n elif self.embedded_tool.tool.get(\"id\", \"\").startswith(\"file:\"):\n raise WorkflowException(\"Tool id '%s' is a local file but expected keep: or arvwf:\" % self.embedded_tool.tool.get(\"id\"))\n else:\n main = self.loadingContext.loader.idx[\"_:main\"]\n if main.get(\"id\") == \"_:main\":\n del main[\"id\"]\n workflowpath = \"/var/lib/cwl/workflow.json#main\"\n container_req[\"mounts\"][\"/var/lib/cwl/workflow.json\"] = {\n \"kind\": \"json\",\n \"content\": main\n }\n\n container_req[\"properties\"].update({k.replace(\"http://arvados.org/cwl#\", \"arv:\"): v for k, v in git_info.items()})\n\n properties_req, _ = self.embedded_tool.get_requirement(\"http://arvados.org/cwl#ProcessProperties\")\n if properties_req:\n builder = make_builder(self.job_order, self.embedded_tool.hints, self.embedded_tool.requirements, runtimeContext, self.embedded_tool.metadata)\n for pr in properties_req[\"processProperties\"]:\n container_req[\"properties\"][pr[\"propertyName\"]] = builder.do_eval(pr[\"propertyValue\"])\n\n # --local means execute the workflow instead of submitting a container request\n # --api=containers means use the containers API\n # --no-log-timestamps means don't add timestamps (the logging infrastructure does this)\n # --disable-validate because we already validated so don't need to do it again\n # --eval-timeout is the timeout for javascript invocation\n # --parallel-task-count is the number of threads to use for job submission\n # --enable/disable-reuse sets desired job reuse\n # --collection-cache-size sets aside memory to store collections\n command = [\"arvados-cwl-runner\",\n \"--local\",\n \"--api=containers\",\n \"--no-log-timestamps\",\n \"--disable-validate\",\n \"--disable-color\",\n \"--eval-timeout=%s\" % self.arvrunner.eval_timeout,\n \"--thread-count=%s\" % self.arvrunner.thread_count,\n \"--enable-reuse\" if self.enable_reuse else \"--disable-reuse\",\n \"--collection-cache-size=%s\" % self.collection_cache_size]\n\n if self.output_name:\n command.append(\"--output-name=\" + self.output_name)\n container_req[\"output_name\"] = self.output_name\n\n if self.output_tags:\n command.append(\"--output-tags=\" + self.output_tags)\n\n if runtimeContext.debug:\n command.append(\"--debug\")\n\n if runtimeContext.storage_classes != \"default\" and runtimeContext.storage_classes:\n command.append(\"--storage-classes=\" + runtimeContext.storage_classes)\n\n if runtimeContext.intermediate_storage_classes != \"default\" and runtimeContext.intermediate_storage_classes:\n command.append(\"--intermediate-storage-classes=\" + runtimeContext.intermediate_storage_classes)\n\n if runtimeContext.on_error:\n command.append(\"--on-error=\" + self.on_error)\n\n if runtimeContext.intermediate_output_ttl:\n command.append(\"--intermediate-output-ttl=%d\" % runtimeContext.intermediate_output_ttl)\n\n if runtimeContext.trash_intermediate:\n command.append(\"--trash-intermediate\")\n\n if runtimeContext.project_uuid:\n command.append(\"--project-uuid=\"+runtimeContext.project_uuid)\n\n if self.enable_dev:\n command.append(\"--enable-dev\")\n\n if runtimeContext.enable_preemptible is True:\n command.append(\"--enable-preemptible\")\n\n if runtimeContext.enable_preemptible is False:\n command.append(\"--disable-preemptible\")\n\n if runtimeContext.varying_url_params:\n command.append(\"--varying-url-params=\"+runtimeContext.varying_url_params)\n\n if runtimeContext.prefer_cached_downloads:\n command.append(\"--prefer-cached-downloads\")\n\n if runtimeContext.enable_usage_report is True:\n command.append(\"--enable-usage-report\")\n\n if runtimeContext.enable_usage_report is False:\n command.append(\"--disable-usage-report\")\n\n if self.fast_parser:\n command.append(\"--fast-parser\")\n\n command.extend([workflowpath, \"/var/lib/cwl/cwl.input.json\"])\n\n container_req[\"command\"] = command\n\n return container_req", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def get_member_flags(name: str, itype: Instance, class_obj: bool = False) -> set[int]:\n \"\"\"Detect whether a member 'name' is settable, whether it is an\n instance or class variable, and whether it is class or static method.\n\n The flags are defined as following:\n * IS_SETTABLE: whether this attribute can be set, not set for methods and\n non-settable properties;\n * IS_CLASSVAR: set if the variable is annotated as 'x: ClassVar[t]';\n * IS_CLASS_OR_STATIC: set for methods decorated with @classmethod or\n with @staticmethod.\n \"\"\"\n info = itype.type\n method = info.get_method(name)\n setattr_meth = info.get_method(\"__setattr__\")\n if method:\n if isinstance(method, Decorator):\n if method.var.is_staticmethod or method.var.is_classmethod:\n return {IS_CLASS_OR_STATIC}\n elif method.var.is_property:\n return {IS_VAR}\n elif method.is_property: # this could be settable property\n assert isinstance(method, OverloadedFuncDef)\n dec = method.items[0]\n assert isinstance(dec, Decorator)\n if dec.var.is_settable_property or setattr_meth:\n return {IS_VAR, IS_SETTABLE}\n else:\n return {IS_VAR}\n return set() # Just a regular method\n node = info.get(name)\n if not node:\n if setattr_meth:\n return {IS_SETTABLE}\n if itype.extra_attrs and name in itype.extra_attrs.attrs:\n flags = set()\n if name not in itype.extra_attrs.immutable:\n flags.add(IS_SETTABLE)\n return flags\n return set()\n v = node.node\n # just a variable\n if isinstance(v, Var):\n if v.is_property:\n return {IS_VAR}\n flags = {IS_VAR}\n if not v.is_final:\n flags.add(IS_SETTABLE)\n if v.is_classvar:\n flags.add(IS_CLASSVAR)\n if class_obj and v.is_inferred:\n flags.add(IS_CLASSVAR)\n return flags\n return set()", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "async def create_and_send_schema(\n self,\n issuer: IndyIssuer,\n schema_name: str,\n schema_version: str,\n attribute_names: Sequence[str],\n write_ledger: bool = True,\n endorser_did: Optional[str] = None,\n ) -> Tuple[str, dict]:\n \"\"\"Send schema to ledger.\n\n Args:\n issuer: The issuer instance to use for schema creation\n schema_name: The schema name\n schema_version: The schema version\n attribute_names: A list of schema attributes\n write_ledger: Flag to write the schema to the ledger\n endorser_did: Optional DID of the endorser\n\n \"\"\"\n\n public_info = await self.get_wallet_public_did()\n if not public_info:\n raise BadLedgerRequestError(\"Cannot publish schema without a public DID\")\n\n if not bool(IndyDID.PATTERN.match(public_info.did)):\n raise BadLedgerRequestError(\n \"Cannot publish schema when public DID is not an IndyDID\"\n )\n\n schema_info = await self.check_existing_schema(\n public_info.did, schema_name, schema_version, attribute_names\n )\n if schema_info:\n LOGGER.warning(\"Schema already exists on ledger. Returning details.\")\n schema_id, schema_def = schema_info\n else:\n if await self.is_ledger_read_only():\n raise LedgerError(\n \"Error cannot write schema when ledger is in read only mode, \"\n \"or TAA is required and not accepted\"\n )\n\n try:\n schema_id, schema_json = await issuer.create_schema(\n public_info.did,\n schema_name,\n schema_version,\n attribute_names,\n )\n except IndyIssuerError as err:\n raise LedgerError(err.message) from err\n schema_def = json.loads(schema_json)\n\n schema_req = await self._create_schema_request(\n public_info,\n schema_json,\n write_ledger=write_ledger,\n endorser_did=endorser_did,\n )\n\n try:\n resp = await self.txn_submit(\n schema_req,\n sign=True,\n sign_did=public_info,\n write_ledger=write_ledger,\n )\n\n if not write_ledger:\n return schema_id, {\"signed_txn\": resp}\n\n try:\n # parse sequence number out of response\n seq_no = json.loads(resp)[\"result\"][\"txnMetadata\"][\"seqNo\"]\n schema_def[\"seqNo\"] = seq_no\n except KeyError as err:\n raise LedgerError(\n \"Failed to parse schema sequence number from ledger response\"\n ) from err\n except LedgerTransactionError as e:\n # Identify possible duplicate schema errors on indy-node < 1.9 and > 1.9\n if (\n \"can have one and only one SCHEMA with name\" in e.message\n or \"UnauthorizedClientRequest\" in e.message\n ):\n # handle potential race condition if multiple agents are publishing\n # the same schema simultaneously\n schema_info = await self.check_existing_schema(\n public_info.did, schema_name, schema_version, attribute_names\n )\n if schema_info:\n LOGGER.warning(\n \"Schema already exists on ledger. Returning details.\"\n \" Error: %s\",\n e,\n )\n schema_id, schema_def = schema_info\n else:\n raise\n\n return schema_id, schema_def", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def divide(self, offsets: Iterable[int]) -> Lines:\n \"\"\"Divide text in to a number of lines at given offsets.\n\n Args:\n offsets (Iterable[int]): Offsets used to divide text.\n\n Returns:\n Lines: New RichText instances between offsets.\n \"\"\"\n _offsets = list(offsets)\n\n if not _offsets:\n return Lines([self.copy()])\n\n text = self.plain\n text_length = len(text)\n divide_offsets = [0, *_offsets, text_length]\n line_ranges = list(zip(divide_offsets, divide_offsets[1:]))\n\n style = self.style\n justify = self.justify\n overflow = self.overflow\n _Text = Text\n new_lines = Lines(\n _Text(\n text[start:end],\n style=style,\n justify=justify,\n overflow=overflow,\n )\n for start, end in line_ranges\n )\n if not self._spans:\n return new_lines\n\n _line_appends = [line._spans.append for line in new_lines._lines]\n line_count = len(line_ranges)\n _Span = Span\n\n for span_start, span_end, style in self._spans:\n\n lower_bound = 0\n upper_bound = line_count\n start_line_no = (lower_bound + upper_bound) // 2\n\n while True:\n line_start, line_end = line_ranges[start_line_no]\n if span_start < line_start:\n upper_bound = start_line_no - 1\n elif span_start > line_end:\n lower_bound = start_line_no + 1\n else:\n break\n start_line_no = (lower_bound + upper_bound) // 2\n\n if span_end < line_end:\n end_line_no = start_line_no\n else:\n end_line_no = lower_bound = start_line_no\n upper_bound = line_count\n\n while True:\n line_start, line_end = line_ranges[end_line_no]\n if span_end < line_start:\n upper_bound = end_line_no - 1\n elif span_end > line_end:\n lower_bound = end_line_no + 1\n else:\n break\n end_line_no = (lower_bound + upper_bound) // 2\n\n for line_no in range(start_line_no, end_line_no + 1):\n line_start, line_end = line_ranges[line_no]\n new_start = max(0, span_start - line_start)\n new_end = min(span_end - line_start, line_end - line_start)\n if new_end > new_start:\n _line_appends[line_no](_Span(new_start, new_end, style))\n\n return new_lines", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def sync_assignee_outbound(\n self,\n external_issue: ExternalIssue,\n user: RpcUser | None,\n assign: bool = True,\n **kwargs: Any,\n ) -> None:\n \"\"\"\n Propagate a sentry issue's assignee to a jira issue's assignee\n \"\"\"\n client = self.get_client()\n\n jira_user = None\n if user and assign:\n for ue in user.emails:\n try:\n possible_users = client.search_users_for_issue(external_issue.key, ue)\n except (ApiUnauthorized, ApiError):\n continue\n for possible_user in possible_users:\n email = possible_user.get(\"emailAddress\")\n # match on lowercase email\n if email and email.lower() == ue.lower():\n jira_user = possible_user\n break\n if jira_user is None:\n # TODO(jess): do we want to email people about these types of failures?\n logger.info(\n \"jira.assignee-not-found\",\n extra={\n \"integration_id\": external_issue.integration_id,\n \"user_id\": user.id,\n \"issue_key\": external_issue.key,\n },\n )\n return\n\n try:\n id_field = client.user_id_field()\n client.assign_issue(external_issue.key, jira_user and jira_user.get(id_field))\n except (ApiUnauthorized, ApiError):\n # TODO(jess): do we want to email people about these types of failures?\n logger.info(\n \"jira.failed-to-assign\",\n extra={\n \"organization_id\": external_issue.organization_id,\n \"integration_id\": external_issue.integration_id,\n \"user_id\": user.id if user else None,\n \"issue_key\": external_issue.key,\n },\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def visit_decorator(self, dec: Decorator) -> None:\n if dec.decorators:\n decorators_to_store = dec.decorators.copy()\n decorators_to_remove: list[int] = []\n # the index of the last non-register decorator before finding a register decorator\n # when going through decorators from top to bottom\n last_non_register: int | None = None\n for i, d in enumerate(decorators_to_store):\n impl = get_singledispatch_register_call_info(d, dec.func)\n if impl is not None:\n self.singledispatch_impls[impl.singledispatch_func].append(\n (impl.dispatch_type, dec.func)\n )\n decorators_to_remove.append(i)\n if last_non_register is not None:\n # found a register decorator after a non-register decorator, which we\n # don't support because we'd have to make a copy of the function before\n # calling the decorator so that we can call it later, which complicates\n # the implementation for something that is probably not commonly used\n self.errors.error(\n \"Calling decorator after registering function not supported\",\n self.current_path,\n decorators_to_store[last_non_register].line,\n )\n else:\n if refers_to_fullname(d, \"functools.singledispatch\"):\n decorators_to_remove.append(i)\n # make sure that we still treat the function as a singledispatch function\n # even if we don't find any registered implementations (which might happen\n # if all registered implementations are registered dynamically)\n self.singledispatch_impls.setdefault(dec.func, [])\n last_non_register = i\n\n if decorators_to_remove:\n # calling register on a function that tries to dispatch based on type annotations\n # raises a TypeError because compiled functions don't have an __annotations__\n # attribute\n self.decorators_to_remove[dec.func] = decorators_to_remove\n\n super().visit_decorator(dec)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def __getitem__(self, ndx):\n querysets_count_zip = zip(self.querysets, self.querysets_counts)\n length = 0 # \u52a0\u4e0a\u672c\u6570\u7ec4\u540e\u7684\u5927\u6570\u7ec4\u957f\u5ea6\n pre_length = 0 # \u4e0d\u5305\u542b\u672c\u6570\u7ec4\u7684\u5927\u6570\u7ec4\u957f\u5ea6\n items = [] # \u8fd4\u56de\u7684\u503c\n loop = 0\n\n if isinstance(ndx, slice):\n ndx_start = ndx.start or 0\n ndx_stop = ndx.stop or self.total_count\n ndx_step = ndx.step or 1\n else:\n ndx_start = ndx\n ndx_stop, ndx_step = None, None\n\n for queryset, count in querysets_count_zip:\n length += count\n loop += 1\n # \u53d6\u5f53\u524d\u6570\u7ec4\u7684start\u89d2\u6807, \u5b58\u57283\u4e2d\u60c5\u51b5\n # 1. start\u89d2\u6807\u5728\u5f53\u524d\u6570\u7ec4\n if length > ndx_start >= pre_length:\n start = ndx_start - pre_length\n # print(\"[loop {}] Start is: {}\".format(loop, start))\n if ndx_step is None:\n return queryset[start]\n # 2. \u4e0d\u5305\u542b\u5f53\u524d\u6570\u7ec4\uff0c\u56e0\u4e3a\u8d77\u59cb\u5df2\u7ecf\u8d85\u8fc7\u4e86\u5f53\u524d\u6570\u7ec4\u7684\u957f\u5ea6\n elif ndx_start >= length:\n pre_length += count\n continue\n # 3. \u4e0d\u5728\u5f53\u524d\u6570\u7ec4\uff0c\u4f46\u662f\u5e94\u8be5\u4ece\u5f53\u524d\u6570\u7ec40\u5f00\u59cb\u8ba1\u7b97\n else:\n start = 0\n\n # \u53ef\u80fd\u53d6\u5355\u4e2a\u503c, ndx_stop \u4e3aNone, \u4e0d\u5e94\u8be5\u518d\u627e\n if ndx_stop is None:\n pre_length += count\n continue\n\n # \u53d6\u5f53\u524d\u6570\u7ec4\u7684stop\u89d2\u6807, \u5b58\u57282\u4e2d\u60c5\u51b5\n # \u4e0d\u5b58\u5728\u7b2c3\u4e2d\u60c5\u51b5\u662f\u56e0\u4e3a\u627e\u5230\u4e86\u4f1a\u63d0\u4ea4\u7ed3\u675f\u5faa\u73af\n # 1. \u7ed3\u675f\u89d2\u6807\u5c0f\u4e8elength\u4ee3\u8868 \u7ed3\u675f\u4f4d\u5728\u5f53\u524d\u6570\u7ec4\u4e0a\n if ndx_stop < length:\n stop = ndx_stop - pre_length\n # 2. \u7ed3\u675f\u4f4d\u7f6e\u5305\u542b\u6539\u6570\u7ec4\u5230\u4e86\u6700\u540e\n else:\n stop = count\n # print(\"[loop {}] Slice: {} {} {}\".format(loop, start, stop, ndx_step))\n items.extend(list(queryset[slice(start, stop, ndx_step)]))\n pre_length += count\n\n # \u5982\u679c\u7ed3\u675f\u518d\u5f53\u524d\u6570\u7ec4\uff0c\u5219\u7ed3\u675f\u5faa\u73af\n if ndx_stop < length:\n break\n return items", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def find_candidates(\n self,\n identifier: str,\n requirements: Mapping[str, Iterable[Requirement]],\n incompatibilities: Mapping[str, Iterator[Candidate]],\n constraint: Constraint,\n prefers_installed: bool,\n ) -> Iterable[Candidate]:\n # Collect basic lookup information from the requirements.\n explicit_candidates: Set[Candidate] = set()\n ireqs: List[InstallRequirement] = []\n for req in requirements[identifier]:\n cand, ireq = req.get_candidate_lookup()\n if cand is not None:\n explicit_candidates.add(cand)\n if ireq is not None:\n ireqs.append(ireq)\n\n # If the current identifier contains extras, add requires and explicit\n # candidates from entries from extra-less identifier.\n with contextlib.suppress(InvalidRequirement):\n parsed_requirement = get_requirement(identifier)\n if parsed_requirement.name != identifier:\n explicit_candidates.update(\n self._iter_explicit_candidates_from_base(\n requirements.get(parsed_requirement.name, ()),\n frozenset(parsed_requirement.extras),\n ),\n )\n for req in requirements.get(parsed_requirement.name, []):\n _, ireq = req.get_candidate_lookup()\n if ireq is not None:\n ireqs.append(ireq)\n\n # Add explicit candidates from constraints. We only do this if there are\n # known ireqs, which represent requirements not already explicit. If\n # there are no ireqs, we're constraining already-explicit requirements,\n # which is handled later when we return the explicit candidates.\n if ireqs:\n try:\n explicit_candidates.update(\n self._iter_candidates_from_constraints(\n identifier,\n constraint,\n template=ireqs[0],\n ),\n )\n except UnsupportedWheel:\n # If we're constrained to install a wheel incompatible with the\n # target architecture, no candidates will ever be valid.\n return ()\n\n # Since we cache all the candidates, incompatibility identification\n # can be made quicker by comparing only the id() values.\n incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}\n\n # If none of the requirements want an explicit candidate, we can ask\n # the finder for candidates.\n if not explicit_candidates:\n return self._iter_found_candidates(\n ireqs,\n constraint.specifier,\n constraint.hashes,\n prefers_installed,\n incompat_ids,\n )\n\n return (\n c\n for c in explicit_candidates\n if id(c) not in incompat_ids\n and constraint.is_satisfied_by(c)\n and all(req.is_satisfied_by(c) for req in requirements[identifier])\n )", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None:\n if cl.is_trait:\n return\n\n if cl in seen:\n return\n seen.add(cl)\n for base in cl.base_mro[1:]:\n detect_undefined_bitmap(cl, seen)\n\n if len(cl.base_mro) > 1:\n cl.bitmap_attrs.extend(cl.base_mro[1].bitmap_attrs)\n for n, t in cl.attributes.items():\n if t.error_overlap and not cl.is_always_defined(n):\n cl.bitmap_attrs.append(n)\n\n for base in cl.mro[1:]:\n if base.is_trait:\n for n, t in base.attributes.items():\n if t.error_overlap and not cl.is_always_defined(n) and n not in cl.bitmap_attrs:\n cl.bitmap_attrs.append(n)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def CreateParaViewFilter(self, inInputFilter):\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.CreateParaViewFilter entered\\n\", 100)\n\n savedActiveSource = GetActiveSource()\n\n segmentListJson = ReadAndMpiBroadcastJsonFile(self.JsonListFileName)\n \n self.myCopyOfInputFilter = inInputFilter\n\n UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)\n\n if self.collectionMethod == \"seed cell with structured grid\":\n self.CreateInternalStructuredSeedCellListFromJson(segmentListJson)\n if PhactoriDbg(100):\n myDebugPrint3(\"self.StructuredNearbyCellPointList:\\n\", 100)\n for ii, oneCell in enumerate(self.StructuredNearbyCellPointList):\n outStr = oneCell.ToStr()\n myDebugPrint3(\"cell \" + str(ii) + \":\\n\" + outStr + \\\n \"from geometry point: \" + \\\n str(self.NearbyGeometryPointList[ii]) + \"\\n\")\n else:\n self.CreateInternalSegmentListFromJson(segmentListJson)\n if PhactoriDbg(100):\n myDebugPrint3(\"self.SegmentList:\\n\", 100)\n for oneSeg in self.SegmentList:\n myDebugPrint3(str(oneSeg.ptA) + \", \" + str(oneSeg.ptB) + \"\\n\")\n\n if self.collectionMethod == \"seed cell with structured grid\":\n perSegmentStructuredCellList = self.GatherStructuredCellsFromSeedCells()\n self.PerSegmentMarkedCellInfoList = perSegmentStructuredCellList\n else:\n perSegmentCellList = self.SetMaskValueForCellsNearSegments(\n self.myCopyOfInputFilter, self.SegmentList, \"blargmask1\", \"Ids\",\n self.MaskTestDistanceSquared, self.ProjectionAxis)\n self.PerSegmentMarkedCellInfoList = perSegmentCellList\n #UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)\n #end new work\n\n if self.DoProgrammableFilterToAddMaskVariable:\n if PhactoriDbg(100):\n myDebugPrint3(\"cell and point data arrays before filter:\\n\")\n RecursivelyPrintPointAndCellArrayInformation(inInputFilter)\n self.mProgFilterMaskSetter = ProgrammableFilter(\n Input = self.myCopyOfInputFilter)\n self.mProgFilterMaskSetter.CopyArrays = 1\n self.CreateProgrammableFilterString()\n self.mProgFilterMaskSetter.Script = self.mProgFilterString\n self.mProgFilterMaskSetter.UpdatePipeline()\n if PhactoriDbg(100):\n myDebugPrint3(\"cell and point data arrays after filter:\\n\")\n RecursivelyPrintPointAndCellArrayInformation(self.mProgFilterMaskSetter)\n else:\n self.mProgFilterMaskSetter = self.myCopyOfInputFilter\n\n SetActiveSource(savedActiveSource)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.CreateParaViewFilter returning\\n\", 100)\n return self.mProgFilterMaskSetter", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def urlencode(query, doseq=False):\n \"\"\"\n A version of Python's urllib.parse.urlencode() function that can operate on\n MultiValueDict and non-string values.\n \"\"\"\n if isinstance(query, MultiValueDict):\n query = query.lists()\n elif hasattr(query, \"items\"):\n query = query.items()\n query_params = []\n for key, value in query:\n if value is None:\n raise TypeError(\n \"Cannot encode None for key '%s' in a query string. Did you \"\n \"mean to pass an empty string or omit the value?\" % key\n )\n elif not doseq or isinstance(value, (str, bytes)):\n query_val = value\n else:\n try:\n itr = iter(value)\n except TypeError:\n query_val = value\n else:\n # Consume generators and iterators, when doseq=True, to\n # work around https://bugs.python.org/issue31706.\n query_val = []\n for item in itr:\n if item is None:\n raise TypeError(\n \"Cannot encode None for key '%s' in a query \"\n \"string. Did you mean to pass an empty string or \"\n \"omit the value?\" % key\n )\n elif not isinstance(item, bytes):\n item = str(item)\n query_val.append(item)\n query_params.append((key, query_val))\n return original_urlencode(query_params, doseq)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def divide_line(text: str, width: int, fold: bool = True) -> List[int]:\n divides: List[int] = []\n append = divides.append\n line_position = 0\n _cell_len = cell_len\n for start, _end, word in words(text):\n word_length = _cell_len(word.rstrip())\n if line_position + word_length > width:\n if word_length > width:\n if fold:\n chopped_words = chop_cells(word, max_size=width, position=0)\n for last, line in loop_last(chopped_words):\n if start:\n append(start)\n\n if last:\n line_position = _cell_len(line)\n else:\n start += len(line)\n else:\n if start:\n append(start)\n line_position = _cell_len(word)\n elif line_position and start:\n append(start)\n line_position = _cell_len(word)\n else:\n line_position += _cell_len(word)\n return divides", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "@routes.post(f\"/{API_VTAG}/auth/register\", name=\"auth_register\")\nasync def register(request: web.Request):\n \"\"\"\n Starts user's registration by providing an email, password and\n invitation code (required by configuration).\n\n An email with a link to 'email_confirmation' is sent to complete registration\n \"\"\"\n product: Product = get_current_product(request)\n settings: LoginSettingsForProduct = get_plugin_settings(\n request.app, product_name=product.name\n )\n db: AsyncpgStorage = get_plugin_storage(request.app)\n cfg: LoginOptions = get_plugin_options(request.app)\n\n registration = await parse_request_body_as(RegisterBody, request)\n\n await check_other_registrations(\n request.app, email=registration.email, current_product=product, db=db, cfg=cfg\n )\n\n # Check for weak passwords\n # This should strictly happen before invitation links are checked and consumed\n # So the invitation can be re-used with a stronger password.\n if (\n len(registration.password.get_secret_value())\n < settings.LOGIN_PASSWORD_MIN_LENGTH\n ):\n raise web.HTTPUnauthorized(\n reason=MSG_WEAK_PASSWORD.format(\n LOGIN_PASSWORD_MIN_LENGTH=settings.LOGIN_PASSWORD_MIN_LENGTH\n ),\n content_type=MIMETYPE_APPLICATION_JSON,\n )\n\n # INVITATIONS\n expires_at: datetime | None = None # = does not expire\n invitation = None\n # There are 3 possible states for an invitation:\n # 1. Invitation is not required (i.e. the app has disabled invitations)\n # 2. Invitation is invalid\n # 3. Invitation is valid\n #\n # For those states the `invitation` variable get the following values\n # 1. `None\n # 2. no value, it raises and exception\n # 3. gets `InvitationData`\n # `\n # In addition, for 3. there are two types of invitations:\n # 1. the invitation generated by the `invitation` service (new).\n # 2. the invitation created by hand in the db confirmation table (deprecated). This\n # one does not understand products.\n #\n if settings.LOGIN_REGISTRATION_INVITATION_REQUIRED:\n # Only requests with INVITATION can register user\n # to either a permanent or to a trial account\n invitation_code = registration.invitation\n if invitation_code is None:\n raise web.HTTPBadRequest(\n reason=\"invitation field is required\",\n content_type=MIMETYPE_APPLICATION_JSON,\n )\n\n invitation = await check_and_consume_invitation(\n invitation_code,\n product=product,\n guest_email=registration.email,\n db=db,\n cfg=cfg,\n app=request.app,\n )\n if invitation.trial_account_days:\n expires_at = datetime.utcnow() + timedelta(invitation.trial_account_days)\n\n # get authorized user or create new\n user = await _auth_api.get_user_by_email(request.app, email=registration.email)\n if user:\n await _auth_api.check_authorized_user_credentials_or_raise(\n user,\n password=registration.password.get_secret_value(),\n product=product,\n )\n else:\n user = await _auth_api.create_user(\n request.app,\n email=registration.email,\n password=registration.password.get_secret_value(),\n status_upon_creation=(\n UserStatus.CONFIRMATION_PENDING\n if settings.LOGIN_REGISTRATION_CONFIRMATION_REQUIRED\n else UserStatus.ACTIVE\n ),\n expires_at=expires_at,\n )\n\n # setup user groups\n assert ( # nosec\n product.name == invitation.product\n if invitation and invitation.product\n else True\n )\n\n await auto_add_user_to_groups(app=request.app, user_id=user[\"id\"])\n await auto_add_user_to_product_group(\n app=request.app,\n user_id=user[\"id\"],\n product_name=product.name,\n )\n\n if settings.LOGIN_REGISTRATION_CONFIRMATION_REQUIRED:\n # Confirmation required: send confirmation email\n _confirmation: ConfirmationTokenDict = await db.create_confirmation(\n user[\"id\"], REGISTRATION, data=invitation.json() if invitation else None\n )\n\n try:\n email_confirmation_url = make_confirmation_link(request, _confirmation)\n email_template_path = await get_template_path(\n request, \"registration_email.jinja2\"\n )\n await send_email_from_template(\n request,\n from_=product.support_email,\n to=registration.email,\n template=email_template_path,\n context={\n \"host\": request.host,\n \"link\": email_confirmation_url, # SEE email_confirmation handler (action=REGISTRATION)\n \"name\": user.get(\"first_name\") or user[\"name\"],\n \"support_email\": product.support_email,\n \"product\": product,\n },\n )\n except Exception as err: # pylint: disable=broad-except\n error_code = create_error_code(err)\n user_error_msg = f\"{MSG_CANT_SEND_MAIL} [{error_code}]\"\n\n _logger.exception(\n **create_troubleshotting_log_kwargs(\n user_error_msg,\n error=err,\n error_code=error_code,\n error_context={\n \"request\": request,\n \"registration\": registration,\n \"user_id\": user.get(\"id\"),\n \"user\": user,\n \"confirmation\": _confirmation,\n },\n tip=\"Failed while sending confirmation email\",\n )\n )\n\n await db.delete_confirmation_and_user(user, _confirmation)\n\n raise web.HTTPServiceUnavailable(reason=user_error_msg) from err\n\n return flash_response(\n \"You are registered successfully! To activate your account, please, \"\n f\"click on the verification link in the email we sent you to {registration.email}.\",\n \"INFO\",\n )\n\n # NOTE: Here confirmation is disabled\n assert settings.LOGIN_REGISTRATION_CONFIRMATION_REQUIRED is False # nosec\n assert ( # nosec\n product.name == invitation.product\n if invitation and invitation.product\n else True\n )\n\n await notify_user_confirmation(\n request.app,\n user_id=user[\"id\"],\n product_name=product.name,\n extra_credits_in_usd=invitation.extra_credits_in_usd if invitation else None,\n )\n\n # No confirmation required: authorize login\n assert not settings.LOGIN_REGISTRATION_CONFIRMATION_REQUIRED # nosec\n assert not settings.LOGIN_2FA_REQUIRED # nosec\n\n return await login_granted_response(request=request, user=user)", "smellKey": "S3776", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def _alter_field(\n self,\n model,\n old_field,\n new_field,\n old_type,\n new_type,\n old_db_params,\n new_db_params,\n strict=False,\n ):\n \"\"\"Perform a \"physical\" (non-ManyToMany) field update.\"\"\"\n # Use \"ALTER TABLE ... RENAME COLUMN\" if only the column name\n # changed and there aren't any constraints.\n if (\n old_field.column != new_field.column\n and self.column_sql(model, old_field) == self.column_sql(model, new_field)\n and not (\n old_field.remote_field\n and old_field.db_constraint\n or new_field.remote_field\n and new_field.db_constraint\n )\n ):\n return self.execute(\n self._rename_field_sql(\n model._meta.db_table, old_field, new_field, new_type\n )\n )\n # Alter by remaking table\n self._remake_table(model, alter_fields=[(old_field, new_field)])\n # Rebuild tables with FKs pointing to this field.\n old_collation = old_db_params.get(\"collation\")\n new_collation = new_db_params.get(\"collation\")\n if new_field.unique and (\n old_type != new_type or old_collation != new_collation\n ):\n related_models = set()\n opts = new_field.model._meta\n for remote_field in opts.related_objects:\n # Ignore self-relationship since the table was already rebuilt.\n if remote_field.related_model == model:\n continue\n if not remote_field.many_to_many:\n if remote_field.field_name == new_field.name:\n related_models.add(remote_field.related_model)\n elif new_field.primary_key and remote_field.through._meta.auto_created:\n related_models.add(remote_field.through)\n if new_field.primary_key:\n for many_to_many in opts.many_to_many:\n # Ignore self-relationship since the table was already rebuilt.\n if many_to_many.related_model == model:\n continue\n if many_to_many.remote_field.through._meta.auto_created:\n related_models.add(many_to_many.remote_field.through)\n for related_model in related_models:\n self._remake_table(related_model)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def __init__(self, depth=PRIMARY):\n\t\tself.depth = depth\n\n\t\twanted_languages = []\n\t\tif depth == self.PRIMARY:\n\t\t\twanted_languages = [\"Undetermined\", \"English\", \"German\", \"Arabic\", \"Catalan\", \"Croatian\", \"Czech\", \"Danish\", \"Dutch\", \"Estonian\", \"Finnish\", \"French\", \"Greek\", \"Hungarian\", \"Lithuanian\", \"Latvian\", \"Icelandic\", \"Italian\", \"Norwegian\", \"Polish\", \"Portuguese\", \"Russian\", \"Serbian\", \"Slovakian\", \"Slovenian\", \"Spanish\", \"Swedish\", \"Turkish\", \"Ukrainian\"]\n\t\telif depth == self.SECONDARY:\n\t\t\tfor key, val in LanguageCodes.items():\n\t\t\t\tif len(key) == 2:\n\t\t\t\t\twanted_languages.append(val[0])\n\t\telse:\n\t\t\tfor key, val in LanguageCodes.items():\n\t\t\t\tif len(key) == 3:\n\t\t\t\t\twanted_languages.append(val[0])\n\n\t\tself.idlist_by_name = {}\n\t\tfor key, val in LanguageCodes.items():\n\t\t\tval = val[0]\n\t\t\tif val not in wanted_languages:\n\t\t\t\tcontinue\n\t\t\tif val not in self.idlist_by_name:\n\t\t\t\tself.idlist_by_name[val] = [key]\n\t\t\telse:\n\t\t\t\tself.idlist_by_name[val].append(key)\n\n\t\tself.name_and_shortid_by_longid = {}\n\t\tself.name_by_shortid = {}\n\t\tfor lang, id_list in self.idlist_by_name.items():\n\t\t\tlong_ids = []\n\t\t\tshort_id = None\n\t\t\tfor id in id_list:\n\t\t\t\tif len(id) == 3:\n\t\t\t\t\tlong_ids.append(id)\n\t\t\t\tif len(id) == 2:\n\t\t\t\t\tself.name_by_shortid[id] = lang\n\t\t\t\t\tshort_id = id\n\t\t\tfor long_id in long_ids:\n\t\t\t\tself.name_and_shortid_by_longid[long_id] = (short_id, lang)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def filter_queryset(self, request, queryset, view):\n fields = self._get_date_range_filter_fields(view)\n\n kwargs = {}\n for attr, date_range_keyword in fields.items():\n if len(date_range_keyword) != 2:\n continue\n for i, v in enumerate(date_range_keyword):\n value = request.query_params.get(v)\n if not value:\n continue\n try:\n field = DateTimeField()\n value = field.to_internal_value(value)\n if i == 0:\n lookup = \"__gte\"\n else:\n lookup = \"__lte\"\n kwargs[attr + lookup] = value\n except ValidationError as e:\n print(e)\n continue\n if kwargs:\n queryset = queryset.filter(**kwargs)\n return queryset", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def find(self, requirement, meta_extras=None, prereleases=False):\n \"\"\"\n Find a distribution and all distributions it depends on.\n\n :param requirement: The requirement specifying the distribution to\n find, or a Distribution instance.\n :param meta_extras: A list of meta extras such as :test:, :build: and\n so on.\n :param prereleases: If ``True``, allow pre-release versions to be\n returned - otherwise, don't return prereleases\n unless they're all that's available.\n\n Return a set of :class:`Distribution` instances and a set of\n problems.\n\n The distributions returned should be such that they have the\n :attr:`required` attribute set to ``True`` if they were\n from the ``requirement`` passed to ``find()``, and they have the\n :attr:`build_time_dependency` attribute set to ``True`` unless they\n are post-installation dependencies of the ``requirement``.\n\n The problems should be a tuple consisting of the string\n ``'unsatisfied'`` and the requirement which couldn't be satisfied\n by any distribution known to the locator.\n \"\"\"\n\n self.provided = {}\n self.dists = {}\n self.dists_by_name = {}\n self.reqts = {}\n\n meta_extras = set(meta_extras or [])\n if ':*:' in meta_extras:\n meta_extras.remove(':*:')\n # :meta: and :run: are implicitly included\n meta_extras |= set([':test:', ':build:', ':dev:'])\n\n if isinstance(requirement, Distribution):\n dist = odist = requirement\n logger.debug('passed %s as requirement', odist)\n else:\n dist = odist = self.locator.locate(requirement,\n prereleases=prereleases)\n if dist is None:\n raise DistlibException('Unable to locate %r' % requirement)\n logger.debug('located %s', odist)\n dist.requested = True\n problems = set()\n todo = set([dist])\n install_dists = set([odist])\n while todo:\n dist = todo.pop()\n name = dist.key # case-insensitive\n if name not in self.dists_by_name:\n self.add_distribution(dist)\n else:\n # import pdb; pdb.set_trace()\n other = self.dists_by_name[name]\n if other != dist:\n self.try_to_replace(dist, other, problems)\n\n ireqts = dist.run_requires | dist.meta_requires\n sreqts = dist.build_requires\n ereqts = set()\n if meta_extras and dist in install_dists:\n for key in ('test', 'build', 'dev'):\n e = ':%s:' % key\n if e in meta_extras:\n ereqts |= getattr(dist, '%s_requires' % key)\n all_reqts = ireqts | sreqts | ereqts\n for r in all_reqts:\n providers = self.find_providers(r)\n if not providers:\n logger.debug('No providers found for %r', r)\n provider = self.locator.locate(r, prereleases=prereleases)\n # If no provider is found and we didn't consider\n # prereleases, consider them now.\n if provider is None and not prereleases:\n provider = self.locator.locate(r, prereleases=True)\n if provider is None:\n logger.debug('Cannot satisfy %r', r)\n problems.add(('unsatisfied', r))\n else:\n n, v = provider.key, provider.version\n if (n, v) not in self.dists:\n todo.add(provider)\n providers.add(provider)\n if r in ireqts and dist in install_dists:\n install_dists.add(provider)\n logger.debug('Adding %s to install_dists',\n provider.name_and_version)\n for p in providers:\n name = p.key\n if name not in self.dists_by_name:\n self.reqts.setdefault(p, set()).add(r)\n else:\n other = self.dists_by_name[name]\n if other != p:\n # see if other can be replaced by p\n self.try_to_replace(p, other, problems)\n\n dists = set(self.dists.values())\n for dist in dists:\n dist.build_time_dependency = dist not in install_dists\n if dist.build_time_dependency:\n logger.debug('%s is a build-time dependency only.',\n dist.name_and_version)\n logger.debug('find done for %s', odist)\n return dists, problems", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def GetProfileStats(profile_dir: str,\n skip_chromium_components=False) -> ProfileStats:\n result = ProfileStats()\n\n with scoped_cwd(profile_dir):\n result.total_size = _GetDirectorySize(profile_dir)\n\n for f in os.listdir(profile_dir):\n info = _GetComponentInfo(f)\n if info is not None:\n name, version = info\n group = _GetComponentGroup(name, f, skip_chromium_components)\n if group is None:\n continue\n size = _GetDirectorySize(f)\n item = StatItem(path=f, size=size, name=name, version=version)\n result.groups.setdefault(group, GroupStat()).items.append(item)\n else:\n for file in Path(f).glob('**/*'):\n is_cache = any(str(file).startswith(c) for c in _CACHE_DIRECTORIES)\n if is_cache or not file.is_file():\n continue\n size = file.stat().st_size\n if size > 1000 * 1000:\n item = StatItem(path=str(file), size=size)\n result.groups.setdefault('large_files',\n GroupStat()).items.append(item)\n\n return result", "smellKey": "S3776", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def read(self):\n\t\tinputfile = open(self.filename)\n\t\tlines = inputfile.readlines()\n\t\tinputfile.close()\n\n\t\tversionstring = lines[0].split('/')\n\t\tversion = int(versionstring[1])\n\t\tif 3 > version or 4 < version:\n\t\t\tprint(\"unsupported lamedb version\")\n\t\t\treturn\n\n\t\ttranspondersreading = False\n\t\tsats = {}\n\t\ttransponders = {}\n\t\tfor line in lines:\n\t\t\tif line.strip() == \"transponders\":\n\t\t\t\ttranspondersreading = True\n\t\t\t\tcontinue\n\t\t\tif line.strip() == \"services\":\n\t\t\t\ttranspondersreading = False\n\t\t\t\tcontinue\n\t\t\tif transpondersreading:\n\t\t\t\tif ord(line[0]) == 9:\n\t\t\t\t\ttransponder = line.strip().split(' ')[1].split(':')\n\t\t\t\t\tsat = transponder[4]\n\t\t\t\t\tif sat not in sats:\n\t\t\t\t\t\tsats[sat] = []\n\t\t\t\t\tsats[sat].append((transponder, tsid, onid))\n\t\t\t\t\ttsid = None\n\t\t\t\t\tonid = None\n\t\t\t\telif line.strip() != \"/\" and line.strip() != \"end\":\n\t\t\t\t\tdata = line.strip().split(\":\")\n\t\t\t\t\ttsid = str(int(data[1], 16))\n\t\t\t\t\tonid = str(int(data[2], 16))\n\t\tsatlist = sats.keys()\n\t\tsatlist.sort()\n\n\t\tfor sat in satlist:\n\t\t\tprint(sat)\n\t\t\tself.addSat(sat, sat)\n\t\t\ttransponders = sats[sat]\n\t\t\ttransponders.sort(key=lambda a: a[0])\n\t\t\tfor transpondertuple in transponders:\n\t\t\t\ttransponder = transpondertuple[0]\n\t\t\t\ttsid = transpondertuple[1]\n\t\t\t\tonid = transpondertuple[2]\n\t\t\t\tprint(transponder, tsid, onid)\n\t\t\t\ttmp_transponder = {\"frequency\": transponder[0], \"symbol_rate\": transponder[1], \"polarization\": transponder[2], \"fec\": transponder[3]}\n\t\t\t\tif version == 3:\n\t\t\t\t\tif len(transponder) > 6:\n\t\t\t\t\t\ttmp_transponder[\"system\"] = transponder[6]\n\t\t\t\t\t\ttmp_transponder[\"modulation\"] = transponder[7]\n\t\t\t\telif version == 4:\n\t\t\t\t\tif len(transponder) > 7:\n\t\t\t\t\t\ttmp_transponder[\"system\"] = transponder[7]\n\t\t\t\t\t\ttmp_transponder[\"modulation\"] = transponder[8]\n\t\t\t\tif tsid != \"1\" or onid != \"1\":\n\t\t\t\t\ttmp_transponder[\"tsid\"] = transponder[0]\n\t\t\t\t\ttmp_transponder[\"onid\"] = transponder[0]\n\t\t\t\tself.addTransponder(sat, tmp_transponder)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def increment(\n self,\n method=None,\n url=None,\n response=None,\n error=None,\n _pool=None,\n _stacktrace=None,\n ):\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.HTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise six.reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise six.reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or not self._is_method_retryable(method):\n raise six.reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n redirect_location = response.get_redirect_location()\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def get_pin_and_cookie_name(\n app: WSGIApplication,\n) -> tuple[str, str] | tuple[None, None]:\n \"\"\"Given an application object this returns a semi-stable 9 digit pin\n code and a random key. The hope is that this is stable between\n restarts to not make debugging particularly frustrating. If the pin\n was forcefully disabled this returns `None`.\n\n Second item in the resulting tuple is the cookie name for remembering.\n \"\"\"\n pin = os.environ.get(\"WERKZEUG_DEBUG_PIN\")\n rv = None\n num = None\n\n # Pin was explicitly disabled\n if pin == \"off\":\n return None, None\n\n # Pin was provided explicitly\n if pin is not None and pin.replace(\"-\", \"\").isdecimal():\n # If there are separators in the pin, return it directly\n if \"-\" in pin:\n rv = pin\n else:\n num = pin\n\n modname = getattr(app, \"__module__\", t.cast(object, app).__class__.__module__)\n username: str | None\n\n try:\n # getuser imports the pwd module, which does not exist in Google\n # App Engine. It may also raise a KeyError if the UID does not\n # have a username, such as in Docker.\n username = getpass.getuser()\n except (ImportError, KeyError):\n username = None\n\n mod = sys.modules.get(modname)\n\n # This information only exists to make the cookie unique on the\n # computer, not as a security feature.\n probably_public_bits = [\n username,\n modname,\n getattr(app, \"__name__\", type(app).__name__),\n getattr(mod, \"__file__\", None),\n ]\n\n # This information is here to make it harder for an attacker to\n # guess the cookie name. They are unlikely to be contained anywhere\n # within the unauthenticated debug page.\n private_bits = [str(uuid.getnode()), get_machine_id()]\n\n h = hashlib.sha1()\n for bit in chain(probably_public_bits, private_bits):\n if not bit:\n continue\n if isinstance(bit, str):\n bit = bit.encode()\n h.update(bit)\n h.update(b\"cookiesalt\")\n\n cookie_name = f\"__wzd{h.hexdigest()[:20]}\"\n\n # If we need to generate a pin we salt it a bit more so that we don't\n # end up with the same value and generate out 9 digits\n if num is None:\n h.update(b\"pinsalt\")\n num = f\"{int(h.hexdigest(), 16):09d}\"[:9]\n\n # Format the pincode in groups of digits for easier remembering if\n # we don't have a result yet.\n if rv is None:\n for group_size in 5, 4, 3:\n if len(num) % group_size == 0:\n rv = \"-\".join(\n num[x : x + group_size].rjust(group_size, \"0\")\n for x in range(0, len(num), group_size)\n )\n break\n else:\n rv = num\n\n return rv, cookie_name", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def __init__(self):\n\t\tself.immutableList = []\n\t\tself.boxInfo = {}\n\t\tself.enigmaInfoList = []\n\t\tself.enigmaConfList = []\n\t\tlines = fileReadLines(join(resolveFilename(SCOPE_LIBDIR), \"enigma.info\"), source=MODULE_NAME)\n\t\tif lines:\n\t\t\tmodified = self.checkChecksum(lines)\n\t\t\tif modified:\n\t\t\t\tprint(\"[SystemInfo] WARNING: Enigma information file checksum is incorrect! File appears to have been modified.\")\n\t\t\t\tself.boxInfo[\"checksumerror\"] = True\n\t\t\telse:\n\t\t\t\tprint(\"[SystemInfo] Enigma information file checksum is correct.\")\n\t\t\t\tself.boxInfo[\"checksumerror\"] = False\n\t\t\tfor line in lines:\n\t\t\t\tif line.startswith(\"#\") or line.strip() == \"\":\n\t\t\t\t\tcontinue\n\t\t\t\tif \"=\" in line:\n\t\t\t\t\titem, value = (x.strip() for x in line.split(\"=\", 1))\n\t\t\t\t\tif item:\n\t\t\t\t\t\tself.immutableList.append(item)\n\t\t\t\t\t\tself.enigmaInfoList.append(item)\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself.boxInfo[item] = literal_eval(value)\n\t\t\t\t\t\texcept: # Remove this code when the build system is updated.\n\t\t\t\t\t\t\tself.boxInfo[item] = value\n\t\t\t\t\t\t# except Exception as err: # Activate this replacement code when the build system is updated.\n\t\t\t\t\t\t# \tprint(f\"[SystemInfo] Error: Information variable '{item}' with a value of '{value}' can not be loaded into BoxInfo! ({err})\")\n\t\t\tself.enigmaInfoList = sorted(self.enigmaInfoList)\n\t\t\tprint(\"[SystemInfo] Enigma information file data loaded into BoxInfo.\")\n\t\telse:\n\t\t\tprint(\"[SystemInfo] ERROR: Enigma information file is not available! The system is unlikely to boot or operate correctly.\")\n\t\tlines = fileReadLines(join(resolveFilename(SCOPE_LIBDIR), \"enigma.conf\"), source=MODULE_NAME)\n\t\tif lines:\n\t\t\tprint(\"[SystemInfo] Enigma config override file available and data loaded into BoxInfo.\")\n\t\t\tself.boxInfo[\"overrideactive\"] = True\n\t\t\tfor line in lines:\n\t\t\t\tif line.startswith(\"#\") or line.strip() == \"\":\n\t\t\t\t\tcontinue\n\t\t\t\tif \"=\" in line:\n\t\t\t\t\titem, value = (x.strip() for x in line.split(\"=\", 1))\n\t\t\t\t\tif item:\n\t\t\t\t\t\tself.enigmaConfList.append(item)\n\t\t\t\t\t\tif item in self.boxInfo:\n\t\t\t\t\t\t\tprint(f\"[SystemInfo] Note: Enigma information value '{item}' with value '{self.boxInfo[item]}' being overridden to '{value}'.\")\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself.boxInfo[item] = literal_eval(value)\n\t\t\t\t\t\texcept Exception: # Remove this code when the build system is updated.\n\t\t\t\t\t\t\tself.boxInfo[item] = value\n\t\t\t\t\t\t# except Exception as err: # Activate this replacement code when the build system is updated.\n\t\t\t\t\t\t# \tprint(f\"[SystemInfo] Error: Information override variable '{item}' with a value of '{value}' can not be loaded into BoxInfo! ({err})\")\n\t\t\tself.enigmaConfList = sorted(self.enigmaConfList)\n\t\telse:\n\t\t\tself.boxInfo[\"overrideactive\"] = False", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "async def _process_loop(self):\n \"\"\"Continually kick off encoding and delivery on outbound messages.\"\"\"\n # Note: this method should not call async methods apart from\n # waiting for the updated event, to avoid yielding to other queue methods\n\n while True:\n self.outbound_event.clear()\n loop_time = get_timer()\n upd_buffer = []\n retry_count = 0\n\n for queued in self.outbound_buffer:\n if queued.state == QueuedOutboundMessage.STATE_DONE:\n if queued.error:\n LOGGER.exception(\n \"Outbound message could not be delivered to %s\",\n queued.endpoint,\n exc_info=queued.error,\n )\n if self.handle_not_delivered and queued.message:\n self.handle_not_delivered(queued.profile, queued.message)\n continue # remove from buffer\n\n deliver = False\n\n if queued.state == QueuedOutboundMessage.STATE_PENDING:\n deliver = True\n elif queued.state == QueuedOutboundMessage.STATE_RETRY:\n if queued.retry_at < loop_time:\n queued.retry_at = None\n deliver = True\n else:\n retry_count += 1\n\n if deliver:\n queued.state = QueuedOutboundMessage.STATE_DELIVER\n p_time = trace_event(\n self.root_profile.settings,\n queued.message if queued.message else queued.payload,\n outcome=\"OutboundTransportManager.DELIVER.START.\"\n + queued.endpoint,\n )\n self.deliver_queued_message(queued)\n trace_event(\n self.root_profile.settings,\n queued.message if queued.message else queued.payload,\n outcome=\"OutboundTransportManager.DELIVER.END.\" + queued.endpoint,\n perf_counter=p_time,\n )\n\n upd_buffer.append(queued)\n\n new_pending = 0\n new_messages = self.outbound_new\n self.outbound_new = []\n\n for queued in new_messages:\n if queued.state == QueuedOutboundMessage.STATE_NEW:\n if queued.message and queued.message.enc_payload:\n queued.payload = queued.message.enc_payload\n queued.state = QueuedOutboundMessage.STATE_PENDING\n new_pending += 1\n else:\n queued.state = QueuedOutboundMessage.STATE_ENCODE\n p_time = trace_event(\n self.root_profile.settings,\n queued.message if queued.message else queued.payload,\n outcome=\"OutboundTransportManager.ENCODE.START\",\n )\n self.encode_queued_message(queued)\n trace_event(\n self.root_profile.settings,\n queued.message if queued.message else queued.payload,\n outcome=\"OutboundTransportManager.ENCODE.END\",\n perf_counter=p_time,\n )\n else:\n new_pending += 1\n\n upd_buffer.append(queued)\n\n self.outbound_buffer = upd_buffer\n if self.outbound_buffer:\n if (not new_pending) and (not retry_count):\n await self.outbound_event.wait()\n elif retry_count:\n # only retries - yield here so we don't hog resources\n await asyncio.sleep(0.05)\n else:\n break", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def buildGraphEntry(self, service, service_name, events, picon, channel):\n\t\tif self.listSizeWidth != self.l.getItemSize().width(): # recalc size if scrollbar is shown\n\t\t\tself.recalcEntrySize()\n\t\tr1 = self.service_rect\n\t\tr2 = self.event_rect\n\t\tleft = r2.x\n\t\ttop = r2.y\n\t\twidth = r2.w\n\t\theight = r2.h\n\t\tselected = self.cur_service[0] == service\n\t\tres = [None]\n\n\t\tborderTopPix = None\n\t\tborderLeftPix = None\n\t\tborderBottomPix = None\n\t\tborderRightPix = None\n\n\t\t# Picon and Service name\n\t\tserviceForeColor = self.foreColorService\n\t\tserviceBackColor = self.backColorService\n\t\tbgpng = self.othServPix\n\n\t\tif CompareWithAlternatives(service, self.currentlyPlaying and self.currentlyPlaying.toString()):\n\t\t\tserviceForeColor = self.foreColorServiceNow\n\t\t\tserviceBackColor = self.backColorServiceNow\n\t\t\tbgpng = self.nowServPix\n\n\t\tif bgpng is not None and self.graphic:\n\t\t\tserviceBackColor = None\n\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\tpos=(r1.x + self.serviceBorderWidth, r1.y + self.serviceBorderWidth),\n\t\t\t\t\tsize=(r1.w - 2 * self.serviceBorderWidth, r1.h - 2 * self.serviceBorderWidth),\n\t\t\t\t\tpng=bgpng,\n\t\t\t\t\tflags=BT_SCALE))\n\t\telse:\n\t\t\tres.append(MultiContentEntryText(\n\t\t\t\t\tpos=(r1.x, r1.y),\n\t\t\t\t\tsize=(r1.w, r1.h),\n\t\t\t\t\tfont=0, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER,\n\t\t\t\t\ttext=\"\",\n\t\t\t\t\tcolor=serviceForeColor, color_sel=serviceForeColor,\n\t\t\t\t\tbackcolor=serviceBackColor, backcolor_sel=serviceBackColor,\n\t\t\t\t\tborder_width=self.serviceBorderWidth, border_color=self.borderColorService))\n\n\t\tdisplayPicon = None\n\t\tif self.showPicon:\n\t\t\tif picon is None: # go find picon and cache its location\n\t\t\t\tpicon = getPiconName(service)\n\t\t\t\tcurIdx = self.l.getCurrentSelectionIndex()\n\t\t\t\tself.list[curIdx] = (service, service_name, events, picon, channel)\n\t\t\tpiconWidth = self.picon_size.width()\n\t\t\tpiconHeight = self.picon_size.height()\n\t\t\tif picon != \"\":\n\t\t\t\tdisplayPicon = loadPNG(picon)\n\t\t\tif displayPicon is not None:\n\t\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\tpos=(r1.x + self.serviceBorderWidth, r1.y + self.serviceBorderWidth),\n\t\t\t\t\tsize=(piconWidth, piconHeight),\n\t\t\t\t\tpng=displayPicon,\n\t\t\t\t\tbackcolor=None, backcolor_sel=None, flags=BT_SCALE | BT_KEEP_ASPECT_RATIO))\n\t\t\telif not self.showServiceTitle:\n\t\t\t\t# no picon so show servicename anyway in picon space\n\t\t\t\tnamefont = 0\n\t\t\t\tnamefontflag = int(config.epgselection.graph_servicename_alignment.value)\n\t\t\t\tnamewidth = piconWidth\n\t\t\telse:\n\t\t\t\tpiconWidth = 0\n\t\telse:\n\t\t\tpiconWidth = 0\n\n\t\tchannelWidth = 0\n\t\tif self.showServiceNumber:\n\t\t\tif not isinstance(channel, int):\n\t\t\t\tchannel = self.getChannelNumber(channel)\n\n\t\t\tif channel:\n\t\t\t\tnamefont = 0\n\t\t\t\tnamefontflag = RT_HALIGN_CENTER | RT_VALIGN_CENTER\n\t\t\t\tfont = gFont(self.serviceFontNameGraph, self.serviceFontSizeGraph + config.epgselection.graph_servfs.value)\n\t\t\t\tchannelWidth = getTextBoundarySize(self.instance, font, self.instance.size(), (channel < 10000) and \"0000\" or str(channel)).width()\n\t\t\t\tres.append(MultiContentEntryText(\n\t\t\t\t\tpos=(r1.x + self.serviceNamePadding + piconWidth + self.serviceNamePadding, r1.y + self.serviceBorderWidth),\n\t\t\t\t\tsize=(channelWidth, r1.h - 2 * self.serviceBorderWidth),\n\t\t\t\t\tfont=namefont, flags=namefontflag,\n\t\t\t\t\ttext=str(channel),\n\t\t\t\t\tcolor=serviceForeColor, color_sel=serviceForeColor,\n\t\t\t\t\tbackcolor=serviceBackColor, backcolor_sel=serviceBackColor))\n\n\t\tif self.showServiceTitle: # we have more space so reset parms\n\t\t\tnamefont = 0\n\t\t\tnamefontflag = int(config.epgselection.graph_servicename_alignment.value)\n\t\t\tnamewidth = r1.w - channelWidth - piconWidth\n\n\t\tif self.showServiceTitle or displayPicon is None:\n\t\t\tres.append(MultiContentEntryText(\n\t\t\t\tpos=(r1.x + self.serviceNamePadding + piconWidth + self.serviceNamePadding + channelWidth + self.serviceNumberPadding,\n\t\t\t\t\tr1.y + self.serviceBorderWidth),\n\t\t\t\tsize=(namewidth - 3 * (self.serviceBorderWidth + self.serviceNamePadding),\n\t\t\t\t\tr1.h - 2 * self.serviceBorderWidth),\n\t\t\t\tfont=namefont, flags=namefontflag,\n\t\t\t\ttext=service_name,\n\t\t\t\tcolor=serviceForeColor, color_sel=serviceForeColor,\n\t\t\t\tbackcolor=serviceBackColor, backcolor_sel=serviceBackColor))\n\n\t\tif self.isIceTV(service) and config.epg.eit.value and self.icetvicon:\n\t\t\ticeicon_size = self.icetvicon.size()\n\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\tpos=(r1.x + r1.w - self.serviceBorderWidth - iceicon_size.width(), r1.y + r1.h - self.serviceBorderWidth - iceicon_size.height()),\n\t\t\t\tsize=(iceicon_size.width(), iceicon_size.height()),\n\t\t\t\tpng=self.icetvicon,\n\t\t\t\tbackcolor=None, backcolor_sel=None))\n\n\t\t# Service Borders\n\t\tif self.borderTopPix is not None and self.graphic:\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r1.x, r1.y),\n\t\t\t\t\tsize=(r1.w, self.serviceBorderWidth),\n\t\t\t\t\tpng=self.borderTopPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x, r2.y),\n\t\t\t\t\tsize=(r2.w, self.eventBorderWidth),\n\t\t\t\t\tpng=self.borderTopPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\tif self.borderBottomPix is not None and self.graphic:\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r1.x, r1.h - self.serviceBorderWidth),\n\t\t\t\t\tsize=(r1.w, self.serviceBorderWidth),\n\t\t\t\t\tpng=self.borderBottomPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x, r2.h - self.eventBorderWidth),\n\t\t\t\t\tsize=(r2.w, self.eventBorderWidth),\n\t\t\t\t\tpng=self.borderBottomPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\tif self.borderLeftPix is not None and self.graphic:\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r1.x, r1.y),\n\t\t\t\t\tsize=(self.serviceBorderWidth, r1.h),\n\t\t\t\t\tpng=self.borderLeftPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x, r2.y),\n\t\t\t\t\tsize=(self.eventBorderWidth, r2.h),\n\t\t\t\t\tpng=self.borderLeftPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\tif self.borderRightPix is not None and self.graphic:\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r1.w - self.serviceBorderWidth, r1.x),\n\t\t\t\t\tsize=(self.serviceBorderWidth, r1.h),\n\t\t\t\t\tpng=self.borderRightPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x + r2.w - self.eventBorderWidth, r2.y),\n\t\t\t\t\tsize=(self.eventBorderWidth, r2.h),\n\t\t\t\t\tpng=self.borderRightPix,\n\t\t\t\t\tflags=BT_SCALE))\n\n\t\tif self.graphic:\n\t\t\tif not selected and self.othEvPix:\n\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x + self.eventBorderWidth, r2.y + self.eventBorderWidth),\n\t\t\t\t\tsize=(r2.w - 2 * self.eventBorderWidth, r2.h - 2 * self.eventBorderWidth),\n\t\t\t\t\tpng=self.othEvPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\t\telif selected and self.selEvPix:\n\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\tpos=(r2.x + self.eventBorderWidth, r2.y + self.eventBorderWidth),\n\t\t\t\t\tsize=(r2.w - 2 * self.eventBorderWidth, r2.h - 2 * self.eventBorderWidth),\n\t\t\t\t\tpng=self.selEvPix,\n\t\t\t\t\tflags=BT_SCALE))\n\t\telse:\n\t\t\tres.append(MultiContentEntryText(\n\t\t\t\tpos=(left, top), size=(width, height),\n\t\t\t\tfont=1, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER,\n\t\t\t\ttext=\"\", color=None, color_sel=None,\n\t\t\t\tbackcolor=self.backColor, backcolor_sel=self.backColorSelected,\n\t\t\t\tborder_width=self.eventBorderWidth, border_color=self.borderColor))\n\n\t\t# Events for service\n\t\tif events:\n\t\t\tstart = self.time_base + self.offs * self.time_epoch * 60\n\t\t\tend = start + self.time_epoch * 60\n\n\t\t\tnow = time()\n\t\t\tfor ev in events: #(event_id, event_title, begin_time, duration)\n\t\t\t\tstime = ev[2]\n\t\t\t\tduration = ev[3]\n\t\t\t\txpos, ewidth = self.calcEntryPosAndWidthHelper(stime, duration, start, end, width)\n\t\t\t\tclock_types = self.getPixmapForEntry(service, ev[0], stime, duration)\n\t\t\t\t#if self.eventNameAlign.lower() == 'left':\n\t\t\t\t#\tif self.eventNameWrap.lower() == 'yes':\n\t\t\t\t#\t\talignnment = RT_HALIGN_LEFT | RT_VALIGN_CENTER | RT_WRAP\n\t\t\t\t#\telse:\n\t\t\t\t#\t\talignnment = RT_HALIGN_LEFT | RT_VALIGN_CENTER\n\t\t\t\t#else:\n\t\t\t\t#\tif self.eventNameWrap.lower() == 'yes':\n\t\t\t\t#\t\talignnment = RT_HALIGN_CENTER | RT_VALIGN_CENTER | RT_WRAP\n\t\t\t\t#\telse:\n\t\t\t\t#\t\talignnment = RT_HALIGN_CENTER | RT_VALIGN_CENTER\n\n\t\t\t\tif stime <= now < (stime + duration):\n\t\t\t\t\tif clock_types is not None and (clock_types == 2 or clock_types == 12):\n\t\t\t\t\t\tforeColor = self.foreColorRecord\n\t\t\t\t\t\tbackColor = self.backColorRecord\n\t\t\t\t\t\tforeColorSel = self.foreColorRecordSelected\n\t\t\t\t\t\tbackColorSel = self.backColorRecordSelected\n\t\t\t\t\telse:\n\t\t\t\t\t\tforeColor = self.foreColorNow\n\t\t\t\t\t\tbackColor = self.backColorNow\n\t\t\t\t\t\tforeColorSel = self.foreColorNowSelected\n\t\t\t\t\t\tbackColorSel = self.backColorNowSelected\n\t\t\t\telse:\n\t\t\t\t\tforeColor = self.foreColor\n\t\t\t\t\tbackColor = self.backColor\n\t\t\t\t\tforeColorSel = self.foreColorSelected\n\t\t\t\t\tbackColorSel = self.backColorSelected\n\t\t\t\t\tif clock_types is not None and (clock_types == 2 or clock_types == 12):\n\t\t\t\t\t\tforeColor = self.foreColorRecord\n\t\t\t\t\t\tbackColor = self.backColorRecord\n\t\t\t\t\t\tforeColorSel = self.foreColorRecordSelected\n\t\t\t\t\t\tbackColorSel = self.backColorRecordSelected\n\t\t\t\t\telif clock_types is not None and clock_types == 7:\n\t\t\t\t\t\tforeColor = self.foreColorZap\n\t\t\t\t\t\tbackColor = self.backColorZap\n\t\t\t\t\t\tforeColorSel = self.foreColorZapSelected\n\t\t\t\t\t\tbackColorSel = self.backColorZapSelected\n\n\t\t\t\tif selected and self.select_rect.x == xpos + left:\n\t\t\t\t\tif clock_types is not None:\n\t\t\t\t\t\tclocks = self.selclocks[clock_types]\n\t\t\t\t\tborderTopPix = self.borderSelectedTopPix\n\t\t\t\t\tborderLeftPix = self.borderSelectedLeftPix\n\t\t\t\t\tborderBottomPix = self.borderSelectedBottomPix\n\t\t\t\t\tborderRightPix = self.borderSelectedRightPix\n\t\t\t\t\tinfoPix = self.selInfoPix\n\t\t\t\t\tif clock_types is not None and clock_types == 2:\n\t\t\t\t\t\tbgpng = self.recSelEvPix\n\t\t\t\t\telif stime <= now < (stime + duration):\n\t\t\t\t\t\tbgpng = self.nowSelEvPix\n\t\t\t\t\telse:\n\t\t\t\t\t\tbgpng = self.selEvPix\n\t\t\t\telse:\n\t\t\t\t\tif clock_types is not None:\n\t\t\t\t\t\tclocks = self.clocks[clock_types]\n\t\t\t\t\tborderTopPix = self.borderTopPix\n\t\t\t\t\tborderLeftPix = self.borderLeftPix\n\t\t\t\t\tborderBottomPix = self.borderBottomPix\n\t\t\t\t\tborderRightPix = self.borderRightPix\n\t\t\t\t\tinfoPix = self.InfoPix\n\t\t\t\t\tif stime <= now < (stime + duration):\n\t\t\t\t\t\tif clock_types is not None and (clock_types == 2 or clock_types == 12):\n\t\t\t\t\t\t\tbgpng = self.recordingEvPix\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbgpng = self.nowEvPix\n\t\t\t\t\telse:\n\t\t\t\t\t\tbgpng = self.othEvPix\n\t\t\t\t\t\tif clock_types is not None and (clock_types == 2 or clock_types == 12):\n\t\t\t\t\t\t\tbgpng = self.recEvPix\n\t\t\t\t\t\telif clock_types is not None and clock_types == 7:\n\t\t\t\t\t\t\tbgpng = self.zapEvPix\n\n\t\t\t\t# event box background\n\t\t\t\tif bgpng is not None and self.graphic:\n\t\t\t\t\tbackColor = None\n\t\t\t\t\tbackColorSel = None\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\t\tpos=(left + xpos + self.eventBorderWidth, top + self.eventBorderWidth),\n\t\t\t\t\t\tsize=(ewidth - 2 * self.eventBorderWidth, height - 2 * self.eventBorderWidth),\n\t\t\t\t\t\tpng=bgpng,\n\t\t\t\t\t\tflags=BT_SCALE))\n\t\t\t\telse:\n\t\t\t\t\tres.append(MultiContentEntryText(\n\t\t\t\t\t\tpos=(left + xpos, top), size=(ewidth, height),\n\t\t\t\t\t\tfont=1, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER,\n\t\t\t\t\t\ttext=\"\", color=None, color_sel=None,\n\t\t\t\t\t\tbackcolor=backColor, backcolor_sel=backColorSel,\n\t\t\t\t\t\tborder_width=self.eventBorderWidth, border_color=self.borderColor))\n\n\t\t\t\t# event text\n\t\t\t\tevX = left + xpos + self.eventBorderWidth + self.eventNamePadding\n\t\t\t\tevY = top + self.eventBorderWidth\n\t\t\t\tevW = ewidth - 2 * (self.eventBorderWidth + self.eventNamePadding)\n\t\t\t\tevH = height - 2 * self.eventBorderWidth\n\t\t\t\tif self.type == EPG_TYPE_GRAPH:\n\t\t\t\t\tinfowidth = config.epgselection.graph_infowidth.value\n\t\t\t\telif self.type == EPG_TYPE_INFOBARGRAPH:\n\t\t\t\t\tinfowidth = config.epgselection.infobar_infowidth.value\n\t\t\t\tif evW < infowidth and infoPix is not None:\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\t\tpos=(evX, evY), size=(evW, evH),\n\t\t\t\t\t\tpng=infoPix))\n\t\t\t\telse:\n\t\t\t\t\tres.append(MultiContentEntryText(\n\t\t\t\t\t\tpos=(evX, evY), size=(evW, evH),\n\t\t\t\t\t\tfont=1, flags=int(config.epgselection.graph_event_alignment.value),\n\t\t\t\t\t\ttext=ev[1],\n\t\t\t\t\t\tcolor=foreColor, color_sel=foreColorSel,\n\t\t\t\t\t\tbackcolor=backColor, backcolor_sel=backColorSel))\n\n\t\t\t\t# event box borders\n\t\t\t\tif borderTopPix is not None and self.graphic:\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\t\t\tpos=(left + xpos, top),\n\t\t\t\t\t\t\tsize=(ewidth, self.eventBorderWidth),\n\t\t\t\t\t\t\tpng=borderTopPix,\n\t\t\t\t\t\t\tflags=BT_SCALE))\n\t\t\t\tif borderBottomPix is not None and self.graphic:\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\t\t\tpos=(left + xpos, height - self.eventBorderWidth),\n\t\t\t\t\t\t\tsize=(ewidth, self.eventBorderWidth),\n\t\t\t\t\t\t\tpng=borderBottomPix,\n\t\t\t\t\t\t\tflags=BT_SCALE))\n\t\t\t\tif borderLeftPix is not None and self.graphic:\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\t\t\tpos=(left + xpos, top),\n\t\t\t\t\t\t\tsize=(self.eventBorderWidth, height),\n\t\t\t\t\t\t\tpng=borderLeftPix,\n\t\t\t\t\t\t\tflags=BT_SCALE))\n\t\t\t\tif borderRightPix is not None and self.graphic:\n\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaTest(\n\t\t\t\t\t\t\tpos=(left + xpos + ewidth - self.eventBorderWidth, top),\n\t\t\t\t\t\t\tsize=(self.eventBorderWidth, height),\n\t\t\t\t\t\t\tpng=borderRightPix,\n\t\t\t\t\t\t\tflags=BT_SCALE))\n\n\t\t\t\t# recording icons\n\t\t\t\tif clock_types is not None and ewidth > 23:\n\t\t\t\t\tif config.epgselection.graph_rec_icon_height.value != \"hide\":\n\t\t\t\t\t\tif config.epgselection.graph_rec_icon_height.value == \"middle\":\n\t\t\t\t\t\t\tRecIconHeight = top + (height / 2) - self.posy\n\t\t\t\t\t\telif config.epgselection.graph_rec_icon_height.value == \"top\":\n\t\t\t\t\t\t\tRecIconHeight = top + self.gap\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tRecIconHeight = top + height - self.picy - self.gap\n\t\t\t\t\t\tif clock_types in (1, 6, 11):\n\t\t\t\t\t\t\tpos = (left + xpos + ewidth - self.picx, RecIconHeight)\n\t\t\t\t\t\telif clock_types in (5, 10, 15):\n\t\t\t\t\t\t\tpos = (left + xpos - self.picx - self.posx, RecIconHeight)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpos = (left + xpos + ewidth - self.picx - self.posx, RecIconHeight)\n\t\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\t\t\tpos=pos, size=(self.picx, self.picy),\n\t\t\t\t\t\t\tpng=clocks))\n\t\t\t\t\t\tif (self.wasEntryAutoTimer or self.wasEntryIceTV) and clock_types in (2, 7, 12):\n\t\t\t\t\t\t\tif self.wasEntryAutoTimer:\n\t\t\t\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\t\t\t\t\tpos=(pos[0] - self.picx - self.gap, pos[1]), size=(self.picx, self.picy),\n\t\t\t\t\t\t\t\t\tpng=self.autotimericon))\n\t\t\t\t\t\t\tif self.wasEntryIceTV:\n\t\t\t\t\t\t\t\tres.append(MultiContentEntryPixmapAlphaBlend(\n\t\t\t\t\t\t\t\t\tpos=(pos[0] - self.picx - self.gap, pos[1]), size=(self.picx, self.picy),\n\t\t\t\t\t\t\t\t\tpng=self.icetvicon))\n\t\treturn res", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "async def main(args):\n extra_args = None\n if DEMO_EXTRA_AGENT_ARGS:\n extra_args = json.loads(DEMO_EXTRA_AGENT_ARGS)\n print(\"Got extra args:\", extra_args)\n alice_agent = await create_agent_with_args(\n args,\n ident=\"alice\",\n extra_args=extra_args,\n )\n\n try:\n log_status(\n \"#7 Provision an agent and wallet, get back configuration details\"\n + (\n f\" (Wallet type: {alice_agent.wallet_type})\"\n if alice_agent.wallet_type\n else \"\"\n )\n )\n agent = AliceAgent(\n \"alice.agent\",\n alice_agent.start_port,\n alice_agent.start_port + 1,\n genesis_data=alice_agent.genesis_txns,\n genesis_txn_list=alice_agent.genesis_txn_list,\n no_auto=alice_agent.no_auto,\n tails_server_base_url=alice_agent.tails_server_base_url,\n revocation=alice_agent.revocation,\n timing=alice_agent.show_timing,\n multitenant=alice_agent.multitenant,\n mediation=alice_agent.mediation,\n wallet_type=alice_agent.wallet_type,\n aip=alice_agent.aip,\n endorser_role=alice_agent.endorser_role,\n log_file=alice_agent.log_file,\n log_config=alice_agent.log_config,\n log_level=alice_agent.log_level,\n reuse_connections=alice_agent.reuse_connections,\n extra_args=extra_args,\n )\n\n await alice_agent.initialize(the_agent=agent)\n\n log_status(\"#9 Input faber.py invitation details\")\n await input_invitation(alice_agent)\n\n options = \" (3) Send Message\\n\" \" (4) Input New Invitation\\n\"\n if alice_agent.endorser_role and alice_agent.endorser_role == \"author\":\n options += \" (D) Set Endorser's DID\\n\"\n if alice_agent.multitenant:\n options += \" (W) Create and/or Enable Wallet\\n\"\n options += \" (X) Exit?\\n[3/4/{}X] \".format(\n \"W/\" if alice_agent.multitenant else \"\",\n )\n async for option in prompt_loop(options):\n if option is not None:\n option = option.strip()\n\n if option is None or option in \"xX\":\n break\n\n elif option in \"dD\" and alice_agent.endorser_role:\n endorser_did = await prompt(\"Enter Endorser's DID: \")\n await alice_agent.agent.admin_POST(\n f\"/transactions/{alice_agent.agent.connection_id}/set-endorser-info\",\n params={\"endorser_did\": endorser_did, \"endorser_name\": \"endorser\"},\n )\n\n elif option in \"wW\" and alice_agent.multitenant:\n target_wallet_name = await prompt(\"Enter wallet name: \")\n include_subwallet_webhook = await prompt(\n \"(Y/N) Create sub-wallet webhook target: \"\n )\n if include_subwallet_webhook.lower() == \"y\":\n await alice_agent.agent.register_or_switch_wallet(\n target_wallet_name,\n webhook_port=alice_agent.agent.get_new_webhook_port(),\n mediator_agent=alice_agent.mediator_agent,\n taa_accept=alice_agent.taa_accept,\n )\n else:\n await alice_agent.agent.register_or_switch_wallet(\n target_wallet_name,\n mediator_agent=alice_agent.mediator_agent,\n taa_accept=alice_agent.taa_accept,\n )\n\n elif option == \"3\":\n msg = await prompt(\"Enter message: \")\n if msg:\n await alice_agent.agent.admin_POST(\n f\"/connections/{alice_agent.agent.connection_id}/send-message\",\n {\"content\": msg},\n )\n\n elif option == \"4\":\n # handle new invitation\n log_status(\"Input new invitation details\")\n await input_invitation(alice_agent)\n\n if alice_agent.show_timing:\n timing = await alice_agent.agent.fetch_timing()\n if timing:\n for line in alice_agent.agent.format_timing(timing):\n log_msg(line)\n\n finally:\n terminated = await alice_agent.terminate()\n\n await asyncio.sleep(0.1)\n\n if not terminated:\n os._exit(1)", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def process_file_type(obj: Any, spec: dict, conf: dict):\n for key in conf:\n if \"type\" in spec[key]:\n if spec[key][\"type\"] == \"file\":\n save_file_type(obj, key, \"\", conf[key])\n elif spec[key][\"type\"] == \"secretfile\":\n if conf[key] is not None:\n value = conf[key]\n if conf[key].startswith(settings.ANSIBLE_VAULT_HEADER):\n try:\n value = ansible_decrypt(msg=value)\n except AnsibleError:\n raise_adcm_ex(\n code=\"CONFIG_VALUE_ERROR\",\n msg=f\"Secret value must not starts with {settings.ANSIBLE_VAULT_HEADER}\",\n )\n else:\n value = None\n\n save_file_type(obj, key, \"\", value)\n elif conf[key]:\n for subkey in conf[key]:\n if spec[key][subkey][\"type\"] == \"file\":\n save_file_type(obj, key, subkey, conf[key][subkey])\n elif spec[key][subkey][\"type\"] == \"secretfile\":\n value = conf[key][subkey]\n if conf[key][subkey] is not None:\n if conf[key][subkey].startswith(settings.ANSIBLE_VAULT_HEADER):\n try:\n value = ansible_decrypt(msg=value)\n except AnsibleError:\n raise_adcm_ex(\n code=\"CONFIG_VALUE_ERROR\",\n msg=f\"Secret value must not starts with {settings.ANSIBLE_VAULT_HEADER}\",\n )\n else:\n value = None\n\n save_file_type(obj, key, subkey, value)", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def post(self, request, **kwargs):\n playbook_id = kwargs.get('pk')\n playbook = self.get_playbook(playbook_id)\n work_path = playbook.work_dir\n\n parent_key = request.data.get('key', '')\n if parent_key == 'root':\n parent_key = ''\n if os.path.dirname(parent_key) == 'root':\n parent_key = os.path.basename(parent_key)\n\n full_path = safe_join(work_path, parent_key)\n\n is_directory = request.data.get('is_directory', False)\n content = request.data.get('content', '')\n name = request.data.get('name', '')\n\n def find_new_name(p, is_file=False):\n if not p:\n if is_file:\n p = 'new_file.yml'\n else:\n p = 'new_dir'\n np = safe_join(full_path, p)\n n = 0\n while os.path.exists(np):\n n += 1\n np = safe_join(full_path, '{}({})'.format(p, n))\n return np\n\n try:\n if is_directory:\n new_file_path = find_new_name(name)\n os.makedirs(new_file_path)\n else:\n new_file_path = find_new_name(name, True)\n with open(new_file_path, 'w') as f:\n f.write(content)\n except SuspiciousFileOperation:\n raise JMSException(code='invalid_file_path', detail={\"msg\": _(\"Invalid file path\")})\n\n relative_path = os.path.relpath(os.path.dirname(new_file_path), work_path)\n new_node = {\n \"name\": os.path.basename(new_file_path),\n \"title\": os.path.basename(new_file_path),\n \"id\": safe_join(relative_path, os.path.basename(new_file_path))\n if not safe_join(relative_path, os.path.basename(new_file_path)).startswith('.')\n else os.path.basename(new_file_path),\n \"isParent\": is_directory,\n \"pId\": relative_path if not relative_path.startswith('.') else 'root',\n \"open\": True,\n }\n if not is_directory:\n new_node['iconSkin'] = 'file'\n return Response(new_node)", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "def InitializePerPipeRoot(datadescription, inCoprocessor):\n if PhactoriDbg():\n myDebugPrint3(\"InitializePerPipeRoot entered\\n\")\n\n sa = GetUserDataStringArrayAccountingForBypass(datadescription)\n\n testJsonString = sa[0]\n separatorCharacterString = sa[1]\n inputDeckFilename = sa[2]\n extraFileString = sa[3]\n sa4 = sa[4]\n sa5 = sa[5]\n dbDummyFname = sa[6]\n if(len(sa) > 7): \n defaultDirectory = sa[7]\n else:\n defaultDirectory = \"\"\n if(len(sa) > 8): \n catalyst_script_extra_file = sa[8]\n else:\n catalyst_script_extra_file = \"\"\n\n outputResultBaseId, remeshRestartTag = parseDbDummyFname(dbDummyFname) \n if PhactoriDbg():\n myDebugPrint3(\" extra data list:\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" separatorCharacterString: ->\" + separatorCharacterString + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inputDeckFilename: ->\" + inputDeckFilename + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" extraFileString: ->\" + extraFileString + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" sa4: ->\" + sa4 + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" sa5: ->\" + sa5 + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" dbDummyFname: ->\" + dbDummyFname + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" outputResultBaseId: ->\" + outputResultBaseId + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" remeshRestartTag: ->\" + remeshRestartTag + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" defaultDirectory: ->\" + defaultDirectory + \"<-\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" catalyst_script_extra_file: ->\" + catalyst_script_extra_file + \"<-\\n\")\n\n global gPipeAndViewsState\n\n if outputResultBaseId in gPhactoriPipeRootMap:\n if PhactoriDbg():\n myDebugPrint3(\" I've seen this outputResults block id\\n\")\n oneRoot = gPhactoriPipeRootMap[outputResultBaseId]\n oneRoot.CurrentDatadescription = datadescription\n gPipeAndViewsState = oneRoot\n if remeshRestartTag != oneRoot.mRemeshRestartTag:\n oneRoot.mRemeshRestartTag = remeshRestartTag\n oneRoot.mRemeshCount += 1\n HandleUserInteractionIfEnabled(oneRoot)\n else:\n if PhactoriDbg():\n myDebugPrint3(\" first time for this outputResults block id\\n\")\n SetUpCoProcessor(inCoprocessor)\n newRoot = PhactoriPipeAndViewsState()\n newRoot.mDefaultBasedirectory = defaultDirectory\n newRoot.CurrentDatadescription = datadescription\n newRoot.mOutputResultsBlockId = outputResultBaseId\n newRoot.mCurrentDatabaseDummyFileName = dbDummyFname\n newRoot.mRemeshRestartTag = remeshRestartTag\n newRoot.mSeparatorString = separatorCharacterString\n newRoot.mOutputResultsBlockCountId = len(gPhactoriPipeRootMap)\n newRoot.mBlockIdForRestart = \"restart.\" + str(len(gPhactoriPipeRootMap))\n gPhactoriPipeRootMap[outputResultBaseId] = newRoot\n gPipeAndViewsState = newRoot\n CreateAllProducersFromAllInputDescriptions(datadescription, inCoprocessor, newRoot)\n\n CreatePipelineFromDataDescription(datadescription)\n HandleRestartUpdateForOutputResultsBlock(newRoot)\n\n gPipeAndViewsState.mCallbackDateTime = datetime.datetime.now()\n\n if PhactoriDbg():\n myDebugPrint3(\"InitializePerPipeRoot returning\\n\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def genSwitch(pixelExpr):\n\t# Note: In practice, only the center subpixel of HQ3x is independent of\n\t# the edge bits. So maybe this is a bit overengineered, but it does\n\t# express why this optimization is correct.\n\tsubExprForSubPixel = tuple(\n\t\t{expr[subPixel] for expr in pixelExpr if expr[subPixel] is not None}\n\t\tfor subPixel in range(len(pixelExpr[0]))\n\t\t)\n\tisIndependentSubPixel = tuple(\n\t\tlen(subExprs) == 1\n\t\tfor subExprs in subExprForSubPixel\n\t\t)\n\n\texprToCases = defaultdict(list)\n\tfor case, expr in enumerate(pixelExpr):\n\t\tif expr[0] is None:\n\t\t\tassert all(subExpr is None for subExpr in expr)\n\t\t\tkey = None\n\t\telse:\n\t\t\tkey = tuple(tuple(subExpr) for subExpr in expr)\n\t\texprToCases[key].append(case)\n\tyield 'switch (pattern) {\\n'\n\tfor cases, expr in sorted(\n\t\t( sorted(cases), expr )\n\t\tfor expr, cases in exprToCases.items()\n\t\t):\n\t\tif expr is not None:\n\t\t\tfor case in cases:\n\t\t\t\tyield 'case %d:\\n' % case\n\t\t\tfor subPixel, subExpr in enumerate(expr):\n\t\t\t\tif not isIndependentSubPixel[subPixel]:\n\t\t\t\t\tyield '\\tpixel%s = %s;\\n' % (\n\t\t\t\t\t\thex(subPixel)[2 : ], getBlendCode(subExpr)\n\t\t\t\t\t\t)\n\t\t\tyield '\\tbreak;\\n'\n\tfor case in sorted(exprToCases[None]):\n\t\tyield 'case %d:\\n' % case\n\tyield 'default:\\n'\n\tyield '\\tUNREACHABLE;\\n'\n\tyield '\\t%s = 0; // avoid warning\\n' % ' = '.join(\n\t\t'pixel%d' % subPixel\n\t\tfor subPixel, independent_ in enumerate(isIndependentSubPixel)\n\t\t)\n\tyield '}\\n'\n\n\tfor subPixel, independent in enumerate(isIndependentSubPixel):\n\t\tif independent:\n\t\t\tsubExpr, = subExprForSubPixel[subPixel]\n\t\t\tyield 'pixel%s = %s;\\n' % (\n\t\t\t\thex(subPixel)[2 : ], getBlendCode(subExpr)\n\t\t\t\t)", "smellKey": "S3776", "smellId": null, "repo": "openMSX_openMSX", "language": "python"} {"function": "def _import_to_task(dataset, instance_data):\n tracks = {}\n label_cat = dataset.categories()[dm.AnnotationType.label]\n\n for item in dataset:\n # NOTE: MOT frames start from 1\n # job has an offset, for task offset is 0\n frame_number = int(item.id) - 1 + instance_data.start\n frame_number = instance_data.abs_frame_id(frame_number)\n\n for ann in item.annotations:\n if ann.type != dm.AnnotationType.bbox:\n continue\n\n occluded = ann.attributes.pop('occluded', False) is True\n track_id = ann.attributes.pop('track_id', None)\n attributes = [\n instance_data.Attribute(name=n, value=str(v))\n for n, v in ann.attributes.items()\n ]\n if track_id is None:\n # Extension. Import regular boxes:\n instance_data.add_shape(instance_data.LabeledShape(\n type='rectangle',\n label=label_cat.items[ann.label].name,\n points=ann.points,\n occluded=occluded,\n z_order=ann.z_order,\n group=0,\n frame=frame_number,\n attributes=attributes,\n source='manual',\n ))\n continue\n\n shape = instance_data.TrackedShape(\n type='rectangle',\n points=ann.points,\n occluded=occluded,\n outside=False,\n keyframe=True,\n z_order=ann.z_order,\n frame=frame_number,\n attributes=attributes,\n source='manual',\n )\n\n # build trajectories as lists of shapes in track dict\n if track_id not in tracks:\n tracks[track_id] = instance_data.Track(\n label_cat.items[ann.label].name, 0, 'manual', [])\n tracks[track_id].shapes.append(shape)\n\n for track in tracks.values():\n # MOT annotations do not require frames to be ordered\n track.shapes.sort(key=lambda t: t.frame)\n\n # insert outside=True in skips between the frames track is visible\n prev_shape_idx = 0\n prev_shape = track.shapes[0]\n for shape in track.shapes[1:]:\n has_skip = instance_data.frame_step < shape.frame - prev_shape.frame\n if has_skip and not prev_shape.outside:\n prev_shape = prev_shape._replace(outside=True,\n frame=prev_shape.frame + instance_data.frame_step)\n prev_shape_idx += 1\n track.shapes.insert(prev_shape_idx, prev_shape)\n prev_shape = shape\n prev_shape_idx += 1\n\n # Append a shape with outside=True to finish the track\n last_shape = track.shapes[-1]\n if last_shape.frame + instance_data.frame_step <= \\\n int(instance_data.meta[instance_data.META_FIELD]['stop_frame']):\n track.shapes.append(last_shape._replace(outside=True,\n frame=last_shape.frame + instance_data.frame_step)\n )\n instance_data.add_track(track)", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def _openc3_script_sleep(sleep_time=None):\n if RunningScript.disconnect:\n return True\n\n Store.publish(\n f\"script-api:running-script-channel:{RunningScript.instance.id}\",\n json.dumps(\n {\n \"type\": \"line\",\n \"filename\": RunningScript.instance.current_filename,\n \"line_no\": RunningScript.instance.current_line_number,\n \"state\": \"waiting\",\n }\n ),\n )\n\n if sleep_time is None: # Handle infinite wait\n sleep_time = 30000000\n if sleep_time > 0.0:\n end_time = time.time() + sleep_time\n count = 0\n while time.time() < end_time:\n time.sleep(0.01)\n count += 1\n if (count % 100) == 0: # Approximately Every Second\n Store.publish(\n f\"script-api:running-script-channel:{RunningScript.instance.id}\",\n json.dumps(\n {\n \"type\": \"line\",\n \"filename\": RunningScript.instance.current_filename,\n \"line_no\": RunningScript.instance.current_line_number,\n \"state\": \"waiting\",\n }\n ),\n )\n\n if RunningScript.instance.pause:\n RunningScript.instance.perform_pause()\n return True\n\n if RunningScript.instance.check_and_clear_go():\n return True\n\n if RunningScript.instance.stop:\n raise StopScript\n return False", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "async def create_pres(\n self,\n pres_ex_record: V20PresExRecord,\n request_data: Optional[dict] = None,\n ) -> Tuple[V20PresFormat, AttachDecorator]:\n \"\"\"Create a presentation.\"\"\"\n request_data = request_data or {}\n proof_request = pres_ex_record.pres_request.attachment(\n DIFPresFormatHandler.format\n )\n\n pres_definition = None\n limit_record_ids = None\n reveal_doc_frame = None\n challenge = None\n domain = None\n if request_data != {} and DIFPresFormatHandler.format.api in request_data:\n dif_spec = request_data.get(DIFPresFormatHandler.format.api)\n pres_spec_payload = DIFPresSpecSchema().load(dif_spec)\n # Overriding with prover provided pres_spec\n pres_definition = pres_spec_payload.get(\"presentation_definition\")\n issuer_id = pres_spec_payload.get(\"issuer_id\")\n limit_record_ids = pres_spec_payload.get(\"record_ids\")\n reveal_doc_frame = pres_spec_payload.get(\"reveal_doc\")\n if not pres_definition:\n pres_definition = PresentationDefinition.deserialize(\n proof_request.get(\"presentation_definition\")\n )\n issuer_id = None\n if \"options\" in proof_request:\n challenge = proof_request[\"options\"].get(\"challenge\")\n domain = proof_request[\"options\"].get(\"domain\")\n if not challenge:\n challenge = str(uuid4())\n input_descriptors = pres_definition.input_descriptors\n claim_fmt = pres_definition.fmt\n dif_handler_proof_type = None\n try:\n holder = self._profile.inject(VCHolder)\n record_ids = set()\n credentials_list = []\n for input_descriptor in input_descriptors:\n proof_type = None\n limit_disclosure = input_descriptor.constraint.limit_disclosure and (\n input_descriptor.constraint.limit_disclosure == \"required\"\n )\n uri_list = []\n one_of_uri_groups = []\n if input_descriptor.schemas:\n if input_descriptor.schemas.oneof_filter:\n one_of_uri_groups = (\n await self.retrieve_uri_list_from_schema_filter(\n input_descriptor.schemas.uri_groups\n )\n )\n else:\n schema_uris = input_descriptor.schemas.uri_groups[0]\n for schema_uri in schema_uris:\n if schema_uri.required is None:\n required = True\n else:\n required = schema_uri.required\n if required:\n uri_list.append(schema_uri.uri)\n if len(uri_list) == 0:\n uri_list = None\n if len(one_of_uri_groups) == 0:\n one_of_uri_groups = None\n if limit_disclosure:\n proof_type = [BbsBlsSignature2020.signature_type]\n dif_handler_proof_type = BbsBlsSignature2020.signature_type\n if claim_fmt:\n if claim_fmt.ldp_vp:\n if \"proof_type\" in claim_fmt.ldp_vp:\n proof_types = claim_fmt.ldp_vp.get(\"proof_type\")\n if limit_disclosure and (\n BbsBlsSignature2020.signature_type not in proof_types\n ):\n raise V20PresFormatHandlerError(\n \"Verifier submitted presentation request with \"\n \"limit_disclosure [selective disclosure] \"\n \"option but verifier does not support \"\n \"BbsBlsSignature2020 format\"\n )\n elif (\n len(proof_types) == 1\n and (\n BbsBlsSignature2020.signature_type not in proof_types\n )\n and (\n Ed25519Signature2018.signature_type not in proof_types\n )\n and (\n Ed25519Signature2020.signature_type not in proof_types\n )\n ):\n raise V20PresFormatHandlerError(\n \"Only BbsBlsSignature2020 and/or \"\n \"Ed25519Signature2018 and/or \"\n \"Ed25519Signature2018 and/or \"\n \"Ed25519Signature2020 signature types \"\n \"are supported\"\n )\n elif (\n len(proof_types) >= 2\n and (\n BbsBlsSignature2020.signature_type not in proof_types\n )\n and (\n Ed25519Signature2018.signature_type not in proof_types\n )\n and (\n Ed25519Signature2020.signature_type not in proof_types\n )\n ):\n raise V20PresFormatHandlerError(\n \"Only BbsBlsSignature2020, Ed25519Signature2018 and \"\n \"Ed25519Signature2020 signature types \"\n \"are supported\"\n )\n else:\n for proof_format in proof_types:\n if (\n proof_format\n == Ed25519Signature2018.signature_type\n ):\n proof_type = [Ed25519Signature2018.signature_type]\n dif_handler_proof_type = (\n Ed25519Signature2018.signature_type\n )\n break\n elif (\n proof_format == BbsBlsSignature2020.signature_type\n ):\n proof_type = [BbsBlsSignature2020.signature_type]\n dif_handler_proof_type = (\n BbsBlsSignature2020.signature_type\n )\n break\n elif claim_fmt.di_vc:\n if \"proof_type\" in claim_fmt.di_vc:\n proof_types = claim_fmt.di_vc.get(\"proof_type\")\n\n proof_type = [\n \"DataIntegrityProof\"\n ] # [LinkedDataProof.signature_type]\n dif_handler_proof_type = \"anoncreds-2023\"\n\n # TODO check acceptable proof type(s) (\"anoncreds-2023\")\n\n else:\n # TODO di_vc allowed ...\n raise V20PresFormatHandlerError(\n \"Currently, only: ldp_vp with \"\n \"BbsBlsSignature2020, Ed25519Signature2018 and \"\n \"Ed25519Signature2020 signature types; and \"\n \"di_vc with anoncreds-2023 signatures are supported\"\n )\n\n if one_of_uri_groups:\n records = []\n cred_group_record_ids = set()\n for uri_group in one_of_uri_groups:\n search = holder.search_credentials(\n proof_types=proof_type, pd_uri_list=uri_group\n )\n max_results = 1000\n cred_group = await search.fetch(max_results)\n (\n cred_group_vcrecord_list,\n cred_group_vcrecord_ids_set,\n ) = await self.process_vcrecords_return_list(\n cred_group, cred_group_record_ids\n )\n cred_group_record_ids = cred_group_vcrecord_ids_set\n records = records + cred_group_vcrecord_list\n else:\n search = holder.search_credentials(\n proof_types=proof_type, pd_uri_list=uri_list\n )\n # Defaults to page_size but would like to include all\n # For now, setting to 1000\n max_results = 1000\n records = await search.fetch(max_results)\n\n # Avoiding addition of duplicate records\n (\n vcrecord_list,\n vcrecord_ids_set,\n ) = await self.process_vcrecords_return_list(records, record_ids)\n record_ids = vcrecord_ids_set\n credentials_list = credentials_list + vcrecord_list\n\n except StorageNotFoundError as err:\n raise V20PresFormatHandlerError(err)\n except TypeError as err:\n LOGGER.error(str(err))\n responder = self._profile.inject_or(BaseResponder)\n if responder:\n report = ProblemReport(\n description={\n \"en\": (\n \"Presentation request not properly formatted,\"\n \" TypeError raised on Holder agent.\"\n ),\n \"code\": ProblemReportReason.ABANDONED.value,\n }\n )\n if pres_ex_record.thread_id:\n report.assign_thread_id(pres_ex_record.thread_id)\n await responder.send_reply(\n report, connection_id=pres_ex_record.connection_id\n )\n return\n\n # TODO check for ldp_vp vs di_vc request and prepare presentation as appropriate\n dif_handler = DIFPresExchHandler(\n self._profile,\n pres_signing_did=issuer_id,\n proof_type=dif_handler_proof_type,\n reveal_doc=reveal_doc_frame,\n )\n try:\n pres = await dif_handler.create_vp(\n challenge=challenge,\n domain=domain,\n pd=pres_definition,\n credentials=credentials_list,\n records_filter=limit_record_ids,\n is_holder_override=True,\n )\n return self.get_format_data(PRES_20, pres)\n except DIFPresExchError as err:\n LOGGER.error(str(err))\n responder = self._profile.inject_or(BaseResponder)\n if responder:\n report = ProblemReport(\n description={\n \"en\": str(err),\n \"code\": ProblemReportReason.ABANDONED.value,\n }\n )\n if pres_ex_record.thread_id:\n report.assign_thread_id(pres_ex_record.thread_id)\n await responder.send_reply(\n report, connection_id=pres_ex_record.connection_id\n )", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None:\n \"\"\"Makes appropriate Windows Console API calls based on the segments in the buffer.\n\n Args:\n buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls.\n term (LegacyWindowsTerm): Used to call the Windows Console API.\n \"\"\"\n for text, style, control in buffer:\n if not control:\n if style:\n term.write_styled(text, style)\n else:\n term.write_text(text)\n else:\n control_codes: Sequence[ControlCode] = control\n for control_code in control_codes:\n control_type = control_code[0]\n if control_type == ControlType.CURSOR_MOVE_TO:\n _, x, y = cast(Tuple[ControlType, int, int], control_code)\n term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1))\n elif control_type == ControlType.CARRIAGE_RETURN:\n term.write_text(\"\\r\")\n elif control_type == ControlType.HOME:\n term.move_cursor_to(WindowsCoordinates(0, 0))\n elif control_type == ControlType.CURSOR_UP:\n term.move_cursor_up()\n elif control_type == ControlType.CURSOR_DOWN:\n term.move_cursor_down()\n elif control_type == ControlType.CURSOR_FORWARD:\n term.move_cursor_forward()\n elif control_type == ControlType.CURSOR_BACKWARD:\n term.move_cursor_backward()\n elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN:\n _, column = cast(Tuple[ControlType, int], control_code)\n term.move_cursor_to_column(column - 1)\n elif control_type == ControlType.HIDE_CURSOR:\n term.hide_cursor()\n elif control_type == ControlType.SHOW_CURSOR:\n term.show_cursor()\n elif control_type == ControlType.ERASE_IN_LINE:\n _, mode = cast(Tuple[ControlType, int], control_code)\n if mode == 0:\n term.erase_end_of_line()\n elif mode == 1:\n term.erase_start_of_line()\n elif mode == 2:\n term.erase_line()\n elif control_type == ControlType.SET_WINDOW_TITLE:\n _, title = cast(Tuple[ControlType, str], control_code)\n term.set_title(title)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def update_xtbs_locally(grd_file_path, brave_source_root):\n \"\"\"Updates XTBs from the local Chromium files\"\"\"\n xtb_files = get_xtb_files(grd_file_path)\n chromium_grd_file_path = get_chromium_grd_src_with_fallback(grd_file_path,\n brave_source_root)\n chromium_xtb_files = get_xtb_files(chromium_grd_file_path)\n if len(xtb_files) != len(chromium_xtb_files):\n assert False, (f'XTB files counts in {grd_file_path} and ' +\n f'{chromium_grd_file_path} do not match ( ' +\n f'{len(xtb_files)} vs {len(chromium_xtb_files)}).')\n\n grd_base_path = os.path.dirname(grd_file_path)\n chromium_grd_base_path = os.path.dirname(chromium_grd_file_path)\n\n # Update XTB FPs so it uses the branded source string\n grd_strings = get_grd_strings(grd_file_path, validate_tags=False)\n chromium_grd_strings = get_grd_strings(\n chromium_grd_file_path, validate_tags=False)\n # Special treatment for brave_strings.grd\n brave_strings_string_ids = []\n if os.path.basename(grd_file_path) == 'brave_strings.grd':\n assert len(grd_strings) == len(chromium_grd_strings) + \\\n len(GOOGLE_CHROME_STRINGS_MIGRATION_MAP)\n brave_strings_string_ids = remove_google_chrome_strings(\n grd_strings, GOOGLE_CHROME_STRINGS_MIGRATION_MAP)\n assert len(grd_strings) == len(chromium_grd_strings)\n # Verify that string names match\n for idx, grd_string in enumerate(grd_strings):\n assert chromium_grd_strings[idx][0] == grd_string[0]\n\n # [2] is the string fingerprint\n fp_map = {\n chromium_grd_strings[idx][2]: grd_strings[idx][2]\n for (idx, _) in enumerate(grd_strings)\n }\n\n xtb_file_paths = [os.path.join(\n grd_base_path, path) for (_, path) in xtb_files]\n chromium_xtb_file_paths = [\n os.path.join(chromium_grd_base_path, path) for\n (_, path) in chromium_xtb_files]\n for idx, xtb_file in enumerate(xtb_file_paths):\n chromium_xtb_file = chromium_xtb_file_paths[idx]\n if not os.path.exists(chromium_xtb_file):\n print('Warning: Skipping because Chromium path does not exist: ' \\\n f'{chromium_xtb_file}')\n continue\n xml_tree = lxml.etree.parse(chromium_xtb_file)\n\n for node in xml_tree.xpath('//translation'):\n generate_braveified_node(node, False, True)\n # Use our fp, when exists.\n old_fp = node.attrib['id']\n # It's possible for an xtb string to not be in our GRD.\n # This happens, for exmaple, with Chrome OS strings which\n # we don't process files for.\n if old_fp in fp_map:\n new_fp = fp_map.get(old_fp)\n if new_fp != old_fp:\n node.attrib['id'] = new_fp\n # print(f'fp: {old_fp} -> {new_fp}')\n\n # Special treatment for brave_strings.grd\n if os.path.basename(grd_file_path) == 'brave_strings.grd':\n add_google_chrome_translations(xtb_file, xml_tree,\n brave_strings_string_ids)\n\n transformed_content = (b'<?xml version=\"1.0\" ?>\\n' +\n lxml.etree.tostring(xml_tree, pretty_print=True,\n xml_declaration=False, encoding='utf-8').strip())\n with open(xtb_file, mode='wb') as f:\n f.write(transformed_content)", "smellKey": "S3776", "smellId": null, "repo": "brave_brave-core", "language": "python"} {"function": "def check(self, strict=False):\n \"\"\"Check if the metadata is compliant. If strict is True then raise if\n no Name or Version are provided\"\"\"\n self.set_metadata_version()\n\n # XXX should check the versions (if the file was loaded)\n missing, warnings = [], []\n\n for attr in ('Name', 'Version'): # required by PEP 345\n if attr not in self:\n missing.append(attr)\n\n if strict and missing != []:\n msg = 'missing required metadata: %s' % ', '.join(missing)\n raise MetadataMissingError(msg)\n\n for attr in ('Home-page', 'Author'):\n if attr not in self:\n missing.append(attr)\n\n # checking metadata 1.2 (XXX needs to check 1.1, 1.0)\n if self['Metadata-Version'] != '1.2':\n return missing, warnings\n\n scheme = get_scheme(self.scheme)\n\n def are_valid_constraints(value):\n for v in value:\n if not scheme.is_valid_matcher(v.split(';')[0]):\n return False\n return True\n\n for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),\n (_VERSIONS_FIELDS,\n scheme.is_valid_constraint_list),\n (_VERSION_FIELDS,\n scheme.is_valid_version)):\n for field in fields:\n value = self.get(field, None)\n if value is not None and not controller(value):\n warnings.append(\"Wrong value for '%s': %s\" % (field, value))\n\n return missing, warnings", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "async def _get_service_state(\n client: aiodocker.docker.Docker, service: Dict\n) -> Tuple[ServiceState, str]:\n # some times one has to wait until the task info is filled\n service_name = service[\"Spec\"][\"Name\"]\n log.debug(\"Getting service %s state\", service_name)\n tasks = await client.tasks.list(filters={\"service\": service_name})\n\n # wait for tasks\n task_started_time = datetime.utcnow()\n while (datetime.utcnow() - task_started_time) < timedelta(seconds=20):\n tasks = await client.tasks.list(filters={\"service\": service_name})\n # only keep the ones with the right service ID (we're being a bit picky maybe)\n tasks = [x for x in tasks if x[\"ServiceID\"] == service[\"ID\"]]\n if tasks:\n break\n await asyncio.sleep(1) # let other events happen too\n\n if not tasks:\n return (ServiceState.FAILED, \"getting state timed out\")\n\n # we are only interested in the last task which has been created last\n last_task = sorted(tasks, key=lambda task: task[\"UpdatedAt\"])[-1]\n task_state = last_task[\"Status\"][\"State\"]\n\n log.debug(\"%s %s\", service[\"ID\"], task_state)\n\n last_task_state = ServiceState.STARTING # default\n last_task_error_msg = (\n last_task[\"Status\"][\"Err\"] if \"Err\" in last_task[\"Status\"] else \"\"\n )\n if task_state in (\"failed\"):\n # check if it failed already the max number of attempts we allow for\n if len(tasks) < config.DIRECTOR_SERVICES_RESTART_POLICY_MAX_ATTEMPTS:\n log.debug(\"number of tasks: %s\", len(tasks))\n last_task_state = ServiceState.STARTING\n else:\n log.error(\n \"service %s failed with %s after %s trials\",\n service_name,\n last_task[\"Status\"],\n len(tasks),\n )\n last_task_state = ServiceState.FAILED\n elif task_state in (\"rejected\"):\n log.error(\"service %s failed with %s\", service_name, last_task[\"Status\"])\n last_task_state = ServiceState.FAILED\n elif task_state in (\"pending\"):\n last_task_state = ServiceState.PENDING\n elif task_state in (\"assigned\", \"accepted\", \"preparing\"):\n last_task_state = ServiceState.PULLING\n elif task_state in (\"ready\", \"starting\"):\n last_task_state = ServiceState.STARTING\n elif task_state in (\"running\"):\n now = datetime.utcnow()\n # NOTE: task_state_update_time is only used to discrimitate between 'starting' and 'running'\n task_state_update_time = parse_as_datetime(\n last_task[\"Status\"][\"Timestamp\"], default=now\n )\n time_since_running = now - task_state_update_time\n\n log.debug(\"Now is %s, time since running mode is %s\", now, time_since_running)\n if time_since_running > timedelta(\n seconds=config.DIRECTOR_SERVICES_STATE_MONITOR_S\n ):\n last_task_state = ServiceState.RUNNING\n else:\n last_task_state = ServiceState.STARTING\n\n elif task_state in (\"complete\", \"shutdown\"):\n last_task_state = ServiceState.COMPLETE\n log.debug(\"service running state is %s\", last_task_state)\n return (last_task_state, last_task_error_msg)", "smellKey": "S3776", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "@staticmethod\n def get_current_transaction(\n transactions: Sequence[SnubaTransaction],\n errors: Sequence[SnubaError],\n event_id: str,\n ) -> tuple[SnubaTransaction | None, Event | GroupEvent | None]:\n \"\"\"Given an event_id return the related transaction event\n\n The event_id could be for an error, since we show the quick-trace\n for both event types\n We occasionally have to get the nodestore data, so this function returns\n the nodestore event as well so that we're doing that in one location.\n \"\"\"\n transaction_event = find_event(\n transactions, lambda item: item is not None and item[\"id\"] == event_id\n )\n if transaction_event is not None:\n return transaction_event, eventstore.backend.get_event_by_id(\n transaction_event[\"project.id\"], transaction_event[\"id\"]\n )\n\n # The event couldn't be found, it might be an error\n error_event = find_event(errors, lambda item: item is not None and item[\"id\"] == event_id)\n # Alright so we're looking at an error, time to see if we can find its transaction\n if error_event is not None:\n # Unfortunately the only association from an event back to its transaction is name & span_id\n # First maybe we got lucky and the error happened on the transaction's \"span\"\n error_span = error_event[\"trace.span\"]\n transaction_event = find_event(\n transactions, lambda item: item is not None and item[\"trace.span\"] == error_span\n )\n if transaction_event is not None:\n return transaction_event, eventstore.backend.get_event_by_id(\n transaction_event[\"project.id\"], transaction_event[\"id\"]\n )\n # We didn't get lucky, time to talk to nodestore...\n for transaction_event in transactions:\n if transaction_event[\"transaction\"] != error_event[\"transaction\"]:\n continue\n\n nodestore_event = eventstore.backend.get_event_by_id(\n transaction_event[\"project.id\"], transaction_event[\"id\"]\n )\n if nodestore_event is None:\n return None, None\n transaction_spans: NodeSpans = nodestore_event.data.get(\"spans\", [])\n for span in transaction_spans:\n if span[\"span_id\"] == error_event[\"trace.span\"]:\n return transaction_event, nodestore_event\n\n return None, None", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def getOpenWebifHTML(self):\n\t\thtml = []\n\t\terror = False\n\t\timage = self.remote[\"image\"]\n\t\tif image:\n\t\t\thtml.append(f\"<img border=\\\"0\\\" src=\\\"{image}\\\" usemap=\\\"#map\\\" />\")\n\t\t\thtml.append(\"<map name=\\\"map\\\">\")\n\t\t\tfor keyId in self.remote[\"keyIds\"]:\n\t\t\t\tattribs = []\n\t\t\t\ttitle = self.remote[keyId][\"title\"]\n\t\t\t\tif title:\n\t\t\t\t\tattribs.append(f\"title=\\\"{title}\\\"\")\n\t\t\t\telse:\n\t\t\t\t\terror = True\n\t\t\t\tshape = self.remote[keyId][\"shape\"]\n\t\t\t\tif shape:\n\t\t\t\t\tattribs.append(f\"shape=\\\"{shape}\\\"\")\n\t\t\t\telse:\n\t\t\t\t\terror = True\n\t\t\t\tcoords = \",\".join([str(x) for x in self.remote[keyId][\"coords\"]])\n\t\t\t\tif coords:\n\t\t\t\t\tattribs.append(f\"coords=\\\"{coords}\\\"\")\n\t\t\t\telse:\n\t\t\t\t\terror = True\n\t\t\t\tif keyId > 0:\n\t\t\t\t\tattribs.append(f\"onclick=\\\"pressMenuRemote('{keyId}');\\\"\")\n\t\t\t\thtml.append(f\"\\t<area {' '.join(attribs)} />\")\n\t\t\thtml.append(\"</map>\")\n\t\telse:\n\t\t\terror = True\n\t\treturn None if error else \"\\n\".join(html)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@classmethod\n def create(cls, request, view, obj, iam_context):\n Scopes = __class__.Scopes\n permissions = []\n if view.basename == \"analytics_reports\":\n scopes = cls.get_scopes(request, view, obj)\n for scope in scopes:\n self = cls.create_base_perm(request, view, scope, iam_context, obj)\n permissions.append(self)\n\n try:\n if view.action == Scopes.LIST:\n job_id = request.query_params.get(\"job_id\", None)\n task_id = request.query_params.get(\"task_id\", None)\n project_id = request.query_params.get(\"project_id\", None)\n\n if job_id:\n perm = JobPermission.create_scope_view(request, int(job_id))\n permissions.append(perm)\n else:\n job_id = request.data.get(\"job_id\", None)\n task_id = request.data.get(\"task_id\", None)\n project_id = request.data.get(\"project_id\", None)\n\n if job_id:\n job = Job.objects.select_related(\"segment__task\").get(id=job_id)\n task_id = job.segment.task.id\n\n if task_id:\n perm = TaskPermission.create_scope_view(request, int(task_id))\n permissions.append(perm)\n\n if project_id:\n perm = ProjectPermission.create_scope_view(request, int(project_id))\n permissions.append(perm)\n except ObjectDoesNotExist as ex:\n raise ValidationError(\n \"The specified resource does not exist. Please check the provided identifiers\"\n ) from ex\n\n return permissions", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def __init__(\n self,\n recipients: Iterable[Recipient],\n project_ids: Iterable[int] | None = None,\n organization_id: int | None = None,\n type: NotificationSettingEnum | None = None,\n provider: ExternalProviderEnum | None = None,\n ) -> None:\n self.project_ids = project_ids\n self.organization_id = organization_id\n self.type = type\n self.provider = provider\n\n if organization_id is not None:\n org_mapping = OrganizationMapping.objects.filter(\n organization_id=organization_id\n ).first()\n org = serialize_organization_mapping(org_mapping) if org_mapping is not None else None\n else:\n org = None\n if org and features.has(\"organizations:team-workflow-notifications\", org):\n self.recipients: list[Recipient] = []\n for recipient in recipients:\n if recipient_is_team(recipient):\n if team_is_valid_recipient(recipient):\n self.recipients.append(recipient)\n else:\n self.recipients += get_team_members(recipient)\n else:\n self.recipients.append(recipient)\n else:\n self.recipients = list(recipients)\n\n if self.recipients:\n query = self._get_query()\n type_filter = Q(type=self.type.value) if self.type else Q()\n provider_filter = Q(provider=self.provider.value) if self.provider else Q()\n self._setting_options = list(\n NotificationSettingOption.objects.filter(query & type_filter)\n )\n self._setting_providers = list(\n NotificationSettingProvider.objects.filter(query & type_filter & provider_filter)\n )\n else:\n self._setting_options = []\n self._setting_providers = []", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "async def filter_constraints(\n self,\n constraints: Constraints,\n credentials: Sequence[VCRecord],\n ) -> Sequence[VCRecord]:\n \"\"\"Return list of applicable VCRecords after applying filtering.\n\n Args:\n constraints: Constraints\n credentials: Sequence of credentials\n to apply filtering on\n Return:\n Sequence of applicable VCRecords\n\n \"\"\"\n document_loader = self.profile.inject(DocumentLoader)\n\n result = []\n for credential in credentials:\n if constraints.subject_issuer == \"required\" and not self.subject_is_issuer(\n credential=credential\n ):\n continue\n\n applicable = False\n is_holder_field_ids = self.field_ids_for_is_holder(constraints)\n for field in constraints._fields:\n applicable = await self.filter_by_field(field, credential)\n # all fields in the constraint should be satisfied\n if not applicable:\n break\n # is_holder with required directive requested for this field\n if applicable and field.id and field.id in is_holder_field_ids:\n # Missing credentialSubject.id - cannot verify that holder of claim\n # is same as subject\n credential_subject_ids = credential.subject_ids\n if not credential_subject_ids or len(credential_subject_ids) == 0:\n applicable = False\n break\n # Holder of claim is not same as the subject\n is_holder_same_as_subject = await self.process_constraint_holders(\n subject_ids=credential_subject_ids\n )\n if not is_holder_same_as_subject:\n applicable = False\n break\n if not applicable:\n continue\n if constraints.limit_disclosure == \"required\":\n credential_dict = credential.cred_value\n new_credential_dict = self.reveal_doc(\n credential_dict=credential_dict, constraints=constraints\n )\n if credential_dict[\"proof\"][\"type\"] == \"DataIntegrityProof\":\n # TODO - don't sign\n credential = self.create_vcrecord(credential_dict)\n else:\n derive_suite = await self._get_derive_suite()\n signed_new_credential_dict = await derive_credential(\n credential=credential_dict,\n reveal_document=new_credential_dict,\n suite=derive_suite,\n document_loader=document_loader,\n )\n credential = self.create_vcrecord(signed_new_credential_dict)\n result.append(credential)\n return result", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def generate_created_models(self):\n \"\"\"\n Find all new models (both managed and unmanaged) and make create\n operations for them as well as separate operations to create any\n foreign key or M2M relationships (these are optimized later, if\n possible).\n\n Defer any model options that refer to collections of fields that might\n be deferred (e.g. unique_together).\n \"\"\"\n old_keys = self.old_model_keys | self.old_unmanaged_keys\n added_models = self.new_model_keys - old_keys\n added_unmanaged_models = self.new_unmanaged_keys - old_keys\n all_added_models = chain(\n sorted(added_models, key=self.swappable_first_key, reverse=True),\n sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True),\n )\n for app_label, model_name in all_added_models:\n model_state = self.to_state.models[app_label, model_name]\n # Gather related fields\n related_fields = {}\n primary_key_rel = None\n for field_name, field in model_state.fields.items():\n if field.remote_field:\n if field.remote_field.model:\n if field.primary_key:\n primary_key_rel = field.remote_field.model\n elif not field.remote_field.parent_link:\n related_fields[field_name] = field\n if getattr(field.remote_field, \"through\", None):\n related_fields[field_name] = field\n\n # Are there indexes/unique_together to defer?\n indexes = model_state.options.pop(\"indexes\")\n constraints = model_state.options.pop(\"constraints\")\n unique_together = model_state.options.pop(\"unique_together\", None)\n order_with_respect_to = model_state.options.pop(\n \"order_with_respect_to\", None\n )\n # Depend on the deletion of any possible proxy version of us\n dependencies = [\n OperationDependency(\n app_label, model_name, None, OperationDependency.Type.REMOVE\n ),\n ]\n # Depend on all bases\n for base in model_state.bases:\n if isinstance(base, str) and \".\" in base:\n base_app_label, base_name = base.split(\".\", 1)\n dependencies.append(\n OperationDependency(\n base_app_label,\n base_name,\n None,\n OperationDependency.Type.CREATE,\n )\n )\n # Depend on the removal of base fields if the new model has\n # a field with the same name.\n old_base_model_state = self.from_state.models.get(\n (base_app_label, base_name)\n )\n new_base_model_state = self.to_state.models.get(\n (base_app_label, base_name)\n )\n if old_base_model_state and new_base_model_state:\n removed_base_fields = (\n set(old_base_model_state.fields)\n .difference(\n new_base_model_state.fields,\n )\n .intersection(model_state.fields)\n )\n for removed_base_field in removed_base_fields:\n dependencies.append(\n OperationDependency(\n base_app_label,\n base_name,\n removed_base_field,\n OperationDependency.Type.REMOVE,\n )\n )\n # Depend on the other end of the primary key if it's a relation\n if primary_key_rel:\n dependencies.append(\n OperationDependency(\n *resolve_relation(primary_key_rel, app_label, model_name),\n None,\n OperationDependency.Type.CREATE,\n ),\n )\n # Generate creation operation\n self.add_operation(\n app_label,\n operations.CreateModel(\n name=model_state.name,\n fields=[\n d\n for d in model_state.fields.items()\n if d[0] not in related_fields\n ],\n options=model_state.options,\n bases=model_state.bases,\n managers=model_state.managers,\n ),\n dependencies=dependencies,\n beginning=True,\n )\n\n # Don't add operations which modify the database for unmanaged models\n if not model_state.options.get(\"managed\", True):\n continue\n\n # Generate operations for each related field\n for name, field in sorted(related_fields.items()):\n dependencies = self._get_dependencies_for_foreign_key(\n app_label,\n model_name,\n field,\n self.to_state,\n )\n # Depend on our own model being created\n dependencies.append(\n OperationDependency(\n app_label, model_name, None, OperationDependency.Type.CREATE\n )\n )\n # Make operation\n self.add_operation(\n app_label,\n operations.AddField(\n model_name=model_name,\n name=name,\n field=field,\n ),\n dependencies=list(set(dependencies)),\n )\n # Generate other opns\n if order_with_respect_to:\n self.add_operation(\n app_label,\n operations.AlterOrderWithRespectTo(\n name=model_name,\n order_with_respect_to=order_with_respect_to,\n ),\n dependencies=[\n OperationDependency(\n app_label,\n model_name,\n order_with_respect_to,\n OperationDependency.Type.CREATE,\n ),\n OperationDependency(\n app_label, model_name, None, OperationDependency.Type.CREATE\n ),\n ],\n )\n related_dependencies = [\n OperationDependency(\n app_label, model_name, name, OperationDependency.Type.CREATE\n )\n for name in sorted(related_fields)\n ]\n related_dependencies.append(\n OperationDependency(\n app_label, model_name, None, OperationDependency.Type.CREATE\n )\n )\n for index in indexes:\n self.add_operation(\n app_label,\n operations.AddIndex(\n model_name=model_name,\n index=index,\n ),\n dependencies=related_dependencies,\n )\n for constraint in constraints:\n self.add_operation(\n app_label,\n operations.AddConstraint(\n model_name=model_name,\n constraint=constraint,\n ),\n dependencies=related_dependencies,\n )\n if unique_together:\n self.add_operation(\n app_label,\n operations.AlterUniqueTogether(\n name=model_name,\n unique_together=unique_together,\n ),\n dependencies=related_dependencies,\n )\n # Fix relationships if the model changed from a proxy model to a\n # concrete model.\n relations = self.to_state.relations\n if (app_label, model_name) in self.old_proxy_keys:\n for related_model_key, related_fields in relations[\n app_label, model_name\n ].items():\n related_model_state = self.to_state.models[related_model_key]\n for related_field_name, related_field in related_fields.items():\n self.add_operation(\n related_model_state.app_label,\n operations.AlterField(\n model_name=related_model_state.name,\n name=related_field_name,\n field=related_field,\n ),\n dependencies=[\n OperationDependency(\n app_label,\n model_name,\n None,\n OperationDependency.Type.CREATE,\n )\n ],\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def justify(\n self,\n console: \"Console\",\n width: int,\n justify: \"JustifyMethod\" = \"left\",\n overflow: \"OverflowMethod\" = \"fold\",\n ) -> None:\n \"\"\"Justify and overflow text to a given width.\n\n Args:\n console (Console): Console instance.\n width (int): Number of characters per line.\n justify (str, optional): Default justify method for text: \"left\", \"center\", \"full\" or \"right\". Defaults to \"left\".\n overflow (str, optional): Default overflow for text: \"crop\", \"fold\", or \"ellipsis\". Defaults to \"fold\".\n\n \"\"\"\n from .text import Text\n\n if justify == \"left\":\n for line in self._lines:\n line.truncate(width, overflow=overflow, pad=True)\n elif justify == \"center\":\n for line in self._lines:\n line.rstrip()\n line.truncate(width, overflow=overflow)\n line.pad_left((width - cell_len(line.plain)) // 2)\n line.pad_right(width - cell_len(line.plain))\n elif justify == \"right\":\n for line in self._lines:\n line.rstrip()\n line.truncate(width, overflow=overflow)\n line.pad_left(width - cell_len(line.plain))\n elif justify == \"full\":\n for line_index, line in enumerate(self._lines):\n if line_index == len(self._lines) - 1:\n break\n words = line.split(\" \")\n words_size = sum(cell_len(word.plain) for word in words)\n num_spaces = len(words) - 1\n spaces = [1 for _ in range(num_spaces)]\n index = 0\n if spaces:\n while words_size + num_spaces < width:\n spaces[len(spaces) - index - 1] += 1\n num_spaces += 1\n index = (index + 1) % len(spaces)\n tokens: List[Text] = []\n for index, (word, next_word) in enumerate(\n zip_longest(words, words[1:])\n ):\n tokens.append(word)\n if index < len(spaces):\n style = word.get_style_at_offset(console, -1)\n next_style = next_word.get_style_at_offset(console, 0)\n space_style = style if style == next_style else line.style\n tokens.append(Text(\" \" * spaces[index], style=space_style))\n self[line_index] = Text(\"\").join(tokens)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def _get_project(self, name):\n result = {}\n for locator in self.locators:\n d = locator.get_project(name)\n if d:\n if self.merge:\n files = result.get('urls', {})\n digests = result.get('digests', {})\n # next line could overwrite result['urls'], result['digests']\n result.update(d)\n df = result.get('urls')\n if files and df:\n for k, v in files.items():\n if k in df:\n df[k] |= v\n else:\n df[k] = v\n dd = result.get('digests')\n if digests and dd:\n dd.update(digests)\n else:\n # See issue #18. If any dists are found and we're looking\n # for specific constraints, we only return something if\n # a match is found. For example, if a DirectoryLocator\n # returns just foo (1.0) while we're looking for\n # foo (>= 2.0), we'll pretend there was nothing there so\n # that subsequent locators can be queried. Otherwise we\n # would just return foo (1.0) which would then lead to a\n # failure to find foo (>= 2.0), because other locators\n # weren't searched. Note that this only matters when\n # merge=False.\n if self.matcher is None:\n found = True\n else:\n found = False\n for k in d:\n if self.matcher.match(k):\n found = True\n break\n if found:\n result = d\n break\n return result", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def update(self, modifier, dest_dir=None, **kwargs):\n \"\"\"\n Update the contents of a wheel in a generic way. The modifier should\n be a callable which expects a dictionary argument: its keys are\n archive-entry paths, and its values are absolute filesystem paths\n where the contents the corresponding archive entries can be found. The\n modifier is free to change the contents of the files pointed to, add\n new entries and remove entries, before returning. This method will\n extract the entire contents of the wheel to a temporary location, call\n the modifier, and then use the passed (and possibly updated)\n dictionary to write a new wheel. If ``dest_dir`` is specified, the new\n wheel is written there -- otherwise, the original wheel is overwritten.\n\n The modifier should return True if it updated the wheel, else False.\n This method returns the same value the modifier returns.\n \"\"\"\n\n def get_version(path_map, info_dir):\n version = path = None\n key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)\n if key not in path_map:\n key = '%s/PKG-INFO' % info_dir\n if key in path_map:\n path = path_map[key]\n version = Metadata(path=path).version\n return version, path\n\n def update_version(version, path):\n updated = None\n try:\n NormalizedVersion(version)\n i = version.find('-')\n if i < 0:\n updated = '%s+1' % version\n else:\n parts = [int(s) for s in version[i + 1:].split('.')]\n parts[-1] += 1\n updated = '%s+%s' % (version[:i], '.'.join(\n str(i) for i in parts))\n except UnsupportedVersionError:\n logger.debug(\n 'Cannot update non-compliant (PEP-440) '\n 'version %r', version)\n if updated:\n md = Metadata(path=path)\n md.version = updated\n legacy = path.endswith(LEGACY_METADATA_FILENAME)\n md.write(path=path, legacy=legacy)\n logger.debug('Version updated from %r to %r', version, updated)\n\n pathname = os.path.join(self.dirname, self.filename)\n name_ver = '%s-%s' % (self.name, self.version)\n info_dir = '%s.dist-info' % name_ver\n record_name = posixpath.join(info_dir, 'RECORD')\n with tempdir() as workdir:\n with ZipFile(pathname, 'r') as zf:\n path_map = {}\n for zinfo in zf.infolist():\n arcname = zinfo.filename\n if isinstance(arcname, text_type):\n u_arcname = arcname\n else:\n u_arcname = arcname.decode('utf-8')\n if u_arcname == record_name:\n continue\n if '..' in u_arcname:\n raise DistlibException('invalid entry in '\n 'wheel: %r' % u_arcname)\n zf.extract(zinfo, workdir)\n path = os.path.join(workdir, convert_path(u_arcname))\n path_map[u_arcname] = path\n\n # Remember the version.\n original_version, _ = get_version(path_map, info_dir)\n # Files extracted. Call the modifier.\n modified = modifier(path_map, **kwargs)\n if modified:\n # Something changed - need to build a new wheel.\n current_version, path = get_version(path_map, info_dir)\n if current_version and (current_version == original_version):\n # Add or update local version to signify changes.\n update_version(current_version, path)\n # Decide where the new wheel goes.\n if dest_dir is None:\n fd, newpath = tempfile.mkstemp(suffix='.whl',\n prefix='wheel-update-',\n dir=workdir)\n os.close(fd)\n else:\n if not os.path.isdir(dest_dir):\n raise DistlibException('Not a directory: %r' %\n dest_dir)\n newpath = os.path.join(dest_dir, self.filename)\n archive_paths = list(path_map.items())\n distinfo = os.path.join(workdir, info_dir)\n info = distinfo, info_dir\n self.write_records(info, workdir, archive_paths)\n self.build_zip(newpath, archive_paths)\n if dest_dir is None:\n shutil.copyfile(newpath, pathname)\n return modified", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def visit_callable_type(\n self, t: CallableType, nested: bool = True, namespace: str = \"\"\n ) -> Type:\n # Every Callable can bind its own type variables, if they're not in the outer scope\n # TODO: attach namespace for nested free type variables (these appear in return type only).\n with self.tvar_scope_frame(namespace=namespace):\n unpacked_kwargs = t.unpack_kwargs\n if self.defining_alias:\n variables = t.variables\n else:\n variables, _ = self.bind_function_type_variables(t, t)\n type_guard = self.anal_type_guard(t.ret_type)\n type_is = self.anal_type_is(t.ret_type)\n arg_kinds = t.arg_kinds\n if len(arg_kinds) >= 2 and arg_kinds[-2] == ARG_STAR and arg_kinds[-1] == ARG_STAR2:\n arg_types = self.anal_array(t.arg_types[:-2], nested=nested) + [\n self.anal_star_arg_type(t.arg_types[-2], ARG_STAR, nested=nested),\n self.anal_star_arg_type(t.arg_types[-1], ARG_STAR2, nested=nested),\n ]\n # If nested is True, it means we are analyzing a Callable[...] type, rather\n # than a function definition type. We need to \"unpack\" ** TypedDict annotation\n # here (for function definitions it is done in semanal).\n if nested and isinstance(arg_types[-1], UnpackType):\n # TODO: it would be better to avoid this get_proper_type() call.\n unpacked = get_proper_type(arg_types[-1].type)\n if isinstance(unpacked, TypedDictType):\n arg_types[-1] = unpacked\n unpacked_kwargs = True\n arg_types = self.check_unpacks_in_list(arg_types)\n else:\n star_index = None\n if ARG_STAR in arg_kinds:\n star_index = arg_kinds.index(ARG_STAR)\n star2_index = None\n if ARG_STAR2 in arg_kinds:\n star2_index = arg_kinds.index(ARG_STAR2)\n arg_types = []\n for i, ut in enumerate(t.arg_types):\n at = self.anal_type(\n ut, nested=nested, allow_unpack=i in (star_index, star2_index)\n )\n if nested and isinstance(at, UnpackType) and i == star_index:\n # TODO: it would be better to avoid this get_proper_type() call.\n p_at = get_proper_type(at.type)\n if isinstance(p_at, TypedDictType) and not at.from_star_syntax:\n # Automatically detect Unpack[Foo] in Callable as backwards\n # compatible syntax for **Foo, if Foo is a TypedDict.\n at = p_at\n arg_kinds[i] = ARG_STAR2\n unpacked_kwargs = True\n arg_types.append(at)\n if nested:\n arg_types = self.check_unpacks_in_list(arg_types)\n # If there were multiple (invalid) unpacks, the arg types list will become shorter,\n # we need to trim the kinds/names as well to avoid crashes.\n arg_kinds = t.arg_kinds[: len(arg_types)]\n arg_names = t.arg_names[: len(arg_types)]\n\n ret = t.copy_modified(\n arg_types=arg_types,\n arg_kinds=arg_kinds,\n arg_names=arg_names,\n ret_type=self.anal_type(t.ret_type, nested=nested),\n # If the fallback isn't filled in yet,\n # its type will be the falsey FakeInfo\n fallback=(t.fallback if t.fallback.type else self.named_type(\"builtins.function\")),\n variables=self.anal_var_defs(variables),\n type_guard=type_guard,\n type_is=type_is,\n unpack_kwargs=unpacked_kwargs,\n )\n return ret", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def transitive_closure(\n tvars: list[TypeVarId], constraints: list[Constraint]\n) -> tuple[Graph, Bounds, Bounds]:\n \"\"\"Find transitive closure for given constraints on type variables.\n\n Transitive closure gives maximal set of lower/upper bounds for each type variable,\n such that we cannot deduce any further bounds by chaining other existing bounds.\n\n The transitive closure is represented by:\n * A set of lower and upper bounds for each type variable, where only constant and\n non-linear terms are included in the bounds.\n * A graph of linear constraints between type variables (represented as a set of pairs)\n Such separation simplifies reasoning, and allows an efficient and simple incremental\n transitive closure algorithm that we use here.\n\n For example if we have initial constraints [T <: S, S <: U, U <: int], the transitive\n closure is given by:\n * {} <: T <: {int}\n * {} <: S <: {int}\n * {} <: U <: {int}\n * {T <: S, S <: U, T <: U}\n \"\"\"\n uppers: Bounds = defaultdict(set)\n lowers: Bounds = defaultdict(set)\n graph: Graph = {(tv, tv) for tv in tvars}\n\n remaining = set(constraints)\n while remaining:\n c = remaining.pop()\n # Note that ParamSpec constraint P <: Q may be considered linear only if Q has no prefix,\n # for cases like P <: Concatenate[T, Q] we should consider this non-linear and put {P} and\n # {T, Q} into separate SCCs. Similarly, Ts <: Tuple[*Us] considered linear, while\n # Ts <: Tuple[*Us, U] is non-linear.\n is_linear, target_id = find_linear(c)\n if is_linear and target_id in tvars:\n assert target_id is not None\n if c.op == SUBTYPE_OF:\n lower, upper = c.type_var, target_id\n else:\n lower, upper = target_id, c.type_var\n if (lower, upper) in graph:\n continue\n graph |= {\n (l, u) for l in tvars for u in tvars if (l, lower) in graph and (upper, u) in graph\n }\n for u in tvars:\n if (upper, u) in graph:\n lowers[u] |= lowers[lower]\n for l in tvars:\n if (l, lower) in graph:\n uppers[l] |= uppers[upper]\n for lt in lowers[lower]:\n for ut in uppers[upper]:\n add_secondary_constraints(remaining, lt, ut)\n elif c.op == SUBTYPE_OF:\n if c.target in uppers[c.type_var]:\n continue\n for l in tvars:\n if (l, c.type_var) in graph:\n uppers[l].add(c.target)\n for lt in lowers[c.type_var]:\n add_secondary_constraints(remaining, lt, c.target)\n else:\n assert c.op == SUPERTYPE_OF\n if c.target in lowers[c.type_var]:\n continue\n for u in tvars:\n if (c.type_var, u) in graph:\n lowers[u].add(c.target)\n for ut in uppers[c.type_var]:\n add_secondary_constraints(remaining, c.target, ut)\n return graph, lowers, uppers", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def send(\n self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n ):\n \"\"\"Sends PreparedRequest object. Returns Response object.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param stream: (optional) Whether to stream the request content.\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) <timeouts>` tuple.\n :type timeout: float or tuple or urllib3 Timeout object\n :param verify: (optional) Either a boolean, in which case it controls whether\n we verify the server's TLS certificate, or a string, in which case it\n must be a path to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary to apply to the request.\n :rtype: requests.Response\n \"\"\"\n\n try:\n conn = self.get_connection_with_tls_context(\n request, verify, proxies=proxies, cert=cert\n )\n except LocationValueError as e:\n raise InvalidURL(e, request=request)\n\n self.cert_verify(conn, request.url, verify, cert)\n url = self.request_url(request, proxies)\n self.add_headers(\n request,\n stream=stream,\n timeout=timeout,\n verify=verify,\n cert=cert,\n proxies=proxies,\n )\n\n chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n if isinstance(timeout, tuple):\n try:\n connect, read = timeout\n timeout = TimeoutSauce(connect=connect, read=read)\n except ValueError:\n raise ValueError(\n f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n f\"or a single float to set both timeouts to the same value.\"\n )\n elif isinstance(timeout, TimeoutSauce):\n pass\n else:\n timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n try:\n resp = conn.urlopen(\n method=request.method,\n url=url,\n body=request.body,\n headers=request.headers,\n redirect=False,\n assert_same_host=False,\n preload_content=False,\n decode_content=False,\n retries=self.max_retries,\n timeout=timeout,\n chunked=chunked,\n )\n\n except (ProtocolError, OSError) as err:\n raise ConnectionError(err, request=request)\n\n except MaxRetryError as e:\n if isinstance(e.reason, ConnectTimeoutError):\n # TODO: Remove this in 3.0.0: see #2811\n if not isinstance(e.reason, NewConnectionError):\n raise ConnectTimeout(e, request=request)\n\n if isinstance(e.reason, ResponseError):\n raise RetryError(e, request=request)\n\n if isinstance(e.reason, _ProxyError):\n raise ProxyError(e, request=request)\n\n if isinstance(e.reason, _SSLError):\n # This branch is for urllib3 v1.22 and later.\n raise SSLError(e, request=request)\n\n raise ConnectionError(e, request=request)\n\n except ClosedPoolError as e:\n raise ConnectionError(e, request=request)\n\n except _ProxyError as e:\n raise ProxyError(e)\n\n except (_SSLError, _HTTPError) as e:\n if isinstance(e, _SSLError):\n # This branch is for urllib3 versions earlier than v1.22\n raise SSLError(e, request=request)\n elif isinstance(e, ReadTimeoutError):\n raise ReadTimeout(e, request=request)\n elif isinstance(e, _InvalidHeader):\n raise InvalidHeader(e, request=request)\n else:\n raise\n\n return self.build_response(request, resp)", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def readTemplate(self, templateName):\n\t\tdef parseTemplateModes(template):\n\t\t\tmodes = {}\n\t\t\tmodesItems = {}\n\t\t\tfor mode in template.findall(\"mode\"):\n\t\t\t\titems = []\n\t\t\t\tmodeName = mode.get(\"name\")\n\t\t\t\titemWidth = int(mode.get(\"itemWidth\", self.itemWidth)) # Override from mode.\n\t\t\t\titemHeight = int(mode.get(\"itemHeight\", self.itemHeight)) # Override from mode.\n\t\t\t\tattibutes = {\n\t\t\t\t\t\"itemWidth\": itemWidth,\n\t\t\t\t\t\"itemHeight\": itemHeight\n\t\t\t\t}\n\t\t\t\tfor name, value in mode.items():\n\t\t\t\t\tattibutes[name] = value\n\t\t\t\tmodes[modeName] = attibutes\n\t\t\t\tcontext = SkinContextStack()\n\t\t\t\tcontext.x = 0\n\t\t\t\tcontext.y = 0\n\t\t\t\tcontext.w = itemWidth\n\t\t\t\tcontext.h = itemHeight\n\t\t\t\tcontext.scale = self.scale # Set scale from the widget.\n\t\t\t\tcontext = SkinContext(context, \"0,0\", f\"{itemWidth},{itemHeight}\")\n\t\t\t\tfor element in list(mode):\n\t\t\t\t\tprocessor = self.processors.get(element.tag, self.processNone)\n\t\t\t\t\tnewItems = processor(element, context)\n\t\t\t\t\tif newItems:\n\t\t\t\t\t\titems += newItems\n\t\t\t\tnewItems = []\n\t\t\t\tfor item in items:\n\t\t\t\t\titemsAttibutes = {}\n\t\t\t\t\tfor name, value in item.items():\n\t\t\t\t\t\titemsAttibutes[name] = int(value) if name == \"font\" else value\n\t\t\t\t\tnewItems.append(itemsAttibutes)\n\t\t\t\tmodesItems[modeName] = newItems\n\t\t\t\tmodes[modeName] = attibutes\n\t\t\t\tif self.debug:\n\t\t\t\t\tprint(f\"[MultiContentTemplateParser] DEBUG ITEMS {modeName}\")\n\t\t\t\t\tprint(modesItems[modeName])\n\t\t\treturn modes, modesItems\n\n\t\tself.template = {}\n\t\tself.template[\"modes\"] = {}\n\t\tself.template[\"fonts\"] = []\n\t\ttry:\n\t\t\tfor template in self.dom.findall(\"template\"):\n\t\t\t\ttemplateStyleName = template.get(\"name\", \"Default\")\n\t\t\t\tself.itemWidth = int(template.get(\"itemWidth\", self.itemWidth))\n\t\t\t\tself.itemHeight = int(template.get(\"itemHeight\", self.itemHeight))\n\t\t\t\tif templateStyleName == templateName:\n\t\t\t\t\ttemplateModes, modesItems = parseTemplateModes(template)\n\t\t\t\t\tfor index, font in enumerate([x.strip() for x in template.get(\"fonts\", \"\").split(\",\")]):\n\t\t\t\t\t\tself.template[\"fonts\"].append(parseFont(font, self.scale))\n\t\t\t\t\tfor modeName, modeProperties in templateModes.items():\n\t\t\t\t\t\tmodeItemWidth = modeProperties.get(\"itemWidth\")\n\t\t\t\t\t\tmodeItemHeight = modeProperties.get(\"itemHeight\")\n\t\t\t\t\t\tmodeData = []\n\t\t\t\t\t\tfor item in modesItems[modeName]:\n\t\t\t\t\t\t\tindex = item.get(\"index\", \"-1\")\n\t\t\t\t\t\t\tif index.isdigit():\n\t\t\t\t\t\t\t\tindex = int(index)\n\t\t\t\t\t\t\telif self.indexNames:\n\t\t\t\t\t\t\t\tindex = self.indexNames.get(index, -1)\n\t\t\t\t\t\t\t\tif index < 0 or index >= len(self.indexNames):\n\t\t\t\t\t\t\t\t\tprint(f\"[XmlMultiContent] Error: Index name must resolve to a number between 0 and {len(self.indexNames) - 1} inclusive!\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tindex = -1\n\t\t\t\t\t\t\t\tprint(\"[XmlMultiContent] Error: Index must be a list item number!\")\n\t\t\t\t\t\t\tpos = item.get(\"position\")\n\t\t\t\t\t\t\tsize = item.get(\"size\")\n\t\t\t\t\t\t\tbackgroundColor = item.get(\"backgroundColor\")\n\t\t\t\t\t\t\tbackgroundColorSelected = item.get(\"backgroundColorSelected\")\n\t\t\t\t\t\t\tborderColor = item.get(\"borderColor\")\n\t\t\t\t\t\t\tborderWidth = int(item.get(\"borderWidth\", \"0\"))\n\t\t\t\t\t\t\tcornerRadius, cornerEdges = item.get(\"_radius\", (0, 0))\n\t\t\t\t\t\t\tflags = item.get(\"_flags\", 0)\n\t\t\t\t\t\t\tmatch item[\"type\"]:\n\t\t\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t\t\tforegroundColorSelected = item.get(\"foregroundColorSelected\")\n\t\t\t\t\t\t\t\t\tforegroundColor = item.get(\"foregroundColor\")\n\t\t\t\t\t\t\t\t\tfont = int(item.get(\"font\", 0))\n\t\t\t\t\t\t\t\t\tif index == -1:\n\t\t\t\t\t\t\t\t\t\tindex = item.get(\"text\", \"\")\n\t\t\t\t\t\t\t\t\tmodeData.append((eListboxPythonMultiContent.TYPE_TEXT, pos[0], pos[1], size[0], size[1], font or 0, flags, index, foregroundColor, foregroundColorSelected, backgroundColor, backgroundColorSelected, borderWidth, borderColor, cornerRadius, cornerEdges))\n\t\t\t\t\t\t\t\tcase \"pixmap\":\n\t\t\t\t\t\t\t\t\tif index == -1:\n\t\t\t\t\t\t\t\t\t\tindex = item.get(\"pixmap\", \"\")\n\t\t\t\t\t\t\t\t\tpixmapType = item.get(\"pixmapType\", eListboxPythonMultiContent.TYPE_PIXMAP)\n\t\t\t\t\t\t\t\t\tpixmapFlags = item.get(\"pixmapFlags\", 0)\n\t\t\t\t\t\t\t\t\tmodeData.append((pixmapType, pos[0], pos[1], size[0], size[1], self.resolvePixmap(index), backgroundColor, backgroundColorSelected, pixmapFlags, cornerRadius, cornerEdges))\n\t\t\t\t\t\t\t\tcase \"rectangle\":\n\t\t\t\t\t\t\t\t\tgradientDirection, gradientAlpha, gradientStart, gradientEnd, gradientMid, gradientStartSelected, gradientEndSelected, gradientMidSelected = item.get(\"_gradient\", (0, 0, None, None, None, None, None, None))\n\t\t\t\t\t\t\t\t\tif gradientDirection:\n\t\t\t\t\t\t\t\t\t\tif gradientAlpha:\n\t\t\t\t\t\t\t\t\t\t\tmodeData.append((eListboxPythonMultiContent.TYPE_LINEAR_GRADIENT_ALPHABLEND, pos[0], pos[1], size[0], size[1], gradientDirection, gradientStart, gradientMid, gradientEnd, gradientStartSelected, gradientMidSelected, gradientEndSelected, cornerRadius, cornerEdges))\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tmodeData.append((eListboxPythonMultiContent.TYPE_LINEAR_GRADIENT, pos[0], pos[1], size[0], size[1], gradientDirection, gradientStart, gradientMid, gradientEnd, gradientStartSelected, gradientMidSelected, gradientEndSelected, cornerRadius, cornerEdges))\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tmodeData.append((eListboxPythonMultiContent.TYPE_RECT, pos[0], pos[1], size[0], size[1], backgroundColor, backgroundColorSelected, borderWidth, borderColor, cornerRadius, cornerEdges))\n\t\t\t\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\t\t\t\tif index == -1:\n\t\t\t\t\t\t\t\t\t\tindex = None\n\t\t\t\t\t\t\t\t\tforegroundColorSelected = item.get(\"foregroundColorSelected\", None)\n\t\t\t\t\t\t\t\t\tforegroundColor = item.get(\"foregroundColor\", None)\n\t\t\t\t\t\t\t\t\tgradientDirection, gradientAlpha, gradientStart, gradientEnd, gradientMid, gradientStartSelected, gradientEndSelected, gradientMidSelected = item.get(\"_gradient\", (0, 0, None, None, None, None, None, None))\n\t\t\t\t\t\t\t\t\tmodeData.append((eListboxPythonMultiContent.TYPE_PROGRESS, pos[0], pos[1], size[0], size[1], index, borderWidth, foregroundColor, foregroundColorSelected, borderColor, gradientStart, gradientMid, gradientEnd, gradientStartSelected, gradientMidSelected, gradientEndSelected, cornerRadius, cornerEdges))\n\t\t\t\t\t\tself.template[\"modes\"][modeName] = ((modeItemWidth, modeItemHeight), modeData)\n\t\texcept Exception as err:\n\t\t\t# TODO: DEBUG: Remove the following two lines before publication.\n\t\t\timport traceback\n\t\t\ttraceback.print_exc()\n\t\t\tprint(f\"[TemplateParser] Error: Unable to parse XML template! {str(err)})\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def reprocess_nodes(\n manager: BuildManager,\n graph: dict[str, State],\n module_id: str,\n nodeset: set[FineGrainedDeferredNode],\n deps: dict[str, set[str]],\n processed_targets: list[str],\n) -> set[str]:\n \"\"\"Reprocess a set of nodes within a single module.\n\n Return fired triggers.\n \"\"\"\n if module_id not in graph:\n manager.log_fine_grained(\"%s not in graph (blocking errors or deleted?)\" % module_id)\n return set()\n\n file_node = manager.modules[module_id]\n old_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names)\n old_symbols = {name: names.copy() for name, names in old_symbols.items()}\n old_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names)\n\n def key(node: FineGrainedDeferredNode) -> int:\n # Unlike modules which are sorted by name within SCC,\n # nodes within the same module are sorted by line number, because\n # this is how they are processed in normal mode.\n return node.node.line\n\n nodes = sorted(nodeset, key=key)\n\n state = graph[module_id]\n options = state.options\n manager.errors.set_file_ignored_lines(\n file_node.path, file_node.ignored_lines, options.ignore_errors or state.ignore_all\n )\n manager.errors.set_skipped_lines(file_node.path, file_node.skipped_lines)\n\n targets = set()\n for node in nodes:\n target = target_from_node(module_id, node.node)\n if target is not None:\n targets.add(target)\n manager.errors.clear_errors_in_targets(file_node.path, targets)\n\n # If one of the nodes is the module itself, emit any errors that\n # happened before semantic analysis.\n for target in targets:\n if target == module_id:\n for info in graph[module_id].early_errors:\n manager.errors.add_error_info(info)\n\n # Strip semantic analysis information.\n saved_attrs: SavedAttributes = {}\n for deferred in nodes:\n processed_targets.append(deferred.node.fullname)\n strip_target(deferred.node, saved_attrs)\n semantic_analysis_for_targets(graph[module_id], nodes, graph, saved_attrs)\n # Merge symbol tables to preserve identities of AST nodes. The file node will remain\n # the same, but other nodes may have been recreated with different identities, such as\n # NamedTuples defined using assignment statements.\n new_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names)\n for name in old_symbols:\n if name in new_symbols:\n merge_asts(file_node, old_symbols[name], file_node, new_symbols[name])\n\n # Type check.\n checker = graph[module_id].type_checker()\n checker.reset()\n # We seem to need additional passes in fine-grained incremental mode.\n checker.pass_num = 0\n checker.last_pass = 3\n more = checker.check_second_pass(nodes)\n while more:\n more = False\n if graph[module_id].type_checker().check_second_pass():\n more = True\n\n if manager.options.export_types:\n manager.all_types.update(graph[module_id].type_map())\n\n new_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names)\n # Check if any attribute types were changed and need to be propagated further.\n changed = compare_symbol_table_snapshots(\n file_node.fullname, old_symbols_snapshot, new_symbols_snapshot\n )\n new_triggered = {make_trigger(name) for name in changed}\n\n # Dependencies may have changed.\n update_deps(module_id, nodes, graph, deps, options)\n\n # Report missing imports.\n graph[module_id].verify_dependencies()\n\n graph[module_id].free_state()\n\n return new_triggered", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "@parametrize(\n \"frame_selection_method, method_params\",\n [\n *tuple(product([\"random_uniform\"], [{\"frame_count\"}, {\"frame_share\"}])),\n *tuple(\n product([\"random_per_job\"], [{\"frames_per_job_count\"}, {\"frames_per_job_share\"}])\n ),\n (\"manual\", {}),\n ],\n idgen=lambda **args: \"-\".join([args[\"frame_selection_method\"], *args[\"method_params\"]]),\n )\n @pytest.mark.parametrize(\"task_mode\", [\"annotation\", \"interpolation\"])\n def test_can_create_gt_job_in_a_task(\n self,\n admin_user,\n tasks,\n task_mode: str,\n frame_selection_method: str,\n method_params: Set[str],\n ):\n required_task_size = 15\n\n task = next(\n t\n for t in tasks\n if t[\"mode\"] == task_mode\n if required_task_size <= t[\"size\"]\n if not t[\"validation_mode\"]\n )\n task_id = task[\"id\"]\n\n segment_size = task[\"segment_size\"]\n total_frame_count = task[\"size\"]\n\n job_params = {\n \"task_id\": task_id,\n \"type\": \"ground_truth\",\n \"frame_selection_method\": frame_selection_method,\n }\n\n if \"random\" in frame_selection_method:\n job_params[\"random_seed\"] = 42\n\n if frame_selection_method == \"random_uniform\":\n validation_frames_count = 5\n\n for method_param in method_params:\n if method_param == \"frame_count\":\n job_params[method_param] = validation_frames_count\n elif method_param == \"frame_share\":\n job_params[method_param] = validation_frames_count / total_frame_count\n else:\n assert False\n elif frame_selection_method == \"random_per_job\":\n validation_per_job_count = 2\n validation_frames_count = validation_per_job_count * math.ceil(\n total_frame_count / segment_size\n )\n\n for method_param in method_params:\n if method_param == \"frames_per_job_count\":\n job_params[method_param] = validation_per_job_count\n elif method_param == \"frames_per_job_share\":\n job_params[method_param] = validation_per_job_count / segment_size\n else:\n assert False\n elif frame_selection_method == \"manual\":\n validation_frames_count = 5\n\n rng = np.random.Generator(np.random.MT19937(seed=42))\n job_params[\"frames\"] = rng.choice(\n range(total_frame_count), validation_frames_count, replace=False\n ).tolist()\n else:\n assert False\n\n with make_api_client(admin_user) as api_client:\n (gt_job, _) = api_client.jobs_api.create(job_write_request=job_params)\n\n # GT jobs occupy the whole task frame range\n assert gt_job.start_frame == 0\n assert gt_job.stop_frame + 1 == task[\"size\"]\n assert gt_job.type == \"ground_truth\"\n assert gt_job.task_id == task_id\n\n annotation_job_metas = [\n api_client.jobs_api.retrieve_data_meta(job.id)[0]\n for job in get_paginated_collection(\n api_client.jobs_api.list_endpoint, task_id=task_id, type=\"annotation\"\n )\n ]\n gt_job_metas = [\n api_client.jobs_api.retrieve_data_meta(job.id)[0]\n for job in get_paginated_collection(\n api_client.jobs_api.list_endpoint, task_id=task_id, type=\"ground_truth\"\n )\n ]\n\n assert len(gt_job_metas) == 1\n\n frame_step = parse_frame_step(gt_job_metas[0].frame_filter)\n validation_frames = [\n abs_frame_id\n for abs_frame_id in range(\n gt_job_metas[0].start_frame,\n gt_job_metas[0].stop_frame + 1,\n frame_step,\n )\n if abs_frame_id in gt_job_metas[0].included_frames\n ]\n\n if frame_selection_method == \"random_per_job\":\n # each job must have the specified number of validation frames\n for job_meta in annotation_job_metas:\n assert (\n len(\n set(\n range(job_meta.start_frame, job_meta.stop_frame + 1, frame_step)\n ).intersection(validation_frames)\n )\n == validation_per_job_count\n )\n else:\n assert len(validation_frames) == validation_frames_count", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def _check_selected_columns_match_dataset(\n builder: ErrorsQueryBuilder | DiscoverQueryBuilder,\n dataset: Dataset,\n):\n for select_col in builder.columns:\n if isinstance(select_col, Column):\n if _check_column_matches_dataset(select_col, dataset):\n return True\n\n elif isinstance(select_col, AliasedExpression):\n if _check_aliased_expression_matches_dataset(select_col, dataset):\n return True\n\n elif isinstance(select_col, Function) or isinstance(select_col, CurriedFunction):\n # The parameter check is a stronger check if applicable, so we should keep that first\n if _check_function_parameter_matches_dataset(select_col, dataset):\n return True\n if _check_function_alias_matches_dataset(select_col, dataset):\n return True\n\n return False", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def llcp_worker(llc, try_alt):\n global handover\n print(\"Start of llcp_worker()\")\n if try_alt:\n summary(\"Starting handover client (try_alt)\")\n dpp_handover_client(handover, alt=True)\n summary(\"Exiting llcp_worker thread (try_alt)\")\n return\n global init_on_touch\n if init_on_touch:\n summary(\"Starting handover client (init_on_touch)\")\n dpp_handover_client(handover)\n summary(\"Exiting llcp_worker thread (init_on_touch)\")\n return\n\n global no_input\n if no_input:\n summary(\"Wait for handover to complete\")\n else:\n print(\"Wait for handover to complete - press 'i' to initiate\")\n while not handover.wait_connection and handover.srv.sent_carrier is None:\n if handover.try_own:\n handover.try_own = False\n summary(\"Try to initiate another handover with own parameters\")\n handover.my_crn_ready = False\n handover.my_crn = None\n handover.peer_crn = None\n handover.hs_sent = False\n dpp_handover_client(handover, alt=True)\n summary(\"Exiting llcp_worker thread (retry with own parameters)\")\n return\n if handover.srv.ho_server_processing:\n time.sleep(0.025)\n elif no_input:\n time.sleep(0.5)\n else:\n res = getch()\n if res != 'i':\n continue\n clear_raw_mode()\n summary(\"Starting handover client\")\n dpp_handover_client(handover)\n summary(\"Exiting llcp_worker thread (manual init)\")\n return\n\n global in_raw_mode\n was_in_raw_mode = in_raw_mode\n clear_raw_mode()\n if was_in_raw_mode:\n print(\"\\r\")\n summary(\"Exiting llcp_worker thread\")", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "def document_lexers(self):\n from pip._vendor.pygments.lexers._mapping import LEXERS\n out = []\n modules = {}\n moduledocstrings = {}\n for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]):\n module = data[0]\n mod = __import__(module, None, None, [classname])\n self.filenames.add(mod.__file__)\n cls = getattr(mod, classname)\n if not cls.__doc__:\n print(\"Warning: %s does not have a docstring.\" % classname)\n docstring = cls.__doc__\n if isinstance(docstring, bytes):\n docstring = docstring.decode('utf8')\n modules.setdefault(module, []).append((\n classname,\n ', '.join(data[2]) or 'None',\n ', '.join(data[3]).replace('*', '\\\\*').replace('_', '\\\\') or 'None',\n ', '.join(data[4]) or 'None',\n docstring))\n if module not in moduledocstrings:\n moddoc = mod.__doc__\n if isinstance(moddoc, bytes):\n moddoc = moddoc.decode('utf8')\n moduledocstrings[module] = moddoc\n\n for module, lexers in sorted(modules.items(), key=lambda x: x[0]):\n if moduledocstrings[module] is None:\n raise Exception(\"Missing docstring for %s\" % (module,))\n heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.')\n out.append(MODULEDOC % (module, heading, '-'*len(heading)))\n for data in lexers:\n out.append(LEXERDOC % data)\n\n return ''.join(out)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def visit_tuple_type(self, left: TupleType) -> bool:\n right = self.right\n if isinstance(right, Instance):\n if is_named_instance(right, \"typing.Sized\"):\n return True\n elif is_named_instance(right, TUPLE_LIKE_INSTANCE_NAMES):\n if right.args:\n iter_type = right.args[0]\n else:\n if self.proper_subtype:\n return False\n iter_type = AnyType(TypeOfAny.special_form)\n if is_named_instance(right, \"builtins.tuple\") and isinstance(\n get_proper_type(iter_type), AnyType\n ):\n # TODO: We shouldn't need this special case. This is currently needed\n # for isinstance(x, tuple), though it's unclear why.\n return True\n for li in left.items:\n if isinstance(li, UnpackType):\n unpack = get_proper_type(li.type)\n if isinstance(unpack, TypeVarTupleType):\n unpack = get_proper_type(unpack.upper_bound)\n assert (\n isinstance(unpack, Instance)\n and unpack.type.fullname == \"builtins.tuple\"\n )\n li = unpack.args[0]\n if not self._is_subtype(li, iter_type):\n return False\n return True\n elif self._is_subtype(left.partial_fallback, right) and self._is_subtype(\n mypy.typeops.tuple_fallback(left), right\n ):\n return True\n return False\n elif isinstance(right, TupleType):\n # If right has a variadic unpack this needs special handling. If there is a TypeVarTuple\n # unpack, item count must coincide. If the left has variadic unpack but right\n # doesn't have one, we will fall through to False down the line.\n if self.variadic_tuple_subtype(left, right):\n return True\n if len(left.items) != len(right.items):\n return False\n if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)):\n return False\n if is_named_instance(right.partial_fallback, \"builtins.tuple\"):\n # No need to verify fallback. This is useful since the calculated fallback\n # may be inconsistent due to how we calculate joins between unions vs.\n # non-unions. For example, join(int, str) == object, whereas\n # join(Union[int, C], Union[str, C]) == Union[int, str, C].\n return True\n if is_named_instance(left.partial_fallback, \"builtins.tuple\"):\n # Again, no need to verify. At this point we know the right fallback\n # is a subclass of tuple, so if left is plain tuple, it cannot be a subtype.\n return False\n # At this point we know both fallbacks are non-tuple.\n return self._is_subtype(left.partial_fallback, right.partial_fallback)\n else:\n return False", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _verify_peercerts_impl(\n ssl_context: ssl.SSLContext,\n cert_chain: list[bytes],\n server_hostname: str | None = None,\n) -> None:\n certs = None\n policies = None\n trust = None\n cf_error = None\n try:\n if server_hostname is not None:\n cf_str_hostname = None\n try:\n cf_str_hostname = _bytes_to_cf_string(server_hostname.encode(\"ascii\"))\n ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)\n finally:\n if cf_str_hostname:\n CoreFoundation.CFRelease(cf_str_hostname)\n else:\n ssl_policy = Security.SecPolicyCreateSSL(True, None)\n\n policies = ssl_policy\n if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n # Add explicit policy requiring positive revocation checks\n policies = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n CoreFoundation.CFArrayAppendValue(policies, ssl_policy)\n CoreFoundation.CFRelease(ssl_policy)\n revocation_policy = Security.SecPolicyCreateRevocation(\n kSecRevocationUseAnyAvailableMethod\n | kSecRevocationRequirePositiveResponse\n )\n CoreFoundation.CFArrayAppendValue(policies, revocation_policy)\n CoreFoundation.CFRelease(revocation_policy)\n elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n raise NotImplementedError(\"VERIFY_CRL_CHECK_LEAF not implemented for macOS\")\n\n certs = None\n try:\n certs = _der_certs_to_cf_cert_array(cert_chain)\n\n # Now that we have certificates loaded and a SecPolicy\n # we can finally create a SecTrust object!\n trust = Security.SecTrustRef()\n Security.SecTrustCreateWithCertificates(\n certs, policies, ctypes.byref(trust)\n )\n\n finally:\n # The certs are now being held by SecTrust so we can\n # release our handles for the array.\n if certs:\n CoreFoundation.CFRelease(certs)\n\n # If there are additional trust anchors to load we need to transform\n # the list of DER-encoded certificates into a CFArray. Otherwise\n # pass 'None' to signal that we only want system / fetched certificates.\n ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(\n binary_form=True\n )\n if ctx_ca_certs_der:\n ctx_ca_certs = None\n try:\n ctx_ca_certs = _der_certs_to_cf_cert_array(cert_chain)\n Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)\n finally:\n if ctx_ca_certs:\n CoreFoundation.CFRelease(ctx_ca_certs)\n else:\n Security.SecTrustSetAnchorCertificates(trust, None)\n\n cf_error = CoreFoundation.CFErrorRef()\n sec_trust_eval_result = Security.SecTrustEvaluateWithError(\n trust, ctypes.byref(cf_error)\n )\n # sec_trust_eval_result is a bool (0 or 1)\n # where 1 means that the certs are trusted.\n if sec_trust_eval_result == 1:\n is_trusted = True\n elif sec_trust_eval_result == 0:\n is_trusted = False\n else:\n raise ssl.SSLError(\n f\"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}\"\n )\n\n cf_error_code = 0\n if not is_trusted:\n cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)\n\n # If the error is a known failure that we're\n # explicitly okay with from SSLContext configuration\n # we can set is_trusted accordingly.\n if ssl_context.verify_mode != ssl.CERT_REQUIRED and (\n cf_error_code == CFConst.errSecNotTrusted\n or cf_error_code == CFConst.errSecCertificateExpired\n ):\n is_trusted = True\n elif (\n not ssl_context.check_hostname\n and cf_error_code == CFConst.errSecHostNameMismatch\n ):\n is_trusted = True\n\n # If we're still not trusted then we start to\n # construct and raise the SSLCertVerificationError.\n if not is_trusted:\n cf_error_string_ref = None\n try:\n cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)\n\n # Can this ever return 'None' if there's a CFError?\n cf_error_message = (\n _cf_string_ref_to_str(cf_error_string_ref)\n or \"Certificate verification failed\"\n )\n\n # TODO: Not sure if we need the SecTrustResultType for anything?\n # We only care whether or not it's a success or failure for now.\n sec_trust_result_type = Security.SecTrustResultType()\n Security.SecTrustGetTrustResult(\n trust, ctypes.byref(sec_trust_result_type)\n )\n\n err = ssl.SSLCertVerificationError(cf_error_message)\n err.verify_message = cf_error_message\n err.verify_code = cf_error_code\n raise err\n finally:\n if cf_error_string_ref:\n CoreFoundation.CFRelease(cf_error_string_ref)\n\n finally:\n if policies:\n CoreFoundation.CFRelease(policies)\n if trust:\n CoreFoundation.CFRelease(trust)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _get_calculated_grouping_variants_for_event(\n event: Event, context: GroupingContext\n) -> dict[str, GroupingComponent]:\n winning_strategy: str | None = None\n precedence_hint: str | None = None\n per_variant_components: dict[str, list[GroupingComponent]] = {}\n\n for strategy in context.config.iter_strategies():\n # Defined in src/sentry/grouping/strategies/base.py\n rv = strategy.get_grouping_component_variants(event, context=context)\n for variant, component in rv.items():\n per_variant_components.setdefault(variant, []).append(component)\n\n if winning_strategy is None:\n if component.contributes:\n winning_strategy = strategy.name\n variants_hint = \"/\".join(sorted(k for k, v in rv.items() if v.contributes))\n precedence_hint = \"{} take{} precedence\".format(\n (\n f\"{strategy.name} of {variants_hint}\"\n if variant != \"default\"\n else strategy.name\n ),\n \"\" if strategy.name.endswith(\"s\") else \"s\",\n )\n elif component.contributes and winning_strategy != strategy.name:\n component.update(contributes=False, hint=precedence_hint)\n\n rv = {}\n for variant, components in per_variant_components.items():\n component = GroupingComponent(id=variant, values=components)\n if not component.contributes and precedence_hint:\n component.update(hint=precedence_hint)\n rv[variant] = component\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def main():\n args = parse_args()\n\n if args.zephyr_base:\n os.environ['ZEPHYR_BASE'] = args.zephyr_base\n\n print(\"Parsing \" + args.kconfig_file)\n kconf = Kconfig(args.kconfig_file, warn_to_stderr=False,\n suppress_traceback=True)\n\n if args.handwritten_input_configs:\n # Warn for assignments to undefined symbols, but only for handwritten\n # fragments, to avoid warnings-turned-errors when using an old\n # configuration file together with updated Kconfig files\n kconf.warn_assign_undef = True\n\n # prj.conf may override settings from the board configuration, so\n # disable warnings about symbols being assigned more than once\n kconf.warn_assign_override = False\n kconf.warn_assign_redun = False\n\n # Load configuration files\n print(kconf.load_config(args.configs_in[0]))\n for config in args.configs_in[1:]:\n # replace=False creates a merged configuration\n print(kconf.load_config(config, replace=False))\n\n if args.handwritten_input_configs:\n # Check that there are no assignments to promptless symbols, which\n # have no effect.\n #\n # This only makes sense when loading handwritten fragments and not when\n # loading zephyr/.config, because zephyr/.config is configuration\n # output and also assigns promptless symbols.\n check_no_promptless_assign(kconf)\n\n # Print warnings for symbols that didn't get the assigned value. Only\n # do this for handwritten input too, to avoid likely unhelpful warnings\n # when using an old configuration and updating Kconfig files.\n check_assigned_sym_values(kconf)\n check_assigned_choice_values(kconf)\n\n # Hack: Force all symbols to be evaluated, to catch warnings generated\n # during evaluation. Wait till the end to write the actual output files, so\n # that we don't generate any output if there are warnings-turned-errors.\n #\n # Kconfiglib caches calculated symbol values internally, so this is still\n # fast.\n kconf.write_config(os.devnull)\n\n if kconf.warnings:\n # Put a blank line between warnings to make them easier to read\n for warning in kconf.warnings:\n print(\"\\n\" + warning, file=sys.stderr)\n\n # Turn all warnings into errors, so that e.g. assignments to undefined\n # Kconfig symbols become errors.\n #\n # A warning is generated by this script whenever a symbol gets a\n # different value than the one it was assigned. Keep that one as just a\n # warning for now.\n err(\"Aborting due to Kconfig warnings\")\n\n # Write the merged configuration and the C header\n print(kconf.write_config(args.config_out))\n print(kconf.write_autoconf(args.header_out))\n\n # Write the list of parsed Kconfig files to a file\n write_kconfig_filenames(kconf, args.kconfig_list_out)", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]:\n known_directives = {\n # https://tools.ietf.org/html/rfc7234#section-5.2\n \"max-age\": (int, True),\n \"max-stale\": (int, False),\n \"min-fresh\": (int, True),\n \"no-cache\": (None, False),\n \"no-store\": (None, False),\n \"no-transform\": (None, False),\n \"only-if-cached\": (None, False),\n \"must-revalidate\": (None, False),\n \"public\": (None, False),\n \"private\": (None, False),\n \"proxy-revalidate\": (None, False),\n \"s-maxage\": (int, True),\n }\n\n cc_headers = headers.get(\"cache-control\", headers.get(\"Cache-Control\", \"\"))\n\n retval: dict[str, int | None] = {}\n\n for cc_directive in cc_headers.split(\",\"):\n if not cc_directive.strip():\n continue\n\n parts = cc_directive.split(\"=\", 1)\n directive = parts[0].strip()\n\n try:\n typ, required = known_directives[directive]\n except KeyError:\n logger.debug(\"Ignoring unknown cache-control directive: %s\", directive)\n continue\n\n if not typ or not required:\n retval[directive] = None\n if typ:\n try:\n retval[directive] = typ(parts[1].strip())\n except IndexError:\n if required:\n logger.debug(\n \"Missing value for cache-control \" \"directive: %s\",\n directive,\n )\n except ValueError:\n logger.debug(\n \"Invalid value for cache-control directive \" \"%s, must be %s\",\n directive,\n typ.__name__,\n )\n\n return retval", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def main():\n clf = nfc.ContactlessFrontend()\n\n parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for DPP NFC operations')\n parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,\n action='store_const', dest='loglevel',\n help='verbose debug output')\n parser.add_argument('-q', const=logging.WARNING, action='store_const',\n dest='loglevel', help='be quiet')\n parser.add_argument('--only-one', '-1', action='store_true',\n help='run only one operation and exit')\n parser.add_argument('--init-on-touch', '-I', action='store_true',\n help='initiate handover on touch')\n parser.add_argument('--no-wait', action='store_true',\n help='do not wait for tag to be removed before exiting')\n parser.add_argument('--ifname', '-i',\n help='network interface name')\n parser.add_argument('--no-input', '-a', action='store_true',\n help='do not use stdout input to initiate handover')\n parser.add_argument('--tag-read-only', '-t', action='store_true',\n help='tag read only (do not allow connection handover)')\n parser.add_argument('--handover-only', action='store_true',\n help='connection handover only (do not allow tag read)')\n parser.add_argument('--enrollee', action='store_true',\n help='run as Enrollee-only')\n parser.add_argument('--configurator', action='store_true',\n help='run as Configurator-only')\n parser.add_argument('--config-params', default='',\n help='configurator parameters')\n parser.add_argument('--ctrl', default='/var/run/wpa_supplicant',\n help='wpa_supplicant/hostapd control interface')\n parser.add_argument('--summary',\n help='summary file for writing status updates')\n parser.add_argument('--success',\n help='success file for writing success update')\n parser.add_argument('--device', default='usb', help='NFC device to open')\n parser.add_argument('--chan', default=None, help='channel list')\n parser.add_argument('--altchan', default=None, help='alternative channel list')\n parser.add_argument('--netrole', default=None, help='netrole for Enrollee')\n parser.add_argument('--test-uri', default=None,\n help='test mode: initial URI')\n parser.add_argument('--test-alt-uri', default=None,\n help='test mode: alternative URI')\n parser.add_argument('--test-sel-uri', default=None,\n help='test mode: handover select URI')\n parser.add_argument('--test-crn', default=None,\n help='test mode: hardcoded crn')\n parser.add_argument('command', choices=['write-nfc-uri',\n 'write-nfc-hs'],\n nargs='?')\n args = parser.parse_args()\n summary(args)\n\n global handover\n handover = ConnectionHandover()\n\n global only_one\n only_one = args.only_one\n\n global no_wait\n no_wait = args.no_wait\n\n global chanlist, netrole, test_uri, test_alt_uri, test_sel_uri\n global test_crn\n chanlist = args.chan\n handover.altchanlist = args.altchan\n netrole = args.netrole\n test_uri = args.test_uri\n test_alt_uri = args.test_alt_uri\n test_sel_uri = args.test_sel_uri\n if args.test_crn:\n test_crn = struct.pack('>H', int(args.test_crn))\n else:\n test_crn = None\n\n logging.basicConfig(level=args.loglevel)\n for l in ['nfc.clf.rcs380',\n 'nfc.clf.transport',\n 'nfc.clf.device',\n 'nfc.clf.__init__',\n 'nfc.llcp',\n 'nfc.handover']:\n log = logging.getLogger(l)\n log.setLevel(args.loglevel)\n\n global init_on_touch\n init_on_touch = args.init_on_touch\n\n global enrollee_only\n enrollee_only = args.enrollee\n\n global configurator_only\n configurator_only = args.configurator\n\n global config_params\n config_params = args.config_params\n\n if args.ifname:\n global ifname\n ifname = args.ifname\n summary(\"Selected ifname \" + ifname)\n\n if args.ctrl:\n global wpas_ctrl\n wpas_ctrl = args.ctrl\n\n if args.summary:\n global summary_file\n summary_file = args.summary\n\n if args.success:\n global success_file\n success_file = args.success\n\n if args.no_input:\n global no_input\n no_input = True\n\n clf = nfc.ContactlessFrontend()\n\n try:\n if not clf.open(args.device):\n summary(\"Could not open connection with an NFC device\", color=C_RED)\n raise SystemExit(1)\n\n if args.command == \"write-nfc-uri\":\n write_nfc_uri(clf, wait_remove=not args.no_wait)\n if not operation_success:\n raise SystemExit(1)\n raise SystemExit\n\n if args.command == \"write-nfc-hs\":\n write_nfc_hs(clf, wait_remove=not args.no_wait)\n if not operation_success:\n raise SystemExit(1)\n raise SystemExit\n\n global continue_loop\n while continue_loop:\n global in_raw_mode\n was_in_raw_mode = in_raw_mode\n clear_raw_mode()\n if was_in_raw_mode:\n print(\"\\r\")\n if args.handover_only:\n summary(\"Waiting a peer to be touched\", color=C_MAGENTA)\n elif args.tag_read_only:\n summary(\"Waiting for a tag to be touched\", color=C_BLUE)\n else:\n summary(\"Waiting for a tag or peer to be touched\",\n color=C_GREEN)\n handover.wait_connection = True\n try:\n if args.tag_read_only:\n if not clf.connect(rdwr={'on-connect': rdwr_connected}):\n break\n elif args.handover_only:\n if not clf.connect(llcp={'on-startup': llcp_startup,\n 'on-connect': llcp_connected,\n 'on-release': llcp_release},\n terminate=terminate_loop):\n break\n else:\n if not clf.connect(rdwr={'on-connect': rdwr_connected},\n llcp={'on-startup': llcp_startup,\n 'on-connect': llcp_connected,\n 'on-release': llcp_release},\n terminate=terminate_loop):\n break\n except Exception as e:\n summary(\"clf.connect failed: \" + str(e))\n break\n\n if only_one and handover.connected:\n role = \"selector\" if handover.i_m_selector else \"requestor\"\n summary(\"Connection handover result: I'm the %s\" % role,\n color=C_YELLOW)\n if handover.peer_uri:\n summary(\"Peer URI: \" + handover.peer_uri, color=C_YELLOW)\n if handover.my_uri:\n summary(\"My URI: \" + handover.my_uri, color=C_YELLOW)\n if not (handover.peer_uri and handover.my_uri):\n summary(\"Negotiated connection handover failed\",\n color=C_YELLOW)\n break\n\n except KeyboardInterrupt:\n raise SystemExit\n finally:\n clf.close()\n\n raise SystemExit", "smellKey": "S3776", "smellId": null, "repo": "swadhinsekhar_foss-sonarqube-sz", "language": "python"} {"function": "@action(methods=[\"get\"], detail=True)\n def object_candidate(self, request, **kwargs): # noqa: ARG002\n role = self.get_object()\n if role.type != RoleTypes.ROLE:\n return Response({\"cluster\": [], \"provider\": [], \"service\": [], \"host\": []})\n\n clusters = []\n providers = []\n services = []\n hosts = []\n\n if RBACObjectType.CLUSTER.value in role.parametrized_by_type:\n for cluster in Cluster.objects.all():\n clusters.append(\n {\n \"name\": cluster.display_name,\n \"type\": ObjectType.CLUSTER,\n \"id\": cluster.id,\n },\n )\n\n if RBACObjectType.PROVIDER.value in role.parametrized_by_type:\n for provider in HostProvider.objects.all():\n providers.append(\n {\n \"name\": provider.display_name,\n \"type\": ObjectType.PROVIDER,\n \"id\": provider.id,\n },\n )\n\n if RBACObjectType.HOST.value in role.parametrized_by_type:\n for host in Host.objects.all():\n hosts.append(\n {\n \"name\": host.display_name,\n \"type\": ObjectType.HOST,\n \"id\": host.id,\n },\n )\n\n if (\n RBACObjectType.SERVICE.value in role.parametrized_by_type\n or RBACObjectType.COMPONENT.value in role.parametrized_by_type\n ):\n _services = defaultdict(list)\n for service in ClusterObject.objects.all():\n _services[service.display_name].append(\n {\n \"name\": service.cluster.display_name,\n \"type\": \"service\",\n \"id\": service.id,\n },\n )\n for service_name, clusters_info in _services.items():\n services.append(\n {\n \"name\": service_name,\n \"clusters\": sorted(clusters_info, key=lambda x: x[\"name\"]),\n },\n )\n\n return Response(\n {\n \"cluster\": sorted(clusters, key=lambda x: x[\"name\"]),\n \"provider\": sorted(providers, key=lambda x: x[\"name\"]),\n \"service\": sorted(services, key=lambda x: x[\"name\"]),\n \"host\": sorted(hosts, key=lambda x: x[\"name\"]),\n },\n )", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def _found_dep_loop(loop, cur):\n # Called \"on the way back\" when we know we have a loop\n\n # Is the symbol/choice 'cur' where the loop started?\n if cur is not loop[0]:\n # Nope, it's just a part of the loop\n return loop + (cur,)\n\n # Yep, we have the entire loop. Throw an exception that shows it.\n\n msg = \"\\nDependency loop\\n\" \\\n \"===============\\n\\n\"\n\n for item in loop:\n if item is not loop[0]:\n msg += \"...depends on \"\n if item.__class__ is Symbol and item.choice:\n msg += \"the choice symbol \"\n\n msg += \"{}, with definition...\\n\\n{}\\n\\n\" \\\n .format(item.name_and_loc, item)\n\n # Small wart: Since we reuse the already calculated\n # Symbol/Choice._dependents sets for recursive dependency detection, we\n # lose information on whether a dependency came from a 'select'/'imply'\n # condition or e.g. a 'depends on'.\n #\n # This might cause selecting symbols to \"disappear\". For example,\n # a symbol B having 'select A if C' gives a direct dependency from A to\n # C, since it corresponds to a reverse dependency of B && C.\n #\n # Always print reverse dependencies for symbols that have them to make\n # sure information isn't lost. I wonder if there's some neat way to\n # improve this.\n\n if item.__class__ is Symbol:\n if item.rev_dep is not item.kconfig.n:\n msg += \"(select-related dependencies: {})\\n\\n\" \\\n .format(expr_str(item.rev_dep))\n\n if item.weak_rev_dep is not item.kconfig.n:\n msg += \"(imply-related dependencies: {})\\n\\n\" \\\n .format(expr_str(item.rev_dep))\n\n msg += \"...depends again on \" + loop[0].name_and_loc\n\n raise KconfigError(msg)", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value:\n # x in (...)/[...]\n # x not in (...)/[...]\n first_op = e.operators[0]\n if (\n first_op in [\"in\", \"not in\"]\n and len(e.operators) == 1\n and isinstance(e.operands[1], (TupleExpr, ListExpr))\n ):\n items = e.operands[1].items\n n_items = len(items)\n # x in y -> x == y[0] or ... or x == y[n]\n # x not in y -> x != y[0] and ... and x != y[n]\n # 16 is arbitrarily chosen to limit code size\n if 1 < n_items < 16:\n if e.operators[0] == \"in\":\n bin_op = \"or\"\n cmp_op = \"==\"\n else:\n bin_op = \"and\"\n cmp_op = \"!=\"\n lhs = e.operands[0]\n mypy_file = builder.graph[\"builtins\"].tree\n assert mypy_file is not None\n info = mypy_file.names[\"bool\"].node\n assert isinstance(info, TypeInfo)\n bool_type = Instance(info, [])\n exprs = []\n for item in items:\n expr = ComparisonExpr([cmp_op], [lhs, item])\n builder.types[expr] = bool_type\n exprs.append(expr)\n\n or_expr: Expression = exprs.pop(0)\n for expr in exprs:\n or_expr = OpExpr(bin_op, or_expr, expr)\n builder.types[or_expr] = bool_type\n return builder.accept(or_expr)\n # x in [y]/(y) -> x == y\n # x not in [y]/(y) -> x != y\n elif n_items == 1:\n if e.operators[0] == \"in\":\n cmp_op = \"==\"\n else:\n cmp_op = \"!=\"\n e.operators = [cmp_op]\n e.operands[1] = items[0]\n # x in []/() -> False\n # x not in []/() -> True\n elif n_items == 0:\n if e.operators[0] == \"in\":\n return builder.false()\n else:\n return builder.true()\n\n # x in {...}\n # x not in {...}\n if (\n first_op in (\"in\", \"not in\")\n and len(e.operators) == 1\n and isinstance(e.operands[1], SetExpr)\n ):\n set_literal = precompute_set_literal(builder, e.operands[1])\n if set_literal is not None:\n lhs = e.operands[0]\n result = builder.builder.primitive_op(\n set_in_op, [builder.accept(lhs), set_literal], e.line, bool_rprimitive\n )\n if first_op == \"not in\":\n return builder.unary_op(result, \"not\", e.line)\n return result\n\n if len(e.operators) == 1:\n # Special some common simple cases\n if first_op in (\"is\", \"is not\"):\n right_expr = e.operands[1]\n if isinstance(right_expr, NameExpr) and right_expr.fullname == \"builtins.None\":\n # Special case 'is None' / 'is not None'.\n return translate_is_none(builder, e.operands[0], negated=first_op != \"is\")\n left_expr = e.operands[0]\n if is_int_rprimitive(builder.node_type(left_expr)):\n right_expr = e.operands[1]\n if is_int_rprimitive(builder.node_type(right_expr)):\n if first_op in int_borrow_friendly_op:\n borrow_left = is_borrow_friendly_expr(builder, right_expr)\n left = builder.accept(left_expr, can_borrow=borrow_left)\n right = builder.accept(right_expr, can_borrow=True)\n return builder.binary_op(left, right, first_op, e.line)\n\n # TODO: Don't produce an expression when used in conditional context\n # All of the trickiness here is due to support for chained conditionals\n # (`e1 < e2 > e3`, etc). `e1 < e2 > e3` is approximately equivalent to\n # `e1 < e2 and e2 > e3` except that `e2` is only evaluated once.\n expr_type = builder.node_type(e)\n\n # go(i, prev) generates code for `ei opi e{i+1} op{i+1} ... en`,\n # assuming that prev contains the value of `ei`.\n def go(i: int, prev: Value) -> Value:\n if i == len(e.operators) - 1:\n return transform_basic_comparison(\n builder, e.operators[i], prev, builder.accept(e.operands[i + 1]), e.line\n )\n\n next = builder.accept(e.operands[i + 1])\n return builder.builder.shortcircuit_helper(\n \"and\",\n expr_type,\n lambda: transform_basic_comparison(builder, e.operators[i], prev, next, e.line),\n lambda: go(i + 1, next),\n e.line,\n )\n\n return go(0, builder.accept(e.operands[0]))", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _create_static_chunks(db_task: models.Task, *, media_extractor: IMediaReader, upload_dir: str):\n @attrs.define\n class _ChunkProgressUpdater:\n _call_counter: int = attrs.field(default=0, init=False)\n _rq_job: rq.job.Job = attrs.field(factory=rq.get_current_job)\n\n def update_progress(self, progress: float):\n progress_animation = '|/-\\\\'\n\n status_message = 'CVAT is preparing data chunks'\n if not progress:\n status_message = '{} {}'.format(\n status_message, progress_animation[self._call_counter]\n )\n\n self._rq_job.meta['status'] = status_message\n self._rq_job.meta['task_progress'] = progress or 0.\n self._rq_job.save_meta()\n\n self._call_counter = (self._call_counter + 1) % len(progress_animation)\n\n def save_chunks(\n executor: concurrent.futures.ThreadPoolExecutor,\n db_segment: models.Segment,\n chunk_idx: int,\n chunk_frame_ids: Sequence[int]\n ):\n chunk_data = [media_iterator[frame_idx] for frame_idx in chunk_frame_ids]\n\n if (\n db_task.dimension == models.DimensionType.DIM_2D and\n isinstance(media_extractor, (\n MEDIA_TYPES['image']['extractor'],\n MEDIA_TYPES['zip']['extractor'],\n MEDIA_TYPES['pdf']['extractor'],\n MEDIA_TYPES['archive']['extractor'],\n ))\n ):\n chunk_data = preload_images(chunk_data)\n\n # TODO: extract into a class\n\n fs_original = executor.submit(\n original_chunk_writer.save_as_chunk,\n images=chunk_data,\n chunk_path=db_data.get_original_segment_chunk_path(\n chunk_idx, segment_id=db_segment.id\n ),\n )\n compressed_chunk_writer.save_as_chunk(\n images=chunk_data,\n chunk_path=db_data.get_compressed_segment_chunk_path(\n chunk_idx, segment_id=db_segment.id\n ),\n )\n\n fs_original.result()\n\n db_data = db_task.data\n\n if db_data.compressed_chunk_type == models.DataChoice.VIDEO:\n compressed_chunk_writer_class = Mpeg4CompressedChunkWriter\n else:\n compressed_chunk_writer_class = ZipCompressedChunkWriter\n\n if db_data.original_chunk_type == models.DataChoice.VIDEO:\n original_chunk_writer_class = Mpeg4ChunkWriter\n\n # Let's use QP=17 (that is 67 for 0-100 range) for the original chunks,\n # which should be visually lossless or nearly so.\n # A lower value will significantly increase the chunk size with a slight increase of quality.\n original_quality = 67 # TODO: fix discrepancy in values in different parts of code\n else:\n original_chunk_writer_class = ZipChunkWriter\n original_quality = 100\n\n chunk_writer_kwargs = {}\n if db_task.dimension == models.DimensionType.DIM_3D:\n chunk_writer_kwargs[\"dimension\"] = db_task.dimension\n compressed_chunk_writer = compressed_chunk_writer_class(\n db_data.image_quality, **chunk_writer_kwargs\n )\n original_chunk_writer = original_chunk_writer_class(original_quality, **chunk_writer_kwargs)\n\n db_segments = db_task.segment_set.order_by('start_frame').all()\n\n frame_map = {} # frame number -> extractor frame number\n\n if isinstance(media_extractor, MEDIA_TYPES['video']['extractor']):\n def _get_frame_size(frame_tuple: Tuple[av.VideoFrame, Any, Any]) -> int:\n # There is no need to be absolutely precise here,\n # just need to provide the reasonable upper boundary.\n # Return bytes needed for 1 frame\n frame = frame_tuple[0]\n return frame.width * frame.height * (frame.format.padded_bits_per_pixel // 8)\n\n # Currently, we only optimize video creation for sequential\n # chunks with potential overlap, so parallel processing is likely to\n # help only for image datasets\n media_iterator = CachingMediaIterator(\n media_extractor,\n max_cache_memory=2 ** 30, max_cache_entries=db_task.overlap,\n object_size_callback=_get_frame_size\n )\n else:\n extractor_frame_ids = {\n media_extractor.get_path(abs_frame_number): abs_frame_number\n for abs_frame_number in media_extractor.frame_range\n }\n\n frame_map = {\n frame.frame: extractor_frame_ids[os.path.join(upload_dir, frame.path)]\n for frame in db_data.images.all()\n }\n\n media_iterator = RandomAccessIterator(media_extractor)\n\n with closing(media_iterator):\n progress_updater = _ChunkProgressUpdater()\n\n # TODO: remove 2 * or the configuration option\n # TODO: maybe make real multithreading support, currently the code is limited by 1\n # video segment chunk, even if more threads are available\n max_concurrency = 2 * settings.CVAT_CONCURRENT_CHUNK_PROCESSING if not isinstance(\n media_extractor, MEDIA_TYPES['video']['extractor']\n ) else 2\n with concurrent.futures.ThreadPoolExecutor(max_workers=max_concurrency) as executor:\n for segment_idx, db_segment in enumerate(db_segments):\n frame_counter = itertools.count()\n for chunk_idx, chunk_frame_ids in (\n (chunk_idx, tuple(chunk_frame_ids))\n for chunk_idx, chunk_frame_ids in itertools.groupby(\n (\n # Convert absolute to relative ids (extractor output positions)\n # Extractor will skip frames outside requested\n (abs_frame_id - media_extractor.start) // media_extractor.step\n for abs_frame_id in (\n frame_map.get(frame, frame)\n for frame in sorted(db_segment.frame_set)\n )\n ),\n lambda _: next(frame_counter) // db_data.chunk_size\n )\n ):\n save_chunks(executor, db_segment, chunk_idx, chunk_frame_ids)\n\n progress_updater.update_progress(segment_idx / len(db_segments))", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def retuneTerr(self):\n\t\tif self.initcomplete:\n\t\t\tif self.scan_input_as.value == \"channel\":\n\t\t\t\tfrequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)\n\t\t\t\tif frequency:\n\t\t\t\t\tfrequency = int(frequency)\n\t\t\t\telse: # FIXME channel2frequency return None because of channel not found\n\t\t\t\t\tprint(\"[Satfinder] retuneTerr DVB-T channel '%s' out of scope\" % str(self.scan_ter.channel.value))\n\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tfrequency = self.scan_ter.frequency.floatint * 1000\n\t\t\tif self.scan_typeterrestrial.value == \"single_transponder\":\n\t\t\t\ttransponder = [\n\t\t\t\t\t2, # TERRESTRIAL\n\t\t\t\t\tfrequency,\n\t\t\t\t\tself.scan_ter.bandwidth.value,\n\t\t\t\t\tself.scan_ter.modulation.value,\n\t\t\t\t\tself.scan_ter.fechigh.value,\n\t\t\t\t\tself.scan_ter.feclow.value,\n\t\t\t\t\tself.scan_ter.guard.value,\n\t\t\t\t\tself.scan_ter.transmission.value,\n\t\t\t\t\tself.scan_ter.hierarchy.value,\n\t\t\t\t\tself.scan_ter.inversion.value,\n\t\t\t\t\tself.scan_ter.system.value,\n\t\t\t\t\tself.scan_ter.plp_id.value]\n\t\t\t\tself.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])\n\t\t\t\tself.transponder = transponder\n\t\t\telif self.scan_typeterrestrial.value == \"predefined_transponder\":\n\t\t\t\tif self.TerrestrialTransponders is not None:\n\t\t\t\t\tregion = nimmanager.getTerrestrialDescription(int(self.scan_nims.value))\n\t\t\t\t\ttps = nimmanager.getTranspondersTerrestrial(region)\n\t\t\t\t\tif len(tps) > self.TerrestrialTransponders.index:\n\t\t\t\t\t\ttransponder = tps[self.TerrestrialTransponders.index]\n\t\t\t\t\t\t# frequency 1, inversion 9, bandwidth 2, fechigh 4, feclow 5, modulation 3, transmission 7, guard 6, hierarchy 8, system 10, plp_id 11\n\t\t\t\t\t\tself.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])\n\t\t\t\t\t\tself.transponder = transponder", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def create_alert_rule(\n organization: Organization,\n projects: Sequence[Project],\n name: str,\n query: str,\n aggregate: str,\n time_window: int,\n threshold_type: AlertRuleThresholdType,\n threshold_period: int,\n owner: Actor | None = None,\n resolve_threshold: int | float | None = None,\n environment: Environment | None = None,\n include_all_projects: bool = False,\n excluded_projects: Collection[Project] | None = None,\n query_type: SnubaQuery.Type = SnubaQuery.Type.ERROR,\n dataset: Dataset = Dataset.Events,\n user: RpcUser | None = None,\n event_types: Collection[SnubaQueryEventType.EventType] = (),\n comparison_delta: int | None = None,\n monitor_type: AlertRuleMonitorTypeInt = AlertRuleMonitorTypeInt.CONTINUOUS,\n activation_condition: AlertRuleActivationConditionType | None = None,\n description: str | None = None,\n sensitivity: AlertRuleSensitivity | None = None,\n seasonality: AlertRuleSeasonality | None = None,\n detection_type: AlertRuleDetectionType = AlertRuleDetectionType.STATIC,\n **kwargs: Any,\n) -> AlertRule:\n \"\"\"\n Creates an alert rule for an organization.\n\n :param organization:\n :param projects: A list of projects to subscribe to the rule. This will be overridden\n if `include_all_projects` is True\n :param name: Name for the alert rule. This will be used as part of the\n incident name, and must be unique per project\n :param owner: Actor (sentry.types.actor.Actor) or None\n :param query: An event search query to subscribe to and monitor for alerts\n :param aggregate: A string representing the aggregate used in this alert rule\n :param time_window: Time period to aggregate over, in minutes\n :param environment: An optional environment that this rule applies to\n :param threshold_type: An AlertRuleThresholdType\n :param threshold_period: How many update periods the value of the\n subscription needs to exceed the threshold before triggering\n :param resolve_threshold: Optional value that the subscription needs to reach to\n resolve the alert\n :param include_all_projects: Whether to include all current and future projects\n from this organization\n :param excluded_projects: List of projects to exclude if we're using\n `include_all_projects`.\n :param query_type: The SnubaQuery.Type of the query\n :param dataset: The dataset that this query will be executed on\n :param event_types: List of `EventType` that this alert will be related to\n :param comparison_delta: An optional int representing the time delta to use to determine the\n comparison period. In minutes.\n :param sensitivity: An AlertRuleSensitivity that specifies sensitivity of anomaly detection alerts\n :param seasonality: An AlertRuleSeasonality that specifies seasonality of anomaly detection alerts\n :param detection_type: the type of metric alert; defaults to AlertRuleDetectionType.STATIC\n\n :return: The created `AlertRule`\n \"\"\"\n has_anomaly_detection = features.has(\n \"organizations:anomaly-detection-alerts\", organization\n ) and features.has(\"organizations:anomaly-detection-rollout\", organization)\n\n if detection_type == AlertRuleDetectionType.DYNAMIC.value and not has_anomaly_detection:\n raise ResourceDoesNotExist(\"Your organization does not have access to this feature.\")\n\n if monitor_type == AlertRuleMonitorTypeInt.ACTIVATED and not activation_condition:\n raise ValidationError(\"Activation condition required for activated alert rule\")\n\n if detection_type == AlertRuleDetectionType.DYNAMIC:\n resolution = time_window\n # NOTE: we hardcode seasonality for EA\n seasonality = AlertRuleSeasonality.AUTO\n if not sensitivity:\n raise ValidationError(\"Dynamic alerts require a sensitivity level\")\n if time_window not in DYNAMIC_TIME_WINDOWS:\n raise ValidationError(INVALID_TIME_WINDOW)\n if \"is:unresolved\" in query:\n raise ValidationError(\"Dynamic alerts do not support 'is:unresolved' queries\")\n else:\n resolution = get_alert_resolution(time_window, organization)\n seasonality = None\n if sensitivity:\n raise ValidationError(\"Sensitivity is not a valid field for this alert type\")\n if threshold_type == AlertRuleThresholdType.ABOVE_AND_BELOW:\n raise ValidationError(\n \"Above and below is not a valid threshold type for this alert type\"\n )\n\n if detection_type == AlertRuleDetectionType.PERCENT:\n if comparison_delta is None:\n raise ValidationError(\"Percentage-based alerts require a comparison delta\")\n else:\n if comparison_delta is not None:\n if not (sensitivity or seasonality):\n # this is a user setting up a percent-based metric alert who doesn't know about the new field\n detection_type = AlertRuleDetectionType.PERCENT\n else:\n # this is an incorrect field selection\n raise ValidationError(\"Comparison delta is not a valid field for this alert type\")\n\n if comparison_delta is not None:\n # Since comparison alerts make twice as many queries, run the queries less frequently.\n resolution = resolution * DEFAULT_CMP_ALERT_RULE_RESOLUTION_MULTIPLIER\n comparison_delta = int(timedelta(minutes=comparison_delta).total_seconds())\n\n with transaction.atomic(router.db_for_write(SnubaQuery)):\n # NOTE: `create_snuba_query` constructs the postgres representation of the snuba query\n snuba_query = create_snuba_query(\n query_type=query_type,\n dataset=dataset,\n query=query,\n aggregate=aggregate,\n time_window=timedelta(minutes=time_window),\n resolution=timedelta(minutes=resolution),\n environment=environment,\n event_types=event_types,\n )\n\n alert_rule = AlertRule.objects.create(\n organization=organization,\n snuba_query=snuba_query,\n name=name,\n threshold_type=threshold_type.value,\n resolve_threshold=resolve_threshold,\n threshold_period=threshold_period,\n include_all_projects=include_all_projects,\n comparison_delta=comparison_delta,\n monitor_type=monitor_type,\n description=description,\n sensitivity=sensitivity,\n seasonality=seasonality,\n detection_type=detection_type,\n **_owner_kwargs_from_actor(owner),\n )\n\n if include_all_projects:\n # NOTE: This feature is not currently utilized.\n excluded_projects = excluded_projects or ()\n projects = list(\n Project.objects.filter(organization=organization).exclude(\n id__in=[p.id for p in excluded_projects]\n )\n )\n exclusions = [\n AlertRuleExcludedProjects(alert_rule=alert_rule, project=project)\n for project in excluded_projects\n ]\n AlertRuleExcludedProjects.objects.bulk_create(exclusions)\n\n if alert_rule.detection_type == AlertRuleDetectionType.DYNAMIC.value:\n # NOTE: if adding a new metric alert type, take care to check that it's handled here\n send_new_rule_data(alert_rule, projects[0], snuba_query)\n\n if user:\n create_audit_entry_from_user(\n user,\n ip_address=kwargs.get(\"ip_address\") if kwargs else None,\n organization_id=organization.id,\n target_object=alert_rule.id,\n data=alert_rule.get_audit_log_data(),\n event=audit_log.get_event_id(\"ALERT_RULE_ADD\"),\n )\n\n if monitor_type == AlertRuleMonitorTypeInt.ACTIVATED and activation_condition:\n # NOTE: if monitor_type is activated, activation_condition is required\n AlertRuleActivationCondition.objects.create(\n alert_rule=alert_rule, condition_type=activation_condition.value\n )\n\n # initialize projects join table for alert rules\n arps = [AlertRuleProjects(alert_rule=alert_rule, project=project) for project in projects]\n AlertRuleProjects.objects.bulk_create(arps)\n\n # NOTE: This constructs the query in snuba\n # NOTE: Will only subscribe if AlertRule.monitor_type === 'CONTINUOUS'\n alert_rule.subscribe_projects(projects=projects)\n\n # Activity is an audit log of what's happened with this alert rule\n AlertRuleActivity.objects.create(\n alert_rule=alert_rule,\n user_id=user.id if user else None,\n type=AlertRuleActivityType.CREATED.value,\n )\n\n schedule_update_project_config(alert_rule, projects)\n\n return alert_rule", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def PreprocessExperimentalTextAnnotationBlock(\n inViewMapC, inExpBlkname, inExpBlk):\n\n substringToSubstituteForSpace = None\n if 'substringtosubstituteforspace' in inExpBlk:\n substringToSubstituteForSpace = \\\n str(inExpBlk['substringtosubstituteforspace'])\n if PhactoriDbg():\n myDebugPrint3(\"substringtosubstituteforspace: ->\" + \\\n substringToSubstituteForSpace + \"<-\\n\")\n\n if 'line1' not in inExpBlk:\n myDebugPrint3AndException(\"PreprocessOneExperimentalBlock:\\n\" \\\n \"textannotation type block must have 'line1' entry\")\n\n myNewTxtAntnBlk = {}\n\n for lineIndex in range(1, 10):\n oneLineString = \"\"\n lineKey = \"line\" + str(lineIndex)\n if lineKey not in inExpBlk:\n break\n oneLineString = str(inExpBlk[lineKey])\n if substringToSubstituteForSpace != None:\n oneLineString = oneLineString.replace(\n substringToSubstituteForSpace, \" \")\n if PhactoriDbg():\n myDebugPrint3(\"line after sub: ->\" + oneLineString + \"\\n\")\n myNewTxtAntnBlk[lineKey] = oneLineString\n\n if 'windowlocation' in inExpBlk:\n myNewTxtAntnBlk['windowlocation'] = inExpBlk['windowlocation']\n\n if ('positionx' in inExpBlk) or ('positiony' in inExpBlk):\n if 'positiony' not in inExpBlk:\n myDebugPrint3AndException(\"PreprocessOneExperimentalBlock:\\n\" \\\n \"if you have 'positionx' you need 'positiony'\\n\")\n if 'positionx' not in inExpBlk:\n myDebugPrint3AndException(\"PreprocessOneExperimentalBlock:\\n\" \\\n \"if you have 'positiony' you need 'positionx'\\n\")\n posx = float(inExpBlk['positionx'])\n posy = float(inExpBlk['positiony'])\n myNewTxtAntnBlk['windowlocation'] = 'AnyLocation'\n myNewTxtAntnBlk['position'] = [posx, posy]\n\n if 'color' in inExpBlk:\n colorRgb = inExpBlk['color']\n myNewTxtAntnBlk['color'] = \\\n [float(colorRgb[0]), float(colorRgb[1]), float(colorRgb[2])]\n\n if 'opacity' in inExpBlk:\n myNewTxtAntnBlk['opacity'] = float(inExpBlk['opacity'])\n\n if 'boldflag' in inExpBlk:\n myNewTxtAntnBlk['boldflag'] = int(inExpBlk['boldflag'])\n if 'italicflag' in inExpBlk:\n myNewTxtAntnBlk['italicflag'] = int(inExpBlk['italicflag'])\n if 'shadowflag' in inExpBlk:\n myNewTxtAntnBlk['shadowflag'] = int(inExpBlk['shadowflag'])\n\n if 'fontsize' in inExpBlk:\n myNewTxtAntnBlk['fontsize'] = int(inExpBlk['fontsize'])\n if 'fontfamily' in inExpBlk:\n myNewTxtAntnBlk['fontfamily'] = inExpBlk['fontfamily']\n\n if 'text annotation blocks' not in inViewMapC:\n inViewMapC['text annotation blocks'] = {}\n inViewMapC['text annotation blocks'][inExpBlkname] = myNewTxtAntnBlk\n\n if 'show_in_imageset' in inExpBlk:\n targetImageset = inExpBlk['show_in_imageset']\n imagesets = inViewMapC['imageset blocks']\n if targetImageset in imagesets:\n theImageset = imagesets[targetImageset]\n if 'text annotations' not in theImageset:\n theImageset['text annotations'] = []\n textAnnotationList = theImageset['text annotations']\n textAnnotationList.append(inExpBlkname)\n else:\n myDebugPrint3AndException(\"PreprocessOneExperimentalBlock:\\n\" \\\n \"textannotation target imageset is not in imageset blocks\")\n else:\n myDebugPrint3AndException(\"PreprocessOneExperimentalBlock:\\n\" \\\n \"textannotation type block must have 'show_in_imageset' entry\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "@transaction.atomic\ndef check_contributor_api_limit(at_datetime, c):\n try:\n contributor = Contributor.objects.get(id=c.get('contributor'))\n except Contributor.DoesNotExist:\n # API Limits and Blocks are linked to contributors.\n # Users without contributors are blocked from the system\n # in middleware and don't need to be handled here.\n return\n log_dates = c.get('log_dates')\n notification, created = ContributorNotifications \\\n .objects \\\n .get_or_create(contributor=contributor)\n try:\n apiLimit = ApiLimit.objects.get(contributor=contributor)\n limit = apiLimit.period_limit\n renewal_period = apiLimit.renewal_period\n date = apiLimit.period_start_date\n except ObjectDoesNotExist:\n limit = None\n renewal_period = ''\n date = min(log_dates)\n\n context = DateLimitationContext()\n\n if renewal_period == '':\n context.set_strategy(BlankDateLimitation())\n if renewal_period == 'MONTHLY':\n context.set_strategy(MonthlyDateLimitation())\n if renewal_period == 'YEARLY':\n context.set_strategy(YearlyDateLimitation())\n\n date_limitation = context.execute(date)\n start_date = date_limitation.get_start_date()\n until = date_limitation.get_api_block_until()\n\n logs_for_period = [x for x in log_dates if x >= start_date]\n request_count = len(logs_for_period)\n\n if (limit is None or\n renewal_period == ''):\n block_free_api_contributor(contributor,\n limit,\n request_count,\n until,\n at_datetime)\n return\n\n apiBlock = get_api_block(contributor)\n if limit == 0:\n if (apiBlock is not None and\n apiBlock.active and\n apiBlock.until > at_datetime):\n update_api_block(apiBlock, limit, request_count, is_active=False)\n return\n if request_count > (limit * .9) and request_count <= limit:\n warning_sent = notification.api_limit_warning_sent_on\n # If no warning was sent in this period\n if (warning_sent is None or warning_sent < start_date):\n send_api_warning(contributor, limit)\n send_admin_api_warning(contributor.name, limit)\n notification.api_limit_warning_sent_on = at_datetime\n notification.save()\n if request_count > limit:\n # If there is no current API block\n if apiBlock is None or apiBlock.until < at_datetime:\n create_api_block(contributor,\n limit,\n request_count,\n until)\n exceeded_sent = notification.api_limit_exceeded_sent_on\n if (exceeded_sent is None or\n exceeded_sent.month < at_datetime.month):\n send_api_notice(contributor, limit)\n send_admin_api_notice(contributor.name, limit)\n notification.api_limit_exceeded_sent_on = (\n at_datetime)\n notification.save()\n else:\n if apiBlock.active:\n return\n if apiBlock.active is False and apiBlock.grace_limit is None:\n update_api_block(apiBlock,\n limit,\n request_count,\n is_active=True)\n return\n grace_limit = apiBlock.grace_limit\n if request_count > grace_limit:\n update_api_block(apiBlock,\n limit,\n request_count,\n is_active=True)\n send_api_notice(contributor, limit, grace_limit)\n send_admin_api_notice(contributor.name, limit, grace_limit)\n notification.api_grace_limit_exceeded_sent_on = (\n at_datetime)\n notification.save()\n else:\n if apiBlock is not None and apiBlock.active:\n update_api_block(apiBlock,\n limit,\n request_count,\n is_active=False)", "smellKey": "S3776", "smellId": null, "repo": "opensupplyhub_open-supply-hub", "language": "python"} {"function": "def streamline(self) -> ParserElement:\n # collapse any _PendingSkip's\n if self.exprs:\n if any(\n isinstance(e, ParseExpression)\n and e.exprs\n and isinstance(e.exprs[-1], _PendingSkip)\n for e in self.exprs[:-1]\n ):\n deleted_expr_marker = NoMatch()\n for i, e in enumerate(self.exprs[:-1]):\n if e is deleted_expr_marker:\n continue\n if (\n isinstance(e, ParseExpression)\n and e.exprs\n and isinstance(e.exprs[-1], _PendingSkip)\n ):\n e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]\n self.exprs[i + 1] = deleted_expr_marker\n self.exprs = [e for e in self.exprs if e is not deleted_expr_marker]\n\n super().streamline()\n\n # link any IndentedBlocks to the prior expression\n prev: ParserElement\n cur: ParserElement\n for prev, cur in zip(self.exprs, self.exprs[1:]):\n # traverse cur or any first embedded expr of cur looking for an IndentedBlock\n # (but watch out for recursive grammar)\n seen = set()\n while True:\n if id(cur) in seen:\n break\n seen.add(id(cur))\n if isinstance(cur, IndentedBlock):\n prev.add_parse_action(\n lambda s, l, t, cur_=cur: setattr(\n cur_, \"parent_anchor\", col(l, s)\n )\n )\n break\n subs = cur.recurse()\n next_first = next(iter(subs), None)\n if next_first is None:\n break\n cur = typing.cast(ParserElement, next_first)\n\n self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n return self", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def SetPlotPointsFromOneBlock(inInputCsData, ioPlotInfo, ioIndex):\n if PhactoriDbg(100):\n myDebugPrint3('SetPlotPointsFromOneBlock entered\\n', 100)\n if PhactoriDbg():\n myDebugPrint3(' x axis variable: ' + ioPlotInfo.m_XAxisVariableInfo.mVariableName + \\\n '\\n y axis varaible: ' + ioPlotInfo.m_YAxisVariableInfo.mVariableName + '\\n')\n\n #detect variable type (node/element) if necessary, and save info if detected\n detectResult = ioPlotInfo.m_YAxisVariableInfo.DetectVariableType(\n inInputCsData, False, False)\n if detectResult == False:\n if PhactoriDbg(100):\n myDebugPrint3('no detection: returning\\n', 100)\n return\n\n ioPlotInfo.m_XAxisVariableInfo.CopyVariableTypeFrom(\n ioPlotInfo.m_YAxisVariableInfo)\n\n if(ioPlotInfo.m_YAxisVariableInfo.mVariableType == 'node'):\n cellOrPointData = inInputCsData.GetPointData()\n if cellOrPointData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no point data: returning\\n', 100)\n return\n else:\n cellOrPointData = inInputCsData.GetCellData()\n if cellOrPointData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no cell data: returning\\n', 100)\n return\n #nodeData = inClientSideData.GetNodeData()\n\n\n #print all element names\n #myDebugPrint3('printing array names:\\n')\n #numCellArrays = cellOrPointData.GetNumberOfArrays()\n #for ii in range(0, numCellArrays):\n # myDebugPrint3(str(ii) + \": \" + cellOrPointData.GetArray(ii).GetName() + \"\\n\")\n\n\n xData = cellOrPointData.GetArray(ioPlotInfo.m_XAxisVariableInfo.mVariableName)\n yData = cellOrPointData.GetArray(ioPlotInfo.m_YAxisVariableInfo.mVariableName)\n if xData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no xData: returning\\n', 100)\n return\n if yData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no yData: returning\\n', 100)\n return\n if PhactoriDbg():\n myDebugPrint3(' x data: ' + str(xData) + ' y data: ' + str(yData) + '\\n')\n if PhactoriDbg():\n myDebugPrint3(' x data name: ' + xData.GetName() + ' y data name : ' + yData.GetName() + '\\n')\n numTuplesX = xData.GetNumberOfTuples()\n numTuplesY = yData.GetNumberOfTuples()\n\n if numTuplesX != numTuplesY:\n if PhactoriDbg():\n myDebugPrint3('number of tuples do not match in SetPlotPointsFromOneBlock')\n return\n\n if 1:\n ptListCount = numTuplesX\n if ptListCount > 100:\n ptListCount = 100\n for jj in range(0, ptListCount):\n if PhactoriDbg():\n myDebugPrint3(' cell ' + str(jj) + ': ' + str(xData.GetTuple1(jj)) + ' data: ' + str(yData.GetTuple1(jj)) + '\\n')\n\n outOutputPoints = ioPlotInfo.m_Points\n\n #myDebugPrint3('ioIndex is ' + str(ioIndex))\n #myDebugPrint3('outOutputPoints is ' + str(outOutputPoints))\n #myDebugPrint3('outOutputPoints number of points is ' + str(outOutputPoints.GetNumberOfPoints()))\n\n localIndex = ioIndex[0]\n for ii in range(0, numTuplesX):\n\n if ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorComponent:\n vecVal = xData.GetTuple3(ii)\n xx = vecVal[ioPlotInfo.m_XAxisVariableInfo.mVariableComponent]\n elif ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorMagnitude:\n vecVal = xData.GetTuple3(ii)\n aa = vecVal[0]\n bb = vecVal[1]\n cc = vecVal[2]\n xx = math.sqrt(aa*aa + bb*bb + cc*cc)\n else:\n xx = xData.GetTuple1(ii)\n\n if ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorComponent:\n vecVal = yData.GetTuple3(ii)\n yy = vecVal[ioPlotInfo.m_YAxisVariableInfo.mVariableComponent]\n elif ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorMagnitude:\n vecVal = yData.GetTuple3(ii)\n aa = vecVal[0]\n bb = vecVal[1]\n cc = vecVal[2]\n yy = math.sqrt(aa*aa + bb*bb + cc*cc)\n else:\n yy = yData.GetTuple1(ii)\n\n zz = 0.0\n if localIndex < outOutputPoints.GetNumberOfPoints():\n if PhactoriDbg():\n myDebugPrint3(' sppfob changing existing point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\\n')\n outOutputPoints.SetPoint(localIndex, xx, yy, zz)\n else:\n if PhactoriDbg():\n myDebugPrint3(' sppfob inserting new point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\\n')\n outOutputPoints.InsertPoint(localIndex, xx, yy, zz)\n localIndex += 1\n ioIndex[0] = localIndex\n #PrintAllPointsA()\n if PhactoriDbg(100):\n myDebugPrint3('SetPlotPointsFromOneBlock returning\\n', 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def handleKey(self, key, callback=None):\n\t\tif key in ACTIONKEY_NUMBERS or key == ACTIONKEY_ASCII:\n\t\t\tprev = int(self.text)\n\t\t\tif key == ACTIONKEY_ASCII:\n\t\t\t\tascii = getPrevAsciiCode()\n\t\t\t\tif not (48 <= ascii <= 57):\n\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tascii = getKeyNumber(key) + 48\n\t\t\tnewChar = chr(ascii)\n\t\t\tif self.allmarked:\n\t\t\t\tself.deleteAllChars()\n\t\t\t\tself.allmarked = False\n\t\t\tself.insertChar(newChar, self.markedPos, False)\n\t\t\tself.markedPos += 1\n\t\t\tself.validateMarker()\n\t\t\tif int(self.text) != prev:\n\t\t\t\tself.changed()\n\t\t\t\tif callable(callback):\n\t\t\t\t\tcallback()\n\t\telse:\n\t\t\tConfigText.handleKey(self, key, callback)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def process_raw_response(response: list[dict[str, Any]]) -> list[dict[str, Any]]:\n \"\"\"Process the response further into the expected output.\"\"\"\n\n def make_selector_name(row) -> str:\n selector = row[\"click_tag\"]\n\n if row[\"click_id\"]:\n selector = selector + f\"#{row['click_id']}\"\n if row[\"click_class_filtered\"]:\n selector = selector + \".\" + \".\".join(row[\"click_class_filtered\"])\n\n if row[\"click_role\"]:\n selector = selector + f'[role=\"{row[\"click_role\"]}\"]'\n if row[\"click_alt\"]:\n selector = selector + f'[alt=\"{row[\"click_alt\"]}\"]'\n if row[\"click_testid\"]:\n selector = selector + f'[testid=\"{row[\"click_testid\"]}\"]'\n if row[\"click_aria_label\"]:\n selector = selector + f'[aria=\"{row[\"click_aria_label\"]}\"]'\n if row[\"click_title\"]:\n selector = selector + f'[title=\"{row[\"click_title\"]}\"]'\n if row[\"click_component_name\"]:\n selector = selector + f'[component_name=\"{row[\"click_component_name\"]}\"]'\n\n return selector\n\n return [\n {\n \"count_dead_clicks\": row[\"count_dead_clicks\"],\n \"count_rage_clicks\": row[\"count_rage_clicks\"],\n \"dom_element\": make_selector_name(row),\n \"element\": {\n \"alt\": row[\"click_alt\"],\n \"aria_label\": row[\"click_aria_label\"],\n \"class\": row[\"click_class_filtered\"],\n \"id\": row[\"click_id\"],\n \"project_id\": row[\"project_id\"],\n \"role\": row[\"click_role\"],\n \"tag\": row[\"click_tag\"],\n \"testid\": row[\"click_testid\"],\n \"title\": row[\"click_title\"],\n \"component_name\": row[\"click_component_name\"],\n },\n \"project_id\": row[\"project_id\"],\n }\n for row in response\n ]", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def ExportOperationData(self, datadescription):\n \"this will be called once per callback (before WriteImages) to allow the\\n operation to export any desired data which is not an image. The child\\n class should override this method if it wants so do something.\\n For PhactoriIntersectNodeNormalsWithSurface we will output information\\n about the nearest and furthest intersections\"\n \n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData \"\n \"entered\\n\", 100)\n\n UpdatePipelineWithCurrentTimeArgument(\n self.mPhactoriOperationBlockOwner.mParaViewFilter)\n self.RunCalculationToCastRays(gPipeAndViewsState)\n UpdatePipelineWithCurrentTimeArgument(\n self.mPhactoriOperationBlockOwner.mParaViewFilter)\n\n if self.mPointNormalRayIntersectDistanceArray == None:\n if PhactoriDbg(100):\n myDebugPrint3(\"no data values, returning\\n\")\n return\n\n numpts = self.mPointNormalRayIntersectDistanceArray.GetNumberOfValues()\n maxval = -1.0\n minval = -1.0\n minval2 = -1.0\n if numpts > 0:\n vv = self.mPointNormalRayIntersectDistanceArray.GetValue(0)\n maxval = vv\n minval = vv\n if vv >= -0.5:\n minval2 = vv\n for ii in range(1, numpts):\n vv = self.mPointNormalRayIntersectDistanceArray.GetValue(ii)\n if vv > maxval:\n maxval = vv\n if vv < minval:\n minval = vv\n if vv >= -0.5:\n if (minval2 < -0.5) or (vv < minval2):\n minval2 = vv\n\n fname = \"RayIntersectionMinMax_\" + \\\n self.mPhactoriOperationBlockOwner.mName + \"_process_\" + \\\n str(SmartGetLocalProcessId()) + \".txt\"\n try:\n ff = open(fname, \"a+b\")\n ff.write(\"minimum, maximum, nonnegative minimum\\n\")\n ff.write(str(minval) + \", \" + str(maxval) + \", \" + str(minval2) + \"\\n\")\n except:\n myDebugPrint3AndException(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData\\n\"\n \"Error writing file: \" + str(fname) + \"\\n\")\n\n if PhactoriDbg(100):\n myDebugPrint3(\n \"PhactoriIntersectNodeNormalsWithSurface::ExportOperationData \"\n \"returning\\n\", 100)\n return", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "async def on_revocation_registry_init_event(profile: Profile, event: Event):\n \"\"\"Handle revocation registry initiation event.\"\"\"\n meta_data = event.payload\n if \"endorser\" in meta_data:\n # TODO error handling - for now just let exceptions get raised\n endorser_connection_id = meta_data[\"endorser\"][\"connection_id\"]\n async with profile.session() as session:\n connection = await ConnRecord.retrieve_by_id(session, endorser_connection_id)\n endorser_info = await connection.metadata_get(session, \"endorser_info\")\n endorser_did = endorser_info[\"endorser_did\"]\n write_ledger = False\n else:\n endorser_connection_id = None\n endorser_did = None\n write_ledger = True\n\n tails_base_url = profile.settings.get(\"tails_server_base_url\")\n if not tails_base_url:\n raise RevocationError(\"tails_server_base_url not configured\")\n\n # Generate the registry and upload the tails file\n async def generate(rr_record: IssuerRevRegRecord) -> dict:\n await rr_record.generate_registry(profile)\n public_uri = tails_base_url.rstrip(\"/\") + f\"/{registry_record.revoc_reg_id}\"\n await rr_record.set_tails_file_public_uri(profile, public_uri)\n rev_reg_resp = await rr_record.send_def(\n profile,\n write_ledger=write_ledger,\n endorser_did=endorser_did,\n )\n if write_ledger:\n # Upload the tails file\n await rr_record.upload_tails_file(profile)\n\n # Post the initial revocation entry\n await notify_revocation_entry_event(profile, record_id, meta_data)\n else:\n transaction_manager = TransactionManager(profile)\n try:\n revo_transaction = await transaction_manager.create_record(\n messages_attach=rev_reg_resp[\"result\"],\n connection_id=connection.connection_id,\n meta_data=event.payload,\n )\n except StorageError as err:\n raise TransactionManagerError(reason=err.roll_up) from err\n\n # if auto-request, send the request to the endorser\n if profile.settings.get_value(\"endorser.auto_request\"):\n try:\n (\n revo_transaction,\n revo_transaction_request,\n ) = await transaction_manager.create_request(\n transaction=revo_transaction,\n # TODO see if we need to parametrize these params\n # expires_time=expires_time,\n )\n except (StorageError, TransactionManagerError) as err:\n raise TransactionManagerError(reason=err.roll_up) from err\n\n responder = profile.inject_or(BaseResponder)\n if responder:\n await responder.send(\n revo_transaction_request,\n connection_id=connection.connection_id,\n )\n else:\n LOGGER.warning(\n \"Configuration has no BaseResponder: cannot update \"\n \"revocation on registry ID: %s\",\n record_id,\n )\n\n record_id = meta_data[\"context\"][\"issuer_rev_id\"]\n async with profile.session() as session:\n registry_record = await IssuerRevRegRecord.retrieve_by_id(session, record_id)\n await shield(generate(registry_record))\n\n create_pending_rev_reg = meta_data[\"processing\"].get(\"create_pending_rev_reg\", False)\n if write_ledger and create_pending_rev_reg:\n revoc = IndyRevocation(profile)\n await revoc.init_issuer_registry(\n registry_record.cred_def_id,\n registry_record.max_cred_num,\n registry_record.revoc_def_type,\n endorser_connection_id=endorser_connection_id,\n )", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def as_json(self):\n config = {}\n config[\"name\"] = self.name\n config[\"bit_offset\"] = self.bit_offset\n config[\"bit_size\"] = self.bit_size\n config[\"data_type\"] = self.data_type\n if self.array_size is not None:\n config[\"array_size\"] = self.array_size\n config[\"description\"] = self.description\n if self.id_value is not None:\n config[\"id_value\"] = self.id_value\n if self.default is not None:\n config[\"default\"] = self.default\n config[\"minimum\"] = self.minimum\n config[\"maximum\"] = self.maximum\n config[\"endianness\"] = self.endianness\n config[\"required\"] = self.required\n if self.format_string:\n config[\"format_string\"] = self.format_string\n if self.units:\n config[\"units\"] = self.units\n config[\"units_full\"] = self.units_full\n config[\"overflow\"] = self.overflow\n if self.states:\n states = {}\n config[\"states\"] = states\n for state_name, state_value in self.states.items():\n state = {}\n states[state_name] = state\n state[\"value\"] = state_value\n if self.hazardous and self.hazardous.get(state_name) is not None:\n state[\"hazardous\"] = self.hazardous[state_name]\n if self.messages_disabled and self.messages_disabled.get(state_name) is not None:\n state[\"messages_disabled\"] = self.messages_disabled[state_name]\n if self.state_colors and self.state_colors.get(state_name) is not None:\n state[\"color\"] = self.state_colors[state_name]\n\n if self.read_conversion:\n config[\"read_conversion\"] = self.read_conversion.as_json()\n if self.write_conversion:\n config[\"write_conversion\"] = self.write_conversion.as_json()\n\n if self.limits:\n config[\"limits\"] = {}\n if self.limits.enabled:\n config[\"limits\"][\"enabled\"] = True\n else:\n config[\"limits\"][\"enabled\"] = False\n if self.limits.values:\n config[\"limits\"][\"persistence_setting\"] = self.limits.persistence_setting\n if self.limits.response:\n config[\"limits\"][\"response\"] = self.limits.response\n for limits_set, limits_values in self.limits.values.items():\n limits = {}\n limits[\"red_low\"] = limits_values[0]\n limits[\"yellow_low\"] = limits_values[1]\n limits[\"yellow_high\"] = limits_values[2]\n limits[\"red_high\"] = limits_values[3]\n if len(limits_values) > 4:\n limits[\"green_low\"] = limits_values[4]\n limits[\"green_high\"] = limits_values[5]\n config[\"limits\"][limits_set] = limits\n if self.limits.response:\n config[\"limits_response\"] = self.limits.response.as_json()\n\n if self.meta:\n config[\"meta\"] = self.meta\n return config", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def execute(self):\n \"\"\"\n Given the command-line arguments, figure out which subcommand is being\n run, create a parser appropriate to that command, and run it.\n \"\"\"\n try:\n subcommand = self.argv[1]\n except IndexError:\n subcommand = \"help\" # Display help if no arguments were given.\n\n # Preprocess options to extract --settings and --pythonpath.\n # These options could affect the commands that are available, so they\n # must be processed early.\n parser = CommandParser(\n prog=self.prog_name,\n usage=\"%(prog)s subcommand [options] [args]\",\n add_help=False,\n allow_abbrev=False,\n )\n parser.add_argument(\"--settings\")\n parser.add_argument(\"--pythonpath\")\n parser.add_argument(\"args\", nargs=\"*\") # catch-all\n try:\n options, args = parser.parse_known_args(self.argv[2:])\n handle_default_options(options)\n except CommandError:\n pass # Ignore any option errors at this point.\n\n try:\n settings.INSTALLED_APPS\n except ImproperlyConfigured as exc:\n self.settings_exception = exc\n except ImportError as exc:\n self.settings_exception = exc\n\n if settings.configured:\n # Start the auto-reloading dev server even if the code is broken.\n # The hardcoded condition is a code smell but we can't rely on a\n # flag on the command class because we haven't located it yet.\n if subcommand == \"runserver\" and \"--noreload\" not in self.argv:\n try:\n autoreload.check_errors(django.setup)()\n except Exception:\n # The exception will be raised later in the child process\n # started by the autoreloader. Pretend it didn't happen by\n # loading an empty list of applications.\n apps.all_models = defaultdict(dict)\n apps.app_configs = {}\n apps.apps_ready = apps.models_ready = apps.ready = True\n\n # Remove options not compatible with the built-in runserver\n # (e.g. options for the contrib.staticfiles' runserver).\n # Changes here require manually testing as described in\n # #27522.\n _parser = self.fetch_command(\"runserver\").create_parser(\n \"django\", \"runserver\"\n )\n _options, _args = _parser.parse_known_args(self.argv[2:])\n for _arg in _args:\n self.argv.remove(_arg)\n\n # In all other cases, django.setup() is required to succeed.\n else:\n django.setup()\n\n self.autocomplete()\n\n if subcommand == \"help\":\n if \"--commands\" in args:\n sys.stdout.write(self.main_help_text(commands_only=True) + \"\\n\")\n elif not options.args:\n sys.stdout.write(self.main_help_text() + \"\\n\")\n else:\n self.fetch_command(options.args[0]).print_help(\n self.prog_name, options.args[0]\n )\n # Special-cases: We want 'django-admin --version' and\n # 'django-admin --help' to work, for backwards compatibility.\n elif subcommand == \"version\" or self.argv[1:] == [\"--version\"]:\n sys.stdout.write(django.get_version() + \"\\n\")\n elif self.argv[1:] in ([\"--help\"], [\"-h\"]):\n sys.stdout.write(self.main_help_text() + \"\\n\")\n else:\n self.fetch_command(subcommand).run_from_argv(self.argv)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _do_init1(self):\n from . import rxd\n\n # TODO: if a list of sections is passed in, make that one region\n # _species_count is used to create a unique _real_name for the species\n global _species_count\n\n regions = self.regions\n self._real_name = self._name\n initial = self.initial\n charge = self._charge\n\n # invalidate any old initialization of external solvers\n rxd._external_solver_initialized = False\n\n # TODO: check about the 0<x<1 problem alluded to in the documentation\n h.define_shape()\n name = self.name\n if name is not None:\n if not isinstance(name, str):\n raise RxDException(\"Species name must be a string\")\n if name in _defined_species:\n spsecs_i = []\n spsecs_o = []\n for r in regions:\n if r in _defined_species[name]:\n raise RxDException(\n 'Species \"%s\" previously defined on region: %r' % (name, r)\n )\n if hasattr(r, \"_secs\"):\n if r.nrn_region == \"i\":\n spsecs_i += r._secs\n elif r.nrn_region == \"o\":\n spsecs_o += r._secs\n spsecs_i = set(spsecs_i)\n spsecs_o = set(spsecs_o)\n for r in _defined_species[name]:\n if hasattr(r, \"_secs\") and r.nrn_region:\n if (\n r.nrn_region == \"i\"\n and any(spsecs_i.intersection(r._secs))\n or (\n r.nrn_region == \"o\"\n and any(spsecs_o.intersection(r._secs))\n )\n ):\n raise RxDException(\n 'Species \"%s\" previously defined on a region %r that overlaps with regions: %r'\n % (name, r, self._regions)\n )\n else:\n name = _species_count\n self._id = _species_count\n _species_count += 1\n if name not in _defined_species:\n _defined_species[name] = weakref.WeakKeyDictionary()\n self._species = weakref.ref(self)\n for r in regions:\n _defined_species[name][r] = self._species\n _all_defined_species.append(self._species)\n\n if regions is None:\n raise RxDException(\"Must specify region where species is present\")\n if hasattr(regions, \"__len__\"):\n regions = list(regions)\n else:\n regions = list([regions])\n # TODO: unite handling of _regions and _extracellular_regions\n self._regions = [r for r in regions if not isinstance(r, region.Extracellular)]\n self._extracellular_regions = [\n r for r in regions if isinstance(r, region.Extracellular)\n ]\n if not all(isinstance(r, region.Region) for r in self._regions):\n raise RxDException(\n \"regions list must consist of Region and Extracellular objects only\"\n )\n\n # at this point self._name is None if unnamed or a string == name if\n # named\n self._ion_register()\n\n # TODO: remove this line when certain no longer need it (commented out 2013-04-17)\n # self._real_secs = region._sort_secs(sum([r.secs for r in regions], []))", "smellKey": "S3776", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def assert_expected_response(response: dict[str, Any], expected_response: dict[str, Any]) -> None:\n \"\"\"Assert a received response matches what was expected.\"\"\"\n # Compare the response structure and values to the expected response.\n for key, value in expected_response.items():\n assert key in response, f\"key: {key}\"\n response_value = response.pop(key)\n\n if isinstance(response_value, dict):\n assert isinstance(value, dict)\n for k, v in value.items():\n if isinstance(v, list):\n assert sorted(response_value[k]) == sorted(v)\n else:\n assert response_value[k] == v, f\"value: {v}, expected: {response_value[k]}\"\n elif isinstance(response_value, list):\n assert len(response_value) == len(value), f'\"{response_value}\" \"{value}\"'\n for item in response_value:\n assert item in value, f\"{key}, {item}\"\n value.remove(item)\n else:\n assert response_value == value, f'\"{key}, {response_value}\" \"{value}\"'\n\n # Ensure no lingering unexpected keys exist.\n assert list(response.keys()) == [], response.keys()", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def untar_file(filename: str, location: str) -> None:\n \"\"\"\n Untar the file (with path `filename`) to the destination `location`.\n All files are written based on system defaults and umask (i.e. permissions\n are not preserved), except that regular file members with any execute\n permissions (user, group, or world) have \"chmod +x\" applied on top of the\n default. Note that for windows, any execute changes using os.chmod are\n no-ops per the python docs.\n \"\"\"\n ensure_dir(location)\n if filename.lower().endswith(\".gz\") or filename.lower().endswith(\".tgz\"):\n mode = \"r:gz\"\n elif filename.lower().endswith(BZ2_EXTENSIONS):\n mode = \"r:bz2\"\n elif filename.lower().endswith(XZ_EXTENSIONS):\n mode = \"r:xz\"\n elif filename.lower().endswith(\".tar\"):\n mode = \"r\"\n else:\n logger.warning(\n \"Cannot determine compression type for file %s\",\n filename,\n )\n mode = \"r:*\"\n\n tar = tarfile.open(filename, mode, encoding=\"utf-8\")\n try:\n leading = has_leading_dir([member.name for member in tar.getmembers()])\n\n # PEP 706 added `tarfile.data_filter`, and made some other changes to\n # Python's tarfile module (see below). The features were backported to\n # security releases.\n try:\n data_filter = tarfile.data_filter\n except AttributeError:\n _untar_without_filter(filename, location, tar, leading)\n else:\n default_mode_plus_executable = _get_default_mode_plus_executable()\n\n if leading:\n # Strip the leading directory from all files in the archive,\n # including hardlink targets (which are relative to the\n # unpack location).\n for member in tar.getmembers():\n name_lead, name_rest = split_leading_dir(member.name)\n member.name = name_rest\n if member.islnk():\n lnk_lead, lnk_rest = split_leading_dir(member.linkname)\n if lnk_lead == name_lead:\n member.linkname = lnk_rest\n\n def pip_filter(member: tarfile.TarInfo, path: str) -> tarfile.TarInfo:\n orig_mode = member.mode\n try:\n try:\n member = data_filter(member, location)\n except tarfile.LinkOutsideDestinationError:\n if sys.version_info[:3] in {\n (3, 8, 17),\n (3, 9, 17),\n (3, 10, 12),\n (3, 11, 4),\n }:\n # The tarfile filter in specific Python versions\n # raises LinkOutsideDestinationError on valid input\n # (https://github.com/python/cpython/issues/107845)\n # Ignore the error there, but do use the\n # more lax `tar_filter`\n member = tarfile.tar_filter(member, location)\n else:\n raise\n except tarfile.TarError as exc:\n message = \"Invalid member in the tar file {}: {}\"\n # Filter error messages mention the member name.\n # No need to add it here.\n raise InstallationError(\n message.format(\n filename,\n exc,\n )\n )\n if member.isfile() and orig_mode & 0o111:\n member.mode = default_mode_plus_executable\n else:\n # See PEP 706 note above.\n # The PEP changed this from `int` to `Optional[int]`,\n # where None means \"use the default\". Mypy doesn't\n # know this yet.\n member.mode = None # type: ignore [assignment]\n return member\n\n tar.extractall(location, filter=pip_filter)\n\n finally:\n tar.close()", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def iter_container_info(self, pending, include_steps, exclude):\n # \"pending\" is a list of arvados-cwl-runner container requests\n # returned by the API. This method fetches detailed\n # information about the runs and yields report rows.\n\n # 1. Get container records corresponding to container requests.\n containers = {}\n\n for container in arvados.util.keyset_list_all(\n self.arv_client.containers().list,\n filters=[\n [\"uuid\", \"in\", [c[\"container_uuid\"] for c in pending if c[\"container_uuid\"]]],\n ],\n select=[\"uuid\", \"started_at\", \"finished_at\", \"cost\"]):\n\n containers[container[\"uuid\"]] = container\n\n # 2. Look for the template_uuid property and fetch the\n # corresponding workflow record.\n workflows = {}\n workflows[\"none\"] = \"workflow run from command line\"\n\n for wf in arvados.util.keyset_list_all(\n self.arv_client.workflows().list,\n filters=[\n [\"uuid\", \"in\", list(set(c[\"properties\"][\"template_uuid\"]\n for c in pending\n if \"template_uuid\" in c[\"properties\"] and c[\"properties\"][\"template_uuid\"].startswith(self.arv_client.config()[\"ClusterID\"])))],\n ],\n select=[\"uuid\", \"name\"]):\n workflows[wf[\"uuid\"]] = wf[\"name\"]\n\n # 3. Look at owner_uuid and fetch owning projects and users\n projects = {}\n\n for pr in arvados.util.keyset_list_all(\n self.arv_client.groups().list,\n filters=[\n [\"uuid\", \"in\", list(set(c[\"owner_uuid\"] for c in pending if c[\"owner_uuid\"][6:11] == 'j7d0g'))],\n ],\n select=[\"uuid\", \"name\"]):\n projects[pr[\"uuid\"]] = pr[\"name\"]\n\n # 4. Look at owner_uuid and modified_by_user_uuid and get user records\n for pr in arvados.util.keyset_list_all(\n self.arv_client.users().list,\n filters=[\n [\"uuid\", \"in\", list(set(c[\"owner_uuid\"] for c in pending if c[\"owner_uuid\"][6:11] == 'tpzed')|set(c[\"modified_by_user_uuid\"] for c in pending))],\n ],\n select=[\"uuid\", \"full_name\", \"first_name\", \"last_name\"]):\n projects[pr[\"uuid\"]] = pr[\"full_name\"]\n\n # 5. Optionally iterate over individual workflow steps.\n if include_steps:\n name_regex = re.compile(r\"(.+)_[0-9]+\")\n child_crs = {}\n child_cr_containers = set()\n stepcount = 0\n\n # 5.1. Go through the container requests owned by the toplevel workflow container\n logging.info(\"Getting workflow steps\")\n for cr in arvados.util.keyset_list_all(\n self.arv_client.container_requests().list,\n filters=[\n [\"requesting_container_uuid\", \"in\", list(containers.keys())],\n ],\n select=[\"uuid\", \"name\", \"cumulative_cost\", \"requesting_container_uuid\", \"container_uuid\"]):\n\n if cr[\"cumulative_cost\"] == 0:\n continue\n\n g = name_regex.fullmatch(cr[\"name\"])\n if g:\n cr[\"name\"] = g[1]\n\n # 5.2. Get the containers corresponding to the\n # container requests. This has the same logic as\n # report_from_api where we batch it into 1000 items at\n # a time.\n child_crs.setdefault(cr[\"requesting_container_uuid\"], []).append(cr)\n child_cr_containers.add(cr[\"container_uuid\"])\n if len(child_cr_containers) == 1000:\n stepcount += len(child_cr_containers)\n for container in arvados.util.keyset_list_all(\n self.arv_client.containers().list,\n filters=[\n [\"uuid\", \"in\", list(child_cr_containers)],\n ],\n select=[\"uuid\", \"started_at\", \"finished_at\", \"cost\"]):\n\n containers[container[\"uuid\"]] = container\n\n logging.info(\"Got workflow steps %s - %s\", stepcount-len(child_cr_containers), stepcount)\n child_cr_containers.clear()\n\n # Get any remaining containers\n if child_cr_containers:\n stepcount += len(child_cr_containers)\n for container in arvados.util.keyset_list_all(\n self.arv_client.containers().list,\n filters=[\n [\"uuid\", \"in\", list(child_cr_containers)],\n ],\n select=[\"uuid\", \"started_at\", \"finished_at\", \"cost\"]):\n\n containers[container[\"uuid\"]] = container\n logging.info(\"Got workflow steps %s - %s\", stepcount-len(child_cr_containers), stepcount)\n\n # 6. Now go through the list of workflow runs, yield a row\n # with all the information we have collected, as well as the\n # details for each workflow step (if enabled)\n for container_request in pending:\n if not container_request[\"container_uuid\"] or not containers[container_request[\"container_uuid\"]][\"started_at\"] or not containers[container_request[\"container_uuid\"]][\"finished_at\"]:\n continue\n\n template_uuid = container_request[\"properties\"].get(\"template_uuid\", \"none\")\n workflowname = container_request[\"name\"] if template_uuid == \"none\" else workflows.get(template_uuid, template_uuid)\n\n if exclude and re.search(exclude, workflowname, flags=re.IGNORECASE):\n continue\n\n yield {\n \"Project\": projects.get(container_request[\"owner_uuid\"], \"unknown owner\"),\n \"ProjectUUID\": container_request[\"owner_uuid\"],\n \"Workflow\": workflowname,\n \"WorkflowUUID\": container_request[\"properties\"].get(\"template_uuid\", \"none\"),\n \"Step\": \"workflow runner\",\n \"StepUUID\": container_request[\"uuid\"],\n \"Sample\": container_request[\"name\"],\n \"SampleUUID\": container_request[\"uuid\"],\n \"User\": projects.get(container_request[\"modified_by_user_uuid\"], \"unknown user\"),\n \"UserUUID\": container_request[\"modified_by_user_uuid\"],\n \"Submitted\": csv_dateformat(container_request[\"created_at\"]),\n \"Started\": csv_dateformat(containers[container_request[\"container_uuid\"]][\"started_at\"]),\n \"Finished\": csv_dateformat(containers[container_request[\"container_uuid\"]][\"finished_at\"]),\n \"Runtime\": runtime_str(container_request, containers),\n \"Cost\": round(containers[container_request[\"container_uuid\"]][\"cost\"] if include_steps else container_request[\"cumulative_cost\"], 3),\n \"CumulativeCost\": round(container_request[\"cumulative_cost\"], 3)\n }\n\n if include_steps:\n for child_cr in child_crs.get(container_request[\"container_uuid\"], []):\n if not child_cr[\"container_uuid\"] or not containers[child_cr[\"container_uuid\"]][\"started_at\"] or not containers[child_cr[\"container_uuid\"]][\"finished_at\"]:\n continue\n yield {\n \"Project\": projects.get(container_request[\"owner_uuid\"], \"unknown owner\"),\n \"ProjectUUID\": container_request[\"owner_uuid\"],\n \"Workflow\": workflows.get(container_request[\"properties\"].get(\"template_uuid\", \"none\"), \"workflow missing\"),\n \"WorkflowUUID\": container_request[\"properties\"].get(\"template_uuid\", \"none\"),\n \"Step\": child_cr[\"name\"],\n \"StepUUID\": child_cr[\"uuid\"],\n \"Sample\": container_request[\"name\"],\n \"SampleUUID\": container_request[\"name\"],\n \"User\": projects.get(container_request[\"modified_by_user_uuid\"], \"unknown user\"),\n \"UserUUID\": container_request[\"modified_by_user_uuid\"],\n \"Submitted\": csv_dateformat(child_cr[\"created_at\"]),\n \"Started\": csv_dateformat(containers[child_cr[\"container_uuid\"]][\"started_at\"]),\n \"Finished\": csv_dateformat(containers[child_cr[\"container_uuid\"]][\"finished_at\"]),\n \"Runtime\": runtime_str(child_cr, containers),\n \"Cost\": round(containers[child_cr[\"container_uuid\"]][\"cost\"], 3),\n \"CumulativeCost\": round(containers[child_cr[\"container_uuid\"]][\"cost\"], 3),\n }", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "@contextlib.contextmanager\ndef get_docker_client() -> Generator[docker.DockerClient]:\n import docker\n\n def _client() -> ContextManager[docker.DockerClient]:\n return contextlib.closing(docker.DockerClient(base_url=f\"unix://{RAW_SOCKET_PATH}\"))\n\n with contextlib.ExitStack() as ctx:\n try:\n client = ctx.enter_context(_client())\n except docker.errors.DockerException:\n if DARWIN:\n if USE_COLIMA:\n click.echo(\"Attempting to start colima...\")\n gitroot = _gitroot()\n subprocess.check_call(\n (\n # explicitly use repo-local devenv, not the global one\n f\"{gitroot}/.venv/bin/devenv\",\n \"colima\",\n \"start\",\n )\n )\n elif USE_DOCKER_DESKTOP:\n click.echo(\"Attempting to start docker...\")\n subprocess.check_call(\n (\"open\", \"-a\", \"/Applications/Docker.app\", \"--args\", \"--unattended\")\n )\n elif USE_ORBSTACK:\n click.echo(\"Attempting to start orbstack...\")\n subprocess.check_call(\n (\"open\", \"-a\", \"/Applications/OrbStack.app\", \"--args\", \"--unattended\")\n )\n else:\n raise click.ClickException(\"Make sure docker is running.\")\n\n max_wait = 90\n timeout = time.monotonic() + max_wait\n\n click.echo(f\"Waiting for docker to be ready.... (timeout in {max_wait}s)\")\n while time.monotonic() < timeout:\n time.sleep(1)\n try:\n client = ctx.enter_context(_client())\n except docker.errors.DockerException:\n continue\n else:\n break\n else:\n raise click.ClickException(\"Failed to start docker.\")\n\n yield client", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __getitem__(self, item):\n max_window = self.max_result_window\n if isinstance(item, slice):\n if self._slice is None:\n clone = self.__clone()\n from_ = item.start or 0\n if item.stop is None:\n size = self.max_result_window - from_\n else:\n size = item.stop - from_\n\n if from_ + size > max_window:\n if from_ >= max_window:\n from_ = max_window\n size = 0\n else:\n size = max_window - from_\n clone._slice = (from_, size)\n return clone\n return self.__execute()[item]", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"} {"function": "@instrumented_task(\n name=\"sentry.integrations.github.tasks.open_pr_comment_workflow\", silo_mode=SiloMode.REGION\n)\ndef open_pr_comment_workflow(pr_id: int) -> None:\n logger.info(\"github.open_pr_comment.start_workflow\")\n\n # CHECKS\n # check PR exists to get PR key\n try:\n pull_request = PullRequest.objects.get(id=pr_id)\n except PullRequest.DoesNotExist:\n logger.info(\"github.open_pr_comment.pr_missing\")\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"missing_pr\"},\n )\n return\n\n # check org option\n org_id = pull_request.organization_id\n try:\n Organization.objects.get_from_cache(id=org_id)\n except Organization.DoesNotExist:\n logger.exception(\"github.open_pr_comment.org_missing\")\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"missing_org\"},\n )\n return\n\n # check PR repo exists to get repo name\n try:\n repo = Repository.objects.get(id=pull_request.repository_id)\n except Repository.DoesNotExist:\n logger.info(\"github.open_pr_comment.repo_missing\", extra={\"organization_id\": org_id})\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"missing_repo\"},\n )\n return\n\n # check integration exists to hit Github API with client\n integration = integration_service.get_integration(\n integration_id=repo.integration_id, status=ObjectStatus.ACTIVE\n )\n if not integration:\n logger.info(\"github.open_pr_comment.integration_missing\", extra={\"organization_id\": org_id})\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"missing_integration\"},\n )\n return\n\n installation = integration.get_installation(organization_id=org_id)\n assert isinstance(installation, CommitContextIntegration)\n\n client = installation.get_client()\n\n # CREATING THE COMMENT\n\n # fetch the files in the PR and determine if it is safe to comment\n pr_files = safe_for_comment(gh_client=client, repository=repo, pull_request=pull_request)\n\n if len(pr_files) == 0:\n logger.info(\n \"github.open_pr_comment.not_safe_for_comment\", extra={\"file_count\": len(pr_files)}\n )\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"unsafe_for_comment\"},\n )\n return\n\n pullrequest_files = get_pr_files(pr_files)\n\n issue_table_contents = {}\n top_issues_per_file = []\n\n patch_parsers = PATCH_PARSERS\n # NOTE: if we are testing beta patch parsers, add check here\n\n file_extensions = set()\n # fetch issues related to the files\n for file in pullrequest_files:\n projects, sentry_filenames = get_projects_and_filenames_from_source_file(\n org_id, repo.id, file.filename\n )\n if not len(projects) or not len(sentry_filenames):\n continue\n\n file_extension = file.filename.split(\".\")[-1]\n logger.info(\n \"github.open_pr_comment.file_extension\",\n extra={\n \"organization_id\": org_id,\n \"repository_id\": repo.id,\n \"extension\": file_extension,\n },\n )\n\n language_parser = patch_parsers.get(file.filename.split(\".\")[-1], None)\n if not language_parser:\n logger.info(\n \"github.open_pr_comment.missing_parser\", extra={\"extension\": file_extension}\n )\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"missing_parser\"),\n tags={\"extension\": file_extension},\n )\n continue\n\n function_names = language_parser.extract_functions_from_patch(file.patch)\n\n if file_extension in [\"js\", \"jsx\"]:\n logger.info(\n \"github.open_pr_comment.javascript\",\n extra={\n \"organization_id\": org_id,\n \"repository_id\": repo.id,\n \"extension\": file_extension,\n \"has_function_names\": bool(function_names),\n },\n )\n\n if file_extension == [\"php\"]:\n logger.info(\n \"github.open_pr_comment.php\",\n extra={\n \"organization_id\": org_id,\n \"repository_id\": repo.id,\n \"extension\": file_extension,\n \"has_function_names\": bool(function_names),\n },\n )\n\n if file_extension == [\"rb\"]:\n logger.info(\n \"github.open_pr_comment.ruby\",\n extra={\n \"organization_id\": org_id,\n \"repository_id\": repo.id,\n \"extension\": file_extension,\n \"has_function_names\": bool(function_names),\n },\n )\n\n if not len(function_names):\n continue\n\n top_issues = get_top_5_issues_by_count_for_file(\n list(projects), list(sentry_filenames), list(function_names)\n )\n if not len(top_issues):\n continue\n\n top_issues_per_file.append(top_issues)\n file_extensions.add(file_extension)\n\n issue_table_contents[file.filename] = get_issue_table_contents(top_issues)\n\n if not len(issue_table_contents):\n logger.info(\"github.open_pr_comment.no_issues\")\n # don't leave a comment if no issues for files in PR\n metrics.incr(OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"no_issues\"))\n return\n\n # format issues per file into comment\n issue_tables = []\n first_table = True\n for file in pullrequest_files:\n pr_filename = file.filename\n issue_table_content = issue_table_contents.get(pr_filename, None)\n\n if issue_table_content is None:\n continue\n\n if first_table:\n issue_table = format_issue_table(\n pr_filename, issue_table_content, patch_parsers, toggle=False\n )\n first_table = False\n else:\n # toggle all tables but the first one\n issue_table = format_issue_table(\n pr_filename, issue_table_content, patch_parsers, toggle=True\n )\n\n issue_tables.append(issue_table)\n\n comment_body = format_open_pr_comment(issue_tables)\n\n # list all issues in the comment\n issue_list: list[dict[str, Any]] = list(itertools.chain.from_iterable(top_issues_per_file))\n issue_id_list: list[int] = [issue[\"group_id\"] for issue in issue_list]\n\n # pick one language from the list of languages in the PR for analytics\n languages = [\n EXTENSION_LANGUAGE_MAP[extension]\n for extension in file_extensions\n if extension in EXTENSION_LANGUAGE_MAP\n ]\n language = languages[0] if len(languages) else \"not found\"\n\n try:\n installation.create_or_update_comment(\n repo=repo,\n pr_key=pull_request.key,\n comment_body=comment_body,\n pullrequest_id=pull_request.id,\n issue_list=issue_id_list,\n comment_type=CommentType.OPEN_PR,\n metrics_base=OPEN_PR_METRICS_BASE,\n language=language,\n )\n except ApiError as e:\n if e.json:\n if ISSUE_LOCKED_ERROR_MESSAGE in e.json.get(\"message\", \"\"):\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"issue_locked_error\"},\n )\n return\n\n elif RATE_LIMITED_MESSAGE in e.json.get(\"message\", \"\"):\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"rate_limited_error\"},\n )\n return\n\n metrics.incr(\n OPEN_PR_METRICS_BASE.format(integration=\"github\", key=\"error\"),\n tags={\"type\": \"api_error\"},\n )\n raise", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def convert_query_values(\n search_filters: ParsedTerms,\n projects: Sequence[Project],\n user: User | RpcUser | None,\n environments: Sequence[Environment] | None,\n value_converters=value_converters,\n allow_aggregate_filters=False,\n) -> list[SearchFilter]:\n \"\"\"\n Accepts a collection of SearchFilter objects and converts their values into\n a specific format, based on converters specified in `value_converters`.\n :param search_filters: Collection of `SearchFilter` objects.\n :param projects: List of projects being searched across\n :param user: The user making the search\n :param environments: The environments to consider when making the search\n :param value_converters: A dictionary of functions that convert search filter values into different formats.\n :return: New collection of `SearchFilters`, which may have converted values.\n \"\"\"\n\n def convert_search_filter(\n search_filter: SearchFilter, organization: Organization\n ) -> SearchFilter:\n if isinstance(search_filter, ParenExpression):\n return search_filter._replace(\n children=[\n child if isinstance(child, str) else convert_search_filter(child, organization)\n for child in search_filter.children\n ]\n )\n elif isinstance(search_filter, str):\n return search_filter\n\n if search_filter.key.name in value_converters:\n converter = value_converters[search_filter.key.name]\n new_value = converter(\n to_list(search_filter.value.raw_value), projects, user, environments\n )\n if isinstance(new_value, list):\n operator = \"IN\" if search_filter.operator in EQUALITY_OPERATORS else \"NOT IN\"\n else:\n operator = \"=\" if search_filter.operator in EQUALITY_OPERATORS else \"!=\"\n\n search_filter = search_filter._replace(\n value=SearchValue(new_value),\n operator=operator,\n )\n elif isinstance(search_filter, AggregateFilter) and not allow_aggregate_filters:\n raise InvalidSearchQuery(\n f\"Aggregate filters ({search_filter.key.name}) are not supported in issue searches.\"\n )\n\n return search_filter\n\n def expand_substatus_query_values(\n search_filters: ParsedTerms, org: Organization\n ) -> list[SearchFilter]:\n first_status_incl = None\n first_status_excl = None\n includes_status_filter = False\n includes_substatus_filter = False\n for search_filter in search_filters:\n if isinstance(search_filter, (ParenExpression, str)):\n continue\n if search_filter.key.name == \"substatus\":\n converted = convert_search_filter(search_filter, org)\n new_value = converted.value.raw_value\n status = GROUP_SUBSTATUS_TO_STATUS_MAP.get(\n new_value[0] if isinstance(new_value, list) else new_value\n )\n if first_status_incl is None and converted.operator in EQUALITY_OPERATORS:\n first_status_incl = SearchFilter(\n key=SearchKey(name=\"status\"), operator=\"IN\", value=SearchValue([status])\n )\n\n if first_status_excl is None and converted.operator in INEQUALITY_OPERATORS:\n first_status_excl = SearchFilter(\n key=SearchKey(name=\"status\"), operator=\"NOT IN\", value=SearchValue([status])\n )\n\n includes_substatus_filter = True\n\n if search_filter.key.name == \"status\":\n includes_status_filter = True\n\n if includes_status_filter:\n return search_filters\n\n if includes_substatus_filter:\n assert first_status_incl is not None or first_status_excl is not None\n return search_filters + [first_status_incl or first_status_excl]\n\n return search_filters\n\n organization = projects[0].organization\n\n expanded_filters = expand_substatus_query_values(search_filters, organization)\n\n return [convert_search_filter(filter, organization) for filter in expanded_filters]", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def download_file(self, url, destfile, digest=None, reporthook=None):\n \"\"\"\n This is a convenience method for downloading a file from an URL.\n Normally, this will be a file from the index, though currently\n no check is made for this (i.e. a file can be downloaded from\n anywhere).\n\n The method is just like the :func:`urlretrieve` function in the\n standard library, except that it allows digest computation to be\n done during download and checking that the downloaded data\n matched any expected value.\n\n :param url: The URL of the file to be downloaded (assumed to be\n available via an HTTP GET request).\n :param destfile: The pathname where the downloaded file is to be\n saved.\n :param digest: If specified, this must be a (hasher, value)\n tuple, where hasher is the algorithm used (e.g.\n ``'md5'``) and ``value`` is the expected value.\n :param reporthook: The same as for :func:`urlretrieve` in the\n standard library.\n \"\"\"\n if digest is None:\n digester = None\n logger.debug('No digest specified')\n else:\n if isinstance(digest, (list, tuple)):\n hasher, digest = digest\n else:\n hasher = 'md5'\n digester = getattr(hashlib, hasher)()\n logger.debug('Digest specified: %s' % digest)\n # The following code is equivalent to urlretrieve.\n # We need to do it this way so that we can compute the\n # digest of the file as we go.\n with open(destfile, 'wb') as dfp:\n # addinfourl is not a context manager on 2.x\n # so we have to use try/finally\n sfp = self.send_request(Request(url))\n try:\n headers = sfp.info()\n blocksize = 8192\n size = -1\n read = 0\n blocknum = 0\n if \"content-length\" in headers:\n size = int(headers[\"Content-Length\"])\n if reporthook:\n reporthook(blocknum, blocksize, size)\n while True:\n block = sfp.read(blocksize)\n if not block:\n break\n read += len(block)\n dfp.write(block)\n if digester:\n digester.update(block)\n blocknum += 1\n if reporthook:\n reporthook(blocknum, blocksize, size)\n finally:\n sfp.close()\n\n # check that we got the whole file, if we can\n if size >= 0 and read < size:\n raise DistlibException(\n 'retrieval incomplete: got only %d out of %d bytes'\n % (read, size))\n # if we have a digest, it must match.\n if digester:\n actual = digester.hexdigest()\n if digest != actual:\n raise DistlibException('%s digest mismatch for %s: expected '\n '%s, got %s' % (hasher, destfile,\n digest, actual))\n logger.debug('Digest verified: %s', digest)", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def CreateInternalSegmentListFromJson(self, segmentListJson):\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.ExportOperationData entered\\n\", 100)\n\n if self.SegmentDefinitionFormat == \"two geometric points\": \n self.ValidateJsonSegmentList(segmentListJson)\n self.SegmentList = []\n self.NearbyGeometryPointList = []\n if PhactoriDbg(100):\n myDebugPrint3(\"format: \" + str(self.SegmentDefinitionFormat) + \"\\n\")\n for item in segmentListJson:\n newSegment = PhactoriSegment()\n newSegment.SetPoints(item[0], item[1])\n self.SegmentList.append(newSegment)\n self.NearbyGeometryPointList.append(item[0])\n elif self.SegmentDefinitionFormat == \"geometric point and nearest cell\":\n self.ValidateJsonSegmentList2(segmentListJson)\n nearbyGeometryPoints = []\n segmentLengths = []\n for item in segmentListJson:\n nearbyGeometryPoints.append(item[0])\n segmentLengths.append(item[1])\n self.NearbyGeometryPointList = nearbyGeometryPoints\n\n nearbyCellPoints = self.GetListOfCellTestPointsNearestListOfPoints(nearbyGeometryPoints)\n #use some vector math to construct the segments from the seed points\n #and the nearest cell to each seed point\n self.SegmentList = []\n if PhactoriDbg(100):\n myDebugPrint3(\"(unstructured) format: \" + str(self.SegmentDefinitionFormat) + \"\\n\")\n for ii in range(0,len(nearbyGeometryPoints)):\n seedPoint = nearbyGeometryPoints[ii]\n segmentPointA = nearbyCellPoints[ii]\n SeedToCell = vecFromAToB(seedPoint, segmentPointA)\n SeedToCellNorm = vecNormalize(SeedToCell)\n segmentPointB = vecMultiplyAdd(segmentPointA, SeedToCellNorm, segmentLengths[ii])\n if PhactoriDbg(100):\n myDebugPrint3(\"segment \" + str(ii) + \"\\n\", 100)\n myDebugPrint3(\"seedPoint: \" + str(seedPoint) + \"\\n\")\n myDebugPrint3(\"closest cell point: \" + str(segmentPointA) + \"\\n\")\n myDebugPrint3(\"SeedToCellNorm: \" + str(SeedToCellNorm) + \"\\n\")\n myDebugPrint3(\"segmentPointB: \" + str(segmentPointB) + \"\\n\")\n newSegment = PhactoriSegment()\n newSegment.SetPoints(segmentPointA, segmentPointB)\n self.SegmentList.append(newSegment)\n elif self.SegmentDefinitionFormat == \"geometric point and nearest cell and direction\":\n self.ValidateJsonSegmentList3(segmentListJson)\n nearbyGeometryPoints = []\n segmentLengths = []\n directionVecs = []\n for item in segmentListJson:\n nearbyGeometryPoints.append(item[0])\n directionVecs.append(item[1])\n segmentLengths.append(item[2])\n self.NearbyGeometryPointList = nearbyGeometryPoints\n\n nearbyCellPoints = self.GetListOfCellTestPointsNearestListOfPoints(nearbyGeometryPoints)\n self.SegmentList = []\n if PhactoriDbg(100):\n myDebugPrint3(\"format: \" + str(self.SegmentDefinitionFormat) + \"\\n\")\n for ii in range(0,len(nearbyGeometryPoints)):\n segmentPointA = nearbyCellPoints[ii]\n directionVecNorm = vecNormalize(directionVecs[ii])\n segmentPointB = vecMultiplyAdd(segmentPointA, directionVecNorm, segmentLengths[ii])\n if PhactoriDbg(100):\n myDebugPrint3(\"seedPoint: \" + str(nearbyGeometryPoints[ii]) + \"\\n\")\n myDebugPrint3(\"segmentPointA (nearest cell point): \" + str(seedPoint) + \"\\n\")\n myDebugPrint3(\"directionVecNorm: \" + str(directionVecNorm) + \"\\n\")\n myDebugPrint3(\"segmentPointB: \" + str(segmentPointB) + \"\\n\")\n newSegment = PhactoriSegment()\n newSegment.SetPoints(segmentPointA, segmentPointB)\n self.SegmentList.append(newSegment)\n else:\n myDebugPrint3AndException(\"bad self.SegmentDefinitionFormat\\n\")\n\n if PhactoriDbg(100):\n myDebugPrint3(\"PhactoriSegmentCellSampler3.ExportOperationData returning\\n\", 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "@config.command()\n@click.option(\n \"--flags\",\n \"-f\",\n default=0,\n help=(\n \"The flags we want to filter. This is supposed to be a disjunction \"\n \"of all required flags. All the flags provided have to be present in \"\n \"the option definition.\"\n ),\n)\n@click.option(\n \"--only-set\",\n \"-s\",\n is_flag=True,\n default=False,\n help=\"Skip options that are not set in DB/setting fi this flag is set.\",\n)\n@click.option(\n \"--pretty-print\",\n is_flag=True,\n default=False,\n help=\"Prints the options in (key) : (value) format.\",\n)\n@configuration\ndef dump(flags: int, only_set: bool, pretty_print: bool) -> None:\n \"\"\"\n Dump the values of all options except for those flagged as credential.\n For each option it provides name, value, last update channel, whether\n the option is set on the DB or disk.\n \"\"\"\n from django.conf import settings\n\n from sentry import options\n\n all_options = options.all()\n\n for opt in all_options:\n if not flags or (flags & opt.flags == flags):\n is_set = options.isset(opt.name)\n set_on_disk = settings.SENTRY_OPTIONS.get(opt.name)\n value = options.get(opt.name)\n is_credential = opt.has_any_flag({options.FLAG_CREDENTIAL})\n last_update_channel = options.get_last_update_channel(opt.name)\n\n if not only_set or (only_set and is_set):\n if is_credential:\n click.echo(\n f\"Option: {opt.name} is a credential. Skipping. Not showing this to you.\"\n )\n\n if pretty_print:\n click.echo(f\"{opt.name} : {value}\")\n else:\n click.echo(\n f\"Option: {opt.name}. Set: {is_set}. Set in settings: \"\n f\"{set_on_disk is not None}. \"\n f\"Last channel: {last_update_channel.value if last_update_channel else 'None'}. \"\n f\"Value: {value}\"\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def main():\n args = parse_args()\n\n msg_it = bt2.TraceCollectionMessageIterator(args.trace)\n last_event_ns_from_origin = None\n timeline = []\n\n def get_thread(name):\n for t in timeline:\n if t.get('name', None) == name and t.get('in', 0 ) != 0 and not t.get('out', None):\n return t\n return {}\n\n for msg in msg_it:\n\n if not isinstance(msg, bt2._EventMessageConst):\n continue\n\n ns_from_origin = msg.default_clock_snapshot.ns_from_origin\n event = msg.event\n # Compute the time difference since the last event message.\n diff_s = 0\n\n if last_event_ns_from_origin is not None:\n diff_s = (ns_from_origin - last_event_ns_from_origin) / 1e9\n\n dt = datetime.datetime.fromtimestamp(ns_from_origin / 1e9)\n\n if event.name in [\n 'thread_switched_out',\n 'thread_switched_in',\n 'thread_pending',\n 'thread_ready',\n 'thread_resume',\n 'thread_suspend',\n 'thread_create',\n 'thread_abort'\n ]:\n\n cpu = event.payload_field.get(\"cpu\", None)\n thread_id = event.payload_field.get(\"thread_id\", None)\n thread_name = event.payload_field.get(\"name\", None)\n\n th = {}\n if event.name in ['thread_switched_out', 'thread_switched_in'] and cpu is not None:\n cpu_string = f\"(cpu: {cpu})\"\n else:\n cpu_string = \"\"\n\n if thread_name:\n print(f\"{dt} (+{diff_s:.6f} s): {event.name}: {thread_name} {cpu_string}\")\n elif thread_id:\n print(f\"{dt} (+{diff_s:.6f} s): {event.name}: {thread_id} {cpu_string}\")\n else:\n print(f\"{dt} (+{diff_s:.6f} s): {event.name}\")\n\n if event.name in ['thread_switched_out', 'thread_switched_in']:\n if thread_name:\n th = get_thread(thread_name)\n if not th:\n th['name'] = thread_name\n else:\n th = get_thread(thread_id)\n if not th:\n th['name'] = thread_id\n\n if event.name in ['thread_switched_out']:\n th['out'] = ns_from_origin\n tin = th.get('in', None)\n tout = th.get('out', None)\n if tout is not None and tin is not None:\n diff = (tout - tin)\n th['runtime'] = diff\n elif event.name in ['thread_switched_in']:\n th['in'] = ns_from_origin\n\n timeline.append(th)\n\n elif event.name in ['thread_info']:\n stack_size = event.payload_field['stack_size']\n print(f\"{dt} (+{diff_s:.6f} s): {event.name} (Stack size: {stack_size})\")\n elif event.name in ['start_call', 'end_call']:\n if event.payload_field['id'] == 39:\n c = Fore.GREEN\n elif event.payload_field['id'] in [37, 38]:\n c = Fore.CYAN\n else:\n c = Fore.YELLOW\n print(c + f\"{dt} (+{diff_s:.6f} s): {event.name} {event.payload_field['id']}\" + Fore.RESET)\n elif event.name in ['semaphore_init', 'semaphore_take', 'semaphore_give']:\n c = Fore.CYAN\n print(c + f\"{dt} (+{diff_s:.6f} s): {event.name} ({event.payload_field['id']})\" + Fore.RESET)\n elif event.name in ['mutex_init', 'mutex_take', 'mutex_give']:\n c = Fore.MAGENTA\n print(c + f\"{dt} (+{diff_s:.6f} s): {event.name} ({event.payload_field['id']})\" + Fore.RESET)\n\n else:\n print(f\"{dt} (+{diff_s:.6f} s): {event.name}\")\n\n last_event_ns_from_origin = ns_from_origin", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def showTransponderInformation(self):\n\t\tdef getValue(key, default):\n\t\t\tvalueLive = frontendLive.get(key, default)\n\t\t\tvalueConfig = frontendConfig.get(key, default)\n\t\t\treturn valueLive if valueLive == valueConfig else f\"{valueLive} ({valueConfig})\"\n\n\t\tdef getDVBCFrequencyValue():\n\t\t\tvalueLive = frontendLive.get(\"frequency\", 0) / 1000.0\n\t\t\tvalueConfig = frontendConfig.get(\"frequency\", 0) / 1000.0\n\t\t\treturn f\"{valueLive:.3f} {mhz}\" if valueLive == valueConfig else f\"{valueLive:.3f} {mhz} ({valueConfig:.3f} {mhz})\"\n\n\t\tdef getSymbolRateValue():\n\t\t\tvalueLive = frontendLive.get(\"symbol_rate\", 0) // 1000\n\t\t\tvalueConfig = frontendConfig.get(\"symbol_rate\", 0) // 1000\n\t\t\treturn f\"{valueLive} {_('KSymb/s')}\" if valueLive == valueConfig else f\"{valueLive} {_('KSymb/s')} ({valueConfig} {_('KSymb/s')})\"\n\n\t\tdef getDVBSFrequencyValue():\n\t\t\tvalueLive = frontendLive.get(\"frequency\", 0) // 1000\n\t\t\tvalueConfig = frontendConfig.get(\"frequency\", 0) // 1000\n\t\t\treturn f\"{valueLive} {mhz}\" if valueLive == valueConfig else f\"{valueLive} {mhz} ({valueConfig} {mhz})\"\n\n\t\tdef getInputStreamID():\n\t\t\tvalueLive = frontendLive.get(\"is_id\", -1)\n\t\t\tif valueLive == -1:\n\t\t\t\tvalueLive = na\n\t\t\tvalueConfig = frontendConfig.get(\"is_id\", -1)\n\t\t\tif valueConfig == -1:\n\t\t\t\tvalueConfig = na\n\t\t\treturn valueLive if valueLive == valueConfig else f\"{valueLive} ({valueConfig})\"\n\n\t\tdef getFrequencyValue():\n\t\t\tvalueLive = frontendLive.get(\"frequency\", 0) / 1000000.0\n\t\t\tvalueConfig = frontendConfig.get(\"frequency\", 0) / 1000000.0\n\t\t\treturn f\"{valueLive:.3f} {mhz}\" if valueLive == valueConfig else f\"{valueLive:.3f} {mhz} ({valueConfig:.3f} {mhz})\"\n\n\t\tinfo = []\n\t\tinfo.append(formatLine(\"H\", _(\"Transponder information for '%s'\") % self.serviceName))\n\t\tinfo.append(\"\")\n\t\tif self.frontendInfo:\n\t\t\tfrontendLive = self.frontendInfo and self.frontendInfo.getAll(False)\n\t\t\tfrontendConfig = self.frontendInfo and self.frontendInfo.getAll(True)\n\t\telse:\n\t\t\tfrontendLive = self.transponderInfo\n\t\t\tfrontendConfig = self.transponderInfo\n\t\tif frontendLive and len(frontendLive) and frontendConfig and len(frontendConfig):\n\t\t\ttunerType = frontendLive[\"tuner_type\"]\n\t\t\tfrontendLive = ConvertToHumanReadable(frontendLive)\n\t\t\tfrontendConfig = ConvertToHumanReadable(frontendConfig)\n\t\t\tna = _(\"N/A\")\n\t\t\tmhz = _(\"MHz\")\n\t\t\tif not self.transponderInfo:\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"NIM\"), f\"{chr(ord('A') + frontendLive.get('tuner_number', 0))}\"))\n\t\t\tinfo.append(formatLine(\"P1\", _(\"Type\"), f\"{frontendLive.get('tuner_type', na)} [{tunerType}]\"))\n\t\t\tif tunerType == \"DVB-C\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Modulation\"), getValue(\"modulation\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Frequency\"), getDVBCFrequencyValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Symbol rate\"), getSymbolRateValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Forward Error Correction (FEC)\"), getValue(\"fec_inner\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Inversion\"), getValue(\"inversion\", na)))\n\t\t\telif tunerType == \"DVB-S\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"System\"), getValue(\"system\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Modulation\"), getValue(\"modulation\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Orbital position\"), getValue(\"orbital_position\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Frequency\"), getDVBSFrequencyValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Polarization\"), getValue(\"polarization\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Symbol rate\"), getSymbolRateValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Forward Error Correction (FEC)\"), getValue(\"fec_inner\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Inversion\"), getValue(\"inversion\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Pilot\"), getValue(\"pilot\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Roll-off\"), getValue(\"rolloff\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Input Stream ID\"), getInputStreamID()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"PLS Mode\"), getValue(\"pls_mode\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"PLS Code\"), getValue(\"pls_code\", 0)))\n\t\t\t\tvalueLive = frontendLive.get(\"t2mi_plp_id\", -1)\n\t\t\t\tvalueConfig = frontendConfig.get(\"t2mi_plp_id\", -1)\n\t\t\t\tif valueLive != -1 or valueConfig != -1:\n\t\t\t\t\tinfo.append(formatLine(\"P1\", _(\"T2MI PLP ID\"), f\"{valueLive}\" if valueLive == valueConfig else f\"{valueLive} ({valueConfig})\"))\n\t\t\t\tvalueLive = None if frontendLive.get(\"t2mi_plp_id\", -1) == -1 else frontendLive.get(\"t2mi_pid\", eDVBFrontendParametersSatellite.T2MI_Default_Pid)\n\t\t\t\tvalueConfig = None if frontendConfig.get(\"t2mi_plp_id\", -1) == -1 else frontendConfig.get(\"t2mi_pid\", eDVBFrontendParametersSatellite.T2MI_Default_Pid)\n\t\t\t\tif valueLive or valueConfig:\n\t\t\t\t\tinfo.append(formatLine(\"P1\", _(\"T2MI PID\"), f\"{valueLive or 'None'}\" if valueLive == valueConfig else f\"{valueLive or 'None'} ({valueConfig or 'None'})\"))\n\t\t\telif tunerType == \"DVB-T\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Frequency\"), getFrequencyValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Channel\"), getValue(\"channel\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Inversion\"), getValue(\"inversion\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Bandwidth\"), getValue(\"bandwidth\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Code rate LP\"), getValue(\"code_rate_lp\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Code rate HP\"), getValue(\"code_rate_hp\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Guard Interval\"), getValue(\"guard_interval\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Constellation\"), getValue(\"constellation\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Transmission mode\"), getValue(\"transmission_mode\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Hierarchy info\"), getValue(\"hierarchy_information\", na)))\n\t\t\telif tunerType == \"ATSC\":\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"System\"), getValue(\"system\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Modulation\"), getValue(\"modulation\", na)))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Frequency\"), getFrequencyValue()))\n\t\t\t\tinfo.append(formatLine(\"P1\", _(\"Inversion\"), getValue(\"inversion\", na)))\n\t\telse:\n\t\t\tinfo.append(formatLine(\"M0\", _(\"Tuner data is not available!\")))\n\t\treturn info", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def enumerateNetworkMounts(self, refresh=False):\n\t\tprint(\"[Harddisk] Enumerating network mounts...\")\n\t\tfor mount in (\"net\", \"autofs\"):\n\t\t\tnetMounts = (exists(join(\"/media\", mount)) and listdir(join(\"/media\", mount))) or []\n\t\t\tfor netMount in netMounts:\n\t\t\t\tpath = join(\"/media\", mount, netMount, \"\")\n\t\t\t\tif ismount(path):\n\t\t\t\t\tpartition = Partition(mountpoint=path, description=netMount)\n\t\t\t\t\tif str(partition) not in [str(x) for x in self.partitions]:\n\t\t\t\t\t\tprint(f\"[Harddisk] New network mount {mount}->{path}.\")\n\t\t\t\t\t\tif refresh:\n\t\t\t\t\t\t\tself.addMountedPartition(device=path, desc=netMount)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.partitions.append(partition)\n\t\tif ismount(\"/media/hdd\") and \"/media/hdd/\" not in [x.mountpoint for x in self.partitions]:\n\t\t\tprint(\"[Harddisk] New network mount being used as HDD replacement -> '/media/hdd/'.\")\n\t\t\tif refresh:\n\t\t\t\tself.addMountedPartition(device=\"/media/hdd/\", desc=\"/media/hdd/\")\n\t\t\telse:\n\t\t\t\tself.partitions.append(Partition(mountpoint=\"/media/hdd/\", description=\"/media/hdd\"))", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def predefinedTranspondersList(self, orbpos):\n\t\tdefault = None\n\t\tif orbpos is not None:\n\t\t\tlist = []\n\t\t\tif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:\n\t\t\t\tfec = self.scan_sat.fec_s2.value\n\t\t\telse:\n\t\t\t\tfec = self.scan_sat.fec.value\n\n\t\t\tcompare = [\n\t\t\t\t0, # DVB type\n\t\t\t\tself.scan_sat.frequency.value * 1000, # 1\n\t\t\t\tself.scan_sat.symbolrate.value * 1000, # 2\n\t\t\t\tself.scan_sat.polarization.value, # 3\n\t\t\t\tfec, # 4\n\t\t\t\tself.scan_sat.system.value, # 5\n\t\t\t\tself.scan_sat.modulation.value, # 6\n\t\t\t\tself.scan_sat.inversion.value, # 7\n\t\t\t\tself.scan_sat.rolloff.value, # 8\n\t\t\t\tself.scan_sat.pilot.value, # 9\n\t\t\t\tself.scan_sat.is_id.value, # 10\n\t\t\t\tself.scan_sat.pls_mode.value, # 11\n\t\t\t\tself.scan_sat.pls_code.value, # 12\n\t\t\t\tself.scan_sat.t2mi_plp_id.value, # 13\n\t\t\t\tself.scan_sat.t2mi_pid.value # 14\n\t\t\t\t# tsid\n\t\t\t\t# onid\n\t\t\t]\n\t\t\ti = 0\n\t\t\ttps = nimmanager.getTransponders(orbpos)\n\t\t\tfor tp in tps:\n\t\t\t\tif tp[0] == 0:\n\t\t\t\t\tif default is None and self.compareTransponders(tp, compare):\n\t\t\t\t\t\tdefault = str(i)\n\t\t\t\t\tlist.append((str(i), self.humanReadableTransponder(tp)))\n\t\t\t\t\ti += 1\n\t\t\tif self.preDefTransponders is None:\n\t\t\t\tself.preDefTransponders = ConfigSelection(choices=list, default=default)\n\t\t\telse:\n\t\t\t\tself.preDefTransponders.setChoices(choices=list, default=default)\n\n\t\treturn default", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def create_vcrecord(self, cred_dict: dict) -> VCRecord:\n \"\"\"Return VCRecord from a credential dict.\"\"\"\n proofs = cred_dict.get(\"proof\") or []\n proof_types = None\n if isinstance(proofs, dict):\n proofs = [proofs]\n if proofs:\n proof_types = [proof.get(\"type\") for proof in proofs]\n contexts = [ctx for ctx in cred_dict.get(\"@context\") if isinstance(ctx, str)]\n if \"@graph\" in cred_dict:\n for enclosed_data in cred_dict.get(\"@graph\"):\n if (\n enclosed_data[\"id\"].startswith(\"urn:\")\n and \"credentialSubject\" in enclosed_data\n ):\n cred_dict.update(enclosed_data)\n del cred_dict[\"@graph\"]\n break\n given_id = cred_dict.get(\"id\")\n if given_id and self.check_if_cred_id_derived(given_id):\n given_id = str(uuid4())\n # issuer\n issuer = cred_dict.get(\"issuer\")\n if isinstance(issuer, dict):\n issuer = issuer.get(\"id\")\n\n # subjects\n subject_ids = None\n subjects = cred_dict.get(\"credentialSubject\")\n if subjects:\n if isinstance(subjects, dict):\n subjects = [subjects]\n subject_ids = [subject.get(\"id\") for subject in subjects if (\"id\" in subject)]\n else:\n cred_dict[\"credentialSubject\"] = {}\n\n # Schemas\n schemas = cred_dict.get(\"credentialSchema\", [])\n if isinstance(schemas, dict):\n schemas = [schemas]\n schema_ids = [schema.get(\"id\") for schema in schemas]\n document_loader = self.profile.inject(DocumentLoader)\n expanded = jsonld.expand(cred_dict, options={\"documentLoader\": document_loader})\n types = JsonLdProcessor.get_values(\n expanded[0],\n \"@type\",\n )\n return VCRecord(\n contexts=contexts,\n expanded_types=types,\n issuer_id=issuer,\n subject_ids=subject_ids,\n proof_types=proof_types,\n given_id=given_id,\n cred_value=cred_dict,\n schema_ids=schema_ids,\n )", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "async def on_cluster_heartbeat(self, cluster_name, msg) -> None:\n # pylint: disable=no-else-continue, unused-variable, too-many-branches\n # pylint: disable=too-many-statements\n assert isinstance(self.log, logging.Logger) # nosec\n\n # HACK: we override the base class heartbeat in order to\n # dynamically allow for more or less workers depending on the\n # available docker nodes!!!\n cluster = self.db.get_cluster(cluster_name)\n if cluster is None or cluster.target > JobStatus.RUNNING:\n return\n\n cluster.last_heartbeat = timestamp()\n\n if cluster.status == JobStatus.RUNNING:\n cluster_update = {}\n else:\n cluster_update = {\n \"api_address\": msg[\"api_address\"],\n \"scheduler_address\": msg[\"scheduler_address\"],\n \"dashboard_address\": msg[\"dashboard_address\"],\n }\n\n count = msg[\"count\"]\n active_workers = set(msg[\"active_workers\"])\n closing_workers = set(msg[\"closing_workers\"])\n closed_workers = set(msg[\"closed_workers\"])\n\n self.log.info(\n \"Cluster %s heartbeat [count: %d, n_active: %d, n_closing: %d, n_closed: %d]\",\n cluster_name,\n count,\n len(active_workers),\n len(closing_workers),\n len(closed_workers),\n )\n\n # THIS IS THE HACK!!!\n # original code in dask_gateway_server.backend.db_base\n max_workers = cluster.config.get(\"cluster_max_workers\")\n if self.settings.GATEWAY_SERVER_ONE_WORKER_PER_NODE:\n # cluster_max_workers = len(await get_cluster_information(self.docker_client))\n # if max_workers != cluster_max_workers:\n # unfrozen_cluster_config = {k: v for k, v in cluster.config.items()}\n # unfrozen_cluster_config[\"cluster_max_workers\"] = cluster_max_workers\n # cluster_update[\"config\"] = unfrozen_cluster_config\n max_workers = len(await get_cluster_information(self.docker_client))\n if max_workers is not None and count > max_workers:\n # This shouldn't happen under normal operation, but could if the\n # user does something malicious (or there's a bug).\n self.log.info(\n \"Cluster %s heartbeat requested %d workers, exceeding limit of %s.\",\n cluster_name,\n count,\n max_workers,\n )\n count = max_workers\n\n if count != cluster.count:\n cluster_update[\"count\"] = count\n\n created_workers = []\n submitted_workers = []\n target_updates = []\n newly_running = []\n close_expected = []\n for worker in cluster.workers.values():\n if worker.status >= JobStatus.STOPPED:\n continue\n if worker.name in closing_workers:\n if worker.status < JobStatus.RUNNING:\n newly_running.append(worker)\n close_expected.append(worker)\n elif worker.name in active_workers:\n if worker.status < JobStatus.RUNNING:\n newly_running.append(worker)\n elif worker.name in closed_workers:\n target = (\n JobStatus.STOPPED if worker.close_expected else JobStatus.FAILED\n )\n target_updates.append((worker, {\"target\": target}))\n elif worker.status == JobStatus.SUBMITTED:\n submitted_workers.append(worker)\n else:\n assert worker.status == JobStatus.CREATED\n created_workers.append(worker)\n\n n_pending = len(created_workers) + len(submitted_workers)\n n_to_stop = len(active_workers) + n_pending - count\n if n_to_stop > 0:\n for w in islice(chain(created_workers, submitted_workers), n_to_stop):\n target_updates.append((w, {\"target\": JobStatus.STOPPED}))\n\n if cluster_update:\n self.db.update_cluster(cluster, **cluster_update)\n self.queue.put(cluster)\n\n self.db.update_workers(target_updates)\n for w, _u in target_updates:\n self.queue.put(w)\n\n if newly_running:\n # At least one worker successfully started, reset failure count\n cluster.worker_start_failure_count = 0\n self.db.update_workers(\n [(w, {\"status\": JobStatus.RUNNING}) for w in newly_running]\n )\n for w in newly_running:\n self.log.info(\"Worker %s is running\", w.name)\n\n self.db.update_workers([(w, {\"close_expected\": True}) for w in close_expected])", "smellKey": "S3776", "smellId": null, "repo": "ITISFoundation_osparc-simcore", "language": "python"} {"function": "def _get_new_credentials(\n self,\n original_url: str,\n *,\n allow_netrc: bool = True,\n allow_keyring: bool = False,\n ) -> AuthInfo:\n \"\"\"Find and return credentials for the specified URL.\"\"\"\n # Split the credentials and netloc from the url.\n url, netloc, url_user_password = split_auth_netloc_from_url(\n original_url,\n )\n\n # Start with the credentials embedded in the url\n username, password = url_user_password\n if username is not None and password is not None:\n logger.debug(\"Found credentials in url for %s\", netloc)\n return url_user_password\n\n # Find a matching index url for this request\n index_url = self._get_index_url(url)\n if index_url:\n # Split the credentials from the url.\n index_info = split_auth_netloc_from_url(index_url)\n if index_info:\n index_url, _, index_url_user_password = index_info\n logger.debug(\"Found index url %s\", index_url)\n\n # If an index URL was found, try its embedded credentials\n if index_url and index_url_user_password[0] is not None:\n username, password = index_url_user_password\n if username is not None and password is not None:\n logger.debug(\"Found credentials in index url for %s\", netloc)\n return index_url_user_password\n\n # Get creds from netrc if we still don't have them\n if allow_netrc:\n netrc_auth = get_netrc_auth(original_url)\n if netrc_auth:\n logger.debug(\"Found credentials in netrc for %s\", netloc)\n return netrc_auth\n\n # If we don't have a password and keyring is available, use it.\n if allow_keyring:\n # The index url is more specific than the netloc, so try it first\n # fmt: off\n kr_auth = (\n self._get_keyring_auth(index_url, username) or\n self._get_keyring_auth(netloc, username)\n )\n # fmt: on\n if kr_auth:\n logger.debug(\"Found credentials in keyring for %s\", netloc)\n return kr_auth\n\n return username, password", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def typed_dict_update_signature_callback(ctx: MethodSigContext) -> CallableType:\n \"\"\"Try to infer a better signature type for methods that update `TypedDict`.\n\n This includes: `TypedDict.update`, `TypedDict.__or__`, `TypedDict.__ror__`,\n and `TypedDict.__ior__`.\n \"\"\"\n signature = ctx.default_signature\n if isinstance(ctx.type, TypedDictType) and len(signature.arg_types) == 1:\n arg_type = get_proper_type(signature.arg_types[0])\n if not isinstance(arg_type, TypedDictType):\n return signature\n arg_type = arg_type.as_anonymous()\n arg_type = arg_type.copy_modified(required_keys=set())\n if ctx.args and ctx.args[0]:\n if signature.name in _TP_DICT_MUTATING_METHODS:\n # If we want to mutate this object in place, we need to set this flag,\n # it will trigger an extra check in TypedDict's checker.\n arg_type.to_be_mutated = True\n with ctx.api.msg.filter_errors(\n filter_errors=lambda name, info: info.code != codes.TYPEDDICT_READONLY_MUTATED,\n save_filtered_errors=True,\n ):\n inferred = get_proper_type(\n ctx.api.get_expression_type(ctx.args[0][0], type_context=arg_type)\n )\n if arg_type.to_be_mutated:\n arg_type.to_be_mutated = False # Done!\n possible_tds = []\n if isinstance(inferred, TypedDictType):\n possible_tds = [inferred]\n elif isinstance(inferred, UnionType):\n possible_tds = [\n t\n for t in get_proper_types(inferred.relevant_items())\n if isinstance(t, TypedDictType)\n ]\n items = []\n for td in possible_tds:\n item = arg_type.copy_modified(\n required_keys=(arg_type.required_keys | td.required_keys)\n & arg_type.items.keys()\n )\n if not ctx.api.options.extra_checks:\n item = item.copy_modified(item_names=list(td.items))\n items.append(item)\n if items:\n arg_type = make_simplified_union(items)\n return signature.copy_modified(arg_types=[arg_type])\n return signature", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def opkgCallback(self, event, parameter):\n\t\tdef modificationCallback(answer):\n\t\t\tself.opkg.write(\"N\" if answer else \"Y\")\n\n\t\tif event == OpkgComponent.EVENT_DOWNLOAD:\n\t\t\tself.downloadCount += 1\n\t\t\tif parameter.find(\"_\") == -1: # Only display the downloading of the feed packages.\n\t\t\t\tself[\"update\"].appendText(f\"{_(\"Downloading\")}: '{parameter}'.\\n\")\n\t\telif event == OpkgComponent.EVENT_UPDATED:\n\t\t\tself.updateCount += 1\n\t\t\tself[\"update\"].appendText(f\"{_(\"Updated\")}: {parameter}\\n\")\n\t\telif event == OpkgComponent.EVENT_UPVERSION:\n\t\t\tself.upgradeCount += 1\n\t\t\tself[\"update\"].appendText(f\"{_(\"Updating\")} {self.upgradeCount}/{self.packageTotal}: '{parameter}'.\\n\")\n\t\t\tif \"enigma2-plugin-skins-metrix-atv\" in parameter:\n\t\t\t\tself.metrixUpdated = True\n\t\telif event == OpkgComponent.EVENT_INSTALL:\n\t\t\tself.installCount += 1\n\t\t\tself[\"update\"].appendText(f\"{_(\"Installing\")}: '{parameter}'.\\n\")\n\t\telif event == OpkgComponent.EVENT_REMOVE:\n\t\t\tself.removeCount += 1\n\t\t\tself[\"update\"].appendText(f\"{_(\"Removing\")}: '{parameter}'.\\n\")\n\t\telif event == OpkgComponent.EVENT_CONFIGURING:\n\t\t\tself.configureCount += 1\n\t\t\tself[\"update\"].appendText(f\"{_(\"Configuring\")}: '{parameter}'.\\n\")\n\t\telif event == OpkgComponent.EVENT_MODIFIED:\n\t\t\tif config.plugins.softwaremanager.overwriteConfigFiles.value in (\"N\", \"Y\"):\n\t\t\t\tself.opkg.write(True and config.plugins.softwaremanager.overwriteConfigFiles.value)\n\t\t\telse:\n\t\t\t\tself.session.openWithCallback(modificationCallback, MessageBox, _(\"Configuration file '%s' has been modified since it was installed, would you like to keep the modified version?\") % parameter)\n\t\telif event in (OpkgComponent.EVENT_DONE, OpkgComponent.EVENT_ERROR):\n\t\t\tif self.opkg.currentCommand == OpkgComponent.CMD_UPGRADE_LIST:\n\t\t\t\tself.packageTotal = len(self.opkg.getFetchedList())\n\t\t\t\tif self.packageTotal:\n\t\t\t\t\tself.opkg.startCmd(OpkgComponent.CMD_UPGRADE, args={\"testMode\": False})\n\t\t\t\telse:\n\t\t\t\t\tself.activity = -1\n\t\t\t\t\tself[\"update\"].appendText(f\"{_(\"No updates available.\")}\\n\\n{_(\"Press OK on your remote control to continue.\")}\")\n\t\t\telse:\n\t\t\t\tself[\"update\"].appendText(f\"\\n{_(\"Update completed.\")}\\n\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was identified for upgrade.\", \"%d packages were identified for upgrade.\", self.packageTotal) % self.packageTotal}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was downloaded.\", \"%d packages were downloaded.\", self.downloadCount) % self.downloadCount}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d feed catalog package was updated.\", \"%d feed catalog packages were updated.\", self.updateCount) % self.updateCount}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was installed.\", \"%d packages were installed.\", self.installCount) % self.installCount}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was removed.\", \"%d packages were removed.\", self.removeCount) % self.removeCount}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was upgraded.\", \"%d packages were upgraded.\", self.upgradeCount) % self.upgradeCount}\\n\")\n\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was configured.\", \"%d packages were configured.\", self.configureCount) % self.configureCount}\\n\")\n\t\t\t\tif self.deselectCount:\n\t\t\t\t\tself[\"update\"].appendText(f\"{ngettext(\"%d package was deselected.\", \"%d packages were deselected.\", self.deselectCount) % self.deselectCount}\\n\")\n\t\t\t\t\tself[\"update\"].appendText(f\"\\n{_(\"Deselected packages usually occur because those packaged are incompatible with existing packages. While this is mostly harmless it is possible that your %s %s may experience issues.\") % getBoxDisplayName()}\\n\")\n\t\t\t\tif event == OpkgComponent.EVENT_ERROR:\n\t\t\t\t\tself[\"update\"].appendText(f\"\\n\\n{_(\"Error\")}:\\n{_(\"Your receiver might be now be unstable. Please consult the manual for further assistance before rebooting your %s %s.\") % getBoxDisplayName()}\\n\")\n\t\t\t\tself.activity = -1\n\t\t\t\tself[\"update\"].appendText(f\"\\n{_(\"Press OK on your remote control to continue.\")}\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False):\n \"\"\"\n Read or writes pixel values for this band. Blocks of data can\n be accessed by specifying the width, height and offset of the\n desired block. The same specification can be used to update\n parts of a raster by providing an array of values.\n\n Allowed input data types are bytes, memoryview, list, tuple, and array.\n \"\"\"\n offset = offset or (0, 0)\n size = size or (self.width - offset[0], self.height - offset[1])\n shape = shape or size\n if any(x <= 0 for x in size):\n raise ValueError(\"Offset too big for this raster.\")\n\n if size[0] > self.width or size[1] > self.height:\n raise ValueError(\"Size is larger than raster.\")\n\n # Create ctypes type array generator\n ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (shape[0] * shape[1])\n\n if data is None:\n # Set read mode\n access_flag = 0\n # Prepare empty ctypes array\n data_array = ctypes_array()\n else:\n # Set write mode\n access_flag = 1\n\n # Instantiate ctypes array holding the input data\n if isinstance(data, (bytes, memoryview)) or (\n numpy and isinstance(data, numpy.ndarray)\n ):\n data_array = ctypes_array.from_buffer_copy(data)\n else:\n data_array = ctypes_array(*data)\n\n # Access band\n capi.band_io(\n self._ptr,\n access_flag,\n offset[0],\n offset[1],\n size[0],\n size[1],\n byref(data_array),\n shape[0],\n shape[1],\n self.datatype(),\n 0,\n 0,\n )\n\n # Return data as numpy array if possible, otherwise as list\n if data is None:\n if as_memoryview:\n return memoryview(data_array)\n elif numpy:\n # reshape() needs a reshape parameter with the height first.\n return numpy.frombuffer(\n data_array, dtype=numpy.dtype(data_array)\n ).reshape(tuple(reversed(size)))\n else:\n return list(data_array)\n else:\n self._flush()", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def findBestEvent(self, getnow=False):\n\t\told_service = self.cur_service #(service, service_name, events, picon)\n\t\tcur_service = self.cur_service = self.l.getCurrentSelection()\n\t\ttime_base = self.getTimeBase()\n\t\tnow = last_time = time()\n\t\tif old_service and self.cur_event is not None:\n\t\t\ttry:\n\t\t\t\tevents = old_service[2]\n\t\t\t\tcur_event = events[self.cur_event] # (event_id, event_title, begin_time, duration)\n\t\t\t\tlast_time = cur_event[2]\n\t\t\texcept Exception:\n\t\t\t\tpass\n\t\tif cur_service:\n\t\t\tself.cur_event = 0\n\t\t\tevents = cur_service[2]\n\t\t\tbest = None\n\t\t\tif events and len(events):\n\t\t\t\tbest_diff = 0\n\t\t\t\tidx = 0\n\t\t\t\tfor event in events: # iterate all events\n\t\t\t\t\tev_time = event[2]\n\t\t\t\t\tev_end_time = event[2] + event[3]\n\t\t\t\t\tif ev_time < time_base:\n\t\t\t\t\t\tev_time = time_base\n\t\t\t\t\tdiff = abs(ev_time - last_time)\n\t\t\t\t\tif best is None or (diff < best_diff):\n\t\t\t\t\t\tbest = idx\n\t\t\t\t\t\tbest_diff = diff\n\t\t\t\t\tif ev_end_time < now and getnow:\n\t\t\t\t\t\tbest = idx + 1\n\t\t\t\t\tif best is not None and ev_end_time > now and (ev_time > last_time or (getnow and ev_time < now)):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tidx += 1\n\t\t\tself.cur_event = best\n\t\tself.selEntry(0)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def run():\n \"\"\"Get filings that haven't been synced with colin and send them to the colin-api.\"\"\"\n application = create_app()\n corps_with_failed_filing = []\n with application.app_context():\n try:\n # get updater-job token\n token = AccountService.get_bearer_token()\n\n filings = get_filings(app=application)\n if not filings:\n # pylint: disable=no-member; false positive\n application.logger.debug('No completed filings to send to colin.')\n for filing in filings:\n filing_id = filing['filingId']\n identifier = filing['filing']['business']['identifier']\n if identifier in corps_with_failed_filing or is_test_coop(identifier):\n # pylint: disable=no-member; false positive\n application.logger.debug(f'Skipping filing {filing_id} for'\n f' {filing[\"filing\"][\"business\"][\"identifier\"]}.')\n else:\n colin_ids = send_filing(app=application, filing=filing, filing_id=filing_id)\n update = None\n if colin_ids:\n update = update_colin_id(app=application, filing_id=filing_id, colin_ids=colin_ids, token=token)\n if update:\n # pylint: disable=no-member; false positive\n application.logger.debug(f'Successfully updated filing {filing_id}')\n else:\n corps_with_failed_filing.append(filing['filing']['business']['identifier'])\n # pylint: disable=no-member; false positive\n application.logger.error(f'Failed to update filing {filing_id} with colin event id.')\n\n except Exception as err: # noqa: B902\n # pylint: disable=no-member; false positive\n application.logger.error(err)", "smellKey": "S3776", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "def SetCameraLookAtPointAndLookDirection(inParaViewRenderView, \\\n inLookDirection, \\\n inImageSettings, \\\n inFocalPoint = None, \\\n inEyeToFocalPointDistance = None, \\\n inEyePositionFactor = 1.0, \\\n inViewUp=[0.0,1.0,0.0], \\\n inCameraViewAngle = 30.0, \\\n inViewBounds = None,\n inPhactoriCamera = None):\n \"Set up camera with position, look at point, and positioning factor\\n\\n Sets the current camera view by looking at a focal point (inFocalPoint)\\n along a specified vector (inLookDirection). The distance from the focal\\n point is set using twice the largest of the data bounding box dimensions\\n multiplied by inEyePositionFactor. To see the whole of the data,\\n inEyePositionFactor can be about 1.0, although trying different values\\n will give you different filling of the screen and 'zooming' into the focal\\n point, while values greater than 1.0 can be used to zoom out, possibly to\\n bring the entire dataset into the image. If inEyeToFocalPointDistance is\\n something other than None, this distance will be used instead of the\\n bounding box of the data. If inFocalPoint is None, then\\n the center of the data bounds will be used as a focal point. inViewBounds\\n allows calling routine to pass along data bounds or other viewing bounds\\n which are used to calculate the viewing distance from the focal point\\n and the focal point if they are not supplied. If inEyeToFocalPointDistance\\n is not None and inFocalPoint is not None, than inViewBounds will not\\n be used and the global data bounds will not be obtained.\\n example: SetCameraLookAtPointAndLookDirection([5.0, 4.0, 3.0],\\n [1.0, 1.0, 1.0], 1.5, [0.0, 1.0, 0.0])\\n \"\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetCameraLookAtPointAndLookDirection entered\\n\", 100);\n\n #check for look view up same as look direction\n #need to do better check here\n if CheckForParallelVector(inLookDirection, inViewUp):\n inViewUp = [0.0, 0.0, 1.0]\n if CheckForParallelVector(inLookDirection, inViewUp):\n inViewUp = [0.0, 1.0, 0.0]\n\n #find maximum data dimension, then multiply by inEyePositionFactor\n if(inFocalPoint == None):\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n inFocalPoint = [ (inViewBounds[1] + inViewBounds[0]) * 0.5, \\\n (inViewBounds[3] + inViewBounds[2]) * 0.5, \\\n (inViewBounds[5] + inViewBounds[4]) * 0.5 ]\n\n if inEyeToFocalPointDistance != None:\n eyeToFocalPointDistance = inEyeToFocalPointDistance\n else:\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n #eyeToFocalPointDistance = GetMaximumDimensionFromBounds(inViewBounds)\n #eyeToFocalPointDistance *= inEyePositionFactor\n eyeToFocalPointDistance = CalcRelativeCameraDistance2(inFocalPoint,\n inLookDirection, inViewUp, inCameraViewAngle, inImageSettings,\n inViewBounds)\n eyeToFocalPointDistance *= inEyePositionFactor\n\n\n if PhactoriDbg():\n myDebugPrint3(\" eyeToFocalPointDistance: \" + str(eyeToFocalPointDistance) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inFocalPoint: \" + str(inFocalPoint) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inLookDirection: \" + str(inLookDirection) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inEyePositionFactor: \" + str(inEyePositionFactor) + \"\\n\")\n if PhactoriDbg():\n myDebugPrint3(\" inViewUp: \" + str(inViewUp) + \"\\n\")\n\n #find eye position based on focal point, distance to eye point, and look direction\n xx = inLookDirection[0]\n yy = inLookDirection[1]\n zz = inLookDirection[2]\n lookDirectionMagnitude = math.sqrt(xx*xx + yy*yy + zz*zz)\n #lookDirectionMagnitude = 1.0\n if PhactoriDbg():\n myDebugPrint3(\" lookDirectionMagnitude: \" + str(lookDirectionMagnitude) + \"\\n\")\n xx = xx / lookDirectionMagnitude\n yy = yy / lookDirectionMagnitude\n zz = zz / lookDirectionMagnitude\n eyePosition = [inFocalPoint[0] - xx * eyeToFocalPointDistance, \\\n inFocalPoint[1] - yy * eyeToFocalPointDistance, \\\n inFocalPoint[2] - zz * eyeToFocalPointDistance]\n if PhactoriDbg():\n myDebugPrint3(\" eyePosition: \" + str(eyePosition) + \"\\n\")\n\n\n useNewClippingCalc = True\n if useNewClippingCalc:\n eyeToFocalPointDist = vecDistance(eyePosition, inFocalPoint)\n clippingRange = [0.01 * eyeToFocalPointDist, 100.0 * eyeToFocalPointDist]\n else:\n clippingRange = [0.01 * lookDirectionMagnitude, 100.0 * lookDirectionMagnitude]\n\n localUseParallelProjection = False\n localParallelScale = 1.0\n if inPhactoriCamera != None:\n if inPhactoriCamera.mUseParallelProjection:\n localUseParallelProjection = True\n if inPhactoriCamera.mParallelScaleAbsoluteOrRelative == 0:\n localParallelScale = inPhactoriCamera.mParallelScale\n if PhactoriDbg():\n myDebugPrint3(\"absolute parallel scale: \" + \\\n str(localParallelScale) + \"\\n\")\n else:\n if inViewBounds == None:\n inViewBounds = GetGlobalDataBoundsParallel()\n #for relative case, we are using the diagonal of the\n #bounding box to determine the parallel scale; other algorithms might\n #be to use the longest bounding box side, or determine all bounding\n #box corner positions from camera position and use the greatest\n #vertical or horizontal extent of those points\n dimx = inViewBounds[1] - inViewBounds[0]\n dimy = inViewBounds[3] - inViewBounds[2]\n dimz = inViewBounds[5] - inViewBounds[4]\n maxbbdim = math.sqrt(dimx*dimx + dimy*dimy + dimz*dimz)\n localParallelScale = maxbbdim * 0.5 * 1.05\n localParallelScale *= inPhactoriCamera.mParallelScale\n if PhactoriDbg():\n myDebugPrint3(\"relative parallel scale: \" + \\\n str(localParallelScale) + \"\\n\")\n\n SetCameraViewExplicitly(inParaViewRenderView, eyePosition, inFocalPoint,\n clippingRange, inViewUp, inCameraViewAngle, inViewBounds,\n inPhactoriCamera, localUseParallelProjection, localParallelScale)\n\n if inPhactoriCamera != None:\n inPhactoriCamera.HandleLockingOption(eyePosition, inFocalPoint)\n\n if PhactoriDbg(100):\n myDebugPrint3(\"SetCameraLookAtPointAndLookDirection returning\\n\", 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None:\n \"\"\"Solve constraints by finding by using meets of upper bounds, and joins of lower bounds.\"\"\"\n bottom: Type | None = None\n top: Type | None = None\n candidate: Type | None = None\n\n # Filter out previous results of failed inference, they will only spoil the current pass...\n new_uppers = []\n for u in uppers:\n pu = get_proper_type(u)\n if not isinstance(pu, UninhabitedType) or not pu.ambiguous:\n new_uppers.append(u)\n uppers = new_uppers\n\n # ...unless this is the only information we have, then we just pass it on.\n if not uppers and not lowers:\n candidate = UninhabitedType()\n candidate.ambiguous = True\n return candidate\n\n # Process each bound separately, and calculate the lower and upper\n # bounds based on constraints. Note that we assume that the constraint\n # targets do not have constraint references.\n for target in lowers:\n if bottom is None:\n bottom = target\n else:\n if type_state.infer_unions:\n # This deviates from the general mypy semantics because\n # recursive types are union-heavy in 95% of cases.\n bottom = UnionType.make_union([bottom, target])\n else:\n bottom = join_types(bottom, target)\n\n for target in uppers:\n if top is None:\n top = target\n else:\n top = meet_types(top, target)\n\n p_top = get_proper_type(top)\n p_bottom = get_proper_type(bottom)\n if isinstance(p_top, AnyType) or isinstance(p_bottom, AnyType):\n source_any = top if isinstance(p_top, AnyType) else bottom\n assert isinstance(source_any, ProperType) and isinstance(source_any, AnyType)\n return AnyType(TypeOfAny.from_another_any, source_any=source_any)\n elif bottom is None:\n if top:\n candidate = top\n else:\n # No constraints for type variable\n return None\n elif top is None:\n candidate = bottom\n elif is_subtype(bottom, top):\n candidate = bottom\n else:\n candidate = None\n return candidate", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _do_init(self):\n from . import region, species\n\n rate = self._original_rate\n if not isinstance(rate, RangeVar):\n regions = []\n if self._regions and self._regions != [None]:\n regions = self._regions\n elif hasattr(self._species(), \"_regions\"):\n regions = self._species()._regions\n elif hasattr(self._species(), \"_region\"):\n regions = [self._species()._region()]\n regions = [\n r\n for r in regions\n if isinstance(r, region.Extracellular) or (r._secs1d or r._secs3d)\n ]\n if regions:\n self._rate, self._involved_species = rxdmath._compile(rate, regions)\n else:\n self._rate, self._involved_species = {}, []\n else:\n self._involved_species = self._species\n self._update_indices()\n\n # Check to if it is an extracellular reaction\n # Was an ECS region was passed to to the constructor\n ecs_region = [r for r in self._regions if isinstance(r, region.Extracellular)]\n # ecs_region = ecs_region[0] if len(ecs_region) > 0 else None\n # commented above out line because we need to pass all ecs_regions in.\n # TODO review this code below...I am very tired. Also did this in reaction.py\n ecs_region = ecs_region if len(ecs_region) > 0 else None\n if ecs_region:\n self._ecs_regions = ecs_region\n # Is the species passed to the constructor extracellular\n if not ecs_region:\n if isinstance(self._species(), species.SpeciesOnExtracellular):\n ecs_region = self._species()._extracellular()\n elif isinstance(self._species(), species._ExtracellularSpecies):\n ecs_region = self._species()._region\n\n # Is the species passed to the constructor defined on the ECS\n if not ecs_region:\n if not isinstance(self._species(), species.SpeciesOnRegion):\n sp = self._species()\n if sp and sp._extracellular_instances:\n self._ecs_regions = [\n key for key in sp._extracellular_instances.keys()\n ]\n\n if hasattr(self, \"_ecs_regions\"):\n self._rate_ecs, self._involved_species_ecs = rxdmath._compile(\n rate, self._ecs_regions\n )\n for sp in self._involved_species_ecs:\n if ecs_region and isinstance(sp(), species.SpeciesOnRegion):\n raise RxDException(\n f\"Error Rate {self._original_rate}: an extracellular rate can not depend on a SpeciesOnRegion\"\n )", "smellKey": "S3776", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "def combine(self, rhs, connector):\n \"\"\"\n Merge the 'rhs' query into the current one (with any 'rhs' effects\n being applied *after* (that is, \"to the right of\") anything in the\n current query. 'rhs' is not modified during a call to this function.\n\n The 'connector' parameter describes how to connect filters from the\n 'rhs' query.\n \"\"\"\n if self.model != rhs.model:\n raise TypeError(\"Cannot combine queries on two different base models.\")\n if self.is_sliced:\n raise TypeError(\"Cannot combine queries once a slice has been taken.\")\n if self.distinct != rhs.distinct:\n raise TypeError(\"Cannot combine a unique query with a non-unique query.\")\n if self.distinct_fields != rhs.distinct_fields:\n raise TypeError(\"Cannot combine queries with different distinct fields.\")\n\n # If lhs and rhs shares the same alias prefix, it is possible to have\n # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up\n # as T4 -> T6 while combining two querysets. To prevent this, change an\n # alias prefix of the rhs and update current aliases accordingly,\n # except if the alias is the base table since it must be present in the\n # query on both sides.\n initial_alias = self.get_initial_alias()\n rhs = rhs.clone()\n rhs.bump_prefix(self, exclude={initial_alias})\n\n # Work out how to relabel the rhs aliases, if necessary.\n change_map = {}\n conjunction = connector == AND\n\n # Determine which existing joins can be reused. When combining the\n # query with AND we must recreate all joins for m2m filters. When\n # combining with OR we can reuse joins. The reason is that in AND\n # case a single row can't fulfill a condition like:\n # revrel__col=1 & revrel__col=2\n # But, there might be two different related rows matching this\n # condition. In OR case a single True is enough, so single row is\n # enough, too.\n #\n # Note that we will be creating duplicate joins for non-m2m joins in\n # the AND case. The results will be correct but this creates too many\n # joins. This is something that could be fixed later on.\n reuse = set() if conjunction else set(self.alias_map)\n joinpromoter = JoinPromoter(connector, 2, False)\n joinpromoter.add_votes(\n j for j in self.alias_map if self.alias_map[j].join_type == INNER\n )\n rhs_votes = set()\n # Now, add the joins from rhs query into the new query (skipping base\n # table).\n rhs_tables = list(rhs.alias_map)[1:]\n for alias in rhs_tables:\n join = rhs.alias_map[alias]\n # If the left side of the join was already relabeled, use the\n # updated alias.\n join = join.relabeled_clone(change_map)\n new_alias = self.join(join, reuse=reuse)\n if join.join_type == INNER:\n rhs_votes.add(new_alias)\n # We can't reuse the same join again in the query. If we have two\n # distinct joins for the same connection in rhs query, then the\n # combined query must have two joins, too.\n reuse.discard(new_alias)\n if alias != new_alias:\n change_map[alias] = new_alias\n if not rhs.alias_refcount[alias]:\n # The alias was unused in the rhs query. Unref it so that it\n # will be unused in the new query, too. We have to add and\n # unref the alias so that join promotion has information of\n # the join type for the unused alias.\n self.unref_alias(new_alias)\n joinpromoter.add_votes(rhs_votes)\n joinpromoter.update_join_types(self)\n\n # Combine subqueries aliases to ensure aliases relabelling properly\n # handle subqueries when combining where and select clauses.\n self.subq_aliases |= rhs.subq_aliases\n\n # Now relabel a copy of the rhs where-clause and add it to the current\n # one.\n w = rhs.where.clone()\n w.relabel_aliases(change_map)\n self.where.add(w, connector)\n\n # Selection columns and extra extensions are those provided by 'rhs'.\n if rhs.select:\n self.set_select([col.relabeled_clone(change_map) for col in rhs.select])\n else:\n self.select = ()\n\n if connector == OR:\n # It would be nice to be able to handle this, but the queries don't\n # really make sense (or return consistent value sets). Not worth\n # the extra complexity when you can write a real query instead.\n if self.extra and rhs.extra:\n raise ValueError(\n \"When merging querysets using 'or', you cannot have \"\n \"extra(select=...) on both sides.\"\n )\n self.extra.update(rhs.extra)\n extra_select_mask = set()\n if self.extra_select_mask is not None:\n extra_select_mask.update(self.extra_select_mask)\n if rhs.extra_select_mask is not None:\n extra_select_mask.update(rhs.extra_select_mask)\n if extra_select_mask:\n self.set_extra_mask(extra_select_mask)\n self.extra_tables += rhs.extra_tables\n\n # Ordering uses the 'rhs' ordering, unless it has none, in which case\n # the current ordering is used.\n self.order_by = rhs.order_by or self.order_by\n self.extra_order_by = rhs.extra_order_by or self.extra_order_by", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@staticmethod\n def _encode_params(data):\n \"\"\"Encode parameters in a piece of data.\n\n Will successfully encode parameters when passed as a dict or a list of\n 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n if parameters are supplied as a dict.\n \"\"\"\n\n if isinstance(data, (str, bytes)):\n return data\n elif hasattr(data, \"read\"):\n return data\n elif hasattr(data, \"__iter__\"):\n result = []\n for k, vs in to_key_val_list(data):\n if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n vs = [vs]\n for v in vs:\n if v is not None:\n result.append(\n (\n k.encode(\"utf-8\") if isinstance(k, str) else k,\n v.encode(\"utf-8\") if isinstance(v, str) else v,\n )\n )\n return urlencode(result, doseq=True)\n else:\n return data", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def check_config_type(\n prototype: StagePrototype | Prototype,\n key: str,\n subkey: str,\n spec: dict,\n value: Any,\n default: bool = False,\n inactive: bool = False,\n) -> None:\n ref = proto_ref(prototype=prototype)\n label = \"Default value\" if default else \"Value\"\n\n tmpl1 = f'{label} of config key \"{key}/{subkey}\" {{}} ({ref})'\n tmpl2 = f'{label} (\"{value}\") of config key \"{key}/{subkey}\" {{}} ({ref})'\n should_not_be_empty = \"should be not empty\"\n\n if (\n value is None\n or (spec[\"type\"] == \"map\" and value == {})\n or (spec[\"type\"] == \"secretmap\" and value == {})\n or (spec[\"type\"] == \"list\" and value == [])\n ):\n if inactive:\n return\n\n if \"required\" in spec and spec[\"required\"]:\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"is required\"))\n\n return\n\n if (\n isinstance(value, (list, dict))\n and spec[\"type\"] not in settings.STACK_COMPLEX_FIELD_TYPES\n and spec[\"type\"] != \"group\"\n ):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"should be flat\"))\n\n if spec[\"type\"] == \"list\":\n if not isinstance(value, list):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"should be an array\"))\n\n if \"required\" in spec and spec[\"required\"] and value == []:\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(should_not_be_empty))\n\n for i, _value in enumerate(value):\n _check_str(value=_value, idx=i, key=key, subkey=subkey, ref=ref, label=label)\n\n if spec[\"type\"] in {\"map\", \"secretmap\"}:\n if not isinstance(value, dict):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"should be a map\"))\n\n if \"required\" in spec and spec[\"required\"] and value == {}:\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(should_not_be_empty))\n\n for value_key, value_value in value.items():\n _check_str(value=value_value, idx=value_key, key=key, subkey=subkey, ref=ref, label=label)\n\n if spec[\"type\"] in (\"string\", \"password\", \"text\", \"secrettext\"):\n if not isinstance(value, str):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(\"should be string\"))\n\n if \"required\" in spec and spec[\"required\"] and value == \"\":\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(should_not_be_empty))\n\n if (\n (saved_pattern := spec[\"limits\"].get(\"pattern\"))\n and not value.startswith(settings.ANSIBLE_VAULT_HEADER)\n and not Pattern(saved_pattern).matches(value)\n ):\n message = f\"The value of {key}/{subkey} config parameter does not match pattern: {saved_pattern}\"\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=message, http_code=HTTP_409_CONFLICT)\n\n if spec[\"type\"] in {\"file\", \"secretfile\"}:\n if not isinstance(value, str):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(\"should be string\"))\n\n if value == \"\":\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(should_not_be_empty))\n\n if default:\n if len(value) > 2048:\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"is too long\"))\n\n if not is_path_correct(value):\n # todo looks like it's only applicable to bundle parsing, not for any other stage\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl1.format(\"has unsupported path format\"))\n\n if spec[\"type\"] == \"structure\":\n schema = spec[\"limits\"][\"yspec\"]\n try:\n process_rule(data=value, rules=schema, name=\"root\")\n except FormatError as e:\n msg = tmpl1.format(f\"yspec error: {str(e)} at block {e.data}\")\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=msg) from e\n except SchemaError as e:\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=f\"yspec error: {str(e)}\") from e\n\n if spec[\"type\"] == \"boolean\" and not isinstance(value, bool):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(\"should be boolean\"))\n\n if spec[\"type\"] == \"integer\" and not isinstance(value, int):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(\"should be integer\"))\n\n if spec[\"type\"] == \"float\" and not isinstance(value, (int, float)):\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(\"should be float\"))\n\n if spec[\"type\"] == \"integer\" or spec[\"type\"] == \"float\":\n limits = spec[\"limits\"]\n if \"min\" in limits and value < limits[\"min\"]:\n msg = f'should be more than {limits[\"min\"]}'\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(msg))\n\n if \"max\" in limits and value > limits[\"max\"]:\n msg = f'should be less than {limits[\"max\"]}'\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(msg))\n\n if spec[\"type\"] == \"option\":\n option = spec[\"limits\"][\"option\"]\n\n if value not in option.values():\n msg = f'not in option list: \"{option.values()}\"'\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(msg))\n\n if spec[\"type\"] == \"variant\":\n source = spec[\"limits\"][\"source\"]\n if source[\"strict\"]:\n if source[\"type\"] == \"inline\" and value not in source[\"value\"]:\n msg = f'not in variant list: \"{source[\"value\"]}\"'\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(msg))\n\n if not default and source[\"type\"] in (\"config\", \"builtin\") and value not in source[\"value\"]:\n msg = f'not in variant list: \"{source[\"value\"]}\"'\n raise AdcmEx(code=\"CONFIG_VALUE_ERROR\", msg=tmpl2.format(msg))", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "def ParseOneImagesetBlockC(ioImagesetBlock, ioImagesetBlockJson,\n ioPipeAndViewsState):\n\n #hack--if we have an imageset with a particular name, we enable\n #interaction\n if ioImagesetBlock.mName == 'PhactoriGoInteractive':\n ioPipeAndViewsState.mInteractionEnabled = True\n\n #we need to get text color for time annotation and text annotation\n #handled properly: for now we allow a \"text color\" setting in any\n #imageset block to set the global text color\n if 'text color' in ioImagesetBlockJson:\n global gTemporaryGlobalImageTextColor\n gTemporaryGlobalImageTextColor = getParameterFromBlock(ioImagesetBlockJson,\n 'text color', [1.0, 1.0, 1.0])\n\n ioImagesetBlock.mBackground = getParameterFromBlock(ioImagesetBlockJson,\n 'background color', ioImagesetBlock.mBackground)\n\n #parse on/off criteria\n if 'onoff criteria' in ioImagesetBlockJson:\n inCriteriaList = ioImagesetBlockJson['onoff criteria']\n for oneCriteriaName in inCriteriaList:\n if oneCriteriaName not in \\\n ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks:\n myDebugPrint3AndException(\"ParseOneImagesetBlockC:\"\n \"imageset with name: \" + ioImagesetBlock.mName + \"\\n\"\n \"calls for nonexistent onoff criteria with name: \" + \\\n oneCriteriaName + \"\\n\")\n ioImagesetBlock.mImagesetOnOffFilter.AddStartCriteria( \\\n ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks[oneCriteriaName])\n\n if 'camera' not in ioImagesetBlockJson:\n #we have to construct and use a default camera, including parsing\n #commands in the imageset for the camera\n if PhactoriDbg():\n myDebugPrint3(\" ParseOneImagesetBlockC: for imageset \" + \\\n ioImagesetBlock.mName + \\\n \" there is no camera, so we must add and reference default\\n\")\n if 'camera type' not in ioImagesetBlockJson:\n ioImagesetBlockJson['camera type'] = 'multicamera8'\n defaultCameraName = ioImagesetBlock.mName + '_default_camera'\n defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}\n ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,\n defaultCameraBlockAndWrapper,\n PhactoriCameraBlock,\n ParseOneCameraBlockC,\n ioPipeAndViewsState)\n ioImagesetBlockJson['camera'] = defaultCameraName\n #myDebugPrint3( \"done adding camera, here it is:\\n\")\n #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()\n\n\n #there is a camera (if there wasn't, we added it), so get the reference\n cameraName = ioImagesetBlockJson['camera']\n if cameraName not in ioPipeAndViewsState.mCameraBlocks:\n errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for camera (' + str(cameraName) + ') which does not exist\\n'\n if PhactoriDbg():\n myDebugPrint3(errStr)\n raise Exception(errStr)\n\n ioImagesetBlock.mCamera = ioPipeAndViewsState.mCameraBlocks[cameraName]\n if PhactoriDbg():\n myDebugPrint3(\" image set \" + ioImagesetBlock.mName + \" is using the following camera:\\n\")\n ioImagesetBlock.mCamera.PrintSelf()\n\n if 'markers' in ioImagesetBlockJson:\n ioImagesetBlock.mVisibleMarkerNames = ioImagesetBlockJson['markers']\n for oneMarkerName in ioImagesetBlock.mVisibleMarkerNames:\n if oneMarkerName in ioPipeAndViewsState.mMarkerBlocks:\n ioImagesetBlock.mVisibleMarkers.append(\n ioPipeAndViewsState.mMarkerBlocks[oneMarkerName])\n else:\n myDebugPrint3AndException(\n \"ParseOneImagesetBlockC:\\n\" \\\n \"image set with name: \" + ioImagesetBlock.mName + \"\\n\"\n \"calls for nonexistent marker named: \" + oneMarkerName + \"\\n\")\n\n if 'text annotations' in ioImagesetBlockJson:\n ioImagesetBlock.mTextAnnotationNames = \\\n ioImagesetBlockJson['text annotations']\n for oneMarkerName in ioImagesetBlock.mTextAnnotationNames:\n if oneMarkerName in ioPipeAndViewsState.mTextAnnotationBlocks:\n ioImagesetBlock.mTextAnnotations.append(\n ioPipeAndViewsState.mTextAnnotationBlocks[oneMarkerName])\n else:\n myDebugPrint3AndException(\n \"ParseOneImagesetBlockC:\\n\" \\\n \"image set with name: \" + ioImagesetBlock.mName + \"\\n\"\n \"calls for nonexistent marker named: \" + oneMarkerName + \"\\n\")\n\n #if 'representation' not in ioImagesetBlockJson:\n # #we have to construct and use a default representation, including parsing\n # #commands in the imageset for the representation\n # if PhactoriDbg():\n # myDebugPrint3(\" ParseOneImagesetBlockC: for imageset \" + \\\n # ioImagesetBlock.mName + \\\n # \" there is no representation, \" +\n # \"so we must add and reference default\\n\")\n # defaultRepName = ioImagesetBlock.mName + '_default_representation'\n # defaultRepBlockAndWrapper = {defaultRepName: ioImagesetBlockJson}\n # ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,\n # defaultRepBlockAndWrapper,\n # PhactoriRepresentationBlock,\n # ParseOneRepresentationBlockC,\n # ioPipeAndViewsState)\n # ioImagesetBlockJson['representation'] = defaultRepName\n\n #if 'representation' in ioImagesetBlockJson:\n # representationName = ioImagesetBlockJson['representation']\n # if representationName not in ioPipeAndViewsState.mRepresentationBlocks:\n # errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for representation (' + str(representationName) + ') which does not exist\\n'\n # if PhactoriDbg():\n # myDebugPrint3(errStr)\n # raise Exception(errStr)\n # ioImagesetBlock.mRepresentation = ioPipeAndViewsState.mRepresentationBlocks[representationName]\n #else:\n # ioImagesetBlock.mRepresentation = None #need to use default representation\n #ioImagesetBlock.mVisibleReps.append(ioImagesetBlock.mRepresentation)\n\n ##get the operation referred to by this image set (or the default incoming\n ##data)\n #ioImagesetBlock.mOperation =\\\n # ioPipeAndViewsState.GetOperationReferredByJson(\n # 'operation', ioImagesetBlockJson)\n #ioImagesetBlock.mVisibleOps.append(ioImagesetBlock.mOperation)\n\n ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,\n ioImagesetBlockJson, 'operation', False, 'representation', False, False)\n ioImagesetBlock.mOperation = ioImagesetBlock.mVisibleOps[0]\n ioImagesetBlock.mRepresentation = ioImagesetBlock.mVisibleReps[0]\n\n #initial implementation of having more than one operation visible:\n #have up to 3 visible with particular parsing names\n ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,\n ioImagesetBlockJson, 'operation2', True, 'representation2', True, True)\n ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,\n ioImagesetBlockJson, 'operation3', True, 'representation3', True, True)\n\n ioImagesetBlock.mImageSettings.ParseImageSettingsInfo(\n ioImagesetBlockJson, 'image basename', 'image basedirectory')\n ioImagesetBlock.mImageFileNameCountSettings.\\\n ParseImageFileNameCountSettings(ioImagesetBlockJson)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def ParseParametersFromJson(self, inJson):\n key1 = \"origin\"\n if key1 in inJson:\n self.PlaneOrigin = inJson[key1]\n try:\n if len(self.PlaneOrigin) != 3:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'origin', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n except:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'origin', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n\n key1 = \"point1\"\n if key1 in inJson:\n self.PlanePoint1 = inJson[key1]\n try:\n if len(self.PlanePoint1) != 3:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'point1', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n except:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'point1', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n\n key1 = \"point2\"\n if key1 in inJson:\n self.PlanePoint2 = inJson[key1]\n try:\n if len(self.PlanePoint2) != 3:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'point2', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n except:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"bad 'point2', must be 3 number list list [1.1,2.3,-4.5]\\n\")\n\n key1 = \"xresolution\"\n if key1 in inJson:\n self.PlaneXResolution = inJson[key1]\n if isinstance(self.PlaneXResolution, int):\n if self.PlaneXResolution < 1:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"'xresolution' must be integer >= 1\\n\")\n else:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"'xresolution' must be integer >= 1\\n\")\n\n key1 = \"yresolution\"\n if key1 in inJson:\n self.PlaneYResolution = inJson[key1]\n if isinstance(self.PlaneYResolution, int):\n if self.PlaneYResolution < 1:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"'yresolution' must be integer >= 1\\n\")\n else:\n myDebugPrint3AndException(\n \"PhactoriPlaneSource:ParseParametersFromJson\\n\"\n \"'yresolution' must be integer >= 1\\n\")", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def get_email_addresses(\n user_ids: Iterable[int], project: Project | None = None, only_verified: bool = False\n) -> Mapping[int, str]:\n \"\"\"\n Find the best email addresses for a collection of users. If a project is\n provided, prefer their project-specific notification preferences. Can also\n optionally filter to only returning verified email addresses.\n \"\"\"\n pending = set(user_ids)\n results = {}\n\n if project:\n to_delete: list[RpcUserOption] = []\n options = user_option_service.get_many(\n filter={\"user_ids\": pending, \"project_id\": project.id, \"keys\": [\"mail:email\"]}\n )\n\n user_id_emails = []\n for option in (o for o in options if o.value and not is_fake_email(o.value)):\n user_id_emails.append(UserIdEmailArgs(user_id=int(option.user_id), email=option.value))\n\n user_id_emails_exists = user_service.verify_user_emails(\n user_id_emails=user_id_emails, only_verified=only_verified\n )\n\n for user_id_key in user_id_emails_exists.keys():\n user_id = int(user_id_key)\n if user_id_emails_exists[user_id_key].exists:\n results[user_id] = user_id_emails_exists[user_id_key].email\n pending.discard(user_id)\n else:\n pending.discard(user_id)\n to_delete.append(option)\n user_option_service.delete_options(option_ids=[o.id for o in to_delete])\n\n if pending:\n users = user_service.get_many_by_id(ids=list(pending))\n for user_id, email in [(user.id, user.email) for user in users]:\n if email and not is_fake_email(email):\n results[user_id] = email\n pending.discard(user_id)\n\n if pending:\n logger.warning(\n \"Could not resolve email addresses for user IDs in %s, discarding...\", pending\n )\n\n return results", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def menuCallback(self, *result):\n\t\tif not len(result):\n\t\t\treturn\n\t\tresult = result[0]\n\n\t\tif result == CutListContextMenu.RET_STARTCUT:\n\t\t\tself.cut_start = self.context_position\n\t\telif result == CutListContextMenu.RET_ENDCUT:\n\t\t\t# remove in/out marks between the new cut\n\t\t\tfor (where, what) in self.cut_list[:]:\n\t\t\t\tif self.cut_start <= where <= self.context_position and what in (0, 1):\n\t\t\t\t\tself.cut_list.remove((where, what))\n\n\t\t\tbisect.insort(self.cut_list, (self.cut_start, 1))\n\t\t\tbisect.insort(self.cut_list, (self.context_position, 0))\n\t\t\tself.uploadCuesheet()\n\t\t\tself.cut_start = None\n\t\telif result == CutListContextMenu.RET_DELETECUT:\n\t\t\tout_before = None\n\t\t\tin_after = None\n\n\t\t\tfor (where, what) in self.cut_list:\n\t\t\t\tif what == 1 and where <= self.context_position: # out\n\t\t\t\t\tout_before = (where, what)\n\t\t\t\telif what == 0 and where < self.context_position: # in, before out\n\t\t\t\t\tout_before = None\n\t\t\t\telif what == 0 and where >= self.context_position and in_after is None:\n\t\t\t\t\tin_after = (where, what)\n\n\t\t\tif out_before is not None:\n\t\t\t\tself.cut_list.remove(out_before)\n\n\t\t\tif in_after is not None:\n\t\t\t\tself.cut_list.remove(in_after)\n\t\t\tself.inhibit_seek = True\n\t\t\tself.uploadCuesheet()\n\t\t\tself.inhibit_seek = False\n\t\telif result == CutListContextMenu.RET_MARK:\n\t\t\tself.__addMark()\n\t\telif result == CutListContextMenu.RET_DELETEMARK:\n\t\t\tself.cut_list.remove(self.context_nearest_mark)\n\t\t\tself.inhibit_seek = True\n\t\t\tself.uploadCuesheet()\n\t\t\tself.inhibit_seek = False\n\t\telif result == CutListContextMenu.RET_REMOVEBEFORE:\n\t\t\t# remove in/out marks before current position\n\t\t\tfor (where, what) in self.cut_list[:]:\n\t\t\t\tif where <= self.context_position and what in (0, 1):\n\t\t\t\t\tself.cut_list.remove((where, what))\n\t\t\t# add 'in' point\n\t\t\tbisect.insort(self.cut_list, (self.context_position, 0))\n\t\t\tself.inhibit_seek = True\n\t\t\tself.uploadCuesheet()\n\t\t\tself.inhibit_seek = False\n\t\telif result == CutListContextMenu.RET_REMOVEAFTER:\n\t\t\t# remove in/out marks after current position\n\t\t\tfor (where, what) in self.cut_list[:]:\n\t\t\t\tif where >= self.context_position and what in (0, 1):\n\t\t\t\t\tself.cut_list.remove((where, what))\n\t\t\t# add 'out' point\n\t\t\tbisect.insort(self.cut_list, (self.context_position, 1))\n\t\t\tself.inhibit_seek = True\n\t\t\tself.uploadCuesheet()\n\t\t\tself.inhibit_seek = False\n\t\telif result == CutListContextMenu.RET_REMOVEALL:\n\t\t\tself.__removeAllCallback(True)\n\t\telif result == CutListContextMenu.RET_GRABFRAME:\n\t\t\tself.grabFrame()\n\t\telif result == CutListContextMenu.RET_TOGGLEINTRO:\n\t\t\tself.toggleIntro()\n\t\telif result == CutListContextMenu.RET_MOVIECUT:\n\t\t\tself.inhibit_seek = True\n\t\t\tself.uploadCuesheet()\n\t\t\tself.inhibit_seek = False\n\t\t\tcservice = self.session.nav.getCurrentlyPlayingServiceReference()\n\t\t\tself.crashFix()\n\t\t\t#self.session.nav.playService(self.old_service, forceRestart=True) #required for actually writing the .cuts file\n\t\t\tself.session.nav.playService(cservice, forceRestart=True) # required for actually writing the .cuts file\n\t\t\tself.pauseService()\n\t\t\ttry:\n\t\t\t\tMovieCut(session=self.session, service=cservice)\n\t\t\texcept:\n\t\t\t\tprint(\"[CutListEditor] calling MovieCut failed\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_assignment_target(\n self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False\n ) -> AssignmentTarget:\n if line == -1:\n line = lvalue.line\n if isinstance(lvalue, NameExpr):\n # If we are visiting a decorator, then the SymbolNode we really want to be looking at\n # is the function that is decorated, not the entire Decorator node itself.\n symbol = lvalue.node\n if isinstance(symbol, Decorator):\n symbol = symbol.func\n if symbol is None:\n # New semantic analyzer doesn't create ad-hoc Vars for special forms.\n assert lvalue.is_special_form\n symbol = Var(lvalue.name)\n if not for_read and isinstance(symbol, Var) and symbol.is_cls:\n self.error(\"Cannot assign to the first argument of classmethod\", line)\n if lvalue.kind == LDEF:\n if symbol not in self.symtables[-1]:\n if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType):\n reg_type = self.type_to_rtype(symbol.type)\n else:\n reg_type = self.node_type(lvalue)\n # If the function is a generator function, then first define a new variable\n # in the current function's environment class. Next, define a target that\n # refers to the newly defined variable in that environment class. Add the\n # target to the table containing class environment variables, as well as the\n # current environment.\n if self.fn_info.is_generator:\n return self.add_var_to_env_class(\n symbol, reg_type, self.fn_info.generator_class, reassign=False\n )\n\n # Otherwise define a new local variable.\n return self.add_local_reg(symbol, reg_type)\n else:\n # Assign to a previously defined variable.\n return self.lookup(symbol)\n elif lvalue.kind == GDEF:\n globals_dict = self.load_globals_dict()\n name = self.load_str(lvalue.name)\n return AssignmentTargetIndex(globals_dict, name)\n else:\n assert False, lvalue.kind\n elif isinstance(lvalue, IndexExpr):\n # Indexed assignment x[y] = e\n base = self.accept(lvalue.base)\n index = self.accept(lvalue.index)\n return AssignmentTargetIndex(base, index)\n elif isinstance(lvalue, MemberExpr):\n # Attribute assignment x.y = e\n can_borrow = self.is_native_attr_ref(lvalue)\n obj = self.accept(lvalue.expr, can_borrow=can_borrow)\n return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow)\n elif isinstance(lvalue, TupleExpr):\n # Multiple assignment a, ..., b = e\n star_idx: int | None = None\n lvalues = []\n for idx, item in enumerate(lvalue.items):\n targ = self.get_assignment_target(item)\n lvalues.append(targ)\n if isinstance(item, StarExpr):\n if star_idx is not None:\n self.error(\"Two starred expressions in assignment\", line)\n star_idx = idx\n\n return AssignmentTargetTuple(lvalues, star_idx)\n\n elif isinstance(lvalue, StarExpr):\n return self.get_assignment_target(lvalue.expr)\n\n assert False, \"Unsupported lvalue: %r\" % lvalue", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def applySkin(self, desktop, parent):\n\t\tattribs = []\n\n\t\tattributeMapping = {\n\t\t\t\"foregroundColorServiceNotAvail\": \"serviceNotAvailColor\",\n\t\t\t\"colorServiceRecording\": \"recordColor\",\n\t\t\t\"colorServiceRecorded\": \"recordColor\",\n\t\t\t\"colorServicePseudoRecorded\": \"pseudoColor\",\n\t\t\t\"colorServiceStreamed\": \"streamColor\",\n\t\t\t\"colorFallbackItem\": \"fallbackColor\",\n\t\t\t\"colorServiceSelectedFallback\": \"fallbackColorSelected\"\n\t\t}\n\n\t\tself.widgetAttributes[\"recordColor\"] = \"#00b40431\"\n\t\tself.widgetAttributes[\"streamColor\"] = \"#00f56712\"\n\t\tself.widgetAttributes[\"pseudoColor\"] = \"#0041b1ec\"\n\t\tself.widgetAttributes[\"serviceNotAvailColor\"] = \"#00bbbbbb\"\n\n\t\tself.widgetAttributes[\"recordColorSelected\"] = \"#00b40431\"\n\t\tself.widgetAttributes[\"streamColorSelected\"] = \"#00f56712\"\n\t\tself.widgetAttributes[\"pseudoColorSelected\"] = \"#0041b1ec\"\n\t\tself.widgetAttributes[\"serviceNotAvailColorSelected\"] = \"#00bbbbbb\"\n\n\t\tfor (attrib, value) in self.skinAttributes:\n\t\t\t# Color attributes\n\t\t\tnewattrib = attributeMapping.get(attrib, attrib)\n\n\t\t\tif newattrib in (\"foregroundColorMarked\", \"foregroundColorMarkedSelected\", \"backgroundColorMarked\", \"backgroundColorMarkedSelected\") + self.widgetColors:\n\t\t\t\tself.widgetAttributes[newattrib] = value\n\t\t\t\tcontinue\n\n\t\t\t# LEGACY attributes will be ignored\n\t\t\tif attrib.startswith(\"colorEventProgressbar\"):\n\t\t\t\tcontinue\n\n\t\t\tif attrib.startswith(\"progressBar\"):\n\t\t\t\tcontinue\n\n\t\t\tif attrib.startswith(\"foregroundColorEvent\"):\n\t\t\t\tcontinue\n\n\t\t\tif attrib.startswith(\"colorServiceDescription\"):\n\t\t\t\tcontinue\n\n\t\t\tif attrib.endswith(\"Font\"):\n\t\t\t\tcontinue\n\n\t\t\tif attrib in (\"listMarginLeft\", \"listMarginRight\", \"fieldMargins\", \"itemsDistances\", \"nonplayableMargins\", \"serviceItemHeight\", \"picServiceEventProgressbar\", \"colorServiceWithAdvertisment\"):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tattribs.append((attrib, value))\n\n\t\tself.skinAttributes = attribs\n\t\trc = GUIComponent.applySkin(self, desktop, parent)\n\t\tself.listHeight = self.instance.size().height()\n\t\tself.listWidth = self.instance.size().width()\n\t\tself.readTemplate(config.channelSelection.widgetStyle.value)\n\t\treturn rc", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_host_platform():\n \"\"\"Return a string that identifies the current platform. This is used mainly to\n distinguish platform-specific build directories and platform-specific built\n distributions. Typically includes the OS name and version and the\n architecture (as supplied by 'os.uname()'), although the exact information\n included depends on the OS; eg. on Linux, the kernel version isn't\n particularly important.\n\n Examples of returned values:\n linux-i586\n linux-alpha (?)\n solaris-2.6-sun4u\n\n Windows will return one of:\n win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)\n win32 (all others - specifically, sys.platform is returned)\n\n For other non-POSIX platforms, currently just returns 'sys.platform'.\n\n \"\"\"\n if os.name == 'nt':\n if 'amd64' in sys.version.lower():\n return 'win-amd64'\n if '(arm)' in sys.version.lower():\n return 'win-arm32'\n if '(arm64)' in sys.version.lower():\n return 'win-arm64'\n return sys.platform\n\n # Set for cross builds explicitly\n if \"_PYTHON_HOST_PLATFORM\" in os.environ:\n return os.environ[\"_PYTHON_HOST_PLATFORM\"]\n\n if os.name != 'posix' or not hasattr(os, 'uname'):\n # XXX what about the architecture? NT is Intel or Alpha,\n # Mac OS is M68k or PPC, etc.\n return sys.platform\n\n # Try to distinguish various flavours of Unix\n\n (osname, host, release, version, machine) = os.uname()\n\n # Convert the OS name to lowercase, remove '/' characters, and translate\n # spaces (for \"Power Macintosh\")\n osname = osname.lower().replace('/', '')\n machine = machine.replace(' ', '_').replace('/', '-')\n\n if osname[:5] == 'linux':\n # At least on Linux/Intel, 'machine' is the processor --\n # i386, etc.\n # XXX what about Alpha, SPARC, etc?\n return \"%s-%s\" % (osname, machine)\n\n elif osname[:5] == 'sunos':\n if release[0] >= '5': # SunOS 5 == Solaris 2\n osname = 'solaris'\n release = '%d.%s' % (int(release[0]) - 3, release[2:])\n # We can't use 'platform.architecture()[0]' because a\n # bootstrap problem. We use a dict to get an error\n # if some suspicious happens.\n bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}\n machine += '.%s' % bitness[sys.maxsize]\n # fall through to standard osname-release-machine representation\n elif osname[:3] == 'aix':\n from _aix_support import aix_platform\n return aix_platform()\n elif osname[:6] == 'cygwin':\n osname = 'cygwin'\n rel_re = re.compile(r'[\\d.]+', re.ASCII)\n m = rel_re.match(release)\n if m:\n release = m.group()\n elif osname[:6] == 'darwin':\n import _osx_support\n try:\n from distutils import sysconfig\n except ImportError:\n import sysconfig\n osname, release, machine = _osx_support.get_platform_osx(\n sysconfig.get_config_vars(), osname, release, machine)\n\n return '%s-%s-%s' % (osname, release, machine)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "async def process_filing(filing_msg: Dict, flask_app: Flask): # pylint: disable=too-many-branches,too-many-statements\n \"\"\"Render the filings contained in the submission.\n\n Start the migration to using core/Filing\n \"\"\"\n if not flask_app:\n raise QueueException('Flask App not available.')\n\n with flask_app.app_context():\n # filing_submission = Filing.find_by_id(filing_msg['filing']['id'])\n filing_core_submission = FilingCore.find_by_id(filing_msg['filing']['id'])\n\n if not filing_core_submission:\n raise QueueException\n\n filing_submission = filing_core_submission.storage\n\n if filing_core_submission.status == Filing.Status.COMPLETED.value:\n logger.warning('QueueFiler: Attempting to reprocess business.id=%s, filing.id=%s filing=%s',\n filing_submission.business_id, filing_submission.id, filing_msg)\n return None, None\n\n if legal_filings := filing_core_submission.legal_filings():\n uow = versioning_manager.unit_of_work(db.session)\n transaction = uow.create_transaction(db.session)\n\n business = Business.find_by_internal_id(filing_submission.business_id)\n\n for filing in legal_filings:\n if filing.get('alteration'):\n alteration.process(business, filing_submission, filing)\n\n if filing.get('annualReport'):\n annual_report.process(business, filing)\n\n elif filing.get('changeOfAddress'):\n change_of_address.process(business, filing)\n\n elif filing.get('changeOfDirectors'):\n filing['colinIds'] = filing_submission.colin_event_ids\n change_of_directors.process(business, filing)\n\n elif filing.get('changeOfName'):\n change_of_name.process(business, filing)\n\n elif filing.get('voluntaryDissolution'):\n voluntary_dissolution.process(business, filing)\n\n elif filing.get('incorporationApplication'):\n business, filing_submission = incorporation_filing.process(business,\n filing_core_submission.json,\n filing_submission)\n\n elif filing.get('conversion'):\n business, filing_submission = conversion.process(business,\n filing_core_submission.json,\n filing_submission)\n\n elif filing.get('courtOrder'):\n court_order.process(filing_submission, filing)\n elif filing.get('registrarsNotation'):\n registrars_notation.process(filing_submission, filing)\n elif filing.get('registrarsOrder'):\n registrars_order.process(filing_submission, filing)\n\n if filing.get('correction'):\n filing_submission = correction.process(filing_submission, filing)\n\n if filing.get('transition'):\n filing_submission = transition.process(business, filing_submission, filing)\n\n filing_submission.transaction_id = transaction.id\n filing_submission.set_processed()\n\n db.session.add(business)\n db.session.add(filing_submission)\n db.session.commit()\n\n # post filing changes to other services\n if any('alteration' in x for x in legal_filings):\n if name_request.has_new_nr_for_alteration(business, filing_submission.filing_json):\n name_request.consume_nr(business, filing_submission, '/filing/alteration/nameRequest/nrNumber')\n alteration.post_process(business, filing_submission)\n db.session.add(business)\n db.session.commit()\n AccountService.update_entity(\n business_registration=business.identifier,\n business_name=business.legal_name,\n corp_type_code=business.legal_type\n )\n\n if any('incorporationApplication' in x for x in legal_filings):\n if any('correction' in x for x in legal_filings):\n if name_request.has_new_nr_for_correction(filing_submission.filing_json):\n name_request.consume_nr(business, filing_submission)\n else:\n filing_submission.business_id = business.id\n db.session.add(filing_submission)\n db.session.commit()\n incorporation_filing.update_affiliation(business, filing_submission)\n name_request.consume_nr(business, filing_submission)\n incorporation_filing.post_process(business, filing_submission)\n try:\n await publish_email_message(\n qsm, APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subject'], filing_submission, 'mras')\n except Exception as err: # pylint: disable=broad-except, unused-variable # noqa F841;\n # mark any failure for human review\n capture_message(\n f'Queue Error: Failed to place email for filing:{filing_submission.id}'\n f'on Queue with error:{err}',\n level='error'\n )\n\n if any('conversion' in x for x in legal_filings):\n filing_submission.business_id = business.id\n db.session.add(filing_submission)\n db.session.commit()\n conversion.post_process(business, filing_submission)\n\n try:\n await publish_email_message(\n qsm, APP_CONFIG.EMAIL_PUBLISH_OPTIONS['subject'], filing_submission, filing_submission.status)\n except Exception as err: # pylint: disable=broad-except, unused-variable # noqa F841;\n # mark any failure for human review\n capture_message(\n f'Queue Error: Failed to place email for filing:{filing_submission.id}'\n f'on Queue with error:{err}',\n level='error'\n )\n\n try:\n await publish_event(business, filing_submission)\n except Exception as err: # pylint: disable=broad-except, unused-variable # noqa F841;\n # mark any failure for human review\n capture_message(\n f'Queue Error: Failed to publish event for filing:{filing_submission.id}'\n f'on Queue with error:{err}',\n level='error'\n )", "smellKey": "S3776", "smellId": null, "repo": "bcgov_lear", "language": "python"} {"function": "@x_robots_tag\ndef sitemap(\n request,\n sitemaps,\n section=None,\n template_name=\"sitemap.xml\",\n content_type=\"application/xml\",\n):\n req_protocol = request.scheme\n req_site = get_current_site(request)\n\n if section is not None:\n if section not in sitemaps:\n raise Http404(\"No sitemap available for section: %r\" % section)\n maps = [sitemaps[section]]\n else:\n maps = sitemaps.values()\n page = request.GET.get(\"p\", 1)\n\n lastmod = None\n all_sites_lastmod = True\n urls = []\n for site in maps:\n try:\n if callable(site):\n site = site()\n urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol))\n if all_sites_lastmod:\n site_lastmod = getattr(site, \"latest_lastmod\", None)\n if site_lastmod is not None:\n lastmod = _get_latest_lastmod(lastmod, site_lastmod)\n else:\n all_sites_lastmod = False\n except EmptyPage:\n raise Http404(\"Page %s empty\" % page)\n except PageNotAnInteger:\n raise Http404(\"No page '%s'\" % page)\n # If lastmod is defined for all sites, set header so as\n # ConditionalGetMiddleware is able to send 304 NOT MODIFIED\n if all_sites_lastmod:\n headers = {\"Last-Modified\": http_date(lastmod.timestamp())} if lastmod else None\n else:\n headers = None\n return TemplateResponse(\n request,\n template_name,\n {\"urlset\": urls},\n content_type=content_type,\n headers=headers,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def resolve_function(\n self,\n function: str,\n match: Match[str] | None = None,\n resolve_only: bool = False,\n overwrite_alias: str | None = None,\n ) -> SelectType:\n \"\"\"Given a public function, resolve to the corresponding Snql function\n\n\n :param function: the public alias for a function eg. \"p50(transaction.duration)\"\n :param match: the Match so we don't have to run the regex twice\n :param resolve_only: whether we should add the aggregate to self.aggregates\n :param overwrite_alias: ignore the alias in the parsed_function and use this string instead\n \"\"\"\n if match is None:\n match = fields.is_function(function)\n\n if not match:\n raise InvalidSearchQuery(f\"Invalid characters in field {function}\")\n\n name, combinator_name, parsed_arguments, alias = self.parse_function(match)\n if overwrite_alias is not None:\n alias = overwrite_alias\n\n snql_function = self.function_converter[name]\n\n combinator = snql_function.find_combinator(combinator_name)\n\n if combinator_name is not None and combinator is None:\n raise InvalidSearchQuery(\n f\"{snql_function.name}: no support for the -{combinator_name} combinator\"\n )\n\n if not snql_function.is_accessible(self.builder_config.functions_acl, combinator):\n raise InvalidSearchQuery(f\"{snql_function.name}: no access to private function\")\n\n combinator_applied = False\n\n arguments = snql_function.format_as_arguments(\n name, parsed_arguments, self.filter_params, combinator\n )\n\n self.function_alias_map[alias] = fields.FunctionDetails(\n function, snql_function, arguments.copy()\n )\n\n for arg in snql_function.args:\n if isinstance(arg, fields.ColumnArg):\n if (\n arguments[arg.name] in fields.NumericColumn.numeric_array_columns\n and isinstance(arg, fields.NumericColumn)\n and not isinstance(combinator, fields.SnQLArrayCombinator)\n ):\n arguments[arg.name] = Function(\n \"arrayJoin\", [self.resolve_column(arguments[arg.name])]\n )\n else:\n column = self.resolve_column(arguments[arg.name])\n # Can't keep aliased expressions\n if isinstance(column, AliasedExpression):\n column = column.exp\n arguments[arg.name] = column\n if combinator is not None and combinator.is_applicable(arg.name):\n arguments[arg.name] = combinator.apply(arguments[arg.name])\n combinator_applied = True\n\n if combinator and not combinator_applied:\n raise InvalidSearchQuery(\"Invalid combinator: Arguments passed were incompatible\")\n\n resolved_function = self.resolve_snql_function(\n snql_function, arguments, alias, resolve_only\n )\n if resolved_function is not None:\n return resolved_function\n if snql_function.requires_other_aggregates:\n self.requires_other_aggregates = True\n\n return snql_function.snql_column(arguments, alias)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _handle_objects_preventing_db_destruction(\n self, cursor, parameters, verbosity, autoclobber\n ):\n # There are objects in the test tablespace which prevent dropping it\n # The easy fix is to drop the test user -- but are we allowed to do so?\n self.log(\n \"There are objects in the old test database which prevent its destruction.\"\n \"\\nIf they belong to the test user, deleting the user will allow the test \"\n \"database to be recreated.\\n\"\n \"Otherwise, you will need to find and remove each of these objects, \"\n \"or use a different tablespace.\\n\"\n )\n if self._test_user_create():\n if not autoclobber:\n confirm = input(\"Type 'yes' to delete user %s: \" % parameters[\"user\"])\n if autoclobber or confirm == \"yes\":\n try:\n if verbosity >= 1:\n self.log(\"Destroying old test user...\")\n self._destroy_test_user(cursor, parameters, verbosity)\n except Exception as e:\n self.log(\"Got an error destroying the test user: %s\" % e)\n sys.exit(2)\n try:\n if verbosity >= 1:\n self.log(\n \"Destroying old test database for alias '%s'...\"\n % self.connection.alias\n )\n self._execute_test_db_destruction(cursor, parameters, verbosity)\n except Exception as e:\n self.log(\"Got an error destroying the test database: %s\" % e)\n sys.exit(2)\n else:\n self.log(\"Tests cancelled -- test database cannot be recreated.\")\n sys.exit(1)\n else:\n self.log(\n \"Django is configured to use pre-existing test user '%s',\"\n \" and will not attempt to delete it.\" % parameters[\"user\"]\n )\n self.log(\"Tests cancelled -- test database cannot be recreated.\")\n sys.exit(1)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def get_json(\n self, force: bool = False, silent: bool = False, cache: bool = True\n ) -> t.Any | None:\n \"\"\"Parse :attr:`data` as JSON.\n\n If the mimetype does not indicate JSON\n (:mimetype:`application/json`, see :attr:`is_json`), or parsing\n fails, :meth:`on_json_loading_failed` is called and\n its return value is used as the return value. By default this\n raises a 415 Unsupported Media Type resp.\n\n :param force: Ignore the mimetype and always try to parse JSON.\n :param silent: Silence mimetype and parsing errors, and\n return ``None`` instead.\n :param cache: Store the parsed JSON to return for subsequent\n calls.\n\n .. versionchanged:: 2.3\n Raise a 415 error instead of 400.\n\n .. versionchanged:: 2.1\n Raise a 400 error if the content type is incorrect.\n \"\"\"\n if cache and self._cached_json[silent] is not Ellipsis:\n return self._cached_json[silent]\n\n if not (force or self.is_json):\n if not silent:\n return self.on_json_loading_failed(None)\n else:\n return None\n\n data = self.get_data(cache=cache)\n\n try:\n rv = self.json_module.loads(data)\n except ValueError as e:\n if silent:\n rv = None\n\n if cache:\n normal_rv, _ = self._cached_json\n self._cached_json = (normal_rv, rv)\n else:\n rv = self.on_json_loading_failed(e)\n\n if cache:\n _, silent_rv = self._cached_json\n self._cached_json = (rv, silent_rv)\n else:\n if cache:\n self._cached_json = (rv, rv)\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def get_rules(self, map: Map) -> t.Iterator[Rule]:\n for rulefactory in self.rules:\n for rule in rulefactory.get_rules(map):\n new_defaults = subdomain = None\n if rule.defaults:\n new_defaults = {}\n for key, value in rule.defaults.items():\n if isinstance(value, str):\n value = Template(value).substitute(self.context)\n new_defaults[key] = value\n if rule.subdomain is not None:\n subdomain = Template(rule.subdomain).substitute(self.context)\n new_endpoint = rule.endpoint\n if isinstance(new_endpoint, str):\n new_endpoint = Template(new_endpoint).substitute(self.context)\n yield Rule(\n Template(rule.rule).substitute(self.context),\n new_defaults,\n subdomain,\n rule.methods,\n rule.build_only,\n new_endpoint,\n rule.strict_slashes,\n )", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def run(self):\n for topic, msg_id, msg_hash, redis in RouterTopic.receive_telemetry(self.router, scope=self.scope):\n msgid_seconds_from_epoch = int(msg_id.split(\"-\")[0]) / 1000.0\n delta = time.time() - msgid_seconds_from_epoch\n if self.metric is not None:\n self.metric.set(\n name=\"router_topic_delta_seconds\",\n value=delta,\n type=\"gauge\",\n unit=\"seconds\",\n help=\"Delta time between data written to stream and router tlm start\",\n )\n\n # Check for commands to the router itself\n if \"CMD}ROUTER\" in topic:\n self.directive_count += 1\n if self.metric is not None:\n self.metric.set(\n name=\"router_directive_total\",\n value=self.directive_count,\n type=\"counter\",\n )\n\n if msg_hash.get(b\"shutdown\"):\n self.logger.info(f\"{self.router.name}: Shutdown requested\")\n return\n if msg_hash.get(b\"connect\"):\n self.logger.info(f\"{self.router.name}: Connect requested\")\n params = []\n if msg_hash.get(b\"params\"):\n params = json.loads(msg_hash[b\"params\"])\n self.router = self.tlm.attempting(*params)\n if msg_hash.get(b\"disconnect\"):\n self.logger.info(f\"{self.router.name}: Disconnect requested\")\n self.tlm.disconnect(False)\n if msg_hash.get(b\"log_stream\"):\n if msg_hash[b\"log_stream\"].decode() == \"true\":\n self.logger.info(f\"{self.router.name}: Enable stream logging\")\n self.router.start_raw_logging\n else:\n self.logger.info(f\"{self.router.name}: Disable stream logging\")\n self.router.stop_raw_logging\n if msg_hash.get(b\"router_cmd\"):\n params = json.loads(msg_hash[b\"router_cmd\"])\n try:\n self.logger.info(\n f\"{self.router.name}: router_cmd: {params['cmd_name']} {' '.join(params['cmd_params'])}\"\n )\n self.router.interface_cmd(params[\"cmd_name\"], *params[\"cmd_params\"])\n except RuntimeError as error:\n self.logger.error(f\"{self.router.name}: router_cmd: {repr(error)}\")\n return error.message\n return \"SUCCESS\"\n if msg_hash.get(b\"protocol_cmd\"):\n params = json.loads(msg_hash[b\"protocol_cmd\"])\n try:\n self.logger.info(\n f\"{self.router.name}: protocol_cmd: {params['cmd_name']} {' '.join(params['cmd_params'])} read_write: {params['read_write']} index: {params['index']}\"\n )\n self.router.protocol_cmd(\n params[\"cmd_name\"],\n *params[\"cmd_params\"],\n read_write=params[\"read_write\"],\n index=params[\"index\"],\n )\n except RuntimeError as error:\n self.logger.error(f\"{self.router.name}: protoco_cmd: {repr(error)}\")\n return error.message\n return \"SUCCESS\"\n return \"SUCCESS\"\n\n if self.router.connected():\n self.count += 1\n if self.metric is not None:\n self.metric.set(name=\"router_tlm_total\", value=self.count, type=\"counter\")\n\n target_name = msg_hash[b\"target_name\"].decode()\n packet_name = msg_hash[b\"packet_name\"].decode()\n\n packet = System.telemetry.packet(target_name, packet_name)\n packet.stored = ConfigParser.handle_true_false(msg_hash[b\"stored\"].decode())\n packet.received_time = from_nsec_from_epoch(int(msg_hash[b\"time\"]))\n packet.received_count = int(msg_hash[b\"received_count\"])\n packet.buffer = msg_hash[b\"buffer\"]\n\n try:\n self.router.write(packet)\n RouterStatusModel.set(self.router.as_json(), queued=True, scope=self.scope)\n return \"SUCCESS\"\n except RuntimeError as error:\n self.logger.error(f\"{self.router.name}: {repr(error)}\")\n return repr(error)", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def InitSkins():\n\tglobal currentPrimarySkin, currentDisplaySkin, resolutions\n\t# #################################################################################################\n\tif isfile(\"/etc/.restore_skins\"):\n\t\tunlink(\"/etc/.restore_skins\")\n\t\tlastPath = \"\"\n\t\tfor skin in sorted(glob(\"/usr/lib/enigma2/python/Plugins/Extensions/*/ActivateSkinSettings.py*\")):\n\t\t\ttry:\n\t\t\t\tprint(f\"[Skin] RESTORE_SKIN: Restore skin from '{skin}'...\")\n\t\t\t\tskinPath, skinExt = splitext(skin)\n\t\t\t\tif skinPath == lastPath or skinExt not in (\".py\", \".pyc\"):\n\t\t\t\t\tprint(\"[Skin] RESTORE_SKIN: Skip!\")\n\t\t\t\t\tcontinue\n\t\t\t\tlastPath = skinPath\n\t\t\t\tif getattr(__import__(skin.replace(\"/usr/lib/enigma2/python/\", \"\").replace(skinExt, \"\").replace(\"/\", \".\"), fromlist=[\"ActivateSkinSettings\"]), \"ActivateSkinSettings\")().WriteSkin(True):\n\t\t\t\t\tprint(\"[Skin] RESTORE_SKIN: Failed!\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"[Skin] RESTORE_SKIN: Done!\")\n\t\t\texcept Exception as err:\n\t\t\t\tprint(f\"[Skin] RESTORE_SKIN: Error occurred! ({err})\")\n\t# #################################################################################################\n\trunCallbacks = False\n\t# Add the emergency skin. This skin should provide enough functionality\n\t# to enable basic GUI functions to work.\n\tloadSkin(EMERGENCY_SKIN, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID)\n\t# Add the subtitle skin.\n\tloadSkin(SUBTITLE_SKIN, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID)\n\t# Add the main GUI skin.\n\tresult = []\n\tfor skin, name in [(config.skin.primary_skin.value, \"current\"), (DEFAULT_SKIN, \"default\")]:\n\t\tif skin in result: # Don't try to add a skin that has already failed.\n\t\t\tcontinue\n\t\tconfig.skin.primary_skin.value = skin\n\t\tif loadSkin(config.skin.primary_skin.value, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID):\n\t\t\tcurrentPrimarySkin = config.skin.primary_skin.value\n\t\t\tbreak\n\t\tprint(f\"[Skin] Error: Adding {name} GUI skin '{config.skin.primary_skin.value}' has failed!\")\n\t\tresult.append(skin)\n\t# Add the front panel / display / lcd skin.\n\tresult = []\n\tfor skin, name in [(config.skin.display_skin.value, \"current\"), (DEFAULT_DISPLAY_SKIN, \"default\")]:\n\t\tif skin in result: # Don't try to add a skin that has already failed.\n\t\t\tcontinue\n\t\tconfig.skin.display_skin.value = skin\n\t\tif loadSkin(config.skin.display_skin.value, scope=SCOPE_LCDSKIN, desktop=getDesktop(DISPLAY_SKIN_ID), screenID=DISPLAY_SKIN_ID):\n\t\t\tcurrentDisplaySkin = config.skin.display_skin.value\n\t\t\tbreak\n\t\tprint(f\"[Skin] Error: Adding {name} display skin '{config.skin.display_skin.value}' has failed!\")\n\t\tresult.append(skin)\n\t# Add the activated optional skin parts.\n\tif currentPrimarySkin is not None:\n\t\tpartsDir = resolveFilename(SCOPE_GUISKIN, pathjoin(dirname(currentPrimarySkin), \"mySkin\", \"\"))\n\t\tif pathExists(partsDir) and currentPrimarySkin != DEFAULT_SKIN:\n\t\t\tfor file in sorted(listdir(partsDir)):\n\t\t\t\tif file.startswith(\"skin_\") and file.endswith(\".xml\"):\n\t\t\t\t\tpartsFile = pathjoin(partsDir, file)\n\t\t\t\t\tif not loadSkin(partsFile, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID):\n\t\t\t\t\t\tprint(f\"[Skin] Error: Failed to load modular skin file '{partsFile}'!\")\n\t# Add an optional skin related user skin \"user_skin_<SkinName>.xml\". If there is\n\t# not a skin related user skin then try to add am optional generic user skin.\n\tresult = None\n\tif isfile(resolveFilename(SCOPE_SKINS, config.skin.primary_skin.value)):\n\t\tname = USER_SKIN_TEMPLATE % dirname(config.skin.primary_skin.value)\n\t\tif isfile(resolveFilename(SCOPE_GUISKIN, name)):\n\t\t\tresult = loadSkin(name, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID)\n\tif result is None:\n\t\tloadSkin(USER_SKIN, scope=SCOPE_GUISKIN, desktop=getDesktop(GUI_SKIN_ID), screenID=GUI_SKIN_ID)\n\tresolution = resolutions.get(GUI_SKIN_ID, (0, 0, 0))\n\tif resolution[0] and resolution[1]:\n\t\tgMainDC.getInstance().setResolution(resolution[0], resolution[1])\n\t\tgetDesktop(GUI_SKIN_ID).resize(eSize(resolution[0], resolution[1]))\n\trunCallbacks = True\n\t# Load all XML templates.\n\treloadSkinTemplates()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def process_stale_scc(graph: Graph, scc: list[str], manager: BuildManager) -> None:\n \"\"\"Process the modules in one SCC from source code.\n\n Exception: If quick_and_dirty is set, use the cache for fresh modules.\n \"\"\"\n stale = scc\n for id in stale:\n # We may already have parsed the module, or not.\n # If the former, parse_file() is a no-op.\n graph[id].parse_file()\n if \"typing\" in scc:\n # For historical reasons we need to manually add typing aliases\n # for built-in generic collections, see docstring of\n # SemanticAnalyzerPass2.add_builtin_aliases for details.\n typing_mod = graph[\"typing\"].tree\n assert typing_mod, \"The typing module was not parsed\"\n mypy.semanal_main.semantic_analysis_for_scc(graph, scc, manager.errors)\n\n # Track what modules aren't yet done so we can finish them as soon\n # as possible, saving memory.\n unfinished_modules = set(stale)\n for id in stale:\n graph[id].type_check_first_pass()\n if not graph[id].type_checker().deferred_nodes:\n unfinished_modules.discard(id)\n graph[id].detect_possibly_undefined_vars()\n graph[id].finish_passes()\n\n while unfinished_modules:\n for id in stale:\n if id not in unfinished_modules:\n continue\n if not graph[id].type_check_second_pass():\n unfinished_modules.discard(id)\n graph[id].detect_possibly_undefined_vars()\n graph[id].finish_passes()\n for id in stale:\n graph[id].generate_unused_ignore_notes()\n graph[id].generate_ignore_without_code_notes()\n if any(manager.errors.is_errors_for_file(graph[id].xpath) for id in stale):\n for id in stale:\n graph[id].transitive_error = True\n for id in stale:\n if graph[id].xpath not in manager.errors.ignored_files:\n errors = manager.errors.file_messages(\n graph[id].xpath, formatter=manager.error_formatter\n )\n manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), errors, False)\n graph[id].write_cache()\n graph[id].mark_as_rechecked()", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def CalculateNearestPointDistanceSquaredList(self, inSourcePointList, inTargetPointList):\n if PhactoriDbg(100):\n myDebugPrint3(\"CalculateNearestPointDistanceSquaredList entered\\n\")\n resultDistancedSquaredList = []\n resultClosestTargetIndexList = []\n localmaxfloat = sys.float_info.max\n if len(inTargetPointList) == 0:\n if PhactoriDbg(100):\n myDebugPrint3(\"no points on this process, returning noresult list\\n\")\n for idx in range(0, len(inSourcePointList)):\n resultDistancedSquaredList.append(localmaxfloat)\n return resultDistancedSquaredList\n\n for srcPnt in inSourcePointList:\n if PhactoriDbg(100):\n myDebugPrint3(\"doing point: \" + str(srcPnt) + \"\\n\")\n tgtPnt = inTargetPointList[0]\n closetsDistSqrd = vecDistanceSquared(srcPnt, tgtPnt)\n closestIndex = 0\n for idx, tgtPnt in enumerate(inTargetPointList):\n testDist = vecDistanceSquared(srcPnt, tgtPnt)\n if testDist < closetsDistSqrd:\n closetsDistSqrd = testDist\n closestIndex = idx\n if PhactoriDbg(100):\n myDebugPrint3(\"result: \" + str(closetsDistSqrd) + \" \" + str(closestIndex) + \"\\n\")\n resultDistancedSquaredList.append(closetsDistSqrd)\n resultClosestTargetIndexList.append(closestIndex)\n if PhactoriDbg(100):\n myDebugPrint3(\"CalculateNearestPointDistanceSquaredList returning\\n\")\n return resultDistancedSquaredList, resultClosestTargetIndexList", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def buildTimerEntry(self, timer, processed):\n\t\twidth = self.timerListWidget.getItemSize().width()\n\t\theight = self.timerListWidget.getItemSize().height()\n\t\tif timer.timerType in (POWER_TIMERTYPE.AUTOSTANDBY, POWER_TIMERTYPE.AUTODEEPSTANDBY):\n\t\t\trepeatIcon = self.iconOnce if timer.autosleeprepeat == \"once\" else self.iconRepeat\n\t\t\ttopText = None\n\t\t\tbottomText = _(\"Delay: %s\") % ngettext(\"%d Minute\", \"%d Minutes\", timer.autosleepdelay) % timer.autosleepdelay\n\t\telse:\n\t\t\trepeatIcon = self.iconRepeat if timer.repeated else self.iconOnce\n\t\t\ttopText = _(\"At end: %s\") % POWERTIMER_AFTER_EVENT_NAMES.get(timer.afterEvent, UNKNOWN)\n\t\t\tbegin = fuzzyDate(timer.begin)\n\t\t\tif timer.repeated:\n\t\t\t\trepeatedText = []\n\t\t\t\tflags = timer.repeated\n\t\t\t\tfor dayName in DAY_LIST:\n\t\t\t\t\tif flags & 1 == 1:\n\t\t\t\t\t\trepeatedText.append(dayName)\n\t\t\t\t\tflags >>= 1\n\t\t\t\tif repeatedText == DAY_LIST:\n\t\t\t\t\trepeatedText = _(\"Everyday\")\n\t\t\t\telif repeatedText == WEEKDAYS:\n\t\t\t\t\trepeatedText = _(\"Weekdays\")\n\t\t\t\telif repeatedText == WEEKENDS:\n\t\t\t\t\trepeatedText = _(\"Weekends\")\n\t\t\t\telse:\n\t\t\t\t\trepeatedText = \", \".join([dict(SHORT_DAY_NAMES).get(x) for x in repeatedText])\n\t\t\telse:\n\t\t\t\trepeatedText = begin[0] # Date.\n\t\t\tduration = int((timer.end - timer.begin) / 60.0)\n\t\t\tbottomText = \"%s %s ... %s (%s)\" % (repeatedText, begin[1], fuzzyDate(timer.end)[1], ngettext(\"%d Min\", \"%d Mins\", duration) % duration)\n\t\tif processed:\n\t\t\tstate = TIMER_STATES.get(TimerEntry.StateEnded)\n\t\t\tstateIcon = self.iconDone\n\t\telse:\n\t\t\tstate = TIMER_STATES.get(timer.state, UNKNOWN)\n\t\t\tif timer.state == TimerEntry.StateWaiting:\n\t\t\t\tstateIcon = self.iconWait\n\t\t\telif timer.state == TimerEntry.StatePrepared:\n\t\t\t\tstateIcon = self.iconPrepared\n\t\t\telif timer.state == TimerEntry.StateRunning:\n\t\t\t\tstateIcon = self.iconZapped\n\t\t\telif timer.state == TimerEntry.StateEnded:\n\t\t\t\tstateIcon = self.iconDone\n\t\t\telse:\n\t\t\t\tstateIcon = None\n\t\tif timer.disabled:\n\t\t\tstate = TIMER_STATES.get(TimerEntry.StateDisabled, UNKNOWN)\n\t\t\tstateIcon = self.iconDisabled\n\t\tif timer.failed:\n\t\t\tstate = TIMER_STATES.get(TimerEntry.StateFailed)\n\t\t\tstateIcon = self.iconFailed\n\t\tleftOffset = self.indent + self.iconWidth + self.iconMargin\n\t\ttextWidth = width - leftOffset - self.indent\n\t\thalfWidth = textWidth // 2 - 5\n\t\tminorWidth = (textWidth - self.statusOffset) // 4 - 5\n\t\tmajorWidth = textWidth - self.statusOffset - minorWidth - 10\n\t\tres = [None]\n\t\tif repeatIcon:\n\t\t\tres.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, self.indent, ((self.topHeight - self.iconHeight) // 2), self.iconWidth, self.iconHeight, repeatIcon, None, None, BT_SCALE))\n\t\tres.append((eListboxPythonMultiContent.TYPE_TEXT, leftOffset, 0, halfWidth, self.topHeight, 0, RT_HALIGN_LEFT | RT_VALIGN_CENTER, POWERTIMER_TYPE_NAMES.get(timer.timerType, UNKNOWN)))\n\t\tif topText:\n\t\t\tres.append((eListboxPythonMultiContent.TYPE_TEXT, leftOffset + halfWidth + 10, 0, halfWidth, self.topHeight, 2, RT_HALIGN_RIGHT | RT_VALIGN_CENTER, topText))\n\t\tif stateIcon:\n\t\t\tres.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, self.indent, self.topHeight + ((self.bottomHeight - self.iconHeight) // 2), self.iconWidth, self.iconHeight, stateIcon, None, None, BT_SCALE))\n\t\tres.append((eListboxPythonMultiContent.TYPE_TEXT, leftOffset + self.statusOffset, self.topHeight, minorWidth, self.bottomHeight, 1, RT_HALIGN_LEFT | RT_VALIGN_CENTER, state))\n\t\tres.append((eListboxPythonMultiContent.TYPE_TEXT, leftOffset + self.statusOffset + minorWidth + 10, self.topHeight, majorWidth, self.bottomHeight, 2, RT_HALIGN_RIGHT | RT_VALIGN_CENTER, bottomText))\n\t\tif self.showSeparator:\n\t\t\tres.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHABLEND, 0, height - 2, width, 2, self.line, None, None, BT_SCALE))\n\t\treturn res", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def evaluate_link(self, link: Link) -> Tuple[LinkType, str]:\n \"\"\"\n Determine whether a link is a candidate for installation.\n\n :return: A tuple (result, detail), where *result* is an enum\n representing whether the evaluation found a candidate, or the reason\n why one is not found. If a candidate is found, *detail* will be the\n candidate's version string; if one is not found, it contains the\n reason the link fails to qualify.\n \"\"\"\n version = None\n if link.is_yanked and not self._allow_yanked:\n reason = link.yanked_reason or \"<none given>\"\n return (LinkType.yanked, f\"yanked for reason: {reason}\")\n\n if link.egg_fragment:\n egg_info = link.egg_fragment\n ext = link.ext\n else:\n egg_info, ext = link.splitext()\n if not ext:\n return (LinkType.format_unsupported, \"not a file\")\n if ext not in SUPPORTED_EXTENSIONS:\n return (\n LinkType.format_unsupported,\n f\"unsupported archive format: {ext}\",\n )\n if \"binary\" not in self._formats and ext == WHEEL_EXTENSION:\n reason = f\"No binaries permitted for {self.project_name}\"\n return (LinkType.format_unsupported, reason)\n if \"macosx10\" in link.path and ext == \".zip\":\n return (LinkType.format_unsupported, \"macosx10 one\")\n if ext == WHEEL_EXTENSION:\n try:\n wheel = Wheel(link.filename)\n except InvalidWheelFilename:\n return (\n LinkType.format_invalid,\n \"invalid wheel filename\",\n )\n if canonicalize_name(wheel.name) != self._canonical_name:\n reason = f\"wrong project name (not {self.project_name})\"\n return (LinkType.different_project, reason)\n\n supported_tags = self._target_python.get_unsorted_tags()\n if not wheel.supported(supported_tags):\n # Include the wheel's tags in the reason string to\n # simplify troubleshooting compatibility issues.\n file_tags = \", \".join(wheel.get_formatted_file_tags())\n reason = (\n f\"none of the wheel's tags ({file_tags}) are compatible \"\n f\"(run pip debug --verbose to show compatible tags)\"\n )\n return (LinkType.platform_mismatch, reason)\n\n version = wheel.version\n\n # This should be up by the self.ok_binary check, but see issue 2700.\n if \"source\" not in self._formats and ext != WHEEL_EXTENSION:\n reason = f\"No sources permitted for {self.project_name}\"\n return (LinkType.format_unsupported, reason)\n\n if not version:\n version = _extract_version_from_fragment(\n egg_info,\n self._canonical_name,\n )\n if not version:\n reason = f\"Missing project version for {self.project_name}\"\n return (LinkType.format_invalid, reason)\n\n match = self._py_version_re.search(version)\n if match:\n version = version[: match.start()]\n py_version = match.group(1)\n if py_version != self._target_python.py_version:\n return (\n LinkType.platform_mismatch,\n \"Python version is incorrect\",\n )\n\n supports_python = _check_link_requires_python(\n link,\n version_info=self._target_python.py_version_info,\n ignore_requires_python=self._ignore_requires_python,\n )\n if not supports_python:\n reason = f\"{version} Requires-Python {link.requires_python}\"\n return (LinkType.requires_python_mismatch, reason)\n\n logger.debug(\"Found link %s, version: %s\", link, version)\n\n return (LinkType.candidate, version)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def startTimerSetting(self):\n\t\tif checkInternetAccess(\"www.google.de\", 5) == 0:\n\t\t\tprint(\"[Programmlisten-Updater]: CHECK FOR UPDATE\")\n\t\t\tsList = downloadPUPage(self.url)\n\t\t\tfor date, name, link in sList:\n\t\t\t\tif name == config.pud.satname.value:\n\t\t\t\t\tlastdate = config.pud.lastdate.value\n\t\t\t\t\tif date > ConverDateBack(lastdate):\n\t\t\t\t\t\tself.date = date\n\t\t\t\t\t\tself.name = name\n\t\t\t\t\t\tself.link = link\n\t\t\t\t\t\tyesno_default = config.pud.update_question.value\n\t\t\t\t\t\tprint(\"[Programmlisten-Updater]: NEW SETTINGS DXANDY\")\n\t\t\t\t\t\tif config.pud.just_update.value:\n\t\t\t\t\t\t\t# Update without information\n\t\t\t\t\t\t\tself.startDownload(self.name, self.link, ConverDate(self.date))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# Auto update with confrimation\n\t\t\t\t\t\t\tself.session.openWithCallback(self.CBupdate, MessageBox, _(\"New Setting DXAndy \") + name + _(\" of \") + ConverDate(date) + _(\" available !!\" + \"\\n\\n\" + \"Do you want to install the new settings list?\"), MessageBox.TYPE_YESNO, default=yesno_default, timeout=60)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"[Programmlisten-Updater]: NO NEW UPDATE AVAILBLE\")\n\t\t\t\t\tbreak\n\t\tself.timerSetting()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_unprotected_existing_bundle_files(self, before: datetime) -> Iterator[File]:\n \"\"\"Returns all existing bundle files from analyses started before 'before' that have no protected tags\"\"\"\n\n workflow: Workflow\n for workflow in Workflow:\n protected_tags_lists = WORKFLOW_PROTECTED_TAGS.get(workflow)\n if not protected_tags_lists:\n LOG.debug(f\"No protected tags defined for {workflow}, skipping\")\n continue\n\n hk_files: list[File]\n for hk_files in self.get_bundle_files(before=before, workflow=workflow):\n hk_file: File\n for hk_file in hk_files:\n if self.has_protected_tags(hk_file, protected_tags_lists=protected_tags_lists):\n continue\n\n file_path: Path = Path(hk_file.full_path)\n if not file_path.exists():\n LOG.info(f\"File {file_path} not on disk.\")\n continue\n LOG.info(f\"File {file_path} found on disk.\")\n yield hk_file", "smellKey": "S3776", "smellId": null, "repo": "Clinical-Genomics_cg", "language": "python"} {"function": "def getBouquetList(self):\n\t\tbouquets = []\n\t\tif self.isSubservices():\n \t\t\tbouquets.append((self.getServiceName(self.subservicesBouquet), self.subservicesBouquet))\n\t\tserviceHandler = eServiceCenter.getInstance()\n\t\tif config.usage.multibouquet.value:\n\t\t\tlist = serviceHandler.list(self.bouquet_root)\n\t\t\tif list:\n\t\t\t\twhile True:\n\t\t\t\t\ts = list.getNext()\n\t\t\t\t\tif not s.valid():\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif s.flags & eServiceReference.isDirectory and not s.flags & eServiceReference.isInvisible:\n\t\t\t\t\t\tinfo = serviceHandler.info(s)\n\t\t\t\t\t\tif info:\n\t\t\t\t\t\t\tbouquets.append((info.getName(s), s))\n\t\t\t\treturn bouquets\n\t\telse:\n\t\t\tinfo = serviceHandler.info(self.bouquet_root)\n\t\t\tif info:\n\t\t\t\tbouquets.append((info.getName(self.bouquet_root), self.bouquet_root))\n\t\t\treturn bouquets\n\t\treturn None", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "@click.command(\"routes\", short_help=\"Show the routes for the app.\")\n@click.option(\n \"--sort\",\n \"-s\",\n type=click.Choice((\"endpoint\", \"methods\", \"domain\", \"rule\", \"match\")),\n default=\"endpoint\",\n help=(\n \"Method to sort routes by. 'match' is the order that Flask will match routes\"\n \" when dispatching a request.\"\n ),\n)\n@click.option(\"--all-methods\", is_flag=True, help=\"Show HEAD and OPTIONS methods.\")\n@with_appcontext\ndef routes_command(sort: str, all_methods: bool) -> None:\n \"\"\"Show all registered routes with endpoints and methods.\"\"\"\n rules = list(current_app.url_map.iter_rules())\n\n if not rules:\n click.echo(\"No routes were registered.\")\n return\n\n ignored_methods = set() if all_methods else {\"HEAD\", \"OPTIONS\"}\n host_matching = current_app.url_map.host_matching\n has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules)\n rows = []\n\n for rule in rules:\n row = [\n rule.endpoint,\n \", \".join(sorted((rule.methods or set()) - ignored_methods)),\n ]\n\n if has_domain:\n row.append((rule.host if host_matching else rule.subdomain) or \"\")\n\n row.append(rule.rule)\n rows.append(row)\n\n headers = [\"Endpoint\", \"Methods\"]\n sorts = [\"endpoint\", \"methods\"]\n\n if has_domain:\n headers.append(\"Host\" if host_matching else \"Subdomain\")\n sorts.append(\"domain\")\n\n headers.append(\"Rule\")\n sorts.append(\"rule\")\n\n try:\n rows.sort(key=itemgetter(sorts.index(sort)))\n except ValueError:\n pass\n\n rows.insert(0, headers)\n widths = [max(len(row[i]) for row in rows) for i in range(len(headers))]\n rows.insert(1, [\"-\" * w for w in widths])\n template = \" \".join(f\"{{{i}:<{w}}}\" for i, w in enumerate(widths))\n\n for row in rows:\n click.echo(template.format(*row))", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def query(\n self,\n projects: Sequence[Project],\n retention_window_start: datetime | None,\n group_queryset: BaseQuerySet,\n environments: Sequence[Environment] | None,\n sort_by: str,\n limit: int,\n cursor: Cursor | None,\n count_hits: bool,\n paginator_options: Mapping[str, Any] | None,\n search_filters: Sequence[SearchFilter] | None,\n date_from: datetime | None,\n date_to: datetime | None,\n max_hits: int | None = None,\n referrer: str | None = None,\n actor: Any | None = None,\n aggregate_kwargs: TrendsSortWeights | None = None,\n ) -> CursorResult[Group]:\n now = timezone.now()\n end = None\n paginator_options = {} if paginator_options is None else paginator_options\n end_params = [\n _f\n for _f in [\n date_to,\n get_search_filter(search_filters, \"date\", \"<\"),\n get_search_filter(search_filters, \"timestamp\", \"<\"),\n ]\n if _f\n ]\n if end_params:\n end = min(end_params)\n\n if not end:\n end = now + ALLOWED_FUTURE_DELTA\n allow_postgres_only_search = True\n else:\n allow_postgres_only_search = features.has(\n \"organizations:issue-search-allow-postgres-only-search\", projects[0].organization\n )\n\n # TODO: Presumably we only want to search back to the project's max\n # retention date, which may be closer than 90 days in the past, but\n # apparently `retention_window_start` can be None(?), so we need a\n # fallback.\n retention_date = max(_f for _f in [retention_window_start, now - timedelta(days=90)] if _f)\n start_params = [\n date_from,\n retention_date,\n get_search_filter(search_filters, \"date\", \">\"),\n get_search_filter(search_filters, \"timestamp\", \">\"),\n ]\n start = max(_f for _f in start_params if _f)\n end = max([retention_date, end])\n\n if start == retention_date and end == retention_date:\n # Both `start` and `end` must have been trimmed to `retention_date`,\n # so this entire search was against a time range that is outside of\n # retention. We'll return empty results to maintain backwards compatibility\n # with Django search (for now).\n return self.empty_result\n\n if start >= end:\n # TODO: This maintains backwards compatibility with Django search, but\n # in the future we should find a way to notify the user that their search\n # is invalid.\n return self.empty_result\n\n # If the requested sort is `date` (`last_seen`) and there\n # are no other Snuba-based search predicates, we can simply\n # return the results from Postgres.\n if (\n # XXX: Don't enable this for now, it doesn't properly respect issue platform rules for hiding issue types.\n # We'll need to consolidate where we apply the type filters if we do want this.\n allow_postgres_only_search\n and cursor is None\n and sort_by == \"date\"\n and\n # This handles tags and date parameters for search filters.\n not [\n sf\n for sf in (search_filters or ())\n if sf.key.name not in self.postgres_only_fields.union([\"date\", \"timestamp\"])\n ]\n ):\n group_queryset = (\n group_queryset.using_replica()\n .filter(last_seen__gte=start, last_seen__lte=end)\n .order_by(\"-last_seen\")\n )\n\n for sf in search_filters or ():\n # general search query:\n if \"message\" == sf.key.name and isinstance(sf.value.raw_value, str):\n group_queryset = group_queryset.filter(\n Q(type=ErrorGroupType.type_id)\n | (\n Q(type__in=get_group_types_by_category(GroupCategory.PERFORMANCE.value))\n and (\n ~Q(message__icontains=sf.value.raw_value)\n if sf.is_negation\n else Q(message__icontains=sf.value.raw_value)\n )\n )\n )\n\n paginator = DateTimePaginator(group_queryset, \"-last_seen\", **paginator_options)\n\n # When it's a simple django-only search, we count_hits like normal\n results = paginator.get_result(limit, cursor, count_hits=count_hits, max_hits=max_hits)\n metrics.timing(\n \"snuba.search.query\",\n (timezone.now() - now).total_seconds(),\n tags={\"postgres_only\": True},\n )\n return results\n\n # Here we check if all the django filters reduce the set of groups down\n # to something that we can send down to Snuba in a `group_id IN (...)`\n # clause.\n max_candidates = options.get(\"snuba.search.max-pre-snuba-candidates\")\n\n with sentry_sdk.start_span(op=\"snuba_group_query\") as span:\n group_ids = list(\n group_queryset.using_replica().values_list(\"id\", flat=True)[: max_candidates + 1]\n )\n span.set_data(\"Max Candidates\", max_candidates)\n span.set_data(\"Result Size\", len(group_ids))\n metrics.distribution(\"snuba.search.num_candidates\", len(group_ids))\n too_many_candidates = False\n if not group_ids:\n # no matches could possibly be found from this point on\n metrics.incr(\"snuba.search.no_candidates\", skip_internal=False)\n return self.empty_result\n elif len(group_ids) > max_candidates:\n # If the pre-filter query didn't include anything to significantly\n # filter down the number of results (from 'first_release', 'status',\n # 'bookmarked_by', 'assigned_to', 'unassigned', or 'subscribed_by')\n # then it might have surpassed the `max_candidates`. In this case,\n # we *don't* want to pass candidates down to Snuba, and instead we\n # want Snuba to do all the filtering/sorting it can and *then* apply\n # this queryset to the results from Snuba, which we call\n # post-filtering.\n metrics.incr(\"snuba.search.too_many_candidates\", skip_internal=False)\n too_many_candidates = True\n group_ids = []\n\n sort_field = self.sort_strategies[sort_by]\n chunk_growth = options.get(\"snuba.search.chunk-growth-rate\")\n max_chunk_size = options.get(\"snuba.search.max-chunk-size\")\n chunk_limit = limit\n offset = 0\n num_chunks = 0\n hits = self.calculate_hits(\n group_ids,\n too_many_candidates,\n sort_field,\n projects,\n retention_window_start,\n group_queryset,\n environments,\n sort_by,\n limit,\n cursor,\n count_hits,\n paginator_options,\n search_filters,\n start,\n end,\n actor,\n )\n if count_hits and hits == 0:\n return self.empty_result\n\n paginator_results = self.empty_result\n result_groups = []\n result_group_ids = set()\n\n max_time = options.get(\"snuba.search.max-total-chunk-time-seconds\")\n time_start = time.time()\n more_results = False\n\n # Do smaller searches in chunks until we have enough results\n # to answer the query (or hit the end of possible results). We do\n # this because a common case for search is to return 100 groups\n # sorted by `last_seen`, and we want to avoid returning all of\n # a project's groups and then post-sorting them all in Postgres\n # when typically the first N results will do.\n while (time.time() - time_start) < max_time:\n num_chunks += 1\n\n # grow the chunk size on each iteration to account for huge projects\n # and weird queries, up to a max size\n chunk_limit = min(int(chunk_limit * chunk_growth), max_chunk_size)\n # but if we have group_ids always query for at least that many items\n chunk_limit = max(chunk_limit, len(group_ids))\n\n # {group_id: group_score, ...}\n snuba_groups, total = self.snuba_search(\n start=start,\n end=end,\n project_ids=[p.id for p in projects],\n environment_ids=environments and [environment.id for environment in environments],\n organization=projects[0].organization,\n sort_field=sort_field,\n cursor=cursor,\n group_ids=group_ids,\n limit=chunk_limit,\n offset=offset,\n search_filters=search_filters,\n referrer=referrer,\n actor=actor,\n aggregate_kwargs=aggregate_kwargs,\n )\n metrics.distribution(\"snuba.search.num_snuba_results\", len(snuba_groups))\n count = len(snuba_groups)\n more_results = count >= limit and (offset + limit) < total\n offset += len(snuba_groups)\n\n if not snuba_groups:\n break\n\n if group_ids:\n # pre-filtered candidates were passed down to Snuba, so we're\n # finished with filtering and these are the only results. Note\n # that because we set the chunk size to at least the size of\n # the group_ids, we know we got all of them (ie there are\n # no more chunks after the first)\n result_groups = snuba_groups\n if count_hits and hits is None:\n hits = len(snuba_groups)\n else:\n # pre-filtered candidates were *not* passed down to Snuba,\n # so we need to do post-filtering to verify Sentry DB predicates\n filtered_group_ids = group_queryset.filter(\n id__in=[gid for gid, _ in snuba_groups]\n ).values_list(\"id\", flat=True)\n\n group_to_score = dict(snuba_groups)\n for group_id in filtered_group_ids:\n if group_id in result_group_ids:\n # because we're doing multiple Snuba queries, which\n # happen outside of a transaction, there is a small possibility\n # of groups moving around in the sort scoring underneath us,\n # so we at least want to protect against duplicates\n continue\n\n group_score = group_to_score[group_id]\n result_group_ids.add(group_id)\n result_groups.append((group_id, group_score))\n\n # break the query loop for one of three reasons:\n # * we started with Postgres candidates and so only do one Snuba query max\n # * the paginator is returning enough results to satisfy the query (>= the limit)\n # * there are no more groups in Snuba to post-filter\n # TODO: do we actually have to rebuild this SequencePaginator every time\n # or can we just make it after we've broken out of the loop?\n paginator_results = SequencePaginator(\n [(score, id) for (id, score) in result_groups], reverse=True, **paginator_options\n ).get_result(limit, cursor, known_hits=hits, max_hits=max_hits)\n\n if group_ids or len(paginator_results.results) >= limit or not more_results:\n break\n\n # HACK: We're using the SequencePaginator to mask the complexities of going\n # back and forth between two databases. This causes a problem with pagination\n # because we're 'lying' to the SequencePaginator (it thinks it has the entire\n # result set in memory when it does not). For this reason we need to make some\n # best guesses as to whether the `prev` and `next` cursors have more results.\n\n if len(paginator_results.results) == limit and more_results:\n # Because we are going back and forth between DBs there is a small\n # chance that we will hand the SequencePaginator exactly `limit`\n # items. In this case the paginator will assume there are no more\n # results, so we need to override the `next` cursor's results.\n paginator_results.next.has_results = True\n\n if cursor is not None and (not cursor.is_prev or len(paginator_results.results) > 0):\n # If the user passed a cursor, and it isn't already a 0 result `is_prev`\n # cursor, then it's worth allowing them to go back a page to check for\n # more results.\n paginator_results.prev.has_results = True\n\n metrics.distribution(\"snuba.search.num_chunks\", num_chunks)\n\n groups = Group.objects.in_bulk(paginator_results.results)\n paginator_results.results = [groups[k] for k in paginator_results.results if k in groups]\n\n metrics.timing(\n \"snuba.search.query\",\n (timezone.now() - now).total_seconds(),\n tags={\"postgres_only\": False},\n )\n return paginator_results", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def switchChannelDown(self):\n\t\tif not self.secondInfoBarScreen or not self.secondInfoBarScreen.shown:\n\t\t\tself.keyHide(False)\n\t\t\tif not self.LongButtonPressed or BoxInfo.getItem(\"NumVideoDecoders\", 1) <= 1:\n\t\t\t\tif not config.usage.show_bouquetalways.value:\n\t\t\t\t\tif \"keep\" not in config.usage.servicelist_cursor_behavior.value:\n\t\t\t\t\t\tself.servicelist.moveDown()\n\t\t\t\t\tself.openServiceList()\n\t\t\t\telse:\n\t\t\t\t\tself.servicelist.showFavourites()\n\t\t\t\t\tself.openServiceList()\n\t\t\telif self.LongButtonPressed:\n\t\t\t\tif not config.usage.show_bouquetalways.value:\n\t\t\t\t\tif \"keep\" not in config.usage.servicelist_cursor_behavior.value:\n\t\t\t\t\t\tself.servicelist2.moveDown()\n\t\t\t\t\tself.openServiceListPiP()\n\t\t\t\telse:\n\t\t\t\t\tself.servicelist2.showFavourites()\n\t\t\t\t\tself.openServiceListPiP()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def _build_migration_list(self, graph=None):\n \"\"\"\n Chop the lists of operations up into migrations with dependencies on\n each other. Do this by going through an app's list of operations until\n one is found that has an outgoing dependency that isn't in another\n app's migration yet (hasn't been chopped off its list). Then chop off\n the operations before it into a migration and move onto the next app.\n If the loops completes without doing anything, there's a circular\n dependency (which _should_ be impossible as the operations are\n all split at this point so they can't depend and be depended on).\n \"\"\"\n self.migrations = {}\n num_ops = sum(len(x) for x in self.generated_operations.values())\n chop_mode = False\n while num_ops:\n # On every iteration, we step through all the apps and see if there\n # is a completed set of operations.\n # If we find that a subset of the operations are complete we can\n # try to chop it off from the rest and continue, but we only\n # do this if we've already been through the list once before\n # without any chopping and nothing has changed.\n for app_label in sorted(self.generated_operations):\n chopped = []\n dependencies = set()\n for operation in list(self.generated_operations[app_label]):\n deps_satisfied = True\n operation_dependencies = set()\n for dep in operation._auto_deps:\n # Temporarily resolve the swappable dependency to\n # prevent circular references. While keeping the\n # dependency checks on the resolved model, add the\n # swappable dependencies.\n original_dep = dep\n dep, is_swappable_dep = self._resolve_dependency(dep)\n if dep.app_label != app_label:\n # External app dependency. See if it's not yet\n # satisfied.\n for other_operation in self.generated_operations.get(\n dep.app_label, []\n ):\n if self.check_dependency(other_operation, dep):\n deps_satisfied = False\n break\n if not deps_satisfied:\n break\n else:\n if is_swappable_dep:\n operation_dependencies.add(\n (\n original_dep.app_label,\n original_dep.model_name,\n )\n )\n elif dep.app_label in self.migrations:\n operation_dependencies.add(\n (\n dep.app_label,\n self.migrations[dep.app_label][-1].name,\n )\n )\n else:\n # If we can't find the other app, we add a\n # first/last dependency, but only if we've\n # already been through once and checked\n # everything.\n if chop_mode:\n # If the app already exists, we add a\n # dependency on the last migration, as\n # we don't know which migration\n # contains the target field. If it's\n # not yet migrated or has no\n # migrations, we use __first__.\n if graph and graph.leaf_nodes(dep.app_label):\n operation_dependencies.add(\n graph.leaf_nodes(dep.app_label)[0]\n )\n else:\n operation_dependencies.add(\n (dep.app_label, \"__first__\")\n )\n else:\n deps_satisfied = False\n if deps_satisfied:\n chopped.append(operation)\n dependencies.update(operation_dependencies)\n del self.generated_operations[app_label][0]\n else:\n break\n # Make a migration! Well, only if there's stuff to put in it\n if dependencies or chopped:\n if not self.generated_operations[app_label] or chop_mode:\n subclass = type(\n \"Migration\",\n (Migration,),\n {\"operations\": [], \"dependencies\": []},\n )\n instance = subclass(\n \"auto_%i\" % (len(self.migrations.get(app_label, [])) + 1),\n app_label,\n )\n instance.dependencies = list(dependencies)\n instance.operations = chopped\n instance.initial = app_label not in self.existing_apps\n self.migrations.setdefault(app_label, []).append(instance)\n chop_mode = False\n else:\n self.generated_operations[app_label] = (\n chopped + self.generated_operations[app_label]\n )\n new_num_ops = sum(len(x) for x in self.generated_operations.values())\n if new_num_ops == num_ops:\n if not chop_mode:\n chop_mode = True\n else:\n raise ValueError(\n \"Cannot resolve operation dependencies: %r\"\n % self.generated_operations\n )\n num_ops = new_num_ops", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def ensure_crash_rate_in_bounds(\n data: Any,\n request: Request,\n organization,\n CRASH_RATE_METRIC_KEY: str,\n lower_bound: float = 0.0,\n upper_bound: float = 1.0,\n):\n \"\"\"\n Ensures that crash rate metric will always have value in expected bounds, and\n that invalid value is never returned to the customer by replacing all the invalid values with\n the bound value.\n Invalid crash rate can happen due to the corrupted data that is used to calculate the metric\n (see: https://github.com/getsentry/sentry/issues/73172)\n\n Example format of data argument:\n {\n ...\n \"groups\" : [\n ...\n \"series\": {..., \"session.crash_free_rate\": [..., None, 0.35]},\n \"totals\": {..., \"session.crash_free_rate\": 0.35}\n ]\n }\n \"\"\"\n groups = data[\"groups\"]\n for group in groups:\n if \"series\" in group:\n series = group[\"series\"]\n if CRASH_RATE_METRIC_KEY in series:\n for i, value in enumerate(series[CRASH_RATE_METRIC_KEY]):\n try:\n value = float(value)\n if value < lower_bound or value > upper_bound:\n with sentry_sdk.isolation_scope() as scope:\n scope.set_tag(\"organization\", organization.id)\n scope.set_extra(f\"{CRASH_RATE_METRIC_KEY} value in series\", value)\n scope.set_extra(\"request_query_params\", request.query_params)\n sentry_sdk.capture_message(\n f\"{CRASH_RATE_METRIC_KEY} not in (f{lower_bound}, f{upper_bound})\"\n )\n if value < lower_bound:\n series[CRASH_RATE_METRIC_KEY][i] = lower_bound\n else:\n series[CRASH_RATE_METRIC_KEY][i] = upper_bound\n except TypeError:\n # value is not a number\n continue\n\n if \"totals\" in group:\n totals = group[\"totals\"]\n if CRASH_RATE_METRIC_KEY not in totals or totals[CRASH_RATE_METRIC_KEY] is None:\n # no action is needed\n continue\n value = totals[CRASH_RATE_METRIC_KEY]\n if value < lower_bound or value > upper_bound:\n with sentry_sdk.isolation_scope() as scope:\n scope.set_tag(\"organization\", organization.id)\n scope.set_extra(f\"{CRASH_RATE_METRIC_KEY} value\", totals[CRASH_RATE_METRIC_KEY])\n scope.set_extra(\"request_query_params\", request.query_params)\n sentry_sdk.capture_message(\n f\"{CRASH_RATE_METRIC_KEY} not in (f{lower_bound}, f{upper_bound})\"\n )\n if value < lower_bound:\n totals[CRASH_RATE_METRIC_KEY] = lower_bound\n else:\n totals[CRASH_RATE_METRIC_KEY] = upper_bound", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def __init__(self, session, retvalue=QUIT_SHUTDOWN, timeout=-1, default_yes=True):\n\t\tself.retval = retvalue\n\t\tself.ptsmainloopvalue = retvalue\n\t\trecordings = session.nav.getRecordings(False, Components.RecordingConfig.recType(config.recording.warn_box_restart_rec_types.getValue()))\n\t\tjobs = len(job_manager.getPendingJobs())\n\t\tinTimeshift = Screens.InfoBar.InfoBar and Screens.InfoBar.InfoBar.instance and Screens.InfoBar.InfoBar.ptsGetTimeshiftStatus(Screens.InfoBar.InfoBar.instance)\n\t\tself.connected = False\n\t\treason = \"\"\n\t\tnext_rec_time = -1\n\t\tif not recordings:\n\t\t\tnext_rec_time = session.nav.RecordTimer.getNextRecordingTime()\n#\t\tif jobs:\n#\t\t\treason = (ngettext(\"%d job is running in the background!\", \"%d jobs are running in the background!\", jobs) % jobs) + '\\n'\n#\t\t\tif jobs == 1:\n#\t\t\t\tjob = job_manager.getPendingJobs()[0]\n#\t\t\t\tif job.name == \"VFD Checker\":\n#\t\t\t\t\treason = \"\"\n#\t\t\t\telse:\n#\t\t\t\t\treason += \"%s: %s (%d%%)\\n\" % (job.getStatustext(), job.name, int(100*job.progress/float(job.end)))\n#\t\t\telse:\n#\t\t\t\treason += (_(\"%d jobs are running in the background!\") % jobs) + '\\n'\n\t\tif inTimeshift:\n\t\t\treason = _(\"You seem to be in time shift!\") + '\\n'\n\t\t\tdefault_yes = True\n\t\t\ttimeout = 30\n\t\telif recordings or (next_rec_time > 0 and (next_rec_time - time()) < 360):\n\t\t\treason = _(\"Recording(s) are in progress or coming up in few seconds!\") + '\\n'\n\t\t\tdefault_yes = False\n\t\t\ttimeout = 30\n\t\telif eStreamServer.getInstance().getConnectedClients() or StreamServiceList:\n\t\t\treason = _(\"Client is streaming from this box!\")\n\t\t\tdefault_yes = False\n\t\t\ttimeout = 30\n\t\t\tclients = eStreamServer.getInstance().getConnectedClients()\n\t\t\tif len(clients) == 1 and len(clients[0]) == 3 and clients[0][0] == \"::ffff:127.0.0.1\": # ignore internal streams\n\t\t\t\treason = \"\"\n\t\telif mediaFilesInUse(session) and retvalue in (QUIT_SHUTDOWN, QUIT_REBOOT, QUIT_RESTART, QUIT_UPGRADE_FP, QUIT_UPGRADE_PROGRAM, QUIT_UPGRADE_FRONTPANEL):\n\t\t\treason = _(\"A file from media is in use!\")\n\t\t\tdefault_yes = False\n\t\t\ttimeout = 30\n\n\t\tif reason and inStandby:\n\t\t\tsession.nav.record_event.append(self.getRecordEvent)\n\t\t\tself.skinName = \"\"\n\t\telif reason and not inStandby:\n\t\t\ttext = {\n\t\t\t\tQUIT_SHUTDOWN: _(\"Really shutdown now?\"),\n\t\t\t\tQUIT_REBOOT: _(\"Really reboot now?\"),\n\t\t\t\tQUIT_RESTART: _(\"Really restart now?\"),\n\t\t\t\tQUIT_UPGRADE_FP: _(\"Really upgrade the front panel processor and reboot now?\"),\n\t\t\t\tQUIT_MAINT: _(\"Really reboot into Recovery Mode?\"),\n\t\t\t\tQUIT_UPGRADE_PROGRAM: _(\"Really upgrade your %s %s and reboot now?\") % getBoxDisplayName(),\n\t\t\t\tQUIT_IMAGE_RESTORE: _(\"Really reflash your %s %s and reboot now?\") % getBoxDisplayName(),\n\t\t\t\tQUIT_UPGRADE_FRONTPANEL: _(\"Really upgrade the front panel and reboot now?\"),\n\t\t\t\tQUIT_WOLSHUTDOWN: _(\"Really WOL now?\")\n\t\t\t\t}.get(retvalue)\n\t\t\tif text:\n\t\t\t\tMessageBox.__init__(self, session, reason + text, type=MessageBox.TYPE_YESNO, timeout=timeout, default=default_yes)\n\t\t\t\tself.skinName = \"MessageBoxSimple\"\n\t\t\t\tsession.nav.record_event.append(self.getRecordEvent)\n\t\t\t\tself.connected = True\n\t\t\t\tself.onShow.append(self.__onShow)\n\t\t\t\tself.onHide.append(self.__onHide)\n\t\t\t\tself.isMessageBox = True\n\t\t\t\treturn\n\t\tself.isMessageBox = False\n\t\tself.skin = \"\"\"<screen position=\"1310,0\" size=\"0,0\"/>\"\"\"\n\t\tScreen.__init__(self, session)\n\t\tself.close(True)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def generate_altered_fields(self):\n \"\"\"\n Make AlterField operations, or possibly RemovedField/AddField if alter\n isn't possible.\n \"\"\"\n for app_label, model_name, field_name in sorted(\n self.old_field_keys & self.new_field_keys\n ):\n # Did the field change?\n old_model_name = self.renamed_models.get(\n (app_label, model_name), model_name\n )\n old_field_name = self.renamed_fields.get(\n (app_label, model_name, field_name), field_name\n )\n old_field = self.from_state.models[app_label, old_model_name].get_field(\n old_field_name\n )\n new_field = self.to_state.models[app_label, model_name].get_field(\n field_name\n )\n dependencies = []\n # Implement any model renames on relations; these are handled by RenameModel\n # so we need to exclude them from the comparison\n if hasattr(new_field, \"remote_field\") and getattr(\n new_field.remote_field, \"model\", None\n ):\n rename_key = resolve_relation(\n new_field.remote_field.model, app_label, model_name\n )\n if rename_key in self.renamed_models:\n new_field.remote_field.model = old_field.remote_field.model\n # Handle ForeignKey which can only have a single to_field.\n remote_field_name = getattr(new_field.remote_field, \"field_name\", None)\n if remote_field_name:\n to_field_rename_key = rename_key + (remote_field_name,)\n if to_field_rename_key in self.renamed_fields:\n # Repoint both model and field name because to_field\n # inclusion in ForeignKey.deconstruct() is based on\n # both.\n new_field.remote_field.model = old_field.remote_field.model\n new_field.remote_field.field_name = (\n old_field.remote_field.field_name\n )\n # Handle ForeignObjects which can have multiple from_fields/to_fields.\n from_fields = getattr(new_field, \"from_fields\", None)\n if from_fields:\n from_rename_key = (app_label, model_name)\n new_field.from_fields = tuple(\n [\n self.renamed_fields.get(\n from_rename_key + (from_field,), from_field\n )\n for from_field in from_fields\n ]\n )\n new_field.to_fields = tuple(\n [\n self.renamed_fields.get(rename_key + (to_field,), to_field)\n for to_field in new_field.to_fields\n ]\n )\n if old_from_fields := getattr(old_field, \"from_fields\", None):\n old_field.from_fields = tuple(old_from_fields)\n old_field.to_fields = tuple(old_field.to_fields)\n dependencies.extend(\n self._get_dependencies_for_foreign_key(\n app_label,\n model_name,\n new_field,\n self.to_state,\n )\n )\n if hasattr(new_field, \"remote_field\") and getattr(\n new_field.remote_field, \"through\", None\n ):\n rename_key = resolve_relation(\n new_field.remote_field.through, app_label, model_name\n )\n if rename_key in self.renamed_models:\n new_field.remote_field.through = old_field.remote_field.through\n old_field_dec = self.deep_deconstruct(old_field)\n new_field_dec = self.deep_deconstruct(new_field)\n # If the field was confirmed to be renamed it means that only\n # db_column was allowed to change which generate_renamed_fields()\n # already accounts for by adding an AlterField operation.\n if old_field_dec != new_field_dec and old_field_name == field_name:\n both_m2m = old_field.many_to_many and new_field.many_to_many\n neither_m2m = not old_field.many_to_many and not new_field.many_to_many\n if both_m2m or neither_m2m:\n # Either both fields are m2m or neither is\n preserve_default = True\n if (\n old_field.null\n and not new_field.null\n and not new_field.has_default()\n and new_field.db_default is models.NOT_PROVIDED\n and not new_field.many_to_many\n ):\n field = new_field.clone()\n new_default = self.questioner.ask_not_null_alteration(\n field_name, model_name\n )\n if new_default is not models.NOT_PROVIDED:\n field.default = new_default\n preserve_default = False\n else:\n field = new_field\n self.add_operation(\n app_label,\n operations.AlterField(\n model_name=model_name,\n name=field_name,\n field=field,\n preserve_default=preserve_default,\n ),\n dependencies=dependencies,\n )\n else:\n # We cannot alter between m2m and concrete fields\n self._generate_removed_field(app_label, model_name, field_name)\n self._generate_added_field(app_label, model_name, field_name)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def _find_reload_model(self, app_label, model_name, delay=False):\n if delay:\n self.is_delayed = True\n\n related_models = set()\n\n try:\n old_model = self.apps.get_model(app_label, model_name)\n except LookupError:\n pass\n else:\n # Get all relations to and from the old model before reloading,\n # as _meta.apps may change\n if delay:\n related_models = get_related_models_tuples(old_model)\n else:\n related_models = get_related_models_recursive(old_model)\n\n # Get all outgoing references from the model to be rendered\n model_state = self.models[(app_label, model_name)]\n # Directly related models are the models pointed to by ForeignKeys,\n # OneToOneFields, and ManyToManyFields.\n direct_related_models = set()\n for field in model_state.fields.values():\n if field.is_relation:\n if field.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT:\n continue\n rel_app_label, rel_model_name = _get_app_label_and_model_name(\n field.related_model, app_label\n )\n direct_related_models.add((rel_app_label, rel_model_name.lower()))\n\n # For all direct related models recursively get all related models.\n related_models.update(direct_related_models)\n for rel_app_label, rel_model_name in direct_related_models:\n try:\n rel_model = self.apps.get_model(rel_app_label, rel_model_name)\n except LookupError:\n pass\n else:\n if delay:\n related_models.update(get_related_models_tuples(rel_model))\n else:\n related_models.update(get_related_models_recursive(rel_model))\n\n # Include the model itself\n related_models.add((app_label, model_name))\n\n return related_models", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def check_argument_count(\n self,\n callee: CallableType,\n actual_types: list[Type],\n actual_kinds: list[ArgKind],\n actual_names: Sequence[str | None] | None,\n formal_to_actual: list[list[int]],\n context: Context | None,\n object_type: Type | None = None,\n callable_name: str | None = None,\n ) -> bool:\n \"\"\"Check that there is a value for all required arguments to a function.\n\n Also check that there are no duplicate values for arguments. Report found errors\n using 'messages' if it's not None. If 'messages' is given, 'context' must also be given.\n\n Return False if there were any errors. Otherwise return True\n \"\"\"\n if context is None:\n # Avoid \"is None\" checks\n context = TempNode(AnyType(TypeOfAny.special_form))\n\n # TODO(jukka): We could return as soon as we find an error if messages is None.\n\n # Collect dict of all actual arguments matched to formal arguments, with occurrence count\n all_actuals: dict[int, int] = {}\n for actuals in formal_to_actual:\n for a in actuals:\n all_actuals[a] = all_actuals.get(a, 0) + 1\n\n ok, is_unexpected_arg_error = self.check_for_extra_actual_arguments(\n callee, actual_types, actual_kinds, actual_names, all_actuals, context\n )\n\n # Check for too many or few values for formals.\n for i, kind in enumerate(callee.arg_kinds):\n if kind.is_required() and not formal_to_actual[i] and not is_unexpected_arg_error:\n # No actual for a mandatory formal\n if kind.is_positional():\n self.msg.too_few_arguments(callee, context, actual_names)\n if object_type and callable_name and \".\" in callable_name:\n self.missing_classvar_callable_note(object_type, callable_name, context)\n else:\n argname = callee.arg_names[i] or \"?\"\n self.msg.missing_named_argument(callee, context, argname)\n ok = False\n elif not kind.is_star() and is_duplicate_mapping(\n formal_to_actual[i], actual_types, actual_kinds\n ):\n if self.chk.in_checked_function() or isinstance(\n get_proper_type(actual_types[formal_to_actual[i][0]]), TupleType\n ):\n self.msg.duplicate_argument_value(callee, i, context)\n ok = False\n elif (\n kind.is_named()\n and formal_to_actual[i]\n and actual_kinds[formal_to_actual[i][0]] not in [nodes.ARG_NAMED, nodes.ARG_STAR2]\n ):\n # Positional argument when expecting a keyword argument.\n self.msg.too_many_positional_arguments(callee, context)\n ok = False\n elif callee.param_spec() is not None and not formal_to_actual[i]:\n self.msg.too_few_arguments(callee, context, actual_names)\n ok = False\n return ok", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:\n \"\"\"Return True for things that look like target for an alias.\n\n Used to know if assignments look like type aliases, function alias,\n or module alias.\n \"\"\"\n # Assignment of TypeVar(...) and other typevar-likes are passed through\n if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in (\n \"typing.TypeVar\",\n \"typing_extensions.TypeVar\",\n \"typing.ParamSpec\",\n \"typing_extensions.ParamSpec\",\n \"typing.TypeVarTuple\",\n \"typing_extensions.TypeVarTuple\",\n ):\n return True\n elif isinstance(expr, EllipsisExpr):\n return not top_level\n elif isinstance(expr, NameExpr):\n if expr.name in (\"True\", \"False\"):\n return False\n elif expr.name == \"None\":\n return not top_level\n else:\n return not self.is_private_name(expr.name)\n elif isinstance(expr, MemberExpr) and self.analyzed:\n # Also add function and module aliases.\n return (\n top_level\n and isinstance(expr.node, (FuncDef, Decorator, MypyFile))\n or isinstance(expr.node, TypeInfo)\n ) and not self.is_private_member(expr.node.fullname)\n elif isinstance(expr, IndexExpr) and (\n (isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name))\n or ( # Also some known aliases that could be member expression\n isinstance(expr.base, MemberExpr)\n and not self.is_private_member(get_qualified_name(expr.base))\n and self.get_fullname(expr.base).startswith(\n (\"builtins.\", \"typing.\", \"typing_extensions.\", \"collections.abc.\")\n )\n )\n ):\n if isinstance(expr.index, TupleExpr):\n indices = expr.index.items\n else:\n indices = [expr.index]\n if expr.base.name == \"Callable\" and len(indices) == 2:\n args, ret = indices\n if isinstance(args, EllipsisExpr):\n indices = [ret]\n elif isinstance(args, ListExpr):\n indices = args.items + [ret]\n else:\n return False\n return all(self.is_alias_expression(i, top_level=False) for i in indices)\n elif isinstance(expr, OpExpr) and expr.op == \"|\":\n return self.is_alias_expression(\n expr.left, top_level=False\n ) and self.is_alias_expression(expr.right, top_level=False)\n else:\n return False", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "async def issue_credential(\n self,\n cred_ex_record: V10CredentialExchange,\n *,\n comment: Optional[str] = None,\n retries: int = 5,\n ) -> Tuple[V10CredentialExchange, CredentialIssue]:\n \"\"\"Issue a credential.\n\n Args:\n cred_ex_record: The credential exchange record\n for which to issue a credential\n comment: optional human-readable comment pertaining to credential issue\n retries: how many times to retry on error\n\n Returns:\n Tuple: (Updated credential exchange record, credential message)\n\n \"\"\"\n\n credential_ser = None\n\n if cred_ex_record.credential:\n LOGGER.warning(\n \"issue_credential called multiple times for v1.0 credential exchange %s\",\n cred_ex_record.credential_exchange_id,\n )\n credential_ser = cred_ex_record._credential.ser\n\n elif cred_ex_record.state != V10CredentialExchange.STATE_REQUEST_RECEIVED:\n raise CredentialManagerError(\n f\"Credential exchange {cred_ex_record.credential_exchange_id} \"\n f\"in {cred_ex_record.state} state \"\n f\"(must be {V10CredentialExchange.STATE_REQUEST_RECEIVED})\"\n )\n\n else:\n cred_offer_ser = cred_ex_record._credential_offer.ser\n cred_req_ser = cred_ex_record._credential_request.ser\n cred_values = (\n cred_ex_record.credential_proposal_dict.credential_proposal.attr_dict(\n decode=False\n )\n )\n schema_id = cred_ex_record.schema_id\n cred_def_id = cred_ex_record.credential_definition_id\n\n issuer = self.profile.inject(IndyIssuer)\n multitenant_mgr = self.profile.inject_or(BaseMultitenantManager)\n if multitenant_mgr:\n ledger_exec_inst = IndyLedgerRequestsExecutor(self.profile)\n else:\n ledger_exec_inst = self.profile.inject(IndyLedgerRequestsExecutor)\n ledger = (\n await ledger_exec_inst.get_ledger_for_identifier(\n schema_id,\n txn_record_type=GET_SCHEMA,\n )\n )[1]\n async with ledger:\n schema = await ledger.get_schema(schema_id)\n credential_definition = await ledger.get_credential_definition(\n cred_ex_record.credential_definition_id\n )\n revocable = credential_definition[\"value\"].get(\"revocation\")\n\n for attempt in range(max(retries, 1)):\n if attempt > 0:\n LOGGER.info(\n \"Waiting 2s before retrying credential issuance \"\n \"for cred def '%s'\",\n cred_def_id,\n )\n await asyncio.sleep(2)\n\n if revocable:\n revoc = IndyRevocation(self._profile)\n registry_info = await revoc.get_or_create_active_registry(cred_def_id)\n if not registry_info:\n continue\n del revoc\n issuer_rev_reg, rev_reg = registry_info\n rev_reg_id = issuer_rev_reg.revoc_reg_id\n tails_path = rev_reg.tails_local_path\n else:\n rev_reg_id = None\n tails_path = None\n\n try:\n (credential_json, cred_rev_id) = await issuer.create_credential(\n schema,\n cred_offer_ser,\n cred_req_ser,\n cred_values,\n rev_reg_id,\n tails_path,\n )\n except IndyIssuerRevocationRegistryFullError:\n # unlucky, another instance filled the registry first\n continue\n\n if revocable and rev_reg.max_creds <= int(cred_rev_id):\n revoc = IndyRevocation(self._profile)\n await revoc.handle_full_registry(rev_reg_id)\n del revoc\n\n credential_ser = json.loads(credential_json)\n break\n\n if not credential_ser:\n raise CredentialManagerError(\n f\"Cred def id {cred_ex_record.credential_definition_id} \"\n \"has no active revocation registry\"\n ) from None\n\n async with self._profile.transaction() as txn:\n if revocable and cred_rev_id:\n issuer_cr_rec = IssuerCredRevRecord(\n state=IssuerCredRevRecord.STATE_ISSUED,\n cred_ex_id=cred_ex_record.credential_exchange_id,\n cred_ex_version=IssuerCredRevRecord.VERSION_1,\n rev_reg_id=rev_reg_id,\n cred_rev_id=cred_rev_id,\n )\n await issuer_cr_rec.save(\n txn,\n reason=(\n \"Created issuer cred rev record for \"\n f\"rev reg id {rev_reg_id}, index {cred_rev_id}\"\n ),\n )\n\n cred_ex_record = await V10CredentialExchange.retrieve_by_id(\n txn, cred_ex_record.credential_exchange_id, for_update=True\n )\n if cred_ex_record.state != V10CredentialExchange.STATE_REQUEST_RECEIVED:\n raise CredentialManagerError(\n f\"Credential exchange {cred_ex_record.credential_exchange_id} \"\n f\"in {cred_ex_record.state} state \"\n f\"(must be {V10CredentialExchange.STATE_REQUEST_RECEIVED})\"\n )\n cred_ex_record.state = V10CredentialExchange.STATE_ISSUED\n cred_ex_record.credential = credential_ser\n cred_ex_record.revoc_reg_id = rev_reg_id\n cred_ex_record.revocation_id = cred_rev_id\n await cred_ex_record.save(txn, reason=\"issue credential\")\n await txn.commit()\n\n credential_message = CredentialIssue(\n comment=comment,\n credentials_attach=[CredentialIssue.wrap_indy_credential(credential_ser)],\n )\n credential_message._thread = {\"thid\": cred_ex_record.thread_id}\n credential_message.assign_trace_decorator(\n self._profile.settings, cred_ex_record.trace\n )\n\n return (cred_ex_record, credential_message)", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "async def register_schema_and_creddef_indy(\n self,\n schema_name,\n version,\n schema_attrs,\n support_revocation: bool = False,\n revocation_registry_size: int = None,\n tag=None,\n ):\n # Create a schema\n schema_body = {\n \"schema_name\": schema_name,\n \"schema_version\": version,\n \"attributes\": schema_attrs,\n }\n schema_response = await self.admin_POST(\"/schemas\", schema_body)\n log_json(json.dumps(schema_response), label=\"Schema:\")\n await asyncio.sleep(2.0)\n if \"schema_id\" in schema_response:\n # schema is created directly\n schema_id = schema_response[\"schema_id\"]\n else:\n # need to wait for the endorser process\n schema_response = {\"schema_ids\": []}\n attempts = 3\n while 0 < attempts and 0 == len(schema_response[\"schema_ids\"]):\n schema_response = await self.admin_GET(\"/schemas/created\")\n if 0 == len(schema_response[\"schema_ids\"]):\n await asyncio.sleep(1.0)\n attempts = attempts - 1\n schema_id = schema_response[\"schema_ids\"][0]\n log_msg(\"Schema ID:\", schema_id)\n\n # Create a cred def for the schema\n cred_def_tag = tag if tag else (self.ident + \".\" + schema_name).replace(\" \", \"_\")\n credential_definition_body = {\n \"schema_id\": schema_id,\n \"support_revocation\": support_revocation,\n **{\n \"revocation_registry_size\": revocation_registry_size\n for _ in [\"\"]\n if support_revocation\n },\n \"tag\": cred_def_tag,\n }\n credential_definition_response = await self.admin_POST(\n \"/credential-definitions\", credential_definition_body\n )\n await asyncio.sleep(2.0)\n if \"credential_definition_id\" in credential_definition_response:\n # cred def is created directly\n credential_definition_id = credential_definition_response[\n \"credential_definition_id\"\n ]\n else:\n # need to wait for the endorser process\n credential_definition_response = {\"credential_definition_ids\": []}\n attempts = 3\n while 0 < attempts and 0 == len(\n credential_definition_response[\"credential_definition_ids\"]\n ):\n credential_definition_response = await self.admin_GET(\n \"/credential-definitions/created\"\n )\n if 0 == len(credential_definition_response[\"credential_definition_ids\"]):\n await asyncio.sleep(1.0)\n attempts = attempts - 1\n credential_definition_id = credential_definition_response[\n \"credential_definition_ids\"\n ][0]\n log_msg(\"Cred def ID:\", credential_definition_id)\n return schema_id, credential_definition_id", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def _derive_abi():\n parts = ['cp', VER_SUFFIX]\n if sysconfig.get_config_var('Py_DEBUG'):\n parts.append('d')\n if IMP_PREFIX == 'cp':\n vi = sys.version_info[:2]\n if vi < (3, 8):\n wpm = sysconfig.get_config_var('WITH_PYMALLOC')\n if wpm is None:\n wpm = True\n if wpm:\n parts.append('m')\n if vi < (3, 3):\n us = sysconfig.get_config_var('Py_UNICODE_SIZE')\n if us == 4 or (us is None and sys.maxunicode == 0x10FFFF):\n parts.append('u')\n return ''.join(parts)", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _fn_val(self, args):\n # Returns the result of calling the function args[0] with the arguments\n # args[1..len(args)-1]. Plain variables are treated as functions\n # without arguments.\n\n fn = args[0]\n\n if fn in self.variables:\n var = self.variables[fn]\n\n if len(args) == 1:\n # Plain variable\n if var._n_expansions:\n self._parse_error(\"Preprocessor variable {} recursively \"\n \"references itself\".format(var.name))\n elif var._n_expansions > 100:\n # Allow functions to call themselves, but guess that functions\n # that are overly recursive are stuck\n self._parse_error(\"Preprocessor function {} seems stuck \"\n \"in infinite recursion\".format(var.name))\n\n var._n_expansions += 1\n res = self._expand_whole(self.variables[fn].value, args)\n var._n_expansions -= 1\n return res\n\n if fn in self._functions:\n # Built-in or user-defined function\n\n py_fn, min_arg, max_arg = self._functions[fn]\n\n if len(args) - 1 < min_arg or \\\n (max_arg is not None and len(args) - 1 > max_arg):\n\n if min_arg == max_arg:\n expected_args = min_arg\n elif max_arg is None:\n expected_args = \"{} or more\".format(min_arg)\n else:\n expected_args = \"{}-{}\".format(min_arg, max_arg)\n\n raise KconfigError(\"{}:{}: bad number of arguments in call \"\n \"to {}, expected {}, got {}\"\n .format(self.filename, self.linenr, fn,\n expected_args, len(args) - 1))\n\n return py_fn(self, *args)\n\n # Environment variables are tried last\n if fn in os.environ:\n self.env_vars.add(fn)\n return os.environ[fn]\n\n return \"\"", "smellKey": "S3776", "smellId": null, "repo": "zephyrproject-rtos_zephyr-testing", "language": "python"} {"function": "def keySave(self):\n\t\tif self.avahiselect.value == \"ip\":\n\t\t\tconfig.usage.remote_fallback.value = \"http://%d.%d.%d.%d:%d\" % (tuple(self.ip.value) + (self.port.value,))\n\t\telif self.avahiselect.value != \"url\":\n\t\t\tconfig.usage.remote_fallback.value = self.avahiselect.value\n\t\tif self.avahiselect_seperate.value == \"ip\":\n\t\t\tconfig.usage.remote_fallback_import_url.value = \"http://%d.%d.%d.%d:%d\" % (tuple(self.ip_seperate.value) + (self.port_seperate.value,))\n\t\telif self.avahiselect_seperate.value == \"same\":\n\t\t\tconfig.usage.remote_fallback_import_url.value = \"\"\n\t\telif self.avahiselect_seperate.value != \"url\":\n\t\t\tconfig.usage.remote_fallback_import_url.value = self.avahiselect_seperate.value\n\t\tif config.usage.remote_fallback_alternative.value and not (self.avahi_dvb_t.value == self.avahi_dvb_c.value == self.avahi_atsc.value == \"same\"):\n\t\t\tif self.avahi_dvb_t.value == \"ip\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_t.value = \"http://%d.%d.%d.%d:%d\" % (tuple(self.ip_dvb_t.value) + (self.port_dvb_t.value,))\n\t\t\telif self.avahi_dvb_t.value == \"same\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_t.value = config.usage.remote_fallback.value\n\t\t\telif self.avahi_dvb_t.value != \"url\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_t.value = self.avahi_dvb_t.value\n\t\t\tif self.avahi_dvb_c.value == \"ip\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_c.value = \"http://%d.%d.%d.%d:%d\" % (tuple(self.ip_dvb_c.value) + (self.port_dvb_c.value,))\n\t\t\telif self.avahi_dvb_c.value == \"same\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_c.value = config.usage.remote_fallback.value\n\t\t\telif self.avahi_dvb_c.value != \"url\":\n\t\t\t\tconfig.usage.remote_fallback_dvb_c.value = self.avahi_dvb_c.value\n\t\t\tif self.avahi_atsc.value == \"ip\":\n\t\t\t\tconfig.usage.remote_fallback_atsc.value = \"http://%d.%d.%d.%d:%d\" % (tuple(self.ip_atsc.value) + (self.port_atsc.value,))\n\t\t\telif self.avahi_atsc.value == \"same\":\n\t\t\t\tconfig.usage.remote_fallback_atsc.value = config.usage.remote_fallback.value\n\t\t\telif self.avahi_atsc.value != \"url\":\n\t\t\t\tconfig.usage.remote_fallback_atsc.value = self.avahi_atsc.value\n\t\telse:\n\t\t\tconfig.usage.remote_fallback_dvb_t.value = config.usage.remote_fallback_dvb_c.value = config.usage.remote_fallback_atsc.value = \"\"\n\t\t\tconfig.usage.remote_fallback_alternative.value = False\n\t\tif config.usage.remote_fallback_import_url.value == config.usage.remote_fallback.value:\n\t\t\tconfig.usage.remote_fallback_import_url.value = \"\"\n\t\tconfig.usage.remote_fallback_enabled.save()\n\t\tconfig.usage.remote_fallback_import.save()\n\t\tconfig.usage.remote_fallback_import_url.save()\n\t\tconfig.usage.remote_fallback_import_restart.save()\n\t\tconfig.usage.remote_fallback_import_standby.save()\n\t\tconfig.usage.remote_fallback_extension_menu.save()\n\t\tconfig.usage.remote_fallback_ok.save()\n\t\tconfig.usage.remote_fallback_nok.save()\n\t\tconfig.usage.remote_fallback.save()\n\t\tconfig.usage.remote_fallback_external_timer.save()\n\t\tconfig.usage.remote_fallback_external_timer_default.save()\n\t\tconfig.usage.remote_fallback_openwebif_customize.save()\n\t\tconfig.usage.remote_fallback_openwebif_userid.save()\n\t\tconfig.usage.remote_fallback_openwebif_password.save()\n\t\tconfig.usage.remote_fallback_openwebif_port.save()\n\t\tconfig.usage.remote_fallback_alternative.save()\n\t\tconfig.usage.remote_fallback_dvb_t.save()\n\t\tconfig.usage.remote_fallback_dvb_c.save()\n\t\tconfig.usage.remote_fallback_atsc.save()\n\t\tconfigfile.save()\n\t\tif not self.remote_fallback_prev and config.usage.remote_fallback_import.value:\n\t\t\tImportChannels()\n\t\tself.close(False)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def put(self, request: Request, organization, repo_id) -> Response:\n if not request.user.is_authenticated:\n return Response(status=401)\n\n try:\n repo = Repository.objects.get(id=repo_id, organization_id=organization.id)\n except Repository.DoesNotExist:\n raise ResourceDoesNotExist\n\n if repo.status == ObjectStatus.DELETION_IN_PROGRESS:\n return Response(status=400)\n\n serializer = RepositorySerializer(data=request.data, partial=True)\n\n if not serializer.is_valid():\n return Response(serializer.errors, status=400)\n\n result = serializer.validated_data\n update_kwargs: dict[str, Any] = {}\n if result.get(\"status\"):\n if result[\"status\"] in (\"visible\", \"active\"):\n update_kwargs[\"status\"] = ObjectStatus.ACTIVE\n elif result[\"status\"] == \"hidden\":\n update_kwargs[\"status\"] = ObjectStatus.HIDDEN\n else:\n raise NotImplementedError\n if result.get(\"integrationId\"):\n integration = integration_service.get_integration(\n integration_id=result[\"integrationId\"],\n organization_id=coerce_id_from(organization),\n status=ObjectStatus.ACTIVE,\n )\n if integration is None:\n return Response({\"detail\": \"Invalid integration id\"}, status=400)\n\n update_kwargs[\"integration_id\"] = integration.id\n update_kwargs[\"provider\"] = f\"integrations:{integration.provider}\"\n\n if update_kwargs:\n old_status = repo.status\n with transaction.atomic(router.db_for_write(Repository)):\n repo.update(**update_kwargs)\n if (\n old_status == ObjectStatus.PENDING_DELETION\n and repo.status == ObjectStatus.ACTIVE\n ):\n repo.reset_pending_deletion_field_names()\n repo.delete_pending_deletion_option()\n elif repo.status == ObjectStatus.HIDDEN and old_status != repo.status:\n repository_cascade_delete_on_hide.apply_async(kwargs={\"repo_id\": repo.id})\n\n return Response(serialize(repo, request.user))", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def handleInputHelpers(self):\n\t\tcurrConfig = self[\"config\"].getCurrent()\n\t\tif currConfig is not None:\n\t\t\tif isinstance(currConfig[1], (ConfigInteger, ConfigSequence, ConfigText)):\n\t\t\t\tself[\"charConfigActions\"].setEnabled(True)\n\t\t\t\tself[\"editConfigActions\"].setEnabled(True)\n\t\t\telse:\n\t\t\t\tself[\"charConfigActions\"].setEnabled(False)\n\t\t\t\tself[\"editConfigActions\"].setEnabled(False)\n\t\t\tif isinstance(currConfig[1], ConfigSelection):\n\t\t\t\tself[\"menuConfigActions\"].setEnabled(True)\n\t\t\t\tself[\"key_menu\"].setText(_(\"MENU\"))\n\t\t\telse:\n\t\t\t\tself[\"menuConfigActions\"].setEnabled(False)\n\t\t\t\tself[\"key_menu\"].setText(\"\")\n\t\t\tif isinstance(currConfig[1], ConfigText):\n\t\t\t\tself.showVirtualKeyBoard(True)\n\t\t\t\tif \"HelpWindow\" in self and currConfig[1].help_window and currConfig[1].help_window.instance is not None:\n\t\t\t\t\thelpwindowpos = self[\"HelpWindow\"].getPosition()\n\t\t\t\t\tcurrConfig[1].help_window.instance.move(ePoint(helpwindowpos[0], helpwindowpos[1]))\n\t\t\telse:\n\t\t\t\tself.showVirtualKeyBoard(False)\n\t\t\tif isinstance(currConfig[1], ConfigMACText):\n\t\t\t\tself[\"editConfigActions\"].setEnabled(False)\n\t\t\t\tself.showVirtualKeyBoard(False)\n\t\t\tif isinstance(currConfig[1], ConfigNumber):\n\t\t\t\tself.showVirtualKeyBoard(False)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def FindNodeOrElementIdForMinMaxOneBlock(inInputCsData, ioVariableInfo):\n if PhactoriDbg(100):\n myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock entered\\n'\n ' variable is ' + ioVariableInfo.mVariableName + '\\n'\n ' min: ' + str(ioVariableInfo.mStats.mMin) + '\\n'\n ' max: ' + str(ioVariableInfo.mStats.mMax) + '\\n', 100)\n\n #detect variable type (node/element) if necessary, and save info if detected\n detectResult = ioVariableInfo.DetectVariableType(inInputCsData,\n False, True)\n if detectResult == False:\n if PhactoriDbg(100):\n myDebugPrint3('no detection: returning\\n', 100)\n return\n\n if(ioVariableInfo.mVariableType == 'node'):\n cellOrPointData = inInputCsData.GetPointData()\n if cellOrPointData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no point data: returning\\n', 100)\n return\n elif(ioVariableInfo.mVariableType == 'element'):\n cellOrPointData = inInputCsData.GetCellData()\n if cellOrPointData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no cell data: returning\\n', 100)\n return\n elif(ioVariableInfo.mVariableType == 'global'):\n cellOrPointData = inInputCsData.GetFieldData()\n if cellOrPointData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no field data: returning\\n', 100)\n return\n else:\n if PhactoriDbg(100):\n myDebugPrint3('no data type, should not be here,: returning\\n', 100)\n return\n\n varData = cellOrPointData.GetArray(ioVariableInfo.mVariableName)\n if varData == None:\n if PhactoriDbg(100):\n myDebugPrint3('no varData: returning\\n', 100)\n return\n if PhactoriDbg():\n myDebugPrint3(' y data: ' + str(varData) + '\\n')\n if PhactoriDbg():\n myDebugPrint3(' y data name: ' + varData.GetName() + '\\n')\n numTuplesX = varData.GetNumberOfTuples()\n\n if numTuplesX <= 0:\n return\n\n globalIdArray = None\n if(ioVariableInfo.mVariableType == 'node'):\n globalIdArray = cellOrPointData.GetArray('GlobalNodeId')\n if globalIdArray == None:\n if PhactoriDbg():\n myDebugPrint3(' no GlobalNodeId to find ids in list\\n')\n else:\n globalIdArray = cellOrPointData.GetArray('GlobalElementId')\n if globalIdArray == None:\n if PhactoriDbg():\n myDebugPrint3(' no GlobalNodeId to find ids in list\\n')\n\n for ii in range(0, numTuplesX):\n #vv = varData.GetTuple1(ii)\n if ioVariableInfo.mVariableIsVectorComponent:\n vecVal = varData.GetTuple3(ii)\n vv = vecVal[ioVariableInfo.mVariableComponent]\n elif ioVariableInfo.mVariableIsVectorMagnitude:\n vecVal = varData.GetTuple3(ii)\n aa = vecVal[0]\n bb = vecVal[1]\n cc = vecVal[2]\n vv = math.sqrt(aa*aa + bb*bb + cc*cc)\n else:\n vv = varData.GetTuple1(ii)\n\n if vv == ioVariableInfo.mStats.mMin:\n #if ioVariableInfo.mStats.mLocalFoundMinId == False:\n # ioVariableInfo.mStats.mMinId = globalIdArray.GetTuple1(ii)\n # ioVariableInfo.mStats.mLocalFoundMinId = True\n # if PhactoriDbg(100):\n # myDebugPrint3(\" found min node/element id: \" + \\\n # str(ioVariableInfo.mStats.mMinId) + \"\\n\", 100)\n ioVariableInfo.mStats.mLocalMinIdCount += 1\n newGId = globalIdArray.GetTuple1(ii)\n if ioVariableInfo.mStats.mLocalMinIdCount <= 5:\n if PhactoriDbg(100):\n myDebugPrint3(\" found min node/element id: \" + \\\n str(newGId) + \"\\n\"\n \" count: \" + str(ioVariableInfo.mStats.mLocalMinIdCount) + \"\\n\",\n 100)\n if ioVariableInfo.mStats.mLocalFoundMinId == False:\n ioVariableInfo.mStats.mMinId = newGId\n ioVariableInfo.mStats.mLocalFoundMinId = True\n else:\n if newGId > ioVariableInfo.mStats.mMinId:\n ioVariableInfo.mStats.mMinId = newGId\n\n if vv == ioVariableInfo.mStats.mMax:\n #if ioVariableInfo.mStats.mLocalFoundMaxId == False:\n # ioVariableInfo.mStats.mMaxId = globalIdArray.GetTuple1(ii)\n # ioVariableInfo.mStats.mLocalFoundMaxId = True\n # if PhactoriDbg(100):\n # myDebugPrint3(\" found max node/element id: \" + \\\n # str(ioVariableInfo.mStats.mMaxId) + \"\\n\", 100)\n ioVariableInfo.mStats.mLocalMaxIdCount += 1\n newGId = globalIdArray.GetTuple1(ii)\n if ioVariableInfo.mStats.mLocalMaxIdCount <= 5:\n if PhactoriDbg(100):\n myDebugPrint3(\" found max node/element id: \" + \\\n str(newGId) + \"\\n\"\n \" count: \" + str(ioVariableInfo.mStats.mLocalMaxIdCount) + \"\\n\",\n 100)\n if ioVariableInfo.mStats.mLocalFoundMaxId == False:\n ioVariableInfo.mStats.mMaxId = newGId\n ioVariableInfo.mStats.mLocalFoundMaxId = True\n else:\n if newGId > ioVariableInfo.mStats.mMaxId:\n ioVariableInfo.mStats.mMaxId = newGId\n\n if PhactoriDbg(100):\n myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock returning\\n', 100)", "smellKey": "S3776", "smellId": null, "repo": "gsjaardema_seacas-fork", "language": "python"} {"function": "def _process_symbolicator_results_for_sample(\n profile: Profile, stacktraces: list[Any], frames_sent: set[int], platform: str\n) -> None:\n if platform == \"rust\":\n\n def truncate_stack_needed(frames: list[dict[str, Any]], stack: list[Any]) -> list[Any]:\n # remove top frames related to the profiler (top of the stack)\n if frames[stack[0]].get(\"function\", \"\") == \"perf_signal_handler\":\n stack = stack[2:]\n # remove unsymbolicated frames before the runtime calls (bottom of the stack)\n if frames[stack[len(stack) - 2]].get(\"function\", \"\") == \"\":\n stack = stack[:-2]\n return stack\n\n elif platform == \"cocoa\":\n\n def truncate_stack_needed(\n frames: list[dict[str, Any]],\n stack: list[Any],\n ) -> list[Any]:\n # remove bottom frames we can't symbolicate\n if frames[stack[-1]].get(\"instruction_addr\", \"\") == \"0xffffffffc\":\n return stack[:-2]\n return stack\n\n else:\n\n def truncate_stack_needed(\n frames: list[dict[str, Any]],\n stack: list[Any],\n ) -> list[Any]:\n return stack\n\n symbolicated_frames = stacktraces[0][\"frames\"]\n symbolicated_frames_dict = get_frame_index_map(symbolicated_frames)\n\n if len(frames_sent) > 0:\n raw_frames = profile[\"profile\"][\"frames\"]\n new_frames = []\n symbolicated_frame_idx = 0\n\n for idx in range(len(raw_frames)):\n # If we didn't send the frame to symbolicator, add the raw frame.\n if idx not in frames_sent:\n new_frames.append(raw_frames[idx])\n continue\n\n # If we sent it to symbolicator, add the current symbolicated frame\n # to new_frames.\n # This works since symbolicated_frames are in the same order\n # as raw_frames (except some frames are not sent).\n for frame_idx in symbolicated_frames_dict[symbolicated_frame_idx]:\n f = symbolicated_frames[frame_idx]\n f[\"platform\"] = platform\n new_frames.append(f)\n\n # go to the next symbolicated frame result\n symbolicated_frame_idx += 1\n\n new_frames_count = (\n len(raw_frames)\n + sum(len(frames) for frames in symbolicated_frames_dict.values())\n - len(symbolicated_frames_dict)\n )\n\n # in case we're dealing with a cocoa stack, we previously made a copy\n # of the leaf frame with adjust_instruction_addr = False.\n # If the original frame doesn't happen to shows up in the middle\n # of another stack, then it'll never be used.\n # Therefore we skip this sanity check for cocoa stacks\n if platform in SHOULD_SYMBOLICATE_JS:\n assert len(new_frames) == new_frames_count\n\n profile[\"profile\"][\"frames\"] = new_frames\n elif symbolicated_frames:\n profile[\"profile\"][\"frames\"] = symbolicated_frames\n\n if platform in SHOULD_SYMBOLICATE:\n\n def get_stack(stack: list[int]) -> list[int]:\n new_stack: list[int] = []\n for index in stack:\n if index in symbolicated_frames_dict:\n # the new stack extends the older by replacing\n # a specific frame index with the indices of\n # the frames originated from the original frame\n # should inlines be present\n new_stack.extend(symbolicated_frames_dict[index])\n else:\n new_stack.append(index)\n return new_stack\n\n else:\n\n def get_stack(stack: list[int]) -> list[int]:\n return stack\n\n stacks = []\n\n for stack in profile[\"profile\"][\"stacks\"]:\n new_stack = get_stack(stack)\n\n if len(new_stack) >= 2:\n # truncate some unneeded frames in the stack (related to the profiler itself or impossible to symbolicate)\n new_stack = truncate_stack_needed(profile[\"profile\"][\"frames\"], new_stack)\n\n stacks.append(new_stack)\n\n profile[\"profile\"][\"stacks\"] = stacks", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "@classmethod\n def divide(\n cls, segments: Iterable[\"Segment\"], cuts: Iterable[int]\n ) -> Iterable[List[\"Segment\"]]:\n \"\"\"Divides an iterable of segments in to portions.\n\n Args:\n cuts (Iterable[int]): Cell positions where to divide.\n\n Yields:\n [Iterable[List[Segment]]]: An iterable of Segments in List.\n \"\"\"\n split_segments: List[\"Segment\"] = []\n add_segment = split_segments.append\n\n iter_cuts = iter(cuts)\n\n while True:\n cut = next(iter_cuts, -1)\n if cut == -1:\n return []\n if cut != 0:\n break\n yield []\n pos = 0\n\n segments_clear = split_segments.clear\n segments_copy = split_segments.copy\n\n _cell_len = cached_cell_len\n for segment in segments:\n text, _style, control = segment\n while text:\n end_pos = pos if control else pos + _cell_len(text)\n if end_pos < cut:\n add_segment(segment)\n pos = end_pos\n break\n\n if end_pos == cut:\n add_segment(segment)\n yield segments_copy()\n segments_clear()\n pos = end_pos\n\n cut = next(iter_cuts, -1)\n if cut == -1:\n if split_segments:\n yield segments_copy()\n return\n\n break\n\n else:\n before, segment = segment.split_cells(cut - pos)\n text, _style, control = segment\n add_segment(before)\n yield segments_copy()\n segments_clear()\n pos = cut\n\n cut = next(iter_cuts, -1)\n if cut == -1:\n if split_segments:\n yield segments_copy()\n return\n\n yield segments_copy()", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def fix_tasklog(apps, schema_editor):\n TaskLog = apps.get_model(\"cm\", \"TaskLog\")\n ServiceComponent = apps.get_model(\"cm\", \"ServiceComponent\")\n ClusterObject = apps.get_model(\"cm\", \"ClusterObject\")\n Host = apps.get_model(\"cm\", \"Host\")\n Cluster = apps.get_model(\"cm\", \"Cluster\")\n HostProvider = apps.get_model(\"cm\", \"HostProvider\")\n ADCM = apps.get_model(\"cm\", \"ADCM\")\n\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n cash = {}\n\n def get_content(context):\n if context not in cash:\n cash[context] = ContentType.objects.get(app_label=\"cm\", model=content[context])\n return cash[context]\n\n def get_task_obj(action, obj_id):\n if action is None:\n return None\n\n def get_obj_safe(model, obj_id):\n try:\n return model.objects.get(id=obj_id)\n except model.DoesNotExist:\n return None\n\n context = action.prototype.type\n if context == \"component\":\n obj = get_obj_safe(ServiceComponent, obj_id)\n elif context == \"service\":\n obj = get_obj_safe(ClusterObject, obj_id)\n elif context == \"host\":\n obj = get_obj_safe(Host, obj_id)\n elif context == \"cluster\":\n obj = get_obj_safe(Cluster, obj_id)\n elif context == \"provider\":\n obj = get_obj_safe(HostProvider, obj_id)\n elif context == \"adcm\":\n obj = get_obj_safe(ADCM, obj_id)\n else:\n return None\n return obj\n\n for task in TaskLog.objects.all():\n obj = get_task_obj(task.action, task.object_id)\n if obj:\n task.object_type = get_content(task.action.prototype.type)\n task.save()", "smellKey": "S3776", "smellId": null, "repo": "arenadata_adcm", "language": "python"} {"function": "@classmethod\n def deserialize(cls, did_doc: dict) -> \"DIDDoc\":\n \"\"\"Construct DIDDoc object from dict representation.\n\n Args:\n did_doc: DIDDoc dict representation\n\n Raises:\n ValueError: for bad DID or missing mandatory item.\n\n Returns: DIDDoc from input json\n\n \"\"\"\n\n rv = None\n if \"id\" in did_doc:\n rv = DIDDoc(did_doc[\"id\"])\n else:\n # heuristic: get DID to serve as DID document identifier from\n # the first OK-looking public key\n for section in (\"publicKey\", \"authentication\"):\n if rv is None and section in did_doc:\n for key_spec in did_doc[section]:\n try:\n pubkey_did = canon_did(resource(key_spec.get(\"id\", \"\")))\n if ok_did(pubkey_did):\n rv = DIDDoc(pubkey_did)\n break\n except ValueError: # no identifier here, move on to next\n break\n if rv is None:\n LOGGER.debug(\"no identifier in DID document\")\n raise ValueError(\"No identifier in DID document\")\n\n for pubkey in did_doc.get(\n \"publicKey\", {}\n ): # include all public keys, authentication pubkeys by reference\n pubkey_type = PublicKeyType.get(pubkey[\"type\"])\n authn = any(\n canon_ref(rv.did, ak.get(\"publicKey\", \"\"))\n == canon_ref(rv.did, pubkey[\"id\"])\n for ak in did_doc.get(\"authentication\", {})\n if isinstance(ak.get(\"publicKey\", None), str)\n )\n key = PublicKey( # initialization canonicalizes id\n rv.did,\n pubkey[\"id\"],\n pubkey[pubkey_type.specifier],\n pubkey_type,\n canon_did(pubkey[\"controller\"]),\n authn,\n )\n rv.pubkey[key.id] = key\n\n for akey in did_doc.get(\n \"authentication\", {}\n ): # include embedded authentication keys\n if \"publicKey\" not in akey: # not yet got it with public keys\n pubkey_type = PublicKeyType.get(akey[\"type\"])\n key = PublicKey( # initialization canonicalized id\n rv.did,\n akey[\"id\"],\n akey[pubkey_type.specifier],\n pubkey_type,\n canon_did(akey[\"controller\"]),\n True,\n )\n rv.pubkey[key.id] = key\n\n for service in did_doc.get(\"service\", {}):\n endpoint = service[\"serviceEndpoint\"]\n svc = Service( # initialization canonicalizes id\n rv.did,\n service.get(\n \"id\",\n canon_ref(rv.did, \"assigned-service-{}\".format(len(rv.service)), \";\"),\n ),\n service[\"type\"],\n rv.add_service_pubkeys(service, \"recipientKeys\"),\n service.get(\"routingKeys\", []),\n canon_ref(rv.did, endpoint, \";\") if \";\" in endpoint else endpoint,\n service.get(\"priority\", None),\n )\n rv.service[svc.id] = svc\n\n return rv", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def serialize(self, obj, attrs, user, **kwargs) -> DashboardDetailsResponse:\n from sentry.api.serializers.rest_framework.base import camel_to_snake_case\n\n page_filter_keys = [\"environment\", \"period\", \"utc\"]\n dashboard_filter_keys = [\"release\", \"releaseId\"]\n data = {\n \"id\": str(obj.id),\n \"title\": obj.title,\n \"dateCreated\": obj.date_added,\n \"createdBy\": user_service.serialize_many(filter={\"user_ids\": [obj.created_by_id]})[0],\n \"widgets\": attrs[\"widgets\"],\n \"projects\": [project.id for project in obj.projects.all()],\n \"filters\": {},\n \"permissions\": serialize(obj.permissions) if hasattr(obj, \"permissions\") else None,\n }\n\n if obj.filters is not None:\n if obj.filters.get(\"all_projects\"):\n data[\"projects\"] = list(ALL_ACCESS_PROJECTS)\n\n for key in page_filter_keys:\n if obj.filters.get(key) is not None:\n data[key] = obj.filters[key]\n\n for key in dashboard_filter_keys:\n if obj.filters.get(camel_to_snake_case(key)) is not None:\n data[\"filters\"][key] = obj.filters[camel_to_snake_case(key)]\n\n start, end = obj.filters.get(\"start\"), obj.filters.get(\"end\")\n if start and end:\n start, end = parse_timestamp(start), parse_timestamp(end)\n data[\"expired\"], data[\"start\"] = outside_retention_with_modified_start(\n start, end, obj.organization\n )\n data[\"end\"] = end\n\n return data", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def run(input_ooi: dict, raw: bytes) -> Iterable[NormalizerOutput]:\n results = json.loads(raw)\n\n pk_ooi_reference = Reference.from_str(input_ooi[\"primary_key\"])\n network_reference = Network(name=\"internet\").reference\n\n for event in results:\n # TODO: add event[\"time\"] to results. This is the time the event was first seen. Date of last scan is not\n # included in the result.\n # TODO: LeakIX want to include a confidence per plugin, since some plugins have more false positives than others\n # TODO: ssh, ssl\n\n # reset loop\n event_ooi_reference = pk_ooi_reference\n\n # Autonomous System\n as_ooi = None\n if event[\"network\"][\"asn\"]:\n as_ooi = handle_autonomous_system(event)\n yield as_ooi\n\n if event[\"ip\"]:\n for ooi in list(handle_ip(event, network_reference, as_ooi.reference if as_ooi else None)):\n yield ooi\n # we only need the last ooi's reference\n event_ooi_reference = ooi.reference\n ip_port_ooi_reference = event_ooi_reference\n\n if event[\"host\"]:\n host_ooi = handle_hostname(event, network_reference)\n yield host_ooi\n event_ooi_reference = host_ooi.reference\n\n software_ooi = None\n for ooi in list(handle_software(event, event_ooi_reference)):\n yield ooi\n if type(ooi) is Software:\n # Leak and CVE Events are bound to the software, not the softwareinstance\n software_ooi = ooi\n\n # Leak\n yield from handle_leak(event, event_ooi_reference, software_ooi)\n\n # CVES\n yield from handle_tag(event, software_ooi.reference if software_ooi else None, ip_port_ooi_reference)", "smellKey": "S3776", "smellId": null, "repo": "minvws_nl-kat-coordination", "language": "python"} {"function": "def readStates(topFilename):\n\topenFilenames = []\n\tbase = None\n\tout = None\n\tscale = 1\n\tinputMap = {}\n\tinputStates = []\n\ttime = 0\n\n\tdef handleProcessingInstruction(words):\n\t\tif not words:\n\t\t\traise ValueError('Missing processing instruction')\n\t\telif words[0] == 'base':\n\t\t\tif len(words) != 2:\n\t\t\t\traise ValueError(\n\t\t\t\t\t\t'Processing instruction \"base\" expects 1 argument, '\n\t\t\t\t\t\t'got %d' % (len(words) - 1))\n\t\t\tnonlocal base\n\t\t\tif base is not None:\n\t\t\t\traise ValueError('Attempt to change base file name')\n\t\t\tbase = words[1]\n\t\telif words[0] == 'out':\n\t\t\tif len(words) != 2:\n\t\t\t\traise ValueError(\n\t\t\t\t\t\t'Processing instruction \"out\" expects 1 argument, '\n\t\t\t\t\t\t'got %d' % (len(words) - 1))\n\t\t\tnonlocal out\n\t\t\tif out is not None:\n\t\t\t\traise ValueError('Attempt to change output file name')\n\t\t\tout = words[1]\n\t\telif words[0] == 'scale':\n\t\t\tif len(words) != 2:\n\t\t\t\traise ValueError(\n\t\t\t\t\t\t'Processing instruction \"scale\" expects 1 argument, '\n\t\t\t\t\t\t'got %d' % (len(words) - 1))\n\t\t\tnonlocal scale\n\t\t\tscale = int(words[1])\n\t\t\tprint('time scale: %.2f frames per second' % (masterClock / scale))\n\t\telif words[0] == 'input':\n\t\t\tif len(words) != 5:\n\t\t\t\traise ValueError(\n\t\t\t\t\t\t'Processing instruction \"input\" expects 4 arguments, '\n\t\t\t\t\t\t'got %d' % (len(words) - 1))\n\t\t\tname, inpType, rowStr, colStr = words[1:]\n\t\t\tif inpType != 'key':\n\t\t\t\traise ValueError('Unknown input type \"%s\"' % inpType)\n\t\t\trow = int(rowStr)\n\t\t\tcol = int(colStr)\n\t\t\tinputMap[name] = (row, col)\n\t\telif words[0] == 'include':\n\t\t\tif len(words) != 2:\n\t\t\t\traise ValueError(\n\t\t\t\t\t\t'Processing instruction \"include\" expects 1 argument, '\n\t\t\t\t\t\t'got %d' % (len(words) - 1))\n\t\t\treadFile(words[1])\n\t\telse:\n\t\t\traise ValueError('Unknown processing instruction: %s' % words[0])\n\n\tdef handleState(words):\n\t\tframes = int(words[0])\n\t\ttry:\n\t\t\tinputs = [inputMap[name] for name in words[1:]]\n\t\texcept KeyError as ex:\n\t\t\traise ValueError('Undefined input: %s' % ex)\n\t\tnonlocal time\n\t\tinputStates.append((time, inputs))\n\t\ttime += frames * scale\n\t\treturn frames\n\n\tdef readFile(filename):\n\t\tif filename in openFilenames:\n\t\t\traise ValueError('Circular include: %s' % filename)\n\t\tlocalStateCount = 0\n\t\tlocalFrameCount = 0\n\t\tstartTime = time\n\t\topenFilenames.append(filename)\n\t\ttry:\n\t\t\twith open(filename, 'r') as stream:\n\t\t\t\tfor lineNr, line in enumerate(stream, 1):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tline = line.strip()\n\t\t\t\t\t\tif not line or line[0] == '#':\n\t\t\t\t\t\t\t# Ignore empty line or comment.\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tif line[0] == '=':\n\t\t\t\t\t\t\thandleProcessingInstruction(line[1:].split())\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlocalFrameCount += handleState(line.split())\n\t\t\t\t\t\t\tlocalStateCount += 1\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\trole = 'In' if filename == openFilenames[-1] \\\n\t\t\t\t\t\t\t\telse 'included from'\n\t\t\t\t\t\tprint('%s \"%s\" line %d,' % (role, filename, lineNr),\n\t\t\t\t\t\t\tfile=stderr)\n\t\t\t\t\t\traise\n\t\texcept OSError as ex:\n\t\t\tprint('Failed to open input file \"%s\",' % filename, file=stderr)\n\t\t\traise ValueError(str(ex)) from ex\n\t\tdel openFilenames[-1]\n\t\tlocalTime = time - startTime\n\t\tprint('%-17s %5d states, %6d frames, %7.2f seconds' % (\n\t\t\t\tfilename + ':', localStateCount, localFrameCount,\n\t\t\t\tlocalTime / masterClock\n\t\t\t\t), file=stderr)\n\n\treadFile(topFilename)\n\tinputStates.append((time, []))\n\tif base is None:\n\t\traise ValueError('Base file not defined')\n\treturn base, out, inputStates", "smellKey": "S3776", "smellId": null, "repo": "openMSX_openMSX", "language": "python"} {"function": "def _parse_volume_fraction(self, volume_fraction):\n\n if numpy.isscalar(volume_fraction):\n alpha = float(volume_fraction)\n alpha = alpha\n ecs_alpha = alpha\n elif isinstance(volume_fraction, dict):\n from .species import State\n\n params = volume_fraction.copy()\n params[\"regions\"] = [self]\n alpha = State(**params)\n ecs_alpha = None\n warnings.warn(\n \"Dynamic changes to the volume fraction does not change the concentrations of species already in the region.\"\n )\n elif hasattr(volume_fraction, \"_extracellular_regions\") or hasattr(\n volume_fraction, \"_extracellular\"\n ):\n # Check Species or SpeciesOnExtracellular is defined on this region\n if (\n hasattr(volume_fraction, \"_extracellular_regions\")\n and self not in volume_fraction._extracellular_regions\n ) or (\n (\n hasattr(volume_fraction, \"_extracellular\")\n and volume_fraction._extracellular()\n and volume_fraction._extracellular()._region != self\n )\n ):\n raise RxDException(\n f\"volume fraction can be set to a State or Parameter, but it must be defined on this Extracellular region {self}\"\n )\n else:\n # make sure volume_fraction has been initialized\n if hasattr(volume_fraction, \"_extracellular_regions\") and not hasattr(\n volume_fraction, \"_extracellular_instances\"\n ):\n initializer._do_init()\n volume_fraction._finitialize()\n alpha = volume_fraction\n ecs_alpha = None\n warnings.warn(\n \"Dynamic changes to the volume fraction does not change the concentrations of species already in the region.\"\n )\n\n elif callable(volume_fraction):\n alpha = numpy.ndarray((self._nx, self._ny, self._nz))\n for i in range(self._nx):\n for j in range(self._ny):\n for k in range(self._nz):\n alpha[i, j, k] = volume_fraction(\n self._xlo + i * self._dx[0],\n self._ylo + j * self._dx[1],\n self._zlo + k * self._dx[2],\n )\n alpha = alpha\n ecs_alpha = h.Vector(alpha.flatten())\n else:\n alpha = numpy.array(volume_fraction)\n if alpha.shape != (self._nx, self._ny, self._nz):\n raise RxDException(\n \"free volume fraction alpha must be a scalar or an array the same size as the grid: {0}x{1}x{2}\".format(\n self._nx, self._ny, self._nz\n )\n )\n\n else:\n alpha = h.Vector(alpha)\n ecs_alpha = self._alpha.as_numpy().reshape(self._nx, self._ny, self._nz)\n return alpha, ecs_alpha", "smellKey": "S3776", "smellId": null, "repo": "neuronsimulator_nrn", "language": "python"} {"function": "@extend_schema(\n operation_id=\"Query Discover Events in Table Format\",\n parameters=[\n GlobalParams.END,\n GlobalParams.ENVIRONMENT,\n GlobalParams.ORG_ID_OR_SLUG,\n OrganizationParams.PROJECT,\n GlobalParams.START,\n GlobalParams.STATS_PERIOD,\n VisibilityParams.FIELD,\n VisibilityParams.PER_PAGE,\n VisibilityParams.QUERY,\n VisibilityParams.SORT,\n ],\n responses={\n 200: inline_sentry_response_serializer(\n \"OrganizationEventsResponseDict\", EventsApiResponse\n ),\n 400: OpenApiResponse(description=\"Invalid Query\"),\n 404: api_constants.RESPONSE_NOT_FOUND,\n },\n examples=DiscoverAndPerformanceExamples.QUERY_DISCOVER_EVENTS,\n )\n def get(self, request: Request, organization) -> Response:\n \"\"\"\n Retrieves discover (also known as events) data for a given organization.\n\n **Eventsv2 Deprecation Note**: Users who may be using the `eventsv2` endpoint should update their requests to the `events` endpoint outline in this document.\n The `eventsv2` endpoint is not a public endpoint and has no guaranteed availability. If you are not making any API calls to `eventsv2`, you can safely ignore this.\n Changes between `eventsv2` and `events` include:\n - Field keys in the response now match the keys in the requested `field` param exactly.\n - The `meta` object in the response now shows types in the nested `field` object.\n\n Aside from the url change, there are no changes to the request payload itself.\n\n **Note**: This endpoint is intended to get a table of results, and is not for doing a full export of data sent to\n Sentry.\n\n The `field` query parameter determines what fields will be selected in the `data` and `meta` keys of the endpoint response.\n - The `data` key contains a list of results row by row that match the `query` made\n - The `meta` key contains information about the response, including the unit or type of the fields requested\n \"\"\"\n if not self.has_feature(organization, request):\n return Response(status=404)\n\n referrer = request.GET.get(\"referrer\")\n\n try:\n snuba_params = self.get_snuba_params(\n request,\n organization,\n # This is only temporary until we come to a decision on global views\n # checking for referrer for an allowlist is a brittle check since referrer\n # can easily be set by the caller\n check_global_views=not (\n referrer in GLOBAL_VIEW_ALLOWLIST and bool(organization.flags.allow_joinleave)\n ),\n )\n except NoProjects:\n return Response(\n {\n \"data\": [],\n \"meta\": {\n \"tips\": {\n \"query\": \"Need at least one valid project to query.\",\n },\n },\n }\n )\n except InvalidParams as err:\n raise ParseError(err)\n\n batch_features = self.get_features(organization, request)\n\n use_metrics = (\n (\n batch_features.get(\"organizations:mep-rollout-flag\", False)\n and batch_features.get(\"organizations:dynamic-sampling\", False)\n )\n or batch_features.get(\"organizations:performance-use-metrics\", False)\n or batch_features.get(\"organizations:dashboards-mep\", False)\n )\n\n try:\n use_on_demand_metrics, on_demand_metrics_type = self.handle_on_demand(request)\n except ValueError:\n metric_type_values = [e.value for e in MetricSpecType]\n metric_types = \",\".join(metric_type_values)\n return Response(\n {\"detail\": f\"On demand metric type must be one of: {metric_types}\"}, status=400\n )\n\n on_demand_metrics_enabled = (\n batch_features.get(\"organizations:on-demand-metrics-extraction\", False)\n or batch_features.get(\"organizations:on-demand-metrics-extraction-widgets\", False)\n ) and use_on_demand_metrics\n\n save_discover_dataset_decision = features.has(\n \"organizations:performance-discover-dataset-selector\", organization, actor=request.user\n )\n\n dataset = self.get_dataset(request)\n metrics_enhanced = dataset in {metrics_performance, metrics_enhanced_performance}\n\n sentry_sdk.set_tag(\"performance.metrics_enhanced\", metrics_enhanced)\n allow_metric_aggregates = request.GET.get(\"preventMetricAggregates\") != \"1\"\n\n # Force the referrer to \"api.auth-token.events\" for events requests authorized through a bearer token\n if request.auth:\n referrer = API_TOKEN_REFERRER\n elif referrer not in ALLOWED_EVENTS_REFERRERS:\n if referrer:\n with sentry_sdk.isolation_scope() as scope:\n scope.set_tag(\"forbidden_referrer\", referrer)\n sentry_sdk.capture_message(\n \"Forbidden Referrer. If this is intentional, add it to `ALLOWED_EVENTS_REFERRERS`\"\n )\n referrer = Referrer.API_ORGANIZATION_EVENTS.value\n\n def _data_fn(scoped_dataset, offset, limit, query) -> dict[str, Any]:\n query_source = self.get_request_source(request)\n return scoped_dataset.query(\n selected_columns=self.get_field_list(organization, request),\n query=query,\n snuba_params=snuba_params,\n equations=self.get_equation_list(organization, request),\n orderby=self.get_orderby(request),\n offset=offset,\n limit=limit,\n referrer=referrer,\n auto_fields=True,\n auto_aggregations=True,\n use_aggregate_conditions=True,\n allow_metric_aggregates=allow_metric_aggregates,\n transform_alias_to_input_format=True,\n # Whether the flag is enabled or not, regardless of the referrer\n has_metrics=use_metrics,\n use_metrics_layer=batch_features.get(\"organizations:use-metrics-layer\", False),\n on_demand_metrics_enabled=on_demand_metrics_enabled,\n on_demand_metrics_type=on_demand_metrics_type,\n query_source=query_source,\n )\n\n @sentry_sdk.tracing.trace\n def _dashboards_data_fn(scoped_dataset, offset, limit, scoped_query, dashboard_widget_id):\n try:\n widget = DashboardWidget.objects.get(id=dashboard_widget_id)\n does_widget_have_split = widget.discover_widget_split is not None\n has_override_feature = features.has(\n \"organizations:performance-discover-widget-split-override-save\",\n organization,\n actor=request.user,\n )\n\n if does_widget_have_split and not has_override_feature:\n # This is essentially cached behaviour and we skip the check\n if widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS:\n split_dataset = errors\n elif widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE:\n # We can't add event.type:transaction for now because of on-demand.\n split_dataset = scoped_dataset\n else:\n split_dataset = discover\n\n return _data_fn(split_dataset, offset, limit, scoped_query)\n\n with handle_query_errors():\n try:\n error_results = _data_fn(errors, offset, limit, scoped_query)\n # Widget has not split the discover dataset yet, so we need to check if there are errors etc.\n has_errors = len(error_results[\"data\"]) > 0\n except SnubaError:\n has_errors = False\n error_results = None\n\n original_results = _data_fn(scoped_dataset, offset, limit, scoped_query)\n if original_results.get(\"data\") is not None:\n dataset_meta = original_results.get(\"meta\", {})\n else:\n dataset_meta = (\n list(original_results.values())[0].get(\"data\").get(\"meta\", {})\n )\n using_metrics = dataset_meta.get(\"isMetricsData\", False) or dataset_meta.get(\n \"isMetricsExtractedData\", False\n )\n has_other_data = len(original_results[\"data\"]) > 0\n\n has_transactions = has_other_data\n transaction_results = None\n if has_errors and has_other_data and not using_metrics:\n # In the case that the original request was not using the metrics dataset, we cannot be certain that other data is solely transactions.\n sentry_sdk.set_tag(\"third_split_query\", True)\n transaction_results = _data_fn(transactions, offset, limit, scoped_query)\n has_transactions = len(transaction_results[\"data\"]) > 0\n\n decision = self.save_split_decision(\n widget, has_errors, has_transactions, organization, request.user\n )\n\n if decision == DashboardWidgetTypes.DISCOVER:\n return _data_fn(discover, offset, limit, scoped_query)\n elif decision == DashboardWidgetTypes.TRANSACTION_LIKE:\n original_results[\"meta\"][\n \"discoverSplitDecision\"\n ] = DashboardWidgetTypes.get_type_name(\n DashboardWidgetTypes.TRANSACTION_LIKE\n )\n return original_results\n elif decision == DashboardWidgetTypes.ERROR_EVENTS and error_results:\n error_results[\"meta\"][\n \"discoverSplitDecision\"\n ] = DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS)\n return error_results\n else:\n return original_results\n except Exception as e:\n # Swallow the exception if it was due to the discover split, and try again one more time.\n if isinstance(e, ParseError):\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n sentry_sdk.capture_exception(e)\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n @sentry_sdk.tracing.trace\n def _discover_data_fn(scoped_dataset, offset, limit, scoped_query, discover_saved_query_id):\n try:\n discover_query = DiscoverSavedQuery.objects.get(\n id=discover_saved_query_id, organization=organization\n )\n does_widget_have_split = (\n discover_query.dataset is not DiscoverSavedQueryTypes.DISCOVER\n )\n if does_widget_have_split:\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n dataset_inferred_from_query = dataset_split_decision_inferred_from_query(\n self.get_field_list(organization, request),\n scoped_query,\n )\n has_errors = False\n has_transactions = False\n\n # See if we can infer which dataset based on selected columns and query string.\n with handle_query_errors():\n if dataset_inferred_from_query is not None:\n result = _data_fn(\n SAVED_QUERY_DATASET_MAP[dataset_inferred_from_query],\n offset,\n limit,\n scoped_query,\n )\n result[\"meta\"][\n \"discoverSplitDecision\"\n ] = DiscoverSavedQueryTypes.get_type_name(dataset_inferred_from_query)\n\n self.save_discover_saved_query_split_decision(\n discover_query,\n dataset_inferred_from_query,\n has_errors,\n has_transactions,\n )\n\n return result\n\n # Unable to infer based on selected fields and query string, so run both queries.\n else:\n map = {}\n with ThreadPoolExecutor(max_workers=3) as exe:\n futures = {\n exe.submit(\n _data_fn, get_dataset(dataset_), offset, limit, scoped_query\n ): dataset_\n for dataset_ in [\n \"errors\",\n \"transactions\",\n ]\n }\n\n for future in as_completed(futures):\n dataset_ = futures[future]\n try:\n result = future.result()\n map[dataset_] = result\n except SnubaError:\n pass\n\n try:\n error_results = map[\"errors\"]\n error_results[\"meta\"][\n \"discoverSplitDecision\"\n ] = DiscoverSavedQueryTypes.get_type_name(\n DiscoverSavedQueryTypes.ERROR_EVENTS\n )\n has_errors = len(error_results[\"data\"]) > 0\n except KeyError:\n error_results = None\n\n try:\n transaction_results = map[\"transactions\"]\n transaction_results[\"meta\"][\n \"discoverSplitDecision\"\n ] = DiscoverSavedQueryTypes.get_type_name(\n DiscoverSavedQueryTypes.TRANSACTION_LIKE\n )\n has_transactions = len(transaction_results[\"data\"]) > 0\n except KeyError:\n transaction_results = None\n\n decision = self.save_discover_saved_query_split_decision(\n discover_query,\n dataset_inferred_from_query,\n has_errors,\n has_transactions,\n )\n\n if (\n decision == DiscoverSavedQueryTypes.TRANSACTION_LIKE\n and transaction_results\n ):\n return transaction_results\n elif error_results:\n return error_results\n else:\n raise DiscoverDatasetSplitException\n\n except Exception as e:\n # Swallow the exception if it was due to the discover split, and try again one more time.\n if isinstance(e, ParseError):\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n sentry_sdk.capture_exception(e)\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n def data_fn_factory(scoped_dataset):\n \"\"\"\n This factory closes over query and dataset in order to make an additional request to the errors dataset\n in the case that this request is from a dashboard widget or a discover query and we're trying to split\n their discover dataset.\n\n This should be removed once the discover dataset is completely split in dashboards and discover.\n \"\"\"\n scoped_query = request.GET.get(\"query\")\n dashboard_widget_id = request.GET.get(\"dashboardWidgetId\", None)\n discover_saved_query_id = request.GET.get(\"discoverSavedQueryId\", None)\n\n def fn(offset, limit) -> dict[str, Any]:\n if save_discover_dataset_decision and discover_saved_query_id:\n return _discover_data_fn(\n scoped_dataset, offset, limit, scoped_query, discover_saved_query_id\n )\n\n if not (metrics_enhanced and dashboard_widget_id):\n return _data_fn(scoped_dataset, offset, limit, scoped_query)\n\n return _dashboards_data_fn(\n scoped_dataset, offset, limit, scoped_query, dashboard_widget_id\n )\n\n return fn\n\n data_fn = data_fn_factory(dataset)\n\n with handle_query_errors():\n # Don't include cursor headers if the client won't be using them\n if request.GET.get(\"noPagination\"):\n return Response(\n self.handle_results_with_meta(\n request,\n organization,\n snuba_params.project_ids,\n data_fn(0, self.get_per_page(request)),\n standard_meta=True,\n dataset=dataset,\n )\n )\n else:\n return self.paginate(\n request=request,\n paginator=GenericOffsetPaginator(data_fn=data_fn),\n on_results=lambda results: self.handle_results_with_meta(\n request,\n organization,\n snuba_params.project_ids,\n results,\n standard_meta=True,\n dataset=dataset,\n ),\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def OpenSkillsWindow(chargen, level=0):\n\tglobal SkillWindow, TextAreaControl, DoneButton, TopIndex\n\tglobal SkillTable, CostTable, PointsLeft\n\tglobal Level, ClassColumn\n\tglobal CharGen, StatLowerLimit, ButtonCount\n\n\tCharGen = chargen\n\n\tSkillPtsTable = GemRB.LoadTable (\"skillpts\")\n\tif chargen:\n\t\tpc = GemRB.GetVar (\"Slot\")\n\t\tLevel = level\n\t\tLevelDiff = 1\n\t\tClassColumn = GemRB.GetVar (\"BaseClass\") - 1\n\telse:\n\t\tpc = GemRB.GameGetSelectedPCSingle ()\n\t\tLevelDiff = GemRB.GetVar (\"LevelDiff\") or 0\n\t\tLevel = GemRB.GetPlayerStat (pc, IE_CLASSLEVELSUM) + LevelDiff\n\t\tBaseClass = GemRB.GetVar (\"LUClass\") or 0\n\t\tClassColumn = BaseClass\n\n\tPointsLeft = SkillPtsTable.GetValue (0, ClassColumn)\n\tIntBonus = GemRB.GetPlayerStat (pc, IE_INT) // 2 - 5\n\tPointsLeft += IntBonus * LevelDiff\n\n\t# at least 1 skillpoint / level advanced\n\tif PointsLeft < 1:\n\t\tPointsLeft = 1\n\n\t# start with 4x as many skills points initially\n\tif chargen:\n\t\tPointsLeft *= 4\n\n\tPointsLeft *= LevelDiff\n\n\t# Humans receive +2 skill points at level 1 and +1 skill points each level thereafter\n\tRaceBonusTable = GemRB.LoadTable (\"racskill\")\n\tRaceName = CommonTables.Races.GetRowName (IDLUCommon.GetRace (pc))\n\tPointsLeft += RaceBonusTable.GetValue (RaceName, \"BONUS\") * LevelDiff\n\tif Level < 2:\n\t\tPointsLeft += RaceBonusTable.GetValue (RaceName, \"LEVEL1_BONUS\")\n\n\tPointsLeft += GemRB.GetPlayerStat (pc, IE_UNUSED_SKILLPTS)\n\n\tSkillTable = GemRB.LoadTable(\"skills\")\n\tRowCount = SkillTable.GetRowCount()\n\n\tCostTable = GemRB.LoadTable(\"skilcost\")\n\n\tTmpTable = GemRB.LoadTable (\"skillsta\")\n\tfor i in range(RowCount):\n\t\t# Racial/Class bonuses don't factor in char-gen or leveling, so can be safely ignored\n\t\tStatID = TmpTable.GetValue (i, 0, GTV_STAT)\n\t\tif CharGen:\n\t\t\tGemRB.SetPlayerStat (pc, StatID, 0)\n\t\tStatLowerLimit[i] = GemRB.GetPlayerStat (pc, StatID, 1)\n\t\tGemRB.SetVar (\"Skill \"+str(i), StatLowerLimit[i])\n\n\tGemRB.SetToken(\"number\",str(PointsLeft) )\n\tif CharGen:\n\t\tSkillWindow = GemRB.LoadWindow (6, \"GUICG\")\n\t\tButtonCount = 10\n\t\tCharOverview.PositionCharGenWin (SkillWindow)\n\telse:\n\t\tSkillWindow = GemRB.LoadWindow (55, \"GUIREC\")\n\t\tButtonCount = 9\n\n\tfor i in range(ButtonCount):\n\t\tButton = SkillWindow.GetControl(i+93)\n\t\tButton.SetVarAssoc(\"Skill\",i)\n\t\tButton.OnPress (JustPress)\n\n\t\tButton = SkillWindow.GetControl(i*2+14)\n\t\tButton.SetVarAssoc(\"Skill\",i)\n\t\tButton.OnPress (LeftPress)\n\t\tButton.SetActionInterval (200)\n\n\t\tButton = SkillWindow.GetControl(i*2+15)\n\t\tButton.SetVarAssoc(\"Skill\",i)\n\t\tButton.OnPress (RightPress)\n\t\tButton.SetActionInterval (200)\n\n\tif chargen:\n\t\tBackButton = SkillWindow.GetControl (105)\n\t\tBackButton.SetText (15416)\n\t\tBackButton.MakeEscape()\n\t\tBackButton.OnPress (BackPress)\n\telse:\n\t\tSkillWindow.DeleteControl (105)\n\n\tDoneButton = SkillWindow.GetControl(0)\n\tDoneButton.SetText(36789)\n\tDoneButton.MakeDefault()\n\n\tTextAreaControl = SkillWindow.GetControl(92)\n\tTextAreaControl.SetText(17248)\n\n\tScrollBarControl = SkillWindow.GetControl(104)\n\tScrollBarControl.OnChange (ScrollBarPress)\n\tSkillWindow.SetEventProxy(ScrollBarControl)\n\t#decrease it with the number of controls on screen (list size)\n\tTopIndex = 0\n\tGemRB.SetVar(\"TopIndex\",0)\n\tScrollBarControl.SetVarAssoc(\"TopIndex\",RowCount-10+1)\n\n\tDoneButton.OnPress (NextPress)\n\tDoneButton.SetState(IE_GUI_BUTTON_DISABLED)\n\tRedrawSkills()\n\n\tif not chargen:\n\t\tSkillWindow.ShowModal (MODAL_SHADOW_GRAY)\n\telse:\n\t\tSkillWindow.Focus()\n\n\treturn", "smellKey": "S3776", "smellId": null, "repo": "gemrb_gemrb", "language": "python"} {"function": "def read_data(self, data, extra=None):\n self.data += data\n\n while True:\n control = self.handle_sync_pattern()\n if control and len(data) > 0: # Only return here if not blank string test\n return (control, extra)\n\n # Reduce the data to a single packet\n packet_data, extra = self.reduce_to_single_packet(extra)\n if packet_data == \"RESYNC\":\n self.sync_state = \"SEARCHING\"\n if len(data) > 0: # Only immediately resync if not blank string test\n continue\n\n # Potentially allow blank string to be sent to other protocols if no packet is ready in this one\n if isinstance(packet_data, str):\n if (len(data) <= 0) and packet_data != \"DISCONNECT\":\n # On blank string test, return blank string (if not we had a packet or need disconnect)\n # The base class handles the special match of returning STOP if on the last protocol in the\n # chain\n return super().read_data(data, extra)\n else:\n return (\n packet_data,\n extra,\n ) # Return any control code if not on blank string test\n\n self.sync_state = \"SEARCHING\"\n\n # Discard leading bytes if necessary\n if self.discard_leading_bytes > 0:\n packet_data = packet_data[self.discard_leading_bytes :]\n return (packet_data, extra)", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def getSettings(self, default_file, user_file):\n\t\t# default setting\n\t\tdefault = (\"default\", _(\"Default\"))\n\n\t\t# search typ\n\t\tstyp = default_file.replace('_Original.xml', '')\n\t\tif self.is_atile:\n\t\t\tsearch_str = '%s_atile_' % styp\n\t\telse:\n\t\t\tsearch_str = '%s_' % styp\n\n\t\t# possible setting\n\t\tchoices = []\n\t\tfiles = listdir(self.skin_base_dir)\n\t\tif exists(self.skin_base_dir + 'allScreens/%s/' % styp):\n\t\t\tfiles += listdir(self.skin_base_dir + 'allScreens/%s/' % styp)\n\t\tfor f in sorted(files, key=str.lower):\n\t\t\tif f.endswith('.xml') and f.startswith(search_str):\n\t\t\t\tfriendly_name = f.replace(search_str, \"\").replace(\".xml\", \"\").replace(\"_\", \" \")\n\t\t\t\tif exists(self.skin_base_dir + 'allScreens/%s/%s' % (styp, f)):\n\t\t\t\t\tchoices.append((self.skin_base_dir + 'allScreens/%s/%s' % (styp, f), friendly_name))\n\t\t\t\telse:\n\t\t\t\t\tchoices.append((self.skin_base_dir + f, friendly_name))\n\t\tchoices.append(default)\n\n\t\t# current setting\n\t\tmyfile = self.skin_base_dir + user_file\n\t\tcurrent = ''\n\t\tif not exists(myfile):\n\t\t\tif exists(self.skin_base_dir + default_file):\n\t\t\t\tif islink(myfile):\n\t\t\t\t\tremove(myfile)\n\t\t\t\tchdir(self.skin_base_dir)\n\t\t\t\tsymlink(default_file, user_file)\n\t\t\telif exists(self.skin_base_dir + 'allScreens/%s/%s' % (styp, default_file)):\n\t\t\t\tif islink(myfile):\n\t\t\t\t\tremove(myfile)\n\t\t\t\tchdir(self.skin_base_dir)\n\t\t\t\tsymlink(self.skin_base_dir + 'allScreens/%s/%s' % (styp, default_file), user_file)\n\t\t\telse:\n\t\t\t\tcurrent = None\n\t\tif current is None:\n\t\t\tcurrent = default\n\t\telse:\n\t\t\tfilename = realpath(myfile)\n\t\t\tfriendly_name = basename(filename).replace(search_str, \"\").replace(\".xml\", \"\").replace(\"_\", \" \")\n\t\t\tcurrent = (filename, friendly_name)\n\n\t\treturn current[0], choices", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def run(self):\n \"\"\"Run the client loop\n\n This method runs in a separate thread to poll and process events\n from the server.\n \"\"\"\n self.on_event({'status': 200})\n\n while not self._closing.is_set():\n moreitems = False\n for f in self.filters:\n for tries_left in RetryLoop(num_retries=25, backoff_start=.1, max_wait=self.poll_time):\n try:\n if not self._skip_old_events:\n # If the caller didn't provide a known\n # recent ID, our first request will ask\n # for the single most recent event from\n # the last 2 hours (the time restriction\n # avoids doing an expensive database\n # query, and leaves a big enough margin to\n # account for clock skew). If we do find a\n # recent event, we remember its ID but\n # then discard it (we are supposed to be\n # returning new/current events, not old\n # ones).\n #\n # Subsequent requests will get multiple\n # events in chronological order, and\n # filter on that same cutoff time, or\n # (once we see our first matching event)\n # the ID of the last-seen event.\n #\n # Note: self._skip_old_events must not be\n # set until the threshold is decided.\n # Otherwise, tests will be unreliable.\n filter_by_time = [[\n \"created_at\", \">=\",\n time.strftime(\n \"%Y-%m-%dT%H:%M:%SZ\",\n time.gmtime(time.time()-7200))]]\n items = self.api.logs().list(\n order=\"id desc\",\n limit=1,\n filters=f+filter_by_time).execute()\n if items[\"items\"]:\n self._skip_old_events = [\n [\"id\", \">\", str(items[\"items\"][0][\"id\"])]]\n items = {\n \"items\": [],\n \"items_available\": 0,\n }\n else:\n # No recent events. We can keep using\n # the same timestamp threshold until\n # we receive our first new event.\n self._skip_old_events = filter_by_time\n else:\n # In this case, either we know the most\n # recent matching ID, or we know there\n # were no matching events in the 2-hour\n # window before subscribing. Either way we\n # can safely ask for events in ascending\n # order.\n items = self.api.logs().list(\n order=\"id asc\",\n filters=f+self._skip_old_events).execute()\n break\n except errors.ApiError as error:\n pass\n else:\n tries_left = 0\n break\n if tries_left == 0:\n _logger.exception(\"PollClient thread could not contact API server.\")\n with self._closing_lock:\n self._closing.set()\n _thread.interrupt_main()\n return\n for i in items[\"items\"]:\n self._skip_old_events = [[\"id\", \">\", str(i[\"id\"])]]\n with self._closing_lock:\n if self._closing.is_set():\n return\n try:\n self.on_event(i)\n except Exception as e:\n _logger.exception(\"Unexpected exception from event callback.\")\n _thread.interrupt_main()\n if items[\"items_available\"] > len(items[\"items\"]):\n moreitems = True\n if not moreitems:\n self._closing.wait(self.poll_time)", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def get_context_data(self, **kwargs):\n model_name = self.kwargs[\"model_name\"]\n # Get the model class.\n try:\n app_config = apps.get_app_config(self.kwargs[\"app_label\"])\n except LookupError:\n raise Http404(_(\"App %(app_label)r not found\") % self.kwargs)\n try:\n model = app_config.get_model(model_name)\n except LookupError:\n raise Http404(\n _(\"Model %(model_name)r not found in app %(app_label)r\") % self.kwargs\n )\n\n opts = model._meta\n\n title, body, metadata = utils.parse_docstring(model.__doc__)\n title = title and utils.parse_rst(title, \"model\", _(\"model:\") + model_name)\n body = body and utils.parse_rst(body, \"model\", _(\"model:\") + model_name)\n\n # Gather fields/field descriptions.\n fields = []\n for field in opts.fields:\n # ForeignKey is a special case since the field will actually be a\n # descriptor that returns the other object\n if isinstance(field, models.ForeignKey):\n data_type = field.remote_field.model.__name__\n app_label = field.remote_field.model._meta.app_label\n verbose = utils.parse_rst(\n (\n _(\"the related `%(app_label)s.%(data_type)s` object\")\n % {\n \"app_label\": app_label,\n \"data_type\": data_type,\n }\n ),\n \"model\",\n _(\"model:\") + data_type,\n )\n else:\n data_type = get_readable_field_data_type(field)\n verbose = field.verbose_name\n fields.append(\n {\n \"name\": field.name,\n \"data_type\": data_type,\n \"verbose\": verbose or \"\",\n \"help_text\": field.help_text,\n }\n )\n\n # Gather many-to-many fields.\n for field in opts.many_to_many:\n data_type = field.remote_field.model.__name__\n app_label = field.remote_field.model._meta.app_label\n verbose = _(\"related `%(app_label)s.%(object_name)s` objects\") % {\n \"app_label\": app_label,\n \"object_name\": data_type,\n }\n fields.append(\n {\n \"name\": \"%s.all\" % field.name,\n \"data_type\": \"List\",\n \"verbose\": utils.parse_rst(\n _(\"all %s\") % verbose, \"model\", _(\"model:\") + opts.model_name\n ),\n }\n )\n fields.append(\n {\n \"name\": \"%s.count\" % field.name,\n \"data_type\": \"Integer\",\n \"verbose\": utils.parse_rst(\n _(\"number of %s\") % verbose,\n \"model\",\n _(\"model:\") + opts.model_name,\n ),\n }\n )\n\n methods = []\n # Gather model methods.\n for func_name, func in model.__dict__.items():\n if inspect.isfunction(func) or isinstance(\n func, (cached_property, property)\n ):\n try:\n for exclude in MODEL_METHODS_EXCLUDE:\n if func_name.startswith(exclude):\n raise StopIteration\n except StopIteration:\n continue\n verbose = func.__doc__\n verbose = verbose and (\n utils.parse_rst(\n cleandoc(verbose), \"model\", _(\"model:\") + opts.model_name\n )\n )\n # Show properties, cached_properties, and methods without\n # arguments as fields. Otherwise, show as a 'method with\n # arguments'.\n if isinstance(func, (cached_property, property)):\n fields.append(\n {\n \"name\": func_name,\n \"data_type\": get_return_data_type(func_name),\n \"verbose\": verbose or \"\",\n }\n )\n elif (\n method_has_no_args(func)\n and not func_accepts_kwargs(func)\n and not func_accepts_var_args(func)\n ):\n fields.append(\n {\n \"name\": func_name,\n \"data_type\": get_return_data_type(func_name),\n \"verbose\": verbose or \"\",\n }\n )\n else:\n arguments = get_func_full_args(func)\n # Join arguments with ', ' and in case of default value,\n # join it with '='. Use repr() so that strings will be\n # correctly displayed.\n print_arguments = \", \".join(\n [\n \"=\".join([arg_el[0], *map(repr, arg_el[1:])])\n for arg_el in arguments\n ]\n )\n methods.append(\n {\n \"name\": func_name,\n \"arguments\": print_arguments,\n \"verbose\": verbose or \"\",\n }\n )\n\n # Gather related objects\n for rel in opts.related_objects:\n verbose = _(\"related `%(app_label)s.%(object_name)s` objects\") % {\n \"app_label\": rel.related_model._meta.app_label,\n \"object_name\": rel.related_model._meta.object_name,\n }\n accessor = rel.accessor_name\n fields.append(\n {\n \"name\": \"%s.all\" % accessor,\n \"data_type\": \"List\",\n \"verbose\": utils.parse_rst(\n _(\"all %s\") % verbose, \"model\", _(\"model:\") + opts.model_name\n ),\n }\n )\n fields.append(\n {\n \"name\": \"%s.count\" % accessor,\n \"data_type\": \"Integer\",\n \"verbose\": utils.parse_rst(\n _(\"number of %s\") % verbose,\n \"model\",\n _(\"model:\") + opts.model_name,\n ),\n }\n )\n return super().get_context_data(\n **{\n **kwargs,\n \"name\": opts.label,\n \"summary\": title,\n \"description\": body,\n \"fields\": fields,\n \"methods\": methods,\n }\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def make_conditional(\n self,\n request_or_environ: WSGIEnvironment | Request,\n accept_ranges: bool | str = False,\n complete_length: int | None = None,\n ) -> Response:\n \"\"\"Make the response conditional to the request. This method works\n best if an etag was defined for the response already. The `add_etag`\n method can be used to do that. If called without etag just the date\n header is set.\n\n This does nothing if the request method in the request or environ is\n anything but GET or HEAD.\n\n For optimal performance when handling range requests, it's recommended\n that your response data object implements `seekable`, `seek` and `tell`\n methods as described by :py:class:`io.IOBase`. Objects returned by\n :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.\n\n It does not remove the body of the response because that's something\n the :meth:`__call__` function does for us automatically.\n\n Returns self so that you can do ``return resp.make_conditional(req)``\n but modifies the object in-place.\n\n :param request_or_environ: a request object or WSGI environment to be\n used to make the response conditional\n against.\n :param accept_ranges: This parameter dictates the value of\n `Accept-Ranges` header. If ``False`` (default),\n the header is not set. If ``True``, it will be set\n to ``\"bytes\"``. If it's a string, it will use this\n value.\n :param complete_length: Will be used only in valid Range Requests.\n It will set `Content-Range` complete length\n value and compute `Content-Length` real value.\n This parameter is mandatory for successful\n Range Requests completion.\n :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`\n if `Range` header could not be parsed or satisfied.\n\n .. versionchanged:: 2.0\n Range processing is skipped if length is 0 instead of\n raising a 416 Range Not Satisfiable error.\n \"\"\"\n environ = _get_environ(request_or_environ)\n if environ[\"REQUEST_METHOD\"] in (\"GET\", \"HEAD\"):\n # if the date is not in the headers, add it now. We however\n # will not override an already existing header. Unfortunately\n # this header will be overridden by many WSGI servers including\n # wsgiref.\n if \"date\" not in self.headers:\n self.headers[\"Date\"] = http_date()\n is206 = self._process_range_request(environ, complete_length, accept_ranges)\n if not is206 and not is_resource_modified(\n environ,\n self.headers.get(\"etag\"),\n None,\n self.headers.get(\"last-modified\"),\n ):\n if parse_etags(environ.get(\"HTTP_IF_MATCH\")):\n self.status_code = 412\n else:\n self.status_code = 304\n if (\n self.automatically_set_content_length\n and \"content-length\" not in self.headers\n ):\n length = self.calculate_content_length()\n if length is not None:\n self.headers[\"Content-Length\"] = str(length)\n return self", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def autocomplete() -> None:\n \"\"\"Entry Point for completion of main and subcommand options.\"\"\"\n # Don't complete if user hasn't sourced bash_completion file.\n if \"PIP_AUTO_COMPLETE\" not in os.environ:\n return\n # Don't complete if autocompletion environment variables\n # are not present\n if not os.environ.get(\"COMP_WORDS\") or not os.environ.get(\"COMP_CWORD\"):\n return\n cwords = os.environ[\"COMP_WORDS\"].split()[1:]\n cword = int(os.environ[\"COMP_CWORD\"])\n try:\n current = cwords[cword - 1]\n except IndexError:\n current = \"\"\n\n parser = create_main_parser()\n subcommands = list(commands_dict)\n options = []\n\n # subcommand\n subcommand_name: Optional[str] = None\n for word in cwords:\n if word in subcommands:\n subcommand_name = word\n break\n # subcommand options\n if subcommand_name is not None:\n # special case: 'help' subcommand has no options\n if subcommand_name == \"help\":\n sys.exit(1)\n # special case: list locally installed dists for show and uninstall\n should_list_installed = not current.startswith(\"-\") and subcommand_name in [\n \"show\",\n \"uninstall\",\n ]\n if should_list_installed:\n env = get_default_environment()\n lc = current.lower()\n installed = [\n dist.canonical_name\n for dist in env.iter_installed_distributions(local_only=True)\n if dist.canonical_name.startswith(lc)\n and dist.canonical_name not in cwords[1:]\n ]\n # if there are no dists installed, fall back to option completion\n if installed:\n for dist in installed:\n print(dist)\n sys.exit(1)\n\n should_list_installables = (\n not current.startswith(\"-\") and subcommand_name == \"install\"\n )\n if should_list_installables:\n for path in auto_complete_paths(current, \"path\"):\n print(path)\n sys.exit(1)\n\n subcommand = create_command(subcommand_name)\n\n for opt in subcommand.parser.option_list_all:\n if opt.help != optparse.SUPPRESS_HELP:\n options += [\n (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts\n ]\n\n # filter out previously specified options from available options\n prev_opts = [x.split(\"=\")[0] for x in cwords[1 : cword - 1]]\n options = [(x, v) for (x, v) in options if x not in prev_opts]\n # filter options by current input\n options = [(k, v) for k, v in options if k.startswith(current)]\n # get completion type given cwords and available subcommand options\n completion_type = get_path_completion_type(\n cwords,\n cword,\n subcommand.parser.option_list_all,\n )\n # get completion files and directories if ``completion_type`` is\n # ``<file>``, ``<dir>`` or ``<path>``\n if completion_type:\n paths = auto_complete_paths(current, completion_type)\n options = [(path, 0) for path in paths]\n for option in options:\n opt_label = option[0]\n # append '=' to options which require args\n if option[1] and option[0][:2] == \"--\":\n opt_label += \"=\"\n print(opt_label)\n else:\n # show main parser options only when necessary\n\n opts = [i.option_list for i in parser.option_groups]\n opts.append(parser.option_list)\n flattened_opts = chain.from_iterable(opts)\n if current.startswith(\"-\"):\n for opt in flattened_opts:\n if opt.help != optparse.SUPPRESS_HELP:\n subcommands += opt._long_opts + opt._short_opts\n else:\n # get completion type given cwords and all available options\n completion_type = get_path_completion_type(cwords, cword, flattened_opts)\n if completion_type:\n subcommands = list(auto_complete_paths(current, completion_type))\n\n print(\" \".join([x for x in subcommands if x.startswith(current)]))\n sys.exit(1)", "smellKey": "S3776", "smellId": null, "repo": "codacy-open-source-projects-scans_pip", "language": "python"} {"function": "def get(self, request: Request, organization) -> Response:\n \"\"\"\n Retrieve Event Counts for an Organization\n `````````````````````````````````````````\n\n .. caution::\n This endpoint may change in the future without notice.\n\n Return a set of points representing a normalized timestamp and the\n number of events seen in the period.\n\n :pparam string organization_id_or_slug: the id or slug of the organization for\n which the stats should be\n retrieved.\n :qparam string stat: the name of the stat to query (``\"received\"``,\n ``\"rejected\"``, ``\"blacklisted\"``)\n :qparam timestamp since: a timestamp to set the start of the query\n in seconds since UNIX epoch.\n :qparam timestamp until: a timestamp to set the end of the query\n in seconds since UNIX epoch.\n :qparam string resolution: an explicit resolution to search\n for (one of ``10s``, ``1h``, and ``1d``)\n :auth: required\n \"\"\"\n group = request.GET.get(\"group\", \"organization\")\n if group == \"organization\":\n keys = [organization.id]\n elif group == \"project\":\n team_list = Team.objects.get_for_user(organization=organization, user=request.user)\n\n project_ids = request.GET.getlist(\"projectID\")\n if not project_ids:\n project_list = []\n for team in team_list:\n project_list.extend(Project.objects.get_for_user(team=team, user=request.user))\n else:\n project_list = Project.objects.filter(teams__in=team_list, id__in=project_ids)\n keys = list({p.id for p in project_list})\n else:\n raise ValueError(\"Invalid group: %s\" % group)\n\n if \"id\" in request.GET:\n id_filter_set = frozenset(map(int, request.GET.getlist(\"id\")))\n keys = [k for k in keys if k in id_filter_set]\n\n if not keys:\n return Response([])\n\n stat_model = None\n stat = request.GET.get(\"stat\", \"received\")\n query_kwargs = {}\n if stat == \"received\":\n if group == \"project\":\n stat_model = TSDBModel.project_total_received\n else:\n stat_model = TSDBModel.organization_total_received\n elif stat == \"rejected\":\n if group == \"project\":\n stat_model = TSDBModel.project_total_rejected\n else:\n stat_model = TSDBModel.organization_total_rejected\n elif stat == \"blacklisted\":\n if group == \"project\":\n stat_model = TSDBModel.project_total_blacklisted\n else:\n stat_model = TSDBModel.organization_total_blacklisted\n elif stat == \"generated\":\n if group == \"project\":\n stat_model = TSDBModel.project\n try:\n query_kwargs[\"environment_id\"] = self._get_environment_id_from_request(\n request, organization.id\n )\n except Environment.DoesNotExist:\n raise ResourceDoesNotExist\n\n if stat_model is None:\n raise ValueError(f\"Invalid group: {group}, stat: {stat}\")\n data = tsdb.get_range(\n model=stat_model,\n keys=keys,\n **self._parse_args(request, **query_kwargs),\n tenant_ids={\"organization_id\": organization.id},\n )\n\n if group == \"organization\":\n data = data[organization.id]\n\n return Response(data)", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def format_unencoded(self, tokensource, outfile):\n \"\"\"\n Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``\n tuples and write it into ``outfile``.\n\n For our implementation we put all lines in their own 'line group'.\n \"\"\"\n x = self.xoffset\n y = self.yoffset\n if not self.nowrap:\n if self.encoding:\n outfile.write('<?xml version=\"1.0\" encoding=\"%s\"?>\\n' %\n self.encoding)\n else:\n outfile.write('<?xml version=\"1.0\"?>\\n')\n outfile.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" '\n '\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'\n 'svg10.dtd\">\\n')\n outfile.write('<svg xmlns=\"http://www.w3.org/2000/svg\">\\n')\n outfile.write('<g font-family=\"%s\" font-size=\"%s\">\\n' %\n (self.fontfamily, self.fontsize))\n\n counter = self.linenostart\n counter_step = self.linenostep\n counter_style = self._get_style(Comment)\n line_x = x\n\n if self.linenos:\n if counter % counter_step == 0:\n outfile.write('<text x=\"%s\" y=\"%s\" %s text-anchor=\"end\">%s</text>' %\n (x+self.linenowidth,y,counter_style,counter))\n line_x += self.linenowidth + self.ystep\n counter += 1\n\n outfile.write('<text x=\"%s\" y=\"%s\" xml:space=\"preserve\">' % (line_x, y))\n for ttype, value in tokensource:\n style = self._get_style(ttype)\n tspan = style and '<tspan' + style + '>' or ''\n tspanend = tspan and '</tspan>' or ''\n value = escape_html(value)\n if self.spacehack:\n value = value.expandtabs().replace(' ', '&#160;')\n parts = value.split('\\n')\n for part in parts[:-1]:\n outfile.write(tspan + part + tspanend)\n y += self.ystep\n outfile.write('</text>\\n')\n if self.linenos and counter % counter_step == 0:\n outfile.write('<text x=\"%s\" y=\"%s\" text-anchor=\"end\" %s>%s</text>' %\n (x+self.linenowidth,y,counter_style,counter))\n\n counter += 1\n outfile.write('<text x=\"%s\" y=\"%s\" ' 'xml:space=\"preserve\">' % (line_x,y))\n outfile.write(tspan + parts[-1] + tspanend)\n outfile.write('</text>')\n\n if not self.nowrap:\n outfile.write('</g></svg>\\n')", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def yellowButtonPressed(self):\n\t\tself.closeEventViewDialog()\n\t\tfrom Screens.InfoBar import InfoBar\n\t\tInfoBarInstance = InfoBar.instance\n\t\tif not InfoBarInstance.LongButtonPressed:\n\t\t\tif self.type == EPG_TYPE_GRAPH or self.type == EPG_TYPE_INFOBARGRAPH:\n\t\t\t\tif config.epgselection.graph_yellow.value == \"24plus\":\n\t\t\t\t\tself.nextService()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"24minus\":\n\t\t\t\t\tself.prevService()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"timer\":\n\t\t\t\t\tself.RecordTimerQuestion(True)\n\t\t\t\tif config.epgselection.graph_yellow.value == \"imdb\":\n\t\t\t\t\tself.openIMDb()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"tmdb\":\n\t\t\t\t\tself.openTMDB()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"autotimer\":\n\t\t\t\t\tself.addAutoTimer()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"bouquetlist\":\n\t\t\t\t\tself.Bouquetlist()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"epgsearch\" or config.epgselection.graph_yellow.value is None:\n\t\t\t\t\tself.openEPGSearch()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"showmovies\":\n\t\t\t\t\tself.showMovieSelection()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"record\":\n\t\t\t\t\tself.RecordTimerQuestion()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"gotodatetime\":\n\t\t\t\t\tself.enterDateTime()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"nextpage\" and self.type == EPG_TYPE_GRAPH:\n\t\t\t\t\tself.nextPage()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"prevpage\" and self.type == EPG_TYPE_GRAPH:\n\t\t\t\t\tself.prevPage()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"nextbouquet\" and self.type == EPG_TYPE_GRAPH:\n\t\t\t\t\tself.nextBouquet()\n\t\t\t\tif config.epgselection.graph_yellow.value == \"prevbouquet\" and self.type == EPG_TYPE_GRAPH:\n\t\t\t\t\tself.prevBouquet()\n\t\t\telif self.type == EPG_TYPE_VERTICAL:\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"24plus\":\n\t\t\t\t\tself.setPlus24h()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"24minus\":\n\t\t\t\t\tself.setMinus24h()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"timer\":\n\t\t\t\t\tself.RecordTimerQuestion(True)\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"imdb\" or config.epgselection.vertical_yellow.value is None:\n\t\t\t\t\tself.openIMDb()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"tmdb\":\n\t\t\t\t\tself.openTMDB()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"autotimer\":\n\t\t\t\t\tself.addAutoTimer()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"bouquetlist\":\n\t\t\t\t\tself.Bouquetlist()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"epgsearch\":\n\t\t\t\t\tself.openEPGSearch()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"showmovies\":\n\t\t\t\t\tself.showMovieSelection()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"record\":\n\t\t\t\t\tself.RecordTimerQuestion()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"gotoprimetime\":\n\t\t\t\t\tself.gotoPrimetime()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"setbasetime\":\n\t\t\t\t\tself.setBasetime()\n\t\t\t\tif config.epgselection.vertical_yellow.value == \"gotodatetime\":\n\t\t\t\t\tself.enterDateTime()\n\t\t\telse:\n\t\t\t\tself.openEPGSearch()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def are_args_compatible(\n left: FormalArgument,\n right: FormalArgument,\n is_compat: Callable[[Type, Type], bool],\n *,\n ignore_pos_arg_names: bool,\n allow_partial_overlap: bool,\n allow_imprecise_kinds: bool = False,\n) -> bool:\n if left.required and right.required:\n # If both arguments are required allow_partial_overlap has no effect.\n allow_partial_overlap = False\n\n def is_different(\n left_item: object | None, right_item: object | None, allow_overlap: bool\n ) -> bool:\n \"\"\"Checks if the left and right items are different.\n\n If the right item is unspecified (e.g. if the right callable doesn't care\n about what name or position its arg has), we default to returning False.\n\n If we're allowing partial overlap, we also default to returning False\n if the left callable also doesn't care.\"\"\"\n if right_item is None:\n return False\n if allow_overlap and left_item is None:\n return False\n return left_item != right_item\n\n # If right has a specific name it wants this argument to be, left must\n # have the same.\n if is_different(left.name, right.name, allow_partial_overlap):\n # But pay attention to whether we're ignoring positional arg names\n if not ignore_pos_arg_names or right.pos is None:\n return False\n\n # If right is at a specific position, left must have the same.\n # TODO: partial overlap logic is flawed for positions.\n # We disable it to avoid false positives at a cost of few false negatives.\n if is_different(left.pos, right.pos, allow_overlap=False) and not allow_imprecise_kinds:\n return False\n\n # If right's argument is optional, left's must also be\n # (unless we're relaxing the checks to allow potential\n # rather than definite compatibility).\n if not allow_partial_overlap and not right.required and left.required:\n return False\n\n # If we're allowing partial overlaps and neither arg is required,\n # the types don't actually need to be the same\n if allow_partial_overlap and not left.required and not right.required:\n return True\n\n # Left must have a more general type\n return is_compat(right.typ, left.typ)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def gen_test_rego(name):\n with open(f\"{name}_test.gen.rego\", \"wt\") as f:\n f.write(f\"package {name}\\nimport rego.v1\\n\\n\")\n for scope, context, ownership, privilege, membership, same_org, has_proj in product(\n SCOPES, CONTEXTS, OWNERSHIPS, GROUPS, ORG_ROLES, SAME_ORG, HAS_PROJ\n ):\n for resource in RESOURCES(scope):\n if not is_valid(\n scope, context, ownership, privilege, membership, resource, same_org, has_proj\n ):\n continue\n\n data = get_data(\n scope, context, ownership, privilege, membership, resource, same_org\n )\n test_name = get_name(\n scope, context, ownership, privilege, membership, resource, same_org, has_proj\n )\n result = eval_rule(scope, context, ownership, privilege, membership, data)\n f.write(\n \"{test_name} if {{\\n {allow} with input as {data}\\n}}\\n\\n\".format(\n test_name=test_name,\n allow=\"allow\" if result else \"not allow\",\n data=json.dumps(data),\n )\n )\n\n # Write the script which is used to generate the file\n with open(sys.argv[0]) as this_file:\n f.write(f\"\\n\\n# {os.path.split(sys.argv[0])[1]}\\n\")\n for line in this_file:\n if line.strip():\n f.write(f\"# {line}\")\n else:\n f.write(f\"#\\n\")\n\n # Write rules which are used to generate the file\n with open(os.path.join(sys.argv[1], f\"{name}.csv\")) as rego_file:\n f.write(f\"\\n\\n# {name}.csv\\n\")\n for line in rego_file:\n if line.strip():\n f.write(f\"# {line}\")\n else:\n f.write(f\"#\\n\")", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "def infer_function_type_arguments(\n self,\n callee_type: CallableType,\n args: list[Expression],\n arg_kinds: list[ArgKind],\n arg_names: Sequence[str | None] | None,\n formal_to_actual: list[list[int]],\n need_refresh: bool,\n context: Context,\n ) -> CallableType:\n \"\"\"Infer the type arguments for a generic callee type.\n\n Infer based on the types of arguments.\n\n Return a derived callable type that has the arguments applied.\n \"\"\"\n if self.chk.in_checked_function():\n # Disable type errors during type inference. There may be errors\n # due to partial available context information at this time, but\n # these errors can be safely ignored as the arguments will be\n # inferred again later.\n with self.msg.filter_errors():\n arg_types = self.infer_arg_types_in_context(\n callee_type, args, arg_kinds, formal_to_actual\n )\n\n arg_pass_nums = self.get_arg_infer_passes(\n callee_type, args, arg_types, formal_to_actual, len(args)\n )\n\n pass1_args: list[Type | None] = []\n for i, arg in enumerate(arg_types):\n if arg_pass_nums[i] > 1:\n pass1_args.append(None)\n else:\n pass1_args.append(arg)\n\n inferred_args, _ = infer_function_type_arguments(\n callee_type,\n pass1_args,\n arg_kinds,\n arg_names,\n formal_to_actual,\n context=self.argument_infer_context(),\n strict=self.chk.in_checked_function(),\n )\n\n if 2 in arg_pass_nums:\n # Second pass of type inference.\n (callee_type, inferred_args) = self.infer_function_type_arguments_pass2(\n callee_type,\n args,\n arg_kinds,\n arg_names,\n formal_to_actual,\n inferred_args,\n need_refresh,\n context,\n )\n\n if (\n callee_type.special_sig == \"dict\"\n and len(inferred_args) == 2\n and (ARG_NAMED in arg_kinds or ARG_STAR2 in arg_kinds)\n ):\n # HACK: Infer str key type for dict(...) with keyword args. The type system\n # can't represent this so we special case it, as this is a pretty common\n # thing. This doesn't quite work with all possible subclasses of dict\n # if they shuffle type variables around, as we assume that there is a 1-1\n # correspondence with dict type variables. This is a marginal issue and\n # a little tricky to fix so it's left unfixed for now.\n first_arg = get_proper_type(inferred_args[0])\n if isinstance(first_arg, (NoneType, UninhabitedType)):\n inferred_args[0] = self.named_type(\"builtins.str\")\n elif not first_arg or not is_subtype(self.named_type(\"builtins.str\"), first_arg):\n self.chk.fail(message_registry.KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE, context)\n\n if not self.chk.options.old_type_inference and any(\n a is None\n or isinstance(get_proper_type(a), UninhabitedType)\n or set(get_type_vars(a)) & set(callee_type.variables)\n for a in inferred_args\n ):\n if need_refresh:\n # Technically we need to refresh formal_to_actual after *each* inference pass,\n # since each pass can expand ParamSpec or TypeVarTuple. Although such situations\n # are very rare, not doing this can cause crashes.\n formal_to_actual = map_actuals_to_formals(\n arg_kinds,\n arg_names,\n callee_type.arg_kinds,\n callee_type.arg_names,\n lambda a: self.accept(args[a]),\n )\n # If the regular two-phase inference didn't work, try inferring type\n # variables while allowing for polymorphic solutions, i.e. for solutions\n # potentially involving free variables.\n # TODO: support the similar inference for return type context.\n poly_inferred_args, free_vars = infer_function_type_arguments(\n callee_type,\n arg_types,\n arg_kinds,\n arg_names,\n formal_to_actual,\n context=self.argument_infer_context(),\n strict=self.chk.in_checked_function(),\n allow_polymorphic=True,\n )\n poly_callee_type = self.apply_generic_arguments(\n callee_type, poly_inferred_args, context\n )\n # Try applying inferred polymorphic type if possible, e.g. Callable[[T], T] can\n # be interpreted as def [T] (T) -> T, but dict[T, T] cannot be expressed.\n applied = applytype.apply_poly(poly_callee_type, free_vars)\n if applied is not None and all(\n a is not None and not isinstance(get_proper_type(a), UninhabitedType)\n for a in poly_inferred_args\n ):\n freeze_all_type_vars(applied)\n return applied\n # If it didn't work, erase free variables as uninhabited, to avoid confusing errors.\n unknown = UninhabitedType()\n unknown.ambiguous = True\n inferred_args = [\n (\n expand_type(\n a, {v.id: unknown for v in list(callee_type.variables) + free_vars}\n )\n if a is not None\n else None\n )\n for a in poly_inferred_args\n ]\n else:\n # In dynamically typed functions use implicit 'Any' types for\n # type variables.\n inferred_args = [AnyType(TypeOfAny.unannotated)] * len(callee_type.variables)\n return self.apply_inferred_arguments(callee_type, inferred_args, context)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def run(self):\n self.setup_microservice_topic()\n while True:\n if self.cancel_thread:\n break\n try:\n # OpenC3.in_span(\"read_topics\") do\n for topic, msg_id, msg_hash, redis in Topic.read_topics(self.topics):\n if self.cancel_thread:\n break\n\n if topic == self.microservice_topic:\n self.microservice_cmd(topic, msg_id, msg_hash, redis)\n elif \"__DECOMINTERFACE__\" in topic:\n if msg_hash.get(b\"inject_tlm\"):\n handle_inject_tlm(msg_hash[b\"inject_tlm\"], self.scope)\n continue\n if msg_hash.get(b\"build_cmd\"):\n handle_build_cmd(msg_hash[b\"build_cmd\"], msg_id, self.scope)\n continue\n else:\n self.decom_packet(topic, msg_id, msg_hash, redis)\n self.metric.set(name=\"decom_total\", value=self.count, type=\"counter\")\n self.count += 1\n LimitsEventTopic.sync_system_thread_body(scope=self.scope)\n except Exception as error:\n self.error_count += 1\n self.metric.set(name=\"decom_error_total\", value=self.error_count, type=\"counter\")\n self.error = error\n self.logger.error(f\"Decom error {repr(error)}\")", "smellKey": "S3776", "smellId": null, "repo": "OpenC3_cosmos", "language": "python"} {"function": "def record(self, events):\n if not events:\n return []\n\n scope: str | None = None\n key: str | None = None\n\n items = []\n for event in events:\n if not event.group_id:\n continue\n for label, features in self.extract(event).items():\n if scope is None:\n scope = self.__get_scope(event.project)\n else:\n assert (\n self.__get_scope(event.project) == scope\n ), \"all events must be associated with the same project\"\n\n if key is None:\n key = self.__get_key(event.group)\n else:\n assert (\n self.__get_key(event.group) == key\n ), \"all events must be associated with the same group\"\n\n try:\n features = [self.encoder.dumps(feature) for feature in features]\n except Exception as error:\n log = (\n logger.debug\n if isinstance(error, self.expected_encoding_errors)\n else logger.warning\n )\n log(\n \"Could not encode features from %r for %r due to error: %r\",\n event,\n label,\n error,\n exc_info=True,\n )\n else:\n if features:\n items.append((self.aliases[label], features))\n\n return self.index.record(scope, key, items, timestamp=int(event.datetime.timestamp()))", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def main(\n *,\n args: list[str] | None = None,\n stdout: TextIO = sys.stdout,\n stderr: TextIO = sys.stderr,\n clean_exit: bool = False,\n) -> None:\n \"\"\"Main entry point to the type checker.\n\n Args:\n args: Custom command-line arguments. If not given, sys.argv[1:] will\n be used.\n clean_exit: Don't hard kill the process on exit. This allows catching\n SystemExit.\n \"\"\"\n util.check_python_version(\"mypy\")\n t0 = time.time()\n # To log stat() calls: os.stat = stat_proxy\n sys.setrecursionlimit(2**14)\n if args is None:\n args = sys.argv[1:]\n\n fscache = FileSystemCache()\n sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache)\n if clean_exit:\n options.fast_exit = False\n\n formatter = util.FancyFormatter(\n stdout, stderr, options.hide_error_codes, hide_success=bool(options.output)\n )\n\n if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr):\n # Since --install-types performs user input, we want regular stdout and stderr.\n fail(\"error: --install-types not supported in this mode of running mypy\", stderr, options)\n\n if options.non_interactive and not options.install_types:\n fail(\"error: --non-interactive is only supported with --install-types\", stderr, options)\n\n if options.install_types and not options.incremental:\n fail(\n \"error: --install-types not supported with incremental mode disabled\", stderr, options\n )\n\n if options.install_types and options.python_executable is None:\n fail(\n \"error: --install-types not supported without python executable or site packages\",\n stderr,\n options,\n )\n\n if options.install_types and not sources:\n install_types(formatter, options, non_interactive=options.non_interactive)\n return\n\n res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n\n if options.non_interactive:\n missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True)\n if missing_pkgs:\n # Install missing type packages and rerun build.\n install_types(formatter, options, after_run=True, non_interactive=True)\n fscache.flush()\n print()\n res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n show_messages(messages, stderr, formatter, options)\n\n if MEM_PROFILE:\n from mypy.memprofile import print_memory_profile\n\n print_memory_profile()\n\n code = 0\n n_errors, n_notes, n_files = util.count_stats(messages)\n if messages and n_notes < len(messages):\n code = 2 if blockers else 1\n if options.error_summary:\n if n_errors:\n summary = formatter.format_error(\n n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output\n )\n stdout.write(summary + \"\\n\")\n # Only notes should also output success\n elif not messages or n_notes == len(messages):\n stdout.write(formatter.format_success(len(sources), options.color_output) + \"\\n\")\n stdout.flush()\n\n if options.install_types and not options.non_interactive:\n result = install_types(formatter, options, after_run=True, non_interactive=False)\n if result:\n print()\n print(\"note: Run mypy again for up-to-date results with installed types\")\n code = 2\n\n if options.fast_exit:\n # Exit without freeing objects -- it's faster.\n #\n # NOTE: We don't flush all open files on exit (or run other destructors)!\n util.hard_exit(code)\n elif code:\n sys.exit(code)\n\n # HACK: keep res alive so that mypyc won't free it before the hard_exit\n list([res]) # noqa: C410", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def createSetup(self):\n\t\tlevel = config.usage.setup_level.index\n\n\t\tself.list = [\n\t\t\tgetConfigListEntry(_(\"Video output\"), config.av.videoport, _(\"Configures which video output connector will be used.\"))\n\t\t]\n\t\tif config.av.videoport.value in (\"HDMI\", \"YPbPr\", \"Scart-YPbPr\") and not getAutoresPlugin_enabled():\n\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution\"), config.av.autores, _(\"If enabled the output resolution of the box will try to match the resolution of the video contents resolution\")))\n\t\t\tif config.av.autores.value in (\"all\", \"hd\"):\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Delay time\"), config.av.autores_delay, _(\"Set the time before checking video source for resolution information.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution label\"), config.av.autores_label_timeout, _(\"Allows you to adjust the amount of time the resolution information display on screen.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Force de-interlace\"), config.av.autores_deinterlace, _(\"If enabled the video will always be de-interlaced.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Always use smart1080p mode\"), config.av.smart1080p, _(\"This option allows you to always use e.g. 1080p50 for TV/.ts, and 1080p24/p50/p60 for videos\")))\n\t\t\t\tif config.av.autores.value == \"hd\":\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show SD as\"), config.av.autores_sd, _(\"This option allows you to choose how to display standard definition video on your TV.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 480/576p 24fps as\"), config.av.autores_480p24, _(\"This option allows you to choose how to display SD progressive 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 720p 24fps as\"), config.av.autores_720p24, _(\"This option allows you to choose how to display 720p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 24fps as\"), config.av.autores_1080p24, _(\"This option allows you to choose how to display 1080p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 25fps as\"), config.av.autores_1080p25, _(\"This option allows you to choose how to display 1080p 25Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 1080p 30fps as\"), config.av.autores_1080p30, _(\"This option allows you to choose how to display 1080p 30Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\tif \"2160p24\" in avSwitch.readAvailableModes():\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 24fps as\"), config.av.autores_2160p24, _(\"This option allows you to choose how to display 2160p 24Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 25fps as\"), config.av.autores_2160p25, _(\"This option allows you to choose how to display 2160p 25Hz on your TV. (as not all TV's support these resolutions)\")))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 2160p 30fps as\"), config.av.autores_2160p30, _(\"This option allows you to choose how to display 2160p 30Hz on your TV. (as not all TV's support these resolutions)\")))\n\n\t\t\telif config.av.autores.value == \"simple\":\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Delay time\"), config.av.autores_delay, _(\"Set the time before checking video source for resolution information.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution label\"), config.av.autores_label_timeout, _(\"Allows you to adjust the amount of time the resolution information display on screen.\")))\n\t\t\t\tself.prev_sd = self.prev_hd = self.prev_fhd = self.prev_uhd = \"\"\n\t\t\t\tservice = self.session.nav.getCurrentService()\n\t\t\t\tinfo = service and service.info()\n\t\t\t\tif info:\n\t\t\t\t\tvideo_height = int(info.getInfo(iServiceInformation.sVideoHeight))\n\t\t\t\t\tif video_height <= 576:\n\t\t\t\t\t\tself.prev_sd = \"* \"\n\t\t\t\t\telif video_height <= 720:\n\t\t\t\t\t\tself.prev_hd = \"* \"\n\t\t\t\t\telif video_height <= 1080:\n\t\t\t\t\t\tself.prev_fhd = \"* \"\n\t\t\t\t\telif video_height <= 2160:\n\t\t\t\t\t\tself.prev_uhd = \"* \"\n\t\t\t\t\telse:\n\t\t\t\t\t\tconfig.av.autores_preview.value = False\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Enable preview\"), config.av.autores_preview, _(\"Show preview of current mode (*).\"), \"check\"))\n\t\t\t\telse:\n\t\t\t\t\tconfig.av.autores_preview.value = False\n\t\t\t\tself.getVerify_videomode(config.av.autores_mode_sd, config.av.autores_rate_sd)\n\t\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode for SD\"), _(\"%sMode for SD (up to 576p)\") % self.prev_sd), config.av.autores_mode_sd[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\"), \"check_sd\"))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"%sRefresh rate for SD\") % self.prev_sd, config.av.autores_rate_sd[config.av.autores_mode_sd[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\"), \"check_sd\"))\n\t\t\t\tmodelist = avSwitch.getModeList(config.av.videoport.value)\n\t\t\t\tif \"720p\" in avSwitch.readAvailableModes():\n\t\t\t\t\tself.getVerify_videomode(config.av.autores_mode_hd, config.av.autores_rate_hd)\n\t\t\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode for HD\"), _(\"%sMode for HD (up to 720p)\") % self.prev_hd), config.av.autores_mode_hd[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\"), \"check_hd\"))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"%sRefresh rate for HD\") % self.prev_hd, config.av.autores_rate_hd[config.av.autores_mode_hd[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\"), \"check_hd\"))\n\t\t\t\tif \"1080i\" in avSwitch.readAvailableModes() or \"1080p\" in avSwitch.readAvailableModes():\n\t\t\t\t\tself.getVerify_videomode(config.av.autores_mode_fhd, config.av.autores_rate_fhd)\n\t\t\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode for FHD\"), _(\"%sMode for FHD (up to 1080p)\") % self.prev_fhd), config.av.autores_mode_fhd[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\"), \"check_fhd\"))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"%sRefresh rate for FHD\") % self.prev_fhd, config.av.autores_rate_fhd[config.av.autores_mode_fhd[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\"), \"check_fhd\"))\n\t\t\t\t\tif config.av.autores_mode_fhd[config.av.videoport.value].value == '1080p' and ('1080p' in avSwitch.readAvailableModes() or \"1080p50\" in avSwitch.readAvailableModes()):\n\t\t\t\t\t\tself.list.append(getConfigListEntry(_(\"%sShow 1080i as 1080p\") % self.prev_fhd, config.av.autores_1080i_deinterlace, _(\"Use Deinterlacing for 1080i Videosignal?\"), \"check_fhd\"))\n\t\t\t\t\telif \"1080p\" not in avSwitch.readAvailableModes() and \"1080p50\" not in avSwitch.readAvailableModes():\n\t\t\t\t\t\tconfig.av.autores_1080i_deinterlace.value = False\n\t\t\t\tif \"2160p\" in avSwitch.readAvailableModes() or \"2160p30\" in avSwitch.readAvailableModes():\n\t\t\t\t\tself.getVerify_videomode(config.av.autores_mode_uhd, config.av.autores_rate_uhd)\n\t\t\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode for UHD\"), _(\"%sMode for UHD (up to 2160p)\") % self.prev_uhd), config.av.autores_mode_uhd[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\"), \"check_uhd\"))\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"%sRefresh rate for UHD\") % self.prev_uhd, config.av.autores_rate_uhd[config.av.autores_mode_uhd[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\"), \"check_uhd\"))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 24p up to 720p / higher than 720p as\"), config.av.autores_24p, _(\"Show 24p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 25p up to 720p / higher than 720p as\"), config.av.autores_25p, _(\"Show 25p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 30p up to 720p / higher than 720p as\"), config.av.autores_30p, _(\"Show 30p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\telif config.av.autores.value == \"native\":\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Delay time\"), config.av.autores_delay, _(\"Set the time before checking video source for resolution information.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Automatic resolution label\"), config.av.autores_label_timeout, _(\"Allows you to adjust the amount of time the resolution information display on screen.\")))\n\t\t\t\tself.getVerify_videomode(config.av.autores_mode_sd, config.av.autores_rate_sd)\n\t\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Lowest Video output mode\"), _(\"Lowest Mode\")), config.av.autores_mode_sd[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Refresh rate for 'Lowest Mode'\"), config.av.autores_rate_sd[config.av.autores_mode_sd[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 24p up to 720p / higher than 720p as\"), config.av.autores_24p, _(\"Show 24p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 25p up to 720p / higher than 720p as\"), config.av.autores_25p, _(\"Show 25p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show 30p up to 720p / higher than 720p as\"), config.av.autores_30p, _(\"Show 30p up to resolution 720p or higher than 720p as a different Framerate.\")))\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Show unknown video format as\"), config.av.autores_unknownres, _(\"Show unknown Videoresolution as next higher or as highest screen resolution.\")))\n\n\t\t# if we have modes for this port:\n\t\tif (config.av.videoport.value in config.av.videomode and config.av.autores.value == \"disabled\") or config.av.videoport.value == \"Scart\":\n\t\t\t# add mode- and rate-selection:\n\t\t\tself.list.append(getConfigListEntry(pgettext(_(\"Video output mode\"), _(\"Mode\")), config.av.videomode[config.av.videoport.value], _(\"This option configures the video output mode (or resolution).\")))\n\t\t\tif config.av.videomode[config.av.videoport.value].value == \"PC\":\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Resolution\"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _(\"This option configures the screen resolution in PC output mode.\")))\n\t\t\telif config.av.videoport.value != \"Scart\":\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Refresh rate\"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _(\"Configure the refresh rate of the screen.\")))\n\n\t\tport = config.av.videoport.value\n\t\tmode = config.av.videomode[port].value if port in config.av.videomode else None\n\n\t\t# some modes (720p, 1080i) are always widescreen. Don't let the user select something here, \"auto\" is not what he wants.\n\t\tforce_wide = avSwitch.isWidescreenMode(port, mode)\n\n\t\tif not force_wide:\n\t\t\tself.list.append(getConfigListEntry(_(\"Aspect ratio\"), config.av.aspect, _(\"Configure the aspect ratio of the screen.\")))\n\n\t\tif force_wide or config.av.aspect.value in (\"16:9\", \"16:10\"):\n\t\t\tself.list.extend((\n\t\t\t\tgetConfigListEntry(_(\"Display 4:3 content as\"), config.av.policy_43, _(\"When the content has an aspect ratio of 4:3, choose whether to scale/stretch the picture.\")),\n\t\t\t\tgetConfigListEntry(_(\"Display >16:9 content as\"), config.av.policy_169, _(\"When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture.\"))\n\t\t\t))\n\t\telif config.av.aspect.value == \"4:3\":\n\t\t\tself.list.append(getConfigListEntry(_(\"Display 16:9 content as\"), config.av.policy_169, _(\"When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture.\")))\n\n\t\tif config.av.videoport.value == \"HDMI\":\n\t\t\tif not BoxInfo.getItem(\"AmlogicFamily\"):\n\t\t\t\tself.list.append(getConfigListEntry(_(\"Aspect switch\"), config.av.aspectswitch.enabled, _(\"This option allows you to set offset values for different Letterbox resolutions.\")))\n\t\t\t\tif config.av.aspectswitch.enabled.value:\n\t\t\t\t\tfor aspect in range(5):\n\t\t\t\t\t\tself.list.append(getConfigListEntry(f\" -> {avSwitch.ASPECT_SWITCH_MSG[aspect]}\", config.av.aspectswitch.offsets[str(aspect)]))\n\n\t\t\tself.list.append(getConfigListEntry(_(\"Allow unsupported modes\"), config.av.edid_override, _(\"This option allows you to use all HDMI Modes\")))\n\n\t\tif config.av.videoport.value == \"Scart\":\n\t\t\tself.list.append(getConfigListEntry(_(\"Color format\"), config.av.colorformat, _(\"Configure which color format should be used on the SCART output.\")))\n\t\t\tif level >= 1:\n\t\t\t\tself.list.append(getConfigListEntry(_(\"WSS on 4:3\"), config.av.wss, _(\"When enabled, content with an aspect ratio of 4:3 will be stretched to fit the screen.\")))\n\t\t\t\tif BoxInfo.getItem(\"ScartSwitch\"):\n\t\t\t\t\tself.list.append(getConfigListEntry(_(\"Auto SCART switching\"), config.av.vcrswitch, _(\"When enabled, your receiver will detect activity on the VCR SCART input.\")))\n\n\t\tif not isinstance(config.av.scaler_sharpness, ConfigNothing) and not isPluginInstalled(\"VideoEnhancement\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"Scaler sharpness\"), config.av.scaler_sharpness, _(\"This option configures the picture sharpness.\")))\n\n\t\tif BoxInfo.getItem(\"havecolorspace\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI color space\"), config.av.hdmicolorspace, _(\"This option allows you can config the Colorspace from Auto to RGB\")))\n\n\t\tif BoxInfo.getItem(\"havecolorimetry\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI Colorimetry\"), config.av.hdmicolorimetry, _(\"This option allows you can config the Colorimetry for HDR\")))\n\n\t\tif BoxInfo.getItem(\"havehdmicolordepth\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI color depth\"), config.av.hdmicolordepth, _(\"This option allows you can config the Colordepth for UHD\")))\n\n\t\tif BoxInfo.getItem(\"havehdmihdrtype\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HDMI HDR Type\"), config.av.hdmihdrtype, _(\"This option allows you can force the HDR Modes for UHD\")))\n\n\t\tif BoxInfo.getItem(\"Canedidchecking\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"Bypass HDMI EDID Check\"), config.av.bypass_edid_checking, _(\"This option allows you to bypass HDMI EDID check\")))\n\n\t\tif BoxInfo.getItem(\"haveboxmode\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"Change Boxmode to control Hardware Chip Modes*\"), config.av.boxmode, _(\"Switch Mode to enable HDR Modes or PiP Functions\")))\n\n\t\tif BoxInfo.getItem(\"HDRSupport\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HLG Support\"), config.av.hlg_support, _(\"This option allows you can force the HLG Modes for UHD\")))\n\t\t\tself.list.append(getConfigListEntry(_(\"HDR10 Support\"), config.av.hdr10_support, _(\"This option allows you can force the HDR10 Modes for UHD\")))\n\t\t\tself.list.append(getConfigListEntry(_(\"Allow 12bit\"), config.av.allow_12bit, _(\"This option allows you can enable or disable the 12 Bit Color Mode\")))\n\t\t\tself.list.append(getConfigListEntry(_(\"Allow 10bit\"), config.av.allow_10bit, _(\"This option allows you can enable or disable the 10 Bit Color Mode\")))\n\n\t\tif BoxInfo.getItem(\"havesyncmode\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"Sync mode\"), config.av.sync_mode, _(\"Setup how to control the channel changing.\")))\n\n\t\tif BoxInfo.getItem(\"haveamlhdrsupport\"):\n\t\t\tself.list.append(getConfigListEntry(_(\"HLG Support\"), config.av.amlhlg_support, _(\"This option allows you can force the HLG Modes for UHD\")))\n\t\t\tself.list.append(getConfigListEntry(_(\"HDR10 Support\"), config.av.amlhdr10_support, _(\"This option allows you can force the HDR10 Modes for UHD\")))\n\n\t\tself[\"config\"].list = self.list\n\t\tself[\"config\"].l.setList(self.list)\n\t\tif config.usage.sort_settings.value:\n\t\t\tself[\"config\"].list.sort()", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def __evEventInfoChanged(self):\n\t\t# Get Current Event Info\n\t\tservice = self.session.nav.getCurrentService()\n\t\told_begin_time = self.pts_begintime\n\t\tinfo = service and service.info()\n\t\tptr = info and info.getEvent(0)\n\t\tself.pts_begintime = ptr and ptr.getBeginTime() or 0\n\t\t# Save current TimeShift permanently now.\n\t\tif info.getInfo(iServiceInformation.sVideoPID) != -1:\n\t\t\t# Take care of Record Margin Time.\n\t\t\tif self.save_current_timeshift and self.timeshiftEnabled():\n\t\t\t\tif config.recording.margin_after.value > 0 and len(self.recording) == 0:\n\t\t\t\t\tself.SaveTimeshift(mergelater=True)\n\t\t\t\t\trecording = RecordTimerEntry(ServiceReference(self.session.nav.getCurrentlyPlayingServiceOrGroup()), time(), time() + (config.recording.margin_after.value * 60), self.pts_curevent_name, self.pts_curevent_description, self.pts_curevent_eventid, afterEvent=AFTEREVENT.AUTO, justplay=False, always_zap=False, dirname=config.usage.default_path.value)\n\t\t\t\t\trecording.dontSave = True\n\t\t\t\t\tself.session.nav.RecordTimer.record(recording)\n\t\t\t\t\tself.recording.append(recording)\n\t\t\t\telse:\n\t\t\t\t\tself.SaveTimeshift()\n\t\t\t\tif not config.timeshift.fileSplitting.value:\n\t\t\t\t\tself.stopTimeshiftcheckTimeshiftRunningCallback(True)\n\t\t\t# (Re)Start TimeShift\n\t\t\tif not self.pts_delay_timer.isActive():\n\t\t\t\tif old_begin_time != self.pts_begintime or old_begin_time == 0:\n\t\t\t\t\tif config.timeshift.startDelay.value or self.timeshiftEnabled():\n\t\t\t\t\t\tself.event_changed = True\n\t\t\t\t\tself.pts_delay_timer.start(1000, True)", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def get_settings(self, args: Namespace) -> dict:\n \"\"\"Extract debug settings.\"\"\"\n settings = {}\n if args.debug_connections:\n settings[\"debug.connections\"] = True\n if args.debug_credentials:\n settings[\"debug.credentials\"] = True\n if args.debug_presentations:\n settings[\"debug.presentations\"] = True\n if args.debug_webhooks:\n settings[\"debug.webhooks\"] = True\n if args.debug_seed:\n settings[\"debug.seed\"] = args.debug_seed\n if args.invite:\n settings[\"debug.print_invitation\"] = True\n if args.connections_invite:\n settings[\"debug.print_connections_invitation\"] = True\n if args.invite_label:\n settings[\"debug.invite_label\"] = args.invite_label\n if args.invite_multi_use:\n settings[\"debug.invite_multi_use\"] = True\n if args.invite_public:\n settings[\"debug.invite_public\"] = True\n if args.invite_metadata_json:\n settings[\"debug.invite_metadata_json\"] = args.invite_metadata_json\n if args.test_suite_endpoint:\n settings[\"debug.test_suite_endpoint\"] = args.test_suite_endpoint\n\n if args.auto_respond_credential_proposal:\n settings[\"debug.auto_respond_credential_proposal\"] = True\n if args.auto_respond_credential_offer:\n settings[\"debug.auto_respond_credential_offer\"] = True\n if args.auto_respond_credential_request:\n settings[\"debug.auto_respond_credential_request\"] = True\n if args.auto_respond_presentation_proposal:\n settings[\"debug.auto_respond_presentation_proposal\"] = True\n if args.auto_respond_presentation_request:\n settings[\"debug.auto_respond_presentation_request\"] = True\n if args.auto_store_credential:\n settings[\"debug.auto_store_credential\"] = True\n if args.auto_verify_presentation:\n settings[\"debug.auto_verify_presentation\"] = True\n if args.auto_accept_invites:\n settings[\"debug.auto_accept_invites\"] = True\n if args.auto_accept_requests:\n settings[\"debug.auto_accept_requests\"] = True\n if args.auto_respond_messages:\n settings[\"debug.auto_respond_messages\"] = True\n return settings", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "def record_event(self, *, tag, request: Request, additional=None):\n \"\"\"Records an Event record on the associated model.\"\"\"\n\n # Get-or-create a new IpAddress object\n ip_address = request.ip_address\n # Add `request.ip_address.geoip_info` data to `Event.additional`\n if ip_address.geoip_info is not None:\n additional = additional or {}\n additional[\"geoip_info\"] = ip_address.geoip_info\n\n if user_agent := request.headers.get(\"User-Agent\"):\n try:\n parsed_user_agent = linehaul_user_agent_parser.parse(user_agent)\n if (\n parsed_user_agent is not None\n and parsed_user_agent.installer is not None\n and parsed_user_agent.installer.name == \"Browser\"\n ):\n parsed_user_agent = user_agent_parser.Parse(user_agent)\n additional = additional or {}\n additional[\"user_agent_info\"] = {\n \"installer\": \"Browser\",\n \"device\": parsed_user_agent[\"device\"][\"family\"],\n \"os\": parsed_user_agent[\"os\"][\"family\"],\n \"user_agent\": parsed_user_agent[\"user_agent\"][\"family\"],\n }\n else:\n additional = additional or {}\n additional[\"user_agent_info\"] = {\n \"installer\": (\n parsed_user_agent.installer.name\n if parsed_user_agent and parsed_user_agent.installer\n else None\n ),\n \"implementation\": (\n parsed_user_agent.implementation.name\n if parsed_user_agent and parsed_user_agent.implementation\n else None\n ),\n \"system\": (\n parsed_user_agent.system.name\n if parsed_user_agent and parsed_user_agent.system\n else None\n ),\n }\n except linehaul_user_agent_parser.UnknownUserAgentError:\n pass\n\n event = self.Event(\n source=self,\n tag=tag,\n ip_address=ip_address,\n additional=additional,\n )\n\n request.db.add(event)\n\n return event", "smellKey": "S3776", "smellId": null, "repo": "shenxianpeng_warehouse", "language": "python"} {"function": "def dataset_split_decision_inferred_from_query(columns, query):\n \"\"\"\n Infers split decision based on fields we know exclusively belong to one\n dataset or the other. Biases towards Errors dataset.\n \"\"\"\n for field in ERROR_ONLY_FIELDS:\n if field in query:\n return DiscoverSavedQueryTypes.ERROR_EVENTS\n\n for field in TRANSACTION_ONLY_FIELDS:\n if field in query:\n return DiscoverSavedQueryTypes.TRANSACTION_LIKE\n\n for column in columns:\n for field in ERROR_ONLY_FIELDS:\n if field in column:\n return DiscoverSavedQueryTypes.ERROR_EVENTS\n\n for field in TRANSACTION_ONLY_FIELDS:\n if field in column:\n return DiscoverSavedQueryTypes.TRANSACTION_LIKE\n\n return None", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def alter_field(self, model, old_field, new_field, strict=False):\n \"\"\"\n Allow a field's type, uniqueness, nullability, default, column,\n constraints, etc. to be modified.\n `old_field` is required to compute the necessary changes.\n If `strict` is True, raise errors if the old column does not match\n `old_field` precisely.\n \"\"\"\n if not self._field_should_be_altered(old_field, new_field):\n return\n # Ensure this field is even column-based\n old_db_params = old_field.db_parameters(connection=self.connection)\n old_type = old_db_params[\"type\"]\n new_db_params = new_field.db_parameters(connection=self.connection)\n new_type = new_db_params[\"type\"]\n modifying_generated_field = False\n if (old_type is None and old_field.remote_field is None) or (\n new_type is None and new_field.remote_field is None\n ):\n raise ValueError(\n \"Cannot alter field %s into %s - they do not properly define \"\n \"db_type (are you using a badly-written custom field?)\"\n % (old_field, new_field),\n )\n elif (\n old_type is None\n and new_type is None\n and (\n old_field.remote_field.through\n and new_field.remote_field.through\n and old_field.remote_field.through._meta.auto_created\n and new_field.remote_field.through._meta.auto_created\n )\n ):\n return self._alter_many_to_many(model, old_field, new_field, strict)\n elif (\n old_type is None\n and new_type is None\n and (\n old_field.remote_field.through\n and new_field.remote_field.through\n and not old_field.remote_field.through._meta.auto_created\n and not new_field.remote_field.through._meta.auto_created\n )\n ):\n # Both sides have through models; this is a no-op.\n return\n elif old_type is None or new_type is None:\n raise ValueError(\n \"Cannot alter field %s into %s - they are not compatible types \"\n \"(you cannot alter to or from M2M fields, or add or remove \"\n \"through= on M2M fields)\" % (old_field, new_field)\n )\n elif old_field.generated != new_field.generated or (\n new_field.generated and old_field.db_persist != new_field.db_persist\n ):\n modifying_generated_field = True\n elif new_field.generated:\n try:\n old_field_sql = old_field.generated_sql(self.connection)\n except FieldError:\n # Field used in a generated field was renamed.\n modifying_generated_field = True\n else:\n new_field_sql = new_field.generated_sql(self.connection)\n modifying_generated_field = old_field_sql != new_field_sql\n if modifying_generated_field:\n raise ValueError(\n f\"Modifying GeneratedFields is not supported - the field {new_field} \"\n \"must be removed and re-added with the new definition.\"\n )\n\n self._alter_field(\n model,\n old_field,\n new_field,\n old_type,\n new_type,\n old_db_params,\n new_db_params,\n strict,\n )", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def getZapUpDownList(self):\n\t\tfccZapUpDownList = []\n\t\tserviceList = InfoBar.instance.servicelist.servicelist.getList()\n\t\tcurServiceRef = InfoBar.instance.servicelist.servicelist.getCurrent().toString()\n\n\t\tserviceRefList = []\n\t\tfor idx in range(len(serviceList)):\n\t\t\tsref = serviceList[idx].toString()\n\t\t\tif (sref.split(':')[1] == '0') and self.isPlayableFCC(sref): # remove marker\n\t\t\t\tserviceRefList.append(sref)\n\n\t\tif curServiceRef in serviceRefList:\n\t\t\tserviceRefListSize = len(serviceRefList)\n\t\t\tcurServiceIndex = serviceRefList.index(curServiceRef)\n\n\t\t\tfor x in range(self.maxFCC - 1):\n\t\t\t\tif x > (serviceRefListSize - 2): # if not ((x+1) <= (serviceRefListSize-1))\n\t\t\t\t\tbreak\n\n\t\t\t\tidx = (x // 2) + 1\n\t\t\t\tif x % 2:\n\t\t\t\t\tidx *= -1 # idx : [ 1, -1, 2, -2, 3, -3, 4, -4 ....]\n\t\t\t\tidx = (curServiceIndex + idx) % serviceRefListSize # calc wraparound\n\t\t\t\ttry:\n\t\t\t\t\tfccZapUpDownList.append(serviceRefList[idx])\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"[FCCCreateList] append error, idx : %d\" % idx)\n\t\t\t\t\tbreak\n\n\t\treturn fccZapUpDownList", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def process_shebang(self, data):\n m = SHEBANG_RE.match(data)\n if m:\n end = m.end()\n shebang, data_after_shebang = data[:end], data[end:]\n # Preserve any arguments after the interpreter\n if b'pythonw' in shebang.lower():\n shebang_python = SHEBANG_PYTHONW\n else:\n shebang_python = SHEBANG_PYTHON\n m = SHEBANG_DETAIL_RE.match(shebang)\n if m:\n args = b' ' + m.groups()[-1]\n else:\n args = b''\n shebang = shebang_python + args\n data = shebang + data_after_shebang\n else:\n cr = data.find(b'\\r')\n lf = data.find(b'\\n')\n if cr < 0 or cr > lf:\n term = b'\\n'\n else:\n if data[cr:cr + 2] == b'\\r\\n':\n term = b'\\r\\n'\n else:\n term = b'\\r'\n data = SHEBANG_PYTHON + term + data\n return data", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def _trim_arity(func, max_limit=3):\n \"\"\"decorator to trim function calls to match the arity of the target\"\"\"\n global _trim_arity_call_line\n\n if func in _single_arg_builtins:\n return lambda s, l, t: func(t)\n\n limit = 0\n found_arity = False\n\n # synthesize what would be returned by traceback.extract_stack at the call to\n # user's parse action 'func', so that we don't incur call penalty at parse time\n\n # fmt: off\n LINE_DIFF = 7\n # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND\n # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!\n _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])\n pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)\n\n def wrapper(*args):\n nonlocal found_arity, limit\n while 1:\n try:\n ret = func(*args[limit:])\n found_arity = True\n return ret\n except TypeError as te:\n # re-raise TypeErrors if they did not come from our arity testing\n if found_arity:\n raise\n else:\n tb = te.__traceback__\n frames = traceback.extract_tb(tb, limit=2)\n frame_summary = frames[-1]\n trim_arity_type_error = (\n [frame_summary[:2]][-1][:2] == pa_call_line_synth\n )\n del tb\n\n if trim_arity_type_error:\n if limit < max_limit:\n limit += 1\n continue\n\n raise\n # fmt: on\n\n # copy func name to wrapper for sensible debug output\n # (can't use functools.wraps, since that messes with function signature)\n func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n wrapper.__name__ = func_name\n wrapper.__doc__ = func.__doc__\n\n return wrapper", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901\n \"\"\"Parse TOML from a string.\"\"\"\n\n # The spec allows converting \"\\r\\n\" to \"\\n\", even in string\n # literals. Let's do so to simplify parsing.\n src = __s.replace(\"\\r\\n\", \"\\n\")\n pos = 0\n out = Output(NestedDict(), Flags())\n header: Key = ()\n parse_float = make_safe_parse_float(parse_float)\n\n # Parse one statement at a time\n # (typically means one line in TOML source)\n while True:\n # 1. Skip line leading whitespace\n pos = skip_chars(src, pos, TOML_WS)\n\n # 2. Parse rules. Expect one of the following:\n # - end of file\n # - end of line\n # - comment\n # - key/value pair\n # - append dict to list (and move to its namespace)\n # - create dict (and move to its namespace)\n # Skip trailing whitespace when applicable.\n try:\n char = src[pos]\n except IndexError:\n break\n if char == \"\\n\":\n pos += 1\n continue\n if char in KEY_INITIAL_CHARS:\n pos = key_value_rule(src, pos, out, header, parse_float)\n pos = skip_chars(src, pos, TOML_WS)\n elif char == \"[\":\n try:\n second_char: str | None = src[pos + 1]\n except IndexError:\n second_char = None\n out.flags.finalize_pending()\n if second_char == \"[\":\n pos, header = create_list_rule(src, pos, out)\n else:\n pos, header = create_dict_rule(src, pos, out)\n pos = skip_chars(src, pos, TOML_WS)\n elif char != \"#\":\n raise suffixed_err(src, pos, \"Invalid statement\")\n\n # 3. Skip comment\n pos = skip_comment(src, pos)\n\n # 4. Expect end of line or end of file\n try:\n char = src[pos]\n except IndexError:\n break\n if char != \"\\n\":\n raise suffixed_err(\n src, pos, \"Expected newline or end of document after a statement\"\n )\n pos += 1\n\n return out.data.dict", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def send_event(self, event: Event) -> bytes:\n if isinstance(event, Preamble) and self.state == State.PREAMBLE:\n self.state = State.PART\n return event.data\n elif isinstance(event, (Field, File)) and self.state in {\n State.PREAMBLE,\n State.PART,\n State.DATA,\n }:\n data = b\"\\r\\n--\" + self.boundary + b\"\\r\\n\"\n data += b'Content-Disposition: form-data; name=\"%s\"' % event.name.encode()\n if isinstance(event, File):\n data += b'; filename=\"%s\"' % event.filename.encode()\n data += b\"\\r\\n\"\n for name, value in t.cast(Field, event).headers:\n if name.lower() != \"content-disposition\":\n data += f\"{name}: {value}\\r\\n\".encode()\n self.state = State.DATA_START\n return data\n elif isinstance(event, Data) and self.state == State.DATA_START:\n self.state = State.DATA\n if len(event.data) > 0:\n return b\"\\r\\n\" + event.data\n else:\n return event.data\n elif isinstance(event, Data) and self.state == State.DATA:\n return event.data\n elif isinstance(event, Epilogue):\n self.state = State.COMPLETE\n return b\"\\r\\n--\" + self.boundary + b\"--\\r\\n\" + event.data\n else:\n raise ValueError(f\"Cannot generate {event} in state: {self.state}\")", "smellKey": "S3776", "smellId": null, "repo": "artofthepossible_new-reef-revelations", "language": "python"} {"function": "def aliased_query_params(\n start=None,\n end=None,\n groupby=None,\n conditions=None,\n filter_keys=None,\n aggregations=None,\n selected_columns=None,\n arrayjoin=None,\n having=None,\n dataset=None,\n orderby=None,\n condition_resolver: Callable | None = None,\n **kwargs,\n) -> dict[str, Any]:\n if dataset is None:\n raise ValueError(\"A dataset is required, and is no longer automatically detected.\")\n\n derived_columns = []\n resolve_func = resolve_column(dataset)\n if selected_columns:\n for i, col in enumerate(selected_columns):\n if isinstance(col, (list, tuple)):\n derived_columns.append(col[2])\n else:\n selected_columns[i] = resolve_func(col)\n selected_columns = [c for c in selected_columns if c]\n\n if aggregations:\n for aggregation in aggregations:\n derived_columns.append(aggregation[2])\n\n if conditions:\n if condition_resolver:\n column_resolver: Callable = functools.partial(condition_resolver, dataset=dataset)\n else:\n column_resolver = resolve_func\n resolved_conditions = resolve_conditions(conditions, column_resolver)\n else:\n resolved_conditions = conditions\n\n if orderby:\n # Don't mutate in case we have a default order passed.\n updated_order = []\n for i, order in enumerate(orderby):\n order_field = order.lstrip(\"-\")\n if order_field not in derived_columns:\n order_field = resolve_func(order_field)\n updated_order.append(\"{}{}\".format(\"-\" if order.startswith(\"-\") else \"\", order_field))\n orderby = updated_order\n\n return dict(\n start=start,\n end=end,\n groupby=groupby,\n conditions=resolved_conditions,\n aggregations=aggregations,\n selected_columns=selected_columns,\n filter_keys=filter_keys,\n arrayjoin=arrayjoin,\n having=having,\n dataset=dataset,\n orderby=orderby,\n condition_resolver=condition_resolver,\n **kwargs,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def visit_class_def(self, defn: ClassDef) -> None:\n \"\"\"Type check a class definition.\"\"\"\n typ = defn.info\n for base in typ.mro[1:]:\n if base.is_final:\n self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn)\n with self.tscope.class_scope(defn.info), self.enter_partial_types(is_class=True):\n old_binder = self.binder\n self.binder = ConditionalTypeBinder()\n with self.binder.top_frame_context():\n with self.scope.push_class(defn.info):\n self.accept(defn.defs)\n self.binder = old_binder\n if not (defn.info.typeddict_type or defn.info.tuple_type or defn.info.is_enum):\n # If it is not a normal class (not a special form) check class keywords.\n self.check_init_subclass(defn)\n if not defn.has_incompatible_baseclass:\n # Otherwise we've already found errors; more errors are not useful\n self.check_multiple_inheritance(typ)\n self.check_metaclass_compatibility(typ)\n self.check_final_deletable(typ)\n\n if defn.decorators:\n sig: Type = type_object_type(defn.info, self.named_type)\n # Decorators are applied in reverse order.\n for decorator in reversed(defn.decorators):\n if isinstance(decorator, CallExpr) and isinstance(\n decorator.analyzed, PromoteExpr\n ):\n # _promote is a special type checking related construct.\n continue\n\n dec = self.expr_checker.accept(decorator)\n temp = self.temp_node(sig, context=decorator)\n fullname = None\n if isinstance(decorator, RefExpr):\n fullname = decorator.fullname or None\n\n # TODO: Figure out how to have clearer error messages.\n # (e.g. \"class decorator must be a function that accepts a type.\"\n old_allow_abstract_call = self.allow_abstract_call\n self.allow_abstract_call = True\n sig, _ = self.expr_checker.check_call(\n dec, [temp], [nodes.ARG_POS], defn, callable_name=fullname\n )\n self.allow_abstract_call = old_allow_abstract_call\n # TODO: Apply the sig to the actual TypeInfo so we can handle decorators\n # that completely swap out the type. (e.g. Callable[[Type[A]], Type[B]])\n if typ.defn.type_vars and typ.defn.type_args is None:\n for base_inst in typ.bases:\n for base_tvar, base_decl_tvar in zip(\n base_inst.args, base_inst.type.defn.type_vars\n ):\n if (\n isinstance(base_tvar, TypeVarType)\n and base_tvar.variance != INVARIANT\n and isinstance(base_decl_tvar, TypeVarType)\n and base_decl_tvar.variance != base_tvar.variance\n ):\n self.fail(\n f'Variance of TypeVar \"{base_tvar.name}\" incompatible '\n \"with variance in parent type\",\n context=defn,\n code=codes.TYPE_VAR,\n )\n\n if typ.is_protocol and typ.defn.type_vars:\n self.check_protocol_variance(defn)\n if not defn.has_incompatible_baseclass and defn.info.is_enum:\n self.check_enum(defn)\n infer_class_variances(defn.info)", "smellKey": "S3776", "smellId": null, "repo": "THIS-IS-NOT-A-BACKUP_mypy", "language": "python"} {"function": "def _detect_changes(self, convert_apps=None, graph=None):\n \"\"\"\n Return a dict of migration plans which will achieve the\n change from from_state to to_state. The dict has app labels\n as keys and a list of migrations as values.\n\n The resulting migrations aren't specially named, but the names\n do matter for dependencies inside the set.\n\n convert_apps is the list of apps to convert to use migrations\n (i.e. to make initial migrations for, in the usual case)\n\n graph is an optional argument that, if provided, can help improve\n dependency generation and avoid potential circular dependencies.\n \"\"\"\n # The first phase is generating all the operations for each app\n # and gathering them into a big per-app list.\n # Then go through that list, order it, and split into migrations to\n # resolve dependencies caused by M2Ms and FKs.\n self.generated_operations = {}\n self.altered_indexes = {}\n self.altered_constraints = {}\n self.renamed_fields = {}\n\n # Prepare some old/new state and model lists, separating\n # proxy models and ignoring unmigrated apps.\n self.old_model_keys = set()\n self.old_proxy_keys = set()\n self.old_unmanaged_keys = set()\n self.new_model_keys = set()\n self.new_proxy_keys = set()\n self.new_unmanaged_keys = set()\n for (app_label, model_name), model_state in self.from_state.models.items():\n if not model_state.options.get(\"managed\", True):\n self.old_unmanaged_keys.add((app_label, model_name))\n elif app_label not in self.from_state.real_apps:\n if model_state.options.get(\"proxy\"):\n self.old_proxy_keys.add((app_label, model_name))\n else:\n self.old_model_keys.add((app_label, model_name))\n\n for (app_label, model_name), model_state in self.to_state.models.items():\n if not model_state.options.get(\"managed\", True):\n self.new_unmanaged_keys.add((app_label, model_name))\n elif app_label not in self.from_state.real_apps or (\n convert_apps and app_label in convert_apps\n ):\n if model_state.options.get(\"proxy\"):\n self.new_proxy_keys.add((app_label, model_name))\n else:\n self.new_model_keys.add((app_label, model_name))\n\n self.from_state.resolve_fields_and_relations()\n self.to_state.resolve_fields_and_relations()\n\n # Renames have to come first\n self.generate_renamed_models()\n\n # Prepare lists of fields and generate through model map\n self._prepare_field_lists()\n self._generate_through_model_map()\n\n # Generate non-rename model operations\n self.generate_deleted_models()\n self.generate_created_models()\n self.generate_deleted_proxies()\n self.generate_created_proxies()\n self.generate_altered_options()\n self.generate_altered_managers()\n self.generate_altered_db_table_comment()\n\n # Create the renamed fields and store them in self.renamed_fields.\n # They are used by create_altered_indexes(), generate_altered_fields(),\n # generate_removed_altered_index/unique_together(), and\n # generate_altered_index/unique_together().\n self.create_renamed_fields()\n # Create the altered indexes and store them in self.altered_indexes.\n # This avoids the same computation in generate_removed_indexes()\n # and generate_added_indexes().\n self.create_altered_indexes()\n self.create_altered_constraints()\n # Generate index removal operations before field is removed\n self.generate_removed_constraints()\n self.generate_removed_indexes()\n # Generate field renaming operations.\n self.generate_renamed_fields()\n self.generate_renamed_indexes()\n # Generate removal of foo together.\n self.generate_removed_altered_unique_together()\n # Generate field operations.\n self.generate_removed_fields()\n self.generate_added_fields()\n self.generate_altered_fields()\n self.generate_altered_order_with_respect_to()\n self.generate_altered_unique_together()\n self.generate_added_indexes()\n self.generate_added_constraints()\n self.generate_altered_db_table()\n\n self._sort_migrations()\n self._build_migration_list(graph)\n self._optimize_migrations()\n\n return self.migrations", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "def onMountpointAdded(mountpoint):\n\tglobal searchPaths\n\ttry:\n\t\tif BW or isdir(mountpoint + \"piconlcd\"):\n\t\t\tpath = join(mountpoint, \"piconlcd\", \"\")\n\t\t\tif isdir(path) and path not in searchPaths:\n\t\t\t\tfor fn in listdir(path):\n\t\t\t\t\tif fn.endswith(\".png\"):\n\t\t\t\t\t\tprint(f\"[LcdPicon] adding path: {path}\")\n\t\t\t\t\t\tsearchPaths.append(path)\n\t\t\t\t\t\treturn\n\t\tpath = join(mountpoint, \"picon\", \"\")\n\t\tif isdir(path) and path not in searchPaths:\n\t\t\tfor fn in listdir(path):\n\t\t\t\tif fn.endswith(\".png\"):\n\t\t\t\t\tprint(f\"[LcdPicon] adding path: {path}\")\n\t\t\t\t\tsearchPaths.append(path)\n\t\t\t\t\tbreak\n\texcept Exception as err:\n\t\tprint(f\"[LcdPicon] Failed to investigate {mountpoint}:{str(err)}\")", "smellKey": "S3776", "smellId": null, "repo": "jbleyel_enigma2", "language": "python"} {"function": "def rename_field(self, app_label, model_name, old_name, new_name):\n model_key = app_label, model_name\n model_state = self.models[model_key]\n # Rename the field.\n fields = model_state.fields\n try:\n found = fields.pop(old_name)\n except KeyError:\n raise FieldDoesNotExist(\n f\"{app_label}.{model_name} has no field named '{old_name}'\"\n )\n fields[new_name] = found\n for field in fields.values():\n # Fix from_fields to refer to the new field.\n from_fields = getattr(field, \"from_fields\", None)\n if from_fields:\n field.from_fields = tuple(\n [\n new_name if from_field_name == old_name else from_field_name\n for from_field_name in from_fields\n ]\n )\n # Fix unique_together to refer to the new field.\n options = model_state.options\n if \"unique_together\" in options:\n options[\"unique_together\"] = [\n [new_name if n == old_name else n for n in together]\n for together in options[\"unique_together\"]\n ]\n # Fix to_fields to refer to the new field.\n delay = True\n references = get_references(self, model_key, (old_name, found))\n for *_, field, reference in references:\n delay = False\n if reference.to:\n remote_field, to_fields = reference.to\n if getattr(remote_field, \"field_name\", None) == old_name:\n remote_field.field_name = new_name\n if to_fields:\n field.to_fields = tuple(\n [\n new_name if to_field_name == old_name else to_field_name\n for to_field_name in to_fields\n ]\n )\n if self._relations is not None:\n old_name_lower = old_name.lower()\n new_name_lower = new_name.lower()\n for to_model in self._relations.values():\n if old_name_lower in to_model[model_key]:\n field = to_model[model_key].pop(old_name_lower)\n field.name = new_name_lower\n to_model[model_key][new_name_lower] = field\n self.reload_model(*model_key, delay=delay)", "smellKey": "S3776", "smellId": null, "repo": "johnorito_djangooo", "language": "python"} {"function": "@dashboard_bp.route(\"/custom_alias\", methods=[\"GET\", \"POST\"])\n@limiter.limit(ALIAS_LIMIT, methods=[\"POST\"])\n@login_required\n@parallel_limiter.lock(name=\"alias_creation\")\ndef custom_alias():\n # check if user has not exceeded the alias quota\n if not current_user.can_create_new_alias():\n LOG.d(\"%s can't create new alias\", current_user)\n flash(\n \"You have reached free plan limit, please upgrade to create new aliases\",\n \"warning\",\n )\n return redirect(url_for(\"dashboard.index\"))\n\n user_custom_domains = [cd.domain for cd in current_user.verified_custom_domains()]\n alias_suffixes = get_alias_suffixes(current_user)\n at_least_a_premium_domain = False\n for alias_suffix in alias_suffixes:\n if not alias_suffix.is_custom and alias_suffix.is_premium:\n at_least_a_premium_domain = True\n break\n\n csrf_form = CSRFValidationForm()\n mailboxes = current_user.mailboxes()\n\n if request.method == \"POST\":\n if not csrf_form.validate():\n flash(\"Invalid request\", \"warning\")\n return redirect(request.url)\n alias_prefix = request.form.get(\"prefix\").strip().lower().replace(\" \", \"\")\n signed_alias_suffix = request.form.get(\"signed-alias-suffix\")\n mailbox_ids = request.form.getlist(\"mailboxes\")\n alias_note = request.form.get(\"note\")\n\n if not check_alias_prefix(alias_prefix):\n flash(\n \"Only lowercase letters, numbers, dashes (-), dots (.) and underscores (_) \"\n \"are currently supported for alias prefix. Cannot be more than 40 letters\",\n \"error\",\n )\n return redirect(request.url)\n\n # check if mailbox is not tempered with\n mailboxes = []\n for mailbox_id in mailbox_ids:\n mailbox = Mailbox.get(mailbox_id)\n if (\n not mailbox\n or mailbox.user_id != current_user.id\n or not mailbox.verified\n ):\n flash(\"Something went wrong, please retry\", \"warning\")\n return redirect(request.url)\n mailboxes.append(mailbox)\n\n if not mailboxes:\n flash(\"At least one mailbox must be selected\", \"error\")\n return redirect(request.url)\n\n try:\n suffix = check_suffix_signature(signed_alias_suffix)\n if not suffix:\n LOG.w(\"Alias creation time expired for %s\", current_user)\n flash(\"Alias creation time is expired, please retry\", \"warning\")\n return redirect(request.url)\n except Exception:\n LOG.w(\"Alias suffix is tampered, user %s\", current_user)\n flash(\"Unknown error, refresh the page\", \"error\")\n return redirect(request.url)\n\n if verify_prefix_suffix(current_user, alias_prefix, suffix):\n full_alias = alias_prefix + suffix\n\n if \"..\" in full_alias:\n flash(\"Your alias can't contain 2 consecutive dots (..)\", \"error\")\n return redirect(request.url)\n\n try:\n validate_email(\n full_alias, check_deliverability=False, allow_smtputf8=False\n )\n except EmailNotValidError as e:\n flash(str(e), \"error\")\n return redirect(request.url)\n\n general_error_msg = f\"{full_alias} cannot be used\"\n\n if Alias.get_by(email=full_alias):\n alias = Alias.get_by(email=full_alias)\n if alias.user_id == current_user.id:\n flash(f\"You already have this alias {full_alias}\", \"error\")\n else:\n flash(general_error_msg, \"error\")\n elif DomainDeletedAlias.get_by(email=full_alias):\n domain_deleted_alias: DomainDeletedAlias = DomainDeletedAlias.get_by(\n email=full_alias\n )\n custom_domain = domain_deleted_alias.domain\n flash(\n f\"You have deleted this alias before. You can restore it on \"\n f\"{custom_domain.domain} 'Deleted Alias' page\",\n \"error\",\n )\n\n elif DeletedAlias.get_by(email=full_alias):\n flash(general_error_msg, \"error\")\n\n else:\n try:\n alias = Alias.create(\n user_id=current_user.id,\n email=full_alias,\n note=alias_note,\n mailbox_id=mailboxes[0].id,\n )\n Session.flush()\n except IntegrityError:\n LOG.w(\"Alias %s already exists\", full_alias)\n Session.rollback()\n flash(\"Unknown error, please retry\", \"error\")\n return redirect(url_for(\"dashboard.custom_alias\"))\n\n for i in range(1, len(mailboxes)):\n AliasMailbox.create(\n alias_id=alias.id,\n mailbox_id=mailboxes[i].id,\n )\n\n Session.commit()\n flash(f\"Alias {full_alias} has been created\", \"success\")\n\n return redirect(url_for(\"dashboard.index\", highlight_alias_id=alias.id))\n # only happen if the request has been \"hacked\"\n else:\n flash(\"something went wrong\", \"warning\")\n\n return render_template(\n \"dashboard/custom_alias.html\",\n user_custom_domains=user_custom_domains,\n alias_suffixes=alias_suffixes,\n at_least_a_premium_domain=at_least_a_premium_domain,\n mailboxes=mailboxes,\n csrf_form=csrf_form,\n )", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_app", "language": "python"} {"function": "def get_overall_res_req(res_reqs):\n \"\"\"Take the overall of a list of ResourceRequirement,\n i.e., the max of coresMin, coresMax, ramMin, ramMax, tmpdirMin, tmpdirMax\n and the sum of outdirMin, outdirMax.\"\"\"\n\n all_res_req = {}\n exception_msgs = []\n for a in max_res_pars + sum_res_pars:\n all_res_req[a] = []\n for res_req in res_reqs:\n if a in res_req:\n if isinstance(res_req[a], int): # integer check\n all_res_req[a].append(res_req[a])\n else:\n msg = SourceLine(res_req, a).makeError(\n \"Non-top-level ResourceRequirement in single container cannot have expressions\")\n exception_msgs.append(msg)\n if exception_msgs:\n raise WorkflowException(\"\\n\".join(exception_msgs))\n else:\n overall_res_req = {}\n for a in all_res_req:\n if all_res_req[a]:\n if a in max_res_pars:\n overall_res_req[a] = max(all_res_req[a])\n elif a in sum_res_pars:\n overall_res_req[a] = sum(all_res_req[a])\n if overall_res_req:\n overall_res_req[\"class\"] = \"ResourceRequirement\"\n return cmap(overall_res_req)", "smellKey": "S3776", "smellId": null, "repo": "arvados_arvados", "language": "python"} {"function": "def _get_shebang(self, encoding, post_interp=b'', options=None):\n enquote = True\n if self.executable:\n executable = self.executable\n enquote = False # assume this will be taken care of\n elif not sysconfig.is_python_build():\n executable = get_executable()\n elif in_venv(): # pragma: no cover\n executable = os.path.join(\n sysconfig.get_path('scripts'),\n 'python%s' % sysconfig.get_config_var('EXE'))\n else: # pragma: no cover\n if os.name == 'nt':\n # for Python builds from source on Windows, no Python executables with\n # a version suffix are created, so we use python.exe\n executable = os.path.join(\n sysconfig.get_config_var('BINDIR'),\n 'python%s' % (sysconfig.get_config_var('EXE')))\n else:\n executable = os.path.join(\n sysconfig.get_config_var('BINDIR'),\n 'python%s%s' % (sysconfig.get_config_var('VERSION'),\n sysconfig.get_config_var('EXE')))\n if options:\n executable = self._get_alternate_executable(executable, options)\n\n if sys.platform.startswith('java'): # pragma: no cover\n executable = self._fix_jython_executable(executable)\n\n # Normalise case for Windows - COMMENTED OUT\n # executable = os.path.normcase(executable)\n # N.B. The normalising operation above has been commented out: See\n # issue #124. Although paths in Windows are generally case-insensitive,\n # they aren't always. For example, a path containing a \u1e9e (which is a\n # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to \u00df (which is a\n # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by\n # Windows as equivalent in path names.\n\n # If the user didn't specify an executable, it may be necessary to\n # cater for executable paths with spaces (not uncommon on Windows)\n if enquote:\n executable = enquote_executable(executable)\n # Issue #51: don't use fsencode, since we later try to\n # check that the shebang is decodable using utf-8.\n executable = executable.encode('utf-8')\n # in case of IronPython, play safe and enable frames support\n if (sys.platform == 'cli' and '-X:Frames' not in post_interp\n and '-X:FullFrames' not in post_interp): # pragma: no cover\n post_interp += b' -X:Frames'\n shebang = self._build_shebang(executable, post_interp)\n # Python parser starts to read a script using UTF-8 until\n # it gets a #coding:xxx cookie. The shebang has to be the\n # first line of a file, the #coding:xxx cookie cannot be\n # written before. So the shebang has to be decodable from\n # UTF-8.\n try:\n shebang.decode('utf-8')\n except UnicodeDecodeError: # pragma: no cover\n raise ValueError('The shebang (%r) is not decodable from utf-8' %\n shebang)\n # If the script is encoded to a custom encoding (use a\n # #coding:xxx cookie), the shebang has to be decodable from\n # the script encoding too.\n if encoding != 'utf-8':\n try:\n shebang.decode(encoding)\n except UnicodeDecodeError: # pragma: no cover\n raise ValueError('The shebang (%r) is not decodable '\n 'from the script encoding (%r)' %\n (shebang, encoding))\n return shebang", "smellKey": "S3776", "smellId": null, "repo": "hasannader2040_restful-opensensemap-Api", "language": "python"} {"function": "def process_events(self):\n\n LEFT_BUTTON = 1\n MIDDLE_BUTTON = 2\n RIGHT_BUTTON = 3\n WHEEL_UP = 4\n WHEEL_DOWN = 5\n\n dx, dy = pygame.mouse.get_rel()\n mousex, mousey = pygame.mouse.get_pos()\n\n zooming_one_shot = False\n\n ok = True\n\n for evt in pygame.event.get():\n if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == LEFT_BUTTON:\n hovered = self.get_hovered_node(mousex, self.h - mousey)\n if hovered:\n if self.currently_selected and self.currently_selected == hovered:\n self.select_node(None)\n else:\n logger.info(\"Node %s selected\" % hovered)\n self.select_node(hovered)\n else:\n self.is_rotating = True\n if evt.type == pygame.MOUSEBUTTONUP and evt.button == LEFT_BUTTON:\n self.is_rotating = False\n\n if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == MIDDLE_BUTTON:\n self.is_panning = True\n if evt.type == pygame.MOUSEBUTTONUP and evt.button == MIDDLE_BUTTON:\n self.is_panning = False\n\n if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == RIGHT_BUTTON:\n self.is_zooming = True\n if evt.type == pygame.MOUSEBUTTONUP and evt.button == RIGHT_BUTTON:\n self.is_zooming = False\n\n if evt.type == pygame.MOUSEBUTTONDOWN and evt.button in [WHEEL_UP, WHEEL_DOWN]:\n zooming_one_shot = True\n self.is_zooming = True\n dy = -10 if evt.button == WHEEL_UP else 10\n\n if evt.type == pygame.KEYDOWN:\n ok = (ok and self.process_keystroke(evt.key, evt.mod))\n\n self.controls_3d(dx, dy, zooming_one_shot)\n\n return ok", "smellKey": "S3776", "smellId": null, "repo": "assimp_assimp", "language": "python"} {"function": "@parametrize(\n \"frame_selection_method, method_params\",\n [\n *tuple(product([\"random_uniform\"], [{\"frame_count\"}, {\"frame_share\"}])),\n *tuple(\n product([\"random_per_job\"], [{\"frames_per_job_count\"}, {\"frames_per_job_share\"}])\n ),\n ],\n idgen=lambda **args: \"-\".join([args[\"frame_selection_method\"], *args[\"method_params\"]]),\n )\n def test_can_create_task_with_gt_job_from_video(\n self,\n request: pytest.FixtureRequest,\n frame_selection_method: str,\n method_params: Set[str],\n ):\n segment_size = 4\n total_frame_count = 15\n resulting_task_size = total_frame_count\n\n video_file = generate_video_file(total_frame_count)\n\n validation_params = {\"mode\": \"gt\", \"frame_selection_method\": frame_selection_method}\n\n if \"random\" in frame_selection_method:\n validation_params[\"random_seed\"] = 42\n\n if frame_selection_method == \"random_uniform\":\n validation_frames_count = 5\n\n for method_param in method_params:\n if method_param == \"frame_count\":\n validation_params[method_param] = validation_frames_count\n elif method_param == \"frame_share\":\n validation_params[method_param] = validation_frames_count / total_frame_count\n else:\n assert False\n elif frame_selection_method == \"random_per_job\":\n validation_per_job_count = 2\n\n for method_param in method_params:\n if method_param == \"frames_per_job_count\":\n validation_params[method_param] = validation_per_job_count\n elif method_param == \"frames_per_job_share\":\n validation_params[method_param] = validation_per_job_count / segment_size\n else:\n assert False\n\n task_params = {\n \"name\": request.node.name,\n \"labels\": [{\"name\": \"a\"}],\n \"segment_size\": segment_size,\n }\n\n data_params = {\n \"image_quality\": 70,\n \"client_files\": [video_file],\n \"validation_params\": validation_params,\n }\n\n task_id, _ = create_task(self._USERNAME, spec=task_params, data=data_params)\n\n with make_api_client(self._USERNAME) as api_client:\n (task, _) = api_client.tasks_api.retrieve(task_id)\n (task_meta, _) = api_client.tasks_api.retrieve_data_meta(task_id)\n annotation_job_metas = [\n api_client.jobs_api.retrieve_data_meta(job.id)[0]\n for job in get_paginated_collection(\n api_client.jobs_api.list_endpoint, task_id=task_id, type=\"annotation\"\n )\n ]\n gt_job_metas = [\n api_client.jobs_api.retrieve_data_meta(job.id)[0]\n for job in get_paginated_collection(\n api_client.jobs_api.list_endpoint, task_id=task_id, type=\"ground_truth\"\n )\n ]\n\n assert len(gt_job_metas) == 1\n\n if frame_selection_method == \"random_uniform\":\n assert gt_job_metas[0].size == validation_frames_count\n elif frame_selection_method == \"random_per_job\":\n assert gt_job_metas[0].size == (\n resulting_task_size // segment_size * validation_per_job_count\n + min(resulting_task_size % segment_size, validation_per_job_count)\n )\n else:\n assert False\n\n assert task.segment_size == segment_size\n assert task.size == resulting_task_size\n assert task_meta.size == resulting_task_size\n\n frame_step = parse_frame_step(gt_job_metas[0].frame_filter)\n validation_frames = [\n abs_frame_id\n for abs_frame_id in range(\n gt_job_metas[0].start_frame,\n gt_job_metas[0].stop_frame + 1,\n frame_step,\n )\n if abs_frame_id in gt_job_metas[0].included_frames\n ]\n\n if frame_selection_method == \"random_per_job\":\n # each job must have the specified number of validation frames\n for job_meta in annotation_job_metas:\n assert (\n len(\n set(\n range(job_meta.start_frame, job_meta.stop_frame + 1, frame_step)\n ).intersection(validation_frames)\n )\n == validation_per_job_count\n )\n else:\n assert len(validation_frames) == validation_frames_count", "smellKey": "S3776", "smellId": null, "repo": "cvat-ai_cvat", "language": "python"} {"function": "async def promote_wallet_public_did(\n context: Union[AdminRequestContext, InjectionContext],\n did: str,\n write_ledger: bool = False,\n profile: Optional[Profile] = None,\n connection_id: Optional[str] = None,\n routing_keys: Optional[List[str]] = None,\n mediator_endpoint: Optional[str] = None,\n) -> Tuple[DIDInfo, Optional[dict]]:\n \"\"\"Promote supplied DID to the wallet public DID.\"\"\"\n info: Optional[DIDInfo] = None\n endorser_did = None\n\n is_indy_did = bool(IndyDID.PATTERN.match(did))\n # write only Indy DID\n write_ledger = is_indy_did and write_ledger\n is_ctx_admin_request = True\n if isinstance(context, InjectionContext):\n is_ctx_admin_request = False\n if not profile:\n raise web.HTTPForbidden(\n reason=(\n \"InjectionContext is provided but no profile is provided. \"\n \"InjectionContext does not have profile attribute but \"\n \"AdminRequestContext does.\"\n )\n )\n ledger = (\n context.profile.inject_or(BaseLedger)\n if is_ctx_admin_request\n else profile.inject_or(BaseLedger)\n )\n\n if is_indy_did:\n if not ledger:\n reason = \"No ledger available\"\n if not context.settings.get_value(\"wallet.type\"):\n reason += \": missing wallet-type?\"\n raise PermissionError(reason)\n\n async with ledger:\n if not await ledger.get_key_for_did(did):\n raise LookupError(f\"DID {did} is not posted to the ledger\")\n\n is_author_profile = (\n is_author_role(context.profile)\n if is_ctx_admin_request\n else is_author_role(profile)\n )\n # check if we need to endorse\n if is_author_profile:\n # authors cannot write to the ledger\n write_ledger = False\n\n # author has not provided a connection id, so determine which to use\n if not connection_id:\n connection_id = (\n await get_endorser_connection_id(context.profile)\n if is_ctx_admin_request\n else await get_endorser_connection_id(profile)\n )\n if not connection_id:\n raise web.HTTPBadRequest(reason=\"No endorser connection found\")\n if not write_ledger:\n async with (\n context.session() if is_ctx_admin_request else profile.session()\n ) as session:\n try:\n connection_record = await ConnRecord.retrieve_by_id(\n session, connection_id\n )\n except StorageNotFoundError as err:\n raise web.HTTPNotFound(reason=err.roll_up) from err\n except BaseModelError as err:\n raise web.HTTPBadRequest(reason=err.roll_up) from err\n endorser_info = await connection_record.metadata_get(\n session, \"endorser_info\"\n )\n\n if not endorser_info:\n raise web.HTTPForbidden(\n reason=(\n \"Endorser Info is not set up in \"\n \"connection metadata for this connection record\"\n )\n )\n if \"endorser_did\" not in endorser_info.keys():\n raise web.HTTPForbidden(\n reason=(\n ' \"endorser_did\" is not set in \"endorser_info\"'\n \" in connection metadata for this connection record\"\n )\n )\n endorser_did = endorser_info[\"endorser_did\"]\n\n did_info: Optional[DIDInfo] = None\n attrib_def = None\n async with (\n context.session() if is_ctx_admin_request else profile.session()\n ) as session:\n wallet = session.inject(BaseWallet)\n did_info = await wallet.get_local_did(did)\n info = await wallet.set_public_did(did_info)\n\n if info:\n # Publish endpoint if necessary\n endpoint = did_info.metadata.get(\"endpoint\")\n\n if is_indy_did and not endpoint:\n endpoint = mediator_endpoint or context.settings.get(\"default_endpoint\")\n attrib_def = await wallet.set_did_endpoint(\n info.did,\n endpoint,\n ledger,\n write_ledger=write_ledger,\n endorser_did=endorser_did,\n routing_keys=routing_keys,\n )\n\n if info:\n # Route the public DID\n route_manager = (\n context.profile.inject(RouteManager)\n if is_ctx_admin_request\n else profile.inject(RouteManager)\n )\n (\n await route_manager.route_verkey(context.profile, info.verkey)\n if is_ctx_admin_request\n else await route_manager.route_verkey(profile, info.verkey)\n )\n\n return info, attrib_def", "smellKey": "S3776", "smellId": null, "repo": "openwallet-foundation_acapy", "language": "python"} {"function": "@instrumented_task(\n name=\"sentry.integrations.slack.tasks.search_channel_id_for_rule\",\n queue=\"integrations\",\n silo_mode=SiloMode.REGION,\n)\ndef find_channel_id_for_rule(\n project: Project,\n actions: Sequence[dict[str, Any]],\n uuid: str,\n rule_id: int | None = None,\n user_id: int | None = None,\n **kwargs: Any,\n) -> None:\n redis_rule_status = RedisRuleStatus(uuid)\n\n try:\n project = Project.objects.get(id=project.id)\n except Project.DoesNotExist:\n redis_rule_status.set_value(\"failed\")\n return\n\n organization = project.organization\n integration_id: int | None = None\n channel_name: str | None = None\n\n # TODO: make work for multiple Slack actions\n for action in actions:\n if action.get(\"workspace\") and action.get(\"channel\"):\n integration_id = action[\"workspace\"]\n # we need to strip the prefix when searching on the channel name\n channel_name = strip_channel_name(action[\"channel\"])\n break\n\n integrations = integration_service.get_integrations(\n organization_id=organization.id, providers=[\"slack\"], integration_ids=[integration_id]\n )\n if not integrations:\n redis_rule_status.set_value(\"failed\")\n return\n integration = integrations[0]\n logger.info(\n \"rule.slack.search_channel_id\",\n extra={\n \"integration_id\": integration.id,\n \"organization_id\": organization.id,\n \"rule_id\": rule_id,\n },\n )\n\n # We do not know exactly how long it will take to paginate through all of the Slack\n # endpoints but need some time limit imposed. 3 minutes should be more than enough time,\n # we can always update later\n channel_data: SlackChannelIdData | None = None\n try:\n channel_data = get_channel_id_with_timeout(\n integration,\n channel_name,\n timeout=3 * 60,\n )\n except DuplicateDisplayNameError:\n # if we find a duplicate display name and nothing else, we\n # want to set the status to failed. This just lets us skip\n # over the next block and hit the failed status at the end.\n redis_rule_status.set_value(\"failed\")\n except ApiRateLimitedError:\n redis_rule_status.set_value(\"failed\", None, SLACK_RATE_LIMITED_MESSAGE)\n return\n\n if channel_data and channel_data.channel_id:\n for action in actions:\n # need to make sure we are adding back the right prefix and also the channel_id\n action_channel = action.get(\"channel\")\n if (\n action_channel\n and channel_name\n and strip_channel_name(action_channel) == channel_name\n ):\n action[\"channel\"] = channel_data.prefix + channel_name\n action[\"channel_id\"] = channel_data.channel_id\n break\n\n kwargs[\"actions\"] = actions\n kwargs[\"project\"] = project\n\n if rule_id:\n rule = Rule.objects.get(id=rule_id)\n rule = Updater.run(rule=rule, pending_save=False, **kwargs)\n else:\n rule = Creator.run(pending_save=False, **kwargs)\n if user_id:\n RuleActivity.objects.create(\n rule=rule, user_id=user_id, type=RuleActivityType.CREATED.value\n )\n\n redis_rule_status.set_value(\"success\", rule.id)\n return\n # if we never find the channel name we failed :(\n redis_rule_status.set_value(\"failed\")", "smellKey": "S3776", "smellId": null, "repo": "RitaMelo18_sentry", "language": "python"} {"function": "def _populate_user_from_attributes(self):\n for field, attr in self.settings.USER_ATTR_MAP.items():\n if field in ['groups']:\n continue\n try:\n value = self.attrs[attr][0]\n value = value.strip()\n if field == 'is_active':\n if attr.lower() == 'useraccountcontrol' and value:\n value = int(value) & LDAP_AD_ACCOUNT_DISABLE != LDAP_AD_ACCOUNT_DISABLE\n else:\n value = is_true(value)\n except LookupError:\n logger.warning(\n \"{} does not have a value for the attribute {}\".format(self.dn, attr))\n else:\n if not hasattr(self._user, field):\n continue\n if isinstance(getattr(self._user, field), bool):\n if isinstance(value, str):\n value = value.lower()\n value = value in ['true', '1', True]\n setattr(self._user, field, value)\n\n email = getattr(self._user, 'email', '')\n email = construct_user_email(self._user.username, email)\n setattr(self._user, 'email', email)", "smellKey": "S3776", "smellId": null, "repo": "jumpserver_jumpserver", "language": "python"}

    Reference Page